1
0

remote_test.go 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271
  1. package runtime
  2. import (
  3. "context"
  4. "encoding/json"
  5. "net/http"
  6. "net/http/httptest"
  7. "net/url"
  8. "testing"
  9. "github.com/mhsanaei/3x-ui/v3/internal/database/model"
  10. )
  11. type stubEgress struct{ url string }
  12. func (s stubEgress) NodeEgressProxyURL(int) string { return s.url }
  13. // cacheGetTag must resolve a remote inbound id even when the n<id>- prefix
  14. // sits on only one side: the node may store the bare tag while the central
  15. // panel pushes the prefixed form, or vice versa. Without this a mismatch makes
  16. // the push create a duplicate inbound on the node.
  17. func TestCacheGetTag_PrefixAgnostic(t *testing.T) {
  18. cases := []struct {
  19. name string
  20. cacheTag string
  21. lookup string
  22. wantID int
  23. wantFound bool
  24. }{
  25. {"exact", "n1-in-443-tcp", "n1-in-443-tcp", 7, true},
  26. {"node bare, lookup prefixed", "in-443-tcp", "n1-in-443-tcp", 7, true},
  27. {"node prefixed, lookup bare", "n1-in-443-tcp", "in-443-tcp", 7, true},
  28. {"unrelated tag", "in-443-tcp", "in-999-tcp", 0, false},
  29. }
  30. for _, c := range cases {
  31. t.Run(c.name, func(t *testing.T) {
  32. r := NewRemote(&model.Node{Id: 1, Name: "n1"}, nil)
  33. r.cacheSet(c.cacheTag, 7)
  34. id, ok := r.cacheGetTag(c.lookup)
  35. if ok != c.wantFound || id != c.wantID {
  36. t.Fatalf("cacheGetTag(%q) = (%d, %v), want (%d, %v)", c.lookup, id, ok, c.wantID, c.wantFound)
  37. }
  38. })
  39. }
  40. }
  41. func TestWireInboundIncludesShareAddressFields(t *testing.T) {
  42. values := wireInbound(&model.Inbound{
  43. ShareAddrStrategy: "custom",
  44. ShareAddr: "edge.example.com",
  45. })
  46. if got := values.Get("shareAddrStrategy"); got != "custom" {
  47. t.Fatalf("shareAddrStrategy = %q, want custom", got)
  48. }
  49. if got := values.Get("shareAddr"); got != "edge.example.com" {
  50. t.Fatalf("shareAddr = %q, want edge.example.com", got)
  51. }
  52. }
  53. func TestRemoteHTTPClientEgressProxy(t *testing.T) {
  54. // OutboundTag + a resolver → a dedicated proxy client (not the shared default).
  55. withTag := NewRemote(&model.Node{Id: 1, Scheme: "https", TlsVerifyMode: "verify", OutboundTag: "warp"}, stubEgress{url: "socks5://127.0.0.1:1080"})
  56. c, err := withTag.httpClient()
  57. if err != nil {
  58. t.Fatalf("httpClient: %v", err)
  59. }
  60. if c == defaultNodeHTTPClient {
  61. t.Fatal("OutboundTag + resolver must produce a dedicated egress client, not the shared default")
  62. }
  63. // No OutboundTag → no egress proxy → shared default client (verify mode).
  64. noTag := NewRemote(&model.Node{Id: 2, Scheme: "https", TlsVerifyMode: "verify"}, stubEgress{url: "socks5://127.0.0.1:1080"})
  65. c2, err := noTag.httpClient()
  66. if err != nil {
  67. t.Fatalf("httpClient: %v", err)
  68. }
  69. if c2 != defaultNodeHTTPClient {
  70. t.Fatal("no OutboundTag must use the shared default client")
  71. }
  72. }
  73. func TestRemoteDoSetsContentType(t *testing.T) {
  74. var gotCT string
  75. srv := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  76. gotCT = r.Header.Get("Content-Type")
  77. w.Header().Set("Content-Type", "application/json")
  78. _, _ = w.Write([]byte(`{"success":true}`))
  79. }))
  80. defer srv.Close()
  81. r := NewRemote(nodeForServer(t, srv, "skip", ""), nil)
  82. if _, err := r.do(context.Background(), http.MethodPost, "x", url.Values{"a": {"b"}}); err != nil {
  83. t.Fatalf("do: %v", err)
  84. }
  85. if gotCT != "application/x-www-form-urlencoded" {
  86. t.Fatalf("Content-Type = %q, want application/x-www-form-urlencoded", gotCT)
  87. }
  88. }
  89. func TestRemoteBaseURL(t *testing.T) {
  90. cases := []struct {
  91. name string
  92. scheme string
  93. port int
  94. bp string
  95. want string
  96. wantErr bool
  97. }{
  98. {"https default path", "https", 443, "", "https://example.com:443/", false},
  99. {"http custom path gets trailing slash", "http", 8080, "/panel", "http://example.com:8080/panel/", false},
  100. {"empty scheme defaults to https", "", 2096, "/", "https://example.com:2096/", false},
  101. {"invalid scheme defaults to https", "ftp", 2096, "/", "https://example.com:2096/", false},
  102. {"port zero rejected", "https", 0, "/", "", true},
  103. {"port above range rejected", "https", 65536, "/", "", true},
  104. {"negative port rejected", "https", -1, "/", "", true},
  105. {"max port accepted", "https", 65535, "/", "https://example.com:65535/", false},
  106. }
  107. for _, c := range cases {
  108. t.Run(c.name, func(t *testing.T) {
  109. r := NewRemote(&model.Node{Address: "example.com", Scheme: c.scheme, Port: c.port, BasePath: c.bp}, nil)
  110. got, err := r.baseURL()
  111. if c.wantErr {
  112. if err == nil {
  113. t.Fatalf("expected error for scheme=%q port=%d", c.scheme, c.port)
  114. }
  115. return
  116. }
  117. if err != nil {
  118. t.Fatalf("unexpected error: %v", err)
  119. }
  120. if got != c.want {
  121. t.Fatalf("baseURL = %q, want %q", got, c.want)
  122. }
  123. })
  124. }
  125. }
  126. func TestIsNonEmptySlice(t *testing.T) {
  127. cases := []struct {
  128. name string
  129. in any
  130. want bool
  131. }{
  132. {"non-empty slice", []any{1}, true},
  133. {"empty slice", []any{}, false},
  134. {"nil slice", []any(nil), false},
  135. {"not a slice", "x", false},
  136. }
  137. for _, c := range cases {
  138. t.Run(c.name, func(t *testing.T) {
  139. if got := isNonEmptySlice(c.in); got != c.want {
  140. t.Fatalf("isNonEmptySlice(%#v) = %v, want %v", c.in, got, c.want)
  141. }
  142. })
  143. }
  144. }
  145. func TestWireInboundTrafficReset(t *testing.T) {
  146. with := wireInbound(&model.Inbound{TrafficReset: "daily"})
  147. if got := with.Get("trafficReset"); got != "daily" {
  148. t.Fatalf("trafficReset = %q, want daily", got)
  149. }
  150. // Empty TrafficReset must be omitted entirely, not sent as an empty field.
  151. without := wireInbound(&model.Inbound{})
  152. if without.Has("trafficReset") {
  153. t.Fatalf("trafficReset must be omitted when empty, got %q", without.Get("trafficReset"))
  154. }
  155. }
  156. func TestWireInboundDefaultsShareAddressStrategy(t *testing.T) {
  157. values := wireInbound(&model.Inbound{})
  158. if got := values.Get("shareAddrStrategy"); got != "node" {
  159. t.Fatalf("shareAddrStrategy = %q, want node", got)
  160. }
  161. values = wireInbound(&model.Inbound{ShareAddrStrategy: "auto"})
  162. if got := values.Get("shareAddrStrategy"); got != "node" {
  163. t.Fatalf("invalid shareAddrStrategy = %q, want node", got)
  164. }
  165. }
  166. func TestSanitizeStreamSettingsForRemote(t *testing.T) {
  167. tests := []struct {
  168. name string
  169. input string
  170. // wantCertFile / wantKeyFile: expected presence after sanitize
  171. wantCertFile bool
  172. wantKeyFile bool
  173. }{
  174. {
  175. name: "file paths only — kept intact (remote node paths)",
  176. input: `{
  177. "tlsSettings": {
  178. "certificates": [{
  179. "certificateFile": "/etc/ssl/cert.crt",
  180. "keyFile": "/etc/ssl/key.key"
  181. }]
  182. }
  183. }`,
  184. wantCertFile: true,
  185. wantKeyFile: true,
  186. },
  187. {
  188. name: "inline content only — unchanged",
  189. input: `{
  190. "tlsSettings": {
  191. "certificates": [{
  192. "certificate": ["-----BEGIN CERTIFICATE-----"],
  193. "key": ["-----BEGIN PRIVATE KEY-----"]
  194. }]
  195. }
  196. }`,
  197. wantCertFile: false,
  198. wantKeyFile: false,
  199. },
  200. {
  201. name: "both file paths and inline content — file paths stripped (redundant)",
  202. input: `{
  203. "tlsSettings": {
  204. "certificates": [{
  205. "certificateFile": "/etc/ssl/cert.crt",
  206. "keyFile": "/etc/ssl/key.key",
  207. "certificate": ["-----BEGIN CERTIFICATE-----"],
  208. "key": ["-----BEGIN PRIVATE KEY-----"]
  209. }]
  210. }
  211. }`,
  212. wantCertFile: false,
  213. wantKeyFile: false,
  214. },
  215. {
  216. name: "empty stream settings",
  217. input: "",
  218. // empty input returns empty, nothing to check
  219. },
  220. }
  221. for _, tc := range tests {
  222. t.Run(tc.name, func(t *testing.T) {
  223. if tc.input == "" {
  224. if got := sanitizeStreamSettingsForRemote(tc.input); got != "" {
  225. t.Errorf("expected empty string, got %q", got)
  226. }
  227. return
  228. }
  229. got := sanitizeStreamSettingsForRemote(tc.input)
  230. var out map[string]any
  231. if err := json.Unmarshal([]byte(got), &out); err != nil {
  232. t.Fatalf("output is not valid JSON: %v\noutput: %s", err, got)
  233. }
  234. tls, _ := out["tlsSettings"].(map[string]any)
  235. certs, _ := tls["certificates"].([]any)
  236. if len(certs) == 0 {
  237. t.Fatal("certificates array missing in output")
  238. }
  239. cert, _ := certs[0].(map[string]any)
  240. _, hasCertFile := cert["certificateFile"]
  241. _, hasKeyFile := cert["keyFile"]
  242. if hasCertFile != tc.wantCertFile {
  243. t.Errorf("certificateFile present=%v, want %v", hasCertFile, tc.wantCertFile)
  244. }
  245. if hasKeyFile != tc.wantKeyFile {
  246. t.Errorf("keyFile present=%v, want %v", hasKeyFile, tc.wantKeyFile)
  247. }
  248. })
  249. }
  250. }