service_test.go 33 KB

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