json_routing_baked_test.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447
  1. package sub
  2. import (
  3. "encoding/base64"
  4. "encoding/json"
  5. "net/http"
  6. "net/http/httptest"
  7. "strings"
  8. "testing"
  9. "time"
  10. "github.com/gin-gonic/gin"
  11. "github.com/mhsanaei/3x-ui/v3/internal/database/model"
  12. "github.com/mhsanaei/3x-ui/v3/internal/logger"
  13. )
  14. const bakedRoutingPayload = `{
  15. "DomainStrategy": "IPIfNonMatch",
  16. "RemoteDNSDomain": "https://8.8.8.8/dns-query",
  17. "RemoteDNSIP": "8.8.8.8",
  18. "DomesticDNSDomain": "https://77.88.8.8/dns-query",
  19. "DomesticDNSIP": "77.88.8.8",
  20. "DnsHosts": {"lknpd.nalog.ru": "213.24.64.181"},
  21. "RouteOrder": "block-proxy-direct",
  22. "DirectSites": ["geosite:category-ru"],
  23. "DirectIp": ["geoip:private"],
  24. "ProxySites": ["geosite:youtube"],
  25. "BlockSites": ["geosite:category-ads"]
  26. }`
  27. func ruleSignatures(t *testing.T, doc map[string]any) []string {
  28. t.Helper()
  29. routing, _ := doc["routing"].(map[string]any)
  30. rules, _ := routing["rules"].([]any)
  31. signatures := make([]string, 0, len(rules))
  32. for _, rule := range rules {
  33. m, _ := rule.(map[string]any)
  34. target, _ := m["outboundTag"].(string)
  35. if target == "" {
  36. target = "balancer:" + m["balancerTag"].(string)
  37. }
  38. kind := "ip"
  39. if _, has := m["domain"]; has {
  40. kind = "domain"
  41. }
  42. if _, has := m["network"]; has {
  43. kind = "network"
  44. }
  45. signatures = append(signatures, kind+"->"+target)
  46. }
  47. return signatures
  48. }
  49. func assertBakedRouting(t *testing.T, doc map[string]any, wantRules []string, proxyTag string) {
  50. t.Helper()
  51. dns, _ := doc["dns"].(map[string]any)
  52. if dns == nil {
  53. t.Fatalf("doc has no dns:\n%v", doc)
  54. }
  55. if dns["tag"] != "dns_out" || dns["queryStrategy"] != "UseIP" {
  56. t.Fatalf("dns header = %v", dns)
  57. }
  58. servers, _ := dns["servers"].([]any)
  59. if len(servers) != 2 {
  60. t.Fatalf("dns servers = %d, want 2 (domestic + remote): %v", len(servers), servers)
  61. }
  62. first, _ := servers[0].(map[string]any)
  63. if first["address"] != "https://77.88.8.8/dns-query" {
  64. t.Fatalf("domestic dns = %v", first)
  65. }
  66. if domains, _ := first["domains"].([]any); strings.Join(stringify(domains), ",") != "geosite:category-ru" {
  67. t.Fatalf("domestic dns domains = %v", first["domains"])
  68. }
  69. second, _ := servers[1].(map[string]any)
  70. if second["address"] != "https://8.8.8.8/dns-query" {
  71. t.Fatalf("remote dns = %v", second)
  72. }
  73. hosts, _ := dns["hosts"].(map[string]any)
  74. if hosts["lknpd.nalog.ru"] != "213.24.64.181" {
  75. t.Fatalf("dns hosts = %v", dns["hosts"])
  76. }
  77. routing, _ := doc["routing"].(map[string]any)
  78. if routing["domainStrategy"] != "IPIfNonMatch" {
  79. t.Fatalf("domainStrategy = %v", routing["domainStrategy"])
  80. }
  81. want := make([]string, 0, len(wantRules))
  82. for _, rule := range wantRules {
  83. want = append(want, strings.Replace(rule, "PROXY", proxyTag, 1))
  84. }
  85. got := ruleSignatures(t, doc)
  86. if strings.Join(got, ",") != strings.Join(want, ",") {
  87. t.Fatalf("rules = %v\nwant %v", got, want)
  88. }
  89. }
  90. func TestSubJson_BakedRoutingInEveryDocument(t *testing.T) {
  91. seedSubDB(t)
  92. seedSubInbound(t, "s1", "tcpin", 4801, 1, `{"network":"tcp","security":"tls","tlsSettings":{"serverName":"base.sni"}}`)
  93. js := NewSubJsonService("", "", "", bakedRoutingPayload, NewSubService(""))
  94. out, _, err := js.GetJson("s1", "req.example.com", true)
  95. if err != nil {
  96. t.Fatalf("GetJson: %v", err)
  97. }
  98. docs := parseSubJsonDocs(t, out)
  99. if len(docs) != 1 {
  100. t.Fatalf("docs = %d, want 1:\n%s", len(docs), out)
  101. }
  102. want := []string{"domain->block", "domain->PROXY", "domain->direct", "ip->direct", "network->PROXY"}
  103. assertBakedRouting(t, docs[0], want, "proxy")
  104. }
  105. func TestSubJson_BakedRoutingReplacesLegacyRules(t *testing.T) {
  106. seedSubDB(t)
  107. seedSubInbound(t, "s1", "tcpin", 4802, 1, `{"network":"tcp","security":"tls","tlsSettings":{"serverName":"base.sni"}}`)
  108. legacy := `[{"type":"field","domain":["geosite:example"],"outboundTag":"proxy"}]`
  109. js := NewSubJsonService("", legacy, "", bakedRoutingPayload, NewSubService(""))
  110. out, _, err := js.GetJson("s1", "req.example.com", true)
  111. if err != nil {
  112. t.Fatalf("GetJson: %v", err)
  113. }
  114. docs := parseSubJsonDocs(t, out)
  115. routing, _ := docs[0]["routing"].(map[string]any)
  116. ruleJSON, _ := json.Marshal(routing["rules"])
  117. if strings.Contains(string(ruleJSON), "geosite:example") {
  118. t.Fatalf("legacy subJsonRules must not leak into baked docs: %s", ruleJSON)
  119. }
  120. }
  121. func TestSubJson_BakedRoutingWithBalancer(t *testing.T) {
  122. seedSubDB(t)
  123. tcp := seedSubInbound(t, "s1", "tcpin", 4803, 1, `{"network":"tcp","security":"tls","tlsSettings":{"serverName":"base.sni"}}`)
  124. seedSubBalancer(t, &model.SubBalancer{
  125. Remark: "auto", Strategy: "leastLoad", InboundIds: []int{tcp.Id}, SortOrder: 1, Enabled: true,
  126. })
  127. js := NewSubJsonService("", "", "", bakedRoutingPayload, NewSubService(""))
  128. out, _, err := js.GetJson("s1", "req.example.com", true)
  129. if err != nil {
  130. t.Fatalf("GetJson: %v", err)
  131. }
  132. docs := parseSubJsonDocs(t, out)
  133. if len(docs) != 2 {
  134. t.Fatalf("docs = %d, want 2 (inbound + balancer):\n%s", len(docs), out)
  135. }
  136. // Manual doc keeps the plain proxy tag.
  137. assertBakedRouting(t, findDocByRemarks(docs, "tcpin-tcpin@e"), []string{
  138. "domain->block", "domain->PROXY", "domain->direct", "ip->direct", "network->PROXY",
  139. }, "proxy")
  140. // Balancer doc routes proxy groups into the balancer.
  141. balancerDoc := findDocByRemarks(docs, "auto")
  142. want := []string{"domain->block", "domain->balancer:balancer", "domain->direct", "ip->direct", "network->balancer:balancer"}
  143. assertBakedRouting(t, balancerDoc, want, "balancer:balancer")
  144. }
  145. func TestSubJson_BakedRoutingInvalidFallsBackToDefault(t *testing.T) {
  146. seedSubDB(t)
  147. seedSubInbound(t, "s1", "tcpin", 4804, 1, `{"network":"tcp","security":"tls","tlsSettings":{"serverName":"base.sni"}}`)
  148. js := NewSubJsonService("", "", "", "not json at all", NewSubService(""))
  149. out, _, err := js.GetJson("s1", "req.example.com", true)
  150. if err != nil {
  151. t.Fatalf("GetJson must survive a bad routing payload: %v", err)
  152. }
  153. docs := parseSubJsonDocs(t, out)
  154. routing, _ := docs[0]["routing"].(map[string]any)
  155. rules, _ := json.Marshal(routing["rules"])
  156. if !strings.Contains(string(rules), `"outboundTag":"proxy"`) {
  157. t.Fatalf("default routing missing: %s", rules)
  158. }
  159. }
  160. func TestSubJson_LegacyRulesStillWorkWithoutBakedRouting(t *testing.T) {
  161. seedSubDB(t)
  162. seedSubInbound(t, "s1", "tcpin", 4805, 1, `{"network":"tcp","security":"tls","tlsSettings":{"serverName":"base.sni"}}`)
  163. legacy := `[{"type":"field","domain":["geosite:example"],"outboundTag":"proxy"}]`
  164. js := NewSubJsonService("", legacy, "", "", NewSubService(""))
  165. out, _, err := js.GetJson("s1", "req.example.com", true)
  166. if err != nil {
  167. t.Fatalf("GetJson: %v", err)
  168. }
  169. docs := parseSubJsonDocs(t, out)
  170. routing, _ := docs[0]["routing"].(map[string]any)
  171. ruleJSON, _ := json.Marshal(routing["rules"])
  172. if !strings.Contains(string(ruleJSON), "geosite:example") {
  173. t.Fatalf("legacy rules missing: %s", ruleJSON)
  174. }
  175. }
  176. func TestSubJson_BakedRoutingRemoteWarmsAfterColdStart(t *testing.T) {
  177. seedSubDB(t)
  178. seedSubInbound(t, "s1", "tcpin", 4806, 1, `{"network":"tcp","security":"tls","tlsSettings":{"serverName":"base.sni"}}`)
  179. oldResolver := routingSourceResolver
  180. t.Cleanup(func() { routingSourceResolver = oldResolver })
  181. const source = "https://example.com/DEFAULT.JSON"
  182. routingSourceResolver = newRemoteRoutingResolver(remoteRoutingTestClient(func(*http.Request) (*http.Response, error) {
  183. return remoteRoutingResponse(200, mustMarshal(t, fullRoutingPayload())), nil
  184. }), false)
  185. js := NewSubJsonService("", "", "", source, NewSubService(""))
  186. // Cold: no request has primed the resolver cache yet.
  187. out, _, err := js.GetJson("s1", "req.example.com", true)
  188. if err != nil {
  189. t.Fatalf("GetJson: %v", err)
  190. }
  191. docs := parseSubJsonDocs(t, out)
  192. routing, _ := docs[0]["routing"].(map[string]any)
  193. if routing["domainStrategy"] != "AsIs" {
  194. t.Fatalf("cold doc must keep default routing: %v", routing["domainStrategy"])
  195. }
  196. // The cron job warms the cache; the next request must bake the profile.
  197. primeRemoteRouting(t, routingSourceResolver, remoteRoutingJson, source)
  198. out, _, err = js.GetJson("s1", "req.example.com", true)
  199. if err != nil {
  200. t.Fatalf("GetJson: %v", err)
  201. }
  202. docs = parseSubJsonDocs(t, out)
  203. routing, _ = docs[0]["routing"].(map[string]any)
  204. if routing["domainStrategy"] != "IPIfNonMatch" {
  205. t.Fatalf("warm doc must carry the profile: %v", routing["domainStrategy"])
  206. }
  207. dns, _ := docs[0]["dns"].(map[string]any)
  208. servers, _ := dns["servers"].([]any)
  209. if len(servers) != 2 {
  210. t.Fatalf("warm doc dns servers = %v", servers)
  211. }
  212. }
  213. func TestApplyCommonHeadersFallsBackToJsonRoutingProfile(t *testing.T) {
  214. gin.SetMode(gin.TestMode)
  215. var object map[string]any
  216. if err := json.Unmarshal([]byte(bakedRoutingPayload), &object); err != nil {
  217. t.Fatalf("payload: %v", err)
  218. }
  219. happDeeplink := "happ://routing/onadd/" + base64.StdEncoding.EncodeToString([]byte(mustMarshal(t, object)))
  220. incyDeeplink := "incy://routing/onadd/" + base64.StdEncoding.EncodeToString([]byte(mustMarshal(t, map[string]any{"Name": "RoscomVPN"})))
  221. cases := []struct {
  222. name string
  223. jsonRules string
  224. happRules string
  225. want string
  226. }{
  227. {name: "inline json becomes a happ deeplink", jsonRules: bakedRoutingPayload, want: happDeeplink},
  228. {name: "happ deeplink passes through", jsonRules: happDeeplink, want: happDeeplink},
  229. {name: "incy deeplink passes through", jsonRules: incyDeeplink, want: incyDeeplink},
  230. {name: "blank profile keeps the header unset", jsonRules: "", want: ""},
  231. {name: "unusable profile keeps the header unset", jsonRules: "happ://routing/onadd/%%%", want: ""},
  232. {name: "explicit happ rules take precedence", jsonRules: bakedRoutingPayload, happRules: "happ://routing/onadd/" + base64.StdEncoding.EncodeToString([]byte(`{"A":1}`)), want: "happ://routing/onadd/" + base64.StdEncoding.EncodeToString([]byte(`{"A":1}`))},
  233. }
  234. for _, tc := range cases {
  235. t.Run(tc.name, func(t *testing.T) {
  236. recorder := httptest.NewRecorder()
  237. ctx, _ := gin.CreateTestContext(recorder)
  238. (&SUBController{subJsonRoutingRules: tc.jsonRules}).ApplyCommonHeaders(ctx, "", "12", "", "", "", "", false, tc.happRules, false)
  239. if got := recorder.Header().Get("Routing"); got != tc.want {
  240. t.Fatalf("Routing = %q, want %q", got, tc.want)
  241. }
  242. })
  243. }
  244. }
  245. func TestApplyCommonHeadersJsonRoutingRemoteFailsClosed(t *testing.T) {
  246. gin.SetMode(gin.TestMode)
  247. oldResolver := routingSourceResolver
  248. t.Cleanup(func() { routingSourceResolver = oldResolver })
  249. const source = "https://example.com/DEFAULT.JSON"
  250. routingSourceResolver = newRemoteRoutingResolver(remoteRoutingTestClient(func(*http.Request) (*http.Response, error) {
  251. return remoteRoutingResponse(200, mustMarshal(t, fullRoutingPayload())), nil
  252. }), false)
  253. recorder := httptest.NewRecorder()
  254. ctx, _ := gin.CreateTestContext(recorder)
  255. (&SUBController{subJsonRoutingRules: source}).ApplyCommonHeaders(ctx, "", "12", "", "", "", "", false, "", false)
  256. if got := recorder.Header().Get("Routing"); got != "" {
  257. t.Fatalf("cold cache must keep the header unset, got %q", got)
  258. }
  259. primeRemoteRouting(t, routingSourceResolver, remoteRoutingJson, source)
  260. recorder = httptest.NewRecorder()
  261. ctx, _ = gin.CreateTestContext(recorder)
  262. (&SUBController{subJsonRoutingRules: source}).ApplyCommonHeaders(ctx, "", "12", "", "", "", "", false, "", false)
  263. got := recorder.Header().Get("Routing")
  264. if !strings.HasPrefix(got, "happ://routing/onadd/") {
  265. t.Fatalf("warm cache Routing = %q", got)
  266. }
  267. decoded, err := decodeRoutingBase64(strings.TrimPrefix(got, "happ://routing/onadd/"))
  268. if err != nil {
  269. t.Fatalf("deeplink payload: %v", err)
  270. }
  271. var payload map[string]any
  272. if err := json.Unmarshal(decoded, &payload); err != nil {
  273. t.Fatalf("deeplink JSON: %v", err)
  274. }
  275. if payload["Name"] != "RoscomVPN" {
  276. t.Fatalf("deeplink payload = %v", payload)
  277. }
  278. waitRemoteRoutingIdle(t, routingSourceResolver)
  279. }
  280. func TestSubJson_BakedRoutingRemoteUpdateReachesDocuments(t *testing.T) {
  281. seedSubDB(t)
  282. seedSubInbound(t, "s1", "tcpin", 4807, 1, `{"network":"tcp","security":"tls","tlsSettings":{"serverName":"base.sni"}}`)
  283. oldResolver := routingSourceResolver
  284. t.Cleanup(func() { routingSourceResolver = oldResolver })
  285. const source = "https://example.com/DEFAULT.JSON"
  286. current := mustMarshal(t, fullRoutingPayload())
  287. routingSourceResolver = newRemoteRoutingResolver(remoteRoutingTestClient(func(*http.Request) (*http.Response, error) {
  288. return remoteRoutingResponse(200, current), nil
  289. }), false)
  290. js := NewSubJsonService("", "", "", source, NewSubService(""))
  291. // A cold resolver fails closed (default routing); prime the cache first.
  292. primeRemoteRouting(t, routingSourceResolver, remoteRoutingJson, source)
  293. out, _, err := js.GetJson("s1", "req.example.com", true)
  294. if err != nil {
  295. t.Fatalf("GetJson: %v", err)
  296. }
  297. docs := parseSubJsonDocs(t, out)
  298. routing, _ := docs[0]["routing"].(map[string]any)
  299. if routing["domainStrategy"] != "IPIfNonMatch" {
  300. t.Fatalf("first doc must carry the profile: %v", routing["domainStrategy"])
  301. }
  302. // The operator edits the published profile; after the cache TTL expires,
  303. // the next request must re-bake the template with the new payload.
  304. updated := fullRoutingPayload()
  305. updated["DomainStrategy"] = "AsIs"
  306. current = mustMarshal(t, updated)
  307. waitRemoteRoutingIdle(t, routingSourceResolver)
  308. staleKey := remoteRoutingKey{kind: remoteRoutingJson, source: source}
  309. routingSourceResolver.mu.Lock()
  310. entry := routingSourceResolver.entries[staleKey]
  311. entry.FetchedAt = time.Now().Add(-remoteRoutingCacheTTL - time.Minute).Unix()
  312. routingSourceResolver.entries[staleKey] = entry
  313. delete(routingSourceResolver.lastAttempt, staleKey)
  314. routingSourceResolver.mu.Unlock()
  315. primeRemoteRouting(t, routingSourceResolver, remoteRoutingJson, source)
  316. out, _, err = js.GetJson("s1", "req.example.com", true)
  317. if err != nil {
  318. t.Fatalf("GetJson: %v", err)
  319. }
  320. docs = parseSubJsonDocs(t, out)
  321. routing, _ = docs[0]["routing"].(map[string]any)
  322. if routing["domainStrategy"] != "AsIs" {
  323. t.Fatalf("updated profile must reach the documents without a restart: %v", routing["domainStrategy"])
  324. }
  325. waitRemoteRoutingIdle(t, routingSourceResolver)
  326. }
  327. func TestRemoteRoutingJsonHasItsOwnPersistedRow(t *testing.T) {
  328. seedSubDB(t)
  329. const source = "https://example.com/DEFAULT.JSON"
  330. // Two happ-payload settings pointing at different sources must not
  331. // overwrite each other's persisted cache rows.
  332. happSource := "https://example.com/HAPP.json"
  333. for _, tc := range []struct {
  334. kind remoteRoutingKind
  335. source string
  336. payload string
  337. }{
  338. {kind: remoteRoutingHapp, source: happSource, payload: `{"Name":"happ-profile"}`},
  339. {kind: remoteRoutingJson, source: source, payload: `{"Name":"json-profile"}`},
  340. } {
  341. deeplink, err := normalizeHappRouting([]byte(tc.payload))
  342. if err != nil {
  343. t.Fatalf("normalize: %v", err)
  344. }
  345. newRemoteRoutingResolver(nil, false).persistEntry(tc.kind, remoteRoutingCacheEntry{
  346. Source: tc.source, Content: deeplink, FetchedAt: time.Now().Unix(),
  347. })
  348. }
  349. for _, tc := range []struct {
  350. kind remoteRoutingKind
  351. source string
  352. want string
  353. }{
  354. {kind: remoteRoutingHapp, source: happSource, want: "happ-profile"},
  355. {kind: remoteRoutingJson, source: source, want: "json-profile"},
  356. } {
  357. resolver := newRemoteRoutingResolver(nil, true)
  358. resolver.now = func() time.Time { return time.Unix(1_800_000_000, 0) }
  359. resolver.ensurePersistedLoaded()
  360. got, remote, err := resolver.resolve(tc.kind, tc.source)
  361. if err != nil || !remote {
  362. t.Fatalf("resolve kind=%s: remote=%v err=%v", tc.kind, remote, err)
  363. }
  364. decoded, err := decodeRoutingBase64(strings.TrimPrefix(got, "happ://routing/onadd/"))
  365. if err != nil {
  366. t.Fatalf("decode kind=%s: %v", tc.kind, err)
  367. }
  368. var payload map[string]any
  369. if json.Unmarshal(decoded, &payload) != nil || payload["Name"] != tc.want {
  370. t.Fatalf("kind=%s payload = %s", tc.kind, decoded)
  371. }
  372. }
  373. }
  374. const maxSubLogScan = 10240
  375. func routingWarningCount(t *testing.T) int {
  376. t.Helper()
  377. n := 0
  378. for _, line := range logger.GetLogs(maxSubLogScan, "warning") {
  379. if strings.Contains(line, "subJsonRoutingRules") {
  380. n++
  381. }
  382. }
  383. return n
  384. }
  385. // A public subscription fetch must not write one warning per emitted document:
  386. // the 10k in-memory buffer the panel's log view reads is evicted by the flood.
  387. func TestSubJson_BadRoutingProfileWarnsOncePerRequest(t *testing.T) {
  388. seedSubDB(t)
  389. for i, name := range []string{"w1", "w2", "w3", "w4", "w5", "w6"} {
  390. seedSubInbound(t, "s1", name, 4870+i, 1, `{"network":"tcp","security":"none"}`)
  391. }
  392. js := NewSubJsonService("", "", "", "not json at all", NewSubService(""))
  393. before := routingWarningCount(t)
  394. out, _, err := js.GetJson("s1", "req.example.com", true)
  395. if err != nil {
  396. t.Fatalf("GetJson: %v", err)
  397. }
  398. docs := parseSubJsonDocs(t, out)
  399. if len(docs) < 6 {
  400. t.Fatalf("docs = %d, want >= 6:\n%s", len(docs), out)
  401. }
  402. if got := routingWarningCount(t) - before; got > 1 {
  403. t.Fatalf("one request emitting %d documents logged %d warnings, want at most 1", len(docs), got)
  404. }
  405. }