perf(auth): hash the cache key from a stack buffer and reuse the mapped identity on cache hits (SEC-012, #256)

This commit is contained in:
Joseph Doherty
2026-12-03 09:45:46 -05:00
parent 3f9ea6a86c
commit 7ec4c20239
3 changed files with 82 additions and 4 deletions
@@ -1,3 +1,4 @@
using System.Buffers;
using System.Collections.Concurrent;
using System.Security.Cryptography;
using System.Text;
@@ -442,8 +443,35 @@ public sealed class CachingApiKeyVerifier : IApiKeyVerifier, IApiKeyCacheInvalid
return false;
}
byte[] hash = SHA256.HashData(Encoding.UTF8.GetBytes(token.ToString()));
cacheKey = CacheKeyPrefix + Convert.ToHexString(hash);
return true;
// Hashed from a stack buffer straight off the header span: this runs on every authenticated
// RPC, so the per-call token string, UTF-8 array, hash array and hex string are avoided;
// the only allocation left is the cache key itself.
const int StackLimit = 512;
int byteCount = Encoding.UTF8.GetByteCount(token);
byte[]? rented = null;
Span<byte> utf8 = byteCount <= StackLimit
? stackalloc byte[StackLimit]
: (rented = ArrayPool<byte>.Shared.Rent(byteCount));
try
{
int written = Encoding.UTF8.GetBytes(token, utf8);
Span<byte> hash = stackalloc byte[SHA256.HashSizeInBytes];
SHA256.HashData(utf8[..written], hash);
Span<char> chars = stackalloc char[CacheKeyPrefix.Length + (SHA256.HashSizeInBytes * 2)];
CacheKeyPrefix.AsSpan().CopyTo(chars);
Convert.TryToHexString(hash, chars[CacheKeyPrefix.Length..], out _);
cacheKey = new string(chars);
return true;
}
finally
{
// The buffer held the bearer token; clear it before it is reused or left on the stack.
CryptographicOperations.ZeroMemory(utf8[..byteCount]);
if (rented is not null)
{
ArrayPool<byte>.Shared.Return(rented);
}
}
}
}
@@ -1,4 +1,5 @@
using System.Collections.Concurrent;
using System.Runtime.CompilerServices;
using LibApiKeyIdentity = ZB.MOM.WW.Auth.Abstractions.ApiKeys.ApiKeyIdentity;
@@ -45,6 +46,14 @@ public static class GatewayApiKeyIdentityMapper
private static readonly ConcurrentQueue<string> InsertionOrder = new();
private static readonly object EvictionLock = new();
/// <summary>
/// Mapped gateway identity per shared-library identity instance. The caching verifier hands
/// back the same library identity for every RPC inside its TTL, so the mapping (and its
/// record allocation) is done once per cached verification instead of once per RPC. The
/// table is weak, so an identity that ages out of the verifier cache takes its mapping with it.
/// </summary>
private static readonly ConditionalWeakTable<LibApiKeyIdentity, ApiKeyIdentity> MappedIdentities = new();
/// <summary>Current cache size, exposed for tests asserting the cap is honoured.</summary>
internal static int CurrentCacheSize => ConstraintCache.Count;
@@ -103,11 +112,16 @@ public static class GatewayApiKeyIdentityMapper
{
ArgumentNullException.ThrowIfNull(identity);
if (MappedIdentities.TryGetValue(identity, out ApiKeyIdentity? mapped))
{
return mapped;
}
// The library stores the opaque constraints blob in Constraints as the ConstraintsJson
// string (or null when the key has no constraints).
string? constraintsJson = identity.Constraints as string;
return new ApiKeyIdentity(
ApiKeyIdentity created = new(
KeyId: identity.KeyId,
// The gateway token prefix is fixed ("mxgw"); the key id is its own field. KeyPrefix
// is retained only for surface compatibility with the gateway identity record.
@@ -115,5 +129,8 @@ public static class GatewayApiKeyIdentityMapper
DisplayName: identity.DisplayName,
Scopes: identity.Scopes,
Constraints: DeserializeConstraints(constraintsJson));
// GetValue-style race: two racers may both build one; both are equivalent, keep the winner.
return MappedIdentities.GetValue(identity, _ => created);
}
}
@@ -37,6 +37,39 @@ public sealed class CachingApiKeyVerifierTests
Assert.Equal(1, inner.CallCount);
}
/// <summary>
/// SEC-012: the cache key is hashed from a stack buffer for tokens up to 512 bytes and from a rented
/// buffer above that; both paths must key distinct tokens distinctly and the same token identically.
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task VerifyAsync_LongAndShortTokens_AreCachedAndNotAliased()
{
FakeVerifier inner = new(Success("operator01"));
using MemoryCache cache = NewCache();
CachingApiKeyVerifier verifier = new(inner, cache, TimeSpan.FromSeconds(15));
string longA = "Bearer mxgw_operator01_" + new string('a', 2000);
string longB = "Bearer mxgw_operator01_" + new string('a', 1999) + "b";
await verifier.VerifyAsync(longA, CancellationToken.None);
await verifier.VerifyAsync(longA, CancellationToken.None);
Assert.Equal(1, inner.CallCount);
await verifier.VerifyAsync(longB, CancellationToken.None);
Assert.Equal(2, inner.CallCount);
}
/// <summary>SEC-012: one mapped gateway identity per cached library identity, not one per RPC.</summary>
[Fact]
public void ToGatewayIdentity_SameLibraryIdentity_ReturnsTheSameMappedInstance()
{
LibApiKeyIdentity library = Success("operator01").Identity!;
Assert.Same(
GatewayApiKeyIdentityMapper.ToGatewayIdentity(library),
GatewayApiKeyIdentityMapper.ToGatewayIdentity(library));
}
/// <summary>Different presented secrets are cached under distinct keys (no cross-secret aliasing).</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]