Skip to content
Open
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
74 changes: 42 additions & 32 deletions lib/private/User/Session.php
Original file line number Diff line number Diff line change
Expand Up @@ -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();
}
Expand Down Expand Up @@ -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);
}
Expand Down Expand Up @@ -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);
Expand All @@ -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) {
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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) {
Expand All @@ -802,31 +810,31 @@ 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)) {
$this->logger->warning('Session token credentials are invalid', [
'app' => 'core',
'user' => $user,
]);
return false;
return null;
}

// Update token scope
$this->lockdownManager->setToken($dbToken);

$this->tokenProvider->updateTokenActivity($dbToken);

return true;
return $dbToken;
}

/**
Expand Down Expand Up @@ -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;
}
Expand Down
130 changes: 121 additions & 9 deletions tests/lib/User/SessionTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}


Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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())
Expand Down Expand Up @@ -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())
Expand All @@ -496,15 +532,15 @@ 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())
->method('getToken')
->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);

Expand All @@ -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);
Expand All @@ -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())
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -1515,15 +1627,15 @@ 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())
->method('getToken')
->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);

Expand Down Expand Up @@ -1562,15 +1674,15 @@ 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())
->method('getToken')
->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
Expand Down
Loading