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
7 changes: 7 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,13 @@ Changelog
Releases for CakePHP 5.0
-------------

* 10.1.2
* reCaptcha: validation is turned off only by the new `Api.reCaptcha.disabled` setting, set to the boolean `true`. `Api.reCaptcha.<domain>.disabled` is ignored and logs a warning. Without a configured secret for the domain, validation now fails instead of raising an error, and a warning is logged.
* Upgrade note: if you disabled reCaptcha for a domain, for example in a development config, set `Api.reCaptcha.disabled` to the boolean `true` there instead; a string such as `'true'` from an environment variable leaves validation on. This setting turns validation off for every domain, so use it only in development and test configs. A production app that skipped reCaptcha for one domain, for example for a mobile or internal client, has to configure a secret for that domain and send real tokens; until then every validation from that domain fails. Do not configure reCaptcha test keys for any domain in production: they accept every response.
* `RequestParser::getDomain()` reads the `Referer` header from the request instead of `$_SERVER`, and no longer raises a PHP warning for a `Referer` header without a host.
* Two-factor authentication: a second factor can no longer be enrolled while another one is registered. A user with a verified OTP secret cannot register a WebAuthn key, a user with a WebAuthn key cannot set up OTP, and WebAuthn keys stored under any domain count, so no further key can be registered under another domain. `two_factor_auth` now reports the WebAuthn keys of every domain and a verified OTP secret.
* Upgrade note: a user who has one second factor and wants the other one needs the first one removed first. With WebAuthn configured for several domains, a user who has registered a key under one domain can no longer register another key, or OTP, under a different domain. In production configs, configure `Api.Webauthn2fa` only for the domains you serve, and set the default `Api.Webauthn2fa.localhost` entry to `null`.

* 10.1.1
* Security: refreshing a JWT issued before the second factor was completed returned tokens that no longer required 2FA; refresh now preserves the token audience.
* Upgrade note: if 2FA is enabled, invalidate existing refresh tokens after upgrading, by emptying the `jwt_refresh_tokens` table or rotating `Api.Jwt.RefreshToken.secret`. Until you do, tokens that were already escalated before the upgrade keep their privileged audience: the access tokens stay valid for the rest of their lifetime, and their refresh tokens keep minting privileged ones. Rotating `Api.Jwt.AccessToken.secret` also ends current access tokens.
Expand Down
36 changes: 36 additions & 0 deletions docs/Documentation/configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -66,3 +66,39 @@ This allow to configure shared behavior for all actions or for specific subset o

See it in auth.md

## reCaptcha configuration

`ReCaptchaTrait::validateReCaptcha()`, used by the `validate` action of `RecaptchaService`, reads its settings from `Api.reCaptcha`:

```php
'Api' => [
'reCaptcha' => [
// turns validation off for every domain; set it only in development and test configs
'disabled' => false,
// the secret for each domain, with the dots of the domain replaced by `$`
'app$example$com' => [
'secret' => 'your-secret-key',
],
],
],
```

The domain is the host of the request's `Referer` header, or, without a `Referer`, the domain of the request without its subdomain (`api.example.com` gives `example$com`). Validation fails, and a warning is logged, when that domain has no secret. `Api.reCaptcha.<domain>.disabled` is ignored. Do not configure reCaptcha test keys for any domain in production: they accept every response.

## Two-factor authentication

A password login of a user with two-factor authentication enabled gives a token for the second step only. With that token the user verifies a registered factor (OTP or WebAuthn), or enrolls one when none is registered yet. Once a factor is registered, the other one cannot be enrolled with that token: a user with a verified OTP secret cannot register a WebAuthn key, and a user with a WebAuthn key, under any domain, cannot set up OTP or register another key.

WebAuthn keys are stored per domain, chosen like the reCaptcha domain above, and each domain needs an `Api.Webauthn2fa.<domain>` entry with `appName` and `id`. In production configs, configure only the domains you serve, and set the default `localhost` entry to `null`:

```php
'Api' => [
'Webauthn2fa' => [
'localhost' => null,
'app$example$com' => [
'appName' => 'Example',
'id' => 'app.example.com',
],
],
],
```
1 change: 1 addition & 0 deletions src/Service/Action/Auth/OtpVerifyAction.php
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
abstract class OtpVerifyAction extends Action
{
use CustomUsersTableTrait;
use SecondFactorTrait;

/**
* @var \RobThree\Auth\TwoFactorAuth $tfa
Expand Down
4 changes: 4 additions & 0 deletions src/Service/Action/Auth/OtpVerifyCheckAction.php
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,10 @@ public function execute()
$verificationCode = $this->getData('code');
$user = $this->getIdentity();
$entity = $this->getUsersTable()->get($user['id']);
// verifying a new secret enrolls OTP; an already verified secret is the normal second step
if (!$entity->get('secret_verified')) {
$this->_refuseEnrollmentIf($this->_hasWebauthnCredential($user));
}

if (!empty($entity['secret'])) {
$codeVerified = $this->verifyCode($entity['secret'], $verificationCode);
Expand Down
1 change: 1 addition & 0 deletions src/Service/Action/Auth/OtpVerifyGetAction.php
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ public function execute()
$secretVerified = $user['secret_verified'] ?? null;
// showing QR-code until shared secret is verified
if (!$secretVerified) {
$this->_refuseEnrollmentIf($this->_hasWebauthnCredential($user));
$secret = $this->onVerifyGetSecret($user);
if (empty($secret)) {
throw new \Exception('Secret generation issue, please try again');
Expand Down
90 changes: 90 additions & 0 deletions src/Service/Action/Auth/SecondFactorTrait.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
<?php
declare(strict_types=1);

/**
* Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com)
* @license MIT License (https://www.opensource.org/licenses/mit-license.php)
*/

namespace CakeDC\Api\Service\Action\Auth;

use Cake\Datasource\EntityInterface;
use Cake\Http\Exception\BadRequestException;
use CakeDC\Api\Webauthn\Repository\UserCredentialSourceRepository;
use Webauthn\PublicKeyCredentialSource;

/**
* Checks which second factors an identity has registered.
*
* A password login gives a `/2fa` token, and that token can enroll a factor. Once one factor is
* registered, the token enrolls no other one.
*
* Expects the using class to provide `getService()` and `getUsersTable()`.
*/
trait SecondFactorTrait
{
/**
* Whether the identity has a verified OTP secret.
*
* @param \Cake\Datasource\EntityInterface|array|null $identity Identity.
* @return bool
*/
protected function _hasVerifiedOtp($identity): bool
{
// toArray() leaves out hidden fields such as `secret`, so read the fields one by one
if ($identity instanceof EntityInterface) {
$secret = $identity->get('secret');
$verified = $identity->get('secret_verified');
} else {
$secret = $identity['secret'] ?? null;
$verified = $identity['secret_verified'] ?? null;
}

return !empty($secret) && !empty($verified);
}

/**
* Whether the identity has a registered WebAuthn credential, under any domain.
*
* @param \Cake\Datasource\EntityInterface|array|null $identity Identity.
* @return bool
*/
protected function _hasWebauthnCredential($identity): bool
{
// web-auth/webauthn-lib is optional; without it no credential can have been registered
if (empty($identity) || !class_exists(PublicKeyCredentialSource::class)) {
return false;
}
// read the stored keys from the user record; a WebAuthn adapter would need the WebAuthn
// settings of the request's domain, which a domain that only uses OTP does not have
$id = $identity instanceof EntityInterface ? $identity->get('id') : ($identity['id'] ?? null);
if ($id === null) {
return false;
}
$usersTable = $this->getUsersTable();
$user = $usersTable->find()->where([$usersTable->aliasField('id') => $id])->first();

return $user !== null && UserCredentialSourceRepository::userHasCredentialOnAnyDomain($user);
}

/**
* Refuses to enroll a factor while another one is registered.
*
* @param bool $otherFactorRegistered Whether the identity has another registered factor.
* @return void
* @throws \Cake\Http\Exception\BadRequestException When another factor is registered.
*/
protected function _refuseEnrollmentIf(bool $otherFactorRegistered): void
{
if ($otherFactorRegistered) {
throw new BadRequestException(
__d('cake_d_c/api', 'Another second factor is already registered; verify with it instead')
);
}
}
}
9 changes: 4 additions & 5 deletions src/Service/Action/Auth/TwoFactorAuthAction.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@
namespace CakeDC\Api\Service\Action\Auth;

use CakeDC\Api\Service\Action\Action;
use CakeDC\Api\Webauthn\RegisterAdapter;
use CakeDC\Users\Controller\Traits\CustomUsersTableTrait;

/**
Expand All @@ -26,6 +25,7 @@ class TwoFactorAuthAction extends Action
{
use CustomUsersTableTrait;
use JwtTokenTrait;
use SecondFactorTrait;

/**
* Execute action.
Expand All @@ -35,12 +35,11 @@ class TwoFactorAuthAction extends Action
public function execute()
{
$user = $this->getIdentity();
$adapter = new RegisterAdapter($this->getService()->getRequest(), $this->getUsersTable(), $user);
$hasWebauthn = $adapter->hasCredential();
// keys of every domain count, and a verified secret counts as OTP
$hasWebauthn = $this->_hasWebauthnCredential($user);
$hasOtp = $this->_hasVerifiedOtp($user);
$user = $user->toArray();

$hasOtp = $user['secret'] && $user['secret_verified'];

return [
'hasRegistered2fa' => $hasWebauthn && $hasOtp,
'hasOtp' => $hasOtp,
Expand Down
5 changes: 4 additions & 1 deletion src/Service/Action/Auth/Webauthn2faRegisterAction.php
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
class Webauthn2faRegisterAction extends Action
{
use CustomUsersTableTrait;
use SecondFactorTrait;

/**
* Execute action.
Expand All @@ -35,9 +36,11 @@ class Webauthn2faRegisterAction extends Action
public function execute()
{
$user = $this->getIdentity();
$this->_refuseEnrollmentIf($this->_hasVerifiedOtp($user));
$adapter = new RegisterAdapter($this->getService()->getRequest(), $this->getUsersTable(), $user);

if (!$adapter->hasCredential()) {
// a key registered under another domain counts too: the domain can come from the Referer
if (!$adapter->hasCredentialOnAnyDomain()) {
$adapter->verifyResponse();

return ['success' => true];
Expand Down
5 changes: 4 additions & 1 deletion src/Service/Action/Auth/Webauthn2faRegisterOptionsAction.php
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
class Webauthn2faRegisterOptionsAction extends Action
{
use CustomUsersTableTrait;
use SecondFactorTrait;

/**
* Execute action.
Expand All @@ -35,9 +36,11 @@ class Webauthn2faRegisterOptionsAction extends Action
public function execute()
{
$user = $this->getIdentity();
$this->_refuseEnrollmentIf($this->_hasVerifiedOtp($user));
$adapter = new RegisterAdapter($this->getService()->getRequest(), $this->getUsersTable(), $user);

if (!$adapter->hasCredential()) {
// a key registered under another domain counts too: the domain can come from the Referer
if (!$adapter->hasCredentialOnAnyDomain()) {
return $adapter->getOptions();
}
throw new BadRequestException(
Expand Down
19 changes: 16 additions & 3 deletions src/Service/Action/Traits/ReCaptchaTrait.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
namespace CakeDC\Api\Service\Action\Traits;

use Cake\Core\Configure;
use Cake\Log\Log;
use CakeDC\Api\Utility\RequestParser;

/**
Expand All @@ -31,13 +32,25 @@ trait ReCaptchaTrait
*/
public function validateReCaptcha($recaptchaResponse = null)
{
$domain = RequestParser::getDomain($this->getService()->getRequest());
$reCaptcha = Configure::read('Api.reCaptcha.' . $domain);
if ($reCaptcha['disabled'] ?? false) {
if (Configure::read('Api.reCaptcha.disabled') === true) {
return true;
}
// turning validation off is a global setting; a domain setting only logs a warning, without a
// scope so that the application's default logs record it
$domain = RequestParser::getDomain($this->getService()->getRequest());
if (Configure::read('Api.reCaptcha.' . $domain . '.disabled')) {
Log::warning(sprintf(
'`Api.reCaptcha.%s.disabled` is ignored; set `Api.reCaptcha.disabled` to true instead',
$domain
));
}

$recaptcha = $this->_getReCaptchaInstance();
if ($recaptcha === null) {
Log::warning(sprintf('No reCaptcha secret is configured for `%s`; validation fails', $domain));

return false;
}
if ($recaptchaResponse === null) {
$recaptchaResponse = $this->getService()->getRequest()->getData('g-recaptcha-response');
}
Expand Down
7 changes: 4 additions & 3 deletions src/Utility/RequestParser.php
Original file line number Diff line number Diff line change
Expand Up @@ -30,10 +30,11 @@ class RequestParser
public static function getDomain(ServerRequest $request, $replace = true)
{
$domain = null;
if (isset($_SERVER['HTTP_REFERER']) && $_SERVER['HTTP_REFERER']) {
$domain = parse_url($_SERVER['HTTP_REFERER']);
$referer = $request->getHeaderLine('Referer');
if ($referer !== '') {
$domain = parse_url($referer);
}
if ($domain !== null && $domain['host']) {
if (is_array($domain) && !empty($domain['host'])) {
$host = $domain['host'];
} else {
$host = $request->domain();
Expand Down
10 changes: 10 additions & 0 deletions src/Webauthn/BaseAdapter.php
Original file line number Diff line number Diff line change
Expand Up @@ -147,6 +147,16 @@ public function hasCredential(): bool
);
}

/**
* Check if the user has a credential under any domain, not only the current one.
*
* @return bool
*/
public function hasCredentialOnAnyDomain(): bool
{
return $this->repository->hasCredentialOnAnyDomain();
}

/**
* Read the store data.
*
Expand Down
33 changes: 33 additions & 0 deletions src/Webauthn/Repository/UserCredentialSourceRepository.php
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,39 @@ public function findAllForUserEntity(PublicKeyCredentialUserEntity $publicKeyCre
return $list;
}

/**
* Whether the user has a credential under any domain, not only the current one.
*
* @return bool
*/
public function hasCredentialOnAnyDomain(): bool
{
return static::userHasCredentialOnAnyDomain($this->user);
}

/**
* Whether a user record has a credential under any domain.
*
* Needs no WebAuthn settings, so it also works for a domain that has none.
*
* @param \Cake\Datasource\EntityInterface|array $user User record.
* @return bool
*/
public static function userHasCredentialOnAnyDomain(EntityInterface|array $user): bool
{
$apiData = Hash::get($user, 'additional_data.api', []);
if (!is_array($apiData)) {
return false;
}
foreach ($apiData as $domainData) {
if (is_array($domainData) && !empty($domainData['webauthn_credentials'])) {
return true;
}
}

return false;
}

/**
* @param \Webauthn\PublicKeyCredentialSource $publicKeyCredentialSource Public key credential source
* @return void
Expand Down
2 changes: 2 additions & 0 deletions tests/Config/users.php
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,8 @@
// ],
],
'OAuth' => ['path' => null],
// robthree/twofactorauth 1.x has no Algorithm enum, so the CakeDC/Users default is null
'OneTimePasswordAuthenticator' => ['algorithm' => 'sha1'],
];

return $config;
Loading
Loading