Add trap logging, dashboard, EF migrations and Dockerfile

This commit is contained in:
Tom committed 2026-11-14 13:31:59 +01:00
1 parent f9161f48e7
commit b561924efa
26 files changed
+784 -62

No files matched your search

+8
View File
@@ -0,0 +1,8 @@
**/bin/
**/obj/
**/*.db
**/*.db-shm
**/*.db-wal
.git/
.idea/
test/
+2
View File
@@ -6,7 +6,9 @@
<ItemGroup> <ItemGroup>
<PackageVersion Include="Microsoft.Extensions.DependencyInjection.Abstractions" 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.Hosting.Abstractions" Version="10.0.15" />
<PackageVersion Include="Microsoft.Extensions.Logging.Abstractions" Version="10.0.15" />
<PackageVersion Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="10.0.15" /> <PackageVersion Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="10.0.15" />
<PackageVersion Include="Microsoft.EntityFrameworkCore.Design" Version="10.0.15" />
<PackageVersion Include="Microsoft.EntityFrameworkCore.Sqlite" Version="10.0.15" /> <PackageVersion Include="Microsoft.EntityFrameworkCore.Sqlite" Version="10.0.15" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
+28
View File
@@ -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"]
+1
View File
@@ -2,6 +2,7 @@
<ItemGroup> <ItemGroup>
<PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" /> <PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" />
<PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" /> <PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" />
</ItemGroup> </ItemGroup>
@@ -13,7 +13,8 @@ public static class ServiceCollectionExtensions
services.Configure<DripOptions>(configuration.GetSection(DripOptions.SectionName)); services.Configure<DripOptions>(configuration.GetSection(DripOptions.SectionName));
services.TryAddSingleton(TimeProvider.System); services.TryAddSingleton(TimeProvider.System);
services.TryAddSingleton<IConnectionGovernor, ConnectionGovernor>(); services.TryAddSingleton<ConnectionGovernor>();
services.TryAddSingleton<IConnectionGovernor>(sp => sp.GetRequiredService<ConnectionGovernor>());
services.TryAddEnumerable(ServiceDescriptor.Singleton<ITarpitStrategy, DripStrategy>()); services.TryAddEnumerable(ServiceDescriptor.Singleton<ITarpitStrategy, DripStrategy>());
services.TryAddSingleton<TrapRunner>(); services.TryAddSingleton<TrapRunner>();
+37 -4
View File
@@ -1,13 +1,16 @@
using System.Net;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options; using Microsoft.Extensions.Options;
namespace Flypaper.Core; namespace Flypaper.Core;
public sealed class TrapRunner( public sealed partial class TrapRunner(
IConnectionGovernor governor, IConnectionGovernor governor,
IEnumerable<ITarpitStrategy> strategies, IEnumerable<ITarpitStrategy> strategies,
ITrapEventSink sink, ITrapEventSink sink,
IOptions<FlypaperOptions> options, IOptions<FlypaperOptions> options,
TimeProvider timeProvider) TimeProvider timeProvider,
ILogger<TrapRunner> logger)
{ {
public async Task<TrapOutcome> RunAsync( public async Task<TrapOutcome> RunAsync(
TrapContext context, TrapContext context,
@@ -52,7 +55,7 @@ public sealed class TrapRunner(
private void Publish(TrapContext context, string strategy, long bytesSent, TrapOutcome outcome) private void Publish(TrapContext context, string strategy, long bytesSent, TrapOutcome outcome)
{ {
var session = context.Session; var session = context.Session;
sink.Publish(new TrapEvent( var trapEvent = new TrapEvent(
session.Id, session.Id,
session.Protocol, session.Protocol,
session.RemoteIp, session.RemoteIp,
@@ -62,6 +65,36 @@ public sealed class TrapRunner(
bytesSent, bytesSent,
outcome, outcome,
context.Target, 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);
} }
+2 -1
View File
@@ -21,10 +21,11 @@ internal sealed class FlypaperMiddleware(
return; return;
} }
var remoteIp = context.Connection.RemoteIpAddress ?? IPAddress.None;
var session = new TrapSession( var session = new TrapSession(
Guid.NewGuid(), Guid.NewGuid(),
TrapProtocol.Http, TrapProtocol.Http,
context.Connection.RemoteIpAddress ?? IPAddress.None, remoteIp.IsIPv4MappedToIPv6 ? remoteIp.MapToIPv4() : remoteIp,
timeProvider.GetUtcNow()); timeProvider.GetUtcNow());
var trapContext = new TrapContext( var trapContext = new TrapContext(
+13
View File
@@ -0,0 +1,13 @@
namespace Flypaper.Storage;
public sealed record DashboardData(
int TotalCatches,
int CatchesLast24Hours,
int Rejected,
int UniqueIps,
TimeSpan TotalHoldTime,
IReadOnlyList<TrapEventEntity> Recent,
IReadOnlyList<TopEntry> TopIps,
IReadOnlyList<TopEntry> TopTargets);
public sealed record TopEntry(string Key, int Count, TimeSpan HoldTime);
+49
View File
@@ -0,0 +1,49 @@
using Flypaper.Core;
using Microsoft.EntityFrameworkCore;
namespace Flypaper.Storage;
public sealed class DashboardQueries(IDbContextFactory<FlypaperDbContext> dbContextFactory, TimeProvider timeProvider)
{
private const int RecentCount = 50;
private const int TopCount = 10;
public async Task<DashboardData> 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<IReadOnlyList<TopEntry>> TopAsync(
IQueryable<IGrouping<string, TrapEventEntity>> 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();
}
}
@@ -0,0 +1,10 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Design;
namespace Flypaper.Storage;
internal sealed class DesignTimeDbContextFactory : IDesignTimeDbContextFactory<FlypaperDbContext>
{
public FlypaperDbContext CreateDbContext(string[] args) =>
new(new DbContextOptionsBuilder<FlypaperDbContext>().UseSqlite("Data Source=flypaper.db").Options);
}
@@ -1,6 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk"> <Project Sdk="Microsoft.NET.Sdk">
<ItemGroup> <ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" PrivateAssets="all" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" /> <PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" />
<PackageReference Include="Microsoft.Extensions.Hosting.Abstractions" /> <PackageReference Include="Microsoft.Extensions.Hosting.Abstractions" />
</ItemGroup> </ItemGroup>
@@ -12,6 +12,14 @@ public static class FlypaperStorageExtensions
services.AddSingleton<ChannelTrapEventSink>(); services.AddSingleton<ChannelTrapEventSink>();
services.AddSingleton<ITrapEventSink>(sp => sp.GetRequiredService<ChannelTrapEventSink>()); services.AddSingleton<ITrapEventSink>(sp => sp.GetRequiredService<ChannelTrapEventSink>());
services.AddHostedService<TrapEventWriter>(); services.AddHostedService<TrapEventWriter>();
services.AddSingleton<DashboardQueries>();
return services; return services;
} }
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);
}
} }
@@ -0,0 +1,83 @@
// <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("20261114122204_InitialCreate")]
partial class InitialCreate
{
/// <inheritdoc />
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<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,55 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Flypaper.Storage.Migrations
{
/// <inheritdoc />
public partial class InitialCreate : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "TrapEvents",
columns: table => new
{
Id = table.Column<long>(type: "INTEGER", nullable: false)
.Annotation("Sqlite:Autoincrement", true),
SessionId = table.Column<Guid>(type: "TEXT", nullable: false),
Protocol = table.Column<string>(type: "TEXT", maxLength: 16, nullable: false),
RemoteIp = table.Column<string>(type: "TEXT", maxLength: 64, nullable: false),
Strategy = table.Column<string>(type: "TEXT", maxLength: 64, nullable: false),
StartedAt = table.Column<DateTime>(type: "TEXT", nullable: false),
EndedAt = table.Column<DateTime>(type: "TEXT", nullable: false),
DurationMs = table.Column<long>(type: "INTEGER", nullable: false),
BytesSent = table.Column<long>(type: "INTEGER", nullable: false),
Outcome = table.Column<string>(type: "TEXT", maxLength: 16, nullable: false),
Target = table.Column<string>(type: "TEXT", maxLength: 2048, nullable: true),
ClientInfo = table.Column<string>(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");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "TrapEvents");
}
}
}
@@ -0,0 +1,80 @@
// <auto-generated />
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<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
}
}
}
-5
View File
@@ -14,11 +14,6 @@ internal sealed class TrapEventWriter(
protected override async Task ExecuteAsync(CancellationToken stoppingToken) protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{ {
await using (var db = await dbContextFactory.CreateDbContextAsync(stoppingToken))
{
await db.Database.EnsureCreatedAsync(stoppingToken);
}
var batch = new List<TrapEvent>(MaxBatchSize); var batch = new List<TrapEvent>(MaxBatchSize);
while (await sink.Reader.WaitToReadAsync(stoppingToken)) while (await sink.Reader.WaitToReadAsync(stoppingToken))
{ {
+1 -1
View File
@@ -1,5 +1,5 @@
<!DOCTYPE html> <!DOCTYPE html>
<html lang="en"> <html lang="de">
<head> <head>
<meta charset="utf-8" /> <meta charset="utf-8" />
@@ -1,3 +1,5 @@
@inherits LayoutComponentBase @inherits LayoutComponentBase
@Body <main class="page">
@Body
</main>
@@ -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;
}
+86 -2
View File
@@ -1,7 +1,91 @@
@page "/" @page "/"
@using Flypaper.Core
@using Flypaper.Storage
@inject DashboardQueries Queries
@inject ConnectionGovernor Governor
<PageTitle>Flypaper</PageTitle> <PageTitle>Flypaper</PageTitle>
<HeadContent>
<meta http-equiv="refresh" content="30" />
</HeadContent>
<h1>Flypaper</h1> <header class="top">
<h1>Flypaper</h1>
<span class="muted">Stand @_loadedAt.ToString("HH:mm:ss") · aktualisiert alle 30 s</span>
</header>
<p>Dashboard folgt.</p> @if (_data is { } data)
{
<section class="metrics">
<div class="metric"><span class="label">Fänge gesamt</span><span class="value">@data.TotalCatches.ToString("N0")</span></div>
<div class="metric"><span class="label">Letzte 24 h</span><span class="value">@data.CatchesLast24Hours.ToString("N0")</span></div>
<div class="metric"><span class="label">Aktiv</span><span class="value">@Governor.ActiveConnections.ToString("N0")</span></div>
<div class="metric"><span class="label">Eindeutige IPs</span><span class="value">@data.UniqueIps.ToString("N0")</span></div>
<div class="metric"><span class="label">Haltezeit gesamt</span><span class="value">@FormatDuration(data.TotalHoldTime)</span></div>
<div class="metric"><span class="label">Abgelehnt</span><span class="value">@data.Rejected.ToString("N0")</span></div>
</section>
<section class="tops">
<TopTable Title="Top 10 IPs" KeyLabel="IP" Entries="data.TopIps" />
<TopTable Title="Top 10 Ziele" KeyLabel="Ziel" Entries="data.TopTargets" />
</section>
<section class="card">
<h2>Letzte 50 Fänge</h2>
@if (data.Recent.Count == 0)
{
<p class="muted">Noch nichts gefangen.</p>
}
else
{
<div class="scroll">
<table>
<thead>
<tr>
<th>Zeit</th>
<th>IP</th>
<th>Ziel</th>
<th>User-Agent</th>
<th class="num">Dauer</th>
<th class="num">Bytes</th>
<th>Ausgang</th>
</tr>
</thead>
<tbody>
@foreach (var trapEvent in data.Recent)
{
<tr>
<td class="nowrap">@trapEvent.StartedAt.ToLocalTime().ToString("dd.MM. HH:mm:ss")</td>
<td class="mono">@trapEvent.RemoteIp</td>
<td class="mono clip" title="@trapEvent.Target">@trapEvent.Target</td>
<td class="clip" title="@trapEvent.ClientInfo">@trapEvent.ClientInfo</td>
<td class="num">@FormatDuration(TimeSpan.FromMilliseconds(trapEvent.DurationMs))</td>
<td class="num">@trapEvent.BytesSent.ToString("N0")</td>
<td><span class="outcome @trapEvent.Outcome.ToString().ToLowerInvariant()">@trapEvent.Outcome</span></td>
</tr>
}
</tbody>
</table>
</div>
}
</section>
}
@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"
};
}
@@ -0,0 +1,39 @@
@using Flypaper.Storage
<section class="card">
<h2>@Title</h2>
@if (Entries.Count == 0)
{
<p class="muted">Keine Daten.</p>
}
else
{
<table>
<thead>
<tr>
<th>@KeyLabel</th>
<th class="num">Fänge</th>
<th class="num">Haltezeit</th>
</tr>
</thead>
<tbody>
@foreach (var entry in Entries)
{
<tr>
<td class="mono clip" title="@entry.Key">@entry.Key</td>
<td class="num">@entry.Count.ToString("N0")</td>
<td class="num">@Home.FormatDuration(entry.HoldTime)</td>
</tr>
}
</tbody>
</table>
}
</section>
@code {
[Parameter, EditorRequired] public required string Title { get; set; }
[Parameter, EditorRequired] public required string KeyLabel { get; set; }
[Parameter, EditorRequired] public required IReadOnlyList<TopEntry> Entries { get; set; }
}
+3 -1
View File
@@ -14,6 +14,8 @@ builder.Services.AddFlypaperStorage(builder.Configuration.GetConnectionString("F
var app = builder.Build(); var app = builder.Build();
await app.Services.MigrateFlypaperDatabaseAsync();
app.UseFlypaper(); app.UseFlypaper();
if (!app.Environment.IsDevelopment()) if (!app.Environment.IsDevelopment())
@@ -27,4 +29,4 @@ app.UseAntiforgery();
app.MapStaticAssets(); app.MapStaticAssets();
app.MapRazorComponents<App>(); app.MapRazorComponents<App>();
app.Run(); await app.RunAsync();
+9 -1
View File
@@ -2,7 +2,15 @@
"Logging": { "Logging": {
"LogLevel": { "LogLevel": {
"Default": "Information", "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": "*", "AllowedHosts": "*",
+170 -23
View File
@@ -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 { h1:focus {
outline: none; outline: none;
} }
.valid.modified:not([type=checkbox]) { .page {
outline: 1px solid #26b050; max-width: 1280px;
margin: 0 auto;
padding: 24px 16px 48px;
} }
.invalid { .top {
outline: 1px solid #e50000; display: flex;
flex-wrap: wrap;
align-items: baseline;
justify-content: space-between;
gap: 8px;
margin-bottom: 20px;
} }
.validation-message { .top h1 {
color: #e50000; margin: 0;
font-size: 22px;
color: var(--accent);
} }
.blazor-error-boundary { h2 {
background: url(data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNTYiIGhlaWdodD0iNDkiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgeG1sbnM6eGxpbms9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkveGxpbmsiIG92ZXJmbG93PSJoaWRkZW4iPjxkZWZzPjxjbGlwUGF0aCBpZD0iY2xpcDAiPjxyZWN0IHg9IjIzNSIgeT0iNTEiIHdpZHRoPSI1NiIgaGVpZ2h0PSI0OSIvPjwvY2xpcFBhdGg+PC9kZWZzPjxnIGNsaXAtcGF0aD0idXJsKCNjbGlwMCkiIHRyYW5zZm9ybT0idHJhbnNsYXRlKC0yMzUgLTUxKSI+PHBhdGggZD0iTTI2My41MDYgNTFDMjY0LjcxNyA1MSAyNjUuODEzIDUxLjQ4MzcgMjY2LjYwNiA1Mi4yNjU4TDI2Ny4wNTIgNTIuNzk4NyAyNjcuNTM5IDUzLjYyODMgMjkwLjE4NSA5Mi4xODMxIDI5MC41NDUgOTIuNzk1IDI5MC42NTYgOTIuOTk2QzI5MC44NzcgOTMuNTEzIDI5MSA5NC4wODE1IDI5MSA5NC42NzgyIDI5MSA5Ny4wNjUxIDI4OS4wMzggOTkgMjg2LjYxNyA5OUwyNDAuMzgzIDk5QzIzNy45NjMgOTkgMjM2IDk3LjA2NTEgMjM2IDk0LjY3ODIgMjM2IDk0LjM3OTkgMjM2LjAzMSA5NC4wODg2IDIzNi4wODkgOTMuODA3MkwyMzYuMzM4IDkzLjAxNjIgMjM2Ljg1OCA5Mi4xMzE0IDI1OS40NzMgNTMuNjI5NCAyNTkuOTYxIDUyLjc5ODUgMjYwLjQwNyA1Mi4yNjU4QzI2MS4yIDUxLjQ4MzcgMjYyLjI5NiA1MSAyNjMuNTA2IDUxWk0yNjMuNTg2IDY2LjAxODNDMjYwLjczNyA2Ni4wMTgzIDI1OS4zMTMgNjcuMTI0NSAyNTkuMzEzIDY5LjMzNyAyNTkuMzEzIDY5LjYxMDIgMjU5LjMzMiA2OS44NjA4IDI1OS4zNzEgNzAuMDg4N0wyNjEuNzk1IDg0LjAxNjEgMjY1LjM4IDg0LjAxNjEgMjY3LjgyMSA2OS43NDc1QzI2Ny44NiA2OS43MzA5IDI2Ny44NzkgNjkuNTg3NyAyNjcuODc5IDY5LjMxNzkgMjY3Ljg3OSA2Ny4xMTgyIDI2Ni40NDggNjYuMDE4MyAyNjMuNTg2IDY2LjAxODNaTTI2My41NzYgODYuMDU0N0MyNjEuMDQ5IDg2LjA1NDcgMjU5Ljc4NiA4Ny4zMDA1IDI1OS43ODYgODkuNzkyMSAyNTkuNzg2IDkyLjI4MzcgMjYxLjA0OSA5My41Mjk1IDI2My41NzYgOTMuNTI5NSAyNjYuMTE2IDkzLjUyOTUgMjY3LjM4NyA5Mi4yODM3IDI2Ny4zODcgODkuNzkyMSAyNjcuMzg3IDg3LjMwMDUgMjY2LjExNiA4Ni4wNTQ3IDI2My41NzYgODYuMDU0N1oiIGZpbGw9IiNGRkU1MDAiIGZpbGwtcnVsZT0iZXZlbm9kZCIvPjwvZz48L3N2Zz4=) no-repeat 1rem/1.8rem, #b32121; margin: 0 0 12px;
padding: 1rem 1rem 1rem 3.7rem; font-size: 15px;
color: white;
} }
.blazor-error-boundary::after { .muted {
content: "An error has occurred." 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 { .clip {
border-color: #929292; 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;
}
@@ -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<IPAddress?> SendAsync(IPAddress remoteIp, params (string Name, string Value)[] headers)
{
var configuration = new ConfigurationBuilder()
.AddInMemoryCollection(new Dictionary<string, string?>
{
["Flypaper:Http:KnownHosts:0"] = "dashboard.lan",
["Flypaper:Http:TrustedProxies:0"] = "172.18.0.0/16"
})
.Build();
var services = new ServiceCollection()
.AddLogging()
.AddSingleton(Substitute.For<ITrapEventSink>())
.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;
}
}
+3 -1
View File
@@ -1,6 +1,7 @@
using System.Net; using System.Net;
using Flypaper.Core; using Flypaper.Core;
using Flypaper.Core.Strategies; using Flypaper.Core.Strategies;
using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.Extensions.Options; using Microsoft.Extensions.Options;
using NSubstitute; using NSubstitute;
using Shouldly; using Shouldly;
@@ -80,7 +81,8 @@ public sealed class TrapRunnerTests
[drip], [drip],
_sink, _sink,
Options.Create(new FlypaperOptions { MaxHoldDuration = maxHoldDuration }), Options.Create(new FlypaperOptions { MaxHoldDuration = maxHoldDuration }),
TimeProvider.System); TimeProvider.System,
NullLogger<TrapRunner>.Instance);
} }
private static TrapContext Context() => private static TrapContext Context() =>