Repository navigation
feat(mfa): add idp:enforce-admin-2fa command #166
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
romanetar
wants to merge
7
commits into
feat/mfa-phase1---migrations--and--interfaces
from
feat/mfa-admin-enforcement-and-reset-commands
Open
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
c5bb408
feat(mfa): add idp:enforce-admin-2fa command
romanetar ff0e5d2
fix(mfa): key enforce-admin-2fa skip on the audit row, written after …
romanetar b915a3e
fix(mfa): refuse to run idp:enforce-admin-2fa when two_factor.enabled…
romanetar b989a7b
docs(adr): add ADR 0002 for idp:enforce-admin-2fa
romanetar e6f2be3
fix(mfa): clear the EntityManager after each chunk in idp:enforce-adm…
romanetar a8187e9
fix(mfa): escape user-controlled values in the 2FA enforced mail
romanetar d52b952
test(mfa): set mail.from in TwoFactorEnforcedMailTest
romanetar File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,178 @@ | ||
| <?php namespace App\Console\Commands; | ||
| /** | ||
| * Copyright 2026 OpenStack Foundation | ||
| * Licensed under the Apache License, Version 2.0 (the "License"); | ||
| * you may not use this file except in compliance with the License. | ||
| * You may obtain a copy of the License at | ||
| * http://www.apache.org/licenses/LICENSE-2.0 | ||
| * Unless required by applicable law or agreed to in writing, software | ||
| * distributed under the License is distributed on an "AS IS" BASIS, | ||
| * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| * See the License for the specific language governing permissions and | ||
| * limitations under the License. | ||
| **/ | ||
|
|
||
| use App\libs\Auth\Models\TwoFactorAuditLog; | ||
| use App\Mail\TwoFactorEnforcedMail; | ||
| use App\Services\Auth\ITwoFactorAuditService; | ||
| use Auth\User; | ||
| use Illuminate\Console\Command; | ||
| use Illuminate\Support\Facades\Log; | ||
| use Illuminate\Support\Facades\Mail; | ||
| use LaravelDoctrine\ORM\Facades\EntityManager; | ||
|
|
||
| /** | ||
| * Class EnforceAdmin2FACommand | ||
| * Onboards every user of the groups in config('two_factor.enforced_groups'): | ||
| * notification email + audit row (the audit row is the "already notified" marker). It deliberately does NOT touch | ||
| * two_factor_enabled / two_factor_method / two_factor_enforced_at: enforcement | ||
| * is derived from group membership at runtime (User::shouldRequire2FA()). | ||
| * @package App\Console\Commands | ||
| */ | ||
| final class EnforceAdmin2FACommand extends Command | ||
| { | ||
| private const ChunkSize = 100; | ||
|
|
||
| /** | ||
| * The audit ip_address for events originated from the console. | ||
| */ | ||
| private const ConsoleIp = '127.0.0.1'; | ||
|
|
||
| private const AuditSource = 'enforce-admin-2fa'; | ||
|
|
||
| /** | ||
| * @var string | ||
| */ | ||
| protected $signature = 'idp:enforce-admin-2fa {--dry-run : List what would be done without writing anything}'; | ||
|
|
||
| /** | ||
| * @var string | ||
| */ | ||
| protected $description = 'Notify every user of the 2FA enforced groups that 2FA is now required'; | ||
|
|
||
| public function handle(ITwoFactorAuditService $audit_service): int | ||
| { | ||
| // with the global kill-switch off shouldRequire2FA() is false for everyone: | ||
| // telling admins that 2FA is required would be wrong | ||
| if (!config('two_factor.enabled', true)) { | ||
| $this->warn('two_factor.enabled is false (TWO_FACTOR_ENABLED): 2FA is not enforced, refusing to notify. Enable it first.'); | ||
| return self::FAILURE; | ||
| } | ||
|
|
||
| $dry_run = (bool)$this->option('dry-run'); | ||
| $slugs = array_values(array_filter((array)config('two_factor.enforced_groups', []))); | ||
|
|
||
| if (empty($slugs)) { | ||
| $this->warn('No groups configured in two_factor.enforced_groups, nothing to do.'); | ||
| return self::SUCCESS; | ||
| } | ||
|
|
||
| $this->info(sprintf( | ||
| '%sEnforced groups: %s', | ||
| $dry_run ? '[DRY RUN] ' : '', | ||
| implode(', ', $slugs) | ||
| )); | ||
|
|
||
| $processed = 0; | ||
| $skipped = 0; | ||
| $errors = 0; | ||
| $last_id = 0; | ||
|
|
||
| do { | ||
| // keyset pagination over ids, plus a clear() after each chunk below: neither the | ||
| // id list nor the managed entities of previous chunks stay in memory | ||
| $ids = $this->getUserIdsChunk($slugs, $last_id); | ||
|
|
||
| foreach ($ids as $id) { | ||
| $last_id = $id; | ||
| $email = (string)$id; | ||
| try { | ||
| $user = EntityManager::getRepository(User::class)->find($id); | ||
| if (is_null($user)) { | ||
| continue; | ||
| } | ||
| $email = $user->getEmail(); | ||
|
|
||
| // the audit row is written only after the mail was sent, so a failed | ||
| // run leaves no marker and the next run retries exactly those users | ||
| if ($this->wasAlreadyNotified($user)) { | ||
| $skipped++; | ||
| $this->line(sprintf(' skipped %s (already notified)', $email)); | ||
| continue; | ||
| } | ||
|
|
||
| if ($dry_run) { | ||
| $processed++; | ||
| $this->line(sprintf(' would process %s', $email)); | ||
| continue; | ||
| } | ||
|
|
||
| // at-least-once: if the audit write fails after the mail was sent, | ||
| // the user is notified again on the next run | ||
| Mail::send(new TwoFactorEnforcedMail($user)); | ||
|
|
||
| $audit_service->log( | ||
| $user, | ||
| TwoFactorAuditLog::EventEnrollmentChanged, | ||
| TwoFactorAuditLog::MethodEmailOtp, | ||
| self::ConsoleIp, | ||
| ['source' => self::AuditSource] | ||
| ); | ||
|
|
||
| $processed++; | ||
| $this->line(sprintf(' processed %s', $email)); | ||
| } catch (\Throwable $ex) { | ||
| $errors++; | ||
| Log::error($ex); | ||
| $this->error(sprintf(' error %s: %s', $email, $ex->getMessage())); | ||
| } | ||
| } | ||
|
|
||
| // the chunk is done (mails sent, audit rows committed): detach its users and | ||
| // audit rows so the unit of work does not grow, and each flush stays cheap | ||
| EntityManager::clear(); | ||
| } while (count($ids) === self::ChunkSize); | ||
|
|
||
| $this->info(sprintf( | ||
| '%sSummary: processed %d, skipped %d, errors %d', | ||
| $dry_run ? '[DRY RUN] ' : '', | ||
| $processed, | ||
| $skipped, | ||
| $errors | ||
| )); | ||
|
|
||
| return $errors > 0 ? self::FAILURE : self::SUCCESS; | ||
| } | ||
|
|
||
| private function wasAlreadyNotified(User $user): bool | ||
| { | ||
| $logs = EntityManager::getRepository(TwoFactorAuditLog::class)->findBy([ | ||
| 'user' => $user, | ||
| 'event_type' => TwoFactorAuditLog::EventEnrollmentChanged, | ||
| ]); | ||
| foreach ($logs as $log) { | ||
| if (($log->getMetadata()['source'] ?? null) === self::AuditSource) { | ||
| return true; | ||
| } | ||
| } | ||
| return false; | ||
| } | ||
|
|
||
| /** | ||
| * @param string[] $slugs | ||
| * @return int[] | ||
| */ | ||
| private function getUserIdsChunk(array $slugs, int $after_id): array | ||
| { | ||
| $rows = EntityManager::createQuery( | ||
| 'SELECT DISTINCT u.id FROM ' . User::class . ' u JOIN u.groups g ' . | ||
| 'WHERE g.slug IN (:slugs) AND u.id > :after_id ORDER BY u.id ASC' | ||
| ) | ||
| ->setParameter('slugs', $slugs) | ||
| ->setParameter('after_id', $after_id) | ||
| ->setMaxResults(self::ChunkSize) | ||
| ->getScalarResult(); | ||
|
|
||
| return array_map(static fn(array $row) => (int)$row['id'], $rows); | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,68 @@ | ||
| <?php namespace App\Mail; | ||
| /** | ||
| * Copyright 2026 OpenStack Foundation | ||
| * Licensed under the Apache License, Version 2.0 (the "License"); | ||
| * you may not use this file except in compliance with the License. | ||
| * You may obtain a copy of the License at | ||
| * http://www.apache.org/licenses/LICENSE-2.0 | ||
| * Unless required by applicable law or agreed to in writing, software | ||
| * distributed under the License is distributed on an "AS IS" BASIS, | ||
| * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| * See the License for the specific language governing permissions and | ||
| * limitations under the License. | ||
| **/ | ||
|
|
||
| use Auth\User; | ||
| use Illuminate\Bus\Queueable; | ||
| use Illuminate\Mail\Mailable; | ||
| use Illuminate\Queue\SerializesModels; | ||
| use Illuminate\Support\Facades\Config; | ||
| use Illuminate\Support\Facades\Log; | ||
|
|
||
| /** | ||
| * Class TwoFactorEnforcedMail | ||
| * Tells a group-enforced user that MFA is now required on their account. | ||
| * It never carries recovery codes: they are only shown once, in the profile. | ||
| * @package App\Mail | ||
| */ | ||
| final class TwoFactorEnforcedMail extends Mailable | ||
| { | ||
| use Queueable, SerializesModels; | ||
|
|
||
| public $tries = 1; | ||
|
|
||
| /** | ||
| * @var string | ||
| */ | ||
| public $user_email; | ||
|
|
||
| /** | ||
| * @var string | ||
| */ | ||
| public $user_fullname; | ||
|
|
||
| /** | ||
| * @var string | ||
| */ | ||
| public $profile_url; | ||
|
|
||
| public function __construct(User $user) | ||
| { | ||
| $this->user_email = $user->getEmail(); | ||
| $this->user_fullname = $user->getFullName(); | ||
| $this->profile_url = rtrim(Config::get('app.url'), '/') . '/accounts/user/profile'; | ||
| } | ||
|
|
||
| /** | ||
| * @return $this | ||
| */ | ||
| public function build() | ||
| { | ||
| $subject = sprintf("[%s] Two-factor authentication is now required on your account", Config::get('app.app_name')); | ||
| Log::debug(sprintf("TwoFactorEnforcedMail::build to %s", $this->user_email)); | ||
| return $this->from(Config::get("mail.from")) | ||
| ->to($this->user_email) | ||
| ->subject($subject) | ||
| ->view('emails.auth.two_factor_enforced'); | ||
| } | ||
| } |
40 changes: 40 additions & 0 deletions
40
doc/adrs/0002-enforce-admin-2fa-command-notifies-without-generating-codes.md
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,40 @@ | ||
| # 0002. `idp:enforce-admin-2fa` notifies enforced users; it does not generate recovery codes | ||
|
|
||
| ## Status | ||
|
|
||
| Accepted — 2026-11-05. Complements [ADR 0001](0001-recovery-code-generation-not-triggered-by-group-enforcement.md), | ||
| which remains in force. | ||
|
|
||
| ## Context | ||
|
|
||
| Group-based 2FA enforcement is derived at runtime from group membership (`User::shouldRequire2FA()`, | ||
| `config('two_factor.enforced_groups')`). Rolling it out to existing admins needs a one-off operator step that | ||
| tells them 2FA is now required. | ||
|
|
||
| An earlier shape of the command also minted a recovery-code batch per user. That would have contradicted | ||
| ADR 0001 (recovery codes for group-enforced users stay on-demand) and had a delivery bug: the codes were | ||
| committed before the email was sent, so a transient SMTP or audit failure left the user "skipped" on every | ||
| later run (they already had unused codes) and never notified. | ||
|
|
||
| ## Decision | ||
|
|
||
| `php artisan idp:enforce-admin-2fa [--dry-run]`: | ||
|
|
||
| - **Only notifies.** It sends `TwoFactorEnforcedMail` to every user of the enforced groups. It never generates | ||
| recovery codes and never touches `two_factor_enabled`, `two_factor_method` or `two_factor_enforced_at`. | ||
| Users get their codes from the profile ("Enable Two-Factor Authentication" generates the first batch, | ||
| "Regenerate Codes" replaces it), as stated in ADR 0001. The mail links to the profile and carries no codes. | ||
| - **The audit row is the "already notified" marker.** After `Mail::send` succeeds it writes an | ||
| `enrollment_changed` event with metadata `source=enforce-admin-2fa`. Users with such a row are skipped. | ||
| Because the row is written only after the mail was sent, a re-run retries exactly the users whose mail failed. | ||
| Delivery is at-least-once: if the audit write fails after the mail was sent, the user is mailed again. | ||
| - **Refuses to run when `two_factor.enabled` is false** (`TWO_FACTOR_ENABLED`), also with `--dry-run`: with the | ||
| global kill-switch off `shouldRequire2FA()` is false for everyone, so telling admins 2FA is required would be | ||
| wrong. The command warns and exits with failure. | ||
|
|
||
| ## Consequences | ||
|
|
||
| - The command is safe to re-run; `--dry-run` writes and sends nothing. | ||
| - A group-enforced user who is challenged for MFA before visiting their profile still has no recovery codes | ||
| (the negative consequence recorded in ADR 0001 is unchanged). The mail is what steers them to the profile. | ||
| - Operators must enable `TWO_FACTOR_ENABLED` before running the command. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,16 @@ | ||
| <!DOCTYPE html> | ||
| <html lang="en-US"> | ||
| <head> | ||
| <meta charset="utf-8"> | ||
| </head> | ||
| <body> | ||
| <p>Dear {{ $user_fullname }},</p> | ||
| <p>Two-factor authentication (MFA) is now required on your account. You will be asked for a second verification step each time you sign in.</p> | ||
| <p>To set it up, sign in and open the Two-Factor Authentication section of your profile. When you enable it, a set of recovery codes is shown only once, so save it right away:</p> | ||
| <p><a href="{{ $profile_url }}">{{ $profile_url }}</a></p> | ||
| <p>Keep your recovery codes in a safe place: they let you sign in if you lose access to your second factor.</p> | ||
| <br/> | ||
| <br/> | ||
| <p>Cheers,<br/>Your {{ Config::get('app.tenant_name') }} Support Team</p> | ||
| </body> | ||
| </html> |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@romanetar The command doesn't check
two_factor.enabled. With the flag off,User::shouldRequire2FA()returns false for everyone, but this would still email every admin that "Two-factor authentication is now required on your account".The SDS rollout (
idp-mfa.mdsteps 43–46) deploys withTWO_FACTOR_ENABLED=falseand only flips it right before this command, so running the steps out of order is a realistic operator mistake.Suggested fix: at the top of
handle(), return early with awarn()(andself::FAILURE) whenconfig('two_factor.enabled', true)is false. Add a unit test for it.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Done in 5688bea.
handle()now returns early with awarn()andself::FAILUREwhenconfig('two_factor.enabled', true)is false, before any mail or audit write. It also applies to--dry-run, so an operator running the steps out of order doesn't get a misleading summary. AddedtestRefusesToRunWhenTwoFactorIsDisabledGlobally(exit code 1, warning shown, no mail, no audit row, for both normal and dry-run).