Compare commits
6
Commits
v0.6.0
..
7c11bf211e
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7c11bf211e | ||
|
|
35aba56255 | ||
|
|
c5167262b9 | ||
|
|
4b946453fb | ||
|
|
2437880013 | ||
|
|
4086fa3da3 |
No files matched your search
+46
-1
@@ -6,6 +6,49 @@ All notable changes to Flypaper are documented in this file. The format follows
|
|||||||
|
|
||||||
## [Unreleased]
|
## [Unreleased]
|
||||||
|
|
||||||
|
## [0.8.0] - 2026-11-22
|
||||||
|
|
||||||
|
### Added
|
||||||
|
|
||||||
|
- Dashboard: the overview lists the bots held in the trap right now („Gerade in der Falle“) with IP (links to its
|
||||||
|
catches), origin, target, strategy, user agent, time held and bytes sent. The list is kept in memory only and
|
||||||
|
refreshes with the page (every 30 s).
|
||||||
|
- MCP: read-only tool `list_active` returns the same list (with provider, city and ASN); empty after a restart.
|
||||||
|
|
||||||
|
## [0.7.0] - 2026-11-21
|
||||||
|
|
||||||
|
### Added
|
||||||
|
|
||||||
|
- Lure for first visits: a GET on `/` or `/favicon.ico` from an IP without any stored catch is answered at once
|
||||||
|
with a small WordPress-looking page (`lure-page`, with `X-Powered-By: PHP/8.1.27`, a `wp-json` link header and
|
||||||
|
links to `/wp-login.php`, `/wp-admin/`, `/wp-content/uploads/backup/`, `/wp-config.php.bak`) or a favicon
|
||||||
|
(`lure-icon`) and is not held. Every later request of that IP is trapped as before. Switch:
|
||||||
|
`Flypaper__Drip__Lure` (default `true`), no dashboard setting.
|
||||||
|
- Explanations for catches: rules in the database (kind `Target`, `ClientInfo` or `Outcome`, regular expression,
|
||||||
|
German plain text, priority, on/off, note, creator) explain what a bot wanted, with which tool and how it ended.
|
||||||
|
Rules are matched when a catch is displayed, so new rules also apply to old catches; per kind the rule with
|
||||||
|
the highest priority wins. Patterns run with `NonBacktracking` and a timeout, are validated and length-limited
|
||||||
|
when saved, and compiled rules are cached until a rule changes. No rules are shipped.
|
||||||
|
- Dashboard: expanded rows of the catch list show „Was ist passiert?“ (or a muted „Unbekanntes Ziel“), the catch
|
||||||
|
filter has „Erklärung: Ohne Erklärung“, and the new page „Erklärungen“ lists the rules with pattern, text,
|
||||||
|
number of matches, on/off switch and delete.
|
||||||
|
- MCP: read-only tools `list_explanation_rules`, `list_unexplained` and `test_explanation_rule`; tools
|
||||||
|
`create_explanation_rule`, `update_explanation_rule`, `set_explanation_rule_enabled` and
|
||||||
|
`delete_explanation_rule` for tokens with write permission.
|
||||||
|
- MCP tokens: write permission is back (switch on the settings page, database column `CanWrite`, new migration).
|
||||||
|
Tokens without it neither see nor can call the write tools. The server description mentions the new tools.
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
|
||||||
|
- Dashboard: the expanded row of the catch list no longer repeats the strategy name, explanation and
|
||||||
|
technical details; they stay in the tooltip of the „Strategie“ column and in the „Strategien“ tab.
|
||||||
|
|
||||||
|
### Removed
|
||||||
|
|
||||||
|
- Hold method „Inhalt“ (HTML filler text, random text, alternating) with `text-drip`, `TextDripStrategy`, the
|
||||||
|
setting `Flypaper__Drip__Content` and its radio buttons. The link labyrinth is always used; a leftover
|
||||||
|
`Flypaper__Drip__Content` is ignored and logged as a removed setting.
|
||||||
|
|
||||||
## [0.6.0] - 2026-11-21
|
## [0.6.0] - 2026-11-21
|
||||||
|
|
||||||
### Removed
|
### Removed
|
||||||
@@ -208,7 +251,9 @@ First release.
|
|||||||
- Unraid Docker template; when started as root, the container hands `/data` to its app user
|
- Unraid Docker template; when started as root, the container hands `/data` to its app user
|
||||||
and drops privileges.
|
and drops privileges.
|
||||||
|
|
||||||
[Unreleased]: https://gitea.anticarnist.de/Tom/Flypaper/compare/v0.6.0...main
|
[Unreleased]: https://gitea.anticarnist.de/Tom/Flypaper/compare/v0.8.0...main
|
||||||
|
[0.8.0]: https://gitea.anticarnist.de/Tom/Flypaper/releases/tag/v0.8.0
|
||||||
|
[0.7.0]: https://gitea.anticarnist.de/Tom/Flypaper/releases/tag/v0.7.0
|
||||||
[0.6.0]: https://gitea.anticarnist.de/Tom/Flypaper/releases/tag/v0.6.0
|
[0.6.0]: https://gitea.anticarnist.de/Tom/Flypaper/releases/tag/v0.6.0
|
||||||
[0.5.2]: https://gitea.anticarnist.de/Tom/Flypaper/releases/tag/v0.5.2
|
[0.5.2]: https://gitea.anticarnist.de/Tom/Flypaper/releases/tag/v0.5.2
|
||||||
[0.5.1]: https://gitea.anticarnist.de/Tom/Flypaper/releases/tag/v0.5.1
|
[0.5.1]: https://gitea.anticarnist.de/Tom/Flypaper/releases/tag/v0.5.1
|
||||||
|
|||||||
@@ -20,12 +20,12 @@ All optional. Read at startup; list entries need an index (`__0`, `__1`, ...).
|
|||||||
| `ConnectionStrings__Flypaper` | SQLite database | `Data Source=/data/flypaper.db` |
|
| `ConnectionStrings__Flypaper` | SQLite database | `Data Source=/data/flypaper.db` |
|
||||||
| `Flypaper__DataProtection__KeysPath` | Keys for login cookies and forms | `/data/keys` |
|
| `Flypaper__DataProtection__KeysPath` | Keys for login cookies and forms | `/data/keys` |
|
||||||
| `Flypaper__GeoIp__Directory` | Folder for the DB-IP databases; empty disables GeoIP | `/data/geoip` |
|
| `Flypaper__GeoIp__Directory` | Folder for the DB-IP databases; empty disables GeoIP | `/data/geoip` |
|
||||||
| `Flypaper__Drip__Content` | Hold method: `Html`, `Text` or `Alternating` | `Html` |
|
|
||||||
| `Flypaper__Drip__MinDelay` / `MaxDelay` | Pause between chunks | `00:00:00.05` / `00:00:01` |
|
| `Flypaper__Drip__MinDelay` / `MaxDelay` | Pause between chunks | `00:00:00.05` / `00:00:01` |
|
||||||
| `Flypaper__Drip__MinChunkSize` / `MaxChunkSize` | Bytes per chunk | `1` / `64` |
|
| `Flypaper__Drip__MinChunkSize` / `MaxChunkSize` | Bytes per chunk | `1` / `64` |
|
||||||
| `Flypaper__Drip__HeadStartSize` | Bytes sent immediately before dripping starts (`0` = off) | `1024` |
|
| `Flypaper__Drip__HeadStartSize` | Bytes sent immediately before dripping starts (`0` = off) | `1024` |
|
||||||
| `Flypaper__Drip__LinkSpacing` | Link labyrinth: bytes of text between two links in the HTML page (`0` = off, plain `html-drip`) | `160` |
|
| `Flypaper__Drip__LinkSpacing` | Link labyrinth: bytes of text between two links in the HTML page (`0` = off, plain `html-drip`) | `160` |
|
||||||
| `Flypaper__Drip__BaitPaths` | Comma-separated decoy paths listed in `robots.txt` (max. 8, empty = off); requests to them get `robots-bait` and are held for at least 24 h | `/backup-2024/,/admin-old/,/internal/db-export/,/old-site/` |
|
| `Flypaper__Drip__BaitPaths` | Comma-separated decoy paths listed in `robots.txt` (max. 8, empty = off); requests to them get `robots-bait` and are held for at least 24 h | `/backup-2024/,/admin-old/,/internal/db-export/,/old-site/` |
|
||||||
|
| `Flypaper__Drip__Lure` | First visit of an unknown IP to `/` or `/favicon.ico` gets an instant WordPress-looking page or icon (`lure-page`, `lure-icon`) and is not held; every later request is trapped as usual | `true` |
|
||||||
| `Flypaper__Drip__MatchPath` | Pick content by request path (`/.env`, `*.json`, `*.xml`, `*.yml`, `*.sql`, `/.git/…`, `/SDK/…`, `/ISAPI/…`, `wp-login.php`) | `true` |
|
| `Flypaper__Drip__MatchPath` | Pick content by request path (`/.env`, `*.json`, `*.xml`, `*.yml`, `*.sql`, `/.git/…`, `/SDK/…`, `/ISAPI/…`, `wp-login.php`) | `true` |
|
||||||
| `TZ` | Time zone for the dashboard | UTC |
|
| `TZ` | Time zone for the dashboard | UTC |
|
||||||
|
|
||||||
@@ -39,7 +39,6 @@ general reset button removes all saved values; the hold method section has its o
|
|||||||
|
|
||||||
| Setting | Default |
|
| Setting | Default |
|
||||||
|---|---|
|
|---|---|
|
||||||
| Hold method: content (HTML filler text, random plain text, or alternating per catch) | HTML filler text |
|
|
||||||
| Hold method: pause between chunks, min and max (10 ms to 30 s) | 50 ms / 1000 ms |
|
| Hold method: pause between chunks, min and max (10 ms to 30 s) | 50 ms / 1000 ms |
|
||||||
| Hold method: chunk size, min and max (1 to 4096 bytes) | 1 / 64 bytes |
|
| Hold method: chunk size, min and max (1 to 4096 bytes) | 1 / 64 bytes |
|
||||||
| Hold method: head start, sent without delay before the drip (0 to 65536 bytes) | 1024 bytes |
|
| Hold method: head start, sent without delay before the drip (0 to 65536 bytes) | 1024 bytes |
|
||||||
|
|||||||
@@ -61,6 +61,7 @@ seconds. A *period* is a number with `m`, `h`, `d` or `w` (e.g. `1h`, `24h`, `7d
|
|||||||
|
|
||||||
| Tool | Parameters | Returns |
|
| Tool | Parameters | Returns |
|
||||||
|---|---|---|
|
|---|---|---|
|
||||||
|
| `list_active` | – | Bots held in the trap right now with origin, URL, user agent, strategy, time held and bytes sent (memory only) |
|
||||||
| `get_stats` | `period` (default `24h`) | Catches, rejected connections, unique IPs, total and average hold time, traps active now, longest catch |
|
| `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 |
|
| `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 |
|
| `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 |
|
||||||
|
|||||||
+1
-1
@@ -31,7 +31,7 @@ flowchart LR
|
|||||||
## Features
|
## Features
|
||||||
|
|
||||||
- **Trap** for everything that reaches the trap port: whatever host or path a bot asks for
|
- **Trap** for everything that reaches the trap port: whatever host or path a bot asks for
|
||||||
- **Slow delivery** of endless generated HTML or plain text (or both, alternating per catch)
|
- **Slow delivery** of endless generated HTML (link labyrinth)
|
||||||
with irregular timing; content, pauses, chunk sizes and hold time are set in the dashboard
|
with irregular timing; content, pauses, chunk sizes and hold time are set in the dashboard
|
||||||
- **Limits**: maximum connections overall and per IP, maximum hold time per catch
|
- **Limits**: maximum connections overall and per IP, maximum hold time per catch
|
||||||
- **Dashboard**: totals, a world map, top countries, providers, IPs and paths, the latest
|
- **Dashboard**: totals, a world map, top countries, providers, IPs and paths, the latest
|
||||||
|
|||||||
@@ -0,0 +1,15 @@
|
|||||||
|
using Flypaper.Core.Models;
|
||||||
|
|
||||||
|
namespace Flypaper.Core.Abstractions;
|
||||||
|
|
||||||
|
public interface IActiveTraps
|
||||||
|
{
|
||||||
|
IActiveTrapHandle Begin(TrapContext context, string strategy);
|
||||||
|
|
||||||
|
IReadOnlyList<ActiveTrap> Snapshot();
|
||||||
|
}
|
||||||
|
|
||||||
|
public interface IActiveTrapHandle : IDisposable
|
||||||
|
{
|
||||||
|
void Attach(Func<long> bytesSent);
|
||||||
|
}
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
using System.Net;
|
||||||
|
|
||||||
|
namespace Flypaper.Core.Abstractions;
|
||||||
|
|
||||||
|
public interface IKnownIpLookup
|
||||||
|
{
|
||||||
|
ValueTask<bool> HasSeenAsync(IPAddress address, CancellationToken ct);
|
||||||
|
}
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
namespace Flypaper.Core.Abstractions;
|
||||||
|
|
||||||
|
public interface IResponseHeaders
|
||||||
|
{
|
||||||
|
IReadOnlyDictionary<string, string> Headers { get; }
|
||||||
|
}
|
||||||
@@ -18,10 +18,12 @@ public static class FlypaperCoreExtensions
|
|||||||
|
|
||||||
services.TryAddSingleton(TimeProvider.System);
|
services.TryAddSingleton(TimeProvider.System);
|
||||||
services.TryAddSingleton<IConnectionGovernor, ConnectionGovernor>();
|
services.TryAddSingleton<IConnectionGovernor, ConnectionGovernor>();
|
||||||
|
services.TryAddSingleton<IActiveTraps, ActiveTrapRegistry>();
|
||||||
services.TryAddSingleton<IRandomSource, SystemRandomSource>();
|
services.TryAddSingleton<IRandomSource, SystemRandomSource>();
|
||||||
services.TryAddEnumerable(ServiceDescriptor.Singleton<ITarpitStrategy, HtmlDripStrategy>());
|
services.TryAddEnumerable(ServiceDescriptor.Singleton<ITarpitStrategy, HtmlDripStrategy>());
|
||||||
services.TryAddEnumerable(ServiceDescriptor.Singleton<ITarpitStrategy, TextDripStrategy>());
|
|
||||||
services.TryAddEnumerable(ServiceDescriptor.Singleton<ITarpitStrategy, RobotsStaticStrategy>());
|
services.TryAddEnumerable(ServiceDescriptor.Singleton<ITarpitStrategy, RobotsStaticStrategy>());
|
||||||
|
services.AddSingleton<ITarpitStrategy>(_ => LureStrategy.Page());
|
||||||
|
services.AddSingleton<ITarpitStrategy>(_ => LureStrategy.Icon());
|
||||||
foreach (var kind in Enum.GetValues<MazeKind>())
|
foreach (var kind in Enum.GetValues<MazeKind>())
|
||||||
{
|
{
|
||||||
services.AddSingleton<ITarpitStrategy>(provider => new MazeDripStrategy(
|
services.AddSingleton<ITarpitStrategy>(provider => new MazeDripStrategy(
|
||||||
@@ -44,6 +46,7 @@ public static class FlypaperCoreExtensions
|
|||||||
services.TryAddSingleton<TrapRunner>();
|
services.TryAddSingleton<TrapRunner>();
|
||||||
services.TryAddSingleton<IIpEnricher, NullIpEnricher>();
|
services.TryAddSingleton<IIpEnricher, NullIpEnricher>();
|
||||||
services.TryAddSingleton<IRepeatOffenderLookup, NullRepeatOffenderLookup>();
|
services.TryAddSingleton<IRepeatOffenderLookup, NullRepeatOffenderLookup>();
|
||||||
|
services.TryAddSingleton<IKnownIpLookup, NullKnownIpLookup>();
|
||||||
|
|
||||||
return services;
|
return services;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,5 @@
|
|||||||
|
using System.Net;
|
||||||
|
|
||||||
|
namespace Flypaper.Core.Models;
|
||||||
|
|
||||||
|
public sealed record ActiveTrap(Guid Id, IPAddress Ip, string? Target, string? ClientInfo, string Strategy, DateTimeOffset StartedAt, long BytesSent);
|
||||||
@@ -1,3 +1,3 @@
|
|||||||
namespace Flypaper.Core.Models;
|
namespace Flypaper.Core.Models;
|
||||||
|
|
||||||
public sealed record TrapContext(TrapSession Session, string? Target = null, string? ClientInfo = null, string? Path = null);
|
public sealed record TrapContext(TrapSession Session, string? Target = null, string? ClientInfo = null, string? Path = null, bool IsNewIp = false);
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
using System.Net;
|
||||||
|
using Flypaper.Core.Abstractions;
|
||||||
|
|
||||||
|
namespace Flypaper.Core.Networking;
|
||||||
|
|
||||||
|
internal sealed class NullKnownIpLookup : IKnownIpLookup
|
||||||
|
{
|
||||||
|
public ValueTask<bool> HasSeenAsync(IPAddress address, CancellationToken ct) => ValueTask.FromResult(true);
|
||||||
|
}
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
using System.Collections.Concurrent;
|
||||||
|
using Flypaper.Core.Abstractions;
|
||||||
|
using Flypaper.Core.Models;
|
||||||
|
|
||||||
|
namespace Flypaper.Core.Runtime;
|
||||||
|
|
||||||
|
public sealed class ActiveTrapRegistry(TimeProvider timeProvider) : IActiveTraps
|
||||||
|
{
|
||||||
|
private readonly ConcurrentDictionary<Guid, Entry> _entries = new();
|
||||||
|
|
||||||
|
public IActiveTrapHandle Begin(TrapContext context, string strategy)
|
||||||
|
{
|
||||||
|
var entry = new Entry(this, context, strategy, timeProvider.GetUtcNow());
|
||||||
|
_entries[context.Session.Id] = entry;
|
||||||
|
return entry;
|
||||||
|
}
|
||||||
|
|
||||||
|
public IReadOnlyList<ActiveTrap> Snapshot() =>
|
||||||
|
_entries.Values.Select(entry => entry.ToActiveTrap()).OrderBy(trap => trap.StartedAt).ToList();
|
||||||
|
|
||||||
|
private sealed class Entry(ActiveTrapRegistry owner, TrapContext context, string strategy, DateTimeOffset startedAt) : IActiveTrapHandle
|
||||||
|
{
|
||||||
|
private Func<long>? _bytesSent;
|
||||||
|
|
||||||
|
public void Attach(Func<long> bytesSent) => _bytesSent = bytesSent;
|
||||||
|
|
||||||
|
public ActiveTrap ToActiveTrap() => new(
|
||||||
|
context.Session.Id,
|
||||||
|
context.Session.RemoteIp,
|
||||||
|
context.Target,
|
||||||
|
context.ClientInfo,
|
||||||
|
strategy,
|
||||||
|
startedAt,
|
||||||
|
_bytesSent?.Invoke() ?? 0);
|
||||||
|
|
||||||
|
public void Dispose() => owner._entries.TryRemove(context.Session.Id, out _);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -19,6 +19,12 @@ public sealed class ConfiguredStrategySelector(
|
|||||||
return robots;
|
return robots;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (context.IsNewIp && options.CurrentValue.Lure && LureContent.Handles(context.Path)
|
||||||
|
&& candidates.FirstOrDefault(strategy => strategy.Name == (context.Path == LureContent.PagePath ? LureStrategy.PageName : LureStrategy.IconName)) is { } lure)
|
||||||
|
{
|
||||||
|
return lure;
|
||||||
|
}
|
||||||
|
|
||||||
if (BaitPaths.Matches(BaitPaths.Parse(options.CurrentValue.BaitPaths), context.Path)
|
if (BaitPaths.Matches(BaitPaths.Parse(options.CurrentValue.BaitPaths), context.Path)
|
||||||
&& candidates.FirstOrDefault(strategy => strategy.Name == MazeDripStrategy.BaitName) is { } bait)
|
&& candidates.FirstOrDefault(strategy => strategy.Name == MazeDripStrategy.BaitName) is { } bait)
|
||||||
{
|
{
|
||||||
@@ -34,14 +40,7 @@ public sealed class ConfiguredStrategySelector(
|
|||||||
var maze = options.CurrentValue.LinkSpacing > 0
|
var maze = options.CurrentValue.LinkSpacing > 0
|
||||||
&& candidates.Any(strategy => strategy.Name == MazeDripStrategy.PageName);
|
&& candidates.Any(strategy => strategy.Name == MazeDripStrategy.PageName);
|
||||||
var page = maze ? MazeDripStrategy.PageName : HtmlDripStrategy.StrategyName;
|
var page = maze ? MazeDripStrategy.PageName : HtmlDripStrategy.StrategyName;
|
||||||
string[] wanted = options.CurrentValue.Content switch
|
var matching = candidates.Where(strategy => strategy.Name == page).ToList();
|
||||||
{
|
|
||||||
DripContent.Text => [TextDripStrategy.StrategyName],
|
|
||||||
DripContent.Alternating => [page, TextDripStrategy.StrategyName],
|
|
||||||
_ => [page]
|
|
||||||
};
|
|
||||||
|
|
||||||
var matching = candidates.Where(strategy => wanted.Contains(strategy.Name)).ToList();
|
|
||||||
var chosen = matching.Count == 0
|
var chosen = matching.Count == 0
|
||||||
? candidates.FirstOrDefault()
|
? candidates.FirstOrDefault()
|
||||||
: matching[random.Next(0, matching.Count)];
|
: matching[random.Next(0, matching.Count)];
|
||||||
|
|||||||
@@ -11,6 +11,7 @@ public sealed partial class TrapRunner(
|
|||||||
IConnectionGovernor governor,
|
IConnectionGovernor governor,
|
||||||
ITrapStrategySelector strategies,
|
ITrapStrategySelector strategies,
|
||||||
ITrapEventSink sink,
|
ITrapEventSink sink,
|
||||||
|
IActiveTraps activeTraps,
|
||||||
IRepeatOffenderLookup repeatOffenders,
|
IRepeatOffenderLookup repeatOffenders,
|
||||||
IOptionsMonitor<FlypaperOptions> options,
|
IOptionsMonitor<FlypaperOptions> options,
|
||||||
TimeProvider timeProvider,
|
TimeProvider timeProvider,
|
||||||
@@ -46,6 +47,7 @@ public sealed partial class TrapRunner(
|
|||||||
description += " repeat";
|
description += " repeat";
|
||||||
}
|
}
|
||||||
|
|
||||||
|
using var active = activeTraps.Begin(context, description);
|
||||||
using var hold = new CancellationTokenSource(holdDuration, timeProvider);
|
using var hold = new CancellationTokenSource(holdDuration, timeProvider);
|
||||||
using var linked = CancellationTokenSource.CreateLinkedTokenSource(ct, hold.Token);
|
using var linked = CancellationTokenSource.CreateLinkedTokenSource(ct, hold.Token);
|
||||||
|
|
||||||
@@ -54,6 +56,8 @@ public sealed partial class TrapRunner(
|
|||||||
try
|
try
|
||||||
{
|
{
|
||||||
channel = new CountingTrapChannel(await openChannel(strategy, linked.Token));
|
channel = new CountingTrapChannel(await openChannel(strategy, linked.Token));
|
||||||
|
var counting = channel;
|
||||||
|
active.Attach(() => counting.BytesSent);
|
||||||
await strategy.RunAsync(channel, linked.Token);
|
await strategy.RunAsync(channel, linked.Token);
|
||||||
}
|
}
|
||||||
catch (OperationCanceledException) when (linked.IsCancellationRequested)
|
catch (OperationCanceledException) when (linked.IsCancellationRequested)
|
||||||
|
|||||||
@@ -4,7 +4,6 @@ using Flypaper.Core.Strategies;
|
|||||||
namespace Flypaper.Core.Settings;
|
namespace Flypaper.Core.Settings;
|
||||||
|
|
||||||
public sealed record HoldMethodSettings(
|
public sealed record HoldMethodSettings(
|
||||||
DripContent Content,
|
|
||||||
TimeSpan MinDelay,
|
TimeSpan MinDelay,
|
||||||
TimeSpan MaxDelay,
|
TimeSpan MaxDelay,
|
||||||
int MinChunkSize,
|
int MinChunkSize,
|
||||||
@@ -21,7 +20,6 @@ public sealed record HoldMethodSettings(
|
|||||||
|
|
||||||
public IReadOnlyDictionary<string, string> ToConfiguration() => new Dictionary<string, string>
|
public IReadOnlyDictionary<string, string> ToConfiguration() => new Dictionary<string, string>
|
||||||
{
|
{
|
||||||
[SettingKeys.DripContent] = Content.ToString(),
|
|
||||||
[SettingKeys.DripMinDelay] = MinDelay.ToString("c", CultureInfo.InvariantCulture),
|
[SettingKeys.DripMinDelay] = MinDelay.ToString("c", CultureInfo.InvariantCulture),
|
||||||
[SettingKeys.DripMaxDelay] = MaxDelay.ToString("c", CultureInfo.InvariantCulture),
|
[SettingKeys.DripMaxDelay] = MaxDelay.ToString("c", CultureInfo.InvariantCulture),
|
||||||
[SettingKeys.DripMinChunkSize] = MinChunkSize.ToString(CultureInfo.InvariantCulture),
|
[SettingKeys.DripMinChunkSize] = MinChunkSize.ToString(CultureInfo.InvariantCulture),
|
||||||
@@ -43,7 +41,6 @@ public sealed record HoldMethodSettings(
|
|||||||
}
|
}
|
||||||
|
|
||||||
public sealed record HoldMethodInput(
|
public sealed record HoldMethodInput(
|
||||||
string? Content,
|
|
||||||
string? MinDelayMs,
|
string? MinDelayMs,
|
||||||
string? MaxDelayMs,
|
string? MaxDelayMs,
|
||||||
string? MinChunkSize,
|
string? MinChunkSize,
|
||||||
|
|||||||
@@ -48,14 +48,6 @@ public static class RuntimeSettingsParser
|
|||||||
{
|
{
|
||||||
var errors = new Dictionary<string, string>();
|
var errors = new Dictionary<string, string>();
|
||||||
|
|
||||||
DripContent? content = Enum.TryParse<DripContent>(input.Content, ignoreCase: true, out var parsed) && Enum.IsDefined(parsed)
|
|
||||||
? parsed
|
|
||||||
: null;
|
|
||||||
if (content is null)
|
|
||||||
{
|
|
||||||
errors[nameof(input.Content)] = "Bitte eine Methode wählen.";
|
|
||||||
}
|
|
||||||
|
|
||||||
var minDelay = ParseInt(input.MinDelayMs, nameof(input.MinDelayMs), MinDelayMs, MaxDelayMs, errors);
|
var minDelay = ParseInt(input.MinDelayMs, nameof(input.MinDelayMs), MinDelayMs, MaxDelayMs, errors);
|
||||||
var maxDelay = ParseInt(input.MaxDelayMs, nameof(input.MaxDelayMs), MinDelayMs, MaxDelayMs, errors);
|
var maxDelay = ParseInt(input.MaxDelayMs, nameof(input.MaxDelayMs), MinDelayMs, MaxDelayMs, errors);
|
||||||
var minChunk = ParseInt(input.MinChunkSize, nameof(input.MinChunkSize), 1, MaxChunkSize, errors);
|
var minChunk = ParseInt(input.MinChunkSize, nameof(input.MinChunkSize), 1, MaxChunkSize, errors);
|
||||||
@@ -84,7 +76,6 @@ public static class RuntimeSettingsParser
|
|||||||
|
|
||||||
return new HoldMethodParseResult(
|
return new HoldMethodParseResult(
|
||||||
new HoldMethodSettings(
|
new HoldMethodSettings(
|
||||||
content!.Value,
|
|
||||||
TimeSpan.FromMilliseconds(minDelay!.Value),
|
TimeSpan.FromMilliseconds(minDelay!.Value),
|
||||||
TimeSpan.FromMilliseconds(maxDelay!.Value),
|
TimeSpan.FromMilliseconds(maxDelay!.Value),
|
||||||
minChunk!.Value,
|
minChunk!.Value,
|
||||||
|
|||||||
@@ -9,7 +9,6 @@ public static class SettingKeys
|
|||||||
public const string RepeatHoldDuration = "Flypaper:RepeatHoldDuration";
|
public const string RepeatHoldDuration = "Flypaper:RepeatHoldDuration";
|
||||||
public const string IgnorePrivateNetworks = "Flypaper:IgnorePrivateNetworks";
|
public const string IgnorePrivateNetworks = "Flypaper:IgnorePrivateNetworks";
|
||||||
public const string RetentionDays = "Flypaper:Retention:Days";
|
public const string RetentionDays = "Flypaper:Retention:Days";
|
||||||
public const string DripContent = "Flypaper:Drip:Content";
|
|
||||||
public const string DripMinDelay = "Flypaper:Drip:MinDelay";
|
public const string DripMinDelay = "Flypaper:Drip:MinDelay";
|
||||||
public const string DripMaxDelay = "Flypaper:Drip:MaxDelay";
|
public const string DripMaxDelay = "Flypaper:Drip:MaxDelay";
|
||||||
public const string DripMinChunkSize = "Flypaper:Drip:MinChunkSize";
|
public const string DripMinChunkSize = "Flypaper:Drip:MinChunkSize";
|
||||||
@@ -23,7 +22,7 @@ public static class SettingKeys
|
|||||||
[MaxConnections, MaxConnectionsPerIp, IgnorePrivateNetworks, RetentionDays];
|
[MaxConnections, MaxConnectionsPerIp, IgnorePrivateNetworks, RetentionDays];
|
||||||
|
|
||||||
public static readonly IReadOnlyList<string> HoldMethod =
|
public static readonly IReadOnlyList<string> HoldMethod =
|
||||||
[DripContent, DripMinDelay, DripMaxDelay, DripMinChunkSize, DripMaxChunkSize, DripHeadStartSize, DripMatchPath, DripLinkSpacing, DripBaitPaths, MaxHoldDuration, RepeatWindowDays, RepeatHoldDuration];
|
[DripMinDelay, DripMaxDelay, DripMinChunkSize, DripMaxChunkSize, DripHeadStartSize, DripMatchPath, DripLinkSpacing, DripBaitPaths, MaxHoldDuration, RepeatWindowDays, RepeatHoldDuration];
|
||||||
|
|
||||||
public static readonly IReadOnlySet<string> All =
|
public static readonly IReadOnlySet<string> All =
|
||||||
new HashSet<string>(General.Concat(HoldMethod), StringComparer.OrdinalIgnoreCase);
|
new HashSet<string>(General.Concat(HoldMethod), StringComparer.OrdinalIgnoreCase);
|
||||||
|
|||||||
@@ -1,8 +0,0 @@
|
|||||||
namespace Flypaper.Core.Strategies;
|
|
||||||
|
|
||||||
public enum DripContent
|
|
||||||
{
|
|
||||||
Html,
|
|
||||||
Text,
|
|
||||||
Alternating
|
|
||||||
}
|
|
||||||
@@ -4,8 +4,6 @@ public sealed class DripOptions
|
|||||||
{
|
{
|
||||||
public const string SectionName = "Flypaper:Drip";
|
public const string SectionName = "Flypaper:Drip";
|
||||||
|
|
||||||
public DripContent Content { get; set; } = DripContent.Html;
|
|
||||||
|
|
||||||
public TimeSpan MinDelay { get; set; } = TimeSpan.FromMilliseconds(50);
|
public TimeSpan MinDelay { get; set; } = TimeSpan.FromMilliseconds(50);
|
||||||
|
|
||||||
public TimeSpan MaxDelay { get; set; } = TimeSpan.FromSeconds(1);
|
public TimeSpan MaxDelay { get; set; } = TimeSpan.FromSeconds(1);
|
||||||
@@ -20,5 +18,7 @@ public sealed class DripOptions
|
|||||||
|
|
||||||
public int LinkSpacing { get; set; } = 160;
|
public int LinkSpacing { get; set; } = 160;
|
||||||
|
|
||||||
|
public bool Lure { get; set; } = true;
|
||||||
|
|
||||||
public string BaitPaths { get; set; } = Strategies.BaitPaths.Default;
|
public string BaitPaths { get; set; } = Strategies.BaitPaths.Default;
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,90 @@
|
|||||||
|
using System.Text;
|
||||||
|
|
||||||
|
namespace Flypaper.Core.Strategies;
|
||||||
|
|
||||||
|
public static class LureContent
|
||||||
|
{
|
||||||
|
public const string PagePath = "/";
|
||||||
|
|
||||||
|
public const string IconPath = "/favicon.ico";
|
||||||
|
|
||||||
|
public static readonly IReadOnlyDictionary<string, string> Headers = new Dictionary<string, string>
|
||||||
|
{
|
||||||
|
["X-Powered-By"] = "PHP/8.1.27",
|
||||||
|
["Link"] = "</wp-json/>; rel=\"https://api.w.org/\""
|
||||||
|
};
|
||||||
|
|
||||||
|
public static bool Handles(string? path) =>
|
||||||
|
string.Equals(path, PagePath, StringComparison.Ordinal) || string.Equals(path, IconPath, StringComparison.OrdinalIgnoreCase);
|
||||||
|
|
||||||
|
public static byte[] Page() => Encoding.UTF8.GetBytes("""
|
||||||
|
<!doctype html>
|
||||||
|
<html lang="en-US">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||||
|
<meta name="generator" content="WordPress 6.4.3">
|
||||||
|
<title>Intranet – Just another WordPress site</title>
|
||||||
|
<link rel="icon" href="/favicon.ico">
|
||||||
|
<link rel="stylesheet" href="/wp-content/themes/twentytwentyfour/style.css?ver=1.0">
|
||||||
|
<link rel="alternate" type="application/rss+xml" title="Intranet » Feed" href="/feed/">
|
||||||
|
<link rel="https://api.w.org/" href="/wp-json/">
|
||||||
|
<link rel="EditURI" type="application/rsd+xml" title="RSD" href="/xmlrpc.php?rsd">
|
||||||
|
</head>
|
||||||
|
<body class="home blog">
|
||||||
|
<header><h1>Intranet</h1><p>Just another WordPress site</p></header>
|
||||||
|
<nav>
|
||||||
|
<a href="/wp-login.php">Log in</a>
|
||||||
|
<a href="/wp-admin/">Dashboard</a>
|
||||||
|
<a href="/wp-content/uploads/backup/">Backups</a>
|
||||||
|
<a href="/wp-config.php.bak">Config</a>
|
||||||
|
</nav>
|
||||||
|
<main><article><h2>Hello world!</h2><p>Welcome to WordPress. This is your first post. Edit or delete it, then start writing!</p></article></main>
|
||||||
|
<footer><p>Proudly powered by <a href="https://wordpress.org/">WordPress</a></p></footer>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
|
""");
|
||||||
|
|
||||||
|
public static byte[] Icon()
|
||||||
|
{
|
||||||
|
const int size = 16;
|
||||||
|
using var stream = new MemoryStream();
|
||||||
|
using var writer = new BinaryWriter(stream);
|
||||||
|
writer.Write((ushort)0);
|
||||||
|
writer.Write((ushort)1);
|
||||||
|
writer.Write((ushort)1);
|
||||||
|
writer.Write((byte)size);
|
||||||
|
writer.Write((byte)size);
|
||||||
|
writer.Write((byte)0);
|
||||||
|
writer.Write((byte)0);
|
||||||
|
writer.Write((ushort)1);
|
||||||
|
writer.Write((ushort)32);
|
||||||
|
var imageSize = 40 + size * size * 4 + size * 4;
|
||||||
|
writer.Write(imageSize);
|
||||||
|
writer.Write(22);
|
||||||
|
writer.Write(40);
|
||||||
|
writer.Write(size);
|
||||||
|
writer.Write(size * 2);
|
||||||
|
writer.Write((ushort)1);
|
||||||
|
writer.Write((ushort)32);
|
||||||
|
writer.Write(0);
|
||||||
|
writer.Write(size * size * 4);
|
||||||
|
writer.Write(0);
|
||||||
|
writer.Write(0);
|
||||||
|
writer.Write(0);
|
||||||
|
writer.Write(0);
|
||||||
|
for (var y = 0; y < size; y++)
|
||||||
|
{
|
||||||
|
for (var x = 0; x < size; x++)
|
||||||
|
{
|
||||||
|
var dx = x - 7.5;
|
||||||
|
var dy = y - 7.5;
|
||||||
|
var inside = dx * dx + dy * dy <= 56;
|
||||||
|
writer.Write(inside ? 0xFF8A5A21u : 0u);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
writer.Write(new byte[size * 4]);
|
||||||
|
return stream.ToArray();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
using Flypaper.Core.Abstractions;
|
||||||
|
using Flypaper.Core.Models;
|
||||||
|
|
||||||
|
namespace Flypaper.Core.Strategies;
|
||||||
|
|
||||||
|
public sealed class LureStrategy(string name, string mediaType, byte[] body) : ITarpitStrategy, IStrategyDetails, IResponseHeaders
|
||||||
|
{
|
||||||
|
public const string PageName = "lure-page";
|
||||||
|
|
||||||
|
public const string IconName = "lure-icon";
|
||||||
|
|
||||||
|
public static LureStrategy Page() => new(PageName, "text/html; charset=utf-8", LureContent.Page());
|
||||||
|
|
||||||
|
public static LureStrategy Icon() => new(IconName, "image/x-icon", LureContent.Icon());
|
||||||
|
|
||||||
|
public string Name => name;
|
||||||
|
|
||||||
|
public string MediaType => mediaType;
|
||||||
|
|
||||||
|
public IReadOnlyDictionary<string, string> Headers => LureContent.Headers;
|
||||||
|
|
||||||
|
public bool Supports(TrapProtocol protocol) => protocol == TrapProtocol.Http;
|
||||||
|
|
||||||
|
public string Describe() => Name;
|
||||||
|
|
||||||
|
public async Task RunAsync(ITrapChannel channel, CancellationToken ct) => await channel.WriteAsync(body, ct);
|
||||||
|
}
|
||||||
@@ -1,27 +0,0 @@
|
|||||||
using System.Text;
|
|
||||||
using Flypaper.Core.Abstractions;
|
|
||||||
|
|
||||||
namespace Flypaper.Core.Strategies;
|
|
||||||
|
|
||||||
public static class TextContent
|
|
||||||
{
|
|
||||||
public static IEnumerable<string> Generate(IRandomSource random)
|
|
||||||
{
|
|
||||||
while (true)
|
|
||||||
{
|
|
||||||
var builder = new StringBuilder();
|
|
||||||
var sentences = random.Next(1, 7);
|
|
||||||
for (var i = 0; i < sentences; i++)
|
|
||||||
{
|
|
||||||
if (i > 0)
|
|
||||||
{
|
|
||||||
builder.Append(' ');
|
|
||||||
}
|
|
||||||
|
|
||||||
builder.Append(LoremText.Sentence(random));
|
|
||||||
}
|
|
||||||
|
|
||||||
yield return builder.Append(random.Next(0, 4) == 0 ? "\n\n" : "\n").ToString();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,18 +0,0 @@
|
|||||||
using Flypaper.Core.Abstractions;
|
|
||||||
using Microsoft.Extensions.Options;
|
|
||||||
|
|
||||||
namespace Flypaper.Core.Strategies;
|
|
||||||
|
|
||||||
public sealed class TextDripStrategy(
|
|
||||||
IOptionsMonitor<DripOptions> options,
|
|
||||||
IRandomSource random,
|
|
||||||
TimeProvider timeProvider) : DripStrategy(options, random, timeProvider)
|
|
||||||
{
|
|
||||||
public const string StrategyName = "text-drip";
|
|
||||||
|
|
||||||
public override string Name => StrategyName;
|
|
||||||
|
|
||||||
public override string MediaType => "text/plain; charset=utf-8";
|
|
||||||
|
|
||||||
protected override IEnumerable<string> Content(IRandomSource random, ITrapChannel channel, DripOptions options) => TextContent.Generate(random);
|
|
||||||
}
|
|
||||||
@@ -19,7 +19,8 @@ public static class FlypaperHttpExtensions
|
|||||||
"Flypaper:Http:KnownHosts",
|
"Flypaper:Http:KnownHosts",
|
||||||
"Flypaper:Http:TrapPaths",
|
"Flypaper:Http:TrapPaths",
|
||||||
"Flypaper:Http:ExtraKnownHosts",
|
"Flypaper:Http:ExtraKnownHosts",
|
||||||
"Flypaper:Http:TrapPathsOverride"
|
"Flypaper:Http:TrapPathsOverride",
|
||||||
|
"Flypaper:Drip:Content"
|
||||||
];
|
];
|
||||||
|
|
||||||
public static IServiceCollection AddFlypaperHttp(this IServiceCollection services, IConfiguration configuration)
|
public static IServiceCollection AddFlypaperHttp(this IServiceCollection services, IConfiguration configuration)
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ using Flypaper.Core.Abstractions;
|
|||||||
using Flypaper.Core.Models;
|
using Flypaper.Core.Models;
|
||||||
using Flypaper.Core.Networking;
|
using Flypaper.Core.Networking;
|
||||||
using Flypaper.Core.Runtime;
|
using Flypaper.Core.Runtime;
|
||||||
|
using Flypaper.Core.Strategies;
|
||||||
using Microsoft.AspNetCore.Http;
|
using Microsoft.AspNetCore.Http;
|
||||||
using Microsoft.AspNetCore.Http.Features;
|
using Microsoft.AspNetCore.Http.Features;
|
||||||
using Microsoft.AspNetCore.Server.Kestrel.Core.Features;
|
using Microsoft.AspNetCore.Server.Kestrel.Core.Features;
|
||||||
@@ -14,6 +15,8 @@ internal sealed class FlypaperMiddleware(
|
|||||||
RequestDelegate next,
|
RequestDelegate next,
|
||||||
TrapRunner runner,
|
TrapRunner runner,
|
||||||
IOptions<PortOptions> ports,
|
IOptions<PortOptions> ports,
|
||||||
|
IKnownIpLookup knownIps,
|
||||||
|
IOptionsMonitor<DripOptions> drip,
|
||||||
TimeProvider timeProvider)
|
TimeProvider timeProvider)
|
||||||
{
|
{
|
||||||
public async Task InvokeAsync(HttpContext context)
|
public async Task InvokeAsync(HttpContext context)
|
||||||
@@ -32,11 +35,17 @@ internal sealed class FlypaperMiddleware(
|
|||||||
context.Connection.RemoteIpAddress ?? IPAddress.None,
|
context.Connection.RemoteIpAddress ?? IPAddress.None,
|
||||||
timeProvider.GetUtcNow());
|
timeProvider.GetUtcNow());
|
||||||
|
|
||||||
|
var isNewIp = drip.CurrentValue.Lure
|
||||||
|
&& HttpMethods.IsGet(request.Method)
|
||||||
|
&& LureContent.Handles(request.Path.Value)
|
||||||
|
&& !await knownIps.HasSeenAsync(session.RemoteIp, context.RequestAborted);
|
||||||
|
|
||||||
var trapContext = new TrapContext(
|
var trapContext = new TrapContext(
|
||||||
session,
|
session,
|
||||||
$"{request.Method} {StoredHost(request.Host)}{request.Path}{request.QueryString}",
|
$"{request.Method} {StoredHost(request.Host)}{request.Path}{request.QueryString}",
|
||||||
request.Headers.UserAgent.ToString(),
|
request.Headers.UserAgent.ToString(),
|
||||||
request.Path.Value);
|
request.Path.Value,
|
||||||
|
isNewIp);
|
||||||
|
|
||||||
var outcome = await runner.RunAsync(
|
var outcome = await runner.RunAsync(
|
||||||
trapContext,
|
trapContext,
|
||||||
@@ -77,6 +86,14 @@ internal sealed class FlypaperMiddleware(
|
|||||||
response.Headers.Server = "nginx";
|
response.Headers.Server = "nginx";
|
||||||
response.Headers.CacheControl = "no-store";
|
response.Headers.CacheControl = "no-store";
|
||||||
response.Headers["X-Accel-Buffering"] = "no";
|
response.Headers["X-Accel-Buffering"] = "no";
|
||||||
|
if (strategy is IResponseHeaders extra)
|
||||||
|
{
|
||||||
|
foreach (var (name, value) in extra.Headers)
|
||||||
|
{
|
||||||
|
response.Headers[name] = value;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
await response.StartAsync(ct);
|
await response.StartAsync(ct);
|
||||||
|
|
||||||
return new HttpTrapChannel(session, response);
|
return new HttpTrapChannel(session, response);
|
||||||
|
|||||||
@@ -1,10 +1,11 @@
|
|||||||
using Flypaper.Core.Models;
|
using Flypaper.Core.Models;
|
||||||
using Flypaper.Storage.Entities;
|
using Flypaper.Storage.Entities;
|
||||||
|
using Flypaper.Storage.Explanations;
|
||||||
using Microsoft.EntityFrameworkCore;
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
|
||||||
namespace Flypaper.Storage.Dashboard;
|
namespace Flypaper.Storage.Dashboard;
|
||||||
|
|
||||||
public sealed class DashboardQueries(IDbContextFactory<FlypaperDbContext> dbContextFactory, TimeProvider timeProvider)
|
public sealed class DashboardQueries(IDbContextFactory<FlypaperDbContext> dbContextFactory, TimeProvider timeProvider, ExplanationRuleStore explanations)
|
||||||
{
|
{
|
||||||
private const int TopCount = 10;
|
private const int TopCount = 10;
|
||||||
|
|
||||||
@@ -64,12 +65,24 @@ public sealed class DashboardQueries(IDbContextFactory<FlypaperDbContext> dbCont
|
|||||||
.Select(g => new CountryOption(g.Key, g.Max(e => e.Country)))
|
.Select(g => new CountryOption(g.Key, g.Max(e => e.Country)))
|
||||||
.ToListAsync(ct);
|
.ToListAsync(ct);
|
||||||
|
|
||||||
return new RecentCatches(
|
var ordered = events.OrderByDescending(e => e.StartedAt).ThenByDescending(e => e.Id);
|
||||||
await events.OrderByDescending(e => e.StartedAt).ThenByDescending(e => e.Id)
|
var take = Math.Clamp(filter.Limit, 1, RecentFilter.MaxLimit);
|
||||||
.Take(Math.Clamp(filter.Limit, 1, RecentFilter.MaxLimit))
|
|
||||||
.ToListAsync(ct),
|
if (filter.Unexplained)
|
||||||
await events.CountAsync(ct),
|
{
|
||||||
countries);
|
var rules = await explanations.GetRuleSetAsync(ct);
|
||||||
|
var candidates = await ordered.Where(e => e.Target != null).Select(e => new { e.Id, e.Target }).ToListAsync(ct);
|
||||||
|
var ids = candidates
|
||||||
|
.Where(c => rules.Winner(ExplanationKind.Target, ExplanationText.Path(c.Target)!) is null)
|
||||||
|
.Select(c => c.Id)
|
||||||
|
.ToList();
|
||||||
|
var page = ids.Take(take).ToList();
|
||||||
|
var items = (await db.TrapEvents.AsNoTracking().Where(e => page.Contains(e.Id)).ToListAsync(ct))
|
||||||
|
.OrderByDescending(e => e.StartedAt).ThenByDescending(e => e.Id).ToList();
|
||||||
|
return new RecentCatches(items, ids.Count, countries);
|
||||||
|
}
|
||||||
|
|
||||||
|
return new RecentCatches(await ordered.Take(take).ToListAsync(ct), await events.CountAsync(ct), countries);
|
||||||
}
|
}
|
||||||
|
|
||||||
private IQueryable<TrapEventEntity> Apply(IQueryable<TrapEventEntity> events, RecentFilter filter)
|
private IQueryable<TrapEventEntity> Apply(IQueryable<TrapEventEntity> events, RecentFilter filter)
|
||||||
|
|||||||
@@ -13,7 +13,8 @@ public sealed record RecentFilter(
|
|||||||
StrategyMatch? Strategy = null,
|
StrategyMatch? Strategy = null,
|
||||||
string? Search = null,
|
string? Search = null,
|
||||||
int Limit = RecentFilter.DefaultLimit,
|
int Limit = RecentFilter.DefaultLimit,
|
||||||
IReadOnlyList<string>? SearchStrategies = null)
|
IReadOnlyList<string>? SearchStrategies = null,
|
||||||
|
bool Unexplained = false)
|
||||||
{
|
{
|
||||||
public const int DefaultLimit = 50;
|
public const int DefaultLimit = 50;
|
||||||
public const int MaxLimit = 500;
|
public const int MaxLimit = 500;
|
||||||
|
|||||||
@@ -0,0 +1,31 @@
|
|||||||
|
namespace Flypaper.Storage.Entities;
|
||||||
|
|
||||||
|
public enum ExplanationKind
|
||||||
|
{
|
||||||
|
Target,
|
||||||
|
ClientInfo,
|
||||||
|
Outcome
|
||||||
|
}
|
||||||
|
|
||||||
|
public sealed class ExplanationRuleEntity
|
||||||
|
{
|
||||||
|
public int Id { get; set; }
|
||||||
|
|
||||||
|
public ExplanationKind Kind { get; set; }
|
||||||
|
|
||||||
|
public required string Pattern { get; set; }
|
||||||
|
|
||||||
|
public required string Text { get; set; }
|
||||||
|
|
||||||
|
public int Priority { get; set; }
|
||||||
|
|
||||||
|
public bool Enabled { get; set; } = true;
|
||||||
|
|
||||||
|
public string? Note { get; set; }
|
||||||
|
|
||||||
|
public DateTime CreatedAt { get; set; }
|
||||||
|
|
||||||
|
public DateTime UpdatedAt { get; set; }
|
||||||
|
|
||||||
|
public required string CreatedBy { get; set; }
|
||||||
|
}
|
||||||
@@ -11,4 +11,6 @@ public sealed class McpTokenEntity
|
|||||||
public DateTime CreatedAt { get; set; }
|
public DateTime CreatedAt { get; set; }
|
||||||
|
|
||||||
public DateTime? LastUsedAt { get; set; }
|
public DateTime? LastUsedAt { get; set; }
|
||||||
|
|
||||||
|
public bool CanWrite { get; set; }
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
namespace Flypaper.Storage.Explanations;
|
||||||
|
|
||||||
|
public static class ExplanationLimits
|
||||||
|
{
|
||||||
|
public const int MaxPatternLength = 500;
|
||||||
|
public const int MaxTextLength = 600;
|
||||||
|
public const int MaxNoteLength = 500;
|
||||||
|
public const int MaxCreatedByLength = 100;
|
||||||
|
public const int MaxPriority = 1000;
|
||||||
|
public const int MaxRules = 2000;
|
||||||
|
}
|
||||||
@@ -0,0 +1,186 @@
|
|||||||
|
using Flypaper.Storage.Entities;
|
||||||
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
|
||||||
|
namespace Flypaper.Storage.Explanations;
|
||||||
|
|
||||||
|
public enum UnexplainedGrouping
|
||||||
|
{
|
||||||
|
Path,
|
||||||
|
Pattern
|
||||||
|
}
|
||||||
|
|
||||||
|
public sealed record ObservedValue(string Value, int Catches, DateTime FirstSeen, DateTime LastSeen, string? ExampleTarget, string? ExampleUserAgent);
|
||||||
|
|
||||||
|
public sealed record UnexplainedGroup(string Key, int Catches, IReadOnlyList<string> ExamplePaths, string? ExampleUserAgent, DateTime FirstSeen, DateTime LastSeen);
|
||||||
|
|
||||||
|
public sealed record UnexplainedResult(int Catches, int DistinctPaths, IReadOnlyList<UnexplainedGroup> Groups, int GroupsOmitted);
|
||||||
|
|
||||||
|
public sealed record RuleTakeover(ExplanationRuleEntity Rule, int Catches, IReadOnlyList<string> Examples);
|
||||||
|
|
||||||
|
public sealed record RuleTestResult(
|
||||||
|
int Catches,
|
||||||
|
int DistinctValues,
|
||||||
|
IReadOnlyList<(string Value, int Catches)> Examples,
|
||||||
|
int NewlyExplained,
|
||||||
|
IReadOnlyList<RuleTakeover> TakesOver,
|
||||||
|
int Lost,
|
||||||
|
IReadOnlyList<string> LostExamples);
|
||||||
|
|
||||||
|
public sealed class ExplanationQueries(IDbContextFactory<FlypaperDbContext> dbContextFactory, ExplanationRuleStore store)
|
||||||
|
{
|
||||||
|
public const int ExampleCount = 10;
|
||||||
|
public const int MaxGroups = 500;
|
||||||
|
|
||||||
|
public async Task<IReadOnlyList<ObservedValue>> GetValuesAsync(ExplanationKind kind, DateTime? since, CancellationToken ct = default)
|
||||||
|
{
|
||||||
|
await using var db = await dbContextFactory.CreateDbContextAsync(ct);
|
||||||
|
var events = db.TrapEvents.AsNoTracking();
|
||||||
|
if (since is { } start)
|
||||||
|
{
|
||||||
|
events = events.Where(e => e.StartedAt >= start);
|
||||||
|
}
|
||||||
|
|
||||||
|
IEnumerable<ObservedValue> values;
|
||||||
|
switch (kind)
|
||||||
|
{
|
||||||
|
case ExplanationKind.Target:
|
||||||
|
var targets = await events.Where(e => e.Target != null).GroupBy(e => e.Target!)
|
||||||
|
.Select(g => new { g.Key, Count = g.Count(), First = g.Min(e => e.StartedAt), Last = g.Max(e => e.StartedAt), Agent = g.Max(e => e.ClientInfo) })
|
||||||
|
.ToListAsync(ct);
|
||||||
|
values = targets.Select(t => new ObservedValue(ExplanationText.Path(t.Key)!, t.Count, t.First, t.Last, t.Key, t.Agent));
|
||||||
|
break;
|
||||||
|
case ExplanationKind.ClientInfo:
|
||||||
|
var agents = await events.GroupBy(e => e.ClientInfo ?? "")
|
||||||
|
.Select(g => new { g.Key, Count = g.Count(), First = g.Min(e => e.StartedAt), Last = g.Max(e => e.StartedAt), Target = g.Max(e => e.Target) })
|
||||||
|
.ToListAsync(ct);
|
||||||
|
values = agents.Select(a => new ObservedValue(a.Key, a.Count, a.First, a.Last, a.Target, a.Key.Length == 0 ? null : a.Key));
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
var outcomes = await events.GroupBy(e => new { e.Outcome, Seconds = e.DurationMs / 1000 })
|
||||||
|
.Select(g => new { g.Key.Outcome, g.Key.Seconds, Count = g.Count(), First = g.Min(e => e.StartedAt), Last = g.Max(e => e.StartedAt), Target = g.Max(e => e.Target), Agent = g.Max(e => e.ClientInfo) })
|
||||||
|
.ToListAsync(ct);
|
||||||
|
values = outcomes.Select(o => new ObservedValue(ExplanationText.Outcome(o.Outcome, o.Seconds * 1000), o.Count, o.First, o.Last, o.Target, o.Agent));
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
return values
|
||||||
|
.GroupBy(v => v.Value)
|
||||||
|
.Select(g => new ObservedValue(
|
||||||
|
g.Key,
|
||||||
|
g.Sum(v => v.Catches),
|
||||||
|
g.Min(v => v.FirstSeen),
|
||||||
|
g.Max(v => v.LastSeen),
|
||||||
|
g.OrderByDescending(v => v.Catches).First().ExampleTarget,
|
||||||
|
g.Select(v => v.ExampleUserAgent).FirstOrDefault(a => a is not null)))
|
||||||
|
.ToList();
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<UnexplainedResult> FindUnexplainedAsync(DateTime? since, UnexplainedGrouping grouping, int limit, CancellationToken ct = default)
|
||||||
|
{
|
||||||
|
var rules = await store.GetRuleSetAsync(ct);
|
||||||
|
var unexplained = (await GetValuesAsync(ExplanationKind.Target, since, ct))
|
||||||
|
.Where(v => rules.Winner(ExplanationKind.Target, v.Value) is null)
|
||||||
|
.ToList();
|
||||||
|
|
||||||
|
var groups = unexplained
|
||||||
|
.GroupBy(v => grouping == UnexplainedGrouping.Path ? v.Value : ExplanationText.PathShape(v.Value))
|
||||||
|
.Select(g => new UnexplainedGroup(
|
||||||
|
g.Key,
|
||||||
|
g.Sum(v => v.Catches),
|
||||||
|
g.OrderByDescending(v => v.Catches).Take(3).Select(v => v.Value).ToList(),
|
||||||
|
g.OrderByDescending(v => v.Catches).Select(v => v.ExampleUserAgent).FirstOrDefault(a => a is not null),
|
||||||
|
g.Min(v => v.FirstSeen),
|
||||||
|
g.Max(v => v.LastSeen)))
|
||||||
|
.OrderByDescending(g => g.Catches)
|
||||||
|
.ThenBy(g => g.Key, StringComparer.Ordinal)
|
||||||
|
.ToList();
|
||||||
|
|
||||||
|
var take = Math.Clamp(limit, 1, MaxGroups);
|
||||||
|
return new UnexplainedResult(unexplained.Sum(v => v.Catches), unexplained.Count, groups.Take(take).ToList(), Math.Max(0, groups.Count - take));
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<RuleTestResult> TestAsync(ExplanationKind kind, string pattern, int priority, int? replacesRuleId, DateTime? since, CancellationToken ct = default)
|
||||||
|
{
|
||||||
|
var validPattern = ExplanationValidator.Pattern(pattern);
|
||||||
|
ExplanationValidator.Priority(priority);
|
||||||
|
|
||||||
|
var existing = (await store.ListAsync(ct)).Where(r => r.Enabled).ToList();
|
||||||
|
var candidateId = replacesRuleId ?? int.MaxValue;
|
||||||
|
var candidate = new ExplanationRuleEntity { Id = candidateId, Kind = kind, Pattern = validPattern, Text = "-", Priority = priority, CreatedBy = "test" };
|
||||||
|
var before = new RuleSet(existing);
|
||||||
|
var after = new RuleSet(existing.Where(r => r.Id != replacesRuleId).Append(candidate));
|
||||||
|
var candidateOnly = new RuleSet([candidate]);
|
||||||
|
|
||||||
|
var byId = existing.ToDictionary(r => r.Id);
|
||||||
|
var matched = new List<ObservedValue>();
|
||||||
|
var newly = 0;
|
||||||
|
var lost = 0;
|
||||||
|
var lostExamples = new List<string>();
|
||||||
|
var takeovers = new Dictionary<int, (int Catches, List<string> Examples)>();
|
||||||
|
|
||||||
|
foreach (var value in (await GetValuesAsync(kind, since, ct)).OrderByDescending(v => v.Catches))
|
||||||
|
{
|
||||||
|
var wasWinner = before.Winner(kind, value.Value);
|
||||||
|
var nowWinner = after.Winner(kind, value.Value);
|
||||||
|
var hit = candidateOnly.Winner(kind, value.Value) is not null;
|
||||||
|
if (hit)
|
||||||
|
{
|
||||||
|
matched.Add(value);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (nowWinner?.Id == candidateId)
|
||||||
|
{
|
||||||
|
if (wasWinner is null)
|
||||||
|
{
|
||||||
|
newly += value.Catches;
|
||||||
|
}
|
||||||
|
else if (wasWinner.Id != candidateId)
|
||||||
|
{
|
||||||
|
var (catches, examples) = takeovers.GetValueOrDefault(wasWinner.Id, (0, []));
|
||||||
|
if (examples.Count < ExampleCount)
|
||||||
|
{
|
||||||
|
examples.Add(value.Value);
|
||||||
|
}
|
||||||
|
|
||||||
|
takeovers[wasWinner.Id] = (catches + value.Catches, examples);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else if (wasWinner?.Id == candidateId && nowWinner is null)
|
||||||
|
{
|
||||||
|
lost += value.Catches;
|
||||||
|
if (lostExamples.Count < ExampleCount)
|
||||||
|
{
|
||||||
|
lostExamples.Add(value.Value);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return new RuleTestResult(
|
||||||
|
matched.Sum(v => v.Catches),
|
||||||
|
matched.Count,
|
||||||
|
matched.Take(ExampleCount).Select(v => (v.Value, v.Catches)).ToList(),
|
||||||
|
newly,
|
||||||
|
takeovers.OrderByDescending(t => t.Value.Catches).Select(t => new RuleTakeover(byId[t.Key], t.Value.Catches, t.Value.Examples)).ToList(),
|
||||||
|
lost,
|
||||||
|
lostExamples);
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<IReadOnlyDictionary<int, int>> CountHitsAsync(CancellationToken ct = default)
|
||||||
|
{
|
||||||
|
var rules = await store.ListAsync(ct);
|
||||||
|
var hits = rules.ToDictionary(r => r.Id, _ => 0);
|
||||||
|
foreach (var group in rules.GroupBy(r => r.Kind))
|
||||||
|
{
|
||||||
|
var set = new RuleSet(group);
|
||||||
|
foreach (var value in await GetValuesAsync(group.Key, null, ct))
|
||||||
|
{
|
||||||
|
foreach (var rule in set.Matching(group.Key, value.Value))
|
||||||
|
{
|
||||||
|
hits[rule.Id] += value.Catches;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return hits;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,156 @@
|
|||||||
|
using Flypaper.Storage.Entities;
|
||||||
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
|
||||||
|
namespace Flypaper.Storage.Explanations;
|
||||||
|
|
||||||
|
public sealed record ExplanationRuleInput(
|
||||||
|
ExplanationKind? Kind = null,
|
||||||
|
string? Pattern = null,
|
||||||
|
string? Text = null,
|
||||||
|
int? Priority = null,
|
||||||
|
string? Note = null);
|
||||||
|
|
||||||
|
public sealed class ExplanationRuleStore(IDbContextFactory<FlypaperDbContext> dbContextFactory, TimeProvider timeProvider)
|
||||||
|
{
|
||||||
|
public const string DashboardActor = "Dashboard";
|
||||||
|
|
||||||
|
private readonly object _gate = new();
|
||||||
|
private RuleSet? _cached;
|
||||||
|
private int _version;
|
||||||
|
|
||||||
|
public async Task<RuleSet> GetRuleSetAsync(CancellationToken ct = default)
|
||||||
|
{
|
||||||
|
int version;
|
||||||
|
lock (_gate)
|
||||||
|
{
|
||||||
|
if (_cached is { } cached)
|
||||||
|
{
|
||||||
|
return cached;
|
||||||
|
}
|
||||||
|
|
||||||
|
version = _version;
|
||||||
|
}
|
||||||
|
|
||||||
|
var rules = new RuleSet((await ListAsync(ct)).Where(r => r.Enabled));
|
||||||
|
lock (_gate)
|
||||||
|
{
|
||||||
|
if (version == _version)
|
||||||
|
{
|
||||||
|
_cached = rules;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return rules;
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<IReadOnlyList<ExplanationRuleEntity>> ListAsync(CancellationToken ct = default)
|
||||||
|
{
|
||||||
|
await using var db = await dbContextFactory.CreateDbContextAsync(ct);
|
||||||
|
return await db.ExplanationRules.AsNoTracking().OrderBy(r => r.Kind).ThenByDescending(r => r.Priority).ThenBy(r => r.Id).ToListAsync(ct);
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<ExplanationRuleEntity?> GetAsync(int id, CancellationToken ct = default)
|
||||||
|
{
|
||||||
|
await using var db = await dbContextFactory.CreateDbContextAsync(ct);
|
||||||
|
return await db.ExplanationRules.AsNoTracking().FirstOrDefaultAsync(r => r.Id == id, ct);
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<ExplanationRuleEntity> CreateAsync(ExplanationRuleInput input, string createdBy, CancellationToken ct = default)
|
||||||
|
{
|
||||||
|
var rule = new ExplanationRuleEntity
|
||||||
|
{
|
||||||
|
Kind = input.Kind ?? throw new ArgumentException("The kind is required."),
|
||||||
|
Pattern = ExplanationValidator.Pattern(input.Pattern),
|
||||||
|
Text = ExplanationValidator.Text(input.Text),
|
||||||
|
Priority = ExplanationValidator.Priority(input.Priority ?? 0),
|
||||||
|
Note = ExplanationValidator.Note(input.Note),
|
||||||
|
CreatedBy = createdBy.Length > ExplanationLimits.MaxCreatedByLength ? createdBy[..ExplanationLimits.MaxCreatedByLength] : createdBy,
|
||||||
|
CreatedAt = timeProvider.GetUtcNow().UtcDateTime
|
||||||
|
};
|
||||||
|
rule.UpdatedAt = rule.CreatedAt;
|
||||||
|
|
||||||
|
await using var db = await dbContextFactory.CreateDbContextAsync(ct);
|
||||||
|
if (await db.ExplanationRules.CountAsync(ct) >= ExplanationLimits.MaxRules)
|
||||||
|
{
|
||||||
|
throw new ArgumentException($"There are already {ExplanationLimits.MaxRules} rules; delete unused ones first.");
|
||||||
|
}
|
||||||
|
|
||||||
|
db.ExplanationRules.Add(rule);
|
||||||
|
await db.SaveChangesAsync(ct);
|
||||||
|
Invalidate();
|
||||||
|
return rule;
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<ExplanationRuleEntity?> UpdateAsync(int id, ExplanationRuleInput input, CancellationToken ct = default)
|
||||||
|
{
|
||||||
|
await using var db = await dbContextFactory.CreateDbContextAsync(ct);
|
||||||
|
var rule = await db.ExplanationRules.FirstOrDefaultAsync(r => r.Id == id, ct);
|
||||||
|
if (rule is null)
|
||||||
|
{
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (input.Kind is { } kind)
|
||||||
|
{
|
||||||
|
rule.Kind = kind;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (input.Pattern is not null)
|
||||||
|
{
|
||||||
|
rule.Pattern = ExplanationValidator.Pattern(input.Pattern);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (input.Text is not null)
|
||||||
|
{
|
||||||
|
rule.Text = ExplanationValidator.Text(input.Text);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (input.Priority is { } priority)
|
||||||
|
{
|
||||||
|
rule.Priority = ExplanationValidator.Priority(priority);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (input.Note is not null)
|
||||||
|
{
|
||||||
|
rule.Note = ExplanationValidator.Note(input.Note);
|
||||||
|
}
|
||||||
|
|
||||||
|
rule.UpdatedAt = timeProvider.GetUtcNow().UtcDateTime;
|
||||||
|
await db.SaveChangesAsync(ct);
|
||||||
|
Invalidate();
|
||||||
|
return rule;
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<ExplanationRuleEntity?> SetEnabledAsync(int id, bool enabled, CancellationToken ct = default)
|
||||||
|
{
|
||||||
|
await using var db = await dbContextFactory.CreateDbContextAsync(ct);
|
||||||
|
var rule = await db.ExplanationRules.FirstOrDefaultAsync(r => r.Id == id, ct);
|
||||||
|
if (rule is null)
|
||||||
|
{
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
rule.Enabled = enabled;
|
||||||
|
rule.UpdatedAt = timeProvider.GetUtcNow().UtcDateTime;
|
||||||
|
await db.SaveChangesAsync(ct);
|
||||||
|
Invalidate();
|
||||||
|
return rule;
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<bool> DeleteAsync(int id, CancellationToken ct = default)
|
||||||
|
{
|
||||||
|
await using var db = await dbContextFactory.CreateDbContextAsync(ct);
|
||||||
|
var deleted = await db.ExplanationRules.Where(r => r.Id == id).ExecuteDeleteAsync(ct) > 0;
|
||||||
|
Invalidate();
|
||||||
|
return deleted;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void Invalidate()
|
||||||
|
{
|
||||||
|
lock (_gate)
|
||||||
|
{
|
||||||
|
_version++;
|
||||||
|
_cached = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,54 @@
|
|||||||
|
using System.Text.RegularExpressions;
|
||||||
|
using Flypaper.Core.Models;
|
||||||
|
using Flypaper.Storage.Entities;
|
||||||
|
|
||||||
|
namespace Flypaper.Storage.Explanations;
|
||||||
|
|
||||||
|
public static partial class ExplanationText
|
||||||
|
{
|
||||||
|
[GeneratedRegex("[0-9a-fA-F]{8,}")]
|
||||||
|
private static partial Regex LongHex();
|
||||||
|
|
||||||
|
[GeneratedRegex("[0-9]+")]
|
||||||
|
private static partial Regex Digits();
|
||||||
|
|
||||||
|
public static string? Path(string? target)
|
||||||
|
{
|
||||||
|
if (target is null)
|
||||||
|
{
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
var space = target.IndexOf(' ');
|
||||||
|
if (space < 0)
|
||||||
|
{
|
||||||
|
return target;
|
||||||
|
}
|
||||||
|
|
||||||
|
var hostAndPath = target[(space + 1)..];
|
||||||
|
if (hostAndPath.StartsWith('/'))
|
||||||
|
{
|
||||||
|
return hostAndPath;
|
||||||
|
}
|
||||||
|
|
||||||
|
var slash = hostAndPath.IndexOf('/');
|
||||||
|
return slash < 0 ? "/" : hostAndPath[slash..];
|
||||||
|
}
|
||||||
|
|
||||||
|
public static string Outcome(TrapOutcome outcome, long durationMs) =>
|
||||||
|
outcome == TrapOutcome.Rejected ? outcome.ToString() : $"{outcome} {durationMs / 1000}s";
|
||||||
|
|
||||||
|
public static string Value(ExplanationKind kind, TrapEventEntity trapEvent) => kind switch
|
||||||
|
{
|
||||||
|
ExplanationKind.Target => Path(trapEvent.Target) ?? "",
|
||||||
|
ExplanationKind.ClientInfo => trapEvent.ClientInfo ?? "",
|
||||||
|
_ => Outcome(trapEvent.Outcome, trapEvent.DurationMs)
|
||||||
|
};
|
||||||
|
|
||||||
|
public static string PathShape(string path)
|
||||||
|
{
|
||||||
|
var query = path.IndexOf('?');
|
||||||
|
var bare = query < 0 ? path : path[..query];
|
||||||
|
return Digits().Replace(LongHex().Replace(bare, "{hex}"), "{n}");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,82 @@
|
|||||||
|
using System.Text.RegularExpressions;
|
||||||
|
|
||||||
|
namespace Flypaper.Storage.Explanations;
|
||||||
|
|
||||||
|
public static class ExplanationValidator
|
||||||
|
{
|
||||||
|
public static readonly TimeSpan MatchTimeout = TimeSpan.FromMilliseconds(250);
|
||||||
|
|
||||||
|
public static Regex Compile(string pattern) =>
|
||||||
|
new(pattern, RegexOptions.NonBacktracking | RegexOptions.IgnoreCase | RegexOptions.CultureInvariant, MatchTimeout);
|
||||||
|
|
||||||
|
public static string Pattern(string? pattern)
|
||||||
|
{
|
||||||
|
var value = pattern?.Trim();
|
||||||
|
if (string.IsNullOrEmpty(value))
|
||||||
|
{
|
||||||
|
throw new ArgumentException("The pattern must not be empty.");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (value.Length > ExplanationLimits.MaxPatternLength)
|
||||||
|
{
|
||||||
|
throw new ArgumentException($"The pattern must have at most {ExplanationLimits.MaxPatternLength} characters.");
|
||||||
|
}
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
Compile(value);
|
||||||
|
}
|
||||||
|
catch (ArgumentException exception)
|
||||||
|
{
|
||||||
|
throw new ArgumentException($"The pattern is not a valid regular expression: {exception.Message}");
|
||||||
|
}
|
||||||
|
catch (NotSupportedException exception)
|
||||||
|
{
|
||||||
|
throw new ArgumentException($"The pattern uses a feature that is not supported (no lookarounds, backreferences or atomic groups): {exception.Message}");
|
||||||
|
}
|
||||||
|
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static string Text(string? text)
|
||||||
|
{
|
||||||
|
var value = text?.Trim();
|
||||||
|
if (string.IsNullOrEmpty(value))
|
||||||
|
{
|
||||||
|
throw new ArgumentException("The text must not be empty.");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (value.Length > ExplanationLimits.MaxTextLength)
|
||||||
|
{
|
||||||
|
throw new ArgumentException($"The text must have at most {ExplanationLimits.MaxTextLength} characters.");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (value.Any(char.IsControl))
|
||||||
|
{
|
||||||
|
throw new ArgumentException("The text must be plain text without line breaks or control characters.");
|
||||||
|
}
|
||||||
|
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static string? Note(string? note)
|
||||||
|
{
|
||||||
|
var value = note?.Trim();
|
||||||
|
if (string.IsNullOrEmpty(value))
|
||||||
|
{
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (value.Length > ExplanationLimits.MaxNoteLength)
|
||||||
|
{
|
||||||
|
throw new ArgumentException($"The note must have at most {ExplanationLimits.MaxNoteLength} characters.");
|
||||||
|
}
|
||||||
|
|
||||||
|
return value.Any(char.IsControl) ? throw new ArgumentException("The note must be plain text without control characters.") : value;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static int Priority(int priority) =>
|
||||||
|
Math.Abs(priority) <= ExplanationLimits.MaxPriority
|
||||||
|
? priority
|
||||||
|
: throw new ArgumentException($"The priority must be between -{ExplanationLimits.MaxPriority} and {ExplanationLimits.MaxPriority}.");
|
||||||
|
}
|
||||||
@@ -0,0 +1,77 @@
|
|||||||
|
using System.Text.RegularExpressions;
|
||||||
|
using Flypaper.Storage.Entities;
|
||||||
|
|
||||||
|
namespace Flypaper.Storage.Explanations;
|
||||||
|
|
||||||
|
public sealed record Explanation(ExplanationRuleEntity? Target, ExplanationRuleEntity? Client, ExplanationRuleEntity? Outcome)
|
||||||
|
{
|
||||||
|
public bool HasTarget => Target is not null;
|
||||||
|
}
|
||||||
|
|
||||||
|
public sealed class RuleSet
|
||||||
|
{
|
||||||
|
public static readonly RuleSet Empty = new([]);
|
||||||
|
|
||||||
|
private readonly IReadOnlyDictionary<ExplanationKind, IReadOnlyList<(ExplanationRuleEntity Rule, Regex Regex)>> _byKind;
|
||||||
|
|
||||||
|
public RuleSet(IEnumerable<ExplanationRuleEntity> rules)
|
||||||
|
{
|
||||||
|
var compiled = new Dictionary<ExplanationKind, List<(ExplanationRuleEntity, Regex)>>();
|
||||||
|
foreach (var rule in rules.OrderByDescending(r => r.Priority).ThenBy(r => r.Id))
|
||||||
|
{
|
||||||
|
Regex regex;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
regex = ExplanationValidator.Compile(rule.Pattern);
|
||||||
|
}
|
||||||
|
catch (Exception exception) when (exception is ArgumentException or NotSupportedException)
|
||||||
|
{
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!compiled.TryGetValue(rule.Kind, out var list))
|
||||||
|
{
|
||||||
|
compiled[rule.Kind] = list = [];
|
||||||
|
}
|
||||||
|
|
||||||
|
list.Add((rule, regex));
|
||||||
|
}
|
||||||
|
|
||||||
|
_byKind = compiled.ToDictionary(p => p.Key, p => (IReadOnlyList<(ExplanationRuleEntity, Regex)>)p.Value);
|
||||||
|
}
|
||||||
|
|
||||||
|
public ExplanationRuleEntity? Winner(ExplanationKind kind, string value) => Matching(kind, value).FirstOrDefault();
|
||||||
|
|
||||||
|
public IEnumerable<ExplanationRuleEntity> Matching(ExplanationKind kind, string value)
|
||||||
|
{
|
||||||
|
if (!_byKind.TryGetValue(kind, out var rules))
|
||||||
|
{
|
||||||
|
yield break;
|
||||||
|
}
|
||||||
|
|
||||||
|
foreach (var (rule, regex) in rules)
|
||||||
|
{
|
||||||
|
if (IsMatch(regex, value))
|
||||||
|
{
|
||||||
|
yield return rule;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public Explanation Explain(TrapEventEntity trapEvent) => new(
|
||||||
|
trapEvent.Target is null ? null : Winner(ExplanationKind.Target, ExplanationText.Value(ExplanationKind.Target, trapEvent)),
|
||||||
|
Winner(ExplanationKind.ClientInfo, ExplanationText.Value(ExplanationKind.ClientInfo, trapEvent)),
|
||||||
|
Winner(ExplanationKind.Outcome, ExplanationText.Value(ExplanationKind.Outcome, trapEvent)));
|
||||||
|
|
||||||
|
private static bool IsMatch(Regex regex, string value)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
return regex.IsMatch(value);
|
||||||
|
}
|
||||||
|
catch (RegexMatchTimeoutException)
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,4 +1,5 @@
|
|||||||
using Flypaper.Storage.Entities;
|
using Flypaper.Storage.Entities;
|
||||||
|
using Flypaper.Storage.Explanations;
|
||||||
using Microsoft.EntityFrameworkCore;
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
|
||||||
namespace Flypaper.Storage;
|
namespace Flypaper.Storage;
|
||||||
@@ -14,6 +15,8 @@ public sealed class FlypaperDbContext(DbContextOptions<FlypaperDbContext> option
|
|||||||
|
|
||||||
public DbSet<McpTokenEntity> McpTokens => Set<McpTokenEntity>();
|
public DbSet<McpTokenEntity> McpTokens => Set<McpTokenEntity>();
|
||||||
|
|
||||||
|
public DbSet<ExplanationRuleEntity> ExplanationRules => Set<ExplanationRuleEntity>();
|
||||||
|
|
||||||
protected override void ConfigureConventions(ModelConfigurationBuilder configurationBuilder) =>
|
protected override void ConfigureConventions(ModelConfigurationBuilder configurationBuilder) =>
|
||||||
configurationBuilder.Properties<DateTime>().HaveConversion<UtcDateTimeConverter>();
|
configurationBuilder.Properties<DateTime>().HaveConversion<UtcDateTimeConverter>();
|
||||||
|
|
||||||
@@ -43,5 +46,12 @@ public sealed class FlypaperDbContext(DbContextOptions<FlypaperDbContext> option
|
|||||||
mcpToken.Property(e => e.Name).HasMaxLength(100);
|
mcpToken.Property(e => e.Name).HasMaxLength(100);
|
||||||
mcpToken.Property(e => e.TokenHash).HasMaxLength(64);
|
mcpToken.Property(e => e.TokenHash).HasMaxLength(64);
|
||||||
mcpToken.HasIndex(e => e.TokenHash).IsUnique();
|
mcpToken.HasIndex(e => e.TokenHash).IsUnique();
|
||||||
|
|
||||||
|
var explanationRule = modelBuilder.Entity<ExplanationRuleEntity>();
|
||||||
|
explanationRule.Property(e => e.Kind).HasConversion<string>().HasMaxLength(16);
|
||||||
|
explanationRule.Property(e => e.Pattern).HasMaxLength(ExplanationLimits.MaxPatternLength);
|
||||||
|
explanationRule.Property(e => e.Text).HasMaxLength(ExplanationLimits.MaxTextLength);
|
||||||
|
explanationRule.Property(e => e.Note).HasMaxLength(ExplanationLimits.MaxNoteLength);
|
||||||
|
explanationRule.Property(e => e.CreatedBy).HasMaxLength(ExplanationLimits.MaxCreatedByLength);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
using Flypaper.Core.Abstractions;
|
using Flypaper.Core.Abstractions;
|
||||||
using Flypaper.Storage.Dashboard;
|
using Flypaper.Storage.Dashboard;
|
||||||
using Flypaper.Storage.Events;
|
using Flypaper.Storage.Events;
|
||||||
|
using Flypaper.Storage.Explanations;
|
||||||
using Flypaper.Storage.Maintenance;
|
using Flypaper.Storage.Maintenance;
|
||||||
using Flypaper.Storage.Queries;
|
using Flypaper.Storage.Queries;
|
||||||
using Flypaper.Storage.Settings;
|
using Flypaper.Storage.Settings;
|
||||||
@@ -36,9 +37,12 @@ public static class FlypaperStorageExtensions
|
|||||||
services.AddSingleton<ITrapEventSink>(sp => sp.GetRequiredService<ChannelTrapEventSink>());
|
services.AddSingleton<ITrapEventSink>(sp => sp.GetRequiredService<ChannelTrapEventSink>());
|
||||||
services.AddHostedService<TrapEventWriter>();
|
services.AddHostedService<TrapEventWriter>();
|
||||||
services.AddHostedService<OriginBackfill>();
|
services.AddHostedService<OriginBackfill>();
|
||||||
|
services.AddSingleton<ExplanationRuleStore>();
|
||||||
|
services.AddSingleton<ExplanationQueries>();
|
||||||
services.AddSingleton<DashboardQueries>();
|
services.AddSingleton<DashboardQueries>();
|
||||||
services.AddSingleton<CatchQueries>();
|
services.AddSingleton<CatchQueries>();
|
||||||
services.AddSingleton<IRepeatOffenderLookup, RepeatOffenderLookup>();
|
services.AddSingleton<IRepeatOffenderLookup, RepeatOffenderLookup>();
|
||||||
|
services.AddSingleton<IKnownIpLookup, KnownIpLookup>();
|
||||||
services.AddSingleton<TrapDataMaintenance>();
|
services.AddSingleton<TrapDataMaintenance>();
|
||||||
services.AddHostedService<RetentionCleanup>();
|
services.AddHostedService<RetentionCleanup>();
|
||||||
return services;
|
return services;
|
||||||
|
|||||||
Generated
+201
@@ -0,0 +1,201 @@
|
|||||||
|
// <auto-generated />
|
||||||
|
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("20261121103849_AddExplanationRulesAndTokenWrite")]
|
||||||
|
partial class AddExplanationRulesAndTokenWrite
|
||||||
|
{
|
||||||
|
/// <inheritdoc />
|
||||||
|
protected override void BuildTargetModel(ModelBuilder modelBuilder)
|
||||||
|
{
|
||||||
|
#pragma warning disable 612, 618
|
||||||
|
modelBuilder.HasAnnotation("ProductVersion", "10.0.15");
|
||||||
|
|
||||||
|
modelBuilder.Entity("Flypaper.Storage.Entities.ExplanationRuleEntity", b =>
|
||||||
|
{
|
||||||
|
b.Property<int>("Id")
|
||||||
|
.ValueGeneratedOnAdd()
|
||||||
|
.HasColumnType("INTEGER");
|
||||||
|
|
||||||
|
b.Property<DateTime>("CreatedAt")
|
||||||
|
.HasColumnType("TEXT");
|
||||||
|
|
||||||
|
b.Property<string>("CreatedBy")
|
||||||
|
.IsRequired()
|
||||||
|
.HasMaxLength(100)
|
||||||
|
.HasColumnType("TEXT");
|
||||||
|
|
||||||
|
b.Property<bool>("Enabled")
|
||||||
|
.HasColumnType("INTEGER");
|
||||||
|
|
||||||
|
b.Property<string>("Kind")
|
||||||
|
.IsRequired()
|
||||||
|
.HasMaxLength(16)
|
||||||
|
.HasColumnType("TEXT");
|
||||||
|
|
||||||
|
b.Property<string>("Note")
|
||||||
|
.HasMaxLength(500)
|
||||||
|
.HasColumnType("TEXT");
|
||||||
|
|
||||||
|
b.Property<string>("Pattern")
|
||||||
|
.IsRequired()
|
||||||
|
.HasMaxLength(500)
|
||||||
|
.HasColumnType("TEXT");
|
||||||
|
|
||||||
|
b.Property<int>("Priority")
|
||||||
|
.HasColumnType("INTEGER");
|
||||||
|
|
||||||
|
b.Property<string>("Text")
|
||||||
|
.IsRequired()
|
||||||
|
.HasMaxLength(600)
|
||||||
|
.HasColumnType("TEXT");
|
||||||
|
|
||||||
|
b.Property<DateTime>("UpdatedAt")
|
||||||
|
.HasColumnType("TEXT");
|
||||||
|
|
||||||
|
b.HasKey("Id");
|
||||||
|
|
||||||
|
b.ToTable("ExplanationRules");
|
||||||
|
});
|
||||||
|
|
||||||
|
modelBuilder.Entity("Flypaper.Storage.Entities.McpTokenEntity", b =>
|
||||||
|
{
|
||||||
|
b.Property<int>("Id")
|
||||||
|
.ValueGeneratedOnAdd()
|
||||||
|
.HasColumnType("INTEGER");
|
||||||
|
|
||||||
|
b.Property<bool>("CanWrite")
|
||||||
|
.HasColumnType("INTEGER");
|
||||||
|
|
||||||
|
b.Property<DateTime>("CreatedAt")
|
||||||
|
.HasColumnType("TEXT");
|
||||||
|
|
||||||
|
b.Property<DateTime?>("LastUsedAt")
|
||||||
|
.HasColumnType("TEXT");
|
||||||
|
|
||||||
|
b.Property<string>("Name")
|
||||||
|
.IsRequired()
|
||||||
|
.HasMaxLength(100)
|
||||||
|
.HasColumnType("TEXT");
|
||||||
|
|
||||||
|
b.Property<string>("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<string>("Key")
|
||||||
|
.HasMaxLength(128)
|
||||||
|
.HasColumnType("TEXT");
|
||||||
|
|
||||||
|
b.Property<string>("Value")
|
||||||
|
.IsRequired()
|
||||||
|
.HasColumnType("TEXT");
|
||||||
|
|
||||||
|
b.HasKey("Key");
|
||||||
|
|
||||||
|
b.ToTable("Settings");
|
||||||
|
});
|
||||||
|
|
||||||
|
modelBuilder.Entity("Flypaper.Storage.Entities.TrapEventEntity", b =>
|
||||||
|
{
|
||||||
|
b.Property<long>("Id")
|
||||||
|
.ValueGeneratedOnAdd()
|
||||||
|
.HasColumnType("INTEGER");
|
||||||
|
|
||||||
|
b.Property<long?>("Asn")
|
||||||
|
.HasColumnType("INTEGER");
|
||||||
|
|
||||||
|
b.Property<long>("BytesSent")
|
||||||
|
.HasColumnType("INTEGER");
|
||||||
|
|
||||||
|
b.Property<string>("City")
|
||||||
|
.HasMaxLength(256)
|
||||||
|
.HasColumnType("TEXT");
|
||||||
|
|
||||||
|
b.Property<string>("ClientInfo")
|
||||||
|
.HasMaxLength(2048)
|
||||||
|
.HasColumnType("TEXT");
|
||||||
|
|
||||||
|
b.Property<string>("Country")
|
||||||
|
.HasMaxLength(256)
|
||||||
|
.HasColumnType("TEXT");
|
||||||
|
|
||||||
|
b.Property<string>("CountryCode")
|
||||||
|
.HasMaxLength(2)
|
||||||
|
.HasColumnType("TEXT");
|
||||||
|
|
||||||
|
b.Property<long>("DurationMs")
|
||||||
|
.HasColumnType("INTEGER");
|
||||||
|
|
||||||
|
b.Property<DateTime>("EndedAt")
|
||||||
|
.HasColumnType("TEXT");
|
||||||
|
|
||||||
|
b.Property<string>("Outcome")
|
||||||
|
.IsRequired()
|
||||||
|
.HasMaxLength(16)
|
||||||
|
.HasColumnType("TEXT");
|
||||||
|
|
||||||
|
b.Property<string>("Protocol")
|
||||||
|
.IsRequired()
|
||||||
|
.HasMaxLength(16)
|
||||||
|
.HasColumnType("TEXT");
|
||||||
|
|
||||||
|
b.Property<string>("Provider")
|
||||||
|
.HasMaxLength(256)
|
||||||
|
.HasColumnType("TEXT");
|
||||||
|
|
||||||
|
b.Property<string>("RemoteIp")
|
||||||
|
.IsRequired()
|
||||||
|
.HasMaxLength(64)
|
||||||
|
.HasColumnType("TEXT");
|
||||||
|
|
||||||
|
b.Property<Guid>("SessionId")
|
||||||
|
.HasColumnType("TEXT");
|
||||||
|
|
||||||
|
b.Property<DateTime>("StartedAt")
|
||||||
|
.HasColumnType("TEXT");
|
||||||
|
|
||||||
|
b.Property<string>("Strategy")
|
||||||
|
.IsRequired()
|
||||||
|
.HasMaxLength(64)
|
||||||
|
.HasColumnType("TEXT");
|
||||||
|
|
||||||
|
b.Property<string>("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
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,54 @@
|
|||||||
|
using System;
|
||||||
|
using Microsoft.EntityFrameworkCore.Migrations;
|
||||||
|
|
||||||
|
#nullable disable
|
||||||
|
|
||||||
|
namespace Flypaper.Storage.Migrations
|
||||||
|
{
|
||||||
|
/// <inheritdoc />
|
||||||
|
public partial class AddExplanationRulesAndTokenWrite : Migration
|
||||||
|
{
|
||||||
|
/// <inheritdoc />
|
||||||
|
protected override void Up(MigrationBuilder migrationBuilder)
|
||||||
|
{
|
||||||
|
migrationBuilder.AddColumn<bool>(
|
||||||
|
name: "CanWrite",
|
||||||
|
table: "McpTokens",
|
||||||
|
type: "INTEGER",
|
||||||
|
nullable: false,
|
||||||
|
defaultValue: false);
|
||||||
|
|
||||||
|
migrationBuilder.CreateTable(
|
||||||
|
name: "ExplanationRules",
|
||||||
|
columns: table => new
|
||||||
|
{
|
||||||
|
Id = table.Column<int>(type: "INTEGER", nullable: false)
|
||||||
|
.Annotation("Sqlite:Autoincrement", true),
|
||||||
|
Kind = table.Column<string>(type: "TEXT", maxLength: 16, nullable: false),
|
||||||
|
Pattern = table.Column<string>(type: "TEXT", maxLength: 500, nullable: false),
|
||||||
|
Text = table.Column<string>(type: "TEXT", maxLength: 600, nullable: false),
|
||||||
|
Priority = table.Column<int>(type: "INTEGER", nullable: false),
|
||||||
|
Enabled = table.Column<bool>(type: "INTEGER", nullable: false),
|
||||||
|
Note = table.Column<string>(type: "TEXT", maxLength: 500, nullable: true),
|
||||||
|
CreatedAt = table.Column<DateTime>(type: "TEXT", nullable: false),
|
||||||
|
UpdatedAt = table.Column<DateTime>(type: "TEXT", nullable: false),
|
||||||
|
CreatedBy = table.Column<string>(type: "TEXT", maxLength: 100, nullable: false)
|
||||||
|
},
|
||||||
|
constraints: table =>
|
||||||
|
{
|
||||||
|
table.PrimaryKey("PK_ExplanationRules", x => x.Id);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
protected override void Down(MigrationBuilder migrationBuilder)
|
||||||
|
{
|
||||||
|
migrationBuilder.DropTable(
|
||||||
|
name: "ExplanationRules");
|
||||||
|
|
||||||
|
migrationBuilder.DropColumn(
|
||||||
|
name: "CanWrite",
|
||||||
|
table: "McpTokens");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -17,12 +17,62 @@ namespace Flypaper.Storage.Migrations
|
|||||||
#pragma warning disable 612, 618
|
#pragma warning disable 612, 618
|
||||||
modelBuilder.HasAnnotation("ProductVersion", "10.0.15");
|
modelBuilder.HasAnnotation("ProductVersion", "10.0.15");
|
||||||
|
|
||||||
|
modelBuilder.Entity("Flypaper.Storage.Entities.ExplanationRuleEntity", b =>
|
||||||
|
{
|
||||||
|
b.Property<int>("Id")
|
||||||
|
.ValueGeneratedOnAdd()
|
||||||
|
.HasColumnType("INTEGER");
|
||||||
|
|
||||||
|
b.Property<DateTime>("CreatedAt")
|
||||||
|
.HasColumnType("TEXT");
|
||||||
|
|
||||||
|
b.Property<string>("CreatedBy")
|
||||||
|
.IsRequired()
|
||||||
|
.HasMaxLength(100)
|
||||||
|
.HasColumnType("TEXT");
|
||||||
|
|
||||||
|
b.Property<bool>("Enabled")
|
||||||
|
.HasColumnType("INTEGER");
|
||||||
|
|
||||||
|
b.Property<string>("Kind")
|
||||||
|
.IsRequired()
|
||||||
|
.HasMaxLength(16)
|
||||||
|
.HasColumnType("TEXT");
|
||||||
|
|
||||||
|
b.Property<string>("Note")
|
||||||
|
.HasMaxLength(500)
|
||||||
|
.HasColumnType("TEXT");
|
||||||
|
|
||||||
|
b.Property<string>("Pattern")
|
||||||
|
.IsRequired()
|
||||||
|
.HasMaxLength(500)
|
||||||
|
.HasColumnType("TEXT");
|
||||||
|
|
||||||
|
b.Property<int>("Priority")
|
||||||
|
.HasColumnType("INTEGER");
|
||||||
|
|
||||||
|
b.Property<string>("Text")
|
||||||
|
.IsRequired()
|
||||||
|
.HasMaxLength(600)
|
||||||
|
.HasColumnType("TEXT");
|
||||||
|
|
||||||
|
b.Property<DateTime>("UpdatedAt")
|
||||||
|
.HasColumnType("TEXT");
|
||||||
|
|
||||||
|
b.HasKey("Id");
|
||||||
|
|
||||||
|
b.ToTable("ExplanationRules");
|
||||||
|
});
|
||||||
|
|
||||||
modelBuilder.Entity("Flypaper.Storage.Entities.McpTokenEntity", b =>
|
modelBuilder.Entity("Flypaper.Storage.Entities.McpTokenEntity", b =>
|
||||||
{
|
{
|
||||||
b.Property<int>("Id")
|
b.Property<int>("Id")
|
||||||
.ValueGeneratedOnAdd()
|
.ValueGeneratedOnAdd()
|
||||||
.HasColumnType("INTEGER");
|
.HasColumnType("INTEGER");
|
||||||
|
|
||||||
|
b.Property<bool>("CanWrite")
|
||||||
|
.HasColumnType("INTEGER");
|
||||||
|
|
||||||
b.Property<DateTime>("CreatedAt")
|
b.Property<DateTime>("CreatedAt")
|
||||||
.HasColumnType("TEXT");
|
.HasColumnType("TEXT");
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,15 @@
|
|||||||
|
using System.Net;
|
||||||
|
using Flypaper.Core.Abstractions;
|
||||||
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
|
||||||
|
namespace Flypaper.Storage.Queries;
|
||||||
|
|
||||||
|
public sealed class KnownIpLookup(IDbContextFactory<FlypaperDbContext> dbContextFactory) : IKnownIpLookup
|
||||||
|
{
|
||||||
|
public async ValueTask<bool> HasSeenAsync(IPAddress address, CancellationToken ct)
|
||||||
|
{
|
||||||
|
var ip = address.ToString();
|
||||||
|
await using var db = await dbContextFactory.CreateDbContextAsync(ct);
|
||||||
|
return await db.TrapEvents.AnyAsync(e => e.RemoteIp == ip, ct);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -13,10 +13,10 @@ public sealed class McpTokenStore(IDbContextFactory<FlypaperDbContext> dbContext
|
|||||||
return await db.McpTokens.AsNoTracking().OrderBy(t => t.Id).ToListAsync(ct);
|
return await db.McpTokens.AsNoTracking().OrderBy(t => t.Id).ToListAsync(ct);
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task<McpTokenEntity> CreateAsync(string name, string tokenHash, CancellationToken ct = default)
|
public async Task<McpTokenEntity> CreateAsync(string name, string tokenHash, bool canWrite = false, CancellationToken ct = default)
|
||||||
{
|
{
|
||||||
await using var db = await dbContextFactory.CreateDbContextAsync(ct);
|
await using var db = await dbContextFactory.CreateDbContextAsync(ct);
|
||||||
var token = new McpTokenEntity { Name = name, TokenHash = tokenHash, CreatedAt = timeProvider.GetUtcNow().UtcDateTime };
|
var token = new McpTokenEntity { Name = name, TokenHash = tokenHash, CanWrite = canWrite, CreatedAt = timeProvider.GetUtcNow().UtcDateTime };
|
||||||
db.McpTokens.Add(token);
|
db.McpTokens.Add(token);
|
||||||
await db.SaveChangesAsync(ct);
|
await db.SaveChangesAsync(ct);
|
||||||
return token;
|
return token;
|
||||||
@@ -28,6 +28,12 @@ public sealed class McpTokenStore(IDbContextFactory<FlypaperDbContext> dbContext
|
|||||||
return await db.McpTokens.Where(t => t.Id == id).ExecuteDeleteAsync(ct) > 0;
|
return await db.McpTokens.Where(t => t.Id == id).ExecuteDeleteAsync(ct) > 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public async Task<bool> SetCanWriteAsync(int id, bool canWrite, CancellationToken ct = default)
|
||||||
|
{
|
||||||
|
await using var db = await dbContextFactory.CreateDbContextAsync(ct);
|
||||||
|
return await db.McpTokens.Where(t => t.Id == id).ExecuteUpdateAsync(set => set.SetProperty(t => t.CanWrite, canWrite), ct) > 0;
|
||||||
|
}
|
||||||
|
|
||||||
public async Task<McpTokenEntity?> UseAsync(string tokenHash, CancellationToken ct = default)
|
public async Task<McpTokenEntity?> UseAsync(string tokenHash, CancellationToken ct = default)
|
||||||
{
|
{
|
||||||
await using var db = await dbContextFactory.CreateDbContextAsync(ct);
|
await using var db = await dbContextFactory.CreateDbContextAsync(ct);
|
||||||
|
|||||||
@@ -4,6 +4,7 @@
|
|||||||
<nav class="nav">
|
<nav class="nav">
|
||||||
<a href="/" class="brand"><span class="brand-mark" aria-hidden="true"></span>Flypaper</a>
|
<a href="/" class="brand"><span class="brand-mark" aria-hidden="true"></span>Flypaper</a>
|
||||||
<NavLink href="/" Match="NavLinkMatch.All">Dashboard</NavLink>
|
<NavLink href="/" Match="NavLinkMatch.All">Dashboard</NavLink>
|
||||||
|
<NavLink href="/erklaerungen">Erklärungen</NavLink>
|
||||||
<NavLink href="/settings">Einstellungen</NavLink>
|
<NavLink href="/settings">Einstellungen</NavLink>
|
||||||
<form method="post" action="/auth/logout" class="logout">
|
<form method="post" action="/auth/logout" class="logout">
|
||||||
<AntiforgeryToken />
|
<AntiforgeryToken />
|
||||||
|
|||||||
@@ -15,7 +15,8 @@ public sealed record DashboardFilter(
|
|||||||
string? Ziel = null,
|
string? Ziel = null,
|
||||||
string? Strategie = null,
|
string? Strategie = null,
|
||||||
string? Q = null,
|
string? Q = null,
|
||||||
int Limit = RecentFilter.DefaultLimit)
|
int Limit = RecentFilter.DefaultLimit,
|
||||||
|
string? Erklaerung = null)
|
||||||
{
|
{
|
||||||
public const string Anchor = "faenge";
|
public const string Anchor = "faenge";
|
||||||
|
|
||||||
@@ -24,6 +25,8 @@ public sealed record DashboardFilter(
|
|||||||
public static readonly IReadOnlyList<(string Value, string Label)> Outcomes =
|
public static readonly IReadOnlyList<(string Value, string Label)> Outcomes =
|
||||||
[("", "Alle"), ("aufgegeben", "Aufgegeben"), ("zeitlimit", "Zeitlimit"), ("abgelehnt", "Abgelehnt")];
|
[("", "Alle"), ("aufgegeben", "Aufgegeben"), ("zeitlimit", "Zeitlimit"), ("abgelehnt", "Abgelehnt")];
|
||||||
|
|
||||||
|
public static readonly IReadOnlyList<(string Value, string Label)> Explanations = [("", "Alle"), ("ohne", "Ohne Erklärung")];
|
||||||
|
|
||||||
public bool IsEmpty => this with { Limit = RecentFilter.DefaultLimit } == new DashboardFilter();
|
public bool IsEmpty => this with { Limit = RecentFilter.DefaultLimit } == new DashboardFilter();
|
||||||
|
|
||||||
public static DashboardFilter Parse(
|
public static DashboardFilter Parse(
|
||||||
@@ -35,7 +38,8 @@ public sealed record DashboardFilter(
|
|||||||
string? ziel,
|
string? ziel,
|
||||||
string? strategie,
|
string? strategie,
|
||||||
string? q,
|
string? q,
|
||||||
string? limit)
|
string? limit,
|
||||||
|
string? erklaerung = null)
|
||||||
{
|
{
|
||||||
var parsedLimit = int.TryParse(limit, NumberStyles.None, CultureInfo.InvariantCulture, out var value)
|
var parsedLimit = int.TryParse(limit, NumberStyles.None, CultureInfo.InvariantCulture, out var value)
|
||||||
? Math.Clamp(value, 1, RecentFilter.MaxLimit)
|
? Math.Clamp(value, 1, RecentFilter.MaxLimit)
|
||||||
@@ -50,7 +54,8 @@ public sealed record DashboardFilter(
|
|||||||
Clean(ziel),
|
Clean(ziel),
|
||||||
Clean(strategie) is { } strategy ? StrategyNames.GroupKey(strategy) : null,
|
Clean(strategie) is { } strategy ? StrategyNames.GroupKey(strategy) : null,
|
||||||
Clean(q),
|
Clean(q),
|
||||||
parsedLimit);
|
parsedLimit,
|
||||||
|
Known(Explanations, erklaerung));
|
||||||
}
|
}
|
||||||
|
|
||||||
public RecentFilter ToRecentFilter() => new(
|
public RecentFilter ToRecentFilter() => new(
|
||||||
@@ -73,7 +78,8 @@ public sealed record DashboardFilter(
|
|||||||
Ziel,
|
Ziel,
|
||||||
StrategyNames.Group(Strategie),
|
StrategyNames.Group(Strategie),
|
||||||
Q,
|
Q,
|
||||||
Limit);
|
Limit,
|
||||||
|
Unexplained: Erklaerung == "ohne");
|
||||||
|
|
||||||
public int NextLimit => Math.Min(Limit * 2, RecentFilter.MaxLimit);
|
public int NextLimit => Math.Min(Limit * 2, RecentFilter.MaxLimit);
|
||||||
|
|
||||||
@@ -88,6 +94,7 @@ public sealed record DashboardFilter(
|
|||||||
Add(parts, "ziel", Ziel);
|
Add(parts, "ziel", Ziel);
|
||||||
Add(parts, "strategie", Strategie);
|
Add(parts, "strategie", Strategie);
|
||||||
Add(parts, "q", Q);
|
Add(parts, "q", Q);
|
||||||
|
Add(parts, "erklaerung", Erklaerung);
|
||||||
if (Limit != RecentFilter.DefaultLimit)
|
if (Limit != RecentFilter.DefaultLimit)
|
||||||
{
|
{
|
||||||
Add(parts, "limit", Limit.ToString(CultureInfo.InvariantCulture));
|
Add(parts, "limit", Limit.ToString(CultureInfo.InvariantCulture));
|
||||||
|
|||||||
@@ -5,8 +5,12 @@
|
|||||||
@using Microsoft.Extensions.Options
|
@using Microsoft.Extensions.Options
|
||||||
@using Flypaper.Storage.Dashboard
|
@using Flypaper.Storage.Dashboard
|
||||||
@using Flypaper.Storage.Entities
|
@using Flypaper.Storage.Entities
|
||||||
|
@using Flypaper.Storage.Explanations
|
||||||
@inject DashboardQueries Queries
|
@inject DashboardQueries Queries
|
||||||
|
@inject ExplanationRuleStore Explanations
|
||||||
@inject IConnectionGovernor Governor
|
@inject IConnectionGovernor Governor
|
||||||
|
@inject IActiveTraps ActiveTraps
|
||||||
|
@inject IIpEnricher Enricher
|
||||||
@inject IOptions<PortOptions> Ports
|
@inject IOptions<PortOptions> Ports
|
||||||
|
|
||||||
<PageTitle>Flypaper</PageTitle>
|
<PageTitle>Flypaper</PageTitle>
|
||||||
@@ -51,6 +55,58 @@
|
|||||||
</div>
|
</div>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
|
@if (_active.Count > 0)
|
||||||
|
{
|
||||||
|
<section class="card recent-card active-card">
|
||||||
|
<div class="card-head">
|
||||||
|
<h2>Gerade in der Falle <span class="count">· @Formatting.Number(_active.Count)</span></h2>
|
||||||
|
<span class="hint">Seit dem Laden der Seite weiter festgehalten</span>
|
||||||
|
</div>
|
||||||
|
<div class="scroll">
|
||||||
|
<table class="recent-table">
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
<th class="c-ip">IP</th>
|
||||||
|
<th class="c-origin">Herkunft</th>
|
||||||
|
<th class="c-target">Ziel</th>
|
||||||
|
<th class="c-strategy">Strategie</th>
|
||||||
|
<th class="c-agent">User-Agent</th>
|
||||||
|
<th class="c-duration num">Seit</th>
|
||||||
|
<th class="c-bytes num">Bytes</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
@foreach (var trap in _active)
|
||||||
|
{
|
||||||
|
var origin = Enricher.Lookup(trap.Ip);
|
||||||
|
var target = Formatting.Target(trap.Target);
|
||||||
|
var strategy = StrategyNames.Describe(trap.Strategy);
|
||||||
|
var ip = trap.Ip.ToString();
|
||||||
|
<tr>
|
||||||
|
<td class="c-ip mono"><a href="@(new DashboardFilter { Ip = ip }.Href(DashboardFilter.Anchor))" title="Fänge dieser IP anzeigen">@ip</a></td>
|
||||||
|
<td class="c-origin" title="@origin?.Provider">
|
||||||
|
@if (origin?.CountryCode is { } countryCode)
|
||||||
|
{
|
||||||
|
@($"{Formatting.Flag(countryCode)} {countryCode}")
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
<span class="muted">–</span>
|
||||||
|
}
|
||||||
|
</td>
|
||||||
|
<td class="c-target mono" title="@target">@target</td>
|
||||||
|
<td class="c-strategy" title="@strategy.Tooltip">@strategy.DisplayName</td>
|
||||||
|
<td class="c-agent" title="@trap.ClientInfo">@trap.ClientInfo</td>
|
||||||
|
<td class="c-duration num">@Formatting.Duration(_loadedAtUtc - trap.StartedAt)</td>
|
||||||
|
<td class="c-bytes num">@Formatting.Number(trap.BytesSent)</td>
|
||||||
|
</tr>
|
||||||
|
}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
}
|
||||||
|
|
||||||
@if (data.TotalCatches == 0)
|
@if (data.TotalCatches == 0)
|
||||||
{
|
{
|
||||||
<section class="card onboarding">
|
<section class="card onboarding">
|
||||||
@@ -125,6 +181,15 @@
|
|||||||
}
|
}
|
||||||
</select>
|
</select>
|
||||||
</label>
|
</label>
|
||||||
|
<label>
|
||||||
|
<span>Erklärung</span>
|
||||||
|
<select name="erklaerung" data-autosubmit>
|
||||||
|
@foreach (var (value, label) in DashboardFilter.Explanations)
|
||||||
|
{
|
||||||
|
<option value="@value" selected="@(value == (_filter.Erklaerung ?? ""))">@label</option>
|
||||||
|
}
|
||||||
|
</select>
|
||||||
|
</label>
|
||||||
<label class="filter-search">
|
<label class="filter-search">
|
||||||
<span>Suche</span>
|
<span>Suche</span>
|
||||||
<input type="search" name="q" value="@_filter.Q" placeholder="IP, Provider, Ziel, Strategie, User-Agent" />
|
<input type="search" name="q" value="@_filter.Q" placeholder="IP, Provider, Ziel, Strategie, User-Agent" />
|
||||||
@@ -179,6 +244,7 @@
|
|||||||
var duration = Formatting.Duration(TimeSpan.FromMilliseconds(trapEvent.DurationMs));
|
var duration = Formatting.Duration(TimeSpan.FromMilliseconds(trapEvent.DurationMs));
|
||||||
var bytes = Formatting.Number(trapEvent.BytesSent);
|
var bytes = Formatting.Number(trapEvent.BytesSent);
|
||||||
var strategy = StrategyNames.Describe(trapEvent.Strategy);
|
var strategy = StrategyNames.Describe(trapEvent.Strategy);
|
||||||
|
var explanation = _rules.Explain(trapEvent);
|
||||||
<tr id="f@(index)" data-expand="event:@trapEvent.Id" tabindex="0" aria-expanded="false" class="@(trapEvent.Outcome == TrapOutcome.Rejected ? "rejected" : null)">
|
<tr id="f@(index)" data-expand="event:@trapEvent.Id" tabindex="0" aria-expanded="false" class="@(trapEvent.Outcome == TrapOutcome.Rejected ? "rejected" : null)">
|
||||||
<td class="c-time"><span class="c-date">@started.ToString("dd.MM.") </span>@started.ToString("HH:mm:ss")</td>
|
<td class="c-time"><span class="c-date">@started.ToString("dd.MM.") </span>@started.ToString("HH:mm:ss")</td>
|
||||||
<td class="c-ip mono" title="@trapEvent.RemoteIp">@trapEvent.RemoteIp</td>
|
<td class="c-ip mono" title="@trapEvent.RemoteIp">@trapEvent.RemoteIp</td>
|
||||||
@@ -197,24 +263,27 @@
|
|||||||
@target
|
@target
|
||||||
<div class="extra extra-md">Provider: @(provider ?? "–")</div>
|
<div class="extra extra-md">Provider: @(provider ?? "–")</div>
|
||||||
<div class="extra extra-md">User-Agent: @(trapEvent.ClientInfo ?? "–")</div>
|
<div class="extra extra-md">User-Agent: @(trapEvent.ClientInfo ?? "–")</div>
|
||||||
<div class="extra extra-all strategy-info">
|
|
||||||
<strong>@strategy.DisplayName</strong>
|
|
||||||
@foreach (var badge in strategy.Badges)
|
|
||||||
{
|
|
||||||
<span class="badge">@badge</span>
|
|
||||||
}
|
|
||||||
@if (strategy.Explanation is not null)
|
|
||||||
{
|
|
||||||
<div>@strategy.Explanation</div>
|
|
||||||
}
|
|
||||||
@foreach (var detail in strategy.Details)
|
|
||||||
{
|
|
||||||
<div>@detail</div>
|
|
||||||
}
|
|
||||||
<div class="mono">@strategy.Raw</div>
|
|
||||||
</div>
|
|
||||||
<div class="extra extra-all">Herkunft: @(trapEvent.CountryCode is { } code ? $"{Formatting.Flag(code)} {code} · {Origin(trapEvent)}" : "–")</div>
|
<div class="extra extra-all">Herkunft: @(trapEvent.CountryCode is { } code ? $"{Formatting.Flag(code)} {code} · {Origin(trapEvent)}" : "–")</div>
|
||||||
<div class="extra extra-sm">Dauer: @duration · Bytes: @bytes</div>
|
<div class="extra extra-sm">Dauer: @duration · Bytes: @bytes</div>
|
||||||
|
<div class="extra extra-all explain">
|
||||||
|
<strong>Was ist passiert?</strong>
|
||||||
|
@if (explanation.Target is { } targetRule)
|
||||||
|
{
|
||||||
|
<p>@targetRule.Text</p>
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
<p class="muted">Unbekanntes Ziel</p>
|
||||||
|
}
|
||||||
|
@if (explanation.Client is { } clientRule)
|
||||||
|
{
|
||||||
|
<p>@clientRule.Text</p>
|
||||||
|
}
|
||||||
|
@if (explanation.Outcome is { } outcomeRule)
|
||||||
|
{
|
||||||
|
<p>@outcomeRule.Text</p>
|
||||||
|
}
|
||||||
|
</div>
|
||||||
<div class="extra extra-xs">Datum: @started.ToString("dd.MM.yyyy") · Ausgang: @OutcomeLabel(trapEvent.Outcome)</div>
|
<div class="extra extra-xs">Datum: @started.ToString("dd.MM.yyyy") · Ausgang: @OutcomeLabel(trapEvent.Outcome)</div>
|
||||||
</td>
|
</td>
|
||||||
<td class="c-strategy" title="@strategy.Tooltip">@strategy.DisplayName@foreach (var badge in strategy.Badges){<span class="badge">@badge</span>}</td>
|
<td class="c-strategy" title="@strategy.Tooltip">@strategy.DisplayName@foreach (var badge in strategy.Badges){<span class="badge">@badge</span>}</td>
|
||||||
@@ -252,7 +321,10 @@
|
|||||||
private DashboardData? _data;
|
private DashboardData? _data;
|
||||||
private RecentCatches? _recent;
|
private RecentCatches? _recent;
|
||||||
private DashboardFilter _filter = new();
|
private DashboardFilter _filter = new();
|
||||||
|
private RuleSet _rules = RuleSet.Empty;
|
||||||
private DateTime _loadedAt;
|
private DateTime _loadedAt;
|
||||||
|
private DateTimeOffset _loadedAtUtc;
|
||||||
|
private IReadOnlyList<ActiveTrap> _active = [];
|
||||||
|
|
||||||
[SupplyParameterFromQuery(Name = "zeit")] public string? Zeit { get; set; }
|
[SupplyParameterFromQuery(Name = "zeit")] public string? Zeit { get; set; }
|
||||||
|
|
||||||
@@ -272,11 +344,16 @@
|
|||||||
|
|
||||||
[SupplyParameterFromQuery(Name = "limit")] public string? Limit { get; set; }
|
[SupplyParameterFromQuery(Name = "limit")] public string? Limit { get; set; }
|
||||||
|
|
||||||
|
[SupplyParameterFromQuery(Name = "erklaerung")] public string? Erklaerung { get; set; }
|
||||||
|
|
||||||
protected override async Task OnInitializedAsync()
|
protected override async Task OnInitializedAsync()
|
||||||
{
|
{
|
||||||
_filter = DashboardFilter.Parse(Zeit, Ausgang, Land, Provider, Ip, Ziel, Strategie, Q, Limit);
|
_filter = DashboardFilter.Parse(Zeit, Ausgang, Land, Provider, Ip, Ziel, Strategie, Q, Limit, Erklaerung);
|
||||||
|
_rules = await Explanations.GetRuleSetAsync();
|
||||||
_data = await Queries.GetAsync();
|
_data = await Queries.GetAsync();
|
||||||
_recent = await Queries.GetRecentAsync(_filter.ToRecentFilter() with { SearchStrategies = StrategyNames.Matching(_filter.Q) });
|
_recent = await Queries.GetRecentAsync(_filter.ToRecentFilter() with { SearchStrategies = StrategyNames.Matching(_filter.Q) });
|
||||||
|
_active = ActiveTraps.Snapshot();
|
||||||
|
_loadedAtUtc = DateTimeOffset.UtcNow;
|
||||||
_loadedAt = DateTime.Now;
|
_loadedAt = DateTime.Now;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -334,6 +411,11 @@
|
|||||||
yield return ($"Strategie: {StrategyNames.Display(strategie)}{(badges.Count == 0 ? "" : $" ({string.Join(", ", badges)})")}", reset with { Strategie = null });
|
yield return ($"Strategie: {StrategyNames.Display(strategie)}{(badges.Count == 0 ? "" : $" ({string.Join(", ", badges)})")}", reset with { Strategie = null });
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (_filter.Erklaerung is { } erklaerung)
|
||||||
|
{
|
||||||
|
yield return ($"Erklärung: {DashboardFilter.Explanations.First(e => e.Value == erklaerung).Label}", reset with { Erklaerung = null });
|
||||||
|
}
|
||||||
|
|
||||||
if (_filter.Q is { } q)
|
if (_filter.Q is { } q)
|
||||||
{
|
{
|
||||||
yield return ($"Suche: „{q}“", reset with { Q = null });
|
yield return ($"Suche: „{q}“", reset with { Q = null });
|
||||||
|
|||||||
@@ -0,0 +1,89 @@
|
|||||||
|
@page "/erklaerungen"
|
||||||
|
@using Flypaper.Storage.Entities
|
||||||
|
@using Flypaper.Storage.Explanations
|
||||||
|
@inject ExplanationRuleStore Store
|
||||||
|
@inject ExplanationQueries Queries
|
||||||
|
|
||||||
|
<PageTitle>Flypaper · Erklärungen</PageTitle>
|
||||||
|
|
||||||
|
<header class="page-head">
|
||||||
|
<h1>Erklärungen</h1>
|
||||||
|
<p>Regeln, die in der Fang-Liste erklären, was ein Bot wollte. Neue Regeln legt eine KI per MCP an. Änderungen gelten sofort, auch für alte Fänge.</p>
|
||||||
|
</header>
|
||||||
|
|
||||||
|
<section class="card">
|
||||||
|
<div class="card-head">
|
||||||
|
<h2>Regeln <span class="count">· @_rules.Count</span></h2>
|
||||||
|
<span class="hint"><a href="/?erklaerung=ohne#faenge">Fänge ohne Erklärung anzeigen</a></span>
|
||||||
|
</div>
|
||||||
|
@if (_rules.Count == 0)
|
||||||
|
{
|
||||||
|
<p class="empty">Noch keine Regeln.</p>
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
<div class="scroll">
|
||||||
|
<table class="s-table rule-table">
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
<th>Art</th>
|
||||||
|
<th>Muster</th>
|
||||||
|
<th>Text</th>
|
||||||
|
<th class="num">Priorität</th>
|
||||||
|
<th class="num">Treffer</th>
|
||||||
|
<th></th>
|
||||||
|
<th></th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
@foreach (var rule in _rules)
|
||||||
|
{
|
||||||
|
<tr class="@(rule.Enabled ? null : "off")">
|
||||||
|
<td class="nowrap">@KindLabel(rule.Kind)</td>
|
||||||
|
<td class="mono">@rule.Pattern</td>
|
||||||
|
<td>
|
||||||
|
@rule.Text
|
||||||
|
<div class="muted rule-meta">
|
||||||
|
@(rule.Note is { } note ? note + " · " : "")von @rule.CreatedBy, @rule.UpdatedAt.ToLocalTime().ToString("dd.MM.yyyy")
|
||||||
|
</div>
|
||||||
|
</td>
|
||||||
|
<td class="num">@rule.Priority</td>
|
||||||
|
<td class="num">@Formatting.Number(_hits.GetValueOrDefault(rule.Id))</td>
|
||||||
|
<td class="nowrap">
|
||||||
|
<form method="post" action="/explanations/@rule.Id/enabled" class="inline-form">
|
||||||
|
<AntiforgeryToken />
|
||||||
|
<input type="hidden" name="enabled" value="@(rule.Enabled ? "false" : "true")" />
|
||||||
|
<button type="submit" class="ghost">@(rule.Enabled ? "Ausschalten" : "Einschalten")</button>
|
||||||
|
</form>
|
||||||
|
</td>
|
||||||
|
<td class="nowrap">
|
||||||
|
<form method="post" action="/explanations/@rule.Id/delete" class="inline-form" onsubmit="return confirm('Regel wirklich löschen?')">
|
||||||
|
<AntiforgeryToken />
|
||||||
|
<button type="submit" class="ghost danger-text">Löschen</button>
|
||||||
|
</form>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
</section>
|
||||||
|
|
||||||
|
@code {
|
||||||
|
private IReadOnlyList<ExplanationRuleEntity> _rules = [];
|
||||||
|
private IReadOnlyDictionary<int, int> _hits = new Dictionary<int, int>();
|
||||||
|
|
||||||
|
protected override async Task OnInitializedAsync()
|
||||||
|
{
|
||||||
|
_rules = await Store.ListAsync();
|
||||||
|
_hits = await Queries.CountHitsAsync();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string KindLabel(ExplanationKind kind) => kind switch
|
||||||
|
{
|
||||||
|
ExplanationKind.Target => "Ziel",
|
||||||
|
ExplanationKind.ClientInfo => "User-Agent",
|
||||||
|
_ => "Ausgang"
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -2,8 +2,6 @@ namespace Flypaper.Web.Components.Pages.Settings;
|
|||||||
|
|
||||||
public sealed class HoldMethodModel
|
public sealed class HoldMethodModel
|
||||||
{
|
{
|
||||||
public string? Content { get; set; }
|
|
||||||
|
|
||||||
public string? MinDelayMs { get; set; }
|
public string? MinDelayMs { get; set; }
|
||||||
|
|
||||||
public string? MaxDelayMs { get; set; }
|
public string? MaxDelayMs { get; set; }
|
||||||
|
|||||||
@@ -21,28 +21,6 @@
|
|||||||
|
|
||||||
<EditForm Model="Model" FormName="hold-method" OnSubmit="SaveAsync" action="/settings#hold-method" id="hold-method-form">
|
<EditForm Model="Model" FormName="hold-method" OnSubmit="SaveAsync" action="/settings#hold-method" id="hold-method-form">
|
||||||
<div class="s-body">
|
<div class="s-body">
|
||||||
<fieldset class="choices">
|
|
||||||
<legend>Inhalt</legend>
|
|
||||||
<InputRadioGroup @bind-Value="Model!.Content">
|
|
||||||
<div class="choice-grid">
|
|
||||||
@foreach (var choice in Choices)
|
|
||||||
{
|
|
||||||
<label class="choice">
|
|
||||||
<InputRadio Value="@choice.Value" />
|
|
||||||
<span class="choice-body">
|
|
||||||
<strong>@choice.Title</strong>
|
|
||||||
<span>@choice.Text</span>
|
|
||||||
</span>
|
|
||||||
</label>
|
|
||||||
}
|
|
||||||
</div>
|
|
||||||
</InputRadioGroup>
|
|
||||||
@if (_errors.TryGetValue(nameof(HoldMethodModel.Content), out var contentError))
|
|
||||||
{
|
|
||||||
<p class="field-error">@contentError</p>
|
|
||||||
}
|
|
||||||
</fieldset>
|
|
||||||
|
|
||||||
<div class="fields">
|
<div class="fields">
|
||||||
<SettingsField Label="Pause min." For="drip-min-delay" Unit="ms" Hint="10 bis 30000" Errors="_errors" Key="@nameof(HoldMethodModel.MinDelayMs)">
|
<SettingsField Label="Pause min." For="drip-min-delay" Unit="ms" Hint="10 bis 30000" Errors="_errors" Key="@nameof(HoldMethodModel.MinDelayMs)">
|
||||||
<InputText id="drip-min-delay" @bind-Value="Model!.MinDelayMs" inputmode="numeric" data-bandwidth-input />
|
<InputText id="drip-min-delay" @bind-Value="Model!.MinDelayMs" inputmode="numeric" data-bandwidth-input />
|
||||||
@@ -105,13 +83,6 @@
|
|||||||
<script src="@Assets["settings.js"]" defer></script>
|
<script src="@Assets["settings.js"]" defer></script>
|
||||||
|
|
||||||
@code {
|
@code {
|
||||||
private static readonly (string Value, string Title, string Text)[] Choices =
|
|
||||||
[
|
|
||||||
(nameof(DripContent.Html), "HTML-Fülltext", "Eine endlose Webseite mit Überschriften, Absätzen und vielen Links, die wieder in die Falle führen (Link-Labyrinth). Wirkt auf Crawler am echtesten."),
|
|
||||||
(nameof(DripContent.Text), "Zufallstext", "Schlichter Text ohne Markup, ausgeliefert als text/plain."),
|
|
||||||
(nameof(DripContent.Alternating), "Wechselnd", "Pro Fang zufällig eine der beiden. Gut, um zu vergleichen, was Bots länger hält.")
|
|
||||||
];
|
|
||||||
|
|
||||||
private readonly object _resetModel = new();
|
private readonly object _resetModel = new();
|
||||||
private IReadOnlyDictionary<string, string> _errors = new Dictionary<string, string>();
|
private IReadOnlyDictionary<string, string> _errors = new Dictionary<string, string>();
|
||||||
private bool _hasOverrides;
|
private bool _hasOverrides;
|
||||||
@@ -146,8 +117,7 @@
|
|||||||
private async Task SaveAsync()
|
private async Task SaveAsync()
|
||||||
{
|
{
|
||||||
var result = RuntimeSettingsParser.ParseHoldMethod(new HoldMethodInput(
|
var result = RuntimeSettingsParser.ParseHoldMethod(new HoldMethodInput(
|
||||||
Model!.Content,
|
Model!.MinDelayMs,
|
||||||
Model.MinDelayMs,
|
|
||||||
Model.MaxDelayMs,
|
Model.MaxDelayMs,
|
||||||
Model.MinChunkSize,
|
Model.MinChunkSize,
|
||||||
Model.MaxChunkSize,
|
Model.MaxChunkSize,
|
||||||
@@ -180,7 +150,6 @@
|
|||||||
var drip = Drip.CurrentValue;
|
var drip = Drip.CurrentValue;
|
||||||
return new HoldMethodModel
|
return new HoldMethodModel
|
||||||
{
|
{
|
||||||
Content = drip.Content.ToString(),
|
|
||||||
MinDelayMs = ((int)drip.MinDelay.TotalMilliseconds).ToString(CultureInfo.InvariantCulture),
|
MinDelayMs = ((int)drip.MinDelay.TotalMilliseconds).ToString(CultureInfo.InvariantCulture),
|
||||||
MaxDelayMs = ((int)drip.MaxDelay.TotalMilliseconds).ToString(CultureInfo.InvariantCulture),
|
MaxDelayMs = ((int)drip.MaxDelay.TotalMilliseconds).ToString(CultureInfo.InvariantCulture),
|
||||||
MinChunkSize = drip.MinChunkSize.ToString(CultureInfo.InvariantCulture),
|
MinChunkSize = drip.MinChunkSize.ToString(CultureInfo.InvariantCulture),
|
||||||
|
|||||||
@@ -5,11 +5,19 @@
|
|||||||
@inject McpTokenStore Store
|
@inject McpTokenStore Store
|
||||||
@inject NavigationManager Navigation
|
@inject NavigationManager Navigation
|
||||||
|
|
||||||
<SettingsSection Id="mcp" Title="MCP-Zugriff" Description="KI-Assistenten wie Claude lesen die Fänge über das Model Context Protocol Nur im LAN.">
|
<SettingsSection Id="mcp" Title="MCP-Zugriff" Description="KI-Assistenten wie Claude lesen die Fänge über das Model Context Protocol und pflegen die Erklärungsregeln. Regeln ändern dürfen nur Tokens mit Schreibrecht. Nur im LAN.">
|
||||||
@if (Revoked == "revoked")
|
@if (Revoked == "revoked")
|
||||||
{
|
{
|
||||||
<Notice>Token widerrufen.</Notice>
|
<Notice>Token widerrufen.</Notice>
|
||||||
}
|
}
|
||||||
|
else if (Revoked == "write-on")
|
||||||
|
{
|
||||||
|
<Notice>Schreibrecht erteilt.</Notice>
|
||||||
|
}
|
||||||
|
else if (Revoked == "write-off")
|
||||||
|
{
|
||||||
|
<Notice>Schreibrecht entzogen.</Notice>
|
||||||
|
}
|
||||||
|
|
||||||
@if (_newToken is not null)
|
@if (_newToken is not null)
|
||||||
{
|
{
|
||||||
@@ -37,6 +45,7 @@
|
|||||||
<th>Name</th>
|
<th>Name</th>
|
||||||
<th>Erstellt</th>
|
<th>Erstellt</th>
|
||||||
<th>Zuletzt genutzt</th>
|
<th>Zuletzt genutzt</th>
|
||||||
|
<th>Zugriff</th>
|
||||||
<th></th>
|
<th></th>
|
||||||
</tr>
|
</tr>
|
||||||
</thead>
|
</thead>
|
||||||
@@ -47,6 +56,14 @@
|
|||||||
<td>@token.Name</td>
|
<td>@token.Name</td>
|
||||||
<td class="nowrap">@token.CreatedAt.ToLocalTime().ToString("dd.MM.yyyy HH:mm")</td>
|
<td class="nowrap">@token.CreatedAt.ToLocalTime().ToString("dd.MM.yyyy HH:mm")</td>
|
||||||
<td class="nowrap">@(token.LastUsedAt?.ToLocalTime().ToString("dd.MM.yyyy HH:mm") ?? "nie")</td>
|
<td class="nowrap">@(token.LastUsedAt?.ToLocalTime().ToString("dd.MM.yyyy HH:mm") ?? "nie")</td>
|
||||||
|
<td class="nowrap">
|
||||||
|
<form method="post" action="/mcp-tokens/@token.Id/write" class="inline-form">
|
||||||
|
<AntiforgeryToken />
|
||||||
|
<input type="hidden" name="enabled" value="@(token.CanWrite ? "false" : "true")" />
|
||||||
|
<span>@(token.CanWrite ? "Lesen und schreiben" : "Nur lesen")</span>
|
||||||
|
<button type="submit" class="ghost">@(token.CanWrite ? "Schreibrecht entziehen" : "Schreibrecht erteilen")</button>
|
||||||
|
</form>
|
||||||
|
</td>
|
||||||
<td class="num">
|
<td class="num">
|
||||||
<form method="post" action="/mcp-tokens/@token.Id/revoke" onsubmit="return confirm('Token „@token.Name“ widerrufen?')">
|
<form method="post" action="/mcp-tokens/@token.Id/revoke" onsubmit="return confirm('Token „@token.Name“ widerrufen?')">
|
||||||
<AntiforgeryToken />
|
<AntiforgeryToken />
|
||||||
@@ -72,6 +89,10 @@
|
|||||||
<span class="field-error">@nameError</span>
|
<span class="field-error">@nameError</span>
|
||||||
}
|
}
|
||||||
</div>
|
</div>
|
||||||
|
<label class="inline-check">
|
||||||
|
<InputCheckbox @bind-Value="Model!.CanWrite" />
|
||||||
|
<span>Mit Schreibrecht</span>
|
||||||
|
</label>
|
||||||
<button type="submit">Token erzeugen</button>
|
<button type="submit">Token erzeugen</button>
|
||||||
</EditForm>
|
</EditForm>
|
||||||
</SettingsSection>
|
</SettingsSection>
|
||||||
@@ -103,9 +124,10 @@
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
_newToken = await Tokens.CreateAsync(name);
|
_newToken = await Tokens.CreateAsync(name, Model.CanWrite);
|
||||||
_newTokenName = name;
|
_newTokenName = name;
|
||||||
Model.Name = null;
|
Model.Name = null;
|
||||||
|
Model.CanWrite = false;
|
||||||
_tokens = await Store.ListAsync();
|
_tokens = await Store.ListAsync();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -3,4 +3,6 @@ namespace Flypaper.Web.Components.Pages.Settings;
|
|||||||
public sealed class McpTokenModel
|
public sealed class McpTokenModel
|
||||||
{
|
{
|
||||||
public string? Name { get; set; }
|
public string? Name { get; set; }
|
||||||
|
|
||||||
|
public bool CanWrite { get; set; }
|
||||||
}
|
}
|
||||||
@@ -34,7 +34,6 @@ public static partial class StrategyNames
|
|||||||
["maze-drip"] = ("Link-Labyrinth", "Eine Webseite voller Links, die immer zu neuen, erfundenen Seiten führen. Der Bot folgt ihnen und verirrt sich, während alles nur tröpfchenweise ankommt."),
|
["maze-drip"] = ("Link-Labyrinth", "Eine Webseite voller Links, die immer zu neuen, erfundenen Seiten führen. Der Bot folgt ihnen und verirrt sich, während alles nur tröpfchenweise ankommt."),
|
||||||
["index-drip"] = ("Gefälschtes Ordner-Listing", "Eine Dateiliste im Stil von „Index of /…“ mit erfundenen Ordnern und Dateien. Wer weiterklickt, landet im Link-Labyrinth."),
|
["index-drip"] = ("Gefälschtes Ordner-Listing", "Eine Dateiliste im Stil von „Index of /…“ mit erfundenen Ordnern und Dateien. Wer weiterklickt, landet im Link-Labyrinth."),
|
||||||
["html-drip"] = ("Endlose Webseite", "Eine gewöhnlich aussehende Webseite, die nie aufhört und nur Stück für Stück geliefert wird. Der Bot wartet auf das Ende, das nie kommt."),
|
["html-drip"] = ("Endlose Webseite", "Eine gewöhnlich aussehende Webseite, die nie aufhört und nur Stück für Stück geliefert wird. Der Bot wartet auf das Ende, das nie kommt."),
|
||||||
["text-drip"] = ("Endloser Text", "Unendlicher Fließtext ohne Formatierung, der nur tröpfchenweise ankommt. Der Bot wartet auf das Ende, das nie kommt."),
|
|
||||||
["env-drip"] = ("Gefälschte Zugangsdaten (.env)", "Eine erfundene .env-Datei mit Passwörtern und Schlüsseln, die nie endet. Bots, die nach geleakten Zugangsdaten suchen, lesen sie bis zum Ende."),
|
["env-drip"] = ("Gefälschte Zugangsdaten (.env)", "Eine erfundene .env-Datei mit Passwörtern und Schlüsseln, die nie endet. Bots, die nach geleakten Zugangsdaten suchen, lesen sie bis zum Ende."),
|
||||||
["git-drip"] = ("Gefälschtes Git-Projekt", "Eine erfundene Git-Konfiguration, die wie die echte beginnt und nie endet. Bots, die Quellcode abgreifen wollen, bleiben daran hängen."),
|
["git-drip"] = ("Gefälschtes Git-Projekt", "Eine erfundene Git-Konfiguration, die wie die echte beginnt und nie endet. Bots, die Quellcode abgreifen wollen, bleiben daran hängen."),
|
||||||
["svn-drip"] = ("Gefälschtes Subversion-Projekt", "Erfundene Dateien aus einem .svn-Ordner, die wie die echten beginnen und nie enden. Bots, die Quellcode abgreifen wollen, bleiben daran hängen."),
|
["svn-drip"] = ("Gefälschtes Subversion-Projekt", "Erfundene Dateien aus einem .svn-Ordner, die wie die echten beginnen und nie enden. Bots, die Quellcode abgreifen wollen, bleiben daran hängen."),
|
||||||
@@ -45,6 +44,8 @@ public static partial class StrategyNames
|
|||||||
["sql-drip"] = ("Gefälschter Datenbank-Export (SQL)", "Ein erfundener SQL-Dump mit endlos vielen Einträgen. Bots, die nach Datenbank-Backups suchen, laden ihn herunter, solange es geht."),
|
["sql-drip"] = ("Gefälschter Datenbank-Export (SQL)", "Ein erfundener SQL-Dump mit endlos vielen Einträgen. Bots, die nach Datenbank-Backups suchen, laden ihn herunter, solange es geht."),
|
||||||
["hikvision-drip"] = ("Gefälschte Überwachungskamera (Hikvision)", "Die Antwort einer erfundenen Hikvision-Kamera, die nie endet. Bots, die nach angreifbaren Kameras suchen, warten auf die komplette Antwort."),
|
["hikvision-drip"] = ("Gefälschte Überwachungskamera (Hikvision)", "Die Antwort einer erfundenen Hikvision-Kamera, die nie endet. Bots, die nach angreifbaren Kameras suchen, warten auf die komplette Antwort."),
|
||||||
["wordpress-drip"] = ("Gefälschte WordPress-Anmeldung", "Eine erfundene WordPress-Anmeldeseite, die nie fertig geladen wird. Bots, die Passwörter durchprobieren, kommen nie zum Formular."),
|
["wordpress-drip"] = ("Gefälschte WordPress-Anmeldung", "Eine erfundene WordPress-Anmeldeseite, die nie fertig geladen wird. Bots, die Passwörter durchprobieren, kommen nie zum Formular."),
|
||||||
|
["lure-page"] = ("Köder-Startseite (WordPress)", "Beim ersten Besuch einer unbekannten IP wird sofort eine kleine WordPress-Seite mit Links geliefert und niemand festgehalten. Wer danach gezielt weitersucht, kommt in die Falle."),
|
||||||
|
["lure-icon"] = ("Köder-Favicon (WordPress)", "Beim ersten Besuch einer unbekannten IP wird sofort ein kleines Favicon geliefert und niemand festgehalten."),
|
||||||
["robots-static"] = ("robots.txt (Hinweis an brave Crawler)", "Die robots.txt wird sofort und vollständig geliefert. Sie verbietet alles, brave Crawler bleiben draußen. Es wird bewusst niemand festgehalten."),
|
["robots-static"] = ("robots.txt (Hinweis an brave Crawler)", "Die robots.txt wird sofort und vollständig geliefert. Sie verbietet alles, brave Crawler bleiben draußen. Es wird bewusst niemand festgehalten."),
|
||||||
["robots-bait"] = ("Köder aus der robots.txt", "Ein Pfad, der in der robots.txt als verboten steht, aber ins Link-Labyrinth führt. Wer dort landet, hat das Verbot gelesen und ignoriert. Er wird mindestens 24 Stunden festgehalten.")
|
["robots-bait"] = ("Köder aus der robots.txt", "Ein Pfad, der in der robots.txt als verboten steht, aber ins Link-Labyrinth führt. Wer dort landet, hat das Verbot gelesen und ignoriert. Er wird mindestens 24 Stunden festgehalten.")
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -0,0 +1,35 @@
|
|||||||
|
using Flypaper.Storage.Explanations;
|
||||||
|
using Microsoft.AspNetCore.Antiforgery;
|
||||||
|
|
||||||
|
namespace Flypaper.Web.Explanations;
|
||||||
|
|
||||||
|
public static class ExplanationEndpoints
|
||||||
|
{
|
||||||
|
public static IEndpointRouteBuilder MapExplanationEndpoints(this IEndpointRouteBuilder app)
|
||||||
|
{
|
||||||
|
app.MapPost("/explanations/{id:int}/enabled", async (int id, HttpContext context, IAntiforgery antiforgery, ExplanationRuleStore store) =>
|
||||||
|
{
|
||||||
|
if (!await antiforgery.IsRequestValidAsync(context))
|
||||||
|
{
|
||||||
|
return Results.BadRequest();
|
||||||
|
}
|
||||||
|
|
||||||
|
var enabled = (await context.Request.ReadFormAsync(context.RequestAborted))["enabled"] == "true";
|
||||||
|
await store.SetEnabledAsync(id, enabled, context.RequestAborted);
|
||||||
|
return Results.LocalRedirect("/erklaerungen");
|
||||||
|
});
|
||||||
|
|
||||||
|
app.MapPost("/explanations/{id:int}/delete", async (int id, HttpContext context, IAntiforgery antiforgery, ExplanationRuleStore store) =>
|
||||||
|
{
|
||||||
|
if (!await antiforgery.IsRequestValidAsync(context))
|
||||||
|
{
|
||||||
|
return Results.BadRequest();
|
||||||
|
}
|
||||||
|
|
||||||
|
await store.DeleteAsync(id, context.RequestAborted);
|
||||||
|
return Results.LocalRedirect("/erklaerungen");
|
||||||
|
});
|
||||||
|
|
||||||
|
return app;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,187 @@
|
|||||||
|
using System.ComponentModel;
|
||||||
|
using System.ComponentModel.DataAnnotations;
|
||||||
|
using Flypaper.Storage.Entities;
|
||||||
|
using Flypaper.Storage.Explanations;
|
||||||
|
using Flypaper.Storage.Queries;
|
||||||
|
using ModelContextProtocol;
|
||||||
|
using ModelContextProtocol.Server;
|
||||||
|
|
||||||
|
namespace Flypaper.Web.Mcp;
|
||||||
|
|
||||||
|
[McpServerToolType]
|
||||||
|
public sealed class ExplanationTools(ExplanationRuleStore store, ExplanationQueries queries, TimeProvider timeProvider, IHttpContextAccessor httpContext)
|
||||||
|
{
|
||||||
|
private const string PeriodDescription = "Time window ending now: a number with m (minutes), h (hours), d (days) or w (weeks), e.g. 24h, 7d; or all.";
|
||||||
|
|
||||||
|
private const string KindDescription =
|
||||||
|
"What the pattern is matched against. " +
|
||||||
|
"target: the requested path including the query string, without method and host, e.g. /.git/HEAD or /index.php?s=/x (the text explains what the bot was looking for). " +
|
||||||
|
"client_info: the User-Agent header, an empty string if the bot sent none (the text explains which tool or kind of client it is). " +
|
||||||
|
"outcome: the text '<Outcome> <whole seconds>s', e.g. 'ClientAborted 9s', 'Timeout 60s', 'Completed 3600s', or just 'Rejected' (the text explains how the catch ended; " +
|
||||||
|
"ClientAborted = the bot gave up, Timeout = Flypaper ended it, Rejected = connection refused because the trap was full, Completed = finished normally).";
|
||||||
|
|
||||||
|
private const string PatternDescription =
|
||||||
|
".NET regular expression, case-insensitive, matches anywhere in the text unless anchored with ^ and $. Lookarounds, backreferences and atomic groups are not supported. " +
|
||||||
|
"Make it as narrow as possible and anchor it, e.g. ^/\\.env(\\.[a-z0-9_-]+)?$ instead of env. Test it with test_explanation_rule before saving. At most 500 characters.";
|
||||||
|
|
||||||
|
private const string TextDescription =
|
||||||
|
"One or two short sentences in German, simple language for laypeople, plain text only (no Markdown, HTML or line breaks), at most 600 characters. " +
|
||||||
|
"target: what the bot wanted, e.g. 'Sucht nach einer vergessenen Konfigurationsdatei, in der oft Passwörter stehen.' " +
|
||||||
|
"client_info: which tool it is, e.g. 'Ein Programm, das das Internet automatisch nach offenen Servern absucht.' " +
|
||||||
|
"outcome: how it ended, e.g. 'Der Bot hat nach 9 Sekunden aufgegeben.' Do not claim more than the data shows.";
|
||||||
|
|
||||||
|
private const string PriorityDescription = "Higher wins when several rules of the same kind match; ties go to the older rule. Use about 10 for narrow rules and 0 for broad fallbacks. Range -1000 to 1000.";
|
||||||
|
|
||||||
|
private const string NoteDescription = "Optional source or remark for maintainers, e.g. a CVE number or a link. At most 500 characters. An empty string removes it.";
|
||||||
|
|
||||||
|
[McpServerTool(Name = "list_explanation_rules", Title = "List explanation rules", ReadOnly = true, Destructive = false, Idempotent = true, OpenWorld = false, UseStructuredContent = true)]
|
||||||
|
[Description("All explanation rules with pattern, text, priority, enabled state and how many catches each one matches (counted over all stored catches, even when the rule is disabled). Look here before creating a rule to avoid duplicates.")]
|
||||||
|
public async Task<RuleListResult> ListRules(
|
||||||
|
[Description("Only this kind: target, client_info or outcome.")] string? kind = null,
|
||||||
|
CancellationToken ct = default)
|
||||||
|
{
|
||||||
|
var filter = kind is null ? (ExplanationKind?)null : ParseKind(kind);
|
||||||
|
var hits = await queries.CountHitsAsync(ct);
|
||||||
|
var rules = (await store.ListAsync(ct)).Where(r => filter is null || r.Kind == filter).Select(r => ToItem(r, hits.GetValueOrDefault(r.Id))).ToList();
|
||||||
|
return new RuleListResult(rules.Count, rules);
|
||||||
|
}
|
||||||
|
|
||||||
|
[McpServerTool(Name = "list_unexplained", Title = "List unexplained targets", ReadOnly = true, Destructive = false, Idempotent = true, OpenWorld = false, UseStructuredContent = true)]
|
||||||
|
[Description("Catches whose requested path is not explained by any enabled target rule, grouped by path or by path pattern and sorted by number of catches. Start here to find what to write rules for: take the biggest groups first.")]
|
||||||
|
public async Task<UnexplainedListResult> ListUnexplained(
|
||||||
|
[Description(PeriodDescription)] string period = "all",
|
||||||
|
[Description("path: one group per exact path including the query string. pattern: paths that differ only in numbers or long hex strings are merged (digits become {n}, hex strings {hex}) and the query string is dropped.")]
|
||||||
|
[AllowedValues("path", "pattern")]
|
||||||
|
string group_by = "pattern",
|
||||||
|
[Description("Maximum number of groups, 1 to 500.")] int limit = 50,
|
||||||
|
CancellationToken ct = default)
|
||||||
|
{
|
||||||
|
var grouping = group_by.Trim().ToLowerInvariant() switch
|
||||||
|
{
|
||||||
|
"path" => UnexplainedGrouping.Path,
|
||||||
|
"pattern" => UnexplainedGrouping.Pattern,
|
||||||
|
_ => throw new McpException("group_by must be path or pattern.")
|
||||||
|
};
|
||||||
|
|
||||||
|
var result = await queries.FindUnexplainedAsync(Since(period), grouping, limit, ct);
|
||||||
|
return new UnexplainedListResult(
|
||||||
|
Normalize(period),
|
||||||
|
group_by.Trim().ToLowerInvariant(),
|
||||||
|
result.Catches,
|
||||||
|
result.DistinctPaths,
|
||||||
|
result.Groups.Select(g => new UnexplainedItem(g.Key, g.Catches, g.ExamplePaths, g.ExampleUserAgent, g.FirstSeen, g.LastSeen)).ToList(),
|
||||||
|
result.GroupsOmitted);
|
||||||
|
}
|
||||||
|
|
||||||
|
[McpServerTool(Name = "test_explanation_rule", Title = "Test an explanation rule", ReadOnly = true, Destructive = false, Idempotent = true, OpenWorld = false, UseStructuredContent = true)]
|
||||||
|
[Description("Tries a pattern against the stored catches without saving anything: how many catches match, example values, how many were unexplained before, and which existing rules would lose catches to it (a higher priority takes over). Check the examples for false positives and tighten the pattern before create_explanation_rule. Pass rule_id to test a change to an existing rule.")]
|
||||||
|
public async Task<RuleTestItem> TestRule(
|
||||||
|
[Description(KindDescription)] [AllowedValues("target", "client_info", "outcome")] string kind,
|
||||||
|
[Description(PatternDescription)] string pattern,
|
||||||
|
[Description(PriorityDescription)] int priority = 0,
|
||||||
|
[Description("Id of an existing rule that this pattern would replace; its current pattern is then ignored and catches it would no longer explain are reported.")] int? rule_id = null,
|
||||||
|
[Description(PeriodDescription)] string period = "all",
|
||||||
|
CancellationToken ct = default)
|
||||||
|
{
|
||||||
|
var parsed = ParseKind(kind);
|
||||||
|
if (rule_id is { } id && await store.GetAsync(id, ct) is null)
|
||||||
|
{
|
||||||
|
throw NotFound(id);
|
||||||
|
}
|
||||||
|
|
||||||
|
var result = await queries.TestAsync(parsed, pattern, priority, rule_id, Since(period), ct);
|
||||||
|
return new RuleTestItem(
|
||||||
|
KindName(parsed),
|
||||||
|
pattern.Trim(),
|
||||||
|
Normalize(period),
|
||||||
|
result.Catches,
|
||||||
|
result.DistinctValues,
|
||||||
|
result.Examples.Select(e => new ValueCount(e.Value, e.Catches)).ToList(),
|
||||||
|
result.NewlyExplained,
|
||||||
|
result.TakesOver.Select(t => new TakeoverItem(t.Rule.Id, t.Rule.Pattern, t.Rule.Text, t.Rule.Priority, t.Catches, t.Examples)).ToList(),
|
||||||
|
result.Lost,
|
||||||
|
result.LostExamples);
|
||||||
|
}
|
||||||
|
|
||||||
|
[McpServerTool(Name = "create_explanation_rule", Title = "Create explanation rule", ReadOnly = false, Destructive = false, Idempotent = false, OpenWorld = false, UseStructuredContent = true)]
|
||||||
|
[Description("Creates an explanation rule. It is active immediately and shows up in the dashboard for all matching catches, old ones included. Test the pattern with test_explanation_rule first. Needs a token with write permission.")]
|
||||||
|
public async Task<RuleItem> CreateRule(
|
||||||
|
[Description(KindDescription)] [AllowedValues("target", "client_info", "outcome")] string kind,
|
||||||
|
[Description(PatternDescription)] string pattern,
|
||||||
|
[Description(TextDescription)] string text,
|
||||||
|
[Description(PriorityDescription)] int priority = 0,
|
||||||
|
[Description(NoteDescription)] string? note = null,
|
||||||
|
CancellationToken ct = default) =>
|
||||||
|
ToItem(await store.CreateAsync(new ExplanationRuleInput(ParseKind(kind), pattern, text, priority, note), Actor(), ct), null);
|
||||||
|
|
||||||
|
[McpServerTool(Name = "update_explanation_rule", Title = "Update explanation rule", ReadOnly = false, Destructive = false, Idempotent = true, OpenWorld = false, UseStructuredContent = true)]
|
||||||
|
[Description("Changes an explanation rule; only the given fields are changed. Test a new pattern with test_explanation_rule (rule_id) first. Needs a token with write permission.")]
|
||||||
|
public async Task<RuleItem> UpdateRule(
|
||||||
|
[Description("Id of the rule.")] int id,
|
||||||
|
[Description("New kind. " + KindDescription)] string? kind = null,
|
||||||
|
[Description("New pattern. " + PatternDescription)] string? pattern = null,
|
||||||
|
[Description("New text. " + TextDescription)] string? text = null,
|
||||||
|
[Description("New priority. " + PriorityDescription)] int? priority = null,
|
||||||
|
[Description(NoteDescription)] string? note = null,
|
||||||
|
CancellationToken ct = default) =>
|
||||||
|
ToItem(await store.UpdateAsync(id, new ExplanationRuleInput(kind is null ? null : ParseKind(kind), pattern, text, priority, note), ct) ?? throw NotFound(id), null);
|
||||||
|
|
||||||
|
[McpServerTool(Name = "set_explanation_rule_enabled", Title = "Enable or disable explanation rule", ReadOnly = false, Destructive = false, Idempotent = true, OpenWorld = false, UseStructuredContent = true)]
|
||||||
|
[Description("Switches a rule on or off without deleting it. Needs a token with write permission.")]
|
||||||
|
public async Task<RuleItem> SetEnabled(
|
||||||
|
[Description("Id of the rule.")] int id,
|
||||||
|
[Description("true to enable, false to disable.")] bool enabled,
|
||||||
|
CancellationToken ct = default) =>
|
||||||
|
ToItem(await store.SetEnabledAsync(id, enabled, ct) ?? throw NotFound(id), null);
|
||||||
|
|
||||||
|
[McpServerTool(Name = "delete_explanation_rule", Title = "Delete explanation rule", ReadOnly = false, Destructive = true, Idempotent = true, OpenWorld = false, UseStructuredContent = true)]
|
||||||
|
[Description("Permanently deletes a rule. Prefer set_explanation_rule_enabled when unsure. Needs a token with write permission.")]
|
||||||
|
public async Task<DeleteResult> DeleteRule(
|
||||||
|
[Description("Id of the rule.")] int id,
|
||||||
|
CancellationToken ct = default) =>
|
||||||
|
new(id, await store.DeleteAsync(id, ct));
|
||||||
|
|
||||||
|
private string Actor() => httpContext.HttpContext?.User.Identity?.Name is { Length: > 0 } name ? name : "MCP";
|
||||||
|
|
||||||
|
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 ExplanationKind ParseKind(string kind) => kind.Trim().ToLowerInvariant() switch
|
||||||
|
{
|
||||||
|
"target" => ExplanationKind.Target,
|
||||||
|
"client_info" => ExplanationKind.ClientInfo,
|
||||||
|
"outcome" => ExplanationKind.Outcome,
|
||||||
|
_ => throw new McpException("kind must be one of target, client_info, outcome.")
|
||||||
|
};
|
||||||
|
|
||||||
|
private static string KindName(ExplanationKind kind) => kind switch
|
||||||
|
{
|
||||||
|
ExplanationKind.Target => "target",
|
||||||
|
ExplanationKind.ClientInfo => "client_info",
|
||||||
|
_ => "outcome"
|
||||||
|
};
|
||||||
|
|
||||||
|
private static McpException NotFound(int id) => new($"There is no explanation rule with id {id}.");
|
||||||
|
|
||||||
|
private static RuleItem ToItem(ExplanationRuleEntity rule, int? catches) => new(
|
||||||
|
rule.Id,
|
||||||
|
KindName(rule.Kind),
|
||||||
|
rule.Pattern,
|
||||||
|
rule.Text,
|
||||||
|
rule.Priority,
|
||||||
|
rule.Enabled,
|
||||||
|
rule.Note,
|
||||||
|
rule.CreatedAt,
|
||||||
|
rule.UpdatedAt,
|
||||||
|
rule.CreatedBy,
|
||||||
|
catches);
|
||||||
|
}
|
||||||
@@ -11,7 +11,7 @@ using ModelContextProtocol.Server;
|
|||||||
namespace Flypaper.Web.Mcp;
|
namespace Flypaper.Web.Mcp;
|
||||||
|
|
||||||
[McpServerToolType]
|
[McpServerToolType]
|
||||||
public sealed class FlypaperTools(CatchQueries queries, IConnectionGovernor governor, TimeProvider timeProvider)
|
public sealed class FlypaperTools(CatchQueries queries, IConnectionGovernor governor, IActiveTraps activeTraps, IIpEnricher enricher, 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.";
|
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.";
|
||||||
|
|
||||||
@@ -35,6 +35,31 @@ public sealed class FlypaperTools(CatchQueries queries, IConnectionGovernor gove
|
|||||||
stats.Longest is null ? null : ToItem(stats.Longest));
|
stats.Longest is null ? null : ToItem(stats.Longest));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[McpServerTool(Name = "list_active", Title = "Bots in the trap right now", ReadOnly = true, Destructive = false, Idempotent = true, OpenWorld = false, UseStructuredContent = true)]
|
||||||
|
[Description("Bots held in the trap right now, longest running first: IP, origin, requested URL, user agent, strategy, how long they have been held and bytes sent so far. Held in memory only, so it is empty after a restart.")]
|
||||||
|
public ActiveTrapListResult ListActive()
|
||||||
|
{
|
||||||
|
var now = timeProvider.GetUtcNow();
|
||||||
|
var traps = activeTraps.Snapshot().Select(trap =>
|
||||||
|
{
|
||||||
|
var origin = enricher.Lookup(trap.Ip);
|
||||||
|
return new ActiveTrapItem(
|
||||||
|
trap.StartedAt.UtcDateTime,
|
||||||
|
Round((now - trap.StartedAt).TotalSeconds),
|
||||||
|
trap.BytesSent,
|
||||||
|
trap.Strategy,
|
||||||
|
trap.Ip.ToString(),
|
||||||
|
origin?.CountryCode,
|
||||||
|
CountryNames.Display(origin?.CountryCode, origin?.Country),
|
||||||
|
origin?.City,
|
||||||
|
Asn(origin?.Asn),
|
||||||
|
origin?.Provider,
|
||||||
|
trap.Target,
|
||||||
|
trap.ClientInfo);
|
||||||
|
}).ToList();
|
||||||
|
return new ActiveTrapListResult(traps.Count, traps);
|
||||||
|
}
|
||||||
|
|
||||||
[McpServerTool(Name = "list_catches", Title = "List catches", ReadOnly = true, Destructive = false, Idempotent = true, OpenWorld = false, UseStructuredContent = true)]
|
[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).")]
|
[Description("Trap events, newest first, optionally filtered. Includes rejected connections (outcome Rejected).")]
|
||||||
public async Task<CatchListResult> ListCatches(
|
public async Task<CatchListResult> ListCatches(
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
using System.Security.Claims;
|
||||||
using System.Text.Json;
|
using System.Text.Json;
|
||||||
using System.Text.Json.Serialization;
|
using System.Text.Json.Serialization;
|
||||||
using Flypaper.Storage.Settings;
|
using Flypaper.Storage.Settings;
|
||||||
@@ -18,7 +19,14 @@ public static class McpExtensions
|
|||||||
"Flypaper is an HTTP tarpit. Scanning bots that probe a server (e.g. for /.env or /wp-login.php) are " +
|
"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 " +
|
"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 " +
|
"stored with its time, client IP, country, network provider (ASN), requested URL, user agent, duration " +
|
||||||
"and bytes sent. All tools only read that data; times are ISO 8601 UTC, durations in seconds.";
|
"and bytes sent. Times are ISO 8601 UTC, durations in seconds. The tools list_catches, top, longest_catches, " +
|
||||||
|
"lookup_ip, list_active (bots held right now) and get_stats only read that data. Explanation rules turn catches into plain German sentences " +
|
||||||
|
"shown in the dashboard (what a bot wanted, with which tool, how it ended); they are matched when a catch is " +
|
||||||
|
"displayed, so a new rule also explains old catches. Use list_unexplained to find catches without an " +
|
||||||
|
"explanation, test_explanation_rule to try a pattern, and list_explanation_rules to see what exists. The tools " +
|
||||||
|
"create_explanation_rule, update_explanation_rule, set_explanation_rule_enabled and delete_explanation_rule " +
|
||||||
|
"change rules and need a token with write permission; read-only tokens do not see them. New rules are active " +
|
||||||
|
"immediately.";
|
||||||
|
|
||||||
private static readonly JsonSerializerOptions ToolJsonOptions = new(McpJsonUtilities.DefaultOptions)
|
private static readonly JsonSerializerOptions ToolJsonOptions = new(McpJsonUtilities.DefaultOptions)
|
||||||
{
|
{
|
||||||
@@ -29,6 +37,7 @@ public static class McpExtensions
|
|||||||
{
|
{
|
||||||
services.Configure<McpOptions>(configuration.GetSection(McpOptions.SectionName));
|
services.Configure<McpOptions>(configuration.GetSection(McpOptions.SectionName));
|
||||||
services.AddSingleton<McpTokenService>();
|
services.AddSingleton<McpTokenService>();
|
||||||
|
services.AddHttpContextAccessor();
|
||||||
|
|
||||||
services.AddAuthentication()
|
services.AddAuthentication()
|
||||||
.AddScheme<AuthenticationSchemeOptions, McpTokenAuthenticationHandler>(McpTokenAuthenticationHandler.SchemeName, null);
|
.AddScheme<AuthenticationSchemeOptions, McpTokenAuthenticationHandler>(McpTokenAuthenticationHandler.SchemeName, null);
|
||||||
@@ -44,20 +53,44 @@ public static class McpExtensions
|
|||||||
})
|
})
|
||||||
.WithHttpTransport(options => options.Stateless = true)
|
.WithHttpTransport(options => options.Stateless = true)
|
||||||
.WithTools<FlypaperTools>(ToolJsonOptions)
|
.WithTools<FlypaperTools>(ToolJsonOptions)
|
||||||
|
.WithTools<ExplanationTools>(ToolJsonOptions)
|
||||||
.WithRequestFilters(filters =>
|
.WithRequestFilters(filters =>
|
||||||
{
|
{
|
||||||
|
filters.AddListToolsFilter(HideWriteTools);
|
||||||
filters.AddCallToolFilter(CheckCall);
|
filters.AddCallToolFilter(CheckCall);
|
||||||
});
|
});
|
||||||
|
|
||||||
return services;
|
return services;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private static McpRequestHandler<ListToolsRequestParams, ListToolsResult> HideWriteTools(McpRequestHandler<ListToolsRequestParams, ListToolsResult> next) =>
|
||||||
|
async (context, ct) =>
|
||||||
|
{
|
||||||
|
var result = await next(context, ct);
|
||||||
|
if (!CanWrite(context.User))
|
||||||
|
{
|
||||||
|
result.Tools = result.Tools.Where(tool => tool.Annotations?.ReadOnlyHint == true).ToList();
|
||||||
|
}
|
||||||
|
|
||||||
|
return result;
|
||||||
|
};
|
||||||
|
|
||||||
private static McpRequestHandler<CallToolRequestParams, CallToolResult> CheckCall(McpRequestHandler<CallToolRequestParams, CallToolResult> next) =>
|
private static McpRequestHandler<CallToolRequestParams, CallToolResult> CheckCall(McpRequestHandler<CallToolRequestParams, CallToolResult> next) =>
|
||||||
async (context, ct) =>
|
async (context, ct) =>
|
||||||
{
|
{
|
||||||
var tool = context.Params?.Name;
|
var tool = context.Params?.Name;
|
||||||
var logger = context.Services?.GetRequiredService<ILoggerFactory>().CreateLogger(typeof(FlypaperTools));
|
var logger = context.Services?.GetRequiredService<ILoggerFactory>().CreateLogger(typeof(FlypaperTools));
|
||||||
|
|
||||||
|
if (context.MatchedPrimitive is McpServerTool { ProtocolTool.Annotations.ReadOnlyHint: not true } && !CanWrite(context.User))
|
||||||
|
{
|
||||||
|
logger?.LogWarning("MCP tool {Tool} was called with a token without write permission", tool);
|
||||||
|
return new CallToolResult
|
||||||
|
{
|
||||||
|
IsError = true,
|
||||||
|
Content = [new TextContentBlock { Text = $"'{tool}' needs a token with write permission. Enable it for this token in the dashboard under Einstellungen > MCP-Zugriff." }]
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
if (context.MatchedPrimitive is McpServerTool matched
|
if (context.MatchedPrimitive is McpServerTool matched
|
||||||
&& McpArgumentCheck.FindProblem(matched.ProtocolTool.InputSchema, context.Params?.Arguments?.AsReadOnly()) is { } problem)
|
&& McpArgumentCheck.FindProblem(matched.ProtocolTool.InputSchema, context.Params?.Arguments?.AsReadOnly()) is { } problem)
|
||||||
{
|
{
|
||||||
@@ -76,6 +109,8 @@ public static class McpExtensions
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
private static bool CanWrite(ClaimsPrincipal? user) => user?.HasClaim(McpTokenAuthenticationHandler.WriteClaim, "true") == true;
|
||||||
|
|
||||||
private static CallToolResult InvalidArguments(string? tool, string message) => new()
|
private static CallToolResult InvalidArguments(string? tool, string message) => new()
|
||||||
{
|
{
|
||||||
IsError = true,
|
IsError = true,
|
||||||
@@ -97,6 +132,18 @@ public static class McpExtensions
|
|||||||
return Results.LocalRedirect("/settings?mcp=revoked#mcp");
|
return Results.LocalRedirect("/settings?mcp=revoked#mcp");
|
||||||
});
|
});
|
||||||
|
|
||||||
|
app.MapPost("/mcp-tokens/{id:int}/write", async (int id, HttpContext context, IAntiforgery antiforgery, McpTokenStore store) =>
|
||||||
|
{
|
||||||
|
if (!await antiforgery.IsRequestValidAsync(context))
|
||||||
|
{
|
||||||
|
return Results.BadRequest();
|
||||||
|
}
|
||||||
|
|
||||||
|
var enabled = (await context.Request.ReadFormAsync(context.RequestAborted))["enabled"] == "true";
|
||||||
|
await store.SetCanWriteAsync(id, enabled, context.RequestAborted);
|
||||||
|
return Results.LocalRedirect("/settings?mcp=" + (enabled ? "write-on" : "write-off") + "#mcp");
|
||||||
|
});
|
||||||
|
|
||||||
return app;
|
return app;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -28,6 +28,22 @@ public sealed record StatsResult(
|
|||||||
int ActiveTraps,
|
int ActiveTraps,
|
||||||
CatchItem? LongestCatch);
|
CatchItem? LongestCatch);
|
||||||
|
|
||||||
|
public sealed record ActiveTrapItem(
|
||||||
|
DateTime StartedAt,
|
||||||
|
double DurationSeconds,
|
||||||
|
long BytesSent,
|
||||||
|
string Strategy,
|
||||||
|
string Ip,
|
||||||
|
string? CountryCode,
|
||||||
|
string? Country,
|
||||||
|
string? City,
|
||||||
|
string? Asn,
|
||||||
|
string? Provider,
|
||||||
|
string? Target,
|
||||||
|
string? UserAgent);
|
||||||
|
|
||||||
|
public sealed record ActiveTrapListResult(int Count, IReadOnlyList<ActiveTrapItem> Traps);
|
||||||
|
|
||||||
public sealed record CatchListResult(int Count, IReadOnlyList<CatchItem> Catches);
|
public sealed record CatchListResult(int Count, IReadOnlyList<CatchItem> Catches);
|
||||||
|
|
||||||
public sealed record TopResultItem(string Key, string? Label, int Catches, double TotalHoldSeconds);
|
public sealed record TopResultItem(string Key, string? Label, int Catches, double TotalHoldSeconds);
|
||||||
@@ -50,3 +66,40 @@ public sealed record IpLookupResult(
|
|||||||
DateTime? LastSeen,
|
DateTime? LastSeen,
|
||||||
IReadOnlyList<CatchItem> Events,
|
IReadOnlyList<CatchItem> Events,
|
||||||
int EventsOmitted);
|
int EventsOmitted);
|
||||||
|
|
||||||
|
public sealed record RuleItem(
|
||||||
|
int Id,
|
||||||
|
string Kind,
|
||||||
|
string Pattern,
|
||||||
|
string Text,
|
||||||
|
int Priority,
|
||||||
|
bool Enabled,
|
||||||
|
string? Note,
|
||||||
|
DateTime CreatedAt,
|
||||||
|
DateTime UpdatedAt,
|
||||||
|
string CreatedBy,
|
||||||
|
int? Catches);
|
||||||
|
|
||||||
|
public sealed record RuleListResult(int Count, IReadOnlyList<RuleItem> Rules);
|
||||||
|
|
||||||
|
public sealed record DeleteResult(int Id, bool Deleted);
|
||||||
|
|
||||||
|
public sealed record UnexplainedItem(string Key, int Catches, IReadOnlyList<string> ExamplePaths, string? ExampleUserAgent, DateTime FirstSeen, DateTime LastSeen);
|
||||||
|
|
||||||
|
public sealed record UnexplainedListResult(string Period, string GroupBy, int UnexplainedCatches, int DistinctPaths, IReadOnlyList<UnexplainedItem> Groups, int GroupsOmitted);
|
||||||
|
|
||||||
|
public sealed record ValueCount(string Value, int Catches);
|
||||||
|
|
||||||
|
public sealed record TakeoverItem(int RuleId, string Pattern, string Text, int Priority, int Catches, IReadOnlyList<string> Examples);
|
||||||
|
|
||||||
|
public sealed record RuleTestItem(
|
||||||
|
string Kind,
|
||||||
|
string Pattern,
|
||||||
|
string Period,
|
||||||
|
int MatchedCatches,
|
||||||
|
int MatchedDistinctValues,
|
||||||
|
IReadOnlyList<ValueCount> Examples,
|
||||||
|
int NewlyExplainedCatches,
|
||||||
|
IReadOnlyList<TakeoverItem> TakesOverFrom,
|
||||||
|
int CatchesNoLongerExplained,
|
||||||
|
IReadOnlyList<string> NoLongerExplainedExamples);
|
||||||
@@ -13,6 +13,8 @@ public sealed class McpTokenAuthenticationHandler(
|
|||||||
{
|
{
|
||||||
public const string SchemeName = "McpToken";
|
public const string SchemeName = "McpToken";
|
||||||
|
|
||||||
|
public const string WriteClaim = "mcp:write";
|
||||||
|
|
||||||
protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
|
protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
|
||||||
{
|
{
|
||||||
var header = Request.Headers.Authorization.ToString();
|
var header = Request.Headers.Authorization.ToString();
|
||||||
@@ -21,12 +23,17 @@ public sealed class McpTokenAuthenticationHandler(
|
|||||||
return AuthenticateResult.NoResult();
|
return AuthenticateResult.NoResult();
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!await tokens.AuthenticateAsync(header["Bearer ".Length..].Trim(), Context.RequestAborted))
|
if (await tokens.AuthenticateAsync(header["Bearer ".Length..].Trim(), Context.RequestAborted) is not { } access)
|
||||||
{
|
{
|
||||||
return AuthenticateResult.Fail("Invalid MCP token.");
|
return AuthenticateResult.Fail("Invalid MCP token.");
|
||||||
}
|
}
|
||||||
|
|
||||||
var identity = new ClaimsIdentity([new Claim(ClaimTypes.Name, "mcp")], SchemeName);
|
var identity = new ClaimsIdentity([new Claim(ClaimTypes.Name, access.Name)], SchemeName);
|
||||||
|
if (access.CanWrite)
|
||||||
|
{
|
||||||
|
identity.AddClaim(new Claim(WriteClaim, "true"));
|
||||||
|
}
|
||||||
|
|
||||||
return AuthenticateResult.Success(new AuthenticationTicket(new ClaimsPrincipal(identity), SchemeName));
|
return AuthenticateResult.Success(new AuthenticationTicket(new ClaimsPrincipal(identity), SchemeName));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -6,33 +6,36 @@ using Microsoft.Extensions.Options;
|
|||||||
|
|
||||||
namespace Flypaper.Web.Mcp;
|
namespace Flypaper.Web.Mcp;
|
||||||
|
|
||||||
|
public sealed record McpAccess(string Name, bool CanWrite);
|
||||||
|
|
||||||
public sealed class McpTokenService(McpTokenStore store, IOptions<McpOptions> options)
|
public sealed class McpTokenService(McpTokenStore store, IOptions<McpOptions> options)
|
||||||
{
|
{
|
||||||
private const string Prefix = "fpm_";
|
private const string Prefix = "fpm_";
|
||||||
|
public const string EnvironmentTokenName = "Umgebungs-Token";
|
||||||
|
|
||||||
public bool UsesEnvironmentToken => !string.IsNullOrEmpty(options.Value.Token);
|
public bool UsesEnvironmentToken => !string.IsNullOrEmpty(options.Value.Token);
|
||||||
|
|
||||||
public async Task<string> CreateAsync(string name, CancellationToken ct = default)
|
public async Task<string> CreateAsync(string name, bool canWrite = false, CancellationToken ct = default)
|
||||||
{
|
{
|
||||||
var token = Prefix + WebEncoders.Base64UrlEncode(RandomNumberGenerator.GetBytes(32));
|
var token = Prefix + WebEncoders.Base64UrlEncode(RandomNumberGenerator.GetBytes(32));
|
||||||
await store.CreateAsync(name, Hash(token), ct);
|
await store.CreateAsync(name, Hash(token), canWrite, ct);
|
||||||
return token;
|
return token;
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task<bool> AuthenticateAsync(string? token, CancellationToken ct = default)
|
public async Task<McpAccess?> AuthenticateAsync(string? token, CancellationToken ct = default)
|
||||||
{
|
{
|
||||||
if (string.IsNullOrEmpty(token))
|
if (string.IsNullOrEmpty(token))
|
||||||
{
|
{
|
||||||
return false;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (UsesEnvironmentToken
|
if (UsesEnvironmentToken
|
||||||
&& CryptographicOperations.FixedTimeEquals(SHA256.HashData(Encoding.UTF8.GetBytes(token)), SHA256.HashData(Encoding.UTF8.GetBytes(options.Value.Token!))))
|
&& CryptographicOperations.FixedTimeEquals(SHA256.HashData(Encoding.UTF8.GetBytes(token)), SHA256.HashData(Encoding.UTF8.GetBytes(options.Value.Token!))))
|
||||||
{
|
{
|
||||||
return true;
|
return new McpAccess(EnvironmentTokenName, false);
|
||||||
}
|
}
|
||||||
|
|
||||||
return await store.UseAsync(Hash(token), ct) is not null;
|
return await store.UseAsync(Hash(token), ct) is { } stored ? new McpAccess(stored.Name, stored.CanWrite) : null;
|
||||||
}
|
}
|
||||||
|
|
||||||
public static string Hash(string token) => Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(token)));
|
public static string Hash(string token) => Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(token)));
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ using Flypaper.Storage;
|
|||||||
using Flypaper.Web;
|
using Flypaper.Web;
|
||||||
using Flypaper.Web.Auth;
|
using Flypaper.Web.Auth;
|
||||||
using Flypaper.Web.Components;
|
using Flypaper.Web.Components;
|
||||||
|
using Flypaper.Web.Explanations;
|
||||||
using Flypaper.Web.Health;
|
using Flypaper.Web.Health;
|
||||||
using Flypaper.Web.Mcp;
|
using Flypaper.Web.Mcp;
|
||||||
using Microsoft.AspNetCore.Authentication.Cookies;
|
using Microsoft.AspNetCore.Authentication.Cookies;
|
||||||
@@ -74,6 +75,7 @@ app.MapStaticAssets().AllowAnonymous();
|
|||||||
app.MapAuthEndpoints();
|
app.MapAuthEndpoints();
|
||||||
app.MapHealthEndpoint();
|
app.MapHealthEndpoint();
|
||||||
app.MapFlypaperMcp();
|
app.MapFlypaperMcp();
|
||||||
|
app.MapExplanationEndpoints();
|
||||||
app.MapRazorComponents<App>();
|
app.MapRazorComponents<App>();
|
||||||
|
|
||||||
await app.RunAsync();
|
await app.RunAsync();
|
||||||
|
|||||||
@@ -495,10 +495,6 @@ a.button:hover {
|
|||||||
width: 190px;
|
width: 190px;
|
||||||
}
|
}
|
||||||
|
|
||||||
.recent-table .strategy-info div {
|
|
||||||
margin-top: 2px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.recent-table .extra {
|
.recent-table .extra {
|
||||||
display: none;
|
display: none;
|
||||||
margin-top: 4px;
|
margin-top: 4px;
|
||||||
@@ -1649,3 +1645,36 @@ button.danger-text {
|
|||||||
align-items: center;
|
align-items: center;
|
||||||
gap: 6px;
|
gap: 6px;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.recent-table .explain {
|
||||||
|
color: var(--text);
|
||||||
|
white-space: normal;
|
||||||
|
}
|
||||||
|
|
||||||
|
.recent-table .explain p {
|
||||||
|
margin: 2px 0 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.recent-table .explain .muted {
|
||||||
|
color: var(--muted);
|
||||||
|
}
|
||||||
|
|
||||||
|
.inline-form {
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 8px;
|
||||||
|
margin: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.rule-table td {
|
||||||
|
vertical-align: top;
|
||||||
|
}
|
||||||
|
|
||||||
|
.rule-table tr.off td {
|
||||||
|
opacity: 0.55;
|
||||||
|
}
|
||||||
|
|
||||||
|
.rule-meta {
|
||||||
|
margin-top: 2px;
|
||||||
|
font-size: 12px;
|
||||||
|
}
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
using System.Net;
|
||||||
|
using Flypaper.Core.Models;
|
||||||
|
using Flypaper.Core.Runtime;
|
||||||
|
using Flypaper.Tests.Fakes;
|
||||||
|
using Shouldly;
|
||||||
|
|
||||||
|
namespace Flypaper.Tests.Core;
|
||||||
|
|
||||||
|
public sealed class ActiveTrapRegistryTests
|
||||||
|
{
|
||||||
|
private static readonly DateTimeOffset Start = new(2026, 11, 22, 10, 0, 0, TimeSpan.Zero);
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Lists_running_traps_with_bytes_and_forgets_finished_ones()
|
||||||
|
{
|
||||||
|
var registry = new ActiveTrapRegistry(new FixedTimeProvider(Start));
|
||||||
|
var first = Context("203.0.113.1", "GET /.env");
|
||||||
|
var second = Context("203.0.113.2", "GET /");
|
||||||
|
|
||||||
|
var handle = registry.Begin(first, "env-drip");
|
||||||
|
registry.Begin(second, "maze-drip");
|
||||||
|
var bytes = 0L;
|
||||||
|
handle.Attach(() => bytes);
|
||||||
|
bytes = 4096;
|
||||||
|
|
||||||
|
var snapshot = registry.Snapshot();
|
||||||
|
|
||||||
|
snapshot.Select(t => t.Ip.ToString()).ShouldBe(["203.0.113.1", "203.0.113.2"], ignoreOrder: true);
|
||||||
|
snapshot.Single(t => t.Ip.ToString() == "203.0.113.1").BytesSent.ShouldBe(4096);
|
||||||
|
snapshot.Single(t => t.Ip.ToString() == "203.0.113.2").BytesSent.ShouldBe(0);
|
||||||
|
snapshot.ShouldAllBe(t => t.StartedAt == Start);
|
||||||
|
|
||||||
|
handle.Dispose();
|
||||||
|
|
||||||
|
registry.Snapshot().Select(t => t.Ip.ToString()).ShouldBe(["203.0.113.2"]);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static TrapContext Context(string ip, string target) =>
|
||||||
|
new(new TrapSession(Guid.NewGuid(), TrapProtocol.Http, IPAddress.Parse(ip), Start), target);
|
||||||
|
}
|
||||||
@@ -126,7 +126,6 @@ public sealed class FileContentTests
|
|||||||
new HtmlDripStrategy(options, random, TimeProvider.System),
|
new HtmlDripStrategy(options, random, TimeProvider.System),
|
||||||
new MazeDripStrategy(MazeKind.Page, options, random, TimeProvider.System),
|
new MazeDripStrategy(MazeKind.Page, options, random, TimeProvider.System),
|
||||||
new MazeDripStrategy(MazeKind.Listing, options, random, TimeProvider.System),
|
new MazeDripStrategy(MazeKind.Listing, options, random, TimeProvider.System),
|
||||||
new TextDripStrategy(options, random, TimeProvider.System),
|
|
||||||
new RobotsStaticStrategy(options),
|
new RobotsStaticStrategy(options),
|
||||||
new MazeDripStrategy(MazeKind.Bait, options, random, TimeProvider.System),
|
new MazeDripStrategy(MazeKind.Bait, options, random, TimeProvider.System),
|
||||||
.. FileContent.Profiles.Select(profile => new FileDripStrategy(profile, options, random, TimeProvider.System))
|
.. FileContent.Profiles.Select(profile => new FileDripStrategy(profile, options, random, TimeProvider.System))
|
||||||
|
|||||||
@@ -6,14 +6,13 @@ namespace Flypaper.Tests.Core;
|
|||||||
|
|
||||||
public sealed class HoldMethodParserTests
|
public sealed class HoldMethodParserTests
|
||||||
{
|
{
|
||||||
private static readonly HoldMethodInput Valid = new("Alternating", "50", "1000", "1", "64", "2048", true, "80", "/Backup-2024, /admin-old/x", "01:00:00", "7", "1.00:00:00");
|
private static readonly HoldMethodInput Valid = new("50", "1000", "1", "64", "2048", true, "80", "/Backup-2024, /admin-old/x", "01:00:00", "7", "1.00:00:00");
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public void Parses_valid_input()
|
public void Parses_valid_input()
|
||||||
{
|
{
|
||||||
var settings = RuntimeSettingsParser.ParseHoldMethod(Valid).Settings.ShouldNotBeNull();
|
var settings = RuntimeSettingsParser.ParseHoldMethod(Valid).Settings.ShouldNotBeNull();
|
||||||
|
|
||||||
settings.Content.ShouldBe(DripContent.Alternating);
|
|
||||||
settings.MinDelay.ShouldBe(TimeSpan.FromMilliseconds(50));
|
settings.MinDelay.ShouldBe(TimeSpan.FromMilliseconds(50));
|
||||||
settings.MaxDelay.ShouldBe(TimeSpan.FromSeconds(1));
|
settings.MaxDelay.ShouldBe(TimeSpan.FromSeconds(1));
|
||||||
settings.MinChunkSize.ShouldBe(1);
|
settings.MinChunkSize.ShouldBe(1);
|
||||||
@@ -26,19 +25,6 @@ public sealed class HoldMethodParserTests
|
|||||||
settings.ToConfiguration().Keys.ShouldBe(SettingKeys.HoldMethod, ignoreOrder: true);
|
settings.ToConfiguration().Keys.ShouldBe(SettingKeys.HoldMethod, ignoreOrder: true);
|
||||||
}
|
}
|
||||||
|
|
||||||
[Theory]
|
|
||||||
[InlineData("html", DripContent.Html)]
|
|
||||||
[InlineData("Text", DripContent.Text)]
|
|
||||||
public void Accepts_content_case_insensitively(string value, DripContent expected) =>
|
|
||||||
RuntimeSettingsParser.ParseHoldMethod(Valid with { Content = value }).Settings.ShouldNotBeNull().Content.ShouldBe(expected);
|
|
||||||
|
|
||||||
[Theory]
|
|
||||||
[InlineData("")]
|
|
||||||
[InlineData("fake-env")]
|
|
||||||
[InlineData("7")]
|
|
||||||
public void Rejects_unknown_content(string value) =>
|
|
||||||
RuntimeSettingsParser.ParseHoldMethod(Valid with { Content = value }).Errors.Keys.ShouldBe([nameof(HoldMethodInput.Content)]);
|
|
||||||
|
|
||||||
[Theory]
|
[Theory]
|
||||||
[InlineData("9", "1000")]
|
[InlineData("9", "1000")]
|
||||||
[InlineData("50", "30001")]
|
[InlineData("50", "30001")]
|
||||||
|
|||||||
@@ -0,0 +1,67 @@
|
|||||||
|
using System.Net;
|
||||||
|
using Flypaper.Core.Abstractions;
|
||||||
|
using Flypaper.Core.Models;
|
||||||
|
using Flypaper.Core.Runtime;
|
||||||
|
using Flypaper.Core.Strategies;
|
||||||
|
using Flypaper.Tests.Fakes;
|
||||||
|
using Shouldly;
|
||||||
|
|
||||||
|
namespace Flypaper.Tests.Core;
|
||||||
|
|
||||||
|
public sealed class LureTests
|
||||||
|
{
|
||||||
|
private static readonly TrapSession Session = new(Guid.NewGuid(), TrapProtocol.Http, IPAddress.Parse("203.0.113.9"), DateTimeOffset.UtcNow);
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData("/", true, "lure-page")]
|
||||||
|
[InlineData("/favicon.ico", true, "lure-icon")]
|
||||||
|
[InlineData("/", false, "html-drip")]
|
||||||
|
[InlineData("/.env", true, "env-drip")]
|
||||||
|
[InlineData("/wp-login.php", true, "wordpress-drip")]
|
||||||
|
public void Lures_only_new_ips_on_start_page_and_favicon(string path, bool isNewIp, string expected) =>
|
||||||
|
Selector(new DripOptions { LinkSpacing = 0 }).Select(new TrapContext(Session, "GET " + path, null, path, isNewIp)).ShouldNotBeNull().Name.ShouldBe(expected);
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Switch_turns_the_lure_off() =>
|
||||||
|
Selector(new DripOptions { LinkSpacing = 0, Lure = false })
|
||||||
|
.Select(new TrapContext(Session, "GET /", null, "/", true)).ShouldNotBeNull().Name.ShouldBe("html-drip");
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task Lure_page_is_one_consistent_wordpress_response()
|
||||||
|
{
|
||||||
|
var channel = new FakeTrapChannel();
|
||||||
|
var strategy = LureStrategy.Page();
|
||||||
|
|
||||||
|
await strategy.RunAsync(channel, default);
|
||||||
|
|
||||||
|
System.Text.Encoding.UTF8.GetString(channel.Writes.SelectMany(w => w).ToArray()).ShouldContain("WordPress 6.4.3");
|
||||||
|
strategy.MediaType.ShouldStartWith("text/html");
|
||||||
|
strategy.Headers["X-Powered-By"].ShouldStartWith("PHP/");
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Lure_icon_is_a_valid_ico_file()
|
||||||
|
{
|
||||||
|
var icon = LureContent.Icon();
|
||||||
|
|
||||||
|
icon[..4].ShouldBe([0, 0, 1, 0]);
|
||||||
|
BitConverter.ToInt32(icon, 14).ShouldBe(icon.Length - 22);
|
||||||
|
LureStrategy.Icon().MediaType.ShouldBe("image/x-icon");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static ConfiguredStrategySelector Selector(DripOptions dripOptions)
|
||||||
|
{
|
||||||
|
var options = TestOptions.Monitor(dripOptions);
|
||||||
|
var random = new SeededRandomSource(5);
|
||||||
|
return new ConfiguredStrategySelector(
|
||||||
|
[
|
||||||
|
new HtmlDripStrategy(options, random, TimeProvider.System),
|
||||||
|
new FileDripStrategy(FileContent.Profiles.First(p => p.Name == "env-drip"), options, random, TimeProvider.System),
|
||||||
|
new FileDripStrategy(FileContent.Profiles.First(p => p.Name == "wordpress-drip"), options, random, TimeProvider.System),
|
||||||
|
LureStrategy.Page(),
|
||||||
|
LureStrategy.Icon()
|
||||||
|
],
|
||||||
|
options,
|
||||||
|
random);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -14,65 +14,34 @@ public sealed class StrategySelectionTests
|
|||||||
private static readonly TrapContext Http =
|
private static readonly TrapContext Http =
|
||||||
new(new TrapSession(Guid.NewGuid(), TrapProtocol.Http, IPAddress.Parse("203.0.113.9"), DateTimeOffset.UtcNow));
|
new(new TrapSession(Guid.NewGuid(), TrapProtocol.Http, IPAddress.Parse("203.0.113.9"), DateTimeOffset.UtcNow));
|
||||||
|
|
||||||
[Theory]
|
|
||||||
[InlineData(DripContent.Html, "html-drip")]
|
|
||||||
[InlineData(DripContent.Text, "text-drip")]
|
|
||||||
public void Selects_the_configured_content(DripContent content, string expected) =>
|
|
||||||
Selector(content).Select(Http).ShouldNotBeNull().Name.ShouldBe(expected);
|
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public void Alternating_picks_both_strategies()
|
public void Selects_the_html_page() =>
|
||||||
{
|
Selector().Select(Http).ShouldNotBeNull().Name.ShouldBe("html-drip");
|
||||||
var selector = Selector(DripContent.Alternating);
|
|
||||||
|
|
||||||
var names = Enumerable.Range(0, 50).Select(_ => selector.Select(Http)!.Name).Distinct().ToList();
|
|
||||||
|
|
||||||
names.ShouldBe(["html-drip", "text-drip"], ignoreOrder: true);
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public void Returns_nothing_for_unsupported_protocols()
|
public void Returns_nothing_for_unsupported_protocols()
|
||||||
{
|
{
|
||||||
var ssh = Http with { Session = Http.Session with { Protocol = TrapProtocol.Ssh } };
|
var ssh = Http with { Session = Http.Session with { Protocol = TrapProtocol.Ssh } };
|
||||||
|
|
||||||
Selector(DripContent.Html).Select(ssh).ShouldBeNull();
|
Selector().Select(ssh).ShouldBeNull();
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public void Strategies_describe_themselves_with_their_parameters()
|
public void Strategies_describe_themselves_with_their_parameters()
|
||||||
{
|
{
|
||||||
var options = TestOptions.Monitor(new DripOptions { MinDelay = TimeSpan.FromMilliseconds(100), MaxDelay = TimeSpan.FromMilliseconds(250), MinChunkSize = 2, MaxChunkSize = 8 });
|
var options = TestOptions.Monitor(new DripOptions { MinDelay = TimeSpan.FromMilliseconds(100), MaxDelay = TimeSpan.FromMilliseconds(250), MinChunkSize = 2, MaxChunkSize = 8 });
|
||||||
var text = new TextDripStrategy(options, new SeededRandomSource(1), TimeProvider.System);
|
var html = new HtmlDripStrategy(options, new SeededRandomSource(1), TimeProvider.System);
|
||||||
|
|
||||||
text.Describe().ShouldBe("text-drip 100-250ms 2-8B head 1024B");
|
html.Describe().ShouldBe("html-drip 100-250ms 2-8B head 1024B");
|
||||||
text.MediaType.ShouldStartWith("text/plain");
|
html.MediaType.ShouldStartWith("text/html");
|
||||||
new HtmlDripStrategy(options, new SeededRandomSource(1), TimeProvider.System).MediaType.ShouldStartWith("text/html");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
private static ConfiguredStrategySelector Selector()
|
||||||
public async Task Text_strategy_drips_plain_text()
|
|
||||||
{
|
{
|
||||||
var strategy = new TextDripStrategy(
|
var options = TestOptions.Monitor(new DripOptions());
|
||||||
TestOptions.Monitor(new DripOptions { MinDelay = TimeSpan.FromMilliseconds(1), MaxDelay = TimeSpan.FromMilliseconds(2), MinChunkSize = 32, MaxChunkSize = 64 }),
|
|
||||||
new SeededRandomSource(3),
|
|
||||||
TimeProvider.System);
|
|
||||||
var channel = new FakeTrapChannel();
|
|
||||||
using var cts = new CancellationTokenSource(TimeSpan.FromMilliseconds(200));
|
|
||||||
|
|
||||||
await Should.ThrowAsync<OperationCanceledException>(() => strategy.RunAsync(channel, cts.Token));
|
|
||||||
|
|
||||||
var text = Encoding.UTF8.GetString(channel.Writes.SelectMany(w => w).ToArray());
|
|
||||||
text.Length.ShouldBeGreaterThan(200);
|
|
||||||
text.ShouldNotContain("<");
|
|
||||||
text.ShouldContain("\n");
|
|
||||||
}
|
|
||||||
|
|
||||||
private static ConfiguredStrategySelector Selector(DripContent content)
|
|
||||||
{
|
|
||||||
var options = TestOptions.Monitor(new DripOptions { Content = content });
|
|
||||||
var random = new SeededRandomSource(11);
|
var random = new SeededRandomSource(11);
|
||||||
return new ConfiguredStrategySelector(
|
return new ConfiguredStrategySelector(
|
||||||
[new HtmlDripStrategy(options, random, TimeProvider.System), new TextDripStrategy(options, random, TimeProvider.System)],
|
[new HtmlDripStrategy(options, random, TimeProvider.System)],
|
||||||
options,
|
options,
|
||||||
random);
|
random);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -179,6 +179,7 @@ public sealed class TrapRunnerTests
|
|||||||
_governor,
|
_governor,
|
||||||
new ConfiguredStrategySelector([drip], dripOptions, random),
|
new ConfiguredStrategySelector([drip], dripOptions, random),
|
||||||
_sink,
|
_sink,
|
||||||
|
new ActiveTrapRegistry(TimeProvider.System),
|
||||||
repeatOffenders ?? new NullRepeatLookup(),
|
repeatOffenders ?? new NullRepeatLookup(),
|
||||||
TestOptions.Monitor(new FlypaperOptions
|
TestOptions.Monitor(new FlypaperOptions
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -14,20 +14,18 @@ namespace Flypaper.Tests.Http;
|
|||||||
public sealed class ContentTypeTests
|
public sealed class ContentTypeTests
|
||||||
{
|
{
|
||||||
[Theory]
|
[Theory]
|
||||||
[InlineData("Html", "/", "text/html; charset=utf-8")]
|
[InlineData("/", "text/html; charset=utf-8")]
|
||||||
[InlineData("Text", "/", "text/plain; charset=utf-8")]
|
[InlineData("/config.json", "application/json")]
|
||||||
[InlineData("Html", "/config.json", "application/json")]
|
[InlineData("/.env", "text/plain; charset=utf-8")]
|
||||||
[InlineData("Html", "/.env", "text/plain; charset=utf-8")]
|
[InlineData("/sitemap.xml", "application/xml")]
|
||||||
[InlineData("Html", "/sitemap.xml", "application/xml")]
|
[InlineData("/SDK/webLanguage", "application/xml")]
|
||||||
[InlineData("Html", "/SDK/webLanguage", "application/xml")]
|
[InlineData("/wp-login.php", "text/html; charset=UTF-8")]
|
||||||
[InlineData("Html", "/wp-login.php", "text/html; charset=UTF-8")]
|
public async Task Trap_answers_with_the_media_type_of_the_selected_strategy(string path, string expected)
|
||||||
public async Task Trap_answers_with_the_media_type_of_the_selected_strategy(string content, string path, string expected)
|
|
||||||
{
|
{
|
||||||
var configuration = new ConfigurationBuilder()
|
var configuration = new ConfigurationBuilder()
|
||||||
.AddInMemoryCollection(new Dictionary<string, string?>
|
.AddInMemoryCollection(new Dictionary<string, string?>
|
||||||
{
|
{
|
||||||
["Flypaper:MaxHoldDuration"] = "00:00:00.100",
|
["Flypaper:MaxHoldDuration"] = "00:00:00.100",
|
||||||
["Flypaper:Drip:Content"] = content,
|
|
||||||
["Flypaper:Drip:MinDelay"] = "00:00:00.005",
|
["Flypaper:Drip:MinDelay"] = "00:00:00.005",
|
||||||
["Flypaper:Drip:MaxDelay"] = "00:00:00.010"
|
["Flypaper:Drip:MaxDelay"] = "00:00:00.010"
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -0,0 +1,71 @@
|
|||||||
|
using System.Net;
|
||||||
|
using System.Text;
|
||||||
|
using Flypaper.Core;
|
||||||
|
using Flypaper.Core.Abstractions;
|
||||||
|
using Flypaper.Core.Models;
|
||||||
|
using Flypaper.Http;
|
||||||
|
using Microsoft.AspNetCore.Builder;
|
||||||
|
using Microsoft.AspNetCore.Http;
|
||||||
|
using Microsoft.Extensions.Configuration;
|
||||||
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
|
using NSubstitute;
|
||||||
|
using Shouldly;
|
||||||
|
|
||||||
|
namespace Flypaper.Tests.Http;
|
||||||
|
|
||||||
|
public sealed class LureTests
|
||||||
|
{
|
||||||
|
[Fact]
|
||||||
|
public async Task Unknown_ip_gets_the_lure_page_with_matching_headers_and_is_not_held()
|
||||||
|
{
|
||||||
|
var (body, headers, sink) = await SendAsync(known: false, "/");
|
||||||
|
|
||||||
|
body.ShouldContain("WordPress");
|
||||||
|
headers["X-Powered-By"].ToString().ShouldStartWith("PHP/");
|
||||||
|
headers.Server.ToString().ShouldBe("nginx");
|
||||||
|
sink.Received(1).Publish(Arg.Is<TrapEvent>(e => e.Strategy == "lure-page" && e.Outcome == TrapOutcome.Completed));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task Known_ip_gets_no_lure()
|
||||||
|
{
|
||||||
|
var (_, headers, sink) = await SendAsync(known: true, "/", cancelAfter: TimeSpan.FromMilliseconds(100));
|
||||||
|
|
||||||
|
headers.ContainsKey("X-Powered-By").ShouldBeFalse();
|
||||||
|
sink.Received(1).Publish(Arg.Is<TrapEvent>(e => e.Strategy != "lure-page"));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static async Task<(string Body, IHeaderDictionary Headers, ITrapEventSink Sink)> SendAsync(bool known, string path, TimeSpan? cancelAfter = null)
|
||||||
|
{
|
||||||
|
var lookup = Substitute.For<IKnownIpLookup>();
|
||||||
|
lookup.HasSeenAsync(Arg.Any<IPAddress>(), Arg.Any<CancellationToken>()).Returns(known);
|
||||||
|
var sink = Substitute.For<ITrapEventSink>();
|
||||||
|
var configuration = new ConfigurationBuilder().Build();
|
||||||
|
var services = new ServiceCollection()
|
||||||
|
.AddLogging()
|
||||||
|
.AddSingleton(sink)
|
||||||
|
.AddSingleton(lookup)
|
||||||
|
.AddFlypaperCore(configuration)
|
||||||
|
.AddFlypaperHttp(configuration)
|
||||||
|
.BuildServiceProvider();
|
||||||
|
|
||||||
|
var app = new ApplicationBuilder(services);
|
||||||
|
app.UseFlypaper();
|
||||||
|
var body = new MemoryStream();
|
||||||
|
using var cts = new CancellationTokenSource();
|
||||||
|
var httpContext = new DefaultHttpContext { RequestServices = services, RequestAborted = cts.Token };
|
||||||
|
httpContext.Connection.RemoteIpAddress = IPAddress.Parse("203.0.113.9");
|
||||||
|
httpContext.Connection.LocalPort = 8080;
|
||||||
|
httpContext.Request.Method = "GET";
|
||||||
|
httpContext.Request.Host = new HostString("example.com");
|
||||||
|
httpContext.Request.Path = path;
|
||||||
|
httpContext.Response.Body = body;
|
||||||
|
if (cancelAfter is { } delay)
|
||||||
|
{
|
||||||
|
cts.CancelAfter(delay);
|
||||||
|
}
|
||||||
|
|
||||||
|
await app.Build()(httpContext);
|
||||||
|
return (Encoding.UTF8.GetString(body.ToArray()), httpContext.Response.Headers, sink);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,4 +1,5 @@
|
|||||||
using Flypaper.Core.Abstractions;
|
using Flypaper.Core.Abstractions;
|
||||||
|
using Flypaper.Core.Runtime;
|
||||||
using Flypaper.Storage.Queries;
|
using Flypaper.Storage.Queries;
|
||||||
using Flypaper.Tests.Fakes;
|
using Flypaper.Tests.Fakes;
|
||||||
using Flypaper.Web.Mcp;
|
using Flypaper.Web.Mcp;
|
||||||
@@ -12,14 +13,42 @@ public sealed class FlypaperToolsTests : IDisposable
|
|||||||
{
|
{
|
||||||
private readonly McpTestData _data = new();
|
private readonly McpTestData _data = new();
|
||||||
private readonly FlypaperTools _tools;
|
private readonly FlypaperTools _tools;
|
||||||
|
private readonly ActiveTrapRegistry _active = new(new FixedTimeProvider(McpTestData.Now));
|
||||||
|
private readonly IIpEnricher _enricher = Substitute.For<IIpEnricher>();
|
||||||
|
|
||||||
public FlypaperToolsTests()
|
public FlypaperToolsTests()
|
||||||
{
|
{
|
||||||
var governor = Substitute.For<IConnectionGovernor>();
|
var governor = Substitute.For<IConnectionGovernor>();
|
||||||
governor.ActiveConnections.Returns(2);
|
governor.ActiveConnections.Returns(2);
|
||||||
_tools = new FlypaperTools(new CatchQueries(_data.Factory), governor, new FixedTimeProvider(McpTestData.Now));
|
_tools = new FlypaperTools(new CatchQueries(_data.Factory), governor, _active, _enricher, new FixedTimeProvider(McpTestData.Now));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void List_active_shows_running_traps_with_origin_and_bytes()
|
||||||
|
{
|
||||||
|
var address = System.Net.IPAddress.Parse("203.0.113.7");
|
||||||
|
_enricher.Lookup(address).Returns(new Flypaper.Core.Models.IpOrigin("DE", "Germany", "Berlin", 3320, "Telekom"));
|
||||||
|
var context = new Flypaper.Core.Models.TrapContext(
|
||||||
|
new Flypaper.Core.Models.TrapSession(Guid.NewGuid(), Flypaper.Core.Models.TrapProtocol.Http, address, McpTestData.Now.AddMinutes(-5)),
|
||||||
|
"GET /.env",
|
||||||
|
"curl/8.7.1");
|
||||||
|
_active.Begin(context, "env-drip").Attach(() => 2048);
|
||||||
|
|
||||||
|
var result = _tools.ListActive();
|
||||||
|
|
||||||
|
var trap = result.Traps.ShouldHaveSingleItem();
|
||||||
|
result.Count.ShouldBe(1);
|
||||||
|
trap.Ip.ShouldBe("203.0.113.7");
|
||||||
|
trap.CountryCode.ShouldBe("DE");
|
||||||
|
trap.Asn.ShouldBe("AS3320");
|
||||||
|
trap.Target.ShouldBe("GET /.env");
|
||||||
|
trap.BytesSent.ShouldBe(2048);
|
||||||
|
trap.DurationSeconds.ShouldBe(0);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void List_active_is_empty_without_traps() => _tools.ListActive().Count.ShouldBe(0);
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public async Task Get_stats_summarizes_the_period()
|
public async Task Get_stats_summarizes_the_period()
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -23,6 +23,9 @@ public sealed class McpEndpointTests : IDisposable
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private static readonly string[] ReadTools =
|
||||||
|
["get_stats", "list_active", "list_catches", "longest_catches", "lookup_ip", "top", "list_explanation_rules", "list_unexplained", "test_explanation_rule"];
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public async Task Rejects_requests_without_token()
|
public async Task Rejects_requests_without_token()
|
||||||
{
|
{
|
||||||
@@ -62,7 +65,7 @@ public sealed class McpEndpointTests : IDisposable
|
|||||||
var tools = await ReadAsync(await client.SendAsync(Rpc("tools/list", token)));
|
var tools = await ReadAsync(await client.SendAsync(Rpc("tools/list", token)));
|
||||||
var listed = tools.GetProperty("result").GetProperty("tools").EnumerateArray().ToList();
|
var listed = tools.GetProperty("result").GetProperty("tools").EnumerateArray().ToList();
|
||||||
listed.Select(t => t.GetProperty("name").GetString())
|
listed.Select(t => t.GetProperty("name").GetString())
|
||||||
.ShouldBe(["get_stats", "list_catches", "longest_catches", "lookup_ip", "top"], ignoreOrder: true);
|
.ShouldBe(ReadTools, ignoreOrder: true);
|
||||||
listed.ShouldAllBe(t => t.GetProperty("annotations").GetProperty("readOnlyHint").GetBoolean());
|
listed.ShouldAllBe(t => t.GetProperty("annotations").GetProperty("readOnlyHint").GetBoolean());
|
||||||
listed.Where(t => !t.TryGetProperty("outputSchema", out var schema) || schema.ValueKind != JsonValueKind.Object).ShouldBeEmpty();
|
listed.Where(t => !t.TryGetProperty("outputSchema", out var schema) || schema.ValueKind != JsonValueKind.Object).ShouldBeEmpty();
|
||||||
|
|
||||||
@@ -77,6 +80,7 @@ public sealed class McpEndpointTests : IDisposable
|
|||||||
{
|
{
|
||||||
{ "get_stats", """{"period":"all"}""" },
|
{ "get_stats", """{"period":"all"}""" },
|
||||||
{ "get_stats", """{"period":"24h"}""" },
|
{ "get_stats", """{"period":"24h"}""" },
|
||||||
|
{ "list_active", """{}""" },
|
||||||
{ "list_catches", """{}""" },
|
{ "list_catches", """{}""" },
|
||||||
{ "list_catches", """{"country":"CN","limit":1}""" },
|
{ "list_catches", """{"country":"CN","limit":1}""" },
|
||||||
{ "top", """{"dimension":"ips","period":"all"}""" },
|
{ "top", """{"dimension":"ips","period":"all"}""" },
|
||||||
@@ -87,7 +91,13 @@ public sealed class McpEndpointTests : IDisposable
|
|||||||
{ "top", """{"dimension":"user_agents","period":"all"}""" },
|
{ "top", """{"dimension":"user_agents","period":"all"}""" },
|
||||||
{ "longest_catches", """{"period":"all"}""" },
|
{ "longest_catches", """{"period":"all"}""" },
|
||||||
{ "lookup_ip", """{"ip":"203.0.113.9"}""" },
|
{ "lookup_ip", """{"ip":"203.0.113.9"}""" },
|
||||||
{ "lookup_ip", """{"ip":"192.0.2.1"}""" }
|
{ "lookup_ip", """{"ip":"192.0.2.1"}""" },
|
||||||
|
{ "list_explanation_rules", """{}""" },
|
||||||
|
{ "list_unexplained", """{}""" },
|
||||||
|
{ "list_unexplained", """{"period":"7d","group_by":"path","limit":5}""" },
|
||||||
|
{ "test_explanation_rule", """{"kind":"target","pattern":"^/\\.env"}""" },
|
||||||
|
{ "test_explanation_rule", """{"kind":"client_info","pattern":"curl","priority":5}""" },
|
||||||
|
{ "test_explanation_rule", """{"kind":"outcome","pattern":"^Rejected$"}""" }
|
||||||
};
|
};
|
||||||
|
|
||||||
[Theory]
|
[Theory]
|
||||||
@@ -134,6 +144,53 @@ public sealed class McpEndpointTests : IDisposable
|
|||||||
result.GetProperty("content")[0].GetProperty("text").GetString().ShouldNotBeNull().ShouldContain(expected, Case.Sensitive);
|
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)
|
private static async Task<Dictionary<string, JsonElement>> OutputSchemasAsync(HttpClient client, string token)
|
||||||
{
|
{
|
||||||
var tools = await ReadAsync(await client.SendAsync(Rpc("tools/list", token)));
|
var tools = await ReadAsync(await client.SendAsync(Rpc("tools/list", token)));
|
||||||
|
|||||||
@@ -21,7 +21,7 @@ public sealed class McpTokenServiceTests : IDisposable
|
|||||||
var token = await service.CreateAsync("Claude Desktop");
|
var token = await service.CreateAsync("Claude Desktop");
|
||||||
|
|
||||||
token.Length.ShouldBeGreaterThan(40);
|
token.Length.ShouldBeGreaterThan(40);
|
||||||
(await service.AuthenticateAsync(token)).ShouldBeTrue();
|
(await service.AuthenticateAsync(token)).ShouldNotBeNull();
|
||||||
var stored = (await _store.ListAsync()).ShouldHaveSingleItem();
|
var stored = (await _store.ListAsync()).ShouldHaveSingleItem();
|
||||||
stored.Name.ShouldBe("Claude Desktop");
|
stored.Name.ShouldBe("Claude Desktop");
|
||||||
stored.TokenHash.ShouldBe(McpTokenService.Hash(token));
|
stored.TokenHash.ShouldBe(McpTokenService.Hash(token));
|
||||||
@@ -35,12 +35,12 @@ public sealed class McpTokenServiceTests : IDisposable
|
|||||||
var service = Create(environmentToken: null);
|
var service = Create(environmentToken: null);
|
||||||
var token = await service.CreateAsync("test");
|
var token = await service.CreateAsync("test");
|
||||||
|
|
||||||
(await service.AuthenticateAsync(null)).ShouldBeFalse();
|
(await service.AuthenticateAsync(null)).ShouldBeNull();
|
||||||
(await service.AuthenticateAsync("")).ShouldBeFalse();
|
(await service.AuthenticateAsync("")).ShouldBeNull();
|
||||||
(await service.AuthenticateAsync(token + "x")).ShouldBeFalse();
|
(await service.AuthenticateAsync(token + "x")).ShouldBeNull();
|
||||||
|
|
||||||
(await _store.RevokeAsync((await _store.ListAsync())[0].Id)).ShouldBeTrue();
|
(await _store.RevokeAsync((await _store.ListAsync())[0].Id)).ShouldBeTrue();
|
||||||
(await service.AuthenticateAsync(token)).ShouldBeFalse();
|
(await service.AuthenticateAsync(token)).ShouldBeNull();
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
@@ -50,9 +50,32 @@ public sealed class McpTokenServiceTests : IDisposable
|
|||||||
var stored = await service.CreateAsync("test");
|
var stored = await service.CreateAsync("test");
|
||||||
|
|
||||||
service.UsesEnvironmentToken.ShouldBeTrue();
|
service.UsesEnvironmentToken.ShouldBeTrue();
|
||||||
(await service.AuthenticateAsync("fixed-token-from-environment")).ShouldBeTrue();
|
(await service.AuthenticateAsync("fixed-token-from-environment")).ShouldNotBeNull();
|
||||||
(await service.AuthenticateAsync(stored)).ShouldBeTrue();
|
(await service.AuthenticateAsync(stored)).ShouldNotBeNull();
|
||||||
(await service.AuthenticateAsync("fixed-token")).ShouldBeFalse();
|
(await service.AuthenticateAsync("fixed-token")).ShouldBeNull();
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task Write_permission_is_granted_per_token_and_can_be_withdrawn()
|
||||||
|
{
|
||||||
|
var service = Create(environmentToken: null);
|
||||||
|
var readOnly = await service.CreateAsync("read");
|
||||||
|
var writer = await service.CreateAsync("write", canWrite: true);
|
||||||
|
|
||||||
|
(await service.AuthenticateAsync(readOnly)).ShouldBe(new McpAccess("read", false));
|
||||||
|
(await service.AuthenticateAsync(writer)).ShouldBe(new McpAccess("write", true));
|
||||||
|
|
||||||
|
var id = (await _store.ListAsync()).Single(t => t.Name == "write").Id;
|
||||||
|
(await _store.SetCanWriteAsync(id, false)).ShouldBeTrue();
|
||||||
|
(await service.AuthenticateAsync(writer)).ShouldBe(new McpAccess("write", false));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task Environment_token_never_has_write_permission()
|
||||||
|
{
|
||||||
|
var service = Create(environmentToken: "fixed-token-from-environment");
|
||||||
|
|
||||||
|
(await service.AuthenticateAsync("fixed-token-from-environment")).ShouldBe(new McpAccess(McpTokenService.EnvironmentTokenName, false));
|
||||||
}
|
}
|
||||||
|
|
||||||
private McpTokenService Create(string? environmentToken) =>
|
private McpTokenService Create(string? environmentToken) =>
|
||||||
|
|||||||
@@ -0,0 +1,222 @@
|
|||||||
|
using Flypaper.Core.Models;
|
||||||
|
using Flypaper.Storage.Entities;
|
||||||
|
using Flypaper.Storage.Explanations;
|
||||||
|
using Flypaper.Tests.Fakes;
|
||||||
|
using Flypaper.Tests.Mcp;
|
||||||
|
using Shouldly;
|
||||||
|
|
||||||
|
namespace Flypaper.Tests.Storage;
|
||||||
|
|
||||||
|
public sealed class ExplanationRuleTests : IDisposable
|
||||||
|
{
|
||||||
|
private readonly McpTestData _data = new();
|
||||||
|
private readonly ExplanationRuleStore _store;
|
||||||
|
private readonly ExplanationQueries _queries;
|
||||||
|
|
||||||
|
public ExplanationRuleTests()
|
||||||
|
{
|
||||||
|
_store = new ExplanationRuleStore(_data.Factory, new FixedTimeProvider(McpTestData.Now));
|
||||||
|
_queries = new ExplanationQueries(_data.Factory, _store);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task Highest_priority_wins_per_kind_and_older_rule_wins_ties()
|
||||||
|
{
|
||||||
|
var broad = await Create(ExplanationKind.Target, @"\.php", "Allgemein PHP", priority: 0);
|
||||||
|
var narrow = await Create(ExplanationKind.Target, @"^/wp-login\.php", "WordPress-Login", priority: 10);
|
||||||
|
var tie = await Create(ExplanationKind.Target, @"\.php", "Zweite PHP-Regel", priority: 0);
|
||||||
|
await Create(ExplanationKind.ClientInfo, "curl", "curl", priority: 0);
|
||||||
|
|
||||||
|
var rules = await _store.GetRuleSetAsync();
|
||||||
|
|
||||||
|
rules.Winner(ExplanationKind.Target, "/wp-login.php")!.Id.ShouldBe(narrow.Id);
|
||||||
|
rules.Winner(ExplanationKind.Target, "/x.php")!.Id.ShouldBe(broad.Id);
|
||||||
|
rules.Matching(ExplanationKind.Target, "/x.php").Select(r => r.Id).ShouldBe([broad.Id, tie.Id]);
|
||||||
|
rules.Winner(ExplanationKind.Target, "/x.html").ShouldBeNull();
|
||||||
|
rules.Winner(ExplanationKind.Outcome, "curl").ShouldBeNull();
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task Matching_is_case_insensitive_and_explains_old_events_without_storing_anything()
|
||||||
|
{
|
||||||
|
await Create(ExplanationKind.Target, @"^/\.GIT/", "Git");
|
||||||
|
await Create(ExplanationKind.ClientInfo, "^zgrab", "Scanner");
|
||||||
|
await Create(ExplanationKind.Outcome, "^ClientAborted [0-9]{2}s$", "Kurz");
|
||||||
|
var rules = await _store.GetRuleSetAsync();
|
||||||
|
await using var db = _data.Factory.CreateDbContext();
|
||||||
|
|
||||||
|
var git = db.TrapEvents.Single(e => e.Target == "GET /.git/config");
|
||||||
|
var zgrab = db.TrapEvents.First(e => e.ClientInfo == "zgrab/0.x");
|
||||||
|
|
||||||
|
rules.Explain(git).Target!.Text.ShouldBe("Git");
|
||||||
|
rules.Explain(zgrab).Client!.Text.ShouldBe("Scanner");
|
||||||
|
rules.Explain(git).Outcome!.Text.ShouldBe("Kurz");
|
||||||
|
rules.Explain(zgrab).Outcome.ShouldBeNull();
|
||||||
|
rules.Explain(git).Client.ShouldBeNull();
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task Rule_set_is_cached_and_changes_invalidate_it()
|
||||||
|
{
|
||||||
|
var rule = await Create(ExplanationKind.Target, "env", "Env");
|
||||||
|
var first = await _store.GetRuleSetAsync();
|
||||||
|
(await _store.GetRuleSetAsync()).ShouldBeSameAs(first);
|
||||||
|
|
||||||
|
await _store.SetEnabledAsync(rule.Id, false);
|
||||||
|
var disabled = await _store.GetRuleSetAsync();
|
||||||
|
disabled.ShouldNotBeSameAs(first);
|
||||||
|
disabled.Winner(ExplanationKind.Target, "/.env").ShouldBeNull();
|
||||||
|
|
||||||
|
await _store.SetEnabledAsync(rule.Id, true);
|
||||||
|
await _store.UpdateAsync(rule.Id, new ExplanationRuleInput(Text: "Neu"));
|
||||||
|
(await _store.GetRuleSetAsync()).Winner(ExplanationKind.Target, "/.env")!.Text.ShouldBe("Neu");
|
||||||
|
|
||||||
|
await _store.DeleteAsync(rule.Id);
|
||||||
|
(await _store.GetRuleSetAsync()).Winner(ExplanationKind.Target, "/.env").ShouldBeNull();
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task Update_changes_only_given_fields_and_clears_note_with_empty_string()
|
||||||
|
{
|
||||||
|
var rule = await _store.CreateAsync(new ExplanationRuleInput(ExplanationKind.Target, "a", "Text", 3, "CVE-1"), "Token A");
|
||||||
|
|
||||||
|
var updated = (await _store.UpdateAsync(rule.Id, new ExplanationRuleInput(Pattern: "b")))!;
|
||||||
|
updated.Pattern.ShouldBe("b");
|
||||||
|
updated.Text.ShouldBe("Text");
|
||||||
|
updated.Priority.ShouldBe(3);
|
||||||
|
updated.Note.ShouldBe("CVE-1");
|
||||||
|
updated.CreatedBy.ShouldBe("Token A");
|
||||||
|
|
||||||
|
(await _store.UpdateAsync(rule.Id, new ExplanationRuleInput(Note: "")))!.Note.ShouldBeNull();
|
||||||
|
(await _store.UpdateAsync(999, new ExplanationRuleInput(Text: "x"))).ShouldBeNull();
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData("")]
|
||||||
|
[InlineData("(unclosed")]
|
||||||
|
[InlineData("(?=lookahead)x")]
|
||||||
|
[InlineData(@"(a)\1")]
|
||||||
|
public async Task Rejects_invalid_or_unsupported_patterns(string pattern) =>
|
||||||
|
await Should.ThrowAsync<ArgumentException>(() => _store.CreateAsync(new ExplanationRuleInput(ExplanationKind.Target, pattern, "Text"), "test"));
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task Rejects_too_long_or_non_plain_values()
|
||||||
|
{
|
||||||
|
ExplanationRuleInput Input(string? pattern = "x", string? text = "Text", int? priority = 0, string? note = null) =>
|
||||||
|
new(ExplanationKind.Target, pattern, text, priority, note);
|
||||||
|
|
||||||
|
await Should.ThrowAsync<ArgumentException>(() => _store.CreateAsync(Input(pattern: new string('a', ExplanationLimits.MaxPatternLength + 1)), "t"));
|
||||||
|
await Should.ThrowAsync<ArgumentException>(() => _store.CreateAsync(Input(text: new string('a', ExplanationLimits.MaxTextLength + 1)), "t"));
|
||||||
|
await Should.ThrowAsync<ArgumentException>(() => _store.CreateAsync(Input(text: "Zeile 1\nZeile 2"), "t"));
|
||||||
|
await Should.ThrowAsync<ArgumentException>(() => _store.CreateAsync(Input(text: " "), "t"));
|
||||||
|
await Should.ThrowAsync<ArgumentException>(() => _store.CreateAsync(Input(note: new string('a', ExplanationLimits.MaxNoteLength + 1)), "t"));
|
||||||
|
await Should.ThrowAsync<ArgumentException>(() => _store.CreateAsync(Input(priority: 5000), "t"));
|
||||||
|
await Should.ThrowAsync<ArgumentException>(() => _store.CreateAsync(new ExplanationRuleInput(null, "x", "Text"), "t"));
|
||||||
|
(await _store.ListAsync()).ShouldBeEmpty();
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task Pattern_cannot_hang_on_catastrophic_input()
|
||||||
|
{
|
||||||
|
await Create(ExplanationKind.Target, "^(a+)+$", "Evil");
|
||||||
|
var rules = await _store.GetRuleSetAsync();
|
||||||
|
|
||||||
|
var started = DateTime.UtcNow;
|
||||||
|
rules.Winner(ExplanationKind.Target, new string('a', 5000) + "!").ShouldBeNull();
|
||||||
|
|
||||||
|
(DateTime.UtcNow - started).ShouldBeLessThan(TimeSpan.FromSeconds(2));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task Lists_unexplained_targets_grouped_by_path_with_counts()
|
||||||
|
{
|
||||||
|
var all = await _queries.FindUnexplainedAsync(null, UnexplainedGrouping.Path, 50);
|
||||||
|
|
||||||
|
all.Catches.ShouldBe(6);
|
||||||
|
all.Groups[0].Key.ShouldBe("/.env");
|
||||||
|
all.Groups[0].Catches.ShouldBe(2);
|
||||||
|
all.Groups[0].ExampleUserAgent.ShouldNotBeNull();
|
||||||
|
|
||||||
|
await Create(ExplanationKind.Target, @"^/\.env$", "Env");
|
||||||
|
var rest = await _queries.FindUnexplainedAsync(null, UnexplainedGrouping.Path, 2);
|
||||||
|
|
||||||
|
rest.Catches.ShouldBe(4);
|
||||||
|
rest.Groups.Count.ShouldBe(2);
|
||||||
|
rest.GroupsOmitted.ShouldBe(2);
|
||||||
|
rest.Groups.Select(g => g.Key).ShouldNotContain("/.env");
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task Pattern_grouping_merges_paths_and_period_limits_the_search()
|
||||||
|
{
|
||||||
|
await using (var db = _data.Factory.CreateDbContext())
|
||||||
|
{
|
||||||
|
foreach (var number in new[] { 1, 2, 3 })
|
||||||
|
{
|
||||||
|
db.TrapEvents.Add(TrapEventEntity.From(new TrapEvent(
|
||||||
|
Guid.NewGuid(), TrapProtocol.Http, System.Net.IPAddress.Parse("203.0.113.1"), "html-drip",
|
||||||
|
McpTestData.Now.AddMinutes(-number), McpTestData.Now, 1000, TrapOutcome.ClientAborted, $"GET /backup/{number}.zip", "agent")));
|
||||||
|
}
|
||||||
|
|
||||||
|
await db.SaveChangesAsync();
|
||||||
|
}
|
||||||
|
|
||||||
|
var result = await _queries.FindUnexplainedAsync(McpTestData.Now.AddHours(-1).UtcDateTime, UnexplainedGrouping.Pattern, 10);
|
||||||
|
|
||||||
|
var group = result.Groups.Single(g => g.Key == "/backup/{n}.zip");
|
||||||
|
group.Catches.ShouldBe(3);
|
||||||
|
group.ExamplePaths.Count.ShouldBe(3);
|
||||||
|
result.Groups.Select(g => g.Key).ShouldNotContain("/wp-login.php");
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task Test_reports_matches_newly_explained_takeovers_and_losses()
|
||||||
|
{
|
||||||
|
var existing = await Create(ExplanationKind.Target, @"\.env", "Allgemein", priority: 0);
|
||||||
|
|
||||||
|
var weaker = await _queries.TestAsync(ExplanationKind.Target, @"^/\.env$", 0, null, null);
|
||||||
|
weaker.Catches.ShouldBe(2);
|
||||||
|
weaker.NewlyExplained.ShouldBe(0);
|
||||||
|
weaker.TakesOver.ShouldBeEmpty();
|
||||||
|
|
||||||
|
var stronger = await _queries.TestAsync(ExplanationKind.Target, @"^/\.env$", 5, null, null);
|
||||||
|
stronger.TakesOver.ShouldHaveSingleItem().Rule.Id.ShouldBe(existing.Id);
|
||||||
|
stronger.TakesOver[0].Catches.ShouldBe(2);
|
||||||
|
|
||||||
|
var fresh = await _queries.TestAsync(ExplanationKind.Target, @"wp-login", 0, null, null);
|
||||||
|
fresh.Catches.ShouldBe(1);
|
||||||
|
fresh.NewlyExplained.ShouldBe(1);
|
||||||
|
fresh.Examples.ShouldHaveSingleItem().Value.ShouldBe("/wp-login.php");
|
||||||
|
|
||||||
|
var narrowed = await _queries.TestAsync(ExplanationKind.Target, @"^/nothing$", 0, existing.Id, null);
|
||||||
|
narrowed.Lost.ShouldBe(2);
|
||||||
|
narrowed.LostExamples.ShouldBe(["/.env"]);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task Test_matches_client_info_and_outcome_text()
|
||||||
|
{
|
||||||
|
(await _queries.TestAsync(ExplanationKind.ClientInfo, "^curl/", 0, null, null)).Catches.ShouldBe(2);
|
||||||
|
(await _queries.TestAsync(ExplanationKind.Outcome, "^Rejected$", 0, null, null)).Catches.ShouldBe(1);
|
||||||
|
(await _queries.TestAsync(ExplanationKind.Outcome, @"^ClientAborted \d{1,2}s$", 0, null, null)).Catches.ShouldBe(2);
|
||||||
|
await Should.ThrowAsync<ArgumentException>(() => _queries.TestAsync(ExplanationKind.Target, "(", 0, null, null));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task Counts_hits_per_rule_including_disabled_ones()
|
||||||
|
{
|
||||||
|
var env = await Create(ExplanationKind.Target, @"^/\.env$", "Env");
|
||||||
|
var off = await Create(ExplanationKind.ClientInfo, "^curl", "curl");
|
||||||
|
await _store.SetEnabledAsync(off.Id, false);
|
||||||
|
|
||||||
|
var hits = await _queries.CountHitsAsync();
|
||||||
|
|
||||||
|
hits[env.Id].ShouldBe(2);
|
||||||
|
hits[off.Id].ShouldBe(2);
|
||||||
|
}
|
||||||
|
|
||||||
|
private Task<ExplanationRuleEntity> Create(ExplanationKind kind, string pattern, string text, int priority = 0) =>
|
||||||
|
_store.CreateAsync(new ExplanationRuleInput(kind, pattern, text, priority), "test");
|
||||||
|
|
||||||
|
public void Dispose() => _data.Dispose();
|
||||||
|
}
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
using Flypaper.Core.Models;
|
||||||
|
using Flypaper.Storage.Explanations;
|
||||||
|
using Shouldly;
|
||||||
|
|
||||||
|
namespace Flypaper.Tests.Storage;
|
||||||
|
|
||||||
|
public sealed class ExplanationTextTests
|
||||||
|
{
|
||||||
|
[Theory]
|
||||||
|
[InlineData("GET 188.103.168.113/.git/HEAD", "/.git/HEAD")]
|
||||||
|
[InlineData("GET anticarnist.de/", "/")]
|
||||||
|
[InlineData("GET /", "/")]
|
||||||
|
[InlineData("GET /x.php?a=1/2", "/x.php?a=1/2")]
|
||||||
|
[InlineData("GET _/boaform/admin", "/boaform/admin")]
|
||||||
|
[InlineData("GET example.com", "/")]
|
||||||
|
[InlineData("POST example.com:8080/api?x=/y", "/api?x=/y")]
|
||||||
|
[InlineData("raw", "raw")]
|
||||||
|
[InlineData(null, null)]
|
||||||
|
public void Extracts_the_path_without_method_and_host(string? target, string? expected) =>
|
||||||
|
ExplanationText.Path(target).ShouldBe(expected);
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData(TrapOutcome.ClientAborted, 9400, "ClientAborted 9s")]
|
||||||
|
[InlineData(TrapOutcome.Timeout, 60000, "Timeout 60s")]
|
||||||
|
[InlineData(TrapOutcome.Completed, 999, "Completed 0s")]
|
||||||
|
[InlineData(TrapOutcome.Rejected, 0, "Rejected")]
|
||||||
|
public void Describes_outcome_and_whole_seconds(TrapOutcome outcome, long milliseconds, string expected) =>
|
||||||
|
ExplanationText.Outcome(outcome, milliseconds).ShouldBe(expected);
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData("/wp-content/uploads/2024/05/x.php?v=3", "/wp-content/uploads/{n}/{n}/x.php")]
|
||||||
|
[InlineData("/a/0123456789abcdef/b", "/a/{hex}/b")]
|
||||||
|
[InlineData("/.env", "/.env")]
|
||||||
|
public void Merges_paths_that_differ_only_in_numbers(string path, string expected) =>
|
||||||
|
ExplanationText.PathShape(path).ShouldBe(expected);
|
||||||
|
}
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
using System.Net;
|
||||||
|
using Flypaper.Core.Models;
|
||||||
|
using Flypaper.Storage.Entities;
|
||||||
|
using Flypaper.Storage.Queries;
|
||||||
|
using Flypaper.Tests.Mcp;
|
||||||
|
using Shouldly;
|
||||||
|
|
||||||
|
namespace Flypaper.Tests.Storage;
|
||||||
|
|
||||||
|
public sealed class KnownIpLookupTests : IDisposable
|
||||||
|
{
|
||||||
|
private readonly McpTestData _data = new();
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task Knows_only_ips_with_a_stored_catch()
|
||||||
|
{
|
||||||
|
using (var db = _data.Factory.CreateDbContext())
|
||||||
|
{
|
||||||
|
var started = McpTestData.Now.AddHours(-2);
|
||||||
|
db.TrapEvents.Add(TrapEventEntity.From(new TrapEvent(
|
||||||
|
Guid.NewGuid(), TrapProtocol.Http, IPAddress.Parse("2001:db8::7"), "lure-page", started, started.AddSeconds(1), 100, TrapOutcome.Completed, "GET /", null)));
|
||||||
|
db.SaveChanges();
|
||||||
|
}
|
||||||
|
|
||||||
|
var lookup = new KnownIpLookup(_data.Factory);
|
||||||
|
|
||||||
|
(await lookup.HasSeenAsync(IPAddress.Parse("2001:db8::7"), default)).ShouldBeTrue();
|
||||||
|
(await lookup.HasSeenAsync(IPAddress.Parse("203.0.113.99"), default)).ShouldBeFalse();
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Dispose() => _data.Dispose();
|
||||||
|
}
|
||||||
@@ -3,6 +3,7 @@ using Flypaper.Core.Models;
|
|||||||
using Flypaper.Storage.Entities;
|
using Flypaper.Storage.Entities;
|
||||||
using Flypaper.Web.Components.Shared;
|
using Flypaper.Web.Components.Shared;
|
||||||
using Flypaper.Storage.Dashboard;
|
using Flypaper.Storage.Dashboard;
|
||||||
|
using Flypaper.Storage.Explanations;
|
||||||
using Flypaper.Tests.Fakes;
|
using Flypaper.Tests.Fakes;
|
||||||
using Flypaper.Tests.Mcp;
|
using Flypaper.Tests.Mcp;
|
||||||
using Shouldly;
|
using Shouldly;
|
||||||
@@ -13,8 +14,9 @@ public sealed class RecentCatchesTests : IDisposable
|
|||||||
{
|
{
|
||||||
private readonly McpTestData _data = new();
|
private readonly McpTestData _data = new();
|
||||||
private readonly DashboardQueries _queries;
|
private readonly DashboardQueries _queries;
|
||||||
|
private readonly ExplanationRuleStore _rules;
|
||||||
|
|
||||||
public RecentCatchesTests() => _queries = new DashboardQueries(_data.Factory, new FixedTimeProvider(McpTestData.Now));
|
public RecentCatchesTests() => _queries = new DashboardQueries(_data.Factory, new FixedTimeProvider(McpTestData.Now), _rules = new ExplanationRuleStore(_data.Factory, new FixedTimeProvider(McpTestData.Now)));
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public async Task Without_filters_returns_all_events_newest_first()
|
public async Task Without_filters_returns_all_events_newest_first()
|
||||||
@@ -47,6 +49,19 @@ public sealed class RecentCatchesTests : IDisposable
|
|||||||
recent.Total.ShouldBe(expected);
|
recent.Total.ShouldBe(expected);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task Unexplained_filter_keeps_only_targets_without_an_enabled_target_rule()
|
||||||
|
{
|
||||||
|
(await _queries.GetRecentAsync(new RecentFilter(Unexplained: true))).Total.ShouldBe(6);
|
||||||
|
|
||||||
|
await _rules.CreateAsync(new ExplanationRuleInput(ExplanationKind.Target, @"^/\.env$", "Sucht nach Zugangsdaten."), "test");
|
||||||
|
var recent = await _queries.GetRecentAsync(new RecentFilter(Unexplained: true));
|
||||||
|
|
||||||
|
recent.Total.ShouldBe(4);
|
||||||
|
recent.Items.Select(e => e.Target).ShouldNotContain("GET /.env");
|
||||||
|
recent.Items.Select(e => e.StartedAt).ShouldBeInOrder(SortDirection.Descending);
|
||||||
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public async Task Matches_strategy_exactly()
|
public async Task Matches_strategy_exactly()
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -89,10 +89,9 @@ public sealed class SettingsOverrideTests : IDisposable
|
|||||||
var store = host.Services.GetRequiredService<RuntimeSettingsStore>();
|
var store = host.Services.GetRequiredService<RuntimeSettingsStore>();
|
||||||
string[] holdKeys = [.. SettingKeys.HoldMethod];
|
string[] holdKeys = [.. SettingKeys.HoldMethod];
|
||||||
|
|
||||||
await store.SaveAsync(new HoldMethodSettings(DripContent.Text, TimeSpan.FromMilliseconds(200), TimeSpan.FromSeconds(2), 8, 16, 256, false, 0, "/trap-a/", TimeSpan.FromMinutes(5), 7, TimeSpan.FromHours(24)));
|
await store.SaveAsync(new HoldMethodSettings(TimeSpan.FromMilliseconds(200), TimeSpan.FromSeconds(2), 8, 16, 256, false, 0, "/trap-a/", TimeSpan.FromMinutes(5), 7, TimeSpan.FromHours(24)));
|
||||||
await store.SaveAsync(new RuntimeSettings(50, 4, 90, true));
|
await store.SaveAsync(new RuntimeSettings(50, 4, 90, true));
|
||||||
|
|
||||||
drip.CurrentValue.Content.ShouldBe(DripContent.Text);
|
|
||||||
drip.CurrentValue.MinDelay.ShouldBe(TimeSpan.FromMilliseconds(200));
|
drip.CurrentValue.MinDelay.ShouldBe(TimeSpan.FromMilliseconds(200));
|
||||||
drip.CurrentValue.MaxChunkSize.ShouldBe(16);
|
drip.CurrentValue.MaxChunkSize.ShouldBe(16);
|
||||||
drip.CurrentValue.HeadStartSize.ShouldBe(256);
|
drip.CurrentValue.HeadStartSize.ShouldBe(256);
|
||||||
@@ -103,13 +102,12 @@ public sealed class SettingsOverrideTests : IDisposable
|
|||||||
core.CurrentValue.MaxConnections.ShouldBe(50);
|
core.CurrentValue.MaxConnections.ShouldBe(50);
|
||||||
(await store.HasOverridesAsync(holdKeys)).ShouldBeTrue();
|
(await store.HasOverridesAsync(holdKeys)).ShouldBeTrue();
|
||||||
|
|
||||||
await store.SaveAsync(new HoldMethodSettings(DripContent.Text, TimeSpan.FromMilliseconds(200), TimeSpan.FromSeconds(2), 8, 16, 256, false, 0, "", TimeSpan.FromMinutes(5), 0, TimeSpan.FromHours(2)));
|
await store.SaveAsync(new HoldMethodSettings(TimeSpan.FromMilliseconds(200), TimeSpan.FromSeconds(2), 8, 16, 256, false, 0, "", TimeSpan.FromMinutes(5), 0, TimeSpan.FromHours(2)));
|
||||||
drip.CurrentValue.BaitPaths.ShouldBe("");
|
drip.CurrentValue.BaitPaths.ShouldBe("");
|
||||||
|
|
||||||
await store.ResetAsync(holdKeys);
|
await store.ResetAsync(holdKeys);
|
||||||
drip.CurrentValue.BaitPaths.ShouldBe(BaitPaths.Default);
|
drip.CurrentValue.BaitPaths.ShouldBe(BaitPaths.Default);
|
||||||
|
|
||||||
drip.CurrentValue.Content.ShouldBe(DripContent.Html);
|
|
||||||
drip.CurrentValue.MinDelay.ShouldBe(TimeSpan.FromMilliseconds(50));
|
drip.CurrentValue.MinDelay.ShouldBe(TimeSpan.FromMilliseconds(50));
|
||||||
core.CurrentValue.MaxHoldDuration.ShouldBe(TimeSpan.FromHours(1));
|
core.CurrentValue.MaxHoldDuration.ShouldBe(TimeSpan.FromHours(1));
|
||||||
core.CurrentValue.MaxConnections.ShouldBe(50);
|
core.CurrentValue.MaxConnections.ShouldBe(50);
|
||||||
|
|||||||
@@ -75,4 +75,17 @@ public sealed class DashboardFilterTests
|
|||||||
new DashboardFilter().NextLimit.ShouldBe(100);
|
new DashboardFilter().NextLimit.ShouldBe(100);
|
||||||
new DashboardFilter(Limit: 400).NextLimit.ShouldBe(RecentFilter.MaxLimit);
|
new DashboardFilter(Limit: 400).NextLimit.ShouldBe(RecentFilter.MaxLimit);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData("ohne", true)]
|
||||||
|
[InlineData("OHNE", true)]
|
||||||
|
[InlineData("alle", false)]
|
||||||
|
[InlineData(null, false)]
|
||||||
|
public void Parses_the_unexplained_filter_and_keeps_it_in_the_link(string? value, bool expected)
|
||||||
|
{
|
||||||
|
var filter = DashboardFilter.Parse(null, null, null, null, null, null, null, null, null, value);
|
||||||
|
|
||||||
|
filter.ToRecentFilter().Unexplained.ShouldBe(expected);
|
||||||
|
filter.Href().Contains("erklaerung=ohne").ShouldBe(expected);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -46,7 +46,8 @@ public sealed class StrategyNamesTests
|
|||||||
string[] names =
|
string[] names =
|
||||||
[
|
[
|
||||||
MazeDripStrategy.PageName, MazeDripStrategy.ListingName, MazeDripStrategy.BaitName,
|
MazeDripStrategy.PageName, MazeDripStrategy.ListingName, MazeDripStrategy.BaitName,
|
||||||
HtmlDripStrategy.StrategyName, TextDripStrategy.StrategyName, RobotsStaticStrategy.StrategyName,
|
HtmlDripStrategy.StrategyName, RobotsStaticStrategy.StrategyName,
|
||||||
|
LureStrategy.PageName, LureStrategy.IconName,
|
||||||
.. FileContent.Profiles.Select(profile => profile.Name)
|
.. FileContent.Profiles.Select(profile => profile.Name)
|
||||||
];
|
];
|
||||||
|
|
||||||
|
|||||||
Reference in new issue
Block a user