|
| 1 | +package auth_providers |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "encoding/json" |
| 6 | + "fmt" |
| 7 | + "os" |
| 8 | + "time" |
| 9 | + |
| 10 | + "github.com/Azure/azure-sdk-for-go/sdk/azidentity" |
| 11 | + "github.com/Azure/azure-sdk-for-go/sdk/keyvault/azsecrets" |
| 12 | +) |
| 13 | + |
| 14 | +const ( |
| 15 | + EnvAzureVaultName = "AZURE_KEYVAULT_NAME" |
| 16 | + EnvAzureSecretName = "AZURE_SECRET_NAME" |
| 17 | +) |
| 18 | + |
| 19 | +// ConfigProviderAzureKeyVault is an Authenticator that uses Azure Key Vault for authentication. |
| 20 | +type ConfigProviderAzureKeyVault struct { |
| 21 | + SecretName string `json:"secret_name"` |
| 22 | + VaultName string `json:"vault_name"` |
| 23 | + DefaultCredential *azidentity.DefaultAzureCredential |
| 24 | + CommandConfig *Config |
| 25 | + //TenantID string `json:"tenant_id;omitempty"` |
| 26 | + //SubscriptionID string `json:"subscription_id;omitempty"` |
| 27 | + //ResourceGroup string `json:"resource_group;omitempty"` |
| 28 | +} |
| 29 | + |
| 30 | +// NewConfigProviderAzureKeyVault creates a new instance of ConfigProviderAzureKeyVault. |
| 31 | +func NewConfigProviderAzureKeyVault() *ConfigProviderAzureKeyVault { |
| 32 | + return &ConfigProviderAzureKeyVault{} |
| 33 | +} |
| 34 | + |
| 35 | +// String returns a string representation of the ConfigProviderAzureKeyVault. |
| 36 | +func (a *ConfigProviderAzureKeyVault) String() string { |
| 37 | + return fmt.Sprintf("SecretName: %s, AzureVaultName: %s", a.SecretName, a.VaultName) |
| 38 | +} |
| 39 | + |
| 40 | +// WithSecretName sets the secret name for authentication. |
| 41 | +func (a *ConfigProviderAzureKeyVault) WithSecretName(secretName string) *ConfigProviderAzureKeyVault { |
| 42 | + a.SecretName = secretName |
| 43 | + return a |
| 44 | +} |
| 45 | + |
| 46 | +// WithVaultName sets the vault name for authentication. |
| 47 | +func (a *ConfigProviderAzureKeyVault) WithVaultName(vaultName string) *ConfigProviderAzureKeyVault { |
| 48 | + a.VaultName = vaultName |
| 49 | + return a |
| 50 | +} |
| 51 | + |
| 52 | +// Authenticate authenticates to Azure. |
| 53 | +func (a *ConfigProviderAzureKeyVault) Authenticate() error { |
| 54 | + |
| 55 | + vErr := a.Validate() |
| 56 | + if vErr != nil { |
| 57 | + return vErr |
| 58 | + } |
| 59 | + |
| 60 | + // Create a context with a timeout |
| 61 | + ctx, cancel := context.WithTimeout(context.Background(), DefaultClientTimeout*time.Second) |
| 62 | + defer cancel() |
| 63 | + |
| 64 | + // Add custom metadata to context |
| 65 | + ctx = context.WithValue(ctx, contextKey("operation"), "AzureAuthenticate") |
| 66 | + |
| 67 | + // Try to authenticate using DefaultAzureCredential |
| 68 | + cred, err := azidentity.NewDefaultAzureCredential(nil) |
| 69 | + if err != nil { |
| 70 | + return fmt.Errorf("failed to obtain a credential: %w", err) |
| 71 | + } |
| 72 | + a.DefaultCredential = cred |
| 73 | + return nil |
| 74 | +} |
| 75 | + |
| 76 | +// Validate validates the ConfigProviderAzureKeyVault. |
| 77 | +func (a *ConfigProviderAzureKeyVault) Validate() error { |
| 78 | + if a.SecretName == "" { |
| 79 | + // Check if the secret name is set in the environment |
| 80 | + if secretName := os.Getenv(EnvAzureSecretName); secretName != "" { |
| 81 | + a.SecretName = secretName |
| 82 | + } else { |
| 83 | + return fmt.Errorf("Azure KeyVault `SecretName` is required") |
| 84 | + } |
| 85 | + } |
| 86 | + if a.VaultName == "" { |
| 87 | + // Check if the vault name is set in the environment |
| 88 | + if vaultName := os.Getenv(EnvAzureVaultName); vaultName != "" { |
| 89 | + a.VaultName = vaultName |
| 90 | + } else { |
| 91 | + return fmt.Errorf("Azure KeyVault `VaultName` is required") |
| 92 | + } |
| 93 | + } |
| 94 | + return nil |
| 95 | +} |
| 96 | + |
| 97 | +// LoadConfigFromAzureKeyVault loads a Config type from Azure Key Vault. |
| 98 | +func (a *ConfigProviderAzureKeyVault) LoadConfigFromAzureKeyVault() (*Config, error) { |
| 99 | + if a.DefaultCredential == nil { |
| 100 | + aErr := a.Authenticate() |
| 101 | + if aErr != nil { |
| 102 | + return nil, aErr |
| 103 | + } |
| 104 | + } |
| 105 | + |
| 106 | + // Create a context with a timeout |
| 107 | + ctx, cancel := context.WithTimeout(context.Background(), DefaultClientTimeout*time.Second) |
| 108 | + defer cancel() |
| 109 | + |
| 110 | + // Add custom metadata to context |
| 111 | + ctx = context.WithValue(ctx, contextKey("operation"), "LoadConfigFromAzureKeyVault") |
| 112 | + ctx = context.WithValue(ctx, contextKey("vaultName"), a.VaultName) |
| 113 | + ctx = context.WithValue(ctx, contextKey("secretName"), a.SecretName) |
| 114 | + // Create a client to access the Azure Key Vault |
| 115 | + vaultURL := fmt.Sprintf("https://%s.vault.azure.net/", a.VaultName) |
| 116 | + client, cErr := azsecrets.NewClient(vaultURL, a.DefaultCredential, nil) |
| 117 | + if cErr != nil { |
| 118 | + return nil, cErr |
| 119 | + } |
| 120 | + |
| 121 | + // Retrieve the secret from the Azure Key Vault |
| 122 | + secretResp, sErr := client.GetSecret(ctx, a.SecretName, "", nil) |
| 123 | + if sErr != nil { |
| 124 | + return nil, sErr |
| 125 | + } |
| 126 | + |
| 127 | + // Check if the secret value is nil to avoid dereferencing a nil pointer |
| 128 | + if secretResp.Value == nil { |
| 129 | + return nil, fmt.Errorf("secret value for '%s' in vault '%s' is nil", a.SecretName, a.VaultName) |
| 130 | + } |
| 131 | + |
| 132 | + // Parse the secret value into a Config type |
| 133 | + var config Config |
| 134 | + if jErr := json.Unmarshal([]byte(*secretResp.Value), &config); jErr != nil { |
| 135 | + //attempt to unmarshal as a single server config |
| 136 | + var singleServerConfig Server |
| 137 | + if sjErr := json.Unmarshal([]byte(*secretResp.Value), &singleServerConfig); sjErr == nil { |
| 138 | + config.Servers = make(map[string]Server) |
| 139 | + config.Servers["default"] = singleServerConfig |
| 140 | + } else { |
| 141 | + return nil, jErr |
| 142 | + } |
| 143 | + } |
| 144 | + |
| 145 | + a.CommandConfig = &config |
| 146 | + return &config, nil |
| 147 | +} |
| 148 | + |
| 149 | +// Example usage of ConfigProviderAzureKeyVault |
| 150 | +// |
| 151 | +// This example demonstrates how to use ConfigProviderAzureKeyVault to load a configuration from Azure Key Vault. |
| 152 | +// |
| 153 | +// func ExampleConfigProviderAzureKeyVault() { |
| 154 | +// provider := NewConfigProviderAzureKeyVault(). |
| 155 | +// WithSecretName("my-secret"). |
| 156 | +// WithVaultName("my-vault") |
| 157 | +// |
| 158 | +// err := provider.Authenticate() |
| 159 | +// if err != nil { |
| 160 | +// fmt.Println("Failed to authenticate:", err) |
| 161 | +// return |
| 162 | +// } |
| 163 | +// |
| 164 | +// config, err := provider.LoadConfigFromAzureKeyVault() |
| 165 | +// if err != nil { |
| 166 | +// fmt.Println("Failed to load config from Azure Key Vault:", err) |
| 167 | +// return |
| 168 | +// } |
| 169 | +// |
| 170 | +// fmt.Println("Loaded config from Azure Key Vault:", config) |
| 171 | +// } |
0 commit comments