| 1 |
package azkeyvault |
| 2 |
|
| 3 |
import ( |
| 4 |
"context" |
| 5 |
"errors" |
| 6 |
"fmt" |
| 7 |
"github.com/Azure/azure-sdk-for-go/sdk/azcore" |
| 8 |
"github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/azsecrets" |
| 9 |
"github.com/knadh/koanf/maps" |
| 10 |
) |
| 11 |
|
| 12 |
type Config struct { |
| 13 |
// KeyVaultUrl key vault url |
| 14 |
KeyVaultUrl string |
| 15 |
|
| 16 |
// Delim is the delimiter to use |
| 17 |
// when specifying config key paths, for instance a . for `parent.child.key` |
| 18 |
// or a / for `parent/child/key`. |
| 19 |
Delim string |
| 20 |
|
| 21 |
// TokenCredential Token credential to connect to the Azure Keyvault. |
| 22 |
// It can be created using client Id with client secret or client certificate. |
| 23 |
TokenCredential azcore.TokenCredential |
| 24 |
|
| 25 |
// If FlatPaths is true, then the loaded configuration is not split into |
| 26 |
// hierarchical maps based on the delimiter. The keys including the delimiter, |
| 27 |
// eg: app.db.name stays as-is in the confmap. |
| 28 |
FlatPaths bool |
| 29 |
} |
| 30 |
|
| 31 |
type AzureKeyVault struct { |
| 32 |
kvclient *azsecrets.Client |
| 33 |
config Config |
| 34 |
} |
| 35 |
|
| 36 |
func Provider(config Config) (*AzureKeyVault, error) { |
| 37 |
kvClient, err := azsecrets.NewClient(config.KeyVaultUrl, config.TokenCredential, nil) |
| 38 |
if err != nil { |
| 39 |
return nil, err |
| 40 |
} |
| 41 |
|
| 42 |
return &AzureKeyVault{kvclient: kvClient, config: config}, nil |
| 43 |
} |
| 44 |
|
| 45 |
func (kv *AzureKeyVault) ReadBytes() ([]byte, error) { |
| 46 |
return nil, errors.New("azure key vault provider does not support this method") |
| 47 |
} |
| 48 |
|
| 49 |
func (kv *AzureKeyVault) Read() (map[string]any, error) { |
| 50 |
ctx := context.Background() |
| 51 |
secrets := make(map[string]any) |
| 52 |
|
| 53 |
// Get all the secrets from the KV |
| 54 |
pager := kv.kvclient.NewListSecretPropertiesPager(nil) |
| 55 |
for pager.More() { |
| 56 |
page, err := pager.NextPage(ctx) |
| 57 |
if err != nil { |
| 58 |
return nil, err |
| 59 |
} |
| 60 |
|
| 61 |
for _, secret := range page.Value { |
| 62 |
sName := secret.ID.Name() |
| 63 |
SValue, err := kv.kvclient.GetSecret(ctx, sName, "", nil) |
| 64 |
|
| 65 |
if err != nil { |
| 66 |
return nil, fmt.Errorf("failed to get the secret value for %s, Error: %w", sName, err) |
| 67 |
} |
| 68 |
|
| 69 |
secrets[sName] = *SValue.Value |
| 70 |
} |
| 71 |
} |
| 72 |
|
| 73 |
if kv.config.Delim != "" && !kv.config.FlatPaths { |
| 74 |
data := maps.Unflatten(secrets, kv.config.Delim) |
| 75 |
return data, nil |
| 76 |
} |
| 77 |
|
| 78 |
return secrets, nil |
| 79 |
} |