forked from drogus/terraform-provider-parameters-manager
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsecrets.go
361 lines (304 loc) · 10.5 KB
/
secrets.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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
package main
import (
"bytes"
"errors"
"fmt"
"os"
"os/exec"
"path/filepath"
"reflect"
"strings"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"gopkg.in/yaml.v3"
)
// mapToYaml converts a map to a YAML string.
func mapToYaml(data map[string]interface{}) (string, error) {
out, err := yaml.Marshal(data)
if err != nil {
return "", err
}
return string(out), nil
}
func resourceSecrets() *schema.Resource {
return &schema.Resource{
Schema: map[string]*schema.Schema{
"secrets": {
Type: schema.TypeMap,
Required: true,
Elem: &schema.Schema{Type: schema.TypeString},
Sensitive: true,
},
"app": {
Type: schema.TypeString,
Required: true,
},
"env": {
Type: schema.TypeString,
Required: true,
},
},
Create: resourceSecretsCreate,
Read: resourceSecretsRead,
Update: resourceSecretsUpdate,
Delete: resourceSecretsDelete,
}
}
func secretsDir(directoryPath string, env string, app string) string {
return filepath.Join(directoryPath, "applications/clusters", env, "charts", app, "secrets")
}
func secretPath(directoryPath string, env string, app string, secretName string, encrypted bool) string {
var encryptedSuffix string
if !encrypted {
encryptedSuffix = ".unencrypted"
}
return filepath.Join(secretsDir(directoryPath, env, app), secretName+encryptedSuffix+".yaml")
}
func resourceSecretsCreate(d *schema.ResourceData, m interface{}) error {
config, ok := m.(*Config) // Cast the interface{} to *Config
if !ok {
return fmt.Errorf("Could not fetch plugin config")
}
directoryPath := config.DirectoryPath // Use the directory path from the provider config
awsProfile := config.AwsProfile
secrets, ok := d.Get("secrets").(map[string]interface{})
if !ok {
return fmt.Errorf("Could not fetch parameter secrets")
}
app, ok := d.Get("app").(string)
if !ok {
return fmt.Errorf("Could not fetch parameter app")
}
env, ok := d.Get("env").(string)
if !ok {
return fmt.Errorf("Could not fetch parameter env")
}
for secretName, val := range secrets {
err := createSecret(awsProfile, directoryPath, app, env, secretName, val)
if err != nil {
return fmt.Errorf("Couldn't create a secret %s: %s", secretName, err)
}
}
id := fmt.Sprintf("%s-%s", env, app)
d.SetId(id)
return nil
}
func createSecret(awsProfile, directoryPath string, app string, env string, secretName string, val interface{}) error {
secretValue := map[string]interface{}{
"value": val,
"managedBy": "terraform-provider-parameters-manager",
}
unencryptedFilePath := secretPath(directoryPath, env, app, secretName, false)
encryptedFilePath := secretPath(directoryPath, env, app, secretName, true)
secretsDir := secretsDir(directoryPath, env, app)
// Convert single secret to YAML
yamlContent, err := mapToYaml(secretValue)
if err != nil {
return err
}
if err := os.MkdirAll(secretsDir, 0755); err != nil {
return fmt.Errorf("could not create a directory %s: %s", secretsDir, err)
}
// Write to unencrypted file
if err := os.WriteFile(unencryptedFilePath, []byte(yamlContent), 0600); err != nil {
return fmt.Errorf("could not write to file %s: %s", unencryptedFilePath, err)
}
// Encrypt file with sops
if err := executeSopsEncrypt(env, awsProfile, unencryptedFilePath, encryptedFilePath); err != nil {
return fmt.Errorf("error encrypting file for secret %s: %s", secretName, err)
}
// Delete unencrypted file
if err := os.Remove(unencryptedFilePath); err != nil {
return fmt.Errorf("error removing unencrypted file for secret %s: %s", secretName, err)
}
return nil
}
func fetchExistingSecrets(awsProfile string, directoryPath string, env string, app string) (map[string]interface{}, error) {
// Placeholder for the decrypted secrets map
decryptedSecrets := make(map[string]interface{})
existingSecrets, err := listSecretFiles(directoryPath, env, app)
if err != nil {
return nil, err
}
existingSecretNames := make([]string, 0)
for _, secretPath := range existingSecrets {
secretName := filepath.Base(secretPath)
secretName = strings.TrimSuffix(secretName, ".yaml")
existingSecretNames = append(existingSecretNames, secretName)
}
for _, name := range existingSecretNames {
encryptedFilePath := secretPath(directoryPath, env, app, name, true)
// Decrypt the file with sops and read the secret value
decryptedData, exists, err := decryptSopsFile(awsProfile, env, encryptedFilePath)
if err != nil {
return nil, err
}
if exists {
managedBy := decryptedData["managedBy"]
if !isNil(managedBy) {
if managedBy == "terraform-provider-parameters-manager" {
decryptedSecrets[name] = decryptedData["value"]
}
}
}
}
return decryptedSecrets, nil
}
func isNil(c interface{}) bool {
return c == nil || (reflect.ValueOf(c).Kind() == reflect.Ptr && reflect.ValueOf(c).IsNil())
}
func resourceSecretsRead(d *schema.ResourceData, m interface{}) error {
config, ok := m.(*Config) // Retrieve the provider configuration
if !ok {
return fmt.Errorf("Could not fetch plugin config")
}
directoryPath := config.DirectoryPath
awsProfile := config.AwsProfile
app, ok := d.Get("app").(string)
if !ok {
return fmt.Errorf("Could not fetch parameter app")
}
env, ok := d.Get("env").(string)
if !ok {
return fmt.Errorf("Could not fetch parameter env")
}
decryptedSecrets, err := fetchExistingSecrets(awsProfile, directoryPath, env, app)
if err != nil {
return fmt.Errorf("Error when fetching existing secrets: %s", err)
}
// Update the Terraform state with the decrypted secrets
if err := d.Set("secrets", decryptedSecrets); err != nil {
return err
}
return nil
}
func resourceSecretsUpdate(d *schema.ResourceData, m interface{}) error {
config, ok := m.(*Config)
if !ok {
return fmt.Errorf("Could not fetch plugin config")
}
directoryPath := config.DirectoryPath
awsProfile := config.AwsProfile
definedSecrets, ok := d.Get("secrets").(map[string]interface{})
if !ok {
return fmt.Errorf("Could not fetch parameter secrets")
}
app, ok := d.Get("app").(string)
if !ok {
return fmt.Errorf("Could not fetch parameter app")
}
env, ok := d.Get("env").(string)
if !ok {
return fmt.Errorf("Could not fetch parameter env")
}
ageKeysPath := filepath.Join(directoryPath, "applications/clusters", env)
existingSecrets, err := fetchExistingSecrets(ageKeysPath, directoryPath, env, app)
if err != nil {
return err
}
for secretName, definedValue := range definedSecrets {
val, ok := existingSecrets[secretName]
if !ok || val != definedValue {
// secret not in the existing map or a value differs, let's add it
// and create the file
existingSecrets[secretName] = definedValue
err := createSecret(awsProfile, directoryPath, app, env, secretName, definedValue)
if err != nil {
return fmt.Errorf("Couldn't create a secret %s: %s", secretName, err)
}
}
}
for secretName := range existingSecrets {
_, ok := definedSecrets[secretName]
if !ok {
// secret is in the file, but is not defined anymore, removing
delete(existingSecrets, secretName)
encryptedFilePath := secretPath(directoryPath, env, app, secretName, true)
if err := os.Remove(encryptedFilePath); err != nil {
return fmt.Errorf("error removing encrypted file for secret %s: %s", secretName, err)
}
}
}
// Update the Terraform state with the decrypted secrets
if err := d.Set("secrets", existingSecrets); err != nil {
return err
}
return nil
}
func listSecretFiles(directoryPath, env, app string) ([]string, error) {
searchPattern := secretPath(directoryPath, env, app, "*", true)
return filepath.Glob(searchPattern)
}
// decryptSopsFile uses `sops` to decrypt a file and returns the decrypted secret value.
func decryptSopsFile(awsProfile string, env string, filePath string) (map[string]interface{}, bool, error) {
if _, err := os.Stat(filePath); errors.Is(err, os.ErrNotExist) {
// File doesn't exist, return nothing
return nil, false, nil
}
// Execute sops command to decrypt the file
key := fmt.Sprintf("SOPS_AGE_KEY=$(aws ssm get-parameter --name /kubernetes/clusters/%s/age_key --with-decryption --query Parameter.Value --output text --profile %s --region us-east-1)", env, awsProfile)
cmd := exec.Command("bash", "-c", fmt.Sprintf("%s sops --config <(echo '') -d %s", key, filePath))
var out, errb bytes.Buffer
cmd.Stderr = &errb
cmd.Stdout = &out
// Execute the command
err := cmd.Run()
if err != nil {
return nil, true, fmt.Errorf("%s", errb.String())
}
// Parse the output to extract the secret value
// Assuming the file contains a simple "value: secret" YAML structure
var secretData map[string]interface{}
if err := yaml.Unmarshal(out.Bytes(), &secretData); err != nil {
return nil, true, err
}
return secretData, true, nil
}
func resourceSecretsDelete(d *schema.ResourceData, m interface{}) error {
config, ok := m.(*Config)
if !ok {
return fmt.Errorf("Could not fetch plugin config")
}
directoryPath := config.DirectoryPath
app, ok := d.Get("app").(string)
if !ok {
return fmt.Errorf("Could not fetch parameter app")
}
env, ok := d.Get("env").(string)
if !ok {
return fmt.Errorf("Could not fetch parameter env")
}
ageKeysPath := filepath.Join(directoryPath, "applications/clusters", env)
existingSecrets, err := fetchExistingSecrets(ageKeysPath, directoryPath, env, app)
if err != nil {
return err
}
for secretName := range existingSecrets {
encryptedFilePath := secretPath(directoryPath, env, app, secretName, true)
// Check if the encrypted file exists
if _, err := os.Stat(encryptedFilePath); err == nil {
// Delete encrypted file
if err := os.Remove(encryptedFilePath); err != nil {
return fmt.Errorf("error removing encrypted file for secret %s: %s", secretName, err)
}
} else if !os.IsNotExist(err) {
// File exists but could not be accessed for some reason
return fmt.Errorf("error checking encrypted file for secret %s: %s", secretName, err)
}
}
// After successfully deleting all files, unset the resource ID
d.SetId("")
return nil
}
// executeSopsEncrypt encrypts a file with sops.
func executeSopsEncrypt(env string, awsProfile string, sourcePath string, destPath string) error {
key := fmt.Sprintf("SOPS_AGE_RECIPIENTS=$(aws ssm get-parameter --name /kubernetes/clusters/%s/age_public_key --with-decryption --query Parameter.Value --output text --profile %s --region us-east-1)", env, awsProfile)
cmd := exec.Command("bash", "-c", fmt.Sprintf("%s sops --config <(echo '') -e %s > %s", key, sourcePath, destPath))
var errb bytes.Buffer
cmd.Stderr = &errb
// Execute the command
err := cmd.Run()
if err != nil {
return fmt.Errorf("%s", errb.String())
}
return nil
}