Files
openwaf/dotnet/OpenWaf.Edge/Admin/AdminEndpoints.cs
T
Pavlo Ratushnyi 39d08eca51 A pillar that stopped reading its table kept answering, and nothing on the surface said so
Measured on the shipped image (openwaf:ci, the head tree), one stand with a real
upstream:

  PUT /admin-api/policy {"streakThreshold":2,"trustProxyHeaders":true} -> 200
  404 404 from 203.0.113.79, third request -> 403   (the threshold is in force)
  04:44:43  DROP TABLE policy_settings, from outside the process
  04:45:2x  GET /admin-api/policy -> still "streakThreshold": 2, answered plainly
            GET /admin-api/state  -> "snapshotAgeSeconds":0 — the refresh "succeeded",
                                     because the tables it also reads were still there
            /healthz 200, /readyz 200, and exactly 1 line in the log
  docker restart -> GET /admin-api/policy -> "streakThreshold": 10,
                                          "trustProxyHeaders": false
  four 404s from 203.0.113.81, fifth -> 404: nothing banned

Both pillars — the policy provider and the guard's snapshot store — catch
everything their read throws, keep the last value they had, and log one line.
Keeping the last good value is the right failure posture: a database restart must
not open the gate. Keeping it unmentioned is not: for a minute the operator's page
showed a threshold that no longer existed anywhere in storage, readiness said
ready, and after a restart the defence silently came back at the default N=10.

Now: EdgePolicyProvider and EdgeStateStore count consecutive failed reads and keep
the last error; /admin-api/state answers snapshotStale (age against the TTL the
process refuses to start without), snapshotRefreshFailures,
snapshotLastRefreshError, policyReloadFailures and policyLastReadAt;
/admin-api/policy carries X-Policy-Reload-Failures and X-Policy-Last-Read
alongside the policy it is enforcing, the same way a capped listing carries its
completeness in headers; /readyz answers 503 while either counter is non-zero,
naming the pillar and the age of the snapshot it is running on; and the console's
summary line goes warn and says "older than the ttl", "snapshot refresh failing
xN", "policy not re-read from storage xN".

Teeth first: PillarFailureVisibilityTests (4) run against the unfixed tree — 4
failed, 0 passed, all four on a missing field (KeyNotFoundException), which is the
point: the numbers did not exist. The refresh test drops country_rules rather than
block_entries on purpose — only one of them is what /readyz probes, so before the
fix that test saw the refresh failing and readiness still answering 200.

Gates: compose-smoke now drops policy_settings from the running stand through a
--volumes-from sidecar, waits for the failure to be counted, asserts the counters,
the 503 and the header, puts the table back and asserts the recovery (+6
assertions; the counters are consecutive, not cumulative, so recovery is part of
the claim). smoke.sh asserts the healthy case with numbers rather than silence
(+3). console-check drives the page against that state answer and requires the
summary line to be marked and to name both pillars (+3); the state body is served
through a route because the guard refreshes the snapshot on every request — a live
stand cannot be left to age — while the contract being rendered is the one
compose-smoke measures end to end against the shipped image.

Numbers on this tree. Host: build 0 warnings, unit 128/128, integration 117/117,
smoke 25 passed / 0 failed, compose 53 passed / 0 failed, console 53 assertions /
0 failed, image 261 MB. Linux rehearsal, each stage on its own — source in
mcr.microsoft.com/dotnet/sdk:10.0 (Ubuntu 24.04.5, SDK 10.0.401): 128/128,
117/117, 25/0; compose in docker:cli: 53/0, enforcement lag 12 ms; console in
mcr.microsoft.com/playwright:v1.63.0-noble: 53/0.
2026-10-02 07:07:25 +02:00

615 lines
36 KiB
C#

using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using OpenWaf.Domain.Engine;
using OpenWaf.Domain.Policy;
using OpenWaf.Domain.Security;
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 class AdminEndpoints
{
public static IEndpointRouteBuilder MapAdminApi(this IEndpointRouteBuilder app, string? adminToken)
{
var group = app.MapGroup("/admin-api");
// No token configured means the admin surface is closed, not open
// without auth. An edge that can ban people must not itself be the
// easiest way to ban everyone.
group.AddEndpointFilter(async (filterCtx, next) =>
{
if (string.IsNullOrWhiteSpace(adminToken))
return Results.NotFound(new { error = "admin api disabled: set OpenWaf__Admin__Token" });
var req = filterCtx.HttpContext.Request;
var provided = req.Headers["X-Admin-Token"].ToString();
var viaQuery = false;
if (string.IsNullOrWhiteSpace(provided))
{
provided = req.Query["token"].ToString();
viaQuery = !string.IsNullOrWhiteSpace(provided);
}
if (!FixedTimeEquals(provided, adminToken)) return Results.Unauthorized();
// The query string is accepted for one reason: an operator typing
// curl at a keyboard does it without thinking, and refusing them is
// how an operator ends up disabling the auth instead of learning the
// header. What is NOT acceptable is doing it silently. A URL is the
// one part of a request that every access log, proxy log and browser
// history keeps, and at the shipped log level the edge does not log
// URLs - but raising Microsoft.AspNetCore to Information, which is
// the ordinary next move when something is misbehaving, makes
// Kestrel log the full URL including this token. Measured on the
// shipped image: one query-string request leaves 0 lines containing
// the token at the shipped level and 2 at Information ("Request
// starting" and "Request finished"), and a header request leaves 0
// at either. So the request is served and the moment it happens is
// named, without ever repeating the secret.
if (viaQuery)
{
filterCtx.HttpContext.RequestServices
.GetRequiredService<ILoggerFactory>()
.CreateLogger("OpenWaf.Admin")
.LogWarning(
"admin token was presented in the query string on {Path}; URLs are what access logs, " +
"proxies and browser histories keep, so prefer the X-Admin-Token header. The token is " +
"not repeated here.",
req.Path.Value);
}
return await next(filterCtx);
});
group.MapGet("/blocks", async (string? source, bool? live, int? limit, int? offset, BlockStore store, HttpContext ctx, CancellationToken ct) =>
{
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 { error = 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, CancellationToken ct) =>
{
if (string.IsNullOrWhiteSpace(req.Ip)) return Results.BadRequest(new { error = "ip is required" });
if (!EntryLimits.NoteOk(req.Reason))
return Results.BadRequest(new { error = $"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 { error = $"redirectTo must be an absolute http(s) URL with no spaces or control characters; got \"{req.RedirectTo}\"" });
var (added, error) = await store.AddOperatorAsync(req.Ip, req.Reason, req.RedirectTo, DateTimeOffset.UtcNow, ct);
// 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.
return added switch
{
BlockStore.AddResult.Ok => Results.NoContent(),
BlockStore.AddResult.InvalidInput => Results.BadRequest(new { error }),
_ => StorageUnavailable(error!)
};
});
// 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, CancellationToken ct) =>
{
if (!TryParseSource(source, out var parsed)) return BadSource(source);
if (parsed is null && string.IsNullOrWhiteSpace(key))
return Results.BadRequest(new { error = "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");
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 (!TryPaging(limit, offset, AllowListDefaultLimit, AllowListMaxLimit,
out var take, out var skip, out var pagingError))
return Results.BadRequest(new { error = 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, CancellationToken ct) =>
{
if (string.IsNullOrWhiteSpace(req.Match) || !IsValidMatch(req.Match))
return Results.BadRequest(new { error = "match must be an address or CIDR" });
if (!EntryLimits.NoteOk(req.Note))
return Results.BadRequest(new { error = $"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 { error = $"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 { error = "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);
return Results.NoContent();
});
group.MapDelete("/allow/{id:long}", async (long id, OpenWafDbContext db, EdgeStateStore state, CancellationToken ct) =>
{
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.
return n > 0
? Results.NoContent()
: Results.NotFound(new { error = $"no allow entry with id {id}" });
});
// 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) =>
{
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, CancellationToken ct) =>
{
var overrides = new Dictionary<string, string?>();
if (req.Mode is not null)
{
if (!Enum.TryParse<EnforcementMode>(req.Mode, true, out var mode))
return Results.BadRequest(new { error = $"mode must be one of {string.Join('|', Enum.GetNames<EnforcementMode>())}" });
overrides["mode"] = mode.ToString();
}
if (req.Geo is not null)
{
if (!Enum.TryParse<GeoMode>(req.Geo, true, out var geo))
return Results.BadRequest(new { error = "geo must be Off|DenyList|AllowList" });
overrides["geo"] = geo.ToString();
}
// 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.
var problem = PolicyProblem(req);
if (problem is not null) return Results.BadRequest(new { error = problem });
if (req.StreakThreshold is { } streakThreshold) overrides["streakThreshold"] = streakThreshold.ToString();
if (req.StreakWindowMinutes is { } windowMinutes) overrides["streakWindowMinutes"] = windowMinutes.ToString();
if (req.BanDurationMinutes is { } banMinutes) overrides["banDurationMinutes"] = banMinutes.ToString();
if (req.RefusalRange is not null) overrides["refusalRange"] = req.RefusalRange.Trim();
if (req.ServerErrorRange is not null) overrides["serverErrorRange"] = req.ServerErrorRange.Trim();
if (req.TrustProxyHeaders is not null) overrides["trustProxyHeaders"] = req.TrustProxyHeaders.Value.ToString().ToLowerInvariant();
if (req.MaxTrackedSources is { } maxSources) overrides["maxTrackedSources"] = maxSources.ToString();
if (req.Ipv4KeyPrefixLength is { } v4) overrides["ipv4KeyPrefixLength"] = v4.ToString();
if (req.Ipv6KeyPrefixLength is { } v6) overrides["ipv6KeyPrefixLength"] = v6.ToString();
if (req.EngineBlockStatus is { } engineStatus) overrides["engineBlockStatus"] = engineStatus.ToString();
if (req.OperatorBlockStatus is { } operatorStatus) overrides["operatorBlockStatus"] = operatorStatus.ToString();
if (req.DefaultRedirectTargets is { Length: > 0 }) overrides["redirectTargets"] = string.Join(',', req.DefaultRedirectTargets);
// 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);
return Results.Ok(ToDto(policy.Current));
});
group.MapGet("/observations", async (OpenWafDbContext db, int? limit, int? offset,
HttpContext ctx, CancellationToken ct) =>
{
if (!TryPaging(limit, offset, ReadListDefaultLimit, ReadListMaxLimit,
out var take, out var skip, out var pagingError))
return Results.BadRequest(new { error = pagingError });
var rows = await db.Observations.AsNoTracking()
.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 db.Observations.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", (StreakTracker tracker, EdgePolicyProvider policyProvider, HttpContext ctx, int? limit, int? offset) =>
{
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 { error = pagingError });
var streaks = tracker.LiveStreaks(now, policy, take, skip, 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
{
scope = "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.
standingStreaks = standing,
maxTrackedSources = policy.MaxTrackedSources,
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, int? limit, int? offset,
HttpContext ctx, CancellationToken ct) =>
{
if (!TryPaging(limit, offset, ReadListDefaultLimit, ReadListMaxLimit,
out var take, out var skip, out var pagingError))
return Results.BadRequest(new { error = pagingError });
var rows = await db.Alerts.AsNoTracking()
.OrderByDescending(a => a.CreatedAt)
.Skip(skip)
.Take(take)
.ToListAsync(ct);
var total = await db.Alerts.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, CancellationToken ct) =>
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, CancellationToken ct) =>
{
if (!TryCountryCode(code, out var normalized, out var codeError))
return Results.BadRequest(new { error = 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);
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, CancellationToken ct) =>
{
if (!TryCountryCode(code, out var normalized, out var codeError))
return Results.BadRequest(new { error = codeError });
var row = await db.CountryRules.FindAsync([normalized], ct);
if (row is null) return Results.NotFound(new { error = $"no country rule for \"{normalized}\"" });
db.CountryRules.Remove(row);
await db.SaveChangesAsync(ct);
await state.InvalidateAsync(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, CancellationToken ct) =>
{
// 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);
return Results.Ok(rows.OrderByDescending(r => r.Sources));
});
group.MapGet("/geo", (IGeoIpLookup geo) => 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
}));
group.MapGet("/state", (EdgeStateStore state, EdgePolicyProvider policyProvider, StreakTracker tracker) =>
{
var now = DateTimeOffset.UtcNow;
var allowLive = state.Current.AllowEntries.Count(a => a.IsLive(now));
var allowExpired = state.Current.AllowEntries.Count - allowLive;
return Results.Ok(new
{
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,
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,
mode = state.Current.Policy.Mode.ToString()
});
});
return app;
}
private const int AllowListDefaultLimit = 500;
private const int AllowListMaxLimit = 2000;
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;
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.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.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);
/// <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 { error = $"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 { error }, statusCode: StatusCodes.Status503ServiceUnavailable);
private static bool FixedTimeEquals(string a, string b)
{
if (string.IsNullOrEmpty(a) || string.IsNullOrEmpty(b)) return false;
return System.Security.Cryptography.CryptographicOperations.FixedTimeEquals(
System.Text.Encoding.UTF8.GetBytes(a), System.Text.Encoding.UTF8.GetBytes(b));
}
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 _);
}
}