package waf import ( "context" "fmt" "log/slog" "os" "path/filepath" "testing" "time" "github.com/miaopanel/miaopanel/internal/config" "github.com/miaopanel/miaopanel/internal/store" ) func TestCollectorFeedsMetricsAndLive(t *testing.T) { dir := t.TempDir() db, err := store.Open(filepath.Join(dir, "panel.db")) if err != nil { t.Fatal(err) } defer db.Close() ctx := context.Background() if err := db.CreateSite(ctx, &store.Site{ Name: "demo", Slug: "demo", Kind: "static", Root: filepath.Join(dir, "www"), Port: 80, Status: "running", RunUser: "www", Domains: []string{"demo.test"}, }); err != nil { t.Fatal(err) } cfg := config.Default() cfg.LogDir = filepath.Join(dir, "logs") logDir := filepath.Join(cfg.LogDir, "demo") if err := os.MkdirAll(logDir, 0o755); err != nil { t.Fatal(err) } now := time.Now() lines := "" for i := 0; i < 5; i++ { lines += fmt.Sprintf("127.0.0.1 - - [%s] \"GET /p%d HTTP/1.1\" 200 120 \"-\" \"curl/8\" \"0.010\"\n", now.Format(logTimeLayout), i) } lines += fmt.Sprintf("127.0.0.1 - - [%s] \"GET / HTTP/1.1\" 444 0 \"-\" \"sqlmap/1.5\" \"0.002\"\n", now.Format(logTimeLayout)) lines += fmt.Sprintf("127.0.0.1 - - [%s] \"GET /api HTTP/1.1\" 429 197 \"-\" \"Mozilla/5.0\" \"0.001\"\n", now.Format(logTimeLayout)) if err := os.WriteFile(filepath.Join(logDir, "access.log"), []byte(lines), 0o644); err != nil { t.Fatal(err) } logger := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelError})) c := NewCollector(db, cfg, logger) c.collect(ctx) qps, traffic, rt := c.Live() if qps <= 0 { t.Fatalf("live qps = %v, want > 0", qps) } if traffic <= 0 { t.Fatalf("live traffic = %v, want > 0", traffic) } if rt <= 0 { t.Fatalf("live rt = %v, want > 0", rt) } totals, err := db.WAFTotals(ctx, now.Add(-time.Hour).Unix(), now.Add(time.Hour).Unix()) if err != nil { t.Fatal(err) } if totals.Requests != 7 || totals.Blocked != 1 || totals.Throttled != 1 { t.Fatalf("totals = %+v, want 7 requests / 1 blocked / 1 throttled", totals) } events, err := db.WAFEvents(ctx, 10, "") if err != nil { t.Fatal(err) } if len(events) != 2 { t.Fatalf("events = %+v", events) } series := c.LiveSeries(6) last := series["requests"][len(series["requests"])-1] if last.Value <= 0 { t.Fatalf("live series tail = %+v", last) } // A second collect must not double count: the offset advanced past EOF. c.collect(ctx) totals, _ = db.WAFTotals(ctx, now.Add(-time.Hour).Unix(), now.Add(time.Hour).Unix()) if totals.Requests != 7 { t.Fatalf("double counted: %+v", totals) } }