# openwaf An edge that sits in front of an application it knows nothing about, proxies to it, and **bans a source because of what the application answered** — a run of refusals from one address — while the operator's own block list stays exactly as it was. Blocking is usually manual: a human notices abuse and adds an IP. That never fires at 3am. openwaf turns the block list from a record of past incidents into a live defence, without inventing a rule language nobody will maintain. .NET 10, YARP reverse proxy, EF Core, one deployable. --- ## The three pillars, and the one place they meet There is exactly **one** middleware that may refuse a request (`EdgeGuardMiddleware`). Everything else observes. Precedence is a property of the design, not a side effect of registration order: | # | Pillar | Answer | Lifetime | |---|--------|--------|----------| | 1 | always-pass prefixes — `/admin-api`, `/admin`, `/healthz`, `/readyz`, `/openapi` | pass | the recovery hatch for an operator who blocked themselves | | 2 | **allowlist** (address or CIDR, matched on the raw peer address) | pass | wins over everything, including a geo deny | | 3 | **request rule** (OPEN-54) — a path pattern an operator wrote; `observe` or `block` | 403 naming the rule id, or a counted match with the request passed through | operator's list, may expire | | 4 | **operator block** (`source=operator`) | 301 to `RedirectTo`, else a honey-pot list | never expires | | 5 | **engine ban** (`source=engine`) | 403 + `Retry-After` + a reason | expires on its own | | 6 | **geo policy** (deny list / allow list) | 451 + a note that says the inference is probabilistic | policy, not data | | 7 | **request budget** (OPEN-56) — N requests per source per window; `observe` or `enforce` | 429 + `Retry-After` for the rest of the window, then an engine ban | counted in this process, window restarts on its own | The request rule is the only pillar that looks at the request rather than at what the upstream answered or who sent it. Before it, a known-bad request always reached the origin and became a defence only if the origin's answer happened to fall in the refusal range three times in a row. A rule is a glob over the path — `*` and `?`, anchored at both ends, case-insensitive, `*` crossing `/` — not a regular expression, because the operator writes the pattern and an anonymous visitor writes the path. The first live rule that matches is the answer, in the order the listing shows them. `observe` counts matches and lets the request through (one alert per rule per 15 minutes, and the rules listing carries the tally), which is how an operator finds out what a rule would have blocked before it blocks anything; `block` refuses in `Observe` mode too, because the mode switches off what the edge decides by itself, not what a human wrote down — the same ruling that keeps an operator block live. The budget is the pillar about *how often*, and it runs last — after every other pillar has already answered — because it is the only one that needs live state rather than the snapshot: a count has to be kept while the requests are arriving. Sitting below the whole ordered list is also what makes its exemptions exact. An always-pass prefix, an allowlisted address, a matched rule, a block or a geo refusal never reaches the counter, so the budget counts exactly the requests that would have cost the origin. It exists because every other defence reads something that already happened. A source asking for a cheap path two hundred times a minute produces no refusal, so no streak matures, no rule names it, and the application serves all two hundred. `observe` counts and raises one `rate_breach` alert per source per window; `enforce` answers the request that crosses with **429 + `Retry-After`** and writes an engine ban, so the stop outlives the window, is visible on the blocks listing, and is shared with the other edges. The 429 is the answer while the window is running; once the ban lands the answer is the ban's own 403. The budget is off until an operator writes one. A second middleware, `ResponseObservationMiddleware`, sits *inside* the guard: it awaits the upstream, classifies the status the application actually returned, and feeds a streak counter. Being inside the guard is load-bearing — a refusal the edge generated itself must never feed the streak that produced the ban. ### The streak `N` consecutive refusals inside a window of `M` minutes ⇒ ban for `BanDuration`. Consecutive means what it says: * a `2xx`/`3xx` resets the streak to zero; * a gap longer than `M` restarts it at one; * `4xx` (default `400-499`, inclusive of 400) counts toward a ban; * `5xx` (default `500-599`) **never bans** — it raises an alert instead, because a broken deploy would otherwise take the site down twice: once by being broken, once by banning its own honest visitors. The ban takes effect on the request *after* the one that matured the streak, because the edge decides from the response it has already served. The reset is done by the observer, not only by the counter: a `2xx`/`3xx` calls `StreakTracker.ResetIfTracked`, which costs one dictionary lookup for a source the map has never seen and no MMDB read for anyone. Before that, the sentence above was true in the domain object and false on the wire — a visitor alternating a 404 with a normal page view accumulated refusals across every honest request and still matured a ban. `A_clean_answer_between_refusals_ends_the_run…` in the integration suite is the test for that sentence. ### Alerts speak per escalation, not per request Both alert kinds are edge-triggered: one row when the streak crosses `N`, then one more each time the count **doubles**. Twelve `502`s at `N=3` cost three rows (at 3, 6 and 12). They used to be level-triggered, which meant one alert row per request for as long as the condition lasted — and neither condition ends on its own. A `5xx` never bans, so the source is observed on every request; in `Observe` mode nothing bans at all, so the same is true of a refusal streak. At `N=3` a source hammering a broken upstream for 10,000 requests cost 9,998 rows, kept for the whole retention window, and the operator's alert list (newest 100 in the console, `limit=500` on the endpoint) showed one source and nothing else. The safest mode was also the cheapest way to grow the operator's tables. Silencing once was not the fix: an alert that fires once per source per process and never again hides an outage that got ten times worse while nobody was looking. So the count keeps escalating, and a gap longer than `M` or a clean answer ends the episode, which lets the next outage announce itself again. `A_storm_of_server_errors_alerts_on_the_crossing_and_then_only_as_it_doubles` (9 rows for 1,000 responses) and `A_dry_run_announces_each_candidate_ban_twice_at_most_rather_than_once_per_request` are the tests; both fail with the edge detection removed. ### A refusal is written for the person who got it Every refusal used to be one JSON body. The operator reads the listings; the only audience that can act on a refusal — the office whose address tripped a streak, the visitor who followed a link into a path a rule refuses — cannot do anything with `{"error":"blocked_by_policy","reason":"3 consecutive refusals…"}`. So the guard negotiates the **body** by `Accept`: a client that names `text/html` or `application/xhtml+xml` with q>0 gets sentences, everything else gets the JSON it has always got. `Accept: */*` is *not* a request for HTML — it means "I did not think about it", and it is what curl, monitors and SDKs send, which are exactly the clients that parse the body. Three rules the renderer exists to keep: * **the status never changes.** Negotiation changes the body, never the answer. A 429 that became 200 because a browser looked at it would be a defence that switches itself off when observed. * **nothing is fetched.** Inline CSS, no script, no font, no image, no link, and `robots=noindex` so a refusal never becomes an indexed page. The page goes to anonymous visitors and the runtime image is distroless: everything the visitor needs arrived in these bytes. * **the operator's note is never shown.** An operator block's `reason` is free text typed during an incident ("confirmed scraper"). It is an internal note about a source, so that branch renders the fact and no reference; the note stays in the listings. What the page does carry is the machine reference the JSON already carried — `rule_12`, `country_denied_DE`, `rate_3_of_2`, a ban's reason — plus `Retry-After` and the expiry in UTC, in words. That reference is the string the visitor quotes and the string the operator searches the listings for, which is the whole point of the page. `BlockPage` is a pure function in the domain (no `HttpContext`, no I/O), so the wording is testable without a pipeline; the wire half is `RefusalPageTests` and four smoke lines that ask a real edge what a browser and what curl get for the same refusal. ### The toggle Automatic banning is a mode, not a replacement: | mode | observes | records | blocks | |------|----------|---------|--------| | `Off` | yes | yes | no | | `Observe` | yes | yes, as `candidate_ban` alerts | **no** | | `Enforce` | yes | yes | yes | Switching it off touches no rows. `DELETE /admin-api/blocks?source=engine` clears engine bans and cannot reach an operator's entries — provenance lives on the row, so "clear the automatic ones" is a filter, not a table operation. --- ## Quickstart ```bash # tests dotnet test dotnet/OpenWaf.slnx # end-to-end against a real upstream, with curl assertions ./scripts/smoke.sh # the whole thing behind a proxy OPENWAF_ADMIN_TOKEN=change-me docker compose up --build # the assertions above, against the built image rather than the source tree: # image HEALTHCHECK, streak ban over a socket, per-source isolation, operator # block, allowlist precedence, country deny OPENWAF_ADMIN_TOKEN=change-me ./scripts/compose-smoke.sh ``` Point one probe at it and watch the ban: ```bash for i in 1 2 3 4; do curl -s -o /dev/null -w '%{http_code}\n' http://localhost:8080/wp-admin; done # 404 404 404 403 curl -s -H "X-Admin-Token: change-me" 'http://localhost:8080/admin-api/blocks?source=engine' ``` ## Configuration Everything under `OpenWaf:Policy` (env: `OpenWaf__Policy__…`), overridable at runtime through `PUT /admin-api/policy`, which persists to `policy_settings`. | key | default | meaning | |-----|---------|---------| | `Mode` | `Observe` | `Off` / `Observe` / `Enforce` | | `StreakThreshold` | `10` | N | | `StreakWindow` | `00:05:00` | M — the gap that still counts as one streak | | `BanDuration` | `01:00:00` | how long a ban stays live | | `RefusalRange` | `400-499` | statuses that count toward a ban | | `ServerErrorRange` | `500-599` | statuses that raise an alert | | `Geo` | `Off` | `Off` / `DenyList` / `AllowList` | | `TrustProxyHeaders` | `false` | may `X-Forwarded-For` define the source? | | `MaxTrackedSources` | `10000` | hard bound on the in-memory streak map | | `Ipv4KeyPrefixLength` / `Ipv6KeyPrefixLength` | `32` / `64` | source-key granularity | | `EngineBlockStatus` / `OperatorBlockStatus` | `403` / `301` | what a block answers | | `DefaultRedirectTargets` | iana example | honey-pot targets for operator blocks | | `Rate` | `Off` | the volume budget: `Off` / `Observe` / `Enforce` (OPEN-56) | | `RateLimitPerWindow` | `100` | requests one source may make per window | | `RateWindowSeconds` | `60` | how long that budget lasts | | `NetblockCandidateBans` | `5` | how many live engine bans inside one block make the edge offer that block to the operator; `0` is the watch off (OPEN-67) | | `NetblockPrefixV4` / `NetblockPrefixV6` | `24` / `48` | the block a candidate is written as | A `PUT` whose value is outside its range is a **400 that names the key and the range**, not a 200 that quietly keeps the old value. Both halves of that matter, and both were measured on the shipped image (`openwaf:ci`) before the fix: `{"streakThreshold":0}`, `{"maxTrackedSources":0}`, `{"banDurationMinutes":-1}`, `{"streakWindowMinutes":0}` and `{"refusalRange":"not-a-range"}` each answered 200 with the untouched policy in the body and zero log lines, so the operator read a success that had not happened; `{"engineBlockStatus":1000}` was stored and obeyed, after which every banned request died as `curl: (1) Unsupported HTTP/1 subversion in response` — no HTTP response at all; and `{"ipv4KeyPrefixLength":0}` collapsed every IPv4 address into one source key (`*`), so a single 404 banned the whole address family — three never-seen addresses were refused on their first request. | field | accepted | why the floor is where it is | |-------|----------|------------------------------| | `streakThreshold` | 1–1000 | 0 is not "never ban" — that is `mode: Off` | | `streakWindowMinutes` | 0.01–1440 | past a day it is a record, not a streak | | `banDurationMinutes` | 0.01–10080 | a ban that outlives its evidence row cannot be explained | | `maxTrackedSources` | 1–1000000 | the bound exists to stop the process being grown at request rate | | `ipv4KeyPrefixLength` | 8–32 | below /8 one key is most of the internet; at 0 it is all of it | | `ipv6KeyPrefixLength` | 32–128 | an /32 is one provider's block; below that a key spans allocations | | `engineBlockStatus` | 400–599 | a block must answer with a status that means blocked | | `operatorBlockStatus` | 301 or 400–599 | 301 is the redirect; any other 3xx is a redirect with no Location | | `refusalRange` / `serverErrorRange` | `low-high` inside 100–599 | a range matching nothing is a pillar switched off by a typo | | `netblockCandidateBans` | 0–1000 | 0 is off and says so; past 1000 the watch is off by arithmetic while the surface still answers | | `netblockPrefixV4` | 8–31 | below /8 a "block" is most of the internet — the same reason the block form refuses `0.0.0.0/0`; /32 is an address, and the list already has a row for that | | `netblockPrefixV6` | 29–127 | /29 is about the smallest allocation a registry hands out; /127 is one address again | | `rateMode` | `off` / `observe` / `enforce` | off is the default: a limit nobody wrote is a defence nobody asked for, and a false positive here locks out a whole office behind one address | | `rateLimitPerWindow` | 1–100000 | 0 is not "no limit" — that is `rateMode: Off`; past 100000 the pillar is switched off by arithmetic while still reading Enforce | | `rateWindowSeconds` | 1–3600 | below a second the counter is stale before it is read (the snapshot TTL is 30 s); past an hour it is a quota, and the lever for a longer sentence is `banDurationMinutes` | | `defaultRedirectTargets` | absolute http(s) URLs | they are written into a `Location` header | Two more layers for a value that arrives without the API — a restored backup, a hand edit: a `policy_settings` row outside its range is ignored at load with a warning naming the key and the value, and `DecisionEngine` refuses to put a status the wire cannot carry (outside 100–999) on a response at all, answering 403 instead. The ranges live in one file, `OpenWaf.Domain/Policy/PolicyBounds.cs`. Four keys are not policy and cannot be changed at runtime. One decides how long this process may keep enforcing a list that is already out of date; two decide how long the data behind the privacy promise sits in storage, and are startup-time because widening a retention window is a deployment decision, not something a request should be able to do; the fourth decides where the streak counters live, which is a startup choice because it selects the store the process registers: | key | default | meaning | |-----|---------|---------| | `OpenWaf:State:RefreshTtlSeconds` | `30` | how stale the in-memory block list may get. On a single edge this is invisible; behind a load balancer it **is** the propagation delay — 23.7 s measured at ~36 req/s in `research/2026-10-01-multi-instance/`. Anything outside 1–300 aborts startup: the process exits non-zero and the log names the key. In Docker the container stays `Up` with nothing listening until the image `HEALTHCHECK` marks it unhealthy — that is what any startup failure in this image looks like, not a special case. `/healthz` reports the value an operator actually got, as `snapshotTtlSeconds`. | | `OpenWaf:Policy:ObservationRetentionDays` | `7` | how long a `source_observations` row survives past its last request. 1–365 whole days; anything else aborts startup naming the key, exactly as `RefreshTtlSeconds` does rather than falling back to 7 — a silently widened window keeps rows longer than the deployment asked for and nothing would say so. Surfaced as `observationRetentionDays` on `/admin-api/state` and `/admin-api/policy`, and as `rows are pruned after Nd` on the console. | | `OpenWaf:Policy:BanRetentionDays` | `7` | how long an expired engine ban and an alert stay readable after they stopped being live. Same 1–365 bound, same startup refusal, surfaced as `banRetentionDays` and `alerts are pruned after Nd`. Two keys rather than one because the two windows answer different questions, and their sharing 7 days was coincidence. Operator-written rows are never pruned by either window. | | `OpenWaf:Policy:SharedStreaks` | `false` | where the streak counters live. `false` is the in-process map: no I/O on the request path, and a threshold counted per instance. `true` moves the same rules onto a row in the database, so N edges mature one streak — the gap measured in `research/2026-10-01-multi-instance/` (four refusals split 2+2 over two edges at a threshold of 3 banned nobody). It costs one round trip per observed response and one optimistic-concurrency retry when two edges touch the same source at once. `/admin-api/state` answers `streakScope`, and `/admin-api/streaks` answers `scope` as `this-process` or `shared-database`, because a count is meaningless without the store it came from. | | `OpenWaf:Alerts:WebhookUrl` (OPEN-53) | empty | where a raised alert is pushed. Empty is no push: the alert table stays the whole record, which is what it was. Set one URL and every alert the edge raises is POSTed there as JSON — `kind`, `sourceKey`, `count`, `lastStatusCode`, `lastPath`, `createdAt`, `detail` — from a **durable queue** — one row in `alert_pushes` per owed delivery, off the request path, written after the alert row is durable (OPEN-60). A failed push never undoes a row, and it is asked again on the schedule below until it lands or the attempts run out; a restart does not lose what is still owed, and two edges sharing one database push each row once, not twice. `OPENWAF_ALERT_WEBHOOK_URL` is the environment fallback. `/admin-api/state` answers `alertWebhookConfigured`, `alertWebhookHost` (host only: a webhook URL carries its secret in the path), `alertWebhookDelivered`, `alertWebhookFailures`, `alertWebhookLost`, `alertWebhookLastError`, `alertWebhookLastSuccessAt`, and the console prints the same on its alert line. The queue itself answers `alertPushPending`, `alertPushDelivered`, `alertPushGivenUp`, `alertPushOldestPendingAt`, `alertPushAttempts` and `alertPushLastError` — counts of rows, so they survive a restart and agree between edges. | | `OpenWaf:Alerts:WebhookTimeoutSeconds` | `5` | how long one push may take. 1–60 whole seconds; anything else aborts startup naming the key, as the other startup-parsed bounds do — a 0-second timeout drops every push and a 600-second one parks a queue worker on an endpoint that is not answering, and neither is what the operator typed. | | `OpenWaf:Alerts:MaxPushAttempts` (OPEN-60) | `6` | how many attempts one delivery gets before the edge stops asking. 1–20 whole attempts; anything else aborts startup naming the key. Against an endpoint that refuses, the default spends its last attempt a little over three minutes in (30 s, 60 s, 120 s, 240 s, 480 s — each step capped at 30 min) and then records the row as given up: `alertPushGivenUp` counts those rows and `alertPushLastError` says why in the sentence the row carries (`gave up after 6 attempts: the endpoint answered 500`). A row that has given up is never retried, and the alert row behind it is untouched — what is lost is the telling, not the record. | | `OpenWaf:Alerts:PushRetrySeconds` | `30` | the base of the backoff between attempts: attempt *n* waits `base × 2^(n−1)`, capped at 30 minutes per step, because exponential growth from a 30-second base reaches a day in eight steps and a day is not a retry interval for a page meant to fire at 03:00. 1–3600 whole seconds, same startup refusal — a 0-second interval against a dead endpoint is a busy loop. | | `OpenWaf:Policy:ChangeRetentionDays` (OPEN-64) | `30` | how long a record of a config change survives. Longer than the observation window on purpose: "when did this rule get here" stays worth asking about an incident weeks old, and the row is about a decision, not a source. 1–365 whole days, same startup refusal. | | `OpenWaf:Policy:ChangeLogMaxRows` (OPEN-64) | `5000` | the other bound on the same table: how many rows it holds however young they are, oldest dropped first. The age window alone would let a scripted churn grow a table whose whole use is being readable. 100–100 000, same startup refusal. | | `OpenWaf:Admin:ReadOnlyToken` (OPEN-62) | empty | a second token that can read every operator surface and change none of it. Unset means the level does not exist and the admin token is the only one there is. The level is decided by the request method — GET, HEAD and OPTIONS read, everything else writes — so a write endpoint added later is behind the rule without anyone remembering to mark it, and forgetting fails closed. `GET /admin-api/export` is the one read deliberately held to the admin token, because the document is a capability. A value equal to the admin token (compared after trimming, because env files add newlines) aborts startup naming both keys and never the secret, and it exits 1 rather than throwing: measured on the shipped image, an unhandled exception there printed the reason and then spun at 100% CPU with the container "Up (unhealthy)" forever, which is a failure no supervisor can see. | A refused value ends the process. Every bound above is checked before the edge serves a request, and a refusal is a written reason naming the key and the value plus **exit code 1** — the same code for every one of them, so a supervisor can tell "refused to start" from "an edge that died while serving". That form was a bug, not a style: measured on the shipped image, an unhandled exception during startup printed the reason and then the process sat at 100% CPU inside the runtime's crash path, leaving the container `Up (unhealthy)` forever with no exit code — compose reported nothing, k8s restarted nothing, and the only symptom was a spinning core. The gates assert the process **leaves** (started detached, polled for an exit), because waiting on it cannot tell a refusal from a hang. Database: `Database:Provider` = `sqlite` (default) or `postgres`, `ConnectionStrings__OpenWaf`. GeoIP: `GEOIP_MAXMIND_DB_PATH`. ### The geo database ages on purpose, and a rebuild does not replace it The image bakes a dbip-country-lite MMDB pinned by `ARG DBIP_VERSION` (currently `2026-10`, moved by hand on 2026-10-01). `/healthz` reports `geoBuiltAt`, `geoDatabase` and `geoStale` (over 90 days), and `/admin-api/geo` reports the age in days. The 90-day flag is an alarm, not the policy, and the gap is measurable: with the named volume holding `dbip-country-lite-2026-09` while the Dockerfile pinned `2026-10`, `/healthz` said `geoBuiltAt: 2026-09-01T01:32:45+00:00` and `geoStale: false`, and every geo assertion in the smoke test still passed — the country deny list still refused 8.8.8.8 with 451. A month behind is a policy nobody chose, reported as healthy. Three things close it: * `scripts/geo-db-freshness.sh` compares the pin with the newest release the vendor actually serves and answers with three codes, not two: 0 current, 1 the vendor has something newer (it prints the bump), 2 could not tell — no network, or a pin the vendor has never served, which would make the image build fail on a 404. "Could not check" is never printed as ok. * `scripts/geo-db-bump.sh` rewrites the ARG and prints the two commands that make the new database actually land. It refuses to write anything when the check could not run: a pin moved on the strength of a check that did not run is worse than a pin left alone. * `.github/workflows/geo-freshness.yml` runs the check on the 1st and the 8th, and deliberately does not open a pull request — a bot that cannot run the geo assertions bumping a data dependency is a worse default than a red job. `scripts/compose-smoke.sh` asserts the pin against the running container (`the loaded geo database is the pinned one`). Its teeth were checked, not assumed: against the stale volume above it printed `Dockerfile pins 2026-10, the container loaded 2026-09` plus the `docker volume rm` line, **27 passed, 1 failed**, and after removing the volume **28 passed, 0 failed**. `docker-compose.yml` mounts a named volume at `/app/geoip` so a redeploy does not re-download 8 MB. Docker seeds a named volume from the image only the first time the volume is created, so **an existing deployment keeps the old database after a rebuild**. Measured on 2026-10-01: the same rebuilt image reported `geoBuiltAt: 2026-09-01` against the existing volume and `2026-10-01` after `docker volume rm openwaf_openwaf-geoip`. That is the command to reach for when the pin moves. ### Two images, one program, and the same 379 assertions against both `Dockerfile` ships the edge on `aspnet:10.0-noble-chiseled`: a distroless runtime, no shell, no package manager. `Dockerfile.scratch` ships the same program on **nothing at all** — no base image, no distro, no shell — and carries the shared objects itself: the ones `ldd` reports, the dynamic loader (the kernel looks for it at the path recorded inside the binary, so it has to land at exactly that path), the NSS modules `getaddrinfo` dlopen()s, OpenSSL, and the CA bundle. Measured twice, on 2026-10-06. On one arm64 host: chiseled **262 MB**, scratch **222 MB**, of which 12 shared objects and a CA bundle make **18.7 MB**. On the x86-64 runner, where the production architecture is the one that matters (Gitea Actions run 2476, head `be6c608`, the `scratch-image` job): RID `linux-x64`, the same **12** shared objects and **19.9 MB**, scratch **218 MB** against chiseled **258 MB**. `scripts/compose-smoke.sh` runs unchanged against either image — the only change is the `docker-compose.scratch.yml` override — and it answered **368 passed, 0 failed** on both architectures. Re-measured on the same arm64 host the evening of 2026-10-06, against the 379-assertion version of this gate: **379 passed, 0 failed** against the chiseled image at load average 12. Against scratch this revision is not green here yet, and the README says so rather than borrowing the other image's number: the shared host has held load average 26–48 since that run, and the scratch runs came back **377 passed, 2 failed** at load 39 and **378 passed, 1 failed** at load 48 — every failure in the load-sensitive scenes named below (OPEN-78), none in the instruments this revision changed. The assertions are the reason the second Dockerfile is worth having, and the first scratch image built here is the reason they were needed: it started, its own `HEALTHCHECK` reported healthy, and it still failed **7 of the 368**. A self-contained apphost takes its content root from the process's working directory; a scratch image has no `WORKDIR`, so the process started in `/`, never found the `appsettings.json` next to it, the reverse proxy had no routes, and every request that should have reached the upstream answered the edge's own 404 — including the `/boom` 502 the "server errors alert, they never ban" scene is built on, which turned that scene into a streak ban. The edge said it in its own log: *"Request reached the end of the middleware pipeline without being handled by application code."* A healthy container was not a working edge. ``` scripts/ci-gates.sh scratch-image # build it, print both images' sizes scripts/ci-gates.sh scratch-smoke # the 379, against it ``` And the fully static shape, measured the same day rather than argued: `Dockerfile.aot-probe` publishes this edge NativeAOT against musl and puts the result on scratch. The link really is static — `file` calls the binary `static-pie linked`, `readelf -l` finds **0** program interpreters, `readelf -d` finds **0** `NEEDED` shared objects — one **58,343,456-byte** file in a **96.4 MB** image (arm64/musl, measured 2026-10-06), against 222 MB self-contained and 262 MB chiseled. **The sqlite wall is closed, and the sentence this paragraph used to carry was wrong for this tree.** It said the binary dies in `Microsoft.Data.Sqlite.SqliteConnection..cctor` with `DllNotFoundException: e_sqlite3`. That was true of a build that *did not link sqlite*. Two items in `OpenWaf.Edge.csproj`, musl-only, close it: `NativeLibrary` puts `/usr/lib/libsqlite3.a` (Alpine `sqlite-static`) on the link line and `DirectPInvoke` makes ILC emit a **direct call to the symbol** instead of a run-time module load. With only the first, the binary still calls `NativeLibrary.Load("e_sqlite3")` at the first query and NativeAOT answers `Dynamic loading not supported` — which is what the probe was reporting. These are the same two items the runtime pack uses for `System.Native` and the OpenSSL shim (`Microsoft.NETCore.Native.Unix.targets`), not an invention here. Measured after the change: the log carries **0** `e_sqlite3` lines and says the edge **created 12 tables** from the DDL the binary carries. The proof is behavioural because the binary is stripped — `nm` reports **0** `sqlite3_` symbols on a binary that demonstrably runs sqlite, so no tool that only reads the file can answer this question. A standalone probe says the same thing one level down: `Microsoft.Data.Sqlite` opens a connection and reads `sqlite_version()` back (3.53.4) from a fully static AOT binary — so the ADO layer survives and only EF's *query compilation* is the wall. It named **two** walls rather than one, which is what closing the sqlite one bought; as of 2026-10-07 **the first of those two is down on this tree**: - ~~the web host refuses to start at all~~ — closed. The AOT edge now reaches `Now listening on:`, answers `/healthz` with 200, proxies a request to the upstream for 200, and its own `--healthcheck` mode exits 0. The refusal was `JsonTypeInfo metadata for type 'OpenWaf.Edge.Admin.NewBlockRequest' was not provided by TypeInfoResolver`; the route handlers in that stack were already the generated ones (`GeneratedRouteBuilderExtensionsCore`), so the API half was never missing code generation, only a registered contract for the shapes that cross the wire. See the next section. - every query is still refused — `Query wasn't precompiled and dynamic code isn't supported with NativeAOT`, **18 refusals in the 2026-10-07 probe window** — 32 before the first query moved off EF, and the count is a window rather than a total because the background refresh loop retries on its own clock — which is EF's precompiler (the NativeAOT entry in `docs/ARCHITECTURE.md` carries its four untranslatable query shapes and its codegen bug). This is the one wall left, and it is the generator slice. The shape that ships past both walls, in a neighbouring deployment of the same runtime, has no EF Core at all: Npgsql plus Roslyn source generators that emit the queries — and the endpoints, and the OpenAPI document — at build time, one static binary in production. `.github/workflows/aot-probe.yml` re-measures this on the x86-64 runner weekly, because the musl AOT compiler crashes under emulation on Apple Silicon and a laptop can only ever produce the arm64 half. ### The first cut into the API wall: a compiled JSON contract The host-start refusal is not a missing switch. A NativeAOT binary has no reflection-based JSON resolver to fall back on, and the fallback it would need is the thing the runtime refuses. So the wire shapes have to be **types** before a contract can be compiled for them. Counted in `dotnet/OpenWaf.Edge` on 2026-10-07 with a string-aware scanner (braces inside interpolated strings are not braces in the code): **144 anonymous-object literals**, in **27 distinct shapes**, of which **111 are the one shape `new { error = … }`**. A source generator cannot describe an anonymous type at all, so those 111 became one named record — `ErrorDto` — and `Admin/EdgeJson.cs` is now the edge's `JsonSerializerContext`: **29 registered types** (the 5 request bodies, the response records the tree already had, `ErrorDto`, `ReadOnlyRefusalDto`, the config-transfer document and its rejected-item row, `HealthDto`, `ReadinessDto`, `ProblemDetails`, `ValidationProblemDetails`). The previous sentence in this section said 24, and 24 was already stale when it was written: the file at that commit holds 25 — `CountrySummaryDto` arrived without the count being re-derived. With `[JsonSourceGenerationOptions(PropertyNamingPolicy = CamelCase)]` because the generated contract carries the property names — without that line the same record answers `{"Error": …}` and every consumer of this API reads a body with no error in it. `Program.cs` puts the context at the head of the resolver chain. The recipe is taken from the neighbouring deployment (`app/lib/Kernel/KernelJson.cs`, `api/Domain/AppJson.cs`, one line in its `Program.cs`), not invented here. Two measurements decided the shape of that wiring, and both cost something to learn: * **A non-empty `TypeInfoResolverChain` replaces the reflection resolver, it does not extend it.** With only the context in the chain, a type it does not know fails on a *JIT* build with the same sentence the AOT probe reports (`JsonTypeInfo metadata for type '<>f__AnonymousType0` `` `1[System.String]' was not provided by TypeInfoResolver of type '[EdgeJson]'` `, from a standalone probe). Twenty-nine anonymous literals are still standing (2026-10-07: 22 of them response shapes, 7 inside an EF query's `Select`, which is the query wall's problem rather than this one), so on a build that can reflect, reflection stays at the end of the chain: the debt kept served and visible rather than a break smuggled into a slice. * **That fallback is not free on the other side.** Naming `DefaultJsonTypeInfoResolver` in an AOT publish pulls the reflection-based JSON stack into the native image: the publish step ran **66 minutes and never finished**, against **232 s** for the same Dockerfile an hour earlier. The branch is now gated on `RuntimeFeature.IsDynamicCodeCompiled`, which the AOT compiler substitutes as a constant, so the shipped binary does not contain the branch at all. The 66-minute figure was taken while this host carried a load average of 26–34 against the earlier run's ~12, so the ratio is an upper bound, not a clean A/B — the weekly runner is where the clean number will come from. What is measured on this tree: `dotnet build OpenWaf.Edge -c Release` **0 warnings**, unit **378/378**, and integration **408/408 in 51 s** — three of them `AotJsonContractTests`, which asks the running edge which body types its endpoints accept (`IAcceptsMetadata`, read from the live endpoint table, so an endpoint added without a contract is red here rather than in next Monday's probe) and asserts the generated contract really says `error` and not `Error`, and that the `ProblemDetails` body every handler falls back to has a contract too. The 408th number also carries a caveat worth keeping: the same suite — 407 tests at the time — run **inside the sandbox** answered **8 failures of those 407**, every one of them `Timed out waiting for the entry point to build the IHost after 00:05:00` — the loopback-bind symptom this README already recorded on 2026-10-04 and 2026-10-05, reproduced here rather than re-diagnosed. What the AOT edge then **does**, measured on this tree on 2026-10-07 with `scripts/aot-probe.sh` (osx-arm64, a **49,609,680-byte** native binary, 10 IL warnings, 0 errors): ``` lines where the edge started listening: 1 json metadata refusals: 0 (was 55, then 1) queries refused at run time: 32 ``` The 55 were **one shape**: the anonymous 8-property `/healthz` literal — the endpoint a scratch container's `HEALTHCHECK` asks, so the edge was serving traffic while its own liveness probe declared it dead. `Health/HealthDtos.cs` names it (`HealthDto`, `ReadinessDto`). The 1 that followed was `Microsoft.AspNetCore.Mvc.ProblemDetails`, the body `Results.Problem` writes and nobody's DTO in this project; its visible cost was a `/readyz` **500 that named nothing** where a **503 naming the failure** is the truth. The probe's scoreboard is now split the way the finding is: three assertions that need no query are **gated** (`/healthz` 200, proxy 200, `--healthcheck` exit 0), five that do are **recorded** with the answer a working edge would give — an operator block answers 503 where 204 is right, the streak ban never forms, `/readyz` says 503 — and any of them that ever matches prints `MOVED`, which is the signal that the query wall moved. The 503 is worth reading, because it is the one the JIT edge gives: `{"status":503,"detail":"Query wasn't precompiled and dynamic code isn't supported with NativeAOT."}`. Before `ProblemDetails` had a contract that body did not exist and the status was 500. Two probe bugs came out of doing this: it sent `Authorization: Bearer` to the admin API, which `AdminAuth` does not read (three assertions were measuring a 401 rather than the query wall), and it checked nothing about whether the host had listened at all. The remaining **29 anonymous literals in 23 shapes** are the rest of the API wall: **22 response shapes** and **7 that live inside an EF query's `Select`** and belong to the query wall instead. The first version of this section carried **130 literals in 51 shapes**, and `fb75890` repeats those figures in its message. They came from a first-pass scanner that walked braces without skipping string literals, so every `{` inside a `$"…{x}…"` was counted as code. The numbers above are the same tree re-measured with a scanner that skips strings, char literals and comments; the 111 that became `ErrorDto` is the one figure both scanners agree on. ### The first query that does not go through EF The query wall is where the generator slice starts, and the first path is moved and measured. Two new projects: * **`dotnet/OpenWaf.Data`** — the runtime, typed over `System.Data.Common` with no provider package in it. `OrmContext` carries a `DbDataSource` and an `ISqlDialect`; `Query` renders SQL by **walking** the expression tree, which is the whole point: EF's pipeline compiles trees into IL at run time, and that is the sentence the probe counts. The supported grammar is a closed set and it says so — joins, subqueries, aggregates other than `COUNT`, updates, deletes, JSON columns and method calls each throw `UnsupportedQueryNodeException` naming the node, rather than rendering SQL that is quietly wrong. * **`dotnet/OpenWaf.Data.Generator`** — a Roslyn incremental generator attached to `OpenWaf.Infrastructure` as an analyzer. For a `[Table]` class it emits the column map, the row materializer and an `OrmMeta.Register` call in a `[ModuleInitializer]`. Nothing at run time asks a type what its properties are, because the answer is a switch the compiler wrote. `PolicySetting` is the first entity moved, `EdgePolicyProvider.ReloadAsync` the first call site, and `Program.cs` composes the driver and dialect on the same `Database:Provider` switch EF uses — sqlite for the shipped image, PostgreSQL for the migrations' provider, one generated query serving both. Measured on the AOT binary, same probe, same window, before and after: ``` queries refused at run time: 32 -> 18 policy reload failures: 1 -> 0 native binary bytes: 49,609,680 -> 49,676,016 (+66,336) ``` The 18 that remain are named by their own stack frames: **14** in `EdgeStateStore.RefreshAsync`, **2** in `BlockStore.WriteBanAsync`, **1** in `BlockStore.AddOperatorAsync`, **1** in an admin endpoint. The policy read — the first refusal in the log before this change — is gone from that list. Two facts about the storage contract came out of it. The model puts EF's `DateTimeOffsetToBinaryConverter` on every timestamp column of sqlite, so that encoding — `(localTicks / 1000) * 2048 + (offsetMinutes & 2047)` — is what every row this application has written already says, and the dialect reproduces it. `SqliteTimestampEncodingTests` asserts the reproduction equals EF's own converter over five instants (a `+03:00`, a `-05:00`, the half-hour `+05:30`, a sub-second value and `DateTimeOffset.MinValue`), and asserts the resolution too: the `/1000` means a round trip through the column drops the sub-microsecond digits, which is EF's behaviour and is now a test rather than a surprise. Two build facts, both paid for: * **`-p:PublishAot` on the command line is a global property**, so it reaches every project in the graph — including a `netstandard2.0` Roslyn analyzer — and the publish dies with `NETSDK1207: Ahead-of-time compilation is not supported for the target framework`. AOT is now switched on by `OpenWafAot=true`, which only `OpenWaf.Edge.csproj` acts on; the same pattern this tree already used for `OpenWafCompiledModel`. * **A raw `Microsoft.Data.Sqlite` data source needs the native bundle registered**: `SQLitePCL.Batteries.Init()` before the first open, because the order in which EF's provider and this data source are first used is not guaranteed. (`SqliteConnectionFactory` is not public API; the factory is `SqliteFactory.Instance.CreateDataSource(…)`.) Gates on this tree: build **0 warnings**, unit **391/391** (13 new: the rendered SQL for both dialects, the null tests, the captured-null case, the refusals, and the timestamp encoding), integration **408/408**, smoke **256/256**. One run of the 408 carried a single failure in `AdminConsoleTests` at a host load average of about 30 and the next run was clean; recorded rather than hidden, and it is the load-sensitive shape this README already documents for the compose gates. ## Schema Migrations are the schema of record for PostgreSQL, which is the provider a real deployment runs: ```bash cd dotnet dotnet ef migrations add --project OpenWaf.Infrastructure --startup-project OpenWaf.Infrastructure ``` A migration set is provider-shaped SQL, so it is not applied to the SQLite default — there the schema is created from the model at startup. `OPENWAF_SCHEMA` overrides the choice: `migrate`, `ensurecreated`, `script`, or `none` when an operator manages the schema themselves. `script` is the same DDL generated from the model at build time and shipped inside the binary (`dotnet/OpenWaf.Infrastructure/Persistence/Schema/schema.sqlite.sql`) rather than re-derived at startup; it exists because a NativeAOT build cannot ask EF to build a model at run time at all, and the `schema-script` CI step regenerates the file and fails the run when the committed copy is not what the current model produces. Both automatic strategies now **finish an upgrade**, because neither used to. `EnsureCreated` creates a missing database and changes nothing about an existing one, and `Migrate` cannot help a database that has no `__EFMigrationsHistory` — it would begin by creating tables that are already there. So an operator who upgraded kept a schema with every table except the new ones, and the pillar behind them answered as if there were nothing to see. At startup the edge now lists the tables the model describes and the database lacks, creates exactly those from the model through the provider in use — indexes included, and never a table that already exists, so an upgrade cannot lose a block list — and on the `migrate` path it first baselines a database with no history table: a migration is claimed as applied only when every table its target model describes is already present, and the claim stops at the first one it cannot confirm. What happened is on `/admin-api/state`: `schemaStrategy`, `schemaTablesAdded`, `schemaMigrationsBaselined`, `schemaMigrationsApplied`, and `schemaMissingTables` — the last one is the invariant, and a non-empty answer names a pillar this build can run with no storage behind it. `none` changes nothing and reports all of it the same way. Measured on postgres rather than assumed: a database created by `ensurecreated` and then asked to `migrate` gained `request_rules` and `source_streaks` — one migration baselined, one applied, both rows in the history table, the indexes present. That run is also what caught a trap in EF itself: `IHistoryRepository.Exists()` answers **true** on postgres for a database that has tables and no history table at all — the one state this step exists to notice — while the same call answers false on sqlite. The question is therefore asked of the table listing, the answer both providers agree on. ## Admin API Requires `X-Admin-Token` (or `?token=`). **No token configured means the admin API is closed**, not open. The header is the form to use. The query string is accepted anyway, because an operator at a keyboard types `?token=` without thinking and the wrong answer to that is an operator who switches auth off. It is not silent: a request authenticated by the query string logs a warning naming the path — never the token. The reason is measured, not assumed. At the shipped log level (`Microsoft.AspNetCore: Warning`) the edge logs no URLs, and a container run with `?token=` in the URL produced **0** lines containing the token; raise `Microsoft.AspNetCore` to `Information` — the ordinary next move while debugging something — and Kestrel logs the full URL, producing **2** such lines. The tests are `A_token_in_the_query_string_is_served_but_named_in_the_log_without_the_secret` and `A_token_in_the_header_produces_no_such_warning_because_it_is_the_form_we_ask_for`; delete the warning and exactly the first one fails. ``` GET /admin-api/blocks?source=operator|engine&live=true POST /admin-api/blocks {"ip","reason","redirectTo","expiresInMinutes"} DELETE /admin-api/blocks?source=engine[&key=…] GET /admin-api/allow?live[=false]&limit&offset POST {"match","note","expiresInMinutes"} DELETE /admin-api/allow/{id} GET /admin-api/policy PUT {"mode":"Enforce","streakThreshold":8,…} GET /admin-api/observations per-source streaks, durable — the maximum ever seen GET /admin-api/streaks the streak standing right now, in this process, with the threshold GET /admin-api/alerts server_error_streak | candidate_ban | rule_match | rate_breach | netblock_candidate GET /admin-api/rate what the volume counter holds right now, biggest first GET /admin-api/netblocks the blocks the edge's own bans point at, with the threshold they were measured against — an offer, never a ban GET /admin-api/rules path patterns, in the order they are enforced POST {"pattern","action":"observe|block","note","expiresInMinutes"} DELETE /admin-api/rules/{id} GET /admin-api/rate-rules per-path request budgets, with what each is counting POST {"pattern","limitPerWindow","windowSeconds","note","expiresInMinutes"} DELETE /admin-api/rate-rules/{id} GET /admin-api/rate-rules/{id}/sources which sources this budget is inside GET is a read; DELETE ?source= drops one source's window on this budget only GET /admin-api/countries PUT /admin-api/countries/{code}?allowed=false GET /admin-api/countries/summary sources and refusals per country, from the aggregates GET /admin-api/geo which database is loaded and how old it is GET /admin-api/state snapshot age, tracked sources, counts, push state GET /admin-api/decide?ip=&path=&country= what the edge WOULD answer that request, which pillar said so, and what the volume counters say about that source right now GET /admin-api/source?ip=&path= everything this edge knows about one address: the exemption, the operator's block (its own or a range that covers it), the engine's ban, the standing streak, the budgets counting it, its alerts and the netblocks that would cover it GET /admin-api/expiring?within= what stops being enforced inside the window (1..1440 min, 30 by default), each row carrying what the engine WOULD answer for that source with only that entry removed GET /admin-api/history?ip= one source's story: every dated record naming it or covering its address, oldest first (within=1..129600 min, 7d default; limit=200) GET /admin-api/find?q=&limit= where a phrase appears: blocks, ranges, exemptions, path rules, path budgets, alerts, change records and country rules, each row naming its store and the field that matched; an address query also returns the rows that COVER it (q=2..128 chars, limit 100, max 500) ``` `?source=` on `/admin-api/blocks` is a provenance filter, and it used to accept anything: an unrecognised value meant `operator`. With two operator blocks and three engine bans live, `GET ?source=enigne` returned the operator list and hid the engine bans, and `DELETE ?source=enigne` answered `{"deleted":1}` and left `operator=0 engine=3` — a typo in the parameter that exists precisely so that "clear the automatic bans" can never erase a human's list erased the human's list. `source` is now `operator|engine|all` or a 400 naming what was sent; a missing source is still "all", and the delete guard for a missing source is unchanged. Two more of the same family: `expiresInMinutes` must be 1–5,256,000 when present (0 and −5 used to mean "never expires", silently, on the one control that outranks every ban — leaving it out is now the only way to say never), and `reason`/`note` are bounded at 512 characters, the budget the attacker-written path field already gets, after a 1 MB note and a 1 MB reason were both accepted and made the listings return ~1 MB each. An operator's block can be time-boxed: `expiresInMinutes` on `POST /admin-api/blocks`, the same 1–5,256,000 bound and the same rule as the exemption's field — present sets the expiry, absent means the block stands until someone takes it off. Nothing in the model was missing: `BlockEntry` has always had `ExpiresAt`, `DecisionEngine` has always asked `IsLive` before honouring a row, and the listing has always printed the column. What was missing was a way to *set* it, so a block typed at midnight over an incident was still there in the morning unless a human remembered to delete it, while the exemption form beside it already had a minutes box. Re-blocking an address that already carries an expiry moves it — the second call means its own duration from now — and 0 or 5,256,001 is a 400 naming the field rather than a permanent block bought by a zero in a box. An operator's block is an address **or a netblock**. `POST /admin-api/blocks` answered `not an IP address` for `203.0.113.96/29` while the allowlist control beside it accepted one, so a scanner rotating through a rented /29 cost one row and one write per address, and the operator's answer to it — one line — was not something the config export could carry. A CIDR now has its own table and is matched by containment on the raw peer address, the same field the allowlist is matched on, after the exact operator block and before the engine's own ban; the verdict stays `block_operator`, so nothing downstream had to learn a new reason. What is written is normalised before it is stored: `203.0.113.37/28` is stored as `203.0.113.32/28`, a `/32` or `/128` is stored as the bare address it already was, and the one value refused on meaning rather than form is the full-width prefix — `"0.0.0.0/0" covers every address there is, including the one this was written from; that is a shutdown, not a ban on a source`. One list answers both shapes: `GET /admin-api/blocks` merges them and says which row is which with `kind`, `DELETE ?key=` takes the CIDR as it was typed, and `?source=engine` still cannot reach an operator's range. A request pays for the number of **distinct prefix lengths** in the table, not the number of ranges — the index buckets by prefix and asks a set for the address masked to it, most specific first — so a hundred /24s cost a request no more than one does. Every capped listing now says how much it cut, and a limit nobody meant is refused instead of reinterpreted. `?limit=` used to be clamped: with 1,103 sources recorded, `GET /admin-api/observations?limit=100000` answered 200 with 1000 rows, no total and no flag, so 103 recorded sources were unreachable and the answer read like the whole window; `?limit=0` and `?limit=-1` each answered 200 with one row. The block listing already carried `X-Total-Count` and `X-Truncated`, with a comment saying that is what stops a page reading like a complete answer; the two listings the console reads most carried neither. They do now, all three take an `offset` that reaches the rest, and a limit outside its range is refused by name — `limit must be 1..1000; got 0`. All of it is now measured on the shipped image rather than only in-process: the compose gate seeds five sources one second apart, reads them back one row at a time, and requires the five pages to be five different sources and exactly the first five rows of the whole listing, with the same total on every page. `/admin-api/streaks` had the opposite fault: it measured truncation against the size of the streak map, and the map keeps a source whose streak a clean answer ended while the listing leaves those out on purpose — with two standing streaks and one reset source, `?limit=1000` returned 2 rows and answered `X-Truncated: true` although nothing had been cut. It measures against standing streaks now and reports `standingStreaks` beside `trackedSources`. On the page, the same run prints "newest 25 of 42 recorded sources" and "Newest 25 of 274 alerts": the data volume survives `compose down`, which is precisely where a table that looks like a window stops being honest. A query parameter the endpoint has never heard of is now refused rather than dropped. Measured on the shipped image with 16 recorded sources: `GET /admin-api/observations?source=203.0.113.11` answered 200 with all 16 rows across 16 different addresses and `X-Total-Count: 16`, and `?src=203.0.113.11` answered the same. The filter was not applied and not refused — it was absent, because the framework binds the parameters a handler declares and discards the rest without a trace. An operator investigating one address was handed fifteen other addresses and a total that matched those fifteen, which is the same shape as the bug found one level up, where an unknown `?source=` *value* meant "operator". Every list endpoint behaved this way. They now answer `400` naming the parameter and listing what that endpoint accepts, and `/observations` and `/alerts` gained the filter the shape of the question implied: `?source=`, exact match, with `X-Total-Count` counting the filtered set rather than the table, so the truncation flag cannot claim a cut that never happened. An empty `?source=` is refused rather than read as "every source"; a source with no rows answers `[]` with a total of 0. `/admin-api/streaks` learned the same filter in the same shape: exact match, `standingStreaks` counting the **filtered** set while `trackedSources` stays the size of the map, and `sourceFilter` echoed in the body — `null` when unfiltered, so a reader never has to guess whether an absent key means "unfiltered" or "this build forgot to say". The operator page asks the question now: a box under "Sources the edge is watching", and every source key the page prints is a button that asks it, narrowing the observation and streak tables together and printing the filtered total under each. A key with nothing recorded is answered in words — `no recorded observations for ` — rather than with an empty box that looks like a loading failure. `?token=` stays accepted, because the admin auth layer reads it out of the query string and that transport is deliberate — and the guard's first run broke three tests that were right to send it, which is the worse failure mode for a guard of this kind: refusing a request that works. That guard covered the read side only, and the image that carried it then answered the same request two ways depending on the verb. Measured on that image: `POST /admin-api/blocks?zzz=1` answered **204** and wrote the ban, `PUT /admin-api/policy?zzz=1` answered **200** and changed the policy, `PUT /admin-api/countries/DE?allowed=true&zzz=1` answered **204**, `DELETE /admin-api/blocks?key=…&zzz=1` answered **200** `{"deleted":1}` — while `GET /admin-api/blocks?zzz=1` answered 400 naming the parameter. The silent half was the half that changes state: a misspelled scoping parameter on a write acts with a wider scope than the caller meant, and answers as if the scope had applied. Every endpoint under `/admin-api` refuses an unknown parameter now — the writes, plus `/state`, `/geo` and `/policy`, which take none — and the refusal runs before any state change, so a rejected write cannot half-happen. One measurement changed the design rather than the coverage: `GET /admin-api/countries?limit=2` still answered 200 with every row after the GET guard landed, because that listing has no paging to honour and the guard had assumed `limit`/`offset` were legal everywhere — the same bug one level down, in the guard itself. Each endpoint now declares its own parameter surface and the base set is only `token`, so the list a refusal prints is true for the endpoint that printed it. The exemption listing was the last one left uncapped, and it had a second fault worth more than the ceiling. `GET /admin-api/allow` answered with every row ever written and no statement of whether any of them still meant anything. Measured on the shipped image — one entry written for one minute against an operator block on the same address: `POST /admin-api/allow {"match":"192.168.65.1", "expiresInMinutes":1}` at 03:58:16; that address answered **502** (through to the upstream, the exemption outranking the block) at 03:58:20 and **301** (blocked again) at 03:59:38; and at 03:59:39 `GET /admin-api/allow` still printed the row with no liveness field while `/admin-api/state` still answered `"allowEntries":1`. The engine was right and the surface was a minute behind it, in the one table whose whole purpose is "who is exempt right now". With 1,101 rows the same endpoint answered 130,386 bytes with no `X-Total-Count` and no `X-Truncated`, and ignored every paging parameter — `?limit=10`, `?offset=1000`, `?limit=0` and `?limit=100000` each returned all 1,101. It takes `live` (default true; `live=false` means "do not filter", the same shape `/blocks` uses), `limit` 1–2,000 and `offset` now, refuses a limit nobody meant by name, carries `X-Total-Count` and `X-Truncated` computed from the same predicate as the rows, and puts `live` on every row — computed from `AllowEntry.IsLive`, the rule the engine itself applies, which is what keeps the listing and the wire from drifting apart again. `/admin-api/state` answers `allowEntries` as the number of exemptions in force, with `allowEntriesExpired` beside it. The dead rows are not pruned, on purpose: retention ages out observations, engine bans and alerts, and an operator's own writes are not the machine's to delete — which is precisely why they have to be visible instead of quietly absent from the only table that shows them. A country rule is matched against the two-letter code the geo database returns, so the code has to be two letters. `PUT /admin-api/countries/{code}` used to check only the length, and on the shipped image `PUT /countries/12?allowed=false` and `PUT /countries/U.?allowed=false` both answered 204: `GET /countries` then listed `12: denied` and `U.: denied` while a source from the busiest country still got through with a 404 — the operator's table claimed two countries were denied and the edge enforced nothing (denying `US` for real turns that same probe into 451, which is the difference the table was hiding). The code is now refused by name — `code must be a two-letter ISO country code; got "12"` — and `DELETE /admin-api/countries/{code}` takes a rule out of the table and out of the snapshot, answering `no country rule for "ZZ"` when there is nothing to remove. That second half matters because a rule used to be permanent: the console gate's own comment read "a country rule cannot be deleted, only overwritten", and the residue outlived `compose down` in the data volume. That was proven in-process first, which is the wrong layer: the shipped image had four country assertions in it, every one of them about a rule that had already been written correctly. It now has nineteen, seeded from the country this run's geo database actually resolves for the probe IP, and the scene refuses to run against leftovers (it counts the junk rows before it starts and requires zero). The teeth were measured, not assumed, and measured on both halves: putting the validation back to a length check answers **179 passed, 6 failed** on the image (`/tmp/c25_mutA_compose.log`) against **5 failed** in-process, and moving the DELETE route off `/countries/{code}` answers **179 passed, 6 failed** (`/tmp/c25_mutB_compose.log`) against **2 failed** in-process. Two of the six in the first case are rows the image would have kept forever (`and none of the four wrote a row` reads 3, and the closing `the junk that used to be eternal is still not in the table` reads 3), which is the sentence the whole ticket is about. That gap — 2 in-process versus 6 on the image for the delete half — is the reason the image-level scene exists. A write that could not happen does not get to answer like one that did. Measured on two images of one stand — the tree before the fix (`b46f5c20`) and after (`08bebf43`) — with the block and policy tables dropped out from under a running edge that held 3 blocks and 1 policy row: | the operator's command | before | now | |---|---|---| | `DELETE /admin-api/blocks?source=operator` | **`200 {"deleted":0}`** | `503 {"error":"…NOTHING was deleted"}` | | `DELETE /admin-api/blocks?key=203.0.113.201` | **`200 {"deleted":0}`** | `503` the same | | `POST /admin-api/blocks` | **`400 {"error":"database error"}`** | `503 {"error":"…the block is NOT in effect"}` | | `PUT /admin-api/policy {"mode":"Enforce"}` | **`200`, body `mode:"Observe"`** | `503 {"error":"…the change is NOT in effect"}` | | `GET /readyz` | **`200 {"status":"ready"}`** | `503` | | `GET /healthz` | 200 | 200 — unchanged on purpose: it is the recovery hatch, and it does not touch the database | `{"deleted":0}` is a fact about the list, so it may only be said when the delete ran; a 400 is a fact about the request, so it may not be used for a storage failure; and readiness has to prove the table the commands touch is readable — `CanConnectAsync` only proves the file opens. The same stand with a healthy storage and six concurrent `POST`s for one address answered `204 204 400 400 400 400` before and `204` six times now: the unique index on (source key, provenance) made the loser of a race the API itself started look like a caller who sent a bad request, which is what a double-click on "block" in the console is. The write retries against the winner's row. That was measured on two images of one stand; the gate had never asked the same question of the ship shape. It now does — 22 assertions of it, triggered with SQLite `BEFORE INSERT/UPDATE/DELETE` triggers rather than a dropped table. A dropped table breaks the listing too, and a listing that answers 500 is honest about being broken; the lie this scene is after is the 2xx that still looks complete, so the trigger has to leave reads working. It also has to cover `DELETE`: measured on the first run of this scene, an `INSERT`/`UPDATE` pair left the delete path untouched, so the two blocks really were deleted, the answer really was 200, and the scene was asserting a failure that had not been produced (**195 passed, 6 failed**, `/tmp/c26_compose1.log`). The teeth, measured on this tree rather than quoted from the ticket: | what was put back | in-process | on the shipped image | |---|---|---| | a failed `DELETE` answering `{"deleted":0}` again | 2 of 7 fail | **204 passed, 3 failed** (`/tmp/c26_mutM1_compose.log`) | | `/readyz` trusting `CanConnectAsync` again | 1 of 7 fails | **208 passed, 1 failed** (`/tmp/c26_mutM2b_compose.log`) | | the console swallowing an empty 5xx again | — | **72 ok, 3 failed** (`/tmp/c26_mutM3_console2.log`) | The second row is the one worth keeping. The scene already asserted *readiness stops saying ready when the block table is not there* → 503, and it still answered **207 passed, 0 failed** with `/readyz` put back to `CanConnectAsync` (`/tmp/c26_mutM2_compose.log`): renaming the table breaks the snapshot build as well, so the snapshot guard refused for its own reason under the same 503. A status code two different guards can produce proves nothing about either of them. The scene now reads the body — the block-table read answers with the storage error alone, the pillar answers with "the guard's snapshot has not refreshed" — and only then does that assertion have teeth. The console half is the sentence the page says when the edge says nothing. An empty 5xx used to make `r.json()` throw, the caller's catch claim that `note()` had already explained, and the status line go quiet exactly when the edge had the worst news to report. Five assertions cover it now, one of them recording every sentence the status line wears during the click — because the regression writes `ok: deleted ? block(s)` and loses it under `refreshed` before a single after-the-fact read could see it. A pillar that stopped reading its table kept answering as though nothing had changed, and nothing on the surface said otherwise. Measured on the shipped image: `PUT /policy {"streakThreshold":2,"trustProxyHeaders":true}` answered 200, and four 404s followed by a 403 from 203.0.113.79 proved a threshold of 2 was live. `DROP TABLE policy_settings` at 04:44:43; 35 s later `GET /policy` still answered `streakThreshold: 2`, `/state` still answered `snapshotAgeSeconds: 0`, `/healthz` and `/readyz` were both 200, and the log carried **one** line. A `docker restart` brought the table's truth back (`streakThreshold: 10`, `trustProxyHeaders: false`) and four 404s plus a fifth wrote no ban: the rule the operator believed was in force had silently been off for that whole window, and the only place that was visible was a log line nobody was reading. Each pillar now counts its own failures — `policyReloadFailures` / `policyLastReadAt` and `snapshotRefreshFailures` / `snapshotLastRefreshError` — `/state` reports them plus `snapshotStale`, `/policy` carries `X-Policy-Reload-Failures` and `X-Policy-Last-Read`, and `/readyz` answers 503 naming the pillar and the age of the snapshot while any counter is non-zero. `/healthz` deliberately stays a liveness answer — the process is up and can serve what it holds — and readiness is the one that stops claiming the policy on the wire is the policy in the database. The engine's own ban write is the durable write on the enforcement path, and it was described worst of all. Measured on the shipped image with writes to `block_entries` aborted by triggers while reads kept working: five refusals from one source at a threshold of 3 answered `404` five times, no ban reached storage or `/state`, `/readyz` answered 200, and the log said "BlockStore: concurrent ban on 203.0.113.12; keeping the winner" four times over an inner `SQLite Error 19: 'gate: ban write blocked'`. Enforcement reads the snapshot, and the snapshot is built from storage — so a ban that cannot be written is a ban that exists nowhere: not on this edge, not on any other edge sharing the database, not after a restart. Nothing was in force, and the only sentence the log offered said the opposite: that another process had won a race and its ban stood. The store now asks storage which case it is, by re-reading the row. A live engine ban for that source means somebody won the unique-index race and nothing is wrong; no row — or a re-read that cannot run either — means the write never happened, and that is counted (`banWriteFailures`, `bansNotWritten`, `banLastWriteError`) and gates `/readyz`. The ban then lands on the next refusal from that source, which is what clears readiness: on a write, not on a timer. That last clause used to have a cost nobody had measured. With the write path broken and then REPAIRED — triggers dropped, zero triggers left, storage healthy — and no further request from the banned source, `GET /readyz` answered **503** at t+30, t+60, t+90 and t+120 s, with `banWriteFailures` and `bansNotWritten` unmoved. The ban pillar clears only on a successful ban write, and the only thing that produced one was the source crossing the threshold again. So the signal an orchestrator uses to keep an edge in rotation was coupled to attack traffic: the quieter the site, the longer a repaired edge sat out of service, enforcing everything except one ban nobody had written. A ban the engine decided and could not write is now kept and re-attempted by a hosted loop on the same 15 s cadence the observation writer uses. The sentence still runs from the moment the ban was decided, so a retry that lands late cannot quietly lengthen it, and a pending ban whose sentence expired first is counted (`bansNeverEnforced`) and logged as never enforced rather than rewritten as a fresh, longer one. `/admin-api/state` answers `bansPendingRetry` and `bansNeverEnforced`, because without the first a healed storage failure is indistinguishable from a quiet site. The readiness gate was not loosened to get this: the enforcement-path boundary above still holds, what changed is that the failure repairs itself. Which failures gate is now a stated boundary rather than a habit. The enforcement path gates — the policy read, the snapshot read, the ban write. The reporting pillars — observations, alerts, retention — are counted and shown and do not gate. The first version of this code gated on all of them, and one measurement moved it: with that gate in place a single lost alert left `alertWriteFailures` at 3 and `/readyz` at **503**; the triggers were then removed and the stand left idle for 120 s, and it answered 503 the whole time with the write path healthy. An alert pillar writes only when an alert happens to be raised, so "not yet proven healthy" had become "unready forever", and an orchestrator would have pulled a working edge out of rotation over a reporting side-channel. Counters clear on evidence — a successful write of that same pillar — never on a clock. The write side had the same silence, and a failed write is worse than a failed read: the row never existed, and no later request brings it back. Measured on the shipped image with SQLite triggers aborting every `INSERT` and `UPDATE` on `source_observations` and `edge_alerts` while reads kept working — a trigger rather than a dropped table, because a missing table breaks the listing too and a broken listing is honest about being broken, while a trigger leaves the listing answering 200. Three new sources refused and a six-request 5xx storm later: `GET /admin-api/observations` answered 200 with the same `X-Total-Count` it had before the break, `GET /admin-api/alerts` still showed the one row it had, `/healthz` and `/readyz` were both 200, `/state` had no write-side field at all, and the log carried "ObservationWriter: flush failed, 4 entries dropped." plus two "AlertWriter: could not persist…". Each writer now counts its own failures — `observationWriteFailures` / `observationsLost` / `observationLastWriteError`, `alertWriteFailures` / `alertsLost`, and `retentionPruneFailures` for the prune that ages aggregates out — and `/readyz` answers 503 naming the pillar and how many rows were lost. A counter clears only on a successful write *of its own pillar*: measured on the same stand, the observation pillar healed on its next flush while readiness stayed red until an alert was actually written again, which is the difference between a counter and a gauge. `retentionPruneFailures` is reported and deliberately **not** a readiness failure — a prune that cannot run keeps aggregates past the age they promise to age out at, which the operator has to be told about, but it does not change what this edge enforces, and pulling every edge out of rotation over a cleanup loop would trade a retention defect for an outage. The error quoted is the innermost one, not the wrapper: "An error occurred while saving the entity changes" is not something an operator can act on, and "gate: durable write blocked" is. The console had its own copy: every destructive row button wrote its green note whatever came back — a refused delete read as `deleted ? block(s)` — and `load()`, which runs after every action and on a 5 s interval, replaced the error line with `refreshed` inside a second. An empty 5xx body threw inside `apiRaw` and was swallowed by the caller's `catch`. A row action now asks whether the answer carried an `error` before it says it worked, and the refresh that follows a failed action holds the note instead of erasing it. A 404 has to explain itself, because the page has nothing else to work from. On the shipped image the same API answered two missing rows differently: | request | before | now | |---|---|---| | `DELETE /admin-api/countries/ZZ` | `404 {"error":"no country rule for \"ZZ\""}` | unchanged | | `DELETE /admin-api/allow/999999` | **`404`, `Content-Length: 0`** | `404 {"error":"no allow entry with id 999999"}` | The silent half is what the console filled in itself: `apiRaw` read **every** 404 as "admin api disabled — set `OpenWaf__Admin__Token`" and threw, so removing a row another tab had already removed sent the operator to configure a token that is already configured — and since the throw landed in a catch that says nothing, the status line ended up reading `refreshed` in the success colour. A 404 is now an answer like any other: its body is shown, and whether the admin surface is off at all is decided by the core read (`/admin-api/state`), which shows the edge's own sentence rather than a guess made from a status code. The same pass found the most destructive button on the page — "clear the automatic bans" — firing its `DELETE` and reading nothing back, so cleared 7, cleared 0 and a refused write looked identical after the reload; it now reports the count the edge gave, and the note for the action just taken survives the refresh that action itself triggered. `redirectTo` on a block is the one field that ends up in a response header, and the shipped image used to accept any string in it — `POST /admin-api/blocks` answered 204 for all of these, and the next request from that source paid: | target written | what the blocked request answered | |---|---| | `https://example.com/ok` | `301 Location: https://example.com/ok` | | `http://bad target` | `301 Location: http://bad target` — unparseable | | `http://x.invalid/` + CRLF + `X-Injected: 1` | **`500 Internal Server Error`, `Content-Length: 0`** | | `javascript:alert(1)` | `301 Location: javascript:alert(1)` | | `not-a-url` | `301 Location: not-a-url` | The CRLF row is the one that makes this a defect rather than a wart: Kestrel refuses to write the header, so the operator's own block — accepted with 204 — turned that visitor's request into a server error. No header was injected, which is the only part of the old behaviour that was safe. `redirectTo` is now an absolute http(s) URL or a 400, and the decision point ignores a target it cannot send and answers the block's own default instead, for a row that arrived by a restored backup or a hand edit. ### Asking what the edge would answer, before it answers anyone `GET /admin-api/decide?ip=&path=&country=` runs the same `DecisionEngine` over the same snapshot the wire reads and answers the question every other admin surface cannot: what would happen to this request. Writing a path rule, an exemption or a country rule currently has one test — a real visitor getting the real refusal — and `Observe` mode is no help, because it switches the engine off for everything rather than answering one named request. ``` GET /admin-api/decide?ip=203.0.113.7&path=/wp-admin { "verdict": "block_rule", "blocked": true, "status": 403, "rule": { "id": 12, "pattern": "/wp-admin*", "action": "block", "note": "scan" }, "pillars": [ { "pillar": "alwaysPass", "outcome": "did_not_match" }, { "pillar": "allowlist", "outcome": "did_not_match" }, { "pillar": "requestRule", "outcome": "answered", "note": "a request rule blocked this path (rule_12)" }, { "pillar": "operatorBlock","outcome": "not_reached" }, { "pillar": "engineBan", "outcome": "not_reached" }, { "pillar": "geo", "outcome": "not_enforced_in_this_mode", "note": "the geo pillar is off" }, { "pillar": "rate", "outcome": "not_evaluated", "note": "answered by the `volume` section of this preview, which reads the counters without spending them" } ], "volume": { "mode": "Enforce", "scope": "this-process", "verdict": "refused_now", "reached": true, "edgeBudget": { "count": 4, "limitPerWindow": 2, "windowSeconds": 60, "windowStartsAt": "…", "windowEndsAt": "…", "secondsLeft": 37, "overBudget": true }, "pathBudgets": [ { "id": 1, "pattern": "/wp-admin*", "limitPerWindow": 20, "windowSeconds": 60, "counted": true, "count": 6, "overBudget": false, "windowEndsAt": "…", "secondsLeft": 51 } ], "note": "the edge-wide budget is already crossed for this source: in Enforce mode this request is answered 429 for the rest of that window, and a path budget pauses only the path it names" } } ``` The `pillars` list is the point. A verdict says what would happen; the trace says **which pillar to change**, and it keeps the three silences apart — `did_not_match` (asked, said no), `not_reached` (never asked, because an earlier pillar spoke), `not_enforced_in_this_mode` (this configuration does not run it) and `not_evaluated` (this question could not ask it). In `Observe` mode the engine line goes further and says whether a live ban for that source exists, because "nothing was known about this address" and "something was known and the mode chose not to act" are the two answers operators keep reading as one. What it cannot answer is stated in the body rather than left out: the **streak** depends on responses the upstream has not produced yet. A bare `pass` without it would be a wrong answer, not an incomplete one. It changes nothing — no counter, no streak, no budget, no alert — and the answer is labelled with the snapshot it was computed from (`snapshotAgeSeconds`, `snapshotTtlSeconds`, `snapshotStale`), because a block written a second ago lands when the snapshot refreshes. The volume half of that gap is closed (OPEN-69). The `volume` section answers what the counters of this process say about that source right now: the mode, the edge-wide window (`count`, `limitPerWindow`, `windowSeconds`, when it ends and how many seconds are left), and one row per live path budget whose pattern matches the asked path — in the order the guard evaluates them, by the same matcher. The `verdict` keeps the four answers apart: `not_counted` (the pillar is off, so there is no budget to cross), `no_source` (no address was asked, and a budget is a claim about a source), `refused_now` (a counter this request falls inside is already past its budget), `would_be_counted`. `reached: false` says an earlier pillar answers the request, so the guard would never consult the counter for it and nothing would be spent. A budget that is in force for this path but has counted nothing for this source yet prints `counted: false` rather than `count: 0` — "0 of 2" and "nothing yet" are answers an operator acts on differently. Reading rather than spending is the invariant: the section is built from peek reads, so N dry runs leave `count` exactly where it was and write no alert. A preview that answered by counting its own question would refuse the next real request because somebody pressed a button, and the tool for finding an over-tight budget would itself be the cause of it. The counters are this process's (`scope: "this-process"`), and the answer says so rather than letting a preview on one edge speak for another. Input is refused, not guessed: an unknown query parameter is a 400 (the same guard every admin endpoint runs), and an `ip` that is not a full address is a 400 naming the value. `IPAddress.TryParse` alone would accept `203.0.113` as `203.0.113.0`, which is exactly the typo that would otherwise be answered `pass`. ### One address, one answer `GET /admin-api/source?ip=
[&path=]` answers what this edge knows about one source in one call. Every other surface here is a table with a filter on it, so investigating one address meant opening six — blocks, allow, streaks, observations, alerts, the dry run — and holding the join in one's head. The join is where the mistakes are, and each of them is a wrong answer about a real visitor: * a v6 address looked up in its full form, when the ban is filed on the `/64` the key rule groups it into — the lookup answers "nothing known"; * a CIDR ban looked up by equality, which never finds it, because a range is a containment claim and not a key; * an exemption that expired last week read as a live one, or as absent; * a streak counted in one process read as the deployment's. So the dossier asks the same objects the request path asks and never a second copy of their logic: containment through `NetworkMatch` and `NetworkBanIndex`, the identity through `SourceKey`, the verdict through `DecisionEngine`. ``` GET /admin-api/source?ip=203.0.113.21 { "ip": "203.0.113.21", "sourceKey": "203.0.113.21", "keyRule": { "ipv4PrefixLength": 32, "ipv6PrefixLength": 64 }, "verdict": "block_operator", "answer": "the operator's range ban 203.0.113.16/28 covers this address and never expires", "geo": { "country": "NL", "source": "geo-database", "rule": null, "mode": "DenyList", "wouldDeny": false }, "allow": null, "operatorBlock": { "sourceKey": "203.0.113.21", "cameFromRange": true, "match": "203.0.113.16/28", "reason": "netblock scanning", "expiresAt": null, "live": true, "scope": "database" }, "engineBan": null, "streak": { "scope": "this-process", "consecutiveRefusals": 2, "threshold": 10, "maxConsecutiveEver": 7, "totalRefusalsEver": 41, "durableScope": "database" }, "volume": { "mode": "Enforce", "scope": "this-process", "edgeBudget": { "count": 6, "limitPerWindow": 100, "secondsLeft": 41, "overBudget": false }, "pathBudgets": [ { "id": 3, "pattern": "/login*", "limitPerWindow": 5, "count": 4, "overBudget": false, "secondsLeft": 12 } ] }, "alerts": [ … ], "netblockOffers": [ { "match": "203.0.113.16/28", "bans": 7 } ], "wouldAnswer": null, "scope": { "database": [ "allow", "operatorBlock", "engineBan", "alerts", "observations", "netblockOffers" ], "thisProcess": [ "streak (unless sharedStreaks)", "volume counters" ] } } ``` Three rulings hold it together. **Containment, not equality.** `cameFromRange: true` and the `match` that covered the address are reported, because the address itself is not on the operator's list and a listing that only shows rows keyed on it would say so. The same `NetworkBanIndex` the wire matches with answers the question, longest prefix first, so the most specific claim about that address is the one that speaks. **The key, not the address.** `sourceKey` and the prefix lengths that produced it travel in the answer, so a v6 `sourceKey` is not mistaken for a typo. Bans, streaks and budgets are filed under the key; the allowlist and the range bans are matched against the address itself — which is why the answer separates them. **`none` and "not visible here" are different words.** A live engine ban under `Observe` mode is reported with `applies: false` and a verdict of `none`, because the ban is real and enforces nothing. An expired row is reported with `live: false` rather than as absent: "this address used to be exempt" is a fact an operator acts on, and `null` would say it never was. With `path=` the answer carries `wouldAnswer`, the dry run's verdict for that named request, so the parts and the verdict cannot disagree. Without it, `answerScope` names the two pillars that need a path instead of leaving them unmentioned. Nothing is written and nothing is spent — the dry run's rule applied to the whole dossier. `pathBudgets` comes from a new `RateRuleTracker.WindowsFor` read, so the budgets a source is already inside are listed without asking for a path, and N dossiers leave every counter where it was. `ip` is required and must be a full address: a typo is a 400 naming the value, never a `none`. The read-only token can ask it. ### The numbers leave the edge in Prometheus format `GET /metrics` answers the counters `/admin-api/state` shows a human, in the exposition format (`text/plain; version=0.0.4; charset=utf-8`), so they land in the alerting the operator already runs instead of being read off a page during an incident. The edge has one push surface — the alert webhook, at-most-once, for the four things it can alert about — and a threshold on "the ban writes have been failing for forty minutes" is a pull question. Same token as the admin API: **no token configured closes it**, a wrong token is a 401. It sits on an always-pass prefix like `/healthz`, so an edge that has blocked the operator's own address is still watchable. What it exposes, and nothing else: * requests by verdict — `openwaf_requests_total{verdict="pass|pass_allowlisted| pass_bypassed|pass_rule_observed|block_operator|block_engine|block_rule|geo_reject|block_rate"}`, all nine from the first scrape, so "nothing happened" and "this build does not count that" stay different answers in a graph; * what is being enforced now — `openwaf_blocks_live{source="operator|engine"}`, `openwaf_allow_entries{state="live|expired"}`, `openwaf_streaks{state="tracked|standing|shared_store"}`; * the volume pillar — `openwaf_rate_limit_per_window`, `openwaf_rate_window_seconds`, `openwaf_rate_tracked_sources`; * the write side — `openwaf_write_failures_total{pillar=…}`, `openwaf_write_entries_lost_total{pillar=…}` and `openwaf_write_last_success_timestamp_seconds{pillar=…}` for `bans`, `observations`, `alerts`, `retention` and `alertWebhook`, plus `openwaf_bans_pending_retry` and `openwaf_bans_never_enforced_total`; * the alerting itself — `openwaf_alerts_raised_total{kind=…}` for the decision and `openwaf_alert_webhook_total{outcome="delivered|failed|configured"}` for the push, because "the edge saw a storm" and "the operator was told" are different questions; * how current the enforcement is — `openwaf_snapshot_age_seconds`, `openwaf_snapshot_ttl_seconds`, `openwaf_snapshot_refresh_failures`, `openwaf_policy_reload_failures`, `openwaf_policy_last_read_timestamp_seconds`, `openwaf_request_rules_available`; * the geo file — `openwaf_geo_database_loaded`, and when one is loaded its `openwaf_geo_database_build_timestamp_seconds` and `openwaf_geo_database_stale`; * the schema — `openwaf_schema_tables_added_total`, `openwaf_schema_migrations_baselined_total`, `openwaf_schema_migrations_applied_total` and `openwaf_schema_missing_tables`, where zero is the invariant; * the mode — `openwaf_policy_mode_info{mode="enforce|observe|off"}`, because `Observe` changes what every refusal count above means. Two rules the endpoint is built on. **Aggregate only**: no source key, address, path, user agent or operator note appears anywhere in the body, and the only labels are bounded sets written in this codebase — a label per source would be a cardinality explosion and an IP leak into every dashboard and alert rule. **No query per scrape**: every number is one the process already holds in memory, so a scrape cannot be the thing that makes an unhealthy database unhealthy for the request path, and an edge whose storage is down still answers with the numbers that describe the failure. ### The operator's config leaves the edge as one document `GET /admin-api/export` answers one JSON document — `version`, `exportedAt`, `edgeId`, the `policy` this edge is enforcing, and the operator's own rows: `blocks`, `allow`, `rules`, `countries`. `POST /admin-api/import` applies a document like it. ```bash curl -H "X-Admin-Token: $TOKEN" http://edge:8080/admin-api/export > openwaf-config.json curl -X POST -H "X-Admin-Token: $TOKEN" -H 'Content-Type: application/json' \ --data-binary @openwaf-config.json http://other-edge:8080/admin-api/import ``` It exists because of the same finding `SharedStreaks` answers, one level up (`research/2026-10-01-multi-instance/`): with N edges and one database each, an operator types every rule N times and the edges drift, a new deployment starts empty, and a change that turns out wrong has nothing to be rebuilt from. What the transfer does **not** do is the part worth reading: * **Engine bans do not travel.** A ban the engine earned is a claim about this edge's own traffic; enforcing it on an edge that never saw that traffic is a decision nobody made. The export answers `engineBlocksLeftBehind` with the count it left out, so "0 blocks" and "0 operator blocks, 7 engine bans left behind" stay different sentences. * **Import is additive and idempotent.** It never deletes a row the document does not mention — a transfer that silently clears a fleet's exemptions is worse than one that duplicates a block — and a row that is already there is reported as `alreadyThere`, not rewritten. Importing the same document twice lands each row once. * **Expiry travels as an instant.** A block that expires in ten minutes where it came from expires in ten minutes here; a row already past its expiry is `skippedExpired`, not imported as a live row. * **A bad item does not stop the document.** Each item is checked by the same guard the write endpoint uses, and the answer reports per section — `added`, `alreadyThere`, `skippedExpired`, `rejected` — plus the first 20 rejections named by section, index and reason. A document this build cannot read (unknown `version`, a section over 2 000 items, a body over 2 MB, malformed JSON) is refused by name and writes nothing at all. * **The `policy` section goes through the same write path as `PUT /admin-api/policy`** — same bounds, same refusal by name. If it is refused, the rows still land and the report says the policy was not changed and why. * **A storage failure is a 503 with the counts.** What landed is reported; the status says the rest did not. After an import the guard enforces it on the next request — the snapshot is invalidated, as it is for every other mutation. ### A second token that can look but not change There is one admin secret, and until now it meant one thing: whatever could read `/admin-api/state` could also delete every block and rewrite the policy. So a Prometheus scrape held a key that can lift a ban, a second operator checking "why was this visitor refused" held a key that can change what the edge enforces, and `GET /admin-api/export` put a whole edge's config behind the same single request. ```bash OPENWAF_READ_ONLY_TOKEN=dashboard-key docker compose up -d curl -H "X-Admin-Token: $DASHBOARD_KEY" http://edge:8080/admin-api/state # 200 curl -X POST -H "X-Admin-Token: $DASHBOARD_KEY" \ -H 'Content-Type: application/json' -d '{"ip":"203.0.113.9"}' \ http://edge:8080/admin-api/blocks # 403 ``` The rulings, in the order they matter: * **403, not 401.** A known token without the right is a different sentence from an unknown one, and collapsing them sends an operator debugging a failing script to check the secret when what is wrong is the endpoint it was sent to. The body names the key that would grant the write. * **The line is drawn by the method, not by a flag per endpoint.** GET, HEAD and OPTIONS are reads; everything else is a write. A write endpoint added tomorrow is behind the rule the moment it is written. A per-endpoint flag would fail the other way — one forgotten flag and the write is open. * **`GET /admin-api/export` needs the admin token.** It is a read, and it is still the whole config: every block, exemption, path rule, country decision and the policy that bounds them. The token meant for a dashboard and a second pair of eyes is exactly the one that must not be able to lift it, so this one read is held to the admin token while every other read is not. * **A read-only token sees exactly what the admin token sees.** Read-only is about what a token may do, not about showing a weaker view; two people comparing answers must not get different answers because of who asked. * **A read-only token equal to the admin token aborts startup.** A security promise that is false is worse than no promise, and the refusal names both keys without ever printing the secret. `/admin-api/state` answers `readOnlyTokenConfigured`, so an operator can check from outside that the key they wrote took effect instead of guessing from a 401. ### A change to the config leaves a record `GET /admin-api/changes` answers what changed on this edge, when, and through which surface — newest first, capped and paged like every other listing, filterable by `section` and `since`, and readable by the read-only token because it is a read. ```bash curl -H "X-Admin-Token: $TOKEN" 'http://edge:8080/admin-api/changes?section=block&limit=5' ``` The console shows the same rows under **What changed on this edge** — when, section, action, target, the operator's own note, and the surface — newest first, newest 25 of the total, with the two retention bounds printed under the table they govern. A block row and the record of why it was written are on one screen. One row per deliberate change: a block, exemption, path rule or country decision added, changed or removed; a policy update; a config import. A policy record says what moved (`mode Enforce->Off, streakThreshold 3->4`) rather than only that something did. What the record deliberately does **not** do: * **It is not a request log.** The project keeps no request log and this does not start one: the rows are about decisions somebody made, never about visitors. * **Engine bans are not in it.** A ban the engine earned is not a decision somebody made, and the block row already carries its evidence — consecutive refusals, status code, path, user agent, country, city. Logging bans would answer a different question and grow the table at the rate of traffic. * **An import is one record per section, not one per row.** A 2 000-row document would otherwise bury the table whose whole use is being readable; the record says `3 added, 1 already there, 0 past expiry, 0 rejected`. * **It names the surface, not a person.** `operator` for an API write, `import` for a transferred document. The edge has one admin token; a log that implied per-person attribution it cannot provide would be a false record, which is worse than no record. * **A record that cannot be written never undoes the change it describes.** Enforcement is the product, so the change stands and the failure is counted — `changeWriteFailures`, `changesNotWritten`, `changeLastError` on `/admin-api/state` — because "the config changed and the record of it did not land" has to be a sentence an operator can read. ### The edge notices the netblock behind its bans OPEN-66 made a range enforceable. This is the half that decides an operator should write one. A scanner farm inside one /24 is twenty engine bans and twenty operator decisions: the streak rule works per source, so the edge bans each address it sees and nothing connects them. `GET /admin-api/netblocks` groups the edge's **live engine bans** by the block they sit under and returns the blocks with at least `netblockCandidateBans` of them (default 5, `0` is off), each with its ban count, its oldest and newest ban, three of the keys inside it, and whether a range the operator already wrote covers it. The rulings: * **The evidence is the edge's own bans.** An operator's row is a decision already taken, and an expired ban is a row the edge stopped honouring — neither is evidence about a netblock. Nothing new is observed and nothing new is stored. * **An offer is not a ban.** A candidate changes nothing on the wire: the operator's call — `POST /admin-api/blocks` with the CIDR — is what enforces it, and the console button is that same call. Twenty honest visitors of one provider and one farm inside one rented block produce the same number, and only a human can tell them apart. * **The grouping is one allocation up from the key.** v4 groups to /24, the unit most providers hand out; v6 groups to /48, because the streak key is already a /64 and grouping at /64 would only repeat the key. Both are keys, because a host that hands out /22s should be shown the block it can actually act on. * **A ban keyed on a wider block is not evidence about one netblock.** With `ipv4KeyPrefixLength` below the netblock prefix, one row already claims more than a /24, and counting it as one ban inside a /24 would invent a candidate. * **Reading the list is not news.** The scan that answers the surface raises no alert, so refreshing a page cannot manufacture alert rows. The timer's scan raises `netblock_candidate` — through the same durable alert table and push queue as every other kind — at most once per block per six hours, and not at all for a block the operator has already banned. * **A failed scan retires the offers.** The last answer is dropped rather than repeated, and `/admin-api/state` says which of the three situations this is: `netblockCandidateBans` (0 is off), `netblockCandidates`, `netblockLastScanAt`, `netblockScanError`. ```bash curl -s -H "X-Admin-Token: $TOKEN" 'http://edge:8080/admin-api/netblocks' # {"threshold":5,"prefixV4":24,"prefixV6":48,"scannedAt":"…","scanError":null, # "scope":"this-edge","note":"candidates only: nothing here is banned …", # "netblocks":[{"match":"203.0.113.0/24","prefix":24,"bans":11, # "firstBanAt":"…","lastBanAt":"…", # "sample":["203.0.113.10","203.0.113.11","203.0.113.12"], # "alreadyBanned":false}]} ``` What it costs: one scan every five minutes over a table the edge already keeps, off the request path. Nothing on the request path changed — a candidate is read by a surface, not by a guard. ### A request budget for one path The volume budget is one number for the whole edge, and for a login path that number is always wrong: a hundred requests a minute does not stop a credential-stuffing run that makes twenty attempts a minute — twenty looks like a person — while five a minute locks an honest office behind one NAT out of every page they own. The only way to make both statements true is to price the paths differently. `rate_rules` is that row: a glob over the request path — the same `PathPattern` matcher as a path rule, anchored, case-insensitive, `*` and `?` only — with its own `limitPerWindow` and `windowSeconds`. The window is per source and starts when that source first asks, exactly as the edge-wide window does; the request that crosses the limit is the breach, and it is the only one that alerts. What it is not, and the difference is the whole feature: * **It is not a path rule.** A path rule refuses a request because of what it asked for; a budget refuses it because of how often that source asked. * **It is not a ban.** Crossing a path budget pauses that source on that path for the rest of that window and writes nothing that outlives it: no engine ban row, the rest of the site stays open, and the answer is `429` with a `Retry-After` naming the rest of the window. The reason names the rule, its count, its limit and the pattern it was written for (`rate_rule_1_4_of_2_for_/login*`), so a log line says which budget fired without opening the console. * **It is not a second switch.** The budgets hang off `rateMode`: `Enforce` refuses, `Observe` counts and raises one `rate_breach` alert per source per window naming the pattern, `Off` counts nothing at all. An operator deciding whether a number is a defence or their own traffic writes it in observe first, and the listing answers with `trackedSources`, `liveWindows` and `overBudgetNow` — the pair that separates "nobody has blown this" from "nobody can". The bounds are the policy's own (`1..100000` requests, `1..3600` seconds), so one vocabulary of numbers covers both budgets. A second live budget for one pattern is refused with `409` — two live numbers for one path mean the stricter one wins by accident rather than by the operator's choice — and at most `PathPattern.MaxRules` (500) live budgets, because every request is checked against each of them. A budget expires on its own (`expiresInMinutes`) and the listing keeps showing it as `live: false` until it is deleted. Counters are per process, so N edges allow N times the budget — the same documented seam as the edge-wide counter, and the reason both share `maxTrackedSources`: the cap counts (rule, source) pairs together, the least-recently-touched evicted first. ```bash curl -s -H "X-Admin-Token: $TOKEN" 'http://edge:8080/admin-api/rate-rules' # [{"id":1,"pattern":"/login*","limitPerWindow":20,"windowSeconds":60, # "note":"credential stuffing","createdAt":"…","expiresAt":null,"live":true, # "trackedSources":7,"overBudgetNow":1,"liveWindows":6}] ``` What it costs: one glob match per live budget per request, and one counter per (rule, source) pair inside the cap. A budget travels in the export/import document as the `rateRules` section, and it is one of the sections the change log records. ### Who a budget is pausing, and letting one source out The budget listing has carried three numbers per budget since the feature landed — sources counted, windows running, over budget now — and no name. "3 over budget" is the half an operator cannot act on, and the only lever for one of those three was `DELETE /admin-api/rate-rules/{id}`: take the budget off every source on the site to release one office behind one NAT. The edge-wide budget never had this hole, because `/admin-api/rate` names its sources. ``` GET /admin-api/rate-rules/3/sources { "id": 3, "pattern": "/login*", "limitPerWindow": 5, "windowSeconds": 120, "live": true, "scope": "this-process", "keyRule": { "ipv4PrefixLength": 32, "ipv6PrefixLength": 64 }, "total": 2, "sources": [ { "sourceKey": "203.0.113.7", "count": 6, "overBudget": true, "windowStartsAt": "…", "windowEndsAt": "…", "secondsLeft": 41 }, { "sourceKey": "198.51.100.0/24", "count": 2, "overBudget": false, "windowStartsAt": "…", "windowEndsAt": "…", "secondsLeft": 88 } ], "howToRead": "the counters live in this process, so N edges allow N budgets; an over-budget source is answered 429 on this path only, and clearing one source restarts its window at zero rather than exempting it" } ``` The entries are **source keys**, not addresses — the same key the budget counts under, with the prefix rule printed beside it, which is why a /24 can appear in the list. Busiest first, live windows only, paged with `X-Total-Count` and `X-Truncated` like every other listing, and `total` is the same number the listing's `windowsRunning` reports: the names come from the same state as the three counters, not from a second ledger. `howToRead` says which kind of empty an empty list is — "counting, nobody inside a window right now" and "this budget has expired" are different answers, and `sources: []` cannot tell them apart. ``` DELETE /admin-api/rate-rules/3/sources?source=203.0.113.7 { "id": 3, "sourceKey": "203.0.113.7", "asked": "203.0.113.7", "cleared": true, "note": "203.0.113.7 starts its window on this budget from zero at its next request: this is a counter reset, not an exemption, and the budget still applies to it and to every other source" } ``` **This is not an exemption, and the answer says so.** The window restarts at zero and the budget starts counting this source again from there; for "let them through whatever they do" the control is the allowlist, which outranks every pillar. Every other source stays paused. An operator who types the address instead of the key gets the key this edge files it under — the answer names the key it actually dropped, because the others sharing that key are still paused. A second clear finds nothing to clear and answers `cleared: false` rather than repeating the first answer, and writes no second record; the first one is in the change log under `rate rule / changed`, because "why did this source stop being paused" is the question the log exists for. The read-only token reads the list and gets a **403** on the clear — the token is known and its level is the answer; a 401 would tell the operator to go chase a secret. Reading the list spends nothing: N reads leave `count` and `overBudgetNow` where they were, so the page that exists to show a pause cannot cause one. ### The enforcement horizon: what stops answering soon `GET /admin-api/expiring?within=` answers the question an operator asks the evening before. Not "what has an expiry" — a date is a timestamp to interpret by hand at 05:55 — but "what stops being enforced today, and what answers once it has". The window is 1..1440 minutes, 30 by default; a day is the ceiling because that is the longest thing an operator plans for. ``` GET /admin-api/expiring?within=120 { "withinMinutes": 120, "asOf": "...", "scope": "database", "count": 2, "expiring": [ { "kind": "range", "match": "203.0.113.16/28", "expiresAt": "...", "minutesLeft": 18, "note": "scan burst from the ticket", "thenAnswers": { "verdict": "pass", "wouldBeRefused": false, "by": "nothing", "note": "when this entry ages out, nothing else refuses this source" } }, { "kind": "allow", "match": "203.0.113.21", "expiresAt": "...", "minutesLeft": 44, "note": "customer on the ticket", "thenAnswers": { "verdict": "block_operator", "wouldBeRefused": true, "by": "203.0.113.16/28", "note": "when this entry ages out, this source is refused again by 203.0.113.16/28" } } ], "alreadyExpired": { "block": 0, "range": 0, "engineBan": 41, "allow": 0, "pathRule": 0, "pathBudget": 0 } } ``` **`thenAnswers` is the engine, not a guess.** For a block, an engine ban, a range and an allow the row runs the real `DecisionEngine.Decide` over a snapshot with **only that entry removed** — `WithoutBlock`, `WithoutAllow`, or a snapshot whose `OperatorRanges` is the live index minus that one range — and probes the address the entry names: the key itself, or the network address of a CIDR, which is inside the group it describes. So the exemption that is about to lapse says which ban is waiting underneath it, and a block that stands alone says the source goes free. That is the difference between "expires at 06:00" and "at 06:00 this customer falls back into the /28 you banned last week". **A path rule and a path budget have no single answer, and say so.** Their `thenAnswers` is `null` and `whyNoAnswer` points at `/admin-api/decide?ip=&path=`: a pattern describes a set of paths, and the verdict depends on the path and the source being asked about. Inventing one would be the surface guessing where it should hand the question back. **Entries that never expire are not listed**, and neither are entries expiring beyond the window. `alreadyExpired` counts the dated rows whose moment has already passed and which still sit in the tables — retention ages out the machine's own rows, and an operator's rows are not the machine's to delete. That is what separates "nothing expires soon" from "there are no dated entries". Rows are sorted nearest-first: the entry to act on today is at the top, not the one with the largest id. The listing reads the database rather than a snapshot, so it answers about every edge that shares that store. A `within` out of bounds is a 400 naming `1..1440`, an unknown query parameter is a 400 by the same rule as everywhere else on the surface, and the read-only token can ask it — it writes nothing, and six asks leave every counter and every row where they were. ### One source through time `GET /admin-api/history?ip=
` answers the Monday question the other two surfaces do not. The dossier says what this edge knows about an address **now**; the horizon says what changes **soon**; this says what already happened to that source, **in the order it happened**. ``` GET /admin-api/history?ip=203.0.113.69 { "ip": "203.0.113.69", "sourceKey": "203.0.113.69", "window": { "withinMinutes": 10080, "since": "...", "until": "..." }, "scope": "database", "count": 6, "shown": 6, "truncated": false, "events": [ { "at": "...", "kind": "range ban", "what": "the operator banned 203.0.113.64/29, which covers this address", "detail": "netblock scanning the site", "inForce": true, "expiresAt": null }, { "at": "...", "kind": "config change", "what": "block added: 203.0.113.64/29", "detail": "netblock scanning the site", "inForce": null }, { "at": "...", "kind": "allow entry", "what": "exempted by \"203.0.113.69\" — an exemption outranks every ban", "detail": "ticket 441", "inForce": false, "expiresAt": "..." }, { "at": "...", "kind": "alert", "what": "alert server_error_streak raised ×3", "detail": "..." }, { "at": "...", "kind": "engine ban", "what": "this edge banned the source itself", "detail": "3 consecutive refusals (400-499) within 5 min; last 404 /wp-login.php", "inForce": true, "expiresAt": "..." }, { "at": "...", "kind": "seen", "what": "last seen — answered 403 on /anything", "detail": "4 refusals counted, worst run 3 in a row", "inForce": null } ], "searched": { "block": 1, "range": 1, "allow": 1, "alert": 1, "change": 2, "observation": 1 } } ``` **The order is the answer.** "The exemption, then the ban" and "the ban, then the exemption" are different incidents, and an operator assembling this from six listings gets whichever one they opened last. Rows come oldest-first whatever order the writes happened in, and the sort is asserted that way. **A range is in the story because it covers the address, not because a row names it.** The same distinction the dossier had to learn: no row says `203.0.113.69`, and the `/29` that refuses it is still part of its history — as is the change record for that `/29`, because a change to the range is a change to this source's conditions. **`inForce` is null for the kinds that are events, not states.** An alert, a change record and a sighting do not answer "is it in force"; printing `false` would say the alert had been switched off. Expired rows stay in the story and carry `inForce: false` with their `expiresAt`: "this exemption stopped exempting on Tuesday" is part of what happened, not a row to hide. **`searched` says what was looked at**, so an empty story is distinguishable from a surface that read nothing: "nothing recorded about this source" and "this edge holds no records at all" are different answers. The window is 1..129600 minutes (7 days by default, because that is how long the observations and alerts that make up most of a story are kept); `limit` is 200 by default and says how much it left out. The read-only token can ask it, and six asks write nothing. ### Where does this appear? `GET /admin-api/find?q=&limit=` answers the question no listing can. An operator has a phrase — a ticket number, a customer's name, the words they typed into a reason six weeks ago — and nothing else. That phrase is not a field any listing filters on: it sits in a block's reason, an exemption's note, a path rule's note, a path budget's note, an alert's detail and the change log's detail, and asking it by hand means opening eight listings and reading every row. ``` GET /admin-api/find?q=ticket%20441 { "query": "ticket 441", "scope": "database", "matched": 8, "shown": 8, "limit": 100, "truncated": false, "counts": { "block": 1, "range": 0, "allow": 1, "pathRule": 1, "pathBudget": 1, "alert": 0, "change": 4, "countryRule": 0 }, "matching": { "mode": "substring", "wildcardsEscaped": true, "note": "…" }, "results": [ { "store": "change", "id": 41, "match": "203.0.113.64/29", "pattern": null, "text": "netblock from ticket 441", "at": "…", "live": null, "expiresAt": null, "why": "text matched detail" }, { "store": "allow", "id": 12, "match": "203.0.113.64/29", "pattern": null, "text": "ticket 441 window", "at": "…", "live": true, "expiresAt": "…", "why": "text matched note" }, { "store": "block", "id": 7, "match": "203.0.113.69", "pattern": null, "text": "closed after ticket 441", "at": "…", "live": true, "expiresAt": null, "why": "text matched reason" } ] } ``` **The query is data, not LIKE's grammar.** `q=100%` searches the four characters `100%`, not "anything that starts with 100": the backslash, the percent and the underscore are escaped and the match runs as `LIKE … ESCAPE '\'`. Unescaped, a `%` in an operator's own sentence would answer about rows nobody asked about, so the gate searches `100%`, `a_b` and a literal backslash to hold that. **An address query returns the rows that cover it, not only the rows that name it.** That is the part a grep cannot do. Searching `203.0.113.69` returns the `/29` that refuses it — no row contains that address — and the row says why it is there: `"why": "203.0.113.64/29 covers 203.0.113.69"`. Blocks are matched on the key this edge files the address under, the same rule the dossier and the story learned: with a `/29` key, searching `.90` finds the ban stored as `203.0.113.88/29` and prints `this edge files 203.0.113.90 under 203.0.113.88/29`. A row that matches by text *and* covers the address is answered once, with the text match as its reason. **`counts` is per store and is that store's whole answer**, not the rows this call happened to return, so `matched: 0` over eight zeroed stores is a different sentence from a surface that read nothing — and a `limit` truncates the merged answer without pretending a store had nothing else in it. Rows come newest-first: this is a search, not a story, and the row an operator wants is the one they wrote last. `q` is 2..128 characters — one character is a dump rather than an answer, and 128 is the longest target the change log stores — `limit` is 100 by default and 500 at most, and an unknown query parameter is refused by name. It is a read: the read-only token can ask it, and eight asks leave every store holding the same rows. ### What would this ban touch? `GET /admin-api/impact?match=&path=&limit=` answers the question that stops being askable the moment the write lands. Both failures it prevents are silent: a `/24` written over an office block refuses people who were never the target, and a range written inside an existing exemption refuses nobody at all — the operator sees 204 and moves on. ``` GET /admin-api/impact?match=203.0.113.64/29 { "match": "203.0.113.64/29", "kind": "range", "filedUnder": "203.0.113.64/29", "path": "/", "asOf": "…", "scope": "snapshot+database", "probed": 3, "limit": 50, "truncated": false, "counts": { "newlyRefused": 2, "alreadyRefused": 1, "stillPassing": 0 }, "wouldRefuse": true, "changesNothing": false, "alreadyCoveredBy": null, "outrankedBy": [], "exemptionsInside": [], "sources": [ { "source": "203.0.113.66", "kind": "standing streak", "lastSeenAt": "…", "refusals": 12, "worstRun": 12, "before": "pass", "beforeBy": null, "after": "block_operator", "afterBy": "203.0.113.64/29", "change": "newly refused" } ], "note": "…", "wrote": false } ``` **It is the engine, not a second implementation of it.** The answer is `DecisionEngine.Decide` run over the live snapshot with the proposed entry added, over the sources this edge is actually watching inside the match — every recorded observation and every standing streak whose key falls in it, plus the match's own address, because "nothing has been seen inside this range" and "the preview did not look" are different answers. This is the same choice the dry run and the horizon already make, for the same reason: a preview that disagrees with the wire is worse than no preview, so there is no second copy of the pillar order here to drift out of date. **The two ways a ban can do nothing are named, not inferred.** `alreadyCoveredBy` is what already answers for the match's own address: a live `/28` makes the `/29` about to be written decoration, and the row says so — `block_operator by 203.0.113.32/28`. `outrankedBy` is the exemption that covers that address: the ban sits behind the allow pillar in the pillar order, so it never speaks there, and the operator has to see that before the 204 rather than after the complaint. `exemptionsInside` lists the exemptions covering *other* addresses inside the match. All three arrive beside `changesNothing`, which is the sentence a 204 would otherwise hide. **The match is normalised by the write path's own code.** `203.0.113.37/29` and `203.0.113.32/29` are one row, so the preview answers about the row the write would create and refuses a match the write would refuse, in the write's words — including `198.51.100.0/0`, which is refused as a shutdown rather than a ban. `filedUnder` is the key the write would file it under, which for a bare address is this edge's group for it: with a `/29` key, banning one address reaches the whole group, and a preview that answered about one address would be a preview of nothing. `path` defaults to `/`, and the pillar order answers per path — a preview of `/` says nothing about a path rule on `/login`. `limit` is 50 by default and 200 at most, with `truncated` saying when the probe set was cut; an unknown query parameter is refused by name. It is a read: the read-only token can ask it, no token cannot, `wrote` is always `false`, and the compose gate checks the wire still answers the upstream after the preview — because a preview that writes is the exact bug this endpoint exists to prevent. The console carries the same answer as its own panel — "What would this ban touch?", an address or CIDR and an optional path — above the tables the operator reads, so the preview is part of where the decision is made rather than a call one has to know to issue. ## Console `GET /admin` serves a single page over those endpoints — mode and snapshot age, live bans with their reasons, the streak standing in this process right now (current count against the threshold, not the historical maximum), the sources being watched, and the countries seen — counted per ISO code, with a bar per country sized against the busiest one. The request budget (OPEN-56) is written from the same page: a mode select, the two numbers, and a table of what the counter holds right now, with the over-budget count marked. Path budgets (OPEN-68) get their own table beside it: the pattern, its two numbers, and three counters — sources counted, windows running, over budget now — with the last one marked, and a form that writes one with a pattern, two numbers, a note and an optional expiry. The line under the table distinguishes a database with no rate-rule table from an operator who wrote no budgets, which is the difference between a migration to apply and a decision not to make. The page also asks the dry run directly (OPEN-69): an address and a path, and the answer prints the verdict, the path rule that spoke if one did, the edge-wide window with the seconds left in it, and one line per path budget whose pattern matches the asked path. Each budget row has a **who** button (OPEN-71): the panel names the sources it is inside, with each one's count against the limit and the seconds left in its window, and puts a **let out** button beside every one of them — the status line then repeats what the API says, that the counter restarts at zero and this is not an exemption. Beside it sits the dossier (OPEN-70): one address in, and the page prints the key that address is filed under, the verdict, the exemption or block behind it — naming the range when the row is a range and not the address — the engine's ban and whether this mode enforces it, the streak standing in this edge against the threshold with the worst run the database remembers, the path budgets already counting it, and its alerts. A read like the dry run above it, and the gate asserts that asking three of them leaves the operator's table holding exactly the two rows the page wrote. The volume line is the part that makes the button safe to press on a live site — it is read off the counters, and the gate asserts that asking leaves those counters where they were. The line under it says which of the two answers an empty table is — "off, nothing is being counted" or "counting, nobody is over budget yet" — and says plainly that the counting is this process's. That bar is the honest limit of the word "map" here: the admin API exposes counts per country code, not coordinates, and the runtime image is distroless with no external assets, so there is no world outline and no tile server. A geographic map would be a decoration this page could not load at the moment it is wanted. Under the dossier sits the horizon (OPEN-72): a window in minutes and one button, and the page prints one line per dated entry that stops being enforced inside it, nearest first, each naming what the engine would answer for that source once the entry is gone — `then: block_operator by 203.0.113.16/28`, or `then: pass by nothing`. A path rule and a path budget print why they have no single answer instead of guessing at one. The window is checked on the page before the call goes out, and the answer box is emptied first and headed with the window that was asked for, so neither a scene nor an operator on a slow link can read the previous answer as the new one. Under the horizon sits the story (OPEN-73): the same address box and one button, and the page prints the joined timeline oldest-first — the range that covers the address, the block written on it, the exemption, the alerts, the operator's own change records and the sightings — each line stamped, marked `in force` or `EXPIRED …`, with the reason the row carries. The header names the key the address is filed under and counts what was searched, so an address with nothing recorded reads as an answer rather than as a broken panel. Under the story sits the search (OPEN-74): a phrase in and one button, and the page prints one line per row that carries it — the store it came from, what it is keyed by, when it was written, `in force` or `EXPIRED …`, the text that matched and the field it matched in — or, for an address query, that the row covers the address rather than names it. The header counts all eight stores, so an empty answer reads as an answer. It also writes, with the two controls an incident actually reaches for: block one address or netblock with a reason, and allowlist an address or CIDR with a note and an optional expiry (the "my customer is locked out" control — an allow entry outranks every ban). A range row prints the CIDR it is stored under and says `range` beside it, and the delete is the same control keyed by that name; the summary pill counts ranges apart from address blocks (`ranges 2`), because "how many things have I blocked" and "how many addresses" stop being the same question once one row can be a /29. Each ban row has a delete that removes that row, each allow row a remove, and each country row a rule toggle plus — only when a rule actually exists — a "remove rule" button. An allow entry whose expiry has passed stays in the table and says "EXPIRED, the edge no longer honours it", and the pill above it counts live exemptions and expired rows apart — the row is not the answer. `DELETE /admin-api/countries/{code}` takes the rule out of the table and out of the snapshot; flipping it to `allowed=true` does not, it leaves a row behind that only means "not denied". The summary line states which geo database this edge is enforcing on, when it was built and how old it is (marked past the 90-day runtime alarm), and the snapshot age against the TTL it is measured against — because on a single edge the TTL is invisible, and behind a load balancer it *is* the delay a ban has. That pill turns `warn`, rather than staying quiet, when the snapshot is older than the TTL or either pillar's failure counter is non-zero, and it names which: `snapshot 412.7s / ttl 30s · older than the ttl · snapshot refresh failing ×14 · policy not re-read from storage ×14`. A second pill carries the write side and is present in the clean case too — `durable writes ok`, or `durable writes bans not written ×2 (2 not enforced) · observations not persisted ×3 (4 rows lost) · alerts not persisted ×2 (2 lost) · retention not running ×1 · change records not written ×1 (1 changes unrecorded)` — because a pill that only appears when something is wrong makes "no alerts" and "alerts are not being written" look identical from the operator's chair, and because the ban case has to read differently: those two bans are not merely unrecorded, they are not in force anywhere. It lists the path rules in the order they are enforced, with the action, the expiry and how many times an observe rule has matched — and writing one from the page is the same call as writing it through the API. It shows the alerts the edge raises — `server_error_streak` (your upstream is failing, and the edge will not ban the visitor who saw it) and `candidate_ban` (the rule would have banned, but the mode is Observe). That table is the whole point of the alerting pillar: an alert nobody reads is a log line — which is why `OpenWaf:Alerts:WebhookUrl` exists: the same reasoning that removed "a human notices abuse and adds an IP" from blocking applies one level up, and an alert nobody is told about never fires at 3am either. With an endpoint configured the page says `pushed to `, with how many landed, how many failed and how many are still owed; without one it says `not pushed anywhere: each row waits for someone to open this page`, so "no alerts" and "alerts go nowhere" stay two different sentences. It shows the netblocks the edge noticed (OPEN-67) — the blocks its own live engine bans point at, each with the count inside it, the span of those bans and a few of the keys, with one button that writes the range through the same block call the form above uses. A block the operator has already banned says `already banned` instead of offering again, the note under the table says plainly that a candidate is an offer and not a ban, and the summary carries `netblock offers N` apart from `ranges N` — what the edge is suggesting and what this edge is enforcing are two numbers, and mixing them would make a suggestion look like a decision. It shows what changed on this edge — the record of every deliberate config change (OPEN-64) as a table of when, section, action, target, the note somebody typed and the surface it came through, with the log's two bounds (`pruned after 30d or 5000 rows, whichever comes first`) printed under it and the reason engine bans are absent said in the same line. The surface column is the honest one: the edge has one admin token, so it names `operator` or `import`, never a person. It decides nothing: every control on it is one call to the API above. It is on the always-pass list, so an operator who is themselves blocked can still reach the page that clears it, and it is never observed, so fumbling it cannot build a streak. The token is typed into the page and sent as a header; it is never in a URL, because a token in a query string ends up in proxy logs and browser history. No external assets — a page that needs a CDN fails at the moment it is wanted. ## Gates `scripts/ci-gates.sh` is the single definition of every gate; the CI workflow calls the same script one gate per step, so a local green run and a CI green run cannot mean different things. ``` scripts/ci-gates.sh all # restore, build, unit, integration, smoke, both images, both smokes scripts/ci-gates.sh scratch-smoke # the 379, against the image with no base scripts/ci-gates.sh unit # or any one gate on its own scripts/ci-gates.sh console # the page, in a real Chromium (not part of `all`) ``` `OPENWAF_ADMIN_TOKEN` defaults inside `ci-gates.sh` to a throwaway for the stack the gate starts itself and tears down on exit; the standalone scripts still refuse to invent one, because run by hand they can be pointed at a real deployment. The compose gate does not only read the stack: it breaks a pillar on purpose. Through a `python:3.12-slim` sidecar sharing the edge container's volume it runs `DROP TABLE policy_settings`, then drives proxy requests in a loop — the snapshot is refreshed by traffic, not by a timer, so a stack nobody is asking anything never notices — until the failure counter appears, and asserts that `/state` counts it, that `/readyz` has stopped saying ready, that `/policy` carries its own provenance headers, that the *other* pillar still reports healthy, and that `CREATE TABLE IF NOT EXISTS` returns the counters to 0 and readiness to 200. Six assertions, and all six were red before the fix. The compose gate breaks the write path on purpose too, with the same care about *how* it breaks: SQLite triggers (`BEFORE INSERT`/`BEFORE UPDATE` on `source_observations` and `edge_alerts`, `RAISE(ABORT, …)`) installed through the sidecar, so the reads stay honest and only the writes fail. It then asserts that `/state` counts both pillars and says how many rows were lost, that the observation listing's `X-Total-Count` is *unchanged* across the break — the lie, asserted directly — that the failure it names is the storage error rather than EF's wrapper, that the three sources the scene says it lost were really three distinct sources in the live streak map and not one docker bridge address wearing a header nobody trusted, and that recovery is per pillar: the observation counter clears on the next flush, while an alert pillar that has had nothing to write since the break stays reported and stays unproven. Eleven assertions. The recovery half was red against the first version of the fix, which reset readiness as soon as any pillar healed. The readiness half was rewritten a cycle later: this scene used to assert `/readyz` 503 for a reporting-path failure, and the measurement described above moved that boundary — a reporting failure is counted and shown, and only an enforcement-path failure makes the edge unready. The same gate breaks the enforcement-path write too, and asserts the discriminator rather than the log's mood: with `block_entries` writes aborted, a scanner at a threshold of 3 answers `404 404 404 404 404`, no engine ban for it reaches storage, `/readyz` is 503 quoting the storage error, the number of log lines calling a ban write a race is measured **before and after** the scene and must not move (0/0), the honest line is present — counted, 3 lines, and polled, because the line reaches the daemon's log store a moment after the `/state` counter it belongs to and a grep run immediately after the burst answers 0 — and after the triggers go the ban lands on a later refusal with readiness returning on that write. Eleven assertions, and the split matters: the ones that describe the fix — the counters, the 503, the quoted reason, the log-line delta, the honest line — were red before it, while the three that describe the consequence (`404 404 404 404 404`, the scanner really is one source the edge is tracking, nothing in storage) were already green. That is the whole point of the finding: the consequence was always observable and nothing on any surface pointed at it. The compose gate proves the guard that *reads* a stored row, not only the one that writes it. `RedirectTarget.IsSendable` runs on the write path and again on every request, and the read-side half had never been seen on the shipped image — because the API cannot be asked to store a target it refuses, and the row that half exists for arrives by another route: a restored backup, a hand edit, an import from a release that had no guard. So the gate writes a good target through the API, then rewrites the stored column underneath a running edge through the same sidecar, and asks what the edge sends once the snapshot rebuilds. A row holding `javascript:alert(1)` answers 301 to the policy's default target and never to the stored value; a row holding a CRLF-bearing target answers 301 rather than the 500 Kestrel used to produce, and injects nothing. Six assertions, and they are the first six ever run against the deployable rather than against the test host. It also tells a dead edge from a slow one. A curl `000` is the gate failing to reach the stack, and the log used to carry the number and nothing else: one Linux run read `000` at `geo off restores the country`, and "the edge hung" and "the edge died" were indistinguishable afterwards. Every `000` now samples the container the request was aimed at and prints what it reports, and the gate ends with a scene that makes the dead case happen on purpose — `compose stop edge`, one request, `exited/unhealthy` in the log beside the `000`, `compose start`, and the stack back to `running/healthy` answering 404. Five assertions. The gate also has to refuse to describe *its own* failure as the product's, and until 2026-10-06 it did not. `jval` was given three answers for three states (OPEN-48) — no body, a field the object does not carry, a field that is there — and `jcount` and `jget` never received the same treatment: they piped the body straight into `json.load`. Measured in the NativeAOT measurement run of that day (`/tmp/aot-smoke.log`), which is what a run against an edge that dies at start-up looks like: **125 Python tracebacks**, **32 `integer expression expected` shell errors**, `docker: volumes-from specification cannot be an empty string` **6** times, `invalid container name or ID: value is empty` **121** times. And two assertions reported **pass** about an edge that had never started: ``` info policy reload failures counted after the table went away: NO_JSON_BODY ok the state counts a policy pillar that cannot read its table yes info observation write failures counted after writes were blocked: NO_JSON_BODY ok the state counts observations this edge could not persist yes ``` because the comparison was `!= "0"`, and a value that was never read is not the string `0`. That is the worst shape this file has caught: not a red gate, a green one about a dead process. Now `jcount` answers `-1` for a body it cannot read — the sentinel `streaks_where` has used since it was written — and `jget` answers the `NO_JSON_BODY` that `jval` prints; every count comparison goes through `count_ge`/`count_gt`/`count_moved`/`count_sub`, which treat anything that is not a run of digits as "not read" rather than as a number or as the shell's problem; the sidecar names the edge container it cannot share a volume with instead of handing docker an empty `--volumes-from`; and the health wait asks a container that is not there for its health in words (`no-container`), which is what the 121 `docker inspect ""` lines become. The dead-edge scene asserts the behaviour against a container that is really stopped rather than against a canned string: the three helpers answer their sentinels, a comparison on a value that was never read answers no, and none of those reads or comparisons wrote a line to stderr. Five assertions, green in both runs that first made them, and the gate's total moved from 368 to **373**. Two runs on that same day went red on this tree and neither red was this file's fault, so they are recorded rather than smoothed: one lost four alert assertions (`alert rows for 12 server errors at N=3: 0`) and the other lost five range assertions, and the second names its own cause — `curl answered 000 … the edge container reports running/healthy`, a request the gate could not make while another project's dotnet suite was running on the same daemon and the same machine (load average 11, and the run that followed it, on a quieter host, was 373/0). The count arithmetic now separates the two shapes a red alert scene can mean: a read that did not parse prints `-1` where a real zero would sit, and both of those runs printed `0`, so in the first the reads answered and agreed — what was missing was the requests, or the rows, not the parse. The family came back the same evening, one level away from transport. Four runs of the 379-assertion tree went red on the shared host at load average 31, 39, 48 and 31 — **375/4**, **377/2**, **378/1** — and every failure sat in a scene that reads a projection right after a write that was answered. Three of them were the two alert-escalation scenes: `alert rows for 12 server errors at N=3: 0` and `1` where 3 were expected, `candidate_ban rows for 10 refusals at N=3: 0` and `1` where 2 were expected. No `000` anywhere near them: the twelve 502s were answered, the same scene's own ban assertions passed, and `settle_alerts` reported a settled number — zero rows, three reads in a row. So the requests happened and the escalation arithmetic still under-reported. The fourth was a different scene with the same shape: `the shipped story names the block, the covering range and the exemption, oldest first` read `no` at load 48 in a run where both alert scenes were green — three writes answered `204 204 204`, and the history read taken immediately after them was missing one of the four events it names. That is not OPEN-77's shape and it has its own item now (OPEN-78): each scene asserts only the final answer, so none of them can tell "the projection had not caught up" from "the product never recorded it". The same tree at load average 10 and 12 was **379 passed, 0 failed** with those scenes reading 3 and 2. A write that never reached the edge is now retried, and the retry is said out loud. `code`'s `000` is the gate failing to reach the stack (OPEN-39), and for a write that is worse than a wrong number: every assertion after it measures a scene that never happened. Measured the same day (`/tmp/compose-diag.log`, the run named above): one `POST` of a `/29` answered `000` while the container reported `running/healthy`, and four range assertions went red about a row that was never written — one of them a Python `StopIteration` from a bare `next()` over a listing that held no such row. Writes now go through `admin_write`: a non-answer is retried three times with the container's own state printed each time, and a refusal is an answer, so `400` and `403` come back after one attempt untouched. Retrying a write that got no response is safe on this surface because every write it takes is keyed and idempotent — the six-parallel-POSTs scene asserts that one address lands as one row, the transfer scene asserts that importing the same document twice adds nothing — and the retry is bounded, so a surface that is really closed still goes red. Measured against a stubbed `code` that answers `000` twice and then `204`: the write returns `204` after three attempts with two retry lines in the log, and a `400` comes back after one attempt with none. The dead-edge scene asserts both halves against a container that is really stopped — the write still answers `000`, and it says so three times — because neither green run printed a retry line at all: the host was quiet, and a rule like this is gated by a scene that makes the condition happen, not by waiting to catch one. Two assertions, three bare `next()` reads given the sentinel treatment OPEN-48 wrote for `jval`, and the gate's total moved to **375**. The claim that paragraph made was false, and the gate now counts it. `a8f440b` wrote that the gate's admin writes go through `admin_write`. Measured against the same file an hour later: of its 60 writes that do not go through `admin`, 34 went through the helper, 25 still answered through the un-retried `code` and one went straight to `curl`; and the other 91 writes and 157 reads went through `admin`, which carried no part of OPEN-39's rule at all — a read that reached nothing answered `NO_JSON_BODY` and the log said nothing about why, because the sentinel names the missing body, not the missing request. The dead-edge scene asserted the opposite of the fix: that those dead reads write **no line to stderr**, which is the gate agreeing to be blind. So `admin` now sits on the same retry as `admin_write` — three retries on a transport failure, each printing the container it sampled, an HTTP answer returned after one attempt — the 25 and the 1 joined the helper, and that assertion asks for the nine diagnosis lines and for the absence of a traceback instead of for silence. The body comes back byte for byte: `$(curl …)` strips trailing newlines, and the six-parallel-POSTs scene writes six `%{http_code}` lines into one shared file, which a wrapper that re-printed the body carelessly would have collapsed into `204204204204204204`. And the claim itself is now a gate: the file greps its own source and goes red, printing the count, if any write answers through the un-retried status helper or goes straight to curl — because a sentence about the gate is worth exactly what asserts it. Three assertions added, one removed, 375 → **379**; the retry itself was again proved against a stub (`000` twice then a body: two diagnosis lines, the body's trailing newline intact; an unreachable edge: three lines and an empty body; a `400`: none), and again neither green run needed it — the host was quiet. The README's own numbers became a gate. `scripts/ci-gates.sh readme-counts scripts/` compares the assertion count the README prints for a gate with the total that gate recorded in this run — each gate writes its total into `$GATE_TOTALS_DIR`, which the workflow sets per job and `all` sets for a local run. It exists because those numbers were copied by hand out of a log and they drifted: the first run of this check said the README claimed **229** assertions for `compose-smoke.sh` while that gate was printing **368**, a 139-assertion gap nothing could see. With no total recorded it exits 2 — "cannot verify" — rather than reporting a pass. The console gate starts the stack, seeds a source sitting at 2 of a threshold of 3 and an operator block with a reason, four 502s from an address chosen for this run (`/boom`, see the alerting note above), drives `/admin` in a real Chromium, and asserts 168 things. The read side: it authenticated, listed the streak as current-over-threshold rather than as a historical maximum, listed the operator block with its reason, listed observations and countries with bars that have real pixel widths, said how many recorded sources the observation table is only a page of, and counted the streak note against standing streaks rather than against the size of the map, listed the alert this run's seeding wrote (by source and count, not just "a row exists"), said in words that a server error is never a reason to ban, kept the token out of the markup, and threw no javascript. The write side, checked on the wire and not just in the table: an address reaches the upstream (404), the page writes a ban for it, the same address is then refused (301 with the policy's redirect Location — the probe uses `redirect: 'manual'`, because following it walks out to the public internet and comes back 200, which is how this assertion first read as a failure while the edge was refusing the client the whole time), the per-row delete removes that one ban and the address reaches the upstream again, an allow entry appears with an expiry and can be removed, an allow entry whose minute passed a minute ago is still listed and marked `EXPIRED` while a live one is not (the seed writes it with a one-minute TTL ahead of waits the gate already pays, so the expired state arrives for free), and a country rule is written from no rule at all, toggled both ways and then removed (`— → allowed → denied → —`). The gate used to assume a US rule was already there, so on a fresh volume — where the first click allows instead of denying — it failed; a gate that only passes on residue from the previous run is not a gate. The quiet failure mode is asserted too: typing `not-an-ip` into the block form has to come back as the API's own error (`not an IP address: not-an-ip`) with no new row, because an operator who believes they blocked an address and did not is worse than an operator with no console at all. The escaping invariant is asserted too: the seed asks for a path carrying a percent-encoded `` and writes an operator block whose reason carries ``, and the page must show both as text, create no `img`/`svg`/`script`/`iframe`/`object`/`embed` inside any table body, and keep its own title — the path in an observation row is whatever an anonymous visitor asked for, and the only browser in this system holding the admin token is the one rendering it. Reducing `esc()` to the identity function makes this gate go red with 6 failures and the page title becomes `"XSS"`, which is the price of the invariant. Two reads in this gate are now waited for rather than sampled once. The observation table used to be read at one instant, and in an act run that instant was empty — `X-Total-Count: 0` where the same head a minute earlier had 11 rows — while the rows are written by the coalesced observation writer, so an empty table is a normal moment in a run that is about to be correct; the table is now polled with a stated budget and the wait is printed whether or not a row arrived. And the page's own request paths are pinned: the gate records the admin-api calls the page issues while it loads, with their statuses, and asserts the 14 it expects, no others, their query strings intact, and none answered 404. Four assertions, and the reason for them is that a wrong URL on a page never looks like a wrong URL — `withSrc`'s first version appended `&source=` to a bare path, the edge answered 404, and the page printed "unknown scope" for a request that never arrived. Then the pass repeats at 375 px in dark mode, where the document must not scroll sideways and the status line must clear WCAG AA (measured 11.85:1). It needs `playwright-core` (`PLAYWRIGHT_CORE=/path/to/it`) and exits 2 when that is missing — a gate that reports success having asserted nothing is worse than no gate. Its negative control (a wrong token) exits 1. `SCREENSHOT=console-evidence.png` writes the desktop and phone screenshots; the console job names them in its log with size and sha256, because `actions/upload-artifact@v4` is not supported by the Gitea runner (measured on run 2370: every assertion passed and the job still went red on the upload step). ### The same gates on the runner's operating system Every green number above was produced on darwin; the workflow runs on `ubuntu-latest`. `scripts/ci-linux-rehearsal.sh` runs the gates in containers. The source gates (restore, build, unit, integration, smoke) run against a copy of the tree — no `.git`, no host build output, because Linux binaries landing in a macOS working tree make the next `--no-build` try to exec an ELF file — inside `mcr.microsoft.com/dotnet/sdk:10.0`. The compose gate runs in `docker:cli` against the host daemon, so the image build and the stack are Linux. Rehearsed 2026-10-02, most recently at `dc88f36`, each stage run on its own. On the head of this file the host suite has been re-run and the container stages have not, so the two sets of numbers are labelled separately rather than merged into one green line. macOS host, this tree, re-measured 2026-10-05 with the durable alert-push queue, the config transfer, the second token, the startup refusals, the change log and that log on the console, the operator's ranges, the netblock watch and the per-path request budgets, the volume answer of the dry run, one address answered in one call, the sources a budget is pausing, the enforcement horizon, one source told in order and one search across every store the operator's decisions live in: build 0 warnings / 0 errors, unit **377/377**, integration **394/394 in 1 m 16 s**, console **159 assertions, 0 failed**, smoke **passed 243, failed 0**, and compose **339 passed, 0 failed** against the built image at 262 MB, 0 containers left behind. One integration run and four console runs earned their keep in this cycle. The integration run caught a product defect, not a test one: the alert push queue's worker was registered as a hosted service *above* the schema step, hosted services start in registration order, and so on a cold start its first queue sweep read `alert_push_queue` out of a database this same process had not created yet. Nothing crashed — the worker counts what it cannot read — but the sentence it left in `alertWebhookLastError` was "SQLite Error 1: 'no such table: alert_push_queue'", which sends the operator to fix the webhook endpoint for the edge's own startup order. The order is now asserted rather than assumed. The console runs caught a second one: a listing the edge could not answer was drawn as an empty one. With two of the page's fourteen calls answering an error, the observation line printed "0 sources the edge has recorded" and the streak line "0 of 0 standing streaks listed" over a map holding twelve sources — a count read off a failed answer is 0, and 0 is the sentence that says there is nothing to see. Every count-bearing note and the table under it now say `NOT READ` with the error beside them. The rest were the gate's own traps: the dossier scene waited for "an answer is in the box", which the previous answer still sitting there satisfies, so every assertion after the first read the address asked one click earlier; and scenes failed with `answered 403`, because the gate's own probes are refusals and the streak pillar had by then banned the probe addresses — a correct edge and a scene that could not retry past a one-hour ban. Those bans are now cleared by name (`?source=engine&key=`), which leaves the engine bans the netblock scene reads standing, and this cycle found the same trap twice more in the budget scene: it cleared the ban *after* the probe the ban was failing, and its reopen retry loop banned itself three refusals deep. One assertion had to be moved rather than the product: the history scene asked for the story of an address "with nothing recorded" and got 34 change records, because the netblock scene writes and removes `192.0.2.0/24` through the run and a change to a /24 really is part of the story of every address inside it — the surface was right and the assertion had picked an address that was not outside anything. The smoke story from the previous cycle is kept here because the numbers are read next to it: the edge used to be started from the repository root, where there is no `appsettings.json`, so it loaded no `ReverseProxy` section, logged "Request reached the end of the middleware pipeline without being handled by application code" for every request, and answered 404 for a path the upstream was serving with 200 — the gate had been passing on an edge that never proxied anything, because every assertion in it expects a 404 or a refusal. Naming the content root is what makes the first line of `scripts/smoke.sh` true, and the streak scene now waits for the ban row to exist before asking the wire whether it is enforced — re-run on this tree because a new pillar changes what the shipped stack enforces, and because the compose data volume outlives `compose down`: the run after a schema change starts against a database that has every table except the new one, which is the state the rules read is now written to survive and to say out loud. Carried from the 2026-10-02 run and not re-measured since: image 261 MB, 0 containers left behind, enforcement lag 33 ms (`/tmp/c26_build.log`, `/tmp/c26_unit.log`, `/tmp/c26_int4.log`, `/tmp/c26_smoke.log`, `/tmp/c26_compose5.log`, `/tmp/c26_console4.log`). The integration count says how it was scheduled, because that changed the answer once: the suite as xUnit runs it — parallel test collections — answered **157 passed, 16 failed**, every one of them `Timed out waiting for the entry point to build the IHost after 00:05:00` (`/tmp/c26_int3.log`), and with `xunit.parallelizeTestCollections=false` the same tree answered **173/173 in 23 s** (`/tmp/c26_int4.log`). Re-measured 2026-10-04, the default parallel scheduling answered **208/208 in 25 s**, and the same tree run inside a filesystem-and-network sandbox failed **every** fixture with exactly that timeout — a test host that cannot bind a loopback socket hangs in this shape. Scheduling is one variable in that symptom; whether the test host can open a socket at all is another, and it is the one that decided the run today. Re-measured on 2026-10-05 and it decided another run the same way: the same tree inside a sandbox answered **9 failures of 251**, every one of them that same `Timed out waiting for the entry point to build the IHost after 00:05:00`, while the identical build outside it answered **251/251 in 34 s**. The suite is not slow in there; it cannot bind a loopback socket, and the failure it reports is a timeout. Earlier in the same cycle two overlapping runs of the suite produced the older OPEN-47 symptom on `PillarFailureVisibilityTests.The_snapshot_age_is_measured_against_the_ttl_it_is_supposed_to_respect` — a real `Assert.False`, not a timeout — while that test passed on its own. The suite is not the only measurement in this project whose value depends on what else was running. The Linux rehearsal and the `act` run below still describe `dc88f36` — compose **185**, console **70** — because neither stage has been run since the two scenes in this cycle were added, and quoting them for this tree would be a number the tree does not produce. The same suite on the macOS host at `dc88f36` gave unit **132/132**, integration **173/173**, smoke **passed 28, failed 0**, compose **185 passed, 0 failed**, console **70 assertions, 0 failed**, image 261 MB, 0 containers left behind. Source gates: Ubuntu 24.04.5, SDK **10.0.401** resolving `dotnet/global.json` (pinned `10.0.100`, `rollForward: latestFeature` — which is also the answer to whether `setup-dotnet` with `10.0.x` satisfies the pin), unit **132/132**, integration **173/173**, smoke **28/28**, first try, nothing to fix. The first rehearsal of this pipeline timed a cold container and a cold NuGet cache at **1:02.81**; the runs after it were not re-timed, so that is the only wall clock measured here, and the source job's 25-minute timeout is not close either way. Compose gate on Linux: **185 passed, 0 failed** (27 before the geo-pin and alerting assertions, 41 before the alert-edge ones, 47 before the pillar-health ones, 53 before the write-health ones, 63 before the ban-write ones, 72 before the scenes were made non-vacuous, 74 before the query surface was refused rather than dropped, 81 before the retry loop, 86 before the write-endpoint guard, 94 before the streak map learned the source filter, 100 before the policy bounds were driven from the image, 107 before the redirect target an edge cannot send was refused by the image, 113 before the provenance a caller mistyped and the bounds an entry has were refused by the image, 132 before the image said which part of a listing it is and how far it reached, 165 before the image refused a country code that is not a code, 184 before the ban scene stopped reading the pillar at one instant, and 185 before an operator command that could not run was asked of the shipped image), enforcement lag 0 ms, 12 ms and 36 ms in three runs, 12 ms at `a77ab53`, 13 ms at `6e6461a`, 11 ms at `c97c7a1`, 12 ms at `7e081da`, 12 ms at `7b57c56`, 14 ms at `1bcc086`, 12 ms at `336c2f7`, 13 ms at `dcf8a73`, 11 ms at `ac672d9`, 17 ms at `17b764e`, 12 ms at `cfe47d1`, 30 ms at `b75888f`, 56 ms at `24e329d`, 29 ms at `d871d57`, 18 ms at `5c44b7c`, 15 ms at `9383362`, 44 ms at `0f17d32`, 20 ms at `dc88f36`. One Linux run at `d871d57` answered **112 passed, 1 failed** — the geo-restore assertion got `000`, which the gate prints for a request that blew its 10 s budget, for a container that had exited and for any other curl error, all as the same three characters — and the run after it was 113/0; the Linux runs at `5c44b7c`, `9383362`, `0f17d32` and `dc88f36` were 113/0, 132/0, 165/0 and 185/0, so it has not reproduced in the six runs since. Filed as OPEN-39 rather than smoothed over: a gate that fails once for an unexplained reason makes the next real regression indistinguishable from it. The same class showed up again in the same cycle: in one run the ban-write scene read `banWriteFailures` as 0 while that same scene logged "the ban was not persisted" three times and answered `/readyz` 503 with the storage error quoted. Filed as OPEN-42. The read side of that is fixed: the scene now polls the pillar for up to 20 s and prints the trajectory (`failures/notWritten: 0/0 1/1 ...`) and the reason string it quoted, so "the counter is 0" and "the field is not in the answer" are no longer the same word in the log, and the wait itself is an assertion (`the ban pillar reached its failure state within the wait budget`). Breaking it on purpose — threshold 3 → 99, so no ban is ever attempted — answers 178/7 with that assertion first (`/tmp/c25_mutD_banteeth.log`). What OPEN-42 still owns is the product half: the pillar is only updated on the request path, so a quiet edge reports a stale failure count for as long as it stays quiet. Console gate on Linux: **70 assertions, 0 failed** — described below, 0 containers left behind. `scripts/geo-db-freshness.sh` was run in `mcr.microsoft.com/dotnet/sdk:10.0` too: current pin answers 0, and a forced `PIN=2026-05` answers 1 with the bump command, so the gate that decides whether the geo database is current behaves the same on the runner's OS. Getting the compose stage green surfaced two things about the harness rather than the product, both now written into the script. The gate asserts over JSON with **python3**: a bare container failed 23 of 27 assertions for nothing else. And the stack the host daemon publishes lives in the host's network namespace, so without `EDGE=http://host.docker.internal:8080` every HTTP assertion returns curl code `000` while the image's own `HEALTHCHECK` says healthy — a green stack with red assertions, the most confusing failure this gate can produce. The console gate needs a real Chromium, so it runs in `mcr.microsoft.com/playwright:v1.63.0-noble`: `scripts/console-smoke.sh` with `SEED_ONLY=1` starts and seeds the stack from `docker:cli`, the browser image drives `scripts/console-check.cjs` against `EDGE=http://host.docker.internal:8080`, and the stack is torn down afterwards. That image ships the browsers but not the npm package, so the script installs `playwright-core` into `/tmp` and points `PLAYWRIGHT_CORE` at it, mounting the repository read-only so the install never lands in the working tree. Rehearsed the same day on Linux 7.0.12-linuxkit aarch64, node v24.20.0, `chromium-1243`: **70 assertions, 0 failed**, including the round-trip the page alone cannot fake — a ban drawn on the page answers 301 on the next request from that address. The driver also refuses to report success when the markup seed never reached it: unsetting SEED_MARKUP_PATH and SEED_MARKUP_BLOCK used to drop four assertions to 65 ok / 0 failed and still print "all assertions passed"; the same run now exits 1 naming both empty values, and the Linux rehearsal refuses the stage outright. The gate is still a sampler, though: at `ff70c64` a host run answered **68 ok, 2 failed** — the click-a-source-key assertion read the observation table after the filter had applied and found nothing recorded for that key — and the run after it was 70/0 on the same tree. Recorded on OPEN-41 rather than smoothed into the re-run: same root, an assertion that reads a table once while the row it wants arrives on a coalesced write. All three scenes in one cold run: **2:14.33** (measured at that earlier commit; the stage has not been re-timed since). Running that stage with the console job's own environment (`COMPOSE_PROJECT_NAME=openwafci-console`, `EDGE_PORT=8090`) turned up a bug in the stage itself: its cleanup container passed no project name, so it tore down the stack named after the repository directory — nothing — and left the CI-named one running, holding its port, behind a summary line that said PASS. 53 assertions green, 2 containers still up. Passing the name through is `7e081da`; the stage re-run after it leaves 0 containers. Honest status of the workflow itself: it has never executed on a GitHub-hosted runner. The repository does have a remote — `git@vezha.io:para/openwaf.git`, a Gitea 1.27.3 instance whose Actions runner executes this file — so the claim that matters is about *that* runner, and it is recorded run by run below. It *has* been executed start to finish by a local Actions-compatible runner — `nektos/act` 0.2.89 on `catthehacker/ubuntu:act-latest`, most recently at `dc88f36` — 5 jobs succeeded, 0 failed: `lint` (both pinned tools download, verify their checksums and find nothing), `source` (unit 132/132, integration 173/173, smoke 28/28), `image` (`openwaf:ci` 261 MB, compose smoke 185 passed / 0 failed), `console` (70 assertions / 0 failed with `playwright@1.63.0` and `chromium-1243`, screenshot artifact published, 685,222-byte zip) and the `freshness` job (pin 2026-10 = newest 2026-10). The two act runs before that one failed, and both failures were real: `lint` refused three SC2086 findings in the new compose scene, which a local `shellcheck -S warning` had passed over in silence — the workflow pins 0.11.0 and runs with no severity filter, and no local gate runs lint at all (filed as OPEN-44); and in the run after the fix, `image` died on a TLS handshake timeout to `auth.docker.io` while `console` read an empty observation listing (`X-Total-Count: 0`) in a run where the same table had 11 rows a minute earlier (filed as OPEN-43). That is a stronger claim than "the steps were run by hand", and a weaker one than "CI is green": it proves the YAML executes and the pinned tools resolve, not that GitHub's image agrees. The gap is not hypothetical — running the file that way is what turned `lint` red, because ubuntu-latest ships shellcheck **0.9.0-1** while developers run **0.11.0**, and the two disagree about one line of `scripts/geo-db-bump.sh` (SC2015). Both halves are fixed: the script is an explicit `if`, and the version is pinned with a checksum in the workflow. ### What the runner actually did, run by run The remote is Gitea, not GitHub, and the runner is one shared machine that also serves other repositories — so a job here queues behind a job there, and the platform is not GitHub's `ubuntu-latest`. Every claim below is a job log, with the run number to read it at. | run | head | what it said | |---|---|---| | 2316 | `6f92d37` | first execution ever. `lint` red on two SC2086 findings in `scripts/smoke.sh`; `source` green (unit 377/377, integration 394/394, smoke 243/0); `image` and `console` died on `docker: command not found` — the job image ships no docker CLI even though `/var/run/docker.sock` is mounted from the host | | 2344–2346 | `4e303cd`, `1ada354` | the CLI, compose plugin and buildx are installed by the job. `image` then died on `not a directory: Are you trying to mount a directory onto a file`: the job's workspace is a **named volume** the host daemon cannot see, so a relative bind mount in `docker-compose.yml` is resolved on the host, where that path does not exist | | 2350 | `b402ec4` | `docker-compose.ci.yml` carries the nginx config through a named volume instead. The edge reached `healthy` and the gate's first admin call died with curl exit 7 — compose publishes the ports in the **host's** namespace, and the job has its own | | 2355, 2361 | `fb491a4`, `223b8d6` | the job reads its default-route gateway out of `/proc/net/route` (`ip` is not in the image). 2361: `lint` green, `source` red on one integration race, `image` 342/6, `console` 4 failures | | 2365 | `63cc575` | `lint` green, `image` **348/0**, `console` down to one failure, `source` still one race | | 2370 | `36d9338` | `lint`, `source` (378/378, 405/405, 256/0) and `image` (348/0) green; `console` printed `console check: all assertions passed` and the job went red on `actions/upload-artifact@v4` — not supported by this runner | | **2376** | `992a7b7` | **all four jobs green**: `lint` (actionlint 1.7.12, shellcheck 0.11.0), `source` (unit **378/378**, integration **405/405**, smoke **256/0**), `image` (`openwaf:ci` 258 MB, compose smoke **348/0**), `console` (**164 assertions, 0 failed**, screenshots 375,961 and 405,773 bytes named with their sha256 in the log) | | **2405** | `249e3f9` | **all four jobs green again**: `lint` now runs `./scripts/ci-gates.sh lint` — one definition, two callers — and prints actionlint 1.7.12 and shellcheck 0.11.0; `source` unit **378/378**, integration **405/405**, smoke **256/0**; `image` `openwaf:ci` 258 MB and compose smoke **356/0** (348 plus the eight assertions OPEN-45 and OPEN-49 asked for); `console` **164 assertions, 0 failed**, screenshots 375,596 and 405,547 bytes named with their sha256 | | **2413** | `cd5935b` | **all four jobs green**: `lint` actionlint 1.7.12 / shellcheck 0.11.0; `source` unit **378/378**, integration **405/405**, smoke **256/0**; `image` compose smoke **368/0**, the log carrying the read-side redirect guard on the shipped image (`info rewrote 1 stored row(s) for 203.0.113.248 to 'javascript:alert(1)'` → `301, Location https://www.iana.org/help/example-domains`, and a CRLF-bearing row answering 301 rather than 500) and the dead-edge scene naming its own cause (`curl answered 000 … the edge container reports exited/unhealthy`, then `running/healthy` again); `console` **168 assertions, 0 failed**, the page's 14 admin-api calls pinned by path and query string and none answered 404, screenshots 378,764 and 408,645 bytes with their sha256. The new `readme-counts` step ran in three jobs and agreed with the README in all three (368=368, 168=168, 256=256) | The ten red assertions 2361 reported across `image` and `console` were one cause, and it was in the workflow rather than in the product: the two "put the upstream config where the daemon can see it" steps were written as `run:` with no `|`, so YAML folded the whole block into **one line**, `set -eu VOL=… docker volume create …` set positional parameters instead of running anything, the named volume stayed empty — and Docker initialised it from the image. The upstream therefore ran nginx's stock default, `/boom` answered 404 instead of 502, and the 502 scene banned its own source at a threshold of 3 before its first assertion. Every failure downstream was that ban being read back. Making the steps block scalars turned `image` from 342/6 to 348/0 and `console` from 4 failures to 1, with no product change at all. The last three causes were the platform's, and each is now written into the file rather than remembered: the missing docker CLI, the workspace the daemon cannot see, and an artifact action the runner refuses. What is left is the suite's own races (OPEN-76, OPEN-47), which are the difference between a gate and a habit — 2361's single integration failure was one of them, and it withheld every item in the merge queue exactly as those items say it would. ## What this deliberately costs Stated, because a defence that hides its failure modes is not a defence. * **The request budget is counted per edge.** The counter is in the process, so N edges behind one load balancer allow N times the budget — the same shape the streak had before `SharedStreaks` (OPEN-52), and the same trade: sharing the count would cost a round trip on every request, not only the observed ones. What *is* shared is the consequence: the breach writes an engine ban, so the stop lands on every edge and survives a restart. * **The budget window is fixed, not sliding.** A sliding counter needs one entry per request, which is a map that grows at attack rate. The cost of a fixed window is the seam: a source can spend the budget at the end of one window and again at the start of the next, so the worst sustained rate is twice the limit across one boundary. `rateWindowSeconds` is the lever, not a smarter counter. * **One shared IPv4 egress is one source.** An office behind one address can accumulate a ban. Mitigations: the streak is *consecutive* (one honest click resets it), the allowlist outranks every pillar, and the ban explains itself so an operator can undo it in one call. * **IPv6 is grouped to `/64`.** A subscriber holds a whole `/64`, so a bot rotating addresses inside one allocation is one source; a per-address v6 rule is unenforceable. A wider prefix over-blocks, which is worse. * **The metrics are per edge, and there is no unauthenticated metrics port.** `openwaf_requests_total` counts what one process answered; the fleet number is the sum, which is what a PromQL query does anyway, and a shared counter would cost a round trip on every request. A separate unauthenticated port is a deployment decision this project does not make: the shipped image answers on the same surface as the admin API with the same token, so a scrape is a credentialed request. Per-source metrics are out for the same reason the project keeps no request log. * **The change log remembers decisions, not people.** It answers what changed, when and through which surface, and it stops there: one admin token means the edge cannot say which human wrote a rule, and a record that implied it would be a false one. Attribution needs identities the deployment does not have. * **The exported document is a capability, not a backup.** It carries the operator's decisions — every operator block, exemption, path rule, country decision and the policy that bounds them — and nothing about traffic: no observations, no alerts, no engine bans. So it rebuilds what an edge enforces, it does not restore what an edge knows, and it is only as secret as the admin token that reads it. Import is additive for the same reason: a document that could delete rows the operator never wrote would make a leak of the file worse than a leak of the file already is. It is also why the read-only token (OPEN-62) is refused on `/export` with a 403: the one surface where "can read" and "can take" are the same act is held to the admin token. * **The push queue is durable; the delivery is still not guaranteed.** What is owed is a row in `alert_pushes`, so a restart picks it up and two edges over one database claim a row before sending it — but the bound is attempts, not time. After `MaxPushAttempts` the row says `gave up after N attempts: …` and stops, because an endpoint that has refused for an hour is broken and the honest answer is to say so rather than keep asking. A process killed mid-delivery leaves its claim for up to 5 minutes, so a crash delays a delivery instead of losing one. At-least-once would need the receiver to deduplicate; nothing here promises that. The alert table stays the record of truth either way — a refused push never undoes an alert. * **Geo is a probabilistic claim about an address**, not a fact about a person. The 451 body says so. The database is pinned by a build argument and ages with the image, so `/healthz` reports its build date and `geoStale`. * **Streak state is per process by default, and that is measured, not assumed.** Round-robin over two edges multiplies the effective threshold by the instance count: four refusals from one address, two per edge, at a threshold of 3, produced no ban at all. A block issued by one edge is enforced by the other after up to `OpenWaf:State:RefreshTtlSeconds` (23.7 s measured at ~36 req/s). `OpenWaf:Policy:SharedStreaks=true` moves the counters into the database so the threshold is the fleet's, and it is what the last sentence of that finding costs: re-measured on this tree with two real edge processes on one SQLite file at a 5 s TTL, the third refusal landed at the edge that had seen only two, both edges then answered `consecutiveRefusals: 3` with `scope: shared-database`, and the edge that never saw a third refusal started enforcing the ban 4 s later. Numbers, method and caveats: `research/2026-10-01-multi-instance/RESULTS.md`. * **A push is at-most-once.** The alert is the record; the webhook is a copy of it. Three attempts and a short backoff, then the failure is counted and surfaced — `alertWebhookFailures`, `alertWebhookLastError` — and the push is not retried again, because a queue that survives a restart is a second system with its own outage story. Alerts raised while the process was down are never pushed at all. The table is what an operator reads; the push is what makes a 03:00 outage reach something that acts. * **An upgrade adds tables; it never changes one.** The startup step creates the tables a database predates, but it recognises a table by its name, so a migration that *alters* an existing table is not something it can perform or baseline honestly — that still needs a human decision, and the edge refuses to guess one rather than applying a migration whose effect it cannot check. The baseline rule is exact while this project's migrations only add tables, which both of the ones that exist do; the day one changes a column, the claim has to be made by hand. Reading a table that is there but unreadable is still reported rather than papered over: the snapshot refresh reads the rules in a statement of their own, so a `request_rules` that cannot be read costs the rules pillar and says so — `requestRulesAvailable` and `requestRulesError` on `/admin-api/state`, a NOT READ line over the rules table — instead of freezing the operator's block list, which is the failure this file keeps warning about. * **A browser gets a page, and the page is not the operator's.** The wording is ours, one template, fixed per verdict. An operator who wants their own brand and their own sentence on a block page cannot have one yet — the extension point is the reference, not the template. And the page never renders what the operator typed about a source, so a visitor learns the verdict and nothing else. * **A path rule is matched on every request.** The scan is a linear walk over the live rules, capped at 500 of them, and the pattern language is a glob rather than a regex so no pattern can backtrack exponentially against a path someone else chose. The cap is a request-path decision, not a UI one. * **Aggregates, not a request log.** `source_observations` keeps counters and the last-seen evidence per source, and ages out after `OpenWaf:Policy:ObservationRetentionDays` (default 7, 1–365). Raw IPs are not logged. ## Shape ``` dotnet/ OpenWaf.Domain/ pure decision core: source key, streak, ordered decision, refusal page OpenWaf.Infrastructure/ EF Core (sqlite/postgres), snapshot store, writers, MMDB geo, in-place schema upgrade OpenWaf.Edge/ the deployable: guard, observer, admin API, healthcheck mode OpenWaf.Tests.Unit/ 378 tests over the decision logic, the budget window, the refusal wording, the schema baseline and the durability counters OpenWaf.Tests.Integration/ 405 tests driving the real pipeline against a fake upstream scripts/smoke.sh 256 assertions against a running edge + a real upstream scripts/compose-smoke.sh 379 assertions against the built image (compose + nginx) scripts/console-check.cjs 168 assertions against the page, in a real Chromium scripts/geo-db-freshness.sh the pinned geo database vs the vendor (0/1/2) .github/workflows/ci.yml runs the gates on every push .github/workflows/geo-freshness.yml the same check on a schedule docs/ARCHITECTURE.md the design authority and its rulings ``` Two protections are inherited from the reference deployment rather than rediscovered, and both are load-bearing: at most **one durable write per source per 30 s**, and a **hard LRU bound** on the in-memory map, so a scanner farm cannot grow the process or tax the database.