From a990af9cc4208b53517258b377fb6e1cec23875a Mon Sep 17 00:00:00 2001 From: Peter Ringelmann Date: Tue, 1 Dec 2026 13:20:59 +0100 Subject: [PATCH 1/4] 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 | 5 +- .../UserDeletedTokenCleanupListener.php | 2 +- .../Authentication/Token/IProvider.php | 9 ++++ lib/private/Authentication/Token/Manager.php | 6 ++- .../Token/PublicKeyTokenMapper.php | 26 +++++++++ .../Token/PublicKeyTokenProvider.php | 4 ++ .../Authentication/Token/RemoteWipe.php | 5 +- .../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, 139 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 6e7d70ab729e3..cfba84a56f5fd 100644 --- a/apps/oauth2/tests/Service/ClientServiceTest.php +++ b/apps/oauth2/tests/Service/ClientServiceTest.php @@ -116,11 +116,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()) @@ -188,7 +188,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 b36aa717505fc..e99ec9be2f8ea 100644 --- a/core/Command/User/AuthTokens/ListCommand.php +++ b/core/Command/User/AuthTokens/ListCommand.php @@ -43,7 +43,10 @@ protected function execute(InputInterface $input, OutputInterface $output): int return 1; } - $tokens = $this->tokenProvider->getTokenByUser($user->getUID()); + $tokens = []; + foreach ($this->tokenProvider->getAllTokensByUser($user->getUID()) as $token) { + $tokens[] = $token; + } $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 3631c04432c89..07d8ee4dbf558 100644 --- a/lib/private/Authentication/Listeners/UserDeletedTokenCleanupListener.php +++ b/lib/private/Authentication/Listeners/UserDeletedTokenCleanupListener.php @@ -43,7 +43,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 04a24bc559e9f..f87d71b29da98 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 2fa0c5e6e1d49..990e6df46710c 100644 --- a/lib/private/Authentication/Token/Manager.php +++ b/lib/private/Authentication/Token/Manager.php @@ -110,6 +110,10 @@ public function getTokenByUser(string $uid): array { return $this->publicKeyTokenProvider->getTokenByUser($uid); } + public function getAllTokensByUser(string $uid): iterable { + return $this->publicKeyTokenProvider->getAllTokensByUser($uid); + } + /** * Get a token by token * @@ -238,7 +242,7 @@ public function updatePasswords(string $uid, string $password) { } 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 9aabd69e57a12..5754e3f5a994c 100644 --- a/lib/private/Authentication/Token/PublicKeyTokenMapper.php +++ b/lib/private/Authentication/Token/PublicKeyTokenMapper.php @@ -133,6 +133,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 ec46d401e2ce4..40b34aed5f191 100644 --- a/lib/private/Authentication/Token/PublicKeyTokenProvider.php +++ b/lib/private/Authentication/Token/PublicKeyTokenProvider.php @@ -356,6 +356,10 @@ public function getTokenByUser(string $uid): array { return $this->mapper->getTokenByUser($uid); } + public function getAllTokensByUser(string $uid): iterable { + return $this->mapper->getAllTokensByUser($uid); + } + public function getPassword(OCPIToken $savedToken, string $tokenId): string { if (!($savedToken instanceof PublicKeyToken)) { throw new InvalidTokenException('Invalid token type'); diff --git a/lib/private/Authentication/Token/RemoteWipe.php b/lib/private/Authentication/Token/RemoteWipe.php index 80ba330b66d80..df0658663b78a 100644 --- a/lib/private/Authentication/Token/RemoteWipe.php +++ b/lib/private/Authentication/Token/RemoteWipe.php @@ -59,7 +59,10 @@ 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 = []; + foreach ($this->tokenProvider->getAllTokensByUser($user->getUID()) as $token) { + $tokens[] = $token; + } /** @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 1861a5b2150e4..9912eb58c2bb4 100644 --- a/tests/lib/Authentication/Listeners/UserDeletedTokenCleanupListenerTest.php +++ b/tests/lib/Authentication/Listeners/UserDeletedTokenCleanupListenerTest.php @@ -44,7 +44,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); @@ -56,7 +56,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()) @@ -76,7 +76,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 8c238fb1587bc..8d4ac50dc71f9 100644 --- a/tests/lib/Authentication/Token/ManagerTest.php +++ b/tests/lib/Authentication/Token/ManagerTest.php @@ -256,6 +256,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') @@ -364,7 +376,7 @@ public function testInvalidateTokensOfUserNoClientName(): void { $this->publicKeyTokenProvider ->expects($this->once()) - ->method('getTokenByUser') + ->method('getAllTokensByUser') ->with('theUser') ->willReturn([$t1, $t2]); @@ -395,7 +407,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 e6c5296c21656..d1f5874f95cce 100644 --- a/tests/lib/Authentication/Token/PublicKeyTokenMapperTest.php +++ b/tests/lib/Authentication/Token/PublicKeyTokenMapperTest.php @@ -233,6 +233,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 1ea38bf208909..f683ea56271ef 100644 --- a/tests/lib/Authentication/Token/PublicKeyTokenProviderTest.php +++ b/tests/lib/Authentication/Token/PublicKeyTokenProviderTest.php @@ -219,6 +219,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 ca09767c75925..2d68084fadf3f 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 9950152dca38ecbd8236c61e484ab0ae32c21f83 Mon Sep 17 00:00:00 2001 From: Peter Ringelmann Date: Tue, 1 Dec 2026 13:01:12 +0100 Subject: [PATCH 2/4] 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 | 53 +++++++++++++++++++ 5 files changed, 63 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 b194674dfacb7..786a3d9b07488 100644 --- a/apps/oauth2/lib/Controller/OauthApiController.php +++ b/apps/oauth2/lib/Controller/OauthApiController.php @@ -26,7 +26,6 @@ use OCP\DB\Exception; use OCP\IDBConnection; use OCP\IRequest; -use OCP\Security\Bruteforce\IThrottler; use OCP\Security\ICrypto; use OCP\Security\ISecureRandom; use Psr\Log\LoggerInterface; @@ -46,7 +45,6 @@ public function __construct( private ISecureRandom $secureRandom, private ITimeFactory $time, private LoggerInterface $logger, - private IThrottler $throttler, private ITimeFactory $timeFactory, private IDBConnection $db, ) { @@ -226,8 +224,6 @@ public function getToken( throw $e; } - $this->throttler->resetDelay($this->request->getRemoteAddress(), 'login', ['user' => $appToken->getUID()]); - return new JSONResponse( [ 'access_token' => $newToken, diff --git a/apps/oauth2/tests/Controller/OauthApiControllerTest.php b/apps/oauth2/tests/Controller/OauthApiControllerTest.php index b528908de2cad..6eec8279985c1 100644 --- a/apps/oauth2/tests/Controller/OauthApiControllerTest.php +++ b/apps/oauth2/tests/Controller/OauthApiControllerTest.php @@ -22,7 +22,6 @@ use OCP\AppFramework\Utility\ITimeFactory; use OCP\IDBConnection; use OCP\IRequest; -use OCP\Security\Bruteforce\IThrottler; use OCP\Security\ICrypto; use OCP\Security\ISecureRandom; use Psr\Log\LoggerInterface; @@ -48,8 +47,6 @@ class OauthApiControllerTest extends TestCase { private $secureRandom; /** @var ITimeFactory|\PHPUnit\Framework\MockObject\MockObject */ private $time; - /** @var IThrottler|\PHPUnit\Framework\MockObject\MockObject */ - private $throttler; /** @var LoggerInterface|\PHPUnit\Framework\MockObject\MockObject */ private $logger; /** @var ITimeFactory|\PHPUnit\Framework\MockObject\MockObject */ @@ -69,7 +66,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); @@ -84,7 +80,6 @@ protected function setUp(): void { $this->secureRandom, $this->time, $this->logger, - $this->throttler, $this->timeFactory, $this->db, ); @@ -415,17 +410,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')); } @@ -528,17 +512,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)); } @@ -638,17 +611,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')); } @@ -731,9 +693,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')); } } diff --git a/lib/base.php b/lib/base.php index cb40eb3979e27..5b2400de02817 100644 --- a/lib/base.php +++ b/lib/base.php @@ -905,13 +905,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 574f6c80c3fae..13f70e6a7bd3b 100644 --- a/lib/private/Security/Bruteforce/Throttler.php +++ b/lib/private/Security/Bruteforce/Throttler.php @@ -31,9 +31,6 @@ * @package OC\Security\Bruteforce */ class Throttler implements IThrottler { - /** @var bool[] */ - private array $hasAttemptsDeleted = []; - public function __construct( private ITimeFactory $timeFactory, private LoggerInterface $logger, @@ -104,7 +101,7 @@ public function getAttempts(string $ip, string $action = '', float $maxAgeHours $maxAgeHours = 48; } - if ($ip === '' || isset($this->hasAttemptsDeleted[$action])) { + if ($ip === '') { return 0; } @@ -170,8 +167,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..aeaa14cceb9cb --- /dev/null +++ b/tests/lib/Security/Bruteforce/ThrottlerTest.php @@ -0,0 +1,53 @@ +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, + ); + + $throttler->resetDelay('10.10.10.10', 'login', ['user' => 'bob']); + $this->assertSame(11, $throttler->getAttempts('10.10.10.10', 'login')); + } +} From 910bee5978f42a0c73287b8c8ca7f2b9ae234e34 Mon Sep 17 00:00:00 2001 From: Benjamin Frueh Date: Sat, 7 Nov 2026 15:43:53 +0100 Subject: [PATCH 3/4] 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 82d567e928590..50d65f6d303da 100644 --- a/lib/private/AppFramework/Http/Request.php +++ b/lib/private/AppFramework/Http/Request.php @@ -882,7 +882,7 @@ private function fromTrustedProxy(): bool { 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 b03a7f4efe40d..1e43ac8bf9956 100644 --- a/tests/lib/AppFramework/Http/RequestTest.php +++ b/tests/lib/AppFramework/Http/RequestTest.php @@ -2321,4 +2321,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 e1b4a4098c6f41e612edd861f48016ceaaedc31b Mon Sep 17 00:00:00 2001 From: Peter Ringelmann Date: Wed, 2 Dec 2026 11:03:40 +0100 Subject: [PATCH 4/4] 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 e5edc165bf503..c6e360613a7dd 100644 --- a/core/Controller/AppPasswordController.php +++ b/core/Controller/AppPasswordController.php @@ -144,15 +144,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 f87d71b29da98..02a032627641e 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 40b34aed5f191..a6d970d1935be 100644 --- a/lib/private/Authentication/Token/PublicKeyTokenProvider.php +++ b/lib/private/Authentication/Token/PublicKeyTokenProvider.php @@ -167,7 +167,7 @@ public function getToken(string $tokenId): OCPIToken { } 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); @@ -406,14 +406,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 eb1566eca8be0..697abdee45e6d 100644 --- a/tests/Core/Controller/AppPasswordControllerTest.php +++ b/tests/Core/Controller/AppPasswordControllerTest.php @@ -246,4 +246,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 f683ea56271ef..014e017499c80 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; @@ -624,6 +626,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'); @@ -639,6 +644,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(); @@ -650,6 +658,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);