remote_test.go 13 KB

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