subService_test.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480
  1. package sub
  2. import (
  3. "encoding/base64"
  4. "encoding/json"
  5. "strings"
  6. "testing"
  7. "github.com/mhsanaei/3x-ui/v3/database/model"
  8. )
  9. func TestFindClientIndex(t *testing.T) {
  10. clients := []model.Client{
  11. {Email: "[email protected]"},
  12. {Email: "[email protected]"},
  13. {Email: "[email protected]"},
  14. }
  15. if got := findClientIndex(clients, "[email protected]"); got != 1 {
  16. t.Fatalf("findClientIndex middle = %d, want 1", got)
  17. }
  18. if got := findClientIndex(clients, "[email protected]"); got != 0 {
  19. t.Fatalf("findClientIndex first = %d, want 0", got)
  20. }
  21. if got := findClientIndex(clients, "[email protected]"); got != -1 {
  22. t.Fatalf("findClientIndex missing = %d, want -1", got)
  23. }
  24. if got := findClientIndex(nil, "x"); got != -1 {
  25. t.Fatalf("findClientIndex on nil slice = %d, want -1", got)
  26. }
  27. }
  28. func TestUnmarshalStreamSettings(t *testing.T) {
  29. got := unmarshalStreamSettings(`{"network":"ws","wsSettings":{"path":"/api"}}`)
  30. if got["network"] != "ws" {
  31. t.Fatalf("network = %v, want ws", got["network"])
  32. }
  33. ws, ok := got["wsSettings"].(map[string]any)
  34. if !ok || ws["path"] != "/api" {
  35. t.Fatalf("wsSettings = %v, want map with path=/api", got["wsSettings"])
  36. }
  37. }
  38. func TestUnmarshalStreamSettings_InvalidJSON(t *testing.T) {
  39. if got := unmarshalStreamSettings("not json"); got != nil {
  40. t.Fatalf("invalid JSON should produce nil map, got %#v", got)
  41. }
  42. }
  43. func TestSearchHost_StringValue(t *testing.T) {
  44. headers := map[string]any{"Host": "example.com"}
  45. if got := searchHost(headers); got != "example.com" {
  46. t.Fatalf("searchHost = %q, want example.com", got)
  47. }
  48. }
  49. func TestSearchHost_CaseInsensitiveKey(t *testing.T) {
  50. headers := map[string]any{"host": "example.com"}
  51. if got := searchHost(headers); got != "example.com" {
  52. t.Fatalf("searchHost = %q, want example.com", got)
  53. }
  54. headers2 := map[string]any{"HOST": "example.com"}
  55. if got := searchHost(headers2); got != "example.com" {
  56. t.Fatalf("searchHost uppercase = %q, want example.com", got)
  57. }
  58. }
  59. func TestSearchHost_ArrayValue(t *testing.T) {
  60. headers := map[string]any{"Host": []any{"first.example.com", "second.example.com"}}
  61. if got := searchHost(headers); got != "first.example.com" {
  62. t.Fatalf("searchHost array = %q, want first.example.com", got)
  63. }
  64. }
  65. func TestSearchHost_EmptyArray(t *testing.T) {
  66. headers := map[string]any{"Host": []any{}}
  67. if got := searchHost(headers); got != "" {
  68. t.Fatalf("searchHost empty array = %q, want empty", got)
  69. }
  70. }
  71. func TestSearchHost_NoHostKey(t *testing.T) {
  72. headers := map[string]any{"X-Other": "value"}
  73. if got := searchHost(headers); got != "" {
  74. t.Fatalf("searchHost no host = %q, want empty", got)
  75. }
  76. }
  77. func TestSearchHost_NotAMap(t *testing.T) {
  78. if got := searchHost("not a map"); got != "" {
  79. t.Fatalf("searchHost non-map = %q, want empty", got)
  80. }
  81. if got := searchHost(nil); got != "" {
  82. t.Fatalf("searchHost nil = %q, want empty", got)
  83. }
  84. }
  85. func TestSearchKey_FoundAtTopLevel(t *testing.T) {
  86. data := map[string]any{"foo": 42, "bar": "x"}
  87. got, ok := searchKey(data, "foo")
  88. if !ok {
  89. t.Fatal("expected to find foo")
  90. }
  91. if got != 42 {
  92. t.Fatalf("got %v, want 42", got)
  93. }
  94. }
  95. func TestSearchKey_FoundInNested(t *testing.T) {
  96. data := map[string]any{
  97. "outer": map[string]any{
  98. "inner": map[string]any{
  99. "target": "hit",
  100. },
  101. },
  102. }
  103. got, ok := searchKey(data, "target")
  104. if !ok {
  105. t.Fatal("expected to find target in nested map")
  106. }
  107. if got != "hit" {
  108. t.Fatalf("got %v, want hit", got)
  109. }
  110. }
  111. func TestSearchKey_FoundInsideArray(t *testing.T) {
  112. data := map[string]any{
  113. "list": []any{
  114. map[string]any{"other": 1},
  115. map[string]any{"needle": "found"},
  116. },
  117. }
  118. got, ok := searchKey(data, "needle")
  119. if !ok {
  120. t.Fatal("expected to find needle in array element")
  121. }
  122. if got != "found" {
  123. t.Fatalf("got %v, want found", got)
  124. }
  125. }
  126. func TestSearchKey_NotFound(t *testing.T) {
  127. data := map[string]any{"foo": "bar"}
  128. if _, ok := searchKey(data, "missing"); ok {
  129. t.Fatal("expected ok=false for missing key")
  130. }
  131. }
  132. func TestSearchKey_OnScalar(t *testing.T) {
  133. if _, ok := searchKey(42, "anything"); ok {
  134. t.Fatal("expected ok=false searching on a scalar")
  135. }
  136. }
  137. func TestCloneStringMap(t *testing.T) {
  138. src := map[string]string{"a": "1", "b": "2"}
  139. dst := cloneStringMap(src)
  140. if len(dst) != len(src) {
  141. t.Fatalf("clone length = %d, want %d", len(dst), len(src))
  142. }
  143. for k, v := range src {
  144. if dst[k] != v {
  145. t.Fatalf("clone[%q] = %q, want %q", k, dst[k], v)
  146. }
  147. }
  148. dst["a"] = "changed"
  149. if src["a"] == "changed" {
  150. t.Fatal("modifying clone leaked into source")
  151. }
  152. }
  153. func TestCloneStringMap_Empty(t *testing.T) {
  154. dst := cloneStringMap(map[string]string{})
  155. if dst == nil {
  156. t.Fatal("clone of empty map should not be nil")
  157. }
  158. if len(dst) != 0 {
  159. t.Fatalf("clone of empty map should be empty, got %v", dst)
  160. }
  161. }
  162. func TestGetHostFromXFH_HostOnly(t *testing.T) {
  163. got, err := getHostFromXFH("example.com")
  164. if err != nil {
  165. t.Fatalf("unexpected error: %v", err)
  166. }
  167. if got != "example.com" {
  168. t.Fatalf("got %q, want example.com", got)
  169. }
  170. }
  171. func TestGetHostFromXFH_HostWithPort(t *testing.T) {
  172. got, err := getHostFromXFH("example.com:8443")
  173. if err != nil {
  174. t.Fatalf("unexpected error: %v", err)
  175. }
  176. if got != "example.com" {
  177. t.Fatalf("got %q, want example.com", got)
  178. }
  179. }
  180. func TestGetHostFromXFH_IPv6WithPort(t *testing.T) {
  181. got, err := getHostFromXFH("[2606:4700::1111]:443")
  182. if err != nil {
  183. t.Fatalf("unexpected error: %v", err)
  184. }
  185. if got != "2606:4700::1111" {
  186. t.Fatalf("got %q, want 2606:4700::1111", got)
  187. }
  188. }
  189. func TestGetHostFromXFH_BadHostPort(t *testing.T) {
  190. if _, err := getHostFromXFH("example.com:8443:9999"); err == nil {
  191. t.Fatal("expected error for malformed host:port")
  192. }
  193. }
  194. func TestReadPositiveInt(t *testing.T) {
  195. cases := []struct {
  196. name string
  197. in any
  198. wantVal int
  199. wantOk bool
  200. }{
  201. {"int_positive", int(5), 5, true},
  202. {"int_zero", int(0), 0, false},
  203. {"int_negative", int(-3), -3, false},
  204. {"int32_positive", int32(7), 7, true},
  205. {"int64_positive", int64(99), 99, true},
  206. {"float64_positive", float64(12), 12, true},
  207. {"float64_zero", float64(0.0), 0, false},
  208. {"float64_negative", float64(-1.5), -1, false},
  209. {"float32_positive", float32(3), 3, true},
  210. {"string", "not a number", 0, false},
  211. {"nil", nil, 0, false},
  212. }
  213. for _, c := range cases {
  214. t.Run(c.name, func(t *testing.T) {
  215. gotVal, gotOk := readPositiveInt(c.in)
  216. if gotVal != c.wantVal || gotOk != c.wantOk {
  217. t.Fatalf("readPositiveInt(%v) = (%d, %v), want (%d, %v)", c.in, gotVal, gotOk, c.wantVal, c.wantOk)
  218. }
  219. })
  220. }
  221. }
  222. func TestSetStringParam(t *testing.T) {
  223. p := map[string]string{"existing": "value"}
  224. setStringParam(p, "new", "hello")
  225. if p["new"] != "hello" {
  226. t.Fatalf("missing key after set: %v", p)
  227. }
  228. setStringParam(p, "existing", "")
  229. if _, ok := p["existing"]; ok {
  230. t.Fatalf("empty value should delete the key, got %v", p)
  231. }
  232. }
  233. func TestSetIntParam(t *testing.T) {
  234. p := map[string]string{"existing": "10"}
  235. setIntParam(p, "n", 42)
  236. if p["n"] != "42" {
  237. t.Fatalf("set positive int: got %v", p)
  238. }
  239. setIntParam(p, "existing", 0)
  240. if _, ok := p["existing"]; ok {
  241. t.Fatalf("zero value should delete the key, got %v", p)
  242. }
  243. p["other"] = "5"
  244. setIntParam(p, "other", -1)
  245. if _, ok := p["other"]; ok {
  246. t.Fatalf("negative value should delete the key, got %v", p)
  247. }
  248. }
  249. func TestSetStringField(t *testing.T) {
  250. f := map[string]any{"existing": "value"}
  251. setStringField(f, "new", "hello")
  252. if f["new"] != "hello" {
  253. t.Fatalf("missing key after set: %v", f)
  254. }
  255. setStringField(f, "existing", "")
  256. if _, ok := f["existing"]; ok {
  257. t.Fatalf("empty value should delete the key, got %v", f)
  258. }
  259. }
  260. func TestSetIntField(t *testing.T) {
  261. f := map[string]any{"existing": 10}
  262. setIntField(f, "n", 7)
  263. if f["n"] != 7 {
  264. t.Fatalf("set positive int: got %v", f)
  265. }
  266. setIntField(f, "existing", 0)
  267. if _, ok := f["existing"]; ok {
  268. t.Fatalf("zero value should delete the key, got %v", f)
  269. }
  270. }
  271. func TestBuildVmessLink(t *testing.T) {
  272. obj := map[string]any{
  273. "v": "2",
  274. "ps": "remark",
  275. "add": "example.com",
  276. "port": 443,
  277. "net": "tcp",
  278. }
  279. link := buildVmessLink(obj)
  280. if !strings.HasPrefix(link, "vmess://") {
  281. t.Fatalf("missing vmess:// prefix: %q", link)
  282. }
  283. payload := strings.TrimPrefix(link, "vmess://")
  284. decoded, err := base64.StdEncoding.DecodeString(payload)
  285. if err != nil {
  286. t.Fatalf("base64 decode failed: %v", err)
  287. }
  288. var roundTrip map[string]any
  289. if err := json.Unmarshal(decoded, &roundTrip); err != nil {
  290. t.Fatalf("decoded payload is not JSON: %v\n%s", err, decoded)
  291. }
  292. if roundTrip["add"] != "example.com" {
  293. t.Fatalf("round-trip add = %v, want example.com", roundTrip["add"])
  294. }
  295. if roundTrip["ps"] != "remark" {
  296. t.Fatalf("round-trip ps = %v, want remark", roundTrip["ps"])
  297. }
  298. }
  299. func TestCloneVmessShareObj_CopiesEverythingByDefault(t *testing.T) {
  300. base := map[string]any{
  301. "v": "2",
  302. "sni": "example.com",
  303. "alpn": "h2",
  304. "fp": "chrome",
  305. "net": "tcp",
  306. }
  307. out := cloneVmessShareObj(base, "tls")
  308. for _, key := range []string{"sni", "alpn", "fp", "net", "v"} {
  309. if _, ok := out[key]; !ok {
  310. t.Fatalf("expected key %q to be preserved when security=tls, got %v", key, out)
  311. }
  312. }
  313. }
  314. func TestCloneVmessShareObj_NoneStripsTLSOnlyKeys(t *testing.T) {
  315. base := map[string]any{
  316. "v": "2",
  317. "sni": "example.com",
  318. "alpn": "h2",
  319. "fp": "chrome",
  320. "net": "tcp",
  321. }
  322. out := cloneVmessShareObj(base, "none")
  323. for _, key := range []string{"sni", "alpn", "fp"} {
  324. if _, ok := out[key]; ok {
  325. t.Fatalf("security=none should strip %q, got %v", key, out)
  326. }
  327. }
  328. if out["v"] != "2" || out["net"] != "tcp" {
  329. t.Fatalf("non-TLS keys should remain, got %v", out)
  330. }
  331. }
  332. func TestExtractKcpShareFields_Defaults(t *testing.T) {
  333. stream := map[string]any{}
  334. got := extractKcpShareFields(stream)
  335. if got.headerType != "none" {
  336. t.Fatalf("default headerType = %q, want none", got.headerType)
  337. }
  338. if got.seed != "" || got.mtu != 0 || got.tti != 0 {
  339. t.Fatalf("default kcpShareFields should be zero except headerType, got %+v", got)
  340. }
  341. }
  342. func TestExtractKcpShareFields_ReadsAllFields(t *testing.T) {
  343. stream := map[string]any{
  344. "kcpSettings": map[string]any{
  345. "header": map[string]any{"type": "wechat-video"},
  346. "seed": "secret-seed",
  347. "mtu": float64(1350),
  348. "tti": float64(50),
  349. },
  350. }
  351. got := extractKcpShareFields(stream)
  352. if got.headerType != "wechat-video" {
  353. t.Fatalf("headerType = %q, want wechat-video", got.headerType)
  354. }
  355. if got.seed != "secret-seed" {
  356. t.Fatalf("seed = %q, want secret-seed", got.seed)
  357. }
  358. if got.mtu != 1350 {
  359. t.Fatalf("mtu = %d, want 1350", got.mtu)
  360. }
  361. if got.tti != 50 {
  362. t.Fatalf("tti = %d, want 50", got.tti)
  363. }
  364. }
  365. func TestKcpShareFields_ApplyToParams(t *testing.T) {
  366. params := map[string]string{}
  367. kcpShareFields{headerType: "wechat-video", seed: "s", mtu: 1350, tti: 50}.applyToParams(params)
  368. if params["headerType"] != "wechat-video" {
  369. t.Fatalf("headerType param = %q", params["headerType"])
  370. }
  371. if params["seed"] != "s" {
  372. t.Fatalf("seed param = %q", params["seed"])
  373. }
  374. if params["mtu"] != "1350" {
  375. t.Fatalf("mtu param = %q", params["mtu"])
  376. }
  377. if params["tti"] != "50" {
  378. t.Fatalf("tti param = %q", params["tti"])
  379. }
  380. }
  381. func TestKcpShareFields_ApplyToParams_NoneHeaderNotAdded(t *testing.T) {
  382. params := map[string]string{}
  383. kcpShareFields{headerType: "none"}.applyToParams(params)
  384. if _, ok := params["headerType"]; ok {
  385. t.Fatalf("headerType=none should not be added, got %v", params)
  386. }
  387. }
  388. func TestMarshalFinalMask_EmptyReturnsFalse(t *testing.T) {
  389. if _, ok := marshalFinalMask(map[string]any{}); ok {
  390. t.Fatal("expected ok=false for empty finalmask")
  391. }
  392. if _, ok := marshalFinalMask(nil); ok {
  393. t.Fatal("expected ok=false for nil finalmask")
  394. }
  395. }
  396. func TestMarshalFinalMask_WithContent(t *testing.T) {
  397. fm := map[string]any{
  398. "tcp": []any{
  399. map[string]any{"type": "fragment"},
  400. },
  401. }
  402. out, ok := marshalFinalMask(fm)
  403. if !ok {
  404. t.Fatal("expected ok=true for finalmask with valid tcp mask")
  405. }
  406. if !strings.Contains(out, `"tcp"`) {
  407. t.Fatalf("marshaled finalmask missing tcp key: %s", out)
  408. }
  409. if !strings.Contains(out, "fragment") {
  410. t.Fatalf("marshaled finalmask missing mask type: %s", out)
  411. }
  412. }
  413. func TestMarshalFinalMask_UnknownTypeIsDropped(t *testing.T) {
  414. fm := map[string]any{
  415. "tcp": []any{
  416. map[string]any{"type": "not-a-real-mask"},
  417. },
  418. }
  419. if _, ok := marshalFinalMask(fm); ok {
  420. t.Fatal("unknown mask types should be dropped, leaving nothing to marshal")
  421. }
  422. }
  423. func TestHasFinalMaskContent(t *testing.T) {
  424. if hasFinalMaskContent(nil) {
  425. t.Fatal("nil should not count as content")
  426. }
  427. if hasFinalMaskContent(map[string]any{}) {
  428. t.Fatal("empty map should not count as content")
  429. }
  430. if !hasFinalMaskContent(map[string]any{"x": 1}) {
  431. t.Fatal("non-empty map should count as content")
  432. }
  433. }