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

* 11.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.
* `CachedApiRbac` now decides by the first matching rule of `api_permissions.php`, like `ApiRbac`. It used to check the rules of the user's role and of the requested service before the `*` rules, and on nested routes such as `/authors/1/articles` it checked the outer service instead of the service of the action. Role and service names are matched like in `ApiRbac`, so a rule for `Auth` also applies to the `auth` service. Rules that `ApiRbac` refuses for every user, such as a rule without an `action`, and rules with a callable or Rule role or service, are checked for every request, as in `ApiRbac`; a rule that `ApiRbac` refuses logs a warning when the map is built. A user whose role is a list of roles is matched as in `ApiRbac`. The permissions map holds the positions of the rules, and the rules themselves are read from the current permissions list, so a changed rule list, including a changed option of a Rule object, takes effect without clearing the cache, and rules set with `setPermissions()` are used. The map is cached under a key that starts with `CachedApiRbac::CACHE_KEY` and depends on the rules. `buildPermissionsMap()` now returns, by role and service, the positions of the rules in the list, and keeps the rules checked for every request under the `*` role and the `_` service. Rules with closures now work with a cache engine that serializes, such as File or Redis.
* Upgrade note: with `CachedApiRbac`, check rule lists that relied on role or service rules winning over earlier `*` rules, and rules for the inner service of nested routes, which now apply there. A rule without `service` or `action`, or with a `user` key, denies every request that reaches it, as in `ApiRbac`, so the rules after it no longer apply to those requests; such rules are logged as warnings. A role or service named like a PHP function, such as `file`, is called as that function, as in `ApiRbac`.
* `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. A refused WebAuthn registration answers HTTP 400 instead of failing with HTTP 500.
* 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`.

* 11.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',
],
],
],
```
223 changes: 195 additions & 28 deletions src/Rbac/CachedApiRbac.php
Original file line number Diff line number Diff line change
Expand Up @@ -28,9 +28,15 @@
class CachedApiRbac extends ApiRbac
{
/**
* A map of rules
* Prefix of the cache key of the permissions map. The key also depends on the rules, so a changed
* rule list builds a new map, and maps cached by earlier versions are not read.
*/
public const CACHE_KEY = 'api_permissions_map_ordered';

/**
* Positions of the rules in the permissions list, by role and service
*
* @var array[] rules array
* @var array<string, array<string, array<int, int>>>
*/
protected $permissionsMap = [];

Expand All @@ -42,15 +48,73 @@ class CachedApiRbac extends ApiRbac
public function __construct($config = [])
{
parent::__construct($config);
$this->permissionsMap = Cache::remember('api_permissions_map', function () {
$this->_loadPermissionsMap();
}

/**
* @param array $permissions permissions
* @return void
*/
public function setPermissions($permissions)
{
parent::setPermissions($permissions);
$this->_loadPermissionsMap();
}

/**
* Read the permissions map of the current rules from the cache, or build and cache it.
*
* @return void
*/
protected function _loadPermissionsMap(): void
{
$key = static::_cacheKey((array)$this->permissions);
$this->permissionsMap = Cache::remember($key, function () {
return $this->buildPermissionsMap();
}, '_cakedc_api_auth_');
}

/**
* Cache key of the permissions map of a rule list.
*
* The map holds rule positions only, and an object in a rule (a Rule or a closure) only decides
* where the rule is stored by its class, so the key uses the class of each object.
*
* @param array $permissions Permission rules.
* @return string
*/
protected static function _cacheKey(array $permissions): string
{
return static::CACHE_KEY . '_' . md5(serialize(static::_keyData(array_values($permissions))));
}

/**
* Rule data for the cache key: objects are replaced by their class name.
*
* @param mixed $value Rule list, rule or rule value.
* @return mixed
*/
protected static function _keyData($value)
{
if (is_object($value)) {
return ['__object' => get_class($value)];
}
if (is_array($value)) {
return array_map(function ($item) {
return static::_keyData($item);
}, $value);
}

return $value;
}

/**
* Build permissions map for caching
*
* @return array
* The map holds the position of each rule in the permissions list, not the rule, so the rules are
* always read from the current list.
*
* @return array<string, array<string, array<int, int>>>
*/
public function buildPermissionsMap()
{
Expand All @@ -69,18 +133,25 @@ public function buildPermissionsMap()
};

$map = [];
foreach ($this->permissions as $permission) {
if (isset($permission['role'])) {
$role = $permission['role'];
} else {
$role = '*';
// positions, not keys: a list with string or unordered keys is checked in its own order
foreach (array_values((array)$this->permissions) as $index => $permission) {
if ($this->_isRefused($permission)) {
$this->log(sprintf(
'Permission rule %d has no `service` or `action`, or has a `user` key: '
. 'it denies every request that reaches it',
$index + 1
), LogLevel::WARNING);
}
if (!$this->_isIndexable($permission)) {
// ApiRbac evaluates such a rule for every request, so every request has to find it
$map['*']['_'][$index] = $index;
continue;
}
$roles = (array)$role;
$roles = isset($permission['role']) ? (array)$permission['role'] : ['*'];
foreach ($roles as $role) {
$services = $asArray($permission, 'service', '*');
foreach ($services as $service) {
$key = $service;
$map[$role][$key][] = $permission;
$map[$role][$service][$index] = $index;
}
}
}
Expand All @@ -107,30 +178,126 @@ public function checkPermissions($user, ServerRequestInterface $request)
}

$target = (array)$request->getAttribute(self::TARGET_ATTRIBUTE);
$keys = array_merge((array)($target['service'] ?? $service->getName()), ['*']);
$candidates = $target['service'] ?? null;
if ($candidates === null) {
// ApiRbac checks the service of the action, which is the inner service on nested routes
$candidates = [$service->getName()];
$action = $service->getAction();
if ($action !== null) {
$candidates[] = $action->getService()->getName();
}
}
$candidates = (array)$candidates;

foreach ([$role, '*'] as $checkRole) {
if (!array_key_exists($checkRole, $this->permissionsMap)) {
// the map only narrows down the rules; each one is still matched, in the order of the
// permissions list, so the first matching rule decides as in ApiRbac
$rules = [];
// a role that is not a plain name, such as a list of roles, is left to the rule matching
$anyRole = !is_string($role) && !is_int($role);
foreach ($this->permissionsMap as $mapRole => $services) {
if (!$anyRole && !$this->_matchOrAsterisk((string)$mapRole, $role, true)) {
continue;
}
foreach ($keys as $key) {
if (!array_key_exists($key, $this->permissionsMap[$checkRole])) {
continue;
foreach ($services as $mapService => $serviceRules) {
if ($this->_matchesAnyService((string)$mapService, $candidates)) {
$rules += $serviceRules;
}
$permissions = $this->permissionsMap[$checkRole][$key];
foreach ($permissions as $permission) {
$matchResult = $this->_matchPermission($permission, $user, $role, $request);
if ($matchResult !== null) {
if ($this->getConfig('log')) {
$this->log($matchResult->getReason(), LogLevel::DEBUG);
}

return $matchResult->isAllowed();
}
}
}
ksort($rules);

$permissions = array_values((array)$this->permissions);
foreach ($rules as $index) {
if (!isset($permissions[$index])) {
continue;
}
$permission = $permissions[$index];
$matchResult = $this->_matchPermission($permission, $user, $role, $request);
if ($matchResult !== null) {
if ($this->getConfig('log')) {
$this->log($matchResult->getReason(), LogLevel::DEBUG);
}

return $matchResult->isAllowed();
}
}

return false;
}

/**
* Whether a rule can be stored under its role and service keys.
*
* Rules that ApiRbac refuses for every request (no `service` or `action`, or a `user` key), and
* rules whose role or service is not a plain name, such as a callable, are not.
*
* @param array $permission Permission rule.
* @return bool
*/
protected function _isIndexable(array $permission): bool
{
if ($this->_isRefused($permission)) {
return false;
}
foreach (['role', 'service'] as $key) {
if (!isset($permission[$key])) {
continue;
}
$value = $permission[$key];
// a `className` array is a Rule, which ApiRbac evaluates for every request
if (is_array($value) && isset($value['className'])) {
return false;
}
// so is a callable, including a function name such as `'file'`
if (is_callable($value)) {
return false;
}
foreach (is_array($value) ? $value : [$value] as $name) {
if (!is_string($name) && !is_int($name)) {
return false;
}
}
}

return true;
}

/**
* Whether ApiRbac refuses the rule for every request: it has no `service` or `action`, or it has a
* `user` key.
*
* @param array $permission Permission rule.
* @return bool
*/
protected function _isRefused(array $permission): bool
{
$issetService = isset($permission['service']) || isset($permission['*service']);
$issetAction = isset($permission['action']) || isset($permission['*action']);

return !$issetService || !$issetAction || isset($permission['user']) || isset($permission['*user']);
}

/**
* Whether rules stored under a service key can apply to one of the service names.
*
* Uses the same comparison as ApiRbac, so `Auth` matches the `auth` service. Rules with an
* empty service (key `_`) are kept and left to the rule matching.
*
* @param string $mapService Service key of the map.
* @param array $candidates Service names of the request.
* @return bool
*/
protected function _matchesAnyService(string $mapService, array $candidates): bool
{
if ($mapService === '_') {
return true;
}
foreach ($candidates as $candidate) {
if ($this->_matchOrAsterisk($mapService, $candidate, true)) {
return true;
}
}

return false;
}
}
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
Loading
Loading