clash_service_test.go 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885
  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_VLESSFlowSuppressedByDisableFlow(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: "disabled-flow",
  241. Settings: `{"encryption":"` + testMlkemEncryption + `"}`,
  242. DisableFlow: true,
  243. }
  244. client := model.Client{ID: "11111111-2222-4333-8444-555555555555", Flow: "xtls-rprx-vision"}
  245. stream := map[string]any{
  246. "network": "xhttp",
  247. "xhttpSettings": map[string]any{"path": "/", "mode": "auto"},
  248. "security": "reality",
  249. "realitySettings": map[string]any{"publicKey": "pub", "serverName": "example.com", "shortId": "abcd"},
  250. }
  251. proxy := svc.buildProxy(svc.SubService, inbound, client, stream, nil)
  252. if _, ok := proxy["flow"]; ok {
  253. t.Fatalf("DisableFlow inbound must not carry a flow in the Clash proxy: %#v", proxy)
  254. }
  255. }
  256. func TestBuildProxy_VLESSFlowDroppedWithoutVisionSupport(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-flow",
  263. Settings: `{"encryption":"none"}`,
  264. }
  265. client := model.Client{ID: "11111111-2222-4333-8444-555555555555", Flow: "xtls-rprx-vision"}
  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["flow"]; ok {
  275. t.Fatalf("tcp without tls/reality must not carry a flow: %#v", proxy)
  276. }
  277. }
  278. func TestBuildProxy_VLESSNoneEncryptionOmittedForClash(t *testing.T) {
  279. svc := &SubClashService{SubService: &SubService{}}
  280. inbound := &model.Inbound{
  281. Listen: "203.0.113.1",
  282. Port: 443,
  283. Protocol: model.VLESS,
  284. Remark: "plain",
  285. Settings: `{"encryption":"none"}`,
  286. }
  287. client := model.Client{ID: "11111111-2222-4333-8444-555555555555"}
  288. stream := map[string]any{
  289. "network": "tcp",
  290. "security": "none",
  291. "tcpSettings": map[string]any{
  292. "header": map[string]any{"type": "none"},
  293. },
  294. }
  295. proxy := svc.buildProxy(svc.SubService, inbound, client, stream, nil)
  296. if _, ok := proxy["encryption"]; ok {
  297. t.Fatalf("plain vless encryption should be omitted for mihomo: %#v", proxy)
  298. }
  299. // The rest of the proxy must still be well-formed — otherwise a mutant that
  300. // drops encryption *and* corrupts a core field passes the absence check alone.
  301. if proxy["type"] != "vless" {
  302. t.Fatalf("type = %v, want vless", proxy["type"])
  303. }
  304. if proxy["server"] != "203.0.113.1" {
  305. t.Fatalf("server = %v, want 203.0.113.1", proxy["server"])
  306. }
  307. if proxy["port"] != 443 {
  308. t.Fatalf("port = %v, want 443", proxy["port"])
  309. }
  310. if proxy["uuid"] != client.ID {
  311. t.Fatalf("uuid = %v, want %v", proxy["uuid"], client.ID)
  312. }
  313. }
  314. func TestBuildXhttpClashOpts_FullFieldMapping(t *testing.T) {
  315. xhttp := map[string]any{
  316. "path": "/api/v1",
  317. "mode": "stream-up",
  318. "host": "example.com",
  319. "xPaddingBytes": "100-1000",
  320. "xPaddingObfsMode": true,
  321. "xPaddingKey": "mykey",
  322. "xPaddingHeader": "X-Trace-ID",
  323. "xPaddingPlacement": "queryInHeader",
  324. "xPaddingMethod": "tokenish",
  325. "uplinkHTTPMethod": "POST",
  326. "sessionIDPlacement": "query",
  327. "sessionIDKey": "sess",
  328. "sessionIDTable": "Base62",
  329. "sessionIDLength": "16-32",
  330. "seqPlacement": "header",
  331. "seqKey": "seq",
  332. "uplinkDataPlacement": "body",
  333. "uplinkDataKey": "udata",
  334. "uplinkChunkSize": "64-256",
  335. "noGRPCHeader": true,
  336. "scMaxEachPostBytes": "500000",
  337. "scMinPostsIntervalMs": "50",
  338. "xmux": map[string]any{
  339. "maxConcurrency": "16-32",
  340. "maxConnections": "4",
  341. "cMaxReuseTimes": "8",
  342. "hMaxRequestTimes": "600-900",
  343. "hMaxReusableSecs": "1800-3000",
  344. "hKeepAlivePeriod": float64(60),
  345. },
  346. "headers": map[string]any{
  347. "User-Agent": "chrome",
  348. "Host": "should-be-dropped.com",
  349. },
  350. }
  351. opts := buildXhttpClashOpts(xhttp)
  352. if opts == nil {
  353. t.Fatal("expected non-nil opts for full field mapping")
  354. }
  355. // Direct fields
  356. if opts["path"] != "/api/v1" {
  357. t.Errorf("path = %v, want /api/v1", opts["path"])
  358. }
  359. if opts["mode"] != "stream-up" {
  360. t.Errorf("mode = %v, want stream-up", opts["mode"])
  361. }
  362. if opts["host"] != "example.com" {
  363. t.Errorf("host = %v, want example.com", opts["host"])
  364. }
  365. // String fields
  366. if opts["x-padding-bytes"] != "100-1000" {
  367. t.Errorf("x-padding-bytes = %v", opts["x-padding-bytes"])
  368. }
  369. if opts["uplink-http-method"] != "POST" {
  370. t.Errorf("uplink-http-method = %v", opts["uplink-http-method"])
  371. }
  372. if opts["session-id-placement"] != "query" {
  373. t.Errorf("session-id-placement = %v", opts["session-id-placement"])
  374. }
  375. if opts["session-id-key"] != "sess" {
  376. t.Errorf("session-id-key = %v", opts["session-id-key"])
  377. }
  378. if opts["session-id-table"] != "Base62" {
  379. t.Errorf("session-id-table = %v", opts["session-id-table"])
  380. }
  381. if opts["session-id-length"] != "16-32" {
  382. t.Errorf("session-id-length = %v", opts["session-id-length"])
  383. }
  384. if opts["seq-placement"] != "header" {
  385. t.Errorf("seq-placement = %v", opts["seq-placement"])
  386. }
  387. if opts["seq-key"] != "seq" {
  388. t.Errorf("seq-key = %v", opts["seq-key"])
  389. }
  390. if opts["uplink-data-placement"] != "body" {
  391. t.Errorf("uplink-data-placement = %v", opts["uplink-data-placement"])
  392. }
  393. if opts["uplink-data-key"] != "udata" {
  394. t.Errorf("uplink-data-key = %v", opts["uplink-data-key"])
  395. }
  396. // DPI-filtered fields (non-default values should pass)
  397. if opts["sc-max-each-post-bytes"] != "500000" {
  398. t.Errorf("sc-max-each-post-bytes = %v", opts["sc-max-each-post-bytes"])
  399. }
  400. if opts["sc-min-posts-interval-ms"] != "50" {
  401. t.Errorf("sc-min-posts-interval-ms = %v", opts["sc-min-posts-interval-ms"])
  402. }
  403. // Bool fields
  404. if opts["no-grpc-header"] != true {
  405. t.Errorf("no-grpc-header = %v, want true", opts["no-grpc-header"])
  406. }
  407. if opts["x-padding-obfs-mode"] != true {
  408. t.Errorf("x-padding-obfs-mode = %v, want true", opts["x-padding-obfs-mode"])
  409. }
  410. // Padding obfs gated fields
  411. if opts["x-padding-key"] != "mykey" {
  412. t.Errorf("x-padding-key = %v", opts["x-padding-key"])
  413. }
  414. if opts["x-padding-header"] != "X-Trace-ID" {
  415. t.Errorf("x-padding-header = %v", opts["x-padding-header"])
  416. }
  417. if opts["x-padding-placement"] != "queryInHeader" {
  418. t.Errorf("x-padding-placement = %v", opts["x-padding-placement"])
  419. }
  420. if opts["x-padding-method"] != "tokenish" {
  421. t.Errorf("x-padding-method = %v", opts["x-padding-method"])
  422. }
  423. // Non-zero value fields
  424. if opts["uplink-chunk-size"] != "64-256" {
  425. t.Errorf("uplink-chunk-size = %v", opts["uplink-chunk-size"])
  426. }
  427. // Reuse-settings (xmux)
  428. reuse, ok := opts["reuse-settings"].(map[string]any)
  429. if !ok {
  430. t.Fatalf("reuse-settings missing or wrong type: %#v", opts["reuse-settings"])
  431. }
  432. if reuse["max-concurrency"] != "16-32" {
  433. t.Errorf("max-concurrency = %v", reuse["max-concurrency"])
  434. }
  435. if reuse["max-connections"] != "4" {
  436. t.Errorf("max-connections = %v", reuse["max-connections"])
  437. }
  438. if reuse["c-max-reuse-times"] != "8" {
  439. t.Errorf("c-max-reuse-times = %v", reuse["c-max-reuse-times"])
  440. }
  441. if reuse["h-max-request-times"] != "600-900" {
  442. t.Errorf("h-max-request-times = %v", reuse["h-max-request-times"])
  443. }
  444. if reuse["h-max-reusable-secs"] != "1800-3000" {
  445. t.Errorf("h-max-reusable-secs = %v", reuse["h-max-reusable-secs"])
  446. }
  447. if reuse["h-keep-alive-period"] != float64(60) {
  448. t.Errorf("h-keep-alive-period = %v, want 60", reuse["h-keep-alive-period"])
  449. }
  450. // Headers (Host should be dropped)
  451. headers, ok := opts["headers"].(map[string]any)
  452. if !ok {
  453. t.Fatalf("headers missing or wrong type: %#v", opts["headers"])
  454. }
  455. if headers["User-Agent"] != "chrome" {
  456. t.Errorf("headers[User-Agent] = %v", headers["User-Agent"])
  457. }
  458. if _, has := headers["Host"]; has {
  459. t.Error("headers should not contain Host key")
  460. }
  461. if _, has := headers["host"]; has {
  462. t.Error("headers should not contain host key (case-insensitive)")
  463. }
  464. }
  465. func TestBuildXhttpClashOpts_DPIDefaultsFiltered(t *testing.T) {
  466. xhttp := map[string]any{
  467. "path": "/",
  468. "mode": "stream-up",
  469. "scMaxEachPostBytes": "1000000",
  470. "scMinPostsIntervalMs": "30",
  471. }
  472. opts := buildXhttpClashOpts(xhttp)
  473. if opts == nil {
  474. t.Fatal("expected non-nil opts (path and mode should be present)")
  475. }
  476. if _, has := opts["sc-max-each-post-bytes"]; has {
  477. t.Error("sc-max-each-post-bytes should be filtered when value is 1000000")
  478. }
  479. if _, has := opts["sc-min-posts-interval-ms"]; has {
  480. t.Error("sc-min-posts-interval-ms should be filtered when value is 30")
  481. }
  482. }
  483. func TestBuildXhttpClashOpts_PaddingObfsGate(t *testing.T) {
  484. // Sub-test 1: obfs mode false — gated fields should not appear
  485. t.Run("ObfsModeFalse", func(t *testing.T) {
  486. xhttp := map[string]any{
  487. "path": "/",
  488. "xPaddingObfsMode": false,
  489. "xPaddingKey": "should-not-appear",
  490. }
  491. opts := buildXhttpClashOpts(xhttp)
  492. if opts == nil {
  493. t.Fatal("expected non-nil opts")
  494. }
  495. if _, has := opts["x-padding-obfs-mode"]; has {
  496. t.Error("x-padding-obfs-mode should not appear when false")
  497. }
  498. if _, has := opts["x-padding-key"]; has {
  499. t.Error("x-padding-key should not appear when obfs mode is false")
  500. }
  501. })
  502. // Sub-test 2: obfs mode absent — gated fields should not appear
  503. t.Run("ObfsModeAbsent", func(t *testing.T) {
  504. xhttp := map[string]any{
  505. "path": "/",
  506. "xPaddingKey": "should-not-appear",
  507. }
  508. opts := buildXhttpClashOpts(xhttp)
  509. if opts == nil {
  510. t.Fatal("expected non-nil opts")
  511. }
  512. if _, has := opts["x-padding-key"]; has {
  513. t.Error("x-padding-key should not appear when obfs mode is absent")
  514. }
  515. })
  516. // Sub-test 3: obfs mode true with no gated fields — only x-padding-obfs-mode appears
  517. t.Run("ObfsModeTrueNoGatedFields", func(t *testing.T) {
  518. xhttp := map[string]any{
  519. "path": "/",
  520. "xPaddingObfsMode": true,
  521. }
  522. opts := buildXhttpClashOpts(xhttp)
  523. if opts == nil {
  524. t.Fatal("expected non-nil opts")
  525. }
  526. if opts["x-padding-obfs-mode"] != true {
  527. t.Errorf("x-padding-obfs-mode = %v, want true", opts["x-padding-obfs-mode"])
  528. }
  529. if _, has := opts["x-padding-key"]; has {
  530. t.Error("x-padding-key should not appear when not set")
  531. }
  532. })
  533. }
  534. func TestBuildXhttpClashOpts_XmuxMapsToReuseSettings(t *testing.T) {
  535. // Sub-test 1: full xmux mapping
  536. t.Run("FullXmux", func(t *testing.T) {
  537. xhttp := map[string]any{
  538. "path": "/",
  539. "xmux": map[string]any{
  540. "maxConcurrency": "16-32",
  541. "maxConnections": "4",
  542. "cMaxReuseTimes": "8",
  543. "hMaxRequestTimes": "600-900",
  544. "hMaxReusableSecs": "1800-3000",
  545. "hKeepAlivePeriod": float64(60),
  546. },
  547. }
  548. opts := buildXhttpClashOpts(xhttp)
  549. if opts == nil {
  550. t.Fatal("expected non-nil opts")
  551. }
  552. reuse, ok := opts["reuse-settings"].(map[string]any)
  553. if !ok {
  554. t.Fatalf("reuse-settings missing or wrong type: %#v", opts["reuse-settings"])
  555. }
  556. if reuse["max-concurrency"] != "16-32" {
  557. t.Errorf("max-concurrency = %v", reuse["max-concurrency"])
  558. }
  559. if reuse["max-connections"] != "4" {
  560. t.Errorf("max-connections = %v", reuse["max-connections"])
  561. }
  562. if reuse["c-max-reuse-times"] != "8" {
  563. t.Errorf("c-max-reuse-times = %v", reuse["c-max-reuse-times"])
  564. }
  565. if reuse["h-max-request-times"] != "600-900" {
  566. t.Errorf("h-max-request-times = %v", reuse["h-max-request-times"])
  567. }
  568. if reuse["h-max-reusable-secs"] != "1800-3000" {
  569. t.Errorf("h-max-reusable-secs = %v", reuse["h-max-reusable-secs"])
  570. }
  571. if reuse["h-keep-alive-period"] != float64(60) {
  572. t.Errorf("h-keep-alive-period = %v, want 60", reuse["h-keep-alive-period"])
  573. }
  574. })
  575. // Sub-test 2: empty xmux map — no reuse-settings key
  576. t.Run("EmptyXmux", func(t *testing.T) {
  577. xhttp := map[string]any{
  578. "path": "/",
  579. "xmux": map[string]any{},
  580. }
  581. opts := buildXhttpClashOpts(xhttp)
  582. if opts == nil {
  583. t.Fatal("expected non-nil opts (path is present)")
  584. }
  585. if _, has := opts["reuse-settings"]; has {
  586. t.Error("reuse-settings should not appear for empty xmux")
  587. }
  588. })
  589. // Sub-test 3: hKeepAlivePeriod as int (not float64)
  590. t.Run("IntKeepAlivePeriod", func(t *testing.T) {
  591. xhttp := map[string]any{
  592. "path": "/",
  593. "xmux": map[string]any{
  594. "hKeepAlivePeriod": int(60),
  595. },
  596. }
  597. opts := buildXhttpClashOpts(xhttp)
  598. if opts == nil {
  599. t.Fatal("expected non-nil opts")
  600. }
  601. reuse, ok := opts["reuse-settings"].(map[string]any)
  602. if !ok {
  603. t.Fatalf("reuse-settings missing: %#v", opts["reuse-settings"])
  604. }
  605. if reuse["h-keep-alive-period"] != int(60) {
  606. t.Errorf("h-keep-alive-period = %v (%T), want 60 (int)", reuse["h-keep-alive-period"], reuse["h-keep-alive-period"])
  607. }
  608. })
  609. // Sub-test 4: hKeepAlivePeriod=0 should be filtered
  610. t.Run("ZeroKeepAlivePeriod", func(t *testing.T) {
  611. xhttp := map[string]any{
  612. "path": "/",
  613. "xmux": map[string]any{
  614. "hKeepAlivePeriod": float64(0),
  615. },
  616. }
  617. opts := buildXhttpClashOpts(xhttp)
  618. if opts == nil {
  619. t.Fatal("expected non-nil opts")
  620. }
  621. if _, has := opts["reuse-settings"]; has {
  622. t.Error("reuse-settings should not appear when only hKeepAlivePeriod=0")
  623. }
  624. })
  625. }
  626. func TestBuildXhttpClashOpts_ServerOnlyFieldsExcluded(t *testing.T) {
  627. xhttp := map[string]any{
  628. "path": "/",
  629. "noSSEHeader": true,
  630. "scMaxBufferedPosts": "100",
  631. "scStreamUpServerSecs": "5",
  632. "serverMaxHeaderBytes": "4096",
  633. }
  634. opts := buildXhttpClashOpts(xhttp)
  635. if opts == nil {
  636. t.Fatal("expected non-nil opts (path is present)")
  637. }
  638. if _, has := opts["no-sse-header"]; has {
  639. t.Error("noSSEHeader should not appear in Clash output (server-only)")
  640. }
  641. if _, has := opts["sc-max-buffered-posts"]; has {
  642. t.Error("scMaxBufferedPosts should not appear in Clash output (server-only)")
  643. }
  644. if _, has := opts["sc-stream-up-server-secs"]; has {
  645. t.Error("scStreamUpServerSecs should not appear in Clash output (server-only)")
  646. }
  647. if _, has := opts["server-max-header-bytes"]; has {
  648. t.Error("serverMaxHeaderBytes should not appear in Clash output (not in Mihomo)")
  649. }
  650. }
  651. func TestBuildXhttpClashOpts_NilInput(t *testing.T) {
  652. opts := buildXhttpClashOpts(nil)
  653. if opts != nil {
  654. t.Fatalf("expected nil for nil input, got %#v", opts)
  655. }
  656. }
  657. func TestBuildXhttpClashOpts_EmptyInput(t *testing.T) {
  658. opts := buildXhttpClashOpts(map[string]any{})
  659. if opts != nil {
  660. t.Fatalf("expected nil for empty input, got %#v", opts)
  661. }
  662. }
  663. func TestBuildXhttpClashOpts_HostFallbackFromHeaders(t *testing.T) {
  664. // Sub-test 1: host from headers.Host
  665. t.Run("HostFromHeaders", func(t *testing.T) {
  666. xhttp := map[string]any{
  667. "path": "/",
  668. "headers": map[string]any{"Host": "via-header.example.com"},
  669. }
  670. opts := buildXhttpClashOpts(xhttp)
  671. if opts == nil {
  672. t.Fatal("expected non-nil opts")
  673. }
  674. if opts["host"] != "via-header.example.com" {
  675. t.Errorf("host = %v, want via-header.example.com", opts["host"])
  676. }
  677. })
  678. // Sub-test 2: headers only contains Host — no headers key in output
  679. t.Run("HeadersOnlyHost", func(t *testing.T) {
  680. xhttp := map[string]any{
  681. "path": "/",
  682. "headers": map[string]any{"Host": "only-host.example.com"},
  683. }
  684. opts := buildXhttpClashOpts(xhttp)
  685. if opts == nil {
  686. t.Fatal("expected non-nil opts")
  687. }
  688. if _, has := opts["headers"]; has {
  689. t.Error("headers key should not appear when only Host is present (Host is extracted to top-level)")
  690. }
  691. })
  692. // Sub-test 3: case-insensitive Host drop
  693. t.Run("CaseInsensitiveHostDrop", func(t *testing.T) {
  694. xhttp := map[string]any{
  695. "path": "/",
  696. "host": "explicit.example.com",
  697. "headers": map[string]any{
  698. "host": "lowercase-host.example.com",
  699. "X-Custom": "value",
  700. },
  701. }
  702. opts := buildXhttpClashOpts(xhttp)
  703. if opts == nil {
  704. t.Fatal("expected non-nil opts")
  705. }
  706. if opts["host"] != "explicit.example.com" {
  707. t.Errorf("host = %v, want explicit.example.com (explicit host wins)", opts["host"])
  708. }
  709. headers, ok := opts["headers"].(map[string]any)
  710. if !ok {
  711. t.Fatal("headers should be present (X-Custom remains)")
  712. }
  713. if _, has := headers["host"]; has {
  714. t.Error("lowercase 'host' should be dropped from headers")
  715. }
  716. if headers["X-Custom"] != "value" {
  717. t.Errorf("X-Custom = %v, want value", headers["X-Custom"])
  718. }
  719. })
  720. }
  721. func TestBuildXhttpClashOpts_NoGRPCHeaderFalsey(t *testing.T) {
  722. // Sub-test 1: noGRPCHeader: false
  723. t.Run("ExplicitFalse", func(t *testing.T) {
  724. xhttp := map[string]any{
  725. "path": "/",
  726. "noGRPCHeader": false,
  727. }
  728. opts := buildXhttpClashOpts(xhttp)
  729. if opts == nil {
  730. t.Fatal("expected non-nil opts (path is present)")
  731. }
  732. if _, has := opts["no-grpc-header"]; has {
  733. t.Error("no-grpc-header should not appear when noGRPCHeader is false")
  734. }
  735. })
  736. // Sub-test 2: noGRPCHeader absent
  737. t.Run("Absent", func(t *testing.T) {
  738. xhttp := map[string]any{
  739. "path": "/",
  740. }
  741. opts := buildXhttpClashOpts(xhttp)
  742. if opts == nil {
  743. t.Fatal("expected non-nil opts")
  744. }
  745. if _, has := opts["no-grpc-header"]; has {
  746. t.Error("no-grpc-header should not appear when absent")
  747. }
  748. })
  749. }
  750. func TestBuildWireguardProxyForClash(t *testing.T) {
  751. serverPriv, serverPub, err := wgutil.GenerateWireguardKeypair()
  752. if err != nil {
  753. t.Fatalf("server keypair: %v", err)
  754. }
  755. clientPriv, _, err := wgutil.GenerateWireguardKeypair()
  756. if err != nil {
  757. t.Fatalf("client keypair: %v", err)
  758. }
  759. svc := &SubClashService{SubService: &SubService{}}
  760. inbound := &model.Inbound{
  761. Listen: "203.0.113.9",
  762. Port: 51820,
  763. Protocol: model.WireGuard,
  764. Remark: "wg",
  765. Settings: `{"secretKey":"` + serverPriv + `","mtu":1420,"dns":"1.1.1.1, 8.8.8.8"}`,
  766. }
  767. client := model.Client{
  768. Email: "user",
  769. PrivateKey: clientPriv,
  770. PreSharedKey: "psk-value",
  771. KeepAlive: 25,
  772. AllowedIPs: []string{"10.0.0.2/32", "fd00::2/128"},
  773. }
  774. proxy := svc.buildProxy(svc.SubService, inbound, client, nil, nil)
  775. if proxy == nil {
  776. t.Fatal("buildProxy returned nil for a valid wireguard client")
  777. }
  778. if proxy["type"] != "wireguard" {
  779. t.Fatalf("type = %v, want wireguard", proxy["type"])
  780. }
  781. if proxy["server"] != "203.0.113.9" {
  782. t.Fatalf("server = %v, want 203.0.113.9", proxy["server"])
  783. }
  784. if proxy["port"] != 51820 {
  785. t.Fatalf("port = %v, want 51820", proxy["port"])
  786. }
  787. if proxy["private-key"] != clientPriv {
  788. t.Fatalf("private-key = %v, want %v", proxy["private-key"], clientPriv)
  789. }
  790. if proxy["public-key"] != serverPub {
  791. t.Fatalf("public-key = %v, want %v (derived from inbound secretKey)", proxy["public-key"], serverPub)
  792. }
  793. if proxy["pre-shared-key"] != "psk-value" {
  794. t.Fatalf("pre-shared-key = %v, want psk-value", proxy["pre-shared-key"])
  795. }
  796. if proxy["persistent-keepalive"] != 25 {
  797. t.Fatalf("persistent-keepalive = %v, want 25", proxy["persistent-keepalive"])
  798. }
  799. if proxy["ip"] != "10.0.0.2" {
  800. t.Fatalf("ip = %v, want 10.0.0.2", proxy["ip"])
  801. }
  802. if proxy["ipv6"] != "fd00::2" {
  803. t.Fatalf("ipv6 = %v, want fd00::2", proxy["ipv6"])
  804. }
  805. if proxy["mtu"] != 1420 {
  806. t.Fatalf("mtu = %v, want 1420", proxy["mtu"])
  807. }
  808. if proxy["udp"] != true {
  809. t.Fatalf("udp = %v, want true", proxy["udp"])
  810. }
  811. if dns, ok := proxy["dns"].([]string); !ok || !reflect.DeepEqual(dns, []string{"1.1.1.1", "8.8.8.8"}) {
  812. t.Fatalf("dns = %v, want [1.1.1.1 8.8.8.8]", proxy["dns"])
  813. }
  814. }
  815. func TestBuildWireguardProxyForClashNoKey(t *testing.T) {
  816. svc := &SubClashService{SubService: &SubService{}}
  817. inbound := &model.Inbound{Listen: "203.0.113.9", Port: 51820, Protocol: model.WireGuard, Settings: `{}`}
  818. client := model.Client{Email: "user"}
  819. if proxy := svc.buildProxy(svc.SubService, inbound, client, nil, nil); proxy != nil {
  820. t.Fatalf("buildProxy = %v, want nil for a keyless wireguard client", proxy)
  821. }
  822. }