-
Notifications
You must be signed in to change notification settings - Fork 8
/
combined.go
191 lines (156 loc) · 5.04 KB
/
combined.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
// Copyright 2022 Namespace Labs Inc; All rights reserved.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
package combined
import (
"context"
"sync"
"google.golang.org/protobuf/proto"
"google.golang.org/protobuf/types/known/anypb"
"namespacelabs.dev/foundation/framework/secrets"
"namespacelabs.dev/foundation/framework/secrets/localsecrets"
"namespacelabs.dev/foundation/internal/fnerrors"
"namespacelabs.dev/foundation/internal/protos"
"namespacelabs.dev/foundation/schema"
"namespacelabs.dev/foundation/std/cfg"
"namespacelabs.dev/foundation/std/pkggraph"
)
var secretProviders = map[string]func(context.Context, cfg.Configuration, secrets.SecretIdentifier, *anypb.Any) ([]byte, error){}
type SecretProvider[V proto.Message] interface {
Load(context.Context, V) ([]byte, error)
}
func RegisterSecretsProvider[V proto.Message](handle func(context.Context, cfg.Configuration, secrets.SecretIdentifier, V) ([]byte, error), aliases ...string) {
secretProviders[protos.TypeUrl[V]()] = func(ctx context.Context, conf cfg.Configuration, secretId secrets.SecretIdentifier, input *anypb.Any) ([]byte, error) {
msg := protos.NewFromType[V]()
if err := input.UnmarshalTo(msg); err != nil {
return nil, err
}
return handle(ctx, conf, secretId, msg)
}
}
type combinedSecrets struct {
envConf cfg.Configuration
// canonical secret ref -> secret binding
bindings map[string]*schema.Workspace_SecretBinding
local secrets.SecretsSource
mu sync.RWMutex
loaded map[string][]byte // secret ref -> value
loading map[string]*loadingSecret // secret ref -> loadingSecret
}
type resultPair struct {
value []byte
err error
}
type loadingSecret struct {
id secrets.SecretIdentifier
load func(context.Context, cfg.Configuration, secrets.SecretIdentifier, *anypb.Any) ([]byte, error)
cfg *anypb.Any
cs *combinedSecrets
mu sync.Mutex
waiters []chan resultPair
waiting int // The first waiter, will also get to the secret load.
done bool
result resultPair
}
func NewCombinedSecrets(env cfg.Context) (secrets.SecretsSource, error) {
local, err := localsecrets.NewLocalSecrets(env)
if err != nil {
return nil, err
}
bindings := map[string]*schema.Workspace_SecretBinding{}
for _, sb := range env.Workspace().Proto().SecretBinding {
if sb.Environment == "" || sb.Environment == env.Environment().Name {
bindings[sb.PackageRef.Canonical()] = sb
}
}
return &combinedSecrets{
envConf: env.Configuration(),
bindings: bindings,
local: local,
loaded: map[string][]byte{},
loading: map[string]*loadingSecret{},
}, nil
}
func (cs *combinedSecrets) Load(ctx context.Context, modules pkggraph.ModuleResolver, req *secrets.SecretLoadRequest) (*schema.SecretResult, error) {
cs.mu.RLock()
value := cs.loaded[req.GetSecretIdentifier().String()]
cs.mu.RUnlock()
if value != nil {
return &schema.SecretResult{Value: value, FileContents: &schema.FileContents{Contents: value}}, nil
}
if b, ok := cs.bindings[req.SecretRef.Canonical()]; ok {
p := secretProviders[b.Configuration.TypeUrl]
if p == nil {
return nil, fnerrors.BadInputError("%s: no such secrets provider", b.Configuration.TypeUrl)
}
cs.mu.Lock()
loading := cs.loading[req.GetSecretIdentifier().String()]
if loading == nil {
loading = &loadingSecret{
id: req.GetSecretIdentifier(),
load: p,
cfg: b.Configuration,
cs: cs,
}
cs.loading[req.GetSecretIdentifier().String()] = loading
}
cs.mu.Unlock()
value, err := loading.Get(ctx)
if err != nil {
return nil, err
}
return &schema.SecretResult{Value: value, FileContents: &schema.FileContents{Contents: value}}, nil
}
return cs.local.Load(ctx, modules, req)
}
func (cs *combinedSecrets) MissingError(missing *schema.PackageRef, missingSpec *schema.SecretSpec, missingServer schema.PackageName) error {
return cs.local.MissingError(missing, missingSpec, missingServer)
}
func (cs *combinedSecrets) complete(id secrets.SecretIdentifier, res []byte) {
cs.mu.Lock()
cs.loaded[id.String()] = res
cs.mu.Unlock()
}
func (l *loadingSecret) Get(ctx context.Context) ([]byte, error) {
l.mu.Lock()
rev := l.waiting
l.waiting++
if rev > 0 {
// Someone is already loading the secret.
if l.done {
defer l.mu.Unlock()
return l.result.value, l.result.err
}
// Very important that this is a buffered channel, else the write above will
// block forever and deadlock secret loading.
ch := make(chan resultPair, 1)
l.waiters = append(l.waiters, ch)
l.mu.Unlock()
select {
case v, ok := <-ch:
if !ok {
return nil, fnerrors.InternalError("unexpected eof")
}
return v.value, v.err
case <-ctx.Done():
return nil, ctx.Err()
}
}
l.mu.Unlock()
var res resultPair
res.value, res.err = l.load(ctx, l.cs.envConf, l.id, l.cfg)
l.mu.Lock()
l.done = true
l.result = res
if res.err == nil {
l.cs.complete(l.id, res.value)
}
waiters := l.waiters
l.waiters = nil
l.mu.Unlock()
for _, ch := range waiters {
ch <- res
close(ch)
}
return res.value, res.err
}