an operator block can now be time-boxed, on the wire and on the page

The model always had it: BlockEntry.ExpiresAt, DecisionEngine asking IsLive
before honouring a row, and the listing printing the column since OPEN-28.
What did not exist was a way to set it — AddOperatorAsync wrote ExpiresAt =
null for every operator block, and NewBlockRequest had no field for it. So
"block this for the night" meant "block this, and remember to delete it in
the morning", while the exemption form beside it already had a minutes box.

POST /admin-api/blocks now takes expiresInMinutes with the same 1..5,256,000
bound and the same rule as the exemption's field: present sets the expiry,
absent means the block stands until someone takes it off. Re-blocking an
address that already carries an expiry moves it, because the second call
means its own duration from now. 0 and 5,256,001 are a 400 naming the field
rather than a permanent block bought by a zero in a box. The console gets the
minutes input and refuses a zero before the round trip.

Measured on this tree: build 0 warnings / 0 errors, unit 132/132, integration
185/185 in 19 s (4 new: the expiry lands and the listing says so; 0, -10 and
5,256,001 refused by name with nothing written and the address still itself;
a block past its expiry stops being enforced while a second blocked address
stays blocked and the dead row shows as expired rather than vanishing; a
second POST moves the expiry), smoke 28/0, console 78 assertions 0 failed.
The console gate run also printed the row it wrote: expiry cell
"2026-10-04 15:05:37" against a permanent block's empty one.
This commit is contained in:
Pavlo Ratushnyi
2026-10-04 16:08:37 +02:00
parent 39dece60e4
commit dbf3c725e6
8 changed files with 251 additions and 11 deletions
+16 -3
View File
@@ -267,7 +267,7 @@ delete the warning and exactly the first one fails.
```
GET /admin-api/blocks?source=operator|engine&live=true
POST /admin-api/blocks {"ip","reason","redirectTo"}
POST /admin-api/blocks {"ip","reason","redirectTo","expiresInMinutes"}
DELETE /admin-api/blocks?source=engine[&key=…]
GET /admin-api/allow?live[=false]&limit&offset POST {"match","note","expiresInMinutes"} DELETE /admin-api/allow/{id}
GET /admin-api/policy PUT {"mode":"Enforce","streakThreshold":8,…}
@@ -295,6 +295,19 @@ never), and `reason`/`note` are bounded at 512 characters, the budget the
attacker-written path field already gets, after a 1 MB note and a 1 MB reason
were both accepted and made the listings return ~1 MB each.
An operator's block can be time-boxed: `expiresInMinutes` on `POST
/admin-api/blocks`, the same 1–5,256,000 bound and the same rule as the
exemption's field — present sets the expiry, absent means the block stands
until someone takes it off. Nothing in the model was missing: `BlockEntry` has
always had `ExpiresAt`, `DecisionEngine` has always asked `IsLive` before
honouring a row, and the listing has always printed the column. What was missing
was a way to *set* it, so a block typed at midnight over an incident was still
there in the morning unless a human remembered to delete it, while the
exemption form beside it already had a minutes box. Re-blocking an address that
already carries an expiry moves it — the second call means its own duration from
now — and 0 or 5,256,001 is a 400 naming the field rather than a permanent block
bought by a zero in a box.
Every capped listing now says how much it cut, and a limit nobody meant is
refused instead of reinterpreted. `?limit=` used to be clamped: with 1,103
sources recorded, `GET /admin-api/observations?limit=100000` answered 200 with
@@ -802,7 +815,7 @@ On the head of this file the host suite has been re-run and the container stages
have not, so the two sets of numbers are labelled separately rather than merged
into one green line. macOS host, this tree, re-measured 2026-10-04 with the
retention window as configuration: build 0 warnings / 0 errors, unit **132/132**,
integration **181/181 in 20 s**, console **76 assertions, 0 failed**, smoke
integration **185/185 in 19 s**, console **78 assertions, 0 failed**, smoke
**passed 28, failed 0**. Carried from the 2026-10-02 run and not re-measured
since: compose **209 passed, 0 failed**, image 261 MB, 0 containers left behind,
enforcement lag 33 ms (`/tmp/c26_build.log`, `/tmp/c26_unit.log`,
@@ -813,7 +826,7 @@ collections — answered **157 passed, 16 failed**, every one of them `Timed out
waiting for the entry point to build the IHost after 00:05:00`
(`/tmp/c26_int3.log`), and with `xunit.parallelizeTestCollections=false` the same
tree answered **173/173 in 23 s** (`/tmp/c26_int4.log`). Re-measured 2026-10-04,
the default parallel scheduling answered **181/181 in 20 s**, and the same tree
the default parallel scheduling answered **185/185 in 19 s**, and the same tree
run inside a filesystem-and-network sandbox failed **every** fixture with exactly
that timeout — a test host that cannot bind a loopback socket hangs in this
shape. Scheduling is one variable in that symptom; whether the test host can
+20 -3
View File
@@ -97,6 +97,7 @@ internal static class AdminConsole
<div class="bar">
<input id="blockIp" placeholder="block this address" autocomplete="off" size="18">
<input id="blockReason" placeholder="reason" autocomplete="off" size="20">
<input id="blockTtl" placeholder="minutes" autocomplete="off" size="7" inputmode="numeric">
<button id="addBlock">block</button>
<input id="allowMatch" placeholder="allow address or CIDR" autocomplete="off" size="18">
<input id="allowNote" placeholder="note" autocomplete="off" size="14">
@@ -478,9 +479,25 @@ async function postJson(path, body) {
el('addBlock').onclick = async () => {
const ip = el('blockIp').value.trim();
if (!ip) { note('an address first', true); return; }
if (await postJson('/admin-api/blocks', { ip, reason: el('blockReason').value.trim() || 'blocked from the console' })) {
el('blockIp').value = ''; el('blockReason').value = '';
done('blocked ' + ip);
// The same shape as the exemption's minutes field, for the same reason: an
// operator blocking a source during an incident wants it gone by itself
// afterwards, and a block that can only be removed by hand is a block that
// is still there in the morning. Empty stays "until I take it off".
const rawTtl = el('blockTtl').value.trim();
let ttl = null;
if (rawTtl !== '') {
const parsed = Number(rawTtl);
if (!Number.isInteger(parsed) || parsed < 1 || parsed > 5256000) {
note('a duration in minutes (1..5256000), or leave it empty for never', true);
return;
}
ttl = parsed;
}
if (await postJson('/admin-api/blocks', { ip,
reason: el('blockReason').value.trim() || 'blocked from the console',
expiresInMinutes: ttl })) {
el('blockIp').value = ''; el('blockReason').value = ''; el('blockTtl').value = '';
done('blocked ' + ip + (ttl ? ' for ' + ttl + ' min' : ''));
load();
}
};
+2 -1
View File
@@ -18,7 +18,8 @@ internal sealed record BlockDto(
string? LastCountryCode,
string? LastCity);
internal sealed record NewBlockRequest(string Ip, string? Reason, string? RedirectTo);
internal sealed record NewBlockRequest(string Ip, string? Reason, string? RedirectTo,
int? ExpiresInMinutes);
internal sealed record StreakDto(
string SourceKey,
+10 -1
View File
@@ -98,7 +98,16 @@ internal static class AdminEndpoints
// come back as 500 with no body — the block itself broke.
if (req.RedirectTo is not null && !RedirectTarget.IsSendable(req.RedirectTo))
return Results.BadRequest(new { error = $"redirectTo must be an absolute http(s) URL with no spaces or control characters; got \"{req.RedirectTo}\"" });
var (added, error) = await store.AddOperatorAsync(req.Ip, req.Reason, req.RedirectTo, DateTimeOffset.UtcNow, ct);
// An operator's block used to be forever: the model had ExpiresAt, the
// engine honoured it, the listing printed it, and no way to set it
// existed. The exemption form already has a minutes field; the block
// form now has one too. Absent means "until I take it off", which is
// what every operator block written before this meant.
if (req.ExpiresInMinutes is { } minutes && !EntryLimits.ExpiresInMinutesOk(minutes))
return Results.BadRequest(new { error = $"expiresInMinutes must be {EntryLimits.ExpiresInMinutesMin}..{EntryLimits.ExpiresInMinutesMax} to expire, or left out to never expire; got {minutes}" });
var (added, error) = await store.AddOperatorAsync(req.Ip, req.Reason, req.RedirectTo,
req.ExpiresInMinutes, DateTimeOffset.UtcNow, ct);
// Two different failures used to arrive as the same 400. A rejected
// input and a storage failure are not the same event: one is fixed
// by editing the request, the other by fixing the database, and a
@@ -281,8 +281,15 @@ public sealed class BlockStore
/// 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)> AddOperatorAsync(
string sourceKey, string? reason, string? redirectTo, DateTimeOffset now, CancellationToken ct = default)
string sourceKey, string? reason, string? redirectTo, int? expiresInMinutes,
DateTimeOffset now, CancellationToken ct = default)
{
if (!SourceKey.TryParse(sourceKey, out _, out var normalized))
return (AddResult.InvalidInput, $"not an IP address: {sourceKey}");
@@ -304,13 +311,18 @@ public sealed class BlockStore
Source = BlockSource.Operator,
CreatedAt = now,
Reason = reason,
RedirectTo = redirectTo
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);
@@ -115,7 +115,7 @@ public sealed class AllowListingHonestyTests
{
var store = scope.ServiceProvider.GetRequiredService<BlockStore>();
foreach (var ip in new[] { Expired, Live })
await store.AddOperatorAsync(ip, "c28 seed", null, DateTimeOffset.UtcNow);
await store.AddOperatorAsync(ip, "c28 seed", null, null, DateTimeOffset.UtcNow);
}
await SeedAllow(f, Expired, DateTimeOffset.UtcNow.AddMinutes(-1));
await SeedAllow(f, Live, null);
@@ -0,0 +1,154 @@
using System.Net;
using System.Net.Http.Json;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using OpenWaf.Domain.Security;
using OpenWaf.Infrastructure.Persistence;
namespace OpenWaf.Tests.Integration;
/// <summary>
/// An operator's block used to be forever. The model had ExpiresAt, the engine
/// honoured it (`DecisionEngine` asks `BlockEntry.IsLive`), the listing printed
/// it and the liveness rule around it was fixed in OPEN-28 — but nothing could
/// set it, so "block this for the night" meant "block this, and remember to
/// delete it in the morning". The exemption form already had a minutes field;
/// these tests are the block form getting the same lever (OPEN-51).
/// </summary>
public sealed class OperatorBlockExpiryTests
{
private const string Blocked = "203.0.113.61";
private const string Other = "203.0.113.62";
private static async Task<HttpResponseMessage> GetAsync(EdgeFixture f, string path, string ip)
{
using var request = new HttpRequestMessage(HttpMethod.Get, path);
request.Headers.TryAddWithoutValidation("X-Forwarded-For", ip);
return await f.Client.SendAsync(request);
}
private static async Task<HttpResponseMessage> BlockAsync(EdgeFixture f, object body)
=> await f.Client.PostAsJsonAsync($"/admin-api/blocks?token={EdgeFixture.AdminToken}", body);
private static async Task<(DateTimeOffset? ExpiresAt, bool Live, int Rows)> ReadRowAsync(EdgeFixture f, bool liveOnly)
{
using var response = await f.Client.GetAsync(
$"/admin-api/blocks?live={(liveOnly ? "true" : "false")}&token={EdgeFixture.AdminToken}");
var rows = System.Text.Json.JsonDocument.Parse(await response.Content.ReadAsStringAsync())
.RootElement.EnumerateArray().ToList();
var mine = rows.FirstOrDefault(r => r.GetProperty("sourceKey").GetString() == Blocked);
return (mine.ValueKind == System.Text.Json.JsonValueKind.Undefined ? null : mine.GetProperty("expiresAt").GetDateTimeOffset(),
mine.ValueKind != System.Text.Json.JsonValueKind.Undefined && mine.GetProperty("live").GetBoolean(),
rows.Count);
}
[Fact]
public async Task An_operator_block_with_a_duration_carries_that_expiry_and_the_listing_says_so()
{
await using var f = new EdgeFixture();
var before = DateTimeOffset.UtcNow;
using (var created = await BlockAsync(f, new { ip = Blocked, reason = "incident: block for an hour", expiresInMinutes = 60 }))
Assert.Equal(HttpStatusCode.NoContent, created.StatusCode);
// Enforced now, and the listing carries the expiry it will stop being
// enforced at — the two halves have to agree.
using (var blocked = await GetAsync(f, "/anything", Blocked))
Assert.Equal(HttpStatusCode.MovedPermanently, blocked.StatusCode);
var (expiresAt, live, _) = await ReadRowAsync(f, liveOnly: true);
Assert.True(live);
Assert.NotNull(expiresAt);
Assert.InRange(expiresAt!.Value, before.AddMinutes(59), DateTimeOffset.UtcNow.AddMinutes(61));
}
[Fact]
public async Task A_duration_outside_the_bound_is_refused_by_name_and_writes_no_block()
{
await using var f = new EdgeFixture();
foreach (var minutes in new[] { 0, -10, 5_256_001 })
{
using var response = await BlockAsync(f, new { ip = Blocked, reason = "bad duration", expiresInMinutes = minutes });
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
var body = await response.Content.ReadAsStringAsync();
Assert.Contains("expiresInMinutes", body);
Assert.Contains(minutes.ToString(), body);
}
// And the refusal is a refusal: nothing was written, so the address is
// still itself.
using (var unblocked = await GetAsync(f, "/anything", Blocked))
Assert.Equal(HttpStatusCode.NotFound, unblocked.StatusCode);
var (_, _, rows) = await ReadRowAsync(f, liveOnly: false);
Assert.Equal(0, rows);
}
[Fact]
public async Task An_operator_block_past_its_expiry_stops_being_enforced_and_shows_itself_as_dead()
{
await using var f = new EdgeFixture();
using (var created = await BlockAsync(f, new { ip = Blocked, reason = "block for an hour", expiresInMinutes = 60 }))
Assert.Equal(HttpStatusCode.NoContent, created.StatusCode);
using (var blocked = await GetAsync(f, "/anything", Blocked))
Assert.Equal(HttpStatusCode.MovedPermanently, blocked.StatusCode);
// Move the clock by moving the row, the way the retention tests do: the
// hour passes for this block and for nothing else.
using (var scope = f.Factory.Services.CreateScope())
{
var db = scope.ServiceProvider.GetRequiredService<OpenWafDbContext>();
var row = await db.Blocks.SingleAsync(b => b.SourceKey == Blocked && b.Source == BlockSource.Operator);
row.ExpiresAt = DateTimeOffset.UtcNow.AddMinutes(-1);
await db.SaveChangesAsync();
}
await f.Service<EdgeStateStore>().InvalidateAsync(CancellationToken.None);
// The engine honours the expiry it was always able to read: the source
// is served again, while a second blocked address stays blocked.
using (var created = await BlockAsync(f, new { ip = Other, reason = "still live", expiresInMinutes = 60 }))
Assert.Equal(HttpStatusCode.NoContent, created.StatusCode);
using (var served = await GetAsync(f, "/anything", Blocked))
Assert.Equal(HttpStatusCode.NotFound, served.StatusCode);
using (var stillBlocked = await GetAsync(f, "/anything", Other))
Assert.Equal(HttpStatusCode.MovedPermanently, stillBlocked.StatusCode);
// And the operator can see the dead row rather than having it vanish
// from the only table that shows it — the OPEN-28 rule, now with an
// expiry the operator actually set.
// The live view is the operator's "who is blocked right now": one row,
// and it is not the expired one.
var (liveViewExpiry, _, liveRows) = await ReadRowAsync(f, liveOnly: true);
Assert.Equal(1, liveRows);
Assert.Null(liveViewExpiry);
var (expiresAt, live, allRows) = await ReadRowAsync(f, liveOnly: false);
Assert.Equal(2, allRows);
Assert.False(live);
Assert.NotNull(expiresAt);
}
[Fact]
public async Task Blocking_the_same_address_again_with_a_duration_moves_the_expiry()
{
await using var f = new EdgeFixture();
using (var first = await BlockAsync(f, new { ip = Blocked, reason = "an hour", expiresInMinutes = 60 }))
Assert.Equal(HttpStatusCode.NoContent, first.StatusCode);
var (firstExpiry, _, _) = await ReadRowAsync(f, liveOnly: true);
await Task.Delay(1100);
using (var second = await BlockAsync(f, new { ip = Blocked, reason = "a day instead", expiresInMinutes = 1440 }))
Assert.Equal(HttpStatusCode.NoContent, second.StatusCode);
var (secondExpiry, live, _) = await ReadRowAsync(f, liveOnly: true);
// The second call means what it says: the expiry moves to the new
// duration from now, it does not keep the hour typed a second ago.
Assert.True(live);
Assert.NotNull(firstExpiry);
Assert.NotNull(secondExpiry);
Assert.True(secondExpiry!.Value > firstExpiry!.Value.AddMinutes(60),
$"first {firstExpiry:O} then {secondExpiry:O}");
Assert.InRange(secondExpiry.Value, DateTimeOffset.UtcNow.AddMinutes(1439), DateTimeOffset.UtcNow.AddMinutes(1441));
}
}
+34
View File
@@ -265,6 +265,40 @@ const rgb = (s) => s.match(/\d+/g).slice(0, 3).map(Number);
check('and the address reaches the upstream again once that row is gone',
wire2.status === 404, `probe from ${WRITE_IP} answered ${wire2.status}`);
// A block can be time-boxed now: the same minutes field the exemption form
// already had. The permanent write above prints an empty expiry cell, so the
// date in this row is the difference the field makes.
await page.fill('#blockIp', WRITE_IP);
await page.fill('#blockReason', 'console gate: time-boxed');
await page.fill('#blockTtl', '60');
await page.click('#addBlock');
await page.waitForFunction(
(ip) => [...document.querySelectorAll('#blocks tbody tr')].some((tr) =>
tr.children[0].textContent === ip && /\d{4}-\d{2}-\d{2}/.test(tr.children[3].textContent)),
WRITE_IP, { timeout: 15000 }).catch(() => {});
const timeBoxed = await cells('#blocks tbody tr');
const boxStatus = (await page.textContent('#status')).trim();
check('a block typed with a duration is listed with the expiry it stops being enforced at',
timeBoxed.some((r) => r[0] === WRITE_IP && /\d{4}-\d{2}-\d{2}/.test(r[3] || '')) && /for 60 min/.test(boxStatus),
`${JSON.stringify(boxStatus)} ${JSON.stringify(timeBoxed.find((r) => r[0] === WRITE_IP))}`);
// And the same trap the exemption field fell into once: a zero in a minutes
// box is not a duration, and here it would have meant "block forever".
await page.fill('#blockIp', WRITE_IP);
await page.fill('#blockTtl', '0');
await page.click('#addBlock');
await page.waitForFunction(() => /duration in minutes/.test(document.getElementById('status').textContent),
null, { timeout: 5000 }).catch(() => {});
const zeroBox = (await page.textContent('#status')).trim();
check('a block duration of 0 is refused by the page instead of becoming a permanent block',
/duration in minutes/.test(zeroBox), JSON.stringify(zeroBox));
await page.fill('#blockTtl', '');
await page.click(`#blocks tbody button[data-act="delblock"][data-k="${WRITE_IP}"]`);
await page.waitForFunction(
(ip) => ![...document.querySelectorAll('#blocks tbody tr')].some((tr) => tr.children[0].textContent === ip),
WRITE_IP, { timeout: 15000 }).catch(() => {});
await page.fill('#allowMatch', WRITE_CIDR);
await page.fill('#allowNote', 'console gate: allow entry');
await page.fill('#allowTtl', '60');