From 9f07d41cb05f5b1659b51c1d5ca72274e96e4dd6 Mon Sep 17 00:00:00 2001 From: Tom Date: Sun, 15 Nov 2026 23:40:52 +0100 Subject: [PATCH] Add filters to the dashboard catch list and filter by clicking top 10 rows Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 7 + .../Dashboard/DashboardData.cs | 3 - .../Dashboard/DashboardQueries.cs | 67 ++++- .../Dashboard/RecentFilter.cs | 22 ++ .../Pages/Dashboard/DashboardFilter.cs | 120 ++++++++ .../Pages/Dashboard/DashboardPage.razor | 271 ++++++++++++++---- .../Components/Pages/Dashboard/TopTable.razor | 38 ++- src/Flypaper.Web/wwwroot/app.css | 154 ++++++++++ src/Flypaper.Web/wwwroot/dashboard.js | 26 ++ .../Storage/RecentCatchesTests.cs | 79 +++++ .../Web/DashboardFilterTests.cs | 67 +++++ 11 files changed, 771 insertions(+), 83 deletions(-) create mode 100644 src/Flypaper.Storage/Dashboard/RecentFilter.cs create mode 100644 src/Flypaper.Web/Components/Pages/Dashboard/DashboardFilter.cs create mode 100644 test/Flypaper.Tests/Storage/RecentCatchesTests.cs create mode 100644 test/Flypaper.Tests/Web/DashboardFilterTests.cs diff --git a/CHANGELOG.md b/CHANGELOG.md index 6cca37d..c37492b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -22,6 +22,13 @@ All notable changes to Flypaper are documented in this file. The format follows 24 hours, and the catch list marks them with an "Abgelehnt" badge. Outcomes are shown in German. Top lists and hold times still count only real catches. - The "Haltezeit gesamt" metric shows the average hold time per catch below it. +- The catch list on the dashboard has filters for period, outcome, country and a free-text + search over IP, provider, target and user agent. A click on a top 10 row filters the list by + that country, provider, IP or target (a second click removes it). Active filters show as + chips with the number of matches, live in the URL (`?land=HK&ausgang=abgelehnt&q=…`) and + survive the auto-refresh; "Weitere laden" shows up to 500 entries. Metrics and top 10 stay + unfiltered. +- The outcome "Abgebrochen" is now called "Aufgegeben". - Dashboard polish: equal metric tiles with a one-line note each (unique IPs show the last 24 hours), map and top 10 card of equal height with a larger legend and visible small-country markers, country and provider names in the regular font with a separate share diff --git a/src/Flypaper.Storage/Dashboard/DashboardData.cs b/src/Flypaper.Storage/Dashboard/DashboardData.cs index ba53ce8..a72a7bb 100644 --- a/src/Flypaper.Storage/Dashboard/DashboardData.cs +++ b/src/Flypaper.Storage/Dashboard/DashboardData.cs @@ -1,5 +1,3 @@ -using Flypaper.Storage.Entities; - namespace Flypaper.Storage.Dashboard; public sealed record DashboardData( @@ -10,7 +8,6 @@ public sealed record DashboardData( int UniqueIps, int UniqueIpsLast24Hours, TimeSpan TotalHoldTime, - IReadOnlyList Recent, IReadOnlyList TopIps, IReadOnlyList TopTargets, IReadOnlyList TopCountries, diff --git a/src/Flypaper.Storage/Dashboard/DashboardQueries.cs b/src/Flypaper.Storage/Dashboard/DashboardQueries.cs index d150898..9fbfa8c 100644 --- a/src/Flypaper.Storage/Dashboard/DashboardQueries.cs +++ b/src/Flypaper.Storage/Dashboard/DashboardQueries.cs @@ -6,7 +6,6 @@ namespace Flypaper.Storage.Dashboard; 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) @@ -41,7 +40,6 @@ public sealed class DashboardQueries(IDbContextFactory dbCont await events.Select(e => e.RemoteIp).Distinct().CountAsync(ct), await events.Where(e => e.StartedAt >= since).Select(e => e.RemoteIp).Distinct().CountAsync(ct), TimeSpan.FromMilliseconds(await catches.SumAsync(e => e.DurationMs, ct)), - await events.OrderByDescending(e => e.Id).Take(RecentCount).ToListAsync(ct), await TopAsync(catches.GroupBy(e => e.RemoteIp), ct), await TopAsync(catches.Where(e => e.Target != null).GroupBy(e => e.Target!), ct), countries @@ -54,6 +52,71 @@ public sealed class DashboardQueries(IDbContextFactory dbCont countries.ToDictionary(x => x.Key, x => x.Count, StringComparer.OrdinalIgnoreCase)); } + public async Task GetRecentAsync(RecentFilter filter, CancellationToken ct = default) + { + await using var db = await dbContextFactory.CreateDbContextAsync(ct); + var events = Apply(db.TrapEvents.AsNoTracking(), filter); + + var countries = await db.TrapEvents + .Where(e => e.CountryCode != null) + .GroupBy(e => e.CountryCode!) + .Select(g => new CountryOption(g.Key, g.Max(e => e.Country))) + .ToListAsync(ct); + + return new RecentCatches( + await events.OrderByDescending(e => e.StartedAt).ThenByDescending(e => e.Id) + .Take(Math.Clamp(filter.Limit, 1, RecentFilter.MaxLimit)) + .ToListAsync(ct), + await events.CountAsync(ct), + countries); + } + + private IQueryable Apply(IQueryable events, RecentFilter filter) + { + if (filter.Window is { } window) + { + var since = timeProvider.GetUtcNow().UtcDateTime - window; + events = events.Where(e => e.StartedAt >= since); + } + + if (filter.Outcome is { } outcome) + { + events = events.Where(e => e.Outcome == outcome); + } + + if (filter.CountryCode is { } country) + { + events = events.Where(e => e.CountryCode == country); + } + + if (filter.Asn is { } asn) + { + events = events.Where(e => e.Asn == asn); + } + + if (filter.Ip is { } ip) + { + events = events.Where(e => e.RemoteIp == ip); + } + + if (filter.Target is { } target) + { + events = events.Where(e => e.Target == target); + } + + if (!string.IsNullOrWhiteSpace(filter.Search)) + { + var pattern = $"%{filter.Search.Trim().Replace("\\", "\\\\").Replace("%", "\\%").Replace("_", "\\_")}%"; + events = events.Where(e => + EF.Functions.Like(e.RemoteIp, pattern, "\\") + || EF.Functions.Like(e.Provider!, pattern, "\\") + || EF.Functions.Like(e.Target!, pattern, "\\") + || EF.Functions.Like(e.ClientInfo!, pattern, "\\")); + } + + return events; + } + private static async Task> TopAsync( IQueryable> groups, CancellationToken ct) diff --git a/src/Flypaper.Storage/Dashboard/RecentFilter.cs b/src/Flypaper.Storage/Dashboard/RecentFilter.cs new file mode 100644 index 0000000..8fbc415 --- /dev/null +++ b/src/Flypaper.Storage/Dashboard/RecentFilter.cs @@ -0,0 +1,22 @@ +using Flypaper.Core.Models; +using Flypaper.Storage.Entities; + +namespace Flypaper.Storage.Dashboard; + +public sealed record RecentFilter( + TimeSpan? Window = null, + TrapOutcome? Outcome = null, + string? CountryCode = null, + long? Asn = null, + string? Ip = null, + string? Target = null, + string? Search = null, + int Limit = RecentFilter.DefaultLimit) +{ + public const int DefaultLimit = 50; + public const int MaxLimit = 500; +} + +public sealed record RecentCatches(IReadOnlyList Items, int Total, IReadOnlyList Countries); + +public sealed record CountryOption(string Code, string? Name); diff --git a/src/Flypaper.Web/Components/Pages/Dashboard/DashboardFilter.cs b/src/Flypaper.Web/Components/Pages/Dashboard/DashboardFilter.cs new file mode 100644 index 0000000..3cf9372 --- /dev/null +++ b/src/Flypaper.Web/Components/Pages/Dashboard/DashboardFilter.cs @@ -0,0 +1,120 @@ +using System.Globalization; +using System.Net; +using Flypaper.Core.Models; +using Flypaper.Storage.Dashboard; + +namespace Flypaper.Web.Components.Pages.Dashboard; + +public sealed record DashboardFilter( + string? Zeit = null, + string? Ausgang = null, + string? Land = null, + string? Provider = null, + string? Ip = null, + string? Ziel = null, + string? Q = null, + int Limit = RecentFilter.DefaultLimit) +{ + public const string Anchor = "faenge"; + + public static readonly IReadOnlyList<(string Value, string Label)> Periods = [("", "Alles"), ("24h", "24 h"), ("7d", "7 Tage")]; + + public static readonly IReadOnlyList<(string Value, string Label)> Outcomes = + [("", "Alle"), ("aufgegeben", "Aufgegeben"), ("zeitlimit", "Zeitlimit"), ("abgelehnt", "Abgelehnt")]; + + public bool IsEmpty => this with { Limit = RecentFilter.DefaultLimit } == new DashboardFilter(); + + public static DashboardFilter Parse( + string? zeit, + string? ausgang, + string? land, + string? provider, + string? ip, + string? ziel, + string? q, + string? limit) + { + var parsedLimit = int.TryParse(limit, NumberStyles.None, CultureInfo.InvariantCulture, out var value) + ? Math.Clamp(value, 1, RecentFilter.MaxLimit) + : RecentFilter.DefaultLimit; + + return new DashboardFilter( + Known(Periods, zeit), + Known(Outcomes, ausgang), + Clean(land) is { Length: 2 } country && country.All(char.IsAsciiLetter) ? country.ToUpperInvariant() : null, + Asn(provider) is { } asn ? $"AS{asn.ToString(CultureInfo.InvariantCulture)}" : null, + IPAddress.TryParse(Clean(ip), out var address) ? address.ToString() : null, + Clean(ziel), + Clean(q), + parsedLimit); + } + + public RecentFilter ToRecentFilter() => new( + Zeit switch + { + "24h" => TimeSpan.FromHours(24), + "7d" => TimeSpan.FromDays(7), + _ => null + }, + Ausgang switch + { + "aufgegeben" => TrapOutcome.ClientAborted, + "zeitlimit" => TrapOutcome.Timeout, + "abgelehnt" => TrapOutcome.Rejected, + _ => null + }, + Land, + Asn(Provider), + Ip, + Ziel, + Q, + Limit); + + public int NextLimit => Math.Min(Limit * 2, RecentFilter.MaxLimit); + + public string Href(string anchor = Anchor) + { + var parts = new List(); + Add(parts, "zeit", Zeit); + Add(parts, "ausgang", Ausgang); + Add(parts, "land", Land); + Add(parts, "provider", Provider); + Add(parts, "ip", Ip); + Add(parts, "ziel", Ziel); + Add(parts, "q", Q); + if (Limit != RecentFilter.DefaultLimit) + { + Add(parts, "limit", Limit.ToString(CultureInfo.InvariantCulture)); + } + + return parts.Count == 0 ? $"/#{anchor}" : $"/?{string.Join("&", parts)}#{anchor}"; + } + + private static void Add(List parts, string name, string? value) + { + if (!string.IsNullOrEmpty(value)) + { + parts.Add($"{name}={Uri.EscapeDataString(value)}"); + } + } + + private static string? Known(IReadOnlyList<(string Value, string Label)> options, string? value) + { + var clean = Clean(value)?.ToLowerInvariant(); + return clean is not null && options.Any(o => o.Value == clean) ? clean : null; + } + + private static long? Asn(string? value) + { + var clean = Clean(value); + if (clean is null) + { + return null; + } + + var digits = clean.StartsWith("AS", StringComparison.OrdinalIgnoreCase) ? clean[2..] : clean; + return long.TryParse(digits, NumberStyles.None, CultureInfo.InvariantCulture, out var asn) ? asn : null; + } + + private static string? Clean(string? value) => string.IsNullOrWhiteSpace(value) ? null : value.Trim(); +} diff --git a/src/Flypaper.Web/Components/Pages/Dashboard/DashboardPage.razor b/src/Flypaper.Web/Components/Pages/Dashboard/DashboardPage.razor index cd815e7..9ddaa92 100644 --- a/src/Flypaper.Web/Components/Pages/Dashboard/DashboardPage.razor +++ b/src/Flypaper.Web/Components/Pages/Dashboard/DashboardPage.razor @@ -67,7 +67,10 @@
-

Top 10

+
+

Top 10

+ Klick filtert die Fänge +
@foreach (var tab in tabs) { @@ -78,73 +81,148 @@ @foreach (var tab in tabs) { }
- @if (data.TotalCatches > 0) + @if (data.TotalCatches > 0 || data.Rejected > 0) { -
+ var recent = _recent!; +
-

Letzte 50 Fänge

- Zeile anklicken zum Aufklappen +

Fänge · @Formatting.Number(recent.Total) Treffer

+ Filter gelten nur für diese Liste
-
- - - - - - - - - - - - - - - - @foreach (var trapEvent in data.Recent) + + - - - - - - - - - - + } - -
ZeitIPHerkunftProviderZielUser-AgentDauerBytesAusgang
-
+ + + + + + @foreach (var (name, value) in new[] { ("provider", _filter.Provider), ("ip", _filter.Ip), ("ziel", _filter.Ziel) }) + { + if (value is not null) + { + + } + } + + + @if (!_filter.IsEmpty) + { +
+ @foreach (var (label, without) in Chips()) + { + @label + } + Alle Filter zurücksetzen +
+ } + @if (recent.Items.Count == 0) + { +

Keine Fänge für diese Filter. Filter zurücksetzen

+ } + else + { +
+ + + + + + + + + + + + + + + + @foreach (var (trapEvent, index) in recent.Items.Select((trapEvent, index) => (trapEvent, index))) + { + var started = trapEvent.StartedAt.ToLocalTime(); + var provider = Formatting.Provider(trapEvent.Asn, trapEvent.Provider); + var target = Formatting.Target(trapEvent.Target); + var duration = Formatting.Duration(TimeSpan.FromMilliseconds(trapEvent.DurationMs)); + var bytes = Formatting.Number(trapEvent.BytesSent); + + + + + + + + + + + + } + +
ZeitIPHerkunftProviderZielUser-AgentDauerBytesAusgang
+
+ @if (recent.Total > recent.Items.Count) + { +
+ @Formatting.Number(recent.Items.Count) von @Formatting.Number(recent.Total) + @if (_filter.Limit < RecentFilter.MaxLimit) + { + Weitere laden + } + else + { + · Für ältere Fänge die Filter eingrenzen + } +
+ } + }
} } @@ -153,26 +231,91 @@ @code { private DashboardData? _data; + private RecentCatches? _recent; + private DashboardFilter _filter = new(); private DateTime _loadedAt; + [SupplyParameterFromQuery(Name = "zeit")] public string? Zeit { get; set; } + + [SupplyParameterFromQuery(Name = "ausgang")] public string? Ausgang { get; set; } + + [SupplyParameterFromQuery(Name = "land")] public string? Land { get; set; } + + [SupplyParameterFromQuery(Name = "provider")] public string? Provider { get; set; } + + [SupplyParameterFromQuery(Name = "ip")] public string? Ip { get; set; } + + [SupplyParameterFromQuery(Name = "ziel")] public string? Ziel { get; set; } + + [SupplyParameterFromQuery(Name = "q")] public string? Q { get; set; } + + [SupplyParameterFromQuery(Name = "limit")] public string? Limit { get; set; } + protected override async Task OnInitializedAsync() { + _filter = DashboardFilter.Parse(Zeit, Ausgang, Land, Provider, Ip, Ziel, Q, Limit); _data = await Queries.GetAsync(); + _recent = await Queries.GetRecentAsync(_filter.ToRecentFilter()); _loadedAt = DateTime.Now; } private static IReadOnlyList TopTabs(DashboardData data) => [ - new("countries", "Länder", "Land", data.TopCountries, ShowFlags: true, LabelFormatter: CountryNames.Display), - new("providers", "Provider", "Provider", data.TopProviders), - new("ips", "IPs", "IP", data.TopIps), - new("targets", "Ziele", "Ziel", data.TopTargets, KeyFormatter: Formatting.Target) + new("countries", "Länder", "Land", data.TopCountries, f => f.Land, (f, key) => f with { Land = key }, ShowFlags: true, LabelFormatter: CountryNames.Display), + new("providers", "Provider", "Provider", data.TopProviders, f => f.Provider, (f, key) => f with { Provider = key }), + new("ips", "IPs", "IP", data.TopIps, f => f.Ip, (f, key) => f with { Ip = key }), + new("targets", "Ziele", "Ziel", data.TopTargets, f => f.Ziel, (f, key) => f with { Ziel = key }, KeyFormatter: Formatting.Target) ]; + private DashboardFilter TopFilter(TopTab tab, TopEntry entry) => + tab.Set(_filter with { Limit = RecentFilter.DefaultLimit }, tab.Current(_filter) == entry.Key ? null : entry.Key); + + private IEnumerable<(string Label, DashboardFilter Without)> Chips() + { + var reset = _filter with { Limit = RecentFilter.DefaultLimit }; + if (_filter.Zeit is { } zeit) + { + yield return ($"Zeitraum: {DashboardFilter.Periods.First(p => p.Value == zeit).Label}", reset with { Zeit = null }); + } + + if (_filter.Ausgang is { } ausgang) + { + yield return ($"Ausgang: {DashboardFilter.Outcomes.First(o => o.Value == ausgang).Label}", reset with { Ausgang = null }); + } + + if (_filter.Land is { } land) + { + var name = _recent?.Countries.FirstOrDefault(c => c.Code == land)?.Name; + yield return ($"Land: {CountryNames.Display(land, name)}", reset with { Land = null }); + } + + if (_filter.Provider is { } provider) + { + var name = _data?.TopProviders.FirstOrDefault(p => p.Key == provider)?.Label + ?? _recent?.Items.FirstOrDefault()?.Provider; + yield return ($"Provider: {(name is null ? provider : $"{name} ({provider})")}", reset with { Provider = null }); + } + + if (_filter.Ip is { } ip) + { + yield return ($"IP: {ip}", reset with { Ip = null }); + } + + if (_filter.Ziel is { } ziel) + { + yield return ($"Ziel: {Formatting.Target(ziel)}", reset with { Ziel = null }); + } + + if (_filter.Q is { } q) + { + yield return ($"Suche: „{q}“", reset with { Q = null }); + } + } + private static string OutcomeLabel(TrapOutcome outcome) => outcome switch { TrapOutcome.Timeout => "Zeitlimit", - TrapOutcome.ClientAborted => "Abgebrochen", + TrapOutcome.ClientAborted => "Aufgegeben", TrapOutcome.Rejected => "Abgelehnt", TrapOutcome.Completed => "Beendet", _ => outcome.ToString() @@ -186,6 +329,8 @@ string Label, string KeyLabel, IReadOnlyList Entries, + Func Current, + Func Set, bool ShowFlags = false, Func? KeyFormatter = null, Func? LabelFormatter = null); diff --git a/src/Flypaper.Web/Components/Pages/Dashboard/TopTable.razor b/src/Flypaper.Web/Components/Pages/Dashboard/TopTable.razor index f344f9c..ec12ee3 100644 --- a/src/Flypaper.Web/Components/Pages/Dashboard/TopTable.razor +++ b/src/Flypaper.Web/Components/Pages/Dashboard/TopTable.razor @@ -28,21 +28,25 @@ else var key = KeyFormatter?.Invoke(entry.Key) ?? entry.Key; var label = LabelFormatter is null ? entry.Label : LabelFormatter(entry.Key, entry.Label); var share = (entry.Count * 100.0 / Entries[0].Count).ToString("0.#", CultureInfo.InvariantCulture); - - - @if (ShowFlags) - { - @Formatting.Flag(entry.Key) - } - @if (label is not null) - { - @label - @key - } - else - { - @key - } + var active = IsActive(entry); + var title = label is null ? key : $"{label} · {key}"; + + + + @if (ShowFlags) + { + @Formatting.Flag(entry.Key) + } + @if (label is not null) + { + @label + @key + } + else + { + @key + } + @Formatting.Number(entry.Count) @@ -63,4 +67,8 @@ else [Parameter] public Func? KeyFormatter { get; set; } [Parameter] public Func? LabelFormatter { get; set; } + + [Parameter, EditorRequired] public required Func Href { get; set; } + + [Parameter, EditorRequired] public required Func IsActive { get; set; } } diff --git a/src/Flypaper.Web/wwwroot/app.css b/src/Flypaper.Web/wwwroot/app.css index 022e4fa..c6aa1e4 100644 --- a/src/Flypaper.Web/wwwroot/app.css +++ b/src/Flypaper.Web/wwwroot/app.css @@ -266,6 +266,143 @@ code { font-size: 12px; } +.top-table tr[data-href] { + cursor: pointer; +} + +.top-table tr[data-href]:hover td { + background-color: color-mix(in srgb, var(--text) 4%, transparent); +} + +.top-table tr.active td { + background-color: color-mix(in srgb, var(--accent) 12%, transparent); +} + +.top-table tr.active td:first-child { + box-shadow: inset 3px 0 0 var(--accent); +} + +.top-table td a { + color: inherit; + text-decoration: none; +} + +.top-table td a:focus-visible { + outline: 2px solid var(--accent); + outline-offset: 2px; + border-radius: 3px; +} + +.recent-card { + scroll-margin-top: 16px; +} + +.recent-card h2 .count { + color: var(--muted); + font-weight: 500; +} + +.recent-table tr[id] { + scroll-margin-top: 80px; +} + +.filters { + display: grid; + grid-template-columns: minmax(110px, 140px) minmax(120px, 150px) minmax(160px, 230px) minmax(180px, 1fr) auto; + gap: 10px; + align-items: end; + margin-bottom: 12px; +} + +.filters label { + display: flex; + flex-direction: column; + gap: 4px; + min-width: 0; + color: var(--muted); + font-size: 12px; + font-weight: 500; +} + +.filters button { + border: 1px solid var(--border); + background: var(--surface); + color: var(--text); + font-weight: 500; +} + +.filters button:hover { + border-color: var(--accent); +} + +.filters select, +.filters input { + padding: 7px 10px; + font-size: 13px; +} + +.chips { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 6px 8px; + margin-bottom: 12px; +} + +.chip { + display: inline-flex; + align-items: center; + gap: 6px; + max-width: 100%; + padding: 3px 6px 3px 10px; + overflow: hidden; + border: 1px solid color-mix(in srgb, var(--accent) 45%, var(--border)); + border-radius: 999px; + background: color-mix(in srgb, var(--accent) 10%, transparent); + color: var(--text); + font-size: 12.5px; + text-decoration: none; + white-space: nowrap; + text-overflow: ellipsis; +} + +.chip span { + color: var(--muted); + font-size: 11px; +} + +.chip:hover span { + color: var(--text); +} + +.chip-reset { + color: var(--muted); + font-size: 12.5px; +} + +.more { + display: flex; + flex-wrap: wrap; + align-items: center; + justify-content: center; + gap: 12px; + padding-top: 14px; +} + +a.button { + display: inline-block; + padding: 7px 14px; + border: 1px solid var(--border); + border-radius: 6px; + color: var(--text); + font-weight: 500; + text-decoration: none; +} + +a.button:hover { + border-color: var(--accent); +} + .share-bar { display: block; height: 6px; @@ -823,6 +960,14 @@ button.danger { .origin { grid-template-columns: minmax(0, 1fr); } + + .filters { + grid-template-columns: repeat(3, minmax(0, 1fr)); + } + + .filter-search { + grid-column: 1 / 3; + } } @media (max-width: 599px) { @@ -843,6 +988,15 @@ button.danger { font-size: 24px; } + .filters { + grid-template-columns: repeat(2, minmax(0, 1fr)); + } + + .filter-search, + .filters button { + grid-column: 1 / -1; + } + .top-table .share, .top-table th:nth-child(2), .top-table td:nth-child(2), diff --git a/src/Flypaper.Web/wwwroot/dashboard.js b/src/Flypaper.Web/wwwroot/dashboard.js index 652d34e..816a9ff 100644 --- a/src/Flypaper.Web/wwwroot/dashboard.js +++ b/src/Flypaper.Web/wwwroot/dashboard.js @@ -108,3 +108,29 @@ }); } })(); + +(() => { + const form = document.querySelector("form.filters"); + if (form) { + form.addEventListener("submit", () => { + for (const field of form.elements) { + if (field.name && field.value === "") { + field.disabled = true; + } + } + }); + + for (const select of form.querySelectorAll("select[data-autosubmit]")) { + select.addEventListener("change", () => form.requestSubmit()); + } + } + + for (const row of document.querySelectorAll("tr[data-href]")) { + row.addEventListener("click", event => { + if (event.target.closest("a") || !window.getSelection()?.isCollapsed) { + return; + } + window.location.href = row.dataset.href; + }); + } +})(); diff --git a/test/Flypaper.Tests/Storage/RecentCatchesTests.cs b/test/Flypaper.Tests/Storage/RecentCatchesTests.cs new file mode 100644 index 0000000..5986e66 --- /dev/null +++ b/test/Flypaper.Tests/Storage/RecentCatchesTests.cs @@ -0,0 +1,79 @@ +using Flypaper.Core.Models; +using Flypaper.Storage.Dashboard; +using Flypaper.Tests.Fakes; +using Flypaper.Tests.Mcp; +using Shouldly; + +namespace Flypaper.Tests.Storage; + +public sealed class RecentCatchesTests : IDisposable +{ + private readonly McpTestData _data = new(); + private readonly DashboardQueries _queries; + + public RecentCatchesTests() => _queries = new DashboardQueries(_data.Factory, new FixedTimeProvider(McpTestData.Now)); + + [Fact] + public async Task Without_filters_returns_all_events_newest_first() + { + var recent = await _queries.GetRecentAsync(new RecentFilter()); + + recent.Total.ShouldBe(6); + recent.Items.Select(e => e.StartedAt).ShouldBeInOrder(SortDirection.Descending); + recent.Countries.Select(c => c.Code).ShouldBe(["CN", "TW", "US"], ignoreOrder: true); + } + + [Fact] + public async Task Combines_filters() + { + var recent = await _queries.GetRecentAsync(new RecentFilter(Window: TimeSpan.FromHours(24), CountryCode: "TW", Outcome: TrapOutcome.Rejected)); + + recent.Total.ShouldBe(1); + recent.Items.ShouldHaveSingleItem().RemoteIp.ShouldBe("198.51.100.7"); + } + + [Theory] + [InlineData(4134L, null, null, 2)] + [InlineData(null, "203.0.113.9", null, 2)] + [InlineData(null, null, "GET /.env", 2)] + [InlineData(4134L, null, "GET /.env", 1)] + public async Task Matches_provider_ip_and_target_exactly(long? asn, string? ip, string? target, int expected) + { + var recent = await _queries.GetRecentAsync(new RecentFilter(Asn: asn, Ip: ip, Target: target)); + + recent.Total.ShouldBe(expected); + } + + [Theory] + [InlineData("chinanet", 2)] + [InlineData("CURL", 2)] + [InlineData("198.51", 2)] + [InlineData("wp-login", 1)] + [InlineData("100%", 0)] + public async Task Search_is_case_insensitive_over_ip_provider_target_and_user_agent(string search, int expected) + { + var recent = await _queries.GetRecentAsync(new RecentFilter(Search: search)); + + recent.Total.ShouldBe(expected); + } + + [Fact] + public async Task Returns_an_empty_result_when_nothing_matches() + { + var recent = await _queries.GetRecentAsync(new RecentFilter(CountryCode: "US", Outcome: TrapOutcome.Rejected)); + + recent.Total.ShouldBe(0); + recent.Items.ShouldBeEmpty(); + } + + [Fact] + public async Task Limits_the_items_but_counts_all_matches() + { + var recent = await _queries.GetRecentAsync(new RecentFilter(Limit: 2)); + + recent.Items.Count.ShouldBe(2); + recent.Total.ShouldBe(6); + } + + public void Dispose() => _data.Dispose(); +} diff --git a/test/Flypaper.Tests/Web/DashboardFilterTests.cs b/test/Flypaper.Tests/Web/DashboardFilterTests.cs new file mode 100644 index 0000000..b9ce22e --- /dev/null +++ b/test/Flypaper.Tests/Web/DashboardFilterTests.cs @@ -0,0 +1,67 @@ +using Flypaper.Core.Models; +using Flypaper.Storage.Dashboard; +using Flypaper.Web.Components.Pages.Dashboard; +using Shouldly; + +namespace Flypaper.Tests.Web; + +public sealed class DashboardFilterTests +{ + [Fact] + public void Parses_all_parameters() + { + var filter = DashboardFilter.Parse("24h", "Abgelehnt", "hk", "as4134", " 203.0.113.9 ", "GET /.env", " wp ", "100"); + + filter.ShouldBe(new DashboardFilter("24h", "abgelehnt", "HK", "AS4134", "203.0.113.9", "GET /.env", "wp", 100)); + filter.ToRecentFilter().ShouldBe(new RecentFilter(TimeSpan.FromHours(24), TrapOutcome.Rejected, "HK", 4134, "203.0.113.9", "GET /.env", "wp", 100)); + } + + [Theory] + [InlineData("aufgegeben", TrapOutcome.ClientAborted)] + [InlineData("zeitlimit", TrapOutcome.Timeout)] + [InlineData("abgelehnt", TrapOutcome.Rejected)] + public void Maps_outcomes(string value, TrapOutcome expected) => + DashboardFilter.Parse(null, value, null, null, null, null, null, null).ToRecentFilter().Outcome.ShouldBe(expected); + + [Fact] + public void Ignores_invalid_values() + { + var filter = DashboardFilter.Parse("gestern", "kaputt", "Hongkong", "Chinanet", "not-an-ip", " ", "", "viele"); + + filter.ShouldBe(new DashboardFilter()); + filter.IsEmpty.ShouldBeTrue(); + filter.ToRecentFilter().ShouldBe(new RecentFilter()); + } + + [Theory] + [InlineData("0", 1)] + [InlineData("100000", RecentFilter.MaxLimit)] + [InlineData(null, RecentFilter.DefaultLimit)] + public void Clamps_the_limit(string? limit, int expected) => + DashboardFilter.Parse(null, null, null, null, null, null, null, limit).Limit.ShouldBe(expected); + + [Fact] + public void Builds_links_without_defaults_and_with_escaping() + { + new DashboardFilter().Href().ShouldBe("/#faenge"); + new DashboardFilter(Land: "CN", Ziel: "GET example.com/a&b", Limit: 100).Href("f50") + .ShouldBe("/?land=CN&ziel=GET%20example.com%2Fa%26b&limit=100#f50"); + } + + [Fact] + public void Links_round_trip() + { + var filter = new DashboardFilter("7d", "zeitlimit", "TW", "AS3462", "2001:db8::1", "POST /xmlrpc.php", "curl", 200); + var query = Microsoft.AspNetCore.WebUtilities.QueryHelpers.ParseQuery(new Uri("http://x" + filter.Href()).Query); + + DashboardFilter.Parse(query["zeit"], query["ausgang"], query["land"], query["provider"], query["ip"], query["ziel"], query["q"], query["limit"]) + .ShouldBe(filter); + } + + [Fact] + public void Doubles_the_limit_up_to_the_maximum() + { + new DashboardFilter().NextLimit.ShouldBe(100); + new DashboardFilter(Limit: 400).NextLimit.ShouldBe(RecentFilter.MaxLimit); + } +}