json_service_test.go 21 KB

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