Files
Pavlo Ratushnyi dbf3c725e6 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.
2026-10-04 16:08:37 +02:00

182 lines
8.4 KiB
C#

using System.Net;
using System.Text.Json;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using OpenWaf.Domain.Security;
using OpenWaf.Infrastructure.Persistence;
namespace OpenWaf.Tests.Integration;
/// <summary>
/// An allow entry is the one rule that outranks every ban, so the listing of it
/// is the operator's answer to "who is exempt right now". Measured on the
/// shipped image (openwaf:c28, the head tree), with one entry added for one
/// minute against an operator block:
///
/// 03:58:16 POST /admin-api/allow {"match":"192.168.65.1","expiresInMinutes":1} → 204
/// 03:58:20 GET /whatever → 502 (passed to the upstream: the exemption is in force)
/// 03:59:38 GET /whatever → 301 (the exemption has expired; the block is back)
/// 03:59:39 GET /admin-api/allow → 200, the row still listed, no liveness field
/// /admin-api/state → "allowEntries":1
///
/// So the page said the address was exempted one minute after the edge stopped
/// honouring it, and the count the page shows is the count of rows, not the
/// count of exemptions in force. The same listing answered 1101 rows in 130,386
/// bytes with no X-Total-Count and no X-Truncated, and every paging parameter
/// was ignored: ?limit=10, ?offset=1000, ?limit=0 and ?limit=100000 each
/// returned all 1101. Nothing prunes expired allow rows either — the retention
/// worker ages out observations, engine bans and alerts — so the table only
/// grows, and the dead rows are the ones the operator cannot tell apart.
/// </summary>
public sealed class AllowListingHonestyTests
{
private const string Expired = "203.0.113.88";
private const string Live = "203.0.113.89";
private static string? Header(HttpResponseMessage r, string name)
=> r.Headers.TryGetValues(name, out var a) ? string.Join(",", a)
: r.Content.Headers.TryGetValues(name, out var b) ? string.Join(",", b)
: null;
private static async Task<(HttpStatusCode Status, JsonElement Body, string? Total, string? Truncated, string Text)> Listed(
EdgeFixture f, string url)
{
using var request = new HttpRequestMessage(HttpMethod.Get, url);
request.Headers.TryAddWithoutValidation("X-Admin-Token", EdgeFixture.AdminToken);
using var response = await f.Client.SendAsync(request);
var text = await response.Content.ReadAsStringAsync();
var body = response.StatusCode == HttpStatusCode.OK && text.Length > 0
? JsonDocument.Parse(text).RootElement
: default;
return (response.StatusCode, body, Header(response, "X-Total-Count"), Header(response, "X-Truncated"), text);
}
private static async Task<HttpStatusCode> FromAsync(EdgeFixture f, string path, string sourceIp)
{
using var request = new HttpRequestMessage(HttpMethod.Get, path);
request.Headers.TryAddWithoutValidation("X-Forwarded-For", sourceIp);
using var response = await f.Client.SendAsync(request);
return response.StatusCode;
}
private static string[] MatchesOf(JsonElement body) =>
body.EnumerateArray().Select(e => e.GetProperty("match").GetString()!).ToArray();
/// <summary>
/// Rows are written straight to the database because the API cannot be asked
/// for an expiry in the past — expiresInMinutes is 1..5,256,000, which is the
/// fix from an earlier cycle and is not about to be loosened to make a test
/// easier. The backdated row is exactly what a minute of waiting produces.
/// </summary>
private static async Task SeedAllow(EdgeFixture f, string match, DateTimeOffset? expiresAt)
{
using var scope = f.Factory.Services.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<OpenWafDbContext>();
db.AllowEntries.Add(new AllowEntry
{
Match = match,
Note = "seeded",
CreatedAt = DateTimeOffset.UtcNow.AddMinutes(-120),
ExpiresAt = expiresAt
});
await db.SaveChangesAsync();
await f.Service<EdgeStateStore>().InvalidateAsync();
}
[Fact]
public async Task An_expired_exemption_is_out_of_the_default_listing_and_says_it_expired_in_the_full_one()
{
await using var f = new EdgeFixture();
await SeedAllow(f, Expired, DateTimeOffset.UtcNow.AddMinutes(-1));
await SeedAllow(f, Live, null);
var defaults = await Listed(f, "/admin-api/allow");
Assert.Equal(HttpStatusCode.OK, defaults.Status);
Assert.Equal(["203.0.113.89"], MatchesOf(defaults.Body));
Assert.Equal("1", defaults.Total);
Assert.Equal("false", defaults.Truncated);
var everything = await Listed(f, "/admin-api/allow?live=false");
Assert.Equal(["203.0.113.88", "203.0.113.89"], MatchesOf(everything.Body));
Assert.Equal("2", everything.Total);
var dead = everything.Body.EnumerateArray().Single(e => e.GetProperty("match").GetString() == Expired);
Assert.False(dead.GetProperty("live").GetBoolean());
var alive = everything.Body.EnumerateArray().Single(e => e.GetProperty("match").GetString() == Live);
Assert.True(alive.GetProperty("live").GetBoolean());
}
[Fact]
public async Task The_allow_listing_and_the_wire_give_the_same_answer_about_an_expired_exemption()
{
await using var f = new EdgeFixture();
// An operator block on both addresses, so the only thing that can let
// either one through is its allow entry.
using (var scope = f.Factory.Services.CreateScope())
{
var store = scope.ServiceProvider.GetRequiredService<BlockStore>();
foreach (var ip in new[] { Expired, Live })
await store.AddOperatorAsync(ip, "c28 seed", null, null, DateTimeOffset.UtcNow);
}
await SeedAllow(f, Expired, DateTimeOffset.UtcNow.AddMinutes(-1));
await SeedAllow(f, Live, null);
Assert.Equal(HttpStatusCode.NotFound, await FromAsync(f, "/anything", Live));
Assert.Equal(HttpStatusCode.MovedPermanently, await FromAsync(f, "/anything", Expired));
// The number the page puts in its pill has to be the number of
// exemptions the edge is honouring, not the number of rows.
using var request = new HttpRequestMessage(HttpMethod.Get, "/admin-api/state");
request.Headers.TryAddWithoutValidation("X-Admin-Token", EdgeFixture.AdminToken);
using var response = await f.Client.SendAsync(request);
var state = JsonDocument.Parse(await response.Content.ReadAsStringAsync()).RootElement;
Assert.Equal(1, state.GetProperty("allowEntries").GetInt32());
Assert.Equal(1, state.GetProperty("allowEntriesExpired").GetInt32());
}
[Fact]
public async Task The_allow_listing_is_capped_and_says_so_and_the_offset_reaches_the_rest()
{
await using var f = new EdgeFixture();
for (var i = 1; i <= 5; i++)
await SeedAllow(f, $"198.51.100.{i}", null);
var first = await Listed(f, "/admin-api/allow?limit=2");
Assert.Equal("5", first.Total);
Assert.Equal("true", first.Truncated);
Assert.Equal(2, MatchesOf(first.Body).Length);
var seen = new List<string>();
for (var offset = 0; offset < 5; offset++)
{
var page = await Listed(f, $"/admin-api/allow?limit=1&offset={offset}");
Assert.Equal("5", page.Total);
seen.AddRange(MatchesOf(page.Body));
}
Assert.Equal(5, seen.Distinct().Count());
var whole = await Listed(f, "/admin-api/allow?limit=2000");
Assert.Equal("false", whole.Truncated);
Assert.Equal(5, MatchesOf(whole.Body).Length);
}
[Fact]
public async Task A_paging_limit_nobody_meant_on_the_allow_listing_is_refused_by_name()
{
await using var f = new EdgeFixture();
await SeedAllow(f, Live, null);
foreach (var (query, expected) in new[]
{
("?limit=0", "limit must be 1..2000; got 0"),
("?limit=-1", "limit must be 1..2000; got -1"),
("?limit=2001", "limit must be 1..2000; got 2001"),
("?offset=-1", "offset must be 0 or more; got -1")
})
{
var bad = await Listed(f, "/admin-api/allow" + query);
Assert.Equal(HttpStatusCode.BadRequest, bad.Status);
Assert.Contains(expected, bad.Text);
}
}
}