remote_test.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512
  1. package runtime
  2. import (
  3. "bytes"
  4. "context"
  5. "encoding/json"
  6. "errors"
  7. "net/http"
  8. "net/http/httptest"
  9. "net/url"
  10. "strings"
  11. "testing"
  12. "github.com/mhsanaei/3x-ui/v3/internal/database/model"
  13. )
  14. // TestRemoteDo_RejectsOversizeResponse: a node streaming a body larger than
  15. // maxRemoteResponseBytes must error out instead of the master buffering it
  16. // unbounded.
  17. func TestRemoteDo_RejectsOversizeResponse(t *testing.T) {
  18. srv := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
  19. w.WriteHeader(http.StatusOK)
  20. chunk := bytes.Repeat([]byte("a"), 1<<20) // 1 MiB
  21. for written := 0; written <= maxRemoteResponseBytes; written += len(chunk) {
  22. if _, err := w.Write(chunk); err != nil {
  23. return // client stopped reading at the cap
  24. }
  25. }
  26. }))
  27. defer srv.Close()
  28. r := NewRemote(nodeForServer(t, srv, "skip", ""), nil)
  29. if _, err := r.do(context.Background(), http.MethodGet, "/probe", nil); !errors.Is(err, errRemoteResponseTooLarge) {
  30. t.Fatalf("do() error = %v, want errRemoteResponseTooLarge", err)
  31. }
  32. }
  33. // TestRemoteDo_AcceptsNormalResponse confirms the cap does not break a normal
  34. // under-limit envelope.
  35. func TestRemoteDo_AcceptsNormalResponse(t *testing.T) {
  36. srv := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
  37. w.Header().Set("Content-Type", "application/json")
  38. _, _ = w.Write([]byte(`{"success":true,"msg":"ok","obj":{"x":1}}`))
  39. }))
  40. defer srv.Close()
  41. r := NewRemote(nodeForServer(t, srv, "skip", ""), nil)
  42. env, err := r.do(context.Background(), http.MethodGet, "/probe", nil)
  43. if err != nil {
  44. t.Fatalf("do() unexpected error: %v", err)
  45. }
  46. if env == nil || !env.Success {
  47. t.Fatalf("env = %+v, want Success=true", env)
  48. }
  49. }
  50. func TestRemoteSetInboundSubSortIndexSendsOnlyNarrowField(t *testing.T) {
  51. var posted url.Values
  52. srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
  53. w.Header().Set("Content-Type", "application/json")
  54. switch req.URL.Path {
  55. case "/panel/api/inbounds/list":
  56. _, _ = w.Write([]byte(`{"success":true,"obj":[{"id":42,"tag":"remote-tag"}]}`))
  57. case "/panel/api/inbounds/42/subSortIndex":
  58. if err := req.ParseForm(); err != nil {
  59. t.Fatalf("ParseForm: %v", err)
  60. }
  61. posted = req.PostForm
  62. _, _ = w.Write([]byte(`{"success":true}`))
  63. default:
  64. http.NotFound(w, req)
  65. }
  66. }))
  67. defer srv.Close()
  68. r := NewRemote(nodeForPlainServer(t, srv, "verify", "tok"), nil)
  69. ib := &model.Inbound{Tag: "remote-tag", Settings: `{"clients":[{"email":"newer"}]}`}
  70. if err := r.SetInboundSubSortIndex(context.Background(), ib, 7); err != nil {
  71. t.Fatalf("SetInboundSubSortIndex: %v", err)
  72. }
  73. if got := posted.Get("subSortIndex"); got != "7" {
  74. t.Fatalf("subSortIndex = %q, want 7", got)
  75. }
  76. if len(posted) != 1 {
  77. t.Fatalf("posted fields = %v, want only subSortIndex", posted)
  78. }
  79. }
  80. // TestReadCappedBody_Boundary pins the cap+1 contract cheaply (no large allocs):
  81. // a body of exactly limit is accepted; limit+1 and beyond are rejected.
  82. func TestReadCappedBody_Boundary(t *testing.T) {
  83. const limit = 8
  84. cases := []struct {
  85. name string
  86. n int
  87. wantErr bool
  88. }{
  89. {"under", limit - 1, false},
  90. {"exact", limit, false},
  91. {"over-by-one", limit + 1, true},
  92. {"way-over", limit * 4, true},
  93. }
  94. for _, c := range cases {
  95. t.Run(c.name, func(t *testing.T) {
  96. raw, err := readCappedBody(bytes.NewReader(bytes.Repeat([]byte("x"), c.n)), limit)
  97. if c.wantErr {
  98. if !errors.Is(err, errRemoteResponseTooLarge) {
  99. t.Fatalf("n=%d: err=%v, want errRemoteResponseTooLarge", c.n, err)
  100. }
  101. return
  102. }
  103. if err != nil {
  104. t.Fatalf("n=%d: unexpected err %v", c.n, err)
  105. }
  106. if len(raw) != c.n {
  107. t.Fatalf("n=%d: read %d bytes, want %d", c.n, len(raw), c.n)
  108. }
  109. })
  110. }
  111. }
  112. // TestRemoteDo_NonOKStatusReturnsHTTPError confirms a non-OK status is reported
  113. // as an HTTP error (with a bounded diagnostic snippet) rather than being read as
  114. // a success payload — i.e. status precedence over the body.
  115. func TestRemoteDo_NonOKStatusReturnsHTTPError(t *testing.T) {
  116. srv := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
  117. w.WriteHeader(http.StatusInternalServerError)
  118. _, _ = w.Write([]byte("boom"))
  119. }))
  120. defer srv.Close()
  121. r := NewRemote(nodeForServer(t, srv, "skip", ""), nil)
  122. _, err := r.do(context.Background(), http.MethodGet, "/probe", nil)
  123. if err == nil {
  124. t.Fatal("do() error = nil, want HTTP 500 error")
  125. }
  126. if !strings.Contains(err.Error(), "HTTP 500") || !strings.Contains(err.Error(), "boom") {
  127. t.Fatalf("error = %q, want it to mention HTTP 500 and the body snippet", err)
  128. }
  129. }
  130. type stubEgress struct{ url string }
  131. func (s stubEgress) NodeEgressProxyURL(int) string { return s.url }
  132. // cacheGetTag must resolve a remote inbound id even when the n<id>- prefix
  133. // sits on only one side: the node may store the bare tag while the central
  134. // panel pushes the prefixed form, or vice versa. Without this a mismatch makes
  135. // the push create a duplicate inbound on the node.
  136. func TestCacheGetTag_PrefixAgnostic(t *testing.T) {
  137. cases := []struct {
  138. name string
  139. cacheTag string
  140. lookup string
  141. wantID int
  142. wantFound bool
  143. }{
  144. {"exact", "n1-in-443-tcp", "n1-in-443-tcp", 7, true},
  145. {"node bare, lookup prefixed", "in-443-tcp", "n1-in-443-tcp", 7, true},
  146. {"node prefixed, lookup bare", "n1-in-443-tcp", "in-443-tcp", 7, true},
  147. {"unrelated tag", "in-443-tcp", "in-999-tcp", 0, false},
  148. }
  149. for _, c := range cases {
  150. t.Run(c.name, func(t *testing.T) {
  151. r := NewRemote(&model.Node{Id: 1, Name: "n1"}, nil)
  152. r.cacheSet(c.cacheTag, 7)
  153. id, ok := r.cacheGetTag(c.lookup)
  154. if ok != c.wantFound || id != c.wantID {
  155. t.Fatalf("cacheGetTag(%q) = (%d, %v), want (%d, %v)", c.lookup, id, ok, c.wantID, c.wantFound)
  156. }
  157. })
  158. }
  159. }
  160. func TestWireInboundIncludesShareAddressFields(t *testing.T) {
  161. values := wireInbound(&model.Inbound{
  162. ShareAddrStrategy: "custom",
  163. ShareAddr: "edge.example.com",
  164. }, 0)
  165. if got := values.Get("shareAddrStrategy"); got != "custom" {
  166. t.Fatalf("shareAddrStrategy = %q, want custom", got)
  167. }
  168. if got := values.Get("shareAddr"); got != "edge.example.com" {
  169. t.Fatalf("shareAddr = %q, want edge.example.com", got)
  170. }
  171. }
  172. // A node that does not mirror DisableFlow re-injects Vision into its own xray
  173. // config and share links, undoing the opt-out on every multi-node deployment.
  174. func TestWireInboundCarriesDisableFlow(t *testing.T) {
  175. if got := wireInbound(&model.Inbound{DisableFlow: true}, 0).Get("disableFlow"); got != "true" {
  176. t.Fatalf("disableFlow = %q, want true", got)
  177. }
  178. if got := wireInbound(&model.Inbound{}, 0).Get("disableFlow"); got != "false" {
  179. t.Fatalf("disableFlow = %q, want false", got)
  180. }
  181. }
  182. func TestWireInboundCarriesExcludeFromSub(t *testing.T) {
  183. if got := wireInbound(&model.Inbound{ExcludeFromSub: true}, 0).Get("excludeFromSub"); got != "true" {
  184. t.Fatalf("excludeFromSub = %q, want true", got)
  185. }
  186. if got := wireInbound(&model.Inbound{}, 0).Get("excludeFromSub"); got != "false" {
  187. t.Fatalf("excludeFromSub = %q, want false", got)
  188. }
  189. }
  190. func TestRemoteHTTPClientEgressProxy(t *testing.T) {
  191. // OutboundTag + a resolver → a dedicated proxy client (not the shared default).
  192. withTag := NewRemote(&model.Node{Id: 1, Scheme: "https", TlsVerifyMode: "verify", OutboundTag: "warp"}, stubEgress{url: "socks5://127.0.0.1:1080"})
  193. c, err := withTag.httpClient()
  194. if err != nil {
  195. t.Fatalf("httpClient: %v", err)
  196. }
  197. if c == defaultNodeHTTPClient {
  198. t.Fatal("OutboundTag + resolver must produce a dedicated egress client, not the shared default")
  199. }
  200. // No OutboundTag → no egress proxy → shared default client (verify mode).
  201. noTag := NewRemote(&model.Node{Id: 2, Scheme: "https", TlsVerifyMode: "verify"}, stubEgress{url: "socks5://127.0.0.1:1080"})
  202. c2, err := noTag.httpClient()
  203. if err != nil {
  204. t.Fatalf("httpClient: %v", err)
  205. }
  206. if c2 != defaultNodeHTTPClient {
  207. t.Fatal("no OutboundTag must use the shared default client")
  208. }
  209. }
  210. func TestRemoteDoSetsContentType(t *testing.T) {
  211. var gotCT string
  212. srv := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  213. gotCT = r.Header.Get("Content-Type")
  214. w.Header().Set("Content-Type", "application/json")
  215. _, _ = w.Write([]byte(`{"success":true}`))
  216. }))
  217. defer srv.Close()
  218. r := NewRemote(nodeForServer(t, srv, "skip", ""), nil)
  219. if _, err := r.do(context.Background(), http.MethodPost, "x", url.Values{"a": {"b"}}); err != nil {
  220. t.Fatalf("do: %v", err)
  221. }
  222. if gotCT != "application/x-www-form-urlencoded" {
  223. t.Fatalf("Content-Type = %q, want application/x-www-form-urlencoded", gotCT)
  224. }
  225. }
  226. func TestRemoteBaseURL(t *testing.T) {
  227. cases := []struct {
  228. name string
  229. scheme string
  230. port int
  231. bp string
  232. want string
  233. wantErr bool
  234. }{
  235. {"https default path", "https", 443, "", "https://example.com:443/", false},
  236. {"http custom path gets trailing slash", "http", 8080, "/panel", "http://example.com:8080/panel/", false},
  237. {"empty scheme defaults to https", "", 2096, "/", "https://example.com:2096/", false},
  238. {"invalid scheme defaults to https", "ftp", 2096, "/", "https://example.com:2096/", false},
  239. {"port zero rejected", "https", 0, "/", "", true},
  240. {"port above range rejected", "https", 65536, "/", "", true},
  241. {"negative port rejected", "https", -1, "/", "", true},
  242. {"max port accepted", "https", 65535, "/", "https://example.com:65535/", false},
  243. }
  244. for _, c := range cases {
  245. t.Run(c.name, func(t *testing.T) {
  246. r := NewRemote(&model.Node{Address: "example.com", Scheme: c.scheme, Port: c.port, BasePath: c.bp}, nil)
  247. got, err := r.baseURL()
  248. if c.wantErr {
  249. if err == nil {
  250. t.Fatalf("expected error for scheme=%q port=%d", c.scheme, c.port)
  251. }
  252. return
  253. }
  254. if err != nil {
  255. t.Fatalf("unexpected error: %v", err)
  256. }
  257. if got != c.want {
  258. t.Fatalf("baseURL = %q, want %q", got, c.want)
  259. }
  260. })
  261. }
  262. }
  263. func TestIsNonEmptySlice(t *testing.T) {
  264. cases := []struct {
  265. name string
  266. in any
  267. want bool
  268. }{
  269. {"non-empty slice", []any{1}, true},
  270. {"empty slice", []any{}, false},
  271. {"nil slice", []any(nil), false},
  272. {"not a slice", "x", false},
  273. }
  274. for _, c := range cases {
  275. t.Run(c.name, func(t *testing.T) {
  276. if got := isNonEmptySlice(c.in); got != c.want {
  277. t.Fatalf("isNonEmptySlice(%#v) = %v, want %v", c.in, got, c.want)
  278. }
  279. })
  280. }
  281. }
  282. func TestWireInboundTrafficReset(t *testing.T) {
  283. with := wireInbound(&model.Inbound{TrafficReset: "monthly", TrafficResetDay: 15}, 0)
  284. if got := with.Get("trafficReset"); got != "monthly" {
  285. t.Fatalf("trafficReset = %q, want monthly", got)
  286. }
  287. if got := with.Get("trafficResetDay"); got != "15" {
  288. t.Fatalf("trafficResetDay = %q, want 15", got)
  289. }
  290. // Empty TrafficReset must be omitted entirely, not sent as an empty field.
  291. without := wireInbound(&model.Inbound{}, 0)
  292. if without.Has("trafficReset") {
  293. t.Fatalf("trafficReset must be omitted when empty, got %q", without.Get("trafficReset"))
  294. }
  295. }
  296. func TestWireInboundDefaultsShareAddressStrategy(t *testing.T) {
  297. values := wireInbound(&model.Inbound{}, 0)
  298. if got := values.Get("shareAddrStrategy"); got != "node" {
  299. t.Fatalf("shareAddrStrategy = %q, want node", got)
  300. }
  301. values = wireInbound(&model.Inbound{ShareAddrStrategy: "auto"}, 0)
  302. if got := values.Get("shareAddrStrategy"); got != "node" {
  303. t.Fatalf("invalid shareAddrStrategy = %q, want node", got)
  304. }
  305. }
  306. func TestStripNodeInboundTagPrefix(t *testing.T) {
  307. cases := []struct {
  308. nodeID int
  309. tag string
  310. want string
  311. }{
  312. {2, "n2-in-443-tcp", "in-443-tcp"},
  313. {2, "in-443-tcp", "in-443-tcp"},
  314. {2, "my-custom", "my-custom"},
  315. {2, "n3-in-443-tcp", "n3-in-443-tcp"},
  316. {0, "n2-in-443-tcp", "n2-in-443-tcp"},
  317. }
  318. for _, c := range cases {
  319. if got := stripNodeInboundTagPrefix(c.nodeID, c.tag); got != c.want {
  320. t.Fatalf("stripNodeInboundTagPrefix(%d, %q) = %q, want %q", c.nodeID, c.tag, got, c.want)
  321. }
  322. }
  323. }
  324. func TestWireInboundStripsNodeTagOnPush(t *testing.T) {
  325. values := wireInbound(&model.Inbound{Tag: "n2-in-443-tcp"}, 2)
  326. if got := values.Get("tag"); got != "in-443-tcp" {
  327. t.Fatalf("tag = %q, want in-443-tcp", got)
  328. }
  329. values = wireInbound(&model.Inbound{Tag: "n2-in-443-tcp"}, 0)
  330. if got := values.Get("tag"); got != "n2-in-443-tcp" {
  331. t.Fatalf("nodeID 0 must not strip, got %q", got)
  332. }
  333. }
  334. func TestSanitizeStreamSettingsForRemote(t *testing.T) {
  335. tests := []struct {
  336. name string
  337. input string
  338. // wantCertFile / wantKeyFile: expected presence after sanitize
  339. wantCertFile bool
  340. wantKeyFile bool
  341. }{
  342. {
  343. name: "file paths only — kept intact (remote node paths)",
  344. input: `{
  345. "tlsSettings": {
  346. "certificates": [{
  347. "certificateFile": "/etc/ssl/cert.crt",
  348. "keyFile": "/etc/ssl/key.key"
  349. }]
  350. }
  351. }`,
  352. wantCertFile: true,
  353. wantKeyFile: true,
  354. },
  355. {
  356. name: "inline content only — unchanged",
  357. input: `{
  358. "tlsSettings": {
  359. "certificates": [{
  360. "certificate": ["-----BEGIN CERTIFICATE-----"],
  361. "key": ["-----BEGIN PRIVATE KEY-----"]
  362. }]
  363. }
  364. }`,
  365. wantCertFile: false,
  366. wantKeyFile: false,
  367. },
  368. {
  369. name: "both file paths and inline content — file paths stripped (redundant)",
  370. input: `{
  371. "tlsSettings": {
  372. "certificates": [{
  373. "certificateFile": "/etc/ssl/cert.crt",
  374. "keyFile": "/etc/ssl/key.key",
  375. "certificate": ["-----BEGIN CERTIFICATE-----"],
  376. "key": ["-----BEGIN PRIVATE KEY-----"]
  377. }]
  378. }
  379. }`,
  380. wantCertFile: false,
  381. wantKeyFile: false,
  382. },
  383. {
  384. name: "empty stream settings",
  385. input: "",
  386. // empty input returns empty, nothing to check
  387. },
  388. }
  389. for _, tc := range tests {
  390. t.Run(tc.name, func(t *testing.T) {
  391. if tc.input == "" {
  392. if got := sanitizeStreamSettingsForRemote(tc.input); got != "" {
  393. t.Errorf("expected empty string, got %q", got)
  394. }
  395. return
  396. }
  397. got := sanitizeStreamSettingsForRemote(tc.input)
  398. var out map[string]any
  399. if err := json.Unmarshal([]byte(got), &out); err != nil {
  400. t.Fatalf("output is not valid JSON: %v\noutput: %s", err, got)
  401. }
  402. tls, _ := out["tlsSettings"].(map[string]any)
  403. certs, _ := tls["certificates"].([]any)
  404. if len(certs) == 0 {
  405. t.Fatal("certificates array missing in output")
  406. }
  407. cert, _ := certs[0].(map[string]any)
  408. _, hasCertFile := cert["certificateFile"]
  409. _, hasKeyFile := cert["keyFile"]
  410. if hasCertFile != tc.wantCertFile {
  411. t.Errorf("certificateFile present=%v, want %v", hasCertFile, tc.wantCertFile)
  412. }
  413. if hasKeyFile != tc.wantKeyFile {
  414. t.Errorf("keyFile present=%v, want %v", hasKeyFile, tc.wantKeyFile)
  415. }
  416. })
  417. }
  418. }
  419. // refreshRemoteIDs rebuilds the cache from node-reported tags only, so an
  420. // adopted alias must be re-applied or every later op on that inbound misses.
  421. func TestRemoteAdoptedAliasSurvivesRefresh(t *testing.T) {
  422. srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
  423. w.Header().Set("Content-Type", "application/json")
  424. if req.URL.Path == "/panel/api/inbounds/list" {
  425. _, _ = w.Write([]byte(`{"success":true,"obj":[{"id":5,"tag":"legacy-in"},{"id":6,"tag":"in-2"}]}`))
  426. return
  427. }
  428. http.NotFound(w, req)
  429. }))
  430. defer srv.Close()
  431. r := NewRemote(nodeForPlainServer(t, srv, "verify", "tok"), nil)
  432. central := &model.Inbound{Tag: "central-in", Settings: `{"clients":[]}`}
  433. r.AdoptInboundAlias(central, RemoteInboundOption{Id: 5, Tag: "legacy-in"})
  434. // Resolving a different tag misses the cache and forces a full refresh.
  435. if _, err := r.resolveRemoteID(context.Background(), "in-2"); err != nil {
  436. t.Fatalf("resolveRemoteID(in-2): %v", err)
  437. }
  438. id, err := r.resolveRemoteID(context.Background(), central.Tag)
  439. if err != nil {
  440. t.Fatalf("resolveRemoteID(%s) after refresh: %v", central.Tag, err)
  441. }
  442. if id != 5 {
  443. t.Fatalf("adopted alias resolved to %d, want 5", id)
  444. }
  445. }
  446. // A stale alias must never outrank the node's own report: once the node lists
  447. // an inbound under the central tag itself, that id is the authoritative one.
  448. func TestRemoteAdoptedAliasYieldsToNodeReportedTag(t *testing.T) {
  449. srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
  450. w.Header().Set("Content-Type", "application/json")
  451. if req.URL.Path == "/panel/api/inbounds/list" {
  452. _, _ = w.Write([]byte(`{"success":true,"obj":[{"id":5,"tag":"central-in"},{"id":7,"tag":"legacy-in"},{"id":9,"tag":"in-2"}]}`))
  453. return
  454. }
  455. http.NotFound(w, req)
  456. }))
  457. defer srv.Close()
  458. r := NewRemote(nodeForPlainServer(t, srv, "verify", "tok"), nil)
  459. central := &model.Inbound{Tag: "central-in", Settings: `{"clients":[]}`}
  460. r.AdoptInboundAlias(central, RemoteInboundOption{Id: 7, Tag: "legacy-in"})
  461. if _, err := r.resolveRemoteID(context.Background(), "in-2"); err != nil {
  462. t.Fatalf("resolveRemoteID(in-2): %v", err)
  463. }
  464. id, err := r.resolveRemoteID(context.Background(), central.Tag)
  465. if err != nil {
  466. t.Fatalf("resolveRemoteID(%s): %v", central.Tag, err)
  467. }
  468. if id != 5 {
  469. t.Fatalf("central tag resolved to %d via a stale alias, want 5 (the id the node reports)", id)
  470. }
  471. }