diff --git a/dotnet/OpenWaf.Edge/Admin/AdminEndpoints.cs b/dotnet/OpenWaf.Edge/Admin/AdminEndpoints.cs index 04284c1..56d4249 100644 --- a/dotnet/OpenWaf.Edge/Admin/AdminEndpoints.cs +++ b/dotnet/OpenWaf.Edge/Admin/AdminEndpoints.cs @@ -71,6 +71,7 @@ internal static 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")) return Results.BadRequest(new { error = 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)) @@ -144,6 +145,7 @@ internal static 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")) return Results.BadRequest(new { error = unknown }); if (!TryPaging(limit, offset, AllowListDefaultLimit, AllowListMaxLimit, out var take, out var skip, out var pagingError)) return Results.BadRequest(new { error = pagingError }); @@ -273,13 +275,25 @@ internal static class AdminEndpoints return Results.Ok(ToDto(policy.Current)); }); - group.MapGet("/observations", async (OpenWafDbContext db, int? limit, int? offset, + group.MapGet("/observations", async (OpenWafDbContext db, string? source, int? limit, int? offset, HttpContext ctx, CancellationToken ct) => { + if (!TryKnownQuery(ctx, out var unknown, "source")) return Results.BadRequest(new { error = unknown }); if (!TryPaging(limit, offset, ReadListDefaultLimit, ReadListMaxLimit, out var take, out var skip, out var pagingError)) return Results.BadRequest(new { error = pagingError }); - var rows = await db.Observations.AsNoTracking() + // ?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 + // single row and make X-Truncated claim a cut that never happened. + var query = db.Observations.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" }); + query = query.Where(o => o.SourceKey == source); + } + var rows = await query .OrderByDescending(o => o.LastSeenAt) .Skip(skip) .Take(take) @@ -287,7 +301,7 @@ internal static class AdminEndpoints o.TotalRefusals, o.TotalServerErrorStreak, o.LastStatusCode, o.LastPath, o.LastCountryCode, o.LastCity)) .ToListAsync(ct); - var total = await db.Observations.CountAsync(ct); + var total = await query.CountAsync(ct); ctx.Response.Headers["X-Total-Count"] = total.ToString(); ctx.Response.Headers["X-Truncated"] = (skip + rows.Count < total).ToString().ToLowerInvariant(); return Results.Ok(rows); @@ -301,6 +315,7 @@ internal static class AdminEndpoints // threshold of 3 produced no ban at all. group.MapGet("/streaks", (StreakTracker tracker, EdgePolicyProvider policyProvider, HttpContext ctx, int? limit, int? offset) => { + if (!TryKnownQuery(ctx, out var unknown)) return Results.BadRequest(new { error = unknown }); var now = DateTimeOffset.UtcNow; var policy = policyProvider.Current; if (!TryPaging(limit, offset, StreakListDefaultLimit, StreakListMaxLimit, @@ -329,18 +344,26 @@ internal static class AdminEndpoints }); }); - group.MapGet("/alerts", async (OpenWafDbContext db, int? limit, int? offset, + group.MapGet("/alerts", async (OpenWafDbContext db, string? source, int? limit, int? offset, HttpContext ctx, CancellationToken ct) => { + if (!TryKnownQuery(ctx, out var unknown, "source")) return Results.BadRequest(new { error = unknown }); if (!TryPaging(limit, offset, ReadListDefaultLimit, ReadListMaxLimit, out var take, out var skip, out var pagingError)) return Results.BadRequest(new { error = pagingError }); - var rows = await db.Alerts.AsNoTracking() + 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" }); + query = query.Where(a => a.SourceKey == source); + } + var rows = await query .OrderByDescending(a => a.CreatedAt) .Skip(skip) .Take(take) .ToListAsync(ct); - var total = await db.Alerts.CountAsync(ct); + var total = await query.CountAsync(ct); ctx.Response.Headers["X-Total-Count"] = total.ToString(); ctx.Response.Headers["X-Truncated"] = (skip + rows.Count < total).ToString().ToLowerInvariant(); return Results.Ok(rows); @@ -527,6 +550,48 @@ internal static class AdminEndpoints IQueryable query, bool liveOnly, DateTimeOffset now) => liveOnly ? query.Where(a => a.ExpiresAt == null || a.ExpiresAt > now) : query; + /// + /// Does this endpoint know the query parameters it was sent? + /// + /// Measured on the shipped image before this existed: `GET + /// /admin-api/observations?source=203.0.113.11` answered 200 with every row + /// in the table and `X-Total-Count: 16` — the filter was not applied, not + /// refused, just absent, so an operator investigating one address was shown + /// fifteen other addresses and a total that matched them. The same held for + /// `?src=`, `?zzz=` and any other spelling on every list endpoint: minimal + /// APIs bind the parameters they know and drop the rest without a trace. + /// A parameter this endpoint has never heard of is now an answer that says + /// so and names what it does accept, because a silently dropped filter is + /// the same shape as the bug OPEN-23 found one level up, where an unknown + /// `?source=` VALUE meant "operator". + /// + /// `allowed` names the extra parameters beyond limit/offset that this + /// endpoint understands; the caller passes them so the refusal can list the + /// truth for that endpoint rather than a project-wide guess. + /// + private static bool TryKnownQuery(HttpContext ctx, out string? error, params string[] allowed) + { + // `token` is not a handler parameter — the admin auth layer reads it out + // of the query string, and OPEN-16 ruled that the curl-friendly form + // stays supported while the console never uses it. A guard that does not + // know the whole surface refuses a request that works, which is a worse + // bug than the one it prevents: three existing integration tests call + // /admin-api/blocks?token=… and were right to. + var known = new HashSet(StringComparer.OrdinalIgnoreCase) { "limit", "offset", "token" }; + foreach (var extra in allowed) known.Add(extra); + error = null; + foreach (var key in ctx.Request.Query.Keys) + { + if (!known.Contains(key)) + { + var accepts = string.Join(", ", known.OrderBy(k => k, StringComparer.Ordinal)); + error = $"unknown query parameter '{key}'; this endpoint accepts {accepts}"; + return false; + } + } + return true; + } + private static bool TryPaging(int? limit, int? offset, int defaultLimit, int maxLimit, out int take, out int skip, out string? error) { diff --git a/dotnet/OpenWaf.Tests.Integration/QueryHonestyTests.cs b/dotnet/OpenWaf.Tests.Integration/QueryHonestyTests.cs new file mode 100644 index 0000000..07bd8ea --- /dev/null +++ b/dotnet/OpenWaf.Tests.Integration/QueryHonestyTests.cs @@ -0,0 +1,153 @@ +using System.Net; +using System.Text.Json; +using Microsoft.Extensions.DependencyInjection; +using OpenWaf.Domain.Security; +using OpenWaf.Infrastructure.Persistence; + +namespace OpenWaf.Tests.Integration; + +/// +/// A query parameter the endpoint has never heard of used to be dropped without +/// a trace, and the answer kept its shape. Measured on the shipped image +/// (openwaf:ci, 2026-10-02) with 16 recorded sources: +/// +/// GET /admin-api/observations?source=203.0.113.11 +/// → 200, 16 rows over 16 different addresses, X-Total-Count: 16 +/// GET /admin-api/observations?src=203.0.113.11 +/// → 200, the same 16 rows +/// +/// Nothing said the filter had not been applied. An operator investigating one +/// address was handed fifteen other addresses and a total that matched those +/// fifteen, which is the same shape as the bug OPEN-23 found one level up — an +/// unknown `?source=` VALUE quietly meaning "operator". Minimal APIs bind the +/// parameters a handler declares and discard the rest, so the fix has to be a +/// refusal that names the parameter and lists what the endpoint accepts, plus a +/// filter that actually filters when the question is a fair one to ask. +/// +public sealed class QueryHonestyTests +{ + private static string? Header(HttpResponseMessage r, string name) + => r.Headers.TryGetValues(name, out var a) ? string.Join(",", a) + : r.Content.Headers.TryGetValues(name, out var b) ? string.Join(",", b) + : null; + + private static async Task<(HttpStatusCode Status, string Text, string? Total, string? Truncated)> GetAsync( + EdgeFixture f, string url) + { + using var request = new HttpRequestMessage(HttpMethod.Get, url); + request.Headers.TryAddWithoutValidation("X-Admin-Token", EdgeFixture.AdminToken); + using var response = await f.Client.SendAsync(request); + return (response.StatusCode, await response.Content.ReadAsStringAsync(), + Header(response, "X-Total-Count"), Header(response, "X-Truncated")); + } + + private static async Task SeedObservationsAsync(EdgeFixture f, params string[] ips) + { + foreach (var ip in ips) await f.SendAsync(f.Client, "/nope", ip); + await f.FlushObservationsAsync(); + } + + [Theory] + [InlineData("/admin-api/observations")] + [InlineData("/admin-api/alerts")] + [InlineData("/admin-api/blocks")] + [InlineData("/admin-api/allow")] + [InlineData("/admin-api/streaks")] + public async Task A_parameter_the_endpoint_never_implemented_is_refused_and_names_itself(string path) + { + await using var f = new EdgeFixture(threshold: 9); + var r = await GetAsync(f, $"{path}?zzz=1"); + Assert.Equal(HttpStatusCode.BadRequest, r.Status); + Assert.Contains("unknown query parameter 'zzz'", r.Text); + // The refusal has to be actionable: naming the bad parameter without + // naming the good ones leaves the operator guessing which spelling works. + Assert.Contains("limit", r.Text); + } + + [Fact] + public async Task A_source_filter_returns_only_that_source_and_counts_only_that_source() + { + await using var f = new EdgeFixture(threshold: 9); + await SeedObservationsAsync(f, "203.0.113.201", "203.0.113.202", "203.0.113.203"); + + var all = await GetAsync(f, "/admin-api/observations?limit=1000"); + Assert.Equal("3", all.Total); + + var one = await GetAsync(f, "/admin-api/observations?limit=1000&source=203.0.113.202"); + Assert.Equal(HttpStatusCode.OK, one.Status); + // The total answers the question that was asked. Counting the table while + // showing one row would put a 3 next to a single row and make X-Truncated + // claim a cut that never happened. + Assert.Equal("1", one.Total); + Assert.Equal("false", one.Truncated); + var body = JsonDocument.Parse(one.Text).RootElement; + Assert.Equal(1, body.GetArrayLength()); + Assert.Equal("203.0.113.202", body[0].GetProperty("sourceKey").GetString()); + } + + [Fact] + public async Task A_source_with_no_rows_answers_empty_and_says_the_total_is_zero() + { + await using var f = new EdgeFixture(threshold: 9); + await SeedObservationsAsync(f, "203.0.113.201"); + + var r = await GetAsync(f, "/admin-api/observations?limit=1000&source=198.51.100.77"); + Assert.Equal(HttpStatusCode.OK, r.Status); + Assert.Equal("0", r.Total); + Assert.Equal("[]", r.Text); + } + + [Fact] + public async Task An_empty_source_is_refused_rather_than_read_as_every_source() + { + await using var f = new EdgeFixture(threshold: 9); + await SeedObservationsAsync(f, "203.0.113.201"); + + var r = await GetAsync(f, "/admin-api/observations?limit=1000&source="); + Assert.Equal(HttpStatusCode.BadRequest, r.Status); + Assert.Contains("source must not be empty", r.Text); + } + + [Fact] + public async Task The_alert_listing_filters_by_source_and_leaves_the_others_out() + { + await using var f = new EdgeFixture(threshold: 9); + var now = DateTimeOffset.UtcNow; + using (var scope = f.Factory.Services.CreateScope()) + { + var db = scope.ServiceProvider.GetRequiredService(); + for (var i = 1; i <= 3; i++) + db.Alerts.Add(new EdgeAlert + { + SourceKey = i == 2 ? "203.0.113.212" : "203.0.113.211", Kind = "server_error_streak", + Count = i, CreatedAt = now.AddMinutes(-i), Detail = "seeded for the filter" + }); + await db.SaveChangesAsync(); + } + + var all = await GetAsync(f, "/admin-api/alerts?limit=1000"); + Assert.Equal("3", all.Total); + + var one = await GetAsync(f, "/admin-api/alerts?limit=1000&source=203.0.113.212"); + Assert.Equal("1", one.Total); + var body = JsonDocument.Parse(one.Text).RootElement; + Assert.Equal(1, body.GetArrayLength()); + Assert.Equal("203.0.113.212", body[0].GetProperty("sourceKey").GetString()); + } + + [Theory] + [InlineData("/admin-api/blocks?source=engine&live=false&limit=1&offset=0")] + [InlineData("/admin-api/allow?live=false&limit=500")] + [InlineData("/admin-api/observations?limit=2&offset=1")] + [InlineData("/admin-api/streaks?limit=1000")] + public async Task The_parameters_the_endpoint_does_implement_keep_working(string url) + { + // The refusal is only worth having if it never fires on a parameter the + // endpoint really does honour — the console and both smoke gates call + // these with live/source/limit/offset every run. + await using var f = new EdgeFixture(threshold: 9); + var r = await GetAsync(f, url); + Assert.NotEqual(HttpStatusCode.BadRequest, r.Status); + Assert.DoesNotContain("unknown query parameter", r.Text); + } +} diff --git a/scripts/compose-smoke.sh b/scripts/compose-smoke.sh index 2a8dcfd..691fa76 100755 --- a/scripts/compose-smoke.sh +++ b/scripts/compose-smoke.sh @@ -322,6 +322,41 @@ else FAIL=$((FAIL+1)); printf ' FAIL %-54s no country resolved for %s\n' 'geo pillar' "$GEO_IP" fi +echo '- a filter nobody implemented is refused, and the one that is filters' +# Measured on the shipped image before this scene existed: with 16 recorded +# sources, GET /admin-api/observations?source=203.0.113.11 answered 200 with all +# 16 rows over 16 different addresses and X-Total-Count: 16. The filter was not +# applied and not refused — it was absent, because minimal APIs bind the +# parameters a handler declares and drop the rest. ?src= did the same. An +# operator investigating one address was handed fifteen other addresses and a +# total that matched those fifteen. +code -H "$(xff 203.0.113.250)" "$EDGE/filter-me" >/dev/null +FILTER_ROWS=0 +for _ in $(seq 1 12); do + FILTER_ROWS=$(admin "$EDGE/admin-api/observations?limit=1000&source=203.0.113.250" \ + | jcount "b['sourceKey']=='203.0.113.250'") + [ "${FILTER_ROWS:-0}" != "0" ] && break + sleep 3 +done +printf ' info rows the source filter returns for a source this run just created: %s\n' "$FILTER_ROWS" +check 'the source filter returns the source it was asked for' '1' "$FILTER_ROWS" +check 'and no other source' '0' \ + "$(admin "$EDGE/admin-api/observations?limit=1000&source=203.0.113.250" | jcount "b['sourceKey']!='203.0.113.250'")" +check 'the total counts the filtered set, not the table' 'X-Total-Count: 1' \ + "$(hdr -H "X-Admin-Token: $OPENWAF_ADMIN_TOKEN" "$EDGE/admin-api/observations?limit=1000&source=203.0.113.250" \ + | grep -i '^x-total-count:' | tr -d '\r')" +check 'a parameter this endpoint has never heard of is refused, by name' 'yes' \ + "$(admin "$EDGE/admin-api/observations?limit=1000&zzz=1" | grep -qi "unknown query parameter 'zzz'" && echo yes || echo no)" +check 'and so is a near miss of the parameter that does work' 'yes' \ + "$(admin "$EDGE/admin-api/observations?limit=1000&src=203.0.113.250" | grep -qi "unknown query parameter 'src'" && echo yes || echo no)" +check 'the alert listing refuses it the same way' 'yes' \ + "$(admin "$EDGE/admin-api/alerts?limit=1000&zzz=1" | grep -qi "unknown query parameter 'zzz'" && echo yes || echo no)" +# The guard is only worth having if it never fires on a parameter the endpoint +# really does honour — the console calls this one with live/source/limit every +# page load, and a refusal there would be a worse bug than the one prevented. +check 'while the parameters the endpoint really does honour still work' '200' \ + "$(code -H "X-Admin-Token: $OPENWAF_ADMIN_TOKEN" "$EDGE/admin-api/blocks?live=false&source=engine&limit=500")" + echo '- a pillar that stops reading its table says so' # Measured on the shipped image before this was fixed: with policy_settings # dropped out from under a running edge, GET /admin-api/policy kept answering the