diff --git a/internal/admin/repository/eventsourcing/eventstore/iam.go b/internal/admin/repository/eventsourcing/eventstore/iam.go index 4d69d8ca34..bce9615978 100644 --- a/internal/admin/repository/eventsourcing/eventstore/iam.go +++ b/internal/admin/repository/eventsourcing/eventstore/iam.go @@ -167,32 +167,6 @@ func (repo *IAMRepository) SearchDefaultIDPProviders(ctx context.Context, reques return result, nil } -func (repo *IAMRepository) GetDefaultLockoutPolicy(ctx context.Context) (*iam_model.LockoutPolicyView, error) { - policy, viewErr := repo.View.LockoutPolicyByAggregateID(repo.SystemDefaults.IamID) - if viewErr != nil && !caos_errs.IsNotFound(viewErr) { - return nil, viewErr - } - if caos_errs.IsNotFound(viewErr) { - policy = new(iam_es_model.LockoutPolicyView) - } - - events, esErr := repo.getIAMEvents(ctx, policy.Sequence) - if caos_errs.IsNotFound(viewErr) && len(events) == 0 { - return nil, caos_errs.ThrowNotFound(nil, "EVENT-2M9oP", "Errors.IAM.LockoutPolicy.NotFound") - } - if esErr != nil { - logging.Log("EVENT-3M0xs").WithError(esErr).Debug("error retrieving new events") - return iam_es_model.LockoutViewToModel(policy), nil - } - policyCopy := *policy - for _, event := range events { - if err := policyCopy.AppendEvent(event); err != nil { - return iam_es_model.LockoutViewToModel(policy), nil - } - } - return iam_es_model.LockoutViewToModel(policy), nil -} - func (repo *IAMRepository) GetOrgIAMPolicy(ctx context.Context) (*iam_model.OrgIAMPolicyView, error) { policy, viewErr := repo.View.OrgIAMPolicyByAggregateID(repo.SystemDefaults.IamID) if viewErr != nil && !caos_errs.IsNotFound(viewErr) { diff --git a/internal/admin/repository/eventsourcing/handler/handler.go b/internal/admin/repository/eventsourcing/handler/handler.go index 1e176af992..0da373db01 100644 --- a/internal/admin/repository/eventsourcing/handler/handler.go +++ b/internal/admin/repository/eventsourcing/handler/handler.go @@ -45,8 +45,6 @@ func Register(configs Configs, bulkLimit, errorCount uint64, view *view.View, es newUser( handler{view, bulkLimit, configs.cycleDuration("User"), errorCount, es}, defaults), - newLockoutPolicy( - handler{view, bulkLimit, configs.cycleDuration("LockoutPolicy"), errorCount, es}), newOrgIAMPolicy( handler{view, bulkLimit, configs.cycleDuration("OrgIAMPolicy"), errorCount, es}), newExternalIDP( diff --git a/internal/admin/repository/eventsourcing/handler/password_lockout_policy.go b/internal/admin/repository/eventsourcing/handler/password_lockout_policy.go deleted file mode 100644 index 024d2f3bc6..0000000000 --- a/internal/admin/repository/eventsourcing/handler/password_lockout_policy.go +++ /dev/null @@ -1,110 +0,0 @@ -package handler - -import ( - "github.com/caos/logging" - "github.com/caos/zitadel/internal/eventstore/v1" - iam_es_model "github.com/caos/zitadel/internal/iam/repository/eventsourcing/model" - - es_models "github.com/caos/zitadel/internal/eventstore/v1/models" - "github.com/caos/zitadel/internal/eventstore/v1/query" - "github.com/caos/zitadel/internal/eventstore/v1/spooler" - iam_model "github.com/caos/zitadel/internal/iam/repository/view/model" - "github.com/caos/zitadel/internal/org/repository/eventsourcing/model" -) - -const ( - lockoutPolicyTable = "adminapi.lockout_policies" -) - -type LockoutPolicy struct { - handler - subscription *v1.Subscription -} - -func newLockoutPolicy(handler handler) *LockoutPolicy { - h := &LockoutPolicy{ - handler: handler, - } - - h.subscribe() - - return h -} - -func (p *LockoutPolicy) subscribe() { - p.subscription = p.es.Subscribe(p.AggregateTypes()...) - go func() { - for event := range p.subscription.Events { - query.ReduceEvent(p, event) - } - }() -} - -func (p *LockoutPolicy) ViewModel() string { - return lockoutPolicyTable -} - -func (m *LockoutPolicy) Subscription() *v1.Subscription { - return m.subscription -} - -func (p *LockoutPolicy) AggregateTypes() []es_models.AggregateType { - return []es_models.AggregateType{model.OrgAggregate, iam_es_model.IAMAggregate} -} - -func (p *LockoutPolicy) CurrentSequence() (uint64, error) { - sequence, err := p.view.GetLatestLockoutPolicySequence() - if err != nil { - return 0, err - } - return sequence.CurrentSequence, nil -} - -func (p *LockoutPolicy) EventQuery() (*es_models.SearchQuery, error) { - sequence, err := p.view.GetLatestLockoutPolicySequence() - if err != nil { - return nil, err - } - return es_models.NewSearchQuery(). - AggregateTypeFilter(p.AggregateTypes()...). - LatestSequenceFilter(sequence.CurrentSequence), nil -} - -func (p *LockoutPolicy) Reduce(event *es_models.Event) (err error) { - switch event.AggregateType { - case model.OrgAggregate, iam_es_model.IAMAggregate: - err = p.processLockoutPolicy(event) - } - return err -} - -func (p *LockoutPolicy) processLockoutPolicy(event *es_models.Event) (err error) { - policy := new(iam_model.LockoutPolicyView) - switch event.Type { - case iam_es_model.LockoutPolicyAdded, model.LockoutPolicyAdded: - err = policy.AppendEvent(event) - case iam_es_model.LockoutPolicyChanged, model.LockoutPolicyChanged: - policy, err = p.view.LockoutPolicyByAggregateID(event.AggregateID) - if err != nil { - return err - } - err = policy.AppendEvent(event) - case model.LockoutPolicyRemoved: - return p.view.DeleteLockoutPolicy(event.AggregateID, event) - default: - return p.view.ProcessedLockoutPolicySequence(event) - } - if err != nil { - return err - } - return p.view.PutLockoutPolicy(policy, event) -} - -func (p *LockoutPolicy) OnError(event *es_models.Event, err error) error { - logging.LogWithFields("SPOOL-nD8sie", "id", event.AggregateID).WithError(err).Warn("something went wrong in Lockout policy handler") - return spooler.HandleError(event, err, p.view.GetLatestLockoutPolicyFailedEvent, p.view.ProcessedLockoutPolicyFailedEvent, p.view.ProcessedLockoutPolicySequence, p.errorCountUntilSkip) -} - -func (p *LockoutPolicy) OnSuccess() error { - return spooler.HandleSuccess(p.view.UpdateLockoutPolicySpoolerRunTimestamp) -} diff --git a/internal/admin/repository/eventsourcing/view/lockout_policy.go b/internal/admin/repository/eventsourcing/view/lockout_policy.go deleted file mode 100644 index a5b54085dd..0000000000 --- a/internal/admin/repository/eventsourcing/view/lockout_policy.go +++ /dev/null @@ -1,53 +0,0 @@ -package view - -import ( - "github.com/caos/zitadel/internal/errors" - "github.com/caos/zitadel/internal/eventstore/v1/models" - "github.com/caos/zitadel/internal/iam/repository/view" - "github.com/caos/zitadel/internal/iam/repository/view/model" - global_view "github.com/caos/zitadel/internal/view/repository" -) - -const ( - lockoutPolicyTable = "adminapi.lockout_policies" -) - -func (v *View) LockoutPolicyByAggregateID(aggregateID string) (*model.LockoutPolicyView, error) { - return view.GetLockoutPolicyByAggregateID(v.Db, lockoutPolicyTable, aggregateID) -} - -func (v *View) PutLockoutPolicy(policy *model.LockoutPolicyView, event *models.Event) error { - err := view.PutLockoutPolicy(v.Db, lockoutPolicyTable, policy) - if err != nil { - return err - } - return v.ProcessedLockoutPolicySequence(event) -} - -func (v *View) DeleteLockoutPolicy(aggregateID string, event *models.Event) error { - err := view.DeleteLockoutPolicy(v.Db, lockoutPolicyTable, aggregateID) - if err != nil && !errors.IsNotFound(err) { - return err - } - return v.ProcessedLockoutPolicySequence(event) -} - -func (v *View) GetLatestLockoutPolicySequence() (*global_view.CurrentSequence, error) { - return v.latestSequence(lockoutPolicyTable) -} - -func (v *View) ProcessedLockoutPolicySequence(event *models.Event) error { - return v.saveCurrentSequence(lockoutPolicyTable, event) -} - -func (v *View) UpdateLockoutPolicySpoolerRunTimestamp() error { - return v.updateSpoolerRunSequence(lockoutPolicyTable) -} - -func (v *View) GetLatestLockoutPolicyFailedEvent(sequence uint64) (*global_view.FailedEvent, error) { - return v.latestFailedEvent(lockoutPolicyTable, sequence) -} - -func (v *View) ProcessedLockoutPolicyFailedEvent(failedEvent *global_view.FailedEvent) error { - return v.saveFailedEvent(failedEvent) -} diff --git a/internal/admin/repository/iam.go b/internal/admin/repository/iam.go index d7983b0d5c..b204e58cb4 100644 --- a/internal/admin/repository/iam.go +++ b/internal/admin/repository/iam.go @@ -35,8 +35,6 @@ type IAMRepository interface { GetDefaultLoginTexts(ctx context.Context, lang string) (*domain.CustomLoginText, error) GetCustomLoginTexts(ctx context.Context, lang string) (*domain.CustomLoginText, error) - GetDefaultLockoutPolicy(ctx context.Context) (*iam_model.LockoutPolicyView, error) - GetDefaultPrivacyPolicy(ctx context.Context) (*iam_model.PrivacyPolicyView, error) GetDefaultOrgIAMPolicy(ctx context.Context) (*iam_model.OrgIAMPolicyView, error) diff --git a/internal/api/grpc/admin/lockout.go b/internal/api/grpc/admin/lockout.go index f5916e4691..f79f823745 100644 --- a/internal/api/grpc/admin/lockout.go +++ b/internal/api/grpc/admin/lockout.go @@ -9,7 +9,7 @@ import ( ) func (s *Server) GetLockoutPolicy(ctx context.Context, req *admin_pb.GetLockoutPolicyRequest) (*admin_pb.GetLockoutPolicyResponse, error) { - policy, err := s.iam.GetDefaultLockoutPolicy(ctx) + policy, err := s.query.DefaultLockoutPolicy(ctx) if err != nil { return nil, err } diff --git a/internal/api/grpc/management/policy_lockout.go b/internal/api/grpc/management/policy_lockout.go index f93d06bfa6..b4506b8dac 100644 --- a/internal/api/grpc/management/policy_lockout.go +++ b/internal/api/grpc/management/policy_lockout.go @@ -2,6 +2,7 @@ package management import ( "context" + "github.com/caos/zitadel/internal/api/authz" "github.com/caos/zitadel/internal/api/grpc/object" policy_grpc "github.com/caos/zitadel/internal/api/grpc/policy" @@ -9,15 +10,15 @@ import ( ) func (s *Server) GetLockoutPolicy(ctx context.Context, req *mgmt_pb.GetLockoutPolicyRequest) (*mgmt_pb.GetLockoutPolicyResponse, error) { - policy, err := s.org.GetLockoutPolicy(ctx) + policy, err := s.query.LockoutPolicyByOrg(ctx, authz.GetCtxData(ctx).OrgID) if err != nil { return nil, err } - return &mgmt_pb.GetLockoutPolicyResponse{Policy: policy_grpc.ModelLockoutPolicyToPb(policy), IsDefault: policy.Default}, nil + return &mgmt_pb.GetLockoutPolicyResponse{Policy: policy_grpc.ModelLockoutPolicyToPb(policy), IsDefault: policy.IsDefault}, nil } func (s *Server) GetDefaultLockoutPolicy(ctx context.Context, req *mgmt_pb.GetDefaultLockoutPolicyRequest) (*mgmt_pb.GetDefaultLockoutPolicyResponse, error) { - policy, err := s.org.GetDefaultLockoutPolicy(ctx) + policy, err := s.query.DefaultLockoutPolicy(ctx) if err != nil { return nil, err } diff --git a/internal/api/grpc/policy/password_lockout_policy.go b/internal/api/grpc/policy/password_lockout_policy.go index 9a2498bd72..7872140ffd 100644 --- a/internal/api/grpc/policy/password_lockout_policy.go +++ b/internal/api/grpc/policy/password_lockout_policy.go @@ -2,19 +2,19 @@ package policy import ( "github.com/caos/zitadel/internal/api/grpc/object" - "github.com/caos/zitadel/internal/iam/model" + "github.com/caos/zitadel/internal/query" policy_pb "github.com/caos/zitadel/pkg/grpc/policy" ) -func ModelLockoutPolicyToPb(policy *model.LockoutPolicyView) *policy_pb.LockoutPolicy { +func ModelLockoutPolicyToPb(policy *query.LockoutPolicy) *policy_pb.LockoutPolicy { return &policy_pb.LockoutPolicy{ - IsDefault: policy.Default, + IsDefault: policy.IsDefault, MaxPasswordAttempts: policy.MaxPasswordAttempts, Details: object.ToViewDetailsPb( policy.Sequence, policy.CreationDate, policy.ChangeDate, - "", //TODO: resourceowner + policy.ResourceOwner, ), } } diff --git a/internal/auth/repository/eventsourcing/eventstore/auth_request.go b/internal/auth/repository/eventsourcing/eventstore/auth_request.go index d65ff01527..1b0c83c8b8 100644 --- a/internal/auth/repository/eventsourcing/eventstore/auth_request.go +++ b/internal/auth/repository/eventsourcing/eventstore/auth_request.go @@ -71,7 +71,7 @@ type loginPolicyViewProvider interface { } type lockoutPolicyViewProvider interface { - LockoutPolicyByAggregateID(string) (*iam_view_model.LockoutPolicyView, error) + LockoutPolicyByOrg(context.Context, string) (*query.LockoutPolicy, error) } type idpProviderViewProvider interface { @@ -294,7 +294,22 @@ func (repo *AuthRequestRepo) VerifyPassword(ctx context.Context, id, userID, res if err != nil { return err } - return repo.Command.HumanCheckPassword(ctx, resourceOwner, userID, password, request.WithCurrentInfo(info), policy) + return repo.Command.HumanCheckPassword(ctx, resourceOwner, userID, password, request.WithCurrentInfo(info), lockoutPolicyToDomain(policy)) +} + +func lockoutPolicyToDomain(policy *query.LockoutPolicy) *domain.LockoutPolicy { + return &domain.LockoutPolicy{ + ObjectRoot: es_models.ObjectRoot{ + AggregateID: policy.ID, + Sequence: policy.Sequence, + ResourceOwner: policy.ResourceOwner, + CreationDate: policy.CreationDate, + ChangeDate: policy.ChangeDate, + }, + Default: policy.IsDefault, + MaxPasswordAttempts: policy.MaxPasswordAttempts, + ShowLockOutFailures: policy.ShowFailures, + } } func (repo *AuthRequestRepo) VerifyMFAOTP(ctx context.Context, authRequestID, userID, resourceOwner, code, userAgentID string, info *domain.BrowserInfo) (err error) { @@ -512,7 +527,7 @@ func (repo *AuthRequestRepo) fillPolicies(ctx context.Context, request *domain.A if err != nil { return err } - request.LockoutPolicy = lockoutPolicy + request.LockoutPolicy = lockoutPolicyToDomain(lockoutPolicy) privacyPolicy, err := repo.getPrivacyPolicy(ctx, orgID) if err != nil { return err @@ -889,34 +904,12 @@ func (repo *AuthRequestRepo) getPrivacyPolicy(ctx context.Context, orgID string) return policy.ToDomain(), err } -func (repo *AuthRequestRepo) getLockoutPolicy(ctx context.Context, orgID string) (*domain.LockoutPolicy, error) { - policy, err := repo.View.LockoutPolicyByAggregateID(orgID) - if errors.IsNotFound(err) { - policy, err = repo.View.LockoutPolicyByAggregateID(repo.IAMID) - if err != nil && !errors.IsNotFound(err) { - return nil, err - } - if err == nil { - return policy.ToDomain(), nil - } - policy = &iam_view_model.LockoutPolicyView{} - events, err := repo.Eventstore.FilterEvents(ctx, es_models.NewSearchQuery(). - AggregateIDFilter(repo.IAMID). - AggregateTypeFilter(iam.AggregateType). - EventTypesFilter(es_models.EventType(iam.LockoutPolicyAddedEventType), es_models.EventType(iam.LockoutPolicyChangedEventType))) - if err != nil || len(events) == 0 { - return nil, errors.ThrowNotFound(err, "EVENT-Gfgr2", "IAM.LockoutPolicy.NotExisting") - } - policy.Default = true - for _, event := range events { - policy.AppendEvent(event) - } - return policy.ToDomain(), nil - } +func (repo *AuthRequestRepo) getLockoutPolicy(ctx context.Context, orgID string) (*query.LockoutPolicy, error) { + policy, err := repo.LockoutPolicyViewProvider.LockoutPolicyByOrg(ctx, orgID) if err != nil { return nil, err } - return policy.ToDomain(), err + return policy, err } func (repo *AuthRequestRepo) getLabelPolicy(ctx context.Context, orgID string) (*domain.LabelPolicy, error) { diff --git a/internal/auth/repository/eventsourcing/eventstore/auth_request_test.go b/internal/auth/repository/eventsourcing/eventstore/auth_request_test.go index 803c28bbbe..b7de857595 100644 --- a/internal/auth/repository/eventsourcing/eventstore/auth_request_test.go +++ b/internal/auth/repository/eventsourcing/eventstore/auth_request_test.go @@ -15,7 +15,6 @@ import ( "github.com/caos/zitadel/internal/domain" "github.com/caos/zitadel/internal/errors" es_models "github.com/caos/zitadel/internal/eventstore/v1/models" - iam_view_model "github.com/caos/zitadel/internal/iam/repository/view/model" proj_view_model "github.com/caos/zitadel/internal/project/repository/view/model" "github.com/caos/zitadel/internal/query" user_model "github.com/caos/zitadel/internal/user/model" @@ -151,10 +150,10 @@ func (m *mockLoginPolicy) LoginPolicyByID(ctx context.Context, id string) (*quer } type mockLockoutPolicy struct { - policy *iam_view_model.LockoutPolicyView + policy *query.LockoutPolicy } -func (m *mockLockoutPolicy) LockoutPolicyByAggregateID(id string) (*iam_view_model.LockoutPolicyView, error) { +func (m *mockLockoutPolicy) LockoutPolicyByOrg(context.Context, string) (*query.LockoutPolicy, error) { return m.policy, nil } @@ -438,8 +437,9 @@ func TestAuthRequestRepo_nextSteps(t *testing.T) { }, orgViewProvider: &mockViewOrg{State: domain.OrgStateActive}, lockoutPolicyProvider: &mockLockoutPolicy{ - policy: &iam_view_model.LockoutPolicyView{ - ShowLockOutFailures: true, + policy: &query.LockoutPolicy{ + + ShowFailures: true, }, }, }, @@ -459,8 +459,8 @@ func TestAuthRequestRepo_nextSteps(t *testing.T) { }, orgViewProvider: &mockViewOrg{State: domain.OrgStateActive}, lockoutPolicyProvider: &mockLockoutPolicy{ - policy: &iam_view_model.LockoutPolicyView{ - ShowLockOutFailures: true, + policy: &query.LockoutPolicy{ + ShowFailures: true, }, }, }, @@ -475,8 +475,8 @@ func TestAuthRequestRepo_nextSteps(t *testing.T) { userEventProvider: &mockEventUser{}, orgViewProvider: &mockViewErrOrg{}, lockoutPolicyProvider: &mockLockoutPolicy{ - policy: &iam_view_model.LockoutPolicyView{ - ShowLockOutFailures: true, + policy: &query.LockoutPolicy{ + ShowFailures: true, }, }, }, @@ -491,8 +491,8 @@ func TestAuthRequestRepo_nextSteps(t *testing.T) { userEventProvider: &mockEventUser{}, orgViewProvider: &mockViewOrg{State: domain.OrgStateInactive}, lockoutPolicyProvider: &mockLockoutPolicy{ - policy: &iam_view_model.LockoutPolicyView{ - ShowLockOutFailures: true, + policy: &query.LockoutPolicy{ + ShowFailures: true, }, }, }, @@ -510,8 +510,8 @@ func TestAuthRequestRepo_nextSteps(t *testing.T) { userEventProvider: &mockEventUser{}, orgViewProvider: &mockViewOrg{State: domain.OrgStateActive}, lockoutPolicyProvider: &mockLockoutPolicy{ - policy: &iam_view_model.LockoutPolicyView{ - ShowLockOutFailures: true, + policy: &query.LockoutPolicy{ + ShowFailures: true, }, }, }, @@ -527,8 +527,8 @@ func TestAuthRequestRepo_nextSteps(t *testing.T) { userEventProvider: &mockEventUser{}, orgViewProvider: &mockViewOrg{State: domain.OrgStateActive}, lockoutPolicyProvider: &mockLockoutPolicy{ - policy: &iam_view_model.LockoutPolicyView{ - ShowLockOutFailures: true, + policy: &query.LockoutPolicy{ + ShowFailures: true, }, }, }, @@ -547,8 +547,8 @@ func TestAuthRequestRepo_nextSteps(t *testing.T) { userEventProvider: &mockEventUser{}, orgViewProvider: &mockViewOrg{State: domain.OrgStateActive}, lockoutPolicyProvider: &mockLockoutPolicy{ - policy: &iam_view_model.LockoutPolicyView{ - ShowLockOutFailures: true, + policy: &query.LockoutPolicy{ + ShowFailures: true, }, }, }, @@ -569,8 +569,8 @@ func TestAuthRequestRepo_nextSteps(t *testing.T) { orgViewProvider: &mockViewOrg{State: domain.OrgStateActive}, MultiFactorCheckLifeTime: 10 * time.Hour, lockoutPolicyProvider: &mockLockoutPolicy{ - policy: &iam_view_model.LockoutPolicyView{ - ShowLockOutFailures: true, + policy: &query.LockoutPolicy{ + ShowFailures: true, }, }, }, @@ -588,8 +588,8 @@ func TestAuthRequestRepo_nextSteps(t *testing.T) { userEventProvider: &mockEventUser{}, orgViewProvider: &mockViewOrg{State: domain.OrgStateActive}, lockoutPolicyProvider: &mockLockoutPolicy{ - policy: &iam_view_model.LockoutPolicyView{ - ShowLockOutFailures: true, + policy: &query.LockoutPolicy{ + ShowFailures: true, }, }, MultiFactorCheckLifeTime: 10 * time.Hour, @@ -609,8 +609,8 @@ func TestAuthRequestRepo_nextSteps(t *testing.T) { userEventProvider: &mockEventUser{}, orgViewProvider: &mockViewOrg{State: domain.OrgStateActive}, lockoutPolicyProvider: &mockLockoutPolicy{ - policy: &iam_view_model.LockoutPolicyView{ - ShowLockOutFailures: true, + policy: &query.LockoutPolicy{ + ShowFailures: true, }, }, MultiFactorCheckLifeTime: 10 * time.Hour, @@ -635,8 +635,8 @@ func TestAuthRequestRepo_nextSteps(t *testing.T) { }, userEventProvider: &mockEventUser{}, lockoutPolicyProvider: &mockLockoutPolicy{ - policy: &iam_view_model.LockoutPolicyView{ - ShowLockOutFailures: true, + policy: &query.LockoutPolicy{ + ShowFailures: true, }, }, orgViewProvider: &mockViewOrg{State: domain.OrgStateActive}, @@ -661,8 +661,8 @@ func TestAuthRequestRepo_nextSteps(t *testing.T) { }, userEventProvider: &mockEventUser{}, lockoutPolicyProvider: &mockLockoutPolicy{ - policy: &iam_view_model.LockoutPolicyView{ - ShowLockOutFailures: true, + policy: &query.LockoutPolicy{ + ShowFailures: true, }, }, orgViewProvider: &mockViewOrg{State: domain.OrgStateActive}, @@ -683,8 +683,8 @@ func TestAuthRequestRepo_nextSteps(t *testing.T) { }, userEventProvider: &mockEventUser{}, lockoutPolicyProvider: &mockLockoutPolicy{ - policy: &iam_view_model.LockoutPolicyView{ - ShowLockOutFailures: true, + policy: &query.LockoutPolicy{ + ShowFailures: true, }, }, orgViewProvider: &mockViewOrg{State: domain.OrgStateActive}, @@ -713,8 +713,8 @@ func TestAuthRequestRepo_nextSteps(t *testing.T) { policy: &query.LoginPolicy{}, }, lockoutPolicyProvider: &mockLockoutPolicy{ - policy: &iam_view_model.LockoutPolicyView{ - ShowLockOutFailures: true, + policy: &query.LockoutPolicy{ + ShowFailures: true, }, }, ExternalLoginCheckLifeTime: 10 * 24 * time.Hour, @@ -741,8 +741,8 @@ func TestAuthRequestRepo_nextSteps(t *testing.T) { userEventProvider: &mockEventUser{}, orgViewProvider: &mockViewOrg{State: domain.OrgStateActive}, lockoutPolicyProvider: &mockLockoutPolicy{ - policy: &iam_view_model.LockoutPolicyView{ - ShowLockOutFailures: true, + policy: &query.LockoutPolicy{ + ShowFailures: true, }, }, PasswordCheckLifeTime: 10 * 24 * time.Hour, @@ -768,8 +768,8 @@ func TestAuthRequestRepo_nextSteps(t *testing.T) { userGrantProvider: &mockUserGrants{}, projectProvider: &mockProject{}, lockoutPolicyProvider: &mockLockoutPolicy{ - policy: &iam_view_model.LockoutPolicyView{ - ShowLockOutFailures: true, + policy: &query.LockoutPolicy{ + ShowFailures: true, }, }, SecondFactorCheckLifeTime: 18 * time.Hour, @@ -800,8 +800,8 @@ func TestAuthRequestRepo_nextSteps(t *testing.T) { userEventProvider: &mockEventUser{}, orgViewProvider: &mockViewOrg{State: domain.OrgStateActive}, lockoutPolicyProvider: &mockLockoutPolicy{ - policy: &iam_view_model.LockoutPolicyView{ - ShowLockOutFailures: true, + policy: &query.LockoutPolicy{ + ShowFailures: true, }, }, PasswordCheckLifeTime: 10 * 24 * time.Hour, @@ -833,8 +833,8 @@ func TestAuthRequestRepo_nextSteps(t *testing.T) { userEventProvider: &mockEventUser{}, orgViewProvider: &mockViewOrg{State: domain.OrgStateActive}, lockoutPolicyProvider: &mockLockoutPolicy{ - policy: &iam_view_model.LockoutPolicyView{ - ShowLockOutFailures: true, + policy: &query.LockoutPolicy{ + ShowFailures: true, }, }, PasswordCheckLifeTime: 10 * 24 * time.Hour, @@ -867,8 +867,8 @@ func TestAuthRequestRepo_nextSteps(t *testing.T) { userEventProvider: &mockEventUser{}, orgViewProvider: &mockViewOrg{State: domain.OrgStateActive}, lockoutPolicyProvider: &mockLockoutPolicy{ - policy: &iam_view_model.LockoutPolicyView{ - ShowLockOutFailures: true, + policy: &query.LockoutPolicy{ + ShowFailures: true, }, }, PasswordCheckLifeTime: 10 * 24 * time.Hour, @@ -904,8 +904,8 @@ func TestAuthRequestRepo_nextSteps(t *testing.T) { userEventProvider: &mockEventUser{}, orgViewProvider: &mockViewOrg{State: domain.OrgStateActive}, lockoutPolicyProvider: &mockLockoutPolicy{ - policy: &iam_view_model.LockoutPolicyView{ - ShowLockOutFailures: true, + policy: &query.LockoutPolicy{ + ShowFailures: true, }, }, PasswordCheckLifeTime: 10 * 24 * time.Hour, @@ -935,8 +935,8 @@ func TestAuthRequestRepo_nextSteps(t *testing.T) { userEventProvider: &mockEventUser{}, orgViewProvider: &mockViewOrg{State: domain.OrgStateActive}, lockoutPolicyProvider: &mockLockoutPolicy{ - policy: &iam_view_model.LockoutPolicyView{ - ShowLockOutFailures: true, + policy: &query.LockoutPolicy{ + ShowFailures: true, }, }, PasswordCheckLifeTime: 10 * 24 * time.Hour, @@ -966,8 +966,8 @@ func TestAuthRequestRepo_nextSteps(t *testing.T) { userEventProvider: &mockEventUser{}, orgViewProvider: &mockViewOrg{State: domain.OrgStateActive}, lockoutPolicyProvider: &mockLockoutPolicy{ - policy: &iam_view_model.LockoutPolicyView{ - ShowLockOutFailures: true, + policy: &query.LockoutPolicy{ + ShowFailures: true, }, }, PasswordCheckLifeTime: 10 * 24 * time.Hour, @@ -999,8 +999,8 @@ func TestAuthRequestRepo_nextSteps(t *testing.T) { userGrantProvider: &mockUserGrants{}, projectProvider: &mockProject{}, lockoutPolicyProvider: &mockLockoutPolicy{ - policy: &iam_view_model.LockoutPolicyView{ - ShowLockOutFailures: true, + policy: &query.LockoutPolicy{ + ShowFailures: true, }, }, PasswordCheckLifeTime: 10 * 24 * time.Hour, @@ -1033,8 +1033,8 @@ func TestAuthRequestRepo_nextSteps(t *testing.T) { userGrantProvider: &mockUserGrants{}, projectProvider: &mockProject{}, lockoutPolicyProvider: &mockLockoutPolicy{ - policy: &iam_view_model.LockoutPolicyView{ - ShowLockOutFailures: true, + policy: &query.LockoutPolicy{ + ShowFailures: true, }, }, PasswordCheckLifeTime: 10 * 24 * time.Hour, @@ -1071,8 +1071,8 @@ func TestAuthRequestRepo_nextSteps(t *testing.T) { }, projectProvider: &mockProject{}, lockoutPolicyProvider: &mockLockoutPolicy{ - policy: &iam_view_model.LockoutPolicyView{ - ShowLockOutFailures: true, + policy: &query.LockoutPolicy{ + ShowFailures: true, }, }, PasswordCheckLifeTime: 10 * 24 * time.Hour, @@ -1109,8 +1109,8 @@ func TestAuthRequestRepo_nextSteps(t *testing.T) { }, projectProvider: &mockProject{}, lockoutPolicyProvider: &mockLockoutPolicy{ - policy: &iam_view_model.LockoutPolicyView{ - ShowLockOutFailures: true, + policy: &query.LockoutPolicy{ + ShowFailures: true, }, }, PasswordCheckLifeTime: 10 * 24 * time.Hour, @@ -1147,8 +1147,8 @@ func TestAuthRequestRepo_nextSteps(t *testing.T) { hasProject: false, }, lockoutPolicyProvider: &mockLockoutPolicy{ - policy: &iam_view_model.LockoutPolicyView{ - ShowLockOutFailures: true, + policy: &query.LockoutPolicy{ + ShowFailures: true, }, }, PasswordCheckLifeTime: 10 * 24 * time.Hour, @@ -1185,8 +1185,8 @@ func TestAuthRequestRepo_nextSteps(t *testing.T) { hasProject: true, }, lockoutPolicyProvider: &mockLockoutPolicy{ - policy: &iam_view_model.LockoutPolicyView{ - ShowLockOutFailures: true, + policy: &query.LockoutPolicy{ + ShowFailures: true, }, }, PasswordCheckLifeTime: 10 * 24 * time.Hour, @@ -1215,8 +1215,8 @@ func TestAuthRequestRepo_nextSteps(t *testing.T) { MFAMaxSetUp: int32(model.MFALevelSecondFactor), }, lockoutPolicyProvider: &mockLockoutPolicy{ - policy: &iam_view_model.LockoutPolicyView{ - ShowLockOutFailures: true, + policy: &query.LockoutPolicy{ + ShowFailures: true, }, }, userEventProvider: &mockEventUser{}, @@ -1248,8 +1248,8 @@ func TestAuthRequestRepo_nextSteps(t *testing.T) { userEventProvider: &mockEventUser{}, orgViewProvider: &mockViewOrg{State: domain.OrgStateActive}, lockoutPolicyProvider: &mockLockoutPolicy{ - policy: &iam_view_model.LockoutPolicyView{ - ShowLockOutFailures: true, + policy: &query.LockoutPolicy{ + ShowFailures: true, }, }, SecondFactorCheckLifeTime: 18 * time.Hour, diff --git a/internal/auth/repository/eventsourcing/handler/handler.go b/internal/auth/repository/eventsourcing/handler/handler.go index d51fd66018..6dd70c71f5 100644 --- a/internal/auth/repository/eventsourcing/handler/handler.go +++ b/internal/auth/repository/eventsourcing/handler/handler.go @@ -67,7 +67,6 @@ func Register(configs Configs, bulkLimit, errorCount uint64, view *view.View, es newPrivacyPolicy(handler{view, bulkLimit, configs.cycleDuration("PrivacyPolicy"), errorCount, es}), newCustomText(handler{view, bulkLimit, configs.cycleDuration("CustomTexts"), errorCount, es}), newMetadata(handler{view, bulkLimit, configs.cycleDuration("Metadata"), errorCount, es}), - newLockoutPolicy(handler{view, bulkLimit, configs.cycleDuration("LockoutPolicy"), errorCount, es}), newOrgProjectMapping(handler{view, bulkLimit, configs.cycleDuration("OrgProjectMapping"), errorCount, es}), } } diff --git a/internal/auth/repository/eventsourcing/handler/lockout_policy.go b/internal/auth/repository/eventsourcing/handler/lockout_policy.go deleted file mode 100644 index f4fb37cac4..0000000000 --- a/internal/auth/repository/eventsourcing/handler/lockout_policy.go +++ /dev/null @@ -1,110 +0,0 @@ -package handler - -import ( - "github.com/caos/logging" - "github.com/caos/zitadel/internal/eventstore/v1" - - es_models "github.com/caos/zitadel/internal/eventstore/v1/models" - "github.com/caos/zitadel/internal/eventstore/v1/query" - "github.com/caos/zitadel/internal/eventstore/v1/spooler" - iam_es_model "github.com/caos/zitadel/internal/iam/repository/eventsourcing/model" - iam_model "github.com/caos/zitadel/internal/iam/repository/view/model" - org_es_model "github.com/caos/zitadel/internal/org/repository/eventsourcing/model" -) - -const ( - lockoutPolicyTable = "auth.lockout_policies" -) - -type LockoutPolicy struct { - handler - subscription *v1.Subscription -} - -func newLockoutPolicy(handler handler) *LockoutPolicy { - h := &LockoutPolicy{ - handler: handler, - } - - h.subscribe() - - return h -} - -func (p *LockoutPolicy) subscribe() { - p.subscription = p.es.Subscribe(p.AggregateTypes()...) - go func() { - for event := range p.subscription.Events { - query.ReduceEvent(p, event) - } - }() -} - -func (p *LockoutPolicy) ViewModel() string { - return lockoutPolicyTable -} - -func (p *LockoutPolicy) Subscription() *v1.Subscription { - return p.subscription -} - -func (_ *LockoutPolicy) AggregateTypes() []es_models.AggregateType { - return []es_models.AggregateType{org_es_model.OrgAggregate, iam_es_model.IAMAggregate} -} - -func (p *LockoutPolicy) CurrentSequence() (uint64, error) { - sequence, err := p.view.GetLatestLockoutPolicySequence() - if err != nil { - return 0, err - } - return sequence.CurrentSequence, nil -} - -func (p *LockoutPolicy) EventQuery() (*es_models.SearchQuery, error) { - sequence, err := p.view.GetLatestLockoutPolicySequence() - if err != nil { - return nil, err - } - return es_models.NewSearchQuery(). - AggregateTypeFilter(p.AggregateTypes()...). - LatestSequenceFilter(sequence.CurrentSequence), nil -} - -func (p *LockoutPolicy) Reduce(event *es_models.Event) (err error) { - switch event.AggregateType { - case org_es_model.OrgAggregate, iam_es_model.IAMAggregate: - err = p.processLockoutPolicy(event) - } - return err -} - -func (p *LockoutPolicy) processLockoutPolicy(event *es_models.Event) (err error) { - policy := new(iam_model.LockoutPolicyView) - switch event.Type { - case iam_es_model.LockoutPolicyAdded, org_es_model.LockoutPolicyAdded: - err = policy.AppendEvent(event) - case iam_es_model.LockoutPolicyChanged, org_es_model.LockoutPolicyChanged: - policy, err = p.view.LockoutPolicyByAggregateID(event.AggregateID) - if err != nil { - return err - } - err = policy.AppendEvent(event) - case org_es_model.LockoutPolicyRemoved: - return p.view.DeleteLockoutPolicy(event.AggregateID, event) - default: - return p.view.ProcessedLockoutPolicySequence(event) - } - if err != nil { - return err - } - return p.view.PutLockoutPolicy(policy, event) -} - -func (p *LockoutPolicy) OnError(event *es_models.Event, err error) error { - logging.LogWithFields("SPOOL-0pos2", "id", event.AggregateID).WithError(err).Warn("something went wrong in passwordLockout policy handler") - return spooler.HandleError(event, err, p.view.GetLatestLockoutPolicyFailedEvent, p.view.ProcessedLockoutPolicyFailedEvent, p.view.ProcessedLockoutPolicySequence, p.errorCountUntilSkip) -} - -func (p *LockoutPolicy) OnSuccess() error { - return spooler.HandleSuccess(p.view.UpdateLockoutPolicySpoolerRunTimestamp) -} diff --git a/internal/auth/repository/eventsourcing/repository.go b/internal/auth/repository/eventsourcing/repository.go index aee8fba363..63dd6569aa 100644 --- a/internal/auth/repository/eventsourcing/repository.go +++ b/internal/auth/repository/eventsourcing/repository.go @@ -108,8 +108,8 @@ func Start(conf Config, authZ authz.Config, systemDefaults sd.SystemDefaults, co UserCommandProvider: command, UserEventProvider: &userRepo, IDPProviderViewProvider: view, + LockoutPolicyViewProvider: queries, LoginPolicyViewProvider: queries, - LockoutPolicyViewProvider: view, UserGrantProvider: view, ProjectProvider: view, IdGenerator: idGenerator, diff --git a/internal/auth/repository/eventsourcing/view/lockout_policy.go b/internal/auth/repository/eventsourcing/view/lockout_policy.go deleted file mode 100644 index de914bbd60..0000000000 --- a/internal/auth/repository/eventsourcing/view/lockout_policy.go +++ /dev/null @@ -1,53 +0,0 @@ -package view - -import ( - "github.com/caos/zitadel/internal/errors" - "github.com/caos/zitadel/internal/eventstore/v1/models" - "github.com/caos/zitadel/internal/iam/repository/view" - "github.com/caos/zitadel/internal/iam/repository/view/model" - global_view "github.com/caos/zitadel/internal/view/repository" -) - -const ( - passwordLockoutPolicyTable = "auth.lockout_policies" -) - -func (v *View) LockoutPolicyByAggregateID(aggregateID string) (*model.LockoutPolicyView, error) { - return view.GetLockoutPolicyByAggregateID(v.Db, passwordLockoutPolicyTable, aggregateID) -} - -func (v *View) PutLockoutPolicy(policy *model.LockoutPolicyView, event *models.Event) error { - err := view.PutLockoutPolicy(v.Db, passwordLockoutPolicyTable, policy) - if err != nil { - return err - } - return v.ProcessedLockoutPolicySequence(event) -} - -func (v *View) DeleteLockoutPolicy(aggregateID string, event *models.Event) error { - err := view.DeleteLockoutPolicy(v.Db, passwordLockoutPolicyTable, aggregateID) - if err != nil && !errors.IsNotFound(err) { - return err - } - return v.ProcessedLockoutPolicySequence(event) -} - -func (v *View) GetLatestLockoutPolicySequence() (*global_view.CurrentSequence, error) { - return v.latestSequence(passwordLockoutPolicyTable) -} - -func (v *View) ProcessedLockoutPolicySequence(event *models.Event) error { - return v.saveCurrentSequence(passwordLockoutPolicyTable, event) -} - -func (v *View) UpdateLockoutPolicySpoolerRunTimestamp() error { - return v.updateSpoolerRunSequence(passwordLockoutPolicyTable) -} - -func (v *View) GetLatestLockoutPolicyFailedEvent(sequence uint64) (*global_view.FailedEvent, error) { - return v.latestFailedEvent(passwordLockoutPolicyTable, sequence) -} - -func (v *View) ProcessedLockoutPolicyFailedEvent(failedEvent *global_view.FailedEvent) error { - return v.saveFailedEvent(failedEvent) -} diff --git a/internal/command/org_policy_lockout.go b/internal/command/org_policy_lockout.go index 8daccf7522..e38cb36f51 100644 --- a/internal/command/org_policy_lockout.go +++ b/internal/command/org_policy_lockout.go @@ -2,6 +2,7 @@ package command import ( "context" + "github.com/caos/zitadel/internal/domain" caos_errs "github.com/caos/zitadel/internal/errors" "github.com/caos/zitadel/internal/repository/org" diff --git a/internal/command/user_human_password.go b/internal/command/user_human_password.go index 4d502b141f..7d0ff8c8e7 100644 --- a/internal/command/user_human_password.go +++ b/internal/command/user_human_password.go @@ -2,6 +2,7 @@ package command import ( "context" + "github.com/caos/logging" "github.com/caos/zitadel/internal/crypto" "github.com/caos/zitadel/internal/domain" diff --git a/internal/iam/repository/view/model/password_lockout_policy.go b/internal/iam/repository/view/model/password_lockout_policy.go deleted file mode 100644 index 14405298bb..0000000000 --- a/internal/iam/repository/view/model/password_lockout_policy.go +++ /dev/null @@ -1,84 +0,0 @@ -package model - -import ( - "encoding/json" - "github.com/caos/zitadel/internal/domain" - org_es_model "github.com/caos/zitadel/internal/org/repository/eventsourcing/model" - "time" - - es_model "github.com/caos/zitadel/internal/iam/repository/eventsourcing/model" - - "github.com/caos/logging" - caos_errs "github.com/caos/zitadel/internal/errors" - "github.com/caos/zitadel/internal/eventstore/v1/models" - "github.com/caos/zitadel/internal/iam/model" -) - -const ( - LockoutKeyAggregateID = "aggregate_id" -) - -type LockoutPolicyView struct { - AggregateID string `json:"-" gorm:"column:aggregate_id;primary_key"` - CreationDate time.Time `json:"-" gorm:"column:creation_date"` - ChangeDate time.Time `json:"-" gorm:"column:change_date"` - State int32 `json:"-" gorm:"column:lockout_policy_state"` - - MaxPasswordAttempts uint64 `json:"maxPasswordAttempts" gorm:"column:max_password_attempts"` - ShowLockOutFailures bool `json:"showLockOutFailures" gorm:"column:show_lockout_failures"` - Default bool `json:"-" gorm:"-"` - - Sequence uint64 `json:"-" gorm:"column:sequence"` -} - -func LockoutViewToModel(policy *LockoutPolicyView) *model.LockoutPolicyView { - return &model.LockoutPolicyView{ - AggregateID: policy.AggregateID, - Sequence: policy.Sequence, - CreationDate: policy.CreationDate, - ChangeDate: policy.ChangeDate, - MaxPasswordAttempts: policy.MaxPasswordAttempts, - ShowLockOutFailures: policy.ShowLockOutFailures, - Default: policy.Default, - } -} - -func (p *LockoutPolicyView) ToDomain() *domain.LockoutPolicy { - return &domain.LockoutPolicy{ - ObjectRoot: models.ObjectRoot{ - AggregateID: p.AggregateID, - CreationDate: p.CreationDate, - ChangeDate: p.ChangeDate, - Sequence: p.Sequence, - }, - MaxPasswordAttempts: p.MaxPasswordAttempts, - ShowLockOutFailures: p.ShowLockOutFailures, - Default: p.Default, - } -} - -func (i *LockoutPolicyView) AppendEvent(event *models.Event) (err error) { - i.Sequence = event.Sequence - i.ChangeDate = event.CreationDate - switch event.Type { - case es_model.LockoutPolicyAdded, org_es_model.LockoutPolicyAdded: - i.setRootData(event) - i.CreationDate = event.CreationDate - err = i.SetData(event) - case es_model.LockoutPolicyChanged, org_es_model.LockoutPolicyChanged: - err = i.SetData(event) - } - return err -} - -func (r *LockoutPolicyView) setRootData(event *models.Event) { - r.AggregateID = event.AggregateID -} - -func (r *LockoutPolicyView) SetData(event *models.Event) error { - if err := json.Unmarshal(event.Data, r); err != nil { - logging.Log("EVEN-gHls0").WithError(err).Error("could not unmarshal event data") - return caos_errs.ThrowInternal(err, "MODEL-Hs8uf", "Could not unmarshal data") - } - return nil -} diff --git a/internal/iam/repository/view/model/password_lockout_policy_query.go b/internal/iam/repository/view/model/password_lockout_policy_query.go deleted file mode 100644 index f99b0c715a..0000000000 --- a/internal/iam/repository/view/model/password_lockout_policy_query.go +++ /dev/null @@ -1,59 +0,0 @@ -package model - -import ( - "github.com/caos/zitadel/internal/domain" - iam_model "github.com/caos/zitadel/internal/iam/model" - "github.com/caos/zitadel/internal/view/repository" -) - -type LockoutPolicySearchRequest iam_model.LockoutPolicySearchRequest -type LockoutPolicySearchQuery iam_model.LockoutPolicySearchQuery -type LockoutPolicySearchKey iam_model.LockoutPolicySearchKey - -func (req LockoutPolicySearchRequest) GetLimit() uint64 { - return req.Limit -} - -func (req LockoutPolicySearchRequest) GetOffset() uint64 { - return req.Offset -} - -func (req LockoutPolicySearchRequest) GetSortingColumn() repository.ColumnKey { - if req.SortingColumn == iam_model.LockoutPolicySearchKeyUnspecified { - return nil - } - return LockoutPolicySearchKey(req.SortingColumn) -} - -func (req LockoutPolicySearchRequest) GetAsc() bool { - return req.Asc -} - -func (req LockoutPolicySearchRequest) GetQueries() []repository.SearchQuery { - result := make([]repository.SearchQuery, len(req.Queries)) - for i, q := range req.Queries { - result[i] = LockoutPolicySearchQuery{Key: q.Key, Value: q.Value, Method: q.Method} - } - return result -} - -func (req LockoutPolicySearchQuery) GetKey() repository.ColumnKey { - return LockoutPolicySearchKey(req.Key) -} - -func (req LockoutPolicySearchQuery) GetMethod() domain.SearchMethod { - return req.Method -} - -func (req LockoutPolicySearchQuery) GetValue() interface{} { - return req.Value -} - -func (key LockoutPolicySearchKey) ToColumnName() string { - switch iam_model.LockoutPolicySearchKey(key) { - case iam_model.LockoutPolicySearchKeyAggregateID: - return LockoutKeyAggregateID - default: - return "" - } -} diff --git a/internal/iam/repository/view/password_lockout_policy_view.go b/internal/iam/repository/view/password_lockout_policy_view.go deleted file mode 100644 index 9625914841..0000000000 --- a/internal/iam/repository/view/password_lockout_policy_view.go +++ /dev/null @@ -1,32 +0,0 @@ -package view - -import ( - "github.com/caos/zitadel/internal/domain" - caos_errs "github.com/caos/zitadel/internal/errors" - iam_model "github.com/caos/zitadel/internal/iam/model" - "github.com/caos/zitadel/internal/iam/repository/view/model" - "github.com/caos/zitadel/internal/view/repository" - "github.com/jinzhu/gorm" -) - -func GetLockoutPolicyByAggregateID(db *gorm.DB, table, aggregateID string) (*model.LockoutPolicyView, error) { - policy := new(model.LockoutPolicyView) - aggregateIDQuery := &model.LockoutPolicySearchQuery{Key: iam_model.LockoutPolicySearchKeyAggregateID, Value: aggregateID, Method: domain.SearchMethodEquals} - query := repository.PrepareGetByQuery(table, aggregateIDQuery) - err := query(db, policy) - if caos_errs.IsNotFound(err) { - return nil, caos_errs.ThrowNotFound(nil, "VIEW-M9fsf", "Errors.IAM.LockoutPolicy.NotExisting") - } - return policy, err -} - -func PutLockoutPolicy(db *gorm.DB, table string, policy *model.LockoutPolicyView) error { - save := repository.PrepareSave(table) - return save(db, policy) -} - -func DeleteLockoutPolicy(db *gorm.DB, table, aggregateID string) error { - delete := repository.PrepareDeleteByKey(table, model.LockoutPolicySearchKey(iam_model.LockoutPolicySearchKeyAggregateID), aggregateID) - - return delete(db) -} diff --git a/internal/management/repository/eventsourcing/eventstore/org.go b/internal/management/repository/eventsourcing/eventstore/org.go index 01909b1f34..60dd178135 100644 --- a/internal/management/repository/eventsourcing/eventstore/org.go +++ b/internal/management/repository/eventsourcing/eventstore/org.go @@ -285,57 +285,6 @@ func (repo *OrgRepository) SearchIDPProviders(ctx context.Context, request *iam_ return result, nil } -func (repo *OrgRepository) GetLockoutPolicy(ctx context.Context) (*iam_model.LockoutPolicyView, error) { - policy, viewErr := repo.View.LockoutPolicyByAggregateID(authz.GetCtxData(ctx).OrgID) - if viewErr != nil && !errors.IsNotFound(viewErr) { - return nil, viewErr - } - if errors.IsNotFound(viewErr) { - policy = new(iam_view_model.LockoutPolicyView) - } - events, esErr := repo.getOrgEvents(ctx, repo.SystemDefaults.IamID, policy.Sequence) - if errors.IsNotFound(viewErr) && len(events) == 0 { - return repo.GetDefaultLockoutPolicy(ctx) - } - if esErr != nil { - logging.Log("EVENT-mS9od").WithError(esErr).Debug("error retrieving new events") - return iam_view_model.LockoutViewToModel(policy), nil - } - policyCopy := *policy - for _, event := range events { - if err := policyCopy.AppendEvent(event); err != nil { - return iam_view_model.LockoutViewToModel(policy), nil - } - } - return iam_view_model.LockoutViewToModel(policy), nil -} - -func (repo *OrgRepository) GetDefaultLockoutPolicy(ctx context.Context) (*iam_model.LockoutPolicyView, error) { - policy, viewErr := repo.View.LockoutPolicyByAggregateID(repo.SystemDefaults.IamID) - if viewErr != nil && !errors.IsNotFound(viewErr) { - return nil, viewErr - } - if errors.IsNotFound(viewErr) { - policy = new(iam_view_model.LockoutPolicyView) - } - events, esErr := repo.getIAMEvents(ctx, policy.Sequence) - if errors.IsNotFound(viewErr) && len(events) == 0 { - return nil, errors.ThrowNotFound(nil, "EVENT-cmO9s", "Errors.IAM.LockoutPolicy.NotFound") - } - if esErr != nil { - logging.Log("EVENT-2Ms9f").WithError(esErr).Debug("error retrieving new events") - return iam_view_model.LockoutViewToModel(policy), nil - } - policyCopy := *policy - for _, event := range events { - if err := policyCopy.AppendEvent(event); err != nil { - return iam_view_model.LockoutViewToModel(policy), nil - } - } - policy.Default = true - return iam_view_model.LockoutViewToModel(policy), nil -} - func (repo *OrgRepository) GetPrivacyPolicy(ctx context.Context) (*iam_model.PrivacyPolicyView, error) { policy, err := repo.View.PrivacyPolicyByAggregateID(authz.GetCtxData(ctx).OrgID) if errors.IsNotFound(err) { diff --git a/internal/management/repository/eventsourcing/handler/handler.go b/internal/management/repository/eventsourcing/handler/handler.go index 43c947c1bf..5bf9facc1d 100644 --- a/internal/management/repository/eventsourcing/handler/handler.go +++ b/internal/management/repository/eventsourcing/handler/handler.go @@ -57,8 +57,6 @@ func Register(configs Configs, bulkLimit, errorCount uint64, view *view.View, es newExternalIDP( handler{view, bulkLimit, configs.cycleDuration("ExternalIDP"), errorCount, es}, defaults), - newLockoutPolicy( - handler{view, bulkLimit, configs.cycleDuration("LockoutPolicy"), errorCount, es}), newOrgIAMPolicy( handler{view, bulkLimit, configs.cycleDuration("OrgIAMPolicy"), errorCount, es}), newMailTemplate( diff --git a/internal/management/repository/eventsourcing/handler/password_lockout_policy.go b/internal/management/repository/eventsourcing/handler/password_lockout_policy.go deleted file mode 100644 index acd59dfb8d..0000000000 --- a/internal/management/repository/eventsourcing/handler/password_lockout_policy.go +++ /dev/null @@ -1,110 +0,0 @@ -package handler - -import ( - "github.com/caos/logging" - "github.com/caos/zitadel/internal/eventstore/v1" - iam_es_model "github.com/caos/zitadel/internal/iam/repository/eventsourcing/model" - - es_models "github.com/caos/zitadel/internal/eventstore/v1/models" - "github.com/caos/zitadel/internal/eventstore/v1/query" - "github.com/caos/zitadel/internal/eventstore/v1/spooler" - iam_model "github.com/caos/zitadel/internal/iam/repository/view/model" - "github.com/caos/zitadel/internal/org/repository/eventsourcing/model" -) - -const ( - lockoutPolicyTable = "management.lockout_policies" -) - -type LockoutPolicy struct { - handler - subscription *v1.Subscription -} - -func newLockoutPolicy(handler handler) *LockoutPolicy { - h := &LockoutPolicy{ - handler: handler, - } - - h.subscribe() - - return h -} - -func (m *LockoutPolicy) subscribe() { - m.subscription = m.es.Subscribe(m.AggregateTypes()...) - go func() { - for event := range m.subscription.Events { - query.ReduceEvent(m, event) - } - }() -} - -func (p *LockoutPolicy) ViewModel() string { - return lockoutPolicyTable -} - -func (p *LockoutPolicy) Subscription() *v1.Subscription { - return p.subscription -} - -func (_ *LockoutPolicy) AggregateTypes() []es_models.AggregateType { - return []es_models.AggregateType{model.OrgAggregate, iam_es_model.IAMAggregate} -} - -func (p *LockoutPolicy) CurrentSequence() (uint64, error) { - sequence, err := p.view.GetLatestLockoutPolicySequence() - if err != nil { - return 0, err - } - return sequence.CurrentSequence, nil -} - -func (p *LockoutPolicy) EventQuery() (*es_models.SearchQuery, error) { - sequence, err := p.view.GetLatestLockoutPolicySequence() - if err != nil { - return nil, err - } - return es_models.NewSearchQuery(). - AggregateTypeFilter(p.AggregateTypes()...). - LatestSequenceFilter(sequence.CurrentSequence), nil -} - -func (p *LockoutPolicy) Reduce(event *es_models.Event) (err error) { - switch event.AggregateType { - case model.OrgAggregate, iam_es_model.IAMAggregate: - err = p.processPasswordLockoutPolicy(event) - } - return err -} - -func (p *LockoutPolicy) processPasswordLockoutPolicy(event *es_models.Event) (err error) { - policy := new(iam_model.LockoutPolicyView) - switch event.Type { - case iam_es_model.LockoutPolicyAdded, model.LockoutPolicyAdded: - err = policy.AppendEvent(event) - case iam_es_model.LockoutPolicyChanged, model.LockoutPolicyChanged: - policy, err = p.view.LockoutPolicyByAggregateID(event.AggregateID) - if err != nil { - return err - } - err = policy.AppendEvent(event) - case model.LockoutPolicyRemoved: - return p.view.DeleteLockoutPolicy(event.AggregateID, event) - default: - return p.view.ProcessedLockoutPolicySequence(event) - } - if err != nil { - return err - } - return p.view.PutLockoutPolicy(policy, event) -} - -func (p *LockoutPolicy) OnError(event *es_models.Event, err error) error { - logging.LogWithFields("SPOOL-Bms8f", "id", event.AggregateID).WithError(err).Warn("something went wrong in passwordLockout policy handler") - return spooler.HandleError(event, err, p.view.GetLatestLockoutPolicyFailedEvent, p.view.ProcessedLockoutPolicyFailedEvent, p.view.ProcessedLockoutPolicySequence, p.errorCountUntilSkip) -} - -func (p *LockoutPolicy) OnSuccess() error { - return spooler.HandleSuccess(p.view.UpdateLockoutPolicySpoolerRunTimestamp) -} diff --git a/internal/management/repository/eventsourcing/view/lockout_policy.go b/internal/management/repository/eventsourcing/view/lockout_policy.go deleted file mode 100644 index 04f8419fe0..0000000000 --- a/internal/management/repository/eventsourcing/view/lockout_policy.go +++ /dev/null @@ -1,53 +0,0 @@ -package view - -import ( - "github.com/caos/zitadel/internal/errors" - "github.com/caos/zitadel/internal/eventstore/v1/models" - "github.com/caos/zitadel/internal/iam/repository/view" - "github.com/caos/zitadel/internal/iam/repository/view/model" - global_view "github.com/caos/zitadel/internal/view/repository" -) - -const ( - lockoutPolicyTable = "management.lockout_policies" -) - -func (v *View) LockoutPolicyByAggregateID(aggregateID string) (*model.LockoutPolicyView, error) { - return view.GetLockoutPolicyByAggregateID(v.Db, lockoutPolicyTable, aggregateID) -} - -func (v *View) PutLockoutPolicy(policy *model.LockoutPolicyView, event *models.Event) error { - err := view.PutLockoutPolicy(v.Db, lockoutPolicyTable, policy) - if err != nil { - return err - } - return v.ProcessedLockoutPolicySequence(event) -} - -func (v *View) DeleteLockoutPolicy(aggregateID string, event *models.Event) error { - err := view.DeleteLockoutPolicy(v.Db, lockoutPolicyTable, aggregateID) - if err != nil && !errors.IsNotFound(err) { - return err - } - return v.ProcessedLockoutPolicySequence(event) -} - -func (v *View) GetLatestLockoutPolicySequence() (*global_view.CurrentSequence, error) { - return v.latestSequence(lockoutPolicyTable) -} - -func (v *View) ProcessedLockoutPolicySequence(event *models.Event) error { - return v.saveCurrentSequence(lockoutPolicyTable, event) -} - -func (v *View) UpdateLockoutPolicySpoolerRunTimestamp() error { - return v.updateSpoolerRunSequence(lockoutPolicyTable) -} - -func (v *View) GetLatestLockoutPolicyFailedEvent(sequence uint64) (*global_view.FailedEvent, error) { - return v.latestFailedEvent(lockoutPolicyTable, sequence) -} - -func (v *View) ProcessedLockoutPolicyFailedEvent(failedEvent *global_view.FailedEvent) error { - return v.saveFailedEvent(failedEvent) -} diff --git a/internal/management/repository/org.go b/internal/management/repository/org.go index 6cb6d5a9fb..eed1451d72 100644 --- a/internal/management/repository/org.go +++ b/internal/management/repository/org.go @@ -28,9 +28,6 @@ type OrgRepository interface { SearchIDPProviders(ctx context.Context, request *iam_model.IDPProviderSearchRequest) (*iam_model.IDPProviderSearchResponse, error) GetIDPProvidersByIDPConfigID(ctx context.Context, aggregateID, idpConfigID string) ([]*iam_model.IDPProviderView, error) - GetLockoutPolicy(ctx context.Context) (*iam_model.LockoutPolicyView, error) - GetDefaultLockoutPolicy(ctx context.Context) (*iam_model.LockoutPolicyView, error) - GetPrivacyPolicy(ctx context.Context) (*iam_model.PrivacyPolicyView, error) GetDefaultPrivacyPolicy(ctx context.Context) (*iam_model.PrivacyPolicyView, error) diff --git a/internal/query/lockout_policy.go b/internal/query/lockout_policy.go new file mode 100644 index 0000000000..bbdbba35e6 --- /dev/null +++ b/internal/query/lockout_policy.go @@ -0,0 +1,125 @@ +package query + +import ( + "context" + "database/sql" + errs "errors" + "time" + + sq "github.com/Masterminds/squirrel" + "github.com/caos/zitadel/internal/errors" + "github.com/caos/zitadel/internal/query/projection" +) + +type LockoutPolicy struct { + ID string + Sequence uint64 + CreationDate time.Time + ChangeDate time.Time + ResourceOwner string + + MaxPasswordAttempts uint64 + ShowFailures bool + + IsDefault bool +} + +var ( + lockoutTable = table{ + name: projection.LockoutPolicyTable, + } + LockoutColID = Column{ + name: projection.LockoutPolicyIDCol, + } + LockoutColSequence = Column{ + name: projection.LockoutPolicySequenceCol, + } + LockoutColCreationDate = Column{ + name: projection.LockoutPolicyCreationDateCol, + } + LockoutColChangeDate = Column{ + name: projection.LockoutPolicyChangeDateCol, + } + LockoutColResourceOwner = Column{ + name: projection.LockoutPolicyResourceOwnerCol, + } + LockoutColShowFailures = Column{ + name: projection.LockoutPolicyShowLockOutFailuresCol, + } + LockoutColMaxPasswordAttempts = Column{ + name: projection.LockoutPolicyMaxPasswordAttemptsCol, + } + LockoutColIsDefault = Column{ + name: projection.LockoutPolicyIsDefaultCol, + } +) + +func (q *Queries) LockoutPolicyByOrg(ctx context.Context, orgID string) (*LockoutPolicy, error) { + stmt, scan := prepareLockoutPolicyQuery() + query, args, err := stmt.Where( + sq.Or{ + sq.Eq{ + LockoutColID.identifier(): orgID, + }, + sq.Eq{ + LockoutColID.identifier(): q.iamID, + }, + }). + OrderBy(LockoutColIsDefault.identifier()). + Limit(1).ToSql() + if err != nil { + return nil, errors.ThrowInternal(err, "QUERY-SKR6X", "Errors.Query.SQLStatement") + } + + row := q.client.QueryRowContext(ctx, query, args...) + return scan(row) +} + +func (q *Queries) DefaultLockoutPolicy(ctx context.Context) (*LockoutPolicy, error) { + stmt, scan := prepareLockoutPolicyQuery() + query, args, err := stmt.Where(sq.Eq{ + LockoutColID.identifier(): q.iamID, + }). + OrderBy(LockoutColIsDefault.identifier()). + Limit(1).ToSql() + if err != nil { + return nil, errors.ThrowInternal(err, "QUERY-mN0Ci", "Errors.Query.SQLStatement") + } + + row := q.client.QueryRowContext(ctx, query, args...) + return scan(row) +} + +func prepareLockoutPolicyQuery() (sq.SelectBuilder, func(*sql.Row) (*LockoutPolicy, error)) { + return sq.Select( + LockoutColID.identifier(), + LockoutColSequence.identifier(), + LockoutColCreationDate.identifier(), + LockoutColChangeDate.identifier(), + LockoutColResourceOwner.identifier(), + LockoutColShowFailures.identifier(), + LockoutColMaxPasswordAttempts.identifier(), + LockoutColIsDefault.identifier(), + ). + From(lockoutTable.identifier()).PlaceholderFormat(sq.Dollar), + func(row *sql.Row) (*LockoutPolicy, error) { + policy := new(LockoutPolicy) + err := row.Scan( + &policy.ID, + &policy.Sequence, + &policy.CreationDate, + &policy.ChangeDate, + &policy.ResourceOwner, + &policy.ShowFailures, + &policy.MaxPasswordAttempts, + &policy.IsDefault, + ) + if err != nil { + if errs.Is(err, sql.ErrNoRows) { + return nil, errors.ThrowNotFound(err, "QUERY-63mtI", "Errors.PasswordComplexityPolicy.NotFound") + } + return nil, errors.ThrowInternal(err, "QUERY-uulCZ", "Errors.Internal") + } + return policy, nil + } +} diff --git a/internal/query/projection/lockout_policy.go b/internal/query/projection/lockout_policy.go new file mode 100644 index 0000000000..9a25a86c3c --- /dev/null +++ b/internal/query/projection/lockout_policy.go @@ -0,0 +1,147 @@ +package projection + +import ( + "context" + + "github.com/caos/logging" + "github.com/caos/zitadel/internal/domain" + "github.com/caos/zitadel/internal/errors" + "github.com/caos/zitadel/internal/eventstore" + "github.com/caos/zitadel/internal/eventstore/handler" + "github.com/caos/zitadel/internal/eventstore/handler/crdb" + "github.com/caos/zitadel/internal/repository/iam" + "github.com/caos/zitadel/internal/repository/org" + "github.com/caos/zitadel/internal/repository/policy" +) + +type LockoutPolicyProjection struct { + crdb.StatementHandler +} + +const ( + LockoutPolicyTable = "zitadel.projections.lockout_policies" + + LockoutPolicyCreationDateCol = "creation_date" + LockoutPolicyChangeDateCol = "change_date" + LockoutPolicySequenceCol = "sequence" + LockoutPolicyIDCol = "id" + LockoutPolicyStateCol = "state" + LockoutPolicyMaxPasswordAttemptsCol = "max_password_attempts" + LockoutPolicyShowLockOutFailuresCol = "show_failure" + LockoutPolicyIsDefaultCol = "is_default" + LockoutPolicyResourceOwnerCol = "resource_owner" +) + +func NewLockoutPolicyProjection(ctx context.Context, config crdb.StatementHandlerConfig) *LockoutPolicyProjection { + p := &LockoutPolicyProjection{} + config.ProjectionName = LockoutPolicyTable + config.Reducers = p.reducers() + p.StatementHandler = crdb.NewStatementHandler(ctx, config) + return p +} + +func (p *LockoutPolicyProjection) reducers() []handler.AggregateReducer { + return []handler.AggregateReducer{ + { + Aggregate: org.AggregateType, + EventRedusers: []handler.EventReducer{ + { + Event: org.LockoutPolicyAddedEventType, + Reduce: p.reduceAdded, + }, + { + Event: org.LockoutPolicyChangedEventType, + Reduce: p.reduceChanged, + }, + { + Event: org.LockoutPolicyRemovedEventType, + Reduce: p.reduceRemoved, + }, + }, + }, + { + Aggregate: iam.AggregateType, + EventRedusers: []handler.EventReducer{ + { + Event: iam.LockoutPolicyAddedEventType, + Reduce: p.reduceAdded, + }, + { + Event: iam.LockoutPolicyChangedEventType, + Reduce: p.reduceChanged, + }, + }, + }, + } +} + +func (p *LockoutPolicyProjection) reduceAdded(event eventstore.EventReader) (*handler.Statement, error) { + var policyEvent policy.LockoutPolicyAddedEvent + var isDefault bool + switch e := event.(type) { + case *org.LockoutPolicyAddedEvent: + policyEvent = e.LockoutPolicyAddedEvent + isDefault = false + case *iam.LockoutPolicyAddedEvent: + policyEvent = e.LockoutPolicyAddedEvent + isDefault = true + default: + logging.LogWithFields("PROJE-uFqFM", "seq", event.Sequence(), "expectedTypes", []eventstore.EventType{org.LockoutPolicyAddedEventType, iam.LockoutPolicyAddedEventType}).Error("wrong event type") + return nil, errors.ThrowInvalidArgument(nil, "PROJE-d8mZO", "reduce.wrong.event.type") + } + return crdb.NewCreateStatement( + &policyEvent, + []handler.Column{ + handler.NewCol(LockoutPolicyCreationDateCol, policyEvent.CreationDate()), + handler.NewCol(LockoutPolicyChangeDateCol, policyEvent.CreationDate()), + handler.NewCol(LockoutPolicySequenceCol, policyEvent.Sequence()), + handler.NewCol(LockoutPolicyIDCol, policyEvent.Aggregate().ID), + handler.NewCol(LockoutPolicyStateCol, domain.PolicyStateActive), + handler.NewCol(LockoutPolicyMaxPasswordAttemptsCol, policyEvent.MaxPasswordAttempts), + handler.NewCol(LockoutPolicyShowLockOutFailuresCol, policyEvent.ShowLockOutFailures), + handler.NewCol(LockoutPolicyIsDefaultCol, isDefault), + handler.NewCol(LockoutPolicyResourceOwnerCol, policyEvent.Aggregate().ResourceOwner), + }), nil +} + +func (p *LockoutPolicyProjection) reduceChanged(event eventstore.EventReader) (*handler.Statement, error) { + var policyEvent policy.LockoutPolicyChangedEvent + switch e := event.(type) { + case *org.LockoutPolicyChangedEvent: + policyEvent = e.LockoutPolicyChangedEvent + case *iam.LockoutPolicyChangedEvent: + policyEvent = e.LockoutPolicyChangedEvent + default: + logging.LogWithFields("PROJE-iIkej", "seq", event.Sequence(), "expectedTypes", []eventstore.EventType{org.LockoutPolicyChangedEventType, iam.LockoutPolicyChangedEventType}).Error("wrong event type") + return nil, errors.ThrowInvalidArgument(nil, "PROJE-pT3mQ", "reduce.wrong.event.type") + } + cols := []handler.Column{ + handler.NewCol(LockoutPolicyChangeDateCol, policyEvent.CreationDate()), + handler.NewCol(LockoutPolicySequenceCol, policyEvent.Sequence()), + } + if policyEvent.MaxPasswordAttempts != nil { + cols = append(cols, handler.NewCol(LockoutPolicyMaxPasswordAttemptsCol, *policyEvent.MaxPasswordAttempts)) + } + if policyEvent.ShowLockOutFailures != nil { + cols = append(cols, handler.NewCol(LockoutPolicyShowLockOutFailuresCol, *policyEvent.ShowLockOutFailures)) + } + return crdb.NewUpdateStatement( + &policyEvent, + cols, + []handler.Condition{ + handler.NewCond(LockoutPolicyIDCol, policyEvent.Aggregate().ID), + }), nil +} + +func (p *LockoutPolicyProjection) reduceRemoved(event eventstore.EventReader) (*handler.Statement, error) { + policyEvent, ok := event.(*org.LockoutPolicyRemovedEvent) + if !ok { + logging.LogWithFields("PROJE-U5cys", "seq", event.Sequence(), "expectedType", org.LockoutPolicyRemovedEventType).Error("wrong event type") + return nil, errors.ThrowInvalidArgument(nil, "PROJE-Bqut9", "reduce.wrong.event.type") + } + return crdb.NewDeleteStatement( + policyEvent, + []handler.Condition{ + handler.NewCond(LockoutPolicyIDCol, policyEvent.Aggregate().ID), + }), nil +} diff --git a/internal/query/projection/lockout_policy_test.go b/internal/query/projection/lockout_policy_test.go new file mode 100644 index 0000000000..27013e5aba --- /dev/null +++ b/internal/query/projection/lockout_policy_test.go @@ -0,0 +1,210 @@ +package projection + +import ( + "testing" + + "github.com/caos/zitadel/internal/domain" + "github.com/caos/zitadel/internal/errors" + "github.com/caos/zitadel/internal/eventstore" + "github.com/caos/zitadel/internal/eventstore/handler" + "github.com/caos/zitadel/internal/eventstore/repository" + "github.com/caos/zitadel/internal/repository/iam" + "github.com/caos/zitadel/internal/repository/org" +) + +func TestLockoutPolicyProjection_reduces(t *testing.T) { + type args struct { + event func(t *testing.T) eventstore.EventReader + } + tests := []struct { + name string + args args + reduce func(event eventstore.EventReader) (*handler.Statement, error) + want wantReduce + }{ + { + name: "org.reduceAdded", + args: args{ + event: getEvent(testEvent( + repository.EventType(org.LockoutPolicyAddedEventType), + org.AggregateType, + []byte(`{ + "maxPasswordAttempts": 10, + "showLockOutFailures": true +}`), + ), org.LockoutPolicyAddedEventMapper), + }, + reduce: (&LockoutPolicyProjection{}).reduceAdded, + want: wantReduce{ + aggregateType: eventstore.AggregateType("org"), + sequence: 15, + previousSequence: 10, + projection: LockoutPolicyTable, + executer: &testExecuter{ + executions: []execution{ + { + expectedStmt: "INSERT INTO zitadel.projections.lockout_policies (creation_date, change_date, sequence, id, state, max_password_attempts, show_failure, is_default, resource_owner) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)", + expectedArgs: []interface{}{ + anyArg{}, + anyArg{}, + uint64(15), + "agg-id", + domain.PolicyStateActive, + uint64(10), + true, + false, + "ro-id", + }, + }, + }, + }, + }, + }, + { + name: "org.reduceChanged", + reduce: (&LockoutPolicyProjection{}).reduceChanged, + args: args{ + event: getEvent(testEvent( + repository.EventType(org.LockoutPolicyChangedEventType), + org.AggregateType, + []byte(`{ + "maxPasswordAttempts": 10, + "showLockOutFailures": true + }`), + ), org.LockoutPolicyChangedEventMapper), + }, + want: wantReduce{ + aggregateType: eventstore.AggregateType("org"), + sequence: 15, + previousSequence: 10, + projection: LockoutPolicyTable, + executer: &testExecuter{ + executions: []execution{ + { + expectedStmt: "UPDATE zitadel.projections.lockout_policies SET (change_date, sequence, max_password_attempts, show_failure) = ($1, $2, $3, $4) WHERE (id = $5)", + expectedArgs: []interface{}{ + anyArg{}, + uint64(15), + uint64(10), + true, + "agg-id", + }, + }, + }, + }, + }, + }, + { + name: "org.reduceRemoved", + reduce: (&LockoutPolicyProjection{}).reduceRemoved, + args: args{ + event: getEvent(testEvent( + repository.EventType(org.LockoutPolicyRemovedEventType), + org.AggregateType, + nil, + ), org.LockoutPolicyRemovedEventMapper), + }, + want: wantReduce{ + aggregateType: eventstore.AggregateType("org"), + sequence: 15, + previousSequence: 10, + projection: LockoutPolicyTable, + executer: &testExecuter{ + executions: []execution{ + { + expectedStmt: "DELETE FROM zitadel.projections.lockout_policies WHERE (id = $1)", + expectedArgs: []interface{}{ + "agg-id", + }, + }, + }, + }, + }, + }, + { + name: "iam.reduceAdded", + reduce: (&LockoutPolicyProjection{}).reduceAdded, + args: args{ + event: getEvent(testEvent( + repository.EventType(iam.LockoutPolicyAddedEventType), + iam.AggregateType, + []byte(`{ + "maxPasswordAttempts": 10, + "showLockOutFailures": true + }`), + ), iam.LockoutPolicyAddedEventMapper), + }, + want: wantReduce{ + aggregateType: eventstore.AggregateType("iam"), + sequence: 15, + previousSequence: 10, + projection: LockoutPolicyTable, + executer: &testExecuter{ + executions: []execution{ + { + expectedStmt: "INSERT INTO zitadel.projections.lockout_policies (creation_date, change_date, sequence, id, state, max_password_attempts, show_failure, is_default, resource_owner) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)", + expectedArgs: []interface{}{ + anyArg{}, + anyArg{}, + uint64(15), + "agg-id", + domain.PolicyStateActive, + uint64(10), + true, + true, + "ro-id", + }, + }, + }, + }, + }, + }, + { + name: "iam.reduceChanged", + reduce: (&LockoutPolicyProjection{}).reduceChanged, + args: args{ + event: getEvent(testEvent( + repository.EventType(iam.LockoutPolicyChangedEventType), + iam.AggregateType, + []byte(`{ + "maxPasswordAttempts": 10, + "showLockOutFailures": true + }`), + ), iam.LockoutPolicyChangedEventMapper), + }, + want: wantReduce{ + aggregateType: eventstore.AggregateType("iam"), + sequence: 15, + previousSequence: 10, + projection: LockoutPolicyTable, + executer: &testExecuter{ + executions: []execution{ + { + expectedStmt: "UPDATE zitadel.projections.lockout_policies SET (change_date, sequence, max_password_attempts, show_failure) = ($1, $2, $3, $4) WHERE (id = $5)", + expectedArgs: []interface{}{ + anyArg{}, + uint64(15), + uint64(10), + true, + "agg-id", + }, + }, + }, + }, + }, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + event := baseEvent(t) + got, err := tt.reduce(event) + if _, ok := err.(errors.InvalidArgument); !ok { + t.Errorf("no wrong event mapping: %v, got: %v", err, got) + } + + event = tt.args.event(t) + got, err = tt.reduce(event) + assertReduce(t, got, err, tt.want) + }) + } +} diff --git a/internal/query/projection/projection.go b/internal/query/projection/projection.go index a03c62af49..68805d0f28 100644 --- a/internal/query/projection/projection.go +++ b/internal/query/projection/projection.go @@ -39,6 +39,7 @@ func Start(ctx context.Context, sqlClient *sql.DB, es *eventstore.Eventstore, co NewProjectProjection(ctx, applyCustomConfig(projectionConfig, config.Customizations["projects"])) NewPasswordComplexityProjection(ctx, applyCustomConfig(projectionConfig, config.Customizations["password_complexities"])) NewPasswordAgeProjection(ctx, applyCustomConfig(projectionConfig, config.Customizations["password_age_policy"])) + NewLockoutPolicyProjection(ctx, applyCustomConfig(projectionConfig, config.Customizations["lockout_policy"])) NewProjectGrantProjection(ctx, applyCustomConfig(projectionConfig, config.Customizations["project_grants"])) NewProjectRoleProjection(ctx, applyCustomConfig(projectionConfig, config.Customizations["project_roles"])) // owner.NewOrgOwnerProjection(ctx, applyCustomConfig(projectionConfig, config.Customizations["org_owners"])) diff --git a/migrations/cockroach/V1.82__lockout_policy.sql b/migrations/cockroach/V1.82__lockout_policy.sql new file mode 100644 index 0000000000..2cb36fa0c2 --- /dev/null +++ b/migrations/cockroach/V1.82__lockout_policy.sql @@ -0,0 +1,14 @@ +CREATE TABLE zitadel.projections.lockout_policies ( + id STRING NOT NULL, + creation_date TIMESTAMPTZ NULL, + change_date TIMESTAMPTZ NULL, + sequence INT8 NULL, + state INT2 NULL, + resource_owner TEXT, + + is_default BOOLEAN, + max_password_attempts INT8 NULL, + show_failure BOOLEAN NULL, + + PRIMARY KEY (id) +); \ No newline at end of file