Add explanation rules for catches, editable over MCP
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
4086fa3da3
commit
2437880013
37 files changed
+1867
-37
No files matched your search
@@ -0,0 +1,222 @@
|
||||
using Flypaper.Core.Models;
|
||||
using Flypaper.Storage.Entities;
|
||||
using Flypaper.Storage.Explanations;
|
||||
using Flypaper.Tests.Fakes;
|
||||
using Flypaper.Tests.Mcp;
|
||||
using Shouldly;
|
||||
|
||||
namespace Flypaper.Tests.Storage;
|
||||
|
||||
public sealed class ExplanationRuleTests : IDisposable
|
||||
{
|
||||
private readonly McpTestData _data = new();
|
||||
private readonly ExplanationRuleStore _store;
|
||||
private readonly ExplanationQueries _queries;
|
||||
|
||||
public ExplanationRuleTests()
|
||||
{
|
||||
_store = new ExplanationRuleStore(_data.Factory, new FixedTimeProvider(McpTestData.Now));
|
||||
_queries = new ExplanationQueries(_data.Factory, _store);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Highest_priority_wins_per_kind_and_older_rule_wins_ties()
|
||||
{
|
||||
var broad = await Create(ExplanationKind.Target, @"\.php", "Allgemein PHP", priority: 0);
|
||||
var narrow = await Create(ExplanationKind.Target, @"^/wp-login\.php", "WordPress-Login", priority: 10);
|
||||
var tie = await Create(ExplanationKind.Target, @"\.php", "Zweite PHP-Regel", priority: 0);
|
||||
await Create(ExplanationKind.ClientInfo, "curl", "curl", priority: 0);
|
||||
|
||||
var rules = await _store.GetRuleSetAsync();
|
||||
|
||||
rules.Winner(ExplanationKind.Target, "/wp-login.php")!.Id.ShouldBe(narrow.Id);
|
||||
rules.Winner(ExplanationKind.Target, "/x.php")!.Id.ShouldBe(broad.Id);
|
||||
rules.Matching(ExplanationKind.Target, "/x.php").Select(r => r.Id).ShouldBe([broad.Id, tie.Id]);
|
||||
rules.Winner(ExplanationKind.Target, "/x.html").ShouldBeNull();
|
||||
rules.Winner(ExplanationKind.Outcome, "curl").ShouldBeNull();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Matching_is_case_insensitive_and_explains_old_events_without_storing_anything()
|
||||
{
|
||||
await Create(ExplanationKind.Target, @"^/\.GIT/", "Git");
|
||||
await Create(ExplanationKind.ClientInfo, "^zgrab", "Scanner");
|
||||
await Create(ExplanationKind.Outcome, "^ClientAborted [0-9]{2}s$", "Kurz");
|
||||
var rules = await _store.GetRuleSetAsync();
|
||||
await using var db = _data.Factory.CreateDbContext();
|
||||
|
||||
var git = db.TrapEvents.Single(e => e.Target == "GET /.git/config");
|
||||
var zgrab = db.TrapEvents.First(e => e.ClientInfo == "zgrab/0.x");
|
||||
|
||||
rules.Explain(git).Target!.Text.ShouldBe("Git");
|
||||
rules.Explain(zgrab).Client!.Text.ShouldBe("Scanner");
|
||||
rules.Explain(git).Outcome!.Text.ShouldBe("Kurz");
|
||||
rules.Explain(zgrab).Outcome.ShouldBeNull();
|
||||
rules.Explain(git).Client.ShouldBeNull();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Rule_set_is_cached_and_changes_invalidate_it()
|
||||
{
|
||||
var rule = await Create(ExplanationKind.Target, "env", "Env");
|
||||
var first = await _store.GetRuleSetAsync();
|
||||
(await _store.GetRuleSetAsync()).ShouldBeSameAs(first);
|
||||
|
||||
await _store.SetEnabledAsync(rule.Id, false);
|
||||
var disabled = await _store.GetRuleSetAsync();
|
||||
disabled.ShouldNotBeSameAs(first);
|
||||
disabled.Winner(ExplanationKind.Target, "/.env").ShouldBeNull();
|
||||
|
||||
await _store.SetEnabledAsync(rule.Id, true);
|
||||
await _store.UpdateAsync(rule.Id, new ExplanationRuleInput(Text: "Neu"));
|
||||
(await _store.GetRuleSetAsync()).Winner(ExplanationKind.Target, "/.env")!.Text.ShouldBe("Neu");
|
||||
|
||||
await _store.DeleteAsync(rule.Id);
|
||||
(await _store.GetRuleSetAsync()).Winner(ExplanationKind.Target, "/.env").ShouldBeNull();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Update_changes_only_given_fields_and_clears_note_with_empty_string()
|
||||
{
|
||||
var rule = await _store.CreateAsync(new ExplanationRuleInput(ExplanationKind.Target, "a", "Text", 3, "CVE-1"), "Token A");
|
||||
|
||||
var updated = (await _store.UpdateAsync(rule.Id, new ExplanationRuleInput(Pattern: "b")))!;
|
||||
updated.Pattern.ShouldBe("b");
|
||||
updated.Text.ShouldBe("Text");
|
||||
updated.Priority.ShouldBe(3);
|
||||
updated.Note.ShouldBe("CVE-1");
|
||||
updated.CreatedBy.ShouldBe("Token A");
|
||||
|
||||
(await _store.UpdateAsync(rule.Id, new ExplanationRuleInput(Note: "")))!.Note.ShouldBeNull();
|
||||
(await _store.UpdateAsync(999, new ExplanationRuleInput(Text: "x"))).ShouldBeNull();
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("")]
|
||||
[InlineData("(unclosed")]
|
||||
[InlineData("(?=lookahead)x")]
|
||||
[InlineData(@"(a)\1")]
|
||||
public async Task Rejects_invalid_or_unsupported_patterns(string pattern) =>
|
||||
await Should.ThrowAsync<ArgumentException>(() => _store.CreateAsync(new ExplanationRuleInput(ExplanationKind.Target, pattern, "Text"), "test"));
|
||||
|
||||
[Fact]
|
||||
public async Task Rejects_too_long_or_non_plain_values()
|
||||
{
|
||||
ExplanationRuleInput Input(string? pattern = "x", string? text = "Text", int? priority = 0, string? note = null) =>
|
||||
new(ExplanationKind.Target, pattern, text, priority, note);
|
||||
|
||||
await Should.ThrowAsync<ArgumentException>(() => _store.CreateAsync(Input(pattern: new string('a', ExplanationLimits.MaxPatternLength + 1)), "t"));
|
||||
await Should.ThrowAsync<ArgumentException>(() => _store.CreateAsync(Input(text: new string('a', ExplanationLimits.MaxTextLength + 1)), "t"));
|
||||
await Should.ThrowAsync<ArgumentException>(() => _store.CreateAsync(Input(text: "Zeile 1\nZeile 2"), "t"));
|
||||
await Should.ThrowAsync<ArgumentException>(() => _store.CreateAsync(Input(text: " "), "t"));
|
||||
await Should.ThrowAsync<ArgumentException>(() => _store.CreateAsync(Input(note: new string('a', ExplanationLimits.MaxNoteLength + 1)), "t"));
|
||||
await Should.ThrowAsync<ArgumentException>(() => _store.CreateAsync(Input(priority: 5000), "t"));
|
||||
await Should.ThrowAsync<ArgumentException>(() => _store.CreateAsync(new ExplanationRuleInput(null, "x", "Text"), "t"));
|
||||
(await _store.ListAsync()).ShouldBeEmpty();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Pattern_cannot_hang_on_catastrophic_input()
|
||||
{
|
||||
await Create(ExplanationKind.Target, "^(a+)+$", "Evil");
|
||||
var rules = await _store.GetRuleSetAsync();
|
||||
|
||||
var started = DateTime.UtcNow;
|
||||
rules.Winner(ExplanationKind.Target, new string('a', 5000) + "!").ShouldBeNull();
|
||||
|
||||
(DateTime.UtcNow - started).ShouldBeLessThan(TimeSpan.FromSeconds(2));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Lists_unexplained_targets_grouped_by_path_with_counts()
|
||||
{
|
||||
var all = await _queries.FindUnexplainedAsync(null, UnexplainedGrouping.Path, 50);
|
||||
|
||||
all.Catches.ShouldBe(6);
|
||||
all.Groups[0].Key.ShouldBe("/.env");
|
||||
all.Groups[0].Catches.ShouldBe(2);
|
||||
all.Groups[0].ExampleUserAgent.ShouldNotBeNull();
|
||||
|
||||
await Create(ExplanationKind.Target, @"^/\.env$", "Env");
|
||||
var rest = await _queries.FindUnexplainedAsync(null, UnexplainedGrouping.Path, 2);
|
||||
|
||||
rest.Catches.ShouldBe(4);
|
||||
rest.Groups.Count.ShouldBe(2);
|
||||
rest.GroupsOmitted.ShouldBe(2);
|
||||
rest.Groups.Select(g => g.Key).ShouldNotContain("/.env");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Pattern_grouping_merges_paths_and_period_limits_the_search()
|
||||
{
|
||||
await using (var db = _data.Factory.CreateDbContext())
|
||||
{
|
||||
foreach (var number in new[] { 1, 2, 3 })
|
||||
{
|
||||
db.TrapEvents.Add(TrapEventEntity.From(new TrapEvent(
|
||||
Guid.NewGuid(), TrapProtocol.Http, System.Net.IPAddress.Parse("203.0.113.1"), "html-drip",
|
||||
McpTestData.Now.AddMinutes(-number), McpTestData.Now, 1000, TrapOutcome.ClientAborted, $"GET /backup/{number}.zip", "agent")));
|
||||
}
|
||||
|
||||
await db.SaveChangesAsync();
|
||||
}
|
||||
|
||||
var result = await _queries.FindUnexplainedAsync(McpTestData.Now.AddHours(-1).UtcDateTime, UnexplainedGrouping.Pattern, 10);
|
||||
|
||||
var group = result.Groups.Single(g => g.Key == "/backup/{n}.zip");
|
||||
group.Catches.ShouldBe(3);
|
||||
group.ExamplePaths.Count.ShouldBe(3);
|
||||
result.Groups.Select(g => g.Key).ShouldNotContain("/wp-login.php");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Test_reports_matches_newly_explained_takeovers_and_losses()
|
||||
{
|
||||
var existing = await Create(ExplanationKind.Target, @"\.env", "Allgemein", priority: 0);
|
||||
|
||||
var weaker = await _queries.TestAsync(ExplanationKind.Target, @"^/\.env$", 0, null, null);
|
||||
weaker.Catches.ShouldBe(2);
|
||||
weaker.NewlyExplained.ShouldBe(0);
|
||||
weaker.TakesOver.ShouldBeEmpty();
|
||||
|
||||
var stronger = await _queries.TestAsync(ExplanationKind.Target, @"^/\.env$", 5, null, null);
|
||||
stronger.TakesOver.ShouldHaveSingleItem().Rule.Id.ShouldBe(existing.Id);
|
||||
stronger.TakesOver[0].Catches.ShouldBe(2);
|
||||
|
||||
var fresh = await _queries.TestAsync(ExplanationKind.Target, @"wp-login", 0, null, null);
|
||||
fresh.Catches.ShouldBe(1);
|
||||
fresh.NewlyExplained.ShouldBe(1);
|
||||
fresh.Examples.ShouldHaveSingleItem().Value.ShouldBe("/wp-login.php");
|
||||
|
||||
var narrowed = await _queries.TestAsync(ExplanationKind.Target, @"^/nothing$", 0, existing.Id, null);
|
||||
narrowed.Lost.ShouldBe(2);
|
||||
narrowed.LostExamples.ShouldBe(["/.env"]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Test_matches_client_info_and_outcome_text()
|
||||
{
|
||||
(await _queries.TestAsync(ExplanationKind.ClientInfo, "^curl/", 0, null, null)).Catches.ShouldBe(2);
|
||||
(await _queries.TestAsync(ExplanationKind.Outcome, "^Rejected$", 0, null, null)).Catches.ShouldBe(1);
|
||||
(await _queries.TestAsync(ExplanationKind.Outcome, @"^ClientAborted \d{1,2}s$", 0, null, null)).Catches.ShouldBe(2);
|
||||
await Should.ThrowAsync<ArgumentException>(() => _queries.TestAsync(ExplanationKind.Target, "(", 0, null, null));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Counts_hits_per_rule_including_disabled_ones()
|
||||
{
|
||||
var env = await Create(ExplanationKind.Target, @"^/\.env$", "Env");
|
||||
var off = await Create(ExplanationKind.ClientInfo, "^curl", "curl");
|
||||
await _store.SetEnabledAsync(off.Id, false);
|
||||
|
||||
var hits = await _queries.CountHitsAsync();
|
||||
|
||||
hits[env.Id].ShouldBe(2);
|
||||
hits[off.Id].ShouldBe(2);
|
||||
}
|
||||
|
||||
private Task<ExplanationRuleEntity> Create(ExplanationKind kind, string pattern, string text, int priority = 0) =>
|
||||
_store.CreateAsync(new ExplanationRuleInput(kind, pattern, text, priority), "test");
|
||||
|
||||
public void Dispose() => _data.Dispose();
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
using Flypaper.Core.Models;
|
||||
using Flypaper.Storage.Explanations;
|
||||
using Shouldly;
|
||||
|
||||
namespace Flypaper.Tests.Storage;
|
||||
|
||||
public sealed class ExplanationTextTests
|
||||
{
|
||||
[Theory]
|
||||
[InlineData("GET 188.103.168.113/.git/HEAD", "/.git/HEAD")]
|
||||
[InlineData("GET anticarnist.de/", "/")]
|
||||
[InlineData("GET /", "/")]
|
||||
[InlineData("GET /x.php?a=1/2", "/x.php?a=1/2")]
|
||||
[InlineData("GET _/boaform/admin", "/boaform/admin")]
|
||||
[InlineData("GET example.com", "/")]
|
||||
[InlineData("POST example.com:8080/api?x=/y", "/api?x=/y")]
|
||||
[InlineData("raw", "raw")]
|
||||
[InlineData(null, null)]
|
||||
public void Extracts_the_path_without_method_and_host(string? target, string? expected) =>
|
||||
ExplanationText.Path(target).ShouldBe(expected);
|
||||
|
||||
[Theory]
|
||||
[InlineData(TrapOutcome.ClientAborted, 9400, "ClientAborted 9s")]
|
||||
[InlineData(TrapOutcome.Timeout, 60000, "Timeout 60s")]
|
||||
[InlineData(TrapOutcome.Completed, 999, "Completed 0s")]
|
||||
[InlineData(TrapOutcome.Rejected, 0, "Rejected")]
|
||||
public void Describes_outcome_and_whole_seconds(TrapOutcome outcome, long milliseconds, string expected) =>
|
||||
ExplanationText.Outcome(outcome, milliseconds).ShouldBe(expected);
|
||||
|
||||
[Theory]
|
||||
[InlineData("/wp-content/uploads/2024/05/x.php?v=3", "/wp-content/uploads/{n}/{n}/x.php")]
|
||||
[InlineData("/a/0123456789abcdef/b", "/a/{hex}/b")]
|
||||
[InlineData("/.env", "/.env")]
|
||||
public void Merges_paths_that_differ_only_in_numbers(string path, string expected) =>
|
||||
ExplanationText.PathShape(path).ShouldBe(expected);
|
||||
}
|
||||
@@ -3,6 +3,7 @@ using Flypaper.Core.Models;
|
||||
using Flypaper.Storage.Entities;
|
||||
using Flypaper.Web.Components.Shared;
|
||||
using Flypaper.Storage.Dashboard;
|
||||
using Flypaper.Storage.Explanations;
|
||||
using Flypaper.Tests.Fakes;
|
||||
using Flypaper.Tests.Mcp;
|
||||
using Shouldly;
|
||||
@@ -13,8 +14,9 @@ public sealed class RecentCatchesTests : IDisposable
|
||||
{
|
||||
private readonly McpTestData _data = new();
|
||||
private readonly DashboardQueries _queries;
|
||||
private readonly ExplanationRuleStore _rules;
|
||||
|
||||
public RecentCatchesTests() => _queries = new DashboardQueries(_data.Factory, new FixedTimeProvider(McpTestData.Now));
|
||||
public RecentCatchesTests() => _queries = new DashboardQueries(_data.Factory, new FixedTimeProvider(McpTestData.Now), _rules = new ExplanationRuleStore(_data.Factory, new FixedTimeProvider(McpTestData.Now)));
|
||||
|
||||
[Fact]
|
||||
public async Task Without_filters_returns_all_events_newest_first()
|
||||
@@ -47,6 +49,19 @@ public sealed class RecentCatchesTests : IDisposable
|
||||
recent.Total.ShouldBe(expected);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Unexplained_filter_keeps_only_targets_without_an_enabled_target_rule()
|
||||
{
|
||||
(await _queries.GetRecentAsync(new RecentFilter(Unexplained: true))).Total.ShouldBe(6);
|
||||
|
||||
await _rules.CreateAsync(new ExplanationRuleInput(ExplanationKind.Target, @"^/\.env$", "Sucht nach Zugangsdaten."), "test");
|
||||
var recent = await _queries.GetRecentAsync(new RecentFilter(Unexplained: true));
|
||||
|
||||
recent.Total.ShouldBe(4);
|
||||
recent.Items.Select(e => e.Target).ShouldNotContain("GET /.env");
|
||||
recent.Items.Select(e => e.StartedAt).ShouldBeInOrder(SortDirection.Descending);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Matches_strategy_exactly()
|
||||
{
|
||||
|
||||
Reference in new issue
Block a user