| | 1 | | // Copyright (c) Microsoft Corporation. All rights reserved. |
| | 2 | | // Licensed under the MIT License. |
| | 3 | |
|
| | 4 | | using System; |
| | 5 | | using System.Collections.Generic; |
| | 6 | | using System.Linq; |
| | 7 | | using System.Threading; |
| | 8 | | using System.Threading.Tasks; |
| | 9 | | using Azure.Core; |
| | 10 | | using Azure.Security.KeyVault.Secrets; |
| | 11 | | using Microsoft.Extensions.Configuration; |
| | 12 | |
|
| | 13 | | namespace Azure.Extensions.AspNetCore.Configuration.Secrets |
| | 14 | | { |
| | 15 | | /// <summary> |
| | 16 | | /// An AzureKeyVault based <see cref="ConfigurationProvider"/>. |
| | 17 | | /// </summary> |
| | 18 | | internal class AzureKeyVaultConfigurationProvider : ConfigurationProvider, IDisposable |
| | 19 | | { |
| | 20 | | private readonly TimeSpan? _reloadInterval; |
| | 21 | | private readonly SecretClient _client; |
| | 22 | | private readonly KeyVaultSecretManager _manager; |
| | 23 | | private Dictionary<string, LoadedSecret> _loadedSecrets; |
| | 24 | | private Task _pollingTask; |
| | 25 | | private readonly CancellationTokenSource _cancellationToken; |
| | 26 | |
|
| | 27 | | /// <summary> |
| | 28 | | /// Creates a new instance of <see cref="AzureKeyVaultConfigurationProvider"/>. |
| | 29 | | /// </summary> |
| | 30 | | /// <param name="client">The <see cref="SecretClient"/> to use for retrieving values.</param> |
| | 31 | | /// <param name="manager">The <see cref="KeyVaultSecretManager"/> to use in managing values.</param> |
| | 32 | | /// <param name="reloadInterval">The timespan to wait in between each attempt at polling the Azure Key Vault for |
| 28 | 33 | | public AzureKeyVaultConfigurationProvider(SecretClient client, KeyVaultSecretManager manager, TimeSpan? reloadIn |
| | 34 | | { |
| 28 | 35 | | Argument.AssertNotNull(client, nameof(client)); |
| 28 | 36 | | Argument.AssertNotNull(manager, nameof(manager)); |
| | 37 | |
|
| 26 | 38 | | _client = client; |
| 26 | 39 | | _manager = manager; |
| 26 | 40 | | if (reloadInterval != null && reloadInterval.Value <= TimeSpan.Zero) |
| | 41 | | { |
| 4 | 42 | | throw new ArgumentOutOfRangeException(nameof(reloadInterval), reloadInterval, nameof(reloadInterval) + " |
| | 43 | | } |
| | 44 | |
|
| 22 | 45 | | _pollingTask = null; |
| 22 | 46 | | _cancellationToken = new CancellationTokenSource(); |
| 22 | 47 | | _reloadInterval = reloadInterval; |
| 22 | 48 | | } |
| | 49 | |
|
| | 50 | | /// <summary> |
| | 51 | | /// Load secrets into this provider. |
| | 52 | | /// </summary> |
| 24 | 53 | | public override void Load() => LoadAsync().GetAwaiter().GetResult(); |
| | 54 | |
|
| | 55 | | private async Task PollForSecretChangesAsync() |
| | 56 | | { |
| 20 | 57 | | while (!_cancellationToken.IsCancellationRequested) |
| | 58 | | { |
| 20 | 59 | | await WaitForReload().ConfigureAwait(false); |
| | 60 | | try |
| | 61 | | { |
| 10 | 62 | | await LoadAsync().ConfigureAwait(false); |
| 10 | 63 | | } |
| 0 | 64 | | catch (Exception) |
| | 65 | | { |
| | 66 | | // Ignore |
| 0 | 67 | | } |
| | 68 | | } |
| 0 | 69 | | } |
| | 70 | |
|
| | 71 | | protected virtual Task WaitForReload() |
| | 72 | | { |
| | 73 | | // WaitForReload is only called when the _reloadInterval has a value. |
| 0 | 74 | | return Task.Delay(_reloadInterval.Value, _cancellationToken.Token); |
| | 75 | | } |
| | 76 | |
|
| | 77 | | private async Task LoadAsync() |
| | 78 | | { |
| 34 | 79 | | var secretPages = _client.GetPropertiesOfSecretsAsync(); |
| | 80 | |
|
| 34 | 81 | | var tasks = new List<Task<Response<KeyVaultSecret>>>(); |
| 34 | 82 | | var newLoadedSecrets = new Dictionary<string, LoadedSecret>(); |
| 34 | 83 | | var oldLoadedSecrets = Interlocked.Exchange(ref _loadedSecrets, null); |
| | 84 | |
|
| 172 | 85 | | await foreach (var secret in secretPages.ConfigureAwait(false)) |
| | 86 | | { |
| 52 | 87 | | if (!_manager.Load(secret) || secret.Enabled != true) |
| | 88 | | { |
| | 89 | | continue; |
| | 90 | | } |
| | 91 | |
|
| 44 | 92 | | var secretId = secret.Name; |
| 44 | 93 | | if (oldLoadedSecrets != null && |
| 44 | 94 | | oldLoadedSecrets.TryGetValue(secretId, out var existingSecret) && |
| 44 | 95 | | existingSecret.IsUpToDate(secret.UpdatedOn)) |
| | 96 | | { |
| 8 | 97 | | oldLoadedSecrets.Remove(secretId); |
| 8 | 98 | | newLoadedSecrets.Add(secretId, existingSecret); |
| | 99 | | } |
| | 100 | | else |
| | 101 | | { |
| 36 | 102 | | tasks.Add(_client.GetSecretAsync(secret.Name)); |
| | 103 | | } |
| | 104 | | } |
| | 105 | |
|
| 34 | 106 | | await Task.WhenAll(tasks).ConfigureAwait(false); |
| | 107 | |
|
| 140 | 108 | | foreach (var task in tasks) |
| | 109 | | { |
| 36 | 110 | | var secretBundle = task.Result; |
| 36 | 111 | | newLoadedSecrets.Add(secretBundle.Value.Name, new LoadedSecret(_manager.GetKey(secretBundle), secretBund |
| | 112 | | } |
| | 113 | |
|
| 34 | 114 | | _loadedSecrets = newLoadedSecrets; |
| | 115 | |
|
| | 116 | | // Reload is needed if we are loading secrets that were not loaded before or |
| | 117 | | // secret that was loaded previously is not available anymore |
| 34 | 118 | | if (tasks.Any() || oldLoadedSecrets?.Any() == true) |
| | 119 | | { |
| 32 | 120 | | SetData(_loadedSecrets, fireToken: oldLoadedSecrets != null); |
| | 121 | | } |
| | 122 | |
|
| | 123 | | // schedule a polling task only if none exists and a valid delay is specified |
| 34 | 124 | | if (_pollingTask == null && _reloadInterval != null) |
| | 125 | | { |
| 10 | 126 | | _pollingTask = PollForSecretChangesAsync(); |
| | 127 | | } |
| 34 | 128 | | } |
| | 129 | |
|
| | 130 | | private void SetData(Dictionary<string, LoadedSecret> loadedSecrets, bool fireToken) |
| | 131 | | { |
| 32 | 132 | | var data = new Dictionary<string, string>(loadedSecrets.Count, StringComparer.OrdinalIgnoreCase); |
| 148 | 133 | | foreach (var secretItem in loadedSecrets) |
| | 134 | | { |
| 42 | 135 | | data.Add(secretItem.Value.Key, secretItem.Value.Value); |
| | 136 | | } |
| | 137 | |
|
| 32 | 138 | | Data = data; |
| 32 | 139 | | if (fireToken) |
| | 140 | | { |
| 10 | 141 | | OnReload(); |
| | 142 | | } |
| 32 | 143 | | } |
| | 144 | |
|
| | 145 | | /// <inheritdoc/> |
| | 146 | | public void Dispose() |
| | 147 | | { |
| 20 | 148 | | _cancellationToken.Cancel(); |
| 20 | 149 | | } |
| | 150 | |
|
| | 151 | | private readonly struct LoadedSecret |
| | 152 | | { |
| | 153 | | public LoadedSecret(string key, string value, DateTimeOffset? updated) |
| | 154 | | { |
| 36 | 155 | | Key = key; |
| 36 | 156 | | Value = value; |
| 36 | 157 | | Updated = updated; |
| 36 | 158 | | } |
| | 159 | |
|
| 42 | 160 | | public string Key { get; } |
| 42 | 161 | | public string Value { get; } |
| 24 | 162 | | public DateTimeOffset? Updated { get; } |
| | 163 | |
|
| | 164 | | public bool IsUpToDate(DateTimeOffset? updated) |
| | 165 | | { |
| 12 | 166 | | if (updated.HasValue != Updated.HasValue) |
| | 167 | | { |
| 0 | 168 | | return false; |
| | 169 | | } |
| | 170 | |
|
| 12 | 171 | | return updated.GetValueOrDefault() == Updated.GetValueOrDefault(); |
| | 172 | | } |
| | 173 | | } |
| | 174 | | } |
| | 175 | | } |