forked from pulumi/pulumi
-
Notifications
You must be signed in to change notification settings - Fork 0
/
manager.go
341 lines (292 loc) 路 11.1 KB
/
manager.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
// Copyright 2016-2022, Pulumi Corporation.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Package passphrase implements support for a local passphrase secret manager.
package passphrase
import (
"context"
cryptorand "crypto/rand"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"io"
"os"
"path/filepath"
"strings"
"sync"
"github.com/pulumi/pulumi/pkg/v3/secrets"
"github.com/pulumi/pulumi/sdk/v3/go/common/diag"
"github.com/pulumi/pulumi/sdk/v3/go/common/resource/config"
"github.com/pulumi/pulumi/sdk/v3/go/common/util/cmdutil"
"github.com/pulumi/pulumi/sdk/v3/go/common/util/contract"
)
const Type = "passphrase"
var ErrIncorrectPassphrase = errors.New("incorrect passphrase")
// given a passphrase and an encryption state, construct a Crypter from it. Our encryption
// state value is a version tag followed by version specific state information. Presently, we only have one version
// we support (`v1`) which is AES-256-GCM using a key derived from a passphrase using 1,000,000 iterations of PDKDF2
// using SHA256.
func symmetricCrypterFromPhraseAndState(phrase string, state string) (config.Crypter, error) {
splits := strings.SplitN(state, ":", 3)
if len(splits) != 3 {
return nil, errors.New("malformed state value")
}
if splits[0] != "v1" {
return nil, errors.New("unknown state version")
}
salt, err := base64.StdEncoding.DecodeString(splits[1])
if err != nil {
return nil, err
}
decrypter := config.NewSymmetricCrypterFromPassphrase(phrase, salt)
// symmetricCrypter does not use ctx, safe to pass context.Background()
ignoredCtx := context.Background()
decrypted, err := decrypter.DecryptValue(ignoredCtx, state[indexN(state, ":", 2)+1:])
if err != nil || decrypted != "pulumi" {
return nil, ErrIncorrectPassphrase
}
return decrypter, nil
}
func indexN(s string, substr string, n int) int {
contract.Require(n > 0, "n")
scratch := s
for i := n; i > 0; i-- {
idx := strings.Index(scratch, substr)
if i == -1 {
return -1
}
scratch = scratch[idx+1:]
}
return len(s) - (len(scratch) + len(substr))
}
type localSecretsManagerState struct {
Salt string `json:"salt"`
}
var _ secrets.Manager = &localSecretsManager{}
type localSecretsManager struct {
state localSecretsManagerState
crypter config.Crypter
}
func (sm *localSecretsManager) Type() string {
return Type
}
func (sm *localSecretsManager) State() interface{} {
return sm.state
}
func (sm *localSecretsManager) Decrypter() (config.Decrypter, error) {
contract.Assert(sm.crypter != nil)
return sm.crypter, nil
}
func (sm *localSecretsManager) Encrypter() (config.Encrypter, error) {
contract.Assert(sm.crypter != nil)
return sm.crypter, nil
}
var lock sync.Mutex
var cache map[string]secrets.Manager
// clearCachedSecretsManagers is used to clear the cache, for tests.
func clearCachedSecretsManagers() {
lock.Lock()
defer lock.Unlock()
cache = nil
}
// getCachedSecretsManager returns a cached secret manager and true, or nil and false if not in the cache.
func getCachedSecretsManager(state string) (secrets.Manager, bool) {
lock.Lock()
defer lock.Unlock()
sm, ok := cache[state]
return sm, ok
}
// setCachedSecretsManager saves a secret manager in the cache.
func setCachedSecretsManager(state string, sm secrets.Manager) {
lock.Lock()
defer lock.Unlock()
if cache == nil {
cache = make(map[string]secrets.Manager)
}
cache[state] = sm
}
func NewPassphaseSecretsManager(phrase string, state string) (secrets.Manager, error) {
// Check the cache first, if we have already seen this state before, return a cached value.
if cached, ok := getCachedSecretsManager(state); ok {
return cached, nil
}
// Wasn't in the cache so try to construct it and add it if there's no error.
crypter, err := symmetricCrypterFromPhraseAndState(phrase, state)
if err != nil {
return nil, err
}
sm := &localSecretsManager{
crypter: crypter,
state: localSecretsManagerState{
Salt: state,
},
}
setCachedSecretsManager(state, sm)
return sm, nil
}
// NewPromptingPassphraseSecretsManager returns a new passphrase-based secrets manager, from the
// given state. Will use the passphrase found in PULUMI_CONFIG_PASSPHRASE, the file specified by
// PULUMI_CONFIG_PASSPHRASE_FILE, or otherwise will prompt for the passphrase if interactive.
func NewPromptingPassphraseSecretsManager(state string) (secrets.Manager, error) {
// Check the cache first, if we have already seen this state before, return a cached value.
if cached, ok := getCachedSecretsManager(state); ok {
return cached, nil
}
// Otherwise, prompt for the password.
const prompt = "Enter your passphrase to unlock config/secrets\n" +
" (set PULUMI_CONFIG_PASSPHRASE or PULUMI_CONFIG_PASSPHRASE_FILE to remember)"
for {
phrase, interactive, phraseErr := readPassphrase(prompt, true /*useEnv*/)
if phraseErr != nil {
return nil, phraseErr
}
sm, smerr := NewPassphaseSecretsManager(phrase, state)
switch {
case interactive && smerr == ErrIncorrectPassphrase:
cmdutil.Diag().Errorf(diag.Message("", "incorrect passphrase"))
continue
case smerr != nil:
return nil, smerr
default:
return sm, nil
}
}
}
// NewPassphaseSecretsManagerFromState returns a new passphrase-based secrets manager, from the
// given state. Will use the passphrase found in PULUMI_CONFIG_PASSPHRASE, the file specified by
// PULUMI_CONFIG_PASSPHRASE_FILE, or otherwise will prompt for the passphrase if interactive.
func NewPromptingPassphaseSecretsManagerFromState(state json.RawMessage) (secrets.Manager, error) {
var s localSecretsManagerState
if err := json.Unmarshal(state, &s); err != nil {
return nil, fmt.Errorf("unmarshalling state: %w", err)
}
sm, err := NewPromptingPassphraseSecretsManager(s.Salt)
switch {
case err == ErrIncorrectPassphrase:
return newLockedPasspharseSecretsManager(s), nil
case err != nil:
return nil, fmt.Errorf("constructing secrets manager: %w", err)
default:
return sm, nil
}
}
// PromptForNewPassphrase prompts for a new passphrase, and returns the state and the secrets manager.
func PromptForNewPassphrase(rotate bool) (string, secrets.Manager, error) {
var phrase string
// Get a the passphrase from the user, ensuring that they match.
for {
firstMessage := "Enter your passphrase to protect config/secrets"
if rotate {
firstMessage = "Enter your new passphrase to protect config/secrets"
if !isInteractive() {
text, err := io.ReadAll(os.Stdin)
if err != nil {
return "", nil, err
}
phrase = strings.TrimSpace(string(text))
break
}
}
// Here, the stack does not have an EncryptionSalt, so we will get a passphrase and create one
first, _, err := readPassphrase(firstMessage, !rotate)
if err != nil {
return "", nil, err
}
secondMessage := "Re-enter your passphrase to confirm"
if rotate {
secondMessage = "Re-enter your new passphrase to confirm"
}
second, _, err := readPassphrase(secondMessage, !rotate)
if err != nil {
return "", nil, err
}
if first == second {
phrase = first
break
}
// If they didn't match, print an error and try again
cmdutil.Diag().Errorf(diag.Message("", "passphrases do not match"))
}
// Produce a new salt.
salt := make([]byte, 8)
_, err := cryptorand.Read(salt)
contract.AssertNoErrorf(err, "could not read from system random")
// Encrypt a message and store it with the salt so we can test if the password is correct later.
crypter := config.NewSymmetricCrypterFromPassphrase(phrase, salt)
// symmetricCrypter does not use ctx, safe to use context.Background()
ignoredCtx := context.Background()
msg, err := crypter.EncryptValue(ignoredCtx, "pulumi")
contract.AssertNoError(err)
// Encode the salt as the passphrase secrets manager state.
state := fmt.Sprintf("v1:%s:%s", base64.StdEncoding.EncodeToString(salt), msg)
// Create the secrets manager using the state.
sm, err := NewPassphaseSecretsManager(phrase, state)
if err != nil {
return "", nil, err
}
// Return both the state and the secrets manager.
return state, sm, nil
}
func readPassphrase(prompt string, useEnv bool) (phrase string, interactive bool, err error) {
if useEnv {
if phrase, ok := os.LookupEnv("PULUMI_CONFIG_PASSPHRASE"); ok {
return phrase, false, nil
}
if phraseFile, ok := os.LookupEnv("PULUMI_CONFIG_PASSPHRASE_FILE"); ok && phraseFile != "" {
phraseFilePath, err := filepath.Abs(phraseFile)
if err != nil {
return "", false, fmt.Errorf("unable to construct a path the PULUMI_CONFIG_PASSPHRASE_FILE: %w", err)
}
phraseDetails, err := os.ReadFile(phraseFilePath)
if err != nil {
return "", false, fmt.Errorf("unable to read PULUMI_CONFIG_PASSPHRASE_FILE: %w", err)
}
return strings.TrimSpace(string(phraseDetails)), false, nil
}
if !isInteractive() {
return "", false, errors.New("passphrase must be set with PULUMI_CONFIG_PASSPHRASE or " +
"PULUMI_CONFIG_PASSPHRASE_FILE environment variables")
}
}
phrase, err = cmdutil.ReadConsoleNoEcho(prompt)
return phrase, true, err
}
func isInteractive() bool {
test, ok := os.LookupEnv("PULUMI_TEST_PASSPHRASE")
return cmdutil.Interactive() || ok && cmdutil.IsTruthy(test)
}
// newLockedPasspharseSecretsManager returns a Passphrase secrets manager that has the correct state, but can not
// encrypt or decrypt anything. This is helpful today for some cases, because we have operations that roundtrip
// checkpoints and we'd like to continue to support these operations even if we don't have the correct passphrase. But
// if we never end up having to call encrypt or decrypt, this provider will be sufficient. Since it has the correct
// state, we ensure that when we roundtrip, we don't lose the state stored in the deployment.
func newLockedPasspharseSecretsManager(state localSecretsManagerState) secrets.Manager {
return &localSecretsManager{
state: state,
crypter: &errorCrypter{},
}
}
type errorCrypter struct{}
func (ec *errorCrypter) EncryptValue(ctx context.Context, _ string) (string, error) {
return "", errors.New("failed to encrypt: incorrect passphrase, please set PULUMI_CONFIG_PASSPHRASE to the " +
"correct passphrase or set PULUMI_CONFIG_PASSPHRASE_FILE to a file containing the passphrase")
}
func (ec *errorCrypter) DecryptValue(ctx context.Context, _ string) (string, error) {
return "", errors.New("failed to decrypt: incorrect passphrase, please set PULUMI_CONFIG_PASSPHRASE to the " +
"correct passphrase or set PULUMI_CONFIG_PASSPHRASE_FILE to a file containing the passphrase")
}
func (ec *errorCrypter) BulkDecrypt(ctx context.Context, _ []string) (map[string]string, error) {
return nil, errors.New("failed to decrypt: incorrect passphrase, please set PULUMI_CONFIG_PASSPHRASE to the " +
"correct passphrase or set PULUMI_CONFIG_PASSPHRASE_FILE to a file containing the passphrase")
}