-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprocessor.go
292 lines (229 loc) · 8.03 KB
/
processor.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
package krmfnsealedsecretfrom1password
import (
"bytes"
"context"
"crypto/rand"
"crypto/rsa"
"encoding/base64"
"errors"
"io"
"log/slog"
"strings"
"github.com/1password/onepassword-sdk-go"
ssv1alpha1 "github.com/bitnami-labs/sealed-secrets/pkg/apis/sealedsecrets/v1alpha1"
"github.com/bitnami-labs/sealed-secrets/pkg/crypto"
"github.com/bitnami-labs/sealed-secrets/pkg/kubeseal"
"sigs.k8s.io/kustomize/kyaml/fn/framework"
"sigs.k8s.io/kustomize/kyaml/yaml"
)
type (
// Processor processes SealedSecrets in a ResourceList by resolving references to 1Password secrets.
Processor struct {
//nolint:containedctx
ctx context.Context // yes you shouldn't do this
client *onepassword.Client
randSrc io.Reader
}
// Config is the configuration for the function.
Config struct {
// Token is the 1Password service account token.
Token string `flag:"required" json:"onePasswordServiceAccountToken" param:"onepassword-service-account-token,t"`
// CertString is the certificate used to seal the secrets
CertString string `flag:"required" json:"sealingCert" param:"sealing-cert,c"`
}
// ProcessorOption is a function that configures a Processor.
ProcessorOption func(*Processor)
)
var (
// ErrLoadConfig is returned when the function configuration cannot be loaded, such as not having the required fields.
ErrLoadConfig = errors.New("unable to load function config")
// ErrConfigCertNotValid is returned when the sealing certificate in the config is not valid.
ErrConfigCertNotValid = errors.New("cert in config is not valid")
// ErrMissingToken is returned when the 1Password service account token is missing.
ErrMissingToken = errors.New("missing 1Password service account token")
// ErrMissingCert is returned when the sealing certificate is missing.
ErrMissingCert = errors.New("missing sealing certificate")
// ErrUnmarshalSealedSecret is returned when the SealedSecret cannot be unmarshalled.
ErrUnmarshalSealedSecret = errors.New("error unmarshalling SealedSecret")
// ErrResolveSecret is returned when the secret cannot be resolved from 1Password.
ErrResolveSecret = errors.New("error resolving secret from 1Password")
// ErrProcessSealedSecret is returned when there is an error processing a SealedSecret.
ErrProcessSealedSecret = errors.New("error processing SealedSecret")
// ErrEncryptSecret is returned when there is an error encrypting a secret.
ErrEncryptSecret = errors.New("error encrypting secret")
)
// Validate validates the function configuration. This is run automatically by the framework library.
func (c Config) Validate() error {
var errs []error
if c.Token == "" {
errs = append(errs, ErrMissingToken)
}
if c.CertString == "" {
errs = append(errs, ErrMissingCert)
}
return errors.Join(errs...)
}
// Cert returns the sealing certificate from the configuration.
func (c Config) Cert() (*rsa.PublicKey, error) {
cert, err := kubeseal.ParseKey(bytes.NewReader([]byte(c.CertString)))
if err != nil {
return nil, errors.Join(ErrConfigCertNotValid, err)
}
return cert, nil
}
func isSealedSecret(node *yaml.RNode) bool {
meta, err := node.GetValidatedMetadata()
if err != nil {
return false
}
return meta.Kind == "SealedSecret"
}
// Process processes the input ResourceList.
//
//nolint:funlen
func (p Processor) Process(input *framework.ResourceList) error {
var cfg Config
slog.DebugContext(p.ctx, "loading function config", "input", input, "cfg", input.FunctionConfig)
err := framework.LoadFunctionConfig(input.FunctionConfig, &cfg)
if err != nil {
return errors.Join(ErrLoadConfig, err)
}
slog.DebugContext(p.ctx, "loaded config", "token", cfg.Token, "certString", cfg.CertString)
slog.DebugContext(p.ctx, "ensuring 1Password client")
client, err := ensureClient(p.ctx, p.client, cfg.Token)
if err != nil {
slog.ErrorContext(p.ctx, "error ensuring 1Password client", "err", err)
return err
}
slog.DebugContext(p.ctx, "parsing cert")
cert, err := cfg.Cert()
if err != nil {
return err
}
slog.DebugContext(p.ctx, "processing resource list", "itemCount", len(input.Items))
for idx := range input.Items {
resource := input.Items[idx]
slog.DebugContext(
p.ctx, "decoding resource", "idx", idx, "kind", resource.GetKind(),
"name", resource.GetName(), "namespace", resource.GetNamespace(),
)
if !isSealedSecret(resource) {
slog.DebugContext(p.ctx, "resource is not a SealedSecret", "idx", idx)
continue
}
if err != nil {
return errors.Join(ErrUnmarshalSealedSecret, err)
}
encryptedDataNode, err := resource.Pipe(yaml.Lookup("spec", "encryptedData"))
if err != nil {
slog.ErrorContext(p.ctx, "cannot retrieve spec.encryptedData", "name", resource.GetName(), "err", err.Error())
return errors.Join(ErrProcessSealedSecret, err)
}
if encryptedDataNode.IsNilOrEmpty() {
slog.DebugContext(p.ctx, "encryptedData is empty")
continue
}
// TODO: Allow configurable scopes
err = encryptedDataNode.VisitFields(
resolveSecretFunc(
p.ctx, client, p.randSrc,
resource.GetName(), resource.GetNamespace(), ssv1alpha1.NamespaceWideScope, cert,
),
)
if err != nil {
return errors.Join(ErrProcessSealedSecret, err)
}
}
return nil
}
func resolveSecretFunc(
ctx context.Context,
client *onepassword.Client,
randSrc io.Reader,
secretName, secretNamespace string,
scope ssv1alpha1.SealingScope,
sealingCert *rsa.PublicKey,
) func(*yaml.MapNode) error {
return func(mapNode *yaml.MapNode) error {
key := strings.TrimSpace(mapNode.Key.MustString())
value := strings.TrimSpace(mapNode.Value.MustString())
slog.DebugContext(ctx, "resolveSecretFunc", "key", key, "value", value)
if value == "op://Vault Name/secret" {
slog.DebugContext(ctx, "matches")
}
ref, err := SecretReferenceFromString(ctx, value)
// Assume that data fields that aren't secret references are already encrypted values. This allows
// mixing and matching directly sealed values with 1Password references, even within the same SealedSecret.
if errors.Is(err, ErrInvalidSecretReference) {
slog.DebugContext(ctx, "skipping non-secret reference", "key", key, "err", err)
return nil
} else if err != nil {
return err
}
secret, err := client.Secrets.Resolve(ctx, ref.String())
if err != nil {
return errors.Join(ErrResolveSecret, err)
}
sealedSecret, err := sealSecret(randSrc, secretName, secretNamespace, []byte(secret), scope, sealingCert)
if err != nil {
return errors.Join(ErrEncryptSecret, err)
}
slog.DebugContext(ctx, "setting secret")
mapNode.Value.SetYNode(&yaml.Node{Kind: yaml.ScalarNode, Value: sealedSecret})
return nil
}
}
func ensureClient(ctx context.Context, client *onepassword.Client, token string) (*onepassword.Client, error) {
if client == nil {
slog.InfoContext(ctx, "creating new 1Password client")
newClient, err := NewClient(ctx, token)
if err != nil {
return nil, err
}
return newClient, nil
}
return client, nil
}
// NewProcessor creates a new Processor with the given options.
func NewProcessor(opts ...ProcessorOption) Processor {
proc := &Processor{
ctx: context.Background(),
randSrc: rand.Reader,
}
for _, opt := range opts {
opt(proc)
}
return *proc
}
// WithContext sets the context for the Processor.
func WithContext(ctx context.Context) ProcessorOption {
return func(p *Processor) {
p.ctx = ctx
}
}
// WithClient sets the 1Password client for the Processor.
func WithClient(client *onepassword.Client) ProcessorOption {
return func(p *Processor) {
p.client = client
}
}
// WithRandSrc sets the source of random bytes for crypto operations for the Processor.
func WithRandSrc(randSrc io.Reader) ProcessorOption {
return func(p *Processor) {
p.randSrc = randSrc
}
}
func sealSecret(
randSrc io.Reader,
secretName, secretNamespace string,
data []byte,
scope ssv1alpha1.SealingScope,
pubKey *rsa.PublicKey,
) (string, error) {
label := ssv1alpha1.EncryptionLabel(secretNamespace, secretName, scope)
out, err := crypto.HybridEncrypt(randSrc, pubKey, data, label)
if err != nil {
return "", errors.Join(ErrEncryptSecret, err)
}
return base64.StdEncoding.EncodeToString(out), nil
}