|
| 1 | +// Licensed to the .NET Foundation under one or more agreements. |
| 2 | +// The .NET Foundation licenses this file to you under the MIT license. |
| 3 | +// See the LICENSE file in the project root for more information.using System; |
| 4 | + |
| 5 | +using System; |
| 6 | +using System.Collections.Generic; |
| 7 | +using Azure.Core; |
| 8 | +using Azure.Security.KeyVault.Keys; |
| 9 | + |
| 10 | +namespace Microsoft.Data.SqlClient.Tests.Common.Fixtures; |
| 11 | + |
| 12 | +/// <summary> |
| 13 | +/// Provides a base class for managing Azure Key Vault keys in test fixtures. |
| 14 | +/// </summary> |
| 15 | +/// <remarks> |
| 16 | +/// This class simplifies the creation and cleanup of RSA keys in an Azure Key Vault during testing |
| 17 | +/// scenarios. It ensures that any keys created during the fixture's lifetime are properly deleted when the fixture is |
| 18 | +/// disposed. |
| 19 | +/// </remarks> |
| 20 | +public abstract class AzureKeyVaultKeyFixtureBase : IDisposable |
| 21 | +{ |
| 22 | + private readonly KeyClient _keyClient; |
| 23 | + private readonly Random _randomGenerator; |
| 24 | + |
| 25 | + private readonly List<KeyVaultKey> _createdKeys = new List<KeyVaultKey>(); |
| 26 | + |
| 27 | + protected AzureKeyVaultKeyFixtureBase(Uri keyVaultUri, TokenCredential keyVaultToken) |
| 28 | + { |
| 29 | + _keyClient = new KeyClient(keyVaultUri, keyVaultToken); |
| 30 | + _randomGenerator = new Random(); |
| 31 | + } |
| 32 | + |
| 33 | + protected Uri CreateKey(string name, int keySize) |
| 34 | + { |
| 35 | + CreateRsaKeyOptions createOptions = new CreateRsaKeyOptions(GenerateUniqueName(name)) { KeySize = keySize }; |
| 36 | + KeyVaultKey created = _keyClient.CreateRsaKey(createOptions); |
| 37 | + |
| 38 | + _createdKeys.Add(created); |
| 39 | + return created.Id; |
| 40 | + } |
| 41 | + |
| 42 | + private string GenerateUniqueName(string name) |
| 43 | + { |
| 44 | + byte[] rndBytes = new byte[16]; |
| 45 | + |
| 46 | + _randomGenerator.NextBytes(rndBytes); |
| 47 | + return name + "-" + BitConverter.ToString(rndBytes); |
| 48 | + } |
| 49 | + |
| 50 | + public void Dispose() |
| 51 | + { |
| 52 | + Dispose(true); |
| 53 | + GC.SuppressFinalize(this); |
| 54 | + } |
| 55 | + |
| 56 | + protected virtual void Dispose(bool disposing) |
| 57 | + { |
| 58 | + foreach (KeyVaultKey key in _createdKeys) |
| 59 | + { |
| 60 | + try |
| 61 | + { |
| 62 | + _keyClient.StartDeleteKey(key.Name).WaitForCompletion(); |
| 63 | + } |
| 64 | + catch (Exception) |
| 65 | + { |
| 66 | + continue; |
| 67 | + } |
| 68 | + } |
| 69 | + } |
| 70 | +} |
0 commit comments