Files
openwaf/dotnet/OpenWaf.Infrastructure/Persistence/EdgePolicyProvider.cs
T
Pavlo Ratushnyi 5cf93ef0fd a source that asks too often is stopped, even when the origin keeps answering
Every defence this edge had reads something that already happened: the status the
application answered, the country the address sits in, a list a human wrote. A
source asking for a cheap path two hundred times a minute produces no refusal, so
no streak matures, no path rule names it, and the origin serves all two hundred.
The only signal is the count, and a count has to be kept while the requests are
arriving — which is why this pillar is the one piece of live state on the request
path, and why it runs after the ordered decision instead of inside it.

`rateMode` off|observe|enforce, `rateLimitPerWindow`, `rateWindowSeconds`
(policy_settings, so no schema change). Off is the default: a limit nobody wrote
is a defence nobody asked for, and a false positive here locks out a whole office
behind one address. `observe` counts and raises one `rate_breach` alert per
source per window. `enforce` answers the request that crosses with 429 +
Retry-After — the surplus never reaches the origin — and writes an engine ban, so
the stop outlives the window, is shared with the other edges and survives a
restart; from then on the answer is the ban's own 403. One breach, one alert, one
ban write per source per window: a flood is exactly the traffic that turns a
per-request durable write into the thing that takes the database down.

Exempt by construction rather than by a second copy of the precedence rules: the
counter runs only on a plain Pass, so an always-pass prefix, an allowlisted
address, a matched rule, a block or a geo refusal never reaches it. The budget
counts exactly the requests that would have cost the origin.

Costs, stated rather than hidden: the counter is per process, so N edges allow N
times the budget (the same trade `SharedStreaks` made for the streak, at a round
trip per request instead of per observed response); the window is fixed, not
sliding, so the worst sustained rate is twice the limit across one boundary — a
sliding counter needs one entry per request, which is a map that grows at attack
rate.

Two things the run caught rather than the design assumed:

 * The guard wrote the 429 and then called next() anyway, so YARP answered
   "the request cannot be forwarded, the response has already started". The
   pillar now says whether the request may go through.
 * `StreakTracker.Configure` was called by nobody outside its own tests, so
   `maxTrackedSources` bounded nothing in a running edge — the map grew to the
   built-in 10000 whatever the operator had asked for. Both maps are configured
   at warm-up and on a policy write now.

And the smoke gate was not testing what its first line says. The edge was started
from the repository root, where there is no appsettings.json, so it loaded no
ReverseProxy section at all, logged "Request reached the end of the middleware
pipeline without being handled by application code" for every request, and
answered 404 for a path the upstream was serving with 200. Every assertion in the
file expects a 404 or a refusal, so the gate kept passing on an edge that never
proxied anything. Naming the content root fixes it; the streak scene also waits
for the ban row to exist before asking the wire whether it is enforced, because
the ban is written out of band after the response that proved it.

Gates on this tree: build 0 warnings 0 errors, unit 207/207, integration 219/219
in 20 s, smoke passed 48 failed 0, console 90 assertions 0 failed, compose 209
passed 0 failed, image 261 MB.

OPEN-56
2026-10-04 21:00:33 +02:00

154 lines
8.5 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 (map.TryGetValue("rateMode", out var rm) && Enum.TryParse<RateMode>(rm, true, out var rmode)) p = p with { Rate = rmode };
if (Usable("rateLimitPerWindow") && map.TryGetValue("rateLimitPerWindow", out var rl) && int.TryParse(rl, out var rlv)) p = p with { RateLimitPerWindow = rlv };
if (Usable("rateWindowSeconds") && map.TryGetValue("rateWindowSeconds", out var rw) && double.TryParse(rw, out var rwv)) p = p with { RateWindow = TimeSpan.FromSeconds(rwv) };
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;
}
}