Add IP origin enrichment with DB-IP and world map
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
536aee1f31
commit
3671019e60
47 files changed
+1389
-12
No files matched your search
@@ -7,8 +7,10 @@
|
||||
<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.Http" 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="MaxMind.GeoIP2" Version="6.1.0" />
|
||||
<PackageVersion Include="Microsoft.EntityFrameworkCore.Design" Version="10.0.15" />
|
||||
<PackageVersion Include="Microsoft.EntityFrameworkCore.Sqlite" Version="10.0.15" />
|
||||
</ItemGroup>
|
||||
|
||||
+3
-1
@@ -3,6 +3,7 @@ WORKDIR /src
|
||||
|
||||
COPY Directory.Build.props Directory.Packages.props ./
|
||||
COPY src/Flypaper.Core/Flypaper.Core.csproj src/Flypaper.Core/
|
||||
COPY src/Flypaper.GeoIp/Flypaper.GeoIp.csproj src/Flypaper.GeoIp/
|
||||
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/
|
||||
@@ -18,7 +19,8 @@ RUN mkdir /data && chown $APP_UID /data
|
||||
|
||||
ENV ASPNETCORE_HTTP_PORTS=8080 \
|
||||
ConnectionStrings__Flypaper="Data Source=/data/flypaper.db" \
|
||||
Flypaper__DataProtection__KeysPath=/data/keys
|
||||
Flypaper__DataProtection__KeysPath=/data/keys \
|
||||
Flypaper__GeoIp__Directory=/data/geoip
|
||||
|
||||
COPY --from=build /app .
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
<Solution>
|
||||
<Folder Name="/src/">
|
||||
<Project Path="src/Flypaper.Core/Flypaper.Core.csproj" />
|
||||
<Project Path="src/Flypaper.GeoIp/Flypaper.GeoIp.csproj" />
|
||||
<Project Path="src/Flypaper.Http/Flypaper.Http.csproj" />
|
||||
<Project Path="src/Flypaper.Storage/Flypaper.Storage.csproj" />
|
||||
<Project Path="src/Flypaper.Web/Flypaper.Web.csproj" />
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
using System.Net;
|
||||
using Flypaper.Core.Models;
|
||||
|
||||
namespace Flypaper.Core.Abstractions;
|
||||
|
||||
public interface IIpEnricher
|
||||
{
|
||||
bool IsAvailable { get; }
|
||||
|
||||
event EventHandler? Updated;
|
||||
|
||||
IpOrigin? Lookup(IPAddress address);
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
using Flypaper.Core.Abstractions;
|
||||
using Flypaper.Core.Networking;
|
||||
using Flypaper.Core.Runtime;
|
||||
using Flypaper.Core.Strategies;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
@@ -18,6 +19,7 @@ public static class FlypaperCoreExtensions
|
||||
services.TryAddSingleton<IConnectionGovernor, ConnectionGovernor>();
|
||||
services.TryAddEnumerable(ServiceDescriptor.Singleton<ITarpitStrategy, DripStrategy>());
|
||||
services.TryAddSingleton<TrapRunner>();
|
||||
services.TryAddSingleton<IIpEnricher, NullIpEnricher>();
|
||||
|
||||
return services;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
namespace Flypaper.Core.Models;
|
||||
|
||||
public sealed record IpOrigin(string? CountryCode, string? Country, string? City, long? Asn, string? Provider);
|
||||
@@ -0,0 +1,18 @@
|
||||
using System.Net;
|
||||
using Flypaper.Core.Abstractions;
|
||||
using Flypaper.Core.Models;
|
||||
|
||||
namespace Flypaper.Core.Networking;
|
||||
|
||||
internal sealed class NullIpEnricher : IIpEnricher
|
||||
{
|
||||
public bool IsAvailable => false;
|
||||
|
||||
public event EventHandler? Updated
|
||||
{
|
||||
add { }
|
||||
remove { }
|
||||
}
|
||||
|
||||
public IpOrigin? Lookup(IPAddress address) => null;
|
||||
}
|
||||
+5
-3
@@ -1,8 +1,8 @@
|
||||
using System.Net;
|
||||
|
||||
namespace Flypaper.Http.Middleware;
|
||||
namespace Flypaper.Core.Networking;
|
||||
|
||||
internal static class PrivateNetworks
|
||||
public static class PrivateNetworks
|
||||
{
|
||||
private static readonly IPNetwork[] Networks =
|
||||
[
|
||||
@@ -10,8 +10,10 @@ internal static class PrivateNetworks
|
||||
IPNetwork.Parse("10.0.0.0/8"),
|
||||
IPNetwork.Parse("172.16.0.0/12"),
|
||||
IPNetwork.Parse("192.168.0.0/16"),
|
||||
IPNetwork.Parse("169.254.0.0/16"),
|
||||
IPNetwork.Parse("::1/128"),
|
||||
IPNetwork.Parse("fc00::/7")
|
||||
IPNetwork.Parse("fc00::/7"),
|
||||
IPNetwork.Parse("fe80::/10")
|
||||
];
|
||||
|
||||
public static bool Contains(IPAddress address)
|
||||
@@ -0,0 +1,66 @@
|
||||
using System.Net;
|
||||
using Flypaper.Core.Abstractions;
|
||||
using Flypaper.Core.Models;
|
||||
using Flypaper.Core.Networking;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace Flypaper.GeoIp;
|
||||
|
||||
public sealed partial class DbIpEnricher : IIpEnricher, IDisposable
|
||||
{
|
||||
private static readonly TimeSpan DisposeDelay = TimeSpan.FromMinutes(1);
|
||||
|
||||
private readonly IGeoIpDatabaseFactory _factory;
|
||||
private readonly ILogger<DbIpEnricher> _logger;
|
||||
private IGeoIpDatabase? _database;
|
||||
|
||||
public DbIpEnricher(IGeoIpDatabaseFactory factory, ILogger<DbIpEnricher> logger)
|
||||
{
|
||||
_factory = factory;
|
||||
_logger = logger;
|
||||
_database = factory.Open();
|
||||
}
|
||||
|
||||
public bool IsAvailable => Volatile.Read(ref _database) is not null;
|
||||
|
||||
public event EventHandler? Updated;
|
||||
|
||||
public IpOrigin? Lookup(IPAddress address)
|
||||
{
|
||||
if (PrivateNetworks.Contains(address) || Volatile.Read(ref _database) is not { } database)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
return database.Find(address.IsIPv4MappedToIPv6 ? address.MapToIPv4() : address);
|
||||
}
|
||||
catch (Exception ex) when (ex is not OutOfMemoryException)
|
||||
{
|
||||
LogLookupFailed(ex, address);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public void Reload()
|
||||
{
|
||||
if (_factory.Open() is not { } next)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var previous = Interlocked.Exchange(ref _database, next);
|
||||
if (previous is not null)
|
||||
{
|
||||
_ = Task.Delay(DisposeDelay).ContinueWith(_ => previous.Dispose(), TaskScheduler.Default);
|
||||
}
|
||||
|
||||
Updated?.Invoke(this, EventArgs.Empty);
|
||||
}
|
||||
|
||||
public void Dispose() => Interlocked.Exchange(ref _database, null)?.Dispose();
|
||||
|
||||
[LoggerMessage(Level = LogLevel.Debug, Message = "GeoIP lookup failed for {Address}")]
|
||||
private partial void LogLookupFailed(Exception exception, IPAddress address);
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
namespace Flypaper.GeoIp;
|
||||
|
||||
internal static class DbIpFiles
|
||||
{
|
||||
public const string City = "city";
|
||||
public const string Asn = "asn";
|
||||
|
||||
public static readonly string[] Kinds = [City, Asn];
|
||||
|
||||
public static string DatabasePath(string directory, string kind) => Path.Combine(directory, $"dbip-{kind}-lite.mmdb");
|
||||
|
||||
public static string VersionPath(string directory, string kind) => DatabasePath(directory, kind) + ".version";
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="MaxMind.GeoIP2" />
|
||||
<PackageReference Include="Microsoft.Extensions.Hosting.Abstractions" />
|
||||
<PackageReference Include="Microsoft.Extensions.Http" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\Flypaper.Core\Flypaper.Core.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<InternalsVisibleTo Include="Flypaper.Tests" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -0,0 +1,28 @@
|
||||
using Flypaper.Core.Abstractions;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.DependencyInjection.Extensions;
|
||||
|
||||
namespace Flypaper.GeoIp;
|
||||
|
||||
public static class FlypaperGeoIpExtensions
|
||||
{
|
||||
public static IServiceCollection AddFlypaperGeoIp(this IServiceCollection services, IConfiguration configuration)
|
||||
{
|
||||
services.Configure<GeoIpOptions>(configuration.GetSection(GeoIpOptions.SectionName));
|
||||
services.AddHttpClient(GeoIpUpdater.HttpClientName, client =>
|
||||
{
|
||||
client.Timeout = TimeSpan.FromMinutes(10);
|
||||
client.DefaultRequestHeaders.UserAgent.ParseAdd("Flypaper");
|
||||
});
|
||||
|
||||
services.TryAddSingleton(TimeProvider.System);
|
||||
services.TryAddSingleton<IGeoIpDatabaseFactory, MaxMindGeoIpDatabaseFactory>();
|
||||
services.TryAddSingleton<DbIpEnricher>();
|
||||
services.RemoveAll<IIpEnricher>();
|
||||
services.AddSingleton<IIpEnricher>(sp => sp.GetRequiredService<DbIpEnricher>());
|
||||
services.AddHostedService<GeoIpUpdater>();
|
||||
|
||||
return services;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
namespace Flypaper.GeoIp;
|
||||
|
||||
public sealed class GeoIpOptions
|
||||
{
|
||||
public const string SectionName = "Flypaper:GeoIp";
|
||||
|
||||
public string? Directory { get; set; }
|
||||
|
||||
public string BaseUrl { get; set; } = "https://download.db-ip.com/free/";
|
||||
|
||||
public TimeSpan CheckInterval { get; set; } = TimeSpan.FromDays(1);
|
||||
|
||||
public TimeSpan RetryInterval { get; set; } = TimeSpan.FromHours(1);
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
using System.Globalization;
|
||||
using System.IO.Compression;
|
||||
using System.Net;
|
||||
using Microsoft.Extensions.Hosting;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Options;
|
||||
|
||||
namespace Flypaper.GeoIp;
|
||||
|
||||
internal sealed partial class GeoIpUpdater(
|
||||
IHttpClientFactory httpClientFactory,
|
||||
IOptions<GeoIpOptions> options,
|
||||
DbIpEnricher enricher,
|
||||
TimeProvider timeProvider,
|
||||
ILogger<GeoIpUpdater> logger) : BackgroundService
|
||||
{
|
||||
public const string HttpClientName = "Flypaper.GeoIp";
|
||||
|
||||
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
|
||||
{
|
||||
if (options.Value.Directory is not { Length: > 0 })
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
while (true)
|
||||
{
|
||||
var delay = options.Value.CheckInterval;
|
||||
try
|
||||
{
|
||||
if (await UpdateAsync(stoppingToken))
|
||||
{
|
||||
enricher.Reload();
|
||||
}
|
||||
}
|
||||
catch (Exception ex) when (ex is not OperationCanceledException)
|
||||
{
|
||||
LogUpdateFailed(ex);
|
||||
delay = options.Value.RetryInterval;
|
||||
}
|
||||
|
||||
await Task.Delay(delay, timeProvider, stoppingToken);
|
||||
}
|
||||
}
|
||||
|
||||
internal async Task<bool> UpdateAsync(CancellationToken ct)
|
||||
{
|
||||
var directory = options.Value.Directory!;
|
||||
Directory.CreateDirectory(directory);
|
||||
|
||||
var changed = false;
|
||||
foreach (var kind in DbIpFiles.Kinds)
|
||||
{
|
||||
changed |= await UpdateDatabaseAsync(directory, kind, ct);
|
||||
}
|
||||
|
||||
return changed;
|
||||
}
|
||||
|
||||
private async Task<bool> UpdateDatabaseAsync(string directory, string kind, CancellationToken ct)
|
||||
{
|
||||
var target = DbIpFiles.DatabasePath(directory, kind);
|
||||
var versionFile = DbIpFiles.VersionPath(directory, kind);
|
||||
var installed = File.Exists(target) && File.Exists(versionFile)
|
||||
? (await File.ReadAllTextAsync(versionFile, ct)).Trim()
|
||||
: null;
|
||||
|
||||
var now = timeProvider.GetUtcNow();
|
||||
foreach (var month in new[] { now, now.AddMonths(-1) }.Select(m => m.ToString("yyyy-MM", CultureInfo.InvariantCulture)))
|
||||
{
|
||||
if (month == installed)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (await TryDownloadAsync(kind, month, target, ct))
|
||||
{
|
||||
await File.WriteAllTextAsync(versionFile, month, ct);
|
||||
LogDownloaded(kind, month);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
if (installed is null)
|
||||
{
|
||||
throw new InvalidOperationException($"No DB-IP {kind} database available for the current or previous month.");
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private async Task<bool> TryDownloadAsync(string kind, string month, string target, CancellationToken ct)
|
||||
{
|
||||
var url = $"{options.Value.BaseUrl.TrimEnd('/')}/dbip-{kind}-lite-{month}.mmdb.gz";
|
||||
using var client = httpClientFactory.CreateClient(HttpClientName);
|
||||
using var response = await client.GetAsync(url, HttpCompletionOption.ResponseHeadersRead, ct);
|
||||
if (response.StatusCode == HttpStatusCode.NotFound)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
response.EnsureSuccessStatusCode();
|
||||
|
||||
var temporary = target + ".download";
|
||||
await using (var source = await response.Content.ReadAsStreamAsync(ct))
|
||||
await using (var gzip = new GZipStream(source, CompressionMode.Decompress))
|
||||
await using (var file = File.Create(temporary))
|
||||
{
|
||||
await gzip.CopyToAsync(file, ct);
|
||||
}
|
||||
|
||||
File.Move(temporary, target, overwrite: true);
|
||||
return true;
|
||||
}
|
||||
|
||||
[LoggerMessage(Level = LogLevel.Information, Message = "Downloaded DB-IP {Kind} database for {Month}")]
|
||||
private partial void LogDownloaded(string kind, string month);
|
||||
|
||||
[LoggerMessage(Level = LogLevel.Warning, Message = "GeoIP database update failed; trap events stay without origin until the next attempt")]
|
||||
private partial void LogUpdateFailed(Exception exception);
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
using System.Net;
|
||||
using Flypaper.Core.Models;
|
||||
|
||||
namespace Flypaper.GeoIp;
|
||||
|
||||
public interface IGeoIpDatabase : IDisposable
|
||||
{
|
||||
IpOrigin? Find(IPAddress address);
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
namespace Flypaper.GeoIp;
|
||||
|
||||
public interface IGeoIpDatabaseFactory
|
||||
{
|
||||
IGeoIpDatabase? Open();
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
using System.Net;
|
||||
using Flypaper.Core.Models;
|
||||
using MaxMind.GeoIP2;
|
||||
using MaxMind.GeoIP2.Responses;
|
||||
|
||||
namespace Flypaper.GeoIp;
|
||||
|
||||
internal sealed class MaxMindGeoIpDatabase(DatabaseReader? city, DatabaseReader? asn) : IGeoIpDatabase
|
||||
{
|
||||
public IpOrigin? Find(IPAddress address)
|
||||
{
|
||||
CityResponse? cityResponse = null;
|
||||
AsnResponse? asnResponse = null;
|
||||
city?.TryCity(address, out cityResponse);
|
||||
asn?.TryAsn(address, out asnResponse);
|
||||
|
||||
if (cityResponse is null && asnResponse is null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
return new IpOrigin(
|
||||
cityResponse?.Country.IsoCode,
|
||||
cityResponse?.Country.Name,
|
||||
cityResponse?.City.Name,
|
||||
asnResponse?.AutonomousSystemNumber,
|
||||
asnResponse?.AutonomousSystemOrganization);
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
city?.Dispose();
|
||||
asn?.Dispose();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
using MaxMind.Db;
|
||||
using MaxMind.GeoIP2;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Options;
|
||||
|
||||
namespace Flypaper.GeoIp;
|
||||
|
||||
internal sealed partial class MaxMindGeoIpDatabaseFactory(
|
||||
IOptions<GeoIpOptions> options,
|
||||
ILogger<MaxMindGeoIpDatabaseFactory> logger) : IGeoIpDatabaseFactory
|
||||
{
|
||||
private static readonly string[] Locales = ["de", "en"];
|
||||
|
||||
public IGeoIpDatabase? Open()
|
||||
{
|
||||
if (options.Value.Directory is not { Length: > 0 } directory)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var city = TryOpen(DbIpFiles.DatabasePath(directory, DbIpFiles.City));
|
||||
var asn = TryOpen(DbIpFiles.DatabasePath(directory, DbIpFiles.Asn));
|
||||
return city is null && asn is null ? null : new MaxMindGeoIpDatabase(city, asn);
|
||||
}
|
||||
|
||||
private DatabaseReader? TryOpen(string path)
|
||||
{
|
||||
if (!File.Exists(path))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
return new DatabaseReader(path, Locales, FileAccessMode.MemoryMapped);
|
||||
}
|
||||
catch (Exception ex) when (ex is InvalidDatabaseException or IOException)
|
||||
{
|
||||
LogOpenFailed(ex, path);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
[LoggerMessage(Level = LogLevel.Warning, Message = "Could not open GeoIP database {Path}")]
|
||||
private partial void LogOpenFailed(Exception exception, string path);
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
using System.Net;
|
||||
using Flypaper.Core.Abstractions;
|
||||
using Flypaper.Core.Models;
|
||||
using Flypaper.Core.Networking;
|
||||
using Flypaper.Core.Runtime;
|
||||
using Flypaper.Http.Matching;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
|
||||
@@ -10,6 +10,9 @@ public sealed record DashboardData(
|
||||
TimeSpan TotalHoldTime,
|
||||
IReadOnlyList<TrapEventEntity> Recent,
|
||||
IReadOnlyList<TopEntry> TopIps,
|
||||
IReadOnlyList<TopEntry> TopTargets);
|
||||
IReadOnlyList<TopEntry> TopTargets,
|
||||
IReadOnlyList<TopEntry> TopCountries,
|
||||
IReadOnlyList<TopEntry> TopProviders,
|
||||
IReadOnlyDictionary<string, int> CatchesByCountry);
|
||||
|
||||
public sealed record TopEntry(string Key, int Count, TimeSpan HoldTime);
|
||||
public sealed record TopEntry(string Key, int Count, TimeSpan HoldTime, string? Label = null);
|
||||
@@ -16,6 +16,23 @@ public sealed class DashboardQueries(IDbContextFactory<FlypaperDbContext> dbCont
|
||||
var catches = events.Where(e => e.Outcome != TrapOutcome.Rejected);
|
||||
var since = timeProvider.GetUtcNow().UtcDateTime.AddHours(-24);
|
||||
|
||||
var countries = await catches
|
||||
.Where(e => e.CountryCode != null)
|
||||
.GroupBy(e => e.CountryCode!)
|
||||
.Select(g => new { g.Key, Count = g.Count(), DurationMs = g.Sum(e => e.DurationMs), Name = g.Max(e => e.Country) })
|
||||
.OrderByDescending(x => x.Count)
|
||||
.ThenByDescending(x => x.DurationMs)
|
||||
.ToListAsync(ct);
|
||||
|
||||
var providers = await catches
|
||||
.Where(e => e.Asn != null)
|
||||
.GroupBy(e => e.Asn!.Value)
|
||||
.Select(g => new { g.Key, Count = g.Count(), DurationMs = g.Sum(e => e.DurationMs), Name = g.Max(e => e.Provider) })
|
||||
.OrderByDescending(x => x.Count)
|
||||
.ThenByDescending(x => x.DurationMs)
|
||||
.Take(TopCount)
|
||||
.ToListAsync(ct);
|
||||
|
||||
return new DashboardData(
|
||||
await catches.CountAsync(ct),
|
||||
await catches.CountAsync(e => e.StartedAt >= since, ct),
|
||||
@@ -24,7 +41,15 @@ public sealed class DashboardQueries(IDbContextFactory<FlypaperDbContext> dbCont
|
||||
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));
|
||||
await TopAsync(catches.Where(e => e.Target != null).GroupBy(e => e.Target!), ct),
|
||||
countries
|
||||
.Take(TopCount)
|
||||
.Select(x => new TopEntry(x.Key, x.Count, TimeSpan.FromMilliseconds(x.DurationMs), x.Name))
|
||||
.ToList(),
|
||||
providers
|
||||
.Select(x => new TopEntry($"AS{x.Key}", x.Count, TimeSpan.FromMilliseconds(x.DurationMs), x.Name))
|
||||
.ToList(),
|
||||
countries.ToDictionary(x => x.Key, x => x.Count, StringComparer.OrdinalIgnoreCase));
|
||||
}
|
||||
|
||||
private static async Task<IReadOnlyList<TopEntry>> TopAsync(
|
||||
|
||||
@@ -28,6 +28,16 @@ public sealed class TrapEventEntity
|
||||
|
||||
public string? ClientInfo { get; set; }
|
||||
|
||||
public string? CountryCode { get; set; }
|
||||
|
||||
public string? Country { get; set; }
|
||||
|
||||
public string? City { get; set; }
|
||||
|
||||
public long? Asn { get; set; }
|
||||
|
||||
public string? Provider { get; set; }
|
||||
|
||||
public static TrapEventEntity From(TrapEvent trapEvent) => new()
|
||||
{
|
||||
SessionId = trapEvent.SessionId,
|
||||
@@ -43,6 +53,15 @@ public sealed class TrapEventEntity
|
||||
ClientInfo = Truncate(trapEvent.ClientInfo, FlypaperDbContext.MaxTextLength)
|
||||
};
|
||||
|
||||
public void ApplyOrigin(IpOrigin? origin)
|
||||
{
|
||||
CountryCode = origin?.CountryCode;
|
||||
Country = Truncate(origin?.Country, FlypaperDbContext.MaxNameLength);
|
||||
City = Truncate(origin?.City, FlypaperDbContext.MaxNameLength);
|
||||
Asn = origin?.Asn;
|
||||
Provider = Truncate(origin?.Provider, FlypaperDbContext.MaxNameLength);
|
||||
}
|
||||
|
||||
private static string? Truncate(string? value, int maxLength) =>
|
||||
value?.Length > maxLength ? value[..maxLength] : value;
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
using System.Net;
|
||||
using Flypaper.Core.Abstractions;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Hosting;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace Flypaper.Storage.Events;
|
||||
|
||||
internal sealed partial class OriginBackfill : BackgroundService
|
||||
{
|
||||
private const int BatchSize = 500;
|
||||
|
||||
private readonly IDbContextFactory<FlypaperDbContext> _dbContextFactory;
|
||||
private readonly IIpEnricher _enricher;
|
||||
private readonly ILogger<OriginBackfill> _logger;
|
||||
private readonly SemaphoreSlim _pending = new(1, 1);
|
||||
|
||||
public OriginBackfill(
|
||||
IDbContextFactory<FlypaperDbContext> dbContextFactory,
|
||||
IIpEnricher enricher,
|
||||
ILogger<OriginBackfill> logger)
|
||||
{
|
||||
_dbContextFactory = dbContextFactory;
|
||||
_enricher = enricher;
|
||||
_logger = logger;
|
||||
_enricher.Updated += OnEnricherUpdated;
|
||||
}
|
||||
|
||||
public override void Dispose()
|
||||
{
|
||||
_enricher.Updated -= OnEnricherUpdated;
|
||||
_pending.Dispose();
|
||||
base.Dispose();
|
||||
}
|
||||
|
||||
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
|
||||
{
|
||||
while (true)
|
||||
{
|
||||
await _pending.WaitAsync(stoppingToken);
|
||||
if (!_enricher.IsAvailable)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
var updated = await BackfillAsync(stoppingToken);
|
||||
if (updated > 0)
|
||||
{
|
||||
LogBackfilled(updated);
|
||||
}
|
||||
}
|
||||
catch (Exception ex) when (ex is not OperationCanceledException)
|
||||
{
|
||||
LogBackfillFailed(ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
internal async Task<int> BackfillAsync(CancellationToken ct)
|
||||
{
|
||||
var updated = 0;
|
||||
var lastId = 0L;
|
||||
|
||||
while (true)
|
||||
{
|
||||
await using var db = await _dbContextFactory.CreateDbContextAsync(ct);
|
||||
var batch = await db.TrapEvents
|
||||
.Where(e => e.Id > lastId && e.CountryCode == null && e.Asn == null)
|
||||
.OrderBy(e => e.Id)
|
||||
.Take(BatchSize)
|
||||
.ToListAsync(ct);
|
||||
|
||||
if (batch.Count == 0)
|
||||
{
|
||||
return updated;
|
||||
}
|
||||
|
||||
foreach (var trapEvent in batch)
|
||||
{
|
||||
if (IPAddress.TryParse(trapEvent.RemoteIp, out var address) && _enricher.Lookup(address) is { } origin)
|
||||
{
|
||||
trapEvent.ApplyOrigin(origin);
|
||||
updated++;
|
||||
}
|
||||
}
|
||||
|
||||
await db.SaveChangesAsync(ct);
|
||||
lastId = batch[^1].Id;
|
||||
}
|
||||
}
|
||||
|
||||
private void OnEnricherUpdated(object? sender, EventArgs e)
|
||||
{
|
||||
if (_pending.CurrentCount == 0)
|
||||
{
|
||||
try
|
||||
{
|
||||
_pending.Release();
|
||||
}
|
||||
catch (SemaphoreFullException)
|
||||
{
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[LoggerMessage(Level = LogLevel.Information, Message = "Added origin to {Count} stored trap events")]
|
||||
private partial void LogBackfilled(int count);
|
||||
|
||||
[LoggerMessage(Level = LogLevel.Warning, Message = "Origin backfill failed")]
|
||||
private partial void LogBackfillFailed(Exception exception);
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
using Flypaper.Core.Abstractions;
|
||||
using Flypaper.Core.Models;
|
||||
using Flypaper.Storage.Entities;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
@@ -9,6 +10,7 @@ namespace Flypaper.Storage.Events;
|
||||
internal sealed class TrapEventWriter(
|
||||
ChannelTrapEventSink sink,
|
||||
IDbContextFactory<FlypaperDbContext> dbContextFactory,
|
||||
IIpEnricher enricher,
|
||||
ILogger<TrapEventWriter> logger) : BackgroundService
|
||||
{
|
||||
private const int MaxBatchSize = 100;
|
||||
@@ -26,7 +28,7 @@ internal sealed class TrapEventWriter(
|
||||
try
|
||||
{
|
||||
await using var db = await dbContextFactory.CreateDbContextAsync(stoppingToken);
|
||||
db.TrapEvents.AddRange(batch.Select(TrapEventEntity.From));
|
||||
db.TrapEvents.AddRange(batch.Select(ToEntity));
|
||||
await db.SaveChangesAsync(stoppingToken);
|
||||
}
|
||||
catch (Exception ex) when (ex is not OperationCanceledException)
|
||||
@@ -37,4 +39,11 @@ internal sealed class TrapEventWriter(
|
||||
batch.Clear();
|
||||
}
|
||||
}
|
||||
|
||||
private TrapEventEntity ToEntity(TrapEvent trapEvent)
|
||||
{
|
||||
var entity = TrapEventEntity.From(trapEvent);
|
||||
entity.ApplyOrigin(enricher.Lookup(trapEvent.RemoteIp));
|
||||
return entity;
|
||||
}
|
||||
}
|
||||
@@ -11,4 +11,8 @@
|
||||
<ProjectReference Include="..\Flypaper.Core\Flypaper.Core.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<InternalsVisibleTo Include="Flypaper.Tests" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -6,6 +6,7 @@ namespace Flypaper.Storage;
|
||||
public sealed class FlypaperDbContext(DbContextOptions<FlypaperDbContext> options) : DbContext(options)
|
||||
{
|
||||
internal const int MaxTextLength = 2048;
|
||||
internal const int MaxNameLength = 256;
|
||||
|
||||
public DbSet<TrapEventEntity> TrapEvents => Set<TrapEventEntity>();
|
||||
|
||||
@@ -24,7 +25,13 @@ public sealed class FlypaperDbContext(DbContextOptions<FlypaperDbContext> option
|
||||
trapEvent.Property(e => e.Target).HasMaxLength(MaxTextLength);
|
||||
trapEvent.Property(e => e.ClientInfo).HasMaxLength(MaxTextLength);
|
||||
trapEvent.HasIndex(e => e.StartedAt);
|
||||
trapEvent.Property(e => e.CountryCode).HasMaxLength(2);
|
||||
trapEvent.Property(e => e.Country).HasMaxLength(MaxNameLength);
|
||||
trapEvent.Property(e => e.City).HasMaxLength(MaxNameLength);
|
||||
trapEvent.Property(e => e.Provider).HasMaxLength(MaxNameLength);
|
||||
trapEvent.HasIndex(e => e.RemoteIp);
|
||||
trapEvent.HasIndex(e => e.CountryCode);
|
||||
trapEvent.HasIndex(e => e.Asn);
|
||||
|
||||
var setting = modelBuilder.Entity<SettingEntity>();
|
||||
setting.HasKey(e => e.Key);
|
||||
|
||||
@@ -30,6 +30,7 @@ public static class FlypaperStorageExtensions
|
||||
services.AddSingleton<ChannelTrapEventSink>();
|
||||
services.AddSingleton<ITrapEventSink>(sp => sp.GetRequiredService<ChannelTrapEventSink>());
|
||||
services.AddHostedService<TrapEventWriter>();
|
||||
services.AddHostedService<OriginBackfill>();
|
||||
services.AddSingleton<DashboardQueries>();
|
||||
return services;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,121 @@
|
||||
// <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("20261114143917_AddOrigin")]
|
||||
partial class AddOrigin
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void BuildTargetModel(ModelBuilder modelBuilder)
|
||||
{
|
||||
#pragma warning disable 612, 618
|
||||
modelBuilder.HasAnnotation("ProductVersion", "10.0.15");
|
||||
|
||||
modelBuilder.Entity("Flypaper.Storage.Entities.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.Entities.TrapEventEntity", b =>
|
||||
{
|
||||
b.Property<long>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<long?>("Asn")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<long>("BytesSent")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<string>("City")
|
||||
.HasMaxLength(256)
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<string>("ClientInfo")
|
||||
.HasMaxLength(2048)
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<string>("Country")
|
||||
.HasMaxLength(256)
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<string>("CountryCode")
|
||||
.HasMaxLength(2)
|
||||
.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>("Provider")
|
||||
.HasMaxLength(256)
|
||||
.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("Asn");
|
||||
|
||||
b.HasIndex("CountryCode");
|
||||
|
||||
b.HasIndex("RemoteIp");
|
||||
|
||||
b.HasIndex("StartedAt");
|
||||
|
||||
b.ToTable("TrapEvents");
|
||||
});
|
||||
#pragma warning restore 612, 618
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace Flypaper.Storage.Migrations
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public partial class AddOrigin : Migration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void Up(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.AddColumn<long>(
|
||||
name: "Asn",
|
||||
table: "TrapEvents",
|
||||
type: "INTEGER",
|
||||
nullable: true);
|
||||
|
||||
migrationBuilder.AddColumn<string>(
|
||||
name: "City",
|
||||
table: "TrapEvents",
|
||||
type: "TEXT",
|
||||
maxLength: 256,
|
||||
nullable: true);
|
||||
|
||||
migrationBuilder.AddColumn<string>(
|
||||
name: "Country",
|
||||
table: "TrapEvents",
|
||||
type: "TEXT",
|
||||
maxLength: 256,
|
||||
nullable: true);
|
||||
|
||||
migrationBuilder.AddColumn<string>(
|
||||
name: "CountryCode",
|
||||
table: "TrapEvents",
|
||||
type: "TEXT",
|
||||
maxLength: 2,
|
||||
nullable: true);
|
||||
|
||||
migrationBuilder.AddColumn<string>(
|
||||
name: "Provider",
|
||||
table: "TrapEvents",
|
||||
type: "TEXT",
|
||||
maxLength: 256,
|
||||
nullable: true);
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_TrapEvents_Asn",
|
||||
table: "TrapEvents",
|
||||
column: "Asn");
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_TrapEvents_CountryCode",
|
||||
table: "TrapEvents",
|
||||
column: "CountryCode");
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void Down(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.DropIndex(
|
||||
name: "IX_TrapEvents_Asn",
|
||||
table: "TrapEvents");
|
||||
|
||||
migrationBuilder.DropIndex(
|
||||
name: "IX_TrapEvents_CountryCode",
|
||||
table: "TrapEvents");
|
||||
|
||||
migrationBuilder.DropColumn(
|
||||
name: "Asn",
|
||||
table: "TrapEvents");
|
||||
|
||||
migrationBuilder.DropColumn(
|
||||
name: "City",
|
||||
table: "TrapEvents");
|
||||
|
||||
migrationBuilder.DropColumn(
|
||||
name: "Country",
|
||||
table: "TrapEvents");
|
||||
|
||||
migrationBuilder.DropColumn(
|
||||
name: "CountryCode",
|
||||
table: "TrapEvents");
|
||||
|
||||
migrationBuilder.DropColumn(
|
||||
name: "Provider",
|
||||
table: "TrapEvents");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -17,7 +17,7 @@ namespace Flypaper.Storage.Migrations
|
||||
#pragma warning disable 612, 618
|
||||
modelBuilder.HasAnnotation("ProductVersion", "10.0.15");
|
||||
|
||||
modelBuilder.Entity("Flypaper.Storage.SettingEntity", b =>
|
||||
modelBuilder.Entity("Flypaper.Storage.Entities.SettingEntity", b =>
|
||||
{
|
||||
b.Property<string>("Key")
|
||||
.HasMaxLength(128)
|
||||
@@ -32,19 +32,34 @@ namespace Flypaper.Storage.Migrations
|
||||
b.ToTable("Settings");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Flypaper.Storage.TrapEventEntity", b =>
|
||||
modelBuilder.Entity("Flypaper.Storage.Entities.TrapEventEntity", b =>
|
||||
{
|
||||
b.Property<long>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<long?>("Asn")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<long>("BytesSent")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<string>("City")
|
||||
.HasMaxLength(256)
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<string>("ClientInfo")
|
||||
.HasMaxLength(2048)
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<string>("Country")
|
||||
.HasMaxLength(256)
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<string>("CountryCode")
|
||||
.HasMaxLength(2)
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<long>("DurationMs")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
@@ -61,6 +76,10 @@ namespace Flypaper.Storage.Migrations
|
||||
.HasMaxLength(16)
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<string>("Provider")
|
||||
.HasMaxLength(256)
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<string>("RemoteIp")
|
||||
.IsRequired()
|
||||
.HasMaxLength(64)
|
||||
@@ -83,6 +102,10 @@ namespace Flypaper.Storage.Migrations
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("Asn");
|
||||
|
||||
b.HasIndex("CountryCode");
|
||||
|
||||
b.HasIndex("RemoteIp");
|
||||
|
||||
b.HasIndex("StartedAt");
|
||||
|
||||
@@ -10,4 +10,7 @@
|
||||
</form>
|
||||
</nav>
|
||||
@Body
|
||||
<footer class="footer">
|
||||
<a href="https://db-ip.com">IP Geolocation by DB-IP</a> (CC BY 4.0) · Kartendaten: Natural Earth
|
||||
</footer>
|
||||
</main>
|
||||
@@ -1,6 +1,7 @@
|
||||
@page "/"
|
||||
@using Flypaper.Core.Abstractions
|
||||
@using Flypaper.Storage.Dashboard
|
||||
@using Flypaper.Storage.Entities
|
||||
@inject DashboardQueries Queries
|
||||
@inject IConnectionGovernor Governor
|
||||
|
||||
@@ -25,7 +26,11 @@
|
||||
<div class="metric"><span class="label">Abgelehnt</span><span class="value">@data.Rejected.ToString("N0")</span></div>
|
||||
</section>
|
||||
|
||||
<WorldMap CatchesByCountry="data.CatchesByCountry" />
|
||||
|
||||
<section class="tops">
|
||||
<TopTable Title="Top 10 Länder" KeyLabel="Land" Entries="data.TopCountries" ShowFlags="true" />
|
||||
<TopTable Title="Top 10 Provider (ASN)" KeyLabel="Provider" Entries="data.TopProviders" />
|
||||
<TopTable Title="Top 10 IPs" KeyLabel="IP" Entries="data.TopIps" />
|
||||
<TopTable Title="Top 10 Ziele" KeyLabel="Ziel" Entries="data.TopTargets" />
|
||||
</section>
|
||||
@@ -44,6 +49,8 @@
|
||||
<tr>
|
||||
<th>Zeit</th>
|
||||
<th>IP</th>
|
||||
<th>Herkunft</th>
|
||||
<th>Provider</th>
|
||||
<th>Ziel</th>
|
||||
<th>User-Agent</th>
|
||||
<th class="num">Dauer</th>
|
||||
@@ -57,6 +64,18 @@
|
||||
<tr data-expand="event:@trapEvent.Id" tabindex="0" aria-expanded="false">
|
||||
<td class="nowrap">@trapEvent.StartedAt.ToLocalTime().ToString("dd.MM. HH:mm:ss")</td>
|
||||
<td class="mono">@trapEvent.RemoteIp</td>
|
||||
<td class="nowrap" title="@Origin(trapEvent)">
|
||||
@if (trapEvent.CountryCode is { } countryCode)
|
||||
{
|
||||
@($"{Formatting.Flag(countryCode)} {countryCode}")
|
||||
<span class="detail">@Origin(trapEvent)</span>
|
||||
}
|
||||
else
|
||||
{
|
||||
<span class="muted">–</span>
|
||||
}
|
||||
</td>
|
||||
<td class="clip" title="@Formatting.Provider(trapEvent.Asn, trapEvent.Provider)">@Formatting.Provider(trapEvent.Asn, trapEvent.Provider)</td>
|
||||
<td class="mono clip" title="@trapEvent.Target">@trapEvent.Target</td>
|
||||
<td class="clip" title="@trapEvent.ClientInfo">@trapEvent.ClientInfo</td>
|
||||
<td class="num">@Formatting.Duration(TimeSpan.FromMilliseconds(trapEvent.DurationMs))</td>
|
||||
@@ -82,4 +101,7 @@
|
||||
_data = await Queries.GetAsync();
|
||||
_loadedAt = DateTime.Now;
|
||||
}
|
||||
|
||||
private static string Origin(TrapEventEntity trapEvent) =>
|
||||
string.Join(", ", new[] { trapEvent.City, trapEvent.Country }.Where(part => !string.IsNullOrEmpty(part)));
|
||||
}
|
||||
@@ -19,7 +19,7 @@
|
||||
@foreach (var entry in Entries)
|
||||
{
|
||||
<tr data-expand="@($"{KeyLabel}:{entry.Key}")" tabindex="0" aria-expanded="false">
|
||||
<td class="mono clip" title="@entry.Key">@entry.Key</td>
|
||||
<td class="mono clip" title="@Display(entry)">@(ShowFlags ? $"{Formatting.Flag(entry.Key)} " : "")@Display(entry)</td>
|
||||
<td class="num">@entry.Count.ToString("N0")</td>
|
||||
<td class="num">@Formatting.Duration(entry.HoldTime)</td>
|
||||
</tr>
|
||||
@@ -35,4 +35,8 @@
|
||||
[Parameter, EditorRequired] public required string KeyLabel { get; set; }
|
||||
|
||||
[Parameter, EditorRequired] public required IReadOnlyList<TopEntry> Entries { get; set; }
|
||||
|
||||
[Parameter] public bool ShowFlags { get; set; }
|
||||
|
||||
private static string Display(TopEntry entry) => entry.Label is null ? entry.Key : $"{entry.Key} · {entry.Label}";
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
@using System.Globalization
|
||||
|
||||
<section class="card">
|
||||
<h2>Herkunft</h2>
|
||||
<svg class="world-map" viewBox="0 0 @Map.Width.ToString(CultureInfo.InvariantCulture) @Map.Height.ToString(CultureInfo.InvariantCulture)" role="img" aria-label="Weltkarte der Fänge nach Land">
|
||||
@foreach (var country in Map.Countries)
|
||||
{
|
||||
var count = Count(country.Code);
|
||||
<path d="@country.Path" class="@($"level-{Level(count)}")"><title>@country.Name: @count.ToString("N0") @(count == 1 ? "Fang" : "Fänge")</title></path>
|
||||
}
|
||||
</svg>
|
||||
<div class="map-legend">
|
||||
<span>0</span>
|
||||
@for (var level = 0; level <= Levels; level++)
|
||||
{
|
||||
<span class="swatch @($"level-{level}")"></span>
|
||||
}
|
||||
<span>@_max.ToString("N0")</span>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
@code {
|
||||
private const int Levels = 5;
|
||||
private int _max;
|
||||
|
||||
[Parameter, EditorRequired] public required IReadOnlyDictionary<string, int> CatchesByCountry { get; set; }
|
||||
|
||||
private static WorldMapData Map => WorldMapData.Instance;
|
||||
|
||||
protected override void OnParametersSet() => _max = CatchesByCountry.Count == 0 ? 0 : CatchesByCountry.Values.Max();
|
||||
|
||||
private int Count(string? code) => code is not null && CatchesByCountry.TryGetValue(code, out var count) ? count : 0;
|
||||
|
||||
private int Level(int count) =>
|
||||
count == 0 || _max == 0 ? 0 : Math.Max(1, (int)Math.Ceiling(Math.Log(count + 1) / Math.Log(_max + 1) * Levels));
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
using System.Text.Json;
|
||||
|
||||
namespace Flypaper.Web.Components.Pages.Dashboard;
|
||||
|
||||
internal sealed record WorldMapData(double Width, double Height, IReadOnlyList<WorldMapCountry> Countries)
|
||||
{
|
||||
private static readonly JsonSerializerOptions JsonOptions = new(JsonSerializerDefaults.Web);
|
||||
|
||||
public static WorldMapData Instance { get; } = Load();
|
||||
|
||||
private static WorldMapData Load()
|
||||
{
|
||||
using var stream = typeof(WorldMapData).Assembly.GetManifestResourceStream("Flypaper.Web.world-map.json")
|
||||
?? throw new InvalidOperationException("Embedded world map is missing.");
|
||||
return JsonSerializer.Deserialize<WorldMapData>(stream, JsonOptions)
|
||||
?? throw new InvalidOperationException("Embedded world map is empty.");
|
||||
}
|
||||
}
|
||||
|
||||
internal sealed record WorldMapCountry(string? Code, string Name, string Path);
|
||||
@@ -0,0 +1 @@
|
||||
{"width":1000.0,"height":439.1,"countries":[{"code":"AF","name":"Afghanistan","path":"M669.6,108.7L671,108.7L673.1,109.4L674,109.9L675.5,108.8L676.6,109.4L677,107.9L678.5,108L678.7,107.5L678.6,106.1L679.3,104.9L680.9,105.7L681,106.7L681.8,106.9L682.4,109.7L683.8,110.8L684.5,110.1L685.5,109.8L686.6,108.3L688.4,108.5L691.1,108.5L691.8,109.5L690.5,109.9L689.4,110.5L686.6,110.9L684,111.6L683,113.1L684,114.5L684.8,116.2L683.9,117.6L684.4,119L684.1,120.2L681.6,120.1L683.2,122.4L681.8,123.3L681.2,125.4L681.9,127.5L681.1,128.4L680.1,128.1L678.2,128.6L678.1,129.5L676.2,129.5L675.2,131.5L675.8,134.5L672.6,136L670.7,135.7L670.4,136.5L668.7,136L666.1,136.5L661.3,134.7L663,131.5L662.3,129.3L660.2,128.7L659.5,126.5L658,123.7L658.7,121.8L657.4,121.3L657.6,118.8L657.5,114.5L660.5,115.8L662.3,115.4L662.5,113.8L664.4,113.3L665.5,112.3L665.3,109.6L667.2,108.9L667.3,107.7L668.8,108.6L669.6,108.7Z"},{"code":"AL","name":"Albanien","path":"M552.5,97.2L552.5,98L551.7,98.5L551.7,99.6L550.7,101.2L550.2,100.9L550.1,100.2L548.6,99.1L548.2,97.5L548.2,95.3L548.5,94.3L548,93.8L547.8,92.8L548.7,91.2L548.9,91.8L549.5,91.5L550.1,92.4L550.8,92.7L551,93.9L550.8,95L551.3,96.4L552.5,97.2Z"},{"code":"DZ","name":"Algerien","path":"M476.7,143.4L476.8,142.7L476.8,142.5L476.9,138.2L481.3,135.6L483.9,135.1L486.1,134.1L487.2,132.4L490.3,131L490.4,128.4L491.9,128.1L493.1,126.8L496.6,126.2L497.1,124.8L496.4,124.1L495.5,120.4L495.4,118.4L494.4,116.2L496.9,114.3L499.7,113.7L501.3,112.3L503.8,111.3L508.1,110.7L512.3,110.4L513.6,110.9L516,109.6L518.7,109.5L519.8,110.3L521.5,110.1L521.1,111.9L521.6,115.1L521.1,117.9L519.5,119.8L519.8,122.4L522,124.5L522.1,125.3L523.7,126.7L525.1,133L526,136.2L526.2,137.8L525.9,140.7L526.1,142.3L525.8,144.3L526.1,146.6L525.1,148.1L526.8,150.7L526.9,152.2L527.9,154.3L529.2,153.6L531.4,155.3L532.6,157.6L523.5,164.5L515.6,171.8L511.8,173.4L508.7,173.8L508.7,171.4L507.4,170.8L505.7,169.8L505,168L495.8,160L486.7,152.1L476.7,143.4Z"},{"code":"AO","name":"Angola","path":"M536.7,264L535.7,264.8L535.2,265.8L535.1,267.4L534.4,267.8L533.7,265L534.8,263.3L535.7,262.7L536.7,264ZM534.8,269L536,268.5L536.8,268.6L537.8,268.1L546.1,268.1L546.8,271L547.5,273.3L548.2,274.5L549.2,276.5L551.1,276.2L552,275.6L553.6,276.2L554,275.2L554.8,273L556.5,272.9L556.7,272.2L558.1,272.2L557.8,273.6L561.3,273.5L561.3,275.9L561.8,277.4L561.4,279.7L561.5,282L562.4,283.4L562.2,287.9L562.9,287.5L564.1,287.6L565.8,287.1L567.1,287.3L567.4,288.5L567,290.3L567.4,292.1L567,293.5L567.2,294.8L561.3,294.7L560.8,306.7L562.5,309.7L564.3,312L559.1,313.5L552.4,313L550.6,311.2L539.3,311.4L538.9,311.7L537.3,310L535.5,309.9L533.8,310.5L532.5,311.2L532.3,308.9L532.7,305.6L533.8,302.2L533.9,300.6L534.9,297.2L535.6,295.6L537.3,293.2L538.2,291.5L538.5,288.7L538.4,286.6L537.6,285.2L536.9,282.9L536.2,280.6L536.4,279.8L537.3,278.3L536.5,274.7L535.9,272.1L534.5,269.7L534.8,269Z"},{"code":"AR","name":"Argentinien","path":"M343.2,430.7L344.7,432L346.9,434.2L350.6,435.8L354.1,436.5L353.8,437.9L351.7,438.1L350.1,437.1L348.7,437L346.3,437L343.2,430.7ZM347.6,358.1L347.5,361L347.5,364.6L348.3,368L347.9,368.8L348.2,371L348.5,372.8L352.4,375.8L352.6,378.1L354.6,379.6L354.9,381.2L353.5,385.5L350.2,387.3L345.3,388L342.5,387.7L343.6,389.7L343.8,392.1L344.7,393.8L343.6,395L341.2,395.4L338.4,394.2L337.7,395.1L339.1,398.3L341.1,399.3L342.1,398.3L343.4,399.9L341.5,400.9L340.2,402.9L340.9,406.1L341,407.8L338.7,407.8L337.4,409.4L337.6,411.8L340.8,414L343.4,414.6L343.6,417.4L341.5,419.1L341.5,422.6L339.9,423.8L339.5,425.2L341.7,428.2L344,429.9L342.9,429.7L340.6,429.3L334.9,428.9L333.1,427.2L332.1,425L330.6,425.2L329.3,424.1L327.6,421L328.8,419.6L328.7,417.7L327.8,416.2L327.9,413.6L327.1,409.5L326.1,407.6L326.9,407L326.2,405.8L324.8,405.2L325.1,403.9L323.6,402.6L321.6,398.9L322.4,398.3L320.5,394.3L319.9,390.9L319.6,388L320.7,386.8L318.9,383.5L318,380.4L319.2,378.2L318.4,375.4L318.9,372L318,368.8L317.2,368.2L314.4,362.2L315.2,358.6L314.1,355.1L314.3,351.9L315.3,348.6L316.7,346.3L315.7,344.9L316,343.8L314.7,337.7L317.3,336L317.6,332.2L317.1,331.3L318.9,328L322.6,328.8L324.6,331.5L325.2,328.5L328.3,328.7L328.9,329.5L334.8,335.4L337.2,336L340.9,338.7L343.9,340.1L344.6,341.7L342.9,347.1L345.7,348.1L348.8,348.7L350.9,348.1L352.8,345.3L352.8,342.2L354,341.5L355.7,343.6L356.1,346.4L354.1,348.4L352.6,349.9L350.2,353.3L347.6,358.1Z"},{"code":"AM","name":"Armenien","path":"M617.6,104L616.7,104.1L615.2,102.2L615.1,101.7L614,101.7L613.1,100.8L612.6,100.9L611.4,99.9L609.4,99.1L609.3,97.5L608.6,96.3L611.9,95.8L612.6,96.7L613.7,97.3L613.4,98.1L615,99.2L614.5,100.3L615.8,101.2L617,101.7L617.6,104Z"},{"code":"AZ","name":"Aserbaidschan","path":"M615,93.8L615.8,94L617.9,95.9L619.1,96.2L619.3,95.3L620.5,94L622.2,95.7L624,98L625.2,98.2L626.2,99.1L624.2,99.3L624.4,101.9L624.2,103.1L623.5,103.9L623.9,105.5L623.3,105.7L621.4,103.9L621.9,102.3L620.9,101.3L620,101.6L617.6,104L617,101.7L615.8,101.2L614.5,100.3L615,99.2L613.4,98.1L613.7,97.3L612.6,96.7L611.9,95.8L612.4,95.3L614.5,96.2L615.9,96.4L616.1,96.1L614.5,94.3L615,93.8ZM616.7Line truncated
|
||||
@@ -9,4 +9,11 @@ public static class Formatting
|
||||
{ TotalMinutes: >= 1 } => $"{duration.Minutes} min {duration.Seconds} s",
|
||||
_ => $"{duration.TotalSeconds:0.0} s"
|
||||
};
|
||||
|
||||
public static string Flag(string? countryCode) =>
|
||||
countryCode is { Length: 2 } && char.IsAsciiLetter(countryCode[0]) && char.IsAsciiLetter(countryCode[1])
|
||||
? string.Concat(countryCode.ToUpperInvariant().Select(c => char.ConvertFromUtf32(0x1F1E6 + c - 'A')))
|
||||
: "";
|
||||
|
||||
public static string? Provider(long? asn, string? provider) => asn is null ? provider : $"AS{asn} {provider}".TrimEnd();
|
||||
}
|
||||
@@ -5,6 +5,12 @@
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Content Remove="Components\Pages\Dashboard\world-map.json" />
|
||||
<EmbeddedResource Include="Components\Pages\Dashboard\world-map.json" LogicalName="Flypaper.Web.world-map.json" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\Flypaper.GeoIp\Flypaper.GeoIp.csproj" />
|
||||
<ProjectReference Include="..\Flypaper.Http\Flypaper.Http.csproj" />
|
||||
<ProjectReference Include="..\Flypaper.Storage\Flypaper.Storage.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
using Flypaper.Core;
|
||||
using Flypaper.GeoIp;
|
||||
using Flypaper.Http;
|
||||
using Flypaper.Storage;
|
||||
using Flypaper.Web.Auth;
|
||||
@@ -16,6 +17,7 @@ builder.AddFlypaperStorage();
|
||||
builder.Services.AddRazorComponents();
|
||||
builder.Services.AddFlypaperCore(builder.Configuration);
|
||||
builder.Services.AddFlypaperHttp(builder.Configuration);
|
||||
builder.Services.AddFlypaperGeoIp(builder.Configuration);
|
||||
|
||||
var dataProtection = builder.Services.AddDataProtection().SetApplicationName("Flypaper");
|
||||
if (builder.Configuration["Flypaper:DataProtection:KeysPath"] is { Length: > 0 } keysPath)
|
||||
|
||||
@@ -3,7 +3,8 @@
|
||||
"LogLevel": {
|
||||
"Default": "Information",
|
||||
"Microsoft.AspNetCore": "Warning",
|
||||
"Microsoft.EntityFrameworkCore": "Warning"
|
||||
"Microsoft.EntityFrameworkCore": "Warning",
|
||||
"System.Net.Http.HttpClient": "Warning"
|
||||
},
|
||||
"Console": {
|
||||
"FormatterName": "simple",
|
||||
|
||||
@@ -369,3 +369,85 @@ tbody th {
|
||||
.top h1 {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.world-map {
|
||||
display: block;
|
||||
width: 100%;
|
||||
height: auto;
|
||||
}
|
||||
|
||||
.world-map path {
|
||||
stroke: var(--surface);
|
||||
stroke-width: 0.5;
|
||||
}
|
||||
|
||||
.world-map path:hover {
|
||||
stroke: var(--text);
|
||||
stroke-width: 1;
|
||||
}
|
||||
|
||||
.level-0 {
|
||||
fill: color-mix(in srgb, var(--text) 10%, var(--surface));
|
||||
background: color-mix(in srgb, var(--text) 10%, var(--surface));
|
||||
}
|
||||
|
||||
.level-1 {
|
||||
fill: color-mix(in srgb, var(--accent) 25%, var(--surface));
|
||||
background: color-mix(in srgb, var(--accent) 25%, var(--surface));
|
||||
}
|
||||
|
||||
.level-2 {
|
||||
fill: color-mix(in srgb, var(--accent) 42%, var(--surface));
|
||||
background: color-mix(in srgb, var(--accent) 42%, var(--surface));
|
||||
}
|
||||
|
||||
.level-3 {
|
||||
fill: color-mix(in srgb, var(--accent) 60%, var(--surface));
|
||||
background: color-mix(in srgb, var(--accent) 60%, var(--surface));
|
||||
}
|
||||
|
||||
.level-4 {
|
||||
fill: color-mix(in srgb, var(--accent) 80%, var(--surface));
|
||||
background: color-mix(in srgb, var(--accent) 80%, var(--surface));
|
||||
}
|
||||
|
||||
.level-5 {
|
||||
fill: var(--accent);
|
||||
background: var(--accent);
|
||||
}
|
||||
|
||||
.map-legend {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: flex-end;
|
||||
gap: 4px;
|
||||
margin-top: 8px;
|
||||
color: var(--muted);
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.map-legend .swatch {
|
||||
width: 18px;
|
||||
height: 10px;
|
||||
border-radius: 2px;
|
||||
}
|
||||
|
||||
.detail {
|
||||
display: none;
|
||||
}
|
||||
|
||||
tr.open .detail {
|
||||
display: block;
|
||||
color: var(--muted);
|
||||
white-space: normal;
|
||||
}
|
||||
|
||||
.footer {
|
||||
margin-top: 24px;
|
||||
color: var(--muted);
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.footer a {
|
||||
color: inherit;
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
using System.Collections.Concurrent;
|
||||
using System.Net;
|
||||
|
||||
namespace Flypaper.Tests.Fakes;
|
||||
|
||||
internal sealed class FakeHttpHandler : HttpMessageHandler
|
||||
{
|
||||
private readonly ConcurrentDictionary<string, Func<HttpResponseMessage>> _responses = new();
|
||||
|
||||
public ConcurrentQueue<string> Requests { get; } = new();
|
||||
|
||||
public void Respond(string url, Func<HttpResponseMessage> response) => _responses[url] = response;
|
||||
|
||||
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
|
||||
{
|
||||
var url = request.RequestUri!.ToString();
|
||||
Requests.Enqueue(url);
|
||||
return Task.FromResult(_responses.TryGetValue(url, out var response)
|
||||
? response()
|
||||
: new HttpResponseMessage(HttpStatusCode.NotFound));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
namespace Flypaper.Tests.Fakes;
|
||||
|
||||
internal sealed class FixedTimeProvider(DateTimeOffset now) : TimeProvider
|
||||
{
|
||||
public override DateTimeOffset GetUtcNow() => now;
|
||||
}
|
||||
@@ -15,6 +15,7 @@
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\src\Flypaper.GeoIp\Flypaper.GeoIp.csproj" />
|
||||
<ProjectReference Include="..\..\src\Flypaper.Http\Flypaper.Http.csproj" />
|
||||
<ProjectReference Include="..\..\src\Flypaper.Storage\Flypaper.Storage.csproj" />
|
||||
<ProjectReference Include="..\..\src\Flypaper.Web\Flypaper.Web.csproj" />
|
||||
|
||||
@@ -0,0 +1,108 @@
|
||||
using System.Net;
|
||||
using Flypaper.Core.Models;
|
||||
using Flypaper.GeoIp;
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
using NSubstitute;
|
||||
using NSubstitute.ExceptionExtensions;
|
||||
using Shouldly;
|
||||
|
||||
namespace Flypaper.Tests.GeoIp;
|
||||
|
||||
public sealed class DbIpEnricherTests
|
||||
{
|
||||
private static readonly IpOrigin Germany = new("DE", "Deutschland", "Berlin", 3320, "Deutsche Telekom AG");
|
||||
private static readonly IPAddress PublicIp = IPAddress.Parse("203.0.113.9");
|
||||
|
||||
private readonly IGeoIpDatabaseFactory _factory = Substitute.For<IGeoIpDatabaseFactory>();
|
||||
private readonly IGeoIpDatabase _database = Substitute.For<IGeoIpDatabase>();
|
||||
|
||||
[Fact]
|
||||
public void Returns_origin_for_public_ip()
|
||||
{
|
||||
_database.Find(PublicIp).Returns(Germany);
|
||||
_factory.Open().Returns(_database);
|
||||
|
||||
var enricher = CreateEnricher();
|
||||
|
||||
enricher.IsAvailable.ShouldBeTrue();
|
||||
enricher.Lookup(PublicIp).ShouldBe(Germany);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Looks_up_ipv4_mapped_addresses_as_ipv4()
|
||||
{
|
||||
_database.Find(PublicIp).Returns(Germany);
|
||||
_factory.Open().Returns(_database);
|
||||
|
||||
CreateEnricher().Lookup(PublicIp.MapToIPv6()).ShouldBe(Germany);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("10.1.2.3")]
|
||||
[InlineData("172.19.0.5")]
|
||||
[InlineData("192.168.1.14")]
|
||||
[InlineData("127.0.0.1")]
|
||||
[InlineData("::1")]
|
||||
[InlineData("fe80::1")]
|
||||
public void Does_not_look_up_private_ips(string address)
|
||||
{
|
||||
_factory.Open().Returns(_database);
|
||||
|
||||
CreateEnricher().Lookup(IPAddress.Parse(address)).ShouldBeNull();
|
||||
|
||||
_database.DidNotReceiveWithAnyArgs().Find(default!);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Returns_nothing_without_database()
|
||||
{
|
||||
_factory.Open().Returns((IGeoIpDatabase?)null);
|
||||
|
||||
var enricher = CreateEnricher();
|
||||
|
||||
enricher.IsAvailable.ShouldBeFalse();
|
||||
enricher.Lookup(PublicIp).ShouldBeNull();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Swallows_lookup_errors()
|
||||
{
|
||||
_database.Find(PublicIp).Throws(new InvalidOperationException("corrupt"));
|
||||
_factory.Open().Returns(_database);
|
||||
|
||||
CreateEnricher().Lookup(PublicIp).ShouldBeNull();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Reload_switches_to_new_database_and_raises_updated()
|
||||
{
|
||||
_factory.Open().Returns((IGeoIpDatabase?)null, _database);
|
||||
_database.Find(PublicIp).Returns(Germany);
|
||||
var enricher = CreateEnricher();
|
||||
var raised = 0;
|
||||
enricher.Updated += (_, _) => raised++;
|
||||
|
||||
enricher.Reload();
|
||||
|
||||
raised.ShouldBe(1);
|
||||
enricher.IsAvailable.ShouldBeTrue();
|
||||
enricher.Lookup(PublicIp).ShouldBe(Germany);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Reload_keeps_current_database_when_files_are_missing()
|
||||
{
|
||||
_factory.Open().Returns(_database, (IGeoIpDatabase?)null);
|
||||
_database.Find(PublicIp).Returns(Germany);
|
||||
var enricher = CreateEnricher();
|
||||
var raised = 0;
|
||||
enricher.Updated += (_, _) => raised++;
|
||||
|
||||
enricher.Reload();
|
||||
|
||||
raised.ShouldBe(0);
|
||||
enricher.Lookup(PublicIp).ShouldBe(Germany);
|
||||
}
|
||||
|
||||
private DbIpEnricher CreateEnricher() => new(_factory, NullLogger<DbIpEnricher>.Instance);
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
using System.IO.Compression;
|
||||
using System.Net;
|
||||
using Flypaper.GeoIp;
|
||||
using Flypaper.Tests.Fakes;
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
using Microsoft.Extensions.Options;
|
||||
using NSubstitute;
|
||||
using Shouldly;
|
||||
|
||||
namespace Flypaper.Tests.GeoIp;
|
||||
|
||||
public sealed class GeoIpUpdaterTests : IDisposable
|
||||
{
|
||||
private const string BaseUrl = "https://download.test/free/";
|
||||
private static readonly DateTimeOffset Now = new(2026, 11, 3, 8, 0, 0, TimeSpan.Zero);
|
||||
|
||||
private readonly string _directory = Path.Combine(Path.GetTempPath(), $"flypaper-geoip-{Guid.NewGuid():N}");
|
||||
private readonly FakeHttpHandler _http = new();
|
||||
|
||||
[Fact]
|
||||
public async Task Falls_back_to_previous_month_when_current_is_not_released()
|
||||
{
|
||||
_http.Respond($"{BaseUrl}dbip-city-lite-2026-10.mmdb.gz", () => Gzip("city-october"));
|
||||
_http.Respond($"{BaseUrl}dbip-asn-lite-2026-10.mmdb.gz", () => Gzip("asn-october"));
|
||||
|
||||
(await CreateUpdater().UpdateAsync(CancellationToken.None)).ShouldBeTrue();
|
||||
|
||||
File.ReadAllText(Path.Combine(_directory, "dbip-city-lite.mmdb")).ShouldBe("city-october");
|
||||
File.ReadAllText(Path.Combine(_directory, "dbip-asn-lite.mmdb")).ShouldBe("asn-october");
|
||||
File.ReadAllText(Path.Combine(_directory, "dbip-city-lite.mmdb.version")).ShouldBe("2026-10");
|
||||
_http.Requests.ShouldContain($"{BaseUrl}dbip-city-lite-2026-11.mmdb.gz");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Prefers_current_month()
|
||||
{
|
||||
_http.Respond($"{BaseUrl}dbip-city-lite-2026-11.mmdb.gz", () => Gzip("city-november"));
|
||||
_http.Respond($"{BaseUrl}dbip-asn-lite-2026-11.mmdb.gz", () => Gzip("asn-november"));
|
||||
|
||||
(await CreateUpdater().UpdateAsync(CancellationToken.None)).ShouldBeTrue();
|
||||
|
||||
File.ReadAllText(Path.Combine(_directory, "dbip-city-lite.mmdb.version")).ShouldBe("2026-11");
|
||||
_http.Requests.ShouldNotContain($"{BaseUrl}dbip-city-lite-2026-10.mmdb.gz");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Skips_download_when_previous_month_is_installed_and_current_is_missing()
|
||||
{
|
||||
Install("city", "2026-10");
|
||||
Install("asn", "2026-10");
|
||||
|
||||
(await CreateUpdater().UpdateAsync(CancellationToken.None)).ShouldBeFalse();
|
||||
|
||||
_http.Requests.ShouldBe([$"{BaseUrl}dbip-city-lite-2026-11.mmdb.gz", $"{BaseUrl}dbip-asn-lite-2026-11.mmdb.gz"]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Skips_requests_when_current_month_is_installed()
|
||||
{
|
||||
Install("city", "2026-11");
|
||||
Install("asn", "2026-11");
|
||||
|
||||
(await CreateUpdater().UpdateAsync(CancellationToken.None)).ShouldBeFalse();
|
||||
|
||||
_http.Requests.ShouldBeEmpty();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Fails_without_touching_files_when_server_errors()
|
||||
{
|
||||
_http.Respond($"{BaseUrl}dbip-city-lite-2026-11.mmdb.gz", () => new HttpResponseMessage(HttpStatusCode.InternalServerError));
|
||||
|
||||
await Should.ThrowAsync<HttpRequestException>(() => CreateUpdater().UpdateAsync(CancellationToken.None));
|
||||
|
||||
File.Exists(Path.Combine(_directory, "dbip-city-lite.mmdb")).ShouldBeFalse();
|
||||
}
|
||||
|
||||
private GeoIpUpdater CreateUpdater()
|
||||
{
|
||||
var options = Options.Create(new GeoIpOptions { Directory = _directory, BaseUrl = BaseUrl });
|
||||
var httpClientFactory = Substitute.For<IHttpClientFactory>();
|
||||
httpClientFactory.CreateClient(Arg.Any<string>()).Returns(_ => new HttpClient(_http, disposeHandler: false));
|
||||
var databaseFactory = Substitute.For<IGeoIpDatabaseFactory>();
|
||||
var enricher = new DbIpEnricher(databaseFactory, NullLogger<DbIpEnricher>.Instance);
|
||||
|
||||
return new GeoIpUpdater(httpClientFactory, options, enricher, new FixedTimeProvider(Now), NullLogger<GeoIpUpdater>.Instance);
|
||||
}
|
||||
|
||||
private void Install(string kind, string month)
|
||||
{
|
||||
Directory.CreateDirectory(_directory);
|
||||
File.WriteAllText(Path.Combine(_directory, $"dbip-{kind}-lite.mmdb"), kind);
|
||||
File.WriteAllText(Path.Combine(_directory, $"dbip-{kind}-lite.mmdb.version"), month);
|
||||
}
|
||||
|
||||
private static HttpResponseMessage Gzip(string content)
|
||||
{
|
||||
using var buffer = new MemoryStream();
|
||||
using (var gzip = new GZipStream(buffer, CompressionMode.Compress, leaveOpen: true))
|
||||
using (var writer = new StreamWriter(gzip))
|
||||
{
|
||||
writer.Write(content);
|
||||
}
|
||||
|
||||
return new HttpResponseMessage(HttpStatusCode.OK) { Content = new ByteArrayContent(buffer.ToArray()) };
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
if (Directory.Exists(_directory))
|
||||
{
|
||||
Directory.Delete(_directory, recursive: true);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
using System.Net;
|
||||
using Flypaper.Core.Abstractions;
|
||||
using Flypaper.Core.Models;
|
||||
using Flypaper.Storage;
|
||||
using Flypaper.Storage.Entities;
|
||||
using Flypaper.Storage.Events;
|
||||
using Microsoft.Data.Sqlite;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
using NSubstitute;
|
||||
using Shouldly;
|
||||
|
||||
namespace Flypaper.Tests.Storage;
|
||||
|
||||
public sealed class OriginEnrichmentTests : IDisposable
|
||||
{
|
||||
private static readonly IpOrigin Germany = new("DE", "Deutschland", "Berlin", 3320, "Deutsche Telekom AG");
|
||||
|
||||
private readonly string _dbPath = Path.Combine(Path.GetTempPath(), $"flypaper-origin-{Guid.NewGuid():N}.db");
|
||||
private readonly IIpEnricher _enricher = Substitute.For<IIpEnricher>();
|
||||
private readonly IDbContextFactory<FlypaperDbContext> _dbContextFactory;
|
||||
|
||||
public OriginEnrichmentTests()
|
||||
{
|
||||
_dbContextFactory = new TestDbContextFactory($"Data Source={_dbPath}");
|
||||
using var db = _dbContextFactory.CreateDbContext();
|
||||
db.Database.Migrate();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Writer_stores_origin_with_new_trap_event()
|
||||
{
|
||||
_enricher.Lookup(IPAddress.Parse("203.0.113.9")).Returns(Germany);
|
||||
var sink = new ChannelTrapEventSink();
|
||||
using var writer = new TrapEventWriter(sink, _dbContextFactory, _enricher, NullLogger<TrapEventWriter>.Instance);
|
||||
await writer.StartAsync(CancellationToken.None);
|
||||
|
||||
sink.Publish(Event("203.0.113.9"));
|
||||
var stored = await WaitForEventAsync();
|
||||
await writer.StopAsync(CancellationToken.None);
|
||||
|
||||
stored.CountryCode.ShouldBe("DE");
|
||||
stored.Country.ShouldBe("Deutschland");
|
||||
stored.City.ShouldBe("Berlin");
|
||||
stored.Asn.ShouldBe(3320);
|
||||
stored.Provider.ShouldBe("Deutsche Telekom AG");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Writer_stores_event_without_origin_when_lookup_has_no_result()
|
||||
{
|
||||
var sink = new ChannelTrapEventSink();
|
||||
using var writer = new TrapEventWriter(sink, _dbContextFactory, _enricher, NullLogger<TrapEventWriter>.Instance);
|
||||
await writer.StartAsync(CancellationToken.None);
|
||||
|
||||
sink.Publish(Event("203.0.113.9"));
|
||||
var stored = await WaitForEventAsync();
|
||||
await writer.StopAsync(CancellationToken.None);
|
||||
|
||||
stored.CountryCode.ShouldBeNull();
|
||||
stored.Asn.ShouldBeNull();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Backfill_adds_origin_to_stored_events_without_one()
|
||||
{
|
||||
await using (var db = await _dbContextFactory.CreateDbContextAsync())
|
||||
{
|
||||
db.TrapEvents.AddRange(Entity("203.0.113.9"), Entity("172.19.0.5"), Entity("198.51.100.1"));
|
||||
await db.SaveChangesAsync();
|
||||
}
|
||||
|
||||
_enricher.Lookup(IPAddress.Parse("203.0.113.9")).Returns(Germany);
|
||||
_enricher.Lookup(IPAddress.Parse("198.51.100.1")).Returns(Germany with { CountryCode = "NL", Country = "Niederlande" });
|
||||
using var backfill = new OriginBackfill(_dbContextFactory, _enricher, NullLogger<OriginBackfill>.Instance);
|
||||
|
||||
(await backfill.BackfillAsync(CancellationToken.None)).ShouldBe(2);
|
||||
|
||||
await using var check = await _dbContextFactory.CreateDbContextAsync();
|
||||
var rows = await check.TrapEvents.OrderBy(e => e.Id).ToListAsync();
|
||||
rows.Select(e => e.CountryCode).ShouldBe(["DE", null, "NL"]);
|
||||
}
|
||||
|
||||
private async Task<TrapEventEntity> WaitForEventAsync()
|
||||
{
|
||||
for (var attempt = 0; attempt < 50; attempt++)
|
||||
{
|
||||
await using var db = await _dbContextFactory.CreateDbContextAsync();
|
||||
if (await db.TrapEvents.FirstOrDefaultAsync() is { } stored)
|
||||
{
|
||||
return stored;
|
||||
}
|
||||
|
||||
await Task.Delay(20);
|
||||
}
|
||||
|
||||
throw new TimeoutException("Trap event was not stored.");
|
||||
}
|
||||
|
||||
private static TrapEvent Event(string ip) => new(
|
||||
Guid.NewGuid(),
|
||||
TrapProtocol.Http,
|
||||
IPAddress.Parse(ip),
|
||||
"drip",
|
||||
DateTimeOffset.UtcNow.AddSeconds(-5),
|
||||
DateTimeOffset.UtcNow,
|
||||
5,
|
||||
TrapOutcome.ClientAborted,
|
||||
"GET /.env");
|
||||
|
||||
private static TrapEventEntity Entity(string ip) => TrapEventEntity.From(Event(ip));
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
SqliteConnection.ClearAllPools();
|
||||
foreach (var suffix in new[] { "", "-wal", "-shm" })
|
||||
{
|
||||
File.Delete(_dbPath + suffix);
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class TestDbContextFactory(string connectionString) : IDbContextFactory<FlypaperDbContext>
|
||||
{
|
||||
public FlypaperDbContext CreateDbContext() =>
|
||||
new(new DbContextOptionsBuilder<FlypaperDbContext>().UseSqlite(connectionString).Options);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user