Files
openwaf/docs/ARCHITECTURE.md
Pavlo Ratushnyi 1e0d11df1c
ci / build, test, smoke (push) Failing after 3m33s
ci / the same smoke on an image with no base (push) Successful in 8m10s
ci / lint the workflow and the shell (push) Failing after 19s
ci / the operator page in a real browser (push) Successful in 4m41s
ci / build the image and smoke it (push) Failing after 8m11s
the first query moves off ef, and the aot edge reads its own policy from the database
Wall 3 starts. Two projects, one query path, measured.

dotnet/OpenWaf.Data is the runtime: OrmContext (a DbDataSource plus an
ISqlDialect), Query<T>, RowReader, OrmMeta. It is typed over System.Data.Common
and carries no provider package; the driver is supplied at composition, which is
how the neighbouring deployment ships it too. Query<T> renders SQL by walking the
expression tree rather than compiling it — that is the exact difference from EF's
pipeline, and the reason it survives a NativeAOT link where EF does not. The
supported grammar is a closed set that refuses by name: joins, subqueries,
aggregates other than COUNT, updates, deletes, JSON columns and method calls each
raise UnsupportedQueryNodeException naming the node, because a renderer that
guesses is a renderer that ships wrong SQL.

dotnet/OpenWaf.Data.Generator is 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 inside a
[ModuleInitializer], so the question a NativeAOT binary cannot answer — what are
this type's properties — is never asked. The generated file is ordinary C#,
readable in obj/ and asserted against.

PolicySetting is the entity moved and EdgePolicyProvider.ReloadAsync the call
site, which was the first refusal in the probe log. Program.cs composes the
driver and dialect on the same Database:Provider switch EF uses, so one generated
query serves sqlite (the shipped image) and PostgreSQL (the migrations'
provider). EF still owns every write and every other read; the two layers
coexist on one composition root, which is what makes this incremental rather than
a rewrite.

Measured on the AOT binary, same probe, same window, before and after:
queries refused at run time 32 -> 18; EdgePolicyProvider reload failures 1 -> 0;
native binary 49,609,680 -> 49,676,016 bytes. The 18 that remain are named by
their own frames: 14 EdgeStateStore.RefreshAsync, 2 BlockStore.WriteBanAsync,
1 BlockStore.AddOperatorAsync, 1 admin endpoint.

The sqlite timestamp column turned out to be a contract, not a detail. The model
puts EF's DateTimeOffsetToBinaryConverter on every timestamp column, so every row
already written says (localTicks / 1000) * 2048 + (offsetMinutes & 2047); the
formula was derived by probing EF's converter and is now pinned by
SqliteTimestampEncodingTests against that converter over five instants including
+05:30, -05:00 and DateTimeOffset.MinValue — including the microsecond
truncation the /1000 imposes, which is EF's behaviour and is now a test rather
than a future surprise.

Two build traps, both paid for and both recorded where the next person will hit
them. -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; AOT is now switched by OpenWafAot=true, which only
OpenWaf.Edge.csproj turns into PublishAot — the same shape as the existing
OpenWafCompiledModel switch. And a raw Microsoft.Data.Sqlite data source needs
SQLitePCL.Batteries.Init() before its first open, because the order in which
EF's provider and this data source are first used is not guaranteed.

Gates on this tree: build 0 warnings, unit 391/391 (13 new: rendered SQL for both
dialects, null tests, the captured-null case, the refusals, the timestamp
encoding), integration 408/408, smoke 256/256, and the AOT probe above. One
earlier run of the 408 carried a single failure in AdminConsoleTests at a host
load average near 30 and the next run was clean; recorded rather than hidden, in
the same family as the load-sensitive compose gates this README already
documents.
2026-10-07 21:48:01 +02:00

293 lines
20 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# 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, and
re-measured on 2026-10-07. The build compiles — a **49,609,680-byte** native
arm64 binary, 10 IL warnings, 0 errors; the "48.8 MB" this entry used to carry
is a rounded figure no measured binary of this tree matches — and the edge
starts, creates its own schema from the DDL the binary carries **and serves**:
`Now listening on:`, `/healthz` 200, a proxied request 200, its own
`--healthcheck` mode exit 0. What it still cannot do is run a query. EF refuses
to compile a LINQ query at run time in a NativeAOT binary — **18 refusals in
the 2026-10-07 probe window, 32 before the first query moved off EF** (a window
count, not a total: the background refresh loop retries on its own clock) — 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:
* `Contains` over a captured collection — a `List<long>` local dies in
`SqlConstantExpression.Quote()` with `ArgumentException: 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 `ExecuteUpdateAsync` set-list — `NullReferenceException` in
`ExpressionTreeFuncletizer.VisitUnary`, reached from
`PrecompiledQueryCodeGenerator.ProcessCapturedVariables`, whether the value is
a cast literal or a nullable local;
* a literal whose type is not the column's — `p.AlertId >= 0` against a `long`
throws `ArgumentException: Argument types do not match` in
`CSharpToLinqTranslator.VisitLiteralExpression`; `0L` is 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 with `scripts/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.
The **packaging** half of NativeAOT is not the problem and is now measured:
`Dockerfile.aot-probe` publishes against musl (`linux-musl-*`,
`StaticExecutable=true`, `StaticOpenSslLinking=true`, `IlcSingleThreaded=true`)
and the result is one fully static binary — `file`: `static-pie linked`,
`readelf -l`: **0** program interpreters, `readelf -d`: **0** `NEEDED` shared
objects — a **96.4 MB** scratch image against 222 MB self-contained and 262 MB
chiseled.
**Ruling, 2026-10-06: every native dependency is baked into the link, and the
link is checked after it runs.** The sentence this entry used to carry — that
the binary dies in `SqliteConnection..cctor` with `DllNotFoundException:
e_sqlite3` — described a build that did not link sqlite. Two musl-only items in
`OpenWaf.Edge.csproj` close that wall: `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. Only the first is not enough: the binary then still calls
`NativeLibrary.Load("e_sqlite3")` at the first query and NativeAOT answers
`Dynamic loading not supported`. The pair is what the runtime pack itself uses
for `System.Native` and the OpenSSL shim (`Microsoft.NETCore.Native.Unix.targets`
140–155), so it is the SDK's mechanism, not a fork of it. Measured on the arm64
half: **58,343,456-byte** static-pie binary, 0 interpreters, 0 NEEDED, and a log
with **0** `e_sqlite3` lines that says the edge **created 12 tables** from the
DDL it carries. A standalone probe with the same link shows `Microsoft.Data.Sqlite`
opening a connection and reading `sqlite_version()` (3.53.4) back — so the ADO
layer survives and **only EF's query compilation is left**.
The check that sqlite is inside the binary is **behavioural**, and has to be:
the binary is stripped, and `nm` reports **0** `sqlite3_` symbols on a binary
that demonstrably runs sqlite. `nm` cannot answer this question; only the run
can. `.github/workflows/aot-probe.yml` now gates three things after the link —
no interpreter, no `NEEDED`, no `e_sqlite3` line — plus the positive half, the
schema line, because a gate that only forbids an error string also passes when
the feature is simply absent.
What were **two** walls on 2026-10-06 is **one**. The API wall came down on
2026-10-07: the edge reaches `Now listening on:` and serves, and
`scripts/aot-probe.sh` now gates exactly that — a `Now listening on:` line must
be in the log and no response may be refused for want of a compiled contract.
The **55** refusals standing between the first cut and a serving edge were
**one shape**: the anonymous 8-property `/healthz` literal, which is the
endpoint a scratch container's `HEALTHCHECK` asks — an edge serving traffic
while its own liveness probe called it dead. The **1** after that was
`Microsoft.AspNetCore.Mvc.ProblemDetails`, the body `Results.Problem` writes
and nobody's DTO here, whose cost was a `/readyz` 500 naming nothing where a
503 naming the failure is the truth. The query wall is what is left: 30
refusals in that window, and five query-backed assertions the probe now
**records** rather than checks — an operator block answers 503 where 204 is
right, the streak ban never forms, `/readyz` says 503 where 200 is right — each
printing `MOVED` the day EF compiles a query again. The `/readyz` 503 carries
the sentence now (`"detail":"Query wasn't precompiled and dynamic code isn't
supported with NativeAOT."`); with no contract for that body it was a 500
saying nothing.
**The API half, first cut (2026-10-07).** A source generator cannot describe an
anonymous type, and the edge's wire shapes were largely anonymous: **144
anonymous-object literals** in `OpenWaf.Edge`, **27 distinct shapes**, **111 of
them the single shape `new { error = … }`** (string-aware count, 2026-10-07;
the first pass reported 130 in 51 because it counted braces inside interpolated
strings as code). Those 111 are now one named record
(`ErrorDto`), and `Admin/EdgeJson.cs` is the edge's `JsonSerializerContext` —
**29 registered types** — 25 at the commit this entry first described, and the
"24" it and the README carried was stale the day it was written — with
`[JsonSourceGenerationOptions(PropertyNamingPolicy = CamelCase)]` because the
generated contract carries the property names and the whole API reads `error`,
not `Error`, registered at the head of the resolver chain in `Program.cs`.
**29 anonymous literals in 23 shapes remain**: **22 response
shapes**, and **7 inside an EF query's `Select`**, which are the query wall's
problem rather than this one. Two facts about the wiring are load-bearing and were
measured, not assumed: a non-empty `TypeInfoResolverChain` **replaces** the
reflection resolver rather than extending it (so an unregistered type breaks on
a JIT build too, with the same sentence the AOT probe reports), and naming
`DefaultJsonTypeInfoResolver` in an AOT publish drags the reflection-based JSON
stack into the native image — that publish ran **66 minutes without finishing**
against **232 s** without it, so the fallback is gated on
`RuntimeFeature.IsDynamicCodeCompiled` and is not in the shipped binary at all.
`AotJsonContractTests` reads the accepted body types off the live endpoint table
and demands a contract for each, so a new endpoint without one is red in the
suite rather than in next Monday's probe.
The query wall is the other half, and the shape that ships past both, in a
neighbouring deployment of the same runtime, has no EF Core at all: a Roslyn
source generator emits the queries — and the endpoints, and the OpenAPI
document — at build time over `System.Data.Common`, with the concrete driver
supplied at composition. That is the slice this entry points at (OPEN-79), and
the reason it is the *correct* step rather than the cheap one: it removes the
walls instead of routing around them.
**The first query moved (2026-10-07).** `dotnet/OpenWaf.Data` (a runtime typed
over `System.Data.Common`, no provider package in it) and
`dotnet/OpenWaf.Data.Generator` (a Roslyn incremental generator attached to
`OpenWaf.Infrastructure` as an analyzer) are that mechanism, first slice. The
generator emits, for a `[Table]` class, the column map, the row materializer and
an `OrmMeta.Register` call inside a `[ModuleInitializer]` — so the question a
NativeAOT binary cannot answer, "what are this type's properties", is never
asked. `Query<T>` renders SQL by **walking** the expression tree rather than
compiling it, which is the exact difference from EF's pipeline. The supported
grammar is a closed set that refuses by name — joins, subqueries, aggregates
other than `COUNT`, updates, deletes, JSON columns, method calls — because a
renderer that guesses is a renderer that ships wrong SQL.
Measured on the AOT binary with the same probe and the same window: query
refusals **32 → 18**, `EdgePolicyProvider: reload failed` **1 → 0**, binary
**49,609,680 → 49,676,016 bytes**. The 18 are named by their own frames: 14
`EdgeStateStore.RefreshAsync`, 2 `BlockStore.WriteBanAsync`, 1
`BlockStore.AddOperatorAsync`, 1 admin endpoint. EF still owns every write and
every other read; the two layers coexist on one composition root, which is what
makes the move incremental rather than a rewrite.
Two contracts this had to respect, both now asserted rather than assumed. The
sqlite timestamp column is EF's `DateTimeOffsetToBinaryConverter` — every row
already written says `(localTicks / 1000) * 2048 + (offsetMinutes & 2047)` — and
`SqliteTimestampEncodingTests` pins the dialect's read and write to EF's own
converter across five instants including a `+05:30` and `DateTimeOffset.MinValue`,
including the microsecond truncation that encoding imposes. And the dialect, not
the generated code, owns the provider differences: quoting, the paging tail
(`LIMIT -1 OFFSET n` on sqlite, `LIMIT 2147483647 OFFSET n` on PostgreSQL), bool
as INTEGER versus boolean, timestamp as integer versus `timestamptz`.
One build trap worth recording: **`-p:PublishAot` on the command line is a
global property**, so it reaches every project in the graph — including a
`netstandard2.0` analyzer — and the publish fails with `NETSDK1207`. AOT is now
switched by `OpenWafAot=true`, which only `OpenWaf.Edge.csproj` turns into
`PublishAot`, the same shape as the existing `OpenWafCompiledModel` switch.
* **Keying the ban on ip+UA** (as the analytics `SessionHash` does): 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.
1. **`ctx.RequestAborted` is 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.
2. **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 stay `timestamptz` on PostgreSQL.
3. **CIDR masking order matters.** Masking the partial octet after zeroing the
rest silently widens the prefix (`198.51.100.24/19` became `198.51.0.0`).
Caught by a unit test, not by review.
4. **An empty string in `appsettings.json` defeats 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.
5. **The configuration binder appends to a collection default** rather than
replacing it, so a non-empty default produced a duplicated redirect target.
6. **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
1. 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.
2. Geo enforced on a stale MMDB → partly fired and was handled. `/healthz`
reports `geoBuiltAt`/`geoStale`, `/admin-api/geo` reports the age, the console
shows which database the process is enforcing on, and `scripts/geo-db-freshness.sh`
plus `.github/workflows/geo-freshness.yml` compare the pin with what the vendor
serves. What the 90-day runtime alarm does **not** catch: a deployment one month
behind reports `geoStale: false` → measured, with the named volume holding
2026-09 while the Dockerfile pinned 2026-10, every other geo assertion still
green. `compose-smoke.sh` now asserts pin == loaded, and that is the assertion
which catches it.
3. 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 answered `consecutiveRefusals: 3` with `scope: 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
with `table "allow_entries" already exists`.
4. A need for a raw request log → the GDPR question the reference repo never
closed comes back with sharper edges.