1
0

subService_test.go 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980
  1. package sub
  2. import (
  3. "encoding/base64"
  4. "encoding/json"
  5. "strings"
  6. "testing"
  7. "github.com/mhsanaei/3x-ui/v3/database/model"
  8. )
  9. func TestSubscriptionExpiryFromClient(t *testing.T) {
  10. const now = int64(1_700_000_000_000)
  11. const oneDayMs = int64(86_400_000)
  12. if got := subscriptionExpiryFromClient(now, 0); got != 0 {
  13. t.Fatalf("zero expiry should stay zero, got %d", got)
  14. }
  15. if got := subscriptionExpiryFromClient(now, 1_700_000_000_000); got != 1_700_000_000_000 {
  16. t.Fatalf("positive expiry should pass through, got %d", got)
  17. }
  18. if got := subscriptionExpiryFromClient(now, -oneDayMs); got != now+oneDayMs {
  19. t.Fatalf("delayed-start expiry should be now+|value|, got %d, want %d", got, now+oneDayMs)
  20. }
  21. if a, b := subscriptionExpiryFromClient(now, -oneDayMs), subscriptionExpiryFromClient(now, -oneDayMs); a != b {
  22. t.Fatalf("same now+value should be deterministic across calls, got %d vs %d (#4545 review)", a, b)
  23. }
  24. }
  25. func TestFindClientIndex(t *testing.T) {
  26. clients := []model.Client{
  27. {Email: "[email protected]"},
  28. {Email: "[email protected]"},
  29. {Email: "[email protected]"},
  30. }
  31. if got := findClientIndex(clients, "[email protected]"); got != 1 {
  32. t.Fatalf("findClientIndex middle = %d, want 1", got)
  33. }
  34. if got := findClientIndex(clients, "[email protected]"); got != 0 {
  35. t.Fatalf("findClientIndex first = %d, want 0", got)
  36. }
  37. if got := findClientIndex(clients, "[email protected]"); got != -1 {
  38. t.Fatalf("findClientIndex missing = %d, want -1", got)
  39. }
  40. if got := findClientIndex(nil, "x"); got != -1 {
  41. t.Fatalf("findClientIndex on nil slice = %d, want -1", got)
  42. }
  43. }
  44. func TestIsRoutableHost(t *testing.T) {
  45. routable := []string{"example.com", "sub.example.com", "10.0.0.1", "192.168.1.5", "1.2.3.4", "2001:db8::1"}
  46. for _, v := range routable {
  47. if !isRoutableHost(v) {
  48. t.Fatalf("isRoutableHost(%q) = false, want true", v)
  49. }
  50. }
  51. notRoutable := []string{"", "0.0.0.0", "::", "::0", "127.0.0.1", "127.0.0.2", "::1", "[::1]"}
  52. for _, v := range notRoutable {
  53. if isRoutableHost(v) {
  54. t.Fatalf("isRoutableHost(%q) = true, want false", v)
  55. }
  56. }
  57. }
  58. func TestResolveInboundAddress(t *testing.T) {
  59. const reqHost = "sub.example.com"
  60. // A routable bind Listen (a real IP or hostname the operator set as the
  61. // inbound's advertised endpoint) becomes the link's connect host.
  62. t.Run("routable listen is advertised as the link host", func(t *testing.T) {
  63. s := &SubService{address: reqHost}
  64. for _, listen := range []string{"1.2.3.4", "10.0.0.5", "192.168.1.10", "203.0.113.7", "vpn.example.com"} {
  65. ib := &model.Inbound{Listen: listen}
  66. if got := s.resolveInboundAddress(ib); got != listen {
  67. t.Fatalf("listen %q: address = %q, want %q (advertised listen)", listen, got, listen)
  68. }
  69. }
  70. })
  71. // A loopback/wildcard bind or a unix-domain-socket listen is a
  72. // server-side detail and must never leak into the link host.
  73. t.Run("non-routable listen falls back to subscriber host", func(t *testing.T) {
  74. s := &SubService{address: reqHost}
  75. for _, listen := range []string{"", "0.0.0.0", "::", "::0", "127.0.0.1", "::1", "@fallback", "/run/x.sock"} {
  76. ib := &model.Inbound{Listen: listen}
  77. if got := s.resolveInboundAddress(ib); got != reqHost {
  78. t.Fatalf("listen %q: address = %q, want %q (subscriber host, not bind detail)", listen, got, reqHost)
  79. }
  80. }
  81. })
  82. t.Run("node-managed inbound uses the node address", func(t *testing.T) {
  83. id := 7
  84. s := &SubService{
  85. address: reqHost,
  86. nodesByID: map[int]*model.Node{7: {Id: 7, Address: "node7.example.com"}},
  87. }
  88. ib := &model.Inbound{NodeID: &id, Listen: "1.2.3.4"}
  89. if got := s.resolveInboundAddress(ib); got != "node7.example.com" {
  90. t.Fatalf("node-managed address = %q, want node7.example.com", got)
  91. }
  92. })
  93. t.Run("node id with no known node falls back to subscriber host", func(t *testing.T) {
  94. id := 9
  95. s := &SubService{address: reqHost, nodesByID: map[int]*model.Node{}}
  96. ib := &model.Inbound{NodeID: &id, Listen: "0.0.0.0"}
  97. if got := s.resolveInboundAddress(ib); got != reqHost {
  98. t.Fatalf("unknown-node address = %q, want subscriber host %q", got, reqHost)
  99. }
  100. })
  101. }
  102. func TestUnmarshalStreamSettings(t *testing.T) {
  103. got := unmarshalStreamSettings(`{"network":"ws","wsSettings":{"path":"/api"}}`)
  104. if got["network"] != "ws" {
  105. t.Fatalf("network = %v, want ws", got["network"])
  106. }
  107. ws, ok := got["wsSettings"].(map[string]any)
  108. if !ok || ws["path"] != "/api" {
  109. t.Fatalf("wsSettings = %v, want map with path=/api", got["wsSettings"])
  110. }
  111. }
  112. func TestUnmarshalStreamSettings_InvalidJSON(t *testing.T) {
  113. if got := unmarshalStreamSettings("not json"); got != nil {
  114. t.Fatalf("invalid JSON should produce nil map, got %#v", got)
  115. }
  116. }
  117. func TestSearchHost_StringValue(t *testing.T) {
  118. headers := map[string]any{"Host": "example.com"}
  119. if got := searchHost(headers); got != "example.com" {
  120. t.Fatalf("searchHost = %q, want example.com", got)
  121. }
  122. }
  123. func TestSearchHost_CaseInsensitiveKey(t *testing.T) {
  124. headers := map[string]any{"host": "example.com"}
  125. if got := searchHost(headers); got != "example.com" {
  126. t.Fatalf("searchHost = %q, want example.com", got)
  127. }
  128. headers2 := map[string]any{"HOST": "example.com"}
  129. if got := searchHost(headers2); got != "example.com" {
  130. t.Fatalf("searchHost uppercase = %q, want example.com", got)
  131. }
  132. }
  133. func TestSearchHost_ArrayValue(t *testing.T) {
  134. headers := map[string]any{"Host": []any{"first.example.com", "second.example.com"}}
  135. if got := searchHost(headers); got != "first.example.com" {
  136. t.Fatalf("searchHost array = %q, want first.example.com", got)
  137. }
  138. }
  139. func TestSearchHost_EmptyArray(t *testing.T) {
  140. headers := map[string]any{"Host": []any{}}
  141. if got := searchHost(headers); got != "" {
  142. t.Fatalf("searchHost empty array = %q, want empty", got)
  143. }
  144. }
  145. func TestSearchHost_NoHostKey(t *testing.T) {
  146. headers := map[string]any{"X-Other": "value"}
  147. if got := searchHost(headers); got != "" {
  148. t.Fatalf("searchHost no host = %q, want empty", got)
  149. }
  150. }
  151. func TestSearchHost_NotAMap(t *testing.T) {
  152. if got := searchHost("not a map"); got != "" {
  153. t.Fatalf("searchHost non-map = %q, want empty", got)
  154. }
  155. if got := searchHost(nil); got != "" {
  156. t.Fatalf("searchHost nil = %q, want empty", got)
  157. }
  158. }
  159. func TestSearchKey_FoundAtTopLevel(t *testing.T) {
  160. data := map[string]any{"foo": 42, "bar": "x"}
  161. got, ok := searchKey(data, "foo")
  162. if !ok {
  163. t.Fatal("expected to find foo")
  164. }
  165. if got != 42 {
  166. t.Fatalf("got %v, want 42", got)
  167. }
  168. }
  169. func TestSearchKey_FoundInNested(t *testing.T) {
  170. data := map[string]any{
  171. "outer": map[string]any{
  172. "inner": map[string]any{
  173. "target": "hit",
  174. },
  175. },
  176. }
  177. got, ok := searchKey(data, "target")
  178. if !ok {
  179. t.Fatal("expected to find target in nested map")
  180. }
  181. if got != "hit" {
  182. t.Fatalf("got %v, want hit", got)
  183. }
  184. }
  185. func TestSearchKey_FoundInsideArray(t *testing.T) {
  186. data := map[string]any{
  187. "list": []any{
  188. map[string]any{"other": 1},
  189. map[string]any{"needle": "found"},
  190. },
  191. }
  192. got, ok := searchKey(data, "needle")
  193. if !ok {
  194. t.Fatal("expected to find needle in array element")
  195. }
  196. if got != "found" {
  197. t.Fatalf("got %v, want found", got)
  198. }
  199. }
  200. func TestSearchKey_NotFound(t *testing.T) {
  201. data := map[string]any{"foo": "bar"}
  202. if _, ok := searchKey(data, "missing"); ok {
  203. t.Fatal("expected ok=false for missing key")
  204. }
  205. }
  206. func TestSearchKey_OnScalar(t *testing.T) {
  207. if _, ok := searchKey(42, "anything"); ok {
  208. t.Fatal("expected ok=false searching on a scalar")
  209. }
  210. }
  211. func TestBuildXhttpExtra_IncludesClientSideFieldsWhenPresent(t *testing.T) {
  212. extra := buildXhttpExtra(map[string]any{
  213. "path": "/xhttp",
  214. "host": "example.com",
  215. "mode": "packet-up",
  216. "xPaddingBytes": "100-1000",
  217. "uplinkHTTPMethod": "GET",
  218. "uplinkChunkSize": float64(4096),
  219. "noGRPCHeader": true,
  220. "scMinPostsIntervalMs": "20-40",
  221. "xmux": map[string]any{
  222. "maxConcurrency": "16-32",
  223. "hMaxRequestTimes": "600-900",
  224. "hMaxReusableSecs": "1800-3000",
  225. "hKeepAlivePeriod": float64(15),
  226. },
  227. "downloadSettings": map[string]any{
  228. "network": "xhttp",
  229. },
  230. "headers": map[string]any{
  231. "Host": "ignored.example.com",
  232. "X-Forwarded": "1",
  233. "X-Test-Empty": "",
  234. },
  235. })
  236. if extra["path"] != nil || extra["host"] != nil {
  237. t.Fatalf("path/host should stay top-level, got extra %#v", extra)
  238. }
  239. for _, key := range []string{
  240. "xPaddingBytes",
  241. "uplinkHTTPMethod",
  242. "uplinkChunkSize",
  243. "noGRPCHeader",
  244. "scMinPostsIntervalMs",
  245. "xmux",
  246. "downloadSettings",
  247. } {
  248. if _, ok := extra[key]; !ok {
  249. t.Fatalf("extra missing %q: %#v", key, extra)
  250. }
  251. }
  252. if _, ok := extra["mode"]; ok {
  253. t.Fatalf("mode should stay as a top-level query parameter, got extra %#v", extra)
  254. }
  255. headers, ok := extra["headers"].(map[string]any)
  256. if !ok {
  257. t.Fatalf("headers = %#v, want map", extra["headers"])
  258. }
  259. if _, ok := headers["Host"]; ok {
  260. t.Fatalf("headers should not include Host: %#v", headers)
  261. }
  262. if headers["X-Forwarded"] != "1" {
  263. t.Fatalf("headers[X-Forwarded] = %#v, want 1", headers["X-Forwarded"])
  264. }
  265. }
  266. func TestBuildXhttpExtra_LeavesDefaultClientSideFieldsOut(t *testing.T) {
  267. extra := buildXhttpExtra(map[string]any{
  268. "uplinkHTTPMethod": "",
  269. "uplinkChunkSize": float64(0),
  270. "noGRPCHeader": false,
  271. "xmux": map[string]any{},
  272. "downloadSettings": map[string]any{},
  273. })
  274. if extra != nil {
  275. t.Fatalf("default-only xhttp extra = %#v, want nil", extra)
  276. }
  277. }
  278. func TestCloneStringMap(t *testing.T) {
  279. src := map[string]string{"a": "1", "b": "2"}
  280. dst := cloneStringMap(src)
  281. if len(dst) != len(src) {
  282. t.Fatalf("clone length = %d, want %d", len(dst), len(src))
  283. }
  284. for k, v := range src {
  285. if dst[k] != v {
  286. t.Fatalf("clone[%q] = %q, want %q", k, dst[k], v)
  287. }
  288. }
  289. dst["a"] = "changed"
  290. if src["a"] == "changed" {
  291. t.Fatal("modifying clone leaked into source")
  292. }
  293. }
  294. func TestCloneStringMap_Empty(t *testing.T) {
  295. dst := cloneStringMap(map[string]string{})
  296. if dst == nil {
  297. t.Fatal("clone of empty map should not be nil")
  298. }
  299. if len(dst) != 0 {
  300. t.Fatalf("clone of empty map should be empty, got %v", dst)
  301. }
  302. }
  303. func TestGetHostFromXFH_HostOnly(t *testing.T) {
  304. got, err := getHostFromXFH("example.com")
  305. if err != nil {
  306. t.Fatalf("unexpected error: %v", err)
  307. }
  308. if got != "example.com" {
  309. t.Fatalf("got %q, want example.com", got)
  310. }
  311. }
  312. func TestGetHostFromXFH_HostWithPort(t *testing.T) {
  313. got, err := getHostFromXFH("example.com:8443")
  314. if err != nil {
  315. t.Fatalf("unexpected error: %v", err)
  316. }
  317. if got != "example.com" {
  318. t.Fatalf("got %q, want example.com", got)
  319. }
  320. }
  321. func TestGetHostFromXFH_IPv6WithPort(t *testing.T) {
  322. got, err := getHostFromXFH("[2606:4700::1111]:443")
  323. if err != nil {
  324. t.Fatalf("unexpected error: %v", err)
  325. }
  326. if got != "2606:4700::1111" {
  327. t.Fatalf("got %q, want 2606:4700::1111", got)
  328. }
  329. }
  330. func TestGetHostFromXFH_BadHostPort(t *testing.T) {
  331. if _, err := getHostFromXFH("example.com:8443:9999"); err == nil {
  332. t.Fatal("expected error for malformed host:port")
  333. }
  334. }
  335. func TestReadPositiveInt(t *testing.T) {
  336. cases := []struct {
  337. name string
  338. in any
  339. wantVal int
  340. wantOk bool
  341. }{
  342. {"int_positive", int(5), 5, true},
  343. {"int_zero", int(0), 0, false},
  344. {"int_negative", int(-3), -3, false},
  345. {"int32_positive", int32(7), 7, true},
  346. {"int64_positive", int64(99), 99, true},
  347. {"float64_positive", float64(12), 12, true},
  348. {"float64_zero", float64(0.0), 0, false},
  349. {"float64_negative", float64(-1.5), -1, false},
  350. {"float32_positive", float32(3), 3, true},
  351. {"string", "not a number", 0, false},
  352. {"nil", nil, 0, false},
  353. }
  354. for _, c := range cases {
  355. t.Run(c.name, func(t *testing.T) {
  356. gotVal, gotOk := readPositiveInt(c.in)
  357. if gotVal != c.wantVal || gotOk != c.wantOk {
  358. t.Fatalf("readPositiveInt(%v) = (%d, %v), want (%d, %v)", c.in, gotVal, gotOk, c.wantVal, c.wantOk)
  359. }
  360. })
  361. }
  362. }
  363. func TestSetStringParam(t *testing.T) {
  364. p := map[string]string{"existing": "value"}
  365. setStringParam(p, "new", "hello")
  366. if p["new"] != "hello" {
  367. t.Fatalf("missing key after set: %v", p)
  368. }
  369. setStringParam(p, "existing", "")
  370. if _, ok := p["existing"]; ok {
  371. t.Fatalf("empty value should delete the key, got %v", p)
  372. }
  373. }
  374. func TestSetIntParam(t *testing.T) {
  375. p := map[string]string{"existing": "10"}
  376. setIntParam(p, "n", 42)
  377. if p["n"] != "42" {
  378. t.Fatalf("set positive int: got %v", p)
  379. }
  380. setIntParam(p, "existing", 0)
  381. if _, ok := p["existing"]; ok {
  382. t.Fatalf("zero value should delete the key, got %v", p)
  383. }
  384. p["other"] = "5"
  385. setIntParam(p, "other", -1)
  386. if _, ok := p["other"]; ok {
  387. t.Fatalf("negative value should delete the key, got %v", p)
  388. }
  389. }
  390. func TestSetStringField(t *testing.T) {
  391. f := map[string]any{"existing": "value"}
  392. setStringField(f, "new", "hello")
  393. if f["new"] != "hello" {
  394. t.Fatalf("missing key after set: %v", f)
  395. }
  396. setStringField(f, "existing", "")
  397. if _, ok := f["existing"]; ok {
  398. t.Fatalf("empty value should delete the key, got %v", f)
  399. }
  400. }
  401. func TestSetIntField(t *testing.T) {
  402. f := map[string]any{"existing": 10}
  403. setIntField(f, "n", 7)
  404. if f["n"] != 7 {
  405. t.Fatalf("set positive int: got %v", f)
  406. }
  407. setIntField(f, "existing", 0)
  408. if _, ok := f["existing"]; ok {
  409. t.Fatalf("zero value should delete the key, got %v", f)
  410. }
  411. }
  412. func TestBuildVmessLink(t *testing.T) {
  413. obj := map[string]any{
  414. "v": "2",
  415. "ps": "remark",
  416. "add": "example.com",
  417. "port": 443,
  418. "net": "tcp",
  419. }
  420. link := buildVmessLink(obj)
  421. if !strings.HasPrefix(link, "vmess://") {
  422. t.Fatalf("missing vmess:// prefix: %q", link)
  423. }
  424. payload := strings.TrimPrefix(link, "vmess://")
  425. decoded, err := base64.StdEncoding.DecodeString(payload)
  426. if err != nil {
  427. t.Fatalf("base64 decode failed: %v", err)
  428. }
  429. var roundTrip map[string]any
  430. if err := json.Unmarshal(decoded, &roundTrip); err != nil {
  431. t.Fatalf("decoded payload is not JSON: %v\n%s", err, decoded)
  432. }
  433. if roundTrip["add"] != "example.com" {
  434. t.Fatalf("round-trip add = %v, want example.com", roundTrip["add"])
  435. }
  436. if roundTrip["ps"] != "remark" {
  437. t.Fatalf("round-trip ps = %v, want remark", roundTrip["ps"])
  438. }
  439. }
  440. func TestCloneVmessShareObj_CopiesEverythingByDefault(t *testing.T) {
  441. base := map[string]any{
  442. "v": "2",
  443. "sni": "example.com",
  444. "alpn": "h2",
  445. "fp": "chrome",
  446. "net": "tcp",
  447. }
  448. out := cloneVmessShareObj(base, "tls")
  449. for _, key := range []string{"sni", "alpn", "fp", "net", "v"} {
  450. if _, ok := out[key]; !ok {
  451. t.Fatalf("expected key %q to be preserved when security=tls, got %v", key, out)
  452. }
  453. }
  454. }
  455. func TestCloneVmessShareObj_NoneStripsTLSOnlyKeys(t *testing.T) {
  456. base := map[string]any{
  457. "v": "2",
  458. "sni": "example.com",
  459. "alpn": "h2",
  460. "fp": "chrome",
  461. "net": "tcp",
  462. }
  463. out := cloneVmessShareObj(base, "none")
  464. for _, key := range []string{"sni", "alpn", "fp"} {
  465. if _, ok := out[key]; ok {
  466. t.Fatalf("security=none should strip %q, got %v", key, out)
  467. }
  468. }
  469. if out["v"] != "2" || out["net"] != "tcp" {
  470. t.Fatalf("non-TLS keys should remain, got %v", out)
  471. }
  472. }
  473. func TestApplyExternalProxyTLSParams_UsesProxyDomainAndOverrides(t *testing.T) {
  474. params := map[string]string{
  475. "security": "tls",
  476. "sni": "origin.example.com",
  477. "fp": "firefox",
  478. "alpn": "h2",
  479. }
  480. ep := map[string]any{
  481. "dest": "proxy.example.com",
  482. "sni": "tls.example.com",
  483. "fingerprint": "chrome",
  484. "alpn": []any{"h3", "h2"},
  485. }
  486. applyExternalProxyTLSParams(ep, params, "tls")
  487. if params["sni"] != "tls.example.com" {
  488. t.Fatalf("sni = %q, want tls.example.com", params["sni"])
  489. }
  490. if params["fp"] != "chrome" {
  491. t.Fatalf("fp = %q, want chrome", params["fp"])
  492. }
  493. if params["alpn"] != "h3,h2" {
  494. t.Fatalf("alpn = %q, want h3,h2", params["alpn"])
  495. }
  496. }
  497. func TestApplyExternalProxyTLSParams_PreservesUpstreamSNI(t *testing.T) {
  498. // External-proxy entry has no SNI of its own; its dest must not
  499. // clobber the upstream tlsSettings.serverName already written into
  500. // params. Regression: the dest fallback used to overwrite "222" with
  501. // "111" whenever an operator set forceTls=same and left the proxy's
  502. // SNI field blank.
  503. params := map[string]string{"security": "tls", "sni": "real.example.com"}
  504. ep := map[string]any{"dest": "proxy.example.com"}
  505. applyExternalProxyTLSParams(ep, params, "tls")
  506. if params["sni"] != "real.example.com" {
  507. t.Fatalf("sni = %q, want upstream sni preserved (real.example.com)", params["sni"])
  508. }
  509. }
  510. func TestApplyExternalProxyTLSParams_ExplicitSNIOverridesUpstream(t *testing.T) {
  511. params := map[string]string{"security": "tls", "sni": "real.example.com"}
  512. ep := map[string]any{"dest": "proxy.example.com", "sni": "edge.example.com"}
  513. applyExternalProxyTLSParams(ep, params, "tls")
  514. if params["sni"] != "edge.example.com" {
  515. t.Fatalf("sni = %q, want edge.example.com", params["sni"])
  516. }
  517. }
  518. func TestApplyExternalProxy_ECHPropagates(t *testing.T) {
  519. const ech = "ech-config-base64"
  520. t.Run("url params", func(t *testing.T) {
  521. params := map[string]string{"security": "tls"}
  522. ep := map[string]any{"dest": "proxy.example.com", "echConfigList": ech}
  523. applyExternalProxyTLSParams(ep, params, "tls")
  524. if params["ech"] != ech {
  525. t.Fatalf("ech param = %q, want %q", params["ech"], ech)
  526. }
  527. })
  528. t.Run("vmess obj", func(t *testing.T) {
  529. obj := map[string]any{}
  530. ep := map[string]any{"dest": "proxy.example.com", "echConfigList": ech}
  531. applyExternalProxyTLSObj(ep, obj, "tls")
  532. if obj["ech"] != ech {
  533. t.Fatalf("ech obj = %v, want %q", obj["ech"], ech)
  534. }
  535. })
  536. t.Run("json stream settings", func(t *testing.T) {
  537. stream := map[string]any{"security": "tls", "tlsSettings": map[string]any{}}
  538. ep := map[string]any{"dest": "proxy.example.com", "echConfigList": ech}
  539. applyExternalProxyTLSToStream(ep, stream, "tls")
  540. settings, _ := stream["tlsSettings"].(map[string]any)["settings"].(map[string]any)
  541. if settings["echConfigList"] != ech {
  542. t.Fatalf("echConfigList = %v, want %q", settings["echConfigList"], ech)
  543. }
  544. })
  545. t.Run("non-tls security drops ech", func(t *testing.T) {
  546. params := map[string]string{}
  547. ep := map[string]any{"echConfigList": ech}
  548. applyExternalProxyTLSParams(ep, params, "none")
  549. if _, ok := params["ech"]; ok {
  550. t.Fatalf("ech must not be set when security != tls")
  551. }
  552. })
  553. }
  554. func TestApplyExternalProxyTLSToStream_DoesNotLeakAcrossProxies(t *testing.T) {
  555. stream := map[string]any{
  556. "security": "tls",
  557. "tlsSettings": map[string]any{
  558. "serverName": "upstream.example.com",
  559. },
  560. }
  561. proxies := []map[string]any{
  562. {"dest": "a.example.com", "sni": "a-sni.example.com", "fingerprint": "chrome", "alpn": []any{"h3"}},
  563. {"dest": "b.example.com"},
  564. }
  565. results := make([]map[string]any, 0, len(proxies))
  566. for _, ep := range proxies {
  567. working := cloneStreamForExternalProxy(stream)
  568. applyExternalProxyTLSToStream(ep, working, "tls")
  569. ts := working["tlsSettings"].(map[string]any)
  570. snapshot := map[string]any{
  571. "serverName": ts["serverName"],
  572. "fingerprint": ts["fingerprint"],
  573. "alpn": ts["alpn"],
  574. }
  575. results = append(results, snapshot)
  576. }
  577. if results[0]["serverName"] != "a-sni.example.com" || results[0]["fingerprint"] != "chrome" {
  578. t.Fatalf("proxy A snapshot = %v", results[0])
  579. }
  580. // Proxy B has no SNI of its own — the upstream tlsSettings serverName
  581. // must remain in place (no dest fallback) and no fingerprint/alpn
  582. // must leak from proxy A.
  583. if results[1]["serverName"] != "upstream.example.com" {
  584. t.Fatalf("proxy B serverName = %v, want upstream.example.com preserved", results[1]["serverName"])
  585. }
  586. if results[1]["fingerprint"] != nil {
  587. t.Fatalf("proxy B should inherit no fingerprint, got %v (leaked from A)", results[1]["fingerprint"])
  588. }
  589. if results[1]["alpn"] != nil {
  590. t.Fatalf("proxy B should inherit no alpn, got %v (leaked from A)", results[1]["alpn"])
  591. }
  592. }
  593. func TestApplyExternalProxyTLSParams_SetsPinnedPeerCert(t *testing.T) {
  594. params := map[string]string{"security": "tls"}
  595. ep := map[string]any{
  596. "dest": "proxy.example.com",
  597. "pinnedPeerCertSha256": []any{"aa11", "bb22"},
  598. }
  599. applyExternalProxyTLSParams(ep, params, "tls")
  600. if params["pcs"] != "aa11,bb22" {
  601. t.Fatalf("pcs = %q, want aa11,bb22", params["pcs"])
  602. }
  603. }
  604. func TestApplyExternalProxyTLSObj_SetsPinnedPeerCert(t *testing.T) {
  605. obj := map[string]any{"tls": "tls"}
  606. ep := map[string]any{
  607. "dest": "proxy.example.com",
  608. "pinnedPeerCertSha256": []any{"aa11"},
  609. }
  610. applyExternalProxyTLSObj(ep, obj, "tls")
  611. if obj["pcs"] != "aa11" {
  612. t.Fatalf("pcs = %v, want aa11", obj["pcs"])
  613. }
  614. }
  615. func TestApplyExternalProxyTLSToStream_SetsPinnedPeerCert(t *testing.T) {
  616. stream := map[string]any{
  617. "security": "tls",
  618. "tlsSettings": map[string]any{"serverName": "upstream.example.com"},
  619. }
  620. ep := map[string]any{"dest": "edge.example.com", "pinnedPeerCertSha256": []any{"aa11", "bb22"}}
  621. working := cloneStreamForExternalProxy(stream)
  622. applyExternalProxyTLSToStream(ep, working, "tls")
  623. ts := working["tlsSettings"].(map[string]any)
  624. settings, _ := ts["settings"].(map[string]any)
  625. pins, ok := settings["pinnedPeerCertSha256"].([]any)
  626. if !ok || len(pins) != 2 || pins[0] != "aa11" || pins[1] != "bb22" {
  627. t.Fatalf("pinnedPeerCertSha256 = %v, want [aa11 bb22]", settings["pinnedPeerCertSha256"])
  628. }
  629. }
  630. func TestApplyExternalProxyHysteriaParams_PinIsHexNormalized(t *testing.T) {
  631. // base64 SHA-256 pin must come out as bare lowercase hex for Hysteria's
  632. // pinSHA256, which other (pcs) protocols leave untouched.
  633. params := map[string]string{"security": "tls", "sni": "server.example.com"}
  634. ep := map[string]any{
  635. "dest": "edge.example.com",
  636. "pinnedPeerCertSha256": []any{"yEfdI5XQl4wHgLggHEsomosoFZfUfCdfLXfT+W2N6cQ="},
  637. }
  638. applyExternalProxyHysteriaParams(ep, params)
  639. if params["pinSHA256"] != "c847dd2395d0978c0780b8201c4b289a8b281597d47c275f2d77d3f96d8de9c4" {
  640. t.Fatalf("pinSHA256 = %q, want hex-normalized pin", params["pinSHA256"])
  641. }
  642. if _, ok := params["pcs"]; ok {
  643. t.Fatalf("pcs must not be set for Hysteria, got %v", params)
  644. }
  645. if params["sni"] != "server.example.com" {
  646. t.Fatalf("sni = %q, want inbound sni preserved (no override for Hysteria)", params["sni"])
  647. }
  648. }
  649. func TestApplyExternalProxyHysteriaParams_NoPinLeavesMainPin(t *testing.T) {
  650. params := map[string]string{"security": "tls", "pinSHA256": "deadbeef"}
  651. ep := map[string]any{"dest": "edge.example.com"}
  652. applyExternalProxyHysteriaParams(ep, params)
  653. if params["pinSHA256"] != "deadbeef" {
  654. t.Fatalf("pinSHA256 = %q, want main pin preserved when proxy has none", params["pinSHA256"])
  655. }
  656. }
  657. func TestApplyExternalProxyTLSParams_DoesNotApplyForNone(t *testing.T) {
  658. params := map[string]string{
  659. "security": "none",
  660. "sni": "origin.example.com",
  661. }
  662. ep := map[string]any{
  663. "dest": "proxy.example.com",
  664. "fingerprint": "chrome",
  665. "alpn": []any{"h3"},
  666. }
  667. applyExternalProxyTLSParams(ep, params, "none")
  668. if params["sni"] != "origin.example.com" {
  669. t.Fatalf("sni should not change for security=none, got %q", params["sni"])
  670. }
  671. if _, ok := params["fp"]; ok {
  672. t.Fatalf("fp should not be set for security=none, got %v", params)
  673. }
  674. if _, ok := params["alpn"]; ok {
  675. t.Fatalf("alpn should not be set for security=none, got %v", params)
  676. }
  677. }
  678. func TestExtractKcpShareFields_Defaults(t *testing.T) {
  679. stream := map[string]any{}
  680. got := extractKcpShareFields(stream)
  681. if got.headerType != "none" {
  682. t.Fatalf("default headerType = %q, want none", got.headerType)
  683. }
  684. if got.seed != "" || got.mtu != 0 || got.tti != 0 {
  685. t.Fatalf("default kcpShareFields should be zero except headerType, got %+v", got)
  686. }
  687. }
  688. func TestExtractKcpShareFields_ReadsAllFields(t *testing.T) {
  689. stream := map[string]any{
  690. "kcpSettings": map[string]any{
  691. "header": map[string]any{"type": "wechat-video"},
  692. "seed": "secret-seed",
  693. "mtu": float64(1350),
  694. "tti": float64(50),
  695. },
  696. }
  697. got := extractKcpShareFields(stream)
  698. if got.headerType != "wechat-video" {
  699. t.Fatalf("headerType = %q, want wechat-video", got.headerType)
  700. }
  701. if got.seed != "secret-seed" {
  702. t.Fatalf("seed = %q, want secret-seed", got.seed)
  703. }
  704. if got.mtu != 1350 {
  705. t.Fatalf("mtu = %d, want 1350", got.mtu)
  706. }
  707. if got.tti != 50 {
  708. t.Fatalf("tti = %d, want 50", got.tti)
  709. }
  710. }
  711. func TestExtractKcpShareFields_FinalMaskLegacyHeader(t *testing.T) {
  712. stream := map[string]any{
  713. "finalmask": map[string]any{
  714. "udp": []any{
  715. map[string]any{
  716. "type": "mkcp-legacy",
  717. "settings": map[string]any{"header": "wechat", "value": ""},
  718. },
  719. },
  720. },
  721. }
  722. got := extractKcpShareFields(stream)
  723. if got.headerType != "wechat-video" {
  724. t.Fatalf("headerType = %q, want wechat-video", got.headerType)
  725. }
  726. if got.seed != "" {
  727. t.Fatalf("seed = %q, want empty for header mask", got.seed)
  728. }
  729. }
  730. func TestExtractKcpShareFields_FinalMaskLegacySeed(t *testing.T) {
  731. stream := map[string]any{
  732. "finalmask": map[string]any{
  733. "udp": []any{
  734. map[string]any{
  735. "type": "mkcp-legacy",
  736. "settings": map[string]any{"header": "", "value": "obfs-pass"},
  737. },
  738. },
  739. },
  740. }
  741. got := extractKcpShareFields(stream)
  742. if got.headerType != "none" {
  743. t.Fatalf("headerType = %q, want none for empty-header legacy mask", got.headerType)
  744. }
  745. if got.seed != "obfs-pass" {
  746. t.Fatalf("seed = %q, want obfs-pass", got.seed)
  747. }
  748. }
  749. func TestKcpShareFields_ApplyToParams(t *testing.T) {
  750. params := map[string]string{}
  751. kcpShareFields{headerType: "wechat-video", seed: "s", mtu: 1350, tti: 50}.applyToParams(params)
  752. if params["headerType"] != "wechat-video" {
  753. t.Fatalf("headerType param = %q", params["headerType"])
  754. }
  755. if params["seed"] != "s" {
  756. t.Fatalf("seed param = %q", params["seed"])
  757. }
  758. if params["mtu"] != "1350" {
  759. t.Fatalf("mtu param = %q", params["mtu"])
  760. }
  761. if params["tti"] != "50" {
  762. t.Fatalf("tti param = %q", params["tti"])
  763. }
  764. }
  765. func TestKcpShareFields_ApplyToParams_NoneHeaderNotAdded(t *testing.T) {
  766. params := map[string]string{}
  767. kcpShareFields{headerType: "none"}.applyToParams(params)
  768. if _, ok := params["headerType"]; ok {
  769. t.Fatalf("headerType=none should not be added, got %v", params)
  770. }
  771. }
  772. func TestMarshalFinalMask_EmptyReturnsFalse(t *testing.T) {
  773. if _, ok := marshalFinalMask(map[string]any{}); ok {
  774. t.Fatal("expected ok=false for empty finalmask")
  775. }
  776. if _, ok := marshalFinalMask(nil); ok {
  777. t.Fatal("expected ok=false for nil finalmask")
  778. }
  779. }
  780. func TestMarshalFinalMask_WithContent(t *testing.T) {
  781. fm := map[string]any{
  782. "tcp": []any{
  783. map[string]any{"type": "fragment"},
  784. },
  785. }
  786. out, ok := marshalFinalMask(fm)
  787. if !ok {
  788. t.Fatal("expected ok=true for finalmask with valid tcp mask")
  789. }
  790. if !strings.Contains(out, `"tcp"`) {
  791. t.Fatalf("marshaled finalmask missing tcp key: %s", out)
  792. }
  793. if !strings.Contains(out, "fragment") {
  794. t.Fatalf("marshaled finalmask missing mask type: %s", out)
  795. }
  796. }
  797. func TestMarshalFinalMask_UnknownTypeIsDropped(t *testing.T) {
  798. fm := map[string]any{
  799. "tcp": []any{
  800. map[string]any{"type": "not-a-real-mask"},
  801. },
  802. }
  803. if _, ok := marshalFinalMask(fm); ok {
  804. t.Fatal("unknown mask types should be dropped, leaving nothing to marshal")
  805. }
  806. }
  807. func TestHasFinalMaskContent(t *testing.T) {
  808. if hasFinalMaskContent(nil) {
  809. t.Fatal("nil should not count as content")
  810. }
  811. if hasFinalMaskContent(map[string]any{}) {
  812. t.Fatal("empty map should not count as content")
  813. }
  814. if !hasFinalMaskContent(map[string]any{"x": 1}) {
  815. t.Fatal("non-empty map should count as content")
  816. }
  817. }
  818. func TestHysteriaPinHex(t *testing.T) {
  819. const hexPin = "c847dd2395d0978c0780b8201c4b289a8b281597d47c275f2d77d3f96d8de9c4"
  820. cases := []struct {
  821. name string
  822. in string
  823. want string
  824. }{
  825. // Std base64 (xray-core's native TLS format / the panel generate button)
  826. // must be re-encoded to the hex form Hysteria2 clients expect (#4818).
  827. {"std base64", "yEfdI5XQl4wHgLggHEsomosoFZfUfCdfLXfT+W2N6cQ=", hexPin},
  828. // A manually pasted hex fingerprint passes through (lowercased).
  829. {"hex passthrough", hexPin, hexPin},
  830. {"uppercase hex lowercased", strings.ToUpper(hexPin), hexPin},
  831. // openssl x509 -fingerprint -sha256 emits colon-separated hex.
  832. {"colon hex stripped", "C8:47:DD:23:95:D0:97:8C:07:80:B8:20:1C:4B:28:9A:8B:28:15:97:D4:7C:27:5F:2D:77:D3:F9:6D:8D:E9:C4", hexPin},
  833. {"surrounding whitespace trimmed", " " + hexPin + " ", hexPin},
  834. // URL-safe base64 with the same 32 bytes decodes identically.
  835. {"url-safe base64", "yEfdI5XQl4wHgLggHEsomosoFZfUfCdfLXfT-W2N6cQ=", hexPin},
  836. // Garbage that is neither valid hex nor a 32-byte base64 is left as-is
  837. // rather than silently dropped.
  838. {"unrecognized passthrough", "not-a-pin", "not-a-pin"},
  839. {"empty", "", ""},
  840. }
  841. for _, tc := range cases {
  842. t.Run(tc.name, func(t *testing.T) {
  843. if got := hysteriaPinHex(tc.in); got != tc.want {
  844. t.Fatalf("hysteriaPinHex(%q) = %q, want %q", tc.in, got, tc.want)
  845. }
  846. })
  847. }
  848. }
  849. func TestHysteriaHopPorts(t *testing.T) {
  850. withHop := func(ports any) map[string]any {
  851. return map[string]any{
  852. "finalmask": map[string]any{
  853. "quicParams": map[string]any{
  854. "udpHop": map[string]any{"ports": ports, "interval": "5-10"},
  855. },
  856. },
  857. }
  858. }
  859. cases := []struct {
  860. name string
  861. stream map[string]any
  862. want string
  863. }{
  864. {"range", withHop("20000-50000"), "20000-50000"},
  865. {"trimmed", withHop(" 443,20000-50000 "), "443,20000-50000"},
  866. {"empty string", withHop(""), ""},
  867. {"non-string", withHop(float64(443)), ""},
  868. {"no udpHop", map[string]any{"finalmask": map[string]any{"quicParams": map[string]any{}}}, ""},
  869. {"no finalmask", map[string]any{}, ""},
  870. {"nil stream", nil, ""},
  871. }
  872. for _, tc := range cases {
  873. t.Run(tc.name, func(t *testing.T) {
  874. if got := hysteriaHopPorts(tc.stream); got != tc.want {
  875. t.Fatalf("hysteriaHopPorts() = %q, want %q", got, tc.want)
  876. }
  877. })
  878. }
  879. }