feat(rt): IDP Intents Relational Table (#11374)

# Which Problems Are Solved

In the context of moving our datastore to relational tables, Identity
Provider Intents have no definition of a relational table nor any DB API
that can be used to store the IDP intents as relational objects.

# How the Problems Are Solved

The PR follows the guidelines left in #11190

- A table `zitadel.identity_provider_intents` is created: it defines its
relational constraints (foreign keys) with the other tables, as well as
an ENUM to represent the state of the intent.
- An IDP Intent repository has been created, which offers CRUD
operations implemented as `Create`, `Get`, `Update` and `Delete` methods
for the IDP intent.
- The repository also defines all columns and conditions useful for
performing DB operations on the IDP intents.
- DB mocks have been added as well to ease testing on the `domain`
package.
- Reduction functions have been implemented for the existing IDP events
so to keep the relational table in sync with the event store.

# Additional Changes

To allow testing LDAP intent flow, the `Session.FetchUser()` method has
been extracted to a separate file. A corresponding mock has been created
as well in `fetch_user_mock.go`. The files are mutually excluded and
added at build time through go build tags: the mock is added when the
`integration` tag is specified, while the real implementation is added
when the same tag IS NOT added to the build tags.

# Additional Context

- Closes #11190

---------

Co-authored-by: Livio Spring <[email protected]>
Co-authored-by: Silvan <[email protected]>
This commit is contained in:
Marco A.
2026-02-05 03:44:07 +00:00
committed by GitHub
co-authored by Livio Spring Silvan
parent ca9c7619c6
commit 4936bdf2c9
23 changed files with 4570 additions and 471 deletions
@@ -69,7 +69,7 @@ func TestMain(m *testing.M) {
CTX = integration.WithSystemAuthorization(ctx)
Instance = integration.NewInstance(CTX)
IAMCTX = Instance.WithAuthorization(ctx, integration.UserTypeIAMOwner)
IAMCTX = Instance.WithAuthorizationToken(ctx, integration.UserTypeIAMOwner)
SystemClient = integration.SystemClient()
OrgClient = Instance.Client.OrgV2beta
ProjectClient = Instance.Client.Projectv2Beta
@@ -145,17 +145,7 @@ func TestServer_TestIDProviderInstanceReduces(t *testing.T) {
name := gofakeit.Name()
before := time.Now()
addOIDC, err := AdminClient.AddOIDCIDP(IAMCTX, &admin.AddOIDCIDPRequest{
Name: name,
StylingType: idp_grpc.IDPStylingType_STYLING_TYPE_GOOGLE,
ClientId: "clientID",
ClientSecret: "clientSecret",
Issuer: "issuer",
Scopes: []string{"scope"},
DisplayNameMapping: idp.OIDCMappingField_OIDC_MAPPING_FIELD_EMAIL,
UsernameMapping: idp.OIDCMappingField_OIDC_MAPPING_FIELD_EMAIL,
AutoRegister: true,
})
addOIDC, err := AdminClient.AddOIDCIDP(IAMCTX, defaultOIDCIDReq(name, true))
after := time.Now()
require.NoError(t, err)
@@ -190,17 +180,7 @@ func TestServer_TestIDProviderInstanceReduces(t *testing.T) {
t.Run("test iam idp update reduces", func(t *testing.T) {
name := gofakeit.Name()
addOIDC, err := AdminClient.AddOIDCIDP(IAMCTX, &admin.AddOIDCIDPRequest{
Name: name,
StylingType: idp_grpc.IDPStylingType_STYLING_TYPE_GOOGLE,
ClientId: "clientID",
ClientSecret: "clientSecret",
Issuer: "issuer",
Scopes: []string{"scope"},
DisplayNameMapping: idp.OIDCMappingField_OIDC_MAPPING_FIELD_EMAIL,
UsernameMapping: idp.OIDCMappingField_OIDC_MAPPING_FIELD_EMAIL,
AutoRegister: true,
})
addOIDC, err := AdminClient.AddOIDCIDP(IAMCTX, defaultOIDCIDReq(name, true))
require.NoError(t, err)
name = "new_" + name
@@ -238,17 +218,7 @@ func TestServer_TestIDProviderInstanceReduces(t *testing.T) {
t.Run("test iam idp deactivate reduces", func(t *testing.T) {
name := gofakeit.Name()
addOIDC, err := AdminClient.AddOIDCIDP(IAMCTX, &admin.AddOIDCIDPRequest{
Name: name,
StylingType: idp_grpc.IDPStylingType_STYLING_TYPE_GOOGLE,
ClientId: "clientID",
ClientSecret: "clientSecret",
Issuer: "issuer",
Scopes: []string{"scope"},
DisplayNameMapping: idp.OIDCMappingField_OIDC_MAPPING_FIELD_EMAIL,
UsernameMapping: idp.OIDCMappingField_OIDC_MAPPING_FIELD_EMAIL,
AutoRegister: true,
})
addOIDC, err := AdminClient.AddOIDCIDP(IAMCTX, defaultOIDCIDReq(name, true))
require.NoError(t, err)
// deactivate idp
@@ -280,17 +250,7 @@ func TestServer_TestIDProviderInstanceReduces(t *testing.T) {
t.Run("test iam idp config reactivate reduces", func(t *testing.T) {
name := gofakeit.Name()
addOIDC, err := AdminClient.AddOIDCIDP(IAMCTX, &admin.AddOIDCIDPRequest{
Name: name,
StylingType: idp_grpc.IDPStylingType_STYLING_TYPE_GOOGLE,
ClientId: "clientID",
ClientSecret: "clientSecret",
Issuer: "issuer",
Scopes: []string{"scope"},
DisplayNameMapping: idp.OIDCMappingField_OIDC_MAPPING_FIELD_EMAIL,
UsernameMapping: idp.OIDCMappingField_OIDC_MAPPING_FIELD_EMAIL,
AutoRegister: true,
})
addOIDC, err := AdminClient.AddOIDCIDP(IAMCTX, defaultOIDCIDReq(name, true))
require.NoError(t, err)
idpRepo := repository.IDProviderRepository()
@@ -342,17 +302,7 @@ func TestServer_TestIDProviderInstanceReduces(t *testing.T) {
name := gofakeit.Name()
// add idp
addOIDC, err := AdminClient.AddOIDCIDP(IAMCTX, &admin.AddOIDCIDPRequest{
Name: name,
StylingType: idp_grpc.IDPStylingType_STYLING_TYPE_GOOGLE,
ClientId: "clientID",
ClientSecret: "clientSecret",
Issuer: "issuer",
Scopes: []string{"scope"},
DisplayNameMapping: idp.OIDCMappingField_OIDC_MAPPING_FIELD_EMAIL,
UsernameMapping: idp.OIDCMappingField_OIDC_MAPPING_FIELD_EMAIL,
AutoRegister: true,
})
addOIDC, err := AdminClient.AddOIDCIDP(IAMCTX, defaultOIDCIDReq(name, true))
require.NoError(t, err)
idpRepo := repository.IDProviderRepository()
@@ -380,17 +330,7 @@ func TestServer_TestIDProviderInstanceReduces(t *testing.T) {
name := gofakeit.Name()
// add oidc
addOIDC, err := AdminClient.AddOIDCIDP(IAMCTX, &admin.AddOIDCIDPRequest{
Name: name,
StylingType: idp_grpc.IDPStylingType_STYLING_TYPE_GOOGLE,
ClientId: "clientID",
ClientSecret: "clientSecret",
Issuer: "issuer",
Scopes: []string{"scope"},
DisplayNameMapping: idp.OIDCMappingField_OIDC_MAPPING_FIELD_EMAIL,
UsernameMapping: idp.OIDCMappingField_OIDC_MAPPING_FIELD_EMAIL,
AutoRegister: false,
})
addOIDC, err := AdminClient.AddOIDCIDP(IAMCTX, defaultOIDCIDReq(name, false))
require.NoError(t, err)
idpRepo := repository.IDProviderRepository()
@@ -427,17 +367,7 @@ func TestServer_TestIDProviderInstanceReduces(t *testing.T) {
name := gofakeit.Name()
// add oidc
addOIDC, err := AdminClient.AddOIDCIDP(IAMCTX, &admin.AddOIDCIDPRequest{
Name: name,
StylingType: idp_grpc.IDPStylingType_STYLING_TYPE_GOOGLE,
ClientId: "clientID",
ClientSecret: "clientSecret",
Issuer: "issuer",
Scopes: []string{"scope"},
DisplayNameMapping: idp.OIDCMappingField_OIDC_MAPPING_FIELD_EMAIL,
UsernameMapping: idp.OIDCMappingField_OIDC_MAPPING_FIELD_EMAIL,
AutoRegister: true,
})
addOIDC, err := AdminClient.AddOIDCIDP(IAMCTX, defaultOIDCIDReq(name, true))
require.NoError(t, err)
idpRepo := repository.IDProviderRepository()
@@ -1968,40 +1898,7 @@ func TestServer_TestIDProviderInstanceReduces(t *testing.T) {
// add ldap
before := time.Now()
addLdap, err := AdminClient.AddLDAPProvider(IAMCTX, &admin.AddLDAPProviderRequest{
Name: name,
Servers: []string{"servers"},
StartTls: true,
BaseDn: "baseDN",
BindDn: "bindND",
BindPassword: "bindPassword",
UserBase: "userBase",
UserObjectClasses: []string{"userOhjectClasses"},
UserFilters: []string{"userFilters"},
Timeout: durationpb.New(time.Minute),
Attributes: &idp_grpc.LDAPAttributes{
IdAttribute: "idAttribute",
FirstNameAttribute: "firstNameAttribute",
LastNameAttribute: "lastNameAttribute",
DisplayNameAttribute: "displayNameAttribute",
NickNameAttribute: "nickNameAttribute",
PreferredUsernameAttribute: "preferredUsernameAttribute",
EmailAttribute: "emailAttribute",
EmailVerifiedAttribute: "emailVerifiedAttribute",
PhoneAttribute: "phoneAttribute",
PhoneVerifiedAttribute: "phoneVerifiedAttribute",
PreferredLanguageAttribute: "preferredLanguageAttribute",
AvatarUrlAttribute: "avatarUrlAttribute",
ProfileAttribute: "profileAttribute",
},
ProviderOptions: &idp_grpc.Options{
IsLinkingAllowed: false,
IsCreationAllowed: false,
IsAutoCreation: false,
IsAutoUpdate: false,
AutoLinking: idp.AutoLinkingOption_AUTO_LINKING_OPTION_EMAIL,
},
})
addLdap, err := AdminClient.AddLDAPProvider(IAMCTX, defaultInstanceLDAPRequest(name))
after := time.Now()
require.NoError(t, err)
@@ -2056,40 +1953,7 @@ func TestServer_TestIDProviderInstanceReduces(t *testing.T) {
name := gofakeit.Name()
// add ldap
addLdap, err := AdminClient.AddLDAPProvider(IAMCTX, &admin.AddLDAPProviderRequest{
Name: name,
Servers: []string{"servers"},
StartTls: true,
BaseDn: "baseDN",
BindDn: "bindND",
BindPassword: "bindPassword",
UserBase: "userBase",
UserObjectClasses: []string{"userOhjectClasses"},
UserFilters: []string{"userFilters"},
Timeout: durationpb.New(time.Minute),
Attributes: &idp_grpc.LDAPAttributes{
IdAttribute: "idAttribute",
FirstNameAttribute: "firstNameAttribute",
LastNameAttribute: "lastNameAttribute",
DisplayNameAttribute: "displayNameAttribute",
NickNameAttribute: "nickNameAttribute",
PreferredUsernameAttribute: "preferredUsernameAttribute",
EmailAttribute: "emailAttribute",
EmailVerifiedAttribute: "emailVerifiedAttribute",
PhoneAttribute: "phoneAttribute",
PhoneVerifiedAttribute: "phoneVerifiedAttribute",
PreferredLanguageAttribute: "preferredLanguageAttribute",
AvatarUrlAttribute: "avatarUrlAttribute",
ProfileAttribute: "profileAttribute",
},
ProviderOptions: &idp_grpc.Options{
IsLinkingAllowed: false,
IsCreationAllowed: false,
IsAutoCreation: false,
IsAutoUpdate: false,
AutoLinking: idp.AutoLinkingOption_AUTO_LINKING_OPTION_EMAIL,
},
})
addLdap, err := AdminClient.AddLDAPProvider(IAMCTX, defaultInstanceLDAPRequest(name))
require.NoError(t, err)
idpRepo := repository.IDProviderRepository()
@@ -2328,25 +2192,7 @@ func TestServer_TestIDProviderInstanceReduces(t *testing.T) {
// add saml
before := time.Now()
addSAML, err := AdminClient.AddSAMLProvider(IAMCTX, &admin.AddSAMLProviderRequest{
Name: name,
Metadata: &admin.AddSAMLProviderRequest_MetadataXml{
MetadataXml: validSAMLMetadata1,
},
Binding: idp.SAMLBinding_SAML_BINDING_POST,
WithSignedRequest: false,
TransientMappingAttributeName: &name,
FederatedLogoutEnabled: &federatedLogoutEnabled,
NameIdFormat: idp.SAMLNameIDFormat_SAML_NAME_ID_FORMAT_TRANSIENT.Enum(),
ProviderOptions: &idp_grpc.Options{
IsLinkingAllowed: false,
IsCreationAllowed: false,
IsAutoCreation: false,
IsAutoUpdate: false,
AutoLinking: idp.AutoLinkingOption_AUTO_LINKING_OPTION_EMAIL,
},
SignatureAlgorithm: idp.SAMLSignatureAlgorithm_SAML_SIGNATURE_RSA_SHA1,
})
addSAML, err := AdminClient.AddSAMLProvider(IAMCTX, defaultInstanceSAMLRequest(name, &federatedLogoutEnabled))
after := time.Now()
require.NoError(t, err)
@@ -2389,25 +2235,7 @@ func TestServer_TestIDProviderInstanceReduces(t *testing.T) {
federatedLogoutEnabled := false
// add saml
addSAML, err := AdminClient.AddSAMLProvider(IAMCTX, &admin.AddSAMLProviderRequest{
Name: name,
Metadata: &admin.AddSAMLProviderRequest_MetadataXml{
MetadataXml: validSAMLMetadata1,
},
Binding: idp.SAMLBinding_SAML_BINDING_POST,
WithSignedRequest: false,
TransientMappingAttributeName: &name,
FederatedLogoutEnabled: &federatedLogoutEnabled,
NameIdFormat: idp.SAMLNameIDFormat_SAML_NAME_ID_FORMAT_TRANSIENT.Enum(),
ProviderOptions: &idp_grpc.Options{
IsLinkingAllowed: false,
IsCreationAllowed: false,
IsAutoCreation: false,
IsAutoUpdate: false,
AutoLinking: idp.AutoLinkingOption_AUTO_LINKING_OPTION_EMAIL,
},
SignatureAlgorithm: idp.SAMLSignatureAlgorithm_SAML_SIGNATURE_RSA_SHA1,
})
addSAML, err := AdminClient.AddSAMLProvider(IAMCTX, defaultInstanceSAMLRequest(name, &federatedLogoutEnabled))
require.NoError(t, err)
idpRepo := repository.IDProviderRepository()
@@ -2484,17 +2312,7 @@ func TestServer_TestIDProviderInstanceReduces(t *testing.T) {
name := gofakeit.Name()
// add idp
addOIDC, err := AdminClient.AddOIDCIDP(IAMCTX, &admin.AddOIDCIDPRequest{
Name: name,
StylingType: idp_grpc.IDPStylingType_STYLING_TYPE_GOOGLE,
ClientId: "clientID",
ClientSecret: "clientSecret",
Issuer: "issuer",
Scopes: []string{"scope"},
DisplayNameMapping: idp.OIDCMappingField_OIDC_MAPPING_FIELD_EMAIL,
UsernameMapping: idp.OIDCMappingField_OIDC_MAPPING_FIELD_EMAIL,
AutoRegister: true,
})
addOIDC, err := AdminClient.AddOIDCIDP(IAMCTX, defaultOIDCIDReq(name, true))
require.NoError(t, err)
idpRepo := repository.IDProviderRepository()
@@ -2528,3 +2346,76 @@ func TestServer_TestIDProviderInstanceReduces(t *testing.T) {
}, retryDuration, tick)
})
}
func defaultInstanceSAMLRequest(name string, federatedLogoutEnable *bool) *admin.AddSAMLProviderRequest {
return &admin.AddSAMLProviderRequest{
Name: name,
Metadata: &admin.AddSAMLProviderRequest_MetadataXml{
MetadataXml: validSAMLMetadata1,
},
Binding: idp.SAMLBinding_SAML_BINDING_POST,
WithSignedRequest: false,
TransientMappingAttributeName: &name,
FederatedLogoutEnabled: federatedLogoutEnable,
NameIdFormat: idp.SAMLNameIDFormat_SAML_NAME_ID_FORMAT_TRANSIENT.Enum(),
ProviderOptions: &idp_grpc.Options{
IsLinkingAllowed: false,
IsCreationAllowed: false,
IsAutoCreation: false,
IsAutoUpdate: false,
AutoLinking: idp.AutoLinkingOption_AUTO_LINKING_OPTION_EMAIL,
},
SignatureAlgorithm: idp.SAMLSignatureAlgorithm_SAML_SIGNATURE_RSA_SHA1,
}
}
func defaultOIDCIDReq(name string, autoRegister bool) *admin.AddOIDCIDPRequest {
return &admin.AddOIDCIDPRequest{
Name: name,
StylingType: idp_grpc.IDPStylingType_STYLING_TYPE_GOOGLE,
ClientId: "clientID",
ClientSecret: "clientSecret",
Issuer: "issuer",
Scopes: []string{"scope"},
DisplayNameMapping: idp.OIDCMappingField_OIDC_MAPPING_FIELD_EMAIL,
UsernameMapping: idp.OIDCMappingField_OIDC_MAPPING_FIELD_EMAIL,
AutoRegister: autoRegister,
}
}
func defaultInstanceLDAPRequest(name string) *admin.AddLDAPProviderRequest {
return &admin.AddLDAPProviderRequest{
Name: name,
Servers: []string{"servers"},
StartTls: true,
BaseDn: "baseDN",
BindDn: "bindND",
BindPassword: "bindPassword",
UserBase: "userBase",
UserObjectClasses: []string{"userOhjectClasses"},
UserFilters: []string{"userFilters"},
Timeout: durationpb.New(time.Minute),
Attributes: &idp_grpc.LDAPAttributes{
IdAttribute: "idAttribute",
FirstNameAttribute: "firstNameAttribute",
LastNameAttribute: "lastNameAttribute",
DisplayNameAttribute: "displayNameAttribute",
NickNameAttribute: "nickNameAttribute",
PreferredUsernameAttribute: "preferredUsernameAttribute",
EmailAttribute: "emailAttribute",
EmailVerifiedAttribute: "emailVerifiedAttribute",
PhoneAttribute: "phoneAttribute",
PhoneVerifiedAttribute: "phoneVerifiedAttribute",
PreferredLanguageAttribute: "preferredLanguageAttribute",
AvatarUrlAttribute: "avatarUrlAttribute",
ProfileAttribute: "profileAttribute",
},
ProviderOptions: &idp_grpc.Options{
IsLinkingAllowed: false,
IsCreationAllowed: false,
IsAutoCreation: false,
IsAutoUpdate: false,
AutoLinking: idp.AutoLinkingOption_AUTO_LINKING_OPTION_EMAIL,
},
}
}
@@ -1852,40 +1852,7 @@ func TestServer_TestIDProviderOrgReduces(t *testing.T) {
// add ldap
before := time.Now()
addLdap, err := MgmtClient.AddLDAPProvider(IAMCTX, &management.AddLDAPProviderRequest{
Name: name,
Servers: []string{"servers"},
StartTls: true,
BaseDn: "baseDN",
BindDn: "bindND",
BindPassword: "bindPassword",
UserBase: "userBase",
UserObjectClasses: []string{"userOhjectClasses"},
UserFilters: []string{"userFilters"},
Timeout: durationpb.New(time.Minute),
Attributes: &idp_grpc.LDAPAttributes{
IdAttribute: "idAttribute",
FirstNameAttribute: "firstNameAttribute",
LastNameAttribute: "lastNameAttribute",
DisplayNameAttribute: "displayNameAttribute",
NickNameAttribute: "nickNameAttribute",
PreferredUsernameAttribute: "preferredUsernameAttribute",
EmailAttribute: "emailAttribute",
EmailVerifiedAttribute: "emailVerifiedAttribute",
PhoneAttribute: "phoneAttribute",
PhoneVerifiedAttribute: "phoneVerifiedAttribute",
PreferredLanguageAttribute: "preferredLanguageAttribute",
AvatarUrlAttribute: "avatarUrlAttribute",
ProfileAttribute: "profileAttribute",
},
ProviderOptions: &idp_grpc.Options{
IsLinkingAllowed: false,
IsCreationAllowed: false,
IsAutoCreation: false,
IsAutoUpdate: false,
AutoLinking: idp.AutoLinkingOption_AUTO_LINKING_OPTION_EMAIL,
},
})
addLdap, err := MgmtClient.AddLDAPProvider(IAMCTX, defaultOrganizationLDAPRequest(name))
after := time.Now()
require.NoError(t, err)
@@ -1940,40 +1907,7 @@ func TestServer_TestIDProviderOrgReduces(t *testing.T) {
name := gofakeit.Name()
// add ldap
addLdap, err := MgmtClient.AddLDAPProvider(IAMCTX, &management.AddLDAPProviderRequest{
Name: name,
Servers: []string{"servers"},
StartTls: true,
BaseDn: "baseDN",
BindDn: "bindND",
BindPassword: "bindPassword",
UserBase: "userBase",
UserObjectClasses: []string{"userOhjectClasses"},
UserFilters: []string{"userFilters"},
Timeout: durationpb.New(time.Minute),
Attributes: &idp_grpc.LDAPAttributes{
IdAttribute: "idAttribute",
FirstNameAttribute: "firstNameAttribute",
LastNameAttribute: "lastNameAttribute",
DisplayNameAttribute: "displayNameAttribute",
NickNameAttribute: "nickNameAttribute",
PreferredUsernameAttribute: "preferredUsernameAttribute",
EmailAttribute: "emailAttribute",
EmailVerifiedAttribute: "emailVerifiedAttribute",
PhoneAttribute: "phoneAttribute",
PhoneVerifiedAttribute: "phoneVerifiedAttribute",
PreferredLanguageAttribute: "preferredLanguageAttribute",
AvatarUrlAttribute: "avatarUrlAttribute",
ProfileAttribute: "profileAttribute",
},
ProviderOptions: &idp_grpc.Options{
IsLinkingAllowed: false,
IsCreationAllowed: false,
IsAutoCreation: false,
IsAutoUpdate: false,
AutoLinking: idp.AutoLinkingOption_AUTO_LINKING_OPTION_EMAIL,
},
})
addLdap, err := MgmtClient.AddLDAPProvider(IAMCTX, defaultOrganizationLDAPRequest(name))
require.NoError(t, err)
idpRepo := repository.IDProviderRepository()
@@ -2412,3 +2346,40 @@ func TestServer_TestIDProviderOrgReduces(t *testing.T) {
}, retryDuration, tick)
})
}
func defaultOrganizationLDAPRequest(providerName string) *management.AddLDAPProviderRequest {
return &management.AddLDAPProviderRequest{
Name: providerName,
Servers: []string{"servers"},
StartTls: true,
BaseDn: "baseDN",
BindDn: "bindND",
BindPassword: "bindPassword",
UserBase: "userBase",
UserObjectClasses: []string{"userOhjectClasses"},
UserFilters: []string{"userFilters"},
Timeout: durationpb.New(time.Minute),
Attributes: &idp_grpc.LDAPAttributes{
IdAttribute: "idAttribute",
FirstNameAttribute: "firstNameAttribute",
LastNameAttribute: "lastNameAttribute",
DisplayNameAttribute: "displayNameAttribute",
NickNameAttribute: "nickNameAttribute",
PreferredUsernameAttribute: "preferredUsernameAttribute",
EmailAttribute: "emailAttribute",
EmailVerifiedAttribute: "emailVerifiedAttribute",
PhoneAttribute: "phoneAttribute",
PhoneVerifiedAttribute: "phoneVerifiedAttribute",
PreferredLanguageAttribute: "preferredLanguageAttribute",
AvatarUrlAttribute: "avatarUrlAttribute",
ProfileAttribute: "profileAttribute",
},
ProviderOptions: &idp_grpc.Options{
IsLinkingAllowed: false,
IsCreationAllowed: false,
IsAutoCreation: false,
IsAutoUpdate: false,
AutoLinking: idp.AutoLinkingOption_AUTO_LINKING_OPTION_EMAIL,
},
}
}
@@ -0,0 +1,396 @@
//go:build integration
package events_test
// TODO(adlerhurst): Uncomment once users table is created and FK can be enforced
// import (
// "net"
// "net/url"
// "testing"
// "time"
// "github.com/brianvoe/gofakeit/v6"
// "github.com/muhlemmer/gu"
// "github.com/stretchr/testify/assert"
// "github.com/stretchr/testify/require"
// durationpb "google.golang.org/protobuf/types/known/durationpb"
// "github.com/zitadel/zitadel/backend/v3/domain"
// "github.com/zitadel/zitadel/backend/v3/storage/database"
// "github.com/zitadel/zitadel/backend/v3/storage/database/repository"
// "github.com/zitadel/zitadel/internal/idp/providers/ldap"
// "github.com/zitadel/zitadel/internal/integration"
// "github.com/zitadel/zitadel/internal/integration/sink"
// "github.com/zitadel/zitadel/pkg/grpc/admin"
// "github.com/zitadel/zitadel/pkg/grpc/session/v2"
// "github.com/zitadel/zitadel/pkg/grpc/user/v2"
// )
// func TestServer_IDPIntentReduces(t *testing.T) {
// retryDuration, tick := integration.WaitForAndTickWithMaxDuration(IAMCTX, time.Minute)
// idpIntentRepo := repository.IDPIntentRepository()
// instanceID := Instance.ID()
// t.Run("start LDAP ID provider intent should create intent and succeed", func(t *testing.T) {
// ldapProvider, err := AdminClient.AddLDAPProvider(IAMCTX, defaultInstanceLDAPRequest(gofakeit.Name()))
// require.NoError(t, err)
// req := &user.StartIdentityProviderIntentRequest{
// IdpId: ldapProvider.GetId(),
// Content: &user.StartIdentityProviderIntentRequest_Ldap{
// Ldap: &user.LDAPCredentials{
// Username: "some-user",
// Password: "some-pass",
// },
// },
// }
// res, err := UserClient.StartIdentityProviderIntent(IAMCTX, req)
// require.NoError(t, err)
// idpIntent, ok := res.GetNextStep().(*user.StartIdentityProviderIntentResponse_IdpIntent)
// require.True(t, ok)
// t.Cleanup(func() {
// idpIntentRepo.Delete(IAMCTX, pool, idpIntentRepo.PrimaryKeyCondition(instanceID, idpIntent.IdpIntent.GetIdpIntentId()))
// AdminClient.RemoveIDP(IAMCTX, &admin.RemoveIDPRequest{IdpId: ldapProvider.GetId()})
// })
// require.EventuallyWithT(t, func(collect *assert.CollectT) {
// retrievedRelationalIntent, err := idpIntentRepo.Get(
// IAMCTX,
// pool,
// database.WithCondition(database.And(
// idpIntentRepo.PrimaryKeyCondition(instanceID, idpIntent.IdpIntent.GetIdpIntentId()),
// idpIntentRepo.StateCondition(domain.IDPIntentStateSucceeded),
// )),
// )
// require.NoError(collect, err)
// assert.Equal(collect, domain.IDPIntentStateSucceeded, retrievedRelationalIntent.State)
// assert.Empty(collect, retrievedRelationalIntent.SuccessURL)
// assert.Empty(collect, retrievedRelationalIntent.FailureURL)
// assert.Equal(collect, ldapProvider.GetId(), retrievedRelationalIntent.IDPID)
// assert.Nil(collect, retrievedRelationalIntent.IDPArguments)
// assert.NotEmpty(collect, retrievedRelationalIntent.IDPUser)
// assert.NotEmpty(collect, retrievedRelationalIntent.IDPUserID)
// assert.NotEmpty(collect, retrievedRelationalIntent.EntryAttributes)
// assert.True(collect, retrievedRelationalIntent.ExpiresAt.IsZero())
// }, retryDuration, tick)
// })
// t.Run("oidc intent flow started with URLs should create intent in started state", func(t *testing.T) {
// idpCreateReq := defaultOIDCIDReq(gofakeit.Name(), true)
// idpCreateReq.Issuer = "http://localhost:8082"
// oidcIDP, err := AdminClient.AddOIDCIDP(IAMCTX, idpCreateReq)
// require.NoError(t, err)
// req := &user.StartIdentityProviderIntentRequest{
// IdpId: oidcIDP.GetIdpId(),
// Content: &user.StartIdentityProviderIntentRequest_Urls{
// Urls: &user.RedirectURLs{
// SuccessUrl: "https://localhost:8081/success",
// FailureUrl: "https://localhost:8081/fail",
// },
// },
// }
// res, err := UserClient.StartIdentityProviderIntent(IAMCTX, req)
// require.NoError(t, err)
// authURL, ok := res.GetNextStep().(*user.StartIdentityProviderIntentResponse_AuthUrl)
// require.True(t, ok)
// parsedAuthURL, err := url.Parse(authURL.AuthUrl)
// require.NoError(t, err)
// idpIntentID := parsedAuthURL.Query().Get("state")
// t.Cleanup(func() {
// idpIntentRepo.Delete(IAMCTX, pool, idpIntentRepo.PrimaryKeyCondition(instanceID, idpIntentID))
// AdminClient.RemoveIDP(IAMCTX, &admin.RemoveIDPRequest{IdpId: oidcIDP.GetIdpId()})
// })
// require.EventuallyWithT(t, func(collect *assert.CollectT) {
// retrievedRelationalIntent, err := idpIntentRepo.Get(
// IAMCTX,
// pool,
// database.WithCondition(idpIntentRepo.PrimaryKeyCondition(instanceID, idpIntentID)),
// )
// require.NoError(collect, err)
// assert.Equal(collect, domain.IDPIntentStateStarted, retrievedRelationalIntent.State)
// assert.Equal(collect, "https://localhost:8081/success", retrievedRelationalIntent.SuccessURL.String())
// assert.Equal(collect, "https://localhost:8081/fail", retrievedRelationalIntent.FailureURL.String())
// assert.Empty(collect, retrievedRelationalIntent.IDPArguments)
// }, retryDuration, tick)
// })
// t.Run("when successful oidc intent should update intent state to succeeded", func(t *testing.T) {
// beforeCreate := time.Now()
// idpCreateReq := defaultOIDCIDReq(gofakeit.Name(), true)
// idpCreateReq.Issuer = "http://localhost:8082"
// oidcIDP, err := AdminClient.AddOIDCIDP(IAMCTX, idpCreateReq)
// require.NoError(t, err)
// expiryDate := time.Now().Add(time.Minute * 30)
// idpIntentID, _, _, _, err := sink.SuccessfulOIDCIntent(instanceID, oidcIDP.GetIdpId(), "some-idp-user", "some-user", expiryDate)
// require.NoError(t, err)
// afterSuccess := time.Now()
// t.Cleanup(func() {
// idpIntentRepo.Delete(IAMCTX, pool, idpIntentRepo.PrimaryKeyCondition(instanceID, idpIntentID))
// AdminClient.RemoveIDP(IAMCTX, &admin.RemoveIDPRequest{IdpId: oidcIDP.GetIdpId()})
// })
// require.EventuallyWithT(t, func(collect *assert.CollectT) {
// retrievedRelationalIntent, err := idpIntentRepo.Get(
// IAMCTX,
// pool,
// database.WithCondition(idpIntentRepo.PrimaryKeyCondition(instanceID, idpIntentID)),
// )
// require.NoError(collect, err)
// assert.Equal(collect, domain.IDPIntentStateSucceeded, retrievedRelationalIntent.State)
// assert.NotEmpty(collect, retrievedRelationalIntent.IDPUser)
// assert.Equal(collect, "some-idp-user", retrievedRelationalIntent.IDPUserID)
// assert.Equal(collect, "username", retrievedRelationalIntent.IDPUsername)
// assert.Equal(collect, "some-user", retrievedRelationalIntent.UserID)
// assert.NotEmpty(collect, retrievedRelationalIntent.IDPAccessToken)
// assert.Equal(collect, "idToken", retrievedRelationalIntent.IDPIDToken)
// require.NotNil(collect, retrievedRelationalIntent.SucceededAt)
// assert.WithinRange(collect, *retrievedRelationalIntent.SucceededAt, beforeCreate, afterSuccess)
// require.NotNil(collect, retrievedRelationalIntent.ExpiresAt)
// assert.WithinRange(collect, *retrievedRelationalIntent.ExpiresAt, expiryDate.Add(time.Millisecond*-5), expiryDate.Add(time.Second*1))
// }, retryDuration, tick)
// })
// t.Run("when successful SAML intent should update intent state to succeeded", func(t *testing.T) {
// beforeCreate := time.Now()
// samlIDP, err := AdminClient.AddSAMLProvider(IAMCTX, defaultInstanceSAMLRequest(gofakeit.Name(), gu.Ptr(true)))
// require.NoError(t, err)
// expiryDate := time.Now().Add(time.Minute * 30)
// idpIntentID, _, _, _, err := sink.SuccessfulSAMLIntent(instanceID, samlIDP.GetId(), "some-idp-user", "some-user", "", expiryDate)
// require.NoError(t, err)
// afterSuccess := time.Now()
// t.Cleanup(func() {
// idpIntentRepo.Delete(IAMCTX, pool, idpIntentRepo.PrimaryKeyCondition(instanceID, idpIntentID))
// AdminClient.RemoveIDP(IAMCTX, &admin.RemoveIDPRequest{IdpId: samlIDP.GetId()})
// })
// require.EventuallyWithT(t, func(collect *assert.CollectT) {
// retrievedRelationalIntent, err := idpIntentRepo.Get(
// IAMCTX,
// pool,
// database.WithCondition(idpIntentRepo.PrimaryKeyCondition(instanceID, idpIntentID)),
// )
// require.NoError(collect, err)
// assert.Equal(collect, domain.IDPIntentStateSucceeded, retrievedRelationalIntent.State)
// assert.NotEmpty(collect, retrievedRelationalIntent.IDPUser)
// assert.Equal(collect, "some-idp-user", retrievedRelationalIntent.IDPUserID)
// assert.Empty(collect, retrievedRelationalIntent.IDPUsername)
// assert.Equal(collect, "some-user", retrievedRelationalIntent.UserID)
// assert.NotEmpty(collect, retrievedRelationalIntent.Assertion)
// require.NotNil(collect, retrievedRelationalIntent.SucceededAt)
// assert.WithinRange(collect, *retrievedRelationalIntent.SucceededAt, beforeCreate, afterSuccess)
// require.NotNil(collect, retrievedRelationalIntent.ExpiresAt)
// assert.WithinRange(collect, *retrievedRelationalIntent.ExpiresAt, expiryDate.Add(time.Millisecond*-5), expiryDate.Add(time.Second*1))
// }, retryDuration, tick)
// })
// t.Run("when emitting SAMLRequest event should update intent with request ID", func(t *testing.T) {
// samlIDP, err := AdminClient.AddSAMLProvider(IAMCTX, defaultInstanceSAMLRequest(gofakeit.Name(), gu.Ptr(true)))
// require.NoError(t, err)
// expiry := time.Now().Add(time.Hour * 1)
// req := &user.StartIdentityProviderIntentRequest{
// IdpId: samlIDP.GetId(),
// Content: &user.StartIdentityProviderIntentRequest_Urls{
// Urls: &user.RedirectURLs{
// SuccessUrl: "https://localhost:8081/success",
// FailureUrl: "https://localhost:8081/fail",
// },
// },
// }
// res, err := UserClient.StartIdentityProviderIntent(IAMCTX, req)
// require.NoError(t, err)
// formData, ok := res.GetNextStep().(*user.StartIdentityProviderIntentResponse_FormData)
// require.True(t, ok)
// idpIntentID, ok := formData.FormData.GetFields()["RelayState"]
// require.True(t, ok)
// t.Cleanup(func() {
// idpIntentRepo.Delete(IAMCTX, pool, idpIntentRepo.PrimaryKeyCondition(instanceID, idpIntentID))
// AdminClient.RemoveIDP(IAMCTX, &admin.RemoveIDPRequest{IdpId: samlIDP.GetId()})
// })
// idpIntentID, token, _, _, err := sink.SuccessfulSAMLIntent(instanceID, samlIDP.GetId(), "idp-user-id", "some-user", idpIntentID, expiry)
// require.NoError(t, err)
// _, err = UserClient.RetrieveIdentityProviderIntent(IAMCTX, &user.RetrieveIdentityProviderIntentRequest{
// IdpIntentId: idpIntentID,
// IdpIntentToken: token,
// })
// require.NoError(t, err)
// require.EventuallyWithT(t, func(collect *assert.CollectT) {
// retrievedRelationalIntent, err := idpIntentRepo.Get(
// IAMCTX,
// pool,
// database.WithCondition(database.And(
// idpIntentRepo.PrimaryKeyCondition(instanceID, idpIntentID),
// )),
// )
// require.NoError(collect, err)
// assert.NotEmpty(collect, retrievedRelationalIntent.RequestID)
// }, retryDuration, tick)
// })
// t.Run("when LDAP intent flow fails should update intent state and reason", func(t *testing.T) {
// beforeCreate := time.Now()
// ldapProvider, err := AdminClient.AddLDAPProvider(IAMCTX, defaultInstanceLDAPRequest(gofakeit.Name()))
// require.NoError(t, err)
// req := &user.StartIdentityProviderIntentRequest{
// IdpId: ldapProvider.GetId(),
// Content: &user.StartIdentityProviderIntentRequest_Ldap{
// Ldap: &user.LDAPCredentials{
// Username: ldap.FailingUser,
// Password: ldap.FailingPsw,
// },
// },
// }
// _, err = UserClient.StartIdentityProviderIntent(IAMCTX, req)
// require.Error(t, err)
// afterFail := time.Now()
// var idpIntentID string
// t.Cleanup(func() {
// idpIntentRepo.Delete(IAMCTX, pool, idpIntentRepo.PrimaryKeyCondition(instanceID, idpIntentID))
// AdminClient.RemoveIDP(IAMCTX, &admin.RemoveIDPRequest{IdpId: ldapProvider.GetId()})
// })
// require.EventuallyWithT(t, func(collect *assert.CollectT) {
// retrievedRelationalIntent, err := idpIntentRepo.Get(
// IAMCTX,
// pool,
// database.WithCondition(database.And(
// idpIntentRepo.InstanceIDCondition(instanceID),
// idpIntentRepo.StateCondition(domain.IDPIntentStateFailed),
// )),
// database.WithOrderByDescending(idpIntentRepo.CreatedAtColumn()),
// )
// require.NoError(collect, err)
// assert.Equal(collect, domain.IDPIntentStateFailed, retrievedRelationalIntent.State)
// assert.NotEmpty(collect, retrievedRelationalIntent.FailReason)
// require.NotNil(collect, retrievedRelationalIntent.FailedAt)
// assert.WithinRange(collect, *retrievedRelationalIntent.FailedAt, beforeCreate, afterFail)
// idpIntentID = retrievedRelationalIntent.ID
// }, retryDuration, tick)
// })
// t.Run("when session update checks intent should delete intent", func(t *testing.T) {
// // ==========
// // GIVEN
// // ==========
// // Create a user
// email := integration.Email()
// testUser := Instance.CreateUserTypeHuman(IAMCTX, email)
// _, err := UserClient.VerifyEmail(IAMCTX, &user.VerifyEmailRequest{
// UserId: testUser.GetId(),
// VerificationCode: testUser.GetEmailCode(),
// })
// require.NoError(t, err)
// _, err = UserClient.SetPassword(CTX, &user.SetPasswordRequest{
// UserId: testUser.GetId(),
// NewPassword: &user.Password{
// Password: integration.UserPassword,
// },
// Verification: nil,
// })
// require.NoError(t, err)
// // Create an ID Provider
// idpID := Instance.AddGenericOAuthProvider(IAMCTX, integration.IDPName()).GetId()
// // Link the user with the provider
// idpUserID := integration.ID()
// _, err = UserClient.AddIDPLink(IAMCTX, &user.AddIDPLinkRequest{
// UserId: testUser.GetId(),
// IdpLink: &user.IDPLink{
// IdpId: idpID,
// UserId: idpUserID,
// UserName: integration.Username(),
// },
// })
// require.NoError(t, err)
// // Create an IDP intent
// _, err = url.Parse(Instance.CreateIntent(CTX, idpID).GetAuthUrl())
// require.NoError(t, err)
// expiry := time.Now().Add(1 * time.Hour)
// // Fake a successful intent flow
// intentID, intentToken, _, _, err := sink.SuccessfulOAuthIntent(Instance.ID(), idpID, idpUserID, testUser.GetId(), expiry)
// require.NoError(t, err)
// // Create a session for the user
// createdSessionID := createSessionForUser(t)
// require.NoError(t, err)
// // ==========
// // TEST
// // ==========
// // Update the session with user, password and IPDIntent checks
// _, err = SessionClient.SetSession(IAMCTX, &session.SetSessionRequest{
// SessionId: createdSessionID,
// Checks: &session.Checks{
// User: &session.CheckUser{
// Search: &session.CheckUser_LoginName{
// LoginName: email,
// },
// },
// Password: &session.CheckPassword{
// Password: integration.UserPassword,
// },
// IdpIntent: &session.CheckIDPIntent{
// IdpIntentId: intentID,
// IdpIntentToken: intentToken,
// },
// },
// })
// require.NoError(t, err)
// // ==========
// // VERIFY
// // ==========
// t.Cleanup(func() {
// idpIntentRepo.Delete(IAMCTX, pool, idpIntentRepo.PrimaryKeyCondition(instanceID, intentID))
// AdminClient.RemoveIDP(IAMCTX, &admin.RemoveIDPRequest{IdpId: idpID})
// SessionClient.DeleteSession(IAMCTX, &session.DeleteSessionRequest{SessionId: createdSessionID})
// })
// require.EventuallyWithT(t, func(collect *assert.CollectT) {
// _, err := idpIntentRepo.Get(
// IAMCTX,
// pool,
// database.WithCondition(idpIntentRepo.PrimaryKeyCondition(instanceID, intentID)),
// )
// assert.Error(collect, err)
// }, retryDuration, tick)
// })
// }
// func createSessionForUser(t *testing.T) (sessionID string) {
// t.Helper()
// lifetime := time.Hour
// createdSession, err := SessionClient.CreateSession(CTX, &session.CreateSessionRequest{
// Checks: nil,
// Metadata: nil,
// Challenges: nil,
// UserAgent: &session.UserAgent{
// FingerprintId: gu.Ptr(integration.ID()),
// Ip: gu.Ptr(net.IPv4(127, 0, 0, 1).String()),
// Description: gu.Ptr("description"),
// Header: map[string]*session.UserAgent_HeaderValues{
// "User-Agent": {Values: []string{"ZITADEL-Integration-Test"}},
// },
// },
// Lifetime: durationpb.New(lifetime),
// })
// require.NoError(t, err)
// return createdSession.GetSessionId()
// }