json_service_test.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472
  1. package sub
  2. import (
  3. "encoding/json"
  4. "reflect"
  5. "testing"
  6. "github.com/mhsanaei/3x-ui/v3/internal/database/model"
  7. wgutil "github.com/mhsanaei/3x-ui/v3/internal/util/wireguard"
  8. )
  9. func hasDirectOutOutbound(svc *SubJsonService) bool {
  10. for _, raw := range svc.defaultOutbounds {
  11. var outbound map[string]any
  12. if err := json.Unmarshal(raw, &outbound); err != nil {
  13. continue
  14. }
  15. if outbound["tag"] == "direct_out" {
  16. return true
  17. }
  18. }
  19. return false
  20. }
  21. func outboundSettings(t *testing.T, raw []byte) map[string]any {
  22. t.Helper()
  23. var parsed map[string]any
  24. if err := json.Unmarshal(raw, &parsed); err != nil {
  25. t.Fatalf("failed to unmarshal outbound: %v", err)
  26. }
  27. settings, _ := parsed["settings"].(map[string]any)
  28. if settings == nil {
  29. t.Fatal("outbound has no settings")
  30. }
  31. return settings
  32. }
  33. func TestDefaultJSONUsesCompatibleLocalInbounds(t *testing.T) {
  34. svc := NewSubJsonService("", "", "", nil)
  35. inbounds, ok := svc.configJson["inbounds"].([]any)
  36. if !ok {
  37. t.Fatalf("default JSON inbounds = %#v, want array", svc.configJson["inbounds"])
  38. }
  39. byPort := make(map[float64]map[string]any, len(inbounds))
  40. for _, raw := range inbounds {
  41. inbound, ok := raw.(map[string]any)
  42. if !ok {
  43. t.Fatalf("default JSON inbound = %#v, want object", raw)
  44. }
  45. port, ok := inbound["port"].(float64)
  46. if !ok {
  47. t.Fatalf("default JSON inbound port = %#v, want number", inbound["port"])
  48. }
  49. byPort[port] = inbound
  50. }
  51. socks := byPort[10808]
  52. if socks == nil {
  53. t.Fatal("default JSON is missing the local inbound on port 10808")
  54. }
  55. if socks["protocol"] != "socks" || socks["tag"] != "mixed" {
  56. t.Fatalf("port 10808 protocol/tag = %v/%v, want socks/mixed", socks["protocol"], socks["tag"])
  57. }
  58. settings, _ := socks["settings"].(map[string]any)
  59. if settings == nil || settings["udp"] != true {
  60. t.Fatalf("port 10808 settings = %#v, want udp enabled", socks["settings"])
  61. }
  62. http := byPort[10809]
  63. if http == nil || http["protocol"] != "http" {
  64. t.Fatalf("port 10809 inbound = %#v, want http protocol", http)
  65. }
  66. }
  67. func TestSubJsonServiceInjectsGlobalFinalMask(t *testing.T) {
  68. finalMask := `{"tcp":[{"type":"fragment","settings":{"packets":"tlshello","length":"100-200","delay":"10-20"}}],"udp":[{"type":"noise","settings":{"noise":[{"type":"base64","packet":"SGVsbG8="}]}}],"quicParams":{"congestion":"bbr"}}`
  69. svc := NewSubJsonService("", "", finalMask, nil)
  70. if hasDirectOutOutbound(svc) {
  71. t.Fatal("direct_out outbound must never be emitted")
  72. }
  73. stream := svc.streamData(`{"network":"tcp","security":"none","tcpSettings":{"header":{"type":"none"}}}`, "")
  74. if _, ok := stream["sockopt"]; ok {
  75. t.Fatal("legacy direct_out dialerProxy sockopt must never be set")
  76. }
  77. finalmask, _ := stream["finalmask"].(map[string]any)
  78. if finalmask == nil {
  79. t.Fatal("streamSettings is missing finalmask")
  80. }
  81. tcp, _ := finalmask["tcp"].([]any)
  82. if len(tcp) != 1 {
  83. t.Fatalf("tcp masks len = %d, want 1", len(tcp))
  84. }
  85. if first, _ := tcp[0].(map[string]any); first["type"] != "fragment" {
  86. t.Fatalf("tcp[0] type = %v, want fragment", first["type"])
  87. }
  88. udp, _ := finalmask["udp"].([]any)
  89. if len(udp) != 1 {
  90. t.Fatalf("udp masks len = %d, want 1", len(udp))
  91. }
  92. quic, _ := finalmask["quicParams"].(map[string]any)
  93. if quic == nil || quic["congestion"] != "bbr" {
  94. t.Fatalf("quicParams missing/wrong: %#v", finalmask["quicParams"])
  95. }
  96. }
  97. func TestSubJsonServiceMergesWithExistingFinalMask(t *testing.T) {
  98. finalMask := `{"tcp":[{"type":"fragment","settings":{"packets":"tlshello"}}]}`
  99. svc := NewSubJsonService("", "", finalMask, nil)
  100. stream := svc.streamData(`{
  101. "network":"tcp","security":"none","tcpSettings":{"header":{"type":"none"}},
  102. "finalmask":{"tcp":[{"type":"sudoku"}]}
  103. }`, "")
  104. finalmask, _ := stream["finalmask"].(map[string]any)
  105. tcp, _ := finalmask["tcp"].([]any)
  106. if len(tcp) != 2 {
  107. t.Fatalf("tcp masks len = %d, want 2 (existing + global)", len(tcp))
  108. }
  109. a, _ := tcp[0].(map[string]any)
  110. b, _ := tcp[1].(map[string]any)
  111. if a["type"] != "sudoku" || b["type"] != "fragment" {
  112. t.Fatalf("tcp masks = %#v, want existing sudoku then global fragment", tcp)
  113. }
  114. }
  115. func TestSubJsonServiceNoFinalMaskWhenEmpty(t *testing.T) {
  116. svc := NewSubJsonService("", "", "", nil)
  117. stream := svc.streamData(`{"network":"tcp","security":"none","tcpSettings":{"header":{"type":"none"}}}`, "")
  118. if _, ok := stream["finalmask"]; ok {
  119. t.Fatal("no finalmask should be emitted when subJsonFinalMask is empty")
  120. }
  121. if _, ok := stream["sockopt"]; ok {
  122. t.Fatal("legacy direct_out sockopt must never be set")
  123. }
  124. }
  125. // xray-core parses tlsSettings.pinnedPeerCertSha256 as a comma-separated string;
  126. // the JSON subscription must emit that form, not an array, or v2ray clients fail
  127. // to import the config (#5401).
  128. func TestSubJsonServicePinnedCertJoinedToString(t *testing.T) {
  129. svc := NewSubJsonService("", "", "", nil)
  130. stream := svc.streamData(`{"network":"tcp","security":"tls","tlsSettings":{"serverName":"a.example.com","settings":{"pinnedPeerCertSha256":["aa11","bb22"]}}}`, "")
  131. tls, _ := stream["tlsSettings"].(map[string]any)
  132. if tls == nil {
  133. t.Fatalf("tlsSettings missing: %#v", stream)
  134. }
  135. if got := tls["pinnedPeerCertSha256"]; got != "aa11,bb22" {
  136. t.Fatalf("pinnedPeerCertSha256 = %#v, want comma-separated string \"aa11,bb22\"", got)
  137. }
  138. }
  139. func TestSubJsonServiceTLSCipherSuitesForwarded(t *testing.T) {
  140. svc := NewSubJsonService("", "", "", nil)
  141. stream := svc.streamData(`{"network":"tcp","security":"tls","tlsSettings":{"serverName":"a.example.com","cipherSuites":"TLS_AES_256_GCM_SHA384","settings":{}}}`, "")
  142. tls, _ := stream["tlsSettings"].(map[string]any)
  143. if got := tls["cipherSuites"]; got != "TLS_AES_256_GCM_SHA384" {
  144. t.Fatalf("cipherSuites = %#v, want %q", got, "TLS_AES_256_GCM_SHA384")
  145. }
  146. stream = svc.streamData(`{"network":"tcp","security":"tls","tlsSettings":{"serverName":"a.example.com","cipherSuites":"","settings":{}}}`, "")
  147. tls, _ = stream["tlsSettings"].(map[string]any)
  148. if _, present := tls["cipherSuites"]; present {
  149. t.Fatalf("empty cipherSuites must be omitted, got %#v", tls["cipherSuites"])
  150. }
  151. }
  152. func TestSubJsonServiceVlessFlattened(t *testing.T) {
  153. inbound := &model.Inbound{Listen: "1.2.3.4", Port: 443, Protocol: model.VLESS, Settings: `{"encryption":"none"}`}
  154. client := model.Client{ID: "uuid-1", Flow: "xtls-rprx-vision"}
  155. settings := outboundSettings(t, NewSubJsonService("", "", "", nil).genVless(&SubService{}, inbound, nil, client, ""))
  156. if _, ok := settings["vnext"]; ok {
  157. t.Fatal("vless outbound must not use vnext")
  158. }
  159. if settings["address"] != "1.2.3.4" || settings["id"] != "uuid-1" || settings["encryption"] != "none" || settings["flow"] != "xtls-rprx-vision" {
  160. t.Fatalf("flat vless settings wrong: %#v", settings)
  161. }
  162. }
  163. func TestSubJsonServiceVlessFlowSuppressedByDisableFlow(t *testing.T) {
  164. inbound := &model.Inbound{Listen: "1.2.3.4", Port: 443, Protocol: model.VLESS, Settings: `{"encryption":"none"}`, DisableFlow: true}
  165. client := model.Client{ID: "uuid-1", Flow: "xtls-rprx-vision"}
  166. settings := outboundSettings(t, NewSubJsonService("", "", "", nil).genVless(&SubService{}, inbound, nil, client, ""))
  167. if _, ok := settings["flow"]; ok {
  168. t.Fatalf("DisableFlow inbound must not carry a flow in the JSON outbound: %#v", settings)
  169. }
  170. }
  171. func TestSubJsonServiceVmessFlattened(t *testing.T) {
  172. inbound := &model.Inbound{Listen: "1.2.3.4", Port: 443, Protocol: model.VMESS, Settings: `{}`}
  173. client := model.Client{ID: "uuid-2"}
  174. settings := outboundSettings(t, NewSubJsonService("", "", "", nil).genVnext(inbound, nil, client, ""))
  175. if _, ok := settings["vnext"]; ok {
  176. t.Fatal("vmess outbound must not use vnext")
  177. }
  178. if settings["id"] != "uuid-2" || settings["security"] != "auto" {
  179. t.Fatalf("flat vmess settings wrong: %#v", settings)
  180. }
  181. }
  182. // Shadowsocks/Trojan outbounds must use the standard "servers" array so older
  183. // bundled xray-cores (e.g. v2rayN) parse them; the flat top-level form only
  184. // works on very recent xray-core.
  185. func TestSubJsonServiceServerUsesServersArray(t *testing.T) {
  186. trojan := &model.Inbound{Listen: "1.2.3.4", Port: 443, Protocol: model.Trojan, Settings: `{}`}
  187. client := model.Client{Password: "p4ss"}
  188. settings := outboundSettings(t, NewSubJsonService("", "", "", nil).genServer(&SubService{}, trojan, nil, client, ""))
  189. server := firstServer(settings)
  190. if server == nil {
  191. t.Fatalf("trojan outbound must use a servers array, got: %#v", settings)
  192. }
  193. if server["password"] != "p4ss" || server["address"] != "1.2.3.4" {
  194. t.Fatalf("trojan server entry wrong: %#v", server)
  195. }
  196. if _, ok := server["method"]; ok {
  197. t.Fatalf("trojan must not carry method: %#v", server)
  198. }
  199. ss := &model.Inbound{Listen: "1.2.3.4", Port: 443, Protocol: model.Shadowsocks, Settings: `{"method":"aes-256-gcm"}`}
  200. ssSettings := outboundSettings(t, NewSubJsonService("", "", "", nil).genServer(&SubService{}, ss, nil, client, ""))
  201. ssServer := firstServer(ssSettings)
  202. if ssServer == nil {
  203. t.Fatalf("shadowsocks outbound must use a servers array, got: %#v", ssSettings)
  204. }
  205. if ssServer["method"] != "aes-256-gcm" {
  206. t.Fatalf("shadowsocks server entry must carry method: %#v", ssServer)
  207. }
  208. }
  209. func TestSubJsonServiceXmuxSuppressesGlobalMux(t *testing.T) {
  210. globalMux := `{"enabled":true,"concurrency":8}`
  211. svc := NewSubJsonService(globalMux, "", "", nil)
  212. // When xmux is present in xhttpSettings, the per-inbound xmux handles
  213. // multiplexing and the legacy outbound.Mux must NOT be set.
  214. stream := `{"network":"xhttp","security":"tls","tlsSettings":{"serverName":"example.com"},"xhttpSettings":{"path":"/api","mode":"packet-up","xmux":{"maxConcurrency":"16-32"}}}`
  215. parsed := svc.streamData(stream, "")
  216. mux := globalMux
  217. if xhttp, ok := parsed["xhttpSettings"].(map[string]any); ok {
  218. if _, hasXmux := xhttp["xmux"]; hasXmux {
  219. mux = ""
  220. }
  221. }
  222. streamSettings, _ := json.Marshal(parsed)
  223. inbound := &model.Inbound{Listen: "1.2.3.4", Port: 443, Protocol: model.VLESS, Settings: `{"encryption":"none"}`}
  224. client := model.Client{ID: "uuid-1"}
  225. raw := svc.genVless(&SubService{}, inbound, streamSettings, client, mux)
  226. var ob map[string]any
  227. if err := json.Unmarshal(raw, &ob); err != nil {
  228. t.Fatalf("unmarshal outbound: %v", err)
  229. }
  230. if _, has := ob["mux"]; has {
  231. t.Fatal("outbound.Mux must NOT be set when per-inbound xmux is present")
  232. }
  233. // Verify xmux is still inside xhttpSettings in streamSettings.
  234. ss, _ := ob["streamSettings"].(map[string]any)
  235. if ss == nil {
  236. t.Fatal("streamSettings missing from outbound")
  237. }
  238. xhttp, _ := ss["xhttpSettings"].(map[string]any)
  239. if xhttp == nil {
  240. t.Fatal("xhttpSettings missing from streamSettings")
  241. }
  242. xmux, _ := xhttp["xmux"].(map[string]any)
  243. if xmux == nil {
  244. t.Fatal("xmux missing from xhttpSettings — per-inbound xmux must survive streamData()")
  245. }
  246. if xmux["maxConcurrency"] != "16-32" {
  247. t.Fatalf("xmux.maxConcurrency = %v, want 16-32", xmux["maxConcurrency"])
  248. }
  249. }
  250. func TestSubJsonServiceGlobalMuxWhenNoXmux(t *testing.T) {
  251. globalMux := `{"enabled":true,"concurrency":8}`
  252. svc := NewSubJsonService(globalMux, "", "", nil)
  253. // When no xmux is present, the global subJsonMux should be used.
  254. stream := `{"network":"xhttp","security":"tls","tlsSettings":{"serverName":"example.com"},"xhttpSettings":{"path":"/api","mode":"packet-up"}}`
  255. parsed := svc.streamData(stream, "")
  256. mux := globalMux
  257. if xhttp, ok := parsed["xhttpSettings"].(map[string]any); ok {
  258. if _, hasXmux := xhttp["xmux"]; hasXmux {
  259. mux = ""
  260. }
  261. }
  262. streamSettings, _ := json.Marshal(parsed)
  263. inbound := &model.Inbound{Listen: "1.2.3.4", Port: 443, Protocol: model.VLESS, Settings: `{"encryption":"none"}`}
  264. client := model.Client{ID: "uuid-1"}
  265. raw := svc.genVless(&SubService{}, inbound, streamSettings, client, mux)
  266. var ob map[string]any
  267. if err := json.Unmarshal(raw, &ob); err != nil {
  268. t.Fatalf("unmarshal outbound: %v", err)
  269. }
  270. m, has := ob["mux"]
  271. if !has {
  272. t.Fatal("outbound.Mux must be set when global subJsonMux is configured and no per-inbound xmux")
  273. }
  274. mm, _ := m.(map[string]any)
  275. if mm["enabled"] != true || mm["concurrency"] != float64(8) {
  276. t.Fatalf("mux payload wrong: %#v", m)
  277. }
  278. }
  279. func realitySpiderXFromStream(t *testing.T, svc *SubJsonService, clientKey string) string {
  280. t.Helper()
  281. stream := svc.streamData(`{
  282. "network":"tcp","security":"reality","tcpSettings":{"header":{"type":"none"}},
  283. "realitySettings":{
  284. "serverNames":["reality.example.com"],
  285. "shortIds":["ab12cd"],
  286. "settings":{"publicKey":"PBKvalue","fingerprint":"firefox","spiderX":"/seed"}
  287. }
  288. }`, clientKey)
  289. rlty, _ := stream["realitySettings"].(map[string]any)
  290. if rlty == nil {
  291. t.Fatal("streamData dropped realitySettings")
  292. }
  293. spx, _ := rlty["spiderX"].(string)
  294. if len(spx) != 16 || spx[0] != '/' {
  295. t.Fatalf("spiderX = %q, want a 16-char /-prefixed value", spx)
  296. }
  297. return spx
  298. }
  299. func TestSubJsonServiceRealityDataDerivesPerClientSpiderX(t *testing.T) {
  300. svc := NewSubJsonService("", "", "", nil)
  301. alice := realitySpiderXFromStream(t, svc, "subAlice")
  302. if again := realitySpiderXFromStream(t, svc, "subAlice"); again != alice {
  303. t.Fatalf("spiderX not stable for the same client: %q vs %q", alice, again)
  304. }
  305. if bob := realitySpiderXFromStream(t, svc, "subBob"); bob == alice {
  306. t.Fatalf("spiderX identical across clients (fingerprintable): %q", alice)
  307. }
  308. }
  309. // streamData must tolerate malformed stored inbounds: unparseable stream JSON
  310. // (with a finalMask configured, which writes into the map) and tls/reality
  311. // security whose settings key is missing or null previously panicked the
  312. // subscription request.
  313. func TestSubJsonServiceStreamDataMalformedInputs(t *testing.T) {
  314. withMask := NewSubJsonService("", "", `{"tcp":[{"type":"fragment"}]}`, nil)
  315. stream := withMask.streamData("not-json", "clientKey")
  316. if _, ok := stream["finalmask"]; !ok {
  317. t.Fatal("finalMask must still apply when stream settings fail to parse")
  318. }
  319. svc := NewSubJsonService("", "", "", nil)
  320. noReality := svc.streamData(`{"network":"tcp","security":"reality"}`, "clientKey")
  321. if v, ok := noReality["realitySettings"]; ok {
  322. t.Fatalf("missing realitySettings must stay absent, got %v", v)
  323. }
  324. nullTls := svc.streamData(`{"network":"tcp","security":"tls","tlsSettings":null}`, "")
  325. if v, ok := nullTls["tlsSettings"]; ok {
  326. t.Fatalf("null tlsSettings must be dropped, got %v", v)
  327. }
  328. }
  329. func TestSubJsonServiceRealityDataSpiderXFallsBackWhenNoClientKey(t *testing.T) {
  330. svc := NewSubJsonService("", "", "", nil)
  331. stream := svc.streamData(`{
  332. "network":"tcp","security":"reality","tcpSettings":{"header":{"type":"none"}},
  333. "realitySettings":{
  334. "serverNames":["reality.example.com"],
  335. "shortIds":["ab12cd"],
  336. "settings":{"publicKey":"PBKvalue","fingerprint":"firefox"}
  337. }
  338. }`, "")
  339. rlty, _ := stream["realitySettings"].(map[string]any)
  340. if rlty == nil {
  341. t.Fatal("streamData dropped realitySettings")
  342. }
  343. spx, _ := rlty["spiderX"].(string)
  344. if len(spx) != 16 || spx[0] != '/' {
  345. t.Fatalf("spiderX fallback = %q, want random 16-char /-prefixed value", spx)
  346. }
  347. }
  348. func TestSubJsonServiceWireguard(t *testing.T) {
  349. serverPriv, serverPub, err := wgutil.GenerateWireguardKeypair()
  350. if err != nil {
  351. t.Fatalf("server keypair: %v", err)
  352. }
  353. clientPriv, _, err := wgutil.GenerateWireguardKeypair()
  354. if err != nil {
  355. t.Fatalf("client keypair: %v", err)
  356. }
  357. inbound := &model.Inbound{
  358. Listen: "203.0.113.9",
  359. Port: 51820,
  360. Protocol: model.WireGuard,
  361. Settings: `{"secretKey":"` + serverPriv + `","mtu":1420}`,
  362. }
  363. client := model.Client{
  364. Email: "user",
  365. PrivateKey: clientPriv,
  366. PreSharedKey: "psk-value",
  367. KeepAlive: 25,
  368. AllowedIPs: []string{"10.0.0.2/32", "fd00::2/128"},
  369. }
  370. raw := NewSubJsonService("", "", "", nil).genWireguard(inbound, client)
  371. if raw == nil {
  372. t.Fatal("genWireguard returned nil for a valid wireguard client")
  373. }
  374. settings := outboundSettings(t, raw)
  375. if settings["secretKey"] != clientPriv {
  376. t.Fatalf("secretKey = %v, want client private key", settings["secretKey"])
  377. }
  378. address, _ := settings["address"].([]any)
  379. if len(address) != 2 || address[0] != "10.0.0.2/32" || address[1] != "fd00::2/128" {
  380. t.Fatalf("address = %v, want client tunnel addresses", settings["address"])
  381. }
  382. if settings["mtu"] != float64(1420) {
  383. t.Fatalf("mtu = %v, want 1420", settings["mtu"])
  384. }
  385. peers, _ := settings["peers"].([]any)
  386. if len(peers) != 1 {
  387. t.Fatalf("peers len = %d, want 1", len(peers))
  388. }
  389. peer, _ := peers[0].(map[string]any)
  390. if peer["publicKey"] != serverPub {
  391. t.Fatalf("peer publicKey = %v, want %v (derived from inbound secretKey)", peer["publicKey"], serverPub)
  392. }
  393. if peer["endpoint"] != "203.0.113.9:51820" {
  394. t.Fatalf("peer endpoint = %v, want 203.0.113.9:51820", peer["endpoint"])
  395. }
  396. if peer["preSharedKey"] != "psk-value" {
  397. t.Fatalf("peer preSharedKey = %v, want psk-value", peer["preSharedKey"])
  398. }
  399. if peer["keepAlive"] != float64(25) {
  400. t.Fatalf("peer keepAlive = %v, want 25", peer["keepAlive"])
  401. }
  402. allowed, _ := peer["allowedIPs"].([]any)
  403. if !reflect.DeepEqual(allowed, []any{"0.0.0.0/0", "::/0"}) {
  404. t.Fatalf("peer allowedIPs = %v, want full tunnel", peer["allowedIPs"])
  405. }
  406. }
  407. func TestSubJsonServiceWireguardNoKey(t *testing.T) {
  408. inbound := &model.Inbound{Listen: "203.0.113.9", Port: 51820, Protocol: model.WireGuard, Settings: `{}`}
  409. client := model.Client{Email: "user"}
  410. if raw := NewSubJsonService("", "", "", nil).genWireguard(inbound, client); raw != nil {
  411. t.Fatalf("genWireguard = %s, want nil for a keyless wireguard client", raw)
  412. }
  413. }