fix(queries): lockout policy (#2419)

* job queue

* wg improvements

* start handler

* statement

* statements

* imporve handler

* improve statement

* 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 <florian@caos.ch>

Co-authored-by: Maximilian Panne <maximilian.panne@gmail.com>
Co-authored-by: Florian Forster <florian@caos.ch>

* 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] <support@github.com>

Co-authored-by: Max Peintner <max@caos.ch>
Co-authored-by: Silvan <silvan.reusser@gmail.com>
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] <support@github.com>

Co-authored-by: Max Peintner <max@caos.ch>
Co-authored-by: Silvan <silvan.reusser@gmail.com>
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] <support@github.com>

Co-authored-by: Max Peintner <max@caos.ch>
Co-authored-by: Silvan <silvan.reusser@gmail.com>
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] <support@github.com>

Co-authored-by: Max Peintner <max@caos.ch>
Co-authored-by: Silvan <silvan.reusser@gmail.com>
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] <support@github.com>

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] <support@github.com>

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] <support@github.com>

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] <support@github.com>

Co-authored-by: Max Peintner <max@caos.ch>
Co-authored-by: Silvan <silvan.reusser@gmail.com>
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 <max@caos.ch>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Silvan <silvan.reusser@gmail.com>

* docs: update run and start section texts (#1745)

* update run and start section texts

* adds showcase

Co-authored-by: Maximilian Panne <maximilian.panne@gmail.com>

* 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 <livio.a@gmail.com>

* 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 <max@caos.ch>
Co-authored-by: Livio Amstutz <livio.a@gmail.com>
Co-authored-by: Florian Forster <florian@caos.ch>
Co-authored-by: mffap <mpa@caos.ch>
Co-authored-by: Maximilian Panne <maximilian.panne@gmail.com>
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 <livio.a@gmail.com>

Co-authored-by: Livio Amstutz <livio.a@gmail.com>

* 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 <livio.a@gmail.com>

* 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 <florian@caos.ch>

Co-authored-by: Florian Forster <florian@caos.ch>

* 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 <livio.a@gmail.com>

* 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 <livio.a@gmail.com>
Co-authored-by: Max Peintner <max@caos.ch>
Co-authored-by: Fabi <38692350+fgerschwiler@users.noreply.github.com>
Co-authored-by: Florian Forster <florian@caos.ch>
Co-authored-by: mffap <mpa@caos.ch>
Co-authored-by: Christian Jakob <47860090+thesephirot@users.noreply.github.com>
Co-authored-by: Elio Bischof <eliobischof@gmail.com>

* 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] <support@github.com>

* 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] <support@github.com>

* 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 <stefan@caos.ch>

* 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

* 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

* fix test

* cleanup code

Co-authored-by: Max Peintner <max@caos.ch>
Co-authored-by: Livio Amstutz <livio.a@gmail.com>
Co-authored-by: Florian Forster <florian@caos.ch>
Co-authored-by: mffap <mpa@caos.ch>
Co-authored-by: Maximilian Panne <maximilian.panne@gmail.com>
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 <eliobischof@gmail.com>
Co-authored-by: Stefan Benz <stefan@caos.ch>
Co-authored-by: fabi <fabienne.gerschwiler@gmail.com>
This commit is contained in:
Silvan 2021-10-20 16:28:24 +02:00 committed by GitHub
parent 9571dc51db
commit 40b7b5a804
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
29 changed files with 593 additions and 851 deletions

View File

@ -167,32 +167,6 @@ func (repo *IAMRepository) SearchDefaultIDPProviders(ctx context.Context, reques
return result, nil
}
func (repo *IAMRepository) GetDefaultLockoutPolicy(ctx context.Context) (*iam_model.LockoutPolicyView, error) {
policy, viewErr := repo.View.LockoutPolicyByAggregateID(repo.SystemDefaults.IamID)
if viewErr != nil && !caos_errs.IsNotFound(viewErr) {
return nil, viewErr
}
if caos_errs.IsNotFound(viewErr) {
policy = new(iam_es_model.LockoutPolicyView)
}
events, esErr := repo.getIAMEvents(ctx, policy.Sequence)
if caos_errs.IsNotFound(viewErr) && len(events) == 0 {
return nil, caos_errs.ThrowNotFound(nil, "EVENT-2M9oP", "Errors.IAM.LockoutPolicy.NotFound")
}
if esErr != nil {
logging.Log("EVENT-3M0xs").WithError(esErr).Debug("error retrieving new events")
return iam_es_model.LockoutViewToModel(policy), nil
}
policyCopy := *policy
for _, event := range events {
if err := policyCopy.AppendEvent(event); err != nil {
return iam_es_model.LockoutViewToModel(policy), nil
}
}
return iam_es_model.LockoutViewToModel(policy), nil
}
func (repo *IAMRepository) GetOrgIAMPolicy(ctx context.Context) (*iam_model.OrgIAMPolicyView, error) {
policy, viewErr := repo.View.OrgIAMPolicyByAggregateID(repo.SystemDefaults.IamID)
if viewErr != nil && !caos_errs.IsNotFound(viewErr) {

View File

@ -45,8 +45,6 @@ func Register(configs Configs, bulkLimit, errorCount uint64, view *view.View, es
newUser(
handler{view, bulkLimit, configs.cycleDuration("User"), errorCount, es},
defaults),
newLockoutPolicy(
handler{view, bulkLimit, configs.cycleDuration("LockoutPolicy"), errorCount, es}),
newOrgIAMPolicy(
handler{view, bulkLimit, configs.cycleDuration("OrgIAMPolicy"), errorCount, es}),
newExternalIDP(

View File

@ -1,110 +0,0 @@
package handler
import (
"github.com/caos/logging"
"github.com/caos/zitadel/internal/eventstore/v1"
iam_es_model "github.com/caos/zitadel/internal/iam/repository/eventsourcing/model"
es_models "github.com/caos/zitadel/internal/eventstore/v1/models"
"github.com/caos/zitadel/internal/eventstore/v1/query"
"github.com/caos/zitadel/internal/eventstore/v1/spooler"
iam_model "github.com/caos/zitadel/internal/iam/repository/view/model"
"github.com/caos/zitadel/internal/org/repository/eventsourcing/model"
)
const (
lockoutPolicyTable = "adminapi.lockout_policies"
)
type LockoutPolicy struct {
handler
subscription *v1.Subscription
}
func newLockoutPolicy(handler handler) *LockoutPolicy {
h := &LockoutPolicy{
handler: handler,
}
h.subscribe()
return h
}
func (p *LockoutPolicy) subscribe() {
p.subscription = p.es.Subscribe(p.AggregateTypes()...)
go func() {
for event := range p.subscription.Events {
query.ReduceEvent(p, event)
}
}()
}
func (p *LockoutPolicy) ViewModel() string {
return lockoutPolicyTable
}
func (m *LockoutPolicy) Subscription() *v1.Subscription {
return m.subscription
}
func (p *LockoutPolicy) AggregateTypes() []es_models.AggregateType {
return []es_models.AggregateType{model.OrgAggregate, iam_es_model.IAMAggregate}
}
func (p *LockoutPolicy) CurrentSequence() (uint64, error) {
sequence, err := p.view.GetLatestLockoutPolicySequence()
if err != nil {
return 0, err
}
return sequence.CurrentSequence, nil
}
func (p *LockoutPolicy) EventQuery() (*es_models.SearchQuery, error) {
sequence, err := p.view.GetLatestLockoutPolicySequence()
if err != nil {
return nil, err
}
return es_models.NewSearchQuery().
AggregateTypeFilter(p.AggregateTypes()...).
LatestSequenceFilter(sequence.CurrentSequence), nil
}
func (p *LockoutPolicy) Reduce(event *es_models.Event) (err error) {
switch event.AggregateType {
case model.OrgAggregate, iam_es_model.IAMAggregate:
err = p.processLockoutPolicy(event)
}
return err
}
func (p *LockoutPolicy) processLockoutPolicy(event *es_models.Event) (err error) {
policy := new(iam_model.LockoutPolicyView)
switch event.Type {
case iam_es_model.LockoutPolicyAdded, model.LockoutPolicyAdded:
err = policy.AppendEvent(event)
case iam_es_model.LockoutPolicyChanged, model.LockoutPolicyChanged:
policy, err = p.view.LockoutPolicyByAggregateID(event.AggregateID)
if err != nil {
return err
}
err = policy.AppendEvent(event)
case model.LockoutPolicyRemoved:
return p.view.DeleteLockoutPolicy(event.AggregateID, event)
default:
return p.view.ProcessedLockoutPolicySequence(event)
}
if err != nil {
return err
}
return p.view.PutLockoutPolicy(policy, event)
}
func (p *LockoutPolicy) OnError(event *es_models.Event, err error) error {
logging.LogWithFields("SPOOL-nD8sie", "id", event.AggregateID).WithError(err).Warn("something went wrong in Lockout policy handler")
return spooler.HandleError(event, err, p.view.GetLatestLockoutPolicyFailedEvent, p.view.ProcessedLockoutPolicyFailedEvent, p.view.ProcessedLockoutPolicySequence, p.errorCountUntilSkip)
}
func (p *LockoutPolicy) OnSuccess() error {
return spooler.HandleSuccess(p.view.UpdateLockoutPolicySpoolerRunTimestamp)
}

View File

@ -1,53 +0,0 @@
package view
import (
"github.com/caos/zitadel/internal/errors"
"github.com/caos/zitadel/internal/eventstore/v1/models"
"github.com/caos/zitadel/internal/iam/repository/view"
"github.com/caos/zitadel/internal/iam/repository/view/model"
global_view "github.com/caos/zitadel/internal/view/repository"
)
const (
lockoutPolicyTable = "adminapi.lockout_policies"
)
func (v *View) LockoutPolicyByAggregateID(aggregateID string) (*model.LockoutPolicyView, error) {
return view.GetLockoutPolicyByAggregateID(v.Db, lockoutPolicyTable, aggregateID)
}
func (v *View) PutLockoutPolicy(policy *model.LockoutPolicyView, event *models.Event) error {
err := view.PutLockoutPolicy(v.Db, lockoutPolicyTable, policy)
if err != nil {
return err
}
return v.ProcessedLockoutPolicySequence(event)
}
func (v *View) DeleteLockoutPolicy(aggregateID string, event *models.Event) error {
err := view.DeleteLockoutPolicy(v.Db, lockoutPolicyTable, aggregateID)
if err != nil && !errors.IsNotFound(err) {
return err
}
return v.ProcessedLockoutPolicySequence(event)
}
func (v *View) GetLatestLockoutPolicySequence() (*global_view.CurrentSequence, error) {
return v.latestSequence(lockoutPolicyTable)
}
func (v *View) ProcessedLockoutPolicySequence(event *models.Event) error {
return v.saveCurrentSequence(lockoutPolicyTable, event)
}
func (v *View) UpdateLockoutPolicySpoolerRunTimestamp() error {
return v.updateSpoolerRunSequence(lockoutPolicyTable)
}
func (v *View) GetLatestLockoutPolicyFailedEvent(sequence uint64) (*global_view.FailedEvent, error) {
return v.latestFailedEvent(lockoutPolicyTable, sequence)
}
func (v *View) ProcessedLockoutPolicyFailedEvent(failedEvent *global_view.FailedEvent) error {
return v.saveFailedEvent(failedEvent)
}

View File

@ -35,8 +35,6 @@ type IAMRepository interface {
GetDefaultLoginTexts(ctx context.Context, lang string) (*domain.CustomLoginText, error)
GetCustomLoginTexts(ctx context.Context, lang string) (*domain.CustomLoginText, error)
GetDefaultLockoutPolicy(ctx context.Context) (*iam_model.LockoutPolicyView, error)
GetDefaultPrivacyPolicy(ctx context.Context) (*iam_model.PrivacyPolicyView, error)
GetDefaultOrgIAMPolicy(ctx context.Context) (*iam_model.OrgIAMPolicyView, error)

View File

@ -9,7 +9,7 @@ import (
)
func (s *Server) GetLockoutPolicy(ctx context.Context, req *admin_pb.GetLockoutPolicyRequest) (*admin_pb.GetLockoutPolicyResponse, error) {
policy, err := s.iam.GetDefaultLockoutPolicy(ctx)
policy, err := s.query.DefaultLockoutPolicy(ctx)
if err != nil {
return nil, err
}

View File

@ -2,6 +2,7 @@ package management
import (
"context"
"github.com/caos/zitadel/internal/api/authz"
"github.com/caos/zitadel/internal/api/grpc/object"
policy_grpc "github.com/caos/zitadel/internal/api/grpc/policy"
@ -9,15 +10,15 @@ import (
)
func (s *Server) GetLockoutPolicy(ctx context.Context, req *mgmt_pb.GetLockoutPolicyRequest) (*mgmt_pb.GetLockoutPolicyResponse, error) {
policy, err := s.org.GetLockoutPolicy(ctx)
policy, err := s.query.LockoutPolicyByOrg(ctx, authz.GetCtxData(ctx).OrgID)
if err != nil {
return nil, err
}
return &mgmt_pb.GetLockoutPolicyResponse{Policy: policy_grpc.ModelLockoutPolicyToPb(policy), IsDefault: policy.Default}, nil
return &mgmt_pb.GetLockoutPolicyResponse{Policy: policy_grpc.ModelLockoutPolicyToPb(policy), IsDefault: policy.IsDefault}, nil
}
func (s *Server) GetDefaultLockoutPolicy(ctx context.Context, req *mgmt_pb.GetDefaultLockoutPolicyRequest) (*mgmt_pb.GetDefaultLockoutPolicyResponse, error) {
policy, err := s.org.GetDefaultLockoutPolicy(ctx)
policy, err := s.query.DefaultLockoutPolicy(ctx)
if err != nil {
return nil, err
}

View File

@ -2,19 +2,19 @@ package policy
import (
"github.com/caos/zitadel/internal/api/grpc/object"
"github.com/caos/zitadel/internal/iam/model"
"github.com/caos/zitadel/internal/query"
policy_pb "github.com/caos/zitadel/pkg/grpc/policy"
)
func ModelLockoutPolicyToPb(policy *model.LockoutPolicyView) *policy_pb.LockoutPolicy {
func ModelLockoutPolicyToPb(policy *query.LockoutPolicy) *policy_pb.LockoutPolicy {
return &policy_pb.LockoutPolicy{
IsDefault: policy.Default,
IsDefault: policy.IsDefault,
MaxPasswordAttempts: policy.MaxPasswordAttempts,
Details: object.ToViewDetailsPb(
policy.Sequence,
policy.CreationDate,
policy.ChangeDate,
"", //TODO: resourceowner
policy.ResourceOwner,
),
}
}

View File

@ -71,7 +71,7 @@ type loginPolicyViewProvider interface {
}
type lockoutPolicyViewProvider interface {
LockoutPolicyByAggregateID(string) (*iam_view_model.LockoutPolicyView, error)
LockoutPolicyByOrg(context.Context, string) (*query.LockoutPolicy, error)
}
type idpProviderViewProvider interface {
@ -294,7 +294,22 @@ func (repo *AuthRequestRepo) VerifyPassword(ctx context.Context, id, userID, res
if err != nil {
return err
}
return repo.Command.HumanCheckPassword(ctx, resourceOwner, userID, password, request.WithCurrentInfo(info), policy)
return repo.Command.HumanCheckPassword(ctx, resourceOwner, userID, password, request.WithCurrentInfo(info), lockoutPolicyToDomain(policy))
}
func lockoutPolicyToDomain(policy *query.LockoutPolicy) *domain.LockoutPolicy {
return &domain.LockoutPolicy{
ObjectRoot: es_models.ObjectRoot{
AggregateID: policy.ID,
Sequence: policy.Sequence,
ResourceOwner: policy.ResourceOwner,
CreationDate: policy.CreationDate,
ChangeDate: policy.ChangeDate,
},
Default: policy.IsDefault,
MaxPasswordAttempts: policy.MaxPasswordAttempts,
ShowLockOutFailures: policy.ShowFailures,
}
}
func (repo *AuthRequestRepo) VerifyMFAOTP(ctx context.Context, authRequestID, userID, resourceOwner, code, userAgentID string, info *domain.BrowserInfo) (err error) {
@ -512,7 +527,7 @@ func (repo *AuthRequestRepo) fillPolicies(ctx context.Context, request *domain.A
if err != nil {
return err
}
request.LockoutPolicy = lockoutPolicy
request.LockoutPolicy = lockoutPolicyToDomain(lockoutPolicy)
privacyPolicy, err := repo.getPrivacyPolicy(ctx, orgID)
if err != nil {
return err
@ -889,34 +904,12 @@ func (repo *AuthRequestRepo) getPrivacyPolicy(ctx context.Context, orgID string)
return policy.ToDomain(), err
}
func (repo *AuthRequestRepo) getLockoutPolicy(ctx context.Context, orgID string) (*domain.LockoutPolicy, error) {
policy, err := repo.View.LockoutPolicyByAggregateID(orgID)
if errors.IsNotFound(err) {
policy, err = repo.View.LockoutPolicyByAggregateID(repo.IAMID)
if err != nil && !errors.IsNotFound(err) {
return nil, err
}
if err == nil {
return policy.ToDomain(), nil
}
policy = &iam_view_model.LockoutPolicyView{}
events, err := repo.Eventstore.FilterEvents(ctx, es_models.NewSearchQuery().
AggregateIDFilter(repo.IAMID).
AggregateTypeFilter(iam.AggregateType).
EventTypesFilter(es_models.EventType(iam.LockoutPolicyAddedEventType), es_models.EventType(iam.LockoutPolicyChangedEventType)))
if err != nil || len(events) == 0 {
return nil, errors.ThrowNotFound(err, "EVENT-Gfgr2", "IAM.LockoutPolicy.NotExisting")
}
policy.Default = true
for _, event := range events {
policy.AppendEvent(event)
}
return policy.ToDomain(), nil
}
func (repo *AuthRequestRepo) getLockoutPolicy(ctx context.Context, orgID string) (*query.LockoutPolicy, error) {
policy, err := repo.LockoutPolicyViewProvider.LockoutPolicyByOrg(ctx, orgID)
if err != nil {
return nil, err
}
return policy.ToDomain(), err
return policy, err
}
func (repo *AuthRequestRepo) getLabelPolicy(ctx context.Context, orgID string) (*domain.LabelPolicy, error) {

View File

@ -15,7 +15,6 @@ import (
"github.com/caos/zitadel/internal/domain"
"github.com/caos/zitadel/internal/errors"
es_models "github.com/caos/zitadel/internal/eventstore/v1/models"
iam_view_model "github.com/caos/zitadel/internal/iam/repository/view/model"
proj_view_model "github.com/caos/zitadel/internal/project/repository/view/model"
"github.com/caos/zitadel/internal/query"
user_model "github.com/caos/zitadel/internal/user/model"
@ -151,10 +150,10 @@ func (m *mockLoginPolicy) LoginPolicyByID(ctx context.Context, id string) (*quer
}
type mockLockoutPolicy struct {
policy *iam_view_model.LockoutPolicyView
policy *query.LockoutPolicy
}
func (m *mockLockoutPolicy) LockoutPolicyByAggregateID(id string) (*iam_view_model.LockoutPolicyView, error) {
func (m *mockLockoutPolicy) LockoutPolicyByOrg(context.Context, string) (*query.LockoutPolicy, error) {
return m.policy, nil
}
@ -438,8 +437,9 @@ func TestAuthRequestRepo_nextSteps(t *testing.T) {
},
orgViewProvider: &mockViewOrg{State: domain.OrgStateActive},
lockoutPolicyProvider: &mockLockoutPolicy{
policy: &iam_view_model.LockoutPolicyView{
ShowLockOutFailures: true,
policy: &query.LockoutPolicy{
ShowFailures: true,
},
},
},
@ -459,8 +459,8 @@ func TestAuthRequestRepo_nextSteps(t *testing.T) {
},
orgViewProvider: &mockViewOrg{State: domain.OrgStateActive},
lockoutPolicyProvider: &mockLockoutPolicy{
policy: &iam_view_model.LockoutPolicyView{
ShowLockOutFailures: true,
policy: &query.LockoutPolicy{
ShowFailures: true,
},
},
},
@ -475,8 +475,8 @@ func TestAuthRequestRepo_nextSteps(t *testing.T) {
userEventProvider: &mockEventUser{},
orgViewProvider: &mockViewErrOrg{},
lockoutPolicyProvider: &mockLockoutPolicy{
policy: &iam_view_model.LockoutPolicyView{
ShowLockOutFailures: true,
policy: &query.LockoutPolicy{
ShowFailures: true,
},
},
},
@ -491,8 +491,8 @@ func TestAuthRequestRepo_nextSteps(t *testing.T) {
userEventProvider: &mockEventUser{},
orgViewProvider: &mockViewOrg{State: domain.OrgStateInactive},
lockoutPolicyProvider: &mockLockoutPolicy{
policy: &iam_view_model.LockoutPolicyView{
ShowLockOutFailures: true,
policy: &query.LockoutPolicy{
ShowFailures: true,
},
},
},
@ -510,8 +510,8 @@ func TestAuthRequestRepo_nextSteps(t *testing.T) {
userEventProvider: &mockEventUser{},
orgViewProvider: &mockViewOrg{State: domain.OrgStateActive},
lockoutPolicyProvider: &mockLockoutPolicy{
policy: &iam_view_model.LockoutPolicyView{
ShowLockOutFailures: true,
policy: &query.LockoutPolicy{
ShowFailures: true,
},
},
},
@ -527,8 +527,8 @@ func TestAuthRequestRepo_nextSteps(t *testing.T) {
userEventProvider: &mockEventUser{},
orgViewProvider: &mockViewOrg{State: domain.OrgStateActive},
lockoutPolicyProvider: &mockLockoutPolicy{
policy: &iam_view_model.LockoutPolicyView{
ShowLockOutFailures: true,
policy: &query.LockoutPolicy{
ShowFailures: true,
},
},
},
@ -547,8 +547,8 @@ func TestAuthRequestRepo_nextSteps(t *testing.T) {
userEventProvider: &mockEventUser{},
orgViewProvider: &mockViewOrg{State: domain.OrgStateActive},
lockoutPolicyProvider: &mockLockoutPolicy{
policy: &iam_view_model.LockoutPolicyView{
ShowLockOutFailures: true,
policy: &query.LockoutPolicy{
ShowFailures: true,
},
},
},
@ -569,8 +569,8 @@ func TestAuthRequestRepo_nextSteps(t *testing.T) {
orgViewProvider: &mockViewOrg{State: domain.OrgStateActive},
MultiFactorCheckLifeTime: 10 * time.Hour,
lockoutPolicyProvider: &mockLockoutPolicy{
policy: &iam_view_model.LockoutPolicyView{
ShowLockOutFailures: true,
policy: &query.LockoutPolicy{
ShowFailures: true,
},
},
},
@ -588,8 +588,8 @@ func TestAuthRequestRepo_nextSteps(t *testing.T) {
userEventProvider: &mockEventUser{},
orgViewProvider: &mockViewOrg{State: domain.OrgStateActive},
lockoutPolicyProvider: &mockLockoutPolicy{
policy: &iam_view_model.LockoutPolicyView{
ShowLockOutFailures: true,
policy: &query.LockoutPolicy{
ShowFailures: true,
},
},
MultiFactorCheckLifeTime: 10 * time.Hour,
@ -609,8 +609,8 @@ func TestAuthRequestRepo_nextSteps(t *testing.T) {
userEventProvider: &mockEventUser{},
orgViewProvider: &mockViewOrg{State: domain.OrgStateActive},
lockoutPolicyProvider: &mockLockoutPolicy{
policy: &iam_view_model.LockoutPolicyView{
ShowLockOutFailures: true,
policy: &query.LockoutPolicy{
ShowFailures: true,
},
},
MultiFactorCheckLifeTime: 10 * time.Hour,
@ -635,8 +635,8 @@ func TestAuthRequestRepo_nextSteps(t *testing.T) {
},
userEventProvider: &mockEventUser{},
lockoutPolicyProvider: &mockLockoutPolicy{
policy: &iam_view_model.LockoutPolicyView{
ShowLockOutFailures: true,
policy: &query.LockoutPolicy{
ShowFailures: true,
},
},
orgViewProvider: &mockViewOrg{State: domain.OrgStateActive},
@ -661,8 +661,8 @@ func TestAuthRequestRepo_nextSteps(t *testing.T) {
},
userEventProvider: &mockEventUser{},
lockoutPolicyProvider: &mockLockoutPolicy{
policy: &iam_view_model.LockoutPolicyView{
ShowLockOutFailures: true,
policy: &query.LockoutPolicy{
ShowFailures: true,
},
},
orgViewProvider: &mockViewOrg{State: domain.OrgStateActive},
@ -683,8 +683,8 @@ func TestAuthRequestRepo_nextSteps(t *testing.T) {
},
userEventProvider: &mockEventUser{},
lockoutPolicyProvider: &mockLockoutPolicy{
policy: &iam_view_model.LockoutPolicyView{
ShowLockOutFailures: true,
policy: &query.LockoutPolicy{
ShowFailures: true,
},
},
orgViewProvider: &mockViewOrg{State: domain.OrgStateActive},
@ -713,8 +713,8 @@ func TestAuthRequestRepo_nextSteps(t *testing.T) {
policy: &query.LoginPolicy{},
},
lockoutPolicyProvider: &mockLockoutPolicy{
policy: &iam_view_model.LockoutPolicyView{
ShowLockOutFailures: true,
policy: &query.LockoutPolicy{
ShowFailures: true,
},
},
ExternalLoginCheckLifeTime: 10 * 24 * time.Hour,
@ -741,8 +741,8 @@ func TestAuthRequestRepo_nextSteps(t *testing.T) {
userEventProvider: &mockEventUser{},
orgViewProvider: &mockViewOrg{State: domain.OrgStateActive},
lockoutPolicyProvider: &mockLockoutPolicy{
policy: &iam_view_model.LockoutPolicyView{
ShowLockOutFailures: true,
policy: &query.LockoutPolicy{
ShowFailures: true,
},
},
PasswordCheckLifeTime: 10 * 24 * time.Hour,
@ -768,8 +768,8 @@ func TestAuthRequestRepo_nextSteps(t *testing.T) {
userGrantProvider: &mockUserGrants{},
projectProvider: &mockProject{},
lockoutPolicyProvider: &mockLockoutPolicy{
policy: &iam_view_model.LockoutPolicyView{
ShowLockOutFailures: true,
policy: &query.LockoutPolicy{
ShowFailures: true,
},
},
SecondFactorCheckLifeTime: 18 * time.Hour,
@ -800,8 +800,8 @@ func TestAuthRequestRepo_nextSteps(t *testing.T) {
userEventProvider: &mockEventUser{},
orgViewProvider: &mockViewOrg{State: domain.OrgStateActive},
lockoutPolicyProvider: &mockLockoutPolicy{
policy: &iam_view_model.LockoutPolicyView{
ShowLockOutFailures: true,
policy: &query.LockoutPolicy{
ShowFailures: true,
},
},
PasswordCheckLifeTime: 10 * 24 * time.Hour,
@ -833,8 +833,8 @@ func TestAuthRequestRepo_nextSteps(t *testing.T) {
userEventProvider: &mockEventUser{},
orgViewProvider: &mockViewOrg{State: domain.OrgStateActive},
lockoutPolicyProvider: &mockLockoutPolicy{
policy: &iam_view_model.LockoutPolicyView{
ShowLockOutFailures: true,
policy: &query.LockoutPolicy{
ShowFailures: true,
},
},
PasswordCheckLifeTime: 10 * 24 * time.Hour,
@ -867,8 +867,8 @@ func TestAuthRequestRepo_nextSteps(t *testing.T) {
userEventProvider: &mockEventUser{},
orgViewProvider: &mockViewOrg{State: domain.OrgStateActive},
lockoutPolicyProvider: &mockLockoutPolicy{
policy: &iam_view_model.LockoutPolicyView{
ShowLockOutFailures: true,
policy: &query.LockoutPolicy{
ShowFailures: true,
},
},
PasswordCheckLifeTime: 10 * 24 * time.Hour,
@ -904,8 +904,8 @@ func TestAuthRequestRepo_nextSteps(t *testing.T) {
userEventProvider: &mockEventUser{},
orgViewProvider: &mockViewOrg{State: domain.OrgStateActive},
lockoutPolicyProvider: &mockLockoutPolicy{
policy: &iam_view_model.LockoutPolicyView{
ShowLockOutFailures: true,
policy: &query.LockoutPolicy{
ShowFailures: true,
},
},
PasswordCheckLifeTime: 10 * 24 * time.Hour,
@ -935,8 +935,8 @@ func TestAuthRequestRepo_nextSteps(t *testing.T) {
userEventProvider: &mockEventUser{},
orgViewProvider: &mockViewOrg{State: domain.OrgStateActive},
lockoutPolicyProvider: &mockLockoutPolicy{
policy: &iam_view_model.LockoutPolicyView{
ShowLockOutFailures: true,
policy: &query.LockoutPolicy{
ShowFailures: true,
},
},
PasswordCheckLifeTime: 10 * 24 * time.Hour,
@ -966,8 +966,8 @@ func TestAuthRequestRepo_nextSteps(t *testing.T) {
userEventProvider: &mockEventUser{},
orgViewProvider: &mockViewOrg{State: domain.OrgStateActive},
lockoutPolicyProvider: &mockLockoutPolicy{
policy: &iam_view_model.LockoutPolicyView{
ShowLockOutFailures: true,
policy: &query.LockoutPolicy{
ShowFailures: true,
},
},
PasswordCheckLifeTime: 10 * 24 * time.Hour,
@ -999,8 +999,8 @@ func TestAuthRequestRepo_nextSteps(t *testing.T) {
userGrantProvider: &mockUserGrants{},
projectProvider: &mockProject{},
lockoutPolicyProvider: &mockLockoutPolicy{
policy: &iam_view_model.LockoutPolicyView{
ShowLockOutFailures: true,
policy: &query.LockoutPolicy{
ShowFailures: true,
},
},
PasswordCheckLifeTime: 10 * 24 * time.Hour,
@ -1033,8 +1033,8 @@ func TestAuthRequestRepo_nextSteps(t *testing.T) {
userGrantProvider: &mockUserGrants{},
projectProvider: &mockProject{},
lockoutPolicyProvider: &mockLockoutPolicy{
policy: &iam_view_model.LockoutPolicyView{
ShowLockOutFailures: true,
policy: &query.LockoutPolicy{
ShowFailures: true,
},
},
PasswordCheckLifeTime: 10 * 24 * time.Hour,
@ -1071,8 +1071,8 @@ func TestAuthRequestRepo_nextSteps(t *testing.T) {
},
projectProvider: &mockProject{},
lockoutPolicyProvider: &mockLockoutPolicy{
policy: &iam_view_model.LockoutPolicyView{
ShowLockOutFailures: true,
policy: &query.LockoutPolicy{
ShowFailures: true,
},
},
PasswordCheckLifeTime: 10 * 24 * time.Hour,
@ -1109,8 +1109,8 @@ func TestAuthRequestRepo_nextSteps(t *testing.T) {
},
projectProvider: &mockProject{},
lockoutPolicyProvider: &mockLockoutPolicy{
policy: &iam_view_model.LockoutPolicyView{
ShowLockOutFailures: true,
policy: &query.LockoutPolicy{
ShowFailures: true,
},
},
PasswordCheckLifeTime: 10 * 24 * time.Hour,
@ -1147,8 +1147,8 @@ func TestAuthRequestRepo_nextSteps(t *testing.T) {
hasProject: false,
},
lockoutPolicyProvider: &mockLockoutPolicy{
policy: &iam_view_model.LockoutPolicyView{
ShowLockOutFailures: true,
policy: &query.LockoutPolicy{
ShowFailures: true,
},
},
PasswordCheckLifeTime: 10 * 24 * time.Hour,
@ -1185,8 +1185,8 @@ func TestAuthRequestRepo_nextSteps(t *testing.T) {
hasProject: true,
},
lockoutPolicyProvider: &mockLockoutPolicy{
policy: &iam_view_model.LockoutPolicyView{
ShowLockOutFailures: true,
policy: &query.LockoutPolicy{
ShowFailures: true,
},
},
PasswordCheckLifeTime: 10 * 24 * time.Hour,
@ -1215,8 +1215,8 @@ func TestAuthRequestRepo_nextSteps(t *testing.T) {
MFAMaxSetUp: int32(model.MFALevelSecondFactor),
},
lockoutPolicyProvider: &mockLockoutPolicy{
policy: &iam_view_model.LockoutPolicyView{
ShowLockOutFailures: true,
policy: &query.LockoutPolicy{
ShowFailures: true,
},
},
userEventProvider: &mockEventUser{},
@ -1248,8 +1248,8 @@ func TestAuthRequestRepo_nextSteps(t *testing.T) {
userEventProvider: &mockEventUser{},
orgViewProvider: &mockViewOrg{State: domain.OrgStateActive},
lockoutPolicyProvider: &mockLockoutPolicy{
policy: &iam_view_model.LockoutPolicyView{
ShowLockOutFailures: true,
policy: &query.LockoutPolicy{
ShowFailures: true,
},
},
SecondFactorCheckLifeTime: 18 * time.Hour,

View File

@ -67,7 +67,6 @@ func Register(configs Configs, bulkLimit, errorCount uint64, view *view.View, es
newPrivacyPolicy(handler{view, bulkLimit, configs.cycleDuration("PrivacyPolicy"), errorCount, es}),
newCustomText(handler{view, bulkLimit, configs.cycleDuration("CustomTexts"), errorCount, es}),
newMetadata(handler{view, bulkLimit, configs.cycleDuration("Metadata"), errorCount, es}),
newLockoutPolicy(handler{view, bulkLimit, configs.cycleDuration("LockoutPolicy"), errorCount, es}),
newOrgProjectMapping(handler{view, bulkLimit, configs.cycleDuration("OrgProjectMapping"), errorCount, es}),
}
}

View File

@ -1,110 +0,0 @@
package handler
import (
"github.com/caos/logging"
"github.com/caos/zitadel/internal/eventstore/v1"
es_models "github.com/caos/zitadel/internal/eventstore/v1/models"
"github.com/caos/zitadel/internal/eventstore/v1/query"
"github.com/caos/zitadel/internal/eventstore/v1/spooler"
iam_es_model "github.com/caos/zitadel/internal/iam/repository/eventsourcing/model"
iam_model "github.com/caos/zitadel/internal/iam/repository/view/model"
org_es_model "github.com/caos/zitadel/internal/org/repository/eventsourcing/model"
)
const (
lockoutPolicyTable = "auth.lockout_policies"
)
type LockoutPolicy struct {
handler
subscription *v1.Subscription
}
func newLockoutPolicy(handler handler) *LockoutPolicy {
h := &LockoutPolicy{
handler: handler,
}
h.subscribe()
return h
}
func (p *LockoutPolicy) subscribe() {
p.subscription = p.es.Subscribe(p.AggregateTypes()...)
go func() {
for event := range p.subscription.Events {
query.ReduceEvent(p, event)
}
}()
}
func (p *LockoutPolicy) ViewModel() string {
return lockoutPolicyTable
}
func (p *LockoutPolicy) Subscription() *v1.Subscription {
return p.subscription
}
func (_ *LockoutPolicy) AggregateTypes() []es_models.AggregateType {
return []es_models.AggregateType{org_es_model.OrgAggregate, iam_es_model.IAMAggregate}
}
func (p *LockoutPolicy) CurrentSequence() (uint64, error) {
sequence, err := p.view.GetLatestLockoutPolicySequence()
if err != nil {
return 0, err
}
return sequence.CurrentSequence, nil
}
func (p *LockoutPolicy) EventQuery() (*es_models.SearchQuery, error) {
sequence, err := p.view.GetLatestLockoutPolicySequence()
if err != nil {
return nil, err
}
return es_models.NewSearchQuery().
AggregateTypeFilter(p.AggregateTypes()...).
LatestSequenceFilter(sequence.CurrentSequence), nil
}
func (p *LockoutPolicy) Reduce(event *es_models.Event) (err error) {
switch event.AggregateType {
case org_es_model.OrgAggregate, iam_es_model.IAMAggregate:
err = p.processLockoutPolicy(event)
}
return err
}
func (p *LockoutPolicy) processLockoutPolicy(event *es_models.Event) (err error) {
policy := new(iam_model.LockoutPolicyView)
switch event.Type {
case iam_es_model.LockoutPolicyAdded, org_es_model.LockoutPolicyAdded:
err = policy.AppendEvent(event)
case iam_es_model.LockoutPolicyChanged, org_es_model.LockoutPolicyChanged:
policy, err = p.view.LockoutPolicyByAggregateID(event.AggregateID)
if err != nil {
return err
}
err = policy.AppendEvent(event)
case org_es_model.LockoutPolicyRemoved:
return p.view.DeleteLockoutPolicy(event.AggregateID, event)
default:
return p.view.ProcessedLockoutPolicySequence(event)
}
if err != nil {
return err
}
return p.view.PutLockoutPolicy(policy, event)
}
func (p *LockoutPolicy) OnError(event *es_models.Event, err error) error {
logging.LogWithFields("SPOOL-0pos2", "id", event.AggregateID).WithError(err).Warn("something went wrong in passwordLockout policy handler")
return spooler.HandleError(event, err, p.view.GetLatestLockoutPolicyFailedEvent, p.view.ProcessedLockoutPolicyFailedEvent, p.view.ProcessedLockoutPolicySequence, p.errorCountUntilSkip)
}
func (p *LockoutPolicy) OnSuccess() error {
return spooler.HandleSuccess(p.view.UpdateLockoutPolicySpoolerRunTimestamp)
}

View File

@ -108,8 +108,8 @@ func Start(conf Config, authZ authz.Config, systemDefaults sd.SystemDefaults, co
UserCommandProvider: command,
UserEventProvider: &userRepo,
IDPProviderViewProvider: view,
LockoutPolicyViewProvider: queries,
LoginPolicyViewProvider: queries,
LockoutPolicyViewProvider: view,
UserGrantProvider: view,
ProjectProvider: view,
IdGenerator: idGenerator,

View File

@ -1,53 +0,0 @@
package view
import (
"github.com/caos/zitadel/internal/errors"
"github.com/caos/zitadel/internal/eventstore/v1/models"
"github.com/caos/zitadel/internal/iam/repository/view"
"github.com/caos/zitadel/internal/iam/repository/view/model"
global_view "github.com/caos/zitadel/internal/view/repository"
)
const (
passwordLockoutPolicyTable = "auth.lockout_policies"
)
func (v *View) LockoutPolicyByAggregateID(aggregateID string) (*model.LockoutPolicyView, error) {
return view.GetLockoutPolicyByAggregateID(v.Db, passwordLockoutPolicyTable, aggregateID)
}
func (v *View) PutLockoutPolicy(policy *model.LockoutPolicyView, event *models.Event) error {
err := view.PutLockoutPolicy(v.Db, passwordLockoutPolicyTable, policy)
if err != nil {
return err
}
return v.ProcessedLockoutPolicySequence(event)
}
func (v *View) DeleteLockoutPolicy(aggregateID string, event *models.Event) error {
err := view.DeleteLockoutPolicy(v.Db, passwordLockoutPolicyTable, aggregateID)
if err != nil && !errors.IsNotFound(err) {
return err
}
return v.ProcessedLockoutPolicySequence(event)
}
func (v *View) GetLatestLockoutPolicySequence() (*global_view.CurrentSequence, error) {
return v.latestSequence(passwordLockoutPolicyTable)
}
func (v *View) ProcessedLockoutPolicySequence(event *models.Event) error {
return v.saveCurrentSequence(passwordLockoutPolicyTable, event)
}
func (v *View) UpdateLockoutPolicySpoolerRunTimestamp() error {
return v.updateSpoolerRunSequence(passwordLockoutPolicyTable)
}
func (v *View) GetLatestLockoutPolicyFailedEvent(sequence uint64) (*global_view.FailedEvent, error) {
return v.latestFailedEvent(passwordLockoutPolicyTable, sequence)
}
func (v *View) ProcessedLockoutPolicyFailedEvent(failedEvent *global_view.FailedEvent) error {
return v.saveFailedEvent(failedEvent)
}

View File

@ -2,6 +2,7 @@ package command
import (
"context"
"github.com/caos/zitadel/internal/domain"
caos_errs "github.com/caos/zitadel/internal/errors"
"github.com/caos/zitadel/internal/repository/org"

View File

@ -2,6 +2,7 @@ package command
import (
"context"
"github.com/caos/logging"
"github.com/caos/zitadel/internal/crypto"
"github.com/caos/zitadel/internal/domain"

View File

@ -1,84 +0,0 @@
package model
import (
"encoding/json"
"github.com/caos/zitadel/internal/domain"
org_es_model "github.com/caos/zitadel/internal/org/repository/eventsourcing/model"
"time"
es_model "github.com/caos/zitadel/internal/iam/repository/eventsourcing/model"
"github.com/caos/logging"
caos_errs "github.com/caos/zitadel/internal/errors"
"github.com/caos/zitadel/internal/eventstore/v1/models"
"github.com/caos/zitadel/internal/iam/model"
)
const (
LockoutKeyAggregateID = "aggregate_id"
)
type LockoutPolicyView struct {
AggregateID string `json:"-" gorm:"column:aggregate_id;primary_key"`
CreationDate time.Time `json:"-" gorm:"column:creation_date"`
ChangeDate time.Time `json:"-" gorm:"column:change_date"`
State int32 `json:"-" gorm:"column:lockout_policy_state"`
MaxPasswordAttempts uint64 `json:"maxPasswordAttempts" gorm:"column:max_password_attempts"`
ShowLockOutFailures bool `json:"showLockOutFailures" gorm:"column:show_lockout_failures"`
Default bool `json:"-" gorm:"-"`
Sequence uint64 `json:"-" gorm:"column:sequence"`
}
func LockoutViewToModel(policy *LockoutPolicyView) *model.LockoutPolicyView {
return &model.LockoutPolicyView{
AggregateID: policy.AggregateID,
Sequence: policy.Sequence,
CreationDate: policy.CreationDate,
ChangeDate: policy.ChangeDate,
MaxPasswordAttempts: policy.MaxPasswordAttempts,
ShowLockOutFailures: policy.ShowLockOutFailures,
Default: policy.Default,
}
}
func (p *LockoutPolicyView) ToDomain() *domain.LockoutPolicy {
return &domain.LockoutPolicy{
ObjectRoot: models.ObjectRoot{
AggregateID: p.AggregateID,
CreationDate: p.CreationDate,
ChangeDate: p.ChangeDate,
Sequence: p.Sequence,
},
MaxPasswordAttempts: p.MaxPasswordAttempts,
ShowLockOutFailures: p.ShowLockOutFailures,
Default: p.Default,
}
}
func (i *LockoutPolicyView) AppendEvent(event *models.Event) (err error) {
i.Sequence = event.Sequence
i.ChangeDate = event.CreationDate
switch event.Type {
case es_model.LockoutPolicyAdded, org_es_model.LockoutPolicyAdded:
i.setRootData(event)
i.CreationDate = event.CreationDate
err = i.SetData(event)
case es_model.LockoutPolicyChanged, org_es_model.LockoutPolicyChanged:
err = i.SetData(event)
}
return err
}
func (r *LockoutPolicyView) setRootData(event *models.Event) {
r.AggregateID = event.AggregateID
}
func (r *LockoutPolicyView) SetData(event *models.Event) error {
if err := json.Unmarshal(event.Data, r); err != nil {
logging.Log("EVEN-gHls0").WithError(err).Error("could not unmarshal event data")
return caos_errs.ThrowInternal(err, "MODEL-Hs8uf", "Could not unmarshal data")
}
return nil
}

View File

@ -1,59 +0,0 @@
package model
import (
"github.com/caos/zitadel/internal/domain"
iam_model "github.com/caos/zitadel/internal/iam/model"
"github.com/caos/zitadel/internal/view/repository"
)
type LockoutPolicySearchRequest iam_model.LockoutPolicySearchRequest
type LockoutPolicySearchQuery iam_model.LockoutPolicySearchQuery
type LockoutPolicySearchKey iam_model.LockoutPolicySearchKey
func (req LockoutPolicySearchRequest) GetLimit() uint64 {
return req.Limit
}
func (req LockoutPolicySearchRequest) GetOffset() uint64 {
return req.Offset
}
func (req LockoutPolicySearchRequest) GetSortingColumn() repository.ColumnKey {
if req.SortingColumn == iam_model.LockoutPolicySearchKeyUnspecified {
return nil
}
return LockoutPolicySearchKey(req.SortingColumn)
}
func (req LockoutPolicySearchRequest) GetAsc() bool {
return req.Asc
}
func (req LockoutPolicySearchRequest) GetQueries() []repository.SearchQuery {
result := make([]repository.SearchQuery, len(req.Queries))
for i, q := range req.Queries {
result[i] = LockoutPolicySearchQuery{Key: q.Key, Value: q.Value, Method: q.Method}
}
return result
}
func (req LockoutPolicySearchQuery) GetKey() repository.ColumnKey {
return LockoutPolicySearchKey(req.Key)
}
func (req LockoutPolicySearchQuery) GetMethod() domain.SearchMethod {
return req.Method
}
func (req LockoutPolicySearchQuery) GetValue() interface{} {
return req.Value
}
func (key LockoutPolicySearchKey) ToColumnName() string {
switch iam_model.LockoutPolicySearchKey(key) {
case iam_model.LockoutPolicySearchKeyAggregateID:
return LockoutKeyAggregateID
default:
return ""
}
}

View File

@ -1,32 +0,0 @@
package view
import (
"github.com/caos/zitadel/internal/domain"
caos_errs "github.com/caos/zitadel/internal/errors"
iam_model "github.com/caos/zitadel/internal/iam/model"
"github.com/caos/zitadel/internal/iam/repository/view/model"
"github.com/caos/zitadel/internal/view/repository"
"github.com/jinzhu/gorm"
)
func GetLockoutPolicyByAggregateID(db *gorm.DB, table, aggregateID string) (*model.LockoutPolicyView, error) {
policy := new(model.LockoutPolicyView)
aggregateIDQuery := &model.LockoutPolicySearchQuery{Key: iam_model.LockoutPolicySearchKeyAggregateID, Value: aggregateID, Method: domain.SearchMethodEquals}
query := repository.PrepareGetByQuery(table, aggregateIDQuery)
err := query(db, policy)
if caos_errs.IsNotFound(err) {
return nil, caos_errs.ThrowNotFound(nil, "VIEW-M9fsf", "Errors.IAM.LockoutPolicy.NotExisting")
}
return policy, err
}
func PutLockoutPolicy(db *gorm.DB, table string, policy *model.LockoutPolicyView) error {
save := repository.PrepareSave(table)
return save(db, policy)
}
func DeleteLockoutPolicy(db *gorm.DB, table, aggregateID string) error {
delete := repository.PrepareDeleteByKey(table, model.LockoutPolicySearchKey(iam_model.LockoutPolicySearchKeyAggregateID), aggregateID)
return delete(db)
}

View File

@ -285,57 +285,6 @@ func (repo *OrgRepository) SearchIDPProviders(ctx context.Context, request *iam_
return result, nil
}
func (repo *OrgRepository) GetLockoutPolicy(ctx context.Context) (*iam_model.LockoutPolicyView, error) {
policy, viewErr := repo.View.LockoutPolicyByAggregateID(authz.GetCtxData(ctx).OrgID)
if viewErr != nil && !errors.IsNotFound(viewErr) {
return nil, viewErr
}
if errors.IsNotFound(viewErr) {
policy = new(iam_view_model.LockoutPolicyView)
}
events, esErr := repo.getOrgEvents(ctx, repo.SystemDefaults.IamID, policy.Sequence)
if errors.IsNotFound(viewErr) && len(events) == 0 {
return repo.GetDefaultLockoutPolicy(ctx)
}
if esErr != nil {
logging.Log("EVENT-mS9od").WithError(esErr).Debug("error retrieving new events")
return iam_view_model.LockoutViewToModel(policy), nil
}
policyCopy := *policy
for _, event := range events {
if err := policyCopy.AppendEvent(event); err != nil {
return iam_view_model.LockoutViewToModel(policy), nil
}
}
return iam_view_model.LockoutViewToModel(policy), nil
}
func (repo *OrgRepository) GetDefaultLockoutPolicy(ctx context.Context) (*iam_model.LockoutPolicyView, error) {
policy, viewErr := repo.View.LockoutPolicyByAggregateID(repo.SystemDefaults.IamID)
if viewErr != nil && !errors.IsNotFound(viewErr) {
return nil, viewErr
}
if errors.IsNotFound(viewErr) {
policy = new(iam_view_model.LockoutPolicyView)
}
events, esErr := repo.getIAMEvents(ctx, policy.Sequence)
if errors.IsNotFound(viewErr) && len(events) == 0 {
return nil, errors.ThrowNotFound(nil, "EVENT-cmO9s", "Errors.IAM.LockoutPolicy.NotFound")
}
if esErr != nil {
logging.Log("EVENT-2Ms9f").WithError(esErr).Debug("error retrieving new events")
return iam_view_model.LockoutViewToModel(policy), nil
}
policyCopy := *policy
for _, event := range events {
if err := policyCopy.AppendEvent(event); err != nil {
return iam_view_model.LockoutViewToModel(policy), nil
}
}
policy.Default = true
return iam_view_model.LockoutViewToModel(policy), nil
}
func (repo *OrgRepository) GetPrivacyPolicy(ctx context.Context) (*iam_model.PrivacyPolicyView, error) {
policy, err := repo.View.PrivacyPolicyByAggregateID(authz.GetCtxData(ctx).OrgID)
if errors.IsNotFound(err) {

View File

@ -57,8 +57,6 @@ func Register(configs Configs, bulkLimit, errorCount uint64, view *view.View, es
newExternalIDP(
handler{view, bulkLimit, configs.cycleDuration("ExternalIDP"), errorCount, es},
defaults),
newLockoutPolicy(
handler{view, bulkLimit, configs.cycleDuration("LockoutPolicy"), errorCount, es}),
newOrgIAMPolicy(
handler{view, bulkLimit, configs.cycleDuration("OrgIAMPolicy"), errorCount, es}),
newMailTemplate(

View File

@ -1,110 +0,0 @@
package handler
import (
"github.com/caos/logging"
"github.com/caos/zitadel/internal/eventstore/v1"
iam_es_model "github.com/caos/zitadel/internal/iam/repository/eventsourcing/model"
es_models "github.com/caos/zitadel/internal/eventstore/v1/models"
"github.com/caos/zitadel/internal/eventstore/v1/query"
"github.com/caos/zitadel/internal/eventstore/v1/spooler"
iam_model "github.com/caos/zitadel/internal/iam/repository/view/model"
"github.com/caos/zitadel/internal/org/repository/eventsourcing/model"
)
const (
lockoutPolicyTable = "management.lockout_policies"
)
type LockoutPolicy struct {
handler
subscription *v1.Subscription
}
func newLockoutPolicy(handler handler) *LockoutPolicy {
h := &LockoutPolicy{
handler: handler,
}
h.subscribe()
return h
}
func (m *LockoutPolicy) subscribe() {
m.subscription = m.es.Subscribe(m.AggregateTypes()...)
go func() {
for event := range m.subscription.Events {
query.ReduceEvent(m, event)
}
}()
}
func (p *LockoutPolicy) ViewModel() string {
return lockoutPolicyTable
}
func (p *LockoutPolicy) Subscription() *v1.Subscription {
return p.subscription
}
func (_ *LockoutPolicy) AggregateTypes() []es_models.AggregateType {
return []es_models.AggregateType{model.OrgAggregate, iam_es_model.IAMAggregate}
}
func (p *LockoutPolicy) CurrentSequence() (uint64, error) {
sequence, err := p.view.GetLatestLockoutPolicySequence()
if err != nil {
return 0, err
}
return sequence.CurrentSequence, nil
}
func (p *LockoutPolicy) EventQuery() (*es_models.SearchQuery, error) {
sequence, err := p.view.GetLatestLockoutPolicySequence()
if err != nil {
return nil, err
}
return es_models.NewSearchQuery().
AggregateTypeFilter(p.AggregateTypes()...).
LatestSequenceFilter(sequence.CurrentSequence), nil
}
func (p *LockoutPolicy) Reduce(event *es_models.Event) (err error) {
switch event.AggregateType {
case model.OrgAggregate, iam_es_model.IAMAggregate:
err = p.processPasswordLockoutPolicy(event)
}
return err
}
func (p *LockoutPolicy) processPasswordLockoutPolicy(event *es_models.Event) (err error) {
policy := new(iam_model.LockoutPolicyView)
switch event.Type {
case iam_es_model.LockoutPolicyAdded, model.LockoutPolicyAdded:
err = policy.AppendEvent(event)
case iam_es_model.LockoutPolicyChanged, model.LockoutPolicyChanged:
policy, err = p.view.LockoutPolicyByAggregateID(event.AggregateID)
if err != nil {
return err
}
err = policy.AppendEvent(event)
case model.LockoutPolicyRemoved:
return p.view.DeleteLockoutPolicy(event.AggregateID, event)
default:
return p.view.ProcessedLockoutPolicySequence(event)
}
if err != nil {
return err
}
return p.view.PutLockoutPolicy(policy, event)
}
func (p *LockoutPolicy) OnError(event *es_models.Event, err error) error {
logging.LogWithFields("SPOOL-Bms8f", "id", event.AggregateID).WithError(err).Warn("something went wrong in passwordLockout policy handler")
return spooler.HandleError(event, err, p.view.GetLatestLockoutPolicyFailedEvent, p.view.ProcessedLockoutPolicyFailedEvent, p.view.ProcessedLockoutPolicySequence, p.errorCountUntilSkip)
}
func (p *LockoutPolicy) OnSuccess() error {
return spooler.HandleSuccess(p.view.UpdateLockoutPolicySpoolerRunTimestamp)
}

View File

@ -1,53 +0,0 @@
package view
import (
"github.com/caos/zitadel/internal/errors"
"github.com/caos/zitadel/internal/eventstore/v1/models"
"github.com/caos/zitadel/internal/iam/repository/view"
"github.com/caos/zitadel/internal/iam/repository/view/model"
global_view "github.com/caos/zitadel/internal/view/repository"
)
const (
lockoutPolicyTable = "management.lockout_policies"
)
func (v *View) LockoutPolicyByAggregateID(aggregateID string) (*model.LockoutPolicyView, error) {
return view.GetLockoutPolicyByAggregateID(v.Db, lockoutPolicyTable, aggregateID)
}
func (v *View) PutLockoutPolicy(policy *model.LockoutPolicyView, event *models.Event) error {
err := view.PutLockoutPolicy(v.Db, lockoutPolicyTable, policy)
if err != nil {
return err
}
return v.ProcessedLockoutPolicySequence(event)
}
func (v *View) DeleteLockoutPolicy(aggregateID string, event *models.Event) error {
err := view.DeleteLockoutPolicy(v.Db, lockoutPolicyTable, aggregateID)
if err != nil && !errors.IsNotFound(err) {
return err
}
return v.ProcessedLockoutPolicySequence(event)
}
func (v *View) GetLatestLockoutPolicySequence() (*global_view.CurrentSequence, error) {
return v.latestSequence(lockoutPolicyTable)
}
func (v *View) ProcessedLockoutPolicySequence(event *models.Event) error {
return v.saveCurrentSequence(lockoutPolicyTable, event)
}
func (v *View) UpdateLockoutPolicySpoolerRunTimestamp() error {
return v.updateSpoolerRunSequence(lockoutPolicyTable)
}
func (v *View) GetLatestLockoutPolicyFailedEvent(sequence uint64) (*global_view.FailedEvent, error) {
return v.latestFailedEvent(lockoutPolicyTable, sequence)
}
func (v *View) ProcessedLockoutPolicyFailedEvent(failedEvent *global_view.FailedEvent) error {
return v.saveFailedEvent(failedEvent)
}

View File

@ -28,9 +28,6 @@ type OrgRepository interface {
SearchIDPProviders(ctx context.Context, request *iam_model.IDPProviderSearchRequest) (*iam_model.IDPProviderSearchResponse, error)
GetIDPProvidersByIDPConfigID(ctx context.Context, aggregateID, idpConfigID string) ([]*iam_model.IDPProviderView, error)
GetLockoutPolicy(ctx context.Context) (*iam_model.LockoutPolicyView, error)
GetDefaultLockoutPolicy(ctx context.Context) (*iam_model.LockoutPolicyView, error)
GetPrivacyPolicy(ctx context.Context) (*iam_model.PrivacyPolicyView, error)
GetDefaultPrivacyPolicy(ctx context.Context) (*iam_model.PrivacyPolicyView, error)

View File

@ -0,0 +1,125 @@
package query
import (
"context"
"database/sql"
errs "errors"
"time"
sq "github.com/Masterminds/squirrel"
"github.com/caos/zitadel/internal/errors"
"github.com/caos/zitadel/internal/query/projection"
)
type LockoutPolicy struct {
ID string
Sequence uint64
CreationDate time.Time
ChangeDate time.Time
ResourceOwner string
MaxPasswordAttempts uint64
ShowFailures bool
IsDefault bool
}
var (
lockoutTable = table{
name: projection.LockoutPolicyTable,
}
LockoutColID = Column{
name: projection.LockoutPolicyIDCol,
}
LockoutColSequence = Column{
name: projection.LockoutPolicySequenceCol,
}
LockoutColCreationDate = Column{
name: projection.LockoutPolicyCreationDateCol,
}
LockoutColChangeDate = Column{
name: projection.LockoutPolicyChangeDateCol,
}
LockoutColResourceOwner = Column{
name: projection.LockoutPolicyResourceOwnerCol,
}
LockoutColShowFailures = Column{
name: projection.LockoutPolicyShowLockOutFailuresCol,
}
LockoutColMaxPasswordAttempts = Column{
name: projection.LockoutPolicyMaxPasswordAttemptsCol,
}
LockoutColIsDefault = Column{
name: projection.LockoutPolicyIsDefaultCol,
}
)
func (q *Queries) LockoutPolicyByOrg(ctx context.Context, orgID string) (*LockoutPolicy, error) {
stmt, scan := prepareLockoutPolicyQuery()
query, args, err := stmt.Where(
sq.Or{
sq.Eq{
LockoutColID.identifier(): orgID,
},
sq.Eq{
LockoutColID.identifier(): q.iamID,
},
}).
OrderBy(LockoutColIsDefault.identifier()).
Limit(1).ToSql()
if err != nil {
return nil, errors.ThrowInternal(err, "QUERY-SKR6X", "Errors.Query.SQLStatement")
}
row := q.client.QueryRowContext(ctx, query, args...)
return scan(row)
}
func (q *Queries) DefaultLockoutPolicy(ctx context.Context) (*LockoutPolicy, error) {
stmt, scan := prepareLockoutPolicyQuery()
query, args, err := stmt.Where(sq.Eq{
LockoutColID.identifier(): q.iamID,
}).
OrderBy(LockoutColIsDefault.identifier()).
Limit(1).ToSql()
if err != nil {
return nil, errors.ThrowInternal(err, "QUERY-mN0Ci", "Errors.Query.SQLStatement")
}
row := q.client.QueryRowContext(ctx, query, args...)
return scan(row)
}
func prepareLockoutPolicyQuery() (sq.SelectBuilder, func(*sql.Row) (*LockoutPolicy, error)) {
return sq.Select(
LockoutColID.identifier(),
LockoutColSequence.identifier(),
LockoutColCreationDate.identifier(),
LockoutColChangeDate.identifier(),
LockoutColResourceOwner.identifier(),
LockoutColShowFailures.identifier(),
LockoutColMaxPasswordAttempts.identifier(),
LockoutColIsDefault.identifier(),
).
From(lockoutTable.identifier()).PlaceholderFormat(sq.Dollar),
func(row *sql.Row) (*LockoutPolicy, error) {
policy := new(LockoutPolicy)
err := row.Scan(
&policy.ID,
&policy.Sequence,
&policy.CreationDate,
&policy.ChangeDate,
&policy.ResourceOwner,
&policy.ShowFailures,
&policy.MaxPasswordAttempts,
&policy.IsDefault,
)
if err != nil {
if errs.Is(err, sql.ErrNoRows) {
return nil, errors.ThrowNotFound(err, "QUERY-63mtI", "Errors.PasswordComplexityPolicy.NotFound")
}
return nil, errors.ThrowInternal(err, "QUERY-uulCZ", "Errors.Internal")
}
return policy, nil
}
}

View File

@ -0,0 +1,147 @@
package projection
import (
"context"
"github.com/caos/logging"
"github.com/caos/zitadel/internal/domain"
"github.com/caos/zitadel/internal/errors"
"github.com/caos/zitadel/internal/eventstore"
"github.com/caos/zitadel/internal/eventstore/handler"
"github.com/caos/zitadel/internal/eventstore/handler/crdb"
"github.com/caos/zitadel/internal/repository/iam"
"github.com/caos/zitadel/internal/repository/org"
"github.com/caos/zitadel/internal/repository/policy"
)
type LockoutPolicyProjection struct {
crdb.StatementHandler
}
const (
LockoutPolicyTable = "zitadel.projections.lockout_policies"
LockoutPolicyCreationDateCol = "creation_date"
LockoutPolicyChangeDateCol = "change_date"
LockoutPolicySequenceCol = "sequence"
LockoutPolicyIDCol = "id"
LockoutPolicyStateCol = "state"
LockoutPolicyMaxPasswordAttemptsCol = "max_password_attempts"
LockoutPolicyShowLockOutFailuresCol = "show_failure"
LockoutPolicyIsDefaultCol = "is_default"
LockoutPolicyResourceOwnerCol = "resource_owner"
)
func NewLockoutPolicyProjection(ctx context.Context, config crdb.StatementHandlerConfig) *LockoutPolicyProjection {
p := &LockoutPolicyProjection{}
config.ProjectionName = LockoutPolicyTable
config.Reducers = p.reducers()
p.StatementHandler = crdb.NewStatementHandler(ctx, config)
return p
}
func (p *LockoutPolicyProjection) reducers() []handler.AggregateReducer {
return []handler.AggregateReducer{
{
Aggregate: org.AggregateType,
EventRedusers: []handler.EventReducer{
{
Event: org.LockoutPolicyAddedEventType,
Reduce: p.reduceAdded,
},
{
Event: org.LockoutPolicyChangedEventType,
Reduce: p.reduceChanged,
},
{
Event: org.LockoutPolicyRemovedEventType,
Reduce: p.reduceRemoved,
},
},
},
{
Aggregate: iam.AggregateType,
EventRedusers: []handler.EventReducer{
{
Event: iam.LockoutPolicyAddedEventType,
Reduce: p.reduceAdded,
},
{
Event: iam.LockoutPolicyChangedEventType,
Reduce: p.reduceChanged,
},
},
},
}
}
func (p *LockoutPolicyProjection) reduceAdded(event eventstore.EventReader) (*handler.Statement, error) {
var policyEvent policy.LockoutPolicyAddedEvent
var isDefault bool
switch e := event.(type) {
case *org.LockoutPolicyAddedEvent:
policyEvent = e.LockoutPolicyAddedEvent
isDefault = false
case *iam.LockoutPolicyAddedEvent:
policyEvent = e.LockoutPolicyAddedEvent
isDefault = true
default:
logging.LogWithFields("PROJE-uFqFM", "seq", event.Sequence(), "expectedTypes", []eventstore.EventType{org.LockoutPolicyAddedEventType, iam.LockoutPolicyAddedEventType}).Error("wrong event type")
return nil, errors.ThrowInvalidArgument(nil, "PROJE-d8mZO", "reduce.wrong.event.type")
}
return crdb.NewCreateStatement(
&policyEvent,
[]handler.Column{
handler.NewCol(LockoutPolicyCreationDateCol, policyEvent.CreationDate()),
handler.NewCol(LockoutPolicyChangeDateCol, policyEvent.CreationDate()),
handler.NewCol(LockoutPolicySequenceCol, policyEvent.Sequence()),
handler.NewCol(LockoutPolicyIDCol, policyEvent.Aggregate().ID),
handler.NewCol(LockoutPolicyStateCol, domain.PolicyStateActive),
handler.NewCol(LockoutPolicyMaxPasswordAttemptsCol, policyEvent.MaxPasswordAttempts),
handler.NewCol(LockoutPolicyShowLockOutFailuresCol, policyEvent.ShowLockOutFailures),
handler.NewCol(LockoutPolicyIsDefaultCol, isDefault),
handler.NewCol(LockoutPolicyResourceOwnerCol, policyEvent.Aggregate().ResourceOwner),
}), nil
}
func (p *LockoutPolicyProjection) reduceChanged(event eventstore.EventReader) (*handler.Statement, error) {
var policyEvent policy.LockoutPolicyChangedEvent
switch e := event.(type) {
case *org.LockoutPolicyChangedEvent:
policyEvent = e.LockoutPolicyChangedEvent
case *iam.LockoutPolicyChangedEvent:
policyEvent = e.LockoutPolicyChangedEvent
default:
logging.LogWithFields("PROJE-iIkej", "seq", event.Sequence(), "expectedTypes", []eventstore.EventType{org.LockoutPolicyChangedEventType, iam.LockoutPolicyChangedEventType}).Error("wrong event type")
return nil, errors.ThrowInvalidArgument(nil, "PROJE-pT3mQ", "reduce.wrong.event.type")
}
cols := []handler.Column{
handler.NewCol(LockoutPolicyChangeDateCol, policyEvent.CreationDate()),
handler.NewCol(LockoutPolicySequenceCol, policyEvent.Sequence()),
}
if policyEvent.MaxPasswordAttempts != nil {
cols = append(cols, handler.NewCol(LockoutPolicyMaxPasswordAttemptsCol, *policyEvent.MaxPasswordAttempts))
}
if policyEvent.ShowLockOutFailures != nil {
cols = append(cols, handler.NewCol(LockoutPolicyShowLockOutFailuresCol, *policyEvent.ShowLockOutFailures))
}
return crdb.NewUpdateStatement(
&policyEvent,
cols,
[]handler.Condition{
handler.NewCond(LockoutPolicyIDCol, policyEvent.Aggregate().ID),
}), nil
}
func (p *LockoutPolicyProjection) reduceRemoved(event eventstore.EventReader) (*handler.Statement, error) {
policyEvent, ok := event.(*org.LockoutPolicyRemovedEvent)
if !ok {
logging.LogWithFields("PROJE-U5cys", "seq", event.Sequence(), "expectedType", org.LockoutPolicyRemovedEventType).Error("wrong event type")
return nil, errors.ThrowInvalidArgument(nil, "PROJE-Bqut9", "reduce.wrong.event.type")
}
return crdb.NewDeleteStatement(
policyEvent,
[]handler.Condition{
handler.NewCond(LockoutPolicyIDCol, policyEvent.Aggregate().ID),
}), nil
}

View File

@ -0,0 +1,210 @@
package projection
import (
"testing"
"github.com/caos/zitadel/internal/domain"
"github.com/caos/zitadel/internal/errors"
"github.com/caos/zitadel/internal/eventstore"
"github.com/caos/zitadel/internal/eventstore/handler"
"github.com/caos/zitadel/internal/eventstore/repository"
"github.com/caos/zitadel/internal/repository/iam"
"github.com/caos/zitadel/internal/repository/org"
)
func TestLockoutPolicyProjection_reduces(t *testing.T) {
type args struct {
event func(t *testing.T) eventstore.EventReader
}
tests := []struct {
name string
args args
reduce func(event eventstore.EventReader) (*handler.Statement, error)
want wantReduce
}{
{
name: "org.reduceAdded",
args: args{
event: getEvent(testEvent(
repository.EventType(org.LockoutPolicyAddedEventType),
org.AggregateType,
[]byte(`{
"maxPasswordAttempts": 10,
"showLockOutFailures": true
}`),
), org.LockoutPolicyAddedEventMapper),
},
reduce: (&LockoutPolicyProjection{}).reduceAdded,
want: wantReduce{
aggregateType: eventstore.AggregateType("org"),
sequence: 15,
previousSequence: 10,
projection: LockoutPolicyTable,
executer: &testExecuter{
executions: []execution{
{
expectedStmt: "INSERT INTO zitadel.projections.lockout_policies (creation_date, change_date, sequence, id, state, max_password_attempts, show_failure, is_default, resource_owner) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)",
expectedArgs: []interface{}{
anyArg{},
anyArg{},
uint64(15),
"agg-id",
domain.PolicyStateActive,
uint64(10),
true,
false,
"ro-id",
},
},
},
},
},
},
{
name: "org.reduceChanged",
reduce: (&LockoutPolicyProjection{}).reduceChanged,
args: args{
event: getEvent(testEvent(
repository.EventType(org.LockoutPolicyChangedEventType),
org.AggregateType,
[]byte(`{
"maxPasswordAttempts": 10,
"showLockOutFailures": true
}`),
), org.LockoutPolicyChangedEventMapper),
},
want: wantReduce{
aggregateType: eventstore.AggregateType("org"),
sequence: 15,
previousSequence: 10,
projection: LockoutPolicyTable,
executer: &testExecuter{
executions: []execution{
{
expectedStmt: "UPDATE zitadel.projections.lockout_policies SET (change_date, sequence, max_password_attempts, show_failure) = ($1, $2, $3, $4) WHERE (id = $5)",
expectedArgs: []interface{}{
anyArg{},
uint64(15),
uint64(10),
true,
"agg-id",
},
},
},
},
},
},
{
name: "org.reduceRemoved",
reduce: (&LockoutPolicyProjection{}).reduceRemoved,
args: args{
event: getEvent(testEvent(
repository.EventType(org.LockoutPolicyRemovedEventType),
org.AggregateType,
nil,
), org.LockoutPolicyRemovedEventMapper),
},
want: wantReduce{
aggregateType: eventstore.AggregateType("org"),
sequence: 15,
previousSequence: 10,
projection: LockoutPolicyTable,
executer: &testExecuter{
executions: []execution{
{
expectedStmt: "DELETE FROM zitadel.projections.lockout_policies WHERE (id = $1)",
expectedArgs: []interface{}{
"agg-id",
},
},
},
},
},
},
{
name: "iam.reduceAdded",
reduce: (&LockoutPolicyProjection{}).reduceAdded,
args: args{
event: getEvent(testEvent(
repository.EventType(iam.LockoutPolicyAddedEventType),
iam.AggregateType,
[]byte(`{
"maxPasswordAttempts": 10,
"showLockOutFailures": true
}`),
), iam.LockoutPolicyAddedEventMapper),
},
want: wantReduce{
aggregateType: eventstore.AggregateType("iam"),
sequence: 15,
previousSequence: 10,
projection: LockoutPolicyTable,
executer: &testExecuter{
executions: []execution{
{
expectedStmt: "INSERT INTO zitadel.projections.lockout_policies (creation_date, change_date, sequence, id, state, max_password_attempts, show_failure, is_default, resource_owner) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)",
expectedArgs: []interface{}{
anyArg{},
anyArg{},
uint64(15),
"agg-id",
domain.PolicyStateActive,
uint64(10),
true,
true,
"ro-id",
},
},
},
},
},
},
{
name: "iam.reduceChanged",
reduce: (&LockoutPolicyProjection{}).reduceChanged,
args: args{
event: getEvent(testEvent(
repository.EventType(iam.LockoutPolicyChangedEventType),
iam.AggregateType,
[]byte(`{
"maxPasswordAttempts": 10,
"showLockOutFailures": true
}`),
), iam.LockoutPolicyChangedEventMapper),
},
want: wantReduce{
aggregateType: eventstore.AggregateType("iam"),
sequence: 15,
previousSequence: 10,
projection: LockoutPolicyTable,
executer: &testExecuter{
executions: []execution{
{
expectedStmt: "UPDATE zitadel.projections.lockout_policies SET (change_date, sequence, max_password_attempts, show_failure) = ($1, $2, $3, $4) WHERE (id = $5)",
expectedArgs: []interface{}{
anyArg{},
uint64(15),
uint64(10),
true,
"agg-id",
},
},
},
},
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
event := baseEvent(t)
got, err := tt.reduce(event)
if _, ok := err.(errors.InvalidArgument); !ok {
t.Errorf("no wrong event mapping: %v, got: %v", err, got)
}
event = tt.args.event(t)
got, err = tt.reduce(event)
assertReduce(t, got, err, tt.want)
})
}
}

View File

@ -39,6 +39,7 @@ func Start(ctx context.Context, sqlClient *sql.DB, es *eventstore.Eventstore, co
NewProjectProjection(ctx, applyCustomConfig(projectionConfig, config.Customizations["projects"]))
NewPasswordComplexityProjection(ctx, applyCustomConfig(projectionConfig, config.Customizations["password_complexities"]))
NewPasswordAgeProjection(ctx, applyCustomConfig(projectionConfig, config.Customizations["password_age_policy"]))
NewLockoutPolicyProjection(ctx, applyCustomConfig(projectionConfig, config.Customizations["lockout_policy"]))
NewProjectGrantProjection(ctx, applyCustomConfig(projectionConfig, config.Customizations["project_grants"]))
NewProjectRoleProjection(ctx, applyCustomConfig(projectionConfig, config.Customizations["project_roles"]))
// owner.NewOrgOwnerProjection(ctx, applyCustomConfig(projectionConfig, config.Customizations["org_owners"]))

View File

@ -0,0 +1,14 @@
CREATE TABLE zitadel.projections.lockout_policies (
id STRING NOT NULL,
creation_date TIMESTAMPTZ NULL,
change_date TIMESTAMPTZ NULL,
sequence INT8 NULL,
state INT2 NULL,
resource_owner TEXT,
is_default BOOLEAN,
max_password_attempts INT8 NULL,
show_failure BOOLEAN NULL,
PRIMARY KEY (id)
);