|
| 1 | +package publish |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "fmt" |
| 6 | + "strings" |
| 7 | + |
| 8 | + "go.mozilla.org/sops/v3/logging" |
| 9 | + |
| 10 | + "github.com/Azure/azure-sdk-for-go/sdk/azidentity" |
| 11 | + "github.com/Azure/azure-sdk-for-go/sdk/keyvault/azsecrets" |
| 12 | + "github.com/sirupsen/logrus" |
| 13 | +) |
| 14 | + |
| 15 | +var azkvLog *logrus.Logger |
| 16 | + |
| 17 | +func init() { |
| 18 | + azkvLog = logging.NewLogger("AZKVPublish") |
| 19 | +} |
| 20 | + |
| 21 | +type AzureKeyVaultDestination struct { |
| 22 | + azureKeyVaultURL string |
| 23 | + publishSuffix string |
| 24 | +} |
| 25 | + |
| 26 | +func NewAzureKeyVaultDestination(azureKeyVaultURL string, publishSuffix string) *AzureKeyVaultDestination { |
| 27 | + return &AzureKeyVaultDestination{azureKeyVaultURL, publishSuffix} |
| 28 | +} |
| 29 | + |
| 30 | +func (azkvd *AzureKeyVaultDestination) Path(fileName string) string { |
| 31 | + return fmt.Sprintf("%s", azkvd.azureKeyVaultURL) |
| 32 | +} |
| 33 | + |
| 34 | +// Returns NotImplementedError |
| 35 | +func (azkvd *AzureKeyVaultDestination) Upload(fileContents []byte, fileName string) error { |
| 36 | + return &NotImplementedError{"Azure Key Vault does not support uploading encrypted sops files directly."} |
| 37 | +} |
| 38 | + |
| 39 | +func (azkvd *AzureKeyVaultDestination) UploadUnencrypted(data map[string]interface{}, fileName string) error { |
| 40 | + credential, err := azidentity.NewDefaultAzureCredential(nil) |
| 41 | + if err != nil { |
| 42 | + log.Fatalf("failed to retrieve Azure credential %v", err) |
| 43 | + return err |
| 44 | + } |
| 45 | + |
| 46 | + client, err := azsecrets.NewClient(azkvd.azureKeyVaultURL, credential, nil) |
| 47 | + if err != nil { |
| 48 | + log.Fatalf("failed to create azsecrets client %v", err) |
| 49 | + return err |
| 50 | + } |
| 51 | + |
| 52 | + for secretName, secretElement := range data { |
| 53 | + |
| 54 | + if !strings.HasSuffix(secretName, azkvd.publishSuffix) { |
| 55 | + continue |
| 56 | + } |
| 57 | + |
| 58 | + secretValue := fmt.Sprintf("%v", secretElement) |
| 59 | + |
| 60 | + sanitizedSecretName := strings.ReplaceAll(secretName, "_", "-") |
| 61 | + |
| 62 | + azkvLog.Infof("Uploading Secret Name: %v, Sanitized: %v", secretName, sanitizedSecretName) |
| 63 | + |
| 64 | + // Create a secret |
| 65 | + params := azsecrets.SetSecretParameters{Value: &secretValue} |
| 66 | + _, err = client.SetSecret(context.TODO(), sanitizedSecretName, params, nil) |
| 67 | + if err != nil { |
| 68 | + log.Fatalf("failed to create a secret %v: %v", secretName, err) |
| 69 | + } |
| 70 | + } |
| 71 | + |
| 72 | + return nil |
| 73 | +} |
0 commit comments