1
0

remote_test.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442
  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 TestRemoteHTTPClientEgressProxy(t *testing.T) {
  183. // OutboundTag + a resolver → a dedicated proxy client (not the shared default).
  184. withTag := NewRemote(&model.Node{Id: 1, Scheme: "https", TlsVerifyMode: "verify", OutboundTag: "warp"}, stubEgress{url: "socks5://127.0.0.1:1080"})
  185. c, err := withTag.httpClient()
  186. if err != nil {
  187. t.Fatalf("httpClient: %v", err)
  188. }
  189. if c == defaultNodeHTTPClient {
  190. t.Fatal("OutboundTag + resolver must produce a dedicated egress client, not the shared default")
  191. }
  192. // No OutboundTag → no egress proxy → shared default client (verify mode).
  193. noTag := NewRemote(&model.Node{Id: 2, Scheme: "https", TlsVerifyMode: "verify"}, stubEgress{url: "socks5://127.0.0.1:1080"})
  194. c2, err := noTag.httpClient()
  195. if err != nil {
  196. t.Fatalf("httpClient: %v", err)
  197. }
  198. if c2 != defaultNodeHTTPClient {
  199. t.Fatal("no OutboundTag must use the shared default client")
  200. }
  201. }
  202. func TestRemoteDoSetsContentType(t *testing.T) {
  203. var gotCT string
  204. srv := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  205. gotCT = r.Header.Get("Content-Type")
  206. w.Header().Set("Content-Type", "application/json")
  207. _, _ = w.Write([]byte(`{"success":true}`))
  208. }))
  209. defer srv.Close()
  210. r := NewRemote(nodeForServer(t, srv, "skip", ""), nil)
  211. if _, err := r.do(context.Background(), http.MethodPost, "x", url.Values{"a": {"b"}}); err != nil {
  212. t.Fatalf("do: %v", err)
  213. }
  214. if gotCT != "application/x-www-form-urlencoded" {
  215. t.Fatalf("Content-Type = %q, want application/x-www-form-urlencoded", gotCT)
  216. }
  217. }
  218. func TestRemoteBaseURL(t *testing.T) {
  219. cases := []struct {
  220. name string
  221. scheme string
  222. port int
  223. bp string
  224. want string
  225. wantErr bool
  226. }{
  227. {"https default path", "https", 443, "", "https://example.com:443/", false},
  228. {"http custom path gets trailing slash", "http", 8080, "/panel", "http://example.com:8080/panel/", false},
  229. {"empty scheme defaults to https", "", 2096, "/", "https://example.com:2096/", false},
  230. {"invalid scheme defaults to https", "ftp", 2096, "/", "https://example.com:2096/", false},
  231. {"port zero rejected", "https", 0, "/", "", true},
  232. {"port above range rejected", "https", 65536, "/", "", true},
  233. {"negative port rejected", "https", -1, "/", "", true},
  234. {"max port accepted", "https", 65535, "/", "https://example.com:65535/", false},
  235. }
  236. for _, c := range cases {
  237. t.Run(c.name, func(t *testing.T) {
  238. r := NewRemote(&model.Node{Address: "example.com", Scheme: c.scheme, Port: c.port, BasePath: c.bp}, nil)
  239. got, err := r.baseURL()
  240. if c.wantErr {
  241. if err == nil {
  242. t.Fatalf("expected error for scheme=%q port=%d", c.scheme, c.port)
  243. }
  244. return
  245. }
  246. if err != nil {
  247. t.Fatalf("unexpected error: %v", err)
  248. }
  249. if got != c.want {
  250. t.Fatalf("baseURL = %q, want %q", got, c.want)
  251. }
  252. })
  253. }
  254. }
  255. func TestIsNonEmptySlice(t *testing.T) {
  256. cases := []struct {
  257. name string
  258. in any
  259. want bool
  260. }{
  261. {"non-empty slice", []any{1}, true},
  262. {"empty slice", []any{}, false},
  263. {"nil slice", []any(nil), false},
  264. {"not a slice", "x", false},
  265. }
  266. for _, c := range cases {
  267. t.Run(c.name, func(t *testing.T) {
  268. if got := isNonEmptySlice(c.in); got != c.want {
  269. t.Fatalf("isNonEmptySlice(%#v) = %v, want %v", c.in, got, c.want)
  270. }
  271. })
  272. }
  273. }
  274. func TestWireInboundTrafficReset(t *testing.T) {
  275. with := wireInbound(&model.Inbound{TrafficReset: "monthly", TrafficResetDay: 15}, 0)
  276. if got := with.Get("trafficReset"); got != "monthly" {
  277. t.Fatalf("trafficReset = %q, want monthly", got)
  278. }
  279. if got := with.Get("trafficResetDay"); got != "15" {
  280. t.Fatalf("trafficResetDay = %q, want 15", got)
  281. }
  282. // Empty TrafficReset must be omitted entirely, not sent as an empty field.
  283. without := wireInbound(&model.Inbound{}, 0)
  284. if without.Has("trafficReset") {
  285. t.Fatalf("trafficReset must be omitted when empty, got %q", without.Get("trafficReset"))
  286. }
  287. }
  288. func TestWireInboundDefaultsShareAddressStrategy(t *testing.T) {
  289. values := wireInbound(&model.Inbound{}, 0)
  290. if got := values.Get("shareAddrStrategy"); got != "node" {
  291. t.Fatalf("shareAddrStrategy = %q, want node", got)
  292. }
  293. values = wireInbound(&model.Inbound{ShareAddrStrategy: "auto"}, 0)
  294. if got := values.Get("shareAddrStrategy"); got != "node" {
  295. t.Fatalf("invalid shareAddrStrategy = %q, want node", got)
  296. }
  297. }
  298. func TestStripNodeInboundTagPrefix(t *testing.T) {
  299. cases := []struct {
  300. nodeID int
  301. tag string
  302. want string
  303. }{
  304. {2, "n2-in-443-tcp", "in-443-tcp"},
  305. {2, "in-443-tcp", "in-443-tcp"},
  306. {2, "my-custom", "my-custom"},
  307. {2, "n3-in-443-tcp", "n3-in-443-tcp"},
  308. {0, "n2-in-443-tcp", "n2-in-443-tcp"},
  309. }
  310. for _, c := range cases {
  311. if got := stripNodeInboundTagPrefix(c.nodeID, c.tag); got != c.want {
  312. t.Fatalf("stripNodeInboundTagPrefix(%d, %q) = %q, want %q", c.nodeID, c.tag, got, c.want)
  313. }
  314. }
  315. }
  316. func TestWireInboundStripsNodeTagOnPush(t *testing.T) {
  317. values := wireInbound(&model.Inbound{Tag: "n2-in-443-tcp"}, 2)
  318. if got := values.Get("tag"); got != "in-443-tcp" {
  319. t.Fatalf("tag = %q, want in-443-tcp", got)
  320. }
  321. values = wireInbound(&model.Inbound{Tag: "n2-in-443-tcp"}, 0)
  322. if got := values.Get("tag"); got != "n2-in-443-tcp" {
  323. t.Fatalf("nodeID 0 must not strip, got %q", got)
  324. }
  325. }
  326. func TestSanitizeStreamSettingsForRemote(t *testing.T) {
  327. tests := []struct {
  328. name string
  329. input string
  330. // wantCertFile / wantKeyFile: expected presence after sanitize
  331. wantCertFile bool
  332. wantKeyFile bool
  333. }{
  334. {
  335. name: "file paths only — kept intact (remote node paths)",
  336. input: `{
  337. "tlsSettings": {
  338. "certificates": [{
  339. "certificateFile": "/etc/ssl/cert.crt",
  340. "keyFile": "/etc/ssl/key.key"
  341. }]
  342. }
  343. }`,
  344. wantCertFile: true,
  345. wantKeyFile: true,
  346. },
  347. {
  348. name: "inline content only — unchanged",
  349. input: `{
  350. "tlsSettings": {
  351. "certificates": [{
  352. "certificate": ["-----BEGIN CERTIFICATE-----"],
  353. "key": ["-----BEGIN PRIVATE KEY-----"]
  354. }]
  355. }
  356. }`,
  357. wantCertFile: false,
  358. wantKeyFile: false,
  359. },
  360. {
  361. name: "both file paths and inline content — file paths stripped (redundant)",
  362. input: `{
  363. "tlsSettings": {
  364. "certificates": [{
  365. "certificateFile": "/etc/ssl/cert.crt",
  366. "keyFile": "/etc/ssl/key.key",
  367. "certificate": ["-----BEGIN CERTIFICATE-----"],
  368. "key": ["-----BEGIN PRIVATE KEY-----"]
  369. }]
  370. }
  371. }`,
  372. wantCertFile: false,
  373. wantKeyFile: false,
  374. },
  375. {
  376. name: "empty stream settings",
  377. input: "",
  378. // empty input returns empty, nothing to check
  379. },
  380. }
  381. for _, tc := range tests {
  382. t.Run(tc.name, func(t *testing.T) {
  383. if tc.input == "" {
  384. if got := sanitizeStreamSettingsForRemote(tc.input); got != "" {
  385. t.Errorf("expected empty string, got %q", got)
  386. }
  387. return
  388. }
  389. got := sanitizeStreamSettingsForRemote(tc.input)
  390. var out map[string]any
  391. if err := json.Unmarshal([]byte(got), &out); err != nil {
  392. t.Fatalf("output is not valid JSON: %v\noutput: %s", err, got)
  393. }
  394. tls, _ := out["tlsSettings"].(map[string]any)
  395. certs, _ := tls["certificates"].([]any)
  396. if len(certs) == 0 {
  397. t.Fatal("certificates array missing in output")
  398. }
  399. cert, _ := certs[0].(map[string]any)
  400. _, hasCertFile := cert["certificateFile"]
  401. _, hasKeyFile := cert["keyFile"]
  402. if hasCertFile != tc.wantCertFile {
  403. t.Errorf("certificateFile present=%v, want %v", hasCertFile, tc.wantCertFile)
  404. }
  405. if hasKeyFile != tc.wantKeyFile {
  406. t.Errorf("keyFile present=%v, want %v", hasKeyFile, tc.wantKeyFile)
  407. }
  408. })
  409. }
  410. }