Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
178 changes: 178 additions & 0 deletions app/Console/Commands/EnforceAdmin2FACommand.php
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', [])));

Copy link
Copy Markdown
Collaborator

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.md steps 43–46) deploys with TWO_FACTOR_ENABLED=false and 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 a warn() (and self::FAILURE) when config('two_factor.enabled', true) is false. Add a unit test for it.

Copy link
Copy Markdown
Contributor Author

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 a warn() and self::FAILURE when config('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. Added testRefusesToRunWhenTwoFactorIsDisabledGlobally (exit code 1, warning shown, no mail, no audit row, for both normal and dry-run).


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);
}
}
1 change: 1 addition & 0 deletions app/Console/Kernel.php
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ class Kernel extends ConsoleKernel
Commands\CleanOAuth2StaleData::class,
Commands\CleanOpenIdStaleData::class,
Commands\CreateSuperAdmin::class,
Commands\EnforceAdmin2FACommand::class,
Commands\CreateRawUser::class,
Commands\CreateOAuth2TestClient::class,
Commands\GetLatestOtp::class,
Expand Down
68 changes: 68 additions & 0 deletions app/Mail/TwoFactorEnforcedMail.php
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');
}
}
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.
16 changes: 16 additions & 0 deletions resources/views/emails/auth/two_factor_enforced.blade.php
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>
Loading
Loading