Skip to content

Commit 626eed5

Browse files
committed
fix(session): keep remembered logins across the session timeout
A session that was idle for longer than session_lifetime is ended with a full logout, which also deletes the remember-me cookies. The user is logged out for good, although they asked to stay logged in and the documentation of session_lifetime says a remembered login is transparently re-authenticated after the session expired. End such a session with endInactiveSession() instead: when the request carries valid remember-me cookies for the current session, only the session data is dropped. The session token is renewed for the new session, so the user stays logged in, and the remember-me cookies and the stored remember-me token get a fresh lifetime. The cookies must belong to the user of the session token. No user backend is set up yet when a session times out, so the session token tells whose session it is. Any other request keeps being logged out as before. In maintenance mode or with a pending upgrade, such a session only loses its data, and the remember-me cookies sign the user in again afterwards. The remember-me login is now only attempted with cookies that are strings, and loginWithCookie() requires strings. Clients can send the cookies as arrays, which ended in a TypeError for nc_username and nc_session_id. Assisted-by: ClaudeCode:claude-opus-5 Assisted-by: ClaudeCode:claude-opus-5-5 Signed-off-by: David Dreschner <david.dreschner@nextcloud.com>
1 parent ad4cf1a commit 626eed5

4 files changed

Lines changed: 367 additions & 21 deletions

File tree

‎lib/OC.php‎

Lines changed: 12 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -491,7 +491,12 @@ public static function initSession(): void {
491491
if (isset($_COOKIE[session_name()])) {
492492
setcookie(session_name(), '', -1, self::$WEBROOT ? : '/');
493493
}
494-
Server::get(IUserSession::class)->logout();
494+
if ((bool)Server::get(\OC\SystemConfig::class)->getValue('maintenance', false) || \OCP\Util::needUpgrade()) {
495+
// No database work yet: end the session, but keep the remember-me cookies for the next login
496+
$session->clear();
497+
} else {
498+
Server::get(\OC\User\Session::class)->endInactiveSession();
499+
}
495500
}
496501

497502
if (!self::hasSessionRelaxedExpiry()) {
@@ -1299,10 +1304,12 @@ public static function handleLogin(OCP\IRequest $request): bool {
12991304
if ($userSession->tryTokenLogin($request)) {
13001305
return true;
13011306
}
1302-
if (isset($_COOKIE['nc_username'])
1303-
&& isset($_COOKIE['nc_token'])
1304-
&& isset($_COOKIE['nc_session_id'])
1305-
&& $userSession->loginWithCookie($_COOKIE['nc_username'], $_COOKIE['nc_token'], $_COOKIE['nc_session_id'])) {
1307+
// From $_COOKIE, where an earlier logout or Apache auth in this request removes them. They can be arrays.
1308+
$username = $_COOKIE['nc_username'] ?? null;
1309+
$token = $_COOKIE['nc_token'] ?? null;
1310+
$sessionId = $_COOKIE['nc_session_id'] ?? null;
1311+
if (is_string($username) && is_string($token) && is_string($sessionId)
1312+
&& $userSession->loginWithCookie($username, $token, $sessionId)) {
13061313
return true;
13071314
}
13081315
if ($userSession->tryBasicAuthLogin($request, Server::get(IThrottler::class))) {

‎lib/private/User/Session.php‎

Lines changed: 96 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -900,22 +900,17 @@ public function tryTokenLogin(IRequest $request, bool $allowOcmAccessToken = fal
900900
* perform login using the magic cookie (remember login)
901901
*
902902
* @param string $uid the username
903-
* @param string $currentToken
904-
* @param string $oldSessionId
905903
* @return bool
906904
*/
907-
public function loginWithCookie($uid, $currentToken, $oldSessionId) {
905+
public function loginWithCookie(string $uid, string $currentToken, string $oldSessionId) {
908906
$this->dispatcher->dispatchTyped(new BeforeUserLoggedInWithCookieEvent($uid));
909907
$user = $this->manager->get($uid);
910908
if (is_null($user)) {
911909
// user does not exist
912910
return false;
913911
}
914912

915-
// get stored tokens
916-
$tokens = $this->config->getUserKeys($uid, 'login_token');
917-
// test cookies token against stored tokens
918-
if (!in_array($currentToken, $tokens, true)) {
913+
if (!$this->isStoredRememberMeToken($uid, $currentToken)) {
919914
$this->logger->info('Tried to log in but could not verify token', [
920915
'app' => 'core',
921916
'user' => $uid,
@@ -949,7 +944,7 @@ public function loginWithCookie($uid, $currentToken, $oldSessionId) {
949944
// replace successfully used token with a new one
950945
$this->config->deleteUserValue($uid, 'login_token', $currentToken);
951946
$newToken = $this->random->generate(32);
952-
$this->config->setUserValue($uid, 'login_token', $newToken, (string)$this->timeFactory->getTime());
947+
$this->storeRememberMeToken($uid, $newToken);
953948
$this->logger->debug('Remember-me token replaced', [
954949
'app' => 'core',
955950
'user' => $uid,
@@ -1001,7 +996,7 @@ public function loginWithCookie($uid, $currentToken, $oldSessionId) {
1001996
*/
1002997
public function createRememberMeToken(IUser $user) {
1003998
$token = $this->random->generate(32);
1004-
$this->config->setUserValue($user->getUID(), 'login_token', $token, (string)$this->timeFactory->getTime());
999+
$this->storeRememberMeToken($user->getUID(), $token);
10051000
$this->setMagicInCookie($user->getUID(), $token);
10061001
}
10071002

@@ -1033,6 +1028,71 @@ public function logout() {
10331028
$this->dispatcher->dispatchTyped(new UserLoggedOutEvent($user));
10341029
}
10351030

1031+
/**
1032+
* End a session inactive for longer than session_lifetime; a remembered login keeps its session token
1033+
*/
1034+
public function endInactiveSession(): void {
1035+
$cookies = $this->rememberedLoginCookies();
1036+
if ($cookies === null) {
1037+
$this->logout();
1038+
return;
1039+
}
1040+
1041+
$this->logger->debug('Ending inactive session, keeping the remembered login', [
1042+
'app' => 'core',
1043+
'user' => $cookies['username'],
1044+
]);
1045+
try {
1046+
$oldSessionId = $this->session->getId();
1047+
$this->setVolatileActiveUser(null);
1048+
$this->session->clear();
1049+
$this->tokenProvider->renewSessionToken($oldSessionId, $this->session->getId());
1050+
$this->storeRememberMeToken($cookies['username'], $cookies['token']);
1051+
$this->setMagicInCookie($cookies['username'], $cookies['token']);
1052+
} catch (InvalidTokenException|SessionNotAvailableException $e) {
1053+
// Without the session token the request continues as an anonymous one
1054+
$this->logger->info('Could not move the session token of the inactive session', [
1055+
'app' => 'core',
1056+
'user' => $cookies['username'],
1057+
'exception' => $e,
1058+
]);
1059+
}
1060+
}
1061+
1062+
/**
1063+
* The cookies of a request that proves a remembered login for the session token of the current session
1064+
*
1065+
* @return ?array{username: string, token: string}
1066+
*/
1067+
private function rememberedLoginCookies(): ?array {
1068+
if ($this->tokenProvider === null) {
1069+
return null;
1070+
}
1071+
try {
1072+
$sessionId = $this->session->getId();
1073+
} catch (SessionNotAvailableException) {
1074+
return null;
1075+
}
1076+
$cookies = $this->rememberMeCookiesFor($sessionId);
1077+
if ($cookies === null) {
1078+
return null;
1079+
}
1080+
1081+
try {
1082+
$token = $this->tokenProvider->getToken($sessionId);
1083+
} catch (InvalidTokenException) {
1084+
return null;
1085+
}
1086+
// No user backend is set up yet when a session times out, so the session token tells whose session it is
1087+
if ($token->getType() !== IToken::TEMPORARY_TOKEN
1088+
|| $token->getRemember() !== IToken::REMEMBER
1089+
|| $token->getUID() !== $cookies['username']
1090+
|| !$this->isStoredRememberMeToken($token->getUID(), $cookies['token'])) {
1091+
return null;
1092+
}
1093+
return $cookies;
1094+
}
1095+
10361096
/**
10371097
* Set cookie value to use in next page load
10381098
*
@@ -1089,14 +1149,37 @@ public function setMagicInCookie($username, $token) {
10891149
* login can still find the token that was renewed along with it.
10901150
*/
10911151
public function renewMagicSessionId(string $oldSessionId): void {
1152+
$cookies = $this->rememberMeCookiesFor($oldSessionId);
1153+
if ($cookies === null) {
1154+
return;
1155+
}
1156+
$this->setMagicInCookie($cookies['username'], $cookies['token']);
1157+
}
1158+
1159+
private function isStoredRememberMeToken(string $uid, string $token): bool {
1160+
return in_array($token, $this->config->getUserKeys($uid, 'login_token'), true);
1161+
}
1162+
1163+
/**
1164+
* Store the remember-me token with the current time, from which it expires
1165+
*/
1166+
private function storeRememberMeToken(string $uid, string $token): void {
1167+
$this->config->setUserValue($uid, 'login_token', $token, (string)$this->timeFactory->getTime());
1168+
}
1169+
1170+
/**
1171+
* The remember-me cookies of the request, if they point at the session $sessionId
1172+
*
1173+
* @return ?array{username: string, token: string}
1174+
*/
1175+
private function rememberMeCookiesFor(string $sessionId): ?array {
10921176
$request = Server::get(IRequest::class);
10931177
$username = $request->getCookie('nc_username');
10941178
$token = $request->getCookie('nc_token');
1095-
$sessionId = $request->getCookie('nc_session_id');
1096-
if ($username === null || $token === null || $sessionId !== $oldSessionId) {
1097-
return;
1179+
if (!is_string($username) || !is_string($token) || $request->getCookie('nc_session_id') !== $sessionId) {
1180+
return null;
10981181
}
1099-
$this->setMagicInCookie($username, $token);
1182+
return ['username' => $username, 'token' => $token];
11001183
}
11011184

11021185
/**

‎tests/lib/OCHandleLoginTest.php‎

Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
/**
6+
* SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors
7+
* SPDX-License-Identifier: AGPL-3.0-or-later
8+
*/
9+
10+
namespace Test;
11+
12+
use OC\User\Session;
13+
use OCP\IRequest;
14+
use OCP\Security\Bruteforce\IThrottler;
15+
use PHPUnit\Framework\Attributes\DataProvider;
16+
use PHPUnit\Framework\MockObject\MockObject;
17+
18+
/**
19+
* The remember-me cookie login of OC::handleLogin()
20+
*/
21+
class OCHandleLoginTest extends TestCase {
22+
private const COOKIES = ['nc_username' => 'foo', 'nc_token' => 'fooToken', 'nc_session_id' => 'sess123'];
23+
24+
private Session&MockObject $userSession;
25+
private IRequest&MockObject $request;
26+
private array $cookiesBefore;
27+
28+
#[\Override]
29+
protected function setUp(): void {
30+
parent::setUp();
31+
32+
$this->cookiesBefore = $_COOKIE;
33+
$this->userSession = $this->createMock(Session::class);
34+
$this->overwriteService(Session::class, $this->userSession);
35+
$this->overwriteService(IThrottler::class, $this->createMock(IThrottler::class));
36+
$this->request = $this->createMock(IRequest::class);
37+
// The cookies as the request came in
38+
$this->request->method('getCookie')->willReturnCallback(fn (string $name) => self::COOKIES[$name] ?? null);
39+
}
40+
41+
#[\Override]
42+
protected function tearDown(): void {
43+
$_COOKIE = $this->cookiesBefore;
44+
45+
parent::tearDown();
46+
}
47+
48+
public function testLoginWithRememberMeCookies(): void {
49+
$_COOKIE = self::COOKIES;
50+
51+
$this->userSession->expects($this->once())
52+
->method('loginWithCookie')
53+
->with('foo', 'fooToken', 'sess123')
54+
->willReturn(true);
55+
56+
$this->assertTrue(\OC::handleLogin($this->request));
57+
}
58+
59+
public static function noRememberMeLoginData(): array {
60+
return [
61+
'username cookie is an array' => ['cookies' => ['nc_username' => ['foo']] + self::COOKIES],
62+
'token cookie is an array' => ['cookies' => ['nc_token' => ['fooToken']] + self::COOKIES],
63+
'session id cookie is an array' => ['cookies' => ['nc_session_id' => ['sess123']] + self::COOKIES],
64+
'cookies removed by a logout or Apache auth earlier in the request' => ['cookies' => []],
65+
];
66+
}
67+
68+
#[DataProvider(methodName: 'noRememberMeLoginData')]
69+
public function testNoRememberMeLogin(array $cookies): void {
70+
$_COOKIE = $cookies;
71+
72+
$this->userSession->expects($this->never())
73+
->method('loginWithCookie');
74+
75+
$this->assertFalse(\OC::handleLogin($this->request));
76+
}
77+
}

0 commit comments

Comments
 (0)