Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

using System;
using System.Collections.Generic;
using System.Security.Cryptography;
using Azure.Core;
using Azure.Security.KeyVault.Keys;

Expand All @@ -20,20 +21,41 @@ namespace Microsoft.Data.SqlClient.Tests.Common.Fixtures;
public abstract class AzureKeyVaultKeyFixtureBase : IDisposable
{
private readonly KeyClient _keyClient;
private readonly Random _randomGenerator;
private readonly RandomNumberGenerator _randomGenerator;

private readonly List<KeyVaultKey> _createdKeys = new List<KeyVaultKey>();

protected AzureKeyVaultKeyFixtureBase(Uri keyVaultUri, TokenCredential keyVaultToken)
{
_keyClient = new KeyClient(keyVaultUri, keyVaultToken);
_randomGenerator = new Random();
_randomGenerator = RandomNumberGenerator.Create();
}

protected Uri CreateKey(string name, int keySize)
{
CreateRsaKeyOptions createOptions = new CreateRsaKeyOptions(GenerateUniqueName(name)) { KeySize = keySize };
KeyVaultKey created = _keyClient.CreateRsaKey(createOptions);
const int MaxConflictResolutions = 5;
KeyVaultKey created;
int i = 0;

while (true)
{
CreateRsaKeyOptions createOptions = new CreateRsaKeyOptions(GenerateUniqueName(name)) { KeySize = keySize };

try
{
created = _keyClient.CreateRsaKey(createOptions);
break;
}
// It's possible for a key to already exist with the same name, even in a deleted state. If so, CreateRsaKey
// will throw an exception with HTTP status code 409 (Conflict.)
// We can't assume we possess permissions to purge or to recover the key, so regenerate the name and try again.
// Only make MaxConflictResolutions attempts, to avoid possible infinite loops.
catch (Azure.RequestFailedException conflictException)
when (conflictException.Status == 409 && i < MaxConflictResolutions)
{
i++;
}
}

_createdKeys.Add(created);
return created.Id;
Expand All @@ -43,7 +65,7 @@ private string GenerateUniqueName(string name)
{
byte[] rndBytes = new byte[16];

_randomGenerator.NextBytes(rndBytes);
_randomGenerator.GetBytes(rndBytes);
return name + "-" + BitConverter.ToString(rndBytes);
}

Expand All @@ -66,5 +88,7 @@ protected virtual void Dispose(bool disposing)
continue;
}
}

_randomGenerator.Dispose();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -204,7 +204,8 @@ public void Dispose()

#region Switch Value Getters and Setters

// These properties get or set the like-named underlying switch field value.
// These properties get the like-named underlying switch *property* value and set the underlying
// switch *field* value. This allows tests to verify the default switch values.
//
// They all throw if the value cannot be retrieved or set.

Expand All @@ -214,7 +215,7 @@ public void Dispose()
/// </summary>
public bool? DisableTnirByDefault
{
get => GetSwitchValue("s_disableTnirByDefault");
get => GetSwitchPropertyValue(nameof(DisableTnirByDefault));
set => SetSwitchValue("s_disableTnirByDefault", value);
}
#endif
Expand All @@ -224,7 +225,7 @@ public bool? DisableTnirByDefault
/// </summary>
public bool? EnableMultiSubnetFailoverByDefault
{
get => GetSwitchValue("s_enableMultiSubnetFailoverByDefault");
get => GetSwitchPropertyValue(nameof(EnableMultiSubnetFailoverByDefault));
set => SetSwitchValue("s_enableMultiSubnetFailoverByDefault", value);
}

Expand All @@ -234,7 +235,7 @@ public bool? EnableMultiSubnetFailoverByDefault
/// </summary>
public bool? GlobalizationInvariantMode
{
get => GetSwitchValue("s_globalizationInvariantMode");
get => GetSwitchPropertyValue(nameof(GlobalizationInvariantMode));
set => SetSwitchValue("s_globalizationInvariantMode", value);
}
#endif
Expand All @@ -244,7 +245,7 @@ public bool? GlobalizationInvariantMode
/// </summary>
public bool? IgnoreServerProvidedFailoverPartner
{
get => GetSwitchValue("s_ignoreServerProvidedFailoverPartner");
get => GetSwitchPropertyValue(nameof(IgnoreServerProvidedFailoverPartner));
set => SetSwitchValue("s_ignoreServerProvidedFailoverPartner", value);
}

Expand All @@ -253,7 +254,7 @@ public bool? IgnoreServerProvidedFailoverPartner
/// </summary>
public bool? UseLegacyFailoverAlternationOnLoginSqlErrors
{
get => GetSwitchValue("s_useLegacyFailoverAlternationOnLoginSqlErrors");
get => GetSwitchPropertyValue(nameof(UseLegacyFailoverAlternationOnLoginSqlErrors));
set => SetSwitchValue("s_useLegacyFailoverAlternationOnLoginSqlErrors", value);
}

Expand All @@ -262,7 +263,7 @@ public bool? UseLegacyFailoverAlternationOnLoginSqlErrors
/// </summary>
public bool? LegacyRowVersionNullBehavior
{
get => GetSwitchValue("s_legacyRowVersionNullBehavior");
get => GetSwitchPropertyValue(nameof(LegacyRowVersionNullBehavior));
set => SetSwitchValue("s_legacyRowVersionNullBehavior", value);
}

Expand All @@ -271,7 +272,7 @@ public bool? LegacyRowVersionNullBehavior
/// </summary>
public bool? LegacyVarTimeZeroScaleBehaviour
{
get => GetSwitchValue("s_legacyVarTimeZeroScaleBehaviour");
get => GetSwitchPropertyValue(nameof(LegacyVarTimeZeroScaleBehaviour));
set => SetSwitchValue("s_legacyVarTimeZeroScaleBehaviour", value);
}

Expand All @@ -280,7 +281,7 @@ public bool? LegacyVarTimeZeroScaleBehaviour
/// </summary>
public bool? MakeReadAsyncBlocking
{
get => GetSwitchValue("s_makeReadAsyncBlocking");
get => GetSwitchPropertyValue(nameof(MakeReadAsyncBlocking));
set => SetSwitchValue("s_makeReadAsyncBlocking", value);
}

Expand All @@ -289,7 +290,7 @@ public bool? MakeReadAsyncBlocking
/// </summary>
public bool? SuppressInsecureTlsWarning
{
get => GetSwitchValue("s_suppressInsecureTlsWarning");
get => GetSwitchPropertyValue(nameof(SuppressInsecureTlsWarning));
set => SetSwitchValue("s_suppressInsecureTlsWarning", value);
}

Expand All @@ -298,7 +299,7 @@ public bool? SuppressInsecureTlsWarning
/// </summary>
public bool? TruncateScaledDecimal
{
get => GetSwitchValue("s_truncateScaledDecimal");
get => GetSwitchPropertyValue(nameof(TruncateScaledDecimal));
set => SetSwitchValue("s_truncateScaledDecimal", value);
}

Expand All @@ -307,7 +308,7 @@ public bool? TruncateScaledDecimal
/// </summary>
public bool? UseCompatibilityAsyncBehaviour
{
get => GetSwitchValue("s_useCompatibilityAsyncBehaviour");
get => GetSwitchPropertyValue(nameof(UseCompatibilityAsyncBehaviour));
set => SetSwitchValue("s_useCompatibilityAsyncBehaviour", value);
}

Expand All @@ -316,7 +317,7 @@ public bool? UseCompatibilityAsyncBehaviour
/// </summary>
public bool? UseCompatibilityProcessSni
{
get => GetSwitchValue("s_useCompatibilityProcessSni");
get => GetSwitchPropertyValue(nameof(UseCompatibilityProcessSni));
set => SetSwitchValue("s_useCompatibilityProcessSni", value);
}

Expand All @@ -325,7 +326,7 @@ public bool? UseCompatibilityProcessSni
/// </summary>
public bool? UseConnectionPoolV2
{
get => GetSwitchValue("s_useConnectionPoolV2");
get => GetSwitchPropertyValue(nameof(UseConnectionPoolV2));
set => SetSwitchValue("s_useConnectionPoolV2", value);
}

Expand All @@ -335,7 +336,7 @@ public bool? UseConnectionPoolV2
/// </summary>
public bool? UseManagedNetworking
{
get => GetSwitchValue("s_useManagedNetworking");
get => GetSwitchPropertyValue(nameof(UseManagedNetworking));
set => SetSwitchValue("s_useManagedNetworking", value);
}
#endif
Expand All @@ -345,7 +346,7 @@ public bool? UseManagedNetworking
/// </summary>
public bool? UseMinimumLoginTimeout
{
get => GetSwitchValue("s_useMinimumLoginTimeout");
get => GetSwitchPropertyValue(nameof(UseMinimumLoginTimeout));
set => SetSwitchValue("s_useMinimumLoginTimeout", value);
}

Expand All @@ -358,19 +359,7 @@ public bool? UseMinimumLoginTimeout
/// </summary>
private static bool? GetSwitchValue(string fieldName)
{
var assembly = Assembly.GetAssembly(typeof(SqlConnection));
if (assembly is null)
{
throw new InvalidOperationException(
"Could not get assembly for Microsoft.Data.SqlClient");
}

var type = assembly.GetType("Microsoft.Data.SqlClient.LocalAppContextSwitches");
if (type is null)
{
throw new InvalidOperationException(
"Could not get type LocalAppContextSwitches");
}
var type = GetLocalAppContextSwitchesType();

var field = type.GetField(
fieldName,
Expand Down Expand Up @@ -405,19 +394,7 @@ public bool? UseMinimumLoginTimeout
/// </summary>
private static void SetSwitchValue(string fieldName, bool? value)
{
var assembly = Assembly.GetAssembly(typeof(SqlConnection));
if (assembly is null)
{
throw new InvalidOperationException(
"Could not get assembly for Microsoft.Data.SqlClient");
}

var type = assembly.GetType("Microsoft.Data.SqlClient.LocalAppContextSwitches");
if (type is null)
{
throw new InvalidOperationException(
"Could not get type LocalAppContextSwitches");
}
var type = GetLocalAppContextSwitchesType();

var field = type.GetField(
fieldName,
Expand All @@ -442,5 +419,49 @@ private static void SetSwitchValue(string fieldName, bool? value)
field.SetValue(null, Enum.ToObject(field.FieldType, byteValue));
}

/// <summary>
/// Use reflection to get a switch property value from LocalAppContextSwitches.
/// </summary>
/// <remarks>
/// Each property in LocalAppContextSwitchHelper corresponds to a like-named property in
/// LocalAppContextSwitches, which may return a different value when the AppContext switch
/// has not been set.
/// </remarks>
private static bool GetSwitchPropertyValue(string propertyName)
{
var type = GetLocalAppContextSwitchesType();
var property = type.GetProperty(
propertyName,
BindingFlags.Static | BindingFlags.Public);

if (property == null)
{
throw new InvalidOperationException(
$"Property '{propertyName}' not found in LocalAppContextSwitches");
}

object? value = property.GetValue(null);

return value is bool boolValue
? boolValue
: throw new InvalidOperationException($"Property '{propertyName}' is not of type bool.");
}

private static Type GetLocalAppContextSwitchesType()
{
var assembly = Assembly.GetAssembly(typeof(SqlConnection));
if (assembly is null)
{
throw new InvalidOperationException("Could not get assembly for Microsoft.Data.SqlClient");
}

var type = assembly.GetType("Microsoft.Data.SqlClient.LocalAppContextSwitches");
if (type is null)
{
throw new InvalidOperationException("Could not get type LocalAppContextSwitches");
}
return type;
}

#endregion
}
Loading
Loading