1
0

service_test.go 32 KB

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