clash_service_test.go 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309
  1. package sub
  2. import (
  3. "fmt"
  4. "reflect"
  5. "testing"
  6. "github.com/mhsanaei/3x-ui/v3/internal/amneziawg"
  7. "github.com/mhsanaei/3x-ui/v3/internal/database/model"
  8. wgutil "github.com/mhsanaei/3x-ui/v3/internal/util/wireguard"
  9. )
  10. func TestEnsureUniqueProxyNames(t *testing.T) {
  11. proxies := []map[string]any{
  12. {"name": "", "type": "vless", "server": "a.com", "port": 443},
  13. {"name": "", "type": "vmess", "server": "b.com", "port": 8443},
  14. {"name": "node"},
  15. {"name": "node"},
  16. {"name": ""},
  17. }
  18. ensureUniqueProxyNames(proxies)
  19. seen := map[string]bool{}
  20. for i, p := range proxies {
  21. name, _ := p["name"].(string)
  22. if name == "" {
  23. t.Fatalf("proxy %d still has an empty name (mihomo would reject the config, #4641)", i)
  24. }
  25. if seen[name] {
  26. t.Fatalf("proxy %d has duplicate name %q (mihomo rejects the whole config, #4641)", i, name)
  27. }
  28. seen[name] = true
  29. }
  30. if got := proxies[0]["name"]; got != "vless-a.com-443" {
  31. t.Errorf("empty name fallback = %q, want vless-a.com-443", got)
  32. }
  33. if proxies[2]["name"] == proxies[3]["name"] {
  34. t.Errorf("duplicate %q was not disambiguated", proxies[2]["name"])
  35. }
  36. if got := proxies[4]["name"]; got != "proxy-5" {
  37. t.Errorf("typeless empty name fallback = %q, want proxy-5", got)
  38. }
  39. }
  40. // TestBuildProxy_VLESSRealityFieldsForClash locks the reality field mapping in
  41. // applySecurity (clash_service.go ~488): a regression that drops servername,
  42. // public-key, short-id, or client-fingerprint would hand mihomo a broken reality
  43. // proxy. The existing clash tests don't assert any of these.
  44. func TestBuildProxy_VLESSRealityFieldsForClash(t *testing.T) {
  45. svc := &SubClashService{SubService: &SubService{}}
  46. inbound := &model.Inbound{Listen: "203.0.113.1", Port: 443, Protocol: model.VLESS, Remark: "r", Settings: `{"encryption":"none"}`}
  47. client := model.Client{ID: "11111111-2222-4333-8444-555555555555"}
  48. stream := map[string]any{
  49. "network": "tcp",
  50. "security": "reality",
  51. "tcpSettings": map[string]any{"header": map[string]any{"type": "none"}},
  52. "realitySettings": map[string]any{"serverName": "reality.example.com", "publicKey": "PBKvalue", "shortId": "ab12", "fingerprint": "chrome"},
  53. }
  54. proxy := svc.buildProxy(svc.SubService, inbound, client, stream, nil)
  55. if proxy == nil {
  56. t.Fatal("buildProxy returned nil for a valid reality stream")
  57. }
  58. if proxy["tls"] != true {
  59. t.Fatalf("tls = %v, want true", proxy["tls"])
  60. }
  61. if proxy["servername"] != "reality.example.com" {
  62. t.Fatalf("servername = %v, want reality.example.com", proxy["servername"])
  63. }
  64. if proxy["client-fingerprint"] != "chrome" {
  65. t.Fatalf("client-fingerprint = %v, want chrome", proxy["client-fingerprint"])
  66. }
  67. opts, _ := proxy["reality-opts"].(map[string]any)
  68. if opts == nil {
  69. t.Fatal("reality-opts missing")
  70. }
  71. if opts["public-key"] != "PBKvalue" {
  72. t.Fatalf("public-key = %v, want PBKvalue", opts["public-key"])
  73. }
  74. if opts["short-id"] != "ab12" {
  75. t.Fatalf("short-id = %v, want ab12", opts["short-id"])
  76. }
  77. }
  78. // TestApplyTransport_TCPHeader pins the tcp-header validation (clash_service.go ~359):
  79. // plain tcp and a "none" header are representable in clash; a non-none obfs header is
  80. // not, so applyTransport must reject it (returning false drops it from the YAML).
  81. func TestApplyTransport_TCPHeader(t *testing.T) {
  82. svc := &SubClashService{}
  83. if !svc.applyTransport(map[string]any{}, "tcp", map[string]any{}) {
  84. t.Fatal("plain tcp must be buildable")
  85. }
  86. noneStream := map[string]any{"tcpSettings": map[string]any{"header": map[string]any{"type": "none"}}}
  87. if !svc.applyTransport(map[string]any{}, "tcp", noneStream) {
  88. t.Fatal("tcp + header type none must be buildable")
  89. }
  90. httpStream := map[string]any{"tcpSettings": map[string]any{"header": map[string]any{"type": "http"}}}
  91. if svc.applyTransport(map[string]any{}, "tcp", httpStream) {
  92. t.Fatal("tcp + non-none (http) header is not representable in clash and must be rejected")
  93. }
  94. }
  95. func TestApplyTransport_XHTTP(t *testing.T) {
  96. svc := &SubClashService{}
  97. proxy := map[string]any{}
  98. stream := map[string]any{
  99. "xhttpSettings": map[string]any{
  100. "path": "/xh",
  101. "host": "example.com",
  102. "mode": "auto",
  103. },
  104. }
  105. if !svc.applyTransport(proxy, "xhttp", stream) {
  106. t.Fatalf("applyTransport returned false for xhttp (#4531: would drop the inbound and yield an empty Clash YAML)")
  107. }
  108. if proxy["network"] != "xhttp" {
  109. t.Fatalf("network = %v, want xhttp", proxy["network"])
  110. }
  111. opts, ok := proxy["xhttp-opts"].(map[string]any)
  112. if !ok {
  113. t.Fatalf("xhttp-opts missing or wrong type: %#v", proxy["xhttp-opts"])
  114. }
  115. want := map[string]any{"path": "/xh", "host": "example.com", "mode": "auto"}
  116. if !reflect.DeepEqual(opts, want) {
  117. t.Fatalf("xhttp-opts = %#v, want %#v", opts, want)
  118. }
  119. }
  120. func TestApplyTransport_XHTTP_HostFromHeaders(t *testing.T) {
  121. svc := &SubClashService{}
  122. proxy := map[string]any{}
  123. stream := map[string]any{
  124. "xhttpSettings": map[string]any{
  125. "path": "/xh",
  126. "headers": map[string]any{"Host": "via-header.example.com"},
  127. },
  128. }
  129. if !svc.applyTransport(proxy, "xhttp", stream) {
  130. t.Fatalf("applyTransport returned false for xhttp")
  131. }
  132. opts, _ := proxy["xhttp-opts"].(map[string]any)
  133. if opts["host"] != "via-header.example.com" {
  134. t.Fatalf("host should fall back to headers.Host, got %v", opts["host"])
  135. }
  136. }
  137. func TestApplyTransport_XHTTP_NoSettings(t *testing.T) {
  138. svc := &SubClashService{}
  139. proxy := map[string]any{}
  140. stream := map[string]any{}
  141. if !svc.applyTransport(proxy, "xhttp", stream) {
  142. t.Fatalf("applyTransport returned false for xhttp with no xhttpSettings")
  143. }
  144. if proxy["network"] != "xhttp" {
  145. t.Fatalf("network = %v, want xhttp", proxy["network"])
  146. }
  147. if _, exists := proxy["xhttp-opts"]; exists {
  148. t.Fatalf("xhttp-opts should be absent when xhttpSettings is missing, got %#v", proxy["xhttp-opts"])
  149. }
  150. }
  151. func TestApplyTransport_HTTPUpgrade(t *testing.T) {
  152. svc := &SubClashService{}
  153. proxy := map[string]any{}
  154. stream := map[string]any{
  155. "httpupgradeSettings": map[string]any{
  156. "path": "/hu",
  157. "host": "example.com",
  158. },
  159. }
  160. if !svc.applyTransport(proxy, "httpupgrade", stream) {
  161. t.Fatalf("applyTransport returned false for httpupgrade")
  162. }
  163. if proxy["network"] != "httpupgrade" {
  164. t.Fatalf("network = %v, want httpupgrade", proxy["network"])
  165. }
  166. opts, ok := proxy["http-upgrade-opts"].(map[string]any)
  167. if !ok {
  168. t.Fatalf("http-upgrade-opts missing: %#v", proxy["http-upgrade-opts"])
  169. }
  170. if opts["path"] != "/hu" {
  171. t.Fatalf("path = %v, want /hu", opts["path"])
  172. }
  173. headers, _ := opts["headers"].(map[string]any)
  174. if headers["Host"] != "example.com" {
  175. t.Fatalf("headers.Host = %v, want example.com", headers["Host"])
  176. }
  177. }
  178. func TestBuildProxy_VLESSPostQuantumEncryptionUsesMihomoEncryptionField(t *testing.T) {
  179. svc := &SubClashService{SubService: &SubService{}}
  180. encryption := "mlkem768x25519plus.native.0rtt.client"
  181. inbound := &model.Inbound{
  182. Listen: "203.0.113.1",
  183. Port: 443,
  184. Protocol: model.VLESS,
  185. Remark: "pq",
  186. Settings: `{"encryption":"` + encryption + `"}`,
  187. }
  188. client := model.Client{ID: "11111111-2222-4333-8444-555555555555"}
  189. stream := map[string]any{
  190. "network": "xhttp",
  191. "xhttpSettings": map[string]any{
  192. "path": "/",
  193. "mode": "auto",
  194. },
  195. "security": "reality",
  196. "realitySettings": map[string]any{
  197. "publicKey": "pub",
  198. "serverName": "example.com",
  199. "shortId": "abcd",
  200. },
  201. }
  202. proxy := svc.buildProxy(svc.SubService, inbound, client, stream, nil)
  203. if proxy["encryption"] != encryption {
  204. t.Fatalf("encryption = %v, want %q", proxy["encryption"], encryption)
  205. }
  206. }
  207. func TestBuildProxy_VLESSFlowXhttpRealityVlessenc(t *testing.T) {
  208. svc := &SubClashService{SubService: &SubService{}}
  209. encryption := "mlkem768x25519plus.native.0rtt.client"
  210. inbound := &model.Inbound{
  211. Listen: "203.0.113.1",
  212. Port: 443,
  213. Protocol: model.VLESS,
  214. Remark: "pq-flow",
  215. Settings: `{"encryption":"` + encryption + `"}`,
  216. }
  217. client := model.Client{ID: "11111111-2222-4333-8444-555555555555", Flow: "xtls-rprx-vision"}
  218. stream := map[string]any{
  219. "network": "xhttp",
  220. "xhttpSettings": map[string]any{
  221. "path": "/",
  222. "mode": "auto",
  223. },
  224. "security": "reality",
  225. "realitySettings": map[string]any{
  226. "publicKey": "pub",
  227. "serverName": "example.com",
  228. "shortId": "abcd",
  229. },
  230. }
  231. proxy := svc.buildProxy(svc.SubService, inbound, client, stream, nil)
  232. if proxy["flow"] != "xtls-rprx-vision" {
  233. t.Fatalf("xhttp+reality+vlessenc Clash proxy must carry the vision flow (#5232): %#v", proxy)
  234. }
  235. }
  236. func TestBuildProxy_VLESSFlowSuppressedByDisableFlow(t *testing.T) {
  237. svc := &SubClashService{SubService: &SubService{}}
  238. inbound := &model.Inbound{
  239. Listen: "203.0.113.1",
  240. Port: 443,
  241. Protocol: model.VLESS,
  242. Remark: "disabled-flow",
  243. Settings: `{"encryption":"` + testMlkemEncryption + `"}`,
  244. DisableFlow: true,
  245. }
  246. client := model.Client{ID: "11111111-2222-4333-8444-555555555555", Flow: "xtls-rprx-vision"}
  247. stream := map[string]any{
  248. "network": "xhttp",
  249. "xhttpSettings": map[string]any{"path": "/", "mode": "auto"},
  250. "security": "reality",
  251. "realitySettings": map[string]any{"publicKey": "pub", "serverName": "example.com", "shortId": "abcd"},
  252. }
  253. proxy := svc.buildProxy(svc.SubService, inbound, client, stream, nil)
  254. if _, ok := proxy["flow"]; ok {
  255. t.Fatalf("DisableFlow inbound must not carry a flow in the Clash proxy: %#v", proxy)
  256. }
  257. }
  258. func TestBuildProxy_VLESSFlowDroppedWithoutVisionSupport(t *testing.T) {
  259. svc := &SubClashService{SubService: &SubService{}}
  260. inbound := &model.Inbound{
  261. Listen: "203.0.113.1",
  262. Port: 443,
  263. Protocol: model.VLESS,
  264. Remark: "plain-flow",
  265. Settings: `{"encryption":"none"}`,
  266. }
  267. client := model.Client{ID: "11111111-2222-4333-8444-555555555555", Flow: "xtls-rprx-vision"}
  268. stream := map[string]any{
  269. "network": "tcp",
  270. "security": "none",
  271. "tcpSettings": map[string]any{
  272. "header": map[string]any{"type": "none"},
  273. },
  274. }
  275. proxy := svc.buildProxy(svc.SubService, inbound, client, stream, nil)
  276. if _, ok := proxy["flow"]; ok {
  277. t.Fatalf("tcp without tls/reality must not carry a flow: %#v", proxy)
  278. }
  279. }
  280. func TestBuildProxy_VLESSNoneEncryptionOmittedForClash(t *testing.T) {
  281. svc := &SubClashService{SubService: &SubService{}}
  282. inbound := &model.Inbound{
  283. Listen: "203.0.113.1",
  284. Port: 443,
  285. Protocol: model.VLESS,
  286. Remark: "plain",
  287. Settings: `{"encryption":"none"}`,
  288. }
  289. client := model.Client{ID: "11111111-2222-4333-8444-555555555555"}
  290. stream := map[string]any{
  291. "network": "tcp",
  292. "security": "none",
  293. "tcpSettings": map[string]any{
  294. "header": map[string]any{"type": "none"},
  295. },
  296. }
  297. proxy := svc.buildProxy(svc.SubService, inbound, client, stream, nil)
  298. if _, ok := proxy["encryption"]; ok {
  299. t.Fatalf("plain vless encryption should be omitted for mihomo: %#v", proxy)
  300. }
  301. // The rest of the proxy must still be well-formed — otherwise a mutant that
  302. // drops encryption *and* corrupts a core field passes the absence check alone.
  303. if proxy["type"] != "vless" {
  304. t.Fatalf("type = %v, want vless", proxy["type"])
  305. }
  306. if proxy["server"] != "203.0.113.1" {
  307. t.Fatalf("server = %v, want 203.0.113.1", proxy["server"])
  308. }
  309. if proxy["port"] != 443 {
  310. t.Fatalf("port = %v, want 443", proxy["port"])
  311. }
  312. if proxy["uuid"] != client.ID {
  313. t.Fatalf("uuid = %v, want %v", proxy["uuid"], client.ID)
  314. }
  315. }
  316. func TestBuildXhttpClashOpts_FullFieldMapping(t *testing.T) {
  317. xhttp := map[string]any{
  318. "path": "/api/v1",
  319. "mode": "stream-up",
  320. "host": "example.com",
  321. "xPaddingBytes": "100-1000",
  322. "xPaddingObfsMode": true,
  323. "xPaddingKey": "mykey",
  324. "xPaddingHeader": "X-Trace-ID",
  325. "xPaddingPlacement": "queryInHeader",
  326. "xPaddingMethod": "tokenish",
  327. "uplinkHTTPMethod": "POST",
  328. "sessionIDPlacement": "query",
  329. "sessionIDKey": "sess",
  330. "sessionIDTable": "Base62",
  331. "sessionIDLength": "16-32",
  332. "seqPlacement": "header",
  333. "seqKey": "seq",
  334. "uplinkDataPlacement": "body",
  335. "uplinkDataKey": "udata",
  336. "uplinkChunkSize": "64-256",
  337. "noGRPCHeader": true,
  338. "scMaxEachPostBytes": "500000",
  339. "scMinPostsIntervalMs": "50",
  340. "xmux": map[string]any{
  341. "maxConcurrency": "16-32",
  342. "maxConnections": "4",
  343. "cMaxReuseTimes": "8",
  344. "hMaxRequestTimes": "600-900",
  345. "hMaxReusableSecs": "1800-3000",
  346. "hKeepAlivePeriod": float64(60),
  347. },
  348. "headers": map[string]any{
  349. "User-Agent": "chrome",
  350. "Host": "should-be-dropped.com",
  351. },
  352. }
  353. opts := buildXhttpClashOpts(xhttp)
  354. if opts == nil {
  355. t.Fatal("expected non-nil opts for full field mapping")
  356. }
  357. // Direct fields
  358. if opts["path"] != "/api/v1" {
  359. t.Errorf("path = %v, want /api/v1", opts["path"])
  360. }
  361. if opts["mode"] != "stream-up" {
  362. t.Errorf("mode = %v, want stream-up", opts["mode"])
  363. }
  364. if opts["host"] != "example.com" {
  365. t.Errorf("host = %v, want example.com", opts["host"])
  366. }
  367. // String fields
  368. if opts["x-padding-bytes"] != "100-1000" {
  369. t.Errorf("x-padding-bytes = %v", opts["x-padding-bytes"])
  370. }
  371. if opts["uplink-http-method"] != "POST" {
  372. t.Errorf("uplink-http-method = %v", opts["uplink-http-method"])
  373. }
  374. if opts["session-id-placement"] != "query" {
  375. t.Errorf("session-id-placement = %v", opts["session-id-placement"])
  376. }
  377. if opts["session-id-key"] != "sess" {
  378. t.Errorf("session-id-key = %v", opts["session-id-key"])
  379. }
  380. if opts["session-id-table"] != "Base62" {
  381. t.Errorf("session-id-table = %v", opts["session-id-table"])
  382. }
  383. if opts["session-id-length"] != "16-32" {
  384. t.Errorf("session-id-length = %v", opts["session-id-length"])
  385. }
  386. if opts["seq-placement"] != "header" {
  387. t.Errorf("seq-placement = %v", opts["seq-placement"])
  388. }
  389. if opts["seq-key"] != "seq" {
  390. t.Errorf("seq-key = %v", opts["seq-key"])
  391. }
  392. if opts["uplink-data-placement"] != "body" {
  393. t.Errorf("uplink-data-placement = %v", opts["uplink-data-placement"])
  394. }
  395. if opts["uplink-data-key"] != "udata" {
  396. t.Errorf("uplink-data-key = %v", opts["uplink-data-key"])
  397. }
  398. // DPI-filtered fields (non-default values should pass)
  399. if opts["sc-max-each-post-bytes"] != "500000" {
  400. t.Errorf("sc-max-each-post-bytes = %v", opts["sc-max-each-post-bytes"])
  401. }
  402. if opts["sc-min-posts-interval-ms"] != "50" {
  403. t.Errorf("sc-min-posts-interval-ms = %v", opts["sc-min-posts-interval-ms"])
  404. }
  405. // Bool fields
  406. if opts["no-grpc-header"] != true {
  407. t.Errorf("no-grpc-header = %v, want true", opts["no-grpc-header"])
  408. }
  409. if opts["x-padding-obfs-mode"] != true {
  410. t.Errorf("x-padding-obfs-mode = %v, want true", opts["x-padding-obfs-mode"])
  411. }
  412. // Padding obfs gated fields
  413. if opts["x-padding-key"] != "mykey" {
  414. t.Errorf("x-padding-key = %v", opts["x-padding-key"])
  415. }
  416. if opts["x-padding-header"] != "X-Trace-ID" {
  417. t.Errorf("x-padding-header = %v", opts["x-padding-header"])
  418. }
  419. if opts["x-padding-placement"] != "queryInHeader" {
  420. t.Errorf("x-padding-placement = %v", opts["x-padding-placement"])
  421. }
  422. if opts["x-padding-method"] != "tokenish" {
  423. t.Errorf("x-padding-method = %v", opts["x-padding-method"])
  424. }
  425. // Non-zero value fields
  426. if opts["uplink-chunk-size"] != "64-256" {
  427. t.Errorf("uplink-chunk-size = %v", opts["uplink-chunk-size"])
  428. }
  429. // Reuse-settings (xmux)
  430. reuse, ok := opts["reuse-settings"].(map[string]any)
  431. if !ok {
  432. t.Fatalf("reuse-settings missing or wrong type: %#v", opts["reuse-settings"])
  433. }
  434. if reuse["max-concurrency"] != "16-32" {
  435. t.Errorf("max-concurrency = %v", reuse["max-concurrency"])
  436. }
  437. if reuse["max-connections"] != "4" {
  438. t.Errorf("max-connections = %v", reuse["max-connections"])
  439. }
  440. if reuse["c-max-reuse-times"] != "8" {
  441. t.Errorf("c-max-reuse-times = %v", reuse["c-max-reuse-times"])
  442. }
  443. if reuse["h-max-request-times"] != "600-900" {
  444. t.Errorf("h-max-request-times = %v", reuse["h-max-request-times"])
  445. }
  446. if reuse["h-max-reusable-secs"] != "1800-3000" {
  447. t.Errorf("h-max-reusable-secs = %v", reuse["h-max-reusable-secs"])
  448. }
  449. if reuse["h-keep-alive-period"] != float64(60) {
  450. t.Errorf("h-keep-alive-period = %v, want 60", reuse["h-keep-alive-period"])
  451. }
  452. // Headers (Host should be dropped)
  453. headers, ok := opts["headers"].(map[string]any)
  454. if !ok {
  455. t.Fatalf("headers missing or wrong type: %#v", opts["headers"])
  456. }
  457. if headers["User-Agent"] != "chrome" {
  458. t.Errorf("headers[User-Agent] = %v", headers["User-Agent"])
  459. }
  460. if _, has := headers["Host"]; has {
  461. t.Error("headers should not contain Host key")
  462. }
  463. if _, has := headers["host"]; has {
  464. t.Error("headers should not contain host key (case-insensitive)")
  465. }
  466. }
  467. func TestBuildXhttpClashOpts_DPIDefaultsFiltered(t *testing.T) {
  468. xhttp := map[string]any{
  469. "path": "/",
  470. "mode": "stream-up",
  471. "scMaxEachPostBytes": "1000000",
  472. "scMinPostsIntervalMs": "30",
  473. }
  474. opts := buildXhttpClashOpts(xhttp)
  475. if opts == nil {
  476. t.Fatal("expected non-nil opts (path and mode should be present)")
  477. }
  478. if _, has := opts["sc-max-each-post-bytes"]; has {
  479. t.Error("sc-max-each-post-bytes should be filtered when value is 1000000")
  480. }
  481. if _, has := opts["sc-min-posts-interval-ms"]; has {
  482. t.Error("sc-min-posts-interval-ms should be filtered when value is 30")
  483. }
  484. }
  485. func TestBuildXhttpClashOpts_PaddingObfsGate(t *testing.T) {
  486. // Sub-test 1: obfs mode false — gated fields should not appear
  487. t.Run("ObfsModeFalse", func(t *testing.T) {
  488. xhttp := map[string]any{
  489. "path": "/",
  490. "xPaddingObfsMode": false,
  491. "xPaddingKey": "should-not-appear",
  492. }
  493. opts := buildXhttpClashOpts(xhttp)
  494. if opts == nil {
  495. t.Fatal("expected non-nil opts")
  496. }
  497. if _, has := opts["x-padding-obfs-mode"]; has {
  498. t.Error("x-padding-obfs-mode should not appear when false")
  499. }
  500. if _, has := opts["x-padding-key"]; has {
  501. t.Error("x-padding-key should not appear when obfs mode is false")
  502. }
  503. })
  504. // Sub-test 2: obfs mode absent — gated fields should not appear
  505. t.Run("ObfsModeAbsent", func(t *testing.T) {
  506. xhttp := map[string]any{
  507. "path": "/",
  508. "xPaddingKey": "should-not-appear",
  509. }
  510. opts := buildXhttpClashOpts(xhttp)
  511. if opts == nil {
  512. t.Fatal("expected non-nil opts")
  513. }
  514. if _, has := opts["x-padding-key"]; has {
  515. t.Error("x-padding-key should not appear when obfs mode is absent")
  516. }
  517. })
  518. // Sub-test 3: obfs mode true with no gated fields — only x-padding-obfs-mode appears
  519. t.Run("ObfsModeTrueNoGatedFields", func(t *testing.T) {
  520. xhttp := map[string]any{
  521. "path": "/",
  522. "xPaddingObfsMode": true,
  523. }
  524. opts := buildXhttpClashOpts(xhttp)
  525. if opts == nil {
  526. t.Fatal("expected non-nil opts")
  527. }
  528. if opts["x-padding-obfs-mode"] != true {
  529. t.Errorf("x-padding-obfs-mode = %v, want true", opts["x-padding-obfs-mode"])
  530. }
  531. if _, has := opts["x-padding-key"]; has {
  532. t.Error("x-padding-key should not appear when not set")
  533. }
  534. })
  535. }
  536. func TestBuildXhttpClashOpts_XmuxMapsToReuseSettings(t *testing.T) {
  537. // Sub-test 1: full xmux mapping
  538. t.Run("FullXmux", func(t *testing.T) {
  539. xhttp := map[string]any{
  540. "path": "/",
  541. "xmux": map[string]any{
  542. "maxConcurrency": "16-32",
  543. "maxConnections": "4",
  544. "cMaxReuseTimes": "8",
  545. "hMaxRequestTimes": "600-900",
  546. "hMaxReusableSecs": "1800-3000",
  547. "hKeepAlivePeriod": float64(60),
  548. },
  549. }
  550. opts := buildXhttpClashOpts(xhttp)
  551. if opts == nil {
  552. t.Fatal("expected non-nil opts")
  553. }
  554. reuse, ok := opts["reuse-settings"].(map[string]any)
  555. if !ok {
  556. t.Fatalf("reuse-settings missing or wrong type: %#v", opts["reuse-settings"])
  557. }
  558. if reuse["max-concurrency"] != "16-32" {
  559. t.Errorf("max-concurrency = %v", reuse["max-concurrency"])
  560. }
  561. if reuse["max-connections"] != "4" {
  562. t.Errorf("max-connections = %v", reuse["max-connections"])
  563. }
  564. if reuse["c-max-reuse-times"] != "8" {
  565. t.Errorf("c-max-reuse-times = %v", reuse["c-max-reuse-times"])
  566. }
  567. if reuse["h-max-request-times"] != "600-900" {
  568. t.Errorf("h-max-request-times = %v", reuse["h-max-request-times"])
  569. }
  570. if reuse["h-max-reusable-secs"] != "1800-3000" {
  571. t.Errorf("h-max-reusable-secs = %v", reuse["h-max-reusable-secs"])
  572. }
  573. if reuse["h-keep-alive-period"] != float64(60) {
  574. t.Errorf("h-keep-alive-period = %v, want 60", reuse["h-keep-alive-period"])
  575. }
  576. })
  577. // Sub-test 2: empty xmux map — no reuse-settings key
  578. t.Run("EmptyXmux", func(t *testing.T) {
  579. xhttp := map[string]any{
  580. "path": "/",
  581. "xmux": map[string]any{},
  582. }
  583. opts := buildXhttpClashOpts(xhttp)
  584. if opts == nil {
  585. t.Fatal("expected non-nil opts (path is present)")
  586. }
  587. if _, has := opts["reuse-settings"]; has {
  588. t.Error("reuse-settings should not appear for empty xmux")
  589. }
  590. })
  591. // Sub-test 3: hKeepAlivePeriod as int (not float64)
  592. t.Run("IntKeepAlivePeriod", func(t *testing.T) {
  593. xhttp := map[string]any{
  594. "path": "/",
  595. "xmux": map[string]any{
  596. "hKeepAlivePeriod": int(60),
  597. },
  598. }
  599. opts := buildXhttpClashOpts(xhttp)
  600. if opts == nil {
  601. t.Fatal("expected non-nil opts")
  602. }
  603. reuse, ok := opts["reuse-settings"].(map[string]any)
  604. if !ok {
  605. t.Fatalf("reuse-settings missing: %#v", opts["reuse-settings"])
  606. }
  607. if reuse["h-keep-alive-period"] != int(60) {
  608. t.Errorf("h-keep-alive-period = %v (%T), want 60 (int)", reuse["h-keep-alive-period"], reuse["h-keep-alive-period"])
  609. }
  610. })
  611. // Sub-test 4: hKeepAlivePeriod=0 should be filtered
  612. t.Run("ZeroKeepAlivePeriod", func(t *testing.T) {
  613. xhttp := map[string]any{
  614. "path": "/",
  615. "xmux": map[string]any{
  616. "hKeepAlivePeriod": float64(0),
  617. },
  618. }
  619. opts := buildXhttpClashOpts(xhttp)
  620. if opts == nil {
  621. t.Fatal("expected non-nil opts")
  622. }
  623. if _, has := opts["reuse-settings"]; has {
  624. t.Error("reuse-settings should not appear when only hKeepAlivePeriod=0")
  625. }
  626. })
  627. }
  628. func TestBuildXhttpClashOpts_ServerOnlyFieldsExcluded(t *testing.T) {
  629. xhttp := map[string]any{
  630. "path": "/",
  631. "noSSEHeader": true,
  632. "scMaxBufferedPosts": "100",
  633. "scStreamUpServerSecs": "5",
  634. "serverMaxHeaderBytes": "4096",
  635. }
  636. opts := buildXhttpClashOpts(xhttp)
  637. if opts == nil {
  638. t.Fatal("expected non-nil opts (path is present)")
  639. }
  640. if _, has := opts["no-sse-header"]; has {
  641. t.Error("noSSEHeader should not appear in Clash output (server-only)")
  642. }
  643. if _, has := opts["sc-max-buffered-posts"]; has {
  644. t.Error("scMaxBufferedPosts should not appear in Clash output (server-only)")
  645. }
  646. if _, has := opts["sc-stream-up-server-secs"]; has {
  647. t.Error("scStreamUpServerSecs should not appear in Clash output (server-only)")
  648. }
  649. if _, has := opts["server-max-header-bytes"]; has {
  650. t.Error("serverMaxHeaderBytes should not appear in Clash output (not in Mihomo)")
  651. }
  652. }
  653. func TestBuildXhttpClashOpts_NilInput(t *testing.T) {
  654. opts := buildXhttpClashOpts(nil)
  655. if opts != nil {
  656. t.Fatalf("expected nil for nil input, got %#v", opts)
  657. }
  658. }
  659. func TestBuildXhttpClashOpts_EmptyInput(t *testing.T) {
  660. opts := buildXhttpClashOpts(map[string]any{})
  661. if opts != nil {
  662. t.Fatalf("expected nil for empty input, got %#v", opts)
  663. }
  664. }
  665. func TestBuildXhttpClashOpts_HostFallbackFromHeaders(t *testing.T) {
  666. // Sub-test 1: host from headers.Host
  667. t.Run("HostFromHeaders", func(t *testing.T) {
  668. xhttp := map[string]any{
  669. "path": "/",
  670. "headers": map[string]any{"Host": "via-header.example.com"},
  671. }
  672. opts := buildXhttpClashOpts(xhttp)
  673. if opts == nil {
  674. t.Fatal("expected non-nil opts")
  675. }
  676. if opts["host"] != "via-header.example.com" {
  677. t.Errorf("host = %v, want via-header.example.com", opts["host"])
  678. }
  679. })
  680. // Sub-test 2: headers only contains Host — no headers key in output
  681. t.Run("HeadersOnlyHost", func(t *testing.T) {
  682. xhttp := map[string]any{
  683. "path": "/",
  684. "headers": map[string]any{"Host": "only-host.example.com"},
  685. }
  686. opts := buildXhttpClashOpts(xhttp)
  687. if opts == nil {
  688. t.Fatal("expected non-nil opts")
  689. }
  690. if _, has := opts["headers"]; has {
  691. t.Error("headers key should not appear when only Host is present (Host is extracted to top-level)")
  692. }
  693. })
  694. // Sub-test 3: case-insensitive Host drop
  695. t.Run("CaseInsensitiveHostDrop", func(t *testing.T) {
  696. xhttp := map[string]any{
  697. "path": "/",
  698. "host": "explicit.example.com",
  699. "headers": map[string]any{
  700. "host": "lowercase-host.example.com",
  701. "X-Custom": "value",
  702. },
  703. }
  704. opts := buildXhttpClashOpts(xhttp)
  705. if opts == nil {
  706. t.Fatal("expected non-nil opts")
  707. }
  708. if opts["host"] != "explicit.example.com" {
  709. t.Errorf("host = %v, want explicit.example.com (explicit host wins)", opts["host"])
  710. }
  711. headers, ok := opts["headers"].(map[string]any)
  712. if !ok {
  713. t.Fatal("headers should be present (X-Custom remains)")
  714. }
  715. if _, has := headers["host"]; has {
  716. t.Error("lowercase 'host' should be dropped from headers")
  717. }
  718. if headers["X-Custom"] != "value" {
  719. t.Errorf("X-Custom = %v, want value", headers["X-Custom"])
  720. }
  721. })
  722. }
  723. func TestBuildXhttpClashOpts_NoGRPCHeaderFalsey(t *testing.T) {
  724. // Sub-test 1: noGRPCHeader: false
  725. t.Run("ExplicitFalse", func(t *testing.T) {
  726. xhttp := map[string]any{
  727. "path": "/",
  728. "noGRPCHeader": false,
  729. }
  730. opts := buildXhttpClashOpts(xhttp)
  731. if opts == nil {
  732. t.Fatal("expected non-nil opts (path is present)")
  733. }
  734. if _, has := opts["no-grpc-header"]; has {
  735. t.Error("no-grpc-header should not appear when noGRPCHeader is false")
  736. }
  737. })
  738. // Sub-test 2: noGRPCHeader absent
  739. t.Run("Absent", func(t *testing.T) {
  740. xhttp := map[string]any{
  741. "path": "/",
  742. }
  743. opts := buildXhttpClashOpts(xhttp)
  744. if opts == nil {
  745. t.Fatal("expected non-nil opts")
  746. }
  747. if _, has := opts["no-grpc-header"]; has {
  748. t.Error("no-grpc-header should not appear when absent")
  749. }
  750. })
  751. }
  752. func TestBuildWireguardProxyForClash(t *testing.T) {
  753. serverPriv, serverPub, err := wgutil.GenerateWireguardKeypair()
  754. if err != nil {
  755. t.Fatalf("server keypair: %v", err)
  756. }
  757. clientPriv, _, err := wgutil.GenerateWireguardKeypair()
  758. if err != nil {
  759. t.Fatalf("client keypair: %v", err)
  760. }
  761. svc := &SubClashService{SubService: &SubService{}}
  762. inbound := &model.Inbound{
  763. Listen: "203.0.113.9",
  764. Port: 51820,
  765. Protocol: model.WireGuard,
  766. Remark: "wg",
  767. Settings: `{"secretKey":"` + serverPriv + `","mtu":1420,"dns":"1.1.1.1, 8.8.8.8"}`,
  768. }
  769. client := model.Client{
  770. Email: "user",
  771. PrivateKey: clientPriv,
  772. PreSharedKey: "psk-value",
  773. KeepAlive: 25,
  774. AllowedIPs: []string{"10.0.0.2/32", "fd00::2/128"},
  775. }
  776. proxy := svc.buildProxy(svc.SubService, inbound, client, nil, nil)
  777. if proxy == nil {
  778. t.Fatal("buildProxy returned nil for a valid wireguard client")
  779. }
  780. if proxy["type"] != "wireguard" {
  781. t.Fatalf("type = %v, want wireguard", proxy["type"])
  782. }
  783. if proxy["server"] != "203.0.113.9" {
  784. t.Fatalf("server = %v, want 203.0.113.9", proxy["server"])
  785. }
  786. if proxy["port"] != 51820 {
  787. t.Fatalf("port = %v, want 51820", proxy["port"])
  788. }
  789. if proxy["private-key"] != clientPriv {
  790. t.Fatalf("private-key = %v, want %v", proxy["private-key"], clientPriv)
  791. }
  792. if proxy["public-key"] != serverPub {
  793. t.Fatalf("public-key = %v, want %v (derived from inbound secretKey)", proxy["public-key"], serverPub)
  794. }
  795. if proxy["pre-shared-key"] != "psk-value" {
  796. t.Fatalf("pre-shared-key = %v, want psk-value", proxy["pre-shared-key"])
  797. }
  798. if proxy["persistent-keepalive"] != 25 {
  799. t.Fatalf("persistent-keepalive = %v, want 25", proxy["persistent-keepalive"])
  800. }
  801. if proxy["ip"] != "10.0.0.2" {
  802. t.Fatalf("ip = %v, want 10.0.0.2", proxy["ip"])
  803. }
  804. if proxy["ipv6"] != "fd00::2" {
  805. t.Fatalf("ipv6 = %v, want fd00::2", proxy["ipv6"])
  806. }
  807. if proxy["mtu"] != 1420 {
  808. t.Fatalf("mtu = %v, want 1420", proxy["mtu"])
  809. }
  810. if proxy["udp"] != true {
  811. t.Fatalf("udp = %v, want true", proxy["udp"])
  812. }
  813. if dns, ok := proxy["dns"].([]string); !ok || !reflect.DeepEqual(dns, []string{"1.1.1.1", "8.8.8.8"}) {
  814. t.Fatalf("dns = %v, want [1.1.1.1 8.8.8.8]", proxy["dns"])
  815. }
  816. }
  817. func TestBuildWireguardProxyForClashNoKey(t *testing.T) {
  818. svc := &SubClashService{SubService: &SubService{}}
  819. inbound := &model.Inbound{Listen: "203.0.113.9", Port: 51820, Protocol: model.WireGuard, Settings: `{}`}
  820. client := model.Client{Email: "user"}
  821. if proxy := svc.buildProxy(svc.SubService, inbound, client, nil, nil); proxy != nil {
  822. t.Fatalf("buildProxy = %v, want nil for a keyless wireguard client", proxy)
  823. }
  824. }
  825. func TestBuildAmneziaWGProxyForClash(t *testing.T) {
  826. serverPriv, serverPub, err := wgutil.GenerateWireguardKeypair()
  827. if err != nil {
  828. t.Fatalf("server keypair: %v", err)
  829. }
  830. clientPriv, _, err := wgutil.GenerateWireguardKeypair()
  831. if err != nil {
  832. t.Fatalf("client keypair: %v", err)
  833. }
  834. settings := `{"server":{"privateKey":"` + serverPriv + `","publicKey":"` + serverPub + `","mtu":1420,"primaryDns":"8.8.8.8","secondaryDns":"8.8.4.4","jc":3,"jmin":66,"jmax":150,"s1":147,"s2":146,"s3":28,"s4":27,"h1":"364198942-470015235","h2":"1041963382-1068354159","h3":"1313106728-1361756201","h4":"1801896583-1875457201","i1":"10-20","i2":"30-40"}}`
  835. svc := &SubClashService{SubService: &SubService{}}
  836. inbound := &model.Inbound{
  837. Listen: "203.0.113.7",
  838. Port: 51820,
  839. Protocol: model.AmneziaWG,
  840. Remark: "amneziawg",
  841. Settings: settings,
  842. }
  843. client := model.Client{
  844. Email: "user",
  845. PrivateKey: clientPriv,
  846. PreSharedKey: "psk-value",
  847. KeepAlive: 25,
  848. AllowedIPs: []string{"10.8.1.2/32", "fd00::2/128"},
  849. }
  850. proxy := svc.buildProxy(svc.SubService, inbound, client, nil, nil)
  851. if proxy == nil {
  852. t.Fatal("buildProxy returned nil for a valid amneziawg client")
  853. }
  854. if proxy["type"] != "wireguard" {
  855. t.Fatalf("type = %v, want wireguard", proxy["type"])
  856. }
  857. if proxy["server"] != "203.0.113.7" {
  858. t.Fatalf("server = %v, want 203.0.113.7", proxy["server"])
  859. }
  860. if proxy["port"] != 51820 {
  861. t.Fatalf("port = %v, want 51820", proxy["port"])
  862. }
  863. if proxy["private-key"] != clientPriv {
  864. t.Fatalf("private-key = %v, want %v", proxy["private-key"], clientPriv)
  865. }
  866. if proxy["public-key"] != serverPub {
  867. t.Fatalf("public-key = %v, want %v", proxy["public-key"], serverPub)
  868. }
  869. if proxy["pre-shared-key"] != "psk-value" {
  870. t.Fatalf("pre-shared-key = %v, want psk-value", proxy["pre-shared-key"])
  871. }
  872. if proxy["persistent-keepalive"] != 25 {
  873. t.Fatalf("persistent-keepalive = %v, want 25", proxy["persistent-keepalive"])
  874. }
  875. if proxy["ip"] != "10.8.1.2" {
  876. t.Fatalf("ip = %v, want 10.8.1.2", proxy["ip"])
  877. }
  878. if proxy["ipv6"] != "fd00::2" {
  879. t.Fatalf("ipv6 = %v, want fd00::2", proxy["ipv6"])
  880. }
  881. if proxy["mtu"] != 1420 {
  882. t.Fatalf("mtu = %v, want 1420", proxy["mtu"])
  883. }
  884. if proxy["udp"] != true {
  885. t.Fatalf("udp = %v, want true", proxy["udp"])
  886. }
  887. if dns, ok := proxy["dns"].([]string); !ok || !reflect.DeepEqual(dns, []string{"8.8.8.8", "8.8.4.4"}) {
  888. t.Fatalf("dns = %v, want [8.8.8.8 8.8.4.4]", proxy["dns"])
  889. }
  890. awg, ok := proxy["amnezia-wg-option"].(map[string]any)
  891. if !ok {
  892. t.Fatal("amnezia-wg-option missing")
  893. }
  894. if awg["jc"] != 3 {
  895. t.Fatalf("jc = %v, want 3", awg["jc"])
  896. }
  897. if awg["jmin"] != 66 {
  898. t.Fatalf("jmin = %v, want 66", awg["jmin"])
  899. }
  900. if awg["jmax"] != 150 {
  901. t.Fatalf("jmax = %v, want 150", awg["jmax"])
  902. }
  903. if awg["s1"] != 147 {
  904. t.Fatalf("s1 = %v, want 147", awg["s1"])
  905. }
  906. if awg["s2"] != 146 {
  907. t.Fatalf("s2 = %v, want 146", awg["s2"])
  908. }
  909. if awg["s3"] != 28 {
  910. t.Fatalf("s3 = %v, want 28", awg["s3"])
  911. }
  912. if awg["s4"] != 27 {
  913. t.Fatalf("s4 = %v, want 27", awg["s4"])
  914. }
  915. if awg["h1"] != "364198942-470015235" {
  916. t.Fatalf("h1 = %v, want 364198942-470015235", awg["h1"])
  917. }
  918. if awg["h2"] != "1041963382-1068354159" {
  919. t.Fatalf("h2 = %v, want 1041963382-1068354159", awg["h2"])
  920. }
  921. if awg["h3"] != "1313106728-1361756201" {
  922. t.Fatalf("h3 = %v, want 1313106728-1361756201", awg["h3"])
  923. }
  924. if awg["h4"] != "1801896583-1875457201" {
  925. t.Fatalf("h4 = %v, want 1801896583-1875457201", awg["h4"])
  926. }
  927. if awg["i1"] != "10-20" {
  928. t.Fatalf("i1 = %v, want 10-20", awg["i1"])
  929. }
  930. if awg["i2"] != "30-40" {
  931. t.Fatalf("i2 = %v, want 30-40", awg["i2"])
  932. }
  933. // v1.0 fields must NOT set version
  934. if _, ok := awg["version"]; ok {
  935. t.Fatalf("version should not be set for v1.0 obfuscation fields")
  936. }
  937. }
  938. func TestBuildAmneziaWGProxyForClashV3(t *testing.T) {
  939. serverPriv, serverPub, err := wgutil.GenerateWireguardKeypair()
  940. if err != nil {
  941. t.Fatalf("server keypair: %v", err)
  942. }
  943. clientPriv, _, err := wgutil.GenerateWireguardKeypair()
  944. if err != nil {
  945. t.Fatalf("client keypair: %v", err)
  946. }
  947. settings := `{"server":{"privateKey":"` + serverPriv + `","publicKey":"` + serverPub + `","mtu":1280,"primaryDns":"1.1.1.1","jc":3,"jmin":66,"jmax":150,"s1":147,"s2":146,"s3":28,"s4":27,"h1":"364198942-470015235","h2":"1041963382-1068354159","h3":"1313106728-1361756201","h4":"1801896583-1875457201","headerProtectionKey":"DmVT7JtmJM8YoHiA2Wp3xPKI5dTXFx83y2JUQkKg1p8=","contentPaddingAddition":"9-31","rekeyAfterTime":"105-125","rekeyTimeout":"3-5","rejectAfterTime":"176-239","keepaliveTimeout":"11-16","maxHandshakeAttempts":"24-41","randomTrailers":true,"disableCookies":true}}`
  948. svc := &SubClashService{SubService: &SubService{}}
  949. inbound := &model.Inbound{
  950. Listen: "203.0.113.7",
  951. Port: 51820,
  952. Protocol: model.AmneziaWG,
  953. Remark: "amneziawg",
  954. Settings: settings,
  955. }
  956. client := model.Client{
  957. Email: "user",
  958. PrivateKey: clientPriv,
  959. AllowedIPs: []string{"10.8.1.2/32"},
  960. }
  961. proxy := svc.buildProxy(svc.SubService, inbound, client, nil, nil)
  962. if proxy == nil {
  963. t.Fatal("buildProxy returned nil for a valid amneziawg v3 client")
  964. }
  965. awg, ok := proxy["amnezia-wg-option"].(map[string]any)
  966. if !ok {
  967. t.Fatal("amnezia-wg-option missing")
  968. }
  969. if awg["version"] != 3 {
  970. t.Fatalf("version = %v, want 3", awg["version"])
  971. }
  972. if awg["header-protection-key"] != "DmVT7JtmJM8YoHiA2Wp3xPKI5dTXFx83y2JUQkKg1p8=" {
  973. t.Fatalf("header-protection-key = %v", awg["header-protection-key"])
  974. }
  975. if awg["content-padding-addition"] != "9-31" {
  976. t.Fatalf("content-padding-addition = %v", awg["content-padding-addition"])
  977. }
  978. if awg["rekey-after-time"] != "105-125" {
  979. t.Fatalf("rekey-after-time = %v", awg["rekey-after-time"])
  980. }
  981. if awg["rekey-timeout"] != "3-5" {
  982. t.Fatalf("rekey-timeout = %v", awg["rekey-timeout"])
  983. }
  984. if awg["reject-after-time"] != "176-239" {
  985. t.Fatalf("reject-after-time = %v", awg["reject-after-time"])
  986. }
  987. if awg["keepalive-timeout"] != "11-16" {
  988. t.Fatalf("keepalive-timeout = %v", awg["keepalive-timeout"])
  989. }
  990. if awg["max-handshake-attempts"] != "24-41" {
  991. t.Fatalf("max-handshake-attempts = %v", awg["max-handshake-attempts"])
  992. }
  993. if awg["random-trailers"] != true {
  994. t.Fatalf("random-trailers = %v, want true", awg["random-trailers"])
  995. }
  996. if awg["disable-cookies"] != true {
  997. t.Fatalf("disable-cookies = %v, want true", awg["disable-cookies"])
  998. }
  999. }
  1000. func TestBuildAmneziaWGProxyForClashNoKey(t *testing.T) {
  1001. svc := &SubClashService{SubService: &SubService{}}
  1002. settings := `{"server":{"privateKey":"abc","publicKey":"def","jc":3,"jmin":66,"jmax":150}}`
  1003. inbound := &model.Inbound{
  1004. Listen: "203.0.113.7",
  1005. Port: 51820,
  1006. Protocol: model.AmneziaWG,
  1007. Settings: settings,
  1008. }
  1009. client := model.Client{Email: "user"}
  1010. if proxy := svc.buildAmneziaWGProxy(svc.SubService, inbound, client, nil); proxy != nil {
  1011. t.Fatalf("buildAmneziaWGProxy = %v, want nil for a keyless amneziawg client", proxy)
  1012. }
  1013. }
  1014. // TestBuildAmneziaWGProxyForClashPerInboundAddress pins the tunnel address to
  1015. // this inbound's own settings.clients[] entry, the one InstanceFromInbound
  1016. // turns into the running peer's AllowedIPs. model.Client here is what
  1017. // matchingClients hands buildProxy: the shared clients.wg_allowed_ips column,
  1018. // which for an identity attached to both wireguard and amneziawg holds the
  1019. // other protocol's address.
  1020. func TestBuildAmneziaWGProxyForClashPerInboundAddress(t *testing.T) {
  1021. serverPriv, serverPub, err := wgutil.GenerateWireguardKeypair()
  1022. if err != nil {
  1023. t.Fatalf("server keypair: %v", err)
  1024. }
  1025. clientPriv, clientPub, err := wgutil.GenerateWireguardKeypair()
  1026. if err != nil {
  1027. t.Fatalf("client keypair: %v", err)
  1028. }
  1029. settings := `{"server":{"privateKey":"` + serverPriv + `","publicKey":"` + serverPub +
  1030. `","jc":3,"jmin":66,"jmax":150},"clients":[{"email":"dual@x","publicKey":"` + clientPub +
  1031. `","allowedIPs":["10.8.1.5/32","fd00::5/128"],"enable":true}]}`
  1032. svc := &SubClashService{SubService: &SubService{}}
  1033. inbound := &model.Inbound{
  1034. Listen: "203.0.113.7",
  1035. Port: 51820,
  1036. Protocol: model.AmneziaWG,
  1037. Remark: "amneziawg",
  1038. Settings: settings,
  1039. }
  1040. client := model.Client{
  1041. Email: "dual@x",
  1042. PrivateKey: clientPriv,
  1043. AllowedIPs: []string{"10.0.0.5/32"},
  1044. }
  1045. proxy := svc.buildProxy(svc.SubService, inbound, client, nil, nil)
  1046. if proxy == nil {
  1047. t.Fatal("buildProxy returned nil for a valid amneziawg client")
  1048. }
  1049. if proxy["ip"] != "10.8.1.5" {
  1050. t.Fatalf("ip = %v, want 10.8.1.5 (this inbound's own address, not the shared column's 10.0.0.5)", proxy["ip"])
  1051. }
  1052. if proxy["ipv6"] != "fd00::5" {
  1053. t.Fatalf("ipv6 = %v, want fd00::5", proxy["ipv6"])
  1054. }
  1055. }
  1056. // TestBuildAmneziaWGProxyForClashFallsBackToClientAddress covers an inbound
  1057. // whose settings.clients[] has no entry for this email: the shared column is
  1058. // then the only address there is.
  1059. func TestBuildAmneziaWGProxyForClashFallsBackToClientAddress(t *testing.T) {
  1060. serverPriv, serverPub, err := wgutil.GenerateWireguardKeypair()
  1061. if err != nil {
  1062. t.Fatalf("server keypair: %v", err)
  1063. }
  1064. clientPriv, _, err := wgutil.GenerateWireguardKeypair()
  1065. if err != nil {
  1066. t.Fatalf("client keypair: %v", err)
  1067. }
  1068. settings := `{"server":{"privateKey":"` + serverPriv + `","publicKey":"` + serverPub +
  1069. `","jc":3,"jmin":66,"jmax":150},"clients":[{"email":"someone-else@x","allowedIPs":["10.8.1.9/32"]}]}`
  1070. svc := &SubClashService{SubService: &SubService{}}
  1071. inbound := &model.Inbound{
  1072. Listen: "203.0.113.7",
  1073. Port: 51820,
  1074. Protocol: model.AmneziaWG,
  1075. Settings: settings,
  1076. }
  1077. client := model.Client{Email: "user@x", PrivateKey: clientPriv, AllowedIPs: []string{"10.8.1.2/32"}}
  1078. proxy := svc.buildProxy(svc.SubService, inbound, client, nil, nil)
  1079. if proxy == nil {
  1080. t.Fatal("buildProxy returned nil for a valid amneziawg client")
  1081. }
  1082. if proxy["ip"] != "10.8.1.2" {
  1083. t.Fatalf("ip = %v, want 10.8.1.2", proxy["ip"])
  1084. }
  1085. }
  1086. // TestBuildAmneziaWGProxyForClashRemoteDNSResolve pins the flag mihomo gates
  1087. // its `dns` list on, and the guard that keeps a non-IP entry from turning an
  1088. // inert key into a whole-config parse abort.
  1089. func TestBuildAmneziaWGProxyForClashRemoteDNSResolve(t *testing.T) {
  1090. serverPriv, serverPub, err := wgutil.GenerateWireguardKeypair()
  1091. if err != nil {
  1092. t.Fatalf("server keypair: %v", err)
  1093. }
  1094. clientPriv, _, err := wgutil.GenerateWireguardKeypair()
  1095. if err != nil {
  1096. t.Fatalf("client keypair: %v", err)
  1097. }
  1098. build := func(t *testing.T, primary, secondary string) map[string]any {
  1099. t.Helper()
  1100. settings := `{"server":{"privateKey":"` + serverPriv + `","publicKey":"` + serverPub +
  1101. `","primaryDns":"` + primary + `","secondaryDns":"` + secondary + `"}}`
  1102. svc := &SubClashService{SubService: &SubService{}}
  1103. inbound := &model.Inbound{
  1104. Listen: "203.0.113.7",
  1105. Port: 51820,
  1106. Protocol: model.AmneziaWG,
  1107. Settings: settings,
  1108. }
  1109. client := model.Client{Email: "user", PrivateKey: clientPriv, AllowedIPs: []string{"10.8.1.2/32"}}
  1110. proxy := svc.buildProxy(svc.SubService, inbound, client, nil, nil)
  1111. if proxy == nil {
  1112. t.Fatal("buildProxy returned nil for a valid amneziawg client")
  1113. }
  1114. return proxy
  1115. }
  1116. t.Run("bare IPs", func(t *testing.T) {
  1117. proxy := build(t, "8.8.8.8", "fd00::1")
  1118. if proxy["remote-dns-resolve"] != true {
  1119. t.Fatalf("remote-dns-resolve = %v, want true: mihomo ignores dns without it", proxy["remote-dns-resolve"])
  1120. }
  1121. })
  1122. // netip.ParseAddr accepts a zone, but mihomo brackets the address into a
  1123. // udp:// URL whose url.Parse then rejects "%eth0" as a bad escape.
  1124. t.Run("zoned IPv6", func(t *testing.T) {
  1125. proxy := build(t, "8.8.8.8", "fe80::1%eth0")
  1126. if _, ok := proxy["remote-dns-resolve"]; ok {
  1127. t.Fatalf("remote-dns-resolve must stay unset for a zoned address, got %v", proxy["remote-dns-resolve"])
  1128. }
  1129. })
  1130. t.Run("non-IP entry", func(t *testing.T) {
  1131. proxy := build(t, "8.8.8.8", "dns.example.com")
  1132. if dns, ok := proxy["dns"].([]string); !ok || !reflect.DeepEqual(dns, []string{"8.8.8.8", "dns.example.com"}) {
  1133. t.Fatalf("dns = %v, want both entries kept", proxy["dns"])
  1134. }
  1135. if _, ok := proxy["remote-dns-resolve"]; ok {
  1136. t.Fatalf("remote-dns-resolve must stay unset when an entry is not a bare IP, got %v", proxy["remote-dns-resolve"])
  1137. }
  1138. })
  1139. t.Run("no DNS", func(t *testing.T) {
  1140. proxy := build(t, "", "")
  1141. if _, ok := proxy["remote-dns-resolve"]; ok {
  1142. t.Fatal("remote-dns-resolve must stay unset when there is no dns list")
  1143. }
  1144. })
  1145. }
  1146. // TestGetProxies_CustomIPv6ShareAddrIsUnbracketed pins that a Clash "server" is a
  1147. // bare host: the custom share address stores IPv6 literals bracketed, and mihomo
  1148. // rejects "[2001:db8::1]" there.
  1149. func TestGetProxies_CustomIPv6ShareAddrIsUnbracketed(t *testing.T) {
  1150. svc := &SubClashService{SubService: &SubService{}}
  1151. inbound := &model.Inbound{
  1152. Protocol: model.VLESS,
  1153. Port: 443,
  1154. Remark: "r",
  1155. Settings: `{"encryption":"none"}`,
  1156. StreamSettings: `{"network":"tcp","security":"none"}`,
  1157. ShareAddrStrategy: "custom",
  1158. ShareAddr: "[2001:db8::1]",
  1159. }
  1160. client := model.Client{ID: "11111111-2222-4333-8444-555555555555", Email: "[email protected]"}
  1161. proxies := svc.getProxies(svc.SubService, inbound, client, "panel.example.com")
  1162. if len(proxies) != 1 {
  1163. t.Fatalf("getProxies returned %d proxies, want 1", len(proxies))
  1164. }
  1165. if got := proxies[0]["server"]; got != "2001:db8::1" {
  1166. t.Fatalf("server = %v, want 2001:db8::1", got)
  1167. }
  1168. }
  1169. // TestBuildAmneziaWGProxyForClashEffectiveMTU pins the Clash mtu to the same
  1170. // amneziawg.EffectiveMTU every other emitter uses -- the running interface
  1171. // (amneziawgnet), the vpn:// .conf and both TS builders. Omitting the key
  1172. // leaves mihomo on its own 1408 default, above the tunnel once s4 > 12.
  1173. func TestBuildAmneziaWGProxyForClashEffectiveMTU(t *testing.T) {
  1174. serverPriv, serverPub, err := wgutil.GenerateWireguardKeypair()
  1175. if err != nil {
  1176. t.Fatalf("server keypair: %v", err)
  1177. }
  1178. clientPriv, _, err := wgutil.GenerateWireguardKeypair()
  1179. if err != nil {
  1180. t.Fatalf("client keypair: %v", err)
  1181. }
  1182. build := func(t *testing.T, mtu, s4 int) map[string]any {
  1183. t.Helper()
  1184. settings := fmt.Sprintf(
  1185. `{"server":{"privateKey":%q,"publicKey":%q,"mtu":%d,"s4":%d}}`,
  1186. serverPriv, serverPub, mtu, s4)
  1187. svc := &SubClashService{SubService: &SubService{}}
  1188. inbound := &model.Inbound{
  1189. Listen: "203.0.113.7",
  1190. Port: 51820,
  1191. Protocol: model.AmneziaWG,
  1192. Settings: settings,
  1193. }
  1194. client := model.Client{Email: "user", PrivateKey: clientPriv, AllowedIPs: []string{"10.8.1.2/32"}}
  1195. proxy := svc.buildProxy(svc.SubService, inbound, client, nil, nil)
  1196. if proxy == nil {
  1197. t.Fatal("buildProxy returned nil for a valid amneziawg client")
  1198. }
  1199. return proxy
  1200. }
  1201. t.Run("unset MTU falls back to 1420-s4", func(t *testing.T) {
  1202. proxy := build(t, 0, 27)
  1203. want := amneziawg.EffectiveMTU(0, 27)
  1204. if proxy["mtu"] != want {
  1205. t.Fatalf("mtu = %v, want %d (amneziawg.EffectiveMTU)", proxy["mtu"], want)
  1206. }
  1207. })
  1208. t.Run("explicit MTU wins", func(t *testing.T) {
  1209. proxy := build(t, 1380, 27)
  1210. if proxy["mtu"] != 1380 {
  1211. t.Fatalf("mtu = %v, want 1380", proxy["mtu"])
  1212. }
  1213. })
  1214. }