service_test.go 33 KB

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