service_test.go 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122
  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. nodesByID: map[int]*model.Node{7: {Id: 7, Name: "Berlin", Address: "node7.example.com"}},
  32. }
  33. ib := &model.Inbound{Remark: "vless-tcp", NodeID: &nodeID}
  34. if got := s.genRemark(ib, "", "", ""); got != "vless-tcp" {
  35. t.Fatalf("remark = %q, want %q (node name must not leak into client-visible remarks)", got, "vless-tcp")
  36. }
  37. }
  38. func TestFindClientIndex(t *testing.T) {
  39. clients := []model.Client{
  40. {Email: "[email protected]"},
  41. {Email: "[email protected]"},
  42. {Email: "[email protected]"},
  43. }
  44. if got := findClientIndex(clients, "[email protected]"); got != 1 {
  45. t.Fatalf("findClientIndex middle = %d, want 1", got)
  46. }
  47. if got := findClientIndex(clients, "[email protected]"); got != 0 {
  48. t.Fatalf("findClientIndex first = %d, want 0", got)
  49. }
  50. if got := findClientIndex(clients, "[email protected]"); got != -1 {
  51. t.Fatalf("findClientIndex missing = %d, want -1", got)
  52. }
  53. if got := findClientIndex(nil, "x"); got != -1 {
  54. t.Fatalf("findClientIndex on nil slice = %d, want -1", got)
  55. }
  56. }
  57. func TestIsRoutableHost(t *testing.T) {
  58. routable := []string{"example.com", "sub.example.com", "10.0.0.1", "192.168.1.5", "1.2.3.4", "2001:db8::1"}
  59. for _, v := range routable {
  60. if !isRoutableHost(v) {
  61. t.Fatalf("isRoutableHost(%q) = false, want true", v)
  62. }
  63. }
  64. notRoutable := []string{"", "0.0.0.0", "::", "::0", "127.0.0.1", "127.0.0.2", "::1", "[::1]"}
  65. for _, v := range notRoutable {
  66. if isRoutableHost(v) {
  67. t.Fatalf("isRoutableHost(%q) = true, want false", v)
  68. }
  69. }
  70. }
  71. func TestListenIsInternalOnly(t *testing.T) {
  72. // Reachable only from the same host -> a fallback child here must be
  73. // projected through its master.
  74. internalOnly := []string{"127.0.0.1", "127.0.0.2", "::1", "[::1]", "@fallback", "/run/x.sock"}
  75. for _, v := range internalOnly {
  76. if !listenIsInternalOnly(v) {
  77. t.Fatalf("listenIsInternalOnly(%q) = false, want true", v)
  78. }
  79. }
  80. // Directly reachable on its own port -> never projected, even if a stale
  81. // fallback rule names it as a child (#4987).
  82. reachable := []string{"", "0.0.0.0", "::", "::0", "1.2.3.4", "10.0.0.5", "192.168.1.10", "vpn.example.com"}
  83. for _, v := range reachable {
  84. if listenIsInternalOnly(v) {
  85. t.Fatalf("listenIsInternalOnly(%q) = true, want false", v)
  86. }
  87. }
  88. }
  89. func TestResolveInboundAddress(t *testing.T) {
  90. initSubDB(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. // mode rides inside extra (in addition to the flat param) so clients
  342. // that only read the extra JSON keep the xhttp mode (#5446).
  343. if extra["mode"] != "packet-up" {
  344. t.Fatalf("extra[mode] = %#v, want packet-up", extra["mode"])
  345. }
  346. headers, ok := extra["headers"].(map[string]any)
  347. if !ok {
  348. t.Fatalf("headers = %#v, want map", extra["headers"])
  349. }
  350. if _, ok := headers["Host"]; ok {
  351. t.Fatalf("headers should not include Host: %#v", headers)
  352. }
  353. if headers["X-Forwarded"] != "1" {
  354. t.Fatalf("headers[X-Forwarded] = %#v, want 1", headers["X-Forwarded"])
  355. }
  356. }
  357. func TestBuildXhttpExtra_LeavesDefaultClientSideFieldsOut(t *testing.T) {
  358. extra := buildXhttpExtra(map[string]any{
  359. "uplinkHTTPMethod": "",
  360. "uplinkChunkSize": float64(0),
  361. "noGRPCHeader": false,
  362. "xmux": map[string]any{},
  363. "downloadSettings": map[string]any{},
  364. })
  365. if extra != nil {
  366. t.Fatalf("default-only xhttp extra = %#v, want nil", extra)
  367. }
  368. }
  369. func TestCloneStringMap(t *testing.T) {
  370. src := map[string]string{"a": "1", "b": "2"}
  371. dst := cloneStringMap(src)
  372. if len(dst) != len(src) {
  373. t.Fatalf("clone length = %d, want %d", len(dst), len(src))
  374. }
  375. for k, v := range src {
  376. if dst[k] != v {
  377. t.Fatalf("clone[%q] = %q, want %q", k, dst[k], v)
  378. }
  379. }
  380. dst["a"] = "changed"
  381. if src["a"] == "changed" {
  382. t.Fatal("modifying clone leaked into source")
  383. }
  384. }
  385. func TestCloneStringMap_Empty(t *testing.T) {
  386. dst := cloneStringMap(map[string]string{})
  387. if dst == nil {
  388. t.Fatal("clone of empty map should not be nil")
  389. }
  390. if len(dst) != 0 {
  391. t.Fatalf("clone of empty map should be empty, got %v", dst)
  392. }
  393. }
  394. func TestJoinHostPort(t *testing.T) {
  395. cases := []struct {
  396. host string
  397. port int
  398. want string
  399. }{
  400. {"example.com", 443, "example.com:443"},
  401. {"1.2.3.4", 443, "1.2.3.4:443"},
  402. {"2001:db8::1", 443, "[2001:db8::1]:443"},
  403. {"[2001:db8::1]", 443, "[2001:db8::1]:443"},
  404. {"2001:db8::1", 8080, "[2001:db8::1]:8080"},
  405. }
  406. for _, c := range cases {
  407. if got := joinHostPort(c.host, c.port); got != c.want {
  408. t.Fatalf("joinHostPort(%q, %d) = %q, want %q", c.host, c.port, got, c.want)
  409. }
  410. }
  411. }
  412. func TestGetHostFromXFH_HostOnly(t *testing.T) {
  413. got, err := getHostFromXFH("example.com")
  414. if err != nil {
  415. t.Fatalf("unexpected error: %v", err)
  416. }
  417. if got != "example.com" {
  418. t.Fatalf("got %q, want example.com", got)
  419. }
  420. }
  421. func TestGetHostFromXFH_HostWithPort(t *testing.T) {
  422. got, err := getHostFromXFH("example.com:8443")
  423. if err != nil {
  424. t.Fatalf("unexpected error: %v", err)
  425. }
  426. if got != "example.com" {
  427. t.Fatalf("got %q, want example.com", got)
  428. }
  429. }
  430. func TestGetHostFromXFH_IPv6WithPort(t *testing.T) {
  431. got, err := getHostFromXFH("[2606:4700::1111]:443")
  432. if err != nil {
  433. t.Fatalf("unexpected error: %v", err)
  434. }
  435. if got != "2606:4700::1111" {
  436. t.Fatalf("got %q, want 2606:4700::1111", got)
  437. }
  438. }
  439. func TestGetHostFromXFH_BadHostPort(t *testing.T) {
  440. if _, err := getHostFromXFH("example.com:8443:9999"); err == nil {
  441. t.Fatal("expected error for malformed host:port")
  442. }
  443. }
  444. func TestReadPositiveInt(t *testing.T) {
  445. cases := []struct {
  446. name string
  447. in any
  448. wantVal int
  449. wantOk bool
  450. }{
  451. {"int_positive", int(5), 5, true},
  452. {"int_zero", int(0), 0, false},
  453. {"int_negative", int(-3), -3, false},
  454. {"int32_positive", int32(7), 7, true},
  455. {"int64_positive", int64(99), 99, true},
  456. {"float64_positive", float64(12), 12, true},
  457. {"float64_zero", float64(0.0), 0, false},
  458. {"float64_negative", float64(-1.5), -1, false},
  459. {"float32_positive", float32(3), 3, true},
  460. {"string", "not a number", 0, false},
  461. {"nil", nil, 0, false},
  462. }
  463. for _, c := range cases {
  464. t.Run(c.name, func(t *testing.T) {
  465. gotVal, gotOk := readPositiveInt(c.in)
  466. if gotVal != c.wantVal || gotOk != c.wantOk {
  467. t.Fatalf("readPositiveInt(%v) = (%d, %v), want (%d, %v)", c.in, gotVal, gotOk, c.wantVal, c.wantOk)
  468. }
  469. })
  470. }
  471. }
  472. func TestSetStringParam(t *testing.T) {
  473. p := map[string]string{"existing": "value"}
  474. setStringParam(p, "new", "hello")
  475. if p["new"] != "hello" {
  476. t.Fatalf("missing key after set: %v", p)
  477. }
  478. setStringParam(p, "existing", "")
  479. if _, ok := p["existing"]; ok {
  480. t.Fatalf("empty value should delete the key, got %v", p)
  481. }
  482. }
  483. func TestSetIntParam(t *testing.T) {
  484. p := map[string]string{"existing": "10"}
  485. setIntParam(p, "n", 42)
  486. if p["n"] != "42" {
  487. t.Fatalf("set positive int: got %v", p)
  488. }
  489. setIntParam(p, "existing", 0)
  490. if _, ok := p["existing"]; ok {
  491. t.Fatalf("zero value should delete the key, got %v", p)
  492. }
  493. p["other"] = "5"
  494. setIntParam(p, "other", -1)
  495. if _, ok := p["other"]; ok {
  496. t.Fatalf("negative value should delete the key, got %v", p)
  497. }
  498. }
  499. func TestSetStringField(t *testing.T) {
  500. f := map[string]any{"existing": "value"}
  501. setStringField(f, "new", "hello")
  502. if f["new"] != "hello" {
  503. t.Fatalf("missing key after set: %v", f)
  504. }
  505. setStringField(f, "existing", "")
  506. if _, ok := f["existing"]; ok {
  507. t.Fatalf("empty value should delete the key, got %v", f)
  508. }
  509. }
  510. func TestSetIntField(t *testing.T) {
  511. f := map[string]any{"existing": 10}
  512. setIntField(f, "n", 7)
  513. if f["n"] != 7 {
  514. t.Fatalf("set positive int: got %v", f)
  515. }
  516. setIntField(f, "existing", 0)
  517. if _, ok := f["existing"]; ok {
  518. t.Fatalf("zero value should delete the key, got %v", f)
  519. }
  520. }
  521. func TestBuildVmessLink(t *testing.T) {
  522. obj := map[string]any{
  523. "v": "2",
  524. "ps": "remark",
  525. "add": "example.com",
  526. "port": 443,
  527. "net": "tcp",
  528. }
  529. link := buildVmessLink(obj)
  530. if !strings.HasPrefix(link, "vmess://") {
  531. t.Fatalf("missing vmess:// prefix: %q", link)
  532. }
  533. payload := strings.TrimPrefix(link, "vmess://")
  534. decoded, err := base64.StdEncoding.DecodeString(payload)
  535. if err != nil {
  536. t.Fatalf("base64 decode failed: %v", err)
  537. }
  538. var roundTrip map[string]any
  539. if err := json.Unmarshal(decoded, &roundTrip); err != nil {
  540. t.Fatalf("decoded payload is not JSON: %v\n%s", err, decoded)
  541. }
  542. if roundTrip["add"] != "example.com" {
  543. t.Fatalf("round-trip add = %v, want example.com", roundTrip["add"])
  544. }
  545. if roundTrip["ps"] != "remark" {
  546. t.Fatalf("round-trip ps = %v, want remark", roundTrip["ps"])
  547. }
  548. }
  549. func TestCloneVmessShareObj_CopiesEverythingByDefault(t *testing.T) {
  550. base := map[string]any{
  551. "v": "2",
  552. "sni": "example.com",
  553. "alpn": "h2",
  554. "fp": "chrome",
  555. "net": "tcp",
  556. }
  557. out := cloneVmessShareObj(base, "tls")
  558. for _, key := range []string{"sni", "alpn", "fp", "net", "v"} {
  559. if _, ok := out[key]; !ok {
  560. t.Fatalf("expected key %q to be preserved when security=tls, got %v", key, out)
  561. }
  562. }
  563. }
  564. func TestCloneVmessShareObj_NoneStripsTLSOnlyKeys(t *testing.T) {
  565. base := map[string]any{
  566. "v": "2",
  567. "sni": "example.com",
  568. "alpn": "h2",
  569. "fp": "chrome",
  570. "net": "tcp",
  571. }
  572. out := cloneVmessShareObj(base, "none")
  573. for _, key := range []string{"sni", "alpn", "fp"} {
  574. if _, ok := out[key]; ok {
  575. t.Fatalf("security=none should strip %q, got %v", key, out)
  576. }
  577. }
  578. if out["v"] != "2" || out["net"] != "tcp" {
  579. t.Fatalf("non-TLS keys should remain, got %v", out)
  580. }
  581. }
  582. func TestApplyExternalProxyTLSParams_UsesProxyDomainAndOverrides(t *testing.T) {
  583. params := map[string]string{
  584. "security": "tls",
  585. "sni": "origin.example.com",
  586. "fp": "firefox",
  587. "alpn": "h2",
  588. }
  589. ep := map[string]any{
  590. "dest": "proxy.example.com",
  591. "sni": "tls.example.com",
  592. "fingerprint": "chrome",
  593. "alpn": []any{"h3", "h2"},
  594. }
  595. applyExternalProxyTLSParams(ep, params, "tls")
  596. if params["sni"] != "tls.example.com" {
  597. t.Fatalf("sni = %q, want tls.example.com", params["sni"])
  598. }
  599. if params["fp"] != "chrome" {
  600. t.Fatalf("fp = %q, want chrome", params["fp"])
  601. }
  602. if params["alpn"] != "h3,h2" {
  603. t.Fatalf("alpn = %q, want h3,h2", params["alpn"])
  604. }
  605. }
  606. func TestApplyExternalProxyTLSParams_PreservesUpstreamSNI(t *testing.T) {
  607. // External-proxy entry has no SNI of its own; its dest must not
  608. // clobber the upstream tlsSettings.serverName already written into
  609. // params. Regression: the dest fallback used to overwrite "222" with
  610. // "111" whenever an operator set forceTls=same and left the proxy's
  611. // SNI field blank.
  612. params := map[string]string{"security": "tls", "sni": "real.example.com"}
  613. ep := map[string]any{"dest": "proxy.example.com"}
  614. applyExternalProxyTLSParams(ep, params, "tls")
  615. if params["sni"] != "real.example.com" {
  616. t.Fatalf("sni = %q, want upstream sni preserved (real.example.com)", params["sni"])
  617. }
  618. }
  619. func TestApplyExternalProxyTLSParams_ExplicitSNIOverridesUpstream(t *testing.T) {
  620. params := map[string]string{"security": "tls", "sni": "real.example.com"}
  621. ep := map[string]any{"dest": "proxy.example.com", "sni": "edge.example.com"}
  622. applyExternalProxyTLSParams(ep, params, "tls")
  623. if params["sni"] != "edge.example.com" {
  624. t.Fatalf("sni = %q, want edge.example.com", params["sni"])
  625. }
  626. }
  627. func TestApplyExternalProxy_ECHPropagates(t *testing.T) {
  628. const ech = "ech-config-base64"
  629. t.Run("url params", func(t *testing.T) {
  630. params := map[string]string{"security": "tls"}
  631. ep := map[string]any{"dest": "proxy.example.com", "echConfigList": ech}
  632. applyExternalProxyTLSParams(ep, params, "tls")
  633. if params["ech"] != ech {
  634. t.Fatalf("ech param = %q, want %q", params["ech"], ech)
  635. }
  636. })
  637. t.Run("vmess obj", func(t *testing.T) {
  638. obj := map[string]any{}
  639. ep := map[string]any{"dest": "proxy.example.com", "echConfigList": ech}
  640. applyExternalProxyTLSObj(ep, obj, "tls")
  641. if obj["ech"] != ech {
  642. t.Fatalf("ech obj = %v, want %q", obj["ech"], ech)
  643. }
  644. })
  645. t.Run("json stream settings", func(t *testing.T) {
  646. stream := map[string]any{"security": "tls", "tlsSettings": map[string]any{}}
  647. ep := map[string]any{"dest": "proxy.example.com", "echConfigList": ech}
  648. applyExternalProxyTLSToStream(ep, stream, "tls")
  649. settings, _ := stream["tlsSettings"].(map[string]any)["settings"].(map[string]any)
  650. if settings["echConfigList"] != ech {
  651. t.Fatalf("echConfigList = %v, want %q", settings["echConfigList"], ech)
  652. }
  653. })
  654. t.Run("non-tls security drops ech", func(t *testing.T) {
  655. params := map[string]string{}
  656. ep := map[string]any{"echConfigList": ech}
  657. applyExternalProxyTLSParams(ep, params, "none")
  658. if _, ok := params["ech"]; ok {
  659. t.Fatalf("ech must not be set when security != tls")
  660. }
  661. })
  662. }
  663. func TestApplyExternalProxyTLSToStream_DoesNotLeakAcrossProxies(t *testing.T) {
  664. stream := map[string]any{
  665. "security": "tls",
  666. "tlsSettings": map[string]any{
  667. "serverName": "upstream.example.com",
  668. },
  669. }
  670. proxies := []map[string]any{
  671. {"dest": "a.example.com", "sni": "a-sni.example.com", "fingerprint": "chrome", "alpn": []any{"h3"}},
  672. {"dest": "b.example.com"},
  673. }
  674. results := make([]map[string]any, 0, len(proxies))
  675. for _, ep := range proxies {
  676. working := cloneStreamForExternalProxy(stream)
  677. applyExternalProxyTLSToStream(ep, working, "tls")
  678. ts := working["tlsSettings"].(map[string]any)
  679. snapshot := map[string]any{
  680. "serverName": ts["serverName"],
  681. "fingerprint": ts["fingerprint"],
  682. "alpn": ts["alpn"],
  683. }
  684. results = append(results, snapshot)
  685. }
  686. if results[0]["serverName"] != "a-sni.example.com" || results[0]["fingerprint"] != "chrome" {
  687. t.Fatalf("proxy A snapshot = %v", results[0])
  688. }
  689. // Proxy B has no SNI of its own — the upstream tlsSettings serverName
  690. // must remain in place (no dest fallback) and no fingerprint/alpn
  691. // must leak from proxy A.
  692. if results[1]["serverName"] != "upstream.example.com" {
  693. t.Fatalf("proxy B serverName = %v, want upstream.example.com preserved", results[1]["serverName"])
  694. }
  695. if results[1]["fingerprint"] != nil {
  696. t.Fatalf("proxy B should inherit no fingerprint, got %v (leaked from A)", results[1]["fingerprint"])
  697. }
  698. if results[1]["alpn"] != nil {
  699. t.Fatalf("proxy B should inherit no alpn, got %v (leaked from A)", results[1]["alpn"])
  700. }
  701. }
  702. func TestApplyExternalProxyTLSParams_SetsPinnedPeerCert(t *testing.T) {
  703. params := map[string]string{"security": "tls"}
  704. ep := map[string]any{
  705. "dest": "proxy.example.com",
  706. "pinnedPeerCertSha256": []any{"aa11", "bb22"},
  707. }
  708. applyExternalProxyTLSParams(ep, params, "tls")
  709. if params["pcs"] != "aa11,bb22" {
  710. t.Fatalf("pcs = %q, want aa11,bb22", params["pcs"])
  711. }
  712. }
  713. func TestApplyExternalProxyTLSObj_SetsPinnedPeerCert(t *testing.T) {
  714. obj := map[string]any{"tls": "tls"}
  715. ep := map[string]any{
  716. "dest": "proxy.example.com",
  717. "pinnedPeerCertSha256": []any{"aa11"},
  718. }
  719. applyExternalProxyTLSObj(ep, obj, "tls")
  720. if obj["pcs"] != "aa11" {
  721. t.Fatalf("pcs = %v, want aa11", obj["pcs"])
  722. }
  723. }
  724. func TestApplyExternalProxyTLSToStream_SetsPinnedPeerCert(t *testing.T) {
  725. stream := map[string]any{
  726. "security": "tls",
  727. "tlsSettings": map[string]any{"serverName": "upstream.example.com"},
  728. }
  729. ep := map[string]any{"dest": "edge.example.com", "pinnedPeerCertSha256": []any{"aa11", "bb22"}}
  730. working := cloneStreamForExternalProxy(stream)
  731. applyExternalProxyTLSToStream(ep, working, "tls")
  732. ts := working["tlsSettings"].(map[string]any)
  733. settings, _ := ts["settings"].(map[string]any)
  734. pins, ok := settings["pinnedPeerCertSha256"].([]any)
  735. if !ok || len(pins) != 2 || pins[0] != "aa11" || pins[1] != "bb22" {
  736. t.Fatalf("pinnedPeerCertSha256 = %v, want [aa11 bb22]", settings["pinnedPeerCertSha256"])
  737. }
  738. }
  739. func TestApplyExternalProxyHysteriaParams_PinIsHexNormalized(t *testing.T) {
  740. // base64 SHA-256 pin must come out as bare lowercase hex for Hysteria's
  741. // pinSHA256, which other (pcs) protocols leave untouched.
  742. params := map[string]string{"security": "tls", "sni": "server.example.com"}
  743. ep := map[string]any{
  744. "dest": "edge.example.com",
  745. "pinnedPeerCertSha256": []any{"yEfdI5XQl4wHgLggHEsomosoFZfUfCdfLXfT+W2N6cQ="},
  746. }
  747. applyExternalProxyHysteriaParams(ep, params)
  748. if params["pinSHA256"] != "c847dd2395d0978c0780b8201c4b289a8b281597d47c275f2d77d3f96d8de9c4" {
  749. t.Fatalf("pinSHA256 = %q, want hex-normalized pin", params["pinSHA256"])
  750. }
  751. if _, ok := params["pcs"]; ok {
  752. t.Fatalf("pcs must not be set for Hysteria, got %v", params)
  753. }
  754. if params["sni"] != "server.example.com" {
  755. t.Fatalf("sni = %q, want inbound sni preserved (no override for Hysteria)", params["sni"])
  756. }
  757. }
  758. func TestApplyExternalProxyHysteriaParams_NoPinLeavesMainPin(t *testing.T) {
  759. params := map[string]string{"security": "tls", "pinSHA256": "deadbeef"}
  760. ep := map[string]any{"dest": "edge.example.com"}
  761. applyExternalProxyHysteriaParams(ep, params)
  762. if params["pinSHA256"] != "deadbeef" {
  763. t.Fatalf("pinSHA256 = %q, want main pin preserved when proxy has none", params["pinSHA256"])
  764. }
  765. }
  766. func TestApplyExternalProxyHysteriaParams_AllowInsecureSetsInsecureParam(t *testing.T) {
  767. params := map[string]string{"security": "tls", "sni": "server.example.com"}
  768. ep := map[string]any{
  769. "dest": "edge.example.com",
  770. "allowInsecure": true,
  771. }
  772. applyExternalProxyHysteriaParams(ep, params)
  773. if params["insecure"] != "1" {
  774. t.Fatalf("insecure = %q, want 1 when ep allowInsecure is true", params["insecure"])
  775. }
  776. }
  777. func TestApplyExternalProxyHysteriaParams_NoAllowInsecureOmitsParam(t *testing.T) {
  778. params := map[string]string{"security": "tls"}
  779. ep := map[string]any{"dest": "edge.example.com"}
  780. applyExternalProxyHysteriaParams(ep, params)
  781. if _, ok := params["insecure"]; ok {
  782. t.Fatalf("insecure should not be set when ep has no allowInsecure, got %v", params)
  783. }
  784. }
  785. func TestApplyExternalProxyTLSParams_DoesNotApplyForNone(t *testing.T) {
  786. params := map[string]string{
  787. "security": "none",
  788. "sni": "origin.example.com",
  789. }
  790. ep := map[string]any{
  791. "dest": "proxy.example.com",
  792. "fingerprint": "chrome",
  793. "alpn": []any{"h3"},
  794. }
  795. applyExternalProxyTLSParams(ep, params, "none")
  796. if params["sni"] != "origin.example.com" {
  797. t.Fatalf("sni should not change for security=none, got %q", params["sni"])
  798. }
  799. if _, ok := params["fp"]; ok {
  800. t.Fatalf("fp should not be set for security=none, got %v", params)
  801. }
  802. if _, ok := params["alpn"]; ok {
  803. t.Fatalf("alpn should not be set for security=none, got %v", params)
  804. }
  805. }
  806. func TestExtractKcpShareFields_Defaults(t *testing.T) {
  807. stream := map[string]any{}
  808. got := extractKcpShareFields(stream)
  809. if got.headerType != "none" {
  810. t.Fatalf("default headerType = %q, want none", got.headerType)
  811. }
  812. if got.seed != "" || got.mtu != 0 || got.tti != 0 {
  813. t.Fatalf("default kcpShareFields should be zero except headerType, got %+v", got)
  814. }
  815. }
  816. func TestExtractKcpShareFields_ReadsAllFields(t *testing.T) {
  817. stream := map[string]any{
  818. "kcpSettings": map[string]any{
  819. "header": map[string]any{"type": "wechat-video"},
  820. "seed": "secret-seed",
  821. "mtu": float64(1350),
  822. "tti": float64(50),
  823. },
  824. }
  825. got := extractKcpShareFields(stream)
  826. if got.headerType != "wechat-video" {
  827. t.Fatalf("headerType = %q, want wechat-video", got.headerType)
  828. }
  829. if got.seed != "secret-seed" {
  830. t.Fatalf("seed = %q, want secret-seed", got.seed)
  831. }
  832. if got.mtu != 1350 {
  833. t.Fatalf("mtu = %d, want 1350", got.mtu)
  834. }
  835. if got.tti != 50 {
  836. t.Fatalf("tti = %d, want 50", got.tti)
  837. }
  838. }
  839. func TestExtractKcpShareFields_FinalMaskLegacyHeader(t *testing.T) {
  840. stream := map[string]any{
  841. "finalmask": map[string]any{
  842. "udp": []any{
  843. map[string]any{
  844. "type": "mkcp-legacy",
  845. "settings": map[string]any{"header": "wechat", "value": ""},
  846. },
  847. },
  848. },
  849. }
  850. got := extractKcpShareFields(stream)
  851. if got.headerType != "wechat-video" {
  852. t.Fatalf("headerType = %q, want wechat-video", got.headerType)
  853. }
  854. if got.seed != "" {
  855. t.Fatalf("seed = %q, want empty for header mask", got.seed)
  856. }
  857. }
  858. func TestExtractKcpShareFields_FinalMaskLegacySeed(t *testing.T) {
  859. stream := map[string]any{
  860. "finalmask": map[string]any{
  861. "udp": []any{
  862. map[string]any{
  863. "type": "mkcp-legacy",
  864. "settings": map[string]any{"header": "", "value": "obfs-pass"},
  865. },
  866. },
  867. },
  868. }
  869. got := extractKcpShareFields(stream)
  870. if got.headerType != "none" {
  871. t.Fatalf("headerType = %q, want none for empty-header legacy mask", got.headerType)
  872. }
  873. if got.seed != "obfs-pass" {
  874. t.Fatalf("seed = %q, want obfs-pass", got.seed)
  875. }
  876. }
  877. func TestKcpShareFields_ApplyToParams(t *testing.T) {
  878. params := map[string]string{}
  879. kcpShareFields{headerType: "wechat-video", seed: "s", mtu: 1350, tti: 50}.applyToParams(params)
  880. if params["headerType"] != "wechat-video" {
  881. t.Fatalf("headerType param = %q", params["headerType"])
  882. }
  883. if params["seed"] != "s" {
  884. t.Fatalf("seed param = %q", params["seed"])
  885. }
  886. if params["mtu"] != "1350" {
  887. t.Fatalf("mtu param = %q", params["mtu"])
  888. }
  889. if params["tti"] != "50" {
  890. t.Fatalf("tti param = %q", params["tti"])
  891. }
  892. }
  893. func TestKcpShareFields_ApplyToParams_NoneHeaderNotAdded(t *testing.T) {
  894. params := map[string]string{}
  895. kcpShareFields{headerType: "none"}.applyToParams(params)
  896. if _, ok := params["headerType"]; ok {
  897. t.Fatalf("headerType=none should not be added, got %v", params)
  898. }
  899. }
  900. func TestMarshalFinalMask_EmptyReturnsFalse(t *testing.T) {
  901. if _, ok := marshalFinalMask(map[string]any{}); ok {
  902. t.Fatal("expected ok=false for empty finalmask")
  903. }
  904. if _, ok := marshalFinalMask(nil); ok {
  905. t.Fatal("expected ok=false for nil finalmask")
  906. }
  907. }
  908. func TestMarshalFinalMask_WithContent(t *testing.T) {
  909. fm := map[string]any{
  910. "tcp": []any{
  911. map[string]any{"type": "fragment"},
  912. },
  913. }
  914. out, ok := marshalFinalMask(fm)
  915. if !ok {
  916. t.Fatal("expected ok=true for finalmask with valid tcp mask")
  917. }
  918. if !strings.Contains(out, `"tcp"`) {
  919. t.Fatalf("marshaled finalmask missing tcp key: %s", out)
  920. }
  921. if !strings.Contains(out, "fragment") {
  922. t.Fatalf("marshaled finalmask missing mask type: %s", out)
  923. }
  924. }
  925. func TestMarshalFinalMask_UnknownTypeIsDropped(t *testing.T) {
  926. fm := map[string]any{
  927. "tcp": []any{
  928. map[string]any{"type": "not-a-real-mask"},
  929. },
  930. }
  931. if _, ok := marshalFinalMask(fm); ok {
  932. t.Fatal("unknown mask types should be dropped, leaving nothing to marshal")
  933. }
  934. }
  935. func TestHasFinalMaskContent(t *testing.T) {
  936. if hasFinalMaskContent(nil) {
  937. t.Fatal("nil should not count as content")
  938. }
  939. if hasFinalMaskContent(map[string]any{}) {
  940. t.Fatal("empty map should not count as content")
  941. }
  942. if !hasFinalMaskContent(map[string]any{"x": 1}) {
  943. t.Fatal("non-empty map should count as content")
  944. }
  945. }
  946. func TestHysteriaPinHex(t *testing.T) {
  947. const hexPin = "c847dd2395d0978c0780b8201c4b289a8b281597d47c275f2d77d3f96d8de9c4"
  948. cases := []struct {
  949. name string
  950. in string
  951. want string
  952. }{
  953. // Std base64 (xray-core's native TLS format / the panel generate button)
  954. // must be re-encoded to the hex form Hysteria2 clients expect (#4818).
  955. {"std base64", "yEfdI5XQl4wHgLggHEsomosoFZfUfCdfLXfT+W2N6cQ=", hexPin},
  956. // A manually pasted hex fingerprint passes through (lowercased).
  957. {"hex passthrough", hexPin, hexPin},
  958. {"uppercase hex lowercased", strings.ToUpper(hexPin), hexPin},
  959. // openssl x509 -fingerprint -sha256 emits colon-separated hex.
  960. {"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},
  961. {"surrounding whitespace trimmed", " " + hexPin + " ", hexPin},
  962. // URL-safe base64 with the same 32 bytes decodes identically.
  963. {"url-safe base64", "yEfdI5XQl4wHgLggHEsomosoFZfUfCdfLXfT-W2N6cQ=", hexPin},
  964. // Garbage that is neither valid hex nor a 32-byte base64 is left as-is
  965. // rather than silently dropped.
  966. {"unrecognized passthrough", "not-a-pin", "not-a-pin"},
  967. {"empty", "", ""},
  968. }
  969. for _, tc := range cases {
  970. t.Run(tc.name, func(t *testing.T) {
  971. if got := hysteriaPinHex(tc.in); got != tc.want {
  972. t.Fatalf("hysteriaPinHex(%q) = %q, want %q", tc.in, got, tc.want)
  973. }
  974. })
  975. }
  976. }
  977. func TestHysteriaHopPorts(t *testing.T) {
  978. withHop := func(ports any) map[string]any {
  979. return map[string]any{
  980. "finalmask": map[string]any{
  981. "quicParams": map[string]any{
  982. "udpHop": map[string]any{"ports": ports, "interval": "5-10"},
  983. },
  984. },
  985. }
  986. }
  987. cases := []struct {
  988. name string
  989. stream map[string]any
  990. want string
  991. }{
  992. {"range", withHop("20000-50000"), "20000-50000"},
  993. {"trimmed", withHop(" 443,20000-50000 "), "443,20000-50000"},
  994. {"empty string", withHop(""), ""},
  995. {"non-string", withHop(float64(443)), ""},
  996. {"no udpHop", map[string]any{"finalmask": map[string]any{"quicParams": map[string]any{}}}, ""},
  997. {"no finalmask", map[string]any{}, ""},
  998. {"nil stream", nil, ""},
  999. }
  1000. for _, tc := range cases {
  1001. t.Run(tc.name, func(t *testing.T) {
  1002. if got := hysteriaHopPorts(tc.stream); got != tc.want {
  1003. t.Fatalf("hysteriaHopPorts() = %q, want %q", got, tc.want)
  1004. }
  1005. })
  1006. }
  1007. }