diff --git a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlSecurityUtility.cs b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlSecurityUtility.cs index b524d805ad..4dc2aedc6c 100644 --- a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlSecurityUtility.cs +++ b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlSecurityUtility.cs @@ -8,6 +8,8 @@ using System.Reflection; using System.Security.Cryptography; using System.Text; +using System.Threading; +using System.Threading.Tasks; using Microsoft.Data.Common; using Microsoft.Data.SqlClient.AlwaysEncrypted; using Microsoft.Data.SqlClient.Parser; @@ -236,6 +238,99 @@ internal static void DecryptSymmetricKey(SqlCipherMetadata md, SqlConnection con return; } + /// + /// Asynchronously decrypts the symmetric key and saves it in metadata. In addition, initializes + /// the SqlClientEncryptionAlgorithm for rapid decryption. + /// + /// + /// This is the async counterpart of + /// and mutates in exactly the same way. + /// + internal static async Task DecryptSymmetricKeyAsync(SqlCipherMetadata md, SqlConnection connection, SqlCommand command, CancellationToken cancellationToken) + { + Debug.Assert(md is not null, "md should not be null in DecryptSymmetricKeyAsync."); + + (SymmetricKey symKey, SqlEncryptionKeyInfo encryptionkeyInfoChosen) = + await DecryptSymmetricKeyAsync(md.EncryptionInfo, connection, command, cancellationToken).ConfigureAwait(false); + + // Given the symmetric key instantiate a SqlClientEncryptionAlgorithm object and cache it in metadata + md.CipherAlgorithm = null; + SqlClientEncryptionAlgorithm cipherAlgorithm = null; + string algorithmName = ValidateAndGetEncryptionAlgorithmName(md.CipherAlgorithmId, md.CipherAlgorithmName); // may throw + EncryptionAlgorithmFactoryList.GetAlgorithm(symKey, md.EncryptionType, algorithmName, out cipherAlgorithm); // will validate algorithm name and type + Debug.Assert(cipherAlgorithm is not null); + md.CipherAlgorithm = cipherAlgorithm; + md.EncryptionKeyInfo = encryptionkeyInfoChosen; + } + + /// + /// Asynchronously decrypts the symmetric key. + /// + /// + /// + /// Async methods cannot declare out parameters, so the two values reported by + /// + /// are returned as a tuple instead (spec Design Decision 4). + /// + /// + /// Like the sync overload, each candidate key is tried in turn and failures are remembered so that the + /// last one can be rethrown if every candidate fails. Unlike the sync overload, a cancellation of + /// is never swallowed: it abandons the loop immediately instead of + /// causing the remaining candidates to be attempted. + /// + /// + internal static async Task<(SymmetricKey Key, SqlEncryptionKeyInfo KeyInfoChosen)> DecryptSymmetricKeyAsync( + SqlTceCipherInfoEntry sqlTceCipherInfoEntry, + SqlConnection connection, + SqlCommand command, + CancellationToken cancellationToken) + { + Debug.Assert(connection is not null, "Connection should not be null."); + Debug.Assert(sqlTceCipherInfoEntry is not null, "sqlTceCipherInfoEntry should not be null in DecryptSymmetricKeyAsync."); + Debug.Assert(sqlTceCipherInfoEntry.ColumnEncryptionKeyValues is not null, + "sqlTceCipherInfoEntry.ColumnEncryptionKeyValues should not be null in DecryptSymmetricKeyAsync."); + + SymmetricKey sqlClientSymmetricKey = null; + SqlEncryptionKeyInfo encryptionkeyInfoChosen = null; + Exception lastException = null; + SymmetricKeyCache globalCekCache = SymmetricKeyCache.Instance; + + foreach (SqlEncryptionKeyInfo keyInfo in sqlTceCipherInfoEntry.ColumnEncryptionKeyValues) + { + cancellationToken.ThrowIfCancellationRequested(); + + try + { + sqlClientSymmetricKey = ShouldUseInstanceLevelProviderFlow(keyInfo.keyStoreName, connection, command) ? + await GetKeyFromLocalProvidersAsync(keyInfo, connection, command, cancellationToken).ConfigureAwait(false) : + await globalCekCache.GetKeyAsync(keyInfo, connection, command, cancellationToken).ConfigureAwait(false); + encryptionkeyInfoChosen = keyInfo; + break; + } + catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) + { + // The caller cancelled. Do not treat this as a failure of this particular key and do not + // attempt the remaining keys; propagate so that the returned Task is cancelled. + throw; + } + catch (Exception e) + { + lastException = e; + } + } + + if (sqlClientSymmetricKey is null) + { + cancellationToken.ThrowIfCancellationRequested(); + Debug.Assert(lastException is not null, "CEK decryption failed without raising exceptions"); + throw lastException; + } + + Debug.Assert(encryptionkeyInfoChosen is not null, "encryptionkeyInfoChosen must have a value."); + + return (sqlClientSymmetricKey, encryptionkeyInfoChosen); + } + /// /// Decrypts the symmetric key and saves it in metadata. /// @@ -308,6 +403,59 @@ private static SymmetricKey GetKeyFromLocalProviders(SqlEncryptionKeyInfo keyInf return new SymmetricKey(plaintextKey); } + /// + /// Asynchronous counterpart of . + /// + /// + /// Instance-level providers are never backed by the global CEK cache, so this method performs the + /// provider call directly. A cancellation of is propagated + /// unwrapped rather than being reported as SQL.KeyDecryptionFailed. + /// + private static async Task GetKeyFromLocalProvidersAsync( + SqlEncryptionKeyInfo keyInfo, + SqlConnection connection, + SqlCommand command, + CancellationToken cancellationToken) + { + cancellationToken.ThrowIfCancellationRequested(); + + string serverName = connection.DataSource; + Debug.Assert(serverName is not null, @"serverName should not be null."); + + Debug.Assert(SqlConnection.ColumnEncryptionTrustedMasterKeyPaths is not null, @"SqlConnection.ColumnEncryptionTrustedMasterKeyPaths should not be null"); + + ThrowIfKeyPathIsNotTrustedForServer(serverName, keyInfo.keyPath); + if (!TryGetColumnEncryptionKeyStoreProvider(keyInfo.keyStoreName, out SqlColumnEncryptionKeyStoreProvider provider, connection, command)) + { + throw SQL.UnrecognizedKeyStoreProviderName(keyInfo.keyStoreName, + SqlConnection.GetColumnEncryptionSystemKeyStoreProvidersNames(), + GetListOfProviderNamesThatWereSearched(connection, command)); + } + + cancellationToken.ThrowIfCancellationRequested(); + + // Wrap provider failures, but preserve cancellation requested by the caller. + byte[] plaintextKey; + try + { + plaintextKey = await provider + .DecryptColumnEncryptionKeyAsync(keyInfo.keyPath, keyInfo.algorithmName, keyInfo.encryptedKey, cancellationToken) + .ConfigureAwait(false); + } + catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) + { + throw; + } + catch (Exception e) + { + // Generate a new exception and throw. + string keyHex = GetBytesAsString(keyInfo.encryptedKey, fLast: true, countOfBytes: 10); + throw SQL.KeyDecryptionFailed(keyInfo.keyStoreName, keyHex, e); + } + + return new SymmetricKey(plaintextKey); + } + /// /// Calculates the length of the Base64 string used to represent a byte[] with the specified length. /// @@ -382,6 +530,102 @@ internal static void VerifyColumnMasterKeySignature(string keyStoreName, string } } + /// + /// Asynchronously verifies Column Master Key Signature. + /// + /// + /// Mirrors , including wrapping failures in + /// SQL.UnableToVerifyColumnMasterKeySignature. The single exception is a cancellation of + /// , which is propagated unwrapped so the returned Task is + /// cancelled rather than faulted with an . + /// Pre-cancellation is observed before signature validation or provider lookup. + /// Cancellation is also observed before accepting provider or cache results. + /// + internal static async Task VerifyColumnMasterKeySignatureAsync( + string keyStoreName, + string keyPath, + bool isEnclaveEnabled, + byte[] CMKSignature, + SqlConnection connection, + SqlCommand command, + CancellationToken cancellationToken) + { + cancellationToken.ThrowIfCancellationRequested(); + + bool isValidSignature = false; + + try + { + Debug.Assert(SqlConnection.ColumnEncryptionTrustedMasterKeyPaths is not null, + @"SqlConnection.ColumnEncryptionTrustedMasterKeyPaths should not be null"); + + if (CMKSignature is null || CMKSignature.Length == 0) + { + throw SQL.ColumnMasterKeySignatureNotFound(keyPath); + } + + ThrowIfKeyPathIsNotTrustedForServer(connection.DataSource, keyPath); + + // Attempt to look up the provider and verify CMK Signature + if (!TryGetColumnEncryptionKeyStoreProvider(keyStoreName, out SqlColumnEncryptionKeyStoreProvider provider, connection, command)) + { + throw SQL.InvalidKeyStoreProviderName(keyStoreName, + SqlConnection.GetColumnEncryptionSystemKeyStoreProvidersNames(), + GetListOfProviderNamesThatWereSearched(connection, command)); + } + + if (ShouldUseInstanceLevelProviderFlow(keyStoreName, connection, command)) + { + cancellationToken.ThrowIfCancellationRequested(); + + isValidSignature = await provider + .VerifyColumnMasterKeyMetadataAsync(keyPath, isEnclaveEnabled, CMKSignature, cancellationToken) + .ConfigureAwait(false); + } + else + { + cancellationToken.ThrowIfCancellationRequested(); + + SignatureVerificationResult cachedResult = ColumnMasterKeyMetadataSignatureVerificationCache.Instance + .GetSignatureVerificationResult(keyStoreName, keyPath, isEnclaveEnabled, CMKSignature); + + if (cachedResult == SignatureVerificationResult.NotFound) + { + cancellationToken.ThrowIfCancellationRequested(); + + // Cache miss: verify with the provider and cache the result. + // Exceptions from VerifyColumnMasterKeyMetadataAsync bubble up to the outer catch. + isValidSignature = await provider + .VerifyColumnMasterKeyMetadataAsync(keyPath, isEnclaveEnabled, CMKSignature, cancellationToken) + .ConfigureAwait(false); + cancellationToken.ThrowIfCancellationRequested(); + ColumnMasterKeyMetadataSignatureVerificationCache.Instance + .AddSignatureVerificationResult(keyStoreName, keyPath, isEnclaveEnabled, CMKSignature, isValidSignature); + } + else + { + isValidSignature = cachedResult == SignatureVerificationResult.True; + } + } + } + catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) + { + throw; + } + catch (Exception e) + { + cancellationToken.ThrowIfCancellationRequested(); + throw SQL.UnableToVerifyColumnMasterKeySignature(e); + } + + cancellationToken.ThrowIfCancellationRequested(); + + if (!isValidSignature) + { + throw SQL.ColumnMasterKeySignatureVerificationFailed(keyPath); + } + } + // Instance-level providers will be used if at least one is registered on a connection or command and // the required provider is not a system provider. System providers are pre-registered globally and // must use the global provider flow diff --git a/src/Microsoft.Data.SqlClient/tests/UnitTests/Microsoft/Data/SqlClient/SqlSecurityUtilityTests.cs b/src/Microsoft.Data.SqlClient/tests/UnitTests/Microsoft/Data/SqlClient/SqlSecurityUtilityTests.cs new file mode 100644 index 0000000000..5c3b718b82 --- /dev/null +++ b/src/Microsoft.Data.SqlClient/tests/UnitTests/Microsoft/Data/SqlClient/SqlSecurityUtilityTests.cs @@ -0,0 +1,943 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +// Internal AE metadata signatures predate nullable annotations. +#nullable disable + +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.Data.SqlClient.AlwaysEncrypted; +using Microsoft.Data.SqlClient.Parser; +using Microsoft.Data.SqlClient.UnitTests.Utilities; +using Xunit; + +namespace Microsoft.Data.SqlClient.UnitTests +{ + /// + /// Verifies async key decryption, candidate fallback, and signature verification contracts. + /// + [Collection(SqlSecurityUtilityTestCollection.Name)] + public class SqlSecurityUtilityTests + { + private const string ProviderName = "TEST_ASYNC_PROVIDER"; + private const string SecondProviderName = "TEST_ASYNC_PROVIDER_2"; + private const string KeyPath = "test-key-path"; + private const string SecondKeyPath = "test-key-path-2"; + private const string EncryptionAlgorithm = "RSA_OAEP"; + + /// Creates deterministic 256-bit key material for the encryption algorithm. + /// Starting value for the key bytes. + /// A root key of the required length. + private static byte[] NewPlaintextKey(byte seed) + { + byte[] key = new byte[32]; + for (int i = 0; i < key.Length; i++) + { + key[i] = (byte)(seed + i); + } + return key; + } + + /// Creates unique encrypted bytes to isolate process-wide cache lookups. + /// Provider registered for the candidate. + /// Master key path supplied to that provider. + /// A candidate key with a unique cache identity. + private static SqlEncryptionKeyInfo NewKeyInfo( + string providerName = ProviderName, string keyPath = KeyPath) + => new SqlEncryptionKeyInfo + { + encryptedKey = Guid.NewGuid().ToByteArray(), + databaseId = 1, + cekId = 1, + cekVersion = 1, + cekMdVersion = 1, + keyPath = keyPath, + keyStoreName = providerName, + algorithmName = EncryptionAlgorithm, + }; + + /// Registers providers without changing process-wide registrations. + /// Provider names and instances for this connection. + /// An unopened connection that the caller must dispose. + private static SqlConnection NewConnection( + params (string Name, SqlColumnEncryptionKeyStoreProvider Provider)[] providers) + { + SqlConnection connection = new( + "Data Source=async-ae-unit-test;Column Encryption Setting=Enabled"); + Dictionary map = new(); + foreach ((string name, SqlColumnEncryptionKeyStoreProvider provider) in providers) + { + map[name] = provider; + } + connection.RegisterColumnEncryptionKeyStoreProvidersOnConnection(map); + return connection; + } + + /// Combines candidates to exercise ordered decryption fallback. + /// Candidates for the same plaintext encryption key. + /// A cipher entry containing the ordered candidates. + private static SqlTceCipherInfoEntry NewCipherInfoEntry( + params SqlEncryptionKeyInfo[] keyInfos) + { + SqlTceCipherInfoEntry entry = new(ordinal: 0); + foreach (SqlEncryptionKeyInfo keyInfo in keyInfos) + { + entry.Add(keyInfo.encryptedKey, keyInfo.databaseId, keyInfo.cekId, keyInfo.cekVersion, + keyInfo.cekMdVersion, keyInfo.keyPath, keyInfo.keyStoreName, keyInfo.algorithmName); + } + return entry; + } + + /// A failed candidate does not prevent the next key from being selected. + [Fact] + public async Task DecryptSymmetricKeyAsync_FirstKeyFails_FallsBackToSecondKey() + { + // Arrange + byte[] expectedKey = NewPlaintextKey(seed: 7); + TestKeyStoreProvider failing = new() + { + DecryptAsyncCallback = _ => throw new InvalidOperationException("first key unavailable") + }; + TestKeyStoreProvider succeeding = new() { PlaintextKey = expectedKey }; + using SqlConnection connection = NewConnection( + (ProviderName, failing), (SecondProviderName, succeeding)); + SqlTceCipherInfoEntry entry = NewCipherInfoEntry( + NewKeyInfo(ProviderName, KeyPath), NewKeyInfo(SecondProviderName, SecondKeyPath)); + + // Act + (SymmetricKey key, SqlEncryptionKeyInfo chosen) = + await SqlSecurityUtility.DecryptSymmetricKeyAsync( + entry, connection, command: null, CancellationToken.None); + + // Assert + Assert.Equal(expectedKey, key.RootKey); + Assert.Equal(SecondProviderName, chosen.keyStoreName); + Assert.Equal(1, failing.DecryptAsyncCallCount); + Assert.Equal(1, succeeding.DecryptAsyncCallCount); + Assert.Equal(0, succeeding.DecryptCallCount); + } + + /// Exhausting candidate keys reports the final wrapped provider error. + [Fact] + public async Task DecryptSymmetricKeyAsync_AllKeysFail_ThrowsLastException() + { + // Arrange + int calls = 0; + TestKeyStoreProvider failing = new() + { + DecryptAsyncCallback = _ => throw new InvalidOperationException( + ++calls == 1 ? "first failure" : "last failure") + }; + using SqlConnection connection = NewConnection((ProviderName, failing)); + SqlTceCipherInfoEntry entry = NewCipherInfoEntry(NewKeyInfo(), NewKeyInfo()); + + // Act + Func decrypt = () => SqlSecurityUtility.DecryptSymmetricKeyAsync( + entry, connection, command: null, CancellationToken.None); + + // Assert + SqlException exception = await Assert.ThrowsAsync(decrypt); + Assert.Contains("last failure", exception.ToString()); + Assert.Equal(2, failing.DecryptAsyncCallCount); + } + + /// Decryption initializes the metadata algorithm and selected key information. + [Fact] + public async Task DecryptSymmetricKeyAsync_CipherMetadata_PopulatesAlgorithmAndKeyInfo() + { + // Arrange + TestKeyStoreProvider provider = new() { PlaintextKey = NewPlaintextKey(seed: 3) }; + using SqlConnection connection = NewConnection((ProviderName, provider)); + SqlEncryptionKeyInfo keyInfo = NewKeyInfo(); + SqlCipherMetadata metadata = new( + NewCipherInfoEntry(keyInfo), ordinal: 0, + cipherAlgorithmId: (byte)TdsEnums.AEAD_AES_256_CBC_HMAC_SHA256, + cipherAlgorithmName: null, encryptionType: (byte)EncryptionType.Deterministic, + normalizationRuleVersion: 0x01); + + // Act + await SqlSecurityUtility.DecryptSymmetricKeyAsync( + metadata, connection, command: null, CancellationToken.None); + + // Assert + Assert.True(metadata.IsAlgorithmInitialized()); + Assert.NotNull(metadata.EncryptionKeyInfo); + Assert.Equal(keyInfo.keyStoreName, metadata.EncryptionKeyInfo.keyStoreName); + Assert.Equal(1, provider.DecryptAsyncCallCount); + Assert.Equal(0, provider.DecryptCallCount); + } + + /// Pre-cancellation avoids invoking an otherwise valid provider. + [Fact] + public async Task DecryptSymmetricKeyAsync_CancelledToken_DoesNotInvokeProvider() + { + // Arrange + TestKeyStoreProvider provider = new() { PlaintextKey = NewPlaintextKey(seed: 1) }; + using SqlConnection connection = NewConnection((ProviderName, provider)); + SqlTceCipherInfoEntry entry = NewCipherInfoEntry(NewKeyInfo()); + using CancellationTokenSource cts = new(); + cts.Cancel(); + + // Act + Task decrypt = SqlSecurityUtility.DecryptSymmetricKeyAsync( + entry, connection, command: null, cts.Token); + + // Assert + await Assert.ThrowsAnyAsync(() => decrypt); + Assert.True(decrypt.IsCanceled); + Assert.Equal(0, provider.DecryptAsyncCallCount); + } + + /// In-flight cancellation abandons fallback and is not wrapped as a key error. + [Fact] + public async Task DecryptSymmetricKeyAsync_CancelledMidFlight_DoesNotAttemptRemainingKeys() + { + // Arrange + using CancellationTokenSource cts = new(); + TaskCompletionSource entered = new( + TaskCreationOptions.RunContinuationsAsynchronously); + TestKeyStoreProvider provider = new() + { + DecryptAsyncCallback = async token => + { + entered.TrySetResult(true); + await Task.Delay(Timeout.Infinite, token); + return NewPlaintextKey(seed: 2); + } + }; + using SqlConnection connection = NewConnection((ProviderName, provider)); + SqlTceCipherInfoEntry entry = NewCipherInfoEntry(NewKeyInfo(), NewKeyInfo()); + + // Act + Task decrypt = SqlSecurityUtility.DecryptSymmetricKeyAsync( + entry, connection, command: null, cts.Token); + await entered.Task; + cts.Cancel(); + + // Assert + await Assert.ThrowsAnyAsync(() => decrypt); + Assert.True(decrypt.IsCanceled); + Assert.Equal(1, provider.DecryptAsyncCallCount); + } + + /// Cancellation after a failed key wins over validation of the next provider. + [Fact] + public async Task DecryptSymmetricKeyAsync_CancelledAfterFailure_DoesNotValidateNextProvider() + { + // Arrange + using CancellationTokenSource cts = new(); + TestKeyStoreProvider provider = new() + { + DecryptAsyncCallback = _ => + { + cts.Cancel(); + throw new InvalidOperationException("first key unavailable"); + } + }; + using SqlConnection connection = NewConnection((ProviderName, provider)); + SqlTceCipherInfoEntry entry = NewCipherInfoEntry( + NewKeyInfo(ProviderName), NewKeyInfo(SecondProviderName)); + + // Act + Task decrypt = SqlSecurityUtility.DecryptSymmetricKeyAsync( + entry, connection, command: null, cts.Token); + + // Assert + await Assert.ThrowsAnyAsync(() => decrypt); + Assert.True(decrypt.IsCanceled); + Assert.Equal(1, provider.DecryptAsyncCallCount); + } + + /// A synchronously failed final candidate must not replace cancellation. + [Theory] + [InlineData(1)] + [InlineData(2)] + public async Task DecryptSymmetricKeyAsync_FinalCandidateFailsInlineAfterCancellation_Cancels( + int candidateCount) + { + // Arrange + using CancellationTokenSource cts = new(); + int calls = 0; + TestKeyStoreProvider provider = new() + { + DecryptAsyncCallback = _ => + { + if (++calls == candidateCount) + { + cts.Cancel(); + } + return Task.FromException(new InvalidOperationException("Key failed")); + } + }; + using SqlConnection connection = NewConnection((ProviderName, provider)); + SqlEncryptionKeyInfo[] candidates = new SqlEncryptionKeyInfo[candidateCount]; + for (int i = 0; i < candidates.Length; i++) + { + candidates[i] = NewKeyInfo(); + } + + // Act + Task decrypt = SqlSecurityUtility.DecryptSymmetricKeyAsync( + NewCipherInfoEntry(candidates), connection, null, cts.Token); + + // Assert + OperationCanceledException error = + await Assert.ThrowsAnyAsync(() => decrypt); + Assert.Equal(cts.Token, error.CancellationToken); + Assert.True(decrypt.IsCanceled); + Assert.Equal(candidateCount, provider.DecryptAsyncCallCount); + } + + /// An asynchronously failed final candidate must not replace cancellation. + [Theory] + [InlineData(1)] + [InlineData(2)] + public async Task DecryptSymmetricKeyAsync_FinalCandidateFailsLaterAfterCancellation_Cancels( + int candidateCount) + { + // Arrange + using CancellationTokenSource cts = new(); + TaskCompletionSource result = new( + TaskCreationOptions.RunContinuationsAsynchronously); + int calls = 0; + TestKeyStoreProvider provider = new() + { + DecryptAsyncCallback = _ => ++calls == candidateCount + ? result.Task + : Task.FromException(new InvalidOperationException("First key failed")) + }; + using SqlConnection connection = NewConnection((ProviderName, provider)); + SqlEncryptionKeyInfo[] candidates = new SqlEncryptionKeyInfo[candidateCount]; + for (int i = 0; i < candidates.Length; i++) + { + candidates[i] = NewKeyInfo(); + } + + // Act + Task decrypt = SqlSecurityUtility.DecryptSymmetricKeyAsync( + NewCipherInfoEntry(candidates), connection, null, cts.Token); + cts.Cancel(); + result.SetException(new InvalidOperationException("Final candidate failed")); + + // Assert + OperationCanceledException error = + await Assert.ThrowsAnyAsync(() => decrypt); + Assert.Equal(cts.Token, error.CancellationToken); + Assert.True(decrypt.IsCanceled); + Assert.Equal(candidateCount, provider.DecryptAsyncCallCount); + } + + /// Pre-cancellation wins over an unregistered provider error. + [Fact] + public async Task DecryptSymmetricKeyAsync_CancelledToken_DoesNotValidateProvider() + { + // Arrange + TestKeyStoreProvider provider = new(); + using SqlConnection connection = NewConnection((ProviderName, provider)); + SqlTceCipherInfoEntry entry = NewCipherInfoEntry(NewKeyInfo(SecondProviderName)); + using CancellationTokenSource cts = new(); + cts.Cancel(); + + // Act + Task decrypt = SqlSecurityUtility.DecryptSymmetricKeyAsync( + entry, connection, command: null, cts.Token); + + // Assert + await Assert.ThrowsAnyAsync(() => decrypt); + Assert.True(decrypt.IsCanceled); + Assert.Equal(0, provider.DecryptAsyncCallCount); + } + + /// Cancellation wins over a verification failure completed inline. + [Fact] + public async Task VerifyColumnMasterKeySignatureAsync_ProviderFailsInlineAfterCancellation_Cancels() + { + // Arrange + using CancellationTokenSource cts = new(); + TestKeyStoreProvider provider = new() + { + VerifyAsyncCallback = _ => + { + cts.Cancel(); + return Task.FromException(new InvalidOperationException("Verification failed")); + } + }; + using SqlConnection connection = NewConnection((ProviderName, provider)); + + // Act + Task verify = SqlSecurityUtility.VerifyColumnMasterKeySignatureAsync( + ProviderName, KeyPath, true, new byte[] { 1, 2, 3 }, connection, null, cts.Token); + + // Assert + OperationCanceledException error = + await Assert.ThrowsAnyAsync(() => verify); + Assert.Equal(cts.Token, error.CancellationToken); + Assert.True(verify.IsCanceled); + Assert.Equal(1, provider.VerifyAsyncCallCount); + } + + /// Cancellation wins over a verification failure completed after suspension. + [Fact] + public async Task VerifyColumnMasterKeySignatureAsync_ProviderFailsLaterAfterCancellation_Cancels() + { + // Arrange + using CancellationTokenSource cts = new(); + TaskCompletionSource result = new( + TaskCreationOptions.RunContinuationsAsynchronously); + TestKeyStoreProvider provider = new() { VerifyAsyncCallback = _ => result.Task }; + using SqlConnection connection = NewConnection((ProviderName, provider)); + + // Act + Task verify = SqlSecurityUtility.VerifyColumnMasterKeySignatureAsync( + ProviderName, KeyPath, true, new byte[] { 1, 2, 3 }, connection, null, cts.Token); + cts.Cancel(); + result.SetException(new InvalidOperationException("Verification failed")); + + // Assert + OperationCanceledException error = + await Assert.ThrowsAnyAsync(() => verify); + Assert.Equal(cts.Token, error.CancellationToken); + Assert.True(verify.IsCanceled); + Assert.Equal(1, provider.VerifyAsyncCallCount); + } + + /// A valid provider signature completes using the async provider API. + [Fact] + public async Task VerifyColumnMasterKeySignatureAsync_ValidSignature_Completes() + { + // Arrange + TestKeyStoreProvider provider = new() { VerifyResult = true }; + using SqlConnection connection = NewConnection((ProviderName, provider)); + + // Act + await SqlSecurityUtility.VerifyColumnMasterKeySignatureAsync( + ProviderName, KeyPath, false, new byte[] { 1, 2, 3 }, + connection, null, CancellationToken.None); + + // Assert + Assert.Equal(1, provider.VerifyAsyncCallCount); + } + + /// An invalid provider signature reports the same error as synchronous verification. + [Fact] + public async Task VerifyColumnMasterKeySignatureAsync_InvalidSignature_Throws() + { + // Arrange + TestKeyStoreProvider provider = new() { VerifyResult = false }; + using SqlConnection connection = NewConnection((ProviderName, provider)); + + // Act + Func verify = () => SqlSecurityUtility.VerifyColumnMasterKeySignatureAsync( + ProviderName, KeyPath, false, new byte[] { 1, 2, 3 }, + connection, null, CancellationToken.None); + + // Assert + InvalidOperationException error = await Assert.ThrowsAsync(verify); + InvalidOperationException syncError = Assert.Throws(() => + SqlSecurityUtility.VerifyColumnMasterKeySignature( + ProviderName, KeyPath, false, new byte[] { 1, 2, 3 }, connection, null)); + Assert.Equal(syncError.Message, error.Message); + Assert.Equal(1, provider.VerifyAsyncCallCount); + } + + /// Cancellation wins over either signature result completed inline. + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task VerifyColumnMasterKeySignatureAsync_ProviderReturnsInlineAfterCancellation_Cancels( + bool verificationResult) + { + // Arrange + using CancellationTokenSource cts = new(); + TestKeyStoreProvider provider = new() + { + VerifyResult = true, + VerifyAsyncCallback = _ => + { + cts.Cancel(); + return Task.FromResult(verificationResult); + } + }; + using SqlConnection connection = NewConnection((ProviderName, provider)); + + // Act + Task verify = SqlSecurityUtility.VerifyColumnMasterKeySignatureAsync( + ProviderName, KeyPath, false, new byte[] { 1, 2, 3 }, connection, null, cts.Token); + + // Assert + OperationCanceledException error = + await Assert.ThrowsAnyAsync(() => verify); + Assert.Equal(cts.Token, error.CancellationToken); + Assert.True(verify.IsCanceled); + + // Verify that the cancelled result cannot bypass the instance provider on retry. + provider.VerifyAsyncCallback = null; + await SqlSecurityUtility.VerifyColumnMasterKeySignatureAsync( + ProviderName, KeyPath, false, new byte[] { 1, 2, 3 }, + connection, null, CancellationToken.None); + Assert.Equal(2, provider.VerifyAsyncCallCount); + } + + /// Cancellation wins over either signature result completed after suspension. + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task VerifyColumnMasterKeySignatureAsync_ProviderReturnsLaterAfterCancellation_Cancels( + bool verificationResult) + { + // Arrange + using CancellationTokenSource cts = new(); + TaskCompletionSource result = new( + TaskCreationOptions.RunContinuationsAsynchronously); + TestKeyStoreProvider provider = new() + { + VerifyResult = true, + VerifyAsyncCallback = _ => result.Task + }; + using SqlConnection connection = NewConnection((ProviderName, provider)); + + // Act + Task verify = SqlSecurityUtility.VerifyColumnMasterKeySignatureAsync( + ProviderName, KeyPath, false, new byte[] { 1, 2, 3 }, connection, null, cts.Token); + cts.Cancel(); + result.SetResult(verificationResult); + + // Assert + OperationCanceledException error = + await Assert.ThrowsAnyAsync(() => verify); + Assert.Equal(cts.Token, error.CancellationToken); + Assert.True(verify.IsCanceled); + + // Verify that the cancelled result cannot bypass the instance provider on retry. + provider.VerifyAsyncCallback = null; + await SqlSecurityUtility.VerifyColumnMasterKeySignatureAsync( + ProviderName, KeyPath, false, new byte[] { 1, 2, 3 }, + connection, null, CancellationToken.None); + Assert.Equal(2, provider.VerifyAsyncCallCount); + } + + /// Provider errors retain the signature-verification wrapper. + [Fact] + public async Task VerifyColumnMasterKeySignatureAsync_ProviderThrows_WrapsException() + { + // Arrange + TestKeyStoreProvider provider = new() + { + VerifyAsyncCallback = _ => throw new InvalidOperationException("verification exploded") + }; + using SqlConnection connection = NewConnection((ProviderName, provider)); + + // Act + Func verify = () => SqlSecurityUtility.VerifyColumnMasterKeySignatureAsync( + ProviderName, KeyPath, false, new byte[] { 1, 2, 3 }, + connection, null, CancellationToken.None); + + // Assert + InvalidOperationException error = await Assert.ThrowsAsync(verify); + Assert.IsType(error.InnerException); + Assert.Contains("verification exploded", error.ToString()); + } + + /// Pre-cancellation takes precedence over empty signature validation. + [Fact] + public async Task VerifyColumnMasterKeySignatureAsync_CancelledWithMissingSignature_Cancels() + { + // Arrange + TestKeyStoreProvider provider = new() { VerifyResult = true }; + using SqlConnection connection = NewConnection((ProviderName, provider)); + using CancellationTokenSource cts = new(); + cts.Cancel(); + + // Act + Task verify = SqlSecurityUtility.VerifyColumnMasterKeySignatureAsync( + ProviderName, KeyPath, false, Array.Empty(), connection, null, cts.Token); + + // Assert + await Assert.ThrowsAnyAsync(() => verify); + Assert.True(verify.IsCanceled); + await Assert.ThrowsAsync(() => + SqlSecurityUtility.VerifyColumnMasterKeySignatureAsync( + ProviderName, KeyPath, false, Array.Empty(), + connection, null, CancellationToken.None)); + Assert.Equal(0, provider.VerifyAsyncCallCount); + } + + /// Pre-cancellation takes precedence over provider lookup errors. + [Fact] + public async Task VerifyColumnMasterKeySignatureAsync_CancelledWithUnknownProvider_Cancels() + { + // Arrange + TestKeyStoreProvider provider = new() { VerifyResult = true }; + using SqlConnection connection = NewConnection((ProviderName, provider)); + using CancellationTokenSource cts = new(); + cts.Cancel(); + + // Act + Task verify = SqlSecurityUtility.VerifyColumnMasterKeySignatureAsync( + SecondProviderName, KeyPath, false, new byte[] { 1, 2, 3 }, + connection, null, cts.Token); + + // Assert + await Assert.ThrowsAnyAsync(() => verify); + Assert.True(verify.IsCanceled); + await Assert.ThrowsAsync(() => + SqlSecurityUtility.VerifyColumnMasterKeySignatureAsync( + SecondProviderName, KeyPath, false, new byte[] { 1, 2, 3 }, + connection, null, CancellationToken.None)); + Assert.Equal(0, provider.VerifyAsyncCallCount); + } + + /// Pre-cancellation does not invoke verification even with valid inputs. + [Fact] + public async Task VerifyColumnMasterKeySignatureAsync_CancelledToken_DoesNotInvokeProvider() + { + // Arrange + TestKeyStoreProvider provider = new() { VerifyResult = true }; + using SqlConnection connection = NewConnection((ProviderName, provider)); + using CancellationTokenSource cts = new(); + cts.Cancel(); + + // Act + Task verify = SqlSecurityUtility.VerifyColumnMasterKeySignatureAsync( + ProviderName, KeyPath, false, new byte[] { 1, 2, 3 }, connection, null, cts.Token); + + // Assert + await Assert.ThrowsAnyAsync(() => verify); + Assert.True(verify.IsCanceled); + Assert.Equal(0, provider.VerifyAsyncCallCount); + } + + /// In-flight cancellation is not wrapped as a signature error. + [Fact] + public async Task VerifyColumnMasterKeySignatureAsync_CancelledMidFlight_ProducesCancelledTask() + { + // Arrange + using CancellationTokenSource cts = new(); + TaskCompletionSource entered = new( + TaskCreationOptions.RunContinuationsAsynchronously); + TestKeyStoreProvider provider = new() + { + VerifyAsyncCallback = async token => + { + entered.TrySetResult(true); + await Task.Delay(Timeout.Infinite, token); + return true; + } + }; + using SqlConnection connection = NewConnection((ProviderName, provider)); + + // Act + Task verify = SqlSecurityUtility.VerifyColumnMasterKeySignatureAsync( + ProviderName, "unique-" + Guid.NewGuid(), false, new byte[] { 4, 5, 6 }, + connection, null, cts.Token); + await entered.Task; + cts.Cancel(); + + // Assert + await Assert.ThrowsAnyAsync(() => verify); + Assert.True(verify.IsCanceled); + } + + /// Neither cached signature result may override caller cancellation. + [Theory] + [InlineData(true)] + [InlineData(false)] + public async Task VerifyColumnMasterKeySignatureAsync_CachedResult_ObservesCancellation( + bool cachedResult) + { + // Arrange + string providerName = SqlColumnEncryptionCertificateStoreProvider.ProviderName; + string keyPath = "cached-signature-" + Guid.NewGuid(); + byte[] signature = Guid.NewGuid().ToByteArray(); + using SqlConnection connection = NewConnection(); + ColumnMasterKeyMetadataSignatureVerificationCache.Instance + .AddSignatureVerificationResult(providerName, keyPath, true, signature, cachedResult); + using CancellationTokenSource cts = new(); + cts.Cancel(); + + // Act + Task verify = SqlSecurityUtility.VerifyColumnMasterKeySignatureAsync( + providerName, keyPath, true, signature, connection, null, cts.Token); + + // Assert + OperationCanceledException error = + await Assert.ThrowsAnyAsync(() => verify); + Assert.Equal(cts.Token, error.CancellationToken); + Assert.True(verify.IsCanceled); + } + + /// A positive signature cache entry is shared with the synchronous utility. + [Fact] + public async Task VerifyColumnMasterKeySignatureAsync_CachedValidSignature_Completes() + { + // Arrange + string providerName = SqlColumnEncryptionCertificateStoreProvider.ProviderName; + string keyPath = "cached-signature-" + Guid.NewGuid(); + byte[] signature = Guid.NewGuid().ToByteArray(); + using SqlConnection connection = NewConnection(); + ColumnMasterKeyMetadataSignatureVerificationCache.Instance + .AddSignatureVerificationResult(providerName, keyPath, true, signature, true); + + // Act + await SqlSecurityUtility.VerifyColumnMasterKeySignatureAsync( + providerName, keyPath, true, signature, connection, null, CancellationToken.None); + + // Assert + SqlSecurityUtility.VerifyColumnMasterKeySignature( + providerName, keyPath, true, signature, connection, null); + } + + /// A negative signature cache entry reports the same sync and async error. + [Fact] + public async Task VerifyColumnMasterKeySignatureAsync_CachedInvalidSignature_ThrowsSameError() + { + // Arrange + string providerName = SqlColumnEncryptionCertificateStoreProvider.ProviderName; + string keyPath = "cached-signature-" + Guid.NewGuid(); + byte[] signature = Guid.NewGuid().ToByteArray(); + using SqlConnection connection = NewConnection(); + ColumnMasterKeyMetadataSignatureVerificationCache.Instance + .AddSignatureVerificationResult(providerName, keyPath, true, signature, false); + + // Act + Func verify = () => SqlSecurityUtility.VerifyColumnMasterKeySignatureAsync( + providerName, keyPath, true, signature, connection, null, CancellationToken.None); + + // Assert + InvalidOperationException error = await Assert.ThrowsAsync(verify); + InvalidOperationException syncError = Assert.Throws(() => + SqlSecurityUtility.VerifyColumnMasterKeySignature( + providerName, keyPath, true, signature, connection, null)); + Assert.Equal(syncError.Message, error.Message); + } + + /// + /// Cancellation before an inline global-provider result prevents publication and permits retry. + /// + [Theory] + [InlineData(true)] + [InlineData(false)] + public async Task VerifyColumnMasterKeySignatureAsync_GlobalResultInlineAfterCancellation_DoesNotCache( + bool verificationResult) + { + // Arrange + using CancellationTokenSource cts = new(); + TestKeyStoreProvider provider = new() + { + VerifyResult = true, + VerifyAsyncCallback = token => + { + Assert.Equal(cts.Token, token); + cts.Cancel(); + return Task.FromResult(verificationResult); + } + }; + using GlobalSignatureProviderScope scope = new(provider); + using SqlConnection connection = new( + "Data Source=async-ae-unit-test;Column Encryption Setting=Enabled"); + ColumnMasterKeyMetadataSignatureVerificationCache cache = + ColumnMasterKeyMetadataSignatureVerificationCache.Instance; + Assert.Equal(SignatureVerificationResult.NotFound, cache.GetSignatureVerificationResult( + scope.ProviderName, scope.KeyPath, true, scope.Signature)); + + // Act + Task verify = SqlSecurityUtility.VerifyColumnMasterKeySignatureAsync( + scope.ProviderName, scope.KeyPath, true, scope.Signature, connection, null, cts.Token); + + // Assert + OperationCanceledException error = + await Assert.ThrowsAnyAsync(() => verify); + Assert.Equal(cts.Token, error.CancellationToken); + Assert.True(verify.IsCanceled); + Assert.Equal(1, provider.VerifyAsyncCallCount); + Assert.Equal(SignatureVerificationResult.NotFound, cache.GetSignatureVerificationResult( + scope.ProviderName, scope.KeyPath, true, scope.Signature)); + + // A retry must reach the provider, not a result published by the canceled call. + provider.VerifyAsyncCallback = null; + await SqlSecurityUtility.VerifyColumnMasterKeySignatureAsync( + scope.ProviderName, scope.KeyPath, true, scope.Signature, + connection, null, CancellationToken.None); + Assert.Equal(2, provider.VerifyAsyncCallCount); + Assert.Equal(SignatureVerificationResult.True, cache.GetSignatureVerificationResult( + scope.ProviderName, scope.KeyPath, true, scope.Signature)); + } + + /// + /// Cancellation before a suspended global-provider result prevents publication and permits retry. + /// + [Theory] + [InlineData(true)] + [InlineData(false)] + public async Task VerifyColumnMasterKeySignatureAsync_GlobalResultLaterAfterCancellation_DoesNotCache( + bool verificationResult) + { + // Arrange + using CancellationTokenSource cts = new(); + TaskCompletionSource result = new( + TaskCreationOptions.RunContinuationsAsynchronously); + TestKeyStoreProvider provider = new() + { + VerifyResult = true, + VerifyAsyncCallback = token => + { + Assert.Equal(cts.Token, token); + return result.Task; + } + }; + using GlobalSignatureProviderScope scope = new(provider); + using SqlConnection connection = new( + "Data Source=async-ae-unit-test;Column Encryption Setting=Enabled"); + ColumnMasterKeyMetadataSignatureVerificationCache cache = + ColumnMasterKeyMetadataSignatureVerificationCache.Instance; + Assert.Equal(SignatureVerificationResult.NotFound, cache.GetSignatureVerificationResult( + scope.ProviderName, scope.KeyPath, true, scope.Signature)); + + // Act + Task verify = SqlSecurityUtility.VerifyColumnMasterKeySignatureAsync( + scope.ProviderName, scope.KeyPath, true, scope.Signature, connection, null, cts.Token); + Assert.False(verify.IsCompleted); + cts.Cancel(); + result.SetResult(verificationResult); + + // Assert + OperationCanceledException error = + await Assert.ThrowsAnyAsync(() => verify); + Assert.Equal(cts.Token, error.CancellationToken); + Assert.True(verify.IsCanceled); + Assert.Equal(1, provider.VerifyAsyncCallCount); + Assert.Equal(SignatureVerificationResult.NotFound, cache.GetSignatureVerificationResult( + scope.ProviderName, scope.KeyPath, true, scope.Signature)); + + // A retry must reach the provider, not a result published by the canceled call. + provider.VerifyAsyncCallback = null; + await SqlSecurityUtility.VerifyColumnMasterKeySignatureAsync( + scope.ProviderName, scope.KeyPath, true, scope.Signature, + connection, null, CancellationToken.None); + Assert.Equal(2, provider.VerifyAsyncCallCount); + Assert.Equal(SignatureVerificationResult.True, cache.GetSignatureVerificationResult( + scope.ProviderName, scope.KeyPath, true, scope.Signature)); + } + + /// An uncanceled global-provider success is published and reused without verification. + [Fact] + public async Task VerifyColumnMasterKeySignatureAsync_GlobalValidResult_PublishesAndReuses() + { + // Arrange + TestKeyStoreProvider provider = new() { VerifyResult = true }; + using GlobalSignatureProviderScope scope = new(provider); + using SqlConnection connection = new( + "Data Source=async-ae-unit-test;Column Encryption Setting=Enabled"); + ColumnMasterKeyMetadataSignatureVerificationCache cache = + ColumnMasterKeyMetadataSignatureVerificationCache.Instance; + Assert.Equal(SignatureVerificationResult.NotFound, cache.GetSignatureVerificationResult( + scope.ProviderName, scope.KeyPath, true, scope.Signature)); + + // Act + await SqlSecurityUtility.VerifyColumnMasterKeySignatureAsync( + scope.ProviderName, scope.KeyPath, true, scope.Signature, + connection, null, CancellationToken.None); + + // Assert + Assert.Equal(1, provider.VerifyAsyncCallCount); + Assert.Equal(SignatureVerificationResult.True, cache.GetSignatureVerificationResult( + scope.ProviderName, scope.KeyPath, true, scope.Signature)); + + // A later call must accept the cached result even if the provider would reject it. + provider.VerifyResult = false; + await SqlSecurityUtility.VerifyColumnMasterKeySignatureAsync( + scope.ProviderName, scope.KeyPath, true, scope.Signature, + connection, null, CancellationToken.None); + Assert.Equal(1, provider.VerifyAsyncCallCount); + } + + /// An uncanceled global-provider rejection is published and reused without verification. + [Fact] + public async Task VerifyColumnMasterKeySignatureAsync_GlobalInvalidResult_PublishesAndReuses() + { + // Arrange + TestKeyStoreProvider provider = new() { VerifyResult = false }; + using GlobalSignatureProviderScope scope = new(provider); + using SqlConnection connection = new( + "Data Source=async-ae-unit-test;Column Encryption Setting=Enabled"); + ColumnMasterKeyMetadataSignatureVerificationCache cache = + ColumnMasterKeyMetadataSignatureVerificationCache.Instance; + Assert.Equal(SignatureVerificationResult.NotFound, cache.GetSignatureVerificationResult( + scope.ProviderName, scope.KeyPath, true, scope.Signature)); + + // Act + Func verify = () => SqlSecurityUtility.VerifyColumnMasterKeySignatureAsync( + scope.ProviderName, scope.KeyPath, true, scope.Signature, + connection, null, CancellationToken.None); + + // Assert + await Assert.ThrowsAsync(verify); + Assert.Equal(1, provider.VerifyAsyncCallCount); + Assert.Equal(SignatureVerificationResult.False, cache.GetSignatureVerificationResult( + scope.ProviderName, scope.KeyPath, true, scope.Signature)); + + // A later call must reject the cached result even if the provider would accept it. + provider.VerifyResult = true; + await Assert.ThrowsAsync(verify); + Assert.Equal(1, provider.VerifyAsyncCallCount); + } + + /// Separately observes synchronous decryption and asynchronous provider calls. + private sealed class TestKeyStoreProvider : SqlColumnEncryptionKeyStoreProvider + { + private int _decryptCallCount; + private int _decryptAsyncCallCount; + private int _verifyAsyncCallCount; + + internal byte[] PlaintextKey { get; set; } = new byte[32]; + internal bool VerifyResult { get; set; } + internal Func> DecryptAsyncCallback { get; set; } + internal Func> VerifyAsyncCallback { get; set; } + internal int DecryptCallCount => _decryptCallCount; + internal int DecryptAsyncCallCount => _decryptAsyncCallCount; + internal int VerifyAsyncCallCount => _verifyAsyncCallCount; + + public override byte[] DecryptColumnEncryptionKey( + string masterKeyPath, string encryptionAlgorithm, byte[] encryptedColumnEncryptionKey) + { + Interlocked.Increment(ref _decryptCallCount); + return PlaintextKey; + } + + public override Task DecryptColumnEncryptionKeyAsync( + string masterKeyPath, string encryptionAlgorithm, byte[] encryptedColumnEncryptionKey, + CancellationToken cancellationToken = default) + { + Interlocked.Increment(ref _decryptAsyncCallCount); + Func> callback = DecryptAsyncCallback; + return callback is not null + ? callback(cancellationToken) : Task.FromResult(PlaintextKey); + } + + public override byte[] EncryptColumnEncryptionKey( + string masterKeyPath, string encryptionAlgorithm, byte[] columnEncryptionKey) + => throw new NotSupportedException(); + + public override byte[] SignColumnMasterKeyMetadata( + string masterKeyPath, bool allowEnclaveComputations) + => throw new NotSupportedException(); + + public override bool VerifyColumnMasterKeyMetadata( + string masterKeyPath, bool allowEnclaveComputations, byte[] signature) + => VerifyResult; + + public override Task VerifyColumnMasterKeyMetadataAsync( + string masterKeyPath, bool allowEnclaveComputations, byte[] signature, + CancellationToken cancellationToken = default) + { + Interlocked.Increment(ref _verifyAsyncCallCount); + Func> callback = VerifyAsyncCallback; + return callback is not null + ? callback(cancellationToken) : Task.FromResult(VerifyResult); + } + } + } +} diff --git a/src/Microsoft.Data.SqlClient/tests/UnitTests/TestIsolationCollections.cs b/src/Microsoft.Data.SqlClient/tests/UnitTests/TestIsolationCollections.cs index f9e5151c4b..ef7550b115 100644 --- a/src/Microsoft.Data.SqlClient/tests/UnitTests/TestIsolationCollections.cs +++ b/src/Microsoft.Data.SqlClient/tests/UnitTests/TestIsolationCollections.cs @@ -34,3 +34,12 @@ public sealed class SymmetricKeyCacheTestCollection { public const string Name = "SymmetricKeyCacheTests"; } + +/// +/// Isolates tests that temporarily replace globally registered encryption key store providers. +/// +[CollectionDefinition(Name, DisableParallelization = true)] +public sealed class SqlSecurityUtilityTestCollection +{ + public const string Name = "SqlSecurityUtilityTests"; +} diff --git a/src/Microsoft.Data.SqlClient/tests/UnitTests/Utilities/GlobalSignatureProviderScope.cs b/src/Microsoft.Data.SqlClient/tests/UnitTests/Utilities/GlobalSignatureProviderScope.cs new file mode 100644 index 0000000000..a5f421469e --- /dev/null +++ b/src/Microsoft.Data.SqlClient/tests/UnitTests/Utilities/GlobalSignatureProviderScope.cs @@ -0,0 +1,72 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System; +using System.Collections.Generic; +using System.Reflection; +using Microsoft.Extensions.Caching.Memory; + +namespace Microsoft.Data.SqlClient.UnitTests.Utilities +{ + /// + /// Temporarily installs a global provider and removes its unique signature-cache entry on exit. + /// Must be used in a collection with parallelization disabled. + /// + internal sealed class GlobalSignatureProviderScope : IDisposable + { + private readonly FieldInfo _providersField; + private readonly object? _originalProviders; + private readonly MemoryCache _cache; + private readonly string _cacheKey; + + internal string ProviderName { get; } = "TEST_SIGNATURE_" + Guid.NewGuid().ToString("N"); + internal string KeyPath { get; } = "signature-key-" + Guid.NewGuid().ToString("N"); + internal byte[] Signature { get; } = Guid.NewGuid().ToByteArray(); + + /// Installs a provider without permanently consuming one-time global registration. + /// Provider to use for this scope's unique signature metadata. + internal GlobalSignatureProviderScope(SqlColumnEncryptionKeyStoreProvider provider) + { + _providersField = typeof(SqlConnection).GetField( + "s_globalCustomColumnEncryptionKeyStoreProviders", + BindingFlags.Static | BindingFlags.NonPublic) + ?? throw new MissingFieldException(typeof(SqlConnection).FullName, + "s_globalCustomColumnEncryptionKeyStoreProviders"); + _originalProviders = _providersField.GetValue(null); + + Type cacheType = typeof(ColumnMasterKeyMetadataSignatureVerificationCache); + FieldInfo cacheField = cacheType.GetField( + "_cache", BindingFlags.Instance | BindingFlags.NonPublic) + ?? throw new MissingFieldException(cacheType.FullName, "_cache"); + _cache = (MemoryCache)cacheField.GetValue( + ColumnMasterKeyMetadataSignatureVerificationCache.Instance)!; + MethodInfo keyMethod = cacheType.GetMethod( + "GetCacheLookupKey", BindingFlags.Static | BindingFlags.NonPublic) + ?? throw new MissingMethodException(cacheType.FullName, "GetCacheLookupKey"); + _cacheKey = (string)keyMethod.Invoke( + null, new object[] { KeyPath, true, Signature, ProviderName })!; + + Dictionary providers = new( + StringComparer.OrdinalIgnoreCase); + IReadOnlyDictionary? original = + (IReadOnlyDictionary?)_originalProviders; + if (original is not null) + { + foreach (KeyValuePair entry in original) + { + providers.Add(entry.Key, entry.Value); + } + } + providers.Add(ProviderName, provider); + _providersField.SetValue(null, providers); + } + + /// Restores prior registrations and removes only this scope's cached result. + public void Dispose() + { + _providersField.SetValue(null, _originalProviders); + _cache.Remove(_cacheKey); + } + } +}