Measured on the shipped image (openwaf:ci, the head tree), one stand with a real
upstream:
PUT /admin-api/policy {"streakThreshold":2,"trustProxyHeaders":true} -> 200
404 404 from 203.0.113.79, third request -> 403 (the threshold is in force)
04:44:43 DROP TABLE policy_settings, from outside the process
04:45:2x GET /admin-api/policy -> still "streakThreshold": 2, answered plainly
GET /admin-api/state -> "snapshotAgeSeconds":0 — the refresh "succeeded",
because the tables it also reads were still there
/healthz 200, /readyz 200, and exactly 1 line in the log
docker restart -> GET /admin-api/policy -> "streakThreshold": 10,
"trustProxyHeaders": false
four 404s from 203.0.113.81, fifth -> 404: nothing banned
Both pillars — the policy provider and the guard's snapshot store — catch
everything their read throws, keep the last value they had, and log one line.
Keeping the last good value is the right failure posture: a database restart must
not open the gate. Keeping it unmentioned is not: for a minute the operator's page
showed a threshold that no longer existed anywhere in storage, readiness said
ready, and after a restart the defence silently came back at the default N=10.
Now: EdgePolicyProvider and EdgeStateStore count consecutive failed reads and keep
the last error; /admin-api/state answers snapshotStale (age against the TTL the
process refuses to start without), snapshotRefreshFailures,
snapshotLastRefreshError, policyReloadFailures and policyLastReadAt;
/admin-api/policy carries X-Policy-Reload-Failures and X-Policy-Last-Read
alongside the policy it is enforcing, the same way a capped listing carries its
completeness in headers; /readyz answers 503 while either counter is non-zero,
naming the pillar and the age of the snapshot it is running on; and the console's
summary line goes warn and says "older than the ttl", "snapshot refresh failing
xN", "policy not re-read from storage xN".
Teeth first: PillarFailureVisibilityTests (4) run against the unfixed tree — 4
failed, 0 passed, all four on a missing field (KeyNotFoundException), which is the
point: the numbers did not exist. The refresh test drops country_rules rather than
block_entries on purpose — only one of them is what /readyz probes, so before the
fix that test saw the refresh failing and readiness still answering 200.
Gates: compose-smoke now drops policy_settings from the running stand through a
--volumes-from sidecar, waits for the failure to be counted, asserts the counters,
the 503 and the header, puts the table back and asserts the recovery (+6
assertions; the counters are consecutive, not cumulative, so recovery is part of
the claim). smoke.sh asserts the healthy case with numbers rather than silence
(+3). console-check drives the page against that state answer and requires the
summary line to be marked and to name both pillars (+3); the state body is served
through a route because the guard refreshes the snapshot on every request — a live
stand cannot be left to age — while the contract being rendered is the one
compose-smoke measures end to end against the shipped image.
Numbers on this tree. Host: build 0 warnings, unit 128/128, integration 117/117,
smoke 25 passed / 0 failed, compose 53 passed / 0 failed, console 53 assertions /
0 failed, image 261 MB. Linux rehearsal, each stage on its own — source in
mcr.microsoft.com/dotnet/sdk:10.0 (Ubuntu 24.04.5, SDK 10.0.401): 128/128,
117/117, 25/0; compose in docker:cli: 53/0, enforcement lag 12 ms; console in
mcr.microsoft.com/playwright:v1.63.0-noble: 53/0.
151 lines
8.0 KiB
C#
151 lines
8.0 KiB
C#
using Microsoft.EntityFrameworkCore;
|
|
using Microsoft.Extensions.DependencyInjection;
|
|
using Microsoft.Extensions.Logging;
|
|
using OpenWaf.Domain.Policy;
|
|
|
|
namespace OpenWaf.Infrastructure.Persistence;
|
|
|
|
/// <summary>
|
|
/// The live policy. Configuration supplies the defaults; the
|
|
/// <c>policy_settings</c> table supplies the operator's overrides, so the
|
|
/// toggle can be flipped without a redeploy and survives one.
|
|
/// </summary>
|
|
public sealed class EdgePolicyProvider
|
|
{
|
|
private readonly IServiceScopeFactory _scopeFactory;
|
|
private readonly ILogger<EdgePolicyProvider> _log;
|
|
private EdgePolicy _current;
|
|
// Warn once per key, not once per refresh: ReloadAsync runs on every
|
|
// snapshot refresh, and a log line every 30 seconds is how an operator
|
|
// stops reading the log.
|
|
private readonly HashSet<string> _warned = new(StringComparer.OrdinalIgnoreCase);
|
|
|
|
public EdgePolicyProvider(
|
|
IServiceScopeFactory scopeFactory,
|
|
EdgePolicy configured,
|
|
ILogger<EdgePolicyProvider> log)
|
|
{
|
|
_scopeFactory = scopeFactory;
|
|
_log = log;
|
|
_current = configured;
|
|
}
|
|
|
|
public EdgePolicy Current => _current;
|
|
|
|
/// <summary>
|
|
/// Consecutive reload failures — zero means the last read succeeded. Kept
|
|
/// because "keeping the current policy" is the right thing to do and the
|
|
/// wrong thing to leave unmentioned: measured on the shipped image, a
|
|
/// deleted policy_settings table produced exactly one log line, while
|
|
/// GET /admin-api/policy went on answering the operator's own
|
|
/// streakThreshold: 2 for as long as the process lived, /admin-api/state
|
|
/// reported a snapshot age of 0 (the refresh "succeeded"), and /readyz said
|
|
/// ready. After a restart that policy was gone — the threshold silently
|
|
/// returned to 10 and trustProxyHeaders to false — and nothing on any
|
|
/// surface had ever said the value being shown was an in-memory copy.
|
|
/// </summary>
|
|
public int ReloadFailures => Volatile.Read(ref _reloadFailures);
|
|
|
|
/// <summary>The last reload error, or null when the last reload succeeded.</summary>
|
|
public string? LastReloadError => Volatile.Read(ref _lastReloadError);
|
|
|
|
/// <summary>When storage last confirmed this policy. Null means never.</summary>
|
|
public DateTimeOffset? LastReloadSuccessAt => _lastReloadSuccessAt;
|
|
|
|
private int _reloadFailures;
|
|
private string? _lastReloadError;
|
|
private DateTimeOffset? _lastReloadSuccessAt;
|
|
|
|
public async Task<EdgePolicy> ReloadAsync(CancellationToken ct = default)
|
|
{
|
|
try
|
|
{
|
|
using var scope = _scopeFactory.CreateScope();
|
|
var db = scope.ServiceProvider.GetRequiredService<OpenWafDbContext>();
|
|
var rows = await db.PolicySettings.AsNoTracking().ToListAsync(ct);
|
|
_current = ApplyOverrides(_current, rows);
|
|
Interlocked.Exchange(ref _reloadFailures, 0);
|
|
Volatile.Write(ref _lastReloadError, null);
|
|
_lastReloadSuccessAt = DateTimeOffset.UtcNow;
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
Interlocked.Increment(ref _reloadFailures);
|
|
Volatile.Write(ref _lastReloadError, ex.Message);
|
|
_log.LogWarning(ex, "EdgePolicyProvider: reload failed; keeping the current policy.");
|
|
}
|
|
return _current;
|
|
}
|
|
|
|
public async Task<bool> SaveAsync(IReadOnlyDictionary<string, string?> overrides, CancellationToken ct = default)
|
|
{
|
|
try
|
|
{
|
|
using var scope = _scopeFactory.CreateScope();
|
|
var db = scope.ServiceProvider.GetRequiredService<OpenWafDbContext>();
|
|
foreach (var (key, value) in overrides)
|
|
{
|
|
if (value is null)
|
|
{
|
|
await db.PolicySettings.Where(p => p.Key == key).ExecuteDeleteAsync(ct);
|
|
continue;
|
|
}
|
|
var row = await db.PolicySettings.FindAsync([key], ct);
|
|
if (row is null) db.PolicySettings.Add(new PolicySetting { Key = key, Value = value, UpdatedAt = DateTimeOffset.UtcNow });
|
|
else { row.Value = value; row.UpdatedAt = DateTimeOffset.UtcNow; }
|
|
}
|
|
await db.SaveChangesAsync(ct);
|
|
await ReloadAsync(ct);
|
|
return true;
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
_log.LogWarning(ex, "EdgePolicyProvider: save failed.");
|
|
return false;
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// The DB is not only written by the admin API: a row can be edited by
|
|
/// hand, or restored from a backup taken before a key had a range. So the
|
|
/// range is checked here too, and a row outside it is skipped with a
|
|
/// warning that names the key and the value. Skipping is the safe half of
|
|
/// the rule — the other half is that the guard never trusts a status it
|
|
/// cannot put on the wire (DecisionEngine.BlockResponse).
|
|
/// </summary>
|
|
private EdgePolicy ApplyOverrides(EdgePolicy basePolicy, IReadOnlyCollection<PolicySetting> rows)
|
|
{
|
|
if (rows.Count == 0) return basePolicy;
|
|
var map = rows.ToDictionary(r => r.Key, r => r.Value, StringComparer.OrdinalIgnoreCase);
|
|
var p = basePolicy;
|
|
|
|
foreach (var row in rows)
|
|
{
|
|
if (row.Value is not null && !PolicyBounds.ValueOk(row.Key, row.Value) && _warned.Add(row.Key))
|
|
_log.LogWarning(
|
|
"policy_settings row {Key}={Value} is outside {Range}; ignoring it. The policy keeps its previous value for this key.",
|
|
row.Key, row.Value, PolicyBounds.RangeOf(row.Key));
|
|
}
|
|
|
|
bool Usable(string key) => !map.TryGetValue(key, out var v) || v is null || PolicyBounds.ValueOk(key, v);
|
|
|
|
if (map.TryGetValue("mode", out var mode) && Enum.TryParse<EnforcementMode>(mode, true, out var m)) p = p with { Mode = m };
|
|
if (Usable("streakThreshold") && map.TryGetValue("streakThreshold", out var n) && int.TryParse(n, out var nv) && nv > 0) p = p with { StreakThreshold = nv };
|
|
if (Usable("streakWindowMinutes") && map.TryGetValue("streakWindowMinutes", out var mw) && double.TryParse(mw, out var mwv) && mwv > 0) p = p with { StreakWindow = TimeSpan.FromMinutes(mwv) };
|
|
if (Usable("banDurationMinutes") && map.TryGetValue("banDurationMinutes", out var bd) && double.TryParse(bd, out var bdv) && bdv > 0) p = p with { BanDuration = TimeSpan.FromMinutes(bdv) };
|
|
if (Usable("refusalRange") && map.TryGetValue("refusalRange", out var rr)) p = p with { RefusalRange = StatusRange.Parse(rr, p.RefusalRange) };
|
|
if (Usable("serverErrorRange") && map.TryGetValue("serverErrorRange", out var sr)) p = p with { ServerErrorRange = StatusRange.Parse(sr, p.ServerErrorRange) };
|
|
if (map.TryGetValue("trustProxyHeaders", out var tph) && bool.TryParse(tph, out var tphv)) p = p with { TrustProxyHeaders = tphv };
|
|
if (map.TryGetValue("geo", out var geo) && Enum.TryParse<GeoMode>(geo, true, out var gm)) p = p with { Geo = gm };
|
|
if (Usable("maxTrackedSources") && map.TryGetValue("maxTrackedSources", out var mts) && int.TryParse(mts, out var mtsv) && mtsv > 0) p = p with { MaxTrackedSources = mtsv };
|
|
if (Usable("ipv6KeyPrefixLength") && map.TryGetValue("ipv6KeyPrefixLength", out var p6) && int.TryParse(p6, out var p6v)) p = p with { Ipv6KeyPrefixLength = p6v };
|
|
if (Usable("ipv4KeyPrefixLength") && map.TryGetValue("ipv4KeyPrefixLength", out var p4) && int.TryParse(p4, out var p4v)) p = p with { Ipv4KeyPrefixLength = p4v };
|
|
if (Usable("engineBlockStatus") && map.TryGetValue("engineBlockStatus", out var ebs) && int.TryParse(ebs, out var ebsv)) p = p with { EngineBlockStatus = ebsv };
|
|
if (Usable("operatorBlockStatus") && map.TryGetValue("operatorBlockStatus", out var obs) && int.TryParse(obs, out var obsv)) p = p with { OperatorBlockStatus = obsv };
|
|
if (map.TryGetValue("redirectTargets", out var rt) && !string.IsNullOrWhiteSpace(rt))
|
|
p = p with { DefaultRedirectTargets = rt.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries) };
|
|
|
|
return p;
|
|
}
|
|
}
|