carlos / platform Public

console: per-app Protection tab and its JSON door

The Protection tab sits between Analytics and Activity: the last 7 or 30
UTC days of what the edge guard recorded and blocked for the app, read
through readEdgeDays scoped to the account and drawn with the Analytics
tab's range links, chart, share list and banners. No tallies says no
counts yet, never nothing caught; a read error says so alone. The JSON
door answers the same summary, or a 502.

Logs gain protection=1: an applog.Filter Keep predicate that keeps edge
watch and block records on non-burst catalogue rules (edgeguard.RuleByID),
applied inside the read before the collect cap. The tab links to it, and
the Logs form carries it on.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev 09a8291be4e5dfabfc9dfe15769beb23c721bc06 parent 3234f81
17 files changed, +872 −2
  • internal/applog/filter.go +8 −0
  • internal/applog/filter_test.go +2 −0
  • internal/console/apilogs.go +7 −0
  • internal/console/approved_protection_copy_test.go +9 −1
  • internal/console/perfwalk_test.go +1 −1
  • internal/console/protection.go +5 −0
  • internal/console/protectiongroups.go +39 −0
  • internal/console/protectionview.go +261 −0
  • internal/console/protectionview_test.go +426 −0
  • internal/console/server.go +12 −0
  • internal/console/templates/app_logs.html +13 −0
  • internal/console/templates/app_protection.html +52 −0
  • internal/console/templates/appnav.html +1 −0
  • internal/console/templates/layout.html +9 −0
  • internal/console/testdata/perf-budgets.txt +2 −0
  • internal/edgeguard/catalogue.go +11 −0
  • internal/edgeguard/catalogue_test.go +14 −0
diff --git a/internal/applog/filter.go b/internal/applog/filter.go
index a6eb235e2..2bbcbee4d 100644
--- a/internal/applog/filter.go
+++ b/internal/applog/filter.go
@@ -23,6 +23,11 @@ type Filter struct {
Level string
Grep *regexp.Regexp // matched against Msg
Fields map[string]string // every listed key must be present and equal
+ // Keep, when set, is one more test a record must pass: a predicate the
+ // fields above cannot say (the console's protection matches). Match
+ // runs it, so ReadWindow applies it inside the read, before any cap
+ // trims the window. It must be safe for concurrent use.
+ Keep func(Record) bool
}
// Match reports whether r survives f.
@@ -54,6 +59,9 @@ func (f Filter) Match(r Record) bool {
return false
}
}
+ if f.Keep != nil && !f.Keep(r) {
+ return false
+ }
return true
}
diff --git a/internal/applog/filter_test.go b/internal/applog/filter_test.go
index 4959c741c..3a09effc4 100644
--- a/internal/applog/filter_test.go
+++ b/internal/applog/filter_test.go
@@ -34,6 +34,8 @@ func TestFilterMatch(t *testing.T) {
{"field match", Filter{Fields: map[string]string{"request_id": "r1"}}, true},
{"field mismatch", Filter{Fields: map[string]string{"request_id": "r2"}}, false},
{"field absent", Filter{Fields: map[string]string{"user": "u"}}, false},
+ {"keep admits", Filter{Keep: func(r Record) bool { return r.Fields["request_id"] == "r1" }}, true},
+ {"keep refuses", Filter{Keep: func(Record) bool { return false }}, false},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
diff --git a/internal/console/apilogs.go b/internal/console/apilogs.go
index ae7d177e5..11200ce45 100644
--- a/internal/console/apilogs.go
+++ b/internal/console/apilogs.go
@@ -141,6 +141,13 @@ func logsFilterFromQuery(r *http.Request, now time.Time) (f applog.Filter, limit
}
f.Fields[k] = v
}
+ // protection=1 keeps the edge's protection matches only: the requests
+ // the Protection tab counts as caught (protectionLogRecord). It runs
+ // inside the read, so the collect cap and the limit apply to matches,
+ // never to the traffic around them.
+ if q.Get("protection") == "1" {
+ f.Keep = protectionLogRecord
+ }
limit = logsDefaultLimit
if v := q.Get("limit"); v != "" {
n, err := strconv.Atoi(v)
diff --git a/internal/console/approved_protection_copy_test.go b/internal/console/approved_protection_copy_test.go
index ffb7ec656..feffdb410 100644
--- a/internal/console/approved_protection_copy_test.go
+++ b/internal/console/approved_protection_copy_test.go
@@ -19,7 +19,15 @@ const protectionCopyDeckPath = "../../docs/superpowers/plans/2026-10-30-console-
// carry. The task that writes a row's text adds its id here in the same
// commit. From then on a "gate" row's new text must be in its file, and any
// other row's named test must exist.
-var protectionCopyBuilt = map[string]bool{}
+var protectionCopyBuilt = map[string]bool{
+ // Task 6: the per-app tab, its group names and the Logs filter.
+ "PT-C01": true, "PT-C02": true, "PT-C03": true, "PT-C04": true, "PT-C05": true, "PT-C06": true,
+ "PT-C10": true, "PT-C11": true, "PT-C12": true, "PT-C13": true, "PT-C14": true, "PT-C15": true,
+ "PT-C16": true, "PT-C17": true, "PT-C18": true, "PT-C19": true, "PT-C20": true, "PT-C21": true,
+ "PT-C22": true, "PT-C23": true, "PT-C24": true, "PT-C25": true, "PT-C26": true, "PT-C27": true,
+ "PT-C28": true, "PT-C29": true, "PT-C30": true, "PT-C31": true, "PT-C32": true, "PT-C33": true,
+ "PT-C34": true, "PT-C35": true, "PT-C36": true, "PT-C37": true,
+}
func parseProtectionCopyDeck(t *testing.T) []navCopyRow {
t.Helper()
diff --git a/internal/console/perfwalk_test.go b/internal/console/perfwalk_test.go
index c2bbe75a8..03a4c8fbd 100644
--- a/internal/console/perfwalk_test.go
+++ b/internal/console/perfwalk_test.go
@@ -515,7 +515,7 @@ func perfTargets(fx *consoleFixture) map[string][]perfTarget {
// GET /upgrade has no parameter but is gated the same way (billingpage.go).
m["GET /upgrade"] = []perfTarget{{Path: "/upgrade", Expect: http.StatusNotFound}}
for _, tab := range []string{"account-review", "activity", "analytics", "availability", "errors",
- "instances", "logs", "logs/data", "settings"} {
+ "instances", "logs", "logs/data", "protection", "protection/data", "settings"} {
m["GET /a/{sqid}/apps/{app}/"+tab] = ok(app + "/" + tab)
}
// The live door (analyticslive.go): the tab's numbers part and the
diff --git a/internal/console/protection.go b/internal/console/protection.go
index 1d8b1485b..c9a62379e 100644
--- a/internal/console/protection.go
+++ b/internal/console/protection.go
@@ -15,6 +15,11 @@ import (
// partly counted or when counting began, so none of its fields can be read
// as one.
+// protectionReadErr is what the Protection tab says when the edge days could
+// not be read (PT-C18). It stands alone: a failed read shows no headline and
+// no zeros.
+const protectionReadErr = "Protection counts could not be read just now. Try again in a moment."
+
// protectionDay is one UTC date's counts.
type protectionDay struct {
Date string `json:"date"`
diff --git a/internal/console/protectiongroups.go b/internal/console/protectiongroups.go
new file mode 100644
index 000000000..8b1982483
--- /dev/null
+++ b/internal/console/protectiongroups.go
@@ -0,0 +1,39 @@
+package console
+
+// protectionGroupNames words the edge guard's catalogue groups for the
+// Protection tab's "What they were after" table. A tally keys its groups
+// "<tier>/<group>" (internal/edge/usagemeter.go), so a group that sits in
+// both tiers (dumps) has a name per tier. Every catalogue group has a name
+// here; TestEveryCatalogueGroupHasAName holds that true as the catalogue
+// grows. The text is the approved copy deck's (PT-C20 to PT-C35).
+var protectionGroupNames = map[string]string{
+ "hard/traversal": "Paths that try to climb out of the site's folder",
+ "hard/secrets": "Secret files such as .env and .git",
+ "hard/keys": "Private keys and cloud credentials",
+ "hard/dumps": "Database dumps",
+ "hard/source": "Editor and backup copies of PHP files",
+ "probe/admin": "Admin pages",
+ "probe/cgi": "Old CGI scripts and router pages",
+ "probe/devconfig": "Docker and CI config files",
+ "probe/dumps": "Backup and dump files",
+ "probe/java": "Java server pages and consoles",
+ "probe/metadata": "Cloud server metadata",
+ "probe/phpframework": "PHP framework debug pages",
+ "probe/phpmyadmin": "phpMyAdmin",
+ "probe/php": "PHP scripts",
+ "probe/status": "Server status pages",
+ "probe/wordpress": "WordPress logins and admin pages",
+}
+
+// protectionOtherGroup is the name of every group the table has no name
+// for: one a newer edge counts under a group this console does not know
+// (PT-C36).
+const protectionOtherGroup = "Other"
+
+// protectionGroupName is a tally group's name, or "Other" for one with none.
+func protectionGroupName(key string) string {
+ if name, ok := protectionGroupNames[key]; ok {
+ return name
+ }
+ return protectionOtherGroup
+}
diff --git a/internal/console/protectionview.go b/internal/console/protectionview.go
new file mode 100644
index 000000000..7b388edc7
--- /dev/null
+++ b/internal/console/protectionview.go
@@ -0,0 +1,261 @@
+package console
+
+// The per-app Protection tab and its JSON door: what the edge guard looked
+// at, recorded and blocked for one app over the last 7 or 30 whole UTC days.
+// Both read the edge days through readEdgeDays, scoped to the account, so
+// only its own fleets are touched, and sum them with sumProtection. The
+// page is built from the Analytics tab's parts (its range links, chart,
+// share lists and banners); the words are the approved copy deck's
+// (docs/superpowers/plans/2026-10-30-console-protection-tab-copy.md).
+
+import (
+ "context"
+ "errors"
+ "log"
+ "math"
+ "net/http"
+ "net/url"
+ "strconv"
+ "strings"
+ "time"
+
+ "github.com/carlosframework/platform/internal/analytics"
+ "github.com/carlosframework/platform/internal/applog"
+ "github.com/carlosframework/platform/internal/edgeguard"
+ "github.com/carlosframework/platform/internal/reqrec"
+)
+
+// protectionLogsKeep is how far back Logs reach (the logs keep 7 days), so
+// the tab's link to the requests behind its counts starts no earlier.
+const protectionLogsKeep = 168 * time.Hour
+
+// protectionView is the tab's page: Err set means the read failed and the
+// page says only that. Otherwise Sum is the window's counts, and the rest is
+// how the template draws them.
+type protectionView struct {
+ Range string // "7d" | "30d"
+ Days int
+ Err string
+ Sum protectionSummary
+ // Caught is everything recorded or blocked, and Share its part of what
+ // was checked, worded so it never reads 0%.
+ Caught int64
+ Share string
+ Chart *protectionChart
+ Groups []shareRow
+ // LogsURL opens Logs filtered to the same requests the counts cover.
+ LogsURL string
+}
+
+// protectionRange reads the tab's range: 30d, or 7d for anything else. A
+// page never 400s over its own query string, as handleAppAnalytics.
+func protectionRange(q url.Values) (string, int) {
+ if q.Get("range") == "30d" {
+ return "30d", 30
+ }
+ return "7d", 7
+}
+
+// readProtection is acct's app's counts over the last days whole UTC days,
+// read under instanceStoreTimeout. Any read error fails it: a short total
+// must never look complete.
+func (s *Server) readProtection(ctx context.Context, sqid, app string, dates []string, now time.Time) (protectionSummary, error) {
+ if s.cfg.Releases == nil {
+ return protectionSummary{}, errors.New("no bucket")
+ }
+ ctx, cancel := context.WithTimeout(ctx, instanceStoreTimeout)
+ defer cancel()
+ srcs, _, err := s.readEdgeDays(ctx, s.usageDayReader(now), dates, sqid)
+ if err != nil {
+ return protectionSummary{}, err
+ }
+ return sumProtection(srcs, dates, sqid, app), nil
+}
+
+// handleAppProtection renders the Protection tab. Access is the Analytics
+// tab's: appPage's member gate and byte-identical 404.
+func (s *Server) handleAppProtection(w http.ResponseWriter, r *http.Request) {
+ p, acct, ok := s.appPage(w, r, "protection")
+ if !ok {
+ return
+ }
+ now := time.Now()
+ rng, days := protectionRange(r.URL.Query())
+ v := &protectionView{Range: rng, Days: days}
+ dates := protectionDates(days, now)
+ sum, err := s.readProtection(r.Context(), acct.Sqid, p.AppName, dates, now)
+ if err != nil {
+ log.Printf("console: app protection %s/%s: %v", acct.Sqid, p.AppName, err)
+ v.Err = protectionReadErr
+ } else {
+ v.Sum = sum
+ v.Caught = sum.Watch + sum.Block
+ if sum.Checked > 0 && v.Caught > 0 {
+ v.Share = protectionShare(v.Caught, sum.Checked)
+ }
+ v.Chart = buildProtectionChart(sum.Days, now)
+ v.Groups = shareRows(protectionGroups(sum.Groups), protectionGroupLabel)
+ v.LogsURL = protectionLogsURL(p.Nav, p.AppName, dates, now)
+ }
+ p.Protection = v
+ s.render(w, http.StatusOK, "app_protection", p)
+}
+
+// handleAppProtectionData is the tab's JSON door: the same summary, groups
+// keyed as the tallies key them. Same gate as the page; a failed read is a
+// 502, never zeros.
+func (s *Server) handleAppProtectionData(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Cache-Control", "no-store")
+ _, _, acct, _, app, ok := s.accountApp(w, r)
+ if !ok {
+ return
+ }
+ now := time.Now()
+ _, days := protectionRange(r.URL.Query())
+ sum, err := s.readProtection(r.Context(), acct.Sqid, app, protectionDates(days, now), now)
+ if err != nil {
+ log.Printf("console: app protection data %s/%s: %v", acct.Sqid, app, err)
+ jsonError(w, http.StatusBadGateway, "could not read the protection counts")
+ return
+ }
+ writeJSON(w, http.StatusOK, sum)
+}
+
+// protectionShare is caught as a whole percentage of checked. A share below
+// one percent says "under 1%" rather than rounding to nothing, and a share
+// short of all of them never rounds up to 100%.
+func protectionShare(caught, checked int64) string {
+ p := float64(caught) / float64(checked) * 100
+ if p < 1 {
+ return "under 1%"
+ }
+ n := int64(math.Round(p))
+ if n >= 100 && caught < checked {
+ n = 99
+ }
+ return strconv.FormatInt(n, 10) + "%"
+}
+
+// protectionGroups folds every group key the tab has no name for into one
+// "Other" row, kept under analytics.OtherKey so sortedKV pins it last. A
+// group with nothing in it is no row.
+func protectionGroups(groups map[string]int64) map[string]int64 {
+ out := make(map[string]int64, len(groups))
+ for k, n := range groups {
+ if n <= 0 {
+ continue
+ }
+ if _, named := protectionGroupNames[k]; !named {
+ k = analytics.OtherKey
+ }
+ out[k] += n
+ }
+ return out
+}
+
+// protectionGroupLabel words a groups row; "Other" is muted, as the
+// Analytics tab's overflow rows are.
+func protectionGroupLabel(k string) (string, string, bool) {
+ if k == analytics.OtherKey {
+ return protectionOtherGroup, "", true
+ }
+ return protectionGroupName(k), "", false
+}
+
+// protectionLogsURL opens the app's Logs at the edge records the counts
+// cover: watch and block matches on rules that act on a single request
+// (protection=1), from the window's first midnight, or from as far back as
+// Logs keep when that is later.
+func protectionLogsURL(nav, app string, dates []string, now time.Time) string {
+ since := now.UTC().Add(-protectionLogsKeep)
+ if len(dates) > 0 {
+ if first, err := time.Parse("2006-01-02", dates[0]); err == nil && first.After(since) {
+ since = first
+ }
+ }
+ return nav + "/apps/" + url.PathEscape(app) + "/logs?stream=" + applog.StreamEdge +
+ "&protection=1&since=" + url.QueryEscape(since.Format(time.RFC3339))
+}
+
+// protectionLogRecord reports whether rec is one of the requests the tab
+// counts as caught: an edge record of a watch or block match on a catalogue
+// rule that acts on a single request. Burst rules (admin pages) are checked
+// but never caught, so their records are not the tab's. Only the edge
+// stream counts: an app's own output can carry any fields it likes.
+func protectionLogRecord(rec applog.Record) bool {
+ if rec.Stream != applog.StreamEdge {
+ return false
+ }
+ if k := rec.Fields["kind"]; k != string(reqrec.KindWatch) && k != string(reqrec.KindBlock) {
+ return false
+ }
+ rule, ok := edgeguard.RuleByID(rec.Fields["rule"])
+ return ok && rule.Mode != edgeguard.ModeBurst
+}
+
+// protectionChart is the tab's day bars, laid out for the Analytics tab's
+// chart markup: one column per day, its bar what was caught that day, the
+// blocked part at its foot.
+type protectionChart struct {
+ Cols []protectionCol
+ Ticks []chartTick
+ XLabels []chartXLabel
+}
+
+// N is the column count, for the grid template.
+func (c *protectionChart) N() int { return len(c.Cols) }
+
+// protectionCol is one day. HPct is the bar's height against the axis top;
+// BlockPct the blocked part's height within the bar.
+type protectionCol struct {
+ When string
+ Lines []string
+ Label string
+ HPct float64
+ BlockPct float64
+ Partial bool // today: still being counted
+ Edge string
+}
+
+// buildProtectionChart lays out days. A window with nothing caught returns
+// nil: the page draws no flat line.
+func buildProtectionChart(days []protectionDay, now time.Time) *protectionChart {
+ today := now.UTC().Format("2006-01-02")
+ var c protectionChart
+ var peak int64
+ axis := make([]analytics.DaySummary, len(days))
+ for i, d := range days {
+ axis[i].Date = d.Date
+ if n := d.Watch + d.Block; n > peak {
+ peak = n
+ }
+ }
+ if peak == 0 {
+ return nil
+ }
+ top := niceCeil(peak)
+ for i, d := range days {
+ col := protectionCol{When: longDay(d.Date), Partial: d.Date == today}
+ col.Lines = []string{groupedCount(d.Block) + " blocked", groupedCount(d.Watch) + " recorded"}
+ if n := d.Watch + d.Block; n > 0 {
+ col.HPct = round2(float64(n) / float64(top) * 100)
+ col.BlockPct = round2(float64(d.Block) / float64(n) * 100)
+ }
+ col.Label = col.When + ": " + strings.Join(col.Lines, ", ")
+ // As the Analytics chart: the outer columns anchor their tooltip
+ // to their own side, so it never spills off the chart.
+ switch n := len(days); {
+ case i < n/6:
+ col.Edge = "start"
+ case i >= n-n/6:
+ col.Edge = "end"
+ }
+ c.Cols = append(c.Cols, col)
+ }
+ c.XLabels = dayXLabels(axis)
+ c.Ticks = []chartTick{{Pct: 0, Label: "0"}, {Pct: 100, Label: compactCount(top)}}
+ if top%2 == 0 {
+ c.Ticks = []chartTick{c.Ticks[0], {Pct: 50, Label: compactCount(top / 2)}, c.Ticks[1]}
+ }
+ return &c
+}
diff --git a/internal/console/protectionview_test.go b/internal/console/protectionview_test.go
new file mode 100644
index 000000000..e58d84cba
--- /dev/null
+++ b/internal/console/protectionview_test.go
@@ -0,0 +1,426 @@
+package console
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "html"
+ "net/http"
+ "net/url"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/applog"
+ "github.com/carlosframework/platform/internal/edgeguard"
+ "github.com/carlosframework/platform/internal/release"
+ "github.com/carlosframework/platform/internal/usage"
+)
+
+const ptHost = "shop.example.com"
+
+// ptFixture is a console whose ops account (bab) has the app shop, and
+// paul, its owner, signed in.
+func ptFixture(t *testing.T) (*consoleFixture, *http.Client) {
+ t.Helper()
+ fx := newConsoleFixture(t)
+ if _, err := fx.st.CreateAppIn(OpsAccountID, "shop", "paul@keymail.dev", time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ fx.setUser("paul@keymail.dev")
+ return fx, signInPaul(t, fx)
+}
+
+// ptSeed writes shop's guard tally for today into root box box-a's day,
+// through the edge's own writer, beside a traffic row.
+func ptSeed(t *testing.T, fx *consoleFixture, checked, watch, block int64, groups map[string]int64) {
+ t.Helper()
+ f := usage.EdgeFlush{
+ Rows: map[string]usage.EdgeRow{ptHost: {Account: release.OpsAccount, App: "shop", Requests: checked + 10}},
+ Guard: map[string]usage.GuardDelta{usage.GuardKey(ptHost, release.OpsAccount, "shop"): {
+ Host: ptHost, Account: release.OpsAccount, App: "shop", Checked: checked, Watch: watch, Block: block, Groups: groups,
+ }},
+ }
+ if err := usage.UpsertEdgeDay(context.Background(), fx.rel, "box-a", time.Now(), f); err != nil {
+ t.Fatal(err)
+ }
+}
+
+// ptCopy is a deck row's approved text with its placeholders filled.
+func ptCopy(t *testing.T, id string, fill map[string]string) string {
+ t.Helper()
+ for _, r := range parseProtectionCopyDeck(t) {
+ if r.ID != id {
+ continue
+ }
+ s := r.New
+ for k, v := range fill {
+ s = strings.ReplaceAll(s, "{"+k+"}", v)
+ }
+ if strings.Contains(s, "{") {
+ t.Fatalf("%s: unfilled placeholder in %q", id, s)
+ }
+ return s
+ }
+ t.Fatalf("no deck row %s", id)
+ return ""
+}
+
+// ptPage gets the tab at query and returns its text as a reader sees it:
+// entities decoded, runs of space folded.
+func ptPage(t *testing.T, fx *consoleFixture, c *http.Client, query string) string {
+ t.Helper()
+ status, _, body := get(t, c, fx.u("/apps/shop/protection"+query))
+ if status != http.StatusOK {
+ t.Fatalf("protection tab%s = %d: %s", query, status, body)
+ }
+ return navSpace(html.UnescapeString(body))
+}
+
+func ptWant(t *testing.T, page string, want ...string) {
+ t.Helper()
+ for _, w := range want {
+ if !strings.Contains(page, navSpace(w)) {
+ t.Errorf("page missing %q", w)
+ }
+ }
+}
+
+func ptRefuse(t *testing.T, page string, refuse ...string) {
+ t.Helper()
+ for _, r := range refuse {
+ if strings.Contains(page, navSpace(r)) {
+ t.Errorf("page shows %q", r)
+ }
+ }
+}
+
+// The headline every caught-something page opens with: no deck row's
+// placeholder-free lead, so a test can say "no headline".
+const ptHeadlineLead = "In the last "
+
+func TestProtectionTabRendersHeadline(t *testing.T) {
+ fx, c := ptFixture(t)
+ ptSeed(t, fx, 150, 8, 0, map[string]int64{"probe/wordpress": 6, "hard/secrets": 2})
+
+ page := ptPage(t, fx, c, "")
+ ptWant(t, page,
+ ptCopy(t, "PT-C02", map[string]string{"days": "7", "caught": "8"}),
+ ptCopy(t, "PT-C05", map[string]string{"pct": "5%", "checked": "150"}),
+ ptCopy(t, "PT-C11", nil), ptCopy(t, "PT-C12", nil), ptCopy(t, "PT-C13", nil),
+ ptCopy(t, "PT-C14", nil), ptCopy(t, "PT-C15", nil),
+ ptCopy(t, "PT-C16", nil), ptCopy(t, "PT-C17", nil),
+ protectionGroupName("probe/wordpress"), protectionGroupName("hard/secrets"),
+ "/apps/shop/logs?stream=edge&protection=1&since=",
+ )
+ // Largest group first.
+ if i, j := strings.Index(page, protectionGroupName("probe/wordpress")), strings.Index(page, protectionGroupName("hard/secrets")); i > j {
+ t.Error("the groups table is not largest first")
+ }
+ ptRefuse(t, page, ptCopy(t, "PT-C19", nil), ptCopy(t, "PT-C10", nil), ptCopy(t, "PT-C18", nil))
+
+ // The 30-day view says 30 and notes that Logs keep 7 days.
+ page = ptPage(t, fx, c, "?range=30d")
+ ptWant(t, page,
+ ptCopy(t, "PT-C02", map[string]string{"days": "30", "caught": "8"}),
+ ptCopy(t, "PT-C19", nil))
+
+ // A page never 400s over its query: an unknown range is 7 days.
+ page = ptPage(t, fx, c, "?range=bogus")
+ ptWant(t, page, ptCopy(t, "PT-C02", map[string]string{"days": "7", "caught": "8"}))
+}
+
+func TestProtectionTabBlockingHeadline(t *testing.T) {
+ fx, c := ptFixture(t)
+ ptSeed(t, fx, 400, 0, 3, map[string]int64{"hard/secrets": 3})
+ page := ptPage(t, fx, c, "")
+ ptWant(t, page,
+ ptCopy(t, "PT-C03", map[string]string{"days": "7", "blocked": "3"}),
+ ptCopy(t, "PT-C05", map[string]string{"pct": "under 1%", "checked": "400"}))
+ ptRefuse(t, page, "looked like attacks", "and recorded")
+}
+
+func TestProtectionTabMixedHeadline(t *testing.T) {
+ fx, c := ptFixture(t)
+ ptSeed(t, fx, 1284, 5, 2, map[string]int64{"hard/secrets": 2, "probe/php": 5})
+ page := ptPage(t, fx, c, "")
+ ptWant(t, page,
+ ptCopy(t, "PT-C04", map[string]string{"days": "7", "blocked": "2", "watched": "5"}),
+ ptCopy(t, "PT-C05", map[string]string{"pct": "under 1%", "checked": "1,284"}))
+ ptRefuse(t, page, "looked like attacks")
+}
+
+// Traffic with no guard tallies is no counts, never nothing caught: a
+// window the guard did not count must not read as a clean one.
+func TestProtectionTabNoCounts(t *testing.T) {
+ fx, c := ptFixture(t)
+ if err := usage.UpsertEdgeDay(context.Background(), fx.rel, "box-a", time.Now(), usage.EdgeFlush{
+ Rows: map[string]usage.EdgeRow{ptHost: {Account: release.OpsAccount, App: "shop", Requests: 40}},
+ }); err != nil {
+ t.Fatal(err)
+ }
+ page := ptPage(t, fx, c, "")
+ ptWant(t, page, ptCopy(t, "PT-C10", nil))
+ ptRefuse(t, page, ptCopy(t, "PT-C06", map[string]string{"days": "7"}), ptHeadlineLead, "That's")
+}
+
+func TestProtectionTabNothingCaught(t *testing.T) {
+ fx, c := ptFixture(t)
+ ptSeed(t, fx, 40, 0, 0, nil)
+ page := ptPage(t, fx, c, "")
+ ptWant(t, page, ptCopy(t, "PT-C06", map[string]string{"days": "7"}))
+ ptRefuse(t, page, ptCopy(t, "PT-C10", nil), "requests to this app", "That's", ptCopy(t, "PT-C15", nil))
+}
+
+// A day that cannot be read is said so, with no headline and no zeros.
+func TestProtectionTabReadErrorSaysSo(t *testing.T) {
+ fx, c := ptFixture(t)
+ ptSeed(t, fx, 150, 8, 0, nil)
+ edPut(t, fx.rel, usage.EdgeDayKey("box-b", usage.DayOf(time.Now())), "{not json")
+ page := ptPage(t, fx, c, "")
+ ptWant(t, page, protectionReadErr)
+ ptRefuse(t, page, ptHeadlineLead, ptCopy(t, "PT-C10", nil), "That's")
+
+ status, _, body := get(t, c, fx.u("/apps/shop/protection/data"))
+ if status != http.StatusBadGateway || strings.Contains(body, `"checked"`) {
+ t.Errorf("data door on a read error = %d %s, want 502 and no counts", status, body)
+ }
+}
+
+func TestProtectionDataJSON(t *testing.T) {
+ fx, c := ptFixture(t)
+ ptSeed(t, fx, 150, 8, 2, map[string]int64{"probe/wordpress": 8, "hard/secrets": 2})
+ for query, days := range map[string]int{"": 7, "?range=30d": 30, "?range=bogus": 7} {
+ status, _, body := get(t, c, fx.u("/apps/shop/protection/data"+query))
+ if status != http.StatusOK {
+ t.Fatalf("data%s = %d %s", query, status, body)
+ }
+ var raw map[string]json.RawMessage
+ if err := json.Unmarshal([]byte(body), &raw); err != nil {
+ t.Fatal(err)
+ }
+ for _, k := range []string{"checked", "watch", "block", "days", "groups", "from", "to"} {
+ if _, ok := raw[k]; !ok {
+ t.Errorf("data%s has no %q: %s", query, k, body)
+ }
+ }
+ var sum protectionSummary
+ if err := json.Unmarshal([]byte(body), &sum); err != nil {
+ t.Fatal(err)
+ }
+ if sum.Checked != 150 || sum.Watch != 8 || sum.Block != 2 || len(sum.Days) != days ||
+ sum.Groups["probe/wordpress"] != 8 || sum.Groups["hard/secrets"] != 2 {
+ t.Errorf("data%s = %+v", query, sum)
+ }
+ }
+}
+
+// Whoever cannot open the Analytics tab cannot open this one or its door,
+// and gets the same answer: the byte-identical 404 of an account that does
+// not exist.
+func TestProtectionTabMembersOnly(t *testing.T) {
+ fx, _ := ptFixture(t)
+ fx.setUser("bob@keymail.dev")
+ bob := newBrowser(t)
+ signUp(t, fx, bob, "code-pt-bob")
+ analytics, _, _ := get(t, bob, fx.u("/apps/shop/analytics"))
+ for _, sub := range []string{"/apps/shop/protection", "/apps/shop/protection/data"} {
+ if status, _, _ := get(t, bob, fx.u(sub)); status != analytics {
+ t.Errorf("non-member %s = %d, Analytics gives %d", sub, status, analytics)
+ }
+ }
+ assertNonMember404(t, fx, "/apps/shop/protection")
+ assertNonMember404(t, fx, "/apps/shop/protection/data")
+ // Signed out: no page and no counts.
+ if status, _, body := get(t, newBrowser(t), fx.u("/apps/shop/protection/data")); status == http.StatusOK || strings.Contains(body, `"checked"`) {
+ t.Errorf("signed-out data door = %d", status)
+ }
+}
+
+func TestEveryCatalogueGroupHasAName(t *testing.T) {
+ other := ptCopyText(t, "PT-C36")
+ if got := protectionGroupName("probe/nosuch"); got != other {
+ t.Errorf("unknown group = %q, want %q", got, other)
+ }
+ for _, r := range edgeguard.Rules() {
+ key := r.Tier.String() + "/" + r.Group
+ if protectionGroupName(key) == other {
+ t.Errorf("catalogue group %s has no name", key)
+ }
+ }
+}
+
+func ptCopyText(t *testing.T, id string) string { return ptCopy(t, id, nil) }
+
+func TestAppNavHasProtection(t *testing.T) {
+ fx, c := ptFixture(t)
+ status, _, body := get(t, c, fx.u("/apps/shop"))
+ if status != http.StatusOK {
+ t.Fatalf("overview = %d", status)
+ }
+ a := strings.Index(body, `/apps/shop/analytics">Analytics</a>`)
+ p := strings.Index(body, `/apps/shop/protection">`+ptCopyText(t, "PT-C01")+`</a>`)
+ v := strings.Index(body, `/apps/shop/activity">Activity</a>`)
+ if a < 0 || p < 0 || v < 0 || !(a < p && p < v) {
+ t.Errorf("tab order: analytics %d, protection %d, activity %d; want Protection between", a, p, v)
+ }
+ if !strings.Contains(ptPage(t, fx, c, ""), `protection" aria-current="page">`+ptCopyText(t, "PT-C01")) {
+ t.Error("the Protection tab is not marked current on its own page")
+ }
+}
+
+// ptLogRecords ships recs as one chunk of shop's logs on box.
+func ptLogRecords(t *testing.T, fx *consoleFixture, box string, recs []applog.Record) {
+ t.Helper()
+ body, err := applog.EncodeChunk(recs)
+ if err != nil {
+ t.Fatal(err)
+ }
+ key := mustKey(t)(applog.ChunkKey(release.OpsAccount, "shop", box, applog.HourOf(recs[0].TS), recs[0].Seq, len(body)))
+ if _, err := fx.rel.Put(context.Background(), key, body, ""); err != nil {
+ t.Fatal(err)
+ }
+}
+
+func ptEdgeRecord(ts time.Time, seq uint64, kind, rule, path string) applog.Record {
+ f := map[string]string{"method": "GET", "path": path, "status": "404"}
+ if kind != "" {
+ f["kind"] = kind
+ }
+ if rule != "" {
+ f["rule"] = rule
+ }
+ return applog.Record{TS: ts, Box: "box-a", Host: ptHost, Stream: applog.StreamEdge,
+ Msg: strings.TrimSpace(kind + " " + rule + " GET " + path), Seq: seq, Fields: f}
+}
+
+func ptLogsData(t *testing.T, fx *consoleFixture, c *http.Client, query string) appLogsDataResponse {
+ t.Helper()
+ status, _, body := get(t, c, fx.u("/apps/shop/logs/data?"+query))
+ if status != http.StatusOK {
+ t.Fatalf("logs data ?%s = %d %s", query, status, body)
+ }
+ var out appLogsDataResponse
+ if err := json.Unmarshal([]byte(body), &out); err != nil {
+ t.Fatal(err)
+ }
+ return out
+}
+
+func ptMsgs(lines []appLogsDataLine) []string {
+ var out []string
+ for _, l := range lines {
+ out = append(out, l.Msg)
+ }
+ return out
+}
+
+func TestLogsProtectionFilter(t *testing.T) {
+ fx, c := ptFixture(t)
+ now := time.Now().UTC().Add(-10 * time.Minute)
+ ptLogRecords(t, fx, "box-a", []applog.Record{
+ ptEdgeRecord(now, 100, "watch", "probe.wordpress.wp-login", "/wp-login.php"),
+ ptEdgeRecord(now.Add(time.Second), 101, "block", "hard.secrets.env", "/.env"),
+ ptEdgeRecord(now.Add(2*time.Second), 102, "watch", "probe.admin.admin", "/admin"),
+ ptEdgeRecord(now.Add(3*time.Second), 103, "", "", "/"),
+ // An app line dressed as a match is the app's output, not the edge's.
+ {TS: now.Add(4 * time.Second), Box: "box-a", Host: ptHost, Stream: applog.StreamApp, Msg: "pretend", Seq: 104,
+ Fields: map[string]string{"kind": "block", "rule": "hard.secrets.env"}},
+ })
+ if got := ptMsgs(ptLogsData(t, fx, c, "stream=edge&protection=1").Lines); len(got) != 2 ||
+ !strings.Contains(got[0], "probe.wordpress.wp-login") || !strings.Contains(got[1], "hard.secrets.env") {
+ t.Errorf("protection=1 lines = %q, want the wordpress watch and the secrets block", got)
+ }
+ if got := ptLogsData(t, fx, c, "protection=1").Lines; len(got) != 2 {
+ t.Errorf("protection=1 on every stream = %q, want the two edge matches", ptMsgs(got))
+ }
+ if got := ptLogsData(t, fx, c, "stream=edge").Lines; len(got) != 4 {
+ t.Errorf("without the filter = %d edge lines, want 4", len(got))
+ }
+}
+
+// The filter runs inside the read, before the collect cap trims the
+// window's oldest records: a match older than a full cap of ordinary edge
+// records is still found, by the data door, its follow, and the CLI door.
+func TestLogsProtectionFilterBeforeCap(t *testing.T) {
+ if testing.Short() {
+ t.Skip("writes a full collect cap of records")
+ }
+ fx, c := ptFixture(t)
+ start := time.Now().UTC().Add(-30 * time.Minute)
+ match := ptEdgeRecord(start, 1, "block", "hard.secrets.env", "/.env")
+ ptLogRecords(t, fx, "box-a", []applog.Record{match})
+ bulk := make([]applog.Record, logsCollectCap+1)
+ for i := range bulk {
+ bulk[i] = ptEdgeRecord(start.Add(time.Second+time.Duration(i)*time.Millisecond), uint64(10+i), "", "", fmt.Sprintf("/p%d", i))
+ }
+ ptLogRecords(t, fx, "box-b", bulk)
+
+ if got := ptMsgs(ptLogsData(t, fx, c, "stream=edge&protection=1&since=1h").Lines); len(got) != 1 || !strings.Contains(got[0], "hard.secrets.env") {
+ t.Errorf("data door = %q, want the one match", got)
+ }
+ before := applog.EncodeCursor(applog.Record{TS: start.Add(-time.Minute), Box: "box-a", Seq: 0})
+ if got := ptMsgs(ptLogsData(t, fx, c, "stream=edge&protection=1&since=1h&cursor="+url.QueryEscape(before)).Lines); len(got) != 1 {
+ t.Errorf("follow = %q, want the one match", got)
+ }
+ if err := fx.st.AddMember(OpsAccountID, "alice@keymail.dev", RoleMember, time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ token := cliToken(t, fx, "alice@keymail.dev", "code-pt-cap-cli")
+ status, _, body := rawReq(t, http.MethodGet, logsURL(fx, fx.sqid, "shop", "stream=edge&protection=1&since=1h"), token, "")
+ var resp logsResponse
+ if status != http.StatusOK || json.Unmarshal([]byte(body), &resp) != nil || len(resp.Records) != 1 {
+ t.Errorf("CLI door = %d, %d records, want the one match", status, len(resp.Records))
+ }
+}
+
+func TestProtectionLogsLinkStart(t *testing.T) {
+ now := time.Date(2026, 11, 5, 13, 0, 0, 0, time.UTC)
+ for days, want := range map[int]string{7: "2026-10-30T00:00:00Z", 30: "2026-10-29T13:00:00Z"} {
+ u, err := url.Parse(protectionLogsURL("/a/bab", "shop", protectionDates(days, now), now))
+ if err != nil {
+ t.Fatal(err)
+ }
+ q := u.Query()
+ if u.Path != "/a/bab/apps/shop/logs" || q.Get("stream") != "edge" || q.Get("protection") != "1" || q.Get("since") != want {
+ t.Errorf("%d-day link = %s, want since %s", days, u, want)
+ }
+ }
+}
+
+func TestLogsPageCarriesProtectionFilter(t *testing.T) {
+ fx, c := ptFixture(t)
+ now := time.Now().UTC().Add(-10 * time.Minute)
+ ptLogRecords(t, fx, "box-a", []applog.Record{
+ ptEdgeRecord(now, 100, "watch", "probe.wordpress.wp-login", "/wp-login.php"),
+ ptEdgeRecord(now.Add(time.Second), 101, "", "", "/plain-response"),
+ })
+ since := now.Add(-time.Hour).Format(time.RFC3339)
+ status, _, body := get(t, c, fx.u("/apps/shop/logs?stream=edge&protection=1&since="+url.QueryEscape(since)))
+ if status != http.StatusOK {
+ t.Fatalf("logs page = %d", status)
+ }
+ form, _, _ := strings.Cut(body[strings.Index(body, `id="logs-filter"`):], "</form>")
+ for _, want := range []string{
+ `<option value="edge" selected>` + ptCopyText(t, "PT-C37") + `</option>`,
+ `<input type="hidden" name="protection" value="1">`,
+ `<option value="` + since + `" selected>`,
+ } {
+ if !strings.Contains(form, want) {
+ t.Errorf("logs form missing %q:\n%s", want, form)
+ }
+ }
+ // The live follow builds its URL from the form and the data door.
+ if !strings.Contains(body, `data-url="`+fx.path("/apps/shop/logs/data")+`"`) || !strings.Contains(body, "new URLSearchParams(new FormData(form))") {
+ t.Error("the live follow does not read its query from the form")
+ }
+ if !strings.Contains(body, "wp-login") || strings.Contains(body, "/plain-response") {
+ t.Error("the page's own lines are not filtered to protection matches")
+ }
+
+ _, _, body = get(t, c, fx.u("/apps/shop/logs?stream=edge"))
+ form, _, _ = strings.Cut(body[strings.Index(body, `id="logs-filter"`):], "</form>")
+ if strings.Contains(form, `name="protection"`) || strings.Contains(form, ptCopyText(t, "PT-C37")) || !strings.Contains(form, `<option value="edge" selected>edge</option>`) {
+ t.Errorf("without protection=1 the form = %s, want the edge stream and no protection filter", form)
+ }
+}
diff --git a/internal/console/server.go b/internal/console/server.go
index 016db3b57..60ef732a2 100644
--- a/internal/console/server.go
+++ b/internal/console/server.go
@@ -1868,6 +1868,11 @@ func NewServer(cfg Config, st *Store) (*Server, error) {
s.registerRoute("GET /a/{sqid}/apps/{app}/analytics", s.handleAppAnalytics)
s.registerRoute("GET /a/{sqid}/apps/{app}/analytics/live", s.handleAnalyticsLive)
s.registerRoute("POST /a/{sqid}/apps/{app}/analytics/setting", s.handleAppAnalyticsSetting)
+ // The Protection tab (protectionview.go) and its JSON door: what the
+ // edge guard checked, recorded and blocked for the app. Member-readable
+ // like the Analytics tab, through the same gate.
+ s.registerRoute("GET /a/{sqid}/apps/{app}/protection", s.handleAppProtection)
+ s.registerRoute("GET /a/{sqid}/apps/{app}/protection/data", s.handleAppProtectionData)
s.registerRoute("GET /a/{sqid}/apps/{app}/activity", s.handleAppActivity)
s.registerRoute("GET /a/{sqid}/apps/{app}/settings", s.handleAppSettings)
s.registerRoute("GET /a/{sqid}/apps/{app}/settings/{section}", s.handleAppSettings)
@@ -2496,6 +2501,9 @@ type page struct {
LogGrep string
LogLegacyGrep string
LogFollow bool
+ // LogProtection: protection=1, the Protection tab's link. The form
+ // carries it on, so Update and the live follow keep the filter.
+ LogProtection bool
LogHosts []string
LogCopy appLogsCopy
LogWidenURL string
@@ -2557,6 +2565,9 @@ type page struct {
// Analytics tab and the Overview card (analyticslive.go).
AnalyticsLive *analyticsLive
TrafficLive *analyticsLive
+ // Protection is the Protection tab (protectionview.go): the window's
+ // counts and how the page draws them, or the read error alone.
+ Protection *protectionView
// Action confirm interstitial (confirm.go): what is about to happen,
// carried fields and all. Nil everywhere except the confirm page.
@@ -4504,6 +4515,7 @@ func (s *Server) handleAppLogs(w http.ResponseWriter, r *http.Request) {
p.LogGrep = q.Get("text")
p.LogLegacyGrep = q.Get("grep")
p.LogFollow = q.Get("follow") == "1"
+ p.LogProtection = q.Get("protection") == "1"
widen, _ := url.ParseQuery(q.Encode())
widen.Set("since", "24h")
widen.Del("cursor")
diff --git a/internal/console/templates/app_logs.html b/internal/console/templates/app_logs.html
index 1c4b09903..b0539bbb5 100644
--- a/internal/console/templates/app_logs.html
+++ b/internal/console/templates/app_logs.html
@@ -17,8 +17,13 @@
<option value=""{{if eq .LogStream ""}} selected{{end}}>everything</option>
<option value="app"{{if eq .LogStream "app"}} selected{{end}}>app output</option>
<option value="platform"{{if eq .LogStream "platform"}} selected{{end}}>platform events</option>
+ {{/* A stream the list does not offer (the Protection tab links to
+ edge) stays selected, as since does below. With protection=1 it
+ is the protection matches. */}}
+ {{if and (ne .LogStream "") (ne .LogStream "app") (ne .LogStream "platform")}}<option value="{{.LogStream}}" selected>{{if and .LogProtection (eq .LogStream "edge")}}protection matches{{else}}{{.LogStream}}{{end}}</option>{{end}}
</select>
</label>
+ {{if .LogProtection}}<input type="hidden" name="protection" value="1">{{end}}
<label>from the last
<select name="since">
{{if and (ne .LogSince "15m") (ne .LogSince "1h") (ne .LogSince "6h") (ne .LogSince "24h") (ne .LogSince "168h")}}<option value="{{.LogSince}}" selected>{{.LogSince}}</option>{{end}}
@@ -78,6 +83,14 @@ site served from files alone has no app output.</p>
var following = false;
var generation = 0;
var dirty = false;
+ // The protection filter goes with the edge stream: choosing another
+ // stream drops it, choosing edge again brings it back.
+ var protection = form.querySelector('input[name="protection"]');
+ if (protection && form.elements.stream) {
+ form.elements.stream.addEventListener("change", function () {
+ protection.disabled = form.elements.stream.value !== "edge";
+ });
+ }
var activeQuery = new URLSearchParams(new FormData(form));
function setFollowing(on) {
diff --git a/internal/console/templates/app_protection.html b/internal/console/templates/app_protection.html
new file mode 100644
index 000000000..023dcb25d
--- /dev/null
+++ b/internal/console/templates/app_protection.html
@@ -0,0 +1,52 @@
+{{define "app_protection"}}{{template "top" .}}
+{{if .Flash}}<p class="banner">{{.Flash}}</p>{{end}}
+{{if .FlashErr}}<p class="banner error">{{.FlashErr}}</p>{{end}}
+{{template "appnav" .}}
+
+<h2 class="visually-hidden">Protection</h2>
+{{with .Protection}}
+{{/* Two links rather than a select and a button, as the Analytics tab:
+ one click, and every view is a URL. */}}
+<nav class="an-range">
+ <a href="?range=7d"{{if eq .Range "7d"}} aria-current="page"{{end}}>7 days</a>
+ <a href="?range=30d"{{if eq .Range "30d"}} aria-current="page"{{end}}>30 days</a>
+</nav>
+{{/* A failed read stands alone: no headline and no zeros. A window with
+ no tallies says so, and never that nothing was caught: that would be a
+ claim about requests nobody counted. */}}
+{{if .Err}}<p class="banner error">{{.Err}}</p>
+{{else if not .Sum.Checked}}<p class="an-empty">No protection counts yet for this app. Counting starts once the servers that run it take the release that adds it, and only while protection is on.</p>
+{{else}}
+<p class="an-insights"><strong>{{if and .Sum.Watch (not .Sum.Block)}}In the last {{.Days}} days, {{count .Sum.Watch}} requests to this app looked like attacks. Protection is recording them and letting them through while we check it never stops a real visitor.
+{{- else if and .Sum.Block (not .Sum.Watch)}}In the last {{.Days}} days, protection blocked {{count .Sum.Block}} requests to this app.
+{{- else if .Caught}}In the last {{.Days}} days, protection blocked {{count .Sum.Block}} requests to this app and recorded {{count .Sum.Watch}} more.
+{{- else}}Nothing in the last {{.Days}} days looked like an attack.{{end}}</strong></p>
+{{if .Caught}}
+<p class="an-quality small">That's {{.Share}} of the {{count .Sum.Checked}} requests protection checked.</p>
+{{with .Chart}}
+<h3 id="pt-days">Day by day</h3>
+{{/* The Analytics chart's markup: a column per day, its bar what was
+ caught that day, the blocked part at its foot. */}}
+<figure class="an-chart an-chart-day" style="--an-cols: {{.N}}">
+ <div class="an-plot">
+ <div class="an-grid" aria-hidden="true">{{range .Ticks}}<span style="bottom: {{.Pct}}%"><i>{{.Label}}</i></span>{{end}}</div>
+ <div class="an-cols" role="group" aria-labelledby="pt-days">
+ {{range .Cols}}<button type="button" class="an-col{{if .Partial}} an-partial{{end}}{{if .Edge}} an-edge-{{.Edge}}{{end}}" aria-label="{{.Label}}"><span class="an-bar" style="height: {{.HPct}}%">{{if .BlockPct}}<span class="pt-blocked" style="height: {{.BlockPct}}%"></span>{{end}}<span class="an-tip" aria-hidden="true"><b>{{index .Lines 0}}</b><span>{{index .Lines 1}}</span><span class="an-when">{{.When}}</span></span></span></button>{{end}}
+ </div>
+ </div>
+ <div class="an-xaxis" aria-hidden="true">{{range .XLabels}}<span style="grid-column: {{.Col}}">{{.Label}}</span>{{end}}</div>
+</figure>
+<p class="an-quality small"><span class="pt-key pt-key-blocked" aria-hidden="true"></span>blocked <span class="pt-key" aria-hidden="true"></span>recorded</p>
+{{end}}
+<div class="an-breakdowns">
+ <section class="an-card" aria-labelledby="pt-groups">
+ <h3 id="pt-groups">What they were after</h3>
+ {{template "sharelist" .Groups}}
+ </section>
+</div>
+<p><a href="{{.LogsURL}}">See these requests in Logs</a>{{if eq .Range "30d"}} <span class="small">Logs keep these requests for 7 days, so older ones are counted here but no longer listed.</span>{{end}}</p>
+{{template "analyticsscript"}}
+{{end}}
+{{end}}
+{{end}}
+{{template "bottom" .}}{{end}}
diff --git a/internal/console/templates/appnav.html b/internal/console/templates/appnav.html
index bab728e31..c3c3ef6d7 100644
--- a/internal/console/templates/appnav.html
+++ b/internal/console/templates/appnav.html
@@ -18,6 +18,7 @@
<a href="{{.Nav}}/apps/{{.AppName}}/errors"{{if eq .ActiveTab "errors"}} aria-current="page"{{end}}>Errors</a>
<a href="{{.Nav}}/apps/{{.AppName}}/availability"{{if eq .ActiveTab "availability"}} aria-current="page"{{end}}>Availability</a>
<a href="{{.Nav}}/apps/{{.AppName}}/analytics"{{if eq .ActiveTab "analytics"}} aria-current="page"{{end}}>Analytics</a>
+ <a href="{{.Nav}}/apps/{{.AppName}}/protection"{{if eq .ActiveTab "protection"}} aria-current="page"{{end}}>Protection</a>
<a href="{{.Nav}}/apps/{{.AppName}}/activity"{{if eq .ActiveTab "activity"}} aria-current="page"{{end}}>Activity</a>
<a href="{{.Nav}}/apps/{{.AppName}}/settings"{{if eq .ActiveTab "settings"}} aria-current="page"{{end}}>Settings</a>
</nav>
diff --git a/internal/console/templates/layout.html b/internal/console/templates/layout.html
index 29279a610..b7e729769 100644
--- a/internal/console/templates/layout.html
+++ b/internal/console/templates/layout.html
@@ -821,6 +821,13 @@
.an-overview .an-figures { gap: 0.75rem 2.5rem; margin-bottom: 1rem; }
.an-overview .an-figures dd:not(.an-note) { font-size: 1.6rem; }
.an-overview .an-empty { padding: 1.5rem 0; }
+ /* The Protection tab draws two series on the Analytics chart: the bar is
+ what was caught that day, its foot what was blocked, in ink so the two
+ read apart in either scheme. The legend keys use the same fills. */
+ .pt-blocked { position: absolute; left: 0; right: 0; bottom: 0; background: var(--ink); border-radius: inherit; }
+ .pt-key { display: inline-block; width: 0.7rem; height: 0.7rem; margin: 0 0.35rem 0 0; border-radius: 2px; background: var(--accent); vertical-align: -0.05rem; }
+ .pt-key + .pt-key { margin-left: 0.75rem; }
+ .pt-key-blocked { background: var(--ink); }
@media (max-width: 40rem) {
.an-figures { gap: 1rem 2rem; }
.an-figures dd:not(.an-note) { font-size: 1.75rem; }
@@ -829,6 +836,8 @@
}
@media (forced-colors: active) {
.an-bar, .an-track span { background: CanvasText; }
+ .pt-key { background: CanvasText; }
+ .pt-blocked, .pt-key-blocked { background: Highlight; }
.an-tip { border: 1px solid CanvasText; }
}
.buy-foot { margin: 1.75rem 0 0; }
diff --git a/internal/console/testdata/perf-budgets.txt b/internal/console/testdata/perf-budgets.txt
index a2b47649e..f4640dc46 100644
--- a/internal/console/testdata/perf-budgets.txt
+++ b/internal/console/testdata/perf-budgets.txt
@@ -65,6 +65,8 @@ GET /a/{sqid}/apps/{app}/logs/data deferred: deferred part (the Logs tab's data
/fleet/architecture calls 12: reads economics/active.json, infra/inventory.json and status/fleet.json, and lists and reads every box report (12 S3 calls warm and cold, about 390 ms)
GET /a/{sqid}/apps/{app}/analytics/live calls 2: the live door the Analytics tab and Overview card refresh from once a minute: both telemetry settings, read on every refresh so an owner turning analytics on sees it at once; the window's counts come from the traffic memo, read at most once a minute per app and view (about 50 ms)
GET /a/{sqid}/apps/{app}/analytics calls 4: both telemetry settings, the analytics day listing and one day read (about 105 ms); cold, also the app-tab frame and the account manifest (11 S3 calls, about 190 ms)
+GET /a/{sqid}/apps/{app}/protection calls 2: the Protection tab reads the edge days: one box listing at the root and one in each fleet the account owns (the walk's fixture: two listings and no edge days, about 55 ms); each box adds its today's and yesterday's day, which never settle, and the usage-day cache answers the rest; cold, also the app-tab frame and the account manifest (9 S3 calls, about 135 ms)
+GET /a/{sqid}/apps/{app}/protection/data calls 2: the Protection tab's JSON door, the same edge-day read without the app-tab frame (about 55 ms)
GET /a/{sqid}/apps/{app}/availability calls 10: both telemetry settings and three listings and a read each for the log and error chunks (about 265 ms); cold, also the app-tab frame and the account manifest (17 S3 calls, about 340 ms)
GET /a/{sqid}/apps/{app}/errors calls 10: both telemetry settings and three listings and a read each for the log and error chunks (about 265 ms); cold, also the app-tab frame and the account manifest (17 S3 calls, about 340 ms)
GET /a/{sqid}/apps/{app}/logs calls 4: three listings for the log chunks and a chunk read; the host picker uses the records the page already holds (about 105 ms); cold, also the app-tab frame and the account manifest (11 S3 calls, about 185 ms)
diff --git a/internal/edgeguard/catalogue.go b/internal/edgeguard/catalogue.go
index 95f580000..c3ff397f2 100644
--- a/internal/edgeguard/catalogue.go
+++ b/internal/edgeguard/catalogue.go
@@ -140,6 +140,17 @@ func RuleByHash(h uint32) (*Rule, bool) {
return &rules[i], true
}
+// RuleByID finds the rule called id, as a request record's "rule" field
+// names it. IDs are unique because their hashes are (buildIndex refuses a
+// catalogue where two share one), so the hash index answers this too.
+func RuleByID(id string) (*Rule, bool) {
+ r, ok := RuleByHash(reqrec.RuleHash(id))
+ if !ok || r.ID != id {
+ return nil, false
+ }
+ return r, true
+}
+
// parseCatalogue reads the catalogue format: one rule per line with the
// columns "tier group name kind pattern mode", "#" comments, blank lines, and
// a "# version N" comment. It returns the rules in file order and the version.
diff --git a/internal/edgeguard/catalogue_test.go b/internal/edgeguard/catalogue_test.go
index 743929be5..cdcf99e58 100644
--- a/internal/edgeguard/catalogue_test.go
+++ b/internal/edgeguard/catalogue_test.go
@@ -55,6 +55,20 @@ func TestCatalogueRuleHashesUnique(t *testing.T) {
}
}
+func TestRuleByID(t *testing.T) {
+ for _, r := range Rules() {
+ got, ok := RuleByID(r.ID)
+ if !ok || got.ID != r.ID || got.Mode != r.Mode {
+ t.Errorf("RuleByID(%q) = %v, %v", r.ID, got, ok)
+ }
+ }
+ for _, id := range []string{"", "hard.secrets", "hard.secrets.nosuch", "HARD.SECRETS.ENV"} {
+ if got, ok := RuleByID(id); ok {
+ t.Errorf("RuleByID(%q) = %v, want no rule", id, got)
+ }
+ }
+}
+
func TestCatalogueAdminIsBurst(t *testing.T) {
admin := 0
for _, r := range Rules() {