Dockerfile.scratch builds the same program self-contained and puts it on scratch: 12 shared objects and the CA bundle — 18.7 MB — carried at their absolute paths, because a scratch layer has nothing to borrow them from, and the dynamic loader has to land at the path recorded inside the binary or the kernel refuses to start the process. Measured on one arm64 host: chiseled 262 MB, scratch 222 MB. scripts/compose-smoke.sh runs against it unchanged through docker-compose.scratch.yml: 368 passed, 0 failed, and 368/0 again when the same gate is called as scripts/ci-gates.sh scratch-smoke. The first scratch image built here is why that second run matters. 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 began 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 /boom's 502, which turned the "server errors alert, they never ban" 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." The schema-script gate was red on the runner at7c5e1ef(run 2462, exit 2): `dotnet tool restore` from the repo root finds no manifest, prints "No tools were restored." and exits 0, so the gate's own restore check passed vacuously and `dotnet ef` then died. It now restores dotnet/dotnet-tools.json by path and asks the tool for its version before trusting it. NativeAOT, measured further: with the two alert-queue queries taken out, `dotnet ef dbcontext optimize --precompile-queries` on EF 10.0.12 reports 0 precompilation errors and writes 8 interceptor files — 14 of whose declarations have dots in the identifier, because the local is named from the entity type's full name. The 4 refusals that remain are four shapes the generator cannot translate at all: Contains over a captured collection, any method parameter referenced inside a query (down to the CancellationToken), an ExecuteUpdate set-list, and a literal whose type is not the column's. docs/ARCHITECTURE.md carries the exception for each. No C# changed in this commit: the experiments that produced those numbers were reverted, and the query rewrites kept at7c5e1efare the ones that made 40 refusals into 4. Gates: scratch-image and scratch-smoke in scripts/ci-gates.sh and in `all`, and a fifth CI job that runs the 368 against the scratch image on the runner.
11 KiB
Architecture — openwaf
Canonical record: Lease Vibe work item OPEN-2, architecture_decision
4c9de3f6-ca26-4020-a16b-8f21e316c936 (v1, authored under a live claim). This
file is the repository-side copy; the tracker holds the versioned authority and
its audit history. Scope carried over from OPEN-1 (Canceled 2026-08-12),
whose BA analysis this builds on rather than repeats.
Decision
One decision point, three pillars, provenance-carrying blocks.
EdgeGuardMiddleware is the only component allowed to short-circuit. It reads
an immutable in-memory snapshot and evaluates, in a fixed order:
always-pass prefixes → allowlist → operator block → engine ban → geo policy
ResponseObservationMiddleware runs inside the guard, awaits the upstream,
classifies the status, and is the only thing that can create an engine ban.
Rulings on the open questions OPEN-1 left
| Q | Ruling | Why |
|---|---|---|
| Q1 — does M bound the streak or the ban? | Both, as two parameters. StreakWindow bounds the streak; BanDuration is separate. |
"N раз підряд на M хвилин" reads both ways; dropping one loses a knob the operator needs. |
Q2 — > 400 or >= 400? |
Inclusive of 400 (400-499). |
A malformed-body probe answers 400 and must count. |
| Q3 — do 5xx count? | Never a ban; always an alert. | A broken deploy makes every honest client draw consecutive 5xx; the first bad release would ban the site's own visitors. |
| Q4 — what is the source key? | Normalised IP: IPv4 as-is, IPv6 grouped to /64, IPv4-mapped v6 collapsed. Allowlist matches the raw address instead. |
A bot rotating inside one v6 allocation is one source; an operator writing a CIDR should mean exactly that. |
| Q5 — one block table or two? | One table, Source provenance column. |
Manual and automatic coexist permanently; clearing one kind must never touch the other, and the admin UI should not have to know about two tables. |
| Q6 — does the 301 survive for automatic bans? | No: engine bans answer 403 + Retry-After; operator blocks keep 301. A per-entry RedirectTo overrides both. |
A 301 is a good answer to a scanner and a baffling one to a customer whose office IP was caught. |
| Q7 — allowlist and override | Allowlist outranks every pillar and survives the toggle; the always-pass prefixes are the self-recovery hatch. | A ban with no exemption path eventually blocks someone who matters at the worst moment. |
| Q8 — retention | Aggregates only, aged out by a worker (ObservationRetention, BanRetention). |
The reference repo left raw-IP TTL unresolved; storing no request log makes the question smaller. |
Why not the alternatives
-
Three independent middlewares (what the reference repo does today): precedence becomes registration order, and an allowlisted operator in a denied country gets whichever guard runs first.
-
Two block tables: makes "clear engine bans" a table operation and invites a future merge that loses data.
-
NativeAOT: relitigated here on 2026-10-06 and measured, not inherited. The build compiles (48.8 MB native arm64 binary, 10 IL warnings, 0 errors) and the edge starts and creates its own schema from the DDL the binary carries — but it never serves: EF refuses to compile a LINQ query at run time in a NativeAOT binary, and the only alternative,
dotnet ef dbcontext optimize --precompile-queries, first refused 40 of this tree's queries (parameter-symbol roots and captures, dotnet/efcore#35887 / #38030 / #35494, fixed only in the 12.0-preview1 line). Four refusals remain, and they are not a style to rewrite around — they are four shapes the 10.0.12 generator cannot translate at all, each measured with its own exception:Containsover a captured collection — aList<long>local dies inSqlConstantExpression.Quote()withArgumentException: Argument types do not match; an array is worse,Expression of type 'System.Int64[]' cannot be used for parameter of type 'System.ReadOnlySpan\1[System.Int64]'`;- any method parameter referenced inside a query, down to the
CancellationToken—UnreachableException: IdentifierName of type ParameterSymbol: token. Only locals declared in the querying method work; - an
ExecuteUpdateAsyncset-list —NullReferenceExceptioninExpressionTreeFuncletizer.VisitUnary, reached fromPrecompiledQueryCodeGenerator.ProcessCapturedVariables, whether the value is a cast literal or a nullable local; - a literal whose type is not the column's —
p.AlertId >= 0against alongthrowsArgumentException: Argument types do not matchinCSharpToLinqTranslator.VisitLiteralExpression;0Lis accepted.
With those two alert-queue queries taken out the generator reports 0 precompilation errors and writes 8 interceptor files — and 14 of their declarations have dots in the identifier (
var openWaf.Domain.Security.BlockEntryPrimaryKeyProperties = …), because the local is named from the entity type's full name: 28 CS1002 and CS1003 errors, one pair per entity materialisation in the model. So the wall is EF's precompiler and its code generator, twice over, not this tree's code. Reproduce the runtime half withscripts/aot-probe.sh. The query rewrites that attempt required are kept: they are behaviour-identical (378 unit, 405 integration, 256 smoke at the same commit) and they are the precondition for trying again when EF's precompiler is fixed. -
Keying the ban on ip+UA (as the analytics
SessionHashdoes): a bot that varies its UA multiplies into many sources and never reaches the threshold. -
Banning on 5xx because the original wording said
> 400: turns an outage into a second, self-inflicted outage.
Properties the tests hold
- A ban never feeds its own streak — the guard refuses before the observer runs.
- The admin surface is never observed either: an operator's syntax error in an admin call must not lock them out.
- Memory is bounded (
MaxTrackedSources, LRU + idle TTL); the request path never touches the database; a stale snapshot is served while one background refresh runs; a failed refresh keeps the previous snapshot (fail closed for blocks, fail open for geo). - Durable writes are coalesced to one per source per
ObservationWriteInterval. - Ban writes are serialised in-process: the observer runs after the response is written, so the next request can arrive while the ban is still landing.
What building it taught us about the design
Recorded because they are the places a reader will otherwise step in again.
ctx.RequestAbortedis the wrong token for post-response work. The ban write was silently cancelled: the client had already hung up, so the request that proved the source abusive was the one that failed to record it.- SQLite cannot compare a
DateTimeOffset— the provider stores it as text and refuses the query at translation time, which kills every "is this ban still live" and "has this row aged out" predicate. Timestamps are stored as integers on SQLite and staytimestamptzon PostgreSQL. - CIDR masking order matters. Masking the partial octet after zeroing the
rest silently widens the prefix (
198.51.100.24/19became198.51.0.0). Caught by a unit test, not by review. - An empty string in
appsettings.jsondefeats the environment fallback (??does not fire on""), which is how a geo database and an admin token go missing in a deployment that looks configured. - The configuration binder appends to a collection default rather than replacing it, so a non-empty default produced a duplicated redirect target.
- Two requests finishing together both saw "no ban yet" and raced into the unique index; the loser's evidence was lost. Now serialised behind a gate.
Evolution triggers
- A shared-egress IPv4 (carrier NAT, office, campus) banned by honest traffic → the per-address v4 key is wrong and keying must move to session or connection.
- Geo enforced on a stale MMDB → partly fired and was handled.
/healthzreportsgeoBuiltAt/geoStale,/admin-api/georeports the age, the console shows which database the process is enforcing on, andscripts/geo-db-freshness.shplus.github/workflows/geo-freshness.ymlcompare the pin with what the vendor serves. What the 90-day runtime alarm does not catch: a deployment one month behind reportsgeoStale: false→ measured, with the named volume holding 2026-09 while the Dockerfile pinned 2026-10, every other geo assertion still green.compose-smoke.shnow asserts pin == loaded, and that is the assertion which catches it. - Multi-instance edge → measured on
research/2026-10-01-multi-instance/, not guessed. Three findings, the first two reproduced twice:- The streak is the problem, and it is not lag. Round-robin over two edges multiplies the effective streak threshold by the instance count: four refusals split 2+2 at threshold 3 produced no ban anywhere (D1).
- Propagation is TTL-bound, and the TTL is now a setting rather than a
rebuild. 23.1 s at the default 30 s under ~28 req/s (D4, reproducing the
23.7 s of D3), 3.4 s at
OpenWaf:State:RefreshTtlSeconds=5→ a 6.9x cut, with no measurable change on the request path (p50 1.75 to 1.93 ms, p95 3.15 to 2.78 ms at n=200; the two move in opposite directions, so the honest reading is "inside noise", not "cheaper"). - Alerting is per process as well. One upstream outage seen by one edge wrote
2 alert rows (counts 3 and 6); the same outage seen by both edges wrote 4
(3, 3, 6, 6) → the single-process answer, twice, with identical
counts per process. Before the edge-trigger fix the same two phases wrote 8
and 16 (D5). So the per-request growth is gone and the per-instance
duplication is not, because both are decided by a counter that lives in the
process.
The block list is already shared through the database; the streak map is not
by default.
OpenWaf:Policy:SharedStreaks=true(OPEN-52) moves the map onto a database row, so the threshold is the fleet's; it costs a round trip per observed response on a path whose measured p95 is ~3 ms, plus an optimistic-concurrency retry when two edges touch one source at the same moment. Re-measured on the tree that shipped it, two edge processes on one SQLite file at a 5 s TTL: the third refusal arrived at the edge that had seen two, both answeredconsecutiveRefusals: 3withscope: shared-database, and the second edge enforced the ban 4 s later. The same run is what found the schema race — two edges creating the schema at once used to kill the loser withtable "allow_entries" already exists.
- A need for a raw request log → the GDPR question the reference repo never closed comes back with sharper edges.