Make the hold method configurable in the dashboard

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
TomandClaude Opus 5.5 committed 2026-11-15 19:05:21 +01:00
1 parent 9a56fc5b48
commit 6b9bf3cd5f
40 files changed
+815 -134

No files matched your search

+15
View File
@@ -6,6 +6,21 @@ All notable changes to Flypaper are documented in this file. The format follows
## [Unreleased] ## [Unreleased]
### Added
- Settings section "Haltemethode": content (HTML filler text, random plain text or alternating
per catch), pause and chunk size ranges and the maximum hold time, with an estimate of the
bandwidth per trapped connection and its own reset button. Changes apply to the next catch
without a restart.
- Plain-text drip strategy (`text-drip`), served as `text/plain`.
- Each catch stores its strategy with the parameters in use, e.g. `text-drip 50-1000ms 1-64B`;
MCP results include it as `strategy`.
### Changed
- The maximum hold time moved from the general settings to "Haltemethode".
- Saving one settings section no longer resets the values saved in another.
### Removed ### Removed
- Trap paths and known hosts, with their settings, the `Flypaper__Http__KnownHosts` and - Trap paths and known hosts, with their settings, the `Flypaper__Http__KnownHosts` and
+1 -1
View File
@@ -99,7 +99,7 @@ Nothing is required. The most useful optional environment variables:
| `Flypaper__Http__TrustedProxies__0` | Proxy IP or CIDR allowed to set `X-Real-IP` (default: private networks) | | `Flypaper__Http__TrustedProxies__0` | Proxy IP or CIDR allowed to set `X-Real-IP` (default: private networks) |
| `TZ` | Time zone for the dashboard | | `TZ` | Time zone for the dashboard |
Limits and retention are changed on the dashboard's settings page. All variables Hold method, limits and retention are changed on the dashboard's settings page. All variables
and settings: [docs/configuration.md](docs/configuration.md). and settings: [docs/configuration.md](docs/configuration.md).
## Security ## Security
+6 -2
View File
@@ -20,6 +20,7 @@ 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` |
| `TZ` | Time zone for the dashboard | UTC | | `TZ` | Time zone for the dashboard | UTC |
@@ -30,11 +31,14 @@ The defaults of the runtime settings below can also be set this way, e.g.
## Runtime settings ## Runtime settings
Changed on the dashboard's settings page, stored in the database, effective immediately. The Changed on the dashboard's settings page, stored in the database, effective immediately. The
reset button removes all saved values. general reset button removes all saved values; the hold method section has its own reset.
| Setting | Default | | Setting | Default |
|---|---| |---|---|
| Maximum hold time per catch | `01:00:00` | | 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: chunk size, min and max (1 to 4096 bytes) | 1 / 64 bytes |
| Hold method: maximum hold time per catch | `01:00:00` |
| Maximum connections overall | `1000` | | Maximum connections overall | `1000` |
| Maximum connections per IP | `10` | | Maximum connections per IP | `10` |
| Keep catches (days, `0` = forever) | `90` | | Keep catches (days, `0` = forever) | `90` |
+3 -2
View File
@@ -31,13 +31,14 @@ 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 with irregular timing - **Slow delivery** of endless generated HTML or plain text (or both, alternating per catch)
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
catches with expandable details; login with an admin password catches with expandable details; login with an admin password
- **GeoIP**: country, city and ASN per catch from DB-IP Lite, downloaded and refreshed - **GeoIP**: country, city and ASN per catch from DB-IP Lite, downloaded and refreshed
monthly; existing catches are filled in once the databases are available monthly; existing catches are filled in once the databases are available
- **Settings page**: limits and retention, changed at runtime - **Settings page**: hold method, limits and retention, changed at runtime
without a restart without a restart
- **Retention**: old catches are deleted daily (90 days by default); catches from private - **Retention**: old catches are deleted daily (90 days by default); catches from private
networks are not stored by default; buttons to delete private or all catches networks are not stored by default; buttons to delete private or all catches
@@ -0,0 +1,8 @@
namespace Flypaper.Core.Abstractions;
public interface IStrategyDetails
{
string MediaType { get; }
string Describe();
}
+2 -1
View File
@@ -19,7 +19,8 @@ public static class FlypaperCoreExtensions
services.TryAddSingleton<IConnectionGovernor, ConnectionGovernor>(); services.TryAddSingleton<IConnectionGovernor, ConnectionGovernor>();
services.TryAddSingleton<IRandomSource, SystemRandomSource>(); services.TryAddSingleton<IRandomSource, SystemRandomSource>();
services.TryAddEnumerable(ServiceDescriptor.Singleton<ITarpitStrategy, HtmlDripStrategy>()); services.TryAddEnumerable(ServiceDescriptor.Singleton<ITarpitStrategy, HtmlDripStrategy>());
services.TryAddSingleton<ITrapStrategySelector, ProtocolStrategySelector>(); services.TryAddEnumerable(ServiceDescriptor.Singleton<ITarpitStrategy, TextDripStrategy>());
services.TryAddSingleton<ITrapStrategySelector, ConfiguredStrategySelector>();
services.TryAddSingleton<TrapRunner>(); services.TryAddSingleton<TrapRunner>();
services.TryAddSingleton<IIpEnricher, NullIpEnricher>(); services.TryAddSingleton<IIpEnricher, NullIpEnricher>();
@@ -0,0 +1,28 @@
using Flypaper.Core.Abstractions;
using Flypaper.Core.Models;
using Flypaper.Core.Strategies;
using Microsoft.Extensions.Options;
namespace Flypaper.Core.Runtime;
public sealed class ConfiguredStrategySelector(
IEnumerable<ITarpitStrategy> strategies,
IOptionsMonitor<DripOptions> options,
IRandomSource random) : ITrapStrategySelector
{
public ITarpitStrategy? Select(TrapContext context)
{
var candidates = strategies.Where(strategy => strategy.Supports(context.Session.Protocol)).ToList();
string[] wanted = options.CurrentValue.Content switch
{
DripContent.Text => [TextDripStrategy.StrategyName],
DripContent.Alternating => [HtmlDripStrategy.StrategyName, TextDripStrategy.StrategyName],
_ => [HtmlDripStrategy.StrategyName]
};
var matching = candidates.Where(strategy => wanted.Contains(strategy.Name)).ToList();
return matching.Count == 0
? candidates.FirstOrDefault()
: matching[random.Next(0, matching.Count)];
}
}
@@ -1,10 +0,0 @@
using Flypaper.Core.Abstractions;
using Flypaper.Core.Models;
namespace Flypaper.Core.Runtime;
public sealed class ProtocolStrategySelector(IEnumerable<ITarpitStrategy> strategies) : ITrapStrategySelector
{
public ITarpitStrategy? Select(TrapContext context) =>
strategies.FirstOrDefault(strategy => strategy.Supports(context.Session.Protocol));
}
+4 -3
View File
@@ -17,7 +17,7 @@ public sealed partial class TrapRunner(
{ {
public async Task<TrapOutcome> RunAsync( public async Task<TrapOutcome> RunAsync(
TrapContext context, TrapContext context,
Func<CancellationToken, ValueTask<ITrapChannel>> openChannel, Func<ITarpitStrategy, CancellationToken, ValueTask<ITrapChannel>> openChannel,
CancellationToken ct) CancellationToken ct)
{ {
var session = context.Session; var session = context.Session;
@@ -30,6 +30,7 @@ public sealed partial class TrapRunner(
} }
using var _ = lease; using var _ = lease;
var description = strategy is IStrategyDetails details ? details.Describe() : strategy.Name;
using var hold = new CancellationTokenSource(options.CurrentValue.MaxHoldDuration, timeProvider); using var hold = new CancellationTokenSource(options.CurrentValue.MaxHoldDuration, timeProvider);
using var linked = CancellationTokenSource.CreateLinkedTokenSource(ct, hold.Token); using var linked = CancellationTokenSource.CreateLinkedTokenSource(ct, hold.Token);
@@ -37,7 +38,7 @@ public sealed partial class TrapRunner(
var outcome = TrapOutcome.Completed; var outcome = TrapOutcome.Completed;
try try
{ {
channel = new CountingTrapChannel(await openChannel(linked.Token)); channel = new CountingTrapChannel(await openChannel(strategy, linked.Token));
await strategy.RunAsync(channel, linked.Token); await strategy.RunAsync(channel, linked.Token);
} }
catch (OperationCanceledException) when (linked.IsCancellationRequested) catch (OperationCanceledException) when (linked.IsCancellationRequested)
@@ -51,7 +52,7 @@ public sealed partial class TrapRunner(
outcome = TrapOutcome.ClientAborted; outcome = TrapOutcome.ClientAborted;
} }
Publish(context, strategy.Name, channel?.BytesSent ?? 0, outcome); Publish(context, description, channel?.BytesSent ?? 0, outcome);
return outcome; return outcome;
} }
@@ -0,0 +1,41 @@
using System.Globalization;
using Flypaper.Core.Strategies;
namespace Flypaper.Core.Settings;
public sealed record HoldMethodSettings(
DripContent Content,
TimeSpan MinDelay,
TimeSpan MaxDelay,
int MinChunkSize,
int MaxChunkSize,
TimeSpan MaxHoldDuration)
{
public double BytesPerSecond => AverageBytesPerSecond(MinDelay, MaxDelay, MinChunkSize, MaxChunkSize);
public IReadOnlyDictionary<string, string> ToConfiguration() => new Dictionary<string, string>
{
[SettingKeys.DripContent] = Content.ToString(),
[SettingKeys.DripMinDelay] = MinDelay.ToString("c", CultureInfo.InvariantCulture),
[SettingKeys.DripMaxDelay] = MaxDelay.ToString("c", CultureInfo.InvariantCulture),
[SettingKeys.DripMinChunkSize] = MinChunkSize.ToString(CultureInfo.InvariantCulture),
[SettingKeys.DripMaxChunkSize] = MaxChunkSize.ToString(CultureInfo.InvariantCulture),
[SettingKeys.MaxHoldDuration] = MaxHoldDuration.ToString("c", CultureInfo.InvariantCulture)
};
public static double AverageBytesPerSecond(TimeSpan minDelay, TimeSpan maxDelay, int minChunkSize, int maxChunkSize)
{
var averageDelay = (minDelay + maxDelay).TotalSeconds / 2;
return averageDelay <= 0 ? 0 : (minChunkSize + maxChunkSize) / 2d / averageDelay;
}
}
public sealed record HoldMethodInput(
string? Content,
string? MinDelayMs,
string? MaxDelayMs,
string? MinChunkSize,
string? MaxChunkSize,
string? MaxHoldDuration);
public sealed record HoldMethodParseResult(HoldMethodSettings? Settings, IReadOnlyDictionary<string, string> Errors);
@@ -5,7 +5,6 @@ namespace Flypaper.Core.Settings;
public sealed record RuntimeSettings( public sealed record RuntimeSettings(
int MaxConnections, int MaxConnections,
int MaxConnectionsPerIp, int MaxConnectionsPerIp,
TimeSpan MaxHoldDuration,
int RetentionDays, int RetentionDays,
bool IgnorePrivateNetworks) bool IgnorePrivateNetworks)
{ {
@@ -13,7 +12,6 @@ public sealed record RuntimeSettings(
{ {
[SettingKeys.MaxConnections] = MaxConnections.ToString(CultureInfo.InvariantCulture), [SettingKeys.MaxConnections] = MaxConnections.ToString(CultureInfo.InvariantCulture),
[SettingKeys.MaxConnectionsPerIp] = MaxConnectionsPerIp.ToString(CultureInfo.InvariantCulture), [SettingKeys.MaxConnectionsPerIp] = MaxConnectionsPerIp.ToString(CultureInfo.InvariantCulture),
[SettingKeys.MaxHoldDuration] = MaxHoldDuration.ToString("c", CultureInfo.InvariantCulture),
[SettingKeys.RetentionDays] = RetentionDays.ToString(CultureInfo.InvariantCulture), [SettingKeys.RetentionDays] = RetentionDays.ToString(CultureInfo.InvariantCulture),
[SettingKeys.IgnorePrivateNetworks] = IgnorePrivateNetworks ? "true" : "false" [SettingKeys.IgnorePrivateNetworks] = IgnorePrivateNetworks ? "true" : "false"
}; };
@@ -3,6 +3,5 @@ namespace Flypaper.Core.Settings;
public sealed record RuntimeSettingsInput( public sealed record RuntimeSettingsInput(
string? MaxConnections, string? MaxConnections,
string? MaxConnectionsPerIp, string? MaxConnectionsPerIp,
string? MaxHoldDuration,
string? RetentionDays, string? RetentionDays,
bool IgnorePrivateNetworks); bool IgnorePrivateNetworks);
@@ -1,4 +1,5 @@
using System.Globalization; using System.Globalization;
using Flypaper.Core.Strategies;
namespace Flypaper.Core.Settings; namespace Flypaper.Core.Settings;
@@ -9,12 +10,14 @@ public static class RuntimeSettingsParser
private static readonly TimeSpan MinHold = TimeSpan.FromSeconds(1); private static readonly TimeSpan MinHold = TimeSpan.FromSeconds(1);
private static readonly TimeSpan MaxHold = TimeSpan.FromDays(7); private static readonly TimeSpan MaxHold = TimeSpan.FromDays(7);
private const int MinDelayMs = 10;
private const int MaxDelayMs = 30_000;
private const int MaxChunkSize = 4096;
public static RuntimeSettingsParseResult Parse(RuntimeSettingsInput input) public static RuntimeSettingsParseResult Parse(RuntimeSettingsInput input)
{ {
var errors = new Dictionary<string, string>(); var errors = new Dictionary<string, string>();
var hold = ParseTimeSpan(input.MaxHoldDuration, nameof(input.MaxHoldDuration), MinHold, MaxHold, errors);
var maxConnections = ParseInt(input.MaxConnections, nameof(input.MaxConnections), 1, MaxLimit, errors); var maxConnections = ParseInt(input.MaxConnections, nameof(input.MaxConnections), 1, MaxLimit, errors);
var perIp = ParseInt(input.MaxConnectionsPerIp, nameof(input.MaxConnectionsPerIp), 1, MaxLimit, errors); var perIp = ParseInt(input.MaxConnectionsPerIp, nameof(input.MaxConnectionsPerIp), 1, MaxLimit, errors);
var retention = ParseInt(input.RetentionDays, nameof(input.RetentionDays), 0, MaxRetentionDays, errors); var retention = ParseInt(input.RetentionDays, nameof(input.RetentionDays), 0, MaxRetentionDays, errors);
@@ -33,12 +36,55 @@ public static class RuntimeSettingsParser
var settings = new RuntimeSettings( var settings = new RuntimeSettings(
maxConnections!.Value, maxConnections!.Value,
perIp!.Value, perIp!.Value,
hold!.Value,
retention!.Value, retention!.Value,
input.IgnorePrivateNetworks); input.IgnorePrivateNetworks);
return new RuntimeSettingsParseResult(settings, errors); return new RuntimeSettingsParseResult(settings, errors);
} }
public static HoldMethodParseResult ParseHoldMethod(HoldMethodInput input)
{
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 maxDelay = ParseInt(input.MaxDelayMs, nameof(input.MaxDelayMs), MinDelayMs, MaxDelayMs, errors);
var minChunk = ParseInt(input.MinChunkSize, nameof(input.MinChunkSize), 1, MaxChunkSize, errors);
var maxChunk = ParseInt(input.MaxChunkSize, nameof(input.MaxChunkSize), 1, MaxChunkSize, errors);
var hold = ParseTimeSpan(input.MaxHoldDuration, nameof(input.MaxHoldDuration), MinHold, MaxHold, errors);
if (minDelay > maxDelay)
{
errors[nameof(input.MaxDelayMs)] = "Darf nicht kleiner sein als das Minimum.";
}
if (minChunk > maxChunk)
{
errors[nameof(input.MaxChunkSize)] = "Darf nicht kleiner sein als das Minimum.";
}
if (errors.Count > 0)
{
return new HoldMethodParseResult(null, errors);
}
return new HoldMethodParseResult(
new HoldMethodSettings(
content!.Value,
TimeSpan.FromMilliseconds(minDelay!.Value),
TimeSpan.FromMilliseconds(maxDelay!.Value),
minChunk!.Value,
maxChunk!.Value,
hold!.Value),
errors);
}
private static TimeSpan? ParseTimeSpan( private static TimeSpan? ParseTimeSpan(
string? raw, string? raw,
string field, string field,
+13 -8
View File
@@ -7,13 +7,18 @@ public static class SettingKeys
public const string MaxHoldDuration = "Flypaper:MaxHoldDuration"; public const string MaxHoldDuration = "Flypaper:MaxHoldDuration";
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 DripMaxDelay = "Flypaper:Drip:MaxDelay";
public const string DripMinChunkSize = "Flypaper:Drip:MinChunkSize";
public const string DripMaxChunkSize = "Flypaper:Drip:MaxChunkSize";
public static readonly IReadOnlySet<string> All = new HashSet<string>(StringComparer.OrdinalIgnoreCase) public static readonly IReadOnlyList<string> General =
{ [MaxConnections, MaxConnectionsPerIp, IgnorePrivateNetworks, RetentionDays];
MaxConnections,
MaxConnectionsPerIp, public static readonly IReadOnlyList<string> HoldMethod =
MaxHoldDuration, [DripContent, DripMinDelay, DripMaxDelay, DripMinChunkSize, DripMaxChunkSize, MaxHoldDuration];
IgnorePrivateNetworks,
RetentionDays public static readonly IReadOnlySet<string> All =
}; new HashSet<string>(General.Concat(HoldMethod), StringComparer.OrdinalIgnoreCase);
} }
@@ -0,0 +1,8 @@
namespace Flypaper.Core.Strategies;
public enum DripContent
{
Html,
Text,
Alternating
}
@@ -4,6 +4,8 @@ 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);
@@ -0,0 +1,38 @@
using System.Globalization;
using Flypaper.Core.Abstractions;
using Flypaper.Core.Models;
using Microsoft.Extensions.Options;
namespace Flypaper.Core.Strategies;
public abstract class DripStrategy(
IOptionsMonitor<DripOptions> options,
IRandomSource random,
TimeProvider timeProvider) : ITarpitStrategy, IStrategyDetails
{
public abstract string Name { get; }
public abstract string MediaType { get; }
public bool Supports(TrapProtocol protocol) => protocol == TrapProtocol.Http;
public string Describe()
{
var current = options.CurrentValue;
return string.Create(
CultureInfo.InvariantCulture,
$"{Name} {current.MinDelay.TotalMilliseconds:0}-{current.MaxDelay.TotalMilliseconds:0}ms {current.MinChunkSize}-{current.MaxChunkSize}B");
}
public async Task RunAsync(ITrapChannel channel, CancellationToken ct)
{
foreach (var step in DripSchedule.Create(Content(random), random, options.CurrentValue))
{
ct.ThrowIfCancellationRequested();
await channel.WriteAsync(step.Chunk, ct);
await Task.Delay(step.Delay, timeProvider, ct);
}
}
protected abstract IEnumerable<string> Content(IRandomSource random);
}
+5 -27
View File
@@ -14,24 +14,6 @@ public static class HtmlContent
a { color: #0b5cad; } a { color: #0b5cad; }
"""; """;
private static readonly string[] Vocabulary =
[
"lorem", "ipsum", "dolor", "sit", "amet", "consectetur", "adipiscing", "elit", "sed", "do", "eiusmod",
"tempor", "incididunt", "ut", "labore", "et", "dolore", "magna", "aliqua", "enim", "ad", "minim",
"veniam", "quis", "nostrud", "exercitation", "ullamco", "laboris", "nisi", "aliquip", "ex", "ea",
"commodo", "consequat", "duis", "aute", "irure", "in", "reprehenderit", "voluptate", "velit", "esse",
"cillum", "fugiat", "nulla", "pariatur", "excepteur", "sint", "occaecat", "cupidatat", "non", "proident",
"sunt", "culpa", "qui", "officia", "deserunt", "mollit", "anim", "id", "est", "laborum", "praesent",
"luctus", "vitae", "semper", "facilisis", "integer", "nec", "odio", "mauris", "massa", "vestibulum",
"lacinia", "arcu", "eget", "nunc", "tristique", "fermentum", "pellentesque", "habitant", "morbi",
"senectus", "netus", "malesuada", "fames", "turpis", "egestas", "porttitor", "rhoncus", "dapibus",
"ornare", "sapien", "volutpat", "blandit", "aliquam", "etiam", "erat", "velit", "scelerisque",
"viverra", "orci", "sagittis", "eu", "tellus", "cras", "pulvinar", "mattis", "pharetra", "convallis",
"posuere", "morbi", "leo", "urna", "molestie", "at", "elementum", "sodales", "neque", "gravida",
"dictum", "fusce", "ultrices", "placerat", "euismod", "quam", "suspendisse", "potenti", "nullam",
"accumsan", "tincidunt", "varius", "sollicitudin", "imperdiet", "hendrerit", "bibendum", "cursus"
];
private static readonly string[] Sections = private static readonly string[] Sections =
["docs", "blog", "wiki", "support", "products", "archive", "news", "help", "files", "guides", "kb", "releases"]; ["docs", "blog", "wiki", "support", "products", "archive", "news", "help", "files", "guides", "kb", "releases"];
@@ -78,7 +60,7 @@ public static class HtmlContent
var count = random.Next(3, 7); var count = random.Next(3, 7);
for (var i = 0; i < count; i++) for (var i = 0; i < count; i++)
{ {
builder.Append($"<a href=\"/{Pick(random, Sections)}/\">{Capitalize(Pick(random, Vocabulary))}</a>\n"); builder.Append($"<a href=\"/{Pick(random, Sections)}/\">{LoremText.Capitalize(LoremText.Word(random))}</a>\n");
} }
return builder.Append("</nav>\n").ToString(); return builder.Append("</nav>\n").ToString();
@@ -145,8 +127,8 @@ public static class HtmlContent
continue; continue;
} }
var word = Pick(random, Vocabulary); var word = LoremText.Word(random);
builder.Append(i == 0 ? Capitalize(word) : word); builder.Append(i == 0 ? LoremText.Capitalize(word) : word);
} }
return builder.Append(random.Next(0, 10) == 0 ? '?' : '.').ToString(); return builder.Append(random.Next(0, 10) == 0 ? '?' : '.').ToString();
@@ -154,17 +136,13 @@ public static class HtmlContent
private static string Link(IRandomSource random, int words) private static string Link(IRandomSource random, int words)
{ {
var text = Phrase(random, words); var text = LoremText.Phrase(random, words);
var slug = text.Replace(' ', '-'); var slug = text.Replace(' ', '-');
return $"<a href=\"/{Pick(random, Sections)}/{slug}\">{text}</a>"; return $"<a href=\"/{Pick(random, Sections)}/{slug}\">{text}</a>";
} }
private static string Title(IRandomSource random, int min, int max) => Capitalize(Phrase(random, random.Next(min, max + 1))); private static string Title(IRandomSource random, int min, int max) => LoremText.Capitalize(LoremText.Phrase(random, random.Next(min, max + 1)));
private static string Phrase(IRandomSource random, int count) =>
string.Join(' ', Enumerable.Range(0, count).Select(_ => Pick(random, Vocabulary)));
private static string Pick(IRandomSource random, string[] values) => values[random.Next(0, values.Length)]; private static string Pick(IRandomSource random, string[] values) => values[random.Next(0, values.Length)];
private static string Capitalize(string value) => value.Length == 0 ? value : char.ToUpperInvariant(value[0]) + value[1..];
} }
@@ -1,5 +1,4 @@
using Flypaper.Core.Abstractions; using Flypaper.Core.Abstractions;
using Flypaper.Core.Models;
using Microsoft.Extensions.Options; using Microsoft.Extensions.Options;
namespace Flypaper.Core.Strategies; namespace Flypaper.Core.Strategies;
@@ -7,19 +6,13 @@ namespace Flypaper.Core.Strategies;
public sealed class HtmlDripStrategy( public sealed class HtmlDripStrategy(
IOptionsMonitor<DripOptions> options, IOptionsMonitor<DripOptions> options,
IRandomSource random, IRandomSource random,
TimeProvider timeProvider) : ITarpitStrategy TimeProvider timeProvider) : DripStrategy(options, random, timeProvider)
{ {
public string Name => "html-drip"; public const string StrategyName = "html-drip";
public bool Supports(TrapProtocol protocol) => protocol == TrapProtocol.Http; public override string Name => StrategyName;
public async Task RunAsync(ITrapChannel channel, CancellationToken ct) public override string MediaType => "text/html; charset=utf-8";
{
foreach (var step in DripSchedule.Create(HtmlContent.Generate(random), random, options.CurrentValue)) protected override IEnumerable<string> Content(IRandomSource random) => HtmlContent.Generate(random);
{
ct.ThrowIfCancellationRequested();
await channel.WriteAsync(step.Chunk, ct);
await Task.Delay(step.Delay, timeProvider, ct);
}
}
} }
+50
View File
@@ -0,0 +1,50 @@
using System.Text;
using Flypaper.Core.Abstractions;
namespace Flypaper.Core.Strategies;
internal static class LoremText
{
private static readonly string[] Vocabulary =
[
"lorem", "ipsum", "dolor", "sit", "amet", "consectetur", "adipiscing", "elit", "sed", "do", "eiusmod",
"tempor", "incididunt", "ut", "labore", "et", "dolore", "magna", "aliqua", "enim", "ad", "minim",
"veniam", "quis", "nostrud", "exercitation", "ullamco", "laboris", "nisi", "aliquip", "ex", "ea",
"commodo", "consequat", "duis", "aute", "irure", "in", "reprehenderit", "voluptate", "velit", "esse",
"cillum", "fugiat", "nulla", "pariatur", "excepteur", "sint", "occaecat", "cupidatat", "non", "proident",
"sunt", "culpa", "qui", "officia", "deserunt", "mollit", "anim", "id", "est", "laborum", "praesent",
"luctus", "vitae", "semper", "facilisis", "integer", "nec", "odio", "mauris", "massa", "vestibulum",
"lacinia", "arcu", "eget", "nunc", "tristique", "fermentum", "pellentesque", "habitant", "morbi",
"senectus", "netus", "malesuada", "fames", "turpis", "egestas", "porttitor", "rhoncus", "dapibus",
"ornare", "sapien", "volutpat", "blandit", "aliquam", "etiam", "erat", "velit", "scelerisque",
"viverra", "orci", "sagittis", "eu", "tellus", "cras", "pulvinar", "mattis", "pharetra", "convallis",
"posuere", "morbi", "leo", "urna", "molestie", "at", "elementum", "sodales", "neque", "gravida",
"dictum", "fusce", "ultrices", "placerat", "euismod", "quam", "suspendisse", "potenti", "nullam",
"accumsan", "tincidunt", "varius", "sollicitudin", "imperdiet", "hendrerit", "bibendum", "cursus"
];
public static string Word(IRandomSource random) => Vocabulary[random.Next(0, Vocabulary.Length)];
public static string Phrase(IRandomSource random, int count) =>
string.Join(' ', Enumerable.Range(0, count).Select(_ => Word(random)));
public static string Sentence(IRandomSource random)
{
var builder = new StringBuilder();
var words = random.Next(4, 21);
for (var i = 0; i < words; i++)
{
if (i > 0)
{
builder.Append(i > 2 && random.Next(0, 9) == 0 ? ", " : " ");
}
var word = Word(random);
builder.Append(i == 0 ? Capitalize(word) : word);
}
return builder.Append(random.Next(0, 10) == 0 ? '?' : '.').ToString();
}
public static string Capitalize(string value) => value.Length == 0 ? value : char.ToUpperInvariant(value[0]) + value[1..];
}
@@ -0,0 +1,27 @@
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();
}
}
}
@@ -0,0 +1,18 @@
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) => TextContent.Generate(random);
}
@@ -39,7 +39,7 @@ internal sealed class FlypaperMiddleware(
var outcome = await runner.RunAsync( var outcome = await runner.RunAsync(
trapContext, trapContext,
ct => OpenChannelAsync(context, session, ct), (strategy, ct) => OpenChannelAsync(context, session, strategy, ct),
context.RequestAborted); context.RequestAborted);
if (outcome == TrapOutcome.Rejected && !context.Response.HasStarted) if (outcome == TrapOutcome.Rejected && !context.Response.HasStarted)
@@ -59,6 +59,7 @@ internal sealed class FlypaperMiddleware(
private static async ValueTask<ITrapChannel> OpenChannelAsync( private static async ValueTask<ITrapChannel> OpenChannelAsync(
HttpContext context, HttpContext context,
TrapSession session, TrapSession session,
ITarpitStrategy strategy,
CancellationToken ct) CancellationToken ct)
{ {
var minDataRate = context.Features.Get<IHttpMinResponseDataRateFeature>(); var minDataRate = context.Features.Get<IHttpMinResponseDataRateFeature>();
@@ -71,7 +72,7 @@ internal sealed class FlypaperMiddleware(
var response = context.Response; var response = context.Response;
response.StatusCode = StatusCodes.Status200OK; response.StatusCode = StatusCodes.Status200OK;
response.ContentType = "text/html; charset=utf-8"; response.ContentType = strategy is IStrategyDetails details ? details.MediaType : "text/html; charset=utf-8";
response.Headers.CacheControl = "no-store"; response.Headers.CacheControl = "no-store";
response.Headers["X-Accel-Buffering"] = "no"; response.Headers["X-Accel-Buffering"] = "no";
await response.StartAsync(ct); await response.StartAsync(ct);
@@ -166,6 +166,7 @@ public sealed class CatchQueries(IDbContextFactory<FlypaperDbContext> dbContextF
e.DurationMs / 1000d, e.DurationMs / 1000d,
e.BytesSent, e.BytesSent,
e.Outcome, e.Outcome,
e.Strategy,
e.RemoteIp, e.RemoteIp,
e.CountryCode, e.CountryCode,
e.Country, e.Country,
@@ -9,6 +9,7 @@ public sealed record CatchRecord(
double DurationSeconds, double DurationSeconds,
long BytesSent, long BytesSent,
TrapOutcome Outcome, TrapOutcome Outcome,
string Strategy,
string Ip, string Ip,
string? CountryCode, string? CountryCode,
string? Country, string? Country,
@@ -12,33 +12,42 @@ public sealed partial class RuntimeSettingsStore(
{ {
private static readonly string[] RuntimeKeys = SettingKeys.All.ToArray(); private static readonly string[] RuntimeKeys = SettingKeys.All.ToArray();
public async Task SaveAsync(RuntimeSettings settings, CancellationToken ct = default) public Task SaveAsync(RuntimeSettings settings, CancellationToken ct = default) =>
SaveValuesAsync(settings.ToConfiguration(), ct);
public Task SaveAsync(HoldMethodSettings settings, CancellationToken ct = default) =>
SaveValuesAsync(settings.ToConfiguration(), ct);
public async Task ResetAsync(IReadOnlyCollection<string>? keys = null, CancellationToken ct = default)
{
await using var db = await dbContextFactory.CreateDbContextAsync(ct);
await RuntimeSettings(db, keys).ExecuteDeleteAsync(ct);
Reload();
}
public async Task<bool> HasOverridesAsync(IReadOnlyCollection<string>? keys = null, CancellationToken ct = default)
{
await using var db = await dbContextFactory.CreateDbContextAsync(ct);
return await RuntimeSettings(db, keys).AnyAsync(ct);
}
private async Task SaveValuesAsync(IReadOnlyDictionary<string, string> values, CancellationToken ct)
{ {
await using var db = await dbContextFactory.CreateDbContextAsync(ct); await using var db = await dbContextFactory.CreateDbContextAsync(ct);
await using var transaction = await db.Database.BeginTransactionAsync(ct); await using var transaction = await db.Database.BeginTransactionAsync(ct);
await RuntimeSettings(db).ExecuteDeleteAsync(ct); await RuntimeSettings(db, values.Keys.ToArray()).ExecuteDeleteAsync(ct);
db.Settings.AddRange(settings.ToConfiguration().Select(pair => new SettingEntity { Key = pair.Key, Value = pair.Value })); db.Settings.AddRange(values.Select(pair => new SettingEntity { Key = pair.Key, Value = pair.Value }));
await db.SaveChangesAsync(ct); await db.SaveChangesAsync(ct);
await transaction.CommitAsync(ct); await transaction.CommitAsync(ct);
Reload(); Reload();
} }
public async Task ResetAsync(CancellationToken ct = default) private static IQueryable<SettingEntity> RuntimeSettings(FlypaperDbContext db, IReadOnlyCollection<string>? keys = null)
{ {
await using var db = await dbContextFactory.CreateDbContextAsync(ct); var selected = keys?.Where(key => SettingKeys.All.Contains(key)).ToArray() ?? RuntimeKeys;
await RuntimeSettings(db).ExecuteDeleteAsync(ct); return db.Settings.Where(setting => selected.Contains(setting.Key));
Reload();
} }
public async Task<bool> HasOverridesAsync(CancellationToken ct = default)
{
await using var db = await dbContextFactory.CreateDbContextAsync(ct);
return await RuntimeSettings(db).AnyAsync(ct);
}
private static IQueryable<SettingEntity> RuntimeSettings(FlypaperDbContext db) =>
db.Settings.Where(setting => RuntimeKeys.Contains(setting.Key));
private void Reload() private void Reload()
{ {
if (!source.TryReload()) if (!source.TryReload())
@@ -0,0 +1,16 @@
namespace Flypaper.Web.Components.Pages.Settings;
public sealed class HoldMethodModel
{
public string? Content { get; set; }
public string? MinDelayMs { get; set; }
public string? MaxDelayMs { get; set; }
public string? MinChunkSize { get; set; }
public string? MaxChunkSize { get; set; }
public string? MaxHoldDuration { get; set; }
}
@@ -0,0 +1,156 @@
@using System.Globalization
@using Flypaper.Core
@using Flypaper.Core.Settings
@using Flypaper.Core.Strategies
@using Flypaper.Storage.Settings
@using Microsoft.Extensions.Options
@inject IOptionsMonitor<DripOptions> Drip
@inject IOptionsMonitor<FlypaperOptions> Core
@inject RuntimeSettingsStore Store
@inject NavigationManager Navigation
<section class="card form" id="hold-method">
<header class="section-head">
<h2>Haltemethode</h2>
@if (_hasOverrides)
{
<span class="badge">Überschrieben</span>
}
</header>
@if (Saved == "saved")
{
<div class="banner ok">Gespeichert. Gilt ab dem nächsten Fang.</div>
}
else if (Saved == "reset")
{
<div class="banner ok">Haltemethode auf Standard zurückgesetzt.</div>
}
<EditForm Model="Model" FormName="hold-method" OnSubmit="SaveAsync" action="/settings" class="form">
<label for="drip-content">Inhalt</label>
<InputSelect id="drip-content" @bind-Value="Model!.Content">
<option value="@DripContent.Html">HTML-Fülltext</option>
<option value="@DripContent.Text">Zufallstext (plain text)</option>
<option value="@DripContent.Alternating">Wechselnd (pro Fang zufällig)</option>
</InputSelect>
<FieldError Errors="_errors" Field="@nameof(HoldMethodModel.Content)" />
<div class="grid">
<div>
<label for="drip-min-delay">Pause min. <span class="muted">(ms)</span></label>
<InputText id="drip-min-delay" @bind-Value="Model!.MinDelayMs" class="mono" inputmode="numeric" data-bandwidth-input />
<FieldError Errors="_errors" Field="@nameof(HoldMethodModel.MinDelayMs)" />
</div>
<div>
<label for="drip-max-delay">Pause max. <span class="muted">(ms)</span></label>
<InputText id="drip-max-delay" @bind-Value="Model!.MaxDelayMs" class="mono" inputmode="numeric" data-bandwidth-input />
<FieldError Errors="_errors" Field="@nameof(HoldMethodModel.MaxDelayMs)" />
</div>
<div>
<label for="drip-min-chunk">Paket min. <span class="muted">(Bytes)</span></label>
<InputText id="drip-min-chunk" @bind-Value="Model!.MinChunkSize" class="mono" inputmode="numeric" data-bandwidth-input />
<FieldError Errors="_errors" Field="@nameof(HoldMethodModel.MinChunkSize)" />
</div>
<div>
<label for="drip-max-chunk">Paket max. <span class="muted">(Bytes)</span></label>
<InputText id="drip-max-chunk" @bind-Value="Model!.MaxChunkSize" class="mono" inputmode="numeric" data-bandwidth-input />
<FieldError Errors="_errors" Field="@nameof(HoldMethodModel.MaxChunkSize)" />
</div>
<div>
<label for="hold">Maximale Haltedauer <span class="muted">(hh:mm:ss)</span></label>
<InputText id="hold" @bind-Value="Model!.MaxHoldDuration" class="mono" />
<FieldError Errors="_errors" Field="@nameof(HoldMethodModel.MaxHoldDuration)" />
</div>
</div>
<p class="muted">
Pause 10 ms bis 30 s, Paket 1 bis 4096 Bytes. Ø ca. <strong id="drip-bandwidth">@Bandwidth</strong> Bytes/s pro gefangener Verbindung.
</p>
<div class="actions">
<button type="submit">Speichern</button>
</div>
</EditForm>
<EditForm Model="_resetModel" FormName="hold-method-reset" OnSubmit="ResetAsync" action="/settings" class="danger-zone">
<div class="actions">
<button type="submit" class="secondary" disabled="@(!_hasOverrides)" onclick="return confirm('Haltemethode auf Standard zurücksetzen?')">Auf Standard zurücksetzen</button>
</div>
</EditForm>
</section>
<script src="@Assets["settings.js"]" defer></script>
@code {
private readonly object _resetModel = new();
private IReadOnlyDictionary<string, string> _errors = new Dictionary<string, string>();
private bool _hasOverrides;
[SupplyParameterFromForm(FormName = "hold-method")] private HoldMethodModel? Model { get; set; }
[SupplyParameterFromQuery(Name = "hold")] private string? Saved { get; set; }
private string Bandwidth
{
get
{
var ok = int.TryParse(Model?.MinDelayMs, out var minDelay) & int.TryParse(Model?.MaxDelayMs, out var maxDelay)
& int.TryParse(Model?.MinChunkSize, out var minChunk) & int.TryParse(Model?.MaxChunkSize, out var maxChunk);
if (!ok)
{
return "–";
}
var bytesPerSecond = HoldMethodSettings.AverageBytesPerSecond(
TimeSpan.FromMilliseconds(minDelay), TimeSpan.FromMilliseconds(maxDelay), minChunk, maxChunk);
return bytesPerSecond.ToString(bytesPerSecond < 10 ? "0.0" : "N0", CultureInfo.GetCultureInfo("de-DE"));
}
}
protected override async Task OnInitializedAsync()
{
Model ??= CurrentValues();
_hasOverrides = await Store.HasOverridesAsync(SettingKeys.HoldMethod.ToArray());
}
private async Task SaveAsync()
{
var result = RuntimeSettingsParser.ParseHoldMethod(new HoldMethodInput(
Model!.Content,
Model.MinDelayMs,
Model.MaxDelayMs,
Model.MinChunkSize,
Model.MaxChunkSize,
Model.MaxHoldDuration));
if (result.Settings is null)
{
_errors = result.Errors;
return;
}
await Store.SaveAsync(result.Settings);
Navigation.NavigateTo("/settings?hold=saved#hold-method");
}
private async Task ResetAsync()
{
await Store.ResetAsync(SettingKeys.HoldMethod.ToArray());
Navigation.NavigateTo("/settings?hold=reset#hold-method");
}
private HoldMethodModel CurrentValues()
{
var drip = Drip.CurrentValue;
return new HoldMethodModel
{
Content = drip.Content.ToString(),
MinDelayMs = ((int)drip.MinDelay.TotalMilliseconds).ToString(CultureInfo.InvariantCulture),
MaxDelayMs = ((int)drip.MaxDelay.TotalMilliseconds).ToString(CultureInfo.InvariantCulture),
MinChunkSize = drip.MinChunkSize.ToString(CultureInfo.InvariantCulture),
MaxChunkSize = drip.MaxChunkSize.ToString(CultureInfo.InvariantCulture),
MaxHoldDuration = Core.CurrentValue.MaxHoldDuration.ToString("c", CultureInfo.InvariantCulture)
};
}
}
@@ -6,8 +6,6 @@ public sealed class SettingsModel
public string? MaxConnectionsPerIp { get; set; } public string? MaxConnectionsPerIp { get; set; }
public string? MaxHoldDuration { get; set; }
public string? RetentionDays { get; set; } public string? RetentionDays { get; set; }
public bool IgnorePrivateNetworks { get; set; } public bool IgnorePrivateNetworks { get; set; }
@@ -35,15 +35,12 @@ else if (Saved == "reset")
<div class="banner ok">Auf Standard zurückgesetzt.</div> <div class="banner ok">Auf Standard zurückgesetzt.</div>
} }
<HoldMethodSection />
<EditForm Model="Model" FormName="settings" OnSubmit="Save" action="/settings" class="card form"> <EditForm Model="Model" FormName="settings" OnSubmit="Save" action="/settings" class="card form">
<h2>Anpassbar</h2> <h2>Allgemein</h2>
<div class="grid"> <div class="grid">
<div>
<label for="hold">Maximale Haltedauer <span class="muted">(hh:mm:ss)</span></label>
<InputText id="hold" @bind-Value="Model!.MaxHoldDuration" class="mono" />
<FieldError Errors="_errors" Field="@nameof(SettingsModel.MaxHoldDuration)" />
</div>
<div> <div>
<label for="max">Max. Verbindungen gesamt</label> <label for="max">Max. Verbindungen gesamt</label>
<InputText id="max" @bind-Value="Model!.MaxConnections" class="mono" /> <InputText id="max" @bind-Value="Model!.MaxConnections" class="mono" />
@@ -121,7 +118,6 @@ else if (Saved == "reset")
var result = RuntimeSettingsParser.Parse(new RuntimeSettingsInput( var result = RuntimeSettingsParser.Parse(new RuntimeSettingsInput(
Model!.MaxConnections, Model!.MaxConnections,
Model.MaxConnectionsPerIp, Model.MaxConnectionsPerIp,
Model.MaxHoldDuration,
Model.RetentionDays, Model.RetentionDays,
Model.IgnorePrivateNetworks)); Model.IgnorePrivateNetworks));
@@ -146,7 +142,6 @@ else if (Saved == "reset")
var core = Core.CurrentValue; var core = Core.CurrentValue;
return new SettingsModel return new SettingsModel
{ {
MaxHoldDuration = core.MaxHoldDuration.ToString("c", CultureInfo.InvariantCulture),
MaxConnections = core.MaxConnections.ToString(CultureInfo.InvariantCulture), MaxConnections = core.MaxConnections.ToString(CultureInfo.InvariantCulture),
MaxConnectionsPerIp = core.MaxConnectionsPerIp.ToString(CultureInfo.InvariantCulture), MaxConnectionsPerIp = core.MaxConnectionsPerIp.ToString(CultureInfo.InvariantCulture),
RetentionDays = Retention.CurrentValue.Days.ToString(CultureInfo.InvariantCulture), RetentionDays = Retention.CurrentValue.Days.ToString(CultureInfo.InvariantCulture),
+1
View File
@@ -169,6 +169,7 @@ public sealed class FlypaperTools(CatchQueries queries, IConnectionGovernor gove
Round(record.DurationSeconds), Round(record.DurationSeconds),
record.BytesSent, record.BytesSent,
record.Outcome.ToString(), record.Outcome.ToString(),
record.Strategy,
record.Ip, record.Ip,
record.CountryCode, record.CountryCode,
CountryNames.Display(record.CountryCode, record.Country), CountryNames.Display(record.CountryCode, record.Country),
+1
View File
@@ -7,6 +7,7 @@ public sealed record CatchItem(
double DurationSeconds, double DurationSeconds,
long BytesSent, long BytesSent,
string Outcome, string Outcome,
string Strategy,
string Ip, string Ip,
string? CountryCode, string? CountryCode,
string? Country, string? Country,
+20
View File
@@ -636,3 +636,23 @@ button.danger {
overflow-wrap: anywhere; overflow-wrap: anywhere;
user-select: all; user-select: all;
} }
.section-head {
display: flex;
align-items: center;
gap: 8px;
}
.section-head h2 {
margin: 0;
}
select {
width: 100%;
padding: 8px 10px;
border: 1px solid var(--border);
border-radius: 6px;
background: var(--bg);
color: var(--text);
font: inherit;
}
+23
View File
@@ -0,0 +1,23 @@
(() => {
const value = id => Number.parseInt(document.getElementById(id)?.value ?? "", 10);
const output = document.getElementById("drip-bandwidth");
if (!output) {
return;
}
const update = () => {
const minDelay = value("drip-min-delay");
const maxDelay = value("drip-max-delay");
const minChunk = value("drip-min-chunk");
const maxChunk = value("drip-max-chunk");
const averageDelay = (minDelay + maxDelay) / 2000;
const bytesPerSecond = (minChunk + maxChunk) / 2 / averageDelay;
output.textContent = Number.isFinite(bytesPerSecond) && bytesPerSecond > 0
? bytesPerSecond.toLocaleString("de-DE", { maximumFractionDigits: bytesPerSecond < 10 ? 1 : 0 })
: "–";
};
for (const input of document.querySelectorAll("[data-bandwidth-input]")) {
input.addEventListener("input", update);
}
})();
@@ -0,0 +1,73 @@
using Flypaper.Core.Settings;
using Flypaper.Core.Strategies;
using Shouldly;
namespace Flypaper.Tests.Core;
public sealed class HoldMethodParserTests
{
private static readonly HoldMethodInput Valid = new("Alternating", "50", "1000", "1", "64", "01:00:00");
[Fact]
public void Parses_valid_input()
{
var settings = RuntimeSettingsParser.ParseHoldMethod(Valid).Settings.ShouldNotBeNull();
settings.Content.ShouldBe(DripContent.Alternating);
settings.MinDelay.ShouldBe(TimeSpan.FromMilliseconds(50));
settings.MaxDelay.ShouldBe(TimeSpan.FromSeconds(1));
settings.MinChunkSize.ShouldBe(1);
settings.MaxChunkSize.ShouldBe(64);
settings.MaxHoldDuration.ShouldBe(TimeSpan.FromHours(1));
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]
[InlineData("9", "1000")]
[InlineData("50", "30001")]
[InlineData("x", "1000")]
public void Rejects_delays_out_of_range(string min, string max) =>
RuntimeSettingsParser.ParseHoldMethod(Valid with { MinDelayMs = min, MaxDelayMs = max }).Settings.ShouldBeNull();
[Theory]
[InlineData("0", "64")]
[InlineData("1", "4097")]
public void Rejects_chunk_sizes_out_of_range(string min, string max) =>
RuntimeSettingsParser.ParseHoldMethod(Valid with { MinChunkSize = min, MaxChunkSize = max }).Settings.ShouldBeNull();
[Fact]
public void Requires_minimum_not_above_maximum()
{
var errors = RuntimeSettingsParser.ParseHoldMethod(Valid with { MinDelayMs = "2000", MaxDelayMs = "1000", MinChunkSize = "100", MaxChunkSize = "10" }).Errors;
errors.Keys.ShouldBe([nameof(HoldMethodInput.MaxDelayMs), nameof(HoldMethodInput.MaxChunkSize)], ignoreOrder: true);
}
[Theory]
[InlineData("10")]
[InlineData("00:00:00")]
[InlineData("8.00:00:00")]
public void Rejects_invalid_hold_durations(string value) =>
RuntimeSettingsParser.ParseHoldMethod(Valid with { MaxHoldDuration = value }).Errors.Keys.ShouldBe([nameof(HoldMethodInput.MaxHoldDuration)]);
[Fact]
public void Computes_average_bandwidth()
{
HoldMethodSettings.AverageBytesPerSecond(TimeSpan.FromMilliseconds(50), TimeSpan.FromSeconds(1), 1, 64)
.ShouldBe(61.9, tolerance: 0.1);
HoldMethodSettings.AverageBytesPerSecond(TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1), 10, 10).ShouldBe(10);
}
}
@@ -5,7 +5,7 @@ namespace Flypaper.Tests.Core;
public sealed class RuntimeSettingsParserTests public sealed class RuntimeSettingsParserTests
{ {
private static readonly RuntimeSettingsInput Valid = new("200", "5", "00:30:00", "90", true); private static readonly RuntimeSettingsInput Valid = new("200", "5", "90", true);
[Fact] [Fact]
public void Parses_valid_input() public void Parses_valid_input()
@@ -16,7 +16,6 @@ public sealed class RuntimeSettingsParserTests
var settings = result.Settings.ShouldNotBeNull(); var settings = result.Settings.ShouldNotBeNull();
settings.MaxConnections.ShouldBe(200); settings.MaxConnections.ShouldBe(200);
settings.MaxConnectionsPerIp.ShouldBe(5); settings.MaxConnectionsPerIp.ShouldBe(5);
settings.MaxHoldDuration.ShouldBe(TimeSpan.FromMinutes(30));
settings.RetentionDays.ShouldBe(90); settings.RetentionDays.ShouldBe(90);
settings.IgnorePrivateNetworks.ShouldBeTrue(); settings.IgnorePrivateNetworks.ShouldBeTrue();
} }
@@ -45,19 +44,6 @@ public sealed class RuntimeSettingsParserTests
settings.ToConfiguration()[SettingKeys.IgnorePrivateNetworks].ShouldBe("false"); settings.ToConfiguration()[SettingKeys.IgnorePrivateNetworks].ShouldBe("false");
} }
[Theory]
[InlineData("10")]
[InlineData("abc")]
[InlineData("")]
[InlineData("00:00:00")]
[InlineData("8.00:00:00")]
public void Rejects_invalid_hold_durations(string value)
{
var result = RuntimeSettingsParser.Parse(Valid with { MaxHoldDuration = value });
result.Errors.ShouldContainKey(nameof(RuntimeSettingsInput.MaxHoldDuration));
}
[Theory] [Theory]
[InlineData("0")] [InlineData("0")]
[InlineData("-3")] [InlineData("-3")]
@@ -81,19 +67,11 @@ public sealed class RuntimeSettingsParserTests
result.Errors.Keys.ShouldBe([nameof(RuntimeSettingsInput.MaxConnectionsPerIp)]); result.Errors.Keys.ShouldBe([nameof(RuntimeSettingsInput.MaxConnectionsPerIp)]);
} }
[Fact]
public void Rejects_hold_duration_out_of_range()
{
var result = RuntimeSettingsParser.Parse(Valid with { MaxHoldDuration = "00:00:00.5" });
result.Errors.ShouldContainKey(nameof(RuntimeSettingsInput.MaxHoldDuration));
}
[Fact] [Fact]
public void Exposes_only_whitelisted_configuration_keys() public void Exposes_only_whitelisted_configuration_keys()
{ {
var keys = RuntimeSettingsParser.Parse(Valid).Settings.ShouldNotBeNull().ToConfiguration().Keys; var keys = RuntimeSettingsParser.Parse(Valid).Settings.ShouldNotBeNull().ToConfiguration().Keys;
keys.ShouldBe(SettingKeys.All, ignoreOrder: true); keys.ShouldBe(SettingKeys.General, ignoreOrder: true);
} }
} }
@@ -0,0 +1,79 @@
using System.Net;
using System.Text;
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 StrategySelectionTests
{
private static readonly TrapContext Http =
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]
public void Alternating_picks_both_strategies()
{
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]
public void Returns_nothing_for_unsupported_protocols()
{
var ssh = Http with { Session = Http.Session with { Protocol = TrapProtocol.Ssh } };
Selector(DripContent.Html).Select(ssh).ShouldBeNull();
}
[Fact]
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 text = new TextDripStrategy(options, new SeededRandomSource(1), TimeProvider.System);
text.Describe().ShouldBe("text-drip 100-250ms 2-8B");
text.MediaType.ShouldStartWith("text/plain");
new HtmlDripStrategy(options, new SeededRandomSource(1), TimeProvider.System).MediaType.ShouldStartWith("text/html");
}
[Fact]
public async Task Text_strategy_drips_plain_text()
{
var strategy = new TextDripStrategy(
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);
return new ConfiguredStrategySelector(
[new HtmlDripStrategy(options, random, TimeProvider.System), new TextDripStrategy(options, random, TimeProvider.System)],
options,
random);
}
}
+7 -8
View File
@@ -25,7 +25,7 @@ public sealed class TrapRunnerTests
var outcome = await CreateRunner(TimeSpan.FromSeconds(1)).RunAsync( var outcome = await CreateRunner(TimeSpan.FromSeconds(1)).RunAsync(
Context(), Context(),
_ => (_, _) =>
{ {
opened = true; opened = true;
return ValueTask.FromResult<ITrapChannel>(_channel); return ValueTask.FromResult<ITrapChannel>(_channel);
@@ -59,7 +59,7 @@ public sealed class TrapRunnerTests
var outcome = await CreateRunner(TimeSpan.FromMinutes(1)).RunAsync(Context(), Open, cts.Token); var outcome = await CreateRunner(TimeSpan.FromMinutes(1)).RunAsync(Context(), Open, cts.Token);
outcome.ShouldBe(TrapOutcome.ClientAborted); outcome.ShouldBe(TrapOutcome.ClientAborted);
_sink.Received(1).Publish(Arg.Is<TrapEvent>(e => e.Outcome == TrapOutcome.ClientAborted && e.Strategy == "html-drip")); _sink.Received(1).Publish(Arg.Is<TrapEvent>(e => e.Outcome == TrapOutcome.ClientAborted && e.Strategy == "html-drip 5-20ms 1-64B"));
} }
[Theory] [Theory]
@@ -111,17 +111,16 @@ public sealed class TrapRunnerTests
return lease; return lease;
} }
private ValueTask<ITrapChannel> Open(CancellationToken ct) => ValueTask.FromResult<ITrapChannel>(_channel); private ValueTask<ITrapChannel> Open(ITarpitStrategy strategy, CancellationToken ct) => ValueTask.FromResult<ITrapChannel>(_channel);
private TrapRunner CreateRunner(TimeSpan maxHoldDuration, bool ignorePrivateNetworks = true) private TrapRunner CreateRunner(TimeSpan maxHoldDuration, bool ignorePrivateNetworks = true)
{ {
var drip = new HtmlDripStrategy( var dripOptions = TestOptions.Monitor(new DripOptions { MinDelay = TimeSpan.FromMilliseconds(5), MaxDelay = TimeSpan.FromMilliseconds(20) });
TestOptions.Monitor(new DripOptions { MinDelay = TimeSpan.FromMilliseconds(5), MaxDelay = TimeSpan.FromMilliseconds(20) }), var random = new SeededRandomSource(7);
new SeededRandomSource(7), var drip = new HtmlDripStrategy(dripOptions, random, TimeProvider.System);
TimeProvider.System);
return new TrapRunner( return new TrapRunner(
_governor, _governor,
new ProtocolStrategySelector([drip]), new ConfiguredStrategySelector([drip], dripOptions, random),
_sink, _sink,
TestOptions.Monitor(new FlypaperOptions { MaxHoldDuration = maxHoldDuration, IgnorePrivateNetworks = ignorePrivateNetworks }), TestOptions.Monitor(new FlypaperOptions { MaxHoldDuration = maxHoldDuration, IgnorePrivateNetworks = ignorePrivateNetworks }),
TimeProvider.System, TimeProvider.System,
@@ -0,0 +1,49 @@
using System.Net;
using Flypaper.Core;
using Flypaper.Core.Abstractions;
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 ContentTypeTests
{
[Theory]
[InlineData("Html", "text/html; charset=utf-8")]
[InlineData("Text", "text/plain; charset=utf-8")]
public async Task Trap_answers_with_the_media_type_of_the_selected_strategy(string content, string expected)
{
var configuration = new ConfigurationBuilder()
.AddInMemoryCollection(new Dictionary<string, string?>
{
["Flypaper:MaxHoldDuration"] = "00:00:00.100",
["Flypaper:Drip:Content"] = content,
["Flypaper:Drip:MinDelay"] = "00:00:00.005",
["Flypaper:Drip:MaxDelay"] = "00:00:00.010"
})
.Build();
var services = new ServiceCollection()
.AddLogging()
.AddSingleton(Substitute.For<ITrapEventSink>())
.AddFlypaperCore(configuration)
.AddFlypaperHttp(configuration)
.BuildServiceProvider();
var app = new ApplicationBuilder(services);
app.UseFlypaper();
var context = new DefaultHttpContext { RequestServices = services };
context.Connection.RemoteIpAddress = IPAddress.Parse("203.0.113.9");
context.Connection.LocalPort = 8080;
context.Request.Path = "/";
await app.Build()(context);
context.Response.StatusCode.ShouldBe(StatusCodes.Status200OK);
context.Response.ContentType.ShouldBe(expected);
}
}
@@ -1,5 +1,6 @@
using Flypaper.Core; using Flypaper.Core;
using Flypaper.Core.Settings; using Flypaper.Core.Settings;
using Flypaper.Core.Strategies;
using Flypaper.Http; using Flypaper.Http;
using Flypaper.Storage; using Flypaper.Storage;
using Flypaper.Storage.Entities; using Flypaper.Storage.Entities;
@@ -64,11 +65,10 @@ public sealed class SettingsOverrideTests : IDisposable
var options = host.Services.GetRequiredService<IOptionsMonitor<FlypaperOptions>>(); var options = host.Services.GetRequiredService<IOptionsMonitor<FlypaperOptions>>();
var store = host.Services.GetRequiredService<RuntimeSettingsStore>(); var store = host.Services.GetRequiredService<RuntimeSettingsStore>();
await store.SaveAsync(new RuntimeSettings(50, 4, TimeSpan.FromMinutes(10), 90, false)); await store.SaveAsync(new RuntimeSettings(50, 4, 90, false));
options.CurrentValue.MaxConnections.ShouldBe(50); options.CurrentValue.MaxConnections.ShouldBe(50);
options.CurrentValue.MaxConnectionsPerIp.ShouldBe(4); options.CurrentValue.MaxConnectionsPerIp.ShouldBe(4);
options.CurrentValue.MaxHoldDuration.ShouldBe(TimeSpan.FromMinutes(10));
options.CurrentValue.IgnorePrivateNetworks.ShouldBeFalse(); options.CurrentValue.IgnorePrivateNetworks.ShouldBeFalse();
(await store.HasOverridesAsync()).ShouldBeTrue(); (await store.HasOverridesAsync()).ShouldBeTrue();
@@ -79,6 +79,36 @@ public sealed class SettingsOverrideTests : IDisposable
(await store.HasOverridesAsync()).ShouldBeFalse(); (await store.HasOverridesAsync()).ShouldBeFalse();
} }
[Fact]
public async Task Hold_method_is_saved_and_reset_separately_from_general_settings()
{
var host = BuildHost();
await host.Services.MigrateFlypaperDatabaseAsync();
var core = host.Services.GetRequiredService<IOptionsMonitor<FlypaperOptions>>();
var drip = host.Services.GetRequiredService<IOptionsMonitor<DripOptions>>();
var store = host.Services.GetRequiredService<RuntimeSettingsStore>();
string[] holdKeys = [.. SettingKeys.HoldMethod];
await store.SaveAsync(new HoldMethodSettings(DripContent.Text, TimeSpan.FromMilliseconds(200), TimeSpan.FromSeconds(2), 8, 16, TimeSpan.FromMinutes(5)));
await store.SaveAsync(new RuntimeSettings(50, 4, 90, true));
drip.CurrentValue.Content.ShouldBe(DripContent.Text);
drip.CurrentValue.MinDelay.ShouldBe(TimeSpan.FromMilliseconds(200));
drip.CurrentValue.MaxChunkSize.ShouldBe(16);
core.CurrentValue.MaxHoldDuration.ShouldBe(TimeSpan.FromMinutes(5));
core.CurrentValue.MaxConnections.ShouldBe(50);
(await store.HasOverridesAsync(holdKeys)).ShouldBeTrue();
await store.ResetAsync(holdKeys);
drip.CurrentValue.Content.ShouldBe(DripContent.Html);
drip.CurrentValue.MinDelay.ShouldBe(TimeSpan.FromMilliseconds(50));
core.CurrentValue.MaxHoldDuration.ShouldBe(TimeSpan.FromHours(1));
core.CurrentValue.MaxConnections.ShouldBe(50);
(await store.HasOverridesAsync(holdKeys)).ShouldBeFalse();
(await store.HasOverridesAsync()).ShouldBeTrue();
}
private IHost BuildHost() private IHost BuildHost()
{ {
var builder = Host.CreateApplicationBuilder(new HostApplicationBuilderSettings { DisableDefaults = true }); var builder = Host.CreateApplicationBuilder(new HostApplicationBuilderSettings { DisableDefaults = true });