Add read-only MCP server with token access
Build and deploy / build (push) Successful in 1m31s
Build and deploy / deploy (push) Successful in 20s

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
TomandClaude Opus 5.5 committed 2026-11-15 13:34:16 +01:00
1 parent b8328f6998
commit 49a8fa1154
34 files changed
+1625

No files matched your search

@@ -0,0 +1,153 @@
using Flypaper.Core.Abstractions;
using Flypaper.Storage.Queries;
using Flypaper.Tests.Fakes;
using Flypaper.Web.Mcp;
using ModelContextProtocol;
using NSubstitute;
using Shouldly;
namespace Flypaper.Tests.Mcp;
public sealed class FlypaperToolsTests : IDisposable
{
private readonly McpTestData _data = new();
private readonly FlypaperTools _tools;
public FlypaperToolsTests()
{
var governor = Substitute.For<IConnectionGovernor>();
governor.ActiveConnections.Returns(2);
_tools = new FlypaperTools(new CatchQueries(_data.Factory), governor, new FixedTimeProvider(McpTestData.Now));
}
[Fact]
public async Task Get_stats_summarizes_the_period()
{
var stats = await _tools.GetStats("24h");
stats.Period.ShouldBe("24h");
stats.Since.ShouldBe(McpTestData.Now.UtcDateTime.AddHours(-24));
stats.Catches.ShouldBe(3);
stats.Rejected.ShouldBe(1);
stats.UniqueIps.ShouldBe(2);
stats.TotalHoldSeconds.ShouldBe(3750);
stats.AverageHoldSeconds.ShouldBe(1250);
stats.ActiveTraps.ShouldBe(2);
stats.LongestCatch.ShouldNotBeNull().DurationSeconds.ShouldBe(3600);
stats.LongestCatch!.Country.ShouldBe("China");
stats.LongestCatch.Asn.ShouldBe("AS4134");
stats.LongestCatch.StartedAt.Kind.ShouldBe(DateTimeKind.Utc);
}
[Fact]
public async Task Get_stats_for_all_time()
{
var stats = await _tools.GetStats("all");
stats.Since.ShouldBeNull();
stats.Catches.ShouldBe(5);
stats.UniqueIps.ShouldBe(4);
}
[Theory]
[InlineData("yesterday")]
[InlineData("0h")]
[InlineData("-1d")]
public async Task Rejects_invalid_periods(string period) =>
await Should.ThrowAsync<McpException>(() => _tools.GetStats(period));
[Fact]
public async Task List_catches_returns_newest_first_with_rejected_ones()
{
var result = await _tools.ListCatches();
result.Count.ShouldBe(6);
result.Catches.Select(c => c.StartedAt).ShouldBeInOrder(SortDirection.Descending);
result.Catches.ShouldContain(c => c.Outcome == "Rejected");
}
[Theory]
[InlineData("cn", null, null, null, 2)]
[InlineData(null, "AS3462", null, null, 2)]
[InlineData(null, "google", null, null, 1)]
[InlineData(null, null, "198.51.100.7", null, 2)]
[InlineData(null, null, null, ".ENV", 2)]
[InlineData("CN", null, null, "wp-login", 1)]
public async Task List_catches_filters(string? country, string? provider, string? ip, string? target, int expected)
{
var result = await _tools.ListCatches(country: country, provider: provider, ip: ip, target_contains: target);
result.Count.ShouldBe(expected);
}
[Fact]
public async Task List_catches_filters_by_time_and_limit()
{
var since = McpTestData.Now.AddHours(-3.5).ToString("O");
var until = McpTestData.Now.AddHours(-1.5).ToString("O");
(await _tools.ListCatches(since: since, until: until)).Count.ShouldBe(2);
(await _tools.ListCatches(limit: 1)).Count.ShouldBe(1);
(await _tools.ListCatches(limit: 100_000)).Count.ShouldBe(6);
await Should.ThrowAsync<McpException>(() => _tools.ListCatches(since: "last tuesday"));
await Should.ThrowAsync<McpException>(() => _tools.ListCatches(ip: "not-an-ip"));
}
[Theory]
[InlineData("ips", "203.0.113.9", 2)]
[InlineData("countries", "CN", 2)]
[InlineData("providers", "AS4134", 2)]
[InlineData("targets", "GET /.env", 1)]
[InlineData("user_agents", "zgrab/0.x", 2)]
public async Task Top_ranks_each_dimension(string dimension, string firstKey, int firstCount)
{
var result = await _tools.Top(dimension, "all");
result.Dimension.ShouldBe(dimension);
result.Items[0].Key.ShouldBe(firstKey);
result.Items[0].Catches.ShouldBe(firstCount);
}
[Fact]
public async Task Top_uses_common_country_names_and_rejects_unknown_dimensions()
{
var countries = await _tools.Top("countries", "24h");
countries.Items.Select(i => i.Label).ShouldBe(["China", "Taiwan"]);
await Should.ThrowAsync<McpException>(() => _tools.Top("cities"));
}
[Fact]
public async Task Longest_catches_are_ordered_by_duration()
{
var result = await _tools.LongestCatches("all", 3);
result.Catches.Select(c => c.DurationSeconds).ShouldBe([3600, 900, 120]);
}
[Fact]
public async Task Lookup_ip_returns_everything_known()
{
var result = await _tools.LookupIp("198.51.100.7");
result.Known.ShouldBeTrue();
result.Country.ShouldBe("Taiwan");
result.Asn.ShouldBe("AS3462");
result.Catches.ShouldBe(1);
result.Rejected.ShouldBe(1);
result.TotalHoldSeconds.ShouldBe(30);
result.FirstSeen.ShouldBe(McpTestData.Now.UtcDateTime.AddHours(-4));
result.LastSeen.ShouldBe(McpTestData.Now.UtcDateTime.AddHours(-3).AddSeconds(30));
result.Events.Count.ShouldBe(2);
}
[Fact]
public async Task Lookup_ip_handles_unknown_and_invalid_addresses()
{
(await _tools.LookupIp("192.0.2.99")).Known.ShouldBeFalse();
(await _tools.LookupIp("2001:0db8::0001")).Known.ShouldBeTrue();
await Should.ThrowAsync<McpException>(() => _tools.LookupIp("999.1.1.1"));
}
public void Dispose() => _data.Dispose();
}
+113
View File
@@ -0,0 +1,113 @@
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.Data.Sqlite;
using Microsoft.Extensions.DependencyInjection;
using Shouldly;
namespace Flypaper.Tests.Mcp;
public sealed class McpEndpointTests : IDisposable
{
private readonly string _dbPath = Path.Combine(Path.GetTempPath(), $"flypaper-mcp-http-{Guid.NewGuid():N}.db");
private readonly WebApplicationFactory<Program> _factory;
public McpEndpointTests()
{
_factory = new WebApplicationFactory<Program>().WithWebHostBuilder(builder =>
{
builder.UseSetting("ConnectionStrings:Flypaper", $"Data Source={_dbPath}");
builder.UseSetting("Flypaper:Ports:Dashboard", "0");
});
}
[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(["get_stats", "list_catches", "longest_catches", "lookup_ip", "top"], 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(0);
structured.GetProperty("period").GetString().ShouldBe("all");
}
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();
SqliteConnection.ClearAllPools();
foreach (var suffix in new[] { "", "-wal", "-shm" })
{
File.Delete(_dbPath + suffix);
}
}
}
+77
View File
@@ -0,0 +1,77 @@
using System.Net;
using Flypaper.Core.Models;
using Flypaper.Storage;
using Flypaper.Storage.Entities;
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
namespace Flypaper.Tests.Mcp;
internal sealed class McpTestData : IDisposable
{
public static readonly DateTimeOffset Now = new(2026, 11, 15, 12, 0, 0, TimeSpan.Zero);
private readonly string _dbPath = Path.Combine(Path.GetTempPath(), $"flypaper-mcp-{Guid.NewGuid():N}.db");
public McpTestData()
{
Factory = new TestDbContextFactory($"Data Source={_dbPath}");
using var db = Factory.CreateDbContext();
db.Database.Migrate();
Add(db, "203.0.113.9", hoursAgo: 1, seconds: 3600, "CN", "Volksrepublik China", "Beijing", 4134, "Chinanet", "GET /.env", "zgrab/0.x");
Add(db, "203.0.113.9", hoursAgo: 2, seconds: 120, "CN", "Volksrepublik China", "Beijing", 4134, "Chinanet", "GET example.com/wp-login.php", "zgrab/0.x");
Add(db, "198.51.100.7", hoursAgo: 3, seconds: 30, "TW", "Republik China", "Taipeh", 3462, "Data Communication Business Group", "GET /.git/config", "curl/8.5.0");
Add(db, "2001:db8::1", hoursAgo: 30, seconds: 900, "US", "Vereinigte Staaten von Amerika", "Mountain View", 15169, "Google LLC", "POST /xmlrpc.php", "python-requests/2.31");
Add(db, "198.51.100.7", hoursAgo: 4, seconds: 0, "TW", "Republik China", "Taipeh", 3462, "Data Communication Business Group", "GET /.env", "curl/8.5.0", TrapOutcome.Rejected);
Add(db, "192.0.2.50", hoursAgo: 200, seconds: 5, null, null, null, null, null, "GET /", null);
db.SaveChanges();
}
public IDbContextFactory<FlypaperDbContext> Factory { get; }
private static void Add(
FlypaperDbContext db,
string ip,
int hoursAgo,
int seconds,
string? countryCode,
string? country,
string? city,
long? asn,
string? provider,
string target,
string? userAgent,
TrapOutcome outcome = TrapOutcome.ClientAborted)
{
var started = Now.AddHours(-hoursAgo);
var entity = TrapEventEntity.From(new TrapEvent(
Guid.NewGuid(),
TrapProtocol.Http,
IPAddress.Parse(ip),
"html-drip",
started,
started.AddSeconds(seconds),
seconds * 10,
outcome,
target,
userAgent));
entity.ApplyOrigin(countryCode is null && asn is null ? null : new IpOrigin(countryCode, country, city, asn, provider));
db.TrapEvents.Add(entity);
}
public void Dispose()
{
SqliteConnection.ClearAllPools();
foreach (var suffix in new[] { "", "-wal", "-shm" })
{
File.Delete(_dbPath + suffix);
}
}
private sealed class TestDbContextFactory(string connectionString) : IDbContextFactory<FlypaperDbContext>
{
public FlypaperDbContext CreateDbContext() =>
new(new DbContextOptionsBuilder<FlypaperDbContext>().UseSqlite(connectionString).Options);
}
}
@@ -0,0 +1,62 @@
using Flypaper.Storage.Settings;
using Flypaper.Tests.Fakes;
using Flypaper.Web.Mcp;
using Microsoft.Extensions.Options;
using Shouldly;
namespace Flypaper.Tests.Mcp;
public sealed class McpTokenServiceTests : IDisposable
{
private readonly McpTestData _data = new();
private readonly McpTokenStore _store;
public McpTokenServiceTests() => _store = new McpTokenStore(_data.Factory, new FixedTimeProvider(McpTestData.Now));
[Fact]
public async Task Created_token_is_valid_and_stored_only_as_hash()
{
var service = Create(environmentToken: null);
var token = await service.CreateAsync("Claude Desktop");
token.Length.ShouldBeGreaterThan(40);
(await service.ValidateAsync(token)).ShouldBeTrue();
var stored = (await _store.ListAsync()).ShouldHaveSingleItem();
stored.Name.ShouldBe("Claude Desktop");
stored.TokenHash.ShouldBe(McpTokenService.Hash(token));
stored.TokenHash.ShouldNotContain(token);
stored.LastUsedAt.ShouldBe(McpTestData.Now.UtcDateTime);
}
[Fact]
public async Task Wrong_missing_and_revoked_tokens_are_rejected()
{
var service = Create(environmentToken: null);
var token = await service.CreateAsync("test");
(await service.ValidateAsync(null)).ShouldBeFalse();
(await service.ValidateAsync("")).ShouldBeFalse();
(await service.ValidateAsync(token + "x")).ShouldBeFalse();
(await _store.RevokeAsync((await _store.ListAsync())[0].Id)).ShouldBeTrue();
(await service.ValidateAsync(token)).ShouldBeFalse();
}
[Fact]
public async Task Environment_token_is_accepted_alongside_stored_ones()
{
var service = Create(environmentToken: "fixed-token-from-environment");
var stored = await service.CreateAsync("test");
service.UsesEnvironmentToken.ShouldBeTrue();
(await service.ValidateAsync("fixed-token-from-environment")).ShouldBeTrue();
(await service.ValidateAsync(stored)).ShouldBeTrue();
(await service.ValidateAsync("fixed-token")).ShouldBeFalse();
}
private McpTokenService Create(string? environmentToken) =>
new(_store, Options.Create(new McpOptions { Token = environmentToken }));
public void Dispose() => _data.Dispose();
}
@@ -0,0 +1,36 @@
using Flypaper.Storage.Queries;
using Shouldly;
namespace Flypaper.Tests.Mcp;
public sealed class QueryPeriodTests
{
[Theory]
[InlineData("30m", 0.5)]
[InlineData("1h", 1)]
[InlineData("24H", 24)]
[InlineData("7d", 168)]
[InlineData("2w", 336)]
public void Parses_relative_periods(string value, double hours)
{
QueryPeriod.TryParse(value, out var span).ShouldBeTrue();
span.ShouldBe(TimeSpan.FromHours(hours));
}
[Theory]
[InlineData("all")]
[InlineData("")]
[InlineData(null)]
public void Treats_all_as_unbounded(string? value)
{
QueryPeriod.TryParse(value, out var span).ShouldBeTrue();
span.ShouldBeNull();
}
[Theory]
[InlineData("0d")]
[InlineData("1y")]
[InlineData("1.5h")]
[InlineData("h")]
public void Rejects_other_values(string value) => QueryPeriod.TryParse(value, out _).ShouldBeFalse();
}