From 842b70566f54b17aaaf1bb1ed35cbbcf37d276c5 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Thu, 1 Oct 2026 20:27:06 +0200 Subject: [PATCH] The query-string token is kept, but it no longer happens silently ?token= on the admin API is an affordance for an operator typing curl; the console never uses it and none of the gates do (0 occurrences of token= in scripts/). Refusing it is how an operator ends up switching auth off instead of learning the header. What was wrong was the silence. Measured on the shipped image before deciding: a container hit with /admin-api/state?token= logged 0 lines containing the token at the shipped level (Microsoft.AspNetCore: Warning), and 2 lines at Microsoft.AspNetCore=Information, including the full URL. Raising that level is the ordinary next move while debugging, so the leak is one environment variable away, not a hypothetical. Now a request authenticated by the query string logs a warning naming the path and never the token. Two tests: the query form is served and named; the header form produces no such warning and no token anywhere in the captured logs. Teeth: delete the warning and exactly the query test fails (1 failed, 33 passed). Also refreshed the ci.yml header, whose Linux numbers had gone stale (54/54 + 30/30 + 41/41 -> 59/59 + 32/32 + 43/43 + 33/33), and kept the wall clock quoted as measured once rather than current. Gates: build 0 warnings, unit 59/59, integration 34/34, actionlint 0 problems. --- .github/workflows/ci.yml | 22 +++-- README.md | 13 +++ dotnet/OpenWaf.Edge/Admin/AdminEndpoints.cs | 49 ++++++++++- .../AdminTokenTransportTests.cs | 84 +++++++++++++++++++ 4 files changed, 154 insertions(+), 14 deletions(-) create mode 100644 dotnet/OpenWaf.Tests.Integration/AdminTokenTransportTests.cs diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 0d12722..e8e59d0 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -16,18 +16,16 @@ # What has been done to narrow the darwin/linux gap without a runner: # scripts/ci-linux-rehearsal.sh runs the gates in containers. Source gates # (restore, build, unit, integration, smoke) in mcr.microsoft.com/dotnet/sdk:10.0 -# — Ubuntu 24.04.5, SDK 10.0.401 resolving the pinned global.json, 54/54 + 30/30 -# + 19/19, first try, 1:02.81 wall cold: evidence that the 25-minute timeout -# below is not near. Compose gate in docker:cli against the host daemon: 41/41 on -# Linux. Console gate in mcr.microsoft.com/playwright:v1.63.0-noble — the stack -# seeded by docker:cli, the same console-check.cjs driving it in a real Linux -# Chromium: 33/33. So every gate this file runs now has a Linux number. What it -# does not have is a runner: the repository has no remote, so this file has -# never executed on GitHub. -# -# One gate is not in this file: geo database freshness. It is a schedule, not a -# push gate (the pin ages on the vendor's calendar, not on ours), so it lives in -# .github/workflows/geo-freshness.yml and calls scripts/geo-db-freshness.sh. +# - Ubuntu 24.04.5, SDK 10.0.401 resolving the pinned global.json: unit 59/59, +# integration 32/32, smoke 19/19, first try. Compose gate in docker:cli against +# the host daemon: 43/43 on Linux. Console gate in +# mcr.microsoft.com/playwright:v1.63.0-noble - the stack seeded by docker:cli, +# the same console-check.cjs driving it in a real Linux Chromium: 33/33. The +# only wall clock ever measured for the source job is 1:02.81 cold (first +# rehearsal); later rehearsals were not re-timed, so that number is quoted as +# measured once, not as current. So every gate this file runs has a Linux +# number. What it does not have is a runner: the repository has no remote, so +# this file has never executed on GitHub. name: ci diff --git a/README.md b/README.md index 5bd234d..86504f1 100644 --- a/README.md +++ b/README.md @@ -215,6 +215,19 @@ manages the schema themselves. Requires `X-Admin-Token` (or `?token=`). **No token configured means the admin API is closed**, not open. +The header is the form to use. The query string is accepted anyway, because an +operator at a keyboard types `?token=` without thinking and the wrong answer to +that is an operator who switches auth off. It is not silent: a request +authenticated by the query string logs a warning naming the path — never the +token. The reason is measured, not assumed. At the shipped log level +(`Microsoft.AspNetCore: Warning`) the edge logs no URLs, and a container run +with `?token=` in the URL produced **0** lines containing the token; raise +`Microsoft.AspNetCore` to `Information` — the ordinary next move while debugging +something — and Kestrel logs the full URL, producing **2** such lines. The tests +are `A_token_in_the_query_string_is_served_but_named_in_the_log_without_the_secret` +and `A_token_in_the_header_produces_no_such_warning_because_it_is_the_form_we_ask_for`; +delete the warning and exactly the first one fails. + ``` GET /admin-api/blocks?source=operator|engine&live=true POST /admin-api/blocks {"ip","reason","redirectTo"} diff --git a/dotnet/OpenWaf.Edge/Admin/AdminEndpoints.cs b/dotnet/OpenWaf.Edge/Admin/AdminEndpoints.cs index fbee9f4..847d5af 100644 --- a/dotnet/OpenWaf.Edge/Admin/AdminEndpoints.cs +++ b/dotnet/OpenWaf.Edge/Admin/AdminEndpoints.cs @@ -1,4 +1,5 @@ using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; using OpenWaf.Domain.Engine; using OpenWaf.Domain.Policy; using OpenWaf.Domain.Security; @@ -30,8 +31,52 @@ internal static class AdminEndpoints var req = filterCtx.HttpContext.Request; var provided = req.Headers["X-Admin-Token"].ToString(); - if (string.IsNullOrWhiteSpace(provided)) provided = req.Query["token"].ToString(); - return FixedTimeEquals(provided, adminToken) ? await next(filterCtx) : Results.Unauthorized(); + var viaQuery = false; + if (string.IsNullOrWhiteSpace(provided)) + { + provided = req.Query["token"].ToString(); + viaQuery = !string.IsNullOrWhiteSpace(provided); + } + + if (!FixedTimeEquals(provided, adminToken)) 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: 0 token + // lines at the shipped level, 2 at Information). So the request is + // served and the moment it happens is named, without ever repeating + // the secret. + // 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: 0 token + // lines at the shipped level, 2 at Information). So the request is + // served and the moment it happens is named, without ever repeating + // the secret. + if (viaQuery) + { + filterCtx.HttpContext.RequestServices + .GetRequiredService() + .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); + } + + return await next(filterCtx); }); group.MapGet("/blocks", async (string? source, bool? live, int? limit, int? offset, BlockStore store, HttpContext ctx, CancellationToken ct) => diff --git a/dotnet/OpenWaf.Tests.Integration/AdminTokenTransportTests.cs b/dotnet/OpenWaf.Tests.Integration/AdminTokenTransportTests.cs new file mode 100644 index 0000000..dac8e6c --- /dev/null +++ b/dotnet/OpenWaf.Tests.Integration/AdminTokenTransportTests.cs @@ -0,0 +1,84 @@ +using System.Net; +using Microsoft.AspNetCore.Mvc.Testing; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using Microsoft.AspNetCore.TestHost; + +namespace OpenWaf.Tests.Integration; + +/// +/// The admin API accepts the token two ways: the X-Admin-Token header, and +/// ?token= in the query string for an operator typing curl. The second one is a +/// documented affordance, not a bug — but a URL is exactly what access logs, +/// proxies and browser histories keep. These tests pin the part that makes the +/// affordance safe to keep: the moment it is used, the edge says so, and it +/// never repeats the secret while doing it. +/// +public sealed class AdminTokenTransportTests +{ + private const string Token = "transport-test-token-4f3a"; + + private sealed class Capturing : ILoggerProvider + { + private readonly List _messages = []; + public IReadOnlyList Messages { get { lock (_messages) return _messages.ToList(); } } + public ILogger CreateLogger(string categoryName) => new Sink(this); + public void Dispose() { } + + private sealed class Sink(Capturing owner) : ILogger + { + public IDisposable? BeginScope(TState state) where TState : notnull => null; + public bool IsEnabled(LogLevel logLevel) => true; + public void Log(LogLevel logLevel, EventId eventId, TState state, Exception? exception, + Func formatter) + { + lock (owner._messages) owner._messages.Add(formatter(state, exception)); + } + } + } + + private static async Task<(HttpResponseMessage Response, Capturing Logs)> CallAsync( + bool viaQuery, string path) + { + var dbPath = Path.Combine(Path.GetTempPath(), $"openwaf-token-transport-{Guid.NewGuid():N}.db"); + var logs = new Capturing(); + using var factory = new WebApplicationFactory().WithWebHostBuilder(builder => + { + builder.UseSetting("ConnectionStrings:OpenWaf", $"Data Source={dbPath}"); + builder.UseSetting("Database:Provider", "sqlite"); + builder.UseSetting("OpenWaf:Admin:Token", Token); + builder.ConfigureTestServices(services => services.AddSingleton(logs)); + }); + + using var request = new HttpRequestMessage(HttpMethod.Get, + viaQuery ? $"{path}?token={Token}" : path); + if (!viaQuery) request.Headers.TryAddWithoutValidation("X-Admin-Token", Token); + + var response = await factory.CreateClient().SendAsync(request); + await factory.DisposeAsync(); + Microsoft.Data.Sqlite.SqliteConnection.ClearAllPools(); + if (File.Exists(dbPath)) File.Delete(dbPath); + return (response, logs); + } + + [Fact] + public async Task A_token_in_the_query_string_is_served_but_named_in_the_log_without_the_secret() + { + var (response, logs) = await CallAsync(viaQuery: true, "/admin-api/state"); + + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + var warning = logs.Messages.First(m => m.Contains("query string")); + Assert.DoesNotContain(Token, warning); + Assert.Contains("X-Admin-Token", warning); + } + + [Fact] + public async Task A_token_in_the_header_produces_no_such_warning_because_it_is_the_form_we_ask_for() + { + var (response, logs) = await CallAsync(viaQuery: false, "/admin-api/state"); + + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.DoesNotContain(logs.Messages, m => m.Contains("query string")); + Assert.DoesNotContain(Token, string.Join("\n", logs.Messages)); + } +}