Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 11 additions & 29 deletions lib/private/Authentication/Token/Manager.php
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down Expand Up @@ -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,
);
}

/**
Expand Down
30 changes: 25 additions & 5 deletions lib/private/User/Session.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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
Expand Down
39 changes: 0 additions & 39 deletions tests/lib/Authentication/Token/ManagerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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')
Expand Down
49 changes: 49 additions & 0 deletions tests/lib/User/SessionTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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);
Expand Down
Loading