feat(auth): batch API-key last-used writes off the request path (0.6.0, #61)

ApiKeyVerifier no longer awaits IApiKeyStore.MarkUsedAsync per verification.
A new ApiKeyUsageRecorder keeps key id -> latest use time in memory and a
background PeriodicTimer writes each key at most once per
ApiKeyOptions.LastUsedWriteIntervalSeconds (default 60; 0 = old inline write),
plus a final flush on dispose. ApiKeyVerifier is now IAsyncDisposable/IDisposable
and owned by the DI container. Failed stamps are counted (FailedWrites + meter
counter zb.auth.apikey.last_used.write_failures) and logged, never surfaced.

last_used_utc is now accurate to the interval. Version 0.6.0, unpublished.
Closes #61.
This commit is contained in:
Joseph Doherty
2026-12-05 01:10:31 -05:00
parent f077556e18
commit 2e52a02b85
10 changed files with 539 additions and 18 deletions
@@ -1,6 +1,7 @@
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using ZB.MOM.WW.Auth.Abstractions.ApiKeys;
using ZB.MOM.WW.Auth.ApiKeys.Sqlite;
@@ -55,11 +56,15 @@ public static class ApiKeyServiceCollectionExtensions
services.TryAddSingleton<IApiKeyAuditStore>(sp =>
new SqliteApiKeyAuditStore(sp.GetRequiredService<AuthSqliteConnectionFactory>()));
// The container owns the verifier, so it disposes it at shutdown — which flushes the
// last interval of batched last-used stamps (scadaproj#61).
services.TryAddSingleton<IApiKeyVerifier>(sp =>
new ApiKeyVerifier(
sp.GetRequiredService<IOptions<ApiKeyOptions>>().Value,
sp.GetRequiredService<IApiKeyStore>(),
sp.GetRequiredService<IApiKeyPepperProvider>()));
sp.GetRequiredService<IApiKeyPepperProvider>(),
sp.GetService<TimeProvider>(),
sp.GetService<ILogger<ApiKeyUsageRecorder>>()));
// Migrator: the SQLite implementation is the default; a provider package that registers
// IApiKeyStoreMigrator (and the three stores) BEFORE this call displaces it — that is the