outbound_helpers_test.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320
  1. package link
  2. import (
  3. "encoding/base64"
  4. "net/url"
  5. "reflect"
  6. "slices"
  7. "testing"
  8. )
  9. func TestDefaultPort(t *testing.T) {
  10. cases := []struct {
  11. in string
  12. def int
  13. want int
  14. }{
  15. {"", 443, 443},
  16. {"8080", 443, 8080},
  17. {"0", 443, 443}, // non-positive falls back
  18. {"-1", 443, 443}, // negative falls back
  19. {"abc", 443, 443}, // unparseable falls back
  20. {"65535", 443, 65535},
  21. }
  22. for _, c := range cases {
  23. if got := defaultPort(c.in, c.def); got != c.want {
  24. t.Errorf("defaultPort(%q,%d) = %d, want %d", c.in, c.def, got, c.want)
  25. }
  26. }
  27. }
  28. func TestFirstNonEmptyAndParam(t *testing.T) {
  29. if got := firstNonEmpty("a", "b"); got != "a" {
  30. t.Errorf("firstNonEmpty(a,b) = %q, want a", got)
  31. }
  32. if got := firstNonEmpty("", "b"); got != "b" {
  33. t.Errorf("firstNonEmpty(,b) = %q, want b", got)
  34. }
  35. p := url.Values{"x": {""}, "y": {"hit"}, "z": {"z"}}
  36. if got := firstParam(p, "x", "y", "z"); got != "hit" {
  37. t.Errorf("firstParam = %q, want hit (first non-empty)", got)
  38. }
  39. if got := firstParam(p, "x"); got != "" {
  40. t.Errorf("firstParam(only empty) = %q, want empty", got)
  41. }
  42. }
  43. func TestSplitComma(t *testing.T) {
  44. if got := splitComma(""); got != nil {
  45. t.Errorf("splitComma(empty) = %v, want nil", got)
  46. }
  47. if got := splitComma("a, ,b ,, c"); !reflect.DeepEqual(got, []string{"a", "b", "c"}) {
  48. t.Errorf("splitComma trim/skip = %v, want [a b c]", got)
  49. }
  50. if got := splitCommaOrDefault("", []string{"d"}); !reflect.DeepEqual(got, []string{"d"}) {
  51. t.Errorf("splitCommaOrDefault(empty) = %v, want [d]", got)
  52. }
  53. if got := splitCommaOrDefault("x,y", []string{"d"}); !reflect.DeepEqual(got, []string{"x", "y"}) {
  54. t.Errorf("splitCommaOrDefault(x,y) = %v, want [x y]", got)
  55. }
  56. }
  57. func TestPadAndBase64DecodeFlexible(t *testing.T) {
  58. if got := padBase64("abc"); got != "abc=" {
  59. t.Errorf("padBase64(abc) = %q, want abc=", got)
  60. }
  61. if got := padBase64("abcd"); got != "abcd" {
  62. t.Errorf("padBase64(abcd) = %q, want unchanged", got)
  63. }
  64. std := base64.StdEncoding.EncodeToString([]byte("aes-256-gcm:secret"))
  65. if got, err := base64DecodeFlexible(std); err != nil || got != "aes-256-gcm:secret" {
  66. t.Errorf("base64DecodeFlexible(std) = (%q,%v), want (aes-256-gcm:secret,nil)", got, err)
  67. }
  68. rawURL := base64.RawURLEncoding.EncodeToString([]byte("m:p"))
  69. if got, err := base64DecodeFlexible(rawURL); err != nil || got != "m:p" {
  70. t.Errorf("base64DecodeFlexible(rawurl) = (%q,%v), want (m:p,nil)", got, err)
  71. }
  72. if _, err := base64DecodeFlexible("!!!not!!!"); err == nil {
  73. t.Error("base64DecodeFlexible(garbage) should error")
  74. }
  75. }
  76. func TestDecodeHash(t *testing.T) {
  77. if got := decodeHash(""); got != "" {
  78. t.Errorf("decodeHash(empty) = %q, want empty", got)
  79. }
  80. if got := decodeHash("a%20b"); got != "a b" {
  81. t.Errorf("decodeHash(a%%20b) = %q, want 'a b'", got)
  82. }
  83. if got := decodeHash("plain"); got != "plain" {
  84. t.Errorf("decodeHash(plain) = %q, want plain", got)
  85. }
  86. }
  87. func TestCanonicalQuery_SortsKeys(t *testing.T) {
  88. // unsorted input must come out key-sorted for a stable identity
  89. got := canonicalQuery(url.Values{"c": {"3"}, "a": {"1"}, "b": {"2"}})
  90. if got != "a=1&b=2&c=3" {
  91. t.Fatalf("canonicalQuery = %q, want a=1&b=2&c=3", got)
  92. }
  93. }
  94. // stream navigates res.Outbound["streamSettings"][key] as a map.
  95. func streamSub(t *testing.T, res *ParseResult, key string) map[string]any {
  96. t.Helper()
  97. ss, _ := res.Outbound["streamSettings"].(map[string]any)
  98. m, ok := ss[key].(map[string]any)
  99. if !ok {
  100. t.Fatalf("streamSettings.%s missing/not a map: %#v", key, ss)
  101. }
  102. return m
  103. }
  104. func TestParse_RealitySecurityMapped(t *testing.T) {
  105. res, err := ParseLink("vless://[email protected]:443?type=tcp&security=reality&pbk=PBK&sid=SID&sni=SNI&fp=firefox&spx=%2Fspx&pqv=PQV")
  106. if err != nil {
  107. t.Fatalf("parse: %v", err)
  108. }
  109. re := streamSub(t, res, "realitySettings")
  110. for k, want := range map[string]string{"publicKey": "PBK", "shortId": "SID", "serverName": "SNI", "fingerprint": "firefox", "spiderX": "/spx", "mldsa65Verify": "PQV"} {
  111. if re[k] != want {
  112. t.Errorf("realitySettings[%q] = %v, want %q", k, re[k], want)
  113. }
  114. }
  115. }
  116. func TestParse_TLSSecurityMapped(t *testing.T) {
  117. res, err := ParseLink("trojan://[email protected]:443?type=tcp&security=tls&sni=SNI&fp=chrome&alpn=h2,http/1.1&ech=ECH&vcn=VCN&pcs=PCS")
  118. if err != nil {
  119. t.Fatalf("parse: %v", err)
  120. }
  121. tls := streamSub(t, res, "tlsSettings")
  122. if tls["serverName"] != "SNI" || tls["fingerprint"] != "chrome" || tls["echConfigList"] != "ECH" || tls["verifyPeerCertByName"] != "VCN" || tls["pinnedPeerCertSha256"] != "PCS" {
  123. t.Errorf("tlsSettings fields = %#v", tls)
  124. }
  125. if alpn, _ := tls["alpn"].([]string); !reflect.DeepEqual(alpn, []string{"h2", "http/1.1"}) {
  126. t.Errorf("alpn = %#v, want [h2 http/1.1]", tls["alpn"])
  127. }
  128. }
  129. func TestParse_WSAndGRPCTransport(t *testing.T) {
  130. ws, err := ParseLink("vless://[email protected]:443?type=ws&host=H&path=%2Fwspath")
  131. if err != nil {
  132. t.Fatalf("parse ws: %v", err)
  133. }
  134. wss := streamSub(t, ws, "wsSettings")
  135. if wss["host"] != "H" || wss["path"] != "/wspath" {
  136. t.Errorf("wsSettings = %#v, want host=H path=/wspath", wss)
  137. }
  138. grpc, err := ParseLink("vless://[email protected]:443?type=grpc&serviceName=svc&authority=auth&mode=multi")
  139. if err != nil {
  140. t.Fatalf("parse grpc: %v", err)
  141. }
  142. gs := streamSub(t, grpc, "grpcSettings")
  143. if gs["serviceName"] != "svc" || gs["authority"] != "auth" || gs["multiMode"] != true {
  144. t.Errorf("grpcSettings = %#v, want serviceName=svc authority=auth multiMode=true", gs)
  145. }
  146. }
  147. func TestParse_XhttpExtraAndSnakeCaseFields(t *testing.T) {
  148. q := url.Values{}
  149. q.Set("type", "xhttp")
  150. q.Set("encryption", "none")
  151. q.Set("security", "none")
  152. q.Set("mode", "auto")
  153. q.Set("x_padding_bytes", "1-50")
  154. q.Set("extra", `{"mode":"auto","xPaddingBytes":"1-50","scMaxEachPostBytes":"1000000"}`)
  155. res, err := ParseLink("vless://[email protected]:443?" + q.Encode() + "#r")
  156. if err != nil {
  157. t.Fatalf("parse: %v", err)
  158. }
  159. xh := streamSub(t, res, "xhttpSettings")
  160. if xh["xPaddingBytes"] != "1-50" {
  161. t.Errorf("xPaddingBytes = %v, want 1-50 (dropped from the snake_case/extra payload the emitter writes)", xh["xPaddingBytes"])
  162. }
  163. if xh["scMaxEachPostBytes"] != "1000000" {
  164. t.Errorf("scMaxEachPostBytes = %v, want 1000000 (dropped from the extra blob)", xh["scMaxEachPostBytes"])
  165. }
  166. }
  167. func TestParse_VmessWSPathWithoutHostKey(t *testing.T) {
  168. inner := `{"v":"2","add":"h","port":443,"id":"11111111-2222-4333-8444-555555555555","net":"ws","path":"/api","tls":"tls"}`
  169. link := "vmess://" + base64.StdEncoding.EncodeToString([]byte(inner))
  170. res, err := ParseLink(link)
  171. if err != nil {
  172. t.Fatalf("parse: %v", err)
  173. }
  174. wss := streamSub(t, res, "wsSettings")
  175. if wss["path"] != "/api" {
  176. t.Errorf("wsSettings path = %v, want /api (dropped when host key absent)", wss["path"])
  177. }
  178. }
  179. func TestParse_Hysteria2VerifyPeerCertByName(t *testing.T) {
  180. res, err := ParseLink("hysteria2://[email protected]:443?security=tls&sni=decoy.com&vcn=real-cert.com#r")
  181. if err != nil {
  182. t.Fatalf("parse: %v", err)
  183. }
  184. tls := streamSub(t, res, "tlsSettings")
  185. if tls["verifyPeerCertByName"] != "real-cert.com" {
  186. t.Errorf("verifyPeerCertByName = %v, want real-cert.com (vcn param ignored)", tls["verifyPeerCertByName"])
  187. }
  188. }
  189. func TestParse_TCPHTTPHeader(t *testing.T) {
  190. res, err := ParseLink("vless://[email protected]:443?type=tcp&headerType=http&host=ex.com&path=%2F")
  191. if err != nil {
  192. t.Fatalf("parse: %v", err)
  193. }
  194. tcp := streamSub(t, res, "tcpSettings")
  195. header, _ := tcp["header"].(map[string]any)
  196. if header["type"] != "http" {
  197. t.Errorf("tcp header type = %v, want http", header["type"])
  198. }
  199. }
  200. func TestParseVless_CoreFields(t *testing.T) {
  201. res, err := ParseLink("vless://[email protected]:8443?type=tcp&security=none&flow=xtls-rprx-vision#tag1")
  202. if err != nil {
  203. t.Fatalf("parse: %v", err)
  204. }
  205. st, _ := res.Outbound["settings"].(map[string]any)
  206. if st["address"] != "9.9.9.9" || st["port"] != 8443 || st["id"] != "the-uuid" || st["flow"] != "xtls-rprx-vision" {
  207. t.Errorf("vless settings = %#v", st)
  208. }
  209. }
  210. func TestParseTrojanAndSS_CoreFields(t *testing.T) {
  211. tr, err := ParseLink("trojan://[email protected]:443?type=tcp&security=tls#tj")
  212. if err != nil {
  213. t.Fatalf("parse trojan: %v", err)
  214. }
  215. srv := tr.Outbound["settings"].(map[string]any)["servers"].([]any)[0].(map[string]any)
  216. if srv["address"] != "t.com" || srv["port"] != 443 || srv["password"] != "secret" {
  217. t.Errorf("trojan server = %#v", srv)
  218. }
  219. ssLink := "ss://" + base64.StdEncoding.EncodeToString([]byte("aes-256-gcm:sspass")) + "@s.com:8388#ss1"
  220. ss, err := ParseLink(ssLink)
  221. if err != nil {
  222. t.Fatalf("parse ss: %v", err)
  223. }
  224. ssrv := ss.Outbound["settings"].(map[string]any)["servers"].([]any)[0].(map[string]any)
  225. if ssrv["address"] != "s.com" || ssrv["port"] != 8388 || ssrv["password"] != "sspass" || ssrv["method"] != "aes-256-gcm" {
  226. t.Errorf("ss server = %#v", ssrv)
  227. }
  228. }
  229. type mkcpMask struct{ header, value string }
  230. func mkcpLegacyMasks(t *testing.T, res *ParseResult) []mkcpMask {
  231. t.Helper()
  232. var out []mkcpMask
  233. for _, raw := range finalmaskUDP(t, res) {
  234. mask, _ := raw.(map[string]any)
  235. if mask["type"] != "mkcp-legacy" {
  236. t.Fatalf("unexpected udp mask %#v", mask)
  237. }
  238. settings, _ := mask["settings"].(map[string]any)
  239. header, _ := settings["header"].(string)
  240. value, _ := settings["value"].(string)
  241. out = append(out, mkcpMask{header, value})
  242. }
  243. return out
  244. }
  245. func TestParse_KcpShareParams(t *testing.T) {
  246. // The emitter flattens one mkcp-legacy mask per field into headerType/seed; a merged
  247. // mask drops the seed in xray-core (MkcpLegacy.Build), so import rebuilds them separately.
  248. cases := []struct {
  249. name string
  250. link string
  251. wantMTU int
  252. wantTTI int
  253. wantMasks []mkcpMask
  254. }{
  255. {
  256. name: "vless header and seed become two masks, seed first",
  257. link: "vless://[email protected]:443?type=kcp&headerType=wechat-video&seed=secret-seed&mtu=1400&tti=50&security=none#kcp1",
  258. wantMTU: 1400,
  259. wantTTI: 50,
  260. wantMasks: []mkcpMask{{"", "secret-seed"}, {"wechat", ""}},
  261. },
  262. {
  263. name: "trojan header only adds no seed mask",
  264. link: "trojan://[email protected]:443?type=kcp&headerType=srtp&security=none#kcp-tj",
  265. wantMTU: 1350,
  266. wantTTI: 20,
  267. wantMasks: []mkcpMask{{"srtp", ""}},
  268. },
  269. {
  270. name: "seed only adds no header mask",
  271. link: "vless://[email protected]:443?type=kcp&headerType=none&seed=abc123&security=none",
  272. wantMTU: 1350,
  273. wantTTI: 20,
  274. wantMasks: []mkcpMask{{"", "abc123"}},
  275. },
  276. {
  277. name: "mtu/tti outside KCPConfig.Build bounds keep the defaults",
  278. link: "vless://[email protected]:443?type=kcp&mtu=10&tti=5000&security=none",
  279. wantMTU: 1350,
  280. wantTTI: 20,
  281. },
  282. }
  283. for _, c := range cases {
  284. t.Run(c.name, func(t *testing.T) {
  285. res, err := ParseLink(c.link)
  286. if err != nil {
  287. t.Fatalf("parse: %v", err)
  288. }
  289. kcp := streamSub(t, res, "kcpSettings")
  290. if kcp["mtu"] != c.wantMTU || kcp["tti"] != c.wantTTI {
  291. t.Fatalf("kcpSettings mtu/tti = %v/%v, want %d/%d", kcp["mtu"], kcp["tti"], c.wantMTU, c.wantTTI)
  292. }
  293. if got := mkcpLegacyMasks(t, res); !slices.Equal(got, c.wantMasks) {
  294. t.Fatalf("mkcp-legacy masks = %v, want %v", got, c.wantMasks)
  295. }
  296. })
  297. }
  298. }