outbound_subscription_test.go 9.8 KB

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