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
6 changes: 6 additions & 0 deletions app/Http/Controllers/Api/APICRUDController.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
use App\Http\Controllers\Api\JsonController;
use App\ModelSerializers\SerializerRegistry;
use App\Services\IBaseService;
use Auth\Exceptions\TwoFactorRateLimitedException;
use Illuminate\Support\Facades\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator;
Expand Down Expand Up @@ -150,6 +151,11 @@ protected function _update($id, array $payload)

return $this->updated(SerializerRegistry::getInstance()->getSerializer($entity, $this->serializerType())->serialize());
}
catch (TwoFactorRateLimitedException $ex0)
{
Log::warning($ex0);
return $this->error429($ex0->getRetryAfterSeconds(), $ex0->getLimit());
}
catch (ValidationException $ex1)
{
Log::warning($ex1);
Expand Down
4 changes: 4 additions & 0 deletions app/Http/Controllers/Api/OAuth2/OAuth2UserApiController.php
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
use App\Http\Utils\HTMLCleaner;
use App\ModelSerializers\SerializerRegistry;
use App\ModelSerializers\SerializerUtils;
use Auth\Exceptions\TwoFactorRateLimitedException;
use Auth\Repositories\IUserRepository;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request as LaravelRequest;
Expand Down Expand Up @@ -317,6 +318,9 @@ private function _update($id)
$user = $this->openid_user_service->update($id, $this->curateUpdatePayload($payload));

return $this->updated(SerializerRegistry::getInstance()->getSerializer($user, SerializerRegistry::SerializerType_Private)->serialize());
} catch (TwoFactorRateLimitedException $ex0) {
Log::warning($ex0);
return $this->error429($ex0->getRetryAfterSeconds(), $ex0->getLimit());
} catch (ValidationException $ex1) {
Log::warning($ex1);
return $this->error412($ex1->getMessages());
Expand Down
23 changes: 22 additions & 1 deletion app/Http/Controllers/Traits/JsonResponses.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use App\Services\Auth\ITwoFactorRateLimitService;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Request;
use Illuminate\Support\Facades\Response;
Expand Down Expand Up @@ -102,4 +103,24 @@ protected function error412($messages){
}
return Response::json(array('message' => 'Validation Failed', 'errors' => $messages), HttpResponse::HTTP_PRECONDITION_FAILED);
}
}

/**
* @param int $retry_after_seconds
* @param int|null $limit
* @return mixed
*/
protected function error429(int $retry_after_seconds, ?int $limit = null){
$headers = ['Retry-After' => $retry_after_seconds];
if(!is_null($limit)){
$headers['X-RateLimit-Limit'] = $limit;
$headers['X-RateLimit-Remaining'] = 0;
}
return Response::json(
[
'error_code' => ITwoFactorRateLimitService::RATE_LIMIT_ERROR_CODE,
'error_message' => ITwoFactorRateLimitService::RATE_LIMIT_MESSAGE,
],
HttpResponse::HTTP_TOO_MANY_REQUESTS
)->withHeaders($headers);
}
}
61 changes: 54 additions & 7 deletions app/Services/OpenId/UserService.php
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,9 @@
use App\Services\AbstractService;
use App\Services\Auth\IRecoveryCodeService;
use App\Services\Auth\ITwoFactorAuditService;
use App\Services\Auth\ITwoFactorRateLimitService;
use App\Services\Auth\IUserIdentifierGeneratorService;
use Auth\Exceptions\TwoFactorRateLimitedException;
use Auth\Group;
use Auth\IUserNameGeneratorService;
use Auth\Repositories\IUserRepository;
Expand Down Expand Up @@ -93,6 +95,11 @@ final class UserService extends AbstractService implements IUserService
*/
private $server_ctx;

/**
* @var ITwoFactorRateLimitService
*/
private $rate_limit_service;

/**
* @var IUserIdentifierGeneratorService
*/
Expand Down Expand Up @@ -121,6 +128,7 @@ final class UserService extends AbstractService implements IUserService
* @param IClientRepository $client_repository
* @param IRecoveryCodeService $recovery_code_service
* @param ITwoFactorAuditService $two_factor_audit_service
* @param ITwoFactorRateLimitService $rate_limit_service
*/
public function __construct
(
Expand All @@ -134,10 +142,12 @@ public function __construct
IUserIdentifierGeneratorService $identifier_service,
IClientRepository $client_repository,
IRecoveryCodeService $recovery_code_service,
ITwoFactorAuditService $two_factor_audit_service
ITwoFactorAuditService $two_factor_audit_service,
ITwoFactorRateLimitService $rate_limit_service
)
{
parent::__construct($tx_service);
$this->rate_limit_service = $rate_limit_service;
$this->recovery_code_service = $recovery_code_service;
$this->two_factor_audit_service = $two_factor_audit_service;
$this->repository = $repository;
Expand Down Expand Up @@ -305,6 +315,48 @@ public function create(array $payload): IEntity
return $user;
}

/**
* Checks the current password of a password change. A wrong or missing one counts against the
* password_confirm limit of the acting user, the same counter 2fa/disable and
* recovery-codes/regenerate use (SDS idp-mfa.md section 4.12), so the password cannot be
* guessed through the user update. The counter is keyed by the acting user resolved by
* update() and not by Auth::id(): it is also set on the OAuth2 route, where there is no
* session. Same as the 2fa.rate middleware, the attempt is reserved first and given back when
* the password is right: a successful change never counts, and a user over the limit gets the
* 429 without learning if the password was right.
* @param User $user user to update
* @param User|null $current_user acting user
* @param array $payload
* @throws ValidationException
* @throws TwoFactorRateLimitedException
*/
private function checkCurrentPassword(User $user, ?User $current_user, array $payload): void
{
$action = ITwoFactorRateLimitService::ActionPasswordConfirm;
// no acting user (console / service account): nobody to throttle
$subject = !is_null($current_user) ? (int)$current_user->getId() : null;

if (!is_null($subject)) {
$attempts = $this->rate_limit_service->consume($action, $subject);
if ($attempts > $this->rate_limit_service->getLimit($action)) {
throw new TwoFactorRateLimitedException(
$this->rate_limit_service->getRetryAfterSeconds($action, $subject),
$this->rate_limit_service->getLimit($action),
ITwoFactorRateLimitService::RATE_LIMIT_MESSAGE
);
}
}

if (!isset($payload['current_password']))
throw new ValidationException(sprintf("current_password is needed to update user password."));

if (!$user->checkPassword(trim($payload['current_password'])))
throw new ValidationException(sprintf("current_password is not correct."));

if (!is_null($subject))
$this->rate_limit_service->refund($action, $subject);
}

/**
* @param int $id
* @param array $payload
Expand Down Expand Up @@ -337,12 +389,7 @@ public function update(int $id, array $payload): IEntity
if ($should_ask_4_cur_password_validation) {
if (isset($payload["password"]) && !empty($payload["password"])) {
// changing password
if (!isset($payload['current_password']))
throw new ValidationException(sprintf("current_password is needed to update user password."));

if (!$user->checkPassword(trim($payload['current_password']))) {
throw new ValidationException(sprintf("current_password is not correct."));
}
$this->checkCurrentPassword($user, $current_user, $payload);
}
}

Expand Down
53 changes: 53 additions & 0 deletions app/libs/Auth/Exceptions/TwoFactorRateLimitedException.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
<?php namespace Auth\Exceptions;
/**
* 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 Exception;

/**
* Class TwoFactorRateLimitedException
*
* Raised by a service when a rate limit of the ITwoFactorRateLimitService is
* reached below the HTTP layer (the 2fa.rate middleware cannot see the
* failures of the current-password check of the user update, see SDS
* idp-mfa.md section 4.12). Controllers map it to a 429 with the
* Retry-After header.
*
* @package Auth\Exceptions
*/
final class TwoFactorRateLimitedException extends Exception
{
public function __construct(
private readonly int $retry_after_seconds,
private readonly int $limit,
string $message = ""
)
{
parent::__construct($message, 0, null);
}

/**
* @return int seconds until the window of the limit resets
*/
public function getRetryAfterSeconds(): int
{
return $this->retry_after_seconds;
}

/**
* @return int max attempts of the window
*/
public function getLimit(): int
{
return $this->limit;
}
}
138 changes: 138 additions & 0 deletions tests/OAuth2UserUpdatePasswordRateLimitTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,138 @@
<?php namespace Tests;
/**
* 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\OAuth2\IUserScopes;
use App\Services\Auth\ITwoFactorRateLimitService;
use Auth\User;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\Facades\Session;
use LaravelDoctrine\ORM\Facades\EntityManager;

/**
* PUT api/v1/users/me (OAuth2UserApiController@updateMe), the route event-site calls with an
* access token to change the password: a wrong current_password counts against the
* password_confirm limit of the token owner, with no session (SDS idp-mfa.md section 4.12).
*
* @package Tests
*/
final class OAuth2UserUpdatePasswordRateLimitTest extends OAuth2ProtectedApiTestCase
{
private const PASSWORD = '1Qaz2wsx!';
private const NEW_PASSWORD = 'NewP@ssw0rd!99';
private const MAX_ATTEMPTS = 5;

private int $owner_id;

protected function getScopes()
{
return [
'openid',
IUserScopes::MeWrite,
];
}

protected function prepareForTests(): void
{
parent::prepareForTests();

$owner = EntityManager::getRepository(User::class)->findOneBy(['identifier' => 'sebastian.marcet']);
$this->owner_id = $owner->getId();
$this->clearCounter();

// the token is issued: from here on the request carries only the token, no session
Auth::forgetGuards();
Session::flush();
}

protected function tearDown(): void
{
if (isset($this->owner_id))
$this->clearCounter();
parent::tearDown();
}

private function counterKey(): string
{
return ITwoFactorRateLimitService::RATE_LIMIT_CACHE_KEY_PREFIX
. ITwoFactorRateLimitService::ActionPasswordConfirm . ':' . $this->owner_id;
}

private function clearCounter(): void
{
RateLimiter::clear($this->counterKey());
}

private function owner(): User
{
return EntityManager::getRepository(User::class)->find($this->owner_id);
}

private function changePassword(string $current_password)
{
return $this->action(
"PUT",
"Api\\OAuth2\\OAuth2UserApiController@updateMe",
[],
[],
[],
[],
[
"HTTP_Authorization" => " Bearer " . $this->access_token,
"CONTENT_TYPE" => "application/json",
],
json_encode([
'email' => 'sebastian.marcet@test.invalid',
'current_password' => $current_password,
'password' => self::NEW_PASSWORD,
'password_confirmation' => self::NEW_PASSWORD,
])
);
}

public function testSixthWrongCurrentPasswordAnswers429NotAn500(): void
{
// the middleware limiter has no subject here: nothing logs the token owner into the session guard
$this->assertNull(Auth::id());

for ($i = 0; $i < self::MAX_ATTEMPTS; $i++) {
$this->changePassword('not-the-password');
$this->assertResponseStatus(412);
}

$response = $this->changePassword('not-the-password');
$this->assertResponseStatus(429);
$this->assertGreaterThan(0, (int)$response->headers->get('Retry-After'));

// locked: not even the right password gets through until the window ends
$this->changePassword(self::PASSWORD);
$this->assertResponseStatus(429);
$this->assertTrue($this->owner()->checkPassword(self::PASSWORD));
$this->assertFalse($this->owner()->checkPassword(self::NEW_PASSWORD));
}

public function testCorrectCurrentPasswordWithinTheLimitChangesItAndDoesNotCount(): void
{
for ($i = 0; $i < self::MAX_ATTEMPTS - 1; $i++) {
$this->changePassword('not-the-password');
$this->assertResponseStatus(412);
}

$this->changePassword(self::PASSWORD);
$this->assertResponseStatus(201);

$this->assertTrue($this->owner()->checkPassword(self::NEW_PASSWORD));
$this->assertSame(self::MAX_ATTEMPTS - 1, (int)RateLimiter::attempts($this->counterKey()));
}
}
Loading
Loading