From b204ad2aca5afa5018618fcb837aff9a64fc5996 Mon Sep 17 00:00:00 2001 From: Silvan Date: Thu, 21 Oct 2021 10:01:08 +0200 Subject: [PATCH] fix(queries): org iam policy (#2432) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * statement in seperate file * move handlers * move query/old to query * handler * read models * bulk works * cleanup * contrib * rename readmodel to projection * rename read_models schema to projections * rename read_models schema to projections * search query as func, bulk iterates as long as new events * add event sequence less query * update checks for events between current sequence and sequence of first statement if it has previous sequence 0 * cleanup crdb projection * refactor projection handler * start with testing * tests for handler * remove todo * refactor statement: remove table name, add tests * improve projection handler shutdown, no savepoint if noop stmt, tests for stmt handler * tests * start failed events * seperate branch for contrib * move statement constructors to crdb pkg * correct import * Subscribe for eventtypes (#1800) * fix: is default (#1737) * fix: use email as username on global org (#1738) * fix: use email as username on global org * Update user_human.go * Update register_handler.go * chore(deps): update docusaurus (#1739) * chore: remove PAT and use GH Token (#1716) * chore: remove PAT and use GH Token * fix env * fix env * fix env * md lint * trigger ci * change user * fix GH bug * replace login part * chore: add GH Token to sem rel (#1746) * chore: add GH Token to sem rel * try branch * add GH Token * remove test branch again * docs: changes acme to acme-caos (#1744) * changes acme to acme-caos * Apply suggestions from code review Co-authored-by: Florian Forster Co-authored-by: Maximilian Panne Co-authored-by: Florian Forster * feat: add additional origins on applications (#1691) * feat: add additional origins on applications * app additional redirects * chore(deps-dev): bump @angular/cli from 11.2.8 to 11.2.11 in /console (#1706) * fix: show org with regex (#1688) * fix: flag mapping (#1699) * chore(deps-dev): bump @angular/cli from 11.2.8 to 11.2.11 in /console Bumps [@angular/cli](https://github.com/angular/angular-cli) from 11.2.8 to 11.2.11. - [Release notes](https://github.com/angular/angular-cli/releases) - [Commits](https://github.com/angular/angular-cli/compare/v11.2.8...v11.2.11) Signed-off-by: dependabot[bot] Co-authored-by: Max Peintner Co-authored-by: Silvan Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> * chore(deps-dev): bump stylelint from 13.10.0 to 13.13.1 in /console (#1703) * fix: show org with regex (#1688) * fix: flag mapping (#1699) * chore(deps-dev): bump stylelint from 13.10.0 to 13.13.1 in /console Bumps [stylelint](https://github.com/stylelint/stylelint) from 13.10.0 to 13.13.1. - [Release notes](https://github.com/stylelint/stylelint/releases) - [Changelog](https://github.com/stylelint/stylelint/blob/master/CHANGELOG.md) - [Commits](https://github.com/stylelint/stylelint/compare/13.10.0...13.13.1) Signed-off-by: dependabot[bot] Co-authored-by: Max Peintner Co-authored-by: Silvan Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> * chore(deps-dev): bump @types/node from 14.14.37 to 15.0.1 in /console (#1702) * fix: show org with regex (#1688) * fix: flag mapping (#1699) * chore(deps-dev): bump @types/node from 14.14.37 to 15.0.1 in /console Bumps [@types/node](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/HEAD/types/node) from 14.14.37 to 15.0.1. - [Release notes](https://github.com/DefinitelyTyped/DefinitelyTyped/releases) - [Commits](https://github.com/DefinitelyTyped/DefinitelyTyped/commits/HEAD/types/node) Signed-off-by: dependabot[bot] Co-authored-by: Max Peintner Co-authored-by: Silvan Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> * chore(deps): bump ts-protoc-gen from 0.14.0 to 0.15.0 in /console (#1701) * fix: show org with regex (#1688) * fix: flag mapping (#1699) * chore(deps): bump ts-protoc-gen from 0.14.0 to 0.15.0 in /console Bumps [ts-protoc-gen](https://github.com/improbable-eng/ts-protoc-gen) from 0.14.0 to 0.15.0. - [Release notes](https://github.com/improbable-eng/ts-protoc-gen/releases) - [Changelog](https://github.com/improbable-eng/ts-protoc-gen/blob/master/CHANGELOG.md) - [Commits](https://github.com/improbable-eng/ts-protoc-gen/compare/0.14.0...0.15.0) Signed-off-by: dependabot[bot] Co-authored-by: Max Peintner Co-authored-by: Silvan Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> * chore(deps-dev): bump @types/jasmine from 3.6.9 to 3.6.10 in /console (#1682) Bumps [@types/jasmine](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/HEAD/types/jasmine) from 3.6.9 to 3.6.10. - [Release notes](https://github.com/DefinitelyTyped/DefinitelyTyped/releases) - [Commits](https://github.com/DefinitelyTyped/DefinitelyTyped/commits/HEAD/types/jasmine) Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> * chore(deps): bump @types/google-protobuf in /console (#1681) Bumps [@types/google-protobuf](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/HEAD/types/google-protobuf) from 3.7.4 to 3.15.2. - [Release notes](https://github.com/DefinitelyTyped/DefinitelyTyped/releases) - [Commits](https://github.com/DefinitelyTyped/DefinitelyTyped/commits/HEAD/types/google-protobuf) Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> * chore(deps): bump grpc from 1.24.5 to 1.24.7 in /console (#1666) Bumps [grpc](https://github.com/grpc/grpc-node) from 1.24.5 to 1.24.7. - [Release notes](https://github.com/grpc/grpc-node/releases) - [Commits](https://github.com/grpc/grpc-node/compare/grpc@1.24.5...grpc@1.24.7) Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> * lock * chore(deps-dev): bump @angular/language-service from 11.2.9 to 11.2.12 in /console (#1704) * fix: show org with regex (#1688) * fix: flag mapping (#1699) * chore(deps-dev): bump @angular/language-service in /console Bumps [@angular/language-service](https://github.com/angular/angular/tree/HEAD/packages/language-service) from 11.2.9 to 11.2.12. - [Release notes](https://github.com/angular/angular/releases) - [Changelog](https://github.com/angular/angular/blob/master/CHANGELOG.md) - [Commits](https://github.com/angular/angular/commits/11.2.12/packages/language-service) Signed-off-by: dependabot[bot] Co-authored-by: Max Peintner Co-authored-by: Silvan Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> * package lock * downgrade grpc * downgrade protobuf types * revert npm packs 🥸 Co-authored-by: Max Peintner Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: Silvan * docs: update run and start section texts (#1745) * update run and start section texts * adds showcase Co-authored-by: Maximilian Panne * fix: additional origin list (#1753) * fix: handle api configs in authz handler (#1755) * fix(console): add model for api keys, fix toast, binding (#1757) * fix: add model for api keys, fix toast, binding * show api clientid * fix: missing patchvalue (#1758) * feat: refresh token (#1728) * begin refresh tokens * refresh tokens * list and revoke refresh tokens * handle remove * tests for refresh tokens * uniqueness and default expiration * rename oidc token methods * cleanup * migration version * Update internal/static/i18n/en.yaml Co-authored-by: Fabi <38692350+fgerschwiler@users.noreply.github.com> * fixes * feat: update oidc pkg for refresh tokens Co-authored-by: Fabi <38692350+fgerschwiler@users.noreply.github.com> * fix: correct json name of clientId in key.json (#1760) * fix: migration version (#1767) * start subscription * eventtypes * fix(login): links (#1778) * fix(login): href for help * fix(login): correct link to tos * fix: access tokens for service users and refresh token infos (#1779) * fix: access token for service user * handle info from refresh request * uniqueness * postpone access token uniqueness change * chore(coc): recommend code of conduct (#1782) * subscribe for events * feat(console): refresh toggle out of granttype context (#1785) * refresh toggle * disable if not code flow, lint * lint * fix: change oidc config order * accept refresh option within flow Co-authored-by: Livio Amstutz * fix: refresh token activation (#1795) * fix: oidc grant type check * docs: add offline_access scope * docs: update refresh token status in supported grant types * fix: update oidc pkg * fix: check refresh token grant type (#1796) * configuration structs * org admins * failed events * fixes Co-authored-by: Max Peintner Co-authored-by: Livio Amstutz Co-authored-by: Florian Forster Co-authored-by: mffap Co-authored-by: Maximilian Panne Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: Fabi <38692350+fgerschwiler@users.noreply.github.com> * remove comment * aggregate reducer * remove eventtypes * add protoc-get-validate to mod * fix transaltion * upsert * add gender on org admins, allow to retry failed stmts after configurable time * remove if * sub queries * fix: tests * add builder to tests * new search query * rename searchquerybuilder to builder * remove comment from code * test with multiple queries * add filters test * current sequences * make org and org_admins work again * add aggregate type to current sequence * fix(contibute): listing * add validate module * fix: search queries * feat(eventstore): previous aggregate root sequence (#1810) * feat(eventstore): previous aggregate root sequence * fix tests * fix: eventstore v1 test * add col to all mocked rows * next try * fix mig * rename aggregate root to aggregate type * update comment Co-authored-by: Livio Amstutz Co-authored-by: Livio Amstutz * small refactorings * allow update multiple current sequences * unique log id * fix migrations * rename org admin to org owner * improve error handling and logging * fix(migration): optimize prev agg root seq * fix: projection handler test * fix: sub queries * small fixes * additional event types * correct org owner projection * fix primary key * feat(eventstore): jobs for projections (#2026) * fix: template names in login (#1974) * fix: template names in login * fix: error.html * fix: check for features on mgmt only (#1976) * fix: add sentry in ui, http and projection handlers (#1977) * fix: add sentry in ui, http and projection handlers * fix test * fix(eventstore): sub queries (#1805) * sub queries * fix: tests * add builder to tests * new search query * rename searchquerybuilder to builder * remove comment from code * test with multiple queries * add filters test * fix(contibute): listing * add validate module * fix: search queries * remove unused event type in query * ignore query if error in marshal * go mod tidy * update privacy policy query * update queries Co-authored-by: Livio Amstutz * feat: Extend oidc idp with oauth endpoints (#1980) * feat: add oauth attributes to oidc idp configuration * feat: return idpconfig id on create idp * feat: tests * feat: descriptions * feat: docs * feat: tests * docs: update to beta 3 (#1984) * fix: role assertion (#1986) * fix: enum to display access token role assertion * improve assertion descriptions * fix nil pointer * docs: eventstore (#1982) * docs: eventstore * Apply suggestions from code review Co-authored-by: Florian Forster Co-authored-by: Florian Forster * fix(sentry): trigger sentry release (#1989) * feat(send sentry release): send sentry release * fix(moved step and added releasetag): moved step and added releasetag * fix: set version for sentry release (#1990) * feat(send sentry release): send sentry release * fix(moved step and added releasetag): moved step and added releasetag * fix(corrected var name): corrected var name Co-authored-by: Livio Amstutz * fix: log error reason on terminate session (#1973) * fix: return default language file, if requested lang does not exist for default login texts (#1988) * fix: return default language file, if requested lang doesnt exists * feat: read default translation file * feat: docs * fix: race condition in auth request unmarshalling (#1993) * feat: handle ui_locales in login (#1994) * fix: handle ui_locales in login * move supportedlanguage func into i18n package * update oidc pkg * fix: handle closed channels on unsubscribe (#1995) * fix: give restore more time (#1997) * fix: translation file read (#2009) * feat: translation file read * feat: readme * fix: enable idp add button for iam users (#2010) * fix: filter event_data (#2011) * feat: Custom message files (#1992) * feat: add get custom message text to admin api * feat: read custom message texts from files * feat: get languages in apis * feat: get languages in apis * feat: get languages in apis * feat: pr feedback * feat: docs * feat: merge main * fix: sms notification (#2013) * fix: phone verifications * feat: fix password reset as sms * fix: phone verification * fix: grpc status in sentry and validation interceptors (#2012) * fix: remove oauth endpoints from oidc config proto (#2014) * try with view * fix(console): disable sw (#2021) * fix: disable sw * angular.json disable sw * project projections * fix typos * customize projections * customizable projections, add change date to projects Co-authored-by: Livio Amstutz Co-authored-by: Max Peintner Co-authored-by: Fabi <38692350+fgerschwiler@users.noreply.github.com> Co-authored-by: Florian Forster Co-authored-by: mffap Co-authored-by: Christian Jakob <47860090+thesephirot@users.noreply.github.com> Co-authored-by: Elio Bischof * env file * typo * correct users * correct migration * fix: merge fail * fix test * fix(tests): unordered matcher * improve currentSequenceMatcher * correct certs * correct certs * add zitadel database on database list * refctor switch in match * enable all handlers * Delete io.env * cleanup * add handlers * rename view to projection * rename view to projection * fix type typo * remove unnecessary logs * refactor stmts * simplify interval calculation * fix tests * fix unlock test * fix migration * migs * fix(operator): update cockroach and flyway versions (#2138) * chore(deps): bump k8s.io/apiextensions-apiserver from 0.19.2 to 0.21.3 Bumps [k8s.io/apiextensions-apiserver](https://github.com/kubernetes/apiextensions-apiserver) from 0.19.2 to 0.21.3. - [Release notes](https://github.com/kubernetes/apiextensions-apiserver/releases) - [Commits](https://github.com/kubernetes/apiextensions-apiserver/compare/v0.19.2...v0.21.3) --- updated-dependencies: - dependency-name: k8s.io/apiextensions-apiserver dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * chore(deps): bump google.golang.org/api from 0.34.0 to 0.52.0 Bumps [google.golang.org/api](https://github.com/googleapis/google-api-go-client) from 0.34.0 to 0.52.0. - [Release notes](https://github.com/googleapis/google-api-go-client/releases) - [Changelog](https://github.com/googleapis/google-api-go-client/blob/master/CHANGES.md) - [Commits](https://github.com/googleapis/google-api-go-client/compare/v0.34.0...v0.52.0) --- updated-dependencies: - dependency-name: google.golang.org/api dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * start update dependencies * update mods and otlp * fix(build): update to go 1.16 * old version for k8s mods * update k8s versions * update orbos * fix(operator): update cockroach and flyway version * Update images.go Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: Stefan Benz * fix import * fix typo * fix(migration): add org projection * fix(projection): correct table for org events in org owners * better insert stmt * fix typo * fix typo * set max connection lifetime * set max conns and conn lifetime in eventstore v1 * configure sql connection settings * add mig for agg type index * fix replace tab in yaml * handler interfaces * subscription * first try * handler * move sql client initialization * first part implemented * removed all occurencies of org by id and search orgs * fix merge issues * cleanup code * fix: queries implements orgviewprovider * cleanup * refactor text comparison * remove unused file * remove unused code * log * remove unused code * remove unused field * remove unused file * refactor * tests for search query * remove try * simplify state change mappers * projection tests * query functions * move reusable objects to separate files * rename domain column to primar_domain * fix tests * add current sequence * remove log prints * fix tests * fix: verifier * fix test * rename domain col migrations * simplify search response * add custom column constructors * fix: org projection table const * fix: full column name * feat: text query extension * fix: tests for query * number query * add deprection message * projection * correct migration * projection * projection * column in a single place (#2416) * column in a single place * use projection for columns * query column with aliases * rename methods * remove unused code * column for current sequences * correct file name * global counter column * fix is org unique * query * fix wrong code * remove unused code * query * remove unused code * remove unused code * query * api * remove unused cod * remove unused code * remove unused code * remove unused code * fix(queries): org iam policy * fix: init provider * tests * tests * tests * tests * tests * fix: tests * migrations * fixes * errors * fix test * add converter option * fix(auth-repo): add queries to struct * error messages * rename method, correct log message * small fixes * correct version * correct version * fix(migration): set pk * correct version * fix test * cleanup code * fix interface * cleanup code * method name * cleanup code * cleanup code * rename method * remove comment Co-authored-by: Max Peintner Co-authored-by: Livio Amstutz Co-authored-by: Florian Forster Co-authored-by: mffap Co-authored-by: Maximilian Panne Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: Fabi <38692350+fgerschwiler@users.noreply.github.com> Co-authored-by: Christian Jakob <47860090+thesephirot@users.noreply.github.com> Co-authored-by: Elio Bischof Co-authored-by: Stefan Benz Co-authored-by: fabi --- .../eventsourcing/eventstore/iam.go | 26 --- .../eventsourcing/eventstore/org.go | 37 ---- .../eventsourcing/handler/handler.go | 2 - .../eventsourcing/handler/org_iam_policy.go | 110 ---------- .../repository/eventsourcing/repository.go | 5 - .../eventsourcing/view/org_iam_policy.go | 53 ----- internal/admin/repository/iam.go | 2 - internal/admin/repository/org.go | 11 - internal/admin/repository/repository.go | 1 - internal/api/grpc/admin/org_iam_policy.go | 4 +- internal/api/grpc/admin/server.go | 2 - internal/api/grpc/management/org.go | 2 +- internal/api/grpc/policy/org_iam_policy.go | 8 +- .../eventsourcing/eventstore/org.go | 21 -- .../eventsourcing/handler/handler.go | 2 - .../eventsourcing/handler/org_iam_policy.go | 110 ---------- .../repository/eventsourcing/repository.go | 1 + .../eventsourcing/view/org_iam_policy.go | 53 ----- internal/auth/repository/org.go | 2 - internal/iam/model/org_iam_policy_view.go | 47 ---- .../eventsourcing/model/org_iam_policy.go | 8 - .../model/org_iam_policy_test.go | 3 +- .../repository/view/model/org_iam_policy.go | 26 +-- .../view/model/org_iam_policy_query.go | 59 ----- .../repository/view/org_iam_policy_view.go | 32 --- .../eventsourcing/eventstore/org.go | 15 -- .../eventsourcing/handler/handler.go | 2 - .../eventsourcing/handler/org_iam_policy.go | 109 ---------- .../eventsourcing/view/org_iam_policy.go | 53 ----- internal/management/repository/org.go | 2 - internal/query/org_iam_policy.go | 126 +++++++++++ internal/query/projection/org_iam_policy.go | 142 ++++++++++++ .../query/projection/org_iam_policy_test.go | 202 ++++++++++++++++++ internal/query/projection/projection.go | 1 + .../login/handler/external_login_handler.go | 3 +- .../handler/external_register_handler.go | 5 +- internal/ui/login/handler/policy_handler.go | 14 +- .../ui/login/handler/register_org_handler.go | 4 +- .../cockroach/V1.84__org_iam_policy.sql | 13 ++ 39 files changed, 511 insertions(+), 807 deletions(-) delete mode 100644 internal/admin/repository/eventsourcing/eventstore/org.go delete mode 100644 internal/admin/repository/eventsourcing/handler/org_iam_policy.go delete mode 100644 internal/admin/repository/eventsourcing/view/org_iam_policy.go delete mode 100644 internal/admin/repository/org.go delete mode 100644 internal/auth/repository/eventsourcing/handler/org_iam_policy.go delete mode 100644 internal/auth/repository/eventsourcing/view/org_iam_policy.go delete mode 100644 internal/iam/model/org_iam_policy_view.go delete mode 100644 internal/iam/repository/view/model/org_iam_policy_query.go delete mode 100644 internal/iam/repository/view/org_iam_policy_view.go delete mode 100644 internal/management/repository/eventsourcing/handler/org_iam_policy.go delete mode 100644 internal/management/repository/eventsourcing/view/org_iam_policy.go create mode 100644 internal/query/org_iam_policy.go create mode 100644 internal/query/projection/org_iam_policy.go create mode 100644 internal/query/projection/org_iam_policy_test.go create mode 100644 migrations/cockroach/V1.84__org_iam_policy.sql diff --git a/internal/admin/repository/eventsourcing/eventstore/iam.go b/internal/admin/repository/eventsourcing/eventstore/iam.go index 55f0ded24..11a379a4d 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 44a5a5f37..000000000 --- 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 b0da90bad..34a72d1ab 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 5b32c8f6b..000000000 --- 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 ebffb31a3..cec4e5211 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 f9470821d..000000000 --- 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 a0d6a9e6d..3937b49ba 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 c27655093..000000000 --- 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 d93f893ba..61fbdad53 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 93a1cada0..c794a7c2d 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 e2106a3dd..45fb45d32 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 8c38fb722..b05ab03db 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 fd14b684a..5bc36af72 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 27edff210..b516603c3 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 1d34603c1..81e98e831 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 8357b5589..000000000 --- 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 63dd6569a..187a8e9f6 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 ec089700a..000000000 --- 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 4d593be27..4d8ff74a2 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 e944bc4ce..000000000 --- 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 e8ab09fd9..fa0ebcc59 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 c86fb532f..a713e7867 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 d40fcd548..d55fabc7c 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 48fc0a3c4..000000000 --- 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 64135173b..000000000 --- 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 0e99c936a..4c1f06320 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 d8c540581..398bd223b 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 1c9b5d13a..000000000 --- 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 3d0409d48..000000000 --- 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 87d9a53f5..75a35fddb 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 000000000..a982c96de --- /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 000000000..325d26433 --- /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 000000000..1ca84e698 --- /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 63b5c3dfb..e8deea60f 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 98f7a1076..42be95a16 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 55fd792c1..992d83c28 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 5d0c92ccd..846dd1d32 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 6cf11384e..ea609fa9b 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 000000000..1a1917581 --- /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