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
+2
View File
@@ -42,6 +42,8 @@ MxAccessGateway & HistorianGateway → the original four; ScadaBridge → those
**`tools/LdapProbe`** (`ldapprobe`, not packable, outside the Auth solution) is the diagnostic that found the above: it drives the **real** `LdapAuthService` so its verdict is what the four apps produce, then separately queries the directory for what the library cannot report — full group DNs, **nested** groups via `LDAP_MATCHING_RULE_IN_CHAIN`, the **primary group** (which AD omits from `memberOf`, so it can never be a role group), group type (security vs distribution), decoded `userAccountControl`, referral counts, and the TLS chain with key sizes. `--list-groups '<pat>'` enumerates every group in the directory matching a pattern, which a membership dump structurally cannot do. Findings recorded in [`ldap_setup.md`](ldap_setup.md), including the **`UG_WW_*` Wonderware group convention (39 groups)** that partly overturns that doc's earlier "no group→role convention exists" claim — it was true of Ignition, false of the domain.
**`0.6.0` (2026-12-05, scadaproj#61, from historiangw#169 HOST-01; unpublished):** API-key `last_used_utc` is no longer written on the request path. `ApiKeyOptions.LastUsedWriteIntervalSeconds` (default 60; 0 = the old inline write) feeds a new `ApiKeyUsageRecorder`: an in-memory map of key id → latest use time, flushed by a background `PeriodicTimer` once per interval and again on dispose. `ApiKeyVerifier` became `IAsyncDisposable`/`IDisposable` (the DI container owns and flushes it). Failed stamps are counted (`FailedWrites`, plus the meter `ZB.MOM.WW.Auth.ApiKeys` counter `zb.auth.apikey.last_used.write_failures`) and logged, never surfaced. 12 new tests in `ApiKeyUsageRecorderTests`. Two mutations were each caught (inline write restored → 4 failures; dispose flush removed → 3 failures). The existing verifier tests are pinned to interval 0. Consumers pick this up by bumping their pins once it is published; HistorianGateway's own verification cache (historiangw#169 step 2) sits on top. README §0.6.0.
**`0.5.0` (2026-11-12, ScadaBridge#46) — passwordless group lookup; first published version carrying 0.4.2–0.4.4.** New `Abstractions` contract `ILdapGroupLookup.GetUserGroupsAsync(username, ct)` → `LdapGroupLookupResult` / `LdapGroupLookupStatus` (`Found`, `UserNotFound`, `UserDisabled` (AD `userAccountControl` bit 2), `AmbiguousUser`, `DirectoryUnavailable`, `NotSupported` (`BindMode=User` / blank service DN / foreign `ILdapAuthService`), `ProviderDisabled`). Implemented by `LdapAuthService` (service-account bind + `UserNameAttribute` search; same extraction/canonicalisation as sign-in; the endpoint walk was factored into one generic `WalkEndpoints<T>` shared by both paths, so failover and the sticky preference are common). `AddZbLdapAuth` registers it as the same singleton. Tests: 30 unit (`LdapGroupLookupTests`, 6 mutations all killed) + 2 DI + 6 live GLAuth (`GLAuthGroupLookupTests`, run against the redundant local pair incl. two-live-endpoint failover; failover mutation killed live). **scadaproj#51 closed by a live NAM run (24/24)** — see README §0.5.0/§0.4.4 for what was proven; the identity check's non-vacuity was shown by mutating the `msDS-PrincipalName` comparison (user-bind sign-ins then fail). Consumers: ScadaBridge adopts 0.5.0 (#46); OtOpcUa / mxgw / HistorianGateway / BTDB stay on their pins.
**`0.4.4` (first published in 0.5.0, scadaproj#40, Auth-007):** `BindMode=User` now proves the entry whose groups it returns is the account that bound — RFC 4532 Who-am-I (`dn:` → DN match; AD `u:DOMAIN\name` → `sAMAccountName` match), falling back to the bind DN only for a DN template (GLAuth has no Who-am-I); otherwise `GroupLookupFailed`. `{0}` is RFC 4514-escaped in DN templates. Before the fix a user could sign in with another account's groups whenever the UPN/DN bind and the `UserNameAttribute` search named different accounts — reproduced live against a throwaway GLAuth (`tests/ZB.MOM.WW.Auth.Ldap.Tests/Integration/glauth-userbind/`, `ZB_LDAP_USERBIND_IT=1`, port 3897): pre-fix `mallory` signed in with `Admins`. **Consumer impact:** AD + down-level/UPN template unchanged for consistent accounts (BTDB Manager is the only user-bind consumer); non-AD user-bind needs a DN template that yields the entry's DN exactly as searched (GLAuth: `cn={0},ou=<group>,ou=users,<base>`). README §0.4.4.
+3 -1
View File
@@ -14,7 +14,9 @@
create/rotate; patched System.Security.Cryptography.Pkcs transitive pin (SqlServer package). -->
<!-- 0.5.0: passwordless group lookup — ILdapGroupLookup.GetUserGroupsAsync (service account; shares the
endpoint walk / sticky preference / TLS policy with AuthenticateAsync). Includes the unpublished 0.4.2–0.4.4. -->
<Version>0.5.0</Version>
<!-- 0.6.0: API-key last-used stamps batched per key per ApiKeyOptions.LastUsedWriteIntervalSeconds (default 60)
and written off the request path by ApiKeyUsageRecorder; ApiKeyVerifier is disposable (scadaproj#61). -->
<Version>0.6.0</Version>
<ManagePackageVersionsCentrally>true</ManagePackageVersionsCentrally>
</PropertyGroup>
+12 -1
View File
@@ -30,7 +30,18 @@ Authentication and authorisation libraries for the **ZB.MOM.WW SCADA family** (O
## Versioning
All five packages are versioned **lockstep** from `Directory.Build.props`. The current release is **0.5.0**. A single version bump in `Directory.Build.props` bumps all five packages simultaneously — consumers should reference the same version for all ZB.MOM.WW.Auth packages.
All five packages are versioned **lockstep** from `Directory.Build.props`. The current release is **0.5.0**; **0.6.0** is in source, not yet published. A single version bump in `Directory.Build.props` bumps all five packages simultaneously — consumers should reference the same version for all ZB.MOM.WW.Auth packages.
### 0.6.0 — batched API-key last-used writes, off the request path (scadaproj#61, unpublished)
Before 0.6.0 every successful `ApiKeyVerifier.VerifyAsync` awaited `IApiKeyStore.MarkUsedAsync`. On the SQLite store that is a fresh connection, the PRAGMAs and an `UPDATE` per RPC, serialised through SQLite's single write lock, and a held lock cost each RPC up to the 5 s busy timeout (historiangw#169, HOST-01).
- New `ApiKeyOptions.LastUsedWriteIntervalSeconds` (default **60**). A successful verification now only notes the use in memory (`ApiKeyUsageRecorder`). A background loop writes each used key's **latest** use time at most once per interval, and the last stamps are written when the verifier is disposed. `VerifyAsync` therefore does no store write: just the read and the HMAC compare.
- **`last_used_utc` is accurate to the interval.** It can lag the real last use by up to one interval. If the process dies without disposing the verifier, that final interval's stamps are lost. `0` restores the old inline, per-call write.
- A failed stamp never fails or delays verification. It is counted (`ApiKeyUsageRecorder.FailedWrites`, plus the `zb.auth.apikey.last_used.write_failures` counter on meter `ZB.MOM.WW.Auth.ApiKeys`) and logged at Warning through an optional `ILogger<ApiKeyUsageRecorder>`.
- `ApiKeyVerifier` is now `IAsyncDisposable`/`IDisposable`. `AddZbApiKeyAuth` lets the container own it, so host shutdown flushes the stamps. A consumer that constructs the verifier itself should dispose it. The constructor gains optional `TimeProvider` (already present) and `ILogger<ApiKeyUsageRecorder>` parameters, and `AddZbApiKeyAuth` takes a registered `TimeProvider` if there is one.
- **Behaviour change for consumers:** cancelling a request no longer cancels its last-used write. Tests that assert `MarkUsedAsync` was called right after `VerifyAsync` need `LastUsedWriteIntervalSeconds = 0`, or must dispose the verifier first.
- Not changed: the SQLite factory still opens a connection and re-runs the PRAGMAs per call. With roughly one write per key per minute this no longer matters.
### 0.5.0 — passwordless group lookup (`ILdapGroupLookup`, ScadaBridge#46)
@@ -6,6 +6,18 @@ public sealed record ApiKeyOptions
public string PepperSecretName { get; init; } = "";
public string SqlitePath { get; init; } = "";
public bool RunMigrationsOnStartup { get; init; } = true;
/// <summary>
/// How often, in seconds, a key's <c>last_used_utc</c> is written (scadaproj#61, since 0.6.0).
/// A successful verification only notes the use in memory; a background flush writes each used
/// key's latest use time at most once per interval, and once more when the verifier is disposed,
/// so <c>VerifyAsync</c> does no store write. <c>last_used_utc</c> is therefore accurate to this
/// interval (it can lag the real last use by up to one interval, and the uses of the final
/// interval are lost if the process dies without disposing the verifier).
/// <c>0</c> restores the pre-0.6.0 behaviour: one store write per successful verification,
/// awaited on the request path. Negative values are treated as <c>0</c>. Default 60.
/// </summary>
public int LastUsedWriteIntervalSeconds { get; init; } = 60;
}
/// <summary>Why an API-key verification failed. New values are only ever appended, so stored or logged numeric values keep their meaning.</summary>
@@ -0,0 +1,194 @@
using System.Collections.Concurrent;
using System.Diagnostics.Metrics;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
using ZB.MOM.WW.Auth.Abstractions.ApiKeys;
namespace ZB.MOM.WW.Auth.ApiKeys;
/// <summary>
/// Coalesces API-key "last used" stamps and writes them off the request path (scadaproj#61).
/// </summary>
/// <remarks>
/// <para>
/// <see cref="Record"/> only updates an in-memory map (key id → latest use time) and never touches
/// the store, so a verification is never slowed by the store's write lock, a slow fsync or a busy
/// timeout. A background loop, started on the first <see cref="Record"/>, calls
/// <see cref="IApiKeyStore.MarkUsedAsync"/> once per pending key every interval with the latest use
/// time seen for it; <see cref="DisposeAsync"/> stops the loop and writes whatever is still pending.
/// </para>
/// <para>
/// A failed write is never surfaced to a caller: it is counted (<see cref="FailedWrites"/> and the
/// <c>zb.auth.apikey.last_used.write_failures</c> counter on the <c>ZB.MOM.WW.Auth.ApiKeys</c> meter)
/// and logged at Warning, and the stamp is dropped (the next use of the key queues a fresh one).
/// </para>
/// </remarks>
public sealed class ApiKeyUsageRecorder : IAsyncDisposable, IDisposable
{
/// <summary>Name of the <see cref="Meter"/> this type reports on.</summary>
public const string MeterName = "ZB.MOM.WW.Auth.ApiKeys";
private static readonly Meter Meter = new(MeterName);
private static readonly Counter<long> WriteFailuresCounter =
Meter.CreateCounter<long>("zb.auth.apikey.last_used.write_failures", description:
"API-key last-used writes that failed (the verification itself succeeded).");
private readonly IApiKeyStore _store;
private readonly TimeSpan _interval;
private readonly TimeProvider _timeProvider;
private readonly ILogger _logger;
private readonly ConcurrentDictionary<string, DateTimeOffset> _pending = new(StringComparer.Ordinal);
private readonly SemaphoreSlim _flushGate = new(1, 1);
private readonly CancellationTokenSource _stopping = new();
private readonly object _startLock = new();
private Task? _loop;
private long _failedWrites;
private long _completedWrites;
private int _disposed;
/// <summary>Creates a recorder that flushes to <paramref name="store"/> every <paramref name="interval"/>.</summary>
/// <param name="store">The store whose <see cref="IApiKeyStore.MarkUsedAsync"/> receives the stamps.</param>
/// <param name="interval">Flush period; must be positive.</param>
/// <param name="timeProvider">Clock for the flush timer; defaults to <see cref="TimeProvider.System"/>.</param>
/// <param name="logger">Receives a Warning per failed write; optional.</param>
public ApiKeyUsageRecorder(
IApiKeyStore store,
TimeSpan interval,
TimeProvider? timeProvider = null,
ILogger<ApiKeyUsageRecorder>? logger = null)
{
ArgumentNullException.ThrowIfNull(store);
ArgumentOutOfRangeException.ThrowIfLessThanOrEqual(interval, TimeSpan.Zero);
_store = store;
_interval = interval;
_timeProvider = timeProvider ?? TimeProvider.System;
_logger = (ILogger?)logger ?? NullLogger.Instance;
}
/// <summary>Number of last-used writes that failed since this recorder was created.</summary>
public long FailedWrites => Interlocked.Read(ref _failedWrites);
/// <summary>Number of last-used writes that completed since this recorder was created.</summary>
public long CompletedWrites => Interlocked.Read(ref _completedWrites);
/// <summary>Number of keys with a stamp waiting for the next flush.</summary>
public int PendingCount => _pending.Count;
/// <summary>
/// Notes that <paramref name="keyId"/> was used at <paramref name="whenUtc"/>. Never blocks on and
/// never throws from the store. Ignored once the recorder is disposed.
/// </summary>
public void Record(string keyId, DateTimeOffset whenUtc)
{
ArgumentException.ThrowIfNullOrWhiteSpace(keyId);
if (Volatile.Read(ref _disposed) != 0)
{
return;
}
_pending.AddOrUpdate(keyId, whenUtc, (_, existing) => whenUtc > existing ? whenUtc : existing);
EnsureStarted();
}
/// <summary>
/// Writes every pending stamp now. The background loop calls this each interval; hosts and tests
/// may call it directly. Write failures are counted and logged, never thrown.
/// </summary>
public async Task FlushAsync(CancellationToken ct = default)
{
await _flushGate.WaitAsync(ct).ConfigureAwait(false);
try
{
foreach (string keyId in _pending.Keys)
{
if (!_pending.TryRemove(keyId, out DateTimeOffset whenUtc))
{
continue;
}
try
{
await _store.MarkUsedAsync(keyId, whenUtc, ct).ConfigureAwait(false);
Interlocked.Increment(ref _completedWrites);
}
catch (OperationCanceledException) when (ct.IsCancellationRequested)
{
// Put the stamp back (unless a newer one arrived) so a final flush can still write it.
_pending.AddOrUpdate(keyId, whenUtc, (_, existing) => existing > whenUtc ? existing : whenUtc);
throw;
}
catch (Exception ex)
{
Interlocked.Increment(ref _failedWrites);
WriteFailuresCounter.Add(1);
_logger.LogWarning(ex,
"API key {KeyId}: last-used write failed; verification was not affected", keyId);
}
}
}
finally
{
_flushGate.Release();
}
}
private void EnsureStarted()
{
if (Volatile.Read(ref _loop) is not null)
{
return;
}
lock (_startLock)
{
if (_loop is null && Volatile.Read(ref _disposed) == 0)
{
Volatile.Write(ref _loop, Task.Run(RunAsync));
}
}
}
private async Task RunAsync()
{
using PeriodicTimer timer = new(_interval, _timeProvider);
try
{
while (await timer.WaitForNextTickAsync(_stopping.Token).ConfigureAwait(false))
{
await FlushAsync(_stopping.Token).ConfigureAwait(false);
}
}
catch (OperationCanceledException) when (_stopping.IsCancellationRequested)
{
// Disposal; the final flush happens in DisposeAsync.
}
}
/// <summary>Stops the background loop and writes every pending stamp.</summary>
public async ValueTask DisposeAsync()
{
if (Interlocked.Exchange(ref _disposed, 1) != 0)
{
return;
}
Task? loop;
lock (_startLock)
{
loop = _loop;
}
await _stopping.CancelAsync().ConfigureAwait(false);
if (loop is not null)
{
await loop.ConfigureAwait(false);
}
await FlushAsync(CancellationToken.None).ConfigureAwait(false);
_stopping.Dispose();
}
/// <summary>Synchronous counterpart of <see cref="DisposeAsync"/>; blocks until the final flush completes.</summary>
public void Dispose() => DisposeAsync().AsTask().GetAwaiter().GetResult();
}
@@ -1,3 +1,4 @@
using Microsoft.Extensions.Logging;
using ZB.MOM.WW.Auth.Abstractions.ApiKeys;
namespace ZB.MOM.WW.Auth.ApiKeys;
@@ -11,17 +12,55 @@ namespace ZB.MOM.WW.Auth.ApiKeys;
/// The failure reason is discriminated for the caller/audit pipeline, but the verifier returns a
/// structured result rather than throwing (the caller decides the opaque client-facing message).
/// The only exception path is cancellation: a key-store lookup that faults is reported as
/// <see cref="ApiKeyFailure.StoreUnavailable"/> (since 0.4.4), and a failed last-used write is ignored. A successful identity carries the key's scopes and the
/// <see cref="ApiKeyFailure.StoreUnavailable"/> (since 0.4.4), and a failed last-used write never fails the verification. A successful identity carries the key's scopes and the
/// opaque <c>ConstraintsJson</c> blob (which the verifier does not interpret); it never carries the
/// presented secret, the pepper, or the stored secret hash.
/// <para>
/// Last-used bookkeeping (scadaproj#61, since 0.6.0): with
/// <see cref="ApiKeyOptions.LastUsedWriteIntervalSeconds"/> &gt; 0 (the default, 60) a successful
/// verification hands the stamp to an <see cref="ApiKeyUsageRecorder"/> and returns without any store
/// write; the recorder writes each key's latest use at most once per interval and on disposal. Dispose
/// the verifier (the DI container does) to flush the last interval. With the interval at 0 the stamp
/// is written inline, as before 0.6.0.
/// </para>
/// </remarks>
public sealed class ApiKeyVerifier(
ApiKeyOptions options,
IApiKeyStore store,
IApiKeyPepperProvider pepperProvider,
TimeProvider? timeProvider = null) : IApiKeyVerifier
public sealed class ApiKeyVerifier : IApiKeyVerifier, IAsyncDisposable, IDisposable
{
private readonly TimeProvider _timeProvider = timeProvider ?? TimeProvider.System;
private readonly ApiKeyOptions options;
private readonly IApiKeyStore store;
private readonly IApiKeyPepperProvider pepperProvider;
private readonly TimeProvider _timeProvider;
private readonly ApiKeyUsageRecorder? _usageRecorder;
/// <summary>Creates a verifier.</summary>
/// <param name="options">Token prefix and the last-used write interval.</param>
/// <param name="store">The key store.</param>
/// <param name="pepperProvider">Supplies the HMAC pepper.</param>
/// <param name="timeProvider">Clock for expiry, last-used stamps and the flush timer.</param>
/// <param name="usageRecorderLogger">Logger for failed last-used writes; optional.</param>
public ApiKeyVerifier(
ApiKeyOptions options,
IApiKeyStore store,
IApiKeyPepperProvider pepperProvider,
TimeProvider? timeProvider = null,
ILogger<ApiKeyUsageRecorder>? usageRecorderLogger = null)
{
ArgumentNullException.ThrowIfNull(options);
ArgumentNullException.ThrowIfNull(store);
ArgumentNullException.ThrowIfNull(pepperProvider);
this.options = options;
this.store = store;
this.pepperProvider = pepperProvider;
_timeProvider = timeProvider ?? TimeProvider.System;
if (options.LastUsedWriteIntervalSeconds > 0)
{
_usageRecorder = new ApiKeyUsageRecorder(
store, TimeSpan.FromSeconds(options.LastUsedWriteIntervalSeconds), _timeProvider, usageRecorderLogger);
}
}
/// <summary>The recorder that batches last-used writes, or <c>null</c> when they are written inline.</summary>
public ApiKeyUsageRecorder? UsageRecorder => _usageRecorder;
/// <inheritdoc />
public async Task<ApiKeyVerification> VerifyAsync(string authorizationHeader, CancellationToken ct)
@@ -88,7 +127,15 @@ public sealed class ApiKeyVerifier(
return Fail(ApiKeyFailure.SecretMismatch);
}
// 6. The authentication decision is already made (line 60). Recording last-used is
// 6. The authentication decision is already made. With a write interval the stamp is only
// noted in memory (no store I/O on the request path; scadaproj#61).
if (_usageRecorder is not null)
{
_usageRecorder.Record(record.KeyId, _timeProvider.GetUtcNow());
return Success(record);
}
// Interval 0: the pre-0.6.0 inline write. Recording last-used is
// best-effort bookkeeping: a transient storage hiccup (SQLITE_BUSY past the busy-timeout,
// disk full, DB locked by a migration) must NOT turn an otherwise-valid credential into a
// failed auth. Swallow any non-cancellation failure so the only exception path remains
@@ -107,11 +154,19 @@ public sealed class ApiKeyVerifier(
// bookkeeping (not the auth decision) rather than denying a legitimate caller.
}
return new ApiKeyVerification(
Succeeded: true,
Identity: new ApiKeyIdentity(record.KeyId, record.DisplayName, record.Scopes, record.ConstraintsJson),
Failure: null);
return Success(record);
}
/// <summary>Flushes pending last-used stamps and stops the background writer.</summary>
public ValueTask DisposeAsync() => _usageRecorder?.DisposeAsync() ?? ValueTask.CompletedTask;
/// <summary>Synchronous counterpart of <see cref="DisposeAsync"/>.</summary>
public void Dispose() => _usageRecorder?.Dispose();
private static ApiKeyVerification Success(ApiKeyRecord record) => new(
Succeeded: true,
Identity: new ApiKeyIdentity(record.KeyId, record.DisplayName, record.Scopes, record.ConstraintsJson),
Failure: null);
private static ApiKeyVerification Fail(ApiKeyFailure failure) => new(false, null, failure);
}
@@ -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
@@ -19,6 +19,8 @@
<PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" />
<PackageReference Include="Microsoft.Extensions.Configuration.Abstractions" />
<PackageReference Include="Microsoft.Extensions.Hosting.Abstractions" />
<!-- ILogger for ApiKeyUsageRecorder's failed last-used writes (optional; a null logger is fine). -->
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" />
</ItemGroup>
<PropertyGroup>
@@ -0,0 +1,234 @@
using System.Collections.Concurrent;
using ZB.MOM.WW.Auth.Abstractions.ApiKeys;
namespace ZB.MOM.WW.Auth.ApiKeys.Tests;
/// <summary>
/// scadaproj#61: last-used stamps are batched (at most one write per key per interval) and written
/// off the request path, so verification never waits on the store's write lock.
/// </summary>
public class ApiKeyUsageRecorderTests
{
private const string TokenPrefix = "mxgw";
private const string Pepper = "test-pepper";
private const string Secret = "supersecretvalue";
private static readonly TimeSpan Generous = TimeSpan.FromSeconds(10);
private static string Header(string keyId) => $"{TokenPrefix}_{keyId}_{Secret}";
private static ApiKeyRecord Record(string keyId) => new(
KeyId: keyId, KeyPrefix: TokenPrefix, SecretHash: ApiKeySecretHasher.Hash(Secret, Pepper),
DisplayName: keyId, Scopes: new HashSet<string>(), ConstraintsJson: null,
CreatedUtc: DateTimeOffset.UnixEpoch, LastUsedUtc: null, RevokedUtc: null, ExpiresUtc: null);
private static ApiKeyVerifier Verifier(RecordingStore store, int intervalSeconds = 60, TimeProvider? clock = null) =>
new(new ApiKeyOptions { TokenPrefix = TokenPrefix, LastUsedWriteIntervalSeconds = intervalSeconds },
store, new Pepper_(), clock);
[Fact]
public void DefaultOptions_BatchLastUsed_EveryMinute()
{
Assert.Equal(60, new ApiKeyOptions().LastUsedWriteIntervalSeconds);
using var verifier = Verifier(new RecordingStore("k1"));
Assert.NotNull(verifier.UsageRecorder);
}
[Fact]
public async Task ManyVerificationsWithinInterval_WriteOnce_WithTheLatestUseTime()
{
var store = new RecordingStore("k1");
var clock = new SteppingClock(new DateTimeOffset(2026, 12, 5, 8, 0, 0, TimeSpan.Zero));
await using var verifier = Verifier(store, clock: clock);
for (int i = 0; i < 50; i++)
{
clock.Advance(TimeSpan.FromMilliseconds(100));
Assert.True((await verifier.VerifyAsync(Header("k1"), CancellationToken.None)).Succeeded);
}
Assert.Empty(store.Writes); // nothing written on the request path
await verifier.UsageRecorder!.FlushAsync();
var write = Assert.Single(store.Writes);
Assert.Equal("k1", write.KeyId);
Assert.Equal(clock.GetUtcNow(), write.WhenUtc);
}
[Fact]
public async Task EachKeyGetsItsOwnStamp()
{
var store = new RecordingStore("k1", "k2");
await using var verifier = Verifier(store);
for (int i = 0; i < 5; i++)
{
await verifier.VerifyAsync(Header("k1"), CancellationToken.None);
await verifier.VerifyAsync(Header("k2"), CancellationToken.None);
}
await verifier.UsageRecorder!.FlushAsync();
Assert.Equal(["k1", "k2"], store.Writes.Select(w => w.KeyId).Order());
}
[Fact]
public async Task VerificationDoesNotWaitForABlockedWrite()
{
// Stands in for a store whose write lock is held (CLI key create, slow fsync, busy timeout).
var store = new RecordingStore("k1") { WriteGate = new TaskCompletionSource() };
var verifier = Verifier(store);
await verifier.VerifyAsync(Header("k1"), CancellationToken.None).WaitAsync(Generous);
Task flush = verifier.UsageRecorder!.FlushAsync(); // now stuck inside MarkUsedAsync
await store.WriteStarted.Task.WaitAsync(Generous);
// Further verifications complete while the write is still blocked.
for (int i = 0; i < 20; i++)
{
ApiKeyVerification result = await verifier.VerifyAsync(Header("k1"), CancellationToken.None)
.WaitAsync(Generous);
Assert.True(result.Succeeded);
}
Assert.False(flush.IsCompleted);
store.WriteGate.SetResult();
await flush.WaitAsync(Generous);
await verifier.DisposeAsync();
// The blocked stamp plus the one queued behind it.
Assert.Equal(2, store.Writes.Count);
}
[Fact]
public async Task FailedStamp_DoesNotFailVerification_AndIsCounted()
{
var store = new RecordingStore("k1") { WriteException = new InvalidOperationException("SQLITE_BUSY") };
await using var verifier = Verifier(store);
Assert.True((await verifier.VerifyAsync(Header("k1"), CancellationToken.None)).Succeeded);
await verifier.UsageRecorder!.FlushAsync();
Assert.Equal(1, verifier.UsageRecorder.FailedWrites);
Assert.Equal(0, verifier.UsageRecorder.CompletedWrites);
Assert.Equal(0, verifier.UsageRecorder.PendingCount);
}
[Fact]
public async Task PendingStamps_AreFlushedOnDispose()
{
var store = new RecordingStore("k1", "k2");
var verifier = Verifier(store);
await verifier.VerifyAsync(Header("k1"), CancellationToken.None);
await verifier.VerifyAsync(Header("k2"), CancellationToken.None);
Assert.Empty(store.Writes);
await verifier.DisposeAsync();
Assert.Equal(2, store.Writes.Count);
}
[Fact]
public async Task SyncDispose_AlsoFlushes()
{
var store = new RecordingStore("k1");
var verifier = Verifier(store);
await verifier.VerifyAsync(Header("k1"), CancellationToken.None);
verifier.Dispose();
Assert.Single(store.Writes);
}
[Fact]
public async Task BackgroundLoop_FlushesEachInterval()
{
var store = new RecordingStore("k1");
await using var verifier = Verifier(store, intervalSeconds: 1);
await verifier.VerifyAsync(Header("k1"), CancellationToken.None);
await store.WriteStarted.Task.WaitAsync(Generous); // written by the timer, not by dispose
Assert.Single(store.Writes);
}
[Fact]
public async Task RecordAfterDispose_IsIgnored()
{
var store = new RecordingStore("k1");
var recorder = new ApiKeyUsageRecorder(store, TimeSpan.FromMinutes(1));
await recorder.DisposeAsync();
recorder.Record("k1", DateTimeOffset.UtcNow);
Assert.Equal(0, recorder.PendingCount);
Assert.Empty(store.Writes);
}
[Fact]
public async Task IntervalZero_WritesInline()
{
var store = new RecordingStore("k1");
await using var verifier = Verifier(store, intervalSeconds: 0);
Assert.Null(verifier.UsageRecorder);
await verifier.VerifyAsync(Header("k1"), CancellationToken.None);
Assert.Single(store.Writes);
}
[Fact]
public void Recorder_RejectsNonPositiveInterval()
{
Assert.Throws<ArgumentOutOfRangeException>(
() => new ApiKeyUsageRecorder(new RecordingStore(), TimeSpan.Zero));
}
private sealed class Pepper_ : IApiKeyPepperProvider
{
public string? GetPepper() => Pepper;
}
private sealed class SteppingClock(DateTimeOffset start) : TimeProvider
{
private DateTimeOffset _now = start;
public void Advance(TimeSpan by) => _now += by;
public override DateTimeOffset GetUtcNow() => _now;
}
private sealed class RecordingStore(params string[] keyIds) : IApiKeyStore
{
private readonly ConcurrentQueue<(string KeyId, DateTimeOffset WhenUtc)> _writes = new();
public IReadOnlyList<(string KeyId, DateTimeOffset WhenUtc)> Writes => _writes.ToArray();
public TaskCompletionSource? WriteGate { get; init; }
public Exception? WriteException { get; init; }
public TaskCompletionSource WriteStarted { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
public Task<ApiKeyRecord?> FindByKeyIdAsync(string keyId, CancellationToken ct) =>
Task.FromResult(keyIds.Contains(keyId) ? Record(keyId) : null);
public Task<ApiKeyRecord?> FindActiveByKeyIdAsync(string keyId, CancellationToken ct) =>
FindByKeyIdAsync(keyId, ct);
public async Task MarkUsedAsync(string keyId, DateTimeOffset whenUtc, CancellationToken ct)
{
WriteStarted.TrySetResult();
if (WriteGate is not null)
{
await WriteGate.Task.ConfigureAwait(false);
}
if (WriteException is not null)
{
throw WriteException;
}
_writes.Enqueue((keyId, whenUtc));
}
}
}
@@ -33,10 +33,14 @@ public class ApiKeyVerifierTests
RevokedUtc: revokedUtc,
ExpiresUtc: expiresUtc);
// These tests pin the verification pipeline with the inline (pre-0.6.0) last-used write so each
// assertion on MarkUsedCalled is immediate; the batched path is covered by ApiKeyUsageRecorderTests.
private static ApiKeyOptions InlineOptions => new() { TokenPrefix = TokenPrefix, LastUsedWriteIntervalSeconds = 0 };
private static ApiKeyVerifier BuildVerifier(
FakeApiKeyStore store,
FakePepperProvider pepperProvider) =>
new(new ApiKeyOptions { TokenPrefix = TokenPrefix }, store, pepperProvider);
new(InlineOptions, store, pepperProvider);
// --- MissingOrMalformed ---
@@ -134,7 +138,7 @@ public class ApiKeyVerifierTests
private static ApiKeyVerifier BuildVerifierAt(
FakeApiKeyStore store, DateTimeOffset now) =>
new(new ApiKeyOptions { TokenPrefix = TokenPrefix },
new(InlineOptions,
store,
new FakePepperProvider(Pepper),
new FakeTimeProvider(now));
@@ -283,7 +287,7 @@ public class ApiKeyVerifierTests
var store = new FakeApiKeyStore { Record = BuildRecord(hash) };
var fakeTime = new FakeTimeProvider(new DateTimeOffset(2026, 1, 2, 3, 4, 5, TimeSpan.Zero));
var verifier = new ApiKeyVerifier(
new ApiKeyOptions { TokenPrefix = TokenPrefix },
InlineOptions,
store,
new FakePepperProvider(Pepper),
fakeTime);