From 7ec4c202398291a3b616e5ce60edca8af080dac6 Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Thu, 3 Dec 2026 09:45:46 -0500 Subject: [PATCH] perf(auth): hash the cache key from a stack buffer and reuse the mapped identity on cache hits (SEC-012, #256) --- .../Authentication/CachingApiKeyVerifier.cs | 34 +++++++++++++++++-- .../GatewayApiKeyIdentityMapper.cs | 19 ++++++++++- .../CachingApiKeyVerifierTests.cs | 33 ++++++++++++++++++ 3 files changed, 82 insertions(+), 4 deletions(-) diff --git a/src/ZB.MOM.WW.MxGateway.Server/Security/Authentication/CachingApiKeyVerifier.cs b/src/ZB.MOM.WW.MxGateway.Server/Security/Authentication/CachingApiKeyVerifier.cs index 113516a8..3ff4131f 100644 --- a/src/ZB.MOM.WW.MxGateway.Server/Security/Authentication/CachingApiKeyVerifier.cs +++ b/src/ZB.MOM.WW.MxGateway.Server/Security/Authentication/CachingApiKeyVerifier.cs @@ -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 utf8 = byteCount <= StackLimit + ? stackalloc byte[StackLimit] + : (rented = ArrayPool.Shared.Rent(byteCount)); + try + { + int written = Encoding.UTF8.GetBytes(token, utf8); + Span hash = stackalloc byte[SHA256.HashSizeInBytes]; + SHA256.HashData(utf8[..written], hash); + + Span 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.Shared.Return(rented); + } + } } } diff --git a/src/ZB.MOM.WW.MxGateway.Server/Security/Authentication/GatewayApiKeyIdentityMapper.cs b/src/ZB.MOM.WW.MxGateway.Server/Security/Authentication/GatewayApiKeyIdentityMapper.cs index 69d73c98..cd304197 100644 --- a/src/ZB.MOM.WW.MxGateway.Server/Security/Authentication/GatewayApiKeyIdentityMapper.cs +++ b/src/ZB.MOM.WW.MxGateway.Server/Security/Authentication/GatewayApiKeyIdentityMapper.cs @@ -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 InsertionOrder = new(); private static readonly object EvictionLock = new(); + /// + /// 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. + /// + private static readonly ConditionalWeakTable MappedIdentities = new(); + /// Current cache size, exposed for tests asserting the cap is honoured. 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); } } diff --git a/src/ZB.MOM.WW.MxGateway.Tests/Security/Authentication/CachingApiKeyVerifierTests.cs b/src/ZB.MOM.WW.MxGateway.Tests/Security/Authentication/CachingApiKeyVerifierTests.cs index d0d9d513..ac8ec8e2 100644 --- a/src/ZB.MOM.WW.MxGateway.Tests/Security/Authentication/CachingApiKeyVerifierTests.cs +++ b/src/ZB.MOM.WW.MxGateway.Tests/Security/Authentication/CachingApiKeyVerifierTests.cs @@ -37,6 +37,39 @@ public sealed class CachingApiKeyVerifierTests Assert.Equal(1, inner.CallCount); } + /// + /// 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. + /// + /// A task that represents the asynchronous operation. + [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); + } + + /// SEC-012: one mapped gateway identity per cached library identity, not one per RPC. + [Fact] + public void ToGatewayIdentity_SameLibraryIdentity_ReturnsTheSameMappedInstance() + { + LibApiKeyIdentity library = Success("operator01").Identity!; + + Assert.Same( + GatewayApiKeyIdentityMapper.ToGatewayIdentity(library), + GatewayApiKeyIdentityMapper.ToGatewayIdentity(library)); + } + /// Different presented secrets are cached under distinct keys (no cross-secret aliasing). /// A task that represents the asynchronous operation. [Fact]