service_test.go 33 KB

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