仰望星辰工作室

miaopanel

miaopanel/ internal/waf/collect_test.go 2.5 KB · 94 行 原始文件
1package waf
2
3import (
4 "context"
5 "fmt"
6 "log/slog"
7 "os"
8 "path/filepath"
9 "testing"
10 "time"
11
12 "github.com/miaopanel/miaopanel/internal/config"
13 "github.com/miaopanel/miaopanel/internal/store"
14)
15
16func TestCollectorFeedsMetricsAndLive(t *testing.T) {
17 dir := t.TempDir()
18 db, err := store.Open(filepath.Join(dir, "panel.db"))
19 if err != nil {
20 t.Fatal(err)
21 }
22 defer db.Close()
23 ctx := context.Background()
24 if err := db.CreateSite(ctx, &store.Site{
25 Name: "demo", Slug: "demo", Kind: "static", Root: filepath.Join(dir, "www"),
26 Port: 80, Status: "running", RunUser: "www", Domains: []string{"demo.test"},
27 }); err != nil {
28 t.Fatal(err)
29 }
30
31 cfg := config.Default()
32 cfg.LogDir = filepath.Join(dir, "logs")
33 logDir := filepath.Join(cfg.LogDir, "demo")
34 if err := os.MkdirAll(logDir, 0o755); err != nil {
35 t.Fatal(err)
36 }
37 now := time.Now()
38 lines := ""
39 for i := 0; i < 5; i++ {
40 lines += fmt.Sprintf("127.0.0.1 - - [%s] \"GET /p%d HTTP/1.1\" 200 120 \"-\" \"curl/8\" \"0.010\"\n",
41 now.Format(logTimeLayout), i)
42 }
43 lines += fmt.Sprintf("127.0.0.1 - - [%s] \"GET / HTTP/1.1\" 444 0 \"-\" \"sqlmap/1.5\" \"0.002\"\n",
44 now.Format(logTimeLayout))
45 lines += fmt.Sprintf("127.0.0.1 - - [%s] \"GET /api HTTP/1.1\" 429 197 \"-\" \"Mozilla/5.0\" \"0.001\"\n",
46 now.Format(logTimeLayout))
47 if err := os.WriteFile(filepath.Join(logDir, "access.log"), []byte(lines), 0o644); err != nil {
48 t.Fatal(err)
49 }
50
51 logger := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelError}))
52 c := NewCollector(db, cfg, logger)
53 c.collect(ctx)
54
55 qps, traffic, rt := c.Live()
56 if qps <= 0 {
57 t.Fatalf("live qps = %v, want > 0", qps)
58 }
59 if traffic <= 0 {
60 t.Fatalf("live traffic = %v, want > 0", traffic)
61 }
62 if rt <= 0 {
63 t.Fatalf("live rt = %v, want > 0", rt)
64 }
65
66 totals, err := db.WAFTotals(ctx, now.Add(-time.Hour).Unix(), now.Add(time.Hour).Unix())
67 if err != nil {
68 t.Fatal(err)
69 }
70 if totals.Requests != 7 || totals.Blocked != 1 || totals.Throttled != 1 {
71 t.Fatalf("totals = %+v, want 7 requests / 1 blocked / 1 throttled", totals)
72 }
73
74 events, err := db.WAFEvents(ctx, 10, "")
75 if err != nil {
76 t.Fatal(err)
77 }
78 if len(events) != 2 {
79 t.Fatalf("events = %+v", events)
80 }
81
82 series := c.LiveSeries(6)
83 last := series["requests"][len(series["requests"])-1]
84 if last.Value <= 0 {
85 t.Fatalf("live series tail = %+v", last)
86 }
87
88 // A second collect must not double count: the offset advanced past EOF.
89 c.collect(ctx)
90 totals, _ = db.WAFTotals(ctx, now.Add(-time.Hour).Unix(), now.Add(time.Hour).Unix())
91 if totals.Requests != 7 {
92 t.Fatalf("double counted: %+v", totals)
93 }
94}