the admin API's error body stops being anonymous, and the AOT build prices a reflection resolver
Wall 2 of the generator slice (OPEN-79) is the web host, not the database: the
AOT edge never reaches `Now listening` because the admin API's request DTOs have
no compiled JSON contract, and a NativeAOT binary has no reflection resolver to
fall back on. The wire shapes have to be types before a contract can exist for
them, so this starts with the shapes.
Counted in `dotnet/OpenWaf.Edge` before the change: **130 anonymous object
literals** in the JSON path, in **51 distinct shapes**, of which **111 are the
one shape `new { error = … }`**. Those 111 are now `ErrorDto`, and the two
read-only-token refusals that carried a second property are `ReadOnlyRefusalDto`.
`ErrorDto.Error` is nullable because the literal it replaces was — the
unknown-query-parameter validators hand back a `string?` next to the false they
return, and making it non-null would hide a second change inside a mechanical
one. `Admin/EdgeJson.cs` is the edge's `JsonSerializerContext`: 24 registered
types (5 request bodies, the 14 response records the tree already had, the two new
ones, the config-transfer document and its rejected-item row), with
`[JsonSourceGenerationOptions(PropertyNamingPolicy = CamelCase)]` because the
generated contract carries the property names — without that line the same record
answers `{"Error": …}` and the console, the smoke gate and every integration
assertion read a body with no error in it. The recipe is the neighbouring
deployment's (`app/lib/Kernel/KernelJson.cs`, `api/Domain/AppJson.cs`, one line in
its `Program.cs`), not an invention here. **18 anonymous literals in 50 shapes
remain**; they are the rest of the wall, and this commit does not pretend
otherwise.
Two measurements decided the wiring, and both were paid for:
* A non-empty `TypeInfoResolverChain` **replaces** the reflection resolver, it
does not extend it. With only the context in the chain, a type it does not
know fails on a *JIT* build with the sentence the AOT probe reports —
`JsonTypeInfo metadata for type '<>f__AnonymousType0`1[System.String]' was not
provided by TypeInfoResolver of type '[EdgeJson]'` — reproduced with a
standalone probe. So on a build that can reflect, reflection stays at the end
of the chain: the 18 remaining literals kept served and visible rather than a
break smuggled into a slice.
* That fallback is not free on the other side. Naming `DefaultJsonTypeInfoResolver`
in an AOT publish pulls the reflection-based JSON stack into the native image:
the publish step ran **66 minutes and never finished**, against **232 s** for
the same Dockerfile an hour earlier. The branch is now gated on
`RuntimeFeature.IsDynamicCodeCompiled`, which the AOT compiler substitutes as
a constant, so the shipped binary contains neither the branch nor the resolver.
The 66-minute figure was taken at load average 26–34 against the earlier run's
~12, so that ratio is an upper bound, not a clean A/B; the weekly runner is
where the clean number will come from.
`AotJsonContractTests` (2 new) asks the running edge which body types its
endpoints accept — `IAcceptsMetadata`, read from the live `EndpointDataSource`,
with the measured count of 5 asserted so the guard cannot pass on an empty set —
and demands a compiled contract for each; the second test asserts the generated
contract really says `error` and `tokenLevel`. An endpoint added without a
contract is therefore red in the suite, not in next Monday's probe.
Measured on this tree: `dotnet build OpenWaf.Edge -c Release` 0 warnings, unit
**378/378**, integration **407/407 in 2 m 16 s** (unsandboxed). The same suite run
inside the sandbox answered **8 failures of 407**, every one of them `Timed out
waiting for the entry point to build the IHost after 00:05:00` — the loopback-bind
symptom the README already recorded on 2026-10-04 and 2026-10-05, reproduced here
rather than re-diagnosed; the 407 figure is the unsandboxed one.
NOT measured on this tree: whether the AOT edge now reaches `Now listening`. The
rebuild that would answer it was interrupted, so the README and
`docs/ARCHITECTURE.md` say so in those words, and `.github/workflows/aot-probe.yml`
now prints `lines where the edge started listening` — 0 means the host still dies
before serving, 1 means it serves. The 18 remaining anonymous shapes are what
stands between the two.
This commit is contained in:
@@ -126,6 +126,14 @@ jobs:
|
||||
# contract, do not reflect over it at run time.
|
||||
printf 'json metadata refusals at startup: %s\n' "$(grep -c 'JsonTypeInfo metadata for type' aotprobe.log || true)"
|
||||
{ grep -m1 -o "JsonTypeInfo metadata for type '[^']*'" aotprobe.log || true; } | sed 's/^/first type without a contract: /'
|
||||
# Did the host get as far as listening? Until 2026-10-06 the answer was
|
||||
# no for a reason that had nothing to do with the database: the admin
|
||||
# API's request DTOs had no compiled JSON contract, so the host threw
|
||||
# before Kestrel opened a port. `OpenWaf.Edge/Admin/EdgeJson.cs` registers
|
||||
# those contracts and Program.cs puts the context at the head of the
|
||||
# resolver chain, so this line is the half-scoreboard of the API slice:
|
||||
# a 0 here means the host still dies before serving, a 1 means it serves.
|
||||
printf 'lines where the edge started listening: %s\n' "$(grep -c 'Now listening on:' aotprobe.log || true)"
|
||||
grep -c "Query wasn't precompiled and dynamic code isn't supported with NativeAOT" aotprobe.log \
|
||||
| sed 's/^/queries refused at run time: /' || true
|
||||
|
||||
|
||||
@@ -425,6 +425,66 @@ static binary in production. `.github/workflows/aot-probe.yml` re-measures this
|
||||
on the x86-64 runner weekly, because the musl AOT compiler crashes under
|
||||
emulation on Apple Silicon and a laptop can only ever produce the arm64 half.
|
||||
|
||||
### The first cut into the API wall: a compiled JSON contract
|
||||
|
||||
The host-start refusal is not a missing switch. A NativeAOT binary has no
|
||||
reflection-based JSON resolver to fall back on, and the fallback it would need is
|
||||
the thing the runtime refuses. So the wire shapes have to be **types** before a
|
||||
contract can be compiled for them. Counted in `dotnet/OpenWaf.Edge` on
|
||||
2026-10-06: **130 anonymous object literals** in the JSON path, in **51 distinct
|
||||
shapes**, of which **111 are the one shape `new { error = … }`**. A source
|
||||
generator cannot describe an anonymous type at all, so those 111 became one
|
||||
named record — `ErrorDto` — and `Admin/EdgeJson.cs` is now the edge's
|
||||
`JsonSerializerContext`: 24 registered types (the 5 request bodies, the 14
|
||||
response records the tree already had, `ErrorDto`, `ReadOnlyRefusalDto`, the
|
||||
config-transfer document and its rejected-item row), with
|
||||
`[JsonSourceGenerationOptions(PropertyNamingPolicy = CamelCase)]` because the
|
||||
generated contract carries the property names — without that line the same record
|
||||
answers `{"Error": …}` and every consumer of this API reads a body with no error
|
||||
in it. `Program.cs` puts the context at the head of the resolver chain. The
|
||||
recipe is taken from the neighbouring deployment (`app/lib/Kernel/KernelJson.cs`,
|
||||
`api/Domain/AppJson.cs`, one line in its `Program.cs`), not invented here.
|
||||
|
||||
Two measurements decided the shape of that wiring, and both cost something to
|
||||
learn:
|
||||
|
||||
* **A non-empty `TypeInfoResolverChain` replaces the reflection resolver, it does
|
||||
not extend it.** With only the context in the chain, a type it does not know
|
||||
fails on a *JIT* build with the same sentence the AOT probe reports
|
||||
(`JsonTypeInfo metadata for type '<>f__AnonymousType0` `` `1[System.String]' was
|
||||
not provided by TypeInfoResolver of type '[EdgeJson]'` `, from a standalone
|
||||
probe). Eighteen anonymous literals are still standing, so on a build that can
|
||||
reflect, reflection stays at the end of the chain: the debt kept served and
|
||||
visible rather than a break smuggled into a slice.
|
||||
* **That fallback is not free on the other side.** Naming
|
||||
`DefaultJsonTypeInfoResolver` in an AOT publish pulls the reflection-based JSON
|
||||
stack into the native image: the publish step ran **66 minutes and never
|
||||
finished**, against **232 s** for the same Dockerfile an hour earlier. The
|
||||
branch is now gated on `RuntimeFeature.IsDynamicCodeCompiled`, which the AOT
|
||||
compiler substitutes as a constant, so the shipped binary does not contain the
|
||||
branch at all. The 66-minute figure was taken while this host carried a load
|
||||
average of 26–34 against the earlier run's ~12, so the ratio is an upper bound,
|
||||
not a clean A/B — the weekly runner is where the clean number will come from.
|
||||
|
||||
What is measured on this tree: `dotnet build OpenWaf.Edge -c Release` **0
|
||||
warnings**, unit **378/378**, and integration **407/407 in 2 m 16 s** — the two
|
||||
new ones are `AotJsonContractTests`, which asks the running edge which body types
|
||||
its endpoints accept (`IAcceptsMetadata`, read from the live endpoint table, so an
|
||||
endpoint added without a contract is red here rather than in next Monday's probe)
|
||||
and asserts the generated contract really says `error` and not `Error`. The
|
||||
407th number also carries a caveat worth keeping: the same suite run **inside the
|
||||
sandbox** answered **8 failures of 407**, every one of them
|
||||
`Timed out waiting for the entry point to build the IHost after 00:05:00` — the
|
||||
loopback-bind symptom this README already recorded on 2026-10-04 and 2026-10-05,
|
||||
reproduced here rather than re-diagnosed.
|
||||
|
||||
What is **not** measured on this tree: whether the AOT edge now reaches
|
||||
`Now listening`. The rebuild that would answer it was interrupted, and the answer
|
||||
is the reason the probe now prints `lines where the edge started listening` —
|
||||
a 0 means the host still dies before serving, a 1 means it serves. The remaining
|
||||
**18 anonymous literals, in 50 distinct shapes**, are what stands between the
|
||||
two, and they are the next cut.
|
||||
|
||||
## Schema
|
||||
|
||||
Migrations are the schema of record for PostgreSQL, which is the provider a
|
||||
|
||||
+35
-10
@@ -111,16 +111,41 @@ classifies the status, and is the only thing that can create an engine ban.
|
||||
schema line, because a gate that only forbids an error string also passes when
|
||||
the feature is simply absent.
|
||||
|
||||
What remains is the query wall and nothing else: the edge starts, creates its
|
||||
schema, refuses every query (`Query wasn't precompiled and dynamic code isn't
|
||||
supported with NativeAOT`, 2 refusals in a 25-second window) and never reaches
|
||||
`Now listening`. The shape that ships past it, in a neighbouring deployment of
|
||||
the same runtime, has no EF Core at all: a Roslyn source generator emits the
|
||||
queries — and the endpoints, and the OpenAPI document — at build time over
|
||||
`System.Data.Common`, with the concrete driver supplied at composition. That is
|
||||
the slice this entry now points at, and the reason it is the *correct* step
|
||||
rather than the cheap one: it removes the only remaining wall instead of
|
||||
routing around it.
|
||||
What remains is **two** walls, not one. The edge creates its schema, refuses
|
||||
every query (`Query wasn't precompiled and dynamic code isn't supported with
|
||||
NativeAOT`, 2 refusals in a 25-second window) and never reaches `Now listening`
|
||||
— and the reason it never listens is upstream of the database: the admin API's
|
||||
request DTOs had no compiled JSON contract, so the host throws before Kestrel
|
||||
opens a port.
|
||||
|
||||
**The API half, first cut (2026-10-07).** A source generator cannot describe an
|
||||
anonymous type, and the edge's wire shapes were largely anonymous: **130
|
||||
anonymous object literals** in `OpenWaf.Edge`, **51 distinct shapes**, **111 of
|
||||
them the single shape `new { error = … }`**. Those 111 are now one named record
|
||||
(`ErrorDto`), and `Admin/EdgeJson.cs` is the edge's `JsonSerializerContext` —
|
||||
24 registered types, `[JsonSourceGenerationOptions(PropertyNamingPolicy =
|
||||
CamelCase)]` because the generated contract carries the property names and the
|
||||
whole API reads `error`, not `Error` — registered at the head of the resolver
|
||||
chain in `Program.cs`. **18 anonymous literals in 50 shapes remain**, and they
|
||||
are the rest of this wall. Two facts about the wiring are load-bearing and were
|
||||
measured, not assumed: a non-empty `TypeInfoResolverChain` **replaces** the
|
||||
reflection resolver rather than extending it (so an unregistered type breaks on
|
||||
a JIT build too, with the same sentence the AOT probe reports), and naming
|
||||
`DefaultJsonTypeInfoResolver` in an AOT publish drags the reflection-based JSON
|
||||
stack into the native image — that publish ran **66 minutes without finishing**
|
||||
against **232 s** without it, so the fallback is gated on
|
||||
`RuntimeFeature.IsDynamicCodeCompiled` and is not in the shipped binary at all.
|
||||
`AotJsonContractTests` reads the accepted body types off the live endpoint table
|
||||
and demands a contract for each, so a new endpoint without one is red in the
|
||||
suite rather than in next Monday's probe.
|
||||
|
||||
The query wall is the other half, and the shape that ships past both, in a
|
||||
neighbouring deployment of the same runtime, has no EF Core at all: a Roslyn
|
||||
source generator emits the queries — and the endpoints, and the OpenAPI
|
||||
document — at build time over `System.Data.Common`, with the concrete driver
|
||||
supplied at composition. That is the slice this entry points at (OPEN-79), and
|
||||
the reason it is the *correct* step rather than the cheap one: it removes the
|
||||
walls instead of routing around them.
|
||||
* **Keying the ban on ip+UA** (as the analytics `SessionHash` does): a bot that
|
||||
varies its UA multiplies into many sources and never reaches the threshold.
|
||||
* **Banning on 5xx because the original wording said `> 400`**: turns an outage
|
||||
|
||||
@@ -47,7 +47,7 @@ internal static class AdminAuth
|
||||
=> async (filterCtx, next) =>
|
||||
{
|
||||
if (!AdminTokenPolicy.IsConfigured(adminToken))
|
||||
return Results.NotFound(new { error = disabledMessage });
|
||||
return Results.NotFound(new ErrorDto(disabledMessage));
|
||||
|
||||
var req = filterCtx.HttpContext.Request;
|
||||
var provided = req.Headers[Header].ToString();
|
||||
@@ -97,7 +97,7 @@ internal static class AdminAuth
|
||||
// wrong, when what is wrong is the endpoint it was sent to.
|
||||
if (level == AdminTokenLevel.ReadOnly && !AdminTokenPolicy.IsRead(req.Method))
|
||||
return Results.Json(
|
||||
new { error = AdminTokenPolicy.ReadOnlyRefusal, tokenLevel = "read-only" },
|
||||
new ReadOnlyRefusalDto(AdminTokenPolicy.ReadOnlyRefusal, "read-only"),
|
||||
statusCode: StatusCodes.Status403Forbidden);
|
||||
|
||||
return await next(filterCtx);
|
||||
@@ -118,7 +118,7 @@ internal static class AdminAuth
|
||||
=> (filterCtx, next) =>
|
||||
filterCtx.HttpContext.Items[LevelItem] is AdminTokenLevel.ReadOnly
|
||||
? new ValueTask<object?>(Results.Json(
|
||||
new { error = refusal, tokenLevel = "read-only" },
|
||||
new ReadOnlyRefusalDto(refusal, "read-only"),
|
||||
statusCode: StatusCodes.Status403Forbidden))
|
||||
: next(filterCtx);
|
||||
}
|
||||
|
||||
@@ -170,6 +170,29 @@ internal sealed record ObservationDto(
|
||||
string? LastCountryCode,
|
||||
string? LastCity);
|
||||
|
||||
/// <summary>The edge's one error body: <c>{"error": "…"}</c>.
|
||||
///
|
||||
/// It used to be written 111 times as the anonymous literal <c>new { error = … }</c>.
|
||||
/// That is not a style question: a NativeAOT binary has no reflection-based JSON
|
||||
/// resolver to fall back on, and a source-generated contract cannot describe an
|
||||
/// anonymous type at all — so the shape the operator reads had to become a type
|
||||
/// before the wire shape could be compiled in. Measured 2026-10-06: 130 anonymous
|
||||
/// literals in this project, 111 of them this one shape, in 51 distinct shapes.
|
||||
/// The camelCase of the wire name comes from <see cref="EdgeJson"/>, which is what
|
||||
/// keeps the JSON byte-identical to what the console and the smoke gate read today.
|
||||
/// <c>Error</c> is nullable because the anonymous literal it replaces was: the
|
||||
/// validators that answer "unknown query parameter" hand back a <c>string?</c>
|
||||
/// alongside the false they return, and a record that refused it would be a
|
||||
/// second, different change hiding inside a mechanical one.
|
||||
/// </summary>
|
||||
internal sealed record ErrorDto(string? Error);
|
||||
|
||||
/// <summary>The 403 a read-only token gets: the same error body plus the level the
|
||||
/// token actually had, because the difference between "wrong token" and "right
|
||||
/// token, endpoint it may not call" is the whole point of the second token
|
||||
/// (OPEN-61/OPEN-62).</summary>
|
||||
internal sealed record ReadOnlyRefusalDto(string Error, string TokenLevel);
|
||||
|
||||
internal static class DtoMapper
|
||||
{
|
||||
public static BlockDto ToDto(this BlockEntry b, DateTimeOffset now) => new(
|
||||
|
||||
@@ -48,7 +48,7 @@ internal static partial class AdminEndpoints
|
||||
var export = group.MapGet("/export", async (OpenWafDbContext db, EdgePolicyProvider policy,
|
||||
HttpContext ctx, CancellationToken ct) =>
|
||||
{
|
||||
if (!TryKnownQuery(ctx, out var unknown)) return Results.BadRequest(new { error = unknown });
|
||||
if (!TryKnownQuery(ctx, out var unknown)) return Results.BadRequest(new ErrorDto(unknown));
|
||||
|
||||
var now = DateTimeOffset.UtcNow;
|
||||
|
||||
@@ -147,15 +147,13 @@ internal static partial class AdminEndpoints
|
||||
IStreakTracker streaks, RateTracker rates, RateRuleTracker rateRules, BlockStore blocks, ConfigChangeWriter changes,
|
||||
HttpContext ctx, CancellationToken ct) =>
|
||||
{
|
||||
if (!TryKnownQuery(ctx, out var unknown)) return Results.BadRequest(new { error = unknown });
|
||||
if (!TryKnownQuery(ctx, out var unknown)) return Results.BadRequest(new ErrorDto(unknown));
|
||||
if (ctx.Request.ContentLength is { } declared && declared > ConfigTransfer.MaxBodyBytes)
|
||||
return Results.BadRequest(new {
|
||||
error = $"the document is {declared} bytes; an import carries at most {ConfigTransfer.MaxBodyBytes}" });
|
||||
return Results.BadRequest(new ErrorDto($"the document is {declared} bytes; an import carries at most {ConfigTransfer.MaxBodyBytes}"));
|
||||
|
||||
var body = await new StreamReader(ctx.Request.Body, Encoding.UTF8).ReadToEndAsync(ct);
|
||||
if (body.Length > ConfigTransfer.MaxBodyBytes)
|
||||
return Results.BadRequest(new {
|
||||
error = $"the document is {body.Length} bytes; an import carries at most {ConfigTransfer.MaxBodyBytes}" });
|
||||
return Results.BadRequest(new ErrorDto($"the document is {body.Length} bytes; an import carries at most {ConfigTransfer.MaxBodyBytes}"));
|
||||
|
||||
ConfigImportDocument? doc;
|
||||
try
|
||||
@@ -166,15 +164,15 @@ internal static partial class AdminEndpoints
|
||||
{
|
||||
// Named as a malformed document, not as an empty one: the two
|
||||
// need different fixes and the operator is holding the file.
|
||||
return Results.BadRequest(new { error = $"the document is not valid JSON: {ex.Message}" });
|
||||
return Results.BadRequest(new ErrorDto($"the document is not valid JSON: {ex.Message}"));
|
||||
}
|
||||
|
||||
if (doc is null) return Results.BadRequest(new { error = "the document is empty" });
|
||||
if (doc is null) return Results.BadRequest(new ErrorDto("the document is empty"));
|
||||
|
||||
// Nothing is written before the document is readable in full: a
|
||||
// half-applied transfer is the state an operator cannot reason about.
|
||||
var versionProblem = ConfigTransfer.ExplainVersion(doc.Version);
|
||||
if (versionProblem is not null) return Results.BadRequest(new { error = versionProblem });
|
||||
if (versionProblem is not null) return Results.BadRequest(new ErrorDto(versionProblem));
|
||||
|
||||
var blocksIn = doc.Blocks ?? [];
|
||||
var allowIn = doc.Allow ?? [];
|
||||
@@ -189,7 +187,7 @@ internal static partial class AdminEndpoints
|
||||
})
|
||||
{
|
||||
var sizeProblem = ConfigTransfer.ExplainSectionSize(section, count);
|
||||
if (sizeProblem is not null) return Results.BadRequest(new { error = sizeProblem });
|
||||
if (sizeProblem is not null) return Results.BadRequest(new ErrorDto(sizeProblem));
|
||||
}
|
||||
|
||||
var now = DateTimeOffset.UtcNow;
|
||||
|
||||
@@ -38,11 +38,11 @@ internal static partial class AdminEndpoints
|
||||
|
||||
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 { error = unknown });
|
||||
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 { error = 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);
|
||||
@@ -55,23 +55,23 @@ internal static partial class AdminEndpoints
|
||||
|
||||
group.MapPost("/blocks", async (NewBlockRequest req, BlockStore store, ConfigChangeWriter changes, HttpContext ctx, CancellationToken ct) =>
|
||||
{
|
||||
if (!TryKnownQuery(ctx, out var unknown)) return Results.BadRequest(new { error = unknown });
|
||||
if (string.IsNullOrWhiteSpace(req.Ip)) return Results.BadRequest(new { error = "ip is required" });
|
||||
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 { error = $"reason must be at most {EntryLimits.NoteMaxLength} characters; got {req.Reason!.Length}" });
|
||||
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 { error = $"redirectTo must be an absolute http(s) URL with no spaces or control characters; got \"{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 { error = $"expiresInMinutes must be {EntryLimits.ExpiresInMinutesMin}..{EntryLimits.ExpiresInMinutesMax} to expire, or left out to never expire; got {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);
|
||||
@@ -83,7 +83,7 @@ internal static partial class AdminEndpoints
|
||||
if (added != BlockStore.AddResult.Ok)
|
||||
return added switch
|
||||
{
|
||||
BlockStore.AddResult.InvalidInput => Results.BadRequest(new { error }),
|
||||
BlockStore.AddResult.InvalidInput => Results.BadRequest(new ErrorDto(error)),
|
||||
_ => StorageUnavailable(error!)
|
||||
};
|
||||
// The record of the change (OPEN-64). After the change, never
|
||||
@@ -102,10 +102,10 @@ internal static partial class AdminEndpoints
|
||||
// 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 { error = unknown });
|
||||
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 { error = "refusing to delete every block: pass source=operator|engine or 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
|
||||
@@ -141,10 +141,10 @@ internal static partial class AdminEndpoints
|
||||
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 { error = unknown });
|
||||
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 { error = 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"
|
||||
@@ -164,19 +164,19 @@ internal static partial class AdminEndpoints
|
||||
|
||||
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 { error = unknown });
|
||||
if (!TryKnownQuery(ctx, out var unknown)) return Results.BadRequest(new ErrorDto(unknown));
|
||||
if (string.IsNullOrWhiteSpace(req.Match) || !IsValidMatch(req.Match))
|
||||
return Results.BadRequest(new { error = "match must be an address or CIDR" });
|
||||
return Results.BadRequest(new ErrorDto("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}" });
|
||||
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 { error = $"expiresInMinutes must be {EntryLimits.ExpiresInMinutesMin}..{EntryLimits.ExpiresInMinutesMax} to expire, or left out to never expire; got {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 { error = "already allowlisted" });
|
||||
if (existing is not null) return Results.Conflict(new ErrorDto("already allowlisted"));
|
||||
|
||||
db.AllowEntries.Add(new AllowEntry
|
||||
{
|
||||
@@ -193,14 +193,14 @@ internal static partial class AdminEndpoints
|
||||
|
||||
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 { error = unknown });
|
||||
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 { error = $"no allow entry with id {id}" });
|
||||
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();
|
||||
@@ -214,10 +214,10 @@ internal static partial class AdminEndpoints
|
||||
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 { error = unknown });
|
||||
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 { error = pagingError });
|
||||
return Results.BadRequest(new ErrorDto(pagingError));
|
||||
var now = DateTimeOffset.UtcNow;
|
||||
var liveOnly = live ?? true;
|
||||
IQueryable<RequestRule> Query() =>
|
||||
@@ -240,20 +240,20 @@ internal static partial class AdminEndpoints
|
||||
|
||||
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 { error = unknown });
|
||||
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 { error = patternProblem });
|
||||
if (patternProblem is not null) return Results.BadRequest(new ErrorDto(patternProblem));
|
||||
if (!EntryLimits.NoteOk(req.Note))
|
||||
return Results.BadRequest(new { error = $"note must be at most {EntryLimits.NoteMaxLength} characters; got {req.Note!.Length}" });
|
||||
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 { error = $"expiresInMinutes must be {EntryLimits.ExpiresInMinutesMin}..{EntryLimits.ExpiresInMinutesMax} to expire, or left out to never expire; got {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 { error = $"action must be observe|block; got \"{req.Action}\"" });
|
||||
return Results.BadRequest(new ErrorDto($"action must be observe|block; got \"{req.Action}\""));
|
||||
|
||||
var pattern = req.Pattern.Trim();
|
||||
var now = DateTimeOffset.UtcNow;
|
||||
@@ -261,12 +261,12 @@ internal static partial class AdminEndpoints
|
||||
.Where(r => r.Pattern == pattern && (r.ExpiresAt == null || r.ExpiresAt > now))
|
||||
.Select(r => r.Id).FirstOrDefaultAsync(ct);
|
||||
if (clash != 0)
|
||||
return Results.Conflict(new { error = $"rule {clash} already covers {pattern} — the listing is the evaluation order, so a second live rule for one pattern can never fire" });
|
||||
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 { error = $"at most {PathPattern.MaxRules} live rules; every request is checked against each of them" });
|
||||
return Results.BadRequest(new ErrorDto($"at most {PathPattern.MaxRules} live rules; every request is checked against each of them"));
|
||||
|
||||
db.RequestRules.Add(new RequestRule
|
||||
{
|
||||
@@ -284,10 +284,10 @@ internal static partial class AdminEndpoints
|
||||
|
||||
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 { error = unknown });
|
||||
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 { error = $"no request rule with id {id}" });
|
||||
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();
|
||||
@@ -302,10 +302,10 @@ internal static partial class AdminEndpoints
|
||||
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 { error = unknown });
|
||||
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 { error = pagingError });
|
||||
return Results.BadRequest(new ErrorDto(pagingError));
|
||||
var now = DateTimeOffset.UtcNow;
|
||||
var liveOnly = live ?? true;
|
||||
IQueryable<RateRule> Query() =>
|
||||
@@ -328,22 +328,22 @@ internal static partial class AdminEndpoints
|
||||
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 { error = unknown });
|
||||
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 { error = patternProblem });
|
||||
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 { error = $"limitPerWindow must be {PolicyBounds.RateLimitPerWindowMin}..{PolicyBounds.RateLimitPerWindowMax}; got {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 { error = $"windowSeconds must be {PolicyBounds.RateWindowSecondsMin:0}..{PolicyBounds.RateWindowSecondsMax:0}; got {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 { error = $"note must be at most {EntryLimits.NoteMaxLength} characters; got {req.Note!.Length}" });
|
||||
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 { error = $"expiresInMinutes must be {EntryLimits.ExpiresInMinutesMin}..{EntryLimits.ExpiresInMinutesMax} to expire, or left out to never expire; got {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;
|
||||
@@ -351,12 +351,12 @@ internal static partial class AdminEndpoints
|
||||
.Where(r => r.Pattern == pattern && (r.ExpiresAt == null || r.ExpiresAt > now))
|
||||
.Select(r => r.Id).FirstOrDefaultAsync(ct);
|
||||
if (clash != 0)
|
||||
return Results.Conflict(new { error = $"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" });
|
||||
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 { error = $"at most {PathPattern.MaxRules} live rate rules; every request is checked against each of them" });
|
||||
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
|
||||
{
|
||||
@@ -376,14 +376,14 @@ internal static partial class AdminEndpoints
|
||||
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 { error = unknown });
|
||||
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 { error = $"no rate rule with id {id}" });
|
||||
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();
|
||||
@@ -403,13 +403,13 @@ internal static partial class AdminEndpoints
|
||||
OpenWafDbContext db, RateRuleTracker rateRules, EdgePolicyProvider policyProvider,
|
||||
HttpContext ctx, CancellationToken ct) =>
|
||||
{
|
||||
if (!TryKnownQuery(ctx, out var unknown, "limit", "offset")) return Results.BadRequest(new { error = unknown });
|
||||
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 { error = 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 { error = $"no rate rule with id {id}" });
|
||||
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
|
||||
@@ -468,11 +468,11 @@ internal static partial class AdminEndpoints
|
||||
OpenWafDbContext db, RateRuleTracker rateRules, EdgeStateStore state,
|
||||
ConfigChangeWriter changes, HttpContext ctx, CancellationToken ct) =>
|
||||
{
|
||||
if (!TryKnownQuery(ctx, out var unknown, "source")) return Results.BadRequest(new { error = unknown });
|
||||
if (!TryKnownQuery(ctx, out var unknown, "source")) return Results.BadRequest(new ErrorDto(unknown));
|
||||
if (string.IsNullOrWhiteSpace(source))
|
||||
return Results.BadRequest(new { error = "source is required: name the source key whose window on this budget should be dropped" });
|
||||
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 { error = $"no rate rule with id {id}" });
|
||||
if (rule is null) return Results.NotFound(new ErrorDto($"no rate rule with id {id}"));
|
||||
|
||||
var asked = source.Trim();
|
||||
var clearedKey = asked;
|
||||
@@ -516,7 +516,7 @@ internal static partial class AdminEndpoints
|
||||
// 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 { error = unknown });
|
||||
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";
|
||||
@@ -526,7 +526,7 @@ internal static partial class AdminEndpoints
|
||||
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 { error = unknown });
|
||||
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.
|
||||
@@ -539,7 +539,7 @@ internal static partial class AdminEndpoints
|
||||
// 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 { error = 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.
|
||||
@@ -576,12 +576,12 @@ internal static partial class AdminEndpoints
|
||||
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 { error = unknown });
|
||||
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 { error = pagingError });
|
||||
return Results.BadRequest(new ErrorDto(pagingError));
|
||||
if (source is not null && string.IsNullOrWhiteSpace(source))
|
||||
return Results.BadRequest(new { error = "source must not be empty; omit the parameter to list every 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;
|
||||
@@ -613,7 +613,7 @@ internal static partial class AdminEndpoints
|
||||
group.MapGet("/netblocks", async (NetblockWatcher watcher, EdgePolicyProvider policyProvider,
|
||||
HttpContext ctx, CancellationToken ct) =>
|
||||
{
|
||||
if (!TryKnownQuery(ctx, out var unknown)) return Results.BadRequest(new { error = unknown });
|
||||
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.
|
||||
@@ -645,10 +645,10 @@ internal static partial class AdminEndpoints
|
||||
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 { error = unknown });
|
||||
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 { error = 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
|
||||
@@ -657,7 +657,7 @@ internal static partial class AdminEndpoints
|
||||
if (source is not null)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(source))
|
||||
return Results.BadRequest(new { error = "source must not be empty; omit the parameter to list every 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
|
||||
@@ -682,12 +682,12 @@ internal static partial class AdminEndpoints
|
||||
// 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 { error = unknown });
|
||||
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 { error = 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
|
||||
@@ -695,7 +695,7 @@ internal static partial class AdminEndpoints
|
||||
// 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 { error = "source must not be empty; omit the parameter to list every 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
|
||||
@@ -736,15 +736,15 @@ internal static partial class AdminEndpoints
|
||||
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 { error = unknown });
|
||||
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 { error = 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 { error = "source must not be empty; omit the parameter to list every 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
|
||||
@@ -764,15 +764,15 @@ internal static partial class AdminEndpoints
|
||||
// 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 { error = unknown });
|
||||
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 { error = unknown });
|
||||
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 { error = 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; }
|
||||
@@ -790,11 +790,11 @@ internal static partial class AdminEndpoints
|
||||
// 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 { error = unknown });
|
||||
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 { error = codeError });
|
||||
return Results.BadRequest(new ErrorDto(codeError));
|
||||
var row = await db.CountryRules.FindAsync([normalized], ct);
|
||||
if (row is null) return Results.NotFound(new { error = $"no country rule for \"{normalized}\"" });
|
||||
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);
|
||||
@@ -808,7 +808,7 @@ internal static partial class AdminEndpoints
|
||||
// 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 { error = unknown });
|
||||
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).
|
||||
@@ -822,7 +822,7 @@ internal static partial class AdminEndpoints
|
||||
|
||||
group.MapGet("/geo", (IGeoIpLookup geo, HttpContext ctx) =>
|
||||
{
|
||||
if (!TryKnownQuery(ctx, out var unknown)) return Results.BadRequest(new { error = unknown });
|
||||
if (!TryKnownQuery(ctx, out var unknown)) return Results.BadRequest(new ErrorDto(unknown));
|
||||
return Results.Ok(new
|
||||
{
|
||||
loaded = geo.IsLoaded,
|
||||
@@ -852,18 +852,18 @@ internal static partial class AdminEndpoints
|
||||
HttpContext ctx) =>
|
||||
{
|
||||
if (!TryKnownQuery(ctx, out var unknown, "ip", "path", "country"))
|
||||
return Results.BadRequest(new { error = unknown });
|
||||
return Results.BadRequest(new ErrorDto(unknown));
|
||||
if (ip is not null && string.IsNullOrWhiteSpace(ip))
|
||||
return Results.BadRequest(new { error = "ip must not be blank; omit the parameter to ask about the path alone" });
|
||||
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 { error = $"ip must be an address; got \"{ip}\"" });
|
||||
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 { error = $"path must start with /; got \"{askedPath}\"" });
|
||||
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
|
||||
@@ -999,14 +999,14 @@ note = t.Note
|
||||
HttpContext ctx, CancellationToken ct) =>
|
||||
{
|
||||
if (!TryKnownQuery(ctx, out var unknown, "ip", "path"))
|
||||
return Results.BadRequest(new { error = unknown });
|
||||
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 { error = "ip is required: this surface answers about one address" });
|
||||
return Results.BadRequest(new ErrorDto("ip is required: this surface answers about one address"));
|
||||
if (!IsAnAddress(ip.Trim()))
|
||||
return Results.BadRequest(new { error = $"ip must be an address; got \"{ip}\"" });
|
||||
return Results.BadRequest(new ErrorDto($"ip must be an address; got \"{ip}\""));
|
||||
|
||||
var askedIp = ip.Trim();
|
||||
string? askedPath = null;
|
||||
@@ -1014,7 +1014,7 @@ note = t.Note
|
||||
{
|
||||
askedPath = path.Trim().Length == 0 ? "/" : path.Trim();
|
||||
if (!askedPath.StartsWith('/'))
|
||||
return Results.BadRequest(new { error = $"path must start with /; got \"{askedPath}\"" });
|
||||
return Results.BadRequest(new ErrorDto($"path must start with /; got \"{askedPath}\""));
|
||||
}
|
||||
|
||||
var now = DateTimeOffset.UtcNow;
|
||||
@@ -1338,19 +1338,19 @@ note = t.Note
|
||||
EdgeStateStore state, OpenWafDbContext db, HttpContext ctx, CancellationToken ct) =>
|
||||
{
|
||||
if (!TryKnownQuery(ctx, out var unknown, "ip", "within", "limit"))
|
||||
return Results.BadRequest(new { error = unknown });
|
||||
return Results.BadRequest(new ErrorDto(unknown));
|
||||
if (string.IsNullOrWhiteSpace(ip))
|
||||
return Results.BadRequest(new { error = "ip is required: this surface answers about one source" });
|
||||
return Results.BadRequest(new ErrorDto("ip is required: this surface answers about one source"));
|
||||
if (!IsAnAddress(ip.Trim()))
|
||||
return Results.BadRequest(new { error = $"ip must be an address; got \"{ip}\"" });
|
||||
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 { error = $"within must be {HistoryMinMinutes}..{HistoryMaxMinutes} minutes; got {minutes}" });
|
||||
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 { error = $"limit must be {HistoryMinLimit}..{HistoryMaxLimit}; got {take}" });
|
||||
return Results.BadRequest(new ErrorDto($"limit must be {HistoryMinLimit}..{HistoryMaxLimit}; got {take}"));
|
||||
|
||||
var now = DateTimeOffset.UtcNow;
|
||||
var since = now.AddMinutes(-minutes);
|
||||
@@ -1503,17 +1503,15 @@ note = t.Note
|
||||
EdgeStateStore state, OpenWafDbContext db, HttpContext ctx, CancellationToken ct) =>
|
||||
{
|
||||
if (!TryKnownQuery(ctx, out var unknown, "q", "limit"))
|
||||
return Results.BadRequest(new { error = unknown });
|
||||
return Results.BadRequest(new ErrorDto(unknown));
|
||||
if (string.IsNullOrWhiteSpace(q))
|
||||
return Results.BadRequest(new { error = "q is required: this surface answers where a text appears" });
|
||||
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 {
|
||||
error = $"q must be {SearchMinQueryLength}..{SearchMaxQueryLength} characters; got {asked.Length}"
|
||||
});
|
||||
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 { error = $"limit must be {SearchMinLimit}..{SearchMaxLimit}; got {take}" });
|
||||
return Results.BadRequest(new ErrorDto($"limit must be {SearchMinLimit}..{SearchMaxLimit}; got {take}"));
|
||||
|
||||
var now = DateTimeOffset.UtcNow;
|
||||
var policy = state.GetOrRefresh().Policy;
|
||||
@@ -1774,7 +1772,7 @@ note = t.Note
|
||||
HttpContext ctx, CancellationToken ct) =>
|
||||
{
|
||||
if (!TryKnownQuery(ctx, out var unknown, "match", "path", "limit"))
|
||||
return Results.BadRequest(new { error = unknown });
|
||||
return Results.BadRequest(new ErrorDto(unknown));
|
||||
if (string.IsNullOrWhiteSpace(match))
|
||||
return Results.BadRequest(new {
|
||||
error = "match is required: an address or a CIDR, the same value the write takes"
|
||||
@@ -1785,13 +1783,13 @@ note = t.Note
|
||||
// 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 { error = inputError });
|
||||
return Results.BadRequest(new ErrorDto(inputError));
|
||||
var askedPath = string.IsNullOrWhiteSpace(path) ? "/" : path!.Trim();
|
||||
if (!askedPath.StartsWith('/'))
|
||||
return Results.BadRequest(new { error = $"path must start with /; got \"{askedPath}\"" });
|
||||
return Results.BadRequest(new ErrorDto($"path must start with /; got \"{askedPath}\""));
|
||||
var take = limit ?? ImpactDefaultLimit;
|
||||
if (take < ImpactMinLimit || take > ImpactMaxLimit)
|
||||
return Results.BadRequest(new { error = $"limit must be {ImpactMinLimit}..{ImpactMaxLimit}; got {limit}" });
|
||||
return Results.BadRequest(new ErrorDto($"limit must be {ImpactMinLimit}..{ImpactMaxLimit}; got {limit}"));
|
||||
|
||||
var now = DateTimeOffset.UtcNow;
|
||||
var snapshot = state.GetOrRefresh();
|
||||
@@ -1951,10 +1949,10 @@ note = t.Note
|
||||
EdgeStateStore state, IGeoIpLookup geo, OpenWafDbContext db,
|
||||
HttpContext ctx, CancellationToken ct) =>
|
||||
{
|
||||
if (!TryKnownQuery(ctx, out var unknown, "within")) return Results.BadRequest(new { error = unknown });
|
||||
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 { error = $"within must be {HorizonMinMinutes}..{HorizonMaxMinutes} minutes; got {minutes}" });
|
||||
return Results.BadRequest(new ErrorDto($"within must be {HorizonMinMinutes}..{HorizonMaxMinutes} minutes; got {minutes}"));
|
||||
|
||||
var now = DateTimeOffset.UtcNow;
|
||||
var until = now.AddMinutes(minutes);
|
||||
@@ -2087,18 +2085,15 @@ note = t.Note
|
||||
OpenWafDbContext db, HttpContext ctx, CancellationToken ct) =>
|
||||
{
|
||||
if (!TryKnownQuery(ctx, out var unknown, "section", "since", "limit", "offset"))
|
||||
return Results.BadRequest(new { error = unknown });
|
||||
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
|
||||
{
|
||||
error = $"section must be one of {string.Join(", ", ConfigChangeLog.Sections)}; got \"{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 { error = pagingError });
|
||||
return Results.BadRequest(new ErrorDto(pagingError));
|
||||
|
||||
var query = db.ConfigChanges.AsNoTracking();
|
||||
if (!string.IsNullOrWhiteSpace(section)) query = query.Where(c => c.Section == section);
|
||||
@@ -2115,7 +2110,7 @@ note = t.Note
|
||||
|
||||
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 { error = unknown });
|
||||
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
|
||||
@@ -2651,7 +2646,7 @@ note = t.Note
|
||||
}
|
||||
|
||||
private static IResult BadSource(string? source)
|
||||
=> Results.BadRequest(new { error = $"source must be operator|engine|all; got \"{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
|
||||
@@ -2660,7 +2655,7 @@ note = t.Note
|
||||
/// sentence rather than an empty 5xx.
|
||||
/// </summary>
|
||||
private static IResult StorageUnavailable(string error)
|
||||
=> Results.Json(new { error }, statusCode: StatusCodes.Status503ServiceUnavailable);
|
||||
=> Results.Json(new ErrorDto(error), statusCode: StatusCodes.Status503ServiceUnavailable);
|
||||
|
||||
private static bool IsValidMatch(string match)
|
||||
{
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace OpenWaf.Edge.Admin;
|
||||
|
||||
/// <summary>
|
||||
/// The edge's source-generated JSON contract — the half of the NativeAOT slice
|
||||
/// that is not the database.
|
||||
///
|
||||
/// Measured on 2026-10-06, the AOT edge does not start at all: the host dies with
|
||||
/// <c>JsonTypeInfo metadata for type 'OpenWaf.Edge.Admin.NewBlockRequest' was not
|
||||
/// provided by TypeInfoResolver</c> (3 refusals in the probe window), while the
|
||||
/// route handlers in that same stack are already the generated ones
|
||||
/// (<c>GeneratedRouteBuilderExtensionsCore</c>). So the API half is not missing
|
||||
/// code generation; it is missing a registered contract for the types that cross
|
||||
/// the wire. A NativeAOT binary has no reflection resolver to fall back on, and
|
||||
/// the fallback it would need is exactly the thing the runtime refuses
|
||||
/// (<c>Dynamic code isn't supported with NativeAOT</c>).
|
||||
///
|
||||
/// The recipe is taken, not invented: this is how the neighbouring .NET 10
|
||||
/// NativeAOT deployment does it (<c>app/lib/Kernel/KernelJson.cs</c> and
|
||||
/// <c>api/Domain/AppJson.cs</c> in <c>~/work/tskr</c> — one context per assembly,
|
||||
/// registered by one line in <c>Program.cs</c>).
|
||||
///
|
||||
/// <see cref="JsonSourceGenerationOptionsAttribute"/> is load-bearing, not
|
||||
/// decoration: the generated contract carries the property names, so a context
|
||||
/// without the camelCase policy would answer <c>{"Error": …}</c> where the console,
|
||||
/// the smoke gate and every integration assertion read <c>{"error": …}</c>. The
|
||||
/// options below are the ones minimal APIs use today (<c>JsonSerializerDefaults.Web</c>),
|
||||
/// so registering this context changes no byte on a non-AOT build.
|
||||
/// </summary>
|
||||
[JsonSourceGenerationOptions(
|
||||
PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase,
|
||||
PropertyNameCaseInsensitive = true,
|
||||
DefaultIgnoreCondition = JsonIgnoreCondition.Never)]
|
||||
[JsonSerializable(typeof(ErrorDto))]
|
||||
[JsonSerializable(typeof(ReadOnlyRefusalDto))]
|
||||
[JsonSerializable(typeof(NewBlockRequest))]
|
||||
[JsonSerializable(typeof(NewAllowRequest))]
|
||||
[JsonSerializable(typeof(NewRuleRequest))]
|
||||
[JsonSerializable(typeof(NewRateRuleRequest))]
|
||||
[JsonSerializable(typeof(PolicyUpdateRequest))]
|
||||
[JsonSerializable(typeof(BlockDto))]
|
||||
[JsonSerializable(typeof(AllowDto))]
|
||||
[JsonSerializable(typeof(RuleDto))]
|
||||
[JsonSerializable(typeof(RateRuleDto))]
|
||||
[JsonSerializable(typeof(PolicyDto))]
|
||||
[JsonSerializable(typeof(NetblockDto))]
|
||||
[JsonSerializable(typeof(RateSourceDto))]
|
||||
[JsonSerializable(typeof(ObservationDto))]
|
||||
[JsonSerializable(typeof(StreakDto))]
|
||||
[JsonSerializable(typeof(HistoryEvent))]
|
||||
[JsonSerializable(typeof(HorizonRow))]
|
||||
[JsonSerializable(typeof(HorizonAfter))]
|
||||
[JsonSerializable(typeof(SearchHit))]
|
||||
[JsonSerializable(typeof(ImpactSource))]
|
||||
[JsonSerializable(typeof(ImpactRow))]
|
||||
[JsonSerializable(typeof(ConfigImportDocument))]
|
||||
[JsonSerializable(typeof(RejectedItem))]
|
||||
internal partial class EdgeJson : JsonSerializerContext;
|
||||
@@ -1,3 +1,6 @@
|
||||
using System.Reflection;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Text.Json.Serialization.Metadata;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Options;
|
||||
using OpenWaf.Domain.Engine;
|
||||
@@ -21,6 +24,40 @@ if (args.Length > 0 && args[0] == "--healthcheck")
|
||||
|
||||
var builder = WebApplication.CreateBuilder(args);
|
||||
|
||||
// The source-generated JSON contract, at the head of the resolver chain. Without
|
||||
// it a NativeAOT edge never reaches the query wall: the host refuses to start
|
||||
// over a missing JsonTypeInfo for an admin request DTO (measured 2026-10-06,
|
||||
// 3 refusals, first type NewBlockRequest). On a non-AOT build the chain still
|
||||
// ends at the reflection resolver, so an unregistered type behaves exactly as it
|
||||
// did before — which is why the 19 anonymous response literals still standing are
|
||||
// a debt this records rather than a break it causes.
|
||||
builder.Services.ConfigureHttpJsonOptions(o =>
|
||||
{
|
||||
o.SerializerOptions.TypeInfoResolverChain.Insert(0, OpenWaf.Edge.Admin.EdgeJson.Default);
|
||||
// Two measurements, both made against this wiring, decide its shape.
|
||||
//
|
||||
// (1) A non-empty chain REPLACES the reflection resolver rather than
|
||||
// extending it. With only the context above in the chain, a type it does not
|
||||
// know fails on a JIT build with the same sentence the AOT probe reports —
|
||||
// `JsonTypeInfo metadata for type '<>f__AnonymousType0`1[System.String]' was
|
||||
// not provided by TypeInfoResolver of type '[EdgeJson]'` (standalone probe,
|
||||
// 2026-10-06). Eighteen anonymous response literals are still in this
|
||||
// project (the rest of the JSON wall, OPEN-79), so on a build that can
|
||||
// reflect, reflection stays at the end of the chain: the debt kept served and
|
||||
// visible rather than a break introduced in the middle of a slice.
|
||||
//
|
||||
// (2) That fallback is not free on the other side. Naming
|
||||
// DefaultJsonTypeInfoResolver in an AOT publish drags the reflection-based
|
||||
// JSON stack into the native image: measured 2026-10-07, the publish step ran
|
||||
// 66 minutes and never finished, against 232 s for the same Dockerfile
|
||||
// without it. `RuntimeFeature.IsDynamicCodeCompiled` is a constant the AOT
|
||||
// compiler substitutes, so on the shipped binary this branch — and the
|
||||
// resolver it names — is not there at all, and the chain is exactly the
|
||||
// compiled contract.
|
||||
if (RuntimeFeature.IsDynamicCodeCompiled)
|
||||
o.SerializerOptions.TypeInfoResolverChain.Add(new DefaultJsonTypeInfoResolver());
|
||||
});
|
||||
|
||||
builder.Services.Configure<EdgePolicyOptions>(builder.Configuration.GetSection("OpenWaf:Policy"));
|
||||
builder.Services.AddSingleton(sp => sp.GetRequiredService<IOptions<EdgePolicyOptions>>().Value.ToPolicy());
|
||||
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
using Microsoft.AspNetCore.Http.Metadata;
|
||||
using Microsoft.AspNetCore.Routing;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using OpenWaf.Edge.Admin;
|
||||
|
||||
namespace OpenWaf.Tests.Integration;
|
||||
|
||||
/// <summary>
|
||||
/// The AOT half of the admin API, checked on the tree that still ships JIT.
|
||||
///
|
||||
/// Measured on 2026-10-06, the NativeAOT edge does not reach the query wall at
|
||||
/// all: the host refuses to start with <c>JsonTypeInfo metadata for type
|
||||
/// 'OpenWaf.Edge.Admin.NewBlockRequest' was not provided by TypeInfoResolver</c>
|
||||
/// (3 refusals in the probe window, first type named). A JIT build never notices,
|
||||
/// because it falls back to a reflection resolver that an AOT binary does not
|
||||
/// have — so the failure is invisible here until it is a dead container there.
|
||||
///
|
||||
/// This test asks the running edge which body types its endpoints accept, and
|
||||
/// demands a compiled contract for each one. It reads the answer from the live
|
||||
/// endpoint table rather than from a list kept by hand, so an endpoint added
|
||||
/// without a contract is red here and not in the weekly probe.
|
||||
///
|
||||
/// The count assertion is not decoration: a guard that walks an empty set passes,
|
||||
/// and the empty set is exactly what a metadata change would produce. The number
|
||||
/// below is the measured count of distinct request-body types this edge accepts.
|
||||
/// </summary>
|
||||
public sealed class AotJsonContractTests
|
||||
{
|
||||
private const int ExpectedBodyTypeCount = 5;
|
||||
|
||||
[Fact]
|
||||
public async Task Every_request_body_the_edge_accepts_has_a_compiled_json_contract()
|
||||
{
|
||||
await using var f = new EdgeFixture(threshold: 9);
|
||||
var source = f.Factory.Services.GetRequiredService<EndpointDataSource>();
|
||||
|
||||
var bodies = new HashSet<Type>();
|
||||
foreach (var endpoint in source.Endpoints)
|
||||
foreach (var metadata in endpoint.Metadata)
|
||||
if (metadata is IAcceptsMetadata accepts && accepts.RequestType is { } body)
|
||||
bodies.Add(body);
|
||||
|
||||
// The set has to be non-empty and the right size, or the assertion below
|
||||
// is vacuous. 5: NewBlockRequest, NewAllowRequest, NewRuleRequest,
|
||||
// NewRateRuleRequest, PolicyUpdateRequest — measured, not assumed.
|
||||
Assert.Equal(ExpectedBodyTypeCount, bodies.Count);
|
||||
|
||||
var missing = bodies
|
||||
.Where(t => EdgeJson.Default.GetTypeInfo(t) is null)
|
||||
.Select(t => t.FullName)
|
||||
.OrderBy(n => n, StringComparer.Ordinal)
|
||||
.ToList();
|
||||
|
||||
Assert.True(missing.Count == 0,
|
||||
"these request bodies have no source-generated contract, so a NativeAOT edge "
|
||||
+ "will not start on them: " + string.Join(", ", missing));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void The_generated_contract_uses_the_wire_names_the_operator_reads()
|
||||
{
|
||||
// The camelCase generation option is load-bearing. Without it the same
|
||||
// record answers {"Error": …} and every consumer of this API — the
|
||||
// console, the smoke gate, the operator's scripts — reads a body with no
|
||||
// error in it. Asserted on the contract itself, so the regression is
|
||||
// caught without waiting for a page to go blank.
|
||||
var info = EdgeJson.Default.GetTypeInfo(typeof(ErrorDto));
|
||||
Assert.NotNull(info);
|
||||
|
||||
var names = info!.Properties
|
||||
.Select(p => p.Name)
|
||||
.OrderBy(n => n, StringComparer.Ordinal)
|
||||
.ToList();
|
||||
Assert.Equal(new[] { "error" }, names);
|
||||
|
||||
var refusal = EdgeJson.Default.GetTypeInfo(typeof(ReadOnlyRefusalDto));
|
||||
Assert.NotNull(refusal);
|
||||
Assert.Equal(
|
||||
new[] { "error", "tokenLevel" },
|
||||
refusal!.Properties.Select(p => p.Name)
|
||||
.OrderBy(n => n, StringComparer.Ordinal)
|
||||
.ToArray());
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user