The admin API answered 200 to anything. Measured on the shipped image
(openwaf:ci) before this commit:
PUT {"streakThreshold":0} -> 200, streakThreshold still 3, 0 log lines
PUT {"maxTrackedSources":0} -> 200, unchanged
PUT {"banDurationMinutes":-1} -> 200, unchanged
PUT {"streakWindowMinutes":0} -> 200, unchanged
PUT {"refusalRange":"not-a-range"} -> 200, unchanged
PUT {"engineBlockStatus":999} -> 200, and the edge answered HTTP/1.1 999
PUT {"engineBlockStatus":1000} -> 200, and every banned request died as
"curl: (1) Unsupported HTTP/1 subversion
in response" — no HTTP response at all
PUT {"ipv4KeyPrefixLength":0} -> 200, one 404 banned the key "*", and the
next three never-seen addresses were
refused on their first request
PUT {"ipv4KeyPrefixLength":999} -> 200, GET echoed 999, enforcement used 32
Two different failures hid behind that 200. A value the code did not want was
dropped without a word, so the operator read "OK" over a policy that had not
moved. A value the code did want was stored and obeyed literally, and one of
those (engineBlockStatus=1000) takes the site down for every banned visitor
from one admin call.
So the ranges now live in one place, PolicyBounds, next to the reason for each
one, and three layers read it:
* the admin endpoint answers 400 naming the key and the range — the same
shape mode, geo and the state TTL already used;
* the loader ignores a row outside the range and logs the key and the value,
for a backup restored or a row edited by hand;
* DecisionEngine refuses to put an unsendable status on the wire at all, and
answers 403 instead.
ipv4KeyPrefixLength keeps a floor of 8 rather than 0, because 0 is not a coarse
grouping, it is the literal key "*" — one streak and one ban shared by every
IPv4 address on the internet.
Tests: 46 unit (the bounds table, the "*" mechanism, the wire guard) and 18
integration (400 by name, a refused write changing nothing, an accepted value
reaching the wire as 451, a hand-edited row ignored). Teeth, each measured by
removing the layer: no API validation -> 16 integration tests fail; no wire
guard -> 3 unit tests fail; no loader gate -> 1 integration test fails.
122 lines
6.4 KiB
C#
122 lines
6.4 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;
|
|
|
|
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);
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
_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;
|
|
}
|
|
}
|