Add IP origin enrichment with DB-IP and world map
Build and deploy / build (push) Successful in 1m46s
Build and deploy / deploy (push) Successful in 22s

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
TomandClaude Opus 5.5 committed 2026-11-14 15:44:33 +01:00
1 parent 536aee1f31
commit 3671019e60
47 files changed
+1389 -12

No files matched your search

@@ -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);
}
}