fix: restrict AllowRegistration check to local registration (#5939)

* fix: restrict AllowRegistration check to local registration

* add comment

* add additional tests

* hide registration fields if no registration allowed

* fix: always allow linking and creation of external idps on users in userV2 and admin import

* chore: exclude console dist and node_module folders from cache

* chore: include node_module folders into cache again

* linting

(cherry picked from commit 66772ad0dd)
This commit is contained in:
Livio Spring 2023-08-23 13:55:52 +02:00
parent 85194666ff
commit a628f2222e
No known key found for this signature in database
GPG Key ID: 26BB1C2FA5952CF0
9 changed files with 468 additions and 40 deletions

View File

@ -623,10 +623,9 @@ func (s *Server) importData(ctx context.Context, orgs []*admin_pb.DataOrg) (*adm
if org.UserLinks != nil { if org.UserLinks != nil {
for _, userLinks := range org.GetUserLinks() { for _, userLinks := range org.GetUserLinks() {
logging.Debugf("import userlink: %s", userLinks.GetUserId()+"_"+userLinks.GetIdpId()+"_"+userLinks.GetProvidedUserId()+"_"+userLinks.GetProvidedUserName()) logging.Debugf("import userlink: %s", userLinks.GetUserId()+"_"+userLinks.GetIdpId()+"_"+userLinks.GetProvidedUserId()+"_"+userLinks.GetProvidedUserName())
externalIDP := &domain.UserIDPLink{ externalIDP := &command.AddLink{
ObjectRoot: models.ObjectRoot{AggregateID: userLinks.UserId}, IDPID: userLinks.IdpId,
IDPConfigID: userLinks.IdpId, IDPExternalID: userLinks.ProvidedUserId,
ExternalUserID: userLinks.ProvidedUserId,
DisplayName: userLinks.ProvidedUserName, DisplayName: userLinks.ProvidedUserName,
} }
if _, err := s.command.AddUserIDPLink(ctx, userLinks.UserId, org.GetOrgId(), externalIDP); err != nil { if _, err := s.command.AddUserIDPLink(ctx, userLinks.UserId, org.GetOrgId(), externalIDP); err != nil {

View File

@ -116,10 +116,10 @@ func genderToDomain(gender user.Gender) domain.Gender {
func (s *Server) AddIDPLink(ctx context.Context, req *user.AddIDPLinkRequest) (_ *user.AddIDPLinkResponse, err error) { func (s *Server) AddIDPLink(ctx context.Context, req *user.AddIDPLinkRequest) (_ *user.AddIDPLinkResponse, err error) {
orgID := authz.GetCtxData(ctx).OrgID orgID := authz.GetCtxData(ctx).OrgID
details, err := s.command.AddUserIDPLink(ctx, req.UserId, orgID, &domain.UserIDPLink{ details, err := s.command.AddUserIDPLink(ctx, req.UserId, orgID, &command.AddLink{
IDPConfigID: req.GetIdpLink().GetIdpId(), IDPID: req.GetIdpLink().GetIdpId(),
ExternalUserID: req.GetIdpLink().GetUserId(),
DisplayName: req.GetIdpLink().GetUserName(), DisplayName: req.GetIdpLink().GetUserName(),
IDPExternalID: req.GetIdpLink().GetUserId(),
}) })
if err != nil { if err != nil {
return nil, err return nil, err

View File

@ -66,6 +66,7 @@ type externalNotFoundOptionData struct {
ExternalEmailVerified bool ExternalEmailVerified bool
ExternalPhone domain.PhoneNumber ExternalPhone domain.PhoneNumber
ExternalPhoneVerified bool ExternalPhoneVerified bool
ProviderName string
} }
type externalRegisterFormData struct { type externalRegisterFormData struct {
@ -503,6 +504,7 @@ func (l *Login) renderExternalNotFoundOption(w http.ResponseWriter, r *http.Requ
ShowUsername: orgIAMPolicy.UserLoginMustBeDomain, ShowUsername: orgIAMPolicy.UserLoginMustBeDomain,
ShowUsernameSuffix: !labelPolicy.HideLoginNameSuffix, ShowUsernameSuffix: !labelPolicy.HideLoginNameSuffix,
OrgRegister: orgIAMPolicy.UserLoginMustBeDomain, OrgRegister: orgIAMPolicy.UserLoginMustBeDomain,
ProviderName: domain.IDPName(idpTemplate.Name, idpTemplate.Type),
} }
if human.Phone != nil { if human.Phone != nil {
data.Phone = human.PhoneNumber data.Phone = human.PhoneNumber

View File

@ -1,8 +1,11 @@
{{template "main-top" .}} {{template "main-top" .}}
<div class="lgn-head"> <div class="lgn-head">
<h1>{{t "ExternalNotFound.Title"}}</h1> <h1>{{.ProviderName}} - {{t "ExternalNotFound.Title"}}</h1>
{{ if or .IsLinkingAllowed .IsCreationAllowed }}
<p>{{t "ExternalNotFound.Description"}}</p> <p>{{t "ExternalNotFound.Description"}}</p>
{{ end }}
</div> </div>
@ -21,6 +24,7 @@
<input type="hidden" id="external-phone-verified" name="external-phone-verified" value="{{ .ExternalPhoneVerified }}" /> <input type="hidden" id="external-phone-verified" name="external-phone-verified" value="{{ .ExternalPhoneVerified }}" />
<div class="lgn-register"> <div class="lgn-register">
{{ if or .IsCreationAllowed }}
<div class="double-col"> <div class="double-col">
<div class="lgn-field"> <div class="lgn-field">
<label class="lgn-label" for="firstname">{{t "ExternalRegistrationUserOverview.FirstnameLabel"}}</label> <label class="lgn-label" for="firstname">{{t "ExternalRegistrationUserOverview.FirstnameLabel"}}</label>
@ -85,8 +89,9 @@
</select> </select>
</div> </div>
</div> </div>
{{end}}
{{ if or .TOSLink .PrivacyLink }} {{ if and (or .IsLinkingAllowed .IsCreationAllowed) (or .TOSLink .PrivacyLink) }}
<div class="lgn-field"> <div class="lgn-field">
<label class="lgn-label">{{t "ExternalNotFound.TosAndPrivacyLabel"}}</label> <label class="lgn-label">{{t "ExternalNotFound.TosAndPrivacyLabel"}}</label>
{{ if .TOSLink }} {{ if .TOSLink }}

View File

@ -189,6 +189,10 @@ func (wm *OAuthIDPWriteModel) ToProvider(callbackURL string, idpAlg crypto.Encry
) )
} }
func (wm *OAuthIDPWriteModel) GetProviderOptions() idp.Options {
return wm.Options
}
type OIDCIDPWriteModel struct { type OIDCIDPWriteModel struct {
eventstore.WriteModel eventstore.WriteModel
@ -310,7 +314,10 @@ func (wm *OIDCIDPWriteModel) NewChanges(
// reduceIDPConfigAddedEvent handles old idpConfig events // reduceIDPConfigAddedEvent handles old idpConfig events
func (wm *OIDCIDPWriteModel) reduceIDPConfigAddedEvent(e *idpconfig.IDPConfigAddedEvent) { func (wm *OIDCIDPWriteModel) reduceIDPConfigAddedEvent(e *idpconfig.IDPConfigAddedEvent) {
wm.Name = e.Name wm.Name = e.Name
wm.Options.IsCreationAllowed = true
wm.Options.IsLinkingAllowed = true
wm.Options.IsAutoCreation = e.AutoRegister wm.Options.IsAutoCreation = e.AutoRegister
wm.Options.IsAutoUpdate = false
wm.State = domain.IDPStateActive wm.State = domain.IDPStateActive
} }
@ -382,6 +389,10 @@ func (wm *OIDCIDPWriteModel) ToProvider(callbackURL string, idpAlg crypto.Encryp
) )
} }
func (wm *OIDCIDPWriteModel) GetProviderOptions() idp.Options {
return wm.Options
}
type JWTIDPWriteModel struct { type JWTIDPWriteModel struct {
eventstore.WriteModel eventstore.WriteModel
@ -483,7 +494,10 @@ func (wm *JWTIDPWriteModel) NewChanges(
// reduceIDPConfigAddedEvent handles old idpConfig events // reduceIDPConfigAddedEvent handles old idpConfig events
func (wm *JWTIDPWriteModel) reduceIDPConfigAddedEvent(e *idpconfig.IDPConfigAddedEvent) { func (wm *JWTIDPWriteModel) reduceIDPConfigAddedEvent(e *idpconfig.IDPConfigAddedEvent) {
wm.Name = e.Name wm.Name = e.Name
wm.Options.IsCreationAllowed = true
wm.Options.IsLinkingAllowed = true
wm.Options.IsAutoCreation = e.AutoRegister wm.Options.IsAutoCreation = e.AutoRegister
wm.Options.IsAutoUpdate = false
wm.State = domain.IDPStateActive wm.State = domain.IDPStateActive
} }
@ -546,6 +560,10 @@ func (wm *JWTIDPWriteModel) ToProvider(callbackURL string, idpAlg crypto.Encrypt
) )
} }
func (wm *JWTIDPWriteModel) GetProviderOptions() idp.Options {
return wm.Options
}
type AzureADIDPWriteModel struct { type AzureADIDPWriteModel struct {
eventstore.WriteModel eventstore.WriteModel
@ -690,6 +708,10 @@ func (wm *AzureADIDPWriteModel) ToProvider(callbackURL string, idpAlg crypto.Enc
) )
} }
func (wm *AzureADIDPWriteModel) GetProviderOptions() idp.Options {
return wm.Options
}
type GitHubIDPWriteModel struct { type GitHubIDPWriteModel struct {
eventstore.WriteModel eventstore.WriteModel
@ -803,6 +825,10 @@ func (wm *GitHubIDPWriteModel) ToProvider(callbackURL string, idpAlg crypto.Encr
) )
} }
func (wm *GitHubIDPWriteModel) GetProviderOptions() idp.Options {
return wm.Options
}
type GitHubEnterpriseIDPWriteModel struct { type GitHubEnterpriseIDPWriteModel struct {
eventstore.WriteModel eventstore.WriteModel
@ -947,6 +973,10 @@ func (wm *GitHubEnterpriseIDPWriteModel) ToProvider(callbackURL string, idpAlg c
) )
} }
func (wm *GitHubEnterpriseIDPWriteModel) GetProviderOptions() idp.Options {
return wm.Options
}
type GitLabIDPWriteModel struct { type GitLabIDPWriteModel struct {
eventstore.WriteModel eventstore.WriteModel
@ -1061,6 +1091,10 @@ func (wm *GitLabIDPWriteModel) ToProvider(callbackURL string, idpAlg crypto.Encr
) )
} }
func (wm *GitLabIDPWriteModel) GetProviderOptions() idp.Options {
return wm.Options
}
type GitLabSelfHostedIDPWriteModel struct { type GitLabSelfHostedIDPWriteModel struct {
eventstore.WriteModel eventstore.WriteModel
@ -1185,6 +1219,10 @@ func (wm *GitLabSelfHostedIDPWriteModel) ToProvider(callbackURL string, idpAlg c
) )
} }
func (wm *GitLabSelfHostedIDPWriteModel) GetProviderOptions() idp.Options {
return wm.Options
}
type GoogleIDPWriteModel struct { type GoogleIDPWriteModel struct {
eventstore.WriteModel eventstore.WriteModel
@ -1306,6 +1344,10 @@ func (wm *GoogleIDPWriteModel) ToProvider(callbackURL string, idpAlg crypto.Encr
) )
} }
func (wm *GoogleIDPWriteModel) GetProviderOptions() idp.Options {
return wm.Options
}
type LDAPIDPWriteModel struct { type LDAPIDPWriteModel struct {
eventstore.WriteModel eventstore.WriteModel
@ -1541,6 +1583,10 @@ func (wm *LDAPIDPWriteModel) ToProvider(callbackURL string, idpAlg crypto.Encryp
), nil ), nil
} }
func (wm *LDAPIDPWriteModel) GetProviderOptions() idp.Options {
return wm.Options
}
type IDPRemoveWriteModel struct { type IDPRemoveWriteModel struct {
eventstore.WriteModel eventstore.WriteModel
@ -1771,6 +1817,7 @@ func (wm *IDPTypeWriteModel) Query() *eventstore.SearchQueryBuilder {
type IDP interface { type IDP interface {
eventstore.QueryReducer eventstore.QueryReducer
ToProvider(string, crypto.EncryptionAlgorithm) (providers.Provider, error) ToProvider(string, crypto.EncryptionAlgorithm) (providers.Provider, error)
GetProviderOptions() idp.Options
} }
type AllIDPWriteModel struct { type AllIDPWriteModel struct {
@ -1863,3 +1910,7 @@ func (wm *AllIDPWriteModel) AppendEvents(events ...eventstore.Event) {
func (wm *AllIDPWriteModel) ToProvider(callbackURL string, idpAlg crypto.EncryptionAlgorithm) (providers.Provider, error) { func (wm *AllIDPWriteModel) ToProvider(callbackURL string, idpAlg crypto.EncryptionAlgorithm) (providers.Provider, error) {
return wm.model.ToProvider(callbackURL, idpAlg) return wm.model.ToProvider(callbackURL, idpAlg)
} }
func (wm *AllIDPWriteModel) GetProviderOptions() idp.Options {
return wm.model.GetProviderOptions()
}

View File

@ -475,7 +475,8 @@ func (c *Commands) RegisterHuman(ctx context.Context, orgID string, human *domai
if err != nil { if err != nil {
return nil, errors.ThrowPreconditionFailed(err, "COMMAND-Dfg3g", "Errors.Org.LoginPolicy.NotFound") return nil, errors.ThrowPreconditionFailed(err, "COMMAND-Dfg3g", "Errors.Org.LoginPolicy.NotFound")
} }
if !loginPolicy.AllowRegister { // check only if local registration is allowed, the idp will be checked separately
if !loginPolicy.AllowRegister && link == nil {
return nil, errors.ThrowPreconditionFailed(err, "COMMAND-SAbr3", "Errors.Org.LoginPolicy.RegistrationNotAllowed") return nil, errors.ThrowPreconditionFailed(err, "COMMAND-SAbr3", "Errors.Org.LoginPolicy.RegistrationNotAllowed")
} }
userEvents, registeredHuman, err := c.registerHuman(ctx, orgID, human, link, domainPolicy, pwPolicy, initCodeGenerator, emailCodeGenerator, phoneCodeGenerator) userEvents, registeredHuman, err := c.registerHuman(ctx, orgID, human, link, domainPolicy, pwPolicy, initCodeGenerator, emailCodeGenerator, phoneCodeGenerator)
@ -605,7 +606,7 @@ func (c *Commands) createHuman(ctx context.Context, orgID string, human *domain.
} }
for _, link := range links { for _, link := range links {
event, err := c.addUserIDPLink(ctx, userAgg, link) event, err := c.addUserIDPLink(ctx, userAgg, link, false)
if err != nil { if err != nil {
return nil, nil, err return nil, nil, err
} }

View File

@ -20,6 +20,7 @@ import (
"github.com/zitadel/zitadel/internal/eventstore/v1/models" "github.com/zitadel/zitadel/internal/eventstore/v1/models"
"github.com/zitadel/zitadel/internal/id" "github.com/zitadel/zitadel/internal/id"
id_mock "github.com/zitadel/zitadel/internal/id/mock" id_mock "github.com/zitadel/zitadel/internal/id/mock"
"github.com/zitadel/zitadel/internal/repository/idp"
"github.com/zitadel/zitadel/internal/repository/org" "github.com/zitadel/zitadel/internal/repository/org"
"github.com/zitadel/zitadel/internal/repository/user" "github.com/zitadel/zitadel/internal/repository/user"
) )
@ -2000,6 +2001,31 @@ func TestCommandSide_ImportHuman(t *testing.T) {
), ),
), ),
), ),
expectFilter(
eventFromEventPusher(
org.NewIDPConfigAddedEvent(context.Background(),
&org.NewAggregate("org1").Aggregate,
"idpID",
"name",
domain.IDPConfigTypeOIDC,
domain.IDPConfigStylingTypeUnspecified,
false,
),
),
eventFromEventPusher(
org.NewIDPOIDCConfigAddedEvent(context.Background(),
&org.NewAggregate("org1").Aggregate,
"clientID",
"idpID",
"issuer",
"authEndpoint",
"tokenEndpoint",
nil,
domain.OIDCMappingFieldUnspecified,
domain.OIDCMappingFieldUnspecified,
),
),
),
expectFilter( expectFilter(
eventFromEventPusher( eventFromEventPusher(
org.NewIDPConfigAddedEvent(context.Background(), org.NewIDPConfigAddedEvent(context.Background(),
@ -2102,6 +2128,146 @@ func TestCommandSide_ImportHuman(t *testing.T) {
}, },
}, },
}, },
{
name: "add human (with idp, creation not allowed), precondition error",
fields: fields{
eventstore: eventstoreExpect(
t,
expectFilter(
eventFromEventPusher(
org.NewDomainPolicyAddedEvent(context.Background(),
&user.NewAggregate("user1", "org1").Aggregate,
true,
true,
true,
),
),
),
expectFilter(
eventFromEventPusher(
org.NewPasswordComplexityPolicyAddedEvent(context.Background(),
&user.NewAggregate("user1", "org1").Aggregate,
1,
false,
false,
false,
false,
),
),
),
expectFilter(
eventFromEventPusher(
org.NewIDPConfigAddedEvent(context.Background(),
&org.NewAggregate("org1").Aggregate,
"idpID",
"name",
domain.IDPConfigTypeOIDC,
domain.IDPConfigStylingTypeUnspecified,
false,
),
),
eventFromEventPusher(
org.NewIDPOIDCConfigAddedEvent(context.Background(),
&org.NewAggregate("org1").Aggregate,
"clientID",
"idpID",
"issuer",
"authEndpoint",
"tokenEndpoint",
nil,
domain.OIDCMappingFieldUnspecified,
domain.OIDCMappingFieldUnspecified,
),
),
eventFromEventPusher(
func() eventstore.Command {
e, _ := org.NewOIDCIDPChangedEvent(context.Background(),
&org.NewAggregate("org1").Aggregate,
"config1",
[]idp.OIDCIDPChanges{
idp.ChangeOIDCOptions(idp.OptionChanges{IsCreationAllowed: gu.Ptr(false)}),
},
)
return e
}(),
),
),
expectFilter(
eventFromEventPusher(
org.NewIDPConfigAddedEvent(context.Background(),
&org.NewAggregate("org1").Aggregate,
"idpID",
"name",
domain.IDPConfigTypeOIDC,
domain.IDPConfigStylingTypeUnspecified,
false,
),
),
eventFromEventPusher(
org.NewIDPOIDCConfigAddedEvent(context.Background(),
&org.NewAggregate("org1").Aggregate,
"clientID",
"idpID",
"issuer",
"authEndpoint",
"tokenEndpoint",
nil,
domain.OIDCMappingFieldUnspecified,
domain.OIDCMappingFieldUnspecified,
),
),
eventFromEventPusher(
func() eventstore.Command {
e, _ := org.NewOIDCIDPChangedEvent(context.Background(),
&org.NewAggregate("org1").Aggregate,
"config1",
[]idp.OIDCIDPChanges{
idp.ChangeOIDCOptions(idp.OptionChanges{IsCreationAllowed: gu.Ptr(false)}),
},
)
return e
}(),
),
eventFromEventPusher(
org.NewIdentityProviderAddedEvent(context.Background(),
&org.NewAggregate("org1").Aggregate,
"idpID",
domain.IdentityProviderTypeOrg,
),
),
),
),
idGenerator: id_mock.NewIDGeneratorExpectIDs(t, "user1"),
userPasswordHasher: mockPasswordHasher("x"),
},
args: args{
ctx: context.Background(),
orgID: "org1",
human: &domain.Human{
Username: "username",
Profile: &domain.Profile{
FirstName: "firstname",
LastName: "lastname",
PreferredLanguage: language.English,
},
Email: &domain.Email{
EmailAddress: "email@test.ch",
IsEmailVerified: true,
},
},
links: []*domain.UserIDPLink{
{
IDPConfigID: "idpID",
ExternalUserID: "externalID",
DisplayName: "name",
},
},
secretGenerator: GetMockSecretGenerator(t),
},
res: res{
err: caos_errs.IsPreconditionFailed,
},
},
} }
for _, tt := range tests { for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) { t.Run(tt.name, func(t *testing.T) {
@ -3333,6 +3499,31 @@ func TestCommandSide_RegisterHuman(t *testing.T) {
), ),
), ),
), ),
expectFilter(
eventFromEventPusher(
org.NewIDPConfigAddedEvent(context.Background(),
&org.NewAggregate("org1").Aggregate,
"idpID",
"name",
domain.IDPConfigTypeOIDC,
domain.IDPConfigStylingTypeUnspecified,
false,
),
),
eventFromEventPusher(
org.NewIDPOIDCConfigAddedEvent(context.Background(),
&org.NewAggregate("org1").Aggregate,
"clientID",
"idpID",
"issuer",
"authEndpoint",
"tokenEndpoint",
nil,
domain.OIDCMappingFieldUnspecified,
domain.OIDCMappingFieldUnspecified,
),
),
),
expectPush( expectPush(
[]*repository.Event{ []*repository.Event{
eventFromEventPusher( eventFromEventPusher(

View File

@ -11,7 +11,7 @@ import (
"github.com/zitadel/zitadel/internal/telemetry/tracing" "github.com/zitadel/zitadel/internal/telemetry/tracing"
) )
func (c *Commands) AddUserIDPLink(ctx context.Context, userID, resourceOwner string, link *domain.UserIDPLink) (_ *domain.ObjectDetails, err error) { func (c *Commands) AddUserIDPLink(ctx context.Context, userID, resourceOwner string, link *AddLink) (_ *domain.ObjectDetails, err error) {
if userID == "" { if userID == "" {
return nil, caos_errs.ThrowInvalidArgument(nil, "COMMAND-03j8f", "Errors.IDMissing") return nil, caos_errs.ThrowInvalidArgument(nil, "COMMAND-03j8f", "Errors.IDMissing")
} }
@ -23,11 +23,7 @@ func (c *Commands) AddUserIDPLink(ctx context.Context, userID, resourceOwner str
return nil, err return nil, err
} }
} }
event, err := addLink(ctx, c.eventstore.Filter, user.NewAggregate(userID, resourceOwner), link)
linkWriteModel := NewUserIDPLinkWriteModel(userID, link.IDPConfigID, link.ExternalUserID, resourceOwner)
userAgg := UserAggregateFromWriteModel(&linkWriteModel.WriteModel)
event, err := c.addUserIDPLink(ctx, userAgg, link)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -60,7 +56,7 @@ func (c *Commands) BulkAddedUserIDPLinks(ctx context.Context, userID, resourceOw
linkWriteModel := NewUserIDPLinkWriteModel(userID, link.IDPConfigID, link.ExternalUserID, resourceOwner) linkWriteModel := NewUserIDPLinkWriteModel(userID, link.IDPConfigID, link.ExternalUserID, resourceOwner)
userAgg := UserAggregateFromWriteModel(&linkWriteModel.WriteModel) userAgg := UserAggregateFromWriteModel(&linkWriteModel.WriteModel)
events[i], err = c.addUserIDPLink(ctx, userAgg, link) events[i], err = c.addUserIDPLink(ctx, userAgg, link, true)
if err != nil { if err != nil {
return err return err
} }
@ -70,18 +66,25 @@ func (c *Commands) BulkAddedUserIDPLinks(ctx context.Context, userID, resourceOw
return err return err
} }
func (c *Commands) addUserIDPLink(ctx context.Context, human *eventstore.Aggregate, link *domain.UserIDPLink) (eventstore.Command, error) { func (c *Commands) addUserIDPLink(ctx context.Context, human *eventstore.Aggregate, link *domain.UserIDPLink, linkToExistingUser bool) (eventstore.Command, error) {
if link.AggregateID != "" && human.ID != link.AggregateID { if link.AggregateID != "" && human.ID != link.AggregateID {
return nil, caos_errs.ThrowInvalidArgument(nil, "COMMAND-33M0g", "Errors.IDMissing") return nil, caos_errs.ThrowInvalidArgument(nil, "COMMAND-33M0g", "Errors.IDMissing")
} }
if !link.IsValid() { if !link.IsValid() {
return nil, caos_errs.ThrowInvalidArgument(nil, "COMMAND-6m9Kd", "Errors.User.ExternalIDP.Invalid") return nil, caos_errs.ThrowInvalidArgument(nil, "COMMAND-6m9Kd", "Errors.User.ExternalIDP.Invalid")
} }
idpWriteModel, err := IDPProviderWriteModel(ctx, c.eventstore.Filter, link.IDPConfigID)
exists, err := ExistsIDP(ctx, c.eventstore.Filter, link.IDPConfigID, human.ResourceOwner) if err != nil {
if !exists || err != nil {
return nil, caos_errs.ThrowPreconditionFailed(err, "COMMAND-39nfs", "Errors.IDPConfig.NotExisting") return nil, caos_errs.ThrowPreconditionFailed(err, "COMMAND-39nfs", "Errors.IDPConfig.NotExisting")
} }
// IDP user will either be linked or created on a new user
// Therefore we need to either check if linking is allowed or creation:
if linkToExistingUser && !idpWriteModel.GetProviderOptions().IsLinkingAllowed {
return nil, caos_errs.ThrowPreconditionFailed(err, "COMMAND-Sfee2", "Errors.ExternalIDP.LinkingNotAllowed")
}
if !linkToExistingUser && !idpWriteModel.GetProviderOptions().IsCreationAllowed {
return nil, caos_errs.ThrowPreconditionFailed(err, "COMMAND-SJI3g", "Errors.ExternalIDP.CreationNotAllowed")
}
return user.NewUserIDPLinkAddedEvent(ctx, human, link.IDPConfigID, link.DisplayName, link.ExternalUserID), nil return user.NewUserIDPLinkAddedEvent(ctx, human, link.IDPConfigID, link.DisplayName, link.ExternalUserID), nil
} }

View File

@ -4,6 +4,7 @@ import (
"context" "context"
"testing" "testing"
"github.com/muhlemmer/gu"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"golang.org/x/text/language" "golang.org/x/text/language"
@ -12,6 +13,7 @@ import (
"github.com/zitadel/zitadel/internal/eventstore" "github.com/zitadel/zitadel/internal/eventstore"
"github.com/zitadel/zitadel/internal/eventstore/repository" "github.com/zitadel/zitadel/internal/eventstore/repository"
"github.com/zitadel/zitadel/internal/eventstore/v1/models" "github.com/zitadel/zitadel/internal/eventstore/v1/models"
"github.com/zitadel/zitadel/internal/repository/idp"
"github.com/zitadel/zitadel/internal/repository/instance" "github.com/zitadel/zitadel/internal/repository/instance"
"github.com/zitadel/zitadel/internal/repository/org" "github.com/zitadel/zitadel/internal/repository/org"
"github.com/zitadel/zitadel/internal/repository/user" "github.com/zitadel/zitadel/internal/repository/user"
@ -28,7 +30,7 @@ func TestCommandSide_BulkAddUserIDPLinks(t *testing.T) {
links []*domain.UserIDPLink links []*domain.UserIDPLink
} }
type res struct { type res struct {
err func(error) bool err error
} }
tests := []struct { tests := []struct {
name string name string
@ -55,7 +57,7 @@ func TestCommandSide_BulkAddUserIDPLinks(t *testing.T) {
resourceOwner: "org1", resourceOwner: "org1",
}, },
res: res{ res: res{
err: caos_errs.IsErrorInvalidArgument, err: caos_errs.ThrowInvalidArgument(nil, "COMMAND-03j8f", "Errors.IDMissing"),
}, },
}, },
{ {
@ -71,7 +73,7 @@ func TestCommandSide_BulkAddUserIDPLinks(t *testing.T) {
resourceOwner: "org1", resourceOwner: "org1",
}, },
res: res{ res: res{
err: caos_errs.IsErrorInvalidArgument, err: caos_errs.ThrowInvalidArgument(nil, "COMMAND-Ek9s", "Errors.User.ExternalIDP.MinimumExternalIDPNeeded"),
}, },
}, },
{ {
@ -113,7 +115,7 @@ func TestCommandSide_BulkAddUserIDPLinks(t *testing.T) {
}, },
}, },
res: res{ res: res{
err: caos_errs.IsErrorInvalidArgument, err: caos_errs.ThrowInvalidArgument(nil, "COMMAND-33M0g", "Errors.IDMissing"),
}, },
}, },
{ {
@ -155,7 +157,7 @@ func TestCommandSide_BulkAddUserIDPLinks(t *testing.T) {
}, },
}, },
res: res{ res: res{
err: caos_errs.IsErrorInvalidArgument, err: caos_errs.ThrowInvalidArgument(nil, "COMMAND-6m9Kd", "Errors.User.ExternalIDP.Invalid"),
}, },
}, },
{ {
@ -181,7 +183,6 @@ func TestCommandSide_BulkAddUserIDPLinks(t *testing.T) {
), ),
), ),
expectFilter(), expectFilter(),
expectFilter(),
), ),
}, },
args: args{ args: args{
@ -199,7 +200,112 @@ func TestCommandSide_BulkAddUserIDPLinks(t *testing.T) {
}, },
}, },
res: res{ res: res{
err: caos_errs.IsPreconditionFailed, err: caos_errs.ThrowPreconditionFailed(nil, "COMMAND-as02jin", "Errors.IDPConfig.NotExisting"),
},
},
{
name: "linking not allowed, precondition error",
fields: fields{
eventstore: eventstoreExpect(
t,
expectFilter(
eventFromEventPusher(
user.NewHumanAddedEvent(
context.Background(),
&user.NewAggregate("user1", "org1").Aggregate,
"userName",
"firstName",
"lastName",
"nickName",
"displayName",
language.German,
domain.GenderFemale,
"email@Address.ch",
false,
),
),
),
expectFilter(
eventFromEventPusher(
org.NewIDPConfigAddedEvent(context.Background(),
&org.NewAggregate("org1").Aggregate,
"config1",
"name",
domain.IDPConfigTypeOIDC,
domain.IDPConfigStylingTypeUnspecified,
true,
),
),
eventFromEventPusher(
org.NewIDPOIDCConfigAddedEvent(context.Background(),
&org.NewAggregate("org1").Aggregate,
"clientID",
"config1",
"issuer",
"authEndpoint",
"tokenEndpoint",
nil,
domain.OIDCMappingFieldUnspecified,
domain.OIDCMappingFieldUnspecified,
),
),
),
expectFilter(
eventFromEventPusher(
org.NewIDPConfigAddedEvent(context.Background(),
&org.NewAggregate("org1").Aggregate,
"config1",
"name",
domain.IDPConfigTypeOIDC,
domain.IDPConfigStylingTypeUnspecified,
true,
),
),
eventFromEventPusher(
org.NewIDPOIDCConfigAddedEvent(context.Background(),
&org.NewAggregate("org1").Aggregate,
"clientID",
"config1",
"issuer",
"authEndpoint",
"tokenEndpoint",
nil,
domain.OIDCMappingFieldUnspecified,
domain.OIDCMappingFieldUnspecified,
),
),
eventFromEventPusher(
func() eventstore.Command {
e, _ := org.NewOIDCIDPChangedEvent(context.Background(),
&org.NewAggregate("org1").Aggregate,
"config1",
[]idp.OIDCIDPChanges{
idp.ChangeOIDCOptions(idp.OptionChanges{IsLinkingAllowed: gu.Ptr(false)}),
},
)
return e
}(),
),
),
),
},
args: args{
ctx: context.Background(),
userID: "user1",
resourceOwner: "org1",
links: []*domain.UserIDPLink{
{
ObjectRoot: models.ObjectRoot{
AggregateID: "user1",
},
IDPConfigID: "config1",
DisplayName: "name",
ExternalUserID: "externaluser1",
},
},
},
res: res{
err: caos_errs.ThrowPreconditionFailed(nil, "COMMAND-Sfee2", "Errors.ExternalIDP.LinkingNotAllowed"),
}, },
}, },
{ {
@ -235,6 +341,44 @@ func TestCommandSide_BulkAddUserIDPLinks(t *testing.T) {
true, true,
), ),
), ),
eventFromEventPusher(
org.NewIDPOIDCConfigAddedEvent(context.Background(),
&org.NewAggregate("org1").Aggregate,
"clientID",
"config1",
"issuer",
"authEndpoint",
"tokenEndpoint",
nil,
domain.OIDCMappingFieldUnspecified,
domain.OIDCMappingFieldUnspecified,
),
),
),
expectFilter(
eventFromEventPusher(
org.NewIDPConfigAddedEvent(context.Background(),
&org.NewAggregate("org1").Aggregate,
"config1",
"name",
domain.IDPConfigTypeOIDC,
domain.IDPConfigStylingTypeUnspecified,
true,
),
),
eventFromEventPusher(
org.NewIDPOIDCConfigAddedEvent(context.Background(),
&org.NewAggregate("org1").Aggregate,
"clientID",
"config1",
"issuer",
"authEndpoint",
"tokenEndpoint",
nil,
domain.OIDCMappingFieldUnspecified,
domain.OIDCMappingFieldUnspecified,
),
),
), ),
expectPush( expectPush(
[]*repository.Event{ []*repository.Event{
@ -290,11 +434,10 @@ func TestCommandSide_BulkAddUserIDPLinks(t *testing.T) {
), ),
), ),
), ),
expectFilter(),
expectFilter( expectFilter(
eventFromEventPusher( eventFromEventPusherWithInstanceID("instance1",
instance.NewIDPConfigAddedEvent(context.Background(), instance.NewIDPConfigAddedEvent(context.Background(),
&org.NewAggregate("org1").Aggregate, &instance.NewAggregate("instance1").Aggregate,
"config1", "config1",
"name", "name",
domain.IDPConfigTypeOIDC, domain.IDPConfigTypeOIDC,
@ -302,6 +445,44 @@ func TestCommandSide_BulkAddUserIDPLinks(t *testing.T) {
true, true,
), ),
), ),
eventFromEventPusherWithInstanceID("instance1",
instance.NewIDPOIDCConfigAddedEvent(context.Background(),
&instance.NewAggregate("instance1").Aggregate,
"clientID",
"config1",
"issuer",
"authEndpoint",
"tokenEndpoint",
nil,
domain.OIDCMappingFieldUnspecified,
domain.OIDCMappingFieldUnspecified,
),
),
),
expectFilter(
eventFromEventPusherWithInstanceID("instance1",
instance.NewIDPConfigAddedEvent(context.Background(),
&instance.NewAggregate("instance1").Aggregate,
"config1",
"name",
domain.IDPConfigTypeOIDC,
domain.IDPConfigStylingTypeUnspecified,
true,
),
),
eventFromEventPusherWithInstanceID("instance1",
instance.NewIDPOIDCConfigAddedEvent(context.Background(),
&instance.NewAggregate("instance1").Aggregate,
"clientID",
"config1",
"issuer",
"authEndpoint",
"tokenEndpoint",
nil,
domain.OIDCMappingFieldUnspecified,
domain.OIDCMappingFieldUnspecified,
),
),
), ),
expectPush( expectPush(
[]*repository.Event{ []*repository.Event{
@ -342,12 +523,7 @@ func TestCommandSide_BulkAddUserIDPLinks(t *testing.T) {
eventstore: tt.fields.eventstore, eventstore: tt.fields.eventstore,
} }
err := r.BulkAddedUserIDPLinks(tt.args.ctx, tt.args.userID, tt.args.resourceOwner, tt.args.links) err := r.BulkAddedUserIDPLinks(tt.args.ctx, tt.args.userID, tt.args.resourceOwner, tt.args.links)
if tt.res.err == nil { assert.ErrorIs(t, err, tt.res.err)
assert.NoError(t, err)
}
if tt.res.err != nil && !tt.res.err(err) {
t.Errorf("got wrong err: %v ", err)
}
}) })
} }
} }