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; /// /// 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. /// public sealed class RequestRuleTests { private const string Visitor = "203.0.113.140"; private static async Task 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 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 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(); 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(); var row = await db.RequestRules.FirstAsync(); row.ExpiresAt = DateTimeOffset.UtcNow.AddSeconds(-5); await db.SaveChangesAsync(); } await f.Service().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() .Database.ExecuteSqlRawAsync("DROP TABLE request_rules"); await f.Service().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()); } }