Files
Pavlo Ratushnyi 5c1a2950d0
ci / lint the workflow and the shell (push) Successful in 22s
ci / build, test, smoke (push) Successful in 4m36s
ci / the operator page in a real browser (push) Successful in 4m48s
ci / build the image and smoke it (push) Successful in 8m34s
ci / the same smoke on an image with no base (push) Failing after 8m44s
two more wire shapes stop being anonymous, and the count of the ones left gets re-measured
`countries/summary` answered with a `List<anonymous>`: the anonymous shape is what
EF translates — the record-constructor form compiles and then fails at query time
with "could not be translated", which is a test's finding, not a guess — so the
projection stays inside the query and the *response* becomes a named record,
`CountrySummaryDto(Code, Sources, Refusals)`, mapped after `ToListAsync` with the
sort left where it was. Registered in `EdgeJson`. `Code` stays nullable in the
model and non-null in these rows: the query filters `LastCountryCode != null`,
which the compiler cannot see and EF does apply. The second literal is one the
first pass missed because it spans three lines — a `Results.BadRequest` whose body
was `new { error = … }`, now `ErrorDto`.

The counts in `README.md` and `docs/ARCHITECTURE.md` are corrected, and the
correction is stated rather than quietly applied: `fb75890` records **130
anonymous-object literals in 51 shapes**, and its message repeats that. Those two
figures came from a first-pass scanner that walked braces without skipping string
literals, so every `{` inside an interpolated string was counted as code. The same
tree re-measured with a scanner that skips strings, char literals and comments:
**144 literals in 27 shapes** before this change, **31 in 25 shapes** after it.
The **111** that became `ErrorDto` is the one figure both scanners agree on, which
is why the first commit still moved the wall it claimed to move.

Measured on this tree: `dotnet build OpenWaf.Edge -c Release` 0 warnings, unit
**378/378**, integration **407/407 in 34 s** (unsandboxed; the sandboxed run of
this suite is not a measurement — see the loopback-bind note in the README).
2026-10-07 09:06:57 +02:00

2757 lines
163 KiB
C#

using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using OpenWaf.Domain.Engine;
using OpenWaf.Domain.Policy;
using OpenWaf.Domain.Security;
using OpenWaf.Edge.Pipeline;
using OpenWaf.Edge.Startup;
using OpenWaf.Infrastructure.Geo;
using OpenWaf.Infrastructure.Persistence;
namespace OpenWaf.Edge.Admin;
/// <summary>
/// The operator's surface. Deliberately plain: the lists, the toggle, the
/// evidence behind a ban, and nothing else. Two invariants are enforced here
/// rather than trusted to the caller — clearing by provenance can only ever
/// clear that provenance, and every mutation invalidates the guard snapshot so
/// the change lands on the next request instead of after the TTL.
/// </summary>
internal static partial class AdminEndpoints
{
/// <param name="adminToken">The token that reads and writes. Nothing opens
/// this surface without it.</param>
/// <param name="readOnlyToken">The optional second token (OPEN-62): reads
/// yes, writes no. Null or blank means the level does not exist and every
/// request behaves exactly as it did before it was added.</param>
public static IEndpointRouteBuilder MapAdminApi(this IEndpointRouteBuilder app, string? adminToken,
string? readOnlyToken)
{
var group = app.MapGroup("/admin-api");
// The same check the metrics endpoint uses. One implementation, so the
// query-string rule cannot drift between the two surfaces - and since
// OPEN-62, one implementation for the read-only level too, which is why
// the level is decided here at the group rather than per endpoint.
group.AddEndpointFilter(AdminAuth.Require(
adminToken, readOnlyToken, "admin api disabled: set OpenWaf__Admin__Token"));
group.MapGet("/blocks", async (string? source, bool? live, int? limit, int? offset, BlockStore store, HttpContext ctx, CancellationToken ct) =>
{
if (!TryKnownQuery(ctx, out var unknown, "source", "live", "limit", "offset")) return Results.BadRequest(new ErrorDto(unknown));
if (!TryParseSource(source, out var wanted)) return BadSource(source);
if (!TryPaging(limit, offset, BlockStore.ListDefaultLimit, BlockStore.ListMaxLimit,
out var take, out var skip, out var pagingError))
return Results.BadRequest(new ErrorDto(pagingError));
var now = DateTimeOffset.UtcNow;
var rows = await store.ListAsync(wanted, live ?? true, now, take, skip, ct);
var total = await store.CountAsync(wanted, live ?? true, now, ct);
// The listing is capped; the header is what stops a page of 500
// reading like a complete answer.
ctx.Response.Headers["X-Total-Count"] = total.ToString();
ctx.Response.Headers["X-Truncated"] = (skip + rows.Count < total).ToString().ToLowerInvariant();
return Results.Ok(rows.Select(r => r.ToDto(now)));
});
group.MapPost("/blocks", async (NewBlockRequest req, BlockStore store, ConfigChangeWriter changes, HttpContext ctx, CancellationToken ct) =>
{
if (!TryKnownQuery(ctx, out var unknown)) return Results.BadRequest(new ErrorDto(unknown));
if (string.IsNullOrWhiteSpace(req.Ip)) return Results.BadRequest(new ErrorDto("ip is required"));
if (!EntryLimits.NoteOk(req.Reason))
return Results.BadRequest(new ErrorDto($"reason must be at most {EntryLimits.NoteMaxLength} characters; got {req.Reason!.Length}"));
// The target goes into a Location header on the next request from
// this source. Measured on the shipped image, POST answered 204 for
// every string, and a redirectTo holding CRLF made that next request
// 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 ErrorDto($"redirectTo must be an absolute http(s) URL with no spaces or control characters; got \"{req.RedirectTo}\""));
// 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 ErrorDto($"expiresInMinutes must be {EntryLimits.ExpiresInMinutesMin}..{EntryLimits.ExpiresInMinutesMax} to expire, or left out to never expire; got {minutes}"));
var (added, error, target) = 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
// 400 tells the operator to do the first while the block they asked
// for is not in effect.
if (added != BlockStore.AddResult.Ok)
return added switch
{
BlockStore.AddResult.InvalidInput => Results.BadRequest(new ErrorDto(error)),
_ => StorageUnavailable(error!)
};
// The record of the change (OPEN-64). After the change, never
// instead of it: a rule the operator believes they have is the worse
// failure, so a record that cannot be written is counted and the
// request still answers what it means.
// The normalised spelling, not what was typed: 198.51.100.37/24 and
// 198.51.100.0/24 are one row, and a change log that recorded both
// spellings would be a log an operator cannot match the table against.
await changes.RecordAsync(ConfigChangeLog.SectionBlocks, ConfigChangeLog.ActionAdded,
target ?? req.Ip, req.Reason, ct: ct);
return Results.NoContent();
});
// Provenance is part of the delete, not an afterthought: "clear the
// automatic bans" must never be able to erase an operator's list.
group.MapDelete("/blocks", async (string? source, string? key, BlockStore store, ConfigChangeWriter changes, HttpContext ctx, CancellationToken ct) =>
{
if (!TryKnownQuery(ctx, out var unknown, "source", "key")) return Results.BadRequest(new ErrorDto(unknown));
if (!TryParseSource(source, out var parsed)) return BadSource(source);
if (parsed is null && string.IsNullOrWhiteSpace(key))
return Results.BadRequest(new ErrorDto("refusing to delete every block: pass source=operator|engine or key=..."));
var (result, n) = await store.DeleteAsync(parsed, key, ct);
// {"deleted":0} is a fact about the list, so it may only be said
// when the delete actually ran. Measured on the shipped image with
// the block table gone: 200 {"deleted":0} for a list that held two
// operator blocks — indistinguishable from "there was nothing to
// remove", which is how an operator stops trusting the count.
if (result == BlockStore.DeleteResult.StorageFailure)
return StorageUnavailable("the block list could not be read or written: NOTHING was deleted");
if (n > 0)
await changes.RecordAsync(ConfigChangeLog.SectionBlocks, ConfigChangeLog.ActionRemoved,
// The spelling the row was stored under, so the record of the
// removal names the same target the record of the add did.
key is not null && NetworkBans.TryNormalize(key, out var removed, out _)
? removed
: key ?? parsed?.ToString().ToLowerInvariant() ?? "all",
$"deleted {n}", ct: ct);
return Results.Ok(new { deleted = n });
});
// The exemption listing, with the two things the shipped image left out.
// Measured there (openwaf:c28, the head tree): one entry added for one
// minute against an operator block let its address through at 03:58:20
// (502 from the upstream) and was obeyed no more at 03:59:38 (301, the
// block back) — yet at 03:59:39 GET /admin-api/allow still listed the
// row with no liveness field and /admin-api/state still counted it. The
// operator's table said "exempted" a minute after the edge stopped
// honouring it. And with 1101 rows the listing answered 130,386 bytes
// with no X-Total-Count and no X-Truncated, ignoring ?limit=10,
// ?offset=1000, ?limit=0 and ?limit=100000 alike. Expired rows are
// never pruned — retention ages out observations, engine bans and
// alerts, and an operator's own rows are not the machine's to delete —
// so the dead ones are only ever removable if they can be seen.
group.MapGet("/allow", async (bool? live, int? limit, int? offset,
OpenWafDbContext db, HttpContext ctx, CancellationToken ct) =>
{
if (!TryKnownQuery(ctx, out var unknown, "live", "limit", "offset")) return Results.BadRequest(new ErrorDto(unknown));
if (!TryPaging(limit, offset, AllowListDefaultLimit, AllowListMaxLimit,
out var take, out var skip, out var pagingError))
return Results.BadRequest(new ErrorDto(pagingError));
var now = DateTimeOffset.UtcNow;
// Same shape as the block listing: live by default, live=false means
// "do not filter", because "who is exempt" and "what rows exist"
// are different questions and the page has to be able to ask both.
var liveOnly = live ?? true;
var rows = await FilterAllow(db.AllowEntries.AsNoTracking(), liveOnly, now)
.OrderBy(a => a.Match).ThenBy(a => a.Id)
.Skip(skip).Take(take)
.Select(a => new AllowDto(a.Id, a.Match, a.Note, a.CreatedAt, a.ExpiresAt,
a.ExpiresAt == null || a.ExpiresAt > now))
.ToListAsync(ct);
var total = await FilterAllow(db.AllowEntries.AsNoTracking(), liveOnly, now).CountAsync(ct);
ctx.Response.Headers["X-Total-Count"] = total.ToString();
ctx.Response.Headers["X-Truncated"] = (skip + rows.Count < total).ToString().ToLowerInvariant();
return Results.Ok(rows);
});
group.MapPost("/allow", async (NewAllowRequest req, OpenWafDbContext db, EdgeStateStore state, ConfigChangeWriter changes, HttpContext ctx, CancellationToken ct) =>
{
if (!TryKnownQuery(ctx, out var unknown)) return Results.BadRequest(new ErrorDto(unknown));
if (string.IsNullOrWhiteSpace(req.Match) || !IsValidMatch(req.Match))
return Results.BadRequest(new ErrorDto("match must be an address or CIDR"));
if (!EntryLimits.NoteOk(req.Note))
return Results.BadRequest(new ErrorDto($"note must be at most {EntryLimits.NoteMaxLength} characters; got {req.Note!.Length}"));
// Present but out of range is a 400. Absent is the only way to say
// "never expires" — it used to be what 0 and -5 said as well.
if (req.ExpiresInMinutes is { } minutes && !EntryLimits.ExpiresInMinutesOk(minutes))
return Results.BadRequest(new ErrorDto($"expiresInMinutes must be {EntryLimits.ExpiresInMinutesMin}..{EntryLimits.ExpiresInMinutesMax} to expire, or left out to never expire; got {minutes}"));
var existing = await db.AllowEntries.FirstOrDefaultAsync(a => a.Match == req.Match, ct);
if (existing is not null) return Results.Conflict(new ErrorDto("already allowlisted"));
db.AllowEntries.Add(new AllowEntry
{
Match = req.Match.Trim(),
Note = req.Note,
ExpiresAt = req.ExpiresInMinutes is { } expiry ? DateTimeOffset.UtcNow.AddMinutes(expiry) : null
});
await db.SaveChangesAsync(ct);
await state.InvalidateAsync(ct);
await changes.RecordAsync(ConfigChangeLog.SectionAllow, ConfigChangeLog.ActionAdded,
req.Match.Trim(), req.Note, ct: ct);
return Results.NoContent();
});
group.MapDelete("/allow/{id:long}", async (long id, OpenWafDbContext db, EdgeStateStore state, ConfigChangeWriter changes, HttpContext ctx, CancellationToken ct) =>
{
if (!TryKnownQuery(ctx, out var unknown)) return Results.BadRequest(new ErrorDto(unknown));
var n = await db.AllowEntries.Where(a => a.Id == id).ExecuteDeleteAsync(ct);
await state.InvalidateAsync(ct);
// The country-rule delete names the row it could not find. This one
// answered 404 with Content-Length: 0, so the same API explained one
// missing row and said nothing about another — and an empty 404 is
// exactly the answer a page then has to guess about.
if (n == 0) return Results.NotFound(new ErrorDto($"no allow entry with id {id}"));
await changes.RecordAsync(ConfigChangeLog.SectionAllow, ConfigChangeLog.ActionRemoved,
id.ToString(), ct: ct);
return Results.NoContent();
});
// Request rules: the one pillar that looks at the request itself
// rather than at what the upstream answered or who sent it. Written by
// an operator, listed in the order the engine evaluates them, and
// capped — every request is checked against each live rule, so the
// listing size is a request-path cost and not only a page length.
group.MapGet("/rules", async (bool? live, int? limit, int? offset,
OpenWafDbContext db, RuleMatchLedger ledger, HttpContext ctx, CancellationToken ct) =>
{
if (!TryKnownQuery(ctx, out var unknown, "live", "limit", "offset")) return Results.BadRequest(new ErrorDto(unknown));
if (!TryPaging(limit, offset, ReadListDefaultLimit, ReadListMaxLimit,
out var take, out var skip, out var pagingError))
return Results.BadRequest(new ErrorDto(pagingError));
var now = DateTimeOffset.UtcNow;
var liveOnly = live ?? true;
IQueryable<RequestRule> Query() =>
liveOnly
? db.RequestRules.AsNoTracking().Where(r => r.ExpiresAt == null || r.ExpiresAt > now)
: db.RequestRules.AsNoTracking();
// Ordered by id, which is the order the engine evaluates them in.
// A listing sorted any other way would show the operator one order
// and enforce another.
var rows = await Query().OrderBy(r => r.Id).Skip(skip).Take(take).ToListAsync(ct);
var total = await Query().CountAsync(ct);
var matches = ledger.Snapshot();
ctx.Response.Headers["X-Total-Count"] = total.ToString();
ctx.Response.Headers["X-Truncated"] = (skip + rows.Count < total).ToString().ToLowerInvariant();
return Results.Ok(rows.Select(r => new RuleDto(
r.Id, r.Pattern, r.Action.ToString().ToLowerInvariant(), r.Note, r.CreatedAt, r.ExpiresAt,
r.ExpiresAt == null || r.ExpiresAt > now,
matches.TryGetValue(r.Id, out var m) ? m : 0)).ToList());
});
group.MapPost("/rules", async (NewRuleRequest req, OpenWafDbContext db, EdgeStateStore state, ConfigChangeWriter changes, HttpContext ctx, CancellationToken ct) =>
{
if (!TryKnownQuery(ctx, out var unknown)) return Results.BadRequest(new ErrorDto(unknown));
// A pattern that can never match is refused here rather than listed
// forever: a rule that silently does nothing is worse than a 400,
// because it reads like a defence that is in place.
var patternProblem = PathPattern.ExplainRejection(req.Pattern);
if (patternProblem is not null) return Results.BadRequest(new ErrorDto(patternProblem));
if (!EntryLimits.NoteOk(req.Note))
return Results.BadRequest(new ErrorDto($"note must be at most {EntryLimits.NoteMaxLength} characters; got {req.Note!.Length}"));
if (req.ExpiresInMinutes is { } minutes && !EntryLimits.ExpiresInMinutesOk(minutes))
return Results.BadRequest(new ErrorDto($"expiresInMinutes must be {EntryLimits.ExpiresInMinutesMin}..{EntryLimits.ExpiresInMinutesMax} to expire, or left out to never expire; got {minutes}"));
var action = string.IsNullOrWhiteSpace(req.Action) ? "observe" : req.Action.Trim().ToLowerInvariant();
if (action is not ("observe" or "block"))
return Results.BadRequest(new ErrorDto($"action must be observe|block; got \"{req.Action}\""));
var pattern = req.Pattern.Trim();
var now = DateTimeOffset.UtcNow;
var clash = await db.RequestRules.AsNoTracking()
.Where(r => r.Pattern == pattern && (r.ExpiresAt == null || r.ExpiresAt > now))
.Select(r => r.Id).FirstOrDefaultAsync(ct);
if (clash != 0)
return Results.Conflict(new ErrorDto($"rule {clash} already covers {pattern} — the listing is the evaluation order, so a second live rule for one pattern can never fire"));
var live = await db.RequestRules.AsNoTracking()
.CountAsync(r => r.ExpiresAt == null || r.ExpiresAt > now, ct);
if (live >= PathPattern.MaxRules)
return Results.BadRequest(new ErrorDto($"at most {PathPattern.MaxRules} live rules; every request is checked against each of them"));
db.RequestRules.Add(new RequestRule
{
Pattern = pattern,
Action = action == "block" ? RequestRuleAction.Block : RequestRuleAction.Observe,
Note = req.Note,
ExpiresAt = req.ExpiresInMinutes is { } expiry ? DateTimeOffset.UtcNow.AddMinutes(expiry) : null
});
await db.SaveChangesAsync(ct);
await state.InvalidateAsync(ct);
await changes.RecordAsync(ConfigChangeLog.SectionRules, ConfigChangeLog.ActionAdded,
pattern, $"{action}{(string.IsNullOrWhiteSpace(req.Note) ? "" : $": {req.Note}")}", ct: ct);
return Results.NoContent();
});
group.MapDelete("/rules/{id:long}", async (long id, OpenWafDbContext db, EdgeStateStore state, ConfigChangeWriter changes, HttpContext ctx, CancellationToken ct) =>
{
if (!TryKnownQuery(ctx, out var unknown)) return Results.BadRequest(new ErrorDto(unknown));
var n = await db.RequestRules.Where(r => r.Id == id).ExecuteDeleteAsync(ct);
await state.InvalidateAsync(ct);
if (n == 0) return Results.NotFound(new ErrorDto($"no request rule with id {id}"));
await changes.RecordAsync(ConfigChangeLog.SectionRules, ConfigChangeLog.ActionRemoved,
id.ToString(), ct: ct);
return Results.NoContent();
});
// Rate rules: the same path language as a request rule, but the claim is
// about how often one source asks, not about what it asked for. The
// counters are per (rule, source) and live in the process, so the listing
// reports what is being counted next to what is configured — an
// observe-mode budget that is being blown quietly is the whole reason to
// write one.
group.MapGet("/rate-rules", async (bool? live, int? limit, int? offset,
OpenWafDbContext db, RateRuleTracker rateRules, HttpContext ctx, CancellationToken ct) =>
{
if (!TryKnownQuery(ctx, out var unknown, "live", "limit", "offset")) return Results.BadRequest(new ErrorDto(unknown));
if (!TryPaging(limit, offset, ReadListDefaultLimit, ReadListMaxLimit,
out var take, out var skip, out var pagingError))
return Results.BadRequest(new ErrorDto(pagingError));
var now = DateTimeOffset.UtcNow;
var liveOnly = live ?? true;
IQueryable<RateRule> Query() =>
liveOnly
? db.RateRules.AsNoTracking().Where(r => r.ExpiresAt == null || r.ExpiresAt > now)
: db.RateRules.AsNoTracking();
var rows = await Query().OrderBy(r => r.Id).Skip(skip).Take(take).ToListAsync(ct);
var total = await Query().CountAsync(ct);
ctx.Response.Headers["X-Total-Count"] = total.ToString();
ctx.Response.Headers["X-Truncated"] = (skip + rows.Count < total).ToString().ToLowerInvariant();
return Results.Ok(rows.Select(r =>
{
var (liveWindows, overNow) = rateRules.LiveCounts(r.Id, r.LimitPerWindow, now);
return new RateRuleDto(r.Id, r.Pattern, r.LimitPerWindow, r.WindowSeconds, r.Note,
r.CreatedAt, r.ExpiresAt, r.ExpiresAt == null || r.ExpiresAt > now,
rateRules.TrackedCount(r.Id), overNow, liveWindows);
}).ToList());
});
group.MapPost("/rate-rules", async (NewRateRuleRequest req, OpenWafDbContext db, EdgeStateStore state,
ConfigChangeWriter changes, HttpContext ctx, CancellationToken ct) =>
{
if (!TryKnownQuery(ctx, out var unknown)) return Results.BadRequest(new ErrorDto(unknown));
var patternProblem = PathPattern.ExplainRejection(req.Pattern);
if (patternProblem is not null) return Results.BadRequest(new ErrorDto(patternProblem));
// The same bounds the edge-wide budget uses, on purpose: two words for
// "requests per window" with two different ceilings would make one of
// them a lie, and the operator reads both off the same page.
var limit = req.LimitPerWindow ?? RateRule.DefaultLimitPerWindow;
if (!PolicyBounds.RateLimitPerWindowOk(limit))
return Results.BadRequest(new ErrorDto($"limitPerWindow must be {PolicyBounds.RateLimitPerWindowMin}..{PolicyBounds.RateLimitPerWindowMax}; got {limit}"));
var window = req.WindowSeconds ?? RateRule.DefaultWindowSeconds;
if (!PolicyBounds.RateWindowSecondsOk(window))
return Results.BadRequest(new ErrorDto($"windowSeconds must be {PolicyBounds.RateWindowSecondsMin:0}..{PolicyBounds.RateWindowSecondsMax:0}; got {window}"));
if (!EntryLimits.NoteOk(req.Note))
return Results.BadRequest(new ErrorDto($"note must be at most {EntryLimits.NoteMaxLength} characters; got {req.Note!.Length}"));
if (req.ExpiresInMinutes is { } minutes && !EntryLimits.ExpiresInMinutesOk(minutes))
return Results.BadRequest(new ErrorDto($"expiresInMinutes must be {EntryLimits.ExpiresInMinutesMin}..{EntryLimits.ExpiresInMinutesMax} to expire, or left out to never expire; got {minutes}"));
var pattern = req.Pattern.Trim();
var now = DateTimeOffset.UtcNow;
var clash = await db.RateRules.AsNoTracking()
.Where(r => r.Pattern == pattern && (r.ExpiresAt == null || r.ExpiresAt > now))
.Select(r => r.Id).FirstOrDefaultAsync(ct);
if (clash != 0)
return Results.Conflict(new ErrorDto($"rate rule {clash} already sets a budget for {pattern} — two live budgets for one path mean the stricter one wins by accident, not by the operator's choice"));
var live = await db.RateRules.AsNoTracking()
.CountAsync(r => r.ExpiresAt == null || r.ExpiresAt > now, ct);
if (live >= PathPattern.MaxRules)
return Results.BadRequest(new ErrorDto($"at most {PathPattern.MaxRules} live rate rules; every request is checked against each of them"));
db.RateRules.Add(new RateRule
{
Pattern = pattern,
LimitPerWindow = limit,
WindowSeconds = window,
Note = req.Note,
ExpiresAt = req.ExpiresInMinutes is { } expiry ? DateTimeOffset.UtcNow.AddMinutes(expiry) : null
});
await db.SaveChangesAsync(ct);
await state.InvalidateAsync(ct);
await changes.RecordAsync(ConfigChangeLog.SectionRateRules, ConfigChangeLog.ActionAdded,
pattern, $"{limit} per {window}s{(string.IsNullOrWhiteSpace(req.Note) ? "" : $": {req.Note}")}", ct: ct);
return Results.NoContent();
});
group.MapDelete("/rate-rules/{id:long}", async (long id, OpenWafDbContext db, EdgeStateStore state,
RateRuleTracker rateRules, ConfigChangeWriter changes, HttpContext ctx, CancellationToken ct) =>
{
if (!TryKnownQuery(ctx, out var unknown)) return Results.BadRequest(new ErrorDto(unknown));
var n = await db.RateRules.Where(r => r.Id == id).ExecuteDeleteAsync(ct);
// The counters go with the row: leaving them would keep counting for a
// budget the operator took off this edge, and a later rule reusing the
// id would inherit a window it never started.
rateRules.ForgetRule(id);
await state.InvalidateAsync(ct);
if (n == 0) return Results.NotFound(new ErrorDto($"no rate rule with id {id}"));
await changes.RecordAsync(ConfigChangeLog.SectionRateRules, ConfigChangeLog.ActionRemoved,
id.ToString(), ct: ct);
return Results.NoContent();
});
// Who a path budget is pausing (OPEN-71). The listing has carried three
// numbers per budget since OPEN-68 — sources counted, windows running,
// over budget now — and no name, so "3 over budget" was the half an
// operator could not act on: the only lever for one of those three was to
// delete the budget for the whole site. The edge-wide budget never had
// this hole, because /admin-api/rate names its sources.
//
// The rows are the same state the guard reads, read without moving it, and
// the limit is passed in from the rule row rather than copied into the
// counter — one copy of the number a budget enforces.
group.MapGet("/rate-rules/{id:long}/sources", async (long id, int? limit, int? offset,
OpenWafDbContext db, RateRuleTracker rateRules, EdgePolicyProvider policyProvider,
HttpContext ctx, CancellationToken ct) =>
{
if (!TryKnownQuery(ctx, out var unknown, "limit", "offset")) return Results.BadRequest(new ErrorDto(unknown));
if (!TryPaging(limit, offset, ReadListDefaultLimit, ReadListMaxLimit,
out var take, out var skip, out var pagingError))
return Results.BadRequest(new ErrorDto(pagingError));
var now = DateTimeOffset.UtcNow;
var rule = await db.RateRules.AsNoTracking().FirstOrDefaultAsync(r => r.Id == id, ct);
if (rule is null) return Results.NotFound(new ErrorDto($"no rate rule with id {id}"));
var live = rule.ExpiresAt is null || rule.ExpiresAt > now;
var rows = rateRules.SourcesFor(id, rule.LimitPerWindow, now, take, skip);
// The same count the listing's `windowsRunning` reports, so a page can
// say whether it is the whole answer.
var total = rateRules.LiveWindowCount(id, now);
ctx.Response.Headers["X-Total-Count"] = total.ToString();
ctx.Response.Headers["X-Truncated"] = (skip + rows.Count < total).ToString().ToLowerInvariant();
var policy = policyProvider.Current;
return Results.Ok(new
{
id = rule.Id,
pattern = rule.Pattern,
limitPerWindow = rule.LimitPerWindow,
windowSeconds = rule.WindowSeconds,
note = rule.Note,
expiresAt = rule.ExpiresAt,
live,
// The windows are keyed on the source key, not on the address the
// operator typed, and the rule that produced the key travels with
// the list — otherwise a /64 entry reads as an address that is not
// the one they are looking for.
scope = "this-process",
keyRule = new
{
ipv4PrefixLength = policy.Ipv4KeyPrefixLength,
ipv6PrefixLength = policy.Ipv6KeyPrefixLength
},
total,
sources = rows.Select(r => new
{
sourceKey = r.SourceKey,
count = r.Count,
overBudget = r.OverBudget,
windowStartsAt = r.WindowStart,
windowEndsAt = r.WindowEnd,
secondsLeft = SecondsLeft(r.WindowEnd, now)
}),
// What an empty list means here, in the list: "the budget is
// counting and nobody is inside a window" and "this budget is dead"
// are different answers, and `sources: []` alone cannot tell them.
howToRead = !live
? "this budget has expired: the guard no longer consults it, and the windows below are what is left of it"
: total == 0
? "the budget is live and counting, and no source is inside a running window right now — which is not the same as nobody ever having asked"
: "the counters live in this process, so N edges allow N budgets; an over-budget source is answered 429 on this path only, and clearing one source restarts its window at zero rather than exempting it"
});
});
// Drop one source's window on one budget: the control for "my office is
// caught by the login budget" that is not "take the budget off every source
// on the site". It is not an exemption and the answer says so — the window
// restarts at zero and the budget starts counting this source again from
// there. For "let them through whatever they do", the allowlist is the
// control, and it outranks every pillar.
group.MapDelete("/rate-rules/{id:long}/sources", async (long id, string? source,
OpenWafDbContext db, RateRuleTracker rateRules, EdgeStateStore state,
ConfigChangeWriter changes, HttpContext ctx, CancellationToken ct) =>
{
if (!TryKnownQuery(ctx, out var unknown, "source")) return Results.BadRequest(new ErrorDto(unknown));
if (string.IsNullOrWhiteSpace(source))
return Results.BadRequest(new ErrorDto("source is required: name the source key whose window on this budget should be dropped"));
var rule = await db.RateRules.AsNoTracking().FirstOrDefaultAsync(r => r.Id == id, ct);
if (rule is null) return Results.NotFound(new ErrorDto($"no rate rule with id {id}"));
var asked = source.Trim();
var clearedKey = asked;
var dropped = rateRules.ForgetRuleSource(id, asked);
if (!dropped && IsAnAddress(asked))
{
// The list prints keys; an operator types an address. Trying the
// key this edge would file that address under is the difference
// between "nothing was cleared" and the right source being let out
// — and the answer names the key it actually dropped.
// The snapshot's policy, not a provider's cached copy: this is the
// key the guard counted under, and a stale prefix length would
// answer "nothing was cleared" for a source that is paused.
var derived = SourceKey.For(asked, state.GetOrRefresh().Policy);
if (!string.Equals(derived, asked, StringComparison.Ordinal))
{
dropped = rateRules.ForgetRuleSource(id, derived);
if (dropped) clearedKey = derived;
}
}
if (dropped)
await changes.RecordAsync(ConfigChangeLog.SectionRateRules, ConfigChangeLog.ActionChanged,
id.ToString(), $"window dropped for {clearedKey} — the counter restarts at zero, this is not an exemption", ct: ct);
return Results.Ok(new
{
id,
sourceKey = clearedKey,
asked = asked,
cleared = dropped,
note = dropped
? $"{clearedKey} starts its window on this budget from zero at its next request: this is a counter reset, not an exemption, and the budget still applies to it and to every other source"
: "this source has no running window on this budget, so nothing was cleared — which is not the same as it being exempt"
});
});
// The policy answer carries its provenance in headers, the same way a
// capped listing carries its completeness there. The body is the policy
// this edge is enforcing — that is what the operator asked for and what
// the page renders — but "enforcing" and "storage confirmed this minute"
// are different claims, and a deleted policy_settings table used to make
// the first look like the second for the whole life of the process.
group.MapGet("/policy", (EdgePolicyProvider policy, HttpContext ctx) =>
{
if (!TryKnownQuery(ctx, out var unknown)) return Results.BadRequest(new ErrorDto(unknown));
ctx.Response.Headers["X-Policy-Reload-Failures"] = policy.ReloadFailures.ToString();
ctx.Response.Headers["X-Policy-Last-Read"] =
policy.LastReloadSuccessAt?.ToString("O") ?? "never";
return Results.Ok(ToDto(policy.Current));
});
group.MapPut("/policy", async (PolicyUpdateRequest req, EdgePolicyProvider policy, EdgeStateStore state,
IStreakTracker streaks, RateTracker rates, RateRuleTracker rateRules, ConfigChangeWriter changes, HttpContext ctx, CancellationToken ct) =>
{
if (!TryKnownQuery(ctx, out var unknown)) return Results.BadRequest(new ErrorDto(unknown));
// The same path an imported document's `policy` section goes through:
// one place turns a policy request into the overrides the store keeps,
// so a document cannot be held to a looser rule than a typed request.
//
// A field that is present but out of range is a 400, not a silent
// no-op. The old shape — `if (req.X is > 0)` — answered 200 with the
// old policy in the body for streakThreshold=0, maxTrackedSources=0,
// banDurationMinutes=-1 and refusalRange="not-a-range", and it stored
// engineBlockStatus=1000 and ipv4KeyPrefixLength=0, which the edge then
// obeyed: the first closed the connection on every banned request, the
// second made one ban apply to every IPv4 address.
if (!PolicyOverrides(req, out var overrides, out var problem))
return Results.BadRequest(new ErrorDto(problem!));
// The policy before the write, so the record can say what changed
// rather than only that something did.
var policyBefore = policy.Current;
// The toggle is a policy change, never a data change: switching
// automatic banning off must leave every row — manual or engine —
// exactly where it was.
// SaveAsync says whether the row landed. Its answer used to be
// thrown away and the endpoint answered 200 with the policy body
// regardless, so a policy change the storage refused — the mode
// toggle, a threshold, the geo lists — read as done. The body even
// showed the old values, which an operator could only notice by
// reading the answer they had just asked for.
if (!await policy.SaveAsync(overrides, ct))
return StorageUnavailable("the policy could not be written: the change is NOT in effect");
// The policy lives inside the snapshot the guard reads, so saving
// it without refreshing the snapshot would leave the toggle
// appearing to work in the API and not on the wire.
await state.InvalidateAsync(ct);
// maxTrackedSources bounds the two live maps, and both read the
// bound once rather than per request — so a policy write that
// changes it has to be pushed into them here, or the new number
// would only take effect on the next restart while the API already
// answers with it.
streaks.Configure(policy.Current);
rates.Configure(policy.Current);
rateRules.Configure(policy.Current);
await changes.RecordAsync(ConfigChangeLog.SectionPolicy, ConfigChangeLog.ActionChanged,
"policy", PolicyChangeSentence(policyBefore, policy.Current), ct: ct);
return Results.Ok(ToDto(policy.Current));
});
group.MapGet("/rate", (RateTracker rates, IStreakTracker streaks, EdgePolicyProvider policyProvider,
HttpContext ctx, int? limit, int? offset, string? source) =>
{
if (!TryKnownQuery(ctx, out var unknown, "limit", "offset", "source")) return Results.BadRequest(new ErrorDto(unknown));
if (!TryPaging(limit, offset, StreakListDefaultLimit, StreakListMaxLimit,
out var take, out var skip, out var pagingError))
return Results.BadRequest(new ErrorDto(pagingError));
if (source is not null && string.IsNullOrWhiteSpace(source))
return Results.BadRequest(new ErrorDto("source must not be empty; omit the parameter to list every source"));
var now = DateTimeOffset.UtcNow;
var policy = policyProvider.Current;
var rows = rates.LiveRates(now, policy, take, skip, source, out var live);
ctx.Response.Headers["X-Truncated"] = (skip + rows.Count < live).ToString().ToLowerInvariant();
return Results.Ok(new
{
// The budget the numbers below are measured against, in the same
// answer. A count without the limit it is compared to is a
// number an operator cannot read, and the mode says whether
// anything is being done about it at all.
mode = policy.Rate.ToString(),
limitPerWindow = policy.RateLimitPerWindow,
windowSeconds = policy.RateWindow.TotalSeconds,
// Counted here, in this process. The budget is per edge — the
// README says so plainly — and a listing that did not name the
// scope would read like the fleet's.
scope = "this-process",
trackedSources = rates.TrackedCount,
liveWindows = live,
sourceFilter = source,
maxTrackedSources = policy.MaxTrackedSources,
trackedIdleMinutes = policy.StateIdleTtl.TotalMinutes,
sources = rows.Select(r => new RateSourceDto(
r.SourceKey, r.Count, r.WindowStart, r.WindowEnd, r.OverBudget))
});
});
group.MapGet("/netblocks", async (NetblockWatcher watcher, EdgePolicyProvider policyProvider,
HttpContext ctx, CancellationToken ct) =>
{
if (!TryKnownQuery(ctx, out var unknown)) return Results.BadRequest(new ErrorDto(unknown));
var policy = policyProvider.Current;
// A surface read is not news: the scan runs without raising alerts,
// so refreshing this page cannot manufacture alert rows.
var candidates = await watcher.ScanAsync(false, ct);
return Results.Ok(new
{
// The rules the numbers below were produced with, in the same
// answer. A candidate count without its threshold is a number an
// operator cannot read, and 0 means the watch is off rather than
// that this edge has no netblocks.
threshold = policy.NetblockCandidateBans,
prefixV4 = policy.NetblockPrefixV4,
prefixV6 = policy.NetblockPrefixV6,
scannedAt = watcher.LastScanAt,
scanError = watcher.LastError,
// Counted on this edge, from this edge's bans. Two edges behind a
// load balancer see different halves of an attack, and a listing
// that did not name its scope would read like the fleet's.
scope = "this-edge",
note = policy.NetblockCandidateBans <= 0
? "the watch is off: netblockCandidateBans is 0, so nothing is grouped and nothing is offered"
: "candidates only: nothing here is banned and nothing here bans anything. "
+ "POST /admin-api/blocks with the CIDR is the operator's decision",
netblocks = candidates.Select(c => new NetblockDto(
c.Match, c.Prefix, c.Bans, c.FirstBanAt, c.LastBanAt, c.Sample, c.AlreadyBanned))
});
});
group.MapGet("/observations", async (OpenWafDbContext db, string? source, int? limit, int? offset,
HttpContext ctx, CancellationToken ct) =>
{
if (!TryKnownQuery(ctx, out var unknown, "source", "limit", "offset")) return Results.BadRequest(new ErrorDto(unknown));
if (!TryPaging(limit, offset, ReadListDefaultLimit, ReadListMaxLimit,
out var take, out var skip, out var pagingError))
return Results.BadRequest(new ErrorDto(pagingError));
// ?source= is the operator's "tell me about this one address" question,
// and the total has to answer the same question. Counting the whole
// table while showing one source's rows would put a 16 next to a
// single row and make X-Truncated claim a cut that never happened.
var query = db.Observations.AsNoTracking();
if (source is not null)
{
if (string.IsNullOrWhiteSpace(source))
return Results.BadRequest(new ErrorDto("source must not be empty; omit the parameter to list every source"));
query = query.Where(o => o.SourceKey == source);
}
var rows = await query
.OrderByDescending(o => o.LastSeenAt)
.Skip(skip)
.Take(take)
.Select(o => new ObservationDto(o.SourceKey, o.LastSeenAt, o.MaxConsecutiveRefusals,
o.TotalRefusals, o.TotalServerErrorStreak, o.LastStatusCode, o.LastPath,
o.LastCountryCode, o.LastCity))
.ToListAsync(ct);
var total = await query.CountAsync(ct);
ctx.Response.Headers["X-Total-Count"] = total.ToString();
ctx.Response.Headers["X-Truncated"] = (skip + rows.Count < total).ToString().ToLowerInvariant();
return Results.Ok(rows);
});
// The streak map is per process, so the answer says which process it
// came from instead of letting a console behind a load balancer imply
// it read the whole deployment. research/2026-10-01-multi-instance
// measured what that assumption costs: round-robin over two edges
// multiplied the effective threshold, and four refusals split 2+2 at a
// threshold of 3 produced no ban at all.
group.MapGet("/streaks", (IStreakTracker tracker, EdgePolicyProvider policyProvider, HttpContext ctx, int? limit, int? offset, string? source) =>
{
if (!TryKnownQuery(ctx, out var unknown, "limit", "offset", "source")) return Results.BadRequest(new ErrorDto(unknown));
var now = DateTimeOffset.UtcNow;
var policy = policyProvider.Current;
if (!TryPaging(limit, offset, StreakListDefaultLimit, StreakListMaxLimit,
out var take, out var skip, out var pagingError))
return Results.BadRequest(new ErrorDto(pagingError));
// The same question the observation and alert listings answer, asked
// of the live map. An empty value is refused rather than read as
// "every source" — the OPEN-23 shape — and the answer names the
// filter it applied, because a page that shows one address and
// reports the whole map's counts is the lie this endpoint already
// fixed once for X-Truncated.
if (source is not null && string.IsNullOrWhiteSpace(source))
return Results.BadRequest(new ErrorDto("source must not be empty; omit the parameter to list every source"));
var streaks = tracker.LiveStreaks(now, policy, take, skip, source, out var standing);
// "Is there more" has to be measured against what is listable, not
// against what the map happens to hold. The map keeps a source whose
// streak a clean answer ended; the listing leaves those out on
// purpose, and counting them made this header claim a cut that never
// happened — measured on the shipped image: 2 standing streaks, one
// reset source, ?limit=1000, and X-Truncated: true.
ctx.Response.Headers["X-Truncated"] = (skip + streaks.Count < standing).ToString().ToLowerInvariant();
return Results.Ok(new
{
// Which store this answer came from, in the answer itself. With the
// shared map the counts are the fleet's, and a page that still said
// "this-process" would be describing a different edge than the one it
// is talking to.
scope = policy.SharedStreaks ? "shared-database" : "this-process",
threshold = policy.StreakThreshold,
windowMinutes = policy.StreakWindow.TotalMinutes,
trackedSources = tracker.TrackedCount,
// The two numbers side by side are the explanation: the map holds
// this many sources, this many of them have something standing.
// With a filter, standingStreaks is the filtered count and
// trackedSources stays the map size — that difference is the
// honest reading of "one of these many".
standingStreaks = standing,
sourceFilter = source,
// What bounds the count above it. A cap is only true of the
// in-process map: the shared store is bounded by time, not by
// how many sources one process can hold, and printing the cap
// there would name a limit nothing enforces.
maxTrackedSources = policy.SharedStreaks ? (int?)null : policy.MaxTrackedSources,
trackedIdleMinutes = policy.StateIdleTtl.TotalMinutes,
trackedRetentionDays = (int)policy.ObservationRetention.TotalDays,
streaks = streaks.Select(st => new StreakDto(st.SourceKey, st.ConsecutiveRefusals,
st.ConsecutiveServerErrors, st.LastStatusCode, st.LastPath, st.LastCountryCode, st.LastSeenAt))
});
});
group.MapGet("/alerts", async (OpenWafDbContext db, string? source, int? limit, int? offset,
HttpContext ctx, CancellationToken ct) =>
{
if (!TryKnownQuery(ctx, out var unknown, "source", "limit", "offset")) return Results.BadRequest(new ErrorDto(unknown));
if (!TryPaging(limit, offset, ReadListDefaultLimit, ReadListMaxLimit,
out var take, out var skip, out var pagingError))
return Results.BadRequest(new ErrorDto(pagingError));
var query = db.Alerts.AsNoTracking();
if (source is not null)
{
if (string.IsNullOrWhiteSpace(source))
return Results.BadRequest(new ErrorDto("source must not be empty; omit the parameter to list every source"));
query = query.Where(a => a.SourceKey == source);
}
var rows = await query
.OrderByDescending(a => a.CreatedAt)
.Skip(skip)
.Take(take)
.ToListAsync(ct);
var total = await query.CountAsync(ct);
ctx.Response.Headers["X-Total-Count"] = total.ToString();
ctx.Response.Headers["X-Truncated"] = (skip + rows.Count < total).ToString().ToLowerInvariant();
return Results.Ok(rows);
});
group.MapGet("/countries", async (OpenWafDbContext db, HttpContext ctx, CancellationToken ct) =>
{
// This listing has no paging, and used to answer 200 with every row
// while pretending not to see ?limit=. Refusing the parameter is the
// honest half: the table is bounded by the number of countries an
// operator can write, so paging is not the fix — saying so is.
if (!TryKnownQuery(ctx, out var unknown)) return Results.BadRequest(new ErrorDto(unknown));
return Results.Ok(await db.CountryRules.AsNoTracking().OrderBy(c => c.Code).ToListAsync(ct));
});
group.MapPut("/countries/{code}", async (string code, bool allowed, OpenWafDbContext db, EdgeStateStore state, ConfigChangeWriter changes, HttpContext ctx, CancellationToken ct) =>
{
if (!TryKnownQuery(ctx, out var unknown, "allowed")) return Results.BadRequest(new ErrorDto(unknown));
if (!TryCountryCode(code, out var normalized, out var codeError))
return Results.BadRequest(new ErrorDto(codeError));
var row = await db.CountryRules.FindAsync([normalized], ct);
if (row is null) db.CountryRules.Add(new CountryRule { Code = normalized, IsAllowed = allowed, UpdatedAt = DateTimeOffset.UtcNow });
else { row.IsAllowed = allowed; row.UpdatedAt = DateTimeOffset.UtcNow; }
await db.SaveChangesAsync(ct);
await state.InvalidateAsync(ct);
await changes.RecordAsync(ConfigChangeLog.SectionCountries, ConfigChangeLog.ActionChanged,
normalized, allowed ? "allowed" : "denied", ct: ct);
return Results.NoContent();
});
// A country rule cannot be un-set by writing the other way: the only way
// to stop enforcing one is to remove it. Until now there was no way to
// remove one at all, which is what made a mistyped code permanent — the
// console gate's own comment used to read "a country rule cannot be
// deleted, only overwritten".
group.MapDelete("/countries/{code}", async (string code, OpenWafDbContext db, EdgeStateStore state, ConfigChangeWriter changes, HttpContext ctx, CancellationToken ct) =>
{
if (!TryKnownQuery(ctx, out var unknown)) return Results.BadRequest(new ErrorDto(unknown));
if (!TryCountryCode(code, out var normalized, out var codeError))
return Results.BadRequest(new ErrorDto(codeError));
var row = await db.CountryRules.FindAsync([normalized], ct);
if (row is null) return Results.NotFound(new ErrorDto($"no country rule for \"{normalized}\""));
db.CountryRules.Remove(row);
await db.SaveChangesAsync(ct);
await state.InvalidateAsync(ct);
await changes.RecordAsync(ConfigChangeLog.SectionCountries, ConfigChangeLog.ActionRemoved,
normalized, ct: ct);
return Results.NoContent();
});
// What the console's country table reads: the sources the edge has
// actually seen, counted from the observation aggregates rather than from
// a request log (there isn't one). A read, not new decision logic.
group.MapGet("/countries/summary", async (OpenWafDbContext db, HttpContext ctx, CancellationToken ct) =>
{
if (!TryKnownQuery(ctx, out var unknown)) return Results.BadRequest(new ErrorDto(unknown));
// Anonymous projection, and the sort happens after translation: the
// record-constructor form compiles and then fails at query time with
// "could not be translated" (found by a test).
var rows = await db.Observations.AsNoTracking()
.Where(o => o.LastCountryCode != null)
.GroupBy(o => o.LastCountryCode)
.Select(g => new { Code = g.Key, Sources = g.Count(), Refusals = g.Sum(o => o.TotalRefusals) })
.ToListAsync(ct);
// The anonymous shape has to survive the query and stop at the query:
// it is what EF translates, and the record-constructor form fails at
// query time with "could not be translated" (measured by a test). The
// wire shape is a named type, so the response has a compiled contract
// and the sort stays where it was — after translation.
// `Code` is nullable in the model and non-null in these rows: the
// query filters `LastCountryCode != null`, which the compiler cannot
// see and EF does apply.
return Results.Ok(rows
.Select(r => new CountrySummaryDto(r.Code!, r.Sources, r.Refusals))
.OrderByDescending(r => r.Sources));
});
group.MapGet("/geo", (IGeoIpLookup geo, HttpContext ctx) =>
{
if (!TryKnownQuery(ctx, out var unknown)) return Results.BadRequest(new ErrorDto(unknown));
return Results.Ok(new
{
loaded = geo.IsLoaded,
database = geo.Info?.DatabaseType,
builtAt = geo.Info?.BuildDate,
ageDays = geo.Info?.Age is { } age ? Math.Round(age.TotalDays, 1) : (double?)null,
supportsCity = geo.Info?.SupportsCity ?? false
});
});
// OPEN-59: the dry run. Every other surface here answers what the edge
// already did; an operator about to write a rule, an exemption or a
// country rule has no way to ask what a request WOULD get, so the only
// test is a real request from a real address and a mistake is a real
// refusal of a real visitor. This runs the same DecisionEngine over the
// same snapshot the wire reads — there is no second decision to drift —
// and narrates the order, because "blocked" without "which pillar said
// so and which never got asked" is the half an operator cannot act on.
//
// It changes nothing: no counter, no streak, no rate window, no alert.
// The two pillars a preview cannot honestly answer — the live budget and
// the streak that depends on responses the upstream has not produced —
// are named in the body rather than left out, because a bare "pass"
// without them is a wrong answer, not an incomplete one.
group.MapGet("/decide", (string? ip, string? path, string? country,
EdgeStateStore state, IGeoIpLookup geo, RateTracker rates, RateRuleTracker rateRules,
HttpContext ctx) =>
{
if (!TryKnownQuery(ctx, out var unknown, "ip", "path", "country"))
return Results.BadRequest(new ErrorDto(unknown));
if (ip is not null && string.IsNullOrWhiteSpace(ip))
return Results.BadRequest(new ErrorDto("ip must not be blank; omit the parameter to ask about the path alone"));
// A typo in the address must not answer "pass". The guard would have
// had a real address; this call has whatever was typed, and the only
// honest response to a non-address is a refusal naming it.
if (ip is not null && !IsAnAddress(ip.Trim()))
return Results.BadRequest(new ErrorDto($"ip must be an address; got \"{ip}\""));
var askedPath = string.IsNullOrWhiteSpace(path) ? "/" : path!.Trim();
if (!askedPath.StartsWith('/'))
return Results.BadRequest(new ErrorDto($"path must start with /; got \"{askedPath}\""));
var now = DateTimeOffset.UtcNow;
// The same call the guard makes, not the raw field: a preview that
// read a stale snapshot would answer a request the wire is no longer
// answering, and the whole claim of the feature is that the two
// agree.
var snapshot = state.GetOrRefresh();
var policy = snapshot.Policy;
var hasAddress = !string.IsNullOrWhiteSpace(ip);
// The country is part of the question. Given, it is used as given;
// otherwise the geo pillar is asked the same way the guard asks it,
// and the answer says which of the two happened — a preview that
// silently skipped the lookup would answer a different request.
string? askedCountry = null;
var countrySource = "none";
if (!string.IsNullOrWhiteSpace(country))
{
askedCountry = country.Trim().ToUpperInvariant();
countrySource = "given";
}
else if (policy.Geo != GeoMode.Off && hasAddress)
{
askedCountry = geo.Lookup(ip);
if (askedCountry is not null) countrySource = "geo-database";
}
var decision = DecisionEngine.Decide(snapshot, hasAddress ? ip!.Trim() : null, askedPath, now, askedCountry);
// The key this edge would use for the address — computed here rather
// than read off the decision, because a Pass carries no source key and
// the trace still has to be able to say whether a live ban exists for
// this source.
var askedKey = hasAddress ? SourceKey.For(ip!.Trim(), policy) : null;
var rows = DecisionTrace.For(
snapshot, decision, now, hasAddress, askedCountry is not null, askedKey);
RequestRule? matchedRule = null;
if (decision.Reason is { Length: > 5 } reason && reason.StartsWith("rule_", StringComparison.Ordinal)
&& long.TryParse(reason[5..], out var ruleId))
matchedRule = snapshot.RequestRules.FirstOrDefault(r => r.Id == ruleId);
return Results.Ok(new
{
// The question, echoed exactly, so the answer cannot be read as
// being about something else.
path = askedPath,
ip = hasAddress ? ip!.Trim() : null,
sourceKey = string.IsNullOrEmpty(askedKey) ? null : askedKey,
country = askedCountry,
countrySource,
// The answer, in the words the wire uses: the same verdict value
// the log prints and the status the visitor gets.
verdict = EdgeVerdictLabel.For(decision.Verdict),
blocked = decision.IsBlocked,
status = decision.StatusCode,
location = decision.Location,
reason = decision.Reason,
expiresAt = decision.ExpiresAt,
// The evidence behind the verdict, not just its name. An id
// without the pattern is a number; a reason without the expiry is
// a sentence with no end.
rule = matchedRule is null ? null : new
{
id = matchedRule.Id,
pattern = matchedRule.Pattern,
action = matchedRule.Action.ToString().ToLowerInvariant(),
note = matchedRule.Note,
expiresAt = matchedRule.ExpiresAt
},
// The volume pillar (OPEN-69). It is not in DecisionEngine — a
// count has to be kept while requests arrive, not read off a
// snapshot — so the preview answered every other pillar and stayed
// silent about this one, which is the pillar operators most often
// read as a ban. What this section says is what the counters of
// this process say right now, read without spending them: a preview
// that answered by counting its own question would refuse the next
// real request because somebody pressed a button.
volume = VolumePreview.For(policy, snapshot, askedPath, askedKey, rates, rateRules, now,
// The guard runs the volume pillar only for a request no other pillar has
// answered, so the preview says the same: a refusal from an earlier pillar
// never reaches the counter and never spends it.
decision.Verdict == EdgeVerdict.Pass),
// The order, pillar by pillar, with the reason each one after the
// answering pillar did not speak. This is the part that makes the
// answer actionable: it says which pillar to change.
pillars = rows.Select(t => new
{
pillar = t.Pillar,
outcome = PillarOutcomes.Label(t.Outcome),
note = t.Note
}),
notEvaluated = rows
.Where(t => t.Outcome is PillarOutcome.NotEvaluated or PillarOutcome.NotEnforcedInThisMode)
.Select(t => t.Pillar),
// Which state this was computed against. A preview is a claim
// about the snapshot, not a guarantee about the next request: a
// block written a second ago lands when the snapshot refreshes.
mode = policy.Mode.ToString(),
geoMode = policy.Geo.ToString(),
rateMode = policy.Rate.ToString(),
snapshotAgeSeconds = Math.Round((now - snapshot.GeneratedAt).TotalSeconds, 1),
snapshotTtlSeconds = Math.Round(state.RefreshTtl.TotalSeconds, 1),
snapshotStale = state.IsStale
});
});
// OPEN-70: one address, one answer.
//
// Every other surface here is a table with a filter on it. Investigating
// one source means opening six of them — blocks, allow, streaks,
// observations, alerts, the dry run — and holding the join in one's head,
// and the join is where the mistakes are: a v6 address looked up in its
// full form when the ban is keyed on the /64, an expired exemption read as
// a live one, a per-process streak read as the deployment's, and a CIDR
// ban that an equality lookup never finds at all. This answers the whole
// question in one call.
//
// It does it by asking the same objects the request path asks, never a
// second copy of their logic: containment through NetworkMatch and
// NetworkBanIndex (the two places that already know what a CIDR means),
// the identity through SourceKey, the verdict through DecisionEngine. A
// dossier with its own matcher would be a dossier about a different edge.
//
// Nothing is written and nothing is spent — the dry run's rule (OPEN-69)
// applied to every part of it. And "no row" and "not visible from this
// process" are different words throughout, because the first is a fact
// about the source and the second is a fact about where the question was
// asked.
group.MapGet("/source", async (string? ip, string? path,
EdgeStateStore state, IGeoIpLookup geo, RateTracker rates, RateRuleTracker rateRules,
IStreakTracker streaks, NetblockWatcher netblocks, OpenWafDbContext db,
HttpContext ctx, CancellationToken ct) =>
{
if (!TryKnownQuery(ctx, out var unknown, "ip", "path"))
return Results.BadRequest(new ErrorDto(unknown));
// Required here, unlike /decide where the path alone is a fair
// question: this surface's claim is that it knows something about a
// source, and a source cannot be inferred from an empty query.
if (string.IsNullOrWhiteSpace(ip))
return Results.BadRequest(new ErrorDto("ip is required: this surface answers about one address"));
if (!IsAnAddress(ip.Trim()))
return Results.BadRequest(new ErrorDto($"ip must be an address; got \"{ip}\""));
var askedIp = ip.Trim();
string? askedPath = null;
if (path is not null)
{
askedPath = path.Trim().Length == 0 ? "/" : path.Trim();
if (!askedPath.StartsWith('/'))
return Results.BadRequest(new ErrorDto($"path must start with /; got \"{askedPath}\""));
}
var now = DateTimeOffset.UtcNow;
var snapshot = state.GetOrRefresh();
var policy = snapshot.Policy;
// The key, not the address. A v6 dossier looked up by the address the
// socket carried would answer "nothing known" about a source this edge
// has banned twice, because the ban is filed on the /64.
var key = SourceKey.For(askedIp, policy);
// --- what the geo pillar would say about this address -----------
var country = policy.Geo == GeoMode.Off ? null : geo.Lookup(askedIp);
var geoSource = policy.Geo == GeoMode.Off
? "geo-off"
: country is not null ? "geo-database" : "not-in-database";
CountryRule? countryRule = null;
if (!string.IsNullOrWhiteSpace(country))
snapshot.Countries.TryGetValue(country.Trim().ToUpperInvariant(), out countryRule);
var geoDenied = policy.Geo != GeoMode.Off && !string.IsNullOrWhiteSpace(country)
&& policy.Geo switch
{
// The same two lines the engine uses. Duplicated logic would
// be a dossier that disagrees with the wire about who is
// refused, which is the one failure this surface cannot have.
GeoMode.DenyList => countryRule is { IsAllowed: false },
GeoMode.AllowList => countryRule is not { IsAllowed: true },
_ => false
};
// --- the exemption: containment, not equality ------------------
AllowEntry? coveringAllow = null;
foreach (var entry in snapshot.AllowEntries)
{
if (!NetworkMatch.Matches(askedIp, entry.Match)) continue;
if (entry.IsLive(now)) { coveringAllow = entry; break; }
// A dead exemption is worth naming: "this address used to be
// let through" is the answer an operator acts on, and it is not
// the same answer as "never was".
coveringAllow ??= entry;
}
// --- the operator's list, in the order the engine reads it -----
snapshot.OperatorBlocks.TryGetValue(key, out var operatorBlock);
NetworkBan? coveringRange = null;
if (operatorBlock is null || !operatorBlock.IsLive(now))
snapshot.OperatorRanges.TryMatch(askedIp, now, out coveringRange!);
// --- the engine's own ban --------------------------------------
snapshot.EngineBans.TryGetValue(key, out var engineBan);
var engineBanApplies = engineBan is not null && engineBan.IsLive(now)
&& policy.Mode == EnforcementMode.Enforce;
// --- the streak: this process's standing, the database's memory -
var liveStreak = streaks.Peek(key);
var observation = await db.Observations.AsNoTracking()
.FirstOrDefaultAsync(o => o.SourceKey == key, ct);
var alerts = await db.Alerts.AsNoTracking()
.Where(a => a.SourceKey == key)
.OrderByDescending(a => a.CreatedAt)
.Take(DossierAlertLimit)
.ToListAsync(ct);
// --- the volume pillar, read without spending it ---------------
var counting = policy.Rate != RateMode.Off;
object? edgeBudget = null;
if (counting)
{
var live = rates.LiveRates(now, policy, 1, 0, key, out _);
if (live.Count > 0)
{
var w = live[0];
edgeBudget = new
{
count = w.Count,
limitPerWindow = policy.RateLimitPerWindow,
windowSeconds = Math.Round(policy.RateWindow.TotalSeconds, 1),
windowStartsAt = w.WindowStart,
windowEndsAt = w.WindowEnd,
secondsLeft = SecondsLeft(w.WindowEnd, now),
overBudget = w.OverBudget
};
}
}
// Every path budget this source is already inside, without being
// asked for a path — the preview needs one, the dossier does not.
var windows = counting
? rateRules.WindowsFor(key, now)
: Array.Empty<RuleWindowObservation>();
var pathBudgets = windows.Select(w =>
{
var rule = snapshot.RateRules.FirstOrDefault(r => r.Id == w.RuleId);
return new
{
id = w.RuleId,
// A window can outlive the budget that created it: the
// counters are dropped when the rule is deleted, but a
// snapshot a few seconds old may still name the rule.
// Naming nothing would be a guess about which of the two
// happened, so the row says what it is.
pattern = rule?.Pattern ?? "(no live rule with this id on this edge)",
note = rule?.Note,
limitPerWindow = rule?.LimitPerWindow ?? 0,
windowSeconds = w.WindowSeconds,
count = w.Count,
overBudget = rule is not null && rule.LimitPerWindow > 0
&& w.Count > rule.LimitPerWindow,
windowEndsAt = w.WindowEnd,
secondsLeft = SecondsLeft(w.WindowEnd, now)
};
}).ToList();
// --- the ranges this edge is offering, that would cover it -----
var candidates = await netblocks.ScanAsync(false, ct);
var offers = candidates
.Where(c => NetworkMatch.Matches(askedIp, c.Match))
.Select(c => new NetblockDto(c.Match, c.Prefix, c.Bans, c.FirstBanAt, c.LastBanAt,
c.Sample, c.AlreadyBanned))
.ToList();
// --- the one sentence, from the pillars that need no path ------
string answerVerdict;
string answer;
if (coveringAllow is not null && coveringAllow.IsLive(now))
{
answerVerdict = EdgeVerdictLabel.For(EdgeVerdict.PassAllowlisted);
answer = $"allowlisted by \"{coveringAllow.Match}\": no pillar below the allowlist is asked about this source";
}
else if (operatorBlock is not null && operatorBlock.IsLive(now))
{
answerVerdict = EdgeVerdictLabel.For(EdgeVerdict.BlockOperator);
answer = $"the operator's block on {key} answers for this source"
+ (operatorBlock.ExpiresAt is null ? " and never expires" : $" until {operatorBlock.ExpiresAt:O}");
}
else if (coveringRange is not null)
{
answerVerdict = EdgeVerdictLabel.For(EdgeVerdict.BlockOperator);
answer = $"the operator's range ban {coveringRange.Match} covers this address"
+ (coveringRange.ExpiresAt is null ? " and never expires" : $" until {coveringRange.ExpiresAt:O}");
}
else if (engineBanApplies)
{
answerVerdict = EdgeVerdictLabel.For(EdgeVerdict.BlockEngine);
answer = $"this edge banned {key} itself"
+ (engineBan!.ExpiresAt is null ? "" : $" until {engineBan.ExpiresAt:O}");
}
else if (geoDenied)
{
answerVerdict = EdgeVerdictLabel.For(EdgeVerdict.GeoReject);
answer = $"the geo pillar refuses {country} in {policy.Geo} mode";
}
else if (engineBan is not null && engineBan.IsLive(now))
{
answerVerdict = "none";
answer = $"a live engine ban exists for {key}, but {policy.Mode} mode enforces nothing: this source is served";
}
else
{
answerVerdict = "none";
answer = "no pillar that answers without a path refuses this source";
}
return Results.Ok(new
{
// The question, echoed exactly, plus the key the answer is filed
// under and the rule that produced it — without the rule the key
// looks like a typo of the address.
ip = askedIp,
sourceKey = key,
keyRule = new
{
ipv4PrefixLength = policy.Ipv4KeyPrefixLength,
ipv6PrefixLength = policy.Ipv6KeyPrefixLength,
note = "bans, streaks and budgets are filed under sourceKey, not under ip; the allowlist and range bans are matched against ip itself"
},
askedPath,
verdict = answerVerdict,
answer,
answerScope = "the pillars that need no path; request rules and the volume budget are path-dependent — pass path= for the full verdict",
geo = new
{
country,
source = geoSource,
rule = countryRule is null ? null : new
{
code = countryRule.Code,
allowed = countryRule.IsAllowed,
updatedAt = countryRule.UpdatedAt
},
mode = policy.Geo.ToString(),
wouldDeny = geoDenied
},
// Each part names its own store, because the two answer different
// questions: the database is what this deployment knows, this
// process is what this instance is currently counting.
allow = coveringAllow is null ? null : new
{
id = coveringAllow.Id,
match = coveringAllow.Match,
note = coveringAllow.Note,
createdAt = coveringAllow.CreatedAt,
expiresAt = coveringAllow.ExpiresAt,
live = coveringAllow.IsLive(now),
scope = "database"
},
operatorBlock = operatorBlock is null
? coveringRange is null ? null : new
{
sourceKey = key,
cameFromRange = true,
match = (string?)coveringRange.Match,
reason = coveringRange.Reason,
redirectTo = coveringRange.RedirectTo,
createdAt = coveringRange.CreatedAt,
expiresAt = coveringRange.ExpiresAt,
live = coveringRange.IsLive(now),
scope = "database"
}
: new
{
sourceKey = operatorBlock.SourceKey,
cameFromRange = false,
match = (string?)null,
reason = operatorBlock.Reason,
redirectTo = operatorBlock.RedirectTo,
createdAt = operatorBlock.CreatedAt,
expiresAt = operatorBlock.ExpiresAt,
live = operatorBlock.IsLive(now),
scope = "database"
},
engineBan = engineBan is null ? null : new
{
sourceKey = engineBan.SourceKey,
reason = engineBan.Reason,
redirectTo = engineBan.RedirectTo,
createdAt = engineBan.CreatedAt,
expiresAt = engineBan.ExpiresAt,
live = engineBan.IsLive(now),
applies = engineBanApplies,
lastStatusCode = engineBan.LastStatusCode,
lastPath = engineBan.LastPath,
consecutiveRefusals = engineBan.ConsecutiveRefusals,
enforcementMode = policy.Mode.ToString(),
scope = "database"
},
streak = liveStreak is null ? null : new
{
scope = policy.SharedStreaks ? "shared-database" : "this-process",
consecutiveRefusals = liveStreak.MaxConsecutiveRefusals,
totalRefusals = liveStreak.TotalRefusals,
consecutiveServerErrors = liveStreak.MaxConsecutiveServerErrors,
lastStatusCode = liveStreak.LastStatusCode,
lastPath = liveStreak.LastPath,
lastSeenAt = liveStreak.LastSeenAt,
threshold = policy.StreakThreshold,
windowMinutes = policy.StreakWindow.TotalMinutes,
// The durable shadow of the same counter: the live map forgets
// a source when it ages out or the process restarts, and "this
// source has done this before" is the question that decides
// whether to ban the range around it.
maxConsecutiveEver = observation?.MaxConsecutiveRefusals,
totalRefusalsEver = observation?.TotalRefusals,
firstSeenAt = observation?.FirstSeenAt,
lastSeenAtDurable = observation?.LastSeenAt,
durableScope = observation is null ? "no observation row" : "database"
},
volume = new
{
mode = policy.Rate.ToString(),
scope = "this-process",
edgeBudget,
pathBudgets,
note = counting
? "counters live in this process, so N edges allow N budgets; nothing here was spent by asking"
: "the volume pillar is off: nothing is counted on this edge, so no budget can be crossed"
},
alerts = alerts.Select(a => new
{
id = a.Id,
kind = a.Kind,
count = a.Count,
lastStatusCode = a.LastStatusCode,
lastPath = a.LastPath,
createdAt = a.CreatedAt,
detail = a.Detail,
scope = "database"
}),
netblockOffers = offers,
// The dry run, only when a path was asked for. The same
// DecisionEngine over the same snapshot the wire reads, so the
// dossier's parts and this verdict cannot disagree.
wouldAnswer = askedPath is null ? null : DescribeSourceVerdict(
DecisionEngine.Decide(snapshot, askedIp, askedPath, now, country),
VolumePreview.For(policy, snapshot, askedPath, key, rates, rateRules, now,
// The guard counts only a request no other pillar answered.
true)),
scope = new
{
database = new[] { "allow", "operatorBlock", "engineBan", "alerts", "observations", "netblockOffers" },
thisProcess = new[] { "streak (unless sharedStreaks)", "volume counters" },
snapshotAgeSeconds = Math.Round((now - snapshot.GeneratedAt).TotalSeconds, 1),
snapshotTtlSeconds = Math.Round(state.RefreshTtl.TotalSeconds, 1),
snapshotStale = state.IsStale
}
});
});
// One source through time (OPEN-73). The dossier answers what this edge
// knows about an address now; the horizon answers what changes soon. The
// question neither answers is the one a complaint on Monday asks: what
// already happened to this source, in the order it happened. Every record
// is dated and every one is in this database — the block an operator
// wrote, the ban this edge decided on its own, the exemption that let it
// through, the alerts raised about it, the operator's own change records,
// the row that counts its refusals — but they sit in six tables, so the
// story is whatever the last-opened listing happened to show.
//
// The join is here rather than in the page for the same reason the dry run
// is: an answer assembled from six calls can have each part true and the
// whole wrong, and the ordering is the answer.
group.MapGet("/history", async (string? ip, int? within, int? limit,
EdgeStateStore state, OpenWafDbContext db, HttpContext ctx, CancellationToken ct) =>
{
if (!TryKnownQuery(ctx, out var unknown, "ip", "within", "limit"))
return Results.BadRequest(new ErrorDto(unknown));
if (string.IsNullOrWhiteSpace(ip))
return Results.BadRequest(new ErrorDto("ip is required: this surface answers about one source"));
if (!IsAnAddress(ip.Trim()))
return Results.BadRequest(new ErrorDto($"ip must be an address; got \"{ip}\""));
var askedIp = ip.Trim();
var minutes = within ?? HistoryDefaultMinutes;
if (minutes < HistoryMinMinutes || minutes > HistoryMaxMinutes)
return Results.BadRequest(new ErrorDto($"within must be {HistoryMinMinutes}..{HistoryMaxMinutes} minutes; got {minutes}"));
var take = limit ?? HistoryDefaultLimit;
if (take < HistoryMinLimit || take > HistoryMaxLimit)
return Results.BadRequest(new ErrorDto($"limit must be {HistoryMinLimit}..{HistoryMaxLimit}; got {take}"));
var now = DateTimeOffset.UtcNow;
var since = now.AddMinutes(-minutes);
var policy = state.GetOrRefresh().Policy;
// The key, not the address — the same rule the dossier had to learn:
// a v6 source is filed under its /64, and looking up the address the
// socket carried would answer "nothing happened to it".
var key = SourceKey.For(askedIp, policy);
var blocks = await db.Blocks.AsNoTracking()
.Where(b => b.SourceKey == key && b.CreatedAt >= since)
.ToListAsync(ct);
var alerts = await db.Alerts.AsNoTracking()
.Where(a => a.SourceKey == key && a.CreatedAt >= since)
.ToListAsync(ct);
var observation = await db.Observations.AsNoTracking()
.FirstOrDefaultAsync(o => o.SourceKey == key, ct);
// A range and an exemption are matched against the address, not the
// key, and both lists are the operator's own — small enough to filter
// here rather than pretend SQL expresses containment for both
// families. The distinction the dossier learned applies to the story
// too: a /28 that covers this address is part of its history even
// though no row names it.
var ranges = (await db.NetworkBans.AsNoTracking().ToListAsync(ct))
.Where(r => NetworkMatch.Matches(askedIp, r.Match) && r.CreatedAt >= since)
.ToList();
var allows = (await db.AllowEntries.AsNoTracking().ToListAsync(ct))
.Where(a => NetworkMatch.Matches(askedIp, a.Match) && a.CreatedAt >= since)
.ToList();
var changes = (await db.ConfigChanges.AsNoTracking()
.Where(c => c.At >= since)
.ToListAsync(ct))
.Where(c => string.Equals(c.Target, key, StringComparison.Ordinal)
|| string.Equals(c.Target, askedIp, StringComparison.Ordinal)
// A change to a range that covers this address is a change to
// this source's conditions, so it belongs in its story.
|| NetworkMatch.Matches(askedIp, c.Target))
.ToList();
var events = new List<HistoryEvent>();
foreach (var b in blocks)
{
// The reason an engine ban carries already narrates its evidence
// ("3 consecutive refusals (400-499) within 5 min; last 404
// /wp-login.php"), so appending the same fields again would print
// the sentence twice with a dash between it. The fields are the
// fallback for a row written without a reason, not a suffix.
var evidence = !string.IsNullOrWhiteSpace(b.Reason)
? b.Reason
: b.LastStatusCode is null && b.LastPath is null
? null
: $"last {b.LastStatusCode?.ToString() ?? "?"} {b.LastPath}"
+ (b.ConsecutiveRefusals is > 0
? $" ({b.ConsecutiveRefusals} refusals in a row)" : "");
events.Add(new HistoryEvent(b.CreatedAt,
b.Source == BlockSource.Operator ? "operator block" : "engine ban",
b.Source == BlockSource.Operator
? "the operator wrote a block on this source"
: "this edge banned the source itself",
string.IsNullOrWhiteSpace(evidence) ? null : evidence,
b.IsLive(now), b.ExpiresAt, key, b.Id));
}
foreach (var r in ranges)
events.Add(new HistoryEvent(r.CreatedAt, "range ban",
$"the operator banned {r.Match}, which covers this address",
string.IsNullOrWhiteSpace(r.Reason) ? null : r.Reason,
r.IsLive(now), r.ExpiresAt, r.Match, r.Id));
foreach (var a in allows)
events.Add(new HistoryEvent(a.CreatedAt, "allow entry",
$"exempted by \"{a.Match}\" \u2014 an exemption outranks every ban",
string.IsNullOrWhiteSpace(a.Note) ? null : a.Note,
a.IsLive(now), a.ExpiresAt, a.Match, a.Id));
foreach (var a in alerts)
events.Add(new HistoryEvent(a.CreatedAt, "alert",
$"alert {a.Kind} raised \u00d7{a.Count}",
string.IsNullOrWhiteSpace(a.Detail)
? $"last {a.LastStatusCode?.ToString() ?? "?"} {a.LastPath}" : a.Detail,
null, null, a.SourceKey, a.Id));
foreach (var c in changes)
events.Add(new HistoryEvent(c.At, "config change",
$"{c.Section} {c.Action}: {c.Target}",
string.IsNullOrWhiteSpace(c.Detail) ? null : c.Detail,
null, null, c.Target, c.Id));
if (observation is not null)
{
if (observation.FirstSeenAt >= since)
events.Add(new HistoryEvent(observation.FirstSeenAt, "seen",
"first seen by this edge", null, null, null, observation.SourceKey, null));
if (observation.LastSeenAt >= since)
events.Add(new HistoryEvent(observation.LastSeenAt, "seen",
$"last seen \u2014 answered {observation.LastStatusCode?.ToString() ?? "?"} on {observation.LastPath}",
$"{observation.TotalRefusals} refusals counted, worst run "
+ $"{observation.MaxConsecutiveRefusals} in a row",
null, null, observation.SourceKey, null));
}
// Oldest first: this is a story, and reading it backwards turns "the
// exemption, then the ban" into "the ban, then the exemption".
events.Sort((x, y) => x.At.CompareTo(y.At));
var shown = events.Take(take).ToList();
return Results.Ok(new
{
ip = askedIp,
sourceKey = key,
keyRule = new
{
ipv4PrefixLength = policy.Ipv4KeyPrefixLength,
ipv6PrefixLength = policy.Ipv6KeyPrefixLength,
note = "bans, alerts and observations are filed under sourceKey; ranges and exemptions are matched against ip itself"
},
window = new { withinMinutes = minutes, since, until = now },
scope = "database",
count = events.Count,
shown = shown.Count,
truncated = events.Count > shown.Count,
events = shown,
// What was looked at, so an empty story is distinguishable from a
// surface that read nothing: "nothing happened to this source" and
// "this edge holds no records at all" are different answers.
searched = new
{
block = blocks.Count,
range = ranges.Count,
allow = allows.Count,
alert = alerts.Count,
change = changes.Count,
observation = observation is null ? 0 : 1
},
note = events.Count == 0
? "nothing recorded about this source inside the window; `searched` names what was looked at"
: "oldest first; a range or an exemption is in the story because it covers this address, not because a row names it; expired rows stay and say so"
});
});
// Where does this appear? (OPEN-74). The words an operator remembers are
// not the fields the listings filter on: "ticket 441" sits in a block's
// reason, in an exemption's note, in a path rule's note and in the change
// log's detail, and six weeks later that phrase is all there is to go on.
// Asking it today means opening eight listings and reading every row,
// because not one of them looks at the text.
//
// Two things make this more than a grep across tables. What an operator
// remembers is often an address, and the row that governs an address does
// not name it — a /28 covers the office without ever carrying its number —
// so an address query also returns the rows that cover it and says that is
// why they are in the answer. And the query is data, not LIKE's grammar:
// "100%" has to search as "100%", which means escaping the wildcards
// instead of answering about everything that happens to start with 100.
group.MapGet("/find", async (string? q, int? limit,
EdgeStateStore state, OpenWafDbContext db, HttpContext ctx, CancellationToken ct) =>
{
if (!TryKnownQuery(ctx, out var unknown, "q", "limit"))
return Results.BadRequest(new ErrorDto(unknown));
if (string.IsNullOrWhiteSpace(q))
return Results.BadRequest(new ErrorDto("q is required: this surface answers where a text appears"));
var asked = q.Trim();
if (asked.Length < SearchMinQueryLength || asked.Length > SearchMaxQueryLength)
return Results.BadRequest(new ErrorDto($"q must be {SearchMinQueryLength}..{SearchMaxQueryLength} characters; got {asked.Length}"));
var take = limit ?? SearchDefaultLimit;
if (take < SearchMinLimit || take > SearchMaxLimit)
return Results.BadRequest(new ErrorDto($"limit must be {SearchMinLimit}..{SearchMaxLimit}; got {take}"));
var now = DateTimeOffset.UtcNow;
var policy = state.GetOrRefresh().Policy;
var pattern = "%" + EscapeLikeWildcards(asked) + "%";
var isAddress = IsAnAddress(asked);
// The key, not the address — the rule the dossier and the story both
// had to learn: a v6 source is filed under its /64, so asking about
// the address the socket carried would miss the ban that answers it.
var key = isAddress ? SourceKey.For(asked, policy) : null;
var hits = new List<SearchHit>();
var seen = new HashSet<string>(StringComparer.Ordinal);
var counts = new Dictionary<string, int>(StringComparer.Ordinal);
foreach (var store in SearchStoreNames) counts[store] = 0;
bool Add(string store, long? id, string? match, string? rule, string? text,
DateTimeOffset at, bool? live, DateTimeOffset? expiresAt, string why)
{
// One row can arrive twice: a range whose text matches and which
// also covers the queried address. It is still one row, and the
// text match is the better reason for being in the answer.
if (id is not null && !seen.Add(store + "#" + id.Value)) return false;
hits.Add(new SearchHit(store, id, match, rule, text, at, live, expiresAt, why));
return true;
}
// Which field carried the text. The store's own query already decided
// the row belongs here; this names the part, so a hit in a block's
// reason is not mistaken for a hit on a path rule's pattern.
static (string? text, string? field) MatchedIn(string needle,
(string? value, string field)[] candidates)
{
foreach (var c in candidates)
if (c.value is not null && c.value.Contains(needle, StringComparison.OrdinalIgnoreCase))
return (c.value, c.field);
return (null, null);
}
static string Why(string? field) => field is null ? "text matched" : $"text matched {field}";
// 1. The blocks this edge holds — the operator's and its own alike.
counts["block"] = await db.Blocks.AsNoTracking()
.Where(b => EF.Functions.Like(b.SourceKey, pattern, LikeEscape)
|| EF.Functions.Like(b.Reason, pattern, LikeEscape)
|| EF.Functions.Like(b.LastPath, pattern, LikeEscape))
.CountAsync(ct);
foreach (var b in await db.Blocks.AsNoTracking()
.Where(b => EF.Functions.Like(b.SourceKey, pattern, LikeEscape)
|| EF.Functions.Like(b.Reason, pattern, LikeEscape)
|| EF.Functions.Like(b.LastPath, pattern, LikeEscape))
.OrderByDescending(b => b.CreatedAt).Take(take).ToListAsync(ct))
{
var m = MatchedIn(asked, new (string?, string)[]
{ (b.Reason, "reason"), (b.LastPath, "last path"), (b.SourceKey, "source key") });
Add("block", b.Id, b.SourceKey, null, m.text, b.CreatedAt,
b.IsLive(now), b.ExpiresAt, Why(m.field));
}
// 2. The ranges the operator banned.
counts["range"] = await db.NetworkBans.AsNoTracking()
.Where(r => EF.Functions.Like(r.Match, pattern, LikeEscape)
|| EF.Functions.Like(r.Reason, pattern, LikeEscape))
.CountAsync(ct);
foreach (var r in await db.NetworkBans.AsNoTracking()
.Where(r => EF.Functions.Like(r.Match, pattern, LikeEscape)
|| EF.Functions.Like(r.Reason, pattern, LikeEscape))
.OrderByDescending(r => r.CreatedAt).Take(take).ToListAsync(ct))
{
var m = MatchedIn(asked, new (string?, string)[] { (r.Match, "match"), (r.Reason, "reason") });
Add("range", r.Id, r.Match, null, m.text, r.CreatedAt, r.IsLive(now), r.ExpiresAt, Why(m.field));
}
// 3. The exemptions, which outrank every ban and are the first thing
// an operator needs to find before lifting one.
counts["allow"] = await db.AllowEntries.AsNoTracking()
.Where(a => EF.Functions.Like(a.Match, pattern, LikeEscape)
|| EF.Functions.Like(a.Note, pattern, LikeEscape))
.CountAsync(ct);
foreach (var a in await db.AllowEntries.AsNoTracking()
.Where(a => EF.Functions.Like(a.Match, pattern, LikeEscape)
|| EF.Functions.Like(a.Note, pattern, LikeEscape))
.OrderByDescending(a => a.CreatedAt).Take(take).ToListAsync(ct))
{
var m = MatchedIn(asked, new (string?, string)[] { (a.Match, "match"), (a.Note, "note") });
Add("allow", a.Id, a.Match, null, m.text, a.CreatedAt, a.IsLive(now), a.ExpiresAt, Why(m.field));
}
// 4 and 5. The path rules and the path budgets.
counts["pathRule"] = await db.RequestRules.AsNoTracking()
.Where(r => EF.Functions.Like(r.Pattern, pattern, LikeEscape)
|| EF.Functions.Like(r.Note, pattern, LikeEscape))
.CountAsync(ct);
foreach (var r in await db.RequestRules.AsNoTracking()
.Where(r => EF.Functions.Like(r.Pattern, pattern, LikeEscape)
|| EF.Functions.Like(r.Note, pattern, LikeEscape))
.OrderByDescending(r => r.CreatedAt).Take(take).ToListAsync(ct))
{
var m = MatchedIn(asked, new (string?, string)[] { (r.Pattern, "pattern"), (r.Note, "note") });
Add("pathRule", r.Id, null, r.Pattern, m.text, r.CreatedAt, r.IsLive(now), r.ExpiresAt, Why(m.field));
}
counts["pathBudget"] = await db.RateRules.AsNoTracking()
.Where(r => EF.Functions.Like(r.Pattern, pattern, LikeEscape)
|| EF.Functions.Like(r.Note, pattern, LikeEscape))
.CountAsync(ct);
foreach (var r in await db.RateRules.AsNoTracking()
.Where(r => EF.Functions.Like(r.Pattern, pattern, LikeEscape)
|| EF.Functions.Like(r.Note, pattern, LikeEscape))
.OrderByDescending(r => r.CreatedAt).Take(take).ToListAsync(ct))
{
var m = MatchedIn(asked, new (string?, string)[] { (r.Pattern, "pattern"), (r.Note, "note") });
Add("pathBudget", r.Id, null, r.Pattern, m.text, r.CreatedAt, r.IsLive(now), r.ExpiresAt, Why(m.field));
}
// 6. The alerts. Their detail is the sentence this edge wrote itself,
// which is often the only place an incident was ever narrated.
counts["alert"] = await db.Alerts.AsNoTracking()
.Where(a => EF.Functions.Like(a.Kind, pattern, LikeEscape)
|| EF.Functions.Like(a.SourceKey, pattern, LikeEscape)
|| EF.Functions.Like(a.Detail, pattern, LikeEscape)
|| EF.Functions.Like(a.LastPath, pattern, LikeEscape))
.CountAsync(ct);
foreach (var a in await db.Alerts.AsNoTracking()
.Where(a => EF.Functions.Like(a.Kind, pattern, LikeEscape)
|| EF.Functions.Like(a.SourceKey, pattern, LikeEscape)
|| EF.Functions.Like(a.Detail, pattern, LikeEscape)
|| EF.Functions.Like(a.LastPath, pattern, LikeEscape))
.OrderByDescending(a => a.CreatedAt).Take(take).ToListAsync(ct))
{
var m = MatchedIn(asked, new (string?, string)[]
{ (a.Detail, "detail"), (a.Kind, "kind"), (a.SourceKey, "source key"), (a.LastPath, "last path") });
Add("alert", a.Id, a.SourceKey, null, m.text, a.CreatedAt, null, null, Why(m.field));
}
// 7. The operator's own change records — including the ones whose
// subject has since been deleted, which is what makes them worth
// searching: the row is gone, the sentence about it is not.
counts["change"] = await db.ConfigChanges.AsNoTracking()
.Where(c => EF.Functions.Like(c.Target, pattern, LikeEscape)
|| EF.Functions.Like(c.Detail, pattern, LikeEscape))
.CountAsync(ct);
foreach (var c in await db.ConfigChanges.AsNoTracking()
.Where(c => EF.Functions.Like(c.Target, pattern, LikeEscape)
|| EF.Functions.Like(c.Detail, pattern, LikeEscape))
.OrderByDescending(c => c.At).Take(take).ToListAsync(ct))
{
var m = MatchedIn(asked, new (string?, string)[] { (c.Target, "target"), (c.Detail, "detail") });
Add("change", c.Id, c.Target, null, m.text, c.At, null, null, Why(m.field));
}
// 8. The country rules. Their code is two characters, so the name is
// searched too — "Germany" is what an operator remembers, "DE" is what
// the row stores.
counts["countryRule"] = await db.CountryRules.AsNoTracking()
.Where(c => EF.Functions.Like(c.Code, pattern, LikeEscape)
|| EF.Functions.Like(c.Name, pattern, LikeEscape))
.CountAsync(ct);
foreach (var c in await db.CountryRules.AsNoTracking()
.Where(c => EF.Functions.Like(c.Code, pattern, LikeEscape)
|| EF.Functions.Like(c.Name, pattern, LikeEscape))
.OrderByDescending(c => c.UpdatedAt).Take(take).ToListAsync(ct))
{
var m = MatchedIn(asked, new (string?, string)[] { (c.Code, "code"), (c.Name, "name") });
Add("countryRule", null, c.Code, null, m.text, c.UpdatedAt, c.IsAllowed ? true : (bool?)null, null,
Why(m.field));
}
// The address bonus. A text search finds the rows that name the
// address; the rows that answer for it are the ones that cover it, and
// those never carry its number.
if (isAddress)
{
foreach (var b in await db.Blocks.AsNoTracking()
.Where(b => b.SourceKey == key)
.OrderByDescending(b => b.CreatedAt).Take(take).ToListAsync(ct))
if (Add("block", b.Id, b.SourceKey, null, b.Reason ?? b.LastPath, b.CreatedAt,
b.IsLive(now), b.ExpiresAt, $"this edge files {asked} under {key}"))
counts["block"]++;
foreach (var r in (await db.NetworkBans.AsNoTracking().ToListAsync(ct))
.Where(r => NetworkMatch.Matches(asked, r.Match)))
if (Add("range", r.Id, r.Match, null, r.Reason, r.CreatedAt, r.IsLive(now), r.ExpiresAt,
$"{r.Match} covers {asked}"))
counts["range"]++;
foreach (var a in (await db.AllowEntries.AsNoTracking().ToListAsync(ct))
.Where(a => NetworkMatch.Matches(asked, a.Match)))
if (Add("allow", a.Id, a.Match, null, a.Note, a.CreatedAt, a.IsLive(now), a.ExpiresAt,
$"{a.Match} covers {asked}"))
counts["allow"]++;
foreach (var c in (await db.ConfigChanges.AsNoTracking().ToListAsync(ct))
.Where(c => string.Equals(c.Target, asked, StringComparison.Ordinal)
|| string.Equals(c.Target, key, StringComparison.Ordinal)
|| NetworkMatch.Matches(asked, c.Target)))
if (Add("change", c.Id, c.Target, null, c.Detail, c.At, null, null,
$"a change to {c.Target}, which is this source or a range covering it"))
counts["change"]++;
}
// Newest first. This is a search, not a story: the row an operator
// wants is the one they wrote most recently. (/history reads oldest
// first because it narrates, and reading a story backwards turns "the
// exemption, then the ban" into the opposite. Neither default is wrong
// for the other question.)
hits.Sort((x, y) => y.At.CompareTo(x.At));
var shown = hits.Take(take).ToList();
var matched = counts.Values.Sum();
return Results.Ok(new
{
query = asked,
scope = "database",
matched,
shown = shown.Count,
limit = take,
truncated = matched > shown.Count,
counts,
matching = new
{
mode = "substring",
wildcardsEscaped = true,
note = "case-insensitive as the database does it, which is ASCII-only; the query's own "
+ "backslash, percent and underscore are searched as themselves"
},
asAddress = isAddress
? new
{
ip = asked,
sourceKey = key,
ipv4PrefixLength = policy.Ipv4KeyPrefixLength,
ipv6PrefixLength = policy.Ipv6KeyPrefixLength,
note = "the query is an address, so the answer also carries the rows that cover it "
+ "rather than name it"
}
: null,
results = shown,
note = matched == 0
? "nothing matched; `counts` names every store that was searched, so an empty answer is "
+ "an answer and not a surface that read nothing"
: "newest first; each row names the store it came from and the field that matched, or says "
+ "the row covers the queried address"
});
});
// What would this ban touch? (OPEN-75). The dry run answers one named
// request and the horizon answers what stops being enforced soon. Neither
// answers the question asked BEFORE the write, and both failures it
// prevents are silent: a /24 written over an office block refuses people
// who were never the target, and a range written inside an existing
// exemption refuses nobody at all — the operator sees 204 and moves on.
//
// The answer is not a second implementation of the pillar order. It is the
// real DecisionEngine run over a snapshot with the proposed entry added,
// over the sources this edge is actually watching inside the match — the
// same trick the horizon uses for "what answers afterwards", for the same
// reason: a preview that disagrees with the wire is worse than no preview.
group.MapGet("/impact", async (string? match, string? path, int? limit,
EdgeStateStore state, IGeoIpLookup geo, OpenWafDbContext db,
HttpContext ctx, CancellationToken ct) =>
{
if (!TryKnownQuery(ctx, out var unknown, "match", "path", "limit"))
return Results.BadRequest(new ErrorDto(unknown));
if (string.IsNullOrWhiteSpace(match))
return Results.BadRequest(new ErrorDto(
"match is required: an address or a CIDR, the same value the write takes"));
// Normalised by the write path's own code, so the preview answers
// about the row the write would create and refuses a match the write
// would refuse, in the write's words. 198.51.100.37/24 and
// 198.51.100.0/24 are one row, and a preview of a third spelling
// would be a preview of nothing.
if (!NetworkBans.TryNormalize(match.Trim(), out var normalized, out var inputError))
return Results.BadRequest(new ErrorDto(inputError));
var askedPath = string.IsNullOrWhiteSpace(path) ? "/" : path!.Trim();
if (!askedPath.StartsWith('/'))
return Results.BadRequest(new ErrorDto($"path must start with /; got \"{askedPath}\""));
var take = limit ?? ImpactDefaultLimit;
if (take < ImpactMinLimit || take > ImpactMaxLimit)
return Results.BadRequest(new ErrorDto($"limit must be {ImpactMinLimit}..{ImpactMaxLimit}; got {limit}"));
var now = DateTimeOffset.UtcNow;
var snapshot = state.GetOrRefresh();
var policy = snapshot.Policy;
var isRange = NetworkBans.IsRangeSyntax(normalized);
// The address that stands for a match. The network address of a
// network is inside it, so the engine can be asked about it, and a
// source key carries a prefix the engine cannot be asked with.
static string? ProbeOf(string? keyOrMatch)
{
if (string.IsNullOrWhiteSpace(keyOrMatch) || keyOrMatch == "*") return null;
var slash = keyOrMatch.IndexOf('/');
return slash < 0 ? keyOrMatch : keyOrMatch[..slash];
}
var probe = ProbeOf(normalized);
// The key the write would file it under, which for a bare address is
// this edge's group for it — with a /29 key, banning one address
// reaches the whole group, and the preview has to say so rather than
// answer about one address.
var key = SourceKey.For(probe ?? normalized, policy);
bool Inside(string? sourceKey)
{
var p = ProbeOf(sourceKey);
if (p is null) return false;
return isRange
? NetworkMatch.Matches(p, normalized)
: string.Equals(SourceKey.For(p, policy), key, StringComparison.Ordinal);
}
// The snapshot with the proposed entry added and nothing else
// changed. Nothing is written anywhere: this is the state the next
// request would be answered from if the operator pressed save, and
// the engine that reads it is the one on the wire.
var after = isRange
? snapshot with
{
OperatorRanges = new NetworkBanIndex(snapshot.OperatorRanges.Bans.Append(
new NetworkBan { Match = normalized, CreatedAt = now, Reason = "impact preview" }))
}
: snapshot with
{
OperatorBlocks = WithProposedBlock(snapshot.OperatorBlocks, new BlockEntry
{
SourceKey = key, Source = BlockSource.Operator, CreatedAt = now,
Reason = "impact preview"
})
};
// The sources to ask about: everything this edge is watching inside
// the match. An observation is a source it has seen; a streak is one
// it is counting right now, and that is the one an operator is about
// to ban. The match's own address is always asked, because "nothing
// has been seen inside this range" and "the preview did not look" are
// different answers.
var inside = new List<ImpactSource>();
var seen = new HashSet<string>(StringComparer.Ordinal);
foreach (var o in await db.Observations.AsNoTracking().ToListAsync(ct))
{
if (!Inside(o.SourceKey) || !seen.Add(o.SourceKey)) continue;
inside.Add(new ImpactSource(o.SourceKey, o.LastSeenAt, o.TotalRefusals,
o.MaxConsecutiveRefusals, "seen"));
}
foreach (var t in await db.Streaks.AsNoTracking().ToListAsync(ct))
{
if (!Inside(t.SourceKey) || !seen.Add(t.SourceKey)) continue;
inside.Add(new ImpactSource(t.SourceKey, t.LastSeenAt, t.TotalRefusals,
t.MaxConsecutiveRefusals, "standing streak"));
}
if (seen.Add(key))
inside.Add(new ImpactSource(key, now, 0, 0, "the match itself"));
inside.Sort((a, b) => b.LastSeenAt.CompareTo(a.LastSeenAt));
var probed = inside.Take(take).ToList();
var newlyRefused = 0;
var alreadyRefused = 0;
var stillPassing = 0;
var rows = new List<ImpactRow>();
foreach (var s in probed)
{
var p = ProbeOf(s.Key) ?? s.Key;
var country = policy.Geo == GeoMode.Off ? null : geo.Lookup(p);
var before = DecisionEngine.Decide(snapshot, p, askedPath, now, country);
var then = DecisionEngine.Decide(after, p, askedPath, now, country);
string change;
if (!before.IsBlocked && then.IsBlocked) { change = "newly refused"; newlyRefused++; }
else if (before.IsBlocked) { change = "already refused"; alreadyRefused++; }
else { change = "still passes"; stillPassing++; }
rows.Add(new ImpactRow(s.Key, s.Kind, s.LastSeenAt, s.Refusals, s.WorstRun,
EdgeVerdictLabel.For(before.Verdict), AnsweredBefore(before),
EdgeVerdictLabel.For(then.Verdict), AnsweredAfter(then), change));
}
// What already answers for the match's own address, and the live
// exemptions that outrank the write. An exemption is not a footnote
// here: it is the reason a ban can be written and refuse nobody, and
// the operator has to see it before the 204, not after the complaint.
var selfCountry = policy.Geo == GeoMode.Off ? null : geo.Lookup(probe ?? normalized);
var self = DecisionEngine.Decide(snapshot, probe ?? normalized, askedPath, now, selfCountry);
object? alreadyCoveredBy = self.IsBlocked
? new { verdict = EdgeVerdictLabel.For(self.Verdict), by = AnsweredBefore(self) }
: null;
var outranked = snapshot.AllowEntries
.Where(a => a.IsLive(now) && NetworkMatch.Matches(probe ?? normalized, a.Match))
.Select(a => (object)new { match = a.Match, note = a.Note, expiresAt = a.ExpiresAt })
.ToList();
var exemptionsInside = snapshot.AllowEntries
.Where(a => a.IsLive(now) && Inside(a.Match)
&& !NetworkMatch.Matches(probe ?? normalized, a.Match))
.Select(a => (object)new { match = a.Match, note = a.Note, expiresAt = a.ExpiresAt })
.ToList();
return Results.Ok(new
{
match = normalized,
kind = isRange ? "range" : "address",
filedUnder = key,
path = askedPath,
asOf = now,
scope = "snapshot+database",
probed = probed.Count,
limit = take,
truncated = inside.Count > probed.Count,
counts = new { newlyRefused, alreadyRefused, stillPassing },
wouldRefuse = newlyRefused > 0,
changesNothing = newlyRefused == 0,
alreadyCoveredBy,
// Live exemptions that cover the match's own address: the ban is
// written after them in the pillar order, so it does not reach
// this address at all.
outrankedBy = outranked,
exemptionsInside,
sources = rows,
note = newlyRefused == 0
? "this write would change nothing for any source this edge is watching inside the match; "
+ "outrankedBy names the exemptions that already answer there"
: $"{newlyRefused} source(s) this edge is watching inside the match would be refused by "
+ "this write and are not refused today; sources outside the match are not probed",
wrote = false
});
});
// The enforcement horizon (OPEN-72). Every dated entry this edge holds —
// an operator's block, a range, an engine ban, an exemption, a path rule, a
// path budget — stops answering on its own, and nothing anywhere shows what
// stops soon or what takes over when it does. The classic incident: an
// office inside a banned /28 gets a 60-minute exemption, the minute passes,
// the office is refused again, and the person who wrote the exemption no
// longer remembers the range underneath it.
//
// "What takes over" is not a second implementation of the pillar order. It
// is the real DecisionEngine run over a snapshot with exactly this one entry
// removed, so the answer cannot disagree with the wire.
group.MapGet("/expiring", async (int? within,
EdgeStateStore state, IGeoIpLookup geo, OpenWafDbContext db,
HttpContext ctx, CancellationToken ct) =>
{
if (!TryKnownQuery(ctx, out var unknown, "within")) return Results.BadRequest(new ErrorDto(unknown));
var minutes = within ?? HorizonDefaultMinutes;
if (minutes < HorizonMinMinutes || minutes > HorizonMaxMinutes)
return Results.BadRequest(new ErrorDto($"within must be {HorizonMinMinutes}..{HorizonMaxMinutes} minutes; got {minutes}"));
var now = DateTimeOffset.UtcNow;
var until = now.AddMinutes(minutes);
var snapshot = state.GetOrRefresh();
var policy = snapshot.Policy;
var blocks = await db.Blocks.AsNoTracking()
.Where(b => b.ExpiresAt != null && b.ExpiresAt > now && b.ExpiresAt <= until)
.ToListAsync(ct);
var liveRanges = await db.NetworkBans.AsNoTracking()
.Where(b => b.ExpiresAt == null || b.ExpiresAt > now)
.ToListAsync(ct);
var allows = await db.AllowEntries.AsNoTracking()
.Where(a => a.ExpiresAt != null && a.ExpiresAt > now && a.ExpiresAt <= until)
.ToListAsync(ct);
var rules = await db.RequestRules.AsNoTracking()
.Where(r => r.ExpiresAt != null && r.ExpiresAt > now && r.ExpiresAt <= until)
.ToListAsync(ct);
var budgets = await db.RateRules.AsNoTracking()
.Where(r => r.ExpiresAt != null && r.ExpiresAt > now && r.ExpiresAt <= until)
.ToListAsync(ct);
// The address to ask the engine about for a key or a match: the network
// address of the group is inside the group, so it is answered by it.
static string? ProbeOf(string? keyOrMatch)
{
if (string.IsNullOrWhiteSpace(keyOrMatch) || keyOrMatch == "*") return null;
var slash = keyOrMatch.IndexOf('/');
return slash < 0 ? keyOrMatch : keyOrMatch[..slash];
}
static EdgeSnapshot WithoutBlock(EdgeSnapshot s, string key, bool engine)
{
var kept = new Dictionary<string, BlockEntry>(StringComparer.Ordinal);
foreach (var kv in (engine ? s.EngineBans : s.OperatorBlocks))
if (!string.Equals(kv.Key, key, StringComparison.Ordinal)) kept[kv.Key] = kv.Value;
return s with { OperatorBlocks = engine ? s.OperatorBlocks : kept, EngineBans = engine ? kept : s.EngineBans };
}
EdgeSnapshot WithoutAllow(EdgeSnapshot s, long id)
=> s with { AllowEntries = s.AllowEntries.Where(a => a.Id != id).ToList() };
HorizonAfter? AnswersAfter(EdgeSnapshot after, string? probe)
{
if (probe is null) return null;
var country = policy.Geo == GeoMode.Off ? null : geo.Lookup(probe);
var d = DecisionEngine.Decide(after, probe, "/", now, country);
var by = d.Verdict switch
{
EdgeVerdict.PassAllowlisted => "an allow entry",
EdgeVerdict.BlockOperator => d.Range ?? d.SourceKey ?? "the operator's list",
EdgeVerdict.BlockEngine => d.SourceKey ?? "this edge's own ban",
EdgeVerdict.BlockRule => d.RulePattern is { } p ? $"path rule {p}" : d.Reason ?? "a path rule",
EdgeVerdict.PassRuleObserved => d.RulePattern is { } p2 ? $"path rule {p2} (observe)" : "a path rule",
EdgeVerdict.GeoReject => d.Reason ?? "the geo pillar",
EdgeVerdict.PassBypassed => "an always-pass prefix",
_ => "nothing"
};
return new HorizonAfter(
EdgeVerdictLabel.For(d.Verdict), d.IsBlocked, by,
d.IsBlocked
? $"when this entry ages out, this source is refused again by {by}"
: $"when this entry ages out, nothing else refuses this source");
}
const string PatternHasNoAnswer =
"a path rule and a path budget describe a set of paths, not one request: ask /admin-api/decide?ip=&path= for the path you care about";
var rows = new List<HorizonRow>();
foreach (var b in blocks.Where(b => b.Source == BlockSource.Operator))
rows.Add(new HorizonRow("block", b.Id, b.SourceKey, null, b.Reason, b.ExpiresAt!.Value,
MinutesUntil(b.ExpiresAt.Value, now),
AnswersAfter(WithoutBlock(snapshot, b.SourceKey, false), ProbeOf(b.SourceKey)), null));
foreach (var b in blocks.Where(b => b.Source != BlockSource.Operator))
rows.Add(new HorizonRow("engine ban", b.Id, b.SourceKey, null, b.Reason, b.ExpiresAt!.Value,
MinutesUntil(b.ExpiresAt.Value, now),
AnswersAfter(WithoutBlock(snapshot, b.SourceKey, true), ProbeOf(b.SourceKey)), null));
foreach (var r in liveRanges.Where(r => r.ExpiresAt != null && r.ExpiresAt > now && r.ExpiresAt <= until))
rows.Add(new HorizonRow("range", r.Id, r.Match, null, r.Reason, r.ExpiresAt!.Value,
MinutesUntil(r.ExpiresAt.Value, now),
AnswersAfter(snapshot with { OperatorRanges = new NetworkBanIndex(liveRanges.Where(x => x.Id != r.Id)) },
ProbeOf(r.Match)), null));
foreach (var a in allows)
rows.Add(new HorizonRow("allow", a.Id, a.Match, null, a.Note, a.ExpiresAt!.Value,
MinutesUntil(a.ExpiresAt.Value, now),
AnswersAfter(WithoutAllow(snapshot, a.Id), ProbeOf(a.Match)), null));
foreach (var r in rules)
rows.Add(new HorizonRow("path rule", r.Id, null, r.Pattern, r.Note, r.ExpiresAt!.Value,
MinutesUntil(r.ExpiresAt.Value, now), null, PatternHasNoAnswer));
foreach (var r in budgets)
rows.Add(new HorizonRow("path budget", r.Id, null, r.Pattern, r.Note, r.ExpiresAt!.Value,
MinutesUntil(r.ExpiresAt.Value, now), null, PatternHasNoAnswer));
// Nearest first: the entry an operator has to act on today is the one
// at the top of the list, not the one with the largest id.
rows.Sort((x, y) => x.ExpiresAt.CompareTo(y.ExpiresAt));
return Results.Ok(new
{
withinMinutes = minutes,
asOf = now,
scope = "database",
count = rows.Count,
expiring = rows,
// Dead rows stay in the tables — retention ages out engine bans and
// observations, an operator's own rows are not the machine's to
// delete — so "nothing expires soon" and "there are no dated
// entries" are different answers.
alreadyExpired = new
{
block = await db.Blocks.CountAsync(b => b.Source == BlockSource.Operator
&& b.ExpiresAt != null && b.ExpiresAt <= now, ct),
range = await db.NetworkBans.CountAsync(b => b.ExpiresAt != null && b.ExpiresAt <= now, ct),
engineBan = await db.Blocks.CountAsync(b => b.Source == BlockSource.Engine
&& b.ExpiresAt != null && b.ExpiresAt <= now, ct),
allow = await db.AllowEntries.CountAsync(a => a.ExpiresAt != null && a.ExpiresAt <= now, ct),
pathRule = await db.RequestRules.CountAsync(r => r.ExpiresAt != null && r.ExpiresAt <= now, ct),
pathBudget = await db.RateRules.CountAsync(r => r.ExpiresAt != null && r.ExpiresAt <= now, ct)
},
note = rows.Count == 0
? "nothing with an expiry stops being enforced inside this window; `alreadyExpired` says whether there are dated entries at all"
: "thenAnswers is the real DecisionEngine run over the state with only this entry removed; entries that never expire are not listed, and neither are entries expiring beyond this window"
});
});
// The record of deliberate changes to the operator's config (OPEN-64).
// Newest first, capped and paged like every other listing, and readable
// by the read-only token: it is a read, and a dashboard that can see the
// config should be able to see how it got there.
group.MapGet("/changes", async (string? section, DateTimeOffset? since, int? limit, int? offset,
OpenWafDbContext db, HttpContext ctx, CancellationToken ct) =>
{
if (!TryKnownQuery(ctx, out var unknown, "section", "since", "limit", "offset"))
return Results.BadRequest(new ErrorDto(unknown));
// An unknown section is answered by the vocabulary, not by an empty
// list: an empty list reads as "no such change happened", and the
// truth is "there is no such section".
if (!string.IsNullOrWhiteSpace(section) && !ConfigChangeLog.IsSection(section))
return Results.BadRequest(new ErrorDto($"section must be one of {string.Join(", ", ConfigChangeLog.Sections)}; got \"{section}\""));
if (!TryPaging(limit, offset, ReadListDefaultLimit, ReadListMaxLimit,
out var take, out var skip, out var pagingError))
return Results.BadRequest(new ErrorDto(pagingError));
var query = db.ConfigChanges.AsNoTracking();
if (!string.IsNullOrWhiteSpace(section)) query = query.Where(c => c.Section == section);
if (since is { } from) query = query.Where(c => c.At >= from);
var total = await query.CountAsync(ct);
// Ordered by id, not by the instant: two changes inside the same
// millisecond have an order, and the id is the one the database
// actually applied them in.
var rows = await query.OrderByDescending(c => c.Id).Skip(skip).Take(take).ToListAsync(ct);
ctx.Response.Headers["X-Total-Count"] = total.ToString();
ctx.Response.Headers["X-Truncated"] = (skip + rows.Count < total).ToString().ToLowerInvariant();
return Results.Ok(rows);
});
group.MapGet("/state", async (EdgeStateStore state, EdgePolicyProvider policyProvider, IStreakTracker tracker, RateTracker rateTracker, DurabilityHealth durability, BlockStore blockStore, AlertNotifier notifier, SchemaUpgradeReport schema, NetblockWatcher netblocks, OpenWafDbContext db, HttpContext ctx, CancellationToken ct) =>
{
if (!TryKnownQuery(ctx, out var unknown)) return Results.BadRequest(new ErrorDto(unknown));
var now = DateTimeOffset.UtcNow;
// The push queue read straight from the table: an operator at this
// page is asking now, and "how many alerts is the edge still trying
// to tell someone about" is the question that has an answer only in
// the rows (OPEN-60).
var pushQueue = await notifier.ReadCountsAsync(ct);
var allowLive = state.Current.AllowEntries.Count(a => a.IsLive(now));
var allowExpired = state.Current.AllowEntries.Count - allowLive;
return Results.Ok(new
{
// Whether this process has a second, read-only token at all
// (OPEN-62). It is here because the alternative is an operator
// guessing from a 401 whether the key they just wrote took effect.
readOnlyTokenConfigured = AdminTokenPolicy.IsConfigured(readOnlyToken),
snapshotAgeSeconds = Math.Round((DateTimeOffset.UtcNow - state.Current.GeneratedAt).TotalSeconds, 1),
// The age without the TTL it is measured against is half a number. On
// a single edge the TTL is invisible; behind a load balancer it *is*
// the propagation delay for a ban, so the page has to be able to say
// which value this process actually got (the key is validated at
// startup, 1-300 s, and /healthz reports it too).
snapshotTtlSeconds = Math.Round(state.RefreshTtl.TotalSeconds, 1),
trackedSources = tracker.TrackedCount,
operatorBlocks = state.Current.OperatorBlocks.Count,
// Ranges are counted apart because they are not comparable: one row
// here can be a thousand addresses, and a number that mixes them
// answers neither "how many things did I write" nor "how wide is it".
operatorRanges = state.Current.OperatorRanges.Count,
engineBans = state.Current.EngineBans.Count,
// The count of exemptions the engine is honouring, not the count of
// rows. Measured on the shipped image: one minute after the edge
// stopped obeying an allow entry (the request went from 502 back to
// 301), this number still said 1 and the listing still showed the
// row. Expired rows are kept on purpose — they are the operator's
// own writes — so they are counted separately rather than hidden.
allowEntries = allowLive,
allowEntriesExpired = allowExpired,
// Which of these numbers the storage actually confirmed. Both pillars
// keep their last good value when a read fails — the right failure
// posture — and both used to do it invisibly: one log line, a
// snapshot age that still looked fresh because the refresh "succeeded"
// at reading the tables that were still there, and /readyz saying
// ready. Measured on the shipped image with policy_settings dropped:
// /policy kept answering the operator's streakThreshold: 2, /state
// said snapshotAgeSeconds 0, /healthz and /readyz said 200, and after
// a restart the threshold was 10 again with nothing ever having said
// the number on screen was a copy.
snapshotStale = state.IsStale,
snapshotRefreshFailures = state.RefreshFailures,
snapshotLastRefreshError = state.LastRefreshError,
policyReloadFailures = policyProvider.ReloadFailures,
policyLastReadAt = policyProvider.LastReloadSuccessAt,
// The read side says whether what this edge is enforcing came from
// storage. The write side says whether what this edge saw ever
// reached storage — and it used to say nothing at all. Measured on
// the shipped image with SQLite triggers aborting every write to
// source_observations and edge_alerts while reads kept answering:
// /admin-api/observations held X-Total-Count: 4 across the break
// while three new sources were being refused, /admin-api/alerts
// held 1 row through a six-request 5xx storm, and the log carried
// "flush failed, 4 entries dropped" plus two "could not persist".
// EntriesLost is cumulative on purpose: a dropped row is not
// recovered by a later successful write.
// The enforcement-path write, counted separately because it gates
// readiness, unlike the reporting pillars below it.
// The change log (OPEN-64): how many records the edge holds, and
// whether the last ones actually landed. A change whose record did
// not land is a hole in the only answer the table exists to give.
configChanges = await db.ConfigChanges.CountAsync(ct),
changeWriteFailures = durability.Get(DurabilityHealth.Changes).Failures,
changesNotWritten = durability.Get(DurabilityHealth.Changes).EntriesLost,
changeLastWriteAt = durability.Get(DurabilityHealth.Changes).LastSuccessAt,
changeLastError = durability.Get(DurabilityHealth.Changes).LastError,
banWriteFailures = durability.Get(DurabilityHealth.Bans).Failures,
bansNotWritten = durability.Get(DurabilityHealth.Bans).EntriesLost,
banLastWriteError = durability.Get(DurabilityHealth.Bans).LastError,
banLastWriteAt = durability.Get(DurabilityHealth.Bans).LastSuccessAt,
// The two numbers that say what happens to a ban that failed to
// reach storage: how many are waiting to be written again, and how
// many expired before a retry could land. Without the first, a
// healed storage failure looks indistinguishable from a quiet site.
bansPendingRetry = blockStore.PendingBanRetries,
bansNeverEnforced = blockStore.BansNeverEnforced,
observationWriteFailures = durability.Get(DurabilityHealth.Observations).Failures,
observationsLost = durability.Get(DurabilityHealth.Observations).EntriesLost,
observationLastWriteError = durability.Get(DurabilityHealth.Observations).LastError,
observationLastWriteAt = durability.Get(DurabilityHealth.Observations).LastSuccessAt,
alertWriteFailures = durability.Get(DurabilityHealth.Alerts).Failures,
alertsLost = durability.Get(DurabilityHealth.Alerts).EntriesLost,
alertLastWriteError = durability.Get(DurabilityHealth.Alerts).LastError,
alertLastWriteAt = durability.Get(DurabilityHealth.Alerts).LastSuccessAt,
// Counted, and deliberately not a /readyz failure: a prune that
// cannot run keeps aggregates past the age they promise to age out
// at, which the operator has to be able to see, but it does not
// change what this edge enforces. See Program.cs.
// Whether alerts are pushed anywhere, and how the push is doing.
// The host rather than the URL: webhook URLs carry their secret in
// the path, and this response is rendered on a page.
alertWebhookConfigured = notifier.IsConfigured,
alertWebhookHost = notifier.WebhookHost,
alertWebhookFailures = durability.Get(AlertNotifier.Pillar).Failures,
alertWebhookLost = durability.Get(AlertNotifier.Pillar).EntriesLost,
alertWebhookDelivered = durability.Get(AlertNotifier.Pillar).EntriesWritten,
alertWebhookLastError = durability.Get(AlertNotifier.Pillar).LastError,
alertWebhookLastSuccessAt = durability.Get(AlertNotifier.Pillar).LastSuccessAt,
// The queue behind the push (OPEN-60). The counters above say how the
// attempts are going; these say what is still owed, and the difference
// between "the endpoint is down and we are still asking" and "we
// stopped asking" is the difference an operator acts on.
alertPushPending = pushQueue.Pending,
alertPushDelivered = pushQueue.Delivered,
alertPushGivenUp = pushQueue.GivenUp,
alertPushLastError = pushQueue.LastError,
alertPushOldestPendingAt = pushQueue.OldestPendingAt,
alertPushAttempts = pushQueue.Attempts,
retentionPruneFailures = durability.Get(DurabilityHealth.Retention).Failures,
retentionLastError = durability.Get(DurabilityHealth.Retention).LastError,
retentionLastPruneAt = durability.Get(DurabilityHealth.Retention).LastSuccessAt,
// The window itself, next to the counter that says whether it is
// running. "Nothing was pruned" and "nothing is due for 300 days"
// look identical without the number the promise is measured against.
// Which streak store this process registered, so the counts beside
// it can be read as one edge's or the fleet's (OPEN-52).
streakScope = policyProvider.Current.SharedStreaks ? "shared-database" : "this-process",
// Whether the rules pillar is reading anything at all. A database
// that predates the feature has every other table, and "no rules"
// and "the rules table is not there" have to be different answers.
requestRulesAvailable = state.RulesAvailable,
operatorRangesAvailable = state.RangesAvailable,
requestRulesError = state.RulesError,
// The per-path budgets (OPEN-68): how many are live in the snapshot
// the guard is actually holding, and whether that snapshot could read
// the table at all. A database that predates rate_rules answers "no
// budgets" the same way an operator who wrote none does, and only one
// of those is a problem.
rateRules = state.Current.RateRules.Count,
rateRulesAvailable = state.RateRulesAvailable,
rateRulesError = state.RateRulesError,
// The netblock watch (OPEN-67). Three answers, not one: whether the
// watch is switched on at all, what it last saw, and whether the scan
// that produced that number actually ran. "0 candidates" from a watch
// that is off, from one that failed and from one that genuinely found
// nothing are three different situations.
netblockCandidateBans = policyProvider.Current.NetblockCandidateBans,
netblockPrefixV4 = policyProvider.Current.NetblockPrefixV4,
netblockPrefixV6 = policyProvider.Current.NetblockPrefixV6,
netblockCandidates = netblocks.LastCandidates().Count,
netblockLastScanAt = netblocks.LastScanAt,
netblockScanError = netblocks.LastError,
// The schema this edge is serving against (OPEN-55). A database that
// predates a table used to be invisible: the pillar it needs answered
// as if there were nothing to see. These four fields say which step
// ran, what it had to add, and — the invariant — whether anything is
// still missing. Non-empty here names a pillar this build can run
// with no storage behind it.
schemaStrategy = schema.Strategy,
schemaTablesAdded = schema.TablesAdded,
schemaMigrationsBaselined = schema.MigrationsBaselined,
schemaMigrationsApplied = schema.MigrationsApplied,
schemaMissingTables = schema.MissingTables,
// The volume pillar (OPEN-56): what the budget is, and whether this
// process is counting anything. "No source is over budget" and "the
// pillar is off" look identical in a listing, and only one of them is
// a defence.
rateMode = state.Current.Policy.Rate.ToString(),
rateLimitPerWindow = state.Current.Policy.RateLimitPerWindow,
rateWindowSeconds = state.Current.Policy.RateWindow.TotalSeconds,
rateTrackedSources = rateTracker.TrackedCount,
// The change log's two bounds, printed on the table they apply to
// (OPEN-64), the same way the retention windows sit on theirs.
changeRetentionDays = (int)state.Current.Policy.ChangeRetention.TotalDays,
changeLogMaxRows = state.Current.Policy.ChangeLogMaxRows,
observationRetentionDays = (int)state.Current.Policy.ObservationRetention.TotalDays,
banRetentionDays = (int)state.Current.Policy.BanRetention.TotalDays,
mode = state.Current.Policy.Mode.ToString()
});
});
// The operator's config as one document (OPEN-61), on the same group so it
// carries the same token check and the same unknown-query rule.
MapConfigTransfer(group);
return app;
}
private const int AllowListDefaultLimit = 500;
private const int AllowListMaxLimit = 2000;
/// <summary>How many of a source's alerts the dossier returns. Five is the
/// shortest list that still shows whether an alert is a one-off or a run, and
/// the full listing is one call away with ?source=.
/// <summary>The dry run's answer in the words /decide uses, so the two
/// surfaces cannot name the same verdict differently. The volume part is the
/// same projection the preview makes, kept short: the dossier is a summary and
/// the full narration is one /decide call away.</summary>
private static object DescribeSourceVerdict(EdgeDecision decision, VolumeAnswer volume) => new
{
verdict = EdgeVerdictLabel.For(decision.Verdict),
blocked = decision.IsBlocked,
status = decision.StatusCode,
location = decision.Location,
reason = decision.Reason,
expiresAt = decision.ExpiresAt,
range = decision.Range,
rulePattern = decision.RulePattern,
volume = new
{
mode = volume.Mode,
scope = volume.Scope,
verdict = volume.Verdict,
reached = volume.Reached,
note = volume.Note
}
};
// One source through time (OPEN-73). Seven days is the default because that
// is how long the observations and alerts that make up most of a story are
// kept (OPEN-19); ninety is the ceiling because past the retention window the
// rows this joins are gone whatever the window says.
private const int HistoryDefaultMinutes = 10080;
private const int HistoryMinMinutes = 1;
private const int HistoryMaxMinutes = 129600;
private const int HistoryDefaultLimit = 200;
private const int HistoryMinLimit = 1;
private const int HistoryMaxLimit = 2000;
// What would this ban touch? (OPEN-75). Fifty sources is the default because
// that is more than an operator can read at once, and two hundred is the
// ceiling because past that the preview is a report, not a decision aid.
private const int ImpactDefaultLimit = 50;
private const int ImpactMinLimit = 1;
private const int ImpactMaxLimit = 200;
// Where does this appear? (OPEN-74). Two characters is the floor because a
// one-character search is a dump of every store rather than an answer; 128 is
// the ceiling because it is the longest target the change log stores, so a
// longer query cannot match the thing it was aimed at.
private const int SearchMinQueryLength = 2;
private const int SearchMaxQueryLength = 128;
private const int SearchDefaultLimit = 100;
private const int SearchMinLimit = 1;
private const int SearchMaxLimit = 500;
// LIKE's escape character. These stores are operator prose — reasons, notes,
// alert details — and prose carries percents and underscores, so the query is
// escaped instead of being handed to LIKE as grammar.
private const string LikeEscape = "\\";
private static readonly string[] SearchStoreNames =
["block", "range", "allow", "pathRule", "pathBudget", "alert", "change", "countryRule"];
/// <summary>Escape LIKE's wildcards. The escape character itself goes first,
/// or the escapes the other two add would be escaped by the next pass.</summary>
private static string EscapeLikeWildcards(string value)
=> value.Replace("\\", "\\\\").Replace("%", "\\%").Replace("_", "\\_");
// The enforcement horizon (OPEN-72). A day is the ceiling because that is the
// longest thing an operator plans for; asking for a year would turn a horizon
// into a dump of every dated row.
private const int HorizonDefaultMinutes = 30;
private const int HorizonMinMinutes = 1;
private const int HorizonMaxMinutes = 1440;
/// <summary>Whole minutes until an entry stops being enforced, never negative:
/// an entry inside the window is at least one minute away by the filter that
/// selected it, and "-4" would read as a clock error.</summary>
private static int MinutesUntil(DateTimeOffset expiresAt, DateTimeOffset now)
=> Math.Max(0, (int)Math.Ceiling((expiresAt - now).TotalMinutes));
private const int DossierAlertLimit = 5;
/// <summary>Whole seconds left in a window, never negative: a window that has
/// run out has nothing left, and "-3" would read as a clock error.</summary>
private static int SecondsLeft(DateTimeOffset windowEnd, DateTimeOffset now)
=> Math.Max(0, (int)Math.Ceiling((windowEnd - now).TotalSeconds));
private const int ReadListDefaultLimit = 100;
private const int ReadListMaxLimit = 1000;
private const int StreakListDefaultLimit = 50;
private const int StreakListMaxLimit = 1000;
/// <summary>
/// A capped listing has two honest answers to a limit outside the cap:
/// refuse it, or answer with what the response itself says is missing. The
/// shipped image gave neither. Math.Clamp turned ?limit=0 and ?limit=-1 into
/// one row and ?limit=100000 into 1000 rows of 1103 observations — every one
/// a 200 that read like a complete answer, on the endpoint the console uses
/// to decide which sources the edge has actually seen. So the range is
/// refused by name, and every capped listing now carries X-Total-Count and
/// X-Truncated plus an offset that reaches the rest.
/// </summary>
/// <summary>
/// A country rule is matched against the two-letter code the geo database
/// returns, so a code made of any other two characters can never match
/// anything. The shipped image only checked the length: PUT
/// /admin-api/countries/12?allowed=false answered 204, GET /countries listed
/// "12: denied", and a source from the busiest country still got through —
/// the operator's table said a country was denied while the engine enforced
/// nothing. And there was no DELETE, so the row was permanent.
/// </summary>
private static bool TryCountryCode(string? raw, out string code, out string? error)
{
code = (raw ?? string.Empty).Trim().ToUpperInvariant();
error = null;
if (code.Length == 2 && char.IsAsciiLetter(code[0]) && char.IsAsciiLetter(code[1])) return true;
error = $"code must be a two-letter ISO country code; got \"{raw}\"";
return false;
}
/// <summary>
/// The one predicate that says whether an allow row is in force, written once
/// so the listing, the count behind X-Total-Count and the number in /state
/// cannot drift apart. AllowEntry.IsLive is the engine's own answer; this is
/// the same rule in the form EF can translate.
/// </summary>
private static IQueryable<OpenWaf.Domain.Security.AllowEntry> FilterAllow(
IQueryable<OpenWaf.Domain.Security.AllowEntry> query, bool liveOnly, DateTimeOffset now)
=> liveOnly ? query.Where(a => a.ExpiresAt == null || a.ExpiresAt > now) : query;
/// <summary>
/// Does this endpoint know the query parameters it was sent?
///
/// Measured on the shipped image before this existed: `GET
/// /admin-api/observations?source=203.0.113.11` answered 200 with every row
/// in the table and `X-Total-Count: 16` — the filter was not applied, not
/// refused, just absent, so an operator investigating one address was shown
/// fifteen other addresses and a total that matched them. The same held for
/// `?src=`, `?zzz=` and any other spelling on every list endpoint: minimal
/// APIs bind the parameters they know and drop the rest without a trace.
/// A parameter this endpoint has never heard of is now an answer that says
/// so and names what it does accept, because a silently dropped filter is
/// the same shape as the bug OPEN-23 found one level up, where an unknown
/// `?source=` VALUE meant "operator".
///
/// The write endpoints are the half that mattered. Measured on the shipped
/// image right after the GET guard landed: POST /blocks?zzz=1 answered 204
/// and wrote the ban, PUT /policy?zzz=1 answered 200 and changed the policy,
/// PUT /countries/DE?allowed=true&zzz=1 answered 204, DELETE
/// /blocks?key=…&zzz=1 answered 200 {"deleted":1}, and GET /countries?limit=2
/// returned every row. Same request shape, two answers depending on the
/// verb — and the silent half was the one that changes state, where a
/// misspelled scoping parameter acts with a wider scope than the caller
/// meant. The refusal also runs before any state change, so a rejected write
/// cannot half-happen.
///
/// `allowed` is the whole parameter surface of THAT endpoint, written out by
/// the caller, and the base set is only `token`. Assuming limit/offset for
/// every endpoint is the same bug one level down: measured on the image that
/// already carried the GET guard, `GET /admin-api/countries?limit=2` answered
/// 200 with all 3 rows, because that listing has no paging to honour and a
/// guard that guesses the surface accepts a parameter the endpoint never
/// implemented. A refusal that lists the truth for the endpoint is only true
/// if the guard knows the truth for the endpoint.
/// </summary>
/// <summary>Is this string an address, or a typo shaped like one?
///
/// <see cref="System.Net.IPAddress.TryParse"/> alone is not enough: it accepts
/// abbreviated IPv4, so "203.0.113" parses as 203.0.113.0. On a preview that
/// is the exact failure this guard exists to catch — an operator missing one
/// octet gets "pass" for an address that is not the one they meant, and the
/// whole value of the surface is that its answer is about a named request.
/// </summary>
/// <summary>The snapshot's operator blocks plus the one this preview is
/// asking about, without touching the snapshot itself (OPEN-75). The
/// proposed row replaces whatever the operator already has on that key, which
/// is what the write would do — POST on an existing key updates the row.</summary>
private static IReadOnlyDictionary<string, BlockEntry> WithProposedBlock(
IReadOnlyDictionary<string, BlockEntry> existing, BlockEntry proposed)
{
var copy = new Dictionary<string, BlockEntry>(StringComparer.Ordinal);
foreach (var kv in existing) copy[kv.Key] = kv.Value;
copy[proposed.SourceKey] = proposed;
return copy;
}
/// <summary>What answers for a source today. Named from the decision the
/// engine returned, never re-derived: the row that refused it is the thing an
/// operator goes looking for in the listings.</summary>
private static string? AnsweredBefore(OpenWaf.Domain.Engine.EdgeDecision d) => d.Verdict switch
{
OpenWaf.Domain.Engine.EdgeVerdict.BlockOperator => d.Range ?? d.SourceKey ?? "the operator's list",
OpenWaf.Domain.Engine.EdgeVerdict.BlockEngine => d.SourceKey ?? "this edge's own ban",
OpenWaf.Domain.Engine.EdgeVerdict.BlockRule => d.RulePattern is { } p ? $"path rule {p}" : d.Reason ?? "a path rule",
OpenWaf.Domain.Engine.EdgeVerdict.GeoReject => d.Reason ?? "a country rule",
_ => null
};
/// <summary>What answers for a source once the proposed entry is in place.
/// A pass is answered too, because "still passes, and this exemption is why"
/// is the sentence that tells an operator their ban will do nothing.</summary>
private static string? AnsweredAfter(OpenWaf.Domain.Engine.EdgeDecision d) => d.Verdict switch
{
OpenWaf.Domain.Engine.EdgeVerdict.PassAllowlisted => "an allow entry",
OpenWaf.Domain.Engine.EdgeVerdict.PassBypassed => "an always-pass path",
OpenWaf.Domain.Engine.EdgeVerdict.BlockOperator => d.Range ?? d.SourceKey ?? "the operator's list",
OpenWaf.Domain.Engine.EdgeVerdict.BlockEngine => d.SourceKey ?? "this edge's own ban",
OpenWaf.Domain.Engine.EdgeVerdict.BlockRule => d.RulePattern is { } p2 ? $"path rule {p2}" : d.Reason ?? "a path rule",
OpenWaf.Domain.Engine.EdgeVerdict.GeoReject => d.Reason ?? "a country rule",
_ => null
};
private static bool IsAnAddress(string value)
{
if (!System.Net.IPAddress.TryParse(value, out var parsed)) return false;
if (parsed.AddressFamily == System.Net.Sockets.AddressFamily.InterNetworkV6) return true;
return value.Split('.').Length == 4;
}
private static bool TryKnownQuery(HttpContext ctx, out string? error, params string[] allowed)
{
// `token` is not a handler parameter — the admin auth layer reads it out
// of the query string, and OPEN-16 ruled that the curl-friendly form
// stays supported while the console never uses it. A guard that does not
// know the whole surface refuses a request that works, which is a worse
// bug than the one it prevents: three existing integration tests call
// /admin-api/blocks?token=… and were right to.
var known = new HashSet<string>(StringComparer.OrdinalIgnoreCase) { "token" };
foreach (var extra in allowed) known.Add(extra);
error = null;
foreach (var key in ctx.Request.Query.Keys)
{
if (!known.Contains(key))
{
var accepts = string.Join(", ", known.OrderBy(k => k, StringComparer.Ordinal));
error = $"unknown query parameter '{key}'; this endpoint accepts {accepts}";
return false;
}
}
return true;
}
private static bool TryPaging(int? limit, int? offset, int defaultLimit, int maxLimit,
out int take, out int skip, out string? error)
{
take = limit ?? defaultLimit;
skip = offset ?? 0;
error = null;
if (limit is < 1 || limit > maxLimit)
{
error = $"limit must be 1..{maxLimit}; got {limit}";
return false;
}
if (offset is < 0)
{
error = $"offset must be 0 or more; got {offset}";
return false;
}
return true;
}
/// <summary>
/// The one place that says no to a policy value, and says it with the key
/// and the range so the operator can fix the call rather than guess which
/// field was dropped. Returns null when every present field is usable.
/// </summary>
private static string? PolicyProblem(PolicyUpdateRequest req)
{
if (req.StreakThreshold is { } n && !PolicyBounds.StreakThresholdOk(n))
return $"streakThreshold must be {PolicyBounds.RangeOf("streakThreshold")}; got {n}";
if (req.StreakWindowMinutes is { } m && !PolicyBounds.StreakWindowMinutesOk(m))
return $"streakWindowMinutes must be {PolicyBounds.RangeOf("streakWindowMinutes")}; got {m}";
if (req.BanDurationMinutes is { } b && !PolicyBounds.BanDurationMinutesOk(b))
return $"banDurationMinutes must be {PolicyBounds.RangeOf("banDurationMinutes")}; got {b}";
if (req.RateLimitPerWindow is { } rl && !PolicyBounds.RateLimitPerWindowOk(rl))
return $"rateLimitPerWindow must be {PolicyBounds.RangeOf("rateLimitPerWindow")}; got {rl}";
if (req.RateWindowSeconds is { } rw && !PolicyBounds.RateWindowSecondsOk(rw))
return $"rateWindowSeconds must be {PolicyBounds.RangeOf("rateWindowSeconds")}; got {rw}";
if (req.MaxTrackedSources is { } t && !PolicyBounds.MaxTrackedSourcesOk(t))
return $"maxTrackedSources must be {PolicyBounds.RangeOf("maxTrackedSources")}; got {t}";
if (req.Ipv4KeyPrefixLength is { } v4 && !PolicyBounds.Ipv4KeyPrefixLengthOk(v4))
return $"ipv4KeyPrefixLength must be {PolicyBounds.RangeOf("ipv4KeyPrefixLength")}; got {v4}";
if (req.Ipv6KeyPrefixLength is { } v6 && !PolicyBounds.Ipv6KeyPrefixLengthOk(v6))
return $"ipv6KeyPrefixLength must be {PolicyBounds.RangeOf("ipv6KeyPrefixLength")}; got {v6}";
if (req.EngineBlockStatus is { } e && !PolicyBounds.EngineBlockStatusOk(e))
return $"engineBlockStatus must be {PolicyBounds.RangeOf("engineBlockStatus")}; got {e}";
if (req.OperatorBlockStatus is { } o && !PolicyBounds.OperatorBlockStatusOk(o))
return $"operatorBlockStatus must be {PolicyBounds.RangeOf("operatorBlockStatus")}; got {o}";
if (req.NetblockCandidateBans is { } ncb && !PolicyBounds.NetblockCandidateBansOk(ncb))
return $"netblockCandidateBans must be {PolicyBounds.RangeOf("netblockCandidateBans")}; got {ncb}";
if (req.NetblockPrefixV4 is { } np4 && !PolicyBounds.NetblockPrefixV4Ok(np4))
return $"netblockPrefixV4 must be {PolicyBounds.RangeOf("netblockPrefixV4")}; got {np4}";
if (req.NetblockPrefixV6 is { } np6 && !PolicyBounds.NetblockPrefixV6Ok(np6))
return $"netblockPrefixV6 must be {PolicyBounds.RangeOf("netblockPrefixV6")}; got {np6}";
if (req.RefusalRange is not null && !StatusRangeUsable(req.RefusalRange))
return $"refusalRange must be {PolicyBounds.RangeOf("refusalRange")}; got \"{req.RefusalRange}\"";
if (req.ServerErrorRange is not null && !StatusRangeUsable(req.ServerErrorRange))
return $"serverErrorRange must be {PolicyBounds.RangeOf("serverErrorRange")}; got \"{req.ServerErrorRange}\"";
if (req.DefaultRedirectTargets is { Length: > 0 })
{
foreach (var target in req.DefaultRedirectTargets)
{
if (!RedirectTarget.IsSendable(target))
return $"redirectTargets must be absolute http(s) URLs; got \"{target}\"";
}
}
return null;
}
/// <summary>A range that classifies nothing is a pillar switched off by a
/// typo, so it is refused rather than stored.</summary>
private static bool StatusRangeUsable(string value)
=> StatusRange.TryParse(value, out var range)
&& range.Low >= PolicyBounds.ClassifiableStatusMin
&& range.High <= PolicyBounds.ClassifiableStatusMax;
private static PolicyDto ToDto(EdgePolicy p) => new(
p.Mode.ToString(), p.StreakThreshold, p.StreakWindow.TotalMinutes, p.BanDuration.TotalMinutes,
p.RefusalRange.ToString(), p.ServerErrorRange.ToString(), p.Geo.ToString(), p.TrustProxyHeaders,
p.MaxTrackedSources, p.Ipv4KeyPrefixLength, p.Ipv6KeyPrefixLength, p.EngineBlockStatus,
p.OperatorBlockStatus, p.DefaultRedirectTargets,
(int)p.ObservationRetention.TotalDays, (int)p.BanRetention.TotalDays,
p.Rate.ToString(), p.RateLimitPerWindow, p.RateWindow.TotalSeconds,
p.NetblockCandidateBans, p.NetblockPrefixV4, p.NetblockPrefixV6);
/// <summary>
/// The provenance filter, parsed honestly. The old shape mapped any unrecognised
/// string to <c>BlockSource.Operator</c>, measured on the shipped image: with two
/// operator blocks and three engine bans live, <c>GET ?source=enigne</c> returned
/// the operator list and hid the engine bans, and
/// <c>DELETE ?source=enigne</c> answered <c>{"deleted":1}</c> and left
/// <c>operator=0 engine=3</c> — the caller who mistyped "engine" while clearing
/// automatic bans erased the operator's own list instead, which is the exact
/// failure the comment above that endpoint says this API exists to prevent. A
/// missing source is still "all"; a misspelled one is a 400.
/// </summary>
private static bool TryParseSource(string? source, out BlockSource? parsed)
{
switch (source?.Trim().ToLowerInvariant())
{
case null or "" or "all": parsed = null; return true;
case "operator": parsed = BlockSource.Operator; return true;
case "engine": parsed = BlockSource.Engine; return true;
default: parsed = null; return false;
}
}
private static IResult BadSource(string? source)
=> Results.BadRequest(new ErrorDto($"source must be operator|engine|all; got \"{source}\""));
/// <summary>
/// The answer for "the storage could not do this". 503, not 400: the
/// request was fine. 503, not 200: nothing happened. The body keeps the
/// <c>error</c> shape the console already renders, so the operator sees the
/// sentence rather than an empty 5xx.
/// </summary>
private static IResult StorageUnavailable(string error)
=> Results.Json(new ErrorDto(error), statusCode: StatusCodes.Status503ServiceUnavailable);
private static bool IsValidMatch(string match)
{
if (match.Contains('/')) return NetworkMatch.Matches("203.0.113.1", match) || match.Split('/')[1].Length <= 3;
return SourceKey.TryParse(match, out _, out _);
}
}
/// <summary>One dated entry that stops being enforced inside the horizon, and —
/// for the address-shaped kinds — what answers once it is gone.</summary>
/// <summary>One moment in one source's story (OPEN-73). `InForce` is null for the
/// kinds that are events rather than states — an alert, a change record, a
/// sighting — because "is it in force" is not a question they answer; a `false`
/// there would say the alert was switched off.</summary>
internal sealed record HistoryEvent(
DateTimeOffset At,
string Kind,
string What,
string? Detail,
bool? InForce,
DateTimeOffset? ExpiresAt,
string? Match,
long? Id);
internal sealed record HorizonRow(
string Kind,
long Id,
string? Match,
string? Pattern,
string? Note,
DateTimeOffset ExpiresAt,
int MinutesLeft,
HorizonAfter? ThenAnswers,
string? WhyNoAnswer);
/// <summary>The verdict the edge would give this source with only the named entry
/// removed, in the words the log and the dry run use.</summary>
internal sealed record HorizonAfter(
string Verdict,
bool WouldBeRefused,
string By,
string Note);
/// <summary>One row that matched the search (OPEN-74), carrying the store it came
/// from and the field that held the text, so a hit in a block's reason is not
/// mistaken for a hit on a path rule's pattern. `Live` is null for the stores that
/// are events rather than states — an alert, a change record — because "is it in
/// force" is not a question they answer; a `false` there would say the row was
/// switched off. `Why` is the reason the row is in the answer at all: a field name
/// for a text match, a sentence for a row that is here because it covers the
/// queried address.</summary>
internal sealed record SearchHit(
string Store,
long? Id,
string? Match,
string? Pattern,
string? Text,
DateTimeOffset At,
bool? Live,
DateTimeOffset? ExpiresAt,
string Why);
/// <summary>A source this edge is watching that falls inside the proposed match
/// (OPEN-75). `Kind` says where it came from: an observation is a source the edge
/// has seen, a standing streak is one it is counting right now, and the match's
/// own address is always asked so an empty answer is not mistaken for an
/// unanswered one.</summary>
internal sealed record ImpactSource(
string Key,
DateTimeOffset LastSeenAt,
int Refusals,
int WorstRun,
string Kind);
/// <summary>The same source answered twice: what the edge says today, and what it
/// would say with the proposed entry in the snapshot. `Change` is the whole point
/// of the surface — newly refused, already refused by something else, or still
/// passing because something outranks the ban.</summary>
internal sealed record ImpactRow(
string Source,
string Kind,
DateTimeOffset LastSeenAt,
int Refusals,
int WorstRun,
string Before,
string? BeforeBy,
string After,
string? AfterBy,
string Change);