service_test.go 41 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351
  1. package sub
  2. import (
  3. "encoding/base64"
  4. "encoding/json"
  5. "reflect"
  6. "strings"
  7. "testing"
  8. "github.com/mhsanaei/3x-ui/v3/internal/database/model"
  9. )
  10. func TestSubscriptionExpiryFromClient(t *testing.T) {
  11. const now = int64(1_700_000_000_000)
  12. const oneDayMs = int64(86_400_000)
  13. if got := subscriptionExpiryFromClient(now, 0); got != 0 {
  14. t.Fatalf("zero expiry should stay zero, got %d", got)
  15. }
  16. if got := subscriptionExpiryFromClient(now, 1_700_000_000_000); got != 1_700_000_000_000 {
  17. t.Fatalf("positive expiry should pass through, got %d", got)
  18. }
  19. if got := subscriptionExpiryFromClient(now, -oneDayMs); got != now+oneDayMs {
  20. t.Fatalf("delayed-start expiry should be now+|value|, got %d, want %d", got, now+oneDayMs)
  21. }
  22. if a, b := subscriptionExpiryFromClient(now, -oneDayMs), subscriptionExpiryFromClient(now, -oneDayMs); a != b {
  23. t.Fatalf("same now+value should be deterministic across calls, got %d vs %d (#4545 review)", a, b)
  24. }
  25. }
  26. // The name an admin gives a node is panel-internal and must not leak into
  27. // the remarks end users see in their client apps (#5231) — not even for
  28. // node-hosted inbounds, which briefly carried a node-name suffix (#5035).
  29. func TestGenRemarkOmitsNodeName(t *testing.T) {
  30. nodeID := 7
  31. s := &SubService{
  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. initSubDB(t)
  92. const reqHost = "sub.example.com"
  93. // A routable bind Listen (a real IP or hostname the operator set as the
  94. // inbound's advertised endpoint) becomes the link's connect host.
  95. t.Run("routable listen is advertised as the link host", func(t *testing.T) {
  96. s := &SubService{address: reqHost}
  97. for _, listen := range []string{"1.2.3.4", "10.0.0.5", "192.168.1.10", "203.0.113.7", "vpn.example.com"} {
  98. ib := &model.Inbound{Listen: listen}
  99. if got := s.resolveInboundAddress(ib); got != listen {
  100. t.Fatalf("listen %q: address = %q, want %q (advertised listen)", listen, got, listen)
  101. }
  102. }
  103. })
  104. // A loopback/wildcard bind or a unix-domain-socket listen is a
  105. // server-side detail and must never leak into the link host.
  106. t.Run("non-routable listen falls back to subscriber host", func(t *testing.T) {
  107. s := &SubService{address: reqHost}
  108. for _, listen := range []string{"", "0.0.0.0", "::", "::0", "127.0.0.1", "::1", "@fallback", "/run/x.sock"} {
  109. ib := &model.Inbound{Listen: listen}
  110. if got := s.resolveInboundAddress(ib); got != reqHost {
  111. t.Fatalf("listen %q: address = %q, want %q (subscriber host, not bind detail)", listen, got, reqHost)
  112. }
  113. }
  114. })
  115. t.Run("node-managed inbound uses the node address", func(t *testing.T) {
  116. id := 7
  117. s := &SubService{
  118. address: reqHost,
  119. nodesByID: map[int]*model.Node{7: {Id: 7, Address: "node7.example.com"}},
  120. }
  121. ib := &model.Inbound{NodeID: &id, Listen: "1.2.3.4"}
  122. if got := s.resolveInboundAddress(ib); got != "node7.example.com" {
  123. t.Fatalf("node-managed address = %q, want node7.example.com", got)
  124. }
  125. })
  126. t.Run("node id with no known node falls back to subscriber host", func(t *testing.T) {
  127. id := 9
  128. s := &SubService{address: reqHost, nodesByID: map[int]*model.Node{}}
  129. ib := &model.Inbound{NodeID: &id, Listen: "0.0.0.0"}
  130. if got := s.resolveInboundAddress(ib); got != reqHost {
  131. t.Fatalf("unknown-node address = %q, want subscriber host %q", got, reqHost)
  132. }
  133. })
  134. // Per-inbound share address strategy (#5208): subscriptions follow the
  135. // same order as the panel's share/QR links.
  136. t.Run("listen strategy prefers the bind over the node address", func(t *testing.T) {
  137. id := 7
  138. s := &SubService{
  139. address: reqHost,
  140. nodesByID: map[int]*model.Node{7: {Id: 7, Address: "node7.example.com"}},
  141. }
  142. ib := &model.Inbound{NodeID: &id, Listen: "203.0.113.7", ShareAddrStrategy: "listen"}
  143. if got := s.resolveInboundAddress(ib); got != "203.0.113.7" {
  144. t.Fatalf("listen-strategy address = %q, want the bind 203.0.113.7", got)
  145. }
  146. })
  147. t.Run("listen strategy falls back to node address on a wildcard bind", func(t *testing.T) {
  148. id := 7
  149. s := &SubService{
  150. address: reqHost,
  151. nodesByID: map[int]*model.Node{7: {Id: 7, Address: "node7.example.com"}},
  152. }
  153. ib := &model.Inbound{NodeID: &id, Listen: "0.0.0.0", ShareAddrStrategy: "listen"}
  154. if got := s.resolveInboundAddress(ib); got != "node7.example.com" {
  155. t.Fatalf("listen-strategy wildcard address = %q, want node7.example.com", got)
  156. }
  157. })
  158. t.Run("custom strategy uses the share address", func(t *testing.T) {
  159. id := 7
  160. s := &SubService{
  161. address: reqHost,
  162. nodesByID: map[int]*model.Node{7: {Id: 7, Address: "node7.example.com"}},
  163. }
  164. ib := &model.Inbound{NodeID: &id, Listen: "203.0.113.7", ShareAddrStrategy: "custom", ShareAddr: "edge.example.com"}
  165. if got := s.resolveInboundAddress(ib); got != "edge.example.com" {
  166. t.Fatalf("custom-strategy address = %q, want edge.example.com", got)
  167. }
  168. })
  169. t.Run("custom strategy with empty share address falls back to node", func(t *testing.T) {
  170. id := 7
  171. s := &SubService{
  172. address: reqHost,
  173. nodesByID: map[int]*model.Node{7: {Id: 7, Address: "node7.example.com"}},
  174. }
  175. ib := &model.Inbound{NodeID: &id, ShareAddrStrategy: "custom"}
  176. if got := s.resolveInboundAddress(ib); got != "node7.example.com" {
  177. t.Fatalf("custom-strategy fallback address = %q, want node7.example.com", got)
  178. }
  179. })
  180. t.Run("node strategy keeps the pre-strategy order", func(t *testing.T) {
  181. id := 7
  182. s := &SubService{
  183. address: reqHost,
  184. nodesByID: map[int]*model.Node{7: {Id: 7, Address: "node7.example.com"}},
  185. }
  186. ib := &model.Inbound{NodeID: &id, Listen: "203.0.113.7", ShareAddrStrategy: "node"}
  187. if got := s.resolveInboundAddress(ib); got != "node7.example.com" {
  188. t.Fatalf("node-strategy address = %q, want node7.example.com", got)
  189. }
  190. })
  191. }
  192. func TestUnmarshalStreamSettings(t *testing.T) {
  193. got := unmarshalStreamSettings(`{"network":"ws","wsSettings":{"path":"/api"}}`)
  194. if got["network"] != "ws" {
  195. t.Fatalf("network = %v, want ws", got["network"])
  196. }
  197. ws, ok := got["wsSettings"].(map[string]any)
  198. if !ok || ws["path"] != "/api" {
  199. t.Fatalf("wsSettings = %v, want map with path=/api", got["wsSettings"])
  200. }
  201. }
  202. func TestUnmarshalStreamSettings_InvalidJSON(t *testing.T) {
  203. if got := unmarshalStreamSettings("not json"); got != nil {
  204. t.Fatalf("invalid JSON should produce nil map, got %#v", got)
  205. }
  206. }
  207. func TestSearchHost_StringValue(t *testing.T) {
  208. headers := map[string]any{"Host": "example.com"}
  209. if got := searchHost(headers); got != "example.com" {
  210. t.Fatalf("searchHost = %q, want example.com", got)
  211. }
  212. }
  213. func TestSearchHost_CaseInsensitiveKey(t *testing.T) {
  214. headers := map[string]any{"host": "example.com"}
  215. if got := searchHost(headers); got != "example.com" {
  216. t.Fatalf("searchHost = %q, want example.com", got)
  217. }
  218. headers2 := map[string]any{"HOST": "example.com"}
  219. if got := searchHost(headers2); got != "example.com" {
  220. t.Fatalf("searchHost uppercase = %q, want example.com", got)
  221. }
  222. }
  223. func TestSearchHost_ArrayValue(t *testing.T) {
  224. headers := map[string]any{"Host": []any{"first.example.com", "second.example.com"}}
  225. if got := searchHost(headers); got != "first.example.com" {
  226. t.Fatalf("searchHost array = %q, want first.example.com", got)
  227. }
  228. }
  229. func TestSearchHost_EmptyArray(t *testing.T) {
  230. headers := map[string]any{"Host": []any{}}
  231. if got := searchHost(headers); got != "" {
  232. t.Fatalf("searchHost empty array = %q, want empty", got)
  233. }
  234. }
  235. func TestSearchHost_NoHostKey(t *testing.T) {
  236. headers := map[string]any{"X-Other": "value"}
  237. if got := searchHost(headers); got != "" {
  238. t.Fatalf("searchHost no host = %q, want empty", got)
  239. }
  240. }
  241. func TestSearchHost_NotAMap(t *testing.T) {
  242. if got := searchHost("not a map"); got != "" {
  243. t.Fatalf("searchHost non-map = %q, want empty", got)
  244. }
  245. if got := searchHost(nil); got != "" {
  246. t.Fatalf("searchHost nil = %q, want empty", got)
  247. }
  248. }
  249. func TestSearchKey_FoundAtTopLevel(t *testing.T) {
  250. data := map[string]any{"foo": 42, "bar": "x"}
  251. got, ok := searchKey(data, "foo")
  252. if !ok {
  253. t.Fatal("expected to find foo")
  254. }
  255. if got != 42 {
  256. t.Fatalf("got %v, want 42", got)
  257. }
  258. }
  259. func TestSearchKey_FoundInNested(t *testing.T) {
  260. data := map[string]any{
  261. "outer": map[string]any{
  262. "inner": map[string]any{
  263. "target": "hit",
  264. },
  265. },
  266. }
  267. got, ok := searchKey(data, "target")
  268. if !ok {
  269. t.Fatal("expected to find target in nested map")
  270. }
  271. if got != "hit" {
  272. t.Fatalf("got %v, want hit", got)
  273. }
  274. }
  275. func TestSearchKey_FoundInsideArray(t *testing.T) {
  276. data := map[string]any{
  277. "list": []any{
  278. map[string]any{"other": 1},
  279. map[string]any{"needle": "found"},
  280. },
  281. }
  282. got, ok := searchKey(data, "needle")
  283. if !ok {
  284. t.Fatal("expected to find needle in array element")
  285. }
  286. if got != "found" {
  287. t.Fatalf("got %v, want found", got)
  288. }
  289. }
  290. func TestSearchKey_NotFound(t *testing.T) {
  291. data := map[string]any{"foo": "bar"}
  292. if _, ok := searchKey(data, "missing"); ok {
  293. t.Fatal("expected ok=false for missing key")
  294. }
  295. }
  296. func TestSearchKey_OnScalar(t *testing.T) {
  297. if _, ok := searchKey(42, "anything"); ok {
  298. t.Fatal("expected ok=false searching on a scalar")
  299. }
  300. }
  301. func TestBuildXhttpExtra_IncludesClientSideFieldsWhenPresent(t *testing.T) {
  302. extra := buildXhttpExtra(map[string]any{
  303. "path": "/xhttp",
  304. "host": "example.com",
  305. "mode": "packet-up",
  306. "xPaddingBytes": "100-1000",
  307. "uplinkHTTPMethod": "GET",
  308. "sessionIDPlacement": "header",
  309. "sessionIDKey": "X-Session",
  310. "uplinkChunkSize": float64(4096),
  311. "noGRPCHeader": true,
  312. "scMinPostsIntervalMs": "20-40",
  313. "xmux": map[string]any{
  314. "maxConcurrency": "16-32",
  315. "hMaxRequestTimes": "600-900",
  316. "hMaxReusableSecs": "1800-3000",
  317. "hKeepAlivePeriod": float64(15),
  318. },
  319. "downloadSettings": map[string]any{
  320. "network": "xhttp",
  321. },
  322. "headers": map[string]any{
  323. "Host": "ignored.example.com",
  324. "X-Forwarded": "1",
  325. "X-Test-Empty": "",
  326. },
  327. })
  328. if extra["path"] != nil || extra["host"] != nil {
  329. t.Fatalf("path/host should stay top-level, got extra %#v", extra)
  330. }
  331. for _, key := range []string{
  332. "xPaddingBytes",
  333. "uplinkHTTPMethod",
  334. "uplinkChunkSize",
  335. "noGRPCHeader",
  336. "scMinPostsIntervalMs",
  337. "xmux",
  338. "downloadSettings",
  339. } {
  340. if _, ok := extra[key]; !ok {
  341. t.Fatalf("extra missing %q: %#v", key, extra)
  342. }
  343. }
  344. // mode rides inside extra (in addition to the flat param) so clients
  345. // that only read the extra JSON keep the xhttp mode (#5446).
  346. if extra["mode"] != "packet-up" {
  347. t.Fatalf("extra[mode] = %#v, want packet-up", extra["mode"])
  348. }
  349. for key, want := range map[string]string{
  350. "sessionIDPlacement": "header",
  351. "sessionIDKey": "X-Session",
  352. "sessionPlacement": "header",
  353. "sessionKey": "X-Session",
  354. } {
  355. if extra[key] != want {
  356. t.Fatalf("extra[%s] = %#v, want %q; extra %#v", key, extra[key], want, extra)
  357. }
  358. }
  359. headers, ok := extra["headers"].(map[string]any)
  360. if !ok {
  361. t.Fatalf("headers = %#v, want map", extra["headers"])
  362. }
  363. if _, ok := headers["Host"]; ok {
  364. t.Fatalf("headers should not include Host: %#v", headers)
  365. }
  366. if headers["X-Forwarded"] != "1" {
  367. t.Fatalf("headers[X-Forwarded] = %#v, want 1", headers["X-Forwarded"])
  368. }
  369. }
  370. func TestBuildXhttpExtra_LegacySessionFieldsEmitBothNames(t *testing.T) {
  371. extra := buildXhttpExtra(map[string]any{
  372. "sessionPlacement": "query",
  373. "sessionKey": "sess",
  374. })
  375. for key, want := range map[string]string{
  376. "sessionIDPlacement": "query",
  377. "sessionIDKey": "sess",
  378. "sessionPlacement": "query",
  379. "sessionKey": "sess",
  380. } {
  381. if extra[key] != want {
  382. t.Fatalf("extra[%s] = %#v, want %q; extra %#v", key, extra[key], want, extra)
  383. }
  384. }
  385. }
  386. func TestBuildXhttpExtra_LeavesDefaultClientSideFieldsOut(t *testing.T) {
  387. extra := buildXhttpExtra(map[string]any{
  388. "uplinkHTTPMethod": "",
  389. "uplinkChunkSize": float64(0),
  390. "noGRPCHeader": false,
  391. "xmux": map[string]any{},
  392. "downloadSettings": map[string]any{},
  393. })
  394. if extra != nil {
  395. t.Fatalf("default-only xhttp extra = %#v, want nil", extra)
  396. }
  397. }
  398. func TestCloneStringMap(t *testing.T) {
  399. src := map[string]string{"a": "1", "b": "2"}
  400. dst := cloneStringMap(src)
  401. if len(dst) != len(src) {
  402. t.Fatalf("clone length = %d, want %d", len(dst), len(src))
  403. }
  404. for k, v := range src {
  405. if dst[k] != v {
  406. t.Fatalf("clone[%q] = %q, want %q", k, dst[k], v)
  407. }
  408. }
  409. dst["a"] = "changed"
  410. if src["a"] == "changed" {
  411. t.Fatal("modifying clone leaked into source")
  412. }
  413. }
  414. func TestCloneStringMap_Empty(t *testing.T) {
  415. dst := cloneStringMap(map[string]string{})
  416. if dst == nil {
  417. t.Fatal("clone of empty map should not be nil")
  418. }
  419. if len(dst) != 0 {
  420. t.Fatalf("clone of empty map should be empty, got %v", dst)
  421. }
  422. }
  423. func TestJoinHostPort(t *testing.T) {
  424. cases := []struct {
  425. host string
  426. port int
  427. want string
  428. }{
  429. {"example.com", 443, "example.com:443"},
  430. {"1.2.3.4", 443, "1.2.3.4:443"},
  431. {"2001:db8::1", 443, "[2001:db8::1]:443"},
  432. {"[2001:db8::1]", 443, "[2001:db8::1]:443"},
  433. {"2001:db8::1", 8080, "[2001:db8::1]:8080"},
  434. }
  435. for _, c := range cases {
  436. if got := joinHostPort(c.host, c.port); got != c.want {
  437. t.Fatalf("joinHostPort(%q, %d) = %q, want %q", c.host, c.port, got, c.want)
  438. }
  439. }
  440. }
  441. func TestGetHostFromXFH_HostOnly(t *testing.T) {
  442. got, err := getHostFromXFH("example.com")
  443. if err != nil {
  444. t.Fatalf("unexpected error: %v", err)
  445. }
  446. if got != "example.com" {
  447. t.Fatalf("got %q, want example.com", got)
  448. }
  449. }
  450. func TestGetHostFromXFH_HostWithPort(t *testing.T) {
  451. got, err := getHostFromXFH("example.com:8443")
  452. if err != nil {
  453. t.Fatalf("unexpected error: %v", err)
  454. }
  455. if got != "example.com" {
  456. t.Fatalf("got %q, want example.com", got)
  457. }
  458. }
  459. func TestGetHostFromXFH_IPv6WithPort(t *testing.T) {
  460. got, err := getHostFromXFH("[2606:4700::1111]:443")
  461. if err != nil {
  462. t.Fatalf("unexpected error: %v", err)
  463. }
  464. if got != "2606:4700::1111" {
  465. t.Fatalf("got %q, want 2606:4700::1111", got)
  466. }
  467. }
  468. func TestGetHostFromXFH_BadHostPort(t *testing.T) {
  469. if _, err := getHostFromXFH("example.com:8443:9999"); err == nil {
  470. t.Fatal("expected error for malformed host:port")
  471. }
  472. }
  473. func TestReadPositiveInt(t *testing.T) {
  474. cases := []struct {
  475. name string
  476. in any
  477. wantVal int
  478. wantOk bool
  479. }{
  480. {"int_positive", int(5), 5, true},
  481. {"int_zero", int(0), 0, false},
  482. {"int_negative", int(-3), -3, false},
  483. {"int32_positive", int32(7), 7, true},
  484. {"int64_positive", int64(99), 99, true},
  485. {"float64_positive", float64(12), 12, true},
  486. {"float64_zero", float64(0.0), 0, false},
  487. {"float64_negative", float64(-1.5), -1, false},
  488. {"float32_positive", float32(3), 3, true},
  489. {"string", "not a number", 0, false},
  490. {"nil", nil, 0, false},
  491. }
  492. for _, c := range cases {
  493. t.Run(c.name, func(t *testing.T) {
  494. gotVal, gotOk := readPositiveInt(c.in)
  495. if gotVal != c.wantVal || gotOk != c.wantOk {
  496. t.Fatalf("readPositiveInt(%v) = (%d, %v), want (%d, %v)", c.in, gotVal, gotOk, c.wantVal, c.wantOk)
  497. }
  498. })
  499. }
  500. }
  501. func TestSetStringParam(t *testing.T) {
  502. p := map[string]string{"existing": "value"}
  503. setStringParam(p, "new", "hello")
  504. if p["new"] != "hello" {
  505. t.Fatalf("missing key after set: %v", p)
  506. }
  507. setStringParam(p, "existing", "")
  508. if _, ok := p["existing"]; ok {
  509. t.Fatalf("empty value should delete the key, got %v", p)
  510. }
  511. }
  512. func TestSetIntParam(t *testing.T) {
  513. p := map[string]string{"existing": "10"}
  514. setIntParam(p, "n", 42)
  515. if p["n"] != "42" {
  516. t.Fatalf("set positive int: got %v", p)
  517. }
  518. setIntParam(p, "existing", 0)
  519. if _, ok := p["existing"]; ok {
  520. t.Fatalf("zero value should delete the key, got %v", p)
  521. }
  522. p["other"] = "5"
  523. setIntParam(p, "other", -1)
  524. if _, ok := p["other"]; ok {
  525. t.Fatalf("negative value should delete the key, got %v", p)
  526. }
  527. }
  528. func TestSetStringField(t *testing.T) {
  529. f := map[string]any{"existing": "value"}
  530. setStringField(f, "new", "hello")
  531. if f["new"] != "hello" {
  532. t.Fatalf("missing key after set: %v", f)
  533. }
  534. setStringField(f, "existing", "")
  535. if _, ok := f["existing"]; ok {
  536. t.Fatalf("empty value should delete the key, got %v", f)
  537. }
  538. }
  539. func TestSetIntField(t *testing.T) {
  540. f := map[string]any{"existing": 10}
  541. setIntField(f, "n", 7)
  542. if f["n"] != 7 {
  543. t.Fatalf("set positive int: got %v", f)
  544. }
  545. setIntField(f, "existing", 0)
  546. if _, ok := f["existing"]; ok {
  547. t.Fatalf("zero value should delete the key, got %v", f)
  548. }
  549. }
  550. func TestBuildVmessLink(t *testing.T) {
  551. obj := map[string]any{
  552. "v": "2",
  553. "ps": "remark",
  554. "add": "example.com",
  555. "port": 443,
  556. "net": "tcp",
  557. }
  558. link := buildVmessLink(obj)
  559. if !strings.HasPrefix(link, "vmess://") {
  560. t.Fatalf("missing vmess:// prefix: %q", link)
  561. }
  562. payload := strings.TrimPrefix(link, "vmess://")
  563. decoded, err := base64.StdEncoding.DecodeString(payload)
  564. if err != nil {
  565. t.Fatalf("base64 decode failed: %v", err)
  566. }
  567. var roundTrip map[string]any
  568. if err := json.Unmarshal(decoded, &roundTrip); err != nil {
  569. t.Fatalf("decoded payload is not JSON: %v\n%s", err, decoded)
  570. }
  571. if roundTrip["add"] != "example.com" {
  572. t.Fatalf("round-trip add = %v, want example.com", roundTrip["add"])
  573. }
  574. if roundTrip["ps"] != "remark" {
  575. t.Fatalf("round-trip ps = %v, want remark", roundTrip["ps"])
  576. }
  577. }
  578. func TestCloneVmessShareObj_CopiesEverythingByDefault(t *testing.T) {
  579. base := map[string]any{
  580. "v": "2",
  581. "sni": "example.com",
  582. "alpn": "h2",
  583. "fp": "chrome",
  584. "net": "tcp",
  585. }
  586. out := cloneVmessShareObj(base, "tls")
  587. for _, key := range []string{"sni", "alpn", "fp", "net", "v"} {
  588. if _, ok := out[key]; !ok {
  589. t.Fatalf("expected key %q to be preserved when security=tls, got %v", key, out)
  590. }
  591. }
  592. }
  593. func TestCloneVmessShareObj_NoneStripsTLSOnlyKeys(t *testing.T) {
  594. base := map[string]any{
  595. "v": "2",
  596. "sni": "example.com",
  597. "alpn": "h2",
  598. "fp": "chrome",
  599. "net": "tcp",
  600. }
  601. out := cloneVmessShareObj(base, "none")
  602. for _, key := range []string{"sni", "alpn", "fp"} {
  603. if _, ok := out[key]; ok {
  604. t.Fatalf("security=none should strip %q, got %v", key, out)
  605. }
  606. }
  607. if out["v"] != "2" || out["net"] != "tcp" {
  608. t.Fatalf("non-TLS keys should remain, got %v", out)
  609. }
  610. }
  611. func TestApplyExternalProxyTLSParams_UsesProxyDomainAndOverrides(t *testing.T) {
  612. params := map[string]string{
  613. "security": "tls",
  614. "sni": "origin.example.com",
  615. "fp": "firefox",
  616. "alpn": "h2",
  617. }
  618. ep := map[string]any{
  619. "dest": "proxy.example.com",
  620. "sni": "tls.example.com",
  621. "fingerprint": "chrome",
  622. "alpn": []any{"h3", "h2"},
  623. }
  624. applyExternalProxyTLSParams(ep, params, "tls")
  625. if params["sni"] != "tls.example.com" {
  626. t.Fatalf("sni = %q, want tls.example.com", params["sni"])
  627. }
  628. if params["fp"] != "chrome" {
  629. t.Fatalf("fp = %q, want chrome", params["fp"])
  630. }
  631. if params["alpn"] != "h3,h2" {
  632. t.Fatalf("alpn = %q, want h3,h2", params["alpn"])
  633. }
  634. }
  635. func TestApplyExternalProxyTLSParams_PreservesUpstreamSNI(t *testing.T) {
  636. // External-proxy entry has no SNI of its own; its dest must not
  637. // clobber the upstream tlsSettings.serverName already written into
  638. // params. Regression: the dest fallback used to overwrite "222" with
  639. // "111" whenever an operator set forceTls=same and left the proxy's
  640. // SNI field blank.
  641. params := map[string]string{"security": "tls", "sni": "real.example.com"}
  642. ep := map[string]any{"dest": "proxy.example.com"}
  643. applyExternalProxyTLSParams(ep, params, "tls")
  644. if params["sni"] != "real.example.com" {
  645. t.Fatalf("sni = %q, want upstream sni preserved (real.example.com)", params["sni"])
  646. }
  647. }
  648. func TestApplyExternalProxyTLSParams_ExplicitSNIOverridesUpstream(t *testing.T) {
  649. params := map[string]string{"security": "tls", "sni": "real.example.com"}
  650. ep := map[string]any{"dest": "proxy.example.com", "sni": "edge.example.com"}
  651. applyExternalProxyTLSParams(ep, params, "tls")
  652. if params["sni"] != "edge.example.com" {
  653. t.Fatalf("sni = %q, want edge.example.com", params["sni"])
  654. }
  655. }
  656. func TestApplyExternalProxy_ECHPropagates(t *testing.T) {
  657. const ech = "ech-config-base64"
  658. t.Run("url params", func(t *testing.T) {
  659. params := map[string]string{"security": "tls"}
  660. ep := map[string]any{"dest": "proxy.example.com", "echConfigList": ech}
  661. applyExternalProxyTLSParams(ep, params, "tls")
  662. if params["ech"] != ech {
  663. t.Fatalf("ech param = %q, want %q", params["ech"], ech)
  664. }
  665. })
  666. t.Run("vmess obj", func(t *testing.T) {
  667. obj := map[string]any{}
  668. ep := map[string]any{"dest": "proxy.example.com", "echConfigList": ech}
  669. applyExternalProxyTLSObj(ep, obj, "tls")
  670. if obj["ech"] != ech {
  671. t.Fatalf("ech obj = %v, want %q", obj["ech"], ech)
  672. }
  673. })
  674. t.Run("json stream settings", func(t *testing.T) {
  675. stream := map[string]any{"security": "tls", "tlsSettings": map[string]any{}}
  676. ep := map[string]any{"dest": "proxy.example.com", "echConfigList": ech}
  677. applyExternalProxyTLSToStream(ep, stream, "tls")
  678. settings, _ := stream["tlsSettings"].(map[string]any)["settings"].(map[string]any)
  679. if settings["echConfigList"] != ech {
  680. t.Fatalf("echConfigList = %v, want %q", settings["echConfigList"], ech)
  681. }
  682. })
  683. t.Run("non-tls security drops ech", func(t *testing.T) {
  684. params := map[string]string{}
  685. ep := map[string]any{"echConfigList": ech}
  686. applyExternalProxyTLSParams(ep, params, "none")
  687. if _, ok := params["ech"]; ok {
  688. t.Fatalf("ech must not be set when security != tls")
  689. }
  690. })
  691. }
  692. func TestApplyExternalProxyTLSToStream_DoesNotLeakAcrossProxies(t *testing.T) {
  693. stream := map[string]any{
  694. "security": "tls",
  695. "tlsSettings": map[string]any{
  696. "serverName": "upstream.example.com",
  697. },
  698. }
  699. proxies := []map[string]any{
  700. {"dest": "a.example.com", "sni": "a-sni.example.com", "fingerprint": "chrome", "alpn": []any{"h3"}},
  701. {"dest": "b.example.com"},
  702. }
  703. results := make([]map[string]any, 0, len(proxies))
  704. for _, ep := range proxies {
  705. working := cloneStreamForExternalProxy(stream)
  706. applyExternalProxyTLSToStream(ep, working, "tls")
  707. ts := working["tlsSettings"].(map[string]any)
  708. snapshot := map[string]any{
  709. "serverName": ts["serverName"],
  710. "fingerprint": ts["fingerprint"],
  711. "alpn": ts["alpn"],
  712. }
  713. results = append(results, snapshot)
  714. }
  715. if results[0]["serverName"] != "a-sni.example.com" || results[0]["fingerprint"] != "chrome" {
  716. t.Fatalf("proxy A snapshot = %v", results[0])
  717. }
  718. // Proxy B has no SNI of its own — the upstream tlsSettings serverName
  719. // must remain in place (no dest fallback) and no fingerprint/alpn
  720. // must leak from proxy A.
  721. if results[1]["serverName"] != "upstream.example.com" {
  722. t.Fatalf("proxy B serverName = %v, want upstream.example.com preserved", results[1]["serverName"])
  723. }
  724. if results[1]["fingerprint"] != nil {
  725. t.Fatalf("proxy B should inherit no fingerprint, got %v (leaked from A)", results[1]["fingerprint"])
  726. }
  727. if results[1]["alpn"] != nil {
  728. t.Fatalf("proxy B should inherit no alpn, got %v (leaked from A)", results[1]["alpn"])
  729. }
  730. }
  731. func TestApplyExternalProxyTLSToStream_FingerprintNotDuplicated(t *testing.T) {
  732. stream := map[string]any{
  733. "security": "tls",
  734. "tlsSettings": map[string]any{},
  735. }
  736. ep := map[string]any{"dest": "proxy.example.com", "fingerprint": "chrome"}
  737. applyExternalProxyTLSToStream(ep, stream, "tls")
  738. ts, _ := stream["tlsSettings"].(map[string]any)
  739. if ts["fingerprint"] != "chrome" {
  740. t.Fatalf("tlsSettings.fingerprint = %v, want %q", ts["fingerprint"], "chrome")
  741. }
  742. if settings, ok := ts["settings"].(map[string]any); ok {
  743. if got, dup := settings["fingerprint"]; dup {
  744. t.Fatalf("fingerprint must not be duplicated into tlsSettings.settings, got %v", got)
  745. }
  746. }
  747. }
  748. func TestApplyExternalProxyTLSParams_SetsPinnedPeerCert(t *testing.T) {
  749. params := map[string]string{"security": "tls"}
  750. ep := map[string]any{
  751. "dest": "proxy.example.com",
  752. "pinnedPeerCertSha256": []any{"aa11", "bb22"},
  753. }
  754. applyExternalProxyTLSParams(ep, params, "tls")
  755. if params["pcs"] != "aa11,bb22" {
  756. t.Fatalf("pcs = %q, want aa11,bb22", params["pcs"])
  757. }
  758. }
  759. func TestApplyExternalProxyTLSObj_SetsPinnedPeerCert(t *testing.T) {
  760. obj := map[string]any{"tls": "tls"}
  761. ep := map[string]any{
  762. "dest": "proxy.example.com",
  763. "pinnedPeerCertSha256": []any{"aa11"},
  764. }
  765. applyExternalProxyTLSObj(ep, obj, "tls")
  766. if obj["pcs"] != "aa11" {
  767. t.Fatalf("pcs = %v, want aa11", obj["pcs"])
  768. }
  769. }
  770. func TestApplyExternalProxyTLSToStream_SetsPinnedPeerCert(t *testing.T) {
  771. stream := map[string]any{
  772. "security": "tls",
  773. "tlsSettings": map[string]any{"serverName": "upstream.example.com"},
  774. }
  775. ep := map[string]any{"dest": "edge.example.com", "pinnedPeerCertSha256": []any{"aa11", "bb22"}}
  776. working := cloneStreamForExternalProxy(stream)
  777. applyExternalProxyTLSToStream(ep, working, "tls")
  778. ts := working["tlsSettings"].(map[string]any)
  779. settings, _ := ts["settings"].(map[string]any)
  780. pins, ok := settings["pinnedPeerCertSha256"].([]any)
  781. if !ok || len(pins) != 2 || pins[0] != "aa11" || pins[1] != "bb22" {
  782. t.Fatalf("pinnedPeerCertSha256 = %v, want [aa11 bb22]", settings["pinnedPeerCertSha256"])
  783. }
  784. }
  785. func TestApplyExternalProxyHysteriaParams_PinIsHexNormalized(t *testing.T) {
  786. // base64 SHA-256 pin must come out as bare lowercase hex for Hysteria's
  787. // pinSHA256, which other (pcs) protocols leave untouched.
  788. params := map[string]string{"security": "tls", "sni": "server.example.com"}
  789. ep := map[string]any{
  790. "dest": "edge.example.com",
  791. "pinnedPeerCertSha256": []any{"yEfdI5XQl4wHgLggHEsomosoFZfUfCdfLXfT+W2N6cQ="},
  792. }
  793. applyExternalProxyHysteriaParams(ep, params)
  794. if params["pinSHA256"] != "c847dd2395d0978c0780b8201c4b289a8b281597d47c275f2d77d3f96d8de9c4" {
  795. t.Fatalf("pinSHA256 = %q, want hex-normalized pin", params["pinSHA256"])
  796. }
  797. if _, ok := params["pcs"]; ok {
  798. t.Fatalf("pcs must not be set for Hysteria, got %v", params)
  799. }
  800. if params["sni"] != "server.example.com" {
  801. t.Fatalf("sni = %q, want inbound sni preserved (no override for Hysteria)", params["sni"])
  802. }
  803. }
  804. func TestApplyExternalProxyHysteriaParams_NoPinLeavesMainPin(t *testing.T) {
  805. params := map[string]string{"security": "tls", "pinSHA256": "deadbeef"}
  806. ep := map[string]any{"dest": "edge.example.com"}
  807. applyExternalProxyHysteriaParams(ep, params)
  808. if params["pinSHA256"] != "deadbeef" {
  809. t.Fatalf("pinSHA256 = %q, want main pin preserved when proxy has none", params["pinSHA256"])
  810. }
  811. }
  812. func TestApplyExternalProxyTLSParams_DoesNotApplyForNone(t *testing.T) {
  813. params := map[string]string{
  814. "security": "none",
  815. "sni": "origin.example.com",
  816. }
  817. ep := map[string]any{
  818. "dest": "proxy.example.com",
  819. "fingerprint": "chrome",
  820. "alpn": []any{"h3"},
  821. }
  822. applyExternalProxyTLSParams(ep, params, "none")
  823. if params["sni"] != "origin.example.com" {
  824. t.Fatalf("sni should not change for security=none, got %q", params["sni"])
  825. }
  826. if _, ok := params["fp"]; ok {
  827. t.Fatalf("fp should not be set for security=none, got %v", params)
  828. }
  829. if _, ok := params["alpn"]; ok {
  830. t.Fatalf("alpn should not be set for security=none, got %v", params)
  831. }
  832. }
  833. func TestExtractKcpShareFields_Defaults(t *testing.T) {
  834. stream := map[string]any{}
  835. got := extractKcpShareFields(stream)
  836. if got.headerType != "none" {
  837. t.Fatalf("default headerType = %q, want none", got.headerType)
  838. }
  839. if got.seed != "" || got.mtu != 0 || got.tti != 0 {
  840. t.Fatalf("default kcpShareFields should be zero except headerType, got %+v", got)
  841. }
  842. }
  843. func TestExtractKcpShareFields_ReadsAllFields(t *testing.T) {
  844. stream := map[string]any{
  845. "kcpSettings": map[string]any{
  846. "header": map[string]any{"type": "wechat-video"},
  847. "seed": "secret-seed",
  848. "mtu": float64(1350),
  849. "tti": float64(50),
  850. },
  851. }
  852. got := extractKcpShareFields(stream)
  853. if got.headerType != "wechat-video" {
  854. t.Fatalf("headerType = %q, want wechat-video", got.headerType)
  855. }
  856. if got.seed != "secret-seed" {
  857. t.Fatalf("seed = %q, want secret-seed", got.seed)
  858. }
  859. if got.mtu != 1350 {
  860. t.Fatalf("mtu = %d, want 1350", got.mtu)
  861. }
  862. if got.tti != 50 {
  863. t.Fatalf("tti = %d, want 50", got.tti)
  864. }
  865. }
  866. func TestExtractKcpShareFields_FinalMaskLegacyHeader(t *testing.T) {
  867. stream := map[string]any{
  868. "finalmask": map[string]any{
  869. "udp": []any{
  870. map[string]any{
  871. "type": "mkcp-legacy",
  872. "settings": map[string]any{"header": "wechat", "value": ""},
  873. },
  874. },
  875. },
  876. }
  877. got := extractKcpShareFields(stream)
  878. if got.headerType != "wechat-video" {
  879. t.Fatalf("headerType = %q, want wechat-video", got.headerType)
  880. }
  881. if got.seed != "" {
  882. t.Fatalf("seed = %q, want empty for header mask", got.seed)
  883. }
  884. }
  885. func TestExtractKcpShareFields_FinalMaskLegacySeed(t *testing.T) {
  886. stream := map[string]any{
  887. "finalmask": map[string]any{
  888. "udp": []any{
  889. map[string]any{
  890. "type": "mkcp-legacy",
  891. "settings": map[string]any{"header": "", "value": "obfs-pass"},
  892. },
  893. },
  894. },
  895. }
  896. got := extractKcpShareFields(stream)
  897. if got.headerType != "none" {
  898. t.Fatalf("headerType = %q, want none for empty-header legacy mask", got.headerType)
  899. }
  900. if got.seed != "obfs-pass" {
  901. t.Fatalf("seed = %q, want obfs-pass", got.seed)
  902. }
  903. }
  904. func TestKcpShareFields_ApplyToParams(t *testing.T) {
  905. params := map[string]string{}
  906. kcpShareFields{headerType: "wechat-video", seed: "s", mtu: 1350, tti: 50}.applyToParams(params)
  907. if params["headerType"] != "wechat-video" {
  908. t.Fatalf("headerType param = %q", params["headerType"])
  909. }
  910. if params["seed"] != "s" {
  911. t.Fatalf("seed param = %q", params["seed"])
  912. }
  913. if params["mtu"] != "1350" {
  914. t.Fatalf("mtu param = %q", params["mtu"])
  915. }
  916. if params["tti"] != "50" {
  917. t.Fatalf("tti param = %q", params["tti"])
  918. }
  919. }
  920. func TestKcpShareFields_ApplyToParams_NoneHeaderNotAdded(t *testing.T) {
  921. params := map[string]string{}
  922. kcpShareFields{headerType: "none"}.applyToParams(params)
  923. if _, ok := params["headerType"]; ok {
  924. t.Fatalf("headerType=none should not be added, got %v", params)
  925. }
  926. }
  927. func TestMarshalFinalMask_EmptyReturnsFalse(t *testing.T) {
  928. if _, ok := marshalFinalMask(map[string]any{}); ok {
  929. t.Fatal("expected ok=false for empty finalmask")
  930. }
  931. if _, ok := marshalFinalMask(nil); ok {
  932. t.Fatal("expected ok=false for nil finalmask")
  933. }
  934. }
  935. func TestMarshalFinalMask_WithContent(t *testing.T) {
  936. fm := map[string]any{
  937. "tcp": []any{
  938. map[string]any{"type": "fragment"},
  939. },
  940. }
  941. out, ok := marshalFinalMask(fm)
  942. if !ok {
  943. t.Fatal("expected ok=true for finalmask with valid tcp mask")
  944. }
  945. if !strings.Contains(out, `"tcp"`) {
  946. t.Fatalf("marshaled finalmask missing tcp key: %s", out)
  947. }
  948. if !strings.Contains(out, "fragment") {
  949. t.Fatalf("marshaled finalmask missing mask type: %s", out)
  950. }
  951. }
  952. func TestMarshalFinalMaskAddsLegacyFragmentRanges(t *testing.T) {
  953. lengths := []any{"5-10", "10-15", "15-20", "20-25", "25-30"}
  954. delays := []any{"10-20", "5-20", "5-25", "15-25", "10-30"}
  955. screenshotSettings := map[string]any{
  956. "packets": "tlshello",
  957. "lengths": lengths,
  958. "delays": delays,
  959. "maxSplit": "10-15",
  960. }
  961. explicitSettings := map[string]any{
  962. "length": "1-2",
  963. "lengths": []any{"8-9"},
  964. "delay": "3-4",
  965. "delays": []any{"6-7"},
  966. }
  967. emptySettings := map[string]any{
  968. "lengths": []any{},
  969. "delays": []any{},
  970. }
  971. legacyOnlySettings := map[string]any{"length": "40-50", "delay": "10-20"}
  972. otherSettings := map[string]any{"lengths": []any{"30-40"}}
  973. fm := map[string]any{
  974. "tcp": []any{
  975. map[string]any{"type": "fragment", "settings": screenshotSettings},
  976. map[string]any{"type": "fragment", "settings": explicitSettings},
  977. map[string]any{"type": "fragment", "settings": emptySettings},
  978. map[string]any{"type": "fragment", "settings": legacyOnlySettings},
  979. map[string]any{"type": "sudoku", "settings": otherSettings},
  980. },
  981. }
  982. original, err := json.Marshal(fm)
  983. if err != nil {
  984. t.Fatalf("marshal input finalmask: %v", err)
  985. }
  986. encoded, ok := marshalFinalMask(fm)
  987. if !ok {
  988. t.Fatal("expected finalmask with fragment masks to be marshaled")
  989. }
  990. var got map[string]any
  991. if err := json.Unmarshal([]byte(encoded), &got); err != nil {
  992. t.Fatalf("unmarshal marshaled finalmask: %v", err)
  993. }
  994. masks, _ := got["tcp"].([]any)
  995. if len(masks) != 5 {
  996. t.Fatalf("tcp mask count = %d, want 5", len(masks))
  997. }
  998. settingsAt := func(index int) map[string]any {
  999. t.Helper()
  1000. mask, _ := masks[index].(map[string]any)
  1001. settings, _ := mask["settings"].(map[string]any)
  1002. if settings == nil {
  1003. t.Fatalf("tcp[%d] settings missing: %#v", index, mask)
  1004. }
  1005. return settings
  1006. }
  1007. gotScreenshot := settingsAt(0)
  1008. if gotScreenshot["length"] != "25-30" || gotScreenshot["delay"] != "10-30" {
  1009. t.Fatalf("legacy ranges = (%v, %v), want last array entries", gotScreenshot["length"], gotScreenshot["delay"])
  1010. }
  1011. if !reflect.DeepEqual(gotScreenshot["lengths"], lengths) || !reflect.DeepEqual(gotScreenshot["delays"], delays) {
  1012. t.Fatalf("per-segment ranges changed: lengths=%#v delays=%#v", gotScreenshot["lengths"], gotScreenshot["delays"])
  1013. }
  1014. if gotScreenshot["packets"] != "tlshello" || gotScreenshot["maxSplit"] != "10-15" {
  1015. t.Fatalf("other fragment settings changed: %#v", gotScreenshot)
  1016. }
  1017. gotExplicit := settingsAt(1)
  1018. if gotExplicit["length"] != "1-2" || gotExplicit["delay"] != "3-4" {
  1019. t.Fatalf("explicit legacy ranges were overwritten: %#v", gotExplicit)
  1020. }
  1021. gotEmpty := settingsAt(2)
  1022. if _, exists := gotEmpty["length"]; exists {
  1023. t.Fatalf("empty lengths must not emit a fallback: %#v", gotEmpty)
  1024. }
  1025. if _, exists := gotEmpty["delay"]; exists {
  1026. t.Fatalf("empty delays must not emit a fallback: %#v", gotEmpty)
  1027. }
  1028. gotLegacyOnly := settingsAt(3)
  1029. if gotLegacyOnly["length"] != "40-50" || gotLegacyOnly["delay"] != "10-20" {
  1030. t.Fatalf("legacy-only ranges changed: %#v", gotLegacyOnly)
  1031. }
  1032. if _, exists := settingsAt(4)["length"]; exists {
  1033. t.Fatalf("non-fragment mask received a fallback: %#v", settingsAt(4))
  1034. }
  1035. after, err := json.Marshal(fm)
  1036. if err != nil {
  1037. t.Fatalf("marshal input finalmask after export: %v", err)
  1038. }
  1039. if string(after) != string(original) {
  1040. t.Fatalf("marshalFinalMask mutated its input:\nbefore: %s\nafter: %s", original, after)
  1041. }
  1042. }
  1043. func TestMarshalFinalMask_UnknownTypeIsDropped(t *testing.T) {
  1044. fm := map[string]any{
  1045. "tcp": []any{
  1046. map[string]any{"type": "not-a-real-mask"},
  1047. },
  1048. }
  1049. if _, ok := marshalFinalMask(fm); ok {
  1050. t.Fatal("unknown mask types should be dropped, leaving nothing to marshal")
  1051. }
  1052. }
  1053. func TestMarshalFinalMask_KeepsXmcTcpMask(t *testing.T) {
  1054. fm := map[string]any{
  1055. "tcp": []any{
  1056. map[string]any{"type": "xmc", "settings": map[string]any{"password": "p"}},
  1057. },
  1058. }
  1059. out, ok := marshalFinalMask(fm)
  1060. if !ok {
  1061. t.Fatal("expected ok=true for an xmc tcp mask")
  1062. }
  1063. if !strings.Contains(out, "xmc") {
  1064. t.Fatalf("marshaled finalmask dropped the xmc mask: %s", out)
  1065. }
  1066. }
  1067. func TestMarshalFinalMask_KeepsUdpHopMask(t *testing.T) {
  1068. fm := map[string]any{
  1069. "udp": []any{udpHopMask("20000-50000")},
  1070. }
  1071. out, ok := marshalFinalMask(fm)
  1072. if !ok {
  1073. t.Fatal("expected ok=true for a udphop udp mask")
  1074. }
  1075. if !strings.Contains(out, "udphop") || !strings.Contains(out, "20000-50000") {
  1076. t.Fatalf("marshaled finalmask dropped the udphop mask: %s", out)
  1077. }
  1078. }
  1079. func TestHasFinalMaskContent(t *testing.T) {
  1080. if hasFinalMaskContent(nil) {
  1081. t.Fatal("nil should not count as content")
  1082. }
  1083. if hasFinalMaskContent(map[string]any{}) {
  1084. t.Fatal("empty map should not count as content")
  1085. }
  1086. if !hasFinalMaskContent(map[string]any{"x": 1}) {
  1087. t.Fatal("non-empty map should count as content")
  1088. }
  1089. }
  1090. func TestHysteriaPinHex(t *testing.T) {
  1091. const hexPin = "c847dd2395d0978c0780b8201c4b289a8b281597d47c275f2d77d3f96d8de9c4"
  1092. cases := []struct {
  1093. name string
  1094. in string
  1095. want string
  1096. }{
  1097. // Std base64 (xray-core's native TLS format / the panel generate button)
  1098. // must be re-encoded to the hex form Hysteria2 clients expect (#4818).
  1099. {"std base64", "yEfdI5XQl4wHgLggHEsomosoFZfUfCdfLXfT+W2N6cQ=", hexPin},
  1100. // A manually pasted hex fingerprint passes through (lowercased).
  1101. {"hex passthrough", hexPin, hexPin},
  1102. {"uppercase hex lowercased", strings.ToUpper(hexPin), hexPin},
  1103. // openssl x509 -fingerprint -sha256 emits colon-separated hex.
  1104. {"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},
  1105. {"surrounding whitespace trimmed", " " + hexPin + " ", hexPin},
  1106. // URL-safe base64 with the same 32 bytes decodes identically.
  1107. {"url-safe base64", "yEfdI5XQl4wHgLggHEsomosoFZfUfCdfLXfT-W2N6cQ=", hexPin},
  1108. // Garbage that is neither valid hex nor a 32-byte base64 is left as-is
  1109. // rather than silently dropped.
  1110. {"unrecognized passthrough", "not-a-pin", "not-a-pin"},
  1111. {"empty", "", ""},
  1112. }
  1113. for _, tc := range cases {
  1114. t.Run(tc.name, func(t *testing.T) {
  1115. if got := hysteriaPinHex(tc.in); got != tc.want {
  1116. t.Fatalf("hysteriaPinHex(%q) = %q, want %q", tc.in, got, tc.want)
  1117. }
  1118. })
  1119. }
  1120. }
  1121. func udpHopMask(ports string) map[string]any {
  1122. return map[string]any{
  1123. "type": "udphop",
  1124. "settings": map[string]any{"mode": "intervalremote", "interval": "5-10", "remotePorts": ports},
  1125. }
  1126. }
  1127. func TestHysteriaHopPorts(t *testing.T) {
  1128. withHop := func(ports any) map[string]any {
  1129. return map[string]any{
  1130. "finalmask": map[string]any{
  1131. "quicParams": map[string]any{
  1132. "udpHop": map[string]any{"ports": ports, "interval": "5-10"},
  1133. },
  1134. },
  1135. }
  1136. }
  1137. withHopMask := func(ports string) map[string]any {
  1138. return map[string]any{
  1139. "finalmask": map[string]any{"udp": []any{udpHopMask(ports)}},
  1140. }
  1141. }
  1142. cases := []struct {
  1143. name string
  1144. stream map[string]any
  1145. want string
  1146. }{
  1147. {"range", withHop("20000-50000"), "20000-50000"},
  1148. {"udphop mask", withHopMask("20000-50000"), "20000-50000"},
  1149. {"udphop mask wins over legacy key", map[string]any{
  1150. "finalmask": map[string]any{
  1151. "udp": []any{udpHopMask("30000-40000")},
  1152. "quicParams": map[string]any{"udpHop": map[string]any{"ports": "20000-50000"}},
  1153. },
  1154. }, "30000-40000"},
  1155. {"udphop mask without remotePorts", withHopMask(""), ""},
  1156. {"trimmed", withHop(" 443,20000-50000 "), "443,20000-50000"},
  1157. {"empty string", withHop(""), ""},
  1158. {"non-string", withHop(float64(443)), ""},
  1159. {"no udpHop", map[string]any{"finalmask": map[string]any{"quicParams": map[string]any{}}}, ""},
  1160. {"no finalmask", map[string]any{}, ""},
  1161. {"nil stream", nil, ""},
  1162. }
  1163. for _, tc := range cases {
  1164. t.Run(tc.name, func(t *testing.T) {
  1165. if got := hysteriaHopPorts(tc.stream); got != tc.want {
  1166. t.Fatalf("hysteriaHopPorts() = %q, want %q", got, tc.want)
  1167. }
  1168. })
  1169. }
  1170. }
  1171. func TestGenHysteriaLinkOmitsFinalMaskQueryParam(t *testing.T) {
  1172. stream := `{
  1173. "security":"tls",
  1174. "tlsSettings":{"serverName":"hy.sni","alpn":["h3"],"settings":{"fingerprint":"chrome"}},
  1175. "finalmask":{"udp":[{"type":"salamander","settings":{"password":"obfs-secret"}}]}
  1176. }`
  1177. in := &model.Inbound{
  1178. Listen: "203.0.113.1",
  1179. Port: 443,
  1180. Protocol: model.Hysteria,
  1181. Remark: "hy2",
  1182. Settings: `{"version":2,"clients":[{"auth":"hyauth","email":"user"}]}`,
  1183. StreamSettings: stream,
  1184. }
  1185. got := (&SubService{}).genHysteriaLink(in, "user")
  1186. if got == "" {
  1187. t.Fatal("expected hysteria2 link")
  1188. }
  1189. if strings.Contains(got, "fm=") {
  1190. t.Fatalf("hysteria2 subscription URI must not include non-standard fm param: %s", got)
  1191. }
  1192. if !strings.Contains(got, "obfs=salamander") {
  1193. t.Fatalf("missing standard obfs=salamander: %s", got)
  1194. }
  1195. if !strings.Contains(got, "obfs-password=obfs-secret") {
  1196. t.Fatalf("missing standard obfs-password: %s", got)
  1197. }
  1198. }
  1199. func TestGenHysteriaLinkKeepsHopPortsWithExternalProxy(t *testing.T) {
  1200. stream := `{
  1201. "security":"tls",
  1202. "tlsSettings":{"serverName":"hy.sni"},
  1203. "finalmask":{"quicParams":{"udpHop":{"ports":"20000-50000","interval":"5-10"}}},
  1204. "externalProxy":[
  1205. {"dest":"cdn.example.com","port":8443},
  1206. {"dest":"2001:db8::10","port":9443}
  1207. ]
  1208. }`
  1209. in := &model.Inbound{
  1210. Listen: "203.0.113.1",
  1211. Port: 443,
  1212. Protocol: model.Hysteria,
  1213. Remark: "hy2",
  1214. Settings: `{"version":2,"clients":[{"auth":"hyauth","email":"user"}]}`,
  1215. StreamSettings: stream,
  1216. }
  1217. got := (&SubService{}).genHysteriaLink(in, "user")
  1218. links := strings.Split(got, "\n")
  1219. if len(links) != 2 {
  1220. t.Fatalf("expected one link per external proxy, got %d: %q", len(links), got)
  1221. }
  1222. for _, link := range links {
  1223. if !strings.Contains(link, "mport=20000-50000") {
  1224. t.Fatalf("external-proxy link lost the UDP hop range: %s", link)
  1225. }
  1226. }
  1227. }