mirror of
https://github.com/andwati/zitadel.git
synced 2026-11-28 15:08:51 +00:00
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:
co-authored by
Livio Spring
Silvan
parent
ca9c7619c6
commit
4936bdf2c9
@@ -28,19 +28,7 @@ func TestCreateIDProvider(t *testing.T) {
|
||||
}()
|
||||
|
||||
// create instance
|
||||
instanceId := gofakeit.Name()
|
||||
instance := domain.Instance{
|
||||
ID: instanceId,
|
||||
Name: gofakeit.Name(),
|
||||
DefaultOrgID: "defaultOrgId",
|
||||
IAMProjectID: "iamProject",
|
||||
ConsoleClientID: "managementConsoleCLient",
|
||||
ConsoleAppID: "managementConsoleApp",
|
||||
DefaultLanguage: "defaultLanguage",
|
||||
}
|
||||
instanceRepo := repository.InstanceRepository()
|
||||
err = instanceRepo.Create(t.Context(), tx, &instance)
|
||||
require.NoError(t, err)
|
||||
instanceId := createInstance(t, tx)
|
||||
|
||||
// create org
|
||||
orgId := gofakeit.Name()
|
||||
@@ -61,7 +49,6 @@ func TestCreateIDProvider(t *testing.T) {
|
||||
err error
|
||||
}
|
||||
|
||||
// TESTS
|
||||
tests := []test{
|
||||
{
|
||||
name: "happy path",
|
||||
@@ -83,11 +70,10 @@ func TestCreateIDProvider(t *testing.T) {
|
||||
{
|
||||
name: "create idp without name",
|
||||
idp: domain.IdentityProvider{
|
||||
InstanceID: instanceId,
|
||||
OrgID: &orgId,
|
||||
ID: gofakeit.Name(),
|
||||
State: domain.IDPStateActive,
|
||||
// Name: gofakeit.Name(),
|
||||
InstanceID: instanceId,
|
||||
OrgID: &orgId,
|
||||
ID: gofakeit.Name(),
|
||||
State: domain.IDPStateActive,
|
||||
Type: gu.Ptr(domain.IDPTypeOIDC),
|
||||
AllowCreation: true,
|
||||
AllowAutoCreation: true,
|
||||
@@ -231,9 +217,8 @@ func TestCreateIDProvider(t *testing.T) {
|
||||
{
|
||||
name: "adding idp with no id",
|
||||
idp: domain.IdentityProvider{
|
||||
InstanceID: instanceId,
|
||||
OrgID: &orgId,
|
||||
// ID: gofakeit.Name(),
|
||||
InstanceID: instanceId,
|
||||
OrgID: &orgId,
|
||||
State: domain.IDPStateActive,
|
||||
Name: gofakeit.Name(),
|
||||
Type: gu.Ptr(domain.IDPTypeOIDC),
|
||||
@@ -249,11 +234,10 @@ func TestCreateIDProvider(t *testing.T) {
|
||||
{
|
||||
name: "adding idp with no name",
|
||||
idp: domain.IdentityProvider{
|
||||
InstanceID: instanceId,
|
||||
OrgID: &orgId,
|
||||
ID: gofakeit.Name(),
|
||||
State: domain.IDPStateActive,
|
||||
// Name: gofakeit.Name(),
|
||||
InstanceID: instanceId,
|
||||
OrgID: &orgId,
|
||||
ID: gofakeit.Name(),
|
||||
State: domain.IDPStateActive,
|
||||
Type: gu.Ptr(domain.IDPTypeOIDC),
|
||||
AllowCreation: true,
|
||||
AllowAutoCreation: true,
|
||||
@@ -267,7 +251,6 @@ func TestCreateIDProvider(t *testing.T) {
|
||||
{
|
||||
name: "adding idp with no instance id",
|
||||
idp: domain.IdentityProvider{
|
||||
// InstanceID: instanceId,
|
||||
OrgID: &orgId,
|
||||
State: domain.IDPStateActive,
|
||||
Name: gofakeit.Name(),
|
||||
@@ -384,31 +367,10 @@ func TestUpdateIDProvider(t *testing.T) {
|
||||
}()
|
||||
|
||||
// create instance
|
||||
instanceId := gofakeit.Name()
|
||||
instance := domain.Instance{
|
||||
ID: instanceId,
|
||||
Name: gofakeit.Name(),
|
||||
DefaultOrgID: "defaultOrgId",
|
||||
IAMProjectID: "iamProject",
|
||||
ConsoleClientID: "managementConsoleCLient",
|
||||
ConsoleAppID: "managementConsoleApp",
|
||||
DefaultLanguage: "defaultLanguage",
|
||||
}
|
||||
instanceRepo := repository.InstanceRepository()
|
||||
err = instanceRepo.Create(t.Context(), tx, &instance)
|
||||
require.NoError(t, err)
|
||||
instanceId := createInstance(t, tx)
|
||||
|
||||
// create org
|
||||
orgId := gofakeit.Name()
|
||||
org := domain.Organization{
|
||||
ID: orgId,
|
||||
Name: gofakeit.Name(),
|
||||
InstanceID: instanceId,
|
||||
State: domain.OrgStateActive,
|
||||
}
|
||||
organizationRepo := repository.OrganizationRepository()
|
||||
err = organizationRepo.Create(t.Context(), tx, &org)
|
||||
require.NoError(t, err)
|
||||
orgId := createOrganization(t, tx, instanceId)
|
||||
|
||||
idpRepo := repository.IDProviderRepository()
|
||||
|
||||
@@ -669,44 +631,12 @@ func TestGetIDProvider(t *testing.T) {
|
||||
}
|
||||
}()
|
||||
|
||||
// create instance
|
||||
instanceId := gofakeit.Name()
|
||||
instance := domain.Instance{
|
||||
ID: instanceId,
|
||||
Name: gofakeit.Name(),
|
||||
DefaultOrgID: "defaultOrgId",
|
||||
IAMProjectID: "iamProject",
|
||||
ConsoleClientID: "managementConsoleCLient",
|
||||
ConsoleAppID: "managementConsoleApp",
|
||||
DefaultLanguage: "defaultLanguage",
|
||||
}
|
||||
instanceRepo := repository.InstanceRepository()
|
||||
err = instanceRepo.Create(t.Context(), tx, &instance)
|
||||
require.NoError(t, err)
|
||||
instanceId := createInstance(t, tx)
|
||||
orgId := createOrganization(t, tx, instanceId)
|
||||
|
||||
// create org
|
||||
orgId := gofakeit.Name()
|
||||
org := domain.Organization{
|
||||
ID: orgId,
|
||||
Name: gofakeit.Name(),
|
||||
InstanceID: instanceId,
|
||||
State: domain.OrgStateActive,
|
||||
}
|
||||
organizationRepo := repository.OrganizationRepository()
|
||||
err = organizationRepo.Create(t.Context(), tx, &org)
|
||||
require.NoError(t, err)
|
||||
|
||||
// create organization
|
||||
// this org is created as an additional org which should NOT
|
||||
// be returned in the results of the tests
|
||||
preexistingOrg := domain.Organization{
|
||||
ID: gofakeit.Name(),
|
||||
Name: gofakeit.Name(),
|
||||
InstanceID: instanceId,
|
||||
State: domain.OrgStateActive,
|
||||
}
|
||||
err = organizationRepo.Create(t.Context(), tx, &preexistingOrg)
|
||||
require.NoError(t, err)
|
||||
createOrganization(t, tx, instanceId)
|
||||
|
||||
idpRepo := repository.IDProviderRepository()
|
||||
type test struct {
|
||||
@@ -955,31 +885,10 @@ func TestListIDProvider(t *testing.T) {
|
||||
}()
|
||||
|
||||
// create instance
|
||||
instanceId := gofakeit.Name()
|
||||
instance := domain.Instance{
|
||||
ID: instanceId,
|
||||
Name: gofakeit.Name(),
|
||||
DefaultOrgID: "defaultOrgId",
|
||||
IAMProjectID: "iamProject",
|
||||
ConsoleClientID: "managementConsoleCLient",
|
||||
ConsoleAppID: "managementConsoleApp",
|
||||
DefaultLanguage: "defaultLanguage",
|
||||
}
|
||||
instanceRepo := repository.InstanceRepository()
|
||||
err = instanceRepo.Create(t.Context(), tx, &instance)
|
||||
require.NoError(t, err)
|
||||
instanceId := createInstance(t, tx)
|
||||
|
||||
// create org
|
||||
orgId := gofakeit.Name()
|
||||
org := domain.Organization{
|
||||
ID: orgId,
|
||||
Name: gofakeit.Name(),
|
||||
InstanceID: instanceId,
|
||||
State: domain.OrgStateActive,
|
||||
}
|
||||
organizationRepo := repository.OrganizationRepository()
|
||||
err = organizationRepo.Create(t.Context(), tx, &org)
|
||||
require.NoError(t, err)
|
||||
orgId := createOrganization(t, tx, instanceId)
|
||||
|
||||
idpRepo := repository.IDProviderRepository()
|
||||
|
||||
@@ -994,30 +903,10 @@ func TestListIDProvider(t *testing.T) {
|
||||
name: "multiple idps filter on instance",
|
||||
testFunc: func(t *testing.T) []*domain.IdentityProvider {
|
||||
// create instance
|
||||
newInstanceId := gofakeit.Name()
|
||||
instance := domain.Instance{
|
||||
ID: newInstanceId,
|
||||
Name: gofakeit.Name(),
|
||||
DefaultOrgID: "defaultOrgId",
|
||||
IAMProjectID: "iamProject",
|
||||
ConsoleClientID: "managementConsoleCLient",
|
||||
ConsoleAppID: "managementConsoleApp",
|
||||
DefaultLanguage: "defaultLanguage",
|
||||
}
|
||||
err = instanceRepo.Create(t.Context(), tx, &instance)
|
||||
require.NoError(t, err)
|
||||
newInstanceId := createInstance(t, tx)
|
||||
|
||||
// create org
|
||||
newOrgId := gofakeit.Name()
|
||||
org := domain.Organization{
|
||||
ID: newOrgId,
|
||||
Name: gofakeit.Name(),
|
||||
InstanceID: newInstanceId,
|
||||
State: domain.OrgStateActive,
|
||||
}
|
||||
organizationRepo := repository.OrganizationRepository()
|
||||
err = organizationRepo.Create(t.Context(), tx, &org)
|
||||
require.NoError(t, err)
|
||||
newOrgId := createOrganization(t, tx, newInstanceId)
|
||||
|
||||
// create idp
|
||||
// this idp is created as an additional idp which should NOT
|
||||
@@ -1785,31 +1674,10 @@ func TestDeleteIDProvider(t *testing.T) {
|
||||
}()
|
||||
|
||||
// create instance
|
||||
instanceId := gofakeit.Name()
|
||||
instance := domain.Instance{
|
||||
ID: instanceId,
|
||||
Name: gofakeit.Name(),
|
||||
DefaultOrgID: "defaultOrgId",
|
||||
IAMProjectID: "iamProject",
|
||||
ConsoleClientID: "managementConsoleCLient",
|
||||
ConsoleAppID: "managementConsoleApp",
|
||||
DefaultLanguage: "defaultLanguage",
|
||||
}
|
||||
instanceRepo := repository.InstanceRepository()
|
||||
err = instanceRepo.Create(t.Context(), tx, &instance)
|
||||
require.NoError(t, err)
|
||||
instanceId := createInstance(t, tx)
|
||||
|
||||
// create org
|
||||
orgId := gofakeit.Name()
|
||||
org := domain.Organization{
|
||||
ID: orgId,
|
||||
Name: gofakeit.Name(),
|
||||
InstanceID: instanceId,
|
||||
State: domain.OrgStateActive,
|
||||
}
|
||||
organizationRepo := repository.OrganizationRepository()
|
||||
err = organizationRepo.Create(t.Context(), tx, &org)
|
||||
require.NoError(t, err)
|
||||
orgId := createOrganization(t, tx, instanceId)
|
||||
|
||||
idpRepo := repository.IDProviderRepository()
|
||||
|
||||
|
||||
@@ -0,0 +1,442 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/url"
|
||||
"time"
|
||||
|
||||
"github.com/muhlemmer/gu"
|
||||
|
||||
"github.com/zitadel/zitadel/backend/v3/domain"
|
||||
"github.com/zitadel/zitadel/backend/v3/storage/database"
|
||||
)
|
||||
|
||||
type idpIntentRepository struct{}
|
||||
|
||||
func (i idpIntentRepository) qualifiedTableName() string {
|
||||
return "zitadel.identity_provider_intents"
|
||||
}
|
||||
|
||||
func (i idpIntentRepository) unqualifiedTableName() string {
|
||||
return "identity_provider_intents"
|
||||
}
|
||||
|
||||
func IDPIntentRepository() domain.IDPIntentRepository {
|
||||
return new(idpIntentRepository)
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------
|
||||
// repository
|
||||
// -------------------------------------------------------------
|
||||
|
||||
const queryIDPIntentStmt = `
|
||||
SELECT
|
||||
identity_provider_intents.instance_id
|
||||
, identity_provider_intents.id
|
||||
, identity_provider_intents.state
|
||||
, identity_provider_intents.success_url
|
||||
, identity_provider_intents.failure_url
|
||||
, identity_provider_intents.created_at
|
||||
, identity_provider_intents.updated_at
|
||||
, identity_provider_intents.idp_id
|
||||
, identity_provider_intents.idp_arguments
|
||||
, identity_provider_intents.idp_user
|
||||
, identity_provider_intents.idp_user_id
|
||||
, identity_provider_intents.idp_username
|
||||
, identity_provider_intents.user_id
|
||||
, identity_provider_intents.idp_access_token
|
||||
, identity_provider_intents.idp_id_token
|
||||
, identity_provider_intents.idp_entry_attributes
|
||||
, identity_provider_intents.request_id
|
||||
, identity_provider_intents.assertion
|
||||
, identity_provider_intents.succeeded_at
|
||||
, identity_provider_intents.failed_at
|
||||
, identity_provider_intents.fail_reason
|
||||
, identity_provider_intents.expires_at
|
||||
FROM
|
||||
zitadel.identity_provider_intents
|
||||
`
|
||||
|
||||
// Create implements [domain.IDPIntentRepository].
|
||||
func (i idpIntentRepository) Create(ctx context.Context, client database.QueryExecutor, intent *domain.IDPIntent) error {
|
||||
var createdAt any = database.DefaultInstruction
|
||||
if !intent.CreatedAt.IsZero() {
|
||||
createdAt = intent.CreatedAt
|
||||
}
|
||||
var updatedAt = createdAt
|
||||
if !intent.UpdatedAt.IsZero() {
|
||||
updatedAt = intent.UpdatedAt
|
||||
}
|
||||
|
||||
builder := new(database.StatementBuilder)
|
||||
builder.WriteString(`INSERT INTO ` + i.qualifiedTableName() + ` (instance_id, id, success_url, failure_url, idp_id, idp_arguments, created_at, updated_at) VALUES ( `)
|
||||
builder.WriteArgs(intent.InstanceID, intent.ID, intent.SuccessURL.String(), intent.FailureURL.String(), intent.IDPID, intent.IDPArguments, createdAt, updatedAt)
|
||||
builder.WriteString(` ) RETURNING created_at, updated_at`)
|
||||
return client.QueryRow(ctx, builder.String(), builder.Args()...).Scan(&intent.CreatedAt, &intent.UpdatedAt)
|
||||
}
|
||||
|
||||
// Delete implements [domain.IDPIntentRepository].
|
||||
func (i idpIntentRepository) Delete(ctx context.Context, client database.QueryExecutor, condition database.Condition) (int64, error) {
|
||||
return deleteOne(ctx, client, i, condition)
|
||||
}
|
||||
|
||||
// Get implements [domain.IDPIntentRepository].
|
||||
func (i idpIntentRepository) Get(ctx context.Context, client database.QueryExecutor, opts ...database.QueryOption) (*domain.IDPIntent, error) {
|
||||
options := new(database.QueryOpts)
|
||||
for _, opt := range opts {
|
||||
opt(options)
|
||||
}
|
||||
|
||||
if options.Condition == nil || !options.Condition.IsRestrictingColumn(i.InstanceIDColumn()) {
|
||||
return nil, database.NewMissingConditionError(i.InstanceIDColumn())
|
||||
}
|
||||
|
||||
var builder database.StatementBuilder
|
||||
builder.WriteString(queryIDPIntentStmt)
|
||||
options.Write(&builder)
|
||||
fmt.Println(builder.String())
|
||||
|
||||
return scanIDPIntent(ctx, client, &builder)
|
||||
}
|
||||
|
||||
type rawIDPIntent struct {
|
||||
*domain.IDPIntent
|
||||
SuccessURL string `json:"success_url,omitempty" db:"success_url"`
|
||||
FailureURL string `json:"failure_url,omitempty" db:"failure_url"`
|
||||
IDPUserID *string `json:"idp_user_id,omitempty" db:"idp_user_id"`
|
||||
IDPUsername *string `json:"idp_username,omitempty" db:"idp_username"`
|
||||
UserID *string `json:"user_id,omitempty" db:"user_id"`
|
||||
IDPIDToken *string `json:"idp_id_token,omitempty" db:"idp_id_token"`
|
||||
RequestID *string `json:"request_id,omitempty" db:"request_id"`
|
||||
FailReason *string `json:"fail_reason,omitempty" db:"fail_reason"`
|
||||
}
|
||||
|
||||
func scanIDPIntent(ctx context.Context, querier database.QueryExecutor, builder *database.StatementBuilder) (*domain.IDPIntent, error) {
|
||||
rows, err := querier.Query(ctx, builder.String(), builder.Args()...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
raw := new(rawIDPIntent)
|
||||
if err := rows.(database.CollectableRows).CollectExactlyOneRow(raw); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return rawIDPIntentToDomain(raw)
|
||||
}
|
||||
|
||||
func rawIDPIntentToDomain(raw *rawIDPIntent) (*domain.IDPIntent, error) {
|
||||
successURL, _ := url.Parse(raw.SuccessURL)
|
||||
failureURL, _ := url.Parse(raw.FailureURL)
|
||||
raw.IDPIntent.SuccessURL = successURL
|
||||
raw.IDPIntent.FailureURL = failureURL
|
||||
raw.IDPIntent.IDPUserID = gu.Value(raw.IDPUserID)
|
||||
raw.IDPIntent.IDPUsername = gu.Value(raw.IDPUsername)
|
||||
raw.IDPIntent.UserID = gu.Value(raw.UserID)
|
||||
raw.IDPIntent.IDPIDToken = gu.Value(raw.IDPIDToken)
|
||||
raw.IDPIntent.RequestID = gu.Value(raw.RequestID)
|
||||
raw.IDPIntent.FailReason = gu.Value(raw.FailReason)
|
||||
|
||||
return raw.IDPIntent, nil
|
||||
}
|
||||
|
||||
// Update implements [domain.IDPIntentRepository].
|
||||
func (i idpIntentRepository) Update(ctx context.Context, client database.QueryExecutor, condition database.Condition, changes ...database.Change) (int64, error) {
|
||||
if changes == nil {
|
||||
return 0, database.ErrNoChanges
|
||||
}
|
||||
if condition == nil || !condition.IsRestrictingColumn(i.InstanceIDColumn()) {
|
||||
return 0, database.NewMissingConditionError(i.InstanceIDColumn())
|
||||
}
|
||||
if !database.Changes(changes).IsOnColumn(i.UpdatedAtColumn()) {
|
||||
changes = append(changes, database.NewChange(i.UpdatedAtColumn(), database.DefaultInstruction))
|
||||
}
|
||||
|
||||
builder := database.StatementBuilder{}
|
||||
builder.WriteString(`UPDATE zitadel.identity_provider_intents SET `)
|
||||
|
||||
err := database.Changes(changes).Write(&builder)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
writeCondition(&builder, condition)
|
||||
|
||||
return client.Exec(ctx, builder.String(), builder.Args()...)
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------
|
||||
// changes
|
||||
// -------------------------------------------------------------
|
||||
|
||||
// SetAssertion implements [domain.idpIntentChanges].
|
||||
func (i idpIntentRepository) SetAssertion(assertion []byte) database.Change {
|
||||
return database.NewChange(i.AssertionColumn(), assertion)
|
||||
}
|
||||
|
||||
// SetFailureURL implements [domain.idpIntentChanges].
|
||||
func (i idpIntentRepository) SetFailureURL(failureURL url.URL) database.Change {
|
||||
return database.NewChange(i.FailureURLColumn(), failureURL.String())
|
||||
}
|
||||
|
||||
// SetIDPAccessToken implements [domain.idpIntentChanges].
|
||||
func (i idpIntentRepository) SetIDPAccessToken(idpAccessToken []byte) database.Change {
|
||||
return database.NewChange(i.IDPAccessTokenColumn(), idpAccessToken)
|
||||
}
|
||||
|
||||
// SetIDPIDToken implements [domain.IDPIntentRepository].
|
||||
func (i *idpIntentRepository) SetIDPIDToken(idpIDToken string) database.Change {
|
||||
return database.NewChange(i.IDPIDTokenColumn(), idpIDToken)
|
||||
}
|
||||
|
||||
// SetIDPArguments implements [domain.idpIntentChanges].
|
||||
func (i idpIntentRepository) SetIDPArguments(idpArguments []byte) database.Change {
|
||||
return database.NewChange(i.IDPArgumentsColumn(), idpArguments)
|
||||
}
|
||||
|
||||
// SetIDPEntryAttributes implements [domain.idpIntentChanges].
|
||||
func (i idpIntentRepository) SetIDPEntryAttributes(idpEntryAttributes []byte) database.Change {
|
||||
return database.NewChange(i.IDPEntryAttributesColumn(), idpEntryAttributes)
|
||||
}
|
||||
|
||||
// SetIDPID implements [domain.idpIntentChanges].
|
||||
func (i idpIntentRepository) SetIDPID(idpID string) database.Change {
|
||||
return database.NewChange(i.IDPIDColumn(), idpID)
|
||||
}
|
||||
|
||||
// SetIDPUser implements [domain.idpIntentChanges].
|
||||
func (i idpIntentRepository) SetIDPUser(idpUser []byte) database.Change {
|
||||
return database.NewChange(i.IDPUserColumn(), idpUser)
|
||||
}
|
||||
|
||||
// SetIDPUserID implements [domain.idpIntentChanges].
|
||||
func (i idpIntentRepository) SetIDPUserID(idpUserID string) database.Change {
|
||||
return database.NewChange(i.IDPUserIDColumn(), idpUserID)
|
||||
}
|
||||
|
||||
// SetIDPUsername implements [domain.idpIntentChanges].
|
||||
func (i idpIntentRepository) SetIDPUsername(idpUsername string) database.Change {
|
||||
return database.NewChange(i.IDPUsernameColumn(), idpUsername)
|
||||
}
|
||||
|
||||
// SetRequestID implements [domain.idpIntentChanges].
|
||||
func (i idpIntentRepository) SetRequestID(requestID string) database.Change {
|
||||
return database.NewChange(i.RequestIDColumn(), requestID)
|
||||
}
|
||||
|
||||
// SetState implements [domain.idpIntentChanges].
|
||||
func (i idpIntentRepository) SetState(state domain.IDPIntentState) database.Change {
|
||||
return database.NewChange(i.StateColumn(), state)
|
||||
}
|
||||
|
||||
// SetSuccessURL implements [domain.idpIntentChanges].
|
||||
func (i idpIntentRepository) SetSuccessURL(successURL url.URL) database.Change {
|
||||
return database.NewChange(i.SuccessURLColumn(), successURL.String())
|
||||
}
|
||||
|
||||
// SetUserID implements [domain.idpIntentChanges].
|
||||
func (i idpIntentRepository) SetUserID(userID string) database.Change {
|
||||
return database.NewChange(i.UserIDColumn(), userID)
|
||||
}
|
||||
|
||||
// SetExpiresAt implements [domain.IDPIntentRepository].
|
||||
func (i *idpIntentRepository) SetExpiresAt(expiration time.Time) database.Change {
|
||||
return database.NewChange(i.ExpiresAtColumn(), expiration)
|
||||
}
|
||||
|
||||
// SetSucceededAt implements [domain.IDPIntentRepository].
|
||||
func (i *idpIntentRepository) SetSucceededAt(succeededAt time.Time) database.Change {
|
||||
return database.NewChange(i.SucceededAtColumn(), succeededAt)
|
||||
}
|
||||
|
||||
// SetFailedAt implements [domain.IDPIntentRepository].
|
||||
func (i *idpIntentRepository) SetFailedAt(failedAt time.Time) database.Change {
|
||||
return database.NewChange(i.FailedAtColumn(), failedAt)
|
||||
}
|
||||
|
||||
// SetFailReason implements [domain.IDPIntentRepository].
|
||||
func (i *idpIntentRepository) SetFailReason(reason string) database.Change {
|
||||
return database.NewChange(i.FailReasonColumn(), reason)
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------
|
||||
// conditions
|
||||
// -------------------------------------------------------------
|
||||
|
||||
// CreatedAtCondition implements [domain.idpIntentConditions].
|
||||
func (i idpIntentRepository) CreatedAtCondition(op database.NumberOperation, createdAt time.Time) database.Condition {
|
||||
return database.NewNumberCondition(i.CreatedAtColumn(), op, createdAt)
|
||||
}
|
||||
|
||||
// IDCondition implements [domain.idpIntentConditions].
|
||||
func (i idpIntentRepository) IDCondition(id string) database.Condition {
|
||||
return database.NewTextCondition(i.IDColumn(), database.TextOperationEqual, id)
|
||||
}
|
||||
|
||||
// IDPIDCondition implements [domain.idpIntentConditions].
|
||||
func (i idpIntentRepository) IDPIDCondition(idpID string) database.Condition {
|
||||
return database.NewTextCondition(i.IDPIDColumn(), database.TextOperationEqual, idpID)
|
||||
}
|
||||
|
||||
// IDPUserIDCondition implements [domain.idpIntentConditions].
|
||||
func (i idpIntentRepository) IDPUserIDCondition(idpUserID string) database.Condition {
|
||||
return database.NewTextCondition(i.IDPUserIDColumn(), database.TextOperationEqual, idpUserID)
|
||||
}
|
||||
|
||||
// IDPUsernameCondition implements [domain.idpIntentConditions].
|
||||
func (i idpIntentRepository) IDPUsernameCondition(idpUsername string) database.Condition {
|
||||
return database.NewTextCondition(i.IDPUsernameColumn(), database.TextOperationEqual, idpUsername)
|
||||
}
|
||||
|
||||
// InstanceIDCondition implements [domain.idpIntentConditions].
|
||||
func (i idpIntentRepository) InstanceIDCondition(instanceID string) database.Condition {
|
||||
return database.NewTextCondition(i.InstanceIDColumn(), database.TextOperationEqual, instanceID)
|
||||
}
|
||||
|
||||
// PrimaryKeyCondition implements [domain.idpIntentConditions].
|
||||
func (i idpIntentRepository) PrimaryKeyCondition(instanceID, id string) database.Condition {
|
||||
return database.And(
|
||||
i.InstanceIDCondition(instanceID),
|
||||
i.IDCondition(id),
|
||||
)
|
||||
}
|
||||
|
||||
// RequestIDCondition implements [domain.idpIntentConditions].
|
||||
func (i idpIntentRepository) RequestIDCondition(requestID string) database.Condition {
|
||||
return database.NewTextCondition(i.RequestIDColumn(), database.TextOperationEqual, requestID)
|
||||
}
|
||||
|
||||
// StateCondition implements [domain.idpIntentConditions].
|
||||
func (i idpIntentRepository) StateCondition(state domain.IDPIntentState) database.Condition {
|
||||
return database.NewTextCondition(i.StateColumn(), database.TextOperationEqual, state.String())
|
||||
}
|
||||
|
||||
// UpdatedAtCondition implements [domain.idpIntentConditions].
|
||||
func (i idpIntentRepository) UpdatedAtCondition(op database.NumberOperation, updatedAt time.Time) database.Condition {
|
||||
return database.NewNumberCondition(i.UpdatedAtColumn(), op, updatedAt)
|
||||
}
|
||||
|
||||
// UserIDCondition implements [domain.idpIntentConditions].
|
||||
func (i idpIntentRepository) UserIDCondition(userID string) database.Condition {
|
||||
return database.NewTextCondition(i.UserIDColumn(), database.TextOperationEqual, userID)
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------
|
||||
// columns
|
||||
// -------------------------------------------------------------
|
||||
|
||||
// AssertionColumn implements [domain.idpIntentColumns].
|
||||
func (i idpIntentRepository) AssertionColumn() database.Column {
|
||||
return database.NewColumn(i.unqualifiedTableName(), "assertion")
|
||||
}
|
||||
|
||||
// CreatedAtColumn implements [domain.idpIntentColumns].
|
||||
func (i idpIntentRepository) CreatedAtColumn() database.Column {
|
||||
return database.NewColumn(i.unqualifiedTableName(), "created_at")
|
||||
}
|
||||
|
||||
// ExpiresAtColumn implements [domain.idpIntentColumns].
|
||||
func (i idpIntentRepository) ExpiresAtColumn() database.Column {
|
||||
return database.NewColumn(i.unqualifiedTableName(), "expires_at")
|
||||
}
|
||||
|
||||
// FailureURLColumn implements [domain.idpIntentColumns].
|
||||
func (i idpIntentRepository) FailureURLColumn() database.Column {
|
||||
return database.NewColumn(i.unqualifiedTableName(), "failure_url")
|
||||
}
|
||||
|
||||
// IDColumn implements [domain.idpIntentColumns].
|
||||
func (i idpIntentRepository) IDColumn() database.Column {
|
||||
return database.NewColumn(i.unqualifiedTableName(), "id")
|
||||
}
|
||||
|
||||
// IDPAccessTokenColumn implements [domain.idpIntentColumns].
|
||||
func (i idpIntentRepository) IDPAccessTokenColumn() database.Column {
|
||||
return database.NewColumn(i.unqualifiedTableName(), "idp_access_token")
|
||||
}
|
||||
|
||||
// IDPIDTokenColumn implements [domain.IDPIntentRepository].
|
||||
func (i *idpIntentRepository) IDPIDTokenColumn() database.Column {
|
||||
return database.NewColumn(i.unqualifiedTableName(), "idp_id_token")
|
||||
}
|
||||
|
||||
// IDPArgumentsColumn implements [domain.idpIntentColumns].
|
||||
func (i idpIntentRepository) IDPArgumentsColumn() database.Column {
|
||||
return database.NewColumn(i.unqualifiedTableName(), "idp_arguments")
|
||||
}
|
||||
|
||||
// IDPEntryAttributesColumn implements [domain.idpIntentColumns].
|
||||
func (i idpIntentRepository) IDPEntryAttributesColumn() database.Column {
|
||||
return database.NewColumn(i.unqualifiedTableName(), "idp_entry_attributes")
|
||||
}
|
||||
|
||||
// IDPIDColumn implements [domain.idpIntentColumns].
|
||||
func (i idpIntentRepository) IDPIDColumn() database.Column {
|
||||
return database.NewColumn(i.unqualifiedTableName(), "idp_id")
|
||||
}
|
||||
|
||||
// IDPUserColumn implements [domain.idpIntentColumns].
|
||||
func (i idpIntentRepository) IDPUserColumn() database.Column {
|
||||
return database.NewColumn(i.unqualifiedTableName(), "idp_user")
|
||||
}
|
||||
|
||||
// IDPUserIDColumn implements [domain.idpIntentColumns].
|
||||
func (i idpIntentRepository) IDPUserIDColumn() database.Column {
|
||||
return database.NewColumn(i.unqualifiedTableName(), "idp_user_id")
|
||||
}
|
||||
|
||||
// IDPUsernameColumn implements [domain.idpIntentColumns].
|
||||
func (i idpIntentRepository) IDPUsernameColumn() database.Column {
|
||||
return database.NewColumn(i.unqualifiedTableName(), "idp_username")
|
||||
}
|
||||
|
||||
// InstanceIDColumn implements [domain.idpIntentColumns].
|
||||
func (i idpIntentRepository) InstanceIDColumn() database.Column {
|
||||
return database.NewColumn(i.unqualifiedTableName(), "instance_id")
|
||||
}
|
||||
|
||||
// PrimaryKeyColumns implements [domain.IDPIntentRepository].
|
||||
func (i idpIntentRepository) PrimaryKeyColumns() []database.Column {
|
||||
return []database.Column{i.IDColumn(), i.InstanceIDColumn()}
|
||||
}
|
||||
|
||||
// RequestIDColumn implements [domain.idpIntentColumns].
|
||||
func (i idpIntentRepository) RequestIDColumn() database.Column {
|
||||
return database.NewColumn(i.unqualifiedTableName(), "request_id")
|
||||
}
|
||||
|
||||
// StateColumn implements [domain.idpIntentColumns].
|
||||
func (i idpIntentRepository) StateColumn() database.Column {
|
||||
return database.NewColumn(i.unqualifiedTableName(), "state")
|
||||
}
|
||||
|
||||
// SucceededAtColumn implements [domain.idpIntentColumns].
|
||||
func (i idpIntentRepository) SucceededAtColumn() database.Column {
|
||||
return database.NewColumn(i.unqualifiedTableName(), "succeeded_at")
|
||||
}
|
||||
|
||||
// SuccessURLColumn implements [domain.idpIntentColumns].
|
||||
func (i idpIntentRepository) SuccessURLColumn() database.Column {
|
||||
return database.NewColumn(i.unqualifiedTableName(), "success_url")
|
||||
}
|
||||
|
||||
// FailReasonColumn implements [domain.IDPIntentRepository].
|
||||
func (i *idpIntentRepository) FailReasonColumn() database.Column {
|
||||
return database.NewColumn(i.unqualifiedTableName(), "fail_reason")
|
||||
}
|
||||
|
||||
// FailedAtColumn implements [domain.IDPIntentRepository].
|
||||
func (i *idpIntentRepository) FailedAtColumn() database.Column {
|
||||
return database.NewColumn(i.unqualifiedTableName(), "failed_at")
|
||||
}
|
||||
|
||||
// UpdatedAtColumn implements [domain.idpIntentColumns].
|
||||
func (i idpIntentRepository) UpdatedAtColumn() database.Column {
|
||||
return database.NewColumn(i.unqualifiedTableName(), "updated_at")
|
||||
}
|
||||
|
||||
// UserIDColumn implements [domain.idpIntentColumns].
|
||||
func (i idpIntentRepository) UserIDColumn() database.Column {
|
||||
return database.NewColumn(i.unqualifiedTableName(), "user_id")
|
||||
}
|
||||
|
||||
var _ domain.IDPIntentRepository = (*idpIntentRepository)(nil)
|
||||
@@ -0,0 +1,591 @@
|
||||
package repository_test
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/url"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/brianvoe/gofakeit/v6"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"github.com/zitadel/zitadel/backend/v3/domain"
|
||||
"github.com/zitadel/zitadel/backend/v3/storage/database"
|
||||
"github.com/zitadel/zitadel/backend/v3/storage/database/repository"
|
||||
)
|
||||
|
||||
func TestCreateIDPIntent(t *testing.T) {
|
||||
beforeCreate := time.Now()
|
||||
tx, err := pool.Begin(t.Context(), nil)
|
||||
require.NoError(t, err)
|
||||
defer func() {
|
||||
err := tx.Rollback(t.Context())
|
||||
require.NoError(t, err)
|
||||
}()
|
||||
|
||||
instanceID := createInstance(t, tx)
|
||||
orgID := createOrganization(t, tx, instanceID)
|
||||
idpID := createIdentityProvider(t, tx, instanceID, orgID)
|
||||
|
||||
successURL, err := url.Parse("https://example.com/success")
|
||||
require.NoError(t, err)
|
||||
failURL, err := url.Parse("https://example.com/fail")
|
||||
require.NoError(t, err)
|
||||
|
||||
emptyURL, err := url.Parse("")
|
||||
require.NoError(t, err)
|
||||
|
||||
intentID := gofakeit.UUID()
|
||||
tt := []struct {
|
||||
testName string
|
||||
|
||||
inputID string
|
||||
inputInstanceID string
|
||||
inputSuccessURL *url.URL
|
||||
inputFailureURL *url.URL
|
||||
inputIDPID string
|
||||
inputIDPArgs map[string]any
|
||||
inputCreatedAt time.Time
|
||||
inputUpdatedAt time.Time
|
||||
inputMaxLifetime time.Duration
|
||||
|
||||
expectedError error
|
||||
}{
|
||||
{
|
||||
testName: "create and update timestamps not set / empty fail url / should generate timestamps and retrieve successfully",
|
||||
inputID: intentID,
|
||||
inputInstanceID: instanceID,
|
||||
inputSuccessURL: successURL,
|
||||
inputFailureURL: emptyURL,
|
||||
inputIDPID: idpID,
|
||||
inputIDPArgs: map[string]any{
|
||||
"arg1": map[string]any{"k1": 1, "k2": "v2"},
|
||||
"arg2": 2,
|
||||
"arg3": "3",
|
||||
"arg4": true,
|
||||
},
|
||||
inputMaxLifetime: time.Hour * 2,
|
||||
},
|
||||
{
|
||||
testName: "all set / should retrieve successfully",
|
||||
inputID: intentID,
|
||||
inputInstanceID: instanceID,
|
||||
inputSuccessURL: successURL,
|
||||
inputFailureURL: failURL,
|
||||
inputIDPID: idpID,
|
||||
inputIDPArgs: map[string]any{"arg1": map[string]any{"k1": 1, "k2": "v2"}},
|
||||
inputMaxLifetime: time.Hour * 2,
|
||||
inputCreatedAt: time.Now(),
|
||||
inputUpdatedAt: time.Now(),
|
||||
},
|
||||
{
|
||||
testName: "id not set / should return check error",
|
||||
inputCreatedAt: time.Now(),
|
||||
inputUpdatedAt: time.Now(),
|
||||
inputInstanceID: instanceID,
|
||||
inputSuccessURL: successURL,
|
||||
inputFailureURL: emptyURL,
|
||||
inputIDPID: idpID,
|
||||
inputIDPArgs: map[string]any{"arg1": map[string]any{"k1": 1, "k2": "v2"}},
|
||||
expectedError: database.NewCheckError("", "", nil),
|
||||
},
|
||||
{
|
||||
testName: "instance id not found / should return foreign key error",
|
||||
inputID: intentID,
|
||||
inputCreatedAt: time.Now(),
|
||||
inputUpdatedAt: time.Now(),
|
||||
inputSuccessURL: successURL,
|
||||
inputFailureURL: emptyURL,
|
||||
inputIDPID: idpID,
|
||||
inputIDPArgs: map[string]any{"arg1": map[string]any{"k1": 1, "k2": "v2"}},
|
||||
expectedError: database.NewForeignKeyError("", "", nil),
|
||||
},
|
||||
{
|
||||
testName: "idp id not found / should return foreign key error",
|
||||
inputID: intentID,
|
||||
inputInstanceID: instanceID,
|
||||
inputCreatedAt: time.Now(),
|
||||
inputUpdatedAt: time.Now(),
|
||||
inputSuccessURL: successURL,
|
||||
inputFailureURL: failURL,
|
||||
inputIDPArgs: map[string]any{"arg1": map[string]any{"k1": 1, "k2": "v2"}},
|
||||
expectedError: database.NewForeignKeyError("", "", nil),
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range tt {
|
||||
t.Run(tc.testName, func(t *testing.T) {
|
||||
// Given
|
||||
savePoint, savePointErr := tx.Begin(t.Context())
|
||||
require.NoError(t, savePointErr)
|
||||
defer func() {
|
||||
err := savePoint.Rollback(t.Context())
|
||||
require.NoError(t, err)
|
||||
}()
|
||||
|
||||
idpIntentRepo := repository.IDPIntentRepository()
|
||||
intent := domain.IDPIntent{
|
||||
ID: tc.inputID,
|
||||
InstanceID: tc.inputInstanceID,
|
||||
SuccessURL: tc.inputSuccessURL,
|
||||
FailureURL: tc.inputFailureURL,
|
||||
IDPID: tc.inputIDPID,
|
||||
IDPArguments: tc.inputIDPArgs,
|
||||
|
||||
State: domain.IDPIntentStateFailed, // Should disregard
|
||||
IDPUserID: "should disregard",
|
||||
}
|
||||
|
||||
// Test
|
||||
createErr := idpIntentRepo.Create(t.Context(), tx, &intent)
|
||||
afterCreate := time.Now()
|
||||
|
||||
// Verify
|
||||
assert.ErrorIs(t, createErr, tc.expectedError)
|
||||
if tc.expectedError == nil {
|
||||
retrieved, getErr := idpIntentRepo.Get(t.Context(), tx, database.WithCondition(idpIntentRepo.PrimaryKeyCondition(instanceID, intentID)))
|
||||
require.NoError(t, getErr)
|
||||
require.NotNil(t, retrieved)
|
||||
|
||||
assert.WithinRange(t, retrieved.CreatedAt, beforeCreate, afterCreate)
|
||||
assert.WithinRange(t, retrieved.UpdatedAt, beforeCreate, afterCreate)
|
||||
assert.NotZero(t, retrieved.ID)
|
||||
if tc.inputID != "" {
|
||||
assert.Equal(t, tc.inputID, retrieved.ID)
|
||||
}
|
||||
assert.Equal(t, tc.inputInstanceID, retrieved.InstanceID)
|
||||
assert.Equal(t, tc.inputSuccessURL, retrieved.SuccessURL)
|
||||
assert.Equal(t, tc.inputFailureURL, retrieved.FailureURL)
|
||||
assert.Equal(t, tc.inputIDPID, retrieved.IDPID)
|
||||
assert.NotZero(t, retrieved.IDPArguments)
|
||||
assert.Equal(t, domain.IDPIntentStateStarted, retrieved.State)
|
||||
assert.Zero(t, retrieved.IDPUserID)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetIDPIntent(t *testing.T) {
|
||||
tx, err := pool.Begin(t.Context(), nil)
|
||||
require.NoError(t, err)
|
||||
defer func() {
|
||||
err := tx.Rollback(t.Context())
|
||||
require.NoError(t, err)
|
||||
}()
|
||||
|
||||
instanceID := createInstance(t, tx)
|
||||
orgID := createOrganization(t, tx, instanceID)
|
||||
idpID := createIdentityProvider(t, tx, instanceID, orgID)
|
||||
|
||||
idpIntentRepo := repository.IDPIntentRepository()
|
||||
|
||||
intentID1 := createIDPIntent(t, tx, instanceID, idpID)
|
||||
successURL, err := url.Parse("https://example.com/success")
|
||||
require.NoError(t, err)
|
||||
failURL, err := url.Parse("https://example.com/fail")
|
||||
require.NoError(t, err)
|
||||
|
||||
intent2 := domain.IDPIntent{
|
||||
ID: gofakeit.UUID(),
|
||||
InstanceID: instanceID,
|
||||
SuccessURL: successURL,
|
||||
FailureURL: failURL,
|
||||
IDPID: idpID,
|
||||
IDPArguments: map[string]any{"arg1": map[string]any{"k1": 1, "k2": "v2"}},
|
||||
CreatedAt: time.Now().AddDate(0, 0, 1),
|
||||
}
|
||||
err = idpIntentRepo.Create(t.Context(), tx, &intent2)
|
||||
require.NoError(t, err)
|
||||
|
||||
tt := []struct {
|
||||
testName string
|
||||
inputQueryOpts []database.QueryOption
|
||||
expectedError error
|
||||
expectedIntentID string
|
||||
}{
|
||||
{
|
||||
testName: "when no condition set should return missing condition error",
|
||||
expectedError: database.NewMissingConditionError(nil),
|
||||
},
|
||||
{
|
||||
testName: "when no instance condition set should return missing condition error",
|
||||
inputQueryOpts: []database.QueryOption{
|
||||
database.WithCondition(idpIntentRepo.IDCondition(intentID1)),
|
||||
},
|
||||
expectedError: database.NewMissingConditionError(nil),
|
||||
},
|
||||
{
|
||||
testName: "when primary key condition set should return matching intent",
|
||||
inputQueryOpts: []database.QueryOption{
|
||||
database.WithCondition(idpIntentRepo.PrimaryKeyCondition(instanceID, intentID1)),
|
||||
},
|
||||
expectedIntentID: intentID1,
|
||||
},
|
||||
{
|
||||
testName: "when filtering by creation date descending should return matching intent with highest PK",
|
||||
inputQueryOpts: []database.QueryOption{
|
||||
database.WithCondition(database.And(
|
||||
idpIntentRepo.InstanceIDCondition(instanceID),
|
||||
)),
|
||||
database.WithOrderByDescending(idpIntentRepo.CreatedAtColumn()),
|
||||
database.WithLimit(1),
|
||||
},
|
||||
expectedIntentID: intent2.ID,
|
||||
},
|
||||
{
|
||||
testName: "when filtering by non-existent PK should return no row found error",
|
||||
inputQueryOpts: []database.QueryOption{
|
||||
database.WithCondition(database.And(
|
||||
idpIntentRepo.InstanceIDCondition(instanceID),
|
||||
idpIntentRepo.IDCondition("not existing"),
|
||||
)),
|
||||
},
|
||||
expectedError: database.NewNoRowFoundError(nil),
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range tt {
|
||||
t.Run(tc.testName, func(t *testing.T) {
|
||||
// Test
|
||||
retrieved, err := idpIntentRepo.Get(t.Context(), tx, tc.inputQueryOpts...)
|
||||
|
||||
// Verify
|
||||
assert.ErrorIs(t, err, tc.expectedError)
|
||||
if tc.expectedError == nil {
|
||||
assert.Equal(t, tc.expectedIntentID, retrieved.ID)
|
||||
assert.Equal(t, "https://example.com/success", retrieved.SuccessURL.String())
|
||||
assert.Equal(t, "https://example.com/fail", retrieved.FailureURL.String())
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestUpdateIDPIntent(t *testing.T) {
|
||||
beforeUpdate := time.Now()
|
||||
|
||||
tx, err := pool.Begin(t.Context(), nil)
|
||||
require.NoError(t, err)
|
||||
defer func() {
|
||||
err := tx.Rollback(t.Context())
|
||||
require.NoError(t, err)
|
||||
}()
|
||||
|
||||
instanceID := createInstance(t, tx)
|
||||
orgID := createOrganization(t, tx, instanceID)
|
||||
idpID := createIdentityProvider(t, tx, instanceID, orgID)
|
||||
|
||||
idpIntentRepo := repository.IDPIntentRepository()
|
||||
|
||||
successURL, err := url.Parse("https://example.com/success")
|
||||
require.NoError(t, err)
|
||||
failURL, err := url.Parse("https://example.com/fail")
|
||||
require.NoError(t, err)
|
||||
|
||||
intentID1 := gofakeit.UUID()
|
||||
intent1 := domain.IDPIntent{
|
||||
ID: intentID1,
|
||||
InstanceID: instanceID,
|
||||
SuccessURL: successURL,
|
||||
FailureURL: failURL,
|
||||
IDPID: idpID,
|
||||
IDPArguments: map[string]any{"arg1": map[string]any{"k1": 1, "k2": "v2"}, "arg2": []int32{1}},
|
||||
CreatedAt: time.Now(),
|
||||
}
|
||||
err = idpIntentRepo.Create(t.Context(), tx, &intent1)
|
||||
require.NoError(t, err)
|
||||
|
||||
entryAttrs := map[string][]string{
|
||||
"attr1": {"1", "2"},
|
||||
"attr2": {"3", "4"},
|
||||
}
|
||||
marshalledAttrs, marshallErr := json.Marshal(entryAttrs)
|
||||
require.NoError(t, marshallErr)
|
||||
|
||||
intentID2 := gofakeit.UUID()
|
||||
intent2 := domain.IDPIntent{
|
||||
ID: intentID2,
|
||||
InstanceID: instanceID,
|
||||
SuccessURL: successURL,
|
||||
FailureURL: failURL,
|
||||
IDPID: idpID,
|
||||
IDPArguments: map[string]any{"arg1": map[string]any{"k1": 1, "k2": "v2"}},
|
||||
CreatedAt: time.Now(),
|
||||
}
|
||||
err = idpIntentRepo.Create(t.Context(), tx, &intent2)
|
||||
require.NoError(t, err)
|
||||
|
||||
now := time.Now()
|
||||
tomorrow := now.AddDate(0, 0, 1)
|
||||
tt := []struct {
|
||||
testName string
|
||||
inputConditions database.Condition
|
||||
inputChanges []database.Change
|
||||
expectedError error
|
||||
expectedUpdatedRecords func() []*domain.IDPIntent
|
||||
expectedUpdatedRows int64
|
||||
}{
|
||||
{
|
||||
testName: "when no changes should return no changes error",
|
||||
expectedError: database.ErrNoChanges,
|
||||
},
|
||||
{
|
||||
testName: "when no condition set should return missing condition error",
|
||||
inputChanges: database.Changes{
|
||||
idpIntentRepo.SetIDPUser([]byte("not a user")),
|
||||
},
|
||||
expectedError: database.NewMissingConditionError(idpIntentRepo.InstanceIDColumn()),
|
||||
},
|
||||
{
|
||||
testName: "when simulating SucceededEvent should update fields accordingly",
|
||||
inputConditions: idpIntentRepo.PrimaryKeyCondition(instanceID, intentID1),
|
||||
inputChanges: database.Changes{
|
||||
idpIntentRepo.SetState(domain.IDPIntentStateSucceeded),
|
||||
idpIntentRepo.SetIDPUser([]byte("update user")),
|
||||
idpIntentRepo.SetIDPUserID("idp user id updated"),
|
||||
idpIntentRepo.SetIDPUsername("idp username updated"),
|
||||
idpIntentRepo.SetUserID("some-user-id"),
|
||||
idpIntentRepo.SetIDPAccessToken([]byte(`{"secret": "g1g4 s3cr3t 4cc3ss t0k3n"}`)),
|
||||
idpIntentRepo.SetIDPIDToken("idp id token"),
|
||||
idpIntentRepo.SetSucceededAt(now),
|
||||
idpIntentRepo.SetExpiresAt(tomorrow),
|
||||
},
|
||||
expectedUpdatedRecords: func() []*domain.IDPIntent {
|
||||
toReturn := intent1
|
||||
toReturn.IDPUser = []byte("update user")
|
||||
toReturn.IDPUserID = "idp user id updated"
|
||||
toReturn.IDPUsername = "idp username updated"
|
||||
toReturn.UserID = "some-user-id"
|
||||
toReturn.IDPAccessToken = []byte(`{"secret": "g1g4 s3cr3t 4cc3ss t0k3n"}`)
|
||||
toReturn.IDPIDToken = "idp id token"
|
||||
toReturn.SucceededAt = &now
|
||||
toReturn.ExpiresAt = &tomorrow
|
||||
toReturn.State = domain.IDPIntentStateSucceeded
|
||||
return []*domain.IDPIntent{&toReturn}
|
||||
},
|
||||
expectedUpdatedRows: 1,
|
||||
},
|
||||
{
|
||||
testName: "when simulating SAMLSucceededEvent should update fields accordingly",
|
||||
inputConditions: idpIntentRepo.PrimaryKeyCondition(instanceID, intentID1),
|
||||
inputChanges: database.Changes{
|
||||
idpIntentRepo.SetState(domain.IDPIntentStateSucceeded),
|
||||
idpIntentRepo.SetIDPUser([]byte("update user")),
|
||||
idpIntentRepo.SetIDPUserID("idp user id updated"),
|
||||
idpIntentRepo.SetIDPUsername("idp username updated"),
|
||||
idpIntentRepo.SetUserID("some-user-id"),
|
||||
idpIntentRepo.SetAssertion([]byte(`{"assertion": "val1"}`)),
|
||||
idpIntentRepo.SetSucceededAt(now),
|
||||
idpIntentRepo.SetExpiresAt(tomorrow),
|
||||
},
|
||||
expectedUpdatedRecords: func() []*domain.IDPIntent {
|
||||
toReturn := intent1
|
||||
toReturn.IDPUser = []byte("update user")
|
||||
toReturn.IDPUserID = "idp user id updated"
|
||||
toReturn.IDPUsername = "idp username updated"
|
||||
toReturn.UserID = "some-user-id"
|
||||
toReturn.Assertion = []byte(`{"assertion": "val1"}`)
|
||||
toReturn.SucceededAt = &now
|
||||
toReturn.ExpiresAt = &tomorrow
|
||||
toReturn.State = domain.IDPIntentStateSucceeded
|
||||
return []*domain.IDPIntent{&toReturn}
|
||||
},
|
||||
expectedUpdatedRows: 1,
|
||||
},
|
||||
{
|
||||
testName: "when simulating LDAPSucceededEvent should update fields accordingly",
|
||||
inputConditions: idpIntentRepo.PrimaryKeyCondition(instanceID, intentID1),
|
||||
inputChanges: database.Changes{
|
||||
idpIntentRepo.SetState(domain.IDPIntentStateSucceeded),
|
||||
idpIntentRepo.SetIDPUser([]byte("update user")),
|
||||
idpIntentRepo.SetIDPUserID("idp user id updated"),
|
||||
idpIntentRepo.SetIDPUsername("idp username updated"),
|
||||
idpIntentRepo.SetUserID("some-user-id"),
|
||||
idpIntentRepo.SetIDPEntryAttributes(marshalledAttrs),
|
||||
idpIntentRepo.SetSucceededAt(now),
|
||||
idpIntentRepo.SetExpiresAt(tomorrow),
|
||||
},
|
||||
expectedUpdatedRecords: func() []*domain.IDPIntent {
|
||||
toReturn := intent1
|
||||
toReturn.IDPUser = []byte("update user")
|
||||
toReturn.IDPUserID = "idp user id updated"
|
||||
toReturn.IDPUsername = "idp username updated"
|
||||
toReturn.UserID = "some-user-id"
|
||||
toReturn.EntryAttributes = entryAttrs
|
||||
toReturn.SucceededAt = &now
|
||||
toReturn.ExpiresAt = &tomorrow
|
||||
toReturn.State = domain.IDPIntentStateSucceeded
|
||||
return []*domain.IDPIntent{&toReturn}
|
||||
},
|
||||
expectedUpdatedRows: 1,
|
||||
},
|
||||
{
|
||||
testName: "when simulating FailedEvent should update reason, state and failedAt",
|
||||
inputConditions: idpIntentRepo.PrimaryKeyCondition(instanceID, intentID1),
|
||||
inputChanges: database.Changes{
|
||||
idpIntentRepo.SetState(domain.IDPIntentStateFailed),
|
||||
idpIntentRepo.SetFailReason("mock failure"),
|
||||
idpIntentRepo.SetFailedAt(now),
|
||||
},
|
||||
expectedUpdatedRecords: func() []*domain.IDPIntent {
|
||||
toReturn := intent1
|
||||
toReturn.FailReason = "mock failure"
|
||||
toReturn.State = domain.IDPIntentStateFailed
|
||||
toReturn.FailedAt = &now
|
||||
return []*domain.IDPIntent{&toReturn}
|
||||
},
|
||||
expectedUpdatedRows: 1,
|
||||
},
|
||||
{
|
||||
testName: "when simulating SAMLRequestEvent should update request ID",
|
||||
inputConditions: idpIntentRepo.PrimaryKeyCondition(instanceID, intentID1),
|
||||
inputChanges: database.Changes{
|
||||
idpIntentRepo.SetRequestID("req-123"),
|
||||
},
|
||||
expectedUpdatedRecords: func() []*domain.IDPIntent {
|
||||
toReturn := intent1
|
||||
toReturn.RequestID = "req-123"
|
||||
return []*domain.IDPIntent{&toReturn}
|
||||
},
|
||||
expectedUpdatedRows: 1,
|
||||
},
|
||||
{
|
||||
testName: "when updating multiple records should return updated records",
|
||||
inputConditions: database.Or(
|
||||
idpIntentRepo.PrimaryKeyCondition(instanceID, intentID1),
|
||||
idpIntentRepo.PrimaryKeyCondition(instanceID, intentID2),
|
||||
),
|
||||
inputChanges: database.Changes{
|
||||
idpIntentRepo.SetState(domain.IDPIntentStateFailed),
|
||||
idpIntentRepo.SetRequestID("req-123"),
|
||||
idpIntentRepo.SetFailedAt(now),
|
||||
},
|
||||
expectedUpdatedRecords: func() []*domain.IDPIntent {
|
||||
toReturn1, toReturn2 := intent1, intent2
|
||||
toReturn1.State = domain.IDPIntentStateFailed
|
||||
toReturn1.RequestID = "req-123"
|
||||
toReturn1.FailedAt = &now
|
||||
toReturn2.State = domain.IDPIntentStateFailed
|
||||
toReturn2.RequestID = "req-123"
|
||||
toReturn2.FailedAt = &now
|
||||
return []*domain.IDPIntent{&toReturn1, &toReturn2}
|
||||
},
|
||||
expectedUpdatedRows: 2,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range tt {
|
||||
t.Run(tc.testName, func(t *testing.T) {
|
||||
savePoint, err := tx.Begin(t.Context())
|
||||
require.NoError(t, err)
|
||||
defer func() {
|
||||
err := savePoint.Rollback(t.Context())
|
||||
require.NoError(t, err)
|
||||
}()
|
||||
|
||||
// Test
|
||||
updatedCount, err := idpIntentRepo.Update(t.Context(), savePoint, tc.inputConditions, tc.inputChanges...)
|
||||
afterUpdate := time.Now()
|
||||
|
||||
// Verify
|
||||
assert.ErrorIs(t, err, tc.expectedError)
|
||||
require.Equal(t, tc.expectedUpdatedRows, updatedCount)
|
||||
if tc.expectedError == nil {
|
||||
for _, expectedIntent := range tc.expectedUpdatedRecords() {
|
||||
retrievedIntent, err := idpIntentRepo.Get(t.Context(), savePoint, database.WithCondition(idpIntentRepo.PrimaryKeyCondition(instanceID, expectedIntent.ID)))
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, expectedIntent.ID, retrievedIntent.ID)
|
||||
assert.Equal(t, expectedIntent.InstanceID, retrievedIntent.InstanceID)
|
||||
assert.Equal(t, expectedIntent.State, retrievedIntent.State)
|
||||
assert.Equal(t, expectedIntent.SuccessURL, retrievedIntent.SuccessURL)
|
||||
assert.Equal(t, expectedIntent.FailureURL, retrievedIntent.FailureURL)
|
||||
assert.Equal(t, expectedIntent.CreatedAt, retrievedIntent.CreatedAt)
|
||||
assert.WithinRange(t, retrievedIntent.UpdatedAt, beforeUpdate, afterUpdate)
|
||||
assert.Equal(t, expectedIntent.IDPID, retrievedIntent.IDPID)
|
||||
assert.Equal(t, expectedIntent.IDPUser, retrievedIntent.IDPUser)
|
||||
assert.Equal(t, expectedIntent.IDPUserID, retrievedIntent.IDPUserID)
|
||||
assert.Equal(t, expectedIntent.IDPUsername, retrievedIntent.IDPUsername)
|
||||
assert.Equal(t, expectedIntent.UserID, retrievedIntent.UserID)
|
||||
assert.Equal(t, expectedIntent.IDPAccessToken, retrievedIntent.IDPAccessToken)
|
||||
assert.Equal(t, expectedIntent.IDPIDToken, retrievedIntent.IDPIDToken)
|
||||
assert.Equal(t, expectedIntent.EntryAttributes, retrievedIntent.EntryAttributes)
|
||||
assert.Equal(t, expectedIntent.RequestID, retrievedIntent.RequestID)
|
||||
assert.Equal(t, expectedIntent.Assertion, retrievedIntent.Assertion)
|
||||
if expectedIntent.State == domain.IDPIntentStateSucceeded {
|
||||
require.NotNil(t, retrievedIntent.SucceededAt)
|
||||
assert.WithinRange(t, *retrievedIntent.SucceededAt, beforeUpdate, afterUpdate)
|
||||
require.NotNil(t, retrievedIntent.ExpiresAt)
|
||||
assert.WithinRange(t, *retrievedIntent.ExpiresAt, beforeUpdate.AddDate(0, 0, 1), afterUpdate.AddDate(0, 0, 1))
|
||||
}
|
||||
if expectedIntent.State == domain.IDPIntentStateFailed {
|
||||
require.NotNil(t, retrievedIntent.FailedAt)
|
||||
assert.WithinRange(t, *retrievedIntent.FailedAt, beforeUpdate, afterUpdate)
|
||||
}
|
||||
assert.Equal(t, expectedIntent.FailReason, retrievedIntent.FailReason)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeleteIDPIntent(t *testing.T) {
|
||||
tx, err := pool.Begin(t.Context(), nil)
|
||||
require.NoError(t, err)
|
||||
defer func() {
|
||||
err := tx.Rollback(t.Context())
|
||||
require.NoError(t, err)
|
||||
}()
|
||||
|
||||
instanceID := createInstance(t, tx)
|
||||
orgID := createOrganization(t, tx, instanceID)
|
||||
idpID := createIdentityProvider(t, tx, instanceID, orgID)
|
||||
intentID := createIDPIntent(t, tx, instanceID, idpID)
|
||||
otherIntentID := createIDPIntent(t, tx, instanceID, idpID)
|
||||
createIDPIntent(t, tx, instanceID, idpID)
|
||||
idpIntentRepo := repository.IDPIntentRepository()
|
||||
|
||||
tt := []struct {
|
||||
testName string
|
||||
inputConditions database.Condition
|
||||
expectedError error
|
||||
expectedDeletedCount int64
|
||||
}{
|
||||
{
|
||||
testName: "when PK condition not set should return missing condition error",
|
||||
inputConditions: idpIntentRepo.StateCondition(domain.IDPIntentStateFailed),
|
||||
expectedError: database.NewMissingConditionError(nil),
|
||||
},
|
||||
{
|
||||
testName: "when condition matches record should delete matching record",
|
||||
inputConditions: idpIntentRepo.PrimaryKeyCondition(instanceID, intentID),
|
||||
expectedDeletedCount: 1,
|
||||
},
|
||||
{
|
||||
testName: "when conditions matches record should delete matching records",
|
||||
inputConditions: database.Or(
|
||||
idpIntentRepo.PrimaryKeyCondition(instanceID, intentID),
|
||||
idpIntentRepo.PrimaryKeyCondition(instanceID, otherIntentID),
|
||||
),
|
||||
expectedDeletedCount: 2,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range tt {
|
||||
t.Run(tc.testName, func(t *testing.T) {
|
||||
savePoint, err := tx.Begin(t.Context())
|
||||
require.NoError(t, err)
|
||||
defer func() {
|
||||
err := savePoint.Rollback(t.Context())
|
||||
require.NoError(t, err)
|
||||
}()
|
||||
|
||||
// Test
|
||||
deleteCount, err := idpIntentRepo.Delete(t.Context(), savePoint, tc.inputConditions)
|
||||
|
||||
// Verify
|
||||
assert.ErrorIs(t, err, tc.expectedError)
|
||||
assert.Equal(t, tc.expectedDeletedCount, deleteCount)
|
||||
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -4,10 +4,13 @@ import (
|
||||
"context"
|
||||
"fmt"
|
||||
"log"
|
||||
"net/url"
|
||||
"os"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/brianvoe/gofakeit/v6"
|
||||
"github.com/muhlemmer/gu"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"github.com/zitadel/zitadel/backend/v3/domain"
|
||||
@@ -161,3 +164,49 @@ func createProjectGrant(t *testing.T, tx database.Transaction, instanceID, grant
|
||||
|
||||
return projectGrant.ID
|
||||
}
|
||||
|
||||
func createIdentityProvider(t *testing.T, tx database.Transaction, instanceID, orgID string) string {
|
||||
t.Helper()
|
||||
idp := domain.IdentityProvider{
|
||||
InstanceID: instanceID,
|
||||
OrgID: &orgID,
|
||||
ID: gofakeit.UUID(),
|
||||
State: domain.IDPStateActive,
|
||||
Name: gofakeit.Name(),
|
||||
Type: gu.Ptr(domain.IDPTypeOIDC),
|
||||
AllowCreation: true,
|
||||
AllowAutoCreation: true,
|
||||
AllowAutoUpdate: true,
|
||||
AllowLinking: true,
|
||||
StylingType: &stylingType,
|
||||
Payload: []byte("{}"),
|
||||
}
|
||||
idpRepo := repository.IDProviderRepository()
|
||||
err := idpRepo.Create(t.Context(), tx, &idp)
|
||||
require.NoError(t, err)
|
||||
|
||||
return idp.ID
|
||||
}
|
||||
|
||||
func createIDPIntent(t *testing.T, tx database.Transaction, instanceID, idpID string) string {
|
||||
t.Helper()
|
||||
successURL, err := url.Parse("https://example.com/success")
|
||||
require.NoError(t, err)
|
||||
failURL, err := url.Parse("https://example.com/fail")
|
||||
require.NoError(t, err)
|
||||
|
||||
intent := domain.IDPIntent{
|
||||
ID: gofakeit.UUID(),
|
||||
InstanceID: instanceID,
|
||||
SuccessURL: successURL,
|
||||
FailureURL: failURL,
|
||||
IDPID: idpID,
|
||||
IDPArguments: map[string]any{"arg1": map[string]any{"k1": 1, "k2": "v2"}},
|
||||
CreatedAt: time.Now(),
|
||||
}
|
||||
idpIntentRepo := repository.IDPIntentRepository()
|
||||
err = idpIntentRepo.Create(t.Context(), tx, &intent)
|
||||
require.NoError(t, err)
|
||||
|
||||
return intent.ID
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user