Add persisted runtime settings page with cookie login
This commit is contained in:
1 parent
b561924efa
commit
37987a394a
43 files changed
+1346
-61
No files matched your search
@@ -4,7 +4,7 @@ using Microsoft.Extensions.Options;
|
||||
|
||||
namespace Flypaper.Core;
|
||||
|
||||
public sealed class ConnectionGovernor(IOptions<FlypaperOptions> options) : IConnectionGovernor
|
||||
public sealed class ConnectionGovernor(IOptionsMonitor<FlypaperOptions> options) : IConnectionGovernor
|
||||
{
|
||||
private readonly Lock _gate = new();
|
||||
private readonly Dictionary<IPAddress, int> _perIp = [];
|
||||
@@ -24,7 +24,7 @@ public sealed class ConnectionGovernor(IOptions<FlypaperOptions> options) : ICon
|
||||
public bool TryAcquire(TrapSession session, [NotNullWhen(true)] out IDisposable? lease)
|
||||
{
|
||||
var ip = Normalize(session.RemoteIp);
|
||||
var limits = options.Value;
|
||||
var limits = options.CurrentValue;
|
||||
|
||||
lock (_gate)
|
||||
{
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
using System.Globalization;
|
||||
|
||||
namespace Flypaper.Core;
|
||||
|
||||
public sealed record RuntimeSettings(
|
||||
IReadOnlyList<string> TrapPaths,
|
||||
TimeSpan DripInterval,
|
||||
int MaxConnections,
|
||||
int MaxConnectionsPerIp,
|
||||
TimeSpan MaxHoldDuration,
|
||||
IReadOnlyList<string> ExtraKnownHosts)
|
||||
{
|
||||
public IReadOnlyDictionary<string, string> ToConfiguration() => new Dictionary<string, string>
|
||||
{
|
||||
[SettingKeys.TrapPaths] = SettingsList.Join(TrapPaths),
|
||||
[SettingKeys.DripInterval] = DripInterval.ToString("c", CultureInfo.InvariantCulture),
|
||||
[SettingKeys.MaxConnections] = MaxConnections.ToString(CultureInfo.InvariantCulture),
|
||||
[SettingKeys.MaxConnectionsPerIp] = MaxConnectionsPerIp.ToString(CultureInfo.InvariantCulture),
|
||||
[SettingKeys.MaxHoldDuration] = MaxHoldDuration.ToString("c", CultureInfo.InvariantCulture),
|
||||
[SettingKeys.ExtraKnownHosts] = SettingsList.Join(ExtraKnownHosts)
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
namespace Flypaper.Core;
|
||||
|
||||
public sealed record RuntimeSettingsInput(
|
||||
string? TrapPaths,
|
||||
string? DripInterval,
|
||||
string? MaxConnections,
|
||||
string? MaxConnectionsPerIp,
|
||||
string? MaxHoldDuration,
|
||||
string? ExtraKnownHosts);
|
||||
|
||||
public sealed record RuntimeSettingsParseResult(RuntimeSettings? Settings, IReadOnlyDictionary<string, string> Errors);
|
||||
@@ -0,0 +1,157 @@
|
||||
using System.Globalization;
|
||||
using System.Text.RegularExpressions;
|
||||
|
||||
namespace Flypaper.Core;
|
||||
|
||||
public static partial class RuntimeSettingsParser
|
||||
{
|
||||
private const int MaxListEntries = 500;
|
||||
private const int MaxPathLength = 256;
|
||||
private const int MaxHostLength = 253;
|
||||
private const int MaxLimit = 100_000;
|
||||
|
||||
private static readonly TimeSpan MinInterval = TimeSpan.FromMilliseconds(100);
|
||||
private static readonly TimeSpan MaxInterval = TimeSpan.FromHours(1);
|
||||
private static readonly TimeSpan MinHold = TimeSpan.FromSeconds(1);
|
||||
private static readonly TimeSpan MaxHold = TimeSpan.FromDays(7);
|
||||
|
||||
[GeneratedRegex(@"^(\*\.)?[A-Za-z0-9]([A-Za-z0-9.\-]*[A-Za-z0-9])?$")]
|
||||
private static partial Regex HostPattern();
|
||||
|
||||
public static RuntimeSettingsParseResult Parse(RuntimeSettingsInput input)
|
||||
{
|
||||
var errors = new Dictionary<string, string>();
|
||||
|
||||
var paths = ParseList(input.TrapPaths, nameof(input.TrapPaths), ValidatePath, errors);
|
||||
var hosts = ParseList(input.ExtraKnownHosts, nameof(input.ExtraKnownHosts), ValidateHost, errors);
|
||||
var interval = ParseTimeSpan(input.DripInterval, nameof(input.DripInterval), MinInterval, MaxInterval, errors);
|
||||
var hold = ParseTimeSpan(input.MaxHoldDuration, nameof(input.MaxHoldDuration), MinHold, MaxHold, errors);
|
||||
var maxConnections = ParseInt(input.MaxConnections, nameof(input.MaxConnections), errors);
|
||||
var perIp = ParseInt(input.MaxConnectionsPerIp, nameof(input.MaxConnectionsPerIp), errors);
|
||||
|
||||
if (maxConnections is { } total && perIp is { } single && single > total
|
||||
&& !errors.ContainsKey(nameof(input.MaxConnectionsPerIp)))
|
||||
{
|
||||
errors[nameof(input.MaxConnectionsPerIp)] = "Darf nicht größer sein als die Gesamtzahl der Verbindungen.";
|
||||
}
|
||||
|
||||
if (errors.Count > 0)
|
||||
{
|
||||
return new RuntimeSettingsParseResult(null, errors);
|
||||
}
|
||||
|
||||
var settings = new RuntimeSettings(paths!, interval!.Value, maxConnections!.Value, perIp!.Value, hold!.Value, hosts!);
|
||||
return new RuntimeSettingsParseResult(settings, errors);
|
||||
}
|
||||
|
||||
private static string[]? ParseList(
|
||||
string? raw,
|
||||
string field,
|
||||
Func<string, string?> validate,
|
||||
Dictionary<string, string> errors)
|
||||
{
|
||||
var lines = (raw ?? string.Empty)
|
||||
.Split(['\r', '\n'], StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries);
|
||||
|
||||
if (lines.Length > MaxListEntries)
|
||||
{
|
||||
errors[field] = $"Höchstens {MaxListEntries} Einträge.";
|
||||
return null;
|
||||
}
|
||||
|
||||
var problems = new List<string>();
|
||||
for (var i = 0; i < lines.Length; i++)
|
||||
{
|
||||
if (validate(lines[i]) is { } problem)
|
||||
{
|
||||
problems.Add($"„{lines[i]}“: {problem}");
|
||||
}
|
||||
}
|
||||
|
||||
if (problems.Count > 0)
|
||||
{
|
||||
errors[field] = string.Join(" ", problems.Take(3)) + (problems.Count > 3 ? $" (+{problems.Count - 3} weitere)" : "");
|
||||
return null;
|
||||
}
|
||||
|
||||
return lines.Distinct(StringComparer.Ordinal).ToArray();
|
||||
}
|
||||
|
||||
private static string? ValidatePath(string path)
|
||||
{
|
||||
if (path[0] != '/')
|
||||
{
|
||||
return "muss mit / beginnen.";
|
||||
}
|
||||
|
||||
if (path.Length > MaxPathLength)
|
||||
{
|
||||
return $"höchstens {MaxPathLength} Zeichen.";
|
||||
}
|
||||
|
||||
if (path.Any(char.IsWhiteSpace))
|
||||
{
|
||||
return "darf keine Leerzeichen enthalten.";
|
||||
}
|
||||
|
||||
var star = path.IndexOf('*');
|
||||
return star >= 0 && star != path.Length - 1 ? "* ist nur am Ende erlaubt." : null;
|
||||
}
|
||||
|
||||
private static string? ValidateHost(string host)
|
||||
{
|
||||
if (host.Length > MaxHostLength)
|
||||
{
|
||||
return $"höchstens {MaxHostLength} Zeichen.";
|
||||
}
|
||||
|
||||
return HostPattern().IsMatch(host) ? null : "ungültiger Hostname (nur Name, ohne Schema, Port oder Pfad; Wildcard als *.beispiel.de).";
|
||||
}
|
||||
|
||||
private static TimeSpan? ParseTimeSpan(
|
||||
string? raw,
|
||||
string field,
|
||||
TimeSpan min,
|
||||
TimeSpan max,
|
||||
Dictionary<string, string> errors)
|
||||
{
|
||||
var text = raw?.Trim();
|
||||
if (string.IsNullOrEmpty(text))
|
||||
{
|
||||
errors[field] = "Pflichtfeld.";
|
||||
return null;
|
||||
}
|
||||
|
||||
if (!text.Contains(':') || !TimeSpan.TryParse(text, CultureInfo.InvariantCulture, out var value))
|
||||
{
|
||||
errors[field] = "Format hh:mm:ss, zum Beispiel 00:00:10.";
|
||||
return null;
|
||||
}
|
||||
|
||||
if (value < min || value > max)
|
||||
{
|
||||
errors[field] = $"Zwischen {min.ToString("c", CultureInfo.InvariantCulture)} und {max.ToString("c", CultureInfo.InvariantCulture)}.";
|
||||
return null;
|
||||
}
|
||||
|
||||
return value;
|
||||
}
|
||||
|
||||
private static int? ParseInt(string? raw, string field, Dictionary<string, string> errors)
|
||||
{
|
||||
var text = raw?.Trim();
|
||||
if (string.IsNullOrEmpty(text))
|
||||
{
|
||||
errors[field] = "Pflichtfeld.";
|
||||
return null;
|
||||
}
|
||||
|
||||
if (!int.TryParse(text, NumberStyles.None, CultureInfo.InvariantCulture, out var value) || value is < 1 or > MaxLimit)
|
||||
{
|
||||
errors[field] = $"Ganze Zahl zwischen 1 und {MaxLimit}.";
|
||||
return null;
|
||||
}
|
||||
|
||||
return value;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
namespace Flypaper.Core;
|
||||
|
||||
public static class SettingKeys
|
||||
{
|
||||
public const string MaxConnections = "Flypaper:MaxConnections";
|
||||
public const string MaxConnectionsPerIp = "Flypaper:MaxConnectionsPerIp";
|
||||
public const string MaxHoldDuration = "Flypaper:MaxHoldDuration";
|
||||
public const string DripInterval = "Flypaper:Drip:Interval";
|
||||
public const string TrapPaths = "Flypaper:Http:TrapPathsOverride";
|
||||
public const string ExtraKnownHosts = "Flypaper:Http:ExtraKnownHosts";
|
||||
|
||||
public static readonly IReadOnlySet<string> All = new HashSet<string>(StringComparer.OrdinalIgnoreCase)
|
||||
{
|
||||
MaxConnections,
|
||||
MaxConnectionsPerIp,
|
||||
MaxHoldDuration,
|
||||
DripInterval,
|
||||
TrapPaths,
|
||||
ExtraKnownHosts
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
namespace Flypaper.Core;
|
||||
|
||||
public static class SettingsList
|
||||
{
|
||||
private static readonly char[] Separators = ['\r', '\n'];
|
||||
|
||||
public static string[] Split(string? value) =>
|
||||
value is null
|
||||
? []
|
||||
: value.Split(Separators, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)
|
||||
.Distinct(StringComparer.Ordinal)
|
||||
.ToArray();
|
||||
|
||||
public static string Join(IEnumerable<string> items) => string.Join('\n', items);
|
||||
}
|
||||
@@ -2,7 +2,7 @@ using Microsoft.Extensions.Options;
|
||||
|
||||
namespace Flypaper.Core.Strategies;
|
||||
|
||||
public sealed class DripStrategy(IOptions<DripOptions> options, TimeProvider timeProvider) : ITarpitStrategy
|
||||
public sealed class DripStrategy(IOptionsMonitor<DripOptions> options, TimeProvider timeProvider) : ITarpitStrategy
|
||||
{
|
||||
private static readonly byte[] Alphabet = "abcdefghijklmnopqrstuvwxyz0123456789"u8.ToArray();
|
||||
|
||||
@@ -18,7 +18,7 @@ public sealed class DripStrategy(IOptions<DripOptions> options, TimeProvider tim
|
||||
ct.ThrowIfCancellationRequested();
|
||||
buffer[0] = Alphabet[Random.Shared.Next(Alphabet.Length)];
|
||||
await channel.WriteAsync(buffer, ct);
|
||||
await Task.Delay(options.Value.Interval, timeProvider, ct);
|
||||
await Task.Delay(options.CurrentValue.Interval, timeProvider, ct);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -8,7 +8,7 @@ public sealed partial class TrapRunner(
|
||||
IConnectionGovernor governor,
|
||||
IEnumerable<ITarpitStrategy> strategies,
|
||||
ITrapEventSink sink,
|
||||
IOptions<FlypaperOptions> options,
|
||||
IOptionsMonitor<FlypaperOptions> options,
|
||||
TimeProvider timeProvider,
|
||||
ILogger<TrapRunner> logger)
|
||||
{
|
||||
@@ -27,7 +27,7 @@ public sealed partial class TrapRunner(
|
||||
}
|
||||
|
||||
using var _ = lease;
|
||||
using var hold = new CancellationTokenSource(options.Value.MaxHoldDuration, timeProvider);
|
||||
using var hold = new CancellationTokenSource(options.CurrentValue.MaxHoldDuration, timeProvider);
|
||||
using var linked = CancellationTokenSource.CreateLinkedTokenSource(ct, hold.Token);
|
||||
|
||||
CountingTrapChannel? channel = null;
|
||||
|
||||
Reference in new issue
Block a user