| | | 1 | | namespace Envilder.Infrastructure.Azure; |
| | | 2 | | |
| | | 3 | | using Envilder.Domain.Ports; |
| | | 4 | | using global::Azure; |
| | | 5 | | using global::Azure.Security.KeyVault.Secrets; |
| | | 6 | | using System; |
| | | 7 | | using System.Threading; |
| | | 8 | | using System.Threading.Tasks; |
| | | 9 | | |
| | | 10 | | /// <summary> |
| | | 11 | | /// <see cref="ISecretProvider"/> backed by Azure Key Vault. |
| | | 12 | | /// Secrets that return HTTP 404 are treated as missing and yield <see langword="null"/>. |
| | | 13 | | /// </summary> |
| | | 14 | | public class AzureKeyVaultSecretProvider : ISecretProvider |
| | | 15 | | { |
| | | 16 | | private readonly SecretClient _secretClient; |
| | | 17 | | |
| | | 18 | | /// <summary> |
| | | 19 | | /// Initializes a new instance using the supplied Key Vault client. |
| | | 20 | | /// </summary> |
| | | 21 | | /// <param name="secretClient">A configured <see cref="SecretClient"/> instance.</param> |
| | 1 | 22 | | public AzureKeyVaultSecretProvider(SecretClient secretClient) |
| | | 23 | | { |
| | 1 | 24 | | _secretClient = secretClient ?? throw new ArgumentNullException(nameof(secretClient)); |
| | 1 | 25 | | } |
| | | 26 | | |
| | | 27 | | /// <inheritdoc /> |
| | | 28 | | public async Task<string?> GetSecretAsync(string name, CancellationToken cancellationToken = default) |
| | | 29 | | { |
| | 1 | 30 | | if (string.IsNullOrWhiteSpace(name)) |
| | | 31 | | { |
| | 0 | 32 | | throw new ArgumentException("Secret name cannot be null or whitespace.", nameof(name)); |
| | | 33 | | } |
| | | 34 | | |
| | | 35 | | try |
| | | 36 | | { |
| | 1 | 37 | | var response = await _secretClient.GetSecretAsync(name, null, cancellationToken); |
| | 1 | 38 | | return response.Value.Value; |
| | | 39 | | } |
| | 1 | 40 | | catch (RequestFailedException ex) when (ex.Status == 404) |
| | | 41 | | { |
| | 1 | 42 | | return null; |
| | | 43 | | } |
| | 1 | 44 | | } |
| | | 45 | | |
| | | 46 | | /// <inheritdoc /> |
| | | 47 | | public string? GetSecret(string name) |
| | | 48 | | { |
| | 1 | 49 | | if (string.IsNullOrWhiteSpace(name)) |
| | | 50 | | { |
| | 0 | 51 | | throw new ArgumentException("Secret name cannot be null or whitespace.", nameof(name)); |
| | | 52 | | } |
| | | 53 | | |
| | | 54 | | try |
| | | 55 | | { |
| | 1 | 56 | | using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(60)); |
| | 1 | 57 | | var response = _secretClient.GetSecret(name, version: null, cancellationToken: cts.Token); |
| | 1 | 58 | | return response.Value.Value; |
| | | 59 | | } |
| | 0 | 60 | | catch (RequestFailedException ex) when (ex.Status == 404) |
| | | 61 | | { |
| | 0 | 62 | | return null; |
| | | 63 | | } |
| | 1 | 64 | | } |
| | | 65 | | } |