outbound_helpers_test.go 12 KB

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