service_test.go 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341
  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("non-tls security drops ech", func(t *testing.T) {
  675. params := map[string]string{}
  676. ep := map[string]any{"echConfigList": ech}
  677. applyExternalProxyTLSParams(ep, params, "none")
  678. if _, ok := params["ech"]; ok {
  679. t.Fatalf("ech must not be set when security != tls")
  680. }
  681. })
  682. }
  683. func TestApplyExternalProxyTLSToStream_DoesNotLeakAcrossProxies(t *testing.T) {
  684. stream := map[string]any{
  685. "security": "tls",
  686. "tlsSettings": map[string]any{
  687. "serverName": "upstream.example.com",
  688. },
  689. }
  690. proxies := []map[string]any{
  691. {"dest": "a.example.com", "sni": "a-sni.example.com", "fingerprint": "chrome", "alpn": []any{"h3"}},
  692. {"dest": "b.example.com"},
  693. }
  694. results := make([]map[string]any, 0, len(proxies))
  695. for _, ep := range proxies {
  696. working := cloneStreamForExternalProxy(stream)
  697. applyExternalProxyTLSToStream(ep, working, "tls")
  698. ts := working["tlsSettings"].(map[string]any)
  699. snapshot := map[string]any{
  700. "serverName": ts["serverName"],
  701. "fingerprint": ts["fingerprint"],
  702. "alpn": ts["alpn"],
  703. }
  704. results = append(results, snapshot)
  705. }
  706. if results[0]["serverName"] != "a-sni.example.com" || results[0]["fingerprint"] != "chrome" {
  707. t.Fatalf("proxy A snapshot = %v", results[0])
  708. }
  709. // Proxy B has no SNI of its own — the upstream tlsSettings serverName
  710. // must remain in place (no dest fallback) and no fingerprint/alpn
  711. // must leak from proxy A.
  712. if results[1]["serverName"] != "upstream.example.com" {
  713. t.Fatalf("proxy B serverName = %v, want upstream.example.com preserved", results[1]["serverName"])
  714. }
  715. if results[1]["fingerprint"] != nil {
  716. t.Fatalf("proxy B should inherit no fingerprint, got %v (leaked from A)", results[1]["fingerprint"])
  717. }
  718. if results[1]["alpn"] != nil {
  719. t.Fatalf("proxy B should inherit no alpn, got %v (leaked from A)", results[1]["alpn"])
  720. }
  721. }
  722. func TestApplyExternalProxyTLSToStream_FingerprintNotDuplicated(t *testing.T) {
  723. stream := map[string]any{
  724. "security": "tls",
  725. "tlsSettings": map[string]any{},
  726. }
  727. ep := map[string]any{"dest": "proxy.example.com", "fingerprint": "chrome"}
  728. applyExternalProxyTLSToStream(ep, stream, "tls")
  729. ts, _ := stream["tlsSettings"].(map[string]any)
  730. if ts["fingerprint"] != "chrome" {
  731. t.Fatalf("tlsSettings.fingerprint = %v, want %q", ts["fingerprint"], "chrome")
  732. }
  733. if settings, ok := ts["settings"].(map[string]any); ok {
  734. if got, dup := settings["fingerprint"]; dup {
  735. t.Fatalf("fingerprint must not be duplicated into tlsSettings.settings, got %v", got)
  736. }
  737. }
  738. }
  739. func TestApplyExternalProxyTLSParams_SetsPinnedPeerCert(t *testing.T) {
  740. params := map[string]string{"security": "tls"}
  741. ep := map[string]any{
  742. "dest": "proxy.example.com",
  743. "pinnedPeerCertSha256": []any{"aa11", "bb22"},
  744. }
  745. applyExternalProxyTLSParams(ep, params, "tls")
  746. if params["pcs"] != "aa11,bb22" {
  747. t.Fatalf("pcs = %q, want aa11,bb22", params["pcs"])
  748. }
  749. }
  750. func TestApplyExternalProxyTLSObj_SetsPinnedPeerCert(t *testing.T) {
  751. obj := map[string]any{"tls": "tls"}
  752. ep := map[string]any{
  753. "dest": "proxy.example.com",
  754. "pinnedPeerCertSha256": []any{"aa11"},
  755. }
  756. applyExternalProxyTLSObj(ep, obj, "tls")
  757. if obj["pcs"] != "aa11" {
  758. t.Fatalf("pcs = %v, want aa11", obj["pcs"])
  759. }
  760. }
  761. func TestApplyExternalProxyTLSToStream_SetsPinnedPeerCert(t *testing.T) {
  762. stream := map[string]any{
  763. "security": "tls",
  764. "tlsSettings": map[string]any{"serverName": "upstream.example.com"},
  765. }
  766. ep := map[string]any{"dest": "edge.example.com", "pinnedPeerCertSha256": []any{"aa11", "bb22"}}
  767. working := cloneStreamForExternalProxy(stream)
  768. applyExternalProxyTLSToStream(ep, working, "tls")
  769. ts := working["tlsSettings"].(map[string]any)
  770. settings, _ := ts["settings"].(map[string]any)
  771. pins, ok := settings["pinnedPeerCertSha256"].([]any)
  772. if !ok || len(pins) != 2 || pins[0] != "aa11" || pins[1] != "bb22" {
  773. t.Fatalf("pinnedPeerCertSha256 = %v, want [aa11 bb22]", settings["pinnedPeerCertSha256"])
  774. }
  775. }
  776. func TestApplyExternalProxyHysteriaParams_PinIsHexNormalized(t *testing.T) {
  777. // base64 SHA-256 pin must come out as bare lowercase hex for Hysteria's
  778. // pinSHA256, which other (pcs) protocols leave untouched.
  779. params := map[string]string{"security": "tls", "sni": "server.example.com"}
  780. ep := map[string]any{
  781. "dest": "edge.example.com",
  782. "pinnedPeerCertSha256": []any{"yEfdI5XQl4wHgLggHEsomosoFZfUfCdfLXfT+W2N6cQ="},
  783. }
  784. applyExternalProxyHysteriaParams(ep, params)
  785. if params["pinSHA256"] != "c847dd2395d0978c0780b8201c4b289a8b281597d47c275f2d77d3f96d8de9c4" {
  786. t.Fatalf("pinSHA256 = %q, want hex-normalized pin", params["pinSHA256"])
  787. }
  788. if _, ok := params["pcs"]; ok {
  789. t.Fatalf("pcs must not be set for Hysteria, got %v", params)
  790. }
  791. if params["sni"] != "server.example.com" {
  792. t.Fatalf("sni = %q, want inbound sni preserved (no override for Hysteria)", params["sni"])
  793. }
  794. }
  795. func TestApplyExternalProxyHysteriaParams_NoPinLeavesMainPin(t *testing.T) {
  796. params := map[string]string{"security": "tls", "pinSHA256": "deadbeef"}
  797. ep := map[string]any{"dest": "edge.example.com"}
  798. applyExternalProxyHysteriaParams(ep, params)
  799. if params["pinSHA256"] != "deadbeef" {
  800. t.Fatalf("pinSHA256 = %q, want main pin preserved when proxy has none", params["pinSHA256"])
  801. }
  802. }
  803. func TestApplyExternalProxyTLSParams_DoesNotApplyForNone(t *testing.T) {
  804. params := map[string]string{
  805. "security": "none",
  806. "sni": "origin.example.com",
  807. }
  808. ep := map[string]any{
  809. "dest": "proxy.example.com",
  810. "fingerprint": "chrome",
  811. "alpn": []any{"h3"},
  812. }
  813. applyExternalProxyTLSParams(ep, params, "none")
  814. if params["sni"] != "origin.example.com" {
  815. t.Fatalf("sni should not change for security=none, got %q", params["sni"])
  816. }
  817. if _, ok := params["fp"]; ok {
  818. t.Fatalf("fp should not be set for security=none, got %v", params)
  819. }
  820. if _, ok := params["alpn"]; ok {
  821. t.Fatalf("alpn should not be set for security=none, got %v", params)
  822. }
  823. }
  824. func TestExtractKcpShareFields_Defaults(t *testing.T) {
  825. stream := map[string]any{}
  826. got := extractKcpShareFields(stream)
  827. if got.headerType != "none" {
  828. t.Fatalf("default headerType = %q, want none", got.headerType)
  829. }
  830. if got.seed != "" || got.mtu != 0 || got.tti != 0 {
  831. t.Fatalf("default kcpShareFields should be zero except headerType, got %+v", got)
  832. }
  833. }
  834. func TestExtractKcpShareFields_ReadsAllFields(t *testing.T) {
  835. stream := map[string]any{
  836. "kcpSettings": map[string]any{
  837. "header": map[string]any{"type": "wechat-video"},
  838. "seed": "secret-seed",
  839. "mtu": float64(1350),
  840. "tti": float64(50),
  841. },
  842. }
  843. got := extractKcpShareFields(stream)
  844. if got.headerType != "wechat-video" {
  845. t.Fatalf("headerType = %q, want wechat-video", got.headerType)
  846. }
  847. if got.seed != "secret-seed" {
  848. t.Fatalf("seed = %q, want secret-seed", got.seed)
  849. }
  850. if got.mtu != 1350 {
  851. t.Fatalf("mtu = %d, want 1350", got.mtu)
  852. }
  853. if got.tti != 50 {
  854. t.Fatalf("tti = %d, want 50", got.tti)
  855. }
  856. }
  857. func TestExtractKcpShareFields_FinalMaskLegacyHeader(t *testing.T) {
  858. stream := map[string]any{
  859. "finalmask": map[string]any{
  860. "udp": []any{
  861. map[string]any{
  862. "type": "mkcp-legacy",
  863. "settings": map[string]any{"header": "wechat", "value": ""},
  864. },
  865. },
  866. },
  867. }
  868. got := extractKcpShareFields(stream)
  869. if got.headerType != "wechat-video" {
  870. t.Fatalf("headerType = %q, want wechat-video", got.headerType)
  871. }
  872. if got.seed != "" {
  873. t.Fatalf("seed = %q, want empty for header mask", got.seed)
  874. }
  875. }
  876. func TestExtractKcpShareFields_FinalMaskLegacySeed(t *testing.T) {
  877. stream := map[string]any{
  878. "finalmask": map[string]any{
  879. "udp": []any{
  880. map[string]any{
  881. "type": "mkcp-legacy",
  882. "settings": map[string]any{"header": "", "value": "obfs-pass"},
  883. },
  884. },
  885. },
  886. }
  887. got := extractKcpShareFields(stream)
  888. if got.headerType != "none" {
  889. t.Fatalf("headerType = %q, want none for empty-header legacy mask", got.headerType)
  890. }
  891. if got.seed != "obfs-pass" {
  892. t.Fatalf("seed = %q, want obfs-pass", got.seed)
  893. }
  894. }
  895. func TestKcpShareFields_ApplyToParams(t *testing.T) {
  896. params := map[string]string{}
  897. kcpShareFields{headerType: "wechat-video", seed: "s", mtu: 1350, tti: 50}.applyToParams(params)
  898. if params["headerType"] != "wechat-video" {
  899. t.Fatalf("headerType param = %q", params["headerType"])
  900. }
  901. if params["seed"] != "s" {
  902. t.Fatalf("seed param = %q", params["seed"])
  903. }
  904. if params["mtu"] != "1350" {
  905. t.Fatalf("mtu param = %q", params["mtu"])
  906. }
  907. if params["tti"] != "50" {
  908. t.Fatalf("tti param = %q", params["tti"])
  909. }
  910. }
  911. func TestKcpShareFields_ApplyToParams_NoneHeaderNotAdded(t *testing.T) {
  912. params := map[string]string{}
  913. kcpShareFields{headerType: "none"}.applyToParams(params)
  914. if _, ok := params["headerType"]; ok {
  915. t.Fatalf("headerType=none should not be added, got %v", params)
  916. }
  917. }
  918. func TestMarshalFinalMask_EmptyReturnsFalse(t *testing.T) {
  919. if _, ok := marshalFinalMask(map[string]any{}); ok {
  920. t.Fatal("expected ok=false for empty finalmask")
  921. }
  922. if _, ok := marshalFinalMask(nil); ok {
  923. t.Fatal("expected ok=false for nil finalmask")
  924. }
  925. }
  926. func TestMarshalFinalMask_WithContent(t *testing.T) {
  927. fm := map[string]any{
  928. "tcp": []any{
  929. map[string]any{"type": "fragment"},
  930. },
  931. }
  932. out, ok := marshalFinalMask(fm)
  933. if !ok {
  934. t.Fatal("expected ok=true for finalmask with valid tcp mask")
  935. }
  936. if !strings.Contains(out, `"tcp"`) {
  937. t.Fatalf("marshaled finalmask missing tcp key: %s", out)
  938. }
  939. if !strings.Contains(out, "fragment") {
  940. t.Fatalf("marshaled finalmask missing mask type: %s", out)
  941. }
  942. }
  943. func TestMarshalFinalMaskAddsLegacyFragmentRanges(t *testing.T) {
  944. lengths := []any{"5-10", "10-15", "15-20", "20-25", "25-30"}
  945. delays := []any{"10-20", "5-20", "5-25", "15-25", "10-30"}
  946. screenshotSettings := map[string]any{
  947. "packets": "tlshello",
  948. "lengths": lengths,
  949. "delays": delays,
  950. "maxSplit": "10-15",
  951. }
  952. explicitSettings := map[string]any{
  953. "length": "1-2",
  954. "lengths": []any{"8-9"},
  955. "delay": "3-4",
  956. "delays": []any{"6-7"},
  957. }
  958. emptySettings := map[string]any{
  959. "lengths": []any{},
  960. "delays": []any{},
  961. }
  962. legacyOnlySettings := map[string]any{"length": "40-50", "delay": "10-20"}
  963. otherSettings := map[string]any{"lengths": []any{"30-40"}}
  964. fm := map[string]any{
  965. "tcp": []any{
  966. map[string]any{"type": "fragment", "settings": screenshotSettings},
  967. map[string]any{"type": "fragment", "settings": explicitSettings},
  968. map[string]any{"type": "fragment", "settings": emptySettings},
  969. map[string]any{"type": "fragment", "settings": legacyOnlySettings},
  970. map[string]any{"type": "sudoku", "settings": otherSettings},
  971. },
  972. }
  973. original, err := json.Marshal(fm)
  974. if err != nil {
  975. t.Fatalf("marshal input finalmask: %v", err)
  976. }
  977. encoded, ok := marshalFinalMask(fm)
  978. if !ok {
  979. t.Fatal("expected finalmask with fragment masks to be marshaled")
  980. }
  981. var got map[string]any
  982. if err := json.Unmarshal([]byte(encoded), &got); err != nil {
  983. t.Fatalf("unmarshal marshaled finalmask: %v", err)
  984. }
  985. masks, _ := got["tcp"].([]any)
  986. if len(masks) != 5 {
  987. t.Fatalf("tcp mask count = %d, want 5", len(masks))
  988. }
  989. settingsAt := func(index int) map[string]any {
  990. t.Helper()
  991. mask, _ := masks[index].(map[string]any)
  992. settings, _ := mask["settings"].(map[string]any)
  993. if settings == nil {
  994. t.Fatalf("tcp[%d] settings missing: %#v", index, mask)
  995. }
  996. return settings
  997. }
  998. gotScreenshot := settingsAt(0)
  999. if gotScreenshot["length"] != "25-30" || gotScreenshot["delay"] != "10-30" {
  1000. t.Fatalf("legacy ranges = (%v, %v), want last array entries", gotScreenshot["length"], gotScreenshot["delay"])
  1001. }
  1002. if !reflect.DeepEqual(gotScreenshot["lengths"], lengths) || !reflect.DeepEqual(gotScreenshot["delays"], delays) {
  1003. t.Fatalf("per-segment ranges changed: lengths=%#v delays=%#v", gotScreenshot["lengths"], gotScreenshot["delays"])
  1004. }
  1005. if gotScreenshot["packets"] != "tlshello" || gotScreenshot["maxSplit"] != "10-15" {
  1006. t.Fatalf("other fragment settings changed: %#v", gotScreenshot)
  1007. }
  1008. gotExplicit := settingsAt(1)
  1009. if gotExplicit["length"] != "1-2" || gotExplicit["delay"] != "3-4" {
  1010. t.Fatalf("explicit legacy ranges were overwritten: %#v", gotExplicit)
  1011. }
  1012. gotEmpty := settingsAt(2)
  1013. if _, exists := gotEmpty["length"]; exists {
  1014. t.Fatalf("empty lengths must not emit a fallback: %#v", gotEmpty)
  1015. }
  1016. if _, exists := gotEmpty["delay"]; exists {
  1017. t.Fatalf("empty delays must not emit a fallback: %#v", gotEmpty)
  1018. }
  1019. gotLegacyOnly := settingsAt(3)
  1020. if gotLegacyOnly["length"] != "40-50" || gotLegacyOnly["delay"] != "10-20" {
  1021. t.Fatalf("legacy-only ranges changed: %#v", gotLegacyOnly)
  1022. }
  1023. if _, exists := settingsAt(4)["length"]; exists {
  1024. t.Fatalf("non-fragment mask received a fallback: %#v", settingsAt(4))
  1025. }
  1026. after, err := json.Marshal(fm)
  1027. if err != nil {
  1028. t.Fatalf("marshal input finalmask after export: %v", err)
  1029. }
  1030. if string(after) != string(original) {
  1031. t.Fatalf("marshalFinalMask mutated its input:\nbefore: %s\nafter: %s", original, after)
  1032. }
  1033. }
  1034. func TestMarshalFinalMask_UnknownTypeIsDropped(t *testing.T) {
  1035. fm := map[string]any{
  1036. "tcp": []any{
  1037. map[string]any{"type": "not-a-real-mask"},
  1038. },
  1039. }
  1040. if _, ok := marshalFinalMask(fm); ok {
  1041. t.Fatal("unknown mask types should be dropped, leaving nothing to marshal")
  1042. }
  1043. }
  1044. func TestMarshalFinalMask_KeepsXmcTcpMask(t *testing.T) {
  1045. fm := map[string]any{
  1046. "tcp": []any{
  1047. map[string]any{"type": "xmc", "settings": map[string]any{"password": "p"}},
  1048. },
  1049. }
  1050. out, ok := marshalFinalMask(fm)
  1051. if !ok {
  1052. t.Fatal("expected ok=true for an xmc tcp mask")
  1053. }
  1054. if !strings.Contains(out, "xmc") {
  1055. t.Fatalf("marshaled finalmask dropped the xmc mask: %s", out)
  1056. }
  1057. }
  1058. func TestMarshalFinalMask_KeepsUdpHopMask(t *testing.T) {
  1059. fm := map[string]any{
  1060. "udp": []any{udpHopMask("20000-50000")},
  1061. }
  1062. out, ok := marshalFinalMask(fm)
  1063. if !ok {
  1064. t.Fatal("expected ok=true for a udphop udp mask")
  1065. }
  1066. if !strings.Contains(out, "udphop") || !strings.Contains(out, "20000-50000") {
  1067. t.Fatalf("marshaled finalmask dropped the udphop mask: %s", out)
  1068. }
  1069. }
  1070. func TestHasFinalMaskContent(t *testing.T) {
  1071. if hasFinalMaskContent(nil) {
  1072. t.Fatal("nil should not count as content")
  1073. }
  1074. if hasFinalMaskContent(map[string]any{}) {
  1075. t.Fatal("empty map should not count as content")
  1076. }
  1077. if !hasFinalMaskContent(map[string]any{"x": 1}) {
  1078. t.Fatal("non-empty map should count as content")
  1079. }
  1080. }
  1081. func TestHysteriaPinHex(t *testing.T) {
  1082. const hexPin = "c847dd2395d0978c0780b8201c4b289a8b281597d47c275f2d77d3f96d8de9c4"
  1083. cases := []struct {
  1084. name string
  1085. in string
  1086. want string
  1087. }{
  1088. // Std base64 (xray-core's native TLS format / the panel generate button)
  1089. // must be re-encoded to the hex form Hysteria2 clients expect (#4818).
  1090. {"std base64", "yEfdI5XQl4wHgLggHEsomosoFZfUfCdfLXfT+W2N6cQ=", hexPin},
  1091. // A manually pasted hex fingerprint passes through (lowercased).
  1092. {"hex passthrough", hexPin, hexPin},
  1093. {"uppercase hex lowercased", strings.ToUpper(hexPin), hexPin},
  1094. // openssl x509 -fingerprint -sha256 emits colon-separated hex.
  1095. {"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},
  1096. {"surrounding whitespace trimmed", " " + hexPin + " ", hexPin},
  1097. // URL-safe base64 with the same 32 bytes decodes identically.
  1098. {"url-safe base64", "yEfdI5XQl4wHgLggHEsomosoFZfUfCdfLXfT-W2N6cQ=", hexPin},
  1099. // Garbage that is neither valid hex nor a 32-byte base64 is left as-is
  1100. // rather than silently dropped.
  1101. {"unrecognized passthrough", "not-a-pin", "not-a-pin"},
  1102. {"empty", "", ""},
  1103. }
  1104. for _, tc := range cases {
  1105. t.Run(tc.name, func(t *testing.T) {
  1106. if got := hysteriaPinHex(tc.in); got != tc.want {
  1107. t.Fatalf("hysteriaPinHex(%q) = %q, want %q", tc.in, got, tc.want)
  1108. }
  1109. })
  1110. }
  1111. }
  1112. func udpHopMask(ports string) map[string]any {
  1113. return map[string]any{
  1114. "type": "udphop",
  1115. "settings": map[string]any{"mode": "intervalremote", "interval": "5-10", "remotePorts": ports},
  1116. }
  1117. }
  1118. func TestHysteriaHopPorts(t *testing.T) {
  1119. withHop := func(ports any) map[string]any {
  1120. return map[string]any{
  1121. "finalmask": map[string]any{
  1122. "quicParams": map[string]any{
  1123. "udpHop": map[string]any{"ports": ports, "interval": "5-10"},
  1124. },
  1125. },
  1126. }
  1127. }
  1128. withHopMask := func(ports string) map[string]any {
  1129. return map[string]any{
  1130. "finalmask": map[string]any{"udp": []any{udpHopMask(ports)}},
  1131. }
  1132. }
  1133. cases := []struct {
  1134. name string
  1135. stream map[string]any
  1136. want string
  1137. }{
  1138. {"range", withHop("20000-50000"), "20000-50000"},
  1139. {"udphop mask", withHopMask("20000-50000"), "20000-50000"},
  1140. {"udphop mask wins over legacy key", map[string]any{
  1141. "finalmask": map[string]any{
  1142. "udp": []any{udpHopMask("30000-40000")},
  1143. "quicParams": map[string]any{"udpHop": map[string]any{"ports": "20000-50000"}},
  1144. },
  1145. }, "30000-40000"},
  1146. {"udphop mask without remotePorts", withHopMask(""), ""},
  1147. {"trimmed", withHop(" 443,20000-50000 "), "443,20000-50000"},
  1148. {"empty string", withHop(""), ""},
  1149. {"non-string", withHop(float64(443)), ""},
  1150. {"no udpHop", map[string]any{"finalmask": map[string]any{"quicParams": map[string]any{}}}, ""},
  1151. {"no finalmask", map[string]any{}, ""},
  1152. {"nil stream", nil, ""},
  1153. }
  1154. for _, tc := range cases {
  1155. t.Run(tc.name, func(t *testing.T) {
  1156. if got := hysteriaHopPorts(tc.stream); got != tc.want {
  1157. t.Fatalf("hysteriaHopPorts() = %q, want %q", got, tc.want)
  1158. }
  1159. })
  1160. }
  1161. }
  1162. func TestGenHysteriaLinkOmitsFinalMaskQueryParam(t *testing.T) {
  1163. stream := `{
  1164. "security":"tls",
  1165. "tlsSettings":{"serverName":"hy.sni","alpn":["h3"],"settings":{"fingerprint":"chrome"}},
  1166. "finalmask":{"udp":[{"type":"salamander","settings":{"password":"obfs-secret"}}]}
  1167. }`
  1168. in := &model.Inbound{
  1169. Listen: "203.0.113.1",
  1170. Port: 443,
  1171. Protocol: model.Hysteria,
  1172. Remark: "hy2",
  1173. Settings: `{"version":2,"clients":[{"auth":"hyauth","email":"user"}]}`,
  1174. StreamSettings: stream,
  1175. }
  1176. got := (&SubService{}).genHysteriaLink(in, "user")
  1177. if got == "" {
  1178. t.Fatal("expected hysteria2 link")
  1179. }
  1180. if strings.Contains(got, "fm=") {
  1181. t.Fatalf("hysteria2 subscription URI must not include non-standard fm param: %s", got)
  1182. }
  1183. if !strings.Contains(got, "obfs=salamander") {
  1184. t.Fatalf("missing standard obfs=salamander: %s", got)
  1185. }
  1186. if !strings.Contains(got, "obfs-password=obfs-secret") {
  1187. t.Fatalf("missing standard obfs-password: %s", got)
  1188. }
  1189. }
  1190. func TestGenHysteriaLinkKeepsHopPortsWithExternalProxy(t *testing.T) {
  1191. stream := `{
  1192. "security":"tls",
  1193. "tlsSettings":{"serverName":"hy.sni"},
  1194. "finalmask":{"quicParams":{"udpHop":{"ports":"20000-50000","interval":"5-10"}}},
  1195. "externalProxy":[
  1196. {"dest":"cdn.example.com","port":8443},
  1197. {"dest":"2001:db8::10","port":9443}
  1198. ]
  1199. }`
  1200. in := &model.Inbound{
  1201. Listen: "203.0.113.1",
  1202. Port: 443,
  1203. Protocol: model.Hysteria,
  1204. Remark: "hy2",
  1205. Settings: `{"version":2,"clients":[{"auth":"hyauth","email":"user"}]}`,
  1206. StreamSettings: stream,
  1207. }
  1208. got := (&SubService{}).genHysteriaLink(in, "user")
  1209. links := strings.Split(got, "\n")
  1210. if len(links) != 2 {
  1211. t.Fatalf("expected one link per external proxy, got %d: %q", len(links), got)
  1212. }
  1213. for _, link := range links {
  1214. if !strings.Contains(link, "mport=20000-50000") {
  1215. t.Fatalf("external-proxy link lost the UDP hop range: %s", link)
  1216. }
  1217. }
  1218. }