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(); private readonly IDbContextFactory _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.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.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.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 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 { public FlypaperDbContext CreateDbContext() => new(new DbContextOptionsBuilder().UseSqlite(connectionString).Options); } }