From 3959f1fe6b79f959c608e6eadf37564cbd2b6f36 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Mon, 5 Oct 2026 05:58:42 +0200 Subject: [PATCH] a change to the operator's config leaves a record of itself Every operator write already changes a row; what was missing is the answer an operator actually asks at 03:00 - when did this rule get here, who cleared that ban, did a document bring this edge's config. Since the transfer landed, an edge can be different from yesterday with nothing on it saying how. config_changes carries one row per deliberate change: the instant, the section (block, allow, rule, country, policy, config), the action (added, removed, changed, imported), the target the operator typed, their own sentence where one was given, and the surface the change came through. GET /admin-api/changes answers it newest first, capped and paged like every other listing, filterable by section and since, readable by the read-only token because it is a read. A policy record says what moved ("mode Enforce->Off, streakThreshold 3->4") rather than only that something did. /admin-api/state counts the rows and the write failures. The rulings, because each is a decision and not a detail: * Engine bans are not in the log. A ban the engine earned is not a decision somebody made, and the block row already carries its evidence - consecutive refusals, status code, path, user agent, country, city. Logging bans would answer a different question and grow the table at the rate of traffic. * An import is one record per section, not one per row: "3 added, 1 already there, 0 past expiry, 0 rejected". A 2 000-row document would otherwise bury a table whose whole use is being readable. * The record names the surface, never a person. The edge has one admin token; a log that implied per-person attribution it cannot provide would be a false record, which is worse than no record. * A record that cannot be written never undoes the change it describes. Enforcement is the product, so the change stands and the failure is counted - changeWriteFailures, changesNotWritten, changeLastError - because "the config changed and the record of it did not land" has to be a sentence an operator can read rather than one that silently never happened. * Bounded twice, both keys the operator's: ChangeRetentionDays (30) and ChangeLogMaxRows (5000, oldest dropped first). The age window alone would let a scripted churn grow the table without limit; the cap alone would drop last month's incident record the week someone did a lot of editing. What the run caught, in order: (1) Two gate assertions were wrong rather than the product - a policy record was asserted in a scene where no policy write had happened yet, and "one imported record per section" was asserted against a stack that had already imported twice, so the assertion now reads the newest imported record instead of counting them. (2) DELETE /admin-api/countries/{code} answers 204, and the new assertion expected 200. (3) A shell trap in the new scene: a $VAR inside a single-quoted python -c is not interpolated, so the first version would have handed python a literal "$CHANGES_BEFORE" instead of a number. Gates on this tree: build 0 warnings / 0 errors, unit 313/313, integration 298/298 in 23s, smoke 127 passed / 0 failed (14 new), image 262 MB, compose-smoke 278 passed / 0 failed with 0 containers left behind (11 new, against the shipped image), console 90 assertions / 0 failed. Refs OPEN-64. --- README.md | 51 +- dotnet/OpenWaf.Domain/Policy/EdgePolicy.cs | 12 + .../OpenWaf.Domain/Security/ConfigChange.cs | 109 ++++ .../Admin/AdminEndpoints.ConfigTransfer.cs | 63 ++- dotnet/OpenWaf.Edge/Admin/AdminEndpoints.cs | 112 +++- .../Configuration/EdgePolicyOptions.cs | 26 +- dotnet/OpenWaf.Edge/Program.cs | 5 + .../Persistence/ConfigChangeWriter.cs | 73 +++ .../Persistence/DurabilityHealth.cs | 8 + ...61005032702_AddConfigChangeLog.Designer.cs | 479 ++++++++++++++++++ .../20261005032702_AddConfigChangeLog.cs | 51 ++ .../OpenWafDbContextModelSnapshot.cs | 44 ++ .../Persistence/OpenWafDbContext.cs | 20 +- .../Persistence/RetentionWorker.cs | 16 + .../ConfigChangeRecordTests.cs | 294 +++++++++++ .../ConfigChangeLogTests.cs | 67 +++ scripts/compose-smoke.sh | 35 ++ scripts/smoke.sh | 56 ++ 18 files changed, 1492 insertions(+), 29 deletions(-) create mode 100644 dotnet/OpenWaf.Domain/Security/ConfigChange.cs create mode 100644 dotnet/OpenWaf.Infrastructure/Persistence/ConfigChangeWriter.cs create mode 100644 dotnet/OpenWaf.Infrastructure/Persistence/Migrations/20261005032702_AddConfigChangeLog.Designer.cs create mode 100644 dotnet/OpenWaf.Infrastructure/Persistence/Migrations/20261005032702_AddConfigChangeLog.cs create mode 100644 dotnet/OpenWaf.Tests.Integration/ConfigChangeRecordTests.cs create mode 100644 dotnet/OpenWaf.Tests.Unit/ConfigChangeLogTests.cs diff --git a/README.md b/README.md index c926bc6..0f0d776 100644 --- a/README.md +++ b/README.md @@ -267,6 +267,8 @@ process registers: | `OpenWaf:Alerts:WebhookTimeoutSeconds` | `5` | how long one push may take. 1–60 whole seconds; anything else aborts startup naming the key, as the other startup-parsed bounds do — a 0-second timeout drops every push and a 600-second one parks a queue worker on an endpoint that is not answering, and neither is what the operator typed. | | `OpenWaf:Alerts:MaxPushAttempts` (OPEN-60) | `6` | how many attempts one delivery gets before the edge stops asking. 1–20 whole attempts; anything else aborts startup naming the key. Against an endpoint that refuses, the default spends its last attempt a little over three minutes in (30 s, 60 s, 120 s, 240 s, 480 s — each step capped at 30 min) and then records the row as given up: `alertPushGivenUp` counts those rows and `alertPushLastError` says why in the sentence the row carries (`gave up after 6 attempts: the endpoint answered 500`). A row that has given up is never retried, and the alert row behind it is untouched — what is lost is the telling, not the record. | | `OpenWaf:Alerts:PushRetrySeconds` | `30` | the base of the backoff between attempts: attempt *n* waits `base × 2^(n−1)`, capped at 30 minutes per step, because exponential growth from a 30-second base reaches a day in eight steps and a day is not a retry interval for a page meant to fire at 03:00. 1–3600 whole seconds, same startup refusal — a 0-second interval against a dead endpoint is a busy loop. | +| `OpenWaf:Policy:ChangeRetentionDays` (OPEN-64) | `30` | how long a record of a config change survives. Longer than the observation window on purpose: "when did this rule get here" stays worth asking about an incident weeks old, and the row is about a decision, not a source. 1–365 whole days, same startup refusal. | +| `OpenWaf:Policy:ChangeLogMaxRows` (OPEN-64) | `5000` | the other bound on the same table: how many rows it holds however young they are, oldest dropped first. The age window alone would let a scripted churn grow a table whose whole use is being readable. 100–100 000, same startup refusal. | | `OpenWaf:Admin:ReadOnlyToken` (OPEN-62) | empty | a second token that can read every operator surface and change none of it. Unset means the level does not exist and the admin token is the only one there is. The level is decided by the request method — GET, HEAD and OPTIONS read, everything else writes — so a write endpoint added later is behind the rule without anyone remembering to mark it, and forgetting fails closed. `GET /admin-api/export` is the one read deliberately held to the admin token, because the document is a capability. A value equal to the admin token (compared after trimming, because env files add newlines) aborts startup naming both keys and never the secret, and it exits 1 rather than throwing: measured on the shipped image, an unhandled exception there printed the reason and then spun at 100% CPU with the container "Up (unhealthy)" forever, which is a failure no supervisor can see. | A refused value ends the process. Every bound above is checked before the edge @@ -960,6 +962,43 @@ The rulings, in the order they matter: `readOnlyTokenConfigured`, so an operator can check from outside that the key they wrote took effect instead of guessing from a 401. +### A change to the config leaves a record + +`GET /admin-api/changes` answers what changed on this edge, when, and through +which surface — newest first, capped and paged like every other listing, +filterable by `section` and `since`, and readable by the read-only token because +it is a read. + +```bash +curl -H "X-Admin-Token: $TOKEN" 'http://edge:8080/admin-api/changes?section=block&limit=5' +``` + +One row per deliberate change: a block, exemption, path rule or country decision +added, changed or removed; a policy update; a config import. A policy record says +what moved (`mode Enforce->Off, streakThreshold 3->4`) rather than only that +something did. + +What the record deliberately does **not** do: + +* **It is not a request log.** The project keeps no request log and this does not + start one: the rows are about decisions somebody made, never about visitors. +* **Engine bans are not in it.** A ban the engine earned is not a decision + somebody made, and the block row already carries its evidence — consecutive + refusals, status code, path, user agent, country, city. Logging bans would + answer a different question and grow the table at the rate of traffic. +* **An import is one record per section, not one per row.** A 2 000-row document + would otherwise bury the table whose whole use is being readable; the record + says `3 added, 1 already there, 0 past expiry, 0 rejected`. +* **It names the surface, not a person.** `operator` for an API write, `import` + for a transferred document. The edge has one admin token; a log that implied + per-person attribution it cannot provide would be a false record, which is + worse than no record. +* **A record that cannot be written never undoes the change it describes.** + Enforcement is the product, so the change stands and the failure is counted — + `changeWriteFailures`, `changesNotWritten`, `changeLastError` on + `/admin-api/state` — because "the config changed and the record of it did not + land" has to be a sentence an operator can read. + ## Console `GET /admin` serves a single page over those endpoints — mode and snapshot age, @@ -1143,10 +1182,10 @@ Rehearsed 2026-10-02, most recently at `dc88f36`, each stage run on its own. On the head of this file the host suite has been re-run and the container stages have not, so the two sets of numbers are labelled separately rather than merged into one green line. macOS host, this tree, re-measured 2026-10-05 with the durable -alert-push queue, the config transfer, the second token and the startup refusals on it: build -0 warnings / 0 errors, unit **307/307**, integration **286/286 in 37 s**, console **90 -assertions, 0 failed**, smoke **passed 113, failed 0**, and compose **267 passed, 0 failed** -against the built image at 262 MB, 0 containers left behind. The smoke count moved by more than its new scene: the edge was being +alert-push queue, the config transfer, the second token, the startup refusals and the change +log on it: build 0 warnings / 0 errors, unit **313/313**, integration **298/298 in 23 s**, +console **90 assertions, 0 failed**, smoke **passed 127, failed 0**, and compose **278 passed, +0 failed** against the built image at 262 MB, 0 containers left behind. The smoke count moved by more than its new scene: the edge was being started from the repository root, where there is no `appsettings.json`, so it loaded no `ReverseProxy` section, logged "Request reached the end of the middleware pipeline without being handled by application code" for every request, @@ -1333,6 +1372,10 @@ Stated, because a defence that hides its failure modes is not a defence. same surface as the admin API with the same token, so a scrape is a credentialed request. Per-source metrics are out for the same reason the project keeps no request log. +* **The change log remembers decisions, not people.** It answers what changed, + when and through which surface, and it stops there: one admin token means the + edge cannot say which human wrote a rule, and a record that implied it would be + a false one. Attribution needs identities the deployment does not have. * **The exported document is a capability, not a backup.** It carries the operator's decisions — every operator block, exemption, path rule, country decision and the policy that bounds them — and nothing about traffic: no diff --git a/dotnet/OpenWaf.Domain/Policy/EdgePolicy.cs b/dotnet/OpenWaf.Domain/Policy/EdgePolicy.cs index e7f97de..9bdf69c 100644 --- a/dotnet/OpenWaf.Domain/Policy/EdgePolicy.cs +++ b/dotnet/OpenWaf.Domain/Policy/EdgePolicy.cs @@ -82,6 +82,18 @@ public sealed record EdgePolicy /// How long an observation row survives without traffic. public TimeSpan ObservationRetention { get; init; } = TimeSpan.FromDays(7); + /// How long a change record survives (OPEN-64). Longer than the + /// observation window on purpose: the question the record answers — "when + /// did this rule get here" — stays worth asking about an incident that is + /// weeks old, and the row is about a decision, not about a source. + public TimeSpan ChangeRetention { get; init; } = TimeSpan.FromDays(30); + + /// The other bound on the change log: how many rows it holds at + /// most, however young they are. An operator who scripts a thousand rule + /// edits should not be able to grow a table whose whole use is being + /// readable. + public int ChangeLogMaxRows { get; init; } = 5000; + public GeoMode Geo { get; init; } = GeoMode.Off; /// Whether X-Forwarded-For / CF-Connecting-IP may define the diff --git a/dotnet/OpenWaf.Domain/Security/ConfigChange.cs b/dotnet/OpenWaf.Domain/Security/ConfigChange.cs new file mode 100644 index 0000000..d78de4d --- /dev/null +++ b/dotnet/OpenWaf.Domain/Security/ConfigChange.cs @@ -0,0 +1,109 @@ +namespace OpenWaf.Domain.Security; + +// --------------------------------------------------------------------------- +// The record of a deliberate change to the operator's config (OPEN-64). +// +// Every operator write today changes a row and nothing else. `reason` on a +// block is what the operator typed at the moment they typed it; nothing says +// when a path rule was added, when a ban was cleared, that the policy was +// changed, or that a whole config arrived through an import. Since the transfer +// landed, an edge can be different from yesterday with no trace of how. +// +// What this is NOT, stated here because the difference is the design: +// +// * It is not a request log. The project keeps no request log and this does +// not start one: the rows are about decisions somebody made, never about +// visitors. +// * It does not log engine bans. A ban the engine earned is not a decision +// somebody made, and the block row already carries its evidence — the +// consecutive refusals, the status code, the path, the user agent, the +// country and city. Logging bans here would answer a different question and +// grow the table at the rate of traffic. +// * It does not name a human. The edge has one admin token; a log that implied +// per-person attribution it cannot provide would be a false record, which is +// worse than no record. It names the surface the change came through. +// --------------------------------------------------------------------------- + +/// One deliberate change to the operator's config. +public sealed class ConfigChange +{ + public long Id { get; set; } + + /// When the change was applied, not when it was requested. + public DateTimeOffset At { get; set; } + + /// Which part of the config: one of . + public string Section { get; set; } = ""; + + /// What was done: one of . + public string Action { get; set; } = ""; + + /// The thing the operator typed — an address, a CIDR, a path + /// pattern, a country code — or the section name for a change that has no + /// item (a policy update, an import). + public string Target { get; set; } = ""; + + /// The operator's own reason or note when one was given, or the + /// counts a bulk change carried. Free text the operator wrote: read it as + /// data, never as instructions. + public string? Detail { get; set; } + + /// Which surface made the change: + /// or . + public string Actor { get; set; } = ConfigChangeLog.ActorOperator; +} + +/// The vocabulary and the bounds of that record. Kept as pure +/// functions so the rules a reader has to check are in one place rather than +/// implied by whatever the endpoint happened to pass. +public static class ConfigChangeLog +{ + public const string SectionBlocks = "block"; + public const string SectionAllow = "allow"; + public const string SectionRules = "rule"; + public const string SectionCountries = "country"; + public const string SectionPolicy = "policy"; + public const string SectionConfig = "config"; + + public static readonly string[] Sections = + [SectionBlocks, SectionAllow, SectionRules, SectionCountries, SectionPolicy, SectionConfig]; + + public const string ActionAdded = "added"; + public const string ActionRemoved = "removed"; + public const string ActionChanged = "changed"; + public const string ActionImported = "imported"; + + public static readonly string[] Actions = [ActionAdded, ActionRemoved, ActionChanged, ActionImported]; + + public const string ActorOperator = "operator"; + public const string ActorImport = "import"; + + /// The target column is the width of every other source key in the + /// schema, so a target that would not fit a block row would not fit here + /// either. + public const int MaxTargetLength = 128; + + /// Detail is the operator's sentence, not a payload. A note that + /// arrives over the cap is clipped rather than refused: the change happened, + /// and a record that drops the change because the sentence was long is the + /// worse failure. + public const int MaxDetailLength = 512; + + /// Is this a section the log knows? A filter that names something + /// else is answered by the vocabulary rather than by an empty list, because + /// an empty list reads as "no such change" and the truth is "no such + /// section". + public static bool IsSection(string? section) => section is not null && Sections.Contains(section); + + public static bool IsAction(string? action) => action is not null && Actions.Contains(action); + + /// Clip to the column width. Never throws: the change has already + /// been applied by the time the record is written, so nothing about the + /// record may fail on the shape of a sentence. + public static string Clip(string? value, int max) + { + if (string.IsNullOrWhiteSpace(value)) return ""; + var trimmed = value.Trim(); + return trimmed.Length <= max ? trimmed : trimmed[..max]; + } +} diff --git a/dotnet/OpenWaf.Edge/Admin/AdminEndpoints.ConfigTransfer.cs b/dotnet/OpenWaf.Edge/Admin/AdminEndpoints.ConfigTransfer.cs index 5d47ec1..cd09e2c 100644 --- a/dotnet/OpenWaf.Edge/Admin/AdminEndpoints.ConfigTransfer.cs +++ b/dotnet/OpenWaf.Edge/Admin/AdminEndpoints.ConfigTransfer.cs @@ -119,7 +119,8 @@ internal static partial class AdminEndpoints + "read-only one")); group.MapPost("/import", async (OpenWafDbContext db, EdgeStateStore state, EdgePolicyProvider policy, - IStreakTracker streaks, RateTracker rates, BlockStore blocks, HttpContext ctx, CancellationToken ct) => + IStreakTracker streaks, RateTracker rates, BlockStore blocks, ConfigChangeWriter changes, + HttpContext ctx, CancellationToken ct) => { if (!TryKnownQuery(ctx, out var unknown)) return Results.BadRequest(new { error = unknown }); if (ctx.Request.ContentLength is { } declared && declared > ConfigTransfer.MaxBodyBytes) @@ -368,6 +369,29 @@ internal static partial class AdminEndpoints // this API already refuses to have. if (blocksAdded + allowAdded + rulesAdded + countriesAdded > 0) await state.InvalidateAsync(ct); + // The change log (OPEN-64): one record per section that carried + // something, not one per imported item. A 2 000-row document would + // otherwise bury the table whose whole use is being readable, and + // the sentence an operator asks — "did a document bring this edge's + // rules?" — is answered by the section row either way. + foreach (var (section, added, there, expired, rejectedCount) in new[] + { + (ConfigChangeLog.SectionBlocks, blocksAdded, blocksThere, blocksExpired, blocksRejected), + (ConfigChangeLog.SectionAllow, allowAdded, allowThere, allowExpired, allowRejected), + (ConfigChangeLog.SectionRules, rulesAdded, rulesThere, rulesExpired, rulesRejected), + (ConfigChangeLog.SectionCountries, countriesAdded, countriesThere, countriesExpired, countriesRejected) + }) + { + if (added + there + expired + rejectedCount == 0) continue; + await changes.RecordAsync(section, ConfigChangeLog.ActionImported, section, + $"{added} added, {there} already there, {expired} past expiry, {rejectedCount} rejected", + ConfigChangeLog.ActorImport, ct); + } + if (policyApplied || policyError is not null) + await changes.RecordAsync(ConfigChangeLog.SectionPolicy, ConfigChangeLog.ActionImported, "policy", + policyApplied ? $"{policyFields} fields applied from the document" : policyError, + ConfigChangeLog.ActorImport, ct); + var report = new { version = ConfigTransfer.CurrentVersion, @@ -392,6 +416,43 @@ internal static partial class AdminEndpoints }); } + /// + /// What a policy write changed, in one sentence (OPEN-64). The record says + /// what moved rather than only that something did: "the policy was changed" + /// tells an operator nothing about what happened at 03:00. + /// + private static string PolicyChangeSentence(OpenWaf.Domain.Policy.EdgePolicy before, + OpenWaf.Domain.Policy.EdgePolicy after) + { + var moved = new List(); + if (before.Mode != after.Mode) moved.Add($"mode {before.Mode}->{after.Mode}"); + if (before.StreakThreshold != after.StreakThreshold) + moved.Add($"streakThreshold {before.StreakThreshold}->{after.StreakThreshold}"); + if (before.StreakWindow != after.StreakWindow) + moved.Add($"streakWindow {before.StreakWindow}->{after.StreakWindow}"); + if (before.BanDuration != after.BanDuration) + moved.Add($"banDuration {before.BanDuration}->{after.BanDuration}"); + if (before.RefusalRange != after.RefusalRange) + moved.Add($"refusalRange {before.RefusalRange}->{after.RefusalRange}"); + if (before.ServerErrorRange != after.ServerErrorRange) + moved.Add($"serverErrorRange {before.ServerErrorRange}->{after.ServerErrorRange}"); + if (before.Geo != after.Geo) moved.Add($"geo {before.Geo}->{after.Geo}"); + if (before.TrustProxyHeaders != after.TrustProxyHeaders) + moved.Add($"trustProxyHeaders {before.TrustProxyHeaders}->{after.TrustProxyHeaders}"); + if (before.MaxTrackedSources != after.MaxTrackedSources) + moved.Add($"maxTrackedSources {before.MaxTrackedSources}->{after.MaxTrackedSources}"); + if (before.EngineBlockStatus != after.EngineBlockStatus) + moved.Add($"engineBlockStatus {before.EngineBlockStatus}->{after.EngineBlockStatus}"); + if (before.OperatorBlockStatus != after.OperatorBlockStatus) + moved.Add($"operatorBlockStatus {before.OperatorBlockStatus}->{after.OperatorBlockStatus}"); + if (before.Rate != after.Rate) moved.Add($"rate {before.Rate}->{after.Rate}"); + if (before.RateLimitPerWindow != after.RateLimitPerWindow) + moved.Add($"rateLimitPerWindow {before.RateLimitPerWindow}->{after.RateLimitPerWindow}"); + if (!before.DefaultRedirectTargets.SequenceEqual(after.DefaultRedirectTargets)) + moved.Add("redirectTargets changed"); + return moved.Count == 0 ? "no field changed" : string.Join(", ", moved); + } + /// /// The one place a policy request becomes the overrides the policy store /// keeps. PUT /admin-api/policy and the policy section of an diff --git a/dotnet/OpenWaf.Edge/Admin/AdminEndpoints.cs b/dotnet/OpenWaf.Edge/Admin/AdminEndpoints.cs index 04371e0..4916b39 100644 --- a/dotnet/OpenWaf.Edge/Admin/AdminEndpoints.cs +++ b/dotnet/OpenWaf.Edge/Admin/AdminEndpoints.cs @@ -53,7 +53,7 @@ internal static partial class AdminEndpoints return Results.Ok(rows.Select(r => r.ToDto(now))); }); - group.MapPost("/blocks", async (NewBlockRequest req, BlockStore store, HttpContext ctx, CancellationToken ct) => + group.MapPost("/blocks", async (NewBlockRequest req, BlockStore store, ConfigChangeWriter changes, HttpContext ctx, CancellationToken ct) => { if (!TryKnownQuery(ctx, out var unknown)) return Results.BadRequest(new { error = unknown }); if (string.IsNullOrWhiteSpace(req.Ip)) return Results.BadRequest(new { error = "ip is required" }); @@ -80,17 +80,24 @@ internal static partial class AdminEndpoints // by editing the request, the other by fixing the database, and a // 400 tells the operator to do the first while the block they asked // for is not in effect. - return added switch - { - BlockStore.AddResult.Ok => Results.NoContent(), - BlockStore.AddResult.InvalidInput => Results.BadRequest(new { error }), - _ => StorageUnavailable(error!) - }; + if (added != BlockStore.AddResult.Ok) + return added switch + { + BlockStore.AddResult.InvalidInput => Results.BadRequest(new { error }), + _ => StorageUnavailable(error!) + }; + // The record of the change (OPEN-64). After the change, never + // instead of it: a rule the operator believes they have is the worse + // failure, so a record that cannot be written is counted and the + // request still answers what it means. + await changes.RecordAsync(ConfigChangeLog.SectionBlocks, ConfigChangeLog.ActionAdded, + req.Ip, req.Reason, ct: ct); + return Results.NoContent(); }); // Provenance is part of the delete, not an afterthought: "clear the // automatic bans" must never be able to erase an operator's list. - group.MapDelete("/blocks", async (string? source, string? key, BlockStore store, HttpContext ctx, CancellationToken ct) => + group.MapDelete("/blocks", async (string? source, string? key, BlockStore store, ConfigChangeWriter changes, HttpContext ctx, CancellationToken ct) => { if (!TryKnownQuery(ctx, out var unknown, "source", "key")) return Results.BadRequest(new { error = unknown }); if (!TryParseSource(source, out var parsed)) return BadSource(source); @@ -104,6 +111,9 @@ internal static partial class AdminEndpoints // remove", which is how an operator stops trusting the count. if (result == BlockStore.DeleteResult.StorageFailure) return StorageUnavailable("the block list could not be read or written: NOTHING was deleted"); + if (n > 0) + await changes.RecordAsync(ConfigChangeLog.SectionBlocks, ConfigChangeLog.ActionRemoved, + key ?? parsed?.ToString().ToLowerInvariant() ?? "all", $"deleted {n}", ct: ct); return Results.Ok(new { deleted = n }); }); @@ -144,7 +154,7 @@ internal static partial class AdminEndpoints return Results.Ok(rows); }); - group.MapPost("/allow", async (NewAllowRequest req, OpenWafDbContext db, EdgeStateStore state, HttpContext ctx, CancellationToken ct) => + group.MapPost("/allow", async (NewAllowRequest req, OpenWafDbContext db, EdgeStateStore state, ConfigChangeWriter changes, HttpContext ctx, CancellationToken ct) => { if (!TryKnownQuery(ctx, out var unknown)) return Results.BadRequest(new { error = unknown }); if (string.IsNullOrWhiteSpace(req.Match) || !IsValidMatch(req.Match)) @@ -168,10 +178,12 @@ internal static partial class AdminEndpoints }); await db.SaveChangesAsync(ct); await state.InvalidateAsync(ct); + await changes.RecordAsync(ConfigChangeLog.SectionAllow, ConfigChangeLog.ActionAdded, + req.Match.Trim(), req.Note, ct: ct); return Results.NoContent(); }); - group.MapDelete("/allow/{id:long}", async (long id, OpenWafDbContext db, EdgeStateStore state, HttpContext ctx, CancellationToken ct) => + group.MapDelete("/allow/{id:long}", async (long id, OpenWafDbContext db, EdgeStateStore state, ConfigChangeWriter changes, HttpContext ctx, CancellationToken ct) => { if (!TryKnownQuery(ctx, out var unknown)) return Results.BadRequest(new { error = unknown }); var n = await db.AllowEntries.Where(a => a.Id == id).ExecuteDeleteAsync(ct); @@ -180,9 +192,10 @@ internal static partial class AdminEndpoints // answered 404 with Content-Length: 0, so the same API explained one // missing row and said nothing about another — and an empty 404 is // exactly the answer a page then has to guess about. - return n > 0 - ? Results.NoContent() - : Results.NotFound(new { error = $"no allow entry with id {id}" }); + if (n == 0) return Results.NotFound(new { error = $"no allow entry with id {id}" }); + await changes.RecordAsync(ConfigChangeLog.SectionAllow, ConfigChangeLog.ActionRemoved, + id.ToString(), ct: ct); + return Results.NoContent(); }); // Request rules: the one pillar that looks at the request itself @@ -217,7 +230,7 @@ internal static partial class AdminEndpoints matches.TryGetValue(r.Id, out var m) ? m : 0)).ToList()); }); - group.MapPost("/rules", async (NewRuleRequest req, OpenWafDbContext db, EdgeStateStore state, HttpContext ctx, CancellationToken ct) => + group.MapPost("/rules", async (NewRuleRequest req, OpenWafDbContext db, EdgeStateStore state, ConfigChangeWriter changes, HttpContext ctx, CancellationToken ct) => { if (!TryKnownQuery(ctx, out var unknown)) return Results.BadRequest(new { error = unknown }); // A pattern that can never match is refused here rather than listed @@ -256,17 +269,20 @@ internal static partial class AdminEndpoints }); await db.SaveChangesAsync(ct); await state.InvalidateAsync(ct); + await changes.RecordAsync(ConfigChangeLog.SectionRules, ConfigChangeLog.ActionAdded, + pattern, $"{action}{(string.IsNullOrWhiteSpace(req.Note) ? "" : $": {req.Note}")}", ct: ct); return Results.NoContent(); }); - group.MapDelete("/rules/{id:long}", async (long id, OpenWafDbContext db, EdgeStateStore state, HttpContext ctx, CancellationToken ct) => + group.MapDelete("/rules/{id:long}", async (long id, OpenWafDbContext db, EdgeStateStore state, ConfigChangeWriter changes, HttpContext ctx, CancellationToken ct) => { if (!TryKnownQuery(ctx, out var unknown)) return Results.BadRequest(new { error = unknown }); var n = await db.RequestRules.Where(r => r.Id == id).ExecuteDeleteAsync(ct); await state.InvalidateAsync(ct); - return n > 0 - ? Results.NoContent() - : Results.NotFound(new { error = $"no request rule with id {id}" }); + if (n == 0) return Results.NotFound(new { error = $"no request rule with id {id}" }); + await changes.RecordAsync(ConfigChangeLog.SectionRules, ConfigChangeLog.ActionRemoved, + id.ToString(), ct: ct); + return Results.NoContent(); }); // The policy answer carries its provenance in headers, the same way a @@ -285,7 +301,7 @@ internal static partial class AdminEndpoints }); group.MapPut("/policy", async (PolicyUpdateRequest req, EdgePolicyProvider policy, EdgeStateStore state, - IStreakTracker streaks, RateTracker rates, HttpContext ctx, CancellationToken ct) => + IStreakTracker streaks, RateTracker rates, ConfigChangeWriter changes, HttpContext ctx, CancellationToken ct) => { if (!TryKnownQuery(ctx, out var unknown)) return Results.BadRequest(new { error = unknown }); // The same path an imported document's `policy` section goes through: @@ -302,6 +318,10 @@ internal static partial class AdminEndpoints if (!PolicyOverrides(req, out var overrides, out var problem)) return Results.BadRequest(new { error = problem! }); + // The policy before the write, so the record can say what changed + // rather than only that something did. + var policyBefore = policy.Current; + // The toggle is a policy change, never a data change: switching // automatic banning off must leave every row — manual or engine — // exactly where it was. @@ -324,6 +344,8 @@ internal static partial class AdminEndpoints // answers with it. streaks.Configure(policy.Current); rates.Configure(policy.Current); + await changes.RecordAsync(ConfigChangeLog.SectionPolicy, ConfigChangeLog.ActionChanged, + "policy", PolicyChangeSentence(policyBefore, policy.Current), ct: ct); return Results.Ok(ToDto(policy.Current)); }); @@ -490,7 +512,7 @@ internal static partial class AdminEndpoints return Results.Ok(await db.CountryRules.AsNoTracking().OrderBy(c => c.Code).ToListAsync(ct)); }); - group.MapPut("/countries/{code}", async (string code, bool allowed, OpenWafDbContext db, EdgeStateStore state, HttpContext ctx, CancellationToken ct) => + group.MapPut("/countries/{code}", async (string code, bool allowed, OpenWafDbContext db, EdgeStateStore state, ConfigChangeWriter changes, HttpContext ctx, CancellationToken ct) => { if (!TryKnownQuery(ctx, out var unknown, "allowed")) return Results.BadRequest(new { error = unknown }); if (!TryCountryCode(code, out var normalized, out var codeError)) @@ -500,6 +522,8 @@ internal static partial class AdminEndpoints else { row.IsAllowed = allowed; row.UpdatedAt = DateTimeOffset.UtcNow; } await db.SaveChangesAsync(ct); await state.InvalidateAsync(ct); + await changes.RecordAsync(ConfigChangeLog.SectionCountries, ConfigChangeLog.ActionChanged, + normalized, allowed ? "allowed" : "denied", ct: ct); return Results.NoContent(); }); @@ -508,7 +532,7 @@ internal static partial class AdminEndpoints // remove one at all, which is what made a mistyped code permanent — the // console gate's own comment used to read "a country rule cannot be // deleted, only overwritten". - group.MapDelete("/countries/{code}", async (string code, OpenWafDbContext db, EdgeStateStore state, HttpContext ctx, CancellationToken ct) => + group.MapDelete("/countries/{code}", async (string code, OpenWafDbContext db, EdgeStateStore state, ConfigChangeWriter changes, HttpContext ctx, CancellationToken ct) => { if (!TryKnownQuery(ctx, out var unknown)) return Results.BadRequest(new { error = unknown }); if (!TryCountryCode(code, out var normalized, out var codeError)) @@ -518,6 +542,8 @@ internal static partial class AdminEndpoints db.CountryRules.Remove(row); await db.SaveChangesAsync(ct); await state.InvalidateAsync(ct); + await changes.RecordAsync(ConfigChangeLog.SectionCountries, ConfigChangeLog.ActionRemoved, + normalized, ct: ct); return Results.NoContent(); }); @@ -675,7 +701,41 @@ note = t.Note }); }); - group.MapGet("/state", async (EdgeStateStore state, EdgePolicyProvider policyProvider, IStreakTracker tracker, RateTracker rateTracker, DurabilityHealth durability, BlockStore blockStore, AlertNotifier notifier, SchemaUpgradeReport schema, HttpContext ctx, CancellationToken ct) => + // The record of deliberate changes to the operator's config (OPEN-64). + // Newest first, capped and paged like every other listing, and readable + // by the read-only token: it is a read, and a dashboard that can see the + // config should be able to see how it got there. + group.MapGet("/changes", async (string? section, DateTimeOffset? since, int? limit, int? offset, + OpenWafDbContext db, HttpContext ctx, CancellationToken ct) => + { + if (!TryKnownQuery(ctx, out var unknown, "section", "since", "limit", "offset")) + return Results.BadRequest(new { error = unknown }); + // An unknown section is answered by the vocabulary, not by an empty + // list: an empty list reads as "no such change happened", and the + // truth is "there is no such section". + if (!string.IsNullOrWhiteSpace(section) && !ConfigChangeLog.IsSection(section)) + return Results.BadRequest(new + { + error = $"section must be one of {string.Join(", ", ConfigChangeLog.Sections)}; got \"{section}\"" + }); + if (!TryPaging(limit, offset, ReadListDefaultLimit, ReadListMaxLimit, + out var take, out var skip, out var pagingError)) + return Results.BadRequest(new { error = pagingError }); + + var query = db.ConfigChanges.AsNoTracking(); + if (!string.IsNullOrWhiteSpace(section)) query = query.Where(c => c.Section == section); + if (since is { } from) query = query.Where(c => c.At >= from); + var total = await query.CountAsync(ct); + // Ordered by id, not by the instant: two changes inside the same + // millisecond have an order, and the id is the one the database + // actually applied them in. + var rows = await query.OrderByDescending(c => c.Id).Skip(skip).Take(take).ToListAsync(ct); + ctx.Response.Headers["X-Total-Count"] = total.ToString(); + ctx.Response.Headers["X-Truncated"] = (skip + rows.Count < total).ToString().ToLowerInvariant(); + return Results.Ok(rows); + }); + + group.MapGet("/state", async (EdgeStateStore state, EdgePolicyProvider policyProvider, IStreakTracker tracker, RateTracker rateTracker, DurabilityHealth durability, BlockStore blockStore, AlertNotifier notifier, SchemaUpgradeReport schema, OpenWafDbContext db, HttpContext ctx, CancellationToken ct) => { if (!TryKnownQuery(ctx, out var unknown)) return Results.BadRequest(new { error = unknown }); var now = DateTimeOffset.UtcNow; @@ -738,6 +798,14 @@ note = t.Note // recovered by a later successful write. // The enforcement-path write, counted separately because it gates // readiness, unlike the reporting pillars below it. + // The change log (OPEN-64): how many records the edge holds, and + // whether the last ones actually landed. A change whose record did + // not land is a hole in the only answer the table exists to give. + configChanges = await db.ConfigChanges.CountAsync(ct), + changeWriteFailures = durability.Get(DurabilityHealth.Changes).Failures, + changesNotWritten = durability.Get(DurabilityHealth.Changes).EntriesLost, + changeLastWriteAt = durability.Get(DurabilityHealth.Changes).LastSuccessAt, + changeLastError = durability.Get(DurabilityHealth.Changes).LastError, banWriteFailures = durability.Get(DurabilityHealth.Bans).Failures, bansNotWritten = durability.Get(DurabilityHealth.Bans).EntriesLost, banLastWriteError = durability.Get(DurabilityHealth.Bans).LastError, diff --git a/dotnet/OpenWaf.Edge/Configuration/EdgePolicyOptions.cs b/dotnet/OpenWaf.Edge/Configuration/EdgePolicyOptions.cs index 202a14f..c8df469 100644 --- a/dotnet/OpenWaf.Edge/Configuration/EdgePolicyOptions.cs +++ b/dotnet/OpenWaf.Edge/Configuration/EdgePolicyOptions.cs @@ -59,8 +59,18 @@ internal sealed class EdgePolicyOptions public int ObservationRetentionDays { get; set; } = 7; public int BanRetentionDays { get; set; } = 7; + // The change log (OPEN-64) is bounded twice, and both bounds are the + // operator's: an age window, and a row cap that holds even inside the + // window. The age window alone would let a scripted churn grow the table + // without limit; the cap alone would drop last month's incident record the + // week someone did a lot of editing. + public int ChangeRetentionDays { get; set; } = 30; + public int ChangeLogMaxRows { get; set; } = 5000; + public const int RetentionDaysFloor = 1; public const int RetentionDaysCeiling = 365; + public const int ChangeLogRowsFloor = 100; + public const int ChangeLogRowsCeiling = 100_000; public EdgePolicy ToPolicy() => new() { @@ -85,7 +95,9 @@ internal sealed class EdgePolicyOptions ? new[] { "https://www.iana.org/help/example-domains" } : DefaultRedirectTargets, ObservationRetention = RetentionDays(ObservationRetentionDays, "OpenWaf:Policy:ObservationRetentionDays"), - BanRetention = RetentionDays(BanRetentionDays, "OpenWaf:Policy:BanRetentionDays") + BanRetention = RetentionDays(BanRetentionDays, "OpenWaf:Policy:BanRetentionDays"), + ChangeRetention = RetentionDays(ChangeRetentionDays, "OpenWaf:Policy:ChangeRetentionDays"), + ChangeLogMaxRows = ChangeLogRows(ChangeLogMaxRows, "OpenWaf:Policy:ChangeLogMaxRows") }; private static int RateWindowLimit(int v) @@ -115,6 +127,18 @@ internal sealed class EdgePolicyOptions return TimeSpan.FromDays(days); } + /// Whole rows, 100..100 000. A cap below 100 would drop the record + /// of the very edits it exists to remember, and a cap that high is not a + /// bound, it is a table the operator cannot read. + private static int ChangeLogRows(int rows, string configKey) + { + if (rows < ChangeLogRowsFloor || rows > ChangeLogRowsCeiling) + throw new InvalidOperationException( + $"{configKey} must be a whole number of rows between {ChangeLogRowsFloor} and " + + $"{ChangeLogRowsCeiling}; got {rows}"); + return rows; + } + /// Accepts both 00:05:00 and a bare number of minutes. private static TimeSpan ParseWindow(string value, TimeSpan fallback) { diff --git a/dotnet/OpenWaf.Edge/Program.cs b/dotnet/OpenWaf.Edge/Program.cs index ff552ad..16336d3 100644 --- a/dotnet/OpenWaf.Edge/Program.cs +++ b/dotnet/OpenWaf.Edge/Program.cs @@ -115,6 +115,11 @@ builder.Services.AddSingleton(sp => new AlertNotifier( alertWebhookUrl, alertWebhookTimeout, alertPushAttempts, alertPushRetrySeconds)); builder.Services.AddHostedService(sp => sp.GetRequiredService()); builder.Services.AddSingleton(); +// The record of a deliberate config change (OPEN-64). Best-effort by design: +// the change has already been applied when this writes, and a change refused +// because its record would not land is a change the operator believes they +// have and does not have. +builder.Services.AddSingleton(); // An empty string in appsettings.json is not the same as "unset" to the // configuration system, and it silently defeats the environment fallback — // which is exactly how a geo database ends up missing in production. diff --git a/dotnet/OpenWaf.Infrastructure/Persistence/ConfigChangeWriter.cs b/dotnet/OpenWaf.Infrastructure/Persistence/ConfigChangeWriter.cs new file mode 100644 index 0000000..453dbc7 --- /dev/null +++ b/dotnet/OpenWaf.Infrastructure/Persistence/ConfigChangeWriter.cs @@ -0,0 +1,73 @@ +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using OpenWaf.Domain.Security; + +namespace OpenWaf.Infrastructure.Persistence; + +/// +/// Writes the record of a deliberate config change (OPEN-64). +/// +/// The posture is the one thing to read here. The change has already been +/// applied by the time this runs — enforcement is the product, and a rule that +/// was refused because its audit row would not fit is a rule the operator +/// believes they have and does not. So a failed record never rolls the change +/// back and never fails the request. What it does instead is get counted: +/// changeWriteFailures and changesNotWritten on /admin-api/state, +/// the same shape the other durable pillars have, because "the config changed +/// and the record of it did not land" has to be a sentence the operator can +/// read rather than one that silently never happened. +/// +public sealed class ConfigChangeWriter +{ + private readonly IServiceScopeFactory _scopeFactory; + private readonly DurabilityHealth _health; + private readonly ILogger _log; + + public ConfigChangeWriter(IServiceScopeFactory scopeFactory, DurabilityHealth health, + ILogger log) + { + _scopeFactory = scopeFactory; + _health = health; + _log = log; + } + + /// Record one change. Returns whether the row landed — the caller + /// does not act on the answer, and that is deliberate: the only thing a + /// caller could do with a false is undo a change the operator made. + public async Task RecordAsync( + string section, string action, string target, string? detail = null, + string actor = ConfigChangeLog.ActorOperator, CancellationToken ct = default) + { + var row = new ConfigChange + { + At = DateTimeOffset.UtcNow, + Section = section, + Action = action, + // Clipped, never refused: the change happened, and a record that + // drops it because a sentence was long is the worse failure. + Target = ConfigChangeLog.Clip(target, ConfigChangeLog.MaxTargetLength), + Detail = string.IsNullOrWhiteSpace(detail) + ? null + : ConfigChangeLog.Clip(detail, ConfigChangeLog.MaxDetailLength), + Actor = actor + }; + + try + { + using var scope = _scopeFactory.CreateScope(); + var db = scope.ServiceProvider.GetRequiredService(); + db.ConfigChanges.Add(row); + await db.SaveChangesAsync(ct); + _health.RecordSuccess(DurabilityHealth.Changes, 1); + return true; + } + catch (Exception ex) + { + _health.RecordFailure(DurabilityHealth.Changes, ex, 1); + _log.LogWarning(ex, "ConfigChangeWriter: the record of a {Section} {Action} did not land.", + section, action); + return false; + } + } +} diff --git a/dotnet/OpenWaf.Infrastructure/Persistence/DurabilityHealth.cs b/dotnet/OpenWaf.Infrastructure/Persistence/DurabilityHealth.cs index 77c9f2f..f143b1a 100644 --- a/dotnet/OpenWaf.Infrastructure/Persistence/DurabilityHealth.cs +++ b/dotnet/OpenWaf.Infrastructure/Persistence/DurabilityHealth.cs @@ -37,6 +37,14 @@ public sealed class DurabilityHealth public const string Alerts = "alerts"; public const string Retention = "retention"; + /// + /// The change log (OPEN-64). Counted because a change whose record did not + /// land is a hole in the only answer the table exists to give, and counted + /// separately from the enforcement writes because the change itself still + /// applied — the loss is the memory, not the decision. + /// + public const string Changes = "changes"; + /// /// The engine's ban writes. Counted separately from the reporting pillars /// because it is the only write on the enforcement path: a ban that never diff --git a/dotnet/OpenWaf.Infrastructure/Persistence/Migrations/20261005032702_AddConfigChangeLog.Designer.cs b/dotnet/OpenWaf.Infrastructure/Persistence/Migrations/20261005032702_AddConfigChangeLog.Designer.cs new file mode 100644 index 0000000..4e3d538 --- /dev/null +++ b/dotnet/OpenWaf.Infrastructure/Persistence/Migrations/20261005032702_AddConfigChangeLog.Designer.cs @@ -0,0 +1,479 @@ +// +using System; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; +using OpenWaf.Infrastructure.Persistence; + +#nullable disable + +namespace OpenWaf.Infrastructure.Persistence.Migrations +{ + [DbContext(typeof(OpenWafDbContext))] + [Migration("20261005032702_AddConfigChangeLog")] + partial class AddConfigChangeLog + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "10.0.0") + .HasAnnotation("Relational:MaxIdentifierLength", 63); + + NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); + + modelBuilder.Entity("OpenWaf.Domain.Policy.CountryRule", b => + { + b.Property("Code") + .HasMaxLength(2) + .HasColumnType("character varying(2)"); + + b.Property("IsAllowed") + .HasColumnType("boolean"); + + b.Property("Name") + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("UpdatedAt") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Code"); + + b.ToTable("country_rules", (string)null); + }); + + modelBuilder.Entity("OpenWaf.Domain.Security.AlertPush", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("AlertCreatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("AlertId") + .HasColumnType("bigint"); + + b.Property("Attempts") + .HasColumnType("integer"); + + b.Property("ClaimedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("ClaimedBy") + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("Count") + .HasColumnType("integer"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("Detail") + .IsRequired() + .HasMaxLength(1024) + .HasColumnType("character varying(1024)"); + + b.Property("GivenUpAt") + .HasColumnType("timestamp with time zone"); + + b.Property("Kind") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("LastError") + .HasMaxLength(512) + .HasColumnType("character varying(512)"); + + b.Property("LastPath") + .HasColumnType("text"); + + b.Property("LastStatusCode") + .HasColumnType("integer"); + + b.Property("NextAttemptAt") + .HasColumnType("timestamp with time zone"); + + b.Property("PushedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("SourceKey") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.HasKey("Id"); + + b.HasIndex("AlertId"); + + b.HasIndex("PushedAt", "GivenUpAt", "NextAttemptAt"); + + b.ToTable("alert_pushes", (string)null); + }); + + modelBuilder.Entity("OpenWaf.Domain.Security.AllowEntry", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("ExpiresAt") + .HasColumnType("timestamp with time zone"); + + b.Property("Match") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("Note") + .HasMaxLength(512) + .HasColumnType("character varying(512)"); + + b.HasKey("Id"); + + b.HasIndex("Match") + .IsUnique(); + + b.ToTable("allow_entries", (string)null); + }); + + modelBuilder.Entity("OpenWaf.Domain.Security.BlockEntry", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ConsecutiveRefusals") + .HasColumnType("integer"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("ExpiresAt") + .HasColumnType("timestamp with time zone"); + + b.Property("LastCity") + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("LastCountryCode") + .HasMaxLength(2) + .HasColumnType("character varying(2)"); + + b.Property("LastPath") + .HasMaxLength(512) + .HasColumnType("character varying(512)"); + + b.Property("LastRegion") + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("LastStatusCode") + .HasColumnType("integer"); + + b.Property("LastUserAgent") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("Reason") + .HasMaxLength(1024) + .HasColumnType("character varying(1024)"); + + b.Property("RedirectTo") + .HasMaxLength(512) + .HasColumnType("character varying(512)"); + + b.Property("Source") + .HasColumnType("integer"); + + b.Property("SourceKey") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.HasKey("Id"); + + b.HasIndex("ExpiresAt"); + + b.HasIndex("SourceKey", "Source") + .IsUnique(); + + b.ToTable("block_entries", (string)null); + }); + + modelBuilder.Entity("OpenWaf.Domain.Security.ConfigChange", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Action") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("character varying(16)"); + + b.Property("Actor") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("character varying(16)"); + + b.Property("At") + .HasColumnType("timestamp with time zone"); + + b.Property("Detail") + .HasMaxLength(512) + .HasColumnType("character varying(512)"); + + b.Property("Section") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("character varying(16)"); + + b.Property("Target") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.HasKey("Id"); + + b.HasIndex("At"); + + b.HasIndex("Section"); + + b.ToTable("config_changes", (string)null); + }); + + modelBuilder.Entity("OpenWaf.Domain.Security.EdgeAlert", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Count") + .HasColumnType("integer"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("Detail") + .IsRequired() + .HasMaxLength(1024) + .HasColumnType("character varying(1024)"); + + b.Property("Kind") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("LastPath") + .HasColumnType("text"); + + b.Property("LastStatusCode") + .HasColumnType("integer"); + + b.Property("SourceKey") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.HasKey("Id"); + + b.HasIndex("CreatedAt"); + + b.ToTable("edge_alerts", (string)null); + }); + + modelBuilder.Entity("OpenWaf.Domain.Security.RequestRule", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Action") + .HasColumnType("integer"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("ExpiresAt") + .HasColumnType("timestamp with time zone"); + + b.Property("Note") + .HasMaxLength(512) + .HasColumnType("character varying(512)"); + + b.Property("Pattern") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Id"); + + b.HasIndex("ExpiresAt"); + + b.HasIndex("Pattern"); + + b.ToTable("request_rules", (string)null); + }); + + modelBuilder.Entity("OpenWaf.Domain.Security.SourceObservation", b => + { + b.Property("SourceKey") + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("FirstSeenAt") + .HasColumnType("timestamp with time zone"); + + b.Property("LastCity") + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("LastCountryCode") + .HasMaxLength(2) + .HasColumnType("character varying(2)"); + + b.Property("LastPath") + .HasMaxLength(512) + .HasColumnType("character varying(512)"); + + b.Property("LastRegion") + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("LastSeenAt") + .HasColumnType("timestamp with time zone"); + + b.Property("LastStatusCode") + .HasColumnType("integer"); + + b.Property("LastUserAgent") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("MaxConsecutiveRefusals") + .HasColumnType("integer"); + + b.Property("TotalRefusals") + .HasColumnType("integer"); + + b.Property("TotalServerErrorStreak") + .HasColumnType("integer"); + + b.HasKey("SourceKey"); + + b.HasIndex("LastSeenAt"); + + b.ToTable("source_observations", (string)null); + }); + + modelBuilder.Entity("OpenWaf.Domain.Security.SourceStreak", b => + { + b.Property("SourceKey") + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("ConsecutiveRefusals") + .HasColumnType("integer"); + + b.Property("ConsecutiveServerErrors") + .HasColumnType("integer"); + + b.Property("LastAlertedRefusals") + .HasColumnType("integer"); + + b.Property("LastAlertedServerErrors") + .HasColumnType("integer"); + + b.Property("LastCity") + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("LastCountryCode") + .HasMaxLength(2) + .HasColumnType("character varying(2)"); + + b.Property("LastPath") + .HasMaxLength(512) + .HasColumnType("character varying(512)"); + + b.Property("LastRefusalAt") + .HasColumnType("timestamp with time zone"); + + b.Property("LastRegion") + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("LastSeenAt") + .HasColumnType("timestamp with time zone"); + + b.Property("LastStatusCode") + .HasColumnType("integer"); + + b.Property("LastUserAgent") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("MaxConsecutiveRefusals") + .HasColumnType("integer"); + + b.Property("MaxConsecutiveServerErrors") + .HasColumnType("integer"); + + b.Property("TotalRefusals") + .HasColumnType("integer"); + + b.Property("Version") + .IsConcurrencyToken() + .HasColumnType("integer"); + + b.HasKey("SourceKey"); + + b.HasIndex("LastSeenAt"); + + b.ToTable("source_streaks", (string)null); + }); + + modelBuilder.Entity("OpenWaf.Infrastructure.Persistence.PolicySetting", b => + { + b.Property("Key") + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("UpdatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("Value") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Key"); + + b.ToTable("policy_settings", (string)null); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/dotnet/OpenWaf.Infrastructure/Persistence/Migrations/20261005032702_AddConfigChangeLog.cs b/dotnet/OpenWaf.Infrastructure/Persistence/Migrations/20261005032702_AddConfigChangeLog.cs new file mode 100644 index 0000000..8b968b2 --- /dev/null +++ b/dotnet/OpenWaf.Infrastructure/Persistence/Migrations/20261005032702_AddConfigChangeLog.cs @@ -0,0 +1,51 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; + +#nullable disable + +namespace OpenWaf.Infrastructure.Persistence.Migrations +{ + /// + public partial class AddConfigChangeLog : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "config_changes", + columns: table => new + { + Id = table.Column(type: "bigint", nullable: false) + .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn), + At = table.Column(type: "timestamp with time zone", nullable: false), + Section = table.Column(type: "character varying(16)", maxLength: 16, nullable: false), + Action = table.Column(type: "character varying(16)", maxLength: 16, nullable: false), + Target = table.Column(type: "character varying(128)", maxLength: 128, nullable: false), + Detail = table.Column(type: "character varying(512)", maxLength: 512, nullable: true), + Actor = table.Column(type: "character varying(16)", maxLength: 16, nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_config_changes", x => x.Id); + }); + + migrationBuilder.CreateIndex( + name: "IX_config_changes_At", + table: "config_changes", + column: "At"); + + migrationBuilder.CreateIndex( + name: "IX_config_changes_Section", + table: "config_changes", + column: "Section"); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "config_changes"); + } + } +} diff --git a/dotnet/OpenWaf.Infrastructure/Persistence/Migrations/OpenWafDbContextModelSnapshot.cs b/dotnet/OpenWaf.Infrastructure/Persistence/Migrations/OpenWafDbContextModelSnapshot.cs index 18fbf7e..bfe086a 100644 --- a/dotnet/OpenWaf.Infrastructure/Persistence/Migrations/OpenWafDbContextModelSnapshot.cs +++ b/dotnet/OpenWaf.Infrastructure/Persistence/Migrations/OpenWafDbContextModelSnapshot.cs @@ -213,6 +213,50 @@ namespace OpenWaf.Infrastructure.Persistence.Migrations b.ToTable("block_entries", (string)null); }); + modelBuilder.Entity("OpenWaf.Domain.Security.ConfigChange", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Action") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("character varying(16)"); + + b.Property("Actor") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("character varying(16)"); + + b.Property("At") + .HasColumnType("timestamp with time zone"); + + b.Property("Detail") + .HasMaxLength(512) + .HasColumnType("character varying(512)"); + + b.Property("Section") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("character varying(16)"); + + b.Property("Target") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.HasKey("Id"); + + b.HasIndex("At"); + + b.HasIndex("Section"); + + b.ToTable("config_changes", (string)null); + }); + modelBuilder.Entity("OpenWaf.Domain.Security.EdgeAlert", b => { b.Property("Id") diff --git a/dotnet/OpenWaf.Infrastructure/Persistence/OpenWafDbContext.cs b/dotnet/OpenWaf.Infrastructure/Persistence/OpenWafDbContext.cs index 12038e7..af1b65c 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; /// -/// Eight tables, all small. The edge never queries them on the request path — +/// Ten 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. @@ -21,6 +21,7 @@ public sealed class OpenWafDbContext(DbContextOptions options) public DbSet Streaks => Set(); public DbSet RequestRules => Set(); public DbSet AlertPushes => Set(); + public DbSet ConfigChanges => Set(); protected override void OnModelCreating(ModelBuilder mb) { @@ -45,6 +46,23 @@ public sealed class OpenWafDbContext(DbContextOptions options) e.Property(b => b.Source).HasConversion(); }); + mb.Entity(e => + { + // The change log (OPEN-64): one row per deliberate change to the + // operator's config. Indexed on the instant because the surface + // reads newest first, and on the section because "what happened to + // the rules" is the question an operator actually asks. + e.ToTable("config_changes"); + e.HasKey(c => c.Id); + e.HasIndex(c => c.At); + e.HasIndex(c => c.Section); + e.Property(c => c.Section).HasMaxLength(16).IsRequired(); + e.Property(c => c.Action).HasMaxLength(16).IsRequired(); + e.Property(c => c.Target).HasMaxLength(ConfigChangeLog.MaxTargetLength).IsRequired(); + e.Property(c => c.Detail).HasMaxLength(ConfigChangeLog.MaxDetailLength); + e.Property(c => c.Actor).HasMaxLength(16).IsRequired(); + }); + mb.Entity(e => { e.ToTable("allow_entries"); diff --git a/dotnet/OpenWaf.Infrastructure/Persistence/RetentionWorker.cs b/dotnet/OpenWaf.Infrastructure/Persistence/RetentionWorker.cs index 18c9fbb..6a7fe38 100644 --- a/dotnet/OpenWaf.Infrastructure/Persistence/RetentionWorker.cs +++ b/dotnet/OpenWaf.Infrastructure/Persistence/RetentionWorker.cs @@ -70,6 +70,22 @@ public sealed class RetentionWorker : BackgroundService // 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); + + // The change log (OPEN-64) is bounded twice, and the second bound is + // the one the age window cannot provide: an operator scripting a + // thousand rule edits inside a week would otherwise grow a table + // whose whole use is being readable. The oldest rows go first, so + // what survives is the recent history an operator actually asks for. + var changeAge = now - policy.ChangeRetention; + await db.ConfigChanges.Where(c => c.At < changeAge).ExecuteDeleteAsync(ct); + var held = await db.ConfigChanges.CountAsync(ct); + var excess = held - policy.ChangeLogMaxRows; + if (excess > 0) + { + var oldest = await db.ConfigChanges.OrderBy(c => c.Id).Select(c => c.Id) + .Take(excess).ToListAsync(ct); + await db.ConfigChanges.Where(c => oldest.Contains(c.Id)).ExecuteDeleteAsync(ct); + } _health.RecordSuccess(DurabilityHealth.Retention); } catch (Exception ex) diff --git a/dotnet/OpenWaf.Tests.Integration/ConfigChangeRecordTests.cs b/dotnet/OpenWaf.Tests.Integration/ConfigChangeRecordTests.cs new file mode 100644 index 0000000..6671c18 --- /dev/null +++ b/dotnet/OpenWaf.Tests.Integration/ConfigChangeRecordTests.cs @@ -0,0 +1,294 @@ +using System.Net; +using System.Net.Http.Json; +using System.Text; +using System.Text.Json; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using OpenWaf.Domain.Security; +using OpenWaf.Infrastructure.Persistence; + +namespace OpenWaf.Tests.Integration; + +/// +/// The record of a deliberate change to the operator's config (OPEN-64). +/// +/// Every operator write already changes a row; what was missing is the answer to +/// "when did this get here, and did a document bring it". These tests ask the +/// surface, not the table, because the surface is what an operator reads at 03:00 +/// — and they ask the rulings, not the plumbing: an import is recorded per +/// section rather than per row, a record that cannot be written never undoes the +/// change it describes, and the log says which surface acted without claiming to +/// know which human. +/// +public sealed class ConfigChangeRecordTests +{ + private const string Blocked = "203.0.113.171"; + private const string Exempt = "203.0.113.172"; + private const string RulePath = "/wp-login*"; + + private static async Task ChangesAsync(EdgeFixture f, string query = "") + { + using var response = await f.Client.GetAsync( + $"/admin-api/changes?token={EdgeFixture.AdminToken}{query}"); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + return JsonDocument.Parse(await response.Content.ReadAsStringAsync()).RootElement.Clone(); + } + + private static async Task StateAsync(EdgeFixture f) + { + using var response = await f.Client.GetAsync($"/admin-api/state?token={EdgeFixture.AdminToken}"); + return JsonDocument.Parse(await response.Content.ReadAsStringAsync()).RootElement.Clone(); + } + + private static async Task ChangeCountAsync(EdgeFixture f) + { + using var scope = f.Factory.Services.CreateScope(); + return await scope.ServiceProvider.GetRequiredService().ConfigChanges.CountAsync(); + } + + [Fact] + public async Task An_operator_block_lands_a_record_that_names_the_ip_and_the_reason() + { + await using var f = new EdgeFixture(); + using (var write = await f.Client.PostAsJsonAsync( + $"/admin-api/blocks?token={EdgeFixture.AdminToken}", + new { ip = Blocked, reason = "incident: confirmed scraper" })) + Assert.Equal(HttpStatusCode.NoContent, write.StatusCode); + + var rows = await ChangesAsync(f); + Assert.Equal(1, rows.GetArrayLength()); + var row = rows[0]; + Assert.Equal("block", row.GetProperty("section").GetString()); + Assert.Equal("added", row.GetProperty("action").GetString()); + Assert.Equal(Blocked, row.GetProperty("target").GetString()); + Assert.Equal("incident: confirmed scraper", row.GetProperty("detail").GetString()); + // The surface, not a person: the edge has one admin token, and a record + // that named a human it cannot identify would be a false record. + Assert.Equal("operator", row.GetProperty("actor").GetString()); + } + + [Fact] + public async Task A_removal_is_recorded_as_a_removal() + { + await using var f = new EdgeFixture(); + using (var write = await f.Client.PostAsJsonAsync( + $"/admin-api/blocks?token={EdgeFixture.AdminToken}", new { ip = Blocked })) + Assert.Equal(HttpStatusCode.NoContent, write.StatusCode); + using (var removed = await f.Client.DeleteAsync( + $"/admin-api/blocks?source=operator&key={Blocked}&token={EdgeFixture.AdminToken}")) + Assert.Equal(HttpStatusCode.OK, removed.StatusCode); + + var rows = await ChangesAsync(f, "§ion=block"); + Assert.Equal(2, rows.GetArrayLength()); + // Newest first: the removal is the first row the operator sees. + Assert.Equal("removed", rows[0].GetProperty("action").GetString()); + Assert.Equal("added", rows[1].GetProperty("action").GetString()); + } + + [Fact] + public async Task A_policy_write_records_what_moved_not_only_that_something_did() + { + await using var f = new EdgeFixture(mode: "Enforce"); + using (var write = await f.Client.PutAsJsonAsync( + $"/admin-api/policy?token={EdgeFixture.AdminToken}", new { mode = "Off" })) + Assert.Equal(HttpStatusCode.OK, write.StatusCode); + + var rows = await ChangesAsync(f, "§ion=policy"); + Assert.Equal(1, rows.GetArrayLength()); + var detail = rows[0].GetProperty("detail").GetString(); + Assert.Contains("mode Enforce->Off", detail); + Assert.Equal("changed", rows[0].GetProperty("action").GetString()); + } + + [Fact] + public async Task A_rule_an_exemption_and_a_country_decision_are_all_recorded() + { + await using var f = new EdgeFixture(); + using (var r = await f.Client.PostAsJsonAsync( + $"/admin-api/rules?token={EdgeFixture.AdminToken}", + new { pattern = RulePath, action = "block", note = "cms" })) + Assert.Equal(HttpStatusCode.NoContent, r.StatusCode); + using (var a = await f.Client.PostAsJsonAsync( + $"/admin-api/allow?token={EdgeFixture.AdminToken}", + new { match = Exempt, note = "office" })) + Assert.Equal(HttpStatusCode.NoContent, a.StatusCode); + using (var c = await f.Client.PutAsync( + $"/admin-api/countries/de?allowed=false&token={EdgeFixture.AdminToken}", null)) + Assert.Equal(HttpStatusCode.NoContent, c.StatusCode); + + var rows = await ChangesAsync(f); + var sections = rows.EnumerateArray().Select(x => x.GetProperty("section").GetString()).ToList(); + Assert.Contains("rule", sections); + Assert.Contains("allow", sections); + Assert.Contains("country", sections); + var rule = rows.EnumerateArray().First(x => x.GetProperty("section").GetString() == "rule"); + Assert.Equal(RulePath, rule.GetProperty("target").GetString()); + Assert.Contains("cms", rule.GetProperty("detail").GetString()); + } + + [Fact] + public async Task An_import_is_recorded_per_section_and_not_per_row() + { + await using var f = new EdgeFixture(readOnlyToken: EdgeFixture.ReadOnlyToken); + var document = JsonSerializer.Serialize(new + { + version = 1, + blocks = new object[] + { + new { ip = "203.0.113.173" }, new { ip = "203.0.113.174" }, new { ip = "203.0.113.175" } + } + }); + using var content = new StringContent(document, Encoding.UTF8, "application/json"); + using var imported = await f.Client.PostAsync( + $"/admin-api/import?token={EdgeFixture.AdminToken}", content); + Assert.Equal(HttpStatusCode.OK, imported.StatusCode); + + var rows = await ChangesAsync(f, "§ion=block"); + // Three rows arrived; one record says so. A 2 000-row document must not + // bury the table whose whole use is being readable. + Assert.Equal(1, rows.GetArrayLength()); + Assert.Equal("imported", rows[0].GetProperty("action").GetString()); + Assert.Equal("import", rows[0].GetProperty("actor").GetString()); + Assert.Contains("3 added", rows[0].GetProperty("detail").GetString()); + } + + [Fact] + public async Task The_read_only_token_can_read_the_log_because_it_is_a_read() + { + await using var f = new EdgeFixture(readOnlyToken: EdgeFixture.ReadOnlyToken); + using (var write = await f.Client.PostAsJsonAsync( + $"/admin-api/blocks?token={EdgeFixture.AdminToken}", new { ip = Blocked })) + Assert.Equal(HttpStatusCode.NoContent, write.StatusCode); + + using var request = new HttpRequestMessage(HttpMethod.Get, "/admin-api/changes"); + using var response = await f.Client.SendAsync(request); + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + + var asReadOnly = await ChangesAsync(f); + Assert.Equal(1, asReadOnly.GetArrayLength()); + } + + [Fact] + public async Task An_unknown_section_is_answered_by_the_vocabulary_not_by_an_empty_list() + { + await using var f = new EdgeFixture(); + using var response = await f.Client.GetAsync( + $"/admin-api/changes?section=traffic&token={EdgeFixture.AdminToken}"); + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + var body = await response.Content.ReadAsStringAsync(); + Assert.Contains("block, allow, rule, country, policy, config", body); + Assert.Contains("traffic", body); + } + + [Fact] + public async Task The_log_is_capped_and_says_when_it_is_truncated() + { + await using var f = new EdgeFixture(); + for (var i = 0; i < 5; i++) + using (var write = await f.Client.PostAsJsonAsync( + $"/admin-api/blocks?token={EdgeFixture.AdminToken}", new { ip = $"203.0.113.{180 + i}" })) + Assert.Equal(HttpStatusCode.NoContent, write.StatusCode); + + using var response = await f.Client.GetAsync( + $"/admin-api/changes?limit=2&token={EdgeFixture.AdminToken}"); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Equal("5", response.Headers.TryGetValues("X-Total-Count", out var total) ? total.Single() : ""); + Assert.Equal("true", response.Headers.TryGetValues("X-Truncated", out var trunc) ? trunc.Single() : ""); + using var page = JsonDocument.Parse(await response.Content.ReadAsStringAsync()); + Assert.Equal(2, page.RootElement.GetArrayLength()); + } + + [Fact] + public async Task A_record_that_cannot_be_written_never_undoes_the_change_and_is_counted() + { + await using var f = new EdgeFixture(); + using var scope = f.Factory.Services.CreateScope(); + var db = scope.ServiceProvider.GetRequiredService(); + await db.Database.ExecuteSqlRawAsync( + """CREATE TRIGGER "gate_changes_insert" BEFORE INSERT ON "config_changes" BEGIN SELECT RAISE(ABORT, 'gate: durable write blocked'); END"""); + + using (var write = await f.Client.PostAsJsonAsync( + $"/admin-api/blocks?token={EdgeFixture.AdminToken}", + new { ip = Blocked, reason = "the record will not land" })) + { + // Enforcement is the product. A change refused because its audit row + // would not fit is a change the operator believes they have. + Assert.Equal(HttpStatusCode.NoContent, write.StatusCode); + } + + Assert.Equal(0, await ChangeCountAsync(f)); + var state = await StateAsync(f); + Assert.Equal(0, state.GetProperty("configChanges").GetInt32()); + Assert.True(state.GetProperty("changeWriteFailures").GetInt32() >= 1); + Assert.Equal(1, state.GetProperty("changesNotWritten").GetInt32()); + Assert.Contains("gate: durable write blocked", state.GetProperty("changeLastError").GetString()); + + // And the block is really in effect, which is the whole reason the + // request was allowed to succeed. + using var probe = new HttpRequestMessage(HttpMethod.Get, "/anything"); + probe.Headers.TryAddWithoutValidation("X-Forwarded-For", Blocked); + using var probeResponse = await f.Client.SendAsync(probe); + Assert.Equal(HttpStatusCode.MovedPermanently, probeResponse.StatusCode); + } + + [Fact] + public async Task The_change_log_is_bounded_by_age_and_by_rows() + { + await using var f = new EdgeFixture(observationRetentionDays: 7); + for (var i = 0; i < 4; i++) + using (var write = await f.Client.PostAsJsonAsync( + $"/admin-api/blocks?token={EdgeFixture.AdminToken}", new { ip = $"203.0.113.{190 + i}" })) + Assert.Equal(HttpStatusCode.NoContent, write.StatusCode); + Assert.Equal(4, await ChangeCountAsync(f)); + + // The age window: a record older than the window goes. + using (var scope = f.Factory.Services.CreateScope()) + { + var db = scope.ServiceProvider.GetRequiredService(); + foreach (var row in await db.ConfigChanges.OrderBy(c => c.Id).Take(2).ToListAsync()) + row.At = DateTimeOffset.UtcNow.AddDays(-40); + await db.SaveChangesAsync(); + } + await f.Service().PruneAsync(CancellationToken.None); + Assert.Equal(2, await ChangeCountAsync(f)); + + // The row cap, which the age window cannot provide: an operator scripting + // a thousand edits inside a week would otherwise grow a table whose whole + // use is being readable. The oldest go first. + using (var scope = f.Factory.Services.CreateScope()) + { + var db = scope.ServiceProvider.GetRequiredService(); + var policy = f.Service().Current; + for (var i = 0; i < policy.ChangeLogMaxRows + 3; i++) + db.ConfigChanges.Add(new ConfigChange + { + At = DateTimeOffset.UtcNow, Section = "block", Action = "added", + Target = $"203.0.113.{i % 200}", Actor = ConfigChangeLog.ActorOperator + }); + await db.SaveChangesAsync(); + } + await f.Service().PruneAsync(CancellationToken.None); + Assert.Equal(f.Service().Current.ChangeLogMaxRows, await ChangeCountAsync(f)); + } + + [Fact] + public async Task The_state_counts_the_records_the_edge_holds() + { + await using var f = new EdgeFixture(); + Assert.Equal(0, (await StateAsync(f)).GetProperty("configChanges").GetInt32()); + using (var write = await f.Client.PostAsJsonAsync( + $"/admin-api/blocks?token={EdgeFixture.AdminToken}", new { ip = Blocked })) + Assert.Equal(HttpStatusCode.NoContent, write.StatusCode); + Assert.Equal(1, (await StateAsync(f)).GetProperty("configChanges").GetInt32()); + } + + [Fact] + public async Task A_rejected_write_lands_no_record_because_it_landed_no_change() + { + await using var f = new EdgeFixture(); + using var rejected = await f.Client.PostAsJsonAsync( + $"/admin-api/blocks?token={EdgeFixture.AdminToken}", new { ip = "not-an-address" }); + Assert.Equal(HttpStatusCode.BadRequest, rejected.StatusCode); + Assert.Equal(0, await ChangeCountAsync(f)); + } +} diff --git a/dotnet/OpenWaf.Tests.Unit/ConfigChangeLogTests.cs b/dotnet/OpenWaf.Tests.Unit/ConfigChangeLogTests.cs new file mode 100644 index 0000000..c5d1330 --- /dev/null +++ b/dotnet/OpenWaf.Tests.Unit/ConfigChangeLogTests.cs @@ -0,0 +1,67 @@ +using OpenWaf.Domain.Security; + +namespace OpenWaf.Tests.Unit; + +/// +/// The vocabulary and the bounds of a change record (OPEN-64). +/// +public sealed class ConfigChangeLogTests +{ + [Fact] + public void Every_vocabulary_word_fits_the_column_that_stores_it() + { + // A section or action longer than its column would be clipped by the + // database rather than by this code, and a filter that asks for the + // unclipped word would then answer "no such change". + foreach (var word in ConfigChangeLog.Sections.Concat(ConfigChangeLog.Actions) + .Append(ConfigChangeLog.ActorOperator).Append(ConfigChangeLog.ActorImport)) + Assert.True(word.Length <= 16, $"\"{word}\" is {word.Length} characters"); + } + + [Fact] + public void The_vocabulary_has_no_duplicates() + { + Assert.Equal(ConfigChangeLog.Sections.Length, ConfigChangeLog.Sections.Distinct().Count()); + Assert.Equal(ConfigChangeLog.Actions.Length, ConfigChangeLog.Actions.Distinct().Count()); + } + + [Fact] + public void Traffic_is_not_a_section_and_says_so() + { + // The log is about decisions, never about visitors: the vocabulary is + // where that ruling is enforced, and a filter for a traffic section is + // answered rather than quietly emptied. + Assert.False(ConfigChangeLog.IsSection("traffic")); + Assert.False(ConfigChangeLog.IsSection("observation")); + Assert.False(ConfigChangeLog.IsSection("BLOCK")); + Assert.False(ConfigChangeLog.IsSection(null)); + foreach (var section in ConfigChangeLog.Sections) Assert.True(ConfigChangeLog.IsSection(section)); + } + + [Fact] + public void Every_action_is_known_and_nothing_else_is() + { + foreach (var action in ConfigChangeLog.Actions) Assert.True(ConfigChangeLog.IsAction(action)); + Assert.False(ConfigChangeLog.IsAction("deleted")); + Assert.False(ConfigChangeLog.IsAction("")); + } + + [Fact] + public void A_detail_over_the_cap_is_clipped_not_refused() + { + // The change has already been applied when the record is written. A + // record that dropped the change because the operator's sentence was + // long would be the worse failure, so the sentence gives way. + var longNote = new string('x', ConfigChangeLog.MaxDetailLength + 200); + var clipped = ConfigChangeLog.Clip(longNote, ConfigChangeLog.MaxDetailLength); + Assert.Equal(ConfigChangeLog.MaxDetailLength, clipped.Length); + } + + [Fact] + public void A_detail_is_trimmed_and_blank_becomes_nothing() + { + Assert.Equal("confirmed scraper", ConfigChangeLog.Clip(" confirmed scraper ", 64)); + Assert.Equal("", ConfigChangeLog.Clip(null, 64)); + Assert.Equal("", ConfigChangeLog.Clip(" ", 64)); + } +} diff --git a/scripts/compose-smoke.sh b/scripts/compose-smoke.sh index 59f1a9c..1603626 100755 --- a/scripts/compose-smoke.sh +++ b/scripts/compose-smoke.sh @@ -1585,6 +1585,41 @@ for bad in 'OpenWaf__State__RefreshTtlSeconds=0' \ "$(grep -q "$msg_key" "$BAD_LOG" && echo yes || echo no)" done rm -f "$BAD_LOG" +echo '- the record of a config change on the shipped image' +# The change log (OPEN-64) against the deployed image: what an operator reads at +# 03:00 is this surface, so the claim is asserted here and not only in a test. +CH_IP="203.0.113.$(( 170 + RANDOM % 20 ))" +admin -X POST -H 'Content-Type: application/json' -d "{\"ip\":\"$CH_IP\",\"reason\":\"shipped image record\"}" \ + "$EDGE/admin-api/blocks" >/dev/null +CHANGES=$(admin "$EDGE/admin-api/changes?section=block") +check 'an operator block lands a record naming the address' 'yes' \ + "$(printf '%s' "$CHANGES" | python3 -c "import sys,json;print('yes' if any(c['target']=='$CH_IP' and c['action']=='added' for c in json.load(sys.stdin)) else 'no')")" +check 'the record carries the operator sentence' 'yes' \ + "$(printf '%s' "$CHANGES" | python3 -c "import sys,json;print('yes' if any('shipped image record' in (c.get('detail') or '') for c in json.load(sys.stdin)) else 'no')")" +check 'it names the surface, never a person' 'operator' \ + "$(printf '%s' "$CHANGES" | python3 -c "import sys,json;print(next(c['actor'] for c in json.load(sys.stdin) if c['target']=='$CH_IP'))")" +check 'no record claims to come from the engine' '0' \ + "$(admin "$EDGE/admin-api/changes" | python3 -c 'import sys,json;print(len([c for c in json.load(sys.stdin) if c["actor"]=="engine"]))')" +check 'the read-only token can read the log' '200' \ + "$(code -H "X-Admin-Token: $OPENWAF_READ_ONLY_TOKEN" "$EDGE/admin-api/changes")" +check 'the state counts the records' 'yes' \ + "$(admin "$EDGE/admin-api/state" | python3 -c 'import sys,json;print("yes" if isinstance(json.load(sys.stdin).get("configChanges"), int) else "no")')" +CH_IMPORT=$(admin -X POST -H 'Content-Type: application/json' -d '{"version":1,"countries":[{"code":"fr","allowed":false}]}' "$EDGE/admin-api/import") +check 'the import report says one country landed' '1' \ + "$(printf '%s' "$CH_IMPORT" | python3 -c 'import sys,json;print(json.load(sys.stdin)["countries"]["added"])')" +# The newest imported record for the section, not a count: the transfer scene +# above imported documents more than once, and each import leaves one record per +# section it carried — which is exactly the ruling being asserted. +check 'an import is recorded per section, not per row' 'yes' \ + "$(admin "$EDGE/admin-api/changes?section=country" | python3 -c 'import sys,json;d=[c for c in json.load(sys.stdin) if c["action"]=="imported"];print("yes" if d and "added" in (d[0].get("detail") or "") and len(d[0]["target"]) <= 16 else "no")')" +check 'and the import record says so' 'import' \ + "$(admin "$EDGE/admin-api/changes?section=country" | python3 -c 'import sys,json;d=[c for c in json.load(sys.stdin) if c["action"]=="imported"];print(d[0]["actor"] if d else "none")')" +check 'a removal is recorded as a removal' 'yes' \ + "$(code -X DELETE -H "X-Admin-Token: $OPENWAF_ADMIN_TOKEN" \ + "$EDGE/admin-api/blocks?source=operator&key=$CH_IP" >/dev/null; \ + admin "$EDGE/admin-api/changes?section=block" | python3 -c "import sys,json;print('yes' if any(c['target']=='$CH_IP' and c['action']=='removed' for c in json.load(sys.stdin)) else 'no')")" +check 'the country rule the import wrote is removable, so the volume stays clean' '204' \ + "$(code -X DELETE -H "X-Admin-Token: $OPENWAF_ADMIN_TOKEN" "$EDGE/admin-api/countries/fr")" echo printf 'compose smoke: %d passed, %d failed\n' "$PASS" "$FAIL" [ "$FAIL" -eq 0 ] diff --git a/scripts/smoke.sh b/scripts/smoke.sh index e37f226..b80b269 100755 --- a/scripts/smoke.sh +++ b/scripts/smoke.sh @@ -435,6 +435,62 @@ for bad in 'OpenWaf__State__RefreshTtlSeconds=0' \ done rm -f "$refused_log" +echo '- the record of a config change' +# The change log (OPEN-64). The assertions are on the surface an operator reads +# at 03:00, and the interesting one is the ruling the log could quietly get +# wrong: an engine ban is not a decision somebody made, so it is not in here. +check 'the state counts the records the edge holds' yes \ + "$(curl -s -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/state" \ + | python3 -c 'import sys,json;print("yes" if isinstance(json.load(sys.stdin).get("configChanges"), int) else "no")')" +check 'an engine ban is not a change record' 0 \ + "$(curl -s -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/changes" \ + | python3 -c 'import sys,json;print(len([c for c in json.load(sys.stdin) if c["target"]=="203.0.113.66"]))')" +check 'the read-only token can read the log' 200 \ + "$(code -H "X-Admin-Token: $RO_TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/changes")" +check 'an unknown section is answered by the vocabulary' 400 \ + "$(code -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/changes?section=traffic")" +LOG_IP="203.0.113.$(( 160 + RANDOM % 20 ))" +curl -s -X POST -H "X-Admin-Token: $TOKEN" -H 'Content-Type: application/json' \ + -d "{\"ip\":\"$LOG_IP\",\"reason\":\"written to be remembered\"}" \ + "http://127.0.0.1:$EDGE_PORT/admin-api/blocks" >/dev/null +CHANGES_JSON="$(curl -s -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/changes?section=block")" +check 'the write added exactly one record' 1 \ + "$(printf '%s' "$CHANGES_JSON" | python3 -c "import sys,json;print(len([c for c in json.load(sys.stdin) if c['target']=='$LOG_IP']))")" +check 'an operator block lands a record naming the address' yes \ + "$(printf '%s' "$CHANGES_JSON" | python3 -c "import sys,json;print('yes' if any(c['target']=='$LOG_IP' and c['action']=='added' for c in json.load(sys.stdin)) else 'no')")" +check 'and the record carries the operator sentence' yes \ + "$(printf '%s' "$CHANGES_JSON" | python3 -c "import sys,json;print('yes' if any('remembered' in (c.get('detail') or '') for c in json.load(sys.stdin)) else 'no')")" +check 'and it names the surface, not a person' operator \ + "$(printf '%s' "$CHANGES_JSON" | python3 -c "import sys,json;print(next(c['actor'] for c in json.load(sys.stdin) if c['target']=='$LOG_IP'))")" +curl -s -X DELETE -H "X-Admin-Token: $TOKEN" \ + "http://127.0.0.1:$EDGE_PORT/admin-api/blocks?source=operator&key=$LOG_IP" >/dev/null +check 'a removal is recorded as a removal' yes \ + "$(curl -s -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/changes?section=block" \ + | python3 -c "import sys,json;print('yes' if any(c['target']=='$LOG_IP' and c['action']=='removed' for c in json.load(sys.stdin)) else 'no')")" +# A policy write of our own, so the assertion is about this scene and not about +# whether an earlier one happened to move a field. +curl -s -X PUT -H "X-Admin-Token: $TOKEN" -H 'Content-Type: application/json' \ + -d '{"streakThreshold":4}' "http://127.0.0.1:$EDGE_PORT/admin-api/policy" >/dev/null +check 'a policy write records what moved' yes \ + "$(curl -s -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/changes?section=policy" \ + | python3 -c 'import sys,json;print("yes" if any("streakThreshold 3->4" in (c.get("detail") or "") for c in json.load(sys.stdin)) else "no")')" +curl -s -X PUT -H "X-Admin-Token: $TOKEN" -H 'Content-Type: application/json' \ + -d '{"streakThreshold":3}' "http://127.0.0.1:$EDGE_PORT/admin-api/policy" >/dev/null +# One record per import per section, whatever the document carried: the transfer +# scene above imported twice, so the newest imported row is the one to read. +check 'an import is recorded per section, not per row' yes \ + "$(curl -s -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/changes?section=block" \ + | python3 -c 'import sys,json;d=[c for c in json.load(sys.stdin) if c["action"]=="imported"];print("yes" if d and "added" in (d[0].get("detail") or "") and "ip" not in (d[0].get("target") or "") else "no")')" +check 'and that record names the import as the surface' import \ + "$(curl -s -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/changes?section=block" \ + | python3 -c 'import sys,json;d=[c for c in json.load(sys.stdin) if c["action"]=="imported"];print(d[0]["actor"] if d else "none")')" +check 'the log is newest first' yes \ + "$(curl -s -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/changes" \ + | python3 -c 'import sys,json;d=json.load(sys.stdin);print("yes" if d==sorted(d,key=lambda c:-c["id"]) else "no")')" +check 'and a page says when it is truncated' yes \ + "$(curl -s -D- -o /dev/null -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/changes?limit=1" \ + | tr -d '\r' | grep -qi '^X-Truncated: true' && echo yes || echo no)" + echo '- volume budget' STATE0_JSON="$(curl -s -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/state")" check 'the budget is off until an operator writes one' Off \