From c50f319e3d32d46afc5e582c2b2fa66152bcb49e Mon Sep 17 00:00:00 2001 From: Louis Chmn Date: Wed, 18 Nov 2026 13:34:01 +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 62af5debadbf9..016ed5092c4d5 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 { public function __construct( @@ -49,34 +48,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 aa904d0679970..831a6918537bb 100644 --- a/lib/private/User/Session.php +++ b/lib/private/User/Session.php @@ -25,6 +25,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\IConfig; @@ -653,11 +654,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 d2714cc1925ea..03984e8a89a6a 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 { @@ -62,43 +60,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 e00ad74c1dd04..a29474bd69a4b 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; @@ -1070,6 +1071,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);