Files
Pavlo Ratushnyi 1ec794dc75 the horizon says what stops being enforced soon, and what answers afterwards
GET /admin-api/expiring?within=<minutes> (1..1440, 30 by default) lists the dated
entries that stop being enforced inside the window, nearest first, and each
address-shaped row carries thenAnswers: the real DecisionEngine.Decide over a
snapshot with only that entry removed. An exemption about to lapse therefore says
which ban is waiting underneath it ("block_operator by 203.0.113.16/28"), and a
block that stands alone says the source goes free. A path rule and a path budget
have no single answer: thenAnswers is null and whyNoAnswer points at
/admin-api/decide?ip=&path= instead of the surface guessing one. Entries that
never expire are not listed; alreadyExpired counts the dated rows whose moment
already passed, which is what separates "nothing expires soon" from "there are no
dated entries". The listing reads the database, the read-only token can ask it,
and six asks write nothing.

Rulings:
- the probe address for a CIDR is its network address, which is inside the group
  it describes; a pattern is not probed at all.
- the window is capped at a day because that is the longest thing an operator
  plans for; out of bounds is a 400 naming 1..1440.
- the console prints the window it asked for as the first line of the answer and
  empties the box before the call, so neither a scene nor an operator on a slow
  link can read the previous answer as the new one.

Two product defects fell out of the gates on the way:
- the alert push worker was registered as a hosted service above the schema step,
  and hosted services start in registration order: on a cold start its first
  queue sweep read alert_push_queue out of a database this process had not
  created, and "SQLite Error 1: no such table" became alertWebhookLastError -
  the state page blaming the webhook endpoint for the edge's own startup order.
  The notifier is now registered below the warmer and the order is asserted.
- a listing the edge could not answer was drawn as an empty one: with two of the
  page's fourteen calls answering an error, the observation line printed "0
  sources the edge has recorded" and the streak line "0 of 0 standing streaks
  listed" over a map holding twelve sources. A count read off a failed answer is
  0, and 0 says there is nothing to see. Every count-bearing note and its table
  now say NOT READ with the error beside them.

The gate's own traps, caught and fixed: the budget scene cleared the engine ban
its probes caused after the probe that ban was failing, and its reopen retry loop
banned itself three refusals deep; the alerts assertion read a row written off the
response before the next refresh drew it.

gates: build 0 warnings / 0 errors, unit 377/377, integration 375/375 in 35 s,
console 142 assertions 0 failed, smoke passed 217 failed 0, compose 324 passed
0 failed against the built image at 262 MB, 0 containers left behind.

Refs OPEN-72.
2026-10-05 11:22:01 +02:00

267 lines
13 KiB
C#
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using System.Net;
using System.Net.Http.Json;
using System.Text.Json;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using OpenWaf.Domain.Security;
using OpenWaf.Infrastructure.Persistence;
namespace OpenWaf.Tests.Integration;
/// <summary>
/// The enforcement horizon (OPEN-72): what stops being enforced soon, and what
/// answers once it has.
///
/// The incident this exists for is a scheduled one. An office inside a banned
/// netblock is given a 60-minute exemption; the minute passes; the office is
/// refused again; and nobody looking at the refusal knows there was ever an
/// exemption, or that a /28 was underneath it. The tables all hold the dates —
/// blocks, ranges, engine bans, exemptions, path rules, path budgets — and no
/// surface reads them forward.
///
/// What these tests hold the surface to: the answer for an address-shaped entry
/// is the real decision engine run with only that entry removed, so it cannot
/// disagree with the wire; a pattern says why it has no answer instead of
/// inventing one; dead rows are counted apart from "nothing expires soon"; and
/// asking writes nothing.
/// </summary>
public sealed class EnforcementHorizonTests
{
private const string Range = "203.0.113.16/28"; // .16 – .31
private const string Inside = "203.0.113.21";
private const string Source = "203.0.113.77";
private static async Task<HttpResponseMessage> AdminAsync(
EdgeFixture f, HttpMethod method, string url, object? body = null,
string token = EdgeFixture.AdminToken)
{
using var request = new HttpRequestMessage(method, url);
if (token is not null) request.Headers.TryAddWithoutValidation("X-Admin-Token", token);
if (body is not null) request.Content = JsonContent.Create(body);
return await f.Client.SendAsync(request);
}
private static async Task<(HttpStatusCode Status, JsonElement Body)> HorizonAsync(
EdgeFixture f, string query, string token = EdgeFixture.AdminToken)
{
using var r = await AdminAsync(f, HttpMethod.Get, $"/admin-api/expiring?{query}", token: token);
var body = JsonDocument.Parse(await r.Content.ReadAsStringAsync()).RootElement.Clone();
return (r.StatusCode, body);
}
private static async Task<int> AskAsync(EdgeFixture f, string path, string ip)
{
using var request = new HttpRequestMessage(HttpMethod.Get, path);
request.Headers.TryAddWithoutValidation("X-Forwarded-For", ip);
using var r = await f.Client.SendAsync(request);
return (int)r.StatusCode;
}
/// <summary>Rows are written straight to the database when the API would only
/// accept an expiry the test then has to wait out.</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 = "the office", CreatedAt = DateTimeOffset.UtcNow, ExpiresAt = expiresAt
});
await db.SaveChangesAsync();
await f.Service<EdgeStateStore>().InvalidateAsync();
}
private static async Task BanByTheEngineAsync(EdgeFixture f, string ip)
{
for (var i = 0; i < 3; i++) await AskAsync(f, "/wp-login.php", ip);
}
[Fact]
public async Task An_exemption_inside_a_banned_range_says_what_takes_over_when_it_ages_out()
{
await using var f = new EdgeFixture();
using (await AdminAsync(f, HttpMethod.Post, "/admin-api/blocks",
new { ip = Range, reason = "netblock scanning" })) { }
await SeedAllow(f, Inside, DateTimeOffset.UtcNow.AddMinutes(10));
// The wire today: the exemption outranks the range, the office is served.
Assert.Equal(404, await AskAsync(f, "/anything", Inside));
var (status, body) = await HorizonAsync(f, "within=30");
Assert.Equal(HttpStatusCode.OK, status);
var row = Assert.Single(body.GetProperty("expiring").EnumerateArray(),
r => r.GetProperty("kind").GetString() == "allow");
Assert.Equal(Inside, row.GetProperty("match").GetString());
Assert.Equal("the office", row.GetProperty("note").GetString());
Assert.True(row.GetProperty("minutesLeft").GetInt32() is > 0 and <= 10);
// The part nobody can assemble from the tables: what answers next.
var after = row.GetProperty("thenAnswers");
Assert.Equal("block_operator", after.GetProperty("verdict").GetString());
Assert.True(after.GetProperty("wouldBeRefused").GetBoolean());
Assert.Equal(Range, after.GetProperty("by").GetString());
Assert.Contains("refused again", after.GetProperty("note").GetString()!);
}
[Fact]
public async Task A_block_with_nothing_underneath_says_nothing_else_refuses_the_source()
{
await using var f = new EdgeFixture();
using (await AdminAsync(f, HttpMethod.Post, "/admin-api/blocks",
new { ip = Source, reason = "incident, time-boxed", expiresInMinutes = 60 })) { }
var (_, body) = await HorizonAsync(f, "within=120");
var row = Assert.Single(body.GetProperty("expiring").EnumerateArray(),
r => r.GetProperty("kind").GetString() == "block");
Assert.Equal(Source, row.GetProperty("match").GetString());
var after = row.GetProperty("thenAnswers");
Assert.Equal("pass", after.GetProperty("verdict").GetString());
Assert.False(after.GetProperty("wouldBeRefused").GetBoolean());
Assert.Contains("nothing else refuses", after.GetProperty("note").GetString()!);
}
[Fact]
public async Task An_engine_ban_under_an_operator_block_reports_the_block_that_would_still_answer()
{
await using var f = new EdgeFixture();
await BanByTheEngineAsync(f, Source);
using (await AdminAsync(f, HttpMethod.Post, "/admin-api/blocks",
new { ip = Source, reason = "written by hand", expiresInMinutes = 600 })) { }
// The ban the engine wrote ages out in about an hour; the operator's block
// is what keeps refusing after it does.
var (_, body) = await HorizonAsync(f, "within=120");
var row = Assert.Single(body.GetProperty("expiring").EnumerateArray(),
r => r.GetProperty("kind").GetString() == "engine ban");
var after = row.GetProperty("thenAnswers");
Assert.Equal("block_operator", after.GetProperty("verdict").GetString());
Assert.True(after.GetProperty("wouldBeRefused").GetBoolean());
Assert.Equal(Source, after.GetProperty("by").GetString());
}
[Fact]
public async Task A_pattern_says_why_it_has_no_answer_instead_of_inventing_one()
{
await using var f = new EdgeFixture();
using (await AdminAsync(f, HttpMethod.Post, "/admin-api/rules",
new { pattern = "/wp-admin*", action = "block", note = "scan", expiresInMinutes = 60 })) { }
using (await AdminAsync(f, HttpMethod.Post, "/admin-api/rate-rules",
new { pattern = "/login*", limitPerWindow = 5, expiresInMinutes = 60 })) { }
var (_, body) = await HorizonAsync(f, "within=120");
foreach (var kind in new[] { "path rule", "path budget" })
{
var row = Assert.Single(body.GetProperty("expiring").EnumerateArray(),
r => r.GetProperty("kind").GetString() == kind);
Assert.True(row.GetProperty("thenAnswers").ValueKind == JsonValueKind.Null);
Assert.Contains("/admin-api/decide", row.GetProperty("whyNoAnswer").GetString()!);
}
}
[Fact]
public async Task Entries_outside_the_window_are_left_out_and_the_bounds_are_said()
{
await using var f = new EdgeFixture();
using (await AdminAsync(f, HttpMethod.Post, "/admin-api/blocks",
new { ip = Source, reason = "a year", expiresInMinutes = 5256000 })) { }
var (_, shortWindow) = await HorizonAsync(f, "within=30");
Assert.Equal(0, shortWindow.GetProperty("count").GetInt32());
Assert.Empty(shortWindow.GetProperty("expiring").EnumerateArray());
var (_, longWindow) = await HorizonAsync(f, "within=1440");
Assert.Equal(0, longWindow.GetProperty("count").GetInt32());
// Out of range is a 400 with the bounds, not a silent clamp: a horizon
// quietly widened to a year is not the question that was asked.
foreach (var bad in new[] { "within=0", "within=99999", "within=-5" })
{
var (status, body) = await HorizonAsync(f, bad);
Assert.Equal(HttpStatusCode.BadRequest, status);
Assert.Contains("1..1440", body.ToString());
}
var (unknownStatus, unknownBody) = await HorizonAsync(f, "within=30&kind=allow");
Assert.Equal(HttpStatusCode.BadRequest, unknownStatus);
Assert.Contains("kind", unknownBody.ToString());
}
[Fact]
public async Task Dead_rows_are_counted_apart_from_nothing_expiring()
{
await using var f = new EdgeFixture();
await SeedAllow(f, Inside, DateTimeOffset.UtcNow.AddMinutes(-30));
var (_, body) = await HorizonAsync(f, "within=30");
Assert.Equal(0, body.GetProperty("count").GetInt32());
Assert.Equal(1, body.GetProperty("alreadyExpired").GetProperty("allow").GetInt32());
}
[Fact]
public async Task Asking_the_horizon_writes_nothing_and_a_read_only_token_can_ask_it()
{
await using var f = new EdgeFixture(readOnlyToken: EdgeFixture.ReadOnlyToken);
using (await AdminAsync(f, HttpMethod.Post, "/admin-api/blocks",
new { ip = Source, expiresInMinutes = 60 })) { }
await SeedAllow(f, Inside, DateTimeOffset.UtcNow.AddMinutes(10));
for (var i = 0; i < 5; i++)
{
var (status, _) = await HorizonAsync(f, "within=120", EdgeFixture.ReadOnlyToken);
Assert.Equal(HttpStatusCode.OK, status);
}
using (var changes = await AdminAsync(f, HttpMethod.Get, "/admin-api/changes",
token: EdgeFixture.ReadOnlyToken))
{
Assert.Equal(HttpStatusCode.OK, changes.StatusCode);
using var doc = JsonDocument.Parse(await changes.Content.ReadAsStringAsync());
// One record: the operator's own block. A read that left a record
// would be a write wearing a mask.
Assert.Single(doc.RootElement.EnumerateArray());
}
// And the wire still answers the same way it did before the five asks.
Assert.Equal(404, await AskAsync(f, "/anything", Inside));
Assert.Equal(301, await AskAsync(f, "/anything", Source));
using (var anonymous = await f.Client.GetAsync("/admin-api/expiring?within=30"))
Assert.Equal(HttpStatusCode.Unauthorized, anonymous.StatusCode);
}
[Fact]
public async Task The_horizon_agrees_with_the_wire_about_what_a_source_would_get()
{
await using var f = new EdgeFixture();
using (await AdminAsync(f, HttpMethod.Post, "/admin-api/blocks",
new { ip = Range, reason = "netblock" })) { }
using (await AdminAsync(f, HttpMethod.Post, "/admin-api/allow",
new { match = Inside, note = "the office", expiresInMinutes = 60 })) { }
var (_, body) = await HorizonAsync(f, "within=120");
var row = Assert.Single(body.GetProperty("expiring").EnumerateArray(),
r => r.GetProperty("kind").GetString() == "allow");
var claimed = row.GetProperty("thenAnswers").GetProperty("verdict").GetString();
// Remove the exemption for real, and the wire has to answer the way the
// horizon said it would. This is the claim the whole surface makes.
using (var list = await AdminAsync(f, HttpMethod.Get, "/admin-api/allow"))
{
using var doc = JsonDocument.Parse(await list.Content.ReadAsStringAsync());
var id = doc.RootElement[0].GetProperty("id").GetInt64();
using (await AdminAsync(f, HttpMethod.Delete, $"/admin-api/allow/{id}")) { }
}
string? verdict = null;
for (var i = 0; i < 10 && verdict != "block_operator"; i++)
{
using var preview = await AdminAsync(f, HttpMethod.Get,
$"/admin-api/decide?ip={Inside}&path=/anything");
using var doc = JsonDocument.Parse(await preview.Content.ReadAsStringAsync());
verdict = doc.RootElement.GetProperty("verdict").GetString();
if (verdict != "block_operator") await Task.Delay(500);
}
Assert.Equal(claimed, verdict);
Assert.Equal(301, await AskAsync(f, "/anything", Inside));
}
}