Update primary error functions to take a context, deprecate old functions (#1358)

* add new error funcs which take a ctx and deprecate existing funcs

* use context where available when writing error events

* remove circular internal/errors pkg dep

* suppress some chatty errors using errors.WithoutEvent()

* convert auth oidc funcs to take context where needed to write events

Co-authored-by: Jim <jlambert@hashicorp.com>
This commit is contained in:
s-christoffandJim authored and GitHub committed 2021-07-29 20:52:56 -04:00
1 parent 02ff2db66e
commit 6b78108ecf
227 files changed
+3945 -3736

No files matched your search

@@ -82,16 +82,16 @@ type Service struct {
func NewService(kms *kms.Kms, pwRepoFn common.PasswordAuthRepoFactory, oidcRepoFn common.OidcAuthRepoFactory, iamRepoFn common.IamRepoFactory, atRepoFn common.AuthTokenRepoFactory, opt ...handlers.Option) (Service, error) {
const op = "authmethods.NewService"
if kms == nil {
return Service{}, errors.New(errors.InvalidParameter, op, "missing kms")
return Service{}, errors.NewDeprecated(errors.InvalidParameter, op, "missing kms")
}
if pwRepoFn == nil {
return Service{}, errors.New(errors.InvalidParameter, op, "missing password repository")
return Service{}, errors.NewDeprecated(errors.InvalidParameter, op, "missing password repository")
}
if oidcRepoFn == nil {
return Service{}, fmt.Errorf("nil oidc repository provided")
}
if iamRepoFn == nil {
return Service{}, errors.New(errors.InvalidParameter, op, "missing iam repository")
return Service{}, errors.NewDeprecated(errors.InvalidParameter, op, "missing iam repository")
}
if atRepoFn == nil {
return Service{}, fmt.Errorf("nil auth token repository provided")
@@ -205,7 +205,7 @@ func (s Service) GetAuthMethod(ctx context.Context, req *pbs.GetAuthMethodReques
outputFields, ok := requests.OutputFields(ctx)
if !ok {
return nil, errors.New(errors.Internal, op, "no request context found")
return nil, errors.New(ctx, errors.Internal, op, "no request context found")
}
outputOpts := make([]handlers.Option, 0, 3)
@@ -236,7 +236,7 @@ func (s Service) GetAuthMethod(ctx context.Context, req *pbs.GetAuthMethodReques
func (s Service) CreateAuthMethod(ctx context.Context, req *pbs.CreateAuthMethodRequest) (*pbs.CreateAuthMethodResponse, error) {
const op = "authmethods.(Service).CreateAuthMethod"
if err := validateCreateRequest(req); err != nil {
if err := validateCreateRequest(ctx, req); err != nil {
return nil, err
}
authResults := s.authResult(ctx, req.GetItem().GetScopeId(), action.Create)
@@ -250,7 +250,7 @@ func (s Service) CreateAuthMethod(ctx context.Context, req *pbs.CreateAuthMethod
outputFields, ok := requests.OutputFields(ctx)
if !ok {
return nil, errors.New(errors.Internal, op, "no request context found")
return nil, errors.New(ctx, errors.Internal, op, "no request context found")
}
outputOpts := make([]handlers.Option, 0, 3)
@@ -281,7 +281,7 @@ func (s Service) CreateAuthMethod(ctx context.Context, req *pbs.CreateAuthMethod
func (s Service) UpdateAuthMethod(ctx context.Context, req *pbs.UpdateAuthMethodRequest) (*pbs.UpdateAuthMethodResponse, error) {
const op = "authmethods.(Service).UpdateAuthMethod"
if err := validateUpdateRequest(req); err != nil {
if err := validateUpdateRequest(ctx, req); err != nil {
return nil, err
}
authResults := s.authResult(ctx, req.GetId(), action.Update)
@@ -300,7 +300,7 @@ func (s Service) UpdateAuthMethod(ctx context.Context, req *pbs.UpdateAuthMethod
outputFields, ok := requests.OutputFields(ctx)
if !ok {
return nil, errors.New(errors.Internal, op, "no request context found")
return nil, errors.New(ctx, errors.Internal, op, "no request context found")
}
outputOpts := make([]handlers.Option, 0, 3)
@@ -354,7 +354,7 @@ func (s Service) ChangeState(ctx context.Context, req *pbs.ChangeStateRequest) (
outputFields, ok := requests.OutputFields(ctx)
if !ok {
return nil, errors.New(errors.Internal, op, "no request context found")
return nil, errors.New(ctx, errors.Internal, op, "no request context found")
}
outputOpts := make([]handlers.Option, 0, 3)
@@ -427,7 +427,7 @@ func (s Service) Authenticate(ctx context.Context, req *pbs.AuthenticateRequest)
case oidc.Subtype:
return s.authenticateOidc(ctx, req, &authResults)
}
return nil, errors.New(errors.Internal, op, "Invalid auth method subtype not caught in validation function.")
return nil, errors.New(ctx, errors.Internal, op, "Invalid auth method subtype not caught in validation function.")
}
// Deprecated: use Authenticate
@@ -491,18 +491,18 @@ func (s Service) listFromRepo(ctx context.Context, scopeIds []string, authResult
const op = "authmethods.(Service).listFromRepo"
reqCtx, ok := requests.RequestContextFromCtx(ctx)
if !ok {
return nil, errors.New(errors.Internal, op, "no request context found")
return nil, errors.New(ctx, errors.Internal, op, "no request context found")
}
var outUl []auth.AuthMethod
oidcRepo, err := s.oidcRepoFn()
if err != nil {
return nil, errors.Wrap(err, op)
return nil, errors.Wrap(ctx, err, op)
}
ol, err := oidcRepo.ListAuthMethods(ctx, scopeIds, oidc.WithUnauthenticatedUser(reqCtx.UserId == requestauth.AnonymousUserId))
if err != nil {
return nil, errors.Wrap(err, op)
return nil, errors.Wrap(ctx, err, op)
}
for _, item := range ol {
outUl = append(outUl, item)
@@ -510,11 +510,11 @@ func (s Service) listFromRepo(ctx context.Context, scopeIds []string, authResult
repo, err := s.pwRepoFn()
if err != nil {
return nil, errors.Wrap(err, op)
return nil, errors.Wrap(ctx, err, op)
}
pl, err := repo.ListAuthMethods(ctx, scopeIds)
if err != nil {
return nil, errors.Wrap(err, op)
return nil, errors.Wrap(ctx, err, op)
}
for _, item := range pl {
outUl = append(outUl, item)
@@ -529,7 +529,7 @@ func (s Service) createInRepo(ctx context.Context, scopeId string, item *pb.Auth
case password.Subtype:
am, err := s.createPwInRepo(ctx, scopeId, item)
if err != nil {
return nil, errors.Wrap(err, op)
return nil, errors.Wrap(ctx, err, op)
}
if am == nil {
return nil, handlers.ApiErrorWithCodeAndMessage(codes.Internal, "Unable to create auth method but no error returned from repository.")
@@ -538,7 +538,7 @@ func (s Service) createInRepo(ctx context.Context, scopeId string, item *pb.Auth
case oidc.Subtype:
am, err := s.createOidcInRepo(ctx, scopeId, item)
if err != nil {
return nil, errors.Wrap(err, op)
return nil, errors.Wrap(ctx, err, op)
}
if am == nil {
return nil, handlers.ApiErrorWithCodeAndMessage(codes.Internal, "Unable to create auth method but no error returned from repository.")
@@ -558,7 +558,7 @@ func (s Service) updateInRepo(ctx context.Context, scopeId string, req *pbs.Upda
case password.Subtype:
pam, err := s.updatePwInRepo(ctx, scopeId, req.GetId(), req.GetUpdateMask().GetPaths(), req.GetItem())
if err != nil {
return nil, false, errors.Wrap(err, op)
return nil, false, errors.Wrap(ctx, err, op)
}
if pam == nil {
return nil, false, handlers.ApiErrorWithCodeAndMessage(codes.Internal, "Unable to update auth method but no error returned from repository.")
@@ -568,7 +568,7 @@ func (s Service) updateInRepo(ctx context.Context, scopeId string, req *pbs.Upda
case oidc.Subtype:
oam, dr, err := s.updateOidcInRepo(ctx, scopeId, req)
if err != nil {
return nil, false, errors.Wrap(err, op)
return nil, false, errors.Wrap(ctx, err, op)
}
if oam == nil {
return nil, false, handlers.ApiErrorWithCodeAndMessage(codes.Internal, "Unable to update auth method but no error returned from repository.")
@@ -588,14 +588,14 @@ func (s Service) deleteFromRepo(ctx context.Context, scopeId, id string) (bool,
case password.Subtype:
repo, err := s.pwRepoFn()
if err != nil {
return false, errors.Wrap(err, op)
return false, errors.Wrap(ctx, err, op)
}
rows, dErr = repo.DeleteAuthMethod(ctx, scopeId, id)
case oidc.Subtype:
repo, err := s.oidcRepoFn()
if err != nil {
return false, errors.Wrap(err, op)
return false, errors.Wrap(ctx, err, op)
}
rows, dErr = repo.DeleteAuthMethod(ctx, id)
}
@@ -604,7 +604,7 @@ func (s Service) deleteFromRepo(ctx context.Context, scopeId, id string) (bool,
if errors.IsNotFoundError(dErr) {
return false, nil
}
return false, errors.Wrap(dErr, op, errors.WithMsg("unable to delete auth method"))
return false, errors.Wrap(ctx, dErr, op, errors.WithMsg("unable to delete auth method"))
}
return rows > 0, nil
@@ -622,7 +622,7 @@ func (s Service) changeStateInRepo(ctx context.Context, req *pbs.ChangeStateRequ
attrs := &pbs.OidcChangeStateAttributes{}
if err := handlers.StructToProto(req.GetAttributes(), attrs); err != nil {
return nil, errors.Wrap(err, op, errors.WithMsg("unable to parse attributes"))
return nil, errors.Wrap(ctx, err, op, errors.WithMsg("unable to parse attributes"))
}
var opts []oidc.Option
@@ -639,7 +639,7 @@ func (s Service) changeStateInRepo(ctx context.Context, req *pbs.ChangeStateRequ
case publicState:
am, err = repo.MakePublic(ctx, req.GetId(), req.GetVersion(), opts...)
default:
err = errors.New(errors.InvalidParameter, op, fmt.Sprintf("unrecognized state %q", attrs.GetState()))
err = errors.New(ctx, errors.InvalidParameter, op, fmt.Sprintf("unrecognized state %q", attrs.GetState()))
}
if err != nil {
return nil, err
@@ -648,7 +648,7 @@ func (s Service) changeStateInRepo(ctx context.Context, req *pbs.ChangeStateRequ
return am, nil
}
return nil, errors.New(errors.InvalidParameter, op, "Given auth method type does not support changing state")
return nil, errors.New(ctx, errors.InvalidParameter, op, "Given auth method type does not support changing state")
}
func (s Service) authResult(ctx context.Context, id string, a action.Type) requestauth.VerifyResults {
@@ -710,7 +710,7 @@ func (s Service) authResult(ctx context.Context, id string, a action.Type) reque
}
authMeth = am
default:
res.Error = errors.New(errors.InvalidPublicId, op, "unrecognized auth method type")
res.Error = errors.New(ctx, errors.InvalidPublicId, op, "unrecognized auth method type")
return res
}
parentId = authMeth.GetScopeId()
@@ -843,15 +843,15 @@ func toAuthTokenProto(t *authtoken.AuthToken) *pba.AuthToken {
func validateGetRequest(req *pbs.GetAuthMethodRequest) error {
const op = "authmethod.validateGetRequest"
if req == nil {
return errors.New(errors.InvalidParameter, op, "Missing request")
return errors.NewDeprecated(errors.InvalidParameter, op, "Missing request")
}
return handlers.ValidateGetRequest(handlers.NoopValidatorFn, req, password.AuthMethodPrefix, oidc.AuthMethodPrefix)
}
func validateCreateRequest(req *pbs.CreateAuthMethodRequest) error {
func validateCreateRequest(ctx context.Context, req *pbs.CreateAuthMethodRequest) error {
const op = "authmethod.validateCreateRequest"
if req == nil {
return errors.New(errors.InvalidParameter, op, "Missing request")
return errors.NewDeprecated(errors.InvalidParameter, op, "Missing request")
}
return handlers.ValidateCreateRequest(req.GetItem(), func() map[string]string {
badFields := map[string]string{}
@@ -917,7 +917,7 @@ func validateCreateRequest(req *pbs.CreateAuthMethodRequest) error {
}
}
if len(attrs.GetIdpCaCerts()) > 0 {
if _, err := oidc.ParseCertificates(attrs.GetIdpCaCerts()...); err != nil {
if _, err := oidc.ParseCertificates(ctx, attrs.GetIdpCaCerts()...); err != nil {
badFields[idpCaCertsField] = fmt.Sprintf("Cannot parse CA certificates. %v", err.Error())
}
}
@@ -930,7 +930,7 @@ func validateCreateRequest(req *pbs.CreateAuthMethodRequest) error {
}
}
if len(attrs.GetAccountClaimMaps()) > 0 {
acm, err := oidc.ParseAccountClaimMaps(attrs.GetAccountClaimMaps()...)
acm, err := oidc.ParseAccountClaimMaps(ctx, attrs.GetAccountClaimMaps()...)
if err != nil {
badFields[accountClaimMapsField] = fmt.Sprintf("Contains invalid map %q", err.Error())
}
@@ -950,10 +950,10 @@ func validateCreateRequest(req *pbs.CreateAuthMethodRequest) error {
})
}
func validateUpdateRequest(req *pbs.UpdateAuthMethodRequest) error {
func validateUpdateRequest(ctx context.Context, req *pbs.UpdateAuthMethodRequest) error {
const op = "authmethod.validateUpdateRequest"
if req == nil {
return errors.New(errors.InvalidParameter, op, "missing request")
return errors.NewDeprecated(errors.InvalidParameter, op, "missing request")
}
return handlers.ValidateUpdateRequest(req, req.GetItem(), func() map[string]string {
badFields := map[string]string{}
@@ -1038,7 +1038,7 @@ func validateUpdateRequest(req *pbs.UpdateAuthMethodRequest) error {
}
}
if len(attrs.GetIdpCaCerts()) > 0 {
if _, err := oidc.ParseCertificates(attrs.GetIdpCaCerts()...); err != nil {
if _, err := oidc.ParseCertificates(ctx, attrs.GetIdpCaCerts()...); err != nil {
badFields[idpCaCertsField] = fmt.Sprintf("Cannot parse CA certificates. %v", err.Error())
}
}
@@ -1051,7 +1051,7 @@ func validateUpdateRequest(req *pbs.UpdateAuthMethodRequest) error {
}
}
if len(attrs.GetAccountClaimMaps()) > 0 {
acm, err := oidc.ParseAccountClaimMaps(attrs.GetAccountClaimMaps()...)
acm, err := oidc.ParseAccountClaimMaps(ctx, attrs.GetAccountClaimMaps()...)
if err != nil {
badFields[accountClaimMapsField] = fmt.Sprintf("Contains invalid map %q", err.Error())
} else {
@@ -1062,7 +1062,7 @@ func validateUpdateRequest(req *pbs.UpdateAuthMethodRequest) error {
}
foundTo[m.To] = true
to, err := oidc.ConvertToAccountToClaim(m.To)
to, err := oidc.ConvertToAccountToClaim(ctx, m.To)
if err != nil {
badFields[accountClaimMapsField] = fmt.Sprintf("%s=%s contains invalid map %q", m.From, m.To, err.Error())
break
@@ -1084,7 +1084,7 @@ func validateUpdateRequest(req *pbs.UpdateAuthMethodRequest) error {
func validateDeleteRequest(req *pbs.DeleteAuthMethodRequest) error {
const op = "authmethod.validateDeleteRequest"
if req == nil {
return errors.New(errors.InvalidParameter, op, "Missing request")
return errors.NewDeprecated(errors.InvalidParameter, op, "Missing request")
}
return handlers.ValidateDeleteRequest(handlers.NoopValidatorFn, req, password.AuthMethodPrefix, oidc.AuthMethodPrefix)
}
@@ -1092,7 +1092,7 @@ func validateDeleteRequest(req *pbs.DeleteAuthMethodRequest) error {
func validateListRequest(req *pbs.ListAuthMethodsRequest) error {
const op = "authmethod.validateListRequest"
if req == nil {
return errors.New(errors.InvalidParameter, op, "Missing request")
return errors.NewDeprecated(errors.InvalidParameter, op, "Missing request")
}
badFields := map[string]string{}
if !handlers.ValidId(handlers.Id(req.GetScopeId()), scope.Org.Prefix()) &&
@@ -1111,7 +1111,7 @@ func validateListRequest(req *pbs.ListAuthMethodsRequest) error {
func validateChangeStateRequest(req *pbs.ChangeStateRequest) error {
const op = "authmethod.validateChangeStateRequest"
if req == nil {
return errors.New(errors.InvalidParameter, op, "Missing request")
return errors.NewDeprecated(errors.InvalidParameter, op, "Missing request")
}
if st := auth.SubtypeFromId(req.GetId()); st != oidc.Subtype {
return handlers.NotFoundErrorf("This endpoint is only available for the %q Auth Method type.", oidc.Subtype.String())
@@ -1139,7 +1139,7 @@ func validateChangeStateRequest(req *pbs.ChangeStateRequest) error {
func validateAuthenticateRequest(req *pbs.AuthenticateRequest) error {
const op = "authmethod.validateAuthenticateRequest"
if req == nil {
return errors.New(errors.InvalidParameter, op, "Missing request")
return errors.NewDeprecated(errors.InvalidParameter, op, "Missing request")
}
badFields := make(map[string]string)
@@ -1166,7 +1166,7 @@ func validateAuthenticateRequest(req *pbs.AuthenticateRequest) error {
func validateAuthenticateLoginRequest(req *pbs.AuthenticateLoginRequest) error {
const op = "authmethod.validateAuthenticateLoginRequest"
if req == nil {
return errors.New(errors.InvalidParameter, op, "Missing request")
return errors.NewDeprecated(errors.InvalidParameter, op, "Missing request")
}
badFields := make(map[string]string)
if strings.TrimSpace(req.GetAuthMethodId()) == "" {
@@ -1201,16 +1201,16 @@ func (s Service) ConvertInternalAuthTokenToApiAuthToken(ctx context.Context, tok
return nil, err
}
if tok == nil {
return nil, errors.New(errors.InvalidParameter, op, "missing auth token.")
return nil, errors.New(ctx, errors.InvalidParameter, op, "missing auth token.")
}
if tok.Token == "" {
return nil, errors.New(errors.InvalidParameter, op, "Empty token.")
return nil, errors.New(ctx, errors.InvalidParameter, op, "Empty token.")
}
if tok.GetPublicId() == "" {
return nil, errors.New(errors.InvalidParameter, op, "Empty token public ID.")
return nil, errors.New(ctx, errors.InvalidParameter, op, "Empty token public ID.")
}
if tok.GetScopeId() == "" {
return nil, errors.New(errors.InvalidParameter, op, "Empty token, scope ID.")
return nil, errors.New(ctx, errors.InvalidParameter, op, "Empty token, scope ID.")
}
token, err := authtoken.EncryptToken(ctx, s.kms, tok.GetScopeId(), tok.GetPublicId(), tok.GetToken())
if err != nil {
@@ -1239,19 +1239,19 @@ func (s Service) ConvertInternalAuthTokenToApiAuthToken(ctx context.Context, tok
func (s Service) convertToAuthenticateResponse(ctx context.Context, req *pbs.AuthenticateRequest, authResults *requestauth.VerifyResults, tok *pba.AuthToken) (*pbs.AuthenticateResponse, error) {
const op = "authmethod.convertToAuthenticateResponse"
if req == nil {
return nil, errors.New(errors.InvalidParameter, op, "Missing request.")
return nil, errors.New(ctx, errors.InvalidParameter, op, "Missing request.")
}
if authResults == nil {
return nil, errors.New(errors.InvalidParameter, op, "Missing auth results.")
return nil, errors.New(ctx, errors.InvalidParameter, op, "Missing auth results.")
}
if authResults.Scope == nil {
return nil, errors.New(errors.InvalidParameter, op, "Missing auth results scope.")
return nil, errors.New(ctx, errors.InvalidParameter, op, "Missing auth results scope.")
}
if authResults.Scope.Id == "" {
return nil, errors.New(errors.InvalidParameter, op, "Missing auth results scope ID.")
return nil, errors.New(ctx, errors.InvalidParameter, op, "Missing auth results scope ID.")
}
if tok == nil {
return nil, errors.New(errors.InvalidParameter, op, "Missing auth token.")
return nil, errors.New(ctx, errors.InvalidParameter, op, "Missing auth token.")
}
res := &perms.Resource{
ScopeId: authResults.Scope.Id,