json_service_test.go 16 KB

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