Files
openwaf/dotnet/OpenWaf.Infrastructure/Persistence/BlockStore.cs
T
Pavlo Ratushnyi 0161018d4d Say when the block listing is not the whole answer
GET /admin-api/blocks silently returned the newest 500 rows. The delete beside
it is not capped, so an operator counting 500 rows on a page — or in the console
— under-counts their own block list in one direction and over-trusts the clear
button in the other. Found while measuring the snapshot refresh cost: 2 000
seeded blocks, 500 rows back, no word about it.

The cap stays (a 2 000-row dump is not a page), but it now travels with the
answer: X-Total-Count and X-Truncated headers, plus limit/offset (default 500,
max 2000). The console renders the difference: showing the newest 500 of 2000,
and clearing by provenance removes all of them, not just this page.

Verified on the deployed image, not only in the fixture: with 600 blocks the
default listing answers X-Total-Count: 600 / X-Truncated: true, and limit=1000
answers X-Truncated: false with all 600 rows. The first attempt at that check
ran against a stale compose image — compose up without --build reuses it. The
README and compose-smoke.sh both use --build; the check had to.

Gates: 36 unit + 20 integration, 0 failed; smoke 19/19; compose-smoke 27/27;
actionlint and shellcheck both 0.
2026-10-01 12:05:58 +02:00

222 lines
9.2 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();
}
}
public async Task<(bool Ok, string? Error)> AddOperatorAsync(
string sourceKey, string? reason, string? redirectTo, DateTimeOffset now, CancellationToken ct = default)
{
if (!SourceKey.TryParse(sourceKey, out _, out var normalized))
return (false, $"not an IP address: {sourceKey}");
var key = SourceKey.For(normalized.ToString(), _policy.Current);
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 (true, null);
}
catch (Exception ex)
{
_log.LogWarning(ex, "BlockStore: add operator block failed for {Key}.", key);
return (false, "database error");
}
}
/// <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 async Task<int> 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 n;
}
catch (Exception ex)
{
_log.LogWarning(ex, "BlockStore: delete failed.");
return 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;
}
}