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,6 +4,7 @@
|
||||
<CentralPackageTransitivePinningEnabled>true</CentralPackageTransitivePinningEnabled>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<PackageVersion Include="Microsoft.Extensions.Configuration" Version="10.0.15" />
|
||||
<PackageVersion Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="10.0.15" />
|
||||
<PackageVersion Include="Microsoft.Extensions.Hosting.Abstractions" Version="10.0.15" />
|
||||
<PackageVersion Include="Microsoft.Extensions.Logging.Abstractions" Version="10.0.15" />
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -15,6 +15,15 @@ public static class FlypaperHttpExtensions
|
||||
public static IServiceCollection AddFlypaperHttp(this IServiceCollection services, IConfiguration configuration)
|
||||
{
|
||||
services.Configure<HttpTrapOptions>(configuration.GetSection(HttpTrapOptions.SectionName));
|
||||
services.PostConfigure<HttpTrapOptions>(options =>
|
||||
{
|
||||
if (options.TrapPathsOverride is not null)
|
||||
{
|
||||
options.TrapPaths = SettingsList.Split(options.TrapPathsOverride);
|
||||
}
|
||||
|
||||
options.KnownHosts = options.KnownHosts.Concat(SettingsList.Split(options.ExtraKnownHosts)).Distinct(StringComparer.OrdinalIgnoreCase).ToArray();
|
||||
});
|
||||
services.TryAddSingleton<TrapMatcher>();
|
||||
|
||||
services.AddOptions<ForwardedHeadersOptions>()
|
||||
|
||||
@@ -9,4 +9,8 @@ public sealed class HttpTrapOptions
|
||||
public string[] TrapPaths { get; set; } = [];
|
||||
|
||||
public string[] TrustedProxies { get; set; } = [];
|
||||
|
||||
public string? TrapPathsOverride { get; set; }
|
||||
|
||||
public string? ExtraKnownHosts { get; set; }
|
||||
}
|
||||
@@ -2,58 +2,73 @@ using Microsoft.Extensions.Options;
|
||||
|
||||
namespace Flypaper.Http;
|
||||
|
||||
public sealed class TrapMatcher
|
||||
public sealed class TrapMatcher : IDisposable
|
||||
{
|
||||
private readonly HashSet<string> _hosts = new(StringComparer.OrdinalIgnoreCase);
|
||||
private readonly List<string> _hostSuffixes = [];
|
||||
private readonly HashSet<string> _paths = new(StringComparer.OrdinalIgnoreCase);
|
||||
private readonly List<string> _pathPrefixes = [];
|
||||
private readonly IDisposable? _subscription;
|
||||
private volatile Snapshot _snapshot;
|
||||
|
||||
public TrapMatcher(IOptions<HttpTrapOptions> options)
|
||||
public TrapMatcher(IOptionsMonitor<HttpTrapOptions> options)
|
||||
{
|
||||
foreach (var host in options.Value.KnownHosts)
|
||||
{
|
||||
if (host.StartsWith("*.", StringComparison.Ordinal))
|
||||
{
|
||||
_hostSuffixes.Add(host[1..]);
|
||||
}
|
||||
else
|
||||
{
|
||||
_hosts.Add(host);
|
||||
}
|
||||
}
|
||||
|
||||
foreach (var path in options.Value.TrapPaths)
|
||||
{
|
||||
if (path.EndsWith('*'))
|
||||
{
|
||||
_pathPrefixes.Add(path[..^1]);
|
||||
}
|
||||
else
|
||||
{
|
||||
_paths.Add(TrimTrailingSlash(path));
|
||||
}
|
||||
}
|
||||
_snapshot = new Snapshot(options.CurrentValue);
|
||||
_subscription = options.OnChange(updated => _snapshot = new Snapshot(updated));
|
||||
}
|
||||
|
||||
public TrapMatch Match(string? host, string? path)
|
||||
{
|
||||
if (!IsKnownHost(host))
|
||||
var snapshot = _snapshot;
|
||||
if (!snapshot.IsKnownHost(host))
|
||||
{
|
||||
return TrapMatch.UnknownHost;
|
||||
}
|
||||
|
||||
return IsTrapPath(path ?? "/") ? TrapMatch.TrapPath : TrapMatch.None;
|
||||
return snapshot.IsTrapPath(path ?? "/") ? TrapMatch.TrapPath : TrapMatch.None;
|
||||
}
|
||||
|
||||
private bool IsKnownHost(string? host) =>
|
||||
!string.IsNullOrEmpty(host)
|
||||
&& (_hosts.Contains(host)
|
||||
|| _hostSuffixes.Any(suffix => host.EndsWith(suffix, StringComparison.OrdinalIgnoreCase)));
|
||||
public void Dispose() => _subscription?.Dispose();
|
||||
|
||||
private bool IsTrapPath(string path) =>
|
||||
_paths.Contains(TrimTrailingSlash(path))
|
||||
|| _pathPrefixes.Any(prefix => path.StartsWith(prefix, StringComparison.OrdinalIgnoreCase));
|
||||
private sealed class Snapshot
|
||||
{
|
||||
private readonly HashSet<string> _hosts = new(StringComparer.OrdinalIgnoreCase);
|
||||
private readonly List<string> _hostSuffixes = [];
|
||||
private readonly HashSet<string> _paths = new(StringComparer.OrdinalIgnoreCase);
|
||||
private readonly List<string> _pathPrefixes = [];
|
||||
|
||||
private static string TrimTrailingSlash(string path) => path.Length > 1 ? path.TrimEnd('/') : path;
|
||||
public Snapshot(HttpTrapOptions options)
|
||||
{
|
||||
foreach (var host in options.KnownHosts.Where(h => !string.IsNullOrWhiteSpace(h)))
|
||||
{
|
||||
if (host.StartsWith("*.", StringComparison.Ordinal))
|
||||
{
|
||||
_hostSuffixes.Add(host[1..]);
|
||||
}
|
||||
else
|
||||
{
|
||||
_hosts.Add(host);
|
||||
}
|
||||
}
|
||||
|
||||
foreach (var path in options.TrapPaths.Where(p => !string.IsNullOrWhiteSpace(p)))
|
||||
{
|
||||
if (path.EndsWith('*'))
|
||||
{
|
||||
_pathPrefixes.Add(path[..^1]);
|
||||
}
|
||||
else
|
||||
{
|
||||
_paths.Add(TrimTrailingSlash(path));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public bool IsKnownHost(string? host) =>
|
||||
!string.IsNullOrEmpty(host)
|
||||
&& (_hosts.Contains(host)
|
||||
|| _hostSuffixes.Any(suffix => host.EndsWith(suffix, StringComparison.OrdinalIgnoreCase)));
|
||||
|
||||
public bool IsTrapPath(string path) =>
|
||||
_paths.Contains(TrimTrailingSlash(path))
|
||||
|| _pathPrefixes.Any(prefix => path.StartsWith(prefix, StringComparison.OrdinalIgnoreCase));
|
||||
|
||||
private static string TrimTrailingSlash(string path) => path.Length > 1 ? path.TrimEnd('/') : path;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
using Flypaper.Core;
|
||||
using Microsoft.Data.Sqlite;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
|
||||
namespace Flypaper.Storage;
|
||||
|
||||
internal sealed class DbConfigurationProvider(string connectionString) : ConfigurationProvider
|
||||
{
|
||||
public override void Load() => Data = Read();
|
||||
|
||||
public void Reload()
|
||||
{
|
||||
Load();
|
||||
OnReload();
|
||||
}
|
||||
|
||||
private Dictionary<string, string?> Read()
|
||||
{
|
||||
var data = new Dictionary<string, string?>(StringComparer.OrdinalIgnoreCase);
|
||||
var builder = new SqliteConnectionStringBuilder(connectionString) { Mode = SqliteOpenMode.ReadOnly };
|
||||
|
||||
try
|
||||
{
|
||||
using var connection = new SqliteConnection(builder.ConnectionString);
|
||||
connection.Open();
|
||||
using var command = connection.CreateCommand();
|
||||
command.CommandText = "SELECT \"Key\", \"Value\" FROM \"Settings\"";
|
||||
using var reader = command.ExecuteReader();
|
||||
while (reader.Read())
|
||||
{
|
||||
var key = reader.GetString(0);
|
||||
if (SettingKeys.All.Contains(key))
|
||||
{
|
||||
data[key] = reader.GetString(1);
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (SqliteException)
|
||||
{
|
||||
data.Clear();
|
||||
}
|
||||
|
||||
return data;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
using Microsoft.Extensions.Configuration;
|
||||
|
||||
namespace Flypaper.Storage;
|
||||
|
||||
public sealed class DbConfigurationSource(string connectionString) : IConfigurationSource
|
||||
{
|
||||
private DbConfigurationProvider? _provider;
|
||||
|
||||
public IConfigurationProvider Build(IConfigurationBuilder builder) =>
|
||||
_provider = new DbConfigurationProvider(connectionString);
|
||||
|
||||
public void Reload() => _provider?.Reload();
|
||||
}
|
||||
@@ -3,6 +3,7 @@
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" PrivateAssets="all" />
|
||||
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" />
|
||||
<PackageReference Include="Microsoft.Extensions.Configuration" />
|
||||
<PackageReference Include="Microsoft.Extensions.Hosting.Abstractions" />
|
||||
</ItemGroup>
|
||||
|
||||
|
||||
@@ -8,6 +8,8 @@ public sealed class FlypaperDbContext(DbContextOptions<FlypaperDbContext> option
|
||||
|
||||
public DbSet<TrapEventEntity> TrapEvents => Set<TrapEventEntity>();
|
||||
|
||||
public DbSet<SettingEntity> Settings => Set<SettingEntity>();
|
||||
|
||||
protected override void OnModelCreating(ModelBuilder modelBuilder)
|
||||
{
|
||||
var trapEvent = modelBuilder.Entity<TrapEventEntity>();
|
||||
@@ -19,5 +21,9 @@ public sealed class FlypaperDbContext(DbContextOptions<FlypaperDbContext> option
|
||||
trapEvent.Property(e => e.ClientInfo).HasMaxLength(MaxTextLength);
|
||||
trapEvent.HasIndex(e => e.StartedAt);
|
||||
trapEvent.HasIndex(e => e.RemoteIp);
|
||||
|
||||
var setting = modelBuilder.Entity<SettingEntity>();
|
||||
setting.HasKey(e => e.Key);
|
||||
setting.Property(e => e.Key).HasMaxLength(128);
|
||||
}
|
||||
}
|
||||
@@ -1,11 +1,26 @@
|
||||
using Flypaper.Core;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Hosting;
|
||||
|
||||
namespace Flypaper.Storage;
|
||||
|
||||
public static class FlypaperStorageExtensions
|
||||
{
|
||||
public static IHostApplicationBuilder AddFlypaperStorage(this IHostApplicationBuilder builder)
|
||||
{
|
||||
var connectionString = builder.Configuration.GetConnectionString("Flypaper") ?? "Data Source=flypaper.db";
|
||||
|
||||
var source = new DbConfigurationSource(connectionString);
|
||||
builder.Configuration.Add(source);
|
||||
builder.Services.AddSingleton(source);
|
||||
builder.Services.AddSingleton<RuntimeSettingsStore>();
|
||||
builder.Services.AddFlypaperStorage(connectionString);
|
||||
|
||||
return builder;
|
||||
}
|
||||
|
||||
public static IServiceCollection AddFlypaperStorage(this IServiceCollection services, string connectionString)
|
||||
{
|
||||
services.AddDbContextFactory<FlypaperDbContext>(options => options.UseSqlite(connectionString));
|
||||
@@ -19,7 +34,11 @@ public static class FlypaperStorageExtensions
|
||||
public static async Task MigrateFlypaperDatabaseAsync(this IServiceProvider services, CancellationToken ct = default)
|
||||
{
|
||||
var factory = services.GetRequiredService<IDbContextFactory<FlypaperDbContext>>();
|
||||
await using var db = await factory.CreateDbContextAsync(ct);
|
||||
await db.Database.MigrateAsync(ct);
|
||||
await using (var db = await factory.CreateDbContextAsync(ct))
|
||||
{
|
||||
await db.Database.MigrateAsync(ct);
|
||||
}
|
||||
|
||||
services.GetService<DbConfigurationSource>()?.Reload();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
// <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("20261114123948_AddSettings")]
|
||||
partial class AddSettings
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void BuildTargetModel(ModelBuilder modelBuilder)
|
||||
{
|
||||
#pragma warning disable 612, 618
|
||||
modelBuilder.HasAnnotation("ProductVersion", "10.0.15");
|
||||
|
||||
modelBuilder.Entity("Flypaper.Storage.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.TrapEventEntity", b =>
|
||||
{
|
||||
b.Property<long>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<long>("BytesSent")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<string>("ClientInfo")
|
||||
.HasMaxLength(2048)
|
||||
.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>("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("RemoteIp");
|
||||
|
||||
b.HasIndex("StartedAt");
|
||||
|
||||
b.ToTable("TrapEvents");
|
||||
});
|
||||
#pragma warning restore 612, 618
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace Flypaper.Storage.Migrations
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public partial class AddSettings : Migration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void Up(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.CreateTable(
|
||||
name: "Settings",
|
||||
columns: table => new
|
||||
{
|
||||
Key = table.Column<string>(type: "TEXT", maxLength: 128, nullable: false),
|
||||
Value = table.Column<string>(type: "TEXT", nullable: false)
|
||||
},
|
||||
constraints: table =>
|
||||
{
|
||||
table.PrimaryKey("PK_Settings", x => x.Key);
|
||||
});
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void Down(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.DropTable(
|
||||
name: "Settings");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -17,6 +17,21 @@ namespace Flypaper.Storage.Migrations
|
||||
#pragma warning disable 612, 618
|
||||
modelBuilder.HasAnnotation("ProductVersion", "10.0.15");
|
||||
|
||||
modelBuilder.Entity("Flypaper.Storage.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.TrapEventEntity", b =>
|
||||
{
|
||||
b.Property<long>("Id")
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
using Flypaper.Core;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace Flypaper.Storage;
|
||||
|
||||
public sealed class RuntimeSettingsStore(IDbContextFactory<FlypaperDbContext> dbContextFactory, DbConfigurationSource source)
|
||||
{
|
||||
public async Task SaveAsync(RuntimeSettings settings, CancellationToken ct = default)
|
||||
{
|
||||
await using var db = await dbContextFactory.CreateDbContextAsync(ct);
|
||||
await using var transaction = await db.Database.BeginTransactionAsync(ct);
|
||||
await db.Settings.ExecuteDeleteAsync(ct);
|
||||
db.Settings.AddRange(settings.ToConfiguration().Select(pair => new SettingEntity { Key = pair.Key, Value = pair.Value }));
|
||||
await db.SaveChangesAsync(ct);
|
||||
await transaction.CommitAsync(ct);
|
||||
source.Reload();
|
||||
}
|
||||
|
||||
public async Task ResetAsync(CancellationToken ct = default)
|
||||
{
|
||||
await using var db = await dbContextFactory.CreateDbContextAsync(ct);
|
||||
await db.Settings.ExecuteDeleteAsync(ct);
|
||||
source.Reload();
|
||||
}
|
||||
|
||||
public async Task<bool> HasOverridesAsync(CancellationToken ct = default)
|
||||
{
|
||||
await using var db = await dbContextFactory.CreateDbContextAsync(ct);
|
||||
return await db.Settings.AnyAsync(ct);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
namespace Flypaper.Storage;
|
||||
|
||||
public sealed class SettingEntity
|
||||
{
|
||||
public required string Key { get; set; }
|
||||
|
||||
public required string Value { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using Microsoft.Extensions.Options;
|
||||
|
||||
namespace Flypaper.Web.Auth;
|
||||
|
||||
public sealed class AdminAuthenticator(IOptions<AdminOptions> options)
|
||||
{
|
||||
public bool IsConfigured => !string.IsNullOrEmpty(options.Value.Password);
|
||||
|
||||
public bool Verify(string? candidate)
|
||||
{
|
||||
if (!IsConfigured || string.IsNullOrEmpty(candidate))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
return CryptographicOperations.FixedTimeEquals(Hash(candidate), Hash(options.Value.Password!));
|
||||
}
|
||||
|
||||
private static byte[] Hash(string value) => SHA256.HashData(Encoding.UTF8.GetBytes(value));
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
namespace Flypaper.Web.Auth;
|
||||
|
||||
public sealed class AdminOptions
|
||||
{
|
||||
public const string SectionName = "Flypaper:Admin";
|
||||
|
||||
public string? Password { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
using System.Security.Claims;
|
||||
using Microsoft.AspNetCore.Antiforgery;
|
||||
using Microsoft.AspNetCore.Authentication;
|
||||
using Microsoft.AspNetCore.Authentication.Cookies;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
namespace Flypaper.Web.Auth;
|
||||
|
||||
public static class AuthEndpoints
|
||||
{
|
||||
public static IEndpointRouteBuilder MapAuthEndpoints(this IEndpointRouteBuilder app)
|
||||
{
|
||||
app.MapPost("/auth/login", async (
|
||||
HttpContext context,
|
||||
AdminAuthenticator admin,
|
||||
[FromForm] string? password,
|
||||
[FromForm] string? returnUrl) =>
|
||||
{
|
||||
var target = IsLocalPath(returnUrl) ? returnUrl! : "/";
|
||||
|
||||
if (!admin.Verify(password))
|
||||
{
|
||||
await Task.Delay(750, context.RequestAborted);
|
||||
return Results.LocalRedirect($"/login?error=1&returnUrl={Uri.EscapeDataString(target)}");
|
||||
}
|
||||
|
||||
var identity = new ClaimsIdentity([new Claim(ClaimTypes.Name, "admin")], CookieAuthenticationDefaults.AuthenticationScheme);
|
||||
await context.SignInAsync(new ClaimsPrincipal(identity));
|
||||
return Results.LocalRedirect(target);
|
||||
}).AllowAnonymous();
|
||||
|
||||
app.MapPost("/auth/logout", async (HttpContext context, IAntiforgery antiforgery) =>
|
||||
{
|
||||
if (!await antiforgery.IsRequestValidAsync(context))
|
||||
{
|
||||
return Results.BadRequest();
|
||||
}
|
||||
|
||||
await context.SignOutAsync();
|
||||
return Results.LocalRedirect("/login");
|
||||
});
|
||||
|
||||
return app;
|
||||
}
|
||||
|
||||
private static bool IsLocalPath(string? url) =>
|
||||
!string.IsNullOrEmpty(url) && url[0] == '/' && (url.Length == 1 || (url[1] != '/' && url[1] != '\\'));
|
||||
}
|
||||
@@ -14,7 +14,6 @@
|
||||
|
||||
<body>
|
||||
<Routes />
|
||||
<script src="@Assets["_framework/blazor.web.js"]"></script>
|
||||
</body>
|
||||
|
||||
</html>
|
||||
@@ -0,0 +1,5 @@
|
||||
@inherits LayoutComponentBase
|
||||
|
||||
<main class="page narrow">
|
||||
@Body
|
||||
</main>
|
||||
@@ -1,5 +1,13 @@
|
||||
@inherits LayoutComponentBase
|
||||
|
||||
<main class="page">
|
||||
<nav class="nav">
|
||||
<NavLink href="/" Match="NavLinkMatch.All">Dashboard</NavLink>
|
||||
<NavLink href="/settings">Einstellungen</NavLink>
|
||||
<form method="post" action="/auth/logout" class="logout">
|
||||
<AntiforgeryToken />
|
||||
<button type="submit" class="link">Abmelden</button>
|
||||
</form>
|
||||
</nav>
|
||||
@Body
|
||||
</main>
|
||||
@@ -0,0 +1,10 @@
|
||||
@if (Errors.TryGetValue(Field, out var message))
|
||||
{
|
||||
<p class="error">@message</p>
|
||||
}
|
||||
|
||||
@code {
|
||||
[Parameter, EditorRequired] public required IReadOnlyDictionary<string, string> Errors { get; set; }
|
||||
|
||||
[Parameter, EditorRequired] public required string Field { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
@page "/login"
|
||||
@layout EmptyLayout
|
||||
@attribute [AllowAnonymous]
|
||||
@using Flypaper.Web.Auth
|
||||
@using Microsoft.AspNetCore.Authorization
|
||||
@inject AdminAuthenticator Admin
|
||||
|
||||
<PageTitle>Flypaper · Anmelden</PageTitle>
|
||||
|
||||
<h1 class="login-title">Flypaper</h1>
|
||||
|
||||
@if (!Admin.IsConfigured)
|
||||
{
|
||||
<div class="banner bad">
|
||||
<strong>Zugang gesperrt.</strong>
|
||||
Es ist kein Admin-Passwort gesetzt. Setze die Umgebungsvariable <code>Flypaper__Admin__Password</code> und starte den Container neu.
|
||||
</div>
|
||||
}
|
||||
else
|
||||
{
|
||||
<form method="post" action="/auth/login" class="card form">
|
||||
<AntiforgeryToken />
|
||||
<input type="hidden" name="returnUrl" value="@ReturnUrl" />
|
||||
<label for="password">Passwort</label>
|
||||
<input id="password" name="password" type="password" autocomplete="current-password" autofocus required />
|
||||
@if (Error is not null)
|
||||
{
|
||||
<p class="error">Passwort falsch.</p>
|
||||
}
|
||||
<button type="submit">Anmelden</button>
|
||||
</form>
|
||||
}
|
||||
|
||||
@code {
|
||||
[SupplyParameterFromQuery(Name = "error")] private string? Error { get; set; }
|
||||
|
||||
[SupplyParameterFromQuery(Name = "returnUrl")] private string? ReturnUrl { get; set; }
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
@page "/not-found"
|
||||
@layout MainLayout
|
||||
@layout EmptyLayout
|
||||
@attribute [Microsoft.AspNetCore.Authorization.AllowAnonymous]
|
||||
|
||||
<h3>Not Found</h3>
|
||||
<p>Sorry, the content you are looking for does not exist.</p>
|
||||
@@ -0,0 +1,157 @@
|
||||
@page "/settings"
|
||||
@using System.Globalization
|
||||
@using Flypaper.Core
|
||||
@using Flypaper.Core.Strategies
|
||||
@using Flypaper.Http
|
||||
@using Flypaper.Storage
|
||||
@using Flypaper.Web.Auth
|
||||
@using Microsoft.Data.Sqlite
|
||||
@using Microsoft.Extensions.Options
|
||||
@inject IOptionsMonitor<FlypaperOptions> Core
|
||||
@inject IOptionsMonitor<DripOptions> Drip
|
||||
@inject IOptionsMonitor<HttpTrapOptions> Http
|
||||
@inject IConfiguration Configuration
|
||||
@inject RuntimeSettingsStore Store
|
||||
@inject AdminAuthenticator Admin
|
||||
@inject NavigationManager Navigation
|
||||
|
||||
<PageTitle>Flypaper · Einstellungen</PageTitle>
|
||||
|
||||
<header class="top">
|
||||
<h1>Einstellungen</h1>
|
||||
@if (_hasOverrides)
|
||||
{
|
||||
<span class="badge">Überschrieben</span>
|
||||
}
|
||||
</header>
|
||||
|
||||
@if (Saved == "1")
|
||||
{
|
||||
<div class="banner ok">Gespeichert. Die Änderungen gelten sofort.</div>
|
||||
}
|
||||
else if (Saved == "reset")
|
||||
{
|
||||
<div class="banner ok">Auf Standard zurückgesetzt.</div>
|
||||
}
|
||||
|
||||
<EditForm Model="Model" FormName="settings" OnSubmit="Save" class="card form">
|
||||
<h2>Anpassbar</h2>
|
||||
|
||||
<label for="trap-paths">Fallenpfade <span class="muted">(einer pro Zeile, mit / am Anfang, * am Ende als Präfix)</span></label>
|
||||
<InputTextArea id="trap-paths" @bind-Value="Model!.TrapPaths" rows="10" class="mono" />
|
||||
<FieldError Errors="_errors" Field="@nameof(SettingsModel.TrapPaths)" />
|
||||
|
||||
<label for="hosts">Zusätzliche bekannte Hosts <span class="muted">(einer pro Zeile, z. B. beispiel.de oder *.beispiel.de)</span></label>
|
||||
<InputTextArea id="hosts" @bind-Value="Model!.ExtraKnownHosts" rows="4" class="mono" />
|
||||
<FieldError Errors="_errors" Field="@nameof(SettingsModel.ExtraKnownHosts)" />
|
||||
|
||||
<div class="grid">
|
||||
<div>
|
||||
<label for="drip">Tröpfel-Intervall <span class="muted">(hh:mm:ss)</span></label>
|
||||
<InputText id="drip" @bind-Value="Model!.DripInterval" class="mono" />
|
||||
<FieldError Errors="_errors" Field="@nameof(SettingsModel.DripInterval)" />
|
||||
</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(SettingsModel.MaxHoldDuration)" />
|
||||
</div>
|
||||
<div>
|
||||
<label for="max">Max. Verbindungen gesamt</label>
|
||||
<InputText id="max" @bind-Value="Model!.MaxConnections" class="mono" />
|
||||
<FieldError Errors="_errors" Field="@nameof(SettingsModel.MaxConnections)" />
|
||||
</div>
|
||||
<div>
|
||||
<label for="per-ip">Max. Verbindungen pro IP</label>
|
||||
<InputText id="per-ip" @bind-Value="Model!.MaxConnectionsPerIp" class="mono" />
|
||||
<FieldError Errors="_errors" Field="@nameof(SettingsModel.MaxConnectionsPerIp)" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="actions">
|
||||
<button type="submit">Speichern</button>
|
||||
</div>
|
||||
</EditForm>
|
||||
|
||||
<EditForm Model="_resetModel" FormName="reset" OnSubmit="Reset" class="card form">
|
||||
<h2>Standard</h2>
|
||||
<p class="muted">Löscht alle gespeicherten Änderungen. Danach gelten wieder die Werte aus Umgebungsvariablen und appsettings.</p>
|
||||
<div class="actions">
|
||||
<button type="submit" class="secondary" disabled="@(!_hasOverrides)" onclick="return confirm('Gespeicherte Einstellungen wirklich löschen?')">Auf Standard zurücksetzen</button>
|
||||
</div>
|
||||
</EditForm>
|
||||
|
||||
<section class="card">
|
||||
<h2>Nur per Umgebungsvariable</h2>
|
||||
<p class="muted">Gelten ab Containerstart und lassen sich hier nicht ändern.</p>
|
||||
<table>
|
||||
<tbody>
|
||||
<tr><th>Datenbank</th><td class="mono">@DatabasePath</td></tr>
|
||||
<tr><th>Bekannte Hosts</th><td class="mono">@Format(Configuration.GetSection("Flypaper:Http:KnownHosts").Get<string[]>())</td></tr>
|
||||
<tr><th>Vertrauenswürdige Proxies</th><td class="mono">@Format(Configuration.GetSection("Flypaper:Http:TrustedProxies").Get<string[]>())</td></tr>
|
||||
<tr><th>Admin-Passwort</th><td>@(Admin.IsConfigured ? "gesetzt" : "nicht gesetzt")</td></tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</section>
|
||||
|
||||
@code {
|
||||
private readonly object _resetModel = new();
|
||||
private IReadOnlyDictionary<string, string> _errors = new Dictionary<string, string>();
|
||||
private bool _hasOverrides;
|
||||
|
||||
[SupplyParameterFromForm(FormName = "settings")] private SettingsModel? Model { get; set; }
|
||||
|
||||
[SupplyParameterFromQuery(Name = "saved")] private string? Saved { get; set; }
|
||||
|
||||
private string DatabasePath =>
|
||||
new SqliteConnectionStringBuilder(Configuration.GetConnectionString("Flypaper") ?? "Data Source=flypaper.db").DataSource;
|
||||
|
||||
protected override async Task OnInitializedAsync()
|
||||
{
|
||||
Model ??= CurrentValues();
|
||||
_hasOverrides = await Store.HasOverridesAsync();
|
||||
}
|
||||
|
||||
private async Task Save()
|
||||
{
|
||||
var result = RuntimeSettingsParser.Parse(new RuntimeSettingsInput(
|
||||
Model!.TrapPaths,
|
||||
Model.DripInterval,
|
||||
Model.MaxConnections,
|
||||
Model.MaxConnectionsPerIp,
|
||||
Model.MaxHoldDuration,
|
||||
Model.ExtraKnownHosts));
|
||||
|
||||
if (result.Settings is null)
|
||||
{
|
||||
_errors = result.Errors;
|
||||
return;
|
||||
}
|
||||
|
||||
await Store.SaveAsync(result.Settings);
|
||||
Navigation.NavigateTo("/settings?saved=1");
|
||||
}
|
||||
|
||||
private async Task Reset()
|
||||
{
|
||||
await Store.ResetAsync();
|
||||
Navigation.NavigateTo("/settings?saved=reset");
|
||||
}
|
||||
|
||||
private SettingsModel CurrentValues()
|
||||
{
|
||||
var core = Core.CurrentValue;
|
||||
var http = Http.CurrentValue;
|
||||
return new SettingsModel
|
||||
{
|
||||
TrapPaths = SettingsList.Join(http.TrapPaths),
|
||||
ExtraKnownHosts = SettingsList.Join(SettingsList.Split(http.ExtraKnownHosts)),
|
||||
DripInterval = Drip.CurrentValue.Interval.ToString("c", CultureInfo.InvariantCulture),
|
||||
MaxHoldDuration = core.MaxHoldDuration.ToString("c", CultureInfo.InvariantCulture),
|
||||
MaxConnections = core.MaxConnections.ToString(CultureInfo.InvariantCulture),
|
||||
MaxConnectionsPerIp = core.MaxConnectionsPerIp.ToString(CultureInfo.InvariantCulture)
|
||||
};
|
||||
}
|
||||
|
||||
private static string Format(string[]? values) => values is { Length: > 0 } ? string.Join(", ", values) : "–";
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
namespace Flypaper.Web.Components.Pages;
|
||||
|
||||
public sealed class SettingsModel
|
||||
{
|
||||
public string? TrapPaths { get; set; }
|
||||
|
||||
public string? DripInterval { get; set; }
|
||||
|
||||
public string? MaxConnections { get; set; }
|
||||
|
||||
public string? MaxConnectionsPerIp { get; set; }
|
||||
|
||||
public string? MaxHoldDuration { get; set; }
|
||||
|
||||
public string? ExtraKnownHosts { get; set; }
|
||||
}
|
||||
@@ -1,16 +1,36 @@
|
||||
using Flypaper.Core;
|
||||
using Flypaper.Http;
|
||||
using Flypaper.Storage;
|
||||
using Flypaper.Web.Auth;
|
||||
using Flypaper.Web.Components;
|
||||
using Microsoft.AspNetCore.Authentication.Cookies;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
|
||||
var builder = WebApplication.CreateBuilder(args);
|
||||
|
||||
builder.WebHost.ConfigureKestrel(options => options.AddServerHeader = false);
|
||||
|
||||
builder.AddFlypaperStorage();
|
||||
builder.Services.AddRazorComponents();
|
||||
builder.Services.AddFlypaperCore(builder.Configuration);
|
||||
builder.Services.AddFlypaperHttp(builder.Configuration);
|
||||
builder.Services.AddFlypaperStorage(builder.Configuration.GetConnectionString("Flypaper") ?? "Data Source=flypaper.db");
|
||||
|
||||
builder.Services.Configure<AdminOptions>(builder.Configuration.GetSection(AdminOptions.SectionName));
|
||||
builder.Services.AddSingleton<AdminAuthenticator>();
|
||||
builder.Services
|
||||
.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
|
||||
.AddCookie(options =>
|
||||
{
|
||||
options.LoginPath = "/login";
|
||||
options.AccessDeniedPath = "/login";
|
||||
options.Cookie.Name = "flypaper.auth";
|
||||
options.Cookie.HttpOnly = true;
|
||||
options.Cookie.SameSite = SameSiteMode.Strict;
|
||||
options.ExpireTimeSpan = TimeSpan.FromHours(8);
|
||||
options.SlidingExpiration = true;
|
||||
});
|
||||
builder.Services.AddAuthorizationBuilder()
|
||||
.SetFallbackPolicy(new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build());
|
||||
|
||||
var app = builder.Build();
|
||||
|
||||
@@ -24,9 +44,12 @@ if (!app.Environment.IsDevelopment())
|
||||
}
|
||||
app.UseStatusCodePagesWithReExecute("/not-found", createScopeForStatusCodePages: true);
|
||||
|
||||
app.UseAuthentication();
|
||||
app.UseAuthorization();
|
||||
app.UseAntiforgery();
|
||||
|
||||
app.MapStaticAssets();
|
||||
app.MapStaticAssets().AllowAnonymous();
|
||||
app.MapAuthEndpoints();
|
||||
app.MapRazorComponents<App>();
|
||||
|
||||
await app.RunAsync();
|
||||
@@ -10,7 +10,12 @@
|
||||
"Interval": "00:00:01"
|
||||
},
|
||||
"Http": {
|
||||
"KnownHosts": [ "localhost" ]
|
||||
"KnownHosts": [
|
||||
"localhost"
|
||||
]
|
||||
},
|
||||
"Admin": {
|
||||
"Password": "dev"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -183,3 +183,160 @@ tbody tr:last-child td {
|
||||
max-width: 180px;
|
||||
}
|
||||
}
|
||||
|
||||
.narrow {
|
||||
max-width: 380px;
|
||||
padding-top: 15vh;
|
||||
}
|
||||
|
||||
.login-title {
|
||||
margin: 0 0 16px;
|
||||
font-size: 22px;
|
||||
color: var(--accent);
|
||||
}
|
||||
|
||||
.nav {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 16px;
|
||||
margin-bottom: 20px;
|
||||
padding-bottom: 12px;
|
||||
border-bottom: 1px solid var(--border);
|
||||
}
|
||||
|
||||
.nav a {
|
||||
color: var(--muted);
|
||||
text-decoration: none;
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.nav a:hover,
|
||||
.nav a.active {
|
||||
color: var(--text);
|
||||
}
|
||||
|
||||
.nav .logout {
|
||||
margin-left: auto;
|
||||
}
|
||||
|
||||
.form {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 6px;
|
||||
margin-bottom: 16px;
|
||||
}
|
||||
|
||||
.form label {
|
||||
margin-top: 8px;
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.form .grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
|
||||
gap: 0 16px;
|
||||
}
|
||||
|
||||
input,
|
||||
textarea {
|
||||
width: 100%;
|
||||
padding: 8px 10px;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 6px;
|
||||
background: var(--bg);
|
||||
color: var(--text);
|
||||
font: inherit;
|
||||
}
|
||||
|
||||
input:focus,
|
||||
textarea:focus {
|
||||
outline: 2px solid var(--accent);
|
||||
outline-offset: -1px;
|
||||
}
|
||||
|
||||
textarea {
|
||||
resize: vertical;
|
||||
}
|
||||
|
||||
button {
|
||||
padding: 8px 16px;
|
||||
border: none;
|
||||
border-radius: 6px;
|
||||
background: var(--accent);
|
||||
color: #fff;
|
||||
font: inherit;
|
||||
font-weight: 600;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
button.secondary {
|
||||
background: transparent;
|
||||
border: 1px solid var(--border);
|
||||
color: var(--text);
|
||||
}
|
||||
|
||||
button.link {
|
||||
padding: 0;
|
||||
background: none;
|
||||
color: var(--muted);
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
button.link:hover {
|
||||
color: var(--text);
|
||||
}
|
||||
|
||||
button:disabled {
|
||||
opacity: 0.45;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
|
||||
.actions {
|
||||
margin-top: 10px;
|
||||
}
|
||||
|
||||
.error {
|
||||
margin: 0;
|
||||
color: var(--bad);
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.banner {
|
||||
margin-bottom: 16px;
|
||||
padding: 12px 16px;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 8px;
|
||||
}
|
||||
|
||||
.banner.ok {
|
||||
border-color: var(--ok);
|
||||
color: var(--ok);
|
||||
}
|
||||
|
||||
.banner.bad {
|
||||
border-color: var(--bad);
|
||||
color: var(--bad);
|
||||
}
|
||||
|
||||
.badge {
|
||||
padding: 2px 8px;
|
||||
border: 1px solid var(--accent);
|
||||
border-radius: 999px;
|
||||
color: var(--accent);
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
th[scope],
|
||||
tbody th {
|
||||
width: 220px;
|
||||
color: var(--muted);
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.card {
|
||||
margin-bottom: 16px;
|
||||
}
|
||||
|
||||
.top h1 {
|
||||
margin: 0;
|
||||
}
|
||||
@@ -1,6 +1,5 @@
|
||||
using System.Net;
|
||||
using Flypaper.Core;
|
||||
using Microsoft.Extensions.Options;
|
||||
using Shouldly;
|
||||
|
||||
namespace Flypaper.Tests;
|
||||
@@ -70,7 +69,7 @@ public sealed class ConnectionGovernorTests
|
||||
}
|
||||
|
||||
private static ConnectionGovernor CreateGovernor(int maxConnections, int maxPerIp) =>
|
||||
new(Options.Create(new FlypaperOptions { MaxConnections = maxConnections, MaxConnectionsPerIp = maxPerIp }));
|
||||
new(TestOptions.Monitor(new FlypaperOptions { MaxConnections = maxConnections, MaxConnectionsPerIp = maxPerIp }));
|
||||
|
||||
private static TrapSession Session(IPAddress ip) => new(Guid.NewGuid(), TrapProtocol.Http, ip, DateTimeOffset.UtcNow);
|
||||
}
|
||||
@@ -1,6 +1,5 @@
|
||||
using Flypaper.Core;
|
||||
using Flypaper.Core.Strategies;
|
||||
using Microsoft.Extensions.Options;
|
||||
using Shouldly;
|
||||
|
||||
namespace Flypaper.Tests;
|
||||
@@ -39,5 +38,5 @@ public sealed class DripStrategyTests
|
||||
CreateStrategy(TimeSpan.FromSeconds(1)).Supports(protocol).ShouldBe(expected);
|
||||
|
||||
private static DripStrategy CreateStrategy(TimeSpan interval) =>
|
||||
new(Options.Create(new DripOptions { Interval = interval }), TimeProvider.System);
|
||||
new(TestOptions.Monitor(new DripOptions { Interval = interval }), TimeProvider.System);
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
using Flypaper.Core;
|
||||
using Shouldly;
|
||||
|
||||
namespace Flypaper.Tests;
|
||||
|
||||
public sealed class RuntimeSettingsParserTests
|
||||
{
|
||||
private static readonly RuntimeSettingsInput Valid = new(
|
||||
"/.env\n/wp-admin/*\r\n /xmlrpc.php \n/.env",
|
||||
"00:00:05",
|
||||
"200",
|
||||
"5",
|
||||
"00:30:00",
|
||||
"example.com\n*.example.org");
|
||||
|
||||
[Fact]
|
||||
public void Parses_valid_input_and_normalizes_lists()
|
||||
{
|
||||
var result = RuntimeSettingsParser.Parse(Valid);
|
||||
|
||||
result.Errors.ShouldBeEmpty();
|
||||
var settings = result.Settings.ShouldNotBeNull();
|
||||
settings.TrapPaths.ShouldBe(["/.env", "/wp-admin/*", "/xmlrpc.php"]);
|
||||
settings.ExtraKnownHosts.ShouldBe(["example.com", "*.example.org"]);
|
||||
settings.DripInterval.ShouldBe(TimeSpan.FromSeconds(5));
|
||||
settings.MaxConnections.ShouldBe(200);
|
||||
settings.MaxConnectionsPerIp.ShouldBe(5);
|
||||
settings.MaxHoldDuration.ShouldBe(TimeSpan.FromMinutes(30));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Accepts_empty_lists()
|
||||
{
|
||||
var result = RuntimeSettingsParser.Parse(Valid with { TrapPaths = "", ExtraKnownHosts = null });
|
||||
|
||||
result.Settings.ShouldNotBeNull().TrapPaths.ShouldBeEmpty();
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("env")]
|
||||
[InlineData("/with space")]
|
||||
[InlineData("/a*b")]
|
||||
public void Rejects_invalid_trap_paths(string path)
|
||||
{
|
||||
var result = RuntimeSettingsParser.Parse(Valid with { TrapPaths = $"/ok\n{path}" });
|
||||
|
||||
result.Settings.ShouldBeNull();
|
||||
result.Errors.Keys.ShouldBe([nameof(RuntimeSettingsInput.TrapPaths)]);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("https://example.com")]
|
||||
[InlineData("example.com/path")]
|
||||
[InlineData("example.com:8080")]
|
||||
[InlineData("-bad.com")]
|
||||
public void Rejects_invalid_hosts(string host)
|
||||
{
|
||||
var result = RuntimeSettingsParser.Parse(Valid with { ExtraKnownHosts = host });
|
||||
|
||||
result.Errors.ShouldContainKey(nameof(RuntimeSettingsInput.ExtraKnownHosts));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("10")]
|
||||
[InlineData("abc")]
|
||||
[InlineData("")]
|
||||
[InlineData("00:00:00")]
|
||||
[InlineData("02:00:00")]
|
||||
public void Rejects_invalid_drip_intervals(string value)
|
||||
{
|
||||
var result = RuntimeSettingsParser.Parse(Valid with { DripInterval = value });
|
||||
|
||||
result.Errors.ShouldContainKey(nameof(RuntimeSettingsInput.DripInterval));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("0")]
|
||||
[InlineData("-3")]
|
||||
[InlineData("1.5")]
|
||||
[InlineData("x")]
|
||||
[InlineData("")]
|
||||
public void Rejects_invalid_connection_counts(string value)
|
||||
{
|
||||
var result = RuntimeSettingsParser.Parse(Valid with { MaxConnections = value, MaxConnectionsPerIp = value });
|
||||
|
||||
result.Errors.Keys.ShouldBe(
|
||||
[nameof(RuntimeSettingsInput.MaxConnections), nameof(RuntimeSettingsInput.MaxConnectionsPerIp)],
|
||||
ignoreOrder: true);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Rejects_per_ip_limit_above_total()
|
||||
{
|
||||
var result = RuntimeSettingsParser.Parse(Valid with { MaxConnections = "3", MaxConnectionsPerIp = "4" });
|
||||
|
||||
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]
|
||||
public void Exposes_only_whitelisted_configuration_keys()
|
||||
{
|
||||
var keys = RuntimeSettingsParser.Parse(Valid).Settings.ShouldNotBeNull().ToConfiguration().Keys;
|
||||
|
||||
keys.ShouldBe(SettingKeys.All, ignoreOrder: true);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,140 @@
|
||||
using Flypaper.Core;
|
||||
using Flypaper.Core.Strategies;
|
||||
using Flypaper.Http;
|
||||
using Flypaper.Storage;
|
||||
using Microsoft.Data.Sqlite;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Hosting;
|
||||
using Microsoft.Extensions.Options;
|
||||
using Shouldly;
|
||||
|
||||
namespace Flypaper.Tests;
|
||||
|
||||
public sealed class SettingsOverrideTests : IDisposable
|
||||
{
|
||||
private readonly string _dbPath = Path.Combine(Path.GetTempPath(), $"flypaper-test-{Guid.NewGuid():N}.db");
|
||||
private IHost? _host;
|
||||
|
||||
[Fact]
|
||||
public async Task Db_overrides_startup_values_for_whitelisted_keys_only()
|
||||
{
|
||||
await using (var db = new FlypaperDbContext(new DbContextOptionsBuilder<FlypaperDbContext>().UseSqlite($"Data Source={_dbPath}").Options))
|
||||
{
|
||||
await db.Database.MigrateAsync();
|
||||
db.Settings.AddRange(
|
||||
new SettingEntity { Key = SettingKeys.MaxConnections, Value = "5" },
|
||||
new SettingEntity { Key = SettingKeys.TrapPaths, Value = "/custom\n/other/*" },
|
||||
new SettingEntity { Key = SettingKeys.ExtraKnownHosts, Value = "extra.example" },
|
||||
new SettingEntity { Key = "Flypaper:Admin:Password", Value = "evil" });
|
||||
await db.SaveChangesAsync();
|
||||
}
|
||||
|
||||
var host = BuildHost();
|
||||
await host.Services.MigrateFlypaperDatabaseAsync();
|
||||
|
||||
var core = host.Services.GetRequiredService<IOptionsMonitor<FlypaperOptions>>().CurrentValue;
|
||||
var http = host.Services.GetRequiredService<IOptionsMonitor<HttpTrapOptions>>().CurrentValue;
|
||||
var configuration = host.Services.GetRequiredService<IConfiguration>();
|
||||
|
||||
core.MaxConnections.ShouldBe(5);
|
||||
core.MaxConnectionsPerIp.ShouldBe(10);
|
||||
http.TrapPaths.ShouldBe(["/custom", "/other/*"]);
|
||||
http.KnownHosts.ShouldBe(["dashboard.lan", "extra.example"]);
|
||||
http.TrustedProxies.ShouldBe(["172.18.0.0/16"]);
|
||||
configuration["Flypaper:Admin:Password"].ShouldBe("secret");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Missing_db_overrides_leave_startup_values_untouched()
|
||||
{
|
||||
var host = BuildHost();
|
||||
await host.Services.MigrateFlypaperDatabaseAsync();
|
||||
|
||||
host.Services.GetRequiredService<IOptionsMonitor<FlypaperOptions>>().CurrentValue.MaxConnections.ShouldBe(100);
|
||||
host.Services.GetRequiredService<IOptionsMonitor<HttpTrapOptions>>().CurrentValue.TrapPaths.ShouldBe(["/.env"]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Saving_reloads_trap_matcher_and_reset_restores_startup_values()
|
||||
{
|
||||
var host = BuildHost();
|
||||
await host.Services.MigrateFlypaperDatabaseAsync();
|
||||
var matcher = host.Services.GetRequiredService<TrapMatcher>();
|
||||
var store = host.Services.GetRequiredService<RuntimeSettingsStore>();
|
||||
|
||||
matcher.Match("dashboard.lan", "/custom").ShouldBe(TrapMatch.None);
|
||||
matcher.Match("dashboard.lan", "/.env").ShouldBe(TrapMatch.TrapPath);
|
||||
matcher.Match("extra.example", "/").ShouldBe(TrapMatch.UnknownHost);
|
||||
|
||||
await store.SaveAsync(new RuntimeSettings(
|
||||
["/custom"],
|
||||
TimeSpan.FromSeconds(3),
|
||||
50,
|
||||
4,
|
||||
TimeSpan.FromMinutes(10),
|
||||
["extra.example"]));
|
||||
|
||||
matcher.Match("dashboard.lan", "/custom").ShouldBe(TrapMatch.TrapPath);
|
||||
matcher.Match("dashboard.lan", "/.env").ShouldBe(TrapMatch.None);
|
||||
matcher.Match("extra.example", "/").ShouldBe(TrapMatch.None);
|
||||
host.Services.GetRequiredService<IOptionsMonitor<DripOptions>>().CurrentValue.Interval.ShouldBe(TimeSpan.FromSeconds(3));
|
||||
(await store.HasOverridesAsync()).ShouldBeTrue();
|
||||
|
||||
await store.ResetAsync();
|
||||
|
||||
matcher.Match("dashboard.lan", "/custom").ShouldBe(TrapMatch.None);
|
||||
matcher.Match("dashboard.lan", "/.env").ShouldBe(TrapMatch.TrapPath);
|
||||
(await store.HasOverridesAsync()).ShouldBeFalse();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Saved_empty_trap_path_list_disables_path_traps()
|
||||
{
|
||||
var host = BuildHost();
|
||||
await host.Services.MigrateFlypaperDatabaseAsync();
|
||||
var matcher = host.Services.GetRequiredService<TrapMatcher>();
|
||||
|
||||
await host.Services.GetRequiredService<RuntimeSettingsStore>().SaveAsync(new RuntimeSettings(
|
||||
[],
|
||||
TimeSpan.FromSeconds(3),
|
||||
50,
|
||||
4,
|
||||
TimeSpan.FromMinutes(10),
|
||||
[]));
|
||||
|
||||
matcher.Match("dashboard.lan", "/.env").ShouldBe(TrapMatch.None);
|
||||
}
|
||||
|
||||
private IHost BuildHost()
|
||||
{
|
||||
var builder = Host.CreateApplicationBuilder(new HostApplicationBuilderSettings { DisableDefaults = true });
|
||||
builder.Configuration.AddInMemoryCollection(new Dictionary<string, string?>
|
||||
{
|
||||
["ConnectionStrings:Flypaper"] = $"Data Source={_dbPath}",
|
||||
["Flypaper:MaxConnections"] = "100",
|
||||
["Flypaper:MaxConnectionsPerIp"] = "10",
|
||||
["Flypaper:Http:TrapPaths:0"] = "/.env",
|
||||
["Flypaper:Http:KnownHosts:0"] = "dashboard.lan",
|
||||
["Flypaper:Http:TrustedProxies:0"] = "172.18.0.0/16",
|
||||
["Flypaper:Admin:Password"] = "secret"
|
||||
});
|
||||
builder.AddFlypaperStorage();
|
||||
builder.Services.AddLogging();
|
||||
builder.Services.AddFlypaperCore(builder.Configuration);
|
||||
builder.Services.AddFlypaperHttp(builder.Configuration);
|
||||
|
||||
return _host = builder.Build();
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
_host?.Dispose();
|
||||
SqliteConnection.ClearAllPools();
|
||||
foreach (var suffix in new[] { "", "-wal", "-shm" })
|
||||
{
|
||||
File.Delete(_dbPath + suffix);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
using Microsoft.Extensions.Options;
|
||||
using NSubstitute;
|
||||
|
||||
namespace Flypaper.Tests;
|
||||
|
||||
internal static class TestOptions
|
||||
{
|
||||
public static IOptionsMonitor<T> Monitor<T>(T value) where T : class
|
||||
{
|
||||
var monitor = Substitute.For<IOptionsMonitor<T>>();
|
||||
monitor.CurrentValue.Returns(value);
|
||||
return monitor;
|
||||
}
|
||||
}
|
||||
@@ -1,12 +1,11 @@
|
||||
using Flypaper.Http;
|
||||
using Microsoft.Extensions.Options;
|
||||
using Shouldly;
|
||||
|
||||
namespace Flypaper.Tests;
|
||||
|
||||
public sealed class TrapMatcherTests
|
||||
{
|
||||
private readonly TrapMatcher _matcher = new(Options.Create(new HttpTrapOptions
|
||||
private readonly TrapMatcher _matcher = new(TestOptions.Monitor(new HttpTrapOptions
|
||||
{
|
||||
KnownHosts = ["example.com", "*.example.org"],
|
||||
TrapPaths = ["/.env", "/.git/*", "/wp-login.php"]
|
||||
|
||||
@@ -2,7 +2,6 @@ using System.Net;
|
||||
using Flypaper.Core;
|
||||
using Flypaper.Core.Strategies;
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
using Microsoft.Extensions.Options;
|
||||
using NSubstitute;
|
||||
using Shouldly;
|
||||
|
||||
@@ -75,12 +74,12 @@ public sealed class TrapRunnerTests
|
||||
|
||||
private TrapRunner CreateRunner(TimeSpan maxHoldDuration)
|
||||
{
|
||||
var drip = new DripStrategy(Options.Create(new DripOptions { Interval = TimeSpan.FromMilliseconds(20) }), TimeProvider.System);
|
||||
var drip = new DripStrategy(TestOptions.Monitor(new DripOptions { Interval = TimeSpan.FromMilliseconds(20) }), TimeProvider.System);
|
||||
return new TrapRunner(
|
||||
_governor,
|
||||
[drip],
|
||||
_sink,
|
||||
Options.Create(new FlypaperOptions { MaxHoldDuration = maxHoldDuration }),
|
||||
TestOptions.Monitor(new FlypaperOptions { MaxHoldDuration = maxHoldDuration }),
|
||||
TimeProvider.System,
|
||||
NullLogger<TrapRunner>.Instance);
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user