diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..a41540f --- /dev/null +++ b/.dockerignore @@ -0,0 +1,8 @@ +**/bin/ +**/obj/ +**/*.db +**/*.db-shm +**/*.db-wal +.git/ +.idea/ +test/ diff --git a/Directory.Packages.props b/Directory.Packages.props index ae460e4..f396bbd 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -6,7 +6,9 @@ + + diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..e14706d --- /dev/null +++ b/Dockerfile @@ -0,0 +1,28 @@ +FROM mcr.microsoft.com/dotnet/sdk:10.0 AS build +WORKDIR /src + +COPY Directory.Build.props Directory.Packages.props ./ +COPY src/Flypaper.Core/Flypaper.Core.csproj src/Flypaper.Core/ +COPY src/Flypaper.Http/Flypaper.Http.csproj src/Flypaper.Http/ +COPY src/Flypaper.Storage/Flypaper.Storage.csproj src/Flypaper.Storage/ +COPY src/Flypaper.Web/Flypaper.Web.csproj src/Flypaper.Web/ +RUN dotnet restore src/Flypaper.Web/Flypaper.Web.csproj + +COPY src/ src/ +RUN dotnet publish src/Flypaper.Web/Flypaper.Web.csproj -c Release -o /app --no-restore + +FROM mcr.microsoft.com/dotnet/aspnet:10.0 +WORKDIR /app + +RUN mkdir /data && chown $APP_UID /data + +ENV ASPNETCORE_HTTP_PORTS=8080 \ + ConnectionStrings__Flypaper="Data Source=/data/flypaper.db" + +COPY --from=build /app . + +USER $APP_UID +EXPOSE 8080 +VOLUME /data + +ENTRYPOINT ["dotnet", "Flypaper.Web.dll"] diff --git a/src/Flypaper.Core/Flypaper.Core.csproj b/src/Flypaper.Core/Flypaper.Core.csproj index 937e5ee..81eeb11 100644 --- a/src/Flypaper.Core/Flypaper.Core.csproj +++ b/src/Flypaper.Core/Flypaper.Core.csproj @@ -2,6 +2,7 @@ + diff --git a/src/Flypaper.Core/ServiceCollectionExtensions.cs b/src/Flypaper.Core/ServiceCollectionExtensions.cs index d16f46a..6d0d2f8 100644 --- a/src/Flypaper.Core/ServiceCollectionExtensions.cs +++ b/src/Flypaper.Core/ServiceCollectionExtensions.cs @@ -13,7 +13,8 @@ public static class ServiceCollectionExtensions services.Configure(configuration.GetSection(DripOptions.SectionName)); services.TryAddSingleton(TimeProvider.System); - services.TryAddSingleton(); + services.TryAddSingleton(); + services.TryAddSingleton(sp => sp.GetRequiredService()); services.TryAddEnumerable(ServiceDescriptor.Singleton()); services.TryAddSingleton(); diff --git a/src/Flypaper.Core/TrapRunner.cs b/src/Flypaper.Core/TrapRunner.cs index db621aa..527bbad 100644 --- a/src/Flypaper.Core/TrapRunner.cs +++ b/src/Flypaper.Core/TrapRunner.cs @@ -1,13 +1,16 @@ +using System.Net; +using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; namespace Flypaper.Core; -public sealed class TrapRunner( +public sealed partial class TrapRunner( IConnectionGovernor governor, IEnumerable strategies, ITrapEventSink sink, IOptions options, - TimeProvider timeProvider) + TimeProvider timeProvider, + ILogger logger) { public async Task RunAsync( TrapContext context, @@ -52,7 +55,7 @@ public sealed class TrapRunner( private void Publish(TrapContext context, string strategy, long bytesSent, TrapOutcome outcome) { var session = context.Session; - sink.Publish(new TrapEvent( + var trapEvent = new TrapEvent( session.Id, session.Protocol, session.RemoteIp, @@ -62,6 +65,36 @@ public sealed class TrapRunner( bytesSent, outcome, context.Target, - context.ClientInfo)); + context.ClientInfo); + + if (outcome == TrapOutcome.Rejected) + { + LogRejected(trapEvent.RemoteIp, trapEvent.Target, trapEvent.ClientInfo); + } + else + { + LogTrapped( + trapEvent.RemoteIp, + trapEvent.Target, + trapEvent.Duration.TotalSeconds, + trapEvent.BytesSent, + trapEvent.Outcome, + trapEvent.ClientInfo); + } + + sink.Publish(trapEvent); } + + [LoggerMessage(Level = LogLevel.Information, + Message = "Trapped {RemoteIp} {Target} {DurationSeconds:F1}s {BytesSent}B {Outcome} \"{UserAgent}\"")] + private partial void LogTrapped( + IPAddress remoteIp, + string? target, + double durationSeconds, + long bytesSent, + TrapOutcome outcome, + string? userAgent); + + [LoggerMessage(Level = LogLevel.Information, Message = "Rejected {RemoteIp} {Target} \"{UserAgent}\"")] + private partial void LogRejected(IPAddress remoteIp, string? target, string? userAgent); } diff --git a/src/Flypaper.Http/FlypaperMiddleware.cs b/src/Flypaper.Http/FlypaperMiddleware.cs index 813e1f8..a5dc2f9 100644 --- a/src/Flypaper.Http/FlypaperMiddleware.cs +++ b/src/Flypaper.Http/FlypaperMiddleware.cs @@ -21,10 +21,11 @@ internal sealed class FlypaperMiddleware( return; } + var remoteIp = context.Connection.RemoteIpAddress ?? IPAddress.None; var session = new TrapSession( Guid.NewGuid(), TrapProtocol.Http, - context.Connection.RemoteIpAddress ?? IPAddress.None, + remoteIp.IsIPv4MappedToIPv6 ? remoteIp.MapToIPv4() : remoteIp, timeProvider.GetUtcNow()); var trapContext = new TrapContext( diff --git a/src/Flypaper.Storage/DashboardData.cs b/src/Flypaper.Storage/DashboardData.cs new file mode 100644 index 0000000..986743b --- /dev/null +++ b/src/Flypaper.Storage/DashboardData.cs @@ -0,0 +1,13 @@ +namespace Flypaper.Storage; + +public sealed record DashboardData( + int TotalCatches, + int CatchesLast24Hours, + int Rejected, + int UniqueIps, + TimeSpan TotalHoldTime, + IReadOnlyList Recent, + IReadOnlyList TopIps, + IReadOnlyList TopTargets); + +public sealed record TopEntry(string Key, int Count, TimeSpan HoldTime); diff --git a/src/Flypaper.Storage/DashboardQueries.cs b/src/Flypaper.Storage/DashboardQueries.cs new file mode 100644 index 0000000..924426b --- /dev/null +++ b/src/Flypaper.Storage/DashboardQueries.cs @@ -0,0 +1,49 @@ +using Flypaper.Core; +using Microsoft.EntityFrameworkCore; + +namespace Flypaper.Storage; + +public sealed class DashboardQueries(IDbContextFactory dbContextFactory, TimeProvider timeProvider) +{ + private const int RecentCount = 50; + private const int TopCount = 10; + + public async Task GetAsync(CancellationToken ct = default) + { + await using var db = await dbContextFactory.CreateDbContextAsync(ct); + var events = db.TrapEvents.AsNoTracking(); + var catches = events.Where(e => e.Outcome != TrapOutcome.Rejected); + var since = timeProvider.GetUtcNow().UtcDateTime.AddHours(-24); + + var recent = await events.OrderByDescending(e => e.Id).Take(RecentCount).ToListAsync(ct); + foreach (var trapEvent in recent) + { + trapEvent.StartedAt = DateTime.SpecifyKind(trapEvent.StartedAt, DateTimeKind.Utc); + trapEvent.EndedAt = DateTime.SpecifyKind(trapEvent.EndedAt, DateTimeKind.Utc); + } + + return new DashboardData( + await catches.CountAsync(ct), + await catches.CountAsync(e => e.StartedAt >= since, ct), + await events.CountAsync(e => e.Outcome == TrapOutcome.Rejected, ct), + await events.Select(e => e.RemoteIp).Distinct().CountAsync(ct), + TimeSpan.FromMilliseconds(await catches.SumAsync(e => e.DurationMs, ct)), + recent, + await TopAsync(catches.GroupBy(e => e.RemoteIp), ct), + await TopAsync(catches.Where(e => e.Target != null).GroupBy(e => e.Target!), ct)); + } + + private static async Task> TopAsync( + IQueryable> groups, + CancellationToken ct) + { + var rows = await groups + .Select(g => new { g.Key, Count = g.Count(), DurationMs = g.Sum(e => e.DurationMs) }) + .OrderByDescending(x => x.Count) + .ThenByDescending(x => x.DurationMs) + .Take(TopCount) + .ToListAsync(ct); + + return rows.Select(x => new TopEntry(x.Key, x.Count, TimeSpan.FromMilliseconds(x.DurationMs))).ToList(); + } +} diff --git a/src/Flypaper.Storage/DesignTimeDbContextFactory.cs b/src/Flypaper.Storage/DesignTimeDbContextFactory.cs new file mode 100644 index 0000000..50aecf6 --- /dev/null +++ b/src/Flypaper.Storage/DesignTimeDbContextFactory.cs @@ -0,0 +1,10 @@ +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Design; + +namespace Flypaper.Storage; + +internal sealed class DesignTimeDbContextFactory : IDesignTimeDbContextFactory +{ + public FlypaperDbContext CreateDbContext(string[] args) => + new(new DbContextOptionsBuilder().UseSqlite("Data Source=flypaper.db").Options); +} diff --git a/src/Flypaper.Storage/Flypaper.Storage.csproj b/src/Flypaper.Storage/Flypaper.Storage.csproj index 21647ea..db74d4d 100644 --- a/src/Flypaper.Storage/Flypaper.Storage.csproj +++ b/src/Flypaper.Storage/Flypaper.Storage.csproj @@ -1,6 +1,7 @@ + diff --git a/src/Flypaper.Storage/FlypaperStorageExtensions.cs b/src/Flypaper.Storage/FlypaperStorageExtensions.cs index c227a7b..ae6f166 100644 --- a/src/Flypaper.Storage/FlypaperStorageExtensions.cs +++ b/src/Flypaper.Storage/FlypaperStorageExtensions.cs @@ -12,6 +12,14 @@ public static class FlypaperStorageExtensions services.AddSingleton(); services.AddSingleton(sp => sp.GetRequiredService()); services.AddHostedService(); + services.AddSingleton(); return services; } + + public static async Task MigrateFlypaperDatabaseAsync(this IServiceProvider services, CancellationToken ct = default) + { + var factory = services.GetRequiredService>(); + await using var db = await factory.CreateDbContextAsync(ct); + await db.Database.MigrateAsync(ct); + } } diff --git a/src/Flypaper.Storage/Migrations/20261114122204_InitialCreate.Designer.cs b/src/Flypaper.Storage/Migrations/20261114122204_InitialCreate.Designer.cs new file mode 100644 index 0000000..2b684c1 --- /dev/null +++ b/src/Flypaper.Storage/Migrations/20261114122204_InitialCreate.Designer.cs @@ -0,0 +1,83 @@ +// +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("20261114122204_InitialCreate")] + partial class InitialCreate + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder.HasAnnotation("ProductVersion", "10.0.15"); + + modelBuilder.Entity("Flypaper.Storage.TrapEventEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("BytesSent") + .HasColumnType("INTEGER"); + + b.Property("ClientInfo") + .HasMaxLength(2048) + .HasColumnType("TEXT"); + + b.Property("DurationMs") + .HasColumnType("INTEGER"); + + b.Property("EndedAt") + .HasColumnType("TEXT"); + + b.Property("Outcome") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("TEXT"); + + b.Property("Protocol") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("TEXT"); + + b.Property("RemoteIp") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("SessionId") + .HasColumnType("TEXT"); + + b.Property("StartedAt") + .HasColumnType("TEXT"); + + b.Property("Strategy") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("Target") + .HasMaxLength(2048) + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("RemoteIp"); + + b.HasIndex("StartedAt"); + + b.ToTable("TrapEvents"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/Flypaper.Storage/Migrations/20261114122204_InitialCreate.cs b/src/Flypaper.Storage/Migrations/20261114122204_InitialCreate.cs new file mode 100644 index 0000000..fe85e57 --- /dev/null +++ b/src/Flypaper.Storage/Migrations/20261114122204_InitialCreate.cs @@ -0,0 +1,55 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Flypaper.Storage.Migrations +{ + /// + public partial class InitialCreate : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "TrapEvents", + columns: table => new + { + Id = table.Column(type: "INTEGER", nullable: false) + .Annotation("Sqlite:Autoincrement", true), + SessionId = table.Column(type: "TEXT", nullable: false), + Protocol = table.Column(type: "TEXT", maxLength: 16, nullable: false), + RemoteIp = table.Column(type: "TEXT", maxLength: 64, nullable: false), + Strategy = table.Column(type: "TEXT", maxLength: 64, nullable: false), + StartedAt = table.Column(type: "TEXT", nullable: false), + EndedAt = table.Column(type: "TEXT", nullable: false), + DurationMs = table.Column(type: "INTEGER", nullable: false), + BytesSent = table.Column(type: "INTEGER", nullable: false), + Outcome = table.Column(type: "TEXT", maxLength: 16, nullable: false), + Target = table.Column(type: "TEXT", maxLength: 2048, nullable: true), + ClientInfo = table.Column(type: "TEXT", maxLength: 2048, nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_TrapEvents", x => x.Id); + }); + + migrationBuilder.CreateIndex( + name: "IX_TrapEvents_RemoteIp", + table: "TrapEvents", + column: "RemoteIp"); + + migrationBuilder.CreateIndex( + name: "IX_TrapEvents_StartedAt", + table: "TrapEvents", + column: "StartedAt"); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "TrapEvents"); + } + } +} diff --git a/src/Flypaper.Storage/Migrations/FlypaperDbContextModelSnapshot.cs b/src/Flypaper.Storage/Migrations/FlypaperDbContextModelSnapshot.cs new file mode 100644 index 0000000..b78260b --- /dev/null +++ b/src/Flypaper.Storage/Migrations/FlypaperDbContextModelSnapshot.cs @@ -0,0 +1,80 @@ +// +using System; +using Flypaper.Storage; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace Flypaper.Storage.Migrations +{ + [DbContext(typeof(FlypaperDbContext))] + partial class FlypaperDbContextModelSnapshot : ModelSnapshot + { + protected override void BuildModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder.HasAnnotation("ProductVersion", "10.0.15"); + + modelBuilder.Entity("Flypaper.Storage.TrapEventEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("BytesSent") + .HasColumnType("INTEGER"); + + b.Property("ClientInfo") + .HasMaxLength(2048) + .HasColumnType("TEXT"); + + b.Property("DurationMs") + .HasColumnType("INTEGER"); + + b.Property("EndedAt") + .HasColumnType("TEXT"); + + b.Property("Outcome") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("TEXT"); + + b.Property("Protocol") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("TEXT"); + + b.Property("RemoteIp") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("SessionId") + .HasColumnType("TEXT"); + + b.Property("StartedAt") + .HasColumnType("TEXT"); + + b.Property("Strategy") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("Target") + .HasMaxLength(2048) + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("RemoteIp"); + + b.HasIndex("StartedAt"); + + b.ToTable("TrapEvents"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/Flypaper.Storage/TrapEventWriter.cs b/src/Flypaper.Storage/TrapEventWriter.cs index a2317ef..984e20a 100644 --- a/src/Flypaper.Storage/TrapEventWriter.cs +++ b/src/Flypaper.Storage/TrapEventWriter.cs @@ -14,11 +14,6 @@ internal sealed class TrapEventWriter( protected override async Task ExecuteAsync(CancellationToken stoppingToken) { - await using (var db = await dbContextFactory.CreateDbContextAsync(stoppingToken)) - { - await db.Database.EnsureCreatedAsync(stoppingToken); - } - var batch = new List(MaxBatchSize); while (await sink.Reader.WaitToReadAsync(stoppingToken)) { diff --git a/src/Flypaper.Web/Components/App.razor b/src/Flypaper.Web/Components/App.razor index ce1943c..bedeb46 100644 --- a/src/Flypaper.Web/Components/App.razor +++ b/src/Flypaper.Web/Components/App.razor @@ -1,5 +1,5 @@  - + diff --git a/src/Flypaper.Web/Components/Layout/MainLayout.razor b/src/Flypaper.Web/Components/Layout/MainLayout.razor index e1a9a75..d7fba3c 100644 --- a/src/Flypaper.Web/Components/Layout/MainLayout.razor +++ b/src/Flypaper.Web/Components/Layout/MainLayout.razor @@ -1,3 +1,5 @@ -@inherits LayoutComponentBase +@inherits LayoutComponentBase -@Body +
+ @Body +
diff --git a/src/Flypaper.Web/Components/Layout/MainLayout.razor.css b/src/Flypaper.Web/Components/Layout/MainLayout.razor.css deleted file mode 100644 index 60cec92..0000000 --- a/src/Flypaper.Web/Components/Layout/MainLayout.razor.css +++ /dev/null @@ -1,20 +0,0 @@ -#blazor-error-ui { - color-scheme: light only; - background: lightyellow; - bottom: 0; - box-shadow: 0 -1px 2px rgba(0, 0, 0, 0.2); - box-sizing: border-box; - display: none; - left: 0; - padding: 0.6rem 1.25rem 0.7rem 1.25rem; - position: fixed; - width: 100%; - z-index: 1000; -} - - #blazor-error-ui .dismiss { - cursor: pointer; - position: absolute; - right: 0.75rem; - top: 0.5rem; - } diff --git a/src/Flypaper.Web/Components/Pages/Home.razor b/src/Flypaper.Web/Components/Pages/Home.razor index 2bbee2a..32e77c1 100644 --- a/src/Flypaper.Web/Components/Pages/Home.razor +++ b/src/Flypaper.Web/Components/Pages/Home.razor @@ -1,7 +1,91 @@ @page "/" +@using Flypaper.Core +@using Flypaper.Storage +@inject DashboardQueries Queries +@inject ConnectionGovernor Governor Flypaper + + + -

Flypaper

+
+

Flypaper

+ Stand @_loadedAt.ToString("HH:mm:ss") · aktualisiert alle 30 s +
-

Dashboard folgt.

+@if (_data is { } data) +{ +
+
Fänge gesamt@data.TotalCatches.ToString("N0")
+
Letzte 24 h@data.CatchesLast24Hours.ToString("N0")
+
Aktiv@Governor.ActiveConnections.ToString("N0")
+
Eindeutige IPs@data.UniqueIps.ToString("N0")
+
Haltezeit gesamt@FormatDuration(data.TotalHoldTime)
+
Abgelehnt@data.Rejected.ToString("N0")
+
+ +
+ + +
+ +
+

Letzte 50 Fänge

+ @if (data.Recent.Count == 0) + { +

Noch nichts gefangen.

+ } + else + { +
+ + + + + + + + + + + + + + @foreach (var trapEvent in data.Recent) + { + + + + + + + + + + } + +
ZeitIPZielUser-AgentDauerBytesAusgang
@trapEvent.StartedAt.ToLocalTime().ToString("dd.MM. HH:mm:ss")@trapEvent.RemoteIp@trapEvent.Target@trapEvent.ClientInfo@FormatDuration(TimeSpan.FromMilliseconds(trapEvent.DurationMs))@trapEvent.BytesSent.ToString("N0")@trapEvent.Outcome
+
+ } +
+} + +@code { + private DashboardData? _data; + private DateTime _loadedAt; + + protected override async Task OnInitializedAsync() + { + _data = await Queries.GetAsync(); + _loadedAt = DateTime.Now; + } + + internal static string FormatDuration(TimeSpan duration) => duration switch + { + { TotalDays: >= 1 } => $"{(int)duration.TotalDays} d {duration.Hours} h", + { TotalHours: >= 1 } => $"{duration.Hours} h {duration.Minutes} min", + { TotalMinutes: >= 1 } => $"{duration.Minutes} min {duration.Seconds} s", + _ => $"{duration.TotalSeconds:0.0} s" + }; +} diff --git a/src/Flypaper.Web/Components/Pages/TopTable.razor b/src/Flypaper.Web/Components/Pages/TopTable.razor new file mode 100644 index 0000000..a6e7e2a --- /dev/null +++ b/src/Flypaper.Web/Components/Pages/TopTable.razor @@ -0,0 +1,39 @@ +@using Flypaper.Storage + +
+

@Title

+ @if (Entries.Count == 0) + { +

Keine Daten.

+ } + else + { + + + + + + + + + + @foreach (var entry in Entries) + { + + + + + + } + +
@KeyLabelFängeHaltezeit
@entry.Key@entry.Count.ToString("N0")@Home.FormatDuration(entry.HoldTime)
+ } +
+ +@code { + [Parameter, EditorRequired] public required string Title { get; set; } + + [Parameter, EditorRequired] public required string KeyLabel { get; set; } + + [Parameter, EditorRequired] public required IReadOnlyList Entries { get; set; } +} diff --git a/src/Flypaper.Web/Program.cs b/src/Flypaper.Web/Program.cs index c7c4189..992ee67 100644 --- a/src/Flypaper.Web/Program.cs +++ b/src/Flypaper.Web/Program.cs @@ -14,6 +14,8 @@ builder.Services.AddFlypaperStorage(builder.Configuration.GetConnectionString("F var app = builder.Build(); +await app.Services.MigrateFlypaperDatabaseAsync(); + app.UseFlypaper(); if (!app.Environment.IsDevelopment()) @@ -27,4 +29,4 @@ app.UseAntiforgery(); app.MapStaticAssets(); app.MapRazorComponents(); -app.Run(); +await app.RunAsync(); diff --git a/src/Flypaper.Web/appsettings.json b/src/Flypaper.Web/appsettings.json index 2bb83b4..2cfcea3 100644 --- a/src/Flypaper.Web/appsettings.json +++ b/src/Flypaper.Web/appsettings.json @@ -2,7 +2,15 @@ "Logging": { "LogLevel": { "Default": "Information", - "Microsoft.AspNetCore": "Warning" + "Microsoft.AspNetCore": "Warning", + "Microsoft.EntityFrameworkCore": "Warning" + }, + "Console": { + "FormatterName": "simple", + "FormatterOptions": { + "SingleLine": true, + "TimestampFormat": "yyyy-MM-dd HH:mm:ss " + } } }, "AllowedHosts": "*", diff --git a/src/Flypaper.Web/wwwroot/app.css b/src/Flypaper.Web/wwwroot/app.css index 5388357..a921049 100644 --- a/src/Flypaper.Web/wwwroot/app.css +++ b/src/Flypaper.Web/wwwroot/app.css @@ -1,38 +1,185 @@ +:root { + --bg: #f6f7f9; + --surface: #ffffff; + --text: #1d232b; + --muted: #6b7380; + --border: #e2e5ea; + --accent: #b5651d; + --ok: #2f7d4a; + --warn: #a6620c; + --bad: #b3261e; + color-scheme: light; +} + +@media (prefers-color-scheme: dark) { + :root { + --bg: #14171c; + --surface: #1c2027; + --text: #e4e7ec; + --muted: #8e96a3; + --border: #2c323c; + --accent: #e09a4f; + --ok: #6cc28a; + --warn: #e0a94f; + --bad: #ef7b72; + color-scheme: dark; + } +} + +* { + box-sizing: border-box; +} + +body { + margin: 0; + background: var(--bg); + color: var(--text); + font: 14px/1.45 system-ui, -apple-system, "Segoe UI", Roboto, sans-serif; +} + h1:focus { outline: none; } -.valid.modified:not([type=checkbox]) { - outline: 1px solid #26b050; +.page { + max-width: 1280px; + margin: 0 auto; + padding: 24px 16px 48px; } -.invalid { - outline: 1px solid #e50000; +.top { + display: flex; + flex-wrap: wrap; + align-items: baseline; + justify-content: space-between; + gap: 8px; + margin-bottom: 20px; } -.validation-message { - color: #e50000; +.top h1 { + margin: 0; + font-size: 22px; + color: var(--accent); } -.blazor-error-boundary { - background: url(data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNTYiIGhlaWdodD0iNDkiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgeG1sbnM6eGxpbms9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkveGxpbmsiIG92ZXJmbG93PSJoaWRkZW4iPjxkZWZzPjxjbGlwUGF0aCBpZD0iY2xpcDAiPjxyZWN0IHg9IjIzNSIgeT0iNTEiIHdpZHRoPSI1NiIgaGVpZ2h0PSI0OSIvPjwvY2xpcFBhdGg+PC9kZWZzPjxnIGNsaXAtcGF0aD0idXJsKCNjbGlwMCkiIHRyYW5zZm9ybT0idHJhbnNsYXRlKC0yMzUgLTUxKSI+PHBhdGggZD0iTTI2My41MDYgNTFDMjY0LjcxNyA1MSAyNjUuODEzIDUxLjQ4MzcgMjY2LjYwNiA1Mi4yNjU4TDI2Ny4wNTIgNTIuNzk4NyAyNjcuNTM5IDUzLjYyODMgMjkwLjE4NSA5Mi4xODMxIDI5MC41NDUgOTIuNzk1IDI5MC42NTYgOTIuOTk2QzI5MC44NzcgOTMuNTEzIDI5MSA5NC4wODE1IDI5MSA5NC42NzgyIDI5MSA5Ny4wNjUxIDI4OS4wMzggOTkgMjg2LjYxNyA5OUwyNDAuMzgzIDk5QzIzNy45NjMgOTkgMjM2IDk3LjA2NTEgMjM2IDk0LjY3ODIgMjM2IDk0LjM3OTkgMjM2LjAzMSA5NC4wODg2IDIzNi4wODkgOTMuODA3MkwyMzYuMzM4IDkzLjAxNjIgMjM2Ljg1OCA5Mi4xMzE0IDI1OS40NzMgNTMuNjI5NCAyNTkuOTYxIDUyLjc5ODUgMjYwLjQwNyA1Mi4yNjU4QzI2MS4yIDUxLjQ4MzcgMjYyLjI5NiA1MSAyNjMuNTA2IDUxWk0yNjMuNTg2IDY2LjAxODNDMjYwLjczNyA2Ni4wMTgzIDI1OS4zMTMgNjcuMTI0NSAyNTkuMzEzIDY5LjMzNyAyNTkuMzEzIDY5LjYxMDIgMjU5LjMzMiA2OS44NjA4IDI1OS4zNzEgNzAuMDg4N0wyNjEuNzk1IDg0LjAxNjEgMjY1LjM4IDg0LjAxNjEgMjY3LjgyMSA2OS43NDc1QzI2Ny44NiA2OS43MzA5IDI2Ny44NzkgNjkuNTg3NyAyNjcuODc5IDY5LjMxNzkgMjY3Ljg3OSA2Ny4xMTgyIDI2Ni40NDggNjYuMDE4MyAyNjMuNTg2IDY2LjAxODNaTTI2My41NzYgODYuMDU0N0MyNjEuMDQ5IDg2LjA1NDcgMjU5Ljc4NiA4Ny4zMDA1IDI1OS43ODYgODkuNzkyMSAyNTkuNzg2IDkyLjI4MzcgMjYxLjA0OSA5My41Mjk1IDI2My41NzYgOTMuNTI5NSAyNjYuMTE2IDkzLjUyOTUgMjY3LjM4NyA5Mi4yODM3IDI2Ny4zODcgODkuNzkyMSAyNjcuMzg3IDg3LjMwMDUgMjY2LjExNiA4Ni4wNTQ3IDI2My41NzYgODYuMDU0N1oiIGZpbGw9IiNGRkU1MDAiIGZpbGwtcnVsZT0iZXZlbm9kZCIvPjwvZz48L3N2Zz4=) no-repeat 1rem/1.8rem, #b32121; - padding: 1rem 1rem 1rem 3.7rem; - color: white; +h2 { + margin: 0 0 12px; + font-size: 15px; } - .blazor-error-boundary::after { - content: "An error has occurred." +.muted { + color: var(--muted); +} + +.metrics { + display: grid; + grid-template-columns: repeat(auto-fit, minmax(160px, 1fr)); + gap: 12px; + margin-bottom: 16px; +} + +.metric, +.card { + background: var(--surface); + border: 1px solid var(--border); + border-radius: 8px; + padding: 14px 16px; +} + +.metric .label { + display: block; + color: var(--muted); + font-size: 12px; +} + +.metric .value { + display: block; + margin-top: 4px; + font-size: 24px; + font-weight: 600; + font-variant-numeric: tabular-nums; +} + +.tops { + display: grid; + grid-template-columns: repeat(auto-fit, minmax(340px, 1fr)); + gap: 16px; + margin-bottom: 16px; +} + +.scroll { + overflow-x: auto; +} + +table { + width: 100%; + border-collapse: collapse; + table-layout: auto; +} + +th, +td { + padding: 6px 8px; + border-bottom: 1px solid var(--border); + text-align: left; + vertical-align: top; +} + +th { + color: var(--muted); + font-size: 12px; + font-weight: 500; +} + +tbody tr:last-child td { + border-bottom: none; +} + +.num { + text-align: right; + font-variant-numeric: tabular-nums; + white-space: nowrap; +} + +.nowrap { + white-space: nowrap; +} + +.mono { + font-family: ui-monospace, "SF Mono", Menlo, Consolas, monospace; + font-size: 13px; +} + +.clip { + max-width: 320px; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.outcome { + font-size: 12px; + font-weight: 600; +} + +.outcome.timeout { + color: var(--ok); +} + +.outcome.clientaborted { + color: var(--warn); +} + +.outcome.rejected { + color: var(--bad); +} + +@media (max-width: 600px) { + .tops { + grid-template-columns: 1fr; } -.darker-border-checkbox.form-check-input { - border-color: #929292; + .clip { + max-width: 180px; + } } - -.form-floating > .form-control-plaintext::placeholder, .form-floating > .form-control::placeholder { - color: var(--bs-secondary-color); - text-align: end; -} - -.form-floating > .form-control-plaintext:focus::placeholder, .form-floating > .form-control:focus::placeholder { - text-align: start; -} \ No newline at end of file diff --git a/test/Flypaper.Tests/ForwardedHeadersTests.cs b/test/Flypaper.Tests/ForwardedHeadersTests.cs new file mode 100644 index 0000000..318caad --- /dev/null +++ b/test/Flypaper.Tests/ForwardedHeadersTests.cs @@ -0,0 +1,90 @@ +using System.Net; +using Flypaper.Core; +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; + +public sealed class ForwardedHeadersTests +{ + private static readonly IPAddress Npm = IPAddress.Parse("172.18.0.5"); + private const string Client = "198.51.100.7"; + + [Fact] + public async Task Uses_x_forwarded_for_from_proxy_in_trusted_network() + { + var ip = await SendAsync(Npm, ("X-Forwarded-For", $"10.9.9.9, {Client}")); + + ip.ShouldBe(IPAddress.Parse(Client)); + } + + [Fact] + public async Task Accepts_ipv4_mapped_proxy_address() + { + var ip = await SendAsync(Npm.MapToIPv6(), ("X-Forwarded-For", Client)); + + ip.ShouldBe(IPAddress.Parse(Client)); + } + + [Fact] + public async Task Falls_back_to_x_real_ip() + { + var ip = await SendAsync(Npm.MapToIPv6(), ("X-Real-IP", Client)); + + ip.ShouldBe(IPAddress.Parse(Client)); + } + + [Fact] + public async Task Ignores_headers_from_untrusted_sender() + { + var sender = IPAddress.Parse("203.0.113.50"); + + var ip = await SendAsync(sender, ("X-Forwarded-For", Client), ("X-Real-IP", Client)); + + ip.ShouldBe(sender); + } + + private static async Task SendAsync(IPAddress remoteIp, params (string Name, string Value)[] headers) + { + var configuration = new ConfigurationBuilder() + .AddInMemoryCollection(new Dictionary + { + ["Flypaper:Http:KnownHosts:0"] = "dashboard.lan", + ["Flypaper:Http:TrustedProxies:0"] = "172.18.0.0/16" + }) + .Build(); + + var services = new ServiceCollection() + .AddLogging() + .AddSingleton(Substitute.For()) + .AddFlypaperCore(configuration) + .AddFlypaperHttp(configuration) + .BuildServiceProvider(); + + IPAddress? seen = null; + var app = new ApplicationBuilder(services); + app.UseFlypaper(); + app.Run(context => + { + seen = context.Connection.RemoteIpAddress; + return Task.CompletedTask; + }); + + var httpContext = new DefaultHttpContext { RequestServices = services }; + httpContext.Connection.RemoteIpAddress = remoteIp; + httpContext.Request.Host = new HostString("dashboard.lan"); + httpContext.Request.Path = "/"; + foreach (var (name, value) in headers) + { + httpContext.Request.Headers[name] = value; + } + + await app.Build()(httpContext); + return seen; + } +} diff --git a/test/Flypaper.Tests/TrapRunnerTests.cs b/test/Flypaper.Tests/TrapRunnerTests.cs index 97230e1..6d78b04 100644 --- a/test/Flypaper.Tests/TrapRunnerTests.cs +++ b/test/Flypaper.Tests/TrapRunnerTests.cs @@ -1,6 +1,7 @@ using System.Net; using Flypaper.Core; using Flypaper.Core.Strategies; +using Microsoft.Extensions.Logging.Abstractions; using Microsoft.Extensions.Options; using NSubstitute; using Shouldly; @@ -80,7 +81,8 @@ public sealed class TrapRunnerTests [drip], _sink, Options.Create(new FlypaperOptions { MaxHoldDuration = maxHoldDuration }), - TimeProvider.System); + TimeProvider.System, + NullLogger.Instance); } private static TrapContext Context() =>