| | | 1 | | namespace Envilder.Infrastructure.Azure; |
| | | 2 | | |
| | | 3 | | using global::Azure; |
| | | 4 | | using global::Azure.Security.KeyVault.Secrets; |
| | | 5 | | using global::Envilder.Domain.Ports; |
| | | 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 | | /// Each reference is mapped to its Key Vault name with the same rule the CLI uses. |
| | | 14 | | /// </summary> |
| | | 15 | | public class AzureKeyVaultSecretProvider : ISecretProvider |
| | | 16 | | { |
| | | 17 | | private readonly SecretClient _secretClient; |
| | | 18 | | |
| | | 19 | | /// <summary> |
| | | 20 | | /// Initializes a new instance using the supplied Key Vault client. |
| | | 21 | | /// </summary> |
| | | 22 | | /// <param name="secretClient">A configured <see cref="SecretClient"/> instance.</param> |
| | 1 | 23 | | public AzureKeyVaultSecretProvider(SecretClient secretClient) |
| | | 24 | | { |
| | 1 | 25 | | _secretClient = secretClient ?? throw new ArgumentNullException(nameof(secretClient)); |
| | 1 | 26 | | } |
| | | 27 | | |
| | | 28 | | /// <inheritdoc /> |
| | | 29 | | public async Task<string?> GetSecretAsync(string name, CancellationToken cancellationToken = default) |
| | | 30 | | { |
| | 1 | 31 | | if (string.IsNullOrWhiteSpace(name)) |
| | | 32 | | { |
| | 0 | 33 | | throw new ArgumentException("Secret name cannot be null or whitespace.", nameof(name)); |
| | | 34 | | } |
| | | 35 | | |
| | | 36 | | try |
| | | 37 | | { |
| | 1 | 38 | | var response = await _secretClient.GetSecretAsync(AzureSecretName.From(name), null, cancellationToken); |
| | 1 | 39 | | return response.Value.Value; |
| | | 40 | | } |
| | 1 | 41 | | catch (RequestFailedException ex) when (ex.Status == 404) |
| | | 42 | | { |
| | 1 | 43 | | return null; |
| | | 44 | | } |
| | 1 | 45 | | } |
| | | 46 | | |
| | | 47 | | /// <inheritdoc /> |
| | | 48 | | public string? GetSecret(string name) |
| | | 49 | | { |
| | 1 | 50 | | if (string.IsNullOrWhiteSpace(name)) |
| | | 51 | | { |
| | 0 | 52 | | throw new ArgumentException("Secret name cannot be null or whitespace.", nameof(name)); |
| | | 53 | | } |
| | | 54 | | |
| | | 55 | | try |
| | | 56 | | { |
| | 1 | 57 | | using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(60)); |
| | 1 | 58 | | var response = _secretClient.GetSecret(AzureSecretName.From(name), version: null, cancellationToken: cts.Token); |
| | 1 | 59 | | return response.Value.Value; |
| | | 60 | | } |
| | 0 | 61 | | catch (RequestFailedException ex) when (ex.Status == 404) |
| | | 62 | | { |
| | 0 | 63 | | return null; |
| | | 64 | | } |
| | 1 | 65 | | } |
| | | 66 | | } |