feat: Add recovery code MFA support (#9954)

<!--
Please inform yourself about the contribution guidelines on submitting a
PR here:
https://github.com/zitadel/zitadel/blob/main/CONTRIBUTING.md#submit-a-pull-request-pr.
Take note of how PR/commit titles should be written and replace the
template texts in the sections below. Don't remove any of the sections.
It is important that the commit history clearly shows what is changed
and why.
Important: By submitting a contribution you agree to the terms from our
Licensing Policy as described here:
https://github.com/zitadel/zitadel/blob/main/LICENSING.md#community-contributions.
-->

One-time recovery codes are a common multi-factor authentication (MFA)
backup method, letting users access their account if they lose other MFA
devices. Support for recovery codes can also reduce support burden for
users locked out of their accounts and provide a more secure and
reliable form of verification than security questions.

# Which Problems Are Solved

Zitadel currently lacks support for recovery codes.

# How the Problems Are Solved

This PR partially addresses recovery code support in Zitadel.
Importantly, it adds recovery codes as a new 2FA `Factor` and an
additional `Check` type for the Session API.

```
Example recovery code flow:

1. User generates N new recovery codes using `POST /v2/users/{user_id}/recovery_codes`
2. Zitadel hashes and stores these codes and returns the un-hashed codes in the response
3. User creates new session with an additional check: `recoveryCode`
4. Code is checked against hash and, if valid, cannot be used again
5. User attempts to adds N more codes using the same endpoint 
6. If `remaining_codes + N <= RecoveryCodes->MaxCount` config value, then recovery codes are added in addition to original codes
7. User can remove all recovery codes using `DEL /v2/users/:userId/recovery_codes` 
```
This PR adds: 
- [x] Session recovery_code check support on `POST+PATCH /v2/sessions`
endpoints
- [x] Adds `mfa_recovery_code_checked_at` column (default null) to
`projections.sessions8` table
- [x] Support for `SECOND_FACTOR_TYPE_RECOVERY_CODES` as available 2FA
method on login policy
- [x] Support for importing recovery codes in /import code

Missing, will _not_ implement in this PR:
- [ ] Admin console support for displaying Recovery Code settings for
user(s)
- [ ] Zitadel Typescript login support for recovery codes 

TODO: 
- [x] Additional unit and integration tests
- [x] Error translations

# Additional Changes

None

# Additional Context

- Closes #6898

---------

Co-authored-by: Livio Spring <[email protected]>
This commit is contained in:
Zach Hirschtritt
2025-11-24 06:44:48 +00:00
committed by GitHub
co-authored by Livio Spring
parent afa92e55f7
commit 5beeb5738a
101 changed files with 3397 additions and 169 deletions
+189
View File
@@ -1283,6 +1283,195 @@ func TestCheckTOTP(t *testing.T) {
}
}
func TestCheckRecoveryCode(t *testing.T) {
ctx := authz.NewMockContext("instance1", "org1", "user1")
sessAgg := &session.NewAggregate("session1", "instance1").Aggregate
userAgg := &user.NewAggregate("user1", "org1").Aggregate
orgAgg := &org.NewAggregate("org1").Aggregate
hasher := mockPasswordHasher("x")
hashedCodes, rawCodes, err := domain.GenerateRecoveryCodes(ctx, 1, domain.RecoveryCodesConfig{
Format: domain.RecoveryCodeFormatUUID,
MaxCount: 10,
Length: 10,
}, hasher)
require.NoError(t, err)
validCode := rawCodes[0]
invalidCode := "invalid-code"
type fields struct {
sessionWriteModel *SessionWriteModel
eventstore func(*testing.T) *eventstore.Eventstore
hasher *crypto.Hasher
}
tests := []struct {
name string
code string
fields fields
wantEventCommands []eventstore.Command
wantErrorCommands []eventstore.Command
wantErr error
}{
{
name: "missing userID",
code: validCode,
fields: fields{
sessionWriteModel: &SessionWriteModel{
aggregate: sessAgg,
},
eventstore: expectEventstore(),
hasher: hasher,
},
wantErr: zerrors.ThrowInvalidArgument(nil, "COMMAND-4m9s2", "Errors.User.UserIDMissing"),
},
{
name: "filter error",
code: validCode,
fields: fields{
sessionWriteModel: &SessionWriteModel{
UserID: "user1",
aggregate: sessAgg,
},
eventstore: expectEventstore(
expectFilterError(io.ErrClosedPipe),
),
hasher: hasher,
},
wantErr: io.ErrClosedPipe,
},
{
name: "recovery codes not ready",
code: validCode,
fields: fields{
sessionWriteModel: &SessionWriteModel{
UserID: "user1",
aggregate: sessAgg,
},
eventstore: expectEventstore(
expectFilter(), // No codes added
),
hasher: hasher,
},
wantErr: zerrors.ThrowPreconditionFailed(nil, "COMMAND-84rgg", "Errors.User.MFA.RecoveryCodes.NotReady"),
},
{
name: "invalid code",
code: invalidCode,
fields: fields{
sessionWriteModel: &SessionWriteModel{
UserID: "user1",
aggregate: sessAgg,
},
eventstore: expectEventstore(
expectFilter(
eventFromEventPusher(
user.NewHumanRecoveryCodesAddedEvent(ctx, userAgg, hashedCodes, nil),
),
),
expectFilter(), // additional lock check
expectFilter(
eventFromEventPusher(org.NewLockoutPolicyAddedEvent(ctx, orgAgg, 0, 0, false)),
),
),
hasher: hasher,
},
wantErrorCommands: []eventstore.Command{
user.NewHumanRecoveryCodeCheckFailedEvent(ctx, userAgg, nil),
},
wantErr: zerrors.ThrowInvalidArgument(nil, "DOMAIN-6uvh0", "Errors.User.MFA.RecoveryCodes.InvalidCode"),
},
{
name: "invalid code, locked",
code: invalidCode,
fields: fields{
sessionWriteModel: &SessionWriteModel{
UserID: "user1",
aggregate: sessAgg,
},
eventstore: expectEventstore(
expectFilter(
eventFromEventPusher(
user.NewHumanRecoveryCodesAddedEvent(ctx, userAgg, hashedCodes, nil),
),
),
expectFilter(), // additional lock check
expectFilter(
eventFromEventPusher(org.NewLockoutPolicyAddedEvent(ctx, orgAgg, 1, 1, false)),
),
),
hasher: hasher,
},
wantErrorCommands: []eventstore.Command{
user.NewHumanRecoveryCodeCheckFailedEvent(ctx, userAgg, nil),
user.NewUserLockedEvent(ctx, userAgg),
},
wantErr: zerrors.ThrowInvalidArgument(nil, "DOMAIN-6uvh0", "Errors.User.MFA.RecoveryCodes.InvalidCode"),
},
{
name: "user locked",
code: validCode,
fields: fields{
sessionWriteModel: &SessionWriteModel{
UserID: "user1",
aggregate: sessAgg,
},
eventstore: expectEventstore(
expectFilter(
eventFromEventPusher(
user.NewHumanRecoveryCodesAddedEvent(ctx, userAgg, hashedCodes, nil),
),
eventFromEventPusher(
user.NewUserLockedEvent(ctx, userAgg),
),
),
),
hasher: hasher,
},
wantErr: zerrors.ThrowPreconditionFailed(nil, "COMMAND-2w6oa", "Errors.User.Locked"),
},
{
name: "ok",
code: validCode,
fields: fields{
sessionWriteModel: &SessionWriteModel{
UserID: "user1",
aggregate: sessAgg,
},
eventstore: expectEventstore(
expectFilter(
eventFromEventPusher(
user.NewHumanRecoveryCodesAddedEvent(ctx, userAgg, hashedCodes, nil),
),
),
expectFilter(), // additional lock check
),
hasher: hasher,
},
wantEventCommands: []eventstore.Command{
user.NewHumanRecoveryCodeCheckSucceededEvent(ctx, userAgg, "$plain$x$"+validCode, nil),
session.NewRecoveryCodeCheckedEvent(ctx, sessAgg, testNow),
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
cmd := &SessionCommands{
sessionWriteModel: tt.fields.sessionWriteModel,
eventstore: tt.fields.eventstore(t),
hasher: tt.fields.hasher,
now: func() time.Time { return testNow },
}
gotCmds, err := CheckRecoveryCode(tt.code)(ctx, cmd)
require.ErrorIs(t, err, tt.wantErr)
assert.Equal(t, tt.wantErrorCommands, gotCmds)
assert.Equal(t, tt.wantEventCommands, cmd.eventCommands)
})
}
}
func TestCommands_TerminateSession(t *testing.T) {
type fields struct {
eventstore func(t *testing.T) *eventstore.Eventstore