diff --git a/CHANGELOG.md b/CHANGELOG.md index 9ac5f5f..60ef6f6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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..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. diff --git a/docs/Documentation/configuration.md b/docs/Documentation/configuration.md index 8e25e0d..332fafd 100644 --- a/docs/Documentation/configuration.md +++ b/docs/Documentation/configuration.md @@ -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..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.` 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', + ], + ], +], +``` diff --git a/src/Rbac/CachedApiRbac.php b/src/Rbac/CachedApiRbac.php index 74f7846..8d0e7d8 100644 --- a/src/Rbac/CachedApiRbac.php +++ b/src/Rbac/CachedApiRbac.php @@ -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>> */ protected $permissionsMap = []; @@ -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>> */ public function buildPermissionsMap() { @@ -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; } } } @@ -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; } } diff --git a/src/Service/Action/Auth/OtpVerifyAction.php b/src/Service/Action/Auth/OtpVerifyAction.php index 24bc23f..b250368 100644 --- a/src/Service/Action/Auth/OtpVerifyAction.php +++ b/src/Service/Action/Auth/OtpVerifyAction.php @@ -26,6 +26,7 @@ abstract class OtpVerifyAction extends Action { use CustomUsersTableTrait; + use SecondFactorTrait; /** * @var \RobThree\Auth\TwoFactorAuth $tfa diff --git a/src/Service/Action/Auth/OtpVerifyCheckAction.php b/src/Service/Action/Auth/OtpVerifyCheckAction.php index 470eb3c..45083cb 100644 --- a/src/Service/Action/Auth/OtpVerifyCheckAction.php +++ b/src/Service/Action/Auth/OtpVerifyCheckAction.php @@ -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); diff --git a/src/Service/Action/Auth/OtpVerifyGetAction.php b/src/Service/Action/Auth/OtpVerifyGetAction.php index d2c6b8d..4abac5f 100644 --- a/src/Service/Action/Auth/OtpVerifyGetAction.php +++ b/src/Service/Action/Auth/OtpVerifyGetAction.php @@ -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'); diff --git a/src/Service/Action/Auth/SecondFactorTrait.php b/src/Service/Action/Auth/SecondFactorTrait.php new file mode 100644 index 0000000..099e3e3 --- /dev/null +++ b/src/Service/Action/Auth/SecondFactorTrait.php @@ -0,0 +1,90 @@ +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') + ); + } + } +} diff --git a/src/Service/Action/Auth/TwoFactorAuthAction.php b/src/Service/Action/Auth/TwoFactorAuthAction.php index 3eb200b..bd811ba 100644 --- a/src/Service/Action/Auth/TwoFactorAuthAction.php +++ b/src/Service/Action/Auth/TwoFactorAuthAction.php @@ -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; /** @@ -26,6 +25,7 @@ class TwoFactorAuthAction extends Action { use CustomUsersTableTrait; use JwtTokenTrait; + use SecondFactorTrait; /** * Execute action. @@ -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, diff --git a/src/Service/Action/Auth/Webauthn2faRegisterAction.php b/src/Service/Action/Auth/Webauthn2faRegisterAction.php index c53a97c..247abde 100644 --- a/src/Service/Action/Auth/Webauthn2faRegisterAction.php +++ b/src/Service/Action/Auth/Webauthn2faRegisterAction.php @@ -13,6 +13,7 @@ namespace CakeDC\Api\Service\Action\Auth; +use Cake\Http\Exception\BadRequestException; use CakeDC\Api\Service\Action\Action; use CakeDC\Api\Webauthn\RegisterAdapter; use CakeDC\Users\Controller\Traits\CustomUsersTableTrait; @@ -25,6 +26,7 @@ class Webauthn2faRegisterAction extends Action { use CustomUsersTableTrait; + use SecondFactorTrait; /** * Execute action. @@ -34,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]; diff --git a/src/Service/Action/Auth/Webauthn2faRegisterOptionsAction.php b/src/Service/Action/Auth/Webauthn2faRegisterOptionsAction.php index 8dc3f36..72794da 100644 --- a/src/Service/Action/Auth/Webauthn2faRegisterOptionsAction.php +++ b/src/Service/Action/Auth/Webauthn2faRegisterOptionsAction.php @@ -26,6 +26,7 @@ class Webauthn2faRegisterOptionsAction extends Action { use CustomUsersTableTrait; + use SecondFactorTrait; /** * Execute action. @@ -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( diff --git a/src/Service/Action/Traits/ReCaptchaTrait.php b/src/Service/Action/Traits/ReCaptchaTrait.php index 3aff708..17a2ce9 100644 --- a/src/Service/Action/Traits/ReCaptchaTrait.php +++ b/src/Service/Action/Traits/ReCaptchaTrait.php @@ -14,6 +14,7 @@ namespace CakeDC\Api\Service\Action\Traits; use Cake\Core\Configure; +use Cake\Log\Log; use CakeDC\Api\Utility\RequestParser; /** @@ -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'); } diff --git a/src/Utility/RequestParser.php b/src/Utility/RequestParser.php index 3483f5f..33bc8e4 100644 --- a/src/Utility/RequestParser.php +++ b/src/Utility/RequestParser.php @@ -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(); diff --git a/src/Webauthn/BaseAdapter.php b/src/Webauthn/BaseAdapter.php index 34f6f20..d8f6db9 100644 --- a/src/Webauthn/BaseAdapter.php +++ b/src/Webauthn/BaseAdapter.php @@ -126,6 +126,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. * diff --git a/src/Webauthn/Repository/UserCredentialSourceRepository.php b/src/Webauthn/Repository/UserCredentialSourceRepository.php index e992c46..7f8c647 100644 --- a/src/Webauthn/Repository/UserCredentialSourceRepository.php +++ b/src/Webauthn/Repository/UserCredentialSourceRepository.php @@ -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($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 diff --git a/tests/App/Application.php b/tests/App/Application.php index 75735ea..b39be12 100644 --- a/tests/App/Application.php +++ b/tests/App/Application.php @@ -17,12 +17,14 @@ namespace CakeDC\Api\Test\App; +use Authentication\Middleware\AuthenticationMiddleware; use Cake\Core\Configure; use Cake\Error\Middleware\ErrorHandlerMiddleware; use Cake\Http\BaseApplication; use Cake\Http\MiddlewareQueue; use Cake\Routing\Middleware\AssetMiddleware; use Cake\Routing\Middleware\RoutingMiddleware; +use CakeDC\Api\ApiInitializer; use CakeDC\Api\Middleware\ParseApiRequestMiddleware; use CakeDC\Api\Middleware\ProcessApiRequestMiddleware; use CakeDC\Api\Service\ServiceRegistry; @@ -67,8 +69,12 @@ public function middleware(MiddlewareQueue $middleware): MiddlewareQueue $middleware // Catch any exceptions in the lower layers, // and make an error page/response - ->add(new ErrorHandlerMiddleware([])) - // ->add($authentication) + ->add(new ErrorHandlerMiddleware([])); + if (Configure::read('Test.Api.Authentication')) { + // the requests of the two-factor tests need the identity from their JWT + $middleware->add(new AuthenticationMiddleware((new ApiInitializer())->getAuthenticationService())); + } + $middleware // Apply Api ->add(new ParseApiRequestMiddleware()) ->add(new ProcessApiRequestMiddleware()) diff --git a/tests/Config/users.php b/tests/Config/users.php index e1d40fc..36946ce 100644 --- a/tests/Config/users.php +++ b/tests/Config/users.php @@ -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; diff --git a/tests/Fixture/AuthStoreFixture.php b/tests/Fixture/AuthStoreFixture.php new file mode 100644 index 0000000..2003838 --- /dev/null +++ b/tests/Fixture/AuthStoreFixture.php @@ -0,0 +1,36 @@ +assertEquals($expected, $data); } diff --git a/tests/TestCase/Integration/Service/Action/Auth/RegisterActionTest.php b/tests/TestCase/Integration/Service/Action/Auth/RegisterActionTest.php index 94bacab..0c49952 100644 --- a/tests/TestCase/Integration/Service/Action/Auth/RegisterActionTest.php +++ b/tests/TestCase/Integration/Service/Action/Auth/RegisterActionTest.php @@ -82,6 +82,8 @@ public function testSuccessRegister() ]; $data = $result['data']; unset($data['id'], $data['tos_date']); + // two-factor columns of the test schema + unset($data['secret'], $data['secret_verified'], $data['additional_data']); $this->assertEquals($expected, $data); } diff --git a/tests/TestCase/Integration/Service/Action/Auth/SecondFactorEnrollmentTest.php b/tests/TestCase/Integration/Service/Action/Auth/SecondFactorEnrollmentTest.php new file mode 100644 index 0000000..bc1adcd --- /dev/null +++ b/tests/TestCase/Integration/Service/Action/Auth/SecondFactorEnrollmentTest.php @@ -0,0 +1,222 @@ +clear(); + $this->_authAccess(); + Configure::write('App.fullBaseUrl', 'http://example.com'); + $config = include dirname(__DIR__, 5) . DS . 'Config' . DS . 'api.php'; + $config['Api']['2fa']['enabled'] = true; + $config['Api']['OneTimePasswordAuthenticator']['login'] = true; + // a second WebAuthn domain, chosen by the Referer header + $config['Api']['Webauthn2fa']['other$test'] = ['appName' => 'other', 'id' => self::RP_ID]; + Configure::write('Test.Api.Config', $config); + Configure::write('Test.Api.Authentication', true); + $this->setOtp(null, false); + } + + public function tearDown(): void + { + parent::tearDown(); + Configure::delete('Test.Api.Config'); + Configure::delete('Test.Api.Authentication'); + } + + /** + * @param string|null $secret OTP secret of user-1. + * @param bool $verified Whether the secret is verified. + * @return void + */ + protected function setOtp(?string $secret, bool $verified): void + { + TableRegistry::getTableLocator()->get('CakeDC/Users.Users')->updateQuery() + ->set(['secret' => $secret, 'secret_verified' => $verified]) + ->where(['username' => 'user-1']) + ->execute(); + } + + /** + * Asserts that the request was refused and returned no token or secret. + * + * @param array $result JSend body. + * @return void + */ + protected function assertRefused(array $result): void + { + $this->assertSame('error', $result['status'] ?? null, (string)$this->_response->getBody()); + $this->assertArrayNotHasKey('access_token', (array)($result['data'] ?? [])); + $this->assertArrayNotHasKey('secret', (array)($result['data'] ?? [])); + } + + public function testWebauthnRegistrationWorks(): void + { + [$login] = $this->loginAndRegister(); + $this->assertNotEmpty($login['access_token']); + } + + public function testWebauthnCannotBeEnrolledWhenOtpIsVerified(): void + { + $this->setOtp(self::SECRET, true); + $login = $this->login(); + + $this->assertRefused($this->withToken('/auth/webauthn2fa_register_options', 'GET', [], $login['access_token'])); + $this->assertRefused($this->withToken( + '/auth/webauthn2fa_register', + 'POST', + $this->attestation($this->newKey(), random_bytes(16), static::b64url(random_bytes(32))), + $login['access_token'], + )); + } + + public function testWebauthnCanBeEnrolledWhileOtpIsOnlyStarted(): void + { + // an unverified secret is not a registered factor + $this->setOtp(self::SECRET, false); + [$login] = $this->loginAndRegister(); + $this->assertNotEmpty($login['access_token']); + } + + public function testOtpCannotBeEnrolledWhenWebauthnIsRegistered(): void + { + [$login] = $this->loginAndRegister(); + + $this->assertRefused($this->withToken('/auth/otp_verify', 'GET', [], $login['access_token'])); + + // a secret provisioned before the key was registered cannot be verified either + $this->setOtp(self::SECRET, false); + $tfa = new TwoFactorAuth(); + $this->assertRefused($this->withToken( + '/auth/otp_verify_check', + 'POST', + ['code' => $tfa->getCode(self::SECRET)], + $login['access_token'], + )); + } + + public function testVerifiedOtpStillWorksWhenWebauthnIsAlsoRegistered(): void + { + // a user who registered both factors earlier can still pass the second step with OTP + [$login] = $this->loginAndRegister(); + $this->setOtp(self::SECRET, true); + $tfa = new TwoFactorAuth(); + + $check = $this->withToken('/auth/otp_verify_check', 'POST', ['code' => $tfa->getCode(self::SECRET)], $login['access_token']); + $this->assertSame('success', $check['status'] ?? null, (string)$this->_response->getBody()); + } + + public function testWebauthnCannotBeRegisteredUnderAnotherDomain(): void + { + [$login] = $this->loginAndRegister(); + + $options = $this->withToken('/auth/webauthn2fa_register_options', 'GET', [], $login['access_token'], self::OTHER_DOMAIN); + $this->assertRefused($options); + $this->assertRefused($this->withToken( + '/auth/webauthn2fa_register', + 'POST', + $this->attestation($this->newKey(), random_bytes(16), (string)($options['data']['challenge'] ?? static::b64url(random_bytes(32)))), + $login['access_token'], + self::OTHER_DOMAIN, + )); + } + + public function testOtpCannotBeEnrolledWhenWebauthnIsRegisteredUnderAnotherDomain(): void + { + [$login] = $this->loginAndRegister(); + + $this->assertRefused($this->withToken('/auth/otp_verify', 'GET', [], $login['access_token'], self::OTHER_DOMAIN)); + } + + public function testOtpCanBeEnrolledOnADomainWithoutWebauthnSettings(): void + { + if (!class_exists(TwoFactorAuth::class)) { + $this->markTestSkipped('robthree/twofactorauth is not installed'); + } + $login = $this->login(); + + $verify = $this->withToken('/auth/otp_verify', 'GET', [], $login['access_token'], 'https://unconfigured.test/'); + $this->assertSame('success', $verify['status'] ?? null, (string)$this->_response->getBody()); + $this->assertNotEmpty($verify['data']['secret'] ?? null); + } + + public function testOtpCanBeEnrolledWithoutTheLocalhostWebauthnEntry(): void + { + if (!class_exists(TwoFactorAuth::class)) { + $this->markTestSkipped('robthree/twofactorauth is not installed'); + } + $config = Configure::read('Test.Api.Config'); + $config['Api']['Webauthn2fa']['localhost'] = null; + Configure::write('Test.Api.Config', $config); + $login = $this->login(); + + $verify = $this->withToken('/auth/otp_verify', 'GET', [], $login['access_token']); + $this->assertSame('success', $verify['status'] ?? null, (string)$this->_response->getBody()); + $this->assertNotEmpty($verify['data']['secret'] ?? null); + } + + public function testTwoFactorStatusOnADomainWithoutWebauthnSettings(): void + { + [$login] = $this->loginAndRegister(); + + $status = $this->withToken('/auth/two_factor_auth', 'GET', [], $login['access_token'], 'https://unconfigured.test/'); + $this->assertSame('success', $status['status'] ?? null, (string)$this->_response->getBody()); + $this->assertTrue($status['data']['hasWebauthn']); + } + + public function testTwoFactorStatusReportsBothFactors(): void + { + [$login] = $this->loginAndRegister(); + $this->setOtp(self::SECRET, true); + + $status = $this->withToken('/auth/two_factor_auth', 'GET', [], $login['access_token'], self::OTHER_DOMAIN); + $this->assertSame('success', $status['status'] ?? null, (string)$this->_response->getBody()); + $this->assertTrue($status['data']['hasOtp']); + $this->assertTrue($status['data']['hasWebauthn']); + } +} diff --git a/tests/TestCase/Integration/Service/Action/Auth/SoftwareAuthenticatorTrait.php b/tests/TestCase/Integration/Service/Action/Auth/SoftwareAuthenticatorTrait.php new file mode 100644 index 0000000..f1aed9a --- /dev/null +++ b/tests/TestCase/Integration/Service/Action/Auth/SoftwareAuthenticatorTrait.php @@ -0,0 +1,192 @@ + + */ + protected function jwtPayload(string $token): array + { + $parts = explode('.', $token); + + return json_decode(base64_decode(strtr($parts[1], '-_', '+/')), true, 512, JSON_THROW_ON_ERROR); + } + + /** + * Sends a request with a JWT and returns the decoded JSend body. + * + * @param string $url Url. + * @param string $method HTTP method. + * @param array $data Request data. + * @param string $token JWT. + * @param string|null $referer Referer header, which selects the WebAuthn domain. + * @return array + */ + protected function withToken(string $url, string $method, array $data, string $token, ?string $referer = null): array + { + ServiceRegistry::getServiceLocator()->clear(); + $headers = ['Authorization' => 'Bearer ' . $token]; + if ($referer !== null) { + $headers['Referer'] = $referer; + } + $this->sendRequest($url, $method, $data, null, $headers); + + return (array)json_decode((string)$this->_response->getBody(), true); + } + + /** + * Logs user-1 in with the password and returns the token response data. + * + * @return array + */ + protected function login(): array + { + ServiceRegistry::getServiceLocator()->clear(); + $this->sendRequest('/auth/jwt_login', 'POST', ['username' => 'user-1', 'password' => '12345']); + $result = $this->getJsonResponse(); + $this->assertSuccess($result); + + return $result['data']; + } + + /** + * @return resource|\OpenSSLAsymmetricKey A new P-256 key pair, the software authenticator's credential key. + */ + protected function newKey() + { + $key = openssl_pkey_new(['curve_name' => 'prime256v1', 'private_key_type' => OPENSSL_KEYTYPE_EC]); + $this->assertNotFalse($key); + + return $key; + } + + /** + * Builds the registration response a browser sends after navigator.credentials.create(). + * + * @param resource|\OpenSSLAsymmetricKey $key Credential key. + * @param string $credentialId Credential id. + * @param string $challenge Base64url challenge from the creation options. + * @param string $origin Origin the browser reports. + * @return array + */ + protected function attestation($key, string $credentialId, string $challenge, string $origin = self::ORIGIN): array + { + $ec = openssl_pkey_get_details($key)['ec']; + $coseKey = MapObject::create() + ->add(UnsignedIntegerObject::create(1), UnsignedIntegerObject::create(2)) // kty: EC2 + ->add(UnsignedIntegerObject::create(3), NegativeIntegerObject::create(-7)) // alg: ES256 + ->add(NegativeIntegerObject::create(-1), UnsignedIntegerObject::create(1)) // crv: P-256 + ->add(NegativeIntegerObject::create(-2), ByteStringObject::create(str_pad($ec['x'], 32, "\0", STR_PAD_LEFT))) + ->add(NegativeIntegerObject::create(-3), ByteStringObject::create(str_pad($ec['y'], 32, "\0", STR_PAD_LEFT))); + $authData = hash('sha256', self::RP_ID, true) + . chr(0x45) // user present, user verified, attested credential data + . pack('N', 0) + . str_repeat("\0", 16) // AAGUID + . pack('n', strlen($credentialId)) . $credentialId + . $coseKey; + $attestationObject = MapObject::create() + ->add(TextStringObject::create('fmt'), TextStringObject::create('none')) + ->add(TextStringObject::create('attStmt'), MapObject::create()) + ->add(TextStringObject::create('authData'), ByteStringObject::create($authData)); + $clientData = json_encode(['type' => 'webauthn.create', 'challenge' => $challenge, 'origin' => $origin], JSON_THROW_ON_ERROR); + + return [ + 'id' => static::b64url($credentialId), + 'rawId' => base64_encode($credentialId), + 'type' => 'public-key', + 'response' => [ + 'clientDataJSON' => static::b64url($clientData), + 'attestationObject' => static::b64url((string)$attestationObject), + ], + ]; + } + + /** + * Builds the authentication response a browser sends after navigator.credentials.get(). + * + * @param resource|\OpenSSLAsymmetricKey $key Key that signs the assertion. + * @param string $credentialId Credential id. + * @param string $challenge Base64url challenge from the request options. + * @param int $signCount Signature counter. + * @return array + */ + protected function assertion($key, string $credentialId, string $challenge, int $signCount = 1): array + { + $authData = hash('sha256', self::RP_ID, true) . chr(0x05) . pack('N', $signCount); // user present, user verified + $clientData = json_encode(['type' => 'webauthn.get', 'challenge' => $challenge, 'origin' => self::ORIGIN], JSON_THROW_ON_ERROR); + $this->assertTrue(openssl_sign($authData . hash('sha256', $clientData, true), $signature, $key, OPENSSL_ALGO_SHA256)); + + return [ + 'id' => static::b64url($credentialId), + 'rawId' => base64_encode($credentialId), + 'type' => 'public-key', + 'response' => [ + 'clientDataJSON' => static::b64url($clientData), + 'authenticatorData' => static::b64url($authData), + 'signature' => base64_encode($signature), + ], + ]; + } + + /** + * Logs in and registers a new credential. + * + * @return array{0: array, 1: resource|\OpenSSLAsymmetricKey, 2: string} Login data, key and credential id. + */ + protected function loginAndRegister(): array + { + $login = $this->login(); + $key = $this->newKey(); + $credentialId = random_bytes(16); + + $options = $this->withToken('/auth/webauthn2fa_register_options', 'GET', [], $login['access_token']); + $this->assertSame('success', $options['status'], (string)$this->_response->getBody()); + $register = $this->withToken( + '/auth/webauthn2fa_register', + 'POST', + $this->attestation($key, $credentialId, $options['data']['challenge']), + $login['access_token'], + ); + $this->assertSame('success', $register['status'], (string)$this->_response->getBody()); + + return [$login, $key, $credentialId]; + } +} diff --git a/tests/TestCase/Integration/Service/Action/RecaptchaValidateTest.php b/tests/TestCase/Integration/Service/Action/RecaptchaValidateTest.php new file mode 100644 index 0000000..bdb84df --- /dev/null +++ b/tests/TestCase/Integration/Service/Action/RecaptchaValidateTest.php @@ -0,0 +1,70 @@ +_authAccess(); + Configure::write('App.fullBaseUrl', 'http://localhost'); + } + + public function tearDown(): void + { + Configure::delete('Test.Api.Config'); + parent::tearDown(); + } + + /** + * @param array $reCaptcha `Api.reCaptcha` settings. + * @return void + */ + protected function configureReCaptcha(array $reCaptcha): void + { + $config = include dirname(__DIR__, 4) . DS . 'Config' . DS . 'api.php'; + $config['Api']['reCaptcha'] = $reCaptcha; + Configure::write('Test.Api.Config', $config); + } + + public function testGlobalDisabledPasses(): void + { + $this->configureReCaptcha(['disabled' => true]); + $this->sendRequest('/recaptcha/validate', 'POST', ['g-recaptcha-response' => 'token']); + $result = $this->getJsonResponse(); + + $this->assertSuccess($result); + $this->assertTrue($result['data']); + } + + public function testDomainDisabledWithoutSecretFails(): void + { + $this->configureReCaptcha(['localhost' => ['disabled' => true]]); + $this->sendRequest('/recaptcha/validate', 'POST', ['g-recaptcha-response' => 'token']); + $result = $this->getJsonResponse(); + + $this->assertSuccess($result); + $this->assertFalse($result['data']); + } +} diff --git a/tests/TestCase/Rbac/ApiRbacKeyOrderTest.php b/tests/TestCase/Rbac/ApiRbacKeyOrderTest.php index 8dd79b0..e260dd7 100644 --- a/tests/TestCase/Rbac/ApiRbacKeyOrderTest.php +++ b/tests/TestCase/Rbac/ApiRbacKeyOrderTest.php @@ -15,6 +15,7 @@ use Cake\Cache\Cache; use Cake\Http\ServerRequest; +use Cake\Log\Log; use CakeDC\Api\Rbac\ApiRbac; use CakeDC\Api\Rbac\CachedApiRbac; use CakeDC\Api\Service\Action\CrudAction; @@ -128,4 +129,418 @@ public function testCachedRbacChecksTheTarget(): void $this->assertTrue($rbac->checkPermissions(['id' => 1, 'role' => 'user'], $request)); $this->assertFalse($rbac->checkPermissions(['id' => 1, 'role' => 'user'], $this->request('articles', 'view'))); } + + /** + * Rule lists where the order of rules for different roles or services decides the result. + * + * @return array + */ + public static function orderedRulesProvider(): array + { + $deny = ['action' => '*', 'method' => '*', 'allowed' => false]; + $allow = ['action' => '*', 'method' => '*', 'allowed' => true]; + + return [ + 'any role denied before own role allowed' => [[ + ['role' => '*', 'service' => 'articles'] + $deny, + ['role' => 'user', 'service' => 'articles'] + $allow, + ], false], + 'own role allowed before any role denied' => [[ + ['role' => 'user', 'service' => 'articles'] + $allow, + ['role' => '*', 'service' => 'articles'] + $deny, + ], true], + 'any service denied before own service allowed' => [[ + ['role' => 'user', 'service' => '*'] + $deny, + ['role' => 'user', 'service' => 'articles'] + $allow, + ], false], + 'role list denied before own role allowed' => [[ + ['role' => ['admin', 'user'], 'service' => ['authors', 'articles']] + $deny, + ['role' => 'user', 'service' => 'articles'] + $allow, + ], false], + 'camelized service name allowed' => [[ + ['role' => 'user', 'service' => 'Articles'] + $allow, + ], true], + 'string keys keep their order' => [[ + 'z_deny' => ['role' => '*', 'service' => '*'] + $deny, + 'a_allow' => ['role' => '*', 'service' => '*'] + $allow, + ], false], + 'unordered keys keep their order' => [[ + 5 => ['role' => '*', 'service' => '*'] + $deny, + 1 => ['role' => '*', 'service' => '*'] + $allow, + ], false], + 'rule without an action refuses every role' => [[ + ['role' => 'admin', 'service' => 'articles', 'allowed' => true], + ['role' => '*', 'service' => '*'] + $allow, + ], false], + 'function name role is checked' => [[ + ['role' => __NAMESPACE__ . '\\cachedRbacRuleFunction', 'service' => 'articles'] + $deny, + ['role' => '*', 'service' => '*'] + $allow, + ], false], + 'static method role is checked' => [[ + ['role' => [self::class, 'callableRule'], 'service' => 'articles'] + $deny, + ['role' => '*', 'service' => '*'] + $allow, + ], false], + 'Class::method role is checked' => [[ + ['role' => self::class . '::callableRule', 'service' => 'articles'] + $deny, + ['role' => '*', 'service' => '*'] + $allow, + ], false], + 'static method service is checked' => [[ + ['role' => 'user', 'service' => [self::class, 'callableRule']] + $deny, + ['role' => '*', 'service' => '*'] + $allow, + ], false], + 'static method allowed is called' => [[ + ['role' => 'user', 'service' => 'articles', 'action' => '*', 'method' => '*', + 'allowed' => [self::class, 'denyingRule']], + ['role' => '*', 'service' => '*'] + $allow, + ], false], + 'Class::method allowed is called' => [[ + ['role' => 'user', 'service' => 'articles', 'action' => '*', 'method' => '*', + 'allowed' => self::class . '::denyingRule'], + ['role' => '*', 'service' => '*'] + $allow, + ], false], + 'rule with a user key refuses every role' => [[ + ['role' => '*', 'service' => '*', 'user' => 'someone'] + $allow, + ['role' => '*', 'service' => '*'] + $allow, + ], false], + 'non-string role is checked' => [[ + ['role' => true, 'service' => 'articles'] + $deny, + ['role' => '*', 'service' => '*'] + $allow, + ], false], + 'callable role is checked' => [[ + ['role' => function () { + return true; + }, 'service' => 'articles'] + $deny, + ['role' => '*', 'service' => '*'] + $allow, + ], false], + ]; + } + + /** + * CachedApiRbac decides by the first matching rule, like ApiRbac. + * + * @dataProvider orderedRulesProvider + * @param array $rules Permission rules. + * @param bool $expected Expected decision. + * @return void + */ + public function testCachedRbacFollowsTheRuleOrder(array $rules, bool $expected): void + { + $request = $this->request('articles', 'index'); + + $this->assertSame($expected, $this->check($rules, $request)); + $this->assertSame($expected, $this->cached($rules)->checkPermissions(['id' => 1, 'role' => 'user'], $request)); + } + + /** + * On a nested route the rules of the inner service apply, as with ApiRbac. + * + * @return void + */ + public function testCachedRbacChecksTheActionServiceOnNestedRoutes(): void + { + $inner = $this->createMock(CrudService::class); + $inner->method('getName')->willReturn('articles'); + $action = $this->createMock(CrudAction::class); + $action->method('getName')->willReturn('index'); + $action->method('getService')->willReturn($inner); + $outer = $this->createMock(CrudService::class); + $outer->method('getName')->willReturn('authors'); + $outer->method('getAction')->willReturn($action); + $request = (new ServerRequest(['environment' => ['REQUEST_METHOD' => 'GET']]))->withAttribute('service', $outer); + $deny = ['action' => '*', 'method' => '*', 'allowed' => false]; + $allow = ['action' => '*', 'method' => '*', 'allowed' => true]; + + $cases = [ + [[['role' => 'user', 'service' => 'articles'] + $deny, ['role' => '*', 'service' => '*'] + $allow], false], + [[['role' => 'user', 'service' => 'articles'] + $allow], true], + ]; + foreach ($cases as [$rules, $expected]) { + $this->assertSame($expected, $this->check($rules, $request)); + $this->assertSame($expected, $this->cached($rules)->checkPermissions(['id' => 1, 'role' => 'user'], $request)); + } + } + + /** + * A callable for a rule's role or service. + * + * @return bool + */ + public static function callableRule(): bool + { + return true; + } + + /** + * A callable for a rule's `allowed` key that denies. + * + * @return bool + */ + public static function denyingRule(): bool + { + return false; + } + + /** + * A user role that is not a plain name is matched as ApiRbac matches it. + * + * @return void + */ + public function testCachedRbacMatchesARoleList(): void + { + $rules = [['role' => ['admin', 'user'], 'service' => '*', 'action' => '*', 'method' => '*', 'allowed' => true]]; + $user = ['id' => 1, 'role' => ['admin', 'user']]; + $request = $this->request('articles', 'index'); + $rbac = new ApiRbac(); + $rbac->setPermissions($rules); + + $this->assertTrue($rbac->checkPermissions($user, $request)); + $this->assertTrue($this->cached($rules)->checkPermissions($user, $request)); + } + + /** + * A role written in another form, such as `SuperAdmin`, is matched as ApiRbac matches it. + * + * @return void + */ + public function testCachedRbacMatchesACamelizedRole(): void + { + $rules = [['role' => 'SuperAdmin', 'service' => '*', 'action' => '*', 'method' => '*', 'allowed' => true]]; + $user = ['id' => 1, 'role' => 'super_admin']; + $request = $this->request('articles', 'index'); + $rbac = new ApiRbac(); + $rbac->setPermissions($rules); + + $this->assertTrue($rbac->checkPermissions($user, $request)); + $this->assertTrue($this->cached($rules)->checkPermissions($user, $request)); + } + + /** + * A changed rule list takes effect without clearing the cache. + * + * @return void + */ + public function testCachedRbacUsesAChangedRuleList(): void + { + $rule = ['role' => '*', 'service' => '*', 'action' => '*', 'method' => '*']; + $this->warmCache([$rule + ['allowed' => true]]); + $rbac = new CachedApiRbac(['api_permissions' => [$rule + ['allowed' => false]]]); + Cache::clear('_cakedc_api_auth_'); + + $this->assertFalse($rbac->checkPermissions(['id' => 1, 'role' => 'user'], $this->request('articles', 'index'))); + } + + /** + * A rule that ApiRbac refuses for every request is logged when the map is built. + * + * @return void + */ + public function testCachedRbacLogsARefusedRule(): void + { + Log::setConfig('cached_rbac_test', ['className' => 'Array', 'levels' => ['warning']]); + try { + $this->cached([ + ['role' => '*', 'service' => '*', 'action' => '*', 'method' => '*', 'allowed' => true], + ['role' => 'admin', 'service' => 'reports', 'allowed' => true], + ]); + $logged = implode("\n", Log::engine('cached_rbac_test')->read()); + } finally { + Log::drop('cached_rbac_test'); + } + + $this->assertStringContainsString('Permission rule 2 has no `service` or `action`', $logged); + } + + /** + * Rules for a target are checked in their order. + * + * @return void + */ + public function testCachedRbacFollowsTheRuleOrderForATarget(): void + { + $rules = [ + ['role' => '*', 'service' => 'authors', 'action' => '*', 'method' => '*', 'allowed' => false], + ['role' => 'user', 'service' => 'authors', 'action' => '*', 'method' => '*', 'allowed' => true], + ]; + $request = $this->request('articles', 'view') + ->withAttribute(ApiRbac::TARGET_ATTRIBUTE, ['service' => ['authors', 'Authors'], 'action' => 'index']); + + $this->assertFalse($this->check($rules, $request)); + $this->assertFalse($this->cached($rules)->checkPermissions(['id' => 1, 'role' => 'user'], $request)); + } + + /** + * A map cached by an earlier version is not used. + * + * @return void + */ + public function testCachedRbacIgnoresMapsOfEarlierVersions(): void + { + if (!Cache::getConfig('_cakedc_api_auth_')) { + Cache::setConfig('_cakedc_api_auth_', ['className' => 'Array']); + } + Cache::clear('_cakedc_api_auth_'); + $allowAll = ['role' => '*', 'service' => '*', 'action' => '*', 'method' => '*', 'allowed' => true]; + Cache::write('api_permissions_map', ['*' => ['*' => [$allowAll]]], '_cakedc_api_auth_'); + $rbac = new CachedApiRbac(['api_permissions' => []]); + Cache::clear('_cakedc_api_auth_'); + + $this->assertFalse($rbac->checkPermissions(['id' => 1, 'role' => 'user'], $this->request('articles', 'index'))); + } + + /** + * A changed option of a Rule object takes effect without clearing a cache that serializes. + * + * @return void + */ + public function testCachedRbacUsesChangedRuleOptions(): void + { + $rule = ['role' => '*', 'service' => '*', 'action' => '*', 'method' => '*']; + $this->withFileCache(function () use ($rule) { + new CachedApiRbac(['api_permissions' => [$rule + ['allowed' => new OptionRule(['allow' => true])]]]); + $rbac = new CachedApiRbac(['api_permissions' => [$rule + ['allowed' => new OptionRule(['allow' => false])]]]); + + $this->assertFalse( + $rbac->checkPermissions(['id' => 1, 'role' => 'user'], $this->request('articles', 'index')) + ); + }); + } + + /** + * Rules with closures work with a cache that serializes, because the map holds rule positions only. + * + * @return void + */ + public function testCachedRbacWorksWithClosuresAndAFileCache(): void + { + $rules = [ + ['role' => '*', 'service' => '*', 'action' => '*', 'method' => '*', 'allowed' => function () { + return true; + }], + ]; + $this->withFileCache(function () use ($rules) { + new CachedApiRbac(['api_permissions' => $rules]); + $rbac = new CachedApiRbac(['api_permissions' => $rules]); + + $this->assertTrue( + $rbac->checkPermissions(['id' => 1, 'role' => 'user'], $this->request('articles', 'index')) + ); + }); + } + + /** + * Rule lists with names that are not valid UTF-8 get their own cache keys. + * + * @return void + */ + public function testCachedRbacCacheKeyOfNamesThatAreNotUtf8(): void + { + $rbac = new class extends CachedApiRbac { + /** + * Without the parent constructor, no map is built. + */ + public function __construct() + { + } + + /** + * @param array $permissions Permission rules. + * @return string + */ + public static function key(array $permissions): string + { + return static::_cacheKey($permissions); + } + }; + $rule = ['service' => '*', 'action' => '*', 'allowed' => true]; + + $keys = [ + $rbac::key([['role' => "\xff"] + $rule]), + $rbac::key([['role' => "\xfe"] + $rule]), + $rbac::key([]), + ]; + $this->assertCount(3, array_unique($keys)); + } + + /** + * Rules set with setPermissions() are checked instead of the rules of the constructor. + * + * @return void + */ + public function testCachedRbacUsesSetPermissions(): void + { + $rule = ['role' => '*', 'service' => '*', 'action' => '*', 'method' => '*']; + $rbac = $this->cached([$rule + ['allowed' => true]]); + $rbac->setPermissions([$rule + ['allowed' => false]]); + Cache::clear('_cakedc_api_auth_'); + + $this->assertFalse($rbac->checkPermissions(['id' => 1, 'role' => 'user'], $this->request('articles', 'index'))); + } + + /** + * Runs a test with a File cache that serializes as the `_cakedc_api_auth_` engine. + * + * @param callable $test Test. + * @return void + */ + protected function withFileCache(callable $test): void + { + $previous = Cache::getConfig('_cakedc_api_auth_'); + Cache::drop('_cakedc_api_auth_'); + Cache::setConfig('_cakedc_api_auth_', [ + 'className' => 'File', + 'path' => TMP . 'cache' . DS . 'cached_rbac_test' . DS, + 'serialize' => true, + ]); + try { + Cache::clear('_cakedc_api_auth_'); + $test(); + } finally { + Cache::clear('_cakedc_api_auth_'); + Cache::drop('_cakedc_api_auth_'); + if ($previous) { + Cache::setConfig('_cakedc_api_auth_', $previous); + } + } + } + + /** + * Builds and caches the map of the rules, and leaves it in the cache. + * + * @param array $rules Permission rules. + * @return void + */ + protected function warmCache(array $rules): void + { + if (!Cache::getConfig('_cakedc_api_auth_')) { + Cache::setConfig('_cakedc_api_auth_', ['className' => 'Array']); + } + Cache::clear('_cakedc_api_auth_'); + new CachedApiRbac(['api_permissions' => $rules]); + } + + /** + * @param array $rules Permission rules. + * @return \CakeDC\Api\Rbac\CachedApiRbac + */ + protected function cached(array $rules): CachedApiRbac + { + if (!Cache::getConfig('_cakedc_api_auth_')) { + Cache::setConfig('_cakedc_api_auth_', ['className' => 'Array']); + } + Cache::clear('_cakedc_api_auth_'); + $rbac = new CachedApiRbac(['api_permissions' => $rules]); + Cache::clear('_cakedc_api_auth_'); + + return $rbac; + } +} + +/** + * A function used as a rule's role. + * + * @return bool + */ +function cachedRbacRuleFunction(): bool +{ + return true; } diff --git a/tests/TestCase/Rbac/OptionRule.php b/tests/TestCase/Rbac/OptionRule.php new file mode 100644 index 0000000..c5306d2 --- /dev/null +++ b/tests/TestCase/Rbac/OptionRule.php @@ -0,0 +1,31 @@ +getConfig('allow'); + } +} diff --git a/tests/TestCase/Service/Action/Traits/ReCaptchaTraitTest.php b/tests/TestCase/Service/Action/Traits/ReCaptchaTraitTest.php new file mode 100644 index 0000000..ec14fb4 --- /dev/null +++ b/tests/TestCase/Service/Action/Traits/ReCaptchaTraitTest.php @@ -0,0 +1,217 @@ + 'example.com']; + if ($referer !== '') { + $environment['HTTP_REFERER'] = $referer; + } + $request = new ServerRequest(['environment' => $environment]); + + return new class ($request, $success) { + use ReCaptchaTrait; + + public $request; + + public $success; + + public function __construct($request, $success) + { + $this->request = $request; + $this->success = $success; + } + + public function getService() + { + $request = $this->request; + + return new class ($request) { + private $request; + + public function __construct($request) + { + $this->request = $request; + } + + public function getRequest() + { + return $this->request; + } + }; + } + + protected function _getReCaptchaInstance() + { + if ($this->success === null) { + return null; + } + $success = $this->success; + + return new class ($success) { + private $success; + + public function __construct($success) + { + $this->success = $success; + } + + public function verify($response, $ip) + { + $success = $this->success && $response === 'valid'; + + return new class ($success) { + private $success; + + public function __construct($success) + { + $this->success = $success; + } + + public function isSuccess() + { + return $this->success; + } + }; + } + }; + } + }; + } + + public function testGlobalDisabledSkipsValidation(): void + { + Configure::write('Api.reCaptcha.disabled', true); + $this->assertTrue($this->subject(false)->validateReCaptcha('any')); + } + + public function testValidTokenPasses(): void + { + $this->assertTrue($this->subject(true)->validateReCaptcha('valid')); + $this->assertFalse($this->subject(true)->validateReCaptcha('invalid')); + } + + public function testDisabledForTheDomainStillValidates(): void + { + Configure::write('Api.reCaptcha.example$com', ['disabled' => true, 'secret' => 'secret']); + $this->assertFalse($this->subject(true)->validateReCaptcha('invalid')); + } + + public function testDisabledForAnotherDomainStillValidates(): void + { + Configure::write('Api.reCaptcha.dev$test', ['disabled' => true]); + $this->assertFalse($this->subject(true, 'https://dev.test/')->validateReCaptcha('invalid')); + } + + public function testNoReCaptchaInstanceFails(): void + { + $this->assertFalse($this->subject(null)->validateReCaptcha('valid')); + } + + public function testGlobalDisabledMustBeTrue(): void + { + // a string, as read from an environment variable, does not turn validation off + Configure::write('Api.reCaptcha.disabled', 'true'); + $this->assertFalse($this->subject(true)->validateReCaptcha('invalid')); + } + + public function testNoSecretFails(): void + { + // the real lookup: no secret for the domain means no reCaptcha instance + $request = new ServerRequest(['environment' => ['HTTP_HOST' => 'example.com']]); + $subject = new class ($request) { + use ReCaptchaTrait; + + public $request; + + public function __construct($request) + { + $this->request = $request; + } + + public function getService() + { + $request = $this->request; + + return new class ($request) { + private $request; + + public function __construct($request) + { + $this->request = $request; + } + + public function getRequest() + { + return $this->request; + } + }; + } + }; + + $this->assertFalse($subject->validateReCaptcha('valid')); + } + + public function testDisabledForTheDomainIsLogged(): void + { + // like the loggers of the application skeleton, which take messages without a scope + Log::setConfig('recaptcha_test', ['className' => 'Array', 'levels' => ['warning'], 'scopes' => false]); + Configure::write('Api.reCaptcha.example$com', ['disabled' => true]); + try { + $this->subject(true)->validateReCaptcha('invalid'); + $logged = implode("\n", Log::engine('recaptcha_test')->read()); + } finally { + Log::drop('recaptcha_test'); + } + + $this->assertStringContainsString('`Api.reCaptcha.example$com.disabled` is ignored', $logged); + } + + public function testNoSecretIsLogged(): void + { + // like the loggers of the application skeleton, which take messages without a scope + Log::setConfig('recaptcha_test', ['className' => 'Array', 'levels' => ['warning'], 'scopes' => false]); + try { + $this->subject(null)->validateReCaptcha('valid'); + $logged = implode("\n", Log::engine('recaptcha_test')->read()); + } finally { + Log::drop('recaptcha_test'); + } + + $this->assertStringContainsString('No reCaptcha secret is configured for `example$com`', $logged); + } +} diff --git a/tests/TestCase/Utility/RequestParserTest.php b/tests/TestCase/Utility/RequestParserTest.php new file mode 100644 index 0000000..21078f9 --- /dev/null +++ b/tests/TestCase/Utility/RequestParserTest.php @@ -0,0 +1,69 @@ + 'api.example.com']; + if ($referer !== '') { + $environment['HTTP_REFERER'] = $referer; + } + + return new ServerRequest(['environment' => $environment]); + } + + public function testDomainOfTheRequestHost(): void + { + // without a Referer the domain of the request is used, without its subdomain + $this->assertSame('example$com', RequestParser::getDomain($this->request())); + $this->assertSame('example.com', RequestParser::getDomain($this->request(), false)); + } + + public function testDomainOfTheReferer(): void + { + $this->assertSame('app$example$org', RequestParser::getDomain($this->request('https://app.example.org/page'))); + } + + public function testRefererWithoutAHostUsesTheRequestHost(): void + { + $warnings = []; + set_error_handler(function (int $level, string $message) use (&$warnings): bool { + $warnings[] = $message; + + return true; + }); + try { + foreach (['foo', 'http:///x'] as $referer) { + $this->assertSame('example$com', RequestParser::getDomain($this->request($referer)), $referer); + } + } finally { + restore_error_handler(); + } + + $this->assertSame([], $warnings); + } +} diff --git a/tests/schema.php b/tests/schema.php index f029d8d..73282c8 100644 --- a/tests/schema.php +++ b/tests/schema.php @@ -115,15 +115,15 @@ 'token_expires' => ['type' => 'datetime', 'length' => null, 'null' => true, 'default' => null, 'comment' => '', 'precision' => null], 'api_token' => ['type' => 'string', 'length' => 255, 'null' => true, 'default' => null, 'comment' => '', 'precision' => null, 'fixed' => null], 'activation_date' => ['type' => 'datetime', 'length' => null, 'null' => true, 'default' => null, 'comment' => '', 'precision' => null], - // 'secret' => ['type' => 'string', 'length' => 255, 'null' => true, 'default' => null, 'comment' => '', 'precision' => null, 'fixed' => null], - // 'secret_verified' => ['type' => 'boolean', 'length' => null, 'null' => true, 'default' => false, 'comment' => '', 'precision' => null], + 'secret' => ['type' => 'string', 'length' => 255, 'null' => true, 'default' => null, 'comment' => '', 'precision' => null, 'fixed' => null], + 'secret_verified' => ['type' => 'boolean', 'length' => null, 'null' => true, 'default' => false, 'comment' => '', 'precision' => null], 'tos_date' => ['type' => 'datetime', 'length' => null, 'null' => true, 'default' => null, 'comment' => '', 'precision' => null], 'active' => ['type' => 'boolean', 'length' => null, 'null' => false, 'default' => true, 'comment' => '', 'precision' => null], 'is_superuser' => ['type' => 'boolean', 'length' => null, 'unsigned' => false, 'null' => false, 'default' => false, 'comment' => '', 'precision' => null, 'autoIncrement' => null], 'role' => ['type' => 'string', 'length' => 255, 'null' => true, 'default' => 'user', 'comment' => '', 'precision' => null, 'fixed' => null], 'created' => ['type' => 'datetime', 'length' => null, 'null' => false, 'default' => null, 'comment' => '', 'precision' => null], 'modified' => ['type' => 'datetime', 'length' => null, 'null' => false, 'default' => null, 'comment' => '', 'precision' => null], - // 'additional_data' => ['type' => 'text', 'length' => null, 'null' => true, 'default' => null, 'comment' => '', 'precision' => null], + 'additional_data' => ['type' => 'text', 'length' => null, 'null' => true, 'default' => null, 'comment' => '', 'precision' => null], // 'last_login' => ['type' => 'datetime', 'length' => null, 'null' => true, 'default' => null, 'comment' => '', 'precision' => null], ], 'constraints' => [ @@ -135,4 +135,16 @@ ], ], ], + [ + 'table' => 'auth_store', + 'columns' => [ + 'id' => ['type' => 'string', 'length' => 500, 'null' => false, 'default' => null, 'comment' => '', 'precision' => null], + 'store' => ['type' => 'text', 'length' => null, 'null' => true, 'default' => null, 'comment' => '', 'precision' => null], + 'created' => ['type' => 'datetime', 'length' => null, 'null' => false, 'default' => null, 'comment' => '', 'precision' => null], + 'modified' => ['type' => 'datetime', 'length' => null, 'null' => false, 'default' => null, 'comment' => '', 'precision' => null], + ], + 'constraints' => [ + 'primary' => ['type' => 'primary', 'columns' => ['id'], 'length' => []], + ], + ], ];