Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(oauth2): retain support for legacy ownCloud clients #50858

Draft
wants to merge 4 commits into
base: master
Choose a base branch
from
Draft
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
4 changes: 4 additions & 0 deletions apps/oauth2/appinfo/info.xml
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,10 @@
</post-migration>
</repair-steps>

<commands>
<command>OCA\OAuth2\Command\ImportLegacyOcClient</command>
</commands>

<settings>
<admin>OCA\OAuth2\Settings\Admin</admin>
</settings>
Expand Down
1 change: 1 addition & 0 deletions apps/oauth2/composer/composer/autoload_classmap.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
return array(
'Composer\\InstalledVersions' => $vendorDir . '/composer/InstalledVersions.php',
'OCA\\OAuth2\\BackgroundJob\\CleanupExpiredAuthorizationCode' => $baseDir . '/../lib/BackgroundJob/CleanupExpiredAuthorizationCode.php',
'OCA\\OAuth2\\Command\\ImportLegacyOcClient' => $baseDir . '/../lib/Command/ImportLegacyOcClient.php',
'OCA\\OAuth2\\Controller\\LoginRedirectorController' => $baseDir . '/../lib/Controller/LoginRedirectorController.php',
'OCA\\OAuth2\\Controller\\OauthApiController' => $baseDir . '/../lib/Controller/OauthApiController.php',
'OCA\\OAuth2\\Controller\\SettingsController' => $baseDir . '/../lib/Controller/SettingsController.php',
Expand Down
1 change: 1 addition & 0 deletions apps/oauth2/composer/composer/autoload_static.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ class ComposerStaticInitOAuth2
public static $classMap = array (
'Composer\\InstalledVersions' => __DIR__ . '/..' . '/composer/InstalledVersions.php',
'OCA\\OAuth2\\BackgroundJob\\CleanupExpiredAuthorizationCode' => __DIR__ . '/..' . '/../lib/BackgroundJob/CleanupExpiredAuthorizationCode.php',
'OCA\\OAuth2\\Command\\ImportLegacyOcClient' => __DIR__ . '/..' . '/../lib/Command/ImportLegacyOcClient.php',
'OCA\\OAuth2\\Controller\\LoginRedirectorController' => __DIR__ . '/..' . '/../lib/Controller/LoginRedirectorController.php',
'OCA\\OAuth2\\Controller\\OauthApiController' => __DIR__ . '/..' . '/../lib/Controller/OauthApiController.php',
'OCA\\OAuth2\\Controller\\SettingsController' => __DIR__ . '/..' . '/../lib/Controller/SettingsController.php',
Expand Down
76 changes: 76 additions & 0 deletions apps/oauth2/lib/Command/ImportLegacyOcClient.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
<?php

declare(strict_types=1);

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

namespace OCA\OAuth2\Command;

use OCA\OAuth2\Db\Client;
use OCA\OAuth2\Db\ClientMapper;
use OCP\IConfig;
use OCP\Security\ICrypto;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

class ImportLegacyOcClient extends Command {
private const ARGUMENT_CLIENT_ID = 'client-id';
private const ARGUMENT_CLIENT_SECRET = 'client-secret';

public function __construct(
private readonly IConfig $config,
private readonly ICrypto $crypto,
private readonly ClientMapper $clientMapper,
) {
parent::__construct();
}

protected function configure(): void {
$this->setName('oauth2:import-legacy-oc-client');
$this->setDescription('Import a legacy Oauth2 client from an ownCloud instance and migrate it. The data is expected to be straight out of the database table oc_oauth2_clients.');
$this->addArgument(
self::ARGUMENT_CLIENT_ID,
InputArgument::REQUIRED,
'Value of the "identifier" column',
);
$this->addArgument(
self::ARGUMENT_CLIENT_SECRET,
InputArgument::REQUIRED,
'Value of the "secret" column',
);
}

public function isEnabled(): bool {
return $this->config->getSystemValueBool('oauth2.enable_oc_clients', false);
}

protected function execute(InputInterface $input, OutputInterface $output): int {
/** @var string $clientId */
$clientId = $input->getArgument(self::ARGUMENT_CLIENT_ID);

/** @var string $clientSecret */
$clientSecret = $input->getArgument(self::ARGUMENT_CLIENT_SECRET);

// Should not happen but just to be sure
if (empty($clientId) || empty($clientSecret)) {
return 1;
}

$hashedClientSecret = bin2hex($this->crypto->calculateHMAC($clientSecret));

$client = new Client();
$client->setName('ownCloud Desktop Client');
$client->setRedirectUri('http://localhost:*');
$client->setClientIdentifier($clientId);
$client->setSecret($hashedClientSecret);
$this->clientMapper->insert($client);

$output->writeln('<info>Client imported successfully</info>');
return 0;
}
}
14 changes: 13 additions & 1 deletion apps/oauth2/lib/Controller/LoginRedirectorController.php
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
use OCP\AppFramework\Http\RedirectResponse;
use OCP\AppFramework\Http\TemplateResponse;
use OCP\IAppConfig;
use OCP\IConfig;
use OCP\IL10N;
use OCP\IRequest;
use OCP\ISession;
Expand All @@ -45,6 +46,7 @@ public function __construct(
private IL10N $l,
private ISecureRandom $random,
private IAppConfig $appConfig,
private IConfig $config,
) {
parent::__construct($appName, $request);
}
Expand All @@ -65,7 +67,8 @@ public function __construct(
#[UseSession]
public function authorize($client_id,
$state,
$response_type): TemplateResponse|RedirectResponse {
$response_type,
string $redirect_uri = ''): TemplateResponse|RedirectResponse {
try {
$client = $this->clientMapper->getByIdentifier($client_id);
} catch (ClientNotFoundException $e) {
Expand All @@ -81,6 +84,13 @@ public function authorize($client_id,
return new RedirectResponse($url);
}

$enableOcClients = $this->config->getSystemValueBool('oauth2.enable_oc_clients', false);

$providedRedirectUri = '';
if ($enableOcClients && $client->getRedirectUri() === 'http://localhost:*') {
$providedRedirectUri = $redirect_uri;
}

$this->session->set('oauth.state', $state);

if (in_array($client->getName(), $this->appConfig->getValueArray('oauth2', 'skipAuthPickerApplications', []))) {
Expand All @@ -95,13 +105,15 @@ public function authorize($client_id,
[
'stateToken' => $stateToken,
'clientIdentifier' => $client->getClientIdentifier(),
'providedRedirectUri' => $providedRedirectUri,
]
);
} else {
$targetUrl = $this->urlGenerator->linkToRouteAbsolute(
'core.ClientFlowLogin.showAuthPickerPage',
[
'clientIdentifier' => $client->getClientIdentifier(),
'providedRedirectUri' => $providedRedirectUri,
]
);
}
Expand Down
20 changes: 19 additions & 1 deletion core/Controller/ClientFlowLoginController.php
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
use OCP\Authentication\Token\IToken;
use OCP\Defaults;
use OCP\EventDispatcher\IEventDispatcher;
use OCP\IConfig;
use OCP\IL10N;
use OCP\IRequest;
use OCP\ISession;
Expand Down Expand Up @@ -55,6 +56,7 @@ public function __construct(
private ICrypto $crypto,
private IEventDispatcher $eventDispatcher,
private ITimeFactory $timeFactory,
private IConfig $config,
) {
parent::__construct($appName, $request);
}
Expand Down Expand Up @@ -89,7 +91,7 @@ private function stateTokenForbiddenResponse(): StandaloneTemplateResponse {
#[NoCSRFRequired]
#[UseSession]
#[FrontpageRoute(verb: 'GET', url: '/login/flow')]
public function showAuthPickerPage(string $clientIdentifier = '', string $user = '', int $direct = 0): StandaloneTemplateResponse {
public function showAuthPickerPage(string $clientIdentifier = '', string $user = '', int $direct = 0, string $providedRedirectUri = ''): StandaloneTemplateResponse {
$clientName = $this->getClientName();
$client = null;
if ($clientIdentifier !== '') {
Expand Down Expand Up @@ -142,6 +144,7 @@ public function showAuthPickerPage(string $clientIdentifier = '', string $user =
'oauthState' => $this->session->get('oauth.state'),
'user' => $user,
'direct' => $direct,
'providedRedirectUri' => $providedRedirectUri,
],
'guest'
);
Expand All @@ -161,6 +164,7 @@ public function grantPage(
string $stateToken = '',
string $clientIdentifier = '',
int $direct = 0,
string $providedRedirectUri = '',
): Response {
if (!$this->isValidToken($stateToken)) {
return $this->stateTokenForbiddenResponse();
Expand Down Expand Up @@ -197,6 +201,7 @@ public function grantPage(
'serverHost' => $this->getServerPath(),
'oauthState' => $this->session->get('oauth.state'),
'direct' => $direct,
'providedRedirectUri' => $providedRedirectUri,
],
'guest'
);
Expand All @@ -211,6 +216,7 @@ public function grantPage(
public function generateAppPassword(
string $stateToken,
string $clientIdentifier = '',
string $providedRedirectUri = '',
): Response {
if (!$this->isValidToken($stateToken)) {
$this->session->remove(self::STATE_NAME);
Expand Down Expand Up @@ -270,7 +276,19 @@ public function generateAppPassword(
$accessToken->setCodeCreatedAt($this->timeFactory->now()->getTimestamp());
$this->accessTokenMapper->insert($accessToken);

$enableOcClients = $this->config->getSystemValueBool('oauth2.enable_oc_clients', false);

$redirectUri = $client->getRedirectUri();
if ($enableOcClients && $redirectUri === 'http://localhost:*') {
// Sanity check untrusted redirect URI provided by the client first
if (!preg_match('/^http:\/\/localhost:[0-9]+$/', $providedRedirectUri)) {
$response = new Response();
$response->setStatus(Http::STATUS_FORBIDDEN);
return $response;
}

$redirectUri = $providedRedirectUri;
}

if (parse_url($redirectUri, PHP_URL_QUERY)) {
$redirectUri .= '&';
Expand Down
2 changes: 1 addition & 1 deletion core/templates/loginflow/authpicker.php
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@
<br/>

<p id="redirect-link">
<form id="login-form" action="<?php p($urlGenerator->linkToRoute('core.ClientFlowLogin.grantPage', ['stateToken' => $_['stateToken'], 'clientIdentifier' => $_['clientIdentifier'], 'oauthState' => $_['oauthState'], 'user' => $_['user'], 'direct' => $_['direct']])) ?>" method="get">
<form id="login-form" action="<?php p($urlGenerator->linkToRoute('core.ClientFlowLogin.grantPage', ['stateToken' => $_['stateToken'], 'clientIdentifier' => $_['clientIdentifier'], 'oauthState' => $_['oauthState'], 'user' => $_['user'], 'direct' => $_['direct'], 'providedRedirectUri' => $_['providedRedirectUri']])) ?>" method="get">
<input type="submit" class="login primary icon-confirm-white" value="<?php p($l->t('Log in')) ?>" disabled>
</form>
</p>
Expand Down
1 change: 1 addition & 0 deletions core/templates/loginflow/grant.php
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@
<input type="hidden" name="requesttoken" value="<?php p($_['requesttoken']) ?>" />
<input type="hidden" name="stateToken" value="<?php p($_['stateToken']) ?>" />
<input type="hidden" name="oauthState" value="<?php p($_['oauthState']) ?>" />
<input type="hidden" name="providedRedirectUri" value="<?php p($_['providedRedirectUri']) ?>">
<?php if ($_['direct']) { ?>
<input type="hidden" name="direct" value="1" />
<?php } ?>
Expand Down
21 changes: 16 additions & 5 deletions lib/private/Repair/Owncloud/MigrateOauthTables.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
use OCP\AppFramework\Utility\ITimeFactory;
use OCP\Authentication\Token\IToken;
use OCP\DB\QueryBuilder\IQueryBuilder;
use OCP\IConfig;
use OCP\Migration\IOutput;
use OCP\Migration\IRepairStep;
use OCP\Security\ICrypto;
Expand All @@ -29,6 +30,7 @@ public function __construct(
private ISecureRandom $random,
private ITimeFactory $timeFactory,
private ICrypto $crypto,
private IConfig $config,
) {
}

Expand Down Expand Up @@ -169,7 +171,12 @@ public function run(IOutput $output) {
$schema = new SchemaWrapper($this->db);
}

$output->info('Delete clients (and their related access tokens) with the redirect_uri starting with oc:// or ending with *');
$enableOcClients = $this->config->getSystemValueBool('oauth2.enable_oc_clients', false);
if ($enableOcClients) {
$output->info('Delete clients (and their related access tokens) with the redirect_uri starting with oc://');
} else {
$output->info('Delete clients (and their related access tokens) with the redirect_uri starting with oc:// or ending with *');
}
// delete the access tokens
$qbDeleteAccessTokens = $this->db->getQueryBuilder();

Expand All @@ -178,10 +185,12 @@ public function run(IOutput $output) {
->from('oauth2_clients')
->where(
$qbSelectClientId->expr()->iLike('redirect_uri', $qbDeleteAccessTokens->createNamedParameter('oc://%', IQueryBuilder::PARAM_STR))
)
->orWhere(
);
if (!$enableOcClients) {
$qbSelectClientId->orWhere(
$qbSelectClientId->expr()->iLike('redirect_uri', $qbDeleteAccessTokens->createNamedParameter('%*', IQueryBuilder::PARAM_STR))
);
}

$qbDeleteAccessTokens->delete('oauth2_access_tokens')
->where(
Expand All @@ -194,10 +203,12 @@ public function run(IOutput $output) {
$qbDeleteClients->delete('oauth2_clients')
->where(
$qbDeleteClients->expr()->iLike('redirect_uri', $qbDeleteClients->createNamedParameter('oc://%', IQueryBuilder::PARAM_STR))
)
->orWhere(
);
if (!$enableOcClients) {
$qbDeleteClients->orWhere(
$qbDeleteClients->expr()->iLike('redirect_uri', $qbDeleteClients->createNamedParameter('%*', IQueryBuilder::PARAM_STR))
);
}
$qbDeleteClients->executeStatement();

// Migrate legacy refresh tokens from oc
Expand Down
Loading