feat: add management for ldap idp template (#5220)

Add management functionality for LDAP idps with templates and the basic functionality for the LDAP provider, which can then be used with a separate login page in the future.

---------

Co-authored-by: Livio Spring <livio.a@gmail.com>
This commit is contained in:
Stefan Benz
2023-02-15 09:14:59 +01:00
committed by GitHub
parent 058192c22b
commit 586495a0be
37 changed files with 7298 additions and 14 deletions

View File

@@ -0,0 +1,621 @@
package query
import (
"context"
"database/sql"
errs "errors"
"time"
sq "github.com/Masterminds/squirrel"
"github.com/zitadel/logging"
"github.com/zitadel/zitadel/internal/api/authz"
"github.com/zitadel/zitadel/internal/crypto"
"github.com/zitadel/zitadel/internal/domain"
"github.com/zitadel/zitadel/internal/errors"
"github.com/zitadel/zitadel/internal/query/projection"
"github.com/zitadel/zitadel/internal/repository/idp"
"github.com/zitadel/zitadel/internal/telemetry/tracing"
)
type IDPTemplate struct {
CreationDate time.Time
ChangeDate time.Time
Sequence uint64
ResourceOwner string
ID string
State domain.IDPState
Name string
Type domain.IDPType
OwnerType domain.IdentityProviderType
IsCreationAllowed bool
IsLinkingAllowed bool
IsAutoCreation bool
IsAutoUpdate bool
*LDAPIDPTemplate
}
type IDPTemplates struct {
SearchResponse
Templates []*IDPTemplate
}
type LDAPIDPTemplate struct {
IDPID string
Host string
Port string
TLS bool
BaseDN string
UserObjectClass string
UserUniqueAttribute string
Admin string
Password *crypto.CryptoValue
idp.LDAPAttributes
idp.Options
}
var (
idpTemplateTable = table{
name: projection.IDPTemplateTable,
instanceIDCol: projection.IDPTemplateInstanceIDCol,
}
IDPTemplateIDCol = Column{
name: projection.IDPTemplateIDCol,
table: idpTemplateTable,
}
IDPTemplateCreationDateCol = Column{
name: projection.IDPTemplateCreationDateCol,
table: idpTemplateTable,
}
IDPTemplateChangeDateCol = Column{
name: projection.IDPTemplateChangeDateCol,
table: idpTemplateTable,
}
IDPTemplateSequenceCol = Column{
name: projection.IDPTemplateSequenceCol,
table: idpTemplateTable,
}
IDPTemplateResourceOwnerCol = Column{
name: projection.IDPTemplateResourceOwnerCol,
table: idpTemplateTable,
}
IDPTemplateInstanceIDCol = Column{
name: projection.IDPTemplateInstanceIDCol,
table: idpTemplateTable,
}
IDPTemplateStateCol = Column{
name: projection.IDPTemplateStateCol,
table: idpTemplateTable,
}
IDPTemplateNameCol = Column{
name: projection.IDPTemplateNameCol,
table: idpTemplateTable,
}
IDPTemplateOwnerTypeCol = Column{
name: projection.IDPOwnerTypeCol,
table: idpTemplateTable,
}
IDPTemplateTypeCol = Column{
name: projection.IDPTemplateTypeCol,
table: idpTemplateTable,
}
IDPTemplateOwnerRemovedCol = Column{
name: projection.IDPTemplateOwnerRemovedCol,
table: idpTemplateTable,
}
IDPTemplateIsCreationAllowedCol = Column{
name: projection.IDPTemplateIsCreationAllowedCol,
table: idpTemplateTable,
}
IDPTemplateIsLinkingAllowedCol = Column{
name: projection.IDPTemplateIsLinkingAllowedCol,
table: idpTemplateTable,
}
IDPTemplateIsAutoCreationCol = Column{
name: projection.IDPTemplateIsAutoCreationCol,
table: idpTemplateTable,
}
IDPTemplateIsAutoUpdateCol = Column{
name: projection.IDPTemplateIsAutoUpdateCol,
table: idpTemplateTable,
}
)
var (
ldapIdpTemplateTable = table{
name: projection.IDPTemplateLDAPTable,
instanceIDCol: projection.IDPTemplateInstanceIDCol,
}
LDAPIDCol = Column{
name: projection.LDAPIDCol,
table: ldapIdpTemplateTable,
}
LDAPInstanceIDCol = Column{
name: projection.LDAPInstanceIDCol,
table: ldapIdpTemplateTable,
}
LDAPHostCol = Column{
name: projection.LDAPHostCol,
table: ldapIdpTemplateTable,
}
LDAPPortCol = Column{
name: projection.LDAPPortCol,
table: ldapIdpTemplateTable,
}
LDAPTlsCol = Column{
name: projection.LDAPTlsCol,
table: ldapIdpTemplateTable,
}
LDAPBaseDNCol = Column{
name: projection.LDAPBaseDNCol,
table: ldapIdpTemplateTable,
}
LDAPUserObjectClassCol = Column{
name: projection.LDAPUserObjectClassCol,
table: ldapIdpTemplateTable,
}
LDAPUserUniqueAttributeCol = Column{
name: projection.LDAPUserUniqueAttributeCol,
table: ldapIdpTemplateTable,
}
LDAPAdminCol = Column{
name: projection.LDAPAdminCol,
table: ldapIdpTemplateTable,
}
LDAPPasswordCol = Column{
name: projection.LDAPPasswordCol,
table: ldapIdpTemplateTable,
}
LDAPIDAttributeCol = Column{
name: projection.LDAPIDAttributeCol,
table: ldapIdpTemplateTable,
}
LDAPFirstNameAttributeCol = Column{
name: projection.LDAPFirstNameAttributeCol,
table: ldapIdpTemplateTable,
}
LDAPLastNameAttributeCol = Column{
name: projection.LDAPLastNameAttributeCol,
table: ldapIdpTemplateTable,
}
LDAPDisplayNameAttributeCol = Column{
name: projection.LDAPDisplayNameAttributeCol,
table: ldapIdpTemplateTable,
}
LDAPNickNameAttributeCol = Column{
name: projection.LDAPNickNameAttributeCol,
table: ldapIdpTemplateTable,
}
LDAPPreferredUsernameAttributeCol = Column{
name: projection.LDAPPreferredUsernameAttributeCol,
table: ldapIdpTemplateTable,
}
LDAPEmailAttributeCol = Column{
name: projection.LDAPEmailAttributeCol,
table: ldapIdpTemplateTable,
}
LDAPEmailVerifiedAttributeCol = Column{
name: projection.LDAPEmailVerifiedAttributeCol,
table: ldapIdpTemplateTable,
}
LDAPPhoneAttributeCol = Column{
name: projection.LDAPPhoneAttributeCol,
table: ldapIdpTemplateTable,
}
LDAPPhoneVerifiedAttributeCol = Column{
name: projection.LDAPPhoneVerifiedAttributeCol,
table: ldapIdpTemplateTable,
}
LDAPPreferredLanguageAttributeCol = Column{
name: projection.LDAPPreferredLanguageAttributeCol,
table: ldapIdpTemplateTable,
}
LDAPAvatarURLAttributeCol = Column{
name: projection.LDAPAvatarURLAttributeCol,
table: ldapIdpTemplateTable,
}
LDAPProfileAttributeCol = Column{
name: projection.LDAPProfileAttributeCol,
table: ldapIdpTemplateTable,
}
)
// IDPTemplateByIDAndResourceOwner searches for the requested id in the context of the resource owner and IAM
func (q *Queries) IDPTemplateByIDAndResourceOwner(ctx context.Context, shouldTriggerBulk bool, id, resourceOwner string, withOwnerRemoved bool) (_ *IDPTemplate, err error) {
ctx, span := tracing.NewSpan(ctx)
defer func() { span.EndWithError(err) }()
if shouldTriggerBulk {
err := projection.IDPTemplateProjection.Trigger(ctx)
logging.OnError(err).WithField("projection", idpTemplateTable.identifier()).Warn("could not trigger projection for query")
}
eq := sq.Eq{
IDPTemplateIDCol.identifier(): id,
IDPTemplateInstanceIDCol.identifier(): authz.GetInstance(ctx).InstanceID(),
}
if !withOwnerRemoved {
eq[IDPTemplateOwnerRemovedCol.identifier()] = false
}
where := sq.And{
eq,
sq.Or{
sq.Eq{IDPTemplateResourceOwnerCol.identifier(): resourceOwner},
sq.Eq{IDPTemplateResourceOwnerCol.identifier(): authz.GetInstance(ctx).InstanceID()},
},
}
stmt, scan := prepareIDPTemplateByIDQuery()
query, args, err := stmt.Where(where).ToSql()
if err != nil {
return nil, errors.ThrowInternal(err, "QUERY-SFAew", "Errors.Query.SQLStatement")
}
row := q.client.QueryRowContext(ctx, query, args...)
return scan(row)
}
// IDPTemplates searches idp templates matching the query
func (q *Queries) IDPTemplates(ctx context.Context, queries *IDPTemplateSearchQueries, withOwnerRemoved bool) (idps *IDPTemplates, err error) {
ctx, span := tracing.NewSpan(ctx)
defer func() { span.EndWithError(err) }()
query, scan := prepareIDPTemplatesQuery()
eq := sq.Eq{
IDPTemplateInstanceIDCol.identifier(): authz.GetInstance(ctx).InstanceID(),
}
if !withOwnerRemoved {
eq[IDPTemplateOwnerRemovedCol.identifier()] = false
}
stmt, args, err := queries.toQuery(query).Where(eq).ToSql()
if err != nil {
return nil, errors.ThrowInvalidArgument(err, "QUERY-SAF34", "Errors.Query.InvalidRequest")
}
rows, err := q.client.QueryContext(ctx, stmt, args...)
if err != nil {
return nil, errors.ThrowInternal(err, "QUERY-BDFrq", "Errors.Internal")
}
idps, err = scan(rows)
if err != nil {
return nil, err
}
idps.LatestSequence, err = q.latestSequence(ctx, idpTemplateTable)
return idps, err
}
type IDPTemplateSearchQueries struct {
SearchRequest
Queries []SearchQuery
}
func NewIDPTemplateIDSearchQuery(id string) (SearchQuery, error) {
return NewTextQuery(IDPTemplateIDCol, id, TextEquals)
}
func NewIDPTemplateOwnerTypeSearchQuery(ownerType domain.IdentityProviderType) (SearchQuery, error) {
return NewNumberQuery(IDPTemplateOwnerTypeCol, ownerType, NumberEquals)
}
func NewIDPTemplateNameSearchQuery(method TextComparison, value string) (SearchQuery, error) {
return NewTextQuery(IDPTemplateNameCol, value, method)
}
func NewIDPTemplateResourceOwnerSearchQuery(value string) (SearchQuery, error) {
return NewTextQuery(IDPTemplateResourceOwnerCol, value, TextEquals)
}
func NewIDPTemplateResourceOwnerListSearchQuery(ids ...string) (SearchQuery, error) {
list := make([]interface{}, len(ids))
for i, value := range ids {
list[i] = value
}
return NewListQuery(IDPTemplateResourceOwnerCol, list, ListIn)
}
func (q *IDPTemplateSearchQueries) toQuery(query sq.SelectBuilder) sq.SelectBuilder {
query = q.SearchRequest.toQuery(query)
for _, q := range q.Queries {
query = q.toQuery(query)
}
return query
}
func prepareIDPTemplateByIDQuery() (sq.SelectBuilder, func(*sql.Row) (*IDPTemplate, error)) {
return sq.Select(
IDPTemplateIDCol.identifier(),
IDPTemplateResourceOwnerCol.identifier(),
IDPTemplateCreationDateCol.identifier(),
IDPTemplateChangeDateCol.identifier(),
IDPTemplateSequenceCol.identifier(),
IDPTemplateStateCol.identifier(),
IDPTemplateNameCol.identifier(),
IDPTemplateTypeCol.identifier(),
IDPTemplateOwnerTypeCol.identifier(),
IDPTemplateIsCreationAllowedCol.identifier(),
IDPTemplateIsLinkingAllowedCol.identifier(),
IDPTemplateIsAutoCreationCol.identifier(),
IDPTemplateIsAutoUpdateCol.identifier(),
LDAPIDCol.identifier(),
LDAPHostCol.identifier(),
LDAPPortCol.identifier(),
LDAPTlsCol.identifier(),
LDAPBaseDNCol.identifier(),
LDAPUserObjectClassCol.identifier(),
LDAPUserUniqueAttributeCol.identifier(),
LDAPAdminCol.identifier(),
LDAPPasswordCol.identifier(),
LDAPIDAttributeCol.identifier(),
LDAPFirstNameAttributeCol.identifier(),
LDAPLastNameAttributeCol.identifier(),
LDAPDisplayNameAttributeCol.identifier(),
LDAPNickNameAttributeCol.identifier(),
LDAPPreferredUsernameAttributeCol.identifier(),
LDAPEmailAttributeCol.identifier(),
LDAPEmailVerifiedAttributeCol.identifier(),
LDAPPhoneAttributeCol.identifier(),
LDAPPhoneVerifiedAttributeCol.identifier(),
LDAPPreferredLanguageAttributeCol.identifier(),
LDAPAvatarURLAttributeCol.identifier(),
LDAPProfileAttributeCol.identifier(),
).From(idpTemplateTable.identifier()).
LeftJoin(join(LDAPIDCol, IDPTemplateIDCol)).
PlaceholderFormat(sq.Dollar),
func(row *sql.Row) (*IDPTemplate, error) {
idpTemplate := new(IDPTemplate)
ldapID := sql.NullString{}
ldapHost := sql.NullString{}
ldapPort := sql.NullString{}
ldapTls := sql.NullBool{}
ldapBaseDN := sql.NullString{}
ldapUserObjectClass := sql.NullString{}
ldapUserUniqueAttribute := sql.NullString{}
ldapAdmin := sql.NullString{}
ldapPassword := new(crypto.CryptoValue)
ldapIDAttribute := sql.NullString{}
ldapFirstNameAttribute := sql.NullString{}
ldapLastNameAttribute := sql.NullString{}
ldapDisplayNameAttribute := sql.NullString{}
ldapNickNameAttribute := sql.NullString{}
ldapPreferredUsernameAttribute := sql.NullString{}
ldapEmailAttribute := sql.NullString{}
ldapEmailVerifiedAttribute := sql.NullString{}
ldapPhoneAttribute := sql.NullString{}
ldapPhoneVerifiedAttribute := sql.NullString{}
ldapPreferredLanguageAttribute := sql.NullString{}
ldapAvatarURLAttribute := sql.NullString{}
ldapProfileAttribute := sql.NullString{}
err := row.Scan(
&idpTemplate.ID,
&idpTemplate.ResourceOwner,
&idpTemplate.CreationDate,
&idpTemplate.ChangeDate,
&idpTemplate.Sequence,
&idpTemplate.State,
&idpTemplate.Name,
&idpTemplate.Type,
&idpTemplate.OwnerType,
&idpTemplate.IsCreationAllowed,
&idpTemplate.IsLinkingAllowed,
&idpTemplate.IsAutoCreation,
&idpTemplate.IsAutoUpdate,
&ldapID,
&ldapHost,
&ldapPort,
&ldapTls,
&ldapBaseDN,
&ldapUserObjectClass,
&ldapUserUniqueAttribute,
&ldapAdmin,
&ldapPassword,
&ldapIDAttribute,
&ldapFirstNameAttribute,
&ldapLastNameAttribute,
&ldapDisplayNameAttribute,
&ldapNickNameAttribute,
&ldapPreferredUsernameAttribute,
&ldapEmailAttribute,
&ldapEmailVerifiedAttribute,
&ldapPhoneAttribute,
&ldapPhoneVerifiedAttribute,
&ldapPreferredLanguageAttribute,
&ldapAvatarURLAttribute,
&ldapProfileAttribute,
)
if err != nil {
if errs.Is(err, sql.ErrNoRows) {
return nil, errors.ThrowNotFound(err, "QUERY-SAFrt", "Errors.IDPConfig.NotExisting")
}
return nil, errors.ThrowInternal(err, "QUERY-ADG42", "Errors.Internal")
}
if ldapID.Valid {
idpTemplate.LDAPIDPTemplate = &LDAPIDPTemplate{
IDPID: ldapID.String,
Host: ldapHost.String,
Port: ldapPort.String,
TLS: ldapTls.Bool,
BaseDN: ldapBaseDN.String,
UserObjectClass: ldapUserObjectClass.String,
UserUniqueAttribute: ldapUserUniqueAttribute.String,
Admin: ldapAdmin.String,
Password: ldapPassword,
LDAPAttributes: idp.LDAPAttributes{
IDAttribute: ldapIDAttribute.String,
FirstNameAttribute: ldapFirstNameAttribute.String,
LastNameAttribute: ldapLastNameAttribute.String,
DisplayNameAttribute: ldapDisplayNameAttribute.String,
NickNameAttribute: ldapNickNameAttribute.String,
PreferredUsernameAttribute: ldapPreferredUsernameAttribute.String,
EmailAttribute: ldapEmailAttribute.String,
EmailVerifiedAttribute: ldapEmailVerifiedAttribute.String,
PhoneAttribute: ldapPhoneAttribute.String,
PhoneVerifiedAttribute: ldapPhoneVerifiedAttribute.String,
PreferredLanguageAttribute: ldapPreferredLanguageAttribute.String,
AvatarURLAttribute: ldapAvatarURLAttribute.String,
ProfileAttribute: ldapProfileAttribute.String,
},
}
}
return idpTemplate, nil
}
}
func prepareIDPTemplatesQuery() (sq.SelectBuilder, func(*sql.Rows) (*IDPTemplates, error)) {
return sq.Select(
IDPTemplateIDCol.identifier(),
IDPTemplateResourceOwnerCol.identifier(),
IDPTemplateCreationDateCol.identifier(),
IDPTemplateChangeDateCol.identifier(),
IDPTemplateSequenceCol.identifier(),
IDPTemplateStateCol.identifier(),
IDPTemplateNameCol.identifier(),
IDPTemplateTypeCol.identifier(),
IDPTemplateOwnerTypeCol.identifier(),
IDPTemplateIsCreationAllowedCol.identifier(),
IDPTemplateIsLinkingAllowedCol.identifier(),
IDPTemplateIsAutoCreationCol.identifier(),
IDPTemplateIsAutoUpdateCol.identifier(),
LDAPIDCol.identifier(),
LDAPHostCol.identifier(),
LDAPPortCol.identifier(),
LDAPTlsCol.identifier(),
LDAPBaseDNCol.identifier(),
LDAPUserObjectClassCol.identifier(),
LDAPUserUniqueAttributeCol.identifier(),
LDAPAdminCol.identifier(),
LDAPPasswordCol.identifier(),
LDAPIDAttributeCol.identifier(),
LDAPFirstNameAttributeCol.identifier(),
LDAPLastNameAttributeCol.identifier(),
LDAPDisplayNameAttributeCol.identifier(),
LDAPNickNameAttributeCol.identifier(),
LDAPPreferredUsernameAttributeCol.identifier(),
LDAPEmailAttributeCol.identifier(),
LDAPEmailVerifiedAttributeCol.identifier(),
LDAPPhoneAttributeCol.identifier(),
LDAPPhoneVerifiedAttributeCol.identifier(),
LDAPPreferredLanguageAttributeCol.identifier(),
LDAPAvatarURLAttributeCol.identifier(),
LDAPProfileAttributeCol.identifier(),
countColumn.identifier(),
).From(idpTemplateTable.identifier()).
LeftJoin(join(LDAPIDCol, IDPTemplateIDCol)).
PlaceholderFormat(sq.Dollar),
func(rows *sql.Rows) (*IDPTemplates, error) {
templates := make([]*IDPTemplate, 0)
var count uint64
for rows.Next() {
idpTemplate := new(IDPTemplate)
ldapID := sql.NullString{}
ldapHost := sql.NullString{}
ldapPort := sql.NullString{}
ldapTls := sql.NullBool{}
ldapBaseDN := sql.NullString{}
ldapUserObjectClass := sql.NullString{}
ldapUserUniqueAttribute := sql.NullString{}
ldapAdmin := sql.NullString{}
ldapPassword := new(crypto.CryptoValue)
ldapIDAttribute := sql.NullString{}
ldapFirstNameAttribute := sql.NullString{}
ldapLastNameAttribute := sql.NullString{}
ldapDisplayNameAttribute := sql.NullString{}
ldapNickNameAttribute := sql.NullString{}
ldapPreferredUsernameAttribute := sql.NullString{}
ldapEmailAttribute := sql.NullString{}
ldapEmailVerifiedAttribute := sql.NullString{}
ldapPhoneAttribute := sql.NullString{}
ldapPhoneVerifiedAttribute := sql.NullString{}
ldapPreferredLanguageAttribute := sql.NullString{}
ldapAvatarURLAttribute := sql.NullString{}
ldapProfileAttribute := sql.NullString{}
err := rows.Scan(
&idpTemplate.ID,
&idpTemplate.ResourceOwner,
&idpTemplate.CreationDate,
&idpTemplate.ChangeDate,
&idpTemplate.Sequence,
&idpTemplate.State,
&idpTemplate.Name,
&idpTemplate.Type,
&idpTemplate.OwnerType,
&idpTemplate.IsCreationAllowed,
&idpTemplate.IsLinkingAllowed,
&idpTemplate.IsAutoCreation,
&idpTemplate.IsAutoUpdate,
&ldapID,
&ldapHost,
&ldapPort,
&ldapTls,
&ldapBaseDN,
&ldapUserObjectClass,
&ldapUserUniqueAttribute,
&ldapAdmin,
&ldapPassword,
&ldapIDAttribute,
&ldapFirstNameAttribute,
&ldapLastNameAttribute,
&ldapDisplayNameAttribute,
&ldapNickNameAttribute,
&ldapPreferredUsernameAttribute,
&ldapEmailAttribute,
&ldapEmailVerifiedAttribute,
&ldapPhoneAttribute,
&ldapPhoneVerifiedAttribute,
&ldapPreferredLanguageAttribute,
&ldapAvatarURLAttribute,
&ldapProfileAttribute,
&count,
)
if err != nil {
return nil, err
}
if ldapID.Valid {
idpTemplate.LDAPIDPTemplate = &LDAPIDPTemplate{
IDPID: ldapID.String,
Host: ldapHost.String,
Port: ldapPort.String,
TLS: ldapTls.Bool,
BaseDN: ldapBaseDN.String,
UserObjectClass: ldapUserObjectClass.String,
UserUniqueAttribute: ldapUserUniqueAttribute.String,
Admin: ldapAdmin.String,
Password: ldapPassword,
LDAPAttributes: idp.LDAPAttributes{
IDAttribute: ldapIDAttribute.String,
FirstNameAttribute: ldapFirstNameAttribute.String,
LastNameAttribute: ldapLastNameAttribute.String,
DisplayNameAttribute: ldapDisplayNameAttribute.String,
NickNameAttribute: ldapNickNameAttribute.String,
PreferredUsernameAttribute: ldapPreferredUsernameAttribute.String,
EmailAttribute: ldapEmailAttribute.String,
EmailVerifiedAttribute: ldapEmailVerifiedAttribute.String,
PhoneAttribute: ldapPhoneAttribute.String,
PhoneVerifiedAttribute: ldapPhoneVerifiedAttribute.String,
PreferredLanguageAttribute: ldapPreferredLanguageAttribute.String,
AvatarURLAttribute: ldapAvatarURLAttribute.String,
ProfileAttribute: ldapProfileAttribute.String,
},
}
}
templates = append(templates, idpTemplate)
}
if err := rows.Close(); err != nil {
return nil, errors.ThrowInternal(err, "QUERY-SAGrt", "Errors.Query.CloseRows")
}
return &IDPTemplates{
Templates: templates,
SearchResponse: SearchResponse{
Count: count,
},
}, nil
}
}

View File

@@ -0,0 +1,727 @@
package query
import (
"database/sql"
"database/sql/driver"
"errors"
"fmt"
"regexp"
"testing"
"github.com/zitadel/zitadel/internal/domain"
errs "github.com/zitadel/zitadel/internal/errors"
"github.com/zitadel/zitadel/internal/repository/idp"
)
var (
idpTemplateQuery = `SELECT projections.idp_templates.id,` +
` projections.idp_templates.resource_owner,` +
` projections.idp_templates.creation_date,` +
` projections.idp_templates.change_date,` +
` projections.idp_templates.sequence,` +
` projections.idp_templates.state,` +
` projections.idp_templates.name,` +
` projections.idp_templates.type,` +
` projections.idp_templates.owner_type,` +
` projections.idp_templates.is_creation_allowed,` +
` projections.idp_templates.is_linking_allowed,` +
` projections.idp_templates.is_auto_creation,` +
` projections.idp_templates.is_auto_update,` +
` projections.idp_templates_ldap.idp_id,` +
` projections.idp_templates_ldap.host,` +
` projections.idp_templates_ldap.port,` +
` projections.idp_templates_ldap.tls,` +
` projections.idp_templates_ldap.base_dn,` +
` projections.idp_templates_ldap.user_object_class,` +
` projections.idp_templates_ldap.user_unique_attribute,` +
` projections.idp_templates_ldap.admin,` +
` projections.idp_templates_ldap.password,` +
` projections.idp_templates_ldap.id_attribute,` +
` projections.idp_templates_ldap.first_name_attribute,` +
` projections.idp_templates_ldap.last_name_attribute,` +
` projections.idp_templates_ldap.display_name_attribute,` +
` projections.idp_templates_ldap.nick_name_attribute,` +
` projections.idp_templates_ldap.preferred_username_attribute,` +
` projections.idp_templates_ldap.email_attribute,` +
` projections.idp_templates_ldap.email_verified,` +
` projections.idp_templates_ldap.phone_attribute,` +
` projections.idp_templates_ldap.phone_verified_attribute,` +
` projections.idp_templates_ldap.preferred_language_attribute,` +
` projections.idp_templates_ldap.avatar_url_attribute,` +
` projections.idp_templates_ldap.profile_attribute` +
` FROM projections.idp_templates` +
` LEFT JOIN projections.idp_templates_ldap ON projections.idp_templates.id = projections.idp_templates_ldap.idp_id AND projections.idp_templates.instance_id = projections.idp_templates_ldap.instance_id`
idpTemplateCols = []string{
"id",
"resource_owner",
"creation_date",
"change_date",
"sequence",
"state",
"name",
"type",
"owner_type",
"is_creation_allowed",
"is_linking_allowed",
"is_auto_creation",
"is_auto_update",
// ldap config
"idp_id",
"host",
"port",
"tls",
"base_dn",
"user_object_class",
"user_unique_attribute",
"admin",
"password",
"id_attribute",
"first_name_attribute",
"last_name_attribute",
"display_name_attribute",
"nick_name_attribute",
"preferred_username_attribute",
"email_attribute",
"email_verified",
"phone_attribute",
"phone_verified_attribute",
"preferred_language_attribute",
"avatar_url_attribute",
"profile_attribute",
}
idpTemplatesQuery = `SELECT projections.idp_templates.id,` +
` projections.idp_templates.resource_owner,` +
` projections.idp_templates.creation_date,` +
` projections.idp_templates.change_date,` +
` projections.idp_templates.sequence,` +
` projections.idp_templates.state,` +
` projections.idp_templates.name,` +
` projections.idp_templates.type,` +
` projections.idp_templates.owner_type,` +
` projections.idp_templates.is_creation_allowed,` +
` projections.idp_templates.is_linking_allowed,` +
` projections.idp_templates.is_auto_creation,` +
` projections.idp_templates.is_auto_update,` +
` projections.idp_templates_ldap.idp_id,` +
` projections.idp_templates_ldap.host,` +
` projections.idp_templates_ldap.port,` +
` projections.idp_templates_ldap.tls,` +
` projections.idp_templates_ldap.base_dn,` +
` projections.idp_templates_ldap.user_object_class,` +
` projections.idp_templates_ldap.user_unique_attribute,` +
` projections.idp_templates_ldap.admin,` +
` projections.idp_templates_ldap.password,` +
` projections.idp_templates_ldap.id_attribute,` +
` projections.idp_templates_ldap.first_name_attribute,` +
` projections.idp_templates_ldap.last_name_attribute,` +
` projections.idp_templates_ldap.display_name_attribute,` +
` projections.idp_templates_ldap.nick_name_attribute,` +
` projections.idp_templates_ldap.preferred_username_attribute,` +
` projections.idp_templates_ldap.email_attribute,` +
` projections.idp_templates_ldap.email_verified,` +
` projections.idp_templates_ldap.phone_attribute,` +
` projections.idp_templates_ldap.phone_verified_attribute,` +
` projections.idp_templates_ldap.preferred_language_attribute,` +
` projections.idp_templates_ldap.avatar_url_attribute,` +
` projections.idp_templates_ldap.profile_attribute,` +
` COUNT(*) OVER ()` +
` FROM projections.idp_templates` +
` LEFT JOIN projections.idp_templates_ldap ON projections.idp_templates.id = projections.idp_templates_ldap.idp_id AND projections.idp_templates.instance_id = projections.idp_templates_ldap.instance_id`
idpTemplatesCols = []string{
"id",
"resource_owner",
"creation_date",
"change_date",
"sequence",
"state",
"name",
"type",
"owner_type",
"is_creation_allowed",
"is_linking_allowed",
"is_auto_creation",
"is_auto_update",
"idp_id",
"host",
"port",
"tls",
"base_dn",
"user_object_class",
"user_unique_attribute",
"admin",
"password",
"id_attribute",
"first_name_attribute",
"last_name_attribute",
"display_name_attribute",
"nick_name_attribute",
"preferred_username_attribute",
"email_attribute",
"email_verified",
"phone_attribute",
"phone_verified_attribute",
"preferred_language_attribute",
"avatar_url_attribute",
"profile_attribute",
"count",
}
)
func Test_IDPTemplateTemplatesPrepares(t *testing.T) {
type want struct {
sqlExpectations sqlExpectation
err checkErr
}
tests := []struct {
name string
prepare interface{}
want want
object interface{}
}{
{
name: "prepareIDPTemplateByIDQuery no result",
prepare: prepareIDPTemplateByIDQuery,
want: want{
sqlExpectations: mockQuery(
regexp.QuoteMeta(idpTemplateQuery),
nil,
nil,
),
err: func(err error) (error, bool) {
if !errs.IsNotFound(err) {
return fmt.Errorf("err should be zitadel.NotFoundError got: %w", err), false
}
return nil, true
},
},
object: (*IDPTemplate)(nil),
},
{
name: "prepareIDPTemplateByIDQuery ldap idp",
prepare: prepareIDPTemplateByIDQuery,
want: want{
sqlExpectations: mockQuery(
regexp.QuoteMeta(idpTemplateQuery),
idpTemplateCols,
[]driver.Value{
"idp-id",
"ro",
testNow,
testNow,
uint64(20211109),
domain.IDPConfigStateActive,
"idp-name",
domain.IDPTypeLDAP,
domain.IdentityProviderTypeOrg,
true,
true,
true,
true,
// ldap config
"idp-id",
"host",
"port",
true,
"base",
"user",
"uid",
"admin",
nil,
"id",
"first",
"last",
"display",
"nickname",
"username",
"email",
"emailVerified",
"phone",
"phoneVerified",
"lang",
"avatar",
"profile",
},
),
},
object: &IDPTemplate{
CreationDate: testNow,
ChangeDate: testNow,
Sequence: 20211109,
ResourceOwner: "ro",
ID: "idp-id",
State: domain.IDPStateActive,
Name: "idp-name",
Type: domain.IDPTypeLDAP,
OwnerType: domain.IdentityProviderTypeOrg,
IsCreationAllowed: true,
IsLinkingAllowed: true,
IsAutoCreation: true,
IsAutoUpdate: true,
LDAPIDPTemplate: &LDAPIDPTemplate{
IDPID: "idp-id",
Host: "host",
Port: "port",
TLS: true,
BaseDN: "base",
UserObjectClass: "user",
UserUniqueAttribute: "uid",
Admin: "admin",
LDAPAttributes: idp.LDAPAttributes{
IDAttribute: "id",
FirstNameAttribute: "first",
LastNameAttribute: "last",
DisplayNameAttribute: "display",
NickNameAttribute: "nickname",
PreferredUsernameAttribute: "username",
EmailAttribute: "email",
EmailVerifiedAttribute: "emailVerified",
PhoneAttribute: "phone",
PhoneVerifiedAttribute: "phoneVerified",
PreferredLanguageAttribute: "lang",
AvatarURLAttribute: "avatar",
ProfileAttribute: "profile",
},
},
},
},
{
name: "prepareIDPTemplateByIDQuery no config",
prepare: prepareIDPTemplateByIDQuery,
want: want{
sqlExpectations: mockQuery(
regexp.QuoteMeta(idpTemplateQuery),
idpTemplateCols,
[]driver.Value{
"idp-id",
"ro",
testNow,
testNow,
uint64(20211109),
domain.IDPConfigStateActive,
"idp-name",
domain.IDPTypeLDAP,
domain.IdentityProviderTypeOrg,
true,
true,
true,
true,
// ldap config
nil,
nil,
nil,
nil,
nil,
nil,
nil,
nil,
nil,
nil,
nil,
nil,
nil,
nil,
nil,
nil,
nil,
nil,
nil,
nil,
nil,
nil,
},
),
},
object: &IDPTemplate{
CreationDate: testNow,
ChangeDate: testNow,
Sequence: 20211109,
ResourceOwner: "ro",
ID: "idp-id",
State: domain.IDPStateActive,
Name: "idp-name",
Type: domain.IDPTypeLDAP,
OwnerType: domain.IdentityProviderTypeOrg,
IsCreationAllowed: true,
IsLinkingAllowed: true,
IsAutoCreation: true,
IsAutoUpdate: true,
},
},
{
name: "prepareIDPTemplateByIDQuery sql err",
prepare: prepareIDPTemplateByIDQuery,
want: want{
sqlExpectations: mockQueryErr(
regexp.QuoteMeta(idpTemplateQuery),
sql.ErrConnDone,
),
err: func(err error) (error, bool) {
if !errors.Is(err, sql.ErrConnDone) {
return fmt.Errorf("err should be sql.ErrConnDone got: %w", err), false
}
return nil, true
},
},
object: nil,
},
{
name: "prepareIDPTemplatesQuery no result",
prepare: prepareIDPTemplatesQuery,
want: want{
sqlExpectations: mockQueries(
regexp.QuoteMeta(idpTemplatesQuery),
nil,
nil,
),
err: func(err error) (error, bool) {
if !errs.IsNotFound(err) {
return fmt.Errorf("err should be zitadel.NotFoundError got: %w", err), false
}
return nil, true
},
},
object: &IDPTemplates{Templates: []*IDPTemplate{}},
},
{
name: "prepareIDPTemplatesQuery ldap idp",
prepare: prepareIDPTemplatesQuery,
want: want{
sqlExpectations: mockQueries(
regexp.QuoteMeta(idpTemplatesQuery),
idpTemplatesCols,
[][]driver.Value{
{
"idp-id",
"ro",
testNow,
testNow,
uint64(20211109),
domain.IDPConfigStateActive,
"idp-name",
domain.IDPTypeLDAP,
domain.IdentityProviderTypeOrg,
true,
true,
true,
true,
// ldap config
"idp-id",
"host",
"port",
true,
"base",
"user",
"uid",
"admin",
nil,
"id",
"first",
"last",
"display",
"nickname",
"username",
"email",
"emailVerified",
"phone",
"phoneVerified",
"lang",
"avatar",
"profile",
},
},
),
},
object: &IDPTemplates{
SearchResponse: SearchResponse{
Count: 1,
},
Templates: []*IDPTemplate{
{
CreationDate: testNow,
ChangeDate: testNow,
Sequence: 20211109,
ResourceOwner: "ro",
ID: "idp-id",
State: domain.IDPStateActive,
Name: "idp-name",
Type: domain.IDPTypeLDAP,
OwnerType: domain.IdentityProviderTypeOrg,
IsCreationAllowed: true,
IsLinkingAllowed: true,
IsAutoCreation: true,
IsAutoUpdate: true,
LDAPIDPTemplate: &LDAPIDPTemplate{
IDPID: "idp-id",
Host: "host",
Port: "port",
TLS: true,
BaseDN: "base",
UserObjectClass: "user",
UserUniqueAttribute: "uid",
Admin: "admin",
LDAPAttributes: idp.LDAPAttributes{
IDAttribute: "id",
FirstNameAttribute: "first",
LastNameAttribute: "last",
DisplayNameAttribute: "display",
NickNameAttribute: "nickname",
PreferredUsernameAttribute: "username",
EmailAttribute: "email",
EmailVerifiedAttribute: "emailVerified",
PhoneAttribute: "phone",
PhoneVerifiedAttribute: "phoneVerified",
PreferredLanguageAttribute: "lang",
AvatarURLAttribute: "avatar",
ProfileAttribute: "profile",
},
},
},
},
},
},
{
name: "prepareIDPTemplatesQuery no config",
prepare: prepareIDPTemplatesQuery,
want: want{
sqlExpectations: mockQueries(
regexp.QuoteMeta(idpTemplatesQuery),
idpTemplatesCols,
[][]driver.Value{
{
"idp-id",
"ro",
testNow,
testNow,
uint64(20211109),
domain.IDPConfigStateActive,
"idp-name",
domain.IDPTypeLDAP,
domain.IdentityProviderTypeOrg,
true,
true,
true,
true,
// ldap config
nil,
nil,
nil,
nil,
nil,
nil,
nil,
nil,
nil,
nil,
nil,
nil,
nil,
nil,
nil,
nil,
nil,
nil,
nil,
nil,
nil,
nil,
},
},
),
},
object: &IDPTemplates{
SearchResponse: SearchResponse{
Count: 1,
},
Templates: []*IDPTemplate{
{
CreationDate: testNow,
ChangeDate: testNow,
Sequence: 20211109,
ResourceOwner: "ro",
ID: "idp-id",
State: domain.IDPStateActive,
Name: "idp-name",
Type: domain.IDPTypeLDAP,
OwnerType: domain.IdentityProviderTypeOrg,
IsCreationAllowed: true,
IsLinkingAllowed: true,
IsAutoCreation: true,
IsAutoUpdate: true,
},
},
},
},
{
name: "prepareIDPTemplatesQuery all config types",
prepare: prepareIDPTemplatesQuery,
want: want{
sqlExpectations: mockQueries(
regexp.QuoteMeta(idpTemplatesQuery),
idpTemplatesCols,
[][]driver.Value{
{
"idp-id-1",
"ro",
testNow,
testNow,
uint64(20211109),
domain.IDPConfigStateActive,
"idp-name",
domain.IDPTypeLDAP,
domain.IdentityProviderTypeOrg,
true,
true,
true,
true,
// ldap config
"idp-id",
"host",
"port",
true,
"base",
"user",
"uid",
"admin",
nil,
"id",
"first",
"last",
"display",
"nickname",
"username",
"email",
"emailVerified",
"phone",
"phoneVerified",
"lang",
"avatar",
"profile",
},
{
"idp-id-2",
"ro",
testNow,
testNow,
uint64(20211109),
domain.IDPConfigStateActive,
"idp-name",
domain.IDPTypeLDAP,
domain.IdentityProviderTypeOrg,
true,
true,
true,
true,
// ldap config
nil,
nil,
nil,
nil,
nil,
nil,
nil,
nil,
nil,
nil,
nil,
nil,
nil,
nil,
nil,
nil,
nil,
nil,
nil,
nil,
nil,
nil,
},
},
),
},
object: &IDPTemplates{
SearchResponse: SearchResponse{
Count: 2,
},
Templates: []*IDPTemplate{
{
CreationDate: testNow,
ChangeDate: testNow,
Sequence: 20211109,
ResourceOwner: "ro",
ID: "idp-id-1",
State: domain.IDPStateActive,
Name: "idp-name",
Type: domain.IDPTypeLDAP,
OwnerType: domain.IdentityProviderTypeOrg,
IsCreationAllowed: true,
IsLinkingAllowed: true,
IsAutoCreation: true,
IsAutoUpdate: true,
LDAPIDPTemplate: &LDAPIDPTemplate{
IDPID: "idp-id",
Host: "host",
Port: "port",
TLS: true,
BaseDN: "base",
UserObjectClass: "user",
UserUniqueAttribute: "uid",
Admin: "admin",
LDAPAttributes: idp.LDAPAttributes{
IDAttribute: "id",
FirstNameAttribute: "first",
LastNameAttribute: "last",
DisplayNameAttribute: "display",
NickNameAttribute: "nickname",
PreferredUsernameAttribute: "username",
EmailAttribute: "email",
EmailVerifiedAttribute: "emailVerified",
PhoneAttribute: "phone",
PhoneVerifiedAttribute: "phoneVerified",
PreferredLanguageAttribute: "lang",
AvatarURLAttribute: "avatar",
ProfileAttribute: "profile",
},
},
},
{
CreationDate: testNow,
ChangeDate: testNow,
Sequence: 20211109,
ResourceOwner: "ro",
ID: "idp-id-2",
State: domain.IDPStateActive,
Name: "idp-name",
Type: domain.IDPTypeLDAP,
OwnerType: domain.IdentityProviderTypeOrg,
IsCreationAllowed: true,
IsLinkingAllowed: true,
IsAutoCreation: true,
IsAutoUpdate: true,
},
},
},
},
{
name: "prepareIDPTemplatesQuery sql err",
prepare: prepareIDPTemplatesQuery,
want: want{
sqlExpectations: mockQueryErr(
regexp.QuoteMeta(idpTemplatesQuery),
sql.ErrConnDone,
),
err: func(err error) (error, bool) {
if !errors.Is(err, sql.ErrConnDone) {
return fmt.Errorf("err should be sql.ErrConnDone got: %w", err), false
}
return nil, true
},
},
object: nil,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
assertPrepare(t, tt.prepare, tt.object, tt.want.sqlExpectations, tt.want.err)
})
}
}

View File

@@ -0,0 +1,412 @@
package projection
import (
"context"
"github.com/zitadel/zitadel/internal/domain"
"github.com/zitadel/zitadel/internal/errors"
"github.com/zitadel/zitadel/internal/eventstore"
"github.com/zitadel/zitadel/internal/eventstore/handler"
"github.com/zitadel/zitadel/internal/eventstore/handler/crdb"
"github.com/zitadel/zitadel/internal/repository/idp"
"github.com/zitadel/zitadel/internal/repository/instance"
"github.com/zitadel/zitadel/internal/repository/org"
)
const (
IDPTemplateTable = "projections.idp_templates"
IDPTemplateLDAPTable = IDPTemplateTable + "_" + IDPTemplateLDAPSuffix
IDPTemplateLDAPSuffix = "ldap"
IDPTemplateIDCol = "id"
IDPTemplateCreationDateCol = "creation_date"
IDPTemplateChangeDateCol = "change_date"
IDPTemplateSequenceCol = "sequence"
IDPTemplateResourceOwnerCol = "resource_owner"
IDPTemplateInstanceIDCol = "instance_id"
IDPTemplateStateCol = "state"
IDPTemplateNameCol = "name"
IDPTemplateOwnerTypeCol = "owner_type"
IDPTemplateTypeCol = "type"
IDPTemplateOwnerRemovedCol = "owner_removed"
IDPTemplateIsCreationAllowedCol = "is_creation_allowed"
IDPTemplateIsLinkingAllowedCol = "is_linking_allowed"
IDPTemplateIsAutoCreationCol = "is_auto_creation"
IDPTemplateIsAutoUpdateCol = "is_auto_update"
LDAPIDCol = "idp_id"
LDAPInstanceIDCol = "instance_id"
LDAPHostCol = "host"
LDAPPortCol = "port"
LDAPTlsCol = "tls"
LDAPBaseDNCol = "base_dn"
LDAPUserObjectClassCol = "user_object_class"
LDAPUserUniqueAttributeCol = "user_unique_attribute"
LDAPAdminCol = "admin"
LDAPPasswordCol = "password"
LDAPIDAttributeCol = "id_attribute"
LDAPFirstNameAttributeCol = "first_name_attribute"
LDAPLastNameAttributeCol = "last_name_attribute"
LDAPDisplayNameAttributeCol = "display_name_attribute"
LDAPNickNameAttributeCol = "nick_name_attribute"
LDAPPreferredUsernameAttributeCol = "preferred_username_attribute"
LDAPEmailAttributeCol = "email_attribute"
LDAPEmailVerifiedAttributeCol = "email_verified"
LDAPPhoneAttributeCol = "phone_attribute"
LDAPPhoneVerifiedAttributeCol = "phone_verified_attribute"
LDAPPreferredLanguageAttributeCol = "preferred_language_attribute"
LDAPAvatarURLAttributeCol = "avatar_url_attribute"
LDAPProfileAttributeCol = "profile_attribute"
)
type idpTemplateProjection struct {
crdb.StatementHandler
}
func newIDPTemplateProjection(ctx context.Context, config crdb.StatementHandlerConfig) *idpTemplateProjection {
p := new(idpTemplateProjection)
config.ProjectionName = IDPTemplateTable
config.Reducers = p.reducers()
config.InitCheck = crdb.NewMultiTableCheck(
crdb.NewTable([]*crdb.Column{
crdb.NewColumn(IDPTemplateIDCol, crdb.ColumnTypeText),
crdb.NewColumn(IDPTemplateCreationDateCol, crdb.ColumnTypeTimestamp),
crdb.NewColumn(IDPTemplateChangeDateCol, crdb.ColumnTypeTimestamp),
crdb.NewColumn(IDPTemplateSequenceCol, crdb.ColumnTypeInt64),
crdb.NewColumn(IDPTemplateResourceOwnerCol, crdb.ColumnTypeText),
crdb.NewColumn(IDPTemplateInstanceIDCol, crdb.ColumnTypeText),
crdb.NewColumn(IDPTemplateStateCol, crdb.ColumnTypeEnum),
crdb.NewColumn(IDPTemplateNameCol, crdb.ColumnTypeText, crdb.Nullable()),
crdb.NewColumn(IDPTemplateOwnerTypeCol, crdb.ColumnTypeEnum),
crdb.NewColumn(IDPTemplateTypeCol, crdb.ColumnTypeEnum),
crdb.NewColumn(IDPTemplateOwnerRemovedCol, crdb.ColumnTypeBool, crdb.Default(false)),
crdb.NewColumn(IDPTemplateIsCreationAllowedCol, crdb.ColumnTypeBool, crdb.Default(false)),
crdb.NewColumn(IDPTemplateIsLinkingAllowedCol, crdb.ColumnTypeBool, crdb.Default(false)),
crdb.NewColumn(IDPTemplateIsAutoCreationCol, crdb.ColumnTypeBool, crdb.Default(false)),
crdb.NewColumn(IDPTemplateIsAutoUpdateCol, crdb.ColumnTypeBool, crdb.Default(false)),
},
crdb.NewPrimaryKey(IDPTemplateInstanceIDCol, IDPTemplateIDCol),
crdb.WithIndex(crdb.NewIndex("resource_owner", []string{IDPTemplateResourceOwnerCol})),
crdb.WithIndex(crdb.NewIndex("owner_removed", []string{IDPTemplateOwnerRemovedCol})),
),
crdb.NewSuffixedTable([]*crdb.Column{
crdb.NewColumn(LDAPIDCol, crdb.ColumnTypeText),
crdb.NewColumn(LDAPInstanceIDCol, crdb.ColumnTypeText),
crdb.NewColumn(LDAPHostCol, crdb.ColumnTypeText, crdb.Nullable()),
crdb.NewColumn(LDAPPortCol, crdb.ColumnTypeText, crdb.Nullable()),
crdb.NewColumn(LDAPTlsCol, crdb.ColumnTypeBool, crdb.Nullable()),
crdb.NewColumn(LDAPBaseDNCol, crdb.ColumnTypeText, crdb.Nullable()),
crdb.NewColumn(LDAPUserObjectClassCol, crdb.ColumnTypeText, crdb.Nullable()),
crdb.NewColumn(LDAPUserUniqueAttributeCol, crdb.ColumnTypeText, crdb.Nullable()),
crdb.NewColumn(LDAPAdminCol, crdb.ColumnTypeText, crdb.Nullable()),
crdb.NewColumn(LDAPPasswordCol, crdb.ColumnTypeJSONB, crdb.Nullable()),
crdb.NewColumn(LDAPIDAttributeCol, crdb.ColumnTypeText, crdb.Nullable()),
crdb.NewColumn(LDAPFirstNameAttributeCol, crdb.ColumnTypeText, crdb.Nullable()),
crdb.NewColumn(LDAPLastNameAttributeCol, crdb.ColumnTypeText, crdb.Nullable()),
crdb.NewColumn(LDAPDisplayNameAttributeCol, crdb.ColumnTypeText, crdb.Nullable()),
crdb.NewColumn(LDAPNickNameAttributeCol, crdb.ColumnTypeText, crdb.Nullable()),
crdb.NewColumn(LDAPPreferredUsernameAttributeCol, crdb.ColumnTypeText, crdb.Nullable()),
crdb.NewColumn(LDAPEmailAttributeCol, crdb.ColumnTypeText, crdb.Nullable()),
crdb.NewColumn(LDAPEmailVerifiedAttributeCol, crdb.ColumnTypeText, crdb.Nullable()),
crdb.NewColumn(LDAPPhoneAttributeCol, crdb.ColumnTypeText, crdb.Nullable()),
crdb.NewColumn(LDAPPhoneVerifiedAttributeCol, crdb.ColumnTypeText, crdb.Nullable()),
crdb.NewColumn(LDAPPreferredLanguageAttributeCol, crdb.ColumnTypeText, crdb.Nullable()),
crdb.NewColumn(LDAPAvatarURLAttributeCol, crdb.ColumnTypeText, crdb.Nullable()),
crdb.NewColumn(LDAPProfileAttributeCol, crdb.ColumnTypeText, crdb.Nullable()),
},
crdb.NewPrimaryKey(LDAPInstanceIDCol, LDAPIDCol),
IDPTemplateLDAPSuffix,
crdb.WithForeignKey(crdb.NewForeignKeyOfPublicKeys()),
),
)
p.StatementHandler = crdb.NewStatementHandler(ctx, config)
return p
}
func (p *idpTemplateProjection) reducers() []handler.AggregateReducer {
return []handler.AggregateReducer{
{
Aggregate: instance.AggregateType,
EventRedusers: []handler.EventReducer{
{
Event: instance.LDAPIDPAddedEventType,
Reduce: p.reduceLDAPIDPAdded,
},
{
Event: instance.LDAPIDPChangedEventType,
Reduce: p.reduceLDAPIDPChanged,
},
{
Event: instance.IDPRemovedEventType,
Reduce: p.reduceIDPRemoved,
},
{
Event: instance.InstanceRemovedEventType,
Reduce: reduceInstanceRemovedHelper(IDPTemplateInstanceIDCol),
},
},
},
{
Aggregate: org.AggregateType,
EventRedusers: []handler.EventReducer{
{
Event: org.LDAPIDPAddedEventType,
Reduce: p.reduceLDAPIDPAdded,
},
{
Event: org.LDAPIDPChangedEventType,
Reduce: p.reduceLDAPIDPChanged,
},
{
Event: org.IDPRemovedEventType,
Reduce: p.reduceIDPRemoved,
},
{
Event: org.OrgRemovedEventType,
Reduce: p.reduceOwnerRemoved,
},
},
},
}
}
func (p *idpTemplateProjection) reduceLDAPIDPAdded(event eventstore.Event) (*handler.Statement, error) {
var idpEvent idp.LDAPIDPAddedEvent
var idpOwnerType domain.IdentityProviderType
switch e := event.(type) {
case *org.LDAPIDPAddedEvent:
idpEvent = e.LDAPIDPAddedEvent
idpOwnerType = domain.IdentityProviderTypeOrg
case *instance.LDAPIDPAddedEvent:
idpEvent = e.LDAPIDPAddedEvent
idpOwnerType = domain.IdentityProviderTypeSystem
default:
return nil, errors.ThrowInvalidArgumentf(nil, "HANDL-9s02m1", "reduce.wrong.event.type %v", []eventstore.EventType{org.LDAPIDPAddedEventType, instance.LDAPIDPAddedEventType})
}
return crdb.NewMultiStatement(
&idpEvent,
crdb.AddCreateStatement(
[]handler.Column{
handler.NewCol(IDPTemplateIDCol, idpEvent.ID),
handler.NewCol(IDPTemplateCreationDateCol, idpEvent.CreationDate()),
handler.NewCol(IDPTemplateChangeDateCol, idpEvent.CreationDate()),
handler.NewCol(IDPTemplateSequenceCol, idpEvent.Sequence()),
handler.NewCol(IDPTemplateResourceOwnerCol, idpEvent.Aggregate().ResourceOwner),
handler.NewCol(IDPTemplateInstanceIDCol, idpEvent.Aggregate().InstanceID),
handler.NewCol(IDPTemplateStateCol, domain.IDPStateActive),
handler.NewCol(IDPTemplateNameCol, idpEvent.Name),
handler.NewCol(IDPTemplateOwnerTypeCol, idpOwnerType),
handler.NewCol(IDPTemplateTypeCol, domain.IDPTypeLDAP),
handler.NewCol(IDPTemplateIsCreationAllowedCol, idpEvent.IsCreationAllowed),
handler.NewCol(IDPTemplateIsLinkingAllowedCol, idpEvent.IsLinkingAllowed),
handler.NewCol(IDPTemplateIsAutoCreationCol, idpEvent.IsAutoCreation),
handler.NewCol(IDPTemplateIsAutoUpdateCol, idpEvent.IsAutoUpdate),
},
),
crdb.AddCreateStatement(
[]handler.Column{
handler.NewCol(LDAPIDCol, idpEvent.ID),
handler.NewCol(LDAPInstanceIDCol, idpEvent.Aggregate().InstanceID),
handler.NewCol(LDAPHostCol, idpEvent.Host),
handler.NewCol(LDAPPortCol, idpEvent.Port),
handler.NewCol(LDAPTlsCol, idpEvent.TLS),
handler.NewCol(LDAPBaseDNCol, idpEvent.BaseDN),
handler.NewCol(LDAPUserObjectClassCol, idpEvent.UserObjectClass),
handler.NewCol(LDAPUserUniqueAttributeCol, idpEvent.UserUniqueAttribute),
handler.NewCol(LDAPAdminCol, idpEvent.Admin),
handler.NewCol(LDAPPasswordCol, idpEvent.Password),
handler.NewCol(LDAPIDAttributeCol, idpEvent.IDAttribute),
handler.NewCol(LDAPFirstNameAttributeCol, idpEvent.FirstNameAttribute),
handler.NewCol(LDAPLastNameAttributeCol, idpEvent.LastNameAttribute),
handler.NewCol(LDAPDisplayNameAttributeCol, idpEvent.DisplayNameAttribute),
handler.NewCol(LDAPNickNameAttributeCol, idpEvent.NickNameAttribute),
handler.NewCol(LDAPPreferredUsernameAttributeCol, idpEvent.PreferredUsernameAttribute),
handler.NewCol(LDAPEmailAttributeCol, idpEvent.EmailAttribute),
handler.NewCol(LDAPEmailVerifiedAttributeCol, idpEvent.EmailVerifiedAttribute),
handler.NewCol(LDAPPhoneAttributeCol, idpEvent.PhoneAttribute),
handler.NewCol(LDAPPhoneVerifiedAttributeCol, idpEvent.PhoneVerifiedAttribute),
handler.NewCol(LDAPPreferredLanguageAttributeCol, idpEvent.PreferredLanguageAttribute),
handler.NewCol(LDAPAvatarURLAttributeCol, idpEvent.AvatarURLAttribute),
handler.NewCol(LDAPProfileAttributeCol, idpEvent.ProfileAttribute),
},
crdb.WithTableSuffix(IDPTemplateLDAPSuffix),
),
), nil
}
func (p *idpTemplateProjection) reduceLDAPIDPChanged(event eventstore.Event) (*handler.Statement, error) {
var idpEvent idp.LDAPIDPChangedEvent
switch e := event.(type) {
case *org.LDAPIDPChangedEvent:
idpEvent = e.LDAPIDPChangedEvent
case *instance.LDAPIDPChangedEvent:
idpEvent = e.LDAPIDPChangedEvent
default:
return nil, errors.ThrowInvalidArgumentf(nil, "HANDL-p1582ks", "reduce.wrong.event.type %v", []eventstore.EventType{org.LDAPIDPChangedEventType, instance.LDAPIDPChangedEventType})
}
cols := reduceLDAPIDPChangedTemplateColumns(idpEvent)
ldapCols := reduceLDAPIDPChangedLDAPColumns(idpEvent)
ops := make([]func(eventstore.Event) crdb.Exec, 0, 2)
ops = append(ops,
crdb.AddUpdateStatement(
cols,
[]handler.Condition{
handler.NewCond(IDPTemplateIDCol, idpEvent.ID),
handler.NewCond(IDPTemplateInstanceIDCol, idpEvent.Aggregate().InstanceID),
},
),
)
if len(ldapCols) > 0 {
ops = append(ops,
crdb.AddUpdateStatement(
ldapCols,
[]handler.Condition{
handler.NewCond(LDAPIDCol, idpEvent.ID),
handler.NewCond(LDAPInstanceIDCol, idpEvent.Aggregate().InstanceID),
},
crdb.WithTableSuffix(IDPTemplateLDAPSuffix),
),
)
}
return crdb.NewMultiStatement(
&idpEvent,
ops...,
), nil
}
func (p *idpTemplateProjection) reduceIDPRemoved(event eventstore.Event) (*handler.Statement, error) {
var idpEvent idp.RemovedEvent
switch e := event.(type) {
case *org.IDPRemovedEvent:
idpEvent = e.RemovedEvent
case *instance.IDPRemovedEvent:
idpEvent = e.RemovedEvent
default:
return nil, errors.ThrowInvalidArgumentf(nil, "HANDL-xbcvwin2", "reduce.wrong.event.type %v", []eventstore.EventType{org.IDPRemovedEventType, instance.IDPRemovedEventType})
}
return crdb.NewDeleteStatement(
&idpEvent,
[]handler.Condition{
handler.NewCond(IDPTemplateIDCol, idpEvent.ID),
handler.NewCond(IDPTemplateInstanceIDCol, idpEvent.Aggregate().InstanceID),
},
), nil
}
func (p *idpTemplateProjection) reduceOwnerRemoved(event eventstore.Event) (*handler.Statement, error) {
e, ok := event.(*org.OrgRemovedEvent)
if !ok {
return nil, errors.ThrowInvalidArgumentf(nil, "PROJE-Jp0D2K", "reduce.wrong.event.type %s", org.OrgRemovedEventType)
}
return crdb.NewUpdateStatement(
e,
[]handler.Column{
handler.NewCol(IDPTemplateChangeDateCol, e.CreationDate()),
handler.NewCol(IDPTemplateSequenceCol, e.Sequence()),
handler.NewCol(IDPTemplateOwnerRemovedCol, true),
},
[]handler.Condition{
handler.NewCond(IDPTemplateInstanceIDCol, e.Aggregate().InstanceID),
handler.NewCond(IDPTemplateResourceOwnerCol, e.Aggregate().ID),
},
), nil
}
func reduceLDAPIDPChangedTemplateColumns(idpEvent idp.LDAPIDPChangedEvent) []handler.Column {
cols := make([]handler.Column, 0, 7)
if idpEvent.Name != nil {
cols = append(cols, handler.NewCol(IDPTemplateNameCol, *idpEvent.Name))
}
if idpEvent.IsCreationAllowed != nil {
cols = append(cols, handler.NewCol(IDPTemplateIsCreationAllowedCol, *idpEvent.IsCreationAllowed))
}
if idpEvent.IsLinkingAllowed != nil {
cols = append(cols, handler.NewCol(IDPTemplateIsLinkingAllowedCol, *idpEvent.IsLinkingAllowed))
}
if idpEvent.IsAutoCreation != nil {
cols = append(cols, handler.NewCol(IDPTemplateIsAutoCreationCol, *idpEvent.IsAutoCreation))
}
if idpEvent.IsAutoUpdate != nil {
cols = append(cols, handler.NewCol(IDPTemplateIsAutoUpdateCol, *idpEvent.IsAutoUpdate))
}
return append(cols,
handler.NewCol(IDPTemplateChangeDateCol, idpEvent.CreationDate()),
handler.NewCol(IDPTemplateSequenceCol, idpEvent.Sequence()),
)
}
func reduceLDAPIDPChangedLDAPColumns(idpEvent idp.LDAPIDPChangedEvent) []handler.Column {
ldapCols := make([]handler.Column, 0, 4)
if idpEvent.Host != nil {
ldapCols = append(ldapCols, handler.NewCol(LDAPHostCol, *idpEvent.Host))
}
if idpEvent.Port != nil {
ldapCols = append(ldapCols, handler.NewCol(LDAPPortCol, *idpEvent.Port))
}
if idpEvent.TLS != nil {
ldapCols = append(ldapCols, handler.NewCol(LDAPTlsCol, *idpEvent.TLS))
}
if idpEvent.BaseDN != nil {
ldapCols = append(ldapCols, handler.NewCol(LDAPBaseDNCol, *idpEvent.BaseDN))
}
if idpEvent.UserObjectClass != nil {
ldapCols = append(ldapCols, handler.NewCol(LDAPUserObjectClassCol, *idpEvent.UserObjectClass))
}
if idpEvent.UserUniqueAttribute != nil {
ldapCols = append(ldapCols, handler.NewCol(LDAPUserUniqueAttributeCol, *idpEvent.UserUniqueAttribute))
}
if idpEvent.Admin != nil {
ldapCols = append(ldapCols, handler.NewCol(LDAPAdminCol, *idpEvent.Admin))
}
if idpEvent.Password != nil {
ldapCols = append(ldapCols, handler.NewCol(LDAPPasswordCol, *idpEvent.Password))
}
if idpEvent.IDAttribute != nil {
ldapCols = append(ldapCols, handler.NewCol(LDAPIDAttributeCol, *idpEvent.IDAttribute))
}
if idpEvent.FirstNameAttribute != nil {
ldapCols = append(ldapCols, handler.NewCol(LDAPFirstNameAttributeCol, *idpEvent.FirstNameAttribute))
}
if idpEvent.LastNameAttribute != nil {
ldapCols = append(ldapCols, handler.NewCol(LDAPLastNameAttributeCol, *idpEvent.LastNameAttribute))
}
if idpEvent.DisplayNameAttribute != nil {
ldapCols = append(ldapCols, handler.NewCol(LDAPDisplayNameAttributeCol, *idpEvent.DisplayNameAttribute))
}
if idpEvent.NickNameAttribute != nil {
ldapCols = append(ldapCols, handler.NewCol(LDAPNickNameAttributeCol, *idpEvent.NickNameAttribute))
}
if idpEvent.PreferredUsernameAttribute != nil {
ldapCols = append(ldapCols, handler.NewCol(LDAPPreferredUsernameAttributeCol, *idpEvent.PreferredUsernameAttribute))
}
if idpEvent.EmailAttribute != nil {
ldapCols = append(ldapCols, handler.NewCol(LDAPEmailAttributeCol, *idpEvent.EmailAttribute))
}
if idpEvent.EmailVerifiedAttribute != nil {
ldapCols = append(ldapCols, handler.NewCol(LDAPEmailVerifiedAttributeCol, *idpEvent.EmailVerifiedAttribute))
}
if idpEvent.PhoneAttribute != nil {
ldapCols = append(ldapCols, handler.NewCol(LDAPPhoneAttributeCol, *idpEvent.PhoneAttribute))
}
if idpEvent.PhoneVerifiedAttribute != nil {
ldapCols = append(ldapCols, handler.NewCol(LDAPPhoneVerifiedAttributeCol, *idpEvent.PhoneVerifiedAttribute))
}
if idpEvent.PreferredLanguageAttribute != nil {
ldapCols = append(ldapCols, handler.NewCol(LDAPPreferredLanguageAttributeCol, *idpEvent.PreferredLanguageAttribute))
}
if idpEvent.AvatarURLAttribute != nil {
ldapCols = append(ldapCols, handler.NewCol(LDAPAvatarURLAttributeCol, *idpEvent.AvatarURLAttribute))
}
if idpEvent.ProfileAttribute != nil {
ldapCols = append(ldapCols, handler.NewCol(LDAPProfileAttributeCol, *idpEvent.ProfileAttribute))
}
return ldapCols
}

View File

@@ -0,0 +1,515 @@
package projection
import (
"testing"
"github.com/zitadel/zitadel/internal/domain"
"github.com/zitadel/zitadel/internal/errors"
"github.com/zitadel/zitadel/internal/eventstore"
"github.com/zitadel/zitadel/internal/eventstore/handler"
"github.com/zitadel/zitadel/internal/eventstore/repository"
"github.com/zitadel/zitadel/internal/repository/instance"
"github.com/zitadel/zitadel/internal/repository/org"
)
func TestIDPTemplateProjection_reducesRemove(t *testing.T) {
type args struct {
event func(t *testing.T) eventstore.Event
}
tests := []struct {
name string
args args
reduce func(event eventstore.Event) (*handler.Statement, error)
want wantReduce
}{
{
name: "instance reduceInstanceRemoved",
args: args{
event: getEvent(testEvent(
repository.EventType(instance.InstanceRemovedEventType),
instance.AggregateType,
nil,
), instance.InstanceRemovedEventMapper),
},
reduce: reduceInstanceRemovedHelper(IDPInstanceIDCol),
want: wantReduce{
aggregateType: eventstore.AggregateType("instance"),
sequence: 15,
previousSequence: 10,
executer: &testExecuter{
executions: []execution{
{
expectedStmt: "DELETE FROM projections.idp_templates WHERE (instance_id = $1)",
expectedArgs: []interface{}{
"agg-id",
},
},
},
},
},
},
{
name: "org reduceOwnerRemoved",
reduce: (&idpTemplateProjection{}).reduceOwnerRemoved,
args: args{
event: getEvent(testEvent(
repository.EventType(org.OrgRemovedEventType),
org.AggregateType,
nil,
), org.OrgRemovedEventMapper),
},
want: wantReduce{
aggregateType: eventstore.AggregateType("org"),
sequence: 15,
previousSequence: 10,
executer: &testExecuter{
executions: []execution{
{
expectedStmt: "UPDATE projections.idp_templates SET (change_date, sequence, owner_removed) = ($1, $2, $3) WHERE (instance_id = $4) AND (resource_owner = $5)",
expectedArgs: []interface{}{
anyArg{},
uint64(15),
true,
"instance-id",
"agg-id",
},
},
},
},
},
},
{
name: "org reduceIDPRemoved",
reduce: (&idpTemplateProjection{}).reduceIDPRemoved,
args: args{
event: getEvent(testEvent(
repository.EventType(org.IDPRemovedEventType),
org.AggregateType,
[]byte(`{
"id": "idp-id"
}`),
), org.IDPRemovedEventMapper),
},
want: wantReduce{
aggregateType: eventstore.AggregateType("org"),
sequence: 15,
previousSequence: 10,
executer: &testExecuter{
executions: []execution{
{
expectedStmt: "DELETE FROM projections.idp_templates WHERE (id = $1) AND (instance_id = $2)",
expectedArgs: []interface{}{
"idp-id",
"instance-id",
},
},
},
},
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
event := baseEvent(t)
got, err := tt.reduce(event)
if !errors.IsErrorInvalidArgument(err) {
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, IDPTemplateTable, tt.want)
})
}
}
func TestIDPTemplateProjection_reducesLDAP(t *testing.T) {
type args struct {
event func(t *testing.T) eventstore.Event
}
tests := []struct {
name string
args args
reduce func(event eventstore.Event) (*handler.Statement, error)
want wantReduce
}{
{
name: "instance reduceLDAPIDPAdded",
args: args{
event: getEvent(testEvent(
repository.EventType(instance.LDAPIDPAddedEventType),
instance.AggregateType,
[]byte(`{
"id": "idp-id",
"name": "custom-zitadel-instance",
"host": "host",
"port": "port",
"tls": true,
"baseDN": "base",
"userObjectClass": "user",
"userUniqueAttribute": "uid",
"admin": "admin",
"password": {
"cryptoType": 0,
"algorithm": "RSA-265",
"keyId": "key-id"
},
"idAttribute": "id",
"firstNameAttribute": "first",
"lastNameAttribute": "last",
"displayNameAttribute": "display",
"nickNameAttribute": "nickname",
"preferredUsernameAttribute": "username",
"emailAttribute": "email",
"emailVerifiedAttribute": "email_verified",
"phoneAttribute": "phone",
"phoneVerifiedAttribute": "phone_verified",
"preferredLanguageAttribute": "lang",
"avatarURLAttribute": "avatar",
"profileAttribute": "profile",
"isCreationAllowed": true,
"isLinkingAllowed": true,
"isAutoCreation": true,
"isAutoUpdate": true
}`),
), instance.LDAPIDPAddedEventMapper),
},
reduce: (&idpTemplateProjection{}).reduceLDAPIDPAdded,
want: wantReduce{
aggregateType: eventstore.AggregateType("instance"),
sequence: 15,
previousSequence: 10,
executer: &testExecuter{
executions: []execution{
{
expectedStmt: "INSERT INTO projections.idp_templates (id, creation_date, change_date, sequence, resource_owner, instance_id, state, name, owner_type, type, is_creation_allowed, is_linking_allowed, is_auto_creation, is_auto_update) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14)",
expectedArgs: []interface{}{
"idp-id",
anyArg{},
anyArg{},
uint64(15),
"ro-id",
"instance-id",
domain.IDPStateActive,
"custom-zitadel-instance",
domain.IdentityProviderTypeSystem,
domain.IDPTypeLDAP,
true,
true,
true,
true,
},
},
{
expectedStmt: "INSERT INTO projections.idp_templates_ldap (idp_id, instance_id, host, port, tls, base_dn, user_object_class, user_unique_attribute, admin, password, id_attribute, first_name_attribute, last_name_attribute, display_name_attribute, nick_name_attribute, preferred_username_attribute, email_attribute, email_verified, phone_attribute, phone_verified_attribute, preferred_language_attribute, avatar_url_attribute, profile_attribute) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19, $20, $21, $22, $23)",
expectedArgs: []interface{}{
"idp-id",
"instance-id",
"host",
"port",
true,
"base",
"user",
"uid",
"admin",
anyArg{},
"id",
"first",
"last",
"display",
"nickname",
"username",
"email",
"email_verified",
"phone",
"phone_verified",
"lang",
"avatar",
"profile",
},
},
},
},
},
},
{
name: "org reduceLDAPIDPAdded",
args: args{
event: getEvent(testEvent(
repository.EventType(org.LDAPIDPAddedEventType),
org.AggregateType,
[]byte(`{
"id": "idp-id",
"name": "custom-zitadel-instance",
"host": "host",
"port": "port",
"tls": true,
"baseDN": "base",
"userObjectClass": "user",
"userUniqueAttribute": "uid",
"admin": "admin",
"password": {
"cryptoType": 0,
"algorithm": "RSA-265",
"keyId": "key-id"
},
"idAttribute": "id",
"firstNameAttribute": "first",
"lastNameAttribute": "last",
"displayNameAttribute": "display",
"nickNameAttribute": "nickname",
"preferredUsernameAttribute": "username",
"emailAttribute": "email",
"emailVerifiedAttribute": "email_verified",
"phoneAttribute": "phone",
"phoneVerifiedAttribute": "phone_verified",
"preferredLanguageAttribute": "lang",
"avatarURLAttribute": "avatar",
"profileAttribute": "profile",
"isCreationAllowed": true,
"isLinkingAllowed": true,
"isAutoCreation": true,
"isAutoUpdate": true
}`),
), org.LDAPIDPAddedEventMapper),
},
reduce: (&idpTemplateProjection{}).reduceLDAPIDPAdded,
want: wantReduce{
aggregateType: eventstore.AggregateType("org"),
sequence: 15,
previousSequence: 10,
executer: &testExecuter{
executions: []execution{
{
expectedStmt: "INSERT INTO projections.idp_templates (id, creation_date, change_date, sequence, resource_owner, instance_id, state, name, owner_type, type, is_creation_allowed, is_linking_allowed, is_auto_creation, is_auto_update) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14)",
expectedArgs: []interface{}{
"idp-id",
anyArg{},
anyArg{},
uint64(15),
"ro-id",
"instance-id",
domain.IDPStateActive,
"custom-zitadel-instance",
domain.IdentityProviderTypeOrg,
domain.IDPTypeLDAP,
true,
true,
true,
true,
},
},
{
expectedStmt: "INSERT INTO projections.idp_templates_ldap (idp_id, instance_id, host, port, tls, base_dn, user_object_class, user_unique_attribute, admin, password, id_attribute, first_name_attribute, last_name_attribute, display_name_attribute, nick_name_attribute, preferred_username_attribute, email_attribute, email_verified, phone_attribute, phone_verified_attribute, preferred_language_attribute, avatar_url_attribute, profile_attribute) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19, $20, $21, $22, $23)",
expectedArgs: []interface{}{
"idp-id",
"instance-id",
"host",
"port",
true,
"base",
"user",
"uid",
"admin",
anyArg{},
"id",
"first",
"last",
"display",
"nickname",
"username",
"email",
"email_verified",
"phone",
"phone_verified",
"lang",
"avatar",
"profile",
},
},
},
},
},
},
{
name: "instance reduceLDAPIDPChanged minimal",
args: args{
event: getEvent(testEvent(
repository.EventType(instance.LDAPIDPChangedEventType),
instance.AggregateType,
[]byte(`{
"id": "idp-id",
"name": "custom-zitadel-instance",
"host": "host"
}`),
), instance.LDAPIDPChangedEventMapper),
},
reduce: (&idpTemplateProjection{}).reduceLDAPIDPChanged,
want: wantReduce{
aggregateType: eventstore.AggregateType("instance"),
sequence: 15,
previousSequence: 10,
executer: &testExecuter{
executions: []execution{
{
expectedStmt: "UPDATE projections.idp_templates SET (name, change_date, sequence) = ($1, $2, $3) WHERE (id = $4) AND (instance_id = $5)",
expectedArgs: []interface{}{
"custom-zitadel-instance",
anyArg{},
uint64(15),
"idp-id",
"instance-id",
},
},
{
expectedStmt: "UPDATE projections.idp_templates_ldap SET host = $1 WHERE (idp_id = $2) AND (instance_id = $3)",
expectedArgs: []interface{}{
"host",
"idp-id",
"instance-id",
},
},
},
},
},
},
{
name: "instance reduceLDAPIDPChanged",
args: args{
event: getEvent(testEvent(
repository.EventType(instance.LDAPIDPChangedEventType),
instance.AggregateType,
[]byte(`{
"id": "idp-id",
"name": "custom-zitadel-instance",
"host": "host",
"port": "port",
"tls": true,
"baseDN": "base",
"userObjectClass": "user",
"userUniqueAttribute": "uid",
"admin": "admin",
"password": {
"cryptoType": 0,
"algorithm": "RSA-265",
"keyId": "key-id"
},
"idAttribute": "id",
"firstNameAttribute": "first",
"lastNameAttribute": "last",
"displayNameAttribute": "display",
"nickNameAttribute": "nickname",
"preferredUsernameAttribute": "username",
"emailAttribute": "email",
"emailVerifiedAttribute": "email_verified",
"phoneAttribute": "phone",
"phoneVerifiedAttribute": "phone_verified",
"preferredLanguageAttribute": "lang",
"avatarURLAttribute": "avatar",
"profileAttribute": "profile",
"isCreationAllowed": true,
"isLinkingAllowed": true,
"isAutoCreation": true,
"isAutoUpdate": true
}`),
), instance.LDAPIDPChangedEventMapper),
},
reduce: (&idpTemplateProjection{}).reduceLDAPIDPChanged,
want: wantReduce{
aggregateType: eventstore.AggregateType("instance"),
sequence: 15,
previousSequence: 10,
executer: &testExecuter{
executions: []execution{
{
expectedStmt: "UPDATE projections.idp_templates SET (name, is_creation_allowed, is_linking_allowed, is_auto_creation, is_auto_update, change_date, sequence) = ($1, $2, $3, $4, $5, $6, $7) WHERE (id = $8) AND (instance_id = $9)",
expectedArgs: []interface{}{
"custom-zitadel-instance",
true,
true,
true,
true,
anyArg{},
uint64(15),
"idp-id",
"instance-id",
},
},
{
expectedStmt: "UPDATE projections.idp_templates_ldap SET (host, port, tls, base_dn, user_object_class, user_unique_attribute, admin, password, id_attribute, first_name_attribute, last_name_attribute, display_name_attribute, nick_name_attribute, preferred_username_attribute, email_attribute, email_verified, phone_attribute, phone_verified_attribute, preferred_language_attribute, avatar_url_attribute, profile_attribute) = ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19, $20, $21) WHERE (idp_id = $22) AND (instance_id = $23)",
expectedArgs: []interface{}{
"host",
"port",
true,
"base",
"user",
"uid",
"admin",
anyArg{},
"id",
"first",
"last",
"display",
"nickname",
"username",
"email",
"email_verified",
"phone",
"phone_verified",
"lang",
"avatar",
"profile",
"idp-id",
"instance-id",
},
},
},
},
},
},
{
name: "org.reduceOwnerRemoved",
reduce: (&idpProjection{}).reduceOwnerRemoved,
args: args{
event: getEvent(testEvent(
repository.EventType(org.OrgRemovedEventType),
org.AggregateType,
nil,
), org.OrgRemovedEventMapper),
},
want: wantReduce{
aggregateType: eventstore.AggregateType("org"),
sequence: 15,
previousSequence: 10,
executer: &testExecuter{
executions: []execution{
{
expectedStmt: "UPDATE projections.idp_templates SET (change_date, sequence, owner_removed) = ($1, $2, $3) WHERE (instance_id = $4) AND (resource_owner = $5)",
expectedArgs: []interface{}{
anyArg{},
uint64(15),
true,
"instance-id",
"agg-id",
},
},
},
},
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
event := baseEvent(t)
got, err := tt.reduce(event)
if !errors.IsErrorInvalidArgument(err) {
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, IDPTemplateTable, tt.want)
})
}
}

View File

@@ -37,6 +37,7 @@ var (
AppProjection *appProjection
IDPUserLinkProjection *idpUserLinkProjection
IDPLoginPolicyLinkProjection *idpLoginPolicyLinkProjection
IDPTemplateProjection *idpTemplateProjection
MailTemplateProjection *mailTemplateProjection
MessageTextProjection *messageTextProjection
CustomTextProjection *customTextProjection
@@ -111,6 +112,7 @@ func Create(ctx context.Context, sqlClient *sql.DB, es *eventstore.Eventstore, c
AppProjection = newAppProjection(ctx, applyCustomConfig(projectionConfig, config.Customizations["apps"]))
IDPUserLinkProjection = newIDPUserLinkProjection(ctx, applyCustomConfig(projectionConfig, config.Customizations["idp_user_links"]))
IDPLoginPolicyLinkProjection = newIDPLoginPolicyLinkProjection(ctx, applyCustomConfig(projectionConfig, config.Customizations["idp_login_policy_links"]))
IDPTemplateProjection = newIDPTemplateProjection(ctx, applyCustomConfig(projectionConfig, config.Customizations["idp_templates"]))
MailTemplateProjection = newMailTemplateProjection(ctx, applyCustomConfig(projectionConfig, config.Customizations["mail_templates"]))
MessageTextProjection = newMessageTextProjection(ctx, applyCustomConfig(projectionConfig, config.Customizations["message_texts"]))
CustomTextProjection = newCustomTextProjection(ctx, applyCustomConfig(projectionConfig, config.Customizations["custom_texts"]))
@@ -199,6 +201,7 @@ func newProjectionsList() {
OrgDomainProjection,
LoginPolicyProjection,
IDPProjection,
IDPTemplateProjection,
AppProjection,
IDPUserLinkProjection,
IDPLoginPolicyLinkProjection,