Files
Pavlo Ratushnyi 7c5e1ef230
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 edge gains a schema step a compiled binary can run, and NativeAOT gets a measured verdict
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.
2026-10-06 05:20:28 +02:00

730 lines
36 KiB
C#

using System.Collections.Concurrent;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using OpenWaf.Domain.Engine;
using OpenWaf.Domain.Policy;
using OpenWaf.Domain.Security;
namespace OpenWaf.Infrastructure.Persistence;
/// <summary>
/// Every write to the block list goes through here, for one reason: the
/// difference between an operator entry and an engine ban has to be enforced
/// somewhere, and it should not be the caller's memory.
/// </summary>
public sealed class BlockStore
{
private readonly IServiceScopeFactory _scopeFactory;
private readonly EdgeStateStore _state;
/// <summary>Ban writes are rare — once per source per ban — so one gate
/// serialises them cheaply. Without it two requests from the same source
/// that finish a few milliseconds apart both read "no ban yet" and both
/// insert, and the loser's evidence is lost to the unique index. The
/// observer runs after the response is written, so the client is free to
/// send the next request while the previous one's ban is still landing.</summary>
private readonly SemaphoreSlim _banGate = new(1, 1);
private readonly EdgePolicyProvider _policy;
private readonly DurabilityHealth _health;
private readonly ILogger<BlockStore> _log;
public BlockStore(
IServiceScopeFactory scopeFactory,
EdgeStateStore state,
EdgePolicyProvider policy,
DurabilityHealth health,
ILogger<BlockStore> log)
{
_scopeFactory = scopeFactory;
_state = state;
_policy = policy;
_health = health;
_log = log;
}
/// <summary>
/// Issue or refresh an engine ban. Rare (once per source per ban), so it
/// writes immediately instead of going through the coalescing writer — a
/// ban that lands 15 seconds late is a ban that let 15 more requests through.
///
/// A live ban is not extended: a scanner that keeps probing while already
/// blocked must not be able to extend its own sentence indefinitely. Its
/// evidence is refreshed so the operator sees the latest probe.
/// </summary>
public Task<BlockEntry?> BanAsync(StreakSnapshot streak, int statusCode, DateTimeOffset now, CancellationToken ct = default)
=> WriteBanAsync(PendingBan.From(streak, statusCode, now), now, ct);
/// <summary>
/// A ban the engine decided and could not write, kept in memory so the retry
/// does not depend on the source offending again.
///
/// Measured on the shipped image (2026-10-02): with writes to block_entries
/// aborted, five refusals produced three counted write failures and
/// /readyz 503. The triggers were then REMOVED — the write path healthy,
/// zero triggers left — and no further traffic was sent. /readyz answered 503
/// at t+30, t+60, t+90 and t+120 s with the counters unmoved. The only thing
/// that clears the counter is a successful ban write, and the only thing that
/// produced one was the attacker coming back. So an edge that enforces
/// everything except one ban it decided during a storage blip sat out of
/// rotation for as long as the site stayed quiet: the recovery signal was
/// attacker traffic.
///
/// The sentence still runs from DecidedAt, so a retry that lands late does
/// not quietly extend a ban; and a pending ban whose sentence has already
/// expired is reported as never enforced rather than written as a fresh one.
/// </summary>
public sealed record PendingBan(
string SourceKey, int ConsecutiveRefusals, int StatusCode, string? Path, string? UserAgent,
string? CountryCode, string? City, string? Region, DateTimeOffset DecidedAt,
/// <summary>Set when the ban was not decided by a streak. The default
/// wording below says "consecutive refusals", which is true of the
/// streak and a lie about a volume breach, and an operator reading a
/// ban's reason is reading the explanation of why they are locked
/// out.</summary>
string? ReasonText = null)
{
public static PendingBan From(StreakSnapshot s, int statusCode, DateTimeOffset now) => new(
s.SourceKey, s.MaxConsecutiveRefusals, statusCode, s.LastPath, s.LastUserAgent,
s.LastCountryCode, s.LastCity, s.LastRegion, now);
}
/// <summary>Pending bans waiting to be written. Bounded by the number of
/// distinct sources the engine has decided to ban, which is bounded by the
/// streak map; a dead database cannot grow it without limit.</summary>
private readonly ConcurrentDictionary<string, PendingBan> _pendingBans = new(StringComparer.Ordinal);
private long _bansNeverEnforced;
public int PendingBanRetries => _pendingBans.Count;
/// <summary>Bans that were decided, failed to reach storage, and whose
/// sentence expired before a retry could land. Cumulative: a ban that was
/// never enforced is a hole in the record, not a gauge.</summary>
public long BansNeverEnforced => Interlocked.Read(ref _bansNeverEnforced);
/// <summary>
/// Re-attempt every ban that failed to reach storage. Called by
/// <see cref="PendingBanRetryWorker"/> on the same cadence the other writers
/// use, so a storage failure that heals returns the edge to ready without
/// waiting for traffic.
/// </summary>
public async Task<int> RetryPendingBansAsync(CancellationToken ct = default)
{
if (_pendingBans.IsEmpty) return 0;
var now = DateTimeOffset.UtcNow;
var policy = _policy.Current;
var written = 0;
foreach (var (_, ban) in _pendingBans.ToArray())
{
if (ban.DecidedAt + policy.BanDuration <= now)
{
if (_pendingBans.TryRemove(ban.SourceKey, out _))
{
Interlocked.Increment(ref _bansNeverEnforced);
_log.LogWarning(
"BlockStore: a ban decided for {Key} at {Decided} expired before it could be written. "
+ "It was never enforced by any edge.", ban.SourceKey, ban.DecidedAt);
}
continue;
}
await WriteBanAsync(ban, now, ct);
if (!_pendingBans.ContainsKey(ban.SourceKey)) written++;
}
return written;
}
/// <summary>
/// Issue or refresh an engine ban decided by the volume pillar (OPEN-56).
///
/// The refusal itself is answered by the guard, immediately, with a 429 —
/// this write is what makes the stop outlast the window it was counted in:
/// it is a row, so the other edges see it and a restart does not forget
/// it, and it appears on the blocks listing where an operator can see and
/// clear it. It goes through the same gate and the same "a live ban is not
/// extended" rule as a streak ban, because a flood that keeps arriving must
/// not be able to lengthen its own sentence.
/// </summary>
public Task<BlockEntry?> BanForRateAsync(
string sourceKey, int count, int limit, TimeSpan window,
string? path, string? userAgent, string? countryCode, string? city, string? region,
DateTimeOffset now, CancellationToken ct = default)
=> WriteBanAsync(new PendingBan(
sourceKey, 0, 429, path, userAgent, countryCode, city, region, now,
$"{count} requests from this source in {window.TotalSeconds:0.#} s against a budget of "
+ $"{limit}; the {limit + 1}th was refused (rate policy)"), now, ct);
private async Task<BlockEntry?> WriteBanAsync(PendingBan ban, DateTimeOffset now, CancellationToken ct)
{
var policy = _policy.Current;
// From when the ban was decided, not from when a retry landed: a write
// that arrives late must not silently lengthen the sentence.
var expiresAt = ban.DecidedAt + policy.BanDuration;
var reason = ban.ReasonText ?? $"{ban.ConsecutiveRefusals} consecutive refusals " +
$"({policy.RefusalRange}) within {policy.StreakWindow.TotalMinutes:0.#} min; " +
$"last {ban.StatusCode} {(ban.Path is null ? "" : ban.Path)}";
// Serialised: the observer runs after the response has been written,
// so the next request from the same source can arrive while this ban is
// still landing, and two readers that both see "no ban yet" produce a
// unique-index loser and a lost evidence row.
await _banGate.WaitAsync(ct);
try
{
using var scope = _scopeFactory.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<OpenWafDbContext>();
var token = ct;
var bannedKey = ban.SourceKey;
var existing = await db.Blocks
.FirstOrDefaultAsync(b => b.SourceKey == bannedKey && b.Source == BlockSource.Engine, token);
if (existing is null)
{
existing = new BlockEntry
{
SourceKey = ban.SourceKey,
Source = BlockSource.Engine,
CreatedAt = now,
ExpiresAt = expiresAt,
Reason = reason,
ConsecutiveRefusals = ban.ConsecutiveRefusals > 0 ? ban.ConsecutiveRefusals : null
};
db.Blocks.Add(existing);
}
else if (!existing.IsLive(now))
{
existing.CreatedAt = now;
existing.ExpiresAt = expiresAt;
existing.Reason = reason;
if (ban.ConsecutiveRefusals > 0) existing.ConsecutiveRefusals = ban.ConsecutiveRefusals;
}
existing.LastStatusCode = ban.StatusCode;
existing.LastPath = ban.Path;
existing.LastUserAgent = ban.UserAgent;
existing.LastCountryCode = ban.CountryCode;
existing.LastCity = ban.City;
existing.LastRegion = ban.Region;
await db.SaveChangesAsync(ct);
// Clears the counter only when a ban actually reached storage, so
// readiness comes back on evidence rather than on the passage of
// time.
_health.RecordSuccess(DurabilityHealth.Bans, 1);
_pendingBans.TryRemove(ban.SourceKey, out _);
await _state.InvalidateAsync(ct);
return existing;
}
catch (DbUpdateException ex)
{
// Two opposite failures arrive here, and the shipped image called
// both of them the benign one. The benign one is the cross-process
// race the unique index exists to settle: the winner's row is in
// storage, the ban is in force, this edge has nothing to do. The
// other one is storage failing, and it was measured being reported
// as a race — with writes to block_entries aborted by a SQLite
// trigger, five refusals from one source at a threshold of 3
// answered 404 five times, no ban ever reached storage (engine bans
// stayed at 1), /readyz answered 200, and the log said "concurrent
// ban on 203.0.113.12; keeping the winner" four times while the
// inner exception was SQLite Error 19: 'gate: ban write blocked'.
//
// Storage itself is the discriminator: re-read the row. A live row
// for this source and provenance means somebody won the race; no
// row — or a read that cannot run either — means the write never
// happened and the ban is not in force anywhere.
if (await HasLiveEngineBanAsync(ban.SourceKey, now, ct))
{
// Somebody else's ban is in force, so this one is not pending:
// leaving it queued would retry a write that is already settled.
_pendingBans.TryRemove(ban.SourceKey, out _);
_log.LogWarning(ex, "BlockStore: concurrent ban on {Key}; keeping the winner.", ban.SourceKey);
return null;
}
_health.RecordFailure(DurabilityHealth.Bans, ex, 1);
_pendingBans[ban.SourceKey] = ban;
_log.LogWarning(ex,
"BlockStore: could not persist a ban for {Key}. This edge is NOT enforcing it — enforcement "
+ "reads the snapshot, and the snapshot is built from storage — so no edge is. The write is "
+ "queued for retry; it does not wait for this source to offend again.", ban.SourceKey);
return null;
}
catch (Exception ex)
{
// A ban that could not be written must not take the request down.
// The streak is still in memory, so the next refusal retries.
_health.RecordFailure(DurabilityHealth.Bans, ex, 1);
_pendingBans[ban.SourceKey] = ban;
_log.LogWarning(ex,
"BlockStore: could not persist a ban for {Key}. This edge is NOT enforcing it — enforcement "
+ "reads the snapshot, and the snapshot is built from storage — so no edge is. The write is "
+ "queued for retry; it does not wait for this source to offend again.", ban.SourceKey);
return null;
}
finally
{
_banGate.Release();
}
}
/// <summary>
/// Is there a live engine ban for this source in storage right now? Used to
/// tell a lost unique-index race from a storage failure. A read that itself
/// fails answers "no", which routes the caller to the storage-failure path —
/// the conservative direction, because claiming a race won when nothing was
/// written is exactly the lie this method exists to stop.
/// </summary>
private async Task<bool> HasLiveEngineBanAsync(string sourceKey, DateTimeOffset now, CancellationToken ct)
{
try
{
using var scope = _scopeFactory.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<OpenWafDbContext>();
// Copied to locals: EF's query precompiler — the only way a NativeAOT
// build runs LINQ at all — fails on a captured method parameter
// (dotnet/efcore#35887, fixed only in 12.0-preview1).
var key = sourceKey;
var asOf = now;
var token = ct;
return await db.Blocks.AsNoTracking()
.AnyAsync(b => b.SourceKey == key && b.Source == BlockSource.Engine && b.ExpiresAt > asOf, token);
}
catch (Exception ex)
{
_log.LogDebug(ex, "BlockStore: the ban re-read used to settle a race could not run either.");
return false;
}
}
/// <summary>What a write to the block list ended as. The caller has to be
/// able to tell "your input was wrong" from "the storage failed", because
/// those two arrive at the operator as different answers and different
/// next actions — and until now they arrived as the same 400.</summary>
public enum AddResult { Ok, InvalidInput, StorageFailure }
/// <summary>
/// Add or refresh an operator block.
///
/// Two attempts, deliberately: the read-then-insert below is not atomic and
/// the unique index on (source key, provenance) is what makes the loser of
/// that race throw. Measured on the shipped image (openwaf:ci, head
/// 72d37ad) with six concurrent POSTs for one address: 4 answered 204 and 2
/// answered <c>400 {"error":"database error"}</c> — the block was in effect
/// either way, so what the operator saw was a 400 blaming their own request
/// for a race the API itself caused. That is exactly what a double-click in
/// the console looks like. The retry takes the winner's row and updates it,
/// which is the same path a sequential repeat already takes.
/// </summary>
/// <summary>
/// Put an address behind an operator block. <c>expiresInMinutes</c> is the
/// time box: present sets (or moves) the expiry, absent leaves whatever the
/// row already had — for a new row, that is no expiry, which is what every
/// operator block written before OPEN-51 was.
/// </summary>
public async Task<(AddResult Result, string? Error, string? Target)> AddOperatorAsync(
string written, string? reason, string? redirectTo, int? expiresInMinutes,
DateTimeOffset now, CancellationToken ct = default)
{
// One control, two shapes (OPEN-66). What the operator typed is either an
// address or a network, and the answer says which one it stored, because
// 198.51.100.37/24 and 198.51.100.0/24 are one row and the operator has
// to be able to find it under the spelling the edge kept.
if (!NetworkBans.TryNormalize(written, out var normalized, out var inputError))
return (AddResult.InvalidInput, inputError, null);
if (NetworkBans.IsRangeSyntax(normalized))
return await AddRangeAsync(normalized, reason, redirectTo, expiresInMinutes, now, ct);
var key = SourceKey.For(normalized, _policy.Current);
for (var attempt = 0; attempt < 2; attempt++)
{
try
{
using var scope = _scopeFactory.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<OpenWafDbContext>();
var token = ct;
var row = await db.Blocks.FirstOrDefaultAsync(b => b.SourceKey == key && b.Source == BlockSource.Operator, token);
if (row is null)
{
db.Blocks.Add(new BlockEntry
{
SourceKey = key,
Source = BlockSource.Operator,
CreatedAt = now,
Reason = reason,
RedirectTo = redirectTo,
ExpiresAt = expiresInMinutes is { } fresh ? now.AddMinutes(fresh) : null
});
}
else
{
row.Reason = reason ?? row.Reason;
row.RedirectTo = redirectTo ?? row.RedirectTo;
// Re-blocking with a duration moves the expiry rather than
// leaving an old one in place: the operator who types "240"
// a second time means two hundred and forty minutes from now.
if (expiresInMinutes is { } again) row.ExpiresAt = now.AddMinutes(again);
}
await db.SaveChangesAsync(ct);
await _state.InvalidateAsync(ct);
return (AddResult.Ok, null, normalized);
}
catch (DbUpdateException ex) when (attempt == 0)
{
_log.LogWarning(ex, "BlockStore: concurrent add on {Key}; retrying against the winner's row.", key);
}
catch (Exception ex)
{
// Not the caller's fault, and not a success either. The old
// answer was a 400 whose only content was "database error",
// which reads like a rejected request: an operator who retried
// got the same 400 and moved on, while the block they typed was
// never in effect.
_log.LogWarning(ex, "BlockStore: add operator block failed for {Key}.", key);
return (AddResult.StorageFailure, "the block list could not be written: the block is NOT in effect", null);
}
}
return (AddResult.StorageFailure, "the block list could not be written: the block is NOT in effect", null);
}
/// <summary>
/// Put a network behind an operator block (OPEN-66).
///
/// Same shape as the address write, on purpose: the same two attempts
/// against a unique index, the same "a write that cannot run is not a
/// success", the same expiry rules. The only difference is the key — a
/// normalised network rather than a source key — and that difference is why
/// this is a separate table: the exact-key lookup that enforces an address
/// block would read "198.51.100.0/24" as an address and answer "no" to every
/// visitor inside the range.
/// </summary>
private async Task<(AddResult Result, string? Error, string? Target)> AddRangeAsync(
string match, string? reason, string? redirectTo, int? expiresInMinutes,
DateTimeOffset now, CancellationToken ct)
{
for (var attempt = 0; attempt < 2; attempt++)
{
try
{
using var scope = _scopeFactory.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<OpenWafDbContext>();
var target = match;
var token = ct;
var row = await db.NetworkBans.FirstOrDefaultAsync(b => b.Match == target, token);
if (row is null)
{
db.NetworkBans.Add(new NetworkBan
{
Match = match,
CreatedAt = now,
Reason = reason,
RedirectTo = redirectTo,
ExpiresAt = expiresInMinutes is { } fresh ? now.AddMinutes(fresh) : null
});
}
else
{
row.Reason = reason ?? row.Reason;
row.RedirectTo = redirectTo ?? row.RedirectTo;
// Re-writing a range with a duration moves the expiry, exactly
// as it does for an address: the operator who types "240" a
// second time means two hundred and forty minutes from now.
if (expiresInMinutes is { } again) row.ExpiresAt = now.AddMinutes(again);
}
await db.SaveChangesAsync(ct);
await _state.InvalidateAsync(ct);
return (AddResult.Ok, null, match);
}
catch (DbUpdateException ex) when (attempt == 0)
{
_log.LogWarning(ex, "BlockStore: concurrent add on the range {Match}; retrying against the winner's row.", match);
}
catch (Exception ex)
{
_log.LogWarning(ex, "BlockStore: add of the range {Match} failed.", match);
return (AddResult.StorageFailure, "the block list could not be written: the block is NOT in effect", null);
}
}
return (AddResult.StorageFailure, "the block list could not be written: the block is NOT in effect", null);
}
/// <summary>What an imported operator block ended as. Different from
/// <see cref="AddResult"/> because an import is not a re-write: a row that
/// is already there is reported as already there and left alone, so the
/// same document applied twice lands once (OPEN-61).</summary>
public enum ImportResult { Added, AlreadyThere, StorageFailure }
/// <summary>
/// Land one operator block from a transferred document.
///
/// Two differences from <see cref="AddOperatorAsync"/>, and both are the
/// transfer's rulings rather than implementation detail. The expiry is an
/// instant carried by the document, not a number of minutes from now — a
/// block that expires in ten minutes on the edge it came from expires in ten
/// minutes here. And a live row for the same source is not refreshed: the
/// operator who imports twice gets the same table, not a table whose expiry
/// moved under them.
/// </summary>
public async Task<(ImportResult Result, string? Error)> ImportOperatorAsync(
string address, string? reason, string? redirectTo, DateTimeOffset? expiresAt,
DateTimeOffset now, CancellationToken ct = default)
{
if (!NetworkBans.TryNormalize(address, out var normalized, out _))
return (ImportResult.StorageFailure, $"not an IP address: {address}");
if (NetworkBans.IsRangeSyntax(normalized))
return await ImportRangeAsync(normalized, reason, redirectTo, expiresAt, now, ct);
var key = SourceKey.For(normalized, _policy.Current);
for (var attempt = 0; attempt < 2; attempt++)
{
try
{
using var scope = _scopeFactory.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<OpenWafDbContext>();
var token = ct;
var asOf = now;
var live = await db.Blocks.AnyAsync(
b => b.SourceKey == key && b.Source == BlockSource.Operator
&& (b.ExpiresAt == null || b.ExpiresAt > asOf), token);
if (live) return (ImportResult.AlreadyThere, null);
db.Blocks.Add(new BlockEntry
{
SourceKey = key,
Source = BlockSource.Operator,
CreatedAt = now,
Reason = reason,
RedirectTo = redirectTo,
ExpiresAt = expiresAt
});
await db.SaveChangesAsync(ct);
return (ImportResult.Added, null);
}
catch (DbUpdateException ex) when (attempt == 0)
{
_log.LogWarning(ex, "BlockStore: concurrent import on {Key}; retrying against the winner's row.", key);
}
catch (Exception ex)
{
_log.LogWarning(ex, "BlockStore: import of an operator block failed for {Key}.", key);
return (ImportResult.StorageFailure, "the block list could not be written: the block is NOT in effect");
}
}
return (ImportResult.StorageFailure, "the block list could not be written: the block is NOT in effect");
}
/// <summary>Land one range from a transferred document. The expiry is the
/// instant the document carried, and a live row for the same network is not
/// refreshed — the same two rulings as the address import, for the same
/// reason (OPEN-61, OPEN-66).</summary>
private async Task<(ImportResult Result, string? Error)> ImportRangeAsync(
string match, string? reason, string? redirectTo, DateTimeOffset? expiresAt,
DateTimeOffset now, CancellationToken ct)
{
for (var attempt = 0; attempt < 2; attempt++)
{
try
{
using var scope = _scopeFactory.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<OpenWafDbContext>();
var target = match;
var token = ct;
var asOf = now;
var live = await db.NetworkBans.AnyAsync(
b => b.Match == target && (b.ExpiresAt == null || b.ExpiresAt > asOf), token);
if (live) return (ImportResult.AlreadyThere, null);
db.NetworkBans.Add(new NetworkBan
{
Match = match,
CreatedAt = now,
Reason = reason,
RedirectTo = redirectTo,
ExpiresAt = expiresAt
});
await db.SaveChangesAsync(ct);
return (ImportResult.Added, null);
}
catch (DbUpdateException ex) when (attempt == 0)
{
_log.LogWarning(ex, "BlockStore: concurrent import on the range {Match}; retrying against the winner's row.", match);
}
catch (Exception ex)
{
_log.LogWarning(ex, "BlockStore: import of the range {Match} failed.", match);
return (ImportResult.StorageFailure, "the block list could not be written: the block is NOT in effect");
}
}
return (ImportResult.StorageFailure, "the block list could not be written: the block is NOT in effect");
}
/// <summary>
/// Delete blocks, optionally restricted to one provenance. The provenance
/// filter is not cosmetic: "clear the automatic bans" must never be able to
/// erase what an operator typed by hand, which is exactly what R1 forbids.
/// </summary>
public enum DeleteResult { Ok, StorageFailure }
/// <summary>
/// Delete blocks, optionally restricted to one provenance. The provenance
/// filter is not cosmetic: "clear the automatic bans" must never be able to
/// erase what an operator typed by hand, which is exactly what R1 forbids.
///
/// The count is only meaningful when the result is Ok. Returning 0 from the
/// catch was the bug: measured on the shipped image with the block table
/// dropped out from under a running edge that held two operator blocks,
/// <c>DELETE ?source=operator</c> answered <c>200 {"deleted":0}</c> — the
/// same bytes the operator gets when the list really is empty. A destructive
/// command that cannot run has to say it did not run.
/// </summary>
public async Task<(DeleteResult Result, int Deleted)> DeleteAsync(BlockSource? source, string? sourceKey, CancellationToken ct = default)
{
try
{
using var scope = _scopeFactory.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<OpenWafDbContext>();
var token = ct;
var n = 0;
if (NetworkBans.IsRangeSyntax(sourceKey))
{
// A range asked for by name. It can only ever be an operator's
// row — the engine does not write ranges — so the provenance the
// caller named is checked rather than assumed.
if (source is BlockSource.Engine)
return (DeleteResult.Ok, 0);
var normalized = NetworkBans.TryNormalize(sourceKey!, out var match, out _)
? match
: sourceKey!;
n += await db.NetworkBans.Where(b => b.Match == normalized).ExecuteDeleteAsync(token);
await _state.InvalidateAsync(ct);
return (DeleteResult.Ok, n);
}
// One chain rather than an IQueryable assembled by two ifs: the
// precompiler reads the query out of the source text, so a query
// composed across statements is "dynamic" to it no matter what it
// does at run time. The two filters are the same two conditions,
// written as the disjunction EF can see.
var provenance = source;
var key = sourceKey;
n += await db.Blocks
.Where(b => (provenance == null || b.Source == provenance)
&& (string.IsNullOrWhiteSpace(key) || b.SourceKey == key))
.ExecuteDeleteAsync(token);
// The listing is one list, so a clear that names the operator's list
// has to clear both shapes of it: answering "deleted 4" while a /24
// is still refusing visitors inside it is the same lie as reporting an
// empty table that still enforces something. Engine clears never touch
// a range — the engine did not write one.
if (string.IsNullOrWhiteSpace(sourceKey) && source is not BlockSource.Engine)
n += await db.NetworkBans.ExecuteDeleteAsync(token);
await _state.InvalidateAsync(ct);
return (DeleteResult.Ok, n);
}
catch (Exception ex)
{
_log.LogWarning(ex, "BlockStore: delete failed.");
return (DeleteResult.StorageFailure, 0);
}
}
/// <summary>
/// The listing is capped, and the cap has to travel with the answer. A page
/// that shows 500 rows out of 2 000 and says nothing is an operator surface
/// that teaches an operator to under-count their own block list — the delete
/// beside it is not capped, so the mismatch is silent in both directions.
/// </summary>
public const int ListDefaultLimit = 500;
public const int ListMaxLimit = 2000;
/// <summary>One row of the operator's list, whichever table it came from.
/// The listing an operator reads is one list (OPEN-66), so the merge happens
/// here rather than in every caller that would otherwise have to know there
/// are two tables behind one page.</summary>
public sealed record BlockRow(BlockEntry? Entry, NetworkBan? Range)
{
// Every accessor picks a row first and then reads the field. The shorter
// `Range?.Field ?? Entry!.Field` is a trap here and threw in the listing:
// the two rows are mutually exclusive, so whenever the range's field is
// null — a range with no expiry, no reason, no redirect, which is the
// common case — the fallback dereferences the row that does not exist.
public bool IsRange => Range is not null;
public long Id => Range is not null ? Range.Id : Entry!.Id;
/// <summary>What the operator wrote, in the spelling the edge kept.</summary>
public string Target => Range is not null ? Range.Match : Entry!.SourceKey;
public DateTimeOffset CreatedAt => Range is not null ? Range.CreatedAt : Entry!.CreatedAt;
public DateTimeOffset? ExpiresAt => Range is not null ? Range.ExpiresAt : Entry!.ExpiresAt;
public string? Reason => Range is not null ? Range.Reason : Entry!.Reason;
public string? RedirectTo => Range is not null ? Range.RedirectTo : Entry!.RedirectTo;
public string Source => Range is not null ? "operator" : Entry!.Source.ToString().ToLowerInvariant();
public bool IsLive(DateTimeOffset now)
=> (Range is not null ? Range.ExpiresAt : Entry!.ExpiresAt) is not { } expiry || expiry > now;
}
public async Task<List<BlockRow>> ListAsync(BlockSource? source, bool liveOnly, DateTimeOffset now,
int limit = ListDefaultLimit, int offset = 0, CancellationToken ct = default)
{
using var scope = _scopeFactory.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<OpenWafDbContext>();
var provenance = source;
var live = liveOnly;
var asOf = now;
var page = limit;
var skip = offset;
var token = ct;
var blocks = await db.Blocks
.AsNoTracking()
.Where(b => (provenance == null || b.Source == provenance)
&& (!live || b.ExpiresAt == null || b.ExpiresAt > asOf))
.OrderByDescending(b => b.CreatedAt).Skip(skip).Take(page)
.ToListAsync(token);
// Ranges are read with the same window rather than re-filtered per page:
// the two tables are small by design, and ordering the union needs both
// sides of the cut. Anything past offset+limit is not shown either way.
var ranges = source == BlockSource.Engine
? []
: await db.NetworkBans
.AsNoTracking()
.Where(b => !live || b.ExpiresAt == null || b.ExpiresAt > asOf)
.OrderByDescending(b => b.CreatedAt).Skip(skip).Take(page)
.ToListAsync(token);
return blocks.Select(b => new BlockRow(b, null))
.Concat(ranges.Select(r => new BlockRow(null, r)))
.OrderByDescending(r => r.CreatedAt)
.ToList();
}
public async Task<int> CountAsync(BlockSource? source, bool liveOnly, DateTimeOffset now, CancellationToken ct = default)
{
using var scope = _scopeFactory.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<OpenWafDbContext>();
var provenance = source;
var live = liveOnly;
var asOf = now;
var token = ct;
var blocks = await db.Blocks
.AsNoTracking()
.Where(b => (provenance == null || b.Source == provenance)
&& (!live || b.ExpiresAt == null || b.ExpiresAt > asOf))
.CountAsync(token);
var ranges = source == BlockSource.Engine
? 0
: await db.NetworkBans
.AsNoTracking()
.Where(b => !live || b.ExpiresAt == null || b.ExpiresAt > asOf)
.CountAsync(token);
return blocks + ranges;
}
}