fix(auth): throttle API key LastUsedAt writes #313

Merged
arnaud.dartois merged 1 commits from fix/api-key-last-used-write-throttle into main 2026-11-09 12:36:54 +01:00
3 changed files with 162 additions and 5 deletions

No files matched your search

@@ -0,0 +1,23 @@
---
name: api-key-last-used-throttle
description: Preserve Heimdall API-key authentication while limiting LastUsedAt persistence to one atomic EF Core update per minute.
---
# API-key activity timestamp
`ApiKeyAuthenticationHandler` authenticates an agent API key for every protected request. `LastUsedAt` is an operator-facing activity indicator; it does not need request-level precision. Keep API-key validation, agent binding, authorization claims, and expiry checks on every request, while avoiding a database write for every heartbeat or telemetry call.
## Implementation
- Pass `HttpContext.RequestAborted` to each database read and write in the authentication handler.
- Update `LastUsedAt` with EF Core `ExecuteUpdateAsync`, using a database-side predicate that permits the write only when the timestamp is null or at least one minute old. The predicate and update must be one SQL statement so concurrent requests using the same key collapse to one write.
- Do not call `SaveChangesAsync` for this timestamp. The handler has no other pending changes, and the tracked API-key entity is only needed for validation and claims.
- Keep the timestamp semantics visible to operators: after a burst of requests, it reports recent use with up to one minute of delay.
## Acceptance
1. A PostgreSQL relational test verifies that a null timestamp is written, requests inside the one-minute window do not rewrite it, an expired window refreshes it, and concurrent requests produce no duplicate update within the window.
2. API-key authentication tests verify valid, expired, unbound, and invalid keys retain their existing outcomes and claims.
3. Run the CI EF Core persistence policy and the focused Infrastructure/Web test suites.
4. Run the disposable Compose recipe from `skills/compose-disposable-recipe/SKILL.md` with unique credentials, project name, ports, volumes, and local image tag. Verify authentication behavior, then verify that project resources and the exact locally built tag are absent after teardown.
5. Link the change to Gitea GlitchTip issues #200, #201, #202, #203, and #205. Record the actual local/CI/Compose results and keep post-deployment GlitchTip evidence distinct.
@@ -45,9 +45,10 @@ public class ApiKeyAuthenticationHandler : AuthenticationHandler<ApiKeyAuthentic
using var scope = _serviceProvider.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
var cancellationToken = Context.RequestAborted;
var apiKeyEntity = await db.ApiKeys
.FirstOrDefaultAsync(k => k.KeyPrefix == prefix && k.Enabled);
.FirstOrDefaultAsync(k => k.KeyPrefix == prefix && k.Enabled, cancellationToken);
if (apiKeyEntity is null)
return AuthenticateResult.Fail("Invalid API key");
@@ -67,13 +68,22 @@ public class ApiKeyAuthenticationHandler : AuthenticationHandler<ApiKeyAuthentic
// by the full verified hash, and reject ambiguous or stale bindings.
var agents = await db.Agents.AsNoTracking()
.Where(a => a.ApiKeyHash == apiKeyEntity.KeyHash && a.SiteId == apiKeyEntity.SiteId)
.Select(a => a.Id).Take(2).ToListAsync(Context.RequestAborted);
.Select(a => a.Id).Take(2).ToListAsync(cancellationToken);
if (agents.Count != 1 || !apiKeyEntity.SiteId.HasValue)
return AuthenticateResult.Fail("API key is not bound to one active agent");
apiKeyEntity.MarkUsed();
// Persist LastUsedAt update
await db.SaveChangesAsync();
// LastUsedAt is an administrative activity indicator, not an audit log.
// Updating it on every request creates avoidable writes and contention
// when an agent sends concurrent heartbeats and telemetry. The predicate
// and update execute atomically in PostgreSQL, so concurrent requests
// collapse to at most one write per key per minute.
var now = DateTime.UtcNow;
var updateBefore = now.AddMinutes(-1);
await db.ApiKeys
.Where(key => key.Id == apiKeyEntity.Id &&
(key.LastUsedAt == null || key.LastUsedAt <= updateBefore))
.ExecuteUpdateAsync(setters => setters.SetProperty(key => key.LastUsedAt, now), cancellationToken)
.ConfigureAwait(false);
var claims = new List<Claim>
{
@@ -0,0 +1,124 @@
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<AppDbContext>()
.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<AppDbContext>(builder => builder.UseNpgsql(postgres.ConnectionString));
services.AddAuthentication("ApiKey")
.AddScheme<ApiKeyAuthenticationOptions, ApiKeyAuthenticationHandler>("ApiKey", _ => { });
using var provider = services.BuildServiceProvider();
async Task<AuthenticateResult> 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<int> 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);
}
}