Skip to content

feat: implement multi-factor authentication (MFA) support - #679

Merged
pikann merged 8 commits into
masterfrom
feature/implement-mfa
Oct 31, 2026
Merged

pikann merged 8 commits into
masterfrom
feature/implement-mfa

Conversation

@pikann

@pikann pikann commented Oct 31, 2026 •

Copy link
Copy Markdown
Contributor

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

  • Two-step login. If the password is right and the account has MFA, POST /auth/login answers 200 {mfa_required, mfa_challenge} and sets no cookies. The web app then goes to a separate /login/mfa page, which posts the challenge and a code to POST /auth/mfa/verify to start the session. The browser never has to keep the password around.
  • Challenge token. A signed, 5-minute token of its own kind (mfa_challenge). Request auth and session refresh both reject it, and a real session token is rejected as a challenge (covered by tests).
  • Codes. TOTP is hand-written to RFC 6238 (SHA-1, 6 digits, 30 s, ±1 step) and checked against the RFC vectors. A used step is rejected (replay protection). Recovery codes are single-use and stored as SHA-256 hashes. The secret is encrypted at rest with ENCRYPTION_KEY; without it, enrollment is refused (MFA_UNAVAILABLE) but allow-lists still work.
  • IP allow-lists. A per-account list, plus an instance list that applies to the protected roles. Both are checked after the password, so the new error codes can't be used to probe usernames, and again at the code step. An unparseable client address fails closed.
  • Forced setup. If policy requires MFA and the account hasn't enrolled, it is enrolled from the sign-in screen using its password (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

  • Self-service under /users/me/mfa: status, enroll, confirm, disable and regenerate recovery codes. Disable and regenerate need a current code.
  • Admin under /admin: GET/PUT /auth-security, GET/PUT /users/{id}/allowed-cidrs, DELETE /users/{id}/mfa.
  • New action settings.security:write, root-equivalent (resetting someone's MFA amounts to taking over the account), so only SUPER_ADMIN has it by default. It is checked on the sso root so no settings wildcard carries it. Docs and the bundled role-policy skill are updated.
  • domainauth.Service.Login now takes a LoginInput struct, and the interface gains CompleteMFALogin.
  • Migration 000077: user_mfa, users.allowed_cidrs and a singleton auth_security_settings. Lists are JSONB (the repo uses the pgx driver, not lib/pq).

Web

  • Account settings (renamed from "My Profile", path /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.
  • Settings has a section nav: Branding, Single sign-on, Login security. Login security sets the protected roles (All roles is the default, stored as "*" so it also covers roles created later), the require-MFA switch and the allowed IPs.
  • Users page: a per-user shield action to edit allowed IPs or reset that person's MFA.
  • Role editor: lists "Manage Login Security", and the policy codec maps its domain to the sso root. Without that mapping a role saved with this permission would not work.
  • API client: /auth/mfa/* 401s are no longer treated as an expired session, so a wrong code shows "invalid code" instead of a generic error.
  • New dependency: qrcode-generator.
  • New strings are translated in all 9 locales (machine-written, so a native-speaker review is welcome).

Testing

  • Go: go test ./... and go vet pass, apart from 6 test/integration tests that fail identically on a clean master (TestIAMMigrationKeyMapping, TestPluginManifestActionsMigration, TestProjectRoleResourcesMigration, TestRolesAPI_EndToEnd, TestRolesAssignMigration, TestServiceAccountsAPI_EndToEnd).
  • The Postgres store and migration were run against a real Postgres with PACA_TEST_PG_DSN (TestMFARepository_PG and the full postgres package).
  • Web: full vitest suite and tsc -b pass; biome is clean apart from existing warnings.
  • Added unit tests for TOTP, the MFA service, the auth gate and challenge flow, the handlers, the router coverage and the web components.

Not covered

  • The pages were not exercised in a browser.
  • The e2e specs were updated for the /account path but not run.
  • There is no user-facing guide for MFA and IP allow-lists yet, and no e2e spec for the MFA flow.
  • The code step is rate-limited per client IP (same limit as password login), not per challenge.
  • The IP check uses the client address the API sees behind the proxy (the rightmost forwarded address); check that matches your deployment before relying on it.

Closes #678

🤖 Generated with Claude Code

- 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.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ℹ️ 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 — Login now takes LoginInput and, on ErrRequired, returns a signed mfa_challenge (no cookies) that only CompleteMFALogin accepts; the challenge kind is rejected as an access or refresh token.
  • Gate — mfasvc.Service.CheckLogin enforces 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-equivalent settings.security:write (SUPER_ADMIN's * only; ADMIN's exact settings:write does 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:437 calls IssueSession directly, so neither require_mfa nor 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/RefreshAnnotation never 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.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using deepseek-v4.1-flash (free via Pullfrog for OSS) | 𝕏

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ 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.SetupRequired and handler requireSetup refuse POST /auth/mfa/setup[/confirm] unless the policy requires MFA for the account and it has not enrolled, returning ErrSetupNotRequired → 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 — newRecoveryCodes now rejection-samples bytes >= 248 instead of taking mod 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: ErrSetupNotRequired mapping added to the presenter (403), and the AllRoles doc 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.

Pullfrog  | View workflow run | Using 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.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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_until to user_mfa, counted by RegisterFailure and cleared by ClearFailures; 5 consecutive wrong codes lock for 15 minutes and surface as 429 with retry_after_seconds / Retry-After, rendered as a localized wait on the web sign-in flows.
  • Self-lockout guard — SetPolicy now takes clientIP and refuses an instance IP allow-list that does not contain the saving admin's address (ErrSelfLockout → 400).
  • Setup-path IP enforcement — requireSetup runs the new CheckIP before 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 — NormalizeCIDRs masks host bits and unmaps IPv4-mapped IPv6; Begin reuses a pending secret younger than 10 minutes instead of invalidating an open QR code.
  • Audit logging and tests — slog.Info on 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?

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using deepseek-v4.1-flash (free via Pullfrog for OSS) | 𝕏

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 in bootstrap/app.go and installed on both authsvc.Service and MFAHandler.
  • Login integration — checks the lock before touching the user table or bcrypt (so unknown names lock too, preserving the anti-enumeration property), records a failure via failLogin (LockedError → 429 with the wait), and resets on a correct password.
  • Shared with the password-only setup path — MFAHandler.passwordUser now consults the same throttle, and resets/fails it the same way.
  • Message change — mfadom.ErrLocked is now too many failed attempts, shared by the password and second-factor lockouts.
  • Tests: Redis-backed throttle test (gated on PACA_TEST_REDIS_URL) and in-memory memThrottle cases covering lock-at-max, unknown names, and reset-on-success.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using 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.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ℹ️ 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 — AdvanceStep and ConsumeRecoveryCode now re-check locked_until, so a concurrent verify burst can no longer advance the step, consume a recovery code, or ClearFailures while the account is locked.
  • Made the MFA challenge single-use — CompleteMFALogin records the challenge JTI via RecordFirstUse after the gate passes, so a reused mfa_challenge is rejected.
  • Extended IP allow-lists to SSO — WithIPCheck(mfaService) enforces the lists in CompleteLogin, surfaced as ip_not_allowed in the UI and all 9 locales.
  • Added configurable TRUSTED_PROXY_HOPS — ClientIP reads the hops-th X-Forwarded-For entry from the right (default 1 preserves prior behaviour), wired through config, docker-compose and Helm.
  • Added anti-enumeration timing — BurnPasswordCheck spends a dummy bcrypt comparison on a username miss in Login and 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.
  • SetUserCIDRs self-lockout guard plus Confirm no longer marking the confirming code used, and a /profile → /account redirect.

Pullfrog  | Fix it ➔ | View workflow run | Using deepseek-v4.1-flash (free via Pullfrog for OSS) | 𝕏

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ℹ️ 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_LOCKOUT code — ErrSelfLockout now maps to apierr.CodeSelfLockout (SELF_LOCKOUT, still 400) instead of the generic BAD_REQUEST, mirrored by ApiErrorCode.SelfLockout in the web client. Handlers pass the raw sentinel to presenter.Error, so statusAndCodeFor (not httpStatusForCode) resolves it.
  • Self-lockout messages surfaced — LoginSecuritySettings and UserSecurityDialog now show a dedicated settings.security.errors.selfLockout string 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), MfaCodeDialog and MfaSetupDialog route a 429 through tooManyAttemptsMessage, so an account lockout renders the localized wait instead of the generic error.
  • Tidy — TokenPair doc comment and import grouping in domain/auth/service.go.

Pullfrog  | Fix it ➔ | View workflow run | Using deepseek-v4.1-flash (free via Pullfrog for OSS) | 𝕏

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ℹ️ 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/Reset now take the client IP and Trust is added. The atomic Lua failScript counts failures per (username, ip) pair and per username across all addresses (cap maxAttempts * 5).
  • Known-address exemption — the per-username lock denies only addresses not in a per-username known set; Trust records 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.go and mfa_handler.go pass in.ClientIP / middleware.ClientIP(r) through failLogin / resetThrottle / passwordUser; memThrottle and 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.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using 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.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ 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.ts and apps/e2e/tests/helpers/mfa.ts exercise 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 (including SELF_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_SuccessClearsFailures now sets a ClientIP and asserts the alice|<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.ts now assert the renamed Account heading (exact) and the new Manage 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.

Pullfrog  | View workflow run | Using deepseek-v4.1-flash (free via Pullfrog for OSS) | 𝕏

@pikann
pikann merged commit c0ee49f into master Oct 31, 2026
13 checks passed
@pikann
pikann deleted the feature/implement-mfa branch October 31, 2026 11:25
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Feature] Multi-factor authentication and IP allow-list for privileged accounts

1 participant