1
0

json_service_test.go 15 KB

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