From 5f8bd0dd8e006ebc6a8a73f6591de7df8c4ed4b2 Mon Sep 17 00:00:00 2001 From: Peter Ringelmann Date: Tue, 1 Dec 2026 13:21:13 +0100 Subject: [PATCH 01/15] fix(auth): iterate all tokens of a user in bulk operations Assisted-by: ClaudeCode:claude-opus-5-5 Signed-off-by: Peter Ringelmann --- apps/oauth2/lib/Service/ClientService.php | 2 +- .../tests/Service/ClientServiceTest.php | 6 +-- core/Command/User/AuthTokens/ListCommand.php | 2 +- .../UserDeletedTokenCleanupListener.php | 2 +- .../Authentication/Token/IProvider.php | 9 ++++ lib/private/Authentication/Token/Manager.php | 7 ++- .../Token/PublicKeyTokenMapper.php | 26 +++++++++ .../Token/PublicKeyTokenProvider.php | 5 ++ .../Authentication/Token/RemoteWipe.php | 2 +- .../UserDeletedTokenCleanupListenerTest.php | 6 +-- .../lib/Authentication/Token/ManagerTest.php | 16 +++++- .../Token/PublicKeyTokenMapperTest.php | 53 +++++++++++++++++++ .../Token/PublicKeyTokenProviderTest.php | 10 ++++ .../Authentication/Token/RemoteWipeTest.php | 4 +- 14 files changed, 135 insertions(+), 15 deletions(-) diff --git a/apps/oauth2/lib/Service/ClientService.php b/apps/oauth2/lib/Service/ClientService.php index e47afa35bc8db..e0316853d250e 100644 --- a/apps/oauth2/lib/Service/ClientService.php +++ b/apps/oauth2/lib/Service/ClientService.php @@ -72,7 +72,7 @@ public function deleteClient(int $id): void { $this->userManager->callForSeenUsers(function (IUser $user) use ($client): void { // Skip tokens that are marked for remote wipe so revoking the // OAuth2 client does not silently cancel a pending wipe. - $tokens = $this->tokenProvider->getTokenByUser($user->getUID()); + $tokens = $this->tokenProvider->getAllTokensByUser($user->getUID()); foreach ($tokens as $token) { if ($token->getName() !== $client->getName()) { continue; diff --git a/apps/oauth2/tests/Service/ClientServiceTest.php b/apps/oauth2/tests/Service/ClientServiceTest.php index bc9986e0b21f9..e762de6b7dd7a 100644 --- a/apps/oauth2/tests/Service/ClientServiceTest.php +++ b/apps/oauth2/tests/Service/ClientServiceTest.php @@ -114,11 +114,11 @@ public function testDeleteClient(): void { $user1->updateLastLoginTimestamp(); $tokenProviderMock = $this->getMockBuilder(IAuthTokenProvider::class)->getMock(); - // One getTokenByUser call per user; we return no matching tokens here + // One getAllTokensByUser call per user; we return no matching tokens here // so invalidateTokenById is never invoked. $tokenProviderMock ->expects($this->exactly($count + 1)) - ->method('getTokenByUser') + ->method('getAllTokensByUser') ->willReturn([]); $tokenProviderMock ->expects($this->never()) @@ -186,7 +186,7 @@ public function testDeleteClientPreservesWipePendingToken(): void { $otherToken->method('getName')->willReturn('Some Other Client'); $this->authTokenProvider - ->method('getTokenByUser') + ->method('getAllTokensByUser') ->willReturnCallback(function (string $uid) use ($wipeToken, $regularToken, $otherToken) { return $uid === 'test_wipe_preserve' ? [$wipeToken, $regularToken, $otherToken] diff --git a/core/Command/User/AuthTokens/ListCommand.php b/core/Command/User/AuthTokens/ListCommand.php index 7b26090735fc5..e6451594aa1f8 100644 --- a/core/Command/User/AuthTokens/ListCommand.php +++ b/core/Command/User/AuthTokens/ListCommand.php @@ -45,7 +45,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int return 1; } - $tokens = $this->tokenProvider->getTokenByUser($user->getUID()); + $tokens = iterator_to_array($this->tokenProvider->getAllTokensByUser($user->getUID()), false); $tokens = array_map(function (IToken $token) use ($input): mixed { $sensitive = [ diff --git a/lib/private/Authentication/Listeners/UserDeletedTokenCleanupListener.php b/lib/private/Authentication/Listeners/UserDeletedTokenCleanupListener.php index bc67ef0feec03..650ef35a2e877 100644 --- a/lib/private/Authentication/Listeners/UserDeletedTokenCleanupListener.php +++ b/lib/private/Authentication/Listeners/UserDeletedTokenCleanupListener.php @@ -38,7 +38,7 @@ public function handle(Event $event): void { */ try { $uid = $event->getUser()->getUID(); - $tokens = $this->manager->getTokenByUser($uid); + $tokens = $this->manager->getAllTokensByUser($uid); foreach ($tokens as $token) { $this->manager->invalidateTokenById($uid, $token->getId()); } diff --git a/lib/private/Authentication/Token/IProvider.php b/lib/private/Authentication/Token/IProvider.php index e30ac5e7b24cf..a53db2942f6b6 100644 --- a/lib/private/Authentication/Token/IProvider.php +++ b/lib/private/Authentication/Token/IProvider.php @@ -123,6 +123,15 @@ public function updateTokenActivity(OCPIToken $token); */ public function getTokenByUser(string $uid): array; + /** + * Get every token of a user, without the limit of getTokenByUser() + * + * Tokens may be deleted or updated while iterating. + * + * @return iterable + */ + public function getAllTokensByUser(string $uid): iterable; + /** * Get the (unencrypted) password of the given token * diff --git a/lib/private/Authentication/Token/Manager.php b/lib/private/Authentication/Token/Manager.php index 016ed5092c4d5..18e775f11b117 100644 --- a/lib/private/Authentication/Token/Manager.php +++ b/lib/private/Authentication/Token/Manager.php @@ -94,6 +94,11 @@ public function getTokenByUser(string $uid): array { return $this->publicKeyTokenProvider->getTokenByUser($uid); } + #[\Override] + public function getAllTokensByUser(string $uid): iterable { + return $this->publicKeyTokenProvider->getAllTokensByUser($uid); + } + /** * Get a token by token * @@ -235,7 +240,7 @@ public function updatePasswords(string $uid, string $password) { #[\Override] public function invalidateTokensOfUser(string $uid, ?string $clientName) { - $tokens = $this->getTokenByUser($uid); + $tokens = $this->getAllTokensByUser($uid); foreach ($tokens as $token) { if ($clientName === null || ($token->getName() === $clientName)) { $this->invalidateTokenById($uid, $token->getId()); diff --git a/lib/private/Authentication/Token/PublicKeyTokenMapper.php b/lib/private/Authentication/Token/PublicKeyTokenMapper.php index 5d703686d4dd3..7fa1489a63579 100644 --- a/lib/private/Authentication/Token/PublicKeyTokenMapper.php +++ b/lib/private/Authentication/Token/PublicKeyTokenMapper.php @@ -150,6 +150,32 @@ public function getTokenByUser(string $uid): array { return $entities; } + /** + * Tokens may be deleted or updated while iterating. + * + * @return \Generator + */ + public function getAllTokensByUser(string $uid): \Generator { + $chunkSize = 1000; + $lastId = 0; + do { + $qb = $this->db->getQueryBuilder(); + $qb->select('*') + ->from($this->tableName) + ->where($qb->expr()->eq('uid', $qb->createNamedParameter($uid))) + ->andWhere($qb->expr()->eq('version', $qb->createNamedParameter(PublicKeyToken::VERSION, IQueryBuilder::PARAM_INT))) + ->andWhere($qb->expr()->gt('id', $qb->createNamedParameter($lastId, IQueryBuilder::PARAM_INT))) + ->orderBy('id') + ->setMaxResults($chunkSize); + $tokens = $this->findEntities($qb); + + foreach ($tokens as $token) { + $lastId = $token->getId(); + yield $token; + } + } while (count($tokens) === $chunkSize); + } + public function getTokenByUserAndId(string $uid, int $id): ?string { /* @var $qb IQueryBuilder */ $qb = $this->db->getQueryBuilder(); diff --git a/lib/private/Authentication/Token/PublicKeyTokenProvider.php b/lib/private/Authentication/Token/PublicKeyTokenProvider.php index 43fbcd50c4ead..87a5ed7e9b724 100644 --- a/lib/private/Authentication/Token/PublicKeyTokenProvider.php +++ b/lib/private/Authentication/Token/PublicKeyTokenProvider.php @@ -343,6 +343,11 @@ public function getTokenByUser(string $uid): array { return $this->mapper->getTokenByUser($uid); } + #[\Override] + public function getAllTokensByUser(string $uid): iterable { + return $this->mapper->getAllTokensByUser($uid); + } + #[\Override] public function getPassword(OCPIToken $savedToken, string $tokenId): string { if (!($savedToken instanceof PublicKeyToken)) { diff --git a/lib/private/Authentication/Token/RemoteWipe.php b/lib/private/Authentication/Token/RemoteWipe.php index 11d0c323fd826..1f4cbb47009f5 100644 --- a/lib/private/Authentication/Token/RemoteWipe.php +++ b/lib/private/Authentication/Token/RemoteWipe.php @@ -52,7 +52,7 @@ public function markTokenForWipe(IToken $token): bool { * @return bool true if any tokens have been marked for remote wipe */ public function markAllTokensForWipe(IUser $user): bool { - $tokens = $this->tokenProvider->getTokenByUser($user->getUID()); + $tokens = iterator_to_array($this->tokenProvider->getAllTokensByUser($user->getUID()), false); /** @var IWipeableToken[] $wipeable */ $wipeable = array_filter($tokens, function (IToken $token) { diff --git a/tests/lib/Authentication/Listeners/UserDeletedTokenCleanupListenerTest.php b/tests/lib/Authentication/Listeners/UserDeletedTokenCleanupListenerTest.php index 0a84a7faafadf..e6cfdbb0bb270 100644 --- a/tests/lib/Authentication/Listeners/UserDeletedTokenCleanupListenerTest.php +++ b/tests/lib/Authentication/Listeners/UserDeletedTokenCleanupListenerTest.php @@ -45,7 +45,7 @@ protected function setUp(): void { public function testHandleUnrelated(): void { $event = new Event(); - $this->manager->expects($this->never())->method('getTokenByUser'); + $this->manager->expects($this->never())->method('getAllTokensByUser'); $this->logger->expects($this->never())->method('error'); $this->listener->handle($event); @@ -57,7 +57,7 @@ public function testHandleWithErrors(): void { $event = new UserDeletedEvent($user); $exception = new Exception('nope'); $this->manager->expects($this->once()) - ->method('getTokenByUser') + ->method('getAllTokensByUser') ->with('user123') ->willThrowException($exception); $this->logger->expects($this->once()) @@ -77,7 +77,7 @@ public function testHandle(): void { $token3 = $this->createMock(IToken::class); $token3->method('getId')->willReturn(3); $this->manager->expects($this->once()) - ->method('getTokenByUser') + ->method('getAllTokensByUser') ->with('user123') ->willReturn([ $token1, diff --git a/tests/lib/Authentication/Token/ManagerTest.php b/tests/lib/Authentication/Token/ManagerTest.php index 03984e8a89a6a..54cbafb73d225 100644 --- a/tests/lib/Authentication/Token/ManagerTest.php +++ b/tests/lib/Authentication/Token/ManagerTest.php @@ -218,6 +218,18 @@ public function testGetTokenByUser(): void { $this->assertEquals([$t1, $t2], $result); } + public function testGetAllTokensByUser(): void { + $t1 = new PublicKeyToken(); + $t2 = new PublicKeyToken(); + + $this->publicKeyTokenProvider + ->method('getAllTokensByUser') + ->with('uid') + ->willReturn([$t1, $t2]); + + $this->assertEquals([$t1, $t2], $this->manager->getAllTokensByUser('uid')); + } + public function testRenewSessionTokenPublicKey(): void { $this->publicKeyTokenProvider->expects($this->once()) ->method('renewSessionToken') @@ -326,7 +338,7 @@ public function testInvalidateTokensOfUserNoClientName(): void { $this->publicKeyTokenProvider ->expects($this->once()) - ->method('getTokenByUser') + ->method('getAllTokensByUser') ->with('theUser') ->willReturn([$t1, $t2]); @@ -357,7 +369,7 @@ public function testInvalidateTokensOfUserClientNameGiven(): void { $this->publicKeyTokenProvider ->expects($this->once()) - ->method('getTokenByUser') + ->method('getAllTokensByUser') ->with('theUser') ->willReturn([$t1, $t2, $t3]); $this->publicKeyTokenProvider diff --git a/tests/lib/Authentication/Token/PublicKeyTokenMapperTest.php b/tests/lib/Authentication/Token/PublicKeyTokenMapperTest.php index 8c38cd62f13ce..894eb03f8c66f 100644 --- a/tests/lib/Authentication/Token/PublicKeyTokenMapperTest.php +++ b/tests/lib/Authentication/Token/PublicKeyTokenMapperTest.php @@ -263,6 +263,59 @@ public function testGetTokenByUserNotFound(): void { $this->assertCount(0, $this->mapper->getTokenByUser('user1000')); } + private function insertTokens(string $uid, int $count, int $version = 2): void { + $this->dbConnection->beginTransaction(); + for ($i = 0; $i < $count; $i++) { + $qb = $this->dbConnection->getQueryBuilder(); + $qb->insert('authtoken')->values([ + 'uid' => $qb->createNamedParameter($uid), + 'login_name' => $qb->createNamedParameter($uid), + 'name' => $qb->createNamedParameter('Token ' . $i), + 'token' => $qb->createNamedParameter($uid . '-v' . $version . '-token-' . $i), + 'type' => $qb->createNamedParameter(IToken::PERMANENT_TOKEN), + 'last_activity' => $qb->createNamedParameter($this->time, IQueryBuilder::PARAM_INT), + 'last_check' => $qb->createNamedParameter($this->time, IQueryBuilder::PARAM_INT), + 'public_key' => $qb->createNamedParameter('public key'), + 'private_key' => $qb->createNamedParameter('private key'), + 'version' => $qb->createNamedParameter($version), + ])->executeStatement(); + } + $this->dbConnection->commit(); + } + + public function testGetAllTokensByUser(): void { + $this->insertTokens('user4', 1000); + + $this->assertCount(1000, iterator_to_array($this->mapper->getAllTokensByUser('user4'), false)); + $this->assertCount(2, iterator_to_array($this->mapper->getAllTokensByUser('user1'), false)); + $this->assertCount(0, iterator_to_array($this->mapper->getAllTokensByUser('user1000'), false)); + } + + public function testGetAllTokensByUserSkipsOtherVersions(): void { + $this->insertTokens('user4', 1, 1); + $this->insertTokens('user4', 2); + + $tokens = iterator_to_array($this->mapper->getAllTokensByUser('user4'), false); + + $this->assertCount(2, $tokens); + foreach ($tokens as $token) { + $this->assertSame(PublicKeyToken::VERSION, $token->getVersion()); + } + } + + public function testGetAllTokensByUserWhileDeleting(): void { + $this->insertTokens('user4', 1001); + + $seen = 0; + foreach ($this->mapper->getAllTokensByUser('user4') as $token) { + $this->mapper->delete($token); + $seen++; + } + + $this->assertSame(1001, $seen); + $this->assertCount(0, $this->mapper->getTokenByUser('user4')); + } + public function testGetById(): void { /** @var IUser|\PHPUnit\Framework\MockObject\MockObject $user */ $user = $this->createMock(IUser::class); diff --git a/tests/lib/Authentication/Token/PublicKeyTokenProviderTest.php b/tests/lib/Authentication/Token/PublicKeyTokenProviderTest.php index 5d93d02b6bb4a..7f064648c0a4d 100644 --- a/tests/lib/Authentication/Token/PublicKeyTokenProviderTest.php +++ b/tests/lib/Authentication/Token/PublicKeyTokenProviderTest.php @@ -212,6 +212,16 @@ public function testGetTokenByUser(): void { $this->assertEquals(['token'], $this->tokenProvider->getTokenByUser('uid')); } + public function testGetAllTokensByUser(): void { + $tokens = (fn () => yield new PublicKeyToken())(); + $this->mapper->expects($this->once()) + ->method('getAllTokensByUser') + ->with('uid') + ->willReturn($tokens); + + $this->assertSame($tokens, $this->tokenProvider->getAllTokensByUser('uid')); + } + public function testGetPassword(): void { $token = 'tokentokentokentokentoken'; $uid = 'user'; diff --git a/tests/lib/Authentication/Token/RemoteWipeTest.php b/tests/lib/Authentication/Token/RemoteWipeTest.php index c5031e2527255..08a18a2abb2c4 100644 --- a/tests/lib/Authentication/Token/RemoteWipeTest.php +++ b/tests/lib/Authentication/Token/RemoteWipeTest.php @@ -76,7 +76,7 @@ public function testMarkAllTokensForWipeNoWipeableToken(): void { $token1 = $this->createMock(IToken::class); $token2 = $this->createMock(IToken::class); $this->tokenProvider->expects($this->once()) - ->method('getTokenByUser') + ->method('getAllTokensByUser') ->with('user123') ->willReturn([$token1, $token2]); @@ -92,7 +92,7 @@ public function testMarkAllTokensForWipe(): void { $token1 = $this->createMock(IToken::class); $token2 = $this->createMock(IWipeableToken::class); $this->tokenProvider->expects($this->once()) - ->method('getTokenByUser') + ->method('getAllTokensByUser') ->with('user123') ->willReturn([$token1, $token2]); $token2->expects($this->once()) From d548861ef1b60bca4f68f033307d7cfd7da0fafb Mon Sep 17 00:00:00 2001 From: Peter Ringelmann Date: Tue, 1 Dec 2026 13:01:24 +0100 Subject: [PATCH 02/15] fix(auth): only reset login attempts after a password login Token logins don't prove the account password, so they must not clear failed login attempts. Resetting attempts for one user also no longer hides the remaining attempts of other users. Assisted-by: ClaudeCode:claude-opus-5-5 Signed-off-by: Peter Ringelmann --- .../lib/Controller/OauthApiController.php | 4 -- .../Controller/OauthApiControllerTest.php | 41 -------------- lib/base.php | 15 +++-- lib/private/Security/Bruteforce/Throttler.php | 7 +-- .../lib/Security/Bruteforce/ThrottlerTest.php | 55 +++++++++++++++++++ 5 files changed, 65 insertions(+), 57 deletions(-) create mode 100644 tests/lib/Security/Bruteforce/ThrottlerTest.php diff --git a/apps/oauth2/lib/Controller/OauthApiController.php b/apps/oauth2/lib/Controller/OauthApiController.php index 2b8d66403fa69..5c1feab9a69e7 100644 --- a/apps/oauth2/lib/Controller/OauthApiController.php +++ b/apps/oauth2/lib/Controller/OauthApiController.php @@ -31,7 +31,6 @@ use OCP\IRequest; use OCP\IURLGenerator; use OCP\IUserManager; -use OCP\Security\Bruteforce\IThrottler; use OCP\Security\ICrypto; use OCP\Security\ISecureRandom; use Psr\Container\ContainerExceptionInterface; @@ -53,7 +52,6 @@ public function __construct( private readonly ISecureRandom $secureRandom, private readonly ITimeFactory $time, private readonly LoggerInterface $logger, - private readonly IThrottler $throttler, private readonly ITimeFactory $timeFactory, private readonly IDBConnection $db, private readonly GlobalScaleConfig $globalScaleConfig, @@ -238,8 +236,6 @@ public function getToken( throw $e; } - $this->throttler->resetDelay($this->request->getRemoteAddress(), 'login', ['user' => $appToken->getUID()]); - $data = [ 'access_token' => $newToken, 'token_type' => 'Bearer', diff --git a/apps/oauth2/tests/Controller/OauthApiControllerTest.php b/apps/oauth2/tests/Controller/OauthApiControllerTest.php index 3e2c4266ed838..5be359ffde467 100644 --- a/apps/oauth2/tests/Controller/OauthApiControllerTest.php +++ b/apps/oauth2/tests/Controller/OauthApiControllerTest.php @@ -28,7 +28,6 @@ use OCP\IURLGenerator; use OCP\IUser; use OCP\IUserManager; -use OCP\Security\Bruteforce\IThrottler; use OCP\Security\ICrypto; use OCP\Security\ISecureRandom; use PHPUnit\Framework\MockObject\MockObject; @@ -50,7 +49,6 @@ class OauthApiControllerTest extends TestCase { private TokenProvider&MockObject $tokenProvider; private ISecureRandom&MockObject $secureRandom; private ITimeFactory&MockObject $time; - private IThrottler&MockObject $throttler; private LoggerInterface&MockObject $logger; private ITimeFactory&MockObject $timeFactory; private IDBConnection&MockObject $db; @@ -70,7 +68,6 @@ protected function setUp(): void { $this->tokenProvider = $this->createMock(TokenProvider::class); $this->secureRandom = $this->createMock(ISecureRandom::class); $this->time = $this->createMock(ITimeFactory::class); - $this->throttler = $this->createMock(IThrottler::class); $this->logger = $this->createMock(LoggerInterface::class); $this->timeFactory = $this->createMock(ITimeFactory::class); $this->db = $this->createMock(IDBConnection::class); @@ -89,7 +86,6 @@ protected function setUp(): void { $this->secureRandom, $this->time, $this->logger, - $this->throttler, $this->timeFactory, $this->db, $this->globalScaleConfig, @@ -424,17 +420,6 @@ public function testRefreshTokenValidAppToken(): void { 'user_id' => 'userId', ]); - $this->request->method('getRemoteAddress') - ->willReturn('1.2.3.4'); - - $this->throttler->expects($this->once()) - ->method('resetDelay') - ->with( - '1.2.3.4', - 'login', - ['user' => 'userId'] - ); - $this->assertEquals($expected, $this->oauthApiController->getToken('refresh_token', null, 'validrefresh', 'clientId', 'clientSecret')); } @@ -537,17 +522,6 @@ public function testRefreshTokenValidAppTokenBasicAuth(): void { $this->request->server['PHP_AUTH_USER'] = 'clientId'; $this->request->server['PHP_AUTH_PW'] = 'clientSecret'; - $this->request->method('getRemoteAddress') - ->willReturn('1.2.3.4'); - - $this->throttler->expects($this->once()) - ->method('resetDelay') - ->with( - '1.2.3.4', - 'login', - ['user' => 'userId'] - ); - $this->assertEquals($expected, $this->oauthApiController->getToken('refresh_token', null, 'validrefresh', null, null)); } @@ -647,17 +621,6 @@ public function testRefreshTokenExpiredAppToken(): void { 'user_id' => 'userId', ]); - $this->request->method('getRemoteAddress') - ->willReturn('1.2.3.4'); - - $this->throttler->expects($this->once()) - ->method('resetDelay') - ->with( - '1.2.3.4', - 'login', - ['user' => 'userId'] - ); - $this->assertEquals($expected, $this->oauthApiController->getToken('refresh_token', null, 'validrefresh', 'clientId', 'clientSecret')); } @@ -740,9 +703,6 @@ public function testRefreshTokenRedeemedConcurrently(): void { false, )->willReturn(0); - $this->throttler->expects($this->never()) - ->method('resetDelay'); - $this->assertEquals($expected, $this->oauthApiController->getToken('refresh_token', null, 'validrefresh', 'clientId', 'clientSecret')); } @@ -796,7 +756,6 @@ private function arrangeSuccessfulTokenExchange(): PublicKeyToken { }); $this->time->method('getTime')->willReturn(1000); $this->accessTokenMapper->method('rotateToken')->willReturn(1); - $this->request->method('getRemoteAddress')->willReturn('1.2.3.4'); return $appToken; } diff --git a/lib/base.php b/lib/base.php index b103214a784a4..c1f3b8150ee87 100644 --- a/lib/base.php +++ b/lib/base.php @@ -970,13 +970,16 @@ public static function registerCleanupHooks(\OC\SystemConfig $systemConfig): voi if ($systemConfig->getValue('installed', false) && !\OCP\Util::needUpgrade()) { // NOTE: This will be replaced to use OCP $userSession = Server::get(\OC\User\Session::class); - $userSession->listen('\OC\User', 'postLogin', function () use ($userSession) { + $userSession->listen('\OC\User', 'postLogin', function ($loggedInUser, $loginName, $password, bool $isTokenLogin) use ($userSession) { if (!defined('PHPUNIT_RUN') && $userSession->isLoggedIn()) { - // reset brute force delay for this IP address and username - $uid = $userSession->getUser()->getUID(); - $request = Server::get(IRequest::class); - $throttler = Server::get(IThrottler::class); - $throttler->resetDelay($request->getRemoteAddress(), 'login', ['user' => $uid]); + // A token login does not prove knowledge of the password + if (!$isTokenLogin) { + // reset brute force delay for this IP address and username + $uid = $userSession->getUser()->getUID(); + $request = Server::get(IRequest::class); + $throttler = Server::get(IThrottler::class); + $throttler->resetDelay($request->getRemoteAddress(), 'login', ['user' => $uid]); + } } try { diff --git a/lib/private/Security/Bruteforce/Throttler.php b/lib/private/Security/Bruteforce/Throttler.php index f6cc666f64b45..b92238b4aaabc 100644 --- a/lib/private/Security/Bruteforce/Throttler.php +++ b/lib/private/Security/Bruteforce/Throttler.php @@ -33,9 +33,6 @@ * @package OC\Security\Bruteforce */ class Throttler implements IThrottler { - /** @var bool[] */ - private array $hasAttemptsDeleted = []; - public function __construct( private ITimeFactory $timeFactory, private LoggerInterface $logger, @@ -117,7 +114,7 @@ public function getAttempts(string $ip, string $action = '', float $maxAgeHours $maxAgeHours = 48; } - if ($ip === '' || isset($this->hasAttemptsDeleted[$action])) { + if ($ip === '') { return 0; } @@ -185,8 +182,6 @@ public function resetDelay(string $ip, string $action, array $metadata): void { $action, $metadata, ); - - $this->hasAttemptsDeleted[$action] = true; } /** diff --git a/tests/lib/Security/Bruteforce/ThrottlerTest.php b/tests/lib/Security/Bruteforce/ThrottlerTest.php new file mode 100644 index 0000000000000..7c06ea4b613a3 --- /dev/null +++ b/tests/lib/Security/Bruteforce/ThrottlerTest.php @@ -0,0 +1,55 @@ +createMock(IConfig::class); + $config->method('getSystemValueBool') + ->with('auth.bruteforce.protection.enabled', true) + ->willReturn(true); + $allowList = $this->createMock(BruteforceAllowList::class); + $allowList->method('isBypassListed') + ->with('10.10.10.10') + ->willReturn(false); + + // Only the attempts matching the metadata are removed, + // so the remaining ones of the action still have to be counted + $backend = $this->createMock(IBackend::class); + $backend->expects($this->once()) + ->method('resetAttempts') + ->with('10.10.10.10/32', 'login', ['user' => 'bob']); + $backend->expects($this->once()) + ->method('getAttempts') + ->with('10.10.10.10/32', $this->anything(), 'login') + ->willReturn(11); + + $throttler = new Throttler( + $this->createMock(ITimeFactory::class), + $this->createMock(LoggerInterface::class), + $config, + $backend, + $allowList, + $this->createMock(IEventDispatcher::class), + ); + + $throttler->resetDelay('10.10.10.10', 'login', ['user' => 'bob']); + $this->assertSame(11, $throttler->getAttempts('10.10.10.10', 'login')); + } +} From d6d4607b8c5ef24f71ed6bf3792e21de6b60ac4f Mon Sep 17 00:00:00 2001 From: Ferdinand Thiessen Date: Mon, 30 Nov 2026 18:02:28 +0100 Subject: [PATCH 03/15] test(auth): cover remember-me renewal after a password change Changing the password on one device deletes the other browser sessions of the account. Their remember-me cookies must not log back in, also when a local memory cache still holds a copy of the deleted session token. The scenario needs memcache.local. The default integration suite runs without one, so the scenario configures APCu when the extension is loaded, otherwise Redis on localhost (the service every integration job provides), and removes the setting afterwards. Assisted-by: ClaudeCode:claude-opus-5-5 Signed-off-by: Ferdinand Thiessen --- build/integration/features/auth.feature | 13 ++++ build/integration/features/bootstrap/Auth.php | 71 +++++++++++++++++++ 2 files changed, 84 insertions(+) diff --git a/build/integration/features/auth.feature b/build/integration/features/auth.feature index 4601221c808a9..f8990fe0598ab 100644 --- a/build/integration/features/auth.feature +++ b/build/integration/features/auth.feature @@ -98,6 +98,19 @@ Feature: auth And requesting "/index.php/apps/files" with "GET" using browser session Then the HTTP status code should be "200" + Scenario: a remembered login ends when the password is changed on another device + Given a local memory cache is configured + And a new remembered browser session is started + And requesting "/ocs/v2.php/cloud/user" with "GET" using browser session + And the HTTP status code should be "200" + And the browser session is stored as "phone" + And a new browser session is started + When the password is changed from "123456" to "654321-new" using browser session + And the browser session "phone" is restored + And the session cookie expires + And requesting "/ocs/v2.php/cloud/user" with "GET" using browser session + Then the HTTP status code should be "401" + # AUTH TOKENS Scenario: Creating an auth token with regular auth token should not work When requesting "/index.php/apps/files" with "GET" using restricted basic token auth diff --git a/build/integration/features/bootstrap/Auth.php b/build/integration/features/bootstrap/Auth.php index 982c14a2ccbde..b52dad328e8b6 100644 --- a/build/integration/features/bootstrap/Auth.php +++ b/build/integration/features/bootstrap/Auth.php @@ -5,6 +5,11 @@ * SPDX-FileCopyrightText: 2016 ownCloud, Inc. * SPDX-License-Identifier: AGPL-3.0-or-later */ + +use Behat\Hook\AfterScenario; +use Behat\Hook\BeforeScenario; +use Behat\Step\Given; +use Behat\Step\When; use GuzzleHttp\Client; use GuzzleHttp\Cookie\CookieJar; use GuzzleHttp\Exception\ClientException; @@ -21,12 +26,25 @@ trait Auth { private $client; /** @var string */ private $responseXml; + /** @var array */ + private array $storedBrowserSessions = []; + /** @var list> system config keys to delete after the scenario */ + private array $systemConfigToDelete = []; /** @BeforeScenario */ public function setUpScenario() { $this->client = new Client(); $this->responseXml = ''; $this->cookieJar = new CookieJar(); + $this->storedBrowserSessions = []; + } + + #[AfterScenario] + public function deleteSystemConfigOfScenario(): void { + foreach (array_reverse($this->systemConfigToDelete) as $keys) { + $this->runOcc(['config:system:delete', ...$keys]); + } + $this->systemConfigToDelete = []; } /** @@ -255,4 +273,57 @@ public function theCookieJarIsReset() { public function whenTheSessionCookieExpires() { $this->cookieJar->clearSessionCookies(); } + + #[Given('the browser session is stored as :name')] + public function theBrowserSessionIsStoredAs(string $name): void { + $this->storedBrowserSessions[$name] = [$this->cookieJar, $this->requestToken]; + $this->cookieJar = new CookieJar(); + $this->requestToken = null; + } + + #[Given('the browser session :name is restored')] + public function theBrowserSessionIsRestored(string $name): void { + [$this->cookieJar, $this->requestToken] = $this->storedBrowserSessions[$name]; + } + + /** + * Configures memcache.local unless one is configured already: APCu when + * the PHP extension is loaded, otherwise Redis on localhost + */ + #[Given('a local memory cache is configured')] + public function aLocalMemoryCacheIsConfigured(): void { + $this->runOcc(['config:system:get', 'memcache.local']); + if (trim($this->lastStdOut) !== '') { + return; + } + + if (extension_loaded('apcu')) { + $this->runOcc(['config:system:set', 'memcache.local', '--value', '\\OC\\Memcache\\APCu']); + } else { + Assert::assertTrue(extension_loaded('redis'), 'Neither APCu nor Redis is available'); + $this->runOcc(['config:system:set', 'redis', 'host', '--value', 'localhost']); + $this->runOcc(['config:system:set', 'redis', 'port', '--value', '6379', '--type', 'integer']); + $this->systemConfigToDelete[] = ['redis']; + $this->runOcc(['config:system:set', 'memcache.local', '--value', '\\OC\\Memcache\\Redis']); + } + Assert::assertSame(0, $this->lastCode, $this->lastStdErr); + $this->systemConfigToDelete[] = ['memcache.local']; + } + + #[When('the password is changed from :oldPassword to :newPassword using browser session')] + public function thePasswordIsChangedUsingBrowserSession(string $oldPassword, string $newPassword): void { + $fullUrl = substr($this->baseUrl, 0, -5) . '/index.php/settings/personal/changepassword'; + $this->response = $this->client->post($fullUrl, [ + 'form_params' => [ + 'oldpassword' => $oldPassword, + 'newpassword' => $newPassword, + ], + 'headers' => [ + 'requesttoken' => $this->requestToken, + ], + 'cookies' => $this->cookieJar, + ]); + $body = json_decode($this->response->getBody()->getContents(), true); + Assert::assertSame('success', $body['status'] ?? null); + } } From f04accd524cd3064562baca7f654d752feb38579 Mon Sep 17 00:00:00 2001 From: Ferdinand Thiessen Date: Mon, 30 Nov 2026 18:06:13 +0100 Subject: [PATCH 04/15] test(auth): cover browser sessions after a password change by an admin A password change by an admin leaves the existing browser sessions to their periodic credential check, which must end every session opened with the previous password. This must also hold when the owner has logged in with the new password before the check runs. The check runs at most every five minutes. The testing app gets an occ command that makes it due for all tokens of a user, so the scenarios need no wait. Assisted-by: ClaudeCode:claude-opus-5-5 Signed-off-by: Ferdinand Thiessen --- apps/testing/appinfo/info.xml | 5 ++ .../composer/composer/autoload_classmap.php | 1 + .../composer/composer/autoload_static.php | 1 + .../lib/Command/ResetTokenLastCheck.php | 47 +++++++++++++++++++ build/integration/features/auth.feature | 32 +++++++++++++ build/integration/features/bootstrap/Auth.php | 29 ++++++++---- 6 files changed, 107 insertions(+), 8 deletions(-) create mode 100644 apps/testing/lib/Command/ResetTokenLastCheck.php diff --git a/apps/testing/appinfo/info.xml b/apps/testing/appinfo/info.xml index fe611157a0848..ab6d4b9ed9049 100644 --- a/apps/testing/appinfo/info.xml +++ b/apps/testing/appinfo/info.xml @@ -16,6 +16,11 @@ + + + OCA\Testing\Command\ResetTokenLastCheck + + monitoring https://github.com/nextcloud/server/issues diff --git a/apps/testing/composer/composer/autoload_classmap.php b/apps/testing/composer/composer/autoload_classmap.php index 72aead2903a76..7f4eeccb3a16c 100644 --- a/apps/testing/composer/composer/autoload_classmap.php +++ b/apps/testing/composer/composer/autoload_classmap.php @@ -9,6 +9,7 @@ 'Composer\\InstalledVersions' => $vendorDir . '/composer/InstalledVersions.php', 'OCA\\Testing\\AlternativeHomeUserBackend' => $baseDir . '/../lib/AlternativeHomeUserBackend.php', 'OCA\\Testing\\AppInfo\\Application' => $baseDir . '/../lib/AppInfo/Application.php', + 'OCA\\Testing\\Command\\ResetTokenLastCheck' => $baseDir . '/../lib/Command/ResetTokenLastCheck.php', 'OCA\\Testing\\Command\\SetUnencryptedSize' => $baseDir . '/../lib/Command/SetUnencryptedSize.php', 'OCA\\Testing\\Controller\\ConfigController' => $baseDir . '/../lib/Controller/ConfigController.php', 'OCA\\Testing\\Controller\\LockingController' => $baseDir . '/../lib/Controller/LockingController.php', diff --git a/apps/testing/composer/composer/autoload_static.php b/apps/testing/composer/composer/autoload_static.php index f1981b29fc713..07127c16803ed 100644 --- a/apps/testing/composer/composer/autoload_static.php +++ b/apps/testing/composer/composer/autoload_static.php @@ -24,6 +24,7 @@ class ComposerStaticInitTesting 'Composer\\InstalledVersions' => __DIR__ . '/..' . '/composer/InstalledVersions.php', 'OCA\\Testing\\AlternativeHomeUserBackend' => __DIR__ . '/..' . '/../lib/AlternativeHomeUserBackend.php', 'OCA\\Testing\\AppInfo\\Application' => __DIR__ . '/..' . '/../lib/AppInfo/Application.php', + 'OCA\\Testing\\Command\\ResetTokenLastCheck' => __DIR__ . '/..' . '/../lib/Command/ResetTokenLastCheck.php', 'OCA\\Testing\\Command\\SetUnencryptedSize' => __DIR__ . '/..' . '/../lib/Command/SetUnencryptedSize.php', 'OCA\\Testing\\Controller\\ConfigController' => __DIR__ . '/..' . '/../lib/Controller/ConfigController.php', 'OCA\\Testing\\Controller\\LockingController' => __DIR__ . '/..' . '/../lib/Controller/LockingController.php', diff --git a/apps/testing/lib/Command/ResetTokenLastCheck.php b/apps/testing/lib/Command/ResetTokenLastCheck.php new file mode 100644 index 0000000000000..191311c8f20dc --- /dev/null +++ b/apps/testing/lib/Command/ResetTokenLastCheck.php @@ -0,0 +1,47 @@ +setName('testing:reset-token-last-check') + ->setDescription('Make the credential check of all auth tokens of a user due') + ->addArgument('user', InputArgument::REQUIRED, 'Owner of the tokens'); + } + + #[\Override] + protected function execute(InputInterface $input, OutputInterface $output): int { + $qb = $this->db->getQueryBuilder(); + $qb->update('authtoken') + ->set('last_check', $qb->createNamedParameter(0)) + ->where($qb->expr()->eq('uid', $qb->createNamedParameter($input->getArgument('user')))) + ->executeStatement(); + + return self::SUCCESS; + } +} diff --git a/build/integration/features/auth.feature b/build/integration/features/auth.feature index f8990fe0598ab..686cb0dcda32e 100644 --- a/build/integration/features/auth.feature +++ b/build/integration/features/auth.feature @@ -111,6 +111,38 @@ Feature: auth And requesting "/ocs/v2.php/cloud/user" with "GET" using browser session Then the HTTP status code should be "401" + # PASSWORD CHANGE BY AN ADMIN + Scenario: a browser session ends at its credential check after the admin changed the password + Given a new browser session is started + And the browser session is stored as "old" + And As an "admin" + And sending "PUT" to "/cloud/users/user0" with + | key | password | + | value | 654321-new | + And the HTTP status code should be "200" + And the credential check of the tokens of "user0" is due + When the browser session "old" is restored + And requesting "/ocs/v2.php/cloud/user" with "GET" using browser session + Then the HTTP status code should be "401" + + Scenario: a browser session opened with the previous password ends although the owner logged in with the new one + Given a new browser session is started + And requesting "/ocs/v2.php/cloud/user" with "GET" using browser session + And the HTTP status code should be "200" + And the browser session is stored as "old" + And As an "admin" + And sending "PUT" to "/cloud/users/user0" with + | key | password | + | value | 654321-new | + And the HTTP status code should be "200" + And a new browser session is started with password "654321-new" + And requesting "/ocs/v2.php/cloud/user" with "GET" using browser session + And the HTTP status code should be "200" + And the credential check of the tokens of "user0" is due + When the browser session "old" is restored + And requesting "/ocs/v2.php/cloud/user" with "GET" using browser session + Then the HTTP status code should be "401" + # AUTH TOKENS Scenario: Creating an auth token with regular auth token should not work When requesting "/index.php/apps/files" with "GET" using restricted basic token auth diff --git a/build/integration/features/bootstrap/Auth.php b/build/integration/features/bootstrap/Auth.php index b52dad328e8b6..1996a504bbec3 100644 --- a/build/integration/features/bootstrap/Auth.php +++ b/build/integration/features/bootstrap/Auth.php @@ -219,11 +219,10 @@ public function requestingWithBrowserSession($url, $method) { } /** - * @Given a new browser session is started - * * @param bool $remember */ - public function aNewBrowserSessionIsStarted($remember = false) { + #[Given('a new browser session is started')] + public function aNewBrowserSessionIsStarted($remember = false, string $password = '123456') { $baseUrl = substr($this->baseUrl, 0, -5); $loginUrl = $baseUrl . '/login'; // Request a new session and extract CSRF token @@ -239,7 +238,7 @@ public function aNewBrowserSessionIsStarted($remember = false) { $loginUrl, [ 'form_params' => [ 'user' => 'user0', - 'password' => '123456', + 'password' => $password, 'rememberme' => $remember ? '1' : '0', 'requesttoken' => $this->requestToken, ], @@ -252,14 +251,16 @@ public function aNewBrowserSessionIsStarted($remember = false) { $this->extracRequestTokenFromResponse($response); } - /** - * @Given a new remembered browser session is started - */ + #[Given('a new browser session is started with password :password')] + public function aNewBrowserSessionIsStartedWithPassword(string $password): void { + $this->aNewBrowserSessionIsStarted(false, $password); + } + + #[Given('a new remembered browser session is started')] public function aNewRememberedBrowserSessionIsStarted() { $this->aNewBrowserSessionIsStarted(true); } - /** * @Given the cookie jar is reset */ @@ -326,4 +327,16 @@ public function thePasswordIsChangedUsingBrowserSession(string $oldPassword, str $body = json_decode($this->response->getBody()->getContents(), true); Assert::assertSame('success', $body['status'] ?? null); } + + /** + * The next request with any auth token of the user checks the stored password again + */ + #[Given('the credential check of the tokens of :user is due')] + public function theCredentialCheckOfTheTokensOfIsDue(string $user): void { + $this->runOcc(['testing:reset-token-last-check', $user]); + Assert::assertSame(0, $this->lastCode, $this->lastStdErr); + if (extension_loaded('apcu')) { + $this->client->get(substr($this->baseUrl, 0, -5) . '/apps/testing/clean_apcu_cache.php'); + } + } } From cf69b7f59b609fa58b9c206b883b33bfd3011fa6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?C=C3=B4me=20Chilliet?= Date: Wed, 10 Jun 2026 10:52:24 +0200 Subject: [PATCH 05/15] chore(tests): Avoid deprecation in PublicKeyTokenProvider MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Also cleaned up the test a bit. Signed-off-by: Côme Chilliet Signed-off-by: Benjamin Gaussorgues --- .../Token/PublicKeyTokenProvider.php | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) diff --git a/lib/private/Authentication/Token/PublicKeyTokenProvider.php b/lib/private/Authentication/Token/PublicKeyTokenProvider.php index 87a5ed7e9b724..a24dc9ac41696 100644 --- a/lib/private/Authentication/Token/PublicKeyTokenProvider.php +++ b/lib/private/Authentication/Token/PublicKeyTokenProvider.php @@ -557,16 +557,18 @@ public function updatePasswords(string $uid, string $password) { $hashNeedsUpdate = []; foreach ($tokens as $t) { - if (!isset($hashNeedsUpdate[$t->getPasswordHash()])) { - if ($t->getPasswordHash() === null) { - $hashNeedsUpdate[$t->getPasswordHash() ?: ''] = true; - } elseif (!$this->hasher->verify(sha1($password) . $password, $t->getPasswordHash())) { - $hashNeedsUpdate[$t->getPasswordHash() ?: ''] = true; + $passwordHash = $t->getPasswordHash(); + if ($passwordHash === null) { + $hashNeedsUpdate[''] = true; + $needsUpdating = true; + } elseif (!isset($hashNeedsUpdate[$passwordHash])) { + if (!$this->hasher->verify(sha1($password) . $password, $passwordHash)) { + $hashNeedsUpdate[$passwordHash] = true; } else { - $hashNeedsUpdate[$t->getPasswordHash() ?: ''] = false; + $hashNeedsUpdate[$passwordHash] = false; } + $needsUpdating = $hashNeedsUpdate[$passwordHash] ?? true; } - $needsUpdating = $hashNeedsUpdate[$t->getPasswordHash() ?: ''] ?? true; if ($needsUpdating) { if ($newPasswordHash === null) { From 1a0514ed6d1874e117d20698a16d4701e584192a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?C=C3=B4me=20Chilliet?= Date: Tue, 3 Nov 2026 16:40:27 +0100 Subject: [PATCH 06/15] fix: Invalidate session token with different password on update MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Côme Chilliet --- .../Authentication/Token/IProvider.php | 6 +- .../Token/PublicKeyTokenProvider.php | 12 ++++ .../Token/PublicKeyTokenProviderTest.php | 56 +++++++++++++++++++ 3 files changed, 70 insertions(+), 4 deletions(-) diff --git a/lib/private/Authentication/Token/IProvider.php b/lib/private/Authentication/Token/IProvider.php index a53db2942f6b6..39cca8f3432a8 100644 --- a/lib/private/Authentication/Token/IProvider.php +++ b/lib/private/Authentication/Token/IProvider.php @@ -173,10 +173,8 @@ public function rotate(OCPIToken $token, string $oldTokenId, string $newTokenId) public function markPasswordInvalid(OCPIToken $token, string $tokenId); /** - * Update all the passwords of $uid if required - * - * @param string $uid - * @param string $password + * Update all the app passwords of $uid if required + * Session tokens that were created with a different password are invalidated */ public function updatePasswords(string $uid, string $password); } diff --git a/lib/private/Authentication/Token/PublicKeyTokenProvider.php b/lib/private/Authentication/Token/PublicKeyTokenProvider.php index a24dc9ac41696..15517847fa8f5 100644 --- a/lib/private/Authentication/Token/PublicKeyTokenProvider.php +++ b/lib/private/Authentication/Token/PublicKeyTokenProvider.php @@ -568,6 +568,18 @@ public function updatePasswords(string $uid, string $password) { $hashNeedsUpdate[$passwordHash] = false; } $needsUpdating = $hashNeedsUpdate[$passwordHash] ?? true; + } else { + $needsUpdating = $hashNeedsUpdate[$passwordHash]; + } + + if ($needsUpdating && $passwordHash !== null && $t->getType() === OCPIToken::TEMPORARY_TOKEN) { + // Only app passwords follow a password change. A session that was + // opened with another password is deleted (like in setPassword), + // otherwise it would outlive the password change + $this->mapper->invalidate($t->getToken()); + $this->cacheInvalidHash($t->getToken()); + $this->eventDispatcher->dispatchTyped(new TokenInvalidatedEvent($t)); + continue; } if ($needsUpdating) { diff --git a/tests/lib/Authentication/Token/PublicKeyTokenProviderTest.php b/tests/lib/Authentication/Token/PublicKeyTokenProviderTest.php index 7f064648c0a4d..526011f72aac1 100644 --- a/tests/lib/Authentication/Token/PublicKeyTokenProviderTest.php +++ b/tests/lib/Authentication/Token/PublicKeyTokenProviderTest.php @@ -704,4 +704,60 @@ public function testUpdatePasswords(): void { $this->tokenProvider->updatePasswords($uid, 'bar2'); } + + public function testUpdatePasswordsInvalidatesSessionsWithOutdatedPassword(): void { + $uid = 'myUID'; + $this->config->method('getSystemValueBool') + ->willReturnMap([ + ['auth.storeCryptedPassword', true, true], + ]); + + $generateToken = fn (string $token, ?string $password, int $type): PublicKeyToken => $this->tokenProvider->generateToken( + $token . 'tokentokentokentoken', + $uid, + $uid, + $password, + $token, + $type, + ); + $currentSession1 = $generateToken('current1', 'bar2', IToken::TEMPORARY_TOKEN); + $outdatedAppPassword = $generateToken('app', 'bar', IToken::PERMANENT_TOKEN); + $outdatedSession1 = $generateToken('outdated1', 'bar', IToken::TEMPORARY_TOKEN); + $currentSession2 = $generateToken('current2', 'bar2', IToken::TEMPORARY_TOKEN); + $currentSession2->setPasswordHash($currentSession1->getPasswordHash()); + $outdatedSession2 = $generateToken('outdated2', 'bar', IToken::TEMPORARY_TOKEN); + $outdatedSession2->setPasswordHash($outdatedSession1->getPasswordHash()); + $passwordlessSession = $generateToken('passwordless', null, IToken::TEMPORARY_TOKEN); + + $this->mapper->expects($this->once()) + ->method('getTokenByUser') + ->with($uid) + ->willReturn([ + $currentSession1, + $outdatedAppPassword, + $outdatedSession1, + $currentSession2, + $outdatedSession2, + $passwordlessSession, + ]); + + $updated = []; + $this->mapper->method('update') + ->willReturnCallback(function (PublicKeyToken $t) use (&$updated) { + $updated[] = $t; + return $t; + }); + $invalidated = []; + $this->mapper->method('invalidate') + ->willReturnCallback(function (string $token) use (&$invalidated): void { + $invalidated[] = $token; + }); + + $this->tokenProvider->updatePasswords($uid, 'bar2'); + + $this->assertSame([$outdatedAppPassword, $passwordlessSession], $updated); + $this->assertSame([$outdatedSession1->getToken(), $outdatedSession2->getToken()], $invalidated); + $this->assertSame('bar2', $this->tokenProvider->getPassword($outdatedAppPassword, 'apptokentokentokentoken')); + $this->assertSame('bar', $this->tokenProvider->getPassword($outdatedSession1, 'outdated1tokentokentokentoken')); + } } From 6859965c9bba0df49c548f7b5a5cdec7143b9ccf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?C=C3=B4me=20Chilliet?= Date: Tue, 1 Dec 2026 11:17:58 +0100 Subject: [PATCH 07/15] fix: Do not read token from cache when renewing session token MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Côme Chilliet --- .../Authentication/Token/PublicKeyTokenProvider.php | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/lib/private/Authentication/Token/PublicKeyTokenProvider.php b/lib/private/Authentication/Token/PublicKeyTokenProvider.php index 15517847fa8f5..d3073b6967434 100644 --- a/lib/private/Authentication/Token/PublicKeyTokenProvider.php +++ b/lib/private/Authentication/Token/PublicKeyTokenProvider.php @@ -105,7 +105,7 @@ public function generateToken(string $token, } #[\Override] - public function getToken(string $tokenId): OCPIToken { + public function getToken(string $tokenId, bool $allowReadFromCache = true): OCPIToken { /** * Token length: 72 * @see \OC\Core\Controller\ClientFlowLoginController::generateAppPassword @@ -128,9 +128,11 @@ public function getToken(string $tokenId): OCPIToken { } $tokenHash = $this->hashToken($tokenId); - if ($token = $this->getTokenFromCache($tokenHash)) { - $this->checkToken($token); - return $token; + if ($allowReadFromCache) { + if ($token = $this->getTokenFromCache($tokenHash)) { + $this->checkToken($token); + return $token; + } } try { @@ -211,7 +213,7 @@ private function checkToken($token): void { #[\Override] public function renewSessionToken(string $oldSessionId, string $sessionId): OCPIToken { return $this->atomic(function () use ($oldSessionId, $sessionId) { - $token = $this->getToken($oldSessionId); + $token = $this->getToken($oldSessionId, allowReadFromCache:false); if (!($token instanceof PublicKeyToken)) { throw new InvalidTokenException('Invalid token type'); From 5bdccfc2ec48bf44cb075d95a00751c8c12da5aa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?C=C3=B4me=20Chilliet?= Date: Tue, 1 Dec 2026 15:21:50 +0100 Subject: [PATCH 08/15] fix: Fix behat test with older behat version MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Côme Chilliet --- build/integration/features/bootstrap/Auth.php | 37 ++++++++++++------- 1 file changed, 24 insertions(+), 13 deletions(-) diff --git a/build/integration/features/bootstrap/Auth.php b/build/integration/features/bootstrap/Auth.php index 1996a504bbec3..520cf78a8e0b7 100644 --- a/build/integration/features/bootstrap/Auth.php +++ b/build/integration/features/bootstrap/Auth.php @@ -6,14 +6,11 @@ * SPDX-License-Identifier: AGPL-3.0-or-later */ -use Behat\Hook\AfterScenario; -use Behat\Hook\BeforeScenario; -use Behat\Step\Given; -use Behat\Step\When; use GuzzleHttp\Client; use GuzzleHttp\Cookie\CookieJar; use GuzzleHttp\Exception\ClientException; use GuzzleHttp\Exception\ServerException; +use PHPUnit\Framework\Assert; require __DIR__ . '/autoload.php'; @@ -39,7 +36,7 @@ public function setUpScenario() { $this->storedBrowserSessions = []; } - #[AfterScenario] + /** @AfterScenario */ public function deleteSystemConfigOfScenario(): void { foreach (array_reverse($this->systemConfigToDelete) as $keys) { $this->runOcc(['config:system:delete', ...$keys]); @@ -219,9 +216,9 @@ public function requestingWithBrowserSession($url, $method) { } /** + * @Given a new browser session is started * @param bool $remember */ - #[Given('a new browser session is started')] public function aNewBrowserSessionIsStarted($remember = false, string $password = '123456') { $baseUrl = substr($this->baseUrl, 0, -5); $loginUrl = $baseUrl . '/login'; @@ -251,12 +248,16 @@ public function aNewBrowserSessionIsStarted($remember = false, string $password $this->extracRequestTokenFromResponse($response); } - #[Given('a new browser session is started with password :password')] + /** + * @Given a new browser session is started with password :password + */ public function aNewBrowserSessionIsStartedWithPassword(string $password): void { $this->aNewBrowserSessionIsStarted(false, $password); } - #[Given('a new remembered browser session is started')] + /** + * @Given a new remembered browser session is started + */ public function aNewRememberedBrowserSessionIsStarted() { $this->aNewBrowserSessionIsStarted(true); } @@ -275,14 +276,18 @@ public function whenTheSessionCookieExpires() { $this->cookieJar->clearSessionCookies(); } - #[Given('the browser session is stored as :name')] + /** + * @Given the browser session is stored as :name + */ public function theBrowserSessionIsStoredAs(string $name): void { $this->storedBrowserSessions[$name] = [$this->cookieJar, $this->requestToken]; $this->cookieJar = new CookieJar(); $this->requestToken = null; } - #[Given('the browser session :name is restored')] + /** + * @Given the browser session :name is restored + */ public function theBrowserSessionIsRestored(string $name): void { [$this->cookieJar, $this->requestToken] = $this->storedBrowserSessions[$name]; } @@ -291,7 +296,9 @@ public function theBrowserSessionIsRestored(string $name): void { * Configures memcache.local unless one is configured already: APCu when * the PHP extension is loaded, otherwise Redis on localhost */ - #[Given('a local memory cache is configured')] + /** + * @Given a local memory cache is configured + */ public function aLocalMemoryCacheIsConfigured(): void { $this->runOcc(['config:system:get', 'memcache.local']); if (trim($this->lastStdOut) !== '') { @@ -311,7 +318,9 @@ public function aLocalMemoryCacheIsConfigured(): void { $this->systemConfigToDelete[] = ['memcache.local']; } - #[When('the password is changed from :oldPassword to :newPassword using browser session')] + /** + * @When the password is changed from :oldPassword to :newPassword using browser session + */ public function thePasswordIsChangedUsingBrowserSession(string $oldPassword, string $newPassword): void { $fullUrl = substr($this->baseUrl, 0, -5) . '/index.php/settings/personal/changepassword'; $this->response = $this->client->post($fullUrl, [ @@ -331,7 +340,9 @@ public function thePasswordIsChangedUsingBrowserSession(string $oldPassword, str /** * The next request with any auth token of the user checks the stored password again */ - #[Given('the credential check of the tokens of :user is due')] + /** + * @Given the credential check of the tokens of :user is due + */ public function theCredentialCheckOfTheTokensOfIsDue(string $user): void { $this->runOcc(['testing:reset-token-last-check', $user]); Assert::assertSame(0, $this->lastCode, $this->lastStdErr); From dc1dd8596ab1f216fc0ed84ba15a7ef98d2cc13f Mon Sep 17 00:00:00 2001 From: Peter Ringelmann Date: Wed, 2 Dec 2026 12:07:23 +0100 Subject: [PATCH 09/15] fix(auth): WebAuthn switch, OAuth state and token name handling Assisted-by: ClaudeCode:claude-opus-5-5 Signed-off-by: Peter Ringelmann --- .../Controller/LoginRedirectorController.php | 5 +- .../LoginRedirectorControllerTest.php | 10 +-- .../lib/Controller/WebAuthnController.php | 8 +++ .../Controller/WebAuthnControllerTest.php | 68 +++++++++++++++++++ core/Controller/ClientFlowLoginController.php | 20 ++++-- core/Controller/WebAuthnController.php | 8 +++ .../Authentication/Token/PublicKeyToken.php | 8 ++- .../ClientFlowLoginControllerTest.php | 15 ++-- .../Controller/WebAuthnControllerTest.php | 67 ++++++++++++++++++ .../Token/PublicKeyTokenTest.php | 21 ++++++ 10 files changed, 210 insertions(+), 20 deletions(-) create mode 100644 apps/settings/tests/Controller/WebAuthnControllerTest.php create mode 100644 tests/Core/Controller/WebAuthnControllerTest.php diff --git a/apps/oauth2/lib/Controller/LoginRedirectorController.php b/apps/oauth2/lib/Controller/LoginRedirectorController.php index b7089e16981ec..6b2f8f504dd76 100644 --- a/apps/oauth2/lib/Controller/LoginRedirectorController.php +++ b/apps/oauth2/lib/Controller/LoginRedirectorController.php @@ -83,7 +83,10 @@ public function authorize( $providedRedirectUri = $redirect_uri; } - $this->session->set('oauth.state', $state); + $this->session->set('oauth.state', [ + 'clientIdentifier' => $client->getClientIdentifier(), + 'state' => $state, + ]); if (in_array($client->getName(), $this->appConfig->getValueArray('oauth2', 'skipAuthPickerApplications', []))) { /** @see ClientFlowLoginController::showAuthPickerPage **/ diff --git a/apps/oauth2/tests/Controller/LoginRedirectorControllerTest.php b/apps/oauth2/tests/Controller/LoginRedirectorControllerTest.php index 673c95ebcde9a..6e1d30892f549 100644 --- a/apps/oauth2/tests/Controller/LoginRedirectorControllerTest.php +++ b/apps/oauth2/tests/Controller/LoginRedirectorControllerTest.php @@ -72,7 +72,7 @@ public function testAuthorize(): void { $this->session ->expects($this->once()) ->method('set') - ->with('oauth.state', 'MyState'); + ->with('oauth.state', ['clientIdentifier' => 'MyClientIdentifier', 'state' => 'MyState']); $this->urlGenerator ->expects($this->once()) ->method('linkToRouteAbsolute') @@ -106,9 +106,9 @@ public function testAuthorizeSkipPicker(): void { $this->session ->expects(static::exactly(2)) ->method('set') - ->willReturnCallback(function (string $key, string $value): void { + ->willReturnCallback(function (string $key, string|array $value): void { switch ([$key, $value]) { - case ['oauth.state', 'MyState']: + case ['oauth.state', ['clientIdentifier' => 'MyClientIdentifier', 'state' => 'MyState']]: case [ClientFlowLoginController::STATE_NAME, 'MyStateToken']: /* Expected */ break; @@ -177,7 +177,7 @@ public function testAuthorizeWithLegacyOcClient(): void { $this->session ->expects($this->once()) ->method('set') - ->with('oauth.state', 'MyState'); + ->with('oauth.state', ['clientIdentifier' => 'MyClientIdentifier', 'state' => 'MyState']); $this->urlGenerator ->expects($this->once()) ->method('linkToRouteAbsolute') @@ -210,7 +210,7 @@ public function testAuthorizeNotForwardingUntrustedURIs(): void { $this->session ->expects($this->once()) ->method('set') - ->with('oauth.state', 'MyState'); + ->with('oauth.state', ['clientIdentifier' => 'MyClientIdentifier', 'state' => 'MyState']); $this->urlGenerator ->expects($this->once()) ->method('linkToRouteAbsolute') diff --git a/apps/settings/lib/Controller/WebAuthnController.php b/apps/settings/lib/Controller/WebAuthnController.php index 495b58e6a4bd3..4f5a8173855b8 100644 --- a/apps/settings/lib/Controller/WebAuthnController.php +++ b/apps/settings/lib/Controller/WebAuthnController.php @@ -48,6 +48,10 @@ public function __construct( public function startRegistration(): JSONResponse { $this->logger->debug('Starting WebAuthn registration'); + if (!$this->manager->isWebAuthnAvailable()) { + return new JSONResponse([], Http::STATUS_FORBIDDEN); + } + $credentialOptions = $this->manager->startRegistration($this->userSession->getUser(), $this->request->getServerHost()); // Set this in the session since we need it on finish @@ -65,6 +69,10 @@ public function startRegistration(): JSONResponse { public function finishRegistration(string $name, string $data): JSONResponse { $this->logger->debug('Finishing WebAuthn registration'); + if (!$this->manager->isWebAuthnAvailable()) { + return new JSONResponse([], Http::STATUS_FORBIDDEN); + } + if (!$this->session->exists(self::WEBAUTHN_REGISTRATION)) { $this->logger->debug('Trying to finish WebAuthn registration without session data'); return new JSONResponse([], Http::STATUS_BAD_REQUEST); diff --git a/apps/settings/tests/Controller/WebAuthnControllerTest.php b/apps/settings/tests/Controller/WebAuthnControllerTest.php new file mode 100644 index 0000000000000..27bda10b6cb56 --- /dev/null +++ b/apps/settings/tests/Controller/WebAuthnControllerTest.php @@ -0,0 +1,68 @@ +manager = $this->createMock(Manager::class); + $this->manager->method('isWebAuthnAvailable')->willReturn(false); + $this->userSession = $this->createMock(IUserSession::class); + $this->session = $this->createMock(ISession::class); + $this->controller = new WebAuthnController( + $this->createMock(IRequest::class), + $this->createMock(LoggerInterface::class), + $this->manager, + $this->userSession, + $this->session, + ); + } + + public function testStartRegistrationRefusedWhenDisabled(): void { + $this->manager->expects($this->never())->method('startRegistration'); + + $response = $this->controller->startRegistration(); + + $this->assertSame(Http::STATUS_FORBIDDEN, $response->getStatus()); + } + + public function testFinishRegistrationRefusedWhenDisabled(): void { + $this->session->method('exists')->willReturn(true); + $this->manager->expects($this->never())->method('finishRegister'); + + $response = $this->controller->finishRegistration('My key', '{}'); + + $this->assertSame(Http::STATUS_FORBIDDEN, $response->getStatus()); + } + + public function testDeleteRegistrationAllowedWhenDisabled(): void { + $this->userSession->method('getUser')->willReturn($this->createMock(IUser::class)); + $this->manager->expects($this->once())->method('deleteRegistration'); + + $this->controller->deleteRegistration(17); + } +} diff --git a/core/Controller/ClientFlowLoginController.php b/core/Controller/ClientFlowLoginController.php index 836bba6d8b734..708f3af2e4c12 100644 --- a/core/Controller/ClientFlowLoginController.php +++ b/core/Controller/ClientFlowLoginController.php @@ -68,6 +68,17 @@ public function __construct( parent::__construct($appName, $request); } + /** + * The state the OAuth client passed to the authorize endpoint, if that client is the one being granted + */ + private function getOAuthState(string $clientIdentifier): ?string { + $stored = $this->session->get('oauth.state'); + if (!is_array($stored) || ($stored['clientIdentifier'] ?? null) !== $clientIdentifier) { + return null; + } + return $stored['state']; + } + private function getClientName(): string { $userAgent = $this->request->getHeader('user-agent'); return $userAgent !== '' ? $userAgent : 'unknown'; @@ -130,6 +141,7 @@ public function showAuthPickerPage(string $clientIdentifier = '', string $user = ISecureRandom::CHAR_LOWER . ISecureRandom::CHAR_UPPER . ISecureRandom::CHAR_DIGITS ); $this->session->set(self::STATE_NAME, $stateToken); + $oauthState = $this->getOAuthState($clientIdentifier); $csp = new ContentSecurityPolicy(); if ($client) { @@ -145,7 +157,7 @@ public function showAuthPickerPage(string $clientIdentifier = '', string $user = 'instanceName' => $this->defaults->getName(), 'stateToken' => $stateToken, 'serverHost' => $this->getServerPath(), - 'oauthState' => $this->session->get('oauth.state'), + 'oauthState' => $oauthState, 'direct' => (bool)$direct, 'providedRedirectUri' => $providedRedirectUri, 'loginRedirectUrl' => $this->urlGenerator->linkToRoute( @@ -153,7 +165,7 @@ public function showAuthPickerPage(string $clientIdentifier = '', string $user = [ 'stateToken' => $stateToken, 'clientIdentifier' => $clientIdentifier, - 'oauthState' => $this->session->get('oauth.state'), + 'oauthState' => $oauthState, 'user' => $user, 'direct' => $direct, 'providedRedirectUri' => $providedRedirectUri, @@ -214,7 +226,7 @@ public function grantPage( 'instanceName' => $this->defaults->getName(), 'stateToken' => $stateToken, 'serverHost' => $this->getServerPath(), - 'oauthState' => $this->session->get('oauth.state'), + 'oauthState' => $this->getOAuthState($clientIdentifier), 'direct' => $direct, 'providedRedirectUri' => $providedRedirectUri, 'userDisplayName' => $user->getDisplayName(), @@ -321,7 +333,7 @@ public function generateAppPassword( $redirectUri .= sprintf( 'state=%s&code=%s', - urlencode($this->session->get('oauth.state')), + urlencode($this->getOAuthState($clientIdentifier) ?? ''), urlencode($code) ); $this->session->remove('oauth.state'); diff --git a/core/Controller/WebAuthnController.php b/core/Controller/WebAuthnController.php index 90f5d3ab73d1c..3a00d03b23362 100644 --- a/core/Controller/WebAuthnController.php +++ b/core/Controller/WebAuthnController.php @@ -49,6 +49,10 @@ public function __construct( public function startAuthentication(string $loginName): JSONResponse { $this->logger->debug('Starting WebAuthn login'); + if (!$this->webAuthnManger->isWebAuthnAvailable()) { + return new JSONResponse([], Http::STATUS_FORBIDDEN); + } + $this->logger->debug('Converting login name to UID'); $uid = $loginName; Util::emitHook( @@ -72,6 +76,10 @@ public function startAuthentication(string $loginName): JSONResponse { public function finishAuthentication(string $data): JSONResponse { $this->logger->debug('Validating WebAuthn login'); + if (!$this->webAuthnManger->isWebAuthnAvailable()) { + return new JSONResponse([], Http::STATUS_FORBIDDEN); + } + if (!$this->session->exists(self::WEBAUTHN_LOGIN) || !$this->session->exists(self::WEBAUTHN_LOGIN_UID) || !$this->session->exists(self::WEBAUTHN_LOGIN_NAME) diff --git a/lib/private/Authentication/Token/PublicKeyToken.php b/lib/private/Authentication/Token/PublicKeyToken.php index 4720bbc40b399..e22bfb0216d66 100644 --- a/lib/private/Authentication/Token/PublicKeyToken.php +++ b/lib/private/Authentication/Token/PublicKeyToken.php @@ -138,7 +138,7 @@ public function getPassword(): ?string { public function jsonSerialize(): array { return [ 'id' => $this->id, - 'name' => $this->name, + 'name' => $this->getName(), 'lastActivity' => $this->lastActivity, 'type' => $this->type, 'scope' => $this->getScopeAsArray() @@ -195,12 +195,14 @@ public function setScope(array|string|null $scope): void { #[\Override] public function getName(): string { - return parent::getName(); + // Rows stored before names were scrubbed may hold invalid UTF-8 + return mb_scrub(parent::getName() ?? '', 'UTF-8'); } #[\Override] public function setName(string $name): void { - parent::setName($name); + // Names often come from the User-Agent header, which isn't guaranteed to be UTF-8 + parent::setName(mb_scrub($name, 'UTF-8')); } #[\Override] diff --git a/tests/Core/Controller/ClientFlowLoginControllerTest.php b/tests/Core/Controller/ClientFlowLoginControllerTest.php index f77db8d79e72e..a33a78dee02fe 100644 --- a/tests/Core/Controller/ClientFlowLoginControllerTest.php +++ b/tests/Core/Controller/ClientFlowLoginControllerTest.php @@ -146,7 +146,7 @@ public function testShowAuthPickerPageWithOcsHeader(): void { ->expects($this->atLeastOnce()) ->method('get') ->with('oauth.state') - ->willReturn('OauthStateToken'); + ->willReturn(['clientIdentifier' => 'OtherClientIdentifier', 'state' => 'OauthStateToken']); $this->defaults ->expects($this->once()) ->method('getName') @@ -184,7 +184,7 @@ public function testShowAuthPickerPageWithOcsHeader(): void { 'instanceName' => 'ExampleCloud', 'stateToken' => 'StateToken', 'serverHost' => 'https://example.com', - 'oauthState' => 'OauthStateToken', + 'oauthState' => null, 'direct' => false, 'providedRedirectUri' => '', 'appTokenUrl' => '', @@ -225,7 +225,7 @@ public function testShowAuthPickerPageWithOauth(): void { ->expects($this->atLeastOnce()) ->method('get') ->with('oauth.state') - ->willReturn('OauthStateToken'); + ->willReturn(['clientIdentifier' => 'MyClientIdentifier', 'state' => 'OauthStateToken']); $this->defaults ->expects($this->once()) ->method('getName') @@ -421,16 +421,17 @@ public function testGeneratePasswordWithPassword(): void { * @param string $redirectUrl * * @testWith - * ["https://example.com/redirect.php", "https://example.com/redirect.php?state=MyOauthState&code=MyAccessCode"] - * ["https://example.com/redirect.php?hello=world", "https://example.com/redirect.php?hello=world&state=MyOauthState&code=MyAccessCode"] + * ["https://example.com/redirect.php", "https://example.com/redirect.php?state=MyOauthState&code=MyAccessCode", "MyClientIdentifier"] + * ["https://example.com/redirect.php?hello=world", "https://example.com/redirect.php?hello=world&state=MyOauthState&code=MyAccessCode", "MyClientIdentifier"] + * ["https://example.com/redirect.php", "https://example.com/redirect.php?state=&code=MyAccessCode", "OtherClientIdentifier"] * */ - public function testGeneratePasswordWithPasswordForOauthClient($redirectUri, $redirectUrl): void { + public function testGeneratePasswordWithPasswordForOauthClient($redirectUri, $redirectUrl, string $stateClientIdentifier): void { $this->session ->method('get') ->willReturnMap([ ['client.flow.state.token', 'MyStateToken'], - ['oauth.state', 'MyOauthState'], + ['oauth.state', ['clientIdentifier' => $stateClientIdentifier, 'state' => 'MyOauthState']], ]); $calls = [ 'client.flow.state.token', diff --git a/tests/Core/Controller/WebAuthnControllerTest.php b/tests/Core/Controller/WebAuthnControllerTest.php new file mode 100644 index 0000000000000..77de26a2e2591 --- /dev/null +++ b/tests/Core/Controller/WebAuthnControllerTest.php @@ -0,0 +1,67 @@ +manager = $this->createMock(Manager::class); + $this->manager->method('isWebAuthnAvailable')->willReturn(false); + $this->session = $this->createMock(ISession::class); + $this->chain = $this->createMock(WebAuthnChain::class); + $this->controller = new WebAuthnController( + 'core', + $this->createMock(IRequest::class), + $this->manager, + $this->session, + $this->createMock(LoggerInterface::class), + $this->chain, + $this->createMock(URLGenerator::class), + $this->createMock(IUserManager::class), + ); + } + + public function testStartAuthenticationRefusedWhenDisabled(): void { + $this->manager->expects($this->never())->method('startAuthentication'); + $this->session->expects($this->never())->method('set'); + + $response = $this->controller->startAuthentication('alice'); + + $this->assertSame(Http::STATUS_FORBIDDEN, $response->getStatus()); + } + + public function testFinishAuthenticationRefusedWhenDisabled(): void { + $this->session->method('exists')->willReturn(true); + $this->manager->expects($this->never())->method('finishAuthentication'); + $this->chain->expects($this->never())->method('process'); + + $response = $this->controller->finishAuthentication('{}'); + + $this->assertSame(Http::STATUS_FORBIDDEN, $response->getStatus()); + } +} diff --git a/tests/lib/Authentication/Token/PublicKeyTokenTest.php b/tests/lib/Authentication/Token/PublicKeyTokenTest.php index 5f5f29c865ffa..59b567ebbef4e 100644 --- a/tests/lib/Authentication/Token/PublicKeyTokenTest.php +++ b/tests/lib/Authentication/Token/PublicKeyTokenTest.php @@ -26,4 +26,25 @@ public function testDefaultScope(): void { $token = new PublicKeyToken(); $this->assertEquals($scope, $token->getScopeAsArray()); } + + public function testSetNameScrubsInvalidUtf8(): void { + $token = new PublicKeyToken(); + $token->setName("Spy\xff"); + + $this->assertTrue(mb_check_encoding($token->getName(), 'UTF-8')); + $this->assertStringStartsWith('Spy', $token->getName()); + } + + public function testSetNameKeepsValidUtf8(): void { + $token = new PublicKeyToken(); + $token->setName('Müller’s iPhone'); + + $this->assertSame('Müller’s iPhone', $token->getName()); + } + + public function testStoredInvalidNameSerializesToJson(): void { + $token = PublicKeyToken::fromRow(['id' => 1, 'name' => "Spy\xff", 'type' => IToken::PERMANENT_TOKEN]); + + $this->assertIsString(json_encode($token->jsonSerialize(), JSON_THROW_ON_ERROR)); + } } From 810abfd4da4813892a4965100b2221a32956ed78 Mon Sep 17 00:00:00 2001 From: Peter Ringelmann Date: Tue, 1 Dec 2026 17:46:06 +0100 Subject: [PATCH 10/15] fix(auth): start an empty session for header token logins The client chooses the session ID it sends, so a token login from the Authorization header must not continue on a session it did not start. Password and Basic logins already get a new session. Assisted-by: ClaudeCode:claude-opus-5-5 Signed-off-by: Peter Ringelmann --- lib/private/User/Session.php | 7 ++++ tests/lib/User/SessionTest.php | 60 ++++++++++++++++++++++++++++++++++ 2 files changed, 67 insertions(+) diff --git a/lib/private/User/Session.php b/lib/private/User/Session.php index 09f78f250ad65..df68e4d51c45b 100644 --- a/lib/private/User/Session.php +++ b/lib/private/User/Session.php @@ -918,6 +918,13 @@ public function tryTokenLogin(IRequest $request) { return false; } + if (!$tokenFromCookie + && $request->getCookie($this->config->getSystemValueString('instanceid')) !== null + && $this->session->get('app_password') !== $token) { + // The client chose this session, so a header login starts an empty one instead of writing into it + $this->session->clear(); + } + if (!$this->loginWithToken($token)) { $this->handleLoginFailed($throttler, $currentDelay, $remoteAddress, $dbToken->getUID(), $token); return false; diff --git a/tests/lib/User/SessionTest.php b/tests/lib/User/SessionTest.php index dd2858aa782a3..12d3eef80b7cf 100644 --- a/tests/lib/User/SessionTest.php +++ b/tests/lib/User/SessionTest.php @@ -655,6 +655,8 @@ public function testTryTokenLoginNotAnAppPassword(): void { ->method('getToken') ->with('abcde12345') ->willReturn($dbToken); + $this->session->expects(self::never()) + ->method('clear'); $this->session->method('set') ->willReturnCallback(function ($key, $value): void { if ($key === 'app_password') { @@ -672,6 +674,64 @@ public function testTryTokenLoginNotAnAppPassword(): void { self::assertTrue($loginResult); } + private function mockAppPasswordLogin(?string $sessionCookie): IRequest { + $request = $this->createMock(IRequest::class); + $request->method('getHeader')->with('Authorization')->willReturn('Bearer app-token'); + $this->config->method('getSystemValueString')->with('instanceid')->willReturn('abc123'); + $request->method('getCookie')->with('abc123')->willReturn($sessionCookie); + $dbToken = new PublicKeyToken(); + $dbToken->setId(42); + $dbToken->setUid('alice'); + $dbToken->setLoginName('alice'); + $dbToken->setLastCheck(10000); + $dbToken->setType(IToken::PERMANENT_TOKEN); + $this->tokenProvider->method('getToken') + ->with('app-token') + ->willReturn($dbToken); + $user = $this->createMock(IUser::class); + $user->method('isEnabled')->willReturn(true); + $this->manager->method('get') + ->with('alice') + ->willReturn($user); + return $request; + } + + public function testTryTokenLoginAuthorizationHeaderClearsClientSessionFirst(): void { + $request = $this->mockAppPasswordLogin('client-chosen-id'); + + $cleared = false; + $this->session->expects($this->once()) + ->method('clear') + ->willReturnCallback(function () use (&$cleared): void { + $cleared = true; + }); + $assertCleared = function () use (&$cleared): void { + $this->assertTrue($cleared); + }; + $this->session->method('set')->willReturnCallback($assertCleared); + $this->dispatcher->method('dispatchTyped')->willReturnCallback($assertCleared); + + $this->assertTrue($this->userSession->tryTokenLogin($request)); + } + + public function testTryTokenLoginAuthorizationHeaderKeepsSessionOfSameAppPassword(): void { + $request = $this->mockAppPasswordLogin('own-session-id'); + $this->session->method('get') + ->willReturnMap([['app_password', 'app-token']]); + $this->session->expects($this->never()) + ->method('clear'); + + $this->assertTrue($this->userSession->tryTokenLogin($request)); + } + + public function testTryTokenLoginAuthorizationHeaderWithoutSessionCookieKeepsSession(): void { + $request = $this->mockAppPasswordLogin(null); + $this->session->expects($this->never()) + ->method('clear'); + + $this->assertTrue($this->userSession->tryTokenLogin($request)); + } + public function testRememberLoginValidToken(): void { $session = $this->createMock(Memory::class); $managerMethods = get_class_methods(Manager::class); From 6826a2980bb7445c48a875653bde4a07a27459ef Mon Sep 17 00:00:00 2001 From: Peter Ringelmann Date: Wed, 2 Dec 2026 11:03:52 +0100 Subject: [PATCH 11/15] fix(auth): rotate the stored token The token passed to rotate() can come from the token cache, which may still hold a token that was deleted or changed in the meantime. Rotate the stored row instead and stop serving the old hash from the cache. Assisted-by: ClaudeCode:claude-opus-5-5 Signed-off-by: Peter Ringelmann --- core/Controller/AppPasswordController.php | 6 +- .../Authentication/Token/IProvider.php | 3 +- .../Token/PublicKeyTokenProvider.php | 23 +++- .../Controller/AppPasswordControllerTest.php | 59 ++++++++++ .../Token/PublicKeyTokenProviderTest.php | 108 ++++++++++++++++++ 5 files changed, 193 insertions(+), 6 deletions(-) diff --git a/core/Controller/AppPasswordController.php b/core/Controller/AppPasswordController.php index ee8ad99fd2fb2..44a72dd51752f 100644 --- a/core/Controller/AppPasswordController.php +++ b/core/Controller/AppPasswordController.php @@ -153,15 +153,15 @@ public function rotateAppPassword(): DataResponse { $appPassword = $this->session->get('app_password'); + $newToken = $this->random->generate(72, ISecureRandom::CHAR_UPPER . ISecureRandom::CHAR_LOWER . ISecureRandom::CHAR_DIGITS); + try { $token = $this->tokenProvider->getToken($appPassword); + $this->tokenProvider->rotate($token, $appPassword, $newToken); } catch (InvalidTokenException $e) { throw new OCSForbiddenException('could not rotate apptoken'); } - $newToken = $this->random->generate(72, ISecureRandom::CHAR_UPPER . ISecureRandom::CHAR_LOWER . ISecureRandom::CHAR_DIGITS); - $this->tokenProvider->rotate($token, $appPassword, $newToken); - return new DataResponse([ 'apppassword' => $newToken, ]); diff --git a/lib/private/Authentication/Token/IProvider.php b/lib/private/Authentication/Token/IProvider.php index 39cca8f3432a8..9350e9bd9f1cc 100644 --- a/lib/private/Authentication/Token/IProvider.php +++ b/lib/private/Authentication/Token/IProvider.php @@ -159,7 +159,8 @@ public function setPassword(OCPIToken $token, string $tokenId, string $password) * @param OCPIToken $token * @param string $oldTokenId * @param string $newTokenId - * @return OCPIToken + * @return OCPIToken the rotated token as it is stored, not necessarily the given instance + * @throws InvalidTokenException when the token does not exist (anymore) * @throws \RuntimeException when OpenSSL reports a problem */ public function rotate(OCPIToken $token, string $oldTokenId, string $newTokenId): OCPIToken; diff --git a/lib/private/Authentication/Token/PublicKeyTokenProvider.php b/lib/private/Authentication/Token/PublicKeyTokenProvider.php index d3073b6967434..d5bf45a58d2fc 100644 --- a/lib/private/Authentication/Token/PublicKeyTokenProvider.php +++ b/lib/private/Authentication/Token/PublicKeyTokenProvider.php @@ -141,7 +141,7 @@ public function getToken(string $tokenId, bool $allowReadFromCache = true): OCPI } catch (DoesNotExistException $ex) { try { $token = $this->mapper->getToken($this->hashTokenWithEmptySecret($tokenId)); - $this->rotate($token, $tokenId, $tokenId); + $token = $this->rotate($token, $tokenId, $tokenId); } catch (DoesNotExistException) { $this->cacheInvalidHash($tokenHash); throw new InvalidTokenException('Token does not exist: ' . $ex->getMessage(), 0, $ex); @@ -399,14 +399,33 @@ public function rotate(OCPIToken $token, string $oldTokenId, string $newTokenId) throw new InvalidTokenException('Invalid token type'); } + // The given token might come from the cache, so rotate what is stored: + // it might have been invalidated, rotated or changed in the meantime + $oldTokenHash = $token->getToken(); + try { + $token = $this->mapper->getToken($oldTokenHash); + } catch (DoesNotExistException $ex) { + $this->cacheInvalidHash($oldTokenHash); + throw new InvalidTokenException('Token does not exist: ' . $ex->getMessage(), 0, $ex); + } + if ($token->getType() === OCPIToken::WIPE_TOKEN) { + $this->cacheToken($token); + throw new WipeTokenException($token); + } + // Decrypt private key with oldTokenId $privateKey = $this->decrypt($token->getPrivateKey(), $oldTokenId); // Encrypt with the new token $token->setPrivateKey($this->encrypt($privateKey, $newTokenId)); - $token->setToken($this->hashToken($newTokenId)); + $newTokenHash = $this->hashToken($newTokenId); + $token->setToken($newTokenHash); $this->updateToken($token); + if ($oldTokenHash !== $newTokenHash) { + $this->cacheInvalidHash($oldTokenHash); + } + return $token; } diff --git a/tests/Core/Controller/AppPasswordControllerTest.php b/tests/Core/Controller/AppPasswordControllerTest.php index 123a61efa119b..de85673fbb4eb 100644 --- a/tests/Core/Controller/AppPasswordControllerTest.php +++ b/tests/Core/Controller/AppPasswordControllerTest.php @@ -293,4 +293,63 @@ public function testDeleteAppPasswordSuccess(): void { $this->assertEquals(new DataResponse(), $result); } + + public function testRotateAppPasswordNoAppPassword(): void { + $this->session->method('exists') + ->with('app_password') + ->willReturn(false); + + $this->expectException(OCSForbiddenException::class); + + $this->controller->rotateAppPassword(); + } + + public function testRotateAppPasswordFails(): void { + $this->session->method('exists') + ->with('app_password') + ->willReturn(true); + $this->session->method('get') + ->with('app_password') + ->willReturn('myAppPassword'); + $this->random->method('generate') + ->willReturn('myNewAppPassword'); + + $token = $this->createMock(IToken::class); + $this->tokenProvider->method('getToken') + ->with('myAppPassword') + ->willReturn($token); + $this->tokenProvider->expects($this->once()) + ->method('rotate') + ->with($token, 'myAppPassword', 'myNewAppPassword') + ->willThrowException(new InvalidTokenException()); + + $this->expectException(OCSForbiddenException::class); + + $this->controller->rotateAppPassword(); + } + + public function testRotateAppPasswordSuccess(): void { + $this->session->method('exists') + ->with('app_password') + ->willReturn(true); + $this->session->method('get') + ->with('app_password') + ->willReturn('myAppPassword'); + $this->random->method('generate') + ->willReturn('myNewAppPassword'); + + $token = $this->createMock(IToken::class); + $this->tokenProvider->method('getToken') + ->with('myAppPassword') + ->willReturn($token); + $this->tokenProvider->expects($this->once()) + ->method('rotate') + ->with($token, 'myAppPassword', 'myNewAppPassword') + ->willReturn($token); + + $result = $this->controller->rotateAppPassword(); + + $this->assertEquals(new DataResponse(['apppassword' => 'myNewAppPassword']), $result); + } + } diff --git a/tests/lib/Authentication/Token/PublicKeyTokenProviderTest.php b/tests/lib/Authentication/Token/PublicKeyTokenProviderTest.php index 526011f72aac1..77616f4c462b0 100644 --- a/tests/lib/Authentication/Token/PublicKeyTokenProviderTest.php +++ b/tests/lib/Authentication/Token/PublicKeyTokenProviderTest.php @@ -12,9 +12,11 @@ use OC\Authentication\Exceptions\ExpiredTokenException; use OC\Authentication\Exceptions\InvalidTokenException; use OC\Authentication\Exceptions\PasswordlessTokenException; +use OC\Authentication\Exceptions\WipeTokenException; use OC\Authentication\Token\PublicKeyToken; use OC\Authentication\Token\PublicKeyTokenMapper; use OC\Authentication\Token\PublicKeyTokenProvider; +use OC\Memcache\ArrayCache; use OCP\AppFramework\Db\DoesNotExistException; use OCP\AppFramework\Utility\ITimeFactory; use OCP\Authentication\Token\IToken; @@ -619,6 +621,9 @@ public function testRotate(): void { ['auth.storeCryptedPassword', true, true], ]); $actual = $this->tokenProvider->generateToken($token, $uid, $user, $password, $name, $type, IToken::DO_NOT_REMEMBER); + $this->mapper->method('getToken') + ->with($actual->getToken()) + ->willReturn($actual); $new = $this->tokenProvider->rotate($actual, 'oldtokentokentokentokentoken', 'newtokentokentokentokentoken'); @@ -634,6 +639,9 @@ public function testRotateNoPassword(): void { $type = IToken::PERMANENT_TOKEN; $actual = $this->tokenProvider->generateToken($token, $uid, $user, $password, $name, $type, IToken::DO_NOT_REMEMBER); + $this->mapper->method('getToken') + ->with($actual->getToken()) + ->willReturn($actual); $oldPrivate = $actual->getPrivateKey(); @@ -645,6 +653,106 @@ public function testRotateNoPassword(): void { $this->assertNull($new->getPassword()); } + public function testRotateInvalidatesOldTokenInCache(): void { + $oldToken = 'oldtokentokentokentokentoken'; + $newToken = 'newtokentokentokentokentoken'; + + $this->cacheFactory->method('createInMemory') + ->willReturn(new ArrayCache()); + $tokenProvider = new PublicKeyTokenProvider( + $this->mapper, + $this->crypto, + $this->config, + $this->db, + $this->logger, + $this->timeFactory, + $this->hasher, + $this->cacheFactory, + $this->eventDispatcher, + ); + + $actual = $tokenProvider->generateToken($oldToken, 'user', 'User', null, 'name', IToken::PERMANENT_TOKEN); + $oldHash = $actual->getToken(); + $this->assertSame($oldHash, $tokenProvider->getToken($oldToken)->getToken()); + + // Only the cache knows the token after the rotation + $stored = true; + $this->mapper->method('getToken') + ->willReturnCallback(function (string $hash) use (&$stored, $oldHash, $actual) { + if ($stored && $hash === $oldHash) { + return $actual; + } + throw new DoesNotExistException(''); + }); + + $tokenProvider->rotate($actual, $oldToken, $newToken); + $stored = false; + + $this->assertSame($actual->getToken(), $tokenProvider->getToken($newToken)->getToken()); + + $this->expectException(InvalidTokenException::class); + $tokenProvider->getToken($oldToken); + } + + public function testRotateStoredToken(): void { + $oldToken = 'oldtokentokentokentokentoken'; + $newToken = 'newtokentokentokentokentoken'; + + // What the caller has, e.g. from the cache, is older than what is stored + $outdated = $this->tokenProvider->generateToken($oldToken, 'user', 'User', null, 'name', IToken::PERMANENT_TOKEN); + $stored = clone $outdated; + $stored->setScope([IToken::SCOPE_FILESYSTEM => false]); + + $this->mapper->expects($this->once()) + ->method('getToken') + ->with($outdated->getToken()) + ->willReturn($stored); + $this->mapper->expects($this->once()) + ->method('update') + ->with($stored); + + $new = $this->tokenProvider->rotate($outdated, $oldToken, $newToken); + + $this->assertSame($stored, $new); + $this->assertSame([IToken::SCOPE_FILESYSTEM => false], $new->getScopeAsArray()); + } + + public function testRotateDeletedToken(): void { + $oldToken = 'oldtokentokentokentokentoken'; + $newToken = 'newtokentokentokentokentoken'; + + $actual = $this->tokenProvider->generateToken($oldToken, 'user', 'User', null, 'name', IToken::PERMANENT_TOKEN); + + $this->mapper->expects($this->once()) + ->method('getToken') + ->with($actual->getToken()) + ->willThrowException(new DoesNotExistException('')); + $this->mapper->expects($this->never()) + ->method('update'); + + $this->expectException(InvalidTokenException::class); + $this->tokenProvider->rotate($actual, $oldToken, $newToken); + } + + public function testRotateTokenMarkedForWipe(): void { + $oldToken = 'oldtokentokentokentokentoken'; + $newToken = 'newtokentokentokentokentoken'; + + $actual = $this->tokenProvider->generateToken($oldToken, 'user', 'User', null, 'name', IToken::PERMANENT_TOKEN); + + $stored = clone $actual; + $stored->setType(IToken::WIPE_TOKEN); + $this->mapper->expects($this->once()) + ->method('getToken') + ->with($actual->getToken()) + ->willReturn($stored); + $this->mapper->expects($this->never()) + ->method('update'); + + $this->expectException(WipeTokenException::class); + $this->tokenProvider->rotate($actual, $oldToken, $newToken); + } + public function testMarkPasswordInvalidInvalidToken(): void { $token = $this->createMock(IToken::class); From b2f51be255da7caec0d06b8cce3f59af6933c2fb Mon Sep 17 00:00:00 2001 From: Carl Schwan Date: Wed, 4 Nov 2026 16:25:37 +0100 Subject: [PATCH 12/15] feat: Add IAppAccessFilter api Allow other apps like guests to filter down the list of accessible apps. Assisted-by: ClaudeCode:claude-opus-5-5 Signed-off-by: Carl Schwan (cherry picked from commit 84518c1ab7094bd50565c392f208f41ebfd51eff) --- lib/composer/composer/autoload_classmap.php | 1 + lib/composer/composer/autoload_static.php | 1 + lib/private/App/AppManager.php | 67 ++++++++++++++++-- .../Bootstrap/RegistrationContext.php | 26 +++++++ lib/public/App/IAppAccessFilter.php | 41 +++++++++++ .../Bootstrap/IRegistrationContext.php | 9 +++ tests/lib/App/AppManagerTest.php | 68 +++++++++++++++++++ 7 files changed, 207 insertions(+), 6 deletions(-) create mode 100644 lib/public/App/IAppAccessFilter.php diff --git a/lib/composer/composer/autoload_classmap.php b/lib/composer/composer/autoload_classmap.php index 6063c8442737b..a02db2254082d 100644 --- a/lib/composer/composer/autoload_classmap.php +++ b/lib/composer/composer/autoload_classmap.php @@ -158,6 +158,7 @@ 'OCP\\App\\Events\\AppDisableEvent' => $baseDir . '/lib/public/App/Events/AppDisableEvent.php', 'OCP\\App\\Events\\AppEnableEvent' => $baseDir . '/lib/public/App/Events/AppEnableEvent.php', 'OCP\\App\\Events\\AppUpdateEvent' => $baseDir . '/lib/public/App/Events/AppUpdateEvent.php', + 'OCP\\App\\IAppAccessFilter' => $baseDir . '/lib/public/App/IAppAccessFilter.php', 'OCP\\App\\IAppManager' => $baseDir . '/lib/public/App/IAppManager.php', 'OCP\\App\\ManagerEvent' => $baseDir . '/lib/public/App/ManagerEvent.php', 'OCP\\Authentication\\Events\\AnyLoginFailedEvent' => $baseDir . '/lib/public/Authentication/Events/AnyLoginFailedEvent.php', diff --git a/lib/composer/composer/autoload_static.php b/lib/composer/composer/autoload_static.php index 3aa646e7dd815..1da917c20f582 100644 --- a/lib/composer/composer/autoload_static.php +++ b/lib/composer/composer/autoload_static.php @@ -199,6 +199,7 @@ class ComposerStaticInit749170dad3f5e7f9ca158f5a9f04f6a2 'OCP\\App\\Events\\AppDisableEvent' => __DIR__ . '/../../..' . '/lib/public/App/Events/AppDisableEvent.php', 'OCP\\App\\Events\\AppEnableEvent' => __DIR__ . '/../../..' . '/lib/public/App/Events/AppEnableEvent.php', 'OCP\\App\\Events\\AppUpdateEvent' => __DIR__ . '/../../..' . '/lib/public/App/Events/AppUpdateEvent.php', + 'OCP\\App\\IAppAccessFilter' => __DIR__ . '/../../..' . '/lib/public/App/IAppAccessFilter.php', 'OCP\\App\\IAppManager' => __DIR__ . '/../../..' . '/lib/public/App/IAppManager.php', 'OCP\\App\\ManagerEvent' => __DIR__ . '/../../..' . '/lib/public/App/ManagerEvent.php', 'OCP\\Authentication\\Events\\AnyLoginFailedEvent' => __DIR__ . '/../../..' . '/lib/public/Authentication/Events/AnyLoginFailedEvent.php', diff --git a/lib/private/App/AppManager.php b/lib/private/App/AppManager.php index 72e2c51164423..f433594a10510 100644 --- a/lib/private/App/AppManager.php +++ b/lib/private/App/AppManager.php @@ -20,6 +20,7 @@ use OCP\App\Events\AppDisableEvent; use OCP\App\Events\AppEnableEvent; use OCP\App\Events\AppUpdateEvent; +use OCP\App\IAppAccessFilter; use OCP\App\IAppManager; use OCP\App\ManagerEvent; use OCP\BackgroundJob\IJobList; @@ -39,6 +40,7 @@ use OCP\Server; use OCP\ServerVersion; use OCP\Settings\IManager as ISettingsManager; +use Psr\Container\ContainerExceptionInterface; use Psr\Log\LoggerInterface; /** @@ -89,6 +91,9 @@ class AppManager implements IAppManager { private ?IURLGenerator $urlGenerator = null; private ?INavigationManager $navigationManager = null; + /** @var list|null */ + private ?array $appAccessFilters = null; + /** * Be extremely careful when injecting classes here. The AppManager is used by the installer, * so it needs to work before installation. See how AppConfig and IURLGenerator are injected for reference @@ -238,12 +243,60 @@ public function getAllAppsInAppsFolders(): array { #[\Override] public function getEnabledAppsForUser(IUser $user) { $apps = $this->getEnabledAppsValues(); - $appsForUser = array_filter($apps, function ($enabled) use ($user) { - return $this->checkAppForUser($enabled, $user); - }); + $appsForUser = array_filter($apps, function (string $enabled, string $appId) use ($user): bool { + return $this->checkAppForUser($enabled, $user) + && $this->isAccessibleForUser($appId, $user); + }, ARRAY_FILTER_USE_BOTH); return array_keys($appsForUser); } + /** + * Apply the registered app access filters. Always enabled apps and apps + * with a protected type can't be restricted. + */ + private function isAccessibleForUser(string $appId, IUser $user): bool { + if ($this->isAlwaysEnabled($appId)) { + return true; + } + + foreach ($this->getAppAccessFilters() as $filter) { + if (!$filter->isAppAccessible($appId, $user)) { + return $this->hasProtectedAppType($this->getAppTypes($appId)); + } + } + + return true; + } + + /** + * @return list + */ + private function getAppAccessFilters(): array { + if ($this->appAccessFilters !== null) { + return $this->appAccessFilters; + } + + $context = Server::get(Coordinator::class)->getRegistrationContext(); + if ($context === null) { + // Apps are not registered yet, so don't cache the empty list + return []; + } + + $filters = []; + foreach ($context->getAppAccessFilters() as $registration) { + try { + $filters[] = Server::get($registration->getService()); + } catch (ContainerExceptionInterface $e) { + $this->logger->error('Could not load app access filter: ' . $e->getMessage(), [ + 'exception' => $e, + 'app' => $registration->getAppId(), + ]); + } + } + + return $this->appAccessFilters = $filters; + } + #[\Override] public function getEnabledAppsForGroup(IGroup $group): array { $apps = $this->getEnabledAppsValues(); @@ -368,11 +421,13 @@ public function isEnabledForUser($appId, $user = null) { $user = $this->userSession->getUser(); } $enabledAppsValues = $this->getEnabledAppsValues(); - if (isset($enabledAppsValues[$appId])) { - return $this->checkAppForUser($enabledAppsValues[$appId], $user); - } else { + if (!isset($enabledAppsValues[$appId])) { + return false; + } + if (!$this->checkAppForUser($enabledAppsValues[$appId], $user)) { return false; } + return $user === null || $this->isAccessibleForUser($appId, $user); } private function checkAppForUser(string $enabled, ?IUser $user): bool { diff --git a/lib/private/AppFramework/Bootstrap/RegistrationContext.php b/lib/private/AppFramework/Bootstrap/RegistrationContext.php index cb4d23cb0f4ca..563bff54870dd 100644 --- a/lib/private/AppFramework/Bootstrap/RegistrationContext.php +++ b/lib/private/AppFramework/Bootstrap/RegistrationContext.php @@ -11,6 +11,7 @@ use Closure; use OC\Support\CrashReport\Registry; +use OCP\App\IAppAccessFilter; use OCP\AppFramework\App; use OCP\AppFramework\Bootstrap\IRegistrationContext; use OCP\AppFramework\Middleware; @@ -174,6 +175,9 @@ class RegistrationContext { /** @var class-string|null */ private ?string $globalScaleService = null; + /** @var ServiceRegistration[] */ + private array $appAccessFilters = []; + public function __construct( private LoggerInterface $logger, ) { @@ -513,6 +517,14 @@ public function registerGlobalScaleService(string $globalScaleServiceClass): voi $globalScaleServiceClass ); } + + #[\Override] + public function registerAppAccessFilter(string $appAccessFilterClass): void { + $this->context->registerAppAccessFilter( + $this->appId, + $appAccessFilterClass + ); + } }; } @@ -745,6 +757,13 @@ public function registerGlobalScaleService(string $class): void { $this->globalScaleService = $class; } + /** + * @psalm-param class-string $class + */ + public function registerAppAccessFilter(string $appId, string $class): void { + $this->appAccessFilters[] = new ServiceRegistration($appId, $class); + } + /** * @param App[] $apps */ @@ -1140,4 +1159,11 @@ public function getConfigLexicon(string $appId): ?ILexicon { public function getGlobalScaleService(): ?string { return $this->globalScaleService; } + + /** + * @return ServiceRegistration[] + */ + public function getAppAccessFilters(): array { + return $this->appAccessFilters; + } } diff --git a/lib/public/App/IAppAccessFilter.php b/lib/public/App/IAppAccessFilter.php new file mode 100644 index 0000000000000..68be8230d4743 --- /dev/null +++ b/lib/public/App/IAppAccessFilter.php @@ -0,0 +1,41 @@ + $appAccessFilterClass + * @since 33.0.10 + */ + public function registerAppAccessFilter(string $appAccessFilterClass): void; } diff --git a/tests/lib/App/AppManagerTest.php b/tests/lib/App/AppManagerTest.php index ee609418fbbac..8b0ab4f585523 100644 --- a/tests/lib/App/AppManagerTest.php +++ b/tests/lib/App/AppManagerTest.php @@ -14,10 +14,14 @@ use OC\App\DependencyAnalyzer; use OC\App\Platform; use OC\AppConfig; +use OC\AppFramework\Bootstrap\Coordinator; +use OC\AppFramework\Bootstrap\RegistrationContext; +use OC\AppFramework\Bootstrap\ServiceRegistration; use OC\Config\ConfigManager; use OCP\App\AppPathNotFoundException; use OCP\App\Events\AppDisableEvent; use OCP\App\Events\AppEnableEvent; +use OCP\App\IAppAccessFilter; use OCP\EventDispatcher\IEventDispatcher; use OCP\ICache; use OCP\ICacheFactory; @@ -601,6 +605,70 @@ public function testGetAppsForUser(): void { $this->assertEquals($enabled, $this->manager->getEnabledAppsForUser($user)); } + /** + * @param list $deniedApps + */ + private function registerAppAccessFilter(array $deniedApps): IAppAccessFilter&MockObject { + $filter = $this->createMock(IAppAccessFilter::class); + $filter->method('isAppAccessible') + ->willReturnCallback(fn (string $appId): bool => !in_array($appId, $deniedApps, true)); + + $registrationContext = $this->createMock(RegistrationContext::class); + $registrationContext->method('getAppAccessFilters') + ->willReturn([new ServiceRegistration('guests', IAppAccessFilter::class)]); + $coordinator = $this->createMock(Coordinator::class); + $coordinator->method('getRegistrationContext') + ->willReturn($registrationContext); + + $this->overwriteService(Coordinator::class, $coordinator); + $this->overwriteService(IAppAccessFilter::class, $filter); + + return $filter; + } + + public function testIsEnabledForUserDeniedByAccessFilter(): void { + $this->registerAppAccessFilter(['test']); + $this->appConfig->setValue('test', 'enabled', 'yes'); + $this->appConfig->setValue('other', 'enabled', 'yes'); + $user = $this->newUser('user1'); + + $this->assertFalse($this->manager->isEnabledForUser('test', $user)); + $this->assertTrue($this->manager->isEnabledForUser('other', $user)); + } + + + + public function testIsEnabledForUserAccessFilterIgnoresProtectedAppType(): void { + $this->registerAppAccessFilter(['test']); + $this->appConfig->setValue('test', 'enabled', 'yes'); + $this->appConfig->setValue('test', 'types', 'filesystem'); + + $this->assertTrue($this->manager->isEnabledForUser('test', $this->newUser('user1'))); + } + + + public function testGetAppsForUserWithAccessFilter(): void { + $this->registerAppAccessFilter(['test1', 'test3', 'files']); + $user = $this->newUser('user1'); + $this->groupManager->method('getUserGroupIds') + ->with($user) + ->willReturn(['foo']); + + $this->appConfig->setValue('test1', 'enabled', 'yes'); + $this->appConfig->setValue('test2', 'enabled', 'yes'); + $this->appConfig->setValue('test3', 'enabled', '["foo"]'); + $this->appConfig->setValue('test4', 'enabled', 'yes'); + $this->appConfig->setValue('test4', 'types', 'authentication'); + + $apps = $this->manager->getEnabledAppsForUser($user); + + $this->assertNotContains('test1', $apps); + $this->assertContains('test2', $apps); + $this->assertNotContains('test3', $apps); + $this->assertContains('test4', $apps); + $this->assertContains('files', $apps); + } + public function testGetAppsNeedingUpgrade(): void { /** @var AppManager&MockObject $manager */ $manager = $this->getMockBuilder(AppManager::class) From 612a4ffd6c9d114d96b81f791409c2bcae6a07e0 Mon Sep 17 00:00:00 2001 From: Carl Schwan Date: Wed, 4 Nov 2026 16:30:32 +0100 Subject: [PATCH 13/15] fix(search): Hide providers of apps not enabled for the user Skip unified search providers whose app is not enabled for the user, so group restrictions and app access filters also apply to search results. Assisted-by: ClaudeCode:claude-opus-5-5 Signed-off-by: Carl Schwan (cherry picked from commit 990c25db60d850eb2818e784ec2fde3f48abc769) --- core/Controller/UnifiedSearchController.php | 2 +- lib/private/Search/SearchComposer.php | 14 ++++- tests/lib/Search/SearchComposerTest.php | 64 ++++++++++++++++++--- 3 files changed, 69 insertions(+), 11 deletions(-) diff --git a/core/Controller/UnifiedSearchController.php b/core/Controller/UnifiedSearchController.php index 6888a9a26393d..df9997f38cfb4 100644 --- a/core/Controller/UnifiedSearchController.php +++ b/core/Controller/UnifiedSearchController.php @@ -61,7 +61,7 @@ public function __construct( public function getProviders(string $from = ''): DataResponse { [$route, $parameters] = $this->getRouteInformation($from); - $result = $this->composer->getProviders($route, $parameters); + $result = $this->composer->getProviders($this->userSession->getUser(), $route, $parameters); $response = new DataResponse($result); $response->setETag(md5(json_encode($result))); return $response; diff --git a/lib/private/Search/SearchComposer.php b/lib/private/Search/SearchComposer.php index c017d1ec9a338..1b894773b3474 100644 --- a/lib/private/Search/SearchComposer.php +++ b/lib/private/Search/SearchComposer.php @@ -13,6 +13,7 @@ use OC\Core\AppInfo\Application; use OC\Core\AppInfo\ConfigLexicon; use OC\Core\ResponseDefinitions; +use OCP\App\IAppManager; use OCP\IAppConfig; use OCP\IURLGenerator; use OCP\IUser; @@ -70,6 +71,7 @@ public function __construct( private IURLGenerator $urlGenerator, private LoggerInterface $logger, private IAppConfig $appConfig, + private IAppManager $appManager, ) { $this->commonFilters = [ IFilter::BUILTIN_TERM => new FilterDefinition(IFilter::BUILTIN_TERM, FilterDefinition::TYPE_STRING), @@ -165,17 +167,21 @@ private function registerCustomFilter(FilterDefinition $filter, string $provider * Get a list of all provider IDs & Names for the consecutive calls to `search` * Sort the list by the order property * + * @param IUser $user the user to list the providers for * @param string $route the route the user is currently at * @param array $routeParameters the parameters of the route the user is currently at * * @return list */ - public function getProviders(string $route, array $routeParameters): array { + public function getProviders(IUser $user, string $route, array $routeParameters): array { $this->loadLazyProviders(); $providers = array_map( - function (array $providerData) use ($route, $routeParameters) { + function (array $providerData) use ($user, $route, $routeParameters) { $appId = $providerData['appId']; + if (!$this->appManager->isEnabledForUser($appId, $user)) { + return; + } $provider = $providerData['provider']; $order = $provider->getOrder($route, $routeParameters); if ($order === null) { @@ -362,6 +368,10 @@ public function search( throw new InvalidArgumentException("Provider $providerId is unknown"); } + if (!$this->appManager->isEnabledForUser($this->providers[$providerId]['appId'], $user)) { + return SearchResult::complete($provider->getName(), []); + } + return $provider->search($user, $query); } } diff --git a/tests/lib/Search/SearchComposerTest.php b/tests/lib/Search/SearchComposerTest.php index 87f0c0b39fc5d..28ebc7b365a5e 100644 --- a/tests/lib/Search/SearchComposerTest.php +++ b/tests/lib/Search/SearchComposerTest.php @@ -14,6 +14,7 @@ use OC\AppFramework\Bootstrap\RegistrationContext; use OC\AppFramework\Bootstrap\ServiceRegistration; use OC\Search\SearchComposer; +use OCP\App\IAppManager; use OCP\IAppConfig; use OCP\IURLGenerator; use OCP\IUser; @@ -31,7 +32,12 @@ class SearchComposerTest extends TestCase { private IURLGenerator&MockObject $urlGenerator; private LoggerInterface&MockObject $logger; private IAppConfig&MockObject $appConfig; + private IAppManager&MockObject $appManager; private SearchComposer $searchComposer; + private IUser $user; + + /** @var list */ + private array $appsDisabledForUser = []; #[\Override] protected function setUp(): void { @@ -42,16 +48,21 @@ protected function setUp(): void { $this->urlGenerator = $this->createMock(IURLGenerator::class); $this->logger = $this->createMock(LoggerInterface::class); $this->appConfig = $this->createMock(IAppConfig::class); + $this->appManager = $this->createMock(IAppManager::class); + $this->user = $this->createMock(IUser::class); $this->searchComposer = new SearchComposer( $this->bootstrapCoordinator, $this->container, $this->urlGenerator, $this->logger, - $this->appConfig + $this->appConfig, + $this->appManager, ); $this->setupUrlGenerator(); + $this->appManager->method('isEnabledForUser') + ->willReturnCallback(fn (string $appId, ?IUser $user): bool => $user === $this->user && !in_array($appId, $this->appsDisabledForUser, true)); } private function setupUrlGenerator(): void { @@ -119,7 +130,7 @@ private function setupRegistrationContextWithProviders(array $registrations): vo public function testGetProvidersWithNoRegisteredProviders(): void { $this->setupEmptyRegistrationContext(); - $providers = $this->searchComposer->getProviders('/test/route', []); + $providers = $this->searchComposer->getProviders($this->user, '/test/route', []); $this->assertIsArray($providers); $this->assertEmpty($providers); @@ -148,7 +159,7 @@ public function testGetProvidersWithMultipleProviders(): void { $this->setupRegistrationContextWithProviders($mockData['registrations']); $this->setupAppConfigForAllowedProviders(); - $providers = $this->searchComposer->getProviders('/test/route', []); + $providers = $this->searchComposer->getProviders($this->user, '/test/route', []); $this->assertProvidersStructureAndSorting($providers, [ ['id' => 'provider2', 'name' => 'Provider provider2', 'appId' => 'app2', 'order' => 5, 'inAppSearch' => false], @@ -167,7 +178,7 @@ public function testGetProvidersWithEmptyAllowedProvidersConfiguration(): void { $this->setupRegistrationContextWithProviders($mockData['registrations']); $this->setupAppConfigForAllowedProviders(); - $providers = $this->searchComposer->getProviders('/test/route', []); + $providers = $this->searchComposer->getProviders($this->user, '/test/route', []); $this->assertCount(2, $providers); $this->assertProvidersAreSortedByOrder($providers); @@ -187,7 +198,7 @@ public function testGetProvidersWithAllowedProvidersRestriction(): void { $this->setupRegistrationContextWithProviders($mockData['registrations']); $this->setupAppConfigForAllowedProviders(['provider1', 'provider3']); - $providers = $this->searchComposer->getProviders('/test/route', []); + $providers = $this->searchComposer->getProviders($this->user, '/test/route', []); $this->assertProvidersStructureAndSorting($providers, [ ['id' => 'provider1', 'name' => 'Provider provider1', 'appId' => 'app1', 'order' => 10, 'inAppSearch' => false], @@ -210,7 +221,7 @@ public function testGetProvidersFiltersByAllowedProvidersCompletely(): void { $this->setupRegistrationContextWithProviders($mockData['registrations']); $this->setupAppConfigForAllowedProviders(['provider_not_exists']); - $providers = $this->searchComposer->getProviders('/test/route', []); + $providers = $this->searchComposer->getProviders($this->user, '/test/route', []); $this->assertIsArray($providers); $this->assertEmpty($providers); @@ -227,7 +238,7 @@ public function testGetProvidersWithMixedOrderValues(): void { $this->setupRegistrationContextWithProviders($mockData['registrations']); $this->setupAppConfigForAllowedProviders(); - $providers = $this->searchComposer->getProviders('/test/route', []); + $providers = $this->searchComposer->getProviders($this->user, '/test/route', []); $this->assertCount(3, $providers); $this->assertProvidersAreSortedByOrder($providers); @@ -238,6 +249,43 @@ public function testGetProvidersWithMixedOrderValues(): void { $this->assertEquals('provider1', $providers[2]['id']); } + public function testGetProvidersHidesProvidersOfAppsNotEnabledForUser(): void { + $providerConfigs = [ + 'provider1' => ['service' => 'provider1_service', 'appId' => 'app1', 'order' => 10], + 'provider2' => ['service' => 'provider2_service', 'appId' => 'app2', 'order' => 5], + ]; + + $mockData = $this->createMockProvidersAndRegistrations($providerConfigs); + $this->setupRegistrationContextWithProviders($mockData['registrations']); + $this->setupAppConfigForAllowedProviders(); + $this->appsDisabledForUser = ['app2']; + + $mockData['providers']['provider2']->expects($this->never())->method('getOrder'); + + $providers = $this->searchComposer->getProviders($this->user, '/test/route', []); + + $this->assertSame(['provider1'], array_column($providers, 'id')); + } + + public function testSearchReturnsNoResultsForAppNotEnabledForUser(): void { + $providerConfigs = [ + 'provider1' => ['service' => 'provider1_service', 'appId' => 'app1', 'order' => 10], + ]; + + $mockData = $this->createMockProvidersAndRegistrations($providerConfigs); + $this->setupRegistrationContextWithProviders($mockData['registrations']); + $this->setupAppConfigForAllowedProviders(); + $this->appsDisabledForUser = ['app1']; + + $mockData['providers']['provider1']->expects($this->never())->method('search'); + + $result = $this->searchComposer->search($this->user, 'provider1', $this->createMock(ISearchQuery::class)); + + $this->assertSame([], $result->jsonSerialize()['entries']); + $this->assertFalse($result->jsonSerialize()['isPaginated']); + } + + public function testProviderIconGeneration(): void { $providerConfigs = [ 'provider1' => ['service' => 'provider1_service', 'appId' => 'app1', 'order' => 10], @@ -247,7 +295,7 @@ public function testProviderIconGeneration(): void { $this->setupRegistrationContextWithProviders($mockData['registrations']); $this->setupAppConfigForAllowedProviders(); - $providers = $this->searchComposer->getProviders('/test/route', []); + $providers = $this->searchComposer->getProviders($this->user, '/test/route', []); $this->assertCount(1, $providers); $this->assertArrayHasKey('icon', $providers[0]); From 95a0a295ed63bdec9f1f2745bfbf6fe64e9dd876 Mon Sep 17 00:00:00 2001 From: Benjamin Frueh Date: Sat, 7 Nov 2026 15:43:53 +0100 Subject: [PATCH 14/15] fix(AppFramework): only accept string format param in Request::getFormat() Assisted-by: ClaudeCode:claude-opus-5-5 Signed-off-by: Benjamin Frueh --- lib/private/AppFramework/Http/Request.php | 2 +- tests/lib/AppFramework/Http/RequestTest.php | 30 +++++++++++++++++++++ 2 files changed, 31 insertions(+), 1 deletion(-) diff --git a/lib/private/AppFramework/Http/Request.php b/lib/private/AppFramework/Http/Request.php index 58d6367b86e3b..40c4adb3c90c2 100644 --- a/lib/private/AppFramework/Http/Request.php +++ b/lib/private/AppFramework/Http/Request.php @@ -908,7 +908,7 @@ private function fromTrustedProxy(): bool { #[\Override] public function getFormat(): ?string { $format = $this->getParam('format'); - if ($format !== null) { + if (is_string($format)) { return $format; } diff --git a/tests/lib/AppFramework/Http/RequestTest.php b/tests/lib/AppFramework/Http/RequestTest.php index e031de6ed7672..2d5398453f652 100644 --- a/tests/lib/AppFramework/Http/RequestTest.php +++ b/tests/lib/AppFramework/Http/RequestTest.php @@ -2387,4 +2387,34 @@ public function testPassesCSRFCheckWithOCSAPIRequestHeader(): void { $this->assertTrue($request->passesCSRFCheck()); } + + public static function dataGetFormat(): array { + return [ + 'parameter' => [['format' => 'json'], '', 'json'], + 'parameter wins over header' => [['format' => 'xml'], 'application/json', 'xml'], + 'header' => [[], 'text/html, application/json', 'json'], + 'nothing' => [[], '', null], + 'array parameter is ignored' => [['format' => ['']], '', null], + 'array parameter falls back to header' => [['format' => ['xml']], 'application/json', 'json'], + ]; + } + + #[\PHPUnit\Framework\Attributes\DataProvider('dataGetFormat')] + public function testGetFormat(array $get, string $accept, ?string $expected): void { + $request = new Request( + [ + 'get' => $get, + 'method' => 'GET', + 'server' => [ + 'HTTP_ACCEPT' => $accept, + ], + ], + $this->requestId, + $this->config, + $this->csrfTokenManager, + $this->stream + ); + + $this->assertSame($expected, $request->getFormat()); + } } From 9c1f78a2fa1ac2112b123b7612cc0709733ed1b7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?C=C3=B4me=20Chilliet?= Date: Thu, 3 Dec 2026 15:41:22 +0100 Subject: [PATCH 15/15] fix: Fix duplicated command block in apps/testing info.xml MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Côme Chilliet --- apps/testing/appinfo/info.xml | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/apps/testing/appinfo/info.xml b/apps/testing/appinfo/info.xml index ab6d4b9ed9049..a3a3b037f7ae0 100644 --- a/apps/testing/appinfo/info.xml +++ b/apps/testing/appinfo/info.xml @@ -19,6 +19,7 @@ OCA\Testing\Command\ResetTokenLastCheck + OCA\Testing\Command\SetUnencryptedSize monitoring @@ -26,8 +27,4 @@ - - - OCA\Testing\Command\SetUnencryptedSize -