remote_test.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400
  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: "monthly", TrafficResetDay: 15}, 0)
  236. if got := with.Get("trafficReset"); got != "monthly" {
  237. t.Fatalf("trafficReset = %q, want monthly", got)
  238. }
  239. if got := with.Get("trafficResetDay"); got != "15" {
  240. t.Fatalf("trafficResetDay = %q, want 15", got)
  241. }
  242. // Empty TrafficReset must be omitted entirely, not sent as an empty field.
  243. without := wireInbound(&model.Inbound{}, 0)
  244. if without.Has("trafficReset") {
  245. t.Fatalf("trafficReset must be omitted when empty, got %q", without.Get("trafficReset"))
  246. }
  247. }
  248. func TestWireInboundDefaultsShareAddressStrategy(t *testing.T) {
  249. values := wireInbound(&model.Inbound{}, 0)
  250. if got := values.Get("shareAddrStrategy"); got != "node" {
  251. t.Fatalf("shareAddrStrategy = %q, want node", got)
  252. }
  253. values = wireInbound(&model.Inbound{ShareAddrStrategy: "auto"}, 0)
  254. if got := values.Get("shareAddrStrategy"); got != "node" {
  255. t.Fatalf("invalid shareAddrStrategy = %q, want node", got)
  256. }
  257. }
  258. func TestStripNodeInboundTagPrefix(t *testing.T) {
  259. cases := []struct {
  260. nodeID int
  261. tag string
  262. want string
  263. }{
  264. {2, "n2-in-443-tcp", "in-443-tcp"},
  265. {2, "in-443-tcp", "in-443-tcp"},
  266. {2, "my-custom", "my-custom"},
  267. {2, "n3-in-443-tcp", "n3-in-443-tcp"},
  268. {0, "n2-in-443-tcp", "n2-in-443-tcp"},
  269. }
  270. for _, c := range cases {
  271. if got := stripNodeInboundTagPrefix(c.nodeID, c.tag); got != c.want {
  272. t.Fatalf("stripNodeInboundTagPrefix(%d, %q) = %q, want %q", c.nodeID, c.tag, got, c.want)
  273. }
  274. }
  275. }
  276. func TestWireInboundStripsNodeTagOnPush(t *testing.T) {
  277. values := wireInbound(&model.Inbound{Tag: "n2-in-443-tcp"}, 2)
  278. if got := values.Get("tag"); got != "in-443-tcp" {
  279. t.Fatalf("tag = %q, want in-443-tcp", got)
  280. }
  281. values = wireInbound(&model.Inbound{Tag: "n2-in-443-tcp"}, 0)
  282. if got := values.Get("tag"); got != "n2-in-443-tcp" {
  283. t.Fatalf("nodeID 0 must not strip, got %q", got)
  284. }
  285. }
  286. func TestSanitizeStreamSettingsForRemote(t *testing.T) {
  287. tests := []struct {
  288. name string
  289. input string
  290. // wantCertFile / wantKeyFile: expected presence after sanitize
  291. wantCertFile bool
  292. wantKeyFile bool
  293. }{
  294. {
  295. name: "file paths only — kept intact (remote node paths)",
  296. input: `{
  297. "tlsSettings": {
  298. "certificates": [{
  299. "certificateFile": "/etc/ssl/cert.crt",
  300. "keyFile": "/etc/ssl/key.key"
  301. }]
  302. }
  303. }`,
  304. wantCertFile: true,
  305. wantKeyFile: true,
  306. },
  307. {
  308. name: "inline content only — unchanged",
  309. input: `{
  310. "tlsSettings": {
  311. "certificates": [{
  312. "certificate": ["-----BEGIN CERTIFICATE-----"],
  313. "key": ["-----BEGIN PRIVATE KEY-----"]
  314. }]
  315. }
  316. }`,
  317. wantCertFile: false,
  318. wantKeyFile: false,
  319. },
  320. {
  321. name: "both file paths and inline content — file paths stripped (redundant)",
  322. input: `{
  323. "tlsSettings": {
  324. "certificates": [{
  325. "certificateFile": "/etc/ssl/cert.crt",
  326. "keyFile": "/etc/ssl/key.key",
  327. "certificate": ["-----BEGIN CERTIFICATE-----"],
  328. "key": ["-----BEGIN PRIVATE KEY-----"]
  329. }]
  330. }
  331. }`,
  332. wantCertFile: false,
  333. wantKeyFile: false,
  334. },
  335. {
  336. name: "empty stream settings",
  337. input: "",
  338. // empty input returns empty, nothing to check
  339. },
  340. }
  341. for _, tc := range tests {
  342. t.Run(tc.name, func(t *testing.T) {
  343. if tc.input == "" {
  344. if got := sanitizeStreamSettingsForRemote(tc.input); got != "" {
  345. t.Errorf("expected empty string, got %q", got)
  346. }
  347. return
  348. }
  349. got := sanitizeStreamSettingsForRemote(tc.input)
  350. var out map[string]any
  351. if err := json.Unmarshal([]byte(got), &out); err != nil {
  352. t.Fatalf("output is not valid JSON: %v\noutput: %s", err, got)
  353. }
  354. tls, _ := out["tlsSettings"].(map[string]any)
  355. certs, _ := tls["certificates"].([]any)
  356. if len(certs) == 0 {
  357. t.Fatal("certificates array missing in output")
  358. }
  359. cert, _ := certs[0].(map[string]any)
  360. _, hasCertFile := cert["certificateFile"]
  361. _, hasKeyFile := cert["keyFile"]
  362. if hasCertFile != tc.wantCertFile {
  363. t.Errorf("certificateFile present=%v, want %v", hasCertFile, tc.wantCertFile)
  364. }
  365. if hasKeyFile != tc.wantKeyFile {
  366. t.Errorf("keyFile present=%v, want %v", hasKeyFile, tc.wantKeyFile)
  367. }
  368. })
  369. }
  370. }