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;
///
/// 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).
///
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 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 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();
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();
db.PolicySettings.Add(new PolicySetting { Key = "engineBlockStatus", Value = "1000" });
await db.SaveChangesAsync();
}
await f.Service().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));
}
}