diff --git a/CHANGELOG.md b/CHANGELOG.md index 81cebc17..b5be72f3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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..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. diff --git a/docs/Documentation/configuration.md b/docs/Documentation/configuration.md index 8e25e0d5..332fafd6 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/Service/Action/Auth/OtpVerifyAction.php b/src/Service/Action/Auth/OtpVerifyAction.php index 24bc23f8..b2503686 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 b22136a0..7ce404cd 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 4cbd6be4..00cc82c8 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 00000000..099e3e3f --- /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 3eb200b7..bd811ba5 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 1567fde1..247abde2 100644 --- a/src/Service/Action/Auth/Webauthn2faRegisterAction.php +++ b/src/Service/Action/Auth/Webauthn2faRegisterAction.php @@ -26,6 +26,7 @@ class Webauthn2faRegisterAction extends Action { use CustomUsersTableTrait; + use SecondFactorTrait; /** * Execute action. @@ -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]; diff --git a/src/Service/Action/Auth/Webauthn2faRegisterOptionsAction.php b/src/Service/Action/Auth/Webauthn2faRegisterOptionsAction.php index 8dc3f363..72794dab 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 3aff7080..17a2ce94 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 3483f5fc..33bc8e42 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 5cd460b0..cdf30efe 100644 --- a/src/Webauthn/BaseAdapter.php +++ b/src/Webauthn/BaseAdapter.php @@ -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. * diff --git a/src/Webauthn/Repository/UserCredentialSourceRepository.php b/src/Webauthn/Repository/UserCredentialSourceRepository.php index 794f995d..940e5d5e 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(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 diff --git a/tests/Config/users.php b/tests/Config/users.php index e1d40fc4..36946cee 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 00000000..c677ac4f --- /dev/null +++ b/tests/Fixture/AuthStoreFixture.php @@ -0,0 +1,36 @@ +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); + $this->setOtp(null, false); + } + + public function tearDown(): void + { + parent::tearDown(); + Configure::delete('Test.Api.Config'); + } + + /** + * @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 00000000..19d957cd --- /dev/null +++ b/tests/TestCase/Integration/Service/Action/Auth/SoftwareAuthenticatorTrait.php @@ -0,0 +1,193 @@ + + */ + 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' => $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 \OpenSSLAsymmetricKey A new P-256 key pair, the software authenticator's credential key. + */ + protected function newKey(): OpenSSLAsymmetricKey + { + $key = openssl_pkey_new(['curve_name' => 'prime256v1', 'private_key_type' => OPENSSL_KEYTYPE_EC]); + $this->assertInstanceOf(OpenSSLAsymmetricKey::class, $key); + + return $key; + } + + /** + * Builds the registration response a browser sends after navigator.credentials.create(). + * + * @param \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(OpenSSLAsymmetricKey $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 \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(OpenSSLAsymmetricKey $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: \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']); + $register = $this->withToken( + '/auth/webauthn2fa_register', + 'POST', + $this->attestation($key, $credentialId, $options['data']['challenge']), + $login['access_token'], + ); + $this->assertSame('success', $register['status']); + + 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 00000000..bdb84df0 --- /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/Service/Action/Traits/ReCaptchaTraitTest.php b/tests/TestCase/Service/Action/Traits/ReCaptchaTraitTest.php new file mode 100644 index 00000000..b1014347 --- /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' => null]); + 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' => null]); + 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 00000000..21078f9a --- /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 70eb5f6b..24d90384 100644 --- a/tests/schema.php +++ b/tests/schema.php @@ -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' => []], + ], + ], ];