From 2e52a02b8587583b9fb601fe2a08c1cfa773d05b Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Sat, 5 Dec 2026 01:10:31 -0500 Subject: [PATCH] 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. --- ZB.MOM.WW.Auth/CLAUDE.md | 2 + ZB.MOM.WW.Auth/Directory.Build.props | 4 +- ZB.MOM.WW.Auth/README.md | 13 +- .../ApiKeys/ApiKeyContracts.cs | 12 + .../ApiKeyUsageRecorder.cs | 194 +++++++++++++++ .../ZB.MOM.WW.Auth.ApiKeys/ApiKeyVerifier.cs | 79 +++++- .../ApiKeyServiceCollectionExtensions.cs | 7 +- .../ZB.MOM.WW.Auth.ApiKeys.csproj | 2 + .../ApiKeyUsageRecorderTests.cs | 234 ++++++++++++++++++ .../ApiKeyVerifierTests.cs | 10 +- 10 files changed, 539 insertions(+), 18 deletions(-) create mode 100644 ZB.MOM.WW.Auth/src/ZB.MOM.WW.Auth.ApiKeys/ApiKeyUsageRecorder.cs create mode 100644 ZB.MOM.WW.Auth/tests/ZB.MOM.WW.Auth.ApiKeys.Tests/ApiKeyUsageRecorderTests.cs diff --git a/ZB.MOM.WW.Auth/CLAUDE.md b/ZB.MOM.WW.Auth/CLAUDE.md index 822e57c..82a2331 100644 --- a/ZB.MOM.WW.Auth/CLAUDE.md +++ b/ZB.MOM.WW.Auth/CLAUDE.md @@ -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 ''` 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` 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=,ou=users,`). README §0.4.4. diff --git a/ZB.MOM.WW.Auth/Directory.Build.props b/ZB.MOM.WW.Auth/Directory.Build.props index 533b8e2..ddb0b69 100644 --- a/ZB.MOM.WW.Auth/Directory.Build.props +++ b/ZB.MOM.WW.Auth/Directory.Build.props @@ -14,7 +14,9 @@ create/rotate; patched System.Security.Cryptography.Pkcs transitive pin (SqlServer package). --> - 0.5.0 + + 0.6.0 true diff --git a/ZB.MOM.WW.Auth/README.md b/ZB.MOM.WW.Auth/README.md index cb4f2c5..c305413 100644 --- a/ZB.MOM.WW.Auth/README.md +++ b/ZB.MOM.WW.Auth/README.md @@ -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`. +- `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` 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) diff --git a/ZB.MOM.WW.Auth/src/ZB.MOM.WW.Auth.Abstractions/ApiKeys/ApiKeyContracts.cs b/ZB.MOM.WW.Auth/src/ZB.MOM.WW.Auth.Abstractions/ApiKeys/ApiKeyContracts.cs index f2a803f..e49f6d1 100644 --- a/ZB.MOM.WW.Auth/src/ZB.MOM.WW.Auth.Abstractions/ApiKeys/ApiKeyContracts.cs +++ b/ZB.MOM.WW.Auth/src/ZB.MOM.WW.Auth.Abstractions/ApiKeys/ApiKeyContracts.cs @@ -6,6 +6,18 @@ public sealed record ApiKeyOptions public string PepperSecretName { get; init; } = ""; public string SqlitePath { get; init; } = ""; public bool RunMigrationsOnStartup { get; init; } = true; + + /// + /// How often, in seconds, a key's last_used_utc 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 VerifyAsync does no store write. last_used_utc 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). + /// 0 restores the pre-0.6.0 behaviour: one store write per successful verification, + /// awaited on the request path. Negative values are treated as 0. Default 60. + /// + public int LastUsedWriteIntervalSeconds { get; init; } = 60; } /// Why an API-key verification failed. New values are only ever appended, so stored or logged numeric values keep their meaning. diff --git a/ZB.MOM.WW.Auth/src/ZB.MOM.WW.Auth.ApiKeys/ApiKeyUsageRecorder.cs b/ZB.MOM.WW.Auth/src/ZB.MOM.WW.Auth.ApiKeys/ApiKeyUsageRecorder.cs new file mode 100644 index 0000000..d53d544 --- /dev/null +++ b/ZB.MOM.WW.Auth/src/ZB.MOM.WW.Auth.ApiKeys/ApiKeyUsageRecorder.cs @@ -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; + +/// +/// Coalesces API-key "last used" stamps and writes them off the request path (scadaproj#61). +/// +/// +/// +/// 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 , calls +/// once per pending key every interval with the latest use +/// time seen for it; stops the loop and writes whatever is still pending. +/// +/// +/// A failed write is never surfaced to a caller: it is counted ( and the +/// zb.auth.apikey.last_used.write_failures counter on the ZB.MOM.WW.Auth.ApiKeys meter) +/// and logged at Warning, and the stamp is dropped (the next use of the key queues a fresh one). +/// +/// +public sealed class ApiKeyUsageRecorder : IAsyncDisposable, IDisposable +{ + /// Name of the this type reports on. + public const string MeterName = "ZB.MOM.WW.Auth.ApiKeys"; + + private static readonly Meter Meter = new(MeterName); + + private static readonly Counter WriteFailuresCounter = + Meter.CreateCounter("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 _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; + + /// Creates a recorder that flushes to every . + /// The store whose receives the stamps. + /// Flush period; must be positive. + /// Clock for the flush timer; defaults to . + /// Receives a Warning per failed write; optional. + public ApiKeyUsageRecorder( + IApiKeyStore store, + TimeSpan interval, + TimeProvider? timeProvider = null, + ILogger? logger = null) + { + ArgumentNullException.ThrowIfNull(store); + ArgumentOutOfRangeException.ThrowIfLessThanOrEqual(interval, TimeSpan.Zero); + _store = store; + _interval = interval; + _timeProvider = timeProvider ?? TimeProvider.System; + _logger = (ILogger?)logger ?? NullLogger.Instance; + } + + /// Number of last-used writes that failed since this recorder was created. + public long FailedWrites => Interlocked.Read(ref _failedWrites); + + /// Number of last-used writes that completed since this recorder was created. + public long CompletedWrites => Interlocked.Read(ref _completedWrites); + + /// Number of keys with a stamp waiting for the next flush. + public int PendingCount => _pending.Count; + + /// + /// Notes that was used at . Never blocks on and + /// never throws from the store. Ignored once the recorder is disposed. + /// + 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(); + } + + /// + /// 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. + /// + 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. + } + } + + /// Stops the background loop and writes every pending stamp. + 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(); + } + + /// Synchronous counterpart of ; blocks until the final flush completes. + public void Dispose() => DisposeAsync().AsTask().GetAwaiter().GetResult(); +} diff --git a/ZB.MOM.WW.Auth/src/ZB.MOM.WW.Auth.ApiKeys/ApiKeyVerifier.cs b/ZB.MOM.WW.Auth/src/ZB.MOM.WW.Auth.ApiKeys/ApiKeyVerifier.cs index c17d825..8a29a0d 100644 --- a/ZB.MOM.WW.Auth/src/ZB.MOM.WW.Auth.ApiKeys/ApiKeyVerifier.cs +++ b/ZB.MOM.WW.Auth/src/ZB.MOM.WW.Auth.ApiKeys/ApiKeyVerifier.cs @@ -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 -/// (since 0.4.4), and a failed last-used write is ignored. A successful identity carries the key's scopes and the +/// (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 ConstraintsJson blob (which the verifier does not interpret); it never carries the /// presented secret, the pepper, or the stored secret hash. +/// +/// Last-used bookkeeping (scadaproj#61, since 0.6.0): with +/// > 0 (the default, 60) a successful +/// verification hands the stamp to an 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. +/// /// -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; + + /// Creates a verifier. + /// Token prefix and the last-used write interval. + /// The key store. + /// Supplies the HMAC pepper. + /// Clock for expiry, last-used stamps and the flush timer. + /// Logger for failed last-used writes; optional. + public ApiKeyVerifier( + ApiKeyOptions options, + IApiKeyStore store, + IApiKeyPepperProvider pepperProvider, + TimeProvider? timeProvider = null, + ILogger? 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); + } + } + + /// The recorder that batches last-used writes, or null when they are written inline. + public ApiKeyUsageRecorder? UsageRecorder => _usageRecorder; /// public async Task 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); } + /// Flushes pending last-used stamps and stops the background writer. + public ValueTask DisposeAsync() => _usageRecorder?.DisposeAsync() ?? ValueTask.CompletedTask; + + /// Synchronous counterpart of . + 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); } diff --git a/ZB.MOM.WW.Auth/src/ZB.MOM.WW.Auth.ApiKeys/DependencyInjection/ApiKeyServiceCollectionExtensions.cs b/ZB.MOM.WW.Auth/src/ZB.MOM.WW.Auth.ApiKeys/DependencyInjection/ApiKeyServiceCollectionExtensions.cs index 092cee1..2231a28 100644 --- a/ZB.MOM.WW.Auth/src/ZB.MOM.WW.Auth.ApiKeys/DependencyInjection/ApiKeyServiceCollectionExtensions.cs +++ b/ZB.MOM.WW.Auth/src/ZB.MOM.WW.Auth.ApiKeys/DependencyInjection/ApiKeyServiceCollectionExtensions.cs @@ -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(sp => new SqliteApiKeyAuditStore(sp.GetRequiredService())); + // 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(sp => new ApiKeyVerifier( sp.GetRequiredService>().Value, sp.GetRequiredService(), - sp.GetRequiredService())); + sp.GetRequiredService(), + sp.GetService(), + sp.GetService>())); // 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 diff --git a/ZB.MOM.WW.Auth/src/ZB.MOM.WW.Auth.ApiKeys/ZB.MOM.WW.Auth.ApiKeys.csproj b/ZB.MOM.WW.Auth/src/ZB.MOM.WW.Auth.ApiKeys/ZB.MOM.WW.Auth.ApiKeys.csproj index 91517a5..7443aba 100644 --- a/ZB.MOM.WW.Auth/src/ZB.MOM.WW.Auth.ApiKeys/ZB.MOM.WW.Auth.ApiKeys.csproj +++ b/ZB.MOM.WW.Auth/src/ZB.MOM.WW.Auth.ApiKeys/ZB.MOM.WW.Auth.ApiKeys.csproj @@ -19,6 +19,8 @@ + + diff --git a/ZB.MOM.WW.Auth/tests/ZB.MOM.WW.Auth.ApiKeys.Tests/ApiKeyUsageRecorderTests.cs b/ZB.MOM.WW.Auth/tests/ZB.MOM.WW.Auth.ApiKeys.Tests/ApiKeyUsageRecorderTests.cs new file mode 100644 index 0000000..fe28eb7 --- /dev/null +++ b/ZB.MOM.WW.Auth/tests/ZB.MOM.WW.Auth.ApiKeys.Tests/ApiKeyUsageRecorderTests.cs @@ -0,0 +1,234 @@ +using System.Collections.Concurrent; +using ZB.MOM.WW.Auth.Abstractions.ApiKeys; + +namespace ZB.MOM.WW.Auth.ApiKeys.Tests; + +/// +/// 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. +/// +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(), 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( + () => 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 FindByKeyIdAsync(string keyId, CancellationToken ct) => + Task.FromResult(keyIds.Contains(keyId) ? Record(keyId) : null); + + public Task 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)); + } + } +} diff --git a/ZB.MOM.WW.Auth/tests/ZB.MOM.WW.Auth.ApiKeys.Tests/ApiKeyVerifierTests.cs b/ZB.MOM.WW.Auth/tests/ZB.MOM.WW.Auth.ApiKeys.Tests/ApiKeyVerifierTests.cs index c0be807..da001d6 100644 --- a/ZB.MOM.WW.Auth/tests/ZB.MOM.WW.Auth.ApiKeys.Tests/ApiKeyVerifierTests.cs +++ b/ZB.MOM.WW.Auth/tests/ZB.MOM.WW.Auth.ApiKeys.Tests/ApiKeyVerifierTests.cs @@ -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);