feat: allow managing invite code in secret generators (#12109)

# Which Problems Are Solved

Zitadel exposes the secrets generator configuration through its admin
api. This allows instance admins to manage them on their own and they
can create overwrite the system / runtime defaults (incl. expiration).
This very much needed in multi-instance scenarios such as zitadel.cloud.
Currently the invite code configuration was not manageable through the
API, but only runtime config.

# How the Problems Are Solved

- added the `invite_code` type to the API allowing it to be set and
retrieved.
- added the type to console's management list
- added the type to be stored on instance setup
- change the `GetSecretGenerator` endpoint to fall back to the runtime
config if no config is stored on the instance itself
- ensure the `length` and at least one charset is enabled, return an
error otherwise
- expiry is not enforced, so 0 allows codes with no expiry (current
state)

# Additional Changes

None

# Additional Context

- closes https://github.com/zitadel/zitadel/issues/10474
This commit is contained in:
Livio Spring
2026-07-01 04:53:16 +00:00
committed by GitHub
parent 782133dbc7
commit 1e0b810dca
44 changed files with 351 additions and 62 deletions
@@ -105,6 +105,8 @@ func SecretGeneratorTypeToPb(generatorType domain.SecretGeneratorType) settings_
return settings_pb.SecretGeneratorType_SECRET_GENERATOR_TYPE_OTP_SMS
case domain.SecretGeneratorTypeOTPEmail:
return settings_pb.SecretGeneratorType_SECRET_GENERATOR_TYPE_OTP_EMAIL
case domain.SecretGeneratorTypeInviteCode:
return settings_pb.SecretGeneratorType_SECRET_GENERATOR_TYPE_INVITE_CODE
default:
return settings_pb.SecretGeneratorType_SECRET_GENERATOR_TYPE_UNSPECIFIED
}
@@ -128,6 +130,8 @@ func SecretGeneratorTypeToDomain(generatorType settings_pb.SecretGeneratorType)
return domain.SecretGeneratorTypeOTPSMS
case settings_pb.SecretGeneratorType_SECRET_GENERATOR_TYPE_OTP_EMAIL:
return domain.SecretGeneratorTypeOTPEmail
case settings_pb.SecretGeneratorType_SECRET_GENERATOR_TYPE_INVITE_CODE:
return domain.SecretGeneratorTypeInviteCode
default:
return domain.SecretGeneratorTypeUnspecified
}
+17
View File
@@ -163,6 +163,22 @@ type SecretGenerators struct {
SigningKey *crypto.GeneratorConfig
}
func (s *SecretGenerators) ToMap() map[domain.SecretGeneratorType]*crypto.GeneratorConfig {
return map[domain.SecretGeneratorType]*crypto.GeneratorConfig{
domain.SecretGeneratorTypeInitCode: s.InitializeUserCode,
domain.SecretGeneratorTypeVerifyEmailCode: s.EmailVerificationCode,
domain.SecretGeneratorTypeVerifyPhoneCode: s.PhoneVerificationCode,
domain.SecretGeneratorTypeVerifyDomain: s.DomainVerification,
domain.SecretGeneratorTypePasswordResetCode: s.PasswordVerificationCode,
domain.SecretGeneratorTypePasswordlessInitCode: s.PasswordlessInitCode,
domain.SecretGeneratorTypeAppSecret: s.ClientSecret,
domain.SecretGeneratorTypeOTPSMS: s.OTPSMS,
domain.SecretGeneratorTypeOTPEmail: s.OTPEmail,
domain.SecretGeneratorTypeInviteCode: s.InviteCode,
domain.SecretGeneratorTypeSigningKey: s.SigningKey,
}
}
type ZitadelConfig struct {
instanceID string
orgID string
@@ -326,6 +342,7 @@ func setupInstanceElements(instanceAgg *instance.Aggregate, setup *InstanceSetup
prepareAddSecretGeneratorConfig(instanceAgg, domain.SecretGeneratorTypeVerifyDomain, setup.SecretGenerators.DomainVerification),
prepareAddSecretGeneratorConfig(instanceAgg, domain.SecretGeneratorTypeOTPSMS, setup.SecretGenerators.OTPSMS),
prepareAddSecretGeneratorConfig(instanceAgg, domain.SecretGeneratorTypeOTPEmail, setup.SecretGenerators.OTPEmail),
prepareAddSecretGeneratorConfig(instanceAgg, domain.SecretGeneratorTypeInviteCode, setup.SecretGenerators.InviteCode),
prepareAddDefaultPasswordComplexityPolicy(
instanceAgg,
+6 -3
View File
@@ -35,8 +35,8 @@ func prepareAddSecretGeneratorConfig(a *instance.Aggregate, typ domain.SecretGen
if !typ.Valid() {
return nil, zerrors.ThrowInvalidArgument(nil, "V2-FGqVj", "Errors.InvalidArgument")
}
if config.Length < 1 {
return nil, zerrors.ThrowInvalidArgument(nil, "V2-jEqCt", "Errors.InvalidArgument")
if err := config.Valid(); err != nil {
return nil, err
}
return func(ctx context.Context, filter preparation.FilterToQueryReducer) ([]eventstore.Command, error) {
writeModel := NewInstanceSecretGeneratorConfigWriteModel(ctx, typ)
@@ -71,9 +71,12 @@ func prepareAddSecretGeneratorConfig(a *instance.Aggregate, typ domain.SecretGen
}
func (c *Commands) ChangeSecretGeneratorConfig(ctx context.Context, generatorType domain.SecretGeneratorType, config *crypto.GeneratorConfig) (*domain.ObjectDetails, error) {
if generatorType == domain.SecretGeneratorTypeUnspecified {
if !generatorType.Valid() {
return nil, zerrors.ThrowInvalidArgument(nil, "COMMAND-33k9f", "Errors.SecretGenerator.TypeMissing")
}
if err := config.Valid(); err != nil {
return nil, err
}
generatorWriteModel, err := c.getSecretConfig(ctx, generatorType)
if err != nil {
+63 -27
View File
@@ -2,6 +2,7 @@ package command
import (
"context"
"errors"
"testing"
"time"
@@ -218,6 +219,52 @@ func TestCommandSide_ChangeSecretGenerator(t *testing.T) {
},
},
},
{
name: "secret generator config invalid (length), invalid error",
fields: fields{
eventstore: expectEventstore(),
},
args: args{
ctx: authz.WithInstanceID(context.Background(), "INSTANCE"),
generator: &crypto.GeneratorConfig{
Length: 0,
Expiry: 2 * time.Hour,
IncludeLowerLetters: true,
IncludeUpperLetters: true,
IncludeDigits: true,
IncludeSymbols: true,
},
generatorType: domain.SecretGeneratorTypeInitCode,
},
res: res{
err: func(err error) bool {
return errors.Is(err, zerrors.ThrowInvalidArgument(nil, "CRYPTO-FVJ2x", "Errors.InvalidArgument"))
},
},
},
{
name: "secret generator config invalid (charset), invalid error",
fields: fields{
eventstore: expectEventstore(),
},
args: args{
ctx: authz.WithInstanceID(context.Background(), "INSTANCE"),
generator: &crypto.GeneratorConfig{
Length: 8,
Expiry: 2 * time.Hour,
IncludeLowerLetters: false,
IncludeUpperLetters: false,
IncludeDigits: false,
IncludeSymbols: false,
},
generatorType: domain.SecretGeneratorTypeInitCode,
},
res: res{
err: func(err error) bool {
return errors.Is(err, zerrors.ThrowInvalidArgument(nil, "CRYPTO-Ckl2s", "Errors.InvalidArgument"))
},
},
},
{
name: "generator removed, new added ok",
fields: fields{
@@ -332,15 +379,21 @@ func TestCommandSide_ChangeSecretGenerator(t *testing.T) {
),
),
expectPush(
newSecretGeneratorChangedEvent(context.Background(),
domain.SecretGeneratorTypeInitCode,
8,
time.Hour*2,
false,
false,
false,
false,
),
func() *instance.SecretGeneratorChangedEvent {
changes := []instance.SecretGeneratorChanges{
instance.ChangeSecretGeneratorLength(8),
instance.ChangeSecretGeneratorExpiry(2 * time.Hour),
instance.ChangeSecretGeneratorIncludeUpperLetters(false),
instance.ChangeSecretGeneratorIncludeDigits(false),
instance.ChangeSecretGeneratorIncludeSymbols(false),
}
event, _ := instance.NewSecretGeneratorChangeEvent(context.Background(),
&instance.NewAggregate("INSTANCE").Aggregate,
domain.SecretGeneratorTypeInitCode,
changes,
)
return event
}(),
),
),
},
@@ -349,7 +402,7 @@ func TestCommandSide_ChangeSecretGenerator(t *testing.T) {
generator: &crypto.GeneratorConfig{
Length: 8,
Expiry: 2 * time.Hour,
IncludeLowerLetters: false,
IncludeLowerLetters: true,
IncludeUpperLetters: false,
IncludeDigits: false,
IncludeSymbols: false,
@@ -523,20 +576,3 @@ func TestCommandSide_RemoveSecretGenerator(t *testing.T) {
})
}
}
func newSecretGeneratorChangedEvent(ctx context.Context, generatorType domain.SecretGeneratorType, length uint, expiry time.Duration, lowerCase, upperCase, digits, symbols bool) *instance.SecretGeneratorChangedEvent {
changes := []instance.SecretGeneratorChanges{
instance.ChangeSecretGeneratorLength(length),
instance.ChangeSecretGeneratorExpiry(expiry),
instance.ChangeSecretGeneratorIncludeLowerLetters(lowerCase),
instance.ChangeSecretGeneratorIncludeUpperLetters(upperCase),
instance.ChangeSecretGeneratorIncludeDigits(digits),
instance.ChangeSecretGeneratorIncludeSymbols(symbols),
}
event, _ := instance.NewSecretGeneratorChangeEvent(ctx,
&instance.NewAggregate("INSTANCE").Aggregate,
generatorType,
changes,
)
return event
}
+3
View File
@@ -331,6 +331,7 @@ func instanceElementsFilters() []expect {
expectFilter(),
expectFilter(),
expectFilter(),
expectFilter(),
}
}
@@ -348,6 +349,7 @@ func instanceElementsEvents(ctx context.Context, instanceID, instanceName string
instance.NewSecretGeneratorAddedEvent(ctx, &instanceAgg.Aggregate, domain.SecretGeneratorTypeVerifyDomain, 32, 0, true, true, true, false),
instance.NewSecretGeneratorAddedEvent(ctx, &instanceAgg.Aggregate, domain.SecretGeneratorTypeOTPSMS, 8, 5*time.Minute, false, false, true, false),
instance.NewSecretGeneratorAddedEvent(ctx, &instanceAgg.Aggregate, domain.SecretGeneratorTypeOTPEmail, 8, 5*time.Minute, false, false, true, false),
instance.NewSecretGeneratorAddedEvent(ctx, &instanceAgg.Aggregate, domain.SecretGeneratorTypeInviteCode, 6, 72*time.Hour, false, true, true, false),
}
}
@@ -362,6 +364,7 @@ func instanceElementsConfig() *SecretGenerators {
DomainVerification: &crypto.GeneratorConfig{Length: 32, IncludeLowerLetters: true, IncludeUpperLetters: true, IncludeDigits: true},
OTPSMS: &crypto.GeneratorConfig{Length: 8, Expiry: 5 * time.Minute, IncludeDigits: true},
OTPEmail: &crypto.GeneratorConfig{Length: 8, Expiry: 5 * time.Minute, IncludeDigits: true},
InviteCode: &crypto.GeneratorConfig{Length: 6, Expiry: 72 * time.Hour, IncludeUpperLetters: true, IncludeDigits: true},
}
}
+10
View File
@@ -23,6 +23,16 @@ type GeneratorConfig struct {
IncludeSymbols bool
}
func (c *GeneratorConfig) Valid() error {
if c.Length < 1 {
return zerrors.ThrowInvalidArgument(nil, "CRYPTO-FVJ2x", "Errors.InvalidArgument")
}
if !c.IncludeLowerLetters && !c.IncludeUpperLetters && !c.IncludeDigits && !c.IncludeSymbols {
return zerrors.ThrowInvalidArgument(nil, "CRYPTO-Ckl2s", "Errors.InvalidArgument")
}
return nil
}
//go:generate mockgen -source code.go -destination ./code_mock.go -package crypto
type Generator interface {
@@ -1584,8 +1584,12 @@ func setSecretGeneratorSettingsAttrs(generatorType legacy_domain.SecretGenerator
secretGeneratorSettingsAttrs.OTPEmail = &domain.OTPEmailAttributes{
SecretGeneratorAttrsWithExpiry: attrsWithExpiry,
}
case legacy_domain.SecretGeneratorTypeInviteCode, legacy_domain.SecretGeneratorTypeSigningKey:
// do nothing as these secret generators are not persisted in the settings
case legacy_domain.SecretGeneratorTypeInviteCode:
secretGeneratorSettingsAttrs.InviteCode = &domain.InviteCodeAttributes{
SecretGeneratorAttrsWithExpiry: attrsWithExpiry,
}
case legacy_domain.SecretGeneratorTypeSigningKey:
// do nothing as this secret generator is not persisted in the settings
case legacy_domain.SecretGeneratorTypeUnspecified:
return domain.SecretGeneratorSettingsAttributes{}, zerrors.ThrowInvalidArgumentf(nil, "HANDL-2n3fK", "unspecified secret generator type")
default:
+3
View File
@@ -45,6 +45,7 @@ type Queries struct {
zitadelRoles []authz.RoleMapping
multifactors domain.MultifactorConfigs
defaultAuditLogRetention time.Duration
defaultSecretGenerators map[domain.SecretGeneratorType]*crypto.GeneratorConfig
}
func StartQueries(
@@ -62,6 +63,7 @@ func StartQueries(
defaultAuditLogRetention time.Duration,
systemAPIUsers map[string]*authz.SystemAPIUser,
startProjections bool,
secretGeneratorDefaults map[domain.SecretGeneratorType]*crypto.GeneratorConfig,
) (repo *Queries, err error) {
repo = &Queries{
eventstore: es,
@@ -84,6 +86,7 @@ func StartQueries(
},
},
defaultAuditLogRetention: defaultAuditLogRetention,
defaultSecretGenerators: secretGeneratorDefaults,
}
repo.checkPermission = permissionCheck(repo)
+107
View File
@@ -9,6 +9,12 @@ import (
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/zitadel/zitadel/internal/api/authz"
"github.com/zitadel/zitadel/internal/crypto"
"github.com/zitadel/zitadel/internal/database"
"github.com/zitadel/zitadel/internal/domain"
"github.com/zitadel/zitadel/internal/zerrors"
)
@@ -70,6 +76,9 @@ var (
"include_symbols",
"count",
}
expectedSecretGeneratorByTypeQuery = regexp.QuoteMeta(prepareSecretGeneratorStmt +
` WHERE projections.secret_generators2.generator_type = $1 AND projections.secret_generators2.instance_id = $2`)
secretGeneratorByTypeInstanceID = "instanceID"
)
func Test_SecretGeneratorsPrepares(t *testing.T) {
@@ -314,3 +323,101 @@ func Test_SecretGeneratorsPrepares(t *testing.T) {
})
}
}
func TestQueries_SecretGeneratorByType(t *testing.T) {
ctx := authz.NewMockContext(secretGeneratorByTypeInstanceID, "orgID", "loginClient")
generatorType := domain.SecretGeneratorTypeInviteCode
queryArgs := []driver.Value{generatorType, secretGeneratorByTypeInstanceID}
inviteCodeDefault := &crypto.GeneratorConfig{
Length: 6,
Expiry: 72 * time.Hour,
IncludeUpperLetters: true,
IncludeDigits: true,
}
tests := []struct {
name string
mock sqlExpectation
defaultSecretGenerators map[domain.SecretGeneratorType]*crypto.GeneratorConfig
want *SecretGenerator
wantErr error
}{
{
name: "found in DB",
mock: mockQuery(expectedSecretGeneratorByTypeQuery, prepareSecretGeneratorCols, []driver.Value{
"agg-id",
domain.SecretGeneratorTypeInviteCode,
testNow,
testNow,
"ro",
uint64(20211108),
6,
72 * time.Hour,
false,
true,
true,
false,
}, queryArgs...),
want: &SecretGenerator{
AggregateID: "agg-id",
GeneratorType: domain.SecretGeneratorTypeInviteCode,
CreationDate: testNow,
ChangeDate: testNow,
ResourceOwner: "ro",
Sequence: 20211108,
Length: 6,
Expiry: 72 * time.Hour,
IncludeLowerLetters: false,
IncludeUpperLetters: true,
IncludeDigits: true,
IncludeSymbols: false,
},
},
{
name: "not found, default exists",
mock: mockQueryErr(expectedSecretGeneratorByTypeQuery, sql.ErrNoRows, queryArgs...),
defaultSecretGenerators: map[domain.SecretGeneratorType]*crypto.GeneratorConfig{
domain.SecretGeneratorTypeInviteCode: inviteCodeDefault,
},
want: &SecretGenerator{
AggregateID: secretGeneratorByTypeInstanceID,
ResourceOwner: secretGeneratorByTypeInstanceID,
GeneratorType: domain.SecretGeneratorTypeInviteCode,
Length: 6,
Expiry: 72 * time.Hour,
IncludeUpperLetters: true,
IncludeDigits: true,
},
},
{
name: "not found, no default",
mock: mockQueryErr(expectedSecretGeneratorByTypeQuery, sql.ErrNoRows, queryArgs...),
defaultSecretGenerators: map[domain.SecretGeneratorType]*crypto.GeneratorConfig{},
wantErr: sql.ErrNoRows,
},
{
name: "DB internal error",
mock: mockQueryErr(expectedSecretGeneratorByTypeQuery, sql.ErrConnDone, queryArgs...),
wantErr: sql.ErrConnDone,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
execMock(t, tt.mock, func(db *sql.DB) {
q := &Queries{
client: &database.DB{
DB: db,
},
defaultSecretGenerators: tt.defaultSecretGenerators,
}
got, err := q.SecretGeneratorByType(ctx, generatorType)
if tt.wantErr != nil {
require.ErrorIs(t, err, tt.wantErr)
} else {
require.NoError(t, err)
}
assert.Equal(t, tt.want, got)
})
})
}
}
+23 -2
View File
@@ -139,8 +139,29 @@ func (q *Queries) SecretGeneratorByType(ctx context.Context, generatorType domai
generator, err = scan(row)
return err
}, query, args...)
logging.OnError(err).WithField("type", generatorType).WithField("instance_id", instanceID).Error("secret generator by type")
return generator, err
if err == nil {
return generator, nil
}
if !errors.Is(err, sql.ErrNoRows) {
logging.OnError(err).WithField("type", generatorType).WithField("instance_id", instanceID).Error("secret generator by type")
return nil, err
}
// if the config was not (yet) stored on the database, fall back to the system / runtime config
defaultConfig, ok := q.defaultSecretGenerators[generatorType]
if !ok {
return nil, err // return the initial not found error
}
return &SecretGenerator{
AggregateID: instanceID,
ResourceOwner: instanceID,
GeneratorType: generatorType,
Length: defaultConfig.Length,
Expiry: defaultConfig.Expiry,
IncludeLowerLetters: defaultConfig.IncludeLowerLetters,
IncludeUpperLetters: defaultConfig.IncludeUpperLetters,
IncludeDigits: defaultConfig.IncludeDigits,
IncludeSymbols: defaultConfig.IncludeSymbols,
}, nil
}
func (q *Queries) SearchSecretGenerators(ctx context.Context, queries *SecretGeneratorSearchQueries) (secretGenerators *SecretGenerators, err error) {