diff --git a/api/client.go b/api/client.go index ff18b5b68..53655fa6d 100644 --- a/api/client.go +++ b/api/client.go @@ -160,7 +160,7 @@ func (c *Config) ConfigureTLS(t *TLSConfig) error { } foundClientCert = true case t.ClientCert != "" || t.ClientKey != "": - return fmt.Errorf("Both client cert and client key must be provided") + return fmt.Errorf("both client cert and client key must be provided") } if t.CACert != "" || t.CAPath != "" { @@ -232,7 +232,7 @@ func (c *Config) ReadEnvironment() error { if t := os.Getenv(EnvVaultClientTimeout); t != "" { clientTimeout, err := parseutil.ParseDurationSecond(t) if err != nil { - return fmt.Errorf("Could not parse %s", EnvVaultClientTimeout) + return fmt.Errorf("could not parse %q", EnvVaultClientTimeout) } envClientTimeout = clientTimeout } @@ -240,7 +240,7 @@ func (c *Config) ReadEnvironment() error { var err error envInsecure, err = strconv.ParseBool(v) if err != nil { - return fmt.Errorf("Could not parse VAULT_SKIP_VERIFY") + return fmt.Errorf("could not parse VAULT_SKIP_VERIFY") } } if v := os.Getenv(EnvVaultTLSServerName); v != "" { @@ -348,7 +348,7 @@ func (c *Client) SetAddress(addr string) error { var err error if c.addr, err = url.Parse(addr); err != nil { - return fmt.Errorf("failed to set address: %v", err) + return errwrap.Wrapf("failed to set address: {{err}}", err) } return nil @@ -539,7 +539,7 @@ func (c *Client) RawRequest(r *Request) (*Response, error) { return !unicode.IsPrint(c) }) if idx != -1 { - return nil, fmt.Errorf("Configured Vault token contains non-printable characters and cannot be used.") + return nil, fmt.Errorf("configured Vault token contains non-printable characters and cannot be used") } redirectCount := 0 @@ -560,8 +560,8 @@ START: } if err != nil { if strings.Contains(err.Error(), "tls: oversized") { - err = fmt.Errorf( - "%s\n\n"+ + err = errwrap.Wrapf( + "{{err}}\n\n"+ "This error usually means that the server is running with TLS disabled\n"+ "but the client is configured to use TLS. Please either enable TLS\n"+ "on the server or run the client with -address set to an address\n"+ diff --git a/api/logical.go b/api/logical.go index 84437391b..d5e5afae8 100644 --- a/api/logical.go +++ b/api/logical.go @@ -7,6 +7,7 @@ import ( "net/http" "os" + "github.com/hashicorp/errwrap" "github.com/hashicorp/vault/helper/jsonutil" ) @@ -213,10 +214,10 @@ func (c *Logical) Unwrap(wrappingToken string) (*Secret, error) { secret, err := c.Read(wrappedResponseLocation) if err != nil { - return nil, fmt.Errorf("error reading %s: %s", wrappedResponseLocation, err) + return nil, errwrap.Wrapf(fmt.Sprintf("error reading %q: {{err}}", wrappedResponseLocation), err) } if secret == nil { - return nil, fmt.Errorf("no value found at %s", wrappedResponseLocation) + return nil, fmt.Errorf("no value found at %q", wrappedResponseLocation) } if secret.Data == nil { return nil, fmt.Errorf("\"data\" not found in wrapping response") @@ -228,7 +229,7 @@ func (c *Logical) Unwrap(wrappingToken string) (*Secret, error) { wrappedSecret := new(Secret) buf := bytes.NewBufferString(secret.Data["response"].(string)) if err := jsonutil.DecodeJSONFromReader(buf, wrappedSecret); err != nil { - return nil, fmt.Errorf("error unmarshalling wrapped secret: %s", err) + return nil, errwrap.Wrapf("error unmarshalling wrapped secret: {{err}}", err) } return wrappedSecret, nil diff --git a/api/secret.go b/api/secret.go index 489165162..4675f4ac6 100644 --- a/api/secret.go +++ b/api/secret.go @@ -5,6 +5,7 @@ import ( "io" "time" + "github.com/hashicorp/errwrap" "github.com/hashicorp/vault/helper/jsonutil" "github.com/hashicorp/vault/helper/parseutil" ) @@ -190,7 +191,7 @@ func (s *Secret) TokenIsRenewable() (bool, error) { renewable, err := parseutil.ParseBool(s.Data["renewable"]) if err != nil { - return false, fmt.Errorf("could not convert renewable value to a boolean: %v", err) + return false, errwrap.Wrapf("could not convert renewable value to a boolean: {{err}}", err) } return renewable, nil diff --git a/api/ssh_agent.go b/api/ssh_agent.go index 729fd99c4..c4e59a471 100644 --- a/api/ssh_agent.go +++ b/api/ssh_agent.go @@ -7,6 +7,7 @@ import ( "io/ioutil" "os" + "github.com/hashicorp/errwrap" "github.com/hashicorp/go-cleanhttp" "github.com/hashicorp/go-multierror" "github.com/hashicorp/go-rootcerts" @@ -141,12 +142,12 @@ func LoadSSHHelperConfig(path string) (*SSHHelperConfig, error) { func ParseSSHHelperConfig(contents string) (*SSHHelperConfig, error) { root, err := hcl.Parse(string(contents)) if err != nil { - return nil, fmt.Errorf("ssh_helper: error parsing config: %s", err) + return nil, errwrap.Wrapf("error parsing config: {{err}}", err) } list, ok := root.Node.(*ast.ObjectList) if !ok { - return nil, fmt.Errorf("ssh_helper: error parsing config: file doesn't contain a root object") + return nil, fmt.Errorf("error parsing config: file doesn't contain a root object") } valid := []string{ @@ -170,7 +171,7 @@ func ParseSSHHelperConfig(contents string) (*SSHHelperConfig, error) { } if c.VaultAddr == "" { - return nil, fmt.Errorf("ssh_helper: missing config 'vault_addr'") + return nil, fmt.Errorf("missing config 'vault_addr'") } return &c, nil } @@ -248,8 +249,7 @@ func checkHCLKeys(node ast.Node, valid []string) error { for _, item := range list.Items { key := item.Keys[0].Token.Value().(string) if _, ok := validMap[key]; !ok { - result = multierror.Append(result, fmt.Errorf( - "invalid key '%s' on line %d", key, item.Assign.Line)) + result = multierror.Append(result, fmt.Errorf("invalid key %q on line %d", key, item.Assign.Line)) } } diff --git a/builtin/audit/file/backend.go b/builtin/audit/file/backend.go index bd69c3e2b..281c1de07 100644 --- a/builtin/audit/file/backend.go +++ b/builtin/audit/file/backend.go @@ -10,6 +10,7 @@ import ( "strings" "sync" + "github.com/hashicorp/errwrap" "github.com/hashicorp/vault/audit" "github.com/hashicorp/vault/helper/salt" "github.com/hashicorp/vault/logical" @@ -46,7 +47,7 @@ func Factory(ctx context.Context, conf *audit.BackendConfig) (audit.Backend, err switch format { case "json", "jsonx": default: - return nil, fmt.Errorf("unknown format type %s", format) + return nil, fmt.Errorf("unknown format type %q", format) } // Check if hashing of accessor is disabled @@ -113,7 +114,7 @@ func Factory(ctx context.Context, conf *audit.BackendConfig) (audit.Backend, err // otherwise it will be too late to catch later without problems // (ref: https://github.com/hashicorp/vault/issues/550) if err := b.open(); err != nil { - return nil, fmt.Errorf("sanity check failed; unable to open %s for writing: %v", path, err) + return nil, errwrap.Wrapf(fmt.Sprintf("sanity check failed; unable to open %q for writing: {{err}}", path), err) } } diff --git a/builtin/audit/socket/backend.go b/builtin/audit/socket/backend.go index e0d5b2271..64e499b46 100644 --- a/builtin/audit/socket/backend.go +++ b/builtin/audit/socket/backend.go @@ -50,7 +50,7 @@ func Factory(ctx context.Context, conf *audit.BackendConfig) (audit.Backend, err switch format { case "json", "jsonx": default: - return nil, fmt.Errorf("unknown format type %s", format) + return nil, fmt.Errorf("unknown format type %q", format) } // Check if hashing of accessor is disabled diff --git a/builtin/audit/syslog/backend.go b/builtin/audit/syslog/backend.go index 68d8a361a..ed707217a 100644 --- a/builtin/audit/syslog/backend.go +++ b/builtin/audit/syslog/backend.go @@ -40,7 +40,7 @@ func Factory(ctx context.Context, conf *audit.BackendConfig) (audit.Backend, err switch format { case "json", "jsonx": default: - return nil, fmt.Errorf("unknown format type %s", format) + return nil, fmt.Errorf("unknown format type %q", format) } // Check if hashing of accessor is disabled diff --git a/builtin/credential/app-id/path_login.go b/builtin/credential/app-id/path_login.go index 584fe4ea9..9fc86b485 100644 --- a/builtin/credential/app-id/path_login.go +++ b/builtin/credential/app-id/path_login.go @@ -9,6 +9,7 @@ import ( "net" "strings" + "github.com/hashicorp/errwrap" "github.com/hashicorp/vault/helper/policyutil" "github.com/hashicorp/vault/logical" "github.com/hashicorp/vault/logical/framework" @@ -168,7 +169,7 @@ func (b *backend) verifyCredentials(ctx context.Context, req *logical.Request, a if raw, ok := appsMap["cidr_block"]; ok { _, cidr, err := net.ParseCIDR(raw.(string)) if err != nil { - return "", nil, fmt.Errorf("invalid restriction cidr: %s", err) + return "", nil, errwrap.Wrapf("invalid restriction cidr: {{err}}", err) } var addr string @@ -187,7 +188,7 @@ func (b *backend) verifyCredentials(ctx context.Context, req *logical.Request, a apps, ok := appsRaw.(string) if !ok { - return "", nil, fmt.Errorf("internal error: mapping is not a string") + return "", nil, fmt.Errorf("mapping is not a string") } // Verify that the app is in the list diff --git a/builtin/credential/approle/path_login.go b/builtin/credential/approle/path_login.go index db8dbb4fd..722f5ea7a 100644 --- a/builtin/credential/approle/path_login.go +++ b/builtin/credential/approle/path_login.go @@ -101,10 +101,10 @@ func (b *backend) pathLoginRenew(ctx context.Context, req *logical.Request, data // Ensure that the Role still exists. role, err := b.roleEntry(ctx, req.Storage, strings.ToLower(roleName)) if err != nil { - return nil, fmt.Errorf("failed to validate role %s during renewal:%s", roleName, err) + return nil, errwrap.Wrapf(fmt.Sprintf("failed to validate role %q during renewal: {{err}}", roleName), err) } if role == nil { - return nil, fmt.Errorf("role %s does not exist during renewal", roleName) + return nil, fmt.Errorf("role %q does not exist during renewal", roleName) } resp := &logical.Response{Auth: req.Auth} diff --git a/builtin/credential/approle/path_role.go b/builtin/credential/approle/path_role.go index 9c44986a4..b0d1e8314 100644 --- a/builtin/credential/approle/path_role.go +++ b/builtin/credential/approle/path_role.go @@ -7,6 +7,7 @@ import ( "time" "github.com/fatih/structs" + "github.com/hashicorp/errwrap" "github.com/hashicorp/go-uuid" "github.com/hashicorp/vault/helper/cidrutil" "github.com/hashicorp/vault/helper/consts" @@ -579,7 +580,7 @@ func (b *backend) pathRoleSecretIDList(ctx context.Context, req *logical.Request roleNameHMAC, err := createHMAC(role.HMACKey, roleName) if err != nil { - return nil, fmt.Errorf("failed to create HMAC of role_name: %v", err) + return nil, errwrap.Wrapf("failed to create HMAC of role_name: {{err}}", err) } // Listing works one level at a time. Get the first level of data @@ -673,7 +674,7 @@ func (b *backend) setRoleEntry(ctx context.Context, s logical.Storage, roleName // Check if the index from the role_id to role already exists roleIDIndex, err := b.roleIDEntry(ctx, s, role.RoleID) if err != nil { - return fmt.Errorf("failed to read role_id index: %v", err) + return errwrap.Wrapf("failed to read role_id index: {{err}}", err) } // If the entry exists, make sure that it belongs to the current role @@ -768,7 +769,7 @@ func (b *backend) pathRoleCreateUpdate(ctx context.Context, req *logical.Request if role == nil && req.Operation == logical.CreateOperation { hmacKey, err := uuid.GenerateUUID() if err != nil { - return nil, fmt.Errorf("failed to create role_id: %v\n", err) + return nil, errwrap.Wrapf("failed to create role_id: {{err}}", err) } role = &roleStorageEntry{ HMACKey: hmacKey, @@ -784,7 +785,7 @@ func (b *backend) pathRoleCreateUpdate(ctx context.Context, req *logical.Request } else if req.Operation == logical.CreateOperation { roleID, err := uuid.GenerateUUID() if err != nil { - return nil, fmt.Errorf("failed to generate role_id: %v\n", err) + return nil, errwrap.Wrapf("failed to generate role_id: {{err}}", err) } role.RoleID = roleID } @@ -807,7 +808,7 @@ func (b *backend) pathRoleCreateUpdate(ctx context.Context, req *logical.Request if len(role.BoundCIDRList) != 0 { valid, err := cidrutil.ValidateCIDRListSlice(role.BoundCIDRList) if err != nil { - return nil, fmt.Errorf("failed to validate CIDR blocks: %v", err) + return nil, errwrap.Wrapf("failed to validate CIDR blocks: {{err}}", err) } if !valid { return logical.ErrorResponse("invalid CIDR blocks"), nil @@ -953,7 +954,7 @@ func (b *backend) pathRoleRead(ctx context.Context, req *logical.Request, data * }) if err != nil { lockRelease() - return nil, fmt.Errorf("failed to create secondary index for role_id %q: %v", role.RoleID, err) + return nil, errwrap.Wrapf(fmt.Sprintf("failed to create secondary index for role_id %q: {{err}}", role.RoleID), err) } resp.AddWarning("Role identifier was missing an index back to role name. A new index has been added. Please report this observation.") } @@ -985,12 +986,12 @@ func (b *backend) pathRoleDelete(ctx context.Context, req *logical.Request, data // Just before the role is deleted, remove all the SecretIDs issued as part of the role. if err = b.flushRoleSecrets(ctx, req.Storage, roleName, role.HMACKey); err != nil { - return nil, fmt.Errorf("failed to invalidate the secrets belonging to role %q: %v", roleName, err) + return nil, errwrap.Wrapf(fmt.Sprintf("failed to invalidate the secrets belonging to role %q: {{err}}", roleName), err) } // Delete the reverse mapping from RoleID to the role if err = b.roleIDEntryDelete(ctx, req.Storage, role.RoleID); err != nil { - return nil, fmt.Errorf("failed to delete the mapping from RoleID to role %q: %v", roleName, err) + return nil, errwrap.Wrapf(fmt.Sprintf("failed to delete the mapping from RoleID to role %q: {{err}}", roleName), err) } // After deleting the SecretIDs and the RoleID, delete the role itself @@ -1033,13 +1034,13 @@ func (b *backend) pathRoleSecretIDLookupUpdate(ctx context.Context, req *logical // Create the HMAC of the secret ID using the per-role HMAC key secretIDHMAC, err := createHMAC(role.HMACKey, secretID) if err != nil { - return nil, fmt.Errorf("failed to create HMAC of secret_id: %v", err) + return nil, errwrap.Wrapf("failed to create HMAC of secret_id: {{err}}", err) } // Create the HMAC of the roleName using the per-role HMAC key roleNameHMAC, err := createHMAC(role.HMACKey, roleName) if err != nil { - return nil, fmt.Errorf("failed to create HMAC of role_name: %v", err) + return nil, errwrap.Wrapf("failed to create HMAC of role_name: {{err}}", err) } // Create the index at which the secret_id would've been stored @@ -1110,12 +1111,12 @@ func (b *backend) pathRoleSecretIDDestroyUpdateDelete(ctx context.Context, req * secretIDHMAC, err := createHMAC(role.HMACKey, secretID) if err != nil { - return nil, fmt.Errorf("failed to create HMAC of secret_id: %v", err) + return nil, errwrap.Wrapf("failed to create HMAC of secret_id: {{err}}", err) } roleNameHMAC, err := createHMAC(role.HMACKey, roleName) if err != nil { - return nil, fmt.Errorf("failed to create HMAC of role_name: %v", err) + return nil, errwrap.Wrapf("failed to create HMAC of role_name: {{err}}", err) } entryIndex := fmt.Sprintf("secret_id/%s/%s", roleNameHMAC, secretIDHMAC) @@ -1140,7 +1141,7 @@ func (b *backend) pathRoleSecretIDDestroyUpdateDelete(ctx context.Context, req * // Delete the storage entry that corresponds to the SecretID if err := req.Storage.Delete(ctx, entryIndex); err != nil { - return nil, fmt.Errorf("failed to delete secret_id: %v", err) + return nil, errwrap.Wrapf("failed to delete secret_id: {{err}}", err) } return nil, nil @@ -1180,12 +1181,12 @@ func (b *backend) pathRoleSecretIDAccessorLookupUpdate(ctx context.Context, req return nil, err } if accessorEntry == nil { - return nil, fmt.Errorf("failed to find accessor entry for secret_id_accessor: %q\n", secretIDAccessor) + return nil, fmt.Errorf("failed to find accessor entry for secret_id_accessor: %q", secretIDAccessor) } roleNameHMAC, err := createHMAC(role.HMACKey, roleName) if err != nil { - return nil, fmt.Errorf("failed to create HMAC of role_name: %v", err) + return nil, errwrap.Wrapf("failed to create HMAC of role_name: {{err}}", err) } entryIndex := fmt.Sprintf("secret_id/%s/%s", roleNameHMAC, accessorEntry.SecretIDHMAC) @@ -1221,12 +1222,12 @@ func (b *backend) pathRoleSecretIDAccessorDestroyUpdateDelete(ctx context.Contex return nil, err } if accessorEntry == nil { - return nil, fmt.Errorf("failed to find accessor entry for secret_id_accessor: %q\n", secretIDAccessor) + return nil, fmt.Errorf("failed to find accessor entry for secret_id_accessor: %q", secretIDAccessor) } roleNameHMAC, err := createHMAC(role.HMACKey, roleName) if err != nil { - return nil, fmt.Errorf("failed to create HMAC of role_name: %v", err) + return nil, errwrap.Wrapf("failed to create HMAC of role_name: {{err}}", err) } entryIndex := fmt.Sprintf("secret_id/%s/%s", roleNameHMAC, accessorEntry.SecretIDHMAC) @@ -1242,7 +1243,7 @@ func (b *backend) pathRoleSecretIDAccessorDestroyUpdateDelete(ctx context.Contex // Delete the storage entry that corresponds to the SecretID if err := req.Storage.Delete(ctx, entryIndex); err != nil { - return nil, fmt.Errorf("failed to delete secret_id: %v", err) + return nil, errwrap.Wrapf("failed to delete secret_id: {{err}}", err) } return nil, nil @@ -1274,7 +1275,7 @@ func (b *backend) pathRoleBoundCIDRListUpdate(ctx context.Context, req *logical. valid, err := cidrutil.ValidateCIDRListSlice(role.BoundCIDRList) if err != nil { - return nil, fmt.Errorf("failed to validate CIDR blocks: %v", err) + return nil, errwrap.Wrapf("failed to validate CIDR blocks: {{err}}", err) } if !valid { return logical.ErrorResponse("failed to validate CIDR blocks"), nil @@ -1978,7 +1979,7 @@ func (b *backend) pathRoleTokenMaxTTLDelete(ctx context.Context, req *logical.Re func (b *backend) pathRoleSecretIDUpdate(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { secretID, err := uuid.GenerateUUID() if err != nil { - return nil, fmt.Errorf("failed to generate secret_id: %v", err) + return nil, errwrap.Wrapf("failed to generate secret_id: {{err}}", err) } return b.handleRoleSecretIDCommon(ctx, req, data, secretID) } @@ -2019,7 +2020,7 @@ func (b *backend) handleRoleSecretIDCommon(ctx context.Context, req *logical.Req if len(secretIDCIDRs) != 0 { valid, err := cidrutil.ValidateCIDRListSlice(secretIDCIDRs) if err != nil { - return nil, fmt.Errorf("failed to validate CIDR blocks: %v", err) + return nil, errwrap.Wrapf("failed to validate CIDR blocks: {{err}}", err) } if !valid { return logical.ErrorResponse("failed to validate CIDR blocks"), nil @@ -2047,7 +2048,7 @@ func (b *backend) handleRoleSecretIDCommon(ctx context.Context, req *logical.Req } if secretIDStorage, err = b.registerSecretIDEntry(ctx, req.Storage, roleName, secretID, role.HMACKey, secretIDStorage); err != nil { - return nil, fmt.Errorf("failed to store secret_id: %v", err) + return nil, errwrap.Wrapf("failed to store secret_id: {{err}}", err) } return &logical.Response{ @@ -2091,7 +2092,7 @@ func (b *backend) setRoleIDEntry(ctx context.Context, s logical.Storage, roleID // roleIDEntry is used to read the storage entry that maps RoleID to Role func (b *backend) roleIDEntry(ctx context.Context, s logical.Storage, roleID string) (*roleIDStorageEntry, error) { if roleID == "" { - return nil, fmt.Errorf("missing roleID") + return nil, fmt.Errorf("missing role id") } lock := b.roleIDLock(roleID) @@ -2121,7 +2122,7 @@ func (b *backend) roleIDEntry(ctx context.Context, s logical.Storage, roleID str // RoleID to the Role itself. func (b *backend) roleIDEntryDelete(ctx context.Context, s logical.Storage, roleID string) error { if roleID == "" { - return fmt.Errorf("missing roleID") + return fmt.Errorf("missing role id") } lock := b.roleIDLock(roleID) diff --git a/builtin/credential/approle/path_tidy_user_id.go b/builtin/credential/approle/path_tidy_user_id.go index 23a380153..27e0d0300 100644 --- a/builtin/credential/approle/path_tidy_user_id.go +++ b/builtin/credential/approle/path_tidy_user_id.go @@ -6,6 +6,7 @@ import ( "sync/atomic" "time" + "github.com/hashicorp/errwrap" "github.com/hashicorp/go-multierror" "github.com/hashicorp/vault/logical" "github.com/hashicorp/vault/logical/framework" @@ -65,18 +66,18 @@ func (b *backend) tidySecretID(ctx context.Context, s logical.Storage) error { secretIDEntry, err := s.Get(ctx, entryIndex) if err != nil { lock.Unlock() - return fmt.Errorf("error fetching SecretID %s: %s", secretIDHMAC, err) + return errwrap.Wrapf(fmt.Sprintf("error fetching SecretID %q: {{err}}", secretIDHMAC), err) } if secretIDEntry == nil { - result = multierror.Append(result, fmt.Errorf("entry for SecretID %s is nil", secretIDHMAC)) + result = multierror.Append(result, fmt.Errorf("entry for SecretID %q is nil", secretIDHMAC)) lock.Unlock() continue } if secretIDEntry.Value == nil || len(secretIDEntry.Value) == 0 { lock.Unlock() - return fmt.Errorf("found entry for SecretID %s but actual SecretID is empty", secretIDHMAC) + return fmt.Errorf("found entry for SecretID %q but actual SecretID is empty", secretIDHMAC) } var result secretIDStorageEntry @@ -96,7 +97,7 @@ func (b *backend) tidySecretID(ctx context.Context, s logical.Storage) error { if err := s.Delete(ctx, entryIndex); err != nil { lock.Unlock() - return fmt.Errorf("error deleting SecretID %s from storage: %s", secretIDHMAC, err) + return errwrap.Wrapf(fmt.Sprintf("error deleting SecretID %q from storage: {{err}}", secretIDHMAC), err) } } diff --git a/builtin/credential/approle/validation.go b/builtin/credential/approle/validation.go index 475692983..955eae81e 100644 --- a/builtin/credential/approle/validation.go +++ b/builtin/credential/approle/validation.go @@ -76,7 +76,7 @@ func (b *backend) validateRoleID(ctx context.Context, s logical.Storage, roleID return nil, "", err } if roleIDIndex == nil { - return nil, "", fmt.Errorf("invalid role_id %q\n", roleID) + return nil, "", fmt.Errorf("invalid role_id %q", roleID) } lock := b.roleLock(roleIDIndex.Name) @@ -160,12 +160,12 @@ func (b *backend) validateBindSecretID(ctx context.Context, req *logical.Request hmacKey string, roleBoundCIDRList []string) (bool, map[string]string, error) { secretIDHMAC, err := createHMAC(hmacKey, secretID) if err != nil { - return false, nil, fmt.Errorf("failed to create HMAC of secret_id: %v", err) + return false, nil, errwrap.Wrapf("failed to create HMAC of secret_id: {{err}}", err) } roleNameHMAC, err := createHMAC(hmacKey, roleName) if err != nil { - return false, nil, fmt.Errorf("failed to create HMAC of role_name: %v", err) + return false, nil, errwrap.Wrapf("failed to create HMAC of role_name: {{err}}", err) } entryIndex := fmt.Sprintf("secret_id/%s/%s", roleNameHMAC, secretIDHMAC) @@ -204,7 +204,7 @@ func (b *backend) validateBindSecretID(ctx context.Context, req *logical.Request } if belongs, err := cidrutil.IPBelongsToCIDRBlocksSlice(req.Connection.RemoteAddr, result.CIDRList); !belongs || err != nil { - return false, nil, fmt.Errorf("source address %q unauthorized through CIDR restrictions on the secret ID: %v", req.Connection.RemoteAddr, err) + return false, nil, errwrap.Wrapf(fmt.Sprintf("source address %q unauthorized through CIDR restrictions on the secret ID: {{err}}", req.Connection.RemoteAddr), err) } } @@ -238,16 +238,16 @@ func (b *backend) validateBindSecretID(ctx context.Context, req *logical.Request return false, nil, err } if err := req.Storage.Delete(ctx, entryIndex); err != nil { - return false, nil, fmt.Errorf("failed to delete secret ID: %v", err) + return false, nil, errwrap.Wrapf("failed to delete secret ID: {{err}}", err) } } else { // If the use count is greater than one, decrement it and update the last updated time. result.SecretIDNumUses -= 1 result.LastUpdatedTime = time.Now() if entry, err := logical.StorageEntryJSON(entryIndex, &result); err != nil { - return false, nil, fmt.Errorf("failed to create storage entry while decrementing the secret ID use count: %v", err) + return false, nil, errwrap.Wrapf("failed to create storage entry while decrementing the secret ID use count: {{err}}", err) } else if err = req.Storage.Put(ctx, entry); err != nil { - return false, nil, fmt.Errorf("failed to decrement the secret ID use count: %v", err) + return false, nil, errwrap.Wrapf("failed to decrement the secret ID use count: {{err}}", err) } } @@ -266,7 +266,7 @@ func (b *backend) validateBindSecretID(ctx context.Context, req *logical.Request } if belongs, err := cidrutil.IPBelongsToCIDRBlocksSlice(req.Connection.RemoteAddr, result.CIDRList); !belongs || err != nil { - return false, nil, fmt.Errorf("source address %q unauthorized through CIDR restrictions on the secret ID: %v", req.Connection.RemoteAddr, err) + return false, nil, errwrap.Wrapf(fmt.Sprintf("source address %q unauthorized through CIDR restrictions on the secret ID: {{err}}", req.Connection.RemoteAddr), err) } } @@ -282,7 +282,7 @@ func verifyCIDRRoleSecretIDSubset(secretIDCIDRs []string, roleBoundCIDRList []st if len(roleBoundCIDRList) != 0 { subset, err := cidrutil.SubsetBlocks(roleBoundCIDRList, secretIDCIDRs) if !subset || err != nil { - return fmt.Errorf("failed to verify subset relationship between CIDR blocks on the role %q and CIDR blocks on the secret ID %q: %v", roleBoundCIDRList, secretIDCIDRs, err) + return errwrap.Wrapf(fmt.Sprintf("failed to verify subset relationship between CIDR blocks on the role %q and CIDR blocks on the secret ID %q: {{err}}", roleBoundCIDRList, secretIDCIDRs), err) } } } @@ -354,7 +354,7 @@ func (b *backend) nonLockedSecretIDStorageEntry(ctx context.Context, s logical.S if persistNeeded { if err := b.nonLockedSetSecretIDStorageEntry(ctx, s, roleNameHMAC, secretIDHMAC, &result); err != nil { - return nil, fmt.Errorf("failed to upgrade role storage entry %s", err) + return nil, errwrap.Wrapf("failed to upgrade role storage entry {{err}}", err) } } @@ -394,11 +394,11 @@ func (b *backend) nonLockedSetSecretIDStorageEntry(ctx context.Context, s logica func (b *backend) registerSecretIDEntry(ctx context.Context, s logical.Storage, roleName, secretID, hmacKey string, secretEntry *secretIDStorageEntry) (*secretIDStorageEntry, error) { secretIDHMAC, err := createHMAC(hmacKey, secretID) if err != nil { - return nil, fmt.Errorf("failed to create HMAC of secret ID: %v", err) + return nil, errwrap.Wrapf("failed to create HMAC of secret ID: {{err}}", err) } roleNameHMAC, err := createHMAC(hmacKey, roleName) if err != nil { - return nil, fmt.Errorf("failed to create HMAC of role_name: %v", err) + return nil, errwrap.Wrapf("failed to create HMAC of role_name: {{err}}", err) } lock := b.secretIDLock(secretIDHMAC) @@ -519,7 +519,7 @@ func (b *backend) createSecretIDAccessorEntry(ctx context.Context, s logical.Sto }); err != nil { return err } else if err = s.Put(ctx, entry); err != nil { - return fmt.Errorf("failed to persist accessor index entry: %v", err) + return errwrap.Wrapf("failed to persist accessor index entry: {{err}}", err) } return nil @@ -539,7 +539,7 @@ func (b *backend) deleteSecretIDAccessorEntry(ctx context.Context, s logical.Sto // Delete the accessor of the SecretID first if err := s.Delete(ctx, accessorEntryIndex); err != nil { - return fmt.Errorf("failed to delete accessor storage entry: %v", err) + return errwrap.Wrapf("failed to delete accessor storage entry: {{err}}", err) } return nil @@ -550,7 +550,7 @@ func (b *backend) deleteSecretIDAccessorEntry(ctx context.Context, s logical.Sto func (b *backend) flushRoleSecrets(ctx context.Context, s logical.Storage, roleName, hmacKey string) error { roleNameHMAC, err := createHMAC(hmacKey, roleName) if err != nil { - return fmt.Errorf("failed to create HMAC of role_name: %v", err) + return errwrap.Wrapf("failed to create HMAC of role_name: {{err}}", err) } // Acquire the custom lock to perform listing of SecretIDs @@ -568,7 +568,7 @@ func (b *backend) flushRoleSecrets(ctx context.Context, s logical.Storage, roleN entryIndex := fmt.Sprintf("secret_id/%s/%s", roleNameHMAC, secretIDHMAC) if err := s.Delete(ctx, entryIndex); err != nil { lock.Unlock() - return fmt.Errorf("error deleting SecretID %q from storage: %v", secretIDHMAC, err) + return errwrap.Wrapf(fmt.Sprintf("error deleting SecretID %q from storage: {{err}}", secretIDHMAC), err) } lock.Unlock() } diff --git a/builtin/credential/aws/backend.go b/builtin/credential/aws/backend.go index 6e789a2b8..146625711 100644 --- a/builtin/credential/aws/backend.go +++ b/builtin/credential/aws/backend.go @@ -227,7 +227,7 @@ func (b *backend) resolveArnToRealUniqueId(ctx context.Context, s logical.Storag // Sigh region := getAnyRegionForAwsPartition(entity.Partition) if region == nil { - return "", fmt.Errorf("Unable to resolve partition %q to a region", entity.Partition) + return "", fmt.Errorf("unable to resolve partition %q to a region", entity.Partition) } iamClient, err := b.clientIAM(ctx, s, region.ID(), entity.AccountNumber) if err != nil { diff --git a/builtin/credential/aws/cli.go b/builtin/credential/aws/cli.go index e6330ca12..0024513e7 100644 --- a/builtin/credential/aws/cli.go +++ b/builtin/credential/aws/cli.go @@ -10,6 +10,7 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/session" "github.com/aws/aws-sdk-go/service/sts" + "github.com/hashicorp/errwrap" "github.com/hashicorp/vault/api" "github.com/hashicorp/vault/helper/awsutil" ) @@ -36,7 +37,7 @@ func GenerateLoginData(accessKey, secretKey, sessionToken, headerValue string) ( _, err = creds.Get() if err != nil { - return nil, fmt.Errorf("failed to retrieve credentials from credential chain: %v", err) + return nil, errwrap.Wrapf("failed to retrieve credentials from credential chain: {{err}}", err) } // Use the credentials we've found to construct an STS session diff --git a/builtin/credential/aws/client.go b/builtin/credential/aws/client.go index 13bc17ba7..2d09bab30 100644 --- a/builtin/credential/aws/client.go +++ b/builtin/credential/aws/client.go @@ -10,6 +10,7 @@ import ( "github.com/aws/aws-sdk-go/service/ec2" "github.com/aws/aws-sdk-go/service/iam" "github.com/aws/aws-sdk-go/service/sts" + "github.com/hashicorp/errwrap" "github.com/hashicorp/go-cleanhttp" "github.com/hashicorp/vault/helper/awsutil" "github.com/hashicorp/vault/logical" @@ -103,12 +104,12 @@ func (b *backend) getClientConfig(ctx context.Context, s logical.Storage, region if b.defaultAWSAccountID == "" { client := sts.New(session.New(stsConfig)) if client == nil { - return nil, fmt.Errorf("could not obtain sts client: %v", err) + return nil, errwrap.Wrapf("could not obtain sts client: {{err}}", err) } inputParams := &sts.GetCallerIdentityInput{} identity, err := client.GetCallerIdentity(inputParams) if err != nil { - return nil, fmt.Errorf("unable to fetch current caller: %v", err) + return nil, errwrap.Wrapf("unable to fetch current caller: {{err}}", err) } if identity == nil { return nil, fmt.Errorf("got nil result from GetCallerIdentity") @@ -116,7 +117,7 @@ func (b *backend) getClientConfig(ctx context.Context, s logical.Storage, region b.defaultAWSAccountID = *identity.Account } if b.defaultAWSAccountID != accountID { - return nil, fmt.Errorf("unable to fetch client for account ID %s -- default client is for account %s", accountID, b.defaultAWSAccountID) + return nil, fmt.Errorf("unable to fetch client for account ID %q -- default client is for account %q", accountID, b.defaultAWSAccountID) } } @@ -168,7 +169,7 @@ func (b *backend) stsRoleForAccount(ctx context.Context, s logical.Storage, acco // Check if an STS configuration exists for the AWS account sts, err := b.lockedAwsStsEntry(ctx, s, accountID) if err != nil { - return "", fmt.Errorf("error fetching STS config for account ID %q: %q\n", accountID, err) + return "", errwrap.Wrapf(fmt.Sprintf("error fetching STS config for account ID %q: {{err}}", accountID), err) } // An empty STS role signifies the master account if sts != nil { diff --git a/builtin/credential/aws/path_config_certificate.go b/builtin/credential/aws/path_config_certificate.go index 3c6f64ab6..1f5a842b2 100644 --- a/builtin/credential/aws/path_config_certificate.go +++ b/builtin/credential/aws/path_config_certificate.go @@ -206,7 +206,7 @@ func (b *backend) awsPublicCertificates(ctx context.Context, s logical.Storage, return nil, err } if certEntry == nil { - return nil, fmt.Errorf("certificate storage has a nil entry under the name:%s\n", cert) + return nil, fmt.Errorf("certificate storage has a nil entry under the name: %q", cert) } // Append relevant certificates only if (isPkcs && certEntry.Type == "pkcs7") || diff --git a/builtin/credential/aws/path_login.go b/builtin/credential/aws/path_login.go index b67ed9fd9..a24792c9c 100644 --- a/builtin/credential/aws/path_login.go +++ b/builtin/credential/aws/path_login.go @@ -21,6 +21,7 @@ import ( "github.com/aws/aws-sdk-go/service/ec2" "github.com/aws/aws-sdk-go/service/iam" "github.com/fullsailor/pkcs7" + "github.com/hashicorp/errwrap" "github.com/hashicorp/go-cleanhttp" "github.com/hashicorp/go-uuid" "github.com/hashicorp/vault/helper/jsonutil" @@ -167,7 +168,7 @@ func (b *backend) validateInstance(ctx context.Context, s logical.Storage, insta }, }) if err != nil { - return nil, fmt.Errorf("error fetching description for instance ID %q: %q\n", instanceID, err) + return nil, errwrap.Wrapf(fmt.Sprintf("error fetching description for instance ID %q: {{err}}", instanceID), err) } if status == nil { return nil, fmt.Errorf("nil output from describe instances") @@ -310,7 +311,7 @@ func (b *backend) parseIdentityDocument(ctx context.Context, s logical.Storage, // Parse the signature from asn1 format into a struct pkcs7Data, err := pkcs7.Parse(pkcs7BER.Bytes) if err != nil { - return nil, fmt.Errorf("failed to parse the BER encoded PKCS#7 signature: %v\n", err) + return nil, errwrap.Wrapf("failed to parse the BER encoded PKCS#7 signature: {{err}}", err) } // Get the public certificates that are used to verify the signature. @@ -494,19 +495,19 @@ func (b *backend) verifyInstanceMeetsRoleRequirements(ctx context.Context, iamInstanceProfileEntity, err := parseIamArn(iamInstanceProfileARN) if err != nil { - return nil, fmt.Errorf("failed to parse IAM instance profile ARN %q; error: %v", iamInstanceProfileARN, err) + return nil, errwrap.Wrapf(fmt.Sprintf("failed to parse IAM instance profile ARN %q: {{err}}", iamInstanceProfileARN), err) } // Use instance profile ARN to fetch the associated role ARN iamClient, err := b.clientIAM(ctx, s, identityDoc.Region, identityDoc.AccountID) if err != nil { - return nil, fmt.Errorf("could not fetch IAM client: %v", err) + return nil, errwrap.Wrapf("could not fetch IAM client: {{err}}", err) } else if iamClient == nil { return nil, fmt.Errorf("received a nil iamClient") } iamRoleARN, err := b.instanceIamRoleARN(iamClient, iamInstanceProfileEntity.FriendlyName) if err != nil { - return nil, fmt.Errorf("IAM role ARN could not be fetched: %v", err) + return nil, errwrap.Wrapf("IAM role ARN could not be fetched: {{err}}", err) } if iamRoleARN == "" { return nil, fmt.Errorf("IAM role ARN could not be fetched") @@ -878,7 +879,7 @@ func (b *backend) handleRoleTagLogin(ctx context.Context, s logical.Storage, rol // If instance_id was set on the role tag, check if the same instance is attempting to login if rTag.InstanceID != "" && rTag.InstanceID != *instance.InstanceId { - return nil, fmt.Errorf("role tag is being used by an unauthorized instance.") + return nil, fmt.Errorf("role tag is being used by an unauthorized instance") } // Check if the role tag is blacklisted @@ -959,7 +960,7 @@ func (b *backend) pathLoginRenewIam(ctx context.Context, req *logical.Request, d } _, err := b.validateInstance(ctx, req.Storage, instanceID, instanceRegion, req.Auth.Metadata["account_id"]) if err != nil { - return nil, fmt.Errorf("failed to verify instance ID %q: %v", instanceID, err) + return nil, errwrap.Wrapf(fmt.Sprintf("failed to verify instance ID %q: {{err}}", instanceID), err) } } else { return nil, fmt.Errorf("unrecognized entity_type in metadata: %q", roleEntry.InferredEntityType) @@ -990,11 +991,11 @@ func (b *backend) pathLoginRenewIam(ctx context.Context, req *logical.Request, d if fullArn == "" { entity, err := parseIamArn(canonicalArn) if err != nil { - return nil, fmt.Errorf("error parsing ARN %q: %v", canonicalArn, err) + return nil, errwrap.Wrapf(fmt.Sprintf("error parsing ARN %q: {{err}}", canonicalArn), err) } fullArn, err = b.fullArn(ctx, entity, req.Storage) if err != nil { - return nil, fmt.Errorf("error looking up full ARN of entity %v: %v", entity, err) + return nil, errwrap.Wrapf(fmt.Sprintf("error looking up full ARN of entity %v: {{err}}", entity), err) } if fullArn == "" { return nil, fmt.Errorf("got empty string back when looking up full ARN of entity %v", entity) @@ -1045,7 +1046,7 @@ func (b *backend) pathLoginRenewEc2(ctx context.Context, req *logical.Request, d // Cross check that the instance is still in 'running' state _, err := b.validateInstance(ctx, req.Storage, instanceID, region, accountID) if err != nil { - return nil, fmt.Errorf("failed to verify instance ID %q: %q", instanceID, err) + return nil, errwrap.Wrapf(fmt.Sprintf("failed to verify instance ID %q: {{err}}", instanceID), err) } storedIdentity, err := whitelistIdentityEntry(ctx, req.Storage, instanceID) @@ -1395,12 +1396,12 @@ func validateVaultHeaderValue(headers http.Header, requestUrl *url.URL, required } } if providedValue == "" { - return fmt.Errorf("didn't find %s", iamServerIdHeader) + return fmt.Errorf("missing header %q", iamServerIdHeader) } // NOT doing a constant time compare here since the value is NOT intended to be secret if providedValue != requiredHeaderValue { - return fmt.Errorf("expected %s but got %s", requiredHeaderValue, providedValue) + return fmt.Errorf("expected %q but got %q", requiredHeaderValue, providedValue) } if authzHeaders, ok := headers["Authorization"]; ok { @@ -1494,7 +1495,7 @@ func parseIamRequestHeaders(headersB64 string) (http.Header, error) { var headersDecoded map[string]interface{} err = jsonutil.DecodeJSON(headersJson, &headersDecoded) if err != nil { - return nil, fmt.Errorf("failed to JSON decode iam_request_headers %q: %v", headersJson, err) + return nil, errwrap.Wrapf(fmt.Sprintf("failed to JSON decode iam_request_headers %q: {{err}}", headersJson), err) } headers := make(http.Header) for k, v := range headersDecoded { @@ -1533,7 +1534,7 @@ func submitCallerIdentityRequest(method, endpoint string, parsedUrl *url.URL, bo } response, err := client.Do(request) if err != nil { - return nil, fmt.Errorf("error making request: %v", err) + return nil, errwrap.Wrapf("error making request: {{err}}", err) } if response != nil { defer response.Body.Close() @@ -1617,7 +1618,7 @@ func (b *backend) fullArn(ctx context.Context, e *iamEntity, s logical.Storage) // Not assuming path is reliable for any entity types client, err := b.clientIAM(ctx, s, getAnyRegionForAwsPartition(e.Partition).ID(), e.AccountNumber) if err != nil { - return "", fmt.Errorf("error creating IAM client: %v", err) + return "", errwrap.Wrapf("error creating IAM client: {{err}}", err) } switch e.Type { @@ -1627,7 +1628,7 @@ func (b *backend) fullArn(ctx context.Context, e *iamEntity, s logical.Storage) } resp, err := client.GetUser(&input) if err != nil { - return "", fmt.Errorf("error fetching user %q: %v", e.FriendlyName, err) + return "", errwrap.Wrapf(fmt.Sprintf("error fetching user %q: {{err}}", e.FriendlyName), err) } if resp == nil { return "", fmt.Errorf("nil response from GetUser") @@ -1641,7 +1642,7 @@ func (b *backend) fullArn(ctx context.Context, e *iamEntity, s logical.Storage) } resp, err := client.GetRole(&input) if err != nil { - return "", fmt.Errorf("error fetching role %q: %v", e.FriendlyName, err) + return "", errwrap.Wrapf(fmt.Sprintf("error fetching role %q: {{err}}", e.FriendlyName), err) } if resp == nil { return "", fmt.Errorf("nil response form GetRole") diff --git a/builtin/credential/aws/path_role.go b/builtin/credential/aws/path_role.go index d31ab3fd7..06e3bec2b 100644 --- a/builtin/credential/aws/path_role.go +++ b/builtin/credential/aws/path_role.go @@ -6,6 +6,7 @@ import ( "strings" "time" + "github.com/hashicorp/errwrap" "github.com/hashicorp/go-uuid" "github.com/hashicorp/vault/helper/consts" "github.com/hashicorp/vault/helper/policyutil" @@ -244,7 +245,7 @@ func (b *backend) lockedAWSRole(ctx context.Context, s logical.Storage, roleName } needUpgrade, err := b.upgradeRoleEntry(ctx, s, roleEntry) if err != nil { - return nil, fmt.Errorf("error upgrading roleEntry: %v", err) + return nil, errwrap.Wrapf("error upgrading roleEntry: {{err}}", err) } if needUpgrade && (b.System().LocalMount() || !b.System().ReplicationState().HasState(consts.ReplicationPerformanceSecondary)) { b.roleMutex.Lock() @@ -261,11 +262,11 @@ func (b *backend) lockedAWSRole(ctx context.Context, s logical.Storage, roleName } // now re-check to see if we need to upgrade if needUpgrade, err = b.upgradeRoleEntry(ctx, s, roleEntry); err != nil { - return nil, fmt.Errorf("error upgrading roleEntry: %v", err) + return nil, errwrap.Wrapf("error upgrading roleEntry: {{err}}", err) } if needUpgrade { if err = b.nonLockedSetAWSRole(ctx, s, roleName, roleEntry); err != nil { - return nil, fmt.Errorf("error saving upgraded roleEntry: %v", err) + return nil, errwrap.Wrapf("error saving upgraded roleEntry: {{err}}", err) } } } @@ -789,7 +790,7 @@ func (b *backend) pathRoleCreateUpdate(ctx context.Context, req *logical.Request if roleEntry.HMACKey == "" { roleEntry.HMACKey, err = uuid.GenerateUUID() if err != nil { - return nil, fmt.Errorf("failed to generate role HMAC key: %v", err) + return nil, errwrap.Wrapf("failed to generate role HMAC key: {{err}}", err) } } diff --git a/builtin/credential/aws/path_role_tag.go b/builtin/credential/aws/path_role_tag.go index 21bed1ff1..48f44caf6 100644 --- a/builtin/credential/aws/path_role_tag.go +++ b/builtin/credential/aws/path_role_tag.go @@ -341,7 +341,7 @@ func (b *backend) parseAndVerifyRoleTagValue(ctx context.Context, s logical.Stor return nil, err } default: - return nil, fmt.Errorf("unrecognized item %s in tag", tagItem) + return nil, fmt.Errorf("unrecognized item %q in tag", tagItem) } } @@ -354,7 +354,7 @@ func (b *backend) parseAndVerifyRoleTagValue(ctx context.Context, s logical.Stor return nil, err } if roleEntry == nil { - return nil, fmt.Errorf("entry not found for %s", rTag.Role) + return nil, fmt.Errorf("entry not found for %q", rTag.Role) } // Create a HMAC of the plaintext value of role tag and compare it with the given value. diff --git a/builtin/credential/aws/path_tidy_identity_whitelist.go b/builtin/credential/aws/path_tidy_identity_whitelist.go index f2a9c2bec..fa0e8d82d 100644 --- a/builtin/credential/aws/path_tidy_identity_whitelist.go +++ b/builtin/credential/aws/path_tidy_identity_whitelist.go @@ -6,6 +6,7 @@ import ( "sync/atomic" "time" + "github.com/hashicorp/errwrap" "github.com/hashicorp/vault/logical" "github.com/hashicorp/vault/logical/framework" ) @@ -50,15 +51,15 @@ func (b *backend) tidyWhitelistIdentity(ctx context.Context, s logical.Storage, for _, instanceID := range identities { identityEntry, err := s.Get(ctx, "whitelist/identity/"+instanceID) if err != nil { - return fmt.Errorf("error fetching identity of instanceID %s: %s", instanceID, err) + return errwrap.Wrapf(fmt.Sprintf("error fetching identity of instanceID %q: {{err}}", instanceID), err) } if identityEntry == nil { - return fmt.Errorf("identity entry for instanceID %s is nil", instanceID) + return fmt.Errorf("identity entry for instanceID %q is nil", instanceID) } if identityEntry.Value == nil || len(identityEntry.Value) == 0 { - return fmt.Errorf("found identity entry for instanceID %s but actual identity is empty", instanceID) + return fmt.Errorf("found identity entry for instanceID %q but actual identity is empty", instanceID) } var result whitelistIdentity @@ -68,7 +69,7 @@ func (b *backend) tidyWhitelistIdentity(ctx context.Context, s logical.Storage, if time.Now().After(result.ExpirationTime.Add(bufferDuration)) { if err := s.Delete(ctx, "whitelist/identity"+instanceID); err != nil { - return fmt.Errorf("error deleting identity of instanceID %s from storage: %s", instanceID, err) + return errwrap.Wrapf(fmt.Sprintf("error deleting identity of instanceID %q from storage: {{err}}", instanceID), err) } } } diff --git a/builtin/credential/aws/path_tidy_roletag_blacklist.go b/builtin/credential/aws/path_tidy_roletag_blacklist.go index 8ccc3b939..dfb420653 100644 --- a/builtin/credential/aws/path_tidy_roletag_blacklist.go +++ b/builtin/credential/aws/path_tidy_roletag_blacklist.go @@ -6,6 +6,7 @@ import ( "sync/atomic" "time" + "github.com/hashicorp/errwrap" "github.com/hashicorp/vault/logical" "github.com/hashicorp/vault/logical/framework" ) @@ -49,15 +50,15 @@ func (b *backend) tidyBlacklistRoleTag(ctx context.Context, s logical.Storage, s for _, tag := range tags { tagEntry, err := s.Get(ctx, "blacklist/roletag/"+tag) if err != nil { - return fmt.Errorf("error fetching tag %s: %s", tag, err) + return errwrap.Wrapf(fmt.Sprintf("error fetching tag %q: {{err}}", tag), err) } if tagEntry == nil { - return fmt.Errorf("tag entry for tag %s is nil", tag) + return fmt.Errorf("tag entry for tag %q is nil", tag) } if tagEntry.Value == nil || len(tagEntry.Value) == 0 { - return fmt.Errorf("found entry for tag %s but actual tag is empty", tag) + return fmt.Errorf("found entry for tag %q but actual tag is empty", tag) } var result roleTagBlacklistEntry @@ -67,7 +68,7 @@ func (b *backend) tidyBlacklistRoleTag(ctx context.Context, s logical.Storage, s if time.Now().After(result.ExpirationTime.Add(bufferDuration)) { if err := s.Delete(ctx, "blacklist/roletag"+tag); err != nil { - return fmt.Errorf("error deleting tag %s from storage: %s", tag, err) + return errwrap.Wrapf(fmt.Sprintf("error deleting tag %q from storage: {{err}}", tag), err) } } } diff --git a/builtin/credential/cert/path_config.go b/builtin/credential/cert/path_config.go index adbbb5588..514a65b49 100644 --- a/builtin/credential/cert/path_config.go +++ b/builtin/credential/cert/path_config.go @@ -2,8 +2,8 @@ package cert import ( "context" - "fmt" + "github.com/hashicorp/errwrap" "github.com/hashicorp/vault/logical" "github.com/hashicorp/vault/logical/framework" ) @@ -52,7 +52,7 @@ func (b *backend) Config(ctx context.Context, s logical.Storage) (*config, error var result config if entry != nil { if err := entry.DecodeJSON(&result); err != nil { - return nil, fmt.Errorf("error reading configuration: %s", err) + return nil, errwrap.Wrapf("error reading configuration: {{err}}", err) } } return &result, nil diff --git a/builtin/credential/cert/path_crls.go b/builtin/credential/cert/path_crls.go index 9f18322f5..06ced5705 100644 --- a/builtin/credential/cert/path_crls.go +++ b/builtin/credential/cert/path_crls.go @@ -8,6 +8,7 @@ import ( "strings" "github.com/fatih/structs" + "github.com/hashicorp/errwrap" "github.com/hashicorp/vault/helper/certutil" "github.com/hashicorp/vault/logical" "github.com/hashicorp/vault/logical/framework" @@ -54,7 +55,7 @@ func (b *backend) populateCRLs(ctx context.Context, storage logical.Storage) err keys, err := storage.List(ctx, "crls/") if err != nil { - return fmt.Errorf("error listing CRLs: %v", err) + return errwrap.Wrapf("error listing CRLs: {{err}}", err) } if keys == nil || len(keys) == 0 { return nil @@ -64,7 +65,7 @@ func (b *backend) populateCRLs(ctx context.Context, storage logical.Storage) err entry, err := storage.Get(ctx, "crls/"+key) if err != nil { b.crls = nil - return fmt.Errorf("error loading CRL %s: %v", key, err) + return errwrap.Wrapf(fmt.Sprintf("error loading CRL %q: {{err}}", key), err) } if entry == nil { continue @@ -73,7 +74,7 @@ func (b *backend) populateCRLs(ctx context.Context, storage logical.Storage) err err = entry.DecodeJSON(&crlInfo) if err != nil { b.crls = nil - return fmt.Errorf("error decoding CRL %s: %v", key, err) + return errwrap.Wrapf(fmt.Sprintf("error decoding CRL %q: {{err}}", key), err) } b.crls[key] = crlInfo } @@ -103,20 +104,20 @@ func parseSerialString(input string) (*big.Int, error) { case strings.Count(input, ":") > 0: serialBytes := certutil.ParseHexFormatted(input, ":") if serialBytes == nil { - return nil, fmt.Errorf("error parsing serial %s", input) + return nil, fmt.Errorf("error parsing serial %q", input) } ret.SetBytes(serialBytes) case strings.Count(input, "-") > 0: serialBytes := certutil.ParseHexFormatted(input, "-") if serialBytes == nil { - return nil, fmt.Errorf("error parsing serial %s", input) + return nil, fmt.Errorf("error parsing serial %q", input) } ret.SetBytes(serialBytes) default: var success bool ret, success = ret.SetString(input, 0) if !success { - return nil, fmt.Errorf("error parsing serial %s", input) + return nil, fmt.Errorf("error parsing serial %q", input) } } diff --git a/builtin/credential/github/cli.go b/builtin/credential/github/cli.go index 3a4642aff..b3a4577ed 100644 --- a/builtin/credential/github/cli.go +++ b/builtin/credential/github/cli.go @@ -6,6 +6,7 @@ import ( "os" "strings" + "github.com/hashicorp/errwrap" "github.com/hashicorp/vault/api" "github.com/hashicorp/vault/helper/password" ) @@ -42,12 +43,12 @@ func (h *CLIHandler) Auth(c *api.Client, m map[string]string) (*api.Secret, erro return nil, fmt.Errorf("user interrupted") } - return nil, fmt.Errorf("An error occurred attempting to "+ + return nil, errwrap.Wrapf("An error occurred attempting to "+ "ask for a token. The raw error message is shown below, but usually "+ "this is because you attempted to pipe a value into the command or "+ "you are executing outside of a terminal (tty). If you want to pipe "+ "the value, pass \"-\" as the argument to read from stdin. The raw "+ - "error was: %s", err) + "error was: {{err}}", err) } } diff --git a/builtin/credential/github/path_config.go b/builtin/credential/github/path_config.go index c3ea04fda..f42b156db 100644 --- a/builtin/credential/github/path_config.go +++ b/builtin/credential/github/path_config.go @@ -6,6 +6,7 @@ import ( "net/url" "time" + "github.com/hashicorp/errwrap" "github.com/hashicorp/vault/logical" "github.com/hashicorp/vault/logical/framework" ) @@ -127,7 +128,7 @@ func (b *backend) Config(ctx context.Context, s logical.Storage) (*config, error var result config if entry != nil { if err := entry.DecodeJSON(&result); err != nil { - return nil, fmt.Errorf("error reading configuration: %s", err) + return nil, errwrap.Wrapf("error reading configuration: {{err}}", err) } } diff --git a/builtin/credential/github/path_login.go b/builtin/credential/github/path_login.go index 3a51097e5..34a0f617c 100644 --- a/builtin/credential/github/path_login.go +++ b/builtin/credential/github/path_login.go @@ -7,6 +7,7 @@ import ( "strings" "github.com/google/go-github/github" + "github.com/hashicorp/errwrap" "github.com/hashicorp/vault/helper/policyutil" "github.com/hashicorp/vault/logical" "github.com/hashicorp/vault/logical/framework" @@ -163,7 +164,7 @@ func (b *backend) verifyCredentials(ctx context.Context, req *logical.Request, t if config.BaseURL != "" { parsedURL, err := url.Parse(config.BaseURL) if err != nil { - return nil, nil, fmt.Errorf("Successfully parsed base_url when set but failing to parse now: %s", err) + return nil, nil, errwrap.Wrapf("successfully parsed base_url when set but failing to parse now: {{err}}", err) } client.BaseURL = parsedURL } diff --git a/builtin/credential/ldap/backend.go b/builtin/credential/ldap/backend.go index 8d3e46b31..ef6364525 100644 --- a/builtin/credential/ldap/backend.go +++ b/builtin/credential/ldap/backend.go @@ -9,6 +9,7 @@ import ( "text/template" "github.com/go-ldap/ldap" + "github.com/hashicorp/errwrap" "github.com/hashicorp/vault/helper/mfa" "github.com/hashicorp/vault/helper/strutil" "github.com/hashicorp/vault/logical" @@ -270,7 +271,7 @@ func (b *backend) getUserBindDN(cfg *ConfigEntry, c *ldap.Conn, username string) err = c.UnauthenticatedBind(cfg.BindDN) } if err != nil { - return bindDN, fmt.Errorf("LDAP bind (service) failed: %v", err) + return bindDN, errwrap.Wrapf("LDAP bind (service) failed: {{err}}", err) } filter := fmt.Sprintf("(%s=%s)", cfg.UserAttr, ldap.EscapeFilter(username)) @@ -284,7 +285,7 @@ func (b *backend) getUserBindDN(cfg *ConfigEntry, c *ldap.Conn, username string) SizeLimit: math.MaxInt32, }) if err != nil { - return bindDN, fmt.Errorf("LDAP search for binddn failed: %v", err) + return bindDN, errwrap.Wrapf("LDAP search for binddn failed: {{err}}", err) } if len(result.Entries) != 1 { return bindDN, fmt.Errorf("LDAP search for binddn 0 or not unique") @@ -319,7 +320,7 @@ func (b *backend) getUserDN(cfg *ConfigEntry, c *ldap.Conn, bindDN string) (stri SizeLimit: math.MaxInt32, }) if err != nil { - return userDN, fmt.Errorf("LDAP search failed for detecting user: %v", err) + return userDN, errwrap.Wrapf("LDAP search failed for detecting user: {{err}}", err) } for _, e := range result.Entries { userDN = e.DN @@ -373,7 +374,7 @@ func (b *backend) getLdapGroups(cfg *ConfigEntry, c *ldap.Conn, userDN string, u // Example template "(&(objectClass=group)(member:1.2.840.113556.1.4.1941:={{.UserDN}}))" t, err := template.New("queryTemplate").Parse(cfg.GroupFilter) if err != nil { - return nil, fmt.Errorf("LDAP search failed due to template compilation error: %v", err) + return nil, errwrap.Wrapf("LDAP search failed due to template compilation error: {{err}}", err) } // Build context to pass to template - we will be exposing UserDn and Username. @@ -402,7 +403,7 @@ func (b *backend) getLdapGroups(cfg *ConfigEntry, c *ldap.Conn, userDN string, u SizeLimit: math.MaxInt32, }) if err != nil { - return nil, fmt.Errorf("LDAP search failed: %v", err) + return nil, errwrap.Wrapf("LDAP search failed: {{err}}", err) } for _, e := range result.Entries { diff --git a/builtin/credential/ldap/path_config.go b/builtin/credential/ldap/path_config.go index 401510c18..659dff9f8 100644 --- a/builtin/credential/ldap/path_config.go +++ b/builtin/credential/ldap/path_config.go @@ -12,6 +12,7 @@ import ( "text/template" "github.com/go-ldap/ldap" + "github.com/hashicorp/errwrap" log "github.com/hashicorp/go-hclog" multierror "github.com/hashicorp/go-multierror" "github.com/hashicorp/vault/helper/consts" @@ -253,7 +254,7 @@ func (b *backend) newConfigEntry(d *framework.FieldData) (*ConfigEntry, error) { // Validate the template before proceeding _, err := template.New("queryTemplate").Parse(groupfilter) if err != nil { - return nil, fmt.Errorf("invalid groupfilter (%v)", err) + return nil, errwrap.Wrapf("invalid groupfilter: {{err}}", err) } cfg.GroupFilter = groupfilter @@ -275,7 +276,7 @@ func (b *backend) newConfigEntry(d *framework.FieldData) (*ConfigEntry, error) { } _, err := x509.ParseCertificate(block.Bytes) if err != nil { - return nil, fmt.Errorf("failed to parse certificate %s", err.Error()) + return nil, errwrap.Wrapf("failed to parse certificate: {{err}}", err) } cfg.Certificate = certificate } @@ -429,7 +430,7 @@ func (c *ConfigEntry) DialLDAP() (*ldap.Conn, error) { for _, uut := range urls { u, err := url.Parse(uut) if err != nil { - retErr = multierror.Append(retErr, fmt.Errorf("error parsing url %q: %s", uut, err.Error())) + retErr = multierror.Append(retErr, errwrap.Wrapf(fmt.Sprintf("error parsing url %q: {{err}}", uut), err)) continue } host, port, err := net.SplitHostPort(u.Host) @@ -480,7 +481,7 @@ func (c *ConfigEntry) DialLDAP() (*ldap.Conn, error) { retErr = nil break } - retErr = multierror.Append(retErr, fmt.Errorf("error connecting to host %q: %s", uut, err.Error())) + retErr = multierror.Append(retErr, errwrap.Wrapf(fmt.Sprintf("error connecting to host %q: {{err}}", uut), err)) } return conn, retErr.ErrorOrNil() diff --git a/builtin/credential/token/cli.go b/builtin/credential/token/cli.go index c828e5d64..21fafb4b1 100644 --- a/builtin/credential/token/cli.go +++ b/builtin/credential/token/cli.go @@ -7,6 +7,7 @@ import ( "strconv" "strings" + "github.com/hashicorp/errwrap" "github.com/hashicorp/vault/api" "github.com/hashicorp/vault/helper/password" ) @@ -26,7 +27,7 @@ func (h *CLIHandler) Auth(c *api.Client, m map[string]string) (*api.Secret, erro if x, ok := m["lookup"]; ok { parsed, err := strconv.ParseBool(x) if err != nil { - return nil, fmt.Errorf("Failed to parse \"lookup\" as boolean: %s", err) + return nil, errwrap.Wrapf("Failed to parse \"lookup\" as boolean: {{err}}", err) } lookup = parsed } @@ -51,12 +52,12 @@ func (h *CLIHandler) Auth(c *api.Client, m map[string]string) (*api.Secret, erro return nil, fmt.Errorf("user interrupted") } - return nil, fmt.Errorf("An error occurred attempting to "+ + return nil, errwrap.Wrapf("An error occurred attempting to "+ "ask for a token. The raw error message is shown below, but usually "+ "this is because you attempted to pipe a value into the command or "+ "you are executing outside of a terminal (tty). If you want to pipe "+ "the value, pass \"-\" as the argument to read from stdin. The raw "+ - "error was: %s", err) + "error was: {{err}}", err) } } @@ -86,10 +87,10 @@ func (h *CLIHandler) Auth(c *api.Client, m map[string]string) (*api.Secret, erro secret, err := c.Auth().Token().LookupSelf() if err != nil { - return nil, fmt.Errorf("Error looking up token: %s", err) + return nil, errwrap.Wrapf("error looking up token: {{err}}", err) } if secret == nil { - return nil, fmt.Errorf("Empty response from lookup-self") + return nil, fmt.Errorf("empty response from lookup-self") } // Return an auth struct that "looks" like the response from an auth method. @@ -97,27 +98,27 @@ func (h *CLIHandler) Auth(c *api.Client, m map[string]string) (*api.Secret, erro // mirror that data here. id, err := secret.TokenID() if err != nil { - return nil, fmt.Errorf("Error accessing token ID: %s", err) + return nil, errwrap.Wrapf("error accessing token ID: {{err}}", err) } accessor, err := secret.TokenAccessor() if err != nil { - return nil, fmt.Errorf("Error accessing token accessor: %s", err) + return nil, errwrap.Wrapf("error accessing token accessor: {{err}}", err) } policies, err := secret.TokenPolicies() if err != nil { - return nil, fmt.Errorf("Error accessing token policies: %s", err) + return nil, errwrap.Wrapf("error accessing token policies: {{err}}", err) } metadata, err := secret.TokenMetadata() if err != nil { - return nil, fmt.Errorf("Error accessing token metadata: %s", err) + return nil, errwrap.Wrapf("error accessing token metadata: {{err}}", err) } dur, err := secret.TokenTTL() if err != nil { - return nil, fmt.Errorf("Error converting token TTL: %s", err) + return nil, errwrap.Wrapf("error converting token TTL: {{err}}", err) } renewable, err := secret.TokenIsRenewable() if err != nil { - return nil, fmt.Errorf("Error checking if token is renewable: %s", err) + return nil, errwrap.Wrapf("error checking if token is renewable: {{err}}", err) } return &api.Secret{ Auth: &api.SecretAuth{ diff --git a/builtin/logical/aws/client.go b/builtin/logical/aws/client.go index 7787cfa67..6a8ffa26f 100644 --- a/builtin/logical/aws/client.go +++ b/builtin/logical/aws/client.go @@ -9,6 +9,7 @@ import ( "github.com/aws/aws-sdk-go/aws/session" "github.com/aws/aws-sdk-go/service/iam" "github.com/aws/aws-sdk-go/service/sts" + "github.com/hashicorp/errwrap" "github.com/hashicorp/go-cleanhttp" "github.com/hashicorp/vault/helper/awsutil" "github.com/hashicorp/vault/logical" @@ -26,7 +27,7 @@ func getRootConfig(ctx context.Context, s logical.Storage, clientType string) (* if entry != nil { var config rootConfig if err := entry.DecodeJSON(&config); err != nil { - return nil, fmt.Errorf("error reading root configuration: %s", err) + return nil, errwrap.Wrapf("error reading root configuration: {{err}}", err) } credsConfig.AccessKey = config.AccessKey diff --git a/builtin/logical/aws/path_sts.go b/builtin/logical/aws/path_sts.go index 05591f0d4..2fe195359 100644 --- a/builtin/logical/aws/path_sts.go +++ b/builtin/logical/aws/path_sts.go @@ -5,6 +5,7 @@ import ( "fmt" "strings" + "github.com/hashicorp/errwrap" "github.com/hashicorp/vault/logical" "github.com/hashicorp/vault/logical/framework" ) @@ -47,7 +48,7 @@ func (b *backend) pathSTSRead(ctx context.Context, req *logical.Request, d *fram // Read the policy policy, err := req.Storage.Get(ctx, "policy/"+policyName) if err != nil { - return nil, fmt.Errorf("error retrieving role: %s", err) + return nil, errwrap.Wrapf("error retrieving role: {{err}}", err) } if policy == nil { return logical.ErrorResponse(fmt.Sprintf( diff --git a/builtin/logical/aws/path_user.go b/builtin/logical/aws/path_user.go index 90a20d07c..74a4ae0bf 100644 --- a/builtin/logical/aws/path_user.go +++ b/builtin/logical/aws/path_user.go @@ -6,6 +6,7 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/iam" + "github.com/hashicorp/errwrap" "github.com/hashicorp/vault/logical" "github.com/hashicorp/vault/logical/framework" "github.com/mitchellh/mapstructure" @@ -36,7 +37,7 @@ func (b *backend) pathUserRead(ctx context.Context, req *logical.Request, d *fra // Read the policy policy, err := req.Storage.Get(ctx, "policy/"+policyName) if err != nil { - return nil, fmt.Errorf("error retrieving role: %s", err) + return nil, errwrap.Wrapf("error retrieving role: {{err}}", err) } if policy == nil { return logical.ErrorResponse(fmt.Sprintf( diff --git a/builtin/logical/aws/secret_access_keys.go b/builtin/logical/aws/secret_access_keys.go index 93d2bb4dd..c45b7eb5a 100644 --- a/builtin/logical/aws/secret_access_keys.go +++ b/builtin/logical/aws/secret_access_keys.go @@ -12,6 +12,7 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/iam" "github.com/aws/aws-sdk-go/service/sts" + "github.com/hashicorp/errwrap" "github.com/hashicorp/vault/logical" "github.com/hashicorp/vault/logical/framework" ) @@ -174,7 +175,7 @@ func (b *backend) secretAccessKeysCreate( UserName: username, }) if err != nil { - return nil, fmt.Errorf("Error writing WAL entry: %s", err) + return nil, errwrap.Wrapf("error writing WAL entry: {{err}}", err) } // Create the user @@ -223,7 +224,7 @@ func (b *backend) secretAccessKeysCreate( // the secret because it'll get rolled back anyways, so we have to return // an error here. if err := framework.DeleteWAL(ctx, s, walId); err != nil { - return nil, fmt.Errorf("Failed to commit WAL entry: %s", err) + return nil, errwrap.Wrapf("failed to commit WAL entry: {{err}}", err) } // Return the info! diff --git a/builtin/logical/cassandra/backend.go b/builtin/logical/cassandra/backend.go index d7102aa5a..fba89781f 100644 --- a/builtin/logical/cassandra/backend.go +++ b/builtin/logical/cassandra/backend.go @@ -92,8 +92,7 @@ func (b *backend) DB(ctx context.Context, s logical.Storage) (*gocql.Session, er return nil, err } if entry == nil { - return nil, - fmt.Errorf("Configure the DB connection with config/connection first") + return nil, fmt.Errorf("configure the DB connection with config/connection first") } config := &sessionConfig{} diff --git a/builtin/logical/cassandra/secret_creds.go b/builtin/logical/cassandra/secret_creds.go index 5fed47579..4aa54956a 100644 --- a/builtin/logical/cassandra/secret_creds.go +++ b/builtin/logical/cassandra/secret_creds.go @@ -4,6 +4,7 @@ import ( "context" "fmt" + "github.com/hashicorp/errwrap" "github.com/hashicorp/vault/logical" "github.com/hashicorp/vault/logical/framework" ) @@ -44,7 +45,7 @@ func (b *backend) secretCredsRenew(ctx context.Context, req *logical.Request, d role, err := getRole(ctx, req.Storage, roleName) if err != nil { - return nil, fmt.Errorf("unable to load role: %s", err) + return nil, errwrap.Wrapf("unable to load role: {{err}}", err) } resp := &logical.Response{Secret: req.Secret} @@ -70,7 +71,7 @@ func (b *backend) secretCredsRevoke(ctx context.Context, req *logical.Request, d err = session.Query(fmt.Sprintf("DROP USER '%s'", username)).Exec() if err != nil { - return nil, fmt.Errorf("error removing user %s", username) + return nil, fmt.Errorf("error removing user %q", username) } return nil, nil diff --git a/builtin/logical/cassandra/util.go b/builtin/logical/cassandra/util.go index ef3d1ee2e..2be6d9671 100644 --- a/builtin/logical/cassandra/util.go +++ b/builtin/logical/cassandra/util.go @@ -7,6 +7,7 @@ import ( "time" "github.com/gocql/gocql" + "github.com/hashicorp/errwrap" "github.com/hashicorp/vault/helper/certutil" "github.com/hashicorp/vault/helper/tlsutil" "github.com/hashicorp/vault/logical" @@ -39,7 +40,7 @@ func createSession(cfg *sessionConfig, s logical.Storage) (*gocql.Session, error var tlsConfig *tls.Config if len(cfg.Certificate) > 0 || len(cfg.IssuingCA) > 0 { if len(cfg.Certificate) > 0 && len(cfg.PrivateKey) == 0 { - return nil, fmt.Errorf("Found certificate for TLS authentication but no private key") + return nil, fmt.Errorf("found certificate for TLS authentication but no private key") } certBundle := &certutil.CertBundle{} @@ -53,12 +54,12 @@ func createSession(cfg *sessionConfig, s logical.Storage) (*gocql.Session, error parsedCertBundle, err := certBundle.ToParsedCertBundle() if err != nil { - return nil, fmt.Errorf("failed to parse certificate bundle: %s", err) + return nil, errwrap.Wrapf("failed to parse certificate bundle: {{err}}", err) } tlsConfig, err = parsedCertBundle.GetTLSConfig(certutil.TLSClient) if err != nil || tlsConfig == nil { - return nil, fmt.Errorf("failed to get TLS configuration: tlsConfig:%#v err:%v", tlsConfig, err) + return nil, errwrap.Wrapf(fmt.Sprintf("failed to get TLS configuration: tlsConfig: %#v; {{err}}", tlsConfig), err) } tlsConfig.InsecureSkipVerify = cfg.InsecureTLS @@ -82,13 +83,13 @@ func createSession(cfg *sessionConfig, s logical.Storage) (*gocql.Session, error session, err := clusterConfig.CreateSession() if err != nil { - return nil, fmt.Errorf("Error creating session: %s", err) + return nil, errwrap.Wrapf("error creating session: {{err}}", err) } // Verify the info err = session.Query(`LIST USERS`).Exec() if err != nil { - return nil, fmt.Errorf("Error validating connection info: %s", err) + return nil, errwrap.Wrapf("error validating connection info: {{err}}", err) } return session, nil diff --git a/builtin/logical/consul/path_config.go b/builtin/logical/consul/path_config.go index e8a7412e0..61087ff5b 100644 --- a/builtin/logical/consul/path_config.go +++ b/builtin/logical/consul/path_config.go @@ -4,6 +4,7 @@ import ( "context" "fmt" + "github.com/hashicorp/errwrap" "github.com/hashicorp/vault/logical" "github.com/hashicorp/vault/logical/framework" ) @@ -46,14 +47,12 @@ func readConfigAccess(ctx context.Context, storage logical.Storage) (*accessConf return nil, nil, err } if entry == nil { - return nil, fmt.Errorf( - "Access credentials for the backend itself haven't been configured. Please configure them at the '/config/access' endpoint"), - nil + return nil, fmt.Errorf("access credentials for the backend itself haven't been configured; please configure them at the '/config/access' endpoint"), nil } conf := &accessConfig{} if err := entry.DecodeJSON(conf); err != nil { - return nil, nil, fmt.Errorf("error reading consul access configuration: %s", err) + return nil, nil, errwrap.Wrapf("error reading consul access configuration: {{err}}", err) } return conf, nil, nil diff --git a/builtin/logical/consul/path_token.go b/builtin/logical/consul/path_token.go index 7310d2a81..a22069fca 100644 --- a/builtin/logical/consul/path_token.go +++ b/builtin/logical/consul/path_token.go @@ -6,6 +6,7 @@ import ( "time" "github.com/hashicorp/consul/api" + "github.com/hashicorp/errwrap" "github.com/hashicorp/vault/logical" "github.com/hashicorp/vault/logical/framework" ) @@ -31,7 +32,7 @@ func (b *backend) pathTokenRead(ctx context.Context, req *logical.Request, d *fr entry, err := req.Storage.Get(ctx, "policy/"+role) if err != nil { - return nil, fmt.Errorf("error retrieving role: %s", err) + return nil, errwrap.Wrapf("error retrieving role: {{err}}", err) } if entry == nil { return logical.ErrorResponse(fmt.Sprintf("role %q not found", role)), nil diff --git a/builtin/logical/consul/secret_token.go b/builtin/logical/consul/secret_token.go index 9a8b956e9..45bf7ff4d 100644 --- a/builtin/logical/consul/secret_token.go +++ b/builtin/logical/consul/secret_token.go @@ -4,6 +4,7 @@ import ( "context" "fmt" + "github.com/hashicorp/errwrap" "github.com/hashicorp/vault/logical" "github.com/hashicorp/vault/logical/framework" ) @@ -41,7 +42,7 @@ func (b *backend) secretTokenRenew(ctx context.Context, req *logical.Request, d entry, err := req.Storage.Get(ctx, "policy/"+role) if err != nil { - return nil, fmt.Errorf("error retrieving role: %s", err) + return nil, errwrap.Wrapf("error retrieving role: {{err}}", err) } if entry == nil { return logical.ErrorResponse(fmt.Sprintf("issuing role %q not found", role)), nil diff --git a/builtin/logical/database/backend.go b/builtin/logical/database/backend.go index db5fb4e8c..e9ee43a7d 100644 --- a/builtin/logical/database/backend.go +++ b/builtin/logical/database/backend.go @@ -96,7 +96,7 @@ func (b *databaseBackend) DatabaseConfig(ctx context.Context, s logical.Storage, return nil, errwrap.Wrapf("failed to read connection configuration: {{err}}", err) } if entry == nil { - return nil, fmt.Errorf("failed to find entry for connection with name: %s", name) + return nil, fmt.Errorf("failed to find entry for connection with name: %q", name) } var config DatabaseConfig diff --git a/builtin/logical/database/dbplugin/plugin.go b/builtin/logical/database/dbplugin/plugin.go index 4cb8d9b7b..502f97ebc 100644 --- a/builtin/logical/database/dbplugin/plugin.go +++ b/builtin/logical/database/dbplugin/plugin.go @@ -54,7 +54,7 @@ func PluginFactory(ctx context.Context, pluginName string, sys pluginutil.LookRu var ok bool db, ok = dbRaw.(Database) if !ok { - return nil, fmt.Errorf("unsupported database type: %s", pluginName) + return nil, fmt.Errorf("unsupported database type: %q", pluginName) } transport = "builtin" diff --git a/builtin/logical/database/secret_creds.go b/builtin/logical/database/secret_creds.go index b6cd3ede9..4489b0798 100644 --- a/builtin/logical/database/secret_creds.go +++ b/builtin/logical/database/secret_creds.go @@ -32,7 +32,7 @@ func (b *databaseBackend) secretCredsRenew() framework.OperationFunc { roleNameRaw, ok := req.Secret.InternalData["role"] if !ok { - return nil, fmt.Errorf("could not find role with name: %s", req.Secret.InternalData["role"]) + return nil, fmt.Errorf("could not find role with name: %q", req.Secret.InternalData["role"]) } role, err := b.Role(ctx, req.Storage, roleNameRaw.(string)) @@ -40,7 +40,7 @@ func (b *databaseBackend) secretCredsRenew() framework.OperationFunc { return nil, err } if role == nil { - return nil, fmt.Errorf("error during renew: could not find role with name %s", req.Secret.InternalData["role"]) + return nil, fmt.Errorf("error during renew: could not find role with name %q", req.Secret.InternalData["role"]) } // Get the Database object @@ -96,7 +96,7 @@ func (b *databaseBackend) secretCredsRevoke() framework.OperationFunc { return nil, err } if role == nil { - return nil, fmt.Errorf("error during revoke: could not find role with name %s", req.Secret.InternalData["role"]) + return nil, fmt.Errorf("error during revoke: could not find role with name %q", req.Secret.InternalData["role"]) } // Get our connection diff --git a/builtin/logical/mssql/secret_creds.go b/builtin/logical/mssql/secret_creds.go index 8ff8d2a84..ce93643ee 100644 --- a/builtin/logical/mssql/secret_creds.go +++ b/builtin/logical/mssql/secret_creds.go @@ -5,6 +5,7 @@ import ( "database/sql" "fmt" + "github.com/hashicorp/errwrap" "github.com/hashicorp/vault/logical" "github.com/hashicorp/vault/logical/framework" ) @@ -143,10 +144,10 @@ func (b *backend) secretCredsRevoke(ctx context.Context, req *logical.Request, d // can't drop if not all database users are dropped if rows.Err() != nil { - return nil, fmt.Errorf("could not generate sql statements for all rows: %s", rows.Err()) + return nil, errwrap.Wrapf("could not generate sql statements for all rows: {{err}}", rows.Err()) } if lastStmtError != nil { - return nil, fmt.Errorf("could not perform all sql statements: %s", lastStmtError) + return nil, errwrap.Wrapf("could not perform all sql statements: {{err}}", lastStmtError) } // Drop this login diff --git a/builtin/logical/pki/crl_util.go b/builtin/logical/pki/crl_util.go index eda4e797e..8eb65ed58 100644 --- a/builtin/logical/pki/crl_util.go +++ b/builtin/logical/pki/crl_util.go @@ -8,6 +8,7 @@ import ( "fmt" "time" + "github.com/hashicorp/errwrap" "github.com/hashicorp/vault/helper/errutil" "github.com/hashicorp/vault/logical" ) @@ -66,7 +67,7 @@ func revokeCert(ctx context.Context, b *backend, req *logical.Request, serial st cert, err := x509.ParseCertificate(certEntry.Value) if err != nil { - return nil, fmt.Errorf("error parsing certificate: %s", err) + return nil, errwrap.Wrapf("error parsing certificate: {{err}}", err) } if cert == nil { return nil, fmt.Errorf("got a nil certificate") @@ -104,7 +105,7 @@ func revokeCert(ctx context.Context, b *backend, req *logical.Request, serial st case errutil.UserError: return logical.ErrorResponse(fmt.Sprintf("Error during CRL building: %s", crlErr)), nil case errutil.InternalError: - return nil, fmt.Errorf("error encountered during CRL building: %s", crlErr) + return nil, errwrap.Wrapf("error encountered during CRL building: {{err}}", crlErr) } resp := &logical.Response{ diff --git a/builtin/logical/pki/path_config_ca.go b/builtin/logical/pki/path_config_ca.go index 11cbf9553..f21e3665c 100644 --- a/builtin/logical/pki/path_config_ca.go +++ b/builtin/logical/pki/path_config_ca.go @@ -2,8 +2,8 @@ package pki import ( "context" - "fmt" + "github.com/hashicorp/errwrap" "github.com/hashicorp/vault/helper/certutil" "github.com/hashicorp/vault/helper/errutil" "github.com/hashicorp/vault/logical" @@ -62,7 +62,7 @@ func (b *backend) pathCAWrite(ctx context.Context, req *logical.Request, data *f cb, err := parsedBundle.ToCertBundle() if err != nil { - return nil, fmt.Errorf("error converting raw values into cert bundle: %s", err) + return nil, errwrap.Wrapf("error converting raw values into cert bundle: {{err}}", err) } entry, err := logical.StorageEntryJSON("config/ca_bundle", cb) diff --git a/builtin/logical/pki/path_config_urls.go b/builtin/logical/pki/path_config_urls.go index aca163cad..e3a0d6f96 100644 --- a/builtin/logical/pki/path_config_urls.go +++ b/builtin/logical/pki/path_config_urls.go @@ -76,7 +76,7 @@ func writeURLs(ctx context.Context, req *logical.Request, entries *urlEntries) e return err } if entry == nil { - return fmt.Errorf("Unable to marshal entry into JSON") + return fmt.Errorf("unable to marshal entry into JSON") } err = req.Storage.Put(ctx, entry) diff --git a/builtin/logical/pki/path_intermediate.go b/builtin/logical/pki/path_intermediate.go index f86d3ae11..0fb249b58 100644 --- a/builtin/logical/pki/path_intermediate.go +++ b/builtin/logical/pki/path_intermediate.go @@ -5,6 +5,7 @@ import ( "encoding/base64" "fmt" + "github.com/hashicorp/errwrap" "github.com/hashicorp/vault/helper/certutil" "github.com/hashicorp/vault/helper/errutil" "github.com/hashicorp/vault/logical" @@ -87,7 +88,7 @@ func (b *backend) pathGenerateIntermediate(ctx context.Context, req *logical.Req csrb, err := parsedBundle.ToCSRBundle() if err != nil { - return nil, fmt.Errorf("Error converting raw CSR bundle to CSR bundle: %s", err) + return nil, errwrap.Wrapf("error converting raw CSR bundle to CSR bundle: {{err}}", err) } resp = &logical.Response{ @@ -197,12 +198,12 @@ func (b *backend) pathSetSignedIntermediate(ctx context.Context, req *logical.Re } if err := inputBundle.Verify(); err != nil { - return nil, fmt.Errorf("verification of parsed bundle failed: %s", err) + return nil, errwrap.Wrapf("verification of parsed bundle failed: {{err}}", err) } cb, err = inputBundle.ToCertBundle() if err != nil { - return nil, fmt.Errorf("error converting raw values into cert bundle: %s", err) + return nil, errwrap.Wrapf("error converting raw values into cert bundle: {{err}}", err) } entry, err = logical.StorageEntryJSON("config/ca_bundle", cb) diff --git a/builtin/logical/pki/path_issue_sign.go b/builtin/logical/pki/path_issue_sign.go index 29c3176ce..6f9bdc141 100644 --- a/builtin/logical/pki/path_issue_sign.go +++ b/builtin/logical/pki/path_issue_sign.go @@ -297,7 +297,7 @@ func (b *backend) pathIssueSignCert(ctx context.Context, req *logical.Request, d Value: parsedBundle.CertificateBytes, }) if err != nil { - return nil, fmt.Errorf("unable to store certificate locally: %v", err) + return nil, errwrap.Wrapf("unable to store certificate locally: {{err}}", err) } } diff --git a/builtin/logical/pki/path_revoke.go b/builtin/logical/pki/path_revoke.go index f0a189e21..52ffac4b1 100644 --- a/builtin/logical/pki/path_revoke.go +++ b/builtin/logical/pki/path_revoke.go @@ -5,6 +5,7 @@ import ( "fmt" "strings" + "github.com/hashicorp/errwrap" "github.com/hashicorp/vault/helper/errutil" "github.com/hashicorp/vault/logical" "github.com/hashicorp/vault/logical/framework" @@ -68,7 +69,7 @@ func (b *backend) pathRotateCRLRead(ctx context.Context, req *logical.Request, d case errutil.UserError: return logical.ErrorResponse(fmt.Sprintf("Error during CRL building: %s", crlErr)), nil case errutil.InternalError: - return nil, fmt.Errorf("Error encountered during CRL building: %s", crlErr) + return nil, errwrap.Wrapf("error encountered during CRL building: {{err}}", crlErr) default: return &logical.Response{ Data: map[string]interface{}{ diff --git a/builtin/logical/pki/path_root.go b/builtin/logical/pki/path_root.go index d2c1f2560..2eae080d6 100644 --- a/builtin/logical/pki/path_root.go +++ b/builtin/logical/pki/path_root.go @@ -309,17 +309,17 @@ func (b *backend) pathCASignIntermediate(ctx context.Context, req *logical.Reque } if err := parsedBundle.Verify(); err != nil { - return nil, fmt.Errorf("verification of parsed bundle failed: %s", err) + return nil, errwrap.Wrapf("verification of parsed bundle failed: {{err}}", err) } signingCB, err := signingBundle.ToCertBundle() if err != nil { - return nil, fmt.Errorf("Error converting raw signing bundle to cert bundle: %s", err) + return nil, errwrap.Wrapf("error converting raw signing bundle to cert bundle: {{err}}", err) } cb, err := parsedBundle.ToCertBundle() if err != nil { - return nil, fmt.Errorf("Error converting raw cert bundle to cert bundle: %s", err) + return nil, errwrap.Wrapf("error converting raw cert bundle to cert bundle: {{err}}", err) } resp := &logical.Response{ @@ -366,7 +366,7 @@ func (b *backend) pathCASignIntermediate(ctx context.Context, req *logical.Reque Value: parsedBundle.CertificateBytes, }) if err != nil { - return nil, fmt.Errorf("Unable to store certificate locally: %v", err) + return nil, errwrap.Wrapf("unable to store certificate locally: {{err}}", err) } if parsedBundle.Certificate.MaxPathLen == 0 { @@ -413,7 +413,7 @@ func (b *backend) pathCASignSelfIssued(ctx context.Context, req *logical.Request signingCB, err := signingBundle.ToCertBundle() if err != nil { - return nil, fmt.Errorf("Error converting raw signing bundle to cert bundle: %s", err) + return nil, errwrap.Wrapf("error converting raw signing bundle to cert bundle: {{err}}", err) } urls := &urlEntries{} diff --git a/builtin/logical/pki/path_tidy.go b/builtin/logical/pki/path_tidy.go index b00a1398f..b254321a3 100644 --- a/builtin/logical/pki/path_tidy.go +++ b/builtin/logical/pki/path_tidy.go @@ -60,13 +60,13 @@ func (b *backend) pathTidyWrite(ctx context.Context, req *logical.Request, d *fr if tidyCertStore { serials, err := req.Storage.List(ctx, "certs/") if err != nil { - return nil, fmt.Errorf("error fetching list of certs: %s", err) + return nil, errwrap.Wrapf("error fetching list of certs: {{err}}", err) } for _, serial := range serials { certEntry, err := req.Storage.Get(ctx, "certs/"+serial) if err != nil { - return nil, fmt.Errorf("error fetching certificate %s: %s", serial, err) + return nil, errwrap.Wrapf(fmt.Sprintf("error fetching certificate %q: {{err}}", serial), err) } if certEntry == nil { @@ -91,12 +91,12 @@ func (b *backend) pathTidyWrite(ctx context.Context, req *logical.Request, d *fr cert, err := x509.ParseCertificate(certEntry.Value) if err != nil { - return nil, fmt.Errorf("unable to parse stored certificate with serial %s: %s", serial, err) + return nil, errwrap.Wrapf(fmt.Sprintf("unable to parse stored certificate with serial %q: {{err}}", serial), err) } if time.Now().After(cert.NotAfter.Add(bufferDuration)) { if err := req.Storage.Delete(ctx, "certs/"+serial); err != nil { - return nil, fmt.Errorf("error deleting serial %s from storage: %s", serial, err) + return nil, errwrap.Wrapf(fmt.Sprintf("error deleting serial %q from storage: {{err}}", serial), err) } } } @@ -110,14 +110,14 @@ func (b *backend) pathTidyWrite(ctx context.Context, req *logical.Request, d *fr revokedSerials, err := req.Storage.List(ctx, "revoked/") if err != nil { - return nil, fmt.Errorf("error fetching list of revoked certs: %s", err) + return nil, errwrap.Wrapf("error fetching list of revoked certs: {{err}}", err) } var revInfo revocationInfo for _, serial := range revokedSerials { revokedEntry, err := req.Storage.Get(ctx, "revoked/"+serial) if err != nil { - return nil, fmt.Errorf("unable to fetch revoked cert with serial %s: %s", serial, err) + return nil, errwrap.Wrapf(fmt.Sprintf("unable to fetch revoked cert with serial %q: {{err}}", serial), err) } if revokedEntry == nil { @@ -142,17 +142,17 @@ func (b *backend) pathTidyWrite(ctx context.Context, req *logical.Request, d *fr err = revokedEntry.DecodeJSON(&revInfo) if err != nil { - return nil, fmt.Errorf("error decoding revocation entry for serial %s: %s", serial, err) + return nil, errwrap.Wrapf(fmt.Sprintf("error decoding revocation entry for serial %q: {{err}}", serial), err) } revokedCert, err := x509.ParseCertificate(revInfo.CertificateBytes) if err != nil { - return nil, fmt.Errorf("unable to parse stored revoked certificate with serial %s: %s", serial, err) + return nil, errwrap.Wrapf(fmt.Sprintf("unable to parse stored revoked certificate with serial %q: {{err}}", serial), err) } if time.Now().After(revokedCert.NotAfter.Add(bufferDuration)) { if err := req.Storage.Delete(ctx, "revoked/"+serial); err != nil { - return nil, fmt.Errorf("error deleting serial %s from revoked list: %s", serial, err) + return nil, errwrap.Wrapf(fmt.Sprintf("error deleting serial %q from revoked list: {{err}}", serial), err) } tidiedRevoked = true } diff --git a/builtin/logical/postgresql/secret_creds.go b/builtin/logical/postgresql/secret_creds.go index 95b291af7..87748d1ff 100644 --- a/builtin/logical/postgresql/secret_creds.go +++ b/builtin/logical/postgresql/secret_creds.go @@ -7,6 +7,7 @@ import ( "strings" "time" + "github.com/hashicorp/errwrap" "github.com/hashicorp/vault/helper/strutil" "github.com/hashicorp/vault/logical" "github.com/hashicorp/vault/logical/framework" @@ -224,10 +225,10 @@ func (b *backend) secretCredsRevoke(ctx context.Context, req *logical.Request, d // can't drop if not all privileges are revoked if rows.Err() != nil { - return nil, fmt.Errorf("could not generate revocation statements for all rows: %s", rows.Err()) + return nil, errwrap.Wrapf("could not generate revocation statements for all rows: {{err}}", rows.Err()) } if lastStmtError != nil { - return nil, fmt.Errorf("could not perform all revocation statements: %s", lastStmtError) + return nil, errwrap.Wrapf("could not perform all revocation statements: {{err}}", lastStmtError) } // Drop this user diff --git a/builtin/logical/rabbitmq/path_config_connection.go b/builtin/logical/rabbitmq/path_config_connection.go index 40ce63750..db2fb3c78 100644 --- a/builtin/logical/rabbitmq/path_config_connection.go +++ b/builtin/logical/rabbitmq/path_config_connection.go @@ -2,8 +2,8 @@ package rabbitmq import ( "context" - "fmt" + "github.com/hashicorp/errwrap" "github.com/hashicorp/vault/logical" "github.com/hashicorp/vault/logical/framework" "github.com/michaelklishin/rabbit-hole" @@ -63,12 +63,12 @@ func (b *backend) pathConnectionUpdate(ctx context.Context, req *logical.Request // Create RabbitMQ management client client, err := rabbithole.NewClient(uri, username, password) if err != nil { - return nil, fmt.Errorf("failed to create client: %s", err) + return nil, errwrap.Wrapf("failed to create client: {{err}}", err) } // Verify that configured credentials is capable of listing if _, err = client.ListUsers(); err != nil { - return nil, fmt.Errorf("failed to validate the connection: %s", err) + return nil, errwrap.Wrapf("failed to validate the connection: {{err}}", err) } } diff --git a/builtin/logical/rabbitmq/path_role_create.go b/builtin/logical/rabbitmq/path_role_create.go index 5cb015c46..6cbced5ac 100644 --- a/builtin/logical/rabbitmq/path_role_create.go +++ b/builtin/logical/rabbitmq/path_role_create.go @@ -4,6 +4,8 @@ import ( "context" "fmt" + "github.com/hashicorp/errwrap" + multierror "github.com/hashicorp/go-multierror" "github.com/hashicorp/go-uuid" "github.com/hashicorp/vault/logical" "github.com/hashicorp/vault/logical/framework" @@ -82,11 +84,12 @@ func (b *backend) pathCredsRead(ctx context.Context, req *logical.Request, d *fr Write: permission.Write, Read: permission.Read, }); err != nil { + outerErr := errwrap.Wrapf(fmt.Sprintf("failed to update permissions to the %q user: {{err}}", username), err) // Delete the user because it's in an unknown state if _, rmErr := client.DeleteUser(username); rmErr != nil { - return nil, fmt.Errorf("failed to delete user:%s, err: %s. %s", username, err, rmErr) + return nil, multierror.Append(errwrap.Wrapf("failed to delete user: {{err}}", rmErr), outerErr) } - return nil, fmt.Errorf("failed to update permissions to the %s user. err:%s", username, err) + return nil, outerErr } } diff --git a/builtin/logical/rabbitmq/secret_creds.go b/builtin/logical/rabbitmq/secret_creds.go index cb7e977eb..3962c7bf8 100644 --- a/builtin/logical/rabbitmq/secret_creds.go +++ b/builtin/logical/rabbitmq/secret_creds.go @@ -4,6 +4,7 @@ import ( "context" "fmt" + "github.com/hashicorp/errwrap" "github.com/hashicorp/vault/logical" "github.com/hashicorp/vault/logical/framework" ) @@ -62,7 +63,7 @@ func (b *backend) secretCredsRevoke(ctx context.Context, req *logical.Request, d } if _, err = client.DeleteUser(username); err != nil { - return nil, fmt.Errorf("could not delete user: %s", err) + return nil, errwrap.Wrapf("could not delete user: {{err}}", err) } return nil, nil diff --git a/builtin/logical/ssh/communicator.go b/builtin/logical/ssh/communicator.go index 47775b36b..8bcd3ec40 100644 --- a/builtin/logical/ssh/communicator.go +++ b/builtin/logical/ssh/communicator.go @@ -11,6 +11,7 @@ import ( "os" "path/filepath" + "github.com/hashicorp/errwrap" log "github.com/hashicorp/go-hclog" "golang.org/x/crypto/ssh" @@ -277,7 +278,7 @@ func checkSCPStatus(r *bufio.Reader) error { // Treat any non-zero (really 1 and 2) as fatal errors message, _, err := r.ReadLine() if err != nil { - return fmt.Errorf("Error reading error message: %s", err) + return errwrap.Wrapf("error reading error message: {{err}}", err) } return errors.New(string(message)) @@ -298,7 +299,7 @@ func scpUploadFile(dst string, src io.Reader, w io.Writer, r *bufio.Reader, fi * // so that we can determine the length, since SCP is length-prefixed. tf, err := ioutil.TempFile("", "vault-ssh-upload") if err != nil { - return fmt.Errorf("Error creating temporary file for upload: %s", err) + return errwrap.Wrapf("error creating temporary file for upload: {{err}}", err) } defer os.Remove(tf.Name()) defer tf.Close() @@ -312,17 +313,17 @@ func scpUploadFile(dst string, src io.Reader, w io.Writer, r *bufio.Reader, fi * // Sync the file so that the contents are definitely on disk, then // read the length of it. if err := tf.Sync(); err != nil { - return fmt.Errorf("Error creating temporary file for upload: %s", err) + return errwrap.Wrapf("error creating temporary file for upload: {{err}}", err) } // Seek the file to the beginning so we can re-read all of it if _, err := tf.Seek(0, 0); err != nil { - return fmt.Errorf("Error creating temporary file for upload: %s", err) + return errwrap.Wrapf("error creating temporary file for upload: {{err}}", err) } tfi, err := tf.Stat() if err != nil { - return fmt.Errorf("Error creating temporary file for upload: %s", err) + return errwrap.Wrapf("error creating temporary file for upload: {{err}}", err) } size = tfi.Size() diff --git a/builtin/logical/ssh/path_config_ca.go b/builtin/logical/ssh/path_config_ca.go index d98a0e38d..de0f5515a 100644 --- a/builtin/logical/ssh/path_config_ca.go +++ b/builtin/logical/ssh/path_config_ca.go @@ -8,6 +8,7 @@ import ( "encoding/pem" "fmt" + "github.com/hashicorp/errwrap" multierror "github.com/hashicorp/go-multierror" "github.com/hashicorp/vault/logical" "github.com/hashicorp/vault/logical/framework" @@ -65,7 +66,7 @@ Read operations will return the public key, if already stored/generated.`, func (b *backend) pathConfigCARead(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { publicKeyEntry, err := caKey(ctx, req.Storage, caPublicKey) if err != nil { - return nil, fmt.Errorf("failed to read CA public key: %v", err) + return nil, errwrap.Wrapf("failed to read CA public key: {{err}}", err) } if publicKeyEntry == nil { @@ -106,7 +107,7 @@ func caKey(ctx context.Context, storage logical.Storage, keyType string) (*keySt entry, err := storage.Get(ctx, path) if err != nil { - return nil, fmt.Errorf("failed to read CA key of type %q: %v", keyType, err) + return nil, errwrap.Wrapf(fmt.Sprintf("failed to read CA key of type %q: {{err}}", keyType), err) } if entry == nil { @@ -202,12 +203,12 @@ func (b *backend) pathConfigCAUpdate(ctx context.Context, req *logical.Request, publicKeyEntry, err := caKey(ctx, req.Storage, caPublicKey) if err != nil { - return nil, fmt.Errorf("failed to read CA public key: %v", err) + return nil, errwrap.Wrapf("failed to read CA public key: {{err}}", err) } privateKeyEntry, err := caKey(ctx, req.Storage, caPrivateKey) if err != nil { - return nil, fmt.Errorf("failed to read CA private key: %v", err) + return nil, errwrap.Wrapf("failed to read CA private key: {{err}}", err) } if (publicKeyEntry != nil && publicKeyEntry.Key != "") || (privateKeyEntry != nil && privateKeyEntry.Key != "") { @@ -239,12 +240,12 @@ func (b *backend) pathConfigCAUpdate(ctx context.Context, req *logical.Request, if err != nil { var mErr *multierror.Error - mErr = multierror.Append(mErr, fmt.Errorf("failed to store CA private key: %v", err)) + mErr = multierror.Append(mErr, errwrap.Wrapf("failed to store CA private key: {{err}}", err)) // If storing private key fails, the corresponding public key should be // removed if delErr := req.Storage.Delete(ctx, caPublicKeyStoragePath); delErr != nil { - mErr = multierror.Append(mErr, fmt.Errorf("failed to cleanup CA public key: %v", delErr)) + mErr = multierror.Append(mErr, errwrap.Wrapf("failed to cleanup CA public key: {{err}}", delErr)) return nil, mErr } diff --git a/builtin/logical/ssh/path_config_zeroaddress.go b/builtin/logical/ssh/path_config_zeroaddress.go index 3dd8c72ba..02754baac 100644 --- a/builtin/logical/ssh/path_config_zeroaddress.go +++ b/builtin/logical/ssh/path_config_zeroaddress.go @@ -146,7 +146,7 @@ func (r *zeroAddressRoles) remove(roleName string) error { } length := len(r.Roles) if index >= length || index < 0 { - return fmt.Errorf("invalid index [%d]", index) + return fmt.Errorf("invalid index %d", index) } // If slice has zero or one item, remove the item by setting slice to nil. if length < 2 { diff --git a/builtin/logical/ssh/path_creds_create.go b/builtin/logical/ssh/path_creds_create.go index 236cb8197..004fbe4e6 100644 --- a/builtin/logical/ssh/path_creds_create.go +++ b/builtin/logical/ssh/path_creds_create.go @@ -6,6 +6,7 @@ import ( "net" "strings" + "github.com/hashicorp/errwrap" "github.com/hashicorp/go-uuid" "github.com/hashicorp/vault/logical" "github.com/hashicorp/vault/logical/framework" @@ -55,7 +56,7 @@ func (b *backend) pathCredsCreateWrite(ctx context.Context, req *logical.Request role, err := b.getRole(ctx, req.Storage, roleName) if err != nil { - return nil, fmt.Errorf("error retrieving role: %v", err) + return nil, errwrap.Wrapf("error retrieving role: {{err}}", err) } if role == nil { return logical.ErrorResponse(fmt.Sprintf("Role %q not found", roleName)), nil @@ -97,7 +98,7 @@ func (b *backend) pathCredsCreateWrite(ctx context.Context, req *logical.Request zeroAddressEntry, err := b.getZeroAddressRoles(ctx, req.Storage) if err != nil { - return nil, fmt.Errorf("error retrieving zero-address roles: %v", err) + return nil, errwrap.Wrapf("error retrieving zero-address roles: {{err}}", err) } var zeroAddressRoles []string if zeroAddressEntry != nil { @@ -171,7 +172,7 @@ func (b *backend) GenerateDynamicCredential(ctx context.Context, req *logical.Re // Fetch the host key to be used for dynamic key installation keyEntry, err := req.Storage.Get(ctx, fmt.Sprintf("keys/%s", role.KeyName)) if err != nil { - return "", "", fmt.Errorf("key %q not found. err: %v", role.KeyName, err) + return "", "", errwrap.Wrapf(fmt.Sprintf("key %q not found: {{err}}", role.KeyName), err) } if keyEntry == nil { @@ -180,13 +181,13 @@ func (b *backend) GenerateDynamicCredential(ctx context.Context, req *logical.Re var hostKey sshHostKey if err := keyEntry.DecodeJSON(&hostKey); err != nil { - return "", "", fmt.Errorf("error reading the host key: %v", err) + return "", "", errwrap.Wrapf("error reading the host key: {{err}}", err) } // Generate a new RSA key pair with the given key length. dynamicPublicKey, dynamicPrivateKey, err := generateRSAKeys(role.KeyBits) if err != nil { - return "", "", fmt.Errorf("error generating key: %v", err) + return "", "", errwrap.Wrapf("error generating key: {{err}}", err) } if len(role.KeyOptionSpecs) != 0 { @@ -196,7 +197,7 @@ func (b *backend) GenerateDynamicCredential(ctx context.Context, req *logical.Re // Add the public key to authorized_keys file in target machine err = b.installPublicKeyInTarget(ctx, role.AdminUser, username, ip, role.Port, hostKey.Key, dynamicPublicKey, role.InstallScript, true) if err != nil { - return "", "", fmt.Errorf("failed to add public key to authorized_keys file in target: %v", err) + return "", "", errwrap.Wrapf("failed to add public key to authorized_keys file in target: {{err}}", err) } return dynamicPublicKey, dynamicPrivateKey, nil } diff --git a/builtin/logical/ssh/path_roles.go b/builtin/logical/ssh/path_roles.go index 9af1aa535..76fda0e0e 100644 --- a/builtin/logical/ssh/path_roles.go +++ b/builtin/logical/ssh/path_roles.go @@ -7,6 +7,7 @@ import ( "time" + "github.com/hashicorp/errwrap" "github.com/hashicorp/vault/helper/cidrutil" "github.com/hashicorp/vault/helper/parseutil" "github.com/hashicorp/vault/logical" @@ -305,7 +306,7 @@ func (b *backend) pathRoleWrite(ctx context.Context, req *logical.Request, d *fr if cidrList != "" { valid, err := cidrutil.ValidateCIDRListString(cidrList, ",") if err != nil { - return nil, fmt.Errorf("failed to validate cidr_list: %v", err) + return nil, errwrap.Wrapf("failed to validate cidr_list: {{err}}", err) } if !valid { return logical.ErrorResponse("failed to validate cidr_list"), nil @@ -317,7 +318,7 @@ func (b *backend) pathRoleWrite(ctx context.Context, req *logical.Request, d *fr if excludeCidrList != "" { valid, err := cidrutil.ValidateCIDRListString(excludeCidrList, ",") if err != nil { - return nil, fmt.Errorf("failed to validate exclude_cidr_list entry: %v", err) + return nil, errwrap.Wrapf("failed to validate exclude_cidr_list entry: {{err}}", err) } if !valid { return logical.ErrorResponse(fmt.Sprintf("failed to validate exclude_cidr_list entry: %v", err)), nil diff --git a/builtin/logical/ssh/path_sign.go b/builtin/logical/ssh/path_sign.go index 3c9c7de64..68bd1efe6 100644 --- a/builtin/logical/ssh/path_sign.go +++ b/builtin/logical/ssh/path_sign.go @@ -10,6 +10,7 @@ import ( "strings" "time" + "github.com/hashicorp/errwrap" "github.com/hashicorp/vault/helper/certutil" "github.com/hashicorp/vault/helper/parseutil" "github.com/hashicorp/vault/helper/strutil" @@ -151,7 +152,7 @@ func (b *backend) pathSignCertificate(ctx context.Context, req *logical.Request, privateKeyEntry, err := caKey(ctx, req.Storage, caPrivateKey) if err != nil { - return nil, fmt.Errorf("failed to read CA private key: %v", err) + return nil, errwrap.Wrapf("failed to read CA private key: {{err}}", err) } if privateKeyEntry == nil || privateKeyEntry.Key == "" { return nil, fmt.Errorf("failed to read CA private key") @@ -159,7 +160,7 @@ func (b *backend) pathSignCertificate(ctx context.Context, req *logical.Request, signer, err := ssh.ParsePrivateKey([]byte(privateKeyEntry.Key)) if err != nil { - return nil, fmt.Errorf("failed to parse stored CA private key: %v", err) + return nil, errwrap.Wrapf("failed to parse stored CA private key: {{err}}", err) } cBundle := creationBundle{ @@ -312,7 +313,7 @@ func (b *backend) calculateCriticalOptions(data *framework.FieldData, role *sshR } if len(notAllowedOptions) != 0 { - return nil, fmt.Errorf("Critical options not on allowed list: %v", notAllowedOptions) + return nil, fmt.Errorf("critical options not on allowed list: %v", notAllowedOptions) } } @@ -376,7 +377,7 @@ func (b *backend) calculateTTL(data *framework.FieldData, role *sshRole) (time.D if !specifiedTTL { ttl = maxTTL } else { - return 0, fmt.Errorf("ttl is larger than maximum allowed (%d)", maxTTL/time.Second) + return 0, fmt.Errorf("ttl is larger than maximum allowed %d", maxTTL/time.Second) } } diff --git a/builtin/logical/ssh/secret_dynamic_key.go b/builtin/logical/ssh/secret_dynamic_key.go index 1a0b3eefb..6078733f7 100644 --- a/builtin/logical/ssh/secret_dynamic_key.go +++ b/builtin/logical/ssh/secret_dynamic_key.go @@ -55,7 +55,7 @@ func (b *backend) secretDynamicKeyRevoke(ctx context.Context, req *logical.Reque // Fetch the host key using the key name hostKey, err := b.getKey(ctx, req.Storage, intSec.HostKeyName) if err != nil { - return nil, fmt.Errorf("key %q not found error: %v", intSec.HostKeyName, err) + return nil, errwrap.Wrapf(fmt.Sprintf("key %q not found error: {{err}}", intSec.HostKeyName), err) } if hostKey == nil { return nil, fmt.Errorf("key %q not found", intSec.HostKeyName) diff --git a/builtin/logical/ssh/util.go b/builtin/logical/ssh/util.go index a455b06da..98a7036a4 100644 --- a/builtin/logical/ssh/util.go +++ b/builtin/logical/ssh/util.go @@ -13,6 +13,7 @@ import ( "strings" "time" + "github.com/hashicorp/errwrap" "github.com/hashicorp/vault/logical" log "github.com/hashicorp/go-hclog" @@ -24,7 +25,7 @@ import ( func generateRSAKeys(keyBits int) (publicKeyRsa string, privateKeyRsa string, err error) { privateKey, err := rsa.GenerateKey(rand.Reader, keyBits) if err != nil { - return "", "", fmt.Errorf("error generating RSA key-pair: %v", err) + return "", "", errwrap.Wrapf("error generating RSA key-pair: {{err}}", err) } privateKeyRsa = string(pem.EncodeToMemory(&pem.Block{ @@ -34,7 +35,7 @@ func generateRSAKeys(keyBits int) (publicKeyRsa string, privateKeyRsa string, er sshPublicKey, err := ssh.NewPublicKey(privateKey.Public()) if err != nil { - return "", "", fmt.Errorf("error generating RSA key-pair: %v", err) + return "", "", errwrap.Wrapf("error generating RSA key-pair: {{err}}", err) } publicKeyRsa = "ssh-rsa " + base64.StdEncoding.EncodeToString(sshPublicKey.Marshal()) return @@ -62,7 +63,7 @@ func (b *backend) installPublicKeyInTarget(ctx context.Context, adminUser, usern err = comm.Upload(publicKeyFileName, bytes.NewBufferString(dynamicPublicKey), nil) if err != nil { - return fmt.Errorf("error uploading public key: %v", err) + return errwrap.Wrapf("error uploading public key: {{err}}", err) } // Transfer the script required to install or uninstall the key to the remote @@ -71,14 +72,14 @@ func (b *backend) installPublicKeyInTarget(ctx context.Context, adminUser, usern scriptFileName := fmt.Sprintf("%s.sh", publicKeyFileName) err = comm.Upload(scriptFileName, bytes.NewBufferString(installScript), nil) if err != nil { - return fmt.Errorf("error uploading install script: %v", err) + return errwrap.Wrapf("error uploading install script: {{err}}", err) } // Create a session to run remote command that triggers the script to install // or uninstall the key. session, err := comm.NewSession() if err != nil { - return fmt.Errorf("unable to create SSH Session using public keys: %v", err) + return errwrap.Wrapf("unable to create SSH Session using public keys: {{err}}", err) } if session == nil { return fmt.Errorf("invalid session object") @@ -117,7 +118,7 @@ func roleContainsIP(ctx context.Context, s logical.Storage, roleName string, ip roleEntry, err := s.Get(ctx, fmt.Sprintf("roles/%s", roleName)) if err != nil { - return false, fmt.Errorf("error retrieving role %v", err) + return false, errwrap.Wrapf("error retrieving role {{err}}", err) } if roleEntry == nil { return false, fmt.Errorf("role %q not found", roleName) diff --git a/builtin/logical/totp/path_keys.go b/builtin/logical/totp/path_keys.go index a96f243f3..9f2b2a26c 100644 --- a/builtin/logical/totp/path_keys.go +++ b/builtin/logical/totp/path_keys.go @@ -11,6 +11,7 @@ import ( "strconv" "strings" + "github.com/hashicorp/errwrap" "github.com/hashicorp/vault/logical" "github.com/hashicorp/vault/logical/framework" otplib "github.com/pquerna/otp" @@ -355,7 +356,7 @@ func (b *backend) pathKeyCreate(ctx context.Context, req *logical.Request, data } else { barcode, err := keyObject.Image(qrSize, qrSize) if err != nil { - return nil, fmt.Errorf("failed to generate QR code image: %v", err) + return nil, errwrap.Wrapf("failed to generate QR code image: {{err}}", err) } var buff bytes.Buffer diff --git a/builtin/logical/transit/path_decrypt.go b/builtin/logical/transit/path_decrypt.go index 94fa58787..007b49b43 100644 --- a/builtin/logical/transit/path_decrypt.go +++ b/builtin/logical/transit/path_decrypt.go @@ -3,8 +3,8 @@ package transit import ( "context" "encoding/base64" - "fmt" + "github.com/hashicorp/errwrap" "github.com/hashicorp/vault/helper/errutil" "github.com/hashicorp/vault/logical" "github.com/hashicorp/vault/logical/framework" @@ -58,7 +58,7 @@ func (b *backend) pathDecryptWrite(ctx context.Context, req *logical.Request, d if batchInputRaw != nil { err = mapstructure.Decode(batchInputRaw, &batchInputItems) if err != nil { - return nil, fmt.Errorf("failed to parse batch input: %v", err) + return nil, errwrap.Wrapf("failed to parse batch input: {{err}}", err) } if len(batchInputItems) == 0 { diff --git a/builtin/logical/transit/path_encrypt.go b/builtin/logical/transit/path_encrypt.go index 812e2a02b..760a9b263 100644 --- a/builtin/logical/transit/path_encrypt.go +++ b/builtin/logical/transit/path_encrypt.go @@ -6,6 +6,7 @@ import ( "fmt" "sync" + "github.com/hashicorp/errwrap" "github.com/hashicorp/vault/helper/errutil" "github.com/hashicorp/vault/helper/keysutil" "github.com/hashicorp/vault/logical" @@ -146,7 +147,7 @@ func (b *backend) pathEncryptWrite(ctx context.Context, req *logical.Request, d if batchInputRaw != nil { err = mapstructure.Decode(batchInputRaw, &batchInputItems) if err != nil { - return nil, fmt.Errorf("failed to parse batch input: %v", err) + return nil, errwrap.Wrapf("failed to parse batch input: {{err}}", err) } if len(batchInputItems) == 0 { diff --git a/builtin/logical/transit/path_keys.go b/builtin/logical/transit/path_keys.go index 7dc7f0a97..f25d6ee7d 100644 --- a/builtin/logical/transit/path_keys.go +++ b/builtin/logical/transit/path_keys.go @@ -13,6 +13,7 @@ import ( "golang.org/x/crypto/ed25519" "github.com/fatih/structs" + "github.com/hashicorp/errwrap" "github.com/hashicorp/vault/helper/keysutil" "github.com/hashicorp/vault/logical" "github.com/hashicorp/vault/logical/framework" @@ -277,7 +278,7 @@ func (b *backend) pathPolicyRead(ctx context.Context, req *logical.Request, d *f } else { ver, err := strconv.Atoi(k) if err != nil { - return nil, fmt.Errorf("invalid version %q: %v", k, err) + return nil, errwrap.Wrapf(fmt.Sprintf("invalid version %q: {{err}}", k), err) } derived, err := p.DeriveKey(context, ver) if err != nil { @@ -298,7 +299,7 @@ func (b *backend) pathPolicyRead(ctx context.Context, req *logical.Request, d *f // API derBytes, err := x509.MarshalPKIXPublicKey(v.RSAKey.Public()) if err != nil { - return nil, fmt.Errorf("error marshaling RSA public key: %v", err) + return nil, errwrap.Wrapf("error marshaling RSA public key: {{err}}", err) } pemBlock := &pem.Block{ Type: "PUBLIC KEY", diff --git a/builtin/logical/transit/path_rewrap.go b/builtin/logical/transit/path_rewrap.go index c7e6e507a..36bb36d74 100644 --- a/builtin/logical/transit/path_rewrap.go +++ b/builtin/logical/transit/path_rewrap.go @@ -5,6 +5,7 @@ import ( "encoding/base64" "fmt" + "github.com/hashicorp/errwrap" "github.com/hashicorp/vault/helper/errutil" "github.com/hashicorp/vault/logical" "github.com/hashicorp/vault/logical/framework" @@ -59,7 +60,7 @@ func (b *backend) pathRewrapWrite(ctx context.Context, req *logical.Request, d * if batchInputRaw != nil { err = mapstructure.Decode(batchInputRaw, &batchInputItems) if err != nil { - return nil, fmt.Errorf("failed to parse batch input: %v", err) + return nil, errwrap.Wrapf("failed to parse batch input: {{err}}", err) } if len(batchInputItems) == 0 { diff --git a/command/base_flags.go b/command/base_flags.go index 57c251d20..bccf1bf6e 100644 --- a/command/base_flags.go +++ b/command/base_flags.go @@ -648,7 +648,7 @@ func newStringMapValue(def map[string]string, target *map[string]string, hidden func (s *stringMapValue) Set(val string) error { idx := strings.Index(val, "=") if idx == -1 { - return fmt.Errorf("Missing = in KV pair: %s", val) + return fmt.Errorf("missing = in KV pair: %q", val) } if *s.target == nil { diff --git a/command/config.go b/command/config.go index 1b0ef603f..71b5cbc9d 100644 --- a/command/config.go +++ b/command/config.go @@ -77,8 +77,7 @@ func checkHCLKeys(node ast.Node, valid []string) error { for _, item := range list.Items { key := item.Keys[0].Token.Value().(string) if _, ok := validMap[key]; !ok { - result = multierror.Append(result, fmt.Errorf( - "invalid key '%s' on line %d", key, item.Assign.Line)) + result = multierror.Append(result, fmt.Errorf("invalid key %q on line %d", key, item.Assign.Line)) } } diff --git a/command/config/config.go b/command/config/config.go index 4697a7494..ebee11ecb 100644 --- a/command/config/config.go +++ b/command/config/config.go @@ -5,6 +5,7 @@ import ( "io/ioutil" "os" + "github.com/hashicorp/errwrap" "github.com/hashicorp/go-multierror" "github.com/hashicorp/hcl" "github.com/hashicorp/hcl/hcl/ast" @@ -56,7 +57,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, fmt.Errorf("Error expanding config path %s: %s", path, err) + return nil, errwrap.Wrapf(fmt.Sprintf("error expanding config path %q: {{err}}", path), err) } contents, err := ioutil.ReadFile(path) @@ -66,7 +67,7 @@ func LoadConfig(path string) (*DefaultConfig, error) { conf, err := ParseConfig(string(contents)) if err != nil { - return nil, fmt.Errorf("Error parsing config file at %s: %q. Ensure that the file is valid; Ansible Vault is known to conflict with it.", path, err) + 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 conf, nil @@ -82,7 +83,7 @@ func ParseConfig(contents string) (*DefaultConfig, error) { // Top-level item should be the object list list, ok := root.Node.(*ast.ObjectList) if !ok { - return nil, fmt.Errorf("Failed to parse config: does not contain a root object") + return nil, fmt.Errorf("failed to parse config; does not contain a root object") } valid := []string{ @@ -119,8 +120,7 @@ func checkHCLKeys(node ast.Node, valid []string) error { for _, item := range list.Items { key := item.Keys[0].Token.Value().(string) if _, ok := validMap[key]; !ok { - result = multierror.Append(result, fmt.Errorf( - "invalid key '%s' on line %d", key, item.Assign.Line)) + result = multierror.Append(result, fmt.Errorf("invalid key %q on line %d", key, item.Assign.Line)) } } diff --git a/command/format.go b/command/format.go index a258cd903..cc864cadb 100644 --- a/command/format.go +++ b/command/format.go @@ -161,7 +161,7 @@ func (t TableFormatter) OutputList(ui cli.Ui, secret *api.Secret, data interface for i, v := range list { typed, ok := v.(string) if !ok { - return fmt.Errorf("Error: %v is not a string", v) + return fmt.Errorf("%v is not a string", v) } keys[i] = typed } diff --git a/command/operator_generate_root.go b/command/operator_generate_root.go index 693aff341..6fa52ad97 100644 --- a/command/operator_generate_root.go +++ b/command/operator_generate_root.go @@ -9,6 +9,7 @@ import ( "os" "strings" + "github.com/hashicorp/errwrap" "github.com/hashicorp/go-uuid" "github.com/hashicorp/vault/api" "github.com/hashicorp/vault/helper/password" @@ -252,14 +253,14 @@ func (c *OperatorGenerateRootCommand) Run(args []string) int { // verifyOTP verifies the given OTP code is exactly 16 bytes. func (c *OperatorGenerateRootCommand) verifyOTP(otp string) error { if len(otp) == 0 { - return fmt.Errorf("No OTP passed in") + return fmt.Errorf("no OTP passed in") } otpBytes, err := base64.StdEncoding.DecodeString(otp) if err != nil { - return fmt.Errorf("Error decoding base64 OTP value: %s", err) + return errwrap.Wrapf("error decoding base64 OTP value: {{err}}", err) } if otpBytes == nil || len(otpBytes) != 16 { - return fmt.Errorf("Decoded OTP value is invalid or wrong length") + return fmt.Errorf("decoded OTP value is invalid or wrong length") } return nil diff --git a/command/server.go b/command/server.go index 4ac201f1b..fde59a607 100644 --- a/command/server.go +++ b/command/server.go @@ -1037,7 +1037,7 @@ func (c *ServerCommand) enableDev(core *vault.Core, coreConfig *vault.CoreConfig isLeader, _, _, err := core.Leader() if err != nil && err != vault.ErrHANotEnabled { - return nil, fmt.Errorf("failed to check active status: %v", err) + return nil, errwrap.Wrapf("failed to check active status: {{err}}", err) } if err == nil { leaderCount := 5 @@ -1050,7 +1050,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, fmt.Errorf("failed to check active status: %v", err) + return nil, errwrap.Wrapf("failed to check active status: {{err}}", err) } leaderCount-- } @@ -1072,13 +1072,13 @@ func (c *ServerCommand) enableDev(core *vault.Core, coreConfig *vault.CoreConfig } resp, err := core.HandleRequest(req) if err != nil { - return nil, fmt.Errorf("failed to create root token with ID %s: %s", coreConfig.DevToken, err) + return nil, errwrap.Wrapf(fmt.Sprintf("failed to create root token with ID %q: {{err}}", coreConfig.DevToken), err) } if resp == nil { - return nil, fmt.Errorf("nil response when creating root token with ID %s", coreConfig.DevToken) + return nil, fmt.Errorf("nil response when creating root token with ID %q", coreConfig.DevToken) } if resp.Auth == nil { - return nil, fmt.Errorf("nil auth when creating root token with ID %s", coreConfig.DevToken) + return nil, fmt.Errorf("nil auth when creating root token with ID %q", coreConfig.DevToken) } init.RootToken = resp.Auth.ClientToken @@ -1088,7 +1088,7 @@ func (c *ServerCommand) enableDev(core *vault.Core, coreConfig *vault.CoreConfig req.Data = nil resp, err = core.HandleRequest(req) if err != nil { - return nil, fmt.Errorf("failed to revoke initial root token: %s", err) + return nil, errwrap.Wrapf("failed to revoke initial root token: {{err}}", err) } } @@ -1355,7 +1355,7 @@ func (c *ServerCommand) detectRedirect(detect physical.RedirectDetect, if val, ok := list.Config["tls_disable"]; ok { disable, err := parseutil.ParseBool(val) if err != nil { - return "", fmt.Errorf("tls_disable: %s", err) + return "", errwrap.Wrapf("tls_disable: {{err}}", err) } if disable { @@ -1483,7 +1483,7 @@ func (c *ServerCommand) setupTelemetry(config *server.Config) error { sink, err := datadog.NewDogStatsdSink(telConfig.DogStatsDAddr, metricsConf.HostName) if err != nil { - return fmt.Errorf("failed to start DogStatsD sink. Got: %s", err) + return errwrap.Wrapf("failed to start DogStatsD sink: {{err}}", err) } sink.SetTags(tags) fanout = append(fanout, sink) @@ -1512,7 +1512,7 @@ func (c *ServerCommand) Reload(lock *sync.RWMutex, reloadFuncs *map[string][]rel for _, relFunc := range relFuncs { if relFunc != nil { if err := relFunc(nil); err != nil { - reloadErrors = multierror.Append(reloadErrors, fmt.Errorf("Error encountered reloading listener: %v", err)) + reloadErrors = multierror.Append(reloadErrors, errwrap.Wrapf("error encountered reloading listener: {{err}}", err)) } } } @@ -1521,7 +1521,7 @@ func (c *ServerCommand) Reload(lock *sync.RWMutex, reloadFuncs *map[string][]rel for _, relFunc := range relFuncs { if relFunc != nil { if err := relFunc(nil); err != nil { - reloadErrors = multierror.Append(reloadErrors, fmt.Errorf("Error encountered reloading file audit device at path %s: %v", strings.TrimPrefix(k, "audit_file|"), err)) + reloadErrors = multierror.Append(reloadErrors, errwrap.Wrapf(fmt.Sprintf("error encountered reloading file audit device at path %q: {{err}}", strings.TrimPrefix(k, "audit_file|")), err)) } } } @@ -1548,7 +1548,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, 0644) if err != nil { - return fmt.Errorf("could not open pid file: %v", err) + return errwrap.Wrapf("could not open pid file: {{err}}", err) } defer pidFile.Close() @@ -1556,7 +1556,7 @@ func (c *ServerCommand) storePidFile(pidPath string) error { pid := os.Getpid() _, err = pidFile.WriteString(fmt.Sprintf("%d", pid)) if err != nil { - return fmt.Errorf("could not write to pid file: %v", err) + return errwrap.Wrapf("could not write to pid file: {{err}}", err) } return nil } diff --git a/command/server/config.go b/command/server/config.go index b24a5e0f9..b150b83bd 100644 --- a/command/server/config.go +++ b/command/server/config.go @@ -10,6 +10,7 @@ import ( "strings" "time" + "github.com/hashicorp/errwrap" log "github.com/hashicorp/go-hclog" "github.com/hashicorp/go-multierror" @@ -430,49 +431,49 @@ func ParseConfig(d string, logger log.Logger) (*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, fmt.Errorf("error parsing 'storage': %s", err) + return nil, errwrap.Wrapf("error parsing 'storage': {{err}}", err) } } else { if o := list.Filter("backend"); len(o.Items) > 0 { if err := parseStorage(&result, o, "backend"); err != nil { - return nil, fmt.Errorf("error parsing 'backend': %s", err) + return nil, errwrap.Wrapf("error parsing 'backend': {{err}}", err) } } } if o := list.Filter("ha_storage"); len(o.Items) > 0 { if err := parseHAStorage(&result, o, "ha_storage"); err != nil { - return nil, fmt.Errorf("error parsing 'ha_storage': %s", err) + return nil, errwrap.Wrapf("error parsing 'ha_storage': {{err}}", err) } } else { if o := list.Filter("ha_backend"); len(o.Items) > 0 { if err := parseHAStorage(&result, o, "ha_backend"); err != nil { - return nil, fmt.Errorf("error parsing 'ha_backend': %s", err) + return nil, errwrap.Wrapf("error parsing 'ha_backend': {{err}}", err) } } } if o := list.Filter("hsm"); len(o.Items) > 0 { if err := parseSeal(&result, o, "hsm"); err != nil { - return nil, fmt.Errorf("error parsing 'hsm': %s", err) + return nil, errwrap.Wrapf("error parsing 'hsm': {{err}}", err) } } if o := list.Filter("seal"); len(o.Items) > 0 { if err := parseSeal(&result, o, "seal"); err != nil { - return nil, fmt.Errorf("error parsing 'seal': %s", err) + return nil, errwrap.Wrapf("error parsing 'seal': {{err}}", err) } } if o := list.Filter("listener"); len(o.Items) > 0 { if err := parseListeners(&result, o); err != nil { - return nil, fmt.Errorf("error parsing 'listener': %s", err) + return nil, errwrap.Wrapf("error parsing 'listener': {{err}}", err) } } if o := list.Filter("telemetry"); len(o.Items) > 0 { if err := parseTelemetry(&result, o); err != nil { - return nil, fmt.Errorf("error parsing 'telemetry': %s", err) + return nil, errwrap.Wrapf("error parsing 'telemetry': {{err}}", err) } } @@ -493,9 +494,7 @@ func LoadConfigDir(dir string, logger log.Logger) (*Config, error) { return nil, err } if !fi.IsDir() { - return nil, fmt.Errorf( - "configuration path must be a directory: %s", - dir) + return nil, fmt.Errorf("configuration path must be a directory: %q", dir) } var files []string @@ -534,7 +533,7 @@ func LoadConfigDir(dir string, logger log.Logger) (*Config, error) { for _, f := range files { config, err := LoadConfigFile(f, logger) if err != nil { - return nil, fmt.Errorf("Error loading %s: %s", f, err) + return nil, errwrap.Wrapf(fmt.Sprintf("error loading %q: {{err}}", f), err) } if result == nil { @@ -866,8 +865,7 @@ func checkHCLKeys(node ast.Node, valid []string) error { for _, item := range list.Items { key := item.Keys[0].Token.Value().(string) if _, ok := validMap[key]; !ok { - result = multierror.Append(result, fmt.Errorf( - "invalid key '%s' on line %d", key, item.Assign.Line)) + result = multierror.Append(result, fmt.Errorf("invalid key %q on line %d", key, item.Assign.Line)) } } diff --git a/command/server/listener.go b/command/server/listener.go index f820320bc..3bd6b580d 100644 --- a/command/server/listener.go +++ b/command/server/listener.go @@ -32,7 +32,7 @@ var BuiltinListeners = map[string]ListenerFactory{ func NewListener(t string, config map[string]interface{}, logger io.Writer, ui cli.Ui) (net.Listener, map[string]string, reload.ReloadFunc, error) { f, ok := BuiltinListeners[t] if !ok { - return nil, nil, nil, fmt.Errorf("unknown listener type: %s", t) + return nil, nil, nil, fmt.Errorf("unknown listener type: %q", t) } return f(config, logger, ui) @@ -58,12 +58,12 @@ func listenerWrapProxy(ln net.Listener, config map[string]interface{}) (net.List Behavior: behavior, } if err := proxyProtoConfig.SetAuthorizedAddrs(authorizedAddrsRaw); err != nil { - return nil, fmt.Errorf("failed parsing proxy_protocol_authorized_addrs: %v", err) + return nil, errwrap.Wrapf("failed parsing proxy_protocol_authorized_addrs: {{err}}", err) } newLn, err := proxyutil.WrapInProxyProto(ln, proxyProtoConfig) if err != nil { - return nil, fmt.Errorf("failed configuring PROXY protocol wrapper: %s", err) + return nil, errwrap.Wrapf("failed configuring PROXY protocol wrapper: {{err}}", err) } return newLn, nil @@ -79,7 +79,7 @@ func listenerWrapTLS( if v, ok := config["tls_disable"]; ok { disabled, err := parseutil.ParseBool(v) if err != nil { - return nil, nil, nil, fmt.Errorf("invalid value for 'tls_disable': %v", err) + return nil, nil, nil, errwrap.Wrapf("invalid value for 'tls_disable': {{err}}", err) } if disabled { return ln, props, nil, nil @@ -128,21 +128,21 @@ PASSPHRASECORRECT: tlsConf.NextProtos = []string{"h2", "http/1.1"} tlsConf.MinVersion, ok = tlsutil.TLSLookup[tlsvers] if !ok { - return nil, nil, nil, fmt.Errorf("'tls_min_version' value %s not supported, please specify one of [tls10,tls11,tls12]", tlsvers) + return nil, nil, nil, fmt.Errorf("'tls_min_version' value %q not supported, please specify one of [tls10,tls11,tls12]", tlsvers) } tlsConf.ClientAuth = tls.RequestClientCert if v, ok := config["tls_cipher_suites"]; ok { ciphers, err := tlsutil.ParseCiphers(v.(string)) if err != nil { - return nil, nil, nil, fmt.Errorf("invalid value for 'tls_cipher_suites': %v", err) + return nil, nil, nil, errwrap.Wrapf("invalid value for 'tls_cipher_suites': {{err}}", err) } tlsConf.CipherSuites = ciphers } if v, ok := config["tls_prefer_server_cipher_suites"]; ok { preferServer, err := parseutil.ParseBool(v) if err != nil { - return nil, nil, nil, fmt.Errorf("invalid value for 'tls_prefer_server_cipher_suites': %v", err) + return nil, nil, nil, errwrap.Wrapf("invalid value for 'tls_prefer_server_cipher_suites': {{err}}", err) } tlsConf.PreferServerCipherSuites = preferServer } @@ -151,7 +151,7 @@ PASSPHRASECORRECT: if v, ok := config["tls_require_and_verify_client_cert"]; ok { requireVerifyCerts, err = parseutil.ParseBool(v) if err != nil { - return nil, nil, nil, fmt.Errorf("invalid value for 'tls_require_and_verify_client_cert': %v", err) + return nil, nil, nil, errwrap.Wrapf("invalid value for 'tls_require_and_verify_client_cert': {{err}}", err) } if requireVerifyCerts { tlsConf.ClientAuth = tls.RequireAndVerifyClientCert @@ -160,7 +160,7 @@ PASSPHRASECORRECT: caPool := x509.NewCertPool() data, err := ioutil.ReadFile(tlsClientCaFile.(string)) if err != nil { - return nil, nil, nil, fmt.Errorf("failed to read tls_client_ca_file: %v", err) + return nil, nil, nil, errwrap.Wrapf("failed to read tls_client_ca_file: {{err}}", err) } if !caPool.AppendCertsFromPEM(data) { @@ -172,7 +172,7 @@ PASSPHRASECORRECT: if v, ok := config["tls_disable_client_certs"]; ok { disableClientCerts, err := parseutil.ParseBool(v) if err != nil { - return nil, nil, nil, fmt.Errorf("invalid value for 'tls_disable_client_certs': %v", err) + return nil, nil, nil, errwrap.Wrapf("invalid value for 'tls_disable_client_certs': {{err}}", err) } if disableClientCerts && requireVerifyCerts { return nil, nil, nil, fmt.Errorf("'tls_disable_client_certs' and 'tls_require_and_verify_client_cert' are mutually exclusive") diff --git a/command/ssh.go b/command/ssh.go index d36aac4ba..0d1ad0a2b 100644 --- a/command/ssh.go +++ b/command/ssh.go @@ -11,6 +11,7 @@ import ( "strings" "syscall" + "github.com/hashicorp/errwrap" "github.com/hashicorp/vault/api" "github.com/hashicorp/vault/builtin/logical/ssh" "github.com/mitchellh/cli" @@ -697,15 +698,14 @@ func (c *SSHCommand) defaultRole(mountPoint, ip string) (string, error) { } secret, err := c.client.Logical().Write(mountPoint+"/lookup", data) if err != nil { - return "", fmt.Errorf("Error finding roles for IP %q: %q", ip, err) - + return "", errwrap.Wrapf(fmt.Sprintf("error finding roles for IP %q: {{err}}", ip), err) } if secret == nil || secret.Data == nil { - return "", fmt.Errorf("Error finding roles for IP %q: %q", ip, err) + return "", errwrap.Wrapf(fmt.Sprintf("error finding roles for IP %q: {{err}}", ip), err) } if secret.Data["roles"] == nil { - return "", fmt.Errorf("No matching roles found for IP %q", ip) + return "", fmt.Errorf("no matching roles found for IP %q", ip) } if len(secret.Data["roles"].([]interface{})) == 1 { @@ -716,7 +716,7 @@ func (c *SSHCommand) defaultRole(mountPoint, ip string) (string, error) { roleNames += item.(string) + ", " } roleNames = strings.TrimRight(roleNames, ", ") - return "", fmt.Errorf("Roles:%q. "+` + return "", fmt.Errorf("Roles: %q. "+` Multiple roles are registered for this IP. Select a role using '-role' option. Note that all roles may not be permitted, based on ACLs.`, roleNames) diff --git a/command/token/helper_external.go b/command/token/helper_external.go index 4483074af..edd95d5e1 100644 --- a/command/token/helper_external.go +++ b/command/token/helper_external.go @@ -8,6 +8,8 @@ import ( "path/filepath" "runtime" "strings" + + "github.com/hashicorp/errwrap" ) // ExternalTokenHelperPath takes the configured path to a helper and expands it to @@ -59,11 +61,10 @@ type ExternalTokenHelper struct { func (h *ExternalTokenHelper) Erase() error { cmd, err := h.cmd("erase") if err != nil { - return fmt.Errorf("Error: %s", err) + return err } if output, err := cmd.CombinedOutput(); err != nil { - return fmt.Errorf( - "Error: %s\n\n%s", err, string(output)) + return errwrap.Wrapf(fmt.Sprintf("%q: {{err}}", string(output)), err) } return nil } @@ -73,13 +74,12 @@ func (h *ExternalTokenHelper) Get() (string, error) { var buf, stderr bytes.Buffer cmd, err := h.cmd("get") if err != nil { - return "", fmt.Errorf("Error: %s", err) + return "", err } cmd.Stdout = &buf cmd.Stderr = &stderr if err := cmd.Run(); err != nil { - return "", fmt.Errorf( - "Error: %s\n\n%s", err, stderr.String()) + return "", errwrap.Wrapf(fmt.Sprintf("%q: {{err}}", stderr.String()), err) } return buf.String(), nil @@ -90,12 +90,11 @@ func (h *ExternalTokenHelper) Store(v string) error { buf := bytes.NewBufferString(v) cmd, err := h.cmd("store") if err != nil { - return fmt.Errorf("Error: %s", err) + return err } cmd.Stdin = buf if output, err := cmd.CombinedOutput(); err != nil { - return fmt.Errorf( - "Error: %s\n\n%s", err, string(output)) + return errwrap.Wrapf(fmt.Sprintf("%q: {{err}}", string(output)), err) } return nil diff --git a/command/token/helper_internal.go b/command/token/helper_internal.go index 58dceaebc..f3f527be0 100644 --- a/command/token/helper_internal.go +++ b/command/token/helper_internal.go @@ -23,7 +23,7 @@ type InternalTokenHelper struct { func (i *InternalTokenHelper) populateTokenPath() { homePath, err := homedir.Dir() if err != nil { - panic(fmt.Errorf("error getting user's home directory: %v", err)) + panic(fmt.Sprintf("error getting user's home directory: %v", err)) } i.tokenPath = homePath + "/.vault-token" } diff --git a/helper/certutil/types.go b/helper/certutil/types.go index 39773c791..6a5251cf8 100644 --- a/helper/certutil/types.go +++ b/helper/certutil/types.go @@ -20,6 +20,7 @@ import ( "math/big" "strings" + "github.com/hashicorp/errwrap" "github.com/hashicorp/vault/helper/errutil" ) @@ -293,10 +294,10 @@ func (p *ParsedCertBundle) Verify() error { if p.PrivateKey != nil && p.Certificate != nil { equal, err := ComparePublicKeys(p.Certificate.PublicKey, p.PrivateKey.Public()) if err != nil { - return fmt.Errorf("could not compare public and private keys: %s", err) + return errwrap.Wrapf("could not compare public and private keys: {{err}}", err) } if !equal { - return fmt.Errorf("Public key of certificate does not match private key") + return fmt.Errorf("public key of certificate does not match private key") } } @@ -307,7 +308,7 @@ func (p *ParsedCertBundle) Verify() error { return fmt.Errorf("certificate %d of certificate chain is not a certificate authority", i+1) } if !bytes.Equal(certPath[i].Certificate.AuthorityKeyId, caCert.Certificate.SubjectKeyId) { - return fmt.Errorf("certificate %d of certificate chain ca trust path is incorrect (%s/%s)", + return fmt.Errorf("certificate %d of certificate chain ca trust path is incorrect (%q/%q)", i+1, certPath[i].Certificate.Subject.CommonName, caCert.Certificate.Subject.CommonName) } } @@ -556,13 +557,13 @@ func (p *ParsedCertBundle) GetTLSConfig(usage TLSUsage) (*tls.Config, error) { // Technically we only need one cert, but this doesn't duplicate code certBundle, err := p.ToCertBundle() if err != nil { - return nil, fmt.Errorf("Error converting parsed bundle to string bundle when getting TLS config: %s", err) + return nil, errwrap.Wrapf("error converting parsed bundle to string bundle when getting TLS config: {{err}}", err) } caPool := x509.NewCertPool() ok := caPool.AppendCertsFromPEM([]byte(certBundle.CAChain[0])) if !ok { - return nil, fmt.Errorf("Could not append CA certificate") + return nil, fmt.Errorf("could not append CA certificate") } if usage&TLSServer > 0 { diff --git a/helper/cidrutil/cidr.go b/helper/cidrutil/cidr.go index 2d89d8468..13552232c 100644 --- a/helper/cidrutil/cidr.go +++ b/helper/cidrutil/cidr.go @@ -5,6 +5,7 @@ import ( "net" "strings" + "github.com/hashicorp/errwrap" "github.com/hashicorp/vault/helper/strutil" ) @@ -102,7 +103,7 @@ func Subset(cidr1, cidr2 string) (bool, error) { ip1, net1, err := net.ParseCIDR(cidr1) if err != nil { - return false, fmt.Errorf("failed to parse the CIDR to be checked against: %q", err) + return false, errwrap.Wrapf("failed to parse the CIDR to be checked against: {{err}}", err) } zeroAddr := false @@ -120,7 +121,7 @@ func Subset(cidr1, cidr2 string) (bool, error) { ip2, net2, err := net.ParseCIDR(cidr2) if err != nil { - return false, fmt.Errorf("failed to parse the CIDR that needs to be checked: %q", err) + return false, errwrap.Wrapf("failed to parse the CIDR that needs to be checked: {{err}}", err) } zeroAddr = false diff --git a/helper/compressutil/compress.go b/helper/compressutil/compress.go index 4acebe31c..a7fb87bcf 100644 --- a/helper/compressutil/compress.go +++ b/helper/compressutil/compress.go @@ -8,6 +8,7 @@ import ( "io" "github.com/golang/snappy" + "github.com/hashicorp/errwrap" ) const ( @@ -107,7 +108,7 @@ func Compress(data []byte, config *CompressionConfig) ([]byte, error) { } if err != nil { - return nil, fmt.Errorf("failed to create a compression writer; err: %v", err) + return nil, errwrap.Wrapf("failed to create a compression writer: {{err}}", err) } if writer == nil { @@ -117,7 +118,7 @@ func Compress(data []byte, config *CompressionConfig) ([]byte, error) { // Compress the input and place it in the same buffer containing the // canary byte. if _, err = writer.Write(data); err != nil { - return nil, fmt.Errorf("failed to compress input data; err: %v", err) + return nil, errwrap.Wrapf("failed to compress input data: err: {{err}}", err) } // Close the io.WriteCloser @@ -172,7 +173,7 @@ func Decompress(data []byte) ([]byte, bool, error) { return nil, true, nil } if err != nil { - return nil, false, fmt.Errorf("failed to create a compression reader; err: %v", err) + return nil, false, errwrap.Wrapf("failed to create a compression reader: {{err}}", err) } if reader == nil { return nil, false, fmt.Errorf("failed to create a compression reader") diff --git a/helper/flag-kv/flag.go b/helper/flag-kv/flag.go index 3e8a8f7c1..06ae27111 100644 --- a/helper/flag-kv/flag.go +++ b/helper/flag-kv/flag.go @@ -16,7 +16,7 @@ func (v *Flag) String() string { func (v *Flag) Set(raw string) error { idx := strings.Index(raw, "=") if idx == -1 { - return fmt.Errorf("No '=' value in arg: %s", raw) + return fmt.Errorf("no '=' value in arg: %q", raw) } if *v == nil { diff --git a/helper/identity/identity.go b/helper/identity/identity.go index a0d812a96..b1eab23ef 100644 --- a/helper/identity/identity.go +++ b/helper/identity/identity.go @@ -4,6 +4,7 @@ import ( "fmt" "github.com/gogo/protobuf/proto" + "github.com/hashicorp/errwrap" ) func (g *Group) Clone() (*Group, error) { @@ -13,13 +14,13 @@ func (g *Group) Clone() (*Group, error) { marshaledGroup, err := proto.Marshal(g) if err != nil { - return nil, fmt.Errorf("failed to marshal group: %v", err) + return nil, errwrap.Wrapf("failed to marshal group: {{err}}", err) } var clonedGroup Group err = proto.Unmarshal(marshaledGroup, &clonedGroup) if err != nil { - return nil, fmt.Errorf("failed to unmarshal group: %v", err) + return nil, errwrap.Wrapf("failed to unmarshal group: {{err}}", err) } return &clonedGroup, nil @@ -32,13 +33,13 @@ func (e *Entity) Clone() (*Entity, error) { marshaledEntity, err := proto.Marshal(e) if err != nil { - return nil, fmt.Errorf("failed to marshal entity: %v", err) + return nil, errwrap.Wrapf("failed to marshal entity: {{err}}", err) } var clonedEntity Entity err = proto.Unmarshal(marshaledEntity, &clonedEntity) if err != nil { - return nil, fmt.Errorf("failed to unmarshal entity: %v", err) + return nil, errwrap.Wrapf("failed to unmarshal entity: {{err}}", err) } return &clonedEntity, nil @@ -51,13 +52,13 @@ func (p *Alias) Clone() (*Alias, error) { marshaledAlias, err := proto.Marshal(p) if err != nil { - return nil, fmt.Errorf("failed to marshal alias: %v", err) + return nil, errwrap.Wrapf("failed to marshal alias: {{err}}", err) } var clonedAlias Alias err = proto.Unmarshal(marshaledAlias, &clonedAlias) if err != nil { - return nil, fmt.Errorf("failed to unmarshal alias: %v", err) + return nil, errwrap.Wrapf("failed to unmarshal alias: {{err}}", err) } return &clonedAlias, nil diff --git a/helper/jsonutil/json.go b/helper/jsonutil/json.go index b560279bd..d03ddef5f 100644 --- a/helper/jsonutil/json.go +++ b/helper/jsonutil/json.go @@ -7,6 +7,7 @@ import ( "fmt" "io" + "github.com/hashicorp/errwrap" "github.com/hashicorp/vault/helper/compressutil" ) @@ -64,7 +65,7 @@ func DecodeJSON(data []byte, out interface{}) error { // Decompress the data if it was compressed in the first place decompressedBytes, uncompressed, err := compressutil.Decompress(data) if err != nil { - return fmt.Errorf("failed to decompress JSON: err: %v", err) + return errwrap.Wrapf("failed to decompress JSON: {{err}}", err) } if !uncompressed && (decompressedBytes == nil || len(decompressedBytes) == 0) { return fmt.Errorf("decompressed data being decoded is invalid") diff --git a/helper/keysutil/lock_manager.go b/helper/keysutil/lock_manager.go index a5350cc87..529b3469d 100644 --- a/helper/keysutil/lock_manager.go +++ b/helper/keysutil/lock_manager.go @@ -8,6 +8,7 @@ import ( "sync" "time" + "github.com/hashicorp/errwrap" "github.com/hashicorp/vault/helper/jsonutil" "github.com/hashicorp/vault/logical" ) @@ -270,7 +271,7 @@ func (lm *LockManager) RestorePolicy(ctx context.Context, storage logical.Storag if keyData.ArchivedKeys != nil { err = keyData.Policy.storeArchive(ctx, storage, keyData.ArchivedKeys) if err != nil { - return fmt.Errorf("failed to restore archived keys for policy %q: %v", name, err) + return errwrap.Wrapf(fmt.Sprintf("failed to restore archived keys for policy %q: {{err}}", name), err) } } @@ -283,7 +284,7 @@ func (lm *LockManager) RestorePolicy(ctx context.Context, storage logical.Storag // Restore the policy. This will also attempt to adjust the archive. err = keyData.Policy.Persist(ctx, storage) if err != nil { - return fmt.Errorf("failed to restore the policy %q: %v", name, err) + return errwrap.Wrapf(fmt.Sprintf("failed to restore the policy %q: {{err}}", name), err) } // Update the cache to contain the restored policy @@ -484,12 +485,12 @@ func (lm *LockManager) DeletePolicy(ctx context.Context, storage logical.Storage err = storage.Delete(ctx, "policy/"+name) if err != nil { - return fmt.Errorf("error deleting policy %s: %s", name, err) + return errwrap.Wrapf(fmt.Sprintf("error deleting policy %q: {{err}}", name), err) } err = storage.Delete(ctx, "archive/"+name) if err != nil { - return fmt.Errorf("error deleting archive %s: %s", name, err) + return errwrap.Wrapf(fmt.Sprintf("error deleting archive %q: {{err}}", name), err) } if lm.CacheActive() { diff --git a/helper/keysutil/policy.go b/helper/keysutil/policy.go index 540092922..7ea2c9489 100644 --- a/helper/keysutil/policy.go +++ b/helper/keysutil/policy.go @@ -30,6 +30,7 @@ import ( "golang.org/x/crypto/ed25519" "golang.org/x/crypto/hkdf" + "github.com/hashicorp/errwrap" uuid "github.com/hashicorp/go-uuid" "github.com/hashicorp/vault/helper/errutil" "github.com/hashicorp/vault/helper/jsonutil" @@ -1227,7 +1228,7 @@ func (p *Policy) Rotate(ctx context.Context, storage logical.Storage) (retErr er entry.EC_Y = privKey.Y derBytes, err := x509.MarshalPKIXPublicKey(privKey.Public()) if err != nil { - return fmt.Errorf("error marshaling public key: %s", err) + return errwrap.Wrapf("error marshaling public key: {{err}}", err) } pemBlock := &pem.Block{ Type: "PUBLIC KEY", @@ -1308,7 +1309,7 @@ func (p *Policy) Backup(ctx context.Context, storage logical.Storage) (out strin } err := p.Persist(ctx, storage) if err != nil { - return "", fmt.Errorf("failed to persist policy with backup info: %v", err) + return "", errwrap.Wrapf("failed to persist policy with backup info: {{err}}", err) } // Load the archive only after persisting the policy as the archive can get diff --git a/helper/kv-builder/builder.go b/helper/kv-builder/builder.go index 685624a12..b0292b92e 100644 --- a/helper/kv-builder/builder.go +++ b/helper/kv-builder/builder.go @@ -8,6 +8,7 @@ import ( "os" "strings" + "github.com/hashicorp/errwrap" "github.com/hashicorp/vault/helper/jsonutil" "github.com/mitchellh/mapstructure" ) @@ -30,7 +31,7 @@ func (b *Builder) Map() map[string]interface{} { func (b *Builder) Add(args ...string) error { for _, a := range args { if err := b.add(a); err != nil { - return fmt.Errorf("Invalid key/value pair '%s': %s", a, err) + return errwrap.Wrapf(fmt.Sprintf("invalid key/value pair %q: {{err}}", a), err) } } @@ -87,7 +88,7 @@ func (b *Builder) add(raw string) error { if value[0] == '@' { contents, err := ioutil.ReadFile(value[1:]) if err != nil { - return fmt.Errorf("error reading file: %s", err) + return errwrap.Wrapf("error reading file: {{err}}", err) } value = string(contents) diff --git a/helper/mfa/duo/path_duo_access.go b/helper/mfa/duo/path_duo_access.go index 4b577ef0a..04ed79a25 100644 --- a/helper/mfa/duo/path_duo_access.go +++ b/helper/mfa/duo/path_duo_access.go @@ -70,7 +70,7 @@ func GetDuoAuthClient(ctx context.Context, req *logical.Request, config *DuoConf return nil, err } if check == nil { - return nil, fmt.Errorf("Could not connect to Duo; got nil result back from API check call") + return nil, fmt.Errorf("could not connect to Duo; got nil result back from API check call") } var msg, detail string if check.StatResult.Message != nil { @@ -80,7 +80,7 @@ func GetDuoAuthClient(ctx context.Context, req *logical.Request, config *DuoConf detail = *check.StatResult.Message_Detail } if check.StatResult.Stat != "OK" { - return nil, fmt.Errorf("Could not connect to Duo: %s (%s)", msg, detail) + return nil, fmt.Errorf("could not connect to Duo: %q (%q)", msg, detail) } return duoAuthClient, nil } diff --git a/helper/password/password_solaris.go b/helper/password/password_solaris.go index 43ad722cf..66ec86dbc 100644 --- a/helper/password/password_solaris.go +++ b/helper/password/password_solaris.go @@ -13,7 +13,7 @@ import ( func read(f *os.File) (string, error) { fd := int(f.Fd()) if !isTerminal(fd) { - return "", fmt.Errorf("File descriptor %d is not a terminal", fd) + return "", fmt.Errorf("file descriptor %d is not a terminal", fd) } oldState, err := makeRaw(fd) diff --git a/helper/password/password_unix.go b/helper/password/password_unix.go index 5ce7501cc..6d04978c3 100644 --- a/helper/password/password_unix.go +++ b/helper/password/password_unix.go @@ -12,7 +12,7 @@ import ( func read(f *os.File) (string, error) { fd := int(f.Fd()) if !terminal.IsTerminal(fd) { - return "", fmt.Errorf("File descriptor %d is not a terminal", fd) + return "", fmt.Errorf("file descriptor %d is not a terminal", fd) } oldState, err := terminal.MakeRaw(fd) diff --git a/helper/pgpkeys/encrypt_decrypt.go b/helper/pgpkeys/encrypt_decrypt.go index d8b7f605c..eef4c5ed0 100644 --- a/helper/pgpkeys/encrypt_decrypt.go +++ b/helper/pgpkeys/encrypt_decrypt.go @@ -5,6 +5,7 @@ import ( "encoding/base64" "fmt" + "github.com/hashicorp/errwrap" "github.com/keybase/go-crypto/openpgp" "github.com/keybase/go-crypto/openpgp/packet" ) @@ -17,7 +18,7 @@ import ( // thoroughly tested in the init and rekey command unit tests func EncryptShares(input [][]byte, pgpKeys []string) ([]string, [][]byte, error) { if len(input) != len(pgpKeys) { - return nil, nil, fmt.Errorf("Mismatch between number items to encrypt and number of PGP keys") + return nil, nil, fmt.Errorf("mismatch between number items to encrypt and number of PGP keys") } encryptedShares := make([][]byte, 0, len(pgpKeys)) entities, err := GetEntities(pgpKeys) @@ -28,11 +29,11 @@ func EncryptShares(input [][]byte, pgpKeys []string) ([]string, [][]byte, error) ctBuf := bytes.NewBuffer(nil) pt, err := openpgp.Encrypt(ctBuf, []*openpgp.Entity{entity}, nil, nil, nil) if err != nil { - return nil, nil, fmt.Errorf("Error setting up encryption for PGP message: %s", err) + return nil, nil, errwrap.Wrapf("error setting up encryption for PGP message: {{err}}", err) } _, err = pt.Write(input[i]) if err != nil { - return nil, nil, fmt.Errorf("Error encrypting PGP message: %s", err) + return nil, nil, errwrap.Wrapf("error encrypting PGP message: {{err}}", err) } pt.Close() encryptedShares = append(encryptedShares, ctBuf.Bytes()) @@ -72,11 +73,11 @@ func GetEntities(pgpKeys []string) ([]*openpgp.Entity, error) { for _, keystring := range pgpKeys { data, err := base64.StdEncoding.DecodeString(keystring) if err != nil { - return nil, fmt.Errorf("Error decoding given PGP key: %s", err) + return nil, errwrap.Wrapf("error decoding given PGP key: {{err}}", err) } entity, err := openpgp.ReadEntity(packet.NewReader(bytes.NewBuffer(data))) if err != nil { - return nil, fmt.Errorf("Error parsing given PGP key: %s", err) + return nil, errwrap.Wrapf("error parsing given PGP key: {{err}}", err) } ret = append(ret, entity) } @@ -91,23 +92,23 @@ func GetEntities(pgpKeys []string) ([]*openpgp.Entity, error) { func DecryptBytes(encodedCrypt, privKey string) (*bytes.Buffer, error) { privKeyBytes, err := base64.StdEncoding.DecodeString(privKey) if err != nil { - return nil, fmt.Errorf("Error decoding base64 private key: %s", err) + return nil, errwrap.Wrapf("error decoding base64 private key: {{err}}", err) } cryptBytes, err := base64.StdEncoding.DecodeString(encodedCrypt) if err != nil { - return nil, fmt.Errorf("Error decoding base64 crypted bytes: %s", err) + return nil, errwrap.Wrapf("error decoding base64 crypted bytes: {{err}}", err) } entity, err := openpgp.ReadEntity(packet.NewReader(bytes.NewBuffer(privKeyBytes))) if err != nil { - return nil, fmt.Errorf("Error parsing private key: %s", err) + return nil, errwrap.Wrapf("error parsing private key: {{err}}", err) } entityList := &openpgp.EntityList{entity} md, err := openpgp.ReadMessage(bytes.NewBuffer(cryptBytes), entityList, nil, nil) if err != nil { - return nil, fmt.Errorf("Error decrypting the messages: %s", err) + return nil, errwrap.Wrapf("error decrypting the messages: {{err}}", err) } ptBuf := bytes.NewBuffer(nil) diff --git a/helper/pgpkeys/flag.go b/helper/pgpkeys/flag.go index a7371e50a..bb0f367d6 100644 --- a/helper/pgpkeys/flag.go +++ b/helper/pgpkeys/flag.go @@ -8,6 +8,7 @@ import ( "os" "strings" + "github.com/hashicorp/errwrap" "github.com/keybase/go-crypto/openpgp" ) @@ -115,16 +116,16 @@ func ReadPGPFile(path string) (string, error) { entityList, err := openpgp.ReadArmoredKeyRing(keyReader) if err == nil { if len(entityList) != 1 { - return "", fmt.Errorf("more than one key found in file %s", path) + return "", fmt.Errorf("more than one key found in file %q", path) } if entityList[0] == nil { - return "", fmt.Errorf("primary key was nil for file %s", path) + return "", fmt.Errorf("primary key was nil for file %q", path) } serializedEntity := bytes.NewBuffer(nil) err = entityList[0].Serialize(serializedEntity) if err != nil { - return "", fmt.Errorf("error serializing entity for file %s: %s", path, err) + return "", errwrap.Wrapf(fmt.Sprintf("error serializing entity for file %q: {{err}}", path), err) } return base64.StdEncoding.EncodeToString(serializedEntity.Bytes()), nil diff --git a/helper/pgpkeys/keybase.go b/helper/pgpkeys/keybase.go index c116194b0..eba067762 100644 --- a/helper/pgpkeys/keybase.go +++ b/helper/pgpkeys/keybase.go @@ -6,6 +6,7 @@ import ( "fmt" "strings" + "github.com/hashicorp/errwrap" "github.com/hashicorp/go-cleanhttp" "github.com/hashicorp/vault/helper/jsonutil" "github.com/keybase/go-crypto/openpgp" @@ -75,7 +76,7 @@ func FetchKeybasePubkeys(input []string) (map[string]string, error) { } if out.Status.Name != "OK" { - return nil, fmt.Errorf("got non-OK response: %s", out.Status.Name) + return nil, fmt.Errorf("got non-OK response: %q", out.Status.Name) } missingNames := make([]string, 0, len(usernames)) @@ -92,16 +93,16 @@ func FetchKeybasePubkeys(input []string) (map[string]string, error) { return nil, err } if len(entityList) != 1 { - return nil, fmt.Errorf("primary key could not be parsed for user %s", usernames[i]) + return nil, fmt.Errorf("primary key could not be parsed for user %q", usernames[i]) } if entityList[0] == nil { - return nil, fmt.Errorf("primary key was nil for user %s", usernames[i]) + return nil, fmt.Errorf("primary key was nil for user %q", usernames[i]) } serializedEntity.Reset() err = entityList[0].Serialize(serializedEntity) if err != nil { - return nil, fmt.Errorf("error serializing entity for user %s: %s", usernames[i], err) + return nil, errwrap.Wrapf(fmt.Sprintf("error serializing entity for user %q: {{err}}", usernames[i]), err) } // The API returns values in the same ordering requested, so this should properly match @@ -109,7 +110,7 @@ func FetchKeybasePubkeys(input []string) (map[string]string, error) { } if len(missingNames) > 0 { - return nil, fmt.Errorf("unable to fetch keys for user(s) %s from keybase", strings.Join(missingNames, ",")) + return nil, fmt.Errorf("unable to fetch keys for user(s) %q from keybase", strings.Join(missingNames, ",")) } return ret, nil diff --git a/helper/pluginutil/tls.go b/helper/pluginutil/tls.go index a2d4e4e60..d43f77806 100644 --- a/helper/pluginutil/tls.go +++ b/helper/pluginutil/tls.go @@ -10,7 +10,6 @@ import ( "crypto/x509/pkix" "encoding/base64" "errors" - "fmt" "net/url" "os" "time" @@ -79,7 +78,7 @@ func generateCert() ([]byte, *ecdsa.PrivateKey, error) { func createClientTLSConfig(certBytes []byte, key *ecdsa.PrivateKey) (*tls.Config, error) { clientCert, err := x509.ParseCertificate(certBytes) if err != nil { - return nil, fmt.Errorf("error parsing generated plugin certificate: %v", err) + return nil, errwrap.Wrapf("error parsing generated plugin certificate: {{err}}", err) } cert := tls.Certificate{ @@ -137,7 +136,7 @@ func VaultPluginTLSProvider(apiTLSConfig *api.TLSConfig) func() (*tls.Config, er // Parse the JWT and retrieve the vault address wt, err := jws.ParseJWT([]byte(unwrapToken)) if err != nil { - return nil, fmt.Errorf("error decoding token: %s", err) + return nil, errwrap.Wrapf("error decoding token: {{err}}", err) } if wt == nil { return nil, errors.New("nil decoded token") @@ -157,7 +156,7 @@ func VaultPluginTLSProvider(apiTLSConfig *api.TLSConfig) func() (*tls.Config, er // Sanity check the value if _, err := url.Parse(vaultAddr); err != nil { - return nil, fmt.Errorf("error parsing the vault api_addr: %s", err) + return nil, errwrap.Wrapf("error parsing the vault api_addr: {{err}}", err) } // Unwrap the token @@ -190,12 +189,12 @@ func VaultPluginTLSProvider(apiTLSConfig *api.TLSConfig) func() (*tls.Config, er serverCertBytes, err := base64.StdEncoding.DecodeString(serverCertBytesRaw) if err != nil { - return nil, fmt.Errorf("error parsing certificate: %v", err) + return nil, errwrap.Wrapf("error parsing certificate: {{err}}", err) } serverCert, err := x509.ParseCertificate(serverCertBytes) if err != nil { - return nil, fmt.Errorf("error parsing certificate: %v", err) + return nil, errwrap.Wrapf("error parsing certificate: {{err}}", err) } // Retrieve and parse the server's private key @@ -206,12 +205,12 @@ func VaultPluginTLSProvider(apiTLSConfig *api.TLSConfig) func() (*tls.Config, er serverKeyRaw, err := base64.StdEncoding.DecodeString(serverKeyB64) if err != nil { - return nil, fmt.Errorf("error parsing certificate: %v", err) + return nil, errwrap.Wrapf("error parsing certificate: {{err}}", err) } serverKey, err := x509.ParseECPrivateKey(serverKeyRaw) if err != nil { - return nil, fmt.Errorf("error parsing certificate: %v", err) + return nil, errwrap.Wrapf("error parsing certificate: {{err}}", err) } // Add CA cert to the cert pool diff --git a/helper/salt/salt.go b/helper/salt/salt.go index 450d9c6e7..4fd562058 100644 --- a/helper/salt/salt.go +++ b/helper/salt/salt.go @@ -9,6 +9,7 @@ import ( "fmt" "hash" + "github.com/hashicorp/errwrap" "github.com/hashicorp/go-uuid" "github.com/hashicorp/vault/logical" ) @@ -78,7 +79,7 @@ func NewSalt(ctx context.Context, view logical.Storage, config *Config) (*Salt, if view != nil { raw, err = view.Get(ctx, config.Location) if err != nil { - return nil, fmt.Errorf("failed to read salt: %v", err) + return nil, errwrap.Wrapf("failed to read salt: {{err}}", err) } } @@ -91,7 +92,7 @@ func NewSalt(ctx context.Context, view logical.Storage, config *Config) (*Salt, if s.salt == "" { s.salt, err = uuid.GenerateUUID() if err != nil { - return nil, fmt.Errorf("failed to generate uuid: %v", err) + return nil, errwrap.Wrapf("failed to generate uuid: {{err}}", err) } s.generated = true if view != nil { @@ -100,7 +101,7 @@ func NewSalt(ctx context.Context, view logical.Storage, config *Config) (*Salt, Value: []byte(s.salt), } if err := view.Put(ctx, raw); err != nil { - return nil, fmt.Errorf("failed to persist salt: %v", err) + return nil, errwrap.Wrapf("failed to persist salt: {{err}}", err) } } } diff --git a/helper/strutil/strutil.go b/helper/strutil/strutil.go index ec6166cc7..a77e60d15 100644 --- a/helper/strutil/strutil.go +++ b/helper/strutil/strutil.go @@ -7,6 +7,7 @@ import ( "sort" "strings" + "github.com/hashicorp/errwrap" glob "github.com/ryanuber/go-glob" ) @@ -89,7 +90,7 @@ func ParseKeyValues(input string, out map[string]string, sep string) error { key := strings.TrimSpace(shards[0]) value := strings.TrimSpace(shards[1]) if key == "" || value == "" { - return fmt.Errorf("invalid pair: key:'%s' value:'%s'", key, value) + return fmt.Errorf("invalid pair: key: %q value: %q", key, value) } out[key] = value } @@ -129,14 +130,14 @@ func ParseArbitraryKeyValues(input string, out map[string]string, sep string) er // If JSON unmarshalling fails, consider that the input was // supplied as a comma separated string of 'key=value' pairs. if err = ParseKeyValues(input, out, sep); err != nil { - return fmt.Errorf("failed to parse the input: %v", err) + return errwrap.Wrapf("failed to parse the input: {{err}}", err) } } // Validate the parsed input for key, value := range out { if key != "" && value == "" { - return fmt.Errorf("invalid value for key '%s'", key) + return fmt.Errorf("invalid value for key %q", key) } } diff --git a/helper/xor/xor.go b/helper/xor/xor.go index 4c5f88c53..0d9567eb5 100644 --- a/helper/xor/xor.go +++ b/helper/xor/xor.go @@ -3,6 +3,8 @@ package xor import ( "encoding/base64" "fmt" + + "github.com/hashicorp/errwrap" ) // XORBytes takes two byte slices and XORs them together, returning the final @@ -28,7 +30,7 @@ func XORBytes(a, b []byte) ([]byte, error) { func XORBase64(a, b string) ([]byte, error) { aBytes, err := base64.StdEncoding.DecodeString(a) if err != nil { - return nil, fmt.Errorf("error decoding first base64 value: %v", err) + return nil, errwrap.Wrapf("error decoding first base64 value: {{err}}", err) } if aBytes == nil || len(aBytes) == 0 { return nil, fmt.Errorf("decoded first base64 value is nil or empty") @@ -36,7 +38,7 @@ func XORBase64(a, b string) ([]byte, error) { bBytes, err := base64.StdEncoding.DecodeString(b) if err != nil { - return nil, fmt.Errorf("error decoding second base64 value: %v", err) + return nil, errwrap.Wrapf("error decoding second base64 value: {{err}}", err) } if bBytes == nil || len(bBytes) == 0 { return nil, fmt.Errorf("decoded second base64 value is nil or empty") diff --git a/http/handler.go b/http/handler.go index 2bad9024e..a4e284dc3 100644 --- a/http/handler.go +++ b/http/handler.go @@ -134,7 +134,7 @@ func wrappingVerificationFunc(core *vault.Core, req *logical.Request) error { valid, err := core.ValidateWrappingToken(req) if err != nil { - return fmt.Errorf("error validating wrapping token: %v", err) + return errwrap.Wrapf("error validating wrapping token: {{err}}", err) } if !valid { return fmt.Errorf("wrapping token is not valid or does not exist") diff --git a/http/sys_generate_root.go b/http/sys_generate_root.go index 205dae1b1..74456b943 100644 --- a/http/sys_generate_root.go +++ b/http/sys_generate_root.go @@ -36,8 +36,7 @@ func handleSysGenerateRootAttemptGet(core *vault.Core, w http.ResponseWriter, r return } if barrierConfig == nil { - respondError(w, http.StatusBadRequest, fmt.Errorf( - "server is not yet initialized")) + respondError(w, http.StatusBadRequest, fmt.Errorf("server is not yet initialized")) return } diff --git a/http/sys_rekey.go b/http/sys_rekey.go index e3637eb0d..f9d595bb4 100644 --- a/http/sys_rekey.go +++ b/http/sys_rekey.go @@ -53,8 +53,7 @@ func handleSysRekeyInitGet(ctx context.Context, core *vault.Core, recovery bool, return } if barrierConfig == nil { - respondError(w, http.StatusBadRequest, fmt.Errorf( - "server is not yet initialized")) + respondError(w, http.StatusBadRequest, fmt.Errorf("server is not yet initialized")) return } diff --git a/http/sys_seal.go b/http/sys_seal.go index a6ba9241c..d86d7f2d0 100644 --- a/http/sys_seal.go +++ b/http/sys_seal.go @@ -182,8 +182,7 @@ func handleSysSealStatusRaw(core *vault.Core, w http.ResponseWriter, r *http.Req } if sealConfig == nil { - respondError(w, http.StatusBadRequest, fmt.Errorf( - "server is not yet initialized")) + respondError(w, http.StatusBadRequest, fmt.Errorf("server is not yet initialized")) return } diff --git a/logical/framework/backend.go b/logical/framework/backend.go index 7c34d03a5..746a45ceb 100644 --- a/logical/framework/backend.go +++ b/logical/framework/backend.go @@ -11,6 +11,7 @@ import ( "sync" "time" + "github.com/hashicorp/errwrap" log "github.com/hashicorp/go-hclog" "github.com/hashicorp/go-multierror" @@ -392,8 +393,7 @@ func (b *Backend) handleRevokeRenew(ctx context.Context, req *logical.Request) ( case logical.RevokeOperation: return secret.HandleRevoke(ctx, req) default: - return nil, fmt.Errorf( - "invalid operation for revoke/renew: %s", req.Operation) + return nil, fmt.Errorf("invalid operation for revoke/renew: %q", req.Operation) } } @@ -460,8 +460,7 @@ func (b *Backend) handleWALRollback(ctx context.Context, req *logical.Request) ( // Attempt a WAL rollback err = b.WALRollback(ctx, req, entry.Kind, entry.Data) if err != nil { - err = fmt.Errorf( - "Error rolling back '%s' entry: %s", entry.Kind, err) + err = errwrap.Wrapf(fmt.Sprintf("error rolling back %q entry: {{err}}", entry.Kind), err) } if err == nil { err = DeleteWAL(ctx, req.Storage, k) diff --git a/logical/framework/field_data.go b/logical/framework/field_data.go index 966a16576..b94612f08 100644 --- a/logical/framework/field_data.go +++ b/logical/framework/field_data.go @@ -7,6 +7,7 @@ import ( "regexp" "strings" + "github.com/hashicorp/errwrap" "github.com/hashicorp/vault/helper/parseutil" "github.com/hashicorp/vault/helper/strutil" "github.com/mitchellh/mapstructure" @@ -39,11 +40,10 @@ func (d *FieldData) Validate() error { TypeKVPairs, TypeCommaIntSlice: _, _, err := d.getPrimitive(field, schema) if err != nil { - return fmt.Errorf("Error converting input %v for field %s: %s", value, field, err) + return errwrap.Wrapf(fmt.Sprintf("error converting input %v for field %q: {{err}}", value, field), err) } default: - return fmt.Errorf("unknown field type %s for field %s", - schema.Type, field) + return fmt.Errorf("unknown field type %q for field %q", schema.Type, field) } } @@ -107,7 +107,7 @@ func (d *FieldData) GetOk(k string) (interface{}, bool) { func (d *FieldData) GetOkErr(k string) (interface{}, bool, error) { schema, ok := d.Schema[k] if !ok { - return nil, false, fmt.Errorf("unknown field: %s", k) + return nil, false, fmt.Errorf("unknown field: %q", k) } switch schema.Type { @@ -117,7 +117,7 @@ func (d *FieldData) GetOkErr(k string) (interface{}, bool, error) { return d.getPrimitive(k, schema) default: return nil, false, - fmt.Errorf("unknown field type %s for field %s", schema.Type, k) + fmt.Errorf("unknown field type %q for field %q", schema.Type, k) } } diff --git a/logical/framework/path.go b/logical/framework/path.go index a72b418b9..e53dd196c 100644 --- a/logical/framework/path.go +++ b/logical/framework/path.go @@ -6,6 +6,7 @@ import ( "sort" "strings" + "github.com/hashicorp/errwrap" "github.com/hashicorp/vault/logical" ) @@ -122,7 +123,7 @@ func (p *Path) helpCallback() OperationFunc { help, err := executeTemplate(pathHelpTemplate, &tplData) if err != nil { - return nil, fmt.Errorf("error executing template: %s", err) + return nil, errwrap.Wrapf("error executing template: {{err}}", err) } return logical.HelpResponse(help, nil), nil diff --git a/logical/framework/template.go b/logical/framework/template.go index 5ac82effe..3abdd624c 100644 --- a/logical/framework/template.go +++ b/logical/framework/template.go @@ -3,9 +3,10 @@ package framework import ( "bufio" "bytes" - "fmt" "strings" "text/template" + + "github.com/hashicorp/errwrap" ) func executeTemplate(tpl string, data interface{}) (string, error) { @@ -17,13 +18,13 @@ func executeTemplate(tpl string, data interface{}) (string, error) { // Parse the help template t, err := template.New("root").Funcs(funcs).Parse(tpl) if err != nil { - return "", fmt.Errorf("error parsing template: %s", err) + return "", errwrap.Wrapf("error parsing template: {{err}}", err) } // Execute the template and store the output var buf bytes.Buffer if err := t.Execute(&buf, data); err != nil { - return "", fmt.Errorf("error executing template: %s", err) + return "", errwrap.Wrapf("error executing template: {{err}}", err) } return strings.TrimSpace(buf.String()), nil diff --git a/logical/plugin/mock/path_kv.go b/logical/plugin/mock/path_kv.go index 3e599621e..4fcd246e8 100644 --- a/logical/plugin/mock/path_kv.go +++ b/logical/plugin/mock/path_kv.go @@ -2,8 +2,8 @@ package mock import ( "context" - "fmt" + "github.com/hashicorp/errwrap" "github.com/hashicorp/vault/logical" "github.com/hashicorp/vault/logical/framework" ) @@ -39,7 +39,7 @@ func kvPaths(b *backend) []*framework.Path { func (b *backend) pathExistenceCheck(ctx context.Context, req *logical.Request, data *framework.FieldData) (bool, error) { out, err := req.Storage.Get(ctx, req.Path) if err != nil { - return false, fmt.Errorf("existence check failed: %v", err) + return false, errwrap.Wrapf("existence check failed: {{err}}", err) } return out != nil, nil diff --git a/logical/plugin/plugin.go b/logical/plugin/plugin.go index 65b53a299..03d21c789 100644 --- a/logical/plugin/plugin.go +++ b/logical/plugin/plugin.go @@ -11,6 +11,7 @@ import ( "sync" + "github.com/hashicorp/errwrap" log "github.com/hashicorp/go-hclog" "github.com/hashicorp/go-plugin" "github.com/hashicorp/vault/helper/pluginutil" @@ -73,13 +74,13 @@ func NewBackend(ctx context.Context, pluginName string, sys pluginutil.LookRunne // from the pluginRunner. Then cast it to logical.Backend. backendRaw, err := pluginRunner.BuiltinFactory() if err != nil { - return nil, fmt.Errorf("error getting plugin type: %s", err) + return nil, errwrap.Wrapf("error getting plugin type: {{err}}", err) } var ok bool backend, ok = backendRaw.(logical.Backend) if !ok { - return nil, fmt.Errorf("unsupported backend type: %s", pluginName) + return nil, fmt.Errorf("unsupported backend type: %q", pluginName) } } else { diff --git a/logical/storage.go b/logical/storage.go index 1ca97ab74..6aa07667a 100644 --- a/logical/storage.go +++ b/logical/storage.go @@ -6,6 +6,7 @@ import ( "fmt" "strings" + "github.com/hashicorp/errwrap" "github.com/hashicorp/vault/helper/jsonutil" ) @@ -42,7 +43,7 @@ func (e *StorageEntry) DecodeJSON(out interface{}) error { func StorageEntryJSON(k string, v interface{}) (*StorageEntry, error) { encodedBytes, err := jsonutil.EncodeJSON(v) if err != nil { - return nil, fmt.Errorf("failed to encode storage entry: %v", err) + return nil, errwrap.Wrapf("failed to encode storage entry: {{err}}", err) } return &StorageEntry{ @@ -67,7 +68,7 @@ func ScanView(ctx context.Context, view ClearableView, cb func(path string)) err // List the contents contents, err := view.List(ctx, current) if err != nil { - return fmt.Errorf("list failed at path '%s': %v", current, err) + return errwrap.Wrapf(fmt.Sprintf("list failed at path %q: {{err}}", current), err) } // Handle the contents in the directory diff --git a/logical/testing/testing.go b/logical/testing/testing.go index c8ed22c79..d9da151f1 100644 --- a/logical/testing/testing.go +++ b/logical/testing/testing.go @@ -271,7 +271,7 @@ func Test(tt TestT, c TestCase) { // If the error is a 'logical.ErrorResponse' and if error was not expected, // set the error so that this can be caught below. if resp.IsError() && !s.ErrorOk { - err = fmt.Errorf("Erroneous response:\n\n%#v", resp) + err = fmt.Errorf("erroneous response:\n\n%#v", resp) } // Either the 'err' was nil or if an error was expected, it was set to nil. @@ -300,7 +300,7 @@ func Test(tt TestT, c TestCase) { req.ClientToken = client.Token() resp, err := core.HandleRequest(req) if err == nil && resp.IsError() { - err = fmt.Errorf("Erroneous response:\n\n%#v", resp) + err = fmt.Errorf("erroneous response:\n\n%#v", resp) } if err != nil { failedRevokes = append(failedRevokes, req.Secret) @@ -317,7 +317,7 @@ func Test(tt TestT, c TestCase) { req.ClientToken = client.Token() resp, err := core.HandleRequest(req) if err == nil && resp.IsError() { - err = fmt.Errorf("Erroneous response:\n\n%#v", resp) + err = fmt.Errorf("erroneous response:\n\n%#v", resp) } if err != nil { if !errwrap.Contains(err, logical.ErrUnsupportedOperation.Error()) { diff --git a/physical/azure/azure.go b/physical/azure/azure.go index 3728edf77..99ce0a0d5 100644 --- a/physical/azure/azure.go +++ b/physical/azure/azure.go @@ -65,7 +65,7 @@ func NewAzureBackend(conf map[string]string, logger log.Logger) (physical.Backen client, err := storage.NewBasicClient(accountName, accountKey) if err != nil { - return nil, fmt.Errorf("failed to create Azure client: %v", err) + return nil, errwrap.Wrapf("failed to create Azure client: {{err}}", err) } client.HTTPClient = cleanhttp.DefaultPooledClient() @@ -75,7 +75,7 @@ func NewAzureBackend(conf map[string]string, logger log.Logger) (physical.Backen Access: storage.ContainerAccessTypePrivate, }) if err != nil { - return nil, fmt.Errorf("failed to create %q container: %v", name, err) + return nil, errwrap.Wrapf(fmt.Sprintf("failed to create %q container: {{err}}", name), err) } maxParStr, ok := conf["max_parallel"] diff --git a/physical/cassandra/cassandra.go b/physical/cassandra/cassandra.go index 47571a03a..09046fdab 100644 --- a/physical/cassandra/cassandra.go +++ b/physical/cassandra/cassandra.go @@ -10,6 +10,7 @@ import ( "strings" "time" + "github.com/hashicorp/errwrap" log "github.com/hashicorp/go-hclog" "github.com/armon/go-metrics" @@ -169,11 +170,11 @@ func setupCassandraTLS(conf map[string]string, cluster *gocql.ClusterConfig) err if pemBundlePath, ok := conf["pem_bundle_file"]; ok { pemBundleData, err := ioutil.ReadFile(pemBundlePath) if err != nil { - return fmt.Errorf("Error reading pem bundle from %s: %v", pemBundlePath, err) + return errwrap.Wrapf(fmt.Sprintf("error reading pem bundle from %q: {{err}}", pemBundlePath), err) } pemBundle, err := certutil.ParsePEMBundle(string(pemBundleData)) if err != nil { - return fmt.Errorf("Error parsing 'pem_bundle': %v", err) + return errwrap.Wrapf("error parsing 'pem_bundle': {{err}}", err) } tlsConfig, err = pemBundle.GetTLSConfig(certutil.TLSClient) if err != nil { @@ -183,7 +184,7 @@ func setupCassandraTLS(conf map[string]string, cluster *gocql.ClusterConfig) err if pemJSONPath, ok := conf["pem_json_file"]; ok { pemJSONData, err := ioutil.ReadFile(pemJSONPath) if err != nil { - return fmt.Errorf("Error reading json bundle from %s: %v", pemJSONPath, err) + return errwrap.Wrapf(fmt.Sprintf("error reading json bundle from %q: {{err}}", pemJSONPath), err) } pemJSON, err := certutil.ParsePKIJSON([]byte(pemJSONData)) if err != nil { diff --git a/physical/cockroachdb/cockroachdb.go b/physical/cockroachdb/cockroachdb.go index a03f24e4c..646eb0822 100644 --- a/physical/cockroachdb/cockroachdb.go +++ b/physical/cockroachdb/cockroachdb.go @@ -65,14 +65,14 @@ func NewCockroachDBBackend(conf map[string]string, logger log.Logger) (physical. // Create CockroachDB handle for the database. db, err := sql.Open("postgres", connURL) if err != nil { - return nil, fmt.Errorf("failed to connect to cockroachdb: %v", err) + return nil, errwrap.Wrapf("failed to connect to cockroachdb: {{err}}", err) } // Create the required table if it doesn't exists. createQuery := "CREATE TABLE IF NOT EXISTS " + dbTable + " (path STRING, value BYTES, PRIMARY KEY (path))" if _, err := db.Exec(createQuery); err != nil { - return nil, fmt.Errorf("failed to create mysql table: %v", err) + return nil, errwrap.Wrapf("failed to create mysql table: {{err}}", err) } // Setup the backend @@ -105,7 +105,7 @@ func NewCockroachDBBackend(conf map[string]string, logger log.Logger) (physical. func (c *CockroachDBBackend) prepare(name, query string) error { stmt, err := c.client.Prepare(query) if err != nil { - return fmt.Errorf("failed to prepare '%s': %v", name, err) + return errwrap.Wrapf(fmt.Sprintf("failed to prepare %q: {{err}}", name), err) } c.statements[name] = stmt return nil @@ -182,7 +182,7 @@ func (c *CockroachDBBackend) List(ctx context.Context, prefix string) ([]string, var key string err = rows.Scan(&key) if err != nil { - return nil, fmt.Errorf("failed to scan rows: %v", err) + return nil, errwrap.Wrapf("failed to scan rows: {{err}}", err) } key = strings.TrimPrefix(key, prefix) diff --git a/physical/consul/consul.go b/physical/consul/consul.go index 405d7197c..af4a7efde 100644 --- a/physical/consul/consul.go +++ b/physical/consul/consul.go @@ -242,7 +242,7 @@ func NewConsulBackend(conf map[string]string, logger log.Logger) (physical.Backe switch consistencyMode { case consistencyModeDefault, consistencyModeStrong: default: - return nil, fmt.Errorf("invalid consistency_mode value: %s", consistencyMode) + return nil, fmt.Errorf("invalid consistency_mode value: %q", consistencyMode) } } else { consistencyMode = consistencyModeDefault @@ -311,7 +311,7 @@ func setupTLSConfig(conf map[string]string) (*tls.Config, error) { if okCert && okKey { tlsCert, err := tls.LoadX509KeyPair(conf["tls_cert_file"], conf["tls_key_file"]) if err != nil { - return nil, fmt.Errorf("client tls setup failed: %v", err) + return nil, errwrap.Wrapf("client tls setup failed: {{err}}", err) } tlsClientConfig.Certificates = []tls.Certificate{tlsCert} @@ -322,7 +322,7 @@ func setupTLSConfig(conf map[string]string) (*tls.Config, error) { data, err := ioutil.ReadFile(tlsCaFile) if err != nil { - return nil, fmt.Errorf("failed to read CA file: %v", err) + return nil, errwrap.Wrapf("failed to read CA file: {{err}}", err) } if !caPool.AppendCertsFromPEM(data) { @@ -469,7 +469,7 @@ func (c *ConsulBackend) LockWith(key, value string) (physical.Lock, error) { } lock, err := c.client.LockOpts(opts) if err != nil { - return nil, fmt.Errorf("failed to create lock: %v", err) + return nil, errwrap.Wrapf("failed to create lock: {{err}}", err) } cl := &ConsulLock{ client: c.client, @@ -495,7 +495,7 @@ func (c *ConsulBackend) DetectHostAddr() (string, error) { } addr, ok := self["Member"]["Addr"].(string) if !ok { - return "", fmt.Errorf("Unable to convert an address to string") + return "", fmt.Errorf("unable to convert an address to string") } return addr, nil } @@ -809,7 +809,7 @@ func (c *ConsulBackend) setRedirectAddr(addr string) (err error) { url, err := url.Parse(addr) if err != nil { - return errwrap.Wrapf(fmt.Sprintf(`failed to parse redirect URL "%v": {{err}}`, addr), err) + return errwrap.Wrapf(fmt.Sprintf("failed to parse redirect URL %q: {{err}}", addr), err) } var portStr string diff --git a/physical/couchdb/couchdb.go b/physical/couchdb/couchdb.go index 228973500..a239d8894 100644 --- a/physical/couchdb/couchdb.go +++ b/physical/couchdb/couchdb.go @@ -105,7 +105,7 @@ func (m *couchDBClient) get(key string) (*physical.Entry, error) { if resp.StatusCode == http.StatusNotFound { return nil, nil } else if resp.StatusCode != http.StatusOK { - return nil, fmt.Errorf("GET returned %s", resp.Status) + return nil, fmt.Errorf("GET returned %q", resp.Status) } bs, err := ioutil.ReadAll(resp.Body) if err != nil { diff --git a/physical/dynamodb/dynamodb.go b/physical/dynamodb/dynamodb.go index c229f9a5b..e3e6e389f 100644 --- a/physical/dynamodb/dynamodb.go +++ b/physical/dynamodb/dynamodb.go @@ -134,7 +134,7 @@ func NewDynamoDBBackend(conf map[string]string, logger log.Logger) (physical.Bac } readCapacity, err := strconv.Atoi(readCapacityString) if err != nil { - return nil, fmt.Errorf("invalid read capacity: %s", readCapacityString) + return nil, fmt.Errorf("invalid read capacity: %q", readCapacityString) } if readCapacity == 0 { readCapacity = DefaultDynamoDBReadCapacity @@ -149,7 +149,7 @@ func NewDynamoDBBackend(conf map[string]string, logger log.Logger) (physical.Bac } writeCapacity, err := strconv.Atoi(writeCapacityString) if err != nil { - return nil, fmt.Errorf("invalid write capacity: %s", writeCapacityString) + return nil, fmt.Errorf("invalid write capacity: %q", writeCapacityString) } if writeCapacity == 0 { writeCapacity = DefaultDynamoDBWriteCapacity @@ -192,7 +192,7 @@ func NewDynamoDBBackend(conf map[string]string, logger log.Logger) (physical.Bac var err error dynamodbMaxRetry, err = strconv.Atoi(dynamodbMaxRetryString) if err != nil { - return nil, fmt.Errorf("invalid max retry: %s", dynamodbMaxRetryString) + return nil, fmt.Errorf("invalid max retry: %q", dynamodbMaxRetryString) } } @@ -261,7 +261,7 @@ func (d *DynamoDBBackend) Put(ctx context.Context, entry *physical.Entry) error } item, err := dynamodbattribute.ConvertToMap(record) if err != nil { - return fmt.Errorf("could not convert prefix record to DynamoDB item: %s", err) + return errwrap.Wrapf("could not convert prefix record to DynamoDB item: {{err}}", err) } requests := []*dynamodb.WriteRequest{{ PutRequest: &dynamodb.PutRequest{ @@ -276,7 +276,7 @@ func (d *DynamoDBBackend) Put(ctx context.Context, entry *physical.Entry) error } item, err := dynamodbattribute.ConvertToMap(record) if err != nil { - return fmt.Errorf("could not convert prefix record to DynamoDB item: %s", err) + return errwrap.Wrapf("could not convert prefix record to DynamoDB item: {{err}}", err) } requests = append(requests, &dynamodb.WriteRequest{ PutRequest: &dynamodb.PutRequest{ diff --git a/physical/etcd/etcd.go b/physical/etcd/etcd.go index 48e47d31d..985d8def7 100644 --- a/physical/etcd/etcd.go +++ b/physical/etcd/etcd.go @@ -3,13 +3,13 @@ package etcd import ( "context" "errors" - "fmt" "net/url" "os" "strings" "github.com/coreos/etcd/client" "github.com/coreos/go-semver/semver" + "github.com/hashicorp/errwrap" log "github.com/hashicorp/go-hclog" "github.com/hashicorp/vault/physical" ) @@ -136,7 +136,7 @@ func getEtcdEndpoints(conf map[string]string) ([]string, error) { discoverer := client.NewSRVDiscover() endpoints, err := discoverer.Discover(domain) if err != nil { - return nil, fmt.Errorf("failed to discover etcd endpoints through SRV discovery: %v", err) + return nil, errwrap.Wrapf("failed to discover etcd endpoints through SRV discovery: {{err}}", err) } return endpoints, nil } diff --git a/physical/etcd/etcd2.go b/physical/etcd/etcd2.go index b67dfd06c..a2a479f2e 100644 --- a/physical/etcd/etcd2.go +++ b/physical/etcd/etcd2.go @@ -15,6 +15,7 @@ import ( "github.com/coreos/etcd/client" "github.com/coreos/etcd/pkg/transport" log "github.com/hashicorp/go-hclog" + multierror "github.com/hashicorp/go-multierror" "github.com/hashicorp/vault/physical" ) @@ -103,7 +104,7 @@ func newEtcd2Backend(conf map[string]string, logger log.Logger) (physical.Backen syncErr := c.Sync(ctx) cancel() if syncErr != nil { - return nil, fmt.Errorf("%s: %s", EtcdSyncClusterError, syncErr) + return nil, multierror.Append(EtcdSyncClusterError, syncErr) } case "no", "false", "n", "0": default: diff --git a/physical/etcd/etcd3.go b/physical/etcd/etcd3.go index 0cd40217c..5c9952788 100644 --- a/physical/etcd/etcd3.go +++ b/physical/etcd/etcd3.go @@ -14,6 +14,7 @@ import ( "github.com/coreos/etcd/clientv3" "github.com/coreos/etcd/clientv3/concurrency" "github.com/coreos/etcd/pkg/transport" + "github.com/hashicorp/errwrap" log "github.com/hashicorp/go-hclog" "github.com/hashicorp/vault/helper/strutil" "github.com/hashicorp/vault/physical" @@ -117,7 +118,7 @@ func newEtcd3Backend(conf map[string]string, logger log.Logger) (physical.Backen // grpc converts this to uint32 internally, so parse as that to avoid passing invalid values val, err := strconv.ParseUint(maxReceive, 10, 32) if err != nil { - return nil, fmt.Errorf("value [%v] of 'max_receive_size' could not be understood", maxReceive) + return nil, errwrap.Wrapf(fmt.Sprintf("value of 'max_receive_size' (%v) could not be understood: {{err}}", maxReceive), err) } cfg.MaxCallRecvMsgSize = int(val) } @@ -133,7 +134,7 @@ func newEtcd3Backend(conf map[string]string, logger log.Logger) (physical.Backen } sync, err := strconv.ParseBool(ssync) if err != nil { - return nil, fmt.Errorf("value of 'sync' (%v) could not be understood", err) + return nil, errwrap.Wrapf(fmt.Sprintf("value of 'sync' (%v) could not be understood: {{err}}", ssync), err) } if sync { diff --git a/physical/file/file.go b/physical/file/file.go index 6028bad44..d93609a19 100644 --- a/physical/file/file.go +++ b/physical/file/file.go @@ -10,6 +10,7 @@ import ( "strings" "sync" + "github.com/hashicorp/errwrap" log "github.com/hashicorp/go-hclog" "github.com/hashicorp/vault/helper/consts" @@ -98,7 +99,7 @@ func (b *FileBackend) DeleteInternal(ctx context.Context, path string) error { err := os.Remove(fullPath) if err != nil && !os.IsNotExist(err) { - return fmt.Errorf("Failed to remove %q: %v", fullPath, err) + return errwrap.Wrapf(fmt.Sprintf("failed to remove %q: {{err}}", fullPath), err) } err = b.cleanupLogicalPath(path) diff --git a/physical/mssql/mssql.go b/physical/mssql/mssql.go index 908c8f90b..a3d73c163 100644 --- a/physical/mssql/mssql.go +++ b/physical/mssql/mssql.go @@ -100,13 +100,13 @@ func NewMSSQLBackend(conf map[string]string, logger log.Logger) (physical.Backen db, err := sql.Open("mssql", connectionString) if err != nil { - return nil, fmt.Errorf("failed to connect to mssql: %v", err) + return nil, errwrap.Wrapf("failed to connect to mssql: {{err}}", err) } db.SetMaxOpenConns(maxParInt) if _, err := db.Exec("IF NOT EXISTS(SELECT * FROM sys.databases WHERE name = '" + database + "') CREATE DATABASE " + database); err != nil { - return nil, fmt.Errorf("failed to create mssql database: %v", err) + return nil, errwrap.Wrapf("failed to create mssql database: {{err}}", err) } dbTable := database + "." + schema + "." + table @@ -115,7 +115,7 @@ func NewMSSQLBackend(conf map[string]string, logger log.Logger) (physical.Backen if schema != "dbo" { if _, err := db.Exec("USE " + database); err != nil { - return nil, fmt.Errorf("failed to switch mssql database: %v", err) + return nil, errwrap.Wrapf("failed to switch mssql database: {{err}}", err) } var num int @@ -124,16 +124,16 @@ func NewMSSQLBackend(conf map[string]string, logger log.Logger) (physical.Backen switch { case err == sql.ErrNoRows: if _, err := db.Exec("CREATE SCHEMA " + schema); err != nil { - return nil, fmt.Errorf("failed to create mssql schema: %v", err) + return nil, errwrap.Wrapf("failed to create mssql schema: {{err}}", err) } case err != nil: - return nil, fmt.Errorf("failed to check if mssql schema exists: %v", err) + return nil, errwrap.Wrapf("failed to check if mssql schema exists: {{err}}", err) } } if _, err := db.Exec(createQuery); err != nil { - return nil, fmt.Errorf("failed to create mssql table: %v", err) + return nil, errwrap.Wrapf("failed to create mssql table: {{err}}", err) } m := &MSSQLBackend{ @@ -164,7 +164,7 @@ func NewMSSQLBackend(conf map[string]string, logger log.Logger) (physical.Backen func (m *MSSQLBackend) prepare(name, query string) error { stmt, err := m.client.Prepare(query) if err != nil { - return fmt.Errorf("failed to prepare '%s': %v", name, err) + return errwrap.Wrapf(fmt.Sprintf("failed to prepare %q: {{err}}", name), err) } m.statements[name] = stmt @@ -240,7 +240,7 @@ func (m *MSSQLBackend) List(ctx context.Context, prefix string) ([]string, error var key string err = rows.Scan(&key) if err != nil { - return nil, fmt.Errorf("failed to scan rows: %v", err) + return nil, errwrap.Wrapf("failed to scan rows: {{err}}", err) } key = strings.TrimPrefix(key, prefix) diff --git a/physical/mysql/mysql.go b/physical/mysql/mysql.go index ac71f09d6..1fc5bfdcf 100644 --- a/physical/mysql/mysql.go +++ b/physical/mysql/mysql.go @@ -113,7 +113,7 @@ func NewMySQLBackend(conf map[string]string, logger log.Logger) (physical.Backen tlsCaFile, ok := conf["tls_ca_file"] if ok { if err := setupMySQLTLSConfig(tlsCaFile); err != nil { - return nil, fmt.Errorf("failed register TLS config: %v", err) + return nil, errwrap.Wrapf("failed register TLS config: {{err}}", err) } dsnParams.Add("tls", mysqlTLSKey) @@ -123,7 +123,7 @@ func NewMySQLBackend(conf map[string]string, logger log.Logger) (physical.Backen dsn := username + ":" + password + "@tcp(" + address + ")/?" + dsnParams.Encode() db, err := sql.Open("mysql", dsn) if err != nil { - return nil, fmt.Errorf("failed to connect to mysql: %v", err) + return nil, errwrap.Wrapf("failed to connect to mysql: {{err}}", err) } db.SetMaxOpenConns(maxParInt) if maxIdleConnInt != 0 { @@ -136,7 +136,7 @@ func NewMySQLBackend(conf map[string]string, logger log.Logger) (physical.Backen var schemaExist bool schemaRows, err := db.Query("SELECT SCHEMA_NAME FROM information_schema.SCHEMATA WHERE SCHEMA_NAME = ?", database) if err != nil { - return nil, fmt.Errorf("failed to check mysql schema exist: %v", err) + return nil, errwrap.Wrapf("failed to check mysql schema exist: {{err}}", err) } defer schemaRows.Close() schemaExist = schemaRows.Next() @@ -146,7 +146,7 @@ func NewMySQLBackend(conf map[string]string, logger log.Logger) (physical.Backen tableRows, err := db.Query("SELECT TABLE_NAME FROM information_schema.TABLES WHERE TABLE_NAME = ? AND TABLE_SCHEMA = ?", table, database) if err != nil { - return nil, fmt.Errorf("failed to check mysql table exist: %v", err) + return nil, errwrap.Wrapf("failed to check mysql table exist: {{err}}", err) } defer tableRows.Close() tableExist = tableRows.Next() @@ -154,7 +154,7 @@ func NewMySQLBackend(conf map[string]string, logger log.Logger) (physical.Backen // Create the required database if it doesn't exists. if !schemaExist { if _, err := db.Exec("CREATE DATABASE IF NOT EXISTS " + database); err != nil { - return nil, fmt.Errorf("failed to create mysql database: %v", err) + return nil, errwrap.Wrapf("failed to create mysql database: {{err}}", err) } } @@ -163,7 +163,7 @@ func NewMySQLBackend(conf map[string]string, logger log.Logger) (physical.Backen create_query := "CREATE TABLE IF NOT EXISTS " + dbTable + " (vault_key varbinary(512), vault_value mediumblob, PRIMARY KEY (vault_key))" if _, err := db.Exec(create_query); err != nil { - return nil, fmt.Errorf("failed to create mysql table: %v", err) + return nil, errwrap.Wrapf("failed to create mysql table: {{err}}", err) } } @@ -197,7 +197,7 @@ func NewMySQLBackend(conf map[string]string, logger log.Logger) (physical.Backen func (m *MySQLBackend) prepare(name, query string) error { stmt, err := m.client.Prepare(query) if err != nil { - return fmt.Errorf("failed to prepare '%s': %v", name, err) + return errwrap.Wrapf(fmt.Sprintf("failed to prepare %q: {{err}}", name), err) } m.statements[name] = stmt return nil @@ -266,7 +266,7 @@ func (m *MySQLBackend) List(ctx context.Context, prefix string) ([]string, error likePrefix := prefix + "%" rows, err := m.statements["list"].Query(likePrefix) if err != nil { - return nil, fmt.Errorf("failed to execute statement: %v", err) + return nil, errwrap.Wrapf("failed to execute statement: {{err}}", err) } var keys []string @@ -274,7 +274,7 @@ func (m *MySQLBackend) List(ctx context.Context, prefix string) ([]string, error var key string err = rows.Scan(&key) if err != nil { - return nil, fmt.Errorf("failed to scan rows: %v", err) + return nil, errwrap.Wrapf("failed to scan rows: {{err}}", err) } key = strings.TrimPrefix(key, prefix) diff --git a/physical/postgresql/postgresql.go b/physical/postgresql/postgresql.go index 04764f4f8..a4332be88 100644 --- a/physical/postgresql/postgresql.go +++ b/physical/postgresql/postgresql.go @@ -66,7 +66,7 @@ func NewPostgreSQLBackend(conf map[string]string, logger log.Logger) (physical.B // Create PostgreSQL handle for the database. db, err := sql.Open("postgres", connURL) if err != nil { - return nil, fmt.Errorf("failed to connect to postgres: %v", err) + return nil, errwrap.Wrapf("failed to connect to postgres: {{err}}", err) } db.SetMaxOpenConns(maxParInt) @@ -74,7 +74,7 @@ func NewPostgreSQLBackend(conf map[string]string, logger log.Logger) (physical.B var upsert_required bool upsert_required_query := "SELECT current_setting('server_version_num')::int < 90500" if err := db.QueryRow(upsert_required_query).Scan(&upsert_required); err != nil { - return nil, fmt.Errorf("failed to check for native upsert: %v", err) + return nil, errwrap.Wrapf("failed to check for native upsert: {{err}}", err) } // Setup our put strategy based on the presence or absence of a native @@ -205,7 +205,7 @@ func (m *PostgreSQLBackend) List(ctx context.Context, prefix string) ([]string, var key string err = rows.Scan(&key) if err != nil { - return nil, fmt.Errorf("failed to scan rows: %v", err) + return nil, errwrap.Wrapf("failed to scan rows: {{err}}", err) } keys = append(keys, key) diff --git a/physical/s3/s3.go b/physical/s3/s3.go index da14c1a4e..c30a20387 100644 --- a/physical/s3/s3.go +++ b/physical/s3/s3.go @@ -83,7 +83,7 @@ func NewS3Backend(conf map[string]string, logger log.Logger) (physical.Backend, } s3ForcePathStyleBool, err := parseutil.ParseBool(s3ForcePathStyleStr) if err != nil { - return nil, fmt.Errorf("invalid boolean set for s3_force_path_style: '%s'", s3ForcePathStyleStr) + return nil, fmt.Errorf("invalid boolean set for s3_force_path_style: %q", s3ForcePathStyleStr) } disableSSLStr, ok := conf["disable_ssl"] if !ok { @@ -91,7 +91,7 @@ func NewS3Backend(conf map[string]string, logger log.Logger) (physical.Backend, } disableSSLBool, err := parseutil.ParseBool(disableSSLStr) if err != nil { - return nil, fmt.Errorf("invalid boolean set for disable_ssl: '%s'", disableSSLStr) + return nil, fmt.Errorf("invalid boolean set for disable_ssl: %q", disableSSLStr) } credsConfig := &awsutil.CredentialsConfig{ @@ -120,7 +120,7 @@ func NewS3Backend(conf map[string]string, logger log.Logger) (physical.Backend, _, err = s3conn.ListObjects(&s3.ListObjectsInput{Bucket: &bucket}) if err != nil { - return nil, fmt.Errorf("unable to access bucket '%s' in region %s: %v", bucket, region, err) + return nil, errwrap.Wrapf(fmt.Sprintf("unable to access bucket %q in region %q: {{err}}", bucket, region), err) } maxParStr, ok := conf["max_parallel"] diff --git a/physical/swift/swift.go b/physical/swift/swift.go index 6888eca73..3689d13f1 100644 --- a/physical/swift/swift.go +++ b/physical/swift/swift.go @@ -102,7 +102,7 @@ func NewSwiftBackend(conf map[string]string, logger log.Logger) (physical.Backen _, _, err = c.Container(container) if err != nil { - return nil, fmt.Errorf("Unable to access container '%s': %v", container, err) + return nil, errwrap.Wrapf(fmt.Sprintf("Unable to access container %q: {{err}}", container), err) } maxParStr, ok := conf["max_parallel"] diff --git a/physical/zookeeper/zookeeper.go b/physical/zookeeper/zookeeper.go index d15209197..5ce0a3799 100644 --- a/physical/zookeeper/zookeeper.go +++ b/physical/zookeeper/zookeeper.go @@ -9,6 +9,7 @@ import ( "sync" "time" + "github.com/hashicorp/errwrap" log "github.com/hashicorp/go-hclog" "github.com/hashicorp/vault/physical" @@ -120,14 +121,14 @@ func NewZooKeeperBackend(conf map[string]string, logger log.Logger) (physical.Ba // We have all of the configuration in hand - let's try and connect to ZK client, _, err := zk.Connect(strings.Split(machines, ","), time.Second) if err != nil { - return nil, fmt.Errorf("client setup failed: %v", err) + return nil, errwrap.Wrapf("client setup failed: {{err}}", err) } // ZK AddAuth API if the user asked for it if useAddAuth { err = client.AddAuth(schema, []byte(owner)) if err != nil { - return nil, fmt.Errorf("ZooKeeper rejected authentication information provided at auth_info: %v", err) + return nil, errwrap.Wrapf("ZooKeeper rejected authentication information provided at auth_info: {{err}}", err) } } @@ -181,23 +182,19 @@ func (c *ZooKeeperBackend) cleanupLogicalPath(path string) error { _, stat, err := c.client.Exists(fullPath) if err != nil { - return fmt.Errorf("Failed to acquire node data: %s", err) + return errwrap.Wrapf("failed to acquire node data: {{err}}", err) } if stat.DataLength > 0 && stat.NumChildren > 0 { - msgFmt := "Node %s is both of data and leaf type ??" - panic(fmt.Sprintf(msgFmt, fullPath)) + panic(fmt.Sprintf("node %q is both of data and leaf type", fullPath)) } else if stat.DataLength > 0 { - msgFmt := "Node %s is a data node, this is either a bug or " + - "backend data is corrupted" - panic(fmt.Sprintf(msgFmt, fullPath)) + panic(fmt.Sprintf("node %q is a data node, this is either a bug or backend data is corrupted", fullPath)) } else if stat.NumChildren > 0 { return nil } else { // Empty node, lets clean it up! if err := c.client.Delete(fullPath, -1); err != nil && err != zk.ErrNoNode { - msgFmt := "Removal of node `%s` failed: `%v`" - return fmt.Errorf(msgFmt, fullPath, err) + return errwrap.Wrapf(fmt.Sprintf("removal of node %q failed: {{err}}", fullPath), err) } } } @@ -265,7 +262,7 @@ func (c *ZooKeeperBackend) Delete(ctx context.Context, key string) error { // Mask if the node does not exist if err != nil && err != zk.ErrNoNode { - return fmt.Errorf("Failed to remove %q: %v", fullPath, err) + return errwrap.Wrapf(fmt.Sprintf("failed to remove %q: {{err}}", fullPath), err) } err = c.cleanupLogicalPath(key) @@ -307,8 +304,7 @@ func (c *ZooKeeperBackend) List(ctx context.Context, prefix string) ([]string, e // under the lock file; just treat it like the file Vault expects children = append(children, key[1:]) } else { - msgFmt := "Node %q is both of data and leaf type ??" - panic(fmt.Sprintf(msgFmt, childPath)) + panic(fmt.Sprintf("node %q is both of data and leaf type", childPath)) } } else if stat.DataLength == 0 { // No, we cannot differentiate here on number of children as node @@ -382,7 +378,7 @@ func (i *ZooKeeperHALock) Lock(stopCh <-chan struct{}) (<-chan struct{}, error) // Watch for Events which could result in loss of our zkLock and close(i.leaderCh) currentVal, _, lockeventCh, err := i.in.client.GetW(lockpath) if err != nil { - return nil, fmt.Errorf("unable to watch HA lock: %v", err) + return nil, errwrap.Wrapf("unable to watch HA lock: {{err}}", err) } if i.value != string(currentVal) { return nil, fmt.Errorf("lost HA lock immediately before watch") diff --git a/shamir/shamir.go b/shamir/shamir.go index 7b8fdc366..04650868c 100644 --- a/shamir/shamir.go +++ b/shamir/shamir.go @@ -6,6 +6,8 @@ import ( "fmt" mathrand "math/rand" "time" + + "github.com/hashicorp/errwrap" ) const ( @@ -188,7 +190,7 @@ func Split(secret []byte, parts, threshold int) ([][]byte, error) { for idx, val := range secret { p, err := makePolynomial(val, uint8(threshold-1)) if err != nil { - return nil, fmt.Errorf("failed to generate polynomial: %v", err) + return nil, errwrap.Wrapf("failed to generate polynomial: {{err}}", err) } // Generate a `parts` number of (x,y) pairs diff --git a/vault/audit.go b/vault/audit.go index 6ad3e44e6..611d33f3e 100644 --- a/vault/audit.go +++ b/vault/audit.go @@ -390,7 +390,7 @@ func (c *Core) removeAuditReloadFunc(entry *MountEntry) { func (c *Core) newAuditBackend(ctx context.Context, entry *MountEntry, view logical.Storage, conf map[string]string) (audit.Backend, error) { f, ok := c.auditBackends[entry.Type] if !ok { - return nil, fmt.Errorf("unknown backend type: %s", entry.Type) + return nil, fmt.Errorf("unknown backend type: %q", entry.Type) } saltConfig := &salt.Config{ HMAC: sha256.New, diff --git a/vault/audit_broker.go b/vault/audit_broker.go index 8dc1b909c..ae6f48ecc 100644 --- a/vault/audit_broker.go +++ b/vault/audit_broker.go @@ -65,7 +65,7 @@ func (a *AuditBroker) GetHash(ctx context.Context, name string, input string) (s defer a.RUnlock() be, ok := a.backends[name] if !ok { - return "", fmt.Errorf("unknown audit backend %s", name) + return "", fmt.Errorf("unknown audit backend %q", name) } return be.backend.GetHash(ctx, input) diff --git a/vault/audited_headers.go b/vault/audited_headers.go index 3dc90e005..ca8383ea8 100644 --- a/vault/audited_headers.go +++ b/vault/audited_headers.go @@ -6,6 +6,7 @@ import ( "strings" "sync" + "github.com/hashicorp/errwrap" "github.com/hashicorp/vault/logical" ) @@ -49,11 +50,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 fmt.Errorf("failed to persist audited headers config: %v", err) + return errwrap.Wrapf("failed to persist audited headers config: {{err}}", err) } if err := a.view.Put(ctx, entry); err != nil { - return fmt.Errorf("failed to persist audited headers config: %v", err) + return errwrap.Wrapf("failed to persist audited headers config: {{err}}", err) } return nil @@ -77,11 +78,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 fmt.Errorf("failed to persist audited headers config: %v", err) + return errwrap.Wrapf("failed to persist audited headers config: {{err}}", err) } if err := a.view.Put(ctx, entry); err != nil { - return fmt.Errorf("failed to persist audited headers config: %v", err) + return errwrap.Wrapf("failed to persist audited headers config: {{err}}", err) } return nil @@ -134,7 +135,7 @@ func (c *Core) setupAuditedHeadersConfig(ctx context.Context) error { // Create the config out, err := view.Get(ctx, auditedHeadersEntry) if err != nil { - return fmt.Errorf("failed to read config: %v", err) + return errwrap.Wrapf("failed to read config: {{err}}", err) } headers := make(map[string]*auditedHeaderSettings) diff --git a/vault/auth.go b/vault/auth.go index f5d2dbc30..e94b85d1e 100644 --- a/vault/auth.go +++ b/vault/auth.go @@ -128,7 +128,7 @@ func (c *Core) enableCredential(ctx context.Context, entry *MountEntry) error { // Check for the correct backend type backendType := backend.Type() if entry.Type == "plugin" && backendType != logical.TypeCredential { - return fmt.Errorf("cannot mount '%s' of type '%s' as an auth method", entry.Config.PluginName, backendType) + return fmt.Errorf("cannot mount %q of type %q as an auth method", entry.Config.PluginName, backendType) } // Update the auth table @@ -168,7 +168,7 @@ func (c *Core) disableCredential(ctx context.Context, path string) error { fullPath := credentialRoutePrefix + path view := c.router.MatchingStorageByAPIPath(fullPath) if view == nil { - return fmt.Errorf("no matching backend %s", fullPath) + return fmt.Errorf("no matching backend %q", fullPath) } // Get the backend/mount entry for this path, used to remove ignored @@ -251,7 +251,7 @@ func (c *Core) remountCredEntryForce(ctx context.Context, path string) error { fullPath := credentialRoutePrefix + path me := c.router.MatchingMountEntry(fullPath) if me == nil { - return fmt.Errorf("cannot find mount for path '%s'", path) + return fmt.Errorf("cannot find mount for path %q", path) } me, err := me.Clone() @@ -492,7 +492,7 @@ func (c *Core) setupCredentials(ctx context.Context) error { // Check for the correct backend type backendType = backend.Type() if entry.Type == "plugin" && backendType != logical.TypeCredential { - return fmt.Errorf("cannot mount '%s' of type '%s' as an auth backend", entry.Config.PluginName, backendType) + return fmt.Errorf("cannot mount %q of type %q as an auth backend", entry.Config.PluginName, backendType) } ROUTER_MOUNT: @@ -555,7 +555,7 @@ func (c *Core) newCredentialBackend(ctx context.Context, entry *MountEntry, sysV } f, ok := c.credentialBackends[t] if !ok { - return nil, fmt.Errorf("unknown backend type: %s", t) + return nil, fmt.Errorf("unknown backend type: %q", t) } // Set up conf to pass in plugin_name diff --git a/vault/barrier_aes_gcm.go b/vault/barrier_aes_gcm.go index 9029a6196..cc3b3cd2d 100644 --- a/vault/barrier_aes_gcm.go +++ b/vault/barrier_aes_gcm.go @@ -13,6 +13,7 @@ import ( "time" "github.com/armon/go-metrics" + "github.com/hashicorp/errwrap" "github.com/hashicorp/vault/helper/jsonutil" "github.com/hashicorp/vault/helper/strutil" "github.com/hashicorp/vault/physical" @@ -86,7 +87,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, fmt.Errorf("failed to check for initialization: %v", err) + return false, errwrap.Wrapf("failed to check for initialization: {{err}}", err) } if strutil.StrListContains(keys, "keyring") { return true, nil @@ -95,7 +96,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, fmt.Errorf("failed to check for initialization: %v", err) + return false, errwrap.Wrapf("failed to check for initialization: {{err}}", err) } return out != nil, nil } @@ -119,7 +120,7 @@ func (b *AESGCMBarrier) Initialize(ctx context.Context, key []byte) error { // Generate encryption key encrypt, err := b.GenerateKey() if err != nil { - return fmt.Errorf("failed to generate encryption key: %v", err) + return errwrap.Wrapf("failed to generate encryption key: {{err}}", err) } // Create a new keyring, install the keys @@ -131,7 +132,7 @@ func (b *AESGCMBarrier) Initialize(ctx context.Context, key []byte) error { Value: encrypt, }) if err != nil { - return fmt.Errorf("failed to create keyring: %v", err) + return errwrap.Wrapf("failed to create keyring: {{err}}", err) } return b.persistKeyring(ctx, keyring) } @@ -143,7 +144,7 @@ func (b *AESGCMBarrier) persistKeyring(ctx context.Context, keyring *Keyring) er keyringBuf, err := keyring.Serialize() defer memzero(keyringBuf) if err != nil { - return fmt.Errorf("failed to serialize keyring: %v", err) + return errwrap.Wrapf("failed to serialize keyring: {{err}}", err) } // Create the AES-GCM @@ -161,7 +162,7 @@ func (b *AESGCMBarrier) persistKeyring(ctx context.Context, keyring *Keyring) er Value: value, } if err := b.backend.Put(ctx, pe); err != nil { - return fmt.Errorf("failed to persist keyring: %v", err) + return errwrap.Wrapf("failed to persist keyring: {{err}}", err) } // Serialize the master key value @@ -173,7 +174,7 @@ func (b *AESGCMBarrier) persistKeyring(ctx context.Context, keyring *Keyring) er keyBuf, err := key.Serialize() defer memzero(keyBuf) if err != nil { - return fmt.Errorf("failed to serialize master key: %v", err) + return errwrap.Wrapf("failed to serialize master key: {{err}}", err) } // Encrypt the master key @@ -190,7 +191,7 @@ func (b *AESGCMBarrier) persistKeyring(ctx context.Context, keyring *Keyring) er Value: value, } if err := b.backend.Put(ctx, pe); err != nil { - return fmt.Errorf("failed to persist master key: %v", err) + return errwrap.Wrapf("failed to persist master key: {{err}}", err) } return nil } @@ -245,7 +246,7 @@ func (b *AESGCMBarrier) ReloadKeyring(ctx context.Context) error { // Read in the keyring out, err := b.backend.Get(ctx, keyringPath) if err != nil { - return fmt.Errorf("failed to check for keyring: %v", err) + return errwrap.Wrapf("failed to check for keyring: {{err}}", err) } // Ensure that the keyring exists. This should never happen, @@ -267,7 +268,7 @@ func (b *AESGCMBarrier) ReloadKeyring(ctx context.Context) error { // Recover the keyring keyring, err := DeserializeKeyring(plain) if err != nil { - return fmt.Errorf("keyring deserialization failed: %v", err) + return errwrap.Wrapf("keyring deserialization failed: {{err}}", err) } // Setup the keyring and finish @@ -282,7 +283,7 @@ func (b *AESGCMBarrier) ReloadMasterKey(ctx context.Context) error { // Read the masterKeyPath upgrade out, err := b.Get(ctx, masterKeyPath) if err != nil { - return fmt.Errorf("failed to read master key path: %v", err) + return errwrap.Wrapf("failed to read master key path: {{err}}", err) } // The masterKeyPath could be missing (backwards incompatible), @@ -297,7 +298,7 @@ func (b *AESGCMBarrier) ReloadMasterKey(ctx context.Context) error { // Deserialize the master key key, err := DeserializeKey(out.Value) if err != nil { - return fmt.Errorf("failed to deserialize key: %v", err) + return errwrap.Wrapf("failed to deserialize key: {{err}}", err) } b.l.Lock() @@ -335,7 +336,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 fmt.Errorf("failed to check for keyring: %v", err) + return errwrap.Wrapf("failed to check for keyring: {{err}}", err) } if out != nil { // Decrypt the barrier init key @@ -351,7 +352,7 @@ func (b *AESGCMBarrier) Unseal(ctx context.Context, key []byte) error { // Recover the keyring keyring, err := DeserializeKeyring(plain) if err != nil { - return fmt.Errorf("keyring deserialization failed: %v", err) + return errwrap.Wrapf("keyring deserialization failed: {{err}}", err) } // Setup the keyring and finish @@ -363,7 +364,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 fmt.Errorf("failed to check for initialization: %v", err) + return errwrap.Wrapf("failed to check for initialization: {{err}}", err) } if out == nil { return ErrBarrierNotInit @@ -398,7 +399,7 @@ func (b *AESGCMBarrier) Unseal(ctx context.Context, key []byte) error { Value: init.Key, }) if err != nil { - return fmt.Errorf("failed to create keyring: %v", err) + return errwrap.Wrapf("failed to create keyring: {{err}}", err) } if err := b.persistKeyring(ctx, keyring); err != nil { return err @@ -406,7 +407,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 fmt.Errorf("failed to delete barrier init file: %v", err) + return errwrap.Wrapf("failed to delete barrier init file: {{err}}", err) } // Set the vault as unsealed @@ -441,7 +442,7 @@ func (b *AESGCMBarrier) Rotate(ctx context.Context) (uint32, error) { // Generate a new key encrypt, err := b.GenerateKey() if err != nil { - return 0, fmt.Errorf("failed to generate encryption key: %v", err) + return 0, errwrap.Wrapf("failed to generate encryption key: {{err}}", err) } // Get the next term @@ -455,7 +456,7 @@ func (b *AESGCMBarrier) Rotate(ctx context.Context) (uint32, error) { Value: encrypt, }) if err != nil { - return 0, fmt.Errorf("failed to add new encryption key: %v", err) + return 0, errwrap.Wrapf("failed to add new encryption key: {{err}}", err) } // Persist the new keyring @@ -547,7 +548,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, fmt.Errorf("failed to add new encryption key: %v", err) + return false, 0, errwrap.Wrapf("failed to add new encryption key: {{err}}", err) } b.keyring = newKeyring @@ -674,7 +675,7 @@ func (b *AESGCMBarrier) Get(ctx context.Context, key string) (*Entry, error) { // Decrypt the ciphertext plain, err := b.decryptKeyring(key, pe.Value) if err != nil { - return nil, fmt.Errorf("decryption failed: %v", err) + return nil, errwrap.Wrapf("decryption failed: {{err}}", err) } // Wrap in a logical entry @@ -751,7 +752,7 @@ func (b *AESGCMBarrier) aeadFromKey(key []byte) (cipher.AEAD, error) { // Create the AES cipher aesCipher, err := aes.NewCipher(key) if err != nil { - return nil, fmt.Errorf("failed to create cipher: %v", err) + return nil, errwrap.Wrapf("failed to create cipher: {{err}}", err) } // Create the GCM mode AEAD @@ -877,7 +878,7 @@ func (b *AESGCMBarrier) Decrypt(ctx context.Context, key string, ciphertext []by // Decrypt the ciphertext plain, err := b.decryptKeyring(key, ciphertext) if err != nil { - return nil, fmt.Errorf("decryption failed: %v", err) + return nil, errwrap.Wrapf("decryption failed: {{err}}", err) } return plain, nil } diff --git a/vault/cluster.go b/vault/cluster.go index 91ab84f88..4919b0b2b 100644 --- a/vault/cluster.go +++ b/vault/cluster.go @@ -74,7 +74,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, fmt.Errorf("failed to decode cluster details: %v", err) + return nil, errwrap.Wrapf("failed to decode cluster details: {{err}}", err) } // Set in config file @@ -139,7 +139,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 fmt.Errorf("error parsing local cluster certificate: %v", err) + return errwrap.Wrapf("error parsing local cluster certificate: {{err}}", err) } c.localClusterParsedCert.Store(cert) diff --git a/vault/core.go b/vault/core.go index bb3cf5843..d82d61d82 100644 --- a/vault/core.go +++ b/vault/core.go @@ -461,7 +461,7 @@ func NewCore(conf *CoreConfig) (*Core, error) { if conf.RedirectAddr != "" { u, err := url.Parse(conf.RedirectAddr) if err != nil { - return nil, fmt.Errorf("redirect address is not valid url: %s", err) + return nil, errwrap.Wrapf("redirect address is not valid url: {{err}}", err) } if u.Scheme == "" { @@ -559,14 +559,14 @@ func NewCore(conf *CoreConfig) (*Core, error) { if conf.PluginDirectory != "" { c.pluginDirectory, err = filepath.Abs(conf.PluginDirectory) if err != nil { - return nil, fmt.Errorf("core setup failed, could not verify plugin directory: %v", err) + return nil, errwrap.Wrapf("core setup failed, could not verify plugin directory: {{err}}", err) } } // Construct a new AES-GCM barrier c.barrier, err = NewAESGCMBarrier(c.physical) if err != nil { - return nil, fmt.Errorf("barrier setup failed: %v", err) + return nil, errwrap.Wrapf("barrier setup failed: {{err}}", err) } if conf.HAPhysical != nil && conf.HAPhysical.HAEnabled() { @@ -1167,7 +1167,7 @@ func (c *Core) unsealPart(ctx context.Context, config *SealConfig, key []byte, u } else { recoveredKey, err = shamir.Combine(c.unlockInfo.Parts) if err != nil { - return nil, fmt.Errorf("failed to compute master key: %v", err) + return nil, errwrap.Wrapf("failed to compute master key: {{err}}", err) } } @@ -1186,7 +1186,7 @@ func (c *Core) unsealPart(ctx context.Context, config *SealConfig, key []byte, u if c.seal.StoredKeysSupported() { masterKeyShares, err := c.seal.GetStoredKeys(ctx) if err != nil { - return nil, fmt.Errorf("unable to retrieve stored keys: %v", err) + return nil, errwrap.Wrapf("unable to retrieve stored keys: {{err}}", err) } if len(masterKeyShares) == 1 { @@ -1195,7 +1195,7 @@ func (c *Core) unsealPart(ctx context.Context, config *SealConfig, key []byte, u masterKey, err = shamir.Combine(masterKeyShares) if err != nil { - return nil, fmt.Errorf("failed to compute master key: %v", err) + return nil, errwrap.Wrapf("failed to compute master key: {{err}}", err) } } return masterKey, nil @@ -2082,7 +2082,7 @@ func (c *Core) scheduleUpgradeCleanup(ctx context.Context) error { // List the upgrades upgrades, err := c.barrier.List(ctx, keyringUpgradePrefix) if err != nil { - return fmt.Errorf("failed to list upgrades: %v", err) + return errwrap.Wrapf("failed to list upgrades: {{err}}", err) } // Nothing to do if no upgrades diff --git a/vault/cors.go b/vault/cors.go index 63a95b528..4ab56b76d 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/helper/consts" "github.com/hashicorp/vault/helper/strutil" "github.com/hashicorp/vault/logical" @@ -52,11 +52,11 @@ func (c *Core) saveCORSConfig(ctx context.Context) error { entry, err := logical.StorageEntryJSON("cors", localConfig) if err != nil { - return fmt.Errorf("failed to create CORS config entry: %v", err) + return errwrap.Wrapf("failed to create CORS config entry: {{err}}", err) } if err := view.Put(ctx, entry); err != nil { - return fmt.Errorf("failed to save CORS config: %v", err) + return errwrap.Wrapf("failed to save CORS config: {{err}}", err) } return nil @@ -69,7 +69,7 @@ func (c *Core) loadCORSConfig(ctx context.Context) error { // Load the config in out, err := view.Get(ctx, "cors") if err != nil { - return fmt.Errorf("failed to read CORS config: %v", err) + return errwrap.Wrapf("failed to read CORS config: {{err}}", err) } if out == nil { return nil diff --git a/vault/expiration.go b/vault/expiration.go index 7882c709a..81ed2c99c 100644 --- a/vault/expiration.go +++ b/vault/expiration.go @@ -206,12 +206,12 @@ func (m *ExpirationManager) Tidy() error { le, err := m.loadEntry(leaseID) if err != nil { - tidyErrors = multierror.Append(tidyErrors, fmt.Errorf("failed to load the lease ID %q: %v", leaseID, err)) + tidyErrors = multierror.Append(tidyErrors, errwrap.Wrapf(fmt.Sprintf("failed to load the lease ID %q: {{err}}", leaseID), err)) return } if le == nil { - tidyErrors = multierror.Append(tidyErrors, fmt.Errorf("nil entry for lease ID %q: %v", leaseID, err)) + tidyErrors = multierror.Append(tidyErrors, errwrap.Wrapf(fmt.Sprintf("nil entry for lease ID %q: {{err}}", leaseID), err)) return } @@ -228,7 +228,7 @@ func (m *ExpirationManager) Tidy() error { if !ok { saltedID, err := m.tokenStore.SaltID(m.quitContext, le.ClientToken) if err != nil { - tidyErrors = multierror.Append(tidyErrors, fmt.Errorf("failed to lookup salt id: %v", err)) + tidyErrors = multierror.Append(tidyErrors, errwrap.Wrapf("failed to lookup salt id: {{err}}", err)) return } lock := locksutil.LockForKey(m.tokenStore.tokenLocks, le.ClientToken) @@ -237,7 +237,7 @@ func (m *ExpirationManager) Tidy() error { lock.RUnlock() if err != nil { - tidyErrors = multierror.Append(tidyErrors, fmt.Errorf("failed to lookup token: %v", err)) + tidyErrors = multierror.Append(tidyErrors, errwrap.Wrapf("failed to lookup token: {{err}}", err)) return } @@ -267,7 +267,7 @@ func (m *ExpirationManager) Tidy() error { // again err = m.revokeCommon(leaseID, true, true) if err != nil { - tidyErrors = multierror.Append(tidyErrors, fmt.Errorf("failed to revoke an invalid lease with ID %q: %v", leaseID, err)) + tidyErrors = multierror.Append(tidyErrors, errwrap.Wrapf(fmt.Sprintf("failed to revoke an invalid lease with ID %q: {{err}}", leaseID), err)) return } revokedCount++ @@ -563,14 +563,13 @@ func (m *ExpirationManager) RevokeByToken(te *TokenEntry) error { // Lookup the leases existing, err := m.lookupByToken(te.ID) if err != nil { - return fmt.Errorf("failed to scan for leases: %v", err) + return errwrap.Wrapf("failed to scan for leases: {{err}}", err) } // Revoke all the keys for idx, leaseID := range existing { if err := m.revokeCommon(leaseID, false, false); err != nil { - return fmt.Errorf("failed to revoke '%s' (%d / %d): %v", - leaseID, idx+1, len(existing), err) + return errwrap.Wrapf(fmt.Sprintf("failed to revoke %q (%d / %d): {{err}}", leaseID, idx+1, len(existing)), err) } } @@ -609,15 +608,14 @@ func (m *ExpirationManager) revokePrefixCommon(prefix string, force bool) error sub := m.idView.SubView(prefix) existing, err := logical.CollectKeys(m.quitContext, sub) if err != nil { - return fmt.Errorf("failed to scan for leases: %v", err) + return errwrap.Wrapf("failed to scan for leases: {{err}}", err) } // Revoke all the keys for idx, suffix := range existing { leaseID := prefix + suffix if err := m.revokeCommon(leaseID, force, false); err != nil { - return fmt.Errorf("failed to revoke '%s' (%d / %d): %v", - leaseID, idx+1, len(existing), err) + return errwrap.Wrapf(fmt.Sprintf("failed to revoke %q (%d / %d): {{err}}", leaseID, idx+1, len(existing)), err) } } return nil @@ -648,7 +646,7 @@ func (m *ExpirationManager) Renew(leaseID string, increment time.Duration) (*log sysView := m.router.MatchingSystemView(le.Path) if sysView == nil { - return nil, fmt.Errorf("expiration: unable to retrieve system view from router") + return nil, fmt.Errorf("unable to retrieve system view from router") } // Attempt to renew the entry @@ -779,7 +777,7 @@ func (m *ExpirationManager) RenewToken(req *logical.Request, source string, toke sysView := m.router.MatchingSystemView(le.Path) if sysView == nil { - return nil, fmt.Errorf("expiration: unable to retrieve system view from router") + return nil, fmt.Errorf("unable to retrieve system view from router") } ttl, warnings, err := framework.CalculateTTL(sysView, increment, resp.Auth.TTL, resp.Auth.Period, resp.Auth.MaxTTL, resp.Auth.ExplicitMaxTTL, le.IssueTime) @@ -817,7 +815,7 @@ func (m *ExpirationManager) Register(req *logical.Request, resp *logical.Respons defer metrics.MeasureSince([]string{"expire", "register"}, time.Now()) if req.ClientToken == "" { - return "", fmt.Errorf("expiration: cannot register a lease with an empty client token") + return "", fmt.Errorf("cannot register a lease with an empty client token") } // Ignore if there is no leased secret @@ -895,11 +893,11 @@ func (m *ExpirationManager) RegisterAuth(source string, auth *logical.Auth) erro defer metrics.MeasureSince([]string{"expire", "register-auth"}, time.Now()) if auth.ClientToken == "" { - return fmt.Errorf("expiration: cannot register an auth lease with an empty token") + return fmt.Errorf("cannot register an auth lease with an empty token") } if strings.Contains(source, "..") { - return fmt.Errorf("expiration: %s", consts.ErrPathContainsParentReferences) + return consts.ErrPathContainsParentReferences } saltedID, err := m.tokenStore.SaltID(m.quitContext, auth.ClientToken) @@ -1048,7 +1046,7 @@ func (m *ExpirationManager) revokeEntry(le *leaseEntry) error { // backend and directly interact with the token store if le.Auth != nil { if err := m.tokenStore.RevokeTree(m.quitContext, le.ClientToken); err != nil { - return fmt.Errorf("failed to revoke token: %v", err) + return errwrap.Wrapf("failed to revoke token: {{err}}", err) } return nil @@ -1057,7 +1055,7 @@ func (m *ExpirationManager) revokeEntry(le *leaseEntry) error { // Handle standard revocation via backends resp, err := m.router.Route(m.quitContext, logical.RevokeRequest(le.Path, le.Secret, le.Data)) if err != nil || (resp != nil && resp.IsError()) { - return fmt.Errorf("failed to revoke entry: resp:%#v err:%s", resp, err) + return errwrap.Wrapf(fmt.Sprintf("failed to revoke entry: resp: %#v err: {{err}}", resp), err) } return nil } @@ -1071,7 +1069,7 @@ func (m *ExpirationManager) renewEntry(le *leaseEntry, increment time.Duration) req := logical.RenewRequest(le.Path, &secret, le.Data) resp, err := m.router.Route(m.quitContext, req) if err != nil || (resp != nil && resp.IsError()) { - return nil, fmt.Errorf("failed to renew entry: resp:%#v err:%s", resp, err) + return nil, errwrap.Wrapf(fmt.Sprintf("failed to renew entry: resp: %#v err: {{err}}", resp), err) } return resp, nil } @@ -1092,7 +1090,7 @@ func (m *ExpirationManager) renewAuthEntry(req *logical.Request, le *leaseEntry, authReq.Connection = req.Connection resp, err := m.router.Route(m.quitContext, authReq) if err != nil { - return nil, fmt.Errorf("failed to renew entry: %v", err) + return nil, errwrap.Wrapf("failed to renew entry: {{err}}", err) } return resp, nil } @@ -1119,14 +1117,14 @@ func (m *ExpirationManager) loadEntry(leaseID string) (*leaseEntry, error) { func (m *ExpirationManager) loadEntryInternal(leaseID string, restoreMode bool, checkRestored bool) (*leaseEntry, error) { out, err := m.idView.Get(m.quitContext, leaseID) if err != nil { - return nil, fmt.Errorf("failed to read lease entry: %v", err) + return nil, errwrap.Wrapf("failed to read lease entry: {{err}}", err) } if out == nil { return nil, nil } le, err := decodeLeaseEntry(out.Value) if err != nil { - return nil, fmt.Errorf("failed to decode lease entry: %v", err) + return nil, errwrap.Wrapf("failed to decode lease entry: {{err}}", err) } if restoreMode { @@ -1154,7 +1152,7 @@ func (m *ExpirationManager) persistEntry(le *leaseEntry) error { // Encode the entry buf, err := le.encode() if err != nil { - return fmt.Errorf("failed to encode lease entry: %v", err) + return errwrap.Wrapf("failed to encode lease entry: {{err}}", err) } // Write out to the view @@ -1166,7 +1164,7 @@ func (m *ExpirationManager) persistEntry(le *leaseEntry) error { ent.SealWrap = true } if err := m.idView.Put(m.quitContext, &ent); err != nil { - return fmt.Errorf("failed to persist lease entry: %v", err) + return errwrap.Wrapf("failed to persist lease entry: {{err}}", err) } return nil } @@ -1174,7 +1172,7 @@ func (m *ExpirationManager) persistEntry(le *leaseEntry) error { // deleteEntry is used to delete a lease entry func (m *ExpirationManager) deleteEntry(leaseID string) error { if err := m.idView.Delete(m.quitContext, leaseID); err != nil { - return fmt.Errorf("failed to delete lease entry: %v", err) + return errwrap.Wrapf("failed to delete lease entry: {{err}}", err) } return nil } @@ -1196,7 +1194,7 @@ func (m *ExpirationManager) createIndexByToken(token, leaseID string) error { Value: []byte(leaseID), } if err := m.tokenView.Put(m.quitContext, &ent); err != nil { - return fmt.Errorf("failed to persist lease index entry: %v", err) + return errwrap.Wrapf("failed to persist lease index entry: {{err}}", err) } return nil } @@ -1235,7 +1233,7 @@ func (m *ExpirationManager) removeIndexByToken(token, leaseID string) error { key := saltedID + "/" + leaseSaltedID if err := m.tokenView.Delete(m.quitContext, key); err != nil { - return fmt.Errorf("failed to delete lease index entry: %v", err) + return errwrap.Wrapf("failed to delete lease index entry: {{err}}", err) } return nil } @@ -1251,7 +1249,7 @@ func (m *ExpirationManager) lookupByToken(token string) ([]string, error) { prefix := saltedID + "/" subKeys, err := m.tokenView.List(m.quitContext, prefix) if err != nil { - return nil, fmt.Errorf("failed to list leases: %v", err) + return nil, errwrap.Wrapf("failed to list leases: {{err}}", err) } // Read each index entry @@ -1259,7 +1257,7 @@ func (m *ExpirationManager) lookupByToken(token string) ([]string, error) { for _, sub := range subKeys { out, err := m.tokenView.Get(m.quitContext, prefix+sub) if err != nil { - return nil, fmt.Errorf("failed to read lease index: %v", err) + return nil, errwrap.Wrapf("failed to read lease index: {{err}}", err) } if out == nil { continue diff --git a/vault/generate_root.go b/vault/generate_root.go index 8df81be13..16aad49ec 100644 --- a/vault/generate_root.go +++ b/vault/generate_root.go @@ -6,6 +6,7 @@ import ( "encoding/base64" "fmt" + "github.com/hashicorp/errwrap" "github.com/hashicorp/go-uuid" "github.com/hashicorp/vault/helper/consts" "github.com/hashicorp/vault/helper/pgpkeys" @@ -118,7 +119,7 @@ func (c *Core) GenerateRootInit(otp, pgpKey string, strategy GenerateRootStrateg case len(otp) > 0: otpBytes, err := base64.StdEncoding.DecodeString(otp) if err != nil { - return fmt.Errorf("error decoding base64 OTP value: %s", err) + return errwrap.Wrapf("error decoding base64 OTP value: {{err}}", err) } if otpBytes == nil || len(otpBytes) != 16 { return fmt.Errorf("decoded OTP value is invalid or wrong length") @@ -127,7 +128,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 fmt.Errorf("error parsing PGP key: %s", err) + return errwrap.Wrapf("error parsing PGP key: {{err}}", err) } if len(fingerprints) != 1 || fingerprints[0] == "" { return fmt.Errorf("could not acquire PGP key entity") @@ -226,7 +227,7 @@ func (c *Core) GenerateRootUpdate(ctx context.Context, key []byte, nonce string, } if nonce != c.generateRootConfig.Nonce { - return nil, fmt.Errorf("incorrect nonce supplied; nonce for this root generation operation is %s", c.generateRootConfig.Nonce) + return nil, fmt.Errorf("incorrect nonce supplied; nonce for this root generation operation is %q", c.generateRootConfig.Nonce) } if strategy != c.generateRootConfig.Strategy { @@ -265,7 +266,7 @@ func (c *Core) GenerateRootUpdate(ctx context.Context, key []byte, nonce string, masterKey, err = shamir.Combine(c.generateRootProgress) c.generateRootProgress = nil if err != nil { - return nil, fmt.Errorf("failed to compute master key: %v", err) + return nil, errwrap.Wrapf("failed to compute master key: {{err}}", err) } } diff --git a/vault/identity_store.go b/vault/identity_store.go index 006027045..518fa123d 100644 --- a/vault/identity_store.go +++ b/vault/identity_store.go @@ -6,6 +6,7 @@ import ( "strings" "github.com/golang/protobuf/ptypes" + "github.com/hashicorp/errwrap" log "github.com/hashicorp/go-hclog" memdb "github.com/hashicorp/go-memdb" "github.com/hashicorp/vault/helper/identity" @@ -30,7 +31,7 @@ func NewIdentityStore(ctx context.Context, core *Core, config *logical.BackendCo // Create a new in-memory database for the identity store db, err := memdb.NewMemDB(identityStoreSchema()) if err != nil { - return nil, fmt.Errorf("failed to create memdb for identity store: %v", err) + return nil, errwrap.Wrapf("failed to create memdb for identity store: {{err}}", err) } iStore := &IdentityStore{ @@ -43,12 +44,12 @@ func NewIdentityStore(ctx context.Context, core *Core, config *logical.BackendCo iStore.entityPacker, err = storagepacker.NewStoragePacker(iStore.view, iStore.logger, "") if err != nil { - return nil, fmt.Errorf("failed to create entity packer: %v", err) + return nil, errwrap.Wrapf("failed to create entity packer: {{err}}", err) } iStore.groupPacker, err = storagepacker.NewStoragePacker(iStore.view, iStore.logger, groupBucketsPrefix) if err != nil { - return nil, fmt.Errorf("failed to create group packer: %v", err) + return nil, errwrap.Wrapf("failed to create group packer: {{err}}", err) } iStore.Backend = &framework.Backend{ @@ -246,7 +247,7 @@ func (i *IdentityStore) parseEntityFromBucketItem(ctx context.Context, item *sto var entity identity.Entity err := ptypes.UnmarshalAny(item.Message, &entity) if err != nil { - return nil, fmt.Errorf("failed to decode entity from storage bucket item: %v", err) + return nil, errwrap.Wrapf("failed to decode entity from storage bucket item: {{err}}", err) } return &entity, nil @@ -260,7 +261,7 @@ func (i *IdentityStore) parseGroupFromBucketItem(item *storagepacker.Item) (*ide var group identity.Group err := ptypes.UnmarshalAny(item.Message, &group) if err != nil { - return nil, fmt.Errorf("failed to decode group from storage bucket item: %v", err) + return nil, errwrap.Wrapf("failed to decode group from storage bucket item: {{err}}", err) } return &group, nil diff --git a/vault/identity_store_aliases.go b/vault/identity_store_aliases.go index daf8404b2..2032bfa06 100644 --- a/vault/identity_store_aliases.go +++ b/vault/identity_store_aliases.go @@ -6,6 +6,7 @@ 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/logical" @@ -407,7 +408,7 @@ func (i *IdentityStore) pathAliasIDList() framework.OperationFunc { ws := memdb.NewWatchSet() iter, err := i.MemDBAliases(ws, false) if err != nil { - return nil, fmt.Errorf("failed to fetch iterator for aliases in memdb: %v", err) + return nil, errwrap.Wrapf("failed to fetch iterator for aliases in memdb: {{err}}", err) } var aliasIDs []string diff --git a/vault/identity_store_entities.go b/vault/identity_store_entities.go index 6288ce880..920a417ee 100644 --- a/vault/identity_store_entities.go +++ b/vault/identity_store_entities.go @@ -6,6 +6,7 @@ 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/locksutil" @@ -229,7 +230,7 @@ func (i *IdentityStore) pathEntityMergeID() framework.OperationFunc { if fromLockHeld { fromEntityLock.Unlock() } - return nil, fmt.Errorf("failed to update alias during merge: %v", err) + return nil, errwrap.Wrapf("failed to update alias during merge: {{err}}", err) } // Add the alias to the desired entity @@ -503,7 +504,7 @@ func (i *IdentityStore) pathEntityIDList() framework.OperationFunc { ws := memdb.NewWatchSet() iter, err := i.MemDBEntities(ws) if err != nil { - return nil, fmt.Errorf("failed to fetch iterator for entities in memdb: %v", err) + return nil, errwrap.Wrapf("failed to fetch iterator for entities in memdb: {{err}}", err) } var entityIDs []string diff --git a/vault/identity_store_group_aliases.go b/vault/identity_store_group_aliases.go index 6b497088b..32bd5239a 100644 --- a/vault/identity_store_group_aliases.go +++ b/vault/identity_store_group_aliases.go @@ -5,6 +5,7 @@ import ( "fmt" "strings" + "github.com/hashicorp/errwrap" memdb "github.com/hashicorp/go-memdb" "github.com/hashicorp/vault/helper/identity" "github.com/hashicorp/vault/logical" @@ -258,7 +259,7 @@ func (i *IdentityStore) pathGroupAliasIDList() framework.OperationFunc { ws := memdb.NewWatchSet() iter, err := i.MemDBAliases(ws, true) if err != nil { - return nil, fmt.Errorf("failed to fetch iterator for group aliases in memdb: %v", err) + return nil, errwrap.Wrapf("failed to fetch iterator for group aliases in memdb: {{err}}", err) } var groupAliasIDs []string diff --git a/vault/identity_store_groups.go b/vault/identity_store_groups.go index e9985cde8..c8bf52d19 100644 --- a/vault/identity_store_groups.go +++ b/vault/identity_store_groups.go @@ -6,6 +6,7 @@ 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/logical" @@ -326,7 +327,7 @@ func (i *IdentityStore) pathGroupIDList() framework.OperationFunc { ws := memdb.NewWatchSet() iter, err := i.MemDBGroupIterator(ws) if err != nil { - return nil, fmt.Errorf("failed to fetch iterator for group in memdb: %v", err) + return nil, errwrap.Wrapf("failed to fetch iterator for group in memdb: {{err}}", err) } var groupIDs []string diff --git a/vault/identity_store_util.go b/vault/identity_store_util.go index aeb1098be..c52eb7847 100644 --- a/vault/identity_store_util.go +++ b/vault/identity_store_util.go @@ -7,6 +7,7 @@ import ( "sync" "github.com/golang/protobuf/ptypes" + "github.com/hashicorp/errwrap" memdb "github.com/hashicorp/go-memdb" uuid "github.com/hashicorp/go-uuid" "github.com/hashicorp/vault/helper/consts" @@ -40,7 +41,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 fmt.Errorf("failed to scan for groups: %v", err) + return errwrap.Wrapf("failed to scan for groups: {{err}}", err) } i.logger.Debug("groups collected", "num_existing", len(existing)) @@ -75,7 +76,7 @@ func (i *IdentityStore) loadGroups(ctx context.Context) error { err = i.upsertGroupInTxn(txn, group, false) if err != nil { txn.Abort() - return fmt.Errorf("failed to update group in memdb: %v", err) + return errwrap.Wrapf("failed to update group in memdb: {{err}}", err) } txn.Commit() @@ -94,7 +95,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 fmt.Errorf("failed to scan for entities: %v", err) + return errwrap.Wrapf("failed to scan for entities: {{err}}", err) } i.logger.Debug("entities collected", "num_existing", len(existing)) @@ -190,7 +191,7 @@ func (i *IdentityStore) loadEntities(ctx context.Context) error { // Only update MemDB and don't hit the storage again err = i.upsertEntity(entity, nil, false) if err != nil { - return fmt.Errorf("failed to update entity in MemDB: %v", err) + return errwrap.Wrapf("failed to update entity in MemDB: {{err}}", err) } } } @@ -532,18 +533,18 @@ func (i *IdentityStore) MemDBUpsertAliasInTxn(txn *memdb.Txn, alias *identity.Al aliasRaw, err := txn.First(tableName, "id", alias.ID) if err != nil { - return fmt.Errorf("failed to lookup alias from memdb using alias ID: %v", err) + return errwrap.Wrapf("failed to lookup alias from memdb using alias ID: {{err}}", err) } if aliasRaw != nil { err = txn.Delete(tableName, aliasRaw) if err != nil { - return fmt.Errorf("failed to delete alias from memdb: %v", err) + return errwrap.Wrapf("failed to delete alias from memdb: {{err}}", err) } } if err := txn.Insert(tableName, alias); err != nil { - return fmt.Errorf("failed to update alias into memdb: %v", err) + return errwrap.Wrapf("failed to update alias into memdb: {{err}}", err) } return nil @@ -583,7 +584,7 @@ func (i *IdentityStore) MemDBAliasByCanonicalIDInTxn(txn *memdb.Txn, canonicalID aliasRaw, err := txn.First(tableName, "canonical_id", canonicalID) if err != nil { - return nil, fmt.Errorf("failed to fetch alias from memdb using canonical ID: %v", err) + return nil, errwrap.Wrapf("failed to fetch alias from memdb using canonical ID: {{err}}", err) } if aliasRaw == nil { @@ -628,7 +629,7 @@ func (i *IdentityStore) MemDBAliasByIDInTxn(txn *memdb.Txn, aliasID string, clon aliasRaw, err := txn.First(tableName, "id", aliasID) if err != nil { - return nil, fmt.Errorf("failed to fetch alias from memdb using alias ID: %v", err) + return nil, errwrap.Wrapf("failed to fetch alias from memdb using alias ID: {{err}}", err) } if aliasRaw == nil { @@ -691,7 +692,7 @@ func (i *IdentityStore) MemDBAliasByFactorsInTxn(txn *memdb.Txn, mountAccessor, aliasRaw, err := txn.First(tableName, "factors", mountAccessor, aliasName) if err != nil { - return nil, fmt.Errorf("failed to fetch alias from memdb using factors: %v", err) + return nil, errwrap.Wrapf("failed to fetch alias from memdb using factors: {{err}}", err) } if aliasRaw == nil { @@ -731,7 +732,7 @@ func (i *IdentityStore) MemDBAliasesByMetadata(filters map[string]string, clone aliasesIter, err := txn.Get(tableName, "metadata", args...) if err != nil { - return nil, fmt.Errorf("failed to lookup aliases using metadata: %v", err) + return nil, errwrap.Wrapf("failed to lookup aliases using metadata: {{err}}", err) } var aliases []*identity.Alias @@ -793,7 +794,7 @@ func (i *IdentityStore) MemDBDeleteAliasByIDInTxn(txn *memdb.Txn, aliasID string err = txn.Delete(tableName, alias) if err != nil { - return fmt.Errorf("failed to delete alias from memdb: %v", err) + return errwrap.Wrapf("failed to delete alias from memdb: {{err}}", err) } return nil @@ -828,18 +829,18 @@ func (i *IdentityStore) MemDBUpsertEntityInTxn(txn *memdb.Txn, entity *identity. entityRaw, err := txn.First(entitiesTable, "id", entity.ID) if err != nil { - return fmt.Errorf("failed to lookup entity from memdb using entity id: %v", err) + return errwrap.Wrapf("failed to lookup entity from memdb using entity id: {{err}}", err) } if entityRaw != nil { err = txn.Delete(entitiesTable, entityRaw) if err != nil { - return fmt.Errorf("failed to delete entity from memdb: %v", err) + return errwrap.Wrapf("failed to delete entity from memdb: {{err}}", err) } } if err := txn.Insert(entitiesTable, entity); err != nil { - return fmt.Errorf("failed to update entity into memdb: %v", err) + return errwrap.Wrapf("failed to update entity into memdb: {{err}}", err) } return nil @@ -874,7 +875,7 @@ func (i *IdentityStore) MemDBEntityByIDInTxn(txn *memdb.Txn, entityID string, cl entityRaw, err := txn.First(entitiesTable, "id", entityID) if err != nil { - return nil, fmt.Errorf("failed to fetch entity from memdb using entity id: %v", err) + return nil, errwrap.Wrapf("failed to fetch entity from memdb using entity id: {{err}}", err) } if entityRaw == nil { @@ -914,7 +915,7 @@ func (i *IdentityStore) MemDBEntityByNameInTxn(txn *memdb.Txn, entityName string entityRaw, err := txn.First(entitiesTable, "name", entityName) if err != nil { - return nil, fmt.Errorf("failed to fetch entity from memdb using entity name: %v", err) + return nil, errwrap.Wrapf("failed to fetch entity from memdb using entity name: {{err}}", err) } if entityRaw == nil { @@ -959,7 +960,7 @@ func (i *IdentityStore) MemDBEntitiesByMetadata(filters map[string]string, clone entitiesIter, err := txn.Get(entitiesTable, "metadata", args...) if err != nil { - return nil, fmt.Errorf("failed to lookup entities using metadata: %v", err) + return nil, errwrap.Wrapf("failed to lookup entities using metadata: {{err}}", err) } var entities []*identity.Entity @@ -1000,7 +1001,7 @@ func (i *IdentityStore) MemDBEntitiesByBucketEntryKeyHashInTxn(txn *memdb.Txn, h entitiesIter, err := txn.Get(entitiesTable, "bucket_key_hash", hashValue) if err != nil { - return nil, fmt.Errorf("failed to lookup entities using bucket entry key hash: %v", err) + return nil, errwrap.Wrapf("failed to lookup entities using bucket entry key hash: {{err}}", err) } var entities []*identity.Entity @@ -1022,7 +1023,7 @@ func (i *IdentityStore) MemDBEntityByMergedEntityIDInTxn(txn *memdb.Txn, mergedE entityRaw, err := txn.First(entitiesTable, "merged_entity_ids", mergedEntityID) if err != nil { - return nil, fmt.Errorf("failed to fetch entity from memdb using merged entity id: %v", err) + return nil, errwrap.Wrapf("failed to fetch entity from memdb using merged entity id: {{err}}", err) } if entityRaw == nil { @@ -1120,7 +1121,7 @@ func (i *IdentityStore) MemDBDeleteEntityByIDInTxn(txn *memdb.Txn, entityID stri err = txn.Delete(entitiesTable, entity) if err != nil { - return fmt.Errorf("failed to delete entity from memdb: %v", err) + return errwrap.Wrapf("failed to delete entity from memdb: {{err}}", err) } return nil @@ -1159,7 +1160,7 @@ func (i *IdentityStore) sanitizeAlias(alias *identity.Alias) error { // Alias metadata should always be map[string]string err = validateMetadata(alias.Metadata) if err != nil { - return fmt.Errorf("invalid alias metadata: %v", err) + return errwrap.Wrapf("invalid alias metadata: {{err}}", err) } // Create an ID if there isn't one already @@ -1210,7 +1211,7 @@ func (i *IdentityStore) sanitizeEntity(entity *identity.Entity) error { // Entity metadata should always be map[string]string err = validateMetadata(entity.Metadata) if err != nil { - return fmt.Errorf("invalid entity metadata: %v", err) + return errwrap.Wrapf("invalid entity metadata: {{err}}", err) } // Set the creation and last update times @@ -1253,7 +1254,7 @@ func (i *IdentityStore) sanitizeAndUpsertGroup(group *identity.Group, memberGrou // Entity metadata should always be map[string]string err = validateMetadata(group.Metadata) if err != nil { - return fmt.Errorf("invalid group metadata: %v", err) + return errwrap.Wrapf("invalid group metadata: {{err}}", err) } // Set the creation and last update times @@ -1375,7 +1376,7 @@ func (i *IdentityStore) validateMemberGroupID(groupID string, memberGroupID stri func (i *IdentityStore) validateEntityID(entityID string) error { entity, err := i.MemDBEntityByID(entityID, false) if err != nil { - return fmt.Errorf("failed to validate entity ID %q: %v", entityID, err) + return errwrap.Wrapf(fmt.Sprintf("failed to validate entity ID %q: {{err}}", entityID), err) } if entity == nil { return fmt.Errorf("invalid entity ID %q", entityID) @@ -1386,7 +1387,7 @@ func (i *IdentityStore) validateEntityID(entityID string) error { func (i *IdentityStore) validateGroupID(groupID string) error { group, err := i.MemDBGroupByID(groupID, false) if err != nil { - return fmt.Errorf("failed to validate group ID %q: %v", groupID, err) + return errwrap.Wrapf(fmt.Sprintf("failed to validate group ID %q: {{err}}", groupID), err) } if group == nil { return fmt.Errorf("invalid group ID %q", groupID) @@ -1489,7 +1490,7 @@ func validateMetadata(meta map[string]string) error { for key, value := range meta { if err := validateMetaPair(key, value); err != nil { - return fmt.Errorf("failed to load metadata pair (%q, %q): %v", key, value, err) + return errwrap.Wrapf(fmt.Sprintf("failed to load metadata pair (%q, %q): {{err}}", key, value), err) } } @@ -1537,7 +1538,7 @@ func (i *IdentityStore) MemDBGroupByNameInTxn(txn *memdb.Txn, groupName string, groupRaw, err := txn.First(groupsTable, "name", groupName) if err != nil { - return nil, fmt.Errorf("failed to fetch group from memdb using group name: %v", err) + return nil, errwrap.Wrapf("failed to fetch group from memdb using group name: {{err}}", err) } if groupRaw == nil { @@ -1644,18 +1645,18 @@ func (i *IdentityStore) MemDBUpsertGroupInTxn(txn *memdb.Txn, group *identity.Gr groupRaw, err := txn.First(groupsTable, "id", group.ID) if err != nil { - return fmt.Errorf("failed to lookup group from memdb using group id: %v", err) + return errwrap.Wrapf("failed to lookup group from memdb using group id: {{err}}", err) } if groupRaw != nil { err = txn.Delete(groupsTable, groupRaw) if err != nil { - return fmt.Errorf("failed to delete group from memdb: %v", err) + return errwrap.Wrapf("failed to delete group from memdb: {{err}}", err) } } if err := txn.Insert(groupsTable, group); err != nil { - return fmt.Errorf("failed to update group into memdb: %v", err) + return errwrap.Wrapf("failed to update group into memdb: {{err}}", err) } return nil @@ -1733,7 +1734,7 @@ func (i *IdentityStore) MemDBDeleteGroupByIDInTxn(txn *memdb.Txn, groupID string err = txn.Delete("groups", group) if err != nil { - return fmt.Errorf("failed to delete group from memdb: %v", err) + return errwrap.Wrapf("failed to delete group from memdb: {{err}}", err) } return nil @@ -1804,7 +1805,7 @@ func (i *IdentityStore) MemDBDeleteGroupByNameInTxn(txn *memdb.Txn, groupName st err = txn.Delete(groupsTable, group) if err != nil { - return fmt.Errorf("failed to delete group from memdb: %v", err) + return errwrap.Wrapf("failed to delete group from memdb: {{err}}", err) } return nil @@ -1821,7 +1822,7 @@ func (i *IdentityStore) MemDBGroupByIDInTxn(txn *memdb.Txn, groupID string, clon groupRaw, err := txn.First(groupsTable, "id", groupID) if err != nil { - return nil, fmt.Errorf("failed to fetch group from memdb using group ID: %v", err) + return nil, errwrap.Wrapf("failed to fetch group from memdb using group ID: {{err}}", err) } if groupRaw == nil { @@ -1857,7 +1858,7 @@ func (i *IdentityStore) MemDBGroupsByPolicyInTxn(txn *memdb.Txn, policyName stri groupsIter, err := txn.Get(groupsTable, "policies", policyName) if err != nil { - return nil, fmt.Errorf("failed to lookup groups using policy name: %v", err) + return nil, errwrap.Wrapf("failed to lookup groups using policy name: {{err}}", err) } var groups []*identity.Group @@ -1892,7 +1893,7 @@ func (i *IdentityStore) MemDBGroupsByParentGroupIDInTxn(txn *memdb.Txn, memberGr groupsIter, err := txn.Get(groupsTable, "parent_group_ids", memberGroupID) if err != nil { - return nil, fmt.Errorf("failed to lookup groups using member group ID: %v", err) + return nil, errwrap.Wrapf("failed to lookup groups using member group ID: {{err}}", err) } var groups []*identity.Group @@ -1934,7 +1935,7 @@ func (i *IdentityStore) MemDBGroupsByMemberEntityIDInTxn(txn *memdb.Txn, entityI groupsIter, err := txn.Get(groupsTable, "member_entity_ids", entityID) if err != nil { - return nil, fmt.Errorf("failed to lookup groups using entity ID: %v", err) + return nil, errwrap.Wrapf("failed to lookup groups using entity ID: {{err}}", err) } var groups []*identity.Group @@ -2201,7 +2202,7 @@ func (i *IdentityStore) MemDBGroupsByBucketEntryKeyHashInTxn(txn *memdb.Txn, has groupsIter, err := txn.Get(groupsTable, "bucket_key_hash", hashValue) if err != nil { - return nil, fmt.Errorf("failed to lookup groups using bucket entry key hash: %v", err) + return nil, errwrap.Wrapf("failed to lookup groups using bucket entry key hash: {{err}}", err) } var groups []*identity.Group diff --git a/vault/init.go b/vault/init.go index 837531d23..659858e90 100644 --- a/vault/init.go +++ b/vault/init.go @@ -6,6 +6,7 @@ import ( "encoding/hex" "fmt" + "github.com/hashicorp/errwrap" "github.com/hashicorp/vault/helper/pgpkeys" "github.com/hashicorp/vault/shamir" ) @@ -55,7 +56,7 @@ func (c *Core) generateShares(sc *SealConfig) ([]byte, [][]byte, error) { // Generate a master key masterKey, err := c.barrier.GenerateKey() if err != nil { - return nil, nil, fmt.Errorf("key generation failed: %v", err) + return nil, nil, errwrap.Wrapf("key generation failed: {{err}}", err) } // Return the master key if only a single key part is used @@ -66,7 +67,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, fmt.Errorf("failed to generate barrier shares: %v", err) + return nil, nil, errwrap.Wrapf("failed to generate barrier shares: {{err}}", err) } unsealKeys = shares } @@ -105,14 +106,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, fmt.Errorf("invalid recovery configuration: %v", err) + return nil, errwrap.Wrapf("invalid recovery configuration: {{err}}", err) } } // Check if the seal configuration is valid if err := barrierConfig.Validate(); err != nil { c.logger.Error("invalid seal configuration", "error", err) - return nil, fmt.Errorf("invalid seal configuration: %v", err) + return nil, errwrap.Wrapf("invalid seal configuration: {{err}}", err) } // Avoid an initialization race @@ -131,7 +132,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, fmt.Errorf("error initializing seal: %v", err) + return nil, errwrap.Wrapf("error initializing seal: {{err}}", err) } barrierKey, barrierUnsealKeys, err := c.generateShares(barrierConfig) @@ -143,7 +144,7 @@ func (c *Core) Initialize(ctx context.Context, initParams *InitParams) (*InitRes // Initialize the barrier if err := c.barrier.Initialize(ctx, barrierKey); err != nil { c.logger.Error("failed to initialize barrier", "error", err) - return nil, fmt.Errorf("failed to initialize barrier: %v", err) + return nil, errwrap.Wrapf("failed to initialize barrier: {{err}}", err) } if c.logger.IsInfo() { c.logger.Info("security barrier initialized", "shares", barrierConfig.SecretShares, "threshold", barrierConfig.SecretThreshold) @@ -152,7 +153,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, fmt.Errorf("failed to unseal barrier: %v", err) + return nil, errwrap.Wrapf("failed to unseal barrier: {{err}}", err) } // Ensure the barrier is re-sealed @@ -168,7 +169,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, fmt.Errorf("barrier configuration saving failed: %v", err) + return nil, errwrap.Wrapf("barrier configuration saving failed: {{err}}", err) } // If we are storing shares, pop them out of the returned results and push @@ -181,7 +182,7 @@ func (c *Core) Initialize(ctx context.Context, initParams *InitParams) (*InitRes } if err := c.seal.SetStoredKeys(ctx, keysToStore); err != nil { c.logger.Error("failed to store keys", "error", err) - return nil, fmt.Errorf("failed to store keys: %v", err) + return nil, errwrap.Wrapf("failed to store keys: {{err}}", err) } } @@ -206,7 +207,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, fmt.Errorf("recovery configuration saving failed: %v", err) + return nil, errwrap.Wrapf("recovery configuration saving failed: {{err}}", err) } if recoveryConfig.SecretShares > 0 { @@ -261,7 +262,7 @@ func (c *Core) UnsealWithStoredKeys(ctx context.Context) error { sealed, err := c.Sealed() if err != nil { c.logger.Error("error checking sealed status in auto-unseal", "error", err) - return fmt.Errorf("error checking sealed status in auto-unseal: %s", err) + return errwrap.Wrapf("error checking sealed status in auto-unseal: {{err}}", err) } if !sealed { return nil @@ -271,7 +272,7 @@ func (c *Core) UnsealWithStoredKeys(ctx context.Context) error { keys, err := c.seal.GetStoredKeys(ctx) if err != nil { c.logger.Error("fetching stored unseal keys failed", "error", err) - return &NonFatalError{Err: fmt.Errorf("fetching stored unseal keys failed: %v", err)} + return &NonFatalError{Err: errwrap.Wrapf("fetching stored unseal keys failed: {{err}}", err)} } if len(keys) == 0 { c.logger.Warn("stored unseal key(s) supported but none found") @@ -282,7 +283,7 @@ func (c *Core) UnsealWithStoredKeys(ctx context.Context) error { unsealed, err = c.Unseal(key) if err != nil { c.logger.Error("unseal with stored unseal key failed", "error", err) - return &NonFatalError{Err: fmt.Errorf("unseal with stored key failed: %v", err)} + return &NonFatalError{Err: errwrap.Wrapf("unseal with stored key failed: {{err}}", err)} } keysUsed += 1 if unsealed { diff --git a/vault/keyring.go b/vault/keyring.go index 2cd487118..fd6564790 100644 --- a/vault/keyring.go +++ b/vault/keyring.go @@ -6,6 +6,7 @@ import ( "fmt" "time" + "github.com/hashicorp/errwrap" "github.com/hashicorp/vault/helper/jsonutil" ) @@ -46,7 +47,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, fmt.Errorf("deserialization failed: %v", err) + return nil, errwrap.Wrapf("deserialization failed: {{err}}", err) } return k, nil } @@ -78,7 +79,7 @@ func (k *Keyring) AddKey(key *Key) (*Keyring, error) { // Ensure there is no conflict if exist, ok := k.keys[key.Term]; ok { if !bytes.Equal(key.Value, exist.Value) { - return nil, fmt.Errorf("Conflicting key for term %d already installed", key.Term) + return nil, fmt.Errorf("conflicting key for term %d already installed", key.Term) } return k, nil } @@ -105,7 +106,7 @@ func (k *Keyring) AddKey(key *Key) (*Keyring, error) { func (k *Keyring) RemoveKey(term uint32) (*Keyring, error) { // Ensure this is not the active key if term == k.activeTerm { - return nil, fmt.Errorf("Cannot remove active key") + return nil, fmt.Errorf("cannot remove active key") } // Check if this term does not exist @@ -168,7 +169,7 @@ func DeserializeKeyring(buf []byte) (*Keyring, error) { // Deserialize the keyring var enc EncodedKeyring if err := jsonutil.DecodeJSON(buf, &enc); err != nil { - return nil, fmt.Errorf("deserialization failed: %v", err) + return nil, errwrap.Wrapf("deserialization failed: {{err}}", err) } // Create a new keyring diff --git a/vault/logical_cubbyhole.go b/vault/logical_cubbyhole.go index 493d63ede..08055ddb3 100644 --- a/vault/logical_cubbyhole.go +++ b/vault/logical_cubbyhole.go @@ -6,6 +6,7 @@ import ( "fmt" "strings" + "github.com/hashicorp/errwrap" "github.com/hashicorp/vault/helper/jsonutil" "github.com/hashicorp/vault/logical" "github.com/hashicorp/vault/logical/framework" @@ -38,7 +39,7 @@ func CubbyholeBackendFactory(ctx context.Context, conf *logical.BackendConfig) ( } if conf == nil { - return nil, fmt.Errorf("Configuration passed into backend is nil") + return nil, fmt.Errorf("configuration passed into backend is nil") } b.Backend.Setup(ctx, conf) @@ -58,7 +59,7 @@ type CubbyholeBackend struct { func (b *CubbyholeBackend) revoke(ctx context.Context, saltedToken string) error { if saltedToken == "" { - return fmt.Errorf("cubbyhole: client token empty during revocation") + return fmt.Errorf("client token empty during revocation") } if err := logical.ClearView(ctx, b.storageView.(*BarrierView).SubView(saltedToken+"/")); err != nil { @@ -71,7 +72,7 @@ func (b *CubbyholeBackend) revoke(ctx context.Context, saltedToken string) error 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, fmt.Errorf("existence check failed: %v", err) + return false, errwrap.Wrapf("existence check failed: {{err}}", err) } return out != nil, nil @@ -79,13 +80,13 @@ func (b *CubbyholeBackend) handleExistenceCheck(ctx context.Context, req *logica func (b *CubbyholeBackend) handleRead(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { if req.ClientToken == "" { - return nil, fmt.Errorf("cubbyhole read: client token empty") + return nil, fmt.Errorf("client token empty") } // Read the path out, err := req.Storage.Get(ctx, req.ClientToken+"/"+req.Path) if err != nil { - return nil, fmt.Errorf("read failed: %v", err) + return nil, errwrap.Wrapf("read failed: {{err}}", err) } // Fast-path the no data case @@ -96,7 +97,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, fmt.Errorf("json decoding failed: %v", err) + return nil, errwrap.Wrapf("json decoding failed: {{err}}", err) } // Generate the response @@ -109,7 +110,7 @@ func (b *CubbyholeBackend) handleRead(ctx context.Context, req *logical.Request, func (b *CubbyholeBackend) handleWrite(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { if req.ClientToken == "" { - return nil, fmt.Errorf("cubbyhole write: client token empty") + return nil, fmt.Errorf("client token empty") } // Check that some fields are given if len(req.Data) == 0 { @@ -119,7 +120,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, fmt.Errorf("json encoding failed: %v", err) + return nil, errwrap.Wrapf("json encoding failed: {{err}}", err) } // Write out a new key @@ -131,7 +132,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, fmt.Errorf("failed to write: %v", err) + return nil, errwrap.Wrapf("failed to write: {{err}}", err) } return nil, nil @@ -139,7 +140,7 @@ func (b *CubbyholeBackend) handleWrite(ctx context.Context, req *logical.Request func (b *CubbyholeBackend) handleDelete(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { if req.ClientToken == "" { - return nil, fmt.Errorf("cubbyhole delete: client token empty") + return nil, fmt.Errorf("client token empty") } // Delete the key at the request path if err := req.Storage.Delete(ctx, req.ClientToken+"/"+req.Path); err != nil { @@ -151,7 +152,7 @@ func (b *CubbyholeBackend) handleDelete(ctx context.Context, req *logical.Reques func (b *CubbyholeBackend) handleList(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { if req.ClientToken == "" { - return nil, fmt.Errorf("cubbyhole list: client token empty") + return nil, fmt.Errorf("client token empty") } // Right now we only handle directories, so ensure it ends with / We also diff --git a/vault/logical_passthrough.go b/vault/logical_passthrough.go index 8a3cff4bb..3a40da251 100644 --- a/vault/logical_passthrough.go +++ b/vault/logical_passthrough.go @@ -6,6 +6,7 @@ import ( "fmt" "strings" + "github.com/hashicorp/errwrap" "github.com/hashicorp/vault/helper/jsonutil" "github.com/hashicorp/vault/helper/parseutil" "github.com/hashicorp/vault/helper/wrapping" @@ -69,7 +70,7 @@ func LeaseSwitchedPassthroughBackend(ctx context.Context, conf *logical.BackendC } if conf == nil { - return nil, fmt.Errorf("Configuration passed into backend is nil") + return nil, fmt.Errorf("configuration passed into backend is nil") } b.Backend.Setup(ctx, conf) @@ -93,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, fmt.Errorf("existence check failed: %v", err) + return false, errwrap.Wrapf("existence check failed: {{err}}", err) } return out != nil, nil @@ -103,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, fmt.Errorf("read failed: %v", err) + return nil, errwrap.Wrapf("read failed: {{err}}", err) } // Fast-path the no data case @@ -115,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, fmt.Errorf("json decoding failed: %v", err) + return nil, errwrap.Wrapf("json decoding failed: {{err}}", err) } var resp *logical.Response @@ -174,7 +175,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, fmt.Errorf("json encoding failed: %v", err) + return nil, errwrap.Wrapf("json encoding failed: {{err}}", err) } // Write out a new key @@ -183,7 +184,7 @@ func (b *PassthroughBackend) handleWrite(ctx context.Context, req *logical.Reque Value: buf, } if err := req.Storage.Put(ctx, entry); err != nil { - return nil, fmt.Errorf("failed to write: %v", err) + return nil, errwrap.Wrapf("failed to write: {{err}}", err) } return nil, nil diff --git a/vault/logical_system.go b/vault/logical_system.go index 77c5948ea..77af84f1a 100644 --- a/vault/logical_system.go +++ b/vault/logical_system.go @@ -1442,7 +1442,7 @@ func (b *SystemBackend) handleRekeyRetrieve( recovery bool) (*logical.Response, error) { backup, err := b.Core.RekeyRetrieveBackup(ctx, recovery) if err != nil { - return nil, fmt.Errorf("unable to look up backed-up keys: %v", err) + return nil, errwrap.Wrapf("unable to look up backed-up keys: {{err}}", err) } if backup == nil { return logical.ErrorResponse("no backed-up keys found"), nil @@ -1457,7 +1457,7 @@ func (b *SystemBackend) handleRekeyRetrieve( } key, err := hex.DecodeString(j) if err != nil { - return nil, fmt.Errorf("error decoding hex-encoded backup key: %v", err) + return nil, errwrap.Wrapf("error decoding hex-encoded backup key: {{err}}", err) } currB64Keys = append(currB64Keys, base64.StdEncoding.EncodeToString(key)) keysB64[k] = currB64Keys @@ -1493,7 +1493,7 @@ func (b *SystemBackend) handleRekeyDelete( recovery bool) (*logical.Response, error) { err := b.Core.RekeyDeleteBackup(ctx, recovery) if err != nil { - return nil, fmt.Errorf("error during deletion of backed-up keys: %v", err) + return nil, errwrap.Wrapf("error during deletion of backed-up keys: {{err}}", err) } return nil, nil @@ -1814,13 +1814,13 @@ func (b *SystemBackend) handleTuneReadCommon(path string) (*logical.Response, er sysView := b.Core.router.MatchingSystemView(path) if sysView == nil { b.Backend.Logger().Error("cannot fetch sysview", "path", path) - return handleError(fmt.Errorf("sys: cannot fetch sysview for path %s", path)) + return handleError(fmt.Errorf("sys: cannot fetch sysview for path %q", path)) } mountEntry := b.Core.router.MatchingMountEntry(path) if mountEntry == nil { b.Backend.Logger().Error("cannot fetch mount entry", "path", path) - return handleError(fmt.Errorf("sys: cannot fetch mount entry for path %s", path)) + return handleError(fmt.Errorf("sys: cannot fetch mount entry for path %q", path)) } resp := &logical.Response{ @@ -1887,14 +1887,14 @@ func (b *SystemBackend) handleTuneWriteCommon(ctx context.Context, path string, for _, p := range untunableMounts { if strings.HasPrefix(path, p) { b.Backend.Logger().Error("cannot tune this mount", "path", path) - return handleError(fmt.Errorf("sys: cannot tune '%s'", path)) + return handleError(fmt.Errorf("cannot tune %q", path)) } } mountEntry := b.Core.router.MatchingMountEntry(path) if mountEntry == nil { b.Backend.Logger().Error("tune failed: no mount entry found", "path", path) - return handleError(fmt.Errorf("sys: tune of path '%s' failed: no mount entry found", path)) + return handleError(fmt.Errorf("tune of path %q failed: no mount entry found", path)) } if mountEntry != nil && !mountEntry.Local && repState.HasState(consts.ReplicationPerformanceSecondary) { return logical.ErrorResponse("cannot tune a non-local mount on a replication secondary"), nil @@ -1915,7 +1915,7 @@ func (b *SystemBackend) handleTuneWriteCommon(ctx context.Context, path string, mountEntry = b.Core.router.MatchingMountEntry(path) if mountEntry == nil { b.Backend.Logger().Error("tune failed: no mount entry found", "path", path) - return handleError(fmt.Errorf("sys: tune of path '%s' failed: no mount entry found", path)) + return handleError(fmt.Errorf("tune of path %q failed: no mount entry found", path)) } if mountEntry != nil && !mountEntry.Local && repState.HasState(consts.ReplicationPerformanceSecondary) { return logical.ErrorResponse("cannot tune a non-local mount on a replication secondary"), nil @@ -2963,7 +2963,7 @@ func (b *SystemBackend) handleRotate(ctx context.Context, req *logical.Request, Value: []byte(fmt.Sprintf("new-rotation-term-%d", newTerm)), }); err != nil { b.Core.logger.Error("core: error saving keyring canary", "error", err) - return nil, fmt.Errorf("failed to save keyring canary: %v", err) + return nil, errwrap.Wrapf("failed to save keyring canary: {{err}}", err) } return nil, nil @@ -3064,7 +3064,7 @@ func (b *SystemBackend) responseWrappingUnwrap(ctx context.Context, token string // 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 "", fmt.Errorf("error decrementing wrapping token's use-count: %v", err) + return "", errwrap.Wrapf("error decrementing wrapping token's use-count: {{err}}", err) } defer b.Core.tokenStore.Revoke(ctx, token) @@ -3077,7 +3077,7 @@ func (b *SystemBackend) responseWrappingUnwrap(ctx context.Context, token string } cubbyResp, err := b.Core.router.Route(ctx, cubbyReq) if err != nil { - return "", fmt.Errorf("error looking up wrapping information: %v", err) + return "", errwrap.Wrapf("error looking up wrapping information: {{err}}", err) } if cubbyResp == nil { return "no information found; wrapping token may be from a previous Vault version", ErrInternalError @@ -3119,7 +3119,7 @@ func (b *SystemBackend) handleWrappingLookup(ctx context.Context, req *logical.R } cubbyResp, err := b.Core.router.Route(ctx, cubbyReq) if err != nil { - return nil, fmt.Errorf("error looking up wrapping information: %v", err) + return nil, errwrap.Wrapf("error looking up wrapping information: {{err}}", err) } if cubbyResp == nil { return logical.ErrorResponse("no information found; wrapping token may be from a previous Vault version"), nil @@ -3141,7 +3141,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, fmt.Errorf("error reading creation_ttl value from wrapping information: %v", err) + return nil, errwrap.Wrapf("error reading creation_ttl value from wrapping information: {{err}}", err) } resp.Data["creation_ttl"] = time.Duration(creationTTL).Seconds() } @@ -3175,7 +3175,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, fmt.Errorf("error decrementing wrapping token's use-count: %v", err) + return nil, errwrap.Wrapf("error decrementing wrapping token's use-count: {{err}}", err) } defer b.Core.tokenStore.Revoke(ctx, token) } @@ -3188,7 +3188,7 @@ func (b *SystemBackend) handleWrappingRewrap(ctx context.Context, req *logical.R } cubbyResp, err := b.Core.router.Route(ctx, cubbyReq) if err != nil { - return nil, fmt.Errorf("error looking up wrapping information: %v", err) + return nil, errwrap.Wrapf("error looking up wrapping information: {{err}}", err) } if cubbyResp == nil { return logical.ErrorResponse("no information found; wrapping token may be from a previous Vault version"), nil @@ -3207,7 +3207,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, fmt.Errorf("error reading creation_ttl value from wrapping information: %v", err) + return nil, errwrap.Wrapf("error reading creation_ttl value from wrapping information: {{err}}", err) } // Get creation_path to return as the response later @@ -3225,7 +3225,7 @@ func (b *SystemBackend) handleWrappingRewrap(ctx context.Context, req *logical.R } cubbyResp, err = b.Core.router.Route(ctx, cubbyReq) if err != nil { - return nil, fmt.Errorf("error looking up response: %v", err) + return nil, errwrap.Wrapf("error looking up response: {{err}}", err) } if cubbyResp == nil { return logical.ErrorResponse("no information found; wrapping token may be from a previous Vault version"), nil diff --git a/vault/logical_system_helpers.go b/vault/logical_system_helpers.go index b0ba8602b..48cbb173c 100644 --- a/vault/logical_system_helpers.go +++ b/vault/logical_system_helpers.go @@ -23,8 +23,7 @@ func (b *SystemBackend) tuneMountTTLs(ctx context.Context, path string, me *Moun case newDefault != zero && newMax != zero: if newMax < newDefault { - return fmt.Errorf("backend max lease TTL of %d would be less than backend default lease TTL of %d", - int(newMax.Seconds()), int(newDefault.Seconds())) + return fmt.Errorf("backend max lease TTL of %d would be less than backend default lease TTL of %d", int(newMax.Seconds()), int(newDefault.Seconds())) } } diff --git a/vault/mount.go b/vault/mount.go index 80dd331fd..82ba99f61 100644 --- a/vault/mount.go +++ b/vault/mount.go @@ -329,7 +329,7 @@ func (c *Core) mountInternal(ctx context.Context, entry *MountEntry) error { // Check for the correct backend type backendType := backend.Type() if entry.Type == "plugin" && backendType != logical.TypeLogical { - return fmt.Errorf("cannot mount '%s' of type '%s' as a logical backend", entry.Config.PluginName, backendType) + return fmt.Errorf("cannot mount %q of type %q as a logical backend", entry.Config.PluginName, backendType) } c.setCoreBackend(entry, backend, view) @@ -363,7 +363,7 @@ func (c *Core) unmount(ctx context.Context, path string) error { // Prevent protected paths from being unmounted for _, p := range protectedMounts { if strings.HasPrefix(path, p) { - return fmt.Errorf("cannot unmount '%s'", path) + return fmt.Errorf("cannot unmount %q", path) } } return c.unmountInternal(ctx, path) @@ -493,7 +493,7 @@ func (c *Core) taintMountEntry(ctx context.Context, path string) error { func (c *Core) remountForce(ctx context.Context, path string) error { me := c.router.MatchingMountEntry(path) if me == nil { - return fmt.Errorf("cannot find mount for path '%s'", path) + return fmt.Errorf("cannot find mount for path %q", path) } me, err := me.Clone() @@ -520,18 +520,18 @@ func (c *Core) remount(ctx context.Context, src, dst string) error { // Prevent protected paths from being remounted for _, p := range protectedMounts { if strings.HasPrefix(src, p) { - return fmt.Errorf("cannot remount '%s'", src) + return fmt.Errorf("cannot remount %q", src) } } // Verify exact match of the route match := c.router.MatchingMount(src) if match == "" || src != match { - return fmt.Errorf("no matching mount at '%s'", src) + return fmt.Errorf("no matching mount at %q", src) } if match := c.router.MatchingMount(dst); match != "" { - return fmt.Errorf("existing mount at '%s'", match) + return fmt.Errorf("existing mount at %q", match) } // Mark the entry as tainted @@ -837,7 +837,7 @@ func (c *Core) setupMounts(ctx context.Context) error { // Check for the correct backend type backendType = backend.Type() if entry.Type == "plugin" && backendType != logical.TypeLogical { - return fmt.Errorf("cannot mount '%s' of type '%s' as a logical backend", entry.Config.PluginName, backendType) + return fmt.Errorf("cannot mount %q of type %q as a logical backend", entry.Config.PluginName, backendType) } c.setCoreBackend(entry, backend, view) @@ -892,7 +892,7 @@ func (c *Core) newLogicalBackend(ctx context.Context, entry *MountEntry, sysView } f, ok := c.logicalBackends[t] if !ok { - return nil, fmt.Errorf("unknown backend type: %s", t) + return nil, fmt.Errorf("unknown backend type: %q", t) } // Set up conf to pass in plugin_name diff --git a/vault/plugin_catalog.go b/vault/plugin_catalog.go index 28af94991..633b7c341 100644 --- a/vault/plugin_catalog.go +++ b/vault/plugin_catalog.go @@ -10,6 +10,7 @@ import ( "strings" "sync" + "github.com/hashicorp/errwrap" "github.com/hashicorp/vault/helper/builtinplugins" "github.com/hashicorp/vault/helper/consts" "github.com/hashicorp/vault/helper/jsonutil" @@ -58,12 +59,12 @@ func (c *PluginCatalog) Get(ctx context.Context, name string) (*pluginutil.Plugi // Look for external plugins in the barrier out, err := c.catalogView.Get(ctx, name) if err != nil { - return nil, fmt.Errorf("failed to retrieve plugin \"%s\": %v", name, err) + return nil, errwrap.Wrapf(fmt.Sprintf("failed to retrieve plugin %q: {{err}}", name), err) } if out != nil { entry := new(pluginutil.PluginRunner) if err := jsonutil.DecodeJSON(out.Value, entry); err != nil { - return nil, fmt.Errorf("failed to decode plugin entry: %v", err) + return nil, errwrap.Wrapf("failed to decode plugin entry: {{err}}", err) } // prepend the plugin directory to the command @@ -106,11 +107,11 @@ func (c *PluginCatalog) Set(ctx context.Context, name, command string, args []st commandFull := filepath.Join(c.directory, command) sym, err := filepath.EvalSymlinks(commandFull) if err != nil { - return fmt.Errorf("error while validating the command path: %v", err) + return errwrap.Wrapf("error while validating the command path: {{err}}", err) } symAbs, err := filepath.Abs(filepath.Dir(sym)) if err != nil { - return fmt.Errorf("error while validating the command path: %v", err) + return errwrap.Wrapf("error while validating the command path: {{err}}", err) } if symAbs != c.directory { @@ -127,7 +128,7 @@ func (c *PluginCatalog) Set(ctx context.Context, name, command string, args []st buf, err := json.Marshal(entry) if err != nil { - return fmt.Errorf("failed to encode plugin entry: %v", err) + return errwrap.Wrapf("failed to encode plugin entry: {{err}}", err) } logicalEntry := logical.StorageEntry{ @@ -135,7 +136,7 @@ func (c *PluginCatalog) Set(ctx context.Context, name, command string, args []st Value: buf, } if err := c.catalogView.Put(ctx, &logicalEntry); err != nil { - return fmt.Errorf("failed to persist plugin entry: %v", err) + return errwrap.Wrapf("failed to persist plugin entry: {{err}}", err) } return nil } diff --git a/vault/plugin_reload.go b/vault/plugin_reload.go index 6636420f2..2192ebdf1 100644 --- a/vault/plugin_reload.go +++ b/vault/plugin_reload.go @@ -5,6 +5,7 @@ import ( "fmt" "strings" + "github.com/hashicorp/errwrap" multierror "github.com/hashicorp/go-multierror" "github.com/hashicorp/vault/logical" ) @@ -19,9 +20,8 @@ func (c *Core) reloadMatchingPluginMounts(ctx context.Context, mounts []string) for _, mount := range mounts { entry := c.router.MatchingMountEntry(mount) if entry == nil { - errors = multierror.Append(errors, fmt.Errorf("cannot fetch mount entry on %s", mount)) + errors = multierror.Append(errors, fmt.Errorf("cannot fetch mount entry on %q", mount)) continue - // return fmt.Errorf("cannot fetch mount entry on %s", mount) } var isAuth bool @@ -33,7 +33,7 @@ func (c *Core) reloadMatchingPluginMounts(ctx context.Context, mounts []string) if entry.Type == "plugin" { err := c.reloadBackendCommon(ctx, entry, isAuth) if err != nil { - errors = multierror.Append(errors, fmt.Errorf("cannot reload plugin on %s: %v", mount, err)) + errors = multierror.Append(errors, errwrap.Wrapf(fmt.Sprintf("cannot reload plugin on %q: {{err}}", mount), err)) continue } c.logger.Info("successfully reloaded plugin", "plugin", entry.Config.PluginName, "path", entry.Path) diff --git a/vault/policy.go b/vault/policy.go index 74d759dc9..d92a4043e 100644 --- a/vault/policy.go +++ b/vault/policy.go @@ -154,13 +154,13 @@ func ParseACLPolicy(rules string) (*Policy, error) { // Parse the rules root, err := hcl.Parse(rules) if err != nil { - return nil, fmt.Errorf("Failed to parse policy: %s", err) + return nil, errwrap.Wrapf("failed to parse policy: {{err}}", err) } // Top-level item should be the object list list, ok := root.Node.(*ast.ObjectList) if !ok { - return nil, fmt.Errorf("Failed to parse policy: does not contain a root object") + return nil, fmt.Errorf("failed to parse policy: does not contain a root object") } // Check for invalid top-level keys @@ -169,7 +169,7 @@ func ParseACLPolicy(rules string) (*Policy, error) { "path", } if err := checkHCLKeys(list, valid); err != nil { - return nil, fmt.Errorf("Failed to parse policy: %s", err) + return nil, errwrap.Wrapf("failed to parse policy: {{err}}", err) } // Create the initial policy and store the raw text of the rules @@ -177,12 +177,12 @@ func ParseACLPolicy(rules string) (*Policy, error) { p.Raw = rules p.Type = PolicyTypeACL if err := hcl.DecodeObject(&p, list); err != nil { - return nil, fmt.Errorf("Failed to parse policy: %s", err) + return nil, errwrap.Wrapf("failed to parse policy: {{err}}", err) } if o := list.Filter("path"); len(o.Items) > 0 { if err := parsePaths(&p, o); err != nil { - return nil, fmt.Errorf("Failed to parse policy: %s", err) + return nil, errwrap.Wrapf("failed to parse policy: {{err}}", err) } } @@ -242,7 +242,7 @@ func parsePaths(result *Policy, list *ast.ObjectList) error { case OldSudoPathPolicy: pc.Capabilities = append(pc.Capabilities, []string{CreateCapability, ReadCapability, UpdateCapability, DeleteCapability, ListCapability, SudoCapability}...) default: - return fmt.Errorf("path %q: invalid policy '%s'", key, pc.Policy) + return fmt.Errorf("path %q: invalid policy %q", key, pc.Policy) } } @@ -258,7 +258,7 @@ func parsePaths(result *Policy, list *ast.ObjectList) error { case CreateCapability, ReadCapability, UpdateCapability, DeleteCapability, ListCapability, SudoCapability: pc.Permissions.CapabilitiesBitmap |= cap2Int[cap] default: - return fmt.Errorf("path %q: invalid capability '%s'", key, cap) + return fmt.Errorf("path %q: invalid capability %q", key, cap) } } @@ -326,8 +326,7 @@ func checkHCLKeys(node ast.Node, valid []string) error { for _, item := range list.Items { key := item.Keys[0].Token.Value().(string) if _, ok := validMap[key]; !ok { - result = multierror.Append(result, fmt.Errorf( - "invalid key '%s' on line %d", key, item.Assign.Line)) + result = multierror.Append(result, fmt.Errorf("invalid key %q on line %d", key, item.Assign.Line)) } } diff --git a/vault/policy_store.go b/vault/policy_store.go index 328a24a84..c44dc5789 100644 --- a/vault/policy_store.go +++ b/vault/policy_store.go @@ -251,7 +251,7 @@ func (ps *PolicyStore) SetPolicy(ctx context.Context, p *Policy) error { // Policies are normalized to lower-case p.Name = ps.sanitizeName(p.Name) if strutil.StrListContains(immutablePolicies, p.Name) { - return fmt.Errorf("cannot update %s policy", p.Name) + return fmt.Errorf("cannot update %q policy", p.Name) } return ps.setPolicyInternal(ctx, p) @@ -267,7 +267,7 @@ func (ps *PolicyStore) setPolicyInternal(ctx context.Context, p *Policy) error { Type: p.Type, }) if err != nil { - return fmt.Errorf("failed to create entry: %v", err) + return errwrap.Wrapf("failed to create entry: {{err}}", err) } switch p.Type { case PolicyTypeACL: @@ -313,7 +313,7 @@ func (ps *PolicyStore) GetPolicy(ctx context.Context, name string, policyType Po case PolicyTypeACL: view = ps.aclView default: - return nil, fmt.Errorf("invalid type of policy in type map: %s", policyType) + return nil, fmt.Errorf("invalid type of policy in type map: %q", policyType) } } @@ -400,7 +400,7 @@ func (ps *PolicyStore) ListPolicies(ctx context.Context, policyType PolicyType) case PolicyTypeACL: keys, err = logical.CollectKeys(ctx, ps.aclView) default: - return nil, fmt.Errorf("unknown policy type %s", policyType) + return nil, fmt.Errorf("unknown policy type %q", policyType) } // We only have non-assignable ACL policies at the moment @@ -436,7 +436,7 @@ func (ps *PolicyStore) DeletePolicy(ctx context.Context, name string, policyType switch policyType { case PolicyTypeACL: if strutil.StrListContains(immutablePolicies, name) { - return fmt.Errorf("cannot delete %s policy", name) + return fmt.Errorf("cannot delete %q policy", name) } if name == "default" { return fmt.Errorf("cannot delete default policy") @@ -499,7 +499,7 @@ func (ps *PolicyStore) loadACLPolicy(ctx context.Context, policyName, policyText } if policy == nil { - return fmt.Errorf("parsing %s policy resulted in nil policy", policyName) + return fmt.Errorf("parsing %q policy resulted in nil policy", policyName) } policy.Name = policyName diff --git a/vault/rekey.go b/vault/rekey.go index d70119b24..1786eb838 100644 --- a/vault/rekey.go +++ b/vault/rekey.go @@ -7,6 +7,7 @@ import ( "encoding/json" "fmt" + "github.com/hashicorp/errwrap" "github.com/hashicorp/go-uuid" "github.com/hashicorp/vault/helper/consts" "github.com/hashicorp/vault/helper/jsonutil" @@ -156,7 +157,7 @@ func (c *Core) BarrierRekeyInit(config *SealConfig) error { // Check if the seal configuration is valid if err := config.Validate(); err != nil { c.logger.Error("invalid rekey seal configuration", "error", err) - return fmt.Errorf("invalid rekey seal configuration: %v", err) + return errwrap.Wrapf("invalid rekey seal configuration: {{err}}", err) } c.stateLock.RLock() @@ -202,7 +203,7 @@ func (c *Core) RecoveryRekeyInit(config *SealConfig) error { // Check if the seal configuration is valid if err := config.Validate(); err != nil { c.logger.Error("invalid recovery configuration", "error", err) - return fmt.Errorf("invalid recovery configuration: %v", err) + return errwrap.Wrapf("invalid recovery configuration: {{err}}", err) } if !c.seal.RecoveryKeySupported() { @@ -305,7 +306,7 @@ func (c *Core) BarrierRekeyUpdate(ctx context.Context, key []byte, nonce string) } if nonce != c.barrierRekeyConfig.Nonce { - return nil, fmt.Errorf("incorrect nonce supplied; nonce for this rekey operation is %s", c.barrierRekeyConfig.Nonce) + return nil, fmt.Errorf("incorrect nonce supplied; nonce for this rekey operation is %q", c.barrierRekeyConfig.Nonce) } // Check if we already have this piece @@ -335,7 +336,7 @@ func (c *Core) BarrierRekeyUpdate(ctx context.Context, key []byte, nonce string) recoveredKey, err = shamir.Combine(c.barrierRekeyProgress) c.barrierRekeyProgress = nil if err != nil { - return nil, fmt.Errorf("failed to compute master key: %v", err) + return nil, errwrap.Wrapf("failed to compute master key: {{err}}", err) } } @@ -355,7 +356,7 @@ func (c *Core) BarrierRekeyUpdate(ctx context.Context, key []byte, nonce string) newMasterKey, err := c.barrier.GenerateKey() if err != nil { c.logger.Error("failed to generate master key", "error", err) - return nil, fmt.Errorf("master key generation failed: %v", err) + return nil, errwrap.Wrapf("master key generation failed: {{err}}", err) } results := &RekeyResult{ @@ -370,7 +371,7 @@ func (c *Core) BarrierRekeyUpdate(ctx context.Context, key []byte, nonce string) shares, err := shamir.Split(newMasterKey, c.barrierRekeyConfig.SecretShares, c.barrierRekeyConfig.SecretThreshold) if err != nil { c.logger.Error("failed to generate shares", "error", err) - return nil, fmt.Errorf("failed to generate shares: %v", err) + return nil, errwrap.Wrapf("failed to generate shares: {{err}}", err) } results.SecretShares = shares } @@ -415,7 +416,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, fmt.Errorf("failed to marshal unseal key backup: %v", err) + return nil, errwrap.Wrapf("failed to marshal unseal key backup: {{err}}", err) } pe := &physical.Entry{ Key: coreBarrierUnsealKeysBackupPath, @@ -423,7 +424,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, fmt.Errorf("failed to save unseal key backup: %v", err) + return nil, errwrap.Wrapf("failed to save unseal key backup: {{err}}", err) } } } @@ -431,21 +432,21 @@ func (c *Core) BarrierRekeyUpdate(ctx context.Context, key []byte, nonce string) if keysToStore != nil { if err := c.seal.SetStoredKeys(ctx, keysToStore); err != nil { c.logger.Error("failed to store keys", "error", err) - return nil, fmt.Errorf("failed to store keys: %v", err) + return nil, errwrap.Wrapf("failed to store keys: {{err}}", err) } } // Rekey the barrier if err := c.barrier.Rekey(ctx, newMasterKey); err != nil { c.logger.Error("failed to rekey barrier", "error", err) - return nil, fmt.Errorf("failed to rekey barrier: %v", err) + return nil, errwrap.Wrapf("failed to rekey barrier: {{err}}", err) } if c.logger.IsInfo() { c.logger.Info("security barrier rekeyed", "shares", c.barrierRekeyConfig.SecretShares, "threshold", c.barrierRekeyConfig.SecretThreshold) } if err := c.seal.SetBarrierConfig(ctx, c.barrierRekeyConfig); err != nil { c.logger.Error("error saving rekey seal configuration", "error", err) - return nil, fmt.Errorf("failed to save rekey seal configuration: %v", err) + return nil, errwrap.Wrapf("failed to save rekey seal configuration: {{err}}", err) } // Write to the canary path, which will force a synchronous truing during @@ -455,7 +456,7 @@ func (c *Core) BarrierRekeyUpdate(ctx context.Context, key []byte, nonce string) Value: []byte(c.barrierRekeyConfig.Nonce), }); err != nil { c.logger.Error("error saving keyring canary", "error", err) - return nil, fmt.Errorf("failed to save keyring canary: %v", err) + return nil, errwrap.Wrapf("failed to save keyring canary: {{err}}", err) } // Done! @@ -506,7 +507,7 @@ func (c *Core) RecoveryRekeyUpdate(ctx context.Context, key []byte, nonce string } if nonce != c.recoveryRekeyConfig.Nonce { - return nil, fmt.Errorf("incorrect nonce supplied; nonce for this rekey operation is %s", c.recoveryRekeyConfig.Nonce) + return nil, fmt.Errorf("incorrect nonce supplied; nonce for this rekey operation is %q", c.recoveryRekeyConfig.Nonce) } // Check if we already have this piece @@ -536,7 +537,7 @@ func (c *Core) RecoveryRekeyUpdate(ctx context.Context, key []byte, nonce string recoveryKey, err = shamir.Combine(c.recoveryRekeyProgress) c.recoveryRekeyProgress = nil if err != nil { - return nil, fmt.Errorf("failed to compute recovery key: %v", err) + return nil, errwrap.Wrapf("failed to compute recovery key: {{err}}", err) } } @@ -550,7 +551,7 @@ func (c *Core) RecoveryRekeyUpdate(ctx context.Context, key []byte, nonce string newMasterKey, err := c.barrier.GenerateKey() if err != nil { c.logger.Error("failed to generate recovery key", "error", err) - return nil, fmt.Errorf("recovery key generation failed: %v", err) + return nil, errwrap.Wrapf("recovery key generation failed: {{err}}", err) } // Return the master key if only a single key part is used @@ -565,7 +566,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, fmt.Errorf("failed to generate shares: %v", err) + return nil, errwrap.Wrapf("failed to generate shares: {{err}}", err) } results.SecretShares = shares } @@ -598,7 +599,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, fmt.Errorf("failed to marshal recovery key backup: %v", err) + return nil, errwrap.Wrapf("failed to marshal recovery key backup: {{err}}", err) } pe := &physical.Entry{ Key: coreRecoveryUnsealKeysBackupPath, @@ -606,19 +607,19 @@ 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, fmt.Errorf("failed to save unseal key backup: %v", err) + return nil, errwrap.Wrapf("failed to save unseal key backup: {{err}}", err) } } } if err := c.seal.SetRecoveryKey(ctx, newMasterKey); err != nil { c.logger.Error("failed to set recovery key", "error", err) - return nil, fmt.Errorf("failed to set recovery key: %v", err) + return nil, errwrap.Wrapf("failed to set recovery key: {{err}}", err) } if err := c.seal.SetRecoveryConfig(ctx, c.recoveryRekeyConfig); err != nil { c.logger.Error("error saving rekey seal configuration", "error", err) - return nil, fmt.Errorf("failed to save rekey seal configuration: %v", err) + return nil, errwrap.Wrapf("failed to save rekey seal configuration: {{err}}", err) } // Write to the canary path, which will force a synchronous truing during @@ -628,7 +629,7 @@ func (c *Core) RecoveryRekeyUpdate(ctx context.Context, key []byte, nonce string Value: []byte(c.recoveryRekeyConfig.Nonce), }); err != nil { c.logger.Error("error saving keyring canary", "error", err) - return nil, fmt.Errorf("failed to save keyring canary: %v", err) + return nil, errwrap.Wrapf("failed to save keyring canary: {{err}}", err) } // Done! diff --git a/vault/router.go b/vault/router.go index 9b58282f3..4cbcabf81 100644 --- a/vault/router.go +++ b/vault/router.go @@ -100,7 +100,7 @@ func (r *Router) Mount(backend logical.Backend, prefix string, mountEntry *Mount // Check if this is a nested mount if existing, _, ok := r.root.LongestPrefix(prefix); ok && existing != "" { - return fmt.Errorf("cannot mount under existing mount '%s'", existing) + return fmt.Errorf("cannot mount under existing mount %q", existing) } // Build the paths @@ -176,7 +176,7 @@ func (r *Router) Remount(src, dst string) error { // Check for existing mount raw, ok := r.root.Get(src) if !ok { - return fmt.Errorf("no mount at '%s'", src) + return fmt.Errorf("no mount at %q", src) } // Update the mount point diff --git a/vault/seal.go b/vault/seal.go index 98b997dd3..55e08741f 100644 --- a/vault/seal.go +++ b/vault/seal.go @@ -8,6 +8,7 @@ import ( "fmt" "sync/atomic" + "github.com/hashicorp/errwrap" "github.com/hashicorp/vault/helper/jsonutil" "github.com/hashicorp/vault/physical" @@ -128,11 +129,11 @@ func (d *defaultSeal) RecoveryKeySupported() bool { } func (d *defaultSeal) SetStoredKeys(ctx context.Context, keys [][]byte) error { - return fmt.Errorf("core: stored keys are not supported") + return fmt.Errorf("stored keys are not supported") } func (d *defaultSeal) GetStoredKeys(ctx context.Context) ([][]byte, error) { - return nil, fmt.Errorf("core: stored keys are not supported") + return nil, fmt.Errorf("stored keys are not supported") } func (d *defaultSeal) BarrierConfig(ctx context.Context) (*SealConfig, error) { @@ -148,7 +149,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, fmt.Errorf("failed to check seal configuration: %v", err) + return nil, errwrap.Wrapf("failed to check seal configuration: {{err}}", err) } // If the seal configuration is missing, we are not initialized @@ -162,7 +163,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, fmt.Errorf("failed to decode seal configuration: %v", err) + return nil, errwrap.Wrapf("failed to decode seal configuration: {{err}}", err) } switch conf.Type { @@ -172,13 +173,13 @@ func (d *defaultSeal) BarrierConfig(ctx context.Context) (*SealConfig, error) { case d.BarrierType(): default: d.core.logger.Error("barrier seal type does not match loaded type", "barrier_seal_type", conf.Type, "loaded_seal_type", d.BarrierType()) - return nil, fmt.Errorf("barrier seal type of %s does not match loaded type of %s", conf.Type, d.BarrierType()) + return nil, fmt.Errorf("barrier seal type of %q does not match loaded type of %q", conf.Type, d.BarrierType()) } // Check for a valid seal configuration if err := conf.Validate(); err != nil { d.core.logger.Error("invalid seal configuration", "error", err) - return nil, fmt.Errorf("seal validation failed: %v", err) + return nil, errwrap.Wrapf("seal validation failed: {{err}}", err) } d.config.Store(&conf) @@ -202,7 +203,7 @@ func (d *defaultSeal) SetBarrierConfig(ctx context.Context, config *SealConfig) // Encode the seal configuration buf, err := json.Marshal(config) if err != nil { - return fmt.Errorf("failed to encode seal configuration: %v", err) + return errwrap.Wrapf("failed to encode seal configuration: {{err}}", err) } // Store the seal configuration @@ -213,7 +214,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 fmt.Errorf("failed to write seal configuration: %v", err) + return errwrap.Wrapf("failed to write seal configuration: {{err}}", err) } d.config.Store(config.Clone()) @@ -303,11 +304,11 @@ func (s *SealConfig) Validate() error { for _, keystring := range s.PGPKeys { data, err := base64.StdEncoding.DecodeString(keystring) if err != nil { - return fmt.Errorf("Error decoding given PGP key: %s", err) + return errwrap.Wrapf("error decoding given PGP key: {{err}}", err) } _, err = openpgp.ReadEntity(packet.NewReader(bytes.NewBuffer(data))) if err != nil { - return fmt.Errorf("Error parsing given PGP key: %s", err) + return errwrap.Wrapf("error parsing given PGP key: {{err}}", err) } } } diff --git a/vault/sealunwrapper.go b/vault/sealunwrapper.go index 5a884ae92..a7e6fc222 100644 --- a/vault/sealunwrapper.go +++ b/vault/sealunwrapper.go @@ -87,7 +87,7 @@ func (d *sealUnwrapper) Get(ctx context.Context, key string) (*physical.Entry, e } // It's actually encrypted and we can't read it if se.Wrapped { - return nil, fmt.Errorf("cannot decode sealwrapped storage entry %s", entry.Key) + return nil, fmt.Errorf("cannot decode sealwrapped storage entry %q", entry.Key) } if atomic.LoadUint32(d.allowUnwraps) != 1 { return &physical.Entry{ @@ -125,7 +125,7 @@ func (d *sealUnwrapper) Get(ctx context.Context, key string) (*physical.Entry, e return entry, nil } if se.Wrapped { - return nil, fmt.Errorf("cannot decode sealwrapped storage entry %s", entry.Key) + return nil, fmt.Errorf("cannot decode sealwrapped storage entry %q", entry.Key) } entry = &physical.Entry{ diff --git a/vault/token_store.go b/vault/token_store.go index 24d92cefd..db1dbbf60 100644 --- a/vault/token_store.go +++ b/vault/token_store.go @@ -11,6 +11,7 @@ import ( "strings" "time" + "github.com/hashicorp/errwrap" log "github.com/hashicorp/go-hclog" "github.com/armon/go-metrics" @@ -743,12 +744,12 @@ func (ts *TokenStore) createAccessor(ctx context.Context, entry *TokenEntry) err } aEntryBytes, err := jsonutil.EncodeJSON(aEntry) if err != nil { - return fmt.Errorf("failed to marshal accessor index entry: %v", err) + return errwrap.Wrapf("failed to marshal accessor index entry: {{err}}", err) } le := &logical.StorageEntry{Key: path, Value: aEntryBytes} if err := ts.view.Put(ctx, le); err != nil { - return fmt.Errorf("failed to persist accessor index entry: %v", err) + return errwrap.Wrapf("failed to persist accessor index entry: {{err}}", err) } return nil } @@ -803,7 +804,7 @@ func (ts *TokenStore) storeCommon(ctx context.Context, entry *TokenEntry, writeS // Marshal the entry enc, err := json.Marshal(entry) if err != nil { - return fmt.Errorf("failed to encode entry: %v", err) + return errwrap.Wrapf("failed to encode entry: {{err}}", err) } if writeSecondary { @@ -815,7 +816,7 @@ func (ts *TokenStore) storeCommon(ctx context.Context, entry *TokenEntry, writeS // Ensure the parent exists parent, err := ts.Lookup(ctx, entry.Parent) if err != nil { - return fmt.Errorf("failed to lookup parent: %v", err) + return errwrap.Wrapf("failed to lookup parent: {{err}}", err) } if parent == nil { return fmt.Errorf("parent token not found") @@ -829,7 +830,7 @@ func (ts *TokenStore) storeCommon(ctx context.Context, entry *TokenEntry, writeS path := parentPrefix + parentSaltedID + "/" + saltedID le := &logical.StorageEntry{Key: path} if err := ts.view.Put(ctx, le); err != nil { - return fmt.Errorf("failed to persist entry: %v", err) + return errwrap.Wrapf("failed to persist entry: {{err}}", err) } } } @@ -841,7 +842,7 @@ func (ts *TokenStore) storeCommon(ctx context.Context, entry *TokenEntry, writeS le.SealWrap = true } if err := ts.view.Put(ctx, le); err != nil { - return fmt.Errorf("failed to persist entry: %v", err) + return errwrap.Wrapf("failed to persist entry: {{err}}", err) } return nil } @@ -882,7 +883,7 @@ func (ts *TokenStore) UseToken(ctx context.Context, te *TokenEntry) (*TokenEntry te, err = ts.lookupSalted(ctx, saltedID, false) if err != nil { - return nil, fmt.Errorf("failed to refresh entry: %v", err) + return nil, errwrap.Wrapf("failed to refresh entry: {{err}}", 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 @@ -966,7 +967,7 @@ func (ts *TokenStore) lookupSalted(ctx context.Context, saltedID string, tainted path := lookupPrefix + saltedID raw, err := ts.view.Get(ctx, path) if err != nil { - return nil, fmt.Errorf("failed to read entry: %v", err) + return nil, errwrap.Wrapf("failed to read entry: {{err}}", err) } // Bail if not found @@ -977,7 +978,7 @@ func (ts *TokenStore) lookupSalted(ctx context.Context, saltedID string, tainted // Unmarshal the token entry := new(TokenEntry) if err := jsonutil.DecodeJSON(raw.Value, entry); err != nil { - return nil, fmt.Errorf("failed to decode entry: %v", err) + return nil, errwrap.Wrapf("failed to decode entry: {{err}}", err) } // This is a token that is awaiting deferred revocation or tainted @@ -992,7 +993,7 @@ func (ts *TokenStore) lookupSalted(ctx context.Context, saltedID string, tainted } check, err := ts.expiration.RestoreSaltedTokenCheck(entry.Path, saltedID) if err != nil { - return nil, fmt.Errorf("failed to check token in restore mode: %v", err) + return nil, errwrap.Wrapf("failed to check token in restore mode: {{err}}", err) } if !check { return nil, nil @@ -1036,7 +1037,7 @@ func (ts *TokenStore) lookupSalted(ctx context.Context, saltedID string, tainted // If fields are getting upgraded, store the changes if persistNeeded { if err := ts.storeCommon(ctx, entry, false); err != nil { - return nil, fmt.Errorf("failed to persist token upgrade: %v", err) + return nil, errwrap.Wrapf("failed to persist token upgrade: {{err}}", err) } } @@ -1152,7 +1153,7 @@ func (ts *TokenStore) revokeSalted(ctx context.Context, saltedID string) (ret er path := parentPrefix + parentSaltedID + "/" + saltedID if err = ts.view.Delete(ctx, path); err != nil { - return fmt.Errorf("failed to delete entry: %v", err) + return errwrap.Wrapf("failed to delete entry: {{err}}", err) } } @@ -1165,7 +1166,7 @@ func (ts *TokenStore) revokeSalted(ctx context.Context, saltedID string) (ret er path := accessorPrefix + accessorSaltedID if err = ts.view.Delete(ctx, path); err != nil { - return fmt.Errorf("failed to delete entry: %v", err) + return errwrap.Wrapf("failed to delete entry: {{err}}", err) } } @@ -1180,12 +1181,12 @@ func (ts *TokenStore) revokeSalted(ctx context.Context, saltedID string) (ret er parentPath := parentPrefix + saltedID + "/" children, err := ts.view.List(ctx, parentPath) if err != nil { - return fmt.Errorf("failed to scan for children: %v", err) + return errwrap.Wrapf("failed to scan for children: {{err}}", err) } for _, child := range children { entry, err := ts.lookupSalted(ctx, child, true) if err != nil { - return fmt.Errorf("failed to get child token: %v", err) + return errwrap.Wrapf("failed to get child token: {{err}}", err) } lock := locksutil.LockForKey(ts.tokenLocks, entry.ID) lock.Lock() @@ -1194,18 +1195,18 @@ func (ts *TokenStore) revokeSalted(ctx context.Context, saltedID string) (ret er err = ts.store(ctx, entry) if err != nil { lock.Unlock() - return fmt.Errorf("failed to update child token: %v", err) + return errwrap.Wrapf("failed to update child token: {{err}}", err) } lock.Unlock() } if err = logical.ClearView(ctx, ts.view.SubView(parentPath)); err != nil { - return fmt.Errorf("failed to delete entry: %v", err) + return errwrap.Wrapf("failed to delete entry: {{err}}", err) } // Now that the entry is not usable for any revocation tasks, nuke it path := lookupPrefix + saltedID if err = ts.view.Delete(ctx, path); err != nil { - return fmt.Errorf("failed to delete entry: %v", err) + return errwrap.Wrapf("failed to delete entry: {{err}}", err) } return nil @@ -1243,13 +1244,13 @@ func (ts *TokenStore) revokeTreeSalted(ctx context.Context, saltedID string) err path := parentPrefix + id + "/" children, err := ts.view.List(ctx, path) if err != nil { - return fmt.Errorf("failed to scan for children: %v", err) + return errwrap.Wrapf("failed to scan for children: {{err}}", err) } // If the length of the children array is zero, // then we are at a leaf node. if len(children) == 0 { if err := ts.revokeSalted(ctx, id); err != nil { - return fmt.Errorf("failed to revoke entry: %v", err) + return errwrap.Wrapf("failed to revoke entry: {{err}}", err) } // If the length of l is equal to 1, then the last token has been deleted if l == 1 { @@ -1293,7 +1294,7 @@ func (ts *TokenStore) lookupBySaltedAccessor(ctx context.Context, saltedAccessor var aEntry accessorEntry if err != nil { - return aEntry, fmt.Errorf("failed to read index using accessor: %s", err) + return aEntry, errwrap.Wrapf("failed to read index using accessor: {{err}}", err) } if entry == nil { return aEntry, &logical.StatusBadRequest{Err: "invalid accessor"} @@ -1309,7 +1310,7 @@ func (ts *TokenStore) lookupBySaltedAccessor(ctx context.Context, saltedAccessor te, err := ts.lookupSalted(ctx, saltedID, tainted) if err != nil { - return accessorEntry{}, fmt.Errorf("failed to look up token using accessor index: %s", err) + return accessorEntry{}, errwrap.Wrapf("failed to look up token using accessor index: {{err}}", err) } // It's hard to reason about what to do here -- it may be that the // token was revoked async, or that it's an old accessor index entry @@ -1343,13 +1344,13 @@ func (ts *TokenStore) handleTidy(ctx context.Context, req *logical.Request, data // List out all the accessors saltedAccessorList, err := ts.view.List(ctx, accessorPrefix) if err != nil { - return nil, fmt.Errorf("failed to fetch accessor index entries: %v", err) + return nil, errwrap.Wrapf("failed to fetch accessor index entries: {{err}}", err) } // First, clean up secondary index entries that are no longer valid parentList, err := ts.view.List(ctx, parentPrefix) if err != nil { - return nil, fmt.Errorf("failed to fetch secondary index entries: %v", err) + return nil, errwrap.Wrapf("failed to fetch secondary index entries: {{err}}", err) } var countParentEntries, deletedCountParentEntries, countParentList, deletedCountParentList int64 @@ -1362,7 +1363,7 @@ func (ts *TokenStore) handleTidy(ctx context.Context, req *logical.Request, data // Get the children children, err := ts.view.List(ctx, parentPrefix+parent) if err != nil { - tidyErrors = multierror.Append(tidyErrors, fmt.Errorf("failed to read secondary index: %v", err)) + tidyErrors = multierror.Append(tidyErrors, errwrap.Wrapf("failed to read secondary index: {{err}}", err)) continue } @@ -1396,7 +1397,7 @@ func (ts *TokenStore) handleTidy(ctx context.Context, req *logical.Request, data te.Parent = "" err = ts.store(ctx, te) if err != nil { - tidyErrors = multierror.Append(tidyErrors, fmt.Errorf("failed to convert child token into an orphan token: %v", err)) + tidyErrors = multierror.Append(tidyErrors, errwrap.Wrapf("failed to convert child token into an orphan token: {{err}}", err)) } lock.Unlock() continue @@ -1408,7 +1409,7 @@ func (ts *TokenStore) handleTidy(ctx context.Context, req *logical.Request, data ts.logger.Debug("deleting invalid secondary index", "index", index) err = ts.view.Delete(ctx, index) if err != nil { - tidyErrors = multierror.Append(tidyErrors, fmt.Errorf("failed to delete secondary index: %v", err)) + tidyErrors = multierror.Append(tidyErrors, errwrap.Wrapf("failed to delete secondary index: {{err}}", err)) continue } deletedChildrenCount++ @@ -1440,7 +1441,7 @@ func (ts *TokenStore) handleTidy(ctx context.Context, req *logical.Request, data accessorEntry, err := ts.lookupBySaltedAccessor(ctx, saltedAccessor, true) if err != nil { - tidyErrors = multierror.Append(tidyErrors, fmt.Errorf("failed to read the accessor index: %v", err)) + tidyErrors = multierror.Append(tidyErrors, errwrap.Wrapf("failed to read the accessor index: {{err}}", err)) continue } @@ -1453,7 +1454,7 @@ func (ts *TokenStore) handleTidy(ctx context.Context, req *logical.Request, data // item since this is just a best-effort operation err = ts.view.Delete(ctx, index) if err != nil { - tidyErrors = multierror.Append(tidyErrors, fmt.Errorf("failed to delete the accessor index: %v", err)) + tidyErrors = multierror.Append(tidyErrors, errwrap.Wrapf("failed to delete the accessor index: {{err}}", err)) continue } deletedCountAccessorEmptyToken++ @@ -1466,13 +1467,13 @@ func (ts *TokenStore) handleTidy(ctx context.Context, req *logical.Request, data // exist saltedID, err := ts.SaltID(ctx, accessorEntry.TokenID) if err != nil { - tidyErrors = multierror.Append(tidyErrors, fmt.Errorf("failed to read salt id: %v", err)) + tidyErrors = multierror.Append(tidyErrors, errwrap.Wrapf("failed to read salt id: {{err}}", err)) lock.RUnlock() continue } te, err := ts.lookupSalted(ctx, saltedID, true) if err != nil { - tidyErrors = multierror.Append(tidyErrors, fmt.Errorf("failed to lookup tainted ID: %v", err)) + tidyErrors = multierror.Append(tidyErrors, errwrap.Wrapf("failed to lookup tainted ID: {{err}}", err)) lock.RUnlock() continue } @@ -1496,7 +1497,7 @@ func (ts *TokenStore) handleTidy(ctx context.Context, req *logical.Request, data // the leases associated with the token. err := ts.expiration.RevokeByToken(tokenEntry) if err != nil { - tidyErrors = multierror.Append(tidyErrors, fmt.Errorf("failed to revoke leases of expired token: %v", err)) + tidyErrors = multierror.Append(tidyErrors, errwrap.Wrapf("failed to revoke leases of expired token: {{err}}", err)) continue } deletedCountInvalidTokenInAccessor++ @@ -1509,7 +1510,7 @@ func (ts *TokenStore) handleTidy(ctx context.Context, req *logical.Request, data // entry to try again. err = ts.view.Delete(ctx, index) if err != nil { - tidyErrors = multierror.Append(tidyErrors, fmt.Errorf("failed to delete accessor entry: %v", err)) + tidyErrors = multierror.Append(tidyErrors, errwrap.Wrapf("failed to delete accessor entry: {{err}}", err)) continue } deletedCountAccessorInvalidToken++ @@ -2268,7 +2269,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, fmt.Errorf("error looking up token: %s", err) + return nil, errwrap.Wrapf("error looking up token: {{err}}", err) } if te == nil { return nil, fmt.Errorf("no token entry found during lookup") @@ -2282,10 +2283,10 @@ func (ts *TokenStore) authRenew(ctx context.Context, req *logical.Request, d *fr role, err := ts.tokenStoreRole(ctx, te.Role) if err != nil { - return nil, fmt.Errorf("error looking up role %s: %s", te.Role, err) + return nil, errwrap.Wrapf(fmt.Sprintf("error looking up role %q: {{err}}", te.Role), err) } if role == nil { - return nil, fmt.Errorf("original token role (%s) could not be found, not renewing", te.Role) + return nil, fmt.Errorf("original token role %q could not be found, not renewing", te.Role) } req.Auth.Period = role.Period