miaopanel
1package wafgw
2
3import (
4 "bytes"
5 "compress/gzip"
6 "context"
7 "io"
8 "log/slog"
9 "net/http"
10 "net/http/httptest"
11 "os"
12 "path/filepath"
13 "strings"
14 "sync/atomic"
15 "testing"
16
17 "github.com/miaopanel/miaopanel/internal/config"
18 "github.com/miaopanel/miaopanel/internal/store"
19 "github.com/miaopanel/miaopanel/internal/waf"
20)
21
22type harness struct {
23 gw *Service
24 db *store.Store
25 origin *httptest.Server
26 hits atomic.Int64
27 lastBody atomic.Value
28}
29
30func newHarness(t *testing.T) *harness {
31 t.Helper()
32 dir := t.TempDir()
33 db, err := store.Open(filepath.Join(dir, "panel.db"))
34 if err != nil {
35 t.Fatal(err)
36 }
37 t.Cleanup(func() { db.Close() })
38 ctx := context.Background()
39 pairs := map[string]string{
40 "waf.gateway": "1",
41 "waf.block_status": "403",
42 "waf.gateway_threshold": "8",
43 "waf.rate": "50",
44 "waf.burst": "200",
45 }
46 for k, v := range pairs {
47 if err := db.SetSetting(ctx, k, v); err != nil {
48 t.Fatal(err)
49 }
50 }
51
52 h := &harness{db: db}
53 h.origin = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
54 h.hits.Add(1)
55 body, _ := io.ReadAll(r.Body)
56 h.lastBody.Store(string(body))
57 w.Header().Set("X-Origin", "1")
58 _, _ = w.Write([]byte("origin:" + r.URL.RequestURI() + "|" + string(body)))
59 }))
60 t.Cleanup(h.origin.Close)
61
62 cfg := config.Default()
63 cfg.PanelDir = dir
64 cfg.DataDir = filepath.Join(dir, "data")
65 cfg.WebRoot = filepath.Join(dir, "www")
66 cfg.WAFGatewayAddr = "127.0.0.1:8899"
67 wafSvc := waf.New(db, cfg, nil, nil)
68 logger := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelError}))
69 h.gw = New(cfg, db, wafSvc, logger)
70 if err := h.gw.Reload(ctx); err != nil {
71 t.Fatal(err)
72 }
73 return h
74}
75
76func (h *harness) do(t *testing.T, method, target string, body io.Reader, headers map[string]string) *httptest.ResponseRecorder {
77 t.Helper()
78 req := httptest.NewRequest(method, target, body)
79 req.RemoteAddr = "127.0.0.1:54321"
80 origin := strings.TrimPrefix(h.origin.URL, "http://")
81 req.Header.Set("X-MP-Site", "demo")
82 req.Header.Set("X-MP-Origin", origin)
83 req.Header.Set("X-Real-IP", "203.0.113.7")
84 for k, v := range headers {
85 req.Header.Set(k, v)
86 }
87 rec := httptest.NewRecorder()
88 h.gw.ServeHTTP(rec, req)
89 return rec
90}
91
92func TestGatewayAllowsBenignRequest(t *testing.T) {
93 h := newHarness(t)
94 rec := h.do(t, http.MethodGet, "/hello?name=world", nil, nil)
95 if rec.Code != http.StatusOK {
96 t.Fatalf("status %d body %s", rec.Code, rec.Body.String())
97 }
98 if h.hits.Load() != 1 {
99 t.Fatalf("origin hits = %d", h.hits.Load())
100 }
101 if !strings.Contains(rec.Body.String(), "origin:/hello?name=world") {
102 t.Fatalf("body %q", rec.Body.String())
103 }
104 if rec.Header().Get("X-Origin") != "1" {
105 t.Fatal("upstream header lost")
106 }
107}
108
109func TestGatewayBlocksSQLi(t *testing.T) {
110 h := newHarness(t)
111 rec := h.do(t, http.MethodGet, "/?id=1+UNION+SELECT+1,2,3", nil, nil)
112 if rec.Code != http.StatusForbidden {
113 t.Fatalf("status %d body %s", rec.Code, rec.Body.String())
114 }
115 if h.hits.Load() != 0 {
116 t.Fatal("blocked request reached the origin")
117 }
118 if rec.Header().Get("X-MP-WAF") != "blocked" {
119 t.Fatal("missing WAF marker")
120 }
121 events, err := h.db.WAFEvents(context.Background(), 10, "")
122 if err != nil || len(events) != 1 {
123 t.Fatalf("events %+v err %v", events, err)
124 }
125 if events[0].Module != "sqli" || events[0].Score < 10 {
126 t.Fatalf("event not attributed: %+v", events[0])
127 }
128}
129
130func TestGatewayBlocksXSSInBody(t *testing.T) {
131 h := newHarness(t)
132 body := strings.NewReader(`{"comment":"\u003cscript\u003ealert(1)\u003c/script\u003e"}`)
133 rec := h.do(t, http.MethodPost, "/api/comment", body, map[string]string{
134 "Content-Type": "application/json", "Accept": "application/json",
135 })
136 if rec.Code != http.StatusForbidden {
137 t.Fatalf("status %d body %s", rec.Code, rec.Body.String())
138 }
139 if !strings.Contains(rec.Body.String(), `"code":403`) {
140 t.Fatalf("json block body: %s", rec.Body.String())
141 }
142 if h.hits.Load() != 0 {
143 t.Fatal("blocked body reached the origin")
144 }
145}
146
147func TestGatewayForwardsPostBody(t *testing.T) {
148 h := newHarness(t)
149 body := strings.NewReader("name=hello¬e=%E4%BD%A0%E5%A5%BD")
150 rec := h.do(t, http.MethodPost, "/save", body, map[string]string{
151 "Content-Type": "application/x-www-form-urlencoded",
152 })
153 if rec.Code != http.StatusOK {
154 t.Fatalf("status %d body %s", rec.Code, rec.Body.String())
155 }
156 if got, _ := h.lastBody.Load().(string); got != "name=hello¬e=%E4%BD%A0%E5%A5%BD" {
157 t.Fatalf("body forwarded as %q", got)
158 }
159}
160
161func TestGatewayInspectsGzipBody(t *testing.T) {
162 h := newHarness(t)
163 var buf bytes.Buffer
164 zw := gzip.NewWriter(&buf)
165 _, _ = zw.Write([]byte("q=1+union+select+1,2,3"))
166 _ = zw.Close()
167 rec := h.do(t, http.MethodPost, "/api", bytes.NewReader(buf.Bytes()), map[string]string{
168 "Content-Type": "application/x-www-form-urlencoded",
169 "Content-Encoding": "gzip",
170 })
171 if rec.Code != http.StatusForbidden {
172 t.Fatalf("gzip payload not blocked: %d %s", rec.Code, rec.Body.String())
173 }
174 if h.hits.Load() != 0 {
175 t.Fatal("blocked gzip request reached the origin")
176 }
177}
178
179func TestGatewayBlocksUpload(t *testing.T) {
180 h := newHarness(t)
181 var b strings.Builder
182 b.WriteString("--BOUND\r\n")
183 b.WriteString("Content-Disposition: form-data; name=\"file\"; filename=\"shell.php\"\r\n")
184 b.WriteString("Content-Type: application/octet-stream\r\n\r\n")
185 b.WriteString("<?php echo 1; ?>\r\n--BOUND--\r\n")
186 rec := h.do(t, http.MethodPost, "/upload", strings.NewReader(b.String()), map[string]string{
187 "Content-Type": "multipart/form-data; boundary=BOUND",
188 })
189 if rec.Code != http.StatusForbidden {
190 t.Fatalf("status %d body %s", rec.Code, rec.Body.String())
191 }
192 if h.hits.Load() != 0 {
193 t.Fatal("upload reached the origin")
194 }
195}
196
197func TestGatewayWhitelist(t *testing.T) {
198 h := newHarness(t)
199 _ = h.db.SetSetting(context.Background(), "waf.whitelist", "10.0.0.0/8")
200 if err := h.gw.Reload(context.Background()); err != nil {
201 t.Fatal(err)
202 }
203 rec := h.do(t, http.MethodGet, "/?id=1+UNION+SELECT+1", nil, map[string]string{
204 "X-Real-IP": "10.1.2.3",
205 })
206 if rec.Code != http.StatusOK || h.hits.Load() != 1 {
207 t.Fatalf("whitelisted request blocked: %d %s", rec.Code, rec.Body.String())
208 }
209}
210
211func TestGatewayRateLimit(t *testing.T) {
212 h := newHarness(t)
213 _ = h.db.SetSetting(context.Background(), "waf.rate", "1")
214 _ = h.db.SetSetting(context.Background(), "waf.burst", "1")
215 if err := h.gw.Reload(context.Background()); err != nil {
216 t.Fatal(err)
217 }
218 first := h.do(t, http.MethodGet, "/a", nil, nil)
219 second := h.do(t, http.MethodGet, "/b", nil, nil)
220 if first.Code != http.StatusOK {
221 t.Fatalf("first status %d", first.Code)
222 }
223 if second.Code != http.StatusTooManyRequests {
224 t.Fatalf("second status %d, want 429", second.Code)
225 }
226}
227
228func TestGatewayHealthAndLoopback(t *testing.T) {
229 h := newHarness(t)
230 req := httptest.NewRequest(http.MethodGet, "/__mp_waf/health", nil)
231 req.RemoteAddr = "127.0.0.1:1234"
232 rec := httptest.NewRecorder()
233 h.gw.ServeHTTP(rec, req)
234 if rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), `"ok":true`) {
235 t.Fatalf("health: %d %s", rec.Code, rec.Body.String())
236 }
237
238 req = httptest.NewRequest(http.MethodGet, "/", nil)
239 req.RemoteAddr = "198.51.100.1:1234"
240 rec = httptest.NewRecorder()
241 h.gw.ServeHTTP(rec, req)
242 if rec.Code != http.StatusForbidden {
243 t.Fatalf("public access allowed: %d", rec.Code)
244 }
245}
246
247func TestGatewayCustomRule(t *testing.T) {
248 h := newHarness(t)
249 ctx := context.Background()
250 if err := h.db.CreateWAFRule(ctx, &store.WAFRule{
251 Name: "block admin", MatchOn: "uri", Op: "contains",
252 Pattern: "/secret", Action: "block", Enabled: true,
253 }); err != nil {
254 t.Fatal(err)
255 }
256 if err := h.gw.Reload(ctx); err != nil {
257 t.Fatal(err)
258 }
259 rec := h.do(t, http.MethodGet, "/secret/page", nil, nil)
260 if rec.Code != http.StatusForbidden {
261 t.Fatalf("custom rule not applied: %d", rec.Code)
262 }
263}
264
265func TestTargetForRejectsInvalid(t *testing.T) {
266 req := httptest.NewRequest(http.MethodGet, "/", nil)
267 req.Header.Set("X-MP-Origin", "bad")
268 if _, err := targetFor(req, nil, "s"); err == nil {
269 t.Fatal("invalid origin accepted")
270 }
271 // A forged header must not turn the gateway into an internal proxy.
272 req.Header.Set("X-MP-Origin", "169.254.169.254:80")
273 if _, err := targetFor(req, nil, "s"); err == nil {
274 t.Fatal("non loopback origin accepted")
275 }
276 req.Header.Set("X-MP-Origin", "")
277 req.Header.Set("X-MP-Upstream", "file:///etc/passwd")
278 if _, err := targetFor(req, nil, "s"); err == nil {
279 t.Fatal("invalid upstream accepted")
280 }
281 req.Header.Set("X-MP-Upstream", "http://10.0.0.5:6379")
282 if _, err := targetFor(req, nil, "s"); err == nil {
283 t.Fatal("non loopback upstream accepted")
284 }
285 u, err := targetFor(httptest.NewRequest(http.MethodGet, "/", nil), nil, "s")
286 if err == nil || u != nil {
287 t.Fatal("missing upstream accepted")
288 }
289 req = httptest.NewRequest(http.MethodGet, "/", nil)
290 req.Header.Set("X-MP-Upstream", "http://127.0.0.1:8080")
291 u, err = targetFor(req, nil, "s")
292 if err != nil || u.Host != "127.0.0.1:8080" {
293 t.Fatalf("upstream parse: %v %v", u, err)
294 }
295}
296
297func TestTargetForPrefersRegisteredOrigin(t *testing.T) {
298 // nginx sets X-MP-Origin from the site row, but nothing stops a local
299 // process from setting it too: the registered origin must win.
300 req := httptest.NewRequest(http.MethodGet, "/", nil)
301 req.Header.Set("X-MP-Origin", "127.0.0.1:9999")
302 pol := &Policy{Origins: map[string]string{"app": "127.0.0.1:10001"}}
303 u, err := targetFor(req, pol, "app")
304 if err != nil {
305 t.Fatal(err)
306 }
307 if u.Host != "127.0.0.1:10001" {
308 t.Fatalf("header overrode the registered origin: %s", u.Host)
309 }
310}