One admin secret meant one thing: whatever could read /admin-api/state could also delete every block and rewrite the policy. A Prometheus scrape therefore held a key that can lift a ban, a second operator checking why a visitor was refused held a key that can change what the edge enforces, and OPEN-61's export put a whole edge's config behind the same single GET. The operator's question was never "does this thing know the secret" but "what is it allowed to do", and the shipped answer could only be all or nothing. OpenWaf:Admin:ReadOnlyToken (env OPENWAF_READ_ONLY_TOKEN) is the second level. Unset is the default and the whole of the previous behaviour. The rulings: * A known token without the right is answered 403, not 401, and the body names the key that would grant the write. Collapsing the two sentences sends someone debugging a failing script to check the secret when what is wrong is the endpoint it was sent to. * The line is drawn by the request method, not by a flag per endpoint: GET/HEAD/OPTIONS read, everything else writes. A write endpoint added tomorrow is behind the rule the moment it is written; a per-endpoint flag would fail the other way, and one forgotten flag would open the write. * GET /admin-api/export is the one read held to the admin token. It is a read and it is still the whole config, so it is the surface where "can read" and "can take" are the same act - and the dashboard token is exactly the one that must not be able to lift a fleet's config. * A read-only token sees byte-identical answers to the admin token. Read-only is about what a token may do, not about a weaker view: two people comparing answers must not get different answers because of who asked. * A read-only token equal to the admin token (compared after trimming, because env files add newlines) aborts startup naming both keys and never the secret. /admin-api/state answers readOnlyTokenConfigured, so the operator can check the key took effect instead of guessing from a 401. What the run caught, in order: (1) A real defect, and the interesting one. On the shipped image the startup refusal printed its reason and then the process sat at 100% CPU inside the runtime's crash path - the container stayed "Up (unhealthy)" forever, no exit code, nothing for a supervisor to react to. Refusing to start is only useful if the process leaves, so the refusal now writes the reason to stderr and returns 1; measured again on the image, it exits in 2 s with code 1 and the same sentence. (2) The gate's own assertion for that case had the same blind spot as the bug: waiting on a foreground docker compose run cannot tell "refused" from "hung", so the container is now started detached and polled for an exit within 30 s, and the assertion is that it left. (3) Two smoke asserts were wrong rather than the product: the blocks listing field is sourceKey, not ip, so the first version read an empty answer, and a two-code assertion compared a newline-separated pair against a space-separated literal. (4) An integration assert compared JsonElement.ToString() against "true" - a bool element prints True, so it now reads GetBoolean(). Gates on this tree: build 0 warnings / 0 errors, unit 307/307, integration 286/286 in 26s, smoke 105 passed / 0 failed (23 new), image 262 MB, compose-smoke 261 passed / 0 failed with 0 containers left behind (18 new, against the shipped image), console 90 assertions / 0 failed. Refs OPEN-62.
125 lines
6.6 KiB
C#
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 { error = 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 { error = AdminTokenPolicy.ReadOnlyRefusal, tokenLevel = "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 { error = refusal, tokenLevel = "read-only" },
|
|
statusCode: StatusCodes.Status403Forbidden))
|
|
: next(filterCtx);
|
|
}
|