clash_service_test.go 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860
  1. package sub
  2. import (
  3. "reflect"
  4. "testing"
  5. "github.com/mhsanaei/3x-ui/v3/internal/database/model"
  6. wgutil "github.com/mhsanaei/3x-ui/v3/internal/util/wireguard"
  7. )
  8. func TestEnsureUniqueProxyNames(t *testing.T) {
  9. proxies := []map[string]any{
  10. {"name": "", "type": "vless", "server": "a.com", "port": 443},
  11. {"name": "", "type": "vmess", "server": "b.com", "port": 8443},
  12. {"name": "node"},
  13. {"name": "node"},
  14. {"name": ""},
  15. }
  16. ensureUniqueProxyNames(proxies)
  17. seen := map[string]bool{}
  18. for i, p := range proxies {
  19. name, _ := p["name"].(string)
  20. if name == "" {
  21. t.Fatalf("proxy %d still has an empty name (mihomo would reject the config, #4641)", i)
  22. }
  23. if seen[name] {
  24. t.Fatalf("proxy %d has duplicate name %q (mihomo rejects the whole config, #4641)", i, name)
  25. }
  26. seen[name] = true
  27. }
  28. if got := proxies[0]["name"]; got != "vless-a.com-443" {
  29. t.Errorf("empty name fallback = %q, want vless-a.com-443", got)
  30. }
  31. if proxies[2]["name"] == proxies[3]["name"] {
  32. t.Errorf("duplicate %q was not disambiguated", proxies[2]["name"])
  33. }
  34. if got := proxies[4]["name"]; got != "proxy-5" {
  35. t.Errorf("typeless empty name fallback = %q, want proxy-5", got)
  36. }
  37. }
  38. // TestBuildProxy_VLESSRealityFieldsForClash locks the reality field mapping in
  39. // applySecurity (clash_service.go ~488): a regression that drops servername,
  40. // public-key, short-id, or client-fingerprint would hand mihomo a broken reality
  41. // proxy. The existing clash tests don't assert any of these.
  42. func TestBuildProxy_VLESSRealityFieldsForClash(t *testing.T) {
  43. svc := &SubClashService{SubService: &SubService{}}
  44. inbound := &model.Inbound{Listen: "203.0.113.1", Port: 443, Protocol: model.VLESS, Remark: "r", Settings: `{"encryption":"none"}`}
  45. client := model.Client{ID: "11111111-2222-4333-8444-555555555555"}
  46. stream := map[string]any{
  47. "network": "tcp",
  48. "security": "reality",
  49. "tcpSettings": map[string]any{"header": map[string]any{"type": "none"}},
  50. "realitySettings": map[string]any{"serverName": "reality.example.com", "publicKey": "PBKvalue", "shortId": "ab12", "fingerprint": "chrome"},
  51. }
  52. proxy := svc.buildProxy(svc.SubService, inbound, client, stream, nil)
  53. if proxy == nil {
  54. t.Fatal("buildProxy returned nil for a valid reality stream")
  55. }
  56. if proxy["tls"] != true {
  57. t.Fatalf("tls = %v, want true", proxy["tls"])
  58. }
  59. if proxy["servername"] != "reality.example.com" {
  60. t.Fatalf("servername = %v, want reality.example.com", proxy["servername"])
  61. }
  62. if proxy["client-fingerprint"] != "chrome" {
  63. t.Fatalf("client-fingerprint = %v, want chrome", proxy["client-fingerprint"])
  64. }
  65. opts, _ := proxy["reality-opts"].(map[string]any)
  66. if opts == nil {
  67. t.Fatal("reality-opts missing")
  68. }
  69. if opts["public-key"] != "PBKvalue" {
  70. t.Fatalf("public-key = %v, want PBKvalue", opts["public-key"])
  71. }
  72. if opts["short-id"] != "ab12" {
  73. t.Fatalf("short-id = %v, want ab12", opts["short-id"])
  74. }
  75. }
  76. // TestApplyTransport_TCPHeader pins the tcp-header validation (clash_service.go ~359):
  77. // plain tcp and a "none" header are representable in clash; a non-none obfs header is
  78. // not, so applyTransport must reject it (returning false drops it from the YAML).
  79. func TestApplyTransport_TCPHeader(t *testing.T) {
  80. svc := &SubClashService{}
  81. if !svc.applyTransport(map[string]any{}, "tcp", map[string]any{}) {
  82. t.Fatal("plain tcp must be buildable")
  83. }
  84. noneStream := map[string]any{"tcpSettings": map[string]any{"header": map[string]any{"type": "none"}}}
  85. if !svc.applyTransport(map[string]any{}, "tcp", noneStream) {
  86. t.Fatal("tcp + header type none must be buildable")
  87. }
  88. httpStream := map[string]any{"tcpSettings": map[string]any{"header": map[string]any{"type": "http"}}}
  89. if svc.applyTransport(map[string]any{}, "tcp", httpStream) {
  90. t.Fatal("tcp + non-none (http) header is not representable in clash and must be rejected")
  91. }
  92. }
  93. func TestApplyTransport_XHTTP(t *testing.T) {
  94. svc := &SubClashService{}
  95. proxy := map[string]any{}
  96. stream := map[string]any{
  97. "xhttpSettings": map[string]any{
  98. "path": "/xh",
  99. "host": "example.com",
  100. "mode": "auto",
  101. },
  102. }
  103. if !svc.applyTransport(proxy, "xhttp", stream) {
  104. t.Fatalf("applyTransport returned false for xhttp (#4531: would drop the inbound and yield an empty Clash YAML)")
  105. }
  106. if proxy["network"] != "xhttp" {
  107. t.Fatalf("network = %v, want xhttp", proxy["network"])
  108. }
  109. opts, ok := proxy["xhttp-opts"].(map[string]any)
  110. if !ok {
  111. t.Fatalf("xhttp-opts missing or wrong type: %#v", proxy["xhttp-opts"])
  112. }
  113. want := map[string]any{"path": "/xh", "host": "example.com", "mode": "auto"}
  114. if !reflect.DeepEqual(opts, want) {
  115. t.Fatalf("xhttp-opts = %#v, want %#v", opts, want)
  116. }
  117. }
  118. func TestApplyTransport_XHTTP_HostFromHeaders(t *testing.T) {
  119. svc := &SubClashService{}
  120. proxy := map[string]any{}
  121. stream := map[string]any{
  122. "xhttpSettings": map[string]any{
  123. "path": "/xh",
  124. "headers": map[string]any{"Host": "via-header.example.com"},
  125. },
  126. }
  127. if !svc.applyTransport(proxy, "xhttp", stream) {
  128. t.Fatalf("applyTransport returned false for xhttp")
  129. }
  130. opts, _ := proxy["xhttp-opts"].(map[string]any)
  131. if opts["host"] != "via-header.example.com" {
  132. t.Fatalf("host should fall back to headers.Host, got %v", opts["host"])
  133. }
  134. }
  135. func TestApplyTransport_XHTTP_NoSettings(t *testing.T) {
  136. svc := &SubClashService{}
  137. proxy := map[string]any{}
  138. stream := map[string]any{}
  139. if !svc.applyTransport(proxy, "xhttp", stream) {
  140. t.Fatalf("applyTransport returned false for xhttp with no xhttpSettings")
  141. }
  142. if proxy["network"] != "xhttp" {
  143. t.Fatalf("network = %v, want xhttp", proxy["network"])
  144. }
  145. if _, exists := proxy["xhttp-opts"]; exists {
  146. t.Fatalf("xhttp-opts should be absent when xhttpSettings is missing, got %#v", proxy["xhttp-opts"])
  147. }
  148. }
  149. func TestApplyTransport_HTTPUpgrade(t *testing.T) {
  150. svc := &SubClashService{}
  151. proxy := map[string]any{}
  152. stream := map[string]any{
  153. "httpupgradeSettings": map[string]any{
  154. "path": "/hu",
  155. "host": "example.com",
  156. },
  157. }
  158. if !svc.applyTransport(proxy, "httpupgrade", stream) {
  159. t.Fatalf("applyTransport returned false for httpupgrade")
  160. }
  161. if proxy["network"] != "httpupgrade" {
  162. t.Fatalf("network = %v, want httpupgrade", proxy["network"])
  163. }
  164. opts, ok := proxy["http-upgrade-opts"].(map[string]any)
  165. if !ok {
  166. t.Fatalf("http-upgrade-opts missing: %#v", proxy["http-upgrade-opts"])
  167. }
  168. if opts["path"] != "/hu" {
  169. t.Fatalf("path = %v, want /hu", opts["path"])
  170. }
  171. headers, _ := opts["headers"].(map[string]any)
  172. if headers["Host"] != "example.com" {
  173. t.Fatalf("headers.Host = %v, want example.com", headers["Host"])
  174. }
  175. }
  176. func TestBuildProxy_VLESSPostQuantumEncryptionUsesMihomoEncryptionField(t *testing.T) {
  177. svc := &SubClashService{SubService: &SubService{}}
  178. encryption := "mlkem768x25519plus.native.0rtt.client"
  179. inbound := &model.Inbound{
  180. Listen: "203.0.113.1",
  181. Port: 443,
  182. Protocol: model.VLESS,
  183. Remark: "pq",
  184. Settings: `{"encryption":"` + encryption + `"}`,
  185. }
  186. client := model.Client{ID: "11111111-2222-4333-8444-555555555555"}
  187. stream := map[string]any{
  188. "network": "xhttp",
  189. "xhttpSettings": map[string]any{
  190. "path": "/",
  191. "mode": "auto",
  192. },
  193. "security": "reality",
  194. "realitySettings": map[string]any{
  195. "publicKey": "pub",
  196. "serverName": "example.com",
  197. "shortId": "abcd",
  198. },
  199. }
  200. proxy := svc.buildProxy(svc.SubService, inbound, client, stream, nil)
  201. if proxy["encryption"] != encryption {
  202. t.Fatalf("encryption = %v, want %q", proxy["encryption"], encryption)
  203. }
  204. }
  205. func TestBuildProxy_VLESSFlowXhttpRealityVlessenc(t *testing.T) {
  206. svc := &SubClashService{SubService: &SubService{}}
  207. encryption := "mlkem768x25519plus.native.0rtt.client"
  208. inbound := &model.Inbound{
  209. Listen: "203.0.113.1",
  210. Port: 443,
  211. Protocol: model.VLESS,
  212. Remark: "pq-flow",
  213. Settings: `{"encryption":"` + encryption + `"}`,
  214. }
  215. client := model.Client{ID: "11111111-2222-4333-8444-555555555555", Flow: "xtls-rprx-vision"}
  216. stream := map[string]any{
  217. "network": "xhttp",
  218. "xhttpSettings": map[string]any{
  219. "path": "/",
  220. "mode": "auto",
  221. },
  222. "security": "reality",
  223. "realitySettings": map[string]any{
  224. "publicKey": "pub",
  225. "serverName": "example.com",
  226. "shortId": "abcd",
  227. },
  228. }
  229. proxy := svc.buildProxy(svc.SubService, inbound, client, stream, nil)
  230. if proxy["flow"] != "xtls-rprx-vision" {
  231. t.Fatalf("xhttp+reality+vlessenc Clash proxy must carry the vision flow (#5232): %#v", proxy)
  232. }
  233. }
  234. func TestBuildProxy_VLESSFlowDroppedWithoutVisionSupport(t *testing.T) {
  235. svc := &SubClashService{SubService: &SubService{}}
  236. inbound := &model.Inbound{
  237. Listen: "203.0.113.1",
  238. Port: 443,
  239. Protocol: model.VLESS,
  240. Remark: "plain-flow",
  241. Settings: `{"encryption":"none"}`,
  242. }
  243. client := model.Client{ID: "11111111-2222-4333-8444-555555555555", Flow: "xtls-rprx-vision"}
  244. stream := map[string]any{
  245. "network": "tcp",
  246. "security": "none",
  247. "tcpSettings": map[string]any{
  248. "header": map[string]any{"type": "none"},
  249. },
  250. }
  251. proxy := svc.buildProxy(svc.SubService, inbound, client, stream, nil)
  252. if _, ok := proxy["flow"]; ok {
  253. t.Fatalf("tcp without tls/reality must not carry a flow: %#v", proxy)
  254. }
  255. }
  256. func TestBuildProxy_VLESSNoneEncryptionOmittedForClash(t *testing.T) {
  257. svc := &SubClashService{SubService: &SubService{}}
  258. inbound := &model.Inbound{
  259. Listen: "203.0.113.1",
  260. Port: 443,
  261. Protocol: model.VLESS,
  262. Remark: "plain",
  263. Settings: `{"encryption":"none"}`,
  264. }
  265. client := model.Client{ID: "11111111-2222-4333-8444-555555555555"}
  266. stream := map[string]any{
  267. "network": "tcp",
  268. "security": "none",
  269. "tcpSettings": map[string]any{
  270. "header": map[string]any{"type": "none"},
  271. },
  272. }
  273. proxy := svc.buildProxy(svc.SubService, inbound, client, stream, nil)
  274. if _, ok := proxy["encryption"]; ok {
  275. t.Fatalf("plain vless encryption should be omitted for mihomo: %#v", proxy)
  276. }
  277. // The rest of the proxy must still be well-formed — otherwise a mutant that
  278. // drops encryption *and* corrupts a core field passes the absence check alone.
  279. if proxy["type"] != "vless" {
  280. t.Fatalf("type = %v, want vless", proxy["type"])
  281. }
  282. if proxy["server"] != "203.0.113.1" {
  283. t.Fatalf("server = %v, want 203.0.113.1", proxy["server"])
  284. }
  285. if proxy["port"] != 443 {
  286. t.Fatalf("port = %v, want 443", proxy["port"])
  287. }
  288. if proxy["uuid"] != client.ID {
  289. t.Fatalf("uuid = %v, want %v", proxy["uuid"], client.ID)
  290. }
  291. }
  292. func TestBuildXhttpClashOpts_FullFieldMapping(t *testing.T) {
  293. xhttp := map[string]any{
  294. "path": "/api/v1",
  295. "mode": "stream-up",
  296. "host": "example.com",
  297. "xPaddingBytes": "100-1000",
  298. "xPaddingObfsMode": true,
  299. "xPaddingKey": "mykey",
  300. "xPaddingHeader": "X-Trace-ID",
  301. "xPaddingPlacement": "queryInHeader",
  302. "xPaddingMethod": "tokenish",
  303. "uplinkHTTPMethod": "POST",
  304. "sessionIDPlacement": "query",
  305. "sessionIDKey": "sess",
  306. "sessionIDTable": "Base62",
  307. "sessionIDLength": "16-32",
  308. "seqPlacement": "header",
  309. "seqKey": "seq",
  310. "uplinkDataPlacement": "body",
  311. "uplinkDataKey": "udata",
  312. "uplinkChunkSize": "64-256",
  313. "noGRPCHeader": true,
  314. "scMaxEachPostBytes": "500000",
  315. "scMinPostsIntervalMs": "50",
  316. "xmux": map[string]any{
  317. "maxConcurrency": "16-32",
  318. "maxConnections": "4",
  319. "cMaxReuseTimes": "8",
  320. "hMaxRequestTimes": "600-900",
  321. "hMaxReusableSecs": "1800-3000",
  322. "hKeepAlivePeriod": float64(60),
  323. },
  324. "headers": map[string]any{
  325. "User-Agent": "chrome",
  326. "Host": "should-be-dropped.com",
  327. },
  328. }
  329. opts := buildXhttpClashOpts(xhttp)
  330. if opts == nil {
  331. t.Fatal("expected non-nil opts for full field mapping")
  332. }
  333. // Direct fields
  334. if opts["path"] != "/api/v1" {
  335. t.Errorf("path = %v, want /api/v1", opts["path"])
  336. }
  337. if opts["mode"] != "stream-up" {
  338. t.Errorf("mode = %v, want stream-up", opts["mode"])
  339. }
  340. if opts["host"] != "example.com" {
  341. t.Errorf("host = %v, want example.com", opts["host"])
  342. }
  343. // String fields
  344. if opts["x-padding-bytes"] != "100-1000" {
  345. t.Errorf("x-padding-bytes = %v", opts["x-padding-bytes"])
  346. }
  347. if opts["uplink-http-method"] != "POST" {
  348. t.Errorf("uplink-http-method = %v", opts["uplink-http-method"])
  349. }
  350. if opts["session-id-placement"] != "query" {
  351. t.Errorf("session-id-placement = %v", opts["session-id-placement"])
  352. }
  353. if opts["session-id-key"] != "sess" {
  354. t.Errorf("session-id-key = %v", opts["session-id-key"])
  355. }
  356. if opts["session-id-table"] != "Base62" {
  357. t.Errorf("session-id-table = %v", opts["session-id-table"])
  358. }
  359. if opts["session-id-length"] != "16-32" {
  360. t.Errorf("session-id-length = %v", opts["session-id-length"])
  361. }
  362. if opts["seq-placement"] != "header" {
  363. t.Errorf("seq-placement = %v", opts["seq-placement"])
  364. }
  365. if opts["seq-key"] != "seq" {
  366. t.Errorf("seq-key = %v", opts["seq-key"])
  367. }
  368. if opts["uplink-data-placement"] != "body" {
  369. t.Errorf("uplink-data-placement = %v", opts["uplink-data-placement"])
  370. }
  371. if opts["uplink-data-key"] != "udata" {
  372. t.Errorf("uplink-data-key = %v", opts["uplink-data-key"])
  373. }
  374. // DPI-filtered fields (non-default values should pass)
  375. if opts["sc-max-each-post-bytes"] != "500000" {
  376. t.Errorf("sc-max-each-post-bytes = %v", opts["sc-max-each-post-bytes"])
  377. }
  378. if opts["sc-min-posts-interval-ms"] != "50" {
  379. t.Errorf("sc-min-posts-interval-ms = %v", opts["sc-min-posts-interval-ms"])
  380. }
  381. // Bool fields
  382. if opts["no-grpc-header"] != true {
  383. t.Errorf("no-grpc-header = %v, want true", opts["no-grpc-header"])
  384. }
  385. if opts["x-padding-obfs-mode"] != true {
  386. t.Errorf("x-padding-obfs-mode = %v, want true", opts["x-padding-obfs-mode"])
  387. }
  388. // Padding obfs gated fields
  389. if opts["x-padding-key"] != "mykey" {
  390. t.Errorf("x-padding-key = %v", opts["x-padding-key"])
  391. }
  392. if opts["x-padding-header"] != "X-Trace-ID" {
  393. t.Errorf("x-padding-header = %v", opts["x-padding-header"])
  394. }
  395. if opts["x-padding-placement"] != "queryInHeader" {
  396. t.Errorf("x-padding-placement = %v", opts["x-padding-placement"])
  397. }
  398. if opts["x-padding-method"] != "tokenish" {
  399. t.Errorf("x-padding-method = %v", opts["x-padding-method"])
  400. }
  401. // Non-zero value fields
  402. if opts["uplink-chunk-size"] != "64-256" {
  403. t.Errorf("uplink-chunk-size = %v", opts["uplink-chunk-size"])
  404. }
  405. // Reuse-settings (xmux)
  406. reuse, ok := opts["reuse-settings"].(map[string]any)
  407. if !ok {
  408. t.Fatalf("reuse-settings missing or wrong type: %#v", opts["reuse-settings"])
  409. }
  410. if reuse["max-concurrency"] != "16-32" {
  411. t.Errorf("max-concurrency = %v", reuse["max-concurrency"])
  412. }
  413. if reuse["max-connections"] != "4" {
  414. t.Errorf("max-connections = %v", reuse["max-connections"])
  415. }
  416. if reuse["c-max-reuse-times"] != "8" {
  417. t.Errorf("c-max-reuse-times = %v", reuse["c-max-reuse-times"])
  418. }
  419. if reuse["h-max-request-times"] != "600-900" {
  420. t.Errorf("h-max-request-times = %v", reuse["h-max-request-times"])
  421. }
  422. if reuse["h-max-reusable-secs"] != "1800-3000" {
  423. t.Errorf("h-max-reusable-secs = %v", reuse["h-max-reusable-secs"])
  424. }
  425. if reuse["h-keep-alive-period"] != float64(60) {
  426. t.Errorf("h-keep-alive-period = %v, want 60", reuse["h-keep-alive-period"])
  427. }
  428. // Headers (Host should be dropped)
  429. headers, ok := opts["headers"].(map[string]any)
  430. if !ok {
  431. t.Fatalf("headers missing or wrong type: %#v", opts["headers"])
  432. }
  433. if headers["User-Agent"] != "chrome" {
  434. t.Errorf("headers[User-Agent] = %v", headers["User-Agent"])
  435. }
  436. if _, has := headers["Host"]; has {
  437. t.Error("headers should not contain Host key")
  438. }
  439. if _, has := headers["host"]; has {
  440. t.Error("headers should not contain host key (case-insensitive)")
  441. }
  442. }
  443. func TestBuildXhttpClashOpts_DPIDefaultsFiltered(t *testing.T) {
  444. xhttp := map[string]any{
  445. "path": "/",
  446. "mode": "stream-up",
  447. "scMaxEachPostBytes": "1000000",
  448. "scMinPostsIntervalMs": "30",
  449. }
  450. opts := buildXhttpClashOpts(xhttp)
  451. if opts == nil {
  452. t.Fatal("expected non-nil opts (path and mode should be present)")
  453. }
  454. if _, has := opts["sc-max-each-post-bytes"]; has {
  455. t.Error("sc-max-each-post-bytes should be filtered when value is 1000000")
  456. }
  457. if _, has := opts["sc-min-posts-interval-ms"]; has {
  458. t.Error("sc-min-posts-interval-ms should be filtered when value is 30")
  459. }
  460. }
  461. func TestBuildXhttpClashOpts_PaddingObfsGate(t *testing.T) {
  462. // Sub-test 1: obfs mode false — gated fields should not appear
  463. t.Run("ObfsModeFalse", func(t *testing.T) {
  464. xhttp := map[string]any{
  465. "path": "/",
  466. "xPaddingObfsMode": false,
  467. "xPaddingKey": "should-not-appear",
  468. }
  469. opts := buildXhttpClashOpts(xhttp)
  470. if opts == nil {
  471. t.Fatal("expected non-nil opts")
  472. }
  473. if _, has := opts["x-padding-obfs-mode"]; has {
  474. t.Error("x-padding-obfs-mode should not appear when false")
  475. }
  476. if _, has := opts["x-padding-key"]; has {
  477. t.Error("x-padding-key should not appear when obfs mode is false")
  478. }
  479. })
  480. // Sub-test 2: obfs mode absent — gated fields should not appear
  481. t.Run("ObfsModeAbsent", func(t *testing.T) {
  482. xhttp := map[string]any{
  483. "path": "/",
  484. "xPaddingKey": "should-not-appear",
  485. }
  486. opts := buildXhttpClashOpts(xhttp)
  487. if opts == nil {
  488. t.Fatal("expected non-nil opts")
  489. }
  490. if _, has := opts["x-padding-key"]; has {
  491. t.Error("x-padding-key should not appear when obfs mode is absent")
  492. }
  493. })
  494. // Sub-test 3: obfs mode true with no gated fields — only x-padding-obfs-mode appears
  495. t.Run("ObfsModeTrueNoGatedFields", func(t *testing.T) {
  496. xhttp := map[string]any{
  497. "path": "/",
  498. "xPaddingObfsMode": true,
  499. }
  500. opts := buildXhttpClashOpts(xhttp)
  501. if opts == nil {
  502. t.Fatal("expected non-nil opts")
  503. }
  504. if opts["x-padding-obfs-mode"] != true {
  505. t.Errorf("x-padding-obfs-mode = %v, want true", opts["x-padding-obfs-mode"])
  506. }
  507. if _, has := opts["x-padding-key"]; has {
  508. t.Error("x-padding-key should not appear when not set")
  509. }
  510. })
  511. }
  512. func TestBuildXhttpClashOpts_XmuxMapsToReuseSettings(t *testing.T) {
  513. // Sub-test 1: full xmux mapping
  514. t.Run("FullXmux", func(t *testing.T) {
  515. xhttp := map[string]any{
  516. "path": "/",
  517. "xmux": map[string]any{
  518. "maxConcurrency": "16-32",
  519. "maxConnections": "4",
  520. "cMaxReuseTimes": "8",
  521. "hMaxRequestTimes": "600-900",
  522. "hMaxReusableSecs": "1800-3000",
  523. "hKeepAlivePeriod": float64(60),
  524. },
  525. }
  526. opts := buildXhttpClashOpts(xhttp)
  527. if opts == nil {
  528. t.Fatal("expected non-nil opts")
  529. }
  530. reuse, ok := opts["reuse-settings"].(map[string]any)
  531. if !ok {
  532. t.Fatalf("reuse-settings missing or wrong type: %#v", opts["reuse-settings"])
  533. }
  534. if reuse["max-concurrency"] != "16-32" {
  535. t.Errorf("max-concurrency = %v", reuse["max-concurrency"])
  536. }
  537. if reuse["max-connections"] != "4" {
  538. t.Errorf("max-connections = %v", reuse["max-connections"])
  539. }
  540. if reuse["c-max-reuse-times"] != "8" {
  541. t.Errorf("c-max-reuse-times = %v", reuse["c-max-reuse-times"])
  542. }
  543. if reuse["h-max-request-times"] != "600-900" {
  544. t.Errorf("h-max-request-times = %v", reuse["h-max-request-times"])
  545. }
  546. if reuse["h-max-reusable-secs"] != "1800-3000" {
  547. t.Errorf("h-max-reusable-secs = %v", reuse["h-max-reusable-secs"])
  548. }
  549. if reuse["h-keep-alive-period"] != float64(60) {
  550. t.Errorf("h-keep-alive-period = %v, want 60", reuse["h-keep-alive-period"])
  551. }
  552. })
  553. // Sub-test 2: empty xmux map — no reuse-settings key
  554. t.Run("EmptyXmux", func(t *testing.T) {
  555. xhttp := map[string]any{
  556. "path": "/",
  557. "xmux": map[string]any{},
  558. }
  559. opts := buildXhttpClashOpts(xhttp)
  560. if opts == nil {
  561. t.Fatal("expected non-nil opts (path is present)")
  562. }
  563. if _, has := opts["reuse-settings"]; has {
  564. t.Error("reuse-settings should not appear for empty xmux")
  565. }
  566. })
  567. // Sub-test 3: hKeepAlivePeriod as int (not float64)
  568. t.Run("IntKeepAlivePeriod", func(t *testing.T) {
  569. xhttp := map[string]any{
  570. "path": "/",
  571. "xmux": map[string]any{
  572. "hKeepAlivePeriod": int(60),
  573. },
  574. }
  575. opts := buildXhttpClashOpts(xhttp)
  576. if opts == nil {
  577. t.Fatal("expected non-nil opts")
  578. }
  579. reuse, ok := opts["reuse-settings"].(map[string]any)
  580. if !ok {
  581. t.Fatalf("reuse-settings missing: %#v", opts["reuse-settings"])
  582. }
  583. if reuse["h-keep-alive-period"] != int(60) {
  584. t.Errorf("h-keep-alive-period = %v (%T), want 60 (int)", reuse["h-keep-alive-period"], reuse["h-keep-alive-period"])
  585. }
  586. })
  587. // Sub-test 4: hKeepAlivePeriod=0 should be filtered
  588. t.Run("ZeroKeepAlivePeriod", func(t *testing.T) {
  589. xhttp := map[string]any{
  590. "path": "/",
  591. "xmux": map[string]any{
  592. "hKeepAlivePeriod": float64(0),
  593. },
  594. }
  595. opts := buildXhttpClashOpts(xhttp)
  596. if opts == nil {
  597. t.Fatal("expected non-nil opts")
  598. }
  599. if _, has := opts["reuse-settings"]; has {
  600. t.Error("reuse-settings should not appear when only hKeepAlivePeriod=0")
  601. }
  602. })
  603. }
  604. func TestBuildXhttpClashOpts_ServerOnlyFieldsExcluded(t *testing.T) {
  605. xhttp := map[string]any{
  606. "path": "/",
  607. "noSSEHeader": true,
  608. "scMaxBufferedPosts": "100",
  609. "scStreamUpServerSecs": "5",
  610. "serverMaxHeaderBytes": "4096",
  611. }
  612. opts := buildXhttpClashOpts(xhttp)
  613. if opts == nil {
  614. t.Fatal("expected non-nil opts (path is present)")
  615. }
  616. if _, has := opts["no-sse-header"]; has {
  617. t.Error("noSSEHeader should not appear in Clash output (server-only)")
  618. }
  619. if _, has := opts["sc-max-buffered-posts"]; has {
  620. t.Error("scMaxBufferedPosts should not appear in Clash output (server-only)")
  621. }
  622. if _, has := opts["sc-stream-up-server-secs"]; has {
  623. t.Error("scStreamUpServerSecs should not appear in Clash output (server-only)")
  624. }
  625. if _, has := opts["server-max-header-bytes"]; has {
  626. t.Error("serverMaxHeaderBytes should not appear in Clash output (not in Mihomo)")
  627. }
  628. }
  629. func TestBuildXhttpClashOpts_NilInput(t *testing.T) {
  630. opts := buildXhttpClashOpts(nil)
  631. if opts != nil {
  632. t.Fatalf("expected nil for nil input, got %#v", opts)
  633. }
  634. }
  635. func TestBuildXhttpClashOpts_EmptyInput(t *testing.T) {
  636. opts := buildXhttpClashOpts(map[string]any{})
  637. if opts != nil {
  638. t.Fatalf("expected nil for empty input, got %#v", opts)
  639. }
  640. }
  641. func TestBuildXhttpClashOpts_HostFallbackFromHeaders(t *testing.T) {
  642. // Sub-test 1: host from headers.Host
  643. t.Run("HostFromHeaders", func(t *testing.T) {
  644. xhttp := map[string]any{
  645. "path": "/",
  646. "headers": map[string]any{"Host": "via-header.example.com"},
  647. }
  648. opts := buildXhttpClashOpts(xhttp)
  649. if opts == nil {
  650. t.Fatal("expected non-nil opts")
  651. }
  652. if opts["host"] != "via-header.example.com" {
  653. t.Errorf("host = %v, want via-header.example.com", opts["host"])
  654. }
  655. })
  656. // Sub-test 2: headers only contains Host — no headers key in output
  657. t.Run("HeadersOnlyHost", func(t *testing.T) {
  658. xhttp := map[string]any{
  659. "path": "/",
  660. "headers": map[string]any{"Host": "only-host.example.com"},
  661. }
  662. opts := buildXhttpClashOpts(xhttp)
  663. if opts == nil {
  664. t.Fatal("expected non-nil opts")
  665. }
  666. if _, has := opts["headers"]; has {
  667. t.Error("headers key should not appear when only Host is present (Host is extracted to top-level)")
  668. }
  669. })
  670. // Sub-test 3: case-insensitive Host drop
  671. t.Run("CaseInsensitiveHostDrop", func(t *testing.T) {
  672. xhttp := map[string]any{
  673. "path": "/",
  674. "host": "explicit.example.com",
  675. "headers": map[string]any{
  676. "host": "lowercase-host.example.com",
  677. "X-Custom": "value",
  678. },
  679. }
  680. opts := buildXhttpClashOpts(xhttp)
  681. if opts == nil {
  682. t.Fatal("expected non-nil opts")
  683. }
  684. if opts["host"] != "explicit.example.com" {
  685. t.Errorf("host = %v, want explicit.example.com (explicit host wins)", opts["host"])
  686. }
  687. headers, ok := opts["headers"].(map[string]any)
  688. if !ok {
  689. t.Fatal("headers should be present (X-Custom remains)")
  690. }
  691. if _, has := headers["host"]; has {
  692. t.Error("lowercase 'host' should be dropped from headers")
  693. }
  694. if headers["X-Custom"] != "value" {
  695. t.Errorf("X-Custom = %v, want value", headers["X-Custom"])
  696. }
  697. })
  698. }
  699. func TestBuildXhttpClashOpts_NoGRPCHeaderFalsey(t *testing.T) {
  700. // Sub-test 1: noGRPCHeader: false
  701. t.Run("ExplicitFalse", func(t *testing.T) {
  702. xhttp := map[string]any{
  703. "path": "/",
  704. "noGRPCHeader": false,
  705. }
  706. opts := buildXhttpClashOpts(xhttp)
  707. if opts == nil {
  708. t.Fatal("expected non-nil opts (path is present)")
  709. }
  710. if _, has := opts["no-grpc-header"]; has {
  711. t.Error("no-grpc-header should not appear when noGRPCHeader is false")
  712. }
  713. })
  714. // Sub-test 2: noGRPCHeader absent
  715. t.Run("Absent", func(t *testing.T) {
  716. xhttp := map[string]any{
  717. "path": "/",
  718. }
  719. opts := buildXhttpClashOpts(xhttp)
  720. if opts == nil {
  721. t.Fatal("expected non-nil opts")
  722. }
  723. if _, has := opts["no-grpc-header"]; has {
  724. t.Error("no-grpc-header should not appear when absent")
  725. }
  726. })
  727. }
  728. func TestBuildWireguardProxyForClash(t *testing.T) {
  729. serverPriv, serverPub, err := wgutil.GenerateWireguardKeypair()
  730. if err != nil {
  731. t.Fatalf("server keypair: %v", err)
  732. }
  733. clientPriv, _, err := wgutil.GenerateWireguardKeypair()
  734. if err != nil {
  735. t.Fatalf("client keypair: %v", err)
  736. }
  737. svc := &SubClashService{SubService: &SubService{}}
  738. inbound := &model.Inbound{
  739. Listen: "203.0.113.9",
  740. Port: 51820,
  741. Protocol: model.WireGuard,
  742. Remark: "wg",
  743. Settings: `{"secretKey":"` + serverPriv + `","mtu":1420,"dns":"1.1.1.1, 8.8.8.8"}`,
  744. }
  745. client := model.Client{
  746. Email: "user",
  747. PrivateKey: clientPriv,
  748. PreSharedKey: "psk-value",
  749. KeepAlive: 25,
  750. AllowedIPs: []string{"10.0.0.2/32", "fd00::2/128"},
  751. }
  752. proxy := svc.buildProxy(svc.SubService, inbound, client, nil, nil)
  753. if proxy == nil {
  754. t.Fatal("buildProxy returned nil for a valid wireguard client")
  755. }
  756. if proxy["type"] != "wireguard" {
  757. t.Fatalf("type = %v, want wireguard", proxy["type"])
  758. }
  759. if proxy["server"] != "203.0.113.9" {
  760. t.Fatalf("server = %v, want 203.0.113.9", proxy["server"])
  761. }
  762. if proxy["port"] != 51820 {
  763. t.Fatalf("port = %v, want 51820", proxy["port"])
  764. }
  765. if proxy["private-key"] != clientPriv {
  766. t.Fatalf("private-key = %v, want %v", proxy["private-key"], clientPriv)
  767. }
  768. if proxy["public-key"] != serverPub {
  769. t.Fatalf("public-key = %v, want %v (derived from inbound secretKey)", proxy["public-key"], serverPub)
  770. }
  771. if proxy["pre-shared-key"] != "psk-value" {
  772. t.Fatalf("pre-shared-key = %v, want psk-value", proxy["pre-shared-key"])
  773. }
  774. if proxy["persistent-keepalive"] != 25 {
  775. t.Fatalf("persistent-keepalive = %v, want 25", proxy["persistent-keepalive"])
  776. }
  777. if proxy["ip"] != "10.0.0.2" {
  778. t.Fatalf("ip = %v, want 10.0.0.2", proxy["ip"])
  779. }
  780. if proxy["ipv6"] != "fd00::2" {
  781. t.Fatalf("ipv6 = %v, want fd00::2", proxy["ipv6"])
  782. }
  783. if proxy["mtu"] != 1420 {
  784. t.Fatalf("mtu = %v, want 1420", proxy["mtu"])
  785. }
  786. if proxy["udp"] != true {
  787. t.Fatalf("udp = %v, want true", proxy["udp"])
  788. }
  789. if dns, ok := proxy["dns"].([]string); !ok || !reflect.DeepEqual(dns, []string{"1.1.1.1", "8.8.8.8"}) {
  790. t.Fatalf("dns = %v, want [1.1.1.1 8.8.8.8]", proxy["dns"])
  791. }
  792. }
  793. func TestBuildWireguardProxyForClashNoKey(t *testing.T) {
  794. svc := &SubClashService{SubService: &SubService{}}
  795. inbound := &model.Inbound{Listen: "203.0.113.9", Port: 51820, Protocol: model.WireGuard, Settings: `{}`}
  796. client := model.Client{Email: "user"}
  797. if proxy := svc.buildProxy(svc.SubService, inbound, client, nil, nil); proxy != nil {
  798. t.Fatalf("buildProxy = %v, want nil for a keyless wireguard client", proxy)
  799. }
  800. }