Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
26 commits
Select commit Hold shift + click to select a range
81c23d0
feat(2fa): add POST users/me/2fa/disable and expose the 2FA state thr…
romanetar Nov 6, 2026
37b3da1
feat(2fa): pass the stored 2FA flag and the group enforcement separat…
romanetar Nov 6, 2026
54742f8
feat(2fa): replace the enable button with a 2FA switch and a disable …
romanetar Nov 6, 2026
4ae5b47
feat(2fa): let a server admin enable or disable 2FA from the user CRUD
romanetar Nov 6, 2026
4c891ae
feat(2fa): add the 2FA checkbox to the admin edit user form
romanetar Nov 6, 2026
3d5cd1b
test(2fa): cover the password login after disabling 2FA and for a gro…
romanetar Nov 6, 2026
fbf805c
fix(2fa): show the disable password error inside the confirmation dialog
romanetar Nov 6, 2026
4572d35
fix(2fa): roll back the admin user update when 2FA cannot be enabled
romanetar Nov 6, 2026
79ac384
fix(2fa): ignore two_factor_enabled on the OAuth2 user update endpoint
romanetar Nov 6, 2026
210cc6c
fix(2fa): check group enforcement against the groups of the same update
romanetar Nov 6, 2026
4051c87
fix(2fa): make the admin 2FA checkbox read only on the admin's own ac…
romanetar Nov 6, 2026
5b3d3aa
fix(2fa): send two_factor_enabled from the admin form only when the a…
romanetar Nov 6, 2026
39f570a
fix(2fa): publish and audit the admin user update when the 2FA step f…
romanetar Nov 6, 2026
d2638c8
fix(2fa): rate limit password confirmation on 2FA disable and code re…
romanetar Nov 6, 2026
94f3022
fix(2fa): audit enrollment_changed when 2FA is disabled by the user o…
romanetar Nov 18, 2026
b8df7c0
fix(2fa): audit enrollment_changed in the disable callers, not in the…
romanetar Nov 18, 2026
c7ebfd1
fix(2fa): describe the recovery code enrollment modal in the admin-en…
romanetar Nov 18, 2026
d8b3213
fix(2fa): require CSRF on the admin user update routes
romanetar Nov 18, 2026
72372bf
fix(2fa): refuse a 2FA change from a server admin who is not an admin…
romanetar Nov 18, 2026
368da2f
fix(2fa): refresh the admin form 2FA state from the saved user
romanetar Nov 18, 2026
8d96f90
fix(2fa): hide or refresh the trusted devices when the 2FA switch cha…
romanetar Nov 18, 2026
6061de7
fix(2fa): keep the trusted devices of a group-enforced user on the pr…
romanetar Nov 18, 2026
a41c27e
fix(2fa): send the CSRF token of the picture upload as a header
romanetar Nov 19, 2026
2180a46
fix(2fa): honour the kill-switch in the profile and guard 2fa/enable …
romanetar Nov 19, 2026
6715f43
fix(2fa): refuse an admin enabling 2FA for a user already enforced by…
romanetar Nov 19, 2026
ca8ecf8
fix(2fa): dispatch UserEmailUpdated only after the 2FA precondition c…
romanetar Nov 20, 2026
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
2 changes: 2 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -168,3 +168,5 @@ L5_SWAGGER_OPEN_API_SPEC_VERSION=3.1.2
TWO_FACTOR_RECOVERY_ENROLLMENT_WINDOW=600
TWO_FACTOR_MAX_ENROLL_REQUESTS=5
TWO_FACTOR_ENROLL_WINDOW_MINUTES=15
TWO_FACTOR_MAX_PASSWORD_CONFIRM_ATTEMPTS=5
TWO_FACTOR_PASSWORD_CONFIRM_WINDOW_MINUTES=15
7 changes: 6 additions & 1 deletion app/Http/Controllers/AdminController.php
Original file line number Diff line number Diff line change
Expand Up @@ -660,8 +660,13 @@ public function editUser($user_id){
return View::make("admin.edit-user",
[
'user_id' => $user_id,
// a server admin manages their own 2FA from the profile (it asks for the
// password); UserService::update ignores the key when editing oneself
'is_own_account' => $this->auth_service->getCurrentUser()?->getId() == $user->getId(),
// the global kill-switch: while it is off the form says that no sign-in is challenged
'two_factor_globally_enabled' => (bool) config('two_factor.enabled', true),
'user' => json_encode(SerializerRegistry::getInstance()
->getSerializer($user, SerializerRegistry::SerializerType_Private)->serialize('groups')),
->getSerializer($user, SerializerRegistry::SerializerType_Admin)->serialize('groups')),
'countries' => CountryList::getCountries(),
'languages' => $lang2Code,
]
Expand Down
5 changes: 5 additions & 0 deletions app/Http/Controllers/Api/OAuth2/OAuth2UserApiController.php
Original file line number Diff line number Diff line change
Expand Up @@ -258,6 +258,11 @@ protected function curateUpdatePayload(array $payload): array
if (isset($payload['active']))
unset($payload['active']);

// 2FA is managed only from the admin user CRUD (server admin session) or the
// owner's profile, never by an OAuth2 client acting with the token owner's rights
if (array_key_exists('two_factor_enabled', $payload))
unset($payload['two_factor_enabled']);

return HTMLCleaner::cleanData($payload, [
'bio',
'statement_of_interest'
Expand Down
95 changes: 86 additions & 9 deletions app/Http/Controllers/Api/UserApiController.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,24 +16,29 @@
use App\Http\Controllers\Traits\MFACookieManager;
use App\Http\Controllers\Traits\RequestProcessor;
use App\Http\Controllers\UserValidationRulesFactory;
use App\libs\Auth\Models\TwoFactorAuditLog;
use App\libs\Auth\Models\UserTrustedDevice;
use App\ModelSerializers\Auth\UserTrustedDeviceSerializer;
use App\ModelSerializers\SerializerRegistry;
use App\Services\Auth\IDeviceTrustService;
use App\Services\Auth\IRecoveryCodeService;
use App\Services\Auth\ITwoFactorAuditService;
use App\Services\Auth\RecoveryCodesBatch;
use Auth\Repositories\IUserRepository;
use Auth\User;
use Exception;
use Illuminate\Http\Request as LaravelRequest;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Cookie;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Request;
use Illuminate\Support\Facades\Validator;
use models\exceptions\EntityNotFoundException;
use models\exceptions\ValidationException;
use OAuth2\Services\ITokenService;
use OpenId\Services\IUserService;
use Utils\IPHelper;
use Utils\Services\ILogService;

/**
Expand Down Expand Up @@ -62,6 +67,11 @@ final class UserApiController extends APICRUDController
*/
private $device_trust_service;

/**
* @var ITwoFactorAuditService
*/
private $two_factor_audit_service;

/**
* UserApiController constructor.
* @param IUserRepository $user_repository
Expand All @@ -70,6 +80,7 @@ final class UserApiController extends APICRUDController
* @param ITokenService $token_service
* @param IRecoveryCodeService $recovery_code_service
* @param IDeviceTrustService $device_trust_service
* @param ITwoFactorAuditService $two_factor_audit_service
*/
public function __construct
(
Expand All @@ -78,10 +89,12 @@ public function __construct
IUserService $user_service,
ITokenService $token_service,
IRecoveryCodeService $recovery_code_service,
IDeviceTrustService $device_trust_service
IDeviceTrustService $device_trust_service,
ITwoFactorAuditService $two_factor_audit_service
)
{
parent::__construct($user_repository, $user_service, $log_service);
$this->two_factor_audit_service = $two_factor_audit_service;
$this->token_service = $token_service;
$this->recovery_code_service = $recovery_code_service;
$this->device_trust_service = $device_trust_service;
Expand Down Expand Up @@ -172,7 +185,7 @@ public function lock($id)

protected function getAllSerializerType(): string
{
return SerializerRegistry::SerializerType_Private;
return SerializerRegistry::SerializerType_Admin;
}

/**
Expand Down Expand Up @@ -297,12 +310,14 @@ public function enableTwoFactor()
$user = Auth::user();
$method = $data['method'];

// shouldRequire2FA() covers both a stored two_factor_enabled flag and
// group enforcement. An enforced admin must not mint a batch here without
// the password (and would leave two_factor_enabled=true behind, keeping
// them enrolled after leaving the group): they get codes through enroll
// (inside the enrollment window) or regenerate (with the password).
if ($user->shouldRequire2FA()) {
// The stored flag and group enforcement, not shouldRequire2FA(): that one is
// false for everyone while the global kill-switch is off, and then a session
// could replace the batch of an account that already has 2FA without the
// password. An enforced admin must not mint a batch here either (and would
// leave two_factor_enabled=true behind, keeping them enrolled after leaving
// the group): they get codes through enroll (inside the enrollment window)
// or regenerate (with the password).
if ($user->isTwoFactorEnabled() || $user->isTwoFactorEnforcedByGroup()) {
return $this->error412(['method' => ['Two-factor authentication is already required for this account. Use the recovery codes section to set up or regenerate your codes.']]);
}

Expand All @@ -312,6 +327,68 @@ public function enableTwoFactor()
});
}

/**
* Disables 2FA for the current user (SDS idp-mfa.md §5.6). Deletes their recovery
* codes and revokes every trusted device, so the device trust cookie is expired too.
* Requires the current password, or for a user without one a session inside the
* recovery enrollment window (SDS rev 2.6 §4.10.3). Refused for group-enforced users.
*
* @return \Illuminate\Http\JsonResponse|mixed
*/
public function disableTwoFactor()
{
if (!Auth::check())
return $this->error403();

return $this->processRequest(function () {
$data = Request::all();
$validator = Validator::make($data, [
'current_password' => 'sometimes|nullable|string',
]);

if (!$validator->passes()) {
return $this->error412($validator->getMessageBag()->getMessages());
}

$user = Auth::user();

if ($user->isTwoFactorEnforcedByGroup()) {
return $this->error412(['two_factor' => ['Two-factor authentication is required for members of an administrator group and cannot be turned off.']]);
}

if (!$user->isTwoFactorEnabled()) {
return $this->error412(['two_factor' => ['Two-factor authentication is not enabled for this account.']]);
}

// the service enforces current_password / the enrollment window for the
// self-service actor and throws ValidationException (-> 412)
$this->recovery_code_service->disableTwoFactor($user, $data['current_password'] ?? null, $user);

// the service does not audit the enrollment change: the caller owns the event.
// Best-effort, 2FA is already disabled and must not be reported as failed.
try {
$this->two_factor_audit_service->log(
$user,
TwoFactorAuditLog::EventEnrollmentChanged,
$user->getTwoFactorMethod(),
IPHelper::getUserIp(),
['enabled' => false, 'actor_id' => $user->getId(), 'reason' => 'self']
);
} catch (\Throwable $ex) {
Log::warning($ex);
}

// every trusted device was just revoked
Cookie::queue(Cookie::forget(
Config::get('two_factor.cookie_name', 'device_trust_token'),
Config::get('session.path'),
Config::get('session.domain')
));

return $this->ok(['two_factor_enabled' => false]);
});
}

/**
* Invalidates the current user's recovery codes and generates a fresh batch.
* Plaintext codes are returned once in the response and never persisted.
Expand Down Expand Up @@ -544,6 +621,6 @@ public function updatePic($id)

protected function serializerType(): string
{
return SerializerRegistry::SerializerType_Private;
return SerializerRegistry::SerializerType_Admin;
}
}
2 changes: 2 additions & 0 deletions app/Http/Controllers/Factories/UserValidationRulesFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,8 @@ public static function build(array $data, $update = false, ?User $currentUser =
// admin fields
'email_verified' => 'nullable|boolean',
'active' => 'nullable|boolean',
// honoured only for a server admin editing ANOTHER user (UserService::update)
'two_factor_enabled' => 'nullable|boolean',
'groups' => 'sometimes|int_array',
'public_profile_show_photo' => 'sometimes|boolean',
'public_profile_show_fullname' => 'sometimes|boolean',
Expand Down
10 changes: 8 additions & 2 deletions app/Http/Controllers/UserController.php
Original file line number Diff line number Diff line change
Expand Up @@ -1208,13 +1208,19 @@ public function getProfile()

return View::make("profile", array_merge([
'user' => json_encode(SerializerRegistry::getInstance()->getSerializer(
$user, SerializerRegistry::SerializerType_Private)->serialize()),
$user, SerializerRegistry::SerializerType_Admin)->serialize()),
"openid_url" => $this->server_configuration_service->getUserIdentityEndpointURL($user->getIdentifier()),
"sites" => $sites,
'actions' => $actions,
'countries' => CountryList::getCountries(),
'languages' => $lang2Code,
'two_factor_enabled' => $user->shouldRequire2FA(),
// the stored flag, not the effective requirement: the profile needs to tell a
// self-enrolled user (can turn it off) from one enforced by group (cannot)
'two_factor_enabled' => $user->isTwoFactorEnabled(),
'two_factor_enforced' => $user->isTwoFactorEnforcedByGroup(),
Comment thread
smarcet marked this conversation as resolved.
Resolved
// the global kill-switch: while it is off no sign-in is challenged and the profile
// says so instead of presenting the stored setting as in force
'two_factor_globally_enabled' => (bool) config('two_factor.enabled', true),
// The session completed a 2FA challenge within the enrollment window:
// a batch can be generated without the password.
'recovery_codes_window_open' => $window_open,
Expand Down
13 changes: 11 additions & 2 deletions app/Http/Middleware/TwoFactorRateLimitMiddleware.php
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,9 @@
*
* - every request reserves an attempt atomically before the controller runs.
* - verify / recovery: the attempt is refunded unless the response is a failure.
* - resend / otp: every request counts.
* - password_confirm: the attempt is refunded when the request succeeds (2xx),
* so only rejected password confirmations count.
* - resend / otp / enroll: every request counts.
*
* @package App\Http\Middleware
*/
Expand All @@ -54,7 +56,7 @@ public function __construct(private readonly ITwoFactorRateLimitService $rate_li
/**
* @param \Illuminate\Http\Request $request
* @param Closure $next
* @param string $action one of verify|recovery|resend|otp
* @param string $action one of verify|recovery|resend|otp|enroll|password_confirm
* @return mixed
*/
public function handle($request, Closure $next, string $action = ITwoFactorRateLimitService::ActionVerify)
Expand Down Expand Up @@ -99,6 +101,13 @@ public function handle($request, Closure $next, string $action = ITwoFactorRateL
$this->rate_limit_service->refund($action, $subject);
}

// password confirmation: the controller answers a wrong password with a plain
// 412 (no error_code), so any non-2xx response counts as a failed attempt
if ($action === ITwoFactorRateLimitService::ActionPasswordConfirm
&& method_exists($response, 'isSuccessful') && $response->isSuccessful()) {
$this->rate_limit_service->refund($action, $subject);
}

return $response;
}

Expand Down
81 changes: 81 additions & 0 deletions app/Mail/TwoFactorEnabledByAdminMail.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
<?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;
use Illuminate\Support\Facades\URL;

/**
* Class TwoFactorEnabledByAdminMail
* Tells a user that an administrator turned two-factor authentication on for their
* account. The user gets the recovery codes at the next sign-in, in the enrollment
* modal shown after the verification code, or later from the profile page.
* The mail never carries recovery codes.
* @package App\Mail
*/
class TwoFactorEnabledByAdminMail extends Mailable
{
use Queueable, SerializesModels;

public $tries = 2;

/**
* @var string
*/
public $user_email;

/**
* @var string
*/
public $user_fullname;

/**
* @var string
*/
public $profile_url;

/**
* The subject of the message.
*
* @var string
*/
public $subject;

/**
* @param User $user
*/
public function __construct(User $user)
{
$this->user_email = $user->getEmail();
$this->user_fullname = $user->getFullName();
$this->profile_url = URL::action('UserController@getProfile');
}

/**
* @return $this
*/
public function build()
{
$this->subject = sprintf('[%s] Two-factor authentication enabled', Config::get('app.app_name'));
Log::debug(sprintf("TwoFactorEnabledByAdminMail::build to %s", $this->user_email));
return $this->from(Config::get("mail.from"))
->to($this->user_email)
->subject($this->subject)
->view('emails.auth.two_factor_enabled_by_admin');
}
}
Loading
Loading