-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathencryption.go
More file actions
428 lines (367 loc) · 11.6 KB
/
Copy pathencryption.go
File metadata and controls
428 lines (367 loc) · 11.6 KB
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
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
// SPDX-License-Identifier: Apache-2.0
package git
import (
"context"
"crypto/sha256"
"encoding/hex"
"errors"
"fmt"
"os"
"path/filepath"
"regexp"
"sort"
"strings"
"filippo.io/age"
corev1 "k8s.io/api/core/v1"
k8stypes "k8s.io/apimachinery/pkg/types"
"sigs.k8s.io/controller-runtime/pkg/client"
"github.com/ConfigButler/gitops-reverser/api/v1alpha3"
itypes "github.com/ConfigButler/gitops-reverser/internal/types"
)
// ResourceMeta is passed to encryptors for context and diagnostics.
type ResourceMeta struct {
Identifier itypes.ResourceIdentifier
UID string
ResourceVersion string
Generation int64
}
// Encryptor transforms plaintext bytes into encrypted bytes.
type Encryptor interface {
Encrypt(ctx context.Context, plain []byte, meta ResourceMeta) ([]byte, error)
}
const (
// EncryptionProviderSOPS is the only supported provider in this increment.
EncryptionProviderSOPS = "sops"
// defaultSOPSBinaryPath is resolved from PATH in the controller runtime image.
defaultSOPSBinaryPath = "sops"
// sopsAgeKeyFileEnvVar points SOPS to a file containing age private identities.
sopsAgeKeyFileEnvVar = "SOPS" + "_AGE_KEY_FILE"
// ageSecretKeySuffix identifies Flux-compatible age private-key entries.
ageSecretKeySuffix = ".agekey"
// ageIdentityFileDir is the temp directory used for SOPS age identity files.
ageIdentityFileDir = "gitops-reverser-age-identities"
)
var envVarNamePattern = regexp.MustCompile(`^[A-Za-z_][A-Za-z0-9_]*$`)
// ResolvedEncryptionConfig contains runtime encryption settings resolved from GitTarget spec.
type ResolvedEncryptionConfig struct {
Provider string
Environment map[string]string
AgeRecipients []string
AgeIdentities []string
}
// ResolveTargetEncryption resolves and validates GitTarget encryption configuration.
func ResolveTargetEncryption(
ctx context.Context,
k8sClient client.Client,
target *v1alpha3.GitTarget,
) (*ResolvedEncryptionConfig, error) {
if target.Spec.Encryption == nil {
return nil, nil //nolint:nilnil // nil means encryption disabled
}
encryptionSpec := target.Spec.Encryption
providerName, err := resolveEncryptionProvider(encryptionSpec)
if err != nil {
return nil, err
}
ageSpec := encryptionSpec.Age
if ageSpec == nil || !ageSpec.Enabled {
return nil, nil //nolint:nilnil // nil means encryption disabled for current provider implementation
}
publicRecipients, err := normalizePublicAgeRecipients(ageSpec.Recipients.PublicKeys)
if err != nil {
return nil, err
}
secretRecipients, secretIdentities, environment, err := resolveSecretRecipientsAndEnvironment(
ctx,
k8sClient,
target,
encryptionSpec,
)
if err != nil {
return nil, err
}
resolvedRecipients := dedupeAndSortRecipients(append(publicRecipients, secretRecipients...))
if len(resolvedRecipients) == 0 {
return nil, errors.New(
"encryption.age.enabled=true requires at least one resolved recipient from age.recipients.publicKeys or secret *.agekey entries",
)
}
environment = normalizeEnvironment(environment)
return &ResolvedEncryptionConfig{
Provider: providerName,
Environment: environment,
AgeRecipients: resolvedRecipients,
AgeIdentities: secretIdentities,
}, nil
}
func resolveEncryptionProvider(encryptionSpec *v1alpha3.EncryptionSpec) (string, error) {
providerName := strings.TrimSpace(encryptionSpec.Provider)
if providerName == "" {
providerName = EncryptionProviderSOPS
}
if providerName != EncryptionProviderSOPS {
return "", fmt.Errorf("unsupported encryption provider %q", encryptionSpec.Provider)
}
return providerName, nil
}
func resolveSecretRecipientsAndEnvironment(
ctx context.Context,
k8sClient client.Client,
target *v1alpha3.GitTarget,
encryptionSpec *v1alpha3.EncryptionSpec,
) ([]string, []string, map[string]string, error) {
if encryptionSpec.Age == nil || !encryptionSpec.Age.Recipients.ExtractFromSecret {
return nil, nil, nil, nil
}
secretKind := strings.TrimSpace(encryptionSpec.SecretRef.Kind)
if secretKind != "" && secretKind != "Secret" {
return nil, nil, nil, fmt.Errorf(
"encryption.secretRef.kind must be Secret, got %q",
encryptionSpec.SecretRef.Kind,
)
}
secretName := strings.TrimSpace(encryptionSpec.SecretRef.Name)
if secretName == "" {
return nil, nil, nil, errors.New(
"encryption.secretRef.name must be set when age.recipients.extractFromSecret=true",
)
}
secret, secretKey, err := getEncryptionSecret(ctx, k8sClient, target.Namespace, secretName)
if err != nil {
return nil, nil, nil, err
}
secretRecipients, secretIdentities, err := resolveAgeRecipientsFromSecret(secret.Data)
if err != nil {
return nil, nil, nil, fmt.Errorf("failed to resolve recipients from encryption secret %s: %w", secretKey, err)
}
environment := toSOPSEnvironment(secret.Data)
return secretRecipients, secretIdentities, environment, nil
}
func getEncryptionSecret(
ctx context.Context,
k8sClient client.Client,
namespace string,
secretName string,
) (*corev1.Secret, k8stypes.NamespacedName, error) {
secretKey := k8stypes.NamespacedName{
Name: secretName,
Namespace: namespace,
}
var secret corev1.Secret
if err := k8sClient.Get(ctx, secretKey, &secret); err != nil {
return nil, secretKey, fmt.Errorf("failed to fetch encryption secret %s: %w", secretKey, err)
}
return &secret, secretKey, nil
}
func normalizeEnvironment(environment map[string]string) map[string]string {
if len(environment) == 0 {
return nil
}
return environment
}
func configureSecretEncryptionWriter(
writer *contentWriter,
workDir string,
cfg *ResolvedEncryptionConfig,
) error {
if cfg == nil {
writer.setEncryptor(nil, "")
return nil
}
switch cfg.Provider {
case EncryptionProviderSOPS:
environment, err := buildSOPSEnvironment(workDir, cfg)
if err != nil {
return err
}
scope := secretEncryptionCacheScope(workDir, cfg)
writer.setEncryptor(NewSOPSEncryptorWithEnv(defaultSOPSBinaryPath, "", workDir, environment), scope)
return nil
default:
return fmt.Errorf("unsupported encryption provider %q", cfg.Provider)
}
}
func secretEncryptionCacheScope(workDir string, cfg *ResolvedEncryptionConfig) string {
if cfg == nil {
return ""
}
hasher := sha256.New()
hasher.Write([]byte(strings.TrimSpace(cfg.Provider)))
hasher.Write([]byte{0})
hasher.Write([]byte(strings.TrimSpace(workDir)))
hasher.Write([]byte{0})
for _, recipient := range cfg.AgeRecipients {
hasher.Write([]byte(strings.TrimSpace(recipient)))
hasher.Write([]byte{0})
}
for _, identity := range cfg.AgeIdentities {
hasher.Write([]byte(strings.TrimSpace(identity)))
hasher.Write([]byte{0})
}
sum := hasher.Sum(nil)
return hex.EncodeToString(sum[:16])
}
func buildSOPSEnvironment(workDir string, cfg *ResolvedEncryptionConfig) (map[string]string, error) {
environment := cloneEnvironment(cfg.Environment)
if len(cfg.AgeIdentities) == 0 {
return environment, nil
}
ageKeyFilePath, err := writeAgeIdentityFile(workDir, cfg.AgeIdentities)
if err != nil {
return nil, fmt.Errorf("failed to write SOPS age identity file: %w", err)
}
if environment == nil {
environment = make(map[string]string, 1)
}
environment[sopsAgeKeyFileEnvVar] = ageKeyFilePath
return environment, nil
}
func cloneEnvironment(environment map[string]string) map[string]string {
if len(environment) == 0 {
return nil
}
cloned := make(map[string]string, len(environment))
for key, value := range environment {
cloned[key] = value
}
return cloned
}
func writeAgeIdentityFile(workDir string, identities []string) (string, error) {
if len(identities) == 0 {
return "", errors.New("no age identities provided")
}
dirPath := filepath.Join(os.TempDir(), ageIdentityFileDir)
if err := os.MkdirAll(dirPath, 0700); err != nil {
return "", fmt.Errorf("create age identity directory: %w", err)
}
keyHash := sha256.Sum256([]byte(strings.TrimSpace(workDir)))
fileName := hex.EncodeToString(keyHash[:8]) + ageSecretKeySuffix
filePath := filepath.Join(dirPath, fileName)
fileContent := strings.Join(identities, "\n") + "\n"
if err := os.WriteFile(filePath, []byte(fileContent), 0600); err != nil {
return "", fmt.Errorf("write age identity file: %w", err)
}
return filePath, nil
}
func toSOPSEnvironment(secretData map[string][]byte) map[string]string {
if len(secretData) == 0 {
return nil
}
environment := make(map[string]string, len(secretData))
for key, value := range secretData {
if !envVarNamePattern.MatchString(key) {
continue
}
environment[key] = string(value)
}
if len(environment) == 0 {
return nil
}
return environment
}
func resolveAgeRecipientsFromSecret(secretData map[string][]byte) ([]string, []string, error) {
if len(secretData) == 0 {
return nil, nil, nil
}
recipients := make([]string, 0, len(secretData))
identities := make([]string, 0, len(secretData))
for key, value := range secretData {
if !strings.HasSuffix(key, ageSecretKeySuffix) {
continue
}
recipient, identity, err := deriveAgeRecipientFromSecretEntry(key, string(value))
if err != nil {
return nil, nil, err
}
recipients = append(recipients, recipient)
identities = append(identities, identity)
}
return dedupeAndSortRecipients(recipients), dedupeAndSortIdentities(identities), nil
}
func normalizePublicAgeRecipients(publicKeys []string) ([]string, error) {
if len(publicKeys) == 0 {
return nil, nil
}
recipients := make([]string, 0, len(publicKeys))
for i, publicKey := range publicKeys {
trimmed := strings.TrimSpace(publicKey)
if trimmed == "" {
continue
}
recipient, err := age.ParseX25519Recipient(trimmed)
if err != nil {
return nil, fmt.Errorf("invalid age recipient in age.recipients.publicKeys[%d]: %w", i, err)
}
recipients = append(recipients, recipient.String())
}
return dedupeAndSortRecipients(recipients), nil
}
func deriveAgeRecipientFromSecretEntry(secretKey, secretValue string) (string, string, error) {
lines := strings.Split(secretValue, "\n")
identities := make([]string, 0, len(lines))
for _, line := range lines {
trimmed := strings.TrimSpace(line)
if trimmed == "" || strings.HasPrefix(trimmed, "#") {
continue
}
identities = append(identities, trimmed)
}
if len(identities) == 0 {
return "", "", fmt.Errorf("%s must contain one AGE-SECRET-KEY identity", secretKey)
}
if len(identities) > 1 {
return "", "", fmt.Errorf("%s must contain exactly one AGE-SECRET-KEY identity", secretKey)
}
if !strings.HasPrefix(identities[0], "AGE-SECRET-KEY-") {
return "", "", fmt.Errorf("%s must contain AGE-SECRET-KEY identity", secretKey)
}
identity, err := age.ParseX25519Identity(identities[0])
if err != nil {
return "", "", fmt.Errorf("invalid %s identity: %w", secretKey, err)
}
return identity.Recipient().String(), identity.String(), nil
}
func dedupeAndSortRecipients(recipients []string) []string {
if len(recipients) == 0 {
return nil
}
uniq := make(map[string]struct{}, len(recipients))
for _, recipient := range recipients {
trimmed := strings.TrimSpace(recipient)
if trimmed == "" {
continue
}
uniq[trimmed] = struct{}{}
}
if len(uniq) == 0 {
return nil
}
result := make([]string, 0, len(uniq))
for recipient := range uniq {
result = append(result, recipient)
}
sort.Strings(result)
return result
}
func dedupeAndSortIdentities(identities []string) []string {
if len(identities) == 0 {
return nil
}
uniq := make(map[string]struct{}, len(identities))
for _, identity := range identities {
trimmed := strings.TrimSpace(identity)
if trimmed == "" {
continue
}
uniq[trimmed] = struct{}{}
}
if len(uniq) == 0 {
return nil
}
result := make([]string, 0, len(uniq))
for identity := range uniq {
result = append(result, identity)
}
sort.Strings(result)
return result
}