From 7ca1b8ec475d43691984217adeba330849dc79c7 Mon Sep 17 00:00:00 2001 From: romanetar Date: Wed, 2 Dec 2026 16:03:28 +0100 Subject: [PATCH 01/11] fix(oauth2): revoke the tokens of a user when an admin locks the account Locking a user only deactivated the account: the access tokens it held stayed valid and the refresh token grant never checked whether the owner was active, so a refresh token issued before the lock kept producing access tokens. - the refresh token grant rejects an inactive owner with invalid_grant - the administrative lock revokes the user's access and refresh tokens (RevokeUserGrantsOnUserLocked, queued once the lock is committed) - the automatic lock for failed sign-ins does not revoke tokens, so the user is not signed out of every application after a few wrong passwords; the refresh grant still refuses it - add DELETE /admin/api/v1/users/{id}/tokens (server admin) and a Revoke tokens action on the admin users list to revoke every token of a user --- .../Controllers/Api/UserApiController.php | 32 ++ app/Jobs/RevokeUserGrantsOnUserLocked.php | 30 ++ app/Services/OAuth2/TokenService.php | 17 ++ app/Services/OpenId/UserService.php | 13 +- .../LockUserCounterMeasure.php | 5 +- app/libs/OpenId/Services/IUserService.php | 3 +- public/assets/js/admin/users.js | 38 +++ resources/views/admin/users.blade.php | 1 + routes/web.php | 1 + tests/LockUserRevokeTokenTest.php | 273 ++++++++++++++++++ 10 files changed, 409 insertions(+), 4 deletions(-) create mode 100644 app/Jobs/RevokeUserGrantsOnUserLocked.php create mode 100644 tests/LockUserRevokeTokenTest.php diff --git a/app/Http/Controllers/Api/UserApiController.php b/app/Http/Controllers/Api/UserApiController.php index b32c7307c..4810c6560 100644 --- a/app/Http/Controllers/Api/UserApiController.php +++ b/app/Http/Controllers/Api/UserApiController.php @@ -15,6 +15,7 @@ use App\Http\Controllers\APICRUDController; use App\Http\Controllers\Traits\RequestProcessor; use App\Http\Controllers\UserValidationRulesFactory; +use App\Jobs\AddUserAction; use App\ModelSerializers\SerializerRegistry; use Auth\Repositories\IUserRepository; use Auth\User; @@ -27,6 +28,7 @@ use models\exceptions\ValidationException; use OAuth2\Services\ITokenService; use OpenId\Services\IUserService; +use Utils\IPHelper; use Utils\Services\ILogService; /** @@ -197,6 +199,36 @@ public function revokeToken($id, $value){ }); } + /** + * Revokes every access and refresh token held by the given user (server admin only). + * @param $id + * @return mixed + */ + public function revokeAllTokens($id) + { + return $this->processRequest(function () use ($id) { + $user = $this->repository->getById(intval($id)); + if (!$user instanceof User) + throw new EntityNotFoundException(); + + $this->token_service->revokeUsersToken($user->getId()); + + $current_user = Auth::user(); + AddUserAction::dispatch + ( + $user->getId(), + IPHelper::getUserIp(), + sprintf + ( + "All tokens revoked by user %s (%s)", + $current_user instanceof User ? $current_user->getEmail() : 'N/A', + $current_user instanceof User ? $current_user->getId() : 'N/A' + ) + ); + return $this->deleted(); + }); + } + /** * @return array */ diff --git a/app/Jobs/RevokeUserGrantsOnUserLocked.php b/app/Jobs/RevokeUserGrantsOnUserLocked.php new file mode 100644 index 000000000..26c6808cd --- /dev/null +++ b/app/Jobs/RevokeUserGrantsOnUserLocked.php @@ -0,0 +1,30 @@ +getValue(), $scope)); + // a refresh token must not outlive the account that owns it: if the owner was locked + // (deactivated) after the token was issued, the grant is no longer valid + $owner_id = $refresh_token->getUserId(); + if (!is_null($owner_id)) { + $owner = $this->auth_service->getUserById($owner_id); + if (is_null($owner) || !$owner->isActive()) { + throw new InvalidGrantTypeException + ( + sprintf + ( + "Owner of refresh token %s is not active.", + $refresh_token->getValue() + ) + ); + } + } + $refresh_token_value = $refresh_token->getValue(); $refresh_token_hashed_value = Hash::compute('sha256', $refresh_token_value); diff --git a/app/Services/OpenId/UserService.php b/app/Services/OpenId/UserService.php index cb5f56545..99671f73b 100644 --- a/app/Services/OpenId/UserService.php +++ b/app/Services/OpenId/UserService.php @@ -16,6 +16,7 @@ use App\Events\UserPasswordResetSuccessful; use App\Jobs\AddUserAction; use App\Jobs\RevokeUserGrantsOnSessionRevocation; +use App\Jobs\RevokeUserGrantsOnUserLocked; use App\Jobs\PublishUserDeleted; use App\Jobs\PublishUserUpdated; use App\libs\Auth\Factories\UserFactory; @@ -185,16 +186,24 @@ public function updateFailedLoginAttempts(int $user_id): User /** * @param int $user_id + * @param bool $revoke_tokens revoke the OAuth2 grants the user holds (administrative lock); + * the lock caused by failed login attempts does not revoke them * @return User * @throws EntityNotFoundException */ - public function lockUser(int $user_id): User + public function lockUser(int $user_id, bool $revoke_tokens = true): User { - return $this->tx_service->transaction(function () use ($user_id) { + $user = $this->tx_service->transaction(function () use ($user_id) { $user = $this->repository->getById($user_id); if (!$user instanceof User) throw new EntityNotFoundException(); return $user->lock(); }); + + // dispatched once the lock is committed + if ($revoke_tokens) + RevokeUserGrantsOnUserLocked::dispatch($user)->afterResponse(); + + return $user; } /** diff --git a/app/Services/SecurityPolicies/LockUserCounterMeasure.php b/app/Services/SecurityPolicies/LockUserCounterMeasure.php index b38df7b3a..9a55512f2 100644 --- a/app/Services/SecurityPolicies/LockUserCounterMeasure.php +++ b/app/Services/SecurityPolicies/LockUserCounterMeasure.php @@ -92,7 +92,10 @@ public function trigger(array $params = []) AddUserAction::dispatch($user->getId(), IPHelper::getUserIp(), $action); - $this->user_service->lockUser($user->getId()); + // the automatic lock (failed login attempts) does not revoke the user's tokens: + // it would sign the user out of every application. The refresh token grant + // rejects inactive users anyway. + $this->user_service->lockUser($user->getId(), false); } } } catch (Exception $ex) { diff --git a/app/libs/OpenId/Services/IUserService.php b/app/libs/OpenId/Services/IUserService.php index 1d301610d..e9d276f35 100644 --- a/app/libs/OpenId/Services/IUserService.php +++ b/app/libs/OpenId/Services/IUserService.php @@ -40,10 +40,11 @@ public function updateFailedLoginAttempts(int $user_id):User; /** * @param int $user_id + * @param bool $revoke_tokens revoke the OAuth2 tokens the user holds (administrative lock) * @return User * @throws EntityNotFoundException */ - public function lockUser(int $user_id):User; + public function lockUser(int $user_id, bool $revoke_tokens = true):User; /** * @param $user_id diff --git a/public/assets/js/admin/users.js b/public/assets/js/admin/users.js index ae8005b27..6596bcc18 100644 --- a/public/assets/js/admin/users.js +++ b/public/assets/js/admin/users.js @@ -1,6 +1,7 @@ // constructor function UsersCrud(urls, perPage) { var actions = 'Edit' + + ' Revoke tokens' + ' Delete'; this.urls = urls; var _this = this; @@ -42,6 +43,11 @@ function UsersCrud(urls, perPage) { var href = _this.urls.edit; return href.replace('@id', id); }, + 'a.revoke-tokens-item@href': function (arg) { + var id = arg.item.id; + var href = _this.urls.revokeTokens; + return href.replace('@id', id); + }, 'a.delete-item@href': function (arg) { var id = arg.item.id; var href = _this.urls.delete; @@ -73,6 +79,38 @@ UsersCrud.prototype.init = function () { // default sort this.orderBy= encodeURI('+email'); + $("body").on('click', "a.revoke-tokens-item", function (event) { + var url = $(this).attr('href'); + + swal({ + title: 'Are you sure to revoke all the tokens of this User?', + text: 'Every access token and refresh token the User holds will stop working.', + type: "warning", + showCancelButton: true, + confirmButtonColor: "#DD6B55", + confirmButtonText: "Yes, Revoke them!", + }).then(function (result) { + if (result.value) { + $.ajax( + { + type: "DELETE", + url: url, + contentType: "application/json; charset=utf-8", + timeout: 60000, + success: function (data, textStatus, jqXHR) { + swal('Revoked', 'All the tokens of the User were revoked.', 'success'); + }, + error: function (jqXHR, textStatus, errorThrown) { + ajaxError(jqXHR, textStatus, errorThrown); + } + } + ); + } + }); + event.preventDefault(); + return false; + }); + $("body").on('click', ".user-active-checkbox", function (event) { var active = $(this).is(':checked'); var userId = $(this).attr('value'); diff --git a/resources/views/admin/users.blade.php b/resources/views/admin/users.blade.php index 6599d99c9..3ed70e129 100644 --- a/resources/views/admin/users.blade.php +++ b/resources/views/admin/users.blade.php @@ -80,6 +80,7 @@ delete: '{!! URL::action("Api\\UserApiController@delete",["id"=>"@id"]) !!}', unlock: '{!! URL::action("Api\\UserApiController@unlock",["id"=>"@id"]) !!}', lock: '{!! URL::action("Api\\UserApiController@lock",["id"=>"@id"]) !!}', + revokeTokens: '{!! URL::action("Api\\UserApiController@revokeAllTokens",["id"=>"@id"]) !!}', edit: '{!! URL::action("AdminController@editUser",["user_id"=>"@id"]) !!}', fetchGroups: '{!!URL::action("Api\GroupApiController@getAll")!!}', }; diff --git a/routes/web.php b/routes/web.php index b49a35476..288958078 100644 --- a/routes/web.php +++ b/routes/web.php @@ -211,6 +211,7 @@ Route::group(['prefix' => 'access-tokens'], function () { Route::delete('{value}', ['middleware' => ['openstackid.currentuser.serveradmin.json'], 'uses' => "UserApiController@revokeToken"]); }); + Route::delete('tokens', ['middleware' => ['openstackid.currentuser.serveradmin.json'], 'uses' => "UserApiController@revokeAllTokens"]); }); }); diff --git a/tests/LockUserRevokeTokenTest.php b/tests/LockUserRevokeTokenTest.php new file mode 100644 index 000000000..4b66007ca --- /dev/null +++ b/tests/LockUserRevokeTokenTest.php @@ -0,0 +1,273 @@ +current_realm = Config::get('app.url'); + $this->user = EntityManager::getRepository(User::class)->findOneBy(['email' => 'sebastian@tipit.net']); + Session::start(); + $this->be($this->user, 'web'); + } + + public function createApplication() + { + $app = parent::createApplication(); + $app->singleton(UtilsServiceCatalog::ServerConfigurationService, StubServerConfigurationService::class); + return $app; + } + + private function clientAuthHeader(): array + { + return ["HTTP_Authorization" => " Basic " . base64_encode(self::ClientId . ':' . self::ClientSecret)]; + } + + /** + * Runs the auth code flow (offline access) for the current user. + * @return array [access_token, refresh_token] + */ + private function issueTokens(): array + { + Session::put("openid.authorization.response", IAuthService::AuthorizationResponse_AllowOnce); + + $response = $this->action("POST", "OAuth2\OAuth2ProviderController@auth", [ + OAuth2Protocol::OAuth2Protocol_ClientId => self::ClientId, + OAuth2Protocol::OAuth2Protocol_RedirectUri => 'https://www.test.com/oauth2', + OAuth2Protocol::OAuth2Protocol_ResponseType => OAuth2Protocol::OAuth2Protocol_ResponseType_Code, + OAuth2Protocol::OAuth2Protocol_Scope => sprintf('%s/resource-server/read', $this->current_realm), + OAuth2Protocol::OAuth2Protocol_AccessType => OAuth2Protocol::OAuth2Protocol_AccessType_Offline, + ], [], [], []); + + $query = []; + parse_str(parse_url($response->getTargetUrl())['query'], $query); + + $response = $this->action("POST", "OAuth2\OAuth2ProviderController@token", [ + 'code' => $query['code'], + 'redirect_uri' => 'https://www.test.com/oauth2', + 'grant_type' => OAuth2Protocol::OAuth2Protocol_GrantType_AuthCode, + ], [], [], [], $this->clientAuthHeader()); + + $this->assertResponseStatus(200); + $content = json_decode($response->getContent()); + $this->assertNotEmpty($content->access_token); + $this->assertNotEmpty($content->refresh_token); + + return [$content->access_token, $content->refresh_token]; + } + + /** + * Each HTTP request (or queue worker) of production starts with an empty entity manager: reload the user + * so the tokens issued by the previous steps of the test are seen. + */ + private function freshRequestContext(): void + { + EntityManager::refresh($this->user); + $this->be($this->user, 'web'); + } + + /** + * The token endpoint and the introspection endpoint are called by clients (client credentials), + * never with a web session of the user. + */ + private function asClientOnly(): void + { + $this->app['auth']->forgetGuards(); + } + + private function refresh(string $refresh_token) + { + $this->asClientOnly(); + return $this->action("POST", "OAuth2\OAuth2ProviderController@token", [ + 'refresh_token' => $refresh_token, + 'grant_type' => OAuth2Protocol::OAuth2Protocol_GrantType_RefreshToken, + ], [], [], [], $this->clientAuthHeader()); + } + + private function introspect(string $access_token) + { + $this->asClientOnly(); + return $this->action("POST", "OAuth2\OAuth2ProviderController@introspection", [ + 'token' => $access_token, + ], [], [], [], $this->clientAuthHeader()); + } + + /** + * Runs the queued jobs the lock scheduled (the queue is faked on tests). + */ + private function runRevokeJob(): void + { + app()->terminate(); + Queue::assertPushed(RevokeUserGrantsOnUserLocked::class); + $job = Queue::pushed(RevokeUserGrantsOnUserLocked::class)->first(); + // a worker runs the job on a fresh entity manager: drop the user's tokens collection + // loaded before the tokens were issued + $this->freshRequestContext(); + $job->handle(app(ITokenService::class)); + } + + // ------------------------------------------------------------------------- + // Refresh token grant + // ------------------------------------------------------------------------- + + /** + * A refresh token issued before the account was locked gets invalid_grant. + * No job is run here: the grant itself must reject the inactive owner. + */ + public function testRefreshTokenGrantRejectedWhenOwnerIsLocked(): void + { + [, $refresh_token] = $this->issueTokens(); + + // sanity check: the refresh token works while the user is active + $this->refresh($refresh_token); + $this->assertResponseStatus(200); + + // automatic lock: nothing is revoked, only the account is deactivated + app(IUserService::class)->lockUser($this->user->getId(), false); + + $response = $this->refresh($refresh_token); + $this->assertResponseStatus(400); + $this->assertEquals(OAuth2Protocol::OAuth2Protocol_Error_InvalidGrant, json_decode($response->getContent())->error); + } + + // ------------------------------------------------------------------------- + // Lock revokes the tokens + // ------------------------------------------------------------------------- + + /** + * After an administrative lock (DELETE /admin/api/v1/users/{id}/locked) the access tokens issued + * before it introspect as invalid_token and the refresh token is rejected. + */ + public function testAdministrativeLockRevokesUserTokens(): void + { + [$access_token, $refresh_token] = $this->issueTokens(); + + $this->introspect($access_token); + $this->assertResponseStatus(200); + + $this->be($this->user, 'web'); + $this->delete(sprintf('/admin/api/v1/users/%s/locked', $this->user->getId())) + ->assertResponseStatus(201); + + $this->runRevokeJob(); + + $response = $this->introspect($access_token); + $this->assertResponseStatus(400); + $this->assertEquals(OAuth2Protocol::OAuth2Protocol_Error_InvalidToken, json_decode($response->getContent())->error); + + $response = $this->refresh($refresh_token); + $this->assertResponseStatus(400); + $this->assertEquals(OAuth2Protocol::OAuth2Protocol_Error_InvalidGrant, json_decode($response->getContent())->error); + } + + /** + * The lock caused by failed login attempts must not sign the user out of every application. + */ + public function testAutomaticLockDoesNotScheduleTokensRevocation(): void + { + app(IUserService::class)->lockUser($this->user->getId(), false); + app()->terminate(); + + Queue::assertNotPushed(RevokeUserGrantsOnUserLocked::class); + } + + public function testAdministrativeLockSchedulesTokensRevocation(): void + { + app(IUserService::class)->lockUser($this->user->getId()); + app()->terminate(); + + Queue::assertPushed(RevokeUserGrantsOnUserLocked::class); + } + + // ------------------------------------------------------------------------- + // Revoke every token of a user + // ------------------------------------------------------------------------- + + /** + * A server admin revokes every token of a user with one API call. + */ + public function testServerAdminRevokesAllTokensOfAUser(): void + { + [$access_token, $refresh_token] = $this->issueTokens(); + + $this->freshRequestContext(); + $this->delete(sprintf('/admin/api/v1/users/%s/tokens', $this->user->getId())) + ->assertResponseStatus(204); + + $response = $this->introspect($access_token); + $this->assertResponseStatus(400); + $this->assertEquals(OAuth2Protocol::OAuth2Protocol_Error_InvalidToken, json_decode($response->getContent())->error); + + $this->refresh($refresh_token); + $this->assertResponseStatus(400); + } + + public function testRevokeAllTokensOfUnknownUserReturns404(): void + { + $this->be($this->user, 'web'); + $this->delete('/admin/api/v1/users/99999999/tokens') + ->assertResponseStatus(404); + } + + public function testNonAdminCannotRevokeAllTokensOfAUser(): void + { + [$access_token] = $this->issueTokens(); + + // every seeded user is a super admin: take the groups away (in memory) from one of them + $non_admin = EntityManager::getRepository(User::class)->findOneBy(['email' => 'mkiss@tipit.net']); + foreach ($non_admin->getGroups()->toArray() as $group) { + $non_admin->removeFromGroup($group); + } + $this->assertFalse($non_admin->isOpenIdServerAdmin()); + $this->be($non_admin, 'web'); + + // the server admin middleware answers with an error payload and does not reach the controller + $this->delete(sprintf('/admin/api/v1/users/%s/tokens', $this->user->getId())) + ->seeJson(['error' => 'you are not allowed to perform this operation']); + + // the tokens of the user are untouched + $this->introspect($access_token); + $this->assertResponseStatus(200); + } +} From f816442ff8f777f86940f74781d1f74a5afec3f8 Mon Sep 17 00:00:00 2001 From: romanetar Date: Wed, 2 Dec 2026 16:11:35 +0100 Subject: [PATCH 02/11] feat(admin): revoke all the tokens of a user from the edit user page Move the "Revoke tokens" action from the users list to the edit user page, next to the user's access tokens: a confirmation dialog, then DELETE /admin/api/v1/users/{id}/tokens, and the tokens table is reloaded. The users list goes back to what it was. --- public/assets/js/admin/users.js | 38 ----------------------- resources/js/admin/edit_user/actions.js | 7 ++++- resources/js/admin/edit_user/edit_user.js | 35 +++++++++++++++++++-- resources/views/admin/edit-user.blade.php | 1 + resources/views/admin/users.blade.php | 1 - 5 files changed, 40 insertions(+), 42 deletions(-) diff --git a/public/assets/js/admin/users.js b/public/assets/js/admin/users.js index 6596bcc18..ae8005b27 100644 --- a/public/assets/js/admin/users.js +++ b/public/assets/js/admin/users.js @@ -1,7 +1,6 @@ // constructor function UsersCrud(urls, perPage) { var actions = 'Edit' + - ' Revoke tokens' + ' Delete'; this.urls = urls; var _this = this; @@ -43,11 +42,6 @@ function UsersCrud(urls, perPage) { var href = _this.urls.edit; return href.replace('@id', id); }, - 'a.revoke-tokens-item@href': function (arg) { - var id = arg.item.id; - var href = _this.urls.revokeTokens; - return href.replace('@id', id); - }, 'a.delete-item@href': function (arg) { var id = arg.item.id; var href = _this.urls.delete; @@ -79,38 +73,6 @@ UsersCrud.prototype.init = function () { // default sort this.orderBy= encodeURI('+email'); - $("body").on('click', "a.revoke-tokens-item", function (event) { - var url = $(this).attr('href'); - - swal({ - title: 'Are you sure to revoke all the tokens of this User?', - text: 'Every access token and refresh token the User holds will stop working.', - type: "warning", - showCancelButton: true, - confirmButtonColor: "#DD6B55", - confirmButtonText: "Yes, Revoke them!", - }).then(function (result) { - if (result.value) { - $.ajax( - { - type: "DELETE", - url: url, - contentType: "application/json; charset=utf-8", - timeout: 60000, - success: function (data, textStatus, jqXHR) { - swal('Revoked', 'All the tokens of the User were revoked.', 'success'); - }, - error: function (jqXHR, textStatus, errorThrown) { - ajaxError(jqXHR, textStatus, errorThrown); - } - } - ); - } - }); - event.preventDefault(); - return false; - }); - $("body").on('click', ".user-active-checkbox", function (event) { var active = $(this).is(':checked'); var userId = $(this).attr('value'); diff --git a/resources/js/admin/edit_user/actions.js b/resources/js/admin/edit_user/actions.js index ca278dcd5..5fc0329ba 100644 --- a/resources/js/admin/edit_user/actions.js +++ b/resources/js/admin/edit_user/actions.js @@ -1,4 +1,4 @@ -import {getRawRequest, putFile, putRawRequest} from "../../base_actions"; +import {deleteRawRequest, getRawRequest, putFile, putRawRequest} from "../../base_actions"; import moment from "moment"; export const PAGE_SIZE = 10; @@ -56,6 +56,11 @@ export const getUserActions = async (page = 1, order = 'created_at', orderDir = return response; } +// revokes every access token and refresh token the user holds +export const revokeAllUserTokens = async (token) => { + return deleteRawRequest(window.REVOKE_ALL_USER_TOKENS_ENDPOINT)({'X-CSRF-TOKEN': token}); +} + export const fetchGroups = async (url, query) => { const params = { page: 1, diff --git a/resources/js/admin/edit_user/edit_user.js b/resources/js/admin/edit_user/edit_user.js index ca6adf34a..2213f08cf 100644 --- a/resources/js/admin/edit_user/edit_user.js +++ b/resources/js/admin/edit_user/edit_user.js @@ -21,7 +21,7 @@ import RichTextEditor from "../../components/rich_text_editor"; import FormControlLabel from "@material-ui/core/FormControlLabel"; import UserActionsGrid from "../../components/user_actions_grid"; import UserAccessTokensGrid from "../../components/user_access_tokens_grid"; -import {getUserActions, PAGE_SIZE, save} from "./actions"; +import {getUserActions, PAGE_SIZE, revokeAllUserTokens, save} from "./actions"; import ProfileImageUploader from "./components/profile_image_uploader/profile_image_uploader"; import Navbar from "../../components/navbar/navbar"; import Divider from "@material-ui/core/Divider"; @@ -109,6 +109,26 @@ const EditUserPage = ({ }); }; + const confirmRevokeAllTokens = () => { + Swal({ + title: 'Are you sure to revoke all the tokens of this user?', + text: 'Every access token and refresh token the user holds will stop working. This is an non reversible process!', + showCancelButton: true, + confirmButtonColor: '#3085d6', + cancelButtonColor: '#d33', + confirmButtonText: 'Yes, revoke them!' + }).then((result) => { + if (result.value) { + revokeAllUserTokens(csrfToken).then(() => { + Swal('Tokens revoked', 'All the tokens of the user have been revoked successfully', 'success'); + setAccessTokensListRefresh(!accessTokensListRefresh); + }).catch((err) => { + handleErrorResponse(err); + }); + } + }); + }; + return ( @@ -836,10 +856,21 @@ const EditUserPage = ({ - + User Access Tokens + {/* the page is a single
: this must not be a submit button */} + {!! script_to('assets/editUser.js') !!} @append \ No newline at end of file diff --git a/resources/views/admin/users.blade.php b/resources/views/admin/users.blade.php index 3ed70e129..6599d99c9 100644 --- a/resources/views/admin/users.blade.php +++ b/resources/views/admin/users.blade.php @@ -80,7 +80,6 @@ delete: '{!! URL::action("Api\\UserApiController@delete",["id"=>"@id"]) !!}', unlock: '{!! URL::action("Api\\UserApiController@unlock",["id"=>"@id"]) !!}', lock: '{!! URL::action("Api\\UserApiController@lock",["id"=>"@id"]) !!}', - revokeTokens: '{!! URL::action("Api\\UserApiController@revokeAllTokens",["id"=>"@id"]) !!}', edit: '{!! URL::action("AdminController@editUser",["user_id"=>"@id"]) !!}', fetchGroups: '{!!URL::action("Api\GroupApiController@getAll")!!}', }; From ac87518ef255292cebc8204da37b2672d2eda461 Mon Sep 17 00:00:00 2001 From: romanetar Date: Wed, 2 Dec 2026 16:13:04 +0100 Subject: [PATCH 03/11] style(admin): put the revoke all tokens button below the tokens grid, wider and red --- resources/js/admin/edit_user/edit_user.js | 26 ++++++++++--------- .../js/admin/edit_user/edit_user.module.scss | 10 +++++++ 2 files changed, 24 insertions(+), 12 deletions(-) diff --git a/resources/js/admin/edit_user/edit_user.js b/resources/js/admin/edit_user/edit_user.js index 2213f08cf..322c478f1 100644 --- a/resources/js/admin/edit_user/edit_user.js +++ b/resources/js/admin/edit_user/edit_user.js @@ -856,21 +856,10 @@ const EditUserPage = ({ - + User Access Tokens - {/* the page is a single : this must not be a submit button */} - + + {/* the page is a single : this must not be a submit button */} + + diff --git a/resources/js/admin/edit_user/edit_user.module.scss b/resources/js/admin/edit_user/edit_user.module.scss index ec9e5610e..b3c454e8c 100644 --- a/resources/js/admin/edit_user/edit_user.module.scss +++ b/resources/js/admin/edit_user/edit_user.module.scss @@ -29,6 +29,16 @@ background-color: $base-color-dark; } + .button_danger { + width: 260px; + color: white; + background-color: #f44336; + + &:hover { + background-color: #d32f2f; + } + } + .countries, .genders, .languages { height: 40px !important; From 267acf3a613e7902eda66b4544e42fc991212c7f Mon Sep 17 00:00:00 2001 From: romanetar Date: Wed, 2 Dec 2026 16:19:57 +0100 Subject: [PATCH 04/11] style(admin): match the revoke all tokens button to "Sign out all other devices" Same outlined secondary button, aligned to the right below the tokens grid. --- resources/js/admin/edit_user/edit_user.js | 9 ++++----- resources/js/admin/edit_user/edit_user.module.scss | 10 ---------- 2 files changed, 4 insertions(+), 15 deletions(-) diff --git a/resources/js/admin/edit_user/edit_user.js b/resources/js/admin/edit_user/edit_user.js index 322c478f1..2a33faeed 100644 --- a/resources/js/admin/edit_user/edit_user.js +++ b/resources/js/admin/edit_user/edit_user.js @@ -872,17 +872,16 @@ const EditUserPage = ({ onRevoke={confirmRevocation} /> - + {/* the page is a single : this must not be a submit button */} diff --git a/resources/js/admin/edit_user/edit_user.module.scss b/resources/js/admin/edit_user/edit_user.module.scss index b3c454e8c..ec9e5610e 100644 --- a/resources/js/admin/edit_user/edit_user.module.scss +++ b/resources/js/admin/edit_user/edit_user.module.scss @@ -29,16 +29,6 @@ background-color: $base-color-dark; } - .button_danger { - width: 260px; - color: white; - background-color: #f44336; - - &:hover { - background-color: #d32f2f; - } - } - .countries, .genders, .languages { height: 40px !important; From ea4cb90c8bbb18bd0846d9d25e4faf93fbd99c23 Mon Sep 17 00:00:00 2001 From: romanetar Date: Wed, 2 Dec 2026 16:35:39 +0100 Subject: [PATCH 05/11] fix(admin): refresh the access tokens grid with a functional state update Both revoke handlers (one token, all tokens) toggled the refresh flag from the value captured when the handler was created, so two overlapping revocations wrote the same value and the second one did not reload the grid. Toggle from the latest state instead. --- resources/js/admin/edit_user/edit_user.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/resources/js/admin/edit_user/edit_user.js b/resources/js/admin/edit_user/edit_user.js index 2a33faeed..4371958a1 100644 --- a/resources/js/admin/edit_user/edit_user.js +++ b/resources/js/admin/edit_user/edit_user.js @@ -101,7 +101,7 @@ const EditUserPage = ({ if (result.value) { revokeToken(value, 'access-token').then(() => { Swal(`Access token revoked`, `The access token has been revoked successfully`, "success"); - setAccessTokensListRefresh(!accessTokensListRefresh); + setAccessTokensListRefresh(prev => !prev); }).catch((err) => { handleErrorResponse(err); }); @@ -121,7 +121,7 @@ const EditUserPage = ({ if (result.value) { revokeAllUserTokens(csrfToken).then(() => { Swal('Tokens revoked', 'All the tokens of the user have been revoked successfully', 'success'); - setAccessTokensListRefresh(!accessTokensListRefresh); + setAccessTokensListRefresh(prev => !prev); }).catch((err) => { handleErrorResponse(err); }); From bdc8ed664c53d61e7c3a878a342eb814d30bd07d Mon Sep 17 00:00:00 2001 From: romanetar Date: Wed, 2 Dec 2026 17:24:03 +0100 Subject: [PATCH 06/11] fix(oauth2): stop issuing tokens to a locked user through a live session or a pending code The lock revoked the user's tokens, but a web session opened before the lock kept the user authenticated, so the authorization endpoint issued new codes and the token endpoint exchanged them for a new access token and refresh token. - InteractiveGrantType::mustAuthenticateUser ends the session of an inactive user and sends the request through the login, which refuses locked users (prompt=none answers login_required). - TokenService::createAccessToken rejects the exchange of an authorization code whose owner is no longer active with invalid_grant. The passwordless grant was already covered: AuthService::loginWithOTP requires canLogin(). --- app/Services/OAuth2/TokenService.php | 13 ++++ .../GrantTypes/InteractiveGrantType.php | 17 +++++ tests/LockUserRevokeTokenTest.php | 72 +++++++++++++++++-- 3 files changed, 96 insertions(+), 6 deletions(-) diff --git a/app/Services/OAuth2/TokenService.php b/app/Services/OAuth2/TokenService.php index a3c610567..4a60e03a8 100644 --- a/app/Services/OAuth2/TokenService.php +++ b/app/Services/OAuth2/TokenService.php @@ -424,6 +424,19 @@ public function createAccessToken(AuthorizationCode $auth_code, $redirect_uri = $client = $this->client_repository->getClientById($client_id); $user = $this->auth_service->getUserById($user_id); + // an authorization code issued before the owner was locked (deactivated) must not be + // exchanged for tokens once the lock is in place + if (!is_null($user_id) && (is_null($user) || !$user->isActive())) { + throw new InvalidGrantTypeException + ( + sprintf + ( + "Owner of authorization code %s is not active.", + $auth_code->getValue() + ) + ); + } + // TODO; move to a factory $access_token_db = new AccessTokenDB(); diff --git a/app/libs/OAuth2/GrantTypes/InteractiveGrantType.php b/app/libs/OAuth2/GrantTypes/InteractiveGrantType.php index 68c031a97..b0c520e00 100644 --- a/app/libs/OAuth2/GrantTypes/InteractiveGrantType.php +++ b/app/libs/OAuth2/GrantTypes/InteractiveGrantType.php @@ -827,6 +827,23 @@ protected function mustAuthenticateUser(OAuth2AuthorizationRequest $request, Cli if (!$this->auth_service->isUserLogged()) return true; + // a session opened before the user was locked (deactivated) must not keep issuing + // authorization codes: end it and send the request through the login, which refuses locked users + $current_user = $this->auth_service->getCurrentUser(); + if (is_null($current_user) || !$current_user->isActive()) + { + Log::warning + ( + sprintf + ( + "InteractiveGrant::mustAuthenticateUser: current user %s is not active", + is_null($current_user) ? 'N/A' : $current_user->getId() + ) + ); + $this->auth_service->logout(false); + return true; + } + return false; } } \ No newline at end of file diff --git a/tests/LockUserRevokeTokenTest.php b/tests/LockUserRevokeTokenTest.php index 4b66007ca..88572509c 100644 --- a/tests/LockUserRevokeTokenTest.php +++ b/tests/LockUserRevokeTokenTest.php @@ -65,29 +65,50 @@ private function clientAuthHeader(): array } /** - * Runs the auth code flow (offline access) for the current user. - * @return array [access_token, refresh_token] + * Runs the authorization endpoint (offline access) for the current user. + * @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse */ - private function issueTokens(): array + private function authorize() { Session::put("openid.authorization.response", IAuthService::AuthorizationResponse_AllowOnce); - $response = $this->action("POST", "OAuth2\OAuth2ProviderController@auth", [ + return $this->action("POST", "OAuth2\OAuth2ProviderController@auth", [ OAuth2Protocol::OAuth2Protocol_ClientId => self::ClientId, OAuth2Protocol::OAuth2Protocol_RedirectUri => 'https://www.test.com/oauth2', OAuth2Protocol::OAuth2Protocol_ResponseType => OAuth2Protocol::OAuth2Protocol_ResponseType_Code, OAuth2Protocol::OAuth2Protocol_Scope => sprintf('%s/resource-server/read', $this->current_realm), OAuth2Protocol::OAuth2Protocol_AccessType => OAuth2Protocol::OAuth2Protocol_AccessType_Offline, ], [], [], []); + } + /** + * @return string the authorization code issued to the current user + */ + private function issueCode(): string + { + $response = $this->authorize(); $query = []; parse_str(parse_url($response->getTargetUrl())['query'], $query); + $this->assertArrayHasKey('code', $query); + return $query['code']; + } - $response = $this->action("POST", "OAuth2\OAuth2ProviderController@token", [ - 'code' => $query['code'], + private function exchangeCode(string $code) + { + return $this->action("POST", "OAuth2\OAuth2ProviderController@token", [ + 'code' => $code, 'redirect_uri' => 'https://www.test.com/oauth2', 'grant_type' => OAuth2Protocol::OAuth2Protocol_GrantType_AuthCode, ], [], [], [], $this->clientAuthHeader()); + } + + /** + * Runs the auth code flow (offline access) for the current user. + * @return array [access_token, refresh_token] + */ + private function issueTokens(): array + { + $response = $this->exchangeCode($this->issueCode()); $this->assertResponseStatus(200); $content = json_decode($response->getContent()); @@ -171,6 +192,45 @@ public function testRefreshTokenGrantRejectedWhenOwnerIsLocked(): void $this->assertEquals(OAuth2Protocol::OAuth2Protocol_Error_InvalidGrant, json_decode($response->getContent())->error); } + // ------------------------------------------------------------------------- + // No new tokens for a locked user + // ------------------------------------------------------------------------- + + /** + * An authorization code issued before the lock cannot be exchanged once the account is locked. + */ + public function testAuthorizationCodeIssuedBeforeLockIsRejected(): void + { + $code = $this->issueCode(); + + app(IUserService::class)->lockUser($this->user->getId(), false); + + $this->asClientOnly(); + $response = $this->exchangeCode($code); + $this->assertResponseStatus(400); + $this->assertEquals(OAuth2Protocol::OAuth2Protocol_Error_InvalidGrant, json_decode($response->getContent())->error); + } + + /** + * A web session opened before the lock does not get new authorization codes: the session is ended + * and the request goes to the login. + */ + public function testWebSessionOfLockedUserDoesNotGetNewAuthorizationCodes(): void + { + // sanity check: the session gets a code while the user is active + $this->issueCode(); + + app(IUserService::class)->lockUser($this->user->getId(), false); + + $this->be($this->user, 'web'); + $response = $this->authorize(); + + $query = []; + parse_str(parse_url($response->getTargetUrl(), PHP_URL_QUERY) ?? '', $query); + $this->assertArrayNotHasKey('code', $query); + $this->assertFalse($this->app['auth']->guard('web')->check()); + } + // ------------------------------------------------------------------------- // Lock revokes the tokens // ------------------------------------------------------------------------- From 3c85ff536c3041b53440fb68d4244b197656dcf5 Mon Sep 17 00:00:00 2001 From: romanetar Date: Wed, 2 Dec 2026 17:24:47 +0100 Subject: [PATCH 07/11] fix(admin): revoke the tokens of a user deactivated from the edit user page Unchecking "Active" on the edit user page (PUT /admin/api/v1/users/{id}) went through UserService::update and UserFactory::populate, which deactivate the user without passing through lockUser(), so the tokens the user held stayed valid. UserService::update now detects the change from active to inactive and queues RevokeUserGrantsOnUserLocked once the update is committed, like the administrative lock. --- app/Services/OpenId/UserService.php | 14 ++++++++++++- tests/LockUserRevokeTokenTest.php | 31 +++++++++++++++++++++++++++++ 2 files changed, 44 insertions(+), 1 deletion(-) diff --git a/app/Services/OpenId/UserService.php b/app/Services/OpenId/UserService.php index 99671f73b..e06d5429a 100644 --- a/app/Services/OpenId/UserService.php +++ b/app/Services/OpenId/UserService.php @@ -304,8 +304,9 @@ public function create(array $payload): IEntity public function update(int $id, array $payload): IEntity { $password_changed = false; + $deactivated = false; - $user = $this->tx_service->transaction(function () use ($id, $payload, &$password_changed) { + $user = $this->tx_service->transaction(function () use ($id, $payload, &$password_changed, &$deactivated) { $user = $this->repository->getById($id); @@ -314,6 +315,7 @@ public function update(int $id, array $payload): IEntity $former_email = $user->getEmail(); $former_password = $user->getPassword(); + $former_active = $user->isActive(); $current_user = !empty($this->server_ctx->getCurrentUserId()) ? $this->repository->getById($this->server_ctx->getCurrentUserId()) : Auth::user(); $should_ask_4_cur_password_validation = !(!is_null($current_user) && $user->getId() != $current_user->getId() && // is not the same user as current user @@ -388,6 +390,11 @@ public function update(int $id, array $payload): IEntity $password_changed = true; } + if ($former_active && !$user->isActive()) { + Log::warning(sprintf("UserService::update user id %s - deactivated", $id)); + $deactivated = true; + } + return $user; }); @@ -396,6 +403,11 @@ public function update(int $id, array $payload): IEntity Event::dispatch(new UserPasswordResetSuccessful($user->getId())); } + // deactivating the user (the "Active" checkbox of the edit user page) is an administrative lock: + // revoke the tokens it holds, once the update is committed + if ($deactivated) + RevokeUserGrantsOnUserLocked::dispatch($user)->afterResponse(); + try { if (Config::get("queue.enable_message_broker", false) == true) PublishUserUpdated::dispatch($user)->onConnection('message_broker'); diff --git a/tests/LockUserRevokeTokenTest.php b/tests/LockUserRevokeTokenTest.php index 88572509c..821469b5c 100644 --- a/tests/LockUserRevokeTokenTest.php +++ b/tests/LockUserRevokeTokenTest.php @@ -261,6 +261,37 @@ public function testAdministrativeLockRevokesUserTokens(): void $this->assertEquals(OAuth2Protocol::OAuth2Protocol_Error_InvalidGrant, json_decode($response->getContent())->error); } + /** + * Unchecking "Active" on the edit user page (PUT /admin/api/v1/users/{id}) is an administrative lock too: + * the access tokens issued before it introspect as invalid_token. + */ + public function testDeactivatingFromTheEditUserPageRevokesUserTokens(): void + { + [$access_token] = $this->issueTokens(); + + $this->freshRequestContext(); + $this->put(sprintf('/admin/api/v1/users/%s', $this->user->getId()), ['active' => 0]) + ->assertResponseStatus(201); + + $this->runRevokeJob(); + + $response = $this->introspect($access_token); + $this->assertResponseStatus(400); + $this->assertEquals(OAuth2Protocol::OAuth2Protocol_Error_InvalidToken, json_decode($response->getContent())->error); + } + + /** + * Saving the edit user page with the user still active does not touch the tokens. + */ + public function testUpdatingAnActiveUserDoesNotScheduleTokensRevocation(): void + { + $this->put(sprintf('/admin/api/v1/users/%s', $this->user->getId()), ['active' => 1, 'first_name' => 'Sebastian']) + ->assertResponseStatus(201); + app()->terminate(); + + Queue::assertNotPushed(RevokeUserGrantsOnUserLocked::class); + } + /** * The lock caused by failed login attempts must not sign the user out of every application. */ From 370aa7b16fa0ae21411f37fbddebb32f9a7d0f37 Mon Sep 17 00:00:00 2001 From: romanetar Date: Wed, 2 Dec 2026 17:27:45 +0100 Subject: [PATCH 08/11] refactor(admin): revoke all the tokens of a user through the service and RevokeUserGrants UserApiController::revokeAllTokens looked up the user, revoked the tokens and wrote the audit entry itself, and unlike every other revocation it did not emit the audit.security.tokens_revoked OpenTelemetry audit log. The controller now calls IUserService::revokeAllGrantsOnAdminRequest, which runs the new RevokeUserGrantsOnAdminRequest job in the request (Bus::dispatchNow): the endpoint still answers once the tokens are revoked, and the user action and the OTEL audit log are written by RevokeUserGrants like the other revocations. --- .../Controllers/Api/UserApiController.php | 21 +-------- app/Jobs/RevokeUserGrantsOnAdminRequest.php | 43 +++++++++++++++++++ app/Services/OpenId/UserService.php | 18 ++++++++ app/libs/OpenId/Services/IUserService.php | 8 ++++ tests/LockUserRevokeTokenTest.php | 9 ++++ 5 files changed, 79 insertions(+), 20 deletions(-) create mode 100644 app/Jobs/RevokeUserGrantsOnAdminRequest.php diff --git a/app/Http/Controllers/Api/UserApiController.php b/app/Http/Controllers/Api/UserApiController.php index 4810c6560..3d067f5e9 100644 --- a/app/Http/Controllers/Api/UserApiController.php +++ b/app/Http/Controllers/Api/UserApiController.php @@ -15,7 +15,6 @@ use App\Http\Controllers\APICRUDController; use App\Http\Controllers\Traits\RequestProcessor; use App\Http\Controllers\UserValidationRulesFactory; -use App\Jobs\AddUserAction; use App\ModelSerializers\SerializerRegistry; use Auth\Repositories\IUserRepository; use Auth\User; @@ -28,7 +27,6 @@ use models\exceptions\ValidationException; use OAuth2\Services\ITokenService; use OpenId\Services\IUserService; -use Utils\IPHelper; use Utils\Services\ILogService; /** @@ -207,24 +205,7 @@ public function revokeToken($id, $value){ public function revokeAllTokens($id) { return $this->processRequest(function () use ($id) { - $user = $this->repository->getById(intval($id)); - if (!$user instanceof User) - throw new EntityNotFoundException(); - - $this->token_service->revokeUsersToken($user->getId()); - - $current_user = Auth::user(); - AddUserAction::dispatch - ( - $user->getId(), - IPHelper::getUserIp(), - sprintf - ( - "All tokens revoked by user %s (%s)", - $current_user instanceof User ? $current_user->getEmail() : 'N/A', - $current_user instanceof User ? $current_user->getId() : 'N/A' - ) - ); + $this->service->revokeAllGrantsOnAdminRequest(intval($id)); return $this->deleted(); }); } diff --git a/app/Jobs/RevokeUserGrantsOnAdminRequest.php b/app/Jobs/RevokeUserGrantsOnAdminRequest.php new file mode 100644 index 000000000..55c6fb140 --- /dev/null +++ b/app/Jobs/RevokeUserGrantsOnAdminRequest.php @@ -0,0 +1,43 @@ +getEmail() : 'N/A', + !is_null($admin) ? $admin->getId() : 'N/A' + ) + ); + } +} diff --git a/app/Services/OpenId/UserService.php b/app/Services/OpenId/UserService.php index e06d5429a..f89f4f760 100644 --- a/app/Services/OpenId/UserService.php +++ b/app/Services/OpenId/UserService.php @@ -15,6 +15,7 @@ use App\Events\UserEmailUpdated; use App\Events\UserPasswordResetSuccessful; use App\Jobs\AddUserAction; +use App\Jobs\RevokeUserGrantsOnAdminRequest; use App\Jobs\RevokeUserGrantsOnSessionRevocation; use App\Jobs\RevokeUserGrantsOnUserLocked; use App\Jobs\PublishUserDeleted; @@ -32,6 +33,7 @@ use Doctrine\Common\Collections\ArrayCollection; use Illuminate\Http\UploadedFile; use Illuminate\Support\Facades\Auth; +use Illuminate\Support\Facades\Bus; use Illuminate\Support\Facades\Config; use Illuminate\Support\Facades\Event; use Illuminate\Support\Facades\Log; @@ -518,6 +520,22 @@ public function revokeAllGrantsOnSessionRevocation(int $user_id): void RevokeUserGrantsOnSessionRevocation::dispatch($user)->afterResponse(); } + /** + * @param int $user_id + * @throws EntityNotFoundException + */ + public function revokeAllGrantsOnAdminRequest(int $user_id): void + { + $user = $this->repository->getById($user_id); + if (!$user instanceof User) + throw new EntityNotFoundException("User not found."); + + $admin = Auth::user(); + // run in this process, not through a queue: the admin gets the answer once the grants are revoked + // (and audited), and a failure reaches the caller + Bus::dispatchNow(new RevokeUserGrantsOnAdminRequest($user, $admin instanceof User ? $admin : null)); + } + public function notifyMonitoredSecurityGroupActivity ( string $action, diff --git a/app/libs/OpenId/Services/IUserService.php b/app/libs/OpenId/Services/IUserService.php index e9d276f35..5215ad27f 100644 --- a/app/libs/OpenId/Services/IUserService.php +++ b/app/libs/OpenId/Services/IUserService.php @@ -114,4 +114,12 @@ public function notifyMonitoredSecurityGroupActivity( */ public function revokeAllGrantsOnSessionRevocation(int $user_id): void; + /** + * Revokes every OAuth2 grant (access and refresh tokens) the user holds, on behalf of the current + * server admin. Runs synchronously: the grants are revoked when it returns. + * @param int $user_id + * @throws EntityNotFoundException + */ + public function revokeAllGrantsOnAdminRequest(int $user_id): void; + } \ No newline at end of file diff --git a/tests/LockUserRevokeTokenTest.php b/tests/LockUserRevokeTokenTest.php index 821469b5c..608495097 100644 --- a/tests/LockUserRevokeTokenTest.php +++ b/tests/LockUserRevokeTokenTest.php @@ -12,6 +12,8 @@ * limitations under the License. **/ +use App\Jobs\AddUserAction; +use App\Jobs\RevokeUserGrantsOnAdminRequest; use App\Jobs\RevokeUserGrantsOnUserLocked; use Auth\User; use Illuminate\Support\Facades\Config; @@ -332,6 +334,13 @@ public function testServerAdminRevokesAllTokensOfAUser(): void $this->refresh($refresh_token); $this->assertResponseStatus(400); + + // revoked in the request, not queued, and audited like the other revocations (RevokeUserGrants) + Queue::assertNotPushed(RevokeUserGrantsOnAdminRequest::class); + Queue::assertPushed(AddUserAction::class, function (AddUserAction $job) { + $action = new \ReflectionProperty(AddUserAction::class, 'action'); + return str_contains($action->getValue($job), 'due to admin request by user'); + }); } public function testRevokeAllTokensOfUnknownUserReturns404(): void From eec64155dafb7e5be55cd88b5ef0af80490b483e Mon Sep 17 00:00:00 2001 From: romanetar Date: Wed, 2 Dec 2026 17:37:26 +0100 Subject: [PATCH 09/11] fix(admin): do not let a user change its own active, email_verified or groups through /users/me PUT /admin/api/v1/users/me used the admin update rules, which accept active, email_verified and groups, and passed the payload unfiltered to UserService::update. A user locked while it had a live session could send {"active":1} and reactivate itself, undoing the administrative lock; any user could also mark its own email as verified. UserApiController::updateMe now drops those fields, as OAuth2UserApiController::curateUpdatePayload already does for the OAuth2 "me" endpoint. Server admins still set them through PUT /admin/api/v1/users/{id}. --- .../Controllers/Api/UserApiController.php | 13 ++++++- tests/LockUserRevokeTokenTest.php | 35 +++++++++++++++++++ 2 files changed, 47 insertions(+), 1 deletion(-) diff --git a/app/Http/Controllers/Api/UserApiController.php b/app/Http/Controllers/Api/UserApiController.php index 3d067f5e9..465216dcb 100644 --- a/app/Http/Controllers/Api/UserApiController.php +++ b/app/Http/Controllers/Api/UserApiController.php @@ -35,6 +35,11 @@ */ final class UserApiController extends APICRUDController { + /** + * fields only a server admin can set (PUT /admin/api/v1/users/{id}), never the user through /users/me + */ + const AdminOnlyFields = ['active', 'email_verified', 'groups']; + use RequestProcessor; @@ -257,7 +262,13 @@ public function updateMe() if (!Auth::check()) return $this->error403(); - return $this->update(Auth::user()->getId()); + $payload = $this->getUpdatePayload(); + // the admin fields of an account are not editable by its owner: otherwise a locked user with a live + // session could reactivate itself (as OAuth2UserApiController does for the OAuth2 "me" endpoint) + foreach (self::AdminOnlyFields as $field) + unset($payload[$field]); + + return $this->_update(Auth::user()->getId(), $payload); } public function revokeAllMyTokens() diff --git a/tests/LockUserRevokeTokenTest.php b/tests/LockUserRevokeTokenTest.php index 608495097..79da481d6 100644 --- a/tests/LockUserRevokeTokenTest.php +++ b/tests/LockUserRevokeTokenTest.php @@ -313,6 +313,41 @@ public function testAdministrativeLockSchedulesTokensRevocation(): void Queue::assertPushed(RevokeUserGrantsOnUserLocked::class); } + // ------------------------------------------------------------------------- + // The owner of an account cannot change its admin fields + // ------------------------------------------------------------------------- + + /** + * A locked user with a session opened before the lock cannot reactivate itself through /users/me. + */ + public function testLockedUserCannotReactivateItselfThroughMe(): void + { + app(IUserService::class)->lockUser($this->user->getId(), false); + + $this->be($this->user, 'web'); + $this->put('/admin/api/v1/users/me', ['active' => 1]); + + EntityManager::refresh($this->user); + $this->assertFalse($this->user->isActive()); + } + + /** + * /users/me updates the profile but ignores active and email_verified. + */ + public function testUserCannotChangeItsAdminFieldsThroughMe(): void + { + $this->assertTrue($this->user->isActive()); + $this->assertTrue($this->user->isEmailVerified()); + + $this->put('/admin/api/v1/users/me', ['active' => 0, 'email_verified' => 0, 'first_name' => 'Renamed']) + ->assertResponseStatus(201); + + EntityManager::refresh($this->user); + $this->assertEquals('Renamed', $this->user->getFirstName()); + $this->assertTrue($this->user->isActive()); + $this->assertTrue($this->user->isEmailVerified()); + } + // ------------------------------------------------------------------------- // Revoke every token of a user // ------------------------------------------------------------------------- From 42124ff929577d5d7de738b60a236398074f2427 Mon Sep 17 00:00:00 2001 From: romanetar Date: Wed, 2 Dec 2026 17:41:12 +0100 Subject: [PATCH 10/11] fix(auth): end the web session of a locked user on every authenticated route CustomAuthProvider::retrieveById rehydrates the session without looking at the user's status, and the auth middleware only checked guest(), so a session opened before the lock kept working on every route behind auth: profile, consent and the admin API. A locked server admin could even unlock itself through PUT /admin/api/v1/users/{id}/locked. Authenticate::handle now ends the session of an inactive user through IAuthService::logout() and handles the request as a guest's (redirect to the login, which refuses locked users). The check in InteractiveGrantType::mustAuthenticateUser stays: /oauth2/auth is not behind the auth middleware. --- app/Http/Middleware/Authenticate.php | 29 +++++++++++++++++ tests/LockUserRevokeTokenTest.php | 47 ++++++++++++++++++++++++++++ 2 files changed, 76 insertions(+) diff --git a/app/Http/Middleware/Authenticate.php b/app/Http/Middleware/Authenticate.php index c48c91352..357b81984 100644 --- a/app/Http/Middleware/Authenticate.php +++ b/app/Http/Middleware/Authenticate.php @@ -18,12 +18,26 @@ use Illuminate\Support\Facades\Session; use Illuminate\Support\Facades\Redirect; use Illuminate\Support\Facades\URL; +use Utils\Services\IAuthService; /** * Class Authenticate * @package App\Http\Middleware */ class Authenticate { + /** + * @var IAuthService + */ + private $auth_service; + + /** + * @param IAuthService $auth_service + */ + public function __construct(IAuthService $auth_service) + { + $this->auth_service = $auth_service; + } + /** * Handle an incoming request. * @@ -34,6 +48,21 @@ class Authenticate */ public function handle($request, Closure $next, $guard = null) { + // a session opened before the user was locked (deactivated) is ended: the user is sent to the + // login as a guest, and the login refuses locked users + $current_user = Auth::guard($guard)->user(); + if (!is_null($current_user) && !$current_user->isActive()) { + Log::warning + ( + sprintf + ( + "Authenticate::handle current user %s is not active, ending the session", + $current_user->getId() + ) + ); + $this->auth_service->logout(); + } + if (Auth::guard($guard)->guest()) { Session::put('backurl', URL::full()); Session::save(); diff --git a/tests/LockUserRevokeTokenTest.php b/tests/LockUserRevokeTokenTest.php index 79da481d6..0d2ac6304 100644 --- a/tests/LockUserRevokeTokenTest.php +++ b/tests/LockUserRevokeTokenTest.php @@ -313,6 +313,53 @@ public function testAdministrativeLockSchedulesTokensRevocation(): void Queue::assertPushed(RevokeUserGrantsOnUserLocked::class); } + // ------------------------------------------------------------------------- + // The web session of a locked user ends + // ------------------------------------------------------------------------- + + /** + * A server admin locked while it had a live session cannot use the admin API anymore + * (for instance, to unlock itself): the session is ended and the request goes to the login. + */ + public function testLockedServerAdminSessionCannotUseTheAdminApi(): void + { + $this->assertTrue($this->user->isOpenIdServerAdmin()); + app(IUserService::class)->lockUser($this->user->getId(), false); + + $this->be($this->user, 'web'); + $this->put(sprintf('/admin/api/v1/users/%s/locked', $this->user->getId())); + + $this->assertRedirectedToAction('UserController@getLogin'); + $this->assertFalse($this->app['auth']->guard('web')->check()); + EntityManager::refresh($this->user); + $this->assertFalse($this->user->isActive()); + } + + /** + * The pages that require a session (profile, consent, admin) send a locked user to the login. + */ + public function testLockedUserSessionIsSentToTheLogin(): void + { + app(IUserService::class)->lockUser($this->user->getId(), false); + + $this->be($this->user, 'web'); + $this->get('/accounts/user/profile'); + + $this->assertRedirectedToAction('UserController@getLogin'); + $this->assertFalse($this->app['auth']->guard('web')->check()); + } + + /** + * An active user keeps its session. + */ + public function testActiveUserSessionReachesTheProfile(): void + { + $this->get('/accounts/user/profile'); + + $this->assertResponseOk(); + $this->assertTrue($this->app['auth']->guard('web')->check()); + } + // ------------------------------------------------------------------------- // The owner of an account cannot change its admin fields // ------------------------------------------------------------------------- From d292042845e521e663b5161bf46baa473d57fcd8 Mon Sep 17 00:00:00 2001 From: romanetar Date: Wed, 2 Dec 2026 17:52:24 +0100 Subject: [PATCH 11/11] fix(auth): do not count the session of a locked user as logged in on the protocol endpoints /accounts/openid2 is not behind the auth middleware, and OpenIdAuthenticationRequestHandler only asked isUserLogged() (Auth::check), so the session of a locked user still got positive OpenID 2.0 assertions for the realms it trusts forever, in both checkid_immediate and checkid_setup. AuthService::isUserLogged() now ends the session of an inactive user and answers false. Its three callers (OpenID 2.0 setup and immediate modes, and InteractiveGrantType::mustAuthenticateUser) then send the request to the login, which refuses locked users, or answer setup_needed. The check that mustAuthenticateUser carried for OAuth2 is now this one. --- app/libs/Auth/AuthService.php | 23 +++++- .../GrantTypes/InteractiveGrantType.php | 19 +---- tests/LockUserRevokeTokenTest.php | 76 +++++++++++++++++++ 3 files changed, 100 insertions(+), 18 deletions(-) diff --git a/app/libs/Auth/AuthService.php b/app/libs/Auth/AuthService.php index 02a653a57..ca0ed4635 100644 --- a/app/libs/Auth/AuthService.php +++ b/app/libs/Auth/AuthService.php @@ -125,11 +125,32 @@ public function __construct } /** + * Whether a user is logged in, for the protocol endpoints that act on the session without the auth + * middleware (OAuth2 authorization, OpenID 2.0): a session opened before the user was locked + * (deactivated) is ended, so the request goes to the login (which refuses locked users) or gets a + * negative answer. * @return bool */ public function isUserLogged() { - return Auth::check(); + if (!Auth::check()) + return false; + + $current_user = $this->getCurrentUser(); + if (is_null($current_user) || !$current_user->isActive()) { + Log::warning + ( + sprintf + ( + "AuthService::isUserLogged current user %s is not active, ending the session", + is_null($current_user) ? 'N/A' : $current_user->getId() + ) + ); + $this->logout(false); + return false; + } + + return true; } /** diff --git a/app/libs/OAuth2/GrantTypes/InteractiveGrantType.php b/app/libs/OAuth2/GrantTypes/InteractiveGrantType.php index b0c520e00..58fa12713 100644 --- a/app/libs/OAuth2/GrantTypes/InteractiveGrantType.php +++ b/app/libs/OAuth2/GrantTypes/InteractiveGrantType.php @@ -824,26 +824,11 @@ protected function mustAuthenticateUser(OAuth2AuthorizationRequest $request, Cli return true; } + // a session opened before the user was locked (deactivated) does not count: isUserLogged() ends it, + // so the request goes through the login, which refuses locked users if (!$this->auth_service->isUserLogged()) return true; - // a session opened before the user was locked (deactivated) must not keep issuing - // authorization codes: end it and send the request through the login, which refuses locked users - $current_user = $this->auth_service->getCurrentUser(); - if (is_null($current_user) || !$current_user->isActive()) - { - Log::warning - ( - sprintf - ( - "InteractiveGrant::mustAuthenticateUser: current user %s is not active", - is_null($current_user) ? 'N/A' : $current_user->getId() - ) - ); - $this->auth_service->logout(false); - return true; - } - return false; } } \ No newline at end of file diff --git a/tests/LockUserRevokeTokenTest.php b/tests/LockUserRevokeTokenTest.php index 0d2ac6304..ecd40a011 100644 --- a/tests/LockUserRevokeTokenTest.php +++ b/tests/LockUserRevokeTokenTest.php @@ -20,6 +20,8 @@ use Illuminate\Support\Facades\Queue; use Illuminate\Support\Facades\Session; use LaravelDoctrine\ORM\Facades\EntityManager; +use Models\OpenId\OpenIdTrustedSite; +use OpenId\OpenIdProtocol; use OAuth2\OAuth2Protocol; use OAuth2\Services\ITokenService; use OpenId\Services\IUserService; @@ -360,6 +362,80 @@ public function testActiveUserSessionReachesTheProfile(): void $this->assertTrue($this->app['auth']->guard('web')->check()); } + /** + * Runs an OpenID 2.0 authentication request for a realm the user trusts forever. + * @param string $mode checkid_immediate or checkid_setup + */ + private function openId2Authentication(string $mode) + { + $site = new OpenIdTrustedSite; + $site->setRealm('https://www.test.com/'); + $site->setPolicy(IAuthService::AuthorizationResponse_AllowForever); + $site->setData(json_encode([])); + $this->user->addTrustedSite($site); + EntityManager::flush(); + + return $this->action("POST", "OpenId\OpenIdProviderController@endpoint", [ + OpenIdProtocol::param(OpenIdProtocol::OpenIDProtocol_NS) => OpenIdProtocol::OpenID2MessageType, + OpenIdProtocol::param(OpenIdProtocol::OpenIDProtocol_Mode) => $mode, + OpenIdProtocol::param(OpenIdProtocol::OpenIDProtocol_Realm) => 'https://www.test.com/', + OpenIdProtocol::param(OpenIdProtocol::OpenIDProtocol_ReturnTo) => 'https://www.test.com/oauth2', + OpenIdProtocol::param(OpenIdProtocol::OpenIDProtocol_Identity) => 'http://specs.openid.net/auth/2.0/identifier_select', + OpenIdProtocol::param(OpenIdProtocol::OpenIDProtocol_ClaimedId) => 'http://specs.openid.net/auth/2.0/identifier_select', + ]); + } + + /** + * @return string|null the openid.mode of the response sent back to the relying party + */ + private function openId2ResponseMode($response): ?string + { + $query = []; + parse_str(parse_url($response->getTargetUrl(), PHP_URL_QUERY) ?? '', $query); + // parse_str turns the dots of openid.mode into underscores + return $query['openid_mode'] ?? null; + } + + /** + * OpenID 2.0 (checkid_immediate) answers setup_needed to the session of a locked user, even for a + * realm the user trusts forever, and ends the session. + */ + public function testOpenId2ImmediateModeDoesNotAssertALockedUser(): void + { + app(IUserService::class)->lockUser($this->user->getId(), false); + $this->be($this->user, 'web'); + + $response = $this->openId2Authentication(OpenIdProtocol::ImmediateMode); + + $this->assertEquals(OpenIdProtocol::SetupNeededMode, $this->openId2ResponseMode($response)); + $this->assertFalse($this->app['auth']->guard('web')->check()); + } + + /** + * OpenID 2.0 (checkid_setup) sends the session of a locked user to the login instead of asserting it. + */ + public function testOpenId2SetupModeDoesNotAssertALockedUser(): void + { + app(IUserService::class)->lockUser($this->user->getId(), false); + $this->be($this->user, 'web'); + + $response = $this->openId2Authentication(OpenIdProtocol::SetupMode); + + $this->assertNotEquals(OpenIdProtocol::IdMode, $this->openId2ResponseMode($response)); + $this->assertStringNotContainsString('www.test.com', $response->getTargetUrl()); + $this->assertFalse($this->app['auth']->guard('web')->check()); + } + + /** + * Control: the same request asserts an active user. + */ + public function testOpenId2ImmediateModeAssertsAnActiveUser(): void + { + $response = $this->openId2Authentication(OpenIdProtocol::ImmediateMode); + + $this->assertEquals(OpenIdProtocol::IdMode, $this->openId2ResponseMode($response)); + } + // ------------------------------------------------------------------------- // The owner of an account cannot change its admin fields // -------------------------------------------------------------------------