Repository navigation
feat: implement multi-factor authentication (MFA) support - #679
Conversation
- Added MFA functionality including TOTP and recovery codes. - Introduced new DTOs for MFA requests and responses. - Updated login handler to support MFA challenges. - Created MFA handler for enrollment, confirmation, and management of MFA settings. - Implemented IP allow-listing for enhanced security. - Added database migrations for MFA and IP allow-listing. - Updated error handling to include MFA-related errors. - Enhanced tests to cover new MFA features and ensure proper functionality.
There was a problem hiding this comment.
ℹ️ No critical issues — the implementation is careful and well-tested. Two design scoping caveats and one minor generator nit below.
Reviewed changes
- TOTP (RFC 6238) — hand-rolled SHA-1 / 6-digit / 30 s with ±1 step skew and replay rejection through
last_used_step; checked against the RFC vectors. - Two-step login —
Loginnow takesLoginInputand, onErrRequired, returns a signedmfa_challenge(no cookies) that onlyCompleteMFALoginaccepts; the challenge kind is rejected as an access or refresh token. - Gate —
mfasvc.Service.CheckLoginenforces the IP allow-lists, then the second factor, after the password and again at the code step; an unparseable client address fails closed. - Recovery codes — 8 single-use SHA-256-hashed codes; disable/regenerate require a current factor.
- Forced enrollment —
/auth/mfa/setup[/confirm]authenticate by password for a policy-subject account that cannot sign in yet, refusing when MFA is already enabled. - Admin controls —
GET/PUT /admin/auth-security, per-user allowed-cidrs,DELETE /users/{id}/mfa, gated by the new root-equivalentsettings.security:write(SUPER_ADMIN's*only; ADMIN's exactsettings:writedoes not carry it). - Migration 000077 and the web restructure ("My Profile" → "Account", challenge/setup/security UI, all 9 locales).
ℹ️ require_mfa does not protect a not-yet-enrolled account from a password-only caller
The rollout flow lets a caller who knows only the password establish a second factor on a policy-subject account that has not enrolled yet: POST /auth/login returns AUTH_MFA_SETUP_REQUIRED, then POST /auth/mfa/setup + /auth/mfa/setup/confirm (password-authenticated) bind a factor the caller controls, after which POST /auth/login with that code issues a full session. The Enabled guards do prevent swapping an existing factor, but not establishing one. So for the exact population require_mfa is rolled out to protect, a password-only attacker can self-enroll and proceed. This is a deliberate tradeoff — the PR body calls it out as avoiding lockout when the switch is turned on — so I am flagging it as a caveat, not a defect. If the rollout window matters, consider gating password-only enrollment on the account actually being policy-subject, or issuing an admin-signed enrollment token.
Technical details
# Password-only MFA enrollment on a policy-subject account
## Affected sites
- `services/api/internal/transport/http/handler/mfa_handler.go:162` — `SetupBegin` (`passwordUser` → `svc.Begin`)
- `services/api/internal/transport/http/handler/mfa_handler.go:181` — `SetupConfirm` (`passwordUser` → `svc.Confirm`)
- `services/api/internal/service/mfa/mfa_service.go:120` — `Begin` only refuses when `enr.Enabled`
- `services/api/internal/transport/http/router/router.go:145` — mounted unauthenticated under `authLimit`
## Required outcome
- Decide whether password-only enrollment should be limited to accounts the policy
actually requires MFA for (currently any account can self-enroll), and whether the
not-yet-enrolled rollout population should require something beyond the password.
## Open questions for the human
- Is racing to enroll before the legitimate user acceptable during rollout?ℹ️ MFA and IP allow-lists are enforced only on the password-login path
Two intentional scoping decisions worth stating plainly, since the admin UI ("people with a protected role must set up an authenticator app before they can sign in") reads broader than the code:
- SSO —
sso_service.go:437callsIssueSessiondirectly, so neitherrequire_mfanor the IP allow-list applies to an SSO sign-in. The settings screen's lockout warning does say "SSO sign-in is not affected", so the UI is accurate, but a privileged user with an SSO provider can always obtain a session without a second factor. - Refresh —
Refresh/RefreshAnnotationnever call the gate, so an allow-listed password login (or a stolen refresh cookie) yields fresh full sessions from any address for the refresh-token lifetime. The domain doc scopes the allow-list to "password login", so this may be by design.
Technical details
# Session issuance bypasses the login gate
## Affected sites
- `services/api/internal/service/sso/sso_service.go:437` — SSO callback issues a session without `CheckLogin`
- `services/api/internal/service/auth/auth_service.go:274` — `Refresh` / `RefreshAnnotation` issue tokens without `CheckLogin`
## Required outcome
- Confirm the intended coverage of `require_mfa` and the IP allow-list for SSO and for
session refresh, and make the admin copy match.deepseek-v4.1-flash (free via Pullfrog for OSS) | 𝕏
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
Reviewed the delta since the prior Pullfrog review (9118b7d → 8c2b604), which addresses the earlier feedback:
- Password-only enrollment narrowed — new
Service.SetupRequiredand handlerrequireSetuprefusePOST /auth/mfa/setup[/confirm]unless the policy requires MFA for the account and it has not enrolled, returningErrSetupNotRequired→403/CodeForbidden. Accounts the policy does not oblige now enroll only from a signed-in session, so a bare password can no longer establish a second factor on an account that could have kept one off. - Recovery codes made unbiased —
newRecoveryCodesnow rejection-samples bytes>= 248instead of takingmod 31, removing the modulo bias; the new test asserts every emitted character is in the alphabet. - SSO scoping copy corrected — the admin "Require two-step verification" description in all 9 locales now states that MFA applies to password sign-in and that SSO defers to the identity provider, matching the code.
- Minor:
ErrSetupNotRequiredmapping added to the presenter (403), and theAllRolesdoc comment reworded.
Note the rollout-window tradeoff the prior review flagged is narrowed, not eliminated: a policy-subject account that has not yet enrolled can still be forced through password-only setup. That remains the deliberate, documented lockout-avoidance tradeoff, so it is not re-raised here.
deepseek-v4.1-flash (free via Pullfrog for OSS) | 𝕏
- Added localization support for error messages related to too many login attempts in multiple languages (Spanish, French, Japanese, Korean, Portuguese, Russian, Vietnamese, Chinese). - Introduced a new `LockedError` type to handle lockout scenarios with retry duration. - Updated the MFA service to track failed attempts and lock accounts after a specified number of failures. - Implemented logic to clear failures upon successful login or confirmation of MFA codes. - Enhanced the API error handling to return appropriate status codes and messages for locked accounts. - Modified database schema to include fields for tracking failed attempts and lockout duration. - Added tests to verify the lockout functionality and ensure proper handling of IP allow lists.
There was a problem hiding this comment.
Important
The new second-factor lockout is well-built for sequential attempts, but its 5-attempt cap is enforced with a check-then-act that is not atomic, so a concurrent burst of code submissions can widen the cap. One minor locked-state UI gap also noted.
Reviewed changes
Reviewed the delta since the prior Pullfrog review (8c2b604 → 1d112c8), which adds second-factor lockout and related hardening:
- Second-factor lockout — added
failed_attempts/locked_untiltouser_mfa, counted byRegisterFailureand cleared byClearFailures; 5 consecutive wrong codes lock for 15 minutes and surface as429withretry_after_seconds/Retry-After, rendered as a localized wait on the web sign-in flows. - Self-lockout guard —
SetPolicynow takesclientIPand refuses an instance IP allow-list that does not contain the saving admin's address (ErrSelfLockout→400). - Setup-path IP enforcement —
requireSetupruns the newCheckIPbefore the password-only setup flow, so that path is no looser than a login. ReplaceRecoveryCodes— regenerating recovery codes writes only the hashes, so it can no longer roll back a concurrent login's advanced replay step or consumed code.- CIDR canonicalization and pending-secret reuse —
NormalizeCIDRsmasks host bits and unmaps IPv4-mapped IPv6;Beginreuses a pending secret younger than 10 minutes instead of invalidating an open QR code. - Audit logging and tests —
slog.Infoon policy / allowed-CIDR / MFA-reset changes, plus Go and Vitest coverage for lockout, self-lockout, pending reuse and CIDR masking.
ℹ️ Locked and self-lockout responses fall through to generic errors in several dialogs
Outside the sign-in form and the MFA challenge page, the new server errors have no matching client handling, so the user is told "something went wrong" rather than why the action was refused.
Technical details
# New locked / self-lockout errors not surfaced
## Affected sites
- `apps/web/src/components/auth/login/MfaLoginSetup.tsx:55` — forced-setup confirm only maps `MfaInvalidCode`; a locked `429` shows `login.errors.genericError`
- `apps/web/src/components/profile/mfa/MfaCodeDialog.tsx:63` — disable / regenerate show `security.mfa.errors.generic` on a locked `429`
- `apps/web/src/components/profile/mfa/MfaSetupDialog.tsx:66` — same for the authenticated setup confirm
- `apps/web/src/components/admin/settings/LoginSecuritySettings.tsx:71` — only `InvalidCidr` is mapped, so an `ErrSelfLockout` (`400`) shows `settings.security.errors.saveFailed` with no hint that the admin's own address is outside the list
## Required outcome
- Surface the lockout wait (reuse `tooManyAttemptsMessage`) in the setup/profile dialogs, and a dedicated message for the self-lockout rejection so the admin knows to include their own address.
## Open questions for the human
- Is a dedicated self-lockout string wanted, or is reusing the invalid-CIDR copy acceptable?deepseek-v4.1-flash (free via Pullfrog for OSS) | 𝕏
There was a problem hiding this comment.
Important
The new per-username login throttle is tripped by anyone who knows a username, so it doubles as an unauthenticated way to lock a target's password login for 15 minutes, repeatably.
Reviewed changes
Reviewed the delta since the prior Pullfrog review (1d112c8 → 12dfd30), which adds a Redis-backed wrong-password throttle:
LoginThrottle— new Redis implementation (login_throttle.go) with an atomic Lua counter: 10 failures within 15 minutes set a 15-minute lock key and reset the counter. Constructed inbootstrap/app.goand installed on bothauthsvc.ServiceandMFAHandler.Loginintegration — checks the lock before touching the user table or bcrypt (so unknown names lock too, preserving the anti-enumeration property), records a failure viafailLogin(LockedError→429with the wait), and resets on a correct password.- Shared with the password-only setup path —
MFAHandler.passwordUsernow consults the same throttle, and resets/fails it the same way. - Message change —
mfadom.ErrLockedis nowtoo many failed attempts, shared by the password and second-factor lockouts. - Tests: Redis-backed throttle test (gated on
PACA_TEST_REDIS_URL) and in-memorymemThrottlecases covering lock-at-max, unknown names, and reset-on-success.
deepseek-v4.1-flash (free via Pullfrog for OSS) | 𝕏
- Added "ip_not_allowed" message to French, Japanese, Korean, Portuguese, Russian, Vietnamese, and Simplified Chinese localization files for authentication errors. feat(routes): introduce profile route - Added a new profile route that redirects to account settings. - Updated route tree to include the new profile route. feat(deploy): add support for trusted proxy hops - Introduced TRUSTED_PROXY_HOPS environment variable to configure the number of reverse proxies. - Updated Docker and Helm configurations to support the new environment variable. feat(api): implement IP address checks for SSO and MFA - Enhanced SSO service to enforce IP allow-lists during login. - Updated MFA service to prevent self-lockout when setting user CIDRs. - Added logic to handle IP checks in the authentication process. fix(auth): improve login security - Implemented a dummy password check to obscure username existence during login attempts. - Enhanced login service to reset throttle on successful login. test(auth): add tests for MFA and login functionality - Added tests to ensure MFA challenge is single-use and that login failures are handled correctly. - Implemented tests for self-lockout prevention when setting user CIDRs. fix(middleware): refine client IP extraction logic - Improved the logic for extracting client IP addresses considering trusted proxy hops.
There was a problem hiding this comment.
ℹ️ No new issues in this incremental delta — it hardens the previously flagged second-factor lockout path and extends IP enforcement to SSO. Nothing here needs action before merge; the open per-username throttle thread remains a design decision for the author.
Reviewed changes
Reviewed the delta since the prior Pullfrog review (12dfd30 → 21e5d0a):
- Closed the second-factor lockout TOCTOU —
AdvanceStepandConsumeRecoveryCodenow re-checklocked_until, so a concurrent verify burst can no longer advance the step, consume a recovery code, orClearFailureswhile the account is locked. - Made the MFA challenge single-use —
CompleteMFALoginrecords the challenge JTI viaRecordFirstUseafter the gate passes, so a reusedmfa_challengeis rejected. - Extended IP allow-lists to SSO —
WithIPCheck(mfaService)enforces the lists inCompleteLogin, surfaced asip_not_allowedin the UI and all 9 locales. - Added configurable
TRUSTED_PROXY_HOPS—ClientIPreads the hops-thX-Forwarded-Forentry from the right (default 1 preserves prior behaviour), wired through config, docker-compose and Helm. - Added anti-enumeration timing —
BurnPasswordCheckspends a dummy bcrypt comparison on a username miss inLoginand the password-only setup path. - Moved the login-throttle reset to after the gate, so an IP-blocked address holding the right password can't keep clearing the counter.
SetUserCIDRsself-lockout guard plusConfirmno longer marking the confirming code used, and a/profile→/accountredirect.
deepseek-v4.1-flash (free via Pullfrog for OSS) | 𝕏
There was a problem hiding this comment.
ℹ️ No new issues in this incremental delta — it closes the locked / self-lockout UI gap flagged in the previous review and gives the self-lockout rejection its own error code. The open per-username throttle thread remains a design decision for the author.
Reviewed changes
Reviewed the delta since the prior Pullfrog review (21e5d0a → 93fceb7):
- Dedicated
SELF_LOCKOUTcode —ErrSelfLockoutnow maps toapierr.CodeSelfLockout(SELF_LOCKOUT, still400) instead of the genericBAD_REQUEST, mirrored byApiErrorCode.SelfLockoutin the web client. Handlers pass the raw sentinel topresenter.Error, sostatusAndCodeFor(nothttpStatusForCode) resolves it. - Self-lockout messages surfaced —
LoginSecuritySettingsandUserSecurityDialognow show a dedicatedsettings.security.errors.selfLockoutstring when the saving admin's own address is outside the list, added in all 9 locales. - Lockout wait surfaced in the MFA dialogs — the forced-setup confirm (
MfaLoginSetup),MfaCodeDialogandMfaSetupDialogroute a429throughtooManyAttemptsMessage, so an account lockout renders the localized wait instead of the generic error. - Tidy —
TokenPairdoc comment and import grouping indomain/auth/service.go.
deepseek-v4.1-flash (free via Pullfrog for OSS) | 𝕏
There was a problem hiding this comment.
ℹ️ No critical issues — the reworked throttle resolves the earlier DoS concern; one minor test-quality suggestion inline.
Reviewed changes
Reviewed the delta since the prior Pullfrog review (93fceb7 → b6b61dc), which reworks the password-login throttle to close the per-username DoS flagged earlier:
- Two-scope throttle —
LoginThrottle.Check/Fail/Resetnow take the client IP andTrustis added. The atomic LuafailScriptcounts failures per(username, ip)pair and per username across all addresses (capmaxAttempts * 5). - Known-address exemption — the per-username lock denies only addresses not in a per-username
knownset;Trustrecords an address after a fully successful sign-in (Login,CompleteMFALogin), so the account owner's usual locations keep working while a distributed-guessing lock is in force. - Call-site updates —
auth_service.goandmfa_handler.gopassin.ClientIP/middleware.ClientIP(r)throughfailLogin/resetThrottle/passwordUser;memThrottleand the Redis tests are updated, plus a new distributed-guessing test.
Outcome: a single address can no longer lock a victim's usual locations out of password login — it only locks its own (key, ip) pair. The residual (an address that has never signed in from before, during an active multi-address attack) is the tradeoff the new doc comment documents.
deepseek-v4.1-flash (free via Pullfrog for OSS) | 𝕏
- Added MFA feature with scenarios for enrollment, signing in, and managing two-step verification. - Implemented tests for MFA enrollment, sign-in challenges, recovery codes, and IP allow-lists. - Updated profile feature to reflect changes in account management language. - Enhanced profile tests to verify new account settings and security messages. - Modified auth service tests to include IP address tracking for login failures.
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
Reviewed the delta since the prior Pullfrog review (b6b61dc → 080b721), which adds end-to-end coverage for the whole feature and fixes the one prior test-quality finding:
- Added e2e coverage — new
apps/e2e/features/auth/mfa.feature(spec of record),apps/e2e/tests/auth/mfa.spec.tsandapps/e2e/tests/helpers/mfa.tsexercise enrollment confirmation, the challenge token (rejected as a bearer/session credential, single-use), TOTP replay, single-use recovery codes, the five-wrong-code second-factor lockout with admin reset, IP allow-lists (includingSELF_LOCKOUT), require-MFA forced setup, the root-only policy gate, the wrong-password throttle (unknown names too) and five browser flows. - Fixed the prior vacuous assertion —
TestLogin_SuccessClearsFailuresnow sets aClientIPand asserts thealice|<ip>key the stub actually writes, with a precondition that the failure was recorded, so it fails again if reset-on-success regresses. Verified locally:go test ./internal/service/auth/ -run 'TestLogin_SuccessClearsFailures|TestLogin_LocksAfterRepeatedWrongPasswords'passes. - Updated the account-page specs —
profile.feature/profile.spec.tsnow assert the renamedAccountheading (exact) and the newManage your profile, sign-in security and access.subtitle.
The delta is test-only (feature files are the spec of record and are not executed), so no runtime behavior changed.
deepseek-v4.1-flash (free via Pullfrog for OSS) | 𝕏

Implements #678: TOTP two-step verification with recovery codes, IP/CIDR allow-lists for password login, and admin controls to require MFA. It is a standalone auth feature and does not depend on SSO. Defaults leave existing installs unchanged: no enrollments, no CIDRs, and the policy is off until an admin turns something on.
Sign-in behaviour
POST /auth/loginanswers200 {mfa_required, mfa_challenge}and sets no cookies. The web app then goes to a separate/login/mfapage, which posts the challenge and a code toPOST /auth/mfa/verifyto start the session. The browser never has to keep the password around.mfa_challenge). Request auth and session refresh both reject it, and a real session token is rejected as a challenge (covered by tests).ENCRYPTION_KEY; without it, enrollment is refused (MFA_UNAVAILABLE) but allow-lists still work.POST /auth/mfa/setup[/confirm]; refused if MFA is already on), then signs in with a code. This avoids locking out privileged users when require-MFA is switched on.API
/users/me/mfa: status, enroll, confirm, disable and regenerate recovery codes. Disable and regenerate need a current code./admin:GET/PUT /auth-security,GET/PUT /users/{id}/allowed-cidrs,DELETE /users/{id}/mfa.settings.security:write, root-equivalent (resetting someone's MFA amounts to taking over the account), so onlySUPER_ADMINhas it by default. It is checked on thessoroot so nosettingswildcard carries it. Docs and the bundled role-policy skill are updated.domainauth.Service.Loginnow takes aLoginInputstruct, and the interface gainsCompleteMFALogin.000077:user_mfa,users.allowed_cidrsand a singletonauth_security_settings. Lists are JSONB (the repo uses the pgx driver, notlib/pq).Web
/profile→/account; there is no redirect from the old URLs). It is split into Profile, Security, API keys and Notifications. The Security page has an MFA card (QR code, setup key, recovery codes shown once, disable, regenerate). API keys is removed from the user menu and stays in the Account nav."*"so it also covers roles created later), the require-MFA switch and the allowed IPs.ssoroot. Without that mapping a role saved with this permission would not work./auth/mfa/*401s are no longer treated as an expired session, so a wrong code shows "invalid code" instead of a generic error.qrcode-generator.Testing
go test ./...andgo vetpass, apart from 6test/integrationtests that fail identically on a cleanmaster(TestIAMMigrationKeyMapping, TestPluginManifestActionsMigration, TestProjectRoleResourcesMigration, TestRolesAPI_EndToEnd, TestRolesAssignMigration, TestServiceAccountsAPI_EndToEnd).PACA_TEST_PG_DSN(TestMFARepository_PGand the fullpostgrespackage).tsc -bpass; biome is clean apart from existing warnings.Not covered
/accountpath but not run.Closes #678
🤖 Generated with Claude Code