Edge protection Plan 2: the hard and probe tiers, in watch mode. A catalogue embedded in the binary (internal/edgeguard) is matched in memory against every request the edge serves except door calls, backhauled door hops and tunnel deliveries: hard rules (.env, .git, traversal) and probe rules (well-known attack paths, matched only where the app would not serve the path; static sites decide from their own files, and a rewrite onto a hard-tier file is refused). By default every match is only recorded, as a Match request record with a reference code; CARLOS_EDGE_PROTECT=block (dev only) answers a 404 block page. The console names a code's catalogue rule, and carlos explain says what a block page's code means. Copy EP-1..EP-14 approved by Paul. Census census-ruling-edge-protection-2: approvals by Astra, two decisions by Paul, on #280. Not released.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Squashed from edge-protection-2 into main.
31 files changed,
+3,626
−66
approved_edge_protect_copy_test.go+190 −0docs/site/cli.md+4 −0docs/superpowers/notes/census-proposal-edge-protection-2.md+23 −0docs/superpowers/plans/2026-10-25-edge-protection-2-copy.md+63 −0docs/superpowers/plans/2026-10-25-edge-protection-2-hard-probe-watch.md+411 −0explain_cmd.go+131 −0explain_cmd_test.go+147 −0internal/console/apiedgeref.go+18 −3internal/console/apiedgeref_test.go+63 −0internal/edge/answered.go+16 −4internal/edge/edge.go+50 −2internal/edge/guard.go+138 −0internal/edge/guard_test.go+432 −0internal/edge/redirects.go+29 −0internal/edge/reqrecords.go+29 −25internal/edge/reqrecords_test.go+41 −25internal/edge/static.go+54 −5internal/edge/static_guard_test.go+313 −0internal/edgeguard/catalogue.go+370 −0internal/edgeguard/catalogue.txt+82 −0internal/edgeguard/catalogue_test.go+137 −0internal/edgeguard/match.go+432 −0internal/edgeguard/match_test.go+380 −0internal/host/reqrec_e2e_test.go+3 −1internal/hostenv/hostenv.go+2 −0internal/provision/edge_protection_2_census_test.go+37 −0internal/provision/plan9_b8_census_test.go+1 −1internal/provision/testdata/plan14-root-reads-chain.tsv+2 −0internal/provision/testdata/plan14-root-reads-edge-protection-2-decisions.tsv+12 −0internal/provision/testdata/plan14-root-reads-edge-protection-2.tsv+13 −0main.go+3 −0
CI failed — run details
diff --git a/approved_edge_protect_copy_test.go b/approved_edge_protect_copy_test.go| new file mode 100644 |
| index 000000000..f67b5118a |
| --- /dev/null |
| +++ b/approved_edge_protect_copy_test.go |
| @@ -0,0 +1,190 @@ |
| +// approved_edge_protect_copy_test.go |
| +package main |
| + |
| +import ( |
| + "fmt" |
| + "os" |
| + "regexp" |
| + "strconv" |
| + "strings" |
| + "testing" |
| +) |
| + |
| +// The copy gate of edge protection Plan 2 (the block page, `carlos explain` |
| +// and its docs), over docs/superpowers/plans/2026-10-25-edge-protection-2-copy.md. |
| +// It reuses the moves gate's parser and checks, as the db region forward |
| +// gate does: |
| +// |
| +// - TestEdgeProtectCopyRecordIsComplete: the record names exactly |
| +// edgeProtectCopyIDs; |
| +// - TestEdgeProtectCopyHasNoEmDash; |
| +// - TestEdgeProtectBuiltCopyIsApproved: an id in edgeProtectCopyBuilt is an |
| +// approved row. No pending string reaches docs as approved text; |
| +// - TestEdgeProtectBuiltCopyIsApplied: a built row's text is in the file it |
| +// names; |
| +// - TestEdgeProtectWiredCopyIsPendingAndApplied: a wired id is a pending, |
| +// non-docs row whose text is in its file; |
| +// - TestEdgeProtectCopyAccounted: every id is built or wired, once; |
| +// - TestEdgeProtectCopyNoneWired: nothing is wired, the review being done. |
| +const edgeProtectCopyRecordPath = "docs/superpowers/plans/2026-10-25-edge-protection-2-copy.md" |
| + |
| +var edgeProtectCopyIDPattern = regexp.MustCompile(`^EP-[0-9]+$`) |
| + |
| +// edgeProtectCopyIDs is the record's inventory, pinned: EP-1 to EP-14. |
| +var edgeProtectCopyIDs = func() []string { |
| + ids := make([]string, 0, 14) |
| + for i := 1; i <= 14; i++ { |
| + ids = append(ids, "EP-"+strconv.Itoa(i)) |
| + } |
| + return ids |
| +}() |
| + |
| +// edgeProtectCopyBuilt is every id whose approved text the code or docs |
| +// carry: all fourteen since Paul's copy review of 2026-10-25, which approved |
| +// every row unedited. EP-3 is the docs entry in docs/site/cli.md and EP-14 is |
| +// the `explain` line of the top-level usage in main.go. |
| +var edgeProtectCopyBuilt = []string{ |
| + "EP-1", "EP-2", "EP-3", "EP-4", "EP-5", "EP-6", "EP-7", "EP-8", "EP-9", "EP-10", "EP-11", "EP-12", "EP-13", "EP-14", |
| +} |
| + |
| +// edgeProtectCopyWired is every id whose PENDING text the code already |
| +// carries, so the branch can be built and tested before the copy review. |
| +// It is empty now the review is done: each id moved to edgeProtectCopyBuilt |
| +// when its row was approved. The gate stays for the next plan's copy. |
| +var edgeProtectCopyWired = []string{} |
| + |
| +func mustParseEdgeProtectRecord(t *testing.T) []copyRow { |
| + t.Helper() |
| + raw, err := os.ReadFile(edgeProtectCopyRecordPath) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + rows, err := parseCopyTable(string(raw), edgeProtectCopyRecordPath, edgeProtectCopyIDPattern, "an EP-<n>") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return rows |
| +} |
| + |
| +func TestEdgeProtectCopyRecordIsComplete(t *testing.T) { |
| + reportAll(t, checkMovesInventory(mustParseEdgeProtectRecord(t), edgeProtectCopyIDs)) |
| +} |
| + |
| +func TestEdgeProtectCopyHasNoEmDash(t *testing.T) { |
| + reportAll(t, checkMovesNoEmDash(mustParseEdgeProtectRecord(t))) |
| +} |
| + |
| +func TestEdgeProtectBuiltCopyIsApproved(t *testing.T) { |
| + reportAll(t, checkRunBuilt(mustParseEdgeProtectRecord(t), edgeProtectCopyBuilt)) |
| +} |
| + |
| +func TestEdgeProtectBuiltCopyIsApplied(t *testing.T) { |
| + rows := builtRows(mustParseEdgeProtectRecord(t), edgeProtectCopyBuilt) |
| + for i := range rows { |
| + rows[i].Text = strings.ReplaceAll(rows[i].Text, `\n`, "\n") |
| + } |
| + reportAll(t, checkRunApplied(rows, ".")) |
| +} |
| + |
| +// checkEdgeProtectWired: a wired id is a pending row the record has, named |
| +// once, not built as well, not a docs row, and its text is in the file it |
| +// names (so the review's edits must reach the code). |
| +func checkEdgeProtectWired(rows []copyRow, wired, built []string) []string { |
| + byID := map[string]copyRow{} |
| + for _, r := range rows { |
| + byID[r.ID] = r |
| + } |
| + isBuilt := map[string]bool{} |
| + for _, id := range built { |
| + isBuilt[id] = true |
| + } |
| + var out []string |
| + var apply []copyRow |
| + seen := map[string]bool{} |
| + for _, id := range wired { |
| + if seen[id] { |
| + out = append(out, fmt.Sprintf("edgeProtectCopyWired names %s twice", id)) |
| + } |
| + seen[id] = true |
| + r, ok := byID[id] |
| + switch { |
| + case !ok: |
| + out = append(out, fmt.Sprintf("edgeProtectCopyWired names %s, which the record has no row for", id)) |
| + continue |
| + case isBuilt[id]: |
| + out = append(out, fmt.Sprintf("%s is both wired and built: an approved row moves to edgeProtectCopyBuilt", id)) |
| + case r.Status != "pending": |
| + out = append(out, fmt.Sprintf("%s is %s: an approved row moves from edgeProtectCopyWired to edgeProtectCopyBuilt", id, r.Status)) |
| + case strings.HasPrefix(r.Path(), "docs/"): |
| + out = append(out, fmt.Sprintf("%s is a docs row: pending docs text is never wired", id)) |
| + } |
| + r.Status = "approved" // checkMovesApplied reads approved rows only |
| + apply = append(apply, r) |
| + } |
| + return append(out, checkMovesApplied(apply, ".")...) |
| +} |
| + |
| +func TestEdgeProtectWiredCopyIsPendingAndApplied(t *testing.T) { |
| + rows := mustParseEdgeProtectRecord(t) |
| + for i := range rows { |
| + rows[i].Text = strings.ReplaceAll(rows[i].Text, `\n`, "\n") |
| + } |
| + reportAll(t, checkEdgeProtectWired(rows, edgeProtectCopyWired, edgeProtectCopyBuilt)) |
| +} |
| + |
| +// checkEdgeProtectAccounted: every id in the inventory is in exactly one of |
| +// built and wired. The docs row is no exception now that it is approved and |
| +// written. |
| +func checkEdgeProtectAccounted(ids, built, wired []string) []string { |
| + count := map[string]int{} |
| + for _, id := range built { |
| + count[id]++ |
| + } |
| + for _, id := range wired { |
| + count[id]++ |
| + } |
| + var out []string |
| + for _, id := range ids { |
| + if n := count[id]; n != 1 { |
| + out = append(out, fmt.Sprintf("%s is named %d times across edgeProtectCopyBuilt and edgeProtectCopyWired, want exactly 1", id, n)) |
| + } |
| + } |
| + return out |
| +} |
| + |
| +func TestEdgeProtectCopyAccounted(t *testing.T) { |
| + reportAll(t, checkEdgeProtectAccounted(edgeProtectCopyIDs, edgeProtectCopyBuilt, edgeProtectCopyWired)) |
| +} |
| + |
| +// The copy review is over: no pending text is left wired, so every string |
| +// the code speaks is an approved, built row. |
| +func TestEdgeProtectCopyNoneWired(t *testing.T) { |
| + if len(edgeProtectCopyWired) != 0 { |
| + t.Errorf("edgeProtectCopyWired = %q, want empty: the copy review approved every row", edgeProtectCopyWired) |
| + } |
| +} |
| + |
| +// The gate bites: a wired row whose text is not in its file, an approved row |
| +// left wired, and a docs row wired are each refused; an id in neither list |
| +// and an id in both are each refused by the accounting. |
| +func TestEdgeProtectGatesRefuse(t *testing.T) { |
| + rows := []copyRow{ |
| + {"EP-1", "internal/edge/guard.go", "nothing like this sentence is in the file.", "pending"}, |
| + {"EP-2", "internal/edge/guard.go", "x", "approved"}, |
| + {"EP-3", "docs/site/cli.md", "x", "pending"}, |
| + } |
| + got := checkEdgeProtectWired(rows, []string{"EP-1", "EP-2", "EP-3"}, nil) |
| + for _, want := range []string{"does not contain the approved text", "EP-2 is approved", "EP-3 is a docs row"} { |
| + found := false |
| + for _, g := range got { |
| + found = found || strings.Contains(g, want) |
| + } |
| + if !found { |
| + t.Errorf("no problem saying %q in %q", want, got) |
| + } |
| + } |
| + acc := checkEdgeProtectAccounted([]string{"EP-1", "EP-2"}, []string{"EP-1"}, []string{"EP-1"}) |
| + if len(acc) != 2 || !strings.Contains(acc[0], "EP-1") || !strings.Contains(acc[1], "EP-2") { |
| + t.Errorf("accounting problems = %q, want EP-1 twice and EP-2 missing", acc) |
| + } |
| +} |
diff --git a/docs/site/cli.md b/docs/site/cli.md| index e0e201493..f2bc6affb 100644 |
| --- a/docs/site/cli.md |
| +++ b/docs/site/cli.md |
| @@ -1334,6 +1334,10 @@ carlos logs --app hello --since 1h -f |
| an RE2 pattern, `--stream app` drops the platform commentary, and `--host` |
| narrows to one instance. |
| +### carlos explain |
| + |
| +`carlos explain <code> --app <a>` reads a reference code from a page the platform's edge protection answered. It says which rule fired and when, and shows the request while a record of it is kept, for 7 days. |
| + |
| ### carlos errors |
| One row per distinct error, newest first, with how many times it happened |
diff --git a/docs/superpowers/notes/census-proposal-edge-protection-2.md b/docs/superpowers/notes/census-proposal-edge-protection-2.md| new file mode 100644 |
| index 000000000..e4c516d98 |
| --- /dev/null |
| +++ b/docs/superpowers/notes/census-proposal-edge-protection-2.md |
| @@ -0,0 +1,23 @@ |
| +# Census approval: edge-protection-2 |
| + |
| +Ruling `census-ruling-edge-protection-2`. Every change below keeps the disposition it already has, so it needs an approval, not a decision. |
| + |
| +| unit | change | read sites | what changed | |
| +|---|---|---|---| |
| +| `internal/edge/reqrecords.go` `Edge.observeRecords` | body | unchanged (1) | files one reqrec.Match in place of the Response when the request's outcome carries a guard verdict (kind block or watch, the verdict's rule tier, id, fragment and reference code; a block woke nothing), and the plain Response otherwise; still in-memory, its one scanned site is the route value passed in; no read added | |
| +| `internal/edge/static.go` `staticSite.serveTree` | body | unchanged (2) | consults the edge protection matcher (internal/edgeguard, pure and in-memory) on the request path (probe tier, only when no file and no _redirects rule names it) and on a rewrite target (hard tier, only when the file is there), and may answer the guard's 404 block page through guardDecide before a redirect or the rewritten file; the _redirects lookup gains an in-memory names check; the same index-aware Stat lookups inside the extracted tree, unchanged; no read added | |
| +| `internal/edge/edge.go` `Edge.ServeHTTP` | sites | +registry:Kind, +whole:Route | runs the guard, a pure in-memory matcher on r.URL.Path and RawQuery (internal/edgeguard), once per request after the meter and observer defer and before the password gate, the upgrade branch, the cache and the activator, for a request that is not a door call, a backhauled door hop or a tunnel delivery; a matched block answers a 404 itself through guardDecide; the two new sites are one expression, up.route.Kind == "static" (a static route this box serves checks only the hard tier here and leaves the probe tier to serveTree), a read of the route row the edge already resolved; no new kind of read | |
| + |
| +Envelopes re-pinned: `.`, `internal/console`, `internal/edge`, `internal/edgeguard`, `internal/hostenv`. |
| + |
| +Review: a model from the other family than the author reads the branch's diff against main on the amadan.net remote (`origin` or `amadan`, whichever points at amadan.net) and gives a verdict for every unit and every re-pinned envelope above. For a unit, compare the change with its recorded disposition and basis below; for an envelope, read every changed function in the package and what it reaches. Escalate if the change lets root open, run, query or follow anything it did not before from a path or input a tenant, an app or a box agent can create, write or name; if it weakens a check, refusal, validation, argument or environment the basis relies on; or if the diff cannot settle either. Otherwise approve. Record each verdict on #280 with the tip. An escalation goes to the census owner as a decision. |
| + |
| +Recorded dispositions, which each change must still satisfy: |
| + |
| +- `internal/edge/reqrecords.go` `Edge.observeRecords`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=census-ruling-edge-request-records;identity=the edge inside the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos);basis=new: called from ServeHTTP's observer defer after observeAnalytics, with the route the defer already holds; returns at once when no recorder is wired or the request arrived over a tunnel (the forwarding box records it); otherwise builds the Response through requestResponse from that route and the request and hands it to the in-memory recorder, which files it into the box's log sink; its one scanned site is the route value passed in; it reads no file, no store and no box state, writes nothing outside the log sink, and makes no serving or root decision; the class of Edge.observeAnalytics (J1 root-route) |
| +- `internal/edge/static.go` `staticSite.serveTree`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=J4;basis=root-input;rev3=PROPOSED-static-redirects;identity=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos);basis=the same index-aware Stat lookup inside the extracted tree, now run at most twice (the request path, then once for a _redirects rewrite destination cleaned rooted inside the same tree); the Open moves to serveFile; the _redirects file itself is never answered; no root decision |
| +- `internal/edge/edge.go` `Edge.ServeHTTP`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=census-ruling-seeded-instances;basis=the edge inside the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): main's body with the import gate checked after the door's scope and a gated row left out of the response cache; serving only;rev3=census-ruling-edge-request-records;basis=one more call in the observer defer, observeRecords(up.route, ...), passing on the route the defer already holds; no new kind of read;rev3=census-ruling-design-edge-rate-limit-358;basis=calls rateAdmit twice, and an admitted request holds a slot on both paths: on the upgrade path before the activator or proxy (the handshake holds its slot through slotWriter, given back at the first final answer or at the reverse proxy's hijack on a 101, so an open WebSocket is not counted; released by a defer), and on the ordinary path after the response-cache check and before the activator and proxy (an admitted request holds a slot through slotWriter, released by a defer); a refusal is a 429 written there and returns; the upgrade path's comment now names slotWriter as its one wrapper; one comment on the door mark reworded; read sites unchanged (22: main's 21 plus edge-request-records' observeRecords pass of the route), offsets moved; no read added;rev3=census-ruling-plans-4c-box-throttle;basis=calls planThrottleAdmit before the response cache, and on an upgrade trackUpgrade then planUpgradeAdmit (plans 4c, Astra findings 1 and 2); the new reads live in those units (plans-4c-units decision). The same read sites here.;rev3=census-ruling-plans-4d-lapse;basis=calls planDisabledAdmit right after the import gate, passing the final upstream's route and the request host; a turned-off route gets the fixed disabled page before the meter, gate, cache and activator (plans 4d). The new read lives in that unit (plans-4d-units decision); one more whole-row pass here. |
| + |
| +Seal: `7d90eff62dcb3d2d211b9f0fa37ba1967f1f418884a11c1476cdaa50b187efd5` → `a864cf31b6bf2c30b5aa8c2647835efdc456f34f4945eea12751daab2457728e`. |
| + |
| +Overlay: `internal/provision/testdata/plan14-root-reads-edge-protection-2.tsv`, appended to `internal/provision/testdata/plan14-root-reads-chain.tsv`. |
diff --git a/docs/superpowers/plans/2026-10-25-edge-protection-2-copy.md b/docs/superpowers/plans/2026-10-25-edge-protection-2-copy.md| new file mode 100644 |
| index 000000000..cd9faa9f8 |
| --- /dev/null |
| +++ b/docs/superpowers/plans/2026-10-25-edge-protection-2-copy.md |
| @@ -0,0 +1,63 @@ |
| +# Edge protection Plan 2: copy record |
| + |
| +Every user-facing string that edge protection Plan 2 writes |
| +(`2026-10-25-edge-protection-2-hard-probe-watch.md`): the block page, the |
| +`carlos explain` lines and the CLI docs. The gate is |
| +`approved_edge_protect_copy_test.go` at the repo root. It reuses the moves |
| +gate's parser, so the format is the moves record's: one table per heading, |
| +with columns id, file, text and status. |
| + |
| +The rules: |
| + |
| +- A row is `pending` until Paul approves it in the copy review (the |
| + `copy-review` skill). His edits are applied to the text here verbatim, |
| + and the row becomes `approved`. |
| +- Pending CLI and edge text may be wired into code while the branch is |
| + being built (`edgeProtectCopyWired`). The branch does not merge until |
| + every row is approved and built. Docs rows are never wired: they are |
| + written only once approved. |
| +- In a Go file the text is one string literal, or one `fmt.Sprintf` or |
| + `fmt.Fprintf` format. It equals the row, with a format verb where the |
| + row has a `<placeholder>`. No trailing newline goes inside the literal. |
| +- A table cell holds one line, so a row writes a line break as `\n`. |
| +- No em dashes. Use a full stop and a new sentence instead, continuing in |
| + lower case. CLI lines are lower case. The block page and the docs use |
| + sentence case. |
| + |
| +Placeholders: |
| + |
| +- `<code>`: a 40-character reference code. |
| +- `<time>`: `2006-01-02 15:04 UTC`. |
| +- `<tier>`: `hard` or `probe`. |
| +- `<rule>`: a rule id such as `hard.secrets.env`. |
| +- `<hash>`: 8 hex digits. |
| +- `<method>`, `<path>`, `<host>` and `<status>`: as the record stores them. |
| + |
| +## The block page |
| + |
| +| id | file | text | status | |
| +|---|---|---|---| |
| +| EP-1 | internal/edge/guard.go | Not found.\n\nIf you expected a page here, send this reference to the site's owner: <code> | approved | |
| + |
| +## `carlos explain` |
| + |
| +| id | file | text | status | |
| +|---|---|---|---| |
| +| EP-2 | explain_cmd.go | usage: carlos explain <code> --app <a> [flags]\n\nWhat a reference code from a page the edge answered says: which protection rule fired, when, and the request it answered, while a record of it is kept. --json prints the console's answer as it is. | approved | |
| +| EP-4 | explain_cmd.go | checked yes. this deployment sealed the code | approved | |
| +| EP-5 | explain_cmd.go | checked no. the console has no key to check the seal with, so treat the rest as unchecked | approved | |
| +| EP-6 | explain_cmd.go | checked no. the code is not sealed, so anyone could have written it. treat the rest as unchecked | approved | |
| +| EP-7 | explain_cmd.go | rule not in this console's catalogue (hash <hash>) | approved | |
| +| EP-8 | explain_cmd.go | reference <code>\nwhen <time>\ntier <tier> | approved | |
| +| EP-9 | explain_cmd.go | request <method> <path> on <host>, answered <status> | approved | |
| +| EP-10 | explain_cmd.go | request not kept. it was sampled away, or is older than 7 days | approved | |
| +| EP-11 | explain_cmd.go | request the records could not be read just now. try again in a minute | approved | |
| +| EP-12 | explain_cmd.go | no reference code like that for this app. check the code, and that it came from one of this app's pages | approved | |
| +| EP-13 | explain_cmd.go | rule <rule> | approved | |
| +| EP-14 | main.go (a fragment of the usage text) | explain what a reference code from a page the edge answered says | approved | |
| + |
| +## Docs |
| + |
| +| id | file | text | status | |
| +|---|---|---|---| |
| +| EP-3 | docs/site/cli.md | `carlos explain <code> --app <a>` reads a reference code from a page the platform's edge protection answered. It says which rule fired and when, and shows the request while a record of it is kept, for 7 days. | approved | |
diff --git a/docs/superpowers/plans/2026-10-25-edge-protection-2-hard-probe-watch.md b/docs/superpowers/plans/2026-10-25-edge-protection-2-hard-probe-watch.md| new file mode 100644 |
| index 000000000..7508af4f0 |
| --- /dev/null |
| +++ b/docs/superpowers/plans/2026-10-25-edge-protection-2-hard-probe-watch.md |
| @@ -0,0 +1,411 @@ |
| +# Edge protection Plan 2: hard and probe tiers in watch mode |
| + |
| +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. |
| + |
| +**Goal:** Every app gets the hard tier and the probe catalogue, matched on path structure before the cache and the activator. Every match is recorded as a watch with the app's real answer. Block mode exists and is tested, but it is off fleet-wide. The console and a new CLI verb explain a reference code by rule name. |
| + |
| +**Architecture:** A new package `internal/edgeguard` holds the catalogue (an embedded, versioned data file) and a matcher that does no allocation on ordinary paths. The edge runs it once per request in `ServeHTTP`, in front of the password gate. It leaves the verdict on the request's `outcome`, and the observer defer files one `reqrec.Match` with the real status instead of a `reqrec.Response`. On a local static site, the static handler decides probe matches itself, because it knows exactly which files exist. It also re-checks a rewritten file against the hard tier. Block mode answers `404` with a sealed reference code. The console maps a code's rule hash back to the catalogue's rule id, and `carlos explain <code>` prints it. |
| + |
| +**Tech Stack:** Go 1.26 (`go:embed`, `net/http`), the existing `internal/reqrec` (Plan 1), `internal/edge`, `internal/console`, the root CLI (package `main`). |
| + |
| +**Spec:** `docs/superpowers/specs/2026-10-24-edge-request-protection-design.md` (approved 2026-10-24). This plan is §8 step 2. Plan 1 (`docs/superpowers/plans/2026-10-24-edge-protection-1-request-records.md`, merged 6e2d9817) built the records and codes this plan uses. |
| + |
| +## Rulings made writing this plan |
| + |
| +These are the planner's calls. Each says what it costs if wrong. |
| + |
| +- **R1. Everything watches in this plan.** Spec §5.1 says the hard tier blocks by default. Spec §8 step 2 says the hard and probe tiers run in watch mode fleet-wide for the calibration window. §8 is the rollout order, so it wins. Every catalogue entry ships in mode `watch`. Promotion to `block`, the hard override, the deploy-time warning, the technology switch, learned exemptions and the probe-burst limit (§5.5) are Plan 3. All of them only matter once something blocks. If wrong: leaks stay served for the 14-day window, as they are today. |
| +- **R2. A box-level mode switch, `CARLOS_EDGE_PROTECT`.** Values: unset (each rule's catalogue mode), `off` (no checks), `watch` (every rule watches), `block` (every rule blocks, except `burst` rules). `block` exists so dev boxes can exercise the block page, the codes and `carlos explain` end to end. It must not be set on the flagship in this plan. It is read once when the edge is built, as `CARLOS_EDGE_GZIP` is. If wrong: one env var to remove. |
| +- **R3. Some of the spec's hard-tier extensions go in the probe tier.** The spec lists `.sql`, `.sql.gz`, `.sqlite` and `.db` dumps by extension as hard, and gives the rule "a hard entry must be something no deployed app should ever serve" (§5.2). Static sites do serve `.sqlite` and `.db` files to the browser on purpose (sql.js and its HTTP VFS), and `.sql` schema downloads are plausible. So they are probe entries, which are served when the file exists. The well-known root dump names (`/db.sql`, `/dump.sql`, `/backup.sql`, `/database.sql`) stay hard. `*.bak` goes in the probe tier. `*.old` is left out. If wrong: Plan 3's review promotes them. |
| +- **R4. Admin panels are mode `burst`.** They are matched and watched, so calibration sees them and Plan 3's burst limit can use them. No mode, forced or not, ever blocks them (spec §5.3). |
| +- **R5. Where the check runs.** |
| + - Skipped for requests that arrived through a tunnel (`fromTunnel`): the hub that forwarded them already checked them and records them. This matches Plan 1's `observeRecords`. |
| + - Run on hopped requests (the sending edge had no route, so it checked nothing). |
| + - Skipped for door callers (`isDoor`): those are the app's own code, not public traffic. |
| + - Skipped for `Kind == "status"` routes, which get no outcome. |
| + - On a hub, a static site served over a tunnel is checked as an app whose routes are unknown. The hub cannot see the far box's files. If wrong: such a site's watch records over-report probe matches until Plan 3 decides. |
| +- **R6. One verdict per request, first one wins.** The `ServeHTTP` check runs first. The static handler adds a verdict only if there is none yet. This carries out Plan 1's handoff: "never call Response and Match for one request". |
| +- **R7. Watch records carry no reference code.** Codes are for pages a visitor sees. Only blocks mint one. |
| +- **R8. Lookups of codes are already rate-limited.** The instance gate in front of `GET …/edge-refs/{code}` spends `s.cli.instances` (60 a minute per token, `internal/console/apiinstances.go:96`). No new limiter. The Plan 1 handoff asked for "lookups rate-limited", and this is it. Unverified codes are shown as unchecked by the CLI (Task 5). |
| +- **R9. Add `CARLOS_EDGE_PROTECT` and `CARLOS_EDGE_RECORDS` to `hostenv.Optional`.** That way a group box takes them from the parameter store like `CARLOS_EDGE_GZIP`. Plan 1 left `CARLOS_EDGE_RECORDS` out. |
| +- **R10. The calibration report is Plan 3's.** The records this plan writes are its input. Plan 3 also has to write the report, review it and promote. |
| +- **R11. The two §9 requests are filed with this plan.** One asks the framework for route lists in the release manifest. The other asks #366 for the rootfs image's file list. The probe tier's existence for framework and rootfs apps waits on both, and Plan 3's blocking of unknown apps should not start before the answers are known. Task 6 files them. |
| + |
| +## Global Constraints |
| + |
| +- Rules match path structure, never a word inside a path: exact path, prefix on segment boundaries, whole segment, final-segment extension, segment sequence, or one named query parameter's value prefix (spec §4 anti-goals, §5.3). |
| +- Matching is case-insensitive, on the decoded path with `\` treated as `/`, and on one further percent-decoding when the decoded path still holds a `%` (spec §5.2). |
| +- `/.well-known/` is exempt from every rule except traversal (spec §5.2). |
| +- Hard and probe checks run before the password gate, the upgrade branch, the cache and the activator, so a check never waits on a wake (spec §5.3, `internal/edge/edge.go` around the gate). |
| +- A watched request is forwarded unchanged. Its record carries the upstream status and whether it woke the app (spec §7, "Calibration needs more"). |
| +- Hard and probe blocks answer `404`, `Content-Type: text/plain; charset=utf-8`, `Cache-Control: no-store`, the code in the `X-Carlos-Ref` header and in the body (spec §5.1). |
| +- No storage write per request. Records go through `reqrec.Recorder` only (spec §7). |
| +- Provider-neutral: nothing here touches AWS or a plan catalog. |
| +- User-facing words are pending until copy review. Their text lives in `docs/superpowers/plans/2026-10-25-edge-protection-2-copy.md` and is used verbatim. No em dashes in any copy (house rule). Platform docs use neutral names (`shop`, `example.com`), never tenant names. |
| +- Local test runs cover only the touched packages, with `-run` (house rule). CI runs everything. Cross-compiles for darwin and windows must still build (nothing here is Linux-only). |
| + |
| +## Review Focus |
| + |
| +1. **Case and encoding tricks:** `/.ENV`, `/.Git/config`, `/%2eenv` (a decoded path still holding `%2e` came from `%252e`), `/static/..%5c.env` and `/x/..;/.env`. All must match the hard tier. Test in Task 1 (`TestCheckEncodingTricks`). |
| +2. **Real paths that look close:** `/wp-content/uploads/…png`, `/assets/admin/app-3f2a.js`, `PMA_FULL_LOGO.png`, `photo..jpg`, `.envoy`, `/index.php-guide`. None may match. Test in Task 1 (`TestCheckMisfireCorpus`). |
| +3. **A 1 MiB path:** must complete in linear time with a bounded number of allocations, and still match a `.env` segment at its far end. Test in Task 1 (`TestCheckLongPath`). |
| +4. **A static site with a single-page splat** (`/* /index.html 200`) asked for `/wp-login.php`: still a probe match, because a splat is not existence. Test in Task 3 (`TestStaticSplatIsNotExistence`). |
| +5. **A watched probe the app answers 200, on a hibernating instance:** the record says `status=200`, `woke=1`, kind `watch` and no `ref`, and there is exactly one record for the request. Test in Task 2 (`TestGuardWatchRecordsUpstreamStatus`). |
| + |
| +--- |
| + |
| +### Task 1: The catalogue and its matcher (`internal/edgeguard`) |
| + |
| +**Files:** |
| +- Create: `internal/edgeguard/catalogue.txt` (embedded data) |
| +- Create: `internal/edgeguard/catalogue.go` (parse, `Rule`, `Mode`, lookup) |
| +- Create: `internal/edgeguard/match.go` (`Check`) |
| +- Test: `internal/edgeguard/catalogue_test.go`, `internal/edgeguard/match_test.go` |
| + |
| +**Interfaces:** |
| +- Consumes: `reqrec.Tier` (`TierHard`, `TierProbe`), `reqrec.RuleHash(string) uint32`. |
| +- Produces: |
| + - `type Mode uint8` with `ModeWatch`, `ModeBlock`, `ModeBurst`, and `func (m Mode) String() string` returning `"watch" | "block" | "burst"`. |
| + - `type Rule struct { ID, Group string; Tier reqrec.Tier; Mode Mode }`. ID is `<tier>.<group>.<name>`, for example `hard.secrets.env`. |
| + - `type Hit struct { Rule *Rule; Fragment string; FromQuery bool; QueryName string }`. Fragment is the raw matched text: a segment, a path, or a query value. |
| + - `func Check(path, rawQuery string) (Hit, bool)`. `path` is `r.URL.Path` (already decoded once). Hard rules are tried before probe rules, and each tier in file order. |
| + - `func CheckTier(path, rawQuery string, tier reqrec.Tier) (Hit, bool)`: the same, limited to one tier (Task 3 uses it). |
| + - `func RuleByHash(h uint32) (*Rule, bool)` and `func Rules() []Rule`. |
| + - `const Version` is the catalogue's `# version N` line, parsed. Plan 2 ships version 1. |
| + |
| +- [ ] **Step 1: Write the catalogue file.** Format: one rule per line, `#` comments, blank lines ignored, whitespace-separated columns `tier group name kind pattern mode`. `tier` is `hard` or `probe`. `group` and `name` match `[a-z0-9-]+`. Patterns are lower case. `kind` is one of: |
| + - `exact`: the cleaned path equals the pattern. |
| + - `prefix`: the cleaned path equals the pattern, or starts with the pattern followed by `/`. |
| + - `segment`: some segment equals the pattern. |
| + - `segglob`: some segment matches a pattern holding one `*`. |
| + - `ext`: the final segment is longer than the pattern and ends with it. |
| + - `segseq`: the pattern's segments appear consecutively. |
| + - `qparam`: the pattern is `name=valueprefix`. A value of that query parameter, lower-cased, starts with `valueprefix`. |
| + - `dotdot`: the pattern is `-`. Some segment is `..`, before cleaning. |
| + |
| + The first line is `# version 1`. Contents, in this order: |
| + |
| +``` |
| +# version 1 |
| +# tier group name kind pattern mode |
| +hard traversal dotdot dotdot - watch |
| +hard traversal proc-self segseq proc/self watch |
| +hard traversal vite-fs segment @fs watch |
| +hard secrets env segment .env watch |
| +hard secrets env-variant segglob .env.* watch |
| +hard secrets git segment .git watch |
| +hard secrets git-credentials segment .git-credentials watch |
| +hard secrets svn segment .svn watch |
| +hard secrets hg segment .hg watch |
| +hard secrets aws segment .aws watch |
| +hard secrets ssh segment .ssh watch |
| +hard secrets docker segment .docker watch |
| +hard secrets kube segment .kube watch |
| +hard secrets npmrc segment .npmrc watch |
| +hard secrets pypirc segment .pypirc watch |
| +hard secrets netrc segment .netrc watch |
| +hard secrets htpasswd segment .htpasswd watch |
| +hard keys id-rsa segment id_rsa watch |
| +hard keys id-dsa segment id_dsa watch |
| +hard keys id-ecdsa segment id_ecdsa watch |
| +hard keys id-ed25519 segment id_ed25519 watch |
| +hard keys credentials-json segment credentials.json watch |
| +hard keys gcp-credentials segment gcp-credentials.json watch |
| +hard keys firebase-admin segglob firebase-adminsdk*.json watch |
| +hard dumps db-sql exact /db.sql watch |
| +hard dumps dump-sql exact /dump.sql watch |
| +hard dumps backup-sql exact /backup.sql watch |
| +hard dumps database-sql exact /database.sql watch |
| +hard source php-save ext .php.save watch |
| +hard source php-bak ext .php.bak watch |
| +hard source php-old ext .php.old watch |
| +hard source php-swp ext .php.swp watch |
| +hard source php-tilde ext .php~ watch |
| +probe wordpress wp-login exact /wp-login.php watch |
| +probe wordpress xmlrpc exact /xmlrpc.php watch |
| +probe wordpress wp-links-opml exact /wp-links-opml.php watch |
| +probe wordpress wp-admin prefix /wp-admin watch |
| +probe wordpress wp-json prefix /wp-json watch |
| +probe wordpress site-wp-json prefix /site/wp-json watch |
| +probe wordpress news-wp-json prefix /news/wp-json watch |
| +probe wordpress cms-wp-json prefix /cms/wp-json watch |
| +probe wordpress blog-wp-json prefix /blog/wp-json watch |
| +probe wordpress wp-wp-json prefix /wp/wp-json watch |
| +probe wordpress wordpress-dir prefix /wordpress watch |
| +probe wordpress press-wp-json prefix /press/wp-json watch |
| +probe phpframework phpunit prefix /vendor/phpunit watch |
| +probe phpframework composer-json exact /vendor/composer/installed.json watch |
| +probe phpframework ignition prefix /_ignition watch |
| +probe phpframework telescope prefix /telescope watch |
| +probe phpframework debugbar prefix /_debugbar watch |
| +probe phpframework profiler-phpinfo prefix /_profiler/phpinfo watch |
| +probe phpframework thinkphp qparam s=/index/\think watch |
| +probe phpmyadmin phpmyadmin prefix /phpmyadmin watch |
| +probe phpmyadmin pma prefix /pma watch |
| +probe php php ext .php watch |
| +probe java actuator prefix /actuator watch |
| +probe java action ext .action watch |
| +probe java do ext .do watch |
| +probe java jsp ext .jsp watch |
| +probe cgi cgi-bin prefix /cgi-bin watch |
| +probe cgi setup-cgi exact /setup.cgi watch |
| +probe cgi hnap1 exact /hnap1 watch |
| +probe cgi gponform prefix /gponform watch |
| +probe status server-status prefix /server-status watch |
| +probe status server-info prefix /server-info watch |
| +probe metadata meta-data prefix /latest/meta-data watch |
| +probe devconfig docker-compose exact /docker-compose.yml watch |
| +probe devconfig dockerfile exact /dockerfile watch |
| +probe devconfig gitlab-ci exact /.gitlab-ci.yml watch |
| +probe dumps sql ext .sql watch |
| +probe dumps sql-gz ext .sql.gz watch |
| +probe dumps sqlite ext .sqlite watch |
| +probe dumps sqlite3 ext .sqlite3 watch |
| +probe dumps db ext .db watch |
| +probe dumps bak ext .bak watch |
| +probe admin admin exact /admin burst |
| +probe admin admin-login exact /admin/login burst |
| +probe admin admin-settings exact /admin/settings burst |
| +probe admin admin-dashboard exact /admin/dashboard burst |
| +probe admin administrator prefix /administrator burst |
| +``` |
| + |
| +- [ ] **Step 2: Write the failing catalogue tests** in `catalogue_test.go`: |
| + - `TestCatalogueParses`: `Rules()` is non-empty, `Version == 1`, every ID is unique and has the form `tier.group.name`, and the hard rules all come before the probe rules. |
| + - `TestCatalogueRuleHashesUnique`: no two IDs share `reqrec.RuleHash`. For every rule, `RuleByHash(reqrec.RuleHash(r.ID))` returns that rule. |
| + - `TestCatalogueAdminIsBurst`: every rule in group `admin` has `ModeBurst`, and no other rule does. |
| + - `TestParseRejects`: the unexported parser (`parseCatalogue([]byte) ([]Rule, int, error)`) refuses an upper-case pattern, an unknown kind, an unknown mode, a duplicate ID, a `segglob` with zero or two `*`, a `qparam` without `=`, and a missing version line. Each refusal names the line number. |
| + |
| +- [ ] **Step 3: Write the failing match tests** in `match_test.go`. Table-driven, each case `{path, rawQuery, wantID}`, with `""` meaning no match: |
| + - `TestCheckHardTier`: `/.env`→`hard.secrets.env`, `/.env.local`, `/.env.production` and `/backend/.env`→env or env-variant (assert the exact ID per row: `/.env.local`→`hard.secrets.env-variant`), `/.git/config` and `/.git/HEAD`→`hard.secrets.git`, `/.git-credentials`→`hard.secrets.git-credentials`, `/.aws/credentials`→`hard.secrets.aws`, `/.docker/config.json`→`hard.secrets.docker`, `/credentials.json`→`hard.keys.credentials-json`, `/gcp-credentials.json`→`hard.keys.gcp-credentials`, `/firebase-adminsdk.json` and `/firebase-adminsdk-x1y2.json`→`hard.keys.firebase-admin`, `/@fs/.env`→`hard.traversal.vite-fs` (file order puts traversal first), `/@fs/proc/self/environ`→`hard.traversal.vite-fs`, `/x/proc/self/environ`→`hard.traversal.proc-self`, `/static/../.env`→`hard.traversal.dotdot`, `/db.sql`→`hard.dumps.db-sql`, `/index.php.save`→`hard.source.php-save`, `/home/.ssh/id_rsa`→`hard.secrets.ssh`, `/id_ed25519`→`hard.keys.id-ed25519`. |
| + - `TestCheckProbeTier`: `/wp-login.php`→`probe.wordpress.wp-login`, `/xmlrpc.php`→`probe.wordpress.xmlrpc`, `/blog/wp-json/wp/v2/users`→`probe.wordpress.blog-wp-json`, `/wp-admin/install.php`→`probe.wordpress.wp-admin`, `/info.php`→`probe.php.php`, `/_profiler/phpinfo`→`probe.phpframework.profiler-phpinfo`, `/vendor/phpunit/phpunit/src/Util/PHP/eval-stdin.php`→`probe.phpframework.phpunit`, `/_ignition/execute-solution`→`probe.phpframework.ignition`, `/vendor/composer/installed.json`→`probe.phpframework.composer-json`, `("/", "s=/index/\\think\\app/invokefunction")`→`probe.phpframework.thinkphp`, `/phpmyadmin/index.php`→`probe.phpmyadmin.phpmyadmin`, `/pma/`→`probe.phpmyadmin.pma`, `/actuator/env`→`probe.java.actuator`, `/login.action`→`probe.java.action`, `/index.jsp`→`probe.java.jsp`, `/cgi-bin/luci`→`probe.cgi.cgi-bin`, `/HNAP1`→`probe.cgi.hnap1`, `/GponForm/diag_Form`→`probe.cgi.gponform`, `/server-status`→`probe.status.server-status`, `/latest/meta-data/iam/`→`probe.metadata.meta-data`, `/Dockerfile`→`probe.devconfig.dockerfile`, `/.gitlab-ci.yml`→`probe.devconfig.gitlab-ci`, `/backup/site.sql`→`probe.dumps.sql`, `/data/app.sqlite`→`probe.dumps.sqlite`, `/admin`→`probe.admin.admin`, `/administrator/`→`probe.admin.administrator`. |
| + - `TestCheckEncodingTricks` (Review Focus 1): `/.ENV`→`hard.secrets.env`, `/.Git/config`→`hard.secrets.git`, `/%2eenv`→`hard.secrets.env`, `/static/%2e%2e/.env`→`hard.traversal.dotdot`, `/static/..\\.env`→`hard.traversal.dotdot`, `/x/..;/.env`→`hard.traversal.dotdot`, `/.env;x=1`→`hard.secrets.env`, `//.env`→`hard.secrets.env`, `/./.git/config`→`hard.secrets.git`. |
| + - `TestCheckWellKnownExempt`: `/.well-known/acme-challenge/abc`, `/.well-known/security.txt` and `/.well-known/.env` all give no match. `/.well-known/../.env` still gives `hard.traversal.dotdot`. |
| + - `TestCheckMisfireCorpus` (Review Focus 2, spec §3): each of these gives no match. |
| + - Paths: `/help/vat-in-the-european-union`, `/docs/display-a-selection-of-tickets`, `/docs/update-the-widget-from-version-1`, `/en/articles/how-do-i-delete-a-hub`, `/help/export-attendees-from-all-events`, `/docs/embeddable-javascript-widget`, `/assets/admin/application-3f2a9c.js`, `/favicon-admin-32.png`, `/help/the-admin-pane`, `/wp-content/uploads/2024/05/logo.png`, `/uploads/PMA_FULL_LOGO.png`, `/img/photo..jpg`, `/en/articles/\"https:/x.example\"`, `/api/union/members`, `/env`, `/environment`, `/blog/.envoy`, `/docs/index.php-guide`, `/products/admin-chair`, `/static/app.min.js`, `/todo`, `/telescopes`. |
| + - Queries on `/`: `redirect_uri=https://example.com/cb`, `sig=ZXZhbCBkcm9wIHVuaW9u`, `s=search+terms`. |
| + - `TestCheckLongPath` (Review Focus 3): a path of 1 MiB of `/a` segments ending `/.env` gives `hard.secrets.env`, and `testing.AllocsPerRun` on it is at most 4. |
| + - `TestCheckOrdinaryPathAllocs`: `testing.AllocsPerRun(100, …)` on `Check("/blog/2026/10/some-article-slug", "")` and on `Check("/assets/app-3f2a9c.js", "v=2")` is 0. |
| + - `BenchmarkCheckOrdinary`: same two inputs. Informational only, not asserted. |
| + |
| +- [ ] **Step 4: Run the tests to see them fail.** Run `go test ./internal/edgeguard/ -run 'TestCatalogue|TestParse|TestCheck' -count=1`. Expected: FAIL (package does not build). |
| + |
| +- [ ] **Step 5: Implement `catalogue.go`.** `//go:embed catalogue.txt`. Parse once at package init with `parseCatalogue`. A parse error panics at init: the file ships in the binary, and the tests catch a bad edit. Build the index structures: |
| + - a map for `exact`; |
| + - a map for `segment`; |
| + - a map keyed by first segment for `prefix`; |
| + - small slices for `segglob`, `ext`, `segseq` and `qparam`; |
| + - a map from hash to rule. |
| + |
| + Each index keeps file order within its tier. |
| + |
| +- [ ] **Step 6: Implement `match.go`.** |
| + - `Check` runs over one or two forms of the path: the path as given, and, only when it contains `%`, `url.PathUnescape` of it (ignore the error and skip that form). |
| + - For each form, read it as lower case with `\` as `/`, without allocating when the path has neither upper case nor `\`. |
| + - The `dotdot` rule looks at raw segments. A segment is the text up to `;`. |
| + - The other kinds look at the segments of `path.Clean("/"+form)`. Strip any `;…` from each segment before comparing. |
| + - If the first segment is `.well-known`, only `dotdot` is tried. |
| + - `qparam` uses `url.ParseQuery` only when `rawQuery` contains the parameter's name. A parse error keeps the pairs that did parse. |
| + - Walk segments by index, not with `strings.Split`, so an ordinary path allocates nothing. |
| + |
| +- [ ] **Step 7: Run the tests to see them pass.** Run `go test ./internal/edgeguard/ -count=1 -bench BenchmarkCheckOrdinary -benchtime=10000x`. Expected: PASS. Report the benchmark ns/op in the task report. |
| + |
| +- [ ] **Step 8: Commit.** |
| + |
| +```bash |
| +git add internal/edgeguard |
| +git commit -m "edgeguard: the hard tier and probe catalogue, matched on path structure" |
| +``` |
| + |
| +### Task 2: The edge runs the guard once per request |
| + |
| +**Files:** |
| +- Create: `internal/edge/guard.go` |
| +- Modify: `internal/edge/edge.go` (the field on `Edge`, set in `New`; the call in `ServeHTTP` after the observer defer and before the password gate) |
| +- Modify: `internal/edge/answered.go` (`outcome` gains `guard *guardState`) |
| +- Modify: `internal/edge/reqrecords.go` (replace `recordMatch` with `mintRef`; `observeRecords` files a `Match` when the outcome holds a verdict) |
| +- Modify: `internal/edge/reqrecords_test.go` (the three `recordMatch` tests move to `mintRef` and to the defer) |
| +- Modify: `internal/hostenv/hostenv.go` (R9: add `CARLOS_EDGE_PROTECT` and `CARLOS_EDGE_RECORDS` to `Optional`, keeping the list sorted) |
| +- Test: `internal/edge/guard_test.go` |
| + |
| +**Interfaces:** |
| +- Consumes: `edgeguard.Check`, `edgeguard.Rule`, `edgeguard.Mode*`, `reqrec.NewRef`, `reqrec.Fragment(reqrec.SourcePath|SourceQuery, name, value)`, `reqrec.Match`, `e.homes.Load().meshKeys()`, `e.box`. |
| +- Produces (used by Task 3): |
| + - `type guardMode uint8` with `guardCatalogue` (zero value), `guardOff`, `guardWatch`, `guardBlock`. |
| + - `func guardModeFromEnv(getenv func(string) string) guardMode` reads `CARLOS_EDGE_PROTECT`. It trims and lower-cases the value. `off`, `watch` and `block` map to the matching mode. Anything else, including unset, is `guardCatalogue`, and an unknown value is logged once. |
| + - `type guardVerdict struct { rule *edgeguard.Rule; frag string; block bool; ref string }`. |
| + - `type guardState struct { mode guardMode; mint func(reqrec.Tier, string) string; verdict *guardVerdict }`. `outcome` gains `guard *guardState`. `ServeHTTP` sets it whenever the guard runs for the request. A nil `guard` means the guard is off for this request, as for door callers, tunnel-delivered requests and mode `off`. |
| + - `func (m guardMode) blocks(rule *edgeguard.Rule) bool`: `guardOff` and `guardWatch` never block. `guardBlock` blocks every rule except `ModeBurst`. `guardCatalogue` blocks only `ModeBlock` rules. |
| + - `func guardDecide(w http.ResponseWriter, r *http.Request, hit edgeguard.Hit) (served bool)` is package-level, so the static handler, which has no `*Edge`, can call it. It reads the request's `guardState`, does nothing when that is nil or already holds a verdict, and otherwise notes the verdict. In block mode it mints a code with `state.mint`, writes the block response and returns true. |
| + - `func writeGuardBlock(w http.ResponseWriter, code string)` writes the `404` (Global Constraints) with the body from copy row EP-1. |
| + - `func (e *Edge) mintRef(tier reqrec.Tier, ruleID string) string` replaces `recordMatch`. It holds the mint half: mesh key, box, `time.Now()`. `ServeHTTP` passes `e.mintRef` as `guardState.mint`. |
| + - `func outcomeFrom(r *http.Request) *outcome` (if no such accessor exists yet; reuse the one `MarkWoke` uses if it does). |
| + |
| +- [ ] **Step 1: Write the failing tests** in `guard_test.go`. Build the edge as `reqrecords_test.go` does, with a fake `RequestRecorder` that keeps every `Response` and `Match`. Assertions: |
| + - `TestGuardModeFromEnv`: `""`→catalogue, `"off"`→off, `" Watch "`→watch, `"block"`→block, `"bogus"`→catalogue. |
| + - `TestGuardWatchForwards`: in mode catalogue (every rule watches), `GET /.env` on an instance route reaches the upstream, which answers 404. The client gets the upstream's 404 body. The recorder has exactly one `Match` (`Kind` watch, `Tier` hard, `RuleID` `hard.secrets.env`, `Status` 404, `Ref` empty) and no `Response`. |
| + - `TestGuardWatchRecordsUpstreamStatus` (Review Focus 5): on a hibernating route whose fake activator wakes it and calls `MarkWoke`, `GET /wp-login.php` answered 200 by the app gives one `Match` with `Status` 200, `WokeKnown` true, `Woke` true, and `Kind` watch. |
| + - `TestGuardBlockMode`: with `guardBlock`, `GET /.git/config` gets 404 with `Content-Type: text/plain; charset=utf-8` and `Cache-Control: no-store`. The `X-Carlos-Ref` header equals the code in the body. `reqrec.ParseRef(code, meshKey)` verifies with `Tier` hard and `RuleHash == reqrec.RuleHash("hard.secrets.git")`. The upstream and the activator were never called. The recorder has one `Match` (`Kind` block, `Ref` == code, `Status` 404, `WokeKnown` true, `Woke` false) and no `Response`. |
| + - `TestGuardBlockModeSparesBurst`: with `guardBlock`, `GET /admin` is forwarded, and its `Match` is a watch. |
| + - `TestGuardBeforeGateAndCache`: with `guardBlock`, a gated route (`Gate` set) asked for `/.env` without a cookie gets the guard's 404, not the login page. A cached response stored for `/.env` (seeded with `e.cache.Put`) is not served. |
| + - `TestGuardOffDoesNothing`: with `guardOff`, `GET /.env` is forwarded, and the recorder has one `Response` and no `Match`. |
| + - `TestGuardSkipsTunnelDelivered`: a request whose context carries the tunnel mark (as `TestRecordsSkipTunnelDelivered` builds it) is forwarded with no verdict, even in `guardBlock`. |
| + - `TestGuardOrdinaryRequestUntouched`: `GET /blog/post` gets one `Response` and no `Match`, and `outcome.guard` stays nil. |
| + - `TestMintRefSealed` and `TestMintRefUnsealed`: the old `recordMatch` code tests, moved to `mintRef`. |
| + |
| +- [ ] **Step 2: Run the tests to see them fail.** Run `go test ./internal/edge/ -run 'TestGuard|TestMintRef|TestRecords' -count=1`. Expected: FAIL (undefined: `guardModeFromEnv` …). |
| + |
| +- [ ] **Step 3: Implement `guard.go`, and the changes to `answered.go` and `reqrecords.go`.** |
| + - `observeRecords` keeps its `fromTunnel` return. |
| + - With `out.guard != nil && out.guard.verdict != nil` it files `reqrec.Match{Response: x, Kind: block or watch, Tier: rule.Tier, RuleID: rule.ID, Fragment: frag, Ref: ref}`. |
| + - `x` is `requestResponse(...)` with the real status. For a watch, `WokeKnown = !viaTunnel` and `Woke = out.woke`. For a block, `WokeKnown = true` and `Woke = false`. |
| + - Otherwise it files the `Response` exactly as today. |
| + - `frag` comes from `reqrec.Fragment(reqrec.SourcePath, "", hit.Fragment)`. When `hit.FromQuery` is set, it comes from `reqrec.Fragment(reqrec.SourceQuery, hit.QueryName, hit.Fragment)` instead. |
| + - A fragment that may not be kept is stored as `""`. |
| + |
| +- [ ] **Step 4: Wire `ServeHTTP`.** |
| + - In `New`: `e.guard = guardModeFromEnv(os.Getenv)`, next to `gzipOn`. |
| + - In `ServeHTTP`, inside the `up.route.Kind != "status"` block after `withOutcome`, set `out.guard = &guardState{mode: e.guard, mint: e.mintRef}` when all of these hold: |
| + - `e.guard != guardOff`; |
| + - `!isDoor`; |
| + - `!fromTunnel(r.Context())`. |
| + - Immediately before the password-gate block (`if loginPost && up.route.Gate == ""`), when `out != nil && out.guard != nil`, check once: |
| + - When `up.route.Kind == "static" && !up.viaTunnel`, Task 3 decides the probe tier, so call `edgeguard.CheckTier(r.URL.Path, r.URL.RawQuery, reqrec.TierHard)`. |
| + - For every other route, call `edgeguard.Check`. |
| + - On a hit, call `guardDecide`. If it returns true, return. |
| + - `out` must be visible at that point: hoist its declaration out of the `if` block. Keep the defer where it is. |
| + |
| +- [ ] **Step 5: Run the tests to see them pass.** Run `go test ./internal/edge/ -run 'TestGuard|TestMintRef|TestRecords|TestGate|TestCache' -count=1` and `go test ./internal/hostenv/ -count=1`. Expected: PASS. |
| + |
| +- [ ] **Step 6: Commit.** |
| + |
| +```bash |
| +git add internal/edge internal/hostenv |
| +git commit -m "edge: run the hard and probe tiers once per request, watch by default" |
| +``` |
| + |
| +### Task 3: Static sites decide probe matches from their own files |
| + |
| +**Files:** |
| +- Modify: `internal/edge/static.go` (`serveTree`) |
| +- Modify: `internal/edge/redirects.go` (add `names`) |
| +- Test: `internal/edge/static_guard_test.go` |
| + |
| +**Interfaces:** |
| +- Consumes: Task 2's `guardDecide`, `outcomeFrom`, `outcome.guard`; `edgeguard.CheckTier`. |
| +- Produces: `func (rs *redirectRules) names(host, p string) bool`. It is true when some rule without splat and without `:placeholder` segments matches `p` for `host`. A nil `rs` is false. |
| + |
| +- [ ] **Step 1: Write the failing tests** in `static_guard_test.go`. Use the static test tree helpers in `static_test.go`. The edge runs in mode catalogue (watch) unless a test says `guardBlock`. Each test asserts the recorder's single `Match` or `Response`. |
| + - `TestStaticProbeAbsentIsMatched`: a tree without `wp-login.php`, asked `GET /wp-login.php`, gives a watch `Match` `probe.wordpress.wp-login` with `Status` 404. In `guardBlock` the response is the guard's 404 with `X-Carlos-Ref`. |
| + - `TestStaticProbePresentIsServed`: a tree holding `wp-login.php` (and, in a second case, `admin/index.html` for `/administrator/`) is served with its bytes and 200, in `guardBlock` too, and there is no `Match`. |
| + - `TestStaticSplatIsNotExistence` (Review Focus 4): with `_redirects` holding `/* /index.html 200`, `GET /wp-login.php` gives a probe `Match`. In `guardBlock` it is blocked, not the fallback page. |
| + - `TestStaticExplicitRedirectIsExistence`: with `_redirects` holding `/xmlrpc.php /api/rpc.html 200`, `GET /xmlrpc.php` is served, with no `Match`. |
| + - `TestStaticRewriteToHardFile`: a tree holding `.env` (packed through the test helper, not `PackDir`, which would refuse it if it does) and `_redirects` holding `/download /.env 200`. `GET /download` gives a hard `Match` `hard.secrets.env`, and in `guardBlock` the guard's 404. In the default mode the file is served (watch). |
| + - `TestStaticHardAtEdgeOnce`: `GET /.env` on a static site gives exactly one `Match`. The `ServeHTTP` check saw it first, and `serveTree` added nothing. |
| + |
| +- [ ] **Step 2: Run the tests to see them fail.** Run `go test ./internal/edge/ -run 'TestStatic' -count=1`. Expected: the new tests FAIL. |
| + |
| +- [ ] **Step 3: Implement.** |
| + - In `serveTree`, after the redirect loop has settled `found` for the request path (before `if !found`): if the outcome has no verdict and `CheckTier(r.URL.Path, r.URL.RawQuery, reqrec.TierProbe)` hits, the hit counts only when `!found && !tree.redirects.names(requestHost(r.Host), p)`. Then `guardDecide`, and return if it served. |
| + - When a rewrite set `rewritten`, run `CheckTier(p, "", reqrec.TierHard)` on the rewritten file path before `serveFile`, with the same `guardDecide`. |
| + - Do nothing when `outcomeFrom(r)` is nil or its `guard` is nil. `guardDecide` already declines when a verdict exists. Check that first anyway, so `serveTree` skips the matcher too. |
| + |
| +- [ ] **Step 4: Run the tests to see them pass.** Run `go test ./internal/edge/ -run 'TestStatic|TestRedirect|TestGuard' -count=1`. Expected: PASS. |
| + |
| +- [ ] **Step 5: Commit.** |
| + |
| +```bash |
| +git add internal/edge |
| +git commit -m "edge: static sites serve probe paths they have, and never a rewrite onto a leak" |
| +``` |
| + |
| +### Task 4: The console names the rule behind a code |
| + |
| +**Files:** |
| +- Modify: `internal/console/apiedgeref.go` |
| +- Test: `internal/console/apiedgeref_test.go` |
| + |
| +**Interfaces:** |
| +- Consumes: `edgeguard.RuleByHash`. |
| +- Produces: `apiEdgeRef` gains `Sealed bool \`json:"sealed"\``, `Rule string \`json:"rule,omitempty"\`` and `Group string \`json:"group,omitempty"\``. Task 5 reads them. |
| + |
| +- [ ] **Step 1: Write the failing tests:** |
| + - `TestAPIEdgeRefNamesCatalogueRule`: a sealed code for `hard.secrets.env` gives `rule == "hard.secrets.env"`, `group == "secrets"`, `sealed == true` and `verified == true`. |
| + - `TestAPIEdgeRefUnknownRule`: a code for rule id `tenant-x` gives no `rule` or `group` field, and the `rule_hash` is still present. |
| + - `TestAPIEdgeRefUnsealed`: an unsealed code gives `sealed == false` and `verified == false`. |
| + |
| +- [ ] **Step 2: Run them to see them fail.** Run `go test ./internal/console/ -run TestAPIEdgeRef -count=1`. Expected: FAIL. |
| + |
| +- [ ] **Step 3: Implement.** Fill `Sealed` from `ref.Sealed`. Fill `Rule` and `Group` when `RuleByHash(ref.RuleHash)` finds a rule whose tier equals `ref.Tier`. |
| + |
| +- [ ] **Step 4: Run the tests to see them pass.** Same command. Expected: PASS. Also run `go test ./internal/console/ -run 'TestClaimConsoleRouteCensus|TestSvcRoutes' -count=1`. The route table is unchanged, so it passes as before. |
| + |
| +- [ ] **Step 5: Commit.** |
| + |
| +```bash |
| +git add internal/console |
| +git commit -m "console: a reference code names its catalogue rule" |
| +``` |
| + |
| +### Task 5: `carlos explain`, its docs and the copy record |
| + |
| +**Files:** |
| +- Create: `explain_cmd.go`, `explain_cmd_test.go` |
| +- Modify: `main.go` (the `case "explain":` dispatch and the command list in the top-level usage) |
| +- Create: `approved_edge_protect_copy_test.go` |
| +- The copy record `docs/superpowers/plans/2026-10-25-edge-protection-2-copy.md` already exists. Rows EP-1 to EP-13 are pending. EP-3 is the docs row: it is not written in this task (docs are never wired), and Task 6 writes it once approved. |
| + |
| +**Interfaces:** |
| +- Consumes: `GET /api/cli/apps/{account}/{app}/edge-refs/{code}` (Task 4's shape), and the CLI helpers `runGeo` uses (`appFlag`, `consoleOption`, `requireAPISession`, `resolvedAccount`, `resolvedApp`, `apiPath`, `sess.getJSON`, `apiErrorFromBody`, `flagUsage`). |
| +- Produces: `func runExplain(args []string)` and `func printExplain(w io.Writer, res apiEdgeRefResponse)`. |
| + |
| +- [ ] **Step 1: Write the failing tests** in `explain_cmd_test.go`, against `printExplain` with fixed responses. Compare whole output strings built from the copy record's EP rows: |
| + - `TestPrintExplainVerifiedFound`: the output is EP-8, then EP-4, then EP-13, then EP-9, in that order, one per line. The time is in UTC (`2006-01-02 15:04 UTC`). |
| + - `TestPrintExplainSealedUnverified`: EP-5 in place of EP-4. |
| + - `TestPrintExplainUnsealed`: EP-6 in place of EP-4. |
| + - `TestPrintExplainUnknownRule`: EP-7, with the response's `rule_hash`, in place of EP-13. |
| + - `TestPrintExplainAbsent` and `TestPrintExplainUnavailable`: EP-10 and EP-11 in place of EP-9. |
| + - `--json` prints the body unchanged. Test it through a fake session if the geo tests have one; otherwise test `printExplain` only and note it in the report. |
| + - In `approved_edge_protect_copy_test.go`, following `approved_db_forward_copy_test.go` and reusing its helpers (`parseCopyTable`, `checkMovesInventory`, `checkMovesNoEmDash`, `checkRunBuilt`, `checkRunApplied`, and the shape of `checkDBForwardWired`): |
| + - `TestEdgeProtectCopyRecordIsComplete`: the record names exactly EP-1 to EP-13. |
| + - `TestEdgeProtectCopyHasNoEmDash`. |
| + - `TestEdgeProtectBuiltCopyIsApproved`: ids in `edgeProtectCopyBuilt` are approved rows. |
| + - `TestEdgeProtectBuiltCopyIsApplied`. |
| + - `TestEdgeProtectWiredCopyIsPendingAndApplied`: a wired id is a pending, non-docs row whose text is in its file. |
| + - `TestEdgeProtectCopyAccounted`: every id except EP-3 is in exactly one of `edgeProtectCopyBuilt` and `edgeProtectCopyWired`. |
| + - In this task every id except EP-3 goes in `edgeProtectCopyWired`, and `edgeProtectCopyBuilt` is empty. |
| + |
| +- [ ] **Step 2: Run them to see them fail.** Run `go test . -run 'TestExplain|TestEdgeProtectCopy' -count=1`. Expected: FAIL. |
| + |
| +- [ ] **Step 3: Implement** `runExplain`. |
| + - Usage: `carlos explain <code> --app <a> [--json] [--console …] [--account …]`. The usage text is EP-2. |
| + - The code goes into the path through `url.PathEscape`. |
| + - A 404 from the console prints EP-12 and exits 1. |
| + - Any other non-200 answer goes through `apiErrorFromBody`, as `runGeo` does. |
| + - All strings come verbatim from the copy record. |
| + |
| +- [ ] **Step 4: Run the tests to see them pass.** Same command, plus `go vet .` and `GOOS=darwin go build -o /dev/null .` and `GOOS=windows go build -o /dev/null .`. Expected: PASS and clean builds. |
| + |
| +- [ ] **Step 5: Commit.** |
| + |
| +```bash |
| +git add explain_cmd.go explain_cmd_test.go main.go approved_edge_protect_copy_test.go |
| +git commit -m "carlos explain: what a block page's reference code says" |
| +``` |
| + |
| +### Task 6: Copy review (controller, with Paul) |
| + |
| +Not dispatched to an implementer. The controller runs the copy-review tool over EP-1 to EP-13, which needs Paul's approval. Then, in one commit, it: |
| +- applies the approved text to the record and the code; |
| +- writes EP-3 as an `explain` section in `docs/site/cli.md` after the `logs` section; |
| +- moves every id into `edgeProtectCopyBuilt`, EP-3 included; |
| +- adds `TestEdgeProtectCopyNoneWired` (`edgeProtectCopyWired` is empty). |
| + |
| +It also files R11's two requests: |
| +- an amadan discussion on carlos/platform naming the framework's route-list request; |
| +- a reply on #366 for the file list. Verify with `go test . -run TestEdgeProtectCopy -count=1` and `go test ./internal/edge/ -run TestGuardBlockMode -count=1`. |
| + |
| +Rollout after merge (Paul's go, dev first): |
| +1. Release, then roll to dev boxes with `CARLOS_EDGE_PROTECT` unset (watch). |
| +2. On one dev box, set `CARLOS_EDGE_PROTECT=block` for a hand check of the block page and `carlos explain`. Then unset it. |
| +3. Roll to the flagship unset. The 14-day calibration window starts there. |
diff --git a/explain_cmd.go b/explain_cmd.go| new file mode 100644 |
| index 000000000..14be119cd |
| --- /dev/null |
| +++ b/explain_cmd.go |
| @@ -0,0 +1,131 @@ |
| +// `carlos explain <code>`: what a reference code from a page the edge |
| +// answered says (edge protection spec, Plan 2). API mode only. Its strings |
| +// are rows EP-2 and EP-4 to EP-13 of the plan's copy record and await copy |
| +// review. |
| +package main |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "flag" |
| + "fmt" |
| + "io" |
| + "log" |
| + "net/http" |
| + "net/url" |
| + "os" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/applog" |
| +) |
| + |
| +const explainUsage = `usage: carlos explain <code> --app <a> [flags] |
| + |
| +What a reference code from a page the edge answered says: which protection rule fired, when, and the request it answered, while a record of it is kept. --json prints the console's answer as it is.` |
| + |
| +// explainNotFound is what a 404 from the console says. The console answers |
| +// the same 404 for a code that is malformed, forged or for another app, so |
| +// the message does not say which. |
| +const explainNotFound = "no reference code like that for this app. check the code, and that it came from one of this app's pages" |
| + |
| +// apiEdgeRefResponse mirrors the console's answer for one code |
| +// (internal/console/apiedgeref.go). The seal's fields are always there; Rule |
| +// is left out when the console's catalogue has no rule of that hash. |
| +type apiEdgeRefResponse struct { |
| + Code string `json:"code"` |
| + Sealed bool `json:"sealed"` |
| + Verified bool `json:"verified"` |
| + At time.Time `json:"at"` |
| + Tier string `json:"tier"` |
| + Rule string `json:"rule"` |
| + Group string `json:"group"` |
| + RuleHash string `json:"rule_hash"` |
| + RecordStatus string `json:"record_status"` |
| + Record *applog.Record `json:"record"` |
| +} |
| + |
| +func runExplain(args []string) { |
| + fs := flag.NewFlagSet("explain", flag.ExitOnError) |
| + app := appFlag(fs, "app whose credential asks") |
| + asJSON := fs.Bool("json", false, "print the console's answer as JSON") |
| + consoleFlag := consoleOption(fs, "console to ask (default: the only logged-in one)") |
| + acctRaw := fs.String("account", "", "account (sqid or name) the app belongs to (default: your only account, or the configured/chosen one)") |
| + acctIDRaw := fs.String("account-id", "", "account sqid, matched as a sqid ONLY, and supersedes --account") |
| + fs.Usage = flagUsage(fs, explainUsage) |
| + // The code leads the line in the usage text, and Go's flag package stops |
| + // at the first non-flag, so it moves after the flags like geo's address. |
| + fs.Parse(ipLast(args)) |
| + if fs.NArg() != 1 { |
| + fs.Usage() |
| + os.Exit(2) |
| + } |
| + sess := requireAPISession("explain", *consoleFlag) |
| + acct := resolvedAccount(sess, acctRaw, acctIDRaw) |
| + app2 := resolvedApp(sess, acct, *app, explainUsage) |
| + st, body, err := sess.getJSON(context.Background(), explainPath(acct, app2, fs.Arg(0))) |
| + if err != nil { |
| + log.Fatalf("explain: %v", err) |
| + } |
| + if st == http.StatusNotFound { |
| + fmt.Fprintln(os.Stderr, explainNotFound) |
| + os.Exit(1) |
| + } |
| + if st != http.StatusOK { |
| + log.Fatalf("explain: %v", apiErrorFromBody(st, body)) |
| + } |
| + if *asJSON { |
| + stdout.Write(body) |
| + fmt.Fprintln(stdout) |
| + return |
| + } |
| + var res apiEdgeRefResponse |
| + if err := json.Unmarshal(body, &res); err != nil { |
| + log.Fatalf("explain: unreadable response: %v", err) |
| + } |
| + printExplain(stdout, res) |
| +} |
| + |
| +// explainPath is the console path for one code. The code is user input, so |
| +// it goes through url.PathEscape and cannot step out of its segment. |
| +func explainPath(acct apiAcct, app, code string) string { |
| + return apiPath(acct, app, "/edge-refs/"+url.PathEscape(code)) |
| +} |
| + |
| +// explainLine writes one line of the answer. The copy record's rows carry |
| +// no trailing newline, so the line end lives here and not in each format. |
| +func explainLine(w io.Writer, format string, args ...any) { |
| + fmt.Fprintf(w, format, args...) |
| + fmt.Fprintln(w) |
| +} |
| + |
| +func printExplain(w io.Writer, res apiEdgeRefResponse) { |
| + explainLine(w, "reference %s\nwhen %s\ntier %s", res.Code, res.At.UTC().Format("2006-01-02 15:04 UTC"), res.Tier) |
| + // What the checked line says follows from the seal alone. An unsealed |
| + // code proves nothing about who wrote it, and a sealed one the console |
| + // cannot check (no key) is no better, so both tell the owner to treat |
| + // the rest as unchecked. |
| + switch { |
| + case res.Verified: |
| + explainLine(w, "checked yes. this deployment sealed the code") |
| + case res.Sealed: |
| + explainLine(w, "checked no. the console has no key to check the seal with, so treat the rest as unchecked") |
| + default: |
| + explainLine(w, "checked no. the code is not sealed, so anyone could have written it. treat the rest as unchecked") |
| + } |
| + if res.Rule != "" { |
| + explainLine(w, "rule %s", res.Rule) |
| + } else { |
| + explainLine(w, "rule not in this console's catalogue (hash %s)", res.RuleHash) |
| + } |
| + switch { |
| + case res.RecordStatus == "found" && res.Record != nil: |
| + f := res.Record.Fields |
| + explainLine(w, "request %s %s on %s, answered %s", f["method"], f["path"], res.Record.Host, f["status"]) |
| + case res.RecordStatus == "unavailable": |
| + explainLine(w, "request the records could not be read just now. try again in a minute") |
| + default: |
| + // "absent", and a "found" that carries no record or a status this |
| + // binary does not know: none has a request to show. |
| + explainLine(w, "request not kept. it was sampled away, or is older than 7 days") |
| + } |
| +} |
diff --git a/explain_cmd_test.go b/explain_cmd_test.go| new file mode 100644 |
| index 000000000..b954bc832 |
| --- /dev/null |
| +++ b/explain_cmd_test.go |
| @@ -0,0 +1,147 @@ |
| +package main |
| + |
| +import ( |
| + "bytes" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/applog" |
| +) |
| + |
| +// epText returns one row of the edge protection copy record, its line |
| +// breaks decoded and its placeholders filled, so the expected output of |
| +// printExplain is built from the record rather than retyped here. |
| +func epText(t *testing.T, id string, fill ...string) string { |
| + t.Helper() |
| + for _, r := range mustParseEdgeProtectRecord(t) { |
| + if r.ID == id { |
| + return strings.NewReplacer(fill...).Replace(strings.ReplaceAll(r.Text, `\n`, "\n")) |
| + } |
| + } |
| + t.Fatalf("copy record has no row %s", id) |
| + return "" |
| +} |
| + |
| +const explainTestCode = "abcdefghijklmnopqrstuvwxyz0123456789abcd" |
| + |
| +func explainResponse() apiEdgeRefResponse { |
| + return apiEdgeRefResponse{ |
| + Code: explainTestCode, |
| + Verified: true, |
| + Sealed: true, |
| + At: time.Date(2026, 10, 25, 14, 7, 31, 0, time.FixedZone("x", 3600)), |
| + Tier: "hard", |
| + Rule: "hard.secrets.env", |
| + Group: "secrets", |
| + RuleHash: "0a1b2c3d", |
| + RecordStatus: "found", |
| + Record: &applog.Record{ |
| + Host: "shop.example.com", |
| + Fields: map[string]string{"method": "GET", "path": "/.env", "status": "404"}, |
| + }, |
| + } |
| +} |
| + |
| +func explainOutput(res apiEdgeRefResponse) string { |
| + var out bytes.Buffer |
| + printExplain(&out, res) |
| + return out.String() |
| +} |
| + |
| +// The header names the code, the time in UTC and the tier. The response's |
| +// time is 14:07 at +01:00, so the line must say 13:07. |
| +func explainHeader(t *testing.T) string { |
| + return epText(t, "EP-8", "<code>", explainTestCode, "<time>", "2026-10-25 13:07 UTC", "<tier>", "hard") + "\n" |
| +} |
| + |
| +func explainRuleLine(t *testing.T) string { |
| + return epText(t, "EP-13", "<rule>", "hard.secrets.env") + "\n" |
| +} |
| + |
| +func explainRequestLine(t *testing.T) string { |
| + return epText(t, "EP-9", "<method>", "GET", "<path>", "/.env", "<host>", "shop.example.com", "<status>", "404") + "\n" |
| +} |
| + |
| +func TestPrintExplainVerifiedFound(t *testing.T) { |
| + want := explainHeader(t) + epText(t, "EP-4") + "\n" + explainRuleLine(t) + explainRequestLine(t) |
| + if got := explainOutput(explainResponse()); got != want { |
| + t.Fatalf("output:\n%s\nwant:\n%s", got, want) |
| + } |
| +} |
| + |
| +func TestPrintExplainSealedUnverified(t *testing.T) { |
| + res := explainResponse() |
| + res.Verified = false |
| + want := explainHeader(t) + epText(t, "EP-5") + "\n" + explainRuleLine(t) + explainRequestLine(t) |
| + if got := explainOutput(res); got != want { |
| + t.Fatalf("output:\n%s\nwant:\n%s", got, want) |
| + } |
| +} |
| + |
| +func TestPrintExplainUnsealed(t *testing.T) { |
| + res := explainResponse() |
| + res.Verified, res.Sealed = false, false |
| + want := explainHeader(t) + epText(t, "EP-6") + "\n" + explainRuleLine(t) + explainRequestLine(t) |
| + if got := explainOutput(res); got != want { |
| + t.Fatalf("output:\n%s\nwant:\n%s", got, want) |
| + } |
| +} |
| + |
| +func TestPrintExplainUnknownRule(t *testing.T) { |
| + res := explainResponse() |
| + res.Rule, res.Group = "", "" |
| + want := explainHeader(t) + epText(t, "EP-4") + "\n" + |
| + epText(t, "EP-7", "<hash>", "0a1b2c3d") + "\n" + explainRequestLine(t) |
| + if got := explainOutput(res); got != want { |
| + t.Fatalf("output:\n%s\nwant:\n%s", got, want) |
| + } |
| +} |
| + |
| +func TestPrintExplainAbsent(t *testing.T) { |
| + res := explainResponse() |
| + res.RecordStatus, res.Record = "absent", nil |
| + want := explainHeader(t) + epText(t, "EP-4") + "\n" + explainRuleLine(t) + epText(t, "EP-10") + "\n" |
| + if got := explainOutput(res); got != want { |
| + t.Fatalf("output:\n%s\nwant:\n%s", got, want) |
| + } |
| +} |
| + |
| +func TestPrintExplainUnavailable(t *testing.T) { |
| + res := explainResponse() |
| + res.RecordStatus, res.Record = "unavailable", nil |
| + want := explainHeader(t) + epText(t, "EP-4") + "\n" + explainRuleLine(t) + epText(t, "EP-11") + "\n" |
| + if got := explainOutput(res); got != want { |
| + t.Fatalf("output:\n%s\nwant:\n%s", got, want) |
| + } |
| +} |
| + |
| +// A console that says "found" without a record must not make a request |
| +// line out of empty fields. |
| +func TestPrintExplainFoundWithoutRecord(t *testing.T) { |
| + res := explainResponse() |
| + res.Record = nil |
| + if got := explainOutput(res); !strings.HasSuffix(got, epText(t, "EP-10")+"\n") { |
| + t.Fatalf("output:\n%s", got) |
| + } |
| +} |
| + |
| +// The usage text is EP-2. |
| +func TestExplainUsageIsTheRecordsText(t *testing.T) { |
| + if got, want := strings.TrimRight(explainUsage, "\n"), epText(t, "EP-2"); got != want { |
| + t.Fatalf("usage:\n%s\nwant:\n%s", got, want) |
| + } |
| +} |
| + |
| +func TestExplainNotFoundText(t *testing.T) { |
| + if got, want := explainNotFound, epText(t, "EP-12"); got != want { |
| + t.Fatalf("not found = %q, want %q", got, want) |
| + } |
| +} |
| + |
| +func TestExplainPathEscapesTheCode(t *testing.T) { |
| + got := explainPath(apiAcct{Seg: "acct"}, "shop", "a/b c") |
| + if want := "/api/cli/apps/acct/shop/edge-refs/a%2Fb%20c"; got != want { |
| + t.Fatalf("path = %q, want %q", got, want) |
| + } |
| +} |
diff --git a/internal/console/apiedgeref.go b/internal/console/apiedgeref.go| index afc8896b7..1fa06f8e5 100644 |
| --- a/internal/console/apiedgeref.go |
| +++ b/internal/console/apiedgeref.go |
| @@ -15,13 +15,19 @@ import ( |
| "time" |
| "github.com/carlosframework/platform/internal/applog" |
| + "github.com/carlosframework/platform/internal/edgeguard" |
| "github.com/carlosframework/platform/internal/reqrec" |
| ) |
| // apiEdgeRef is the wire shape of one explained code. The seal's fields |
| -// (code, verified, at, tier, rule_hash) are always there: they come from the |
| -// code itself, so they tell the owner which rule fired and when whatever |
| -// happened to the record. RecordStatus says what happened to it: |
| +// (code, sealed, verified, at, tier, rule_hash) are always there: they come |
| +// from the code itself, so they tell the owner which rule fired and when |
| +// whatever happened to the record. Sealed says whether the edge sealed the |
| +// code at all; an unsealed code is never verified, so the two together tell |
| +// "not checkable" from "checked and genuine". Rule and Group name the |
| +// catalogue rule behind rule_hash, and are left out when the catalogue has |
| +// no rule of that hash and tier (a tenant's own rule, or a rule from another |
| +// catalogue version). RecordStatus says what happened to the record: |
| // |
| // found Record is the edge record carrying this code |
| // absent the logs were read and hold no such record (sampled away, |
| @@ -30,10 +36,13 @@ import ( |
| // asking again later may find it |
| type apiEdgeRef struct { |
| Code string `json:"code"` |
| + Sealed bool `json:"sealed"` |
| Verified bool `json:"verified"` |
| At time.Time `json:"at"` |
| Tier string `json:"tier"` |
| RuleHash string `json:"rule_hash"` |
| + Rule string `json:"rule,omitempty"` |
| + Group string `json:"group,omitempty"` |
| RecordStatus string `json:"record_status"` |
| Record *applog.Record `json:"record"` |
| } |
| @@ -82,12 +91,18 @@ func (s *Server) handleAPIEdgeRef(w http.ResponseWriter, r *http.Request) { |
| }, 1000) |
| resp := apiEdgeRef{ |
| Code: canon, |
| + Sealed: ref.Sealed, |
| Verified: ref.Verified, |
| At: ref.At, |
| Tier: ref.Tier.String(), |
| RuleHash: fmt.Sprintf("%08x", ref.RuleHash), |
| RecordStatus: "absent", |
| } |
| + // The hash is 32 bits, so a rule only counts as the code's when its tier |
| + // is the code's tier too; a chance collision across tiers names nothing. |
| + if rule, ok := edgeguard.RuleByHash(ref.RuleHash); ok && rule.Tier == ref.Tier { |
| + resp.Rule, resp.Group = rule.ID, rule.Group |
| + } |
| switch { |
| case err != nil: |
| // The code still explains itself; a failed read must not take that |
diff --git a/internal/console/apiedgeref_test.go b/internal/console/apiedgeref_test.go| index 2a88a93a9..af360ac18 100644 |
| --- a/internal/console/apiedgeref_test.go |
| +++ b/internal/console/apiedgeref_test.go |
| @@ -207,3 +207,66 @@ func TestEdgeRefRecordUnavailable(t *testing.T) { |
| t.Fatalf("got %+v", resp) |
| } |
| } |
| + |
| +// TestAPIEdgeRefNamesCatalogueRule: a sealed code for a catalogue rule comes |
| +// back with the rule's id and group, so the owner reads which rule fired |
| +// without decoding the hash. |
| +func TestAPIEdgeRefNamesCatalogueRule(t *testing.T) { |
| + fx, token := edgeRefFixture(t, "code-edgeref-catalogue") |
| + code := reqrec.NewRef(time.Now().UTC(), reqrec.TierHard, "hard.secrets.env", "box1", edgeRefTestKey) |
| + |
| + resp := getEdgeRef(t, fx, token, code) |
| + if resp.Rule != "hard.secrets.env" || resp.Group != "secrets" || !resp.Sealed || !resp.Verified { |
| + t.Fatalf("rule/group/sealed/verified: %+v", resp) |
| + } |
| +} |
| + |
| +// TestAPIEdgeRefUnknownRule: a rule the catalogue does not hold (a tenant's |
| +// own rule, or one from a catalogue version this console lacks) is named by |
| +// its hash alone, and the rule and group fields are left out. |
| +func TestAPIEdgeRefUnknownRule(t *testing.T) { |
| + fx, token := edgeRefFixture(t, "code-edgeref-unknownrule") |
| + code := reqrec.NewRef(time.Now().UTC(), reqrec.TierHard, "tenant-x", "box1", edgeRefTestKey) |
| + |
| + status, _, body := rawReq(t, http.MethodGet, edgeRefURL(fx, fx.sqid, "titogo", code), token, "") |
| + if status != http.StatusOK { |
| + t.Fatalf("status = %d: %s", status, body) |
| + } |
| + var fields map[string]any |
| + if err := json.Unmarshal([]byte(body), &fields); err != nil { |
| + t.Fatal(err) |
| + } |
| + for _, k := range []string{"rule", "group"} { |
| + if _, ok := fields[k]; ok { |
| + t.Errorf("%s present for an unknown rule: %s", k, body) |
| + } |
| + } |
| + if want := fmt.Sprintf("%08x", reqrec.RuleHash("tenant-x")); fields["rule_hash"] != want { |
| + t.Fatalf("rule_hash = %v, want %s", fields["rule_hash"], want) |
| + } |
| +} |
| + |
| +// TestAPIEdgeRefTierMismatch: a code whose hash matches a catalogue rule but |
| +// whose tier is not that rule's tier does not name the rule. The hash is only |
| +// 32 bits, so the tier is the cheap second check against a chance collision. |
| +func TestAPIEdgeRefTierMismatch(t *testing.T) { |
| + fx, token := edgeRefFixture(t, "code-edgeref-tiermismatch") |
| + code := reqrec.NewRef(time.Now().UTC(), reqrec.TierProbe, "hard.secrets.env", "box1", edgeRefTestKey) |
| + |
| + resp := getEdgeRef(t, fx, token, code) |
| + if resp.Rule != "" || resp.Group != "" { |
| + t.Fatalf("named a rule of another tier: %+v", resp) |
| + } |
| +} |
| + |
| +// TestAPIEdgeRefUnsealed: a code minted without a key still explains itself, |
| +// but says it was not sealed and so cannot be verified. |
| +func TestAPIEdgeRefUnsealed(t *testing.T) { |
| + fx, token := edgeRefFixture(t, "code-edgeref-unsealed") |
| + code := reqrec.NewRef(time.Now().UTC(), reqrec.TierHard, "hard.secrets.env", "box1", nil) |
| + |
| + resp := getEdgeRef(t, fx, token, code) |
| + if resp.Sealed || resp.Verified { |
| + t.Fatalf("sealed/verified: %+v", resp) |
| + } |
| +} |
diff --git a/internal/edge/answered.go b/internal/edge/answered.go| index e92d52977..2b0fce230 100644 |
| --- a/internal/edge/answered.go |
| +++ b/internal/edge/answered.go |
| @@ -39,6 +39,11 @@ type outcome struct { |
| // (MarkWoke), so a request record can say which request woke the app. |
| // Requests that queued behind the same wake are not marked. |
| woke bool |
| + // guard is set when the hard and probe checks run for this request |
| + // (guard.go), and holds their verdict once one matched. nil means the |
| + // guard is off for it: a door caller, a request a tunnel delivered (the |
| + // hub checked it), or CARLOS_EDGE_PROTECT=off. |
| + guard *guardState |
| } |
| // causeClientGone is the cause noted when a proxy fails because the CLIENT |
| @@ -67,11 +72,18 @@ func WithAnswerFlag(r *http.Request) (*http.Request, *bool) { |
| return r, &o.answered |
| } |
| +// outcomeFrom returns the outcome r carries, or nil when the edge attached |
| +// none. |
| +func outcomeFrom(r *http.Request) *outcome { |
| + o, _ := r.Context().Value(answeredKey{}).(*outcome) |
| + return o |
| +} |
| + |
| // MarkAnswered sets the flag when r carries one; a no-op otherwise — so the |
| // activator can call it unconditionally, including on the paths (a |
| // non-hibernating route, a direct unit test) where the edge attached none. |
| func MarkAnswered(r *http.Request) { |
| - if o, ok := r.Context().Value(answeredKey{}).(*outcome); ok { |
| + if o := outcomeFrom(r); o != nil { |
| o.answered = true |
| } |
| } |
| @@ -83,15 +95,15 @@ func MarkWoke(r *http.Request) { |
| if r == nil { |
| return |
| } |
| - if o, ok := r.Context().Value(answeredKey{}).(*outcome); ok { |
| + if o := outcomeFrom(r); o != nil { |
| o.woke = true |
| } |
| } |
| // Woke reports whether MarkWoke was called for r. |
| func Woke(r *http.Request) bool { |
| - o, ok := r.Context().Value(answeredKey{}).(*outcome) |
| - return ok && o.woke |
| + o := outcomeFrom(r) |
| + return o != nil && o.woke |
| } |
| // waited reports how long r has been served for, when the edge attached an |
diff --git a/internal/edge/edge.go b/internal/edge/edge.go| index 0eb588d36..f63a693b5 100644 |
| --- a/internal/edge/edge.go |
| +++ b/internal/edge/edge.go |
| @@ -51,6 +51,7 @@ import ( |
| "golang.org/x/crypto/acme/autocert" |
| "github.com/carlosframework/platform/internal/apperr" |
| + "github.com/carlosframework/platform/internal/edgeguard" |
| "github.com/carlosframework/platform/internal/edgeproof" |
| "github.com/carlosframework/platform/internal/edgesfile" |
| "github.com/carlosframework/platform/internal/gate" |
| @@ -62,6 +63,7 @@ import ( |
| "github.com/carlosframework/platform/internal/ratelimit" |
| "github.com/carlosframework/platform/internal/registry" |
| "github.com/carlosframework/platform/internal/release" |
| + "github.com/carlosframework/platform/internal/reqrec" |
| ) |
| // Default cache sizing for EnableCache: 4096 entries is comfortably above a |
| @@ -253,6 +255,15 @@ type Edge struct { |
| // false, ServeHTTP never constructs a gzipWriter and the writer stack is |
| // byte-for-byte what it was before compression existed (compress.go). |
| gzipOn bool |
| + // guard is CARLOS_EDGE_PROTECT, read once in New: what the edge does |
| + // with a request matching a hard or probe rule (guard.go). By default |
| + // each rule's own mode, and in catalogue version 1 that is only ever to |
| + // watch. |
| + guard guardMode |
| + // guardMint is mintRef, bound once in New: a method value taken per |
| + // request would allocate for every guarded request, and most never |
| + // mint a code. |
| + guardMint func(reqrec.Tier, string) string |
| // 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 |
| @@ -433,11 +444,12 @@ type upstream struct { |
| // New builds an Edge over reg and performs the startup reload. act may be nil |
| // (no hibernation). |
| func New(reg *registry.Registry, act Activator) (*Edge, error) { |
| - e := &Edge{reg: reg, act: act, gate: gate.New(), probers: newProberSet(), gzipOn: gzipEnabled(), steeringHost: steeringProbeHostFromEnv(), appsDomain: appsDomainFromEnv(), |
| + e := &Edge{reg: reg, act: act, gate: gate.New(), probers: newProberSet(), 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)} |
| e.geo = geo.NewSwappable() |
| e.geoLookup = e.geo.Lookup |
| + e.guardMint = e.mintRef |
| // Generations (zero-downtime spec §7.2), before the startup Reload so |
| // its first table build already proxies through them. |
| if gs, ok := act.(GenSource); ok && gs.GenerationsOn() { |
| @@ -1738,6 +1750,7 @@ func (e *Edge) ServeHTTP(w http.ResponseWriter, r *http.Request) { |
| var bytes int64 |
| ob := &countingWriter{ResponseWriter: w, n: &bytes} |
| w = ob |
| + var out *outcome |
| if up.route.Kind != "status" { |
| // The outcome rides the request so the two things only the inner |
| // layers know reach this defer: the activator marks the wake-path |
| @@ -1745,8 +1758,17 @@ func (e *Edge) ServeHTTP(w http.ResponseWriter, r *http.Request) { |
| // member's platform event, so not filed again (spec §3.2, "exactly |
| // once") — and a proxy ErrorHandler notes WHY it answered 502/503 |
| // (noteCause), which is what groups Availability by cause. |
| - var out *outcome |
| r, out = withOutcome(r) |
| + // The hard and probe checks (guard.go) run for every request this |
| + // box is the first to see. A door caller is the platform itself, |
| + // not a visitor, whether its door is on this box or on the box that |
| + // backhauled it here (hopDoorFrom, set only beside a verified hop, |
| + // as the rate limit reads it). A request a tunnel delivered was |
| + // checked, and is recorded, by the hub that forwarded it, so |
| + // 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() |
| + } |
| defer func() { |
| if m := e.usageMeter.Load(); m != nil { |
| m.Record(up.route, 1, bytes, hopped) |
| @@ -1759,6 +1781,32 @@ func (e *Edge) ServeHTTP(w http.ResponseWriter, r *http.Request) { |
| }() |
| } |
| + // The hard and probe checks (internal/edgeguard; edge protection spec |
| + // §5.3), once per request. Placed HERE for the gate's reasons below: |
| + // after the meter and the observer defer, so a block page bills and is |
| + // recorded like any answer; before the gate, so a probe on a gated |
| + // route meets the guard rather than the login page; before the upgrade |
| + // branch and the cache, so a stored answer is never served to a probe; |
| + // and before the activator, so a check never waits on a wake and a |
| + // blocked probe never wakes anything. The matcher allocates nothing for |
| + // an ordinary path. |
| + // |
| + // 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. |
| + if out != nil && out.guard != nil { |
| + var hit edgeguard.Hit |
| + var matched bool |
| + if up.route.Kind == "static" && !up.viaTunnel { |
| + hit, matched = edgeguard.CheckTier(r.URL.Path, r.URL.RawQuery, reqrec.TierHard) |
| + } else { |
| + hit, matched = edgeguard.Check(r.URL.Path, r.URL.RawQuery) |
| + } |
| + if matched && guardDecide(w, r, hit) { |
| + return |
| + } |
| + } |
| + |
| // The password gate (internal/gate; spec 2026-09-07-password-gate-design |
| // §4.1). Placed HERE and the neighbours are load-bearing: after the |
| // meter, so the login page's bytes bill to the route that caused them; |
diff --git a/internal/edge/guard.go b/internal/edge/guard.go| new file mode 100644 |
| index 000000000..dd2ee7f73 |
| --- /dev/null |
| +++ b/internal/edge/guard.go |
| @@ -0,0 +1,138 @@ |
| +package edge |
| + |
| +import ( |
| + "fmt" |
| + "io" |
| + "log" |
| + "net/http" |
| + "strings" |
| + |
| + "github.com/carlosframework/platform/internal/edgeguard" |
| + "github.com/carlosframework/platform/internal/reqrec" |
| +) |
| + |
| +// guardMode is what the edge does with a request that matches a hard or |
| +// probe rule (internal/edgeguard). It is read once, in New, from |
| +// CARLOS_EDGE_PROTECT. |
| +type guardMode uint8 |
| + |
| +const ( |
| + // guardCatalogue, the default, does what each rule's own mode says. Every |
| + // rule in catalogue version 1 watches or counts toward a burst, so by |
| + // default nothing is blocked: a match is recorded with the app's answer. |
| + guardCatalogue guardMode = iota |
| + // guardOff runs no check at all. |
| + guardOff |
| + // guardWatch records every match and blocks none, whatever the catalogue |
| + // says. |
| + guardWatch |
| + // guardBlock blocks every match except a burst rule's, which is a page a |
| + // real visitor may ask for once. It is for dev boxes, to see the block |
| + // page and its code end to end. |
| + guardBlock |
| +) |
| + |
| +// guardModeFromEnv reads CARLOS_EDGE_PROTECT. An unknown value is logged and |
| +// read as the default, so a typo never turns protection off. |
| +func guardModeFromEnv(getenv func(string) string) guardMode { |
| + v := getenv("CARLOS_EDGE_PROTECT") |
| + switch strings.ToLower(strings.TrimSpace(v)) { |
| + case "off": |
| + return guardOff |
| + case "watch": |
| + return guardWatch |
| + case "block": |
| + return guardBlock |
| + case "": |
| + return guardCatalogue |
| + } |
| + log.Printf("edge: CARLOS_EDGE_PROTECT=%q is not off, watch or block; using the catalogue's modes", v) |
| + return guardCatalogue |
| +} |
| + |
| +// blocks reports whether a match on rule is answered with the block page |
| +// rather than forwarded. |
| +func (m guardMode) blocks(rule *edgeguard.Rule) bool { |
| + switch m { |
| + case guardBlock: |
| + return rule.Mode != edgeguard.ModeBurst |
| + case guardCatalogue: |
| + return rule.Mode == edgeguard.ModeBlock |
| + } |
| + return false |
| +} |
| + |
| +// 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. |
| +type guardVerdict struct { |
| + rule *edgeguard.Rule |
| + frag string |
| + block bool |
| + ref string |
| +} |
| + |
| +// guardState rides a request's outcome when the guard runs for it. ServeHTTP |
| +// sets it, and the observer defer reads the verdict to file one Match in |
| +// 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. |
| +type guardState struct { |
| + mode guardMode |
| + mint func(reqrec.Tier, string) string |
| + verdict *guardVerdict |
| +} |
| + |
| +// newGuardState is the guard's state for one request. It costs the struct |
| +// and nothing else: the mint function was bound in New. An Edge built |
| +// without New has none bound and pays for the method value instead, so a |
| +// block never calls a nil func. |
| +func (e *Edge) newGuardState() *guardState { |
| + mint := e.guardMint |
| + if mint == nil { |
| + mint = e.mintRef |
| + } |
| + return &guardState{mode: e.guard, mint: mint} |
| +} |
| + |
| +// guardDecide notes hit as r's verdict and, when the mode blocks the rule, |
| +// 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. |
| +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 { |
| + return false |
| + } |
| + st := out.guard |
| + v := &guardVerdict{rule: hit.Rule} |
| + 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) { |
| + return false |
| + } |
| + v.block = true |
| + v.ref = st.mint(hit.Rule.Tier, hit.Rule.ID) |
| + writeGuardBlock(w, v.ref) |
| + return true |
| +} |
| + |
| +// 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: |
| +// a code names one request. |
| +func writeGuardBlock(w http.ResponseWriter, code string) { |
| + 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) |
| + w.WriteHeader(http.StatusNotFound) |
| + fmt.Fprintf(w, "Not found.\n\nIf you expected a page here, send this reference to the site's owner: %s", code) |
| + io.WriteString(w, "\n") |
| +} |
diff --git a/internal/edge/guard_test.go b/internal/edge/guard_test.go| new file mode 100644 |
| index 000000000..bbe424cb9 |
| --- /dev/null |
| +++ b/internal/edge/guard_test.go |
| @@ -0,0 +1,432 @@ |
| +package edge |
| + |
| +import ( |
| + "context" |
| + "io" |
| + "net/http" |
| + "net/http/httptest" |
| + "strings" |
| + "sync/atomic" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/registry" |
| + "github.com/carlosframework/platform/internal/release" |
| + "github.com/carlosframework/platform/internal/reqrec" |
| + "github.com/carlosframework/platform/internal/tunnelclient" |
| +) |
| + |
| +func TestGuardModeFromEnv(t *testing.T) { |
| + for v, want := range map[string]guardMode{ |
| + "": guardCatalogue, |
| + "off": guardOff, |
| + " Watch ": guardWatch, |
| + "block": guardBlock, |
| + "bogus": guardCatalogue, |
| + } { |
| + got := guardModeFromEnv(func(k string) string { |
| + if k == "CARLOS_EDGE_PROTECT" { |
| + return v |
| + } |
| + return "" |
| + }) |
| + if got != want { |
| + t.Errorf("CARLOS_EDGE_PROTECT=%q: mode %d, want %d", v, got, want) |
| + } |
| + } |
| +} |
| + |
| +// guardRig is an edge over one route whose upstream and activator count what |
| +// reached them, with a recorder that keeps every record. |
| +type guardRig struct { |
| + e *Edge |
| + rec *memRecorder |
| + upstream *atomic.Int32 |
| + act *fakeActivator |
| + key []byte |
| +} |
| + |
| +// guardEdge builds a guardRig over an instance route for app.test whose |
| +// upstream answers status with body. hibernate puts the route behind a |
| +// counting activator; armed installs a mesh key, so the codes are sealed. |
| +func guardEdge(t *testing.T, hibernate, armed bool, status int, body string) *guardRig { |
| + t.Helper() |
| + g := &guardRig{rec: &memRecorder{}, upstream: new(atomic.Int32), act: &fakeActivator{}} |
| + backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + g.upstream.Add(1) |
| + w.WriteHeader(status) |
| + io.WriteString(w, body) |
| + })) |
| + t.Cleanup(backend.Close) |
| + reg := openReg(t) |
| + if err := reg.Upsert(registry.Route{Host: "app.test", Kind: "instance", Addr: backend.Listener.Addr().String(), |
| + Status: "ready", Hibernate: hibernate, App: "shop"}); err != nil { |
| + t.Fatal(err) |
| + } |
| + e, err := New(reg, g.act) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Cleanup(e.probers.Stop) |
| + if armed { |
| + 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.key, _ = m.meshKeys() |
| + } |
| + e.EnableRequestRecords(g.rec) |
| + g.e = e |
| + return g |
| +} |
| + |
| +func (g *guardRig) get(path string) *httptest.ResponseRecorder { |
| + w := httptest.NewRecorder() |
| + g.e.ServeHTTP(w, httptest.NewRequest("GET", "http://app.test"+path, nil)) |
| + return w |
| +} |
| + |
| +// In the default mode every rule of catalogue version 1 only watches: the |
| +// probe goes through, the visitor gets the app's own answer, and the one |
| +// record for it is a watch carrying that answer's status. |
| +func TestGuardWatchForwards(t *testing.T) { |
| + g := guardEdge(t, false, false, http.StatusNotFound, "the app's own 404") |
| + w := g.get("/.env") |
| + if w.Code != 404 || w.Body.String() != "the app's own 404" || g.upstream.Load() != 1 { |
| + t.Fatalf("got %d %q, upstream %d", w.Code, w.Body.String(), g.upstream.Load()) |
| + } |
| + if w.Header().Get("X-Carlos-Ref") != "" { |
| + t.Fatal("a watched request carried a reference code") |
| + } |
| + if len(g.rec.resp) != 0 || len(g.rec.match) != 1 { |
| + t.Fatalf("responses %d, matches %d; want 0 and 1", len(g.rec.resp), len(g.rec.match)) |
| + } |
| + m := g.rec.match[0] |
| + if m.Kind != reqrec.KindWatch || m.Tier != reqrec.TierHard || m.RuleID != "hard.secrets.env" || m.Status != 404 || m.Ref != "" { |
| + t.Fatalf("match %+v", m) |
| + } |
| + if m.Fragment != ".env" || m.App != "shop" || m.Path != "/.env" { |
| + t.Fatalf("match %+v", m) |
| + } |
| +} |
| + |
| +// Review Focus 5: a watched probe that a sleeping app wakes for and answers |
| +// 200 is one record, a watch, saying 200 and that it woke the app. |
| +func TestGuardWatchRecordsUpstreamStatus(t *testing.T) { |
| + reg := openReg(t) |
| + rt := registry.Route{Host: "sleepy.example.com", Kind: "instance", Socket: t.TempDir() + "/x.sock", Status: "ready", Hibernate: true, App: "web"} |
| + if err := reg.Upsert(rt); err != nil { |
| + t.Fatal(err) |
| + } |
| + e, err := New(reg, wakingActivator{}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + rec := &memRecorder{} |
| + e.EnableRequestRecords(rec) |
| + e.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest("GET", "http://sleepy.example.com/wp-login.php", nil)) |
| + if len(rec.resp) != 0 || len(rec.match) != 1 { |
| + t.Fatalf("responses %d, matches %d; want 0 and 1", len(rec.resp), len(rec.match)) |
| + } |
| + m := rec.match[0] |
| + if m.Kind != reqrec.KindWatch || m.Status != 200 || !m.WokeKnown || !m.Woke || m.Ref != "" || m.RuleID != "probe.wordpress.wp-login" { |
| + t.Fatalf("match %+v", m) |
| + } |
| +} |
| + |
| +// In block mode a hard-tier probe is answered here with the block page: a |
| +// 404 whose body and header carry one sealed code naming the rule. Nothing |
| +// behind the edge sees the request. |
| +func TestGuardBlockMode(t *testing.T) { |
| + g := guardEdge(t, true, true, http.StatusOK, "app") |
| + g.e.guard = guardBlock |
| + w := g.get("/.git/config") |
| + if w.Code != 404 { |
| + t.Fatalf("status %d, want 404", w.Code) |
| + } |
| + if ct := w.Header().Get("Content-Type"); ct != "text/plain; charset=utf-8" { |
| + t.Fatalf("Content-Type %q", ct) |
| + } |
| + if cc := w.Header().Get("Cache-Control"); cc != "no-store" { |
| + t.Fatalf("Cache-Control %q", cc) |
| + } |
| + code := w.Header().Get("X-Carlos-Ref") |
| + want := "Not found.\n\nIf you expected a page here, send this reference to the site's owner: " + code |
| + if code == "" || strings.TrimSuffix(w.Body.String(), "\n") != want { |
| + t.Fatalf("code %q, body %q", code, w.Body.String()) |
| + } |
| + ref, err := reqrec.ParseRef(code, g.key) |
| + if err != nil || !ref.Verified || ref.Tier != reqrec.TierHard || ref.RuleHash != reqrec.RuleHash("hard.secrets.git") { |
| + t.Fatalf("code %q: %+v %v", code, ref, err) |
| + } |
| + if g.upstream.Load() != 0 || g.act.served != 0 { |
| + t.Fatalf("upstream %d, activator %d; want neither called", g.upstream.Load(), g.act.served) |
| + } |
| + if len(g.rec.resp) != 0 || len(g.rec.match) != 1 { |
| + t.Fatalf("responses %d, matches %d; want 0 and 1", len(g.rec.resp), len(g.rec.match)) |
| + } |
| + m := g.rec.match[0] |
| + if m.Kind != reqrec.KindBlock || m.Ref != code || m.Status != 404 || !m.WokeKnown || m.Woke || m.RuleID != "hard.secrets.git" { |
| + t.Fatalf("match %+v", m) |
| + } |
| +} |
| + |
| +// Block mode still never blocks a burst rule: an admin page is a normal |
| +// thing to visit once, so it is forwarded and only watched. |
| +func TestGuardBlockModeSparesBurst(t *testing.T) { |
| + g := guardEdge(t, false, false, http.StatusOK, "admin page") |
| + g.e.guard = guardBlock |
| + w := g.get("/admin") |
| + if w.Code != 200 || w.Body.String() != "admin page" || g.upstream.Load() != 1 { |
| + t.Fatalf("got %d %q, upstream %d", w.Code, w.Body.String(), g.upstream.Load()) |
| + } |
| + if len(g.rec.resp) != 0 || len(g.rec.match) != 1 || g.rec.match[0].Kind != reqrec.KindWatch || g.rec.match[0].RuleID != "probe.admin.admin" { |
| + t.Fatalf("responses %+v, matches %+v", g.rec.resp, g.rec.match) |
| + } |
| +} |
| + |
| +// The guard answers before the password gate and before the cache: a probe |
| +// on a gated route gets the block page rather than the login page, and a |
| +// response cached for the probe's path is never served. |
| +func TestGuardBeforeGateAndCache(t *testing.T) { |
| + cached := func(e *Edge, host string) { |
| + e.EnableCache(NewCache(DefaultCacheMaxEntries, DefaultCacheMaxBodyBytes)) |
| + e.cache.Put(CacheKey{Host: host, Method: "GET", Path: "/.env"}, "", &CachedResponse{ |
| + StatusCode: 200, Header: http.Header{"Content-Type": {"text/plain"}}, Body: []byte("cached secret"), |
| + StoredAt: time.Now(), TTL: time.Minute, |
| + }) |
| + } |
| + |
| + e, srv, _, _ := gatedEdge(t, &fakeActivator{}, false) |
| + e.guard = guardBlock |
| + cached(e, "gated.example.com") |
| + resp := doHost(t, srv, http.MethodGet, "gated.example.com", "/.env", "") |
| + b, _ := io.ReadAll(resp.Body) |
| + resp.Body.Close() |
| + if resp.StatusCode != 404 || resp.Header.Get("X-Carlos-Ref") == "" || strings.Contains(string(b), "cached secret") { |
| + t.Fatalf("gated route: %d ref %q body %q", resp.StatusCode, resp.Header.Get("X-Carlos-Ref"), b) |
| + } |
| + |
| + // An ungated route would serve the cached entry if the guard came after |
| + // the cache, so this is the half that shows the order. |
| + g := guardEdge(t, false, false, http.StatusOK, "app") |
| + g.e.guard = guardBlock |
| + cached(g.e, "app.test") |
| + w := g.get("/.env") |
| + if w.Code != 404 || w.Header().Get("X-Carlos-Ref") == "" || strings.Contains(w.Body.String(), "cached secret") { |
| + t.Fatalf("ungated route: %d %q", w.Code, w.Body.String()) |
| + } |
| + // The control: with the guard off the same request is a cache hit, so |
| + // the entry above is one the cache would have served. |
| + g.e.guard = guardOff |
| + if w := g.get("/.env"); w.Body.String() != "cached secret" { |
| + t.Fatalf("control: %d %q, want the cached entry", w.Code, w.Body.String()) |
| + } |
| +} |
| + |
| +// With protection off, a probe is an ordinary request: forwarded, and filed |
| +// as a plain response. |
| +func TestGuardOffDoesNothing(t *testing.T) { |
| + g := guardEdge(t, false, false, http.StatusNotFound, "the app's own 404") |
| + g.e.guard = guardOff |
| + w := g.get("/.env") |
| + if w.Code != 404 || w.Body.String() != "the app's own 404" || g.upstream.Load() != 1 { |
| + t.Fatalf("got %d %q, upstream %d", w.Code, w.Body.String(), g.upstream.Load()) |
| + } |
| + if len(g.rec.resp) != 1 || len(g.rec.match) != 0 { |
| + t.Fatalf("responses %d, matches %d; want 1 and 0", len(g.rec.resp), len(g.rec.match)) |
| + } |
| +} |
| + |
| +// A request delivered over a tunnel was already checked by the hub that |
| +// forwarded it, which also records it, so this box neither blocks nor |
| +// records it, even in block mode. |
| +func TestGuardSkipsTunnelDelivered(t *testing.T) { |
| + g := guardEdge(t, false, false, http.StatusNotFound, "the app's own 404") |
| + g.e.guard = guardBlock |
| + w := httptest.NewRecorder() |
| + tunnelclient.Mark(g.e).ServeHTTP(w, httptest.NewRequest("GET", "http://app.test/.env", nil)) |
| + if w.Code != 404 || w.Body.String() != "the app's own 404" || w.Header().Get("X-Carlos-Ref") != "" || g.upstream.Load() != 1 { |
| + t.Fatalf("got %d %q ref %q, upstream %d", w.Code, w.Body.String(), w.Header().Get("X-Carlos-Ref"), g.upstream.Load()) |
| + } |
| + if len(g.rec.resp) != 0 || len(g.rec.match) != 0 { |
| + t.Fatalf("responses %d, matches %d; want none", len(g.rec.resp), len(g.rec.match)) |
| + } |
| +} |
| + |
| +// outcomeActivator keeps the outcome of the request it serves, so a test can |
| +// see what the guard left on it. |
| +type outcomeActivator struct{ out *outcome } |
| + |
| +func (a *outcomeActivator) ServeHTTP(w http.ResponseWriter, r *http.Request, rt registry.Route, proxy http.Handler) bool { |
| + a.out = outcomeFrom(r) |
| + w.WriteHeader(http.StatusOK) |
| + return true |
| +} |
| +func (a *outcomeActivator) RetireExcept(map[string]bool) {} |
| + |
| +// An ordinary request matches no rule: it is filed as a plain response and |
| +// the guard leaves no verdict on it. |
| +func TestGuardOrdinaryRequestUntouched(t *testing.T) { |
| + reg := openReg(t) |
| + if err := reg.Upsert(registry.Route{Host: "app.test", Kind: "instance", Socket: t.TempDir() + "/x.sock", Status: "ready", Hibernate: true, App: "shop"}); err != nil { |
| + t.Fatal(err) |
| + } |
| + act := &outcomeActivator{} |
| + e, err := New(reg, act) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + rec := &memRecorder{} |
| + e.EnableRequestRecords(rec) |
| + e.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest("GET", "http://app.test/blog/post", nil)) |
| + if len(rec.resp) != 1 || len(rec.match) != 0 { |
| + t.Fatalf("responses %d, matches %d; want 1 and 0", len(rec.resp), len(rec.match)) |
| + } |
| + if act.out == nil || act.out.guard == nil || act.out.guard.verdict != nil { |
| + t.Fatalf("outcome %+v: want the guard run and no verdict", act.out) |
| + } |
| +} |
| + |
| +// fieldSink keeps the fields of every record a real reqrec.Recorder writes. |
| +type fieldSink struct{ recs []map[string]string } |
| + |
| +func (s *fieldSink) Edge(acct, app, host, level, msg string, f map[string]string) { |
| + s.recs = append(s.recs, f) |
| +} |
| +func (s *fieldSink) EdgeSummary(acct, app, host, level, msg string, f map[string]string) {} |
| + |
| +// Review C1: a token in a watched probe's path must not reach the record by |
| +// way of the fragment, in its own spelling or case-folded. The rules compare |
| +// lower-cased text, and a folded token no longer looks mixed case to the |
| +// redactor, so the fragment is only the part the rule matched, in the |
| +// request's spelling. Through the real recorder, so this is what is stored. |
| +func TestGuardFragmentKeepsNoToken(t *testing.T) { |
| + const token = "AbCd12_EfGh34_IjKl56_MnOp78" |
| + for _, tc := range []struct{ name, path, frag string }{ |
| + {"underscores", "/wp-admin/" + token, "/wp-admin"}, |
| + {"hyphens", "/WP-Admin/AbCd12-EfGh34-IjKl56-MnOp78", "/WP-Admin"}, |
| + {"slashes", "/wp-admin/AbCd12/EfGh34/IjKl56/MnOp78", "/wp-admin"}, |
| + {"under a segseq", "/Proc/Self/AbCd12_EfGh34_IjKl56_MnOp78", "Proc/Self"}, |
| + } { |
| + g := guardEdge(t, false, false, http.StatusNotFound, "no") |
| + sink := &fieldSink{} |
| + g.e.EnableRequestRecords(reqrec.NewRecorder(sink, nil, nil)) |
| + g.get(tc.path) |
| + if len(sink.recs) != 1 { |
| + t.Fatalf("%s: %d records, want 1", tc.name, len(sink.recs)) |
| + } |
| + f := sink.recs[0] |
| + if f["kind"] != string(reqrec.KindWatch) || f["frag"] != tc.frag { |
| + t.Fatalf("%s: kind %q frag %q, want watch and %q", tc.name, f["kind"], f["frag"], tc.frag) |
| + } |
| + for _, piece := range []string{"AbCd12", "EfGh34", "IjKl56", "MnOp78"} { |
| + for _, spelt := range []string{piece, strings.ToLower(piece)} { |
| + if strings.Contains(f["frag"], spelt) { |
| + t.Errorf("%s: frag %q keeps %q", tc.name, f["frag"], spelt) |
| + } |
| + } |
| + } |
| + } |
| +} |
| + |
| +// Review I2: a door caller is the platform, not a visitor, on the box its |
| +// door is on and on the box a backhaul carried it to, where it arrives as a |
| +// verified hop carrying the door mark. Neither is guarded, even in block |
| +// mode. A door mark on anything but a verified hop is a header a client made |
| +// up, and that request is guarded like any other. |
| +func TestGuardSkipsDoorCalls(t *testing.T) { |
| + const probe = "/wp-login.php" |
| + served := func(t *testing.T, name string, g *guardRig, w *httptest.ResponseRecorder) { |
| + t.Helper() |
| + if w.Code != 200 || w.Header().Get("X-Carlos-Ref") != "" || g.upstream.Load() != 1 { |
| + t.Fatalf("%s: %d ref %q, upstream %d; want the app's answer", name, w.Code, w.Header().Get("X-Carlos-Ref"), g.upstream.Load()) |
| + } |
| + if len(g.rec.match) != 0 || len(g.rec.resp) != 1 { |
| + t.Fatalf("%s: responses %d, matches %d; want 1 and 0", name, len(g.rec.resp), len(g.rec.match)) |
| + } |
| + } |
| + blocked := func(t *testing.T, name string, g *guardRig, w *httptest.ResponseRecorder) { |
| + t.Helper() |
| + if w.Code != 404 || w.Header().Get("X-Carlos-Ref") == "" || g.upstream.Load() != 0 { |
| + t.Fatalf("%s: %d ref %q, upstream %d; want the block page", name, w.Code, w.Header().Get("X-Carlos-Ref"), g.upstream.Load()) |
| + } |
| + if len(g.rec.match) != 1 || g.rec.match[0].Kind != reqrec.KindBlock || g.rec.match[0].RuleID != "probe.wordpress.wp-login" { |
| + t.Fatalf("%s: matches %+v", name, g.rec.match) |
| + } |
| + } |
| + serve := func(g *guardRig, r *http.Request) *httptest.ResponseRecorder { |
| + w := httptest.NewRecorder() |
| + g.e.ServeHTTP(w, r) |
| + return w |
| + } |
| + |
| + // The door on this box: serveDoor's mark on the context. |
| + g := guardEdge(t, false, false, http.StatusOK, "app") |
| + g.e.guard = guardBlock |
| + r := httptest.NewRequest("GET", "http://app.test"+probe, nil) |
| + owner := doorCaller{Account: release.RouteAccount(registry.Route{}), App: "shop"} |
| + r = r.WithContext(context.WithValue(r.Context(), doorCallerKey{}, owner)) |
| + served(t, "local door call", g, serve(g, r)) |
| + |
| + now := time.Now() |
| + hop := func(g *guardRig, auth string, door []string) *http.Request { |
| + r := httptest.NewRequest("GET", "http://app.test"+probe, nil) |
| + r.Header.Set(hopHeader, "1") |
| + if auth != "" { |
| + r.Header.Set(hopAuthHeader, auth) |
| + } |
| + if door != nil { |
| + r.Header[hopDoorHeader] = door |
| + } |
| + return r |
| + } |
| + |
| + // Backhauled from the box the door is on: a verified hop with the mark. |
| + g = guardEdge(t, false, true, http.StatusOK, "app") |
| + g.e.guard = guardBlock |
| + served(t, "forwarded door call", g, serve(g, hop(g, signHop(g.key, "app.test", now), []string{signHopDoor(g.key, "app.test", now)}))) |
| + |
| + // The same mark on a hop that does not verify, or with no hop at all, is |
| + // a client's header. A verified hop without the mark is a visitor sent |
| + // on by another box. |
| + for _, tc := range []struct { |
| + name string |
| + req func(g *guardRig) *http.Request |
| + }{ |
| + {"door mark on an unverified hop", func(g *guardRig) *http.Request { |
| + return hop(g, "0:deadbeef", []string{signHopDoor(g.key, "app.test", now)}) |
| + }}, |
| + {"door mark with no hop", func(g *guardRig) *http.Request { |
| + r := httptest.NewRequest("GET", "http://app.test"+probe, nil) |
| + r.Header.Set(hopDoorHeader, signHopDoor(g.key, "app.test", now)) |
| + return r |
| + }}, |
| + {"door mark that does not verify", func(g *guardRig) *http.Request { |
| + return hop(g, signHop(g.key, "app.test", now), []string{"0:deadbeef"}) |
| + }}, |
| + {"verified hop without a door mark", func(g *guardRig) *http.Request { |
| + return hop(g, signHop(g.key, "app.test", now), nil) |
| + }}, |
| + } { |
| + g := guardEdge(t, false, true, http.StatusOK, "app") |
| + g.e.guard = guardBlock |
| + blocked(t, tc.name, g, serve(g, tc.req(g))) |
| + } |
| +} |
| + |
| +// Review M1: the guard's per-request state is the struct alone. The mint |
| +// function is bound once in New, not taken as a method value per request. |
| +func TestGuardStateAllocs(t *testing.T) { |
| + g := guardEdge(t, false, false, http.StatusOK, "app") |
| + var keep *guardState |
| + if n := testing.AllocsPerRun(100, func() { keep = g.e.newGuardState() }); n != 1 { |
| + t.Fatalf("newGuardState allocates %v times, want 1 (the struct)", n) |
| + } |
| + if keep.mint == nil { |
| + t.Fatal("no mint function bound") |
| + } |
| +} |
diff --git a/internal/edge/redirects.go b/internal/edge/redirects.go| index f38a1d416..df918c316 100644 |
| --- a/internal/edge/redirects.go |
| +++ b/internal/edge/redirects.go |
| @@ -410,6 +410,35 @@ func (rs *redirectRules) resolve(host, p, rawPath, rawQuery string, exists bool) |
| return redirectAction{}, false |
| } |
| +// names reports whether some rule names the cleaned path p outright for |
| +// host: a rule with no splat and no ":name" segment, whose source segments |
| +// are p's. Such a rule is the site saying it has a page at p, wherever the |
| +// file is. A catch-all or a placeholder rule says nothing of the kind, because |
| +// it answers paths the site never listed. A nil set names nothing. |
| +func (rs *redirectRules) names(host, p string) bool { |
| + if rs == nil { |
| + return false |
| + } |
| + var reqSegs []string |
| + if p != "/" { |
| + reqSegs = strings.Split(p[1:], "/") |
| + } |
| +rules: |
| + for i := range rs.rules { |
| + rule := &rs.rules[i] |
| + if rule.splat || len(rule.segs) != len(reqSegs) || rule.host != "" && rule.host != host { |
| + continue |
| + } |
| + for j, seg := range rule.segs { |
| + if strings.HasPrefix(seg, ":") || seg != reqSegs[j] { |
| + continue rules |
| + } |
| + } |
| + return true |
| + } |
| + return false |
| +} |
| + |
| // hostOf is the host of a "scheme://host[:port]" prefix, normalized as |
| // requestHost normalizes a request's. |
| func hostOf(prefix string) string { |
diff --git a/internal/edge/reqrecords.go b/internal/edge/reqrecords.go| index 15c6121c7..4a9d5a812 100644 |
| --- a/internal/edge/reqrecords.go |
| +++ b/internal/edge/reqrecords.go |
| @@ -31,9 +31,9 @@ func (e *Edge) EnableRequestRecords(rec RequestRecorder) { |
| e.requestRecords.Store(&requestRecorderRef{rec}) |
| } |
| -// requestResponse is the Response for r on rt, shared by the observer defer |
| -// and recordMatch so a match and a plain response describe a request the |
| -// same way. Woke is left for the caller: only the defer knows it. When is |
| +// requestResponse is the Response for r on rt, shared by the observer |
| +// defer's plain responses and matches so both describe a request the same |
| +// way. Woke is left for the caller: only the defer knows it. When is |
| // left zero, so the recorder stamps it from its own clock; the environment |
| // is the route's as it was when this request was served. |
| func requestResponse(rt registry.Route, r *http.Request, status int) reqrec.Response { |
| @@ -69,32 +69,36 @@ func (e *Edge) observeRecords(rt registry.Route, viaTunnel bool, r *http.Request |
| status = http.StatusOK // nothing written: net/http answers 200 |
| } |
| x := requestResponse(rt, r, status) |
| + // A request a protection rule matched is filed as one Match in place of |
| + // the Response, never both: the Match carries the same response, so a |
| + // second record would count the request twice. |
| + if out != nil && out.guard != nil && out.guard.verdict != nil { |
| + v := out.guard.verdict |
| + kind := reqrec.KindWatch |
| + if v.block { |
| + // A blocked request never reached the activator, so it woke |
| + // nothing, and that is known on whichever box answered it. |
| + kind = reqrec.KindBlock |
| + x.WokeKnown, x.Woke = true, false |
| + } else { |
| + // A watched one was forwarded like any other request, so what |
| + // 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}) |
| + return |
| + } |
| x.WokeKnown = !viaTunnel |
| x.Woke = out != nil && out.woke |
| ref.Response(x) |
| } |
| -// recordMatch files a Match for a request a protection rule blocked (kind |
| -// KindBlock) or only watched (KindWatch), and returns the reference code the |
| -// block page shows. The code is sealed with the current mesh key when this |
| -// box has one, and unsealed otherwise, so a box outside the mesh can still |
| -// show one. It is returned even when recording is off: the visitor's page |
| -// does not depend on whether anything was written. |
| -// |
| -// frag must already have passed through reqrec.Fragment. |
| -func (e *Edge) recordMatch(rt registry.Route, r *http.Request, kind reqrec.Kind, tier reqrec.Tier, ruleID, frag string, status int) string { |
| +// mintRef returns the reference code for a block by the rule ruleID of tier. |
| +// The code is sealed with the current mesh key when this box has one, and |
| +// unsealed otherwise, so a box outside the mesh can still show one. Minting |
| +// writes nothing: the visitor's page does not depend on whether recording |
| +// is on, and the observer defer files the Match that carries the code. |
| +func (e *Edge) mintRef(tier reqrec.Tier, ruleID string) string { |
| key, _ := e.homes.Load().meshKeys() |
| - code := reqrec.NewRef(time.Now(), tier, ruleID, e.box, key) |
| - ref := e.requestRecords.Load() |
| - if ref == nil { |
| - return code |
| - } |
| - x := requestResponse(rt, r, status) |
| - // A blocked request never reaches the activator, so it woke nothing, and |
| - // that is known on whichever box answers it. A watched one is forwarded |
| - // and may wake the app, which nothing passed in here says, so its record |
| - // leaves woke out rather than claim it did not. |
| - x.WokeKnown = kind == reqrec.KindBlock |
| - ref.Match(reqrec.Match{Response: x, Kind: kind, Tier: tier, RuleID: ruleID, Fragment: frag, Ref: code}) |
| - return code |
| + return reqrec.NewRef(time.Now(), tier, ruleID, e.box, key) |
| } |
diff --git a/internal/edge/reqrecords_test.go b/internal/edge/reqrecords_test.go| index 16ad3ef9b..3ff1860bd 100644 |
| --- a/internal/edge/reqrecords_test.go |
| +++ b/internal/edge/reqrecords_test.go |
| @@ -24,25 +24,36 @@ func TestRecordsSeeAppNotFound(t *testing.T) { |
| e := edgeWithBackend(t, http.NotFoundHandler()) |
| rec := &memRecorder{} |
| e.EnableRequestRecords(rec) |
| - req := httptest.NewRequest("GET", "http://app.test/wp-login.php?x=1", nil) |
| + req := httptest.NewRequest("GET", "http://app.test/old-page.html?x=1", nil) |
| e.ServeHTTP(httptest.NewRecorder(), req) |
| - if len(rec.resp) != 1 || rec.resp[0].Status != 404 || rec.resp[0].Path != "/wp-login.php" || rec.resp[0].RawQuery != "x=1" || !rec.resp[0].WokeKnown { |
| + if len(rec.resp) != 1 || rec.resp[0].Status != 404 || rec.resp[0].Path != "/old-page.html" || rec.resp[0].RawQuery != "x=1" || !rec.resp[0].WokeKnown { |
| t.Fatalf("got %+v", rec.resp) |
| } |
| } |
| -// The edge leaves When unset: the recorder stamps it with its own clock, so |
| -// one clock decides which minute a request lands in. |
| +// The edge leaves When unset, on a plain response and on a match alike: the |
| +// recorder stamps it with its own clock, so one clock decides which minute a |
| +// request lands in. A match also carries the route's environment as it was |
| +// when the request was served, as a plain response does. |
| func TestRecordsLeaveWhenToTheRecorder(t *testing.T) { |
| e := edgeWithBackend(t, http.NotFoundHandler()) |
| + if err := e.reg.SetEnvironment("app.test", "staging"); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := e.Reload(); err != nil { |
| + t.Fatal(err) |
| + } |
| + e.guard = guardBlock |
| rec := &memRecorder{} |
| e.EnableRequestRecords(rec) |
| e.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest("GET", "http://app.test/x", nil)) |
| - rt := registry.Route{Host: "app.test", App: "shop"} |
| - e.recordMatch(rt, httptest.NewRequest("GET", "http://app.test/.env", nil), reqrec.KindBlock, reqrec.TierHard, "dotenv", "", 404) |
| + e.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest("GET", "http://app.test/.env", nil)) |
| if len(rec.resp) != 1 || !rec.resp[0].When.IsZero() || len(rec.match) != 1 || !rec.match[0].When.IsZero() { |
| t.Fatalf("resp %+v match %+v", rec.resp, rec.match) |
| } |
| + if rec.match[0].Environment != "staging" { |
| + t.Fatalf("environment %q, want the route's", rec.match[0].Environment) |
| + } |
| } |
| // The hub that forwarded a request over the tunnel records it; the box it |
| @@ -58,36 +69,41 @@ func TestRecordsSkipTunnelDelivered(t *testing.T) { |
| } |
| } |
| -// recordMatch seals its reference code with the mesh key, so the code it |
| -// hands back verifies against that key and is the one the match carries. |
| -func TestRecordMatchReturnsSealedCode(t *testing.T) { |
| +// mintRef seals its reference code with the mesh key, so the code verifies |
| +// against that key and names the tier and rule it was minted for. |
| +func TestMintRefSealed(t *testing.T) { |
| e, _, key := proofEdge(t, true) |
| - rec := &memRecorder{} |
| - e.EnableRequestRecords(rec) |
| - rt := registry.Route{Host: "app.test", App: "shop"} |
| - rt.Environment = "staging" |
| - code := e.recordMatch(rt, httptest.NewRequest("GET", "http://app.test/.env", nil), reqrec.KindBlock, reqrec.TierHard, "dotenv", "", 404) |
| + code := e.mintRef(reqrec.TierHard, "hard.secrets.env") |
| r, err := reqrec.ParseRef(code, key) |
| - if err != nil || !r.Verified || len(rec.match) != 1 || rec.match[0].Ref != code { |
| - t.Fatalf("code %q: %+v %v; matches %d", code, r, err, len(rec.match)) |
| - } |
| - if rec.match[0].Environment != "staging" { |
| - t.Fatalf("environment %q, want the route's", rec.match[0].Environment) |
| + if err != nil || !r.Verified || r.Tier != reqrec.TierHard || r.RuleHash != reqrec.RuleHash("hard.secrets.env") { |
| + t.Fatalf("code %q: %+v %v", code, r, err) |
| } |
| } |
| -// With recording off, recordMatch still hands back a code: the block page |
| -// shows it whether or not anything was written. With no home map there is no |
| -// mesh key, so the code is unsealed rather than missing. |
| -func TestRecordMatchCodeWithoutRecorder(t *testing.T) { |
| +// With no home map there is no mesh key, so mintRef hands back an unsealed |
| +// code rather than none: the block page shows one either way, and whether |
| +// anything is recorded does not change it. |
| +func TestMintRefUnsealed(t *testing.T) { |
| e, _, _ := proofEdge(t, false) |
| - rt := registry.Route{Host: "app.test", App: "shop"} |
| - code := e.recordMatch(rt, httptest.NewRequest("GET", "http://app.test/.env", nil), reqrec.KindBlock, reqrec.TierHard, "dotenv", "", 404) |
| + code := e.mintRef(reqrec.TierHard, "hard.secrets.env") |
| if r, err := reqrec.ParseRef(code); err != nil || r.Sealed || r.Tier != reqrec.TierHard { |
| t.Fatalf("code %q: %+v %v", code, r, err) |
| } |
| } |
| +// In block mode with recording off, the visitor still gets the block page |
| +// and its code: the page does not depend on whether anything was written. |
| +func TestGuardBlockWithoutRecorder(t *testing.T) { |
| + e := edgeWithBackend(t, http.NotFoundHandler()) |
| + e.guard = guardBlock |
| + w := httptest.NewRecorder() |
| + e.ServeHTTP(w, httptest.NewRequest("GET", "http://app.test/.env", nil)) |
| + code := w.Header().Get("X-Carlos-Ref") |
| + if r, err := reqrec.ParseRef(code); w.Code != 404 || err != nil || r.Tier != reqrec.TierHard { |
| + t.Fatalf("%d, code %q: %+v %v", w.Code, code, r, err) |
| + } |
| +} |
| + |
| // wakingActivator answers every request as an activator that woke the |
| // instance for it would: MarkWoke, the call internal/activator's begin makes |
| // for the request that starts a wake, then the app's answer. |
diff --git a/internal/edge/static.go b/internal/edge/static.go| index 2f2fd0907..b1f783f89 100644 |
| --- a/internal/edge/static.go |
| +++ b/internal/edge/static.go |
| @@ -35,8 +35,10 @@ import ( |
| "time" |
| "github.com/carlosframework/platform/internal/apperr" |
| + "github.com/carlosframework/platform/internal/edgeguard" |
| "github.com/carlosframework/platform/internal/registry" |
| "github.com/carlosframework/platform/internal/release" |
| + "github.com/carlosframework/platform/internal/reqrec" |
| ) |
| // siteArtifactFile is the one artifact a static release carries: the gzipped |
| @@ -469,6 +471,13 @@ func (s *staticSite) serveTree(tree servedTree, w http.ResponseWriter, r *http.R |
| // Clean rooted at "/" so no request path can climb out of the tree. |
| p := path.Clean("/" + r.URL.Path) |
| status, rewritten := http.StatusOK, false |
| + // guard is whether the guard still has this request to decide: it runs |
| + // for r, and ServeHTTP's hard check on the request path noted nothing. |
| + // probe is the probe tier's hit on the request path, held rather than |
| + // decided until the rules have had their say, because a rewrite onto a |
| + // hard-tier file must be the verdict instead (one verdict per request). |
| + guard := staticGuardPending(r) |
| + var probe edgeguard.Hit |
| for { |
| fp := filepath.Join(tree.dir, filepath.FromSlash(p)) |
| fi, err := os.Stat(fp) |
| @@ -479,17 +488,48 @@ func (s *staticSite) serveTree(tree servedTree, w http.ResponseWriter, r *http.R |
| // The _redirects file is configuration and answers nothing. |
| found := err == nil && !fi.IsDir() && p != "/"+redirectsFile |
| if !rewritten { |
| - if act, ok := tree.redirects.resolve(requestHost(r.Host), p, r.URL.Path, r.URL.RawQuery, found); ok { |
| - if act.location != "" { |
| - http.Redirect(w, r, act.location, act.status) |
| - return |
| - } |
| + // The probe tier, which ServeHTTP leaves to the tree: a path like |
| + // /wp-login.php is a probe only when the site has no such page, |
| + // and only the tree knows. A _redirects rule that names the path |
| + // outright counts as a page there; a catch-all or placeholder rule |
| + // does not, or one "/* /index.html 200" would exempt every probe. |
| + // It is decided before the rules act, so a blocked probe is never |
| + // redirected or given the fallback page; a rewrite is decided |
| + // 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) |
| + } |
| + act, ok := tree.redirects.resolve(requestHost(r.Host), p, r.URL.Path, r.URL.RawQuery, found) |
| + if ok && act.location == "" { |
| // A rewrite serves another file of the tree at this URL. It is |
| // looked up once: rules are not consulted a second time, and a |
| // destination with no file is a plain 404. |
| p, status, rewritten = act.file, act.status, true |
| continue |
| } |
| + if probe.Rule != nil && guardDecide(w, r, probe) { |
| + return |
| + } |
| + if ok { |
| + http.Redirect(w, r, act.location, act.status) |
| + return |
| + } |
| + } else if guard { |
| + // A rewrite sends a file the request did not name, so the request's |
| + // own path passing the hard tier in ServeHTTP says nothing about |
| + // it: /download rewritten onto /.env would serve a leak. A hard |
| + // hit on a file that is there wins over the request path's probe |
| + // hit, which says only what the visitor asked for: "/* /.env 200" |
| + // must not serve the secret as a watched /admin. |
| + hit := probe |
| + if found { |
| + if h, ok := edgeguard.CheckTier(p, "", reqrec.TierHard); ok { |
| + hit = h |
| + } |
| + } |
| + if hit.Rule != nil && guardDecide(w, r, hit) { |
| + return |
| + } |
| } |
| if !found { |
| http.NotFound(w, r) |
| @@ -511,6 +551,15 @@ 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. |
| +func staticGuardPending(r *http.Request) bool { |
| + out := outcomeFrom(r) |
| + return out != nil && out.guard != nil && out.guard.verdict == nil |
| +} |
| + |
| // serveFile sends the tree file at fp, whose tree path is p (for logs). A 200 |
| // gets a content tag and net/http's conditional and range handling. Any other |
| // status — a _redirects 404 page — is the file's bytes under that status, |
diff --git a/internal/edge/static_guard_test.go b/internal/edge/static_guard_test.go| new file mode 100644 |
| index 000000000..faae416a1 |
| --- /dev/null |
| +++ b/internal/edge/static_guard_test.go |
| @@ -0,0 +1,313 @@ |
| +package edge |
| + |
| +import ( |
| + "context" |
| + "net/http/httptest" |
| + "path/filepath" |
| + "testing" |
| + |
| + "github.com/carlosframework/platform/internal/registry" |
| + "github.com/carlosframework/platform/internal/release" |
| + "github.com/carlosframework/platform/internal/reqrec" |
| +) |
| + |
| +// staticGuardRig is a whole edge over one static route for site.example.com, |
| +// serving files, with a recorder that keeps every record. Requests go through |
| +// ServeHTTP, so the guard state exists as it does in production. |
| +type staticGuardRig struct { |
| + e *Edge |
| + rec *memRecorder |
| +} |
| + |
| +func staticGuardEdge(t *testing.T, mode guardMode, files map[string]string) *staticGuardRig { |
| + t.Helper() |
| + store := release.NewDirStore(filepath.Join(t.TempDir(), "store")) |
| + priv, pub := testKeys(t) |
| + shipSite(t, store, "site", "v1", files) |
| + if err := release.Promote(context.Background(), store, priv, release.OpsAccount, "site", "canary/x", "v1"); err != nil { |
| + t.Fatalf("Promote: %v", err) |
| + } |
| + reg := openReg(t) |
| + if err := reg.Upsert(registry.Route{Host: "site.example.com", Kind: "static", App: "site", Channel: "canary/x", Status: "ready"}); err != nil { |
| + t.Fatalf("upsert: %v", err) |
| + } |
| + e, err := New(reg, nil) |
| + if err != nil { |
| + t.Fatalf("New: %v", err) |
| + } |
| + t.Cleanup(e.probers.Stop) |
| + e.EnableStatic(store, pub, filepath.Join(t.TempDir(), "cache")) |
| + if err := e.Reload(); err != nil { |
| + t.Fatalf("Reload: %v", err) |
| + } |
| + rec := &memRecorder{} |
| + e.EnableRequestRecords(rec) |
| + e.guard = mode |
| + return &staticGuardRig{e: e, rec: rec} |
| +} |
| + |
| +func (g *staticGuardRig) get(path string) *httptest.ResponseRecorder { |
| + w := httptest.NewRecorder() |
| + g.e.ServeHTTP(w, httptest.NewRequest("GET", "http://site.example.com"+path, nil)) |
| + return w |
| +} |
| + |
| +// onlyMatch fails unless the recorder holds exactly one Match and no plain |
| +// Response, and returns that Match. |
| +func (g *staticGuardRig) onlyMatch(t *testing.T) reqrec.Match { |
| + t.Helper() |
| + if len(g.rec.resp) != 0 || len(g.rec.match) != 1 { |
| + t.Fatalf("responses %+v, matches %+v; want 0 and 1", g.rec.resp, g.rec.match) |
| + } |
| + return g.rec.match[0] |
| +} |
| + |
| +// onlyResponse fails unless the recorder holds exactly one plain Response and |
| +// no Match, and returns that Response. |
| +func (g *staticGuardRig) onlyResponse(t *testing.T) reqrec.Response { |
| + t.Helper() |
| + if len(g.rec.resp) != 1 || len(g.rec.match) != 0 { |
| + t.Fatalf("responses %+v, matches %+v; want 1 and 0", g.rec.resp, g.rec.match) |
| + } |
| + return g.rec.resp[0] |
| +} |
| + |
| +// A site without the file is asked for a probe path: the tree's own answer is |
| +// a 404, and the one record is a watch for the probe rule carrying it. In |
| +// block mode the guard's block page answers instead. |
| +func TestStaticProbeAbsentIsMatched(t *testing.T) { |
| + files := map[string]string{"index.html": "home"} |
| + |
| + g := staticGuardEdge(t, guardCatalogue, files) |
| + if w := g.get("/wp-login.php"); w.Code != 404 { |
| + t.Fatalf("watch: status %d, want 404", w.Code) |
| + } |
| + m := g.onlyMatch(t) |
| + if m.Kind != reqrec.KindWatch || m.Tier != reqrec.TierProbe || m.RuleID != "probe.wordpress.wp-login" || m.Status != 404 || m.Ref != "" { |
| + t.Fatalf("watch: match %+v", m) |
| + } |
| + |
| + g = staticGuardEdge(t, guardBlock, files) |
| + w := g.get("/wp-login.php") |
| + if w.Code != 404 || w.Header().Get("X-Carlos-Ref") == "" { |
| + t.Fatalf("block: %d ref %q", w.Code, w.Header().Get("X-Carlos-Ref")) |
| + } |
| + m = g.onlyMatch(t) |
| + if m.Kind != reqrec.KindBlock || m.RuleID != "probe.wordpress.wp-login" || m.Ref != w.Header().Get("X-Carlos-Ref") { |
| + t.Fatalf("block: match %+v", m) |
| + } |
| +} |
| + |
| +// A probe-looking path the site really has is the site's own page: served |
| +// with its bytes, in block mode too, and nothing is recorded as a match. |
| +func TestStaticProbePresentIsServed(t *testing.T) { |
| + for _, tc := range []struct { |
| + name string |
| + files map[string]string |
| + path string |
| + body string |
| + }{ |
| + {"file", map[string]string{"wp-login.php": "a login page of my own"}, "/wp-login.php", "a login page of my own"}, |
| + {"directory index", map[string]string{"administrator/index.html": "our administrators"}, "/administrator/", "our administrators"}, |
| + } { |
| + for _, mode := range []guardMode{guardCatalogue, guardBlock} { |
| + g := staticGuardEdge(t, mode, tc.files) |
| + w := g.get(tc.path) |
| + if w.Code != 200 || w.Body.String() != tc.body { |
| + t.Fatalf("%s, mode %d: %d %q", tc.name, mode, w.Code, w.Body.String()) |
| + } |
| + if r := g.onlyResponse(t); r.Status != 200 { |
| + t.Fatalf("%s, mode %d: response %+v", tc.name, mode, r) |
| + } |
| + } |
| + } |
| +} |
| + |
| +// Review Focus 4: a catch-all rule answers every path, so it says nothing |
| +// about which paths the site has. A probe path it would answer is still a |
| +// probe, and in block mode it is blocked rather than given the fallback page. |
| +func TestStaticSplatIsNotExistence(t *testing.T) { |
| + files := map[string]string{"index.html": "the fallback page", "_redirects": "/* /index.html 200\n"} |
| + |
| + g := staticGuardEdge(t, guardCatalogue, files) |
| + if w := g.get("/wp-login.php"); w.Code != 200 || w.Body.String() != "the fallback page" { |
| + t.Fatalf("watch: %d %q, want the fallback page", w.Code, w.Body.String()) |
| + } |
| + m := g.onlyMatch(t) |
| + if m.Kind != reqrec.KindWatch || m.RuleID != "probe.wordpress.wp-login" || m.Status != 200 { |
| + t.Fatalf("watch: match %+v", m) |
| + } |
| + |
| + g = staticGuardEdge(t, guardBlock, files) |
| + w := g.get("/wp-login.php") |
| + if w.Code != 404 || w.Header().Get("X-Carlos-Ref") == "" || w.Body.String() == "the fallback page" { |
| + t.Fatalf("block: %d ref %q body %q", w.Code, w.Header().Get("X-Carlos-Ref"), w.Body.String()) |
| + } |
| + if m := g.onlyMatch(t); m.Kind != reqrec.KindBlock { |
| + t.Fatalf("block: match %+v", m) |
| + } |
| +} |
| + |
| +// A rule that names the path outright is the site declaring it has a page |
| +// there, so the answer is served and nothing is matched. |
| +func TestStaticExplicitRedirectIsExistence(t *testing.T) { |
| + files := map[string]string{"api/rpc.html": "our rpc docs", "_redirects": "/xmlrpc.php /api/rpc.html 200\n"} |
| + for _, mode := range []guardMode{guardCatalogue, guardBlock} { |
| + g := staticGuardEdge(t, mode, files) |
| + if w := g.get("/xmlrpc.php"); w.Code != 200 || w.Body.String() != "our rpc docs" { |
| + t.Fatalf("mode %d: %d %q", mode, w.Code, w.Body.String()) |
| + } |
| + g.onlyResponse(t) |
| + } |
| +} |
| + |
| +// A rewrite onto a file the hard tier names is not served as a rewrite: the |
| +// request path looked harmless, the file it would send is a leak. Watching |
| +// records it and serves the file; blocking answers with the guard's 404. |
| +func TestStaticRewriteToHardFile(t *testing.T) { |
| + files := map[string]string{".env": "SECRET=1", "_redirects": "/download /.env 200\n"} |
| + |
| + g := staticGuardEdge(t, guardCatalogue, files) |
| + if w := g.get("/download"); w.Code != 200 || w.Body.String() != "SECRET=1" { |
| + t.Fatalf("watch: %d %q, want the file served", w.Code, w.Body.String()) |
| + } |
| + m := g.onlyMatch(t) |
| + if m.Kind != reqrec.KindWatch || m.Tier != reqrec.TierHard || m.RuleID != "hard.secrets.env" || m.Status != 200 { |
| + t.Fatalf("watch: match %+v", m) |
| + } |
| + |
| + g = staticGuardEdge(t, guardBlock, files) |
| + w := g.get("/download") |
| + if w.Code != 404 || w.Header().Get("X-Carlos-Ref") == "" || w.Body.String() == "SECRET=1" { |
| + t.Fatalf("block: %d ref %q body %q", w.Code, w.Header().Get("X-Carlos-Ref"), w.Body.String()) |
| + } |
| + m = g.onlyMatch(t) |
| + if m.Kind != reqrec.KindBlock || m.Tier != reqrec.TierHard || m.RuleID != "hard.secrets.env" || m.Ref != w.Header().Get("X-Carlos-Ref") { |
| + t.Fatalf("block: match %+v", m) |
| + } |
| +} |
| + |
| +// Review I1: a request path the probe tier would note, rewritten onto a file |
| +// the hard tier names. The hard hit on what would be sent is the verdict, |
| +// not the probe hit on what was asked for: blocking answers with the guard's |
| +// 404 rather than the secret, and watching records the leak, not /admin. |
| +func TestStaticRewriteToHardFileOverProbe(t *testing.T) { |
| + files := map[string]string{".env": "SECRET=1", "_redirects": "/* /.env 200\n"} |
| + |
| + g := staticGuardEdge(t, guardWatch, files) |
| + if w := g.get("/admin"); w.Code != 200 || w.Body.String() != "SECRET=1" { |
| + t.Fatalf("watch: %d %q, want the file served", w.Code, w.Body.String()) |
| + } |
| + m := g.onlyMatch(t) |
| + if m.Kind != reqrec.KindWatch || m.Tier != reqrec.TierHard || m.RuleID != "hard.secrets.env" || m.Status != 200 || m.Ref != "" { |
| + t.Fatalf("watch: match %+v", m) |
| + } |
| + |
| + g = staticGuardEdge(t, guardBlock, files) |
| + w := g.get("/admin") |
| + if w.Code != 404 || w.Header().Get("X-Carlos-Ref") == "" || w.Body.String() == "SECRET=1" { |
| + t.Fatalf("block: %d ref %q body %q", w.Code, w.Header().Get("X-Carlos-Ref"), w.Body.String()) |
| + } |
| + m = g.onlyMatch(t) |
| + if m.Kind != reqrec.KindBlock || m.Tier != reqrec.TierHard || m.RuleID != "hard.secrets.env" || m.Ref != w.Header().Get("X-Carlos-Ref") { |
| + t.Fatalf("block: match %+v", m) |
| + } |
| +} |
| + |
| +// The other side of that order: a rewrite onto an ordinary file leaves the |
| +// request path's probe hit as the verdict, and so does a rewrite onto a |
| +// hard-tier name the tree does not have, which sends nothing. |
| +func TestStaticRewriteKeepsProbeVerdict(t *testing.T) { |
| + for _, tc := range []struct { |
| + name, redirects string |
| + code int |
| + }{ |
| + {"ordinary target", "/* /index.html 200\n", 200}, |
| + {"absent hard target", "/* /.env 200\n", 404}, |
| + } { |
| + g := staticGuardEdge(t, guardWatch, map[string]string{"index.html": "home", "_redirects": tc.redirects}) |
| + if w := g.get("/wp-login.php"); w.Code != tc.code { |
| + t.Fatalf("%s: status %d, want %d", tc.name, w.Code, tc.code) |
| + } |
| + m := g.onlyMatch(t) |
| + if m.Kind != reqrec.KindWatch || m.Tier != reqrec.TierProbe || m.RuleID != "probe.wordpress.wp-login" || m.Status != tc.code { |
| + t.Fatalf("%s: match %+v", tc.name, m) |
| + } |
| + } |
| +} |
| + |
| +// A hard-tier path asked for directly is decided by the check in ServeHTTP, |
| +// before the static handler runs. The handler must not file it a second time. |
| +func TestStaticHardAtEdgeOnce(t *testing.T) { |
| + files := map[string]string{".env": "SECRET=1", "index.html": "home"} |
| + for _, mode := range []guardMode{guardCatalogue, guardBlock} { |
| + g := staticGuardEdge(t, mode, files) |
| + w := g.get("/.env") |
| + if mode == guardBlock && w.Code != 404 { |
| + t.Fatalf("block: status %d, want 404", w.Code) |
| + } |
| + m := g.onlyMatch(t) |
| + if m.Tier != reqrec.TierHard || m.RuleID != "hard.secrets.env" { |
| + t.Fatalf("mode %d: match %+v", mode, m) |
| + } |
| + } |
| +} |
| + |
| +// With the guard off for a request there is no state to decide on, so the |
| +// handler checks nothing and serves as it always did. |
| +func TestStaticGuardOffServesAsBefore(t *testing.T) { |
| + g := staticGuardEdge(t, guardOff, map[string]string{".env": "SECRET=1", "_redirects": "/download /.env 200\n/* /index.html 200\n", "index.html": "home"}) |
| + if w := g.get("/download"); w.Code != 200 || w.Body.String() != "SECRET=1" { |
| + t.Fatalf("%d %q", w.Code, w.Body.String()) |
| + } |
| + if w := g.get("/wp-login.php"); w.Code != 200 || w.Body.String() != "home" { |
| + t.Fatalf("%d %q", w.Code, w.Body.String()) |
| + } |
| + if len(g.rec.match) != 0 || len(g.rec.resp) != 2 { |
| + t.Fatalf("responses %d, matches %d; want 2 and 0", len(g.rec.resp), len(g.rec.match)) |
| + } |
| +} |
| + |
| +func TestRedirectNames(t *testing.T) { |
| + rs, err := parseRedirects([]byte("" + |
| + "/old /new 301\n" + |
| + "/blog/:slug /posts/:slug 301\n" + |
| + "/docs/* /d/:splat 200\n" + |
| + "/xmlrpc.php /api/rpc.html 200\n" + |
| + "https://other.example.com/only-there /x 301\n" + |
| + "/nested/deep/page /y 200\n")) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + for _, tc := range []struct { |
| + host, p string |
| + want bool |
| + }{ |
| + {"site.example.com", "/old", true}, |
| + {"site.example.com", "/xmlrpc.php", true}, |
| + {"site.example.com", "/nested/deep/page", true}, |
| + {"site.example.com", "/nested/deep", false}, |
| + {"site.example.com", "/blog/hello", false}, |
| + {"site.example.com", "/docs/a", false}, |
| + {"site.example.com", "/docs", false}, |
| + {"site.example.com", "/wp-login.php", false}, |
| + {"site.example.com", "/only-there", false}, |
| + {"other.example.com", "/only-there", true}, |
| + } { |
| + if got := rs.names(tc.host, tc.p); got != tc.want { |
| + t.Errorf("names(%q, %q) = %v, want %v", tc.host, tc.p, got, tc.want) |
| + } |
| + } |
| + var none *redirectRules |
| + if none.names("site.example.com", "/old") { |
| + t.Error("a nil rule set names nothing") |
| + } |
| + // A catch-all alone names no path in particular. |
| + all, err := parseRedirects([]byte("/* /index.html 200\n")) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if all.names("site.example.com", "/wp-login.php") { |
| + t.Error("a splat rule must not count as naming a path") |
| + } |
| +} |
diff --git a/internal/edgeguard/catalogue.go b/internal/edgeguard/catalogue.go| new file mode 100644 |
| index 000000000..95f580000 |
| --- /dev/null |
| +++ b/internal/edgeguard/catalogue.go |
| @@ -0,0 +1,370 @@ |
| +// Package edgeguard is the edge's catalogue of requests that no real visitor |
| +// makes, and the matcher that recognises them. |
| +// |
| +// The catalogue is a text file embedded in the binary. Every rule matches on |
| +// the structure of the request path (whole segments, an extension on the last |
| +// segment, a whole path or a leading path) or on the start of a query value. |
| +// None of them looks for a word inside a path, because a misfire on a real |
| +// visitor costs more than a missed probe: "/help/vat-in-the-european-union" |
| +// must stay a help page. |
| +package edgeguard |
| + |
| +import ( |
| + _ "embed" |
| + "fmt" |
| + "slices" |
| + "strconv" |
| + "strings" |
| + |
| + "github.com/carlosframework/platform/internal/reqrec" |
| +) |
| + |
| +// Mode says what the edge does with a request that matched a rule. |
| +type Mode uint8 |
| + |
| +const ( |
| + // ModeWatch records the match and lets the request through. |
| + ModeWatch Mode = iota |
| + // ModeBlock refuses the request. |
| + ModeBlock |
| + // ModeBurst counts the match toward a per-client burst limit instead of |
| + // acting on a single request (an admin page is a normal thing to visit |
| + // once). |
| + ModeBurst |
| +) |
| + |
| +func (m Mode) String() string { |
| + switch m { |
| + case ModeWatch: |
| + return "watch" |
| + case ModeBlock: |
| + return "block" |
| + case ModeBurst: |
| + return "burst" |
| + } |
| + return "unknown" |
| +} |
| + |
| +// Rule is one row of the catalogue. ID is "<tier>.<group>.<name>", for |
| +// example "hard.secrets.env". |
| +type Rule struct { |
| + ID string |
| + Group string |
| + Tier reqrec.Tier |
| + Mode Mode |
| + |
| + kind kind |
| + pattern string |
| +} |
| + |
| +// Hit is a rule that matched, with the text that matched it. Fragment is |
| +// only the part the rule matched, in the request's own spelling rather than |
| +// the case-folded text the rules compare: the whole cleaned path for an exact |
| +// rule, the pattern's leading segments for a prefix rule (never what lies |
| +// under them), the run of segments for a segseq rule, the matched segment for |
| +// a segment, segglob or ext rule, ".." for dotdot, and, when FromQuery is |
| +// set, the decoded value of the query parameter called QueryName. |
| +type Hit struct { |
| + Rule *Rule |
| + Fragment string |
| + FromQuery bool |
| + QueryName string |
| +} |
| + |
| +type kind uint8 |
| + |
| +const ( |
| + kindExact kind = iota + 1 |
| + kindPrefix |
| + kindSegment |
| + kindSegglob |
| + kindExt |
| + kindSegseq |
| + kindQparam |
| + kindDotdot |
| +) |
| + |
| +var kindNames = map[string]kind{ |
| + "exact": kindExact, |
| + "prefix": kindPrefix, |
| + "segment": kindSegment, |
| + "segglob": kindSegglob, |
| + "ext": kindExt, |
| + "segseq": kindSegseq, |
| + "qparam": kindQparam, |
| + "dotdot": kindDotdot, |
| +} |
| + |
| +var modeNames = map[string]Mode{"watch": ModeWatch, "block": ModeBlock, "burst": ModeBurst} |
| + |
| +//go:embed catalogue.txt |
| +var catalogueData []byte |
| + |
| +// Version is the catalogue's version. It is bumped whenever a rule is added, |
| +// removed or changed, so a log line can say which catalogue produced it. It |
| +// must equal the "# version N" line in catalogue.txt, and init panics if the |
| +// two disagree, so a rule edit that forgets one of them fails the tests. |
| +const Version = 1 |
| + |
| +var ( |
| + rules []Rule |
| + idx index |
| +) |
| + |
| +func init() { |
| + rs, v, err := parseCatalogue(catalogueData) |
| + if err != nil { |
| + panic(err) |
| + } |
| + if v != Version { |
| + panic(fmt.Sprintf("edgeguard catalogue: catalogue.txt says version %d but Version is %d", v, Version)) |
| + } |
| + ix, err := buildIndex(rs) |
| + if err != nil { |
| + panic(err) |
| + } |
| + rules, idx = rs, ix |
| +} |
| + |
| +// Rules returns the catalogue in file order. The caller may keep and modify |
| +// the slice. |
| +func Rules() []Rule { return slices.Clone(rules) } |
| + |
| +// RuleByHash finds the rule whose ID hashes to h under reqrec.RuleHash, which |
| +// is how a reference code names a rule. |
| +func RuleByHash(h uint32) (*Rule, bool) { |
| + i, ok := idx.byHash[h] |
| + if !ok { |
| + return nil, false |
| + } |
| + return &rules[i], 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. |
| +// Every error names the line that caused it. |
| +func parseCatalogue(data []byte) ([]Rule, int, error) { |
| + var ( |
| + out []Rule |
| + version int |
| + haveVer bool |
| + seen = map[string]bool{} |
| + sawProbe bool |
| + lineNumber int |
| + ) |
| + for _, line := range strings.Split(string(data), "\n") { |
| + lineNumber++ |
| + line = strings.TrimSpace(line) |
| + if line == "" { |
| + continue |
| + } |
| + rest, isVersion := strings.CutPrefix(line, "# version ") |
| + if !haveVer { |
| + // The version is the first thing in the file, so a catalogue |
| + // with rules ahead of it, or none, is refused. |
| + if !isVersion { |
| + return nil, 0, fmt.Errorf("edgeguard catalogue line %d: the first line must be \"# version N\"", lineNumber) |
| + } |
| + n, err := strconv.Atoi(strings.TrimSpace(rest)) |
| + if err != nil || n < 1 { |
| + return nil, 0, fmt.Errorf("edgeguard catalogue line %d: bad version %q", lineNumber, rest) |
| + } |
| + version, haveVer = n, true |
| + continue |
| + } |
| + if isVersion { |
| + return nil, 0, fmt.Errorf("edgeguard catalogue line %d: a second version line", lineNumber) |
| + } |
| + if strings.HasPrefix(line, "#") { |
| + continue |
| + } |
| + f := strings.Fields(line) |
| + if len(f) != 6 { |
| + return nil, 0, fmt.Errorf("edgeguard catalogue line %d: want 6 columns (tier group name kind pattern mode), got %d", lineNumber, len(f)) |
| + } |
| + tierName, group, name, kindName, pattern, modeName := f[0], f[1], f[2], f[3], f[4], f[5] |
| + var tier reqrec.Tier |
| + switch tierName { |
| + case "hard": |
| + tier = reqrec.TierHard |
| + if sawProbe { |
| + return nil, 0, fmt.Errorf("edgeguard catalogue line %d: hard rule after a probe rule (Check relies on hard rules coming first)", lineNumber) |
| + } |
| + case "probe": |
| + tier = reqrec.TierProbe |
| + sawProbe = true |
| + default: |
| + return nil, 0, fmt.Errorf("edgeguard catalogue line %d: unknown tier %q", lineNumber, tierName) |
| + } |
| + if !isName(group) || !isName(name) { |
| + return nil, 0, fmt.Errorf("edgeguard catalogue line %d: group %q and name %q must match [a-z0-9-]+", lineNumber, group, name) |
| + } |
| + k, ok := kindNames[kindName] |
| + if !ok { |
| + return nil, 0, fmt.Errorf("edgeguard catalogue line %d: unknown kind %q", lineNumber, kindName) |
| + } |
| + mode, ok := modeNames[modeName] |
| + if !ok { |
| + return nil, 0, fmt.Errorf("edgeguard catalogue line %d: unknown mode %q", lineNumber, modeName) |
| + } |
| + if err := checkPattern(k, pattern); err != nil { |
| + return nil, 0, fmt.Errorf("edgeguard catalogue line %d: %v", lineNumber, err) |
| + } |
| + id := tierName + "." + group + "." + name |
| + if seen[id] { |
| + return nil, 0, fmt.Errorf("edgeguard catalogue line %d: duplicate rule id %q", lineNumber, id) |
| + } |
| + seen[id] = true |
| + out = append(out, Rule{ID: id, Group: group, Tier: tier, Mode: mode, kind: k, pattern: pattern}) |
| + } |
| + if !haveVer { |
| + return nil, 0, fmt.Errorf("edgeguard catalogue line 1: missing \"# version N\" line") |
| + } |
| + return out, version, nil |
| +} |
| + |
| +func isName(s string) bool { |
| + if s == "" { |
| + return false |
| + } |
| + for i := 0; i < len(s); i++ { |
| + c := s[i] |
| + if !(c >= 'a' && c <= 'z' || c >= '0' && c <= '9' || c == '-') { |
| + return false |
| + } |
| + } |
| + return true |
| +} |
| + |
| +// checkPattern holds a pattern to what its kind can match. The matcher works |
| +// on lower-cased, cleaned paths, so a pattern that could never be equal to |
| +// one is a mistake in the file, not a rule that quietly never fires. |
| +func checkPattern(k kind, p string) error { |
| + for i := 0; i < len(p); i++ { |
| + if p[i] >= 'A' && p[i] <= 'Z' { |
| + return fmt.Errorf("pattern %q must be lower case", p) |
| + } |
| + } |
| + switch k { |
| + case kindExact, kindPrefix: |
| + if len(p) < 2 || p[0] != '/' || p[len(p)-1] == '/' { |
| + return fmt.Errorf("pattern %q must start with / and not end with /", p) |
| + } |
| + case kindSegment, kindExt: |
| + if strings.Contains(p, "/") || p == ".." || p == "." { |
| + return fmt.Errorf("pattern %q must be a single path segment", p) |
| + } |
| + case kindSegglob: |
| + if strings.Count(p, "*") != 1 || strings.Contains(p, "/") { |
| + return fmt.Errorf("segglob pattern %q must be one segment holding exactly one *", p) |
| + } |
| + case kindSegseq: |
| + if strings.HasPrefix(p, "/") || strings.HasSuffix(p, "/") || !strings.Contains(p, "/") { |
| + return fmt.Errorf("segseq pattern %q must be two or more segments without a leading or trailing /", p) |
| + } |
| + case kindQparam: |
| + if name, _, ok := strings.Cut(p, "="); !ok || name == "" { |
| + return fmt.Errorf("qparam pattern %q must be name=valueprefix", p) |
| + } |
| + case kindDotdot: |
| + if p != "-" { |
| + return fmt.Errorf("dotdot pattern must be -, got %q", p) |
| + } |
| + } |
| + return nil |
| +} |
| + |
| +// index is the catalogue arranged for lookup. Every entry holds the rule's |
| +// position in file order, and lists are in ascending position, so the matcher |
| +// can take the earliest hit across all kinds and get what a scan down the |
| +// file would give. |
| +type index struct { |
| + exact map[string][]int |
| + segment map[string][]int |
| + // prefix is keyed by the pattern's first segment, so a request path |
| + // needs one map lookup rather than one comparison per prefix rule. |
| + prefix map[string][]prefixEntry |
| + globs []globEntry |
| + exts []extEntry |
| + segseqs []seqEntry |
| + qparams []qparamEntry |
| + dotdots []int |
| + |
| + // minSeg and maxSeg bound the length of any segment rule's pattern, so |
| + // most segments skip the map lookup. |
| + minSeg, maxSeg int |
| + |
| + hardEnd int |
| + byHash map[uint32]int |
| +} |
| + |
| +type prefixEntry struct { |
| + pattern string |
| + pos int |
| +} |
| + |
| +type globEntry struct { |
| + prefix, suffix string |
| + pos int |
| +} |
| + |
| +type extEntry struct { |
| + suffix string |
| + pos int |
| +} |
| + |
| +type seqEntry struct { |
| + segs string |
| + pos int |
| +} |
| + |
| +type qparamEntry struct { |
| + name, nameEq, valuePrefix string |
| + pos int |
| +} |
| + |
| +func buildIndex(rs []Rule) (index, error) { |
| + ix := index{ |
| + exact: map[string][]int{}, |
| + segment: map[string][]int{}, |
| + prefix: map[string][]prefixEntry{}, |
| + byHash: map[uint32]int{}, |
| + minSeg: 1 << 30, |
| + } |
| + for i := range rs { |
| + r := &rs[i] |
| + if r.Tier == reqrec.TierHard { |
| + ix.hardEnd = i + 1 |
| + } |
| + h := reqrec.RuleHash(r.ID) |
| + if other, dup := ix.byHash[h]; dup { |
| + return index{}, fmt.Errorf("edgeguard catalogue: %q and %q share rule hash %08x", r.ID, rs[other].ID, h) |
| + } |
| + ix.byHash[h] = i |
| + switch r.kind { |
| + case kindExact: |
| + ix.exact[r.pattern] = append(ix.exact[r.pattern], i) |
| + case kindPrefix: |
| + first, _, _ := strings.Cut(r.pattern[1:], "/") |
| + ix.prefix[first] = append(ix.prefix[first], prefixEntry{r.pattern, i}) |
| + case kindSegment: |
| + ix.segment[r.pattern] = append(ix.segment[r.pattern], i) |
| + ix.minSeg = min(ix.minSeg, len(r.pattern)) |
| + ix.maxSeg = max(ix.maxSeg, len(r.pattern)) |
| + case kindSegglob: |
| + pre, suf, _ := strings.Cut(r.pattern, "*") |
| + ix.globs = append(ix.globs, globEntry{pre, suf, i}) |
| + case kindExt: |
| + ix.exts = append(ix.exts, extEntry{r.pattern, i}) |
| + case kindSegseq: |
| + ix.segseqs = append(ix.segseqs, seqEntry{r.pattern, i}) |
| + case kindQparam: |
| + name, val, _ := strings.Cut(r.pattern, "=") |
| + ix.qparams = append(ix.qparams, qparamEntry{name, name + "=", val, i}) |
| + case kindDotdot: |
| + ix.dotdots = append(ix.dotdots, i) |
| + } |
| + } |
| + return ix, nil |
| +} |
diff --git a/internal/edgeguard/catalogue.txt b/internal/edgeguard/catalogue.txt| new file mode 100644 |
| index 000000000..0b7cc81f0 |
| --- /dev/null |
| +++ b/internal/edgeguard/catalogue.txt |
| @@ -0,0 +1,82 @@ |
| +# version 1 |
| +# tier group name kind pattern mode |
| +hard traversal dotdot dotdot - watch |
| +hard traversal proc-self segseq proc/self watch |
| +hard traversal vite-fs segment @fs watch |
| +hard secrets env segment .env watch |
| +hard secrets env-variant segglob .env.* watch |
| +hard secrets git segment .git watch |
| +hard secrets git-credentials segment .git-credentials watch |
| +hard secrets svn segment .svn watch |
| +hard secrets hg segment .hg watch |
| +hard secrets aws segment .aws watch |
| +hard secrets ssh segment .ssh watch |
| +hard secrets docker segment .docker watch |
| +hard secrets kube segment .kube watch |
| +hard secrets npmrc segment .npmrc watch |
| +hard secrets pypirc segment .pypirc watch |
| +hard secrets netrc segment .netrc watch |
| +hard secrets htpasswd segment .htpasswd watch |
| +hard keys id-rsa segment id_rsa watch |
| +hard keys id-dsa segment id_dsa watch |
| +hard keys id-ecdsa segment id_ecdsa watch |
| +hard keys id-ed25519 segment id_ed25519 watch |
| +hard keys credentials-json segment credentials.json watch |
| +hard keys gcp-credentials segment gcp-credentials.json watch |
| +hard keys firebase-admin segglob firebase-adminsdk*.json watch |
| +hard dumps db-sql exact /db.sql watch |
| +hard dumps dump-sql exact /dump.sql watch |
| +hard dumps backup-sql exact /backup.sql watch |
| +hard dumps database-sql exact /database.sql watch |
| +hard source php-save ext .php.save watch |
| +hard source php-bak ext .php.bak watch |
| +hard source php-old ext .php.old watch |
| +hard source php-swp ext .php.swp watch |
| +hard source php-tilde ext .php~ watch |
| +probe wordpress wp-login exact /wp-login.php watch |
| +probe wordpress xmlrpc exact /xmlrpc.php watch |
| +probe wordpress wp-links-opml exact /wp-links-opml.php watch |
| +probe wordpress wp-admin prefix /wp-admin watch |
| +probe wordpress wp-json prefix /wp-json watch |
| +probe wordpress site-wp-json prefix /site/wp-json watch |
| +probe wordpress news-wp-json prefix /news/wp-json watch |
| +probe wordpress cms-wp-json prefix /cms/wp-json watch |
| +probe wordpress blog-wp-json prefix /blog/wp-json watch |
| +probe wordpress wp-wp-json prefix /wp/wp-json watch |
| +probe wordpress wordpress-dir prefix /wordpress watch |
| +probe wordpress press-wp-json prefix /press/wp-json watch |
| +probe phpframework phpunit prefix /vendor/phpunit watch |
| +probe phpframework composer-json exact /vendor/composer/installed.json watch |
| +probe phpframework ignition prefix /_ignition watch |
| +probe phpframework telescope prefix /telescope watch |
| +probe phpframework debugbar prefix /_debugbar watch |
| +probe phpframework profiler-phpinfo prefix /_profiler/phpinfo watch |
| +probe phpframework thinkphp qparam s=/index/\think watch |
| +probe phpmyadmin phpmyadmin prefix /phpmyadmin watch |
| +probe phpmyadmin pma prefix /pma watch |
| +probe php php ext .php watch |
| +probe java actuator prefix /actuator watch |
| +probe java action ext .action watch |
| +probe java do ext .do watch |
| +probe java jsp ext .jsp watch |
| +probe cgi cgi-bin prefix /cgi-bin watch |
| +probe cgi setup-cgi exact /setup.cgi watch |
| +probe cgi hnap1 exact /hnap1 watch |
| +probe cgi gponform prefix /gponform watch |
| +probe status server-status prefix /server-status watch |
| +probe status server-info prefix /server-info watch |
| +probe metadata meta-data prefix /latest/meta-data watch |
| +probe devconfig docker-compose exact /docker-compose.yml watch |
| +probe devconfig dockerfile exact /dockerfile watch |
| +probe devconfig gitlab-ci exact /.gitlab-ci.yml watch |
| +probe dumps sql ext .sql watch |
| +probe dumps sql-gz ext .sql.gz watch |
| +probe dumps sqlite ext .sqlite watch |
| +probe dumps sqlite3 ext .sqlite3 watch |
| +probe dumps db ext .db watch |
| +probe dumps bak ext .bak watch |
| +probe admin admin exact /admin burst |
| +probe admin admin-login exact /admin/login burst |
| +probe admin admin-settings exact /admin/settings burst |
| +probe admin admin-dashboard exact /admin/dashboard burst |
| +probe admin administrator prefix /administrator burst |
diff --git a/internal/edgeguard/catalogue_test.go b/internal/edgeguard/catalogue_test.go| new file mode 100644 |
| index 000000000..743929be5 |
| --- /dev/null |
| +++ b/internal/edgeguard/catalogue_test.go |
| @@ -0,0 +1,137 @@ |
| +package edgeguard |
| + |
| +import ( |
| + "fmt" |
| + "strings" |
| + "testing" |
| + |
| + "github.com/carlosframework/platform/internal/reqrec" |
| +) |
| + |
| +func TestCatalogueParses(t *testing.T) { |
| + rs := Rules() |
| + if len(rs) == 0 { |
| + t.Fatal("no rules") |
| + } |
| + if _, v, err := parseCatalogue(catalogueData); err != nil || v != Version { |
| + t.Fatalf("catalogue.txt parses to version %d, %v; Version is %d", v, err, Version) |
| + } |
| + seen := map[string]bool{} |
| + sawProbe := false |
| + for _, r := range rs { |
| + parts := strings.Split(r.ID, ".") |
| + if len(parts) != 3 || parts[0] != r.Tier.String() || parts[1] != r.Group || parts[2] == "" { |
| + t.Errorf("rule %q (tier %s, group %s) is not tier.group.name", r.ID, r.Tier, r.Group) |
| + } |
| + if seen[r.ID] { |
| + t.Errorf("duplicate id %q", r.ID) |
| + } |
| + seen[r.ID] = true |
| + switch r.Tier { |
| + case reqrec.TierHard: |
| + if sawProbe { |
| + t.Errorf("hard rule %q comes after a probe rule", r.ID) |
| + } |
| + case reqrec.TierProbe: |
| + sawProbe = true |
| + default: |
| + t.Errorf("rule %q has tier %s", r.ID, r.Tier) |
| + } |
| + } |
| +} |
| + |
| +func TestCatalogueRuleHashesUnique(t *testing.T) { |
| + seen := map[uint32]string{} |
| + for _, r := range Rules() { |
| + h := reqrec.RuleHash(r.ID) |
| + if other, dup := seen[h]; dup { |
| + t.Errorf("%q and %q share hash %08x", r.ID, other, h) |
| + } |
| + seen[h] = r.ID |
| + got, ok := RuleByHash(h) |
| + if !ok || got.ID != r.ID { |
| + t.Errorf("RuleByHash(%08x) = %v, %v; want %q", h, got, ok, r.ID) |
| + } |
| + } |
| +} |
| + |
| +func TestCatalogueAdminIsBurst(t *testing.T) { |
| + admin := 0 |
| + for _, r := range Rules() { |
| + if r.Group == "admin" { |
| + admin++ |
| + if r.Mode != ModeBurst { |
| + t.Errorf("%s has mode %s, want burst", r.ID, r.Mode) |
| + } |
| + } else if r.Mode == ModeBurst { |
| + t.Errorf("%s is burst but not in group admin", r.ID) |
| + } |
| + } |
| + if admin == 0 { |
| + t.Error("no admin rules") |
| + } |
| +} |
| + |
| +func TestModeString(t *testing.T) { |
| + for m, want := range map[Mode]string{ModeWatch: "watch", ModeBlock: "block", ModeBurst: "burst"} { |
| + if got := m.String(); got != want { |
| + t.Errorf("Mode(%d).String() = %q, want %q", m, got, want) |
| + } |
| + } |
| +} |
| + |
| +func TestParseRejects(t *testing.T) { |
| + const ok = "hard a b segment .env watch\n" |
| + cases := []struct { |
| + name string |
| + in string |
| + line int |
| + }{ |
| + {"upper-case pattern", "# version 1\nhard a b segment .ENV watch\n", 2}, |
| + {"unknown kind", "# version 1\n\nhard a b regex .env watch\n", 3}, |
| + {"unknown mode", "# version 1\nhard a b segment .env ban\n", 2}, |
| + {"unknown tier", "# version 1\ntenant a b segment .env watch\n", 2}, |
| + {"duplicate id", "# version 1\n" + ok + "# again\n" + ok, 4}, |
| + {"segglob without star", "# version 1\nhard a b segglob .env watch\n", 2}, |
| + {"segglob with two stars", "# version 1\nhard a b segglob .env.*.* watch\n", 2}, |
| + {"qparam without equals", "# version 1\nhard a b qparam s watch\n", 2}, |
| + {"qparam without name", "# version 1\nhard a b qparam =x watch\n", 2}, |
| + {"missing columns", "# version 1\nhard a b segment .env\n", 2}, |
| + {"extra columns", "# version 1\nhard a b segment .env watch more\n", 2}, |
| + {"bad name", "# version 1\nhard a B_c segment .env watch\n", 2}, |
| + {"exact without slash", "# version 1\nhard a b exact db.sql watch\n", 2}, |
| + {"prefix with trailing slash", "# version 1\nhard a b prefix /pma/ watch\n", 2}, |
| + {"segment holding a slash", "# version 1\nhard a b segment a/b watch\n", 2}, |
| + {"dotdot with a pattern", "# version 1\nhard a b dotdot .. watch\n", 2}, |
| + {"hard after probe", "# version 1\nprobe a b segment .env watch\nhard a c segment .git watch\n", 3}, |
| + {"missing version", ok, 1}, |
| + {"version not a number", "# version x\n" + ok, 1}, |
| + {"empty file", "", 1}, |
| + {"rule before the version line", ok + "# version 1\n", 1}, |
| + {"comment before the version line", "# notes\n# version 1\n" + ok, 1}, |
| + {"second version line", "# version 1\n" + ok + "# version 2\n", 3}, |
| + {"repeated version line", "# version 1\n# version 1\n" + ok, 2}, |
| + } |
| + for _, c := range cases { |
| + t.Run(c.name, func(t *testing.T) { |
| + _, _, err := parseCatalogue([]byte(c.in)) |
| + if err == nil { |
| + t.Fatal("parseCatalogue accepted it") |
| + } |
| + want := fmt.Sprintf("line %d", c.line) |
| + if !strings.Contains(err.Error(), want) { |
| + t.Fatalf("error %q does not name %q", err, want) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestParseAccepts(t *testing.T) { |
| + rs, v, err := parseCatalogue([]byte("# version 7\n\n# note\nhard a b segment .env watch\nprobe a c qparam s=/x\\y burst\n")) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if v != 7 || len(rs) != 2 || rs[0].ID != "hard.a.b" || rs[1].Mode != ModeBurst { |
| + t.Fatalf("got version %d, rules %+v", v, rs) |
| + } |
| +} |
diff --git a/internal/edgeguard/match.go b/internal/edgeguard/match.go| new file mode 100644 |
| index 000000000..8059f406c |
| --- /dev/null |
| +++ b/internal/edgeguard/match.go |
| @@ -0,0 +1,432 @@ |
| +package edgeguard |
| + |
| +import ( |
| + "net/url" |
| + "path" |
| + "strings" |
| + |
| + "github.com/carlosframework/platform/internal/reqrec" |
| +) |
| + |
| +// Check reports the first catalogue rule the request matches. urlPath is |
| +// r.URL.Path, which has already been decoded once; rawQuery is r.URL.RawQuery. |
| +// Hard rules are tried before probe rules and each tier in file order, so the |
| +// answer is the same as scanning the catalogue from the top. |
| +// |
| +// The path is read in a few forms so that dressing a probe up does not hide |
| +// it. Case and "\" are folded, ";params" on a segment are dropped, and when |
| +// the path holds a "%" it is decoded once more and read again. Rules other |
| +// than dotdot then look at the cleaned path, but dotdot looks at the segments |
| +// before cleaning, because "/static/../.env" is the request, not "/.env". |
| +// |
| +// A request under /.well-known/ is exempt from every path rule except dotdot: |
| +// that tree is where certificate issuers and security contacts look, and some |
| +// of what they fetch has names the rules would otherwise catch. |
| +// |
| +// An ordinary path allocates nothing. |
| +func Check(urlPath, rawQuery string) (Hit, bool) { |
| + return check(urlPath, rawQuery, 0, len(rules)) |
| +} |
| + |
| +// CheckTier is Check limited to the rules of one tier. |
| +func CheckTier(urlPath, rawQuery string, tier reqrec.Tier) (Hit, bool) { |
| + switch tier { |
| + case reqrec.TierHard: |
| + return check(urlPath, rawQuery, 0, idx.hardEnd) |
| + case reqrec.TierProbe: |
| + return check(urlPath, rawQuery, idx.hardEnd, len(rules)) |
| + } |
| + return Hit{}, false |
| +} |
| + |
| +// best is the earliest matching rule so far. pos is the rule's place in file |
| +// order, or the end of the range being checked while nothing has matched. |
| +// |
| +// A path match is kept as a place, not as text: form is the form of the path |
| +// it was found in, as the request spelled it, and from and to are where the |
| +// match lies in that form's cleaned, folded text. check spells the fragment |
| +// out of form only once the search is over (spell), so the evidence is the |
| +// request's own text and never the case-folded copy the rules compare, and a |
| +// path that matches nothing pays for none of it. text is the fragment of a |
| +// match that is not a span of the path: ".." or a query value. |
| +type best struct { |
| + lo, pos int |
| + span bool |
| + form string |
| + from, to int |
| + text string |
| + query string |
| + fromQ bool |
| +} |
| + |
| +// offer records a match on the span [from, to) of form's cleaned text when it |
| +// is in range and earlier than the best so far, and reports whether it did. |
| +func (b *best) offer(pos int, form string, from, to int) bool { |
| + if pos < b.lo || pos >= b.pos { |
| + return false |
| + } |
| + *b = best{lo: b.lo, pos: pos, span: true, form: form, from: from, to: to} |
| + return true |
| +} |
| + |
| +// offerText is offer for a match whose fragment is text rather than a span. |
| +func (b *best) offerText(pos int, text string) bool { |
| + if pos < b.lo || pos >= b.pos { |
| + return false |
| + } |
| + *b = best{lo: b.lo, pos: pos, text: text} |
| + return true |
| +} |
| + |
| +// first returns the first position at or after lo from an ascending list, or |
| +// -1 when there is none. |
| +func (b *best) first(positions []int) int { |
| + for _, p := range positions { |
| + if p >= b.lo { |
| + return p |
| + } |
| + } |
| + return -1 |
| +} |
| + |
| +func check(urlPath, rawQuery string, lo, hi int) (Hit, bool) { |
| + b := best{lo: lo, pos: hi} |
| + exempt := scanPath(urlPath, &b) |
| + if strings.IndexByte(urlPath, '%') >= 0 { |
| + if dec := unescapeLenient(urlPath); dec != urlPath { |
| + if scanPath(dec, &b) { |
| + exempt = true |
| + } |
| + } |
| + } |
| + if rawQuery != "" && !exempt { |
| + scanQuery(rawQuery, &b) |
| + } |
| + if b.pos >= hi { |
| + return Hit{}, false |
| + } |
| + h := Hit{Rule: &rules[b.pos], Fragment: b.text, FromQuery: b.fromQ, QueryName: b.query} |
| + if b.span { |
| + h.Fragment = spell(b.form)[b.from:b.to] |
| + } |
| + return h, true |
| +} |
| + |
| +// scanPath offers every path rule that matches one form of the path. It |
| +// reports whether the form lies under /.well-known/, which exempts the |
| +// request from every rule but dotdot, query rules included. |
| +func scanPath(form string, b *best) (exempt bool) { |
| + p := fold(form) |
| + if strings.IndexByte(p, ';') >= 0 { |
| + p = stripParams(p) |
| + } |
| + if len(idx.dotdots) > 0 && hasDotDot(p) { |
| + if pos := b.first(idx.dotdots); pos >= 0 { |
| + b.offerText(pos, "..") |
| + } |
| + } |
| + if p == "" || p[0] != '/' { |
| + p = "/" + p |
| + } |
| + c := path.Clean(p) |
| + rest := c[1:] |
| + if first, _, _ := strings.Cut(rest, "/"); first == ".well-known" { |
| + return true |
| + } |
| + |
| + if pos, ok := idx.exact[c]; ok { |
| + if pos := b.first(pos); pos >= 0 { |
| + b.offer(pos, form, 0, len(c)) |
| + } |
| + } |
| + if rest != "" { |
| + first, _, _ := strings.Cut(rest, "/") |
| + for _, e := range idx.prefix[first] { |
| + // A rule outside the requested tier must not end the search. |
| + if e.pos < b.lo { |
| + continue |
| + } |
| + if isPrefixPath(c, e.pattern) { |
| + // The pattern's span only: what lies under it is the |
| + // request's own text, and may be a token. |
| + b.offer(e.pos, form, 0, len(e.pattern)) |
| + break |
| + } |
| + } |
| + } |
| + // at is where seg starts in c. A cleaned path has no empty segment, so |
| + // each one starts just past the "/" that ends the one before. |
| + last, lastAt := "", 0 |
| + for at := 1; rest != ""; { |
| + var seg string |
| + seg, rest, _ = strings.Cut(rest, "/") |
| + last, lastAt = seg, at |
| + if len(seg) >= idx.minSeg && len(seg) <= idx.maxSeg { |
| + if pos, ok := idx.segment[seg]; ok { |
| + if pos := b.first(pos); pos >= 0 { |
| + b.offer(pos, form, at, at+len(seg)) |
| + } |
| + } |
| + } |
| + for _, g := range idx.globs { |
| + if g.pos >= b.lo && g.pos < b.pos && len(seg) >= len(g.prefix)+len(g.suffix) && |
| + strings.HasPrefix(seg, g.prefix) && strings.HasSuffix(seg, g.suffix) { |
| + b.offer(g.pos, form, at, at+len(seg)) |
| + } |
| + } |
| + at += len(seg) + 1 |
| + } |
| + for _, e := range idx.exts { |
| + if e.pos >= b.lo && e.pos < b.pos && len(last) > len(e.suffix) && strings.HasSuffix(last, e.suffix) { |
| + b.offer(e.pos, form, lastAt, lastAt+len(last)) |
| + } |
| + } |
| + for _, e := range idx.segseqs { |
| + if e.pos >= b.lo && e.pos < b.pos { |
| + if at := segmentsAt(c, e.segs); at >= 0 { |
| + b.offer(e.pos, form, at, at+len(e.segs)) |
| + } |
| + } |
| + } |
| + return false |
| +} |
| + |
| +// spell is the cleaned path scanPath compares, made from form with its case |
| +// left as the request sent it. Folding case changes no "/", ";" or ".", which |
| +// are all that stripping parameters and cleaning look at, so the result lines |
| +// up byte for byte with the folded text: a match's place in one is its place |
| +// in the other. It runs only for a match, so its allocations are a match's. |
| +func spell(form string) string { |
| + p := form |
| + if strings.IndexByte(p, '\\') >= 0 { |
| + p = strings.ReplaceAll(p, `\`, "/") |
| + } |
| + if strings.IndexByte(p, ';') >= 0 { |
| + p = stripParams(p) |
| + } |
| + if p == "" || p[0] != '/' { |
| + p = "/" + p |
| + } |
| + return path.Clean(p) |
| +} |
| + |
| +// unescapeLenient decodes every valid %XX in s and leaves an invalid escape |
| +// as it is. url.PathUnescape refuses the whole string over one bad escape, |
| +// which would let "/%zz/%2eenv" hide the second escape from the rules. It |
| +// returns s itself when nothing was decoded. |
| +func unescapeLenient(s string) string { |
| + var sb strings.Builder |
| + decoded := false |
| + start := 0 // the start of the text not yet copied to sb |
| + for i := 0; i+2 < len(s); i++ { |
| + if s[i] != '%' { |
| + continue |
| + } |
| + hi, lo := unhex(s[i+1]), unhex(s[i+2]) |
| + if hi < 0 || lo < 0 { |
| + continue |
| + } |
| + if !decoded { |
| + sb.Grow(len(s)) |
| + decoded = true |
| + } |
| + sb.WriteString(s[start:i]) |
| + sb.WriteByte(byte(hi<<4 | lo)) |
| + i += 2 |
| + start = i + 1 |
| + } |
| + if !decoded { |
| + return s |
| + } |
| + sb.WriteString(s[start:]) |
| + return sb.String() |
| +} |
| + |
| +func unhex(c byte) int { |
| + switch { |
| + case c >= '0' && c <= '9': |
| + return int(c - '0') |
| + case c >= 'a' && c <= 'f': |
| + return int(c-'a') + 10 |
| + case c >= 'A' && c <= 'F': |
| + return int(c-'A') + 10 |
| + } |
| + return -1 |
| +} |
| + |
| +// isPrefixPath reports whether the cleaned path is the pattern or lies under |
| +// it. "/wp-json" covers "/wp-json/wp/v2" but not "/wp-jsonx". |
| +func isPrefixPath(c, pattern string) bool { |
| + return strings.HasPrefix(c, pattern) && (len(c) == len(pattern) || c[len(pattern)] == '/') |
| +} |
| + |
| +// segmentsAt reports where segs, a run of whole segments such as |
| +// "proc/self", first appears in the cleaned path, or -1 when it does not. |
| +func segmentsAt(c, segs string) int { |
| + for from := 0; ; { |
| + i := strings.Index(c[from:], segs) |
| + if i < 0 { |
| + return -1 |
| + } |
| + start := from + i |
| + end := start + len(segs) |
| + if c[start-1] == '/' && (end == len(c) || c[end] == '/') { |
| + return start |
| + } |
| + from = start + 1 |
| + } |
| +} |
| + |
| +// hasDotDot reports whether any segment of the path is "..". |
| +func hasDotDot(p string) bool { |
| + for p != "" { |
| + var seg string |
| + seg, p, _ = strings.Cut(p, "/") |
| + if seg == ".." { |
| + return true |
| + } |
| + } |
| + return false |
| +} |
| + |
| +// fold lower-cases ASCII and turns "\" into "/", returning s itself when it |
| +// needs neither. Only ASCII is folded: the patterns are ASCII, and full |
| +// Unicode folding would let a Kelvin sign pass for a "k". |
| +func fold(s string) string { |
| + for i := 0; i < len(s); i++ { |
| + if c := s[i]; c >= 'A' && c <= 'Z' || c == '\\' { |
| + return foldFrom(s, i) |
| + } |
| + } |
| + return s |
| +} |
| + |
| +func foldFrom(s string, i int) string { |
| + var sb strings.Builder |
| + sb.Grow(len(s)) |
| + sb.WriteString(s[:i]) |
| + for ; i < len(s); i++ { |
| + switch c := s[i]; { |
| + case c >= 'A' && c <= 'Z': |
| + sb.WriteByte(c + 'a' - 'A') |
| + case c == '\\': |
| + sb.WriteByte('/') |
| + default: |
| + sb.WriteByte(c) |
| + } |
| + } |
| + return sb.String() |
| +} |
| + |
| +// stripParams drops ";..." from the end of every segment, the way servlet |
| +// containers read "/..;/" and "/.env;x=1". |
| +func stripParams(p string) string { |
| + var sb strings.Builder |
| + sb.Grow(len(p)) |
| + for { |
| + seg, rest, more := strings.Cut(p, "/") |
| + if i := strings.IndexByte(seg, ';'); i >= 0 { |
| + seg = seg[:i] |
| + } |
| + sb.WriteString(seg) |
| + if !more { |
| + return sb.String() |
| + } |
| + sb.WriteByte('/') |
| + p = rest |
| + } |
| +} |
| + |
| +// hasParam reports whether rawQuery has a parameter called name, judged on |
| +// the raw text. nameEq is the name followed by "=": it must be at the start |
| +// or right after "&". ";" is not treated as a separator, because |
| +// url.ParseQuery does not treat it as one. A name that is percent-encoded in |
| +// the query is not found here; escapedName is the check for that. |
| +func hasParam(rawQuery, nameEq string) bool { |
| + for from := 0; ; { |
| + i := strings.Index(rawQuery[from:], nameEq) |
| + if i < 0 { |
| + return false |
| + } |
| + i += from |
| + if i == 0 || rawQuery[i-1] == '&' { |
| + return true |
| + } |
| + from = i + 1 |
| + } |
| +} |
| + |
| +// escapedName reports whether any parameter name in rawQuery holds a "%". |
| +// url.ParseQuery decodes names as well as values, so "%73=..." is the |
| +// parameter "s", which hasParam cannot see on the raw text. It looks at the |
| +// names only: an escape in a value, the ordinary case, does not count. |
| +func escapedName(rawQuery string) bool { |
| + for rawQuery != "" { |
| + var pair string |
| + pair, rawQuery, _ = strings.Cut(rawQuery, "&") |
| + name, _, _ := strings.Cut(pair, "=") |
| + if strings.IndexByte(name, '%') >= 0 { |
| + return true |
| + } |
| + } |
| + return false |
| +} |
| + |
| +// scanQuery offers the query parameter rules. The query is only parsed when |
| +// it has a parameter by a rule's name, or a name with an escape in it that |
| +// might decode to one, so an ordinary request pays for a substring search |
| +// and nothing more. |
| +func scanQuery(rawQuery string, b *best) { |
| + var vals url.Values |
| + parsed := false |
| + // escaped is escapedName(rawQuery), worked out the first time a rule's |
| + // name is not found plainly: 0 not yet, 1 no, 2 yes. |
| + escaped := 0 |
| + for _, e := range idx.qparams { |
| + if e.pos < b.lo || e.pos >= b.pos { |
| + continue |
| + } |
| + if !hasParam(rawQuery, e.nameEq) { |
| + if escaped == 0 { |
| + escaped = 1 |
| + if strings.IndexByte(rawQuery, '%') >= 0 && escapedName(rawQuery) { |
| + escaped = 2 |
| + } |
| + } |
| + if escaped == 1 { |
| + continue |
| + } |
| + } |
| + if !parsed { |
| + // A parse error still returns the pairs that did parse. |
| + vals, _ = url.ParseQuery(rawQuery) |
| + parsed = true |
| + } |
| + for _, v := range vals[e.name] { |
| + if hasPrefixFold(v, e.valuePrefix) { |
| + if b.offerText(e.pos, v) { |
| + b.fromQ, b.query = true, e.name |
| + } |
| + break |
| + } |
| + } |
| + } |
| +} |
| + |
| +// hasPrefixFold reports whether s, lower-cased, starts with the lower-case |
| +// prefix. |
| +func hasPrefixFold(s, prefix string) bool { |
| + if len(s) < len(prefix) { |
| + return false |
| + } |
| + for i := 0; i < len(prefix); i++ { |
| + c := s[i] |
| + if c >= 'A' && c <= 'Z' { |
| + c += 'a' - 'A' |
| + } |
| + if c != prefix[i] { |
| + return false |
| + } |
| + } |
| + return true |
| +} |
diff --git a/internal/edgeguard/match_test.go b/internal/edgeguard/match_test.go| new file mode 100644 |
| index 000000000..2ad119708 |
| --- /dev/null |
| +++ b/internal/edgeguard/match_test.go |
| @@ -0,0 +1,380 @@ |
| +package edgeguard |
| + |
| +import ( |
| + "path" |
| + "strings" |
| + "testing" |
| + |
| + "github.com/carlosframework/platform/internal/reqrec" |
| +) |
| + |
| +type checkCase struct { |
| + path, rawQuery, wantID string |
| +} |
| + |
| +func runCases(t *testing.T, cases []checkCase) { |
| + t.Helper() |
| + for _, c := range cases { |
| + hit, ok := Check(c.path, c.rawQuery) |
| + switch { |
| + case c.wantID == "" && ok: |
| + t.Errorf("Check(%q, %q) = %s (fragment %q), want no match", c.path, c.rawQuery, hit.Rule.ID, hit.Fragment) |
| + case c.wantID != "" && !ok: |
| + t.Errorf("Check(%q, %q) = no match, want %s", c.path, c.rawQuery, c.wantID) |
| + case c.wantID != "" && hit.Rule.ID != c.wantID: |
| + t.Errorf("Check(%q, %q) = %s, want %s", c.path, c.rawQuery, hit.Rule.ID, c.wantID) |
| + } |
| + } |
| +} |
| + |
| +func TestCheckHardTier(t *testing.T) { |
| + runCases(t, []checkCase{ |
| + {"/.env", "", "hard.secrets.env"}, |
| + {"/backend/.env", "", "hard.secrets.env"}, |
| + {"/.env.local", "", "hard.secrets.env-variant"}, |
| + {"/.env.production", "", "hard.secrets.env-variant"}, |
| + {"/.git/config", "", "hard.secrets.git"}, |
| + {"/.git/HEAD", "", "hard.secrets.git"}, |
| + {"/.git-credentials", "", "hard.secrets.git-credentials"}, |
| + {"/.aws/credentials", "", "hard.secrets.aws"}, |
| + {"/.docker/config.json", "", "hard.secrets.docker"}, |
| + {"/credentials.json", "", "hard.keys.credentials-json"}, |
| + {"/gcp-credentials.json", "", "hard.keys.gcp-credentials"}, |
| + {"/firebase-adminsdk.json", "", "hard.keys.firebase-admin"}, |
| + {"/firebase-adminsdk-x1y2.json", "", "hard.keys.firebase-admin"}, |
| + {"/@fs/.env", "", "hard.traversal.vite-fs"}, |
| + // proc-self precedes vite-fs in the catalogue, and the first rule in |
| + // file order wins, so this is not vite-fs. |
| + {"/@fs/proc/self/environ", "", "hard.traversal.proc-self"}, |
| + {"/x/proc/self/environ", "", "hard.traversal.proc-self"}, |
| + {"/static/../.env", "", "hard.traversal.dotdot"}, |
| + {"/db.sql", "", "hard.dumps.db-sql"}, |
| + {"/index.php.save", "", "hard.source.php-save"}, |
| + {"/index.php~", "", "hard.source.php-tilde"}, |
| + {"/home/.ssh/id_rsa", "", "hard.secrets.ssh"}, |
| + {"/id_ed25519", "", "hard.keys.id-ed25519"}, |
| + }) |
| +} |
| + |
| +func TestCheckProbeTier(t *testing.T) { |
| + runCases(t, []checkCase{ |
| + {"/wp-login.php", "", "probe.wordpress.wp-login"}, |
| + {"/xmlrpc.php", "", "probe.wordpress.xmlrpc"}, |
| + {"/blog/wp-json/wp/v2/users", "", "probe.wordpress.blog-wp-json"}, |
| + {"/wp-admin/install.php", "", "probe.wordpress.wp-admin"}, |
| + {"/info.php", "", "probe.php.php"}, |
| + {"/_profiler/phpinfo", "", "probe.phpframework.profiler-phpinfo"}, |
| + {"/vendor/phpunit/phpunit/src/Util/PHP/eval-stdin.php", "", "probe.phpframework.phpunit"}, |
| + {"/_ignition/execute-solution", "", "probe.phpframework.ignition"}, |
| + {"/vendor/composer/installed.json", "", "probe.phpframework.composer-json"}, |
| + {"/", `s=/index/\think\app/invokefunction`, "probe.phpframework.thinkphp"}, |
| + {"/phpmyadmin/index.php", "", "probe.phpmyadmin.phpmyadmin"}, |
| + {"/pma/", "", "probe.phpmyadmin.pma"}, |
| + {"/actuator/env", "", "probe.java.actuator"}, |
| + {"/login.action", "", "probe.java.action"}, |
| + {"/index.jsp", "", "probe.java.jsp"}, |
| + {"/cgi-bin/luci", "", "probe.cgi.cgi-bin"}, |
| + {"/HNAP1", "", "probe.cgi.hnap1"}, |
| + {"/GponForm/diag_Form", "", "probe.cgi.gponform"}, |
| + {"/server-status", "", "probe.status.server-status"}, |
| + {"/latest/meta-data/iam/", "", "probe.metadata.meta-data"}, |
| + {"/Dockerfile", "", "probe.devconfig.dockerfile"}, |
| + {"/.gitlab-ci.yml", "", "probe.devconfig.gitlab-ci"}, |
| + {"/backup/site.sql", "", "probe.dumps.sql"}, |
| + {"/data/app.sqlite", "", "probe.dumps.sqlite"}, |
| + {"/admin", "", "probe.admin.admin"}, |
| + {"/administrator/", "", "probe.admin.administrator"}, |
| + }) |
| +} |
| + |
| +func TestCheckEncodingTricks(t *testing.T) { |
| + runCases(t, []checkCase{ |
| + {"/.ENV", "", "hard.secrets.env"}, |
| + {"/.Git/config", "", "hard.secrets.git"}, |
| + {"/%2eenv", "", "hard.secrets.env"}, |
| + {"/static/%2e%2e/.env", "", "hard.traversal.dotdot"}, |
| + {`/static/..\.env`, "", "hard.traversal.dotdot"}, |
| + {"/x/..;/.env", "", "hard.traversal.dotdot"}, |
| + {"/.env;x=1", "", "hard.secrets.env"}, |
| + {"//.env", "", "hard.secrets.env"}, |
| + {"/./.git/config", "", "hard.secrets.git"}, |
| + {"/a;b=c/.git/config", "", "hard.secrets.git"}, |
| + {"/%2E%2Egit/x", "", ""}, |
| + {"/bad%zz/.env", "", "hard.secrets.env"}, |
| + // One invalid escape does not stop the valid ones being decoded. |
| + {"/%zz/%2eenv", "", "hard.secrets.env"}, |
| + {"/%/%2e%2e/%2Egit", "", "hard.traversal.dotdot"}, |
| + {"/100%/%2egit/config", "", "hard.secrets.git"}, |
| + {"/%2", "", ""}, |
| + // Decoding happens once: %252e is a literal "%2e", not a dot. |
| + {"/%252eenv", "", ""}, |
| + }) |
| +} |
| + |
| +func TestCheckWellKnownExempt(t *testing.T) { |
| + runCases(t, []checkCase{ |
| + {"/.well-known/acme-challenge/abc", "", ""}, |
| + {"/.well-known/security.txt", "", ""}, |
| + {"/.well-known/.env", "", ""}, |
| + {"/.well-known/../.env", "", "hard.traversal.dotdot"}, |
| + // The exemption covers query rules as well as path rules. |
| + {"/.well-known/x", `s=/index/\think`, ""}, |
| + {"/.well-known", `s=/index/\think`, ""}, |
| + {"/%2ewell-known/x", `s=/index/\think`, ""}, |
| + {"/x", `s=/index/\think`, "probe.phpframework.thinkphp"}, |
| + }) |
| +} |
| + |
| +func TestCheckQueryParamBoundary(t *testing.T) { |
| + runCases(t, []checkCase{ |
| + {"/", `s=/index/\think`, "probe.phpframework.thinkphp"}, |
| + // url.ParseQuery decodes names as well as values, so a name spelled |
| + // with escapes is the same parameter. |
| + {"/", `%73=%2Findex%2F%5Cthink`, "probe.phpframework.thinkphp"}, |
| + {"/", `a=1&%73=%2Findex%2F%5Cthink&b=2`, "probe.phpframework.thinkphp"}, |
| + {"/", `utm_source=x%20y&%73=/index/\think`, "probe.phpframework.thinkphp"}, |
| + {"/", `%53=%2Findex%2F%5Cthink`, ""}, |
| + {"/", `%78s=%2Findex%2F%5Cthink`, ""}, |
| + {"/", `a=%73&b=/index/\think`, ""}, |
| + {"/", `a=1&s=/index/\think`, "probe.phpframework.thinkphp"}, |
| + {"/", `a=1&S=/index/\think`, ""}, |
| + {"/", `xs=/index/\think`, ""}, |
| + {"/", `a=1&xs=/index/\think`, ""}, |
| + {"/", `a=s=/index/\think`, ""}, |
| + {"/", `a=1;s=/index/\think`, ""}, |
| + }) |
| +} |
| + |
| +// withCatalogue swaps the package's catalogue for the given text, built |
| +// through the same parser and index builder as the real one. |
| +func withCatalogue(t *testing.T, text string) { |
| + t.Helper() |
| + rs, _, err := parseCatalogue([]byte(text)) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + ix, err := buildIndex(rs) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + oldRules, oldIdx := rules, idx |
| + rules, idx = rs, ix |
| + t.Cleanup(func() { rules, idx = oldRules, oldIdx }) |
| +} |
| + |
| +// A rule outside the requested tier must not end the search for one inside |
| +// it, even when both share a first segment. |
| +func TestCheckTierSharedPrefixSegment(t *testing.T) { |
| + withCatalogue(t, "# version 1\n"+ |
| + "hard g one prefix /a watch\n"+ |
| + "probe g two prefix /a/b watch\n") |
| + if h, ok := CheckTier("/a/b", "", reqrec.TierProbe); !ok || h.Rule.ID != "probe.g.two" { |
| + t.Errorf("probe check = %v, %v; want probe.g.two", h, ok) |
| + } |
| + if h, ok := CheckTier("/a/b", "", reqrec.TierHard); !ok || h.Rule.ID != "hard.g.one" { |
| + t.Errorf("hard check = %v, %v; want hard.g.one", h, ok) |
| + } |
| + if h, ok := Check("/a/b", ""); !ok || h.Rule.ID != "hard.g.one" { |
| + t.Errorf("Check = %v, %v; want hard.g.one", h, ok) |
| + } |
| +} |
| + |
| +func TestCheckMisfireCorpus(t *testing.T) { |
| + var cases []checkCase |
| + for _, p := range []string{ |
| + "/help/vat-in-the-european-union", |
| + "/docs/display-a-selection-of-tickets", |
| + "/docs/update-the-widget-from-version-1", |
| + "/en/articles/how-do-i-delete-a-hub", |
| + "/help/export-attendees-from-all-events", |
| + "/docs/embeddable-javascript-widget", |
| + "/assets/admin/application-3f2a9c.js", |
| + "/favicon-admin-32.png", |
| + "/help/the-admin-pane", |
| + "/wp-content/uploads/2024/05/logo.png", |
| + "/uploads/PMA_FULL_LOGO.png", |
| + "/img/photo..jpg", |
| + `/en/articles/"https:/x.example"`, |
| + "/api/union/members", |
| + "/env", |
| + "/environment", |
| + "/blog/.envoy", |
| + "/docs/index.php-guide", |
| + "/products/admin-chair", |
| + "/static/app.min.js", |
| + "/todo", |
| + "/telescopes", |
| + } { |
| + cases = append(cases, checkCase{p, "", ""}) |
| + } |
| + for _, q := range []string{ |
| + "redirect_uri=https://example.com/cb", |
| + "sig=ZXZhbCBkcm9wIHVuaW9u", |
| + "s=search+terms", |
| + } { |
| + cases = append(cases, checkCase{"/", q, ""}) |
| + } |
| + runCases(t, cases) |
| +} |
| + |
| +// Two kinds can both match one request, and a linear scan in file order picks |
| +// the earlier rule. The indexes must agree, whichever kind found it first. |
| +func TestCheckFileOrderAcrossKinds(t *testing.T) { |
| + runCases(t, []checkCase{ |
| + // vite-fs (segment) is listed before env (segment) and before |
| + // php-save (ext). |
| + {"/@fs/.env", "", "hard.traversal.vite-fs"}, |
| + {"/@fs/index.php.save", "", "hard.traversal.vite-fs"}, |
| + // env (segment) is listed before db-sql (exact). |
| + {"/.env/db.sql", "", "hard.secrets.env"}, |
| + // A hard rule beats a probe rule even when the probe rule is an |
| + // exact match on the whole path. |
| + {"/.git/wp-login.php", "", "hard.secrets.git"}, |
| + // wp-login (exact) is listed before php (ext). |
| + {"/wp-login.php", "", "probe.wordpress.wp-login"}, |
| + // A query parameter rule loses to an earlier path rule and beats a |
| + // later one. |
| + {"/wp-admin/x", `s=/index/\think`, "probe.wordpress.wp-admin"}, |
| + {"/admin", `s=/index/\think`, "probe.phpframework.thinkphp"}, |
| + }) |
| +} |
| + |
| +func TestCheckFragments(t *testing.T) { |
| + cases := []struct { |
| + path, rawQuery, fragment string |
| + fromQuery bool |
| + queryName string |
| + }{ |
| + // A fragment is in the request's own spelling, never the folded |
| + // text the rules compare. |
| + {"/a/.ENV", "", ".ENV", false, ""}, |
| + {"/a/.env.local", "", ".env.local", false, ""}, |
| + {"/a/.Env.Local", "", ".Env.Local", false, ""}, |
| + {"/static/../.env", "", "..", false, ""}, |
| + {"/static/../.ENV", "", "..", false, ""}, |
| + // A prefix rule's fragment is the pattern's span and nothing under |
| + // it: what follows /wp-admin is the request's own, and may be a |
| + // token. |
| + {"/pma/", "", "/pma", false, ""}, |
| + {"/wp-admin/x/", "", "/wp-admin", false, ""}, |
| + {"/WP-Admin/AbCd12_EfGh34_IjKl56_MnOp78", "", "/WP-Admin", false, ""}, |
| + {`\WP-Admin\AbCd12`, "", "/WP-Admin", false, ""}, |
| + {"//WP-Admin/./x", "", "/WP-Admin", false, ""}, |
| + {"/Blog/WP-Json/wp/v2/users", "", "/Blog/WP-Json", false, ""}, |
| + // A segseq rule's fragment is its run of segments. |
| + {"/x/proc/self/environ", "", "proc/self", false, ""}, |
| + {"/X/Proc/Self/Environ", "", "Proc/Self", false, ""}, |
| + {"/WP-Login.php", "", "/WP-Login.php", false, ""}, |
| + {"/a/b/info.php", "", "info.php", false, ""}, |
| + {"/a/B/Info.PHP", "", "Info.PHP", false, ""}, |
| + {"/a;x=1/.ENV;y=2", "", ".ENV", false, ""}, |
| + // The decoded form's spelling, when that is the form that matched. |
| + {"/%2EEnv", "", ".Env", false, ""}, |
| + {"/a/%2EGit/config", "", ".Git", false, ""}, |
| + {"/", `a=1&s=%2Findex%2F%5CThink%5Capp`, `/index/\Think\app`, true, "s"}, |
| + {"/", `a=1&%73=%2Findex%2F%5CThink%5Capp`, `/index/\Think\app`, true, "s"}, |
| + } |
| + for _, c := range cases { |
| + hit, ok := Check(c.path, c.rawQuery) |
| + if !ok { |
| + t.Errorf("Check(%q, %q) = no match", c.path, c.rawQuery) |
| + continue |
| + } |
| + if hit.Fragment != c.fragment || hit.FromQuery != c.fromQuery || hit.QueryName != c.queryName { |
| + t.Errorf("Check(%q, %q) = fragment %q, fromQuery %v, name %q; want %q, %v, %q", |
| + c.path, c.rawQuery, hit.Fragment, hit.FromQuery, hit.QueryName, c.fragment, c.fromQuery, c.queryName) |
| + } |
| + } |
| +} |
| + |
| +// spell must line up byte for byte with the folded, cleaned text scanPath |
| +// compares, or a fragment would be cut from the wrong place. |
| +func TestSpellLinesUpWithFold(t *testing.T) { |
| + for _, p := range []string{ |
| + "", "/", "x", "/A/B/C", `\A\..\B`, "/a;X=1/B;y/.ENV", "//A/./B/../C/", "/Ä/.ENV", |
| + "/%2E%2E/X", "/A;b/;c/D;", `/x/..;\.Git`, "/ABC/./../../D", |
| + } { |
| + c := fold(p) |
| + if strings.IndexByte(c, ';') >= 0 { |
| + c = stripParams(c) |
| + } |
| + if c == "" || c[0] != '/' { |
| + c = "/" + c |
| + } |
| + c = path.Clean(c) |
| + if got := spell(p); fold(got) != c { |
| + t.Errorf("spell(%q) = %q, folds to %q; want %q", p, got, fold(got), c) |
| + } |
| + } |
| +} |
| + |
| +func TestCheckTier(t *testing.T) { |
| + if _, ok := CheckTier("/.env", "", reqrec.TierProbe); ok { |
| + t.Error("probe-only check matched a hard rule") |
| + } |
| + if _, ok := CheckTier("/wp-login.php", "", reqrec.TierHard); ok { |
| + t.Error("hard-only check matched a probe rule") |
| + } |
| + if h, ok := CheckTier("/wp-login.php", "", reqrec.TierProbe); !ok || h.Rule.ID != "probe.wordpress.wp-login" { |
| + t.Errorf("probe check = %v, %v", h, ok) |
| + } |
| + // The probe tier still sees the path when a hard rule hides it from Check. |
| + if h, ok := CheckTier("/.git/wp-login.php", "", reqrec.TierProbe); !ok || h.Rule.ID != "probe.php.php" { |
| + t.Errorf("probe check under a hard hit = %v, %v", h, ok) |
| + } |
| + if h, ok := CheckTier("/", `s=/index/\think`, reqrec.TierProbe); !ok || !h.FromQuery { |
| + t.Errorf("probe query check = %v, %v", h, ok) |
| + } |
| + if _, ok := CheckTier("/", `s=/index/\think`, reqrec.TierHard); ok { |
| + t.Error("hard-only check matched a probe query rule") |
| + } |
| + if _, ok := CheckTier("/.env", "", reqrec.TierAttack); ok { |
| + t.Error("a tier with no rules matched") |
| + } |
| +} |
| + |
| +func TestCheckLongPath(t *testing.T) { |
| + long := strings.Repeat("/a", 512*1024) + "/.env" |
| + if len(long) < 1<<20 { |
| + t.Fatalf("path is %d bytes", len(long)) |
| + } |
| + hit, ok := Check(long, "") |
| + if !ok || hit.Rule.ID != "hard.secrets.env" { |
| + t.Fatalf("Check(long) = %v, %v", hit, ok) |
| + } |
| + if n := testing.AllocsPerRun(3, func() { Check(long, "") }); n > 4 { |
| + t.Fatalf("Check(long) allocates %v times, want at most 4", n) |
| + } |
| +} |
| + |
| +func TestCheckOrdinaryPathAllocs(t *testing.T) { |
| + for _, c := range []struct{ path, query string }{ |
| + {"/blog/2026/10/some-article-slug", ""}, |
| + {"/assets/app-3f2a9c.js", "v=2"}, |
| + {"/blog/post", "utm_source=newsletter"}, |
| + {"/blog/post", "page=2&sort=asc"}, |
| + {"/blog/post", "session=abc"}, |
| + // An escape in a value is ordinary, and does not send the query to |
| + // the parser the way an escape in a name does. |
| + {"/search", "q=hello%20world&page=2"}, |
| + {"/", ""}, |
| + } { |
| + if n := testing.AllocsPerRun(100, func() { Check(c.path, c.query) }); n != 0 { |
| + t.Errorf("Check(%q, %q) allocates %v times, want 0", c.path, c.query, n) |
| + } |
| + } |
| +} |
| + |
| +func BenchmarkCheckOrdinary(b *testing.B) { |
| + for _, c := range []struct{ name, path, query string }{ |
| + {"article", "/blog/2026/10/some-article-slug", ""}, |
| + {"asset", "/assets/app-3f2a9c.js", "v=2"}, |
| + } { |
| + b.Run(c.name, func(b *testing.B) { |
| + b.ReportAllocs() |
| + for i := 0; i < b.N; i++ { |
| + Check(c.path, c.query) |
| + } |
| + }) |
| + } |
| +} |
diff --git a/internal/host/reqrec_e2e_test.go b/internal/host/reqrec_e2e_test.go| index 3a10edf3d..e797e170c 100644 |
| --- a/internal/host/reqrec_e2e_test.go |
| +++ b/internal/host/reqrec_e2e_test.go |
| @@ -35,9 +35,11 @@ func TestRequestRecordsEndToEnd(t *testing.T) { |
| get := func(path string) { t.Helper(); x.serve("GET", path, clientAddr) } |
| // The reset link goes first so it is inside the 60-record sample, which |
| // is the case where the token would leak if masking were not applied. |
| + // The missing page is one no protection rule matches: a probe path such |
| + // as /wp-login.php is filed as a watch match, not a not-found record. |
| get("/reset/" + token) |
| for i := 0; i < 70; i++ { |
| - get("/wp-login.php") |
| + get("/old-page.html") |
| } |
| x.flush() |
diff --git a/internal/hostenv/hostenv.go b/internal/hostenv/hostenv.go| index 5459a548d..aeef72cd6 100644 |
| --- a/internal/hostenv/hostenv.go |
| +++ b/internal/hostenv/hostenv.go |
| @@ -78,6 +78,8 @@ var Optional = []string{ |
| "CARLOS_DEPLOYMENT_SINGLE_TENANT", |
| "CARLOS_DNS_PROVIDER", |
| "CARLOS_EDGE_GZIP", |
| + "CARLOS_EDGE_PROTECT", |
| + "CARLOS_EDGE_RECORDS", |
| "CARLOS_HIBERNATE_IDLE", |
| "CARLOS_HIBERNATE_PREFIX", |
| "CARLOS_HOST_CLAIM_RETIRED_LOCATIONS", |
diff --git a/internal/provision/edge_protection_2_census_test.go b/internal/provision/edge_protection_2_census_test.go| new file mode 100644 |
| index 000000000..d907f1ee2 |
| --- /dev/null |
| +++ b/internal/provision/edge_protection_2_census_test.go |
| @@ -0,0 +1,37 @@ |
| +package provision |
| + |
| +// Record-write census entries for edge protection Plan 2 (branch |
| +// edge-protection-2: the hard and probe tiers, watch by default; Plan 2 of |
| +// docs/superpowers/specs/2026-10-24-edge-request-protection-design.md), |
| +// layered on rootfsApps2WriteCensusInventory (main's newest at the merge |
| +// of origin/main, d34c0a72). Reviewed by the branch author; the census |
| +// owner rules on #280 (census-ruling-edge-protection-2, with the root-read |
| +// card docs/superpowers/notes/census-proposal-edge-protection-2.md). |
| +// - main dispatches the new `carlos explain` verb (runExplain), which reads |
| +// what a block page's reference code says; the change is that dispatch |
| +// case and one help line. Its instance and sidecar literals are |
| +// unchanged: key-site. Re-digested at the merge of origin/main on main's |
| +// body as of edge-asset-cache-1 (its `carlos assets` dispatch and help |
| +// lines) plus this branch's case and help line. |
| +// |
| +// The edge's guard matches requests in memory, and its matches go into the |
| +// box's in-memory applog.Sink beside the other request records. Nothing in |
| +// this plan writes an instance or sidecar record, and no write site is added. |
| +func edgeProtection2WriteCensusInventory() []censusEntry { |
| + entries := append([]censusEntry(nil), rootfsApps2WriteCensusInventory()...) |
| + replacements := []censusEntry{ |
| + {"main.go", "main", "key-site", "lit:instances,lit:sidecars", "fe41f258356c289551f1411386170a7d3fdbab6994e1ab861edbfe3f4ad1f14b"}, |
| + } |
| + for _, r := range replacements { |
| + found := false |
| + for i, e := range entries { |
| + if e.File == r.File && e.Unit == r.Unit { |
| + entries[i], found = r, true |
| + } |
| + } |
| + if !found { |
| + entries = append(entries, r) |
| + } |
| + } |
| + return entries |
| +} |
diff --git a/internal/provision/plan9_b8_census_test.go b/internal/provision/plan9_b8_census_test.go| index 9e7de56f7..ba9af913e 100644 |
| --- a/internal/provision/plan9_b8_census_test.go |
| +++ b/internal/provision/plan9_b8_census_test.go |
| @@ -366,7 +366,7 @@ func TestPlan9B8RecordWriteCensus(t *testing.T) { |
| if len(got) < 100 { |
| t.Fatalf("census found only %d units under %s; the walk is broken", len(got), root) |
| } |
| - inventory := rootfsApps2WriteCensusInventory() |
| + inventory := edgeProtection2WriteCensusInventory() |
| problems := append(censusDiff(inventory, got), censusPolicy(inventory)...) |
| if len(problems) > 0 { |
| t.Fatalf("record-write census rejected %d site(s); update the explicit inventory only after reviewing the source:\n %s", len(problems), strings.Join(problems, "\n ")) |
diff --git a/internal/provision/testdata/plan14-root-reads-chain.tsv b/internal/provision/testdata/plan14-root-reads-chain.tsv| index fbca8619b..a1098722c 100644 |
| --- a/internal/provision/testdata/plan14-root-reads-chain.tsv |
| +++ b/internal/provision/testdata/plan14-root-reads-chain.tsv |
| @@ -40,3 +40,5 @@ plan14-root-reads-plans-4d-units.tsv d8040ae2e40478dd1d5d8eac4010f3382cf22b4766e |
| plan14-root-reads-plans-4d-lapse.tsv e44eb0934bbb3c22b2b40d0d923cb33b1d092a8437e694bf733e685fb224ece2 |
| plan14-root-reads-rootfs-apps-2-new.tsv b9e0e5339dee58e5851774f049ae6096f5b7617de917efcc2b4bec7b3f71b495 |
| plan14-root-reads-rootfs-apps-2.tsv b1b17467ff148c3a0b1dd3312b7a80498db11cc4b455e2331c6b0da2e369e2ee |
| +plan14-root-reads-edge-protection-2-decisions.tsv 7d90eff62dcb3d2d211b9f0fa37ba1967f1f418884a11c1476cdaa50b187efd5 |
| +plan14-root-reads-edge-protection-2.tsv a864cf31b6bf2c30b5aa8c2647835efdc456f34f4945eea12751daab2457728e |
diff --git a/internal/provision/testdata/plan14-root-reads-edge-protection-2-decisions.tsv b/internal/provision/testdata/plan14-root-reads-edge-protection-2-decisions.tsv| new file mode 100644 |
| index 000000000..d43354d7b |
| --- /dev/null |
| +++ b/internal/provision/testdata/plan14-root-reads-edge-protection-2-decisions.tsv |
| @@ -0,0 +1,12 @@ |
| +# Census overlay edge-protection-2-decisions, written BY HAND (AGENTS.md, The census: census-propose refuses decisions). The decisions of census-ruling-edge-protection-2 (branch edge-protection-2, Plan 2 of docs/superpowers/specs/2026-10-24-edge-request-protection-design.md: the hard and probe tiers, watch by default; plan docs/superpowers/plans/2026-10-25-edge-protection-2-hard-probe-watch.md): one new unit, one re-frozen and one removed. Loaded from the chain manifest before plan14-root-reads-edge-protection-2.tsv, which census-propose wrote for the approvals. Asked of the census owner on #280 with the card docs/superpowers/notes/census-proposal-edge-protection-2.md; rows carry the ruling from the start (#369). |
| +# No root read is added. The catalogue is data compiled into the binary and parsed at init. Its consumers are the edge inside the agent (carlos-edge.service, user carlos), which matches requests against it, and the console (console.service, user carlos-console), which names a reference code's rule with edgeguard.RuleByHash; nothing opens it from disk. Two frozen declarations are added (the catalogue, new, and NewRef, re-frozen), so the seal moves. |
| +# Merge of origin/main (c743efea: static sweep, edge asset cache Plan 1, the account root hardening, plans 4c, gated deploy watch): rows unchanged; main touched none of the units frozen or removed here. Loaded after gated-deploy-watch-164 (was certwarm-wake), so only the chain line's seal moved. |
| +# NEW, embedded data (file:external): the protection catalogue, each rule's match and mode. Mirrors the console's embedded templates (internal/console/templates/*.html external, accepted legacy). |
| +@legacy 0291888d7f4309afcf563fa8d5e61e9a948363ed26e0a217e211d35674c9dad2 internal/edgeguard/catalogue.txt external legacy accepted-legacy accepted-legacy;rev3=census-ruling-edge-protection-2;identity=its two consumers: the edge inside the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos), which matches requests against it, and the console (cmd/console serve under console.service, user carlos-console), which names a reference code's rule through edgeguard.RuleByHash (apiedgeref.go);basis=new: the edge protection catalogue, the hard and probe tier rules, each with what it matches and its mode (watch, block or burst): embedded with go:embed into the binary (edgeguard.catalogueData) and parsed once at init (parseCatalogue, then buildIndex; init panics on a malformed row or a version line that disagrees with edgeguard.Version); never opened from disk at runtime; data, not code; it only says which request paths and query values the edge matches, what the edge does with a match, and which rule a code names; no root decision; the class of the console's embedded templates (internal/console/templates/*.html external) file:external@0 f017cbb0b580fb799dec98930051c816c3ad45ed18a05eb424337fd1bdf3a269 |
| +internal/edgeguard/catalogue.txt external legacy accepted-legacy accepted-legacy;rev3=census-ruling-edge-protection-2;identity=its two consumers: the edge inside the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos), which matches requests against it, and the console (cmd/console serve under console.service, user carlos-console), which names a reference code's rule through edgeguard.RuleByHash (apiedgeref.go);basis=new: the edge protection catalogue, the hard and probe tier rules, each with what it matches and its mode (watch, block or burst): embedded with go:embed into the binary (edgeguard.catalogueData) and parsed once at init (parseCatalogue, then buildIndex; init panics on a malformed row or a version line that disagrees with edgeguard.Version); never opened from disk at runtime; data, not code; it only says which request paths and query values the edge matches, what the edge does with a match, and which rule a code names; no root decision; the class of the console's embedded templates (internal/console/templates/*.html external) file:external@0 f017cbb0b580fb799dec98930051c816c3ad45ed18a05eb424337fd1bdf3a269 |
| +# RE-FROZEN, basis only (census review, Astra, 2026-10-25): NewRef's caller is now Edge.mintRef, as Edge.recordMatch is removed below. Same digest, same read, same disposition; the basis says "production caller is Edge.mintRef" in place of "called only by Edge.recordMatch". |
| +@legacy 87090950033303f14d4a6eb0a3f49b62f7f8614bd91657d15e4900dae16bf49c internal/reqrec/ref.go NewRef legacy accepted-legacy accepted-legacy;rev3=census-ruling-edge-request-records;identity=the edge inside the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos);basis=new: production caller is Edge.mintRef; one crypto/rand.Read of the code's 8-byte nonce from the kernel's random source (rand.Read, not a file), then an HMAC-SHA256 seal over the code's head with the mesh key the caller passed in, when it passed one; the nonce only makes codes unique, and the code is a reference the owner looks up, never an authorization; no file, no store, no box state, nothing written; the class of mintMeshKey's crypto/rand read (J4 root-input) and dbreads nonce (census-ruling-db-region-forward-1) file:Read@484 a2e27bb0dfd313172d0b43c81f9dceb91c13910c0258f027b720cd59593960c8 |
| +internal/reqrec/ref.go NewRef legacy accepted-legacy accepted-legacy;rev3=census-ruling-edge-request-records;identity=the edge inside the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos);basis=new: production caller is Edge.mintRef; one crypto/rand.Read of the code's 8-byte nonce from the kernel's random source (rand.Read, not a file), then an HMAC-SHA256 seal over the code's head with the mesh key the caller passed in, when it passed one; the nonce only makes codes unique, and the code is a reference the owner looks up, never an authorization; no file, no store, no box state, nothing written; the class of mintMeshKey's crypto/rand read (J4 root-input) and dbreads nonce (census-ruling-db-region-forward-1) file:Read@484 a2e27bb0dfd313172d0b43c81f9dceb91c13910c0258f027b720cd59593960c8 |
| +# Removed: Edge.recordMatch (frozen by edge-request-records-decisions) is no longer declared. Retired by an H3 census-ruling removal (zddr3's form; the loader takes H3 only with a census-ruling- basis). A removal is not in the seal. |
| +@remove internal/edge/reqrecords.go Edge.recordMatch |
| +@removed internal/edge/reqrecords.go Edge.recordMatch H3 census-ruling-edge-protection-2: no longer declared: its body is split in two. The reference-code mint (reqrec.NewRef from the time, the rule tier and id, this box's name and the mesh key the edge already holds in memory) moved unchanged into Edge.mintRef, in which the scan finds no read site, and the Match it filed is now built by Edge.observeRecords (re-frozen in the census-propose overlay edge-protection-2) from the guard verdict the observer defer finds on the request's outcome; its one scanned site, the route passed in, went with the Match. It ran in the edge inside the agent as carlos. |
diff --git a/internal/provision/testdata/plan14-root-reads-edge-protection-2.tsv b/internal/provision/testdata/plan14-root-reads-edge-protection-2.tsv| new file mode 100644 |
| index 000000000..1507127b5 |
| --- /dev/null |
| +++ b/internal/provision/testdata/plan14-root-reads-edge-protection-2.tsv |
| @@ -0,0 +1,13 @@ |
| +# Census overlay edge-protection-2, written by census-propose (#369). census-ruling-edge-protection-2, approved on #280 before the merge; the approval card is docs/superpowers/notes/census-proposal-edge-protection-2.md. |
| +# 2 body, 1 sites, 5 envelope: each changed unit re-frozen at its existing disposition with its claim appended. |
| +@legacy c2d6ffbd62656c6d14d42498f6ab6259a7f8eaad9b450b19f550ca95bafa3012 internal/edge/reqrecords.go Edge.observeRecords legacy accepted-legacy accepted-legacy;rev3=census-ruling-edge-request-records;identity=the edge inside the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos);basis=new: called from ServeHTTP's observer defer after observeAnalytics, with the route the defer already holds; returns at once when no recorder is wired or the request arrived over a tunnel (the forwarding box records it); otherwise builds the Response through requestResponse from that route and the request and hands it to the in-memory recorder, which files it into the box's log sink; its one scanned site is the route value passed in; it reads no file, no store and no box state, writes nothing outside the log sink, and makes no serving or root decision; the class of Edge.observeAnalytics (J1 root-route);rev3=census-ruling-edge-protection-2;basis=files one reqrec.Match in place of the Response when the request's outcome carries a guard verdict (kind block or watch, the verdict's rule tier, id, fragment and reference code; a block woke nothing), and the plain Response otherwise; still in-memory, its one scanned site is the route value passed in; no read added whole:Route@491 c6e8607b6453e04bad358009746bcc1a97e00ef16463594e5b216e4025a84b37 |
| +@legacy f701732ef85b1b75af7ae3fba38ce61ac6aabd606d6752aeaec5c917254ab46d internal/edge/static.go staticSite.serveTree legacy accepted-legacy accepted-legacy;rev3=J4;basis=root-input;rev3=PROPOSED-static-redirects;identity=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos);basis=the same index-aware Stat lookup inside the extracted tree, now run at most twice (the request path, then once for a _redirects rewrite destination cleaned rooted inside the same tree); the Open moves to serveFile; the _redirects file itself is never answered; no root decision;rev3=census-ruling-edge-protection-2;basis=consults the edge protection matcher (internal/edgeguard, pure and in-memory) on the request path (probe tier, only when no file and no _redirects rule names it) and on a rewrite target (hard tier, only when the file is there), and may answer the guard's 404 block page through guardDecide before a redirect or the rewritten file; the _redirects lookup gains an in-memory names check; the same index-aware Stat lookups inside the extracted tree, unchanged; no read added file:Stat@1064,file:Stat@967 a0d335dd9c673d8e5fded6c8b07e54a29c8939c337b11b891ec804a286b9ca1d |
| +@legacy 3949672e7293ddfad77bb0864c01c97ab3e1d382e5adb0a7b932b0182528a749 internal/edge/edge.go Edge.ServeHTTP legacy accepted-legacy accepted-legacy;rev3=census-ruling-seeded-instances;basis=the edge inside the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): main's body with the import gate checked after the door's scope and a gated row left out of the response cache; serving only;rev3=census-ruling-edge-request-records;basis=one more call in the observer defer, observeRecords(up.route, ...), passing on the route the defer already holds; no new kind of read;rev3=census-ruling-design-edge-rate-limit-358;basis=calls rateAdmit twice, and an admitted request holds a slot on both paths: on the upgrade path before the activator or proxy (the handshake holds its slot through slotWriter, given back at the first final answer or at the reverse proxy's hijack on a 101, so an open WebSocket is not counted; released by a defer), and on the ordinary path after the response-cache check and before the activator and proxy (an admitted request holds a slot through slotWriter, released by a defer); a refusal is a 429 written there and returns; the upgrade path's comment now names slotWriter as its one wrapper; one comment on the door mark reworded; read sites unchanged (22: main's 21 plus edge-request-records' observeRecords pass of the route), offsets moved; no read added;rev3=census-ruling-plans-4c-box-throttle;basis=calls planThrottleAdmit before the response cache, and on an upgrade trackUpgrade then planUpgradeAdmit (plans 4c, Astra findings 1 and 2); the new reads live in those units (plans-4c-units decision). The same read sites here.;rev3=census-ruling-plans-4d-lapse;basis=calls planDisabledAdmit right after the import gate, passing the final upstream's route and the request host; a turned-off route gets the fixed disabled page before the meter, gate, cache and activator (plans 4d). The new read lives in that unit (plans-4d-units decision); one more whole-row pass here.;rev3=census-ruling-edge-protection-2;basis=runs the guard, a pure in-memory matcher on r.URL.Path and RawQuery (internal/edgeguard), once per request after the meter and observer defer and before the password gate, the upgrade branch, the cache and the activator, for a request that is not a door call, a backhauled door hop or a tunnel delivery; a matched block answers a 404 itself through guardDecide; the two new sites are one expression, up.route.Kind == "static" (a static route this box serves checks only the hard tier here and leaves the probe tier to serveTree), a read of the route row the edge already resolved; no new kind of read registry:Gate@15566,registry:Gate@15626,registry:Gate@15684,registry:Host@15669,registry:ImportGate@19879,registry:Kind@11997,registry:Kind@14304,registry:Kind@19850,whole:Route@10017,whole:Route@10209,whole:Route@12000,whole:Route@13140,whole:Route@13235,whole:Route@13311,whole:Route@13355,whole:Route@14307,whole:Route@15569,whole:Route@15629,whole:Route@15672,whole:Route@15687,whole:Route@17320,whole:Route@19853,whole:Route@19882,whole:Route@21714,whole:Route@9805 4802013d63e84703ae99692da0978b3a83fbd77cfe67e83a20c8b9c4bb731136 |
| +internal/edge/reqrecords.go Edge.observeRecords legacy accepted-legacy accepted-legacy;rev3=census-ruling-edge-request-records;identity=the edge inside the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos);basis=new: called from ServeHTTP's observer defer after observeAnalytics, with the route the defer already holds; returns at once when no recorder is wired or the request arrived over a tunnel (the forwarding box records it); otherwise builds the Response through requestResponse from that route and the request and hands it to the in-memory recorder, which files it into the box's log sink; its one scanned site is the route value passed in; it reads no file, no store and no box state, writes nothing outside the log sink, and makes no serving or root decision; the class of Edge.observeAnalytics (J1 root-route);rev3=census-ruling-edge-protection-2;basis=files one reqrec.Match in place of the Response when the request's outcome carries a guard verdict (kind block or watch, the verdict's rule tier, id, fragment and reference code; a block woke nothing), and the plain Response otherwise; still in-memory, its one scanned site is the route value passed in; no read added whole:Route@491 c6e8607b6453e04bad358009746bcc1a97e00ef16463594e5b216e4025a84b37 |
| +internal/edge/static.go staticSite.serveTree legacy accepted-legacy accepted-legacy;rev3=J4;basis=root-input;rev3=PROPOSED-static-redirects;identity=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos);basis=the same index-aware Stat lookup inside the extracted tree, now run at most twice (the request path, then once for a _redirects rewrite destination cleaned rooted inside the same tree); the Open moves to serveFile; the _redirects file itself is never answered; no root decision;rev3=census-ruling-edge-protection-2;basis=consults the edge protection matcher (internal/edgeguard, pure and in-memory) on the request path (probe tier, only when no file and no _redirects rule names it) and on a rewrite target (hard tier, only when the file is there), and may answer the guard's 404 block page through guardDecide before a redirect or the rewritten file; the _redirects lookup gains an in-memory names check; the same index-aware Stat lookups inside the extracted tree, unchanged; no read added file:Stat@1064,file:Stat@967 a0d335dd9c673d8e5fded6c8b07e54a29c8939c337b11b891ec804a286b9ca1d |
| +internal/edge/edge.go Edge.ServeHTTP legacy accepted-legacy accepted-legacy;rev3=census-ruling-seeded-instances;basis=the edge inside the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): main's body with the import gate checked after the door's scope and a gated row left out of the response cache; serving only;rev3=census-ruling-edge-request-records;basis=one more call in the observer defer, observeRecords(up.route, ...), passing on the route the defer already holds; no new kind of read;rev3=census-ruling-design-edge-rate-limit-358;basis=calls rateAdmit twice, and an admitted request holds a slot on both paths: on the upgrade path before the activator or proxy (the handshake holds its slot through slotWriter, given back at the first final answer or at the reverse proxy's hijack on a 101, so an open WebSocket is not counted; released by a defer), and on the ordinary path after the response-cache check and before the activator and proxy (an admitted request holds a slot through slotWriter, released by a defer); a refusal is a 429 written there and returns; the upgrade path's comment now names slotWriter as its one wrapper; one comment on the door mark reworded; read sites unchanged (22: main's 21 plus edge-request-records' observeRecords pass of the route), offsets moved; no read added;rev3=census-ruling-plans-4c-box-throttle;basis=calls planThrottleAdmit before the response cache, and on an upgrade trackUpgrade then planUpgradeAdmit (plans 4c, Astra findings 1 and 2); the new reads live in those units (plans-4c-units decision). The same read sites here.;rev3=census-ruling-plans-4d-lapse;basis=calls planDisabledAdmit right after the import gate, passing the final upstream's route and the request host; a turned-off route gets the fixed disabled page before the meter, gate, cache and activator (plans 4d). The new read lives in that unit (plans-4d-units decision); one more whole-row pass here.;rev3=census-ruling-edge-protection-2;basis=runs the guard, a pure in-memory matcher on r.URL.Path and RawQuery (internal/edgeguard), once per request after the meter and observer defer and before the password gate, the upgrade branch, the cache and the activator, for a request that is not a door call, a backhauled door hop or a tunnel delivery; a matched block answers a 404 itself through guardDecide; the two new sites are one expression, up.route.Kind == "static" (a static route this box serves checks only the hard tier here and leaves the probe tier to serveTree), a read of the route row the edge already resolved; no new kind of read registry:Gate@15566,registry:Gate@15626,registry:Gate@15684,registry:Host@15669,registry:ImportGate@19879,registry:Kind@11997,registry:Kind@14304,registry:Kind@19850,whole:Route@10017,whole:Route@10209,whole:Route@12000,whole:Route@13140,whole:Route@13235,whole:Route@13311,whole:Route@13355,whole:Route@14307,whole:Route@15569,whole:Route@15629,whole:Route@15672,whole:Route@15687,whole:Route@17320,whole:Route@19853,whole:Route@19882,whole:Route@21714,whole:Route@9805 4802013d63e84703ae99692da0978b3a83fbd77cfe67e83a20c8b9c4bb731136 |
| +@coverage . 09e6a90414bfb83907186e5d560f52eb8aeb87ab6124139c702a6abc5811011c |
| +@coverage internal/console 09305da294d3cabcd3e132aabb09a7148e2737b75b0a5aae447d2f0fdb55b1ff |
| +@coverage internal/edge 4ad1833891472571f41602f496832bb7c4333b106eb4a59fd16119aa82a56471 |
| +@coverage internal/edgeguard eb7fbf69f820445425ef4dd34b16a4af56e695867f799a7ae8cf2a70af975794 |
| +@coverage internal/hostenv 59676bc45c9778eaf2f59dc03f13937f10fc07aa7b7405a12c91871604c01882 |
diff --git a/main.go b/main.go| index 393054f5b..96b33c85a 100644 |
| --- a/main.go |
| +++ b/main.go |
| @@ -118,6 +118,8 @@ func main() { |
| runAvailability(args) |
| case "geo": |
| runGeo(args) |
| + case "explain": |
| + runExplain(args) |
| case "analytics": |
| runAnalytics(args) |
| case "channels": |
| @@ -293,6 +295,7 @@ Your apps — ship and run software on a CARLOS deployment |
| analytics an app's page views and visitors from a terminal, counted at |
| the edge as it serves your app |
| geo what the platform's GeoIP database says about an address |
| + explain what a reference code from a page the edge answered says |
| ledger open ledgers: append | head | list | publish | blob | verify |
| vet check a release against the platform contract |
| update update this carlos binary to the latest release (or name |