Files
openwaf/dotnet/OpenWaf.Infrastructure/Persistence/EdgePolicyProvider.cs
T
Pavlo Ratushnyi a3d0777492 openwaf: edge WAF with one decision point and a streak ban
Initial implementation of the OPEN-2 epic: a .NET 10 YARP edge that
decides from what the upstream answered.

Design (docs/ARCHITECTURE.md, tracker authority 4c9de3f6):
- one short-circuit point, ordered: always-pass prefixes -> allowlist ->
  operator block (301) -> engine ban (403 + Retry-After) -> geo (451)
- a post-response observer feeds a consecutive-refusal streak; N refusals
  in M minutes ban for BanDuration; 5xx alerts and never bans
- provenance on the block row, so clearing engine bans cannot touch an
  operator's entries; the toggle is Off/Observe/Enforce and changes no rows
- inherited protections from the reference deployment: one durable write
  per source per 30s, LRU-bounded streak map, no DB on the request path

Verification: 36 unit + 14 integration tests, plus scripts/smoke.sh (19
assertions against a running edge and a real upstream, including the
distroless --healthcheck mode).

Findings worth keeping (documented in docs/ARCHITECTURE.md):
- ctx.RequestAborted silently cancelled the ban write, because the
  observer runs after the response is written
- SQLite cannot translate DateTimeOffset comparisons; timestamps are
  stored as integers there and stay timestamptz on PostgreSQL
- CIDR masking order silently widened prefixes (198.51.100.24/19 -> /16)
- an empty string in appsettings.json defeats the env fallback (?? on "")
- concurrent ban writes raced into the unique index and lost evidence

Also moves the unrelated 2026-09-30 inference benchmarks out of the
project root into research/.
2026-10-01 02:13:01 +02:00

100 lines
4.9 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;
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;
}
}
private static 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;
if (map.TryGetValue("mode", out var mode) && Enum.TryParse<EnforcementMode>(mode, true, out var m)) p = p with { Mode = m };
if (map.TryGetValue("streakThreshold", out var n) && int.TryParse(n, out var nv) && nv > 0) p = p with { StreakThreshold = nv };
if (map.TryGetValue("streakWindowMinutes", out var mw) && double.TryParse(mw, out var mwv) && mwv > 0) p = p with { StreakWindow = TimeSpan.FromMinutes(mwv) };
if (map.TryGetValue("banDurationMinutes", out var bd) && double.TryParse(bd, out var bdv) && bdv > 0) p = p with { BanDuration = TimeSpan.FromMinutes(bdv) };
if (map.TryGetValue("refusalRange", out var rr)) p = p with { RefusalRange = StatusRange.Parse(rr, p.RefusalRange) };
if (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("maxTrackedSources", out var mts) && int.TryParse(mts, out var mtsv) && mtsv > 0) p = p with { MaxTrackedSources = mtsv };
if (map.TryGetValue("ipv6KeyPrefixLength", out var p6) && int.TryParse(p6, out var p6v)) p = p with { Ipv6KeyPrefixLength = p6v };
if (map.TryGetValue("ipv4KeyPrefixLength", out var p4) && int.TryParse(p4, out var p4v)) p = p with { Ipv4KeyPrefixLength = p4v };
if (map.TryGetValue("engineBlockStatus", out var ebs) && int.TryParse(ebs, out var ebsv)) p = p with { EngineBlockStatus = ebsv };
if (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;
}
}