Files
Flypaper/test/Flypaper.Tests/Mcp/McpEndpointTests.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

296 lines
14 KiB
C#

using System.Net;
using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;
using Flypaper.Web.Mcp;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.Extensions.DependencyInjection;
using Shouldly;
namespace Flypaper.Tests.Mcp;
public sealed class McpEndpointTests : IDisposable
{
private readonly McpTestData _data = new();
private readonly WebApplicationFactory<Program> _factory;
public McpEndpointTests()
{
_factory = new WebApplicationFactory<Program>().WithWebHostBuilder(builder =>
{
builder.UseSetting("ConnectionStrings:Flypaper", _data.ConnectionString);
builder.UseSetting("Flypaper:Ports:Dashboard", "0");
});
}
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()
{
using var client = _factory.CreateClient();
var response = await client.SendAsync(Rpc("tools/list", token: null));
response.StatusCode.ShouldBe(HttpStatusCode.Unauthorized);
response.Headers.WwwAuthenticate.ToString().ShouldStartWith("Bearer");
}
[Fact]
public async Task Rejects_requests_with_wrong_token()
{
using var client = _factory.CreateClient();
await _factory.Services.GetRequiredService<McpTokenService>().CreateAsync("real");
var response = await client.SendAsync(Rpc("tools/list", token: "fpm_wrong"));
response.StatusCode.ShouldBe(HttpStatusCode.Unauthorized);
}
[Fact]
public async Task Serves_initialize_tools_list_and_get_stats_with_valid_token()
{
using var client = _factory.CreateClient();
var token = await _factory.Services.GetRequiredService<McpTokenService>().CreateAsync("test");
var initialize = await ReadAsync(await client.SendAsync(Rpc("initialize", token, new
{
protocolVersion = "2025-06-18",
capabilities = new { },
clientInfo = new { name = "test", version = "1.0" }
})));
initialize.GetProperty("result").GetProperty("serverInfo").GetProperty("name").GetString().ShouldBe("flypaper");
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(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();
var stats = await ReadAsync(await client.SendAsync(Rpc("tools/call", token, new { name = "get_stats", arguments = new { period = "all" } })));
var structured = stats.GetProperty("result").GetProperty("structuredContent");
structured.GetProperty("catches").GetInt32().ShouldBe(5);
structured.GetProperty("period").GetString().ShouldBe("all");
structured.GetProperty("since").ValueKind.ShouldBe(JsonValueKind.Null);
}
public static TheoryData<string, string> ToolCalls => new()
{
{ "get_stats", """{"period":"all"}""" },
{ "get_stats", """{"period":"24h"}""" },
{ "list_catches", """{}""" },
{ "list_catches", """{"country":"CN","limit":1}""" },
{ "top", """{"dimension":"ips","period":"all"}""" },
{ "top", """{"dimension":"countries","period":"all"}""" },
{ "top", """{"dimension":"countries","period":"24h"}""" },
{ "top", """{"dimension":"providers","period":"all"}""" },
{ "top", """{"dimension":"targets","period":"all"}""" },
{ "top", """{"dimension":"user_agents","period":"all"}""" },
{ "longest_catches", """{"period":"all"}""" },
{ "lookup_ip", """{"ip":"203.0.113.9"}""" },
{ "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]
[MemberData(nameof(ToolCalls))]
public async Task Tool_results_match_their_output_schema(string tool, string arguments)
{
using var client = _factory.CreateClient();
var token = await _factory.Services.GetRequiredService<McpTokenService>().CreateAsync("test");
var schema = (await OutputSchemasAsync(client, token))[tool];
var response = await ReadAsync(await client.SendAsync(Rpc("tools/call", token, new { name = tool, arguments = JsonDocument.Parse(arguments).RootElement })));
var result = response.GetProperty("result");
(result.TryGetProperty("isError", out var isError) && isError.GetBoolean()).ShouldBeFalse(result.ToString());
var errors = new List<string>();
Validate(schema, result.GetProperty("structuredContent"), "$", errors);
errors.ShouldBeEmpty();
}
[Fact]
public async Task Every_listed_tool_is_covered_by_the_schema_test()
{
using var client = _factory.CreateClient();
var token = await _factory.Services.GetRequiredService<McpTokenService>().CreateAsync("test");
var listed = (await OutputSchemasAsync(client, token)).Keys;
listed.ShouldBe(ToolCalls.Select(row => (string)row[0]!).Distinct(), ignoreOrder: true);
}
[Theory]
[InlineData("top", """{"by":"countries","period":"all"}""", "unknown parameter 'by'; expected 'dimension' (ips|countries|providers|targets|strategies|user_agents)")]
[InlineData("top", """{"period":"all"}""", "missing required parameter 'dimension' (ips|countries|providers|targets|strategies|user_agents)")]
[InlineData("list_catches", """{"countryCode":"GB"}""", "unknown parameter 'countryCode'")]
public async Task Invalid_arguments_return_a_readable_tool_error(string tool, string arguments, string expected)
{
using var client = _factory.CreateClient();
var token = await _factory.Services.GetRequiredService<McpTokenService>().CreateAsync("test");
var response = await ReadAsync(await client.SendAsync(Rpc("tools/call", token, new { name = tool, arguments = JsonDocument.Parse(arguments).RootElement })));
var result = response.GetProperty("result");
result.GetProperty("isError").GetBoolean().ShouldBeTrue();
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)));
return tools.GetProperty("result").GetProperty("tools").EnumerateArray()
.ToDictionary(t => t.GetProperty("name").GetString()!, t => t.GetProperty("outputSchema"));
}
private static void Validate(JsonElement schema, JsonElement value, string path, List<string> errors)
{
if (schema.TryGetProperty("type", out var type))
{
var allowed = type.ValueKind == JsonValueKind.Array
? type.EnumerateArray().Select(t => t.GetString()!).ToList()
: [type.GetString()!];
if (!allowed.Any(t => HasType(value, t)))
{
errors.Add($"{path}: {value.ValueKind} is not {string.Join(" or ", allowed)}");
return;
}
}
if (schema.TryGetProperty("enum", out var values) && !values.EnumerateArray().Any(v => v.ToString() == value.ToString()))
{
errors.Add($"{path}: {value} is not one of {values}");
}
if (value.ValueKind == JsonValueKind.Object)
{
if (schema.TryGetProperty("required", out var required))
{
errors.AddRange(required.EnumerateArray()
.Where(name => !value.TryGetProperty(name.GetString()!, out _))
.Select(name => $"{path}: missing required property '{name.GetString()}'"));
}
if (schema.TryGetProperty("properties", out var properties))
{
foreach (var property in properties.EnumerateObject())
{
if (value.TryGetProperty(property.Name, out var child))
{
Validate(property.Value, child, $"{path}.{property.Name}", errors);
}
}
}
}
if (value.ValueKind == JsonValueKind.Array && schema.TryGetProperty("items", out var items))
{
var index = 0;
foreach (var item in value.EnumerateArray())
{
Validate(items, item, $"{path}[{index++}]", errors);
}
}
}
private static bool HasType(JsonElement value, string type) => type switch
{
"object" => value.ValueKind == JsonValueKind.Object,
"array" => value.ValueKind == JsonValueKind.Array,
"string" => value.ValueKind == JsonValueKind.String,
"integer" => value.ValueKind == JsonValueKind.Number && value.TryGetInt64(out _),
"number" => value.ValueKind == JsonValueKind.Number,
"boolean" => value.ValueKind is JsonValueKind.True or JsonValueKind.False,
"null" => value.ValueKind == JsonValueKind.Null,
_ => throw new NotSupportedException($"Schema type '{type}'")
};
private static HttpRequestMessage Rpc(string method, string? token, object? parameters = null)
{
var body = JsonSerializer.Serialize(new { jsonrpc = "2.0", id = 1, method, @params = parameters ?? new { } });
var request = new HttpRequestMessage(HttpMethod.Post, "/mcp")
{
Content = new StringContent(body, Encoding.UTF8, "application/json")
};
request.Headers.Accept.ParseAdd("application/json");
request.Headers.Accept.ParseAdd("text/event-stream");
request.Headers.Add("MCP-Protocol-Version", "2025-06-18");
if (token is not null)
{
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
}
return request;
}
private static async Task<JsonElement> ReadAsync(HttpResponseMessage response)
{
response.StatusCode.ShouldBe(HttpStatusCode.OK);
var text = await response.Content.ReadAsStringAsync();
var json = response.Content.Headers.ContentType?.MediaType == "text/event-stream"
? string.Join("", text.Split('\n').Where(l => l.StartsWith("data:", StringComparison.Ordinal)).Select(l => l[5..].Trim()))
: text;
return JsonDocument.Parse(json).RootElement.Clone();
}
public void Dispose()
{
_factory.Dispose();
_data.Dispose();
}
}