using System.Net;
using System.Net.Http.Json;
using System.Text.Json;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using OpenWaf.Domain.Policy;
using OpenWaf.Domain.Security;
using OpenWaf.Infrastructure.Persistence;
namespace OpenWaf.Tests.Integration;
///
/// Where does this appear? (OPEN-74): one search across every store the
/// operator's decisions live in.
///
/// The phrase an operator remembers is not a field the listings filter on.
/// "ticket 441" sits in a block's reason, an exemption's note, a path rule's
/// note, a path budget's note and the change log's detail; six weeks later that
/// phrase is all there is, and asking it means opening eight listings.
///
/// What these tests hold the surface to: the search reaches all eight stores and
/// says which one each row came from; the query is data and not LIKE's grammar,
/// so "100%" and "a_b" search as themselves; an address query also returns the
/// rows that cover it rather than name it, and says that is why; a row counted
/// twice is answered once; the per-store counts make "nothing matched"
/// distinguishable from "nothing was searched"; the limit reports what it left
/// out; the refusals name the parameter; and asking writes nothing.
///
public sealed class OperatorSearchTests
{
private const string Phrase = "ticket 441";
private const string Range = "203.0.113.64/29"; // .64 – .71
private const string Inside = "203.0.113.69";
private const string Source = "203.0.113.88";
private static async Task AdminAsync(
EdgeFixture f, HttpMethod method, string url, object? body = null,
string? token = EdgeFixture.AdminToken)
{
using var request = new HttpRequestMessage(method, url);
if (token is not null) request.Headers.TryAddWithoutValidation("X-Admin-Token", token);
if (body is not null) request.Content = JsonContent.Create(body);
return await f.Client.SendAsync(request);
}
private static async Task<(HttpStatusCode Status, JsonElement Body)> FindAsync(
EdgeFixture f, string query, string? token = EdgeFixture.AdminToken)
{
using var r = await AdminAsync(f, HttpMethod.Get, $"/admin-api/find?{query}", token: token);
var text = await r.Content.ReadAsStringAsync();
// A refusal carries no body: parsing one would fail the test for the
// wrong reason.
var body = string.IsNullOrWhiteSpace(text)
? default
: JsonDocument.Parse(text).RootElement.Clone();
return (r.StatusCode, body);
}
/// Rows written straight to storage. The API would do for most of
/// them, but this test needs one row in every store at once, including the
/// alert and the change record the edge writes by itself.
private static async Task SeedAsync(EdgeFixture f, object row)
{
using var scope = f.Factory.Services.CreateScope();
var db = scope.ServiceProvider.GetRequiredService();
db.Add(row);
await db.SaveChangesAsync();
await f.Service().InvalidateAsync();
}
private static async Task SeedPhraseInEveryStoreAsync(EdgeFixture f)
{
var now = DateTimeOffset.UtcNow;
await SeedAsync(f, new BlockEntry
{
SourceKey = Source, Source = BlockSource.Operator, CreatedAt = now,
Reason = $"closed after {Phrase}", LastPath = "/wp-login.php"
});
await SeedAsync(f, new NetworkBan
{
Match = Range, CreatedAt = now, Reason = $"netblock from {Phrase}"
});
await SeedAsync(f, new AllowEntry
{
Match = Inside, CreatedAt = now, Note = $"the window {Phrase} gave"
});
await SeedAsync(f, new RequestRule
{
Pattern = "/wp-login.php", Action = RequestRuleAction.Block,
CreatedAt = now, Note = Phrase
});
await SeedAsync(f, new RateRule
{
Pattern = "/login", CreatedAt = now, Note = $"loosened for {Phrase}"
});
await SeedAsync(f, new EdgeAlert
{
SourceKey = Source, Kind = "server_error_streak", Count = 3,
CreatedAt = now, Detail = $"upstream down while {Phrase} was open"
});
await SeedAsync(f, new ConfigChange
{
At = now, Section = ConfigChangeLog.SectionBlocks, Action = ConfigChangeLog.ActionAdded,
Target = Source, Detail = $"written for {Phrase}"
});
await SeedAsync(f, new CountryRule
{
Code = "UA", Name = "Ukraine", IsAllowed = false, UpdatedAt = now
});
}
private static List Results(JsonElement body)
=> body.GetProperty("results").EnumerateArray().ToList();
private static bool HasStore(List rows, string store)
=> rows.Any(r => r.GetProperty("store").GetString() == store);
[Fact]
public async Task One_phrase_comes_back_from_every_store_that_holds_it()
{
await using var f = new EdgeFixture();
await SeedPhraseInEveryStoreAsync(f);
var (status, body) = await FindAsync(f, $"q={Phrase}");
Assert.Equal(HttpStatusCode.OK, status);
Assert.Equal(Phrase, body.GetProperty("query").GetString());
Assert.Equal("database", body.GetProperty("scope").GetString());
var rows = Results(body);
foreach (var store in new[] { "block", "range", "allow", "pathRule", "pathBudget", "alert", "change" })
Assert.True(HasStore(rows, store), $"no {store} row in {body}");
// Every row says where it came from and which field carried the text, so
// a hit in a reason is not mistaken for a hit on a pattern.
var rule = rows.Single(r => r.GetProperty("store").GetString() == "pathRule");
Assert.Equal("/wp-login.php", rule.GetProperty("pattern").GetString());
Assert.Contains("text matched note", rule.GetProperty("why").GetString()!);
var block = rows.Single(r => r.GetProperty("store").GetString() == "block");
Assert.Equal(Source, block.GetProperty("match").GetString());
Assert.Contains("text matched reason", block.GetProperty("why").GetString()!);
Assert.True(block.GetProperty("live").GetBoolean());
Assert.NotEqual(JsonValueKind.Null, block.GetProperty("id").ValueKind);
// An alert is an event, not a state: "is it in force" is not a question
// it answers, and false would say it had been switched off.
var alert = rows.Single(r => r.GetProperty("store").GetString() == "alert");
Assert.True(alert.GetProperty("live").ValueKind == JsonValueKind.Null);
// The counts are per store, so the answer says what it looked at and what
// it found there.
var counts = body.GetProperty("counts");
Assert.Equal(1, counts.GetProperty("block").GetInt32());
Assert.Equal(1, counts.GetProperty("alert").GetInt32());
Assert.Equal(7, body.GetProperty("matched").GetInt32());
Assert.False(body.GetProperty("truncated").GetBoolean());
}
[Fact]
public async Task A_country_rule_is_found_by_the_name_the_operator_remembers()
{
await using var f = new EdgeFixture();
await SeedPhraseInEveryStoreAsync(f);
var (_, body) = await FindAsync(f, "q=ukr");
var rule = Assert.Single(Results(body), r => r.GetProperty("store").GetString() == "countryRule");
Assert.Equal("UA", rule.GetProperty("match").GetString());
Assert.Contains("text matched name", rule.GetProperty("why").GetString()!);
Assert.Equal(1, body.GetProperty("counts").GetProperty("countryRule").GetInt32());
// The code is searched too, and a two-letter query is long enough to ask.
var (_, byCode) = await FindAsync(f, "q=UA");
Assert.Equal(1, byCode.GetProperty("counts").GetProperty("countryRule").GetInt32());
}
[Fact]
public async Task The_query_is_data_and_not_likes_grammar()
{
await using var f = new EdgeFixture();
var now = DateTimeOffset.UtcNow;
await SeedAsync(f, new BlockEntry
{
SourceKey = Source, Source = BlockSource.Operator, CreatedAt = now,
Reason = "100% sure about this one"
});
await SeedAsync(f, new BlockEntry
{
SourceKey = "203.0.113.89", Source = BlockSource.Operator, CreatedAt = now,
Reason = "100 requests a minute"
});
await SeedAsync(f, new AllowEntry { Match = "203.0.113.90", CreatedAt = now, Note = "a_b note" });
await SeedAsync(f, new AllowEntry { Match = "203.0.113.91", CreatedAt = now, Note = "axb note" });
// Unescaped, "100%" is LIKE for "100 followed by anything", which answers
// about a row nobody asked about.
var (status, percent) = await FindAsync(f, "q=100%25");
Assert.Equal(HttpStatusCode.OK, status);
Assert.Equal(1, percent.GetProperty("matched").GetInt32());
var hit = Assert.Single(Results(percent));
Assert.Equal("100% sure about this one", hit.GetProperty("text").GetString());
var (_, underscore) = await FindAsync(f, "q=a_b");
Assert.Equal(1, underscore.GetProperty("matched").GetInt32());
Assert.Equal("a_b note", Assert.Single(Results(underscore)).GetProperty("text").GetString());
// A literal backslash in the query survives its own escaping. It is
// searched inside three characters because a query of one is refused.
await SeedAsync(f, new AllowEntry { Match = "203.0.113.92", CreatedAt = now, Note = @"say a\b here" });
await SeedAsync(f, new AllowEntry { Match = "203.0.113.93", CreatedAt = now, Note = "say axb here" });
var (_, backslash) = await FindAsync(f, "q=a%5Cb");
Assert.Equal(1, backslash.GetProperty("matched").GetInt32());
Assert.Equal(@"say a\b here", Assert.Single(Results(backslash)).GetProperty("text").GetString());
Assert.True(percent.GetProperty("matching").GetProperty("wildcardsEscaped").GetBoolean());
}
[Fact]
public async Task Matching_ignores_case_the_way_a_person_expects()
{
await using var f = new EdgeFixture();
await SeedAsync(f, new BlockEntry
{
SourceKey = Source, Source = BlockSource.Operator, CreatedAt = DateTimeOffset.UtcNow,
Reason = "Ticket 441 CLOSED"
});
foreach (var needle in new[] { "ticket 441", "TICKET", "441 closed" })
{
var (_, body) = await FindAsync(f, $"q={Uri.EscapeDataString(needle)}");
Assert.Equal(1, body.GetProperty("matched").GetInt32());
Assert.Contains("Ticket 441 CLOSED", Assert.Single(Results(body)).GetProperty("text").GetString());
}
}
[Fact]
public async Task An_address_query_finds_the_rows_that_cover_it_and_not_only_the_ones_that_name_it()
{
await using var f = new EdgeFixture();
var now = DateTimeOffset.UtcNow;
// Nothing here names the address except the block. The range, the
// exemption and the change record all name the netblock, which is what
// actually answers for this address.
await SeedAsync(f, new NetworkBan { Match = Range, CreatedAt = now, Reason = "rotating scanner" });
await SeedAsync(f, new AllowEntry { Match = "203.0.113.64/28", CreatedAt = now, Note = "the office" });
await SeedAsync(f, new ConfigChange
{
At = now, Section = ConfigChangeLog.SectionBlocks, Action = ConfigChangeLog.ActionAdded,
Target = Range, Detail = "banned on the ticket"
});
await SeedAsync(f, new BlockEntry
{
SourceKey = Inside, Source = BlockSource.Operator, CreatedAt = now, Reason = "the printer"
});
// A range that does not cover it is not told it does.
await SeedAsync(f, new NetworkBan { Match = "203.0.113.96/29", CreatedAt = now, Reason = "elsewhere" });
var (status, body) = await FindAsync(f, $"q={Inside}");
Assert.Equal(HttpStatusCode.OK, status);
var asAddress = body.GetProperty("asAddress");
Assert.Equal(Inside, asAddress.GetProperty("ip").GetString());
Assert.Equal(Inside, asAddress.GetProperty("sourceKey").GetString());
var rows = Results(body);
var range = rows.Single(r => r.GetProperty("store").GetString() == "range");
Assert.Equal(Range, range.GetProperty("match").GetString());
Assert.Contains($"covers {Inside}", range.GetProperty("why").GetString()!);
var allow = rows.Single(r => r.GetProperty("store").GetString() == "allow");
Assert.Equal("203.0.113.64/28", allow.GetProperty("match").GetString());
Assert.Contains("covers", allow.GetProperty("why").GetString()!);
var change = rows.Single(r => r.GetProperty("store").GetString() == "change");
Assert.Equal(Range, change.GetProperty("match").GetString());
Assert.DoesNotContain("203.0.113.96/29", body.ToString());
// The counts carry the coverage rows, so the answer's totals describe the
// answer rather than only the text matches.
Assert.Equal(1, body.GetProperty("counts").GetProperty("range").GetInt32());
Assert.Equal(4, body.GetProperty("matched").GetInt32());
}
[Fact]
public async Task A_source_is_found_under_the_key_this_edge_files_it_under()
{
await using var f = new EdgeFixture();
var now = DateTimeOffset.UtcNow;
// The ban is filed under the /29; the operator searches the address the
// socket carried, which no row names.
using (await AdminAsync(f, HttpMethod.Put, "/admin-api/policy",
new { ipv4KeyPrefixLength = 29 })) { }
await SeedAsync(f, new BlockEntry
{
SourceKey = "203.0.113.88/29", Source = BlockSource.Engine, CreatedAt = now,
Reason = "3 consecutive refusals"
});
// Nothing in that row contains ".90", so only the key rule can find it.
var (_, body) = await FindAsync(f, "q=203.0.113.90");
Assert.Equal("203.0.113.88/29", body.GetProperty("asAddress").GetProperty("sourceKey").GetString());
var block = Assert.Single(Results(body), r => r.GetProperty("store").GetString() == "block");
Assert.Contains("files 203.0.113.90 under 203.0.113.88/29", block.GetProperty("why").GetString()!);
Assert.Equal(1, body.GetProperty("counts").GetProperty("block").GetInt32());
// And the address that is named by the key's own text is still one row.
var (_, named) = await FindAsync(f, $"q={Source}");
Assert.Equal(1, named.GetProperty("counts").GetProperty("block").GetInt32());
Assert.Single(Results(named), r => r.GetProperty("store").GetString() == "block");
}
[Fact]
public async Task A_row_that_matches_by_text_and_covers_the_address_is_answered_once()
{
await using var f = new EdgeFixture();
await SeedAsync(f, new AllowEntry
{
Match = Inside, CreatedAt = DateTimeOffset.UtcNow, Note = "named and covering"
});
var (_, body) = await FindAsync(f, $"q={Inside}");
var allow = Assert.Single(Results(body), r => r.GetProperty("store").GetString() == "allow");
// The text match is the better reason: the row does name this address.
Assert.Contains("text matched match", allow.GetProperty("why").GetString()!);
Assert.Equal(1, body.GetProperty("counts").GetProperty("allow").GetInt32());
Assert.Equal(1, body.GetProperty("matched").GetInt32());
}
[Fact]
public async Task An_empty_answer_names_every_store_it_searched()
{
await using var f = new EdgeFixture();
await SeedAsync(f, new BlockEntry
{
SourceKey = Source, Source = BlockSource.Operator,
CreatedAt = DateTimeOffset.UtcNow, Reason = "something else entirely"
});
var (_, body) = await FindAsync(f, "q=nothing+like+this");
Assert.Equal(0, body.GetProperty("matched").GetInt32());
Assert.Empty(Results(body));
var counts = body.GetProperty("counts");
foreach (var store in new[]
{ "block", "range", "allow", "pathRule", "pathBudget", "alert", "change", "countryRule" })
Assert.Equal(0, counts.GetProperty(store).GetInt32());
// "Nothing matched" and "nothing was searched" are different answers, and
// an envelope that listed no stores could not tell them apart.
Assert.Contains("counts", body.GetProperty("note").GetString()!);
}
[Fact]
public async Task The_limit_says_how_much_it_left_out()
{
await using var f = new EdgeFixture();
var now = DateTimeOffset.UtcNow;
for (var i = 0; i < 5; i++)
await SeedAsync(f, new BlockEntry
{
SourceKey = $"203.0.113.{100 + i}", Source = BlockSource.Operator,
CreatedAt = now.AddMinutes(i), Reason = Phrase
});
var (_, body) = await FindAsync(f, $"q={Phrase}&limit=2");
Assert.Equal(5, body.GetProperty("matched").GetInt32());
Assert.Equal(2, body.GetProperty("shown").GetInt32());
Assert.Equal(2, body.GetProperty("limit").GetInt32());
Assert.True(body.GetProperty("truncated").GetBoolean());
Assert.Equal(5, body.GetProperty("counts").GetProperty("block").GetInt32());
// Newest first: the row an operator wants is the one they wrote last.
var rows = Results(body);
Assert.Equal(2, rows.Count);
Assert.True(rows[0].GetProperty("at").GetDateTimeOffset()
> rows[1].GetProperty("at").GetDateTimeOffset());
}
[Fact]
public async Task A_bad_query_is_refused_by_name()
{
await using var f = new EdgeFixture();
var cases = new[]
{
("", "q is required"),
("q=x", "q must be 2..128 characters"),
("q=" + Uri.EscapeDataString(new string('x', 129)), "q must be 2..128 characters"),
("q=" + Phrase + "&store=block", "unknown query parameter 'store'"),
("q=" + Phrase + "&limit=0", "limit must be 1..500"),
("q=" + Phrase + "&limit=501", "limit must be 1..500"),
};
foreach (var (query, expected) in cases)
{
var (status, body) = await FindAsync(f, query);
Assert.Equal(HttpStatusCode.BadRequest, status);
Assert.Contains(expected, body.GetProperty("error").GetString()!);
}
// A query that is only whitespace is the same refusal as no query: it
// names nothing to search for.
var (blank, blankBody) = await FindAsync(f, "q=%20%20");
Assert.Equal(HttpStatusCode.BadRequest, blank);
Assert.Contains("q is required", blankBody.GetProperty("error").GetString()!);
}
[Fact]
public async Task Asking_is_a_read_the_read_only_token_can_make_and_that_writes_nothing()
{
await using var f = new EdgeFixture(readOnlyToken: EdgeFixture.ReadOnlyToken);
await SeedPhraseInEveryStoreAsync(f);
static async Task RowsAsync(EdgeFixture f)
{
using var scope = f.Factory.Services.CreateScope();
var db = scope.ServiceProvider.GetRequiredService();
return await db.Blocks.CountAsync() + await db.Alerts.CountAsync()
+ await db.ConfigChanges.CountAsync() + await db.AllowEntries.CountAsync();
}
var before = await RowsAsync(f);
var (status, _) = await FindAsync(f, $"q={Phrase}", token: EdgeFixture.ReadOnlyToken);
Assert.Equal(HttpStatusCode.OK, status);
Assert.Equal(before, await RowsAsync(f));
// And nothing at all without a token.
var (anon, _) = await FindAsync(f, $"q={Phrase}", token: null);
Assert.Equal(HttpStatusCode.Unauthorized, anon);
}
}