Files
Flypaper/test/Flypaper.Tests/Storage/ExplanationRuleTests.cs
T
TomandClaude Opus 5.5 2437880013
Build and deploy / build (push) Successful in 1m29s
Build and deploy / deploy (push) Successful in 21s
Add explanation rules for catches, editable over MCP
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 11:46:22 +01:00

223 lines
10 KiB
C#

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();
}