Files
Pavlo Ratushnyi 718dcaaba3 a second token can read the operator's surfaces and change none of them
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.
2026-10-05 04:57:59 +02:00

126 lines
6.8 KiB
C#

namespace OpenWaf.Domain.Security;
// ---------------------------------------------------------------------------
// Two tokens, two levels of power (OPEN-62).
//
// There used to be one admin secret, and it was all-or-nothing: whatever could
// read /admin-api/state could also delete every block and rewrite the policy.
// The operator's real question is never "does this thing know the secret" but
// "what is this thing allowed to do" — a Prometheus scrape and a human
// checking why a customer was refused should not hold a key that can clear the
// block list.
//
// The level is decided by the request method, not by a flag on each endpoint,
// and that is a ruling rather than a shortcut: a new write endpoint is
// protected the moment it is written, while a per-endpoint flag would fail the
// other way — forget it once and the write is open to a read-only token.
//
// The functions here are pure and the comparison is constant-time, so the one
// place a secret is compared stays in one place. AdminAuth used to own that
// comparison; it now asks this type, because a second copy of a secret check is
// how one of the two ends up stale.
// ---------------------------------------------------------------------------
/// <summary>What a presented token may do. <see cref="None"/> means the token is
/// not one this edge knows — the answer to that is 401, and it must stay
/// distinguishable from <see cref="ReadOnly"/>, which is a known token that
/// simply lacks the right (403).</summary>
public enum AdminTokenLevel { None, ReadOnly, Full }
public static class AdminTokenPolicy
{
/// <summary>The key that grants everything, as the operator has to type it.</summary>
public const string FullKey = "OpenWaf__Admin__Token";
/// <summary>The key that grants reading only.</summary>
public const string ReadOnlyKey = "OpenWaf__Admin__ReadOnlyToken";
/// <summary>What a read-only token is told when it reaches a write surface.
/// It names the key that would grant the write, because the operator
/// debugging a failing script is the audience for this sentence.</summary>
public const string ReadOnlyRefusal =
"this token is read-only: it can read the operator surfaces but not change them; " +
$"the write surfaces need {FullKey}";
/// <summary>A blank or whitespace token is not a configured token. The
/// configuration system distinguishes "" from unset and the edge has
/// learned the hard way that treating them differently here would be a
/// surprise, so both mean "this level does not exist".</summary>
public static bool IsConfigured(string? token) => !string.IsNullOrWhiteSpace(token);
/// <summary>
/// A configuration that cannot mean what it says, named before the edge
/// starts serving. Two cases, and both are refusals rather than warnings:
///
/// * a read-only token equal to the admin token makes the read-only claim
/// false — every "look but do not change" promise would be a promise
/// about a token that can change everything, which is worse than having
/// no such promise at all;
/// * a read-only token with no admin token configures a level on a surface
/// that is closed: the admin token is what opens the surface, so the
/// operator would be handed a 404 and no explanation.
///
/// The equality test trims. A token read out of a file or an env pair often
/// carries a trailing newline, and "different by a newline" is exactly the
/// difference a security check must not be relying on. Authentication
/// itself compares the bytes as configured — this trim is only for deciding
/// that the two keys were meant to be different secrets.
/// </summary>
/// <returns>The problem, or null when the pair is usable.</returns>
public static string? ExplainConfigurationProblem(string? fullToken, string? readOnlyToken)
{
if (!IsConfigured(readOnlyToken)) return null;
if (!IsConfigured(fullToken))
return $"{ReadOnlyKey} is set while {FullKey} is not: the admin token is what opens " +
"the operator surfaces, so a read-only token on its own would only ever be answered 404. " +
"Set an admin token, or remove the read-only one.";
if (string.Equals(fullToken!.Trim(), readOnlyToken!.Trim(), StringComparison.Ordinal))
return $"{ReadOnlyKey} is the same value as {FullKey}: a read-only token that is also the " +
"admin token can change everything, so the read-only claim would be false. " +
"Give the read-only token its own value.";
return null;
}
/// <summary>Which level a presented token has. Compared against at most the
/// two configured tokens — there is no token list and no lookup table, so
/// the number of comparisons a request costs is fixed at two.</summary>
public static AdminTokenLevel LevelOf(string? provided, string? fullToken, string? readOnlyToken)
{
if (string.IsNullOrWhiteSpace(provided)) return AdminTokenLevel.None;
// Full is checked first on purpose. The startup refusal above makes
// "both tokens are the same value" unstartable; if a process is still
// configured that way by some path this build did not predict, the
// honest answer is the level the value actually has, not a downgrade of
// a token that can in fact write.
if (Matches(provided, fullToken)) return AdminTokenLevel.Full;
if (Matches(provided, readOnlyToken)) return AdminTokenLevel.ReadOnly;
return AdminTokenLevel.None;
}
/// <summary>Is this method a read? GET, HEAD and OPTIONS ask for a
/// representation and change nothing, so both tokens may do them. Everything
/// else — POST, PUT, PATCH, DELETE — is a write and needs the admin token.
/// Unknown methods count as writes: failing closed is the whole point of
/// deciding by method.</summary>
public static bool IsRead(string? httpMethod)
=> httpMethod is not null
&& (string.Equals(httpMethod, "GET", StringComparison.OrdinalIgnoreCase)
|| string.Equals(httpMethod, "HEAD", StringComparison.OrdinalIgnoreCase)
|| string.Equals(httpMethod, "OPTIONS", StringComparison.OrdinalIgnoreCase));
/// <summary>Constant-time on purpose: the comparison is against a secret,
/// and a comparison that returns early on the first wrong byte tells an
/// attacker how far their guess got.</summary>
private static bool Matches(string provided, string? configured)
{
if (!IsConfigured(configured)) return false;
return System.Security.Cryptography.CryptographicOperations.FixedTimeEquals(
System.Text.Encoding.UTF8.GetBytes(provided),
System.Text.Encoding.UTF8.GetBytes(configured!));
}
}