forked from getsops/sops
/
vault.go
102 lines (85 loc) · 2.55 KB
/
vault.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
package publish
import (
"fmt"
"strings"
"github.com/google/go-cmp/cmp"
vault "github.com/hashicorp/vault/api"
"go.mozilla.org/sops/v3/logging"
"github.com/sirupsen/logrus"
)
var log *logrus.Logger
func init() {
log = logging.NewLogger("PUBLISH")
}
type VaultDestination struct {
vaultAddress string
vaultPath string
kvMountName string
kvVersion int
}
func NewVaultDestination(vaultAddress, vaultPath, kvMountName string, kvVersion int) *VaultDestination {
if !strings.HasSuffix(vaultPath, "/") {
vaultPath = vaultPath + "/"
}
if kvMountName == "" {
kvMountName = "secret/"
}
if !strings.HasSuffix(kvMountName, "/") {
kvMountName = kvMountName + "/"
}
if kvVersion != 1 && kvVersion != 2 {
kvVersion = 2
}
return &VaultDestination{vaultAddress, vaultPath, kvMountName, kvVersion}
}
func (vaultd *VaultDestination) getAddress() string {
if vaultd.vaultAddress != "" {
return vaultd.vaultAddress
}
return vault.DefaultConfig().Address
}
func (vaultd *VaultDestination) Path(fileName string) string {
return fmt.Sprintf("%s/v1/%s", vaultd.getAddress(), vaultd.secretsPath(fileName))
}
func (vaultd *VaultDestination) secretsPath(fileName string) string {
if vaultd.kvVersion == 1 {
return fmt.Sprintf("%s%s%s", vaultd.kvMountName, vaultd.vaultPath, fileName)
}
return fmt.Sprintf("%sdata/%s%s", vaultd.kvMountName, vaultd.vaultPath, fileName)
}
// Returns NotImplementedError
func (vaultd *VaultDestination) Upload(fileContents []byte, fileName string) error {
return &NotImplementedError{"Vault does not support uploading encrypted sops files directly."}
}
func (vaultd *VaultDestination) UploadUnencrypted(data map[string]interface{}, fileName string) error {
client, err := vault.NewClient(nil)
if err != nil {
return err
}
if vaultd.vaultAddress != "" {
err = client.SetAddress(vaultd.vaultAddress)
if err != nil {
return err
}
}
secretsPath := vaultd.secretsPath(fileName)
existingSecret, err := client.Logical().Read(secretsPath)
if err != nil {
log.Warnf("Cannot check if destination secret already exists in %s. New version will be created even if the data has not been changed.", secretsPath)
}
if existingSecret != nil && cmp.Equal(data, existingSecret.Data["data"]) {
log.Infof("Secret in %s is already up-to-date.\n", secretsPath)
return nil
}
secretsData := make(map[string]interface{})
if vaultd.kvVersion == 1 {
secretsData = data
} else if vaultd.kvVersion == 2 {
secretsData["data"] = data
}
_, err = client.Logical().Write(secretsPath, secretsData)
if err != nil {
return err
}
return nil
}