-
Notifications
You must be signed in to change notification settings - Fork 18
/
sops.go
95 lines (79 loc) · 2.27 KB
/
sops.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
package crypt
import (
"fmt"
"log"
"os"
"strconv"
sops "go.mozilla.org/sops/v3"
"go.mozilla.org/sops/v3/aes"
"go.mozilla.org/sops/v3/cmd/sops/common"
"go.mozilla.org/sops/v3/keyservice"
sopsjson "go.mozilla.org/sops/v3/stores/json"
"go.mozilla.org/sops/v3/version"
sc "github.com/plumber-cd/terraform-backend-git/crypt/sops"
)
func init() {
EncryptionProviders["sops"] = &SOPSEncryptionProvider{}
}
type SOPSEncryptionProvider struct{}
// Encrypt will encrypt the data in buffer and return encrypted result.
func (p *SOPSEncryptionProvider) Encrypt(data []byte) ([]byte, error) {
keyGroups, err := sc.GetActivatedKeyGroups()
if err != nil {
return nil, err
}
inputStore := &sopsjson.Store{}
branches, err := inputStore.LoadPlainFile(data)
if err != nil {
return nil, err
}
tree := sops.Tree{
Branches: branches,
Metadata: sops.Metadata{
KeyGroups: keyGroups,
Version: version.Version,
},
}
if shamirThreshold, ok := os.LookupEnv("TF_BACKEND_HTTP_SOPS_SHAMIR_THRESHOLD"); ok {
st, err := strconv.Atoi(shamirThreshold)
if err != nil {
return nil, err
}
tree.Metadata.ShamirThreshold = st
}
dataKey, errs := tree.GenerateDataKeyWithKeyServices([]keyservice.KeyServiceClient{keyservice.NewLocalClient()})
if len(errs) > 0 {
return nil, fmt.Errorf("Could not generate data key: %s", errs)
}
if err := common.EncryptTree(common.EncryptTreeOpts{
DataKey: dataKey,
Tree: &tree,
Cipher: aes.NewCipher(),
}); err != nil {
return nil, err
}
outputStore := &sopsjson.Store{}
return outputStore.EmitEncryptedFile(tree)
}
// Decrypt will decrypt the data in buffer.
func (p *SOPSEncryptionProvider) Decrypt(data []byte) ([]byte, error) {
inputStore := &sopsjson.Store{}
tree, err := inputStore.LoadEncryptedFile(data)
if err != nil {
return nil, err
}
if tree.Metadata.Version == "" {
log.Println("SOPS metadata version was not set, assuming state was not previously encrypted and returning as-is document")
return data, nil
}
_, err = common.DecryptTree(common.DecryptTreeOpts{
Cipher: aes.NewCipher(),
Tree: &tree,
KeyServices: []keyservice.KeyServiceClient{keyservice.NewLocalClient()},
})
if err != nil {
return nil, err
}
outputStore := &sopsjson.Store{}
return outputStore.EmitPlainFile(tree.Branches)
}