Files
openwaf/dotnet/OpenWaf.Infrastructure/Persistence/BlockStore.cs
T
Pavlo Ratushnyi a77ab53ea8 A storage failure was reported to the operator as success, as their own bad request, and as ready
Measured on two shipped images of the same stand — openwaf:prefix built from
72d37ad and openwaf:ci built from this tree — with the block table and the
policy table dropped out from under a running edge that held 3 blocks and 1
policy row:

  DELETE /admin-api/blocks?source=operator   200 {"deleted":0}      -> 503 "NOTHING was deleted"
  DELETE /admin-api/blocks?key=203.0.113.201 200 {"deleted":0}      -> 503 "NOTHING was deleted"
  POST   /admin-api/blocks                   400 database error     -> 503 "the block is NOT in effect"
  PUT    /admin-api/policy {"mode":"Enforce"} 200, body mode=Observe -> 503 "the change is NOT in effect"
  GET    /admin-api/blocks                   500                    -> 500 (unchanged)
  GET    /readyz                             200 ready              -> 503
  GET    /healthz                            200                    -> 200 (unchanged: the recovery hatch)

Four separate lies, one class:

* BlockStore.DeleteAsync caught everything, logged a warning and returned 0, so
  the endpoint answered {"deleted":0} — the same bytes an empty list produces.
  A destructive command that could not run told the operator there was nothing
  to remove.
* BlockStore.AddOperatorAsync returned the string "database error" and the
  endpoint mapped it to 400, next to the real validation errors. A storage
  failure arrived as "your request is wrong", which invites a retry of the
  request while no block is in effect.
* PUT /admin-api/policy threw away SaveAsync's false and answered 200 with the
  policy body — showing the mode that had NOT been saved.
* /readyz used CanConnectAsync, which only proves the file opens. It kept
  answering 200 through all of the above.

The same stand, six concurrent POSTs for one address (no broken storage):
4x 204 and 2x 400 {"error":"database error"} before; 6x 204 after. The unique
index on (source key, provenance) made the loser of a race the API itself
started look like a caller who sent a bad request — which is what a double-click
on "block" in the console is. The write now retries against the winner's row.

The console had its own copy of the bug: every destructive row button wrote its
green note whatever came back, so a refused delete read as "deleted ? block(s)",
and load() — which runs after every action and on a 5 s interval — replaced the
error line with "refreshed" inside a second. The note now waits for an answer
that did not carry an error, and the refresh that follows a failed action holds
it. An empty 5xx body is now reported as an empty 5xx body instead of throwing
inside apiRaw and being swallowed.

Gates on this tree (macOS): build 0 warnings / 0 errors, unit 128/128,
integration 106/106 (7 new in StorageFailureHonestyTests), smoke 19/0,
compose 43/0, image 261 MB, console 45/45 (1 new assertion).
Dents: delete answers deleted:0 -> 2 fail; POST answers 400 -> 1; readyz trusts
CanConnectAsync -> 1; no retry after the unique-index loser -> 1; delete
swallows into a bare 0 -> 2; PUT /policy discards the save answer -> 1; console
writes the note whatever came back -> the console gate fails that assertion.
2026-10-02 04:22:07 +02:00

269 lines
12 KiB
C#

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 ILogger<BlockStore> _log;
public BlockStore(
IServiceScopeFactory scopeFactory,
EdgeStateStore state,
EdgePolicyProvider policy,
ILogger<BlockStore> log)
{
_scopeFactory = scopeFactory;
_state = state;
_policy = policy;
_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 async Task<BlockEntry?> BanAsync(StreakSnapshot streak, int statusCode, DateTimeOffset now, CancellationToken ct = default)
{
var policy = _policy.Current;
var expiresAt = now + policy.BanDuration;
var reason = $"{streak.MaxConsecutiveRefusals} consecutive refusals " +
$"({policy.RefusalRange}) within {policy.StreakWindow.TotalMinutes:0.#} min; " +
$"last {statusCode} {(streak.LastPath is null ? "" : streak.LastPath)}";
// 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 existing = await db.Blocks
.FirstOrDefaultAsync(b => b.SourceKey == streak.SourceKey && b.Source == BlockSource.Engine, ct);
if (existing is null)
{
existing = new BlockEntry
{
SourceKey = streak.SourceKey,
Source = BlockSource.Engine,
CreatedAt = now,
ExpiresAt = expiresAt,
Reason = reason,
ConsecutiveRefusals = streak.MaxConsecutiveRefusals
};
db.Blocks.Add(existing);
}
else if (!existing.IsLive(now))
{
existing.CreatedAt = now;
existing.ExpiresAt = expiresAt;
existing.Reason = reason;
existing.ConsecutiveRefusals = streak.MaxConsecutiveRefusals;
}
existing.LastStatusCode = statusCode;
existing.LastPath = streak.LastPath;
existing.LastUserAgent = streak.LastUserAgent;
existing.LastCountryCode = streak.LastCountryCode;
existing.LastCity = streak.LastCity;
existing.LastRegion = streak.LastRegion;
await db.SaveChangesAsync(ct);
await _state.InvalidateAsync(ct);
return existing;
}
catch (DbUpdateException ex)
{
// Still possible across processes — two edges sharing one database.
// The winner's row is the one that matters; the loser's evidence is
// already in the observation stream.
_log.LogWarning(ex, "BlockStore: concurrent ban on {Key}; keeping the winner.", streak.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.
_log.LogWarning(ex, "BlockStore: could not persist a ban for {Key}.", streak.SourceKey);
return null;
}
finally
{
_banGate.Release();
}
}
/// <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>
public async Task<(AddResult Result, string? Error)> AddOperatorAsync(
string sourceKey, string? reason, string? redirectTo, DateTimeOffset now, CancellationToken ct = default)
{
if (!SourceKey.TryParse(sourceKey, out _, out var normalized))
return (AddResult.InvalidInput, $"not an IP address: {sourceKey}");
var key = SourceKey.For(normalized.ToString(), _policy.Current);
for (var attempt = 0; attempt < 2; attempt++)
{
try
{
using var scope = _scopeFactory.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<OpenWafDbContext>();
var row = await db.Blocks.FirstOrDefaultAsync(b => b.SourceKey == key && b.Source == BlockSource.Operator, ct);
if (row is null)
{
db.Blocks.Add(new BlockEntry
{
SourceKey = key,
Source = BlockSource.Operator,
CreatedAt = now,
Reason = reason,
RedirectTo = redirectTo
});
}
else
{
row.Reason = reason ?? row.Reason;
row.RedirectTo = redirectTo ?? row.RedirectTo;
}
await db.SaveChangesAsync(ct);
await _state.InvalidateAsync(ct);
return (AddResult.Ok, null);
}
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");
}
}
return (AddResult.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 q = db.Blocks.AsQueryable();
if (source is not null) q = q.Where(b => b.Source == source.Value);
if (!string.IsNullOrWhiteSpace(sourceKey)) q = q.Where(b => b.SourceKey == sourceKey);
var n = await q.ExecuteDeleteAsync(ct);
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;
public async Task<List<BlockEntry>> 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 q = Filtered(db, source, liveOnly, now);
return await q.OrderByDescending(b => b.CreatedAt).Skip(offset).Take(limit).ToListAsync(ct);
}
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>();
return await Filtered(db, source, liveOnly, now).CountAsync(ct);
}
private static IQueryable<BlockEntry> Filtered(OpenWafDbContext db, BlockSource? source, bool liveOnly, DateTimeOffset now)
{
var q = db.Blocks.AsNoTracking().AsQueryable();
if (source is not null) q = q.Where(b => b.Source == source.Value);
if (liveOnly) q = q.Where(b => b.ExpiresAt == null || b.ExpiresAt > now);
return q;
}
}