< Summary - Envilder .NET SDK

Information
Class: Envilder.Infrastructure.AwsProfileNotFoundException
Assembly: Envilder
File(s): /home/runner/work/envilder/envilder/src/sdks/dotnet/Infrastructure/SecretProviderFactory.cs
Tag: 605_44106794472
Line coverage
100%
Covered lines: 2
Uncovered lines: 0
Coverable lines: 2
Total lines: 137
Line coverage: 100%
Branch coverage
N/A
Covered branches: 0
Total branches: 0
Branch coverage: N/A
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
.ctor(...)100%11100%

File(s)

/home/runner/work/envilder/envilder/src/sdks/dotnet/Infrastructure/SecretProviderFactory.cs

#LineLine coverage
 1namespace Envilder.Infrastructure;
 2
 3using Amazon;
 4using Amazon.Runtime.CredentialManagement;
 5using Amazon.SimpleSystemsManagement;
 6using global::Azure.Identity;
 7using global::Azure.Security.KeyVault.Secrets;
 8using global::Envilder.Domain.Ports;
 9using global::Envilder.Infrastructure.Aws;
 10using global::Envilder.Infrastructure.Azure;
 11using System;
 12
 13/// <summary>
 14/// Creates the appropriate <see cref="ISecretProvider"/> implementation
 15/// based on the map file configuration and optional runtime overrides.
 16/// </summary>
 17internal static class SecretProviderFactory
 18{
 19  private static readonly RegionEndpoint FallbackRegion = RegionEndpoint.USEast1;
 20
 21  /// <summary>
 22  /// Creates an <see cref="ISecretProvider"/> for the provider specified in
 23  /// <paramref name="config"/>. When <paramref name="options"/> is provided,
 24  /// its values take precedence over <paramref name="config"/>.
 25  /// </summary>
 26  /// <param name="config">Configuration from the <c>$config</c> section of a map file.</param>
 27  /// <param name="options">Optional runtime overrides (e.g. CLI flags).</param>
 28  /// <returns>A ready-to-use secret provider.</returns>
 29  /// <exception cref="InvalidOperationException">
 30  /// Thrown when Azure is selected but no Vault URL is provided.
 31  /// </exception>
 32  public static ISecretProvider Create(MapFileConfig config, EnvilderOptions? options = null)
 33  {
 34    if (config is null)
 35    {
 36      throw new ArgumentNullException(nameof(config));
 37    }
 38
 39    var provider = options?.Provider ?? config.Provider;
 40    var profile = options?.Profile ?? config.Profile;
 41    var vaultUrl = options?.VaultUrl ?? config.VaultUrl;
 42
 43    ValidateCrossProviderConfig(provider, profile, vaultUrl);
 44
 45    return provider switch
 46    {
 47      SecretProviderType.Azure => CreateAzureSecretProvider(vaultUrl),
 48      _ => CreateAwsSecretProvider(profile),
 49    };
 50  }
 51
 52  private static void ValidateCrossProviderConfig(
 53    SecretProviderType? provider,
 54    string? profile,
 55    string? vaultUrl)
 56  {
 57    var isAzure = provider == SecretProviderType.Azure;
 58
 59    if (isAzure && !string.IsNullOrWhiteSpace(profile))
 60    {
 61      throw new InvalidOperationException(
 62        "AWS profile cannot be used with Azure Key Vault provider.");
 63    }
 64
 65    if (!isAzure && !string.IsNullOrWhiteSpace(vaultUrl))
 66    {
 67      throw new InvalidOperationException(
 68        "Vault URL cannot be used with AWS SSM provider.");
 69    }
 70  }
 71
 72  private static AzureKeyVaultSecretProvider CreateAzureSecretProvider(string? vaultUrl)
 73  {
 74    if (string.IsNullOrWhiteSpace(vaultUrl))
 75    {
 76      throw new InvalidOperationException("Vault URL must be provided for Azure Key Vault provider.");
 77    }
 78
 79    var secretClient = new SecretClient(new Uri(vaultUrl), new DefaultAzureCredential());
 80    return new(secretClient);
 81  }
 82
 83  private static AwsSsmSecretProvider CreateAwsSecretProvider(string? profile)
 84  {
 85    if (!string.IsNullOrWhiteSpace(profile))
 86    {
 87      var profilesLocation = Environment.GetEnvironmentVariable("AWS_SHARED_CREDENTIALS_FILE");
 88      var chain = new CredentialProfileStoreChain(profilesLocation);
 89      if (chain.TryGetAWSCredentials(profile, out var credentials))
 90      {
 91        var region = ResolveProfileRegion(chain, profile!);
 92        return new(new AmazonSimpleSystemsManagementClient(credentials, region), profile);
 93      }
 94
 95      throw new AwsProfileNotFoundException(profile!);
 96    }
 97
 98    return new(new AmazonSimpleSystemsManagementClient(), profile);
 99  }
 100
 101  private static RegionEndpoint ResolveProfileRegion(CredentialProfileStoreChain chain, string profile)
 102  {
 103    if (chain.TryGetProfile(profile, out var credentialProfile) && credentialProfile.Region != null)
 104    {
 105      return credentialProfile.Region;
 106    }
 107
 108    return ResolveRegion();
 109  }
 110
 111  /// <summary>
 112  /// Resolves the AWS region from environment variables (<c>AWS_REGION</c> or
 113  /// <c>AWS_DEFAULT_REGION</c>), falling back to <c>us-east-1</c> when neither is set.
 114  /// </summary>
 115  private static RegionEndpoint ResolveRegion()
 116  {
 117    var regionName = Environment.GetEnvironmentVariable("AWS_REGION")
 118      ?? Environment.GetEnvironmentVariable("AWS_DEFAULT_REGION");
 119
 120    return string.IsNullOrWhiteSpace(regionName)
 121      ? FallbackRegion
 122      : RegionEndpoint.GetBySystemName(regionName);
 123  }
 124}
 125
 126/// <summary>
 127/// Thrown when the AWS profile is not in the credential store. Still an
 128/// <see cref="InvalidOperationException"/> for callers of a load; contract
 129/// validation reports it as an authentication failure instead.
 130/// </summary>
 131internal sealed class AwsProfileNotFoundException : InvalidOperationException
 132{
 133  public AwsProfileNotFoundException(string profile)
 1134    : base($"AWS profile '{profile}' was not found in the credential store.")
 135  {
 1136  }
 137}

Methods/Properties

.ctor(string)