From 49a8fa11542967c96f47322325440f0f43382d4d Mon Sep 17 00:00:00 2001 From: Tom Date: Sun, 15 Nov 2026 13:34:16 +0100 Subject: [PATCH] Add read-only MCP server with token access Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 8 + Directory.Packages.props | 1 + README.md | 1 + docs/configuration.md | 1 + docs/mcp.md | 71 +++++++ docs/overview.md | 2 + .../Entities/McpTokenEntity.cs | 14 ++ src/Flypaper.Storage/FlypaperDbContext.cs | 7 + .../FlypaperStorageExtensions.cs | 3 + .../20261115122552_AddMcpTokens.Designer.cs | 151 ++++++++++++++ .../Migrations/20261115122552_AddMcpTokens.cs | 44 ++++ .../FlypaperDbContextModelSnapshot.cs | 30 +++ src/Flypaper.Storage/Queries/CatchQueries.cs | 188 ++++++++++++++++++ src/Flypaper.Storage/Queries/CatchRecords.cs | 63 ++++++ src/Flypaper.Storage/Queries/QueryPeriod.cs | 36 ++++ .../Settings/McpTokenStore.cs | 49 +++++ .../Pages/Settings/McpSection.razor | 109 ++++++++++ .../Pages/Settings/McpTokenModel.cs | 6 + .../Pages/Settings/SettingsPage.razor | 2 + src/Flypaper.Web/Flypaper.Web.csproj | 4 + src/Flypaper.Web/Mcp/FlypaperTools.cs | 180 +++++++++++++++++ src/Flypaper.Web/Mcp/McpExtensions.cs | 59 ++++++ src/Flypaper.Web/Mcp/McpOptions.cs | 8 + src/Flypaper.Web/Mcp/McpResults.cs | 51 +++++ .../Mcp/McpTokenAuthenticationHandler.cs | 39 ++++ src/Flypaper.Web/Mcp/McpTokenService.cs | 39 ++++ src/Flypaper.Web/Program.cs | 4 + src/Flypaper.Web/wwwroot/app.css | 11 + .../Http/PortSeparationTests.cs | 3 + test/Flypaper.Tests/Mcp/FlypaperToolsTests.cs | 153 ++++++++++++++ test/Flypaper.Tests/Mcp/McpEndpointTests.cs | 113 +++++++++++ test/Flypaper.Tests/Mcp/McpTestData.cs | 77 +++++++ .../Mcp/McpTokenServiceTests.cs | 62 ++++++ test/Flypaper.Tests/Mcp/QueryPeriodTests.cs | 36 ++++ 34 files changed, 1625 insertions(+) create mode 100644 docs/mcp.md create mode 100644 src/Flypaper.Storage/Entities/McpTokenEntity.cs create mode 100644 src/Flypaper.Storage/Migrations/20261115122552_AddMcpTokens.Designer.cs create mode 100644 src/Flypaper.Storage/Migrations/20261115122552_AddMcpTokens.cs create mode 100644 src/Flypaper.Storage/Queries/CatchQueries.cs create mode 100644 src/Flypaper.Storage/Queries/CatchRecords.cs create mode 100644 src/Flypaper.Storage/Queries/QueryPeriod.cs create mode 100644 src/Flypaper.Storage/Settings/McpTokenStore.cs create mode 100644 src/Flypaper.Web/Components/Pages/Settings/McpSection.razor create mode 100644 src/Flypaper.Web/Components/Pages/Settings/McpTokenModel.cs create mode 100644 src/Flypaper.Web/Mcp/FlypaperTools.cs create mode 100644 src/Flypaper.Web/Mcp/McpExtensions.cs create mode 100644 src/Flypaper.Web/Mcp/McpOptions.cs create mode 100644 src/Flypaper.Web/Mcp/McpResults.cs create mode 100644 src/Flypaper.Web/Mcp/McpTokenAuthenticationHandler.cs create mode 100644 src/Flypaper.Web/Mcp/McpTokenService.cs create mode 100644 test/Flypaper.Tests/Mcp/FlypaperToolsTests.cs create mode 100644 test/Flypaper.Tests/Mcp/McpEndpointTests.cs create mode 100644 test/Flypaper.Tests/Mcp/McpTestData.cs create mode 100644 test/Flypaper.Tests/Mcp/McpTokenServiceTests.cs create mode 100644 test/Flypaper.Tests/Mcp/QueryPeriodTests.cs diff --git a/CHANGELOG.md b/CHANGELOG.md index f6a39ad..d7047ba 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,14 @@ All notable changes to Flypaper are documented in this file. The format follows ## [Unreleased] +### Added + +- MCP server at `/mcp` on the dashboard port (Streamable HTTP) with read-only tools + `get_stats`, `list_catches`, `top`, `longest_catches` and `lookup_ip`, returning structured + JSON. +- Bearer tokens for MCP, created, listed and revoked on the settings page and stored only as + SHA-256 hashes; optional fixed token via `Flypaper__Mcp__Token`. + ## [0.1.1] - 2026-11-15 ### Fixed diff --git a/Directory.Packages.props b/Directory.Packages.props index ea0f2ee..2c10719 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -11,6 +11,7 @@ + diff --git a/README.md b/README.md index 52e3c34..ac5adcf 100644 --- a/README.md +++ b/README.md @@ -23,6 +23,7 @@ flowchart LR within limits per IP, overall and per catch. - Each catch is logged and stored with its origin (DB-IP GeoIP); the dashboard on port `8081` shows maps and tables. +- AI assistants such as Claude can query the catches over MCP: [docs/mcp.md](docs/mcp.md). More: [how it works and all features](docs/overview.md). diff --git a/docs/configuration.md b/docs/configuration.md index ca22b99..b1bbb0e 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -16,6 +16,7 @@ All optional. Read at startup; list entries need an index (`__0`, `__1`, ...). | `Flypaper__Admin__Password` | Fixes the dashboard password and disables the first-visit setup and the password change | set on first visit | | `Flypaper__Http__TrustedProxies__0` | IP or CIDR of the reverse proxy allowed to set `X-Real-IP` / `X-Forwarded-For`; replaces the default | private networks | | `Flypaper__Http__KnownHosts__0` | Hosts that are caught only on trap paths (`*.example.com` allowed), see [reverse proxy](reverse-proxy.md#what-to-send-to-flypaper) | none | +| `Flypaper__Mcp__Token` | Fixed bearer token for the [MCP endpoint](mcp.md), in addition to tokens created on the settings page | none | | `Flypaper__Ports__Trap` / `Flypaper__Ports__Dashboard` | Container ports | `8080` / `8081` | | `ConnectionStrings__Flypaper` | SQLite database | `Data Source=/data/flypaper.db` | | `Flypaper__DataProtection__KeysPath` | Keys for login cookies and forms | `/data/keys` | diff --git a/docs/mcp.md b/docs/mcp.md new file mode 100644 index 0000000..9d53ab5 --- /dev/null +++ b/docs/mcp.md @@ -0,0 +1,71 @@ +# MCP access for AI assistants + +Flypaper includes a [Model Context Protocol](https://modelcontextprotocol.io) server, so AI +assistants such as Claude can query your catches: "Which countries hit the trap most this week?", +"What do we know about 203.0.113.9?". All tools only read; nothing can be changed or deleted +over MCP. + +- Endpoint: `http://:8081/mcp` (Streamable HTTP, dashboard port only; on the trap port + `8080` the path is just another trap) +- Authentication: `Authorization: Bearer `; without a valid token the answer is `401` + +**LAN only.** The MCP endpoint lives on the dashboard port and must stay as internal as the +dashboard: never forward port `8081` from your public proxy. + +## Create a token + +Dashboard → **Einstellungen** → **MCP-Zugriff**: enter a name (e.g. *Claude Code*) and create +the token. It is shown exactly once, so copy it right away; Flypaper stores only its SHA-256 +hash. The list shows each token's name, creation date and last use, and lets you revoke it. + +Alternatively, set a fixed token with the environment variable `Flypaper__Mcp__Token` (useful +for automated setups). It works in addition to the tokens created in the dashboard. + +## Connect Claude Code + +```bash +claude mcp add --transport http flypaper http://192.168.1.10:8081/mcp \ + --header "Authorization: Bearer fpm_your_token" +``` + +## Connect Claude Desktop + +Claude Desktop's custom connectors are reached from Anthropic's cloud and can't see your LAN. +Use the local [`mcp-remote`](https://www.npmjs.com/package/mcp-remote) bridge instead (needs +Node.js), in `claude_desktop_config.json`: + +```json +{ + "mcpServers": { + "flypaper": { + "command": "npx", + "args": [ + "mcp-remote", + "http://192.168.1.10:8081/mcp", + "--allow-http", + "--header", + "Authorization: Bearer ${FLYPAPER_TOKEN}" + ], + "env": { "FLYPAPER_TOKEN": "fpm_your_token" } + } + } +} +``` + +`--allow-http` is needed because the dashboard port speaks plain HTTP. + +## Tools + +All tools return structured JSON (with an output schema); times are ISO 8601 UTC, durations in +seconds. A *period* is a number with `m`, `h`, `d` or `w` (e.g. `1h`, `24h`, `7d`) or `all`. + +| Tool | Parameters | Returns | +|---|---|---| +| `get_stats` | `period` (default `24h`) | Catches, rejected connections, unique IPs, total and average hold time, traps active now, longest catch | +| `list_catches` | `since`, `until` (ISO 8601), `country` (ISO code), `provider` (`AS4134` or part of the name), `ip`, `target_contains`, `limit` (default 50, max 500) | Events, newest first, including rejected ones | +| `top` | `dimension` (`ips`, `countries`, `providers`, `targets`, `user_agents`), `period` (default `24h`), `limit` (default 10) | Most frequent values by number of catches, with total hold time | +| `longest_catches` | `period` (default `7d`), `limit` (default 10) | Catches that held a bot the longest | +| `lookup_ip` | `ip` | Origin, provider, totals, first and last seen, and its events (newest first, at most 500); local data only | + +Catches from private networks appear only if they are stored, i.e. if the setting *Fänge aus +privaten Netzen nicht speichern* is off. diff --git a/docs/overview.md b/docs/overview.md index 431d223..796836f 100644 --- a/docs/overview.md +++ b/docs/overview.md @@ -44,6 +44,8 @@ flowchart LR - **Retention**: old catches are deleted daily (90 days by default); catches from private networks are not stored by default; buttons to delete private or all catches - **One log line per catch**, so `docker logs` alone shows whether the trap works +- **MCP server** on the dashboard port, so AI assistants can query the catches read-only + ([docs/mcp.md](mcp.md)) - **Health endpoint** `/health` for container health checks (on the trap port it answers only to private addresses) - **No configuration needed to start**: one volume, two ports, the admin password is set on diff --git a/src/Flypaper.Storage/Entities/McpTokenEntity.cs b/src/Flypaper.Storage/Entities/McpTokenEntity.cs new file mode 100644 index 0000000..c2143f4 --- /dev/null +++ b/src/Flypaper.Storage/Entities/McpTokenEntity.cs @@ -0,0 +1,14 @@ +namespace Flypaper.Storage.Entities; + +public sealed class McpTokenEntity +{ + public int Id { get; set; } + + public required string Name { get; set; } + + public required string TokenHash { get; set; } + + public DateTime CreatedAt { get; set; } + + public DateTime? LastUsedAt { get; set; } +} diff --git a/src/Flypaper.Storage/FlypaperDbContext.cs b/src/Flypaper.Storage/FlypaperDbContext.cs index 629840e..7a1739b 100644 --- a/src/Flypaper.Storage/FlypaperDbContext.cs +++ b/src/Flypaper.Storage/FlypaperDbContext.cs @@ -12,6 +12,8 @@ public sealed class FlypaperDbContext(DbContextOptions option public DbSet Settings => Set(); + public DbSet McpTokens => Set(); + protected override void ConfigureConventions(ModelConfigurationBuilder configurationBuilder) => configurationBuilder.Properties().HaveConversion(); @@ -36,5 +38,10 @@ public sealed class FlypaperDbContext(DbContextOptions option var setting = modelBuilder.Entity(); setting.HasKey(e => e.Key); setting.Property(e => e.Key).HasMaxLength(128); + + var mcpToken = modelBuilder.Entity(); + mcpToken.Property(e => e.Name).HasMaxLength(100); + mcpToken.Property(e => e.TokenHash).HasMaxLength(64); + mcpToken.HasIndex(e => e.TokenHash).IsUnique(); } } diff --git a/src/Flypaper.Storage/FlypaperStorageExtensions.cs b/src/Flypaper.Storage/FlypaperStorageExtensions.cs index 498b88e..6b361a4 100644 --- a/src/Flypaper.Storage/FlypaperStorageExtensions.cs +++ b/src/Flypaper.Storage/FlypaperStorageExtensions.cs @@ -2,6 +2,7 @@ using Flypaper.Core.Abstractions; using Flypaper.Storage.Dashboard; using Flypaper.Storage.Events; using Flypaper.Storage.Maintenance; +using Flypaper.Storage.Queries; using Flypaper.Storage.Settings; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; @@ -21,6 +22,7 @@ public static class FlypaperStorageExtensions builder.Services.AddSingleton(source); builder.Services.AddSingleton(); builder.Services.AddSingleton(); + builder.Services.AddSingleton(); builder.Services.Configure(builder.Configuration.GetSection(RetentionOptions.SectionName)); builder.Services.AddFlypaperStorage(connectionString); @@ -35,6 +37,7 @@ public static class FlypaperStorageExtensions services.AddHostedService(); services.AddHostedService(); services.AddSingleton(); + services.AddSingleton(); services.AddSingleton(); services.AddHostedService(); return services; diff --git a/src/Flypaper.Storage/Migrations/20261115122552_AddMcpTokens.Designer.cs b/src/Flypaper.Storage/Migrations/20261115122552_AddMcpTokens.Designer.cs new file mode 100644 index 0000000..01dd734 --- /dev/null +++ b/src/Flypaper.Storage/Migrations/20261115122552_AddMcpTokens.Designer.cs @@ -0,0 +1,151 @@ +// +using System; +using Flypaper.Storage; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace Flypaper.Storage.Migrations +{ + [DbContext(typeof(FlypaperDbContext))] + [Migration("20261115122552_AddMcpTokens")] + partial class AddMcpTokens + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder.HasAnnotation("ProductVersion", "10.0.15"); + + modelBuilder.Entity("Flypaper.Storage.Entities.McpTokenEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("CreatedAt") + .HasColumnType("TEXT"); + + b.Property("LastUsedAt") + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("TEXT"); + + b.Property("TokenHash") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("TokenHash") + .IsUnique(); + + b.ToTable("McpTokens"); + }); + + modelBuilder.Entity("Flypaper.Storage.Entities.SettingEntity", b => + { + b.Property("Key") + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("Value") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.ToTable("Settings"); + }); + + modelBuilder.Entity("Flypaper.Storage.Entities.TrapEventEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Asn") + .HasColumnType("INTEGER"); + + b.Property("BytesSent") + .HasColumnType("INTEGER"); + + b.Property("City") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("ClientInfo") + .HasMaxLength(2048) + .HasColumnType("TEXT"); + + b.Property("Country") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("CountryCode") + .HasMaxLength(2) + .HasColumnType("TEXT"); + + b.Property("DurationMs") + .HasColumnType("INTEGER"); + + b.Property("EndedAt") + .HasColumnType("TEXT"); + + b.Property("Outcome") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("TEXT"); + + b.Property("Protocol") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("TEXT"); + + b.Property("Provider") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("RemoteIp") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("SessionId") + .HasColumnType("TEXT"); + + b.Property("StartedAt") + .HasColumnType("TEXT"); + + b.Property("Strategy") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("Target") + .HasMaxLength(2048) + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("Asn"); + + b.HasIndex("CountryCode"); + + b.HasIndex("RemoteIp"); + + b.HasIndex("StartedAt"); + + b.ToTable("TrapEvents"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/Flypaper.Storage/Migrations/20261115122552_AddMcpTokens.cs b/src/Flypaper.Storage/Migrations/20261115122552_AddMcpTokens.cs new file mode 100644 index 0000000..7345603 --- /dev/null +++ b/src/Flypaper.Storage/Migrations/20261115122552_AddMcpTokens.cs @@ -0,0 +1,44 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Flypaper.Storage.Migrations +{ + /// + public partial class AddMcpTokens : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "McpTokens", + columns: table => new + { + Id = table.Column(type: "INTEGER", nullable: false) + .Annotation("Sqlite:Autoincrement", true), + Name = table.Column(type: "TEXT", maxLength: 100, nullable: false), + TokenHash = table.Column(type: "TEXT", maxLength: 64, nullable: false), + CreatedAt = table.Column(type: "TEXT", nullable: false), + LastUsedAt = table.Column(type: "TEXT", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_McpTokens", x => x.Id); + }); + + migrationBuilder.CreateIndex( + name: "IX_McpTokens_TokenHash", + table: "McpTokens", + column: "TokenHash", + unique: true); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "McpTokens"); + } + } +} diff --git a/src/Flypaper.Storage/Migrations/FlypaperDbContextModelSnapshot.cs b/src/Flypaper.Storage/Migrations/FlypaperDbContextModelSnapshot.cs index 4184f36..e02f387 100644 --- a/src/Flypaper.Storage/Migrations/FlypaperDbContextModelSnapshot.cs +++ b/src/Flypaper.Storage/Migrations/FlypaperDbContextModelSnapshot.cs @@ -17,6 +17,36 @@ namespace Flypaper.Storage.Migrations #pragma warning disable 612, 618 modelBuilder.HasAnnotation("ProductVersion", "10.0.15"); + modelBuilder.Entity("Flypaper.Storage.Entities.McpTokenEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("CreatedAt") + .HasColumnType("TEXT"); + + b.Property("LastUsedAt") + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("TEXT"); + + b.Property("TokenHash") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("TokenHash") + .IsUnique(); + + b.ToTable("McpTokens"); + }); + modelBuilder.Entity("Flypaper.Storage.Entities.SettingEntity", b => { b.Property("Key") diff --git a/src/Flypaper.Storage/Queries/CatchQueries.cs b/src/Flypaper.Storage/Queries/CatchQueries.cs new file mode 100644 index 0000000..b4dfd8e --- /dev/null +++ b/src/Flypaper.Storage/Queries/CatchQueries.cs @@ -0,0 +1,188 @@ +using System.Globalization; +using Flypaper.Core.Models; +using Flypaper.Storage.Entities; +using Microsoft.EntityFrameworkCore; + +namespace Flypaper.Storage.Queries; + +public sealed class CatchQueries(IDbContextFactory dbContextFactory) +{ + public const int MaxLimit = 500; + + public async Task GetStatsAsync(DateTime? since, CancellationToken ct = default) + { + await using var db = await dbContextFactory.CreateDbContextAsync(ct); + var events = InPeriod(db, since); + var catches = events.Where(e => e.Outcome != TrapOutcome.Rejected); + + var count = await catches.CountAsync(ct); + var totalMs = count == 0 ? 0 : await catches.SumAsync(e => e.DurationMs, ct); + var longest = await catches.OrderByDescending(e => e.DurationMs).ThenByDescending(e => e.Id).FirstOrDefaultAsync(ct); + + return new CatchStats( + count, + await events.CountAsync(e => e.Outcome == TrapOutcome.Rejected, ct), + await events.Select(e => e.RemoteIp).Distinct().CountAsync(ct), + totalMs / 1000d, + count == 0 ? 0 : totalMs / 1000d / count, + longest is null ? null : ToRecord(longest)); + } + + public async Task> ListAsync(CatchFilter filter, CancellationToken ct = default) + { + await using var db = await dbContextFactory.CreateDbContextAsync(ct); + var events = InPeriod(db, filter.Since); + + if (filter.Until is { } until) + { + events = events.Where(e => e.StartedAt < until); + } + + if (!string.IsNullOrWhiteSpace(filter.Country)) + { + var country = filter.Country.Trim().ToUpperInvariant(); + events = events.Where(e => e.CountryCode == country); + } + + if (!string.IsNullOrWhiteSpace(filter.Provider)) + { + events = ByProvider(events, filter.Provider.Trim()); + } + + if (!string.IsNullOrWhiteSpace(filter.Ip)) + { + var ip = filter.Ip.Trim(); + events = events.Where(e => e.RemoteIp == ip); + } + + if (!string.IsNullOrWhiteSpace(filter.TargetContains)) + { + var text = filter.TargetContains.Trim().ToLowerInvariant(); + events = events.Where(e => e.Target != null && e.Target.ToLower().Contains(text)); + } + + var rows = await events.OrderByDescending(e => e.StartedAt).ThenByDescending(e => e.Id).Take(Clamp(filter.Limit)).ToListAsync(ct); + return rows.Select(ToRecord).ToList(); + } + + public async Task> LongestAsync(DateTime? since, int limit, CancellationToken ct = default) + { + await using var db = await dbContextFactory.CreateDbContextAsync(ct); + var rows = await InPeriod(db, since) + .Where(e => e.Outcome != TrapOutcome.Rejected) + .OrderByDescending(e => e.DurationMs) + .ThenByDescending(e => e.Id) + .Take(Clamp(limit)) + .ToListAsync(ct); + return rows.Select(ToRecord).ToList(); + } + + public async Task> TopAsync(TopDimension dimension, DateTime? since, int limit, CancellationToken ct = default) + { + await using var db = await dbContextFactory.CreateDbContextAsync(ct); + var catches = InPeriod(db, since).Where(e => e.Outcome != TrapOutcome.Rejected); + var take = Clamp(limit); + + IQueryable rows = dimension switch + { + TopDimension.Ips => catches.GroupBy(e => e.RemoteIp) + .Select(g => new TopRow { Key = g.Key, Label = g.Max(e => e.CountryCode), Count = g.Count(), DurationMs = g.Sum(e => e.DurationMs) }), + TopDimension.Countries => catches.Where(e => e.CountryCode != null).GroupBy(e => e.CountryCode!) + .Select(g => new TopRow { Key = g.Key, Label = g.Max(e => e.Country), Count = g.Count(), DurationMs = g.Sum(e => e.DurationMs) }), + TopDimension.Providers => catches.Where(e => e.Asn != null).GroupBy(e => e.Asn!.Value) + .Select(g => new TopRow { Key = "AS" + g.Key.ToString(), Label = g.Max(e => e.Provider), Count = g.Count(), DurationMs = g.Sum(e => e.DurationMs) }), + TopDimension.Targets => catches.Where(e => e.Target != null).GroupBy(e => e.Target!) + .Select(g => new TopRow { Key = g.Key, Count = g.Count(), DurationMs = g.Sum(e => e.DurationMs) }), + TopDimension.UserAgents => catches.Where(e => e.ClientInfo != null).GroupBy(e => e.ClientInfo!) + .Select(g => new TopRow { Key = g.Key, Count = g.Count(), DurationMs = g.Sum(e => e.DurationMs) }), + _ => throw new ArgumentOutOfRangeException(nameof(dimension)) + }; + + var top = await rows + .OrderByDescending(x => x.Count) + .ThenByDescending(x => x.DurationMs) + .Take(take) + .ToListAsync(ct); + + return top.Select(x => new TopItem(x.Key, x.Label, x.Count, x.DurationMs / 1000d)).ToList(); + } + + public async Task LookupIpAsync(string ip, CancellationToken ct = default) + { + await using var db = await dbContextFactory.CreateDbContextAsync(ct); + var events = db.TrapEvents.AsNoTracking().Where(e => e.RemoteIp == ip); + + var total = await events.CountAsync(ct); + if (total == 0) + { + return null; + } + + var catches = events.Where(e => e.Outcome != TrapOutcome.Rejected); + var origin = await events.Where(e => e.CountryCode != null || e.Asn != null).OrderByDescending(e => e.Id).FirstOrDefaultAsync(ct); + var recent = await events.OrderByDescending(e => e.StartedAt).ThenByDescending(e => e.Id).Take(MaxLimit).ToListAsync(ct); + + return new IpProfile( + ip, + origin?.CountryCode, + origin?.Country, + origin?.City, + origin?.Asn, + origin?.Provider, + await catches.CountAsync(ct), + await events.CountAsync(e => e.Outcome == TrapOutcome.Rejected, ct), + await catches.SumAsync(e => e.DurationMs, ct) / 1000d, + await events.SumAsync(e => e.BytesSent, ct), + await events.MinAsync(e => e.StartedAt, ct), + await events.MaxAsync(e => e.EndedAt, ct), + recent.Select(ToRecord).ToList(), + Math.Max(0, total - recent.Count)); + } + + private static IQueryable InPeriod(FlypaperDbContext db, DateTime? since) + { + var events = db.TrapEvents.AsNoTracking(); + return since is { } start ? events.Where(e => e.StartedAt >= start) : events; + } + + private static IQueryable ByProvider(IQueryable events, string provider) + { + var number = provider.StartsWith("AS", StringComparison.OrdinalIgnoreCase) ? provider[2..] : provider; + if (long.TryParse(number, NumberStyles.None, CultureInfo.InvariantCulture, out var asn)) + { + return events.Where(e => e.Asn == asn); + } + + var text = provider.ToLowerInvariant(); + return events.Where(e => e.Provider != null && e.Provider.ToLower().Contains(text)); + } + + private static int Clamp(int limit) => Math.Clamp(limit, 1, MaxLimit); + + private static CatchRecord ToRecord(TrapEventEntity e) => new( + e.Id, + e.StartedAt, + e.EndedAt, + e.DurationMs / 1000d, + e.BytesSent, + e.Outcome, + e.RemoteIp, + e.CountryCode, + e.Country, + e.City, + e.Asn, + e.Provider, + e.Target, + e.ClientInfo); + + private sealed class TopRow + { + public required string Key { get; init; } + + public string? Label { get; init; } + + public int Count { get; init; } + + public long DurationMs { get; init; } + } +} diff --git a/src/Flypaper.Storage/Queries/CatchRecords.cs b/src/Flypaper.Storage/Queries/CatchRecords.cs new file mode 100644 index 0000000..169c647 --- /dev/null +++ b/src/Flypaper.Storage/Queries/CatchRecords.cs @@ -0,0 +1,63 @@ +using Flypaper.Core.Models; + +namespace Flypaper.Storage.Queries; + +public sealed record CatchRecord( + long Id, + DateTime StartedAt, + DateTime EndedAt, + double DurationSeconds, + long BytesSent, + TrapOutcome Outcome, + string Ip, + string? CountryCode, + string? Country, + string? City, + long? Asn, + string? Provider, + string? Target, + string? UserAgent); + +public sealed record CatchFilter( + DateTime? Since = null, + DateTime? Until = null, + string? Country = null, + string? Provider = null, + string? Ip = null, + string? TargetContains = null, + int Limit = 50); + +public sealed record CatchStats( + int Catches, + int Rejected, + int UniqueIps, + double TotalHoldSeconds, + double AverageHoldSeconds, + CatchRecord? Longest); + +public enum TopDimension +{ + Ips, + Countries, + Providers, + Targets, + UserAgents +} + +public sealed record TopItem(string Key, string? Label, int Catches, double TotalHoldSeconds); + +public sealed record IpProfile( + string Ip, + string? CountryCode, + string? Country, + string? City, + long? Asn, + string? Provider, + int Catches, + int Rejected, + double TotalHoldSeconds, + long TotalBytesSent, + DateTime? FirstSeen, + DateTime? LastSeen, + IReadOnlyList Events, + int EventsOmitted); diff --git a/src/Flypaper.Storage/Queries/QueryPeriod.cs b/src/Flypaper.Storage/Queries/QueryPeriod.cs new file mode 100644 index 0000000..815b90e --- /dev/null +++ b/src/Flypaper.Storage/Queries/QueryPeriod.cs @@ -0,0 +1,36 @@ +using System.Globalization; +using System.Text.RegularExpressions; + +namespace Flypaper.Storage.Queries; + +public static partial class QueryPeriod +{ + [GeneratedRegex(@"^(\d{1,5})([mhdw])$", RegexOptions.IgnoreCase)] + private static partial Regex Pattern(); + + public static bool TryParse(string? value, out TimeSpan? span) + { + span = null; + var text = value?.Trim(); + if (string.IsNullOrEmpty(text) || text.Equals("all", StringComparison.OrdinalIgnoreCase)) + { + return true; + } + + var match = Pattern().Match(text); + if (!match.Success) + { + return false; + } + + var amount = int.Parse(match.Groups[1].Value, CultureInfo.InvariantCulture); + span = char.ToLowerInvariant(match.Groups[2].Value[0]) switch + { + 'm' => TimeSpan.FromMinutes(amount), + 'h' => TimeSpan.FromHours(amount), + 'd' => TimeSpan.FromDays(amount), + _ => TimeSpan.FromDays(amount * 7) + }; + return amount > 0; + } +} diff --git a/src/Flypaper.Storage/Settings/McpTokenStore.cs b/src/Flypaper.Storage/Settings/McpTokenStore.cs new file mode 100644 index 0000000..83c8894 --- /dev/null +++ b/src/Flypaper.Storage/Settings/McpTokenStore.cs @@ -0,0 +1,49 @@ +using Flypaper.Storage.Entities; +using Microsoft.EntityFrameworkCore; + +namespace Flypaper.Storage.Settings; + +public sealed class McpTokenStore(IDbContextFactory dbContextFactory, TimeProvider timeProvider) +{ + private static readonly TimeSpan LastUsedResolution = TimeSpan.FromMinutes(1); + + public async Task> ListAsync(CancellationToken ct = default) + { + await using var db = await dbContextFactory.CreateDbContextAsync(ct); + return await db.McpTokens.AsNoTracking().OrderBy(t => t.Id).ToListAsync(ct); + } + + public async Task CreateAsync(string name, string tokenHash, CancellationToken ct = default) + { + await using var db = await dbContextFactory.CreateDbContextAsync(ct); + var token = new McpTokenEntity { Name = name, TokenHash = tokenHash, CreatedAt = timeProvider.GetUtcNow().UtcDateTime }; + db.McpTokens.Add(token); + await db.SaveChangesAsync(ct); + return token; + } + + public async Task RevokeAsync(int id, CancellationToken ct = default) + { + await using var db = await dbContextFactory.CreateDbContextAsync(ct); + return await db.McpTokens.Where(t => t.Id == id).ExecuteDeleteAsync(ct) > 0; + } + + public async Task UseAsync(string tokenHash, CancellationToken ct = default) + { + await using var db = await dbContextFactory.CreateDbContextAsync(ct); + var token = await db.McpTokens.SingleOrDefaultAsync(t => t.TokenHash == tokenHash, ct); + if (token is null) + { + return null; + } + + var now = timeProvider.GetUtcNow().UtcDateTime; + if (token.LastUsedAt is null || now - token.LastUsedAt >= LastUsedResolution) + { + token.LastUsedAt = now; + await db.SaveChangesAsync(ct); + } + + return token; + } +} diff --git a/src/Flypaper.Web/Components/Pages/Settings/McpSection.razor b/src/Flypaper.Web/Components/Pages/Settings/McpSection.razor new file mode 100644 index 0000000..6caa071 --- /dev/null +++ b/src/Flypaper.Web/Components/Pages/Settings/McpSection.razor @@ -0,0 +1,109 @@ +@using Flypaper.Storage.Entities +@using Flypaper.Storage.Settings +@using Flypaper.Web.Mcp +@inject McpTokenService Tokens +@inject McpTokenStore Store +@inject NavigationManager Navigation + +
+

MCP-Zugriff

+

+ KI-Assistenten wie Claude lesen die Fänge über @Endpoint (nur lesend, nur im LAN). + Jeder Zugriff braucht einen Token im Header Authorization: Bearer …. +

+ + @if (Revoked == "revoked") + { + + } + + @if (_newToken is not null) + { + + } + + @if (Tokens.UsesEnvironmentToken) + { +

Zusätzlich gilt ein fester Token aus der Umgebungsvariable Flypaper__Mcp__Token.

+ } + + @if (_tokens.Count > 0) + { + + + + + + + + + + + @foreach (var token in _tokens) + { + + + + + + + } + +
NameErstelltZuletzt genutzt
@token.Name@token.CreatedAt.ToLocalTime().ToString("dd.MM.yyyy HH:mm")@(token.LastUsedAt?.ToLocalTime().ToString("dd.MM.yyyy HH:mm") ?? "nie") +
+ + + +
+ } + else + { +

Noch keine Tokens.

+ } + + + + + +
+ +
+
+
+ +@code { + private IReadOnlyList _tokens = []; + private readonly Dictionary _errors = []; + private string? _newToken; + private string? _newTokenName; + + [SupplyParameterFromForm(FormName = "mcp-create")] private McpTokenModel? Model { get; set; } + + [SupplyParameterFromQuery(Name = "mcp")] private string? Revoked { get; set; } + + private string Endpoint => Navigation.BaseUri.TrimEnd('/') + McpExtensions.Path; + + protected override async Task OnInitializedAsync() + { + Model ??= new McpTokenModel(); + _tokens = await Store.ListAsync(); + } + + private async Task CreateAsync() + { + var name = Model!.Name?.Trim(); + if (string.IsNullOrEmpty(name) || name.Length > 100) + { + _errors[nameof(McpTokenModel.Name)] = "Bitte einen Namen mit höchstens 100 Zeichen angeben."; + return; + } + + _newToken = await Tokens.CreateAsync(name); + _newTokenName = name; + Model.Name = null; + _tokens = await Store.ListAsync(); + } +} diff --git a/src/Flypaper.Web/Components/Pages/Settings/McpTokenModel.cs b/src/Flypaper.Web/Components/Pages/Settings/McpTokenModel.cs new file mode 100644 index 0000000..5a57745 --- /dev/null +++ b/src/Flypaper.Web/Components/Pages/Settings/McpTokenModel.cs @@ -0,0 +1,6 @@ +namespace Flypaper.Web.Components.Pages.Settings; + +public sealed class McpTokenModel +{ + public string? Name { get; set; } +} diff --git a/src/Flypaper.Web/Components/Pages/Settings/SettingsPage.razor b/src/Flypaper.Web/Components/Pages/Settings/SettingsPage.razor index fd5cefe..0cc60fe 100644 --- a/src/Flypaper.Web/Components/Pages/Settings/SettingsPage.razor +++ b/src/Flypaper.Web/Components/Pages/Settings/SettingsPage.razor @@ -92,6 +92,8 @@ else if (Saved == "reset") + +

Nur per Umgebungsvariable

Gelten ab Containerstart und lassen sich hier nicht ändern.

diff --git a/src/Flypaper.Web/Flypaper.Web.csproj b/src/Flypaper.Web/Flypaper.Web.csproj index 80c0e5c..ec2dd96 100644 --- a/src/Flypaper.Web/Flypaper.Web.csproj +++ b/src/Flypaper.Web/Flypaper.Web.csproj @@ -9,6 +9,10 @@ + + + + diff --git a/src/Flypaper.Web/Mcp/FlypaperTools.cs b/src/Flypaper.Web/Mcp/FlypaperTools.cs new file mode 100644 index 0000000..cf32661 --- /dev/null +++ b/src/Flypaper.Web/Mcp/FlypaperTools.cs @@ -0,0 +1,180 @@ +using System.ComponentModel; +using System.Globalization; +using System.Net; +using Flypaper.Core.Abstractions; +using Flypaper.Storage.Queries; +using Flypaper.Web.Components.Shared; +using ModelContextProtocol; +using ModelContextProtocol.Server; + +namespace Flypaper.Web.Mcp; + +[McpServerToolType] +public sealed class FlypaperTools(CatchQueries queries, IConnectionGovernor governor, TimeProvider timeProvider) +{ + private const string PeriodDescription = "Time window ending now: a number with m (minutes), h (hours), d (days) or w (weeks), e.g. 1h, 24h, 7d; or all."; + + [McpServerTool(Name = "get_stats", Title = "Trap statistics", ReadOnly = true, Destructive = false, Idempotent = true, OpenWorld = false, UseStructuredContent = true)] + [Description("Summary of the tarpit for a time window: number of catches and rejected connections, unique IPs, total and average hold time, traps active right now and the longest catch.")] + public async Task GetStats( + [Description(PeriodDescription)] string period = "24h", + CancellationToken ct = default) + { + var since = Since(period); + var stats = await queries.GetStatsAsync(since, ct); + return new StatsResult( + Normalize(period), + since, + stats.Catches, + stats.Rejected, + stats.UniqueIps, + Round(stats.TotalHoldSeconds), + Round(stats.AverageHoldSeconds), + governor.ActiveConnections, + stats.Longest is null ? null : ToItem(stats.Longest)); + } + + [McpServerTool(Name = "list_catches", Title = "List catches", ReadOnly = true, Destructive = false, Idempotent = true, OpenWorld = false, UseStructuredContent = true)] + [Description("Trap events, newest first, optionally filtered. Includes rejected connections (outcome Rejected).")] + public async Task ListCatches( + [Description("Only events that started at or after this ISO 8601 time, e.g. 2026-11-15T08:00:00Z.")] string? since = null, + [Description("Only events that started before this ISO 8601 time.")] string? until = null, + [Description("ISO 3166-1 alpha-2 country code, e.g. CN.")] string? country = null, + [Description("Network provider: an AS number such as AS4134, or part of the provider name.")] string? provider = null, + [Description("Exact client IP address.")] string? ip = null, + [Description("Case-insensitive text the request (method, host and path) must contain, e.g. .env.")] string? target_contains = null, + [Description("Maximum number of events, 1 to 500.")] int limit = 50, + CancellationToken ct = default) + { + var filter = new CatchFilter( + ParseTime(since, nameof(since)), + ParseTime(until, nameof(until)), + country, + provider, + ip is null ? null : ParseIp(ip), + target_contains, + limit); + var catches = (await queries.ListAsync(filter, ct)).Select(ToItem).ToList(); + return new CatchListResult(catches.Count, catches); + } + + [McpServerTool(Name = "top", Title = "Top values", ReadOnly = true, Destructive = false, Idempotent = true, OpenWorld = false, UseStructuredContent = true)] + [Description("Most frequent values among the catches of a time window, by number of catches. Rejected connections are not counted.")] + public async Task Top( + [Description("What to rank: ips, countries, providers, targets or user_agents.")] string dimension, + [Description(PeriodDescription)] string period = "24h", + [Description("Number of entries, 1 to 500.")] int limit = 10, + CancellationToken ct = default) + { + var parsed = dimension.Trim().ToLowerInvariant() switch + { + "ips" => TopDimension.Ips, + "countries" => TopDimension.Countries, + "providers" => TopDimension.Providers, + "targets" => TopDimension.Targets, + "user_agents" => TopDimension.UserAgents, + _ => throw new McpException("dimension must be one of ips, countries, providers, targets, user_agents.") + }; + + var items = await queries.TopAsync(parsed, Since(period), limit, ct); + return new TopResult( + dimension.Trim().ToLowerInvariant(), + Normalize(period), + items.Select(i => new TopResultItem( + i.Key, + parsed == TopDimension.Countries ? CountryNames.Display(i.Key, i.Label) : i.Label, + i.Catches, + Round(i.TotalHoldSeconds))).ToList()); + } + + [McpServerTool(Name = "longest_catches", Title = "Longest catches", ReadOnly = true, Destructive = false, Idempotent = true, OpenWorld = false, UseStructuredContent = true)] + [Description("The catches that held a bot the longest within a time window, longest first.")] + public async Task LongestCatches( + [Description(PeriodDescription)] string period = "7d", + [Description("Number of catches, 1 to 500.")] int limit = 10, + CancellationToken ct = default) + { + var catches = (await queries.LongestAsync(Since(period), limit, ct)).Select(ToItem).ToList(); + return new CatchListResult(catches.Count, catches); + } + + [McpServerTool(Name = "lookup_ip", Title = "Look up an IP", ReadOnly = true, Destructive = false, Idempotent = true, OpenWorld = false, UseStructuredContent = true)] + [Description("Everything Flypaper has stored about one IP address: origin, network provider, totals, first and last seen, and its events (newest first, at most 500). Uses only local data.")] + public async Task LookupIp( + [Description("IPv4 or IPv6 address.")] string ip, + CancellationToken ct = default) + { + var address = ParseIp(ip); + var profile = await queries.LookupIpAsync(address, ct); + if (profile is null) + { + return new IpLookupResult(address, false, null, null, null, null, null, 0, 0, 0, 0, null, null, [], 0); + } + + return new IpLookupResult( + profile.Ip, + true, + profile.CountryCode, + CountryNames.Display(profile.CountryCode, profile.Country), + profile.City, + Asn(profile.Asn), + profile.Provider, + profile.Catches, + profile.Rejected, + Round(profile.TotalHoldSeconds), + profile.TotalBytesSent, + profile.FirstSeen, + profile.LastSeen, + profile.Events.Select(ToItem).ToList(), + profile.EventsOmitted); + } + + private DateTime? Since(string? period) + { + if (!QueryPeriod.TryParse(period, out var span)) + { + throw new McpException($"Invalid period '{period}'. {PeriodDescription}"); + } + + return span is { } window ? timeProvider.GetUtcNow().UtcDateTime - window : null; + } + + private static string Normalize(string? period) => string.IsNullOrWhiteSpace(period) ? "all" : period.Trim().ToLowerInvariant(); + + private static DateTime? ParseTime(string? value, string name) + { + if (string.IsNullOrWhiteSpace(value)) + { + return null; + } + + return DateTimeOffset.TryParse(value, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal, out var time) + ? time.UtcDateTime + : throw new McpException($"{name} must be an ISO 8601 time, e.g. 2026-11-15T08:00:00Z."); + } + + private static string ParseIp(string value) => + IPAddress.TryParse(value.Trim(), out var address) + ? (address.IsIPv4MappedToIPv6 ? address.MapToIPv4() : address).ToString() + : throw new McpException($"'{value}' is not an IP address."); + + private static string? Asn(long? asn) => asn is null ? null : $"AS{asn.Value.ToString(CultureInfo.InvariantCulture)}"; + + private static double Round(double seconds) => Math.Round(seconds, 3); + + private static CatchItem ToItem(CatchRecord record) => new( + record.Id, + record.StartedAt, + record.EndedAt, + Round(record.DurationSeconds), + record.BytesSent, + record.Outcome.ToString(), + record.Ip, + record.CountryCode, + CountryNames.Display(record.CountryCode, record.Country), + record.City, + Asn(record.Asn), + record.Provider, + record.Target, + record.UserAgent); +} diff --git a/src/Flypaper.Web/Mcp/McpExtensions.cs b/src/Flypaper.Web/Mcp/McpExtensions.cs new file mode 100644 index 0000000..c3a30dd --- /dev/null +++ b/src/Flypaper.Web/Mcp/McpExtensions.cs @@ -0,0 +1,59 @@ +using Flypaper.Storage.Settings; +using Microsoft.AspNetCore.Antiforgery; +using Microsoft.AspNetCore.Authentication; +using ModelContextProtocol.Protocol; + +namespace Flypaper.Web.Mcp; + +public static class McpExtensions +{ + public const string Path = "/mcp"; + private const string PolicyName = "Mcp"; + + private const string Instructions = + "Flypaper is an HTTP tarpit. Scanning bots that probe a server (e.g. for /.env or /wp-login.php) are " + + "answered with an endless page a few bytes at a time and held as long as possible. Every such catch is " + + "stored with its time, client IP, country, network provider (ASN), requested URL, user agent, duration " + + "and bytes sent. These tools only read that data; times are ISO 8601 UTC, durations in seconds."; + + public static IServiceCollection AddFlypaperMcp(this IServiceCollection services, IConfiguration configuration) + { + services.Configure(configuration.GetSection(McpOptions.SectionName)); + services.AddSingleton(); + + services.AddAuthentication() + .AddScheme(McpTokenAuthenticationHandler.SchemeName, null); + services.AddAuthorizationBuilder() + .AddPolicy(PolicyName, policy => policy + .AddAuthenticationSchemes(McpTokenAuthenticationHandler.SchemeName) + .RequireAuthenticatedUser()); + + services.AddMcpServer(options => + { + options.ServerInfo = new Implementation { Name = "flypaper", Version = AppVersion.Current }; + options.ServerInstructions = Instructions; + }) + .WithHttpTransport(options => options.Stateless = true) + .WithTools(); + + return services; + } + + public static IEndpointRouteBuilder MapFlypaperMcp(this IEndpointRouteBuilder app) + { + app.MapMcp(Path).RequireAuthorization(PolicyName); + + app.MapPost("/mcp-tokens/{id:int}/revoke", async (int id, HttpContext context, IAntiforgery antiforgery, McpTokenStore store) => + { + if (!await antiforgery.IsRequestValidAsync(context)) + { + return Results.BadRequest(); + } + + await store.RevokeAsync(id, context.RequestAborted); + return Results.LocalRedirect("/settings?mcp=revoked"); + }); + + return app; + } +} diff --git a/src/Flypaper.Web/Mcp/McpOptions.cs b/src/Flypaper.Web/Mcp/McpOptions.cs new file mode 100644 index 0000000..57da59d --- /dev/null +++ b/src/Flypaper.Web/Mcp/McpOptions.cs @@ -0,0 +1,8 @@ +namespace Flypaper.Web.Mcp; + +public sealed class McpOptions +{ + public const string SectionName = "Flypaper:Mcp"; + + public string? Token { get; set; } +} diff --git a/src/Flypaper.Web/Mcp/McpResults.cs b/src/Flypaper.Web/Mcp/McpResults.cs new file mode 100644 index 0000000..cc7a154 --- /dev/null +++ b/src/Flypaper.Web/Mcp/McpResults.cs @@ -0,0 +1,51 @@ +namespace Flypaper.Web.Mcp; + +public sealed record CatchItem( + long Id, + DateTime StartedAt, + DateTime EndedAt, + double DurationSeconds, + long BytesSent, + string Outcome, + string Ip, + string? CountryCode, + string? Country, + string? City, + string? Asn, + string? Provider, + string? Target, + string? UserAgent); + +public sealed record StatsResult( + string Period, + DateTime? Since, + int Catches, + int Rejected, + int UniqueIps, + double TotalHoldSeconds, + double AverageHoldSeconds, + int ActiveTraps, + CatchItem? LongestCatch); + +public sealed record CatchListResult(int Count, IReadOnlyList Catches); + +public sealed record TopResultItem(string Key, string? Label, int Catches, double TotalHoldSeconds); + +public sealed record TopResult(string Dimension, string Period, IReadOnlyList Items); + +public sealed record IpLookupResult( + string Ip, + bool Known, + string? CountryCode, + string? Country, + string? City, + string? Asn, + string? Provider, + int Catches, + int Rejected, + double TotalHoldSeconds, + long TotalBytesSent, + DateTime? FirstSeen, + DateTime? LastSeen, + IReadOnlyList Events, + int EventsOmitted); diff --git a/src/Flypaper.Web/Mcp/McpTokenAuthenticationHandler.cs b/src/Flypaper.Web/Mcp/McpTokenAuthenticationHandler.cs new file mode 100644 index 0000000..dd13555 --- /dev/null +++ b/src/Flypaper.Web/Mcp/McpTokenAuthenticationHandler.cs @@ -0,0 +1,39 @@ +using System.Security.Claims; +using System.Text.Encodings.Web; +using Microsoft.AspNetCore.Authentication; +using Microsoft.Extensions.Options; + +namespace Flypaper.Web.Mcp; + +public sealed class McpTokenAuthenticationHandler( + IOptionsMonitor options, + ILoggerFactory logger, + UrlEncoder encoder, + McpTokenService tokens) : AuthenticationHandler(options, logger, encoder) +{ + public const string SchemeName = "McpToken"; + + protected override async Task HandleAuthenticateAsync() + { + var header = Request.Headers.Authorization.ToString(); + if (!header.StartsWith("Bearer ", StringComparison.OrdinalIgnoreCase)) + { + return AuthenticateResult.NoResult(); + } + + if (!await tokens.ValidateAsync(header["Bearer ".Length..].Trim(), Context.RequestAborted)) + { + return AuthenticateResult.Fail("Invalid MCP token."); + } + + var identity = new ClaimsIdentity([new Claim(ClaimTypes.Name, "mcp")], SchemeName); + return AuthenticateResult.Success(new AuthenticationTicket(new ClaimsPrincipal(identity), SchemeName)); + } + + protected override async Task HandleChallengeAsync(AuthenticationProperties properties) + { + Response.StatusCode = StatusCodes.Status401Unauthorized; + Response.Headers.WWWAuthenticate = "Bearer"; + await Response.WriteAsJsonAsync(new { error = "invalid_token" }); + } +} diff --git a/src/Flypaper.Web/Mcp/McpTokenService.cs b/src/Flypaper.Web/Mcp/McpTokenService.cs new file mode 100644 index 0000000..8102088 --- /dev/null +++ b/src/Flypaper.Web/Mcp/McpTokenService.cs @@ -0,0 +1,39 @@ +using System.Security.Cryptography; +using System.Text; +using Flypaper.Storage.Settings; +using Microsoft.AspNetCore.WebUtilities; +using Microsoft.Extensions.Options; + +namespace Flypaper.Web.Mcp; + +public sealed class McpTokenService(McpTokenStore store, IOptions options) +{ + private const string Prefix = "fpm_"; + + public bool UsesEnvironmentToken => !string.IsNullOrEmpty(options.Value.Token); + + public async Task CreateAsync(string name, CancellationToken ct = default) + { + var token = Prefix + WebEncoders.Base64UrlEncode(RandomNumberGenerator.GetBytes(32)); + await store.CreateAsync(name, Hash(token), ct); + return token; + } + + public async Task ValidateAsync(string? token, CancellationToken ct = default) + { + if (string.IsNullOrEmpty(token)) + { + return false; + } + + if (UsesEnvironmentToken + && CryptographicOperations.FixedTimeEquals(SHA256.HashData(Encoding.UTF8.GetBytes(token)), SHA256.HashData(Encoding.UTF8.GetBytes(options.Value.Token!)))) + { + return true; + } + + return await store.UseAsync(Hash(token), ct) is not null; + } + + public static string Hash(string token) => Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(token))); +} diff --git a/src/Flypaper.Web/Program.cs b/src/Flypaper.Web/Program.cs index 6c30c7b..4c2c71a 100644 --- a/src/Flypaper.Web/Program.cs +++ b/src/Flypaper.Web/Program.cs @@ -6,6 +6,7 @@ using Flypaper.Web; using Flypaper.Web.Auth; using Flypaper.Web.Components; using Flypaper.Web.Health; +using Flypaper.Web.Mcp; using Microsoft.AspNetCore.Authentication.Cookies; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.DataProtection; @@ -32,6 +33,8 @@ if (builder.Configuration["Flypaper:DataProtection:KeysPath"] is { Length: > 0 } dataProtection.PersistKeysToFileSystem(new DirectoryInfo(keysPath)); } +builder.Services.AddFlypaperMcp(builder.Configuration); + builder.Services.Configure(builder.Configuration.GetSection(AdminOptions.SectionName)); builder.Services.AddSingleton(); builder.Services @@ -69,6 +72,7 @@ app.UseAntiforgery(); app.MapStaticAssets().AllowAnonymous(); app.MapAuthEndpoints(); app.MapHealthEndpoint(); +app.MapFlypaperMcp(); app.MapRazorComponents(); await app.RunAsync(); diff --git a/src/Flypaper.Web/wwwroot/app.css b/src/Flypaper.Web/wwwroot/app.css index b99c638..5172759 100644 --- a/src/Flypaper.Web/wwwroot/app.css +++ b/src/Flypaper.Web/wwwroot/app.css @@ -625,3 +625,14 @@ button.danger { grid-template-columns: minmax(0, 1fr); } } + +.token { + display: block; + margin-top: 8px; + padding: 8px 10px; + border-radius: 6px; + background: var(--bg); + color: var(--text); + overflow-wrap: anywhere; + user-select: all; +} diff --git a/test/Flypaper.Tests/Http/PortSeparationTests.cs b/test/Flypaper.Tests/Http/PortSeparationTests.cs index 1bdcc05..fcbfade 100644 --- a/test/Flypaper.Tests/Http/PortSeparationTests.cs +++ b/test/Flypaper.Tests/Http/PortSeparationTests.cs @@ -32,6 +32,8 @@ public sealed class PortSeparationTests [InlineData("unknown.example", "/")] [InlineData("203.0.113.7", "/settings")] [InlineData("example.com", "/.env")] + [InlineData("unknown.example", "/mcp")] + [InlineData("203.0.113.7", "/mcp")] public async Task Trap_port_traps_unknown_hosts_and_trap_paths(string host, string path) { var (reachedApp, status) = await SendAsync(TrapPort, host, path); @@ -44,6 +46,7 @@ public sealed class PortSeparationTests [InlineData("/")] [InlineData("/settings")] [InlineData("/login")] + [InlineData("/mcp")] public async Task Trap_port_answers_other_paths_of_known_hosts_with_plain_404(string path) { var sink = Substitute.For(); diff --git a/test/Flypaper.Tests/Mcp/FlypaperToolsTests.cs b/test/Flypaper.Tests/Mcp/FlypaperToolsTests.cs new file mode 100644 index 0000000..8019961 --- /dev/null +++ b/test/Flypaper.Tests/Mcp/FlypaperToolsTests.cs @@ -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(); + 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(() => _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(() => _tools.ListCatches(since: "last tuesday")); + await Should.ThrowAsync(() => _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(() => _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(() => _tools.LookupIp("999.1.1.1")); + } + + public void Dispose() => _data.Dispose(); +} diff --git a/test/Flypaper.Tests/Mcp/McpEndpointTests.cs b/test/Flypaper.Tests/Mcp/McpEndpointTests.cs new file mode 100644 index 0000000..57c6888 --- /dev/null +++ b/test/Flypaper.Tests/Mcp/McpEndpointTests.cs @@ -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 _factory; + + public McpEndpointTests() + { + _factory = new WebApplicationFactory().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().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().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 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); + } + } +} diff --git a/test/Flypaper.Tests/Mcp/McpTestData.cs b/test/Flypaper.Tests/Mcp/McpTestData.cs new file mode 100644 index 0000000..6e1368b --- /dev/null +++ b/test/Flypaper.Tests/Mcp/McpTestData.cs @@ -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 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 + { + public FlypaperDbContext CreateDbContext() => + new(new DbContextOptionsBuilder().UseSqlite(connectionString).Options); + } +} diff --git a/test/Flypaper.Tests/Mcp/McpTokenServiceTests.cs b/test/Flypaper.Tests/Mcp/McpTokenServiceTests.cs new file mode 100644 index 0000000..cc2fca1 --- /dev/null +++ b/test/Flypaper.Tests/Mcp/McpTokenServiceTests.cs @@ -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(); +} diff --git a/test/Flypaper.Tests/Mcp/QueryPeriodTests.cs b/test/Flypaper.Tests/Mcp/QueryPeriodTests.cs new file mode 100644 index 0000000..bbf445a --- /dev/null +++ b/test/Flypaper.Tests/Mcp/QueryPeriodTests.cs @@ -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(); +}