From 7da7aee765a5f8dc66cae5231ffcc267f149eaa9 Mon Sep 17 00:00:00 2001 From: Louis Chmn Date: Wed, 18 Nov 2026 13:36:34 +0100 Subject: [PATCH] fix(session): handle session token conflicts outside of the transaction When two concurrent requests of the same session (e.g. with Apache/SSO based login) try to create the session token, one of them fails with a unique constraint violation. The recovery path then looked up the existing token, but it ran inside the transaction opened by createSessionToken(). On PostgreSQL the failed INSERT aborts the whole transaction, so the lookup failed with "SQLSTATE[25P02]: current transaction is aborted" and the request errored out. Move the conflict handling from Token\Manager to Session so that it runs after the transaction was rolled back. Assisted-by: ClaudeCode:claude-opus-5-5 Signed-off-by: Carl Schwan Signed-off-by: Louis Chmn --- lib/private/Authentication/Token/Manager.php | 40 +++++---------- lib/private/User/Session.php | 30 ++++++++++-- .../lib/Authentication/Token/ManagerTest.php | 39 --------------- tests/lib/User/SessionTest.php | 49 +++++++++++++++++++ 4 files changed, 85 insertions(+), 73 deletions(-) diff --git a/lib/private/Authentication/Token/Manager.php b/lib/private/Authentication/Token/Manager.php index 2fa0c5e6e1d49..da370a6421b08 100644 --- a/lib/private/Authentication/Token/Manager.php +++ b/lib/private/Authentication/Token/Manager.php @@ -14,7 +14,6 @@ use OCP\Authentication\Exceptions\WipeTokenException; use OCP\Authentication\Token\IProvider as OCPIProvider; use OCP\Authentication\Token\IToken as OCPIToken; -use OCP\DB\Exception; class Manager implements IProvider, OCPIProvider { /** @var PublicKeyTokenProvider */ @@ -50,34 +49,17 @@ public function generateToken(string $token, $name = mb_substr($name, 0, 120) . '…'; } - try { - return $this->publicKeyTokenProvider->generateToken( - $token, - $uid, - $loginName, - $password, - $name, - $type, - $remember, - $scope, - $expires, - ); - } catch (Exception $e) { - if ($e->getReason() !== Exception::REASON_UNIQUE_CONSTRAINT_VIOLATION) { - throw $e; - } - // It's rare, but if two requests of the same session (e.g. env-based SAML) - // try to create the session token they might end up here at the same time - // because we use the session ID as token and the db token is created anew - // with every request. - // - // If the UIDs match, then this should be fine. - $existing = $this->getToken($token); - if ($existing->getUID() !== $uid) { - throw new \Exception('Token conflict handled, but UIDs do not match. This should not happen', 0, $e); - } - return $existing; - } + return $this->publicKeyTokenProvider->generateToken( + $token, + $uid, + $loginName, + $password, + $name, + $type, + $remember, + $scope, + $expires, + ); } /** diff --git a/lib/private/User/Session.php b/lib/private/User/Session.php index eee520709d44a..736e4fce26e13 100644 --- a/lib/private/User/Session.php +++ b/lib/private/User/Session.php @@ -24,6 +24,7 @@ use OCP\AppFramework\Utility\ITimeFactory; use OCP\Authentication\Exceptions\ExpiredTokenException; use OCP\Authentication\Exceptions\InvalidTokenException; +use OCP\DB\Exception; use OCP\EventDispatcher\GenericEvent; use OCP\EventDispatcher\IEventDispatcher; use OCP\Files\NotPermittedException; @@ -659,11 +660,30 @@ public function createSessionToken( try { $sessionId = $this->session->getId(); $pwd = $this->getPassword($password); - // Make sure the current sessionId has no leftover tokens - $this->atomic(function () use ($sessionId, $uid, $loginName, $pwd, $name, $remember, $expires): void { - $this->tokenProvider->invalidateToken($sessionId); - $this->tokenProvider->generateToken($sessionId, $uid, $loginName, $pwd, $name, IToken::TEMPORARY_TOKEN, $remember, expires:$expires); - }, Server::get(IDBConnection::class)); + try { + // Make sure the current sessionId has no leftover tokens + $this->atomic(function () use ($sessionId, $uid, $loginName, $pwd, $name, $remember, $expires): void { + $this->tokenProvider->invalidateToken($sessionId); + $this->tokenProvider->generateToken($sessionId, $uid, $loginName, $pwd, $name, IToken::TEMPORARY_TOKEN, $remember, expires:$expires); + }, Server::get(IDBConnection::class)); + } catch (Exception $e) { + if ($e->getReason() !== Exception::REASON_UNIQUE_CONSTRAINT_VIOLATION) { + throw $e; + } + // It's rare, but if two requests of the same session (e.g. env-based SAML) + // try to create the session token they might end up here at the same time + // because we use the session ID as token and a new db token is created + // with every request. + // + // This has to happen after the transaction was rolled back, as PostgreSQL + // rejects any further query in a transaction that had an error. + // + // If the UIDs match, then this should be fine. + $existing = $this->tokenProvider->getToken($sessionId); + if ($existing->getUID() !== $uid) { + throw new \Exception('Token conflict handled, but UIDs do not match. This should not happen', 0, $e); + } + } return true; } catch (SessionNotAvailableException $ex) { // This can happen with OCC, where a memory session is used diff --git a/tests/lib/Authentication/Token/ManagerTest.php b/tests/lib/Authentication/Token/ManagerTest.php index 8c238fb1587bc..27ef046bd6d68 100644 --- a/tests/lib/Authentication/Token/ManagerTest.php +++ b/tests/lib/Authentication/Token/ManagerTest.php @@ -14,8 +14,6 @@ use OC\Authentication\Token\Manager; use OC\Authentication\Token\PublicKeyToken; use OC\Authentication\Token\PublicKeyTokenProvider; -use OCP\DB\Exception; -use PHPUnit\Framework\MockObject\MockObject; use Test\TestCase; class ManagerTest extends TestCase { @@ -61,43 +59,6 @@ public function testGenerateToken(): void { $this->assertSame($token, $actual); } - public function testGenerateConflictingToken(): void { - /** @var MockObject|Exception $exception */ - $exception = $this->createMock(Exception::class); - $exception->method('getReason')->willReturn(Exception::REASON_UNIQUE_CONSTRAINT_VIOLATION); - - $token = new PublicKeyToken(); - $token->setUid('uid'); - - $this->publicKeyTokenProvider->expects($this->once()) - ->method('generateToken') - ->with( - 'token', - 'uid', - 'loginName', - 'password', - 'name', - IToken::TEMPORARY_TOKEN, - IToken::REMEMBER - )->willThrowException($exception); - $this->publicKeyTokenProvider->expects($this->once()) - ->method('getToken') - ->with('token') - ->willReturn($token); - - $actual = $this->manager->generateToken( - 'token', - 'uid', - 'loginName', - 'password', - 'name', - IToken::TEMPORARY_TOKEN, - IToken::REMEMBER - ); - - $this->assertSame($token, $actual); - } - public function testGenerateTokenTooLongName(): void { $token = $this->createMock(IToken::class); $token->method('getName') diff --git a/tests/lib/User/SessionTest.php b/tests/lib/User/SessionTest.php index ffd39b2b7bd5a..a7d557ccbb099 100644 --- a/tests/lib/User/SessionTest.php +++ b/tests/lib/User/SessionTest.php @@ -24,6 +24,7 @@ use OC\User\User; use OCA\DAV\Connector\Sabre\Auth; use OCP\AppFramework\Utility\ITimeFactory; +use OCP\DB\Exception as DbException; use OCP\EventDispatcher\IEventDispatcher; use OCP\ICacheFactory; use OCP\IConfig; @@ -1068,6 +1069,54 @@ public function testCreateSessionToken(): void { $this->assertTrue($userSession->createSessionToken($request, $uid, $loginName, $password)); } + public static function dataCreateSessionTokenConflict(): array { + return [ + 'same user' => ['user123', true], + 'other user' => ['otheruser', false], + ]; + } + + #[\PHPUnit\Framework\Attributes\DataProvider(methodName: 'dataCreateSessionTokenConflict')] + public function testCreateSessionTokenConflict(string $existingUid, bool $expectSuccess): void { + $manager = $this->createMock(Manager::class); + $session = $this->createMock(ISession::class); + $user = $this->createMock(IUser::class); + $userSession = new Session($manager, $session, $this->timeFactory, $this->tokenProvider, $this->config, $this->random, $this->lockdownManager, $this->logger, $this->dispatcher); + + $request = new Request([ + 'server' => [ + 'HTTP_USER_AGENT' => 'Firefox', + ] + ], $this->createMock(IRequestId::class), $this->createMock(IConfig::class), $this->createMock(CsrfTokenManager::class)); + + $uid = 'user123'; + $sessionId = 'abcxyz'; + + $manager->method('get') + ->with($uid) + ->willReturn($user); + $session->method('getId') + ->willReturn($sessionId); + + $exception = $this->createMock(DbException::class); + $exception->method('getReason')->willReturn(DbException::REASON_UNIQUE_CONSTRAINT_VIOLATION); + $this->tokenProvider->expects($this->once()) + ->method('generateToken') + ->willThrowException($exception); + + $existing = new PublicKeyToken(); + $existing->setUid($existingUid); + $this->tokenProvider->expects($this->once()) + ->method('getToken') + ->with($sessionId) + ->willReturn($existing); + + if (!$expectSuccess) { + $this->expectExceptionMessage('Token conflict handled, but UIDs do not match'); + } + $this->assertTrue($userSession->createSessionToken($request, $uid, $uid)); + } + public function testCreateRememberedSessionToken(): void { $manager = $this->createMock(Manager::class); $session = $this->createMock(ISession::class);