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.
167 lines
7.2 KiB
C#
167 lines
7.2 KiB
C#
using System.Collections.Concurrent;
|
|
using Microsoft.EntityFrameworkCore;
|
|
using Microsoft.Extensions.DependencyInjection;
|
|
using Microsoft.Extensions.Hosting;
|
|
using Microsoft.Extensions.Logging;
|
|
using OpenWaf.Domain.Engine;
|
|
using OpenWaf.Domain.Policy;
|
|
using OpenWaf.Domain.Security;
|
|
|
|
namespace OpenWaf.Infrastructure.Persistence;
|
|
|
|
/// <summary>
|
|
/// The watch that turns the edge's own bans into an offer (OPEN-67).
|
|
///
|
|
/// A scanner farm inside one /24 is twenty engine bans and twenty operator
|
|
/// decisions. OPEN-66 made a range enforceable; this is the half that notices
|
|
/// the range exists. It reads only what is already there — live engine bans —
|
|
/// and it writes nothing to the block list. The only thing it produces is a row
|
|
/// in the alert table and a line on a surface, both of which say the same
|
|
/// sentence: "these N bans sit inside this block, and here is the call that
|
|
/// would replace them".
|
|
///
|
|
/// Why a timer rather than the request path: the answer changes on the scale of
|
|
/// minutes, and a per-request grouping over the block table would price a
|
|
/// decision nobody is reading. Why not a database view: the grouping has to
|
|
/// consult the operator's ranges to know whether the offer was already taken,
|
|
/// and the rules of that comparison live in <see cref="Netblocks"/> where the
|
|
/// unit tests can reach them.
|
|
/// </summary>
|
|
public sealed class NetblockWatcher : BackgroundService
|
|
{
|
|
/// <summary>The alert kind. It is one of the fixed kinds this codebase
|
|
/// writes, which is what lets it be a metric label and a table filter.</summary>
|
|
public const string AlertKind = "netblock_candidate";
|
|
|
|
private static readonly TimeSpan Interval = TimeSpan.FromMinutes(5);
|
|
|
|
/// <summary>How often the same block may raise the same alert. A /24 that is
|
|
/// still producing bans every five minutes is the same news, and an alert
|
|
/// that repeats is an alert the operator stops reading — the same reasoning
|
|
/// that made the push queue count attempts instead of firing more payloads.</summary>
|
|
private static readonly TimeSpan AlertCooldown = TimeSpan.FromHours(6);
|
|
|
|
private readonly IServiceScopeFactory _scopeFactory;
|
|
private readonly EdgePolicyProvider _policy;
|
|
private readonly AlertWriter _alerts;
|
|
private readonly ILogger<NetblockWatcher> _log;
|
|
|
|
private readonly ConcurrentDictionary<string, DateTimeOffset> _alerted = new(StringComparer.Ordinal);
|
|
private long _lastScanTicks;
|
|
private IReadOnlyList<NetblockCandidate> _last = [];
|
|
private string? _lastError;
|
|
|
|
public NetblockWatcher(
|
|
IServiceScopeFactory scopeFactory, EdgePolicyProvider policy, AlertWriter alerts,
|
|
ILogger<NetblockWatcher> log)
|
|
{
|
|
_scopeFactory = scopeFactory;
|
|
_policy = policy;
|
|
_alerts = alerts;
|
|
_log = log;
|
|
}
|
|
|
|
/// <summary>When this process last looked, and what it saw. The state
|
|
/// surface shows both: a watch that is off, a watch that is failing and a
|
|
/// watch that found nothing have to read differently from the outside.</summary>
|
|
public DateTimeOffset LastScanAt => new(Interlocked.Read(ref _lastScanTicks), TimeSpan.Zero);
|
|
|
|
/// <summary>The last scan's answer, without running one. Cheap enough for a
|
|
/// status surface that is scraped more often than anyone reads it.</summary>
|
|
public IReadOnlyList<NetblockCandidate> LastCandidates() => _last;
|
|
|
|
public string? LastError => Volatile.Read(ref _lastError);
|
|
|
|
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
|
|
{
|
|
while (!stoppingToken.IsCancellationRequested)
|
|
{
|
|
try { await Task.Delay(Interval, stoppingToken); }
|
|
catch (TaskCanceledException) { return; }
|
|
try { await ScanAndAlertAsync(CancellationToken.None); }
|
|
catch (Exception ex) { _log.LogWarning(ex, "NetblockWatcher: the scan failed."); }
|
|
}
|
|
}
|
|
|
|
/// <summary>One scan. <paramref name="raiseAlerts"/> is false when a surface
|
|
/// asked for the answer: reading the list is not news, and an operator
|
|
/// refreshing a page must not be able to raise an alert per refresh.</summary>
|
|
public async Task<IReadOnlyList<NetblockCandidate>> ScanAndAlertAsync(CancellationToken ct)
|
|
=> await ScanAsync(true, ct);
|
|
|
|
public async Task<IReadOnlyList<NetblockCandidate>> ScanAsync(bool raiseAlerts, CancellationToken ct)
|
|
{
|
|
var policy = _policy.Current;
|
|
var now = DateTimeOffset.UtcNow;
|
|
|
|
if (policy.NetblockCandidateBans <= 0)
|
|
{
|
|
// Off is an answer, not a failure: the cache is cleared so a surface
|
|
// cannot keep showing candidates the operator switched off.
|
|
_last = [];
|
|
Interlocked.Exchange(ref _lastScanTicks, now.UtcTicks);
|
|
Volatile.Write(ref _lastError, null);
|
|
return _last;
|
|
}
|
|
|
|
IReadOnlyList<NetblockCandidate> candidates;
|
|
try
|
|
{
|
|
using var scope = _scopeFactory.CreateScope();
|
|
var db = scope.ServiceProvider.GetRequiredService<OpenWafDbContext>();
|
|
var token = ct;
|
|
|
|
var bans = await db.Blocks
|
|
.Where(b => b.Source == BlockSource.Engine && (b.ExpiresAt == null || b.ExpiresAt > now))
|
|
.Select(b => new { b.SourceKey, b.CreatedAt })
|
|
.AsNoTracking()
|
|
.ToListAsync(token);
|
|
|
|
var ranges = await db.NetworkBans
|
|
.Where(r => r.ExpiresAt == null || r.ExpiresAt > now)
|
|
.AsNoTracking()
|
|
.ToListAsync(token);
|
|
|
|
candidates = Netblocks.Candidates(
|
|
bans.Select(b => (b.SourceKey, b.CreatedAt)),
|
|
policy,
|
|
new NetworkBanIndex(ranges),
|
|
now);
|
|
Volatile.Write(ref _lastError, null);
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
// The watch is a suggestion engine, so a failure here retires the
|
|
// suggestions rather than repeating the last ones: an operator
|
|
// offering a range from a scan that never ran is offering a fact
|
|
// that stopped being true.
|
|
_last = [];
|
|
Volatile.Write(ref _lastError, ex.Message);
|
|
_log.LogWarning(ex, "NetblockWatcher: the scan failed; no candidates are offered.");
|
|
Interlocked.Exchange(ref _lastScanTicks, now.UtcTicks);
|
|
return _last;
|
|
}
|
|
|
|
_last = candidates;
|
|
Interlocked.Exchange(ref _lastScanTicks, now.UtcTicks);
|
|
|
|
if (raiseAlerts)
|
|
{
|
|
foreach (var candidate in candidates)
|
|
{
|
|
if (candidate.AlreadyBanned) continue;
|
|
if (_alerted.TryGetValue(candidate.Match, out var at) && now - at < AlertCooldown) continue;
|
|
_alerted[candidate.Match] = now;
|
|
await _alerts.RaiseAsync(
|
|
AlertKind, candidate.Match, candidate.Bans, null, null,
|
|
$"{candidate.Bans} live engine bans sit inside {candidate.Match}; "
|
|
+ $"the oldest is from {candidate.FirstBanAt:u} and the newest from {candidate.LastBanAt:u}. "
|
|
+ "Nothing was banned: POST /admin-api/blocks with this CIDR would replace those rows with one.",
|
|
ct);
|
|
}
|
|
}
|
|
|
|
return candidates;
|
|
}
|
|
}
|