Files
nextcloud-server-mirror/apps/settings/tests/Controller/AuthSettingsControllerTest.php
Peter R. 7cb5127db4 Merge pull request #65940 from nextcloud/feat/noid/app-password-app-grants
feat(auth): let app passwords be limited to whole apps
2026-11-19 17:28:46 +01:00

995 lines
33 KiB
PHP

<?php
/**
* SPDX-FileCopyrightText: 2019-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
* SPDX-License-Identifier: AGPL-3.0-only
*/
namespace Test\Settings\Controller;
use OC\AppFramework\Http;
use OC\Authentication\Exceptions\ExpiredTokenException;
use OC\Authentication\Exceptions\InvalidTokenException;
use OC\Authentication\Token\GrantableApps;
use OC\Authentication\Token\IProvider;
use OC\Authentication\Token\IToken;
use OC\Authentication\Token\IWipeableToken;
use OC\Authentication\Token\PublicKeyToken;
use OC\Authentication\Token\RemoteWipe;
use OC\Authentication\Token\TokenScopes;
use OCA\Files\TokenScopes as FilesTokenScopes;
use OCA\Files_Sharing\TokenScopes as SharingTokenScopes;
use OCA\Settings\Activity\Provider;
use OCA\Settings\Controller\AuthSettingsController;
use OCP\Activity\IEvent;
use OCP\Activity\IManager;
use OCP\AppFramework\Http\Attribute\PasswordConfirmationRequired;
use OCP\AppFramework\Http\JSONResponse;
use OCP\AppFramework\Services\IAppConfig;
use OCP\Authentication\Exceptions\WipeTokenException;
use OCP\EventDispatcher\IEventDispatcher;
use OCP\IConfig;
use OCP\IL10N;
use OCP\IRequest;
use OCP\ISession;
use OCP\IUserSession;
use OCP\Log\Audit\CriticalActionPerformedEvent;
use OCP\Security\ISecureRandom;
use OCP\Session\Exceptions\SessionNotAvailableException;
use PHPUnit\Framework\MockObject\MockObject;
use Psr\Log\LoggerInterface;
use Test\TestCase;
class AuthSettingsControllerTest extends TestCase {
private IRequest&MockObject $request;
private IProvider&MockObject $tokenProvider;
private ISession&MockObject $session;
private IUserSession&MockObject $userSession;
private ISecureRandom&MockObject $secureRandom;
private IManager&MockObject $activityManager;
private IAppConfig&MockObject $appConfig;
private RemoteWipe&MockObject $remoteWipe;
private IConfig&MockObject $serverConfig;
private IL10N&MockObject $l;
private IEventDispatcher&MockObject $eventDispatcher;
private GrantableApps&MockObject $grantableApps;
private string $uid = 'jane';
private AuthSettingsController $controller;
protected function setUp(): void {
parent::setUp();
$this->request = $this->createMock(IRequest::class);
$this->tokenProvider = $this->createMock(IProvider::class);
$this->session = $this->createMock(ISession::class);
$this->userSession = $this->createMock(IUserSession::class);
$this->secureRandom = $this->createMock(ISecureRandom::class);
$this->activityManager = $this->createMock(IManager::class);
$this->appConfig = $this->createMock(IAppConfig::class);
$this->remoteWipe = $this->createMock(RemoteWipe::class);
$this->serverConfig = $this->createMock(IConfig::class);
/** @var LoggerInterface&MockObject $logger */
$logger = $this->createMock(LoggerInterface::class);
$this->l = $this->createMock(IL10N::class);
$this->eventDispatcher = $this->createMock(IEventDispatcher::class);
$this->grantableApps = $this->createMock(GrantableApps::class);
$this->grantableApps->method('getAppIds')->willReturn(['deck']);
$this->controller = new AuthSettingsController(
'core',
$this->request,
$this->tokenProvider,
$this->session,
$this->secureRandom,
$this->uid,
$this->userSession,
$this->activityManager,
$this->appConfig,
$this->remoteWipe,
$logger,
$this->serverConfig,
$this->l,
new TokenScopes(),
$this->eventDispatcher,
$this->grantableApps,
);
}
public static function dataCreate(): array {
return [
'plain name' => ['Nexus 4', 'Nexus 4'],
'surrounding whitespace' => [' Nexus 4 ', 'Nexus 4'],
];
}
#[\PHPUnit\Framework\Attributes\DataProvider(methodName: 'dataCreate')]
public function testCreate(string $name, string $expectedName): void {
$sessionToken = $this->createMock(IToken::class);
$deviceToken = $this->createMock(IToken::class);
$password = '123456';
$this->serverConfig->method('getSystemValueBool')
->with('auth_can_create_app_token', true)
->willReturn(true);
$this->session->expects($this->once())
->method('getId')
->willReturn('sessionid');
$this->tokenProvider->expects($this->once())
->method('getToken')
->with('sessionid')
->willReturn($sessionToken);
$this->tokenProvider->expects($this->once())
->method('getPassword')
->with($sessionToken, 'sessionid')
->willReturn($password);
$sessionToken->expects($this->once())
->method('getLoginName')
->willReturn('User13');
$this->secureRandom->expects($this->exactly(5))
->method('generate')
->with(5, ISecureRandom::CHAR_HUMAN_READABLE)
->willReturn('XXXXX');
$newToken = 'XXXXX-XXXXX-XXXXX-XXXXX-XXXXX';
$this->tokenProvider->expects($this->once())
->method('generateToken')
->with($newToken, $this->uid, 'User13', $password, $expectedName, IToken::PERMANENT_TOKEN)
->willReturn($deviceToken);
$deviceToken->expects($this->once())
->method('jsonSerialize')
->willReturn(['dummy' => 'dummy', 'canDelete' => true]);
$deviceToken->method('getId')->willReturn(7);
$deviceToken->method('getName')->willReturn($name);
$this->mockActivityManager();
$this->expectAuditEvent('auth.app_password.created', ['tokenId' => 7, 'tokenName' => $name], 'App password with ID "%s" and name "%s" was created');
$expected = [
'token' => $newToken,
'deviceToken' => ['dummy' => 'dummy', 'canDelete' => true, 'canRename' => true],
'loginName' => 'User13',
];
$response = $this->controller->create($name);
$this->assertInstanceOf(JSONResponse::class, $response);
$this->assertEquals($expected, $response->getData());
}
public static function dataCreateWithScopes(): array {
$files = [SharingTokenScopes::SHARES_WRITE, FilesTokenScopes::FILES_READ, FilesTokenScopes::FILES_WRITE];
$sorted = [FilesTokenScopes::FILES_READ, FilesTokenScopes::FILES_WRITE, SharingTokenScopes::SHARES_WRITE];
return [
'files' => [$files, [TokenScopes::KEY => $sorted, IToken::SCOPE_FILESYSTEM => true]],
'calendar' => [['dav:calendar:read'], [TokenScopes::KEY => ['dav:calendar:read'], IToken::SCOPE_FILESYSTEM => false]],
'whole app' => [['deck'], [TokenScopes::KEY => ['deck'], IToken::SCOPE_FILESYSTEM => false]],
];
}
#[\PHPUnit\Framework\Attributes\DataProvider(methodName: 'dataCreateWithScopes')]
public function testCreateWithScopes(array $scopes, array $expectedScope): void {
$this->mockSessionForCreate();
$deviceToken = $this->createMock(IToken::class);
$deviceToken->method('jsonSerialize')->willReturn([]);
$this->tokenProvider->expects($this->once())
->method('generateToken')
->with($this->anything(), $this->uid, 'User13', '123456', 'Nexus 4', IToken::PERMANENT_TOKEN, IToken::DO_NOT_REMEMBER, $expectedScope)
->willReturn($deviceToken);
$this->mockActivityManager();
$response = $this->controller->create('Nexus 4', false, $scopes);
$this->assertSame(Http::STATUS_OK, $response->getStatus());
}
public function testCreateInvalidScopes(): void {
$this->mockSessionForCreate();
$this->tokenProvider->expects($this->never())->method('generateToken');
$response = $this->controller->create('Nexus 4', false, [FilesTokenScopes::FILES_WRITE]);
$this->assertSame(Http::STATUS_BAD_REQUEST, $response->getStatus());
$this->assertSame(['message' => 'Files scopes require ' . FilesTokenScopes::FILES_READ], $response->getData());
}
public function testCreateDisabledBySystemConfig(): void {
$name = 'Nexus 4';
$this->serverConfig->method('getSystemValueBool')
->with('auth_can_create_app_token', true)
->willReturn(false);
$this->session->expects($this->once())
->method('getId')
->willReturn('sessionid');
$this->tokenProvider->expects($this->never())
->method('getToken');
$this->tokenProvider->expects($this->never())
->method('getPassword');
$this->tokenProvider->expects($this->never())
->method('generateToken');
$expected = new JSONResponse();
$expected->setStatus(Http::STATUS_SERVICE_UNAVAILABLE);
$this->assertEquals($expected, $this->controller->create($name));
}
public function testCreateWhitespaceName(): void {
$sessionToken = $this->createMock(IToken::class);
$this->serverConfig->method('getSystemValueBool')
->with('auth_can_create_app_token', true)
->willReturn(true);
$this->session->expects($this->once())
->method('getId')
->willReturn('sessionid');
$this->tokenProvider->expects($this->once())
->method('getToken')
->with('sessionid')
->willReturn($sessionToken);
$this->tokenProvider->expects($this->once())
->method('getPassword')
->with($sessionToken, 'sessionid')
->willReturn('123456');
$sessionToken->expects($this->once())
->method('getLoginName')
->willReturn('User13');
$this->tokenProvider->expects($this->never())
->method('generateToken');
$expected = new JSONResponse();
$expected->setStatus(Http::STATUS_SERVICE_UNAVAILABLE);
$this->assertEquals($expected, $this->controller->create(' '));
}
public function testCreateSessionNotAvailable(): void {
$name = 'personal phone';
$this->session->expects($this->once())
->method('getId')
->willThrowException(new SessionNotAvailableException());
$expected = new JSONResponse();
$expected->setStatus(Http::STATUS_SERVICE_UNAVAILABLE);
$this->assertEquals($expected, $this->controller->create($name));
}
public function testCreateInvalidToken(): void {
$name = 'Company IPhone';
$this->serverConfig->method('getSystemValueBool')
->with('auth_can_create_app_token', true)
->willReturn(true);
$this->session->expects($this->once())
->method('getId')
->willReturn('sessionid');
$this->tokenProvider->expects($this->once())
->method('getToken')
->with('sessionid')
->willThrowException(new InvalidTokenException());
$expected = new JSONResponse();
$expected->setStatus(Http::STATUS_SERVICE_UNAVAILABLE);
$this->assertEquals($expected, $this->controller->create($name));
}
public function testDestroy(): void {
$tokenId = 124;
$token = $this->createMock(PublicKeyToken::class);
$this->mockGetTokenById($tokenId, $token);
$this->mockActivityManager();
$token->expects($this->once())
->method('getId')
->willReturn($tokenId);
$token->expects($this->once())
->method('getUID')
->willReturn('jane');
$this->tokenProvider->expects($this->once())
->method('invalidateTokenById')
->with($this->uid, $tokenId);
$this->expectAuditEvent('auth.app_password.deleted', ['tokenId' => $tokenId], 'App password with ID "%s" was deleted');
$this->assertEquals([], $this->controller->destroy($tokenId)->getData());
}
public function testDestroyExpired(): void {
$tokenId = 124;
$token = $this->createMock(PublicKeyToken::class);
$token->expects($this->once())
->method('getId')
->willReturn($tokenId);
$token->expects($this->once())
->method('getUID')
->willReturn($this->uid);
$this->tokenProvider->expects($this->once())
->method('getTokenById')
->with($this->equalTo($tokenId))
->willThrowException(new ExpiredTokenException($token));
$this->tokenProvider->expects($this->once())
->method('invalidateTokenById')
->with($this->uid, $tokenId);
$this->assertSame([], $this->controller->destroy($tokenId)->getData());
}
public function testDestroyWipePendingEmitsCancelledSubject(): void {
$tokenId = 125;
$token = $this->createMock(PublicKeyToken::class);
$token->method('getId')->willReturn($tokenId);
$token->method('getName')->willReturn('My phone');
$this->tokenProvider->expects($this->once())
->method('getTokenById')
->with($tokenId)
->willThrowException(new WipeTokenException($token));
// The token is still invalidated (the user opted into cancelling the wipe).
$this->tokenProvider->expects($this->once())
->method('invalidateTokenById')
->with($this->uid, $tokenId);
// Activity event must use the distinguishing subject.
$event = $this->createMock(IEvent::class);
$event->method('setApp')->willReturnSelf();
$event->method('setType')->willReturnSelf();
$event->method('setAffectedUser')->willReturnSelf();
$event->method('setAuthor')->willReturnSelf();
$event->method('setObject')->willReturnSelf();
$event->expects($this->once())
->method('setSubject')
->with(\OCA\Settings\Activity\Provider::APP_TOKEN_DELETED_WIPE_CANCELLED, ['name' => 'My phone'])
->willReturnSelf();
$this->activityManager->expects($this->once())
->method('generateEvent')
->willReturn($event);
$this->activityManager->expects($this->once())
->method('publish');
$this->assertEquals([], $this->controller->destroy($tokenId)->getData());
}
public function testDestroyOthersRevokesEveryTokenButTheCurrent(): void {
$currentToken = $this->mockAuthToken(10);
$otherToken = $this->mockAuthToken(11);
$appPassword = $this->mockAuthToken(12);
$this->session->method('getId')->willReturn('sessionid');
$this->tokenProvider->expects($this->once())
->method('getToken')
->with('sessionid')
->willReturn($currentToken);
$this->tokenProvider->expects($this->once())
->method('getTokenByUser')
->with($this->uid)
->willReturn([$currentToken, $otherToken, $appPassword]);
$revokedIds = [];
$this->tokenProvider->expects($this->exactly(2))
->method('invalidateTokenById')
->willReturnCallback(function (string $uid, int $id) use (&$revokedIds): void {
$this->assertSame($this->uid, $uid);
$revokedIds[] = $id;
});
$this->mockActivityManager();
$auditedIds = [];
$this->eventDispatcher->expects($this->exactly(2))
->method('dispatchTyped')
->willReturnCallback(function (CriticalActionPerformedEvent $event) use (&$auditedIds): void {
$this->assertSame('auth.app_password.deleted', $event->getOperation());
$auditedIds[] = $event->getParameters()['tokenId'];
});
$response = $this->controller->destroyOthers();
$this->assertSame([11, 12], $auditedIds);
$this->assertSame([11, 12], $revokedIds, 'the current session token must not be revoked');
$this->assertSame(['revoked' => [11, 12]], $response->getData());
}
public function testDestroyOthersKeepsWipePendingTokens(): void {
$currentToken = $this->mockAuthToken(10);
$otherToken = $this->mockAuthToken(11);
$wipingToken = $this->mockAuthToken(12, IToken::WIPE_TOKEN);
$this->session->method('getId')->willReturn('sessionid');
$this->tokenProvider->method('getToken')->willReturn($currentToken);
$this->tokenProvider->method('getTokenByUser')->willReturn([$currentToken, $otherToken, $wipingToken]);
$this->tokenProvider->expects($this->once())
->method('invalidateTokenById')
->with($this->uid, 11);
$this->mockActivityManager();
$this->assertSame(['revoked' => [11]], $this->controller->destroyOthers()->getData());
}
public function testDestroyOthersPublishesOneAggregateActivity(): void {
$currentToken = $this->mockAuthToken(10);
$this->session->method('getId')->willReturn('sessionid');
$this->tokenProvider->method('getToken')->willReturn($currentToken);
$this->tokenProvider->method('getTokenByUser')
->willReturn([$currentToken, $this->mockAuthToken(11), $this->mockAuthToken(12)]);
$event = $this->createMock(IEvent::class);
$event->method('setApp')->willReturnSelf();
$event->method('setType')->willReturnSelf();
$event->method('setAffectedUser')->willReturnSelf();
$event->method('setAuthor')->willReturnSelf();
$event->expects($this->once())
->method('setSubject')
->with(Provider::APP_TOKEN_DELETED_ALL, ['count' => 2])
->willReturnSelf();
// Aggregate event, so there is no single app_token to attach.
$event->expects($this->never())
->method('setObject');
$this->activityManager->expects($this->once())
->method('generateEvent')
->willReturn($event);
$this->activityManager->expects($this->once())
->method('publish');
$this->controller->destroyOthers();
}
public function testDestroyOthersWithNothingToRevokePublishesNoActivity(): void {
$currentToken = $this->mockAuthToken(10);
$this->session->method('getId')->willReturn('sessionid');
$this->tokenProvider->method('getToken')->willReturn($currentToken);
$this->tokenProvider->method('getTokenByUser')->willReturn([$currentToken]);
$this->tokenProvider->expects($this->never())->method('invalidateTokenById');
$this->activityManager->expects($this->never())->method('publish');
$this->assertSame(['revoked' => []], $this->controller->destroyOthers()->getData());
}
public function testDestroyOthersWithAppPassword(): void {
$this->session->expects($this->once())
->method('exists')
->with('app_password')
->willReturn(true);
$this->tokenProvider->expects($this->never())->method('invalidateTokenById');
$response = $this->controller->destroyOthers();
$this->assertSame(Http::STATUS_BAD_REQUEST, $response->getStatus());
}
public function testDestroyOthersWhileImpersonating(): void {
$this->userSession->method('getImpersonatingUserID')->willReturn('admin');
$this->tokenProvider->expects($this->never())->method('invalidateTokenById');
$response = $this->controller->destroyOthers();
$this->assertSame(Http::STATUS_SERVICE_UNAVAILABLE, $response->getStatus());
}
public function testDestroyOthersSessionNotAvailable(): void {
$this->session->method('getId')
->willThrowException(new SessionNotAvailableException());
$this->tokenProvider->expects($this->never())->method('invalidateTokenById');
$response = $this->controller->destroyOthers();
$this->assertSame(Http::STATUS_SERVICE_UNAVAILABLE, $response->getStatus());
}
public function testDestroyOthersInvalidSessionToken(): void {
$this->session->method('getId')->willReturn('sessionid');
$this->tokenProvider->method('getToken')
->willThrowException(new InvalidTokenException('Token does not exist'));
$this->tokenProvider->expects($this->never())->method('invalidateTokenById');
$response = $this->controller->destroyOthers();
$this->assertSame(Http::STATUS_SERVICE_UNAVAILABLE, $response->getStatus());
}
public function testDestroyWrongUser(): void {
$tokenId = 124;
$token = $this->createMock(PublicKeyToken::class);
$this->mockGetTokenById($tokenId, $token);
$token->expects($this->once())
->method('getUID')
->willReturn('foobar');
$response = $this->controller->destroy($tokenId);
$this->assertSame([], $response->getData());
$this->assertSame(\OCP\AppFramework\Http::STATUS_NOT_FOUND, $response->getStatus());
}
public static function dataRenameToken(): array {
return [
'App password => Other token name' => ['App password', 'Other token name', 'Other token name'],
'Other token name => App password' => ['Other token name', 'App password', 'App password'],
'surrounding whitespace is trimmed' => ['App password', ' Other token name ', 'Other token name'],
];
}
#[\PHPUnit\Framework\Attributes\DataProvider(methodName: 'dataRenameToken')]
public function testUpdateRename(string $name, string $newName, string $expectedName): void {
$tokenId = 42;
$token = $this->createMock(PublicKeyToken::class);
$this->mockGetTokenById($tokenId, $token);
$this->mockActivityManager();
$token->expects($this->once())
->method('getUID')
->willReturn('jane');
$token->expects($this->once())
->method('getName')
->willReturn($name);
$token->expects($this->once())
->method('getScopeAsArray')
->willReturn([IToken::SCOPE_FILESYSTEM => true]);
$token->expects($this->once())
->method('setName')
->with($this->equalTo($expectedName));
$this->tokenProvider->expects($this->once())
->method('updateToken')
->with($this->equalTo($token));
$this->assertSame(['scope' => [IToken::SCOPE_FILESYSTEM => true]], $this->controller->update($tokenId, [IToken::SCOPE_FILESYSTEM => true], $newName)->getData());
}
public static function dataRenameTokenToEmptyName(): array {
return [
'empty name' => [''],
'whitespace only' => [' '],
];
}
#[\PHPUnit\Framework\Attributes\DataProvider(methodName: 'dataRenameTokenToEmptyName')]
public function testUpdateRenameToEmptyName(string $newName): void {
$tokenId = 42;
$token = $this->createMock(PublicKeyToken::class);
$this->mockGetTokenById($tokenId, $token);
$token->expects($this->once())
->method('getUID')
->willReturn('jane');
$token->expects($this->once())
->method('getName')
->willReturn('App password');
$token->expects($this->never())
->method('setName');
$token->expects($this->never())
->method('setScope');
$this->tokenProvider->expects($this->never())
->method('updateToken');
$this->activityManager->expects($this->never())
->method('publish');
$response = $this->controller->update($tokenId, [IToken::SCOPE_FILESYSTEM => false], $newName);
$this->assertSame(Http::STATUS_BAD_REQUEST, $response->getStatus());
}
public function testUpdateScopeOfTokenWithEmptyName(): void {
$tokenId = 42;
$token = $this->createMock(PublicKeyToken::class);
$this->mockGetTokenById($tokenId, $token);
$this->mockActivityManager();
$token->expects($this->once())
->method('getUID')
->willReturn('jane');
$token->expects($this->once())
->method('getName')
->willReturn('');
$token->expects($this->once())
->method('getScopeAsArray')
->willReturn([IToken::SCOPE_FILESYSTEM => true]);
$token->expects($this->once())
->method('setScope')
->with($this->equalTo([IToken::SCOPE_FILESYSTEM => false]));
$this->tokenProvider->expects($this->once())
->method('updateToken')
->with($this->equalTo($token));
$token->method('getId')->willReturn($tokenId);
$this->expectAuditEvent(
'auth.app_password.scope_changed',
['tokenId' => $tokenId, 'filesystemAccess' => 'revoked'],
'Filesystem access of app password with ID "%s" was %s',
);
$this->assertSame(['scope' => [IToken::SCOPE_FILESYSTEM => false]], $this->controller->update($tokenId, [IToken::SCOPE_FILESYSTEM => false], '')->getData());
}
public static function dataUpdateFilesystemScope(): array {
return [
'Grant filesystem access' => [false, true],
'Revoke filesystem access' => [true, false],
];
}
#[\PHPUnit\Framework\Attributes\DataProvider(methodName: 'dataUpdateFilesystemScope')]
public function testUpdateFilesystemScope(bool $filesystem, bool $newFilesystem): void {
$tokenId = 42;
$token = $this->createMock(PublicKeyToken::class);
$this->mockGetTokenById($tokenId, $token);
$this->mockActivityManager();
$token->expects($this->once())
->method('getUID')
->willReturn('jane');
$token->expects($this->once())
->method('getName')
->willReturn('App password');
$token->expects($this->once())
->method('getScopeAsArray')
->willReturn([IToken::SCOPE_FILESYSTEM => $filesystem]);
$token->expects($this->once())
->method('setScope')
->with($this->equalTo([IToken::SCOPE_FILESYSTEM => $newFilesystem]));
$this->tokenProvider->expects($this->once())
->method('updateToken')
->with($this->equalTo($token));
$token->method('getId')->willReturn($tokenId);
$this->expectAuditEvent(
'auth.app_password.scope_changed',
['tokenId' => $tokenId, 'filesystemAccess' => $newFilesystem ? 'granted' : 'revoked'],
'Filesystem access of app password with ID "%s" was %s',
);
$this->assertSame(['scope' => [IToken::SCOPE_FILESYSTEM => $newFilesystem]], $this->controller->update($tokenId, [IToken::SCOPE_FILESYSTEM => $newFilesystem], 'App password')->getData());
}
public static function dataUpdateNoChange(): array {
return [
'same name' => ['App password'],
'same name with surrounding whitespace' => [' App password '],
];
}
#[\PHPUnit\Framework\Attributes\DataProvider(methodName: 'dataUpdateNoChange')]
public function testUpdateNoChange(string $newName): void {
$tokenId = 42;
$token = $this->createMock(PublicKeyToken::class);
$this->mockGetTokenById($tokenId, $token);
$token->expects($this->once())
->method('getUID')
->willReturn('jane');
$token->expects($this->once())
->method('getName')
->willReturn('App password');
$token->expects($this->once())
->method('getScopeAsArray')
->willReturn([IToken::SCOPE_FILESYSTEM => true]);
$token->expects($this->never())
->method('setName');
$token->expects($this->never())
->method('setScope');
$this->eventDispatcher->expects($this->never())
->method('dispatchTyped');
$this->tokenProvider->expects($this->once())
->method('updateToken')
->with($this->equalTo($token));
$this->assertSame(['scope' => [IToken::SCOPE_FILESYSTEM => true]], $this->controller->update($tokenId, [IToken::SCOPE_FILESYSTEM => true], $newName)->getData());
}
public static function dataUpdateScopedToken(): array {
$stored = [IToken::SCOPE_FILESYSTEM => false, TokenScopes::KEY => ['dav:calendar:read']];
return [
'scopes omitted' => [$stored, [IToken::SCOPE_FILESYSTEM => false]],
'scopes sent back unchanged' => [$stored, $stored],
'legacy filesystem toggle' => [$stored, [IToken::SCOPE_FILESYSTEM => true, TokenScopes::KEY => ['dav:calendar:read']]],
];
}
#[\PHPUnit\Framework\Attributes\DataProvider(methodName: 'dataUpdateScopedToken')]
public function testUpdateScopedTokenKeepsScopes(array $stored, array $scope): void {
$tokenId = 42;
$token = $this->createMock(PublicKeyToken::class);
$this->mockGetTokenById($tokenId, $token);
$this->mockActivityManager();
$token->method('getUID')->willReturn('jane');
$token->method('getName')->willReturn('App password');
$token->method('getScopeAsArray')->willReturn($stored);
$token->expects($this->never())
->method('setScope');
$token->expects($this->once())
->method('setName')
->with('Renamed');
$this->tokenProvider->expects($this->once())
->method('updateToken')
->with($token);
$this->assertSame(['scope' => $stored], $this->controller->update($tokenId, $scope, 'Renamed')->getData());
}
public static function dataUpdateScopes(): array {
$calendar = [IToken::SCOPE_FILESYSTEM => false, TokenScopes::KEY => ['dav:calendar:read']];
return [
'scopes set, filesystem flips too' => [[IToken::SCOPE_FILESYSTEM => true], [TokenScopes::KEY => ['dav:calendar:read']], $calendar, 'dav:calendar:read'],
'scopes cleared' => [$calendar, [IToken::SCOPE_FILESYSTEM => false, TokenScopes::KEY => null], [IToken::SCOPE_FILESYSTEM => true], 'all'],
];
}
#[\PHPUnit\Framework\Attributes\DataProvider(methodName: 'dataUpdateScopes')]
public function testUpdateScopesPublishOneActivity(array $stored, array $scope, array $expected, string $auditedScopes): void {
$tokenId = 42;
$token = $this->createMock(PublicKeyToken::class);
$this->mockGetTokenById($tokenId, $token);
$this->mockActivityManager(Provider::APP_TOKEN_SCOPES_CHANGED);
$token->method('getUID')->willReturn('jane');
$token->method('getName')->willReturn('App password');
$token->method('getScopeAsArray')->willReturn($stored);
$token->method('getId')->willReturn($tokenId);
$token->expects($this->once())
->method('setScope')
->with($expected);
$this->tokenProvider->expects($this->once())
->method('updateToken')
->with($token);
$this->expectAuditEvent(
'auth.app_password.scope_changed',
['tokenId' => $tokenId, 'scopes' => $auditedScopes],
'Scopes of app password with ID "%s" were changed to "%s"',
);
$this->assertSame(['scope' => $expected], $this->controller->update($tokenId, $scope, 'App password')->getData());
}
public function testUpdateInvalidScopes(): void {
$tokenId = 42;
$token = $this->createMock(PublicKeyToken::class);
$this->mockGetTokenById($tokenId, $token);
$token->method('getUID')->willReturn('jane');
$token->method('getName')->willReturn('App password');
$token->method('getScopeAsArray')->willReturn([IToken::SCOPE_FILESYSTEM => true]);
$token->expects($this->never())
->method('setScope');
$token->expects($this->never())
->method('setName');
$this->tokenProvider->expects($this->never())
->method('updateToken');
$response = $this->controller->update($tokenId, [TokenScopes::KEY => [FilesTokenScopes::FILES_READ]], 'Renamed');
$this->assertSame(Http::STATUS_BAD_REQUEST, $response->getStatus());
}
public function testUpdateRequiresStrictPasswordConfirmation(): void {
$attributes = (new \ReflectionMethod(AuthSettingsController::class, 'update'))
->getAttributes(PasswordConfirmationRequired::class);
$this->assertCount(1, $attributes);
$this->assertTrue($attributes[0]->newInstance()->getStrict());
}
public function testUpdateExpired(): void {
$tokenId = 42;
$token = $this->createMock(PublicKeyToken::class);
$token->expects($this->once())
->method('getUID')
->willReturn($this->uid);
$this->tokenProvider->expects($this->once())
->method('getTokenById')
->with($this->equalTo($tokenId))
->willThrowException(new ExpiredTokenException($token));
$this->tokenProvider->expects($this->once())
->method('updateToken')
->with($this->equalTo($token));
$this->assertSame(['scope' => [IToken::SCOPE_FILESYSTEM => true]], $this->controller->update($tokenId, [IToken::SCOPE_FILESYSTEM => true], 'App password')->getData());
}
public function testUpdateTokenWrongUser(): void {
$tokenId = 42;
$token = $this->createMock(PublicKeyToken::class);
$this->mockGetTokenById($tokenId, $token);
$token->expects($this->once())
->method('getUID')
->willReturn('foobar');
$token->expects($this->never())
->method('setScope');
$this->tokenProvider->expects($this->never())
->method('updateToken');
$response = $this->controller->update($tokenId, [IToken::SCOPE_FILESYSTEM => true], 'App password');
$this->assertSame([], $response->getData());
$this->assertSame(\OCP\AppFramework\Http::STATUS_NOT_FOUND, $response->getStatus());
}
public function testUpdateTokenNonExisting(): void {
$this->tokenProvider->expects($this->once())
->method('getTokenById')
->with($this->equalTo(42))
->willThrowException(new InvalidTokenException('Token does not exist'));
$this->tokenProvider->expects($this->never())
->method('updateToken');
$response = $this->controller->update(42, [IToken::SCOPE_FILESYSTEM => true], 'App password');
$this->assertSame([], $response->getData());
$this->assertSame(\OCP\AppFramework\Http::STATUS_NOT_FOUND, $response->getStatus());
}
private function mockSessionForCreate(): void {
$sessionToken = $this->createMock(IToken::class);
$sessionToken->method('getLoginName')->willReturn('User13');
$this->serverConfig->method('getSystemValueBool')
->with('auth_can_create_app_token', true)
->willReturn(true);
$this->session->method('getId')->willReturn('sessionid');
$this->tokenProvider->method('getToken')->with('sessionid')->willReturn($sessionToken);
$this->tokenProvider->method('getPassword')->willReturn('123456');
$this->secureRandom->method('generate')->willReturn('XXXXX');
}
private function mockAuthToken(int $id, int $type = IToken::PERMANENT_TOKEN): PublicKeyToken&MockObject {
$token = $this->createMock(PublicKeyToken::class);
$token->method('getId')->willReturn($id);
$token->method('getType')->willReturn($type);
return $token;
}
private function expectAuditEvent(string $operation, array $parameters, string $message): void {
$this->eventDispatcher->expects($this->once())
->method('dispatchTyped')
->with($this->callback(fn (CriticalActionPerformedEvent $event): bool => $event->getOperation() === $operation
&& $event->getParameters() === $parameters
&& $event->getLogMessage() === $message));
}
private function mockActivityManager(?string $subject = null): void {
$event = $this->createMock(IEvent::class);
if ($subject !== null) {
foreach (['setApp', 'setType', 'setAffectedUser', 'setAuthor', 'setObject'] as $method) {
$event->method($method)->willReturnSelf();
}
$event->expects($this->once())
->method('setSubject')
->with($subject, $this->anything())
->willReturnSelf();
}
$this->activityManager->expects($this->once())
->method('generateEvent')
->willReturn($event);
$this->activityManager->expects($this->once())
->method('publish');
}
/**
* @param int $tokenId
* @param $token
*/
private function mockGetTokenById(int $tokenId, $token): void {
$this->tokenProvider->expects($this->once())
->method('getTokenById')
->with($this->equalTo($tokenId))
->willReturn($token);
}
public function testRemoteWipeNotSuccessful(): void {
$token = $this->createMock(IToken::class);
$token->expects($this->once())
->method('getUID')
->willReturn($this->uid);
$this->mockGetTokenById(123, $token);
$this->remoteWipe->expects($this->once())
->method('markTokenForWipe')
->with($token)
->willReturn(false);
$this->eventDispatcher->expects($this->never())
->method('dispatchTyped');
$response = $this->controller->wipe(123);
$expected = new JSONResponse([], Http::STATUS_BAD_REQUEST);
$this->assertEquals($expected, $response);
}
public function testRemoteWipeWrongUser(): void {
$token = $this->createMock(IToken::class);
$token->expects($this->once())
->method('getUID')
->willReturn('definetly-not-' . $this->uid);
$this->mockGetTokenById(123, $token);
$this->remoteWipe->expects($this->never())
->method('markTokenForWipe');
$response = $this->controller->wipe(123);
$expected = new JSONResponse([], Http::STATUS_NOT_FOUND);
$this->assertEquals($expected, $response);
}
public function testRemoteWipeSuccessful(): void {
$token = $this->createMock(IWipeableToken::class);
$token->expects($this->once())
->method('getUID')
->willReturn($this->uid);
$this->mockGetTokenById(123, $token);
$this->remoteWipe->expects($this->once())
->method('markTokenForWipe')
->with($token)
->willReturn(true);
$token->method('getId')->willReturn(123);
$this->expectAuditEvent('auth.remote_wipe.requested', ['tokenId' => 123], 'Remote wipe was requested for app password with ID "%s"');
$response = $this->controller->wipe(123);
$expected = new JSONResponse([]);
$this->assertEquals($expected, $response);
}
}