Every pillar this edge had until now judged the response or the source: a streak of refusals the upstream produced, a country, an operator's list of addresses. The request itself was never looked at. A known-bad request therefore always reached the origin and cost it something, and became a defence only if the origin's answer happened to fall in the refusal range three times in a row. A request rule is a path pattern an operator writes: `GET/POST/DELETE /admin-api/rules`, listed in the order they are enforced, with an action. `observe` counts matches (one alert per rule per 15 minutes, the tally on the listing) and lets the request through, which is how an operator learns what a rule would have blocked before it blocks anything; `block` answers 403 naming the rule id — the id, not the pattern, because a 403 body that quotes the pattern tells the visitor which payload to change. It fires in Observe mode too: the mode switches off what the edge decides by itself, not what a human wrote down. It sits below the allowlist and above the two source-level lists, because "this path is refused" is the more specific claim about this request. The pattern language is a glob — `*` and `?`, anchored, case-insensitive, `*` crossing `/` — and deliberately not a regex: the operator writes the pattern and an anonymous visitor writes the path, and `(a+)+$` against 400 a's is a ReDoS with the edge's CPU. A pattern that can only silently do nothing (no leading `/`, `/*`, a control character, over 256 characters) is refused with the reason, and at most 500 live rules exist because every request is checked against each. Two things the run caught rather than the design assumed: * The rules read shared one statement block with the rest of the snapshot. `request_rules` is the newest table in the schema, and the default schema step is EnsureCreated, which creates a missing database and changes nothing about an existing one — so every database created before this feature has every table except that one, and the first refresh after startup would have thrown, frozen the operator's block list at its old contents, and looked healthy. The rules read is a statement of its own now: a missing table costs the rules pillar and says so (`requestRulesAvailable`, `requestRulesError`, a NOT READ line over the rules table) while every other pillar keeps enforcing. The migration set was stale in the same direction — it never had `source_streaks` either, so the `migrate` path could not create the table OPEN-52 added; `AddRequestRules` adds both. * The console gate banned its own probe address. The seed sets the streak threshold to 3 and the gate probes 404 paths, so the last assertion in the new scene read a `blocked_by_policy` as "the rule is still in force" — and the ban, unlike the rule, outlives `compose down` in the data volume. The scene probes its own address now and the cleanup clears engine bans. Measured on this tree: build 0 warnings / 0 errors, unit 195/195 (44 new: the glob's semantics and rejections, and where the new pillar sits in the order), integration 208/208 in 25 s (14 new, including a fixture that drops the rules table and asserts the operator block is still enforced), smoke 36/0 (7 new against a running edge), console 85 assertions 0 failed (6 new, driving the rule form in a real browser), compose 209/0 against the built image at 261 MB.
308 lines
15 KiB
C#
308 lines
15 KiB
C#
using System.Net;
|
|
using System.Net.Http.Json;
|
|
using System.Text.Json;
|
|
using Microsoft.EntityFrameworkCore;
|
|
using Microsoft.Extensions.DependencyInjection;
|
|
using OpenWaf.Infrastructure.Persistence;
|
|
|
|
namespace OpenWaf.Tests.Integration;
|
|
|
|
/// <summary>
|
|
/// The request rule, end to end: an operator writes a pattern over the API, the
|
|
/// guard refuses the path before the application ever sees the request, and the
|
|
/// observe action answers the question an operator actually has before turning
|
|
/// a rule on — what would this have blocked?
|
|
///
|
|
/// Before this feature the edge only ever reacted to what the upstream answered.
|
|
/// A known-bad request still reached the origin and only became a defence if the
|
|
/// origin's answer happened to fall in the refusal range three times in a row.
|
|
/// </summary>
|
|
public sealed class RequestRuleTests
|
|
{
|
|
private const string Visitor = "203.0.113.140";
|
|
|
|
private static async Task<HttpResponseMessage> GetAsync(EdgeFixture f, string path, string ip = Visitor)
|
|
{
|
|
using var request = new HttpRequestMessage(HttpMethod.Get, path);
|
|
request.Headers.TryAddWithoutValidation("X-Forwarded-For", ip);
|
|
return await f.Client.SendAsync(request);
|
|
}
|
|
|
|
private static async Task<HttpResponseMessage> AdminAsync(
|
|
EdgeFixture f, HttpMethod method, string url, object? body = null)
|
|
{
|
|
using var request = new HttpRequestMessage(method, url);
|
|
request.Headers.TryAddWithoutValidation("X-Admin-Token", EdgeFixture.AdminToken);
|
|
if (body is not null) request.Content = JsonContent.Create(body);
|
|
return await f.Client.SendAsync(request);
|
|
}
|
|
|
|
private static async Task<string> BodyAsync(HttpResponseMessage r) => await r.Content.ReadAsStringAsync();
|
|
|
|
[Fact]
|
|
public async Task A_block_rule_refuses_the_path_before_the_upstream_sees_the_request()
|
|
{
|
|
await using var f = new EdgeFixture();
|
|
|
|
using (var created = await AdminAsync(f, HttpMethod.Post, "/admin-api/rules",
|
|
new { pattern = "/.env*", action = "block", note = "probe sweep seen in the log" }))
|
|
Assert.Equal(HttpStatusCode.NoContent, created.StatusCode);
|
|
|
|
using (var probe = await GetAsync(f, "/.env"))
|
|
{
|
|
Assert.Equal(HttpStatusCode.Forbidden, probe.StatusCode);
|
|
var body = await BodyAsync(probe);
|
|
Assert.Contains("blocked_by_rule", body);
|
|
// The answer names the rule by id, never by pattern: the pattern in
|
|
// a 403 body tells the visitor which payload to change instead.
|
|
Assert.Contains("rule_", body);
|
|
Assert.DoesNotContain("/.env", body);
|
|
}
|
|
|
|
using (var probe = await GetAsync(f, "/.env.local"))
|
|
Assert.Equal(HttpStatusCode.Forbidden, probe.StatusCode);
|
|
|
|
// The path the rule does not name still flows.
|
|
using (var probe = await GetAsync(f, "/index.html"))
|
|
Assert.Equal(HttpStatusCode.NotFound, probe.StatusCode);
|
|
|
|
lock (f.Upstream.Paths)
|
|
{
|
|
Assert.DoesNotContain("/.env", f.Upstream.Paths);
|
|
Assert.DoesNotContain("/.env.local", f.Upstream.Paths);
|
|
Assert.Contains("/index.html", f.Upstream.Paths);
|
|
}
|
|
}
|
|
|
|
[Fact]
|
|
public async Task An_observe_rule_lets_the_request_through_and_answers_what_it_would_have_blocked()
|
|
{
|
|
await using var f = new EdgeFixture();
|
|
|
|
using (var created = await AdminAsync(f, HttpMethod.Post, "/admin-api/rules",
|
|
new { pattern = "/xmlrpc.php", action = "observe" }))
|
|
Assert.Equal(HttpStatusCode.NoContent, created.StatusCode);
|
|
|
|
for (var i = 0; i < 3; i++)
|
|
{
|
|
using var probe = await GetAsync(f, "/xmlrpc.php");
|
|
Assert.Equal(HttpStatusCode.NotFound, probe.StatusCode);
|
|
}
|
|
// A path the rule does not name is not counted.
|
|
using (var probe = await GetAsync(f, "/index.html")) { }
|
|
|
|
using var scope = f.Factory.Services.CreateScope();
|
|
var db = scope.ServiceProvider.GetRequiredService<OpenWafDbContext>();
|
|
var alerts = await db.Alerts.AsNoTracking().Where(a => a.Kind == "rule_match").ToListAsync();
|
|
|
|
// One alert, raised by the first match — the same storm rule the 5xx
|
|
// alerts learned ("alert on the crossing and the doublings, not once per
|
|
// request"). The rest of the matches are counted, not re-alerted, and
|
|
// the listing below is where they are read.
|
|
Assert.Single(alerts);
|
|
Assert.Equal(1, alerts[0].Count);
|
|
Assert.Contains("/xmlrpc.php", alerts[0].Detail);
|
|
Assert.Contains("nothing was blocked", alerts[0].Detail);
|
|
|
|
// And the listing carries the tally, so the page can say "watching,
|
|
// this many matches" rather than only "watching".
|
|
using var list = await AdminAsync(f, HttpMethod.Get, "/admin-api/rules");
|
|
var rows = JsonDocument.Parse(await BodyAsync(list)).RootElement;
|
|
Assert.Equal(3, rows[0].GetProperty("matches").GetInt32());
|
|
Assert.Equal("observe", rows[0].GetProperty("action").GetString());
|
|
}
|
|
|
|
[Fact]
|
|
public async Task The_listing_is_the_order_the_engine_enforces()
|
|
{
|
|
await using var f = new EdgeFixture();
|
|
using (var a = await AdminAsync(f, HttpMethod.Post, "/admin-api/rules",
|
|
new { pattern = "/api*", action = "observe", note = "first" }))
|
|
Assert.Equal(HttpStatusCode.NoContent, a.StatusCode);
|
|
using (var b = await AdminAsync(f, HttpMethod.Post, "/admin-api/rules",
|
|
new { pattern = "/api/secret", action = "block", note = "second" }))
|
|
Assert.Equal(HttpStatusCode.NoContent, b.StatusCode);
|
|
|
|
using var list = await AdminAsync(f, HttpMethod.Get, "/admin-api/rules");
|
|
var rows = JsonDocument.Parse(await BodyAsync(list)).RootElement;
|
|
Assert.Equal(2, rows.GetArrayLength());
|
|
Assert.Equal("/api*", rows[0].GetProperty("pattern").GetString());
|
|
Assert.Equal("first", rows[0].GetProperty("note").GetString());
|
|
Assert.True(rows[0].GetProperty("live").GetBoolean());
|
|
Assert.Equal("/api/secret", rows[1].GetProperty("pattern").GetString());
|
|
|
|
// The first match wins, so the rule the page shows first is the answer —
|
|
// including when it is the gentler of the two actions.
|
|
using var probe = await GetAsync(f, "/api/secret");
|
|
Assert.Equal(HttpStatusCode.NotFound, probe.StatusCode);
|
|
}
|
|
|
|
[Theory]
|
|
[InlineData("wp-admin", "must start with /")]
|
|
[InlineData("/*", "more specific than every request")]
|
|
[InlineData("", "must not be empty")]
|
|
[InlineData(" ", "must not be empty")]
|
|
public async Task A_pattern_that_could_only_silently_do_nothing_is_refused_with_the_reason(
|
|
string pattern, string because)
|
|
{
|
|
await using var f = new EdgeFixture();
|
|
using var created = await AdminAsync(f, HttpMethod.Post, "/admin-api/rules",
|
|
new { pattern, action = "block" });
|
|
Assert.Equal(HttpStatusCode.BadRequest, created.StatusCode);
|
|
Assert.Contains(because, await BodyAsync(created));
|
|
}
|
|
|
|
[Fact]
|
|
public async Task An_unknown_action_is_refused_by_name_rather_than_defaulted()
|
|
{
|
|
await using var f = new EdgeFixture();
|
|
using var created = await AdminAsync(f, HttpMethod.Post, "/admin-api/rules",
|
|
new { pattern = "/.env", action = "blocked" });
|
|
Assert.Equal(HttpStatusCode.BadRequest, created.StatusCode);
|
|
Assert.Contains("action must be observe|block", await BodyAsync(created));
|
|
}
|
|
|
|
[Fact]
|
|
public async Task A_second_live_rule_for_one_pattern_is_refused_and_names_the_rule_it_duplicates()
|
|
{
|
|
await using var f = new EdgeFixture();
|
|
using (var first = await AdminAsync(f, HttpMethod.Post, "/admin-api/rules",
|
|
new { pattern = "/.env*", action = "block" }))
|
|
Assert.Equal(HttpStatusCode.NoContent, first.StatusCode);
|
|
|
|
using var second = await AdminAsync(f, HttpMethod.Post, "/admin-api/rules",
|
|
new { pattern = "/.env*", action = "observe" });
|
|
Assert.Equal(HttpStatusCode.Conflict, second.StatusCode);
|
|
var text = await BodyAsync(second);
|
|
Assert.Contains("already covers /.env*", text);
|
|
Assert.Contains("can never fire", text);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task Removing_a_rule_flows_the_path_again_and_says_which_row_was_not_there()
|
|
{
|
|
await using var f = new EdgeFixture();
|
|
using (var created = await AdminAsync(f, HttpMethod.Post, "/admin-api/rules",
|
|
new { pattern = "/config*", action = "block" }))
|
|
Assert.Equal(HttpStatusCode.NoContent, created.StatusCode);
|
|
|
|
using (var probe = await GetAsync(f, "/config.php"))
|
|
Assert.Equal(HttpStatusCode.Forbidden, probe.StatusCode);
|
|
|
|
using var list = await AdminAsync(f, HttpMethod.Get, "/admin-api/rules");
|
|
var id = JsonDocument.Parse(await BodyAsync(list)).RootElement[0].GetProperty("id").GetInt64();
|
|
|
|
using (var removed = await AdminAsync(f, HttpMethod.Delete, $"/admin-api/rules/{id}"))
|
|
Assert.Equal(HttpStatusCode.NoContent, removed.StatusCode);
|
|
|
|
using (var probe = await GetAsync(f, "/config.php"))
|
|
Assert.Equal(HttpStatusCode.NotFound, probe.StatusCode);
|
|
|
|
using (var again = await AdminAsync(f, HttpMethod.Delete, $"/admin-api/rules/{id}"))
|
|
{
|
|
Assert.Equal(HttpStatusCode.NotFound, again.StatusCode);
|
|
Assert.Contains($"no request rule with id {id}", await BodyAsync(again));
|
|
}
|
|
}
|
|
|
|
[Fact]
|
|
public async Task A_rule_stops_blocking_the_minute_its_expiry_passes()
|
|
{
|
|
await using var f = new EdgeFixture();
|
|
using (var created = await AdminAsync(f, HttpMethod.Post, "/admin-api/rules",
|
|
new { pattern = "/backup*", action = "block", expiresInMinutes = 60 }))
|
|
Assert.Equal(HttpStatusCode.NoContent, created.StatusCode);
|
|
|
|
using (var probe = await GetAsync(f, "/backup.sql"))
|
|
Assert.Equal(HttpStatusCode.Forbidden, probe.StatusCode);
|
|
|
|
// Backdate the row rather than wait for a minute the test would rather
|
|
// not spend — the same shape the retention tests use.
|
|
using (var scope = f.Factory.Services.CreateScope())
|
|
{
|
|
var db = scope.ServiceProvider.GetRequiredService<OpenWafDbContext>();
|
|
var row = await db.RequestRules.FirstAsync();
|
|
row.ExpiresAt = DateTimeOffset.UtcNow.AddSeconds(-5);
|
|
await db.SaveChangesAsync();
|
|
}
|
|
await f.Service<EdgeStateStore>().InvalidateAsync();
|
|
|
|
using (var probe = await GetAsync(f, "/backup.sql"))
|
|
Assert.Equal(HttpStatusCode.NotFound, probe.StatusCode);
|
|
|
|
using var list = await AdminAsync(f, HttpMethod.Get, "/admin-api/rules");
|
|
Assert.Equal(0, JsonDocument.Parse(await BodyAsync(list)).RootElement.GetArrayLength());
|
|
|
|
using var all = await AdminAsync(f, HttpMethod.Get, "/admin-api/rules?live=false");
|
|
var rows = JsonDocument.Parse(await BodyAsync(all)).RootElement;
|
|
Assert.Equal(1, rows.GetArrayLength());
|
|
Assert.False(rows[0].GetProperty("live").GetBoolean());
|
|
}
|
|
|
|
[Fact]
|
|
public async Task A_database_without_the_rule_table_enforces_everything_else_and_says_so()
|
|
{
|
|
// `request_rules` is the newest table in the schema, so a database
|
|
// created before this feature has every other one. If the rules read
|
|
// shared one statement block with the rest of the snapshot, that
|
|
// missing table would stop an operator block written a minute ago from
|
|
// ever being enforced. It does not, and the surface says which pillar is
|
|
// reading nothing.
|
|
await using var f = new EdgeFixture();
|
|
|
|
using (var blocked = await AdminAsync(f, HttpMethod.Post, "/admin-api/blocks",
|
|
new { ip = Visitor, reason = "the ban that must survive a missing table" }))
|
|
Assert.Equal(HttpStatusCode.NoContent, blocked.StatusCode);
|
|
|
|
using (var scope = f.Factory.Services.CreateScope())
|
|
await scope.ServiceProvider.GetRequiredService<OpenWafDbContext>()
|
|
.Database.ExecuteSqlRawAsync("DROP TABLE request_rules");
|
|
|
|
await f.Service<EdgeStateStore>().InvalidateAsync();
|
|
|
|
// The operator block is still enforced — 301 to the policy's redirect
|
|
// target, which is what an operator block answers. The missing table
|
|
// costs the rules pillar, not the ban.
|
|
using (var probe = await GetAsync(f, "/anything"))
|
|
Assert.Equal(HttpStatusCode.MovedPermanently, probe.StatusCode);
|
|
|
|
using var state = await AdminAsync(f, HttpMethod.Get, "/admin-api/state");
|
|
var body = JsonDocument.Parse(await BodyAsync(state)).RootElement;
|
|
Assert.False(body.GetProperty("requestRulesAvailable").GetBoolean());
|
|
Assert.Contains("request_rules", body.GetProperty("requestRulesError").GetString());
|
|
Assert.Equal(0, body.GetProperty("snapshotRefreshFailures").GetInt32());
|
|
}
|
|
|
|
[Fact]
|
|
public async Task The_allowlist_still_outranks_a_rule_that_names_every_path()
|
|
{
|
|
await using var f = new EdgeFixture();
|
|
using (var exempt = await AdminAsync(f, HttpMethod.Post, "/admin-api/allow",
|
|
new { match = Visitor, note = "the operator's own probe" }))
|
|
Assert.Equal(HttpStatusCode.NoContent, exempt.StatusCode);
|
|
using (var created = await AdminAsync(f, HttpMethod.Post, "/admin-api/rules",
|
|
new { pattern = "/.env*", action = "block" }))
|
|
Assert.Equal(HttpStatusCode.NoContent, created.StatusCode);
|
|
|
|
using (var probe = await GetAsync(f, "/.env", Visitor))
|
|
Assert.Equal(HttpStatusCode.NotFound, probe.StatusCode);
|
|
using (var probe = await GetAsync(f, "/.env", "203.0.113.141"))
|
|
Assert.Equal(HttpStatusCode.Forbidden, probe.StatusCode);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task A_rule_answer_carries_the_completeness_headers_like_every_other_listing()
|
|
{
|
|
await using var f = new EdgeFixture();
|
|
for (var i = 0; i < 3; i++)
|
|
using (var created = await AdminAsync(f, HttpMethod.Post, "/admin-api/rules",
|
|
new { pattern = $"/p{i}*", action = "observe" }))
|
|
Assert.Equal(HttpStatusCode.NoContent, created.StatusCode);
|
|
|
|
using var page = await AdminAsync(f, HttpMethod.Get, "/admin-api/rules?limit=2");
|
|
Assert.Equal("3", page.Headers.TryGetValues("X-Total-Count", out var v) ? string.Join(",", v) : null);
|
|
Assert.Equal("true", page.Headers.TryGetValues("X-Truncated", out var t) ? string.Join(",", t) : null);
|
|
Assert.Equal(2, JsonDocument.Parse(await BodyAsync(page)).RootElement.GetArrayLength());
|
|
}
|
|
}
|