Skip to content
Open
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
2 changes: 1 addition & 1 deletion apps/oauth2/appinfo/info.xml
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
<name>OAuth 2.0</name>
<summary>Allows OAuth2 compatible authentication from other web applications.</summary>
<description>The OAuth2 app allows administrators to configure the built-in authentication workflow to also allow OAuth2 compatible authentication from other web applications.</description>
<version>3.0.0-dev.0</version>
<version>3.0.0-dev.1</version>
<licence>agpl</licence>
<author>Lukas Reschke</author>
<namespace>OAuth2</namespace>
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 @@ -27,6 +27,7 @@
'OCA\\OAuth2\\Migration\\Version011602Date20230613160650' => $baseDir . '/../lib/Migration/Version011602Date20230613160650.php',
'OCA\\OAuth2\\Migration\\Version011603Date20230620111039' => $baseDir . '/../lib/Migration/Version011603Date20230620111039.php',
'OCA\\OAuth2\\Migration\\Version011901Date20240829164356' => $baseDir . '/../lib/Migration/Version011901Date20240829164356.php',
'OCA\\OAuth2\\Migration\\Version030000Date20261202224022' => $baseDir . '/../lib/Migration/Version030000Date20261202224022.php',
'OCA\\OAuth2\\Service\\ClientService' => $baseDir . '/../lib/Service/ClientService.php',
'OCA\\OAuth2\\Settings\\Admin' => $baseDir . '/../lib/Settings/Admin.php',
);
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 @@ -42,6 +42,7 @@ class ComposerStaticInitOAuth2
'OCA\\OAuth2\\Migration\\Version011602Date20230613160650' => __DIR__ . '/..' . '/../lib/Migration/Version011602Date20230613160650.php',
'OCA\\OAuth2\\Migration\\Version011603Date20230620111039' => __DIR__ . '/..' . '/../lib/Migration/Version011603Date20230620111039.php',
'OCA\\OAuth2\\Migration\\Version011901Date20240829164356' => __DIR__ . '/..' . '/../lib/Migration/Version011901Date20240829164356.php',
'OCA\\OAuth2\\Migration\\Version030000Date20261202224022' => __DIR__ . '/..' . '/../lib/Migration/Version030000Date20261202224022.php',
'OCA\\OAuth2\\Service\\ClientService' => __DIR__ . '/..' . '/../lib/Service/ClientService.php',
'OCA\\OAuth2\\Settings\\Admin' => __DIR__ . '/..' . '/../lib/Settings/Admin.php',
);
Expand Down
74 changes: 70 additions & 4 deletions apps/oauth2/lib/Controller/LoginRedirectorController.php
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,11 @@

#[OpenAPI(scope: OpenAPI::SCOPE_DEFAULT)]
final class LoginRedirectorController extends Controller {
// An S256 code challenge is the unpadded base64url encoding of a SHA-256 hash, which is always 43 characters
private const string CODE_CHALLENGE_PATTERN = '/^[A-Za-z0-9_-]{43}$/D';

private const string LEGACY_LOCALHOST_REDIRECT_PATTERN = '/^http:\/\/localhost:[0-9]+$/D';

public function __construct(
string $appName,
IRequest $request,
Expand All @@ -44,13 +49,51 @@ public function __construct(
parent::__construct($appName, $request);
}

/**
* @return RedirectResponse<Http::STATUS_SEE_OTHER, array{}>
*/
private function buildErrorRedirectResponse(
string $registeredRedirectUri,
string $providedRedirectUri,
string $error,
string $state,
?string $errorDescription = null,
): RedirectResponse {
$redirectUri = $registeredRedirectUri;
$enableOcClients = $this->config->getSystemValueBool('oauth2.enable_oc_clients', false);
if ($enableOcClients && $redirectUri === 'http://localhost:*' && preg_match(self::LEGACY_LOCALHOST_REDIRECT_PATTERN, $providedRedirectUri) === 1) {
$redirectUri = $providedRedirectUri;
}

$fragment = '';
$fragmentPosition = strpos($redirectUri, '#');
if ($fragmentPosition !== false) {
$fragment = substr($redirectUri, $fragmentPosition);
$redirectUri = substr($redirectUri, 0, $fragmentPosition);
}

$params = [
'error' => $error,
];
if ($errorDescription !== null) {
$params['error_description'] = $errorDescription;
}

$params['state'] = $state;

$separator = str_contains($redirectUri, '?') ? '&' : '?';
return new RedirectResponse($redirectUri . $separator . http_build_query($params, '', '&') . $fragment);
}

/**
* Authorize the user
*
* @param string $client_id Client ID
* @param string $state State of the flow
* @param string $response_type Response type for the flow
* @param string $redirect_uri URI to redirect to after the flow (is only used for legacy ownCloud clients)
* @param string $code_challenge PKCE code challenge (optional, RFC 7636 format)
* @param string $code_challenge_method PKCE code challenge method. Only "S256" is supported. If omitted, RFC 7636 defaults to "plain", which is rejected.
* @return TemplateResponse<Http::STATUS_OK, array{}>|RedirectResponse<Http::STATUS_SEE_OTHER, array{}>
*
* 200: Client not found
Expand All @@ -60,7 +103,12 @@ public function __construct(
#[NoCSRFRequired]
#[UseSession]
public function authorize(
string $client_id, string $state, string $response_type, string $redirect_uri = '',
string $client_id,
string $state,
string $response_type,
string $redirect_uri = '',
string $code_challenge = '',
string $code_challenge_method = '',
): TemplateResponse|RedirectResponse {
try {
$client = $this->clientMapper->getByIdentifier($client_id);
Expand All @@ -72,9 +120,22 @@ public function authorize(
}

if ($response_type !== 'code') {
//Fail
$url = $client->redirectUri . '?error=unsupported_response_type&state=' . \urlencode($state);
return new RedirectResponse($url);
return $this->buildErrorRedirectResponse($client->redirectUri, $redirect_uri, 'unsupported_response_type', $state);
}

if ($code_challenge === '' && $code_challenge_method !== '') {
return $this->buildErrorRedirectResponse($client->redirectUri, $redirect_uri, 'invalid_request', $state, 'code_challenge required');
}

if ($code_challenge !== '' && preg_match(self::CODE_CHALLENGE_PATTERN, $code_challenge) !== 1) {
return $this->buildErrorRedirectResponse($client->redirectUri, $redirect_uri, 'invalid_request', $state, 'Invalid code_challenge');
}

$effectiveCodeChallengeMethod = $code_challenge_method === '' && $code_challenge !== ''
? 'plain'
: $code_challenge_method;
if ($effectiveCodeChallengeMethod !== '' && $effectiveCodeChallengeMethod !== 'S256') {
return $this->buildErrorRedirectResponse($client->redirectUri, $redirect_uri, 'invalid_request', $state, 'Transform algorithm not supported');
}

$enableOcClients = $this->config->getSystemValueBool('oauth2.enable_oc_clients', false);
Expand All @@ -84,10 +145,15 @@ public function authorize(
$providedRedirectUri = $redirect_uri;
}

// The values below are stored once per session. A consent page that is still open from an
// earlier request must not be able to complete with them, so its flow token is dropped here.
$this->session->remove(ClientFlowLoginController::STATE_NAME);
$this->session->set('oauth.state', [
'clientIdentifier' => $client->clientIdentifier,
'state' => $state,
]);
$this->session->set('oauth.code_challenge', $code_challenge);
$this->session->set('oauth.code_challenge_method', $effectiveCodeChallengeMethod);

if (in_array($client->name, $this->appConfig->getValueArray('oauth2', 'skipAuthPickerApplications', []), true)) {
/** @see ClientFlowLoginController::showAuthPickerPage **/
Expand Down
52 changes: 52 additions & 0 deletions apps/oauth2/lib/Controller/OauthApiController.php
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,8 @@ final class OauthApiController extends Controller {
// the authorization code expires after 10 minutes
public const int AUTHORIZATION_CODE_EXPIRES_AFTER = 10 * 60;

private const string PKCE_STRING_PATTERN = '/^[A-Za-z0-9._~-]{43,128}$/D';

public function __construct(
string $appName,
IRequest $request,
Expand Down Expand Up @@ -72,6 +74,7 @@ public function __construct(
* @param ?string $refresh_token Refresh token
* @param ?string $client_id Client ID
* @param ?string $client_secret Client secret
* @param ?string $code_verifier PKCE code verifier in RFC 7636 format (required if code_challenge was provided, rejected otherwise)
* @throws Exception
* @return JSONResponse<Http::STATUS_OK, array{access_token: string, token_type: string, expires_in: int, refresh_token: string, user_id: string, "x.nc-gss.secondary_url"?: ?string}, array{}>|JSONResponse<Http::STATUS_BAD_REQUEST, array{error: string}, array{}>
*
Expand All @@ -84,6 +87,7 @@ public function __construct(
public function getToken(
string $grant_type, ?string $code, ?string $refresh_token,
?string $client_id, ?string $client_secret,
?string $code_verifier = null,
): JSONResponse {

// We only handle two types
Expand Down Expand Up @@ -193,6 +197,54 @@ public function getToken(
return $response;
}

if ($grant_type === 'authorization_code') {
// Verify the PKCE code verifier only for an authenticated client, so the answer says nothing to anybody else
$hashedCodeChallenge = $accessToken->hashedCodeChallenge;
if ($hashedCodeChallenge !== null && $hashedCodeChallenge !== '') {
if ($code_verifier === null || $code_verifier === '') {
$response = new JSONResponse([
'error' => 'invalid_request',
], Http::STATUS_BAD_REQUEST);
$response->throttle(['invalid_request' => 'code_verifier_required']);
return $response;
}

if (preg_match(self::PKCE_STRING_PATTERN, $code_verifier) !== 1) {
$response = new JSONResponse([
'error' => 'invalid_grant',
], Http::STATUS_BAD_REQUEST);
$response->throttle(['invalid_grant' => 'invalid_code_verifier']);
return $response;
}

$codeChallengeMethod = $accessToken->codeChallengeMethod;
if ($codeChallengeMethod !== 'S256') {
$response = new JSONResponse([
'error' => 'invalid_grant',
], Http::STATUS_BAD_REQUEST);
$response->throttle(['invalid_grant' => 'unsupported_code_challenge_method']);
return $response;
}

$expectedHash = rtrim(strtr(base64_encode(hash('sha256', $code_verifier, true)), '+/', '-_'), '=');
if (!hash_equals($hashedCodeChallenge, $expectedHash)) {
$response = new JSONResponse([
'error' => 'invalid_grant',
], Http::STATUS_BAD_REQUEST);
$response->throttle(['invalid_grant' => 'pkce_verification_failed']);
return $response;
}
} elseif ($code_verifier !== null && $code_verifier !== '') {
// A code verifier is only valid for a code that was requested with a code challenge (RFC 9700 section 2.1.1).
// Accepting it here would hide that the challenge was stripped from the authorization request.
$response = new JSONResponse([
'error' => 'invalid_grant',
], Http::STATUS_BAD_REQUEST);
$response->throttle(['invalid_grant' => 'unexpected_code_verifier']);
return $response;
}
}

$decryptedToken = $this->crypto->decrypt($accessToken->encryptedToken, $code);

// Obtain the appToken associated
Expand Down
6 changes: 6 additions & 0 deletions apps/oauth2/lib/Db/AccessToken.php
Original file line number Diff line number Diff line change
Expand Up @@ -39,4 +39,10 @@ final class AccessToken {

#[Column(name: 'token_count', type: ColumnType::Bigint, default: 0)]
public int $tokenCount = 0;

#[Column(name: 'hashed_code_challenge', type: ColumnType::String, length: 128, nullable: true)]
public ?string $hashedCodeChallenge = null;

#[Column(name: 'code_challenge_method', type: ColumnType::String, length: 10, nullable: true)]
public ?string $codeChallengeMethod = null;
}
48 changes: 48 additions & 0 deletions apps/oauth2/lib/Migration/Version030000Date20261202224022.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
<?php

declare(strict_types=1);

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

namespace OCA\OAuth2\Migration;

use Closure;
use OCP\DB\ISchemaWrapper;
use OCP\DB\Types;
use OCP\Migration\Attributes\AddColumn;
use OCP\Migration\Attributes\ColumnType;
use OCP\Migration\IOutput;
use OCP\Migration\SimpleMigrationStep;
use Override;

#[AddColumn(table: 'oauth2_access_tokens', name: 'hashed_code_challenge', type: ColumnType::STRING)]
#[AddColumn(table: 'oauth2_access_tokens', name: 'code_challenge_method', type: ColumnType::STRING)]
final class Version030000Date20261202224022 extends SimpleMigrationStep {
#[Override]
public function changeSchema(IOutput $output, Closure $schemaClosure, array $options): ?ISchemaWrapper {
$schema = $schemaClosure();
$modified = false;

$table = $schema->getTable('oauth2_access_tokens');
if (!$table->hasColumn('hashed_code_challenge')) {
$table->addColumn('hashed_code_challenge', Types::STRING, [
'notnull' => false,
'length' => 128,
]);
$modified = true;
}

if (!$table->hasColumn('code_challenge_method')) {
$table->addColumn('code_challenge_method', Types::STRING, [
'notnull' => false,
'length' => 10,
]);
$modified = true;
}

return $modified ? $schema : null;
}
}
24 changes: 24 additions & 0 deletions apps/oauth2/openapi.json
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,24 @@
"type": "string",
"default": ""
}
},
{
"name": "code_challenge",
"in": "query",
"description": "PKCE code challenge (optional, RFC 7636 format)",
"schema": {
"type": "string",
"default": ""
}
},
{
"name": "code_challenge_method",
"in": "query",
"description": "PKCE code challenge method. Only \"S256\" is supported. If omitted, RFC 7636 defaults to \"plain\", which is rejected.",
"schema": {
"type": "string",
"default": ""
}
}
],
"responses": {
Expand Down Expand Up @@ -153,6 +171,12 @@
"type": "string",
"nullable": true,
"description": "Client secret"
},
"code_verifier": {
"type": "string",
"nullable": true,
"default": null,
"description": "PKCE code verifier in RFC 7636 format (required if code_challenge was provided, rejected otherwise)"
}
}
}
Expand Down
Loading