service_test.go 33 KB

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