From 8d515fec2b888a7b178c1d3b92f8735ad278b2eb Mon Sep 17 00:00:00 2001 From: Lars Lehtonen Date: Wed, 2 Jun 2021 06:22:31 -0700 Subject: [PATCH] command: deprecate errwrap.Wrapf() (#11744) --- command/agent.go | 9 ++++---- command/agent/auth/approle/approle.go | 13 +++++------ command/agent/auth/aws/aws.go | 11 +++++---- command/agent/auth/azure/azure.go | 9 ++++---- command/agent/auth/gcp/gcp.go | 17 +++++++------- command/agent/auth/kubernetes/kubernetes.go | 3 +-- command/agent/cache/handler.go | 5 ++--- command/agent/cache/lease_cache.go | 7 +++--- command/agent/config/config.go | 15 ++++++------- command/agent/sink/file/file_sink.go | 15 ++++++------- command/agent/sink/sink.go | 24 ++++++++++---------- command/base_helpers.go | 3 +-- command/config/config.go | 5 ++--- command/operator_generate_root.go | 7 +++--- command/operator_migrate.go | 25 ++++++++++----------- command/server.go | 22 +++++++++--------- command/server/config.go | 15 ++++++------- command/server/listener.go | 3 +-- command/ssh.go | 5 ++--- command/token/helper_external.go | 8 +++---- 20 files changed, 101 insertions(+), 120 deletions(-) diff --git a/command/agent.go b/command/agent.go index 576d9a40ed..dbe7d81c82 100644 --- a/command/agent.go +++ b/command/agent.go @@ -17,7 +17,6 @@ import ( "sync" "time" - "github.com/hashicorp/errwrap" log "github.com/hashicorp/go-hclog" "github.com/hashicorp/vault/api" "github.com/hashicorp/vault/command/agent/auth" @@ -357,7 +356,7 @@ func (c *AgentCommand) Run(args []string) int { } s, err := file.NewFileSink(config) if err != nil { - c.UI.Error(errwrap.Wrapf("Error creating file sink: {{err}}", err).Error()) + c.UI.Error(fmt.Errorf("Error creating file sink: %w", err).Error()) return 1 } config.Sink = s @@ -411,7 +410,7 @@ func (c *AgentCommand) Run(args []string) int { return 1 } if err != nil { - c.UI.Error(errwrap.Wrapf(fmt.Sprintf("Error creating %s auth method: {{err}}", config.AutoAuth.Method.Type), err).Error()) + c.UI.Error(fmt.Errorf("Error creating %s auth method: %w", config.AutoAuth.Method.Type, err).Error()) return 1 } } @@ -947,7 +946,7 @@ func (c *AgentCommand) storePidFile(pidPath string) error { // Open the PID file pidFile, err := os.OpenFile(pidPath, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0o644) if err != nil { - return errwrap.Wrapf("could not open pid file: {{err}}", err) + return fmt.Errorf("could not open pid file: %w", err) } defer pidFile.Close() @@ -955,7 +954,7 @@ func (c *AgentCommand) storePidFile(pidPath string) error { pid := os.Getpid() _, err = pidFile.WriteString(fmt.Sprintf("%d", pid)) if err != nil { - return errwrap.Wrapf("could not write to pid file: {{err}}", err) + return fmt.Errorf("could not write to pid file: %w", err) } return nil } diff --git a/command/agent/auth/approle/approle.go b/command/agent/auth/approle/approle.go index f9970348b7..a76ba0b774 100644 --- a/command/agent/auth/approle/approle.go +++ b/command/agent/auth/approle/approle.go @@ -9,7 +9,6 @@ import ( "os" "strings" - "github.com/hashicorp/errwrap" hclog "github.com/hashicorp/go-hclog" "github.com/hashicorp/vault/api" "github.com/hashicorp/vault/command/agent/auth" @@ -68,7 +67,7 @@ func NewApproleAuthMethod(conf *auth.AuthConfig) (auth.AuthMethod, error) { if ok { removeSecretIDFileAfterReading, err := parseutil.ParseBool(removeSecretIDFileAfterReadingRaw) if err != nil { - return nil, errwrap.Wrapf("error parsing 'remove_secret_id_file_after_reading' value: {{err}}", err) + return nil, fmt.Errorf("error parsing 'remove_secret_id_file_after_reading' value: %w", err) } a.removeSecretIDFileAfterReading = removeSecretIDFileAfterReading } @@ -93,7 +92,7 @@ func (a *approleMethod) Authenticate(ctx context.Context, client *api.Client) (s roleID, err := ioutil.ReadFile(a.roleIDFilePath) if err != nil { if a.cachedRoleID == "" { - return "", nil, nil, errwrap.Wrapf("error reading role ID file and no cached role ID known: {{err}}", err) + return "", nil, nil, fmt.Errorf("error reading role ID file and no cached role ID known: %w", err) } a.logger.Warn("error reading role ID file", "error", err) } @@ -121,7 +120,7 @@ func (a *approleMethod) Authenticate(ctx context.Context, client *api.Client) (s secretID, err := ioutil.ReadFile(a.secretIDFilePath) if err != nil { if a.cachedSecretID == "" { - return "", nil, nil, errwrap.Wrapf("error reading secret ID file and no cached secret ID known: {{err}}", err) + return "", nil, nil, fmt.Errorf("error reading secret ID file and no cached secret ID known: %w", err) } a.logger.Warn("error reading secret ID file", "error", err) } @@ -135,13 +134,13 @@ func (a *approleMethod) Authenticate(ctx context.Context, client *api.Client) (s if a.secretIDResponseWrappingPath != "" { clonedClient, err := client.Clone() if err != nil { - return "", nil, nil, errwrap.Wrapf("error cloning client to unwrap secret ID: {{err}}", err) + return "", nil, nil, fmt.Errorf("error cloning client to unwrap secret ID: %w", err) } clonedClient.SetToken(stringSecretID) // Validate the creation path resp, err := clonedClient.Logical().Read("sys/wrapping/lookup") if err != nil { - return "", nil, nil, errwrap.Wrapf("error looking up wrapped secret ID: {{err}}", err) + return "", nil, nil, fmt.Errorf("error looking up wrapped secret ID: %w", err) } if resp == nil { return "", nil, nil, errors.New("response nil when looking up wrapped secret ID") @@ -164,7 +163,7 @@ func (a *approleMethod) Authenticate(ctx context.Context, client *api.Client) (s // Now get the secret ID resp, err = clonedClient.Logical().Unwrap("") if err != nil { - return "", nil, nil, errwrap.Wrapf("error unwrapping secret ID: {{err}}", err) + return "", nil, nil, fmt.Errorf("error unwrapping secret ID: %w", err) } if resp == nil { return "", nil, nil, errors.New("response nil when unwrapping secret ID") diff --git a/command/agent/auth/aws/aws.go b/command/agent/auth/aws/aws.go index f24fd205cf..56992b3ae0 100644 --- a/command/agent/auth/aws/aws.go +++ b/command/agent/auth/aws/aws.go @@ -13,7 +13,6 @@ import ( "github.com/aws/aws-sdk-go/aws/credentials" "github.com/aws/aws-sdk-go/aws/ec2metadata" "github.com/aws/aws-sdk-go/aws/session" - "github.com/hashicorp/errwrap" "github.com/hashicorp/go-hclog" "github.com/hashicorp/go-uuid" "github.com/hashicorp/vault/api" @@ -183,7 +182,7 @@ func (a *awsMethod) Authenticate(ctx context.Context, client *api.Client) (retTo data := make(map[string]interface{}) sess, err := session.NewSession() if err != nil { - retErr = errwrap.Wrapf("error creating session: {{err}}", err) + retErr = fmt.Errorf("error creating session: %w", err) return } metadataSvc := ec2metadata.New(sess) @@ -194,7 +193,7 @@ func (a *awsMethod) Authenticate(ctx context.Context, client *api.Client) (retTo { doc, err := metadataSvc.GetDynamicData("/instance-identity/document") if err != nil { - retErr = errwrap.Wrapf("error requesting doc: {{err}}", err) + retErr = fmt.Errorf("error requesting doc: %w", err) return } data["identity"] = base64.StdEncoding.EncodeToString([]byte(doc)) @@ -204,7 +203,7 @@ func (a *awsMethod) Authenticate(ctx context.Context, client *api.Client) (retTo { signature, err := metadataSvc.GetDynamicData("/instance-identity/signature") if err != nil { - retErr = errwrap.Wrapf("error requesting signature: {{err}}", err) + retErr = fmt.Errorf("error requesting signature: %w", err) return } data["signature"] = signature @@ -214,7 +213,7 @@ func (a *awsMethod) Authenticate(ctx context.Context, client *api.Client) (retTo if a.nonce == "" { uid, err := uuid.GenerateUUID() if err != nil { - retErr = errwrap.Wrapf("error generating uuid for reauthentication value: {{err}}", err) + retErr = fmt.Errorf("error generating uuid for reauthentication value: %w", err) return } a.nonce = uid @@ -229,7 +228,7 @@ func (a *awsMethod) Authenticate(ctx context.Context, client *api.Client) (retTo var err error data, err = awsutil.GenerateLoginData(a.lastCreds, a.headerValue, a.region, a.logger) if err != nil { - retErr = errwrap.Wrapf("error creating login value: {{err}}", err) + retErr = fmt.Errorf("error creating login value: %w", err) return } } diff --git a/command/agent/auth/azure/azure.go b/command/agent/auth/azure/azure.go index 4b2f7274a3..bc01e561f3 100644 --- a/command/agent/auth/azure/azure.go +++ b/command/agent/auth/azure/azure.go @@ -7,7 +7,6 @@ import ( "io/ioutil" "net/http" - "github.com/hashicorp/errwrap" cleanhttp "github.com/hashicorp/go-cleanhttp" hclog "github.com/hashicorp/go-hclog" "github.com/hashicorp/vault/api" @@ -95,7 +94,7 @@ func (a *azureMethod) Authenticate(ctx context.Context, client *api.Client) (ret err = jsonutil.DecodeJSON(body, &instance) if err != nil { - retErr = errwrap.Wrapf("error parsing instance metadata response: {{err}}", err) + retErr = fmt.Errorf("error parsing instance metadata response: %w", err) return } @@ -112,7 +111,7 @@ func (a *azureMethod) Authenticate(ctx context.Context, client *api.Client) (ret err = jsonutil.DecodeJSON(body, &identity) if err != nil { - retErr = errwrap.Wrapf("error parsing identity metadata response: {{err}}", err) + retErr = fmt.Errorf("error parsing identity metadata response: %w", err) return } @@ -158,7 +157,7 @@ func getMetadataInfo(ctx context.Context, endpoint, resource string) ([]byte, er client := cleanhttp.DefaultClient() resp, err := client.Do(req) if err != nil { - return nil, errwrap.Wrapf(fmt.Sprintf("error fetching metadata from %s: {{err}}", endpoint), err) + return nil, fmt.Errorf("error fetching metadata from %s: %w", endpoint, err) } if resp == nil { @@ -168,7 +167,7 @@ func getMetadataInfo(ctx context.Context, endpoint, resource string) ([]byte, er defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) if err != nil { - return nil, errwrap.Wrapf(fmt.Sprintf("error reading metadata from %s: {{err}}", endpoint), err) + return nil, fmt.Errorf("error reading metadata from %s: %w", endpoint, err) } if resp.StatusCode != http.StatusOK { diff --git a/command/agent/auth/gcp/gcp.go b/command/agent/auth/gcp/gcp.go index 4d36b05e19..3c8053f1b2 100644 --- a/command/agent/auth/gcp/gcp.go +++ b/command/agent/auth/gcp/gcp.go @@ -9,7 +9,6 @@ import ( "net/http" "time" - "github.com/hashicorp/errwrap" cleanhttp "github.com/hashicorp/go-cleanhttp" "github.com/hashicorp/go-gcp-common/gcputil" hclog "github.com/hashicorp/go-hclog" @@ -109,7 +108,7 @@ func NewGCPAuthMethod(conf *auth.AuthConfig) (auth.AuthMethod, error) { if ok { g.jwtExp, err = parseutil.ParseInt(jwtExpRaw) if err != nil { - return nil, errwrap.Wrapf("error parsing 'jwt_raw' into integer: {{err}}", err) + return nil, fmt.Errorf("error parsing 'jwt_raw' into integer: %w", err) } } @@ -130,7 +129,7 @@ func (g *gcpMethod) Authenticate(ctx context.Context, client *api.Client) (retPa { req, err := http.NewRequest("GET", fmt.Sprintf(identityEndpoint, g.serviceAccount), nil) if err != nil { - retErr = errwrap.Wrapf("error creating request: {{err}}", err) + retErr = fmt.Errorf("error creating request: %w", err) return } req = req.WithContext(ctx) @@ -141,7 +140,7 @@ func (g *gcpMethod) Authenticate(ctx context.Context, client *api.Client) (retPa req.URL.RawQuery = q.Encode() resp, err := httpClient.Do(req) if err != nil { - retErr = errwrap.Wrapf("error fetching instance token: {{err}}", err) + retErr = fmt.Errorf("error fetching instance token: %w", err) return } if resp == nil { @@ -151,7 +150,7 @@ func (g *gcpMethod) Authenticate(ctx context.Context, client *api.Client) (retPa defer resp.Body.Close() jwtBytes, err := ioutil.ReadAll(resp.Body) if err != nil { - retErr = errwrap.Wrapf("error reading instance token response body: {{err}}", err) + retErr = fmt.Errorf("error reading instance token response body: %w", err) return } @@ -163,7 +162,7 @@ func (g *gcpMethod) Authenticate(ctx context.Context, client *api.Client) (retPa credentials, tokenSource, err := gcputil.FindCredentials(g.credentials, ctx, iamcredentials.CloudPlatformScope) if err != nil { - retErr = errwrap.Wrapf("could not obtain credentials: {{err}}", err) + retErr = fmt.Errorf("could not obtain credentials: %w", err) return } @@ -193,7 +192,7 @@ func (g *gcpMethod) Authenticate(ctx context.Context, client *api.Client) (retPa } payloadBytes, err := json.Marshal(jwtPayload) if err != nil { - retErr = errwrap.Wrapf("could not convert JWT payload to JSON string: {{err}}", err) + retErr = fmt.Errorf("could not convert JWT payload to JSON string: %w", err) return } @@ -203,14 +202,14 @@ func (g *gcpMethod) Authenticate(ctx context.Context, client *api.Client) (retPa iamClient, err := iamcredentials.New(httpClient) if err != nil { - retErr = errwrap.Wrapf("could not create IAM client: {{err}}", err) + retErr = fmt.Errorf("could not create IAM client: %w", err) return } resourceName := fmt.Sprintf("projects/-/serviceAccounts/%s", serviceAccount) resp, err := iamClient.Projects.ServiceAccounts.SignJwt(resourceName, jwtReq).Do() if err != nil { - retErr = errwrap.Wrapf(fmt.Sprintf("unable to sign JWT for %s using given Vault credentials: {{err}}", resourceName), err) + retErr = fmt.Errorf("unable to sign JWT for %s using given Vault credentials: %w", resourceName, err) return } diff --git a/command/agent/auth/kubernetes/kubernetes.go b/command/agent/auth/kubernetes/kubernetes.go index 8b35b30ae6..c30f3cb5a6 100644 --- a/command/agent/auth/kubernetes/kubernetes.go +++ b/command/agent/auth/kubernetes/kubernetes.go @@ -10,7 +10,6 @@ import ( "os" "strings" - "github.com/hashicorp/errwrap" hclog "github.com/hashicorp/go-hclog" "github.com/hashicorp/vault/api" "github.com/hashicorp/vault/command/agent/auth" @@ -78,7 +77,7 @@ func (k *kubernetesMethod) Authenticate(ctx context.Context, client *api.Client) jwtString, err := k.readJWT() if err != nil { - return "", nil, nil, errwrap.Wrapf("error reading JWT with Kubernetes Auth: {{err}}", err) + return "", nil, nil, fmt.Errorf("error reading JWT with Kubernetes Auth: %w", err) } return fmt.Sprintf("%s/login", k.mountPath), nil, map[string]interface{}{ diff --git a/command/agent/cache/handler.go b/command/agent/cache/handler.go index a63d32a79c..73062df41f 100644 --- a/command/agent/cache/handler.go +++ b/command/agent/cache/handler.go @@ -12,7 +12,6 @@ import ( "net/http" "time" - "github.com/hashicorp/errwrap" hclog "github.com/hashicorp/go-hclog" "github.com/hashicorp/vault/api" "github.com/hashicorp/vault/command/agent/sink" @@ -60,14 +59,14 @@ func Handler(ctx context.Context, logger hclog.Logger, proxier Proxier, inmemSin w.WriteHeader(resp.Response.StatusCode) io.Copy(w, resp.Response.Body) } else { - logical.RespondError(w, http.StatusInternalServerError, errwrap.Wrapf("failed to get the response: {{err}}", err)) + logical.RespondError(w, http.StatusInternalServerError, fmt.Errorf("failed to get the response: %w", err)) } return } err = processTokenLookupResponse(ctx, logger, inmemSink, req, resp) if err != nil { - logical.RespondError(w, http.StatusInternalServerError, errwrap.Wrapf("failed to process token lookup response: {{err}}", err)) + logical.RespondError(w, http.StatusInternalServerError, fmt.Errorf("failed to process token lookup response: %w", err)) return } diff --git a/command/agent/cache/lease_cache.go b/command/agent/cache/lease_cache.go index 0a68692134..5723418648 100644 --- a/command/agent/cache/lease_cache.go +++ b/command/agent/cache/lease_cache.go @@ -16,7 +16,6 @@ import ( "sync" "time" - "github.com/hashicorp/errwrap" hclog "github.com/hashicorp/go-hclog" "github.com/hashicorp/vault/api" "github.com/hashicorp/vault/command/agent/cache/cacheboltdb" @@ -577,7 +576,7 @@ func (c *LeaseCache) HandleCacheClear(ctx context.Context) http.Handler { if err == io.EOF { err = errors.New("empty JSON provided") } - logical.RespondError(w, http.StatusBadRequest, errwrap.Wrapf("failed to parse JSON input: {{err}}", err)) + logical.RespondError(w, http.StatusBadRequest, fmt.Errorf("failed to parse JSON input: %w", err)) return } @@ -586,7 +585,7 @@ func (c *LeaseCache) HandleCacheClear(ctx context.Context) http.Handler { in, err := parseCacheClearInput(req) if err != nil { c.logger.Error("unable to parse clear input", "error", err) - logical.RespondError(w, http.StatusBadRequest, errwrap.Wrapf("failed to parse clear input: {{err}}", err)) + logical.RespondError(w, http.StatusBadRequest, fmt.Errorf("failed to parse clear input: %w", err)) return } @@ -597,7 +596,7 @@ func (c *LeaseCache) HandleCacheClear(ctx context.Context) http.Handler { if err == errInvalidType { httpStatus = http.StatusBadRequest } - logical.RespondError(w, httpStatus, errwrap.Wrapf("failed to clear cache: {{err}}", err)) + logical.RespondError(w, httpStatus, fmt.Errorf("failed to clear cache: %w", err)) return } diff --git a/command/agent/config/config.go b/command/agent/config/config.go index 618e172a51..aa0647bd66 100644 --- a/command/agent/config/config.go +++ b/command/agent/config/config.go @@ -9,7 +9,6 @@ import ( "time" ctconfig "github.com/hashicorp/consul-template/config" - "github.com/hashicorp/errwrap" "github.com/hashicorp/go-multierror" "github.com/hashicorp/hcl" "github.com/hashicorp/hcl/hcl/ast" @@ -171,15 +170,15 @@ func LoadConfig(path string) (*Config, error) { } if err := parseAutoAuth(result, list); err != nil { - return nil, errwrap.Wrapf("error parsing 'auto_auth': {{err}}", err) + return nil, fmt.Errorf("error parsing 'auto_auth': %w", err) } if err := parseCache(result, list); err != nil { - return nil, errwrap.Wrapf("error parsing 'cache':{{err}}", err) + return nil, fmt.Errorf("error parsing 'cache':%w", err) } if err := parseTemplates(result, list); err != nil { - return nil, errwrap.Wrapf("error parsing 'template': {{err}}", err) + return nil, fmt.Errorf("error parsing 'template': %w", err) } if result.Cache != nil { @@ -207,7 +206,7 @@ func LoadConfig(path string) (*Config, error) { err = parseVault(result, list) if err != nil { - return nil, errwrap.Wrapf("error parsing 'vault':{{err}}", err) + return nil, fmt.Errorf("error parsing 'vault':%w", err) } if result.Vault == nil { @@ -263,7 +262,7 @@ func parseVault(result *Config, list *ast.ObjectList) error { } if err := parseRetry(result, subs.List); err != nil { - return errwrap.Wrapf("error parsing 'retry': {{err}}", err) + return fmt.Errorf("error parsing 'retry': %w", err) } return nil @@ -409,14 +408,14 @@ func parseAutoAuth(result *Config, list *ast.ObjectList) error { subList := subs.List if err := parseMethod(result, subList); err != nil { - return errwrap.Wrapf("error parsing 'method': {{err}}", err) + return fmt.Errorf("error parsing 'method': %w", err) } if a.Method == nil { return fmt.Errorf("no 'method' block found") } if err := parseSinks(result, subList); err != nil { - return errwrap.Wrapf("error parsing 'sink' stanzas: {{err}}", err) + return fmt.Errorf("error parsing 'sink' stanzas: %w", err) } if result.AutoAuth.Method.WrapTTL > 0 { diff --git a/command/agent/sink/file/file_sink.go b/command/agent/sink/file/file_sink.go index 0437aae981..f2faf56417 100644 --- a/command/agent/sink/file/file_sink.go +++ b/command/agent/sink/file/file_sink.go @@ -7,7 +7,6 @@ import ( "path/filepath" "strings" - "github.com/hashicorp/errwrap" hclog "github.com/hashicorp/go-hclog" uuid "github.com/hashicorp/go-uuid" "github.com/hashicorp/vault/command/agent/sink" @@ -60,7 +59,7 @@ func NewFileSink(conf *sink.SinkConfig) (sink.Sink, error) { } if err := f.WriteToken(""); err != nil { - return nil, errwrap.Wrapf("error during write check: {{err}}", err) + return nil, fmt.Errorf("error during write check: %w", err) } f.logger.Info("file sink configured", "path", f.path, "mode", f.mode) @@ -79,7 +78,7 @@ func (f *fileSink) WriteToken(token string) error { u, err := uuid.GenerateUUID() if err != nil { - return errwrap.Wrapf("error generating a uuid during write check: {{err}}", err) + return fmt.Errorf("error generating a uuid during write check: %w", err) } targetDir := filepath.Dir(f.path) @@ -88,7 +87,7 @@ func (f *fileSink) WriteToken(token string) error { tmpFile, err := os.OpenFile(filepath.Join(targetDir, fmt.Sprintf("%s.tmp.%s", fileName, tmpSuffix)), os.O_WRONLY|os.O_CREATE, f.mode) if err != nil { - return errwrap.Wrapf(fmt.Sprintf("error opening temp file in dir %s for writing: {{err}}", targetDir), err) + return fmt.Errorf("error opening temp file in dir %s for writing: %w", targetDir, err) } valToWrite := token @@ -101,12 +100,12 @@ func (f *fileSink) WriteToken(token string) error { // Attempt closing and deleting but ignore any error tmpFile.Close() os.Remove(tmpFile.Name()) - return errwrap.Wrapf(fmt.Sprintf("error writing to %s: {{err}}", tmpFile.Name()), err) + return fmt.Errorf("error writing to %s: %w", tmpFile.Name(), err) } err = tmpFile.Close() if err != nil { - return errwrap.Wrapf(fmt.Sprintf("error closing %s: {{err}}", tmpFile.Name()), err) + return fmt.Errorf("error closing %s: %w", tmpFile.Name(), err) } // Now, if we were just doing a write check (blank token), remove the file @@ -114,14 +113,14 @@ func (f *fileSink) WriteToken(token string) error { if token == "" { err = os.Remove(tmpFile.Name()) if err != nil { - return errwrap.Wrapf(fmt.Sprintf("error removing temp file %s during write check: {{err}}", tmpFile.Name()), err) + return fmt.Errorf("error removing temp file %s during write check: %w", tmpFile.Name(), err) } return nil } err = os.Rename(tmpFile.Name(), f.path) if err != nil { - return errwrap.Wrapf(fmt.Sprintf("error renaming temp file %s to target file %s: {{err}}", tmpFile.Name(), f.path), err) + return fmt.Errorf("error renaming temp file %s to target file %s: %w", tmpFile.Name(), f.path, err) } f.logger.Info("token written", "path", f.path) diff --git a/command/agent/sink/sink.go b/command/agent/sink/sink.go index bbbc8edf94..853cc9345f 100644 --- a/command/agent/sink/sink.go +++ b/command/agent/sink/sink.go @@ -3,13 +3,13 @@ package sink import ( "context" "errors" + "fmt" "io/ioutil" "math/rand" "os" "sync/atomic" "time" - "github.com/hashicorp/errwrap" hclog "github.com/hashicorp/go-hclog" "github.com/hashicorp/vault/api" "github.com/hashicorp/vault/helper/dhutil" @@ -177,17 +177,17 @@ func (s *SinkConfig) encryptToken(token string) (string, error) { _, err = os.Lstat(s.DHPath) if err != nil { if !os.IsNotExist(err) { - return "", errwrap.Wrapf("error stat-ing dh parameters file: {{err}}", err) + return "", fmt.Errorf("error stat-ing dh parameters file: %w", err) } return "", errors.New("no dh parameters file found, and no cached pub key") } fileBytes, err := ioutil.ReadFile(s.DHPath) if err != nil { - return "", errwrap.Wrapf("error reading file for dh parameters: {{err}}", err) + return "", fmt.Errorf("error reading file for dh parameters: %w", err) } theirPubKey := new(dhutil.PublicKeyInfo) if err := jsonutil.DecodeJSON(fileBytes, theirPubKey); err != nil { - return "", errwrap.Wrapf("error decoding public key: {{err}}", err) + return "", fmt.Errorf("error decoding public key: %w", err) } if len(theirPubKey.Curve25519PublicKey) == 0 { return "", errors.New("public key is nil") @@ -197,7 +197,7 @@ func (s *SinkConfig) encryptToken(token string) (string, error) { if len(s.cachedPubKey) == 0 { s.cachedPubKey, s.cachedPriKey, err = dhutil.GeneratePublicPrivateKey() if err != nil { - return "", errwrap.Wrapf("error generating pub/pri curve25519 keys: {{err}}", err) + return "", fmt.Errorf("error generating pub/pri curve25519 keys: %w", err) } } resp.Curve25519PublicKey = s.cachedPubKey @@ -205,7 +205,7 @@ func (s *SinkConfig) encryptToken(token string) (string, error) { secret, err := dhutil.GenerateSharedSecret(s.cachedPriKey, s.cachedRemotePubKey) if err != nil { - return "", errwrap.Wrapf("error calculating shared key: {{err}}", err) + return "", fmt.Errorf("error calculating shared key: %w", err) } if s.DeriveKey { aesKey, err = dhutil.DeriveSharedKey(secret, s.cachedPubKey, s.cachedRemotePubKey) @@ -214,7 +214,7 @@ func (s *SinkConfig) encryptToken(token string) (string, error) { } if err != nil { - return "", errwrap.Wrapf("error deriving shared key: {{err}}", err) + return "", fmt.Errorf("error deriving shared key: %w", err) } if len(aesKey) == 0 { return "", errors.New("derived AES key is empty") @@ -222,11 +222,11 @@ func (s *SinkConfig) encryptToken(token string) (string, error) { resp.EncryptedPayload, resp.Nonce, err = dhutil.EncryptAES(aesKey, []byte(token), []byte(s.AAD)) if err != nil { - return "", errwrap.Wrapf("error encrypting with shared key: {{err}}", err) + return "", fmt.Errorf("error encrypting with shared key: %w", err) } m, err := jsonutil.EncodeJSON(resp) if err != nil { - return "", errwrap.Wrapf("error encoding encrypted payload: {{err}}", err) + return "", fmt.Errorf("error encoding encrypted payload: %w", err) } return string(m), nil @@ -235,7 +235,7 @@ func (s *SinkConfig) encryptToken(token string) (string, error) { func (s *SinkConfig) wrapToken(client *api.Client, wrapTTL time.Duration, token string) (string, error) { wrapClient, err := client.Clone() if err != nil { - return "", errwrap.Wrapf("error deriving client for wrapping, not writing out to sink: {{err}})", err) + return "", fmt.Errorf("error deriving client for wrapping, not writing out to sink: %w)", err) } wrapClient.SetToken(token) wrapClient.SetWrappingLookupFunc(func(string, string) string { @@ -245,7 +245,7 @@ func (s *SinkConfig) wrapToken(client *api.Client, wrapTTL time.Duration, token "token": token, }) if err != nil { - return "", errwrap.Wrapf("error wrapping token, not writing out to sink: {{err}})", err) + return "", fmt.Errorf("error wrapping token, not writing out to sink: %w)", err) } if secret == nil { return "", errors.New("nil secret returned, not writing out to sink") @@ -256,7 +256,7 @@ func (s *SinkConfig) wrapToken(client *api.Client, wrapTTL time.Duration, token m, err := jsonutil.EncodeJSON(secret.WrapInfo) if err != nil { - return "", errwrap.Wrapf("error marshaling token, not writing out to sink: {{err}})", err) + return "", fmt.Errorf("error marshaling token, not writing out to sink: %w)", err) } return string(m), nil diff --git a/command/base_helpers.go b/command/base_helpers.go index 1d6b3ce545..5a6339d096 100644 --- a/command/base_helpers.go +++ b/command/base_helpers.go @@ -8,7 +8,6 @@ import ( "strings" "time" - "github.com/hashicorp/errwrap" "github.com/hashicorp/vault/api" kvbuilder "github.com/hashicorp/vault/internalshared/kv-builder" "github.com/kr/text" @@ -285,7 +284,7 @@ func parseFlagFile(raw string) (string, error) { if len(raw) > 0 && raw[0] == '@' { contents, err := ioutil.ReadFile(raw[1:]) if err != nil { - return "", errwrap.Wrapf("error reading file: {{err}}", err) + return "", fmt.Errorf("error reading file: %w", err) } return string(contents), nil diff --git a/command/config/config.go b/command/config/config.go index 4a9916e131..ef0c4adf6d 100644 --- a/command/config/config.go +++ b/command/config/config.go @@ -5,7 +5,6 @@ import ( "io/ioutil" "os" - "github.com/hashicorp/errwrap" "github.com/hashicorp/hcl" "github.com/hashicorp/hcl/hcl/ast" "github.com/hashicorp/vault/sdk/helper/hclutil" @@ -57,7 +56,7 @@ func LoadConfig(path string) (*DefaultConfig, error) { // NOTE: requires HOME env var to be set path, err := homedir.Expand(path) if err != nil { - return nil, errwrap.Wrapf(fmt.Sprintf("error expanding config path %q: {{err}}", path), err) + return nil, fmt.Errorf("error expanding config path %q: %w", path, err) } contents, err := ioutil.ReadFile(path) @@ -67,7 +66,7 @@ func LoadConfig(path string) (*DefaultConfig, error) { conf, err := ParseConfig(string(contents)) if err != nil { - return nil, errwrap.Wrapf(fmt.Sprintf("error parsing config file at %q: {{err}}; ensure that the file is valid; Ansible Vault is known to conflict with it.", path), err) + return nil, fmt.Errorf("error parsing config file at %q: %w; ensure that the file is valid; Ansible Vault is known to conflict with it.", path, err) } return conf, nil diff --git a/command/operator_generate_root.go b/command/operator_generate_root.go index a9f9117feb..eb44fece68 100644 --- a/command/operator_generate_root.go +++ b/command/operator_generate_root.go @@ -9,7 +9,6 @@ import ( "os" "strings" - "github.com/hashicorp/errwrap" uuid "github.com/hashicorp/go-uuid" "github.com/hashicorp/vault/api" "github.com/hashicorp/vault/helper/pgpkeys" @@ -310,7 +309,7 @@ func (c *OperatorGenerateRootCommand) generateOTP(client *api.Client, kind gener default: otp, err := base62.Random(status.OTPLength) if err != nil { - c.UI.Error(errwrap.Wrapf("Error reading random bytes: {{err}}", err).Error()) + c.UI.Error(fmt.Errorf("Error reading random bytes: %w", err).Error()) return "", 2 } @@ -363,13 +362,13 @@ func (c *OperatorGenerateRootCommand) decode(client *api.Client, encoded, otp st default: tokenBytes, err := base64.RawStdEncoding.DecodeString(encoded) if err != nil { - c.UI.Error(errwrap.Wrapf("Error decoding base64'd token: {{err}}", err).Error()) + c.UI.Error(fmt.Errorf("Error decoding base64'd token: %w", err).Error()) return 1 } tokenBytes, err = xor.XORBytes(tokenBytes, []byte(otp)) if err != nil { - c.UI.Error(errwrap.Wrapf("Error xoring token: {{err}}", err).Error()) + c.UI.Error(fmt.Errorf("Error xoring token: %w", err).Error()) return 1 } token = string(tokenBytes) diff --git a/command/operator_migrate.go b/command/operator_migrate.go index c243864e4c..1931584bc3 100644 --- a/command/operator_migrate.go +++ b/command/operator_migrate.go @@ -10,7 +10,6 @@ import ( "strings" "time" - "github.com/hashicorp/errwrap" log "github.com/hashicorp/go-hclog" "github.com/hashicorp/hcl" "github.com/hashicorp/hcl/hcl/ast" @@ -150,24 +149,24 @@ func (c *OperatorMigrateCommand) Run(args []string) int { func (c *OperatorMigrateCommand) migrate(config *migratorConfig) error { from, err := c.newBackend(config.StorageSource.Type, config.StorageSource.Config) if err != nil { - return errwrap.Wrapf("error mounting 'storage_source': {{err}}", err) + return fmt.Errorf("error mounting 'storage_source': %w", err) } if c.flagReset { if err := SetStorageMigration(from, false); err != nil { - return errwrap.Wrapf("error resetting migration lock: {{err}}", err) + return fmt.Errorf("error resetting migration lock: %w", err) } return nil } to, err := c.createDestinationBackend(config.StorageDestination.Type, config.StorageDestination.Config, config) if err != nil { - return errwrap.Wrapf("error mounting 'storage_destination': {{err}}", err) + return fmt.Errorf("error mounting 'storage_destination': %w", err) } migrationStatus, err := CheckStorageMigration(from) if err != nil { - return errwrap.Wrapf("error checking migration status: {{err}}", err) + return fmt.Errorf("error checking migration status: %w", err) } if migrationStatus != nil { @@ -181,7 +180,7 @@ func (c *OperatorMigrateCommand) migrate(config *migratorConfig) error { // it. default: if err := SetStorageMigration(from, true); err != nil { - return errwrap.Wrapf("error setting migration lock: {{err}}", err) + return fmt.Errorf("error setting migration lock: %w", err) } defer SetStorageMigration(from, false) @@ -215,7 +214,7 @@ func (c *OperatorMigrateCommand) migrateAll(ctx context.Context, from physical.B entry, err := from.Get(ctx, path) if err != nil { - return errwrap.Wrapf("error reading entry: {{err}}", err) + return fmt.Errorf("error reading entry: %w", err) } if entry == nil { @@ -223,7 +222,7 @@ func (c *OperatorMigrateCommand) migrateAll(ctx context.Context, from physical.B } if err := to.Put(ctx, entry); err != nil { - return errwrap.Wrapf("error writing entry: {{err}}", err) + return fmt.Errorf("error writing entry: %w", err) } c.logger.Info("copied key", "path", path) return nil @@ -258,7 +257,7 @@ func (c *OperatorMigrateCommand) createDestinationBackend(kind string, conf map[ parsedClusterAddr, err := url.Parse(config.ClusterAddr) if err != nil { - return nil, errwrap.Wrapf("error parsing cluster address: {{err}}", err) + return nil, fmt.Errorf("error parsing cluster address: %w", err) } if err := raftStorage.Bootstrap([]raft.Peer{ { @@ -266,13 +265,13 @@ func (c *OperatorMigrateCommand) createDestinationBackend(kind string, conf map[ Address: parsedClusterAddr.Host, }, }); err != nil { - return nil, errwrap.Wrapf("could not bootstrap clustered storage: {{err}}", err) + return nil, fmt.Errorf("could not bootstrap clustered storage: %w", err) } if err := raftStorage.SetupCluster(context.Background(), raft.SetupOpts{ StartAsLeader: true, }); err != nil { - return nil, errwrap.Wrapf("could not start clustered storage: {{err}}", err) + return nil, fmt.Errorf("could not start clustered storage: %w", err) } } @@ -318,7 +317,7 @@ func (c *OperatorMigrateCommand) loadMigratorConfig(path string) (*migratorConfi } if err := parseStorage(&result, o, stanza); err != nil { - return nil, errwrap.Wrapf("error parsing '%s': {{err}}", err) + return nil, fmt.Errorf("error parsing '%s': %w", stanza, err) } } return &result, nil @@ -355,7 +354,7 @@ func dfsScan(ctx context.Context, source physical.Backend, cb func(ctx context.C if key == "" || strings.HasSuffix(key, "/") { children, err := source.List(ctx, key) if err != nil { - return errwrap.Wrapf("failed to scan for children: {{err}}", err) + return fmt.Errorf("failed to scan for children: %w", err) } sort.Strings(children) diff --git a/command/server.go b/command/server.go index 62aec9a938..bee8f87aec 100644 --- a/command/server.go +++ b/command/server.go @@ -410,7 +410,7 @@ func (c *ServerCommand) parseConfig() (*server.Config, error) { for _, path := range c.flagConfigs { current, err := server.LoadConfig(path) if err != nil { - return nil, errwrap.Wrapf(fmt.Sprintf("error loading configuration from %s: {{err}}", path), err) + return nil, fmt.Errorf("error loading configuration from %s: %w", path, err) } if config == nil { @@ -1650,7 +1650,7 @@ func (c *ServerCommand) enableDev(core *vault.Core, coreConfig *vault.CoreConfig isLeader, _, _, err := core.Leader() if err != nil && err != vault.ErrHANotEnabled { - return nil, errwrap.Wrapf("failed to check active status: {{err}}", err) + return nil, fmt.Errorf("failed to check active status: %w", err) } if err == nil { leaderCount := 5 @@ -1663,7 +1663,7 @@ func (c *ServerCommand) enableDev(core *vault.Core, coreConfig *vault.CoreConfig time.Sleep(1 * time.Second) isLeader, _, _, err = core.Leader() if err != nil { - return nil, errwrap.Wrapf("failed to check active status: {{err}}", err) + return nil, fmt.Errorf("failed to check active status: %w", err) } leaderCount-- } @@ -1685,7 +1685,7 @@ func (c *ServerCommand) enableDev(core *vault.Core, coreConfig *vault.CoreConfig } resp, err := core.HandleRequest(ctx, req) if err != nil { - return nil, errwrap.Wrapf(fmt.Sprintf("failed to create root token with ID %q: {{err}}", coreConfig.DevToken), err) + return nil, fmt.Errorf("failed to create root token with ID %q: %w", coreConfig.DevToken, err) } if resp == nil { return nil, fmt.Errorf("nil response when creating root token with ID %q", coreConfig.DevToken) @@ -1701,7 +1701,7 @@ func (c *ServerCommand) enableDev(core *vault.Core, coreConfig *vault.CoreConfig req.Data = nil resp, err = core.HandleRequest(ctx, req) if err != nil { - return nil, errwrap.Wrapf("failed to revoke initial root token: {{err}}", err) + return nil, fmt.Errorf("failed to revoke initial root token: %w", err) } } @@ -1735,10 +1735,10 @@ func (c *ServerCommand) enableDev(core *vault.Core, coreConfig *vault.CoreConfig } resp, err := core.HandleRequest(ctx, req) if err != nil { - return nil, errwrap.Wrapf("error creating default K/V store: {{err}}", err) + return nil, fmt.Errorf("error creating default K/V store: %w", err) } if resp.IsError() { - return nil, errwrap.Wrapf("failed to create default K/V store: {{err}}", resp.Error()) + return nil, fmt.Errorf("failed to create default K/V store: %w", resp.Error()) } return init, nil @@ -2053,7 +2053,7 @@ func (c *ServerCommand) Reload(lock *sync.RWMutex, reloadFuncs *map[string][]rel for _, relFunc := range relFuncs { if relFunc != nil { if err := relFunc(); err != nil { - reloadErrors = multierror.Append(reloadErrors, errwrap.Wrapf("error encountered reloading listener: {{err}}", err)) + reloadErrors = multierror.Append(reloadErrors, fmt.Errorf("error encountered reloading listener: %w", err)) } } } @@ -2062,7 +2062,7 @@ func (c *ServerCommand) Reload(lock *sync.RWMutex, reloadFuncs *map[string][]rel for _, relFunc := range relFuncs { if relFunc != nil { if err := relFunc(); err != nil { - reloadErrors = multierror.Append(reloadErrors, errwrap.Wrapf(fmt.Sprintf("error encountered reloading file audit device at path %q: {{err}}", strings.TrimPrefix(k, "audit_file|")), err)) + reloadErrors = multierror.Append(reloadErrors, fmt.Errorf("error encountered reloading file audit device at path %q: %w", strings.TrimPrefix(k, "audit_file|"), err)) } } } @@ -2089,7 +2089,7 @@ func (c *ServerCommand) storePidFile(pidPath string) error { // Open the PID file pidFile, err := os.OpenFile(pidPath, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0o644) if err != nil { - return errwrap.Wrapf("could not open pid file: {{err}}", err) + return fmt.Errorf("could not open pid file: %w", err) } defer pidFile.Close() @@ -2097,7 +2097,7 @@ func (c *ServerCommand) storePidFile(pidPath string) error { pid := os.Getpid() _, err = pidFile.WriteString(fmt.Sprintf("%d", pid)) if err != nil { - return errwrap.Wrapf("could not write to pid file: {{err}}", err) + return fmt.Errorf("could not write to pid file: %w", err) } return nil } diff --git a/command/server/config.go b/command/server/config.go index 617af886ff..2626d249b9 100644 --- a/command/server/config.go +++ b/command/server/config.go @@ -12,7 +12,6 @@ import ( "strings" "time" - "github.com/hashicorp/errwrap" "github.com/hashicorp/go-multierror" "github.com/hashicorp/hcl" "github.com/hashicorp/hcl/hcl/ast" @@ -464,24 +463,24 @@ func ParseConfig(d, source string) (*Config, error) { // Look for storage but still support old backend if o := list.Filter("storage"); len(o.Items) > 0 { if err := ParseStorage(result, o, "storage"); err != nil { - return nil, errwrap.Wrapf("error parsing 'storage': {{err}}", err) + return nil, fmt.Errorf("error parsing 'storage': %w", err) } } else { if o := list.Filter("backend"); len(o.Items) > 0 { if err := ParseStorage(result, o, "backend"); err != nil { - return nil, errwrap.Wrapf("error parsing 'backend': {{err}}", err) + return nil, fmt.Errorf("error parsing 'backend': %w", err) } } } if o := list.Filter("ha_storage"); len(o.Items) > 0 { if err := parseHAStorage(result, o, "ha_storage"); err != nil { - return nil, errwrap.Wrapf("error parsing 'ha_storage': {{err}}", err) + return nil, fmt.Errorf("error parsing 'ha_storage': %w", err) } } else { if o := list.Filter("ha_backend"); len(o.Items) > 0 { if err := parseHAStorage(result, o, "ha_backend"); err != nil { - return nil, errwrap.Wrapf("error parsing 'ha_backend': {{err}}", err) + return nil, fmt.Errorf("error parsing 'ha_backend': %w", err) } } } @@ -489,13 +488,13 @@ func ParseConfig(d, source string) (*Config, error) { // Parse service discovery if o := list.Filter("service_registration"); len(o.Items) > 0 { if err := parseServiceRegistration(result, o, "service_registration"); err != nil { - return nil, errwrap.Wrapf("error parsing 'service_registration': {{err}}", err) + return nil, fmt.Errorf("error parsing 'service_registration': %w", err) } } entConfig := &(result.entConfig) if err := entConfig.parseConfig(list); err != nil { - return nil, errwrap.Wrapf("error parsing enterprise config: {{err}}", err) + return nil, fmt.Errorf("error parsing enterprise config: %w", err) } // Remove all unused keys from Config that were satisfied by SharedConfig. @@ -563,7 +562,7 @@ func LoadConfigDir(dir string) (*Config, error) { for _, f := range files { config, err := LoadConfigFile(f) if err != nil { - return nil, errwrap.Wrapf(fmt.Sprintf("error loading %q: {{err}}", f), err) + return nil, fmt.Errorf("error loading %q: %w", f, err) } if result == nil { diff --git a/command/server/listener.go b/command/server/listener.go index eca313d72d..248df52957 100644 --- a/command/server/listener.go +++ b/command/server/listener.go @@ -6,7 +6,6 @@ import ( "io" "net" - "github.com/hashicorp/errwrap" // We must import sha512 so that it registers with the runtime so that // certificates that use it can be parsed. @@ -48,7 +47,7 @@ func listenerWrapProxy(ln net.Listener, l *configutil.Listener) (net.Listener, e newLn, err := proxyutil.WrapInProxyProto(ln, proxyProtoConfig) if err != nil { - return nil, errwrap.Wrapf("failed configuring PROXY protocol wrapper: {{err}}", err) + return nil, fmt.Errorf("failed configuring PROXY protocol wrapper: %w", err) } return newLn, nil diff --git a/command/ssh.go b/command/ssh.go index 7e01882630..e5e5af373e 100644 --- a/command/ssh.go +++ b/command/ssh.go @@ -11,7 +11,6 @@ import ( "strings" "syscall" - "github.com/hashicorp/errwrap" "github.com/hashicorp/vault/api" "github.com/hashicorp/vault/builtin/logical/ssh" "github.com/mitchellh/cli" @@ -751,10 +750,10 @@ func (c *SSHCommand) defaultRole(mountPoint, ip string) (string, error) { } secret, err := c.client.Logical().Write(mountPoint+"/lookup", data) if err != nil { - return "", errwrap.Wrapf(fmt.Sprintf("error finding roles for IP %q: {{err}}", ip), err) + return "", fmt.Errorf("error finding roles for IP %q: %w", ip, err) } if secret == nil || secret.Data == nil { - return "", errwrap.Wrapf(fmt.Sprintf("error finding roles for IP %q: {{err}}", ip), err) + return "", fmt.Errorf("error finding roles for IP %q: %w", ip, err) } if secret.Data["roles"] == nil { diff --git a/command/token/helper_external.go b/command/token/helper_external.go index edd95d5e1a..102bc1cff4 100644 --- a/command/token/helper_external.go +++ b/command/token/helper_external.go @@ -8,8 +8,6 @@ import ( "path/filepath" "runtime" "strings" - - "github.com/hashicorp/errwrap" ) // ExternalTokenHelperPath takes the configured path to a helper and expands it to @@ -64,7 +62,7 @@ func (h *ExternalTokenHelper) Erase() error { return err } if output, err := cmd.CombinedOutput(); err != nil { - return errwrap.Wrapf(fmt.Sprintf("%q: {{err}}", string(output)), err) + return fmt.Errorf("%q: %w", string(output), err) } return nil } @@ -79,7 +77,7 @@ func (h *ExternalTokenHelper) Get() (string, error) { cmd.Stdout = &buf cmd.Stderr = &stderr if err := cmd.Run(); err != nil { - return "", errwrap.Wrapf(fmt.Sprintf("%q: {{err}}", stderr.String()), err) + return "", fmt.Errorf("%q: %w", stderr.String(), err) } return buf.String(), nil @@ -94,7 +92,7 @@ func (h *ExternalTokenHelper) Store(v string) error { } cmd.Stdin = buf if output, err := cmd.CombinedOutput(); err != nil { - return errwrap.Wrapf(fmt.Sprintf("%q: {{err}}", string(output)), err) + return fmt.Errorf("%q: %w", string(output), err) } return nil