subService_test.go 30 KB

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