diff --git a/internal/admin/repository/eventsourcing/eventstore/iam.go b/internal/admin/repository/eventsourcing/eventstore/iam.go index 55f0ded240..11a379a4d9 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) GetOrgIAMPolicy(ctx context.Context) (*iam_model.OrgIAMPolicyView, error) { - policy, viewErr := repo.View.OrgIAMPolicyByAggregateID(repo.SystemDefaults.IamID) - if viewErr != nil && !caos_errs.IsNotFound(viewErr) { - return nil, viewErr - } - if caos_errs.IsNotFound(viewErr) { - policy = new(iam_es_model.OrgIAMPolicyView) - } - - events, esErr := repo.getIAMEvents(ctx, policy.Sequence) - if caos_errs.IsNotFound(viewErr) && len(events) == 0 { - return nil, caos_errs.ThrowNotFound(nil, "EVENT-MkoL0", "Errors.IAM.OrgIAMPolicy.NotFound") - } - if esErr != nil { - logging.Log("EVENT-3M0xs").WithError(esErr).Debug("error retrieving new events") - return iam_es_model.OrgIAMViewToModel(policy), nil - } - policyCopy := *policy - for _, event := range events { - if err := policyCopy.AppendEvent(event); err != nil { - return iam_es_model.OrgIAMViewToModel(policy), nil - } - } - return iam_es_model.OrgIAMViewToModel(policy), nil -} - func (repo *IAMRepository) GetDefaultLabelPolicy(ctx context.Context) (*iam_model.LabelPolicyView, error) { policy, err := repo.View.LabelPolicyByAggregateIDAndState(repo.SystemDefaults.IamID, int32(domain.LabelPolicyStateActive)) if err != nil { diff --git a/internal/admin/repository/eventsourcing/eventstore/org.go b/internal/admin/repository/eventsourcing/eventstore/org.go deleted file mode 100644 index 44a5a5f370..0000000000 --- a/internal/admin/repository/eventsourcing/eventstore/org.go +++ /dev/null @@ -1,37 +0,0 @@ -package eventstore - -import ( - "context" - - admin_view "github.com/caos/zitadel/internal/admin/repository/eventsourcing/view" - "github.com/caos/zitadel/internal/config/systemdefaults" - "github.com/caos/zitadel/internal/errors" - iam_model "github.com/caos/zitadel/internal/iam/model" - iam_es_model "github.com/caos/zitadel/internal/iam/repository/view/model" -) - -type OrgRepo struct { - View *admin_view.View - - SystemDefaults systemdefaults.SystemDefaults -} - -func (repo *OrgRepo) GetOrgIAMPolicyByID(ctx context.Context, id string) (*iam_model.OrgIAMPolicyView, error) { - policy, err := repo.View.OrgIAMPolicyByAggregateID(id) - if errors.IsNotFound(err) { - return repo.GetDefaultOrgIAMPolicy(ctx) - } - if err != nil { - return nil, err - } - return iam_es_model.OrgIAMViewToModel(policy), err -} - -func (repo *OrgRepo) GetDefaultOrgIAMPolicy(ctx context.Context) (*iam_model.OrgIAMPolicyView, error) { - policy, err := repo.View.OrgIAMPolicyByAggregateID(repo.SystemDefaults.IamID) - if err != nil { - return nil, err - } - policy.Default = true - return iam_es_model.OrgIAMViewToModel(policy), err -} diff --git a/internal/admin/repository/eventsourcing/handler/handler.go b/internal/admin/repository/eventsourcing/handler/handler.go index b0da90badd..34a72d1abf 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), - newOrgIAMPolicy( - handler{view, bulkLimit, configs.cycleDuration("OrgIAMPolicy"), errorCount, es}), newExternalIDP( handler{view, bulkLimit, configs.cycleDuration("ExternalIDP"), errorCount, es}, defaults), diff --git a/internal/admin/repository/eventsourcing/handler/org_iam_policy.go b/internal/admin/repository/eventsourcing/handler/org_iam_policy.go deleted file mode 100644 index 5b32c8f6b1..0000000000 --- a/internal/admin/repository/eventsourcing/handler/org_iam_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" - "github.com/caos/zitadel/internal/org/repository/eventsourcing/model" -) - -const ( - orgIAMPolicyTable = "adminapi.org_iam_policies" -) - -type OrgIAMPolicy struct { - handler - subscription *v1.Subscription -} - -func newOrgIAMPolicy(handler handler) *OrgIAMPolicy { - h := &OrgIAMPolicy{ - handler: handler, - } - - h.subscribe() - - return h -} - -func (p *OrgIAMPolicy) subscribe() { - p.subscription = p.es.Subscribe(p.AggregateTypes()...) - go func() { - for event := range p.subscription.Events { - query.ReduceEvent(p, event) - } - }() -} - -func (p *OrgIAMPolicy) ViewModel() string { - return orgIAMPolicyTable -} - -func (p *OrgIAMPolicy) Subscription() *v1.Subscription { - return p.subscription -} - -func (p *OrgIAMPolicy) AggregateTypes() []es_models.AggregateType { - return []es_models.AggregateType{model.OrgAggregate, iam_es_model.IAMAggregate} -} - -func (p *OrgIAMPolicy) EventQuery() (*es_models.SearchQuery, error) { - sequence, err := p.view.GetLatestOrgIAMPolicySequence() - if err != nil { - return nil, err - } - return es_models.NewSearchQuery(). - AggregateTypeFilter(p.AggregateTypes()...). - LatestSequenceFilter(sequence.CurrentSequence), nil -} - -func (p *OrgIAMPolicy) CurrentSequence() (uint64, error) { - sequence, err := p.view.GetLatestOrgIAMPolicySequence() - if err != nil { - return 0, err - } - return sequence.CurrentSequence, nil -} - -func (p *OrgIAMPolicy) Reduce(event *es_models.Event) (err error) { - switch event.AggregateType { - case model.OrgAggregate, iam_es_model.IAMAggregate: - err = p.processOrgIAMPolicy(event) - } - return err -} - -func (p *OrgIAMPolicy) processOrgIAMPolicy(event *es_models.Event) (err error) { - policy := new(iam_model.OrgIAMPolicyView) - switch event.Type { - case iam_es_model.OrgIAMPolicyAdded, model.OrgIAMPolicyAdded: - err = policy.AppendEvent(event) - case iam_es_model.OrgIAMPolicyChanged, model.OrgIAMPolicyChanged: - policy, err = p.view.OrgIAMPolicyByAggregateID(event.AggregateID) - if err != nil { - return err - } - err = policy.AppendEvent(event) - case model.OrgIAMPolicyRemoved: - return p.view.DeleteOrgIAMPolicy(event.AggregateID, event) - default: - return p.view.ProcessedOrgIAMPolicySequence(event) - } - if err != nil { - return err - } - return p.view.PutOrgIAMPolicy(policy, event) -} - -func (p *OrgIAMPolicy) OnError(event *es_models.Event, err error) error { - logging.LogWithFields("SPOOL-Wm8fs", "id", event.AggregateID).WithError(err).Warn("something went wrong in orgIAM policy handler") - return spooler.HandleError(event, err, p.view.GetLatestOrgIAMPolicyFailedEvent, p.view.ProcessedOrgIAMPolicyFailedEvent, p.view.ProcessedOrgIAMPolicySequence, p.errorCountUntilSkip) -} - -func (p *OrgIAMPolicy) OnSuccess() error { - return spooler.HandleSuccess(p.view.UpdateOrgIAMPolicySpoolerRunTimestamp) -} diff --git a/internal/admin/repository/eventsourcing/repository.go b/internal/admin/repository/eventsourcing/repository.go index ebffb31a33..cec4e52118 100644 --- a/internal/admin/repository/eventsourcing/repository.go +++ b/internal/admin/repository/eventsourcing/repository.go @@ -28,7 +28,6 @@ type Config struct { type EsRepository struct { spooler *es_spol.Spooler - eventstore.OrgRepo eventstore.IAMRepository eventstore.AdministratorRepo eventstore.FeaturesRepo @@ -60,10 +59,6 @@ func Start(ctx context.Context, conf Config, systemDefaults sd.SystemDefaults, c return &EsRepository{ spooler: spool, - OrgRepo: eventstore.OrgRepo{ - View: view, - SystemDefaults: systemDefaults, - }, IAMRepository: eventstore.IAMRepository{ Eventstore: es, View: view, diff --git a/internal/admin/repository/eventsourcing/view/org_iam_policy.go b/internal/admin/repository/eventsourcing/view/org_iam_policy.go deleted file mode 100644 index f9470821d4..0000000000 --- a/internal/admin/repository/eventsourcing/view/org_iam_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 ( - orgIAMPolicyTable = "adminapi.org_iam_policies" -) - -func (v *View) OrgIAMPolicyByAggregateID(aggregateID string) (*model.OrgIAMPolicyView, error) { - return view.GetOrgIAMPolicyByAggregateID(v.Db, orgIAMPolicyTable, aggregateID) -} - -func (v *View) PutOrgIAMPolicy(policy *model.OrgIAMPolicyView, event *models.Event) error { - err := view.PutOrgIAMPolicy(v.Db, orgIAMPolicyTable, policy) - if err != nil { - return err - } - return v.ProcessedOrgIAMPolicySequence(event) -} - -func (v *View) DeleteOrgIAMPolicy(aggregateID string, event *models.Event) error { - err := view.DeleteOrgIAMPolicy(v.Db, orgIAMPolicyTable, aggregateID) - if err != nil && !errors.IsNotFound(err) { - return err - } - return v.ProcessedOrgIAMPolicySequence(event) -} - -func (v *View) GetLatestOrgIAMPolicySequence() (*global_view.CurrentSequence, error) { - return v.latestSequence(orgIAMPolicyTable) -} - -func (v *View) ProcessedOrgIAMPolicySequence(event *models.Event) error { - return v.saveCurrentSequence(orgIAMPolicyTable, event) -} - -func (v *View) UpdateOrgIAMPolicySpoolerRunTimestamp() error { - return v.updateSpoolerRunSequence(orgIAMPolicyTable) -} - -func (v *View) GetLatestOrgIAMPolicyFailedEvent(sequence uint64) (*global_view.FailedEvent, error) { - return v.latestFailedEvent(orgIAMPolicyTable, sequence) -} - -func (v *View) ProcessedOrgIAMPolicyFailedEvent(failedEvent *global_view.FailedEvent) error { - return v.saveFailedEvent(failedEvent) -} diff --git a/internal/admin/repository/iam.go b/internal/admin/repository/iam.go index a0d6a9e6d9..3937b49ba1 100644 --- a/internal/admin/repository/iam.go +++ b/internal/admin/repository/iam.go @@ -34,6 +34,4 @@ type IAMRepository interface { GetCustomMessageText(ctx context.Context, textType string, language string) (*domain.CustomMessageText, error) GetDefaultLoginTexts(ctx context.Context, lang string) (*domain.CustomLoginText, error) GetCustomLoginTexts(ctx context.Context, lang string) (*domain.CustomLoginText, error) - - GetDefaultOrgIAMPolicy(ctx context.Context) (*iam_model.OrgIAMPolicyView, error) } diff --git a/internal/admin/repository/org.go b/internal/admin/repository/org.go deleted file mode 100644 index c276550932..0000000000 --- a/internal/admin/repository/org.go +++ /dev/null @@ -1,11 +0,0 @@ -package repository - -import ( - "context" - - iam_model "github.com/caos/zitadel/internal/iam/model" -) - -type OrgRepository interface { - GetOrgIAMPolicyByID(ctx context.Context, id string) (*iam_model.OrgIAMPolicyView, error) -} diff --git a/internal/admin/repository/repository.go b/internal/admin/repository/repository.go index d93f893ba8..61fbdad53f 100644 --- a/internal/admin/repository/repository.go +++ b/internal/admin/repository/repository.go @@ -4,7 +4,6 @@ import "context" type Repository interface { Health(ctx context.Context) error - OrgRepository IAMRepository AdministratorRepository FeaturesRepository diff --git a/internal/api/grpc/admin/org_iam_policy.go b/internal/api/grpc/admin/org_iam_policy.go index 93a1cada08..c794a7c2d9 100644 --- a/internal/api/grpc/admin/org_iam_policy.go +++ b/internal/api/grpc/admin/org_iam_policy.go @@ -11,7 +11,7 @@ import ( ) func (s *Server) GetOrgIAMPolicy(ctx context.Context, _ *admin_pb.GetOrgIAMPolicyRequest) (*admin_pb.GetOrgIAMPolicyResponse, error) { - policy, err := s.iam.GetDefaultOrgIAMPolicy(ctx) + policy, err := s.query.DefaultOrgIAMPolicy(ctx) if err != nil { return nil, err } @@ -19,7 +19,7 @@ func (s *Server) GetOrgIAMPolicy(ctx context.Context, _ *admin_pb.GetOrgIAMPolic } func (s *Server) GetCustomOrgIAMPolicy(ctx context.Context, req *admin_pb.GetCustomOrgIAMPolicyRequest) (*admin_pb.GetCustomOrgIAMPolicyResponse, error) { - policy, err := s.org.GetOrgIAMPolicyByID(ctx, req.OrgId) + policy, err := s.query.OrgIAMPolicyByOrg(ctx, req.OrgId) if err != nil { return nil, err } diff --git a/internal/api/grpc/admin/server.go b/internal/api/grpc/admin/server.go index e2106a3dd5..45fb45d326 100644 --- a/internal/api/grpc/admin/server.go +++ b/internal/api/grpc/admin/server.go @@ -22,7 +22,6 @@ type Server struct { admin.UnimplementedAdminServiceServer command *command.Commands query *query.Queries - org repository.OrgRepository iam repository.IAMRepository administrator repository.AdministratorRepository repo repository.Repository @@ -39,7 +38,6 @@ func CreateServer(command *command.Commands, query *query.Queries, repo reposito return &Server{ command: command, query: query, - org: repo, iam: repo, administrator: repo, repo: repo, diff --git a/internal/api/grpc/management/org.go b/internal/api/grpc/management/org.go index 8c38fb722e..b05ab03dbe 100644 --- a/internal/api/grpc/management/org.go +++ b/internal/api/grpc/management/org.go @@ -105,7 +105,7 @@ func (s *Server) ReactivateOrg(ctx context.Context, req *mgmt_pb.ReactivateOrgRe } func (s *Server) GetOrgIAMPolicy(ctx context.Context, req *mgmt_pb.GetOrgIAMPolicyRequest) (*mgmt_pb.GetOrgIAMPolicyResponse, error) { - policy, err := s.org.GetMyOrgIamPolicy(ctx) + policy, err := s.query.OrgIAMPolicyByOrg(ctx, authz.GetCtxData(ctx).OrgID) if err != nil { return nil, err } diff --git a/internal/api/grpc/policy/org_iam_policy.go b/internal/api/grpc/policy/org_iam_policy.go index fd14b684aa..5bc36af72f 100644 --- a/internal/api/grpc/policy/org_iam_policy.go +++ b/internal/api/grpc/policy/org_iam_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 OrgIAMPolicyToPb(policy *model.OrgIAMPolicyView) *policy_pb.OrgIAMPolicy { +func OrgIAMPolicyToPb(policy *query.OrgIAMPolicy) *policy_pb.OrgIAMPolicy { return &policy_pb.OrgIAMPolicy{ UserLoginMustBeDomain: policy.UserLoginMustBeDomain, - IsDefault: policy.Default, + IsDefault: policy.IsDefault, Details: object.ToViewDetailsPb( policy.Sequence, policy.CreationDate, policy.ChangeDate, - "", //TODO: resource owner + policy.ResourceOwner, ), } } diff --git a/internal/auth/repository/eventsourcing/eventstore/org.go b/internal/auth/repository/eventsourcing/eventstore/org.go index 27edff2107..b516603c35 100644 --- a/internal/auth/repository/eventsourcing/eventstore/org.go +++ b/internal/auth/repository/eventsourcing/eventstore/org.go @@ -29,27 +29,6 @@ type OrgRepository struct { Query *query.Queries } -func (repo *OrgRepository) GetDefaultOrgIAMPolicy(ctx context.Context) (*iam_model.OrgIAMPolicyView, error) { - orgPolicy, err := repo.View.OrgIAMPolicyByAggregateID(repo.SystemDefaults.IamID) - if err != nil { - return nil, err - } - policy := iam_view_model.OrgIAMViewToModel(orgPolicy) - policy.IAMDomain = repo.SystemDefaults.Domain - return policy, err -} - -func (repo *OrgRepository) GetOrgIAMPolicy(ctx context.Context, orgID string) (*iam_model.OrgIAMPolicyView, error) { - orgPolicy, err := repo.View.OrgIAMPolicyByAggregateID(orgID) - if errors.IsNotFound(err) { - orgPolicy, err = repo.View.OrgIAMPolicyByAggregateID(repo.SystemDefaults.IamID) - } - if err != nil { - return nil, err - } - return iam_view_model.OrgIAMViewToModel(orgPolicy), nil -} - func (repo *OrgRepository) GetIDPConfigByID(ctx context.Context, idpConfigID string) (*iam_model.IDPConfigView, error) { idpConfig, err := repo.View.IDPConfigByID(idpConfigID) if err != nil { diff --git a/internal/auth/repository/eventsourcing/handler/handler.go b/internal/auth/repository/eventsourcing/handler/handler.go index 1d34603c14..81e98e831d 100644 --- a/internal/auth/repository/eventsourcing/handler/handler.go +++ b/internal/auth/repository/eventsourcing/handler/handler.go @@ -58,8 +58,6 @@ func Register(configs Configs, bulkLimit, errorCount uint64, view *view.View, es newExternalIDP( handler{view, bulkLimit, configs.cycleDuration("ExternalIDP"), errorCount, es}, systemDefaults), - newOrgIAMPolicy( - handler{view, bulkLimit, configs.cycleDuration("OrgIAMPolicy"), errorCount, es}), newProjectRole(handler{view, bulkLimit, configs.cycleDuration("ProjectRole"), errorCount, es}), newLabelPolicy(handler{view, bulkLimit, configs.cycleDuration("LabelPolicy"), errorCount, es}), newFeatures(handler{view, bulkLimit, configs.cycleDuration("Features"), errorCount, es}), diff --git a/internal/auth/repository/eventsourcing/handler/org_iam_policy.go b/internal/auth/repository/eventsourcing/handler/org_iam_policy.go deleted file mode 100644 index 8357b55892..0000000000 --- a/internal/auth/repository/eventsourcing/handler/org_iam_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 ( - orgIAMPolicyTable = "auth.org_iam_policies" -) - -type OrgIAMPolicy struct { - handler - subscription *v1.Subscription -} - -func newOrgIAMPolicy(handler handler) *OrgIAMPolicy { - h := &OrgIAMPolicy{ - handler: handler, - } - - h.subscribe() - - return h -} - -func (p *OrgIAMPolicy) subscribe() { - p.subscription = p.es.Subscribe(p.AggregateTypes()...) - go func() { - for event := range p.subscription.Events { - query.ReduceEvent(p, event) - } - }() -} - -func (p *OrgIAMPolicy) ViewModel() string { - return orgIAMPolicyTable -} - -func (p *OrgIAMPolicy) Subscription() *v1.Subscription { - return p.subscription -} - -func (_ *OrgIAMPolicy) AggregateTypes() []es_models.AggregateType { - return []es_models.AggregateType{org_es_model.OrgAggregate, iam_es_model.IAMAggregate} -} - -func (p *OrgIAMPolicy) CurrentSequence() (uint64, error) { - sequence, err := p.view.GetLatestOrgIAMPolicySequence() - if err != nil { - return 0, err - } - return sequence.CurrentSequence, nil -} - -func (p *OrgIAMPolicy) EventQuery() (*es_models.SearchQuery, error) { - sequence, err := p.view.GetLatestOrgIAMPolicySequence() - if err != nil { - return nil, err - } - return es_models.NewSearchQuery(). - AggregateTypeFilter(p.AggregateTypes()...). - LatestSequenceFilter(sequence.CurrentSequence), nil -} - -func (p *OrgIAMPolicy) Reduce(event *es_models.Event) (err error) { - switch event.AggregateType { - case org_es_model.OrgAggregate, iam_es_model.IAMAggregate: - err = p.processOrgIAMPolicy(event) - } - return err -} - -func (p *OrgIAMPolicy) processOrgIAMPolicy(event *es_models.Event) (err error) { - policy := new(iam_model.OrgIAMPolicyView) - switch event.Type { - case iam_es_model.OrgIAMPolicyAdded, org_es_model.OrgIAMPolicyAdded: - err = policy.AppendEvent(event) - case iam_es_model.OrgIAMPolicyChanged, org_es_model.OrgIAMPolicyChanged: - policy, err = p.view.OrgIAMPolicyByAggregateID(event.AggregateID) - if err != nil { - return err - } - err = policy.AppendEvent(event) - case org_es_model.OrgIAMPolicyRemoved: - return p.view.DeleteOrgIAMPolicy(event.AggregateID, event) - default: - return p.view.ProcessedOrgIAMPolicySequence(event) - } - if err != nil { - return err - } - return p.view.PutOrgIAMPolicy(policy, event) -} - -func (p *OrgIAMPolicy) OnError(event *es_models.Event, err error) error { - logging.LogWithFields("SPOOL-3Gj8s", "id", event.AggregateID).WithError(err).Warn("something went wrong in orgIAM policy handler") - return spooler.HandleError(event, err, p.view.GetLatestOrgIAMPolicyFailedEvent, p.view.ProcessedOrgIAMPolicyFailedEvent, p.view.ProcessedOrgIAMPolicySequence, p.errorCountUntilSkip) -} - -func (p *OrgIAMPolicy) OnSuccess() error { - return spooler.HandleSuccess(p.view.UpdateOrgIAMPolicySpoolerRunTimestamp) -} diff --git a/internal/auth/repository/eventsourcing/repository.go b/internal/auth/repository/eventsourcing/repository.go index 63dd6569aa..187a8e9f6e 100644 --- a/internal/auth/repository/eventsourcing/repository.go +++ b/internal/auth/repository/eventsourcing/repository.go @@ -98,6 +98,7 @@ func Start(conf Config, authZ authz.Config, systemDefaults sd.SystemDefaults, co es, userRepo, eventstore.AuthRequestRepo{ + PrivacyPolicyProvider: queries, Command: command, OrgViewProvider: queries, AuthRequests: authReq, diff --git a/internal/auth/repository/eventsourcing/view/org_iam_policy.go b/internal/auth/repository/eventsourcing/view/org_iam_policy.go deleted file mode 100644 index ec089700a6..0000000000 --- a/internal/auth/repository/eventsourcing/view/org_iam_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 ( - orgIAMPolicyTable = "auth.org_iam_policies" -) - -func (v *View) OrgIAMPolicyByAggregateID(aggregateID string) (*model.OrgIAMPolicyView, error) { - return view.GetOrgIAMPolicyByAggregateID(v.Db, orgIAMPolicyTable, aggregateID) -} - -func (v *View) PutOrgIAMPolicy(policy *model.OrgIAMPolicyView, event *models.Event) error { - err := view.PutOrgIAMPolicy(v.Db, orgIAMPolicyTable, policy) - if err != nil { - return err - } - return v.ProcessedOrgIAMPolicySequence(event) -} - -func (v *View) DeleteOrgIAMPolicy(aggregateID string, event *models.Event) error { - err := view.DeleteOrgIAMPolicy(v.Db, orgIAMPolicyTable, aggregateID) - if err != nil && !errors.IsNotFound(err) { - return err - } - return v.ProcessedOrgIAMPolicySequence(event) -} - -func (v *View) GetLatestOrgIAMPolicySequence() (*global_view.CurrentSequence, error) { - return v.latestSequence(orgIAMPolicyTable) -} - -func (v *View) ProcessedOrgIAMPolicySequence(event *models.Event) error { - return v.saveCurrentSequence(orgIAMPolicyTable, event) -} - -func (v *View) UpdateOrgIAMPolicySpoolerRunTimestamp() error { - return v.updateSpoolerRunSequence(orgIAMPolicyTable) -} - -func (v *View) GetLatestOrgIAMPolicyFailedEvent(sequence uint64) (*global_view.FailedEvent, error) { - return v.latestFailedEvent(orgIAMPolicyTable, sequence) -} - -func (v *View) ProcessedOrgIAMPolicyFailedEvent(failedEvent *global_view.FailedEvent) error { - return v.saveFailedEvent(failedEvent) -} diff --git a/internal/auth/repository/org.go b/internal/auth/repository/org.go index 4d593be27f..4d8ff74a21 100644 --- a/internal/auth/repository/org.go +++ b/internal/auth/repository/org.go @@ -8,8 +8,6 @@ import ( ) type OrgRepository interface { - GetOrgIAMPolicy(ctx context.Context, orgID string) (*iam_model.OrgIAMPolicyView, error) - GetDefaultOrgIAMPolicy(ctx context.Context) (*iam_model.OrgIAMPolicyView, error) GetIDPConfigByID(ctx context.Context, idpConfigID string) (*iam_model.IDPConfigView, error) GetMyPasswordComplexityPolicy(ctx context.Context) (*iam_model.PasswordComplexityPolicyView, error) GetLabelPolicy(ctx context.Context, orgID string) (*domain.LabelPolicy, error) diff --git a/internal/iam/model/org_iam_policy_view.go b/internal/iam/model/org_iam_policy_view.go deleted file mode 100644 index e944bc4ced..0000000000 --- a/internal/iam/model/org_iam_policy_view.go +++ /dev/null @@ -1,47 +0,0 @@ -package model - -import ( - "github.com/caos/zitadel/internal/domain" - "time" -) - -type OrgIAMPolicyView struct { - AggregateID string - UserLoginMustBeDomain bool - IAMDomain string - Default bool - - CreationDate time.Time - ChangeDate time.Time - Sequence uint64 -} - -type OrgIAMPolicySearchRequest struct { - Offset uint64 - Limit uint64 - SortingColumn OrgIAMPolicySearchKey - Asc bool - Queries []*OrgIAMPolicySearchQuery -} - -type OrgIAMPolicySearchKey int32 - -const ( - OrgIAMPolicySearchKeyUnspecified OrgIAMPolicySearchKey = iota - OrgIAMPolicySearchKeyAggregateID -) - -type OrgIAMPolicySearchQuery struct { - Key OrgIAMPolicySearchKey - Method domain.SearchMethod - Value interface{} -} - -type OrgIAMPolicySearchResponse struct { - Offset uint64 - Limit uint64 - TotalResult uint64 - Result []*OrgIAMPolicyView - Sequence uint64 - Timestamp time.Time -} diff --git a/internal/iam/repository/eventsourcing/model/org_iam_policy.go b/internal/iam/repository/eventsourcing/model/org_iam_policy.go index e8ab09fd90..fa0ebcc594 100644 --- a/internal/iam/repository/eventsourcing/model/org_iam_policy.go +++ b/internal/iam/repository/eventsourcing/model/org_iam_policy.go @@ -15,14 +15,6 @@ type OrgIAMPolicy struct { UserLoginMustBeDomain bool `json:"userLoginMustBeDomain"` } -func OrgIAMPolicyFromModel(policy *iam_model.OrgIAMPolicy) *OrgIAMPolicy { - return &OrgIAMPolicy{ - ObjectRoot: policy.ObjectRoot, - State: int32(policy.State), - UserLoginMustBeDomain: policy.UserLoginMustBeDomain, - } -} - func OrgIAMPolicyToModel(policy *OrgIAMPolicy) *iam_model.OrgIAMPolicy { return &iam_model.OrgIAMPolicy{ ObjectRoot: policy.ObjectRoot, diff --git a/internal/iam/repository/eventsourcing/model/org_iam_policy_test.go b/internal/iam/repository/eventsourcing/model/org_iam_policy_test.go index c86fb532ff..a713e78671 100644 --- a/internal/iam/repository/eventsourcing/model/org_iam_policy_test.go +++ b/internal/iam/repository/eventsourcing/model/org_iam_policy_test.go @@ -2,8 +2,9 @@ package model import ( "encoding/json" - es_models "github.com/caos/zitadel/internal/eventstore/v1/models" "testing" + + es_models "github.com/caos/zitadel/internal/eventstore/v1/models" ) func TestOrgIAMPolicyChanges(t *testing.T) { diff --git a/internal/iam/repository/view/model/org_iam_policy.go b/internal/iam/repository/view/model/org_iam_policy.go index d40fcd5481..d55fabc7c0 100644 --- a/internal/iam/repository/view/model/org_iam_policy.go +++ b/internal/iam/repository/view/model/org_iam_policy.go @@ -2,15 +2,15 @@ package model import ( "encoding/json" - org_es_model "github.com/caos/zitadel/internal/org/repository/eventsourcing/model" "time" + 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 ( @@ -29,28 +29,6 @@ type OrgIAMPolicyView struct { Sequence uint64 `json:"-" gorm:"column:sequence"` } -func OrgIAMViewFromModel(policy *model.OrgIAMPolicyView) *OrgIAMPolicyView { - return &OrgIAMPolicyView{ - AggregateID: policy.AggregateID, - Sequence: policy.Sequence, - CreationDate: policy.CreationDate, - ChangeDate: policy.ChangeDate, - Default: policy.Default, - UserLoginMustBeDomain: policy.UserLoginMustBeDomain, - } -} - -func OrgIAMViewToModel(policy *OrgIAMPolicyView) *model.OrgIAMPolicyView { - return &model.OrgIAMPolicyView{ - AggregateID: policy.AggregateID, - Sequence: policy.Sequence, - CreationDate: policy.CreationDate, - ChangeDate: policy.ChangeDate, - UserLoginMustBeDomain: policy.UserLoginMustBeDomain, - Default: policy.Default, - } -} - func (i *OrgIAMPolicyView) AppendEvent(event *models.Event) (err error) { i.Sequence = event.Sequence i.ChangeDate = event.CreationDate diff --git a/internal/iam/repository/view/model/org_iam_policy_query.go b/internal/iam/repository/view/model/org_iam_policy_query.go deleted file mode 100644 index 48fc0a3c4c..0000000000 --- a/internal/iam/repository/view/model/org_iam_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 OrgIAMPolicySearchRequest iam_model.OrgIAMPolicySearchRequest -type OrgIAMPolicySearchQuery iam_model.OrgIAMPolicySearchQuery -type OrgIAMPolicySearchKey iam_model.OrgIAMPolicySearchKey - -func (req OrgIAMPolicySearchRequest) GetLimit() uint64 { - return req.Limit -} - -func (req OrgIAMPolicySearchRequest) GetOffset() uint64 { - return req.Offset -} - -func (req OrgIAMPolicySearchRequest) GetSortingColumn() repository.ColumnKey { - if req.SortingColumn == iam_model.OrgIAMPolicySearchKeyUnspecified { - return nil - } - return OrgIAMPolicySearchKey(req.SortingColumn) -} - -func (req OrgIAMPolicySearchRequest) GetAsc() bool { - return req.Asc -} - -func (req OrgIAMPolicySearchRequest) GetQueries() []repository.SearchQuery { - result := make([]repository.SearchQuery, len(req.Queries)) - for i, q := range req.Queries { - result[i] = OrgIAMPolicySearchQuery{Key: q.Key, Value: q.Value, Method: q.Method} - } - return result -} - -func (req OrgIAMPolicySearchQuery) GetKey() repository.ColumnKey { - return OrgIAMPolicySearchKey(req.Key) -} - -func (req OrgIAMPolicySearchQuery) GetMethod() domain.SearchMethod { - return req.Method -} - -func (req OrgIAMPolicySearchQuery) GetValue() interface{} { - return req.Value -} - -func (key OrgIAMPolicySearchKey) ToColumnName() string { - switch iam_model.OrgIAMPolicySearchKey(key) { - case iam_model.OrgIAMPolicySearchKeyAggregateID: - return OrgIAMPolicyKeyAggregateID - default: - return "" - } -} diff --git a/internal/iam/repository/view/org_iam_policy_view.go b/internal/iam/repository/view/org_iam_policy_view.go deleted file mode 100644 index 64135173bb..0000000000 --- a/internal/iam/repository/view/org_iam_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 GetOrgIAMPolicyByAggregateID(db *gorm.DB, table, aggregateID string) (*model.OrgIAMPolicyView, error) { - policy := new(model.OrgIAMPolicyView) - aggregateIDQuery := &model.OrgIAMPolicySearchQuery{Key: iam_model.OrgIAMPolicySearchKeyAggregateID, 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-5fi9s", "Errors.IAM.OrgIAMPolicy.NotExisting") - } - return policy, err -} - -func PutOrgIAMPolicy(db *gorm.DB, table string, policy *model.OrgIAMPolicyView) error { - save := repository.PrepareSave(table) - return save(db, policy) -} - -func DeleteOrgIAMPolicy(db *gorm.DB, table, aggregateID string) error { - delete := repository.PrepareDeleteByKey(table, model.OrgIAMPolicySearchKey(iam_model.OrgIAMPolicySearchKeyAggregateID), aggregateID) - - return delete(db) -} diff --git a/internal/management/repository/eventsourcing/eventstore/org.go b/internal/management/repository/eventsourcing/eventstore/org.go index 0e99c936ad..4c1f063209 100644 --- a/internal/management/repository/eventsourcing/eventstore/org.go +++ b/internal/management/repository/eventsourcing/eventstore/org.go @@ -65,21 +65,6 @@ func (repo *OrgRepository) Languages(ctx context.Context) ([]language.Tag, error return repo.supportedLangs, nil } -func (repo *OrgRepository) GetMyOrgIamPolicy(ctx context.Context) (*iam_model.OrgIAMPolicyView, error) { - policy, err := repo.View.OrgIAMPolicyByAggregateID(authz.GetCtxData(ctx).OrgID) - if errors.IsNotFound(err) { - policy, err = repo.View.OrgIAMPolicyByAggregateID(repo.SystemDefaults.IamID) - if err != nil { - return nil, err - } - policy.Default = true - } - if err != nil { - return nil, err - } - return iam_view_model.OrgIAMViewToModel(policy), err -} - func (repo *OrgRepository) OrgChanges(ctx context.Context, id string, lastSequence uint64, limit uint64, sortAscending bool, auditLogRetention time.Duration) (*org_model.OrgChanges, error) { changes, err := repo.getOrgChanges(ctx, id, lastSequence, limit, sortAscending, auditLogRetention) if err != nil { diff --git a/internal/management/repository/eventsourcing/handler/handler.go b/internal/management/repository/eventsourcing/handler/handler.go index d8c540581b..398bd223bc 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), - newOrgIAMPolicy( - handler{view, bulkLimit, configs.cycleDuration("OrgIAMPolicy"), errorCount, es}), newMailTemplate( handler{view, bulkLimit, configs.cycleDuration("MailTemplate"), errorCount, es}), newMessageText( diff --git a/internal/management/repository/eventsourcing/handler/org_iam_policy.go b/internal/management/repository/eventsourcing/handler/org_iam_policy.go deleted file mode 100644 index 1c9b5d13a5..0000000000 --- a/internal/management/repository/eventsourcing/handler/org_iam_policy.go +++ /dev/null @@ -1,109 +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" - "github.com/caos/zitadel/internal/org/repository/eventsourcing/model" -) - -const ( - orgIAMPolicyTable = "management.org_iam_policies" -) - -type OrgIAMPolicy struct { - handler - subscription *v1.Subscription -} - -func newOrgIAMPolicy(handler handler) *OrgIAMPolicy { - h := &OrgIAMPolicy{ - handler: handler, - } - - h.subscribe() - - return h -} - -func (m *OrgIAMPolicy) subscribe() { - m.subscription = m.es.Subscribe(m.AggregateTypes()...) - go func() { - for event := range m.subscription.Events { - query.ReduceEvent(m, event) - } - }() -} - -func (m *OrgIAMPolicy) ViewModel() string { - return orgIAMPolicyTable -} - -func (m *OrgIAMPolicy) Subscription() *v1.Subscription { - return m.subscription -} - -func (_ *OrgIAMPolicy) AggregateTypes() []es_models.AggregateType { - return []es_models.AggregateType{model.OrgAggregate, iam_es_model.IAMAggregate} -} - -func (p *OrgIAMPolicy) CurrentSequence() (uint64, error) { - sequence, err := p.view.GetLatestOrgIAMPolicySequence() - if err != nil { - return 0, err - } - return sequence.CurrentSequence, nil -} - -func (m *OrgIAMPolicy) EventQuery() (*es_models.SearchQuery, error) { - sequence, err := m.view.GetLatestOrgIAMPolicySequence() - if err != nil { - return nil, err - } - return es_models.NewSearchQuery(). - AggregateTypeFilter(m.AggregateTypes()...). - LatestSequenceFilter(sequence.CurrentSequence), nil -} - -func (m *OrgIAMPolicy) Reduce(event *es_models.Event) (err error) { - switch event.AggregateType { - case model.OrgAggregate, iam_es_model.IAMAggregate: - err = m.processOrgIAMPolicy(event) - } - return err -} - -func (m *OrgIAMPolicy) processOrgIAMPolicy(event *es_models.Event) (err error) { - policy := new(iam_model.OrgIAMPolicyView) - switch event.Type { - case iam_es_model.OrgIAMPolicyAdded, model.OrgIAMPolicyAdded: - err = policy.AppendEvent(event) - case iam_es_model.OrgIAMPolicyChanged, model.OrgIAMPolicyChanged: - policy, err = m.view.OrgIAMPolicyByAggregateID(event.AggregateID) - if err != nil { - return err - } - err = policy.AppendEvent(event) - case model.OrgIAMPolicyRemoved: - return m.view.DeleteOrgIAMPolicy(event.AggregateID, event) - default: - return m.view.ProcessedOrgIAMPolicySequence(event) - } - if err != nil { - return err - } - return m.view.PutOrgIAMPolicy(policy, event) -} - -func (m *OrgIAMPolicy) OnError(event *es_models.Event, err error) error { - logging.LogWithFields("SPOOL-3Gf9s", "id", event.AggregateID).WithError(err).Warn("something went wrong in orgIAM policy handler") - return spooler.HandleError(event, err, m.view.GetLatestOrgIAMPolicyFailedEvent, m.view.ProcessedOrgIAMPolicyFailedEvent, m.view.ProcessedOrgIAMPolicySequence, m.errorCountUntilSkip) -} - -func (o *OrgIAMPolicy) OnSuccess() error { - return spooler.HandleSuccess(o.view.UpdateOrgIAMPolicySpoolerRunTimestamp) -} diff --git a/internal/management/repository/eventsourcing/view/org_iam_policy.go b/internal/management/repository/eventsourcing/view/org_iam_policy.go deleted file mode 100644 index 3d0409d486..0000000000 --- a/internal/management/repository/eventsourcing/view/org_iam_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 ( - orgIAMPolicyTable = "management.org_iam_policies" -) - -func (v *View) OrgIAMPolicyByAggregateID(aggregateID string) (*model.OrgIAMPolicyView, error) { - return view.GetOrgIAMPolicyByAggregateID(v.Db, orgIAMPolicyTable, aggregateID) -} - -func (v *View) PutOrgIAMPolicy(policy *model.OrgIAMPolicyView, event *models.Event) error { - err := view.PutOrgIAMPolicy(v.Db, orgIAMPolicyTable, policy) - if err != nil { - return err - } - return v.ProcessedOrgIAMPolicySequence(event) -} - -func (v *View) DeleteOrgIAMPolicy(aggregateID string, event *models.Event) error { - err := view.DeleteOrgIAMPolicy(v.Db, orgIAMPolicyTable, aggregateID) - if err != nil && !errors.IsNotFound(err) { - return err - } - return v.ProcessedOrgIAMPolicySequence(event) -} - -func (v *View) GetLatestOrgIAMPolicySequence() (*global_view.CurrentSequence, error) { - return v.latestSequence(orgIAMPolicyTable) -} - -func (v *View) ProcessedOrgIAMPolicySequence(event *models.Event) error { - return v.saveCurrentSequence(orgIAMPolicyTable, event) -} - -func (v *View) UpdateOrgIAMPolicySpoolerRunTimestamp() error { - return v.updateSpoolerRunSequence(orgIAMPolicyTable) -} - -func (v *View) GetLatestOrgIAMPolicyFailedEvent(sequence uint64) (*global_view.FailedEvent, error) { - return v.latestFailedEvent(orgIAMPolicyTable, sequence) -} - -func (v *View) ProcessedOrgIAMPolicyFailedEvent(failedEvent *global_view.FailedEvent) error { - return v.saveFailedEvent(failedEvent) -} diff --git a/internal/management/repository/org.go b/internal/management/repository/org.go index 87d9a53f5e..75a35fddb8 100644 --- a/internal/management/repository/org.go +++ b/internal/management/repository/org.go @@ -23,8 +23,6 @@ type OrgRepository interface { SearchIDPConfigs(ctx context.Context, request *iam_model.IDPConfigSearchRequest) (*iam_model.IDPConfigSearchResponse, error) IDPConfigByID(ctx context.Context, id string) (*iam_model.IDPConfigView, error) - GetMyOrgIamPolicy(ctx context.Context) (*iam_model.OrgIAMPolicyView, error) - SearchIDPProviders(ctx context.Context, request *iam_model.IDPProviderSearchRequest) (*iam_model.IDPProviderSearchResponse, error) GetIDPProvidersByIDPConfigID(ctx context.Context, aggregateID, idpConfigID string) ([]*iam_model.IDPProviderView, error) diff --git a/internal/query/org_iam_policy.go b/internal/query/org_iam_policy.go new file mode 100644 index 0000000000..a982c96de5 --- /dev/null +++ b/internal/query/org_iam_policy.go @@ -0,0 +1,126 @@ +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 OrgIAMPolicy struct { + ID string + Sequence uint64 + CreationDate time.Time + ChangeDate time.Time + ResourceOwner string + State domain.PolicyState + + UserLoginMustBeDomain bool + + IsDefault bool +} + +var ( + orgIAMTable = table{ + name: projection.OrgIAMPolicyTable, + } + OrgIAMColID = Column{ + name: projection.OrgIAMPolicyIDCol, + } + OrgIAMColSequence = Column{ + name: projection.OrgIAMPolicySequenceCol, + } + OrgIAMColCreationDate = Column{ + name: projection.OrgIAMPolicyCreationDateCol, + } + OrgIAMColChangeDate = Column{ + name: projection.OrgIAMPolicyChangeDateCol, + } + OrgIAMColResourceOwner = Column{ + name: projection.OrgIAMPolicyResourceOwnerCol, + } + OrgIAMColUserLoginMustBeDomain = Column{ + name: projection.OrgIAMPolicyUserLoginMustBeDomainCol, + } + OrgIAMColIsDefault = Column{ + name: projection.OrgIAMPolicyIsDefaultCol, + } + OrgIAMColState = Column{ + name: projection.OrgIAMPolicyStateCol, + } +) + +func (q *Queries) OrgIAMPolicyByOrg(ctx context.Context, orgID string) (*OrgIAMPolicy, error) { + stmt, scan := prepareOrgIAMPolicyQuery() + query, args, err := stmt.Where( + sq.Or{ + sq.Eq{ + OrgIAMColID.identifier(): orgID, + }, + sq.Eq{ + OrgIAMColID.identifier(): q.iamID, + }, + }). + OrderBy(OrgIAMColIsDefault.identifier()). + Limit(1).ToSql() + if err != nil { + return nil, errors.ThrowInternal(err, "QUERY-D3CqT", "Errors.Query.SQLStatement") + } + + row := q.client.QueryRowContext(ctx, query, args...) + return scan(row) +} + +func (q *Queries) DefaultOrgIAMPolicy(ctx context.Context) (*OrgIAMPolicy, error) { + stmt, scan := prepareOrgIAMPolicyQuery() + query, args, err := stmt.Where(sq.Eq{ + OrgIAMColID.identifier(): q.iamID, + }). + OrderBy(OrgIAMColIsDefault.identifier()). + Limit(1).ToSql() + if err != nil { + return nil, errors.ThrowInternal(err, "QUERY-pM7lP", "Errors.Query.SQLStatement") + } + + row := q.client.QueryRowContext(ctx, query, args...) + return scan(row) +} + +func prepareOrgIAMPolicyQuery() (sq.SelectBuilder, func(*sql.Row) (*OrgIAMPolicy, error)) { + return sq.Select( + OrgIAMColID.identifier(), + OrgIAMColSequence.identifier(), + OrgIAMColCreationDate.identifier(), + OrgIAMColChangeDate.identifier(), + OrgIAMColResourceOwner.identifier(), + OrgIAMColUserLoginMustBeDomain.identifier(), + OrgIAMColIsDefault.identifier(), + OrgIAMColState.identifier(), + ). + From(orgIAMTable.identifier()).PlaceholderFormat(sq.Dollar), + func(row *sql.Row) (*OrgIAMPolicy, error) { + policy := new(OrgIAMPolicy) + err := row.Scan( + &policy.ID, + &policy.Sequence, + &policy.CreationDate, + &policy.ChangeDate, + &policy.ResourceOwner, + &policy.UserLoginMustBeDomain, + &policy.IsDefault, + &policy.State, + ) + if err != nil { + if errs.Is(err, sql.ErrNoRows) { + return nil, errors.ThrowNotFound(err, "QUERY-K0Jr5", "Errors.OrgIAMPolicy.NotFound") + } + return nil, errors.ThrowInternal(err, "QUERY-rIy6j", "Errors.Internal") + } + return policy, nil + } +} diff --git a/internal/query/projection/org_iam_policy.go b/internal/query/projection/org_iam_policy.go new file mode 100644 index 0000000000..325d264331 --- /dev/null +++ b/internal/query/projection/org_iam_policy.go @@ -0,0 +1,142 @@ +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 OrgIAMPolicyProjection struct { + crdb.StatementHandler +} + +const ( + OrgIAMPolicyTable = "zitadel.projections.org_iam_policies" + + OrgIAMPolicyCreationDateCol = "creation_date" + OrgIAMPolicyChangeDateCol = "change_date" + OrgIAMPolicySequenceCol = "sequence" + OrgIAMPolicyIDCol = "id" + OrgIAMPolicyStateCol = "state" + OrgIAMPolicyUserLoginMustBeDomainCol = "user_login_must_be_domain" + OrgIAMPolicyIsDefaultCol = "is_default" + OrgIAMPolicyResourceOwnerCol = "resource_owner" +) + +func NewOrgIAMPolicyProjection(ctx context.Context, config crdb.StatementHandlerConfig) *OrgIAMPolicyProjection { + p := &OrgIAMPolicyProjection{} + config.ProjectionName = OrgIAMPolicyTable + config.Reducers = p.reducers() + p.StatementHandler = crdb.NewStatementHandler(ctx, config) + return p +} + +func (p *OrgIAMPolicyProjection) reducers() []handler.AggregateReducer { + return []handler.AggregateReducer{ + { + Aggregate: org.AggregateType, + EventRedusers: []handler.EventReducer{ + { + Event: org.OrgIAMPolicyAddedEventType, + Reduce: p.reduceAdded, + }, + { + Event: org.OrgIAMPolicyChangedEventType, + Reduce: p.reduceChanged, + }, + { + Event: org.OrgIAMPolicyRemovedEventType, + Reduce: p.reduceRemoved, + }, + }, + }, + { + Aggregate: iam.AggregateType, + EventRedusers: []handler.EventReducer{ + { + Event: iam.OrgIAMPolicyAddedEventType, + Reduce: p.reduceAdded, + }, + { + Event: iam.OrgIAMPolicyChangedEventType, + Reduce: p.reduceChanged, + }, + }, + }, + } +} + +func (p *OrgIAMPolicyProjection) reduceAdded(event eventstore.EventReader) (*handler.Statement, error) { + var policyEvent policy.OrgIAMPolicyAddedEvent + var isDefault bool + switch e := event.(type) { + case *org.OrgIAMPolicyAddedEvent: + policyEvent = e.OrgIAMPolicyAddedEvent + isDefault = false + case *iam.OrgIAMPolicyAddedEvent: + policyEvent = e.OrgIAMPolicyAddedEvent + isDefault = true + default: + logging.LogWithFields("PROJE-XakxJ", "seq", event.Sequence(), "expectedTypes", []eventstore.EventType{org.OrgIAMPolicyAddedEventType, iam.OrgIAMPolicyAddedEventType}).Error("wrong event type") + return nil, errors.ThrowInvalidArgument(nil, "PROJE-CSE7A", "reduce.wrong.event.type") + } + return crdb.NewCreateStatement( + &policyEvent, + []handler.Column{ + handler.NewCol(OrgIAMPolicyCreationDateCol, policyEvent.CreationDate()), + handler.NewCol(OrgIAMPolicyChangeDateCol, policyEvent.CreationDate()), + handler.NewCol(OrgIAMPolicySequenceCol, policyEvent.Sequence()), + handler.NewCol(OrgIAMPolicyIDCol, policyEvent.Aggregate().ID), + handler.NewCol(OrgIAMPolicyStateCol, domain.PolicyStateActive), + handler.NewCol(OrgIAMPolicyUserLoginMustBeDomainCol, policyEvent.UserLoginMustBeDomain), + handler.NewCol(OrgIAMPolicyIsDefaultCol, isDefault), + handler.NewCol(OrgIAMPolicyResourceOwnerCol, policyEvent.Aggregate().ResourceOwner), + }), nil +} + +func (p *OrgIAMPolicyProjection) reduceChanged(event eventstore.EventReader) (*handler.Statement, error) { + var policyEvent policy.OrgIAMPolicyChangedEvent + switch e := event.(type) { + case *org.OrgIAMPolicyChangedEvent: + policyEvent = e.OrgIAMPolicyChangedEvent + case *iam.OrgIAMPolicyChangedEvent: + policyEvent = e.OrgIAMPolicyChangedEvent + default: + logging.LogWithFields("PROJE-SvTK0", "seq", event.Sequence(), "expectedTypes", []eventstore.EventType{org.OrgIAMPolicyChangedEventType, iam.OrgIAMPolicyChangedEventType}).Error("wrong event type") + return nil, errors.ThrowInvalidArgument(nil, "PROJE-qgVug", "reduce.wrong.event.type") + } + cols := []handler.Column{ + handler.NewCol(OrgIAMPolicyChangeDateCol, policyEvent.CreationDate()), + handler.NewCol(OrgIAMPolicySequenceCol, policyEvent.Sequence()), + } + if policyEvent.UserLoginMustBeDomain != nil { + cols = append(cols, handler.NewCol(OrgIAMPolicyUserLoginMustBeDomainCol, *policyEvent.UserLoginMustBeDomain)) + } + return crdb.NewUpdateStatement( + &policyEvent, + cols, + []handler.Condition{ + handler.NewCond(OrgIAMPolicyIDCol, policyEvent.Aggregate().ID), + }), nil +} + +func (p *OrgIAMPolicyProjection) reduceRemoved(event eventstore.EventReader) (*handler.Statement, error) { + policyEvent, ok := event.(*org.OrgIAMPolicyRemovedEvent) + if !ok { + logging.LogWithFields("PROJE-ovQya", "seq", event.Sequence(), "expectedType", org.OrgIAMPolicyRemovedEventType).Error("wrong event type") + return nil, errors.ThrowInvalidArgument(nil, "PROJE-JAENd", "reduce.wrong.event.type") + } + return crdb.NewDeleteStatement( + policyEvent, + []handler.Condition{ + handler.NewCond(OrgIAMPolicyIDCol, policyEvent.Aggregate().ID), + }), nil +} diff --git a/internal/query/projection/org_iam_policy_test.go b/internal/query/projection/org_iam_policy_test.go new file mode 100644 index 0000000000..1ca84e698c --- /dev/null +++ b/internal/query/projection/org_iam_policy_test.go @@ -0,0 +1,202 @@ +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 TestOrgIAMPolicyProjection_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.OrgIAMPolicyAddedEventType), + org.AggregateType, + []byte(`{ + "userLoginMustBeDomain": true +}`), + ), org.OrgIAMPolicyAddedEventMapper), + }, + reduce: (&OrgIAMPolicyProjection{}).reduceAdded, + want: wantReduce{ + aggregateType: eventstore.AggregateType("org"), + sequence: 15, + previousSequence: 10, + projection: OrgIAMPolicyTable, + executer: &testExecuter{ + executions: []execution{ + { + expectedStmt: "INSERT INTO zitadel.projections.org_iam_policies (creation_date, change_date, sequence, id, state, user_login_must_be_domain, is_default, resource_owner) VALUES ($1, $2, $3, $4, $5, $6, $7, $8)", + expectedArgs: []interface{}{ + anyArg{}, + anyArg{}, + uint64(15), + "agg-id", + domain.PolicyStateActive, + true, + false, + "ro-id", + }, + }, + }, + }, + }, + }, + { + name: "org.reduceChanged", + reduce: (&OrgIAMPolicyProjection{}).reduceChanged, + args: args{ + event: getEvent(testEvent( + repository.EventType(org.OrgIAMPolicyChangedEventType), + org.AggregateType, + []byte(`{ + "userLoginMustBeDomain": true + }`), + ), org.OrgIAMPolicyChangedEventMapper), + }, + want: wantReduce{ + aggregateType: eventstore.AggregateType("org"), + sequence: 15, + previousSequence: 10, + projection: OrgIAMPolicyTable, + executer: &testExecuter{ + executions: []execution{ + { + expectedStmt: "UPDATE zitadel.projections.org_iam_policies SET (change_date, sequence, user_login_must_be_domain) = ($1, $2, $3) WHERE (id = $4)", + expectedArgs: []interface{}{ + anyArg{}, + uint64(15), + true, + "agg-id", + }, + }, + }, + }, + }, + }, + { + name: "org.reduceRemoved", + reduce: (&OrgIAMPolicyProjection{}).reduceRemoved, + args: args{ + event: getEvent(testEvent( + repository.EventType(org.OrgIAMPolicyRemovedEventType), + org.AggregateType, + nil, + ), org.OrgIAMPolicyRemovedEventMapper), + }, + want: wantReduce{ + aggregateType: eventstore.AggregateType("org"), + sequence: 15, + previousSequence: 10, + projection: OrgIAMPolicyTable, + executer: &testExecuter{ + executions: []execution{ + { + expectedStmt: "DELETE FROM zitadel.projections.org_iam_policies WHERE (id = $1)", + expectedArgs: []interface{}{ + "agg-id", + }, + }, + }, + }, + }, + }, + { + name: "iam.reduceAdded", + reduce: (&OrgIAMPolicyProjection{}).reduceAdded, + args: args{ + event: getEvent(testEvent( + repository.EventType(iam.OrgIAMPolicyAddedEventType), + iam.AggregateType, + []byte(`{ + "userLoginMustBeDomain": true + }`), + ), iam.OrgIAMPolicyAddedEventMapper), + }, + want: wantReduce{ + aggregateType: eventstore.AggregateType("iam"), + sequence: 15, + previousSequence: 10, + projection: OrgIAMPolicyTable, + executer: &testExecuter{ + executions: []execution{ + { + expectedStmt: "INSERT INTO zitadel.projections.org_iam_policies (creation_date, change_date, sequence, id, state, user_login_must_be_domain, is_default, resource_owner) VALUES ($1, $2, $3, $4, $5, $6, $7, $8)", + expectedArgs: []interface{}{ + anyArg{}, + anyArg{}, + uint64(15), + "agg-id", + domain.PolicyStateActive, + true, + true, + "ro-id", + }, + }, + }, + }, + }, + }, + { + name: "iam.reduceChanged", + reduce: (&OrgIAMPolicyProjection{}).reduceChanged, + args: args{ + event: getEvent(testEvent( + repository.EventType(iam.OrgIAMPolicyChangedEventType), + iam.AggregateType, + []byte(`{ + "userLoginMustBeDomain": true + }`), + ), iam.OrgIAMPolicyChangedEventMapper), + }, + want: wantReduce{ + aggregateType: eventstore.AggregateType("iam"), + sequence: 15, + previousSequence: 10, + projection: OrgIAMPolicyTable, + executer: &testExecuter{ + executions: []execution{ + { + expectedStmt: "UPDATE zitadel.projections.org_iam_policies SET (change_date, sequence, user_login_must_be_domain) = ($1, $2, $3) WHERE (id = $4)", + expectedArgs: []interface{}{ + anyArg{}, + uint64(15), + 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 63b5c3dfb7..e8deea60f0 100644 --- a/internal/query/projection/projection.go +++ b/internal/query/projection/projection.go @@ -41,6 +41,7 @@ func Start(ctx context.Context, sqlClient *sql.DB, es *eventstore.Eventstore, co 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"])) + NewOrgIAMPolicyProjection(ctx, applyCustomConfig(projectionConfig, config.Customizations["org_iam_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/external_login_handler.go b/internal/ui/login/handler/external_login_handler.go index 98f7a10769..42be95a169 100644 --- a/internal/ui/login/handler/external_login_handler.go +++ b/internal/ui/login/handler/external_login_handler.go @@ -17,6 +17,7 @@ import ( "github.com/caos/zitadel/internal/errors" caos_errors "github.com/caos/zitadel/internal/errors" iam_model "github.com/caos/zitadel/internal/iam/model" + "github.com/caos/zitadel/internal/query" ) const ( @@ -346,7 +347,7 @@ func (l *Login) mapTokenToLoginUser(tokens *oidc.Tokens, idpConfig *iam_model.ID } return externalUser } -func (l *Login) mapExternalUserToLoginUser(orgIamPolicy *iam_model.OrgIAMPolicyView, linkingUser *domain.ExternalUser, idpConfig *iam_model.IDPConfigView) (*domain.Human, *domain.ExternalIDP, []*domain.Metadata) { +func (l *Login) mapExternalUserToLoginUser(orgIamPolicy *query.OrgIAMPolicy, linkingUser *domain.ExternalUser, idpConfig *iam_model.IDPConfigView) (*domain.Human, *domain.ExternalIDP, []*domain.Metadata) { username := linkingUser.PreferredUsername switch idpConfig.OIDCUsernameMapping { case iam_model.OIDCMappingFieldEmail: diff --git a/internal/ui/login/handler/external_register_handler.go b/internal/ui/login/handler/external_register_handler.go index 55fd792c19..992d83c28b 100644 --- a/internal/ui/login/handler/external_register_handler.go +++ b/internal/ui/login/handler/external_register_handler.go @@ -11,6 +11,7 @@ import ( http_mw "github.com/caos/zitadel/internal/api/http/middleware" "github.com/caos/zitadel/internal/domain" iam_model "github.com/caos/zitadel/internal/iam/model" + "github.com/caos/zitadel/internal/query" ) const ( @@ -145,7 +146,7 @@ func (l *Login) registerExternalUser(w http.ResponseWriter, r *http.Request, aut l.renderNextStep(w, r, authReq) } -func (l *Login) renderExternalRegisterOverview(w http.ResponseWriter, r *http.Request, authReq *domain.AuthRequest, orgIAMPolicy *iam_model.OrgIAMPolicyView, human *domain.Human, idp *domain.ExternalIDP, err error) { +func (l *Login) renderExternalRegisterOverview(w http.ResponseWriter, r *http.Request, authReq *domain.AuthRequest, orgIAMPolicy *query.OrgIAMPolicy, human *domain.Human, idp *domain.ExternalIDP, err error) { var errID, errMessage string if err != nil { errID, errMessage = l.getErrorMessage(r, err) @@ -215,7 +216,7 @@ func (l *Login) handleExternalRegisterCheck(w http.ResponseWriter, r *http.Reque l.renderNextStep(w, r, authReq) } -func (l *Login) mapTokenToLoginHumanAndExternalIDP(orgIamPolicy *iam_model.OrgIAMPolicyView, tokens *oidc.Tokens, idpConfig *iam_model.IDPConfigView) (*domain.Human, *domain.ExternalIDP) { +func (l *Login) mapTokenToLoginHumanAndExternalIDP(orgIamPolicy *query.OrgIAMPolicy, tokens *oidc.Tokens, idpConfig *iam_model.IDPConfigView) (*domain.Human, *domain.ExternalIDP) { username := tokens.IDTokenClaims.GetPreferredUsername() switch idpConfig.OIDCUsernameMapping { case iam_model.OIDCMappingFieldEmail: diff --git a/internal/ui/login/handler/policy_handler.go b/internal/ui/login/handler/policy_handler.go index 5d0c92ccd0..846dd1d320 100644 --- a/internal/ui/login/handler/policy_handler.go +++ b/internal/ui/login/handler/policy_handler.go @@ -1,19 +1,21 @@ package handler import ( - iam_model "github.com/caos/zitadel/internal/iam/model" "net/http" + + iam_model "github.com/caos/zitadel/internal/iam/model" + "github.com/caos/zitadel/internal/query" ) -func (l *Login) getDefaultOrgIamPolicy(r *http.Request) (*iam_model.OrgIAMPolicyView, error) { - return l.authRepo.GetDefaultOrgIAMPolicy(r.Context()) +func (l *Login) getDefaultOrgIamPolicy(r *http.Request) (*query.OrgIAMPolicy, error) { + return l.query.DefaultOrgIAMPolicy(r.Context()) } -func (l *Login) getOrgIamPolicy(r *http.Request, orgID string) (*iam_model.OrgIAMPolicyView, error) { +func (l *Login) getOrgIamPolicy(r *http.Request, orgID string) (*query.OrgIAMPolicy, error) { if orgID == "" { - return l.authRepo.GetDefaultOrgIAMPolicy(r.Context()) + return l.query.DefaultOrgIAMPolicy(r.Context()) } - return l.authRepo.GetOrgIAMPolicy(r.Context(), orgID) + return l.query.OrgIAMPolicyByOrg(r.Context(), orgID) } func (l *Login) getIDPConfigByID(r *http.Request, idpConfigID string) (*iam_model.IDPConfigView, error) { diff --git a/internal/ui/login/handler/register_org_handler.go b/internal/ui/login/handler/register_org_handler.go index 6cf11384e0..ea609fa9bb 100644 --- a/internal/ui/login/handler/register_org_handler.go +++ b/internal/ui/login/handler/register_org_handler.go @@ -106,10 +106,10 @@ func (l *Login) renderRegisterOrg(w http.ResponseWriter, r *http.Request, authRe data.HasNumber = NumberRegex } } - orgPolicy, err := l.getDefaultOrgIamPolicy(r) + orgPolicy, _ := l.getDefaultOrgIamPolicy(r) if orgPolicy != nil { data.UserLoginMustBeDomain = orgPolicy.UserLoginMustBeDomain - data.IamDomain = orgPolicy.IAMDomain + data.IamDomain = l.iamDomain } translator := l.getTranslator(authRequest) diff --git a/migrations/cockroach/V1.84__org_iam_policy.sql b/migrations/cockroach/V1.84__org_iam_policy.sql new file mode 100644 index 0000000000..1a19175810 --- /dev/null +++ b/migrations/cockroach/V1.84__org_iam_policy.sql @@ -0,0 +1,13 @@ +CREATE TABLE zitadel.projections.org_iam_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, + user_login_must_be_domain BOOLEAN, + + PRIMARY KEY (id) +); \ No newline at end of file