remote_test.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397
  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. // TestReadCappedBody_Boundary pins the cap+1 contract cheaply (no large allocs):
  51. // a body of exactly limit is accepted; limit+1 and beyond are rejected.
  52. func TestReadCappedBody_Boundary(t *testing.T) {
  53. const limit = 8
  54. cases := []struct {
  55. name string
  56. n int
  57. wantErr bool
  58. }{
  59. {"under", limit - 1, false},
  60. {"exact", limit, false},
  61. {"over-by-one", limit + 1, true},
  62. {"way-over", limit * 4, true},
  63. }
  64. for _, c := range cases {
  65. t.Run(c.name, func(t *testing.T) {
  66. raw, err := readCappedBody(bytes.NewReader(bytes.Repeat([]byte("x"), c.n)), limit)
  67. if c.wantErr {
  68. if !errors.Is(err, errRemoteResponseTooLarge) {
  69. t.Fatalf("n=%d: err=%v, want errRemoteResponseTooLarge", c.n, err)
  70. }
  71. return
  72. }
  73. if err != nil {
  74. t.Fatalf("n=%d: unexpected err %v", c.n, err)
  75. }
  76. if len(raw) != c.n {
  77. t.Fatalf("n=%d: read %d bytes, want %d", c.n, len(raw), c.n)
  78. }
  79. })
  80. }
  81. }
  82. // TestRemoteDo_NonOKStatusReturnsHTTPError confirms a non-OK status is reported
  83. // as an HTTP error (with a bounded diagnostic snippet) rather than being read as
  84. // a success payload — i.e. status precedence over the body.
  85. func TestRemoteDo_NonOKStatusReturnsHTTPError(t *testing.T) {
  86. srv := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
  87. w.WriteHeader(http.StatusInternalServerError)
  88. _, _ = w.Write([]byte("boom"))
  89. }))
  90. defer srv.Close()
  91. r := NewRemote(nodeForServer(t, srv, "skip", ""), nil)
  92. _, err := r.do(context.Background(), http.MethodGet, "/probe", nil)
  93. if err == nil {
  94. t.Fatal("do() error = nil, want HTTP 500 error")
  95. }
  96. if !strings.Contains(err.Error(), "HTTP 500") || !strings.Contains(err.Error(), "boom") {
  97. t.Fatalf("error = %q, want it to mention HTTP 500 and the body snippet", err)
  98. }
  99. }
  100. type stubEgress struct{ url string }
  101. func (s stubEgress) NodeEgressProxyURL(int) string { return s.url }
  102. // cacheGetTag must resolve a remote inbound id even when the n<id>- prefix
  103. // sits on only one side: the node may store the bare tag while the central
  104. // panel pushes the prefixed form, or vice versa. Without this a mismatch makes
  105. // the push create a duplicate inbound on the node.
  106. func TestCacheGetTag_PrefixAgnostic(t *testing.T) {
  107. cases := []struct {
  108. name string
  109. cacheTag string
  110. lookup string
  111. wantID int
  112. wantFound bool
  113. }{
  114. {"exact", "n1-in-443-tcp", "n1-in-443-tcp", 7, true},
  115. {"node bare, lookup prefixed", "in-443-tcp", "n1-in-443-tcp", 7, true},
  116. {"node prefixed, lookup bare", "n1-in-443-tcp", "in-443-tcp", 7, true},
  117. {"unrelated tag", "in-443-tcp", "in-999-tcp", 0, false},
  118. }
  119. for _, c := range cases {
  120. t.Run(c.name, func(t *testing.T) {
  121. r := NewRemote(&model.Node{Id: 1, Name: "n1"}, nil)
  122. r.cacheSet(c.cacheTag, 7)
  123. id, ok := r.cacheGetTag(c.lookup)
  124. if ok != c.wantFound || id != c.wantID {
  125. t.Fatalf("cacheGetTag(%q) = (%d, %v), want (%d, %v)", c.lookup, id, ok, c.wantID, c.wantFound)
  126. }
  127. })
  128. }
  129. }
  130. func TestWireInboundIncludesShareAddressFields(t *testing.T) {
  131. values := wireInbound(&model.Inbound{
  132. ShareAddrStrategy: "custom",
  133. ShareAddr: "edge.example.com",
  134. }, 0)
  135. if got := values.Get("shareAddrStrategy"); got != "custom" {
  136. t.Fatalf("shareAddrStrategy = %q, want custom", got)
  137. }
  138. if got := values.Get("shareAddr"); got != "edge.example.com" {
  139. t.Fatalf("shareAddr = %q, want edge.example.com", got)
  140. }
  141. }
  142. func TestRemoteHTTPClientEgressProxy(t *testing.T) {
  143. // OutboundTag + a resolver → a dedicated proxy client (not the shared default).
  144. withTag := NewRemote(&model.Node{Id: 1, Scheme: "https", TlsVerifyMode: "verify", OutboundTag: "warp"}, stubEgress{url: "socks5://127.0.0.1:1080"})
  145. c, err := withTag.httpClient()
  146. if err != nil {
  147. t.Fatalf("httpClient: %v", err)
  148. }
  149. if c == defaultNodeHTTPClient {
  150. t.Fatal("OutboundTag + resolver must produce a dedicated egress client, not the shared default")
  151. }
  152. // No OutboundTag → no egress proxy → shared default client (verify mode).
  153. noTag := NewRemote(&model.Node{Id: 2, Scheme: "https", TlsVerifyMode: "verify"}, stubEgress{url: "socks5://127.0.0.1:1080"})
  154. c2, err := noTag.httpClient()
  155. if err != nil {
  156. t.Fatalf("httpClient: %v", err)
  157. }
  158. if c2 != defaultNodeHTTPClient {
  159. t.Fatal("no OutboundTag must use the shared default client")
  160. }
  161. }
  162. func TestRemoteDoSetsContentType(t *testing.T) {
  163. var gotCT string
  164. srv := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  165. gotCT = r.Header.Get("Content-Type")
  166. w.Header().Set("Content-Type", "application/json")
  167. _, _ = w.Write([]byte(`{"success":true}`))
  168. }))
  169. defer srv.Close()
  170. r := NewRemote(nodeForServer(t, srv, "skip", ""), nil)
  171. if _, err := r.do(context.Background(), http.MethodPost, "x", url.Values{"a": {"b"}}); err != nil {
  172. t.Fatalf("do: %v", err)
  173. }
  174. if gotCT != "application/x-www-form-urlencoded" {
  175. t.Fatalf("Content-Type = %q, want application/x-www-form-urlencoded", gotCT)
  176. }
  177. }
  178. func TestRemoteBaseURL(t *testing.T) {
  179. cases := []struct {
  180. name string
  181. scheme string
  182. port int
  183. bp string
  184. want string
  185. wantErr bool
  186. }{
  187. {"https default path", "https", 443, "", "https://example.com:443/", false},
  188. {"http custom path gets trailing slash", "http", 8080, "/panel", "http://example.com:8080/panel/", false},
  189. {"empty scheme defaults to https", "", 2096, "/", "https://example.com:2096/", false},
  190. {"invalid scheme defaults to https", "ftp", 2096, "/", "https://example.com:2096/", false},
  191. {"port zero rejected", "https", 0, "/", "", true},
  192. {"port above range rejected", "https", 65536, "/", "", true},
  193. {"negative port rejected", "https", -1, "/", "", true},
  194. {"max port accepted", "https", 65535, "/", "https://example.com:65535/", false},
  195. }
  196. for _, c := range cases {
  197. t.Run(c.name, func(t *testing.T) {
  198. r := NewRemote(&model.Node{Address: "example.com", Scheme: c.scheme, Port: c.port, BasePath: c.bp}, nil)
  199. got, err := r.baseURL()
  200. if c.wantErr {
  201. if err == nil {
  202. t.Fatalf("expected error for scheme=%q port=%d", c.scheme, c.port)
  203. }
  204. return
  205. }
  206. if err != nil {
  207. t.Fatalf("unexpected error: %v", err)
  208. }
  209. if got != c.want {
  210. t.Fatalf("baseURL = %q, want %q", got, c.want)
  211. }
  212. })
  213. }
  214. }
  215. func TestIsNonEmptySlice(t *testing.T) {
  216. cases := []struct {
  217. name string
  218. in any
  219. want bool
  220. }{
  221. {"non-empty slice", []any{1}, true},
  222. {"empty slice", []any{}, false},
  223. {"nil slice", []any(nil), false},
  224. {"not a slice", "x", false},
  225. }
  226. for _, c := range cases {
  227. t.Run(c.name, func(t *testing.T) {
  228. if got := isNonEmptySlice(c.in); got != c.want {
  229. t.Fatalf("isNonEmptySlice(%#v) = %v, want %v", c.in, got, c.want)
  230. }
  231. })
  232. }
  233. }
  234. func TestWireInboundTrafficReset(t *testing.T) {
  235. with := wireInbound(&model.Inbound{TrafficReset: "daily"}, 0)
  236. if got := with.Get("trafficReset"); got != "daily" {
  237. t.Fatalf("trafficReset = %q, want daily", got)
  238. }
  239. // Empty TrafficReset must be omitted entirely, not sent as an empty field.
  240. without := wireInbound(&model.Inbound{}, 0)
  241. if without.Has("trafficReset") {
  242. t.Fatalf("trafficReset must be omitted when empty, got %q", without.Get("trafficReset"))
  243. }
  244. }
  245. func TestWireInboundDefaultsShareAddressStrategy(t *testing.T) {
  246. values := wireInbound(&model.Inbound{}, 0)
  247. if got := values.Get("shareAddrStrategy"); got != "node" {
  248. t.Fatalf("shareAddrStrategy = %q, want node", got)
  249. }
  250. values = wireInbound(&model.Inbound{ShareAddrStrategy: "auto"}, 0)
  251. if got := values.Get("shareAddrStrategy"); got != "node" {
  252. t.Fatalf("invalid shareAddrStrategy = %q, want node", got)
  253. }
  254. }
  255. func TestStripNodeInboundTagPrefix(t *testing.T) {
  256. cases := []struct {
  257. nodeID int
  258. tag string
  259. want string
  260. }{
  261. {2, "n2-in-443-tcp", "in-443-tcp"},
  262. {2, "in-443-tcp", "in-443-tcp"},
  263. {2, "my-custom", "my-custom"},
  264. {2, "n3-in-443-tcp", "n3-in-443-tcp"},
  265. {0, "n2-in-443-tcp", "n2-in-443-tcp"},
  266. }
  267. for _, c := range cases {
  268. if got := stripNodeInboundTagPrefix(c.nodeID, c.tag); got != c.want {
  269. t.Fatalf("stripNodeInboundTagPrefix(%d, %q) = %q, want %q", c.nodeID, c.tag, got, c.want)
  270. }
  271. }
  272. }
  273. func TestWireInboundStripsNodeTagOnPush(t *testing.T) {
  274. values := wireInbound(&model.Inbound{Tag: "n2-in-443-tcp"}, 2)
  275. if got := values.Get("tag"); got != "in-443-tcp" {
  276. t.Fatalf("tag = %q, want in-443-tcp", got)
  277. }
  278. values = wireInbound(&model.Inbound{Tag: "n2-in-443-tcp"}, 0)
  279. if got := values.Get("tag"); got != "n2-in-443-tcp" {
  280. t.Fatalf("nodeID 0 must not strip, got %q", got)
  281. }
  282. }
  283. func TestSanitizeStreamSettingsForRemote(t *testing.T) {
  284. tests := []struct {
  285. name string
  286. input string
  287. // wantCertFile / wantKeyFile: expected presence after sanitize
  288. wantCertFile bool
  289. wantKeyFile bool
  290. }{
  291. {
  292. name: "file paths only — kept intact (remote node paths)",
  293. input: `{
  294. "tlsSettings": {
  295. "certificates": [{
  296. "certificateFile": "/etc/ssl/cert.crt",
  297. "keyFile": "/etc/ssl/key.key"
  298. }]
  299. }
  300. }`,
  301. wantCertFile: true,
  302. wantKeyFile: true,
  303. },
  304. {
  305. name: "inline content only — unchanged",
  306. input: `{
  307. "tlsSettings": {
  308. "certificates": [{
  309. "certificate": ["-----BEGIN CERTIFICATE-----"],
  310. "key": ["-----BEGIN PRIVATE KEY-----"]
  311. }]
  312. }
  313. }`,
  314. wantCertFile: false,
  315. wantKeyFile: false,
  316. },
  317. {
  318. name: "both file paths and inline content — file paths stripped (redundant)",
  319. input: `{
  320. "tlsSettings": {
  321. "certificates": [{
  322. "certificateFile": "/etc/ssl/cert.crt",
  323. "keyFile": "/etc/ssl/key.key",
  324. "certificate": ["-----BEGIN CERTIFICATE-----"],
  325. "key": ["-----BEGIN PRIVATE KEY-----"]
  326. }]
  327. }
  328. }`,
  329. wantCertFile: false,
  330. wantKeyFile: false,
  331. },
  332. {
  333. name: "empty stream settings",
  334. input: "",
  335. // empty input returns empty, nothing to check
  336. },
  337. }
  338. for _, tc := range tests {
  339. t.Run(tc.name, func(t *testing.T) {
  340. if tc.input == "" {
  341. if got := sanitizeStreamSettingsForRemote(tc.input); got != "" {
  342. t.Errorf("expected empty string, got %q", got)
  343. }
  344. return
  345. }
  346. got := sanitizeStreamSettingsForRemote(tc.input)
  347. var out map[string]any
  348. if err := json.Unmarshal([]byte(got), &out); err != nil {
  349. t.Fatalf("output is not valid JSON: %v\noutput: %s", err, got)
  350. }
  351. tls, _ := out["tlsSettings"].(map[string]any)
  352. certs, _ := tls["certificates"].([]any)
  353. if len(certs) == 0 {
  354. t.Fatal("certificates array missing in output")
  355. }
  356. cert, _ := certs[0].(map[string]any)
  357. _, hasCertFile := cert["certificateFile"]
  358. _, hasKeyFile := cert["keyFile"]
  359. if hasCertFile != tc.wantCertFile {
  360. t.Errorf("certificateFile present=%v, want %v", hasCertFile, tc.wantCertFile)
  361. }
  362. if hasKeyFile != tc.wantKeyFile {
  363. t.Errorf("keyFile present=%v, want %v", hasKeyFile, tc.wantKeyFile)
  364. }
  365. })
  366. }
  367. }