An audit of the admin surface by gate coverage turned up two endpoints with zero
appearances in any gate: `/admin-api/state` and `/admin-api/geo`. The first is
the one the console's entire summary line is built from — the page could have
been reporting a mode the edge is not in, or a ban count that is not the count,
and every assertion in every script would have stayed green.
`/admin-api/state` also lacked one field the summary needs. It reported the age
of the in-memory snapshot and not the TTL that age is measured against, so
"snapshot 0.4s" was half a number. On a single edge the TTL is invisible; behind
a load balancer it *is* the delay a ban has, which is the whole subject of the
multi-instance question. `/healthz` already reported it — the endpoint the page
actually reads did not.
The summary line now says, in one place an operator looks at:
mode Enforce · snapshot 0.1s / ttl 30s · tracked 3 · engine bans 0
operator blocks 0 · allow entries 0 · geo DBIP-Country-Lite · built 2026-10-01 · 0.6d
The geo pill is marked past 90 days, the same rule `/healthz` reports as
`geoStale`, and the assertion checks it is *not* marked while the database is
inside the alarm — an always-green warning is a warning nobody reads.
Gates: `compose-smoke.sh` asserts `/state` at the moment a ban exists, so the
numbers have known values rather than "some number" — mode `Enforce`, TTL `30`,
`engineBans` 1 — 35 → **38 assertions**. `console-check.cjs` asserts the TTL in
the summary, the geo database with its build date and age, and the marking: 30 →
**33** assertions. `SnapshotStalenessTests` got the
fast half for the new field.
That test caught the test, not the product: the first version read `/state` with
a bare client and got a 401, because the admin surface is token-gated while
`/healthz` deliberately is not. The endpoint was right and the test was wrong.
Numbers on this tree. Host: build 0 warnings, unit 54/54, integration **30/30**,
compose-smoke **38/38**. Linux rehearsal, one invocation, EXIT=0: source gates
54/54 + 30/30 + smoke 19/19, compose **38/38**, console **33/33** in a real
Chromium. actionlint 1.7.12 over both workflow files: 0 problems; shellcheck,
`bash -n`, `node --check` clean.
Still the same boundary as every other commit here: none of it has executed on a
runner, because the repository has no remote (OPEN-15).
265 lines
15 KiB
C#
265 lines
15 KiB
C#
using Microsoft.EntityFrameworkCore;
|
|
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();
|
|
if (string.IsNullOrWhiteSpace(provided)) provided = req.Query["token"].ToString();
|
|
return FixedTimeEquals(provided, adminToken) ? await next(filterCtx) : Results.Unauthorized();
|
|
});
|
|
|
|
group.MapGet("/blocks", async (string? source, bool? live, int? limit, int? offset, BlockStore store, HttpContext ctx, CancellationToken ct) =>
|
|
{
|
|
var now = DateTimeOffset.UtcNow;
|
|
var take = Math.Clamp(limit ?? BlockStore.ListDefaultLimit, 1, BlockStore.ListMaxLimit);
|
|
var skip = Math.Max(0, offset ?? 0);
|
|
var rows = await store.ListAsync(ParseSource(source), live ?? true, now, take, skip, ct);
|
|
var total = await store.CountAsync(ParseSource(source), 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" });
|
|
var (ok, error) = await store.AddOperatorAsync(req.Ip, req.Reason, req.RedirectTo, DateTimeOffset.UtcNow, ct);
|
|
return ok ? Results.NoContent() : Results.BadRequest(new { 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) =>
|
|
{
|
|
var parsed = ParseSource(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 n = await store.DeleteAsync(parsed, key, ct);
|
|
return Results.Ok(new { deleted = n });
|
|
});
|
|
|
|
group.MapGet("/allow", async (OpenWafDbContext db, CancellationToken ct) =>
|
|
Results.Ok(await db.AllowEntries.AsNoTracking().OrderBy(a => a.Match).ToListAsync(ct)));
|
|
|
|
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" });
|
|
|
|
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 > 0 ? DateTimeOffset.UtcNow.AddMinutes(req.ExpiresInMinutes.Value) : 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);
|
|
return n > 0 ? Results.NoContent() : Results.NotFound();
|
|
});
|
|
|
|
group.MapGet("/policy", (EdgePolicyProvider policy) => 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();
|
|
}
|
|
if (req.StreakThreshold is > 0) overrides["streakThreshold"] = req.StreakThreshold.Value.ToString();
|
|
if (req.StreakWindowMinutes is > 0) overrides["streakWindowMinutes"] = req.StreakWindowMinutes.Value.ToString();
|
|
if (req.BanDurationMinutes is > 0) overrides["banDurationMinutes"] = req.BanDurationMinutes.Value.ToString();
|
|
if (req.RefusalRange is not null) overrides["refusalRange"] = req.RefusalRange;
|
|
if (req.ServerErrorRange is not null) overrides["serverErrorRange"] = req.ServerErrorRange;
|
|
if (req.TrustProxyHeaders is not null) overrides["trustProxyHeaders"] = req.TrustProxyHeaders.Value.ToString().ToLowerInvariant();
|
|
if (req.MaxTrackedSources is > 0) overrides["maxTrackedSources"] = req.MaxTrackedSources.Value.ToString();
|
|
if (req.Ipv4KeyPrefixLength is >= 0) overrides["ipv4KeyPrefixLength"] = req.Ipv4KeyPrefixLength.Value.ToString();
|
|
if (req.Ipv6KeyPrefixLength is >= 0) overrides["ipv6KeyPrefixLength"] = req.Ipv6KeyPrefixLength.Value.ToString();
|
|
if (req.EngineBlockStatus is > 0) overrides["engineBlockStatus"] = req.EngineBlockStatus.Value.ToString();
|
|
if (req.OperatorBlockStatus is > 0) overrides["operatorBlockStatus"] = req.OperatorBlockStatus.Value.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.
|
|
await policy.SaveAsync(overrides, ct);
|
|
// 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, CancellationToken ct) =>
|
|
Results.Ok(await db.Observations.AsNoTracking()
|
|
.OrderByDescending(o => o.LastSeenAt)
|
|
.Take(Math.Clamp(limit ?? 100, 1, 1000))
|
|
.Select(o => new ObservationDto(o.SourceKey, o.LastSeenAt, o.MaxConsecutiveRefusals,
|
|
o.TotalRefusals, o.TotalServerErrorStreak, o.LastStatusCode, o.LastPath,
|
|
o.LastCountryCode, o.LastCity))
|
|
.ToListAsync(ct)));
|
|
|
|
// 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) =>
|
|
{
|
|
var now = DateTimeOffset.UtcNow;
|
|
var policy = policyProvider.Current;
|
|
var take = Math.Clamp(limit ?? 50, 1, 1000);
|
|
var streaks = tracker.LiveStreaks(now, policy, take);
|
|
ctx.Response.Headers["X-Truncated"] = (streaks.Count < tracker.TrackedCount).ToString().ToLowerInvariant();
|
|
return Results.Ok(new
|
|
{
|
|
scope = "this-process",
|
|
threshold = policy.StreakThreshold,
|
|
windowMinutes = policy.StreakWindow.TotalMinutes,
|
|
trackedSources = tracker.TrackedCount,
|
|
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, CancellationToken ct) =>
|
|
Results.Ok(await db.Alerts.AsNoTracking()
|
|
.OrderByDescending(a => a.CreatedAt)
|
|
.Take(Math.Clamp(limit ?? 100, 1, 1000))
|
|
.ToListAsync(ct)));
|
|
|
|
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) =>
|
|
{
|
|
code = code.Trim().ToUpperInvariant();
|
|
if (code.Length != 2) return Results.BadRequest(new { error = "code must be a two-letter ISO country code" });
|
|
var row = await db.CountryRules.FindAsync([code], ct);
|
|
if (row is null) db.CountryRules.Add(new CountryRule { Code = code, IsAllowed = allowed, UpdatedAt = DateTimeOffset.UtcNow });
|
|
else { row.IsAllowed = allowed; row.UpdatedAt = DateTimeOffset.UtcNow; }
|
|
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, StreakTracker tracker) => 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,
|
|
allowEntries = state.Current.AllowEntries.Count,
|
|
mode = state.Current.Policy.Mode.ToString()
|
|
}));
|
|
|
|
return app;
|
|
}
|
|
|
|
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);
|
|
|
|
private static BlockSource? ParseSource(string? source) => source?.Trim().ToLowerInvariant() switch
|
|
{
|
|
"operator" => BlockSource.Operator,
|
|
"engine" => BlockSource.Engine,
|
|
"all" or "" or null => null,
|
|
_ => BlockSource.Operator
|
|
};
|
|
|
|
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 _);
|
|
}
|
|
}
|