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
@@ -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");
|
||||
|
||||
Reference in new issue
Block a user