From 57405873572e703c08ce783aafb6b1383c91db99 Mon Sep 17 00:00:00 2001 From: Ghassen kefi Date: Thu, 26 Nov 2026 11:45:28 +0100 Subject: [PATCH] fix(core): dispatch BeforeUserLoggedInEvent once per login Only the public login entry points dispatch the event, never the private helpers they share, so no login path can report the same attempt twice. Assisted-by: ClaudeCode:claude-opus-5-5 Signed-off-by: Ghassen kefi (cherry picked from commit 990ca06be950a3ea1d1ad465ecc2340c89bce0ee) --- lib/private/User/Session.php | 74 +++++++++++-------- tests/lib/User/SessionTest.php | 130 ++++++++++++++++++++++++++++++--- 2 files changed, 163 insertions(+), 41 deletions(-) diff --git a/lib/private/User/Session.php b/lib/private/User/Session.php index 51681692d8492..1bf48d4dbbd8d 100644 --- a/lib/private/User/Session.php +++ b/lib/private/User/Session.php @@ -223,7 +223,7 @@ protected function validateSession() { $token = $appPassword; } - if (!$this->validateToken($token, checkOwner: true)) { + if ($this->validateToken($token, checkOwner: true) === null) { // Session was invalidated $this->logout(); } @@ -317,9 +317,22 @@ protected function setToken($token) { * @throws LoginException */ public function login($uid, $password) { + $this->manager->emit('\OC\User', 'preLogin', [$uid, $password]); + return $this->loginWithCredentials($uid, $password); + } + + /** + * Log a user in with a login name and either a password or an app token + * + * Callers emit the preLogin hook themselves. + * + * @throws LoginException + */ + protected function loginWithCredentials(string $uid, string $password): bool { $this->session->regenerateId(); - if ($this->validateToken($password, $uid)) { - return $this->loginWithToken($password); + $dbToken = $this->validateToken($password, $uid); + if ($dbToken !== null) { + return $this->loginWithToken($dbToken, $this->getTokenLoginPassword($dbToken, $password)); } return $this->loginWithPassword($uid, $password); } @@ -424,7 +437,7 @@ public function logClientIn($user, } // Try to login with this username and password - if (!$this->login($user, $password)) { + if (!$this->loginWithCredentials($user, $password)) { // Failed, maybe the user used their email address if (!filter_var($user, FILTER_VALIDATE_EMAIL)) { $this->handleLoginFailed($throttler, $currentDelay, $remoteAddress, $user, $password); @@ -438,7 +451,7 @@ public function logClientIn($user, && $this->validateTokenLoginName($userFromToken->getEMailAddress(), $dbToken); } else { $users = $this->manager->getByEmail($user); - $isValidEmailLogin = (\count($users) === 1 && $this->login($users[0]->getUID(), $password)); + $isValidEmailLogin = (\count($users) === 1 && $this->loginWithCredentials($users[0]->getUID(), $password)); } if (!$isValidEmailLogin) { @@ -615,30 +628,25 @@ private function loginWithPassword($uid, $password) { } /** - * Log an user in with a given token (id) + * Decrypt the login password stored in a token * - * @param string $token - * @return boolean - * @throws LoginException if an app canceled the login process or the user is not enabled + * @return string the password, or an empty string for passwordless tokens */ - private function loginWithToken($token) { + private function getTokenLoginPassword(IToken $dbToken, string $token): string { try { - $dbToken = $this->tokenProvider->getToken($token); - } catch (InvalidTokenException $ex) { - return false; - } - $uid = $dbToken->getUID(); - - // When logging in with token, the password must be decrypted first before passing to login hook - $password = ''; - try { - $password = $this->tokenProvider->getPassword($dbToken, $token); + return $this->tokenProvider->getPassword($dbToken, $token); } catch (PasswordlessTokenException $ex) { - // Ignore and use empty string instead + return ''; } + } - $this->manager->emit('\OC\User', 'preLogin', [$dbToken->getLoginName(), $password]); - + /** + * Log an user in with a given token + * + * @throws LoginException if an app canceled the login process or the user is not enabled + */ + private function loginWithToken(IToken $dbToken, string $password) { + $uid = $dbToken->getUID(); $user = $this->manager->get($uid); if (is_null($user)) { // user does not exist @@ -791,9 +799,9 @@ private function checkTokenCredentials(IToken $dbToken, $token) { * @param string $token * @param string $user login name * @param bool $checkOwner Whether the token must belong to the session user - * @return boolean + * @return ?\OCP\Authentication\Token\IToken the token if it is valid, null otherwise */ - private function validateToken($token, $user = null, bool $checkOwner = false) { + private function validateToken($token, $user = null, bool $checkOwner = false): ?\OCP\Authentication\Token\IToken { try { $dbToken = $this->tokenProvider->getToken($token); } catch (InvalidTokenException $ex) { @@ -802,15 +810,15 @@ private function validateToken($token, $user = null, bool $checkOwner = false) { 'user' => $user, 'exception' => $ex, ]); - return false; + return null; } if (!is_null($user) && !$this->validateTokenLoginName($user, $dbToken)) { - return false; + return null; } if ($checkOwner && !$this->validateTokenOwner($dbToken)) { - return false; + return null; } if (!$this->checkTokenCredentials($dbToken, $token)) { @@ -818,7 +826,7 @@ private function validateToken($token, $user = null, bool $checkOwner = false) { 'app' => 'core', 'user' => $user, ]); - return false; + return null; } // Update token scope @@ -826,7 +834,7 @@ private function validateToken($token, $user = null, bool $checkOwner = false) { $this->tokenProvider->updateTokenActivity($dbToken); - return true; + return $dbToken; } /** @@ -911,11 +919,13 @@ public function tryTokenLogin(IRequest $request) { return false; } - if (!$this->loginWithToken($token)) { + $password = $this->getTokenLoginPassword($dbToken, $token); + $this->manager->emit('\OC\User', 'preLogin', [$dbToken->getLoginName(), $password]); + if (!$this->loginWithToken($dbToken, $password)) { $this->handleLoginFailed($throttler, $currentDelay, $remoteAddress, $dbToken->getUID(), $token); return false; } - if (!$this->validateToken($token)) { + if ($this->validateToken($token) === null) { $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 1832a9c1001c1..8d81812f874dd 100644 --- a/tests/lib/User/SessionTest.php +++ b/tests/lib/User/SessionTest.php @@ -223,8 +223,14 @@ public function testLoginValidPasswordEnabled(): void { }) ); + $preLoginCalls = []; + $manager->listen('\OC\User', 'preLogin', function (string $uid, string $password) use (&$preLoginCalls): void { + $preLoginCalls[] = [$uid, $password]; + }); + $userSession->login('foo', 'bar'); $this->assertEquals($user, $userSession->getUser()); + $this->assertSame([['foo', 'bar']], $preLoginCalls); } @@ -393,6 +399,36 @@ public function testLoginLastCheckUpdate(): void { $userSession->login('foo', 'app-password'); } + public function testLoginWithAppTokenFetchesTokenOnce(): void { + $session = $this->createMock(Memory::class); + $manager = $this->createMock(Manager::class); + $userSession = new Session($manager, $session, $this->timeFactory, $this->tokenProvider, $this->config, $this->random, $this->lockdownManager, $this->logger, $this->dispatcher); + + $user = $this->createMock(IUser::class); + $user->method('getUID')->willReturn('foo'); + $user->method('isEnabled')->willReturn(true); + $manager->method('get') + ->with('foo') + ->willReturn($user); + + $token = new PublicKeyToken(); + $token->setId(1); + $token->setLoginName('foo'); + $token->setLastCheck(0); + $token->setUid('foo'); + $this->tokenProvider->expects($this->once()) + ->method('getToken') + ->with('app-password') + ->willReturn($token); + $this->tokenProvider + ->method('getPassword') + ->with($token) + ->willThrowException(new PasswordlessTokenException()); + + $this->assertTrue($userSession->login('foo', 'app-password')); + $this->assertSame($user, $userSession->getUser()); + } + public function testLoginNonExisting(): void { $session = $this->createMock(Memory::class); $manager = $this->createMock(Manager::class); @@ -425,7 +461,7 @@ public function testLogClientInNoTokenPasswordWith2fa(): void { /** @var Session $userSession */ $userSession = $this->getMockBuilder(Session::class) ->setConstructorArgs([$manager, $session, $this->timeFactory, $this->tokenProvider, $this->config, $this->random, $this->lockdownManager, $this->logger, $this->dispatcher]) - ->onlyMethods(['login', 'supportsCookies', 'createSessionToken', 'getUser']) + ->onlyMethods(['loginWithCredentials', 'supportsCookies', 'createSessionToken', 'getUser']) ->getMock(); $this->tokenProvider->expects($this->once()) @@ -470,7 +506,7 @@ public function testLogClientInUnexist(): void { /** @var Session $userSession */ $userSession = $this->getMockBuilder(Session::class) ->setConstructorArgs([$manager, $session, $this->timeFactory, $this->tokenProvider, $this->config, $this->random, $this->lockdownManager, $this->logger, $this->dispatcher]) - ->onlyMethods(['login', 'supportsCookies', 'createSessionToken', 'getUser']) + ->onlyMethods(['loginWithCredentials', 'supportsCookies', 'createSessionToken', 'getUser']) ->getMock(); $this->tokenProvider->expects($this->once()) @@ -496,7 +532,7 @@ public function testLogClientInWithTokenPassword(): void { /** @var Session $userSession */ $userSession = $this->getMockBuilder(Session::class) ->setConstructorArgs([$manager, $session, $this->timeFactory, $this->tokenProvider, $this->config, $this->random, $this->lockdownManager, $this->logger, $this->dispatcher]) - ->onlyMethods(['login', 'supportsCookies', 'createSessionToken', 'getUser']) + ->onlyMethods(['loginWithCredentials', 'supportsCookies', 'createSessionToken', 'getUser']) ->getMock(); $this->tokenProvider->expects($this->once()) @@ -504,7 +540,7 @@ public function testLogClientInWithTokenPassword(): void { ->with('I-AM-AN-APP-PASSWORD') ->willReturn($this->createMock(IToken::class)); $userSession->expects($this->once()) - ->method('login') + ->method('loginWithCredentials') ->with('john', 'I-AM-AN-APP-PASSWORD') ->willReturn(true); @@ -528,6 +564,48 @@ public function testLogClientInWithTokenPassword(): void { $this->assertTrue($userSession->logClientIn('john', 'I-AM-AN-APP-PASSWORD', $request, $this->throttler)); } + public function testLogClientInWithTokenPasswordEmitsPreLoginOnce(): void { + $session = $this->createMock(ISession::class); + $request = $this->createMock(IRequest::class); + $request->method('getRemoteAddress')->willReturn('192.168.0.1'); + + $user = $this->createMock(IUser::class); + $user->method('getUID')->willReturn('john'); + $user->method('isEnabled')->willReturn(true); + $this->manager->method('get') + ->with('john') + ->willReturn($user); + + $token = new PublicKeyToken(); + $token->setId(1); + $token->setUid('john'); + $token->setLoginName('john'); + $token->setType(IToken::PERMANENT_TOKEN); + $token->setLastCheck(10000); + $this->tokenProvider->method('getToken') + ->with('I-AM-AN-APP-PASSWORD') + ->willReturn($token); + $this->tokenProvider->method('getPassword') + ->with($token, 'I-AM-AN-APP-PASSWORD') + ->willReturn('secret'); + + $userSession = $this->getMockBuilder(Session::class) + ->setConstructorArgs([$this->manager, $session, $this->timeFactory, $this->tokenProvider, $this->config, $this->random, $this->lockdownManager, $this->logger, $this->dispatcher]) + ->onlyMethods(['prepareUserLogin']) + ->getMock(); + + $preLoginCalls = []; + $this->manager->method('emit') + ->willReturnCallback(function (string $scope, string $method, array $arguments = []) use (&$preLoginCalls): void { + if ($method === 'preLogin') { + $preLoginCalls[] = $arguments; + } + }); + + $this->assertTrue($userSession->logClientIn('john', 'I-AM-AN-APP-PASSWORD', $request, $this->throttler)); + $this->assertSame([['john', 'I-AM-AN-APP-PASSWORD']], $preLoginCalls); + } + public function testLogClientInNoTokenPasswordNo2fa(): void { $this->expectException(PasswordLoginForbiddenException::class); @@ -539,7 +617,7 @@ public function testLogClientInNoTokenPasswordNo2fa(): void { /** @var Session $userSession */ $userSession = $this->getMockBuilder(Session::class) ->setConstructorArgs([$manager, $session, $this->timeFactory, $this->tokenProvider, $this->config, $this->random, $this->lockdownManager, $this->logger, $this->dispatcher]) - ->onlyMethods(['login', 'isTwoFactorEnforced']) + ->onlyMethods(['loginWithCredentials', 'isTwoFactorEnforced']) ->getMock(); $this->tokenProvider->expects($this->once()) @@ -671,6 +749,40 @@ public function testTryTokenLoginNotAnAppPassword(): void { self::assertTrue($loginResult); } + public function testTryTokenLoginEmitsPreLoginOnce(): void { + $request = $this->createMock(IRequest::class); + $request->method('getHeader')->with('Authorization')->willReturn('Bearer app-token'); + $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); + $this->tokenProvider->expects($this->once()) + ->method('getPassword') + ->with($dbToken, 'app-token') + ->willReturn('secret'); + $user = $this->createMock(IUser::class); + $user->method('isEnabled')->willReturn(true); + $this->manager->method('get') + ->with('alice') + ->willReturn($user); + + $preLoginCalls = []; + $this->manager->method('emit') + ->willReturnCallback(function (string $scope, string $method, array $arguments = []) use (&$preLoginCalls): void { + if ($method === 'preLogin') { + $preLoginCalls[] = $arguments; + } + }); + + $this->assertTrue($this->userSession->tryTokenLogin($request)); + $this->assertSame([['alice', 'secret']], $preLoginCalls); + } + public function testRememberLoginValidToken(): void { $session = $this->createMock(Memory::class); $managerMethods = get_class_methods(Manager::class); @@ -1515,7 +1627,7 @@ public function testLogClientInThrottlerUsername(): void { /** @var Session $userSession */ $userSession = $this->getMockBuilder(Session::class) ->setConstructorArgs([$manager, $session, $this->timeFactory, $this->tokenProvider, $this->config, $this->random, $this->lockdownManager, $this->logger, $this->dispatcher]) - ->onlyMethods(['login', 'supportsCookies', 'createSessionToken', 'getUser']) + ->onlyMethods(['loginWithCredentials', 'supportsCookies', 'createSessionToken', 'getUser']) ->getMock(); $this->tokenProvider->expects($this->once()) @@ -1523,7 +1635,7 @@ public function testLogClientInThrottlerUsername(): void { ->with('I-AM-A-PASSWORD') ->willReturn($this->createMock(IToken::class)); $userSession->expects($this->once()) - ->method('login') + ->method('loginWithCredentials') ->with('john', 'I-AM-A-PASSWORD') ->willReturn(false); @@ -1562,7 +1674,7 @@ public function testLogClientInThrottlerEmail(): void { /** @var Session $userSession */ $userSession = $this->getMockBuilder(Session::class) ->setConstructorArgs([$manager, $session, $this->timeFactory, $this->tokenProvider, $this->config, $this->random, $this->lockdownManager, $this->logger, $this->dispatcher]) - ->onlyMethods(['login', 'supportsCookies', 'createSessionToken', 'getUser']) + ->onlyMethods(['loginWithCredentials', 'supportsCookies', 'createSessionToken', 'getUser']) ->getMock(); $this->tokenProvider->expects($this->once()) @@ -1570,7 +1682,7 @@ public function testLogClientInThrottlerEmail(): void { ->with('I-AM-A-PASSWORD') ->willThrowException(new InvalidTokenException()); $userSession->expects($this->once()) - ->method('login') + ->method('loginWithCredentials') ->with('john@foo.bar', 'I-AM-A-PASSWORD') ->willReturn(false); $manager