diff --git a/apps/oauth2/lib/Controller/LoginRedirectorController.php b/apps/oauth2/lib/Controller/LoginRedirectorController.php
index b7089e16981ec..6b2f8f504dd76 100644
--- a/apps/oauth2/lib/Controller/LoginRedirectorController.php
+++ b/apps/oauth2/lib/Controller/LoginRedirectorController.php
@@ -83,7 +83,10 @@ public function authorize(
$providedRedirectUri = $redirect_uri;
}
- $this->session->set('oauth.state', $state);
+ $this->session->set('oauth.state', [
+ 'clientIdentifier' => $client->getClientIdentifier(),
+ 'state' => $state,
+ ]);
if (in_array($client->getName(), $this->appConfig->getValueArray('oauth2', 'skipAuthPickerApplications', []))) {
/** @see ClientFlowLoginController::showAuthPickerPage **/
diff --git a/apps/oauth2/lib/Controller/OauthApiController.php b/apps/oauth2/lib/Controller/OauthApiController.php
index 2b8d66403fa69..5c1feab9a69e7 100644
--- a/apps/oauth2/lib/Controller/OauthApiController.php
+++ b/apps/oauth2/lib/Controller/OauthApiController.php
@@ -31,7 +31,6 @@
use OCP\IRequest;
use OCP\IURLGenerator;
use OCP\IUserManager;
-use OCP\Security\Bruteforce\IThrottler;
use OCP\Security\ICrypto;
use OCP\Security\ISecureRandom;
use Psr\Container\ContainerExceptionInterface;
@@ -53,7 +52,6 @@ public function __construct(
private readonly ISecureRandom $secureRandom,
private readonly ITimeFactory $time,
private readonly LoggerInterface $logger,
- private readonly IThrottler $throttler,
private readonly ITimeFactory $timeFactory,
private readonly IDBConnection $db,
private readonly GlobalScaleConfig $globalScaleConfig,
@@ -238,8 +236,6 @@ public function getToken(
throw $e;
}
- $this->throttler->resetDelay($this->request->getRemoteAddress(), 'login', ['user' => $appToken->getUID()]);
-
$data = [
'access_token' => $newToken,
'token_type' => 'Bearer',
diff --git a/apps/oauth2/lib/Service/ClientService.php b/apps/oauth2/lib/Service/ClientService.php
index e47afa35bc8db..e0316853d250e 100644
--- a/apps/oauth2/lib/Service/ClientService.php
+++ b/apps/oauth2/lib/Service/ClientService.php
@@ -72,7 +72,7 @@ public function deleteClient(int $id): void {
$this->userManager->callForSeenUsers(function (IUser $user) use ($client): void {
// Skip tokens that are marked for remote wipe so revoking the
// OAuth2 client does not silently cancel a pending wipe.
- $tokens = $this->tokenProvider->getTokenByUser($user->getUID());
+ $tokens = $this->tokenProvider->getAllTokensByUser($user->getUID());
foreach ($tokens as $token) {
if ($token->getName() !== $client->getName()) {
continue;
diff --git a/apps/oauth2/tests/Controller/LoginRedirectorControllerTest.php b/apps/oauth2/tests/Controller/LoginRedirectorControllerTest.php
index 673c95ebcde9a..6e1d30892f549 100644
--- a/apps/oauth2/tests/Controller/LoginRedirectorControllerTest.php
+++ b/apps/oauth2/tests/Controller/LoginRedirectorControllerTest.php
@@ -72,7 +72,7 @@ public function testAuthorize(): void {
$this->session
->expects($this->once())
->method('set')
- ->with('oauth.state', 'MyState');
+ ->with('oauth.state', ['clientIdentifier' => 'MyClientIdentifier', 'state' => 'MyState']);
$this->urlGenerator
->expects($this->once())
->method('linkToRouteAbsolute')
@@ -106,9 +106,9 @@ public function testAuthorizeSkipPicker(): void {
$this->session
->expects(static::exactly(2))
->method('set')
- ->willReturnCallback(function (string $key, string $value): void {
+ ->willReturnCallback(function (string $key, string|array $value): void {
switch ([$key, $value]) {
- case ['oauth.state', 'MyState']:
+ case ['oauth.state', ['clientIdentifier' => 'MyClientIdentifier', 'state' => 'MyState']]:
case [ClientFlowLoginController::STATE_NAME, 'MyStateToken']:
/* Expected */
break;
@@ -177,7 +177,7 @@ public function testAuthorizeWithLegacyOcClient(): void {
$this->session
->expects($this->once())
->method('set')
- ->with('oauth.state', 'MyState');
+ ->with('oauth.state', ['clientIdentifier' => 'MyClientIdentifier', 'state' => 'MyState']);
$this->urlGenerator
->expects($this->once())
->method('linkToRouteAbsolute')
@@ -210,7 +210,7 @@ public function testAuthorizeNotForwardingUntrustedURIs(): void {
$this->session
->expects($this->once())
->method('set')
- ->with('oauth.state', 'MyState');
+ ->with('oauth.state', ['clientIdentifier' => 'MyClientIdentifier', 'state' => 'MyState']);
$this->urlGenerator
->expects($this->once())
->method('linkToRouteAbsolute')
diff --git a/apps/oauth2/tests/Controller/OauthApiControllerTest.php b/apps/oauth2/tests/Controller/OauthApiControllerTest.php
index 3e2c4266ed838..5be359ffde467 100644
--- a/apps/oauth2/tests/Controller/OauthApiControllerTest.php
+++ b/apps/oauth2/tests/Controller/OauthApiControllerTest.php
@@ -28,7 +28,6 @@
use OCP\IURLGenerator;
use OCP\IUser;
use OCP\IUserManager;
-use OCP\Security\Bruteforce\IThrottler;
use OCP\Security\ICrypto;
use OCP\Security\ISecureRandom;
use PHPUnit\Framework\MockObject\MockObject;
@@ -50,7 +49,6 @@ class OauthApiControllerTest extends TestCase {
private TokenProvider&MockObject $tokenProvider;
private ISecureRandom&MockObject $secureRandom;
private ITimeFactory&MockObject $time;
- private IThrottler&MockObject $throttler;
private LoggerInterface&MockObject $logger;
private ITimeFactory&MockObject $timeFactory;
private IDBConnection&MockObject $db;
@@ -70,7 +68,6 @@ protected function setUp(): void {
$this->tokenProvider = $this->createMock(TokenProvider::class);
$this->secureRandom = $this->createMock(ISecureRandom::class);
$this->time = $this->createMock(ITimeFactory::class);
- $this->throttler = $this->createMock(IThrottler::class);
$this->logger = $this->createMock(LoggerInterface::class);
$this->timeFactory = $this->createMock(ITimeFactory::class);
$this->db = $this->createMock(IDBConnection::class);
@@ -89,7 +86,6 @@ protected function setUp(): void {
$this->secureRandom,
$this->time,
$this->logger,
- $this->throttler,
$this->timeFactory,
$this->db,
$this->globalScaleConfig,
@@ -424,17 +420,6 @@ public function testRefreshTokenValidAppToken(): void {
'user_id' => 'userId',
]);
- $this->request->method('getRemoteAddress')
- ->willReturn('1.2.3.4');
-
- $this->throttler->expects($this->once())
- ->method('resetDelay')
- ->with(
- '1.2.3.4',
- 'login',
- ['user' => 'userId']
- );
-
$this->assertEquals($expected, $this->oauthApiController->getToken('refresh_token', null, 'validrefresh', 'clientId', 'clientSecret'));
}
@@ -537,17 +522,6 @@ public function testRefreshTokenValidAppTokenBasicAuth(): void {
$this->request->server['PHP_AUTH_USER'] = 'clientId';
$this->request->server['PHP_AUTH_PW'] = 'clientSecret';
- $this->request->method('getRemoteAddress')
- ->willReturn('1.2.3.4');
-
- $this->throttler->expects($this->once())
- ->method('resetDelay')
- ->with(
- '1.2.3.4',
- 'login',
- ['user' => 'userId']
- );
-
$this->assertEquals($expected, $this->oauthApiController->getToken('refresh_token', null, 'validrefresh', null, null));
}
@@ -647,17 +621,6 @@ public function testRefreshTokenExpiredAppToken(): void {
'user_id' => 'userId',
]);
- $this->request->method('getRemoteAddress')
- ->willReturn('1.2.3.4');
-
- $this->throttler->expects($this->once())
- ->method('resetDelay')
- ->with(
- '1.2.3.4',
- 'login',
- ['user' => 'userId']
- );
-
$this->assertEquals($expected, $this->oauthApiController->getToken('refresh_token', null, 'validrefresh', 'clientId', 'clientSecret'));
}
@@ -740,9 +703,6 @@ public function testRefreshTokenRedeemedConcurrently(): void {
false,
)->willReturn(0);
- $this->throttler->expects($this->never())
- ->method('resetDelay');
-
$this->assertEquals($expected, $this->oauthApiController->getToken('refresh_token', null, 'validrefresh', 'clientId', 'clientSecret'));
}
@@ -796,7 +756,6 @@ private function arrangeSuccessfulTokenExchange(): PublicKeyToken {
});
$this->time->method('getTime')->willReturn(1000);
$this->accessTokenMapper->method('rotateToken')->willReturn(1);
- $this->request->method('getRemoteAddress')->willReturn('1.2.3.4');
return $appToken;
}
diff --git a/apps/oauth2/tests/Service/ClientServiceTest.php b/apps/oauth2/tests/Service/ClientServiceTest.php
index bc9986e0b21f9..e762de6b7dd7a 100644
--- a/apps/oauth2/tests/Service/ClientServiceTest.php
+++ b/apps/oauth2/tests/Service/ClientServiceTest.php
@@ -114,11 +114,11 @@ public function testDeleteClient(): void {
$user1->updateLastLoginTimestamp();
$tokenProviderMock = $this->getMockBuilder(IAuthTokenProvider::class)->getMock();
- // One getTokenByUser call per user; we return no matching tokens here
+ // One getAllTokensByUser call per user; we return no matching tokens here
// so invalidateTokenById is never invoked.
$tokenProviderMock
->expects($this->exactly($count + 1))
- ->method('getTokenByUser')
+ ->method('getAllTokensByUser')
->willReturn([]);
$tokenProviderMock
->expects($this->never())
@@ -186,7 +186,7 @@ public function testDeleteClientPreservesWipePendingToken(): void {
$otherToken->method('getName')->willReturn('Some Other Client');
$this->authTokenProvider
- ->method('getTokenByUser')
+ ->method('getAllTokensByUser')
->willReturnCallback(function (string $uid) use ($wipeToken, $regularToken, $otherToken) {
return $uid === 'test_wipe_preserve'
? [$wipeToken, $regularToken, $otherToken]
diff --git a/apps/settings/lib/Controller/WebAuthnController.php b/apps/settings/lib/Controller/WebAuthnController.php
index 495b58e6a4bd3..4f5a8173855b8 100644
--- a/apps/settings/lib/Controller/WebAuthnController.php
+++ b/apps/settings/lib/Controller/WebAuthnController.php
@@ -48,6 +48,10 @@ public function __construct(
public function startRegistration(): JSONResponse {
$this->logger->debug('Starting WebAuthn registration');
+ if (!$this->manager->isWebAuthnAvailable()) {
+ return new JSONResponse([], Http::STATUS_FORBIDDEN);
+ }
+
$credentialOptions = $this->manager->startRegistration($this->userSession->getUser(), $this->request->getServerHost());
// Set this in the session since we need it on finish
@@ -65,6 +69,10 @@ public function startRegistration(): JSONResponse {
public function finishRegistration(string $name, string $data): JSONResponse {
$this->logger->debug('Finishing WebAuthn registration');
+ if (!$this->manager->isWebAuthnAvailable()) {
+ return new JSONResponse([], Http::STATUS_FORBIDDEN);
+ }
+
if (!$this->session->exists(self::WEBAUTHN_REGISTRATION)) {
$this->logger->debug('Trying to finish WebAuthn registration without session data');
return new JSONResponse([], Http::STATUS_BAD_REQUEST);
diff --git a/apps/settings/tests/Controller/WebAuthnControllerTest.php b/apps/settings/tests/Controller/WebAuthnControllerTest.php
new file mode 100644
index 0000000000000..27bda10b6cb56
--- /dev/null
+++ b/apps/settings/tests/Controller/WebAuthnControllerTest.php
@@ -0,0 +1,68 @@
+manager = $this->createMock(Manager::class);
+ $this->manager->method('isWebAuthnAvailable')->willReturn(false);
+ $this->userSession = $this->createMock(IUserSession::class);
+ $this->session = $this->createMock(ISession::class);
+ $this->controller = new WebAuthnController(
+ $this->createMock(IRequest::class),
+ $this->createMock(LoggerInterface::class),
+ $this->manager,
+ $this->userSession,
+ $this->session,
+ );
+ }
+
+ public function testStartRegistrationRefusedWhenDisabled(): void {
+ $this->manager->expects($this->never())->method('startRegistration');
+
+ $response = $this->controller->startRegistration();
+
+ $this->assertSame(Http::STATUS_FORBIDDEN, $response->getStatus());
+ }
+
+ public function testFinishRegistrationRefusedWhenDisabled(): void {
+ $this->session->method('exists')->willReturn(true);
+ $this->manager->expects($this->never())->method('finishRegister');
+
+ $response = $this->controller->finishRegistration('My key', '{}');
+
+ $this->assertSame(Http::STATUS_FORBIDDEN, $response->getStatus());
+ }
+
+ public function testDeleteRegistrationAllowedWhenDisabled(): void {
+ $this->userSession->method('getUser')->willReturn($this->createMock(IUser::class));
+ $this->manager->expects($this->once())->method('deleteRegistration');
+
+ $this->controller->deleteRegistration(17);
+ }
+}
diff --git a/apps/testing/appinfo/info.xml b/apps/testing/appinfo/info.xml
index 98d5c07408b73..a3db0abb61467 100644
--- a/apps/testing/appinfo/info.xml
+++ b/apps/testing/appinfo/info.xml
@@ -16,13 +16,15 @@
+
+
+ OCA\Testing\Command\ResetTokenLastCheck
+ OCA\Testing\Command\SetUnencryptedSize
+
+
monitoring
https://github.com/nextcloud/server/issues
-
-
- OCA\Testing\Command\SetUnencryptedSize
-
diff --git a/apps/testing/composer/composer/autoload_classmap.php b/apps/testing/composer/composer/autoload_classmap.php
index 72aead2903a76..7f4eeccb3a16c 100644
--- a/apps/testing/composer/composer/autoload_classmap.php
+++ b/apps/testing/composer/composer/autoload_classmap.php
@@ -9,6 +9,7 @@
'Composer\\InstalledVersions' => $vendorDir . '/composer/InstalledVersions.php',
'OCA\\Testing\\AlternativeHomeUserBackend' => $baseDir . '/../lib/AlternativeHomeUserBackend.php',
'OCA\\Testing\\AppInfo\\Application' => $baseDir . '/../lib/AppInfo/Application.php',
+ 'OCA\\Testing\\Command\\ResetTokenLastCheck' => $baseDir . '/../lib/Command/ResetTokenLastCheck.php',
'OCA\\Testing\\Command\\SetUnencryptedSize' => $baseDir . '/../lib/Command/SetUnencryptedSize.php',
'OCA\\Testing\\Controller\\ConfigController' => $baseDir . '/../lib/Controller/ConfigController.php',
'OCA\\Testing\\Controller\\LockingController' => $baseDir . '/../lib/Controller/LockingController.php',
diff --git a/apps/testing/composer/composer/autoload_static.php b/apps/testing/composer/composer/autoload_static.php
index f1981b29fc713..07127c16803ed 100644
--- a/apps/testing/composer/composer/autoload_static.php
+++ b/apps/testing/composer/composer/autoload_static.php
@@ -24,6 +24,7 @@ class ComposerStaticInitTesting
'Composer\\InstalledVersions' => __DIR__ . '/..' . '/composer/InstalledVersions.php',
'OCA\\Testing\\AlternativeHomeUserBackend' => __DIR__ . '/..' . '/../lib/AlternativeHomeUserBackend.php',
'OCA\\Testing\\AppInfo\\Application' => __DIR__ . '/..' . '/../lib/AppInfo/Application.php',
+ 'OCA\\Testing\\Command\\ResetTokenLastCheck' => __DIR__ . '/..' . '/../lib/Command/ResetTokenLastCheck.php',
'OCA\\Testing\\Command\\SetUnencryptedSize' => __DIR__ . '/..' . '/../lib/Command/SetUnencryptedSize.php',
'OCA\\Testing\\Controller\\ConfigController' => __DIR__ . '/..' . '/../lib/Controller/ConfigController.php',
'OCA\\Testing\\Controller\\LockingController' => __DIR__ . '/..' . '/../lib/Controller/LockingController.php',
diff --git a/apps/testing/lib/Command/ResetTokenLastCheck.php b/apps/testing/lib/Command/ResetTokenLastCheck.php
new file mode 100644
index 0000000000000..191311c8f20dc
--- /dev/null
+++ b/apps/testing/lib/Command/ResetTokenLastCheck.php
@@ -0,0 +1,47 @@
+setName('testing:reset-token-last-check')
+ ->setDescription('Make the credential check of all auth tokens of a user due')
+ ->addArgument('user', InputArgument::REQUIRED, 'Owner of the tokens');
+ }
+
+ #[\Override]
+ protected function execute(InputInterface $input, OutputInterface $output): int {
+ $qb = $this->db->getQueryBuilder();
+ $qb->update('authtoken')
+ ->set('last_check', $qb->createNamedParameter(0))
+ ->where($qb->expr()->eq('uid', $qb->createNamedParameter($input->getArgument('user'))))
+ ->executeStatement();
+
+ return self::SUCCESS;
+ }
+}
diff --git a/build/integration/features/auth.feature b/build/integration/features/auth.feature
index 4601221c808a9..686cb0dcda32e 100644
--- a/build/integration/features/auth.feature
+++ b/build/integration/features/auth.feature
@@ -98,6 +98,51 @@ Feature: auth
And requesting "/index.php/apps/files" with "GET" using browser session
Then the HTTP status code should be "200"
+ Scenario: a remembered login ends when the password is changed on another device
+ Given a local memory cache is configured
+ And a new remembered browser session is started
+ And requesting "/ocs/v2.php/cloud/user" with "GET" using browser session
+ And the HTTP status code should be "200"
+ And the browser session is stored as "phone"
+ And a new browser session is started
+ When the password is changed from "123456" to "654321-new" using browser session
+ And the browser session "phone" is restored
+ And the session cookie expires
+ And requesting "/ocs/v2.php/cloud/user" with "GET" using browser session
+ Then the HTTP status code should be "401"
+
+ # PASSWORD CHANGE BY AN ADMIN
+ Scenario: a browser session ends at its credential check after the admin changed the password
+ Given a new browser session is started
+ And the browser session is stored as "old"
+ And As an "admin"
+ And sending "PUT" to "/cloud/users/user0" with
+ | key | password |
+ | value | 654321-new |
+ And the HTTP status code should be "200"
+ And the credential check of the tokens of "user0" is due
+ When the browser session "old" is restored
+ And requesting "/ocs/v2.php/cloud/user" with "GET" using browser session
+ Then the HTTP status code should be "401"
+
+ Scenario: a browser session opened with the previous password ends although the owner logged in with the new one
+ Given a new browser session is started
+ And requesting "/ocs/v2.php/cloud/user" with "GET" using browser session
+ And the HTTP status code should be "200"
+ And the browser session is stored as "old"
+ And As an "admin"
+ And sending "PUT" to "/cloud/users/user0" with
+ | key | password |
+ | value | 654321-new |
+ And the HTTP status code should be "200"
+ And a new browser session is started with password "654321-new"
+ And requesting "/ocs/v2.php/cloud/user" with "GET" using browser session
+ And the HTTP status code should be "200"
+ And the credential check of the tokens of "user0" is due
+ When the browser session "old" is restored
+ And requesting "/ocs/v2.php/cloud/user" with "GET" using browser session
+ Then the HTTP status code should be "401"
+
# AUTH TOKENS
Scenario: Creating an auth token with regular auth token should not work
When requesting "/index.php/apps/files" with "GET" using restricted basic token auth
diff --git a/build/integration/features/bootstrap/Auth.php b/build/integration/features/bootstrap/Auth.php
index 982c14a2ccbde..520cf78a8e0b7 100644
--- a/build/integration/features/bootstrap/Auth.php
+++ b/build/integration/features/bootstrap/Auth.php
@@ -5,10 +5,12 @@
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
+
use GuzzleHttp\Client;
use GuzzleHttp\Cookie\CookieJar;
use GuzzleHttp\Exception\ClientException;
use GuzzleHttp\Exception\ServerException;
+use PHPUnit\Framework\Assert;
require __DIR__ . '/autoload.php';
@@ -21,12 +23,25 @@ trait Auth {
private $client;
/** @var string */
private $responseXml;
+ /** @var array */
+ private array $storedBrowserSessions = [];
+ /** @var list> system config keys to delete after the scenario */
+ private array $systemConfigToDelete = [];
/** @BeforeScenario */
public function setUpScenario() {
$this->client = new Client();
$this->responseXml = '';
$this->cookieJar = new CookieJar();
+ $this->storedBrowserSessions = [];
+ }
+
+ /** @AfterScenario */
+ public function deleteSystemConfigOfScenario(): void {
+ foreach (array_reverse($this->systemConfigToDelete) as $keys) {
+ $this->runOcc(['config:system:delete', ...$keys]);
+ }
+ $this->systemConfigToDelete = [];
}
/**
@@ -202,10 +217,9 @@ public function requestingWithBrowserSession($url, $method) {
/**
* @Given a new browser session is started
- *
* @param bool $remember
*/
- public function aNewBrowserSessionIsStarted($remember = false) {
+ public function aNewBrowserSessionIsStarted($remember = false, string $password = '123456') {
$baseUrl = substr($this->baseUrl, 0, -5);
$loginUrl = $baseUrl . '/login';
// Request a new session and extract CSRF token
@@ -221,7 +235,7 @@ public function aNewBrowserSessionIsStarted($remember = false) {
$loginUrl, [
'form_params' => [
'user' => 'user0',
- 'password' => '123456',
+ 'password' => $password,
'rememberme' => $remember ? '1' : '0',
'requesttoken' => $this->requestToken,
],
@@ -234,6 +248,13 @@ public function aNewBrowserSessionIsStarted($remember = false) {
$this->extracRequestTokenFromResponse($response);
}
+ /**
+ * @Given a new browser session is started with password :password
+ */
+ public function aNewBrowserSessionIsStartedWithPassword(string $password): void {
+ $this->aNewBrowserSessionIsStarted(false, $password);
+ }
+
/**
* @Given a new remembered browser session is started
*/
@@ -241,7 +262,6 @@ public function aNewRememberedBrowserSessionIsStarted() {
$this->aNewBrowserSessionIsStarted(true);
}
-
/**
* @Given the cookie jar is reset
*/
@@ -255,4 +275,79 @@ public function theCookieJarIsReset() {
public function whenTheSessionCookieExpires() {
$this->cookieJar->clearSessionCookies();
}
+
+ /**
+ * @Given the browser session is stored as :name
+ */
+ public function theBrowserSessionIsStoredAs(string $name): void {
+ $this->storedBrowserSessions[$name] = [$this->cookieJar, $this->requestToken];
+ $this->cookieJar = new CookieJar();
+ $this->requestToken = null;
+ }
+
+ /**
+ * @Given the browser session :name is restored
+ */
+ public function theBrowserSessionIsRestored(string $name): void {
+ [$this->cookieJar, $this->requestToken] = $this->storedBrowserSessions[$name];
+ }
+
+ /**
+ * Configures memcache.local unless one is configured already: APCu when
+ * the PHP extension is loaded, otherwise Redis on localhost
+ */
+ /**
+ * @Given a local memory cache is configured
+ */
+ public function aLocalMemoryCacheIsConfigured(): void {
+ $this->runOcc(['config:system:get', 'memcache.local']);
+ if (trim($this->lastStdOut) !== '') {
+ return;
+ }
+
+ if (extension_loaded('apcu')) {
+ $this->runOcc(['config:system:set', 'memcache.local', '--value', '\\OC\\Memcache\\APCu']);
+ } else {
+ Assert::assertTrue(extension_loaded('redis'), 'Neither APCu nor Redis is available');
+ $this->runOcc(['config:system:set', 'redis', 'host', '--value', 'localhost']);
+ $this->runOcc(['config:system:set', 'redis', 'port', '--value', '6379', '--type', 'integer']);
+ $this->systemConfigToDelete[] = ['redis'];
+ $this->runOcc(['config:system:set', 'memcache.local', '--value', '\\OC\\Memcache\\Redis']);
+ }
+ Assert::assertSame(0, $this->lastCode, $this->lastStdErr);
+ $this->systemConfigToDelete[] = ['memcache.local'];
+ }
+
+ /**
+ * @When the password is changed from :oldPassword to :newPassword using browser session
+ */
+ public function thePasswordIsChangedUsingBrowserSession(string $oldPassword, string $newPassword): void {
+ $fullUrl = substr($this->baseUrl, 0, -5) . '/index.php/settings/personal/changepassword';
+ $this->response = $this->client->post($fullUrl, [
+ 'form_params' => [
+ 'oldpassword' => $oldPassword,
+ 'newpassword' => $newPassword,
+ ],
+ 'headers' => [
+ 'requesttoken' => $this->requestToken,
+ ],
+ 'cookies' => $this->cookieJar,
+ ]);
+ $body = json_decode($this->response->getBody()->getContents(), true);
+ Assert::assertSame('success', $body['status'] ?? null);
+ }
+
+ /**
+ * The next request with any auth token of the user checks the stored password again
+ */
+ /**
+ * @Given the credential check of the tokens of :user is due
+ */
+ public function theCredentialCheckOfTheTokensOfIsDue(string $user): void {
+ $this->runOcc(['testing:reset-token-last-check', $user]);
+ Assert::assertSame(0, $this->lastCode, $this->lastStdErr);
+ if (extension_loaded('apcu')) {
+ $this->client->get(substr($this->baseUrl, 0, -5) . '/apps/testing/clean_apcu_cache.php');
+ }
+ }
}
diff --git a/core/Command/User/AuthTokens/ListCommand.php b/core/Command/User/AuthTokens/ListCommand.php
index b36aa717505fc..e99ec9be2f8ea 100644
--- a/core/Command/User/AuthTokens/ListCommand.php
+++ b/core/Command/User/AuthTokens/ListCommand.php
@@ -43,7 +43,10 @@ protected function execute(InputInterface $input, OutputInterface $output): int
return 1;
}
- $tokens = $this->tokenProvider->getTokenByUser($user->getUID());
+ $tokens = [];
+ foreach ($this->tokenProvider->getAllTokensByUser($user->getUID()) as $token) {
+ $tokens[] = $token;
+ }
$tokens = array_map(function (IToken $token) use ($input): mixed {
$sensitive = [
diff --git a/core/Controller/AppPasswordController.php b/core/Controller/AppPasswordController.php
index 9b015a1dd5d1a..7d20de8951ab5 100644
--- a/core/Controller/AppPasswordController.php
+++ b/core/Controller/AppPasswordController.php
@@ -153,15 +153,15 @@ public function rotateAppPassword(): DataResponse {
$appPassword = $this->session->get('app_password');
+ $newToken = $this->random->generate(72, ISecureRandom::CHAR_UPPER . ISecureRandom::CHAR_LOWER . ISecureRandom::CHAR_DIGITS);
+
try {
$token = $this->tokenProvider->getToken($appPassword);
+ $this->tokenProvider->rotate($token, $appPassword, $newToken);
} catch (InvalidTokenException $e) {
throw new OCSForbiddenException('could not rotate apptoken');
}
- $newToken = $this->random->generate(72, ISecureRandom::CHAR_UPPER . ISecureRandom::CHAR_LOWER . ISecureRandom::CHAR_DIGITS);
- $this->tokenProvider->rotate($token, $appPassword, $newToken);
-
return new DataResponse([
'apppassword' => $newToken,
]);
diff --git a/core/Controller/ClientFlowLoginController.php b/core/Controller/ClientFlowLoginController.php
index 0e83ef283a9ff..f2714ccb4abd4 100644
--- a/core/Controller/ClientFlowLoginController.php
+++ b/core/Controller/ClientFlowLoginController.php
@@ -67,6 +67,17 @@ public function __construct(
parent::__construct($appName, $request);
}
+ /**
+ * The state the OAuth client passed to the authorize endpoint, if that client is the one being granted
+ */
+ private function getOAuthState(string $clientIdentifier): ?string {
+ $stored = $this->session->get('oauth.state');
+ if (!is_array($stored) || ($stored['clientIdentifier'] ?? null) !== $clientIdentifier) {
+ return null;
+ }
+ return $stored['state'];
+ }
+
private function getClientName(): string {
$userAgent = $this->request->getHeader('user-agent');
return $userAgent !== '' ? $userAgent : 'unknown';
@@ -129,6 +140,7 @@ public function showAuthPickerPage(string $clientIdentifier = '', string $user =
ISecureRandom::CHAR_LOWER . ISecureRandom::CHAR_UPPER . ISecureRandom::CHAR_DIGITS
);
$this->session->set(self::STATE_NAME, $stateToken);
+ $oauthState = $this->getOAuthState($clientIdentifier);
$csp = new ContentSecurityPolicy();
if ($client) {
@@ -144,7 +156,7 @@ public function showAuthPickerPage(string $clientIdentifier = '', string $user =
'instanceName' => $this->defaults->getName(),
'stateToken' => $stateToken,
'serverHost' => $this->getServerPath(),
- 'oauthState' => $this->session->get('oauth.state'),
+ 'oauthState' => $oauthState,
'direct' => (bool)$direct,
'providedRedirectUri' => $providedRedirectUri,
'loginRedirectUrl' => $this->urlGenerator->linkToRoute(
@@ -152,7 +164,7 @@ public function showAuthPickerPage(string $clientIdentifier = '', string $user =
[
'stateToken' => $stateToken,
'clientIdentifier' => $clientIdentifier,
- 'oauthState' => $this->session->get('oauth.state'),
+ 'oauthState' => $oauthState,
'user' => $user,
'direct' => $direct,
'providedRedirectUri' => $providedRedirectUri,
@@ -215,7 +227,7 @@ public function grantPage(
'instanceName' => $this->defaults->getName(),
'stateToken' => $stateToken,
'serverHost' => $this->getServerPath(),
- 'oauthState' => $this->session->get('oauth.state'),
+ 'oauthState' => $this->getOAuthState($clientIdentifier),
'direct' => $direct,
'providedRedirectUri' => $providedRedirectUri,
'userDisplayName' => $user->getDisplayName(),
@@ -322,7 +334,7 @@ public function generateAppPassword(
$redirectUri .= sprintf(
'state=%s&code=%s',
- urlencode($this->session->get('oauth.state')),
+ urlencode($this->getOAuthState($clientIdentifier) ?? ''),
urlencode($code)
);
$this->session->remove('oauth.state');
diff --git a/core/Controller/UnifiedSearchController.php b/core/Controller/UnifiedSearchController.php
index 6888a9a26393d..df9997f38cfb4 100644
--- a/core/Controller/UnifiedSearchController.php
+++ b/core/Controller/UnifiedSearchController.php
@@ -61,7 +61,7 @@ public function __construct(
public function getProviders(string $from = ''): DataResponse {
[$route, $parameters] = $this->getRouteInformation($from);
- $result = $this->composer->getProviders($route, $parameters);
+ $result = $this->composer->getProviders($this->userSession->getUser(), $route, $parameters);
$response = new DataResponse($result);
$response->setETag(md5(json_encode($result)));
return $response;
diff --git a/core/Controller/WebAuthnController.php b/core/Controller/WebAuthnController.php
index d7255831e88de..f07af3e0f96d8 100644
--- a/core/Controller/WebAuthnController.php
+++ b/core/Controller/WebAuthnController.php
@@ -46,6 +46,10 @@ public function __construct(
public function startAuthentication(string $loginName): JSONResponse {
$this->logger->debug('Starting WebAuthn login');
+ if (!$this->webAuthnManger->isWebAuthnAvailable()) {
+ return new JSONResponse([], Http::STATUS_FORBIDDEN);
+ }
+
$this->logger->debug('Converting login name to UID');
$uid = $loginName;
Util::emitHook(
@@ -68,6 +72,10 @@ public function startAuthentication(string $loginName): JSONResponse {
public function finishAuthentication(string $data): JSONResponse {
$this->logger->debug('Validating WebAuthn login');
+ if (!$this->webAuthnManger->isWebAuthnAvailable()) {
+ return new JSONResponse([], Http::STATUS_FORBIDDEN);
+ }
+
if (!$this->session->exists(self::WEBAUTHN_LOGIN) || !$this->session->exists(self::WEBAUTHN_LOGIN_UID)) {
$this->logger->debug('Trying to finish WebAuthn login without session data');
return new JSONResponse([], Http::STATUS_BAD_REQUEST);
diff --git a/lib/base.php b/lib/base.php
index a0b9e6d096145..6b13ca52967f2 100644
--- a/lib/base.php
+++ b/lib/base.php
@@ -966,13 +966,16 @@ public static function registerCleanupHooks(\OC\SystemConfig $systemConfig): voi
if ($systemConfig->getValue('installed', false) && !\OCP\Util::needUpgrade()) {
// NOTE: This will be replaced to use OCP
$userSession = Server::get(\OC\User\Session::class);
- $userSession->listen('\OC\User', 'postLogin', function () use ($userSession) {
+ $userSession->listen('\OC\User', 'postLogin', function ($loggedInUser, $loginName, $password, bool $isTokenLogin) use ($userSession) {
if (!defined('PHPUNIT_RUN') && $userSession->isLoggedIn()) {
- // reset brute force delay for this IP address and username
- $uid = $userSession->getUser()->getUID();
- $request = Server::get(IRequest::class);
- $throttler = Server::get(IThrottler::class);
- $throttler->resetDelay($request->getRemoteAddress(), 'login', ['user' => $uid]);
+ // A token login does not prove knowledge of the password
+ if (!$isTokenLogin) {
+ // reset brute force delay for this IP address and username
+ $uid = $userSession->getUser()->getUID();
+ $request = Server::get(IRequest::class);
+ $throttler = Server::get(IThrottler::class);
+ $throttler->resetDelay($request->getRemoteAddress(), 'login', ['user' => $uid]);
+ }
}
try {
diff --git a/lib/composer/composer/autoload_classmap.php b/lib/composer/composer/autoload_classmap.php
index f3e5aee2d5058..cd055bf8f7457 100644
--- a/lib/composer/composer/autoload_classmap.php
+++ b/lib/composer/composer/autoload_classmap.php
@@ -155,6 +155,7 @@
'OCP\\App\\Events\\AppDisableEvent' => $baseDir . '/lib/public/App/Events/AppDisableEvent.php',
'OCP\\App\\Events\\AppEnableEvent' => $baseDir . '/lib/public/App/Events/AppEnableEvent.php',
'OCP\\App\\Events\\AppUpdateEvent' => $baseDir . '/lib/public/App/Events/AppUpdateEvent.php',
+ 'OCP\\App\\IAppAccessFilter' => $baseDir . '/lib/public/App/IAppAccessFilter.php',
'OCP\\App\\IAppManager' => $baseDir . '/lib/public/App/IAppManager.php',
'OCP\\App\\ManagerEvent' => $baseDir . '/lib/public/App/ManagerEvent.php',
'OCP\\Authentication\\Events\\AnyLoginFailedEvent' => $baseDir . '/lib/public/Authentication/Events/AnyLoginFailedEvent.php',
diff --git a/lib/composer/composer/autoload_static.php b/lib/composer/composer/autoload_static.php
index f2967f187fa7d..36690c62699d0 100644
--- a/lib/composer/composer/autoload_static.php
+++ b/lib/composer/composer/autoload_static.php
@@ -196,6 +196,7 @@ class ComposerStaticInit749170dad3f5e7f9ca158f5a9f04f6a2
'OCP\\App\\Events\\AppDisableEvent' => __DIR__ . '/../../..' . '/lib/public/App/Events/AppDisableEvent.php',
'OCP\\App\\Events\\AppEnableEvent' => __DIR__ . '/../../..' . '/lib/public/App/Events/AppEnableEvent.php',
'OCP\\App\\Events\\AppUpdateEvent' => __DIR__ . '/../../..' . '/lib/public/App/Events/AppUpdateEvent.php',
+ 'OCP\\App\\IAppAccessFilter' => __DIR__ . '/../../..' . '/lib/public/App/IAppAccessFilter.php',
'OCP\\App\\IAppManager' => __DIR__ . '/../../..' . '/lib/public/App/IAppManager.php',
'OCP\\App\\ManagerEvent' => __DIR__ . '/../../..' . '/lib/public/App/ManagerEvent.php',
'OCP\\Authentication\\Events\\AnyLoginFailedEvent' => __DIR__ . '/../../..' . '/lib/public/Authentication/Events/AnyLoginFailedEvent.php',
diff --git a/lib/private/App/AppManager.php b/lib/private/App/AppManager.php
index 655d80e9b6c91..1c53adef6948f 100644
--- a/lib/private/App/AppManager.php
+++ b/lib/private/App/AppManager.php
@@ -16,6 +16,7 @@
use OCP\App\Events\AppDisableEvent;
use OCP\App\Events\AppEnableEvent;
use OCP\App\Events\AppUpdateEvent;
+use OCP\App\IAppAccessFilter;
use OCP\App\IAppManager;
use OCP\App\ManagerEvent;
use OCP\BackgroundJob\IJobList;
@@ -35,6 +36,7 @@
use OCP\Server;
use OCP\ServerVersion;
use OCP\Settings\IManager as ISettingsManager;
+use Psr\Container\ContainerExceptionInterface;
use Psr\Log\LoggerInterface;
class AppManager implements IAppManager {
@@ -76,6 +78,9 @@ class AppManager implements IAppManager {
private ?IURLGenerator $urlGenerator = null;
private ?INavigationManager $navigationManager = null;
+ /** @var list|null */
+ private ?array $appAccessFilters = null;
+
/**
* Be extremely careful when injecting classes here. The AppManager is used by the installer,
* so it needs to work before installation. See how AppConfig and IURLGenerator are injected for reference
@@ -216,12 +221,60 @@ public function getAllAppsInAppsFolders(): array {
*/
public function getEnabledAppsForUser(IUser $user) {
$apps = $this->getEnabledAppsValues();
- $appsForUser = array_filter($apps, function ($enabled) use ($user) {
- return $this->checkAppForUser($enabled, $user);
- });
+ $appsForUser = array_filter($apps, function (string $enabled, string $appId) use ($user): bool {
+ return $this->checkAppForUser($enabled, $user)
+ && $this->isAccessibleForUser($appId, $user);
+ }, ARRAY_FILTER_USE_BOTH);
return array_keys($appsForUser);
}
+ /**
+ * Apply the registered app access filters. Always enabled apps and apps
+ * with a protected type can't be restricted.
+ */
+ private function isAccessibleForUser(string $appId, IUser $user): bool {
+ if ($this->isAlwaysEnabled($appId)) {
+ return true;
+ }
+
+ foreach ($this->getAppAccessFilters() as $filter) {
+ if (!$filter->isAppAccessible($appId, $user)) {
+ return $this->hasProtectedAppType($this->getAppTypes($appId));
+ }
+ }
+
+ return true;
+ }
+
+ /**
+ * @return list
+ */
+ private function getAppAccessFilters(): array {
+ if ($this->appAccessFilters !== null) {
+ return $this->appAccessFilters;
+ }
+
+ $context = Server::get(Coordinator::class)->getRegistrationContext();
+ if ($context === null) {
+ // Apps are not registered yet, so don't cache the empty list
+ return [];
+ }
+
+ $filters = [];
+ foreach ($context->getAppAccessFilters() as $registration) {
+ try {
+ $filters[] = Server::get($registration->getService());
+ } catch (ContainerExceptionInterface $e) {
+ $this->logger->error('Could not load app access filter: ' . $e->getMessage(), [
+ 'exception' => $e,
+ 'app' => $registration->getAppId(),
+ ]);
+ }
+ }
+
+ return $this->appAccessFilters = $filters;
+ }
+
public function getEnabledAppsForGroup(IGroup $group): array {
$apps = $this->getEnabledAppsValues();
$appsForGroups = array_filter($apps, function ($enabled) use ($group) {
@@ -355,11 +408,13 @@ public function isEnabledForUser($appId, $user = null) {
$user = $this->userSession->getUser();
}
$enabledAppsValues = $this->getEnabledAppsValues();
- if (isset($enabledAppsValues[$appId])) {
- return $this->checkAppForUser($enabledAppsValues[$appId], $user);
- } else {
+ if (!isset($enabledAppsValues[$appId])) {
+ return false;
+ }
+ if (!$this->checkAppForUser($enabledAppsValues[$appId], $user)) {
return false;
}
+ return $user === null || $this->isAccessibleForUser($appId, $user);
}
private function checkAppForUser(string $enabled, ?IUser $user): bool {
diff --git a/lib/private/AppFramework/Bootstrap/RegistrationContext.php b/lib/private/AppFramework/Bootstrap/RegistrationContext.php
index c95edc1ee076c..3b36bcd880b82 100644
--- a/lib/private/AppFramework/Bootstrap/RegistrationContext.php
+++ b/lib/private/AppFramework/Bootstrap/RegistrationContext.php
@@ -11,6 +11,7 @@
use Closure;
use OC\Support\CrashReport\Registry;
+use OCP\App\IAppAccessFilter;
use OCP\AppFramework\App;
use OCP\AppFramework\Bootstrap\IRegistrationContext;
use OCP\AppFramework\Middleware;
@@ -168,6 +169,9 @@ class RegistrationContext {
/** @var class-string|null */
private ?string $globalScaleService = null;
+ /** @var ServiceRegistration[] */
+ private array $appAccessFilters = [];
+
public function __construct(LoggerInterface $logger) {
$this->logger = $logger;
}
@@ -465,6 +469,14 @@ public function registerGlobalScaleService(string $globalScaleServiceClass): voi
$globalScaleServiceClass
);
}
+
+ #[\Override]
+ public function registerAppAccessFilter(string $appAccessFilterClass): void {
+ $this->context->registerAppAccessFilter(
+ $this->appId,
+ $appAccessFilterClass
+ );
+ }
};
}
@@ -693,6 +705,13 @@ public function registerGlobalScaleService(string $class): void {
$this->globalScaleService = $class;
}
+ /**
+ * @psalm-param class-string $class
+ */
+ public function registerAppAccessFilter(string $appId, string $class): void {
+ $this->appAccessFilters[] = new ServiceRegistration($appId, $class);
+ }
+
/**
* @param App[] $apps
*/
@@ -1081,4 +1100,11 @@ public function getConfigLexicon(string $appId): ?ILexicon {
public function getGlobalScaleService(): ?string {
return $this->globalScaleService;
}
+
+ /**
+ * @return ServiceRegistration[]
+ */
+ public function getAppAccessFilters(): array {
+ return $this->appAccessFilters;
+ }
}
diff --git a/lib/private/AppFramework/Http/Request.php b/lib/private/AppFramework/Http/Request.php
index 87aa20179b0b9..18e2a367f594a 100644
--- a/lib/private/AppFramework/Http/Request.php
+++ b/lib/private/AppFramework/Http/Request.php
@@ -886,7 +886,7 @@ private function fromTrustedProxy(): bool {
public function getFormat(): ?string {
$format = $this->getParam('format');
- if ($format !== null) {
+ if (is_string($format)) {
return $format;
}
diff --git a/lib/private/Authentication/Listeners/UserDeletedTokenCleanupListener.php b/lib/private/Authentication/Listeners/UserDeletedTokenCleanupListener.php
index 3631c04432c89..07d8ee4dbf558 100644
--- a/lib/private/Authentication/Listeners/UserDeletedTokenCleanupListener.php
+++ b/lib/private/Authentication/Listeners/UserDeletedTokenCleanupListener.php
@@ -43,7 +43,7 @@ public function handle(Event $event): void {
*/
try {
$uid = $event->getUser()->getUID();
- $tokens = $this->manager->getTokenByUser($uid);
+ $tokens = $this->manager->getAllTokensByUser($uid);
foreach ($tokens as $token) {
$this->manager->invalidateTokenById($uid, $token->getId());
}
diff --git a/lib/private/Authentication/Token/IProvider.php b/lib/private/Authentication/Token/IProvider.php
index e30ac5e7b24cf..9350e9bd9f1cc 100644
--- a/lib/private/Authentication/Token/IProvider.php
+++ b/lib/private/Authentication/Token/IProvider.php
@@ -123,6 +123,15 @@ public function updateTokenActivity(OCPIToken $token);
*/
public function getTokenByUser(string $uid): array;
+ /**
+ * Get every token of a user, without the limit of getTokenByUser()
+ *
+ * Tokens may be deleted or updated while iterating.
+ *
+ * @return iterable
+ */
+ public function getAllTokensByUser(string $uid): iterable;
+
/**
* Get the (unencrypted) password of the given token
*
@@ -150,7 +159,8 @@ public function setPassword(OCPIToken $token, string $tokenId, string $password)
* @param OCPIToken $token
* @param string $oldTokenId
* @param string $newTokenId
- * @return OCPIToken
+ * @return OCPIToken the rotated token as it is stored, not necessarily the given instance
+ * @throws InvalidTokenException when the token does not exist (anymore)
* @throws \RuntimeException when OpenSSL reports a problem
*/
public function rotate(OCPIToken $token, string $oldTokenId, string $newTokenId): OCPIToken;
@@ -164,10 +174,8 @@ public function rotate(OCPIToken $token, string $oldTokenId, string $newTokenId)
public function markPasswordInvalid(OCPIToken $token, string $tokenId);
/**
- * Update all the passwords of $uid if required
- *
- * @param string $uid
- * @param string $password
+ * Update all the app passwords of $uid if required
+ * Session tokens that were created with a different password are invalidated
*/
public function updatePasswords(string $uid, string $password);
}
diff --git a/lib/private/Authentication/Token/Manager.php b/lib/private/Authentication/Token/Manager.php
index da370a6421b08..50d595e49ffde 100644
--- a/lib/private/Authentication/Token/Manager.php
+++ b/lib/private/Authentication/Token/Manager.php
@@ -92,6 +92,10 @@ public function getTokenByUser(string $uid): array {
return $this->publicKeyTokenProvider->getTokenByUser($uid);
}
+ public function getAllTokensByUser(string $uid): iterable {
+ return $this->publicKeyTokenProvider->getAllTokensByUser($uid);
+ }
+
/**
* Get a token by token
*
@@ -220,7 +224,7 @@ public function updatePasswords(string $uid, string $password) {
}
public function invalidateTokensOfUser(string $uid, ?string $clientName) {
- $tokens = $this->getTokenByUser($uid);
+ $tokens = $this->getAllTokensByUser($uid);
foreach ($tokens as $token) {
if ($clientName === null || ($token->getName() === $clientName)) {
$this->invalidateTokenById($uid, $token->getId());
diff --git a/lib/private/Authentication/Token/PublicKeyToken.php b/lib/private/Authentication/Token/PublicKeyToken.php
index b82b67940d4f6..ad81b254e3f8a 100644
--- a/lib/private/Authentication/Token/PublicKeyToken.php
+++ b/lib/private/Authentication/Token/PublicKeyToken.php
@@ -129,7 +129,7 @@ public function getPassword(): ?string {
public function jsonSerialize(): array {
return [
'id' => $this->id,
- 'name' => $this->name,
+ 'name' => $this->getName(),
'lastActivity' => $this->lastActivity,
'type' => $this->type,
'scope' => $this->getScopeAsArray()
@@ -180,11 +180,13 @@ public function setScope(array|string|null $scope): void {
}
public function getName(): string {
- return parent::getName();
+ // Rows stored before names were scrubbed may hold invalid UTF-8
+ return mb_scrub(parent::getName() ?? '', 'UTF-8');
}
public function setName(string $name): void {
- parent::setName($name);
+ // Names often come from the User-Agent header, which isn't guaranteed to be UTF-8
+ parent::setName(mb_scrub($name, 'UTF-8'));
}
public function getRemember(): int {
diff --git a/lib/private/Authentication/Token/PublicKeyTokenMapper.php b/lib/private/Authentication/Token/PublicKeyTokenMapper.php
index 9aabd69e57a12..5754e3f5a994c 100644
--- a/lib/private/Authentication/Token/PublicKeyTokenMapper.php
+++ b/lib/private/Authentication/Token/PublicKeyTokenMapper.php
@@ -133,6 +133,32 @@ public function getTokenByUser(string $uid): array {
return $entities;
}
+ /**
+ * Tokens may be deleted or updated while iterating.
+ *
+ * @return \Generator
+ */
+ public function getAllTokensByUser(string $uid): \Generator {
+ $chunkSize = 1000;
+ $lastId = 0;
+ do {
+ $qb = $this->db->getQueryBuilder();
+ $qb->select('*')
+ ->from($this->tableName)
+ ->where($qb->expr()->eq('uid', $qb->createNamedParameter($uid)))
+ ->andWhere($qb->expr()->eq('version', $qb->createNamedParameter(PublicKeyToken::VERSION, IQueryBuilder::PARAM_INT)))
+ ->andWhere($qb->expr()->gt('id', $qb->createNamedParameter($lastId, IQueryBuilder::PARAM_INT)))
+ ->orderBy('id')
+ ->setMaxResults($chunkSize);
+ $tokens = $this->findEntities($qb);
+
+ foreach ($tokens as $token) {
+ $lastId = $token->getId();
+ yield $token;
+ }
+ } while (count($tokens) === $chunkSize);
+ }
+
public function getTokenByUserAndId(string $uid, int $id): ?string {
/* @var $qb IQueryBuilder */
$qb = $this->db->getQueryBuilder();
diff --git a/lib/private/Authentication/Token/PublicKeyTokenProvider.php b/lib/private/Authentication/Token/PublicKeyTokenProvider.php
index 0fba91baf32e4..2da4c2722f61a 100644
--- a/lib/private/Authentication/Token/PublicKeyTokenProvider.php
+++ b/lib/private/Authentication/Token/PublicKeyTokenProvider.php
@@ -133,7 +133,8 @@ public function generateToken(string $token,
return $dbToken;
}
- public function getToken(string $tokenId): OCPIToken {
+ #[\Override]
+ public function getToken(string $tokenId, bool $allowReadFromCache = true): OCPIToken {
/**
* Token length: 72
* @see \OC\Core\Controller\ClientFlowLoginController::generateAppPassword
@@ -156,9 +157,11 @@ public function getToken(string $tokenId): OCPIToken {
}
$tokenHash = $this->hashToken($tokenId);
- if ($token = $this->getTokenFromCache($tokenHash)) {
- $this->checkToken($token);
- return $token;
+ if ($allowReadFromCache) {
+ if ($token = $this->getTokenFromCache($tokenHash)) {
+ $this->checkToken($token);
+ return $token;
+ }
}
try {
@@ -167,7 +170,7 @@ public function getToken(string $tokenId): OCPIToken {
} catch (DoesNotExistException $ex) {
try {
$token = $this->mapper->getToken($this->hashTokenWithEmptySecret($tokenId));
- $this->rotate($token, $tokenId, $tokenId);
+ $token = $this->rotate($token, $tokenId, $tokenId);
} catch (DoesNotExistException) {
$this->cacheInvalidHash($tokenHash);
throw new InvalidTokenException('Token does not exist: ' . $ex->getMessage(), 0, $ex);
@@ -237,7 +240,7 @@ private function checkToken($token): void {
public function renewSessionToken(string $oldSessionId, string $sessionId): OCPIToken {
return $this->atomic(function () use ($oldSessionId, $sessionId) {
- $token = $this->getToken($oldSessionId);
+ $token = $this->getToken($oldSessionId, allowReadFromCache:false);
if (!($token instanceof PublicKeyToken)) {
throw new InvalidTokenException('Invalid token type');
@@ -356,6 +359,10 @@ public function getTokenByUser(string $uid): array {
return $this->mapper->getTokenByUser($uid);
}
+ public function getAllTokensByUser(string $uid): iterable {
+ return $this->mapper->getAllTokensByUser($uid);
+ }
+
public function getPassword(OCPIToken $savedToken, string $tokenId): string {
if (!($savedToken instanceof PublicKeyToken)) {
throw new InvalidTokenException('Invalid token type');
@@ -402,14 +409,33 @@ public function rotate(OCPIToken $token, string $oldTokenId, string $newTokenId)
throw new InvalidTokenException('Invalid token type');
}
+ // The given token might come from the cache, so rotate what is stored:
+ // it might have been invalidated, rotated or changed in the meantime
+ $oldTokenHash = $token->getToken();
+ try {
+ $token = $this->mapper->getToken($oldTokenHash);
+ } catch (DoesNotExistException $ex) {
+ $this->cacheInvalidHash($oldTokenHash);
+ throw new InvalidTokenException('Token does not exist: ' . $ex->getMessage(), 0, $ex);
+ }
+ if ($token->getType() === OCPIToken::WIPE_TOKEN) {
+ $this->cacheToken($token);
+ throw new WipeTokenException($token);
+ }
+
// Decrypt private key with oldTokenId
$privateKey = $this->decrypt($token->getPrivateKey(), $oldTokenId);
// Encrypt with the new token
$token->setPrivateKey($this->encrypt($privateKey, $newTokenId));
- $token->setToken($this->hashToken($newTokenId));
+ $newTokenHash = $this->hashToken($newTokenId);
+ $token->setToken($newTokenHash);
$this->updateToken($token);
+ if ($oldTokenHash !== $newTokenHash) {
+ $this->cacheInvalidHash($oldTokenHash);
+ }
+
return $token;
}
@@ -560,16 +586,30 @@ public function updatePasswords(string $uid, string $password) {
$hashNeedsUpdate = [];
foreach ($tokens as $t) {
- if (!isset($hashNeedsUpdate[$t->getPasswordHash()])) {
- if ($t->getPasswordHash() === null) {
- $hashNeedsUpdate[$t->getPasswordHash() ?: ''] = true;
- } elseif (!$this->hasher->verify(sha1($password) . $password, $t->getPasswordHash())) {
- $hashNeedsUpdate[$t->getPasswordHash() ?: ''] = true;
+ $passwordHash = $t->getPasswordHash();
+ if ($passwordHash === null) {
+ $hashNeedsUpdate[''] = true;
+ $needsUpdating = true;
+ } elseif (!isset($hashNeedsUpdate[$passwordHash])) {
+ if (!$this->hasher->verify(sha1($password) . $password, $passwordHash)) {
+ $hashNeedsUpdate[$passwordHash] = true;
} else {
- $hashNeedsUpdate[$t->getPasswordHash() ?: ''] = false;
+ $hashNeedsUpdate[$passwordHash] = false;
}
+ $needsUpdating = $hashNeedsUpdate[$passwordHash] ?? true;
+ } else {
+ $needsUpdating = $hashNeedsUpdate[$passwordHash];
+ }
+
+ if ($needsUpdating && $passwordHash !== null && $t->getType() === OCPIToken::TEMPORARY_TOKEN) {
+ // Only app passwords follow a password change. A session that was
+ // opened with another password is deleted (like in setPassword),
+ // otherwise it would outlive the password change
+ $this->mapper->invalidate($t->getToken());
+ $this->cacheInvalidHash($t->getToken());
+ $this->eventDispatcher->dispatchTyped(new TokenInvalidatedEvent($t));
+ continue;
}
- $needsUpdating = $hashNeedsUpdate[$t->getPasswordHash() ?: ''] ?? true;
if ($needsUpdating) {
if ($newPasswordHash === null) {
diff --git a/lib/private/Authentication/Token/RemoteWipe.php b/lib/private/Authentication/Token/RemoteWipe.php
index eb1abf2098aa9..5f236b359a96c 100644
--- a/lib/private/Authentication/Token/RemoteWipe.php
+++ b/lib/private/Authentication/Token/RemoteWipe.php
@@ -62,7 +62,10 @@ public function markTokenForWipe(IToken $token): bool {
* @return bool true if any tokens have been marked for remote wipe
*/
public function markAllTokensForWipe(IUser $user): bool {
- $tokens = $this->tokenProvider->getTokenByUser($user->getUID());
+ $tokens = [];
+ foreach ($this->tokenProvider->getAllTokensByUser($user->getUID()) as $token) {
+ $tokens[] = $token;
+ }
/** @var IWipeableToken[] $wipeable */
$wipeable = array_filter($tokens, function (IToken $token) {
diff --git a/lib/private/Search/SearchComposer.php b/lib/private/Search/SearchComposer.php
index c017d1ec9a338..1b894773b3474 100644
--- a/lib/private/Search/SearchComposer.php
+++ b/lib/private/Search/SearchComposer.php
@@ -13,6 +13,7 @@
use OC\Core\AppInfo\Application;
use OC\Core\AppInfo\ConfigLexicon;
use OC\Core\ResponseDefinitions;
+use OCP\App\IAppManager;
use OCP\IAppConfig;
use OCP\IURLGenerator;
use OCP\IUser;
@@ -70,6 +71,7 @@ public function __construct(
private IURLGenerator $urlGenerator,
private LoggerInterface $logger,
private IAppConfig $appConfig,
+ private IAppManager $appManager,
) {
$this->commonFilters = [
IFilter::BUILTIN_TERM => new FilterDefinition(IFilter::BUILTIN_TERM, FilterDefinition::TYPE_STRING),
@@ -165,17 +167,21 @@ private function registerCustomFilter(FilterDefinition $filter, string $provider
* Get a list of all provider IDs & Names for the consecutive calls to `search`
* Sort the list by the order property
*
+ * @param IUser $user the user to list the providers for
* @param string $route the route the user is currently at
* @param array $routeParameters the parameters of the route the user is currently at
*
* @return list
*/
- public function getProviders(string $route, array $routeParameters): array {
+ public function getProviders(IUser $user, string $route, array $routeParameters): array {
$this->loadLazyProviders();
$providers = array_map(
- function (array $providerData) use ($route, $routeParameters) {
+ function (array $providerData) use ($user, $route, $routeParameters) {
$appId = $providerData['appId'];
+ if (!$this->appManager->isEnabledForUser($appId, $user)) {
+ return;
+ }
$provider = $providerData['provider'];
$order = $provider->getOrder($route, $routeParameters);
if ($order === null) {
@@ -362,6 +368,10 @@ public function search(
throw new InvalidArgumentException("Provider $providerId is unknown");
}
+ if (!$this->appManager->isEnabledForUser($this->providers[$providerId]['appId'], $user)) {
+ return SearchResult::complete($provider->getName(), []);
+ }
+
return $provider->search($user, $query);
}
}
diff --git a/lib/private/Security/Bruteforce/Throttler.php b/lib/private/Security/Bruteforce/Throttler.php
index 9882e8b68645c..33f18a3244fad 100644
--- a/lib/private/Security/Bruteforce/Throttler.php
+++ b/lib/private/Security/Bruteforce/Throttler.php
@@ -33,9 +33,6 @@
* @package OC\Security\Bruteforce
*/
class Throttler implements IThrottler {
- /** @var bool[] */
- private array $hasAttemptsDeleted = [];
-
public function __construct(
private ITimeFactory $timeFactory,
private LoggerInterface $logger,
@@ -113,7 +110,7 @@ public function getAttempts(string $ip, string $action = '', float $maxAgeHours
$maxAgeHours = 48;
}
- if ($ip === '' || isset($this->hasAttemptsDeleted[$action])) {
+ if ($ip === '') {
return 0;
}
@@ -179,8 +176,6 @@ public function resetDelay(string $ip, string $action, array $metadata): void {
$action,
$metadata,
);
-
- $this->hasAttemptsDeleted[$action] = true;
}
/**
diff --git a/lib/private/User/Session.php b/lib/private/User/Session.php
index 51681692d8492..ce327d2d42fad 100644
--- a/lib/private/User/Session.php
+++ b/lib/private/User/Session.php
@@ -911,6 +911,13 @@ public function tryTokenLogin(IRequest $request) {
return false;
}
+ if (!$tokenFromCookie
+ && $request->getCookie($this->config->getSystemValueString('instanceid')) !== null
+ && $this->session->get('app_password') !== $token) {
+ // The client chose this session, so a header login starts an empty one instead of writing into it
+ $this->session->clear();
+ }
+
if (!$this->loginWithToken($token)) {
$this->handleLoginFailed($throttler, $currentDelay, $remoteAddress, $dbToken->getUID(), $token);
return false;
diff --git a/lib/public/App/IAppAccessFilter.php b/lib/public/App/IAppAccessFilter.php
new file mode 100644
index 0000000000000..68be8230d4743
--- /dev/null
+++ b/lib/public/App/IAppAccessFilter.php
@@ -0,0 +1,41 @@
+ $appAccessFilterClass
+ * @since 33.0.10
+ */
+ public function registerAppAccessFilter(string $appAccessFilterClass): void;
}
diff --git a/tests/Core/Controller/AppPasswordControllerTest.php b/tests/Core/Controller/AppPasswordControllerTest.php
index 86bc3c05a1c20..4fc693295c882 100644
--- a/tests/Core/Controller/AppPasswordControllerTest.php
+++ b/tests/Core/Controller/AppPasswordControllerTest.php
@@ -292,4 +292,63 @@ public function testDeleteAppPasswordSuccess(): void {
$this->assertEquals(new DataResponse(), $result);
}
+
+ public function testRotateAppPasswordNoAppPassword(): void {
+ $this->session->method('exists')
+ ->with('app_password')
+ ->willReturn(false);
+
+ $this->expectException(OCSForbiddenException::class);
+
+ $this->controller->rotateAppPassword();
+ }
+
+ public function testRotateAppPasswordFails(): void {
+ $this->session->method('exists')
+ ->with('app_password')
+ ->willReturn(true);
+ $this->session->method('get')
+ ->with('app_password')
+ ->willReturn('myAppPassword');
+ $this->random->method('generate')
+ ->willReturn('myNewAppPassword');
+
+ $token = $this->createMock(IToken::class);
+ $this->tokenProvider->method('getToken')
+ ->with('myAppPassword')
+ ->willReturn($token);
+ $this->tokenProvider->expects($this->once())
+ ->method('rotate')
+ ->with($token, 'myAppPassword', 'myNewAppPassword')
+ ->willThrowException(new InvalidTokenException());
+
+ $this->expectException(OCSForbiddenException::class);
+
+ $this->controller->rotateAppPassword();
+ }
+
+ public function testRotateAppPasswordSuccess(): void {
+ $this->session->method('exists')
+ ->with('app_password')
+ ->willReturn(true);
+ $this->session->method('get')
+ ->with('app_password')
+ ->willReturn('myAppPassword');
+ $this->random->method('generate')
+ ->willReturn('myNewAppPassword');
+
+ $token = $this->createMock(IToken::class);
+ $this->tokenProvider->method('getToken')
+ ->with('myAppPassword')
+ ->willReturn($token);
+ $this->tokenProvider->expects($this->once())
+ ->method('rotate')
+ ->with($token, 'myAppPassword', 'myNewAppPassword')
+ ->willReturn($token);
+
+ $result = $this->controller->rotateAppPassword();
+
+ $this->assertEquals(new DataResponse(['apppassword' => 'myNewAppPassword']), $result);
+ }
+
}
diff --git a/tests/Core/Controller/ClientFlowLoginControllerTest.php b/tests/Core/Controller/ClientFlowLoginControllerTest.php
index 7a5bbbec82d5a..a129994b2e5e4 100644
--- a/tests/Core/Controller/ClientFlowLoginControllerTest.php
+++ b/tests/Core/Controller/ClientFlowLoginControllerTest.php
@@ -145,7 +145,7 @@ public function testShowAuthPickerPageWithOcsHeader(): void {
->expects($this->atLeastOnce())
->method('get')
->with('oauth.state')
- ->willReturn('OauthStateToken');
+ ->willReturn(['clientIdentifier' => 'OtherClientIdentifier', 'state' => 'OauthStateToken']);
$this->defaults
->expects($this->once())
->method('getName')
@@ -183,7 +183,7 @@ public function testShowAuthPickerPageWithOcsHeader(): void {
'instanceName' => 'ExampleCloud',
'stateToken' => 'StateToken',
'serverHost' => 'https://example.com',
- 'oauthState' => 'OauthStateToken',
+ 'oauthState' => null,
'direct' => false,
'providedRedirectUri' => '',
'appTokenUrl' => '',
@@ -224,7 +224,7 @@ public function testShowAuthPickerPageWithOauth(): void {
->expects($this->atLeastOnce())
->method('get')
->with('oauth.state')
- ->willReturn('OauthStateToken');
+ ->willReturn(['clientIdentifier' => 'MyClientIdentifier', 'state' => 'OauthStateToken']);
$this->defaults
->expects($this->once())
->method('getName')
@@ -420,16 +420,17 @@ public function testGeneratePasswordWithPassword(): void {
* @param string $redirectUrl
*
* @testWith
- * ["https://example.com/redirect.php", "https://example.com/redirect.php?state=MyOauthState&code=MyAccessCode"]
- * ["https://example.com/redirect.php?hello=world", "https://example.com/redirect.php?hello=world&state=MyOauthState&code=MyAccessCode"]
+ * ["https://example.com/redirect.php", "https://example.com/redirect.php?state=MyOauthState&code=MyAccessCode", "MyClientIdentifier"]
+ * ["https://example.com/redirect.php?hello=world", "https://example.com/redirect.php?hello=world&state=MyOauthState&code=MyAccessCode", "MyClientIdentifier"]
+ * ["https://example.com/redirect.php", "https://example.com/redirect.php?state=&code=MyAccessCode", "OtherClientIdentifier"]
*
*/
- public function testGeneratePasswordWithPasswordForOauthClient($redirectUri, $redirectUrl): void {
+ public function testGeneratePasswordWithPasswordForOauthClient($redirectUri, $redirectUrl, string $stateClientIdentifier): void {
$this->session
->method('get')
->willReturnMap([
['client.flow.state.token', 'MyStateToken'],
- ['oauth.state', 'MyOauthState'],
+ ['oauth.state', ['clientIdentifier' => $stateClientIdentifier, 'state' => 'MyOauthState']],
]);
$calls = [
'client.flow.state.token',
diff --git a/tests/Core/Controller/WebAuthnControllerTest.php b/tests/Core/Controller/WebAuthnControllerTest.php
new file mode 100644
index 0000000000000..11696dae0410f
--- /dev/null
+++ b/tests/Core/Controller/WebAuthnControllerTest.php
@@ -0,0 +1,65 @@
+manager = $this->createMock(Manager::class);
+ $this->manager->method('isWebAuthnAvailable')->willReturn(false);
+ $this->session = $this->createMock(ISession::class);
+ $this->chain = $this->createMock(WebAuthnChain::class);
+ $this->controller = new WebAuthnController(
+ 'core',
+ $this->createMock(IRequest::class),
+ $this->manager,
+ $this->session,
+ $this->createMock(LoggerInterface::class),
+ $this->chain,
+ $this->createMock(URLGenerator::class),
+ );
+ }
+
+ public function testStartAuthenticationRefusedWhenDisabled(): void {
+ $this->manager->expects($this->never())->method('startAuthentication');
+ $this->session->expects($this->never())->method('set');
+
+ $response = $this->controller->startAuthentication('alice');
+
+ $this->assertSame(Http::STATUS_FORBIDDEN, $response->getStatus());
+ }
+
+ public function testFinishAuthenticationRefusedWhenDisabled(): void {
+ $this->session->method('exists')->willReturn(true);
+ $this->manager->expects($this->never())->method('finishAuthentication');
+ $this->chain->expects($this->never())->method('process');
+
+ $response = $this->controller->finishAuthentication('{}');
+
+ $this->assertSame(Http::STATUS_FORBIDDEN, $response->getStatus());
+ }
+}
diff --git a/tests/lib/App/AppManagerTest.php b/tests/lib/App/AppManagerTest.php
index 11bc35c14f215..c95745d164e0a 100644
--- a/tests/lib/App/AppManagerTest.php
+++ b/tests/lib/App/AppManagerTest.php
@@ -14,10 +14,14 @@
use OC\App\DependencyAnalyzer;
use OC\App\Platform;
use OC\AppConfig;
+use OC\AppFramework\Bootstrap\Coordinator;
+use OC\AppFramework\Bootstrap\RegistrationContext;
+use OC\AppFramework\Bootstrap\ServiceRegistration;
use OC\Config\ConfigManager;
use OCP\App\AppPathNotFoundException;
use OCP\App\Events\AppDisableEvent;
use OCP\App\Events\AppEnableEvent;
+use OCP\App\IAppAccessFilter;
use OCP\EventDispatcher\IEventDispatcher;
use OCP\ICache;
use OCP\ICacheFactory;
@@ -598,6 +602,70 @@ public function testGetAppsForUser(): void {
$this->assertEquals($enabled, $this->manager->getEnabledAppsForUser($user));
}
+ /**
+ * @param list $deniedApps
+ */
+ private function registerAppAccessFilter(array $deniedApps): IAppAccessFilter&MockObject {
+ $filter = $this->createMock(IAppAccessFilter::class);
+ $filter->method('isAppAccessible')
+ ->willReturnCallback(fn (string $appId): bool => !in_array($appId, $deniedApps, true));
+
+ $registrationContext = $this->createMock(RegistrationContext::class);
+ $registrationContext->method('getAppAccessFilters')
+ ->willReturn([new ServiceRegistration('guests', IAppAccessFilter::class)]);
+ $coordinator = $this->createMock(Coordinator::class);
+ $coordinator->method('getRegistrationContext')
+ ->willReturn($registrationContext);
+
+ $this->overwriteService(Coordinator::class, $coordinator);
+ $this->overwriteService(IAppAccessFilter::class, $filter);
+
+ return $filter;
+ }
+
+ public function testIsEnabledForUserDeniedByAccessFilter(): void {
+ $this->registerAppAccessFilter(['test']);
+ $this->appConfig->setValue('test', 'enabled', 'yes');
+ $this->appConfig->setValue('other', 'enabled', 'yes');
+ $user = $this->newUser('user1');
+
+ $this->assertFalse($this->manager->isEnabledForUser('test', $user));
+ $this->assertTrue($this->manager->isEnabledForUser('other', $user));
+ }
+
+
+
+ public function testIsEnabledForUserAccessFilterIgnoresProtectedAppType(): void {
+ $this->registerAppAccessFilter(['test']);
+ $this->appConfig->setValue('test', 'enabled', 'yes');
+ $this->appConfig->setValue('test', 'types', 'filesystem');
+
+ $this->assertTrue($this->manager->isEnabledForUser('test', $this->newUser('user1')));
+ }
+
+
+ public function testGetAppsForUserWithAccessFilter(): void {
+ $this->registerAppAccessFilter(['test1', 'test3', 'files']);
+ $user = $this->newUser('user1');
+ $this->groupManager->method('getUserGroupIds')
+ ->with($user)
+ ->willReturn(['foo']);
+
+ $this->appConfig->setValue('test1', 'enabled', 'yes');
+ $this->appConfig->setValue('test2', 'enabled', 'yes');
+ $this->appConfig->setValue('test3', 'enabled', '["foo"]');
+ $this->appConfig->setValue('test4', 'enabled', 'yes');
+ $this->appConfig->setValue('test4', 'types', 'authentication');
+
+ $apps = $this->manager->getEnabledAppsForUser($user);
+
+ $this->assertNotContains('test1', $apps);
+ $this->assertContains('test2', $apps);
+ $this->assertNotContains('test3', $apps);
+ $this->assertContains('test4', $apps);
+ $this->assertContains('files', $apps);
+ }
+
public function testGetAppsNeedingUpgrade(): void {
/** @var AppManager&MockObject $manager */
$manager = $this->getMockBuilder(AppManager::class)
diff --git a/tests/lib/AppFramework/Http/RequestTest.php b/tests/lib/AppFramework/Http/RequestTest.php
index 51da27579432a..001f4d93741c6 100644
--- a/tests/lib/AppFramework/Http/RequestTest.php
+++ b/tests/lib/AppFramework/Http/RequestTest.php
@@ -2385,4 +2385,34 @@ public function testPassesCSRFCheckWithOCSAPIRequestHeader(): void {
$this->assertTrue($request->passesCSRFCheck());
}
+
+ public static function dataGetFormat(): array {
+ return [
+ 'parameter' => [['format' => 'json'], '', 'json'],
+ 'parameter wins over header' => [['format' => 'xml'], 'application/json', 'xml'],
+ 'header' => [[], 'text/html, application/json', 'json'],
+ 'nothing' => [[], '', null],
+ 'array parameter is ignored' => [['format' => ['']], '', null],
+ 'array parameter falls back to header' => [['format' => ['xml']], 'application/json', 'json'],
+ ];
+ }
+
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataGetFormat')]
+ public function testGetFormat(array $get, string $accept, ?string $expected): void {
+ $request = new Request(
+ [
+ 'get' => $get,
+ 'method' => 'GET',
+ 'server' => [
+ 'HTTP_ACCEPT' => $accept,
+ ],
+ ],
+ $this->requestId,
+ $this->config,
+ $this->csrfTokenManager,
+ $this->stream
+ );
+
+ $this->assertSame($expected, $request->getFormat());
+ }
}
diff --git a/tests/lib/Authentication/Listeners/UserDeletedTokenCleanupListenerTest.php b/tests/lib/Authentication/Listeners/UserDeletedTokenCleanupListenerTest.php
index 1861a5b2150e4..9912eb58c2bb4 100644
--- a/tests/lib/Authentication/Listeners/UserDeletedTokenCleanupListenerTest.php
+++ b/tests/lib/Authentication/Listeners/UserDeletedTokenCleanupListenerTest.php
@@ -44,7 +44,7 @@ protected function setUp(): void {
public function testHandleUnrelated(): void {
$event = new Event();
- $this->manager->expects($this->never())->method('getTokenByUser');
+ $this->manager->expects($this->never())->method('getAllTokensByUser');
$this->logger->expects($this->never())->method('error');
$this->listener->handle($event);
@@ -56,7 +56,7 @@ public function testHandleWithErrors(): void {
$event = new UserDeletedEvent($user);
$exception = new Exception('nope');
$this->manager->expects($this->once())
- ->method('getTokenByUser')
+ ->method('getAllTokensByUser')
->with('user123')
->willThrowException($exception);
$this->logger->expects($this->once())
@@ -76,7 +76,7 @@ public function testHandle(): void {
$token3 = $this->createMock(IToken::class);
$token3->method('getId')->willReturn(3);
$this->manager->expects($this->once())
- ->method('getTokenByUser')
+ ->method('getAllTokensByUser')
->with('user123')
->willReturn([
$token1,
diff --git a/tests/lib/Authentication/Token/ManagerTest.php b/tests/lib/Authentication/Token/ManagerTest.php
index 27ef046bd6d68..f1a15137fce83 100644
--- a/tests/lib/Authentication/Token/ManagerTest.php
+++ b/tests/lib/Authentication/Token/ManagerTest.php
@@ -217,6 +217,18 @@ public function testGetTokenByUser(): void {
$this->assertEquals([$t1, $t2], $result);
}
+ public function testGetAllTokensByUser(): void {
+ $t1 = new PublicKeyToken();
+ $t2 = new PublicKeyToken();
+
+ $this->publicKeyTokenProvider
+ ->method('getAllTokensByUser')
+ ->with('uid')
+ ->willReturn([$t1, $t2]);
+
+ $this->assertEquals([$t1, $t2], $this->manager->getAllTokensByUser('uid'));
+ }
+
public function testRenewSessionTokenPublicKey(): void {
$this->publicKeyTokenProvider->expects($this->once())
->method('renewSessionToken')
@@ -325,7 +337,7 @@ public function testInvalidateTokensOfUserNoClientName(): void {
$this->publicKeyTokenProvider
->expects($this->once())
- ->method('getTokenByUser')
+ ->method('getAllTokensByUser')
->with('theUser')
->willReturn([$t1, $t2]);
@@ -356,7 +368,7 @@ public function testInvalidateTokensOfUserClientNameGiven(): void {
$this->publicKeyTokenProvider
->expects($this->once())
- ->method('getTokenByUser')
+ ->method('getAllTokensByUser')
->with('theUser')
->willReturn([$t1, $t2, $t3]);
$this->publicKeyTokenProvider
diff --git a/tests/lib/Authentication/Token/PublicKeyTokenMapperTest.php b/tests/lib/Authentication/Token/PublicKeyTokenMapperTest.php
index d64c2dde81da9..052b250944fa9 100644
--- a/tests/lib/Authentication/Token/PublicKeyTokenMapperTest.php
+++ b/tests/lib/Authentication/Token/PublicKeyTokenMapperTest.php
@@ -231,6 +231,59 @@ public function testGetTokenByUserNotFound(): void {
$this->assertCount(0, $this->mapper->getTokenByUser('user1000'));
}
+ private function insertTokens(string $uid, int $count, int $version = 2): void {
+ $this->dbConnection->beginTransaction();
+ for ($i = 0; $i < $count; $i++) {
+ $qb = $this->dbConnection->getQueryBuilder();
+ $qb->insert('authtoken')->values([
+ 'uid' => $qb->createNamedParameter($uid),
+ 'login_name' => $qb->createNamedParameter($uid),
+ 'name' => $qb->createNamedParameter('Token ' . $i),
+ 'token' => $qb->createNamedParameter($uid . '-v' . $version . '-token-' . $i),
+ 'type' => $qb->createNamedParameter(IToken::PERMANENT_TOKEN),
+ 'last_activity' => $qb->createNamedParameter($this->time, IQueryBuilder::PARAM_INT),
+ 'last_check' => $qb->createNamedParameter($this->time, IQueryBuilder::PARAM_INT),
+ 'public_key' => $qb->createNamedParameter('public key'),
+ 'private_key' => $qb->createNamedParameter('private key'),
+ 'version' => $qb->createNamedParameter($version),
+ ])->executeStatement();
+ }
+ $this->dbConnection->commit();
+ }
+
+ public function testGetAllTokensByUser(): void {
+ $this->insertTokens('user4', 1000);
+
+ $this->assertCount(1000, iterator_to_array($this->mapper->getAllTokensByUser('user4'), false));
+ $this->assertCount(2, iterator_to_array($this->mapper->getAllTokensByUser('user1'), false));
+ $this->assertCount(0, iterator_to_array($this->mapper->getAllTokensByUser('user1000'), false));
+ }
+
+ public function testGetAllTokensByUserSkipsOtherVersions(): void {
+ $this->insertTokens('user4', 1, 1);
+ $this->insertTokens('user4', 2);
+
+ $tokens = iterator_to_array($this->mapper->getAllTokensByUser('user4'), false);
+
+ $this->assertCount(2, $tokens);
+ foreach ($tokens as $token) {
+ $this->assertSame(PublicKeyToken::VERSION, $token->getVersion());
+ }
+ }
+
+ public function testGetAllTokensByUserWhileDeleting(): void {
+ $this->insertTokens('user4', 1001);
+
+ $seen = 0;
+ foreach ($this->mapper->getAllTokensByUser('user4') as $token) {
+ $this->mapper->delete($token);
+ $seen++;
+ }
+
+ $this->assertSame(1001, $seen);
+ $this->assertCount(0, $this->mapper->getTokenByUser('user4'));
+ }
+
public function testGetById(): void {
/** @var IUser|\PHPUnit\Framework\MockObject\MockObject $user */
$user = $this->createMock(IUser::class);
diff --git a/tests/lib/Authentication/Token/PublicKeyTokenProviderTest.php b/tests/lib/Authentication/Token/PublicKeyTokenProviderTest.php
index ef81d00613c84..0cb339f4b390d 100644
--- a/tests/lib/Authentication/Token/PublicKeyTokenProviderTest.php
+++ b/tests/lib/Authentication/Token/PublicKeyTokenProviderTest.php
@@ -12,9 +12,11 @@
use OC\Authentication\Exceptions\ExpiredTokenException;
use OC\Authentication\Exceptions\InvalidTokenException;
use OC\Authentication\Exceptions\PasswordlessTokenException;
+use OC\Authentication\Exceptions\WipeTokenException;
use OC\Authentication\Token\PublicKeyToken;
use OC\Authentication\Token\PublicKeyTokenMapper;
use OC\Authentication\Token\PublicKeyTokenProvider;
+use OC\Memcache\ArrayCache;
use OCP\AppFramework\Db\DoesNotExistException;
use OCP\AppFramework\Utility\ITimeFactory;
use OCP\Authentication\Token\IToken;
@@ -212,6 +214,16 @@ public function testGetTokenByUser(): void {
$this->assertEquals(['token'], $this->tokenProvider->getTokenByUser('uid'));
}
+ public function testGetAllTokensByUser(): void {
+ $tokens = (fn () => yield new PublicKeyToken())();
+ $this->mapper->expects($this->once())
+ ->method('getAllTokensByUser')
+ ->with('uid')
+ ->willReturn($tokens);
+
+ $this->assertSame($tokens, $this->tokenProvider->getAllTokensByUser('uid'));
+ }
+
public function testGetPassword(): void {
$token = 'tokentokentokentokentoken';
$uid = 'user';
@@ -604,6 +616,9 @@ public function testRotate(): void {
['auth.storeCryptedPassword', true, true],
]);
$actual = $this->tokenProvider->generateToken($token, $uid, $user, $password, $name, $type, IToken::DO_NOT_REMEMBER);
+ $this->mapper->method('getToken')
+ ->with($actual->getToken())
+ ->willReturn($actual);
$new = $this->tokenProvider->rotate($actual, 'oldtokentokentokentokentoken', 'newtokentokentokentokentoken');
@@ -619,6 +634,9 @@ public function testRotateNoPassword(): void {
$type = IToken::PERMANENT_TOKEN;
$actual = $this->tokenProvider->generateToken($token, $uid, $user, $password, $name, $type, IToken::DO_NOT_REMEMBER);
+ $this->mapper->method('getToken')
+ ->with($actual->getToken())
+ ->willReturn($actual);
$oldPrivate = $actual->getPrivateKey();
@@ -630,6 +648,106 @@ public function testRotateNoPassword(): void {
$this->assertNull($new->getPassword());
}
+ public function testRotateInvalidatesOldTokenInCache(): void {
+ $oldToken = 'oldtokentokentokentokentoken';
+ $newToken = 'newtokentokentokentokentoken';
+
+ $this->cacheFactory->method('createInMemory')
+ ->willReturn(new ArrayCache());
+ $tokenProvider = new PublicKeyTokenProvider(
+ $this->mapper,
+ $this->crypto,
+ $this->config,
+ $this->db,
+ $this->logger,
+ $this->timeFactory,
+ $this->hasher,
+ $this->cacheFactory,
+ $this->eventDispatcher,
+ );
+
+ $actual = $tokenProvider->generateToken($oldToken, 'user', 'User', null, 'name', IToken::PERMANENT_TOKEN);
+ $oldHash = $actual->getToken();
+ $this->assertSame($oldHash, $tokenProvider->getToken($oldToken)->getToken());
+
+ // Only the cache knows the token after the rotation
+ $stored = true;
+ $this->mapper->method('getToken')
+ ->willReturnCallback(function (string $hash) use (&$stored, $oldHash, $actual) {
+ if ($stored && $hash === $oldHash) {
+ return $actual;
+ }
+ throw new DoesNotExistException('');
+ });
+
+ $tokenProvider->rotate($actual, $oldToken, $newToken);
+ $stored = false;
+
+ $this->assertSame($actual->getToken(), $tokenProvider->getToken($newToken)->getToken());
+
+ $this->expectException(InvalidTokenException::class);
+ $tokenProvider->getToken($oldToken);
+ }
+
+ public function testRotateStoredToken(): void {
+ $oldToken = 'oldtokentokentokentokentoken';
+ $newToken = 'newtokentokentokentokentoken';
+
+ // What the caller has, e.g. from the cache, is older than what is stored
+ $outdated = $this->tokenProvider->generateToken($oldToken, 'user', 'User', null, 'name', IToken::PERMANENT_TOKEN);
+ $stored = clone $outdated;
+ $stored->setScope([IToken::SCOPE_FILESYSTEM => false]);
+
+ $this->mapper->expects($this->once())
+ ->method('getToken')
+ ->with($outdated->getToken())
+ ->willReturn($stored);
+ $this->mapper->expects($this->once())
+ ->method('update')
+ ->with($stored);
+
+ $new = $this->tokenProvider->rotate($outdated, $oldToken, $newToken);
+
+ $this->assertSame($stored, $new);
+ $this->assertSame([IToken::SCOPE_FILESYSTEM => false], $new->getScopeAsArray());
+ }
+
+ public function testRotateDeletedToken(): void {
+ $oldToken = 'oldtokentokentokentokentoken';
+ $newToken = 'newtokentokentokentokentoken';
+
+ $actual = $this->tokenProvider->generateToken($oldToken, 'user', 'User', null, 'name', IToken::PERMANENT_TOKEN);
+
+ $this->mapper->expects($this->once())
+ ->method('getToken')
+ ->with($actual->getToken())
+ ->willThrowException(new DoesNotExistException(''));
+ $this->mapper->expects($this->never())
+ ->method('update');
+
+ $this->expectException(InvalidTokenException::class);
+ $this->tokenProvider->rotate($actual, $oldToken, $newToken);
+ }
+
+ public function testRotateTokenMarkedForWipe(): void {
+ $oldToken = 'oldtokentokentokentokentoken';
+ $newToken = 'newtokentokentokentokentoken';
+
+ $actual = $this->tokenProvider->generateToken($oldToken, 'user', 'User', null, 'name', IToken::PERMANENT_TOKEN);
+
+ $stored = clone $actual;
+ $stored->setType(IToken::WIPE_TOKEN);
+ $this->mapper->expects($this->once())
+ ->method('getToken')
+ ->with($actual->getToken())
+ ->willReturn($stored);
+ $this->mapper->expects($this->never())
+ ->method('update');
+
+ $this->expectException(WipeTokenException::class);
+ $this->tokenProvider->rotate($actual, $oldToken, $newToken);
+ }
+
public function testMarkPasswordInvalidInvalidToken(): void {
$token = $this->createMock(IToken::class);
@@ -689,4 +807,60 @@ public function testUpdatePasswords(): void {
$this->tokenProvider->updatePasswords($uid, 'bar2');
}
+
+ public function testUpdatePasswordsInvalidatesSessionsWithOutdatedPassword(): void {
+ $uid = 'myUID';
+ $this->config->method('getSystemValueBool')
+ ->willReturnMap([
+ ['auth.storeCryptedPassword', true, true],
+ ]);
+
+ $generateToken = fn (string $token, ?string $password, int $type): PublicKeyToken => $this->tokenProvider->generateToken(
+ $token . 'tokentokentokentoken',
+ $uid,
+ $uid,
+ $password,
+ $token,
+ $type,
+ );
+ $currentSession1 = $generateToken('current1', 'bar2', IToken::TEMPORARY_TOKEN);
+ $outdatedAppPassword = $generateToken('app', 'bar', IToken::PERMANENT_TOKEN);
+ $outdatedSession1 = $generateToken('outdated1', 'bar', IToken::TEMPORARY_TOKEN);
+ $currentSession2 = $generateToken('current2', 'bar2', IToken::TEMPORARY_TOKEN);
+ $currentSession2->setPasswordHash($currentSession1->getPasswordHash());
+ $outdatedSession2 = $generateToken('outdated2', 'bar', IToken::TEMPORARY_TOKEN);
+ $outdatedSession2->setPasswordHash($outdatedSession1->getPasswordHash());
+ $passwordlessSession = $generateToken('passwordless', null, IToken::TEMPORARY_TOKEN);
+
+ $this->mapper->expects($this->once())
+ ->method('getTokenByUser')
+ ->with($uid)
+ ->willReturn([
+ $currentSession1,
+ $outdatedAppPassword,
+ $outdatedSession1,
+ $currentSession2,
+ $outdatedSession2,
+ $passwordlessSession,
+ ]);
+
+ $updated = [];
+ $this->mapper->method('update')
+ ->willReturnCallback(function (PublicKeyToken $t) use (&$updated) {
+ $updated[] = $t;
+ return $t;
+ });
+ $invalidated = [];
+ $this->mapper->method('invalidate')
+ ->willReturnCallback(function (string $token) use (&$invalidated): void {
+ $invalidated[] = $token;
+ });
+
+ $this->tokenProvider->updatePasswords($uid, 'bar2');
+
+ $this->assertSame([$outdatedAppPassword, $passwordlessSession], $updated);
+ $this->assertSame([$outdatedSession1->getToken(), $outdatedSession2->getToken()], $invalidated);
+ $this->assertSame('bar2', $this->tokenProvider->getPassword($outdatedAppPassword, 'apptokentokentokentoken'));
+ $this->assertSame('bar', $this->tokenProvider->getPassword($outdatedSession1, 'outdated1tokentokentokentoken'));
+ }
}
diff --git a/tests/lib/Authentication/Token/PublicKeyTokenTest.php b/tests/lib/Authentication/Token/PublicKeyTokenTest.php
index 5f5f29c865ffa..59b567ebbef4e 100644
--- a/tests/lib/Authentication/Token/PublicKeyTokenTest.php
+++ b/tests/lib/Authentication/Token/PublicKeyTokenTest.php
@@ -26,4 +26,25 @@ public function testDefaultScope(): void {
$token = new PublicKeyToken();
$this->assertEquals($scope, $token->getScopeAsArray());
}
+
+ public function testSetNameScrubsInvalidUtf8(): void {
+ $token = new PublicKeyToken();
+ $token->setName("Spy\xff");
+
+ $this->assertTrue(mb_check_encoding($token->getName(), 'UTF-8'));
+ $this->assertStringStartsWith('Spy', $token->getName());
+ }
+
+ public function testSetNameKeepsValidUtf8(): void {
+ $token = new PublicKeyToken();
+ $token->setName('Müller’s iPhone');
+
+ $this->assertSame('Müller’s iPhone', $token->getName());
+ }
+
+ public function testStoredInvalidNameSerializesToJson(): void {
+ $token = PublicKeyToken::fromRow(['id' => 1, 'name' => "Spy\xff", 'type' => IToken::PERMANENT_TOKEN]);
+
+ $this->assertIsString(json_encode($token->jsonSerialize(), JSON_THROW_ON_ERROR));
+ }
}
diff --git a/tests/lib/Authentication/Token/RemoteWipeTest.php b/tests/lib/Authentication/Token/RemoteWipeTest.php
index b1676e90b9d99..b9f17c103cba6 100644
--- a/tests/lib/Authentication/Token/RemoteWipeTest.php
+++ b/tests/lib/Authentication/Token/RemoteWipeTest.php
@@ -75,7 +75,7 @@ public function testMarkAllTokensForWipeNoWipeableToken(): void {
$token1 = $this->createMock(IToken::class);
$token2 = $this->createMock(IToken::class);
$this->tokenProvider->expects($this->once())
- ->method('getTokenByUser')
+ ->method('getAllTokensByUser')
->with('user123')
->willReturn([$token1, $token2]);
@@ -91,7 +91,7 @@ public function testMarkAllTokensForWipe(): void {
$token1 = $this->createMock(IToken::class);
$token2 = $this->createMock(IWipeableToken::class);
$this->tokenProvider->expects($this->once())
- ->method('getTokenByUser')
+ ->method('getAllTokensByUser')
->with('user123')
->willReturn([$token1, $token2]);
$token2->expects($this->once())
diff --git a/tests/lib/Search/SearchComposerTest.php b/tests/lib/Search/SearchComposerTest.php
index f8cf1410fad0f..6cce0344c779b 100644
--- a/tests/lib/Search/SearchComposerTest.php
+++ b/tests/lib/Search/SearchComposerTest.php
@@ -14,6 +14,7 @@
use OC\AppFramework\Bootstrap\RegistrationContext;
use OC\AppFramework\Bootstrap\ServiceRegistration;
use OC\Search\SearchComposer;
+use OCP\App\IAppManager;
use OCP\IAppConfig;
use OCP\IURLGenerator;
use OCP\IUser;
@@ -31,7 +32,12 @@ class SearchComposerTest extends TestCase {
private IURLGenerator&MockObject $urlGenerator;
private LoggerInterface&MockObject $logger;
private IAppConfig&MockObject $appConfig;
+ private IAppManager&MockObject $appManager;
private SearchComposer $searchComposer;
+ private IUser $user;
+
+ /** @var list */
+ private array $appsDisabledForUser = [];
protected function setUp(): void {
parent::setUp();
@@ -41,16 +47,21 @@ protected function setUp(): void {
$this->urlGenerator = $this->createMock(IURLGenerator::class);
$this->logger = $this->createMock(LoggerInterface::class);
$this->appConfig = $this->createMock(IAppConfig::class);
+ $this->appManager = $this->createMock(IAppManager::class);
+ $this->user = $this->createMock(IUser::class);
$this->searchComposer = new SearchComposer(
$this->bootstrapCoordinator,
$this->container,
$this->urlGenerator,
$this->logger,
- $this->appConfig
+ $this->appConfig,
+ $this->appManager,
);
$this->setupUrlGenerator();
+ $this->appManager->method('isEnabledForUser')
+ ->willReturnCallback(fn (string $appId, ?IUser $user): bool => $user === $this->user && !in_array($appId, $this->appsDisabledForUser, true));
}
private function setupUrlGenerator(): void {
@@ -118,7 +129,7 @@ private function setupRegistrationContextWithProviders(array $registrations): vo
public function testGetProvidersWithNoRegisteredProviders(): void {
$this->setupEmptyRegistrationContext();
- $providers = $this->searchComposer->getProviders('/test/route', []);
+ $providers = $this->searchComposer->getProviders($this->user, '/test/route', []);
$this->assertIsArray($providers);
$this->assertEmpty($providers);
@@ -147,7 +158,7 @@ public function testGetProvidersWithMultipleProviders(): void {
$this->setupRegistrationContextWithProviders($mockData['registrations']);
$this->setupAppConfigForAllowedProviders();
- $providers = $this->searchComposer->getProviders('/test/route', []);
+ $providers = $this->searchComposer->getProviders($this->user, '/test/route', []);
$this->assertProvidersStructureAndSorting($providers, [
['id' => 'provider2', 'name' => 'Provider provider2', 'appId' => 'app2', 'order' => 5, 'inAppSearch' => false],
@@ -166,7 +177,7 @@ public function testGetProvidersWithEmptyAllowedProvidersConfiguration(): void {
$this->setupRegistrationContextWithProviders($mockData['registrations']);
$this->setupAppConfigForAllowedProviders();
- $providers = $this->searchComposer->getProviders('/test/route', []);
+ $providers = $this->searchComposer->getProviders($this->user, '/test/route', []);
$this->assertCount(2, $providers);
$this->assertProvidersAreSortedByOrder($providers);
@@ -186,7 +197,7 @@ public function testGetProvidersWithAllowedProvidersRestriction(): void {
$this->setupRegistrationContextWithProviders($mockData['registrations']);
$this->setupAppConfigForAllowedProviders(['provider1', 'provider3']);
- $providers = $this->searchComposer->getProviders('/test/route', []);
+ $providers = $this->searchComposer->getProviders($this->user, '/test/route', []);
$this->assertProvidersStructureAndSorting($providers, [
['id' => 'provider1', 'name' => 'Provider provider1', 'appId' => 'app1', 'order' => 10, 'inAppSearch' => false],
@@ -209,7 +220,7 @@ public function testGetProvidersFiltersByAllowedProvidersCompletely(): void {
$this->setupRegistrationContextWithProviders($mockData['registrations']);
$this->setupAppConfigForAllowedProviders(['provider_not_exists']);
- $providers = $this->searchComposer->getProviders('/test/route', []);
+ $providers = $this->searchComposer->getProviders($this->user, '/test/route', []);
$this->assertIsArray($providers);
$this->assertEmpty($providers);
@@ -226,7 +237,7 @@ public function testGetProvidersWithMixedOrderValues(): void {
$this->setupRegistrationContextWithProviders($mockData['registrations']);
$this->setupAppConfigForAllowedProviders();
- $providers = $this->searchComposer->getProviders('/test/route', []);
+ $providers = $this->searchComposer->getProviders($this->user, '/test/route', []);
$this->assertCount(3, $providers);
$this->assertProvidersAreSortedByOrder($providers);
@@ -237,6 +248,43 @@ public function testGetProvidersWithMixedOrderValues(): void {
$this->assertEquals('provider1', $providers[2]['id']);
}
+ public function testGetProvidersHidesProvidersOfAppsNotEnabledForUser(): void {
+ $providerConfigs = [
+ 'provider1' => ['service' => 'provider1_service', 'appId' => 'app1', 'order' => 10],
+ 'provider2' => ['service' => 'provider2_service', 'appId' => 'app2', 'order' => 5],
+ ];
+
+ $mockData = $this->createMockProvidersAndRegistrations($providerConfigs);
+ $this->setupRegistrationContextWithProviders($mockData['registrations']);
+ $this->setupAppConfigForAllowedProviders();
+ $this->appsDisabledForUser = ['app2'];
+
+ $mockData['providers']['provider2']->expects($this->never())->method('getOrder');
+
+ $providers = $this->searchComposer->getProviders($this->user, '/test/route', []);
+
+ $this->assertSame(['provider1'], array_column($providers, 'id'));
+ }
+
+ public function testSearchReturnsNoResultsForAppNotEnabledForUser(): void {
+ $providerConfigs = [
+ 'provider1' => ['service' => 'provider1_service', 'appId' => 'app1', 'order' => 10],
+ ];
+
+ $mockData = $this->createMockProvidersAndRegistrations($providerConfigs);
+ $this->setupRegistrationContextWithProviders($mockData['registrations']);
+ $this->setupAppConfigForAllowedProviders();
+ $this->appsDisabledForUser = ['app1'];
+
+ $mockData['providers']['provider1']->expects($this->never())->method('search');
+
+ $result = $this->searchComposer->search($this->user, 'provider1', $this->createMock(ISearchQuery::class));
+
+ $this->assertSame([], $result->jsonSerialize()['entries']);
+ $this->assertFalse($result->jsonSerialize()['isPaginated']);
+ }
+
+
public function testProviderIconGeneration(): void {
$providerConfigs = [
'provider1' => ['service' => 'provider1_service', 'appId' => 'app1', 'order' => 10],
@@ -246,7 +294,7 @@ public function testProviderIconGeneration(): void {
$this->setupRegistrationContextWithProviders($mockData['registrations']);
$this->setupAppConfigForAllowedProviders();
- $providers = $this->searchComposer->getProviders('/test/route', []);
+ $providers = $this->searchComposer->getProviders($this->user, '/test/route', []);
$this->assertCount(1, $providers);
$this->assertArrayHasKey('icon', $providers[0]);
diff --git a/tests/lib/Security/Bruteforce/ThrottlerTest.php b/tests/lib/Security/Bruteforce/ThrottlerTest.php
new file mode 100644
index 0000000000000..7c06ea4b613a3
--- /dev/null
+++ b/tests/lib/Security/Bruteforce/ThrottlerTest.php
@@ -0,0 +1,55 @@
+createMock(IConfig::class);
+ $config->method('getSystemValueBool')
+ ->with('auth.bruteforce.protection.enabled', true)
+ ->willReturn(true);
+ $allowList = $this->createMock(BruteforceAllowList::class);
+ $allowList->method('isBypassListed')
+ ->with('10.10.10.10')
+ ->willReturn(false);
+
+ // Only the attempts matching the metadata are removed,
+ // so the remaining ones of the action still have to be counted
+ $backend = $this->createMock(IBackend::class);
+ $backend->expects($this->once())
+ ->method('resetAttempts')
+ ->with('10.10.10.10/32', 'login', ['user' => 'bob']);
+ $backend->expects($this->once())
+ ->method('getAttempts')
+ ->with('10.10.10.10/32', $this->anything(), 'login')
+ ->willReturn(11);
+
+ $throttler = new Throttler(
+ $this->createMock(ITimeFactory::class),
+ $this->createMock(LoggerInterface::class),
+ $config,
+ $backend,
+ $allowList,
+ $this->createMock(IEventDispatcher::class),
+ );
+
+ $throttler->resetDelay('10.10.10.10', 'login', ['user' => 'bob']);
+ $this->assertSame(11, $throttler->getAttempts('10.10.10.10', 'login'));
+ }
+}
diff --git a/tests/lib/User/SessionTest.php b/tests/lib/User/SessionTest.php
index 1832a9c1001c1..dde503ba6c391 100644
--- a/tests/lib/User/SessionTest.php
+++ b/tests/lib/User/SessionTest.php
@@ -654,6 +654,8 @@ public function testTryTokenLoginNotAnAppPassword(): void {
->method('getToken')
->with('abcde12345')
->willReturn($dbToken);
+ $this->session->expects(self::never())
+ ->method('clear');
$this->session->method('set')
->willReturnCallback(function ($key, $value): void {
if ($key === 'app_password') {
@@ -671,6 +673,64 @@ public function testTryTokenLoginNotAnAppPassword(): void {
self::assertTrue($loginResult);
}
+ private function mockAppPasswordLogin(?string $sessionCookie): IRequest {
+ $request = $this->createMock(IRequest::class);
+ $request->method('getHeader')->with('Authorization')->willReturn('Bearer app-token');
+ $this->config->method('getSystemValueString')->with('instanceid')->willReturn('abc123');
+ $request->method('getCookie')->with('abc123')->willReturn($sessionCookie);
+ $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);
+ $user = $this->createMock(IUser::class);
+ $user->method('isEnabled')->willReturn(true);
+ $this->manager->method('get')
+ ->with('alice')
+ ->willReturn($user);
+ return $request;
+ }
+
+ public function testTryTokenLoginAuthorizationHeaderClearsClientSessionFirst(): void {
+ $request = $this->mockAppPasswordLogin('client-chosen-id');
+
+ $cleared = false;
+ $this->session->expects($this->once())
+ ->method('clear')
+ ->willReturnCallback(function () use (&$cleared): void {
+ $cleared = true;
+ });
+ $assertCleared = function () use (&$cleared): void {
+ $this->assertTrue($cleared);
+ };
+ $this->session->method('set')->willReturnCallback($assertCleared);
+ $this->dispatcher->method('dispatchTyped')->willReturnCallback($assertCleared);
+
+ $this->assertTrue($this->userSession->tryTokenLogin($request));
+ }
+
+ public function testTryTokenLoginAuthorizationHeaderKeepsSessionOfSameAppPassword(): void {
+ $request = $this->mockAppPasswordLogin('own-session-id');
+ $this->session->method('get')
+ ->willReturnMap([['app_password', 'app-token']]);
+ $this->session->expects($this->never())
+ ->method('clear');
+
+ $this->assertTrue($this->userSession->tryTokenLogin($request));
+ }
+
+ public function testTryTokenLoginAuthorizationHeaderWithoutSessionCookieKeepsSession(): void {
+ $request = $this->mockAppPasswordLogin(null);
+ $this->session->expects($this->never())
+ ->method('clear');
+
+ $this->assertTrue($this->userSession->tryTokenLogin($request));
+ }
+
public function testRememberLoginValidToken(): void {
$session = $this->createMock(Memory::class);
$managerMethods = get_class_methods(Manager::class);