1
0

subService_test.go 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860
  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 TestApplyExternalProxyTLSToStream_DoesNotLeakAcrossProxies(t *testing.T) {
  519. stream := map[string]any{
  520. "security": "tls",
  521. "tlsSettings": map[string]any{
  522. "serverName": "upstream.example.com",
  523. },
  524. }
  525. proxies := []map[string]any{
  526. {"dest": "a.example.com", "sni": "a-sni.example.com", "fingerprint": "chrome", "alpn": []any{"h3"}},
  527. {"dest": "b.example.com"},
  528. }
  529. results := make([]map[string]any, 0, len(proxies))
  530. for _, ep := range proxies {
  531. working := cloneStreamForExternalProxy(stream)
  532. applyExternalProxyTLSToStream(ep, working, "tls")
  533. ts := working["tlsSettings"].(map[string]any)
  534. snapshot := map[string]any{
  535. "serverName": ts["serverName"],
  536. "fingerprint": ts["fingerprint"],
  537. "alpn": ts["alpn"],
  538. }
  539. results = append(results, snapshot)
  540. }
  541. if results[0]["serverName"] != "a-sni.example.com" || results[0]["fingerprint"] != "chrome" {
  542. t.Fatalf("proxy A snapshot = %v", results[0])
  543. }
  544. // Proxy B has no SNI of its own — the upstream tlsSettings serverName
  545. // must remain in place (no dest fallback) and no fingerprint/alpn
  546. // must leak from proxy A.
  547. if results[1]["serverName"] != "upstream.example.com" {
  548. t.Fatalf("proxy B serverName = %v, want upstream.example.com preserved", results[1]["serverName"])
  549. }
  550. if results[1]["fingerprint"] != nil {
  551. t.Fatalf("proxy B should inherit no fingerprint, got %v (leaked from A)", results[1]["fingerprint"])
  552. }
  553. if results[1]["alpn"] != nil {
  554. t.Fatalf("proxy B should inherit no alpn, got %v (leaked from A)", results[1]["alpn"])
  555. }
  556. }
  557. func TestApplyExternalProxyTLSParams_DoesNotApplyForNone(t *testing.T) {
  558. params := map[string]string{
  559. "security": "none",
  560. "sni": "origin.example.com",
  561. }
  562. ep := map[string]any{
  563. "dest": "proxy.example.com",
  564. "fingerprint": "chrome",
  565. "alpn": []any{"h3"},
  566. }
  567. applyExternalProxyTLSParams(ep, params, "none")
  568. if params["sni"] != "origin.example.com" {
  569. t.Fatalf("sni should not change for security=none, got %q", params["sni"])
  570. }
  571. if _, ok := params["fp"]; ok {
  572. t.Fatalf("fp should not be set for security=none, got %v", params)
  573. }
  574. if _, ok := params["alpn"]; ok {
  575. t.Fatalf("alpn should not be set for security=none, got %v", params)
  576. }
  577. }
  578. func TestExtractKcpShareFields_Defaults(t *testing.T) {
  579. stream := map[string]any{}
  580. got := extractKcpShareFields(stream)
  581. if got.headerType != "none" {
  582. t.Fatalf("default headerType = %q, want none", got.headerType)
  583. }
  584. if got.seed != "" || got.mtu != 0 || got.tti != 0 {
  585. t.Fatalf("default kcpShareFields should be zero except headerType, got %+v", got)
  586. }
  587. }
  588. func TestExtractKcpShareFields_ReadsAllFields(t *testing.T) {
  589. stream := map[string]any{
  590. "kcpSettings": map[string]any{
  591. "header": map[string]any{"type": "wechat-video"},
  592. "seed": "secret-seed",
  593. "mtu": float64(1350),
  594. "tti": float64(50),
  595. },
  596. }
  597. got := extractKcpShareFields(stream)
  598. if got.headerType != "wechat-video" {
  599. t.Fatalf("headerType = %q, want wechat-video", got.headerType)
  600. }
  601. if got.seed != "secret-seed" {
  602. t.Fatalf("seed = %q, want secret-seed", got.seed)
  603. }
  604. if got.mtu != 1350 {
  605. t.Fatalf("mtu = %d, want 1350", got.mtu)
  606. }
  607. if got.tti != 50 {
  608. t.Fatalf("tti = %d, want 50", got.tti)
  609. }
  610. }
  611. func TestExtractKcpShareFields_FinalMaskLegacyHeader(t *testing.T) {
  612. stream := map[string]any{
  613. "finalmask": map[string]any{
  614. "udp": []any{
  615. map[string]any{
  616. "type": "mkcp-legacy",
  617. "settings": map[string]any{"header": "wechat", "value": ""},
  618. },
  619. },
  620. },
  621. }
  622. got := extractKcpShareFields(stream)
  623. if got.headerType != "wechat-video" {
  624. t.Fatalf("headerType = %q, want wechat-video", got.headerType)
  625. }
  626. if got.seed != "" {
  627. t.Fatalf("seed = %q, want empty for header mask", got.seed)
  628. }
  629. }
  630. func TestExtractKcpShareFields_FinalMaskLegacySeed(t *testing.T) {
  631. stream := map[string]any{
  632. "finalmask": map[string]any{
  633. "udp": []any{
  634. map[string]any{
  635. "type": "mkcp-legacy",
  636. "settings": map[string]any{"header": "", "value": "obfs-pass"},
  637. },
  638. },
  639. },
  640. }
  641. got := extractKcpShareFields(stream)
  642. if got.headerType != "none" {
  643. t.Fatalf("headerType = %q, want none for empty-header legacy mask", got.headerType)
  644. }
  645. if got.seed != "obfs-pass" {
  646. t.Fatalf("seed = %q, want obfs-pass", got.seed)
  647. }
  648. }
  649. func TestKcpShareFields_ApplyToParams(t *testing.T) {
  650. params := map[string]string{}
  651. kcpShareFields{headerType: "wechat-video", seed: "s", mtu: 1350, tti: 50}.applyToParams(params)
  652. if params["headerType"] != "wechat-video" {
  653. t.Fatalf("headerType param = %q", params["headerType"])
  654. }
  655. if params["seed"] != "s" {
  656. t.Fatalf("seed param = %q", params["seed"])
  657. }
  658. if params["mtu"] != "1350" {
  659. t.Fatalf("mtu param = %q", params["mtu"])
  660. }
  661. if params["tti"] != "50" {
  662. t.Fatalf("tti param = %q", params["tti"])
  663. }
  664. }
  665. func TestKcpShareFields_ApplyToParams_NoneHeaderNotAdded(t *testing.T) {
  666. params := map[string]string{}
  667. kcpShareFields{headerType: "none"}.applyToParams(params)
  668. if _, ok := params["headerType"]; ok {
  669. t.Fatalf("headerType=none should not be added, got %v", params)
  670. }
  671. }
  672. func TestMarshalFinalMask_EmptyReturnsFalse(t *testing.T) {
  673. if _, ok := marshalFinalMask(map[string]any{}); ok {
  674. t.Fatal("expected ok=false for empty finalmask")
  675. }
  676. if _, ok := marshalFinalMask(nil); ok {
  677. t.Fatal("expected ok=false for nil finalmask")
  678. }
  679. }
  680. func TestMarshalFinalMask_WithContent(t *testing.T) {
  681. fm := map[string]any{
  682. "tcp": []any{
  683. map[string]any{"type": "fragment"},
  684. },
  685. }
  686. out, ok := marshalFinalMask(fm)
  687. if !ok {
  688. t.Fatal("expected ok=true for finalmask with valid tcp mask")
  689. }
  690. if !strings.Contains(out, `"tcp"`) {
  691. t.Fatalf("marshaled finalmask missing tcp key: %s", out)
  692. }
  693. if !strings.Contains(out, "fragment") {
  694. t.Fatalf("marshaled finalmask missing mask type: %s", out)
  695. }
  696. }
  697. func TestMarshalFinalMask_UnknownTypeIsDropped(t *testing.T) {
  698. fm := map[string]any{
  699. "tcp": []any{
  700. map[string]any{"type": "not-a-real-mask"},
  701. },
  702. }
  703. if _, ok := marshalFinalMask(fm); ok {
  704. t.Fatal("unknown mask types should be dropped, leaving nothing to marshal")
  705. }
  706. }
  707. func TestHasFinalMaskContent(t *testing.T) {
  708. if hasFinalMaskContent(nil) {
  709. t.Fatal("nil should not count as content")
  710. }
  711. if hasFinalMaskContent(map[string]any{}) {
  712. t.Fatal("empty map should not count as content")
  713. }
  714. if !hasFinalMaskContent(map[string]any{"x": 1}) {
  715. t.Fatal("non-empty map should count as content")
  716. }
  717. }
  718. func TestHysteriaPinHex(t *testing.T) {
  719. const hexPin = "c847dd2395d0978c0780b8201c4b289a8b281597d47c275f2d77d3f96d8de9c4"
  720. cases := []struct {
  721. name string
  722. in string
  723. want string
  724. }{
  725. // Std base64 (xray-core's native TLS format / the panel generate button)
  726. // must be re-encoded to the hex form Hysteria2 clients expect (#4818).
  727. {"std base64", "yEfdI5XQl4wHgLggHEsomosoFZfUfCdfLXfT+W2N6cQ=", hexPin},
  728. // A manually pasted hex fingerprint passes through (lowercased).
  729. {"hex passthrough", hexPin, hexPin},
  730. {"uppercase hex lowercased", strings.ToUpper(hexPin), hexPin},
  731. // openssl x509 -fingerprint -sha256 emits colon-separated hex.
  732. {"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},
  733. {"surrounding whitespace trimmed", " " + hexPin + " ", hexPin},
  734. // URL-safe base64 with the same 32 bytes decodes identically.
  735. {"url-safe base64", "yEfdI5XQl4wHgLggHEsomosoFZfUfCdfLXfT-W2N6cQ=", hexPin},
  736. // Garbage that is neither valid hex nor a 32-byte base64 is left as-is
  737. // rather than silently dropped.
  738. {"unrecognized passthrough", "not-a-pin", "not-a-pin"},
  739. {"empty", "", ""},
  740. }
  741. for _, tc := range cases {
  742. t.Run(tc.name, func(t *testing.T) {
  743. if got := hysteriaPinHex(tc.in); got != tc.want {
  744. t.Fatalf("hysteriaPinHex(%q) = %q, want %q", tc.in, got, tc.want)
  745. }
  746. })
  747. }
  748. }
  749. func TestHysteriaHopPorts(t *testing.T) {
  750. withHop := func(ports any) map[string]any {
  751. return map[string]any{
  752. "finalmask": map[string]any{
  753. "quicParams": map[string]any{
  754. "udpHop": map[string]any{"ports": ports, "interval": "5-10"},
  755. },
  756. },
  757. }
  758. }
  759. cases := []struct {
  760. name string
  761. stream map[string]any
  762. want string
  763. }{
  764. {"range", withHop("20000-50000"), "20000-50000"},
  765. {"trimmed", withHop(" 443,20000-50000 "), "443,20000-50000"},
  766. {"empty string", withHop(""), ""},
  767. {"non-string", withHop(float64(443)), ""},
  768. {"no udpHop", map[string]any{"finalmask": map[string]any{"quicParams": map[string]any{}}}, ""},
  769. {"no finalmask", map[string]any{}, ""},
  770. {"nil stream", nil, ""},
  771. }
  772. for _, tc := range cases {
  773. t.Run(tc.name, func(t *testing.T) {
  774. if got := hysteriaHopPorts(tc.stream); got != tc.want {
  775. t.Fatalf("hysteriaHopPorts() = %q, want %q", got, tc.want)
  776. }
  777. })
  778. }
  779. }