2023-03-15 19:00:52 +03:00
|
|
|
// Copyright (c) HashiCorp, Inc.
|
2024-01-02 21:36:20 +03:00
|
|
|
// SPDX-License-Identifier: BUSL-1.1
|
2023-03-15 19:00:52 +03:00
|
|
|
|
2019-10-15 07:55:31 +03:00
|
|
|
package vault
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
2021-05-11 20:12:54 +03:00
|
|
|
"fmt"
|
2019-11-07 19:54:34 +03:00
|
|
|
|
2021-07-16 03:17:31 +03:00
|
|
|
"github.com/hashicorp/go-secure-stdlib/base62"
|
2022-02-17 22:43:07 +03:00
|
|
|
"github.com/hashicorp/vault/sdk/helper/consts"
|
2019-10-15 07:55:31 +03:00
|
|
|
"go.uber.org/atomic"
|
|
|
|
)
|
|
|
|
|
|
|
|
// GenerateRecoveryTokenStrategy is the strategy used to generate a
|
|
|
|
// recovery token
|
|
|
|
func GenerateRecoveryTokenStrategy(token *atomic.String) GenerateRootStrategy {
|
|
|
|
return &generateRecoveryToken{token: token}
|
|
|
|
}
|
|
|
|
|
|
|
|
// generateRecoveryToken implements the GenerateRootStrategy and is in
|
|
|
|
// charge of creating recovery tokens.
|
|
|
|
type generateRecoveryToken struct {
|
|
|
|
token *atomic.String
|
|
|
|
}
|
|
|
|
|
2019-10-23 19:52:28 +03:00
|
|
|
func (g *generateRecoveryToken) authenticate(ctx context.Context, c *Core, combinedKey []byte) error {
|
2021-12-07 04:12:20 +03:00
|
|
|
key, err := c.unsealKeyToRootKeyPostUnseal(ctx, combinedKey)
|
2019-10-23 19:52:28 +03:00
|
|
|
if err != nil {
|
2021-05-11 20:12:54 +03:00
|
|
|
return fmt.Errorf("unable to authenticate: %w", err)
|
2019-10-23 19:52:28 +03:00
|
|
|
}
|
|
|
|
|
2021-12-07 04:12:20 +03:00
|
|
|
// Use the retrieved root key to unseal the barrier
|
2019-10-23 19:52:28 +03:00
|
|
|
if err := c.barrier.Unseal(ctx, key); err != nil {
|
2021-05-11 20:12:54 +03:00
|
|
|
return fmt.Errorf("recovery operation token generation failed, cannot unseal barrier: %w", err)
|
2019-10-23 19:52:28 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
for _, v := range c.postRecoveryUnsealFuncs {
|
|
|
|
if err := v(); err != nil {
|
2021-05-11 20:12:54 +03:00
|
|
|
return fmt.Errorf("failed to run post unseal func: %w", err)
|
2019-10-23 19:52:28 +03:00
|
|
|
}
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2019-10-15 07:55:31 +03:00
|
|
|
func (g *generateRecoveryToken) generate(ctx context.Context, c *Core) (string, func(), error) {
|
2022-02-17 22:43:07 +03:00
|
|
|
var id string
|
|
|
|
var err error
|
|
|
|
id, err = base62.Random(TokenLength)
|
2019-10-15 07:55:31 +03:00
|
|
|
if err != nil {
|
|
|
|
return "", nil, err
|
|
|
|
}
|
2022-02-17 22:43:07 +03:00
|
|
|
var token string
|
|
|
|
if c.DisableSSCTokens() {
|
|
|
|
token = consts.LegacyRecoveryTokenPrefix + id
|
|
|
|
} else {
|
|
|
|
token = consts.RecoveryTokenPrefix + id
|
|
|
|
}
|
2019-10-15 07:55:31 +03:00
|
|
|
g.token.Store(token)
|
|
|
|
|
|
|
|
return token, func() { g.token.Store("") }, nil
|
|
|
|
}
|