Skip to content

Feature | Add MultiFactor Authentication. Initial migrations and entities - #125

Open
matiasperrone-exo wants to merge 37 commits into
mainfrom
feat/mfa-phase1---migrations--and--interfaces
Open

matiasperrone-exo wants to merge 37 commits into
mainfrom
feat/mfa-phase1---migrations--and--interfaces

Conversation

@matiasperrone-exo

@matiasperrone-exo matiasperrone-exo commented Apr 22, 2026 •

Copy link
Copy Markdown
Contributor

Task:

Ref: https://app.clickup.com/t/86b9e8wm7

Changes

  • Add migration for 2FA schema foundation (Phase I)
  • Add UserTrustedDevice entity
  • Add TwoFactorAuditLog entity
  • Add UserRecoveryCode entity
  • Add repository interfaces for 2FA entities
  • Add Doctrine implementations for 2FA repositories
  • Register 2FA repositories in service container
  • Add repository round-trip tests for 2FA entities

Requested Goal

Current state

The IDP database has no 2FA-related tables or columns. The User entity lacks fields for tracking two-factor enrollment or enforcement status.

Target state

Three new tables (user_trusted_devices, two_factor_audit_log, user_recovery_codes) and three new columns on the users table (two_factor_enabled, two_factor_method, two_factor_enforced_at) exist via a single additive Doctrine migration. Corresponding Doctrine entities and repositories are registered in the ORM mappings.

This migration is the foundation for every other Phase I ticket. It must run with zero downtime since it only adds nullable columns and new tables.

Tasks

  • Create Doctrine migration adding three columns to the users table: two_factor_enabled (boolean, default false), two_factor_method (string/enum, default 'email_otp'), two_factor_enforced_at
    (datetime, nullable)
  • Create UserTrustedDevice Doctrine entity with fields: id, user_id (FK), device_identifier (varchar 255), device_name (varchar 255), ip_address (varchar 45), user_agent (text), trusted_at,
    expires_at, last_seen_at, is_revoked (boolean, default false), created_at, updated_at. Indexes on (user_id, device_identifier), (user_id, is_revoked), (expires_at)
  • Create TwoFactorAuditLog Doctrine entity with fields: id, user_id (FK), event_type (enum: challenge_issued, challenge_succeeded, challenge_failed, enrollment_changed, device_trusted,
    device_revoked, recovery_used, settings_changed), method (enum: email_otp, sms_otp, totp, passkey, recovery), ip_address (varchar 45), user_agent (text), metadata (json, nullable), created_at.
    Indexes on (user_id, event_type, created_at), (created_at)
  • Create UserRecoveryCode Doctrine entity with fields: id, user_id (FK), code_hash (varchar 255, bcrypt hash), used_at (datetime, nullable), created_at. Index on (user_id, used_at)
  • Create IUserTrustedDeviceRepository, IUserRecoveryCodeRepository, ITwoFactorAuditLogRepository interfaces and their Doctrine implementations
  • Register all new entities in the Doctrine ORM entity mappings
  • Verify migration runs cleanly on a fresh database and on an existing database with data

ACCEPTANCE CRITERIA

php artisan doctrine:migrations:migrate runs without errors on both fresh and populated databases
All three new tables exist with correct column types, defaults, and indexes
Users table has the three new columns with correct defaults (two_factor_enabled=false, two_factor_method='email_otp', two_factor_enforced_at=NULL)
Each Doctrine entity can be persisted and retrieved via its repository ( provide unit tests )
Migration is fully additive: no columns dropped, no data modified, no destructive operations
Existing application functionality is unaffected after migration (login, OTP flow, admin panel all work)

DEVELOPMENT NOTES

Key files:

  • New: app/libs/Auth/Models/UserTrustedDevice.php
  • New: app/libs/Auth/Models/TwoFactorAuditLog.php
  • New: app/libs/Auth/Models/UserRecoveryCode.php
  • New: database/migrations/Version*.php (single migration file)
  • Modified: Doctrine entity mapping configuration

Gotchas

  • The User entity uses Doctrine ORM, not Eloquent. All mappings follow the existing annotation/attribute pattern in the codebase.
  • device_identifier stores a SHA-256 hash, not the raw cookie token. Size varchar(255) is sufficient for hex-encoded SHA-256 (64 chars).
  • The OTP table (oauth2_otp) already has phone_number and connection='sms' columns from existing infrastructure. Do NOT modify this table.
  • two_factor_method should be stored as a string column, not a database-level ENUM, to allow adding values in Phase II/III without migration.

Out of scope:

User entity PHP methods (separate ticket), service layer code, UI changes.

Summary by CodeRabbit

  • New Features

    • 2FA foundation: trusted device management (trust/expire/revoke), single‑use recovery codes, and detailed 2FA audit logging with event/method types and user-scoped queries.
    • Added repository support and interfaces for trusted devices, recovery codes, and 2FA audit logs.
  • Tests

    • Comprehensive tests for trusted-device behavior, recovery-code lifecycle/deletion, audit-log ordering, and device-identifier uniqueness.
  • Chores

    • Database migrations to add 2FA columns/tables and enforce unique (user, device) identifiers.

Review Change Stack

@matiasperrone-exo matiasperrone-exo self-assigned this Apr 22, 2026
@coderabbitai

coderabbitai Bot commented Apr 22, 2026 •

Copy link
Copy Markdown

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
Walkthrough

Adds Phase I two-factor: three Doctrine entities (trusted devices, audit logs, recovery codes), repository interfaces and Doctrine implementations, provider bindings, two migrations (schema + unique index), and integration tests exercising repository behavior.

Changes

Two-factor foundation

Layer / File(s) Summary
Entities & domain models
app/libs/Auth/Models/TwoFactorAuditLog.php, app/libs/Auth/Models/UserRecoveryCode.php, app/libs/Auth/Models/UserTrustedDevice.php
New Doctrine entities mapped to two_factor_audit_log, user_recovery_codes, and user_trusted_devices with fields, relations to users, lifecycle initialization, getters/setters, validation (allowlists and bcrypt check), and repositoryClass hints.
Repository contracts
app/libs/Auth/Repositories/ITwoFactorAuditLogRepository.php, app/libs/Auth/Repositories/IUserRecoveryCodeRepository.php, app/libs/Auth/Repositories/IUserTrustedDeviceRepository.php
New interfaces declaring repository operations: getRecentByUser(User,int): array, getUnusedByUser(User): array, deleteAllForUser(User): int, getActiveByUserAndIdentifier(User,string): ?UserTrustedDevice, and getActiveByUser(User): array.
Doctrine repository implementations
app/Repositories/DoctrineTwoFactorAuditLogRepository.php, app/Repositories/DoctrineUserRecoveryCodeRepository.php, app/Repositories/DoctrineUserTrustedDeviceRepository.php
Concrete repositories wired to their entity classes: recent-audit query ordered by created_at desc; retrieval and DQL deletion of recovery codes; active trusted-device queries enforcing is_revoked = false and expires_at > now (UTC).
Service provider wiring
app/Repositories/RepositoriesProvider.php
Container bindings registered for the three repository interfaces to their Doctrine repositories and added to the provider provides() list for deferred resolution.
Migrations
database/migrations/Version20260416194357.php, database/migrations/Version20260424120000.php
Migration adding 2FA columns to users and creating user_trusted_devices, two_factor_audit_log, user_recovery_codes; separate migration to convert the user/device index into a unique index after checking for duplicates.
Integration tests
tests/TwoFactorRepositoriesTest.php
Repository integration tests: trusted device round-trips, exclusion of expired/revoked devices from active queries, uniqueness index assertion, audit-log ordering and retrieval, recovery-code lifecycle (unused, mark used, deleteAllForUser), and validation on double-use.
sequenceDiagram
    rect rgba(100,150,240,0.5)
    participant Client
    end
    rect rgba(120,200,160,0.5)
    participant Repository
    end
    rect rgba(200,100,140,0.5)
    participant EntityManager
    end
    rect rgba(240,200,100,0.5)
    participant Database
    end

    Client->>Repository: persistTrustedDevice(data)
    Repository->>EntityManager: persist(UserTrustedDevice)
    EntityManager->>Database: INSERT user_trusted_devices
    Database-->>EntityManager: OK
    EntityManager-->>Repository: persisted entity

    Client->>Repository: getActiveByUserAndIdentifier(user, id)
    Repository->>EntityManager: createQuery(filter active conditions)
    EntityManager->>Database: SELECT ... WHERE user_id=? AND device_identifier=? AND is_revoked=0 AND expires_at > now()
    Database-->>EntityManager: rows
    EntityManager-->>Repository: entity/NULL
    Repository-->>Client: entity/NULL
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Suggested reviewers

  • smarcet
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 8.86% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)

Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately and concisely summarizes the main objective: adding Multi-Factor Authentication foundation through migrations and entities.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

Finishing Touches

🧪 Generate unit tests (beta)

  • Create PR with unit tests
  • Commit unit tests in branch feat/mfa-phase1---migrations--and--interfaces
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

@github-actions

Copy link
Copy Markdown

📘 OpenAPI / Swagger preview

➡️ https://OpenStackweb.github.io/openstackid/openapi/pr-125/

This page is automatically updated on each push to this PR.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 3

🧹 Nitpick comments (6)
app/libs/Auth/Repositories/IUserRecoveryCodeRepository.php (1)

25-28: Consider documenting transaction/atomicity expectations for deleteAllForUser.

Since this is typically invoked during recovery-code regeneration (delete-then-insert), callers likely need the operation wrapped in a transaction with the subsequent re-insert to avoid leaving a user with zero recovery codes on partial failure. Document whether callers must manage the transaction themselves, or have the implementation wrap it. A one-line docblock addition is sufficient.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@app/libs/Auth/Repositories/IUserRecoveryCodeRepository.php` around lines 25 -
28, Add a one-line sentence to the deleteAllForUser(User $user): int docblock
clarifying transaction/atomicity expectations: state whether implementations
will wrap this operation in a database transaction or whether callers must
perform a surrounding transaction when doing delete-then-insert (e.g., "This
method does NOT start a transaction; callers should wrap delete-and-reinsert
operations in a transaction to ensure atomicity." or the converse if
implementations guarantee transactional semantics). Reference the method name
deleteAllForUser in the docblock so callers know the requirement.
app/Repositories/DoctrineUserRecoveryCodeRepository.php (1)

34-42: Consider flushing pending UoW changes or documenting caller responsibility.

Query::execute() on a DQL DELETE bypasses the UnitOfWork and runs directly against the DB. If a caller has pending in-memory changes on UserRecoveryCode entities for this user (e.g. newly persisted but not flushed, or a markUsed() pending flush), those will not be considered by the bulk delete and may re-surface on a later flush(), or conflict. Either document this (bulk operation; caller must flush/clear beforehand) or call $em->flush()/$em->clear(UserRecoveryCode::class) around the delete. Given the "used when regenerating" use case, a docblock note is likely sufficient.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@app/Repositories/DoctrineUserRecoveryCodeRepository.php` around lines 34 -
42, The bulk DQL delete in deleteAllForUser bypasses the UnitOfWork and can
conflict with pending in-memory UserRecoveryCode changes; update the docblock
for DoctrineUserRecoveryCodeRepository::deleteAllForUser to state this is a bulk
operation and callers must flush or clear pending UserRecoveryCode changes
before calling, or alternatively call $em->flush() and/or
$em->clear(UserRecoveryCode::class) around the delete inside deleteAllForUser to
ensure UoW consistency (refer to getEntityManager(), UserRecoveryCode and the
Query::execute() bulk delete in your change).
app/libs/Auth/Models/UserRecoveryCode.php (1)

27-29: Minor: attribute order — JoinColumn is placed before ManyToOne.

Doctrine accepts either order, but the conventional pairing is #[ManyToOne] first, then #[JoinColumn], which matches Doctrine docs/examples and the surrounding codebase's style. Purely stylistic; no behavior change.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@app/libs/Auth/Models/UserRecoveryCode.php` around lines 27 - 29, Swap the
attribute order on the $user property so #[ORM\ManyToOne(...)] appears before
#[ORM\JoinColumn(...)]; specifically update the attributes on the private $user
property (currently using #[ORM\JoinColumn(...)] then #[ORM\ManyToOne(...)] ) to
#[ORM\ManyToOne(targetEntity: \Auth\User::class)] followed by
#[ORM\JoinColumn(name: 'user_id', referencedColumnName: 'id', onDelete:
'CASCADE')], preserving the same arguments.
app/Repositories/DoctrineUserTrustedDeviceRepository.php (1)

35-41: Consider deterministic ordering for getActiveByUser.

No orderBy is specified, so results come back in storage order. For a user-facing "trusted devices" listing, ordering by last_seen_at DESC (or trusted_at DESC) produces a more predictable/useful listing and avoids flaky tests if ever asserting order.

♻️ Suggested change
     public function getActiveByUser(User $user): array
     {
         return $this->findBy([
             'user'       => $user,
             'is_revoked' => false,
-        ]);
+        ], ['last_seen_at' => 'DESC']);
     }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@app/Repositories/DoctrineUserTrustedDeviceRepository.php` around lines 35 -
41, getActiveByUser currently returns results with no deterministic ordering;
update the repository method (getActiveByUser) to return active devices ordered
by most-recent activity (e.g. order by last_seen_at DESC or trusted_at DESC
depending on your entity field name) so the user-facing list and tests are
stable—use the Doctrine findBy third parameter for orderBy or switch to the
query builder in DoctrineUserTrustedDeviceRepository::getActiveByUser to apply
the DESC ordering on the appropriate timestamp field.
database/migrations/Version20260416194357.php (2)

33-39: Partial-state guard only checks one column.

The up() guard checks only two_factor_enabled. If a prior run failed after adding two_factor_enabled but before adding the other two columns (or vice versa in a manual intervention), subsequent runs will silently skip the missing columns. Consider guarding each column addition independently, e.g.:

-        if ($schema->hasTable("users") && !$builder->hasColumn("users", "two_factor_enabled")) {
-            $builder->table('users', function (Table $table) {
-                $table->boolean('two_factor_enabled')->setNotnull(true)->setDefault(false);
-                $table->string('two_factor_method', 32)->setNotnull(true)->setDefault('email_otp');
-                $table->dateTime('two_factor_enforced_at')->setNotnull(false)->setDefault(null);
-            });
-        }
+        if ($schema->hasTable("users")) {
+            $builder->table('users', function (Table $table) use ($builder) {
+                if (!$builder->hasColumn("users", "two_factor_enabled")) {
+                    $table->boolean('two_factor_enabled')->setNotnull(true)->setDefault(false);
+                }
+                if (!$builder->hasColumn("users", "two_factor_method")) {
+                    $table->string('two_factor_method', 32)->setNotnull(true)->setDefault('email_otp');
+                }
+                if (!$builder->hasColumn("users", "two_factor_enforced_at")) {
+                    $table->dateTime('two_factor_enforced_at')->setNotnull(false)->setDefault(null);
+                }
+            });
+        }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@database/migrations/Version20260416194357.php` around lines 33 - 39, The
migration's up() currently gates adding all three columns behind a single check
for two_factor_enabled, so if a prior run added one column and failed the rest
will be skipped; change the logic to first verify $schema->hasTable("users") and
then individually check $builder->hasColumn("users", "<column_name>") for each
of the three columns (two_factor_enabled, two_factor_method,
two_factor_enforced_at) and add each missing column (using the existing
builder->table('users', function (Table $table) { ... }) block or separate
blocks) so each column is created idempotently even if previous runs partially
applied the migration.

55-58: Consider a UNIQUE index on (user_id, device_identifier).

DoctrineUserTrustedDeviceRepository::getActiveByUserAndIdentifier() is expected to return a single row for a given (user, device_identifier) pair, and device_identifier is a SHA-256 hex string (globally unique per device/token). A plain index allows duplicate rows to accumulate (e.g., re-trusting the same device on retries) and makes the "single active device" contract unenforceable at the DB layer. A unique constraint would prevent silent duplication and align the schema with the repository's semantics.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@database/migrations/Version20260416194357.php` around lines 55 - 58, Replace
the non-unique index on (user_id, device_identifier) with a UNIQUE constraint so
the DB enforces one row per (user_id, device_identifier) pair; update the
migration where $table->index(["user_id", "device_identifier"],
"utd_user_device_idx") is declared in Version20260416194357.php to create a
unique index/constraint (e.g. using $table->unique(...) or the DBAL equivalent)
with a clear name like "utd_user_device_unique", and remove or replace the
existing plain index to avoid duplicate-key conflicts; this aligns the schema
with DoctrineUserTrustedDeviceRepository::getActiveByUserAndIdentifier()
expectations.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@app/libs/Auth/Models/UserRecoveryCode.php`:
- Line 66: The magic __get method on class UserRecoveryCode exposes
private/protected properties (notably code_hash) and bypasses the explicit
getters; replace it with a safe approach by removing the passthrough or
implementing an allow-list: in UserRecoveryCode::__get only return values for an
explicit whitelist of non-sensitive keys (e.g., id, user_id, created_at) or
throw/return null for anything else, so sensitive fields like code_hash are not
accessible via property access while preserving legacy compatibility for
approved fields.

In `@app/libs/Auth/Models/UserTrustedDevice.php`:
- Line 85: Remove the magic __get() passthrough from the UserTrustedDevice
entity: delete the public function __get($name) { return $this->{$name}; } so
callers no longer bypass explicit accessors (e.g. getIsRevoked(), isRevoked(),
getUser()) and Doctrine proxies fire their lazy-load hooks; update any call
sites that relied on property-style access to use the declared getters instead
to preserve type casting and avoid silent nulls for missing properties.

In `@tests/TwoFactorRepositoriesTest.php`:
- Around line 37-41: The test currently grabs an arbitrary real user via
IUserRepository->findOneBy([]) in setUp and testRecoveryCodeRoundTrip calls
RecoveryCodeRepository->deleteAllForUser($this->user), risking deletion of real
users' data; change setUp to create (and persist) a dedicated test user or
select a user explicitly marked for testing, then use that user object for the
test, and in tearDown remove that test user and assert deleteAllForUser removed
exactly the number of recovery codes inserted by the test (or call delete only
for the specific created entities) so that testRecoveryCodeRoundTrip no longer
wipes production/seeding data. Ensure you update any references to findOneBy,
testRecoveryCodeRoundTrip, deleteAllForUser, setUp and tearDown accordingly.

---

Nitpick comments:
In `@app/libs/Auth/Models/UserRecoveryCode.php`:
- Around line 27-29: Swap the attribute order on the $user property so
#[ORM\ManyToOne(...)] appears before #[ORM\JoinColumn(...)]; specifically update
the attributes on the private $user property (currently using
#[ORM\JoinColumn(...)] then #[ORM\ManyToOne(...)] ) to
#[ORM\ManyToOne(targetEntity: \Auth\User::class)] followed by
#[ORM\JoinColumn(name: 'user_id', referencedColumnName: 'id', onDelete:
'CASCADE')], preserving the same arguments.

In `@app/libs/Auth/Repositories/IUserRecoveryCodeRepository.php`:
- Around line 25-28: Add a one-line sentence to the deleteAllForUser(User
$user): int docblock clarifying transaction/atomicity expectations: state
whether implementations will wrap this operation in a database transaction or
whether callers must perform a surrounding transaction when doing
delete-then-insert (e.g., "This method does NOT start a transaction; callers
should wrap delete-and-reinsert operations in a transaction to ensure
atomicity." or the converse if implementations guarantee transactional
semantics). Reference the method name deleteAllForUser in the docblock so
callers know the requirement.

In `@app/Repositories/DoctrineUserRecoveryCodeRepository.php`:
- Around line 34-42: The bulk DQL delete in deleteAllForUser bypasses the
UnitOfWork and can conflict with pending in-memory UserRecoveryCode changes;
update the docblock for DoctrineUserRecoveryCodeRepository::deleteAllForUser to
state this is a bulk operation and callers must flush or clear pending
UserRecoveryCode changes before calling, or alternatively call $em->flush()
and/or $em->clear(UserRecoveryCode::class) around the delete inside
deleteAllForUser to ensure UoW consistency (refer to getEntityManager(),
UserRecoveryCode and the Query::execute() bulk delete in your change).

In `@app/Repositories/DoctrineUserTrustedDeviceRepository.php`:
- Around line 35-41: getActiveByUser currently returns results with no
deterministic ordering; update the repository method (getActiveByUser) to return
active devices ordered by most-recent activity (e.g. order by last_seen_at DESC
or trusted_at DESC depending on your entity field name) so the user-facing list
and tests are stable—use the Doctrine findBy third parameter for orderBy or
switch to the query builder in
DoctrineUserTrustedDeviceRepository::getActiveByUser to apply the DESC ordering
on the appropriate timestamp field.

In `@database/migrations/Version20260416194357.php`:
- Around line 33-39: The migration's up() currently gates adding all three
columns behind a single check for two_factor_enabled, so if a prior run added
one column and failed the rest will be skipped; change the logic to first verify
$schema->hasTable("users") and then individually check
$builder->hasColumn("users", "<column_name>") for each of the three columns
(two_factor_enabled, two_factor_method, two_factor_enforced_at) and add each
missing column (using the existing builder->table('users', function (Table
$table) { ... }) block or separate blocks) so each column is created
idempotently even if previous runs partially applied the migration.
- Around line 55-58: Replace the non-unique index on (user_id,
device_identifier) with a UNIQUE constraint so the DB enforces one row per
(user_id, device_identifier) pair; update the migration where
$table->index(["user_id", "device_identifier"], "utd_user_device_idx") is
declared in Version20260416194357.php to create a unique index/constraint (e.g.
using $table->unique(...) or the DBAL equivalent) with a clear name like
"utd_user_device_unique", and remove or replace the existing plain index to
avoid duplicate-key conflicts; this aligns the schema with
DoctrineUserTrustedDeviceRepository::getActiveByUserAndIdentifier()
expectations.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 672e540a-70f5-47fd-8667-ab3e07d97782

📥 Commits

Reviewing files that changed from the base of the PR and between db9f777 and 6a2bd34.

📒 Files selected for processing (12)
  • app/Repositories/DoctrineTwoFactorAuditLogRepository.php
  • app/Repositories/DoctrineUserRecoveryCodeRepository.php
  • app/Repositories/DoctrineUserTrustedDeviceRepository.php
  • app/Repositories/RepositoriesProvider.php
  • app/libs/Auth/Models/TwoFactorAuditLog.php
  • app/libs/Auth/Models/UserRecoveryCode.php
  • app/libs/Auth/Models/UserTrustedDevice.php
  • app/libs/Auth/Repositories/ITwoFactorAuditLogRepository.php
  • app/libs/Auth/Repositories/IUserRecoveryCodeRepository.php
  • app/libs/Auth/Repositories/IUserTrustedDeviceRepository.php
  • database/migrations/Version20260416194357.php
  • tests/TwoFactorRepositoriesTest.php

Comment thread tests/TwoFactorRepositoriesTest.php Resolved

@martinquiroga-exo martinquiroga-exo left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

@matiasperrone-exo please see comments. Thanks

Comment thread tests/TwoFactorRepositoriesTest.php Resolved
@github-actions

Copy link
Copy Markdown

📘 OpenAPI / Swagger preview

➡️ https://OpenStackweb.github.io/openstackid/openapi/pr-125/

This page is automatically updated on each push to this PR.

@matiasperrone-exo
matiasperrone-exo force-pushed the feat/mfa-phase1---migrations--and--interfaces branch from bd6e93f to f75c63d Compare April 24, 2026 20:59
@github-actions

Copy link
Copy Markdown

📘 OpenAPI / Swagger preview

➡️ https://OpenStackweb.github.io/openstackid/openapi/pr-125/

This page is automatically updated on each push to this PR.

@matiasperrone-exo
matiasperrone-exo force-pushed the feat/mfa-phase1---migrations--and--interfaces branch from f75c63d to 4624ff5 Compare April 24, 2026 21:04
@github-actions

Copy link
Copy Markdown

📘 OpenAPI / Swagger preview

➡️ https://OpenStackweb.github.io/openstackid/openapi/pr-125/

This page is automatically updated on each push to this PR.

@matiasperrone-exo

Copy link
Copy Markdown
Contributor Author

@martinquiroga-exo please review again

@martinquiroga-exo martinquiroga-exo left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

@matiasperrone-exo please see comments

@github-actions

Copy link
Copy Markdown

📘 OpenAPI / Swagger preview

➡️ https://OpenStackweb.github.io/openstackid/openapi/pr-125/

This page is automatically updated on each push to this PR.

@coderabbitai coderabbitai Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🧹 Nitpick comments (1)
app/libs/Auth/Models/UserTrustedDevice.php (1)

19-20: Add UniqueConstraint annotation to mirror the database migration.

The migration enforces uniqueness on (user_id, device_identifier) via UNIQUE INDEX utd_user_device_uniq, but the entity metadata declares no corresponding UniqueConstraint. This drift causes schema validation mismatches and lets metadata-driven tools miss the constraint. Add a #[ORM\UniqueConstraint(name: 'utd_user_device_uniq', columns: ['user_id', 'device_identifier'])] attribute to the #[ORM\Table] declaration.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@app/libs/Auth/Models/UserTrustedDevice.php` around lines 19 - 20, The ORM
entity for UserTrustedDevice is missing the UniqueConstraint that mirrors the DB
migration; update the #[ORM\Table(...)] attribute on the UserTrustedDevice class
to include #[ORM\UniqueConstraint(name: 'utd_user_device_uniq', columns:
['user_id', 'device_identifier'])] so the entity metadata matches the migration
(ensure the attribute is added alongside the existing name and repositoryClass
in the class declaration for UserTrustedDevice).
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@app/libs/Auth/Models/TwoFactorAuditLog.php`:
- Around line 22-35: The setters for audit event/method must validate input
against the allowed constants to prevent typos from being persisted; update the
TwoFactorAuditLog class to add validation in the relevant setters (e.g., the
methods that set event and method values) by building arrays of allowed values
from the constants (Event* and Method*) and checking inputs with an explicit
membership test (throw a ValidationException/InvalidArgumentException or return
an error instead of accepting unknown strings), and apply the same guard to the
other setters referenced around lines 75-79 so only the defined constants can be
stored (also consider adding a DB constraint/migration as a follow-up).

In `@database/migrations/Version20260424120000.php`:
- Around line 27-33: In Version20260424120000.php inside the up(Schema $schema)
method, guard the ALTER TABLE that replaces utd_user_device_idx with the UNIQUE
utd_user_device_uniq by first running a preflight duplicate check on
user_trusted_devices for (user_id, device_identifier) and aborting/messaging the
migration if any duplicates exist; if duplicates are found implement a
deterministic dedupe/backfill step (e.g. keep the most recent row per (user_id,
device_identifier) or copy conflicting rows to a retention table and delete
extras) before executing the ALTER TABLE, and then proceed to DROP INDEX
utd_user_device_idx and ADD UNIQUE INDEX utd_user_device_uniq only after
deduplication completes successfully.

---

Nitpick comments:
In `@app/libs/Auth/Models/UserTrustedDevice.php`:
- Around line 19-20: The ORM entity for UserTrustedDevice is missing the
UniqueConstraint that mirrors the DB migration; update the #[ORM\Table(...)]
attribute on the UserTrustedDevice class to include #[ORM\UniqueConstraint(name:
'utd_user_device_uniq', columns: ['user_id', 'device_identifier'])] so the
entity metadata matches the migration (ensure the attribute is added alongside
the existing name and repositoryClass in the class declaration for
UserTrustedDevice).
🪄 Autofix (Beta)

❌ Autofix failed (check again to retry)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 8e15f9c4-68e3-4df9-a2d3-f1e2af5e201f

📥 Commits

Reviewing files that changed from the base of the PR and between 6a2bd34 and 16e6ebb.

📒 Files selected for processing (6)
  • app/Repositories/DoctrineUserTrustedDeviceRepository.php
  • app/libs/Auth/Models/TwoFactorAuditLog.php
  • app/libs/Auth/Models/UserRecoveryCode.php
  • app/libs/Auth/Models/UserTrustedDevice.php
  • database/migrations/Version20260424120000.php
  • tests/TwoFactorRepositoriesTest.php

@matiasperrone-exo
matiasperrone-exo force-pushed the feat/mfa-phase1---migrations--and--interfaces branch from 16e6ebb to 8fab15c Compare April 29, 2026 19:19
@github-actions

Copy link
Copy Markdown

📘 OpenAPI / Swagger preview

➡️ https://OpenStackweb.github.io/openstackid/openapi/pr-125/

This page is automatically updated on each push to this PR.

@matiasperrone-exo
matiasperrone-exo force-pushed the feat/mfa-phase1---migrations--and--interfaces branch from 8fab15c to 5b8c829 Compare April 29, 2026 19:22
@github-actions

Copy link
Copy Markdown

📘 OpenAPI / Swagger preview

➡️ https://OpenStackweb.github.io/openstackid/openapi/pr-125/

This page is automatically updated on each push to this PR.

@matiasperrone-exo
matiasperrone-exo force-pushed the feat/mfa-phase1---migrations--and--interfaces branch 2 times, most recently from a5c0cff to f21b6fb Compare April 29, 2026 19:55
@github-actions

Copy link
Copy Markdown

📘 OpenAPI / Swagger preview

➡️ https://OpenStackweb.github.io/openstackid/openapi/pr-125/

This page is automatically updated on each push to this PR.

3 similar comments
@github-actions

Copy link
Copy Markdown

📘 OpenAPI / Swagger preview

➡️ https://OpenStackweb.github.io/openstackid/openapi/pr-125/

This page is automatically updated on each push to this PR.

@github-actions

Copy link
Copy Markdown

📘 OpenAPI / Swagger preview

➡️ https://OpenStackweb.github.io/openstackid/openapi/pr-125/

This page is automatically updated on each push to this PR.

@github-actions

Copy link
Copy Markdown

📘 OpenAPI / Swagger preview

➡️ https://OpenStackweb.github.io/openstackid/openapi/pr-125/

This page is automatically updated on each push to this PR.

@matiasperrone-exo

Copy link
Copy Markdown
Contributor Author

Add UniqueConstraint annotation to mirror the database migration.

done

@coderabbitai

coderabbitai Bot commented Apr 29, 2026

Copy link
Copy Markdown

Note

Autofix is a beta feature. Expect some limitations and changes as we gather feedback and continue to improve it.

Autofix skipped. No unresolved CodeRabbit review comments with fix instructions found.

@github-actions

Copy link
Copy Markdown

📘 OpenAPI / Swagger preview

➡️ https://OpenStackweb.github.io/openstackid/openapi/pr-125/

This page is automatically updated on each push to this PR.

smarcet and others added 8 commits November 16, 2026 16:57
Signed-off-by: smarcet <smarcet@gmail.com>
Social login (SocialLoginController::callback) established a full session
for any user that passed canLogin(), so an account with
shouldRequire2FA() true could log in and obtain tokens without ever
passing the 2FA challenge the password flow enforces.

Extract the password flow's challenge issuance (gate check, resend
rate-limit, OTP issuance scoped to the pending OAuth2 client, audit log,
session bookkeeping) from UserController::postLogin into a dedicated
TwoFactorChallengeService, and call it from the social callback before
Auth::login(). An enforced user now gets the same email-OTP challenge and
completes it through the unchanged verify2FA endpoint; non-enforced users
and the two_factor.enabled kill-switch behave as before.

Drop the now-unused ITwoFactorGateService / ITwoFactorRateLimitService
dependencies from UserController.
…on main

main #161 renamed the env var that drives the session cookie Secure flag
from SESSION_SECURE_COOKIE to SESSION_COOKIE_SECURE. The rebase brought
the new config/session.php in but left the branch-side consumers on the
old name:

- tests/unit/SessionCookieConfigTest.php set SESSION_SECURE_COOKIE=false
  and asserted secure=false, which now fails because the config no longer
  reads that var.
- Both frontend test workflows exported SESSION_SECURE_COOKIE=false, so
  CI would emit a Secure cookie over plain http.
- The same_site comment in config/session.php still named the old var.

Also drop a stray "<" left in .env.example by the conflict resolution.
…ovider=

Relying parties (event-site) send the OIDC authorization request with
provider=facebook so the IDP skips its own login screen and dispatches
straight to the provider. The social callback already issued the 2FA
challenge for an enforced user and bounced back to /login to render the
2FA screen, but OAuth2LoginStrategy::getLogin() only looked at the memento,
which still carries the provider, and dispatched to it again. Facebook
answered without interaction, the callback issued another OTP, and the
loop repeated until the resend rate-limit failed the login with the
social_login_error page: the user received several codes and never saw
the screen to enter one.

Skip the provider auto-dispatch while a 2FA challenge is pending in
session (flow=2fa), so the login page renders and login.js opens the 2FA
screen, exactly as it does when the social button is pressed on the IDP's
own login screen. The first dispatch (no challenge pending) is unchanged.

Add a regression test that runs the OIDC request with provider=facebook
through the social callback and asserts the login page renders the 2FA
screen and the challenge completes back into the relying party's request.
URL::forceScheme('https') ran for every non-local environment, including
testing. The CI e2e job serves the app with php artisan serve over plain
http (APP_ENV=testing), so every asset URL became https://localhost:8001/...
and failed with ERR_CONNECTION_CLOSED: login.js never loaded and every
Playwright test timed out waiting for the login form.
…emption lock

verifyRecoveryCode() reads the unused codes, matches the hash and then
re-reads the matched row with a PESSIMISTIC_WRITE lock. That re-read used
EntityManager::refresh(), which hydrates nothing and reports nothing when
the row is gone. If a regeneration or 2FA reset deleted the batch between
the read and the lock, the stale entity still looked unused, markUsed()
updated no row and the sign-in completed with an invalidated code.

refreshExclusiveLock() now re-reads through a locked DQL query with
HINT_REFRESH and returns false when the row no longer exists, and the
strategy rejects the code in that case (SDS idp-mfa rev 2.6, 3.5).
…t's passwordless lifetime (#182)

* fix(2fa): issue MFA codes with two_factor.otp_lifetime, not the client's passwordless lifetime

A login started from an OAuth2 client made OTPFactory take the client's
passwordless otp_lifetime for the MFA code. With 0 ("never expires" for
passwordless login) the login screen rendered the code as already
expired, kept VERIFY disabled and no resend could recover it (every
resend returned lifetime 0 again), while the code itself never expired
server-side.

- EmailOTPMFAChallengeStrategy passes two_factor.otp_lifetime (env
  TWO_FACTOR_OTP_LIFETIME, default 600) as an explicit override;
  non-positive values fall back to 600 with a warning.
- OTPFactory::buildFromPayload / ITokenService::createOTPFromPayload take
  an optional lifetime override (default null, existing callers unchanged).
- Login screen: failed resends (429/500) are shown inline and release the
  resend link instead of silently counting down.

* docs(2fa): session_ttl must cover the effective OTP lifetime, fallback included

* fix(2fa): pending challenge session lives at least as long as the code

two_factor.session_ttl and two_factor.otp_lifetime were independent
knobs with the same default: raising the code lifetime (or lowering the
session TTL) made getPendingState() expire the challenge while the code
and its UI countdown were still valid.

- resolveOtpLifetime() moves to AbstractMFAChallengeStrategy.
- New resolvePendingSessionTtl() = max(session_ttl, effective otp
  lifetime); getPendingState() uses it.

* fix(2fa): anchor the pending challenge session to the code's creation time

issueChallenge() wrote 2fa_pending_at before creating and mailing the
code, so a slow issuance left the code alive for a few seconds after the
pending session had expired. The timestamp is now written after the code
exists and set to its created_at, the same clock isAlive() and the UI
countdown use. A failed issuance no longer leaves an orphan pending state.

* fix(2fa): reject a non-positive OTP lifetime override in OTPFactory

The override exists so MFA codes always expire; accepting 0 would rebuild
the never-expiring code it was added to prevent, and a silent fallback
could land on a client's 0 again.
* feat(2fa): trusted devices list and revoke endpoints

Add GET/DELETE /admin/api/v1/users/me/2fa/devices[/{id}] so a user can
list their active trusted devices and revoke one or all of them
(SDS idp-mfa.md 5.6, CU-86bc647cd).

- Revocation is scoped by owner: another user's device id returns 404.
- Revoking an already revoked or expired device is a 204 no-op and is
  not audited; revoke-all logs one device_revoked event per device it
  actually revokes and none when there are no active devices.
- Audit runs best-effort after the revocation commits, following
  RecoveryCodeService: audit_service->log() opens its own transaction,
  which cannot be nested.
- The device-trust cookie is expired when the revoked device is the one
  the request came from.
- The list never exposes device_identifier or user_agent and flags the
  current device via is_current; it does not touch last_seen_at.
- Replace the bulk revokeAllForUser() UPDATE with a per-entity revoke of
  active devices so each revoked device can be audited.

* feat(profile): trusted devices subsection with revoke actions

Add a Trusted Devices subsection to the profile page (SDS idp-mfa.md
5.5, CU-86bc647cd), shown only when 2FA applies to the user. It lists
the user's active trusted devices (name, IP, trusted, last seen,
expiry), labels the current one, and lets the user revoke a single
device or all of them (with a confirmation), updating the table in
place. Buttons are plain onClick handlers since the profile page is a
single <form>.

Expose the three device endpoints on window from profile.blade.php and
add getTrustedDevices / revokeTrustedDevice / revokeAllTrustedDevices
helpers, covered by Jest tests for the component and the unmocked
request layer.

* refactor(2fa): single bulk revocation, revokeAllActiveForUser, returning the revoked devices

The repository revokes entity by entity inside the caller's transaction and
returns the devices, so callers can log one device_revoked per device after
commit. Replaces the revokeAllForUser contract that other MFA branches rely on.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Sonnet 5.5 <noreply@anthropic.com>
@romanetar
romanetar force-pushed the feat/mfa-phase1---migrations--and--interfaces branch from 295c98b to cf62177 Compare November 16, 2026 15:58
@github-actions

Copy link
Copy Markdown

📘 OpenAPI / Swagger preview

➡️ https://OpenStackweb.github.io/openstackid/openapi/pr-125/

This page is automatically updated on each push to this PR.

Comment thread app/libs/Auth/AuthService.php Resolved
@romanetar
romanetar self-requested a review November 16, 2026 17:40

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

LGTM

* feat(mfa): add idp:enforce-admin-2fa command

Onboards every user of the groups in two_factor.enforced_groups: generates
a recovery code batch, emails the user that MFA is now required (no codes in
the mail or the console output) and records an enrollment_changed audit event
with {"source": "enforce-admin-2fa"}.

Users that already have unused recovery codes are skipped so a saved batch is
never invalidated. Supports --dry-run, chunked queries and processed /
skipped / error counts.

It deliberately does not set two_factor_enabled / two_factor_method /
two_factor_enforced_at: enforcement is derived from group membership by
User::shouldRequire2FA().

* fix(mfa): key enforce-admin-2fa skip on the audit row, written after the mail

The command no longer generates recovery codes (users get them when they
enable 2FA from the profile). The skip criterion is now an
enrollment_changed audit event with source=enforce-admin-2fa, written only
after Mail::send succeeds, so a failed run is retried for exactly the
users whose email failed.

* fix(mfa): refuse to run idp:enforce-admin-2fa when two_factor.enabled is off

With the global kill-switch off shouldRequire2FA() is false for everyone,
so notifying admins that 2FA is required would be wrong. Return FAILURE
with a warning, also for --dry-run.

* docs(adr): add ADR 0002 for idp:enforce-admin-2fa

Records that the command only notifies (no recovery code generation, so
ADR 0001 stays in force), keys the skip on the audit row written after the
mail, and refuses to run when two_factor.enabled is off.

* fix(mfa): clear the EntityManager after each chunk in idp:enforce-admin-2fa

Paging the ids did not bound memory: loaded users and persisted audit rows
stayed managed across chunks and every flush grew with them.

* fix(mfa): escape user-controlled values in the 2FA enforced mail

The full name was rendered with {!! !!}, allowing HTML injection into a
security notification. Also stop claiming that recovery codes were already
set up: the command no longer generates them, the user gets them when
enabling 2FA from the profile.

* test(mfa): set mail.from in TwoFactorEnforcedMailTest

CI does not define MAIL_FROM_EMAIL, so Mailable::from() received a null
address and rendering failed. The test no longer depends on the environment.

* docs(mfa): point enforced users to "Regenerate Codes" in ADR 0002 and the 2FA enforced mail

Group-enforced users never see "Enable Two-Factor Authentication" in the
profile (two_factor_enabled reflects shouldRequire2FA()), so it cannot
generate their first recovery-code batch.

* fix(mfa): rewrite the 2FA enforced mail for users who cannot "enable" 2FA

The mail told enforced users to enable 2FA and "set it up", but nothing needs
to be set up: the email challenge applies at the next sign-in. Say so, and
point to Regenerate Codes, noting that it asks for the current password.
@github-actions

Copy link
Copy Markdown

📘 OpenAPI / Swagger preview

➡️ https://OpenStackweb.github.io/openstackid/openapi/pr-125/

This page is automatically updated on each push to this PR.

* feat(mfa): add IRecoveryCodeService::disableTwoFactor

Shared service method that disables 2FA for a user: clears
two_factor_enabled and two_factor_enforced_at, deletes every recovery code
and revokes every trusted device in a single transaction, then records a
device_revoked audit event best-effort.

The actor decides the password rule: null (console) and another user (admin)
need no password, the user acting on their own account must provide the
current one. The settings_changed audit event is left to the caller, which
knows the context (reason, actor, operator).

Group-enforced users are still challenged at login afterwards, as
enforcement is derived from group membership.

* docs(mfa): document passwordless self-service in disableTwoFactor

A social-only user cannot pass the self-service password check, as
User::checkPassword() returns false for an empty password. Document that
the caller must require another proof of identity (a recent 2FA challenge)
and pin the behaviour with a unit test.

* refactor(mfa): use revokeAllActiveForUser and audit one device_revoked per device

Replaces the revokeAllForUser bulk UPDATE, which the trusted-devices branch
removes. disableTwoFactor and removeTrustedDevices revoke inside their
transaction and log one device_revoked (with device_id) per revoked device
after commit, with the same semantics as the devices-management endpoints.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* test(mfa): expect one device_revoked audit event per device in DisableTwoFactorIntegrationTest

---------

Co-authored-by: Claude Sonnet 5.5 <noreply@anthropic.com>
@github-actions

Copy link
Copy Markdown

📘 OpenAPI / Swagger preview

➡️ https://OpenStackweb.github.io/openstackid/openapi/pr-125/

This page is automatically updated on each push to this PR.

* feat(mfa): add idp:reset-2fa command

Resets 2FA for one user, for operators with server access: requires
--reason (aborts without it), finds the user by email and calls
IRecoveryCodeService::disableTwoFactor, which clears the enrollment, deletes
the recovery codes and revokes the trusted devices in one transaction.

Emits a settings_changed audit event with {reason, actor: "console",
operator} and prints a summary with the number of codes deleted and devices
revoked. Group-enforced users stay challenged at login because enforcement is
derived from group membership; the output says so explicitly.

* fix(mfa): record the process user as the reset-2fa operator

get_current_user() returns the owner of the artisan script, not the OS
user running the command, so the audit operator was always the checkout
owner.
@github-actions

Copy link
Copy Markdown

📘 OpenAPI / Swagger preview

➡️ https://OpenStackweb.github.io/openstackid/openapi/pr-125/

This page is automatically updated on each push to this PR.

)

* feat(2fa): enroll recovery codes at the next 2FA challenge and count them only once acknowledged

A user who requires 2FA and has no usable batch of recovery codes (none,
exhausted or unacknowledged) is now challenged at every sign-in, trusted
device included, and gets the non-dismissable "Save Your Recovery Codes"
modal right after the challenge. A batch counts as usable only after the
user confirms it, and the confirmation is bound to the exact batch shown
(SDS idp-mfa.md rev 2.5 + 2.6, ClickUp 86bcy7rv7).

Backend
- users.recovery_codes_acknowledged_at with a backfill migration.
- RecoveryCodesBatch: the generation methods return the codes and the batch
  id read inside the same locked transaction, so a concurrent regeneration
  cannot pair dead codes with another batch's id.
- Every path that writes or deletes codes (generation, acknowledgment,
  redemption) locks the users row first and re-hydrates the entity.
- POST recovery-codes/enroll (window after a real challenge, 5 per 15 min
  per authenticated user) and recovery-codes/acknowledge; 2fa/enable is
  rejected for users who already require 2FA; regenerate accepts a user
  without a password inside the enrollment window.
- Auth::login() regenerates the session CSRF token, so verify2FA and
  verify2FARecovery return the current csrf_token for the calls that follow.
- Authenticate no longer redirects JSON requests to the session backurl.

Frontend
- Login page enrolls, shows the modal and navigates only after the batch is
  acknowledged; enrollment failures never block the sign-in.
- Profile panel renders the server's status keys and enrolls only when the
  user clicks "Set up recovery codes".

Docs: ADR 0002 supersedes 0001.

* test(e2e): cover the profile recovery-codes panel against the real server

jest covers every panel state in isolation; this spec proves the pieces work
together on the profile page: the real status keys of the profile view, the
real CSRF check on enroll / regenerate / acknowledge, nothing generated on
load or reload, the batch not counted until it is acknowledged, and the
panel's buttons never submitting the page's enclosing form.

It is a single test made of steps because the steps share the signed-in
session and the account's recovery codes. CI seeds its user,
mfa-profile@test.com, in both frontend workflows.

* fix(2fa): restart the acknowledge delay for a replaced batch and wait for the post-acknowledge navigation in e2e

Review feedback on #183.

- RecoveryCodeModal: the 5 second read-before-confirm delay restarted only when
  `open` changed. On the login page a 412 from acknowledge re-enrolls and swaps
  the codes while the modal stays open, so the new batch could be confirmed
  immediately. The countdown now also restarts when the displayed codes change
  (keyed by content, so an equal array passed again does not reset it).
- e2e helper acknowledgeRecoveryCodesModal: optional `expectNavigation` waits for
  the load event of the navigation the login page starts after acknowledging,
  so the page.goto that follows cannot race it. Used by the login flows; the
  profile panel does not navigate, so it keeps the default.

* docs(mfa): renumber the enrollment ADR to 0003 and point the enforced mail to the enrollment modal

- Rename ADR 0002 (recovery-code enrollment) to 0003 now that #166 owns 0002.
- ADR 0001 is superseded by 0003; update the Status of ADR 0002 accordingly.
- Rewrite the TwoFactorEnforcedMail copy: recovery codes are shown once in the
  enrollment modal at the next 2FA challenge, or from the profile.

* fix(2fa): do not re-enroll on its own after a 412 at recovery-code acknowledge

Keep the modal open, drop the dead codes and show a replaced notice with a
"Generate new codes" button, so the user explicitly requests the new batch
(SDS idp-mfa.md §4.10.1, rev 2.6).

* fix(2fa): point the idp:reset-2fa enforced-user warning to the enrollment modal

After a reset, a group-enforced user has no recovery codes, so they get the
enrollment modal right after the next email OTP challenge instead of having
to regenerate codes from the profile.
@github-actions

Copy link
Copy Markdown

📘 OpenAPI / Swagger preview

➡️ https://OpenStackweb.github.io/openstackid/openapi/pr-125/

This page is automatically updated on each push to this PR.

…185)

* fix(login): recover from Turnstile load failures on the login forms

Once the failed-attempts threshold is reached the password and OTP login
forms render Turnstile. When its iframe cannot be loaded the widget never
renders and onError is not always invoked, and the password form answered
a submit with "you must check CAPTCHA" while there was nothing to check.

Use the shared TurnstileCaptcha component and useTurnstileCaptcha hook in
both forms: submitting before a token exists asks the user to wait, no
token after 15s or a Turnstile error shows a failure message with a retry
action, and an expired token re-runs the widget. The OTP form is gated
too, matching UserController::postLogin, which requires the token for
both flows above the threshold.

The captcha state moves out of LoginPage (captcha_value, its three
handlers, the validation branch and the componentDidUpdate reset that only
cleared it): each form owns it and remounts on a flow change.

The shared component, its test and the Turnstile test double are the same
files as in the registration fix (#184).

* fix(auth-ui): keep interactive challenges alive and reload api.js on retry

Same change to the shared Turnstile component as in
#184 (444cde1), so both copies stay identical:
an interactive challenge is no longer timed out as a load failure, and
retry reloads api.js when the script itself never loaded.

The login captcha test now simulates a loaded api.js, so retry exercises
the widget reset path.
@github-actions

Copy link
Copy Markdown

📘 OpenAPI / Swagger preview

➡️ https://OpenStackweb.github.io/openstackid/openapi/pr-125/

This page is automatically updated on each push to this PR.

…oFactor (#186)

* feat(2fa): guard group-enforced users and lock the row in disableTwoFactor

Builds on the disableTwoFactor service method (#169):

- refuse a user or administrator actor on a group-enforced user, as the
  enforcement is derived from group membership (User::isTwoFactorEnforcedByGroup());
  the console path (null actor) stays allowed for manual recovery
- self-service: with a password it must match; a social-only account is
  accepted inside the recovery enrollment window instead
- take the users-row lock before mutating, so it serializes with a concurrent
  regenerate/enroll, and clear recovery_codes_acknowledged_at
- the service writes no enrollment/settings audit event: recording it is the
  caller's responsibility; it keeps one device_revoked event per revoked device

* test(2fa): prove disableTwoFactor clears recovery_codes_acknowledged_at

The integration test now acknowledges the enrolled batch in setUp, asserts
the column is set before disableTwoFactor() and NULL after it. The unit test
orders setRecoveryCodesAcknowledgedAt(null) after lockUserRow(), so moving it
before the lock (where HINT_REFRESH would re-hydrate the user and drop it)
no longer passes.
@github-actions

Copy link
Copy Markdown

📘 OpenAPI / Swagger preview

➡️ https://OpenStackweb.github.io/openstackid/openapi/pr-125/

This page is automatically updated on each push to this PR.

* fix(2fa): show low recovery-codes warning after email OTP sign-in

verify2FA now returns the recovery-codes standing (same payload as
verify2FARecovery) and the login SPA shares one helper for both paths to
show the low-codes warning before navigating to redirect_url. The warning
block no longer depends on the recovery form so it renders after an OTP
verification too.

* fix(2fa): do not warn about 0 recovery codes after email OTP sign-in

A user who passes the email OTP challenge with no unused recovery codes
most likely never generated any (codes are only created on enrollment or
explicit regeneration), so "you have 0 recovery codes left" is misleading
there. Only warn on the OTP path when 0 < remaining < threshold; the
recovery-code path still warns at 0, since the user just burned their
last code.

* fix(2fa): make the recovery-codes status read best-effort after verification

verify2FA() and verify2FARecovery() read the recovery-codes standing after
the second factor is redeemed, the session is established and postLogin()
may have consumed the OAuth2 memento. A failure there turned the sign-in
into a 500 without redirect_url. Log it and return redirect_url without
the status fields instead; the login page already navigates directly when
they are absent.

* fix(2fa): keep the low recovery-codes warning accessible and its redirect intact

Announce the warning (role=alert) and focus Continue when the verify form
unmounts, and hide the account chip's delete action while the warning is
pending: the sign-in already completed server-side, so removing the
account there left the warning beside a fresh sign-in form and cancelled
the OAuth2 request behind its redirect.

* fix(2fa): never block post-verification navigation on sessionStorage failures

Guard the dismissed-warning read/write in the login page so a browser with
blocked site data still shows the warning or navigates after a successful
OTP/recovery verification. Also restore clearMFAUISessionState()'s docblock
to its method.

* test(2fa): only fail getStatus() in the recovery-codes status failure tests

After rebasing on the enrollment modal work, MFAGateService calls
IRecoveryCodeService::requiresRecoveryCodeEnrollment() during login, so a
full mock that only stubbed getStatus() broke the login before reaching the
code under test. Delegate every other method to the real service.

* fix(2fa): ignore Cancel while a 2FA verification is in flight

Cancel during a pending OTP/recovery verify reset the view to the password
form, and the late success response then rendered the low recovery-codes
warning beside it, with Continue completing a sign-in the user had left.
Both forms now ignore Cancel while disableInput is set; a failed
verification clears it, so Cancel works again after an error.

* test(2fa): assert the verify forms unmount when the low-codes warning shows

The rendered-transition test never checked that the OTP form disappears, so
rendering the warning beside it would still pass. Assert it for the OTP path
and add the equivalent rendered test for the recovery-code path.

* fix(validators): treat a phpseclib ValueError on a wrong key password as an invalid key

Decrypting a private key with the wrong password can, by chance (~1/256,
valid padding), yield garbage that phpseclib's ASN.1 parser rejects with a
ValueError instead of NoKeyLoadedException. loadRSAKey() only caught the
latter, making RSAKeyPemValidatorTest flaky in CI.

* fix(2fa): hide the account chip delete action while a verification is in flight

Deleting the chip during a pending OTP/recovery verify ran handleDelete(),
which cancelled the login server-side and reset the view to the password
step; a late success response then navigated away or rendered the low
recovery-codes warning beside the initial form. Same race c24b472 closed
for Cancel, through another entry point. The chip now drops onDelete while
disableInput is set; a failed verification clears it, so it is deletable
again after an error.

* fix(2fa): require CSRF on the admin user update routes

PUT admin/api/v1/users/{id} now accepts two_factor_enabled, but the
admin/api/v1 group only applies ssl+auth and the web group has no CSRF
check. With a SameSite=None session cookie, a cross-site form POST with
_method=PUT could disable another user's 2FA using a logged-in
super-admin's session. Add csrf to the update and pic routes (the admin
form already sends X-CSRF-TOKEN on both) and cover them in the CSRF
regression test.

* Revert "fix(2fa): require CSRF on the admin user update routes"

Pushed to this branch by mistake; the change belongs to #187 (d8b3213).

This reverts commit a19915d.
@github-actions

Copy link
Copy Markdown

📘 OpenAPI / Swagger preview

➡️ https://OpenStackweb.github.io/openstackid/openapi/pr-125/

This page is automatically updated on each push to this PR.

…admin user CRUD (#187)

* feat(2fa): add POST users/me/2fa/disable and expose the 2FA state through an admin user serializer

- disableTwoFactor endpoint: csrf, current password (or the enrollment window for
  a user without one), 412 for a group-enforced user or when 2FA is off, expires
  the device trust cookie
- new AdminUserSerializer (SerializerType_Admin) = private + two_factor_enabled,
  two_factor_method, two_factor_enforced (group-derived) and two_factor_enforced_at,
  used by the admin user CRUD, the admin edit page and the user's own profile
- the private and public serializers keep their shape: OAuth2 clients receive the
  private one and must not get the 2FA state

* feat(2fa): pass the stored 2FA flag and the group enforcement separately to the profile

- getProfile passes two_factor_enabled (stored flag) and two_factor_enforced (group)
- profile.blade.php exposes twoFactorEnforced and DISABLE_TWO_FACTOR_ENDPOINT
- add the disableTwoFactor action; TwoFactorSection treats an enforced user as enabled

* feat(2fa): replace the enable button with a 2FA switch and a disable confirmation dialog

- Switch labelled "Two-Factor Authentication (Email OTP)"; on -> off asks for the
  current password (none for a user without one) and calls the disable endpoint
- group-enforced users see the switch checked and disabled with an explanation
- Jest coverage for the switch, the dialog and the enforced state

* feat(2fa): let a server admin enable or disable 2FA from the user CRUD

- PUT /users/{id} accepts two_factor_enabled; UserService::update applies it only
  when a server admin edits another user and the value differs from the stored one
- enabling goes through IRecoveryCodeService::enableTwoFactorForUser: no recovery
  codes, enrollment_changed audit with actor_id, notification email to the user
- disabling reuses disableTwoFactor; a group-enforced user returns 412 and the
  whole update is rolled back
- PUT /users/me and an admin editing their own account ignore the key

* feat(2fa): add the 2FA checkbox to the admin edit user form

- checkbox bound to two_factor_enabled, normalised to 1/0 like active/email_verified
- a group-enforced user shows it checked and disabled with "Enforced by group membership"
- two_factor_enforced_at shown as read-only text; the read-only 2FA keys are not submitted

* test(2fa): cover the password login after disabling 2FA and for a group-enforced user

- after the user disables 2FA the password alone logs in (Auth::check, no 2fa flow)
- a group-enforced user cannot disable it and is still challenged

* fix(2fa): show the disable password error inside the confirmation dialog

A SweetAlert opens below a MUI Dialog (z-index 1060 vs 1300), so a wrong password
produced an error popup hidden behind the dialog. Resolve the message with
handleErrorResponse and render it inside the dialog instead.

* fix(2fa): roll back the admin user update when 2FA cannot be enabled

enable2FA() runs after the update transaction, so a user without a verified
email got the rest of the edit saved and a 412 back. The email_otp
precondition is now checked inside the transaction, after populate and the
email change, so a refused enable saves nothing.

* fix(2fa): ignore two_factor_enabled on the OAuth2 user update endpoint

PUT /api/v1/users/{id} on the OAuth2 resource server shares the update
rules and UserService::update with the admin CRUD. With a token owned by
an admin, a client could turn another user's 2FA off (wiping recovery
codes and trusted devices) or on, without a password or session. Strip the
key in curateUpdatePayload, like groups, email_verified and active.

* fix(2fa): check group enforcement against the groups of the same update

The admin form sends groups on every save, but the enforced-by-group check
ran before they were applied. Adding an enforced group and disabling 2FA in
one save committed the update and then failed with a 412 after the commit
(no audit entry, no publish); removing the enforced group and disabling 2FA
was refused. Run the check after the groups block, inside the transaction.

* fix(2fa): make the admin 2FA checkbox read only on the admin's own account

UserService::update ignores two_factor_enabled when an admin edits
themselves, so toggling the box on their own record reported "User saved"
without changing anything. Show it disabled with a pointer to the profile,
where turning 2FA off asks for the password.

* fix(2fa): send two_factor_enabled from the admin form only when the admin changed it

A stale form (2FA turned on by the user after the page loaded) sent the old
value on an unrelated save, and the server disabled 2FA and deleted the
recovery codes.

* fix(2fa): publish and audit the admin user update when the 2FA step fails

The profile changes are already committed when the post-commit 2FA change
runs, so they are published and recorded even if it throws.

* fix(2fa): rate limit password confirmation on 2FA disable and code regeneration

Both routes share one per-user budget of failed attempts, so password
guesses cannot move from one route to the other.

* fix(2fa): audit enrollment_changed when 2FA is disabled by the user or an admin

disableTwoFactor never wrote the enrollment_changed event with
enabled/actor_id/reason, and none of its callers did either. Log it from
the service for the self-service and admin actors, mirroring
enableTwoFactorForUser. The console (null actor) keeps logging its own
settings_changed event.

* fix(2fa): audit enrollment_changed in the disable callers, not in the service

The disable service writes no enrollment audit event: the caller owns it
(7c901af), so a rebase onto that commit would otherwise leave 2FA
disables with no trail. Revert 94f3022, which logged it inside
disableTwoFactor, and write enrollment_changed with
{enabled: false, actor_id, reason} from the self-service endpoint
(reason self) and the admin user update (reason admin).

* fix(2fa): describe the recovery code enrollment modal in the admin-enabled email

The email sent the user to the profile to generate recovery codes, but
since #183 a user who requires 2FA and has no codes gets the enrollment
modal right after the OTP at the next sign-in. A social-only user
following the old copy was sent to a page that told them to sign out and
back in. Reuse the wording of two_factor_enforced and keep the profile
link for a new set later.

* fix(2fa): require CSRF on the admin user update routes

PUT admin/api/v1/users/{id} now accepts two_factor_enabled, but the
admin/api/v1 group only applies ssl+auth and the web group has no CSRF
check. With a SameSite=None session cookie, a cross-site form POST with
_method=PUT could disable another user's 2FA using a logged-in
super-admin's session. Add csrf to the update and pic routes (the admin
form already sends X-CSRF-TOKEN on both) and cover them in the CSRF
regression test.

* fix(2fa): refuse a 2FA change from a server admin who is not an administrator

PUT /api/v1/users/{id} is authorized with isOpenIdServerAdmin()
(super-admins or openid-server-admins), but the 2FA change only applied
for isAdmin() || isSuperAdmin(). A member of openid-server-admins alone
got a 201 with the two_factor_enabled key silently ignored. Keep the
stricter administrator requirement and answer 412, rolling back the whole
update, when such a caller would change the value. An unchanged value is
still ignored.

* fix(2fa): refresh the admin form 2FA state from the saved user

save() dropped the response of the user update, so after a save the
checkbox kept the two_factor_enforced and two_factor_enforced_at values
the page was loaded with: removing an enforced group left it checked and
disabled until a reload, adding one left it editable. Return the saved
user from save() (also when a picture is uploaded) and sync the form 2FA
fields and the baseline from it.

* fix(2fa): hide or refresh the trusted devices when the 2FA switch changes

TwoFactorSection kept the switch state to itself while the profile mounted
TrustedDevicesSection from the twoFactorEnabled prop of the page load, so
after turning 2FA off the devices the server had just revoked stayed on
screen as trusted, and after turning it on the section did not appear
until a reload. Lift the state to the profile page through an
onTwoFactorChange callback: the section is mounted only while 2FA is on,
so it fetches a fresh list each time.

* fix(2fa): keep the trusted devices of a group-enforced user on the profile

two_factor_enabled now carries only the stored flag, but the trusted
devices section was still shown from it alone, so a user enforced by group
membership with the flag off lost the device list and the revoke
controls although 2FA still applies to them. Initialize the state that
drives the section from the stored flag or the enforcement.

* fix(2fa): send the CSRF token of the picture upload as a header

The admin edit form passed the token as the third argument of putFile,
which is fileMetadata, so it travelled as a multipart field and
PUT admin/api/v1/users/{id}/pic answered 419 since the route got csrf.
Pass it as the fourth argument (headers) instead.

The profile page had the same misplaced argument on the picture upload,
and sent the token of the profile PUT as a query param. Both now use
the headers argument.

Pin the argument positions in the admin and profile action tests.

* fix(2fa): honour the kill-switch in the profile and guard 2fa/enable on the stored state

With TWO_FACTOR_ENABLED=false shouldRequire2FA() is false for everyone, so after the
profile switched to isTwoFactorEnabled()/isTwoFactorEnforcedByGroup():

- 2fa/enable (still guarded by shouldRequire2FA()) minted a fresh recovery-code batch,
  without the password, for an account that already had 2FA, and left
  two_factor_enabled=true behind for a group-enforced user. It now rejects (412) on the
  stored flag or the group enforcement.
- the profile presented 2FA as in force although no sign-in is challenged. The profile
  view and the admin edit user page now carry two_factor.enabled, and while it is off a
  notice replaces the enforcement text for every user whose switch is on. The switch and
  the subsections keep following the stored flag and the enforcement.

Tests: 2fa/enable answers 412 with the kill-switch off for a stored-flag user and a
group-enforced user, the profile view carries the flag, and the notice is covered in
TwoFactorSection and the admin TwoFactorCheckbox.

* fix(2fa): refuse an admin enabling 2FA for a user already enforced by group

UserService::update only refused the disable for a group-enforced user. The enable went
through: it set the stored flag, which outlives the group membership and keeps the user
enrolled after leaving it, and queued TwoFactorEnabledByAdminMail announcing a recovery
codes window that never appears for a user who already holds an acknowledged batch.
The admin form cannot send it (the checkbox is disabled), a direct PUT can.

The enable is now refused with 412 like the disable, checked against the groups of the
same update and inside the transaction, so a refused change rolls the whole update back.

Tests: enabling an enforced user, and enabling while adding the enforced group in the
same save, answer 412 with the flag at 0 and no mail queued; enabling while removing the
enforced group in the same save succeeds.

* fix(2fa): dispatch UserEmailUpdated only after the 2FA precondition check

A save refused with "Two-factor authentication requires a verified email
address" still queued a verification mail to the new address and a
"USER UPDATED from email" audit action: the UserEmailUpdated listener
flushes inside the open transaction and queued jobs survive the rollback.

Keep clearEmailVerification() where it is and dispatch the event after
the check, so a refused change queues nothing. Adds a regression test.
@github-actions

Copy link
Copy Markdown

📘 OpenAPI / Swagger preview

➡️ https://OpenStackweb.github.io/openstackid/openapi/pr-125/

This page is automatically updated on each push to this PR.

This branch has not been deployed

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

6 participants