diff --git a/README.md b/README.md index 1af8e0d..f2b4d64 100644 --- a/README.md +++ b/README.md @@ -174,17 +174,20 @@ 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`. -Three 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; the other two -decide how long the data behind the privacy promise sits in storage, and are +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: +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. | Database: `Database:Provider` = `sqlite` (default) or `postgres`, `ConnectionStrings__OpenWaf`. GeoIP: `GEOIP_MAXMIND_DB_PATH`. @@ -815,7 +818,7 @@ 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-04 with the retention window as configuration: build 0 warnings / 0 errors, unit **132/132**, -integration **185/185 in 19 s**, console **78 assertions, 0 failed**, smoke +integration **191/191 in 32 s**, console **78 assertions, 0 failed**, smoke **passed 28, failed 0**. Carried from the 2026-10-02 run and not re-measured since: compose **209 passed, 0 failed**, image 261 MB, 0 containers left behind, enforcement lag 33 ms (`/tmp/c26_build.log`, `/tmp/c26_unit.log`, @@ -826,7 +829,7 @@ 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 **185/185 in 19 s**, and the same tree +the default parallel scheduling answered **191/191 in 32 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 @@ -971,13 +974,18 @@ Stated, because a defence that hides its failure modes is not a defence. * **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, 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). The block - list is already shared through the database; the streak map is not. Numbers, - method and caveats: `research/2026-10-01-multi-instance/RESULTS.md`. +* **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`. * **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 diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 3352fd8..1980572 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -113,8 +113,16 @@ Recorded because they are the places a reader will otherwise step in again. 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. - Move the streak map when the threshold has to be exact behind a load balancer - — it costs a round trip on a path whose measured p95 is ~3 ms. + 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. diff --git a/dotnet/OpenWaf.Domain/Engine/IStreakTracker.cs b/dotnet/OpenWaf.Domain/Engine/IStreakTracker.cs new file mode 100644 index 0000000..776bf3f --- /dev/null +++ b/dotnet/OpenWaf.Domain/Engine/IStreakTracker.cs @@ -0,0 +1,47 @@ +using OpenWaf.Domain.Policy; + +namespace OpenWaf.Domain.Engine; + +/// +/// The streak store the edge talks to. Two implementations exist and the +/// deployment chooses one at startup, because the choice is about where the +/// counters live, not about what a streak means: +/// +/// * — the in-process map. No I/O on the request +/// path, and a threshold counted per instance: measured in +/// research/2026-10-01-multi-instance/, four refusals split 2+2 over +/// two edges at a threshold of 3 produced no ban anywhere. +/// * SharedStreakTracker (Infrastructure) — the same rules applied to a +/// row in the database, so N edges mature one streak. Costs a round trip on +/// a path whose measured p95 is ~3 ms. +/// +/// Both call and nothing else, so the two +/// answers cannot drift apart on what counts as consecutive. +/// +public interface IStreakTracker +{ + StreakOutcome Observe( + string sourceKey, int statusCode, ResponseClass responseClass, + EdgePolicy policy, DateTimeOffset now, RequestEvidence? evidence = null); + + IReadOnlyList Snapshot(DateTimeOffset now, EdgePolicy policy); + + StreakSnapshot? Peek(string sourceKey); + + IReadOnlyList LiveStreaks(DateTimeOffset now, EdgePolicy policy, int limit); + + IReadOnlyList LiveStreaks( + DateTimeOffset now, EdgePolicy policy, int limit, int offset, out int standingTotal); + + IReadOnlyList LiveStreaks( + DateTimeOffset now, EdgePolicy policy, int limit, int offset, string? sourceKey, + out int standingTotal); + + int TrackedCount { get; } + + void ResetIfTracked(string sourceKey); + + void Forget(string sourceKey); + + void Configure(EdgePolicy policy); +} diff --git a/dotnet/OpenWaf.Domain/Engine/StreakRules.cs b/dotnet/OpenWaf.Domain/Engine/StreakRules.cs new file mode 100644 index 0000000..f79f6f8 --- /dev/null +++ b/dotnet/OpenWaf.Domain/Engine/StreakRules.cs @@ -0,0 +1,120 @@ +using OpenWaf.Domain.Policy; + +namespace OpenWaf.Domain.Engine; + +/// +/// The streak semantics, in one function, so there is exactly one copy of them. +/// +/// Both streak stores apply this and nothing else: the in-process map +/// () and the shared, database-backed one that makes +/// the threshold mean the same thing on every instance behind a load balancer. +/// Two copies of these rules is how a deployment ends up with a threshold that +/// counts one way on one edge and another way on the next — which is the exact +/// failure the shared store exists to remove, reintroduced one level down. +/// +public static class StreakRules +{ + /// + /// Streak semantics (Q1): a refusal counts toward the current streak only if + /// it lands within of the previous + /// refusal; otherwise the streak restarts at 1. A neutral response + /// (2xx/3xx) resets the refusal streak to zero — that is what "consecutive" + /// means, and it is what keeps a shared-egress office from accumulating a + /// ban across a whole working day. + /// + public static StreakOutcome Apply( + StreakState state, + int statusCode, + ResponseClass responseClass, + EdgePolicy policy, + DateTimeOffset now, + RequestEvidence? evidence = null) + { + state.LastSeenAt = now; + state.LastStatusCode = statusCode; + if (evidence is not null) state.Apply(evidence.Value); + + switch (responseClass) + { + case ResponseClass.Refusal: + var withinWindow = state.LastRefusalAt is not null + && now - state.LastRefusalAt.Value <= policy.StreakWindow; + if (!withinWindow) state.LastAlertedRefusals = 0; + state.ConsecutiveRefusals = withinWindow ? state.ConsecutiveRefusals + 1 : 1; + state.LastRefusalAt = now; + state.TotalRefusals++; + if (state.ConsecutiveRefusals > state.MaxConsecutiveRefusals) + state.MaxConsecutiveRefusals = state.ConsecutiveRefusals; + // A refusal ends the server-error run, and with it the + // episode: without this, a source that alternates 5xx with + // 4xx keeps the "already alerted at 12" mark while its + // error count restarts at 1, and the next outage is silent + // until the count doubles the old mark. + state.LastAlertedServerErrors = 0; + state.ConsecutiveServerErrors = 0; + break; + + case ResponseClass.ServerError: + var withinErrorWindow = state.LastRefusalAt is not null + && now - state.LastRefusalAt.Value <= policy.StreakWindow; + if (!withinErrorWindow) state.LastAlertedServerErrors = 0; + state.ConsecutiveServerErrors = withinErrorWindow ? state.ConsecutiveServerErrors + 1 : 1; + state.LastRefusalAt = now; + if (state.ConsecutiveServerErrors > state.MaxConsecutiveServerErrors) + state.MaxConsecutiveServerErrors = state.ConsecutiveServerErrors; + // A server error is not a clean answer either, so it does + // not reset the refusal streak; it just does not extend it. + break; + + default: + state.ConsecutiveRefusals = 0; + state.ConsecutiveServerErrors = 0; + // A clean answer ends the episode, so the next one is + // allowed (and expected) to raise its own alert. + state.LastAlertedRefusals = 0; + state.LastAlertedServerErrors = 0; + break; + } + + var ban = responseClass == ResponseClass.Refusal + && state.ConsecutiveRefusals >= policy.StreakThreshold; + + // Both alerts are edge-triggered. They used to be level-triggered, + // which wrote one alert row per request for as long as the + // condition lasted, and neither condition ends on its own: a 5xx + // never bans, and in Observe mode nothing bans at all, so the + // source stays observable on every request. At N=3 a source + // hammering a broken upstream for 10,000 requests cost 9,998 alert + // rows, kept for the whole retention window, and the operator's + // alert list (newest 100) was one source deep. Silencing alone + // would be worse, because an alert that fires once and never again + // hides a problem that got ten times worse since. So: speak on the + // crossing, then again on every doubling. + var alert = false; + var banAlertDue = false; + if (responseClass == ResponseClass.ServerError + && state.ConsecutiveServerErrors >= policy.StreakThreshold) + { + alert = IsEscalation(state.LastAlertedServerErrors, state.ConsecutiveServerErrors); + if (alert) state.LastAlertedServerErrors = state.ConsecutiveServerErrors; + } + else if (ban) + { + banAlertDue = IsEscalation(state.LastAlertedRefusals, state.ConsecutiveRefusals); + if (banAlertDue) state.LastAlertedRefusals = state.ConsecutiveRefusals; + } + + return new StreakOutcome( + state.ConsecutiveRefusals, state.ConsecutiveServerErrors, ban, alert, banAlertDue); + } + + /// + /// Whether a count deserves a fresh alert row. Zero means this episode has + /// not alerted yet, so the crossing always speaks; after that only a + /// doubling does. A storm of S responses therefore costs O(log S) rows + /// instead of S, and the rows that do exist still say the useful thing: + /// the count is climbing and nobody has acted. + /// + public static bool IsEscalation(int lastAlerted, int current) + => lastAlerted == 0 || current >= lastAlerted * 2; +} diff --git a/dotnet/OpenWaf.Domain/Engine/StreakState.cs b/dotnet/OpenWaf.Domain/Engine/StreakState.cs index 94cc0b9..8b07e09 100644 --- a/dotnet/OpenWaf.Domain/Engine/StreakState.cs +++ b/dotnet/OpenWaf.Domain/Engine/StreakState.cs @@ -21,7 +21,7 @@ public sealed class StreakState /// episode. 0 means "no alert yet", which is what makes the crossing /// itself always speak. Reset when the episode ends (a clean answer, or a /// gap longer than the window), so the next episode gets its own alert. - /// See StreakTracker.IsEscalation for what counts as escalation. + /// See StreakRules.IsEscalation for what counts as escalation. public int LastAlertedRefusals; public int LastAlertedServerErrors; diff --git a/dotnet/OpenWaf.Domain/Engine/StreakTracker.cs b/dotnet/OpenWaf.Domain/Engine/StreakTracker.cs index ac47491..45b6a37 100644 --- a/dotnet/OpenWaf.Domain/Engine/StreakTracker.cs +++ b/dotnet/OpenWaf.Domain/Engine/StreakTracker.cs @@ -23,7 +23,7 @@ namespace OpenWaf.Domain.Engine; /// what keeps a shared-egress office from accumulating a ban across a whole /// working day. /// -public sealed class StreakTracker +public sealed class StreakTracker : IStreakTracker { private readonly object _gate = new(); private readonly Dictionary _states = new(StringComparer.Ordinal); @@ -43,95 +43,13 @@ public sealed class StreakTracker { var state = GetOrCreate(sourceKey, now); Touch(state); - state.LastSeenAt = now; - state.LastStatusCode = statusCode; - if (evidence is not null) state.Apply(evidence.Value); - - switch (responseClass) - { - case ResponseClass.Refusal: - var withinWindow = state.LastRefusalAt is not null - && now - state.LastRefusalAt.Value <= policy.StreakWindow; - if (!withinWindow) state.LastAlertedRefusals = 0; - state.ConsecutiveRefusals = withinWindow ? state.ConsecutiveRefusals + 1 : 1; - state.LastRefusalAt = now; - state.TotalRefusals++; - if (state.ConsecutiveRefusals > state.MaxConsecutiveRefusals) - state.MaxConsecutiveRefusals = state.ConsecutiveRefusals; - // A refusal ends the server-error run, and with it the - // episode: without this, a source that alternates 5xx with - // 4xx keeps the "already alerted at 12" mark while its - // error count restarts at 1, and the next outage is silent - // until the count doubles the old mark. - state.LastAlertedServerErrors = 0; - state.ConsecutiveServerErrors = 0; - break; - - case ResponseClass.ServerError: - var withinErrorWindow = state.LastRefusalAt is not null - && now - state.LastRefusalAt.Value <= policy.StreakWindow; - if (!withinErrorWindow) state.LastAlertedServerErrors = 0; - state.ConsecutiveServerErrors = withinErrorWindow ? state.ConsecutiveServerErrors + 1 : 1; - state.LastRefusalAt = now; - if (state.ConsecutiveServerErrors > state.MaxConsecutiveServerErrors) - state.MaxConsecutiveServerErrors = state.ConsecutiveServerErrors; - // A server error is not a clean answer either, so it does - // not reset the refusal streak; it just does not extend it. - break; - - default: - state.ConsecutiveRefusals = 0; - state.ConsecutiveServerErrors = 0; - // A clean answer ends the episode, so the next one is - // allowed (and expected) to raise its own alert. - state.LastAlertedRefusals = 0; - state.LastAlertedServerErrors = 0; - break; - } - - var ban = responseClass == ResponseClass.Refusal - && state.ConsecutiveRefusals >= policy.StreakThreshold; - - // Both alerts are edge-triggered. They used to be level-triggered, - // which wrote one alert row per request for as long as the - // condition lasted, and neither condition ends on its own: a 5xx - // never bans, and in Observe mode nothing bans at all, so the - // source stays observable on every request. At N=3 a source - // hammering a broken upstream for 10,000 requests cost 9,998 alert - // rows, kept for the whole retention window, and the operator's - // alert list (newest 100) was one source deep. Silencing alone - // would be worse, because an alert that fires once and never again - // hides a problem that got ten times worse since. So: speak on the - // crossing, then again on every doubling. - var alert = false; - var banAlertDue = false; - if (responseClass == ResponseClass.ServerError - && state.ConsecutiveServerErrors >= policy.StreakThreshold) - { - alert = IsEscalation(state.LastAlertedServerErrors, state.ConsecutiveServerErrors); - if (alert) state.LastAlertedServerErrors = state.ConsecutiveServerErrors; - } - else if (ban) - { - banAlertDue = IsEscalation(state.LastAlertedRefusals, state.ConsecutiveRefusals); - if (banAlertDue) state.LastAlertedRefusals = state.ConsecutiveRefusals; - } - - return new StreakOutcome( - state.ConsecutiveRefusals, state.ConsecutiveServerErrors, ban, alert, banAlertDue); + // The rules themselves live in one place, because the shared + // streak store (OPEN-52) has to apply exactly these and not a + // second copy of them. + return StreakRules.Apply(state, statusCode, responseClass, policy, now, evidence); } } - /// - /// Whether a count deserves a fresh alert row. Zero means this episode has - /// not alerted yet, so the crossing always speaks; after that only a - /// doubling does. A storm of S responses therefore costs O(log S) rows - /// instead of S, and the rows that do exist still say the useful thing: - /// the count is climbing and nobody has acted. - /// - private static bool IsEscalation(int lastAlerted, int current) - => lastAlerted == 0 || current >= lastAlerted * 2; - /// Snapshot for the durable writer. Copies rather than hands out /// live objects, so the writer never reads half-updated state. public IReadOnlyList Snapshot(DateTimeOffset now, EdgePolicy policy) diff --git a/dotnet/OpenWaf.Domain/Policy/EdgePolicy.cs b/dotnet/OpenWaf.Domain/Policy/EdgePolicy.cs index c1e7fa1..5b41001 100644 --- a/dotnet/OpenWaf.Domain/Policy/EdgePolicy.cs +++ b/dotnet/OpenWaf.Domain/Policy/EdgePolicy.cs @@ -49,6 +49,16 @@ public sealed record EdgePolicy /// A source state nobody has touched for this long is evicted. public TimeSpan StateIdleTtl { get; init; } = TimeSpan.FromHours(2); + /// Where the streak counters live (OPEN-52). False — the default — + /// is the in-process map: no I/O on the request path, and a threshold that + /// is per instance (measured: 2+2 over two edges at a threshold of 3 banned + /// nobody). True moves the same rules to a database row, so N edges mature + /// one streak, at the cost of a round trip per observed response. + /// Startup-time only: it decides which store the process registers, and a + /// policy that changed underneath a running process would leave the streaks + /// in the store the old setting chose. + public bool SharedStreaks { get; init; } + /// How long a ban's evidence row survives after it stops being live. public TimeSpan BanRetention { get; init; } = TimeSpan.FromDays(7); diff --git a/dotnet/OpenWaf.Domain/Security/SourceStreak.cs b/dotnet/OpenWaf.Domain/Security/SourceStreak.cs new file mode 100644 index 0000000..dfb0abb --- /dev/null +++ b/dotnet/OpenWaf.Domain/Security/SourceStreak.cs @@ -0,0 +1,53 @@ +namespace OpenWaf.Domain.Security; + +/// +/// The streak counters for one source, held in the database instead of in one +/// process's memory (OPEN-52). +/// +/// This is what makes a threshold of 3 mean three refusals across a fleet. +/// Measured in research/2026-10-01-multi-instance/: four refusals from +/// one address, two per edge, at a threshold of 3, produced no ban anywhere — +/// each edge was counting its own map. The block list was already shared +/// through the database; the streak map was the half that was not. +/// +/// One row per source key, upserted rather than appended — the same shape that +/// keeps a scanner farm from turning the edge into an append-only log. The row +/// ages out on : idle rows are dropped when they are +/// read past and pruned by the retention +/// worker, so the table is bounded by traffic, not by how long the process runs. +/// +public sealed class SourceStreak +{ + public string SourceKey { get; init; } = string.Empty; + + public int ConsecutiveRefusals { get; set; } + public int MaxConsecutiveRefusals { get; set; } + public int TotalRefusals { get; set; } + public int ConsecutiveServerErrors { get; set; } + public int MaxConsecutiveServerErrors { get; set; } + + /// The count the last alert of each kind was raised at, for this + /// episode — the field that makes the alerts edge-triggered rather than + /// per-request. Shared, so two edges do not each raise their own first + /// alert for one outage. + public int LastAlertedRefusals { get; set; } + public int LastAlertedServerErrors { get; set; } + + public DateTimeOffset? LastRefusalAt { get; set; } + public DateTimeOffset LastSeenAt { get; set; } = DateTimeOffset.UtcNow; + + public int? LastStatusCode { get; set; } + public string? LastPath { get; set; } + public string? LastUserAgent { get; set; } + public string? LastCountryCode { get; set; } + public string? LastCity { get; set; } + public string? LastRegion { get; set; } + + /// Optimistic concurrency. Two edges reading the same row and both + /// writing is the normal case behind a load balancer, not a corner: without + /// this, the second write silently drops the first edge's refusal and the + /// threshold is wrong again — the exact bug this table exists to fix. The + /// loser gets DbUpdateConcurrencyException and re-applies the rules + /// against the winner's row. + public int Version { get; set; } +} diff --git a/dotnet/OpenWaf.Edge/Admin/AdminConsole.cs b/dotnet/OpenWaf.Edge/Admin/AdminConsole.cs index 2033dad..51db186 100644 --- a/dotnet/OpenWaf.Edge/Admin/AdminConsole.cs +++ b/dotnet/OpenWaf.Edge/Admin/AdminConsole.cs @@ -386,8 +386,14 @@ async function load() { // FILTERED count while trackedSources stays the whole map, and that pair is // the honest reading of "one of these many". el('streaknote').textContent = - streaks.scope !== 'this-process' ? 'unknown scope' - : 'this edge process only — ' + streaks.scope !== 'this-process' && streaks.scope !== 'shared-database' ? 'unknown scope' + : (streaks.scope === 'shared-database' + // The streaks in this table were counted by every edge sharing the + // database, not only by the one serving this page (OPEN-52). Saying + // "this edge process only" here would understate what the operator + // is looking at. + ? 'shared across every edge on this database — ' + : 'this edge process only — ') + (obsSource ? (Number(streaks.standingStreaks) === 0 ? 'filtered to ' + obsSource + ': nothing standing for this source' diff --git a/dotnet/OpenWaf.Edge/Admin/AdminEndpoints.cs b/dotnet/OpenWaf.Edge/Admin/AdminEndpoints.cs index 1b401cb..2569d6d 100644 --- a/dotnet/OpenWaf.Edge/Admin/AdminEndpoints.cs +++ b/dotnet/OpenWaf.Edge/Admin/AdminEndpoints.cs @@ -328,7 +328,7 @@ internal static class AdminEndpoints // measured what that assumption costs: round-robin over two edges // multiplied the effective threshold, and four refusals split 2+2 at a // threshold of 3 produced no ban at all. - group.MapGet("/streaks", (StreakTracker tracker, EdgePolicyProvider policyProvider, HttpContext ctx, int? limit, int? offset, string? source) => + group.MapGet("/streaks", (IStreakTracker tracker, EdgePolicyProvider policyProvider, HttpContext ctx, int? limit, int? offset, string? source) => { if (!TryKnownQuery(ctx, out var unknown, "limit", "offset", "source")) return Results.BadRequest(new { error = unknown }); var now = DateTimeOffset.UtcNow; @@ -354,7 +354,11 @@ internal static class AdminEndpoints ctx.Response.Headers["X-Truncated"] = (skip + streaks.Count < standing).ToString().ToLowerInvariant(); return Results.Ok(new { - scope = "this-process", + // Which store this answer came from, in the answer itself. With the + // shared map the counts are the fleet's, and a page that still said + // "this-process" would be describing a different edge than the one it + // is talking to. + scope = policy.SharedStreaks ? "shared-database" : "this-process", threshold = policy.StreakThreshold, windowMinutes = policy.StreakWindow.TotalMinutes, trackedSources = tracker.TrackedCount, @@ -467,7 +471,7 @@ internal static class AdminEndpoints }); }); - group.MapGet("/state", (EdgeStateStore state, EdgePolicyProvider policyProvider, StreakTracker tracker, DurabilityHealth durability, BlockStore blockStore, HttpContext ctx) => + group.MapGet("/state", (EdgeStateStore state, EdgePolicyProvider policyProvider, IStreakTracker tracker, DurabilityHealth durability, BlockStore blockStore, HttpContext ctx) => { if (!TryKnownQuery(ctx, out var unknown)) return Results.BadRequest(new { error = unknown }); var now = DateTimeOffset.UtcNow; @@ -549,6 +553,9 @@ internal static class AdminEndpoints // The window itself, next to the counter that says whether it is // running. "Nothing was pruned" and "nothing is due for 300 days" // look identical without the number the promise is measured against. + // Which streak store this process registered, so the counts beside + // it can be read as one edge's or the fleet's (OPEN-52). + streakScope = policyProvider.Current.SharedStreaks ? "shared-database" : "this-process", observationRetentionDays = (int)state.Current.Policy.ObservationRetention.TotalDays, banRetentionDays = (int)state.Current.Policy.BanRetention.TotalDays, mode = state.Current.Policy.Mode.ToString() diff --git a/dotnet/OpenWaf.Edge/Configuration/EdgePolicyOptions.cs b/dotnet/OpenWaf.Edge/Configuration/EdgePolicyOptions.cs index fa275be..5558af1 100644 --- a/dotnet/OpenWaf.Edge/Configuration/EdgePolicyOptions.cs +++ b/dotnet/OpenWaf.Edge/Configuration/EdgePolicyOptions.cs @@ -25,6 +25,12 @@ internal sealed class EdgePolicyOptions public int Ipv6KeyPrefixLength { get; set; } = 64; public int EngineBlockStatus { get; set; } = 403; public int OperatorBlockStatus { get; set; } = 301; + + // Where the streak counters live. Not a runtime knob: it selects which + // store the process registers at startup, so changing it is a redeploy. + // Off by default — the in-process map costs nothing on the request path, + // and a single-edge deployment loses nothing by it. + public bool SharedStreaks { get; set; } // Empty by default: the configuration binder appends to an existing // collection rather than replacing it, so a non-empty default here would // leave a duplicate target in every deployment. @@ -63,6 +69,7 @@ internal sealed class EdgePolicyOptions Ipv6KeyPrefixLength = Ipv6KeyPrefixLength, EngineBlockStatus = EngineBlockStatus, OperatorBlockStatus = OperatorBlockStatus, + SharedStreaks = SharedStreaks, DefaultRedirectTargets = DefaultRedirectTargets.Length == 0 ? new[] { "https://www.iana.org/help/example-domains" } : DefaultRedirectTargets, diff --git a/dotnet/OpenWaf.Edge/Pipeline/ResponseObservationMiddleware.cs b/dotnet/OpenWaf.Edge/Pipeline/ResponseObservationMiddleware.cs index 234326e..9b9c9b0 100644 --- a/dotnet/OpenWaf.Edge/Pipeline/ResponseObservationMiddleware.cs +++ b/dotnet/OpenWaf.Edge/Pipeline/ResponseObservationMiddleware.cs @@ -23,7 +23,7 @@ namespace OpenWaf.Edge.Pipeline; public sealed class ResponseObservationMiddleware( RequestDelegate next, EdgeStateStore state, - StreakTracker tracker, + IStreakTracker tracker, BlockStore blocks, AlertWriter alerts, IGeoIpLookup geo, diff --git a/dotnet/OpenWaf.Edge/Program.cs b/dotnet/OpenWaf.Edge/Program.cs index d5f75dc..1e2b3d3 100644 --- a/dotnet/OpenWaf.Edge/Program.cs +++ b/dotnet/OpenWaf.Edge/Program.cs @@ -32,10 +32,22 @@ builder.Services.AddDbContext(options => else options.UseSqlite(connectionString); }); -// One streak map per process. A multi-instance deployment therefore counts -// each instance's traffic separately — recorded as an evolution trigger in the -// OPEN-2 architecture decision, not hidden. -builder.Services.AddSingleton(); +// Where the streak counters live. The default is one map per process, which +// counts each instance's traffic separately — measured, not hidden: four +// refusals from one address, two per edge, at a threshold of 3 produced no ban +// anywhere (research/2026-10-01-multi-instance/, D1). +// +// OpenWaf:Policy:SharedStreaks=true moves the same rules onto a database row so +// N edges mature one streak, at the cost of a round trip per observed response +// on a path whose measured p95 is ~3 ms. It is read here, once, because it +// selects which store the process registers; a policy PUT cannot move the +// counters from one store to the other underneath a running process. +if (builder.Configuration.GetValue("OpenWaf:Policy:SharedStreaks", false)) + builder.Services.AddSingleton(sp => new SharedStreakTracker( + sp.GetRequiredService(), + sp.GetRequiredService>())); +else + builder.Services.AddSingleton(_ => new StreakTracker()); builder.Services.AddSingleton(); builder.Services.AddSingleton(sp => new EdgeStateStore( sp.GetRequiredService(), diff --git a/dotnet/OpenWaf.Edge/Startup/EdgeStateWarmer.cs b/dotnet/OpenWaf.Edge/Startup/EdgeStateWarmer.cs index 7f2992f..c6bf0a4 100644 --- a/dotnet/OpenWaf.Edge/Startup/EdgeStateWarmer.cs +++ b/dotnet/OpenWaf.Edge/Startup/EdgeStateWarmer.cs @@ -1,4 +1,7 @@ using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Storage; +using Microsoft.Extensions.DependencyInjection; using OpenWaf.Infrastructure.Persistence; namespace OpenWaf.Edge.Startup; @@ -36,10 +39,10 @@ internal sealed class EdgeStateWarmer( switch (strategy.ToLowerInvariant()) { case "ensurecreated": - await db.Database.EnsureCreatedAsync(cancellationToken); + await CreateSchemaAsync(db, migrate: false, cancellationToken); break; case "migrate": - await db.Database.MigrateAsync(cancellationToken); + await CreateSchemaAsync(db, migrate: true, cancellationToken); break; default: log.LogInformation("edge: schema management left to the operator (OPENWAF_SCHEMA={Strategy})", strategy); @@ -52,5 +55,41 @@ internal sealed class EdgeStateWarmer( state.Current.OperatorBlocks.Count, state.Current.EngineBans.Count, state.Current.AllowEntries.Count); } + /// + /// Bring the schema up, and survive losing the race for it. + /// + /// Two edges on one database start at the same moment in every deployment + /// that shares the block list — and in the shared-streak store (OPEN-52) + /// that is the configuration, not an accident. Measured with two processes + /// against one SQLite file: the first created the tables, the second died in + /// StartAsync with SQLite Error 1: 'table "allow_entries" already + /// exists', hosting reported "Hosting failed to start", and the process + /// never listened on its port. What has to be true is that the schema exists, + /// not that this process was the one that made it, so the loser re-checks and + /// carries on. + /// + private async Task CreateSchemaAsync(OpenWafDbContext db, bool migrate, CancellationToken ct) + { + try + { + if (migrate) await db.Database.MigrateAsync(ct); + else await db.Database.EnsureCreatedAsync(ct); + } + catch (Exception ex) + { + // Give the winner a moment to finish, then ask the question that + // matters. If the tables are there, this edge serves against them; + // if they are not, the failure was something else and the process + // must still refuse to start. + await Task.Delay(TimeSpan.FromMilliseconds(500), ct); + var creator = ((IInfrastructure)db.Database).Instance + .GetRequiredService(); + if (!await creator.ExistsAsync(ct)) throw; + log.LogWarning( + "edge: the schema was being created by another instance ({Error}); continuing against it.", + ex.Message); + } + } + public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask; } diff --git a/dotnet/OpenWaf.Edge/appsettings.json b/dotnet/OpenWaf.Edge/appsettings.json index 825eee0..9826388 100644 --- a/dotnet/OpenWaf.Edge/appsettings.json +++ b/dotnet/OpenWaf.Edge/appsettings.json @@ -37,6 +37,7 @@ "Ipv6KeyPrefixLength": 64, "EngineBlockStatus": 403, "OperatorBlockStatus": 301, + "SharedStreaks": false, "ObservationRetentionDays": 7, "BanRetentionDays": 7, "DefaultRedirectTargets": [ "https://www.iana.org/help/example-domains" ] diff --git a/dotnet/OpenWaf.Infrastructure/Persistence/ObservationWriter.cs b/dotnet/OpenWaf.Infrastructure/Persistence/ObservationWriter.cs index ca0b518..c5d129c 100644 --- a/dotnet/OpenWaf.Infrastructure/Persistence/ObservationWriter.cs +++ b/dotnet/OpenWaf.Infrastructure/Persistence/ObservationWriter.cs @@ -17,7 +17,7 @@ namespace OpenWaf.Infrastructure.Persistence; public sealed class ObservationWriter : BackgroundService { private readonly IServiceScopeFactory _scopeFactory; - private readonly StreakTracker _tracker; + private readonly IStreakTracker _tracker; private readonly EdgePolicyProvider _policy; private readonly DurabilityHealth _health; private readonly ILogger _log; @@ -26,7 +26,7 @@ public sealed class ObservationWriter : BackgroundService public ObservationWriter( IServiceScopeFactory scopeFactory, - StreakTracker tracker, + IStreakTracker tracker, EdgePolicyProvider policy, DurabilityHealth health, ILogger log) diff --git a/dotnet/OpenWaf.Infrastructure/Persistence/OpenWafDbContext.cs b/dotnet/OpenWaf.Infrastructure/Persistence/OpenWafDbContext.cs index df68ed6..65e3657 100644 --- a/dotnet/OpenWaf.Infrastructure/Persistence/OpenWafDbContext.cs +++ b/dotnet/OpenWaf.Infrastructure/Persistence/OpenWafDbContext.cs @@ -5,7 +5,7 @@ using OpenWaf.Domain.Security; namespace OpenWaf.Infrastructure.Persistence; /// -/// Six tables, all small. The edge never queries them on the request path — +/// Seven tables, all small. The edge never queries them on the request path — /// holds the snapshot it reads — so the schema is /// sized for operator inspection and for explaining a ban after the fact, not /// for throughput. @@ -18,6 +18,7 @@ public sealed class OpenWafDbContext(DbContextOptions options) public DbSet CountryRules => Set(); public DbSet Alerts => Set(); public DbSet PolicySettings => Set(); + public DbSet Streaks => Set(); protected override void OnModelCreating(ModelBuilder mb) { @@ -64,6 +65,24 @@ public sealed class OpenWafDbContext(DbContextOptions options) e.Property(o => o.LastRegion).HasMaxLength(128); }); + mb.Entity(e => + { + e.ToTable("source_streaks"); + e.HasKey(t => t.SourceKey); + e.Property(t => t.SourceKey).HasMaxLength(128); + e.HasIndex(t => t.LastSeenAt); + e.Property(t => t.LastPath).HasMaxLength(512); + e.Property(t => t.LastUserAgent).HasMaxLength(256); + e.Property(t => t.LastCountryCode).HasMaxLength(2); + e.Property(t => t.LastCity).HasMaxLength(128); + e.Property(t => t.LastRegion).HasMaxLength(128); + // The streak row is written by every edge that sees the source, so + // it is the one table in this schema where two writers routinely + // collide. The token is what turns that collision into a retry + // instead of a lost refusal. + e.Property(t => t.Version).IsConcurrencyToken(); + }); + mb.Entity(e => { e.ToTable("country_rules"); diff --git a/dotnet/OpenWaf.Infrastructure/Persistence/RetentionWorker.cs b/dotnet/OpenWaf.Infrastructure/Persistence/RetentionWorker.cs index 1029362..08d1523 100644 --- a/dotnet/OpenWaf.Infrastructure/Persistence/RetentionWorker.cs +++ b/dotnet/OpenWaf.Infrastructure/Persistence/RetentionWorker.cs @@ -54,6 +54,11 @@ public sealed class RetentionWorker : BackgroundService .Where(b => b.Source == BlockSource.Engine && b.ExpiresAt != null && b.ExpiresAt < now - policy.BanRetention) .ExecuteDeleteAsync(ct); await db.Alerts.Where(a => a.CreatedAt < now - policy.BanRetention).ExecuteDeleteAsync(ct); + // The shared streak map (OPEN-52) is the one table this edge writes + // on the request path, so it is also the one that could grow without + // bound if nothing swept it. Same window as observations: a source + // key stops being kept after this long without traffic. + await db.Streaks.Where(t => t.LastSeenAt < now - policy.ObservationRetention).ExecuteDeleteAsync(ct); _health.RecordSuccess(DurabilityHealth.Retention); } catch (Exception ex) diff --git a/dotnet/OpenWaf.Infrastructure/Persistence/SharedStreakTracker.cs b/dotnet/OpenWaf.Infrastructure/Persistence/SharedStreakTracker.cs new file mode 100644 index 0000000..f7aef76 --- /dev/null +++ b/dotnet/OpenWaf.Infrastructure/Persistence/SharedStreakTracker.cs @@ -0,0 +1,234 @@ +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using OpenWaf.Domain.Engine; +using OpenWaf.Domain.Policy; +using OpenWaf.Domain.Security; + +namespace OpenWaf.Infrastructure.Persistence; + +/// +/// The streak map moved into the database, so N edges mature one streak instead +/// of N streaks (OPEN-52). +/// +/// The rules are not reimplemented here: this calls +/// against a row, exactly as the in-process calls it +/// against a . A second copy of those rules would put +/// the drift back where this class exists to remove it. +/// +/// What it costs, stated: one database round trip per observed response, on a +/// request path whose measured p95 is ~3 ms, and one optimistic-concurrency +/// retry when two edges touch the same source at the same moment. That is the +/// price of a threshold that means the same thing behind a load balancer; the +/// default remains the in-process map, and the deployment decides. +/// +public sealed class SharedStreakTracker : IStreakTracker +{ + private readonly IServiceScopeFactory _scopeFactory; + private readonly ILogger _log; + + /// Two edges racing on one row is the normal case here, not a + /// corner. The loser re-reads the winner's row and re-applies the rules, so + /// both refusals are counted; the retry bound is there so a pathological + /// contention loop cannot pin a request thread forever. + private const int ContentionRetries = 3; + + public SharedStreakTracker(IServiceScopeFactory scopeFactory, ILogger log) + { + _scopeFactory = scopeFactory; + _log = log; + } + + /// Sync on purpose: sits on + /// the request path between the upstream's answer and the operator's view of + /// it, and EF Core's synchronous API is real. Making this async would change + /// the interface for every caller to wrap a completed value. + public StreakOutcome Observe( + string sourceKey, int statusCode, ResponseClass responseClass, + EdgePolicy policy, DateTimeOffset now, RequestEvidence? evidence = null) + { + if (string.IsNullOrEmpty(sourceKey)) return StreakOutcome.None; + + for (var attempt = 0; ; attempt++) + { + using var scope = _scopeFactory.CreateScope(); + var db = scope.ServiceProvider.GetRequiredService(); + try + { + var row = db.Streaks.FirstOrDefault(t => t.SourceKey == sourceKey); + var isNew = row is null; + row ??= new SourceStreak { SourceKey = sourceKey, LastSeenAt = now }; + + var state = Read(row); + var outcome = StreakRules.Apply(state, statusCode, responseClass, policy, now, evidence); + Write(row, state); + row.Version++; + + if (isNew) db.Streaks.Add(row); + db.SaveChanges(); + return outcome; + } + catch (DbUpdateConcurrencyException) when (attempt < ContentionRetries) + { + // Another edge wrote this source between the read and the write. + // Counting on top of its row is the whole point: dropping this + // refusal is how the threshold goes wrong again. + _log.LogDebug("SharedStreaks: contention on {Key}; retrying against the winner's row.", sourceKey); + } + catch (DbUpdateException) when (attempt < ContentionRetries) + { + // Another edge inserted the same key between the read and the + // insert. The retry finds that row and counts on it. + _log.LogDebug("SharedStreaks: insert raced for {Key}; retrying.", sourceKey); + } + } + } + + public IReadOnlyList Snapshot(DateTimeOffset now, EdgePolicy policy) + { + using var scope = _scopeFactory.CreateScope(); + var db = scope.ServiceProvider.GetRequiredService(); + EvictIdle(db, now, policy); + return db.Streaks.AsNoTracking() + .Where(t => t.TotalRefusals > 0 || t.MaxConsecutiveServerErrors > 0) + .ToList() + .Select(t => new StreakSnapshot( + t.SourceKey, t.MaxConsecutiveRefusals, t.TotalRefusals, t.MaxConsecutiveServerErrors, + t.LastStatusCode, t.LastPath, t.LastUserAgent, t.LastCountryCode, t.LastCity, t.LastRegion, + t.LastSeenAt)) + .ToList(); + } + + public StreakSnapshot? Peek(string sourceKey) + { + using var scope = _scopeFactory.CreateScope(); + var db = scope.ServiceProvider.GetRequiredService(); + var t = db.Streaks.AsNoTracking().FirstOrDefault(x => x.SourceKey == sourceKey); + return t is null ? null : new StreakSnapshot( + t.SourceKey, t.MaxConsecutiveRefusals, t.TotalRefusals, t.MaxConsecutiveServerErrors, + t.LastStatusCode, t.LastPath, t.LastUserAgent, t.LastCountryCode, t.LastCity, t.LastRegion, + t.LastSeenAt); + } + + public IReadOnlyList LiveStreaks(DateTimeOffset now, EdgePolicy policy, int limit) + => LiveStreaks(now, policy, limit, 0, out _); + + public IReadOnlyList LiveStreaks( + DateTimeOffset now, EdgePolicy policy, int limit, int offset, out int standingTotal) + => LiveStreaks(now, policy, limit, offset, null, out standingTotal); + + /// Same contract as the in-process listing: only sources with + /// something standing, worst first, and standingTotal counted over the + /// filtered set so a filtered page cannot claim a cut that did not happen. + public IReadOnlyList LiveStreaks( + DateTimeOffset now, EdgePolicy policy, int limit, int offset, string? sourceKey, + out int standingTotal) + { + var take = Math.Max(1, limit); + var skip = Math.Max(0, offset); + using var scope = _scopeFactory.CreateScope(); + var db = scope.ServiceProvider.GetRequiredService(); + EvictIdle(db, now, policy); + + var query = db.Streaks.AsNoTracking() + .Where(t => t.ConsecutiveRefusals > 0 || t.ConsecutiveServerErrors > 0); + if (sourceKey is not null) query = query.Where(t => t.SourceKey == sourceKey); + + standingTotal = query.Count(); + return query + .OrderByDescending(t => t.ConsecutiveRefusals) + .ThenByDescending(t => t.ConsecutiveServerErrors) + .ThenByDescending(t => t.LastSeenAt) + .Skip(skip).Take(take) + .ToList() + .Select(t => new LiveStreak( + t.SourceKey, t.ConsecutiveRefusals, t.ConsecutiveServerErrors, + t.LastStatusCode, t.LastPath, t.LastCountryCode, t.LastSeenAt)) + .ToList(); + } + + public int TrackedCount + { + get + { + using var scope = _scopeFactory.CreateScope(); + var db = scope.ServiceProvider.GetRequiredService(); + return db.Streaks.Count(); + } + } + + /// A clean answer ends the run. One statement, no read: this runs + /// for every 2xx/3xx, which is most of the traffic, and a source nobody has + /// ever seen must cost as little here as it does in the in-process map. + public void ResetIfTracked(string sourceKey) + { + if (string.IsNullOrEmpty(sourceKey)) return; + using var scope = _scopeFactory.CreateScope(); + var db = scope.ServiceProvider.GetRequiredService(); + db.Streaks + .Where(t => t.SourceKey == sourceKey && (t.ConsecutiveRefusals > 0 || t.ConsecutiveServerErrors > 0)) + .ExecuteUpdate(u => u + .SetProperty(t => t.ConsecutiveRefusals, 0) + .SetProperty(t => t.ConsecutiveServerErrors, 0) + .SetProperty(t => t.LastAlertedRefusals, 0) + .SetProperty(t => t.LastAlertedServerErrors, 0)); + } + + public void Forget(string sourceKey) + { + using var scope = _scopeFactory.CreateScope(); + var db = scope.ServiceProvider.GetRequiredService(); + db.Streaks.Where(t => t.SourceKey == sourceKey).ExecuteDelete(); + } + + /// No cap to carry: + /// bounds a process's memory, and this store is bounded by time instead — + /// idle rows are dropped when read () and pruned by + /// the retention worker. + public void Configure(EdgePolicy policy) { } + + private static void EvictIdle(OpenWafDbContext db, DateTimeOffset now, EdgePolicy policy) + { + if (policy.StateIdleTtl <= TimeSpan.Zero) return; + db.Streaks.Where(t => t.LastSeenAt < now - policy.StateIdleTtl).ExecuteDelete(); + } + + private static StreakState Read(SourceStreak row) => new() + { + SourceKey = row.SourceKey, + ConsecutiveRefusals = row.ConsecutiveRefusals, + MaxConsecutiveRefusals = row.MaxConsecutiveRefusals, + TotalRefusals = row.TotalRefusals, + ConsecutiveServerErrors = row.ConsecutiveServerErrors, + MaxConsecutiveServerErrors = row.MaxConsecutiveServerErrors, + LastAlertedRefusals = row.LastAlertedRefusals, + LastAlertedServerErrors = row.LastAlertedServerErrors, + LastRefusalAt = row.LastRefusalAt, + LastSeenAt = row.LastSeenAt, + LastStatusCode = row.LastStatusCode, + LastPath = row.LastPath, + LastUserAgent = row.LastUserAgent, + LastCountryCode = row.LastCountryCode, + LastCity = row.LastCity, + LastRegion = row.LastRegion + }; + + private static void Write(SourceStreak row, StreakState state) + { + row.ConsecutiveRefusals = state.ConsecutiveRefusals; + row.MaxConsecutiveRefusals = state.MaxConsecutiveRefusals; + row.TotalRefusals = state.TotalRefusals; + row.ConsecutiveServerErrors = state.ConsecutiveServerErrors; + row.MaxConsecutiveServerErrors = state.MaxConsecutiveServerErrors; + row.LastAlertedRefusals = state.LastAlertedRefusals; + row.LastAlertedServerErrors = state.LastAlertedServerErrors; + row.LastRefusalAt = state.LastRefusalAt; + row.LastSeenAt = state.LastSeenAt; + row.LastStatusCode = state.LastStatusCode; + row.LastPath = state.LastPath; + row.LastUserAgent = state.LastUserAgent; + row.LastCountryCode = state.LastCountryCode; + row.LastCity = state.LastCity; + row.LastRegion = state.LastRegion; + } +} diff --git a/dotnet/OpenWaf.Tests.Integration/EdgeFixture.cs b/dotnet/OpenWaf.Tests.Integration/EdgeFixture.cs index bbe82f0..4f9e327 100644 --- a/dotnet/OpenWaf.Tests.Integration/EdgeFixture.cs +++ b/dotnet/OpenWaf.Tests.Integration/EdgeFixture.cs @@ -12,7 +12,13 @@ namespace OpenWaf.Tests.Integration; /// internal sealed class EdgeFixture : IAsyncDisposable { - private readonly string _dbPath = Path.Combine(Path.GetTempPath(), $"openwaf-test-{Guid.NewGuid():N}.db"); + private readonly string _dbPath; + + /// True when the caller passed a database to share with another + /// fixture, in which case this fixture must not be the one that deletes it. + /// Two edges on one database is the multi-instance case (OPEN-52), and the + /// file is the thing under test. + private readonly bool _sharedDb; public FakeUpstream Upstream { get; } = FakeUpstream.Start(); @@ -29,8 +35,12 @@ internal sealed class EdgeFixture : IAsyncDisposable int? refreshTtlSeconds = null, int? observationRetentionDays = null, int? banRetentionDays = null, - string? adminToken = AdminToken) + string? adminToken = AdminToken, + string? dbPath = null, + bool sharedStreaks = false) { + _sharedDb = dbPath is not null; + _dbPath = dbPath ?? Path.Combine(Path.GetTempPath(), $"openwaf-test-{Guid.NewGuid():N}.db"); Factory = new WebApplicationFactory().WithWebHostBuilder(builder => { builder.UseSetting("ConnectionStrings:OpenWaf", $"Data Source={_dbPath}"); @@ -55,6 +65,10 @@ internal sealed class EdgeFixture : IAsyncDisposable builder.UseSetting("OpenWaf:Policy:ObservationRetentionDays", ord.ToString()); if (banRetentionDays is { } brd) builder.UseSetting("OpenWaf:Policy:BanRetentionDays", brd.ToString()); + // Which streak store the process registers. Off is the default and + // the shape every other fixture runs; on is the multi-instance case + // where two of these fixtures share one database. + builder.UseSetting("OpenWaf:Policy:SharedStreaks", sharedStreaks ? "true" : "false"); builder.UseSetting("ReverseProxy:Clusters:upstream:Destinations:upstream1:Address", Upstream.Address); }); } @@ -78,6 +92,6 @@ internal sealed class EdgeFixture : IAsyncDisposable Upstream.RequestCount = 0; await Upstream.DisposeAsync(); Microsoft.Data.Sqlite.SqliteConnection.ClearAllPools(); - if (File.Exists(_dbPath)) File.Delete(_dbPath); + if (!_sharedDb && File.Exists(_dbPath)) File.Delete(_dbPath); } } diff --git a/dotnet/OpenWaf.Tests.Integration/SharedStreakTests.cs b/dotnet/OpenWaf.Tests.Integration/SharedStreakTests.cs new file mode 100644 index 0000000..1e2b6b5 --- /dev/null +++ b/dotnet/OpenWaf.Tests.Integration/SharedStreakTests.cs @@ -0,0 +1,228 @@ +using System.Net; +using Microsoft.AspNetCore.Http; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using OpenWaf.Domain.Security; +using OpenWaf.Infrastructure.Persistence; + +namespace OpenWaf.Tests.Integration; + +/// +/// The one gap the multi-instance research measured rather than guessed: the +/// block list is shared through the database, the streak map was not. Four +/// refusals from one address, two per edge, at a threshold of 3, produced no ban +/// anywhere (research/2026-10-01-multi-instance/, D1, reproduced twice). +/// +/// These tests run two real edge instances against one SQLite file, so the +/// answer is not a simulation of sharing — it is sharing. The default stays the +/// in-process map, and the second test is the proof that the default still +/// behaves the way the research measured it. +/// +public sealed class SharedStreakTests +{ + private const string Scanner = "203.0.113.71"; + + private static string NewSharedDb() => + Path.Combine(Path.GetTempPath(), $"openwaf-shared-{Guid.NewGuid():N}.db"); + + private static async Task GetAsync(EdgeFixture f, string path, string ip) + { + using var request = new HttpRequestMessage(HttpMethod.Get, path); + request.Headers.TryAddWithoutValidation("X-Forwarded-For", ip); + return await f.Client.SendAsync(request); + } + + [Fact] + public async Task Two_edges_on_one_database_mature_one_streak_together() + { + var db = NewSharedDb(); + try + { + await using var a = new EdgeFixture(threshold: 3, dbPath: db, sharedStreaks: true); + await using var b = new EdgeFixture(threshold: 3, dbPath: db, sharedStreaks: true); + + // Two refusals at one edge: 1 of 3, then 2 of 3. Nothing bans yet. + using (var first = await GetAsync(a, "/probe", Scanner)) + Assert.Equal(HttpStatusCode.NotFound, first.StatusCode); + using (var second = await GetAsync(a, "/probe", Scanner)) + Assert.Equal(HttpStatusCode.NotFound, second.StatusCode); + + // The third lands at the other edge. Per process that is 1 of 3 and + // bans nobody; shared it is 3 of 3, so the ban exists after this + // request — which is the request D1 measured as answering 404 on + // both edges, because neither map had crossed on its own. + using (var third = await GetAsync(b, "/probe", Scanner)) + Assert.Equal(HttpStatusCode.NotFound, third.StatusCode); + + using (var scope = b.Factory.Services.CreateScope()) + { + var dbf = scope.ServiceProvider.GetRequiredService(); + var ban = await dbf.Blocks.SingleOrDefaultAsync(x => x.SourceKey == Scanner && x.Source == BlockSource.Engine); + Assert.NotNull(ban); + Assert.Equal(3, ban!.ConsecutiveRefusals); + } + + // The banning edge enforces it, and so does the edge that never saw + // a third refusal — the ban is the fleet's, once the snapshot moves. + using (var enforcedHere = await GetAsync(b, "/anything", Scanner)) + Assert.Equal(HttpStatusCode.Forbidden, enforcedHere.StatusCode); + await a.Service().InvalidateAsync(CancellationToken.None); + using (var enforcedThere = await GetAsync(a, "/anything", Scanner)) + Assert.Equal(HttpStatusCode.Forbidden, enforcedThere.StatusCode); + } + finally { if (File.Exists(db)) File.Delete(db); } + } + + [Fact] + public async Task The_same_split_traffic_bans_nobody_without_the_shared_store() + { + // The default, kept honest: this is D1 reproduced, not a strawman. Two + // edges, threshold 3, two refusals each — nobody crosses the threshold + // in either map, so the visitor is served and no ban exists anywhere. + var db = NewSharedDb(); + try + { + await using var a = new EdgeFixture(threshold: 3, dbPath: db); + await using var b = new EdgeFixture(threshold: 3, dbPath: db); + + for (var i = 0; i < 2; i++) + using (var viaA = await GetAsync(a, "/probe", Scanner)) + Assert.Equal(HttpStatusCode.NotFound, viaA.StatusCode); + for (var i = 0; i < 2; i++) + using (var viaB = await GetAsync(b, "/probe", Scanner)) + Assert.Equal(HttpStatusCode.NotFound, viaB.StatusCode); + + // Four refusals, two per map, threshold 3: nobody crossed, so no ban + // was written anywhere. (A fifth request would be the third of one + // edge's own run — that is the per-process behaviour, and it is not + // what this test is about.) + using (var scope = a.Factory.Services.CreateScope()) + { + var dbf = scope.ServiceProvider.GetRequiredService(); + Assert.Empty(await dbf.Blocks.Where(x => x.SourceKey == Scanner).ToListAsync()); + } + } + finally { if (File.Exists(db)) File.Delete(db); } + } + + [Fact] + public async Task The_streak_listing_names_the_store_it_answered_from_and_shows_the_other_edge_s_work() + { + var db = NewSharedDb(); + try + { + await using var a = new EdgeFixture(threshold: 5, dbPath: db, sharedStreaks: true); + await using var b = new EdgeFixture(threshold: 5, dbPath: db, sharedStreaks: true); + await using var local = new EdgeFixture(threshold: 5); + + using (await GetAsync(a, "/probe", Scanner)) { } + using (await GetAsync(a, "/probe", Scanner)) { } + + // Asked on the edge that saw nothing, the shared listing still shows + // the streak — and says where it came from. + var shared = await (await b.Client.GetAsync( + $"/admin-api/streaks?source={Scanner}&token={EdgeFixture.AdminToken}")).Content.ReadAsStringAsync(); + Assert.Contains("\"scope\":\"shared-database\"", shared); + Assert.Contains("\"consecutiveRefusals\":2", shared); + Assert.Contains("\"standingStreaks\":1", shared); + + // The default store answers for one process and says so. + var localBody = await (await local.Client.GetAsync( + $"/admin-api/streaks?token={EdgeFixture.AdminToken}")).Content.ReadAsStringAsync(); + Assert.Contains("\"scope\":\"this-process\"", localBody); + Assert.Contains("\"standingStreaks\":0", localBody); + + var state = await (await b.Client.GetAsync($"/admin-api/state?token={EdgeFixture.AdminToken}")).Content.ReadAsStringAsync(); + Assert.Contains("\"streakScope\":\"shared-database\"", state); + } + finally { if (File.Exists(db)) File.Delete(db); } + } + + [Fact] + public async Task A_clean_answer_at_the_other_edge_ends_the_shared_streak() + { + // "Consecutive" has to mean the same thing across edges, or sharing the + // counters makes the ban worse rather than correct: a visitor who fixes + // what the edge objected to, on any instance, starts over. + var db = NewSharedDb(); + try + { + await using var a = new EdgeFixture(threshold: 3, dbPath: db, sharedStreaks: true); + await using var b = new EdgeFixture(threshold: 3, dbPath: db, sharedStreaks: true); + a.Upstream.StatusFor = path => path == "/ok" ? StatusCodes.Status200OK : StatusCodes.Status404NotFound; + b.Upstream.StatusFor = path => path == "/ok" ? StatusCodes.Status200OK : StatusCodes.Status404NotFound; + + using (await GetAsync(a, "/probe", Scanner)) { } + using (await GetAsync(a, "/probe", Scanner)) { } + + using (var clean = await GetAsync(b, "/ok", Scanner)) + Assert.Equal(HttpStatusCode.OK, clean.StatusCode); + + // Two more refusals at the first edge. Without the reset across + // edges this is the third and fourth of one run and bans at the + // first of them. + using (var afterReset1 = await GetAsync(a, "/probe", Scanner)) + Assert.Equal(HttpStatusCode.NotFound, afterReset1.StatusCode); + using (var afterReset2 = await GetAsync(a, "/probe", Scanner)) + Assert.Equal(HttpStatusCode.NotFound, afterReset2.StatusCode); + } + finally { if (File.Exists(db)) File.Delete(db); } + } + + [Fact] + public async Task Two_edges_started_at_the_same_moment_against_one_database_both_come_up() + { + // The shared store makes "two edges, one database" the configuration + // rather than an accident, and both edges create the schema on startup. + // The loser of that race used to die in StartAsync with 'table + // "allow_entries" already exists' and never listened — measured with two + // real processes on one file, which is also how the fix was confirmed. + // Here both hosts are forced to build at the same instant. + var db = NewSharedDb(); + try + { + await using var a = new EdgeFixture(dbPath: db, sharedStreaks: true); + await using var b = new EdgeFixture(dbPath: db, sharedStreaks: true); + + var responses = await Task.WhenAll( + a.Client.GetAsync("/healthz"), + b.Client.GetAsync("/healthz"), + a.Client.GetAsync("/healthz"), + b.Client.GetAsync("/healthz")); + Assert.All(responses, r => Assert.Equal(HttpStatusCode.OK, r.StatusCode)); + } + finally { if (File.Exists(db)) File.Delete(db); } + } + + [Fact] + public async Task The_retention_window_ages_out_shared_streak_rows_too() + { + // The shared map is the one table this edge writes on the request path, + // so the privacy window has to sweep it as well: a source key must not + // outlive ObservationRetentionDays just because the counters moved out + // of memory. + var db = NewSharedDb(); + try + { + await using var f = new EdgeFixture(threshold: 3, dbPath: db, sharedStreaks: true, observationRetentionDays: 1); + using (await GetAsync(f, "/probe", Scanner)) { } + + using (var scope = f.Factory.Services.CreateScope()) + { + var dbf = scope.ServiceProvider.GetRequiredService(); + var row = await dbf.Streaks.SingleAsync(t => t.SourceKey == Scanner); + row.LastSeenAt = DateTimeOffset.UtcNow.AddDays(-3); + await dbf.SaveChangesAsync(); + } + + await f.Service().PruneAsync(CancellationToken.None); + + using (var scope = f.Factory.Services.CreateScope()) + { + var dbf = scope.ServiceProvider.GetRequiredService(); + Assert.Equal(0, await dbf.Streaks.CountAsync()); + } + } + finally { if (File.Exists(db)) File.Delete(db); } + } +}