1
0

outbound_subscription_test.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316
  1. package service
  2. import (
  3. "bytes"
  4. "errors"
  5. "slices"
  6. "testing"
  7. "gorm.io/gorm"
  8. "github.com/mhsanaei/3x-ui/v3/internal/database"
  9. "github.com/mhsanaei/3x-ui/v3/internal/database/model"
  10. "github.com/mhsanaei/3x-ui/v3/internal/util/link"
  11. )
  12. func TestOutboundSubscriptionCreatePropagatesAllocationDatabaseFailures(t *testing.T) {
  13. setupSettingTestDB(t)
  14. db := database.GetDB()
  15. const callback = "test:fail_outbound_subscription_query"
  16. errInjected := errors.New("injected outbound subscription query failure")
  17. if err := db.Callback().Query().Before("gorm:query").Register(callback, func(tx *gorm.DB) {
  18. if tx.Statement != nil && tx.Statement.Table == "outbound_subscriptions" {
  19. tx.AddError(errInjected)
  20. }
  21. }); err != nil {
  22. t.Fatalf("register query callback: %v", err)
  23. }
  24. t.Cleanup(func() {
  25. if err := db.Callback().Query().Remove(callback); err != nil {
  26. t.Errorf("remove query callback: %v", err)
  27. }
  28. })
  29. for _, tc := range []struct {
  30. name string
  31. tagPrefix string
  32. operation string
  33. }{
  34. {name: "default prefix query", tagPrefix: "", operation: "prefix allocation"},
  35. {name: "priority count query", tagPrefix: "custom-", operation: "priority allocation"},
  36. } {
  37. t.Run(tc.name, func(t *testing.T) {
  38. created, err := (&OutboundSubscriptionService{}).Create("test", "https://1.1.1.1/sub", tc.tagPrefix, true, 600, false, false, false)
  39. if !errors.Is(err, errInjected) {
  40. t.Fatalf("Create error = %v, want injected %s query failure", err, tc.operation)
  41. }
  42. if created != nil {
  43. t.Fatalf("Create returned row %+v after %s query failure", created, tc.operation)
  44. }
  45. })
  46. }
  47. }
  48. func TestOutboundSubscriptionUpdatePropagatesPrefixQueryFailureWithoutMutation(t *testing.T) {
  49. setupSettingTestDB(t)
  50. db := database.GetDB()
  51. original := &model.OutboundSubscription{
  52. Remark: "before", Url: "https://1.1.1.1/original", TagPrefix: "custom-",
  53. Enabled: true, UpdateInterval: 600,
  54. }
  55. if err := db.Create(original).Error; err != nil {
  56. t.Fatalf("seed subscription: %v", err)
  57. }
  58. errInjected := errors.New("injected update prefix query failure")
  59. queryCount := 0
  60. const callback = "test:fail_update_prefix_query"
  61. if err := db.Callback().Query().Before("gorm:query").Register(callback, func(tx *gorm.DB) {
  62. if tx.Statement == nil || tx.Statement.Table != "outbound_subscriptions" {
  63. return
  64. }
  65. queryCount++
  66. if queryCount == 2 {
  67. tx.AddError(errInjected)
  68. }
  69. }); err != nil {
  70. t.Fatalf("register query callback: %v", err)
  71. }
  72. t.Cleanup(func() {
  73. if err := db.Callback().Query().Remove(callback); err != nil {
  74. t.Errorf("remove query callback: %v", err)
  75. }
  76. })
  77. err := (&OutboundSubscriptionService{}).Update(
  78. original.Id, "after", "https://1.1.1.1/changed", "", false, 1200, false, false, false,
  79. )
  80. if !errors.Is(err, errInjected) {
  81. t.Fatalf("Update error = %v, want injected prefix query failure", err)
  82. }
  83. if queryCount != 2 {
  84. t.Fatalf("outbound subscription queries = %d, want Get plus prefix allocation", queryCount)
  85. }
  86. var got model.OutboundSubscription
  87. if err := db.First(&got, original.Id).Error; err != nil {
  88. t.Fatalf("reload subscription: %v", err)
  89. }
  90. if got.Remark != original.Remark || got.Url != original.Url || got.TagPrefix != original.TagPrefix ||
  91. got.Enabled != original.Enabled || got.UpdateInterval != original.UpdateInterval {
  92. t.Fatalf("subscription changed after failed allocation: got %+v, want %+v", got, *original)
  93. }
  94. }
  95. func TestReadBoundedOutboundSubscriptionBody(t *testing.T) {
  96. t.Run("accepts body at the limit", func(t *testing.T) {
  97. want := bytes.Repeat([]byte("a"), int(maxOutboundSubscriptionBytes))
  98. got, err := readBoundedOutboundSubscriptionBody(bytes.NewReader(want))
  99. if err != nil {
  100. t.Fatalf("readBoundedOutboundSubscriptionBody: %v", err)
  101. }
  102. if !bytes.Equal(got, want) {
  103. t.Fatalf("body mismatch: got %d bytes, want %d", len(got), len(want))
  104. }
  105. })
  106. t.Run("rejects body over the limit", func(t *testing.T) {
  107. body := bytes.Repeat([]byte("b"), int(maxOutboundSubscriptionBytes)+1)
  108. got, err := readBoundedOutboundSubscriptionBody(bytes.NewReader(body))
  109. if !errors.Is(err, errOutboundSubscriptionBodyTooLarge) {
  110. t.Fatalf("error = %v, want errOutboundSubscriptionBodyTooLarge", err)
  111. }
  112. if got != nil {
  113. t.Fatalf("oversized body returned %d bytes, want nil", len(got))
  114. }
  115. })
  116. }
  117. func TestDefaultPrefixNumber(t *testing.T) {
  118. mk := func(id int, prefix string) *model.OutboundSubscription {
  119. return &model.OutboundSubscription{Id: id, TagPrefix: prefix}
  120. }
  121. cases := []struct {
  122. name string
  123. subs []*model.OutboundSubscription
  124. excludeId int
  125. want int
  126. }{
  127. {"no subscriptions starts at 1", nil, 0, 1},
  128. {"sequential prefixes give the next", []*model.OutboundSubscription{mk(1, "sub1-"), mk(2, "sub2-")}, 0, 3},
  129. {"reuses the lowest freed number", []*model.OutboundSubscription{mk(2, "sub2-")}, 0, 1},
  130. {"legacy blank prefix reserves its id", []*model.OutboundSubscription{mk(1, ""), mk(5, "sub3-")}, 0, 2},
  131. {"custom prefixes are ignored", []*model.OutboundSubscription{mk(1, "hk-"), mk(2, "jp-")}, 0, 1},
  132. {"excludes the edited subscription", []*model.OutboundSubscription{mk(5, "sub2-")}, 5, 1},
  133. }
  134. for _, c := range cases {
  135. t.Run(c.name, func(t *testing.T) {
  136. if got := defaultPrefixNumber(c.subs, c.excludeId); got != c.want {
  137. t.Fatalf("got %d, want %d", got, c.want)
  138. }
  139. })
  140. }
  141. }
  142. func TestAssignStableTags(t *testing.T) {
  143. t.Run("reuses the tag mapped to a known identity", func(t *testing.T) {
  144. parsed := []link.Outbound{{"tag": "JP-Tokyo"}}
  145. prev := map[string]string{"id-abc": "sub1-keepme"}
  146. got := assignStableTags(parsed, []string{"id-abc"}, prev, nil, 1, "")
  147. if got[0] != "sub1-keepme" {
  148. t.Fatalf("got %q, want sub1-keepme", got[0])
  149. }
  150. if parsed[0]["tag"] != "sub1-keepme" {
  151. t.Fatalf("tag was not written back into the outbound: %v", parsed[0]["tag"])
  152. }
  153. })
  154. t.Run("falls back to the previous tag at the same position", func(t *testing.T) {
  155. parsed := []link.Outbound{{"tag": "JP-Tokyo"}}
  156. prev := map[string]string{"id-gone": "sub1-oldpos"}
  157. got := assignStableTags(parsed, []string{"id-new"}, prev, map[int]string{0: "sub1-oldpos"}, 1, "")
  158. if got[0] != "sub1-oldpos" {
  159. t.Fatalf("got %q, want sub1-oldpos", got[0])
  160. }
  161. })
  162. t.Run("does not let an inserted link steal a stable tag", func(t *testing.T) {
  163. parsed := []link.Outbound{{"tag": "Poland"}, {"tag": "NewServer"}, {"tag": "Netherlands"}}
  164. prev := map[string]string{
  165. "id-poland": "sub1-poland",
  166. "id-netherlands": "sub1-netherlands",
  167. }
  168. prevTagByIndex := map[int]string{0: "sub1-poland", 1: "sub1-netherlands"}
  169. got := assignStableTags(parsed, []string{"id-poland", "id-new", "id-netherlands"}, prev, prevTagByIndex, 1, "")
  170. want := []string{"sub1-poland", "sub1-newserver", "sub1-netherlands"}
  171. if !slices.Equal(got, want) {
  172. t.Fatalf("got %v, want %v", got, want)
  173. }
  174. })
  175. t.Run("does not let a fresh tag steal a stable tag", func(t *testing.T) {
  176. parsed := []link.Outbound{{"tag": "Netherlands"}, {"tag": "Renamed"}}
  177. prev := map[string]string{"id-netherlands": "sub1-netherlands"}
  178. got := assignStableTags(parsed, []string{"id-new", "id-netherlands"}, prev, nil, 1, "")
  179. want := []string{"sub1-netherlands-1", "sub1-netherlands"}
  180. if !slices.Equal(got, want) {
  181. t.Fatalf("got %v, want %v", got, want)
  182. }
  183. })
  184. t.Run("skips reserved tags while adding a suffix", func(t *testing.T) {
  185. parsed := []link.Outbound{{"tag": "Netherlands"}, {"tag": "First"}, {"tag": "Second"}}
  186. prev := map[string]string{
  187. "id-first": "sub1-netherlands",
  188. "id-second": "sub1-netherlands-1",
  189. }
  190. got := assignStableTags(parsed, []string{"id-new", "id-first", "id-second"}, prev, nil, 1, "")
  191. want := []string{"sub1-netherlands-2", "sub1-netherlands", "sub1-netherlands-1"}
  192. if !slices.Equal(got, want) {
  193. t.Fatalf("got %v, want %v", got, want)
  194. }
  195. })
  196. t.Run("allocates a fresh tag with the default sub<id>- prefix", func(t *testing.T) {
  197. parsed := []link.Outbound{{"tag": "Tokyo"}}
  198. got := assignStableTags(parsed, []string{"id-x"}, nil, nil, 7, "")
  199. want := link.SuggestTag("sub7-", "Tokyo", 0)
  200. if got[0] != want {
  201. t.Fatalf("got %q, want %q", got[0], want)
  202. }
  203. })
  204. t.Run("uses a custom prefix for fresh tags", func(t *testing.T) {
  205. parsed := []link.Outbound{{"tag": "Tokyo"}}
  206. got := assignStableTags(parsed, []string{"id-x"}, nil, nil, 1, "hk-")
  207. want := link.SuggestTag("hk-", "Tokyo", 0)
  208. if got[0] != want {
  209. t.Fatalf("got %q, want %q", got[0], want)
  210. }
  211. })
  212. t.Run("disambiguates colliding tags with a -N suffix", func(t *testing.T) {
  213. parsed := []link.Outbound{{"tag": "Same"}, {"tag": "Same"}}
  214. got := assignStableTags(parsed, []string{"id1", "id2"}, nil, nil, 1, "p-")
  215. base := link.SuggestTag("p-", "Same", 0)
  216. if got[0] != base {
  217. t.Fatalf("got[0] = %q, want %q", got[0], base)
  218. }
  219. if got[1] != base+"-1" {
  220. t.Fatalf("got[1] = %q, want %q", got[1], base+"-1")
  221. }
  222. })
  223. }
  224. // TestOutboundsContainTag covers the guard that ensures the outbound under test
  225. // is present in the HTTP-probe config. Subscription outbounds aren't part of the
  226. // template outbounds the frontend sends as allOutbounds, so the probe must append
  227. // the tested outbound when its tag is missing (otherwise burstObservatory has
  228. // nothing to probe and every subscription test times out).
  229. func TestOutboundsContainTag(t *testing.T) {
  230. template := []any{
  231. map[string]any{"tag": "direct", "protocol": "freedom"},
  232. map[string]any{"tag": "blocked", "protocol": "blackhole"},
  233. }
  234. if !outboundsContainTag(template, "direct") {
  235. t.Fatal("expected tag 'direct' to be found")
  236. }
  237. if outboundsContainTag(template, "sub1-tokyo") {
  238. t.Fatal("expected subscription tag to be absent from template outbounds")
  239. }
  240. if outboundsContainTag(nil, "anything") {
  241. t.Fatal("expected empty slice to contain no tags")
  242. }
  243. // Tolerates non-map / untagged entries without panicking.
  244. mixed := []any{"not-a-map", map[string]any{"protocol": "freedom"}}
  245. if outboundsContainTag(mixed, "direct") {
  246. t.Fatal("expected no match among untagged/non-map entries")
  247. }
  248. }
  249. // TestSanitizePublicHTTPURLRejectsPrivateAndBadSchemes covers the SSRF guard used
  250. // when fetching subscription URLs. All rejected cases use literal IPs or bad
  251. // schemes so the test never performs real DNS resolution.
  252. func TestSanitizePublicHTTPURLRejectsPrivateAndBadSchemes(t *testing.T) {
  253. rejected := []string{
  254. "http://127.0.0.1/sub", // loopback
  255. "http://10.0.0.1/x", // private
  256. "http://192.168.1.1", // private
  257. "http://169.254.169.254/latest/meta-data", // link-local (cloud metadata)
  258. "http://[::1]:8080/sub", // IPv6 loopback
  259. "http://0.0.0.0", // unspecified
  260. "ftp://example.com/x", // unsupported scheme
  261. "file:///etc/passwd", // unsupported scheme
  262. }
  263. for _, raw := range rejected {
  264. if _, err := SanitizePublicHTTPURL(raw, false); err == nil {
  265. t.Errorf("expected %q to be rejected, got nil error", raw)
  266. }
  267. }
  268. t.Run("allows a public literal IP without DNS", func(t *testing.T) {
  269. got, err := SanitizePublicHTTPURL("http://8.8.8.8/sub", false)
  270. if err != nil {
  271. t.Fatalf("unexpected error: %v", err)
  272. }
  273. if got != "http://8.8.8.8/sub" {
  274. t.Fatalf("got %q, want http://8.8.8.8/sub", got)
  275. }
  276. })
  277. }
  278. // outboundsContainTag mirrors the small helper in the outbound subpackage so
  279. // these subscription tests can assert on tag presence without importing it.
  280. func outboundsContainTag(outbounds []any, tag string) bool {
  281. for _, ob := range outbounds {
  282. if m, ok := ob.(map[string]any); ok {
  283. if t, _ := m["tag"].(string); t == tag {
  284. return true
  285. }
  286. }
  287. }
  288. return false
  289. }