| | | 1 | | namespace Envilder; |
| | | 2 | | |
| | | 3 | | using global::Envilder.Domain.Ports; |
| | | 4 | | using global::Envilder.Infrastructure; |
| | | 5 | | using System; |
| | | 6 | | using System.Collections.Generic; |
| | | 7 | | using System.IO; |
| | | 8 | | using System.Threading; |
| | | 9 | | using System.Threading.Tasks; |
| | | 10 | | |
| | | 11 | | /// <summary> |
| | | 12 | | /// Fluent builder for configuring and resolving secrets from a map file. |
| | | 13 | | /// Obtain an instance via <see cref="Env.FromMapFile(string)"/>. |
| | | 14 | | /// </summary> |
| | | 15 | | /// <example> |
| | | 16 | | /// <code> |
| | | 17 | | /// var secrets = Env.FromMapFile("envilder.json") |
| | | 18 | | /// .WithProvider(SecretProviderType.Azure) |
| | | 19 | | /// .WithVaultUrl("https://my-vault.vault.azure.net") |
| | | 20 | | /// .Resolve(); |
| | | 21 | | /// </code> |
| | | 22 | | /// </example> |
| | | 23 | | public class EnvilderBuilder |
| | | 24 | | { |
| | | 25 | | private readonly string _filePath; |
| | | 26 | | private readonly EnvilderOptions _options = new(); |
| | | 27 | | private readonly Func<MapFileConfig, EnvilderOptions, ISecretProvider> _createProvider; |
| | | 28 | | private bool _contractValidation; |
| | | 29 | | private ISecretProvider? _secretProvider; |
| | | 30 | | |
| | | 31 | | internal EnvilderBuilder(string filePath) |
| | | 32 | | : this(filePath, static (config, options) => SecretProviderFactory.Create(config, options)) |
| | | 33 | | { |
| | | 34 | | } |
| | | 35 | | |
| | | 36 | | internal EnvilderBuilder( |
| | | 37 | | string filePath, |
| | | 38 | | Func<MapFileConfig, EnvilderOptions, ISecretProvider> createProvider) |
| | | 39 | | { |
| | | 40 | | _filePath = filePath; |
| | | 41 | | _createProvider = createProvider; |
| | | 42 | | } |
| | | 43 | | |
| | | 44 | | /// <summary> |
| | | 45 | | /// Overrides the secret provider type specified in the map file's <c>$config</c>. |
| | | 46 | | /// </summary> |
| | | 47 | | /// <param name="provider">The provider to use (AWS or Azure).</param> |
| | | 48 | | /// <returns>This builder for chaining.</returns> |
| | | 49 | | public EnvilderBuilder WithProvider(SecretProviderType provider) |
| | | 50 | | { |
| | | 51 | | _options.Provider = provider; |
| | | 52 | | return this; |
| | | 53 | | } |
| | | 54 | | |
| | | 55 | | /// <summary> |
| | | 56 | | /// Overrides the AWS named profile used for credential resolution. |
| | | 57 | | /// Only applicable when the provider is AWS. |
| | | 58 | | /// </summary> |
| | | 59 | | /// <param name="profile">The AWS profile name.</param> |
| | | 60 | | /// <returns>This builder for chaining.</returns> |
| | | 61 | | public EnvilderBuilder WithProfile(string profile) |
| | | 62 | | { |
| | | 63 | | _options.Profile = profile; |
| | | 64 | | return this; |
| | | 65 | | } |
| | | 66 | | |
| | | 67 | | /// <summary> |
| | | 68 | | /// Overrides the Azure Key Vault URL used for secret retrieval. |
| | | 69 | | /// Only applicable when the provider is Azure. |
| | | 70 | | /// </summary> |
| | | 71 | | /// <param name="vaultUrl">The Key Vault URL (e.g. <c>https://my-vault.vault.azure.net</c>).</param> |
| | | 72 | | /// <returns>This builder for chaining.</returns> |
| | | 73 | | public EnvilderBuilder WithVaultUrl(string vaultUrl) |
| | | 74 | | { |
| | | 75 | | _options.VaultUrl = vaultUrl; |
| | | 76 | | return this; |
| | | 77 | | } |
| | | 78 | | |
| | | 79 | | /// <summary> |
| | | 80 | | /// Uses this provider instance instead of building one from the map file |
| | | 81 | | /// <c>$config</c>. The map file is still validated as usual, and the |
| | | 82 | | /// provider overrides still set the provider type reported by |
| | | 83 | | /// <see cref="ValidateContractAsync"/>. To take part in contract |
| | | 84 | | /// validation, the provider must also implement |
| | | 85 | | /// <see cref="ISecretExistenceChecker"/>; otherwise every key is reported |
| | | 86 | | /// as <see cref="SecretExistenceStatus.ProviderError"/>. |
| | | 87 | | /// </summary> |
| | | 88 | | /// <param name="provider">The secret store to resolve values from.</param> |
| | | 89 | | /// <returns>This builder for chaining.</returns> |
| | | 90 | | /// <exception cref="ArgumentNullException">When <paramref name="provider"/> is null.</exception> |
| | | 91 | | public EnvilderBuilder WithSecretProvider(ISecretProvider provider) |
| | | 92 | | { |
| | | 93 | | _secretProvider = provider ?? throw new ArgumentNullException(nameof(provider)); |
| | | 94 | | return this; |
| | | 95 | | } |
| | | 96 | | |
| | | 97 | | /// <summary> |
| | | 98 | | /// Runs <see cref="ValidateContractAsync"/> once before every load |
| | | 99 | | /// (<see cref="Resolve"/>, <see cref="ResolveAsync"/>, <see cref="Inject"/>, |
| | | 100 | | /// <see cref="InjectAsync"/>) and fails the load with a |
| | | 101 | | /// <see cref="ContractValidationException"/> when it does not pass. Off by |
| | | 102 | | /// default: without it, a load makes no extra provider call. |
| | | 103 | | /// </summary> |
| | | 104 | | /// <returns>This builder for chaining.</returns> |
| | | 105 | | public EnvilderBuilder WithContractValidation() |
| | | 106 | | { |
| | | 107 | | _contractValidation = true; |
| | | 108 | | return this; |
| | | 109 | | } |
| | | 110 | | |
| | | 111 | | /// <summary> |
| | | 112 | | /// Checks the map file contract without reading any secret value: the map |
| | | 113 | | /// file matches <c>spec/map-file.v1.json</c> and the provider configuration |
| | | 114 | | /// it resolves to is coherent, and every declared secret exists. Expected |
| | | 115 | | /// failures (invalid map file, missing secret, access denied, rejected |
| | | 116 | | /// credentials, provider errors) are reported in the result, not thrown. |
| | | 117 | | /// When the map file is invalid, no provider is created or called. |
| | | 118 | | /// </summary> |
| | | 119 | | /// <param name="cancellationToken">Optional cancellation token, observed by every provider call.</param> |
| | | 120 | | /// <returns>The outcome of the check.</returns> |
| | | 121 | | /// <exception cref="FileNotFoundException">When the map file does not exist.</exception> |
| | | 122 | | /// <exception cref="OperationCanceledException">When <paramref name="cancellationToken"/> is canceled.</exception> |
| | | 123 | | public async Task<ContractValidationResult> ValidateContractAsync( |
| | | 124 | | CancellationToken cancellationToken = default) |
| | | 125 | | { |
| | | 126 | | Env.ValidateFileExists(_filePath); |
| | | 127 | | var json = await Env.ReadFileAsync(_filePath, cancellationToken).ConfigureAwait(false); |
| | | 128 | | var check = await CheckContractAsync(json, cancellationToken).ConfigureAwait(false); |
| | | 129 | | return check.Result; |
| | | 130 | | } |
| | | 131 | | |
| | | 132 | | /// <summary> |
| | | 133 | | /// Resolves secrets from the map file using the configured overrides and |
| | | 134 | | /// returns them as a dictionary, without injecting into the environment. |
| | | 135 | | /// </summary> |
| | | 136 | | /// <returns>Resolved secrets keyed by environment variable name.</returns> |
| | | 137 | | public IReadOnlyDictionary<string, string> Resolve() |
| | | 138 | | { |
| | | 139 | | Env.ValidateFileExists(_filePath); |
| | | 140 | | var json = File.ReadAllText(_filePath); |
| | | 141 | | if (_contractValidation) |
| | | 142 | | { |
| | | 143 | | using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(60)); |
| | | 144 | | #pragma warning disable VSTHRD002 // The sync API has no async counterpart to await |
| | | 145 | | var check = Task.Run(() => CheckContractAsync(json, cts.Token)).GetAwaiter().GetResult(); |
| | | 146 | | #pragma warning restore VSTHRD002 |
| | | 147 | | return new Dictionary<string, string>( |
| | | 148 | | new EnvilderClient(check.RequireProvider()).ResolveSecrets(check.MapFile!)); |
| | | 149 | | } |
| | | 150 | | |
| | | 151 | | var mapFile = new MapFileParser().Parse(json); |
| | | 152 | | var provider = CreateProvider(mapFile); |
| | | 153 | | return new Dictionary<string, string>(new EnvilderClient(provider).ResolveSecrets(mapFile)); |
| | | 154 | | } |
| | | 155 | | |
| | | 156 | | /// <summary> |
| | | 157 | | /// Asynchronously resolves secrets from the map file using the configured overrides. |
| | | 158 | | /// </summary> |
| | | 159 | | /// <param name="cancellationToken">Optional cancellation token.</param> |
| | | 160 | | /// <returns>Resolved secrets keyed by environment variable name.</returns> |
| | | 161 | | public async Task<IReadOnlyDictionary<string, string>> ResolveAsync( |
| | | 162 | | CancellationToken cancellationToken = default) |
| | | 163 | | { |
| | | 164 | | Env.ValidateFileExists(_filePath); |
| | | 165 | | var json = await Env.ReadFileAsync(_filePath, cancellationToken).ConfigureAwait(false); |
| | | 166 | | if (_contractValidation) |
| | | 167 | | { |
| | | 168 | | var check = await CheckContractAsync(json, cancellationToken).ConfigureAwait(false); |
| | | 169 | | var validated = await new EnvilderClient(check.RequireProvider()) |
| | | 170 | | .ResolveSecretsAsync(check.MapFile!, cancellationToken).ConfigureAwait(false); |
| | | 171 | | return new Dictionary<string, string>(validated); |
| | | 172 | | } |
| | | 173 | | |
| | | 174 | | var mapFile = new MapFileParser().Parse(json); |
| | | 175 | | var provider = CreateProvider(mapFile); |
| | | 176 | | var secrets = await new EnvilderClient(provider).ResolveSecretsAsync(mapFile, cancellationToken).ConfigureAwait(fals |
| | | 177 | | return new Dictionary<string, string>(secrets); |
| | | 178 | | } |
| | | 179 | | |
| | | 180 | | /// <summary> |
| | | 181 | | /// Resolves secrets and injects them as process-level environment variables |
| | | 182 | | /// via <see cref="System.Environment.SetEnvironmentVariable(string, string)"/>. |
| | | 183 | | /// </summary> |
| | | 184 | | /// <returns>Resolved secrets keyed by environment variable name.</returns> |
| | | 185 | | public IReadOnlyDictionary<string, string> Inject() |
| | | 186 | | { |
| | | 187 | | var secrets = Resolve(); |
| | | 188 | | EnvilderClient.InjectIntoEnvironment(secrets); |
| | | 189 | | return secrets; |
| | | 190 | | } |
| | | 191 | | |
| | | 192 | | /// <summary> |
| | | 193 | | /// Asynchronously resolves secrets and injects them as process-level environment variables. |
| | | 194 | | /// </summary> |
| | | 195 | | /// <param name="cancellationToken">Optional cancellation token.</param> |
| | | 196 | | /// <returns>Resolved secrets keyed by environment variable name.</returns> |
| | | 197 | | public async Task<IReadOnlyDictionary<string, string>> InjectAsync( |
| | | 198 | | CancellationToken cancellationToken = default) |
| | | 199 | | { |
| | | 200 | | var secrets = await ResolveAsync(cancellationToken).ConfigureAwait(false); |
| | | 201 | | EnvilderClient.InjectIntoEnvironment(secrets); |
| | | 202 | | return secrets; |
| | | 203 | | } |
| | | 204 | | |
| | | 205 | | /// <summary> |
| | | 206 | | /// Validates the map file and, when it is valid, checks every declared key |
| | | 207 | | /// with the provider a load would use, which is returned for that load. |
| | | 208 | | /// </summary> |
| | | 209 | | private async Task<ContractCheck> CheckContractAsync(string json, CancellationToken cancellationToken) |
| | | 210 | | { |
| | | 211 | | var mapFileErrors = MapFileValidator.ValidateContent(json, _options); |
| | | 212 | | if (mapFileErrors.Count > 0) |
| | | 213 | | { |
| | | 214 | | return new(ContractValidation.InvalidMapFile(mapFileErrors), null, null); |
| | | 215 | | } |
| | | 216 | | |
| | | 217 | | var mapFile = new MapFileParser().Parse(json); |
| | | 218 | | var providerType = _options.Provider ?? mapFile.Config.Provider ?? SecretProviderType.Aws; |
| | | 219 | | ISecretProvider provider; |
| | | 220 | | try |
| | | 221 | | { |
| | | 222 | | provider = CreateProvider(mapFile); |
| | | 223 | | } |
| | | 224 | | catch (AwsProfileNotFoundException ex) |
| | | 225 | | { |
| | | 226 | | return new(ContractValidation.ProfileNotFound(mapFile, providerType, ex.Message), null, null); |
| | | 227 | | } |
| | | 228 | | |
| | | 229 | | var result = provider is ISecretExistenceChecker checker |
| | | 230 | | ? await ContractValidation |
| | | 231 | | .CheckRemoteKeysAsync(mapFile, checker, providerType, cancellationToken) |
| | | 232 | | .ConfigureAwait(false) |
| | | 233 | | : ContractValidation.NotCheckable(mapFile, providerType); |
| | | 234 | | return new(result, mapFile, provider); |
| | | 235 | | } |
| | | 236 | | |
| | | 237 | | private ISecretProvider CreateProvider(ParsedMapFile mapFile) |
| | | 238 | | { |
| | | 239 | | return _secretProvider ?? _createProvider(mapFile.Config, _options); |
| | | 240 | | } |
| | | 241 | | |
| | | 242 | | private sealed class ContractCheck |
| | | 243 | | { |
| | 1 | 244 | | public ContractCheck(ContractValidationResult result, ParsedMapFile? mapFile, ISecretProvider? provider) |
| | | 245 | | { |
| | 1 | 246 | | Result = result; |
| | 1 | 247 | | MapFile = mapFile; |
| | 1 | 248 | | Provider = provider; |
| | 1 | 249 | | } |
| | | 250 | | |
| | | 251 | | public ContractValidationResult Result { get; } |
| | | 252 | | |
| | | 253 | | public ParsedMapFile? MapFile { get; } |
| | | 254 | | |
| | | 255 | | private ISecretProvider? Provider { get; } |
| | | 256 | | |
| | | 257 | | public ISecretProvider RequireProvider() |
| | | 258 | | { |
| | 1 | 259 | | if (!Result.IsValid || Provider is null) |
| | | 260 | | { |
| | 1 | 261 | | throw new ContractValidationException(Result); |
| | | 262 | | } |
| | | 263 | | |
| | 1 | 264 | | return Provider; |
| | | 265 | | } |
| | | 266 | | } |
| | | 267 | | } |