Files
openwaf/dotnet/OpenWaf.Domain/Policy/EdgePolicy.cs
T
Pavlo Ratushnyi 3959f1fe6b 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.
2026-10-05 05:58:42 +02:00

124 lines
6.5 KiB
C#

namespace OpenWaf.Domain.Policy;
/// <summary>
/// The whole edge policy as one immutable snapshot, read from configuration
/// and from the <c>policy_settings</c> row (the DB wins where a key is set,
/// so the operator can change the toggle without a redeploy).
///
/// Q1 is settled here: the streak window (M) and the ban duration are two
/// separate parameters. "N раз підряд на M хвилин" bounds the streak; how
/// long a ban then lasts is a different question and gets its own knob.
/// </summary>
public sealed record EdgePolicy
{
public EnforcementMode Mode { get; init; } = EnforcementMode.Observe;
/// <summary>N — consecutive refusals that trigger a ban.</summary>
public int StreakThreshold { get; init; } = 10;
/// <summary>M — the gap between two refusals that still counts as the same
/// streak. A gap longer than this restarts the streak at 1.</summary>
public TimeSpan StreakWindow { get; init; } = TimeSpan.FromMinutes(5);
/// <summary>How long an engine ban stays live.</summary>
public TimeSpan BanDuration { get; init; } = TimeSpan.FromMinutes(60);
/// <summary>Q2: the refusal class is inclusive of 400 — a malformed-body
/// probe answers 400 and must count.</summary>
public StatusRange RefusalRange { get; init; } = new(400, 499);
/// <summary>Q3: 5xx is an alert, never a ban.</summary>
public StatusRange ServerErrorRange { get; init; } = new(500, 599);
/// <summary>Q4: source key granularity. IPv6 is grouped to /64 so a bot
/// rotating addresses inside one provider allocation is one source, and a
/// whole office behind one v4 address stays one source (accepted cost,
/// documented, mitigated by the allowlist).</summary>
public int Ipv4KeyPrefixLength { get; init; } = 32;
public int Ipv6KeyPrefixLength { get; init; } = 64;
/// <summary>Hard bound on the in-memory streak map. Beyond it the oldest
/// sources are evicted, so a scanner farm cannot grow the process.
/// (LEAS-785 is the cautionary tale: an unbounded ConcurrentDictionary.)</summary>
public int MaxTrackedSources { get; init; } = 10_000;
/// <summary>Write-amplification cap: at most one durable observation per
/// source per this interval.</summary>
public TimeSpan ObservationWriteInterval { get; init; } = TimeSpan.FromSeconds(30);
/// <summary>A source state nobody has touched for this long is evicted.</summary>
public TimeSpan StateIdleTtl { get; init; } = TimeSpan.FromHours(2);
/// <summary>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.</summary>
public bool SharedStreaks { get; init; }
/// <summary>What the edge does with a source that asked more often than the
/// budget allows (OPEN-56). Off by default: a limit nobody wrote is a
/// defence nobody asked for, and a false positive here locks out a whole
/// office behind one address.</summary>
public RateMode Rate { get; init; } = RateMode.Off;
/// <summary>The budget. Requests per source per window; the request that
/// crosses it is the breach. Meaningful only when
/// <see cref="Rate"/> is not Off, but kept valid regardless so a policy
/// that is switched on later cannot come up with a limit of zero, which
/// would refuse every request.</summary>
public int RateLimitPerWindow { get; init; } = 100;
/// <summary>How long a source's budget lasts. The window starts at that
/// source's first request, not on a global clock.</summary>
public TimeSpan RateWindow { get; init; } = TimeSpan.FromMinutes(1);
/// <summary>How long a ban's evidence row survives after it stops being live.</summary>
public TimeSpan BanRetention { get; init; } = TimeSpan.FromDays(7);
/// <summary>How long an observation row survives without traffic.</summary>
public TimeSpan ObservationRetention { get; init; } = TimeSpan.FromDays(7);
/// <summary>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.</summary>
public TimeSpan ChangeRetention { get; init; } = TimeSpan.FromDays(30);
/// <summary>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.</summary>
public int ChangeLogMaxRows { get; init; } = 5000;
public GeoMode Geo { get; init; } = GeoMode.Off;
/// <summary>Whether X-Forwarded-For / CF-Connecting-IP may define the
/// source address. Off by default: if the header is attacker-controlled
/// every request gets a fresh source key and no streak ever matures.</summary>
public bool TrustProxyHeaders { get; init; }
/// <summary>Response the edge gives an engine ban. 403, not 301: a 301 is
/// a good answer to a scanner and a baffling one to a customer whose
/// office IP was caught (Q6).</summary>
public int EngineBlockStatus { get; init; } = 403;
/// <summary>Response the edge gives an operator block when the entry has no
/// per-entry redirect. Defaults to the reference behaviour: 301 to a
/// honey-pot list, because scanners follow redirects and honest users
/// typed nothing.</summary>
public int OperatorBlockStatus { get; init; } = 301;
public IReadOnlyList<string> DefaultRedirectTargets { get; init; } =
new[] { "https://www.iana.org/help/example-domains" };
/// <summary>Paths that never consult the guard, so an operator who blocks
/// their own address can still reach the admin API and undo it.</summary>
public IReadOnlyList<string> AlwaysPassPrefixes { get; init; } =
new[] { "/admin-api", "/admin", "/healthz", "/readyz", "/metrics", "/openapi", "/swagger" };
public static EdgePolicy Default { get; } = new();
}