The admin API answered 200 to anything. Measured on the shipped image
(openwaf:ci) before this commit:
PUT {"streakThreshold":0} -> 200, streakThreshold still 3, 0 log lines
PUT {"maxTrackedSources":0} -> 200, unchanged
PUT {"banDurationMinutes":-1} -> 200, unchanged
PUT {"streakWindowMinutes":0} -> 200, unchanged
PUT {"refusalRange":"not-a-range"} -> 200, unchanged
PUT {"engineBlockStatus":999} -> 200, and the edge answered HTTP/1.1 999
PUT {"engineBlockStatus":1000} -> 200, and every banned request died as
"curl: (1) Unsupported HTTP/1 subversion
in response" — no HTTP response at all
PUT {"ipv4KeyPrefixLength":0} -> 200, one 404 banned the key "*", and the
next three never-seen addresses were
refused on their first request
PUT {"ipv4KeyPrefixLength":999} -> 200, GET echoed 999, enforcement used 32
Two different failures hid behind that 200. A value the code did not want was
dropped without a word, so the operator read "OK" over a policy that had not
moved. A value the code did want was stored and obeyed literally, and one of
those (engineBlockStatus=1000) takes the site down for every banned visitor
from one admin call.
So the ranges now live in one place, PolicyBounds, next to the reason for each
one, and three layers read it:
* the admin endpoint answers 400 naming the key and the range — the same
shape mode, geo and the state TTL already used;
* the loader ignores a row outside the range and logs the key and the value,
for a backup restored or a row edited by hand;
* DecisionEngine refuses to put an unsendable status on the wire at all, and
answers 403 instead.
ipv4KeyPrefixLength keeps a floor of 8 rather than 0, because 0 is not a coarse
grouping, it is the literal key "*" — one streak and one ban shared by every
IPv4 address on the internet.
Tests: 46 unit (the bounds table, the "*" mechanism, the wire guard) and 18
integration (400 by name, a refused write changing nothing, an accepted value
reaching the wire as 451, a hand-edited row ignored). Teeth, each measured by
removing the layer: no API validation -> 16 integration tests fail; no wire
guard -> 3 unit tests fail; no loader gate -> 1 integration test fails.
168 lines
8.0 KiB
C#
168 lines
8.0 KiB
C#
using System.Net;
|
|
using System.Text.Json;
|
|
using Microsoft.EntityFrameworkCore;
|
|
using Microsoft.Extensions.DependencyInjection;
|
|
using OpenWaf.Domain.Security;
|
|
using OpenWaf.Infrastructure.Persistence;
|
|
|
|
namespace OpenWaf.Tests.Integration;
|
|
|
|
/// <summary>
|
|
/// A policy write that is not believed is worse than a policy write that fails.
|
|
///
|
|
/// Measured on the shipped image (openwaf:ci) before these tests existed:
|
|
/// PUT {"streakThreshold":0} -> 200, streakThreshold still 1, 0 log lines
|
|
/// PUT {"maxTrackedSources":0} -> 200, unchanged
|
|
/// PUT {"banDurationMinutes":-1} -> 200, unchanged
|
|
/// PUT {"streakWindowMinutes":0} -> 200, unchanged
|
|
/// PUT {"refusalRange":"not-a-range"} -> 200, unchanged
|
|
/// PUT {"engineBlockStatus":999} -> 200, and the edge then answered HTTP/1.1 999
|
|
/// PUT {"engineBlockStatus":1000} -> 200, and every banned request died as
|
|
/// "curl: (1) Unsupported HTTP/1 subversion in response"
|
|
/// PUT {"ipv4KeyPrefixLength":0} -> 200, and one 404 banned the key "*", after which
|
|
/// three addresses that had never been seen were
|
|
/// refused on their first request
|
|
/// PUT {"ipv4KeyPrefixLength":999} -> 200, GET echoed 999, enforcement used 32
|
|
///
|
|
/// So the API now answers 400 naming the key and the range, and the guard has a
|
|
/// last line for a value that arrives by another route (a hand-edited row).
|
|
/// </summary>
|
|
public sealed class PolicyValidationTests
|
|
{
|
|
private const string Scanner = "203.0.113.66";
|
|
private const string Bystander = "198.51.100.7";
|
|
|
|
private static async Task<(HttpStatusCode Status, string Body)> PutAsync(EdgeFixture f, string json)
|
|
{
|
|
using var request = new HttpRequestMessage(new HttpMethod("PUT"), "/admin-api/policy")
|
|
{
|
|
Content = new StringContent(json, System.Text.Encoding.UTF8, "application/json")
|
|
};
|
|
request.Headers.TryAddWithoutValidation("X-Admin-Token", EdgeFixture.AdminToken);
|
|
var response = await f.Client.SendAsync(request);
|
|
return (response.StatusCode, await response.Content.ReadAsStringAsync());
|
|
}
|
|
|
|
private static async Task<string> GetPolicyAsync(EdgeFixture f)
|
|
{
|
|
using var request = new HttpRequestMessage(HttpMethod.Get, "/admin-api/policy");
|
|
request.Headers.TryAddWithoutValidation("X-Admin-Token", EdgeFixture.AdminToken);
|
|
return await (await f.Client.SendAsync(request)).Content.ReadAsStringAsync();
|
|
}
|
|
|
|
private static async Task<HttpStatusCode> GetAsync(EdgeFixture f, string path, string sourceIp)
|
|
{
|
|
using var request = new HttpRequestMessage(HttpMethod.Get, path);
|
|
request.Headers.TryAddWithoutValidation("X-Forwarded-For", sourceIp);
|
|
return (await f.Client.SendAsync(request)).StatusCode;
|
|
}
|
|
|
|
[Theory]
|
|
[InlineData("{\"streakThreshold\":0}", "streakThreshold", "1..1000")]
|
|
[InlineData("{\"streakThreshold\":-5}", "streakThreshold", "1..1000")]
|
|
[InlineData("{\"streakWindowMinutes\":0}", "streakWindowMinutes", "0.01..1440")]
|
|
[InlineData("{\"banDurationMinutes\":-1}", "banDurationMinutes", "0.01..10080")]
|
|
[InlineData("{\"maxTrackedSources\":0}", "maxTrackedSources", "1..1000000")]
|
|
[InlineData("{\"refusalRange\":\"not-a-range\"}", "refusalRange", "low-high")]
|
|
[InlineData("{\"refusalRange\":\"600-700\"}", "refusalRange", "100 <= low <= high <= 599")]
|
|
[InlineData("{\"ipv4KeyPrefixLength\":0}", "ipv4KeyPrefixLength", "8..32")]
|
|
[InlineData("{\"ipv4KeyPrefixLength\":999}", "ipv4KeyPrefixLength", "8..32")]
|
|
[InlineData("{\"ipv6KeyPrefixLength\":999}", "ipv6KeyPrefixLength", "32..128")]
|
|
[InlineData("{\"engineBlockStatus\":999}", "engineBlockStatus", "400..599")]
|
|
[InlineData("{\"engineBlockStatus\":1000}", "engineBlockStatus", "400..599")]
|
|
[InlineData("{\"operatorBlockStatus\":302}", "operatorBlockStatus", "301 or 400..599")]
|
|
[InlineData("{\"defaultRedirectTargets\":[\"http://bad target\"]}", "redirectTargets", "absolute http(s) URLs")]
|
|
public async Task An_out_of_range_value_is_refused_by_name_instead_of_answering_200_and_changing_nothing(
|
|
string json, string key, string range)
|
|
{
|
|
await using var f = new EdgeFixture(threshold: 3);
|
|
|
|
var (status, body) = await PutAsync(f, json);
|
|
|
|
Assert.Equal(HttpStatusCode.BadRequest, status);
|
|
Assert.Contains(key, body);
|
|
Assert.Contains(range, body);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task A_refused_write_leaves_the_policy_exactly_where_it_was_and_the_pillar_still_works()
|
|
{
|
|
await using var f = new EdgeFixture(threshold: 3);
|
|
|
|
var before = await GetPolicyAsync(f);
|
|
var (status, _) = await PutAsync(f, "{\"engineBlockStatus\":1000}");
|
|
Assert.Equal(HttpStatusCode.BadRequest, status);
|
|
Assert.Equal(before, await GetPolicyAsync(f));
|
|
|
|
for (var i = 0; i < 3; i++)
|
|
Assert.Equal(HttpStatusCode.NotFound, await GetAsync(f, "/nope", Scanner));
|
|
|
|
// The point of the whole file in one assertion: the banned visitor gets
|
|
// an answer, not a closed connection.
|
|
Assert.Equal(HttpStatusCode.Forbidden, await GetAsync(f, "/nope", Scanner));
|
|
}
|
|
|
|
[Fact]
|
|
public async Task A_policy_value_that_is_accepted_reaches_the_wire_and_not_only_the_api()
|
|
{
|
|
await using var f = new EdgeFixture(threshold: 3);
|
|
|
|
var (status, body) = await PutAsync(f, "{\"engineBlockStatus\":451}");
|
|
Assert.Equal(HttpStatusCode.OK, status);
|
|
using var doc = JsonDocument.Parse(body);
|
|
Assert.Equal(451, doc.RootElement.GetProperty("engineBlockStatus").GetInt32());
|
|
|
|
for (var i = 0; i < 3; i++)
|
|
Assert.Equal(HttpStatusCode.NotFound, await GetAsync(f, "/nope", Scanner));
|
|
|
|
Assert.Equal((HttpStatusCode)451, await GetAsync(f, "/nope", Scanner));
|
|
Assert.Equal(HttpStatusCode.NotFound, await GetAsync(f, "/nope", Bystander));
|
|
}
|
|
|
|
[Fact]
|
|
public async Task Asking_for_a_source_key_that_covers_the_whole_address_family_is_refused_and_the_ban_stays_one_address()
|
|
{
|
|
await using var f = new EdgeFixture(threshold: 1);
|
|
|
|
var (status, _) = await PutAsync(f, "{\"ipv4KeyPrefixLength\":0}");
|
|
Assert.Equal(HttpStatusCode.BadRequest, status);
|
|
|
|
Assert.Equal(HttpStatusCode.NotFound, await GetAsync(f, "/nope", Scanner));
|
|
Assert.Equal(HttpStatusCode.Forbidden, await GetAsync(f, "/nope", Scanner));
|
|
|
|
// With the key collapsed to "*" this bystander's first-ever request
|
|
// would have been refused, which is what was measured on the image.
|
|
Assert.Equal(HttpStatusCode.NotFound, await GetAsync(f, "/nope", Bystander));
|
|
|
|
using var scope = f.Factory.Services.CreateScope();
|
|
var db = scope.ServiceProvider.GetRequiredService<OpenWafDbContext>();
|
|
var keys = await db.Blocks.Where(b => b.Source == BlockSource.Engine).Select(b => b.SourceKey).ToListAsync();
|
|
Assert.DoesNotContain("*", keys);
|
|
Assert.Contains(Scanner, keys);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task A_row_edited_by_hand_outside_the_range_is_ignored_rather_than_put_on_the_wire()
|
|
{
|
|
await using var f = new EdgeFixture(threshold: 3);
|
|
|
|
// Not through the API: a restored backup or a hand edit. The API guard
|
|
// cannot see this, so the loader has to.
|
|
using (var scope = f.Factory.Services.CreateScope())
|
|
{
|
|
var db = scope.ServiceProvider.GetRequiredService<OpenWafDbContext>();
|
|
db.PolicySettings.Add(new PolicySetting { Key = "engineBlockStatus", Value = "1000" });
|
|
await db.SaveChangesAsync();
|
|
}
|
|
|
|
await f.Service<EdgeStateStore>().InvalidateAsync();
|
|
using var doc = JsonDocument.Parse(await GetPolicyAsync(f));
|
|
Assert.Equal(403, doc.RootElement.GetProperty("engineBlockStatus").GetInt32());
|
|
|
|
for (var i = 0; i < 3; i++)
|
|
Assert.Equal(HttpStatusCode.NotFound, await GetAsync(f, "/nope", Scanner));
|
|
|
|
Assert.Equal(HttpStatusCode.Forbidden, await GetAsync(f, "/nope", Scanner));
|
|
}
|
|
}
|