diff --git a/dotnet/OpenWaf.Edge/Admin/AdminEndpoints.cs b/dotnet/OpenWaf.Edge/Admin/AdminEndpoints.cs index 6901957..e2868f8 100644 --- a/dotnet/OpenWaf.Edge/Admin/AdminEndpoints.cs +++ b/dotnet/OpenWaf.Edge/Admin/AdminEndpoints.cs @@ -71,7 +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 (!TryKnownQuery(ctx, out var unknown, "source", "live", "limit", "offset")) 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)) @@ -86,8 +86,9 @@ internal static class AdminEndpoints return Results.Ok(rows.Select(r => r.ToDto(now))); }); - group.MapPost("/blocks", async (NewBlockRequest req, BlockStore store, CancellationToken ct) => + group.MapPost("/blocks", async (NewBlockRequest req, BlockStore store, HttpContext ctx, CancellationToken ct) => { + if (!TryKnownQuery(ctx, out var unknown)) return Results.BadRequest(new { error = unknown }); if (string.IsNullOrWhiteSpace(req.Ip)) return Results.BadRequest(new { error = "ip is required" }); if (!EntryLimits.NoteOk(req.Reason)) return Results.BadRequest(new { error = $"reason must be at most {EntryLimits.NoteMaxLength} characters; got {req.Reason!.Length}" }); @@ -113,8 +114,9 @@ internal static class AdminEndpoints // Provenance is part of the delete, not an afterthought: "clear the // automatic bans" must never be able to erase an operator's list. - group.MapDelete("/blocks", async (string? source, string? key, BlockStore store, CancellationToken ct) => + group.MapDelete("/blocks", async (string? source, string? key, BlockStore store, HttpContext ctx, CancellationToken ct) => { + if (!TryKnownQuery(ctx, out var unknown, "source", "key")) return Results.BadRequest(new { error = unknown }); if (!TryParseSource(source, out var parsed)) return BadSource(source); if (parsed is null && string.IsNullOrWhiteSpace(key)) return Results.BadRequest(new { error = "refusing to delete every block: pass source=operator|engine or key=..." }); @@ -145,7 +147,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 (!TryKnownQuery(ctx, out var unknown, "live", "limit", "offset")) 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 }); @@ -166,8 +168,9 @@ internal static class AdminEndpoints return Results.Ok(rows); }); - group.MapPost("/allow", async (NewAllowRequest req, OpenWafDbContext db, EdgeStateStore state, CancellationToken ct) => + group.MapPost("/allow", async (NewAllowRequest req, OpenWafDbContext db, EdgeStateStore state, HttpContext ctx, CancellationToken ct) => { + if (!TryKnownQuery(ctx, out var unknown)) return Results.BadRequest(new { error = unknown }); if (string.IsNullOrWhiteSpace(req.Match) || !IsValidMatch(req.Match)) return Results.BadRequest(new { error = "match must be an address or CIDR" }); @@ -192,8 +195,9 @@ internal static class AdminEndpoints return Results.NoContent(); }); - group.MapDelete("/allow/{id:long}", async (long id, OpenWafDbContext db, EdgeStateStore state, CancellationToken ct) => + group.MapDelete("/allow/{id:long}", async (long id, OpenWafDbContext db, EdgeStateStore state, HttpContext ctx, CancellationToken ct) => { + if (!TryKnownQuery(ctx, out var unknown)) return Results.BadRequest(new { error = unknown }); var n = await db.AllowEntries.Where(a => a.Id == id).ExecuteDeleteAsync(ct); await state.InvalidateAsync(ct); // The country-rule delete names the row it could not find. This one @@ -213,14 +217,16 @@ internal static class AdminEndpoints // the first look like the second for the whole life of the process. group.MapGet("/policy", (EdgePolicyProvider policy, HttpContext ctx) => { + if (!TryKnownQuery(ctx, out var unknown)) return Results.BadRequest(new { error = unknown }); ctx.Response.Headers["X-Policy-Reload-Failures"] = policy.ReloadFailures.ToString(); ctx.Response.Headers["X-Policy-Last-Read"] = policy.LastReloadSuccessAt?.ToString("O") ?? "never"; return Results.Ok(ToDto(policy.Current)); }); - group.MapPut("/policy", async (PolicyUpdateRequest req, EdgePolicyProvider policy, EdgeStateStore state, CancellationToken ct) => + group.MapPut("/policy", async (PolicyUpdateRequest req, EdgePolicyProvider policy, EdgeStateStore state, HttpContext ctx, CancellationToken ct) => { + if (!TryKnownQuery(ctx, out var unknown)) return Results.BadRequest(new { error = unknown }); var overrides = new Dictionary(); if (req.Mode is not null) { @@ -278,7 +284,7 @@ internal static class AdminEndpoints 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 (!TryKnownQuery(ctx, out var unknown, "source", "limit", "offset")) 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 }); @@ -315,7 +321,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 }); + if (!TryKnownQuery(ctx, out var unknown, "limit", "offset")) return Results.BadRequest(new { error = unknown }); var now = DateTimeOffset.UtcNow; var policy = policyProvider.Current; if (!TryPaging(limit, offset, StreakListDefaultLimit, StreakListMaxLimit, @@ -347,7 +353,7 @@ internal static class AdminEndpoints 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 (!TryKnownQuery(ctx, out var unknown, "source", "limit", "offset")) 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 }); @@ -369,11 +375,19 @@ internal static class AdminEndpoints return Results.Ok(rows); }); - group.MapGet("/countries", async (OpenWafDbContext db, CancellationToken ct) => - Results.Ok(await db.CountryRules.AsNoTracking().OrderBy(c => c.Code).ToListAsync(ct))); - - group.MapPut("/countries/{code}", async (string code, bool allowed, OpenWafDbContext db, EdgeStateStore state, CancellationToken ct) => + group.MapGet("/countries", async (OpenWafDbContext db, HttpContext ctx, CancellationToken ct) => { + // This listing has no paging, and used to answer 200 with every row + // while pretending not to see ?limit=. Refusing the parameter is the + // honest half: the table is bounded by the number of countries an + // operator can write, so paging is not the fix — saying so is. + if (!TryKnownQuery(ctx, out var unknown)) return Results.BadRequest(new { error = unknown }); + return Results.Ok(await db.CountryRules.AsNoTracking().OrderBy(c => c.Code).ToListAsync(ct)); + }); + + group.MapPut("/countries/{code}", async (string code, bool allowed, OpenWafDbContext db, EdgeStateStore state, HttpContext ctx, CancellationToken ct) => + { + if (!TryKnownQuery(ctx, out var unknown, "allowed")) return Results.BadRequest(new { error = unknown }); if (!TryCountryCode(code, out var normalized, out var codeError)) return Results.BadRequest(new { error = codeError }); var row = await db.CountryRules.FindAsync([normalized], ct); @@ -389,8 +403,9 @@ internal static class AdminEndpoints // remove one at all, which is what made a mistyped code permanent — the // console gate's own comment used to read "a country rule cannot be // deleted, only overwritten". - group.MapDelete("/countries/{code}", async (string code, OpenWafDbContext db, EdgeStateStore state, CancellationToken ct) => + group.MapDelete("/countries/{code}", async (string code, OpenWafDbContext db, EdgeStateStore state, HttpContext ctx, CancellationToken ct) => { + if (!TryKnownQuery(ctx, out var unknown)) return Results.BadRequest(new { error = unknown }); if (!TryCountryCode(code, out var normalized, out var codeError)) return Results.BadRequest(new { error = codeError }); var row = await db.CountryRules.FindAsync([normalized], ct); @@ -404,8 +419,9 @@ internal static class AdminEndpoints // What the console's country table reads: the sources the edge has // actually seen, counted from the observation aggregates rather than from // a request log (there isn't one). A read, not new decision logic. - group.MapGet("/countries/summary", async (OpenWafDbContext db, CancellationToken ct) => + group.MapGet("/countries/summary", async (OpenWafDbContext db, HttpContext ctx, CancellationToken ct) => { + if (!TryKnownQuery(ctx, out var unknown)) return Results.BadRequest(new { error = unknown }); // Anonymous projection, and the sort happens after translation: the // record-constructor form compiles and then fails at query time with // "could not be translated" (found by a test). @@ -417,17 +433,22 @@ internal static class AdminEndpoints return Results.Ok(rows.OrderByDescending(r => r.Sources)); }); - group.MapGet("/geo", (IGeoIpLookup geo) => Results.Ok(new + group.MapGet("/geo", (IGeoIpLookup geo, HttpContext ctx) => { - loaded = geo.IsLoaded, - database = geo.Info?.DatabaseType, - builtAt = geo.Info?.BuildDate, - ageDays = geo.Info?.Age is { } age ? Math.Round(age.TotalDays, 1) : (double?)null, - supportsCity = geo.Info?.SupportsCity ?? false - })); + if (!TryKnownQuery(ctx, out var unknown)) return Results.BadRequest(new { error = unknown }); + return Results.Ok(new + { + loaded = geo.IsLoaded, + database = geo.Info?.DatabaseType, + builtAt = geo.Info?.BuildDate, + ageDays = geo.Info?.Age is { } age ? Math.Round(age.TotalDays, 1) : (double?)null, + supportsCity = geo.Info?.SupportsCity ?? false + }); + }); - group.MapGet("/state", (EdgeStateStore state, EdgePolicyProvider policyProvider, StreakTracker tracker, DurabilityHealth durability, BlockStore blockStore) => + group.MapGet("/state", (EdgeStateStore state, EdgePolicyProvider policyProvider, StreakTracker tracker, DurabilityHealth durability, BlockStore blockStore, HttpContext ctx) => { + if (!TryKnownQuery(ctx, out var unknown)) return Results.BadRequest(new { error = unknown }); var now = DateTimeOffset.UtcNow; var allowLive = state.Current.AllowEntries.Count(a => a.IsLive(now)); var allowExpired = state.Current.AllowEntries.Count - allowLive; @@ -571,9 +592,25 @@ internal static class AdminEndpoints /// 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. + /// The write endpoints are the half that mattered. Measured on the shipped + /// image right after the GET guard landed: POST /blocks?zzz=1 answered 204 + /// and wrote the ban, PUT /policy?zzz=1 answered 200 and changed the policy, + /// PUT /countries/DE?allowed=true&zzz=1 answered 204, DELETE + /// /blocks?key=…&zzz=1 answered 200 {"deleted":1}, and GET /countries?limit=2 + /// returned every row. Same request shape, two answers depending on the + /// verb — and the silent half was the one that changes state, where a + /// misspelled scoping parameter acts with a wider scope than the caller + /// meant. The refusal also runs before any state change, so a rejected write + /// cannot half-happen. + /// + /// `allowed` is the whole parameter surface of THAT endpoint, written out by + /// the caller, and the base set is only `token`. Assuming limit/offset for + /// every endpoint is the same bug one level down: measured on the image that + /// already carried the GET guard, `GET /admin-api/countries?limit=2` answered + /// 200 with all 3 rows, because that listing has no paging to honour and a + /// guard that guesses the surface accepts a parameter the endpoint never + /// implemented. A refusal that lists the truth for the endpoint is only true + /// if the guard knows the truth for the endpoint. /// private static bool TryKnownQuery(HttpContext ctx, out string? error, params string[] allowed) { @@ -583,7 +620,7 @@ internal static class AdminEndpoints // 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" }; + var known = new HashSet(StringComparer.OrdinalIgnoreCase) { "token" }; foreach (var extra in allowed) known.Add(extra); error = null; foreach (var key in ctx.Request.Query.Keys) diff --git a/dotnet/OpenWaf.Tests.Integration/WriteQueryGuardTests.cs b/dotnet/OpenWaf.Tests.Integration/WriteQueryGuardTests.cs new file mode 100644 index 0000000..5084c39 --- /dev/null +++ b/dotnet/OpenWaf.Tests.Integration/WriteQueryGuardTests.cs @@ -0,0 +1,203 @@ +using System.Net; +using System.Text; +using System.Text.Json; + +namespace OpenWaf.Tests.Integration; + +/// +/// The query guard landed on the read endpoints first, and the shipped image then +/// answered the same request two different ways depending on the verb. Measured +/// on openwaf:ci (the tree at 336c2f7) with the guard in place: +/// +/// GET /admin-api/blocks?zzz=1 -> 400, names 'zzz' +/// POST /admin-api/blocks?zzz=1 -> 204, and the ban was written +/// PUT /admin-api/policy?zzz=1 -> 200, and the policy changed +/// PUT /admin-api/countries/DE?allowed=true&zzz=1 -> 204 +/// DELETE /admin-api/blocks?key=...&zzz=1 -> 200 {"deleted":1} +/// GET /admin-api/countries?limit=2 -> 200 with every row +/// +/// The silent half was the half that changes state. A misspelled scoping +/// parameter on a write is not a cosmetic miss: `DELETE +/// /admin-api/blocks?src=engine` reads as "no source filter", which the endpoint +/// then refuses only because it also demands a key - while `?sourc=operator` next +/// to a key would have deleted the row the caller did not mean to touch. So the +/// guard covers every endpoint under /admin-api, and it runs before any state +/// change, so a rejected write cannot half-happen. +/// +/// The second measurement is the one that changed the design: the guard used to +/// assume limit/offset were always legal, and that is the same bug one level +/// down. /admin-api/countries has no paging, so `?limit=2` was accepted, dropped, +/// and answered with all 3 rows. Each endpoint now declares its own parameter +/// surface and the guard's base set is only `token`, the one parameter that is +/// real for every endpoint because the auth layer reads it (OPEN-16). +/// +public sealed class WriteQueryGuardTests +{ + private static async Task<(HttpStatusCode Status, string Body)> AdminAsync( + EdgeFixture f, HttpMethod method, string url, string? json = null) + { + using var request = new HttpRequestMessage(method, url); + request.Headers.TryAddWithoutValidation("X-Admin-Token", EdgeFixture.AdminToken); + if (json is not null) + request.Content = new StringContent(json, Encoding.UTF8, "application/json"); + using var response = await f.Client.SendAsync(request); + return (response.StatusCode, await response.Content.ReadAsStringAsync()); + } + + private static async Task CountAsync(EdgeFixture f, string url) + { + var (_, body) = await AdminAsync(f, HttpMethod.Get, url); + return JsonDocument.Parse(body).RootElement.GetArrayLength(); + } + + private static async Task PolicyThresholdAsync(EdgeFixture f) + { + var (_, body) = await AdminAsync(f, HttpMethod.Get, "/admin-api/policy"); + return JsonDocument.Parse(body).RootElement.GetProperty("streakThreshold").GetInt32(); + } + + [Theory] + [InlineData("POST", "/admin-api/blocks?zzz=1", "{\"ip\":\"203.0.113.77\"}")] + [InlineData("DELETE", "/admin-api/blocks?source=operator&zzz=1", null)] + [InlineData("DELETE", "/admin-api/blocks?key=203.0.113.77&zzz=1", null)] + [InlineData("POST", "/admin-api/allow?zzz=1", "{\"match\":\"203.0.113.78\"}")] + [InlineData("DELETE", "/admin-api/allow/1?zzz=1", null)] + [InlineData("PUT", "/admin-api/policy?zzz=1", "{\"streakThreshold\":7}")] + [InlineData("PUT", "/admin-api/countries/de?allowed=true&zzz=1", null)] + [InlineData("DELETE", "/admin-api/countries/de?zzz=1", null)] + public async Task A_write_refuses_a_query_parameter_it_never_implemented_and_names_it( + string method, string url, string? json) + { + await using var f = new EdgeFixture(threshold: 9); + var (status, body) = await AdminAsync(f, new HttpMethod(method), url, json); + Assert.Equal(HttpStatusCode.BadRequest, status); + Assert.Contains("unknown query parameter 'zzz'", body); + // Naming the bad parameter is half the answer; the operator also has to + // be able to see the spelling this endpoint really does take. + Assert.Contains("this endpoint accepts", body); + } + + [Theory] + [InlineData("/admin-api/countries?limit=2", "limit")] + [InlineData("/admin-api/countries?offset=1", "offset")] + [InlineData("/admin-api/countries/summary?limit=2", "limit")] + [InlineData("/admin-api/policy?live=false", "live")] + [InlineData("/admin-api/state?zzz=1", "zzz")] + [InlineData("/admin-api/geo?zzz=1", "zzz")] + public async Task An_endpoint_without_paging_refuses_the_paging_parameters_it_never_implemented( + string url, string name) + { + await using var f = new EdgeFixture(threshold: 9, geo: "DenyList"); + var (status, body) = await AdminAsync(f, HttpMethod.Get, url); + Assert.Equal(HttpStatusCode.BadRequest, status); + // The name has to be the one that was actually sent. A guard that reports + // a generic complaint is a 400 the operator still has to debug by hand. + Assert.Contains($"unknown query parameter '{name}'", body); + } + + [Fact] + public async Task A_refused_write_changes_nothing_and_the_same_request_without_it_still_works() + { + await using var f = new EdgeFixture(threshold: 9); + var (status, _) = await AdminAsync(f, HttpMethod.Post, "/admin-api/blocks?zzz=1", + "{\"ip\":\"203.0.113.77\",\"reason\":\"guard probe\"}"); + Assert.Equal(HttpStatusCode.BadRequest, status); + Assert.Equal(0, await CountAsync(f, "/admin-api/blocks?source=operator")); + + // The refusal is about the parameter, not about the write: the identical + // body with no unknown parameter is served. + var (ok, _) = await AdminAsync(f, HttpMethod.Post, "/admin-api/blocks", + "{\"ip\":\"203.0.113.77\",\"reason\":\"guard probe\"}"); + Assert.Equal(HttpStatusCode.NoContent, ok); + Assert.Equal(1, await CountAsync(f, "/admin-api/blocks?source=operator")); + } + + [Fact] + public async Task A_refused_delete_leaves_the_row_it_was_asked_to_remove() + { + await using var f = new EdgeFixture(threshold: 9); + var (created, _) = await AdminAsync(f, HttpMethod.Post, "/admin-api/blocks", + "{\"ip\":\"203.0.113.79\"}"); + Assert.Equal(HttpStatusCode.NoContent, created); + + var (status, body) = await AdminAsync(f, HttpMethod.Delete, + "/admin-api/blocks?key=203.0.113.79&zzz=1"); + Assert.Equal(HttpStatusCode.BadRequest, status); + // A count of what was removed may only be said by an endpoint that ran + // the removal - the same rule that made {"deleted":0} a 503 in OPEN-32. + Assert.DoesNotContain("deleted", body); + Assert.Equal(1, await CountAsync(f, "/admin-api/blocks?source=operator")); + } + + [Fact] + public async Task A_refused_policy_write_leaves_the_policy_the_edge_is_enforcing() + { + await using var f = new EdgeFixture(threshold: 3); + Assert.Equal(3, await PolicyThresholdAsync(f)); + + var (status, _) = await AdminAsync(f, HttpMethod.Put, "/admin-api/policy?zzz=1", + "{\"streakThreshold\":7}"); + Assert.Equal(HttpStatusCode.BadRequest, status); + Assert.Equal(3, await PolicyThresholdAsync(f)); + + var (ok, _) = await AdminAsync(f, HttpMethod.Put, "/admin-api/policy", + "{\"streakThreshold\":7}"); + Assert.Equal(HttpStatusCode.OK, ok); + Assert.Equal(7, await PolicyThresholdAsync(f)); + } + + [Fact] + public async Task A_refused_country_write_writes_no_rule() + { + await using var f = new EdgeFixture(geo: "DenyList"); + var (status, _) = await AdminAsync(f, HttpMethod.Put, + "/admin-api/countries/de?allowed=false&zzz=1"); + Assert.Equal(HttpStatusCode.BadRequest, status); + Assert.Equal(0, await CountAsync(f, "/admin-api/countries")); + + var (ok, _) = await AdminAsync(f, HttpMethod.Put, "/admin-api/countries/de?allowed=false"); + Assert.Equal(HttpStatusCode.NoContent, ok); + Assert.Equal(1, await CountAsync(f, "/admin-api/countries")); + } + + [Theory] + [InlineData("POST", "/admin-api/blocks", "{\"ip\":\"203.0.113.80\"}")] + [InlineData("DELETE", "/admin-api/blocks?source=operator", null)] + [InlineData("POST", "/admin-api/allow", "{\"match\":\"203.0.113.0/24\"}")] + [InlineData("DELETE", "/admin-api/allow/404", null)] + [InlineData("PUT", "/admin-api/countries/fr?allowed=true", null)] + [InlineData("DELETE", "/admin-api/countries/fr", null)] + [InlineData("GET", "/admin-api/countries", null)] + [InlineData("GET", "/admin-api/countries/summary", null)] + [InlineData("GET", "/admin-api/state", null)] + [InlineData("GET", "/admin-api/geo", null)] + public async Task The_parameters_each_endpoint_does_implement_keep_working( + string method, string url, string? json) + { + // The guard is only worth having if it never fires on a parameter the + // endpoint really honours. Both smoke gates, the console gate and the + // compose gate call these with source/key/live/allowed every run. + await using var f = new EdgeFixture(threshold: 9, geo: "DenyList"); + var (status, body) = await AdminAsync(f, new HttpMethod(method), url, json); + Assert.NotEqual(HttpStatusCode.BadRequest, status); + Assert.DoesNotContain("unknown query parameter", body); + } + + [Fact] + public async Task The_curl_friendly_token_still_works_on_a_write_endpoint() + { + // `token` is not a handler parameter, so a guard that only knows the + // handler's own signature would refuse the one request shape OPEN-16 + // ruled has to keep working. + await using var f = new EdgeFixture(threshold: 9); + var (created, _) = await AdminAsync(f, HttpMethod.Post, "/admin-api/blocks", + "{\"ip\":\"203.0.113.81\"}"); + Assert.Equal(HttpStatusCode.NoContent, created); + + using var request = new HttpRequestMessage(HttpMethod.Delete, + $"/admin-api/blocks?token={EdgeFixture.AdminToken}&source=operator"); + using var response = await f.Client.SendAsync(request); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Equal(0, await CountAsync(f, "/admin-api/blocks?source=operator")); + } +} diff --git a/scripts/compose-smoke.sh b/scripts/compose-smoke.sh index a3475e6..5b2e04f 100755 --- a/scripts/compose-smoke.sh +++ b/scripts/compose-smoke.sh @@ -357,6 +357,44 @@ check 'the alert listing refuses it the same way' 'yes' \ 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 write refuses a parameter it never implemented, before it changes anything' +# The query guard landed on the read endpoints first, and the image that carried +# it then answered the same request two ways depending on the verb. Measured on +# that image: POST /admin-api/blocks?zzz=1 answered 204 and wrote the ban, PUT +# /admin-api/policy?zzz=1 answered 200 and changed the policy, DELETE +# /admin-api/blocks?key=...&zzz=1 answered 200 {"deleted":1}, and GET +# /admin-api/countries?limit=2 answered 200 with every row. That last one is the +# same bug one level down: the guard assumed limit/offset were always legal, and +# this listing has no paging to honour, so the parameter was accepted, dropped +# and answered with the whole table. The silent half was the half that changes +# state — a mistyped scoping parameter on a write acts with a wider scope than +# the caller meant. +WRITE_SRC=203.0.113.251 +POLICY_BEFORE=$(admin "$EDGE/admin-api/policy" | jval streakThreshold) +printf ' info the policy this edge is enforcing before the refused write: streakThreshold=%s\n' "$POLICY_BEFORE" +check 'a write refuses a query parameter it never implemented' '400' \ + "$(code -H "X-Admin-Token: $OPENWAF_ADMIN_TOKEN" -X POST -H 'Content-Type: application/json' \ + -d "{\"ip\":\"$WRITE_SRC\"}" "$EDGE/admin-api/blocks?zzz=1")" +check 'and the ban it refused was never written' '0' \ + "$(admin "$EDGE/admin-api/blocks?source=operator" | jcount "b['sourceKey']=='$WRITE_SRC'")" +check 'the same write with no unknown parameter is served' '204' \ + "$(code -H "X-Admin-Token: $OPENWAF_ADMIN_TOKEN" -X POST -H 'Content-Type: application/json' \ + -d "{\"ip\":\"$WRITE_SRC\"}" "$EDGE/admin-api/blocks")" +check 'a delete whose scope is misspelled is refused, not run' '400' \ + "$(code -H "X-Admin-Token: $OPENWAF_ADMIN_TOKEN" -X DELETE \ + "$EDGE/admin-api/blocks?key=$WRITE_SRC&src=operator")" +check 'and the row it was asked to remove is still there' '1' \ + "$(admin "$EDGE/admin-api/blocks?source=operator" | jcount "b['sourceKey']=='$WRITE_SRC'")" +code -H "X-Admin-Token: $OPENWAF_ADMIN_TOKEN" -X PUT -H 'Content-Type: application/json' \ + -d '{"streakThreshold":7}' "$EDGE/admin-api/policy?zzz=1" >/dev/null +POLICY_AFTER=$(admin "$EDGE/admin-api/policy" | jval streakThreshold) +check 'a policy write with an unknown parameter changes nothing' "$POLICY_BEFORE" "$POLICY_AFTER" +check 'a listing with no paging refuses the paging it never implemented' 'yes' \ + "$(admin "$EDGE/admin-api/countries?limit=2" | grep -qi "unknown query parameter 'limit'" && echo yes || echo no)" +check 'the curl-friendly ?token= still works on a write' '200' \ + "$(code "$EDGE/admin-api/blocks?token=$OPENWAF_ADMIN_TOKEN&source=operator")" +admin -X DELETE "$EDGE/admin-api/blocks?source=operator" >/dev/null + 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