Files
arnaud.dartois 374b7f267f
Heimdall Gitea / Detect CI scope (push) Successful in 6s
Heimdall Gitea / Build and tests (push) Successful in 26m21s
Heimdall Gitea / Build and scan agent image (push) Successful in 6m32s
Heimdall Gitea / Build and scan server image (push) Successful in 8m59s
Heimdall Gitea / Publish Docker Hub latest tags (push) Successful in 1m37s
Heimdall Gitea / Build and scan NVIDIA Agent image (push) Successful in 26m10s
Heimdall Gitea / Publish signed main release (push) Canceled after 42m57s
Heimdall Gitea / CI policy (push) Failing after 2s
fix(auth): throttle API key LastUsedAt writes (#313)
## Résumé
Réduit les écritures de `LastUsedAt` à une mise à jour atomique EF Core par clé et par minute, tout en transmettant l’annulation HTTP aux requêtes de validation. Ajoute une vérification PostgreSQL concurrente et le workflow projet dans `skills/api-key-last-used-throttle/SKILL.md`.

## Tickets
Refs #200, #201, #202, #203, #205. Les tickets restent ouverts jusqu’à la vérification post-déploiement GlitchTip requise par leurs critères; les événements examinés étaient en environnement Development et ne démontrent pas une régression en production.

## Vérifications observées
- `dotnet test tests/Heimdall.Infrastructure.Tests/Heimdall.Infrastructure.Tests.csproj --no-restore --filter FullyQualifiedName~ApiKeyLastUsedPostgresTests` — 1 réussi.
- `dotnet test tests/Heimdall.Web.Tests/Heimdall.Web.Tests.csproj --no-restore --filter FullyQualifiedName~ApiKeyIdentityTests` — 1 réussi.
- `python3 scripts/ci/check-efcore-usage.py` — réussi.
- Compose jetable construit depuis le commit, projet isolé `heimdall-api-key-20261109100145-12450`, image `heimdall:heimdall-api-key-20261109100145-12450-acceptance`; `/healthz` et `/api/auth/bootstrap-status` HTTP 200. Après teardown, aucune ressource Compose du projet ne subsiste et le tag exact est absent. L’image PostgreSQL et les images amont sont conservées.

## Limite d’acceptation
Le Compose vérifie le démarrage source et les routes HTTP de santé/bootstrap; le changement de persistance et la concurrence sont exercés par le test d’intégration PostgreSQL.

Reviewed-on: #313
Co-authored-by: Arnaud Dartois <admin@tordais.cc>
2026-11-09 12:36:53 +01:00

125 lines
5.7 KiB
C#

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