Files
openwaf/dotnet/OpenWaf.Infrastructure/Persistence/EdgePolicyProvider.cs
T
Pavlo Ratushnyi 1e0d11df1c
ci / build, test, smoke (push) Failing after 3m33s
ci / the same smoke on an image with no base (push) Successful in 8m10s
ci / lint the workflow and the shell (push) Failing after 19s
ci / the operator page in a real browser (push) Successful in 4m41s
ci / build the image and smoke it (push) Failing after 8m11s
the first query moves off ef, and the aot edge reads its own policy from the database
Wall 3 starts. Two projects, one query path, measured.

dotnet/OpenWaf.Data is the runtime: OrmContext (a DbDataSource plus an
ISqlDialect), Query<T>, RowReader, OrmMeta. It is typed over System.Data.Common
and carries no provider package; the driver is supplied at composition, which is
how the neighbouring deployment ships it too. Query<T> renders SQL by walking the
expression tree rather than compiling it — that is the exact difference from EF's
pipeline, and the reason it survives a NativeAOT link where EF does not. The
supported grammar is a closed set that refuses by name: joins, subqueries,
aggregates other than COUNT, updates, deletes, JSON columns and method calls each
raise UnsupportedQueryNodeException naming the node, because a renderer that
guesses is a renderer that ships wrong SQL.

dotnet/OpenWaf.Data.Generator is a Roslyn incremental generator attached to
OpenWaf.Infrastructure as an analyzer. For a [Table] class it emits the column
map, the row materializer and an OrmMeta.Register call inside a
[ModuleInitializer], so the question a NativeAOT binary cannot answer — what are
this type's properties — is never asked. The generated file is ordinary C#,
readable in obj/ and asserted against.

PolicySetting is the entity moved and EdgePolicyProvider.ReloadAsync the call
site, which was the first refusal in the probe log. Program.cs composes the
driver and dialect on the same Database:Provider switch EF uses, so one generated
query serves sqlite (the shipped image) and PostgreSQL (the migrations'
provider). EF still owns every write and every other read; the two layers
coexist on one composition root, which is what makes this incremental rather than
a rewrite.

Measured on the AOT binary, same probe, same window, before and after:
queries refused at run time 32 -> 18; EdgePolicyProvider reload failures 1 -> 0;
native binary 49,609,680 -> 49,676,016 bytes. The 18 that remain are named by
their own frames: 14 EdgeStateStore.RefreshAsync, 2 BlockStore.WriteBanAsync,
1 BlockStore.AddOperatorAsync, 1 admin endpoint.

The sqlite timestamp column turned out to be a contract, not a detail. The model
puts EF's DateTimeOffsetToBinaryConverter on every timestamp column, so every row
already written says (localTicks / 1000) * 2048 + (offsetMinutes & 2047); the
formula was derived by probing EF's converter and is now pinned by
SqliteTimestampEncodingTests against that converter over five instants including
+05:30, -05:00 and DateTimeOffset.MinValue — including the microsecond
truncation the /1000 imposes, which is EF's behaviour and is now a test rather
than a future surprise.

Two build traps, both paid for and both recorded where the next person will hit
them. -p:PublishAot on the command line is a global property, so it reaches every
project in the graph including a netstandard2.0 Roslyn analyzer, and the publish
dies with NETSDK1207; AOT is now switched by OpenWafAot=true, which only
OpenWaf.Edge.csproj turns into PublishAot — the same shape as the existing
OpenWafCompiledModel switch. And a raw Microsoft.Data.Sqlite data source needs
SQLitePCL.Batteries.Init() before its first open, because the order in which
EF's provider and this data source are first used is not guaranteed.

Gates on this tree: build 0 warnings, unit 391/391 (13 new: rendered SQL for both
dialects, null tests, the captured-null case, the refusals, the timestamp
encoding), integration 408/408, smoke 256/256, and the AOT probe above. One
earlier run of the 408 carried a single failure in AdminConsoleTests at a host
load average near 30 and the next run was clean; recorded rather than hidden, in
the same family as the load-sensitive compose gates this README already
documents.
2026-10-07 21:48:01 +02:00

168 lines
9.7 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 token = ct;
// The read moved to the generated query layer (OPEN-79, wall 3). EF
// answers this exact query — a whole-table read with no predicate — with
// "Query wasn't precompiled and dynamic code isn't supported with
// NativeAOT" in an AOT binary, and it was the first refusal in the probe
// log. The SQL is rendered from the expression tree by walking it, and the
// row materializer is a function the compiler emitted, so there is nothing
// left for the run time to generate. The writes below still go through EF;
// they are the next ones standing.
var rows = await PolicySettingOrm
.Query(scope.ServiceProvider.GetRequiredService<OpenWaf.Data.OrmContext>())
.ToListAsync(token);
_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>();
var token = ct;
foreach (var (key, value) in overrides)
{
if (value is null)
{
await db.PolicySettings.Where(p => p.Key == key).ExecuteDeleteAsync(token);
continue;
}
var row = await db.PolicySettings.FindAsync([key], token);
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 (Usable("netblockCandidateBans") && map.TryGetValue("netblockCandidateBans", out var ncb) && int.TryParse(ncb, out var ncbv)) p = p with { NetblockCandidateBans = ncbv };
if (Usable("netblockPrefixV4") && map.TryGetValue("netblockPrefixV4", out var np4) && int.TryParse(np4, out var np4v)) p = p with { NetblockPrefixV4 = np4v };
if (Usable("netblockPrefixV6") && map.TryGetValue("netblockPrefixV6", out var np6) && int.TryParse(np6, out var np6v)) p = p with { NetblockPrefixV6 = np6v };
if (map.TryGetValue("redirectTargets", out var rt) && !string.IsNullOrWhiteSpace(rt))
p = p with { DefaultRedirectTargets = rt.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries) };
return p;
}
}