package wafgw import ( "bytes" "compress/gzip" "context" "io" "log/slog" "net/http" "net/http/httptest" "os" "path/filepath" "strings" "sync/atomic" "testing" "github.com/miaopanel/miaopanel/internal/config" "github.com/miaopanel/miaopanel/internal/store" "github.com/miaopanel/miaopanel/internal/waf" ) type harness struct { gw *Service db *store.Store origin *httptest.Server hits atomic.Int64 lastBody atomic.Value } func newHarness(t *testing.T) *harness { t.Helper() dir := t.TempDir() db, err := store.Open(filepath.Join(dir, "panel.db")) if err != nil { t.Fatal(err) } t.Cleanup(func() { db.Close() }) ctx := context.Background() pairs := map[string]string{ "waf.gateway": "1", "waf.block_status": "403", "waf.gateway_threshold": "8", "waf.rate": "50", "waf.burst": "200", } for k, v := range pairs { if err := db.SetSetting(ctx, k, v); err != nil { t.Fatal(err) } } h := &harness{db: db} h.origin = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { h.hits.Add(1) body, _ := io.ReadAll(r.Body) h.lastBody.Store(string(body)) w.Header().Set("X-Origin", "1") _, _ = w.Write([]byte("origin:" + r.URL.RequestURI() + "|" + string(body))) })) t.Cleanup(h.origin.Close) cfg := config.Default() cfg.PanelDir = dir cfg.DataDir = filepath.Join(dir, "data") cfg.WebRoot = filepath.Join(dir, "www") cfg.WAFGatewayAddr = "127.0.0.1:8899" wafSvc := waf.New(db, cfg, nil, nil) logger := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelError})) h.gw = New(cfg, db, wafSvc, logger) if err := h.gw.Reload(ctx); err != nil { t.Fatal(err) } return h } func (h *harness) do(t *testing.T, method, target string, body io.Reader, headers map[string]string) *httptest.ResponseRecorder { t.Helper() req := httptest.NewRequest(method, target, body) req.RemoteAddr = "127.0.0.1:54321" origin := strings.TrimPrefix(h.origin.URL, "http://") req.Header.Set("X-MP-Site", "demo") req.Header.Set("X-MP-Origin", origin) req.Header.Set("X-Real-IP", "203.0.113.7") for k, v := range headers { req.Header.Set(k, v) } rec := httptest.NewRecorder() h.gw.ServeHTTP(rec, req) return rec } func TestGatewayAllowsBenignRequest(t *testing.T) { h := newHarness(t) rec := h.do(t, http.MethodGet, "/hello?name=world", nil, nil) if rec.Code != http.StatusOK { t.Fatalf("status %d body %s", rec.Code, rec.Body.String()) } if h.hits.Load() != 1 { t.Fatalf("origin hits = %d", h.hits.Load()) } if !strings.Contains(rec.Body.String(), "origin:/hello?name=world") { t.Fatalf("body %q", rec.Body.String()) } if rec.Header().Get("X-Origin") != "1" { t.Fatal("upstream header lost") } } func TestGatewayBlocksSQLi(t *testing.T) { h := newHarness(t) rec := h.do(t, http.MethodGet, "/?id=1+UNION+SELECT+1,2,3", nil, nil) if rec.Code != http.StatusForbidden { t.Fatalf("status %d body %s", rec.Code, rec.Body.String()) } if h.hits.Load() != 0 { t.Fatal("blocked request reached the origin") } if rec.Header().Get("X-MP-WAF") != "blocked" { t.Fatal("missing WAF marker") } events, err := h.db.WAFEvents(context.Background(), 10, "") if err != nil || len(events) != 1 { t.Fatalf("events %+v err %v", events, err) } if events[0].Module != "sqli" || events[0].Score < 10 { t.Fatalf("event not attributed: %+v", events[0]) } } func TestGatewayBlocksXSSInBody(t *testing.T) { h := newHarness(t) body := strings.NewReader(`{"comment":"\u003cscript\u003ealert(1)\u003c/script\u003e"}`) rec := h.do(t, http.MethodPost, "/api/comment", body, map[string]string{ "Content-Type": "application/json", "Accept": "application/json", }) if rec.Code != http.StatusForbidden { t.Fatalf("status %d body %s", rec.Code, rec.Body.String()) } if !strings.Contains(rec.Body.String(), `"code":403`) { t.Fatalf("json block body: %s", rec.Body.String()) } if h.hits.Load() != 0 { t.Fatal("blocked body reached the origin") } } func TestGatewayForwardsPostBody(t *testing.T) { h := newHarness(t) body := strings.NewReader("name=hello¬e=%E4%BD%A0%E5%A5%BD") rec := h.do(t, http.MethodPost, "/save", body, map[string]string{ "Content-Type": "application/x-www-form-urlencoded", }) if rec.Code != http.StatusOK { t.Fatalf("status %d body %s", rec.Code, rec.Body.String()) } if got, _ := h.lastBody.Load().(string); got != "name=hello¬e=%E4%BD%A0%E5%A5%BD" { t.Fatalf("body forwarded as %q", got) } } func TestGatewayInspectsGzipBody(t *testing.T) { h := newHarness(t) var buf bytes.Buffer zw := gzip.NewWriter(&buf) _, _ = zw.Write([]byte("q=1+union+select+1,2,3")) _ = zw.Close() rec := h.do(t, http.MethodPost, "/api", bytes.NewReader(buf.Bytes()), map[string]string{ "Content-Type": "application/x-www-form-urlencoded", "Content-Encoding": "gzip", }) if rec.Code != http.StatusForbidden { t.Fatalf("gzip payload not blocked: %d %s", rec.Code, rec.Body.String()) } if h.hits.Load() != 0 { t.Fatal("blocked gzip request reached the origin") } } func TestGatewayBlocksUpload(t *testing.T) { h := newHarness(t) var b strings.Builder b.WriteString("--BOUND\r\n") b.WriteString("Content-Disposition: form-data; name=\"file\"; filename=\"shell.php\"\r\n") b.WriteString("Content-Type: application/octet-stream\r\n\r\n") b.WriteString("\r\n--BOUND--\r\n") rec := h.do(t, http.MethodPost, "/upload", strings.NewReader(b.String()), map[string]string{ "Content-Type": "multipart/form-data; boundary=BOUND", }) if rec.Code != http.StatusForbidden { t.Fatalf("status %d body %s", rec.Code, rec.Body.String()) } if h.hits.Load() != 0 { t.Fatal("upload reached the origin") } } func TestGatewayWhitelist(t *testing.T) { h := newHarness(t) _ = h.db.SetSetting(context.Background(), "waf.whitelist", "10.0.0.0/8") if err := h.gw.Reload(context.Background()); err != nil { t.Fatal(err) } rec := h.do(t, http.MethodGet, "/?id=1+UNION+SELECT+1", nil, map[string]string{ "X-Real-IP": "10.1.2.3", }) if rec.Code != http.StatusOK || h.hits.Load() != 1 { t.Fatalf("whitelisted request blocked: %d %s", rec.Code, rec.Body.String()) } } func TestGatewayRateLimit(t *testing.T) { h := newHarness(t) _ = h.db.SetSetting(context.Background(), "waf.rate", "1") _ = h.db.SetSetting(context.Background(), "waf.burst", "1") if err := h.gw.Reload(context.Background()); err != nil { t.Fatal(err) } first := h.do(t, http.MethodGet, "/a", nil, nil) second := h.do(t, http.MethodGet, "/b", nil, nil) if first.Code != http.StatusOK { t.Fatalf("first status %d", first.Code) } if second.Code != http.StatusTooManyRequests { t.Fatalf("second status %d, want 429", second.Code) } } func TestGatewayHealthAndLoopback(t *testing.T) { h := newHarness(t) req := httptest.NewRequest(http.MethodGet, "/__mp_waf/health", nil) req.RemoteAddr = "127.0.0.1:1234" rec := httptest.NewRecorder() h.gw.ServeHTTP(rec, req) if rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), `"ok":true`) { t.Fatalf("health: %d %s", rec.Code, rec.Body.String()) } req = httptest.NewRequest(http.MethodGet, "/", nil) req.RemoteAddr = "198.51.100.1:1234" rec = httptest.NewRecorder() h.gw.ServeHTTP(rec, req) if rec.Code != http.StatusForbidden { t.Fatalf("public access allowed: %d", rec.Code) } } func TestGatewayCustomRule(t *testing.T) { h := newHarness(t) ctx := context.Background() if err := h.db.CreateWAFRule(ctx, &store.WAFRule{ Name: "block admin", MatchOn: "uri", Op: "contains", Pattern: "/secret", Action: "block", Enabled: true, }); err != nil { t.Fatal(err) } if err := h.gw.Reload(ctx); err != nil { t.Fatal(err) } rec := h.do(t, http.MethodGet, "/secret/page", nil, nil) if rec.Code != http.StatusForbidden { t.Fatalf("custom rule not applied: %d", rec.Code) } } func TestTargetForRejectsInvalid(t *testing.T) { req := httptest.NewRequest(http.MethodGet, "/", nil) req.Header.Set("X-MP-Origin", "bad") if _, err := targetFor(req, nil, "s"); err == nil { t.Fatal("invalid origin accepted") } // A forged header must not turn the gateway into an internal proxy. req.Header.Set("X-MP-Origin", "169.254.169.254:80") if _, err := targetFor(req, nil, "s"); err == nil { t.Fatal("non loopback origin accepted") } req.Header.Set("X-MP-Origin", "") req.Header.Set("X-MP-Upstream", "file:///etc/passwd") if _, err := targetFor(req, nil, "s"); err == nil { t.Fatal("invalid upstream accepted") } req.Header.Set("X-MP-Upstream", "http://10.0.0.5:6379") if _, err := targetFor(req, nil, "s"); err == nil { t.Fatal("non loopback upstream accepted") } u, err := targetFor(httptest.NewRequest(http.MethodGet, "/", nil), nil, "s") if err == nil || u != nil { t.Fatal("missing upstream accepted") } req = httptest.NewRequest(http.MethodGet, "/", nil) req.Header.Set("X-MP-Upstream", "http://127.0.0.1:8080") u, err = targetFor(req, nil, "s") if err != nil || u.Host != "127.0.0.1:8080" { t.Fatalf("upstream parse: %v %v", u, err) } } func TestTargetForPrefersRegisteredOrigin(t *testing.T) { // nginx sets X-MP-Origin from the site row, but nothing stops a local // process from setting it too: the registered origin must win. req := httptest.NewRequest(http.MethodGet, "/", nil) req.Header.Set("X-MP-Origin", "127.0.0.1:9999") pol := &Policy{Origins: map[string]string{"app": "127.0.0.1:10001"}} u, err := targetFor(req, pol, "app") if err != nil { t.Fatal(err) } if u.Host != "127.0.0.1:10001" { t.Fatalf("header overrode the registered origin: %s", u.Host) } }