Files
Pavlo Ratushnyi fb758900b8 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.
2026-10-07 08:35:51 +02:00

125 lines
6.6 KiB
C#

using Microsoft.AspNetCore.Http;
using OpenWaf.Domain.Security;
namespace OpenWaf.Edge.Admin;
/// <summary>
/// The one token check the operator's surfaces share (OPEN-58), now with two
/// levels of power (OPEN-62).
///
/// It used to live inline on the admin API group. It is a type now because the
/// metrics endpoint needs the same rule and a second copy of an auth check is
/// the kind of duplication that ends with one of the two being updated: the
/// admin surface was already carrying a decision about the query string that a
/// second implementation would not have known about.
///
/// What is new is that knowing a token is no longer one answer. The admin token
/// reads and writes; the read-only token reads. Which of the two a request
/// needs is decided by the method — see <see cref="AdminTokenPolicy.IsRead"/> —
/// so a write endpoint added tomorrow is behind this rule without anyone
/// remembering to mark it. The secret comparison itself moved to
/// <see cref="AdminTokenPolicy"/> so there is exactly one place in the build
/// where a token is compared to a configured token.
///
/// Unchanged: no token configured means the surface is closed rather than open
/// without auth, and the query string is accepted but named out loud, because a
/// URL is the part of a request that access logs, proxies and browser histories
/// keep.
/// </summary>
internal static class AdminAuth
{
/// <summary>The header an operator is asked to use. The query string is
/// tolerated, not recommended, and the warning says so.</summary>
public const string Header = "X-Admin-Token";
/// <summary>Where the level decided for this request is parked, so an
/// endpoint-level filter can ask what the group filter already settled
/// without comparing the secret a second time.</summary>
private const string LevelItem = "openwaf:admin-token-level";
/// <summary>The shape <c>AddEndpointFilter</c> takes. Named as a Func rather
/// than as <c>EndpointFilterDelegate</c> because that delegate type is the
/// inner link of the chain, not the thing the registration accepts — the
/// two have different arities, and the compiler only figures that out for a
/// lambda written inline at the call site.</summary>
public static Func<EndpointFilterInvocationContext, EndpointFilterDelegate, ValueTask<object?>> Require(
string? adminToken, string? readOnlyToken, string disabledMessage)
=> async (filterCtx, next) =>
{
if (!AdminTokenPolicy.IsConfigured(adminToken))
return Results.NotFound(new ErrorDto(disabledMessage));
var req = filterCtx.HttpContext.Request;
var provided = req.Headers[Header].ToString();
var viaQuery = false;
if (string.IsNullOrWhiteSpace(provided))
{
provided = req.Query["token"].ToString();
viaQuery = !string.IsNullOrWhiteSpace(provided);
}
var level = AdminTokenPolicy.LevelOf(provided, adminToken, readOnlyToken);
if (level == AdminTokenLevel.None) return Results.Unauthorized();
// The query string is accepted for one reason: an operator typing
// curl at a keyboard does it without thinking, and refusing them is
// how an operator ends up disabling the auth instead of learning the
// header. What is NOT acceptable is doing it silently. A URL is the
// one part of a request that every access log, proxy log and browser
// history keeps, and at the shipped log level the edge does not log
// URLs - but raising Microsoft.AspNetCore to Information, which is
// the ordinary next move when something is misbehaving, makes
// Kestrel log the full URL including this token. Measured on the
// shipped image: one query-string request leaves 0 lines containing
// the token at the shipped level and 2 at Information ("Request
// starting" and "Request finished"), and a header request leaves 0
// at either. So the request is served and the moment it happens is
// named, without ever repeating the secret. It applies to the
// read-only token exactly as it applies to the admin one: a weaker
// token is still a token.
if (viaQuery)
{
filterCtx.HttpContext.RequestServices
.GetRequiredService<ILoggerFactory>()
.CreateLogger("OpenWaf.Admin")
.LogWarning(
"admin token was presented in the query string on {Path}; URLs are what access logs, " +
"proxies and browser histories keep, so prefer the X-Admin-Token header. The token is " +
"not repeated here.",
req.Path.Value);
}
filterCtx.HttpContext.Items[LevelItem] = level;
// A known token that lacks the right is a different answer from an
// unknown one, and the difference is the whole point of the feature:
// 401 would tell an operator debugging a script that the token is
// wrong, when what is wrong is the endpoint it was sent to.
if (level == AdminTokenLevel.ReadOnly && !AdminTokenPolicy.IsRead(req.Method))
return Results.Json(
new ReadOnlyRefusalDto(AdminTokenPolicy.ReadOnlyRefusal, "read-only"),
statusCode: StatusCodes.Status403Forbidden);
return await next(filterCtx);
};
/// <summary>
/// A surface that reads but is not for a read-only token.
///
/// There is exactly one: <c>GET /admin-api/export</c>. The exported document
/// is the edge's whole operator config — every block, exemption, rule and
/// policy override — and OPEN-61 itself files it under "a capability, not a
/// backup". The token meant for a dashboard and for a second pair of eyes is
/// precisely the one that must not be able to lift it, so this read is
/// deliberately held to the admin token while every other read is not.
/// </summary>
public static Func<EndpointFilterInvocationContext, EndpointFilterDelegate, ValueTask<object?>> RequireFull(
string refusal)
=> (filterCtx, next) =>
filterCtx.HttpContext.Items[LevelItem] is AdminTokenLevel.ReadOnly
? new ValueTask<object?>(Results.Json(
new ReadOnlyRefusalDto(refusal, "read-only"),
statusCode: StatusCodes.Status403Forbidden))
: next(filterCtx);
}