diff --git a/internal/admin/repository/eventsourcing/eventstore/iam.go b/internal/admin/repository/eventsourcing/eventstore/iam.go index bce9615978..55f0ded240 100644 --- a/internal/admin/repository/eventsourcing/eventstore/iam.go +++ b/internal/admin/repository/eventsourcing/eventstore/iam.go @@ -272,33 +272,6 @@ func (repo *IAMRepository) GetCustomMessageText(ctx context.Context, textType, l return result, err } -func (repo *IAMRepository) GetDefaultPrivacyPolicy(ctx context.Context) (*iam_model.PrivacyPolicyView, error) { - policy, viewErr := repo.View.PrivacyPolicyByAggregateID(repo.SystemDefaults.IamID) - if viewErr != nil && !caos_errs.IsNotFound(viewErr) { - return nil, viewErr - } - if caos_errs.IsNotFound(viewErr) { - policy = new(iam_es_model.PrivacyPolicyView) - } - events, esErr := repo.getIAMEvents(ctx, policy.Sequence) - if caos_errs.IsNotFound(viewErr) && len(events) == 0 { - return nil, caos_errs.ThrowNotFound(nil, "EVENT-84Nfs", "Errors.IAM.PrivacyPolicy.NotFound") - } - if esErr != nil { - logging.Log("EVENT-0p3Fs").WithError(esErr).Debug("error retrieving new events") - return iam_es_model.PrivacyViewToModel(policy), nil - } - policyCopy := *policy - for _, event := range events { - if err := policyCopy.AppendEvent(event); err != nil { - return iam_es_model.PrivacyViewToModel(policy), nil - } - } - result := iam_es_model.PrivacyViewToModel(policy) - result.Default = true - return result, nil -} - func (repo *IAMRepository) GetDefaultLoginTexts(ctx context.Context, lang string) (*domain.CustomLoginText, error) { repo.mutex.Lock() defer repo.mutex.Unlock() diff --git a/internal/admin/repository/eventsourcing/handler/handler.go b/internal/admin/repository/eventsourcing/handler/handler.go index 0da373db01..b0da90badd 100644 --- a/internal/admin/repository/eventsourcing/handler/handler.go +++ b/internal/admin/repository/eventsourcing/handler/handler.go @@ -56,8 +56,6 @@ func Register(configs Configs, bulkLimit, errorCount uint64, view *view.View, es handler{view, bulkLimit, configs.cycleDuration("MessageText"), errorCount, es}), newFeatures( handler{view, bulkLimit, configs.cycleDuration("Features"), errorCount, es}), - newPrivacyPolicy( - handler{view, bulkLimit, configs.cycleDuration("PrivacyPolicy"), errorCount, es}), newCustomText( handler{view, bulkLimit, configs.cycleDuration("CustomTexts"), errorCount, es}), } diff --git a/internal/admin/repository/eventsourcing/handler/privacy_policy.go b/internal/admin/repository/eventsourcing/handler/privacy_policy.go deleted file mode 100644 index 0b842eb7ed..0000000000 --- a/internal/admin/repository/eventsourcing/handler/privacy_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 ( - privacyPolicyTable = "adminapi.privacy_policies" -) - -type PrivacyPolicy struct { - handler - subscription *v1.Subscription -} - -func newPrivacyPolicy(handler handler) *PrivacyPolicy { - h := &PrivacyPolicy{ - handler: handler, - } - - h.subscribe() - - return h -} - -func (p *PrivacyPolicy) subscribe() { - p.subscription = p.es.Subscribe(p.AggregateTypes()...) - go func() { - for event := range p.subscription.Events { - query.ReduceEvent(p, event) - } - }() -} - -func (p *PrivacyPolicy) ViewModel() string { - return privacyPolicyTable -} - -func (p *PrivacyPolicy) Subscription() *v1.Subscription { - return p.subscription -} - -func (p *PrivacyPolicy) AggregateTypes() []es_models.AggregateType { - return []es_models.AggregateType{model.OrgAggregate, iam_es_model.IAMAggregate} -} - -func (p *PrivacyPolicy) CurrentSequence() (uint64, error) { - sequence, err := p.view.GetLatestPrivacyPolicySequence() - if err != nil { - return 0, err - } - return sequence.CurrentSequence, nil -} - -func (p *PrivacyPolicy) EventQuery() (*es_models.SearchQuery, error) { - sequence, err := p.view.GetLatestPrivacyPolicySequence() - if err != nil { - return nil, err - } - return es_models.NewSearchQuery(). - AggregateTypeFilter(p.AggregateTypes()...). - LatestSequenceFilter(sequence.CurrentSequence), nil -} - -func (p *PrivacyPolicy) Reduce(event *es_models.Event) (err error) { - switch event.AggregateType { - case model.OrgAggregate, iam_es_model.IAMAggregate: - err = p.processPrivacyPolicy(event) - } - return err -} - -func (p *PrivacyPolicy) processPrivacyPolicy(event *es_models.Event) (err error) { - policy := new(iam_model.PrivacyPolicyView) - switch event.Type { - case iam_es_model.PrivacyPolicyAdded, model.PrivacyPolicyAdded: - err = policy.AppendEvent(event) - case iam_es_model.PrivacyPolicyChanged, model.PrivacyPolicyChanged: - policy, err = p.view.PrivacyPolicyByAggregateID(event.AggregateID) - if err != nil { - return err - } - err = policy.AppendEvent(event) - case model.PrivacyPolicyRemoved: - return p.view.DeletePrivacyPolicy(event.AggregateID, event) - default: - return p.view.ProcessedPrivacyPolicySequence(event) - } - if err != nil { - return err - } - return p.view.PutPrivacyPolicy(policy, event) -} - -func (p *PrivacyPolicy) OnError(event *es_models.Event, err error) error { - logging.LogWithFields("SPOOL-4N8sw", "id", event.AggregateID).WithError(err).Warn("something went wrong in privacy policy handler") - return spooler.HandleError(event, err, p.view.GetLatestPrivacyPolicyFailedEvent, p.view.ProcessedPrivacyPolicyFailedEvent, p.view.ProcessedPrivacyPolicySequence, p.errorCountUntilSkip) -} - -func (p *PrivacyPolicy) OnSuccess() error { - return spooler.HandleSuccess(p.view.UpdatePrivacyPolicySpoolerRunTimestamp) -} diff --git a/internal/admin/repository/eventsourcing/view/privacy_policy.go b/internal/admin/repository/eventsourcing/view/privacy_policy.go deleted file mode 100644 index 8f3eded17f..0000000000 --- a/internal/admin/repository/eventsourcing/view/privacy_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 ( - privacyPolicyTable = "adminapi.privacy_policies" -) - -func (v *View) PrivacyPolicyByAggregateID(aggregateID string) (*model.PrivacyPolicyView, error) { - return view.GetPrivacyPolicyByAggregateID(v.Db, privacyPolicyTable, aggregateID) -} - -func (v *View) PutPrivacyPolicy(policy *model.PrivacyPolicyView, event *models.Event) error { - err := view.PutPrivacyPolicy(v.Db, privacyPolicyTable, policy) - if err != nil { - return err - } - return v.ProcessedPrivacyPolicySequence(event) -} - -func (v *View) DeletePrivacyPolicy(aggregateID string, event *models.Event) error { - err := view.DeletePrivacyPolicy(v.Db, privacyPolicyTable, aggregateID) - if err != nil && !errors.IsNotFound(err) { - return err - } - return v.ProcessedPrivacyPolicySequence(event) -} - -func (v *View) GetLatestPrivacyPolicySequence() (*global_view.CurrentSequence, error) { - return v.latestSequence(privacyPolicyTable) -} - -func (v *View) ProcessedPrivacyPolicySequence(event *models.Event) error { - return v.saveCurrentSequence(privacyPolicyTable, event) -} - -func (v *View) UpdatePrivacyPolicySpoolerRunTimestamp() error { - return v.updateSpoolerRunSequence(privacyPolicyTable) -} - -func (v *View) GetLatestPrivacyPolicyFailedEvent(sequence uint64) (*global_view.FailedEvent, error) { - return v.latestFailedEvent(privacyPolicyTable, sequence) -} - -func (v *View) ProcessedPrivacyPolicyFailedEvent(failedEvent *global_view.FailedEvent) error { - return v.saveFailedEvent(failedEvent) -} diff --git a/internal/admin/repository/iam.go b/internal/admin/repository/iam.go index b204e58cb4..a0d6a9e6d9 100644 --- a/internal/admin/repository/iam.go +++ b/internal/admin/repository/iam.go @@ -35,7 +35,5 @@ type IAMRepository interface { GetDefaultLoginTexts(ctx context.Context, lang string) (*domain.CustomLoginText, error) GetCustomLoginTexts(ctx context.Context, lang string) (*domain.CustomLoginText, error) - GetDefaultPrivacyPolicy(ctx context.Context) (*iam_model.PrivacyPolicyView, error) - GetDefaultOrgIAMPolicy(ctx context.Context) (*iam_model.OrgIAMPolicyView, error) } diff --git a/internal/api/grpc/admin/privacy_policy.go b/internal/api/grpc/admin/privacy_policy.go index 95497edf70..03670ae0a0 100644 --- a/internal/api/grpc/admin/privacy_policy.go +++ b/internal/api/grpc/admin/privacy_policy.go @@ -9,7 +9,7 @@ import ( ) func (s *Server) GetPrivacyPolicy(ctx context.Context, _ *admin_pb.GetPrivacyPolicyRequest) (*admin_pb.GetPrivacyPolicyResponse, error) { - policy, err := s.iam.GetDefaultPrivacyPolicy(ctx) + policy, err := s.query.DefaultPrivacyPolicy(ctx) if err != nil { return nil, err } diff --git a/internal/api/grpc/management/policy_privacy.go b/internal/api/grpc/management/policy_privacy.go index 45e0bcb556..1ff36e7b67 100644 --- a/internal/api/grpc/management/policy_privacy.go +++ b/internal/api/grpc/management/policy_privacy.go @@ -10,7 +10,7 @@ import ( ) func (s *Server) GetPrivacyPolicy(ctx context.Context, _ *mgmt_pb.GetPrivacyPolicyRequest) (*mgmt_pb.GetPrivacyPolicyResponse, error) { - policy, err := s.org.GetPrivacyPolicy(ctx) + policy, err := s.query.PrivacyPolicyByOrg(ctx, authz.GetCtxData(ctx).OrgID) if err != nil { return nil, err } @@ -18,7 +18,7 @@ func (s *Server) GetPrivacyPolicy(ctx context.Context, _ *mgmt_pb.GetPrivacyPoli } func (s *Server) GetDefaultPrivacyPolicy(ctx context.Context, _ *mgmt_pb.GetDefaultPrivacyPolicyRequest) (*mgmt_pb.GetDefaultPrivacyPolicyResponse, error) { - policy, err := s.org.GetDefaultPrivacyPolicy(ctx) + policy, err := s.query.DefaultPrivacyPolicy(ctx) if err != nil { return nil, err } diff --git a/internal/api/grpc/policy/privacy_policy.go b/internal/api/grpc/policy/privacy_policy.go index b3816c1bf5..6145668982 100644 --- a/internal/api/grpc/policy/privacy_policy.go +++ b/internal/api/grpc/policy/privacy_policy.go @@ -2,20 +2,20 @@ 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 ModelPrivacyPolicyToPb(policy *model.PrivacyPolicyView) *policy_pb.PrivacyPolicy { +func ModelPrivacyPolicyToPb(policy *query.PrivacyPolicy) *policy_pb.PrivacyPolicy { return &policy_pb.PrivacyPolicy{ - IsDefault: policy.Default, + IsDefault: policy.IsDefault, TosLink: policy.TOSLink, PrivacyLink: policy.PrivacyLink, 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 1b0c83c8b8..5705971343 100644 --- a/internal/auth/repository/eventsourcing/eventstore/auth_request.go +++ b/internal/auth/repository/eventsourcing/eventstore/auth_request.go @@ -20,7 +20,6 @@ import ( "github.com/caos/zitadel/internal/id" project_view_model "github.com/caos/zitadel/internal/project/repository/view/model" "github.com/caos/zitadel/internal/query" - "github.com/caos/zitadel/internal/repository/iam" "github.com/caos/zitadel/internal/telemetry/tracing" user_model "github.com/caos/zitadel/internal/user/model" es_model "github.com/caos/zitadel/internal/user/repository/eventsourcing/model" @@ -41,6 +40,7 @@ type AuthRequestRepo struct { OrgViewProvider orgViewProvider LoginPolicyViewProvider loginPolicyViewProvider LockoutPolicyViewProvider lockoutPolicyViewProvider + PrivacyPolicyProvider privacyPolicyProvider IDPProviderViewProvider idpProviderViewProvider UserGrantProvider userGrantProvider ProjectProvider projectProvider @@ -56,6 +56,10 @@ type AuthRequestRepo struct { IAMID string } +type privacyPolicyProvider interface { + PrivacyPolicyByOrg(context.Context, string) (*query.PrivacyPolicy, error) +} + type userSessionViewProvider interface { UserSessionByIDs(string, string) (*user_view_model.UserSessionView, error) UserSessionsByAgentID(string) ([]*user_view_model.UserSessionView, error) @@ -875,33 +879,27 @@ func (repo *AuthRequestRepo) mfaSkippedOrSetUp(user *user_model.UserView) bool { } func (repo *AuthRequestRepo) getPrivacyPolicy(ctx context.Context, orgID string) (*domain.PrivacyPolicy, error) { - policy, err := repo.View.PrivacyPolicyByAggregateID(orgID) - if errors.IsNotFound(err) { - policy, err = repo.View.PrivacyPolicyByAggregateID(repo.IAMID) - if err != nil && !errors.IsNotFound(err) { - return nil, err - } - if err == nil { - return policy.ToDomain(), nil - } - policy = &iam_view_model.PrivacyPolicyView{} - events, err := repo.Eventstore.FilterEvents(ctx, es_models.NewSearchQuery(). - AggregateIDFilter(repo.IAMID). - AggregateTypeFilter(iam.AggregateType). - EventTypesFilter(es_models.EventType(iam.PrivacyPolicyAddedEventType), es_models.EventType(iam.PrivacyPolicyChangedEventType))) - if err != nil || len(events) == 0 { - return nil, errors.ThrowNotFound(err, "EVENT-GSRqg", "IAM.PrivacyPolicy.NotExisting") - } - policy.Default = true - for _, event := range events { - policy.AppendEvent(event) - } - return policy.ToDomain(), nil - } + policy, err := repo.PrivacyPolicyProvider.PrivacyPolicyByOrg(ctx, orgID) if err != nil { return nil, err } - return policy.ToDomain(), err + return privacyPolicyToDomain(policy), err +} + +func privacyPolicyToDomain(p *query.PrivacyPolicy) *domain.PrivacyPolicy { + return &domain.PrivacyPolicy{ + ObjectRoot: es_models.ObjectRoot{ + AggregateID: p.ID, + Sequence: p.Sequence, + ResourceOwner: p.ResourceOwner, + CreationDate: p.CreationDate, + ChangeDate: p.ChangeDate, + }, + State: p.State, + Default: p.IsDefault, + TOSLink: p.TOSLink, + PrivacyLink: p.PrivacyLink, + } } func (repo *AuthRequestRepo) getLockoutPolicy(ctx context.Context, orgID string) (*query.LockoutPolicy, error) { diff --git a/internal/auth/repository/eventsourcing/eventstore/org.go b/internal/auth/repository/eventsourcing/eventstore/org.go index 6c3e7704eb..27edff2107 100644 --- a/internal/auth/repository/eventsourcing/eventstore/org.go +++ b/internal/auth/repository/eventsourcing/eventstore/org.go @@ -3,8 +3,6 @@ package eventstore import ( "context" - "github.com/caos/logging" - "github.com/caos/zitadel/internal/api/authz" auth_view "github.com/caos/zitadel/internal/auth/repository/eventsourcing/view" "github.com/caos/zitadel/internal/config/systemdefaults" @@ -91,33 +89,6 @@ func (repo *OrgRepository) GetLoginText(ctx context.Context, orgID string) ([]*d return append(iam_view_model.CustomTextViewsToDomain(loginTexts), iam_view_model.CustomTextViewsToDomain(orgLoginTexts)...), nil } -func (repo *OrgRepository) GetDefaultPrivacyPolicy(ctx context.Context) (*iam_model.PrivacyPolicyView, error) { - policy, viewErr := repo.View.PrivacyPolicyByAggregateID(repo.SystemDefaults.IamID) - if viewErr != nil && !errors.IsNotFound(viewErr) { - return nil, viewErr - } - if errors.IsNotFound(viewErr) { - policy = new(iam_view_model.PrivacyPolicyView) - } - events, esErr := repo.getIAMEvents(ctx, policy.Sequence) - if errors.IsNotFound(viewErr) && len(events) == 0 { - return nil, errors.ThrowNotFound(nil, "EVENT-LPJMp", "Errors.IAM.PrivacyPolicy.NotFound") - } - if esErr != nil { - logging.Log("EVENT-1l7bf").WithError(esErr).Debug("error retrieving new events") - return iam_view_model.PrivacyViewToModel(policy), nil - } - policyCopy := *policy - for _, event := range events { - if err := policyCopy.AppendEvent(event); err != nil { - return iam_view_model.PrivacyViewToModel(policy), nil - } - } - result := iam_view_model.PrivacyViewToModel(policy) - result.Default = true - return result, nil -} - func (p *OrgRepository) getIAMEvents(ctx context.Context, sequence uint64) ([]*models.Event, error) { return p.Eventstore.FilterEvents(ctx, models.NewSearchQuery().AggregateIDFilter(p.SystemDefaults.IamID).AggregateTypeFilter(iam.AggregateType)) } diff --git a/internal/auth/repository/eventsourcing/handler/handler.go b/internal/auth/repository/eventsourcing/handler/handler.go index 6dd70c71f5..1d34603c14 100644 --- a/internal/auth/repository/eventsourcing/handler/handler.go +++ b/internal/auth/repository/eventsourcing/handler/handler.go @@ -64,7 +64,6 @@ func Register(configs Configs, bulkLimit, errorCount uint64, view *view.View, es newLabelPolicy(handler{view, bulkLimit, configs.cycleDuration("LabelPolicy"), errorCount, es}), newFeatures(handler{view, bulkLimit, configs.cycleDuration("Features"), errorCount, es}), newRefreshToken(handler{view, bulkLimit, configs.cycleDuration("RefreshToken"), errorCount, 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}), newOrgProjectMapping(handler{view, bulkLimit, configs.cycleDuration("OrgProjectMapping"), errorCount, es}), diff --git a/internal/auth/repository/eventsourcing/handler/privacy_policy.go b/internal/auth/repository/eventsourcing/handler/privacy_policy.go deleted file mode 100644 index 4240f1c1f7..0000000000 --- a/internal/auth/repository/eventsourcing/handler/privacy_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 ( - privacyPolicyTable = "auth.privacy_policies" -) - -type PrivacyPolicy struct { - handler - subscription *v1.Subscription -} - -func newPrivacyPolicy(handler handler) *PrivacyPolicy { - h := &PrivacyPolicy{ - handler: handler, - } - - h.subscribe() - - return h -} - -func (p *PrivacyPolicy) subscribe() { - p.subscription = p.es.Subscribe(p.AggregateTypes()...) - go func() { - for event := range p.subscription.Events { - query.ReduceEvent(p, event) - } - }() -} - -func (p *PrivacyPolicy) ViewModel() string { - return privacyPolicyTable -} - -func (p *PrivacyPolicy) Subscription() *v1.Subscription { - return p.subscription -} - -func (p *PrivacyPolicy) AggregateTypes() []es_models.AggregateType { - return []es_models.AggregateType{model.OrgAggregate, iam_es_model.IAMAggregate} -} - -func (p *PrivacyPolicy) CurrentSequence() (uint64, error) { - sequence, err := p.view.GetLatestPrivacyPolicySequence() - if err != nil { - return 0, err - } - return sequence.CurrentSequence, nil -} - -func (p *PrivacyPolicy) EventQuery() (*es_models.SearchQuery, error) { - sequence, err := p.view.GetLatestPrivacyPolicySequence() - if err != nil { - return nil, err - } - return es_models.NewSearchQuery(). - AggregateTypeFilter(p.AggregateTypes()...). - LatestSequenceFilter(sequence.CurrentSequence), nil -} - -func (p *PrivacyPolicy) Reduce(event *es_models.Event) (err error) { - switch event.AggregateType { - case model.OrgAggregate, iam_es_model.IAMAggregate: - err = p.processPrivacyPolicy(event) - } - return err -} - -func (p *PrivacyPolicy) processPrivacyPolicy(event *es_models.Event) (err error) { - policy := new(iam_model.PrivacyPolicyView) - switch event.Type { - case iam_es_model.PrivacyPolicyAdded, model.PrivacyPolicyAdded: - err = policy.AppendEvent(event) - case iam_es_model.PrivacyPolicyChanged, model.PrivacyPolicyChanged: - policy, err = p.view.PrivacyPolicyByAggregateID(event.AggregateID) - if err != nil { - return err - } - err = policy.AppendEvent(event) - case model.PrivacyPolicyRemoved: - return p.view.DeletePrivacyPolicy(event.AggregateID, event) - default: - return p.view.ProcessedPrivacyPolicySequence(event) - } - if err != nil { - return err - } - return p.view.PutPrivacyPolicy(policy, event) -} - -func (p *PrivacyPolicy) OnError(event *es_models.Event, err error) error { - logging.LogWithFields("SPOOL-4N8sw", "id", event.AggregateID).WithError(err).Warn("something went wrong in privacy policy handler") - return spooler.HandleError(event, err, p.view.GetLatestPrivacyPolicyFailedEvent, p.view.ProcessedPrivacyPolicyFailedEvent, p.view.ProcessedPrivacyPolicySequence, p.errorCountUntilSkip) -} - -func (p *PrivacyPolicy) OnSuccess() error { - return spooler.HandleSuccess(p.view.UpdatePrivacyPolicySpoolerRunTimestamp) -} diff --git a/internal/auth/repository/eventsourcing/view/privacy_policy.go b/internal/auth/repository/eventsourcing/view/privacy_policy.go deleted file mode 100644 index 8a2e921273..0000000000 --- a/internal/auth/repository/eventsourcing/view/privacy_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 ( - privacyPolicyTable = "auth.privacy_policies" -) - -func (v *View) PrivacyPolicyByAggregateID(aggregateID string) (*model.PrivacyPolicyView, error) { - return view.GetPrivacyPolicyByAggregateID(v.Db, privacyPolicyTable, aggregateID) -} - -func (v *View) PutPrivacyPolicy(policy *model.PrivacyPolicyView, event *models.Event) error { - err := view.PutPrivacyPolicy(v.Db, privacyPolicyTable, policy) - if err != nil { - return err - } - return v.ProcessedPrivacyPolicySequence(event) -} - -func (v *View) DeletePrivacyPolicy(aggregateID string, event *models.Event) error { - err := view.DeletePrivacyPolicy(v.Db, privacyPolicyTable, aggregateID) - if err != nil && !errors.IsNotFound(err) { - return err - } - return v.ProcessedPrivacyPolicySequence(event) -} - -func (v *View) GetLatestPrivacyPolicySequence() (*global_view.CurrentSequence, error) { - return v.latestSequence(privacyPolicyTable) -} - -func (v *View) ProcessedPrivacyPolicySequence(event *models.Event) error { - return v.saveCurrentSequence(privacyPolicyTable, event) -} - -func (v *View) UpdatePrivacyPolicySpoolerRunTimestamp() error { - return v.updateSpoolerRunSequence(privacyPolicyTable) -} - -func (v *View) GetLatestPrivacyPolicyFailedEvent(sequence uint64) (*global_view.FailedEvent, error) { - return v.latestFailedEvent(privacyPolicyTable, sequence) -} - -func (v *View) ProcessedPrivacyPolicyFailedEvent(failedEvent *global_view.FailedEvent) error { - return v.saveFailedEvent(failedEvent) -} diff --git a/internal/auth/repository/org.go b/internal/auth/repository/org.go index fce19afe79..4d593be27f 100644 --- a/internal/auth/repository/org.go +++ b/internal/auth/repository/org.go @@ -14,5 +14,4 @@ type OrgRepository interface { GetMyPasswordComplexityPolicy(ctx context.Context) (*iam_model.PasswordComplexityPolicyView, error) GetLabelPolicy(ctx context.Context, orgID string) (*domain.LabelPolicy, error) GetLoginText(ctx context.Context, orgID string) ([]*domain.CustomText, error) - GetDefaultPrivacyPolicy(ctx context.Context) (*iam_model.PrivacyPolicyView, error) } diff --git a/internal/iam/repository/view/model/privacy_policy.go b/internal/iam/repository/view/model/privacy_policy.go deleted file mode 100644 index d66f0af276..0000000000 --- a/internal/iam/repository/view/model/privacy_policy.go +++ /dev/null @@ -1,98 +0,0 @@ -package model - -import ( - "encoding/json" - "time" - - "github.com/caos/zitadel/internal/domain" - org_es_model "github.com/caos/zitadel/internal/org/repository/eventsourcing/model" - - 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 ( - PrivacyKeyAggregateID = "aggregate_id" -) - -type PrivacyPolicyView 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:state"` - - TOSLink string `json:"tosLink" gorm:"column:tos_link"` - PrivacyLink string `json:"privacyLink" gorm:"column:privacy_link"` - Default bool `json:"-" gorm:"-"` - - Sequence uint64 `json:"-" gorm:"column:sequence"` -} - -func PrivacyViewFromModel(policy *model.PrivacyPolicyView) *PrivacyPolicyView { - return &PrivacyPolicyView{ - AggregateID: policy.AggregateID, - Sequence: policy.Sequence, - CreationDate: policy.CreationDate, - ChangeDate: policy.ChangeDate, - TOSLink: policy.TOSLink, - PrivacyLink: policy.PrivacyLink, - Default: policy.Default, - } -} - -func PrivacyViewToModel(policy *PrivacyPolicyView) *model.PrivacyPolicyView { - return &model.PrivacyPolicyView{ - AggregateID: policy.AggregateID, - Sequence: policy.Sequence, - CreationDate: policy.CreationDate, - ChangeDate: policy.ChangeDate, - TOSLink: policy.TOSLink, - PrivacyLink: policy.PrivacyLink, - Default: policy.Default, - } -} - -func (p *PrivacyPolicyView) ToDomain() *domain.PrivacyPolicy { - return &domain.PrivacyPolicy{ - ObjectRoot: models.ObjectRoot{ - AggregateID: p.AggregateID, - CreationDate: p.CreationDate, - ChangeDate: p.ChangeDate, - Sequence: p.Sequence, - }, - Default: p.Default, - TOSLink: p.TOSLink, - PrivacyLink: p.PrivacyLink, - } -} - -func (i *PrivacyPolicyView) AppendEvent(event *models.Event) (err error) { - i.Sequence = event.Sequence - i.ChangeDate = event.CreationDate - switch event.Type { - case es_model.PrivacyPolicyAdded, org_es_model.PrivacyPolicyAdded: - i.setRootData(event) - i.CreationDate = event.CreationDate - err = i.SetData(event) - case es_model.PrivacyPolicyChanged, org_es_model.PrivacyPolicyChanged: - err = i.SetData(event) - } - return err -} - -func (r *PrivacyPolicyView) setRootData(event *models.Event) { - r.AggregateID = event.AggregateID -} - -func (r *PrivacyPolicyView) 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/privacy_policy_query.go b/internal/iam/repository/view/model/privacy_policy_query.go deleted file mode 100644 index b8daf2e93b..0000000000 --- a/internal/iam/repository/view/model/privacy_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 PrivacyPolicySearchRequest iam_model.PrivacyPolicySearchRequest -type PrivacyPolicySearchQuery iam_model.PrivacyPolicySearchQuery -type PrivacyPolicySearchKey iam_model.PrivacyPolicySearchKey - -func (req PrivacyPolicySearchRequest) GetLimit() uint64 { - return req.Limit -} - -func (req PrivacyPolicySearchRequest) GetOffset() uint64 { - return req.Offset -} - -func (req PrivacyPolicySearchRequest) GetSortingColumn() repository.ColumnKey { - if req.SortingColumn == iam_model.PrivacyPolicySearchKeyUnspecified { - return nil - } - return PrivacyPolicySearchKey(req.SortingColumn) -} - -func (req PrivacyPolicySearchRequest) GetAsc() bool { - return req.Asc -} - -func (req PrivacyPolicySearchRequest) GetQueries() []repository.SearchQuery { - result := make([]repository.SearchQuery, len(req.Queries)) - for i, q := range req.Queries { - result[i] = PrivacyPolicySearchQuery{Key: q.Key, Value: q.Value, Method: q.Method} - } - return result -} - -func (req PrivacyPolicySearchQuery) GetKey() repository.ColumnKey { - return PrivacyPolicySearchKey(req.Key) -} - -func (req PrivacyPolicySearchQuery) GetMethod() domain.SearchMethod { - return req.Method -} - -func (req PrivacyPolicySearchQuery) GetValue() interface{} { - return req.Value -} - -func (key PrivacyPolicySearchKey) ToColumnName() string { - switch iam_model.PrivacyPolicySearchKey(key) { - case iam_model.PrivacyPolicySearchKeyAggregateID: - return PrivacyKeyAggregateID - default: - return "" - } -} diff --git a/internal/iam/repository/view/privacy_policy_view.go b/internal/iam/repository/view/privacy_policy_view.go deleted file mode 100644 index e53eea9ee6..0000000000 --- a/internal/iam/repository/view/privacy_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 GetPrivacyPolicyByAggregateID(db *gorm.DB, table, aggregateID string) (*model.PrivacyPolicyView, error) { - policy := new(model.PrivacyPolicyView) - aggregateIDQuery := &model.PrivacyPolicySearchQuery{Key: iam_model.PrivacyPolicySearchKeyAggregateID, 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-2N9fs", "Errors.IAM.PrivacyPolicy.NotExisting") - } - return policy, err -} - -func PutPrivacyPolicy(db *gorm.DB, table string, policy *model.PrivacyPolicyView) error { - save := repository.PrepareSave(table) - return save(db, policy) -} - -func DeletePrivacyPolicy(db *gorm.DB, table, aggregateID string) error { - delete := repository.PrepareDeleteByKey(table, model.PrivacyPolicySearchKey(iam_model.PrivacyPolicySearchKeyAggregateID), aggregateID) - - return delete(db) -} diff --git a/internal/management/repository/eventsourcing/eventstore/org.go b/internal/management/repository/eventsourcing/eventstore/org.go index 60dd178135..0e99c936ad 100644 --- a/internal/management/repository/eventsourcing/eventstore/org.go +++ b/internal/management/repository/eventsourcing/eventstore/org.go @@ -285,23 +285,6 @@ func (repo *OrgRepository) SearchIDPProviders(ctx context.Context, request *iam_ return result, 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) { - return repo.GetDefaultPrivacyPolicy(ctx) - } - return iam_view_model.PrivacyViewToModel(policy), nil -} - -func (repo *OrgRepository) GetDefaultPrivacyPolicy(ctx context.Context) (*iam_model.PrivacyPolicyView, error) { - policy, err := repo.View.PrivacyPolicyByAggregateID(repo.SystemDefaults.IamID) - if err != nil { - return nil, err - } - policy.Default = true - return iam_view_model.PrivacyViewToModel(policy), nil -} - func (repo *OrgRepository) GetDefaultMailTemplate(ctx context.Context) (*iam_model.MailTemplateView, error) { template, err := repo.View.MailTemplateByAggregateID(repo.SystemDefaults.IamID) if err != nil { diff --git a/internal/management/repository/eventsourcing/handler/handler.go b/internal/management/repository/eventsourcing/handler/handler.go index 5bf9facc1d..d8c540581b 100644 --- a/internal/management/repository/eventsourcing/handler/handler.go +++ b/internal/management/repository/eventsourcing/handler/handler.go @@ -65,8 +65,6 @@ func Register(configs Configs, bulkLimit, errorCount uint64, view *view.View, es handler{view, bulkLimit, configs.cycleDuration("MessageText"), errorCount, es}), newFeatures( handler{view, bulkLimit, configs.cycleDuration("Features"), errorCount, es}), - newPrivacyPolicy( - handler{view, bulkLimit, configs.cycleDuration("PrivacyPolicy"), errorCount, es}), newCustomText( handler{view, bulkLimit, configs.cycleDuration("CustomText"), errorCount, es}), newMetadata( diff --git a/internal/management/repository/eventsourcing/handler/privacy_policy.go b/internal/management/repository/eventsourcing/handler/privacy_policy.go deleted file mode 100644 index 382b74d788..0000000000 --- a/internal/management/repository/eventsourcing/handler/privacy_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 ( - privacyPolicyTable = "management.privacy_policies" -) - -type PrivacyPolicy struct { - handler - subscription *v1.Subscription -} - -func newPrivacyPolicy(handler handler) *PrivacyPolicy { - h := &PrivacyPolicy{ - handler: handler, - } - - h.subscribe() - - return h -} - -func (p *PrivacyPolicy) subscribe() { - p.subscription = p.es.Subscribe(p.AggregateTypes()...) - go func() { - for event := range p.subscription.Events { - query.ReduceEvent(p, event) - } - }() -} - -func (p *PrivacyPolicy) ViewModel() string { - return privacyPolicyTable -} - -func (p *PrivacyPolicy) Subscription() *v1.Subscription { - return p.subscription -} - -func (p *PrivacyPolicy) AggregateTypes() []es_models.AggregateType { - return []es_models.AggregateType{model.OrgAggregate, iam_es_model.IAMAggregate} -} - -func (p *PrivacyPolicy) CurrentSequence() (uint64, error) { - sequence, err := p.view.GetLatestPrivacyPolicySequence() - if err != nil { - return 0, err - } - return sequence.CurrentSequence, nil -} - -func (p *PrivacyPolicy) EventQuery() (*es_models.SearchQuery, error) { - sequence, err := p.view.GetLatestPrivacyPolicySequence() - if err != nil { - return nil, err - } - return es_models.NewSearchQuery(). - AggregateTypeFilter(p.AggregateTypes()...). - LatestSequenceFilter(sequence.CurrentSequence), nil -} - -func (p *PrivacyPolicy) Reduce(event *es_models.Event) (err error) { - switch event.AggregateType { - case model.OrgAggregate, iam_es_model.IAMAggregate: - err = p.processPrivacyPolicy(event) - } - return err -} - -func (p *PrivacyPolicy) processPrivacyPolicy(event *es_models.Event) (err error) { - policy := new(iam_model.PrivacyPolicyView) - switch event.Type { - case iam_es_model.PrivacyPolicyAdded, model.PrivacyPolicyAdded: - err = policy.AppendEvent(event) - case iam_es_model.PrivacyPolicyChanged, model.PrivacyPolicyChanged: - policy, err = p.view.PrivacyPolicyByAggregateID(event.AggregateID) - if err != nil { - return err - } - err = policy.AppendEvent(event) - case model.PrivacyPolicyRemoved: - return p.view.DeletePrivacyPolicy(event.AggregateID, event) - default: - return p.view.ProcessedPrivacyPolicySequence(event) - } - if err != nil { - return err - } - return p.view.PutPrivacyPolicy(policy, event) -} - -func (p *PrivacyPolicy) OnError(event *es_models.Event, err error) error { - logging.LogWithFields("SPOOL-4N8sw", "id", event.AggregateID).WithError(err).Warn("something went wrong in privacy policy handler") - return spooler.HandleError(event, err, p.view.GetLatestPrivacyPolicyFailedEvent, p.view.ProcessedPrivacyPolicyFailedEvent, p.view.ProcessedPrivacyPolicySequence, p.errorCountUntilSkip) -} - -func (p *PrivacyPolicy) OnSuccess() error { - return spooler.HandleSuccess(p.view.UpdatePrivacyPolicySpoolerRunTimestamp) -} diff --git a/internal/management/repository/eventsourcing/view/privacy_policy.go b/internal/management/repository/eventsourcing/view/privacy_policy.go deleted file mode 100644 index 5ca5d81707..0000000000 --- a/internal/management/repository/eventsourcing/view/privacy_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 ( - privacyPolicyTable = "management.privacy_policies" -) - -func (v *View) PrivacyPolicyByAggregateID(aggregateID string) (*model.PrivacyPolicyView, error) { - return view.GetPrivacyPolicyByAggregateID(v.Db, privacyPolicyTable, aggregateID) -} - -func (v *View) PutPrivacyPolicy(policy *model.PrivacyPolicyView, event *models.Event) error { - err := view.PutPrivacyPolicy(v.Db, privacyPolicyTable, policy) - if err != nil { - return err - } - return v.ProcessedPrivacyPolicySequence(event) -} - -func (v *View) DeletePrivacyPolicy(aggregateID string, event *models.Event) error { - err := view.DeletePrivacyPolicy(v.Db, privacyPolicyTable, aggregateID) - if err != nil && !errors.IsNotFound(err) { - return err - } - return v.ProcessedPrivacyPolicySequence(event) -} - -func (v *View) GetLatestPrivacyPolicySequence() (*global_view.CurrentSequence, error) { - return v.latestSequence(privacyPolicyTable) -} - -func (v *View) ProcessedPrivacyPolicySequence(event *models.Event) error { - return v.saveCurrentSequence(privacyPolicyTable, event) -} - -func (v *View) UpdatePrivacyPolicySpoolerRunTimestamp() error { - return v.updateSpoolerRunSequence(privacyPolicyTable) -} - -func (v *View) GetLatestPrivacyPolicyFailedEvent(sequence uint64) (*global_view.FailedEvent, error) { - return v.latestFailedEvent(privacyPolicyTable, sequence) -} - -func (v *View) ProcessedPrivacyPolicyFailedEvent(failedEvent *global_view.FailedEvent) error { - return v.saveFailedEvent(failedEvent) -} diff --git a/internal/management/repository/org.go b/internal/management/repository/org.go index eed1451d72..87d9a53f5e 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) - GetPrivacyPolicy(ctx context.Context) (*iam_model.PrivacyPolicyView, error) - GetDefaultPrivacyPolicy(ctx context.Context) (*iam_model.PrivacyPolicyView, error) - GetDefaultMailTemplate(ctx context.Context) (*iam_model.MailTemplateView, error) GetMailTemplate(ctx context.Context) (*iam_model.MailTemplateView, error) diff --git a/internal/query/lockout_policy.go b/internal/query/lockout_policy.go index bbdbba35e6..45f93bcf40 100644 --- a/internal/query/lockout_policy.go +++ b/internal/query/lockout_policy.go @@ -7,6 +7,7 @@ import ( "time" sq "github.com/Masterminds/squirrel" + "github.com/caos/zitadel/internal/domain" "github.com/caos/zitadel/internal/errors" "github.com/caos/zitadel/internal/query/projection" ) @@ -17,6 +18,7 @@ type LockoutPolicy struct { CreationDate time.Time ChangeDate time.Time ResourceOwner string + State domain.PolicyState MaxPasswordAttempts uint64 ShowFailures bool @@ -52,6 +54,9 @@ var ( LockoutColIsDefault = Column{ name: projection.LockoutPolicyIsDefaultCol, } + LockoutColState = Column{ + name: projection.LockoutPolicyStateCol, + } ) func (q *Queries) LockoutPolicyByOrg(ctx context.Context, orgID string) (*LockoutPolicy, error) { @@ -100,6 +105,7 @@ func prepareLockoutPolicyQuery() (sq.SelectBuilder, func(*sql.Row) (*LockoutPoli LockoutColShowFailures.identifier(), LockoutColMaxPasswordAttempts.identifier(), LockoutColIsDefault.identifier(), + LockoutColState.identifier(), ). From(lockoutTable.identifier()).PlaceholderFormat(sq.Dollar), func(row *sql.Row) (*LockoutPolicy, error) { @@ -113,6 +119,7 @@ func prepareLockoutPolicyQuery() (sq.SelectBuilder, func(*sql.Row) (*LockoutPoli &policy.ShowFailures, &policy.MaxPasswordAttempts, &policy.IsDefault, + &policy.State, ) if err != nil { if errs.Is(err, sql.ErrNoRows) { diff --git a/internal/query/password_age_policy.go b/internal/query/password_age_policy.go index 9f7a8a5e5e..62c32ffc36 100644 --- a/internal/query/password_age_policy.go +++ b/internal/query/password_age_policy.go @@ -7,6 +7,7 @@ import ( "time" sq "github.com/Masterminds/squirrel" + "github.com/caos/zitadel/internal/domain" "github.com/caos/zitadel/internal/errors" "github.com/caos/zitadel/internal/query/projection" ) @@ -17,6 +18,7 @@ type PasswordAgePolicy struct { CreationDate time.Time ChangeDate time.Time ResourceOwner string + State domain.PolicyState ExpireWarnDays uint64 MaxAgeDays uint64 @@ -52,6 +54,9 @@ var ( PasswordAgeColIsDefault = Column{ name: projection.AgePolicyIsDefaultCol, } + PasswordAgeColState = Column{ + name: projection.AgePolicyStateCol, + } ) func (q *Queries) PasswordAgePolicyByOrg(ctx context.Context, orgID string) (*PasswordAgePolicy, error) { @@ -100,6 +105,7 @@ func preparePasswordAgePolicyQuery() (sq.SelectBuilder, func(*sql.Row) (*Passwor PasswordAgeColWarnDays.identifier(), PasswordAgeColMaxAge.identifier(), PasswordAgeColIsDefault.identifier(), + PasswordAgeColState.identifier(), ). From(passwordAgeTable.identifier()).PlaceholderFormat(sq.Dollar), func(row *sql.Row) (*PasswordAgePolicy, error) { @@ -113,6 +119,7 @@ func preparePasswordAgePolicyQuery() (sq.SelectBuilder, func(*sql.Row) (*Passwor &policy.ExpireWarnDays, &policy.MaxAgeDays, &policy.IsDefault, + &policy.State, ) if err != nil { if errs.Is(err, sql.ErrNoRows) { diff --git a/internal/query/password_complexity_policy.go b/internal/query/password_complexity_policy.go index 9f9d1ff2b8..1fde884a6f 100644 --- a/internal/query/password_complexity_policy.go +++ b/internal/query/password_complexity_policy.go @@ -7,6 +7,7 @@ import ( "time" sq "github.com/Masterminds/squirrel" + "github.com/caos/zitadel/internal/domain" "github.com/caos/zitadel/internal/errors" "github.com/caos/zitadel/internal/query/projection" ) @@ -17,6 +18,7 @@ type PasswordComplexityPolicy struct { CreationDate time.Time ChangeDate time.Time ResourceOwner string + State domain.PolicyState MinLength uint64 HasLowercase bool @@ -100,6 +102,9 @@ var ( PasswordComplexityColIsDefault = Column{ name: projection.ComplexityPolicyIsDefaultCol, } + PasswordComplexityColState = Column{ + name: projection.ComplexityPolicyStateCol, + } ) func preparePasswordComplexityPolicyQuery() (sq.SelectBuilder, func(*sql.Row) (*PasswordComplexityPolicy, error)) { @@ -115,6 +120,7 @@ func preparePasswordComplexityPolicyQuery() (sq.SelectBuilder, func(*sql.Row) (* PasswordComplexityColHasNumber.identifier(), PasswordComplexityColHasSymbol.identifier(), PasswordComplexityColIsDefault.identifier(), + PasswordComplexityColState.identifier(), ). From(passwordComplexityTable.identifier()).PlaceholderFormat(sq.Dollar), func(row *sql.Row) (*PasswordComplexityPolicy, error) { @@ -131,6 +137,7 @@ func preparePasswordComplexityPolicyQuery() (sq.SelectBuilder, func(*sql.Row) (* &policy.HasNumber, &policy.HasSymbol, &policy.IsDefault, + &policy.State, ) if err != nil { if errs.Is(err, sql.ErrNoRows) { diff --git a/internal/query/privacy_policy.go b/internal/query/privacy_policy.go new file mode 100644 index 0000000000..8791464a52 --- /dev/null +++ b/internal/query/privacy_policy.go @@ -0,0 +1,132 @@ +package query + +import ( + "context" + "database/sql" + errs "errors" + "time" + + sq "github.com/Masterminds/squirrel" + "github.com/caos/zitadel/internal/domain" + "github.com/caos/zitadel/internal/errors" + "github.com/caos/zitadel/internal/query/projection" +) + +type PrivacyPolicy struct { + ID string + Sequence uint64 + CreationDate time.Time + ChangeDate time.Time + ResourceOwner string + State domain.PolicyState + + TOSLink string + PrivacyLink string + + IsDefault bool +} + +var ( + privacyTable = table{ + name: projection.PrivacyPolicyTable, + } + PrivacyColID = Column{ + name: projection.PrivacyPolicyIDCol, + } + PrivacyColSequence = Column{ + name: projection.PrivacyPolicySequenceCol, + } + PrivacyColCreationDate = Column{ + name: projection.PrivacyPolicyCreationDateCol, + } + PrivacyColChangeDate = Column{ + name: projection.PrivacyPolicyChangeDateCol, + } + PrivacyColResourceOwner = Column{ + name: projection.PrivacyPolicyResourceOwnerCol, + } + PrivacyColPrivacyLink = Column{ + name: projection.PrivacyPolicyPrivacyLinkCol, + } + PrivacyColTOSLink = Column{ + name: projection.PrivacyPolicyTOSLinkCol, + } + PrivacyColIsDefault = Column{ + name: projection.PrivacyPolicyIsDefaultCol, + } + PrivacyColState = Column{ + name: projection.PrivacyPolicyStateCol, + } +) + +func (q *Queries) PrivacyPolicyByOrg(ctx context.Context, orgID string) (*PrivacyPolicy, error) { + stmt, scan := preparePrivacyPolicyQuery() + query, args, err := stmt.Where( + sq.Or{ + sq.Eq{ + PrivacyColID.identifier(): orgID, + }, + sq.Eq{ + PrivacyColID.identifier(): q.iamID, + }, + }). + OrderBy(PrivacyColIsDefault.identifier()). + Limit(1).ToSql() + if err != nil { + return nil, errors.ThrowInternal(err, "QUERY-UXuPI", "Errors.Query.SQLStatement") + } + + row := q.client.QueryRowContext(ctx, query, args...) + return scan(row) +} + +func (q *Queries) DefaultPrivacyPolicy(ctx context.Context) (*PrivacyPolicy, error) { + stmt, scan := preparePrivacyPolicyQuery() + query, args, err := stmt.Where(sq.Eq{ + PrivacyColID.identifier(): q.iamID, + }). + OrderBy(PrivacyColIsDefault.identifier()). + Limit(1).ToSql() + if err != nil { + return nil, errors.ThrowInternal(err, "QUERY-LkFZ7", "Errors.Query.SQLStatement") + } + + row := q.client.QueryRowContext(ctx, query, args...) + return scan(row) +} + +func preparePrivacyPolicyQuery() (sq.SelectBuilder, func(*sql.Row) (*PrivacyPolicy, error)) { + return sq.Select( + PrivacyColID.identifier(), + PrivacyColSequence.identifier(), + PrivacyColCreationDate.identifier(), + PrivacyColChangeDate.identifier(), + PrivacyColResourceOwner.identifier(), + PrivacyColPrivacyLink.identifier(), + PrivacyColTOSLink.identifier(), + PrivacyColIsDefault.identifier(), + PrivacyColState.identifier(), + ). + From(privacyTable.identifier()).PlaceholderFormat(sq.Dollar), + func(row *sql.Row) (*PrivacyPolicy, error) { + policy := new(PrivacyPolicy) + err := row.Scan( + &policy.ID, + &policy.Sequence, + &policy.CreationDate, + &policy.ChangeDate, + &policy.ResourceOwner, + &policy.PrivacyLink, + &policy.TOSLink, + &policy.IsDefault, + &policy.State, + ) + if err != nil { + if errs.Is(err, sql.ErrNoRows) { + return nil, errors.ThrowNotFound(err, "QUERY-vNMHL", "Errors.PrivacyPolicy.NotFound") + } + return nil, errors.ThrowInternal(err, "QUERY-csrdo", "Errors.Internal") + } + return policy, nil + } +} diff --git a/internal/query/projection/privacy_policy.go b/internal/query/projection/privacy_policy.go new file mode 100644 index 0000000000..430174bd44 --- /dev/null +++ b/internal/query/projection/privacy_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 PrivacyPolicyProjection struct { + crdb.StatementHandler +} + +const ( + PrivacyPolicyTable = "zitadel.projections.privacy_policies" + + PrivacyPolicyCreationDateCol = "creation_date" + PrivacyPolicyChangeDateCol = "change_date" + PrivacyPolicySequenceCol = "sequence" + PrivacyPolicyIDCol = "id" + PrivacyPolicyStateCol = "state" + PrivacyPolicyPrivacyLinkCol = "privacy_link" + PrivacyPolicyTOSLinkCol = "tos_link" + PrivacyPolicyIsDefaultCol = "is_default" + PrivacyPolicyResourceOwnerCol = "resource_owner" +) + +func NewPrivacyPolicyProjection(ctx context.Context, config crdb.StatementHandlerConfig) *PrivacyPolicyProjection { + p := &PrivacyPolicyProjection{} + config.ProjectionName = PrivacyPolicyTable + config.Reducers = p.reducers() + p.StatementHandler = crdb.NewStatementHandler(ctx, config) + return p +} + +func (p *PrivacyPolicyProjection) reducers() []handler.AggregateReducer { + return []handler.AggregateReducer{ + { + Aggregate: org.AggregateType, + EventRedusers: []handler.EventReducer{ + { + Event: org.PrivacyPolicyAddedEventType, + Reduce: p.reduceAdded, + }, + { + Event: org.PrivacyPolicyChangedEventType, + Reduce: p.reduceChanged, + }, + { + Event: org.PrivacyPolicyRemovedEventType, + Reduce: p.reduceRemoved, + }, + }, + }, + { + Aggregate: iam.AggregateType, + EventRedusers: []handler.EventReducer{ + { + Event: iam.PrivacyPolicyAddedEventType, + Reduce: p.reduceAdded, + }, + { + Event: iam.PrivacyPolicyChangedEventType, + Reduce: p.reduceChanged, + }, + }, + }, + } +} + +func (p *PrivacyPolicyProjection) reduceAdded(event eventstore.EventReader) (*handler.Statement, error) { + var policyEvent policy.PrivacyPolicyAddedEvent + var isDefault bool + switch e := event.(type) { + case *org.PrivacyPolicyAddedEvent: + policyEvent = e.PrivacyPolicyAddedEvent + isDefault = false + case *iam.PrivacyPolicyAddedEvent: + policyEvent = e.PrivacyPolicyAddedEvent + isDefault = true + default: + logging.LogWithFields("PROJE-BrdLn", "seq", event.Sequence(), "expectedTypes", []eventstore.EventType{org.PrivacyPolicyAddedEventType, iam.PrivacyPolicyAddedEventType}).Error("wrong event type") + return nil, errors.ThrowInvalidArgument(nil, "PROJE-kRNh8", "reduce.wrong.event.type") + } + return crdb.NewCreateStatement( + &policyEvent, + []handler.Column{ + handler.NewCol(PrivacyPolicyCreationDateCol, policyEvent.CreationDate()), + handler.NewCol(PrivacyPolicyChangeDateCol, policyEvent.CreationDate()), + handler.NewCol(PrivacyPolicySequenceCol, policyEvent.Sequence()), + handler.NewCol(PrivacyPolicyIDCol, policyEvent.Aggregate().ID), + handler.NewCol(PrivacyPolicyStateCol, domain.PolicyStateActive), + handler.NewCol(PrivacyPolicyPrivacyLinkCol, policyEvent.PrivacyLink), + handler.NewCol(PrivacyPolicyTOSLinkCol, policyEvent.TOSLink), + handler.NewCol(PrivacyPolicyIsDefaultCol, isDefault), + handler.NewCol(PrivacyPolicyResourceOwnerCol, policyEvent.Aggregate().ResourceOwner), + }), nil +} + +func (p *PrivacyPolicyProjection) reduceChanged(event eventstore.EventReader) (*handler.Statement, error) { + var policyEvent policy.PrivacyPolicyChangedEvent + switch e := event.(type) { + case *org.PrivacyPolicyChangedEvent: + policyEvent = e.PrivacyPolicyChangedEvent + case *iam.PrivacyPolicyChangedEvent: + policyEvent = e.PrivacyPolicyChangedEvent + default: + logging.LogWithFields("PROJE-1nQWm", "seq", event.Sequence(), "expectedTypes", []eventstore.EventType{org.PrivacyPolicyChangedEventType, iam.PrivacyPolicyChangedEventType}).Error("wrong event type") + return nil, errors.ThrowInvalidArgument(nil, "PROJE-91weZ", "reduce.wrong.event.type") + } + cols := []handler.Column{ + handler.NewCol(PrivacyPolicyChangeDateCol, policyEvent.CreationDate()), + handler.NewCol(PrivacyPolicySequenceCol, policyEvent.Sequence()), + } + if policyEvent.PrivacyLink != nil { + cols = append(cols, handler.NewCol(PrivacyPolicyPrivacyLinkCol, *policyEvent.PrivacyLink)) + } + if policyEvent.TOSLink != nil { + cols = append(cols, handler.NewCol(PrivacyPolicyTOSLinkCol, *policyEvent.TOSLink)) + } + return crdb.NewUpdateStatement( + &policyEvent, + cols, + []handler.Condition{ + handler.NewCond(PrivacyPolicyIDCol, policyEvent.Aggregate().ID), + }), nil +} + +func (p *PrivacyPolicyProjection) reduceRemoved(event eventstore.EventReader) (*handler.Statement, error) { + policyEvent, ok := event.(*org.PrivacyPolicyRemovedEvent) + if !ok { + logging.LogWithFields("PROJE-hN5Ip", "seq", event.Sequence(), "expectedType", org.PrivacyPolicyRemovedEventType).Error("wrong event type") + return nil, errors.ThrowInvalidArgument(nil, "PROJE-FvtGO", "reduce.wrong.event.type") + } + return crdb.NewDeleteStatement( + policyEvent, + []handler.Condition{ + handler.NewCond(PrivacyPolicyIDCol, policyEvent.Aggregate().ID), + }), nil +} diff --git a/internal/query/projection/privacy_policy_test.go b/internal/query/projection/privacy_policy_test.go new file mode 100644 index 0000000000..5922d2f782 --- /dev/null +++ b/internal/query/projection/privacy_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 TestPrivacyPolicyProjection_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.PrivacyPolicyAddedEventType), + org.AggregateType, + []byte(`{ + "tosLink": "http://tos.link", + "privacyLink": "http://privacy.link" +}`), + ), org.PrivacyPolicyAddedEventMapper), + }, + reduce: (&PrivacyPolicyProjection{}).reduceAdded, + want: wantReduce{ + aggregateType: eventstore.AggregateType("org"), + sequence: 15, + previousSequence: 10, + projection: PrivacyPolicyTable, + executer: &testExecuter{ + executions: []execution{ + { + expectedStmt: "INSERT INTO zitadel.projections.privacy_policies (creation_date, change_date, sequence, id, state, privacy_link, tos_link, is_default, resource_owner) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)", + expectedArgs: []interface{}{ + anyArg{}, + anyArg{}, + uint64(15), + "agg-id", + domain.PolicyStateActive, + "http://privacy.link", + "http://tos.link", + false, + "ro-id", + }, + }, + }, + }, + }, + }, + { + name: "org.reduceChanged", + reduce: (&PrivacyPolicyProjection{}).reduceChanged, + args: args{ + event: getEvent(testEvent( + repository.EventType(org.PrivacyPolicyChangedEventType), + org.AggregateType, + []byte(`{ + "tosLink": "http://tos.link", + "privacyLink": "http://privacy.link" + }`), + ), org.PrivacyPolicyChangedEventMapper), + }, + want: wantReduce{ + aggregateType: eventstore.AggregateType("org"), + sequence: 15, + previousSequence: 10, + projection: PrivacyPolicyTable, + executer: &testExecuter{ + executions: []execution{ + { + expectedStmt: "UPDATE zitadel.projections.privacy_policies SET (change_date, sequence, privacy_link, tos_link) = ($1, $2, $3, $4) WHERE (id = $5)", + expectedArgs: []interface{}{ + anyArg{}, + uint64(15), + "http://privacy.link", + "http://tos.link", + "agg-id", + }, + }, + }, + }, + }, + }, + { + name: "org.reduceRemoved", + reduce: (&PrivacyPolicyProjection{}).reduceRemoved, + args: args{ + event: getEvent(testEvent( + repository.EventType(org.PrivacyPolicyRemovedEventType), + org.AggregateType, + nil, + ), org.PrivacyPolicyRemovedEventMapper), + }, + want: wantReduce{ + aggregateType: eventstore.AggregateType("org"), + sequence: 15, + previousSequence: 10, + projection: PrivacyPolicyTable, + executer: &testExecuter{ + executions: []execution{ + { + expectedStmt: "DELETE FROM zitadel.projections.privacy_policies WHERE (id = $1)", + expectedArgs: []interface{}{ + "agg-id", + }, + }, + }, + }, + }, + }, + { + name: "iam.reduceAdded", + reduce: (&PrivacyPolicyProjection{}).reduceAdded, + args: args{ + event: getEvent(testEvent( + repository.EventType(iam.PrivacyPolicyAddedEventType), + iam.AggregateType, + []byte(`{ + "tosLink": "http://tos.link", + "privacyLink": "http://privacy.link" + }`), + ), iam.PrivacyPolicyAddedEventMapper), + }, + want: wantReduce{ + aggregateType: eventstore.AggregateType("iam"), + sequence: 15, + previousSequence: 10, + projection: PrivacyPolicyTable, + executer: &testExecuter{ + executions: []execution{ + { + expectedStmt: "INSERT INTO zitadel.projections.privacy_policies (creation_date, change_date, sequence, id, state, privacy_link, tos_link, is_default, resource_owner) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)", + expectedArgs: []interface{}{ + anyArg{}, + anyArg{}, + uint64(15), + "agg-id", + domain.PolicyStateActive, + "http://privacy.link", + "http://tos.link", + true, + "ro-id", + }, + }, + }, + }, + }, + }, + { + name: "iam.reduceChanged", + reduce: (&PrivacyPolicyProjection{}).reduceChanged, + args: args{ + event: getEvent(testEvent( + repository.EventType(iam.PrivacyPolicyChangedEventType), + iam.AggregateType, + []byte(`{ + "tosLink": "http://tos.link", + "privacyLink": "http://privacy.link" + }`), + ), iam.PrivacyPolicyChangedEventMapper), + }, + want: wantReduce{ + aggregateType: eventstore.AggregateType("iam"), + sequence: 15, + previousSequence: 10, + projection: PrivacyPolicyTable, + executer: &testExecuter{ + executions: []execution{ + { + expectedStmt: "UPDATE zitadel.projections.privacy_policies SET (change_date, sequence, privacy_link, tos_link) = ($1, $2, $3, $4) WHERE (id = $5)", + expectedArgs: []interface{}{ + anyArg{}, + uint64(15), + "http://privacy.link", + "http://tos.link", + "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 68805d0f28..63b5c3dfb7 100644 --- a/internal/query/projection/projection.go +++ b/internal/query/projection/projection.go @@ -40,6 +40,7 @@ func Start(ctx context.Context, sqlClient *sql.DB, es *eventstore.Eventstore, co 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"])) + NewPrivacyPolicyProjection(ctx, applyCustomConfig(projectionConfig, config.Customizations["privacy_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/internal/ui/login/handler/privacy_policy_handler.go b/internal/ui/login/handler/privacy_policy_handler.go deleted file mode 100644 index 8f8289cc2e..0000000000 --- a/internal/ui/login/handler/privacy_policy_handler.go +++ /dev/null @@ -1,15 +0,0 @@ -package handler - -import ( - "net/http" - - iam_model "github.com/caos/zitadel/internal/iam/model" -) - -func (l *Login) getDefaultPrivacyPolicy(r *http.Request) (*iam_model.PrivacyPolicyView, error) { - policy, err := l.authRepo.GetDefaultPrivacyPolicy(r.Context()) - if err != nil { - return nil, err - } - return policy, nil -} diff --git a/internal/ui/login/handler/renderer.go b/internal/ui/login/handler/renderer.go index bede0a9ed3..95ded170f5 100644 --- a/internal/ui/login/handler/renderer.go +++ b/internal/ui/login/handler/renderer.go @@ -353,7 +353,7 @@ func (l *Login) getBaseData(r *http.Request, authReq *domain.AuthRequest, title baseData.PrivacyLink = authReq.PrivacyPolicy.PrivacyLink } } else { - privacyPolicy, err := l.getDefaultPrivacyPolicy(r) + privacyPolicy, err := l.query.DefaultPrivacyPolicy(r.Context()) if err != nil { return baseData } diff --git a/migrations/cockroach/V1.83__privacy_policy.sql b/migrations/cockroach/V1.83__privacy_policy.sql new file mode 100644 index 0000000000..2df3fbea63 --- /dev/null +++ b/migrations/cockroach/V1.83__privacy_policy.sql @@ -0,0 +1,14 @@ +CREATE TABLE zitadel.projections.privacy_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, + privacy_link TEXT, + tos_link TEXT, + + PRIMARY KEY (id) +); \ No newline at end of file