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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion apps/oauth2/lib/Controller/LoginRedirectorController.php
Original file line number Diff line number Diff line change
Expand Up @@ -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 **/
Expand Down
4 changes: 0 additions & 4 deletions apps/oauth2/lib/Controller/OauthApiController.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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,
Expand Down Expand Up @@ -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',
Expand Down
2 changes: 1 addition & 1 deletion apps/oauth2/lib/Service/ClientService.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
10 changes: 5 additions & 5 deletions apps/oauth2/tests/Controller/LoginRedirectorControllerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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')
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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')
Expand Down Expand Up @@ -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')
Expand Down
41 changes: 0 additions & 41 deletions apps/oauth2/tests/Controller/OauthApiControllerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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;
Expand All @@ -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);
Expand All @@ -89,7 +86,6 @@ protected function setUp(): void {
$this->secureRandom,
$this->time,
$this->logger,
$this->throttler,
$this->timeFactory,
$this->db,
$this->globalScaleConfig,
Expand Down Expand Up @@ -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'));
}

Expand Down Expand Up @@ -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));
}

Expand Down Expand Up @@ -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'));
}

Expand Down Expand Up @@ -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'));
}

Expand Down Expand Up @@ -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;
}
Expand Down
6 changes: 3 additions & 3 deletions apps/oauth2/tests/Service/ClientServiceTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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())
Expand Down Expand Up @@ -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]
Expand Down
8 changes: 8 additions & 0 deletions apps/settings/lib/Controller/WebAuthnController.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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);
Expand Down
68 changes: 68 additions & 0 deletions apps/settings/tests/Controller/WebAuthnControllerTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
<?php

declare(strict_types=1);

/**
* SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/

namespace OCA\Settings\Tests\Controller;

use OC\Authentication\WebAuthn\Manager;
use OCA\Settings\Controller\WebAuthnController;
use OCP\AppFramework\Http;
use OCP\IRequest;
use OCP\ISession;
use OCP\IUser;
use OCP\IUserSession;
use PHPUnit\Framework\MockObject\MockObject;
use Psr\Log\LoggerInterface;
use Test\TestCase;

class WebAuthnControllerTest extends TestCase {
private Manager&MockObject $manager;
private IUserSession&MockObject $userSession;
private ISession&MockObject $session;
private WebAuthnController $controller;

protected function setUp(): void {
parent::setUp();

$this->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);
}
}
10 changes: 6 additions & 4 deletions apps/testing/appinfo/info.xml
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,15 @@
<types>
<authentication/>
</types>

<commands>
<command>OCA\Testing\Command\ResetTokenLastCheck</command>
<command>OCA\Testing\Command\SetUnencryptedSize</command>
</commands>

<category>monitoring</category>
<bugs>https://github.com/nextcloud/server/issues</bugs>
<dependencies>
<nextcloud min-version="34" max-version="34"/>
</dependencies>

<commands>
<command>OCA\Testing\Command\SetUnencryptedSize</command>
</commands>
</info>
1 change: 1 addition & 0 deletions apps/testing/composer/composer/autoload_classmap.php
Original file line number Diff line number Diff line change
Expand Up @@ -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',
Expand Down
1 change: 1 addition & 0 deletions apps/testing/composer/composer/autoload_static.php
Original file line number Diff line number Diff line change
Expand Up @@ -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',
Expand Down
47 changes: 47 additions & 0 deletions apps/testing/lib/Command/ResetTokenLastCheck.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
<?php

declare(strict_types=1);

/**
* SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/

namespace OCA\Testing\Command;

use OCP\IDBConnection;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

/**
* Make the periodic credential check of all auth tokens of a user due, so
* that the next request with one of them checks its stored password again.
*/
class ResetTokenLastCheck extends Command {
public function __construct(
private IDBConnection $db,
) {
parent::__construct();
}

#[\Override]
protected function configure(): void {
$this
->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;
}
}
Loading
Loading