ci / lint the workflow and the shell (push) Successful in 10s
geo-freshness / the pinned geo database vs the vendor (push) Successful in 5s
ci / the operator page in a real browser (push) Successful in 3m42s
ci / build, test, smoke (push) Failing after 2m6s
ci / build the image and smoke it (push) Successful in 5m7s
The Dockerfile said "why not NativeAOT" on the authority of another repo's
Dockerfile. That claim is now this repo's own, and it is a measurement.
What was built to find out:
* Persistence/Schema/schema.sqlite.sql — the model's DDL, generated by
`dotnet ef dbcontext script`, embedded in the binary and read by
Persistence/EmbeddedSchema.cs. A NativeAOT build cannot ask EF to build a
model at run time, and EnsureCreated and GenerateCreateScript both go through
the design-time model, so the schema step has nowhere to get its SQL from.
OPENWAF_SCHEMA=script is the fourth strategy: same provider-shaped
statements, produced at build time instead of at start-up. The schema-script
CI step regenerates the file and fails the run when the committed copy is not
what the current model produces (5652 bytes today).
* SchemaUpgrader.ModelTables asks the runtime model, per entity type. The
design-time one is refused outright under NativeAOT, and GetRelationalModel()
on the runtime model of a compiled model throws
"The annotation 'Relational:DefaultMappings' cannot be added because an
annotation with the same name already exists on the object EntityType:
CountryRule" — building a compiled model's relational model a second time
collides with itself.
* The persistence layer's queries were rewritten into the shape EF's query
precompiler accepts: captured parameters copied to locals, conditional
IQueryable composition written as literal chains, aggregates that take a
predicate given their own Where. 40 of them were refused before that.
* dotnet-ef and EF Core moved 10.0.0 -> 10.0.12, because 10.0.0's design package
ships no build host and `--precompile-queries` cannot load a project without it.
What the measurement says, from scripts/aot-probe.sh on osx-arm64: the AOT build
compiles (48,797,072-byte native binary, 10 IL warnings, 0 errors), starts, and
creates all 12 tables from the DDL it carries. Then it never serves. EF refuses
every query at run time ("Query wasn't precompiled and dynamic code isn't
supported with NativeAOT"), and the precompiler that would fix that is not
usable on this model: after all 40 refusals were cleared it emitted 14
declarations with dots in the identifier
(`var openWaf.Domain.Security.BlockEntryPrimaryKeyProperties = …`) — 28 CS1002
and CS1003 errors, one per entity materialisation — with or without --nativeaot.
The refusals themselves trace to dotnet/efcore#35887, #38030 and #35494; the fix
landed in the 12.0-preview1 milestone, not in any 10.0.x.
Two things were not kept, and why:
* The atomic alert-queue claim and the claim release were rewritten as raw SQL
to dodge the precompiler's ExecuteUpdate failures. Reverted: with the
statement written as SQL, DateTimeOffset reaches sqlite as a provider
parameter instead of through the property's own mapping, the reclaim
comparison stops matching, and
AlertPushQueueTests.A_delivery_owed_by_a_process_that_stopped_is_owed_by_the_next_one
fails with the row still owed. A correctness risk here buys nothing when the
AOT build is blocked further along anyway.
* --nativeaot on the compiled model: its unsafe accessors do not compile
(CS1503 in BlockEntryEntityType.cs). The plain compiled model is what is
committed.
The compose gate's two escalation-count scenes also stopped being a coin toss.
They slept a fixed 2 s and then counted; on a loaded host the same tree read 3
rows once and 1 the next, and the assertion is about a settled number either
way. They now wait for three equal reads, bounded. The scene count is unchanged
at 368.
Gates at this commit: build 0 warnings / 0 errors, unit 378/378, integration
405/405, schema-script ok, smoke 256/0, compose-smoke 368/0, README counts
match (256, 368), lint clean (actionlint 1.7.12, shellcheck 0.11.0).
Not verified: the AOT image on linux-x64 — the probe ran on osx-arm64, and the
ILC failure mode that ends the attempt is a codegen bug in EF, not a
platform-specific one, but that is an inference rather than a measurement.
159 lines
9.0 KiB
C#
159 lines
9.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 token = ct;
|
|
var rows = await db.PolicySettings.AsNoTracking().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;
|
|
}
|
|
}
|