Files
scadaproj/ZB.MOM.WW.Auth/tests/ZB.MOM.WW.Auth.ApiKeys.Tests/ApiKeyUsageRecorderTests.cs
T
Joseph Doherty 2e52a02b85 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.
2026-12-05 01:10:31 -05:00

235 lines
8.2 KiB
C#

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