1
0

json_service_test.go 15 KB

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