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,
@@ -67,6 +67,7 @@ var authorizedCollectionActions = map[string]*structpb.ListValue{
}
func TestGet(t *testing.T) {
ctx := context.TODO()
conn, _ := db.TestSetup(t, "postgres")
rw := db.New(conn)
wrapper := db.TestWrapper(t)
@@ -75,7 +76,7 @@ func TestGet(t *testing.T) {
return iam.TestRepo(t, conn, wrapper), nil
}
oidcRepoFn := func() (*oidc.Repository, error) {
return oidc.NewRepository(rw, rw, kmsCache)
return oidc.NewRepository(ctx, rw, rw, kmsCache)
}
pwRepoFn := func() (*password.Repository, error) {
return password.NewRepository(rw, rw, kmsCache)
@@ -204,6 +205,7 @@ func TestGet(t *testing.T) {
}
func TestList(t *testing.T) {
ctx := context.TODO()
conn, _ := db.TestSetup(t, "postgres")
rw := db.New(conn)
wrapper := db.TestWrapper(t)
@@ -212,7 +214,7 @@ func TestList(t *testing.T) {
return iam.TestRepo(t, conn, wrapper), nil
}
oidcRepoFn := func() (*oidc.Repository, error) {
return oidc.NewRepository(rw, rw, kmsCache)
return oidc.NewRepository(ctx, rw, rw, kmsCache)
}
pwRepoFn := func() (*password.Repository, error) {
return password.NewRepository(rw, rw, kmsCache)
@@ -385,6 +387,7 @@ func TestList(t *testing.T) {
}
func TestDelete(t *testing.T) {
ctx := context.TODO()
conn, _ := db.TestSetup(t, "postgres")
rw := db.New(conn)
wrapper := db.TestWrapper(t)
@@ -393,7 +396,7 @@ func TestDelete(t *testing.T) {
return iam.TestRepo(t, conn, wrapper), nil
}
oidcRepoFn := func() (*oidc.Repository, error) {
return oidc.NewRepository(rw, rw, kmsCache)
return oidc.NewRepository(ctx, rw, rw, kmsCache)
}
pwRepoFn := func() (*password.Repository, error) {
return password.NewRepository(rw, rw, kmsCache)
@@ -461,6 +464,7 @@ func TestDelete(t *testing.T) {
}
func TestDelete_twice(t *testing.T) {
ctx := context.TODO()
assert, require := assert.New(t), require.New(t)
conn, _ := db.TestSetup(t, "postgres")
rw := db.New(conn)
@@ -470,7 +474,7 @@ func TestDelete_twice(t *testing.T) {
return iam.TestRepo(t, conn, wrapper), nil
}
oidcRepoFn := func() (*oidc.Repository, error) {
return oidc.NewRepository(rw, rw, kms)
return oidc.NewRepository(ctx, rw, rw, kms)
}
pwRepoFn := func() (*password.Repository, error) {
return password.NewRepository(rw, rw, kms)
@@ -497,6 +501,7 @@ func TestDelete_twice(t *testing.T) {
}
func TestCreate(t *testing.T) {
ctx := context.TODO()
conn, _ := db.TestSetup(t, "postgres")
rw := db.New(conn)
wrapper := db.TestWrapper(t)
@@ -508,7 +513,7 @@ func TestCreate(t *testing.T) {
return password.NewRepository(rw, rw, kms)
}
oidcRepoFn := func() (*oidc.Repository, error) {
return oidc.NewRepository(rw, rw, kms)
return oidc.NewRepository(ctx, rw, rw, kms)
}
atRepoFn := func() (*authtoken.Repository, error) {
return authtoken.NewRepository(rw, rw, kms)
@@ -91,7 +91,7 @@ func (o oidcState) String() string {
// createOidcInRepo creates an oidc auth method in a repo and returns the result.
// This method should never return a nil AuthMethod without returning an error.
func (s Service) createOidcInRepo(ctx context.Context, scopeId string, item *pb.AuthMethod) (*oidc.AuthMethod, error) {
u, _, _, err := toStorageOidcAuthMethod(scopeId, item)
u, _, _, err := toStorageOidcAuthMethod(ctx, scopeId, item)
if err != nil {
return nil, err
}
@@ -108,7 +108,7 @@ func (s Service) createOidcInRepo(ctx context.Context, scopeId string, item *pb.
func (s Service) updateOidcInRepo(ctx context.Context, scopeId string, req *pbs.UpdateAuthMethodRequest) (*oidc.AuthMethod, bool, error) {
item := req.GetItem()
u, dryRun, forced, err := toStorageOidcAuthMethod(scopeId, item)
u, dryRun, forced, err := toStorageOidcAuthMethod(ctx, scopeId, item)
if err != nil {
return nil, dryRun, err
}
@@ -145,10 +145,10 @@ func (s Service) updateOidcInRepo(ctx context.Context, scopeId string, req *pbs.
func (s Service) authenticateOidc(ctx context.Context, req *pbs.AuthenticateRequest, authResults *auth.VerifyResults) (*pbs.AuthenticateResponse, error) {
const op = "authmethod_service.(Service).authenticateOidc"
if req == nil {
return nil, errors.New(errors.InvalidParameter, op, "Nil request.")
return nil, errors.New(ctx, errors.InvalidParameter, op, "Nil request.")
}
if authResults == nil {
return nil, errors.New(errors.InvalidParameter, op, "Nil auth results.")
return nil, errors.New(ctx, errors.InvalidParameter, op, "Nil auth results.")
}
switch req.GetCommand() {
case startCommand:
@@ -165,13 +165,13 @@ func (s Service) authenticateOidc(ctx context.Context, req *pbs.AuthenticateRequ
func (s Service) authenticateOidcStart(ctx context.Context, req *pbs.AuthenticateRequest) (*pbs.AuthenticateResponse, error) {
const op = "authmethod_service.(Service).authenticateOidcStart"
if req == nil {
return nil, errors.New(errors.InvalidParameter, op, "Nil request.")
return nil, errors.New(ctx, errors.InvalidParameter, op, "Nil request.")
}
var opts []oidc.Option
attrs := new(pbs.OidcStartAttributes)
if err := handlers.StructToProto(req.GetAttributes(), attrs); err != nil {
return nil, errors.New(errors.InvalidParameter, op, "Error parsing request attributes.", errors.WithWrap(err))
return nil, errors.New(ctx, errors.InvalidParameter, op, "Error parsing request attributes.", errors.WithWrap(err))
}
if attrs.GetCachedRoundtripPayload() != "" {
opts = append(opts, oidc.WithRoundtripPayload(attrs.GetCachedRoundtripPayload()))
@@ -182,7 +182,7 @@ func (s Service) authenticateOidcStart(ctx context.Context, req *pbs.Authenticat
// this event.WriteError(...) may cause a dup error to be emitted...
// it should be removed if that's the case.
event.WriteError(ctx, op, err, event.WithInfoMsg("error starting the oidc authentication flow"))
return nil, errors.New(errors.Internal, op, "Error generating parameters for starting the OIDC flow. See the controller's log for more information.")
return nil, errors.New(ctx, errors.Internal, op, "Error generating parameters for starting the OIDC flow. See the controller's log for more information.")
}
respAttrs := &pb.OidcAuthMethodAuthenticateStartResponse{
@@ -191,7 +191,7 @@ func (s Service) authenticateOidcStart(ctx context.Context, req *pbs.Authenticat
}
resp := &pbs.AuthenticateResponse{Command: req.GetCommand()}
if resp.Attributes, err = handlers.ProtoToStruct(respAttrs); err != nil {
return nil, errors.New(errors.Internal, op, "Error marshaling parameters.", errors.WithWrap(err))
return nil, errors.New(ctx, errors.Internal, op, "Error marshaling parameters.", errors.WithWrap(err))
}
return resp, nil
}
@@ -208,22 +208,22 @@ func (s Service) authenticateOidcCallback(ctx context.Context, req *pbs.Authenti
// in the redirect URL once we start looking at the url used for this
// request instead of requiring the API URL to be set on the auth method.
if req == nil {
return nil, errors.New(errors.InvalidParameter, op, "Nil request.")
return nil, errors.New(ctx, errors.InvalidParameter, op, "Nil request.")
}
repo, err := s.oidcRepoFn()
if err != nil {
return nil, errors.Wrap(err, op)
return nil, errors.Wrap(ctx, err, op)
}
am, err := repo.LookupAuthMethod(ctx, req.GetAuthMethodId())
if err != nil {
return nil, errors.Wrap(err, op)
return nil, errors.Wrap(ctx, err, op)
}
if am == nil {
return nil, errors.New(errors.RecordNotFound, op, fmt.Sprintf("Auth method %s not found.", req.GetAuthMethodId()))
return nil, errors.New(ctx, errors.RecordNotFound, op, fmt.Sprintf("Auth method %s not found.", req.GetAuthMethodId()))
}
if am.GetApiUrl() == "" {
return nil, errors.New(errors.InvalidParameter, op, "Auth method doesn't have API URL defined.")
return nil, errors.New(ctx, errors.InvalidParameter, op, "Auth method doesn't have API URL defined.")
}
errRedirectBase := fmt.Sprintf(oidc.AuthenticationErrorsEndpoint, am.GetApiUrl())
@@ -232,7 +232,7 @@ func (s Service) authenticateOidcCallback(ctx context.Context, req *pbs.Authenti
pbErr := handlers.ToApiError(err)
out, err := handlers.JSONMarshaler().Marshal(pbErr)
if err != nil {
return nil, errors.Wrap(err, op, errors.WithMsg("unable to marshal the error for callback"))
return nil, errors.Wrap(ctx, err, op, errors.WithMsg("unable to marshal the error for callback"))
}
u.Add("error", string(out))
errRedirect := fmt.Sprintf("%s?%s", errRedirectBase, u.Encode())
@@ -240,7 +240,7 @@ func (s Service) authenticateOidcCallback(ctx context.Context, req *pbs.Authenti
FinalRedirectUrl: errRedirect,
})
if err != nil {
return nil, errors.Wrap(err, op, errors.WithMsg("failed creating error redirect response"))
return nil, errors.Wrap(ctx, err, op, errors.WithMsg("failed creating error redirect response"))
}
return &pbs.AuthenticateResponse{Command: callbackCommand, Attributes: respAttrs}, nil
}
@@ -253,7 +253,7 @@ func (s Service) authenticateOidcCallback(ctx context.Context, req *pbs.Authenti
var finalRedirectUrl string
if attrs.GetError() != "" {
err := errors.Wrap(fmt.Errorf("Error: %q, Details: %q", attrs.GetError(), attrs.GetErrorDescription()), op, errors.WithCode(errors.OidcProviderCallbackError))
err := errors.Wrap(ctx, fmt.Errorf("Error: %q, Details: %q", attrs.GetError(), attrs.GetErrorDescription()), op, errors.WithCode(errors.OidcProviderCallbackError))
return errResponse(err)
}
finalRedirectUrl, err = oidc.Callback(
@@ -265,14 +265,14 @@ func (s Service) authenticateOidcCallback(ctx context.Context, req *pbs.Authenti
attrs.GetState(),
attrs.GetCode())
if err != nil {
return errResponse(errors.New(errors.InvalidParameter, op, "Callback validation failed.", errors.WithWrap(err)))
return errResponse(errors.New(ctx, errors.InvalidParameter, op, "Callback validation failed.", errors.WithWrap(err)))
}
respAttrs, err := handlers.ProtoToStruct(&pb.OidcAuthMethodAuthenticateCallbackResponse{
FinalRedirectUrl: finalRedirectUrl,
})
if err != nil {
return errResponse(errors.New(errors.Internal, op, "Error marshaling parameters after successful callback", errors.WithWrap(err)))
return errResponse(errors.New(ctx, errors.Internal, op, "Error marshaling parameters after successful callback", errors.WithWrap(err)))
}
return &pbs.AuthenticateResponse{Command: req.GetCommand(), Attributes: respAttrs}, nil
@@ -281,35 +281,35 @@ func (s Service) authenticateOidcCallback(ctx context.Context, req *pbs.Authenti
func (s Service) authenticateOidcToken(ctx context.Context, req *pbs.AuthenticateRequest, authResults *auth.VerifyResults) (*pbs.AuthenticateResponse, error) {
const op = "authmethod_service.(Service).authenticateOidcToken"
if req == nil {
return nil, errors.New(errors.InvalidParameter, op, "Nil request.")
return nil, errors.New(ctx, errors.InvalidParameter, op, "Nil request.")
}
if authResults == nil {
return nil, errors.New(errors.InvalidParameter, op, "Nil auth results.")
return nil, errors.New(ctx, errors.InvalidParameter, op, "Nil auth results.")
}
if req.GetAttributes() == nil {
return nil, errors.New(errors.InvalidParameter, op, "Nil request attributes.")
return nil, errors.New(ctx, errors.InvalidParameter, op, "Nil request attributes.")
}
attrs := new(pb.OidcAuthMethodAuthenticateTokenRequest)
if err := handlers.StructToProto(req.GetAttributes(), attrs); err != nil {
return nil, errors.New(errors.InvalidParameter, op, "Error parsing request attributes.", errors.WithWrap(err))
return nil, errors.New(ctx, errors.InvalidParameter, op, "Error parsing request attributes.", errors.WithWrap(err))
}
if attrs.TokenId == "" {
return nil, errors.New(errors.InvalidParameter, op, "Empty token ID in request attributes.")
return nil, errors.New(ctx, errors.InvalidParameter, op, "Empty token ID in request attributes.")
}
token, err := oidc.TokenRequest(ctx, s.kms, s.atRepoFn, req.GetAuthMethodId(), attrs.TokenId)
if err != nil {
switch {
case errors.Match(errors.T(errors.Forbidden), err):
return nil, errors.Wrap(err, op, errors.WithMsg("Forbidden."))
return nil, errors.Wrap(ctx, err, op, errors.WithMsg("Forbidden."))
case errors.Match(errors.T(errors.AuthAttemptExpired), err):
return nil, errors.Wrap(err, op, errors.WithMsg("Forbidden."))
return nil, errors.Wrap(ctx, err, op, errors.WithMsg("Forbidden."))
default:
// this event.WriteError(...) may cause a dup error to be emitted...
// it should be removed if that's the case.
event.WriteError(ctx, op, err, event.WithInfoMsg("error generating parameters for token request"))
return nil, errors.Wrap(err, op, errors.WithMsg("Error generating parameters for token request. See the controller's log for more information."))
return nil, errors.Wrap(ctx, err, op, errors.WithMsg("Error generating parameters for token request. See the controller's log for more information."))
}
}
if token == nil {
@@ -317,7 +317,7 @@ func (s Service) authenticateOidcToken(ctx context.Context, req *pbs.Authenticat
statusField: "unknown",
})
if err != nil {
return nil, errors.New(errors.Internal, op, "Error generating response attributes.", errors.WithWrap(err))
return nil, errors.New(ctx, errors.Internal, op, "Error generating response attributes.", errors.WithWrap(err))
}
return &pbs.AuthenticateResponse{
Command: req.Command,
@@ -330,7 +330,7 @@ func (s Service) authenticateOidcToken(ctx context.Context, req *pbs.Authenticat
token,
)
if err != nil {
return nil, errors.New(errors.Internal, op, "Error converting response to proper format.", errors.WithWrap(err))
return nil, errors.New(ctx, errors.Internal, op, "Error converting response to proper format.", errors.WithWrap(err))
}
return s.convertToAuthenticateResponse(ctx, req, authResults, responseToken)
}
@@ -404,10 +404,10 @@ func validateAuthenticateOidcRequest(req *pbs.AuthenticateRequest) error {
return nil
}
func toStorageOidcAuthMethod(scopeId string, in *pb.AuthMethod) (out *oidc.AuthMethod, dryRun, forced bool, err error) {
func toStorageOidcAuthMethod(ctx context.Context, scopeId string, in *pb.AuthMethod) (out *oidc.AuthMethod, dryRun, forced bool, err error) {
const op = "authmethod_service.toStorageOidcAuthMethod"
if in == nil {
return nil, false, false, errors.New(errors.InvalidParameter, op, "nil auth method.")
return nil, false, false, errors.NewDeprecated(errors.InvalidParameter, op, "nil auth method.")
}
attrs := &pb.OidcAuthMethodAttributes{}
if err := handlers.StructToProto(in.GetAttributes(), attrs); err != nil {
@@ -431,14 +431,14 @@ func toStorageOidcAuthMethod(scopeId string, in *pb.AuthMethod) (out *oidc.AuthM
iss = strings.SplitN(iss, ".well-known/", 2)[0]
issuer, err := url.Parse(iss)
if err != nil {
return nil, false, false, errors.Wrap(err, op, errors.WithMsg("cannot parse issuer"), errors.WithCode(errors.InvalidParameter))
return nil, false, false, errors.WrapDeprecated(err, op, errors.WithMsg("cannot parse issuer"), errors.WithCode(errors.InvalidParameter))
}
opts = append(opts, oidc.WithIssuer(issuer))
}
if apiUrl := strings.TrimSpace(attrs.GetApiUrlPrefix().GetValue()); apiUrl != "" {
apiU, err := url.Parse(apiUrl)
if err != nil {
return nil, false, false, errors.Wrap(err, op, errors.WithMsg("cannot parse api_url_prefix"), errors.WithCode(errors.InvalidParameter))
return nil, false, false, errors.WrapDeprecated(err, op, errors.WithMsg("cannot parse api_url_prefix"), errors.WithCode(errors.InvalidParameter))
}
opts = append(opts, oidc.WithApiUrl(apiU))
}
@@ -463,7 +463,7 @@ func toStorageOidcAuthMethod(scopeId string, in *pb.AuthMethod) (out *oidc.AuthM
}
if len(attrs.GetIdpCaCerts()) > 0 {
certs, err := oidc.ParseCertificates(attrs.GetIdpCaCerts()...)
certs, err := oidc.ParseCertificates(ctx, attrs.GetIdpCaCerts()...)
if err != nil {
return nil, false, false, err
}
@@ -477,26 +477,26 @@ func toStorageOidcAuthMethod(scopeId string, in *pb.AuthMethod) (out *oidc.AuthM
if len(attrs.GetAccountClaimMaps()) > 0 {
claimsMap := make(map[string]oidc.AccountToClaim, len(attrs.GetAccountClaimMaps()))
for _, v := range attrs.GetAccountClaimMaps() {
acm, err := oidc.ParseAccountClaimMaps(v)
acm, err := oidc.ParseAccountClaimMaps(ctx, v)
if err != nil {
return nil, false, false, errors.Wrap(err, op)
return nil, false, false, errors.WrapDeprecated(err, op)
}
if len(acm) > 1 {
return nil, false, false, errors.New(errors.InvalidParameter, op, fmt.Sprintf("unable to parse account claim map %s", v))
return nil, false, false, errors.NewDeprecated(errors.InvalidParameter, op, fmt.Sprintf("unable to parse account claim map %s", v))
}
var m oidc.ClaimMap
for _, m = range acm {
}
to, err := oidc.ConvertToAccountToClaim(m.To)
to, err := oidc.ConvertToAccountToClaim(ctx, m.To)
if err != nil {
return nil, false, false, errors.Wrap(err, op)
return nil, false, false, errors.WrapDeprecated(err, op)
}
claimsMap[m.From] = to
}
opts = append(opts, oidc.WithAccountClaimMap(claimsMap))
}
u, err := oidc.NewAuthMethod(scopeId, clientId, clientSecret, opts...)
u, err := oidc.NewAuthMethod(ctx, scopeId, clientId, clientSecret, opts...)
if err != nil {
return nil, false, false, handlers.ApiErrorWithCodeAndMessage(codes.Internal, "Unable to build auth method: %v.", err)
}
@@ -69,6 +69,7 @@ type setup struct {
func getSetup(t *testing.T) setup {
t.Helper()
ctx := context.TODO()
require := require.New(t)
var ret setup
var err error
@@ -84,7 +85,7 @@ func getSetup(t *testing.T) setup {
return ret.iamRepo, nil
}
ret.oidcRepoFn = func() (*oidc.Repository, error) {
return oidc.NewRepository(ret.rw, ret.rw, ret.kmsCache)
return oidc.NewRepository(ctx, ret.rw, ret.rw, ret.kmsCache)
}
ret.pwRepoFn = func() (*password.Repository, error) {
return password.NewRepository(ret.rw, ret.rw, ret.kmsCache)
@@ -102,7 +103,7 @@ func getSetup(t *testing.T) setup {
ret.testProvider = capoidc.StartTestProvider(t)
_, _, ret.testProviderAlg, _ = ret.testProvider.SigningKeys()
ret.testProviderCaCert, err = oidc.ParseCertificates(ret.testProvider.CACert())
ret.testProviderCaCert, err = oidc.ParseCertificates(ctx, ret.testProvider.CACert())
require.NoError(err)
ret.testController = httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
@@ -132,6 +133,7 @@ func getSetup(t *testing.T) setup {
}
func TestList_FilterNonPublic(t *testing.T) {
ctx := context.TODO()
conn, _ := db.TestSetup(t, "postgres")
rw := db.New(conn)
wrapper := db.TestWrapper(t)
@@ -140,7 +142,7 @@ func TestList_FilterNonPublic(t *testing.T) {
return iam.TestRepo(t, conn, wrapper), nil
}
oidcRepoFn := func() (*oidc.Repository, error) {
return oidc.NewRepository(rw, rw, kmsCache)
return oidc.NewRepository(ctx, rw, rw, kmsCache)
}
pwRepoFn := func() (*password.Repository, error) {
return password.NewRepository(rw, rw, kmsCache)
@@ -234,6 +236,7 @@ func TestList_FilterNonPublic(t *testing.T) {
}
func TestUpdate_OIDC(t *testing.T) {
ctx := context.TODO()
conn, _ := db.TestSetup(t, "postgres")
rw := db.New(conn)
wrapper := db.TestWrapper(t)
@@ -242,7 +245,7 @@ func TestUpdate_OIDC(t *testing.T) {
return iam.TestRepo(t, conn, wrapper), nil
}
oidcRepoFn := func() (*oidc.Repository, error) {
return oidc.NewRepository(rw, rw, kms)
return oidc.NewRepository(ctx, rw, rw, kms)
}
pwRepoFn := func() (*password.Repository, error) {
return password.NewRepository(rw, rw, kms)
@@ -1120,6 +1123,7 @@ func TestUpdate_OIDC(t *testing.T) {
}
func TestUpdate_OIDCDryRun(t *testing.T) {
ctx := context.TODO()
conn, _ := db.TestSetup(t, "postgres")
rw := db.New(conn)
wrapper := db.TestWrapper(t)
@@ -1128,7 +1132,7 @@ func TestUpdate_OIDCDryRun(t *testing.T) {
return iam.TestRepo(t, conn, wrapper), nil
}
oidcRepoFn := func() (*oidc.Repository, error) {
return oidc.NewRepository(rw, rw, kmsCache)
return oidc.NewRepository(ctx, rw, rw, kmsCache)
}
pwRepoFn := func() (*password.Repository, error) {
return password.NewRepository(rw, rw, kmsCache)
@@ -1146,7 +1150,7 @@ func TestUpdate_OIDCDryRun(t *testing.T) {
tp.SetClientCreds(tpClientId, tpClientSecret)
_, _, tpAlg, _ := tp.SigningKeys()
tpCert, err := oidc.ParseCertificates(tp.CACert())
tpCert, err := oidc.ParseCertificates(ctx, tp.CACert())
require.NoError(t, err)
databaseWrapper, err := kmsCache.GetWrapper(context.Background(), o.PublicId, kms.KeyPurposeDatabase)
require.NoError(t, err)
@@ -1294,6 +1298,7 @@ func TestUpdate_OIDCDryRun(t *testing.T) {
}
func TestChangeState_OIDC(t *testing.T) {
ctx := context.TODO()
conn, _ := db.TestSetup(t, "postgres")
rw := db.New(conn)
wrapper := db.TestWrapper(t)
@@ -1302,7 +1307,7 @@ func TestChangeState_OIDC(t *testing.T) {
return iam.TestRepo(t, conn, wrapper), nil
}
oidcRepoFn := func() (*oidc.Repository, error) {
return oidc.NewRepository(rw, rw, kmsCache)
return oidc.NewRepository(ctx, rw, rw, kmsCache)
}
pwRepoFn := func() (*password.Repository, error) {
return password.NewRepository(rw, rw, kmsCache)
@@ -1323,7 +1328,7 @@ func TestChangeState_OIDC(t *testing.T) {
tpClientSecret := "her-dog's-name"
tp.SetClientCreds(tpClientId, tpClientSecret)
_, _, tpAlg, _ := tp.SigningKeys()
tpCert, err := oidc.ParseCertificates(tp.CACert())
tpCert, err := oidc.ParseCertificates(ctx, tp.CACert())
require.NoError(t, err)
incompleteAm := oidc.TestAuthMethod(t, conn, databaseWrapper, o.PublicId, "inactive", "client id", "secret",
@@ -174,7 +174,7 @@ func validateAuthenticatePasswordRequest(req *pbs.AuthenticateRequest) error {
func toStoragePwAuthMethod(scopeId string, item *pb.AuthMethod) (*password.AuthMethod, error) {
const op = "authmethod_service.toStoragePwAuthMethod"
if item == nil {
return nil, errors.New(errors.InvalidParameter, op, "nil auth method.")
return nil, errors.NewDeprecated(errors.InvalidParameter, op, "nil auth method.")
}
var opts []password.Option
if item.GetName() != nil {
@@ -32,6 +32,7 @@ import (
)
func TestUpdate_Password(t *testing.T) {
ctx := context.TODO()
conn, _ := db.TestSetup(t, "postgres")
rw := db.New(conn)
wrapper := db.TestWrapper(t)
@@ -40,7 +41,7 @@ func TestUpdate_Password(t *testing.T) {
return iam.TestRepo(t, conn, wrapper), nil
}
oidcRepoFn := func() (*oidc.Repository, error) {
return oidc.NewRepository(rw, rw, kms)
return oidc.NewRepository(ctx, rw, rw, kms)
}
pwRepoFn := func() (*password.Repository, error) {
return password.NewRepository(rw, rw, kms)
@@ -447,6 +448,7 @@ func TestUpdate_Password(t *testing.T) {
}
func TestAuthenticate_Password(t *testing.T) {
ctx := context.TODO()
conn, _ := db.TestSetup(t, "postgres")
rw := db.New(conn)
wrapper := db.TestWrapper(t)
@@ -457,7 +459,7 @@ func TestAuthenticate_Password(t *testing.T) {
return iam.TestRepo(t, conn, wrapper), nil
}
oidcRepoFn := func() (*oidc.Repository, error) {
return oidc.NewRepository(rw, rw, kms)
return oidc.NewRepository(ctx, rw, rw, kms)
}
pwRepoFn := func() (*password.Repository, error) {
return password.NewRepository(rw, rw, kms)
@@ -616,6 +618,7 @@ func TestAuthenticate_Password(t *testing.T) {
}
func TestAuthenticateLogin_Password(t *testing.T) {
ctx := context.TODO()
conn, _ := db.TestSetup(t, "postgres")
rw := db.New(conn)
wrapper := db.TestWrapper(t)
@@ -626,7 +629,7 @@ func TestAuthenticateLogin_Password(t *testing.T) {
return iam.TestRepo(t, conn, wrapper), nil
}
oidcRepoFn := func() (*oidc.Repository, error) {
return oidc.NewRepository(rw, rw, kms)
return oidc.NewRepository(ctx, rw, rw, kms)
}
pwRepoFn := func() (*password.Repository, error) {
return password.NewRepository(rw, rw, kms)
@@ -784,6 +787,7 @@ func TestAuthenticateLogin_Password(t *testing.T) {
}
func TestAuthenticate_AuthAccountConnectedToIamUser_Password(t *testing.T) {
ctx := context.TODO()
assert, require := assert.New(t), require.New(t)
conn, _ := db.TestSetup(t, "postgres")
rw := db.New(conn)
@@ -795,7 +799,7 @@ func TestAuthenticate_AuthAccountConnectedToIamUser_Password(t *testing.T) {
return iam.TestRepo(t, conn, wrapper), nil
}
oidcRepoFn := func() (*oidc.Repository, error) {
return oidc.NewRepository(rw, rw, kms)
return oidc.NewRepository(ctx, rw, rw, kms)
}
pwRepoFn := func() (*password.Repository, error) {
return password.NewRepository(rw, rw, kms)