using Heimdall.Domain.Entities; using Heimdall.Infrastructure.Data; using Heimdall.Infrastructure.Data.Interceptors; using Heimdall.Infrastructure.Security; using Heimdall.TestCommon; using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Http; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Npgsql; using Shouldly; namespace Heimdall.Infrastructure.Tests; [Collection("PostgresInfra")] public sealed class ApiKeyLastUsedPostgresTests(PostgreSqlContainerFixture postgres) { [Fact] public async Task Authentication_updates_last_used_once_per_minute_even_for_concurrent_requests() { var options = new DbContextOptionsBuilder() .UseNpgsql(postgres.ConnectionString) .Options; await using (var setup = new AppDbContext(options, new AuditInterceptor())) await setup.Database.EnsureCreatedAsync(); var (plainKey, prefix, hash) = ApiKeyAuthenticationHandler.GenerateApiKey(); var site = new Site("API key activity test", "test", "UTC"); var agent = new Agent(site.Id, "activity-agent", "activity-host", "1.0"); agent.Register(hash, prefix); var apiKey = new ApiKey(hash, prefix, site.Id); await using (var seed = new AppDbContext(options, new AuditInterceptor())) { seed.AddRange(site, agent, apiKey); await seed.SaveChangesAsync(); await seed.Database.ExecuteSqlRawAsync(""" CREATE TABLE IF NOT EXISTS api_key_update_counts ( "Id" uuid PRIMARY KEY, "Count" integer NOT NULL ); CREATE OR REPLACE FUNCTION count_api_key_update() RETURNS trigger AS $$ BEGIN INSERT INTO api_key_update_counts ("Id", "Count") VALUES (NEW."Id", 1) ON CONFLICT ("Id") DO UPDATE SET "Count" = api_key_update_counts."Count" + 1; RETURN NEW; END; $$ LANGUAGE plpgsql; DROP TRIGGER IF EXISTS count_api_key_update_trigger ON api_keys; CREATE TRIGGER count_api_key_update_trigger AFTER UPDATE ON api_keys FOR EACH ROW EXECUTE FUNCTION count_api_key_update(); """); } var services = new ServiceCollection(); services.AddLogging(); services.AddSingleton(new AuditInterceptor()); services.AddDbContext(builder => builder.UseNpgsql(postgres.ConnectionString)); services.AddAuthentication("ApiKey") .AddScheme("ApiKey", _ => { }); using var provider = services.BuildServiceProvider(); async Task AuthenticateAsync() { await using var scope = provider.CreateAsyncScope(); var context = new DefaultHttpContext { RequestServices = scope.ServiceProvider }; context.Request.Headers["X-API-Key"] = plainKey; return await context.AuthenticateAsync("ApiKey"); } var results = await Task.WhenAll(Enumerable.Range(0, 8).Select(_ => AuthenticateAsync())); results.ShouldAllBe(result => result.Succeeded); DateTime firstUse; await using (var verify = new AppDbContext(options, new AuditInterceptor())) { var firstApiKey = await verify.ApiKeys.AsNoTracking().SingleAsync(key => key.Id == apiKey.Id); firstApiKey.LastUsedAt.ShouldNotBeNull(); firstUse = firstApiKey.LastUsedAt!.Value; var firstWindowWrites = await ReadWriteCountAsync(verify, apiKey.Id); firstWindowWrites.ShouldBe(1); } (await AuthenticateAsync()).Succeeded.ShouldBeTrue(); await using (var verify = new AppDbContext(options, new AuditInterceptor())) { var recentUse = (await verify.ApiKeys.AsNoTracking().SingleAsync(key => key.Id == apiKey.Id)).LastUsedAt; recentUse.ShouldBe(firstUse); (await ReadWriteCountAsync(verify, apiKey.Id)).ShouldBe(1); var staleTimestamp = DateTime.UtcNow.AddMinutes(-2); await verify.ApiKeys.Where(key => key.Id == apiKey.Id) .ExecuteUpdateAsync(setters => setters.SetProperty(key => key.LastUsedAt, staleTimestamp)); await verify.Database.ExecuteSqlInterpolatedAsync( $"UPDATE api_key_update_counts SET \"Count\" = 0 WHERE \"Id\" = {apiKey.Id}"); } (await AuthenticateAsync()).Succeeded.ShouldBeTrue(); await using (var verify = new AppDbContext(options, new AuditInterceptor())) { var refreshedUse = (await verify.ApiKeys.AsNoTracking().SingleAsync(key => key.Id == apiKey.Id)).LastUsedAt; refreshedUse.ShouldNotBeNull(); refreshedUse!.Value.ShouldBeGreaterThan(firstUse); (await ReadWriteCountAsync(verify, apiKey.Id)).ShouldBe(1); } } private static async Task ReadWriteCountAsync(AppDbContext db, Guid apiKeyId) { await using var command = db.Database.GetDbConnection().CreateCommand(); command.CommandText = "SELECT \"Count\" FROM api_key_update_counts WHERE \"Id\" = @id"; var parameter = command.CreateParameter(); parameter.ParameterName = "id"; parameter.Value = apiKeyId; command.Parameters.Add(parameter); if (command.Connection!.State != System.Data.ConnectionState.Open) await command.Connection.OpenAsync(); var result = await command.ExecuteScalarAsync(); return Convert.ToInt32(result, System.Globalization.CultureInfo.InvariantCulture); } }