edge: count not-founds and refuse catalogue paths during a probe-burst cool-down
Wires Task 2's limiter into serving (probe-burst plan Task 3). - Counting: the observer defer counts a not-found (a 404, or a hard or probe match whatever the status; an admin-page match only as a 404) per app and client, never for a request carrying Sec-Fetch-Mode. The home skips requests that arrived as a far edge's asset fill (a verified hop carrying X-Carlos-Asset-Fill); the far edge counts every request it guarded except one an ordinary hop delivered to the home. - Refusing: a catalogue request from a cooling client is offered the burst rule before the hard/probe verdict, in ServeHTTP and at the static handler's probe point (an existing static file is never refused). 429 with Retry-After, X-Carlos-Ref and the PB-C01 draft body. Fleet apps are only recorded. - One precedence rule (decideVerdict): a verdict that does not block gives way to a later block; a block is never replaced. - guardState.recordOnly (false until Task 5) makes nothing block. - edgeguard.BurstRule (found by RuleByID/RuleByHash, never by Check); reqrec Match cool-down fields, KindTrip and Recorder.Trip (10/app/min). - sendBurstNotices is a no-op stub for Task 4.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
14 files changed,
+1,199
−26
internal/edge/answered.go+5 −0internal/edge/asset_e2e_test.go+1 −0internal/edge/assetcatch.go+22 −1internal/edge/burst_edge_test.go+728 −0internal/edge/burst_refusal.go+31 −0internal/edge/edge.go+25 −3internal/edge/guard.go+173 −13internal/edge/reqrecords.go+7 −4internal/edge/reqrecords_test.go+1 −0internal/edge/static.go+24 −5internal/edgeguard/catalogue.go+17 −0internal/edgeguard/catalogue_test.go+31 −0internal/reqrec/recorder.go+64 −0internal/reqrec/recorder_test.go+70 −0
diff --git a/internal/edge/answered.go b/internal/edge/answered.go| index bba7ec852..c60c3876b 100644 |
| --- a/internal/edge/answered.go |
| +++ b/internal/edge/answered.go |
| @@ -48,6 +48,11 @@ type outcome struct { |
| // guard is off for it: a door caller, a request a tunnel delivered (the |
| // hub checked it), or CARLOS_EDGE_PROTECT=off. |
| guard *guardState |
| + // assetFill is set on a verified hop that arrived as a far edge's asset |
| + // fill (assetcatch.go). The fill rebuilt the visitor's headers, so the |
| + // far edge, which saw them, counts the request toward the probe-burst |
| + // limit, and this box does not. |
| + assetFill bool |
| } |
| // causeClientGone is the cause noted when a proxy fails because the CLIENT |
diff --git a/internal/edge/asset_e2e_test.go b/internal/edge/asset_e2e_test.go| index c6fc187ef..9174762e5 100644 |
| --- a/internal/edge/asset_e2e_test.go |
| +++ b/internal/edge/asset_e2e_test.go |
| @@ -1424,6 +1424,7 @@ type lockedRecorder struct { |
| mu sync.Mutex |
| resp []reqrec.Response |
| match []reqrec.Match |
| + trips []reqrec.Trip |
| } |
| func (l *lockedRecorder) Response(x reqrec.Response) { |
diff --git a/internal/edge/assetcatch.go b/internal/edge/assetcatch.go| index efd237e71..09fe39c60 100644 |
| --- a/internal/edge/assetcatch.go |
| +++ b/internal/edge/assetcatch.go |
| @@ -1070,6 +1070,11 @@ func (e *Edge) serveAssetFar(w http.ResponseWriter, r *http.Request, host string |
| // to judge and record. Set from the transport (httptrace), which may run |
| // on another goroutine. |
| var reached atomic.Bool |
| + // hopped is set once an ordinary hop for this request (a forward, not a |
| + // fill) has written its headers to the home. That hop carries the |
| + // visitor's own headers, so the home counts the request toward the |
| + // probe-burst limit, and this edge does not. |
| + var hopped atomic.Bool |
| defer func() { |
| if billed || (acked && !reforwarded) { |
| if m := e.usageMeter.Load(); m != nil { |
| @@ -1091,6 +1096,14 @@ func (e *Edge) serveAssetFar(w http.ResponseWriter, r *http.Request, host string |
| } |
| e.observeGuardCount(rt, out) |
| } |
| + // The probe-burst count has its own owner rule: this edge counts |
| + // every request it guarded, filled or not, since a fill rebuilt the |
| + // headers the home would judge (the home skips fills), except one an |
| + // ordinary hop delivered to the home, which the home counts. Each |
| + // visitor response counts once. Counting never refuses here. |
| + if out != nil && out.guard != nil && !hopped.Load() { |
| + e.noteBurst(rt, r, cw.status, out) |
| + } |
| }() |
| // The hard and probe checks, as ServeHTTP runs them for a request this |
| // box is the first to see, before anything is answered from the store or |
| @@ -1113,7 +1126,15 @@ func (e *Edge) serveAssetFar(w http.ResponseWriter, r *http.Request, host string |
| // From here on a forward writes through cw, so a refusal it writes |
| // itself is recorded with its status; it bills nothing (billed is not |
| // set on a forward). |
| - forward = func() { e.farForward(cw, r, host, eip, box) } |
| + forward = func() { |
| + fr := r |
| + if out != nil && out.guard != nil { |
| + fr = r.WithContext(httptrace.WithClientTrace(r.Context(), &httptrace.ClientTrace{ |
| + WroteHeaders: func() { hopped.Store(true) }, |
| + })) |
| + } |
| + e.farForward(cw, fr, host, eip, box) |
| + } |
| var judged, admitted bool |
| throttle := func() bool { |
| if !judged { |
diff --git a/internal/edge/burst_edge_test.go b/internal/edge/burst_edge_test.go| new file mode 100644 |
| index 000000000..69fcf4468 |
| --- /dev/null |
| +++ b/internal/edge/burst_edge_test.go |
| @@ -0,0 +1,728 @@ |
| +package edge |
| + |
| +import ( |
| + "context" |
| + "fmt" |
| + "io" |
| + "maps" |
| + "net/http" |
| + "net/http/httptest" |
| + "net/netip" |
| + "path/filepath" |
| + "strconv" |
| + "strings" |
| + "sync/atomic" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/applog" |
| + "github.com/carlosframework/platform/internal/edgeguard" |
| + "github.com/carlosframework/platform/internal/registry" |
| + "github.com/carlosframework/platform/internal/release" |
| + "github.com/carlosframework/platform/internal/reqrec" |
| + "github.com/carlosframework/platform/internal/usage" |
| +) |
| + |
| +// Counting and refusing on the edge (probe-burst plan Task 3), through real |
| +// edges serving the embedded catalogue. The limiter runs on a hand-driven |
| +// clock, so the window and the cool-down are exact; everything else is the |
| +// production path. |
| + |
| +const ( |
| + burstHost = "shop.example.com" // bdk/shop |
| + burstOther = "blog.example.com" // bab/blog |
| +) |
| + |
| +// httptest.NewRequest comes from 192.0.2.1, so that is the scanner here. |
| +var burstScanner = netip.MustParsePrefix("192.0.2.1/32") |
| + |
| +// burstRig is a real Edge built by New, so CARLOS_EDGE_PROTECT is read as on |
| +// a box, with a mesh key (codes are sealed), a usage meter and a recorder. |
| +type burstRig struct { |
| + e *Edge |
| + rec *memRecorder |
| + meter *UsageMeter |
| + key []byte |
| + clock *burstClock |
| + upstream *atomic.Int32 |
| +} |
| + |
| +// burstArm gives e a mesh key and the hand-driven limiter clock, and wires |
| +// a meter and a recorder. |
| +func burstArm(t *testing.T, e *Edge) *burstRig { |
| + t.Helper() |
| + s := meshTestStore(t) |
| + if err := mintMeshKey(context.Background(), s); err != nil { |
| + t.Fatal(err) |
| + } |
| + m := newHomeMap(s, "annie") |
| + refreshHomeMap(t, m) |
| + e.homes.Store(m) |
| + g := &burstRig{e: e, rec: &memRecorder{}, meter: NewUsageMeter(), clock: newBurstClock(), upstream: new(atomic.Int32)} |
| + g.key, _ = m.meshKeys() |
| + e.burst = newBurstLimiter(g.clock.now) |
| + e.EnableUsage(g.meter) |
| + e.EnableRequestRecords(g.rec) |
| + return g |
| +} |
| + |
| +// newBurstRig serves two apps from one backend: burstHost (bdk/shop) and |
| +// burstOther (bab/blog). The backend answers 200 for each "host/path" in |
| +// pages and 404 for everything else. |
| +func newBurstRig(t *testing.T, protect string, pages ...string) *burstRig { |
| + t.Helper() |
| + t.Setenv("CARLOS_EDGE_PROTECT", protect) |
| + have := map[string]bool{} |
| + for _, p := range pages { |
| + have[p] = true |
| + } |
| + upstream := new(atomic.Int32) |
| + backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + upstream.Add(1) |
| + if have[r.Host+r.URL.Path] { |
| + io.WriteString(w, "page "+r.URL.Path) |
| + return |
| + } |
| + w.WriteHeader(http.StatusNotFound) |
| + io.WriteString(w, "the app's own 404") |
| + })) |
| + t.Cleanup(backend.Close) |
| + reg := openReg(t) |
| + for _, rt := range []registry.Route{ |
| + {Host: burstHost, Kind: "instance", Addr: backend.Listener.Addr().String(), Status: "ready", Account: "bdk", App: "shop"}, |
| + {Host: burstOther, Kind: "instance", Addr: backend.Listener.Addr().String(), Status: "ready", Account: "bab", App: "blog"}, |
| + } { |
| + if err := reg.Upsert(rt); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + e, err := New(reg, &fakeActivator{}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Cleanup(e.probers.Stop) |
| + g := burstArm(t, e) |
| + g.upstream = upstream |
| + return g |
| +} |
| + |
| +// newBurstStaticRig is one static site on burstHost holding files. |
| +func newBurstStaticRig(t *testing.T, protect string, files map[string]string) *burstRig { |
| + t.Helper() |
| + t.Setenv("CARLOS_EDGE_PROTECT", protect) |
| + store := release.NewDirStore(filepath.Join(t.TempDir(), "store")) |
| + priv, pub := testKeys(t) |
| + shipSite(t, store, "shop", "v1", files) |
| + if err := release.Promote(context.Background(), store, priv, release.OpsAccount, "shop", "canary/x", "v1"); err != nil { |
| + t.Fatalf("Promote: %v", err) |
| + } |
| + reg := openReg(t) |
| + if err := reg.Upsert(registry.Route{Host: burstHost, Kind: "static", App: "shop", Channel: "canary/x", Status: "ready"}); err != nil { |
| + t.Fatal(err) |
| + } |
| + e, err := New(reg, nil) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Cleanup(e.probers.Stop) |
| + e.EnableStatic(store, pub, filepath.Join(t.TempDir(), "cache")) |
| + if err := e.Reload(); err != nil { |
| + t.Fatal(err) |
| + } |
| + return burstArm(t, e) |
| +} |
| + |
| +func (g *burstRig) get(host, path string, hdr ...string) *httptest.ResponseRecorder { |
| + r := httptest.NewRequest("GET", "http://"+host+path, nil) |
| + for i := 0; i+1 < len(hdr); i += 2 { |
| + r.Header.Set(hdr[i], hdr[i+1]) |
| + } |
| + w := httptest.NewRecorder() |
| + g.e.ServeHTTP(w, r) |
| + return w |
| +} |
| + |
| +// scanPath is the i'th missing catalogue path a scanner asks for. |
| +func scanPath(i int) string { return fmt.Sprintf("/wp-admin/setup-%d.php", i) } |
| + |
| +// scan asks host for n missing catalogue paths, as a scanner does. |
| +func (g *burstRig) scan(host string, n int, hdr ...string) { |
| + for i := 0; i < n; i++ { |
| + g.get(host, scanPath(i), hdr...) |
| + } |
| +} |
| + |
| +// trip scans host until the scanner trips, checks the trip's record, and |
| +// returns when its cool-down ends. |
| +func (g *burstRig) trip(t *testing.T, host string) time.Time { |
| + t.Helper() |
| + before := len(g.rec.trips) |
| + g.scan(host, burstThreshold-1) |
| + if _, _, ok := g.e.burst.cooling(burstScanner); ok || len(g.rec.trips) != before { |
| + t.Fatalf("tripped after %d not-founds, want %d", burstThreshold-1, burstThreshold) |
| + } |
| + g.scan(host, 1) |
| + until, _, ok := g.e.burst.cooling(burstScanner) |
| + if !ok || len(g.rec.trips) != before+1 { |
| + t.Fatalf("not tripped after %d not-founds (cooling %v, trips %d)", burstThreshold, ok, len(g.rec.trips)-before) |
| + } |
| + if want := g.clock.now().Add(burstCooldown); !until.Equal(want) { |
| + t.Fatalf("cool-down ends %v, want %v", until, want) |
| + } |
| + return until |
| +} |
| + |
| +// lastMatch is the last Match filed, which must be for path. |
| +func (g *burstRig) lastMatch(t *testing.T, path string) reqrec.Match { |
| + t.Helper() |
| + if len(g.rec.match) == 0 { |
| + t.Fatalf("no match filed for %s", path) |
| + } |
| + m := g.rec.match[len(g.rec.match)-1] |
| + if m.Path != path { |
| + t.Fatalf("last match is for %s, want %s", m.Path, path) |
| + } |
| + return m |
| +} |
| + |
| +func wantBurstMatch(t *testing.T, m reqrec.Match, kind reqrec.Kind, from string, until time.Time) { |
| + t.Helper() |
| + if m.Tier != reqrec.TierBurst || m.RuleID != edgeguard.BurstRule.ID || m.Kind != kind || |
| + m.CooldownFrom != from || !m.CooldownUntil.Equal(until) { |
| + t.Fatalf("match %+v, want a burst %s from %q until %v", m, kind, from, until) |
| + } |
| +} |
| + |
| +// wantRefused checks a refusal: 429, Retry-After the cool-down's remaining |
| +// whole seconds, never stored, and the deck's body carrying the same sealed |
| +// burst code as the header. It returns the code. |
| +func (g *burstRig) wantRefused(t *testing.T, w *httptest.ResponseRecorder, until time.Time) string { |
| + t.Helper() |
| + if w.Code != http.StatusTooManyRequests { |
| + t.Fatalf("status %d (%q), want 429", w.Code, w.Body.String()) |
| + } |
| + ra, err := strconv.Atoi(w.Header().Get("Retry-After")) |
| + // The remaining seconds, rounded up. |
| + if want := int((until.Sub(g.clock.now()) + time.Second - 1) / time.Second); err != nil || ra != want || ra > 600 { |
| + t.Fatalf("Retry-After %q, want %d", w.Header().Get("Retry-After"), want) |
| + } |
| + if cc := w.Header().Get("Cache-Control"); cc != "no-store" { |
| + t.Fatalf("Cache-Control %q", cc) |
| + } |
| + code := w.Header().Get("X-Carlos-Ref") |
| + ref, err := reqrec.ParseRef(code, g.key) |
| + if err != nil || !ref.Verified || ref.Tier != reqrec.TierBurst || ref.RuleHash != reqrec.RuleHash(edgeguard.BurstRule.ID) { |
| + t.Fatalf("code %q: %+v %v", code, ref, err) |
| + } |
| + if want := strings.ReplaceAll(burstRefusalCopy, "{code}", code); strings.TrimSuffix(w.Body.String(), "\n") != want { |
| + t.Fatalf("body %q, want %q", w.Body.String(), want) |
| + } |
| + return code |
| +} |
| + |
| +// The scanner's 60th not-found trips it. In the default (watch) mode its |
| +// 61st catalogue request still reaches the app, and is recorded as the |
| +// refusal it would have been, saying the cool-down started on this app. |
| +func TestBurstTripsAndRecordsWouldRefuse(t *testing.T) { |
| + g := newBurstRig(t, "") |
| + until := g.trip(t, burstHost) |
| + tr := g.rec.trips[0] |
| + ref, err := reqrec.ParseRef(tr.Ref, g.key) |
| + if err != nil || !ref.Verified || ref.Tier != reqrec.TierBurst || !tr.Until.Equal(until) || tr.App != "shop" || tr.Acct != "bdk" { |
| + t.Fatalf("trip %+v (%+v, %v)", tr, ref, err) |
| + } |
| + n := g.upstream.Load() |
| + w := g.get(burstHost, "/wp-login.php") |
| + if w.Code != 404 || w.Body.String() != "the app's own 404" || g.upstream.Load() != n+1 { |
| + t.Fatalf("watch mode: %d %q, upstream %d; want the app's answer", w.Code, w.Body.String(), g.upstream.Load()-n) |
| + } |
| + m := g.lastMatch(t, "/wp-login.php") |
| + wantBurstMatch(t, m, reqrec.KindWatch, reqrec.CooldownFromThisApp, until) |
| + if m.Ref != "" || m.Status != 404 { |
| + t.Fatalf("watch: %+v", m) |
| + } |
| +} |
| + |
| +func TestBurstRefusesInBlockMode(t *testing.T) { |
| + g := newBurstRig(t, "block") |
| + until := g.trip(t, burstHost) |
| + g.clock.advance(90*time.Second + 300*time.Millisecond) |
| + n := g.upstream.Load() |
| + w := g.get(burstHost, "/wp-login.php") |
| + code := g.wantRefused(t, w, until) |
| + if w.Header().Get("Retry-After") != "510" { |
| + t.Fatalf("Retry-After %q, want 510 (509.7 s rounded up)", w.Header().Get("Retry-After")) |
| + } |
| + if g.upstream.Load() != n { |
| + t.Fatal("a refused request reached the app") |
| + } |
| + m := g.lastMatch(t, "/wp-login.php") |
| + wantBurstMatch(t, m, reqrec.KindBlock, reqrec.CooldownFromThisApp, until) |
| + if m.Ref != code || m.Status != 429 { |
| + t.Fatalf("block: %+v", m) |
| + } |
| +} |
| + |
| +// Review Focus 1: a page that is not in the catalogue is never refused, |
| +// whoever shares the address. |
| +func TestBurstNeverRefusesAnOrdinaryPage(t *testing.T) { |
| + g := newBurstRig(t, "block", burstHost+"/about") |
| + g.trip(t, burstHost) |
| + w := g.get(burstHost, "/about") |
| + if w.Code != 200 || w.Body.String() != "page /about" { |
| + t.Fatalf("%d %q, want the page", w.Code, w.Body.String()) |
| + } |
| + if len(g.rec.resp) == 0 || g.rec.resp[len(g.rec.resp)-1].Path != "/about" { |
| + t.Fatalf("/about was not filed as a plain response") |
| + } |
| +} |
| + |
| +// Review Focus 4: a static site's own file is served to a cooling client |
| +// even when its path is in the catalogue; a missing catalogue path is |
| +// refused. |
| +func TestBurstNeverRefusesAnExistingStaticFile(t *testing.T) { |
| + g := newBurstStaticRig(t, "block", map[string]string{"index.html": "home", "admin/index.html": "our admin"}) |
| + until := g.trip(t, burstHost) |
| + if w := g.get(burstHost, "/admin/"); w.Code != 200 || w.Body.String() != "our admin" { |
| + t.Fatalf("/admin/: %d %q, want the site's page", w.Code, w.Body.String()) |
| + } |
| + if r := g.rec.resp[len(g.rec.resp)-1]; r.Path != "/admin/" || r.Status != 200 { |
| + t.Fatalf("/admin/ filed as %+v", r) |
| + } |
| + g.wantRefused(t, g.get(burstHost, "/wp-login.php"), until) |
| + wantBurstMatch(t, g.lastMatch(t, "/wp-login.php"), reqrec.KindBlock, reqrec.CooldownFromThisApp, until) |
| +} |
| + |
| +// The cool-down is the client's, on every app on the box. The record on the |
| +// other app says where it came from without naming the app. |
| +func TestBurstCooldownCoversOtherApps(t *testing.T) { |
| + g := newBurstRig(t, "block") |
| + until := g.trip(t, burstHost) |
| + g.wantRefused(t, g.get(burstOther, "/xmlrpc.php"), until) |
| + m := g.lastMatch(t, "/xmlrpc.php") |
| + wantBurstMatch(t, m, reqrec.KindBlock, reqrec.CooldownFromOtherApp, until) |
| + if m.App != "blog" || m.Acct != "bab" { |
| + t.Fatalf("filed under %s/%s, want bab/blog", m.Acct, m.App) |
| + } |
| +} |
| + |
| +// A browser's requests never count, however many of them miss. |
| +func TestBurstBrowserRequestsNeverCount(t *testing.T) { |
| + g := newBurstRig(t, "") |
| + for i := 0; i < 100; i++ { |
| + g.get(burstHost, fmt.Sprintf("/missing-%d", i), "Sec-Fetch-Mode", "navigate") |
| + } |
| + g.scan(burstHost, 100, "Sec-Fetch-Mode", "navigate") |
| + if _, _, ok := g.e.burst.cooling(burstScanner); ok || len(g.rec.trips) != 0 || g.e.burst.counterCount() != 0 { |
| + t.Fatalf("browser requests counted: cooling %v, trips %d, counters %d", ok, len(g.rec.trips), g.e.burst.counterCount()) |
| + } |
| +} |
| + |
| +// An admin page is a page real admins open: a match on it counts only when |
| +// the app has no such page. |
| +func TestBurstAdminCountsOnlyOn404(t *testing.T) { |
| + g := newBurstRig(t, "", burstHost+"/admin") |
| + shop, blog := burstAppKey(registry.Route{Account: "bdk", App: "shop"}), burstAppKey(registry.Route{Account: "bab", App: "blog"}) |
| + for i := 0; i < 5; i++ { |
| + if w := g.get(burstHost, "/admin"); w.Code != 200 { |
| + t.Fatalf("/admin on shop: %d", w.Code) |
| + } |
| + } |
| + if n := g.e.burst.ringLen(shop, burstScanner); n != 0 { |
| + t.Fatalf("an answered /admin counted %d times", n) |
| + } |
| + for i := 0; i < 5; i++ { |
| + if w := g.get(burstOther, "/admin"); w.Code != 404 { |
| + t.Fatalf("/admin on blog: %d", w.Code) |
| + } |
| + } |
| + if n := g.e.burst.ringLen(blog, burstScanner); n != 5 { |
| + t.Fatalf("a missing /admin counted %d times, want 5", n) |
| + } |
| +} |
| + |
| +// burstHub is forwardHubAndBox in block mode with a forward row for |
| +// burstHost and a recorder that takes records from the hub's server |
| +// goroutines, with the test client already tripped on the hub. The hub keeps |
| +// the limiter New built, on the real clock: it is serving by now, and sixty |
| +// loopback requests take well under the window. |
| +func burstHub(t *testing.T) (hubURL string, hub *Edge, rec *lockedRecorder, box *countingBox) { |
| + t.Helper() |
| + t.Setenv("CARLOS_EDGE_PROTECT", "block") |
| + box = &countingBox{} |
| + hubURL, hub, _ = forwardHubAndBox(t, []registry.Route{forwardRow(burstHost, "home", fwdOwner)}, nil, box) |
| + rec = &lockedRecorder{} |
| + hub.EnableRequestRecords(rec) |
| + // The hub sees the test client's loopback address. |
| + client := netip.MustParsePrefix("127.0.0.1/32") |
| + for i := 0; i < burstThreshold; i++ { |
| + fwdDo(t, hubURL, "GET", burstHost, scanPath(i), "", nil) |
| + } |
| + laWaitFor(t, "the scanner to trip on the hub", func() bool { |
| + _, _, ok := hub.burst.cooling(client) |
| + return ok |
| + }) |
| + return hubURL, hub, rec, box |
| +} |
| + |
| +// matchFor waits for the hub's one Match for path and returns it. |
| +func matchFor(t *testing.T, rec *lockedRecorder, path string) reqrec.Match { |
| + t.Helper() |
| + var got []reqrec.Match |
| + laWaitFor(t, "the match for "+path, func() bool { |
| + got = got[:0] |
| + for _, m := range rec.matches() { |
| + if m.Path == path { |
| + got = append(got, m) |
| + } |
| + } |
| + return len(got) > 0 |
| + }) |
| + if len(got) != 1 { |
| + t.Fatalf("%d matches for %s, want 1: %+v", len(got), path, got) |
| + } |
| + return got[0] |
| +} |
| + |
| +// A fleet app is never refused by the burst limit: the hub cannot see what |
| +// the fleet box serves. Its request is forwarded and recorded. |
| +func TestBurstFleetAppNeverRefused(t *testing.T) { |
| + hubURL, _, rec, box := burstHub(t) |
| + before := box.count(burstHost) |
| + resp, body := fwdDo(t, hubURL, "GET", burstHost, "/admin", "", nil) |
| + if resp.StatusCode != 200 || box.count(burstHost) != before+1 || !strings.HasPrefix(string(body), "call ") { |
| + t.Fatalf("%d %q, box %d; want the box's answer", resp.StatusCode, body, box.count(burstHost)-before) |
| + } |
| + m := matchFor(t, rec, "/admin") |
| + if m.Tier != reqrec.TierBurst || m.Kind != reqrec.KindWatch || m.CooldownFrom != reqrec.CooldownFromThisApp || m.Ref != "" { |
| + t.Fatalf("match %+v, want a burst watch", m) |
| + } |
| +} |
| + |
| +// One request has one verdict, one record and one Protection count, however |
| +// many rules it meets. |
| +func TestBurstOneVerdictPerRequest(t *testing.T) { |
| + g := newBurstRig(t, "") |
| + until := g.trip(t, burstHost) |
| + g.meter.Drain() |
| + matches := len(g.rec.match) |
| + g.get(burstHost, "/.env") |
| + if len(g.rec.match) != matches+1 { |
| + t.Fatalf("%d matches for one request", len(g.rec.match)-matches) |
| + } |
| + wantBurstMatch(t, g.lastMatch(t, "/.env"), reqrec.KindWatch, reqrec.CooldownFromThisApp, until) |
| + f := g.meter.Drain() |
| + d, ok := f.Guard[usage.GuardKey(burstHost, "bdk", "shop")] |
| + if len(f.Guard) != 1 || !ok || d.Checked != 1 || d.Watch != 1 || d.Block != 0 || !maps.Equal(d.Groups, map[string]int64{"burst/probe-burst": 1}) { |
| + t.Fatalf("guard counts %+v, want one recorded burst/probe-burst", f.Guard) |
| + } |
| +} |
| + |
| +// R1-1: a burst verdict that does not block never takes the place of one |
| +// that does. On a fleet app (never refused by the burst limit) a hard path is |
| +// still blocked; on a static site whose rewrite would send a file the hard |
| +// tier blocks, the burst watch on the request path does not save the file. |
| +func TestBurstWatchNeverWeakensABlock(t *testing.T) { |
| + t.Run("fleet", func(t *testing.T) { |
| + hubURL, _, rec, box := burstHub(t) |
| + before := box.count(burstHost) |
| + resp, _ := fwdDo(t, hubURL, "GET", burstHost, "/.env", "", nil) |
| + if resp.StatusCode != 404 || resp.Header.Get("X-Carlos-Ref") == "" || box.count(burstHost) != before { |
| + t.Fatalf("%d ref %q, box %d; want the block page", resp.StatusCode, resp.Header.Get("X-Carlos-Ref"), box.count(burstHost)-before) |
| + } |
| + m := matchFor(t, rec, "/.env") |
| + if m.Kind != reqrec.KindBlock || m.RuleID != "hard.secrets.env" || m.Ref != resp.Header.Get("X-Carlos-Ref") { |
| + t.Fatalf("match %+v, want the hard block", m) |
| + } |
| + }) |
| + t.Run("static rewrite", func(t *testing.T) { |
| + // The default mode, where the burst rule watches; the .env rule as |
| + // it will be once promoted to block. |
| + g := newBurstStaticRig(t, "", map[string]string{".env": "SECRET=1", "_redirects": "/* /.env 200\n"}) |
| + until := g.trip(t, burstHost) |
| + env, ok := edgeguard.RuleByID("hard.secrets.env") |
| + if !ok { |
| + t.Fatal("no hard.secrets.env") |
| + } |
| + env.Mode = edgeguard.ModeBlock |
| + t.Cleanup(func() { env.Mode = edgeguard.ModeWatch }) |
| + matches := len(g.rec.match) |
| + w := g.get(burstHost, "/wp-login.php") |
| + if w.Code != 404 || w.Header().Get("X-Carlos-Ref") == "" || strings.Contains(w.Body.String(), "SECRET") { |
| + t.Fatalf("%d ref %q body %q; want the block page", w.Code, w.Header().Get("X-Carlos-Ref"), w.Body.String()) |
| + } |
| + m := g.lastMatch(t, "/wp-login.php") |
| + if len(g.rec.match) != matches+1 || m.Kind != reqrec.KindBlock || m.RuleID != "hard.secrets.env" { |
| + t.Fatalf("match %+v, want the one hard block", m) |
| + } |
| + // A hard-tier request path is offered the burst rule in ServeHTTP, |
| + // before the static handler runs; the handler must still check |
| + // what the rewrite would send. |
| + w = g.get(burstHost, "/.git/config") |
| + if w.Code != 404 || w.Header().Get("X-Carlos-Ref") == "" || strings.Contains(w.Body.String(), "SECRET") { |
| + t.Fatalf("/.git/config: %d ref %q body %q; want the block page", w.Code, w.Header().Get("X-Carlos-Ref"), w.Body.String()) |
| + } |
| + if m := g.lastMatch(t, "/.git/config"); m.Kind != reqrec.KindBlock || m.RuleID != "hard.secrets.env" { |
| + t.Fatalf("/.git/config: match %+v, want the hard block", m) |
| + } |
| + // Without the promotion the burst watch stands, as the first |
| + // verdict that does not block. |
| + env.Mode = edgeguard.ModeWatch |
| + g.get(burstHost, "/wp-login.php") |
| + wantBurstMatch(t, g.lastMatch(t, "/wp-login.php"), reqrec.KindWatch, reqrec.CooldownFromThisApp, until) |
| + }) |
| +} |
| + |
| +// burstFar is a far edge and a real home edge (betty) for laHost, both on |
| +// the hand-driven limiter clock, with recorders. served counts the home's |
| +// finished ServeHTTP calls, so a test can wait for the home's defers. |
| +type burstFar struct { |
| + s *farScene |
| + home *laScene |
| + served *atomic.Int32 |
| + farRec *lockedRecorder |
| + homeRec *lockedRecorder |
| +} |
| + |
| +func newBurstFar(t *testing.T, app http.HandlerFunc) *burstFar { |
| + t.Helper() |
| + t.Setenv("CARLOS_EDGE_PROTECT", "") |
| + clock := newBurstClock() |
| + x := &burstFar{served: new(atomic.Int32), farRec: &lockedRecorder{}, homeRec: &lockedRecorder{}} |
| + x.s = newFarEdge(t, func(key []byte, m *homeMap) http.Handler { |
| + x.home = newLAScene(t, app) |
| + hm := newHomeMap(m.s, "betty") |
| + refreshHomeMap(t, hm) |
| + x.home.e.homes.Store(hm) |
| + x.home.e.burst = newBurstLimiter(clock.now) |
| + x.home.e.EnableRequestRecords(x.homeRec) |
| + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + defer x.served.Add(1) |
| + x.home.e.ServeHTTP(w, r) |
| + }) |
| + }) |
| + x.s.e.burst = newBurstLimiter(clock.now) |
| + x.s.e.EnableRequestRecords(x.farRec) |
| + return x |
| +} |
| + |
| +// waitHome waits until the home has finished n requests. |
| +func (x *burstFar) waitHome(t *testing.T, n int32) { |
| + t.Helper() |
| + laWaitFor(t, fmt.Sprintf("the home to finish %d requests", n), func() bool { return x.served.Load() >= n }) |
| + if got := x.served.Load(); got != n { |
| + t.Fatalf("the home served %d requests, want %d", got, n) |
| + } |
| +} |
| + |
| +// burstNotes is how many not-founds b holds, over every app and client. |
| +func burstNotes(b *burstLimiter) int { |
| + b.mu.Lock() |
| + defer b.mu.Unlock() |
| + n := 0 |
| + for el := b.counterLRU.Front(); el != nil; el = el.Next() { |
| + n += len(el.Value.(*burstCounter).ts) |
| + } |
| + return n |
| +} |
| + |
| +// missingAsset answers 404 for every asset. |
| +func missingAsset(w http.ResponseWriter, r *http.Request) { |
| + w.WriteHeader(http.StatusNotFound) |
| + io.WriteString(w, "no such asset") |
| +} |
| + |
| +// R2-1: a far edge's fill rebuilds the request's headers, so only the far |
| +// edge, which saw the visitor's own, may count it. A browser's misses count |
| +// nowhere; a scanner's count on the far edge and never at the home. |
| +func TestBurstAssetFillCountedOnlyAtTheFarEdge(t *testing.T) { |
| + x := newBurstFar(t, missingAsset) |
| + for i := 0; i < burstThreshold; i++ { |
| + if w := x.s.get(t, fmt.Sprintf("/assets/missing-%d.js", i), "Sec-Fetch-Mode", "no-cors"); w.Code != 404 { |
| + t.Fatalf("browser asset %d: %d", i, w.Code) |
| + } |
| + } |
| + x.waitHome(t, burstThreshold) |
| + if far, home := burstNotes(x.s.e.burst), burstNotes(x.home.e.burst); far != 0 || home != 0 { |
| + t.Fatalf("browser misses counted: far %d, home %d", far, home) |
| + } |
| + for i := 0; i < burstThreshold; i++ { |
| + x.s.get(t, fmt.Sprintf("/assets/gone-%d.js", i)) |
| + } |
| + x.waitHome(t, 2*burstThreshold) |
| + if _, _, ok := x.s.e.burst.cooling(burstScanner); !ok { |
| + t.Fatal("the scanner did not trip on the far edge") |
| + } |
| + x.farRec.mu.Lock() |
| + trips := len(x.farRec.trips) |
| + x.farRec.mu.Unlock() |
| + if trips != 1 { |
| + t.Fatalf("%d trip records on the far edge, want 1", trips) |
| + } |
| + if n, cool := burstNotes(x.home.e.burst), x.home.e.burst.cooldownCount(); n != 0 || cool != 0 { |
| + t.Fatalf("the home counted fills: %d notes, %d cool-downs", n, cool) |
| + } |
| +} |
| + |
| +// R3-2: each visitor response counts once. A scanner's missing asset filled |
| +// through the far edge counts there; one the far edge re-forwards to the |
| +// home as an ordinary hop (a buffered request whose fill stored nothing) |
| +// counts at the home, which saw the visitor's headers on that hop. |
| +func TestBurstFarCountsOnceIncludingReforward(t *testing.T) { |
| + x := newBurstFar(t, func(w http.ResponseWriter, r *http.Request) { |
| + if !strings.HasSuffix(r.URL.Path, ".php") { |
| + missingAsset(w, r) |
| + return |
| + } |
| + // Storable at the headers, vetoed by a Set-Cookie trailer: a |
| + // buffered initiator is then re-forwarded. |
| + w.Header().Set("Content-Type", "application/javascript") |
| + w.Header().Set("Cache-Control", "public, max-age=3600") |
| + w.Header().Set("Trailer", "Set-Cookie") |
| + io.WriteString(w, laBody) |
| + w.(http.Flusher).Flush() |
| + w.Header().Set("Set-Cookie", "late=1") |
| + }) |
| + const n = 5 |
| + for i := 0; i < n; i++ { |
| + if w := x.s.get(t, fmt.Sprintf("/assets/gone-%d.js", i)); w.Code != 404 { |
| + t.Fatalf("filled miss %d: %d", i, w.Code) |
| + } |
| + } |
| + x.waitHome(t, n) |
| + if far, home := burstNotes(x.s.e.burst), burstNotes(x.home.e.burst); far != n || home != 0 { |
| + t.Fatalf("filled: far %d, home %d; want %d and 0", far, home, n) |
| + } |
| + for i := 0; i < n; i++ { |
| + w := x.s.get(t, fmt.Sprintf("/assets/probe-%d.php", i), "Range", "bytes=0-6") |
| + wantCache(t, w, "bypass") |
| + } |
| + // Each one is a fill and then the re-forward. |
| + x.waitHome(t, 3*n) |
| + if far, home := burstNotes(x.s.e.burst), burstNotes(x.home.e.burst); far != n || home != n { |
| + t.Fatalf("re-forwarded: far %d, home %d; want %d and %d", far, home, n, n) |
| + } |
| +} |
| + |
| +// The trip's code finds its record the way the console's edge-ref lookup |
| +// does (apiedgeref.go): through the box's log sink and shipped chunks, read |
| +// back with that handler's window, stream and ref filter, and named as the |
| +// burst rule by its hash and tier. |
| +func TestBurstTripRefFindsItsRecord(t *testing.T) { |
| + g := newBurstRig(t, "") |
| + sink := applog.NewSink("annie", time.Now) |
| + g.e.EnableRequestRecords(reqrec.NewRecorder(sink, nil, nil)) |
| + g.scan(burstHost, burstThreshold) |
| + if _, _, ok := g.e.burst.cooling(burstScanner); !ok { |
| + t.Fatal("no trip") |
| + } |
| + // Ship what the sink holds, as the box's shipper does (logship.go). |
| + store := release.NewDirStore(t.TempDir()) |
| + var code string |
| + for k, recs := range sink.Drain() { |
| + for _, r := range recs { |
| + if r.Fields["kind"] == "trip" { |
| + code = r.Fields["ref"] |
| + } |
| + } |
| + body, err := applog.EncodeChunk(recs) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + key, err := applog.ChunkKey(k.Acct, k.App, recs[0].Box, applog.HourOf(recs[0].TS), recs[0].Seq, len(body)) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := store.Put(context.Background(), key, body, ""); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + if code == "" { |
| + t.Fatal("no trip record in the sink") |
| + } |
| + ref, err := reqrec.ParseRef(code, g.key) |
| + if err != nil || !ref.Verified { |
| + t.Fatalf("code %q: %+v %v", code, ref, err) |
| + } |
| + canon, err := reqrec.CanonicalRef(code) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + recs, _, err := applog.ReadWindow(context.Background(), store, "bdk", "shop", applog.Filter{ |
| + Since: ref.At.Add(-time.Minute), |
| + Until: ref.At.Add(2 * time.Minute), |
| + Stream: applog.StreamEdge, |
| + Fields: map[string]string{"ref": canon}, |
| + }, 1000) |
| + if err != nil || len(recs) != 1 || recs[0].Fields["kind"] != "trip" || recs[0].Fields["rule"] != edgeguard.BurstRule.ID { |
| + t.Fatalf("lookup found %+v (%v), want the trip record", recs, err) |
| + } |
| + if rule, ok := edgeguard.RuleByHash(ref.RuleHash); !ok || rule.Tier != ref.Tier || rule != edgeguard.BurstRule { |
| + t.Fatalf("the code names %v, want the burst rule", rule) |
| + } |
| +} |
| + |
| +// The precedence rule, one place: a verdict that does not block gives way to |
| +// a later one that does; a block is never replaced; among verdicts that do |
| +// not block the first stands. |
| +func TestBurstDecideVerdictPrecedence(t *testing.T) { |
| + watchA, watchB := &guardVerdict{rule: edgeguard.BurstRule}, &guardVerdict{rule: edgeguard.BurstRule} |
| + blockA, blockB := &guardVerdict{rule: edgeguard.BurstRule, block: true}, &guardVerdict{rule: edgeguard.BurstRule, block: true} |
| + for _, tc := range []struct { |
| + name string |
| + first, next *guardVerdict |
| + applied bool |
| + want *guardVerdict |
| + }{ |
| + {"none then watch", nil, watchA, true, watchA}, |
| + {"watch then watch", watchA, watchB, false, watchA}, |
| + {"watch then block", watchA, blockA, true, blockA}, |
| + {"block then watch", blockA, watchA, false, blockA}, |
| + {"block then block", blockA, blockB, false, blockA}, |
| + } { |
| + st := &guardState{verdict: tc.first} |
| + if got := decideVerdict(st, tc.next); got != tc.applied || st.verdict != tc.want { |
| + t.Errorf("%s: applied %v, verdict %p; want %v, %p", tc.name, got, st.verdict, tc.applied, tc.want) |
| + } |
| + } |
| +} |
| + |
| +// The record-only switch (set by Task 5): with it on, nothing blocks, hard |
| +// rules and the burst limit alike, and every match is still noted. |
| +func TestBurstRecordOnlyBlocksNothing(t *testing.T) { |
| + g := newBurstRig(t, "block") |
| + until := g.clock.now().Add(burstCooldown) |
| + for _, tc := range []struct { |
| + name string |
| + decide func(w http.ResponseWriter, r *http.Request) bool |
| + rule string |
| + }{ |
| + {"hard", func(w http.ResponseWriter, r *http.Request) bool { |
| + hit, _ := edgeguard.Check("/.env", "") |
| + return guardDecide(w, r, hit) |
| + }, "hard.secrets.env"}, |
| + {"burst", func(w http.ResponseWriter, r *http.Request) bool { |
| + return burstDecide(w, r, until, reqrec.CooldownFromThisApp, false) |
| + }, edgeguard.BurstRule.ID}, |
| + } { |
| + r, out := withOutcome(httptest.NewRequest("GET", "http://"+burstHost+"/.env", nil)) |
| + out.guard = g.e.newGuardState() |
| + out.guard.recordOnly = true |
| + w := httptest.NewRecorder() |
| + if tc.decide(w, r) || w.Code != 200 || w.Body.Len() != 0 { |
| + t.Fatalf("%s: answered %d %q with record-only on", tc.name, w.Code, w.Body.String()) |
| + } |
| + if v := out.guard.verdict; v == nil || v.block || v.ref != "" || v.rule.ID != tc.rule { |
| + t.Fatalf("%s: verdict %+v, want a recorded %s", tc.name, v, tc.rule) |
| + } |
| + } |
| +} |
| + |
| +// memRecorder and lockedRecorder take trips too. |
| +func (m *memRecorder) Trip(x reqrec.Trip) { m.trips = append(m.trips, x) } |
| + |
| +func (l *lockedRecorder) Trip(x reqrec.Trip) { |
| + l.mu.Lock() |
| + defer l.mu.Unlock() |
| + l.trips = append(l.trips, x) |
| +} |
diff --git a/internal/edge/burst_refusal.go b/internal/edge/burst_refusal.go| new file mode 100644 |
| index 000000000..03b677193 |
| --- /dev/null |
| +++ b/internal/edge/burst_refusal.go |
| @@ -0,0 +1,31 @@ |
| +package edge |
| + |
| +import ( |
| + "io" |
| + "net/http" |
| + "strconv" |
| + "strings" |
| + "time" |
| +) |
| + |
| +// burstRefusalCopy is the body of a probe-burst refusal, copy deck row |
| +// PB-C01, with {code} standing for the refusal's reference code. It is the |
| +// only place the text lives. |
| +const burstRefusalCopy = "Too many requests for pages that do not exist came from your network. Try again in a few minutes. Reference: {code}" |
| + |
| +// writeBurstRefusal answers a catalogue request from a client in a |
| +// probe-burst cool-down: 429 with Retry-After the cool-down's remaining |
| +// whole seconds, rounded up (at least one), and the reference code in a |
| +// header and in the body. Never stored: a code names one request. |
| +func writeBurstRefusal(w http.ResponseWriter, code string, remaining time.Duration) { |
| + secs := max(int64((remaining+time.Second-1)/time.Second), 1) |
| + h := w.Header() |
| + h.Set("Content-Type", "text/plain; charset=utf-8") |
| + h.Set("Cache-Control", "no-store") |
| + h.Set("X-Content-Type-Options", "nosniff") |
| + h.Set("X-Carlos-Ref", code) |
| + h.Set("Retry-After", strconv.FormatInt(secs, 10)) |
| + w.WriteHeader(http.StatusTooManyRequests) |
| + io.WriteString(w, strings.ReplaceAll(burstRefusalCopy, "{code}", code)) |
| + io.WriteString(w, "\n") |
| +} |
diff --git a/internal/edge/edge.go b/internal/edge/edge.go| index 7240ca06f..6aa3e426f 100644 |
| --- a/internal/edge/edge.go |
| +++ b/internal/edge/edge.go |
| @@ -279,6 +279,10 @@ type Edge struct { |
| // request would allocate for every guarded request, and most never |
| // mint a code. |
| guardMint func(reqrec.Tier, string) string |
| + // burst is the probe-burst limiter (burst.go): not-founds counted per |
| + // app and client in the observer defer, and the box-wide cool-downs the |
| + // guard checks catalogue requests against. |
| + burst *burstLimiter |
| // issuer, when set, gates certificate ISSUANCE on this box holding the |
| // deployment's housekeeper lease (certsync.go). It arrives through |
| // WithIssuerGate because internal/host imports this package and never the |
| @@ -529,7 +533,7 @@ func New(reg *registry.Registry, act Activator) (*Edge, error) { |
| func newEdge(reg *registry.Registry, act Activator, hold localHold) (*Edge, error) { |
| e := &Edge{reg: reg, act: act, hold: hold, gate: gate.New(), probers: newProberSet(hold), gzipOn: gzipEnabled(), guard: guardModeFromEnv(os.Getenv), steeringHost: steeringProbeHostFromEnv(), appsDomain: appsDomainFromEnv(), |
| lbHealth: lbHealthFromEnv(os.Getenv, act), rateMode: rateModeFromEnv(), rateLimiter: ratelimit.NewLimiter(time.Now, 100_000), |
| - planLimiter: ratelimit.NewLimiter(time.Now, 100_000)} |
| + planLimiter: ratelimit.NewLimiter(time.Now, 100_000), burst: newBurstLimiter(time.Now)} |
| e.geo = geo.NewSwappable() |
| e.geoLookup = e.geo.Lookup |
| e.guardMint = e.mintRef |
| @@ -2176,6 +2180,11 @@ func (e *Edge) ServeHTTP(w http.ResponseWriter, r *http.Request) { |
| // checking it again here would answer or count it twice. |
| if e.guard != guardOff && !isDoor && !hopDoorFrom(r.Context()) && !fromTunnel(r.Context()) { |
| out.guard = e.newGuardState() |
| + out.guard.acct, out.guard.app = release.RouteAccount(up.route), up.route.App |
| + // A verified hop carrying a fill assertion is a far edge's |
| + // asset fill, whatever becomes of it here (serveAssetFillForHop |
| + // may still take it as an ordinary hop): the far edge counts it. |
| + out.assetFill = hopped && r.Header.Get(assetFillHeader) != "" |
| } |
| defer func() { |
| // An acknowledged home fill is billed by the far edge that |
| @@ -2194,6 +2203,7 @@ func (e *Edge) ServeHTTP(w http.ResponseWriter, r *http.Request) { |
| // under !out.unbilled: an acknowledged home fill is checked |
| // and recorded here, so it is counted here too. |
| e.observeGuardCount(up.route, out) |
| + e.noteBurst(up.route, r, ob.status, out) |
| }() |
| } |
| @@ -2210,6 +2220,12 @@ func (e *Edge) ServeHTTP(w http.ResponseWriter, r *http.Request) { |
| // A static route this box serves itself checks only the hard tier here: |
| // whether a probe-tier path is a probe depends on what the site holds, |
| // which only the static handler knows, so it decides that tier itself. |
| + // |
| + // A catalogue request from a client in a probe-burst cool-down is |
| + // offered the burst rule first: refused in place of the block page when |
| + // the mode blocks it, and otherwise a verdict that any block below still |
| + // replaces (decideVerdict). A fleet app's request, whether a forward row |
| + // or another box's tunnel, is only ever recorded. |
| if out != nil && out.guard != nil { |
| var hit edgeguard.Hit |
| var matched bool |
| @@ -2218,8 +2234,14 @@ func (e *Edge) ServeHTTP(w http.ResponseWriter, r *http.Request) { |
| } else { |
| hit, matched = edgeguard.Check(r.URL.Path, r.URL.RawQuery) |
| } |
| - if matched && guardDecide(w, r, hit) { |
| - return |
| + if matched { |
| + fleet := up.viaTunnel || up.route.IsForward() |
| + if until, from, cooling := out.guard.cooling(r); cooling && burstDecide(w, r, until, from, fleet) { |
| + return |
| + } |
| + if guardDecide(w, r, hit) { |
| + return |
| + } |
| } |
| } |
diff --git a/internal/edge/guard.go b/internal/edge/guard.go| index 410a40753..ae3008f66 100644 |
| --- a/internal/edge/guard.go |
| +++ b/internal/edge/guard.go |
| @@ -5,10 +5,14 @@ import ( |
| "io" |
| "log" |
| "net/http" |
| + "net/netip" |
| "strings" |
| + "time" |
| "github.com/carlosframework/platform/internal/edgeguard" |
| + "github.com/carlosframework/platform/internal/ratelimit" |
| "github.com/carlosframework/platform/internal/registry" |
| + "github.com/carlosframework/platform/internal/release" |
| "github.com/carlosframework/platform/internal/reqrec" |
| ) |
| @@ -66,11 +70,16 @@ func (m guardMode) blocks(rule *edgeguard.Rule) bool { |
| // guardVerdict is what the guard decided about a request that matched a |
| // rule. frag has already passed through reqrec.Fragment, and is "" when it |
| // may not be kept; ref is the code on the block page, set only for a block. |
| +// until and from are set only for the burst rule: when the client's |
| +// cool-down ends and where it started (reqrec.CooldownFromThisApp or |
| +// reqrec.CooldownFromOtherApp). |
| type guardVerdict struct { |
| rule *edgeguard.Rule |
| frag string |
| block bool |
| ref string |
| + until time.Time |
| + from string |
| } |
| // guardState rides a request's outcome when the guard runs for it. ServeHTTP |
| @@ -78,10 +87,20 @@ type guardVerdict struct { |
| // place of the plain Response. mint is the edge's mintRef, carried here so |
| // guardDecide needs no *Edge: the static handler, which has none, decides |
| // the probe tier for its own routes. |
| +// |
| +// burst, acct and app are what the static handler needs to ask whether the |
| +// client is in a probe-burst cool-down (cooling): the edge's limiter and the |
| +// route's owner, which ServeHTTP fills in once it knows the route. |
| +// |
| +// recordOnly is the app's record-only switch: with it on nothing blocks, |
| +// whatever the mode, and every match is still recorded. |
| type guardState struct { |
| - mode guardMode |
| - mint func(reqrec.Tier, string) string |
| - verdict *guardVerdict |
| + mode guardMode |
| + mint func(reqrec.Tier, string) string |
| + verdict *guardVerdict |
| + recordOnly bool |
| + burst *burstLimiter |
| + acct, app string |
| } |
| // newGuardState is the guard's state for one request. It costs the struct |
| @@ -93,7 +112,35 @@ func (e *Edge) newGuardState() *guardState { |
| if mint == nil { |
| mint = e.mintRef |
| } |
| - return &guardState{mode: e.guard, mint: mint} |
| + return &guardState{mode: e.guard, mint: mint, burst: e.burst} |
| +} |
| + |
| +// blocks reports whether a match on rule is answered here rather than |
| +// forwarded: the mode says so and the app's record-only switch is off. |
| +func (st *guardState) blocks(rule *edgeguard.Rule) bool { |
| + return !st.recordOnly && st.mode.blocks(rule) |
| +} |
| + |
| +// cooling reports whether r's client is in a probe-burst cool-down, when it |
| +// ends, and where it started as a record says it. It takes the limiter's |
| +// lock, so callers ask only once a catalogue rule has matched. |
| +func (st *guardState) cooling(r *http.Request) (until time.Time, from string, ok bool) { |
| + if st.burst == nil { |
| + return time.Time{}, "", false |
| + } |
| + client, ok := ratelimit.ClientKey(clientIP(r)) |
| + if !ok { |
| + return time.Time{}, "", false |
| + } |
| + until, app, ok := st.burst.cooling(client) |
| + if !ok { |
| + return time.Time{}, "", false |
| + } |
| + from = reqrec.CooldownFromOtherApp |
| + if app != "" && app == burstAppKeyOf(st.acct, st.app) { |
| + from = reqrec.CooldownFromThisApp |
| + } |
| + return until, from, true |
| } |
| // observeGuardCount counts one request the guard ran for into the usage |
| @@ -116,33 +163,146 @@ func (e *Edge) observeGuardCount(rt registry.Route, out *outcome) { |
| m.RecordGuard(rt, rule, blocked) |
| } |
| -// guardDecide notes hit as r's verdict and, when the mode blocks the rule, |
| +// decideVerdict is the one rule for which of a request's candidate verdicts |
| +// stands. A request has one verdict, but one that does not block gives way |
| +// to a later candidate that does, so a burst watch, a fleet app's exemption |
| +// or a record-only app's never weakens a hard or probe block; a block is |
| +// never replaced; and among candidates that do not block the first stands. |
| +// It reports whether v is now the verdict. |
| +func decideVerdict(st *guardState, v *guardVerdict) (applied bool) { |
| + if !verdictWouldStand(st, v.block) { |
| + return false |
| + } |
| + st.verdict = v |
| + return true |
| +} |
| + |
| +// verdictWouldStand is decideVerdict's rule on its own, so a caller can skip |
| +// building a verdict that would not stand. |
| +func verdictWouldStand(st *guardState, block bool) bool { |
| + cur := st.verdict |
| + return cur == nil || (!cur.block && block) |
| +} |
| + |
| +// guardDecide offers hit as r's verdict and, when it stands and blocks, |
| // answers r with the block page and reports true: the caller must then stop |
| -// serving. It does nothing when the guard is not running for r, or when a |
| -// verdict is already noted, so a request is decided once however many |
| -// places check it. |
| +// serving. It does nothing when the guard is not running for r, or when |
| +// decideVerdict keeps the verdict already noted, so however many places |
| +// check a request, it is decided by one rule. |
| func guardDecide(w http.ResponseWriter, r *http.Request, hit edgeguard.Hit) (served bool) { |
| out := outcomeFrom(r) |
| - if out == nil || out.guard == nil || out.guard.verdict != nil || hit.Rule == nil { |
| + if out == nil || out.guard == nil || hit.Rule == nil { |
| return false |
| } |
| st := out.guard |
| - v := &guardVerdict{rule: hit.Rule} |
| + block := st.blocks(hit.Rule) |
| + if !verdictWouldStand(st, block) { |
| + return false |
| + } |
| + v := &guardVerdict{rule: hit.Rule, block: block} |
| if hit.FromQuery { |
| v.frag, _ = reqrec.Fragment(reqrec.SourceQuery, hit.QueryName, hit.Fragment) |
| } else { |
| v.frag, _ = reqrec.Fragment(reqrec.SourcePath, "", hit.Fragment) |
| } |
| - st.verdict = v |
| - if !st.mode.blocks(hit.Rule) { |
| + if !decideVerdict(st, v) || !block { |
| return false |
| } |
| - v.block = true |
| v.ref = st.mint(hit.Rule.Tier, hit.Rule.ID) |
| writeGuardBlock(w, v.ref) |
| return true |
| } |
| +// burstDecide offers the burst rule as r's verdict for a catalogue request |
| +// from a client cooling until until, from naming where the cool-down started. |
| +// When it stands and blocks it answers r with the refusal and reports true. |
| +// It blocks only when the mode blocks the burst rule, the app is not record |
| +// only, and the app is not a fleet's: the hub cannot see what a fleet box |
| +// serves, so it cannot tell a real fleet page from a missing one, and only |
| +// records it. |
| +func burstDecide(w http.ResponseWriter, r *http.Request, until time.Time, from string, fleet bool) (served bool) { |
| + out := outcomeFrom(r) |
| + if out == nil || out.guard == nil { |
| + return false |
| + } |
| + st := out.guard |
| + rule := edgeguard.BurstRule |
| + v := &guardVerdict{rule: rule, block: !fleet && st.blocks(rule), until: until, from: from} |
| + if !decideVerdict(st, v) || !v.block { |
| + return false |
| + } |
| + v.ref = st.mint(rule.Tier, rule.ID) |
| + now := time.Now |
| + if st.burst != nil { |
| + now = st.burst.now |
| + } |
| + writeBurstRefusal(w, v.ref, until.Sub(now())) |
| + return true |
| +} |
| + |
| +// burstAppKey is the probe-burst limiter's key for rt's app: counting is per |
| +// app, and a cool-down remembers the app that tripped it so a record can say |
| +// whether it was this one. |
| +func burstAppKey(rt registry.Route) string { |
| + return burstAppKeyOf(release.RouteAccount(rt), rt.App) |
| +} |
| + |
| +func burstAppKeyOf(acct, app string) string { return acct + "/" + app } |
| + |
| +// burstNotFound reports whether a response counts toward the probe-burst |
| +// limit: a 404, or a hard or probe match whatever the answer. A match on a |
| +// burst-mode rule (an admin page) counts only as a 404, since real admins |
| +// open those pages. |
| +func burstNotFound(status int, v *guardVerdict) bool { |
| + if status == http.StatusNotFound { |
| + return true |
| + } |
| + if v == nil || v.rule.Mode == edgeguard.ModeBurst { |
| + return false |
| + } |
| + return v.rule.Tier == reqrec.TierHard || v.rule.Tier == reqrec.TierProbe |
| +} |
| + |
| +// noteBurst counts one answered request toward the probe-burst limit, from |
| +// the observer defer of the box that saw the visitor's own headers: a |
| +// request the guard ran for, that no browser sent (every current browser |
| +// sends Sec-Fetch-Mode on every request, scanners do not), and that is a |
| +// not-found by burstNotFound. A request that arrived as a far edge's asset |
| +// fill is the far edge's to count. On a trip it mints the trip's code once, |
| +// files the trip record and tells the other edges. |
| +func (e *Edge) noteBurst(rt registry.Route, r *http.Request, status int, out *outcome) { |
| + if e.burst == nil || out == nil || out.guard == nil || out.assetFill { |
| + return |
| + } |
| + if status == 0 { |
| + status = http.StatusOK // nothing written: net/http answers 200 |
| + } |
| + if !burstNotFound(status, out.guard.verdict) { |
| + return |
| + } |
| + if _, browser := r.Header["Sec-Fetch-Mode"]; browser { |
| + return |
| + } |
| + client, ok := ratelimit.ClientKey(clientIP(r)) |
| + if !ok { |
| + return |
| + } |
| + tripped, until := e.burst.note(burstAppKey(rt), client) |
| + if !tripped { |
| + return |
| + } |
| + ref := e.mintRef(reqrec.TierBurst, edgeguard.BurstRule.ID) |
| + if rec := e.requestRecords.Load(); rec != nil { |
| + rec.Trip(reqrec.Trip{Response: requestResponse(rt, r, status), Until: until, Ref: ref}) |
| + } |
| + e.sendBurstNotices(client, until, ref) |
| +} |
| + |
| +// sendBurstNotices tells the platform's other edges that client tripped |
| +// here, so they apply the same cool-down. Task 4 of the probe-burst plan |
| +// fills it in; until then a trip stays on this box. |
| +func (e *Edge) sendBurstNotices(client netip.Prefix, until time.Time, ref string) {} |
| + |
| // writeGuardBlock writes the block page: a plain 404 that says no more than |
| // a missing page would, with the reference code in a header and in the |
| // body, so the visitor can pass it to the site's owner. It is never cached: |
diff --git a/internal/edge/reqrecords.go b/internal/edge/reqrecords.go| index 4a9d5a812..d30585f56 100644 |
| --- a/internal/edge/reqrecords.go |
| +++ b/internal/edge/reqrecords.go |
| @@ -10,12 +10,14 @@ import ( |
| ) |
| // RequestRecorder is where the edge files request records: one Response per |
| -// response the observer defer sees, and one Match per request a protection |
| -// rule blocked or watched. reqrec.Recorder satisfies it; the interface keeps |
| -// the edge's dependency on the contract, as AnalyticsMeter does. |
| +// response the observer defer sees, one Match per request a protection rule |
| +// blocked or watched, and one Trip per client that trips the probe-burst |
| +// limit. reqrec.Recorder satisfies it; the interface keeps the edge's |
| +// dependency on the contract, as AnalyticsMeter does. |
| type RequestRecorder interface { |
| Response(reqrec.Response) |
| Match(reqrec.Match) |
| + Trip(reqrec.Trip) |
| } |
| type requestRecorderRef struct{ RequestRecorder } |
| @@ -85,7 +87,8 @@ func (e *Edge) observeRecords(rt registry.Route, viaTunnel bool, r *http.Request |
| // it woke is known exactly as for a plain response. |
| x.WokeKnown, x.Woke = !viaTunnel, out.woke |
| } |
| - ref.Match(reqrec.Match{Response: x, Kind: kind, Tier: v.rule.Tier, RuleID: v.rule.ID, Fragment: v.frag, Ref: v.ref}) |
| + ref.Match(reqrec.Match{Response: x, Kind: kind, Tier: v.rule.Tier, RuleID: v.rule.ID, Fragment: v.frag, Ref: v.ref, |
| + CooldownFrom: v.from, CooldownUntil: v.until}) |
| return |
| } |
| x.WokeKnown = !viaTunnel |
diff --git a/internal/edge/reqrecords_test.go b/internal/edge/reqrecords_test.go| index 3ff1860bd..a0f136d42 100644 |
| --- a/internal/edge/reqrecords_test.go |
| +++ b/internal/edge/reqrecords_test.go |
| @@ -13,6 +13,7 @@ import ( |
| type memRecorder struct { |
| resp []reqrec.Response |
| match []reqrec.Match |
| + trips []reqrec.Trip |
| } |
| func (m *memRecorder) Response(x reqrec.Response) { m.resp = append(m.resp, x) } |
diff --git a/internal/edge/static.go b/internal/edge/static.go| index 8b91f7da5..4cc913849 100644 |
| --- a/internal/edge/static.go |
| +++ b/internal/edge/static.go |
| @@ -578,6 +578,14 @@ func (s *staticSite) serveTree(tree servedTree, w http.ResponseWriter, r *http.R |
| // below, once its target is known. |
| if guard && !found && !tree.redirects.names(requestHost(r.Host), p) { |
| probe, _ = edgeguard.CheckTier(r.URL.Path, r.URL.RawQuery, reqrec.TierProbe) |
| + // The probe-burst cool-down refuses a catalogue path only |
| + // where the site is not known to have it, which is this |
| + // point. A hard-tier hit on the request path was offered in |
| + // ServeHTTP already: the hard tier refuses even a file that |
| + // is there. |
| + if probe.Rule != nil && staticBurstDecide(w, r) { |
| + return |
| + } |
| } |
| act, ok := tree.redirects.resolve(requestHost(r.Host), p, r.URL.Path, r.URL.RawQuery, found) |
| if ok && act.location == "" { |
| @@ -654,13 +662,24 @@ func (s *staticSite) serveTree(tree servedTree, w http.ResponseWriter, r *http.R |
| } |
| } |
| -// staticGuardPending reports whether the guard runs for r and has not yet |
| -// decided it. Otherwise serveTree checks nothing, the matcher and the |
| -// _redirects lookup included, so a request is decided once however many |
| -// places could check it. |
| +// staticGuardPending reports whether the guard runs for r and a check here |
| +// could still change its verdict: there is none yet, or the one there does |
| +// not block, which a block found here replaces (decideVerdict). A burst |
| +// watch on the request path must not spare a rewrite onto a hard-tier file. |
| +// Otherwise serveTree checks nothing, the matcher and the _redirects lookup |
| +// included. |
| func staticGuardPending(r *http.Request) bool { |
| out := outcomeFrom(r) |
| - return out != nil && out.guard != nil && out.guard.verdict == nil |
| + return out != nil && out.guard != nil && (out.guard.verdict == nil || !out.guard.verdict.block) |
| +} |
| + |
| +// staticBurstDecide offers the burst rule for a catalogue path the site does |
| +// not have, when r's client is cooling. A static route this box serves is |
| +// never a fleet's. |
| +func staticBurstDecide(w http.ResponseWriter, r *http.Request) bool { |
| + st := outcomeFrom(r).guard |
| + until, from, ok := st.cooling(r) |
| + return ok && burstDecide(w, r, until, from, false) |
| } |
| // serveFile sends the tree file at fp, whose tree path is p (for logs). A 200 |
diff --git a/internal/edgeguard/catalogue.go b/internal/edgeguard/catalogue.go| index c3ff397f2..e6070930f 100644 |
| --- a/internal/edgeguard/catalogue.go |
| +++ b/internal/edgeguard/catalogue.go |
| @@ -111,6 +111,16 @@ var ( |
| idx index |
| ) |
| +// BurstRule is the verdict the edge gives a catalogue request from a client |
| +// in a probe-burst cool-down. It is not a catalogue rule: no path matches |
| +// it, because the cool-down is about the client, and the edge decides it |
| +// beside Check rather than through it. It is here so a record or a |
| +// reference code that names it is explained like any other rule (RuleByID, |
| +// RuleByHash). Its mode is watch until blocking is approved. |
| +var BurstRule = &Rule{ID: reqrec.BurstRuleID, Group: "probe-burst", Tier: reqrec.TierBurst, Mode: ModeWatch} |
| + |
| +var burstRuleHash = reqrec.RuleHash(BurstRule.ID) |
| + |
| func init() { |
| rs, v, err := parseCatalogue(catalogueData) |
| if err != nil { |
| @@ -123,6 +133,10 @@ func init() { |
| if err != nil { |
| panic(err) |
| } |
| + // A code carries only the rule's hash, so the burst rule's must be its own. |
| + if i, ok := ix.byHash[burstRuleHash]; ok { |
| + panic(fmt.Sprintf("edgeguard catalogue: rule %s has the burst rule's hash", rs[i].ID)) |
| + } |
| rules, idx = rs, ix |
| } |
| @@ -135,6 +149,9 @@ func Rules() []Rule { return slices.Clone(rules) } |
| func RuleByHash(h uint32) (*Rule, bool) { |
| i, ok := idx.byHash[h] |
| if !ok { |
| + if h == burstRuleHash { |
| + return BurstRule, true |
| + } |
| return nil, false |
| } |
| return &rules[i], true |
diff --git a/internal/edgeguard/catalogue_test.go b/internal/edgeguard/catalogue_test.go| index cdcf99e58..792703b1d 100644 |
| --- a/internal/edgeguard/catalogue_test.go |
| +++ b/internal/edgeguard/catalogue_test.go |
| @@ -149,3 +149,34 @@ func TestParseAccepts(t *testing.T) { |
| t.Fatalf("got version %d, rules %+v", v, rs) |
| } |
| } |
| + |
| +// The probe-burst cool-down rule is the edge's, not the catalogue's: a |
| +// reference code or a record naming it finds it like any rule, but no path |
| +// ever matches it, because a cool-down is about the client, not the request. |
| +func TestBurstRuleLookups(t *testing.T) { |
| + r := BurstRule |
| + if r.ID != "burst.probe-burst.cooldown" || r.Group != "probe-burst" || r.Tier != reqrec.TierBurst || r.Mode != ModeWatch { |
| + t.Fatalf("BurstRule = %+v", *r) |
| + } |
| + if got, ok := RuleByID(r.ID); !ok || got != r { |
| + t.Fatalf("RuleByID(%q) = %v, %v; want BurstRule", r.ID, got, ok) |
| + } |
| + if got, ok := RuleByHash(reqrec.RuleHash(r.ID)); !ok || got != r { |
| + t.Fatalf("RuleByHash = %v, %v; want BurstRule", got, ok) |
| + } |
| + for _, rule := range Rules() { |
| + if rule.ID == r.ID || rule.Tier == reqrec.TierBurst { |
| + t.Fatalf("the catalogue holds %+v; the burst rule is not a catalogue rule", rule) |
| + } |
| + } |
| + for _, p := range []string{"/", "/burst", "/probe-burst/cooldown", "/burst.probe-burst.cooldown", "/.env", "/wp-login.php", "/admin"} { |
| + if h, ok := Check(p, "q=burst.probe-burst.cooldown"); ok && h.Rule == r { |
| + t.Fatalf("Check(%q) returned the burst rule", p) |
| + } |
| + for _, tier := range []reqrec.Tier{reqrec.TierHard, reqrec.TierProbe, reqrec.TierBurst} { |
| + if h, ok := CheckTier(p, "", tier); ok && h.Rule == r { |
| + t.Fatalf("CheckTier(%q, %v) returned the burst rule", p, tier) |
| + } |
| + } |
| + } |
| +} |
diff --git a/internal/reqrec/recorder.go b/internal/reqrec/recorder.go| index e12bc910d..be4f97346 100644 |
| --- a/internal/reqrec/recorder.go |
| +++ b/internal/reqrec/recorder.go |
| @@ -29,6 +29,9 @@ const ( |
| KindBlock Kind = "block" |
| KindWatch Kind = "watch" |
| KindMinute Kind = "minute" |
| + // KindTrip is the record of a client tripping the probe-burst limit, |
| + // filed beside the record of the request that tripped it. |
| + KindTrip Kind = "trip" |
| ) |
| // Per app and minute, at most this many records of each class are written. The |
| @@ -40,6 +43,7 @@ const ( |
| NotFoundPerMin = 60 |
| BlockPerMin = 300 |
| WatchPerMin = 300 |
| + TripPerMin = 10 |
| ) |
| // methods are the request methods a record names. Anything else is stored as |
| @@ -113,6 +117,26 @@ type Match struct { |
| // Fragment arrives already passed through Fragment by the caller. |
| Fragment string |
| Ref string |
| + // CooldownFrom and CooldownUntil describe the probe-burst cool-down |
| + // behind a match of tier burst: where it started (CooldownFromThisApp or |
| + // CooldownFromOtherApp, never the other app's name) and when it ends. |
| + // They are written only for that tier. |
| + CooldownFrom string |
| + CooldownUntil time.Time |
| +} |
| + |
| +// Where a probe-burst cool-down started, as a burst match says it. |
| +const ( |
| + CooldownFromThisApp = "this app" |
| + CooldownFromOtherApp = "another app on the platform" |
| +) |
| + |
| +// Trip is a client tripping the probe-burst limit on the request in |
| +// Response. Until is when its cool-down ends; Ref is the trip's own code. |
| +type Trip struct { |
| + Response |
| + Until time.Time |
| + Ref string |
| } |
| type minuteKey struct { |
| @@ -126,6 +150,7 @@ type minuteCounts struct { |
| block, watch int |
| methods [len(methodCounters)]int |
| notFoundRecs, blockRecs, watchRecs int |
| + tripRecs int |
| droppedNotFound, droppedBlock, droppedWatch int |
| } |
| @@ -329,6 +354,12 @@ func (r *Recorder) Match(m Match) { |
| // controls; escaping again here keeps that true at the record boundary |
| // whatever a caller did, and costs nothing on text that has none. |
| set(f, "frag", truncate(escapeControls(strings.ToValidUTF8(m.Fragment, "\ufffd")), MaxFragment)) |
| + if m.Tier == TierBurst { |
| + set(f, "cooldown_from", m.CooldownFrom) |
| + if !m.CooldownUntil.IsZero() { |
| + f["cooldown_until"] = m.CooldownUntil.UTC().Format(time.RFC3339) |
| + } |
| + } |
| level := "info" |
| if m.Kind == KindBlock { |
| level = "warn" |
| @@ -337,6 +368,39 @@ func (r *Recorder) Match(m Match) { |
| string(m.Kind)+" "+m.Tier.String()+" "+m.RuleID+" "+f["method"]+" "+f["path"], f) |
| } |
| +// Trip writes the record of a probe-burst trip, at most TripPerMin per app |
| +// and minute. The request that tripped has its own record already (a Match |
| +// or a not-found), so a trip counts toward no status or method: it is an |
| +// event about the client, not a second response. |
| +func (r *Recorder) Trip(t Trip) { |
| + if r == nil { |
| + return |
| + } |
| + r.stamp(&t.Response) |
| + r.mu.Lock() |
| + c := r.counts(t.Response) |
| + emit := c.tripRecs < TripPerMin |
| + if emit { |
| + c.tripRecs++ |
| + } |
| + r.mu.Unlock() |
| + if !emit { |
| + return |
| + } |
| + f := r.fields(t.Response, KindTrip) |
| + f["tier"] = TierBurst.String() |
| + f["rule"] = BurstRuleID |
| + set(f, "ref", t.Ref) |
| + until := t.Until.UTC().Format(time.RFC3339) |
| + f["cooldown_until"] = until |
| + r.sink.Edge(t.Acct, t.App, t.Host, "warn", "trip burst "+f["client"]+" until "+until, f) |
| +} |
| + |
| +// BurstRuleID is the probe-burst cool-down rule's ID (edgeguard.BurstRule, |
| +// which imports this package), so a trip record names the rule a burst |
| +// match names. |
| +const BurstRuleID = "burst.probe-burst.cooldown" |
| + |
| // fields builds the redacted record body shared by not-found and match records. |
| // Empty values are left out. Every request-derived string is bounded and has |
| // its controls escaped: the method is one of a few words, the path and query |
diff --git a/internal/reqrec/recorder_test.go b/internal/reqrec/recorder_test.go| index f5d66ac79..d3112f228 100644 |
| --- a/internal/reqrec/recorder_test.go |
| +++ b/internal/reqrec/recorder_test.go |
| @@ -482,3 +482,73 @@ func TestRecorderFragmentControlsEscaped(t *testing.T) { |
| t.Fatalf("frag %q path %q msg %q", f["frag"], f["path"], s.msgs[0]) |
| } |
| } |
| + |
| +// A trip is one record of its own, beside the request's own record: kind |
| +// trip, tier burst, the burst rule, the trip's code and when the cool-down |
| +// ends. At most TripPerMin are written per app and minute. A trip is not a |
| +// response, so it changes no status or method count. |
| +func TestTripRecordAndCap(t *testing.T) { |
| + now := time.Date(2026, 10, 31, 9, 4, 0, 0, time.UTC) |
| + until := now.Add(10 * time.Minute) |
| + s := &memSink{} |
| + r := NewRecorder(s, nil, func() time.Time { return now }) |
| + for i := 0; i < 25; i++ { |
| + r.Trip(Trip{Response: Response{Acct: "bdk", App: "shop", Host: "shop.example.com", Method: "GET", |
| + Path: "/wp-login.php", UA: "curl/8.7.1", ClientIP: "203.0.113.7", Status: 404}, Until: until, Ref: fmt.Sprintf("REF%d", i)}) |
| + } |
| + if len(s.recs) != TripPerMin || TripPerMin != 10 { |
| + t.Fatalf("%d trip records, want %d (TripPerMin = %d, want 10)", len(s.recs), 10, TripPerMin) |
| + } |
| + f := s.recs[0] |
| + want := map[string]string{"kind": "trip", "tier": "burst", "rule": "burst.probe-burst.cooldown", "ref": "REF0", |
| + "cooldown_until": until.Format(time.RFC3339), "client": "203.0.113.0/24", "path": "/wp-login.php", "status": "404"} |
| + for k, v := range want { |
| + if f[k] != v { |
| + t.Fatalf("field %s = %q, want %q (%v)", k, f[k], v, f) |
| + } |
| + } |
| + if s.msgs[0] != "trip burst 203.0.113.0/24 until "+until.Format(time.RFC3339) { |
| + t.Fatalf("msg %q", s.msgs[0]) |
| + } |
| + // The next minute has its own allowance. |
| + later := now.Add(time.Minute) |
| + r.Trip(Trip{Response: Response{Acct: "bdk", App: "shop", ClientIP: "203.0.113.7", Status: 404, When: later}, Until: until, Ref: "NEXT"}) |
| + if len(s.recs) != TripPerMin+1 { |
| + t.Fatalf("%d records, want the next minute's trip too", len(s.recs)) |
| + } |
| + // No status or method was counted for the trips. |
| + r.Flush(later.Add(2 * time.Minute)) |
| + for _, f := range s.recs { |
| + if f["kind"] == "minute" && (f["s404"] != "0" || f["m_get"] != "0") { |
| + t.Fatalf("a trip was counted as a response: %v", f) |
| + } |
| + } |
| +} |
| + |
| +// A burst match says where its cool-down came from and when it ends; no |
| +// other tier carries those fields. |
| +func TestBurstMatchCooldownFields(t *testing.T) { |
| + now := time.Date(2026, 10, 31, 9, 4, 0, 0, time.UTC) |
| + until := now.Add(7 * time.Minute) |
| + s := &memSink{} |
| + r := NewRecorder(s, nil, func() time.Time { return now }) |
| + base := Response{Acct: "bdk", App: "shop", Method: "GET", Path: "/wp-login.php", ClientIP: "203.0.113.7", Status: 429} |
| + r.Match(Match{Response: base, Kind: KindBlock, Tier: TierBurst, RuleID: "burst.probe-burst.cooldown", Ref: "R1", |
| + CooldownFrom: CooldownFromOtherApp, CooldownUntil: until}) |
| + r.Match(Match{Response: base, Kind: KindWatch, Tier: TierBurst, RuleID: "burst.probe-burst.cooldown", |
| + CooldownFrom: CooldownFromThisApp, CooldownUntil: until}) |
| + r.Match(Match{Response: base, Kind: KindWatch, Tier: TierProbe, RuleID: "probe.wordpress.wp-login", |
| + CooldownFrom: CooldownFromThisApp, CooldownUntil: until}) |
| + if len(s.recs) != 3 { |
| + t.Fatalf("%d records", len(s.recs)) |
| + } |
| + if f := s.recs[0]; f["cooldown_from"] != "another app on the platform" || f["cooldown_until"] != until.Format(time.RFC3339) || f["tier"] != "burst" { |
| + t.Fatalf("block: %v", f) |
| + } |
| + if f := s.recs[1]; f["cooldown_from"] != "this app" || f["cooldown_until"] != until.Format(time.RFC3339) { |
| + t.Fatalf("watch: %v", f) |
| + } |
| + if f := s.recs[2]; f["cooldown_from"] != "" || f["cooldown_until"] != "" { |
| + t.Fatalf("a probe match carried cool-down fields: %v", f) |
| + } |
| +} |