fix(projections): login names projection (#2698)

* refactor(domain): add user type

* fix(projections): start with login names

* fix(login_policy): correct handling of user domain claimed event

* refactor: login name projection

* fix: set correct suffixes on login name projections

* test(projections): login name reduces

* migration versioning

* refactor: use const for login name table name
This commit is contained in:
Silvan 2021-11-23 10:31:23 +01:00 committed by GitHub
parent a194354f47
commit 861b777d9f
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
6 changed files with 1247 additions and 0 deletions

View File

@ -26,3 +26,16 @@ func (f UserState) Valid() bool {
func (s UserState) Exists() bool {
return s != UserStateUnspecified && s != UserStateDeleted
}
type UserType int32
const (
UserTypeUnspecified UserType = iota
UserTypeHuman
UserTypeMachine
userTypeCount
)
func (f UserType) Valid() bool {
return f >= 0 && f < userTypeCount
}

View File

@ -0,0 +1,350 @@
package projection
import (
"context"
"github.com/caos/logging"
"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"
"github.com/caos/zitadel/internal/repository/user"
)
type LoginNameProjection struct {
crdb.StatementHandler
}
const (
LoginNameProjectionTable = "zitadel.projections.login_names"
LoginNameUserProjectionTable = LoginNameProjectionTable + "_" + loginNameUserSuffix
LoginNamePolicyProjectionTable = LoginNameProjectionTable + "_" + loginNamePolicySuffix
LoginNameDomainProjectionTable = LoginNameProjectionTable + "_" + loginNameDomainSuffix
)
func NewLoginNameProjection(ctx context.Context, config crdb.StatementHandlerConfig) *LoginNameProjection {
p := &LoginNameProjection{}
config.ProjectionName = LoginNameProjectionTable
config.Reducers = p.reducers()
p.StatementHandler = crdb.NewStatementHandler(ctx, config)
return p
}
func (p *LoginNameProjection) reducers() []handler.AggregateReducer {
return []handler.AggregateReducer{
{
Aggregate: user.AggregateType,
EventRedusers: []handler.EventReducer{
{
Event: user.HumanAddedType,
Reduce: p.reduceUserCreated,
},
{
Event: user.HumanRegisteredType,
Reduce: p.reduceUserCreated,
},
{
Event: user.MachineAddedEventType,
Reduce: p.reduceUserCreated,
},
{
Event: user.UserRemovedType,
Reduce: p.reduceUserRemoved,
},
{
Event: user.UserUserNameChangedType,
Reduce: p.reduceUserNameChanged,
},
{
// changes the username of the user
// this event occures in orgs
// where policy.must_be_domain=false
Event: user.UserDomainClaimedType,
Reduce: p.reduceUserDomainClaimed,
},
},
},
{
Aggregate: org.AggregateType,
EventRedusers: []handler.EventReducer{
{
Event: org.OrgIAMPolicyAddedEventType,
Reduce: p.reduceOrgIAMPolicyAdded,
},
{
Event: org.OrgIAMPolicyChangedEventType,
Reduce: p.reduceOrgIAMPolicyChanged,
},
{
Event: org.OrgIAMPolicyRemovedEventType,
Reduce: p.reduceOrgIAMPolicyRemoved,
},
{
Event: org.OrgDomainPrimarySetEventType,
Reduce: p.reducePrimaryDomainSet,
},
{
Event: org.OrgDomainRemovedEventType,
Reduce: p.reduceDomainRemoved,
},
{
Event: org.OrgDomainVerifiedEventType,
Reduce: p.reduceDomainVerified,
},
},
},
{
Aggregate: iam.AggregateType,
EventRedusers: []handler.EventReducer{
{
Event: iam.OrgIAMPolicyAddedEventType,
Reduce: p.reduceOrgIAMPolicyAdded,
},
{
Event: iam.OrgIAMPolicyChangedEventType,
Reduce: p.reduceOrgIAMPolicyChanged,
},
},
},
}
}
const (
loginNameUserSuffix = "users"
LoginNameUserIDCol = "id"
LoginNameUserUserNameCol = "user_name"
LoginNameUserResourceOwnerCol = "resource_owner"
loginNameDomainSuffix = "domains"
LoginNameDomainNameCol = "name"
LoginNameDomainIsPrimaryCol = "is_primary"
LoginNameDomainResourceOwnerCol = "resource_owner"
loginNamePolicySuffix = "policies"
LoginNamePoliciesMustBeDomainCol = "must_be_domain"
LoginNamePoliciesIsDefaultCol = "is_default"
LoginNamePoliciesResourceOwnerCol = "resource_owner"
)
func (p *LoginNameProjection) reduceUserCreated(event eventstore.EventReader) (*handler.Statement, error) {
var userName string
switch e := event.(type) {
case *user.HumanAddedEvent:
userName = e.UserName
case *user.HumanRegisteredEvent:
userName = e.UserName
case *user.MachineAddedEvent:
userName = e.UserName
default:
logging.LogWithFields("HANDL-tDUx3", "seq", event.Sequence(), "expectedTypes", []eventstore.EventType{user.HumanAddedType, user.HumanRegisteredType, user.MachineAddedEventType}).Error("wrong event type")
return nil, errors.ThrowInvalidArgument(nil, "HANDL-ayo69", "reduce.wrong.event.type")
}
return crdb.NewCreateStatement(
event,
[]handler.Column{
handler.NewCol(LoginNameUserIDCol, event.Aggregate().ID),
handler.NewCol(LoginNameUserUserNameCol, userName),
handler.NewCol(LoginNameUserResourceOwnerCol, event.Aggregate().ResourceOwner),
},
crdb.WithTableSuffix(loginNameUserSuffix),
), nil
}
func (p *LoginNameProjection) reduceUserRemoved(event eventstore.EventReader) (*handler.Statement, error) {
e, ok := event.(*user.UserRemovedEvent)
if !ok {
logging.LogWithFields("HANDL-8XEdC", "seq", event.Sequence(), "expectedType", user.UserRemovedType).Error("wrong event type")
return nil, errors.ThrowInvalidArgument(nil, "HANDL-QIe3C", "reduce.wrong.event.type")
}
return crdb.NewDeleteStatement(
event,
[]handler.Condition{
handler.NewCond(LoginNameUserIDCol, e.Aggregate().ID),
},
crdb.WithTableSuffix(loginNameUserSuffix),
), nil
}
func (p *LoginNameProjection) reduceUserNameChanged(event eventstore.EventReader) (*handler.Statement, error) {
e, ok := event.(*user.UsernameChangedEvent)
if !ok {
logging.LogWithFields("HANDL-UGo7U", "seq", event.Sequence(), "expectedType", user.UserUserNameChangedType).Error("wrong event type")
return nil, errors.ThrowInvalidArgument(nil, "HANDL-QlwjC", "reduce.wrong.event.type")
}
return crdb.NewUpdateStatement(
event,
[]handler.Column{
handler.NewCol(LoginNameUserUserNameCol, e.UserName),
},
[]handler.Condition{
handler.NewCond(LoginNameUserIDCol, e.Aggregate().ID),
},
crdb.WithTableSuffix(loginNameUserSuffix),
), nil
}
func (p *LoginNameProjection) reduceUserDomainClaimed(event eventstore.EventReader) (*handler.Statement, error) {
e, ok := event.(*user.DomainClaimedEvent)
if !ok {
logging.LogWithFields("HANDL-zIbyU", "seq", event.Sequence(), "expectedType", user.UserDomainClaimedType).Error("wrong event type")
return nil, errors.ThrowInvalidArgument(nil, "HANDL-AQMBY", "reduce.wrong.event.type")
}
return crdb.NewUpdateStatement(
event,
[]handler.Column{
handler.NewCol(LoginNameUserUserNameCol, e.UserName),
},
[]handler.Condition{
handler.NewCond(LoginNameUserIDCol, e.Aggregate().ID),
},
crdb.WithTableSuffix(loginNameUserSuffix),
), nil
}
func (p *LoginNameProjection) reduceOrgIAMPolicyAdded(event eventstore.EventReader) (*handler.Statement, error) {
var (
policyEvent *policy.OrgIAMPolicyAddedEvent
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("HANDL-PQluH", "seq", event.Sequence(), "expectedTypes", []eventstore.EventType{org.OrgIAMPolicyAddedEventType, iam.OrgIAMPolicyAddedEventType}).Error("wrong event type")
return nil, errors.ThrowInvalidArgument(nil, "HANDL-yCV6S", "reduce.wrong.event.type")
}
return crdb.NewCreateStatement(
event,
[]handler.Column{
handler.NewCol(LoginNamePoliciesMustBeDomainCol, policyEvent.UserLoginMustBeDomain),
handler.NewCol(LoginNamePoliciesIsDefaultCol, isDefault),
handler.NewCol(LoginNamePoliciesResourceOwnerCol, policyEvent.Aggregate().ResourceOwner),
},
crdb.WithTableSuffix(loginNamePolicySuffix),
), nil
}
func (p *LoginNameProjection) reduceOrgIAMPolicyChanged(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("HANDL-Z27QN", "seq", event.Sequence(), "expectedTypes", []eventstore.EventType{org.OrgIAMPolicyChangedEventType, iam.OrgIAMPolicyChangedEventType}).Error("wrong event type")
return nil, errors.ThrowInvalidArgument(nil, "HANDL-ArFDd", "reduce.wrong.event.type")
}
if policyEvent.UserLoginMustBeDomain == nil {
return crdb.NewNoOpStatement(event), nil
}
return crdb.NewUpdateStatement(
event,
[]handler.Column{
handler.NewCol(LoginNamePoliciesMustBeDomainCol, *policyEvent.UserLoginMustBeDomain),
},
[]handler.Condition{
handler.NewCond(LoginNamePoliciesResourceOwnerCol, policyEvent.Aggregate().ResourceOwner),
},
crdb.WithTableSuffix(loginNamePolicySuffix),
), nil
}
func (p *LoginNameProjection) reduceOrgIAMPolicyRemoved(event eventstore.EventReader) (*handler.Statement, error) {
e, ok := event.(*org.OrgIAMPolicyRemovedEvent)
if !ok {
logging.LogWithFields("HANDL-1ZFHL", "seq", event.Sequence(), "expectedType", org.OrgIAMPolicyRemovedEventType).Error("wrong event type")
return nil, errors.ThrowInvalidArgument(nil, "HANDL-ysEeB", "reduce.wrong.event.type")
}
return crdb.NewDeleteStatement(
event,
[]handler.Condition{
handler.NewCond(LoginNamePoliciesResourceOwnerCol, e.Aggregate().ResourceOwner),
},
crdb.WithTableSuffix(loginNamePolicySuffix),
), nil
}
func (p *LoginNameProjection) reduceDomainVerified(event eventstore.EventReader) (*handler.Statement, error) {
e, ok := event.(*org.DomainVerifiedEvent)
if !ok {
logging.LogWithFields("HANDL-Rr7Tq", "seq", event.Sequence(), "expectedType", org.OrgDomainVerifiedEventType).Error("wrong event type")
return nil, errors.ThrowInvalidArgument(nil, "HANDL-weGAh", "reduce.wrong.event.type")
}
return crdb.NewCreateStatement(
event,
[]handler.Column{
handler.NewCol(LoginNameDomainNameCol, e.Domain),
handler.NewCol(LoginNameDomainResourceOwnerCol, e.Aggregate().ResourceOwner),
},
crdb.WithTableSuffix(loginNameDomainSuffix),
), nil
}
func (p *LoginNameProjection) reducePrimaryDomainSet(event eventstore.EventReader) (*handler.Statement, error) {
e, ok := event.(*org.DomainPrimarySetEvent)
if !ok {
logging.LogWithFields("HANDL-0L5tW", "seq", event.Sequence(), "expectedType", org.OrgDomainPrimarySetEventType).Error("wrong event type")
return nil, errors.ThrowInvalidArgument(nil, "HANDL-eOXPN", "reduce.wrong.event.type")
}
return crdb.NewMultiStatement(
e,
crdb.AddUpdateStatement(
[]handler.Column{
handler.NewCol(LoginNameDomainIsPrimaryCol, false),
},
[]handler.Condition{
handler.NewCond(LoginNameDomainResourceOwnerCol, e.Aggregate().ResourceOwner),
handler.NewCond(LoginNameDomainIsPrimaryCol, true),
},
crdb.WithTableSuffix(loginNameDomainSuffix),
),
crdb.AddUpdateStatement(
[]handler.Column{
handler.NewCol(LoginNameDomainIsPrimaryCol, true),
},
[]handler.Condition{
handler.NewCond(LoginNameDomainNameCol, e.Domain),
handler.NewCond(LoginNameDomainResourceOwnerCol, e.Aggregate().ResourceOwner),
},
crdb.WithTableSuffix(loginNameDomainSuffix),
),
), nil
}
func (p *LoginNameProjection) reduceDomainRemoved(event eventstore.EventReader) (*handler.Statement, error) {
e, ok := event.(*org.DomainRemovedEvent)
if !ok {
logging.LogWithFields("HANDL-reP2u", "seq", event.Sequence(), "expectedType", org.OrgDomainRemovedEventType).Error("wrong event type")
return nil, errors.ThrowInvalidArgument(nil, "HANDL-4RHYq", "reduce.wrong.event.type")
}
return crdb.NewDeleteStatement(
event,
[]handler.Condition{
handler.NewCond(LoginNameDomainNameCol, e.Domain),
handler.NewCond(LoginNameDomainResourceOwnerCol, e.Aggregate().ResourceOwner),
},
crdb.WithTableSuffix(loginNameDomainSuffix),
), nil
}

View File

@ -0,0 +1,507 @@
package projection
import (
"testing"
"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"
"github.com/caos/zitadel/internal/repository/user"
)
func TestLoginNameProjection_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: "user.HumanAddedType",
args: args{
event: getEvent(testEvent(
repository.EventType(user.HumanAddedType),
user.AggregateType,
[]byte(`{
"userName": "human-added"
}`),
), user.HumanAddedEventMapper),
},
reduce: (&LoginNameProjection{}).reduceUserCreated,
want: wantReduce{
aggregateType: user.AggregateType,
sequence: 15,
previousSequence: 10,
projection: LoginNameProjectionTable,
executer: &testExecuter{
executions: []execution{
{
expectedStmt: "INSERT INTO zitadel.projections.login_names_users (id, user_name, resource_owner) VALUES ($1, $2, $3)",
expectedArgs: []interface{}{
"agg-id",
"human-added",
"ro-id",
},
},
},
},
},
},
{
name: "user.HumanRegisteredType",
args: args{
event: getEvent(testEvent(
repository.EventType(user.HumanRegisteredType),
user.AggregateType,
[]byte(`{
"userName": "human-registered"
}`),
), user.HumanRegisteredEventMapper),
},
reduce: (&LoginNameProjection{}).reduceUserCreated,
want: wantReduce{
aggregateType: user.AggregateType,
sequence: 15,
previousSequence: 10,
projection: LoginNameProjectionTable,
executer: &testExecuter{
executions: []execution{
{
expectedStmt: "INSERT INTO zitadel.projections.login_names_users (id, user_name, resource_owner) VALUES ($1, $2, $3)",
expectedArgs: []interface{}{
"agg-id",
"human-registered",
"ro-id",
},
},
},
},
},
},
{
name: "user.MachineAddedEventType",
args: args{
event: getEvent(testEvent(
repository.EventType(user.MachineAddedEventType),
user.AggregateType,
[]byte(`{
"userName": "machine-added"
}`),
), user.MachineAddedEventMapper),
},
reduce: (&LoginNameProjection{}).reduceUserCreated,
want: wantReduce{
aggregateType: user.AggregateType,
sequence: 15,
previousSequence: 10,
projection: LoginNameProjectionTable,
executer: &testExecuter{
executions: []execution{
{
expectedStmt: "INSERT INTO zitadel.projections.login_names_users (id, user_name, resource_owner) VALUES ($1, $2, $3)",
expectedArgs: []interface{}{
"agg-id",
"machine-added",
"ro-id",
},
},
},
},
},
},
{
name: "user.UserRemovedType",
args: args{
event: getEvent(testEvent(
repository.EventType(user.UserRemovedType),
user.AggregateType,
[]byte(`{}`),
), user.UserRemovedEventMapper),
},
reduce: (&LoginNameProjection{}).reduceUserRemoved,
want: wantReduce{
aggregateType: user.AggregateType,
sequence: 15,
previousSequence: 10,
projection: LoginNameProjectionTable,
executer: &testExecuter{
executions: []execution{
{
expectedStmt: "DELETE FROM zitadel.projections.login_names_users WHERE (id = $1)",
expectedArgs: []interface{}{
"agg-id",
},
},
},
},
},
},
{
name: "user.UserUserNameChangedType",
args: args{
event: getEvent(testEvent(
repository.EventType(user.UserUserNameChangedType),
user.AggregateType,
[]byte(`{
"userName": "changed"
}`),
), user.UsernameChangedEventMapper),
},
reduce: (&LoginNameProjection{}).reduceUserNameChanged,
want: wantReduce{
aggregateType: user.AggregateType,
sequence: 15,
previousSequence: 10,
projection: LoginNameProjectionTable,
executer: &testExecuter{
executions: []execution{
{
expectedStmt: "UPDATE zitadel.projections.login_names_users SET (user_name) = ($1) WHERE (id = $2)",
expectedArgs: []interface{}{
"changed",
"agg-id",
},
},
},
},
},
},
{
name: "user.UserDomainClaimedType",
args: args{
event: getEvent(testEvent(
repository.EventType(user.UserDomainClaimedType),
user.AggregateType,
[]byte(`{
"userName": "claimed"
}`),
), user.DomainClaimedEventMapper),
},
reduce: (&LoginNameProjection{}).reduceUserDomainClaimed,
want: wantReduce{
aggregateType: user.AggregateType,
sequence: 15,
previousSequence: 10,
projection: LoginNameProjectionTable,
executer: &testExecuter{
executions: []execution{
{
expectedStmt: "UPDATE zitadel.projections.login_names_users SET (user_name) = ($1) WHERE (id = $2)",
expectedArgs: []interface{}{
"claimed",
"agg-id",
},
},
},
},
},
},
{
name: "org.OrgIAMPolicyAddedEventType",
args: args{
event: getEvent(testEvent(
repository.EventType(org.OrgIAMPolicyAddedEventType),
user.AggregateType,
[]byte(`{
"userLoginMustBeDomain": true
}`),
), org.OrgIAMPolicyAddedEventMapper),
},
reduce: (&LoginNameProjection{}).reduceOrgIAMPolicyAdded,
want: wantReduce{
aggregateType: user.AggregateType,
sequence: 15,
previousSequence: 10,
projection: LoginNameProjectionTable,
executer: &testExecuter{
executions: []execution{
{
expectedStmt: "INSERT INTO zitadel.projections.login_names_policies (must_be_domain, is_default, resource_owner) VALUES ($1, $2, $3)",
expectedArgs: []interface{}{
true,
false,
"ro-id",
},
},
},
},
},
},
{
name: "org.OrgIAMPolicyChangedEventType",
args: args{
event: getEvent(testEvent(
repository.EventType(org.OrgIAMPolicyChangedEventType),
user.AggregateType,
[]byte(`{
"userLoginMustBeDomain": false
}`),
), org.OrgIAMPolicyChangedEventMapper),
},
reduce: (&LoginNameProjection{}).reduceOrgIAMPolicyChanged,
want: wantReduce{
aggregateType: user.AggregateType,
sequence: 15,
previousSequence: 10,
projection: LoginNameProjectionTable,
executer: &testExecuter{
executions: []execution{
{
expectedStmt: "UPDATE zitadel.projections.login_names_policies SET (must_be_domain) = ($1) WHERE (resource_owner = $2)",
expectedArgs: []interface{}{
false,
"ro-id",
},
},
},
},
},
},
{
name: "org.OrgIAMPolicyChangedEventType no change",
args: args{
event: getEvent(testEvent(
repository.EventType(org.OrgIAMPolicyChangedEventType),
user.AggregateType,
[]byte(`{}`),
), org.OrgIAMPolicyChangedEventMapper),
},
reduce: (&LoginNameProjection{}).reduceOrgIAMPolicyChanged,
want: wantReduce{
aggregateType: user.AggregateType,
sequence: 15,
previousSequence: 10,
projection: LoginNameProjectionTable,
executer: &testExecuter{
executions: []execution{},
},
},
},
{
name: "org.OrgIAMPolicyRemovedEventType",
args: args{
event: getEvent(testEvent(
repository.EventType(org.OrgIAMPolicyRemovedEventType),
user.AggregateType,
[]byte(`{}`),
), org.OrgIAMPolicyRemovedEventMapper),
},
reduce: (&LoginNameProjection{}).reduceOrgIAMPolicyRemoved,
want: wantReduce{
aggregateType: user.AggregateType,
sequence: 15,
previousSequence: 10,
projection: LoginNameProjectionTable,
executer: &testExecuter{
executions: []execution{
{
expectedStmt: "DELETE FROM zitadel.projections.login_names_policies WHERE (resource_owner = $1)",
expectedArgs: []interface{}{
"ro-id",
},
},
},
},
},
},
{
name: "org.OrgDomainVerifiedEventType",
args: args{
event: getEvent(testEvent(
repository.EventType(org.OrgDomainVerifiedEventType),
user.AggregateType,
[]byte(`{
"domain": "verified"
}`),
), org.DomainVerifiedEventMapper),
},
reduce: (&LoginNameProjection{}).reduceDomainVerified,
want: wantReduce{
aggregateType: user.AggregateType,
sequence: 15,
previousSequence: 10,
projection: LoginNameProjectionTable,
executer: &testExecuter{
executions: []execution{
{
expectedStmt: "INSERT INTO zitadel.projections.login_names_domains (name, resource_owner) VALUES ($1, $2)",
expectedArgs: []interface{}{
"verified",
"ro-id",
},
},
},
},
},
},
{
name: "org.OrgDomainRemovedEventType",
args: args{
event: getEvent(testEvent(
repository.EventType(org.OrgDomainRemovedEventType),
user.AggregateType,
[]byte(`{
"domain": "remove"
}`),
), org.DomainRemovedEventMapper),
},
reduce: (&LoginNameProjection{}).reduceDomainRemoved,
want: wantReduce{
aggregateType: user.AggregateType,
sequence: 15,
previousSequence: 10,
projection: LoginNameProjectionTable,
executer: &testExecuter{
executions: []execution{
{
expectedStmt: "DELETE FROM zitadel.projections.login_names_domains WHERE (name = $1) AND (resource_owner = $2)",
expectedArgs: []interface{}{
"remove",
"ro-id",
},
},
},
},
},
},
{
name: "org.OrgDomainPrimarySetEventType",
args: args{
event: getEvent(testEvent(
repository.EventType(org.OrgDomainPrimarySetEventType),
user.AggregateType,
[]byte(`{
"domain": "primary"
}`),
), org.DomainPrimarySetEventMapper),
},
reduce: (&LoginNameProjection{}).reducePrimaryDomainSet,
want: wantReduce{
aggregateType: user.AggregateType,
sequence: 15,
previousSequence: 10,
projection: LoginNameProjectionTable,
executer: &testExecuter{
executions: []execution{
{
expectedStmt: "UPDATE zitadel.projections.login_names_domains SET (is_primary) = ($1) WHERE (resource_owner = $2) AND (is_primary = $3)",
expectedArgs: []interface{}{
false,
"ro-id",
true,
},
},
{
expectedStmt: "UPDATE zitadel.projections.login_names_domains SET (is_primary) = ($1) WHERE (name = $2) AND (resource_owner = $3)",
expectedArgs: []interface{}{
true,
"primary",
"ro-id",
},
},
},
},
},
},
{
name: "iam.OrgIAMPolicyAddedEventType",
args: args{
event: getEvent(testEvent(
repository.EventType(iam.OrgIAMPolicyAddedEventType),
user.AggregateType,
[]byte(`{
"userLoginMustBeDomain": true
}`),
), iam.OrgIAMPolicyAddedEventMapper),
},
reduce: (&LoginNameProjection{}).reduceOrgIAMPolicyAdded,
want: wantReduce{
aggregateType: user.AggregateType,
sequence: 15,
previousSequence: 10,
projection: LoginNameProjectionTable,
executer: &testExecuter{
executions: []execution{
{
expectedStmt: "INSERT INTO zitadel.projections.login_names_policies (must_be_domain, is_default, resource_owner) VALUES ($1, $2, $3)",
expectedArgs: []interface{}{
true,
true,
"ro-id",
},
},
},
},
},
},
{
name: "iam.OrgIAMPolicyChangedEventType",
args: args{
event: getEvent(testEvent(
repository.EventType(iam.OrgIAMPolicyChangedEventType),
user.AggregateType,
[]byte(`{
"userLoginMustBeDomain": false
}`),
), iam.OrgIAMPolicyChangedEventMapper),
},
reduce: (&LoginNameProjection{}).reduceOrgIAMPolicyChanged,
want: wantReduce{
aggregateType: user.AggregateType,
sequence: 15,
previousSequence: 10,
projection: LoginNameProjectionTable,
executer: &testExecuter{
executions: []execution{
{
expectedStmt: "UPDATE zitadel.projections.login_names_policies SET (must_be_domain) = ($1) WHERE (resource_owner = $2)",
expectedArgs: []interface{}{
false,
"ro-id",
},
},
},
},
},
},
{
name: "iam.OrgIAMPolicyChangedEventType no change",
args: args{
event: getEvent(testEvent(
repository.EventType(iam.OrgIAMPolicyChangedEventType),
user.AggregateType,
[]byte(`{}`),
), iam.OrgIAMPolicyChangedEventMapper),
},
reduce: (&LoginNameProjection{}).reduceOrgIAMPolicyChanged,
want: wantReduce{
aggregateType: user.AggregateType,
sequence: 15,
previousSequence: 10,
projection: LoginNameProjectionTable,
executer: &testExecuter{
executions: []execution{},
},
},
},
}
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

@ -55,6 +55,7 @@ func Start(ctx context.Context, sqlClient *sql.DB, es *eventstore.Eventstore, co
NewMessageTextProjection(ctx, applyCustomConfig(projectionConfig, config.Customizations["message_texts"]))
NewCustomTextProjection(ctx, applyCustomConfig(projectionConfig, config.Customizations["custom_texts"]))
NewFeatureProjection(ctx, applyCustomConfig(projectionConfig, config.Customizations["features"]))
NewLoginNameProjection(ctx, applyCustomConfig(projectionConfig, config.Customizations["login_names"]))
return nil
}

View File

@ -0,0 +1,54 @@
CREATE TABLE zitadel.projections.login_names_users (
id STRING NOT NULL
, user_name STRING NOT NULL
, resource_owner STRING NOT NULL
, PRIMARY KEY (id)
, INDEX idx_ro (resource_owner)
);
CREATE TABLE zitadel.projections.login_names_domains (
name STRING NOT NULL
, is_primary BOOLEAN NOT NULL DEFAULT false
, resource_owner STRING NOT NULL
, PRIMARY KEY (resource_owner, name)
);
CREATE TABLE zitadel.projections.login_names_policies (
must_be_domain BOOLEAN NOT NULL
, is_default BOOLEAN NOT NULL
, resource_owner STRING NOT NULL
, PRIMARY KEY (resource_owner)
, INDEX idx_is_default (resource_owner, is_default)
);
CREATE VIEW zitadel.projections.login_names
AS SELECT
user_id
, IF(
must_be_domain
, CONCAT(user_name, '@', domain)
, user_name
) AS login_name
, IFNULL(is_primary, true) AS is_primary -- is_default is null on additional verified domain and policy with must_be_domain=false
FROM (
SELECT
policy_users.user_id
, policy_users.user_name
, policy_users.resource_owner
, policy_users.must_be_domain
, domains.name AS domain
, domains.is_primary
FROM (
SELECT
users.id as user_id
, users.user_name
, users.resource_owner
, IFNULL(policy_custom.must_be_domain, policy_default.must_be_domain) AS must_be_domain
FROM zitadel.projections.login_names_users users
LEFT JOIN zitadel.projections.login_names_policies policy_custom on policy_custom.resource_owner = users.resource_owner
LEFT JOIN zitadel.projections.login_names_policies policy_default on policy_default.is_default = true) policy_users
LEFT JOIN zitadel.projections.login_names_domains domains ON policy_users.must_be_domain AND policy_users.resource_owner = domains.resource_owner
);

View File

@ -0,0 +1,322 @@
-- --------------------------------------------------------
-- only default domain
-- --------------------------------------------------------
BEGIN;
INSERT INTO zitadel.projections.login_names_users (
id
, user_name
, resource_owner
) VALUES
('h', 'human', 'org')
, ('m', 'machine', 'org')
;
INSERT INTO zitadel.projections.login_names_domains (
name
, is_primary
, resource_owner
) VALUES
('org-ch.localhost', true, 'org')
;
INSERT INTO zitadel.projections.login_names_policies (
must_be_domain
, is_default
, resource_owner
) VALUES
(true, true, 'IAM')
;
SELECT * FROM zitadel.projections.login_names WHERE user_id IN ('h', 'm');
ROLLBACK;
-- --------------------------------------------------------
-- default and additional domain verified
-- --------------------------------------------------------
BEGIN;
INSERT INTO zitadel.projections.login_names_users (
id
, user_name
, resource_owner
) VALUES
('h', 'human', 'org')
, ('m', 'machine', 'org')
;
INSERT INTO zitadel.projections.login_names_domains (
name
, is_primary
, resource_owner
) VALUES
('org-ch.localhost', true, 'org')
, ('custom.ch', false, 'org')
;
INSERT INTO zitadel.projections.login_names_policies (
must_be_domain
, is_default
, resource_owner
) VALUES
(true, true, 'IAM')
;
-- default and custom login name => 4 login names default is primary
SELECT * FROM zitadel.projections.login_names WHERE user_id IN ('h', 'm');
ROLLBACK;
-- --------------------------------------------------------
-- default and additional domain verified and primary
-- --------------------------------------------------------
BEGIN;
INSERT INTO zitadel.projections.login_names_users (
id
, user_name
, resource_owner
) VALUES
('h', 'human', 'org')
, ('m', 'machine', 'org')
;
INSERT INTO zitadel.projections.login_names_domains (
name
, is_primary
, resource_owner
) VALUES
('org-ch.localhost', false, 'org')
, ('custom.ch', true, 'org')
;
INSERT INTO zitadel.projections.login_names_policies (
must_be_domain
, is_default
, resource_owner
) VALUES
(true, true, 'IAM')
;
-- default and custom login name => 2 login names default is primary
SELECT * FROM zitadel.projections.login_names WHERE user_id IN ('h', 'm');
ROLLBACK;
-- --------------------------------------------------------
-- custom policy (must_be_domain=false) no domain
-- --------------------------------------------------------
BEGIN;
INSERT INTO zitadel.projections.login_names_users (
id
, user_name
, resource_owner
) VALUES
('h', 'human', 'org')
, ('m', 'machine', 'org')
;
INSERT INTO zitadel.projections.login_names_domains (
name
, is_primary
, resource_owner
) VALUES
-- only default for org
('org-ch.localhost', true, 'org')
;
INSERT INTO zitadel.projections.login_names_policies (
must_be_domain
, is_default
, resource_owner
) VALUES
(true, true, 'IAM')
, (false, false, 'org')
;
-- default and custom login name => 1 login name machine=user_name human=user_name(=email)
SELECT * FROM zitadel.projections.login_names WHERE user_id IN ('h', 'm');
ROLLBACK;
-- --------------------------------------------------------
-- custom policy (must_be_domain=false) verified domain
-- --------------------------------------------------------
BEGIN;
INSERT INTO zitadel.projections.login_names_users (
id
, user_name
, resource_owner
) VALUES
('h', 'human', 'org')
, ('m', 'machine', 'org')
;
INSERT INTO zitadel.projections.login_names_domains (
name
, is_primary
, resource_owner
) VALUES
-- default and unverified for org
('org-ch.localhost', true, 'org')
, ('custom.ch', false, 'org')
;
INSERT INTO zitadel.projections.login_names_policies (
must_be_domain
, is_default
, resource_owner
) VALUES
(true, true, 'IAM')
, (false, false, 'org')
;
-- 1 login name machine=user_name human=user_name(=email)
SELECT * FROM zitadel.projections.login_names WHERE user_id IN ('h', 'm');
ROLLBACK;
-- --------------------------------------------------------
-- custom policy (must_be_domain=false) verified, primary domain
-- --------------------------------------------------------
BEGIN;
INSERT INTO zitadel.projections.login_names_users (
id
, user_name
, resource_owner
) VALUES
('h', 'human', 'org')
, ('m', 'machine', 'org')
;
INSERT INTO zitadel.projections.login_names_domains (
name
, is_primary
, resource_owner
) VALUES
-- default and unverified for org
('org-ch.localhost', false, 'org')
, ('custom.ch', true, 'org')
;
INSERT INTO zitadel.projections.login_names_policies (
must_be_domain
, is_default
, resource_owner
) VALUES
(true, true, 'IAM')
, (false, false, 'org')
;
-- 1 login name machine=user_name human=user_name(=email)
SELECT * FROM zitadel.projections.login_names WHERE user_id IN ('h', 'm');
ROLLBACK;
-- --------------------------------------------------------
-- custom policy (must_be_domain=true) no domain
-- --------------------------------------------------------
BEGIN;
INSERT INTO zitadel.projections.login_names_users (
id
, user_name
, resource_owner
) VALUES
('h', 'human', 'org')
, ('m', 'machine', 'org')
;
INSERT INTO zitadel.projections.login_names_domains (
name
, is_primary
, resource_owner
) VALUES
-- only default for org
('org-ch.localhost', true, 'org')
;
INSERT INTO zitadel.projections.login_names_policies (
must_be_domain
, is_default
, resource_owner
) VALUES
(true, true, 'IAM')
, (true, false, 'org')
;
-- one login per user
SELECT * FROM zitadel.projections.login_names WHERE user_id IN ('h', 'm');
ROLLBACK;
-- --------------------------------------------------------
-- custom policy (must_be_domain=true) verified domain
-- --------------------------------------------------------
BEGIN;
INSERT INTO zitadel.projections.login_names_users (
id
, user_name
, resource_owner
) VALUES
('h', 'human', 'org')
, ('m', 'machine', 'org')
;
INSERT INTO zitadel.projections.login_names_domains (
name
, is_primary
, resource_owner
) VALUES
-- default and unverified for org
('org-ch.localhost', true, 'org')
, ('custom.ch', false, 'org')
;
INSERT INTO zitadel.projections.login_names_policies (
must_be_domain
, is_default
, resource_owner
) VALUES
(true, true, 'IAM')
, (true, false, 'org')
;
-- 2 login names per user
SELECT * FROM zitadel.projections.login_names WHERE user_id IN ('h', 'm');
ROLLBACK;
-- --------------------------------------------------------
-- custom policy (must_be_domain=true) verified, primary domain
-- --------------------------------------------------------
BEGIN;
INSERT INTO zitadel.projections.login_names_users (
id
, user_name
, resource_owner
) VALUES
('h', 'human', 'org')
, ('m', 'machine', 'org')
;
INSERT INTO zitadel.projections.login_names_domains (
name
, is_primary
, resource_owner
) VALUES
-- default and unverified for org
('org-ch.localhost', false, 'org')
, ('custom.ch', true, 'org')
;
INSERT INTO zitadel.projections.login_names_policies (
must_be_domain
, is_default
, resource_owner
) VALUES
(true, true, 'IAM')
, (true, false, 'org')
;
-- 2 login names per user
explain analyze SELECT * FROM zitadel.projections.login_names WHERE user_id = 'h';
ROLLBACK;