-
Notifications
You must be signed in to change notification settings - Fork 484
/
init.go
708 lines (608 loc) · 24.1 KB
/
init.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
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
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
/*******************************************************************************
* Copyright 2021 Intel Corporation
* Copyright 2019 Dell Inc.
*
* 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 secretstore
import (
"context"
"crypto/sha256"
"encoding/json"
"errors"
"fmt"
"net/http"
"os"
"path/filepath"
"regexp"
"strings"
"sync"
"time"
"github.com/edgexfoundry/edgex-go/internal"
"github.com/edgexfoundry/edgex-go/internal/security/kdf"
"github.com/edgexfoundry/edgex-go/internal/security/pipedhexreader"
"github.com/edgexfoundry/edgex-go/internal/security/secretstore/config"
"github.com/edgexfoundry/edgex-go/internal/security/secretstore/container"
"github.com/edgexfoundry/edgex-go/internal/security/secretstore/secretsengine"
"github.com/edgexfoundry/edgex-go/internal/security/secretstore/tokenfilewriter"
bootstrapContainer "github.com/edgexfoundry/go-mod-bootstrap/v2/bootstrap/container"
"github.com/edgexfoundry/go-mod-bootstrap/v2/bootstrap/startup"
"github.com/edgexfoundry/go-mod-bootstrap/v2/di"
"github.com/edgexfoundry/go-mod-core-contracts/v2/clients/logger"
"github.com/edgexfoundry/go-mod-secrets/v2/pkg"
"github.com/edgexfoundry/go-mod-secrets/v2/pkg/token/fileioperformer"
"github.com/edgexfoundry/go-mod-secrets/v2/pkg/types"
"github.com/edgexfoundry/go-mod-secrets/v2/secrets"
)
const (
addKnownSecretsEnv = "ADD_KNOWN_SECRETS"
redisSecretName = "redisdb"
knownSecretSeparator = ","
serviceListBegin = "["
serviceListEnd = "]"
serviceListSeparator = ";"
secretBasePath = "/v1/secret/edgex" // nolint:gosec
)
var errNotFound = errors.New("credential NOT found")
type Bootstrap struct {
insecureSkipVerify bool
vaultInterval int
validKnownSecrets map[string]bool
}
func NewBootstrap(insecureSkipVerify bool, vaultInterval int) *Bootstrap {
return &Bootstrap{
insecureSkipVerify: insecureSkipVerify,
vaultInterval: vaultInterval,
validKnownSecrets: map[string]bool{redisSecretName: true},
}
}
// BootstrapHandler fulfills the BootstrapHandler contract and performs initialization needed by the data service.
func (b *Bootstrap) BootstrapHandler(ctx context.Context, _ *sync.WaitGroup, _ startup.Timer, dic *di.Container) bool {
configuration := container.ConfigurationFrom(dic.Get)
secretStoreConfig := configuration.SecretStore
kongAdminConfig := configuration.KongAdmin
lc := bootstrapContainer.LoggingClientFrom(dic.Get)
//step 1: boot up secretstore general steps same as other EdgeX microservice
//step 2: initialize the communications
fileOpener := fileioperformer.NewDefaultFileIoPerformer()
var httpCaller internal.HttpCaller
if caFilePath := secretStoreConfig.CaFilePath; caFilePath != "" {
lc.Info("using certificate verification for secret store connection")
caReader, err := fileOpener.OpenFileReader(caFilePath, os.O_RDONLY, 0400)
if err != nil {
lc.Errorf("failed to load CA certificate: %s", err.Error())
return false
}
httpCaller = pkg.NewRequester(lc).WithTLS(caReader, secretStoreConfig.ServerName)
} else {
lc.Info("bypassing certificate verification for secret store connection")
httpCaller = pkg.NewRequester(lc).Insecure()
}
intervalDuration := time.Duration(b.vaultInterval) * time.Second
clientConfig := types.SecretConfig{
Type: secretStoreConfig.Type,
Protocol: secretStoreConfig.Protocol,
Host: secretStoreConfig.Host,
Port: secretStoreConfig.Port,
}
client, err := secrets.NewSecretStoreClient(clientConfig, lc, httpCaller)
if err != nil {
lc.Errorf("failed to create SecretStoreClient: %s", err.Error())
return false
}
lc.Info("SecretStoreClient created")
pipedHexReader := pipedhexreader.NewPipedHexReader()
keyDeriver := kdf.NewKdf(fileOpener, secretStoreConfig.TokenFolderPath, sha256.New)
vmkEncryption := NewVMKEncryption(fileOpener, pipedHexReader, keyDeriver)
hook := os.Getenv("IKM_HOOK")
if len(hook) > 0 {
err := vmkEncryption.LoadIKM(hook)
defer vmkEncryption.WipeIKM() // Ensure IKM is wiped from memory
if err != nil {
lc.Errorf("failed to setup vault master key encryption: %s", err.Error())
return false
}
lc.Info("Enabled encryption of Vault master key")
} else {
lc.Info("vault master key encryption not enabled. IKM_HOOK not set.")
}
var initResponse types.InitResponse // reused many places in below flow
//step 3: initialize and unseal Vault
for shouldContinue := true; shouldContinue; {
// Anonymous function used to prevent file handles from accumulating
terminalFailure := func() bool {
sCode, _ := client.HealthCheck()
switch sCode {
case http.StatusOK:
// Load the init response from disk since we need it to regenerate root token later
if err := loadInitResponse(lc, fileOpener, secretStoreConfig, &initResponse); err != nil {
lc.Errorf("unable to load init response: %s", err.Error())
return true
}
lc.Infof("vault is initialized and unsealed (status code: %d)", sCode)
shouldContinue = false
case http.StatusTooManyRequests:
// we're done here. Will go into ready mode or reseal
shouldContinue = false
case http.StatusNotImplemented:
lc.Infof("vault is not initialized (status code: %d). Starting initialization and unseal phases", sCode)
initResponse, err = client.Init(secretStoreConfig.VaultSecretThreshold, secretStoreConfig.VaultSecretShares)
if err != nil {
lc.Errorf("Unable to Initialize Vault: %s. Will try again...", err.Error())
// Not terminal failure, should continue and try again
return false
}
if secretStoreConfig.RevokeRootTokens {
// Never persist the root token to disk on secret store initialization if we intend to revoke it later
initResponse.RootToken = ""
lc.Info("Root token stripped from init response for security reasons")
}
err = client.Unseal(initResponse.KeysBase64)
if err != nil {
lc.Errorf("Unable to unseal Vault: %s", err.Error())
return true
}
// We need the unencrypted initResponse in order to generate a temporary root token later
// Make a copy and save the copy, possibly encrypted
encryptedInitResponse := initResponse
// Optionally encrypt the vault init response based on whether encryption was enabled
if vmkEncryption.IsEncrypting() {
if err := vmkEncryption.EncryptInitResponse(&encryptedInitResponse); err != nil {
lc.Errorf("failed to encrypt init response from secret store: %s", err.Error())
return true
}
}
if err := saveInitResponse(lc, fileOpener, secretStoreConfig, &encryptedInitResponse); err != nil {
lc.Errorf("unable to save init response: %s", err.Error())
return true
}
case http.StatusServiceUnavailable:
lc.Infof("vault is sealed (status code: %d). Starting unseal phase", sCode)
if err := loadInitResponse(lc, fileOpener, secretStoreConfig, &initResponse); err != nil {
lc.Errorf("unable to load init response: %s", err.Error())
return true
}
// Optionally decrypt the vault init response based on whether encryption was enabled
if vmkEncryption.IsEncrypting() {
err = vmkEncryption.DecryptInitResponse(&initResponse)
if err != nil {
lc.Errorf("failed to decrypt key shares for secret store unsealing: %s", err.Error())
return true
}
}
err := client.Unseal(initResponse.KeysBase64)
if err == nil {
shouldContinue = false
}
default:
if sCode == 0 {
lc.Errorf("vault is in an unknown state. No Status code available")
} else {
lc.Errorf("vault is in an unknown state. Status code: %d", sCode)
}
}
return false
}()
if terminalFailure {
return false
}
if shouldContinue {
lc.Infof("trying Vault init/unseal again in %d seconds", b.vaultInterval)
time.Sleep(intervalDuration)
}
}
/* After vault is initialized and unsealed, it takes a while to get ready to accept any request. During which period any request will get http 500 error.
We need to check the status constantly until it return http StatusOK.
*/
ticker := time.NewTicker(time.Second)
healthOkCh := make(chan struct{})
go func() {
for {
<-ticker.C
if sCode, _ := client.HealthCheck(); sCode == http.StatusOK {
close(healthOkCh)
ticker.Stop()
return
}
}
}()
// Wait on a StatusOK response from client.HealthCheck()
<-healthOkCh
// create new root token
// defer revoke token
// optional: revoke other root token
// revoke old tokens
// create delegate credential
// spawn token provider
// create db credentials
// upload kong certificate
tokenMaintenance := NewTokenMaintenance(lc, client)
// Create a transient root token from the key shares
var rootToken string
rootToken, err = client.RegenRootToken(initResponse.Keys)
if err != nil {
lc.Errorf("could not regenerate root token %s", err.Error())
os.Exit(1)
}
defer func() {
// Revoke transient root token at the end of this function
lc.Info("revoking temporary root token")
err := client.RevokeToken(rootToken)
if err != nil {
lc.Errorf("could not revoke temporary root token %s", err.Error())
}
}()
lc.Info("generated transient root token")
// Revoke the other root tokens
if secretStoreConfig.RevokeRootTokens {
if initResponse.RootToken != "" {
initResponse.RootToken = ""
if err := saveInitResponse(lc, fileOpener, secretStoreConfig, &initResponse); err != nil {
lc.Errorf("unable to save init response: %s", err.Error())
os.Exit(1)
}
lc.Info("Root token stripped from init response (on disk) for security reasons")
}
if err := tokenMaintenance.RevokeRootTokens(rootToken); err != nil {
lc.Warnf("failed to revoke non-transient root tokens %s", err.Error())
}
lc.Info("completed cleanup of old root tokens")
} else {
lc.Info("not revoking existing root tokens")
}
// Revoke non-root tokens from previous runs
if err := tokenMaintenance.RevokeNonRootTokens(rootToken); err != nil {
lc.Warn("failed to revoke non-root tokens")
}
lc.Info("completed cleanup of old admin/service tokens")
// If configured to do so, create a token issuing token
if secretStoreConfig.TokenProviderAdminTokenPath != "" {
revokeIssuingTokenFuc, err := tokenfilewriter.NewWriter(lc, client, fileOpener).
CreateAndWrite(rootToken, secretStoreConfig.TokenProviderAdminTokenPath, tokenMaintenance.CreateTokenIssuingToken)
if err != nil {
lc.Errorf("failed to create token issuing token: %s", err.Error())
os.Exit(1)
}
if secretStoreConfig.TokenProviderType == OneShotProvider {
// Revoke the admin token at the end of the current function if running a one-shot provider
// otherwise assume the token provider will keep its token fresh after this point
defer revokeIssuingTokenFuc()
}
}
//Step 4: Launch token handler
tokenProvider := NewTokenProvider(ctx, lc, NewDefaultExecRunner())
if secretStoreConfig.TokenProvider != "" {
if err := tokenProvider.SetConfiguration(secretStoreConfig); err != nil {
lc.Errorf("failed to configure token provider: %s", err.Error())
os.Exit(1)
}
if err := tokenProvider.Launch(); err != nil {
lc.Errorf("token provider failed: %s", err.Error())
os.Exit(1)
}
} else {
lc.Info("no token provider configured")
}
// Enable KV secret engine
if err := secretsengine.New(secretsengine.KVSecretsEngineMountPoint, secretsengine.KeyValue).
Enable(&rootToken, lc, client); err != nil {
lc.Errorf("failed to enable KV secrets engine: %s", err.Error())
os.Exit(1)
}
knownSecretsToAdd, err := b.getKnownSecretsToAdd()
if err != nil {
lc.Error(err.Error())
os.Exit(1)
}
// credential creation
gen := NewPasswordGenerator(lc, secretStoreConfig.PasswordProvider, secretStoreConfig.PasswordProviderArgs)
cred := NewCred(httpCaller, rootToken, gen, secretStoreConfig.GetBaseURL(), lc)
// continue credential creation
// A little note on why there are two secrets paths. For each microservice, the
// username/password is uploaded to the vault on both /v1/secret/edgex/%s/redisdb and
// /v1/secret/edgex/redisdb/%s). The go-mod-secrets client requires a Path property to prefix all
// secrets.
// So edgex/%s/redisdb is for the microservices (microservices are restricted to their specific
// edgex/%s), and edgex/redisdb/* is enumerated to initialize the database.
//
// Redis 5.x only supports a single shared password. When Redis 6 is released, this can be updated
// to a per service password.
redis5Pair, err := getDBCredential("security-bootstrapper-redis", cred, "redisdb")
if err != nil {
if err != errNotFound {
lc.Error("failed to determine if Redis credentials already exist or not: %w", err)
os.Exit(1)
}
lc.Info("Generating new password for Redis DB")
redis5Password, err := cred.GeneratePassword(ctx)
if err != nil {
lc.Error("failed to generate redis5 password")
os.Exit(1)
}
redis5Pair = UserPasswordPair{
User: "redis5",
Password: redis5Password,
}
} else {
lc.Info("Redis DB credentials exist, skipping generating new password")
}
// Add any additional services that need the known DB secret
services, ok := knownSecretsToAdd[redisSecretName]
if ok {
for _, service := range services {
configuration.Databases[service] = config.Database{
Service: service,
}
}
}
for _, info := range configuration.Databases {
service := info.Service
// add credentials to service path if specified and they're not already there
if len(service) != 0 {
err = addServiceCredential(lc, "redisdb", cred, service, redis5Pair)
if err != nil {
lc.Error(err.Error())
os.Exit(1)
}
}
}
// security-bootstrapper-redis uses the path /v1/secret/edgex/security-bootstrapper-redis/ and go-mod-bootstrap
// with append the DB type (redisdb)
err = addDBCredential(lc, "security-bootstrapper-redis", cred, "redisdb", redis5Pair)
if err != nil {
lc.Error(err.Error())
os.Exit(1)
}
err = ConfigureSecureMessageBus(configuration.SecureMessageBus, redis5Pair, lc)
if err != nil {
lc.Error("failed to configure for Secure Message Bus: %w", err)
os.Exit(1)
}
// Concat all cert path secretStore values together to check for empty values
certPathCheck := secretStoreConfig.CertPath +
secretStoreConfig.CertFilePath +
secretStoreConfig.KeyFilePath
// If any of the previous three proxy cert path values are present (len > 0), attempt to upload to secret store
if len(strings.TrimSpace(certPathCheck)) != 0 {
// Grab the certificate & check to see if it's already in the secret store
cert := NewCerts(httpCaller, secretStoreConfig.CertPath, rootToken, secretStoreConfig.GetBaseURL(), lc)
existing, err := cert.AlreadyInStore()
if err != nil {
lc.Error(err.Error())
os.Exit(1)
}
if existing {
lc.Info("proxy certificate pair are in the secret store already, skip uploading")
return false
}
lc.Info("proxy certificate pair are not in the secret store yet, uploading them")
cp, err := cert.ReadFrom(secretStoreConfig.CertFilePath, secretStoreConfig.KeyFilePath)
if err != nil {
lc.Error("failed to get certificate pair from volume")
os.Exit(1)
}
lc.Info("proxy certificate pair are loaded from volume successfully, will upload to secret store")
err = cert.UploadToStore(cp)
if err != nil {
lc.Error("failed to upload the proxy cert pair into the secret store")
lc.Error(err.Error())
os.Exit(1)
}
lc.Info("proxy certificate pair are uploaded to secret store successfully")
} else {
lc.Info("proxy certificate pair upload was skipped because cert secretStore value(s) were blank")
}
// create and save a Vault token to configure
// Consul secret engine access, role operations, and managing Consul agent tokens.
// Enable Consul secret engine
if err := secretsengine.New(secretsengine.ConsulSecretEngineMountPoint, secretsengine.Consul).
Enable(&rootToken, lc, client); err != nil {
lc.Errorf("failed to enable Consul secrets engine: %s", err.Error())
os.Exit(1)
}
// generate a management token for Consul secrets engine operations:
tokenFileWriter := tokenfilewriter.NewWriter(lc, client, fileOpener)
if _, err := tokenFileWriter.CreateAndWrite(rootToken, configuration.SecretStore.ConsulSecretsAdminTokenPath,
tokenFileWriter.CreateMgmtTokenForConsulSecretsEngine); err != nil {
lc.Errorf("failed to create and write the token for Consul secret management: %s", err.Error())
os.Exit(1)
}
// Configure Kong Admin API
//
// For context - this process doesn't actually talk to Kong, it creates the configuration
// file and JWT necessary in order for the Kong process to bootstrap itself with a properly
// locked down Admin API and enable security-proxy-setup with the JWT in order to setup
// the services/routes as configured.
//
// The reason why this code exists in the Secret Store setup is a matter of timing and
// file permissions. This process has to occur before Kong is started, and cannot be executed
// by the Kong entrypoint script because that executes as the Kong user. The JWT created
// needs to be used by the security-proxy-setup process, so needs to be created before.
// Since Secret Store setup runs prior to both of these, it made sense to logically drop them
// here, especially if we're going to incorporate ties in to the Secret Store at a later
// time.
//
// As of now, the private key that is generated for the "admin" group in Kong never
// gets saved to disk out of memory. This could change in the future and be placed into
// the Secret Store if we need to regenerate the JWT on the fly after setup has occurred.
//
lc.Info("Starting the Kong Admin API config file creation")
// Get an instance of KongAdminAPI and map the paths from configuration.toml
ka := NewKongAdminAPI(kongAdminConfig)
// Setup Kong Admin API loopback configuration
err = ka.Setup()
if err != nil {
lc.Errorf("failed to configure the Kong Admin API: %s", err.Error())
}
lc.Info("Vault init done successfully")
return false
}
func (b *Bootstrap) getKnownSecretsToAdd() (map[string][]string, error) {
// Process the env var for adding known secrets to the specified services' secret stores.
// Format of the env var value is:
// "<secretName>[<serviceName>;<serviceName>; ...], <secretName>[<serviceName>;<serviceName>; ...], ..."
knownSecretsToAdd := map[string][]string{}
addKnownSecretsValue := strings.TrimSpace(os.Getenv(addKnownSecretsEnv))
if len(addKnownSecretsValue) == 0 {
return knownSecretsToAdd, nil
}
serviceNameRegx := regexp.MustCompile(ServiceNameValidationRegx)
knownSecrets := strings.Split(addKnownSecretsValue, knownSecretSeparator)
for _, secretSpec := range knownSecrets {
// each secretSpec has format of "<secretName>[<serviceName>;<serviceName>; ...]"
secretItems := strings.Split(secretSpec, serviceListBegin)
if len(secretItems) != 2 {
return nil, fmt.Errorf(
"invalid specification for %s environment vaiable: Format of value '%s' is invalid. Missing or too many '%s'",
addKnownSecretsEnv,
secretSpec,
serviceListBegin)
}
secretName := strings.TrimSpace(secretItems[0])
_, valid := b.validKnownSecrets[secretName]
if !valid {
return nil, fmt.Errorf(
"invalid specification for %s environment vaiable: '%s' is not a known secret",
addKnownSecretsEnv,
secretName)
}
serviceNameList := secretItems[1]
if !strings.Contains(serviceNameList, serviceListEnd) {
return nil, fmt.Errorf(
"invalid specification for %s environment vaiable: Service list for '%s' missing closing '%s'",
addKnownSecretsEnv,
secretName,
serviceListEnd)
}
serviceNameList = strings.TrimSpace(strings.Replace(serviceNameList, serviceListEnd, "", 1))
if len(serviceNameList) == 0 {
return nil, fmt.Errorf(
"invalid specification for %s environment vaiable: Service name list for '%s' is empty.",
addKnownSecretsEnv,
secretName)
}
serviceNames := strings.Split(serviceNameList, serviceListSeparator)
for index := range serviceNames {
serviceNames[index] = strings.TrimSpace(serviceNames[index])
if !serviceNameRegx.MatchString(serviceNames[index]) {
return nil, fmt.Errorf(
"invalid specification for %s environment vaiable: Service name '%s' has invalid characters.",
addKnownSecretsEnv, serviceNames[index])
}
}
// This supports listing known secret multiple times.
// Same service name listed twice is not an issue since the add logic checks if the secret is already present.
existingServices := knownSecretsToAdd[secretName]
knownSecretsToAdd[secretName] = append(existingServices, serviceNames...)
}
return knownSecretsToAdd, nil
}
// XXX Collapse addServiceCredential and addDBCredential together by passing in the path or using
// variadic functions
func addServiceCredential(lc logger.LoggingClient, db string, cred Cred, service string, pair UserPasswordPair) error {
path := fmt.Sprintf("%s/%s/%s", secretBasePath, service, db)
existing, err := cred.AlreadyInStore(path)
if err != nil {
return err
}
if !existing {
err = cred.UploadToStore(&pair, path)
if err != nil {
lc.Errorf("failed to upload credential pair for %s on path %s", service, path)
return err
}
} else {
lc.Infof("credentials for %s already present at path %s", service, path)
}
return err
}
func getDBCredential(db string, cred Cred, service string) (UserPasswordPair, error) {
path := fmt.Sprintf("%s/%s/%s", secretBasePath, db, service)
pair, err := cred.getUserPasswordPair(path)
if err != nil {
return UserPasswordPair{}, err
}
return *pair, err
}
func addDBCredential(lc logger.LoggingClient, db string, cred Cred, service string, pair UserPasswordPair) error {
path := fmt.Sprintf("%s/%s/%s", secretBasePath, db, service)
existing, err := cred.AlreadyInStore(path)
if err != nil {
lc.Error(err.Error())
return err
}
if !existing {
err = cred.UploadToStore(&pair, path)
if err != nil {
lc.Errorf("failed to upload credential pair for db %s on path %s", service, path)
return err
}
} else {
lc.Infof("credentials for %s already present at path %s", service, path)
}
return err
}
func loadInitResponse(
lc logger.LoggingClient,
fileOpener fileioperformer.FileIoPerformer,
secretConfig config.SecretStoreInfo,
initResponse *types.InitResponse) error {
absPath := filepath.Join(secretConfig.TokenFolderPath, secretConfig.TokenFile)
tokenFile, err := fileOpener.OpenFileReader(absPath, os.O_RDONLY, 0400)
if err != nil {
lc.Errorf("could not read master key shares file %s: %s", absPath, err.Error())
return err
}
tokenFileCloseable := fileioperformer.MakeReadCloser(tokenFile)
defer func() { _ = tokenFileCloseable.Close() }()
decoder := json.NewDecoder(tokenFileCloseable)
if decoder == nil {
err := errors.New("Failed to create JSON decoder")
lc.Error(err.Error())
return err
}
if err := decoder.Decode(initResponse); err != nil {
lc.Errorf("unable to read token file at %s with error: %s", absPath, err.Error())
return err
}
return nil
}
func saveInitResponse(
lc logger.LoggingClient,
fileOpener fileioperformer.FileIoPerformer,
secretConfig config.SecretStoreInfo,
initResponse *types.InitResponse) error {
absPath := filepath.Join(secretConfig.TokenFolderPath, secretConfig.TokenFile)
tokenFile, err := fileOpener.OpenFileWriter(absPath, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0600)
if err != nil {
lc.Errorf("could not read master key shares file %s: %s", absPath, err.Error())
return err
}
encoder := json.NewEncoder(tokenFile)
if encoder == nil {
err := errors.New("Failed to create JSON encoder")
lc.Error(err.Error())
_ = tokenFile.Close()
return err
}
if err := encoder.Encode(initResponse); err != nil {
lc.Errorf("unable to write token file at %s with error: %s", absPath, err.Error())
_ = tokenFile.Close()
return err
}
if err := tokenFile.Close(); err != nil {
lc.Errorf("unable to close token file at %s with error: %s", absPath, err.Error())
_ = tokenFile.Close()
return err
}
return nil
}