Add explanation rules for catches, editable over MCP
Build and deploy / build (push) Successful in 1m29s
Build and deploy / deploy (push) Successful in 21s

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
TomandClaude Opus 5.5 committed 2026-11-21 11:46:22 +01:00
1 parent 4086fa3da3
commit 2437880013
37 files changed
+1867 -37

No files matched your search

+58 -2
View File
@@ -23,6 +23,9 @@ public sealed class McpEndpointTests : IDisposable
});
}
private static readonly string[] ReadTools =
["get_stats", "list_catches", "longest_catches", "lookup_ip", "top", "list_explanation_rules", "list_unexplained", "test_explanation_rule"];
[Fact]
public async Task Rejects_requests_without_token()
{
@@ -62,7 +65,7 @@ public sealed class McpEndpointTests : IDisposable
var tools = await ReadAsync(await client.SendAsync(Rpc("tools/list", token)));
var listed = tools.GetProperty("result").GetProperty("tools").EnumerateArray().ToList();
listed.Select(t => t.GetProperty("name").GetString())
.ShouldBe(["get_stats", "list_catches", "longest_catches", "lookup_ip", "top"], ignoreOrder: true);
.ShouldBe(ReadTools, ignoreOrder: true);
listed.ShouldAllBe(t => t.GetProperty("annotations").GetProperty("readOnlyHint").GetBoolean());
listed.Where(t => !t.TryGetProperty("outputSchema", out var schema) || schema.ValueKind != JsonValueKind.Object).ShouldBeEmpty();
@@ -87,7 +90,13 @@ public sealed class McpEndpointTests : IDisposable
{ "top", """{"dimension":"user_agents","period":"all"}""" },
{ "longest_catches", """{"period":"all"}""" },
{ "lookup_ip", """{"ip":"203.0.113.9"}""" },
{ "lookup_ip", """{"ip":"192.0.2.1"}""" }
{ "lookup_ip", """{"ip":"192.0.2.1"}""" },
{ "list_explanation_rules", """{}""" },
{ "list_unexplained", """{}""" },
{ "list_unexplained", """{"period":"7d","group_by":"path","limit":5}""" },
{ "test_explanation_rule", """{"kind":"target","pattern":"^/\\.env"}""" },
{ "test_explanation_rule", """{"kind":"client_info","pattern":"curl","priority":5}""" },
{ "test_explanation_rule", """{"kind":"outcome","pattern":"^Rejected$"}""" }
};
[Theory]
@@ -134,6 +143,53 @@ public sealed class McpEndpointTests : IDisposable
result.GetProperty("content")[0].GetProperty("text").GetString().ShouldNotBeNull().ShouldContain(expected, Case.Sensitive);
}
[Fact]
public async Task Write_tools_are_only_offered_to_and_usable_by_tokens_with_write_permission()
{
using var client = _factory.CreateClient();
var tokens = _factory.Services.GetRequiredService<McpTokenService>();
var readOnly = await tokens.CreateAsync("read");
var writer = await tokens.CreateAsync("Claude Code", canWrite: true);
var writerTools = (await ReadAsync(await client.SendAsync(Rpc("tools/list", writer)))).GetProperty("result").GetProperty("tools")
.EnumerateArray().Select(t => t.GetProperty("name").GetString()).ToList();
writerTools.ShouldBe(
[.. ReadTools, "create_explanation_rule", "update_explanation_rule", "set_explanation_rule_enabled", "delete_explanation_rule"],
ignoreOrder: true);
var denied = (await ReadAsync(await client.SendAsync(Rpc("tools/call", readOnly, new
{
name = "create_explanation_rule",
arguments = new { kind = "target", pattern = "^/\\.env$", text = "Sucht nach einer Konfigurationsdatei." }
})))).GetProperty("result");
denied.GetProperty("isError").GetBoolean().ShouldBeTrue();
denied.GetProperty("content")[0].GetProperty("text").GetString().ShouldNotBeNull().ShouldContain("write permission");
var created = (await ReadAsync(await client.SendAsync(Rpc("tools/call", writer, new
{
name = "create_explanation_rule",
arguments = new { kind = "target", pattern = "^/\\.env$", text = "Sucht nach einer Konfigurationsdatei.", priority = 5, note = "CVE-0000-0000" }
})))).GetProperty("result");
(created.TryGetProperty("isError", out var isError) && isError.GetBoolean()).ShouldBeFalse(created.ToString());
var rule = created.GetProperty("structuredContent");
rule.GetProperty("kind").GetString().ShouldBe("target");
rule.GetProperty("createdBy").GetString().ShouldBe("Claude Code");
rule.GetProperty("enabled").GetBoolean().ShouldBeTrue();
var listed = (await ReadAsync(await client.SendAsync(Rpc("tools/call", readOnly, new { name = "list_explanation_rules", arguments = new { } }))))
.GetProperty("result").GetProperty("structuredContent");
listed.GetProperty("count").GetInt32().ShouldBe(1);
listed.GetProperty("rules")[0].GetProperty("catches").GetInt32().ShouldBe(2);
var invalid = (await ReadAsync(await client.SendAsync(Rpc("tools/call", writer, new
{
name = "create_explanation_rule",
arguments = new { kind = "target", pattern = "(unclosed", text = "Text" }
})))).GetProperty("result");
invalid.GetProperty("isError").GetBoolean().ShouldBeTrue();
invalid.GetProperty("content")[0].GetProperty("text").GetString().ShouldNotBeNull().ShouldContain("regular expression");
}
private static async Task<Dictionary<string, JsonElement>> OutputSchemasAsync(HttpClient client, string token)
{
var tools = await ReadAsync(await client.SendAsync(Rpc("tools/list", token)));
@@ -21,7 +21,7 @@ public sealed class McpTokenServiceTests : IDisposable
var token = await service.CreateAsync("Claude Desktop");
token.Length.ShouldBeGreaterThan(40);
(await service.AuthenticateAsync(token)).ShouldBeTrue();
(await service.AuthenticateAsync(token)).ShouldNotBeNull();
var stored = (await _store.ListAsync()).ShouldHaveSingleItem();
stored.Name.ShouldBe("Claude Desktop");
stored.TokenHash.ShouldBe(McpTokenService.Hash(token));
@@ -35,12 +35,12 @@ public sealed class McpTokenServiceTests : IDisposable
var service = Create(environmentToken: null);
var token = await service.CreateAsync("test");
(await service.AuthenticateAsync(null)).ShouldBeFalse();
(await service.AuthenticateAsync("")).ShouldBeFalse();
(await service.AuthenticateAsync(token + "x")).ShouldBeFalse();
(await service.AuthenticateAsync(null)).ShouldBeNull();
(await service.AuthenticateAsync("")).ShouldBeNull();
(await service.AuthenticateAsync(token + "x")).ShouldBeNull();
(await _store.RevokeAsync((await _store.ListAsync())[0].Id)).ShouldBeTrue();
(await service.AuthenticateAsync(token)).ShouldBeFalse();
(await service.AuthenticateAsync(token)).ShouldBeNull();
}
[Fact]
@@ -50,9 +50,32 @@ public sealed class McpTokenServiceTests : IDisposable
var stored = await service.CreateAsync("test");
service.UsesEnvironmentToken.ShouldBeTrue();
(await service.AuthenticateAsync("fixed-token-from-environment")).ShouldBeTrue();
(await service.AuthenticateAsync(stored)).ShouldBeTrue();
(await service.AuthenticateAsync("fixed-token")).ShouldBeFalse();
(await service.AuthenticateAsync("fixed-token-from-environment")).ShouldNotBeNull();
(await service.AuthenticateAsync(stored)).ShouldNotBeNull();
(await service.AuthenticateAsync("fixed-token")).ShouldBeNull();
}
[Fact]
public async Task Write_permission_is_granted_per_token_and_can_be_withdrawn()
{
var service = Create(environmentToken: null);
var readOnly = await service.CreateAsync("read");
var writer = await service.CreateAsync("write", canWrite: true);
(await service.AuthenticateAsync(readOnly)).ShouldBe(new McpAccess("read", false));
(await service.AuthenticateAsync(writer)).ShouldBe(new McpAccess("write", true));
var id = (await _store.ListAsync()).Single(t => t.Name == "write").Id;
(await _store.SetCanWriteAsync(id, false)).ShouldBeTrue();
(await service.AuthenticateAsync(writer)).ShouldBe(new McpAccess("write", false));
}
[Fact]
public async Task Environment_token_never_has_write_permission()
{
var service = Create(environmentToken: "fixed-token-from-environment");
(await service.AuthenticateAsync("fixed-token-from-environment")).ShouldBe(new McpAccess(McpTokenService.EnvironmentTokenName, false));
}
private McpTokenService Create(string? environmentToken) =>
@@ -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()
{
@@ -75,4 +75,17 @@ public sealed class DashboardFilterTests
new DashboardFilter().NextLimit.ShouldBe(100);
new DashboardFilter(Limit: 400).NextLimit.ShouldBe(RecentFilter.MaxLimit);
}
[Theory]
[InlineData("ohne", true)]
[InlineData("OHNE", true)]
[InlineData("alle", false)]
[InlineData(null, false)]
public void Parses_the_unexplained_filter_and_keeps_it_in_the_link(string? value, bool expected)
{
var filter = DashboardFilter.Parse(null, null, null, null, null, null, null, null, null, value);
filter.ToRecentFilter().Unexplained.ShouldBe(expected);
filter.Href().Contains("erklaerung=ohne").ShouldBe(expected);
}
}