diff --git a/vault/acl.go b/vault/acl.go index 040258f6f..78a37dd3f 100644 --- a/vault/acl.go +++ b/vault/acl.go @@ -8,7 +8,6 @@ import ( "strings" "github.com/armon/go-radix" - "github.com/hashicorp/errwrap" "github.com/hashicorp/go-multierror" "github.com/hashicorp/vault/helper/identity" "github.com/hashicorp/vault/helper/namespace" @@ -125,7 +124,7 @@ func NewACL(ctx context.Context, policies []*Policy) (*ACL, error) { if !ok { clonedPerms, err := pc.Permissions.Clone() if err != nil { - return nil, errwrap.Wrapf("error cloning ACL permissions: {{err}}", err) + return nil, fmt.Errorf("error cloning ACL permissions: %w", err) } switch { case pc.HasSegmentWildcards: diff --git a/vault/audited_headers.go b/vault/audited_headers.go index 7abe78cd6..4e83d9bff 100644 --- a/vault/audited_headers.go +++ b/vault/audited_headers.go @@ -6,7 +6,6 @@ import ( "strings" "sync" - "github.com/hashicorp/errwrap" "github.com/hashicorp/vault/sdk/logical" ) @@ -50,11 +49,11 @@ func (a *AuditedHeadersConfig) add(ctx context.Context, header string, hmac bool a.Headers[strings.ToLower(header)] = &auditedHeaderSettings{hmac} entry, err := logical.StorageEntryJSON(auditedHeadersEntry, a.Headers) if err != nil { - return errwrap.Wrapf("failed to persist audited headers config: {{err}}", err) + return fmt.Errorf("failed to persist audited headers config: %w", err) } if err := a.view.Put(ctx, entry); err != nil { - return errwrap.Wrapf("failed to persist audited headers config: {{err}}", err) + return fmt.Errorf("failed to persist audited headers config: %w", err) } return nil @@ -78,11 +77,11 @@ func (a *AuditedHeadersConfig) remove(ctx context.Context, header string) error delete(a.Headers, strings.ToLower(header)) entry, err := logical.StorageEntryJSON(auditedHeadersEntry, a.Headers) if err != nil { - return errwrap.Wrapf("failed to persist audited headers config: {{err}}", err) + return fmt.Errorf("failed to persist audited headers config: %w", err) } if err := a.view.Put(ctx, entry); err != nil { - return errwrap.Wrapf("failed to persist audited headers config: {{err}}", err) + return fmt.Errorf("failed to persist audited headers config: %w", err) } return nil @@ -135,7 +134,7 @@ func (c *Core) setupAuditedHeadersConfig(ctx context.Context) error { // Create the config out, err := view.Get(ctx, auditedHeadersEntry) if err != nil { - return errwrap.Wrapf("failed to read config: {{err}}", err) + return fmt.Errorf("failed to read config: %w", err) } headers := make(map[string]*auditedHeaderSettings) diff --git a/vault/barrier_aes_gcm.go b/vault/barrier_aes_gcm.go index edce5cef2..730680b8f 100644 --- a/vault/barrier_aes_gcm.go +++ b/vault/barrier_aes_gcm.go @@ -16,7 +16,6 @@ import ( "time" "github.com/armon/go-metrics" - "github.com/hashicorp/errwrap" "github.com/hashicorp/vault/sdk/helper/jsonutil" "github.com/hashicorp/vault/sdk/helper/strutil" "github.com/hashicorp/vault/sdk/logical" @@ -132,7 +131,7 @@ func (b *AESGCMBarrier) Initialized(ctx context.Context) (bool, error) { // Read the keyring file keys, err := b.backend.List(ctx, keyringPrefix) if err != nil { - return false, errwrap.Wrapf("failed to check for initialization: {{err}}", err) + return false, fmt.Errorf("failed to check for initialization: %w", err) } if strutil.StrListContains(keys, "keyring") { b.initialized.Store(true) @@ -142,7 +141,7 @@ func (b *AESGCMBarrier) Initialized(ctx context.Context) (bool, error) { // Fallback, check for the old sentinel file out, err := b.backend.Get(ctx, barrierInitPath) if err != nil { - return false, errwrap.Wrapf("failed to check for initialization: {{err}}", err) + return false, fmt.Errorf("failed to check for initialization: %w", err) } b.initialized.Store(out != nil) return out != nil, nil @@ -167,7 +166,7 @@ func (b *AESGCMBarrier) Initialize(ctx context.Context, key, sealKey []byte, rea // Generate encryption key encrypt, err := b.GenerateKey(reader) if err != nil { - return errwrap.Wrapf("failed to generate encryption key: {{err}}", err) + return fmt.Errorf("failed to generate encryption key: %w", err) } // Create a new keyring, install the keys @@ -179,7 +178,7 @@ func (b *AESGCMBarrier) Initialize(ctx context.Context, key, sealKey []byte, rea Value: encrypt, }) if err != nil { - return errwrap.Wrapf("failed to create keyring: {{err}}", err) + return fmt.Errorf("failed to create keyring: %w", err) } err = b.persistKeyring(ctx, keyring) @@ -198,7 +197,7 @@ func (b *AESGCMBarrier) Initialize(ctx context.Context, key, sealKey []byte, rea Value: sealKey, }) if err != nil { - return errwrap.Wrapf("failed to store new seal key: {{err}}", err) + return fmt.Errorf("failed to store new seal key: %w", err) } } @@ -212,7 +211,7 @@ func (b *AESGCMBarrier) persistKeyring(ctx context.Context, keyring *Keyring) er keyringBuf, err := keyring.Serialize() defer memzero(keyringBuf) if err != nil { - return errwrap.Wrapf("failed to serialize keyring: {{err}}", err) + return fmt.Errorf("failed to serialize keyring: %w", err) } // Create the AES-GCM @@ -233,7 +232,7 @@ func (b *AESGCMBarrier) persistKeyring(ctx context.Context, keyring *Keyring) er Value: value, } if err := b.backend.Put(ctx, pe); err != nil { - return errwrap.Wrapf("failed to persist keyring: {{err}}", err) + return fmt.Errorf("failed to persist keyring: %w", err) } // Serialize the master key value @@ -245,7 +244,7 @@ func (b *AESGCMBarrier) persistKeyring(ctx context.Context, keyring *Keyring) er keyBuf, err := key.Serialize() defer memzero(keyBuf) if err != nil { - return errwrap.Wrapf("failed to serialize master key: {{err}}", err) + return fmt.Errorf("failed to serialize master key: %w", err) } // Encrypt the master key @@ -265,7 +264,7 @@ func (b *AESGCMBarrier) persistKeyring(ctx context.Context, keyring *Keyring) er Value: value, } if err := b.backend.Put(ctx, pe); err != nil { - return errwrap.Wrapf("failed to persist master key: {{err}}", err) + return fmt.Errorf("failed to persist master key: %w", err) } return nil } @@ -322,7 +321,7 @@ func (b *AESGCMBarrier) ReloadKeyring(ctx context.Context) error { // Read in the keyring out, err := b.backend.Get(ctx, keyringPath) if err != nil { - return errwrap.Wrapf("failed to check for keyring: {{err}}", err) + return fmt.Errorf("failed to check for keyring: %w", err) } // Ensure that the keyring exists. This should never happen, @@ -359,7 +358,7 @@ func (b *AESGCMBarrier) ReloadKeyring(ctx context.Context) error { func (b *AESGCMBarrier) recoverKeyring(plaintext []byte) error { keyring, err := DeserializeKeyring(plaintext) if err != nil { - return errwrap.Wrapf("keyring deserialization failed: {{err}}", err) + return fmt.Errorf("keyring deserialization failed: %w", err) } // Setup the keyring and finish @@ -375,7 +374,7 @@ func (b *AESGCMBarrier) ReloadMasterKey(ctx context.Context) error { // Read the masterKeyPath upgrade out, err := b.Get(ctx, masterKeyPath) if err != nil { - return errwrap.Wrapf("failed to read master key path: {{err}}", err) + return fmt.Errorf("failed to read master key path: %w", err) } // The masterKeyPath could be missing (backwards incompatible), @@ -391,7 +390,7 @@ func (b *AESGCMBarrier) ReloadMasterKey(ctx context.Context) error { out, err = b.lockSwitchedGet(ctx, masterKeyPath, false) if err != nil { - return errwrap.Wrapf("failed to read master key path: {{err}}", err) + return fmt.Errorf("failed to read master key path: %w", err) } if out == nil { @@ -402,7 +401,7 @@ func (b *AESGCMBarrier) ReloadMasterKey(ctx context.Context) error { key, err := DeserializeKey(out.Value) memzero(out.Value) if err != nil { - return errwrap.Wrapf("failed to deserialize key: {{err}}", err) + return fmt.Errorf("failed to deserialize key: %w", err) } // Check if the master key is the same @@ -437,7 +436,7 @@ func (b *AESGCMBarrier) Unseal(ctx context.Context, key []byte) error { // Read in the keyring out, err := b.backend.Get(ctx, keyringPath) if err != nil { - return errwrap.Wrapf("failed to check for keyring: {{err}}", err) + return fmt.Errorf("failed to check for keyring: %w", err) } if out != nil { // Verify the term is always just one @@ -459,7 +458,7 @@ func (b *AESGCMBarrier) Unseal(ctx context.Context, key []byte) error { // Recover the keyring err = b.recoverKeyring(plain) if err != nil { - return errwrap.Wrapf("keyring deserialization failed: {{err}}", err) + return fmt.Errorf("keyring deserialization failed: %w", err) } b.sealed = false @@ -470,7 +469,7 @@ func (b *AESGCMBarrier) Unseal(ctx context.Context, key []byte) error { // Read the barrier initialization key out, err = b.backend.Get(ctx, barrierInitPath) if err != nil { - return errwrap.Wrapf("failed to check for initialization: {{err}}", err) + return fmt.Errorf("failed to check for initialization: %w", err) } if out == nil { return ErrBarrierNotInit @@ -511,7 +510,7 @@ func (b *AESGCMBarrier) Unseal(ctx context.Context, key []byte) error { Value: init.Key, }) if err != nil { - return errwrap.Wrapf("failed to create keyring: {{err}}", err) + return fmt.Errorf("failed to create keyring: %w", err) } if err := b.persistKeyring(ctx, keyring); err != nil { return err @@ -519,7 +518,7 @@ func (b *AESGCMBarrier) Unseal(ctx context.Context, key []byte) error { // Delete the old barrier entry if err := b.backend.Delete(ctx, barrierInitPath); err != nil { - return errwrap.Wrapf("failed to delete barrier init file: {{err}}", err) + return fmt.Errorf("failed to delete barrier init file: %w", err) } // Set the vault as unsealed @@ -555,7 +554,7 @@ func (b *AESGCMBarrier) Rotate(ctx context.Context, randomSource io.Reader) (uin // Generate a new key encrypt, err := b.GenerateKey(randomSource) if err != nil { - return 0, errwrap.Wrapf("failed to generate encryption key: {{err}}", err) + return 0, fmt.Errorf("failed to generate encryption key: %w", err) } // Get the next term @@ -569,7 +568,7 @@ func (b *AESGCMBarrier) Rotate(ctx context.Context, randomSource io.Reader) (uin Value: encrypt, }) if err != nil { - return 0, errwrap.Wrapf("failed to add new encryption key: {{err}}", err) + return 0, fmt.Errorf("failed to add new encryption key: %w", err) } // Persist the new keyring @@ -691,7 +690,7 @@ func (b *AESGCMBarrier) CheckUpgrade(ctx context.Context) (bool, uint32, error) // Update the keyring newKeyring, err := b.keyring.AddKey(key) if err != nil { - return false, 0, errwrap.Wrapf("failed to add new encryption key: {{err}}", err) + return false, 0, fmt.Errorf("failed to add new encryption key: %w", err) } b.keyring = newKeyring @@ -866,7 +865,7 @@ func (b *AESGCMBarrier) lockSwitchedGet(ctx context.Context, key string, getLock // Decrypt the ciphertext plain, err := b.decrypt(key, gcm, pe.Value) if err != nil { - return nil, errwrap.Wrapf("decryption failed: {{err}}", err) + return nil, fmt.Errorf("decryption failed: %w", err) } // Wrap in a logical entry @@ -945,7 +944,7 @@ func (b *AESGCMBarrier) aeadFromKey(key []byte) (cipher.AEAD, error) { // Create the AES cipher aesCipher, err := aes.NewCipher(key) if err != nil { - return nil, errwrap.Wrapf("failed to create cipher: {{err}}", err) + return nil, fmt.Errorf("failed to create cipher: %w", err) } // Create the GCM mode AEAD @@ -1080,7 +1079,7 @@ func (b *AESGCMBarrier) Decrypt(_ context.Context, key string, ciphertext []byte // Decrypt the ciphertext plain, err := b.decrypt(key, gcm, ciphertext) if err != nil { - return nil, errwrap.Wrapf("decryption failed: {{err}}", err) + return nil, fmt.Errorf("decryption failed: %w", err) } return plain, nil diff --git a/vault/cluster.go b/vault/cluster.go index 649dd0d3d..c114e09bd 100644 --- a/vault/cluster.go +++ b/vault/cluster.go @@ -17,7 +17,6 @@ import ( "strings" "time" - "github.com/hashicorp/errwrap" uuid "github.com/hashicorp/go-uuid" "github.com/hashicorp/vault/sdk/helper/jsonutil" "github.com/hashicorp/vault/sdk/logical" @@ -71,7 +70,7 @@ func (c *Core) Cluster(ctx context.Context) (*Cluster, error) { // Decode the cluster information if err = jsonutil.DecodeJSON(entry.Value, &cluster); err != nil { - return nil, errwrap.Wrapf("failed to decode cluster details: {{err}}", err) + return nil, fmt.Errorf("failed to decode cluster details: %w", err) } // Set in config file @@ -136,7 +135,7 @@ func (c *Core) loadLocalClusterTLS(adv activeAdvertisement) (retErr error) { cert, err := x509.ParseCertificate(adv.ClusterCert) if err != nil { c.logger.Error("failed parsing local cluster certificate", "error", err) - return errwrap.Wrapf("error parsing local cluster certificate: {{err}}", err) + return fmt.Errorf("error parsing local cluster certificate: %w", err) } c.localClusterParsedCert.Store(cert) @@ -247,13 +246,13 @@ func (c *Core) setupCluster(ctx context.Context) error { certBytes, err := x509.CreateCertificate(rand.Reader, template, template, c.localClusterPrivateKey.Load().(*ecdsa.PrivateKey).Public(), c.localClusterPrivateKey.Load().(*ecdsa.PrivateKey)) if err != nil { c.logger.Error("error generating self-signed cert", "error", err) - return errwrap.Wrapf("unable to generate local cluster certificate: {{err}}", err) + return fmt.Errorf("unable to generate local cluster certificate: %w", err) } parsedCert, err := x509.ParseCertificate(certBytes) if err != nil { c.logger.Error("error parsing self-signed cert", "error", err) - return errwrap.Wrapf("error parsing generated certificate: {{err}}", err) + return fmt.Errorf("error parsing generated certificate: %w", err) } c.localClusterCert.Store(certBytes) diff --git a/vault/cluster/cluster.go b/vault/cluster/cluster.go index 3c0e71ad5..b4ec28cf6 100644 --- a/vault/cluster/cluster.go +++ b/vault/cluster/cluster.go @@ -12,7 +12,6 @@ import ( "sync/atomic" "time" - "github.com/hashicorp/errwrap" log "github.com/hashicorp/go-hclog" "github.com/hashicorp/vault/sdk/helper/consts" "golang.org/x/net/http2" @@ -95,7 +94,7 @@ func NewListener(networkLayer NetworkLayer, cipherSuites []uint16, logger log.Lo func (cl *Listener) SetAdvertiseAddr(addr string) error { u, err := url.ParseRequestURI(addr) if err != nil { - return errwrap.Wrapf("failed to parse advertise address: {{err}}", err) + return fmt.Errorf("failed to parse advertise address: %w", err) } cl.advertise = &NetAddr{ Host: u.Host, diff --git a/vault/core.go b/vault/core.go index 464eb7c20..770f0f8c3 100644 --- a/vault/core.go +++ b/vault/core.go @@ -727,7 +727,7 @@ func NewCore(conf *CoreConfig) (*Core, error) { if conf.RedirectAddr != "" { u, err := url.Parse(conf.RedirectAddr) if err != nil { - return nil, errwrap.Wrapf("redirect address is not valid url: {{err}}", err) + return nil, fmt.Errorf("redirect address is not valid url: %w", err) } if u.Scheme == "" { @@ -875,7 +875,7 @@ func NewCore(conf *CoreConfig) (*Core, error) { default: suites, err := tlsutil.ParseCiphers(conf.ClusterCipherSuites) if err != nil { - return nil, errwrap.Wrapf("error parsing cluster cipher suites: {{err}}", err) + return nil, fmt.Errorf("error parsing cluster cipher suites: %w", err) } c.clusterCipherSuites = suites } @@ -920,7 +920,7 @@ func NewCore(conf *CoreConfig) (*Core, error) { // Construct a new AES-GCM barrier c.barrier, err = NewAESGCMBarrier(c.physical) if err != nil { - return nil, errwrap.Wrapf("barrier setup failed: {{err}}", err) + return nil, fmt.Errorf("barrier setup failed: %w", err) } // We create the funcs here, then populate the given config with it so that @@ -940,7 +940,7 @@ func NewCore(conf *CoreConfig) (*Core, error) { if conf.PluginDirectory != "" { c.pluginDirectory, err = filepath.Abs(conf.PluginDirectory) if err != nil { - return nil, errwrap.Wrapf("core setup failed, could not verify plugin directory: {{err}}", err) + return nil, fmt.Errorf("core setup failed, could not verify plugin directory: %w", err) } } @@ -1342,7 +1342,7 @@ func (c *Core) getUnsealKey(ctx context.Context, seal Seal) ([]byte, error) { } else { unsealKey, err = shamir.Combine(c.unlockInfo.Parts) if err != nil { - return nil, errwrap.Wrapf("failed to compute combined key: {{err}}", err) + return nil, fmt.Errorf("failed to compute combined key: %w", err) } } @@ -1426,20 +1426,20 @@ func (c *Core) migrateSeal(ctx context.Context) error { // Set the recovery and barrier keys to be the same. recoveryKey, err := c.migrationInfo.seal.RecoveryKey(ctx) if err != nil { - return errwrap.Wrapf("error getting recovery key to set on new seal: {{err}}", err) + return fmt.Errorf("error getting recovery key to set on new seal: %w", err) } if err := c.seal.SetRecoveryKey(ctx, recoveryKey); err != nil { - return errwrap.Wrapf("error setting new recovery key information during migrate: {{err}}", err) + return fmt.Errorf("error setting new recovery key information during migrate: %w", err) } barrierKeys, err := c.migrationInfo.seal.GetStoredKeys(ctx) if err != nil { - return errwrap.Wrapf("error getting stored keys to set on new seal: {{err}}", err) + return fmt.Errorf("error getting stored keys to set on new seal: %w", err) } if err := c.seal.SetStoredKeys(ctx, barrierKeys); err != nil { - return errwrap.Wrapf("error setting new barrier key information during migrate: {{err}}", err) + return fmt.Errorf("error setting new barrier key information during migrate: %w", err) } case c.migrationInfo.seal.RecoveryKeySupported(): @@ -1448,22 +1448,22 @@ func (c *Core) migrateSeal(ctx context.Context) error { recoveryKey, err := c.migrationInfo.seal.RecoveryKey(ctx) if err != nil { - return errwrap.Wrapf("error getting recovery key to set on new seal: {{err}}", err) + return fmt.Errorf("error getting recovery key to set on new seal: %w", err) } // We have recovery keys; we're going to use them as the new shamir KeK. err = c.seal.GetAccess().Wrapper.(*aeadwrapper.ShamirWrapper).SetAESGCMKeyBytes(recoveryKey) if err != nil { - return errwrap.Wrapf("failed to set master key in seal: {{err}}", err) + return fmt.Errorf("failed to set master key in seal: %w", err) } barrierKeys, err := c.migrationInfo.seal.GetStoredKeys(ctx) if err != nil { - return errwrap.Wrapf("error getting stored keys to set on new seal: {{err}}", err) + return fmt.Errorf("error getting stored keys to set on new seal: %w", err) } if err := c.seal.SetStoredKeys(ctx, barrierKeys); err != nil { - return errwrap.Wrapf("error setting new barrier key information during migrate: {{err}}", err) + return fmt.Errorf("error setting new barrier key information during migrate: %w", err) } case c.seal.RecoveryKeySupported(): @@ -1471,24 +1471,24 @@ func (c *Core) migrateSeal(ctx context.Context) error { // Migration is happening from shamir -> auto. In this case use the shamir // combined key that was used to store the master key as the new recovery key. if err := c.seal.SetRecoveryKey(ctx, c.migrationInfo.unsealKey); err != nil { - return errwrap.Wrapf("error setting new recovery key information: {{err}}", err) + return fmt.Errorf("error setting new recovery key information: %w", err) } // Generate a new master key newMasterKey, err := c.barrier.GenerateKey(c.secureRandomReader) if err != nil { - return errwrap.Wrapf("error generating new master key: {{err}}", err) + return fmt.Errorf("error generating new master key: %w", err) } // Rekey the barrier. This handles the case where the shamir seal we're // migrating from was a legacy seal without a stored master key. if err := c.barrier.Rekey(ctx, newMasterKey); err != nil { - return errwrap.Wrapf("error rekeying barrier during migration: {{err}}", err) + return fmt.Errorf("error rekeying barrier during migration: %w", err) } // Store the new master key if err := c.seal.SetStoredKeys(ctx, [][]byte{newMasterKey}); err != nil { - return errwrap.Wrapf("error storing new master key: {{err}}", err) + return fmt.Errorf("error storing new master key: %w", err) } default: @@ -1497,7 +1497,7 @@ func (c *Core) migrateSeal(ctx context.Context) error { err = c.migrateSealConfig(ctx) if err != nil { - return errwrap.Wrapf("error storing new seal configs: {{err}}", err) + return fmt.Errorf("error storing new seal configs: %w", err) } // Flag migration performed for seal-rewrap later @@ -2146,28 +2146,28 @@ func (c *Core) preSeal() error { c.clusterParamsLock.Lock() if err := stopReplication(c); err != nil { - result = multierror.Append(result, errwrap.Wrapf("error stopping replication: {{err}}", err)) + result = multierror.Append(result, fmt.Errorf("error stopping replication: %w", err)) } c.clusterParamsLock.Unlock() if err := c.teardownAudits(); err != nil { - result = multierror.Append(result, errwrap.Wrapf("error tearing down audits: {{err}}", err)) + result = multierror.Append(result, fmt.Errorf("error tearing down audits: %w", err)) } if err := c.stopExpiration(); err != nil { - result = multierror.Append(result, errwrap.Wrapf("error stopping expiration: {{err}}", err)) + result = multierror.Append(result, fmt.Errorf("error stopping expiration: %w", err)) } c.stopActivityLog() if err := c.teardownCredentials(context.Background()); err != nil { - result = multierror.Append(result, errwrap.Wrapf("error tearing down credentials: {{err}}", err)) + result = multierror.Append(result, fmt.Errorf("error tearing down credentials: %w", err)) } if err := c.teardownPolicyStore(); err != nil { - result = multierror.Append(result, errwrap.Wrapf("error tearing down policy store: {{err}}", err)) + result = multierror.Append(result, fmt.Errorf("error tearing down policy store: %w", err)) } if err := c.stopRollback(); err != nil { - result = multierror.Append(result, errwrap.Wrapf("error stopping rollback: {{err}}", err)) + result = multierror.Append(result, fmt.Errorf("error stopping rollback: %w", err)) } if err := c.unloadMounts(context.Background()); err != nil { - result = multierror.Append(result, errwrap.Wrapf("error unloading mounts: {{err}}", err)) + result = multierror.Append(result, fmt.Errorf("error unloading mounts: %w", err)) } if err := enterprisePreSeal(c); err != nil { result = multierror.Append(result, err) @@ -2266,7 +2266,7 @@ func lastRemoteUpstreamWALImpl(c *Core) uint64 { func (c *Core) PhysicalSealConfigs(ctx context.Context) (*SealConfig, *SealConfig, error) { pe, err := c.physical.Get(ctx, barrierSealConfigPath) if err != nil { - return nil, nil, errwrap.Wrapf("failed to fetch barrier seal configuration at migration check time: {{err}}", err) + return nil, nil, fmt.Errorf("failed to fetch barrier seal configuration at migration check time: %w", err) } if pe == nil { return nil, nil, nil @@ -2275,11 +2275,11 @@ func (c *Core) PhysicalSealConfigs(ctx context.Context) (*SealConfig, *SealConfi barrierConf := new(SealConfig) if err := jsonutil.DecodeJSON(pe.Value, barrierConf); err != nil { - return nil, nil, errwrap.Wrapf("failed to decode barrier seal configuration at migration check time: {{err}}", err) + return nil, nil, fmt.Errorf("failed to decode barrier seal configuration at migration check time: %w", err) } err = barrierConf.Validate() if err != nil { - return nil, nil, errwrap.Wrapf("failed to validate barrier seal configuration at migration check time: {{err}}", err) + return nil, nil, fmt.Errorf("failed to validate barrier seal configuration at migration check time: %w", err) } // In older versions of vault the default seal would not store a type. This // is here to offer backwards compatibility for older seal configs. @@ -2290,16 +2290,16 @@ func (c *Core) PhysicalSealConfigs(ctx context.Context) (*SealConfig, *SealConfi var recoveryConf *SealConfig pe, err = c.physical.Get(ctx, recoverySealConfigPlaintextPath) if err != nil { - return nil, nil, errwrap.Wrapf("failed to fetch seal configuration at migration check time: {{err}}", err) + return nil, nil, fmt.Errorf("failed to fetch seal configuration at migration check time: %w", err) } if pe != nil { recoveryConf = &SealConfig{} if err := jsonutil.DecodeJSON(pe.Value, recoveryConf); err != nil { - return nil, nil, errwrap.Wrapf("failed to decode seal configuration at migration check time: {{err}}", err) + return nil, nil, fmt.Errorf("failed to decode seal configuration at migration check time: %w", err) } err = recoveryConf.Validate() if err != nil { - return nil, nil, errwrap.Wrapf("failed to validate seal configuration at migration check time: {{err}}", err) + return nil, nil, fmt.Errorf("failed to validate seal configuration at migration check time: %w", err) } // In older versions of vault the default seal would not store a type. This // is here to offer backwards compatibility for older seal configs. @@ -2388,7 +2388,7 @@ func (c *Core) adjustForSealMigration(unwrapSeal Seal) error { if existBarrierSealConfig.Type != wrapping.Shamir && existRecoverySealConfig == nil { entry, err := c.physical.Get(ctx, recoverySealConfigPath) if err != nil { - return errwrap.Wrapf(fmt.Sprintf("failed to read %q recovery seal configuration: {{err}}", existBarrierSealConfig.Type), err) + return fmt.Errorf("failed to read %q recovery seal configuration: %w", existBarrierSealConfig.Type, err) } if entry == nil { return errors.New("Recovery seal configuration not found for existing seal") @@ -2444,15 +2444,15 @@ func (c *Core) migrateSealConfig(ctx context.Context) error { } if err := c.seal.SetBarrierConfig(ctx, bc); err != nil { - return errwrap.Wrapf("error storing barrier config after migration: {{err}}", err) + return fmt.Errorf("error storing barrier config after migration: %w", err) } if c.seal.RecoveryKeySupported() { if err := c.seal.SetRecoveryConfig(ctx, rc); err != nil { - return errwrap.Wrapf("error storing recovery config after migration: {{err}}", err) + return fmt.Errorf("error storing recovery config after migration: %w", err) } } else if err := c.physical.Delete(ctx, recoverySealConfigPlaintextPath); err != nil { - return errwrap.Wrapf("failed to delete old recovery seal configuration during migration: {{err}}", err) + return fmt.Errorf("failed to delete old recovery seal configuration during migration: %w", err) } return nil @@ -2508,7 +2508,7 @@ func (c *Core) unsealKeyToMasterKey(ctx context.Context, seal Seal, combinedKey switch seal.StoredKeysSupported() { case vaultseal.StoredKeysSupportedGeneric: if err := seal.VerifyRecoveryKey(ctx, combinedKey); err != nil { - return nil, errwrap.Wrapf("recovery key verification failed: {{err}}", err) + return nil, fmt.Errorf("recovery key verification failed: %w", err) } storedKeys, err := seal.GetStoredKeys(ctx) @@ -2520,7 +2520,7 @@ func (c *Core) unsealKeyToMasterKey(ctx context.Context, seal Seal, combinedKey err = fmt.Errorf("expected exactly one stored key, got %d", len(storedKeys)) } if err != nil { - return nil, errwrap.Wrapf("unable to retrieve stored keys: {{err}}", err) + return nil, fmt.Errorf("unable to retrieve stored keys: %w", err) } return storedKeys[0], nil @@ -2534,7 +2534,7 @@ func (c *Core) unsealKeyToMasterKey(ctx context.Context, seal Seal, combinedKey testseal.SetCore(c) cfg, err := seal.BarrierConfig(ctx) if err != nil { - return nil, errwrap.Wrapf("failed to setup test barrier config: {{err}}", err) + return nil, fmt.Errorf("failed to setup test barrier config: %w", err) } testseal.SetCachedBarrierConfig(cfg) seal = testseal @@ -2542,7 +2542,7 @@ func (c *Core) unsealKeyToMasterKey(ctx context.Context, seal Seal, combinedKey err := seal.GetAccess().Wrapper.(*aeadwrapper.ShamirWrapper).SetAESGCMKeyBytes(combinedKey) if err != nil { - return nil, errwrap.Wrapf("failed to setup unseal key: {{err}}", err) + return nil, fmt.Errorf("failed to setup unseal key: %w", err) } storedKeys, err := seal.GetStoredKeys(ctx) if storedKeys == nil && err == nil && allowMissing { @@ -2552,7 +2552,7 @@ func (c *Core) unsealKeyToMasterKey(ctx context.Context, seal Seal, combinedKey err = fmt.Errorf("expected exactly one stored key, got %d", len(storedKeys)) } if err != nil { - return nil, errwrap.Wrapf("unable to retrieve stored keys: {{err}}", err) + return nil, fmt.Errorf("unable to retrieve stored keys: %w", err) } return storedKeys[0], nil diff --git a/vault/cors.go b/vault/cors.go index 8a9533b0c..0ee0df229 100644 --- a/vault/cors.go +++ b/vault/cors.go @@ -3,10 +3,10 @@ package vault import ( "context" "errors" + "fmt" "sync" "sync/atomic" - "github.com/hashicorp/errwrap" "github.com/hashicorp/vault/sdk/helper/consts" "github.com/hashicorp/vault/sdk/helper/strutil" "github.com/hashicorp/vault/sdk/logical" @@ -53,11 +53,11 @@ func (c *Core) saveCORSConfig(ctx context.Context) error { entry, err := logical.StorageEntryJSON("cors", localConfig) if err != nil { - return errwrap.Wrapf("failed to create CORS config entry: {{err}}", err) + return fmt.Errorf("failed to create CORS config entry: %w", err) } if err := view.Put(ctx, entry); err != nil { - return errwrap.Wrapf("failed to save CORS config: {{err}}", err) + return fmt.Errorf("failed to save CORS config: %w", err) } return nil @@ -70,7 +70,7 @@ func (c *Core) loadCORSConfig(ctx context.Context) error { // Load the config in out, err := view.Get(ctx, "cors") if err != nil { - return errwrap.Wrapf("failed to read CORS config: {{err}}", err) + return fmt.Errorf("failed to read CORS config: %w", err) } if out == nil { return nil diff --git a/vault/counters.go b/vault/counters.go index c0a914a8e..e90092254 100644 --- a/vault/counters.go +++ b/vault/counters.go @@ -2,11 +2,11 @@ package vault import ( "context" + "fmt" "sort" "sync/atomic" "time" - "github.com/hashicorp/errwrap" "github.com/hashicorp/vault/sdk/logical" ) @@ -58,7 +58,7 @@ func (c *Core) loadAllRequestCounters(ctx context.Context, now time.Time) ([]Dat datepaths, err := view.List(ctx, "") if err != nil { - return nil, errwrap.Wrapf("failed to read request counters: {{err}}", err) + return nil, fmt.Errorf("failed to read request counters: %w", err) } var all []DatedRequestCounter @@ -66,7 +66,7 @@ func (c *Core) loadAllRequestCounters(ctx context.Context, now time.Time) ([]Dat for _, datepath := range datepaths { datesubpaths, err := view.List(ctx, datepath) if err != nil { - return nil, errwrap.Wrapf("failed to read request counters: {{err}}", err) + return nil, fmt.Errorf("failed to read request counters: %w", err) } sort.Strings(datesubpaths) for _, datesubpath := range datesubpaths { @@ -123,7 +123,7 @@ func (c *Core) loadRequestCounters(ctx context.Context, datepath string) (*Reque out, err := view.Get(ctx, datepath) if err != nil { - return nil, errwrap.Wrapf("failed to read request counters: {{err}}", err) + return nil, fmt.Errorf("failed to read request counters: %w", err) } if out == nil { return nil, nil @@ -160,11 +160,11 @@ func (c *Core) saveCurrentRequestCounters(ctx context.Context, now time.Time) er } entry, err := logical.StorageEntryJSON(writeDatePath, localCounters) if err != nil { - return errwrap.Wrapf("failed to create request counters entry: {{err}}", err) + return fmt.Errorf("failed to create request counters entry: %w", err) } if err := view.Put(ctx, entry); err != nil { - return errwrap.Wrapf("failed to save request counters: {{err}}", err) + return fmt.Errorf("failed to save request counters: %w", err) } if shouldReset { diff --git a/vault/dynamic_system_view.go b/vault/dynamic_system_view.go index 41b132bd1..86e8b560b 100644 --- a/vault/dynamic_system_view.go +++ b/vault/dynamic_system_view.go @@ -5,7 +5,6 @@ import ( "fmt" "time" - "github.com/hashicorp/errwrap" "github.com/hashicorp/vault/helper/identity" "github.com/hashicorp/vault/helper/namespace" "github.com/hashicorp/vault/helper/random" @@ -219,7 +218,7 @@ func (d dynamicSystemView) LookupPlugin(ctx context.Context, name string, plugin return nil, err } if r == nil { - return nil, errwrap.Wrapf(fmt.Sprintf("{{err}}: %s", name), ErrPluginNotFound) + return nil, fmt.Errorf("%w: %s", ErrPluginNotFound, name) } return r, nil diff --git a/vault/expiration.go b/vault/expiration.go index 33fe34f40..4c3f28f5f 100644 --- a/vault/expiration.go +++ b/vault/expiration.go @@ -583,12 +583,12 @@ func (m *ExpirationManager) Tidy(ctx context.Context) error { le, err := m.loadEntry(ctx, leaseID) if err != nil { - tidyErrors = multierror.Append(tidyErrors, errwrap.Wrapf(fmt.Sprintf("failed to load the lease ID %q: {{err}}", leaseID), err)) + tidyErrors = multierror.Append(tidyErrors, fmt.Errorf("failed to load the lease ID %q: %w", leaseID, err)) return } if le == nil { - tidyErrors = multierror.Append(tidyErrors, errwrap.Wrapf(fmt.Sprintf("nil entry for lease ID %q: {{err}}", leaseID), err)) + tidyErrors = multierror.Append(tidyErrors, fmt.Errorf("nil entry for lease ID %q: %w", leaseID, err)) return } @@ -609,7 +609,7 @@ func (m *ExpirationManager) Tidy(ctx context.Context) error { lock.RUnlock() if err != nil { - tidyErrors = multierror.Append(tidyErrors, errwrap.Wrapf("failed to lookup token: {{err}}", err)) + tidyErrors = multierror.Append(tidyErrors, fmt.Errorf("failed to lookup token: %w", err)) return } @@ -639,7 +639,7 @@ func (m *ExpirationManager) Tidy(ctx context.Context) error { // again err = m.revokeCommon(ctx, leaseID, true, true) if err != nil { - tidyErrors = multierror.Append(tidyErrors, errwrap.Wrapf(fmt.Sprintf("failed to revoke an invalid lease with ID %q: {{err}}", leaseID), err)) + tidyErrors = multierror.Append(tidyErrors, fmt.Errorf("failed to revoke an invalid lease with ID %q: %w", leaseID, err)) return } revokedCount++ @@ -1032,7 +1032,7 @@ func (m *ExpirationManager) RevokeByToken(ctx context.Context, te *logical.Token // Lookup the leases existing, err := m.lookupLeasesByToken(tokenCtx, te) if err != nil { - return errwrap.Wrapf("failed to scan for leases: {{err}}", err) + return fmt.Errorf("failed to scan for leases: %w", err) } // Revoke all the keys @@ -1101,7 +1101,7 @@ func (m *ExpirationManager) revokePrefixCommon(ctx context.Context, prefix strin if err == nil && le != nil { if sync { if err := m.revokeCommon(ctx, prefix, force, false); err != nil { - return errwrap.Wrapf(fmt.Sprintf("failed to revoke %q: {{err}}", prefix), err) + return fmt.Errorf("failed to revoke %q: %w", prefix, err) } return nil } @@ -1119,7 +1119,7 @@ func (m *ExpirationManager) revokePrefixCommon(ctx context.Context, prefix strin sub := view.SubView(prefix) existing, err := logical.CollectKeys(ctx, sub) if err != nil { - return errwrap.Wrapf("failed to scan for leases: {{err}}", err) + return fmt.Errorf("failed to scan for leases: %w", err) } // Revoke all the keys @@ -1128,11 +1128,11 @@ func (m *ExpirationManager) revokePrefixCommon(ctx context.Context, prefix strin switch { case sync: if err := m.revokeCommon(ctx, leaseID, force, false); err != nil { - return errwrap.Wrapf(fmt.Sprintf("failed to revoke %q (%d / %d): {{err}}", leaseID, idx+1, len(existing)), err) + return fmt.Errorf("failed to revoke %q (%d / %d): %w", leaseID, idx+1, len(existing), err) } default: if err := m.LazyRevoke(ctx, leaseID); err != nil { - return errwrap.Wrapf(fmt.Sprintf("failed to revoke %q (%d / %d): {{err}}", leaseID, idx+1, len(existing)), err) + return fmt.Errorf("failed to revoke %q (%d / %d): %w", leaseID, idx+1, len(existing), err) } } } @@ -1443,17 +1443,17 @@ func (m *ExpirationManager) Register(ctx context.Context, req *logical.Request, revokeCtx := namespace.ContextWithNamespace(m.quitContext, ns) revResp, err := m.router.Route(revokeCtx, logical.RevokeRequest(req.Path, resp.Secret, resp.Data)) if err != nil { - retErr = multierror.Append(retErr, errwrap.Wrapf("an additional internal error was encountered revoking the newly-generated secret: {{err}}", err)) + retErr = multierror.Append(retErr, fmt.Errorf("an additional internal error was encountered revoking the newly-generated secret: %w", err)) } else if revResp != nil && revResp.IsError() { - retErr = multierror.Append(retErr, errwrap.Wrapf("an additional error was encountered revoking the newly-generated secret: {{err}}", revResp.Error())) + retErr = multierror.Append(retErr, fmt.Errorf("an additional error was encountered revoking the newly-generated secret: %w", revResp.Error())) } if err := m.deleteEntry(ctx, le); err != nil { - retErr = multierror.Append(retErr, errwrap.Wrapf("an additional error was encountered deleting any lease associated with the newly-generated secret: {{err}}", err)) + retErr = multierror.Append(retErr, fmt.Errorf("an additional error was encountered deleting any lease associated with the newly-generated secret: %w", err)) } if err := m.removeIndexByToken(ctx, le, indexToken); err != nil { - retErr = multierror.Append(retErr, errwrap.Wrapf("an additional error was encountered removing lease indexes associated with the newly-generated secret: {{err}}", err)) + retErr = multierror.Append(retErr, fmt.Errorf("an additional error was encountered removing lease indexes associated with the newly-generated secret: %w", err)) } } }() @@ -1791,7 +1791,7 @@ func (m *ExpirationManager) revokeEntry(ctx context.Context, le *leaseEntry) err } if err := m.tokenStore.revokeTree(ctx, le); err != nil { - return errwrap.Wrapf("failed to revoke token: {{err}}", err) + return fmt.Errorf("failed to revoke token: %w", err) } return nil @@ -1828,7 +1828,7 @@ func (m *ExpirationManager) renewEntry(ctx context.Context, le *leaseEntry, incr req := logical.RenewRequest(le.Path, &secret, le.Data) resp, err := m.router.Route(nsCtx, req) if err != nil || (resp != nil && resp.IsError()) { - return nil, errwrap.Wrapf(fmt.Sprintf("failed to renew entry: resp: %#v err: {{err}}", resp), err) + return nil, fmt.Errorf("failed to renew entry: resp: %#v err: %w", resp, err) } return resp, nil } @@ -1856,7 +1856,7 @@ func (m *ExpirationManager) renewAuthEntry(ctx context.Context, req *logical.Req authReq.Connection = req.Connection resp, err := m.router.Route(nsCtx, authReq) if err != nil { - return nil, errwrap.Wrapf("failed to renew entry: {{err}}", err) + return nil, fmt.Errorf("failed to renew entry: %w", err) } return resp, nil } @@ -1902,14 +1902,14 @@ func (m *ExpirationManager) loadEntryInternal(ctx context.Context, leaseID strin view := m.leaseView(ns) out, err := view.Get(ctx, leaseID) if err != nil { - return nil, errwrap.Wrapf(fmt.Sprintf("failed to read lease entry %s: {{err}}", leaseID), err) + return nil, fmt.Errorf("failed to read lease entry %s: %w", leaseID, err) } if out == nil { return nil, nil } le, err := decodeLeaseEntry(out.Value) if err != nil { - return nil, errwrap.Wrapf(fmt.Sprintf("failed to decode lease entry %s: {{err}}", leaseID), err) + return nil, fmt.Errorf("failed to decode lease entry %s: %w", leaseID, err) } le.namespace = ns @@ -1943,7 +1943,7 @@ func (m *ExpirationManager) persistEntry(ctx context.Context, le *leaseEntry) er // Encode the entry buf, err := le.encode() if err != nil { - return errwrap.Wrapf("failed to encode lease entry: {{err}}", err) + return fmt.Errorf("failed to encode lease entry: %w", err) } // Write out to the view @@ -1957,7 +1957,7 @@ func (m *ExpirationManager) persistEntry(ctx context.Context, le *leaseEntry) er view := m.leaseView(le.namespace) if err := view.Put(ctx, &ent); err != nil { - return errwrap.Wrapf("failed to persist lease entry: {{err}}", err) + return fmt.Errorf("failed to persist lease entry: %w", err) } return nil } @@ -1966,7 +1966,7 @@ func (m *ExpirationManager) persistEntry(ctx context.Context, le *leaseEntry) er func (m *ExpirationManager) deleteEntry(ctx context.Context, le *leaseEntry) error { view := m.leaseView(le.namespace) if err := view.Delete(ctx, le.LeaseID); err != nil { - return errwrap.Wrapf("failed to delete lease entry: {{err}}", err) + return fmt.Errorf("failed to delete lease entry: %w", err) } return nil } @@ -2003,7 +2003,7 @@ func (m *ExpirationManager) createIndexByToken(ctx context.Context, le *leaseEnt } tokenView := m.tokenIndexView(tokenNS) if err := tokenView.Put(ctx, &ent); err != nil { - return errwrap.Wrapf("failed to persist lease index entry: {{err}}", err) + return fmt.Errorf("failed to persist lease index entry: %w", err) } return nil } @@ -2081,7 +2081,7 @@ func (m *ExpirationManager) removeIndexByToken(ctx context.Context, le *leaseEnt key := saltedID + "/" + leaseSaltedID tokenView := m.tokenIndexView(tokenNS) if err := tokenView.Delete(ctx, key); err != nil { - return errwrap.Wrapf("failed to delete lease index entry: {{err}}", err) + return fmt.Errorf("failed to delete lease index entry: %w", err) } return nil } @@ -2173,7 +2173,7 @@ func (m *ExpirationManager) lookupLeasesByToken(ctx context.Context, te *logical prefix := saltedID + "/" subKeys, err := tokenView.List(ctx, prefix) if err != nil { - return nil, errwrap.Wrapf("failed to list leases: {{err}}", err) + return nil, fmt.Errorf("failed to list leases: %w", err) } // Read each index entry @@ -2181,7 +2181,7 @@ func (m *ExpirationManager) lookupLeasesByToken(ctx context.Context, te *logical for _, sub := range subKeys { out, err := tokenView.Get(ctx, prefix+sub) if err != nil { - return nil, errwrap.Wrapf("failed to read lease index: {{err}}", err) + return nil, fmt.Errorf("failed to read lease index: %w", err) } if out == nil { continue @@ -2198,13 +2198,13 @@ func (m *ExpirationManager) lookupLeasesByToken(ctx context.Context, te *logical prefix := saltedID + "/" subKeys, err := tokenView.List(ctx, prefix) if err != nil { - return nil, errwrap.Wrapf("failed to list leases on root namespace: {{err}}", err) + return nil, fmt.Errorf("failed to list leases on root namespace: %w", err) } for _, sub := range subKeys { out, err := tokenView.Get(ctx, prefix+sub) if err != nil { - return nil, errwrap.Wrapf("failed to read lease index on root namespace: {{err}}", err) + return nil, fmt.Errorf("failed to read lease index on root namespace: %w", err) } if out == nil { continue diff --git a/vault/expiration_util.go b/vault/expiration_util.go index c1bdaae18..eac1703bc 100644 --- a/vault/expiration_util.go +++ b/vault/expiration_util.go @@ -3,7 +3,8 @@ package vault import ( - "github.com/hashicorp/errwrap" + "fmt" + "github.com/hashicorp/vault/helper/namespace" "github.com/hashicorp/vault/sdk/logical" ) @@ -21,7 +22,7 @@ func (m *ExpirationManager) collectLeases() (map[*namespace.Namespace][]string, existing := make(map[*namespace.Namespace][]string) keys, err := logical.CollectKeys(m.quitContext, m.leaseView(namespace.RootNamespace)) if err != nil { - return nil, 0, errwrap.Wrapf("failed to scan for leases: {{err}}", err) + return nil, 0, fmt.Errorf("failed to scan for leases: %w", err) } existing[namespace.RootNamespace] = keys leaseCount += len(keys) diff --git a/vault/generate_root.go b/vault/generate_root.go index 745f57d5a..b701e5bfe 100644 --- a/vault/generate_root.go +++ b/vault/generate_root.go @@ -7,7 +7,6 @@ import ( "errors" "fmt" - "github.com/hashicorp/errwrap" "github.com/hashicorp/go-uuid" "github.com/hashicorp/vault/helper/pgpkeys" "github.com/hashicorp/vault/helper/xor" @@ -41,10 +40,10 @@ type generateStandardRootToken struct{} func (g generateStandardRootToken) authenticate(ctx context.Context, c *Core, combinedKey []byte) error { masterKey, err := c.unsealKeyToMasterKeyPostUnseal(ctx, combinedKey) if err != nil { - return errwrap.Wrapf("unable to authenticate: {{err}}", err) + return fmt.Errorf("unable to authenticate: %w", err) } if err := c.barrier.VerifyMaster(masterKey); err != nil { - return errwrap.Wrapf("master key verification failed: {{err}}", err) + return fmt.Errorf("master key verification failed: %w", err) } return nil @@ -142,7 +141,7 @@ func (c *Core) GenerateRootInit(otp, pgpKey string, strategy GenerateRootStrateg case len(pgpKey) > 0: fingerprints, err := pgpkeys.GetFingerprints([]string{pgpKey}, nil) if err != nil { - return errwrap.Wrapf("error parsing PGP key: {{err}}", err) + return fmt.Errorf("error parsing PGP key: %w", err) } if len(fingerprints) != 1 || fingerprints[0] == "" { return fmt.Errorf("could not acquire PGP key entity") @@ -304,13 +303,13 @@ func (c *Core) GenerateRootUpdate(ctx context.Context, key []byte, nonce string, combinedKey, err = shamir.Combine(c.generateRootProgress) c.generateRootProgress = nil if err != nil { - return nil, errwrap.Wrapf("failed to compute master key: {{err}}", err) + return nil, fmt.Errorf("failed to compute master key: %w", err) } } if err := strategy.authenticate(ctx, c, combinedKey); err != nil { c.logger.Error("root generation aborted", "error", err.Error()) - return nil, errwrap.Wrapf("root generation aborted: {{err}}", err) + return nil, fmt.Errorf("root generation aborted: %w", err) } // Run the generate strategy diff --git a/vault/generate_root_recovery.go b/vault/generate_root_recovery.go index 4ad839ea2..f016af013 100644 --- a/vault/generate_root_recovery.go +++ b/vault/generate_root_recovery.go @@ -2,8 +2,8 @@ package vault import ( "context" + "fmt" - "github.com/hashicorp/errwrap" "github.com/hashicorp/vault/sdk/helper/base62" "go.uber.org/atomic" ) @@ -23,17 +23,17 @@ type generateRecoveryToken struct { func (g *generateRecoveryToken) authenticate(ctx context.Context, c *Core, combinedKey []byte) error { key, err := c.unsealKeyToMasterKeyPostUnseal(ctx, combinedKey) if err != nil { - return errwrap.Wrapf("unable to authenticate: {{err}}", err) + return fmt.Errorf("unable to authenticate: %w", err) } // Use the retrieved master key to unseal the barrier if err := c.barrier.Unseal(ctx, key); err != nil { - return errwrap.Wrapf("recovery operation token generation failed, cannot unseal barrier: {{err}}", err) + return fmt.Errorf("recovery operation token generation failed, cannot unseal barrier: %w", err) } for _, v := range c.postRecoveryUnsealFuncs { if err := v(); err != nil { - return errwrap.Wrapf("failed to run post unseal func: {{err}}", err) + return fmt.Errorf("failed to run post unseal func: %w", err) } } return nil diff --git a/vault/ha.go b/vault/ha.go index d81d18ab7..158a6e604 100644 --- a/vault/ha.go +++ b/vault/ha.go @@ -18,7 +18,6 @@ import ( "github.com/hashicorp/vault/sdk/physical" "github.com/armon/go-metrics" - "github.com/hashicorp/errwrap" aeadwrapper "github.com/hashicorp/go-kms-wrapping/wrappers/aead" "github.com/hashicorp/go-multierror" "github.com/hashicorp/go-uuid" @@ -828,7 +827,7 @@ func (c *Core) checkKeyUpgrades(ctx context.Context) error { func (c *Core) reloadMasterKey(ctx context.Context) error { if err := c.barrier.ReloadMasterKey(ctx); err != nil { - return errwrap.Wrapf("error reloading master key: {{err}}", err) + return fmt.Errorf("error reloading master key: %w", err) } return nil } @@ -854,7 +853,7 @@ func (c *Core) reloadShamirKey(ctx context.Context) error { case seal.StoredKeysNotSupported: keyring, err := c.barrier.Keyring() if err != nil { - return errwrap.Wrapf("failed to update seal access: {{err}}", err) + return fmt.Errorf("failed to update seal access: %w", err) } shamirKey = keyring.masterKey } @@ -863,23 +862,23 @@ func (c *Core) reloadShamirKey(ctx context.Context) error { func (c *Core) performKeyUpgrades(ctx context.Context) error { if err := c.checkKeyUpgrades(ctx); err != nil { - return errwrap.Wrapf("error checking for key upgrades: {{err}}", err) + return fmt.Errorf("error checking for key upgrades: %w", err) } if err := c.reloadMasterKey(ctx); err != nil { - return errwrap.Wrapf("error reloading master key: {{err}}", err) + return fmt.Errorf("error reloading master key: %w", err) } if err := c.barrier.ReloadKeyring(ctx); err != nil { - return errwrap.Wrapf("error reloading keyring: {{err}}", err) + return fmt.Errorf("error reloading keyring: %w", err) } if err := c.reloadShamirKey(ctx); err != nil { - return errwrap.Wrapf("error reloading shamir kek key: {{err}}", err) + return fmt.Errorf("error reloading shamir kek key: %w", err) } if err := c.scheduleUpgradeCleanup(ctx); err != nil { - return errwrap.Wrapf("error scheduling upgrade cleanup: {{err}}", err) + return fmt.Errorf("error scheduling upgrade cleanup: %w", err) } return nil @@ -891,7 +890,7 @@ func (c *Core) scheduleUpgradeCleanup(ctx context.Context) error { // List the upgrades upgrades, err := c.barrier.List(ctx, keyringUpgradePrefix) if err != nil { - return errwrap.Wrapf("failed to list upgrades: {{err}}", err) + return fmt.Errorf("failed to list upgrades: %w", err) } // Nothing to do if no upgrades diff --git a/vault/identity_store.go b/vault/identity_store.go index b7e5422ac..176ba2a00 100644 --- a/vault/identity_store.go +++ b/vault/identity_store.go @@ -8,7 +8,6 @@ import ( metrics "github.com/armon/go-metrics" "github.com/golang/protobuf/ptypes" - "github.com/hashicorp/errwrap" log "github.com/hashicorp/go-hclog" "github.com/hashicorp/go-memdb" "github.com/hashicorp/vault/helper/identity" @@ -67,12 +66,12 @@ func NewIdentityStore(ctx context.Context, core *Core, config *logical.BackendCo core.AddLogger(groupsPackerLogger) iStore.entityPacker, err = storagepacker.NewStoragePacker(iStore.view, entitiesPackerLogger, "") if err != nil { - return nil, errwrap.Wrapf("failed to create entity packer: {{err}}", err) + return nil, fmt.Errorf("failed to create entity packer: %w", err) } iStore.groupPacker, err = storagepacker.NewStoragePacker(iStore.view, groupsPackerLogger, groupBucketsPrefix) if err != nil { - return nil, errwrap.Wrapf("failed to create group packer: {{err}}", err) + return nil, fmt.Errorf("failed to create group packer: %w", err) } iStore.Backend = &framework.Backend{ @@ -348,7 +347,7 @@ func (i *IdentityStore) parseEntityFromBucketItem(ctx context.Context, item *sto var oldEntity identity.EntityStorageEntry oldEntityErr := ptypes.UnmarshalAny(item.Message, &oldEntity) if oldEntityErr != nil { - return nil, errwrap.Wrapf("failed to decode entity from storage bucket item: {{err}}", err) + return nil, fmt.Errorf("failed to decode entity from storage bucket item: %w", err) } i.logger.Debug("upgrading the entity using patch introduced with vault 0.8.2.1", "entity_id", oldEntity.ID) @@ -425,7 +424,7 @@ func (i *IdentityStore) parseGroupFromBucketItem(item *storagepacker.Item) (*ide var group identity.Group err := ptypes.UnmarshalAny(item.Message, &group) if err != nil { - return nil, errwrap.Wrapf("failed to decode group from storage bucket item: {{err}}", err) + return nil, fmt.Errorf("failed to decode group from storage bucket item: %w", err) } if group.NamespaceID == "" { diff --git a/vault/identity_store_entities.go b/vault/identity_store_entities.go index 70dd3c507..95949c855 100644 --- a/vault/identity_store_entities.go +++ b/vault/identity_store_entities.go @@ -7,7 +7,6 @@ import ( "strings" "github.com/golang/protobuf/ptypes" - "github.com/hashicorp/errwrap" memdb "github.com/hashicorp/go-memdb" "github.com/hashicorp/vault/helper/identity" "github.com/hashicorp/vault/helper/identity/mfa" @@ -644,7 +643,7 @@ func (i *IdentityStore) handlePathEntityListCommon(ctx context.Context, req *log iter, err := txn.Get(entitiesTable, "namespace_id", ns.ID) if err != nil { - return nil, errwrap.Wrapf("failed to fetch iterator for entities in memdb: {{err}}", err) + return nil, fmt.Errorf("failed to fetch iterator for entities in memdb: %w", err) } ws.Add(iter.WatchCh()) @@ -793,7 +792,7 @@ func (i *IdentityStore) mergeEntity(ctx context.Context, txn *memdb.Txn, toEntit err = i.MemDBUpsertAliasInTxn(txn, alias, false) if err != nil { - return nil, errwrap.Wrapf("failed to update alias during merge: {{err}}", err) + return nil, fmt.Errorf("failed to update alias during merge: %w", err) } // Add the alias to the desired entity diff --git a/vault/identity_store_groups.go b/vault/identity_store_groups.go index 5f8c88f6b..0be981d9a 100644 --- a/vault/identity_store_groups.go +++ b/vault/identity_store_groups.go @@ -6,7 +6,6 @@ import ( "strings" "github.com/golang/protobuf/ptypes" - "github.com/hashicorp/errwrap" "github.com/hashicorp/vault/helper/identity" "github.com/hashicorp/vault/helper/namespace" "github.com/hashicorp/vault/sdk/framework" @@ -478,7 +477,7 @@ func (i *IdentityStore) handleGroupListCommon(ctx context.Context, byID bool) (* iter, err := txn.Get(groupsTable, "namespace_id", ns.ID) if err != nil { - return nil, errwrap.Wrapf("failed to lookup groups using namespace ID: {{err}}", err) + return nil, fmt.Errorf("failed to lookup groups using namespace ID: %w", err) } var keys []string diff --git a/vault/identity_store_oidc.go b/vault/identity_store_oidc.go index 7d9e098f0..dec2695bc 100644 --- a/vault/identity_store_oidc.go +++ b/vault/identity_store_oidc.go @@ -14,7 +14,6 @@ import ( "strings" "time" - "github.com/hashicorp/errwrap" "github.com/hashicorp/go-hclog" "github.com/hashicorp/go-uuid" "github.com/hashicorp/vault/helper/identity" @@ -780,7 +779,7 @@ func (i *IdentityStore) pathOIDCGenerateToken(ctx context.Context, req *logical. signedIdToken, err := key.signPayload(payload) if err != nil { - return nil, errwrap.Wrapf("error signing OIDC token: {{err}}", err) + return nil, fmt.Errorf("error signing OIDC token: %w", err) } return &logical.Response{ diff --git a/vault/identity_store_util.go b/vault/identity_store_util.go index a868fd374..f6535b615 100644 --- a/vault/identity_store_util.go +++ b/vault/identity_store_util.go @@ -82,7 +82,7 @@ func (i *IdentityStore) loadGroups(ctx context.Context) error { i.logger.Debug("identity loading groups") existing, err := i.groupPacker.View().List(ctx, groupBucketsPrefix) if err != nil { - return errwrap.Wrapf("failed to scan for groups: {{err}}", err) + return fmt.Errorf("failed to scan for groups: %w", err) } i.logger.Debug("groups collected", "num_existing", len(existing)) @@ -162,7 +162,7 @@ func (i *IdentityStore) loadGroups(ctx context.Context) error { err = i.UpsertGroupInTxn(ctx, txn, group, persist) if err != nil { txn.Abort() - return errwrap.Wrapf("failed to update group in memdb: {{err}}", err) + return fmt.Errorf("failed to update group in memdb: %w", err) } txn.Commit() @@ -181,7 +181,7 @@ func (i *IdentityStore) loadEntities(ctx context.Context) error { i.logger.Debug("loading entities") existing, err := i.entityPacker.View().List(ctx, storagepacker.StoragePackerBucketsPrefix) if err != nil { - return errwrap.Wrapf("failed to scan for entities: {{err}}", err) + return fmt.Errorf("failed to scan for entities: %w", err) } i.logger.Debug("entities collected", "num_existing", len(existing)) @@ -307,7 +307,7 @@ func (i *IdentityStore) loadEntities(ctx context.Context) error { // Only update MemDB and don't hit the storage again err = i.upsertEntity(nsCtx, entity, nil, false) if err != nil { - return errwrap.Wrapf("failed to update entity in MemDB: {{err}}", err) + return fmt.Errorf("failed to update entity in MemDB: %w", err) } } } @@ -522,18 +522,18 @@ func (i *IdentityStore) MemDBUpsertAliasInTxn(txn *memdb.Txn, alias *identity.Al aliasRaw, err := txn.First(tableName, "id", alias.ID) if err != nil { - return errwrap.Wrapf("failed to lookup alias from memdb using alias ID: {{err}}", err) + return fmt.Errorf("failed to lookup alias from memdb using alias ID: %w", err) } if aliasRaw != nil { err = txn.Delete(tableName, aliasRaw) if err != nil { - return errwrap.Wrapf("failed to delete alias from memdb: {{err}}", err) + return fmt.Errorf("failed to delete alias from memdb: %w", err) } } if err := txn.Insert(tableName, alias); err != nil { - return errwrap.Wrapf("failed to update alias into memdb: {{err}}", err) + return fmt.Errorf("failed to update alias into memdb: %w", err) } return nil @@ -555,7 +555,7 @@ func (i *IdentityStore) MemDBAliasByIDInTxn(txn *memdb.Txn, aliasID string, clon aliasRaw, err := txn.First(tableName, "id", aliasID) if err != nil { - return nil, errwrap.Wrapf("failed to fetch alias from memdb using alias ID: {{err}}", err) + return nil, fmt.Errorf("failed to fetch alias from memdb using alias ID: %w", err) } if aliasRaw == nil { @@ -618,7 +618,7 @@ func (i *IdentityStore) MemDBAliasByFactorsInTxn(txn *memdb.Txn, mountAccessor, aliasRaw, err := txn.First(tableName, "factors", mountAccessor, aliasName) if err != nil { - return nil, errwrap.Wrapf("failed to fetch alias from memdb using factors: {{err}}", err) + return nil, fmt.Errorf("failed to fetch alias from memdb using factors: %w", err) } if aliasRaw == nil { @@ -662,7 +662,7 @@ func (i *IdentityStore) MemDBDeleteAliasByIDInTxn(txn *memdb.Txn, aliasID string err = txn.Delete(tableName, alias) if err != nil { - return errwrap.Wrapf("failed to delete alias from memdb: {{err}}", err) + return fmt.Errorf("failed to delete alias from memdb: %w", err) } return nil @@ -701,18 +701,18 @@ func (i *IdentityStore) MemDBUpsertEntityInTxn(txn *memdb.Txn, entity *identity. entityRaw, err := txn.First(entitiesTable, "id", entity.ID) if err != nil { - return errwrap.Wrapf("failed to lookup entity from memdb using entity id: {{err}}", err) + return fmt.Errorf("failed to lookup entity from memdb using entity id: %w", err) } if entityRaw != nil { err = txn.Delete(entitiesTable, entityRaw) if err != nil { - return errwrap.Wrapf("failed to delete entity from memdb: {{err}}", err) + return fmt.Errorf("failed to delete entity from memdb: %w", err) } } if err := txn.Insert(entitiesTable, entity); err != nil { - return errwrap.Wrapf("failed to update entity into memdb: {{err}}", err) + return fmt.Errorf("failed to update entity into memdb: %w", err) } return nil @@ -729,7 +729,7 @@ func (i *IdentityStore) MemDBEntityByIDInTxn(txn *memdb.Txn, entityID string, cl entityRaw, err := txn.First(entitiesTable, "id", entityID) if err != nil { - return nil, errwrap.Wrapf("failed to fetch entity from memdb using entity id: {{err}}", err) + return nil, fmt.Errorf("failed to fetch entity from memdb using entity id: %w", err) } if entityRaw == nil { @@ -780,7 +780,7 @@ func (i *IdentityStore) MemDBEntityByNameInTxn(ctx context.Context, txn *memdb.T entityRaw, err := txn.First(entitiesTable, "name", ns.ID, entityName) if err != nil { - return nil, errwrap.Wrapf("failed to fetch entity from memdb using entity name: {{err}}", err) + return nil, fmt.Errorf("failed to fetch entity from memdb using entity name: %w", err) } if entityRaw == nil { @@ -810,7 +810,7 @@ func (i *IdentityStore) MemDBEntitiesByBucketKeyInTxn(txn *memdb.Txn, bucketKey entitiesIter, err := txn.Get(entitiesTable, "bucket_key", bucketKey) if err != nil { - return nil, errwrap.Wrapf("failed to lookup entities using bucket entry key hash: {{err}}", err) + return nil, fmt.Errorf("failed to lookup entities using bucket entry key hash: %w", err) } var entities []*identity.Entity @@ -830,7 +830,7 @@ func (i *IdentityStore) MemDBEntityByMergedEntityID(mergedEntityID string, clone entityRaw, err := txn.First(entitiesTable, "merged_entity_ids", mergedEntityID) if err != nil { - return nil, errwrap.Wrapf("failed to fetch entity from memdb using merged entity id: {{err}}", err) + return nil, fmt.Errorf("failed to fetch entity from memdb using merged entity id: %w", err) } if entityRaw == nil { @@ -918,7 +918,7 @@ func (i *IdentityStore) MemDBDeleteEntityByIDInTxn(txn *memdb.Txn, entityID stri err = txn.Delete(entitiesTable, entity) if err != nil { - return errwrap.Wrapf("failed to delete entity from memdb: {{err}}", err) + return fmt.Errorf("failed to delete entity from memdb: %w", err) } return nil @@ -944,7 +944,7 @@ func (i *IdentityStore) sanitizeAlias(ctx context.Context, alias *identity.Alias // Alias metadata should always be map[string]string err = validateMetadata(alias.Metadata) if err != nil { - return errwrap.Wrapf("invalid alias metadata: {{err}}", err) + return fmt.Errorf("invalid alias metadata: %w", err) } // Create an ID if there isn't one already @@ -1022,7 +1022,7 @@ func (i *IdentityStore) sanitizeEntity(ctx context.Context, entity *identity.Ent // Entity metadata should always be map[string]string err = validateMetadata(entity.Metadata) if err != nil { - return errwrap.Wrapf("invalid entity metadata: {{err}}", err) + return fmt.Errorf("invalid entity metadata: %w", err) } // Set the creation and last update times @@ -1086,7 +1086,7 @@ func (i *IdentityStore) sanitizeAndUpsertGroup(ctx context.Context, group *ident // Entity metadata should always be map[string]string err = validateMetadata(group.Metadata) if err != nil { - return errwrap.Wrapf("invalid group metadata: {{err}}", err) + return fmt.Errorf("invalid group metadata: %w", err) } // Set the creation and last update times @@ -1102,7 +1102,7 @@ func (i *IdentityStore) sanitizeAndUpsertGroup(ctx context.Context, group *ident for _, entityID := range group.MemberEntityIDs { entity, err := i.MemDBEntityByID(entityID, false) if err != nil { - return errwrap.Wrapf(fmt.Sprintf("failed to validate entity ID %q: {{err}}", entityID), err) + return fmt.Errorf("failed to validate entity ID %q: %w", entityID, err) } if entity == nil { return fmt.Errorf("invalid entity ID %q", entityID) @@ -1294,7 +1294,7 @@ func validateMetadata(meta map[string]string) error { for key, value := range meta { if err := validateMetaPair(key, value); err != nil { - return errwrap.Wrapf(fmt.Sprintf("failed to load metadata pair (%q, %q): {{err}}", key, value), err) + return fmt.Errorf("failed to load metadata pair (%q, %q): %w", key, value, err) } } @@ -1337,7 +1337,7 @@ func (i *IdentityStore) MemDBGroupByNameInTxn(ctx context.Context, txn *memdb.Tx groupRaw, err := txn.First(groupsTable, "name", ns.ID, groupName) if err != nil { - return nil, errwrap.Wrapf("failed to fetch group from memdb using group name: {{err}}", err) + return nil, fmt.Errorf("failed to fetch group from memdb using group name: %w", err) } if groupRaw == nil { @@ -1464,18 +1464,18 @@ func (i *IdentityStore) MemDBUpsertGroupInTxn(txn *memdb.Txn, group *identity.Gr groupRaw, err := txn.First(groupsTable, "id", group.ID) if err != nil { - return errwrap.Wrapf("failed to lookup group from memdb using group id: {{err}}", err) + return fmt.Errorf("failed to lookup group from memdb using group id: %w", err) } if groupRaw != nil { err = txn.Delete(groupsTable, groupRaw) if err != nil { - return errwrap.Wrapf("failed to delete group from memdb: {{err}}", err) + return fmt.Errorf("failed to delete group from memdb: %w", err) } } if err := txn.Insert(groupsTable, group); err != nil { - return errwrap.Wrapf("failed to update group into memdb: {{err}}", err) + return fmt.Errorf("failed to update group into memdb: %w", err) } return nil @@ -1501,7 +1501,7 @@ func (i *IdentityStore) MemDBDeleteGroupByIDInTxn(txn *memdb.Txn, groupID string err = txn.Delete("groups", group) if err != nil { - return errwrap.Wrapf("failed to delete group from memdb: {{err}}", err) + return fmt.Errorf("failed to delete group from memdb: %w", err) } return nil @@ -1518,7 +1518,7 @@ func (i *IdentityStore) MemDBGroupByIDInTxn(txn *memdb.Txn, groupID string, clon groupRaw, err := txn.First(groupsTable, "id", groupID) if err != nil { - return nil, errwrap.Wrapf("failed to fetch group from memdb using group ID: {{err}}", err) + return nil, fmt.Errorf("failed to fetch group from memdb using group ID: %w", err) } if groupRaw == nil { @@ -1554,7 +1554,7 @@ func (i *IdentityStore) MemDBGroupsByParentGroupIDInTxn(txn *memdb.Txn, memberGr groupsIter, err := txn.Get(groupsTable, "parent_group_ids", memberGroupID) if err != nil { - return nil, errwrap.Wrapf("failed to lookup groups using member group ID: {{err}}", err) + return nil, fmt.Errorf("failed to lookup groups using member group ID: %w", err) } var groups []*identity.Group @@ -1596,7 +1596,7 @@ func (i *IdentityStore) MemDBGroupsByMemberEntityIDInTxn(txn *memdb.Txn, entityI groupsIter, err := txn.Get(groupsTable, "member_entity_ids", entityID) if err != nil { - return nil, errwrap.Wrapf("failed to lookup groups using entity ID: {{err}}", err) + return nil, fmt.Errorf("failed to lookup groups using entity ID: %w", err) } var groups []*identity.Group @@ -1842,7 +1842,7 @@ func (i *IdentityStore) MemDBGroupsByBucketKeyInTxn(txn *memdb.Txn, bucketKey st groupsIter, err := txn.Get(groupsTable, "bucket_key", bucketKey) if err != nil { - return nil, errwrap.Wrapf("failed to lookup groups using bucket entry key hash: {{err}}", err) + return nil, fmt.Errorf("failed to lookup groups using bucket entry key hash: %w", err) } var groups []*identity.Group @@ -2058,7 +2058,7 @@ func (i *IdentityStore) handleAliasListCommon(ctx context.Context, groupAlias bo iter, err := txn.Get(tableName, "namespace_id", ns.ID) if err != nil { - return nil, errwrap.Wrapf("failed to fetch iterator for aliases in memdb: {{err}}", err) + return nil, fmt.Errorf("failed to fetch iterator for aliases in memdb: %w", err) } ws.Add(iter.WatchCh()) diff --git a/vault/init.go b/vault/init.go index 3afde6b81..64f1c6a9b 100644 --- a/vault/init.go +++ b/vault/init.go @@ -13,7 +13,6 @@ import ( "github.com/hashicorp/vault/physical/raft" "github.com/hashicorp/vault/vault/seal" - "github.com/hashicorp/errwrap" aeadwrapper "github.com/hashicorp/go-kms-wrapping/wrappers/aead" "github.com/hashicorp/vault/helper/namespace" "github.com/hashicorp/vault/helper/pgpkeys" @@ -125,7 +124,7 @@ func (c *Core) generateShares(sc *SealConfig) ([]byte, [][]byte, error) { // Generate a master key masterKey, err := c.barrier.GenerateKey(c.secureRandomReader) if err != nil { - return nil, nil, errwrap.Wrapf("key generation failed: {{err}}", err) + return nil, nil, fmt.Errorf("key generation failed: %w", err) } // Return the master key if only a single key part is used @@ -136,7 +135,7 @@ func (c *Core) generateShares(sc *SealConfig) ([]byte, [][]byte, error) { // Split the master key using the Shamir algorithm shares, err := shamir.Split(masterKey, sc.SecretShares, sc.SecretThreshold) if err != nil { - return nil, nil, errwrap.Wrapf("failed to generate barrier shares: {{err}}", err) + return nil, nil, fmt.Errorf("failed to generate barrier shares: %w", err) } unsealKeys = shares } @@ -212,14 +211,14 @@ func (c *Core) Initialize(ctx context.Context, initParams *InitParams) (*InitRes // Check if the seal configuration is valid if err := recoveryConfig.Validate(); err != nil { c.logger.Error("invalid recovery configuration", "error", err) - return nil, errwrap.Wrapf("invalid recovery configuration: {{err}}", err) + return nil, fmt.Errorf("invalid recovery configuration: %w", err) } } // Check if the seal configuration is valid if err := barrierConfig.Validate(); err != nil { c.logger.Error("invalid seal configuration", "error", err) - return nil, errwrap.Wrapf("invalid seal configuration: {{err}}", err) + return nil, fmt.Errorf("invalid seal configuration: %w", err) } // Avoid an initialization race @@ -256,7 +255,7 @@ func (c *Core) Initialize(ctx context.Context, initParams *InitParams) (*InitRes err = c.seal.Init(ctx) if err != nil { c.logger.Error("failed to initialize seal", "error", err) - return nil, errwrap.Wrapf("error initializing seal: {{err}}", err) + return nil, fmt.Errorf("error initializing seal: %w", err) } initPTCleanup := initPTFunc(c) @@ -283,7 +282,7 @@ func (c *Core) Initialize(ctx context.Context, initParams *InitParams) (*InitRes // Initialize the barrier if err := c.barrier.Initialize(ctx, barrierKey, sealKey, c.secureRandomReader); err != nil { c.logger.Error("failed to initialize barrier", "error", err) - return nil, errwrap.Wrapf("failed to initialize barrier: {{err}}", err) + return nil, fmt.Errorf("failed to initialize barrier: %w", err) } if c.logger.IsInfo() { c.logger.Info("security barrier initialized", "stored", barrierConfig.StoredShares, "shares", barrierConfig.SecretShares, "threshold", barrierConfig.SecretThreshold) @@ -292,7 +291,7 @@ func (c *Core) Initialize(ctx context.Context, initParams *InitParams) (*InitRes // Unseal the barrier if err := c.barrier.Unseal(ctx, barrierKey); err != nil { c.logger.Error("failed to unseal barrier", "error", err) - return nil, errwrap.Wrapf("failed to unseal barrier: {{err}}", err) + return nil, fmt.Errorf("failed to unseal barrier: %w", err) } // Ensure the barrier is re-sealed @@ -308,7 +307,7 @@ func (c *Core) Initialize(ctx context.Context, initParams *InitParams) (*InitRes err = c.seal.SetBarrierConfig(ctx, barrierConfig) if err != nil { c.logger.Error("failed to save barrier configuration", "error", err) - return nil, errwrap.Wrapf("barrier configuration saving failed: {{err}}", err) + return nil, fmt.Errorf("barrier configuration saving failed: %w", err) } results := &InitResult{ @@ -322,18 +321,18 @@ func (c *Core) Initialize(ctx context.Context, initParams *InitParams) (*InitRes keysToStore := [][]byte{barrierKey} if err := c.seal.GetAccess().Wrapper.(*aeadwrapper.ShamirWrapper).SetAESGCMKeyBytes(sealKey); err != nil { c.logger.Error("failed to set seal key", "error", err) - return nil, errwrap.Wrapf("failed to set seal key: {{err}}", err) + return nil, fmt.Errorf("failed to set seal key: %w", err) } if err := c.seal.SetStoredKeys(ctx, keysToStore); err != nil { c.logger.Error("failed to store keys", "error", err) - return nil, errwrap.Wrapf("failed to store keys: {{err}}", err) + return nil, fmt.Errorf("failed to store keys: %w", err) } results.SecretShares = sealKeyShares case seal.StoredKeysSupportedGeneric: keysToStore := [][]byte{barrierKey} if err := c.seal.SetStoredKeys(ctx, keysToStore); err != nil { c.logger.Error("failed to store keys", "error", err) - return nil, errwrap.Wrapf("failed to store keys: {{err}}", err) + return nil, fmt.Errorf("failed to store keys: %w", err) } default: // We don't support initializing an old-style Shamir seal anymore, so @@ -365,7 +364,7 @@ func (c *Core) Initialize(ctx context.Context, initParams *InitParams) (*InitRes err = c.seal.SetRecoveryConfig(ctx, recoveryConfig) if err != nil { c.logger.Error("failed to save recovery configuration", "error", err) - return nil, errwrap.Wrapf("recovery configuration saving failed: {{err}}", err) + return nil, fmt.Errorf("recovery configuration saving failed: %w", err) } if recoveryConfig.SecretShares > 0 { @@ -456,7 +455,7 @@ func (c *Core) UnsealWithStoredKeys(ctx context.Context) error { c.Logger().Info("stored unseal keys supported, attempting fetch") keys, err := c.seal.GetStoredKeys(ctx) if err != nil { - return NewNonFatalError(errwrap.Wrapf("fetching stored unseal keys failed: {{err}}", err)) + return NewNonFatalError(fmt.Errorf("fetching stored unseal keys failed: %w", err)) } // This usually happens when auto-unseal is configured, but the servers have @@ -470,7 +469,7 @@ func (c *Core) UnsealWithStoredKeys(ctx context.Context) error { err = c.unsealInternal(ctx, keys[0]) if err != nil { - return NewNonFatalError(errwrap.Wrapf("unseal with stored key failed: {{err}}", err)) + return NewNonFatalError(fmt.Errorf("unseal with stored key failed: %w", err)) } if c.Sealed() { diff --git a/vault/keyring.go b/vault/keyring.go index e2ea9441f..7db04a7c8 100644 --- a/vault/keyring.go +++ b/vault/keyring.go @@ -6,7 +6,6 @@ import ( "fmt" "time" - "github.com/hashicorp/errwrap" "github.com/hashicorp/vault/sdk/helper/jsonutil" ) @@ -73,7 +72,7 @@ func (k *Key) Serialize() ([]byte, error) { func DeserializeKey(buf []byte) (*Key, error) { k := new(Key) if err := jsonutil.DecodeJSON(buf, k); err != nil { - return nil, errwrap.Wrapf("deserialization failed: {{err}}", err) + return nil, fmt.Errorf("deserialization failed: %w", err) } return k, nil } @@ -206,7 +205,7 @@ func DeserializeKeyring(buf []byte) (*Keyring, error) { // Deserialize the keyring var enc EncodedKeyring if err := jsonutil.DecodeJSON(buf, &enc); err != nil { - return nil, errwrap.Wrapf("deserialization failed: {{err}}", err) + return nil, fmt.Errorf("deserialization failed: %w", err) } // Create a new keyring diff --git a/vault/logical_cubbyhole.go b/vault/logical_cubbyhole.go index 719be7552..51d5e81a3 100644 --- a/vault/logical_cubbyhole.go +++ b/vault/logical_cubbyhole.go @@ -6,7 +6,6 @@ import ( "fmt" "strings" - "github.com/hashicorp/errwrap" "github.com/hashicorp/vault/sdk/framework" "github.com/hashicorp/vault/sdk/helper/jsonutil" "github.com/hashicorp/vault/sdk/logical" @@ -98,7 +97,7 @@ func (b *CubbyholeBackend) revoke(ctx context.Context, view *BarrierView, salted func (b *CubbyholeBackend) handleExistenceCheck(ctx context.Context, req *logical.Request, data *framework.FieldData) (bool, error) { out, err := req.Storage.Get(ctx, req.ClientToken+"/"+req.Path) if err != nil { - return false, errwrap.Wrapf("existence check failed: {{err}}", err) + return false, fmt.Errorf("existence check failed: %w", err) } return out != nil, nil @@ -118,7 +117,7 @@ func (b *CubbyholeBackend) handleRead(ctx context.Context, req *logical.Request, // Read the path out, err := req.Storage.Get(ctx, req.ClientToken+"/"+path) if err != nil { - return nil, errwrap.Wrapf("read failed: {{err}}", err) + return nil, fmt.Errorf("read failed: %w", err) } // Fast-path the no data case @@ -129,7 +128,7 @@ func (b *CubbyholeBackend) handleRead(ctx context.Context, req *logical.Request, // Decode the data var rawData map[string]interface{} if err := jsonutil.DecodeJSON(out.Value, &rawData); err != nil { - return nil, errwrap.Wrapf("json decoding failed: {{err}}", err) + return nil, fmt.Errorf("json decoding failed: %w", err) } // Generate the response @@ -158,7 +157,7 @@ func (b *CubbyholeBackend) handleWrite(ctx context.Context, req *logical.Request // JSON encode the data buf, err := json.Marshal(req.Data) if err != nil { - return nil, errwrap.Wrapf("json encoding failed: {{err}}", err) + return nil, fmt.Errorf("json encoding failed: %w", err) } // Write out a new key @@ -170,7 +169,7 @@ func (b *CubbyholeBackend) handleWrite(ctx context.Context, req *logical.Request entry.SealWrap = true } if err := req.Storage.Put(ctx, entry); err != nil { - return nil, errwrap.Wrapf("failed to write: {{err}}", err) + return nil, fmt.Errorf("failed to write: %w", err) } return nil, nil diff --git a/vault/logical_passthrough.go b/vault/logical_passthrough.go index 23d854dc2..c04bcd4ab 100644 --- a/vault/logical_passthrough.go +++ b/vault/logical_passthrough.go @@ -6,7 +6,6 @@ import ( "fmt" "strings" - "github.com/hashicorp/errwrap" "github.com/hashicorp/vault/sdk/framework" "github.com/hashicorp/vault/sdk/helper/jsonutil" "github.com/hashicorp/vault/sdk/helper/parseutil" @@ -95,7 +94,7 @@ func (b *PassthroughBackend) handleRevoke(ctx context.Context, req *logical.Requ func (b *PassthroughBackend) handleExistenceCheck(ctx context.Context, req *logical.Request, data *framework.FieldData) (bool, error) { out, err := req.Storage.Get(ctx, req.Path) if err != nil { - return false, errwrap.Wrapf("existence check failed: {{err}}", err) + return false, fmt.Errorf("existence check failed: %w", err) } return out != nil, nil @@ -105,7 +104,7 @@ func (b *PassthroughBackend) handleRead(ctx context.Context, req *logical.Reques // Read the path out, err := req.Storage.Get(ctx, req.Path) if err != nil { - return nil, errwrap.Wrapf("read failed: {{err}}", err) + return nil, fmt.Errorf("read failed: %w", err) } // Fast-path the no data case @@ -117,7 +116,7 @@ func (b *PassthroughBackend) handleRead(ctx context.Context, req *logical.Reques var rawData map[string]interface{} if err := jsonutil.DecodeJSON(out.Value, &rawData); err != nil { - return nil, errwrap.Wrapf("json decoding failed: {{err}}", err) + return nil, fmt.Errorf("json decoding failed: %w", err) } var resp *logical.Response @@ -180,7 +179,7 @@ func (b *PassthroughBackend) handleWrite(ctx context.Context, req *logical.Reque // JSON encode the data buf, err := json.Marshal(req.Data) if err != nil { - return nil, errwrap.Wrapf("json encoding failed: {{err}}", err) + return nil, fmt.Errorf("json encoding failed: %w", err) } // Write out a new key @@ -189,7 +188,7 @@ func (b *PassthroughBackend) handleWrite(ctx context.Context, req *logical.Reque Value: buf, } if err := req.Storage.Put(ctx, entry); err != nil { - return nil, errwrap.Wrapf("failed to write: {{err}}", err) + return nil, fmt.Errorf("failed to write: %w", err) } return nil, nil diff --git a/vault/logical_system.go b/vault/logical_system.go index c2d3f2653..fe743cf65 100644 --- a/vault/logical_system.go +++ b/vault/logical_system.go @@ -633,7 +633,7 @@ func (b *SystemBackend) handleRekeyRetrieve( recovery bool) (*logical.Response, error) { backup, err := b.Core.RekeyRetrieveBackup(ctx, recovery) if err != nil { - return nil, errwrap.Wrapf("unable to look up backed-up keys: {{err}}", err) + return nil, fmt.Errorf("unable to look up backed-up keys: %w", err) } if backup == nil { return logical.ErrorResponse("no backed-up keys found"), nil @@ -648,7 +648,7 @@ func (b *SystemBackend) handleRekeyRetrieve( } key, err := hex.DecodeString(j) if err != nil { - return nil, errwrap.Wrapf("error decoding hex-encoded backup key: {{err}}", err) + return nil, fmt.Errorf("error decoding hex-encoded backup key: %w", err) } currB64Keys = append(currB64Keys, base64.StdEncoding.EncodeToString(key)) keysB64[k] = currB64Keys @@ -684,7 +684,7 @@ func (b *SystemBackend) handleRekeyDelete( recovery bool) (*logical.Response, error) { err := b.Core.RekeyDeleteBackup(ctx, recovery) if err != nil { - return nil, errwrap.Wrapf("error during deletion of backed-up keys: {{err}}", err) + return nil, fmt.Errorf("error during deletion of backed-up keys: %w", err) } return nil, nil @@ -1511,11 +1511,11 @@ func (b *SystemBackend) handleTuneWriteCommon(ctx context.Context, path string, // enabled. If the vkv backend suports downgrading this can be removed. meVersion, err := parseutil.ParseInt(mountEntry.Options["version"]) if err != nil { - return nil, errwrap.Wrapf("unable to parse mount entry: {{err}}", err) + return nil, fmt.Errorf("unable to parse mount entry: %w", err) } optVersion, err := parseutil.ParseInt(v) if err != nil { - return handleError(errwrap.Wrapf("unable to parse options: {{err}}", err)) + return handleError(fmt.Errorf("unable to parse options: %w", err)) } // Only accept valid versions @@ -2715,7 +2715,7 @@ func (b *SystemBackend) handleWrappingUnwrap(ctx context.Context, req *logical.R httpResp := &logical.HTTPResponse{} err = jsonutil.DecodeJSON([]byte(response), httpResp) if err != nil { - return nil, errwrap.Wrapf("error decoding wrapped response: {{err}}", err) + return nil, fmt.Errorf("error decoding wrapped response: %w", err) } if httpResp.Data != nil && (httpResp.Data[logical.HTTPStatusCode] != nil || @@ -2769,7 +2769,7 @@ func (b *SystemBackend) responseWrappingUnwrap(ctx context.Context, te *logical. // Use the token to decrement the use count to avoid a second operation on the token. _, err := b.Core.tokenStore.UseTokenByID(ctx, tokenID) if err != nil { - return "", errwrap.Wrapf("error decrementing wrapping token's use-count: {{err}}", err) + return "", fmt.Errorf("error decrementing wrapping token's use-count: %w", err) } defer b.Core.tokenStore.revokeOrphan(ctx, tokenID) @@ -2783,7 +2783,7 @@ func (b *SystemBackend) responseWrappingUnwrap(ctx context.Context, te *logical. cubbyReq.SetTokenEntry(te) cubbyResp, err := b.Core.router.Route(ctx, cubbyReq) if err != nil { - return "", errwrap.Wrapf("error looking up wrapping information: {{err}}", err) + return "", fmt.Errorf("error looking up wrapping information: %w", err) } if cubbyResp == nil { return "no information found; wrapping token may be from a previous Vault version", ErrInternalError @@ -2979,7 +2979,7 @@ func (b *SystemBackend) handleWrappingLookup(ctx context.Context, req *logical.R cubbyReq.SetTokenEntry(te) cubbyResp, err := b.Core.router.Route(ctx, cubbyReq) if err != nil { - return nil, errwrap.Wrapf("error looking up wrapping information: {{err}}", err) + return nil, fmt.Errorf("error looking up wrapping information: %w", err) } if cubbyResp == nil { return logical.ErrorResponse("no information found; wrapping token may be from a previous Vault version"), nil @@ -3001,7 +3001,7 @@ func (b *SystemBackend) handleWrappingLookup(ctx context.Context, req *logical.R if creationTTLRaw != nil { creationTTL, err := creationTTLRaw.(json.Number).Int64() if err != nil { - return nil, errwrap.Wrapf("error reading creation_ttl value from wrapping information: {{err}}", err) + return nil, fmt.Errorf("error reading creation_ttl value from wrapping information: %w", err) } resp.Data["creation_ttl"] = time.Duration(creationTTL).Seconds() } @@ -3046,7 +3046,7 @@ func (b *SystemBackend) handleWrappingRewrap(ctx context.Context, req *logical.R // Use the token to decrement the use count to avoid a second operation on the token. _, err := b.Core.tokenStore.UseTokenByID(ctx, token) if err != nil { - return nil, errwrap.Wrapf("error decrementing wrapping token's use-count: {{err}}", err) + return nil, fmt.Errorf("error decrementing wrapping token's use-count: %w", err) } defer b.Core.tokenStore.revokeOrphan(ctx, token) } @@ -3060,7 +3060,7 @@ func (b *SystemBackend) handleWrappingRewrap(ctx context.Context, req *logical.R cubbyReq.SetTokenEntry(te) cubbyResp, err := b.Core.router.Route(ctx, cubbyReq) if err != nil { - return nil, errwrap.Wrapf("error looking up wrapping information: {{err}}", err) + return nil, fmt.Errorf("error looking up wrapping information: %w", err) } if cubbyResp == nil { return logical.ErrorResponse("no information found; wrapping token may be from a previous Vault version"), nil @@ -3079,7 +3079,7 @@ func (b *SystemBackend) handleWrappingRewrap(ctx context.Context, req *logical.R } creationTTL, err := cubbyResp.Data["creation_ttl"].(json.Number).Int64() if err != nil { - return nil, errwrap.Wrapf("error reading creation_ttl value from wrapping information: {{err}}", err) + return nil, fmt.Errorf("error reading creation_ttl value from wrapping information: %w", err) } // Get creation_path to return as the response later @@ -3098,7 +3098,7 @@ func (b *SystemBackend) handleWrappingRewrap(ctx context.Context, req *logical.R cubbyReq.SetTokenEntry(te) cubbyResp, err = b.Core.router.Route(ctx, cubbyReq) if err != nil { - return nil, errwrap.Wrapf("error looking up response: {{err}}", err) + return nil, fmt.Errorf("error looking up response: %w", err) } if cubbyResp == nil { return logical.ErrorResponse("no information found; wrapping token may be from a previous Vault version"), nil diff --git a/vault/plugin_catalog.go b/vault/plugin_catalog.go index d52c1ac37..71d4603e6 100644 --- a/vault/plugin_catalog.go +++ b/vault/plugin_catalog.go @@ -10,7 +10,6 @@ import ( "strings" "sync" - "github.com/hashicorp/errwrap" log "github.com/hashicorp/go-hclog" multierror "github.com/hashicorp/go-multierror" v4 "github.com/hashicorp/vault/sdk/database/dbplugin" @@ -157,13 +156,13 @@ func (c *PluginCatalog) UpgradePlugins(ctx context.Context, logger log.Logger) e for _, pluginName := range plugins { pluginRaw, err := c.catalogView.Get(ctx, pluginName) if err != nil { - retErr = multierror.Append(errwrap.Wrapf("failed to load plugin entry: {{err}}", err)) + retErr = multierror.Append(fmt.Errorf("failed to load plugin entry: %w", err)) continue } plugin := new(pluginutil.PluginRunner) if err := jsonutil.DecodeJSON(pluginRaw.Value, plugin); err != nil { - retErr = multierror.Append(errwrap.Wrapf("failed to decode plugin entry: {{err}}", err)) + retErr = multierror.Append(fmt.Errorf("failed to decode plugin entry: %w", err)) continue } @@ -215,20 +214,20 @@ func (c *PluginCatalog) get(ctx context.Context, name string, pluginType consts. // Look for external plugins in the barrier out, err := c.catalogView.Get(ctx, pluginType.String()+"/"+name) if err != nil { - return nil, errwrap.Wrapf(fmt.Sprintf("failed to retrieve plugin %q: {{err}}", name), err) + return nil, fmt.Errorf("failed to retrieve plugin %q: %w", name, err) } if out == nil { // Also look for external plugins under what their name would have been if they // were registered before plugin types existed. out, err = c.catalogView.Get(ctx, name) if err != nil { - return nil, errwrap.Wrapf(fmt.Sprintf("failed to retrieve plugin %q: {{err}}", name), err) + return nil, fmt.Errorf("failed to retrieve plugin %q: %w", name, err) } } if out != nil { entry := new(pluginutil.PluginRunner) if err := jsonutil.DecodeJSON(out.Value, entry); err != nil { - return nil, errwrap.Wrapf("failed to decode plugin entry: {{err}}", err) + return nil, fmt.Errorf("failed to decode plugin entry: %w", err) } if entry.Type != pluginType && entry.Type != consts.PluginTypeUnknown { return nil, nil @@ -279,11 +278,11 @@ func (c *PluginCatalog) setInternal(ctx context.Context, name string, pluginType commandFull := filepath.Join(c.directory, command) sym, err := filepath.EvalSymlinks(commandFull) if err != nil { - return errwrap.Wrapf("error while validating the command path: {{err}}", err) + return fmt.Errorf("error while validating the command path: %w", err) } symAbs, err := filepath.Abs(filepath.Dir(sym)) if err != nil { - return errwrap.Wrapf("error while validating the command path: {{err}}", err) + return fmt.Errorf("error while validating the command path: %w", err) } if symAbs != c.directory { @@ -324,7 +323,7 @@ func (c *PluginCatalog) setInternal(ctx context.Context, name string, pluginType buf, err := json.Marshal(entry) if err != nil { - return errwrap.Wrapf("failed to encode plugin entry: {{err}}", err) + return fmt.Errorf("failed to encode plugin entry: %w", err) } logicalEntry := logical.StorageEntry{ @@ -332,7 +331,7 @@ func (c *PluginCatalog) setInternal(ctx context.Context, name string, pluginType Value: buf, } if err := c.catalogView.Put(ctx, &logicalEntry); err != nil { - return errwrap.Wrapf("failed to persist plugin entry: {{err}}", err) + return fmt.Errorf("failed to persist plugin entry: %w", err) } return nil } diff --git a/vault/plugin_reload.go b/vault/plugin_reload.go index 0d94623e7..bfc455586 100644 --- a/vault/plugin_reload.go +++ b/vault/plugin_reload.go @@ -7,7 +7,6 @@ import ( "github.com/hashicorp/vault/helper/namespace" - "github.com/hashicorp/errwrap" multierror "github.com/hashicorp/go-multierror" "github.com/hashicorp/vault/sdk/helper/strutil" "github.com/hashicorp/vault/sdk/logical" @@ -47,7 +46,7 @@ func (c *Core) reloadMatchingPluginMounts(ctx context.Context, mounts []string) err := c.reloadBackendCommon(ctx, entry, isAuth) if err != nil { - errors = multierror.Append(errors, errwrap.Wrapf(fmt.Sprintf("cannot reload plugin on %q: {{err}}", mount), err)) + errors = multierror.Append(errors, fmt.Errorf("cannot reload plugin on %q: %w", mount, err)) continue } c.logger.Info("successfully reloaded plugin", "plugin", entry.Accessor, "path", entry.Path) diff --git a/vault/policy.go b/vault/policy.go index 6f6ec8b55..e87372933 100644 --- a/vault/policy.go +++ b/vault/policy.go @@ -6,7 +6,6 @@ import ( "strings" "time" - "github.com/hashicorp/errwrap" multierror "github.com/hashicorp/go-multierror" "github.com/hashicorp/hcl" "github.com/hashicorp/hcl/hcl/ast" @@ -233,7 +232,7 @@ func parseACLPolicyWithTemplating(ns *namespace.Namespace, rules string, perform // Parse the rules root, err := hcl.Parse(rules) if err != nil { - return nil, errwrap.Wrapf("failed to parse policy: {{err}}", err) + return nil, fmt.Errorf("failed to parse policy: %w", err) } // Top-level item should be the object list @@ -248,7 +247,7 @@ func parseACLPolicyWithTemplating(ns *namespace.Namespace, rules string, perform "path", } if err := hclutil.CheckHCLKeys(list, valid); err != nil { - return nil, errwrap.Wrapf("failed to parse policy: {{err}}", err) + return nil, fmt.Errorf("failed to parse policy: %w", err) } // Create the initial policy and store the raw text of the rules @@ -258,12 +257,12 @@ func parseACLPolicyWithTemplating(ns *namespace.Namespace, rules string, perform namespace: ns, } if err := hcl.DecodeObject(&p, list); err != nil { - return nil, errwrap.Wrapf("failed to parse policy: {{err}}", err) + return nil, fmt.Errorf("failed to parse policy: %w", err) } if o := list.Filter("path"); len(o.Items) > 0 { if err := parsePaths(&p, o, performTemplating, entity, groups); err != nil { - return nil, errwrap.Wrapf("failed to parse policy: {{err}}", err) + return nil, fmt.Errorf("failed to parse policy: %w", err) } } @@ -298,7 +297,7 @@ func parsePaths(result *Policy, list *ast.ObjectList, performTemplating bool, en String: key, }) if err != nil { - return errwrap.Wrapf("failed to validate policy templating: {{err}}", err) + return fmt.Errorf("failed to validate policy templating: %w", err) } if hasTemplating { result.Templated = true @@ -406,14 +405,14 @@ func parsePaths(result *Policy, list *ast.ObjectList, performTemplating bool, en if pc.MinWrappingTTLHCL != nil { dur, err := parseutil.ParseDurationSecond(pc.MinWrappingTTLHCL) if err != nil { - return errwrap.Wrapf("error parsing min_wrapping_ttl: {{err}}", err) + return fmt.Errorf("error parsing min_wrapping_ttl: %w", err) } pc.Permissions.MinWrappingTTL = dur } if pc.MaxWrappingTTLHCL != nil { dur, err := parseutil.ParseDurationSecond(pc.MaxWrappingTTLHCL) if err != nil { - return errwrap.Wrapf("error parsing max_wrapping_ttl: {{err}}", err) + return fmt.Errorf("error parsing max_wrapping_ttl: %w", err) } pc.Permissions.MaxWrappingTTL = dur } @@ -428,7 +427,7 @@ func parsePaths(result *Policy, list *ast.ObjectList, performTemplating bool, en if pc.ControlGroupHCL.TTL != nil { dur, err := parseutil.ParseDurationSecond(pc.ControlGroupHCL.TTL) if err != nil { - return errwrap.Wrapf("error parsing control group max ttl: {{err}}", err) + return fmt.Errorf("error parsing control group max ttl: %w", err) } pc.Permissions.ControlGroup.TTL = dur } diff --git a/vault/policy_store.go b/vault/policy_store.go index 33f8cf0b6..9798d186f 100644 --- a/vault/policy_store.go +++ b/vault/policy_store.go @@ -9,7 +9,6 @@ import ( "time" metrics "github.com/armon/go-metrics" - "github.com/hashicorp/errwrap" log "github.com/hashicorp/go-hclog" lru "github.com/hashicorp/golang-lru" "github.com/hashicorp/vault/helper/identity" @@ -373,7 +372,7 @@ func (ps *PolicyStore) setPolicyInternal(ctx context.Context, p *Policy) error { sentinelPolicy: p.sentinelPolicy, }) if err != nil { - return errwrap.Wrapf("failed to create entry: {{err}}", err) + return fmt.Errorf("failed to create entry: %w", err) } // Construct the cache key @@ -384,14 +383,14 @@ func (ps *PolicyStore) setPolicyInternal(ctx context.Context, p *Policy) error { rgpView := ps.getRGPView(p.namespace) rgp, err := rgpView.Get(ctx, entry.Key) if err != nil { - return errwrap.Wrapf("failed looking up conflicting policy: {{err}}", err) + return fmt.Errorf("failed looking up conflicting policy: %w", err) } if rgp != nil { return fmt.Errorf("cannot reuse policy names between ACLs and RGPs") } if err := view.Put(ctx, entry); err != nil { - return errwrap.Wrapf("failed to persist policy: {{err}}", err) + return fmt.Errorf("failed to persist policy: %w", err) } ps.policyTypeMap.Store(index, PolicyTypeACL) @@ -404,7 +403,7 @@ func (ps *PolicyStore) setPolicyInternal(ctx context.Context, p *Policy) error { aclView := ps.getACLView(p.namespace) acl, err := aclView.Get(ctx, entry.Key) if err != nil { - return errwrap.Wrapf("failed looking up conflicting policy: {{err}}", err) + return fmt.Errorf("failed looking up conflicting policy: %w", err) } if acl != nil { return fmt.Errorf("cannot reuse policy names between ACLs and RGPs") @@ -525,7 +524,7 @@ func (ps *PolicyStore) switchedGetPolicy(ctx context.Context, name string, polic out, err := view.Get(ctx, name) if err != nil { - return nil, errwrap.Wrapf("failed to read policy: {{err}}", err) + return nil, fmt.Errorf("failed to read policy: %w", err) } if out == nil { @@ -536,7 +535,7 @@ func (ps *PolicyStore) switchedGetPolicy(ctx context.Context, name string, polic policy := new(Policy) err = out.DecodeJSON(policyEntry) if err != nil { - return nil, errwrap.Wrapf("failed to parse policy: {{err}}", err) + return nil, fmt.Errorf("failed to parse policy: %w", err) } // Set these up here so that they're available for loading into @@ -552,7 +551,7 @@ func (ps *PolicyStore) switchedGetPolicy(ctx context.Context, name string, polic // Parse normally p, err := ParseACLPolicy(ns, policyEntry.Raw) if err != nil { - return nil, errwrap.Wrapf("failed to parse policy: {{err}}", err) + return nil, fmt.Errorf("failed to parse policy: %w", err) } policy.Paths = p.Paths @@ -687,7 +686,7 @@ func (ps *PolicyStore) switchedDeletePolicy(ctx context.Context, name string, po if physicalDeletion { err := view.Delete(ctx, name) if err != nil { - return errwrap.Wrapf("failed to delete policy: {{err}}", err) + return fmt.Errorf("failed to delete policy: %w", err) } } @@ -702,7 +701,7 @@ func (ps *PolicyStore) switchedDeletePolicy(ctx context.Context, name string, po if physicalDeletion { err := view.Delete(ctx, name) if err != nil { - return errwrap.Wrapf("failed to delete policy: {{err}}", err) + return fmt.Errorf("failed to delete policy: %w", err) } } @@ -719,7 +718,7 @@ func (ps *PolicyStore) switchedDeletePolicy(ctx context.Context, name string, po if physicalDeletion { err := view.Delete(ctx, name) if err != nil { - return errwrap.Wrapf("failed to delete policy: {{err}}", err) + return fmt.Errorf("failed to delete policy: %w", err) } } @@ -765,7 +764,7 @@ func (ps *PolicyStore) ACL(ctx context.Context, entity *identity.Entity, policyN for _, nsPolicyName := range nsPolicyNames { p, err := ps.GetPolicy(policyCtx, nsPolicyName, PolicyTypeToken) if err != nil { - return nil, errwrap.Wrapf("failed to get policy: {{err}}", err) + return nil, fmt.Errorf("failed to get policy: %w", err) } if p != nil { policies = append(policies, p) @@ -782,14 +781,14 @@ func (ps *PolicyStore) ACL(ctx context.Context, entity *identity.Entity, policyN if entity != nil { directGroups, inheritedGroups, err := ps.core.identityStore.groupsByEntityID(entity.ID) if err != nil { - return nil, errwrap.Wrapf("failed to fetch group memberships: {{err}}", err) + return nil, fmt.Errorf("failed to fetch group memberships: %w", err) } groups = append(directGroups, inheritedGroups...) } } p, err := parseACLPolicyWithTemplating(policy.namespace, policy.Raw, true, entity, groups) if err != nil { - return nil, errwrap.Wrapf(fmt.Sprintf("error parsing templated policy %q: {{err}}", policy.Name), err) + return nil, fmt.Errorf("error parsing templated policy %q: %w", policy.Name, err) } p.Name = policy.Name policies[i] = p @@ -799,7 +798,7 @@ func (ps *PolicyStore) ACL(ctx context.Context, entity *identity.Entity, policyN // Construct the ACL acl, err := NewACL(ctx, policies) if err != nil { - return nil, errwrap.Wrapf("failed to construct ACL: {{err}}", err) + return nil, fmt.Errorf("failed to construct ACL: %w", err) } return acl, nil @@ -822,7 +821,7 @@ func (ps *PolicyStore) loadACLPolicyInternal(ctx context.Context, policyName, po // Check if the policy already exists policy, err := ps.GetPolicy(ctx, policyName, PolicyTypeACL) if err != nil { - return errwrap.Wrapf(fmt.Sprintf("error fetching %s policy from store: {{err}}", policyName), err) + return fmt.Errorf("error fetching %s policy from store: %w", policyName, err) } if policy != nil { if !strutil.StrListContains(immutablePolicies, policyName) || policyText == policy.Raw { @@ -832,7 +831,7 @@ func (ps *PolicyStore) loadACLPolicyInternal(ctx context.Context, policyName, po policy, err = ParseACLPolicy(ns, policyText) if err != nil { - return errwrap.Wrapf(fmt.Sprintf("error parsing %s policy: {{err}}", policyName), err) + return fmt.Errorf("error parsing %s policy: %w", policyName, err) } if policy == nil { diff --git a/vault/raft.go b/vault/raft.go index f663d854d..ab7932005 100644 --- a/vault/raft.go +++ b/vault/raft.go @@ -13,7 +13,6 @@ import ( "time" "github.com/golang/protobuf/proto" - "github.com/hashicorp/errwrap" cleanhttp "github.com/hashicorp/go-cleanhttp" "github.com/hashicorp/go-discover" discoverk8s "github.com/hashicorp/go-discover/provider/k8s" @@ -237,13 +236,13 @@ func (c *Core) raftTLSRotateDirect(ctx context.Context, logger hclog.Logger, sto // Create a new key raftTLSKey, err := raft.GenerateTLSKey(c.secureRandomReader) if err != nil { - return time.Time{}, errwrap.Wrapf("failed to generate new raft TLS key: {{err}}", err) + return time.Time{}, fmt.Errorf("failed to generate new raft TLS key: %w", err) } // Read the existing keyring keyring, err := c.raftReadTLSKeyring(ctx) if err != nil { - return time.Time{}, errwrap.Wrapf("failed to read raft TLS keyring: {{err}}", err) + return time.Time{}, fmt.Errorf("failed to read raft TLS keyring: %w", err) } // Advance the term and store the new key, replacing the old one. @@ -256,10 +255,10 @@ func (c *Core) raftTLSRotateDirect(ctx context.Context, logger hclog.Logger, sto keyring.ActiveKeyID = raftTLSKey.ID entry, err := logical.StorageEntryJSON(raftTLSStoragePath, keyring) if err != nil { - return time.Time{}, errwrap.Wrapf("failed to json encode keyring: {{err}}", err) + return time.Time{}, fmt.Errorf("failed to json encode keyring: %w", err) } if err := c.barrier.Put(ctx, entry); err != nil { - return time.Time{}, errwrap.Wrapf("failed to write keyring: {{err}}", err) + return time.Time{}, fmt.Errorf("failed to write keyring: %w", err) } logger.Info("wrote new raft TLS config") @@ -354,7 +353,7 @@ func (c *Core) raftTLSRotatePhased(ctx context.Context, logger hclog.Logger, raf // Read the existing keyring keyring, err := c.raftReadTLSKeyring(ctx) if err != nil { - return time.Time{}, errwrap.Wrapf("failed to read raft TLS keyring: {{err}}", err) + return time.Time{}, fmt.Errorf("failed to read raft TLS keyring: %w", err) } switch { @@ -365,10 +364,10 @@ func (c *Core) raftTLSRotatePhased(ctx context.Context, logger hclog.Logger, raf keyring.AppliedIndex = raftBackend.AppliedIndex() entry, err := logical.StorageEntryJSON(raftTLSStoragePath, keyring) if err != nil { - return time.Time{}, errwrap.Wrapf("failed to json encode keyring: {{err}}", err) + return time.Time{}, fmt.Errorf("failed to json encode keyring: %w", err) } if err := c.barrier.Put(ctx, entry); err != nil { - return time.Time{}, errwrap.Wrapf("failed to write keyring: {{err}}", err) + return time.Time{}, fmt.Errorf("failed to write keyring: %w", err) } case len(keyring.Keys) > 1: @@ -386,7 +385,7 @@ func (c *Core) raftTLSRotatePhased(ctx context.Context, logger hclog.Logger, raf // Create a new key raftTLSKey, err := raft.GenerateTLSKey(c.secureRandomReader) if err != nil { - return time.Time{}, errwrap.Wrapf("failed to generate new raft TLS key: {{err}}", err) + return time.Time{}, fmt.Errorf("failed to generate new raft TLS key: %w", err) } // Advance the term and store the new key @@ -394,10 +393,10 @@ func (c *Core) raftTLSRotatePhased(ctx context.Context, logger hclog.Logger, raf keyring.Keys = append(keyring.Keys, raftTLSKey) entry, err := logical.StorageEntryJSON(raftTLSStoragePath, keyring) if err != nil { - return time.Time{}, errwrap.Wrapf("failed to json encode keyring: {{err}}", err) + return time.Time{}, fmt.Errorf("failed to json encode keyring: %w", err) } if err := c.barrier.Put(ctx, entry); err != nil { - return time.Time{}, errwrap.Wrapf("failed to write keyring: {{err}}", err) + return time.Time{}, fmt.Errorf("failed to write keyring: %w", err) } // Write the keyring again with the new applied index. This allows us to @@ -406,10 +405,10 @@ func (c *Core) raftTLSRotatePhased(ctx context.Context, logger hclog.Logger, raf keyring.AppliedIndex = raftBackend.AppliedIndex() entry, err = logical.StorageEntryJSON(raftTLSStoragePath, keyring) if err != nil { - return time.Time{}, errwrap.Wrapf("failed to json encode keyring: {{err}}", err) + return time.Time{}, fmt.Errorf("failed to json encode keyring: %w", err) } if err := c.barrier.Put(ctx, entry); err != nil { - return time.Time{}, errwrap.Wrapf("failed to write keyring: {{err}}", err) + return time.Time{}, fmt.Errorf("failed to write keyring: %w", err) } logger.Info("wrote new raft TLS config") @@ -423,7 +422,7 @@ func (c *Core) raftTLSRotatePhased(ctx context.Context, logger hclog.Logger, raf checkCommitted := func() error { keyring, err := c.raftReadTLSKeyring(ctx) if err != nil { - return errwrap.Wrapf("failed to read raft TLS keyring: {{err}}", err) + return fmt.Errorf("failed to read raft TLS keyring: %w", err) } switch { @@ -444,15 +443,15 @@ func (c *Core) raftTLSRotatePhased(ctx context.Context, logger hclog.Logger, raf keyring.Term += 1 entry, err := logical.StorageEntryJSON(raftTLSStoragePath, keyring) if err != nil { - return errwrap.Wrapf("failed to json encode keyring: {{err}}", err) + return fmt.Errorf("failed to json encode keyring: %w", err) } if err := c.barrier.Put(ctx, entry); err != nil { - return errwrap.Wrapf("failed to write keyring: {{err}}", err) + return fmt.Errorf("failed to write keyring: %w", err) } // Update the TLS Key in the backend if err := raftBackend.SetTLSKeyring(keyring); err != nil { - return errwrap.Wrapf("failed to install keyring: {{err}}", err) + return fmt.Errorf("failed to install keyring: %w", err) } logger.Info("installed new raft TLS key", "term", keyring.Term) @@ -719,7 +718,7 @@ func (c *Core) JoinRaftCluster(ctx context.Context, leaderInfos []*raft.LeaderJo init, err := c.InitializedLocally(ctx) if err != nil { - return false, errwrap.Wrapf("failed to check if core is initialized: {{err}}", err) + return false, fmt.Errorf("failed to check if core is initialized: %w", err) } isRaftHAOnly := c.isRaftHAOnly() @@ -775,7 +774,7 @@ func (c *Core) JoinRaftCluster(ctx context.Context, leaderInfos []*raft.LeaderJo var adv activeAdvertisement err = jsonutil.DecodeJSON(entry.Value, &adv) if err != nil { - return false, errwrap.Wrapf("unable to decoded leader entry: {{err}}", err) + return false, fmt.Errorf("unable to decoded leader entry: %w", err) } leaderInfos[0].LeaderAPIAddr = adv.RedirectAddr @@ -783,7 +782,7 @@ func (c *Core) JoinRaftCluster(ctx context.Context, leaderInfos []*raft.LeaderJo disco, err := newDiscover() if err != nil { - return false, errwrap.Wrapf("failed to create auto-join discovery: {{err}}", err) + return false, fmt.Errorf("failed to create auto-join discovery: %w", err) } join := func(retry bool) error { @@ -797,7 +796,7 @@ func (c *Core) JoinRaftCluster(ctx context.Context, leaderInfos []*raft.LeaderJo init, err := c.InitializedLocally(ctx) if err != nil { - return errwrap.Wrapf("failed to check if core is initialized: {{err}}", err) + return fmt.Errorf("failed to check if core is initialized: %w", err) } if init && !isRaftHAOnly { @@ -813,21 +812,21 @@ func (c *Core) JoinRaftCluster(ctx context.Context, leaderInfos []*raft.LeaderJo if leaderInfo.TLSConfig == nil && (len(leaderInfo.LeaderCACert) != 0 || len(leaderInfo.LeaderClientCert) != 0 || len(leaderInfo.LeaderClientKey) != 0) { leaderInfo.TLSConfig, err = tlsutil.ClientTLSConfig([]byte(leaderInfo.LeaderCACert), []byte(leaderInfo.LeaderClientCert), []byte(leaderInfo.LeaderClientKey)) if err != nil { - return errwrap.Wrapf("failed to create TLS config: {{err}}", err) + return fmt.Errorf("failed to create TLS config: %w", err) } leaderInfo.TLSConfig.ServerName = leaderInfo.LeaderTLSServerName } if leaderInfo.TLSConfig == nil && leaderInfo.LeaderTLSServerName != "" { leaderInfo.TLSConfig, err = tlsutil.SetupTLSConfig(map[string]string{"address": leaderInfo.LeaderTLSServerName}, "") if err != nil { - return errwrap.Wrapf("failed to create TLS config: {{err}}", err) + return fmt.Errorf("failed to create TLS config: %w", err) } } if leaderInfo.TLSConfig != nil { transport.TLSClientConfig = leaderInfo.TLSConfig.Clone() if err := http2.ConfigureTransport(transport); err != nil { - return errwrap.Wrapf("failed to configure TLS: {{err}}", err) + return fmt.Errorf("failed to configure TLS: %w", err) } } @@ -837,7 +836,7 @@ func (c *Core) JoinRaftCluster(ctx context.Context, leaderInfos []*raft.LeaderJo config := api.DefaultConfig() if config.Error != nil { - return errwrap.Wrapf("failed to create api client: {{err}}", config.Error) + return fmt.Errorf("failed to create api client: %w", config.Error) } config.Address = leaderAddr @@ -846,7 +845,7 @@ func (c *Core) JoinRaftCluster(ctx context.Context, leaderInfos []*raft.LeaderJo apiClient, err := api.NewClient(config) if err != nil { - return errwrap.Wrapf("failed to create api client: {{err}}", err) + return fmt.Errorf("failed to create api client: %w", err) } // Attempt to join the leader by requesting for the bootstrap challenge @@ -854,7 +853,7 @@ func (c *Core) JoinRaftCluster(ctx context.Context, leaderInfos []*raft.LeaderJo "server_id": raftBackend.NodeID(), }) if err != nil { - return errwrap.Wrapf("error during raft bootstrap init call: {{err}}", err) + return fmt.Errorf("error during raft bootstrap init call: %w", err) } if secret == nil { return errors.New("could not retrieve raft bootstrap package") @@ -876,12 +875,12 @@ func (c *Core) JoinRaftCluster(ctx context.Context, leaderInfos []*raft.LeaderJo } challengeRaw, err := base64.StdEncoding.DecodeString(challengeB64.(string)) if err != nil { - return errwrap.Wrapf("error decoding raft bootstrap challenge: {{err}}", err) + return fmt.Errorf("error decoding raft bootstrap challenge: %w", err) } eBlob := &wrapping.EncryptedBlobInfo{} if err := proto.Unmarshal(challengeRaw, eBlob); err != nil { - return errwrap.Wrapf("error decoding raft bootstrap challenge: {{err}}", err) + return fmt.Errorf("error decoding raft bootstrap challenge: %w", err) } raftInfo := &raftInformation{ @@ -912,7 +911,7 @@ func (c *Core) JoinRaftCluster(ctx context.Context, leaderInfos []*raft.LeaderJo } if err := c.joinRaftSendAnswer(ctx, c.seal.GetAccess(), raftInfo); err != nil { - return errwrap.Wrapf("failed to send answer to raft leader node: {{err}}", err) + return fmt.Errorf("failed to send answer to raft leader node: %w", err) } if c.seal.BarrierType() == wrapping.Shamir && !isRaftHAOnly { @@ -1014,7 +1013,7 @@ func (c *Core) JoinRaftCluster(ctx context.Context, leaderInfos []*raft.LeaderJo default: if err := join(false); err != nil { c.logger.Error("failed to join raft cluster", "error", err) - return false, errwrap.Wrapf("failed to join raft cluster: {{err}}", err) + return false, fmt.Errorf("failed to join raft cluster: %w", err) } } @@ -1061,12 +1060,12 @@ func (c *Core) joinRaftSendAnswer(ctx context.Context, sealAccess *seal.Access, plaintext, err := sealAccess.Decrypt(ctx, raftInfo.challenge, nil) if err != nil { - return errwrap.Wrapf("error decrypting challenge: {{err}}", err) + return fmt.Errorf("error decrypting challenge: %w", err) } parsedClusterAddr, err := url.Parse(c.ClusterAddr()) if err != nil { - return errwrap.Wrapf("error parsing cluster address: {{err}}", err) + return fmt.Errorf("error parsing cluster address: %w", err) } clusterAddr := parsedClusterAddr.Host if atomic.LoadUint32(&TestingUpdateClusterAddr) == 1 && strings.HasSuffix(clusterAddr, ":0") { @@ -1108,7 +1107,7 @@ func (c *Core) joinRaftSendAnswer(ctx context.Context, sealAccess *seal.Access, err = c.startClusterListener(ctx) if err != nil { - return errwrap.Wrapf("error starting cluster: {{err}}", err) + return fmt.Errorf("error starting cluster: %w", err) } raftBackend.SetRestoreCallback(c.raftSnapshotRestoreCallback(true, true)) @@ -1118,7 +1117,7 @@ func (c *Core) joinRaftSendAnswer(ctx context.Context, sealAccess *seal.Access, } err = raftBackend.SetupCluster(ctx, opts) if err != nil { - return errwrap.Wrapf("failed to setup raft cluster: {{err}}", err) + return fmt.Errorf("failed to setup raft cluster: %w", err) } return nil @@ -1158,7 +1157,7 @@ func (c *Core) RaftBootstrap(ctx context.Context, onInit bool) error { parsedClusterAddr, err := url.Parse(c.ClusterAddr()) if err != nil { - return errwrap.Wrapf("error parsing cluster address: {{err}}", err) + return fmt.Errorf("error parsing cluster address: %w", err) } if err := raftBackend.Bootstrap([]raft.Peer{ { @@ -1166,7 +1165,7 @@ func (c *Core) RaftBootstrap(ctx context.Context, onInit bool) error { Address: parsedClusterAddr.Host, }, }); err != nil { - return errwrap.Wrapf("could not bootstrap clustered storage: {{err}}", err) + return fmt.Errorf("could not bootstrap clustered storage: %w", err) } raftOpts := raft.SetupOpts{ @@ -1177,7 +1176,7 @@ func (c *Core) RaftBootstrap(ctx context.Context, onInit bool) error { // Generate the TLS Keyring info for SetupCluster to consume raftTLS, err := c.raftCreateTLSKeyring(ctx) if err != nil { - return errwrap.Wrapf("could not generate TLS keyring during bootstrap: {{err}}", err) + return fmt.Errorf("could not generate TLS keyring during bootstrap: %w", err) } raftBackend.SetRestoreCallback(c.raftSnapshotRestoreCallback(true, true)) @@ -1187,7 +1186,7 @@ func (c *Core) RaftBootstrap(ctx context.Context, onInit bool) error { } if err := raftBackend.SetupCluster(ctx, raftOpts); err != nil { - return errwrap.Wrapf("could not start clustered storage: {{err}}", err) + return fmt.Errorf("could not start clustered storage: %w", err) } return nil diff --git a/vault/rekey.go b/vault/rekey.go index 38912324b..4ce863856 100644 --- a/vault/rekey.go +++ b/vault/rekey.go @@ -9,7 +9,6 @@ import ( "fmt" "net/http" - "github.com/hashicorp/errwrap" wrapping "github.com/hashicorp/go-kms-wrapping" aeadwrapper "github.com/hashicorp/go-kms-wrapping/wrappers/aead" "github.com/hashicorp/go-uuid" @@ -85,7 +84,7 @@ func (c *Core) RekeyThreshold(ctx context.Context, recovery bool) (int, logical. config, err = c.seal.BarrierConfig(ctx) } if err != nil { - return 0, logical.CodedError(http.StatusInternalServerError, errwrap.Wrapf("unable to look up config: {{err}}", err).Error()) + return 0, logical.CodedError(http.StatusInternalServerError, fmt.Errorf("unable to look up config: %w", err).Error()) } if config == nil { return 0, logical.CodedError(http.StatusBadRequest, ErrNotInit.Error()) @@ -205,7 +204,7 @@ func (c *Core) BarrierRekeyInit(config *SealConfig) logical.HTTPCodedError { // Check if the seal configuration is valid if err := config.Validate(); err != nil { c.logger.Error("invalid rekey seal configuration", "error", err) - return logical.CodedError(http.StatusInternalServerError, errwrap.Wrapf("invalid rekey seal configuration: {{err}}", err).Error()) + return logical.CodedError(http.StatusInternalServerError, fmt.Errorf("invalid rekey seal configuration: %w", err).Error()) } c.stateLock.RLock() @@ -232,7 +231,7 @@ func (c *Core) BarrierRekeyInit(config *SealConfig) logical.HTTPCodedError { nonce, err := uuid.GenerateUUID() if err != nil { c.barrierRekeyConfig = nil - return logical.CodedError(http.StatusInternalServerError, errwrap.Wrapf("error generating nonce for procedure: {{err}}", err).Error()) + return logical.CodedError(http.StatusInternalServerError, fmt.Errorf("error generating nonce for procedure: %w", err).Error()) } c.barrierRekeyConfig.Nonce = nonce @@ -251,7 +250,7 @@ func (c *Core) RecoveryRekeyInit(config *SealConfig) logical.HTTPCodedError { // Check if the seal configuration is valid if err := config.Validate(); err != nil { c.logger.Error("invalid recovery configuration", "error", err) - return logical.CodedError(http.StatusInternalServerError, errwrap.Wrapf("invalid recovery configuration: {{err}}", err).Error()) + return logical.CodedError(http.StatusInternalServerError, fmt.Errorf("invalid recovery configuration: %w", err).Error()) } if !c.seal.RecoveryKeySupported() { @@ -282,7 +281,7 @@ func (c *Core) RecoveryRekeyInit(config *SealConfig) logical.HTTPCodedError { nonce, err := uuid.GenerateUUID() if err != nil { c.recoveryRekeyConfig = nil - return logical.CodedError(http.StatusInternalServerError, errwrap.Wrapf("error generating nonce for procedure: {{err}}", err).Error()) + return logical.CodedError(http.StatusInternalServerError, fmt.Errorf("error generating nonce for procedure: %w", err).Error()) } c.recoveryRekeyConfig.Nonce = nonce @@ -340,7 +339,7 @@ func (c *Core) BarrierRekeyUpdate(ctx context.Context, key []byte, nonce string) existingConfig, err = c.seal.BarrierConfig(ctx) } if err != nil { - return nil, logical.CodedError(http.StatusInternalServerError, errwrap.Wrapf("failed to fetch existing config: {{err}}", err).Error()) + return nil, logical.CodedError(http.StatusInternalServerError, fmt.Errorf("failed to fetch existing config: %w", err).Error()) } // Ensure the barrier is initialized if existingConfig == nil { @@ -387,7 +386,7 @@ func (c *Core) BarrierRekeyUpdate(ctx context.Context, key []byte, nonce string) recoveredKey, err = shamir.Combine(c.barrierRekeyConfig.RekeyProgress) c.barrierRekeyConfig.RekeyProgress = nil if err != nil { - return nil, logical.CodedError(http.StatusInternalServerError, errwrap.Wrapf("failed to compute master key: {{err}}", err).Error()) + return nil, logical.CodedError(http.StatusInternalServerError, fmt.Errorf("failed to compute master key: %w", err).Error()) } } @@ -395,7 +394,7 @@ func (c *Core) BarrierRekeyUpdate(ctx context.Context, key []byte, nonce string) case useRecovery: if err := c.seal.VerifyRecoveryKey(ctx, recoveredKey); err != nil { c.logger.Error("rekey recovery key verification failed", "error", err) - return nil, logical.CodedError(http.StatusBadRequest, errwrap.Wrapf("recovery key verification failed: {{err}}", err).Error()) + return nil, logical.CodedError(http.StatusBadRequest, fmt.Errorf("recovery key verification failed: %w", err).Error()) } case c.seal.BarrierType() == wrapping.Shamir: if c.seal.StoredKeysSupported() == seal.StoredKeysSupportedShamirMaster { @@ -407,22 +406,22 @@ func (c *Core) BarrierRekeyUpdate(ctx context.Context, key []byte, nonce string) testseal.SetCore(c) err = testseal.GetAccess().Wrapper.(*aeadwrapper.ShamirWrapper).SetAESGCMKeyBytes(recoveredKey) if err != nil { - return nil, logical.CodedError(http.StatusInternalServerError, errwrap.Wrapf("failed to setup unseal key: {{err}}", err).Error()) + return nil, logical.CodedError(http.StatusInternalServerError, fmt.Errorf("failed to setup unseal key: %w", err).Error()) } cfg, err := c.seal.BarrierConfig(ctx) if err != nil { - return nil, logical.CodedError(http.StatusInternalServerError, errwrap.Wrapf("failed to setup test barrier config: {{err}}", err).Error()) + return nil, logical.CodedError(http.StatusInternalServerError, fmt.Errorf("failed to setup test barrier config: %w", err).Error()) } testseal.SetCachedBarrierConfig(cfg) stored, err := testseal.GetStoredKeys(ctx) if err != nil { - return nil, logical.CodedError(http.StatusInternalServerError, errwrap.Wrapf("failed to read master key: {{err}}", err).Error()) + return nil, logical.CodedError(http.StatusInternalServerError, fmt.Errorf("failed to read master key: %w", err).Error()) } recoveredKey = stored[0] } if err := c.barrier.VerifyMaster(recoveredKey); err != nil { c.logger.Error("master key verification failed", "error", err) - return nil, logical.CodedError(http.StatusBadRequest, errwrap.Wrapf("master key verification failed: {{err}}", err).Error()) + return nil, logical.CodedError(http.StatusBadRequest, fmt.Errorf("master key verification failed: %w", err).Error()) } } @@ -432,7 +431,7 @@ func (c *Core) BarrierRekeyUpdate(ctx context.Context, key []byte, nonce string) newKey, err := c.barrier.GenerateKey(c.secureRandomReader) if err != nil { c.logger.Error("failed to generate master key", "error", err) - return nil, logical.CodedError(http.StatusInternalServerError, errwrap.Wrapf("master key generation failed: {{err}}", err).Error()) + return nil, logical.CodedError(http.StatusInternalServerError, fmt.Errorf("master key generation failed: %w", err).Error()) } results := &RekeyResult{ @@ -448,7 +447,7 @@ func (c *Core) BarrierRekeyUpdate(ctx context.Context, key []byte, nonce string) shares, err := shamir.Split(newKey, c.barrierRekeyConfig.SecretShares, c.barrierRekeyConfig.SecretThreshold) if err != nil { c.logger.Error("failed to generate shares", "error", err) - return nil, logical.CodedError(http.StatusInternalServerError, errwrap.Wrapf("failed to generate shares: {{err}}", err).Error()) + return nil, logical.CodedError(http.StatusInternalServerError, fmt.Errorf("failed to generate shares: %w", err).Error()) } results.SecretShares = shares } @@ -462,7 +461,7 @@ func (c *Core) BarrierRekeyUpdate(ctx context.Context, key []byte, nonce string) } results.PGPFingerprints, results.SecretShares, err = pgpkeys.EncryptShares(hexEncodedShares, c.barrierRekeyConfig.PGPKeys) if err != nil { - return nil, logical.CodedError(http.StatusInternalServerError, errwrap.Wrapf("failed to encrypt shares: {{err}}", err).Error()) + return nil, logical.CodedError(http.StatusInternalServerError, fmt.Errorf("failed to encrypt shares: %w", err).Error()) } // If backup is enabled, store backup info in vault.coreBarrierUnsealKeysBackupPath @@ -484,7 +483,7 @@ func (c *Core) BarrierRekeyUpdate(ctx context.Context, key []byte, nonce string) buf, err := json.Marshal(backupVals) if err != nil { c.logger.Error("failed to marshal unseal key backup", "error", err) - return nil, logical.CodedError(http.StatusInternalServerError, errwrap.Wrapf("failed to marshal unseal key backup: {{err}}", err).Error()) + return nil, logical.CodedError(http.StatusInternalServerError, fmt.Errorf("failed to marshal unseal key backup: %w", err).Error()) } pe := &physical.Entry{ Key: coreBarrierUnsealKeysBackupPath, @@ -492,7 +491,7 @@ func (c *Core) BarrierRekeyUpdate(ctx context.Context, key []byte, nonce string) } if err = c.physical.Put(ctx, pe); err != nil { c.logger.Error("failed to save unseal key backup", "error", err) - return nil, logical.CodedError(http.StatusInternalServerError, errwrap.Wrapf("failed to save unseal key backup: {{err}}", err).Error()) + return nil, logical.CodedError(http.StatusInternalServerError, fmt.Errorf("failed to save unseal key backup: %w", err).Error()) } } } @@ -502,7 +501,7 @@ func (c *Core) BarrierRekeyUpdate(ctx context.Context, key []byte, nonce string) nonce, err := uuid.GenerateUUID() if err != nil { c.barrierRekeyConfig = nil - return nil, logical.CodedError(http.StatusInternalServerError, errwrap.Wrapf("failed to generate verification nonce: {{err}}", err).Error()) + return nil, logical.CodedError(http.StatusInternalServerError, fmt.Errorf("failed to generate verification nonce: %w", err).Error()) } c.barrierRekeyConfig.VerificationNonce = nonce c.barrierRekeyConfig.VerificationKey = newKey @@ -513,7 +512,7 @@ func (c *Core) BarrierRekeyUpdate(ctx context.Context, key []byte, nonce string) } if err := c.performBarrierRekey(ctx, newKey); err != nil { - return nil, logical.CodedError(http.StatusInternalServerError, errwrap.Wrapf("failed to perform barrier rekey: {{err}}", err).Error()) + return nil, logical.CodedError(http.StatusInternalServerError, fmt.Errorf("failed to perform barrier rekey: %w", err).Error()) } c.barrierRekeyConfig = nil @@ -526,7 +525,7 @@ func (c *Core) performBarrierRekey(ctx context.Context, newSealKey []byte) logic // We won't be able to call SetStoredKeys without setting StoredShares=1. existingConfig, err := c.seal.BarrierConfig(ctx) if err != nil { - return logical.CodedError(http.StatusInternalServerError, errwrap.Wrapf("failed to fetch existing config: {{err}}", err).Error()) + return logical.CodedError(http.StatusInternalServerError, fmt.Errorf("failed to fetch existing config: %w", err).Error()) } existingConfig.StoredShares = 1 c.seal.SetCachedBarrierConfig(existingConfig) @@ -535,23 +534,23 @@ func (c *Core) performBarrierRekey(ctx context.Context, newSealKey []byte) logic if c.seal.StoredKeysSupported() != seal.StoredKeysSupportedGeneric { err := c.seal.GetAccess().Wrapper.(*aeadwrapper.ShamirWrapper).SetAESGCMKeyBytes(newSealKey) if err != nil { - return logical.CodedError(http.StatusInternalServerError, errwrap.Wrapf("failed to update barrier seal key: {{err}}", err).Error()) + return logical.CodedError(http.StatusInternalServerError, fmt.Errorf("failed to update barrier seal key: %w", err).Error()) } } newMasterKey, err := c.barrier.GenerateKey(c.secureRandomReader) if err != nil { - return logical.CodedError(http.StatusInternalServerError, errwrap.Wrapf("failed to perform rekey: {{err}}", err).Error()) + return logical.CodedError(http.StatusInternalServerError, fmt.Errorf("failed to perform rekey: %w", err).Error()) } if err := c.seal.SetStoredKeys(ctx, [][]byte{newMasterKey}); err != nil { c.logger.Error("failed to store keys", "error", err) - return logical.CodedError(http.StatusInternalServerError, errwrap.Wrapf("failed to store keys: {{err}}", err).Error()) + return logical.CodedError(http.StatusInternalServerError, fmt.Errorf("failed to store keys: %w", err).Error()) } // Rekey the barrier if err := c.barrier.Rekey(ctx, newMasterKey); err != nil { c.logger.Error("failed to rekey barrier", "error", err) - return logical.CodedError(http.StatusInternalServerError, errwrap.Wrapf("failed to rekey barrier: {{err}}", err).Error()) + return logical.CodedError(http.StatusInternalServerError, fmt.Errorf("failed to rekey barrier: %w", err).Error()) } if c.logger.IsInfo() { c.logger.Info("security barrier rekeyed", "stored", c.barrierRekeyConfig.StoredShares, "shares", c.barrierRekeyConfig.SecretShares, "threshold", c.barrierRekeyConfig.SecretThreshold) @@ -564,7 +563,7 @@ func (c *Core) performBarrierRekey(ctx context.Context, newSealKey []byte) logic }) if err != nil { c.logger.Error("failed to store new seal key", "error", err) - return logical.CodedError(http.StatusInternalServerError, errwrap.Wrapf("failed to store new seal key: {{err}}", err).Error()) + return logical.CodedError(http.StatusInternalServerError, fmt.Errorf("failed to store new seal key: %w", err).Error()) } } @@ -572,7 +571,7 @@ func (c *Core) performBarrierRekey(ctx context.Context, newSealKey []byte) logic if err := c.seal.SetBarrierConfig(ctx, c.barrierRekeyConfig); err != nil { c.logger.Error("error saving rekey seal configuration", "error", err) - return logical.CodedError(http.StatusInternalServerError, errwrap.Wrapf("failed to save rekey seal configuration: {{err}}", err).Error()) + return logical.CodedError(http.StatusInternalServerError, fmt.Errorf("failed to save rekey seal configuration: %w", err).Error()) } // Write to the canary path, which will force a synchronous truing during @@ -582,7 +581,7 @@ func (c *Core) performBarrierRekey(ctx context.Context, newSealKey []byte) logic Value: []byte(c.barrierRekeyConfig.Nonce), }); err != nil { c.logger.Error("error saving keyring canary", "error", err) - return logical.CodedError(http.StatusInternalServerError, errwrap.Wrapf("failed to save keyring canary: {{err}}", err).Error()) + return logical.CodedError(http.StatusInternalServerError, fmt.Errorf("failed to save keyring canary: %w", err).Error()) } c.barrierRekeyConfig.RekeyProgress = nil @@ -618,7 +617,7 @@ func (c *Core) RecoveryRekeyUpdate(ctx context.Context, key []byte, nonce string // Get the seal configuration existingConfig, err := c.seal.RecoveryConfig(ctx) if err != nil { - return nil, logical.CodedError(http.StatusInternalServerError, errwrap.Wrapf("failed to fetch existing recovery config: {{err}}", err).Error()) + return nil, logical.CodedError(http.StatusInternalServerError, fmt.Errorf("failed to fetch existing recovery config: %w", err).Error()) } // Ensure the seal is initialized if existingConfig == nil { @@ -665,21 +664,21 @@ func (c *Core) RecoveryRekeyUpdate(ctx context.Context, key []byte, nonce string recoveryKey, err = shamir.Combine(c.recoveryRekeyConfig.RekeyProgress) c.recoveryRekeyConfig.RekeyProgress = nil if err != nil { - return nil, logical.CodedError(http.StatusInternalServerError, errwrap.Wrapf("failed to compute recovery key: {{err}}", err).Error()) + return nil, logical.CodedError(http.StatusInternalServerError, fmt.Errorf("failed to compute recovery key: %w", err).Error()) } } // Verify the recovery key if err := c.seal.VerifyRecoveryKey(ctx, recoveryKey); err != nil { c.logger.Error("recovery key verification failed", "error", err) - return nil, logical.CodedError(http.StatusBadRequest, errwrap.Wrapf("recovery key verification failed: {{err}}", err).Error()) + return nil, logical.CodedError(http.StatusBadRequest, fmt.Errorf("recovery key verification failed: %w", err).Error()) } // Generate a new master key newMasterKey, err := c.barrier.GenerateKey(c.secureRandomReader) if err != nil { c.logger.Error("failed to generate recovery key", "error", err) - return nil, logical.CodedError(http.StatusInternalServerError, errwrap.Wrapf("recovery key generation failed: {{err}}", err).Error()) + return nil, logical.CodedError(http.StatusInternalServerError, fmt.Errorf("recovery key generation failed: %w", err).Error()) } // Return the master key if only a single key part is used @@ -694,7 +693,7 @@ func (c *Core) RecoveryRekeyUpdate(ctx context.Context, key []byte, nonce string shares, err := shamir.Split(newMasterKey, c.recoveryRekeyConfig.SecretShares, c.recoveryRekeyConfig.SecretThreshold) if err != nil { c.logger.Error("failed to generate shares", "error", err) - return nil, logical.CodedError(http.StatusInternalServerError, errwrap.Wrapf("failed to generate shares: {{err}}", err).Error()) + return nil, logical.CodedError(http.StatusInternalServerError, fmt.Errorf("failed to generate shares: %w", err).Error()) } results.SecretShares = shares } @@ -706,7 +705,7 @@ func (c *Core) RecoveryRekeyUpdate(ctx context.Context, key []byte, nonce string } results.PGPFingerprints, results.SecretShares, err = pgpkeys.EncryptShares(hexEncodedShares, c.recoveryRekeyConfig.PGPKeys) if err != nil { - return nil, logical.CodedError(http.StatusInternalServerError, errwrap.Wrapf("failed to encrypt shares: {{err}}", err).Error()) + return nil, logical.CodedError(http.StatusInternalServerError, fmt.Errorf("failed to encrypt shares: %w", err).Error()) } if c.recoveryRekeyConfig.Backup { @@ -727,7 +726,7 @@ func (c *Core) RecoveryRekeyUpdate(ctx context.Context, key []byte, nonce string buf, err := json.Marshal(backupVals) if err != nil { c.logger.Error("failed to marshal recovery key backup", "error", err) - return nil, logical.CodedError(http.StatusInternalServerError, errwrap.Wrapf("failed to marshal recovery key backup: {{err}}", err).Error()) + return nil, logical.CodedError(http.StatusInternalServerError, fmt.Errorf("failed to marshal recovery key backup: %w", err).Error()) } pe := &physical.Entry{ Key: coreRecoveryUnsealKeysBackupPath, @@ -735,7 +734,7 @@ func (c *Core) RecoveryRekeyUpdate(ctx context.Context, key []byte, nonce string } if err = c.physical.Put(ctx, pe); err != nil { c.logger.Error("failed to save unseal key backup", "error", err) - return nil, logical.CodedError(http.StatusInternalServerError, errwrap.Wrapf("failed to save unseal key backup: {{err}}", err).Error()) + return nil, logical.CodedError(http.StatusInternalServerError, fmt.Errorf("failed to save unseal key backup: %w", err).Error()) } } } @@ -746,7 +745,7 @@ func (c *Core) RecoveryRekeyUpdate(ctx context.Context, key []byte, nonce string nonce, err := uuid.GenerateUUID() if err != nil { c.recoveryRekeyConfig = nil - return nil, logical.CodedError(http.StatusInternalServerError, errwrap.Wrapf("failed to generate verification nonce: {{err}}", err).Error()) + return nil, logical.CodedError(http.StatusInternalServerError, fmt.Errorf("failed to generate verification nonce: %w", err).Error()) } c.recoveryRekeyConfig.VerificationNonce = nonce c.recoveryRekeyConfig.VerificationKey = newMasterKey @@ -757,7 +756,7 @@ func (c *Core) RecoveryRekeyUpdate(ctx context.Context, key []byte, nonce string } if err := c.performRecoveryRekey(ctx, newMasterKey); err != nil { - return nil, logical.CodedError(http.StatusInternalServerError, errwrap.Wrapf("failed to perform recovery rekey: {{err}}", err).Error()) + return nil, logical.CodedError(http.StatusInternalServerError, fmt.Errorf("failed to perform recovery rekey: %w", err).Error()) } c.recoveryRekeyConfig = nil @@ -767,14 +766,14 @@ func (c *Core) RecoveryRekeyUpdate(ctx context.Context, key []byte, nonce string func (c *Core) performRecoveryRekey(ctx context.Context, newMasterKey []byte) logical.HTTPCodedError { if err := c.seal.SetRecoveryKey(ctx, newMasterKey); err != nil { c.logger.Error("failed to set recovery key", "error", err) - return logical.CodedError(http.StatusInternalServerError, errwrap.Wrapf("failed to set recovery key: {{err}}", err).Error()) + return logical.CodedError(http.StatusInternalServerError, fmt.Errorf("failed to set recovery key: %w", err).Error()) } c.recoveryRekeyConfig.VerificationKey = nil if err := c.seal.SetRecoveryConfig(ctx, c.recoveryRekeyConfig); err != nil { c.logger.Error("error saving rekey seal configuration", "error", err) - return logical.CodedError(http.StatusInternalServerError, errwrap.Wrapf("failed to save rekey seal configuration: {{err}}", err).Error()) + return logical.CodedError(http.StatusInternalServerError, fmt.Errorf("failed to save rekey seal configuration: %w", err).Error()) } // Write to the canary path, which will force a synchronous truing during @@ -784,7 +783,7 @@ func (c *Core) performRecoveryRekey(ctx context.Context, newMasterKey []byte) lo Value: []byte(c.recoveryRekeyConfig.Nonce), }); err != nil { c.logger.Error("error saving keyring canary", "error", err) - return logical.CodedError(http.StatusInternalServerError, errwrap.Wrapf("failed to save keyring canary: {{err}}", err).Error()) + return logical.CodedError(http.StatusInternalServerError, fmt.Errorf("failed to save keyring canary: %w", err).Error()) } c.recoveryRekeyConfig.RekeyProgress = nil @@ -876,7 +875,7 @@ func (c *Core) RekeyVerify(ctx context.Context, key []byte, nonce string, recove var err error recoveredKey, err = shamir.Combine(config.VerificationProgress) if err != nil { - return nil, logical.CodedError(http.StatusInternalServerError, errwrap.Wrapf("failed to compute key for verification: {{err}}", err).Error()) + return nil, logical.CodedError(http.StatusInternalServerError, fmt.Errorf("failed to compute key for verification: %w", err).Error()) } } @@ -888,12 +887,12 @@ func (c *Core) RekeyVerify(ctx context.Context, key []byte, nonce string, recove switch recovery { case false: if err := c.performBarrierRekey(ctx, recoveredKey); err != nil { - return nil, logical.CodedError(http.StatusInternalServerError, errwrap.Wrapf("failed to perform rekey: {{err}}", err).Error()) + return nil, logical.CodedError(http.StatusInternalServerError, fmt.Errorf("failed to perform rekey: %w", err).Error()) } c.barrierRekeyConfig = nil default: if err := c.performRecoveryRekey(ctx, recoveredKey); err != nil { - return nil, logical.CodedError(http.StatusInternalServerError, errwrap.Wrapf("failed to perform recovery key rekey: {{err}}", err).Error()) + return nil, logical.CodedError(http.StatusInternalServerError, fmt.Errorf("failed to perform recovery key rekey: %w", err).Error()) } c.recoveryRekeyConfig = nil } @@ -988,7 +987,7 @@ func (c *Core) RekeyRetrieveBackup(ctx context.Context, recovery bool) (*RekeyBa entry, err = c.physical.Get(ctx, coreBarrierUnsealKeysBackupPath) } if err != nil { - return nil, logical.CodedError(http.StatusInternalServerError, errwrap.Wrapf("error getting keys from backup: {{err}}", err).Error()) + return nil, logical.CodedError(http.StatusInternalServerError, fmt.Errorf("error getting keys from backup: %w", err).Error()) } if entry == nil { return nil, nil @@ -997,7 +996,7 @@ func (c *Core) RekeyRetrieveBackup(ctx context.Context, recovery bool) (*RekeyBa ret := &RekeyBackup{} err = jsonutil.DecodeJSON(entry.Value, ret) if err != nil { - return nil, logical.CodedError(http.StatusInternalServerError, errwrap.Wrapf("error decoding backup keys: {{err}}", err).Error()) + return nil, logical.CodedError(http.StatusInternalServerError, fmt.Errorf("error decoding backup keys: %w", err).Error()) } return ret, nil @@ -1018,13 +1017,13 @@ func (c *Core) RekeyDeleteBackup(ctx context.Context, recovery bool) logical.HTT if recovery { err := c.physical.Delete(ctx, coreRecoveryUnsealKeysBackupPath) if err != nil { - return logical.CodedError(http.StatusInternalServerError, errwrap.Wrapf("error deleting backup keys: {{err}}", err).Error()) + return logical.CodedError(http.StatusInternalServerError, fmt.Errorf("error deleting backup keys: %w", err).Error()) } return nil } err := c.physical.Delete(ctx, coreBarrierUnsealKeysBackupPath) if err != nil { - return logical.CodedError(http.StatusInternalServerError, errwrap.Wrapf("error deleting backup keys: {{err}}", err).Error()) + return logical.CodedError(http.StatusInternalServerError, fmt.Errorf("error deleting backup keys: %w", err).Error()) } return nil } diff --git a/vault/request_handling.go b/vault/request_handling.go index 4e8643b91..2dfdf6b73 100644 --- a/vault/request_handling.go +++ b/vault/request_handling.go @@ -419,7 +419,7 @@ func (c *Core) switchedLockHandleRequest(httpCtx context.Context, req *logical.R ns, err := namespace.FromContext(httpCtx) if err != nil { cancel() - return nil, errwrap.Wrapf("could not parse namespace from http context: {{err}}", err) + return nil, fmt.Errorf("could not parse namespace from http context: %w", err) } ctx = namespace.ContextWithNamespace(ctx, ns) @@ -754,7 +754,7 @@ func (c *Core) handleRequest(ctx context.Context, req *logical.Request) (retResp c.logger.Trace("request rejected due to lease count quota violation", "request_path", req.Path) } - retErr = multierror.Append(retErr, errwrap.Wrapf(fmt.Sprintf("request path %q: {{err}}", req.Path), quotas.ErrLeaseCountQuotaExceeded)) + retErr = multierror.Append(retErr, fmt.Errorf("request path %q: %w", req.Path, quotas.ErrLeaseCountQuotaExceeded)) return nil, auth, retErr } @@ -1152,7 +1152,7 @@ func (c *Core) handleLoginRequest(ctx context.Context, req *logical.Request) (re c.logger.Trace("request rejected due to lease count quota violation", "request_path", req.Path) } - retErr = multierror.Append(retErr, errwrap.Wrapf(fmt.Sprintf("request path %q: {{err}}", req.Path), quotas.ErrLeaseCountQuotaExceeded)) + retErr = multierror.Append(retErr, fmt.Errorf("request path %q: %w", req.Path, quotas.ErrLeaseCountQuotaExceeded)) return } diff --git a/vault/seal.go b/vault/seal.go index 3bd0cc80b..6ef7da7ee 100644 --- a/vault/seal.go +++ b/vault/seal.go @@ -13,7 +13,6 @@ import ( "github.com/hashicorp/vault/sdk/physical" "github.com/golang/protobuf/proto" - "github.com/hashicorp/errwrap" wrapping "github.com/hashicorp/go-kms-wrapping" "github.com/hashicorp/vault/vault/seal" "github.com/keybase/go-crypto/openpgp" @@ -178,7 +177,7 @@ func (d *defaultSeal) BarrierConfig(ctx context.Context) (*SealConfig, error) { pe, err := d.core.physical.Get(ctx, barrierSealConfigPath) if err != nil { d.core.logger.Error("failed to read seal configuration", "error", err) - return nil, errwrap.Wrapf("failed to check seal configuration: {{err}}", err) + return nil, fmt.Errorf("failed to check seal configuration: %w", err) } // If the seal configuration is missing, we are not initialized @@ -192,7 +191,7 @@ func (d *defaultSeal) BarrierConfig(ctx context.Context) (*SealConfig, error) { // Decode the barrier entry if err := jsonutil.DecodeJSON(pe.Value, &conf); err != nil { d.core.logger.Error("failed to decode seal configuration", "error", err) - return nil, errwrap.Wrapf("failed to decode seal configuration: {{err}}", err) + return nil, fmt.Errorf("failed to decode seal configuration: %w", err) } switch conf.Type { @@ -208,7 +207,7 @@ func (d *defaultSeal) BarrierConfig(ctx context.Context) (*SealConfig, error) { // Check for a valid seal configuration if err := conf.Validate(); err != nil { d.core.logger.Error("invalid seal configuration", "error", err) - return nil, errwrap.Wrapf("seal validation failed: {{err}}", err) + return nil, fmt.Errorf("seal validation failed: %w", err) } d.SetCachedBarrierConfig(&conf) @@ -239,7 +238,7 @@ func (d *defaultSeal) SetBarrierConfig(ctx context.Context, config *SealConfig) // Encode the seal configuration buf, err := json.Marshal(config) if err != nil { - return errwrap.Wrapf("failed to encode seal configuration: {{err}}", err) + return fmt.Errorf("failed to encode seal configuration: %w", err) } // Store the seal configuration @@ -250,7 +249,7 @@ func (d *defaultSeal) SetBarrierConfig(ctx context.Context, config *SealConfig) if err := d.core.physical.Put(ctx, pe); err != nil { d.core.logger.Error("failed to write seal configuration", "error", err) - return errwrap.Wrapf("failed to write seal configuration: {{err}}", err) + return fmt.Errorf("failed to write seal configuration: %w", err) } d.SetCachedBarrierConfig(config.Clone()) @@ -370,11 +369,11 @@ func (s *SealConfig) Validate() error { for _, keystring := range s.PGPKeys { data, err := base64.StdEncoding.DecodeString(keystring) if err != nil { - return errwrap.Wrapf("error decoding given PGP key: {{err}}", err) + return fmt.Errorf("error decoding given PGP key: %w", err) } _, err = openpgp.ReadEntity(packet.NewReader(bytes.NewBuffer(data))) if err != nil { - return errwrap.Wrapf("error parsing given PGP key: {{err}}", err) + return fmt.Errorf("error parsing given PGP key: %w", err) } } } @@ -443,18 +442,18 @@ func writeStoredKeys(ctx context.Context, storage physical.Backend, encryptor *s buf, err := json.Marshal(keys) if err != nil { - return errwrap.Wrapf("failed to encode keys for storage: {{err}}", err) + return fmt.Errorf("failed to encode keys for storage: %w", err) } // Encrypt and marshal the keys blobInfo, err := encryptor.Encrypt(ctx, buf, nil) if err != nil { - return &ErrEncrypt{Err: errwrap.Wrapf("failed to encrypt keys for storage: {{err}}", err)} + return &ErrEncrypt{Err: fmt.Errorf("failed to encrypt keys for storage: %w", err)} } value, err := proto.Marshal(blobInfo) if err != nil { - return errwrap.Wrapf("failed to marshal value for storage: {{err}}", err) + return fmt.Errorf("failed to marshal value for storage: %w", err) } // Store the seal configuration. @@ -464,7 +463,7 @@ func writeStoredKeys(ctx context.Context, storage physical.Backend, encryptor *s } if err := storage.Put(ctx, pe); err != nil { - return errwrap.Wrapf("failed to write keys to storage: {{err}}", err) + return fmt.Errorf("failed to write keys to storage: %w", err) } return nil @@ -473,7 +472,7 @@ func writeStoredKeys(ctx context.Context, storage physical.Backend, encryptor *s func readStoredKeys(ctx context.Context, storage physical.Backend, encryptor *seal.Access) ([][]byte, error) { pe, err := storage.Get(ctx, StoredBarrierKeysPath) if err != nil { - return nil, errwrap.Wrapf("failed to fetch stored keys: {{err}}", err) + return nil, fmt.Errorf("failed to fetch stored keys: %w", err) } // This is not strictly an error; we may not have any stored keys, for @@ -484,12 +483,12 @@ func readStoredKeys(ctx context.Context, storage physical.Backend, encryptor *se blobInfo := &wrapping.EncryptedBlobInfo{} if err := proto.Unmarshal(pe.Value, blobInfo); err != nil { - return nil, errwrap.Wrapf("failed to proto decode stored keys: {{err}}", err) + return nil, fmt.Errorf("failed to proto decode stored keys: %w", err) } pt, err := encryptor.Decrypt(ctx, blobInfo, nil) if err != nil { - return nil, &ErrDecrypt{Err: errwrap.Wrapf("failed to encrypt keys for storage: {{err}}", err)} + return nil, &ErrDecrypt{Err: fmt.Errorf("failed to encrypt keys for storage: %w", err)} } // Decode the barrier entry diff --git a/vault/seal_autoseal.go b/vault/seal_autoseal.go index 5f38582b0..a037bc866 100644 --- a/vault/seal_autoseal.go +++ b/vault/seal_autoseal.go @@ -8,7 +8,6 @@ import ( "sync/atomic" proto "github.com/golang/protobuf/proto" - "github.com/hashicorp/errwrap" log "github.com/hashicorp/go-hclog" wrapping "github.com/hashicorp/go-kms-wrapping" "github.com/hashicorp/vault/sdk/physical" @@ -101,7 +100,7 @@ func (d *autoSeal) GetStoredKeys(ctx context.Context) ([][]byte, error) { func (d *autoSeal) upgradeStoredKeys(ctx context.Context) error { pe, err := d.core.physical.Get(ctx, StoredBarrierKeysPath) if err != nil { - return errwrap.Wrapf("failed to fetch stored keys: {{err}}", err) + return fmt.Errorf("failed to fetch stored keys: %w", err) } if pe == nil { return fmt.Errorf("no stored keys found") @@ -109,7 +108,7 @@ func (d *autoSeal) upgradeStoredKeys(ctx context.Context) error { blobInfo := &wrapping.EncryptedBlobInfo{} if err := proto.Unmarshal(pe.Value, blobInfo); err != nil { - return errwrap.Wrapf("failed to proto decode stored keys: {{err}}", err) + return fmt.Errorf("failed to proto decode stored keys: %w", err) } if blobInfo.KeyInfo != nil && blobInfo.KeyInfo.KeyID != d.Access.KeyID() { @@ -117,17 +116,17 @@ func (d *autoSeal) upgradeStoredKeys(ctx context.Context) error { pt, err := d.Decrypt(ctx, blobInfo, nil) if err != nil { - return errwrap.Wrapf("failed to decrypt encrypted stored keys: {{err}}", err) + return fmt.Errorf("failed to decrypt encrypted stored keys: %w", err) } // Decode the barrier entry var keys [][]byte if err := json.Unmarshal(pt, &keys); err != nil { - return errwrap.Wrapf("failed to decode stored keys: {{err}}", err) + return fmt.Errorf("failed to decode stored keys: %w", err) } if err := d.SetStoredKeys(ctx, keys); err != nil { - return errwrap.Wrapf("failed to save upgraded stored keys: {{err}}", err) + return fmt.Errorf("failed to save upgraded stored keys: %w", err) } } return nil @@ -167,7 +166,7 @@ func (d *autoSeal) BarrierConfig(ctx context.Context) (*SealConfig, error) { entry, err := d.core.physical.Get(ctx, barrierSealConfigPath) if err != nil { d.logger.Error("failed to read seal configuration", "seal_type", sealType, "error", err) - return nil, errwrap.Wrapf(fmt.Sprintf("failed to read %q seal configuration: {{err}}", sealType), err) + return nil, fmt.Errorf("failed to read %q seal configuration: %w", sealType, err) } // If the seal configuration is missing, we are not initialized @@ -182,13 +181,13 @@ func (d *autoSeal) BarrierConfig(ctx context.Context) (*SealConfig, error) { err = json.Unmarshal(entry.Value, conf) if err != nil { d.logger.Error("failed to decode seal configuration", "seal_type", sealType, "error", err) - return nil, errwrap.Wrapf(fmt.Sprintf("failed to decode %q seal configuration: {{err}}", sealType), err) + return nil, fmt.Errorf("failed to decode %q seal configuration: %w", sealType, err) } // Check for a valid seal configuration if err := conf.Validate(); err != nil { d.logger.Error("invalid seal configuration", "seal_type", sealType, "error", err) - return nil, errwrap.Wrapf(fmt.Sprintf("%q seal validation failed: {{err}}", sealType), err) + return nil, fmt.Errorf("%q seal validation failed: %w", sealType, err) } barrierTypeUpgradeCheck(d.BarrierType(), conf) @@ -217,7 +216,7 @@ func (d *autoSeal) SetBarrierConfig(ctx context.Context, conf *SealConfig) error // Encode the seal configuration buf, err := json.Marshal(conf) if err != nil { - return errwrap.Wrapf("failed to encode barrier seal configuration: {{err}}", err) + return fmt.Errorf("failed to encode barrier seal configuration: %w", err) } // Store the seal configuration @@ -228,7 +227,7 @@ func (d *autoSeal) SetBarrierConfig(ctx context.Context, conf *SealConfig) error if err := d.core.physical.Put(ctx, pe); err != nil { d.logger.Error("failed to write barrier seal configuration", "error", err) - return errwrap.Wrapf("failed to write barrier seal configuration: {{err}}", err) + return fmt.Errorf("failed to write barrier seal configuration: %w", err) } d.SetCachedBarrierConfig(conf.Clone()) @@ -261,7 +260,7 @@ func (d *autoSeal) RecoveryConfig(ctx context.Context) (*SealConfig, error) { entry, err = d.core.physical.Get(ctx, recoverySealConfigPlaintextPath) if err != nil { d.logger.Error("failed to read seal configuration", "seal_type", sealType, "error", err) - return nil, errwrap.Wrapf(fmt.Sprintf("failed to read %q seal configuration: {{err}}", sealType), err) + return nil, fmt.Errorf("failed to read %q seal configuration: %w", sealType, err) } if entry == nil { @@ -274,7 +273,7 @@ func (d *autoSeal) RecoveryConfig(ctx context.Context) (*SealConfig, error) { // return the correct seal config be, err := d.core.barrier.Get(ctx, recoverySealConfigPath) if err != nil { - return nil, errwrap.Wrapf("failed to read old recovery seal configuration: {{err}}", err) + return nil, fmt.Errorf("failed to read old recovery seal configuration: %w", err) } // If the seal configuration is missing, then we are not initialized. @@ -295,13 +294,13 @@ func (d *autoSeal) RecoveryConfig(ctx context.Context) (*SealConfig, error) { conf := &SealConfig{} if err := json.Unmarshal(entry.Value, conf); err != nil { d.logger.Error("failed to decode seal configuration", "seal_type", sealType, "error", err) - return nil, errwrap.Wrapf(fmt.Sprintf("failed to decode %q seal configuration: {{err}}", sealType), err) + return nil, fmt.Errorf("failed to decode %q seal configuration: %w", sealType, err) } // Check for a valid seal configuration if err := conf.Validate(); err != nil { d.logger.Error("invalid seal configuration", "seal_type", sealType, "error", err) - return nil, errwrap.Wrapf(fmt.Sprintf("%q seal validation failed: {{err}}", sealType), err) + return nil, fmt.Errorf("%q seal validation failed: %w", sealType, err) } if conf.Type != d.RecoveryType() { @@ -335,7 +334,7 @@ func (d *autoSeal) SetRecoveryConfig(ctx context.Context, conf *SealConfig) erro // Encode the seal configuration buf, err := json.Marshal(conf) if err != nil { - return errwrap.Wrapf("failed to encode recovery seal configuration: {{err}}", err) + return fmt.Errorf("failed to encode recovery seal configuration: %w", err) } // Store the seal configuration directly in the physical storage @@ -346,7 +345,7 @@ func (d *autoSeal) SetRecoveryConfig(ctx context.Context, conf *SealConfig) erro if err := d.core.physical.Put(ctx, pe); err != nil { d.logger.Error("failed to write recovery seal configuration", "error", err) - return errwrap.Wrapf("failed to write recovery seal configuration: {{err}}", err) + return fmt.Errorf("failed to write recovery seal configuration: %w", err) } d.recoveryConfig.Store(conf.Clone()) @@ -387,12 +386,12 @@ func (d *autoSeal) SetRecoveryKey(ctx context.Context, key []byte) error { // Encrypt and marshal the keys blobInfo, err := d.Encrypt(ctx, key, nil) if err != nil { - return errwrap.Wrapf("failed to encrypt keys for storage: {{err}}", err) + return fmt.Errorf("failed to encrypt keys for storage: %w", err) } value, err := proto.Marshal(blobInfo) if err != nil { - return errwrap.Wrapf("failed to marshal value for storage: {{err}}", err) + return fmt.Errorf("failed to marshal value for storage: %w", err) } be := &physical.Entry{ @@ -402,7 +401,7 @@ func (d *autoSeal) SetRecoveryKey(ctx context.Context, key []byte) error { if err := d.core.physical.Put(ctx, be); err != nil { d.logger.Error("failed to write recovery key", "error", err) - return errwrap.Wrapf("failed to write recovery key: {{err}}", err) + return fmt.Errorf("failed to write recovery key: %w", err) } return nil @@ -416,7 +415,7 @@ func (d *autoSeal) getRecoveryKeyInternal(ctx context.Context) ([]byte, error) { pe, err := d.core.physical.Get(ctx, recoveryKeyPath) if err != nil { d.logger.Error("failed to read recovery key", "error", err) - return nil, errwrap.Wrapf("failed to read recovery key: {{err}}", err) + return nil, fmt.Errorf("failed to read recovery key: %w", err) } if pe == nil { d.logger.Warn("no recovery key found") @@ -425,12 +424,12 @@ func (d *autoSeal) getRecoveryKeyInternal(ctx context.Context) ([]byte, error) { blobInfo := &wrapping.EncryptedBlobInfo{} if err := proto.Unmarshal(pe.Value, blobInfo); err != nil { - return nil, errwrap.Wrapf("failed to proto decode stored keys: {{err}}", err) + return nil, fmt.Errorf("failed to proto decode stored keys: %w", err) } pt, err := d.Decrypt(ctx, blobInfo, nil) if err != nil { - return nil, errwrap.Wrapf("failed to decrypt encrypted stored keys: {{err}}", err) + return nil, fmt.Errorf("failed to decrypt encrypted stored keys: %w", err) } return pt, nil @@ -439,7 +438,7 @@ func (d *autoSeal) getRecoveryKeyInternal(ctx context.Context) ([]byte, error) { func (d *autoSeal) upgradeRecoveryKey(ctx context.Context) error { pe, err := d.core.physical.Get(ctx, recoveryKeyPath) if err != nil { - return errwrap.Wrapf("failed to fetch recovery key: {{err}}", err) + return fmt.Errorf("failed to fetch recovery key: %w", err) } if pe == nil { return fmt.Errorf("no recovery key found") @@ -447,7 +446,7 @@ func (d *autoSeal) upgradeRecoveryKey(ctx context.Context) error { blobInfo := &wrapping.EncryptedBlobInfo{} if err := proto.Unmarshal(pe.Value, blobInfo); err != nil { - return errwrap.Wrapf("failed to proto decode recovery key: {{err}}", err) + return fmt.Errorf("failed to proto decode recovery key: %w", err) } if blobInfo.KeyInfo != nil && blobInfo.KeyInfo.KeyID != d.Access.KeyID() { @@ -455,10 +454,10 @@ func (d *autoSeal) upgradeRecoveryKey(ctx context.Context) error { pt, err := d.Decrypt(ctx, blobInfo, nil) if err != nil { - return errwrap.Wrapf("failed to decrypt encrypted recovery key: {{err}}", err) + return fmt.Errorf("failed to decrypt encrypted recovery key: %w", err) } if err := d.SetRecoveryKey(ctx, pt); err != nil { - return errwrap.Wrapf("failed to save upgraded recovery key: {{err}}", err) + return fmt.Errorf("failed to save upgraded recovery key: %w", err) } } return nil @@ -471,7 +470,7 @@ func (d *autoSeal) migrateRecoveryConfig(ctx context.Context) error { // Get config from the old recoverySealConfigPath path be, err := d.core.barrier.Get(ctx, recoverySealConfigPath) if err != nil { - return errwrap.Wrapf("failed to read old recovery seal configuration during migration: {{err}}", err) + return fmt.Errorf("failed to read old recovery seal configuration during migration: %w", err) } // If this entry is nil, then skip migration @@ -490,12 +489,12 @@ func (d *autoSeal) migrateRecoveryConfig(ctx context.Context) error { } if err := d.core.physical.Put(ctx, pe); err != nil { - return errwrap.Wrapf("failed to write recovery seal configuration during migration: {{err}}", err) + return fmt.Errorf("failed to write recovery seal configuration during migration: %w", err) } // Perform deletion of the old entry if err := d.core.barrier.Delete(ctx, recoverySealConfigPath); err != nil { - return errwrap.Wrapf("failed to delete old recovery seal configuration during migration: {{err}}", err) + return fmt.Errorf("failed to delete old recovery seal configuration during migration: %w", err) } return nil diff --git a/vault/token_store.go b/vault/token_store.go index b83c53568..e2f7c4edb 100644 --- a/vault/token_store.go +++ b/vault/token_store.go @@ -16,7 +16,6 @@ import ( "github.com/armon/go-metrics" "github.com/armon/go-radix" "github.com/golang/protobuf/proto" - "github.com/hashicorp/errwrap" log "github.com/hashicorp/go-hclog" "github.com/hashicorp/go-multierror" "github.com/hashicorp/go-sockaddr" @@ -787,12 +786,12 @@ func (ts *TokenStore) createAccessor(ctx context.Context, entry *logical.TokenEn aEntryBytes, err := jsonutil.EncodeJSON(aEntry) if err != nil { - return errwrap.Wrapf("failed to marshal accessor index entry: {{err}}", err) + return fmt.Errorf("failed to marshal accessor index entry: %w", err) } le := &logical.StorageEntry{Key: saltID, Value: aEntryBytes} if err := ts.accessorView(tokenNS).Put(ctx, le); err != nil { - return errwrap.Wrapf("failed to persist accessor index entry: {{err}}", err) + return fmt.Errorf("failed to persist accessor index entry: %w", err) } return nil } @@ -967,7 +966,7 @@ func (ts *TokenStore) storeCommon(ctx context.Context, entry *logical.TokenEntry // Marshal the entry enc, err := json.Marshal(entry) if err != nil { - return errwrap.Wrapf("failed to encode entry: {{err}}", err) + return fmt.Errorf("failed to encode entry: %w", err) } if writeSecondary { @@ -979,7 +978,7 @@ func (ts *TokenStore) storeCommon(ctx context.Context, entry *logical.TokenEntry // Ensure the parent exists parent, err := ts.Lookup(ctx, entry.Parent) if err != nil { - return errwrap.Wrapf("failed to lookup parent: {{err}}", err) + return fmt.Errorf("failed to lookup parent: %w", err) } if parent == nil { return fmt.Errorf("parent token not found") @@ -1008,7 +1007,7 @@ func (ts *TokenStore) storeCommon(ctx context.Context, entry *logical.TokenEntry le := &logical.StorageEntry{Key: path} if err := ts.parentView(parentNS).Put(ctx, le); err != nil { - return errwrap.Wrapf("failed to persist entry: {{err}}", err) + return fmt.Errorf("failed to persist entry: %w", err) } } } @@ -1019,7 +1018,7 @@ func (ts *TokenStore) storeCommon(ctx context.Context, entry *logical.TokenEntry le.SealWrap = true } if err := ts.idView(tokenNS).Put(ctx, le); err != nil { - return errwrap.Wrapf("failed to persist entry: {{err}}", err) + return fmt.Errorf("failed to persist entry: %w", err) } return nil } @@ -1055,7 +1054,7 @@ func (ts *TokenStore) UseToken(ctx context.Context, te *logical.TokenEntry) (*lo var err error te, err = ts.lookupInternal(ctx, te.ID, false, false) if err != nil { - return nil, errwrap.Wrapf("failed to refresh entry: {{err}}", err) + return nil, fmt.Errorf("failed to refresh entry: %w", err) } // If it can't be found we shouldn't be trying to use it, so if we get nil // back, it is because it has been revoked in the interim or will be @@ -1188,7 +1187,7 @@ func (ts *TokenStore) lookupBatchToken(ctx context.Context, id string) (*logical func (ts *TokenStore) lookupInternal(ctx context.Context, id string, salted, tainted bool) (*logical.TokenEntry, error) { ns, err := namespace.FromContext(ctx) if err != nil { - return nil, errwrap.Wrapf("failed to find namespace in context: {{err}}", err) + return nil, fmt.Errorf("failed to find namespace in context: %w", err) } // If it starts with "b." it's a batch token @@ -1206,7 +1205,7 @@ func (ts *TokenStore) lookupInternal(ctx context.Context, id string, salted, tai if nsID != "" { tokenNS, err := NamespaceByID(ctx, nsID, ts.core) if err != nil { - return nil, errwrap.Wrapf("failed to look up namespace from the token: {{err}}", err) + return nil, fmt.Errorf("failed to look up namespace from the token: %w", err) } if tokenNS != nil { if tokenNS.ID != ns.ID { @@ -1230,7 +1229,7 @@ func (ts *TokenStore) lookupInternal(ctx context.Context, id string, salted, tai raw, err = ts.idView(ns).Get(ctx, lookupID) if err != nil { - return nil, errwrap.Wrapf("failed to read entry: {{err}}", err) + return nil, fmt.Errorf("failed to read entry: %w", err) } // Bail if not found @@ -1241,7 +1240,7 @@ func (ts *TokenStore) lookupInternal(ctx context.Context, id string, salted, tai // Unmarshal the token entry := new(logical.TokenEntry) if err := jsonutil.DecodeJSON(raw.Value, entry); err != nil { - return nil, errwrap.Wrapf("failed to decode entry: {{err}}", err) + return nil, fmt.Errorf("failed to decode entry: %w", err) } // This is a token that is awaiting deferred revocation or tainted @@ -1301,7 +1300,7 @@ func (ts *TokenStore) lookupInternal(ctx context.Context, id string, salted, tai // If fields are getting upgraded, store the changes if persistNeeded { if err := ts.store(ctx, entry); err != nil { - return nil, errwrap.Wrapf("failed to persist token upgrade: {{err}}", err) + return nil, fmt.Errorf("failed to persist token upgrade: %w", err) } } return entry, nil @@ -1316,7 +1315,7 @@ func (ts *TokenStore) lookupInternal(ctx context.Context, id string, salted, tai } le, err := ts.expiration.FetchLeaseTimesByToken(ctx, entry) if err != nil { - return nil, errwrap.Wrapf("failed to fetch lease times: {{err}}", err) + return nil, fmt.Errorf("failed to fetch lease times: %w", err) } var ret *logical.TokenEntry @@ -1354,7 +1353,7 @@ func (ts *TokenStore) lookupInternal(ctx context.Context, id string, salted, tai // If fields are getting upgraded, store the changes if persistNeeded { if err := ts.store(ctx, entry); err != nil { - return nil, errwrap.Wrapf("failed to persist token upgrade: {{err}}", err) + return nil, fmt.Errorf("failed to persist token upgrade: %w", err) } } @@ -1428,7 +1427,7 @@ func (ts *TokenStore) revokeInternal(ctx context.Context, saltedID string, skipO // before we return, we can remove the token store entry if ret == nil { if err := ts.idView(tokenNS).Delete(ctx, saltedID); err != nil { - ret = errwrap.Wrapf("failed to delete entry: {{err}}", err) + ret = fmt.Errorf("failed to delete entry: %w", err) } } @@ -1467,7 +1466,7 @@ func (ts *TokenStore) revokeInternal(ctx context.Context, saltedID string, skipO default: parentNS, err = NamespaceByID(ctx, parentNSID, ts.core) if err != nil { - return errwrap.Wrapf("failed to get parent namespace: {{err}}", err) + return fmt.Errorf("failed to get parent namespace: %w", err) } if parentNS == nil { return namespace.ErrNoNamespace @@ -1488,7 +1487,7 @@ func (ts *TokenStore) revokeInternal(ctx context.Context, saltedID string, skipO } if err = ts.parentView(parentNS).Delete(ctx, path); err != nil { - return errwrap.Wrapf("failed to delete entry: {{err}}", err) + return fmt.Errorf("failed to delete entry: %w", err) } } @@ -1500,7 +1499,7 @@ func (ts *TokenStore) revokeInternal(ctx context.Context, saltedID string, skipO } if err = ts.accessorView(tokenNS).Delete(ctx, accessorSaltedID); err != nil { - return errwrap.Wrapf("failed to delete entry: {{err}}", err) + return fmt.Errorf("failed to delete entry: %w", err) } } @@ -1514,7 +1513,7 @@ func (ts *TokenStore) revokeInternal(ctx context.Context, saltedID string, skipO // on child prefixes as there will be none (as saltedID entry is a leaf node). children, err := ts.parentView(tokenNS).List(ctx, saltedID+"/") if err != nil { - return errwrap.Wrapf("failed to scan for children: {{err}}", err) + return fmt.Errorf("failed to scan for children: %w", err) } for _, child := range children { var childNSID string @@ -1523,7 +1522,7 @@ func (ts *TokenStore) revokeInternal(ctx context.Context, saltedID string, skipO if childNSID != "" { childNS, err := NamespaceByID(ctx, childNSID, ts.core) if err != nil { - return errwrap.Wrapf("failed to get child token: {{err}}", err) + return fmt.Errorf("failed to get child token: %w", err) } if childNS == nil { return namespace.ErrNoNamespace @@ -1534,13 +1533,13 @@ func (ts *TokenStore) revokeInternal(ctx context.Context, saltedID string, skipO entry, err := ts.lookupInternal(childCtx, child, true, true) if err != nil { - return errwrap.Wrapf("failed to get child token: {{err}}", err) + return fmt.Errorf("failed to get child token: %w", err) } if entry == nil { // Seems it's already revoked, so nothing to do here except delete the index err = ts.parentView(tokenNS).Delete(ctx, child) if err != nil { - return errwrap.Wrapf("failed to delete child entry: {{err}}", err) + return fmt.Errorf("failed to delete child entry: %w", err) } continue } @@ -1552,7 +1551,7 @@ func (ts *TokenStore) revokeInternal(ctx context.Context, saltedID string, skipO err = ts.store(childCtx, entry) if err != nil { lock.Unlock() - return errwrap.Wrapf("failed to update child token: {{err}}", err) + return fmt.Errorf("failed to update child token: %w", err) } lock.Unlock() @@ -1562,7 +1561,7 @@ func (ts *TokenStore) revokeInternal(ctx context.Context, saltedID string, skipO // of logical.ClearView err = ts.parentView(tokenNS).Delete(ctx, child) if err != nil { - return errwrap.Wrapf("failed to delete child entry: {{err}}", err) + return fmt.Errorf("failed to delete child entry: %w", err) } } } @@ -1633,7 +1632,7 @@ func (ts *TokenStore) revokeTreeInternal(ctx context.Context, id string) error { if saltedNSID != "" { saltedNS, err = NamespaceByID(ctx, saltedNSID, ts.core) if err != nil { - return errwrap.Wrapf("failed to find namespace for token revocation: {{err}}", err) + return fmt.Errorf("failed to find namespace for token revocation: %w", err) } saltedCtx = namespace.ContextWithNamespace(ctx, saltedNS) @@ -1642,7 +1641,7 @@ func (ts *TokenStore) revokeTreeInternal(ctx context.Context, id string) error { path := saltedID + "/" childrenRaw, err := ts.parentView(saltedNS).List(saltedCtx, path) if err != nil { - return errwrap.Wrapf("failed to scan for children: {{err}}", err) + return fmt.Errorf("failed to scan for children: %w", err) } // Filter the child list to remove any items that have ever been in the dfs stack. @@ -1653,7 +1652,7 @@ func (ts *TokenStore) revokeTreeInternal(ctx context.Context, id string) error { children = append(children, child) } else { if err = ts.parentView(saltedNS).Delete(saltedCtx, path+child); err != nil { - return errwrap.Wrapf("failed to delete entry: {{err}}", err) + return fmt.Errorf("failed to delete entry: %w", err) } ts.Logger().Warn("token cycle found", "token", child) @@ -1669,7 +1668,7 @@ func (ts *TokenStore) revokeTreeInternal(ctx context.Context, id string) error { // would have been deleted, and any pending leases for deletion will be restored // by the expiration manager. if err := ts.revokeInternal(saltedCtx, saltedID, true); err != nil { - return errwrap.Wrapf("failed to revoke entry: {{err}}", err) + return fmt.Errorf("failed to revoke entry: %w", err) } // If the length of l is equal to 1, then the last token has been deleted if l == 1 { @@ -1756,7 +1755,7 @@ func (ts *TokenStore) lookupByAccessor(ctx context.Context, id string, salted, t entry, err := ts.accessorView(ns).Get(ctx, lookupID) if err != nil { - return aEntry, errwrap.Wrapf("failed to read index using accessor: {{err}}", err) + return aEntry, fmt.Errorf("failed to read index using accessor: %w", err) } if entry == nil { return aEntry, &logical.StatusBadRequest{Err: "invalid accessor"} @@ -1767,7 +1766,7 @@ func (ts *TokenStore) lookupByAccessor(ctx context.Context, id string, salted, t if err != nil { te, err := ts.lookupInternal(ctx, string(entry.Value), false, tainted) if err != nil { - return accessorEntry{}, errwrap.Wrapf("failed to look up token using accessor index: {{err}}", err) + return accessorEntry{}, fmt.Errorf("failed to look up token using accessor index: %w", err) } // It's hard to reason about what to do here if te is nil -- it may be // that the token was revoked async, or that it's an old accessor index @@ -1799,7 +1798,7 @@ func (ts *TokenStore) handleTidy(ctx context.Context, req *logical.Request, data ns, err := namespace.FromContext(ctx) if err != nil { - return nil, errwrap.Wrapf("failed to get namespace from context: {{err}}", err) + return nil, fmt.Errorf("failed to get namespace from context: %w", err) } go func() { @@ -1818,13 +1817,13 @@ func (ts *TokenStore) handleTidy(ctx context.Context, req *logical.Request, data // List out all the accessors saltedAccessorList, err := ts.accessorView(ns).List(quitCtx, "") if err != nil { - return errwrap.Wrapf("failed to fetch accessor index entries: {{err}}", err) + return fmt.Errorf("failed to fetch accessor index entries: %w", err) } // First, clean up secondary index entries that are no longer valid parentList, err := ts.parentView(ns).List(quitCtx, "") if err != nil { - return errwrap.Wrapf("failed to fetch secondary index entries: {{err}}", err) + return fmt.Errorf("failed to fetch secondary index entries: %w", err) } // List all the cubbyhole storage keys @@ -1836,7 +1835,7 @@ func (ts *TokenStore) handleTidy(ctx context.Context, req *logical.Request, data cubbyholeKeys, err := bview.List(quitCtx, "") if err != nil { - return errwrap.Wrapf("failed to fetch cubbyhole storage keys: {{err}}", err) + return fmt.Errorf("failed to fetch cubbyhole storage keys: %w", err) } var countParentEntries, deletedCountParentEntries, countParentList, deletedCountParentList int64 @@ -1849,7 +1848,7 @@ func (ts *TokenStore) handleTidy(ctx context.Context, req *logical.Request, data // Get the children children, err := ts.parentView(ns).List(quitCtx, parent) if err != nil { - tidyErrors = multierror.Append(tidyErrors, errwrap.Wrapf("failed to read secondary index: {{err}}", err)) + tidyErrors = multierror.Append(tidyErrors, fmt.Errorf("failed to read secondary index: %w", err)) continue } @@ -1884,7 +1883,7 @@ func (ts *TokenStore) handleTidy(ctx context.Context, req *logical.Request, data te.Parent = "" err = ts.store(quitCtx, te) if err != nil { - tidyErrors = multierror.Append(tidyErrors, errwrap.Wrapf("failed to convert child token into an orphan token: {{err}}", err)) + tidyErrors = multierror.Append(tidyErrors, fmt.Errorf("failed to convert child token into an orphan token: %w", err)) } lock.Unlock() continue @@ -1896,7 +1895,7 @@ func (ts *TokenStore) handleTidy(ctx context.Context, req *logical.Request, data ts.logger.Debug("deleting invalid secondary index", "index", index) err = ts.parentView(ns).Delete(quitCtx, index) if err != nil { - tidyErrors = multierror.Append(tidyErrors, errwrap.Wrapf("failed to delete secondary index: {{err}}", err)) + tidyErrors = multierror.Append(tidyErrors, fmt.Errorf("failed to delete secondary index: %w", err)) continue } deletedChildrenCount++ @@ -1933,7 +1932,7 @@ func (ts *TokenStore) handleTidy(ctx context.Context, req *logical.Request, data accessorEntry, err := ts.lookupByAccessor(quitCtx, saltedAccessor, true, true) if err != nil { - tidyErrors = multierror.Append(tidyErrors, errwrap.Wrapf("failed to read the accessor index: {{err}}", err)) + tidyErrors = multierror.Append(tidyErrors, fmt.Errorf("failed to read the accessor index: %w", err)) continue } @@ -1945,7 +1944,7 @@ func (ts *TokenStore) handleTidy(ctx context.Context, req *logical.Request, data // item since this is just a best-effort operation err = ts.accessorView(ns).Delete(quitCtx, saltedAccessor) if err != nil { - tidyErrors = multierror.Append(tidyErrors, errwrap.Wrapf("failed to delete the accessor index: {{err}}", err)) + tidyErrors = multierror.Append(tidyErrors, fmt.Errorf("failed to delete the accessor index: %w", err)) continue } deletedCountAccessorEmptyToken++ @@ -1958,7 +1957,7 @@ func (ts *TokenStore) handleTidy(ctx context.Context, req *logical.Request, data // exist te, err := ts.lookupInternal(quitCtx, accessorEntry.TokenID, false, true) if err != nil { - tidyErrors = multierror.Append(tidyErrors, errwrap.Wrapf("failed to lookup tainted ID: {{err}}", err)) + tidyErrors = multierror.Append(tidyErrors, fmt.Errorf("failed to lookup tainted ID: %w", err)) lock.RUnlock() continue } @@ -1985,7 +1984,7 @@ func (ts *TokenStore) handleTidy(ctx context.Context, req *logical.Request, data // the leases associated with the token. err = ts.expiration.RevokeByToken(quitCtx, tokenEntry) if err != nil { - tidyErrors = multierror.Append(tidyErrors, errwrap.Wrapf("failed to revoke leases of expired token: {{err}}", err)) + tidyErrors = multierror.Append(tidyErrors, fmt.Errorf("failed to revoke leases of expired token: %w", err)) continue } deletedCountInvalidTokenInAccessor++ @@ -1996,7 +1995,7 @@ func (ts *TokenStore) handleTidy(ctx context.Context, req *logical.Request, data // entry to try again. err = ts.accessorView(ns).Delete(quitCtx, saltedAccessor) if err != nil { - tidyErrors = multierror.Append(tidyErrors, errwrap.Wrapf("failed to delete accessor entry: {{err}}", err)) + tidyErrors = multierror.Append(tidyErrors, fmt.Errorf("failed to delete accessor entry: %w", err)) continue } deletedCountAccessorInvalidToken++ @@ -2006,7 +2005,7 @@ func (ts *TokenStore) handleTidy(ctx context.Context, req *logical.Request, data case te.NamespaceID == namespace.RootNamespaceID && !strings.HasPrefix(te.ID, "s."): saltedID, err := ts.SaltID(quitCtx, te.ID) if err != nil { - tidyErrors = multierror.Append(tidyErrors, errwrap.Wrapf("failed to create salted token id: {{err}}", err)) + tidyErrors = multierror.Append(tidyErrors, fmt.Errorf("failed to create salted token id: %w", err)) continue } validCubbyholeKeys[salt.SaltID(ts.cubbyholeBackend.saltUUID, saltedID, salt.SHA1Hash)] = true @@ -2033,7 +2032,7 @@ func (ts *TokenStore) handleTidy(ctx context.Context, req *logical.Request, data ts.logger.Info("deleting invalid cubbyhole", "key", key) err = ts.cubbyholeBackend.revoke(quitCtx, bview, key) if err != nil { - tidyErrors = multierror.Append(tidyErrors, errwrap.Wrapf(fmt.Sprintf("failed to revoke cubbyhole key %q: {{err}}", key), err)) + tidyErrors = multierror.Append(tidyErrors, fmt.Errorf("failed to revoke cubbyhole key %q: %w", key, err)) } deletedCountInvalidCubbyholeKey++ } @@ -2215,7 +2214,7 @@ func (ts *TokenStore) handleCreateCommon(ctx context.Context, req *logical.Reque // Read the parent policy parent, err := ts.Lookup(ctx, req.ClientToken) if err != nil { - return nil, errwrap.Wrapf("parent token lookup failed: {{err}}", err) + return nil, fmt.Errorf("parent token lookup failed: %w", err) } if parent == nil { return logical.ErrorResponse("parent token lookup failed: no parent found"), logical.ErrInvalidRequest @@ -2897,7 +2896,7 @@ func (ts *TokenStore) handleRevokeOrphan(ctx context.Context, req *logical.Reque // running in the same namespace or a parent. te, err := ts.Lookup(ctx, id) if err != nil { - return nil, errwrap.Wrapf("error when looking up token to revoke: {{err}}", err) + return nil, fmt.Errorf("error when looking up token to revoke: %w", err) } if te == nil { return logical.ErrorResponse("token to revoke not found"), logical.ErrInvalidRequest @@ -3048,7 +3047,7 @@ func (ts *TokenStore) handleRenew(ctx context.Context, req *logical.Request, dat // Lookup the token te, err := ts.Lookup(ctx, id) if err != nil { - return nil, errwrap.Wrapf("error looking up token to renew: {{err}}", err) + return nil, fmt.Errorf("error looking up token to renew: %w", err) } if te == nil { return logical.ErrorResponse("token not found"), logical.ErrInvalidRequest @@ -3073,7 +3072,7 @@ func (ts *TokenStore) authRenew(ctx context.Context, req *logical.Request, d *fr te, err := ts.Lookup(ctx, req.Auth.ClientToken) if err != nil { - return nil, errwrap.Wrapf("error looking up token: {{err}}", err) + return nil, fmt.Errorf("error looking up token: %w", err) } if te == nil { return nil, fmt.Errorf("no token entry found during lookup") @@ -3087,7 +3086,7 @@ func (ts *TokenStore) authRenew(ctx context.Context, req *logical.Request, d *fr role, err := ts.tokenStoreRole(ctx, te.Role) if err != nil { - return nil, errwrap.Wrapf(fmt.Sprintf("error looking up role %q: {{err}}", te.Role), err) + return nil, fmt.Errorf("error looking up role %q: %w", te.Role, err) } if role == nil { return nil, fmt.Errorf("original token role %q could not be found, not renewing", te.Role) @@ -3305,7 +3304,7 @@ func (ts *TokenStore) tokenStoreRoleCreateUpdate(ctx context.Context, req *logic // Next parse token fields from the helper if err := entry.ParseTokenFields(req, data); err != nil { - return logical.ErrorResponse(errwrap.Wrapf("error parsing role fields: {{err}}", err).Error()), nil + return logical.ErrorResponse(fmt.Errorf("error parsing role fields: %w", err).Error()), nil } entry.TokenType = oldEntryTokenType @@ -3358,7 +3357,7 @@ func (ts *TokenStore) tokenStoreRoleCreateUpdate(ctx context.Context, req *logic if ok { boundCIDRs, err := parseutil.ParseAddrs(boundCIDRsRaw.([]string)) if err != nil { - return logical.ErrorResponse(errwrap.Wrapf("error parsing bound_cidrs: {{err}}", err).Error()), nil + return logical.ErrorResponse(fmt.Errorf("error parsing bound_cidrs: %w", err).Error()), nil } entry.BoundCIDRs = boundCIDRs entry.TokenBoundCIDRs = entry.BoundCIDRs diff --git a/vault/wrapping.go b/vault/wrapping.go index 6e67093d4..03026f7fe 100644 --- a/vault/wrapping.go +++ b/vault/wrapping.go @@ -11,7 +11,6 @@ import ( "time" "github.com/armon/go-metrics" - "github.com/hashicorp/errwrap" "github.com/hashicorp/vault/helper/metricsutil" "github.com/hashicorp/vault/helper/namespace" "github.com/hashicorp/vault/sdk/helper/certutil" @@ -38,7 +37,7 @@ func (c *Core) ensureWrappingKey(ctx context.Context) error { if entry == nil { key, err := ecdsa.GenerateKey(elliptic.P521(), c.secureRandomReader) if err != nil { - return errwrap.Wrapf("failed to generate wrapping key: {{err}}", err) + return fmt.Errorf("failed to generate wrapping key: %w", err) } keyParams.D = key.D keyParams.X = key.X @@ -46,20 +45,20 @@ func (c *Core) ensureWrappingKey(ctx context.Context) error { keyParams.Type = corePrivateKeyTypeP521 val, err := jsonutil.EncodeJSON(keyParams) if err != nil { - return errwrap.Wrapf("failed to encode wrapping key: {{err}}", err) + return fmt.Errorf("failed to encode wrapping key: %w", err) } entry = &logical.StorageEntry{ Key: coreWrappingJWTKeyPath, Value: val, } if err = c.barrier.Put(ctx, entry); err != nil { - return errwrap.Wrapf("failed to store wrapping key: {{err}}", err) + return fmt.Errorf("failed to store wrapping key: %w", err) } } // Redundant if we just created it, but in this case serves as a check anyways if err = jsonutil.DecodeJSON(entry.Value, &keyParams); err != nil { - return errwrap.Wrapf("failed to decode wrapping key parameters: {{err}}", err) + return fmt.Errorf("failed to decode wrapping key parameters: %w", err) } c.wrappingJWTKey = &ecdsa.PrivateKey{ @@ -406,12 +405,12 @@ func (c *Core) ValidateWrappingToken(ctx context.Context, req *logical.Request) // Implement the jose library way parsedJWT, err := squarejwt.ParseSigned(token) if err != nil { - return false, errwrap.Wrapf("wrapping token could not be parsed: {{err}}", err) + return false, fmt.Errorf("wrapping token could not be parsed: %w", err) } var claims squarejwt.Claims allClaims := make(map[string]interface{}) if err = parsedJWT.Claims(&c.wrappingJWTKey.PublicKey, &claims, &allClaims); err != nil { - return false, errwrap.Wrapf("wrapping token signature could not be validated: {{err}}", err) + return false, fmt.Errorf("wrapping token signature could not be validated: %w", err) } typeClaimRaw, ok := allClaims["type"] if !ok {