From 93e696c8a1ad868bdb2968baeb4f2a656fc2974f Mon Sep 17 00:00:00 2001 From: Alejandro Ibarra Date: Fri, 28 Aug 2026 14:17:51 +0200 Subject: [PATCH 01/35] fix(recaptcha): treat a missing or empty token as invalid instead of erroring (cherry picked from commit 653b0fcbb721fec7e5afaf0cf84f90fca90a8912) --- CHANGELOG.md | 5 + src/Traits/ReCaptchaTrait.php | 8 +- .../Authenticator/FormAuthenticatorTest.php | 60 ++++++++++ tests/TestCase/Traits/ReCaptchaTraitTest.php | 112 ++++++++++++++++++ 4 files changed, 184 insertions(+), 1 deletion(-) create mode 100644 tests/TestCase/Traits/ReCaptchaTraitTest.php diff --git a/CHANGELOG.md b/CHANGELOG.md index 035502d..927a9c3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,11 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). ## [Unreleased] +### Fixed +- `ReCaptchaTrait::validateReCaptchaFromRequest()` treats a missing or empty + `g-recaptcha-response` as an invalid captcha (returns `false`) instead of passing `null` to the + non-nullable `validateReCaptcha(string ...)`, which raised a `TypeError` (HTTP 500). A tokenless + request — e.g. a programmatic JSON client — now fails the reCaptcha check cleanly. ## [10.1.2] - 2025-09-26 - Github social login diff --git a/src/Traits/ReCaptchaTrait.php b/src/Traits/ReCaptchaTrait.php index 007033b..a3a2371 100644 --- a/src/Traits/ReCaptchaTrait.php +++ b/src/Traits/ReCaptchaTrait.php @@ -36,7 +36,13 @@ public function validateReCaptchaFromRequest(ServerRequestInterface $request): b throw new BadMethodCallException('Request must be an instance of ServerRequest'); } $data = $request->getParsedBody(); - $captcha = $data['g-recaptcha-response'] ?? null; + $captcha = is_array($data) ? ($data['g-recaptcha-response'] ?? null) : null; + // A missing/empty token is simply an invalid captcha. Guard here so a request + // without the field (e.g. a programmatic JSON client) fails validation cleanly + // instead of hitting validateReCaptcha()'s non-nullable string param (TypeError -> 500). + if (!is_string($captcha) || $captcha === '') { + return false; + } return $this->validateReCaptcha( $captcha, diff --git a/tests/TestCase/Authenticator/FormAuthenticatorTest.php b/tests/TestCase/Authenticator/FormAuthenticatorTest.php index e6ed09c..0504e98 100644 --- a/tests/TestCase/Authenticator/FormAuthenticatorTest.php +++ b/tests/TestCase/Authenticator/FormAuthenticatorTest.php @@ -299,6 +299,66 @@ public function testAuthenticateInvalidRecaptcha() $this->assertNull($result->getData()); } + /** + * A request without a g-recaptcha-response token, with reCaptcha enabled and valid + * credentials, must fail as FAILURE_INVALID_RECAPTCHA through the real + * validateReCaptchaFromRequest() guard (no token never reaches validateReCaptcha(), + * so this asserts the guard end-to-end and that it no longer raises a TypeError). + * + * @return void + */ + public function testAuthenticateTokenlessRecaptchaFailsCleanly() + { + $identifiers = new IdentifierCollection([ + 'Authentication.Password', + ]); + + $BaseAuthenticator = $this->getMockBuilder(CakeFormAuthenticator::class) + ->setConstructorArgs([$identifiers]) + ->onlyMethods(['authenticate']) + ->getMock(); + $request = ServerRequestFactory::fromGlobals( + ['REQUEST_URI' => '/testpath', 'REMOTE_ADDR' => '127.0.0.1'], + [], + ['username' => 'marcelo', 'password' => 'password'] + ); + + $baseResult = new Result( + [ + 'id' => '42', + 'username' => 'marcelo', + 'role' => 'user', + ], + Result::SUCCESS + ); + $BaseAuthenticator->expects($this->once()) + ->method('authenticate') + ->with($request) + ->willReturn($baseResult); + + // Only the base authenticator is mocked; validateReCaptcha() is left real and + // must never be reached because the token is absent. + $Authenticator = $this->getMockBuilder(FormAuthenticator::class)->setConstructorArgs([ + $identifiers, + [ + 'fields' => [ + AbstractIdentifier::CREDENTIAL_USERNAME => 'email', + AbstractIdentifier::CREDENTIAL_PASSWORD => 'password', + ], + ], + ])->onlyMethods(['createBaseAuthenticator'])->getMock(); + + Configure::write('Users.reCaptcha.login', true); + $Authenticator->expects($this->once()) + ->method('createBaseAuthenticator') + ->willReturn($BaseAuthenticator); + + $result = $Authenticator->authenticate($request); + $this->assertInstanceOf(Result::class, $result); + $this->assertEquals(FormAuthenticator::FAILURE_INVALID_RECAPTCHA, $result->getStatus()); + $this->assertNull($result->getData()); + } + /** * test getBaseAuthenticator * diff --git a/tests/TestCase/Traits/ReCaptchaTraitTest.php b/tests/TestCase/Traits/ReCaptchaTraitTest.php new file mode 100644 index 0000000..21caaea --- /dev/null +++ b/tests/TestCase/Traits/ReCaptchaTraitTest.php @@ -0,0 +1,112 @@ + '127.0.0.1']); + + return $request->withParsedBody($parsedBody); + } + + /** + * A subject that uses the trait and stubs the actual verification so the tests + * never reach _getReCaptchaInstance()/the google/recaptcha dependency and can + * observe whether the guard short-circuited. + * + * @param bool $return value the stubbed validateReCaptcha() returns + * @return object + */ + protected function subject(bool $return = true): object + { + return new class ($return) { + use ReCaptchaTrait; + + public bool $validatorCalled = false; + public array $validatorArgs = []; + + public function __construct(protected bool $return) + { + } + + public function validateReCaptcha(string $recaptchaResponse, string $clientIp): bool + { + $this->validatorCalled = true; + $this->validatorArgs = [$recaptchaResponse, $clientIp]; + + return $this->return; + } + }; + } + + /** + * @return array + */ + public static function tokenlessProvider(): array + { + return [ + 'missing field' => [[]], + 'empty string' => [['g-recaptcha-response' => '']], + 'array value' => [['g-recaptcha-response' => ['nested']]], + 'object body' => [(object)['g-recaptcha-response' => 'x']], + ]; + } + + /** + * A missing/empty/non-string token is invalid and must not reach the verifier. + * + * @param mixed $parsedBody parsed request body + * @return void + */ + #[DataProvider('tokenlessProvider')] + public function testTokenlessRequestFailsWithoutCallingValidator(mixed $parsedBody): void + { + $subject = $this->subject(true); + + $result = $subject->validateReCaptchaFromRequest($this->request($parsedBody)); + + $this->assertFalse($result); + $this->assertFalse( + $subject->validatorCalled, + 'The guard must short-circuit before validateReCaptcha().', + ); + } + + /** + * A real token is forwarded verbatim to validateReCaptcha() with the client IP. + * + * @return void + */ + public function testValidTokenDelegatesToValidator(): void + { + $subject = $this->subject(true); + + $result = $subject->validateReCaptchaFromRequest( + $this->request(['g-recaptcha-response' => 'the-token']), + ); + + $this->assertTrue($result); + $this->assertTrue($subject->validatorCalled); + $this->assertSame(['the-token', '127.0.0.1'], $subject->validatorArgs); + } +} From 0cb56083f2d5154c932b6af3a46fca27592ecaf5 Mon Sep 17 00:00:00 2001 From: Alejandro Ibarra Date: Fri, 14 Mar 2025 12:58:07 +0100 Subject: [PATCH 02/35] 89 - Allow string url for verify action (cherry picked from commit 29d0fee74cbf3b0b1b8e93e6908ac31ae2b9d660) --- .../TwoFactorProcessor/OneTimePasswordProcessor.php | 4 ++-- .../TwoFactorProcessor/Webauthn2faProcessor.php | 4 ++-- src/Authentication/TwoFactorProcessorInterface.php | 4 ++-- src/Middleware/TwoFactorMiddleware.php | 12 +++++++++--- 4 files changed, 15 insertions(+), 9 deletions(-) diff --git a/src/Authentication/TwoFactorProcessor/OneTimePasswordProcessor.php b/src/Authentication/TwoFactorProcessor/OneTimePasswordProcessor.php index 7e1c5f9..401f98f 100644 --- a/src/Authentication/TwoFactorProcessor/OneTimePasswordProcessor.php +++ b/src/Authentication/TwoFactorProcessor/OneTimePasswordProcessor.php @@ -92,9 +92,9 @@ public function proceed(ServerRequestInterface $request, ResultInterface $result * Generates 2fa url, if enable. * * @param string $type Processor type. - * @return array|null + * @return array|string|null */ - public function getUrlByType(string $type): ?array + public function getUrlByType(string $type): array|string|null { if ($type == $this->getType()) { return Configure::read('OneTimePasswordAuthenticator.verifyAction'); diff --git a/src/Authentication/TwoFactorProcessor/Webauthn2faProcessor.php b/src/Authentication/TwoFactorProcessor/Webauthn2faProcessor.php index 622ed06..b23d686 100644 --- a/src/Authentication/TwoFactorProcessor/Webauthn2faProcessor.php +++ b/src/Authentication/TwoFactorProcessor/Webauthn2faProcessor.php @@ -92,9 +92,9 @@ public function proceed(ServerRequestInterface $request, ResultInterface $result * Generates 2fa url, if enable. * * @param string $type Processor type. - * @return array|null + * @return array|string|null */ - public function getUrlByType(string $type): ?array + public function getUrlByType(string $type): array|string|null { if ($type == $this->getType()) { return Configure::read('Webauthn2fa.startAction'); diff --git a/src/Authentication/TwoFactorProcessorInterface.php b/src/Authentication/TwoFactorProcessorInterface.php index 0a1809a..ccedd22 100644 --- a/src/Authentication/TwoFactorProcessorInterface.php +++ b/src/Authentication/TwoFactorProcessorInterface.php @@ -47,7 +47,7 @@ public function proceed(ServerRequestInterface $request, ResultInterface $result * Generates 2fa url, if enable. * * @param string $type Processor type. - * @return array|null + * @return array|string|null */ - public function getUrlByType(string $type): ?array; + public function getUrlByType(string $type): array|string|null; } diff --git a/src/Middleware/TwoFactorMiddleware.php b/src/Middleware/TwoFactorMiddleware.php index 172376d..5d95cac 100644 --- a/src/Middleware/TwoFactorMiddleware.php +++ b/src/Middleware/TwoFactorMiddleware.php @@ -52,9 +52,15 @@ public function process(ServerRequestInterface $request, RequestHandlerInterface $session->write(CookieAuthenticator::SESSION_DATA_KEY, [ 'remember_me' => $data['remember_me'] ?? null, ]); - $url = array_merge($url, [ - '?' => $request->getQueryParams(), - ]); + $params = $request->getQueryParams(); + if (is_array($url)) { + $url = array_merge($url, [ + '?' => $params, + ]); + } else { + $url .= '?' . implode('&', array_map(fn ($k, $v) => "$k=$v", array_keys($params), array_values($params))); + } + $url = Router::url($url); return (new Response()) From 0304d2f05571b05935f60017ce0dc54453e47cdb Mon Sep 17 00:00:00 2001 From: Robitmoh Date: Tue, 30 Apr 2024 15:56:05 +0200 Subject: [PATCH 03/35] Add keycloak support require stevenmaguire/oauth2-keycloak (cherry picked from commit 48501d69973003a4b83fe4cf0161b6c27e4e8928) --- src/Social/Mapper/Keycloak.php | 49 ++++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 src/Social/Mapper/Keycloak.php diff --git a/src/Social/Mapper/Keycloak.php b/src/Social/Mapper/Keycloak.php new file mode 100644 index 0000000..bd1e0f6 --- /dev/null +++ b/src/Social/Mapper/Keycloak.php @@ -0,0 +1,49 @@ + 'given_name', + 'last_name' => 'family_name', + 'email' => 'email', + 'username' => 'preferred_username', + 'id' => 'sub', + 'link' => 'website', + 'roles' => 'Cakedc' + ]; + protected $_rolesMatch = 'CakeDc-'; + + + function _roles($data){ # Client Scopes > roles > Mappers > realm roles -> Add to userinfo := Enable + $roles = array_filter(@$data[$this->_mapFields['roles']]['cakedc'], + function ($var) { return (strpos($var, $this->_rolesMatch) !== false); }); + + $role= str_ireplace($this->_rolesMatch, '',array_pop($roles)); + # + # Set the cakedc default user role from keycloak roles + # + Configure::write('Users.Registration.defaultRole',$role); + Configure::write('Users.Registration.KeycloakRole',$role); + return $role; + } +} From 6461d9d12f7ce1aa87f34e8dc29a11a39c8c0a06 Mon Sep 17 00:00:00 2001 From: Robitmoh Date: Fri, 24 May 2024 09:50:20 +0200 Subject: [PATCH 04/35] Change role mapping New Exceptions for error handling (cherry picked from commit debf42e315c8c84c68391a34e2d1b15b8fa2c0c1) --- src/Social/Mapper/Keycloak.php | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/src/Social/Mapper/Keycloak.php b/src/Social/Mapper/Keycloak.php index bd1e0f6..823df9f 100644 --- a/src/Social/Mapper/Keycloak.php +++ b/src/Social/Mapper/Keycloak.php @@ -29,16 +29,22 @@ class Keycloak extends AbstractMapper 'username' => 'preferred_username', 'id' => 'sub', 'link' => 'website', - 'roles' => 'Cakedc' + 'roles' => 'realm_access' ]; protected $_rolesMatch = 'CakeDc-'; function _roles($data){ # Client Scopes > roles > Mappers > realm roles -> Add to userinfo := Enable - $roles = array_filter(@$data[$this->_mapFields['roles']]['cakedc'], + if (is_null($data[$this->_mapFields['roles']])){ + throw new \Exception("No roles in UserInfo token. Set realm roles 'Add to userinfo' field to ON in Client scopes or check the roles field in _mapFields"); + } + $roles = array_filter($data[$this->_mapFields['roles']]['roles'], function ($var) { return (strpos($var, $this->_rolesMatch) !== false); }); - - $role= str_ireplace($this->_rolesMatch, '',array_pop($roles)); + + if (empty($roles)){ + throw new \Exception("No CakeDc-* role mapped in keycloak"); + } + $role= str_ireplace($this->_rolesMatch, '',array_pop($roles)); # # Set the cakedc default user role from keycloak roles # From 27841066ad436ce6a8b9800229d0f8270b33e2d8 Mon Sep 17 00:00:00 2001 From: Robitmoh Date: Fri, 19 Jul 2024 11:36:16 +0200 Subject: [PATCH 05/35] Fix variables types (cherry picked from commit 0700e2202ff995fe01d0acaf98b7b293cbb1eaf9) --- src/Social/Mapper/Keycloak.php | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/Social/Mapper/Keycloak.php b/src/Social/Mapper/Keycloak.php index 823df9f..6e47872 100644 --- a/src/Social/Mapper/Keycloak.php +++ b/src/Social/Mapper/Keycloak.php @@ -31,10 +31,11 @@ class Keycloak extends AbstractMapper 'link' => 'website', 'roles' => 'realm_access' ]; - protected $_rolesMatch = 'CakeDc-'; + protected string $_rolesMatch = 'CakeDc-'; - function _roles($data){ # Client Scopes > roles > Mappers > realm roles -> Add to userinfo := Enable + function _roles(array: $data) :string + { # Client Scopes > roles > Mappers > realm roles -> Add to userinfo := Enable if (is_null($data[$this->_mapFields['roles']])){ throw new \Exception("No roles in UserInfo token. Set realm roles 'Add to userinfo' field to ON in Client scopes or check the roles field in _mapFields"); } From 362daa3b37c780e7016600acc5fde900126a06bf Mon Sep 17 00:00:00 2001 From: Robitmoh Date: Fri, 19 Jul 2024 11:49:26 +0200 Subject: [PATCH 06/35] Typo error (cherry picked from commit a92a1c4e306beb7c884f1ea70ba0c5a04e548260) --- src/Social/Mapper/Keycloak.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Social/Mapper/Keycloak.php b/src/Social/Mapper/Keycloak.php index 6e47872..5a5f852 100644 --- a/src/Social/Mapper/Keycloak.php +++ b/src/Social/Mapper/Keycloak.php @@ -34,7 +34,7 @@ class Keycloak extends AbstractMapper protected string $_rolesMatch = 'CakeDc-'; - function _roles(array: $data) :string + function _roles(array $data) :string { # Client Scopes > roles > Mappers > realm roles -> Add to userinfo := Enable if (is_null($data[$this->_mapFields['roles']])){ throw new \Exception("No roles in UserInfo token. Set realm roles 'Add to userinfo' field to ON in Client scopes or check the roles field in _mapFields"); From dd7d92c576fd6ef4945543fcda601d7089f4f31a Mon Sep 17 00:00:00 2001 From: Robitmoh Date: Tue, 1 Apr 2025 10:07:59 +0200 Subject: [PATCH 07/35] Add keycloak support to Social auth (cherry picked from commit 3600ad2fa7513bad847765954de1df85da5432af) --- Docs/Documentation/Social.md | 106 ++++++++++++++++++++++++++++++++- config/auth.php | 23 ++++++- src/Social/MapUser.php | 16 +++++ src/Social/Mapper/Keycloak.php | 62 ++++++++++++++----- 4 files changed, 187 insertions(+), 20 deletions(-) diff --git a/Docs/Documentation/Social.md b/Docs/Documentation/Social.md index d99a65a..16eeb31 100644 --- a/Docs/Documentation/Social.md +++ b/Docs/Documentation/Social.md @@ -93,4 +93,108 @@ Working with cakephp/authentication If you're using the new cakephp/authentication we recommend you to use the SocialAuthenticator and SocialMiddleware provided in this plugin. For more details of how to handle social authentication with cakephp/authentication, please check -how we implemented at CakeDC/Users plugins. \ No newline at end of file +how we implemented at CakeDC/Users plugins. + +Working with Keycloak +------------------- + +Keycloak is an open source identity and access management solution that can be integrated with this plugin. Here's how to set it up: + +### Configuration + +Add the Keycloak provider configuration to your `config/users.php` file: + +```php +'OAuth' => [ + 'providers' => [ + 'keycloak' => [ + 'service' => 'CakeDC\Auth\Social\Service\OAuth2Service', + 'className' => 'Stevenmaguire\OAuth2\Client\Provider\Keycloak', + 'mapper' => 'CakeDC\Auth\Social\Mapper\Keycloak', + 'rolesMap' => [ + 'CakeDc-Admin' => 'admin', + 'CakeDc-User' => 'user', + 'CakeDc-Worker' => 'user' + ], + 'authParams' => ['scope' => ['openid', 'roles']], + 'skipSocialAccountValidation' => true, + 'options' => [ + 'redirectUri' => Router::fullBaseUrl() . '/auth/keycloak', + 'linkSocialUri' => Router::fullBaseUrl() . '/auth/link-social/keycloak', + 'callbackLinkSocialUri' => Router::fullBaseUrl() . '/auth/callback-link-social/keycloak', + 'realm' => env('KEYCLOAK_REALM', null), + 'clientId' => env('KEYCLOAK_CLIENT_ID', null), + 'clientSecret' => env('KEYCLOAK_CLIENT_SECRET', null), + 'authServerUrl' => env('KEYCLOAK_AUTH_SERVER_URL', null), + ] + ], + ], +], +``` + +### Keycloak Server Configuration + +1. **Client Scopes Setup**: + - Enable the `openid` scope + - Add a `roles` scope with Mappers configuration + - Configure the `realm_roles` mapper with "Add to userinfo" set to ON + +2. **Realm Roles**: + - Create roles that match your configuration (e.g., `CakeDc-Admin`, `CakeDc-User`, `CakeDc-Worker`) + - Assign these roles to users or groups in Keycloak + +3. **User Attributes**: + - You can add additional attributes like `website` to users if needed + +### Role Mapping + +The plugin maps Keycloak roles to application roles using the `rolesMap` configuration. When a user logs in, their Keycloak roles are checked against this map and the corresponding application role is assigned. + +### Event Listener for Role Updates + +You can create a custom event listener to update user roles during login: + +```php + 'changeRole', + ]; + } + + public function changeRole(EventInterface $event) + { + $data = $event->getData('data'); + $userEntity = $event->getData('userEntity'); + + if (isset($data['provider']) && $data['provider'] === 'keycloak' && isset($data['roles'])) { + $userEntity->set('role', $data['roles']); + return $userEntity; + } + + return null; + } +} +``` + +### Environment Variables + +For security, store your Keycloak configuration in environment variables: + +``` +KEYCLOAK_REALM=your-realm +KEYCLOAK_CLIENT_ID=your-client-id +KEYCLOAK_CLIENT_SECRET=your-client-secret +KEYCLOAK_AUTH_SERVER_URL=https://your-keycloak-server/auth +``` + +This setup allows your CakePHP application to authenticate users through Keycloak and map their roles appropriately. \ No newline at end of file diff --git a/config/auth.php b/config/auth.php index cf2ec4e..782d5ab 100644 --- a/config/auth.php +++ b/config/auth.php @@ -86,11 +86,28 @@ 'callbackLinkSocialUri' => Router::fullBaseUrl() . '/callback-link-social/azure', ], ], + 'keycloak' => [ + 'service' => 'CakeDC\Auth\Social\Service\OAuth2Service', + 'className' => 'Stevenmaguire\OAuth2\Client\Provider\Keycloak', + 'mapper' => 'CakeDC\Auth\Social\Mapper\Keycloak', + 'rolesMap' => [ + 'CakeDc-Admin' => 'Admin', + 'CakeDc-User' => 'User', + 'CakeDc-Worker' => 'User' + ], + 'authParams' => ['scope' => ['openid','roles']], + 'skipSocialAccountValidation' => true, + 'options' => [ + 'redirectUri' => Router::fullBaseUrl() . '/auth/keycloak', + 'linkSocialUri' => Router::fullBaseUrl() . '/auth/link-social/keycloak', + 'callbackLinkSocialUri' => Router::fullBaseUrl() . '/auth/callback-link-social/keycloak', + ] + ], ], - 'TwoFactorProcessors' => [ + 'TwoFactorProcessors' => [ \CakeDC\Auth\Authentication\TwoFactorProcessor\OneTimePasswordProcessor::class, - \CakeDC\Auth\Authentication\TwoFactorProcessor\Webauthn2faProcessor::class, - ], + \CakeDC\Auth\Authentication\TwoFactorProcessor\Webauthn2faProcessor::class + ], 'OneTimePasswordAuthenticator' => [ 'checker' => \CakeDC\Auth\Authentication\DefaultOneTimePasswordAuthenticationChecker::class, 'verifyAction' => [ diff --git a/src/Social/MapUser.php b/src/Social/MapUser.php index 7391e4f..b3490a4 100644 --- a/src/Social/MapUser.php +++ b/src/Social/MapUser.php @@ -15,9 +15,25 @@ use CakeDC\Auth\Social\Service\ServiceInterface; use InvalidArgumentException; +use Cake\Event\EventManager; +use App\Event\SocialLoginListener; + class MapUser { + /** + * Constructor + * + * Initializes the MapUser class and registers the SocialLoginListener + * to handle social login events. + */ + public function __construct() + { + + $listener = new SocialLoginListener(); + EventManager::instance()->on($listener); + + } /** * Map social user user data * diff --git a/src/Social/Mapper/Keycloak.php b/src/Social/Mapper/Keycloak.php index 5a5f852..a58927d 100644 --- a/src/Social/Mapper/Keycloak.php +++ b/src/Social/Mapper/Keycloak.php @@ -31,26 +31,56 @@ class Keycloak extends AbstractMapper 'link' => 'website', 'roles' => 'realm_access' ]; - protected string $_rolesMatch = 'CakeDc-'; - + + /** + * Map Keycloak roles to CakeDC roles + * + * @var array + */ + protected array $_rolesMap = [ + 'CakeDc-Admin' => 'admin', + 'CakeDc-User' => 'user', + 'CakeDc-Worker' => 'user' + ]; + + /** + * Constructor + */ + public function __construct() + { + $configRoleMap = Configure::read('OAuth.providers.keycloak.rolesMap'); + if (!empty($configRoleMap) && is_array($configRoleMap)) { + $this->_rolesMap = $configRoleMap; + } + } - function _roles(array $data) :string - { # Client Scopes > roles > Mappers > realm roles -> Add to userinfo := Enable - if (is_null($data[$this->_mapFields['roles']])){ - throw new \Exception("No roles in UserInfo token. Set realm roles 'Add to userinfo' field to ON in Client scopes or check the roles field in _mapFields"); + function _roles(array $data): string + { // Client Scopes > roles > Mappers > realm roles -> Add to userinfo := Enable + if (is_null($data[$this->_mapFields['roles']])) { + throw new \Exception("No roles in UserInfo token. Set realm roles 'Add to userinfo' field to ON in Client scopes or check the roles field in _mapFields"); + } + + $keycloakRoles = $data[$this->_mapFields['roles']]['roles']; + + // Ignore case when comparing roles + $mappedRoles = []; + foreach ($keycloakRoles as $keycloakRole) { + foreach (array_keys($this->_rolesMap) as $mapKey) { + if (strcasecmp($keycloakRole, $mapKey) === 0) { + $mappedRoles[] = $mapKey; + break; + } + } } - $roles = array_filter($data[$this->_mapFields['roles']]['roles'], - function ($var) { return (strpos($var, $this->_rolesMatch) !== false); }); - if (empty($roles)){ - throw new \Exception("No CakeDc-* role mapped in keycloak"); + if (empty($mappedRoles)) { + throw new \Exception("No mappable role found in Keycloak. Available roles in map: " . implode(', ', array_keys($this->_rolesMap)) . ' / '. implode(', ', ($keycloakRoles))); } - $role= str_ireplace($this->_rolesMatch, '',array_pop($roles)); - # - # Set the cakedc default user role from keycloak roles - # - Configure::write('Users.Registration.defaultRole',$role); - Configure::write('Users.Registration.KeycloakRole',$role); + + $keycloakRole = array_pop($mappedRoles); + $role = $this->_rolesMap[$keycloakRole]; + // Set the cakedc default user role from keycloak roles + Configure::write('Users.Registration.defaultRole', $role); return $role; } } From 5517927d55540cf07eb5f5c0ae42f2c6eee8498c Mon Sep 17 00:00:00 2001 From: Robitmoh Date: Tue, 1 Apr 2025 10:39:15 +0200 Subject: [PATCH 08/35] Add composer example (cherry picked from commit 0ec3055f074f786e5ce19fa11a9217d554e68aba) --- Docs/Documentation/Social.md | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/Docs/Documentation/Social.md b/Docs/Documentation/Social.md index 16eeb31..2f2bf08 100644 --- a/Docs/Documentation/Social.md +++ b/Docs/Documentation/Social.md @@ -100,6 +100,14 @@ Working with Keycloak Keycloak is an open source identity and access management solution that can be integrated with this plugin. Here's how to set it up: +### Installation + +First, install the required OAuth2 Keycloak provider package (version 5.1 or newer): + +```bash +composer require stevenmaguire/oauth2-keycloak +``` + ### Configuration Add the Keycloak provider configuration to your `config/users.php` file: From 3e0de3a232135bdffe81cbe70d4624f157c05903 Mon Sep 17 00:00:00 2001 From: Robitmoh Date: Tue, 1 Apr 2025 10:39:51 +0200 Subject: [PATCH 09/35] Add Event listener (cherry picked from commit 504de1798d555911038253c52c54028549d714f4) --- src/Event/SocialLoginListener.php | 42 +++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 src/Event/SocialLoginListener.php diff --git a/src/Event/SocialLoginListener.php b/src/Event/SocialLoginListener.php new file mode 100644 index 0000000..fe9e9f5 --- /dev/null +++ b/src/Event/SocialLoginListener.php @@ -0,0 +1,42 @@ + + */ + public function implementedEvents(): array + { + return [ + Plugin::EVENT_SOCIAL_LOGIN_EXISTING_ACCOUNT => 'changeRole', + ]; + } + + /** + * Szerepkör módosítása Keycloak bejelentkezés esetén + * + * @param \Cake\Event\EventInterface $event Az esemény objektum + * @return \Cake\Datasource\EntityInterface|null + */ + public function changeRole(EventInterface $event) + { + $data = $event->getData('data'); + $userEntity = $event->getData('userEntity'); + debug($data); + if (isset($data['provider']) && $data['provider'] === 'keycloak' && isset($data['roles'])) { + $userEntity->set('role', $data['roles']); + return $userEntity; + } + + return null; + } +} \ No newline at end of file From 334483d826b8e46882900de2d0c7347120a71edd Mon Sep 17 00:00:00 2001 From: Robitmoh Date: Tue, 1 Apr 2025 13:24:25 +0200 Subject: [PATCH 10/35] Namespace corrections (cherry picked from commit f18f379ace5c547ef4a594f7ace6fba383e0d405) --- src/Event/SocialLoginListener.php | 3 +-- src/Social/MapUser.php | 2 +- 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/src/Event/SocialLoginListener.php b/src/Event/SocialLoginListener.php index fe9e9f5..94a71d0 100644 --- a/src/Event/SocialLoginListener.php +++ b/src/Event/SocialLoginListener.php @@ -1,7 +1,7 @@ getData('data'); $userEntity = $event->getData('userEntity'); - debug($data); if (isset($data['provider']) && $data['provider'] === 'keycloak' && isset($data['roles'])) { $userEntity->set('role', $data['roles']); return $userEntity; diff --git a/src/Social/MapUser.php b/src/Social/MapUser.php index b3490a4..4ae7cf6 100644 --- a/src/Social/MapUser.php +++ b/src/Social/MapUser.php @@ -16,7 +16,7 @@ use CakeDC\Auth\Social\Service\ServiceInterface; use InvalidArgumentException; use Cake\Event\EventManager; -use App\Event\SocialLoginListener; +use CakeDC\Auth\Event\SocialLoginListener; class MapUser From efe6c8ae90bd26607ce0e3c31753a0406845e86e Mon Sep 17 00:00:00 2001 From: Robitmoh Date: Mon, 14 Apr 2025 11:54:52 +0200 Subject: [PATCH 11/35] Fix: Remove dependency on CakeDC\Users\Plugin class (cherry picked from commit 405b444754f6bd72c63c2e0b12c96e6d5cd7d8d5) --- src/Event/SocialLoginListener.php | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/src/Event/SocialLoginListener.php b/src/Event/SocialLoginListener.php index 94a71d0..b426805 100644 --- a/src/Event/SocialLoginListener.php +++ b/src/Event/SocialLoginListener.php @@ -5,7 +5,6 @@ use Cake\Event\EventInterface; use Cake\Event\EventListenerInterface; -use CakeDC\Users\Plugin; class SocialLoginListener implements EventListenerInterface { @@ -17,7 +16,12 @@ class SocialLoginListener implements EventListenerInterface public function implementedEvents(): array { return [ - Plugin::EVENT_SOCIAL_LOGIN_EXISTING_ACCOUNT => 'changeRole', + /** + * Event name directly used from CakeDC/Users plugin + * Original source: CakeDC\Users\Plugin::EVENT_SOCIAL_LOGIN_EXISTING_ACCOUNT + * If the constant is changed in the CakeDC/Users plugin, this string must be updated accordingly + */ + 'CakeDC.Users.Social.afterIdentify' => 'changeRole', ]; } From 481a81e2fe54b7707bc52f0589fd5dcf4d1b1c35 Mon Sep 17 00:00:00 2001 From: Robitmoh Date: Mon, 27 Oct 2025 10:44:38 +0100 Subject: [PATCH 12/35] Add 'validated' field mapping and enhance constructor to support custom map fields in Keycloak mapper (cherry picked from commit 83d34d8adae40122ddfc467dee6b3bfc3b8fe9f1) --- src/Social/Mapper/Keycloak.php | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/src/Social/Mapper/Keycloak.php b/src/Social/Mapper/Keycloak.php index a58927d..eb2bf21 100644 --- a/src/Social/Mapper/Keycloak.php +++ b/src/Social/Mapper/Keycloak.php @@ -29,7 +29,8 @@ class Keycloak extends AbstractMapper 'username' => 'preferred_username', 'id' => 'sub', 'link' => 'website', - 'roles' => 'realm_access' + 'roles' => 'realm_access', + 'validated' => 'email_verified' ]; /** @@ -49,9 +50,13 @@ class Keycloak extends AbstractMapper public function __construct() { $configRoleMap = Configure::read('OAuth.providers.keycloak.rolesMap'); + $configMapFields = Configure::read('OAuth.providers.keycloak.mapFields'); if (!empty($configRoleMap) && is_array($configRoleMap)) { $this->_rolesMap = $configRoleMap; } + if (!empty($configMapFields) && is_array($configMapFields)) { + $this->_mapFields = $configMapFields; + } } function _roles(array $data): string From 05f93342e2d6c6bc4c84f610e3c9ecb2ba89a19d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gonz=C3=A1lez?= Date: Thu, 7 Sep 2023 12:54:30 +0100 Subject: [PATCH 13/35] add openid connect service (cherry picked from commit 291099cf4d31e110827c702dffec33fbea1fd6af) --- src/Social/Service/OpenIDConnectService.php | 85 +++++++++++++++++++++ 1 file changed, 85 insertions(+) create mode 100644 src/Social/Service/OpenIDConnectService.php diff --git a/src/Social/Service/OpenIDConnectService.php b/src/Social/Service/OpenIDConnectService.php new file mode 100644 index 0000000..d855c45 --- /dev/null +++ b/src/Social/Service/OpenIDConnectService.php @@ -0,0 +1,85 @@ + [ + 'baseUrl' => 'https://www.linkedin.com/', + 'url' => 'https://www.linkedin.com/oauth/.well-known/openid-configuration', + 'jwk' => [ + 'defaultAlgorithm' => 'RS256', + ], + ], + ]; + + public function getUser(ServerRequestInterface $request): array + { + if (!$request instanceof ServerRequest) { + throw new \BadMethodCallException('Request must be an instance of ServerRequest'); + } + if (!$this->validate($request)) { + throw new BadRequestException('Invalid OAuth2 state'); + } + + $code = $request->getQuery('code'); + /** @var \League\OAuth2\Client\Token\AccessToken $token */ + $token = $this->provider->getAccessToken('authorization_code', ['code' => $code]); + $tokenValues = $token->getValues(); + $idToken = $tokenValues['id_token'] ?? null; + if (!$idToken) { + throw new BadRequestException('Missing id_token in response'); + } + try { + $idTokenDecoded = JWT::decode($idToken, $this->getIdTokenKeys()); + + return ['token' => $token] + (array)$idTokenDecoded; + } catch (\Exception $ex) { + throw new BadRequestException('Invalid id token. ' . $ex->getMessage()); + } + } + + protected function getIdTokenKeys(): array + { + $discoverData = $this->discover(); + $jwksUri = $discoverData['jwks_uri'] ?? null; + if (!$jwksUri) { + throw new BadRequestException( + 'No `jwks_uri` in discover data. Unable to retrieve the JWT signature public key' + ); + } + if (strpos($jwksUri, $this->getConfig('openid.baseUrl')) !== 0) { + throw new BadRequestException( + 'Invalid `jwks_uri` in discover data. It is not pointing to ' . + $this->getConfig('openid.baseUrl') + ); + } + $client = new Client(); + $jwksData = $client->get($jwksUri)->getJson(); + if (!$jwksData) { + throw new BadRequestException( + 'Unable to retrieve jwks. Not found in the `jwks_uri` contents' + ); + } + + return JWK::parseKeySet($jwksData, $this->getConfig('openid.jwk.defaultAlgorithm')); + } + + public function discover(): array + { + $openidUrl = $this->getConfig('openid.url'); + $client = new Client(); + + return $client->get($openidUrl)->getJson(); + } +} From a09bf0f9d059c1616dd9051fdcf20f83d5df0483 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gonz=C3=A1lez?= Date: Thu, 7 Sep 2023 12:54:30 +0100 Subject: [PATCH 14/35] fix cs (cherry picked from commit 4c0a660f9925ea17281d3702b04a7fb1a9280757) --- src/Social/Service/OpenIDConnectService.php | 1 - 1 file changed, 1 deletion(-) diff --git a/src/Social/Service/OpenIDConnectService.php b/src/Social/Service/OpenIDConnectService.php index d855c45..3cac93f 100644 --- a/src/Social/Service/OpenIDConnectService.php +++ b/src/Social/Service/OpenIDConnectService.php @@ -6,7 +6,6 @@ use Cake\Http\Client; use Cake\Http\Exception\BadRequestException; use Cake\Http\ServerRequest; -use CakeDC\Auth\Social\Service\OAuth2Service; use Firebase\JWT\JWK; use Firebase\JWT\JWT; use Psr\Http\Message\ServerRequestInterface; From 126992980eb900158529e3eec0470c8650985530 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gonz=C3=A1lez?= Date: Thu, 7 Sep 2023 12:57:49 +0100 Subject: [PATCH 15/35] #openid-connect-linkedin add linkedin connect mapper (cherry picked from commit f522e5999ac5dd63e6089459c1a289be06fbc38f) --- src/Social/Mapper/LinkedInOpenIDConnect.php | 39 +++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 src/Social/Mapper/LinkedInOpenIDConnect.php diff --git a/src/Social/Mapper/LinkedInOpenIDConnect.php b/src/Social/Mapper/LinkedInOpenIDConnect.php new file mode 100644 index 0000000..7efd449 --- /dev/null +++ b/src/Social/Mapper/LinkedInOpenIDConnect.php @@ -0,0 +1,39 @@ + 'picture', + 'first_name' => 'given_name', + 'last_name' => 'family_name', + 'email' => 'email', + 'link' => 'link', + 'id' => 'sub', + ]; + + protected function _link(): string { + // no way to retrieve the public url from the users profile + + return 'https://www.linkedin.com'; + } +} From 05e60c3f677dc5ac437d00d0f501f3d6736da0c3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gonz=C3=A1lez?= Date: Thu, 7 Sep 2023 12:57:49 +0100 Subject: [PATCH 16/35] fix cs (cherry picked from commit aee0010b0a6da699b3320823ece06abaa01b28f0) --- src/Social/Mapper/LinkedInOpenIDConnect.php | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/src/Social/Mapper/LinkedInOpenIDConnect.php b/src/Social/Mapper/LinkedInOpenIDConnect.php index 7efd449..cd190ab 100644 --- a/src/Social/Mapper/LinkedInOpenIDConnect.php +++ b/src/Social/Mapper/LinkedInOpenIDConnect.php @@ -13,8 +13,6 @@ namespace CakeDC\Auth\Social\Mapper; -use CakeDC\Auth\Social\Mapper\AbstractMapper; - class LinkedInOpenIDConnect extends AbstractMapper { /** @@ -31,7 +29,8 @@ class LinkedInOpenIDConnect extends AbstractMapper 'id' => 'sub', ]; - protected function _link(): string { + protected function _link(): string + { // no way to retrieve the public url from the users profile return 'https://www.linkedin.com'; From d5afa914101e981ac6094702d53424afce105fdc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gonz=C3=A1lez?= Date: Thu, 7 Sep 2023 13:22:00 +0100 Subject: [PATCH 17/35] #openid-connect-linkedin update docs (cherry picked from commit 7df2287cc65e0af804b7ed9e1098a18b143704e6) --- Docs/Documentation/Social.md | 13 +++++++------ config/auth.php | 12 ++++++++++++ 2 files changed, 19 insertions(+), 6 deletions(-) diff --git a/Docs/Documentation/Social.md b/Docs/Documentation/Social.md index 2f2bf08..ed74a1a 100644 --- a/Docs/Documentation/Social.md +++ b/Docs/Documentation/Social.md @@ -1,7 +1,7 @@ Social Layer ============ The social layer provide a easier way to handle social provider authentication -with provides using OAuth1 or OAuth2. The idea is to provide a base +with provides using OAuth1 or OAuth2. The idea is to provide a base interface for both OAuth and OAuth2. ***Make sure to load the bootstap.php file of this plugin!*** @@ -12,9 +12,10 @@ We have mappers to allow you a quick start with these providers: - Facebook - Google - Instagram -- LinkedIn +- LinkedIn (Deprecated, they switched to OpenID-Connect) +- LinkedInOpenIDConnect (New, OIDC based authentication) - Pinterest -- Tumblr +- Tumblr - Twitter - Github @@ -58,7 +59,7 @@ use CakeDC\Auth\Social\Service\ServiceFactory; ->getAuthorizationUrl($this->request) ); } - + /** * Callback to get user information from provider * @@ -81,7 +82,7 @@ use CakeDC\Auth\Social\Service\ServiceFactory; } $data = $server->getUser($this->request); $data = (new MapUser())($server, $data); - + //your code } catch (\Exception $e) { $this->log($log); @@ -205,4 +206,4 @@ KEYCLOAK_CLIENT_SECRET=your-client-secret KEYCLOAK_AUTH_SERVER_URL=https://your-keycloak-server/auth ``` -This setup allows your CakePHP application to authenticate users through Keycloak and map their roles appropriately. \ No newline at end of file +This setup allows your CakePHP application to authenticate users through Keycloak and map their roles appropriately. diff --git a/config/auth.php b/config/auth.php index 782d5ab..0d57dab 100644 --- a/config/auth.php +++ b/config/auth.php @@ -35,6 +35,7 @@ 'callbackLinkSocialUri' => Router::fullBaseUrl() . '/callback-link-social/twitter', ] ], + // Deprecated, LinkedIn switched to OpenID-Connect and OAuth2 is no longer working properly 'linkedIn' => [ 'service' => 'CakeDC\Auth\Social\Service\OAuth2Service', 'className' => 'League\OAuth2\Client\Provider\LinkedIn', @@ -45,6 +46,17 @@ 'callbackLinkSocialUri' => Router::fullBaseUrl() . '/callback-link-social/linkedIn', ], ], + 'linkedInOpenIDConnect' => [ + 'service' => 'CakeDC\Auth\Social\Service\OpenIDConnectService', + 'className' => 'League\OAuth2\Client\Provider\LinkedIn', + 'mapper' => 'CakeDC\Auth\Social\Mapper\LinkedInOpenIDConnect', + 'options' => [ + 'redirectUri' => Router::fullBaseUrl() . '/auth/linkedInOpenIDConnect', + 'linkSocialUri' => Router::fullBaseUrl() . '/link-social/linkedInOpenIDConnect', + 'callbackLinkSocialUri' => Router::fullBaseUrl() . '/callback-link-social/linkedInOpenIDConnect', + 'defaultScopes' => ['email', 'openid', 'profile'], + ], + ], 'instagram' => [ 'service' => 'CakeDC\Auth\Social\Service\OAuth2Service', 'className' => 'League\OAuth2\Client\Provider\Instagram', From 4d859da759a4b502f90f16aa710e222b350ddbbb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gonz=C3=A1lez?= Date: Thu, 7 Sep 2023 13:22:01 +0100 Subject: [PATCH 18/35] fix cs (cherry picked from commit 978370b126cd06bcfd0cecd8994fd9cc1aad4a11) # Conflicts: # config/auth.php --- config/auth.php | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/config/auth.php b/config/auth.php index 0d57dab..3c170af 100644 --- a/config/auth.php +++ b/config/auth.php @@ -10,6 +10,7 @@ */ use Cake\Routing\Router; + return [ 'OAuth.path' => ['plugin' => 'CakeDC/Users', 'controller' => 'Users', 'action' => 'socialLogin', 'prefix' => null], 'OAuth.providers' => [ @@ -33,7 +34,7 @@ 'redirectUri' => Router::fullBaseUrl() . '/auth/twitter', 'linkSocialUri' => Router::fullBaseUrl() . '/link-social/twitter', 'callbackLinkSocialUri' => Router::fullBaseUrl() . '/callback-link-social/twitter', - ] + ], ], // Deprecated, LinkedIn switched to OpenID-Connect and OAuth2 is no longer working properly 'linkedIn' => [ @@ -65,7 +66,7 @@ 'redirectUri' => Router::fullBaseUrl() . '/auth/instagram', 'linkSocialUri' => Router::fullBaseUrl() . '/link-social/instagram', 'callbackLinkSocialUri' => Router::fullBaseUrl() . '/callback-link-social/instagram', - ] + ], ], 'google' => [ 'service' => 'CakeDC\Auth\Social\Service\OAuth2Service', From dc64e62e506c70198d5a8eb99c846436a78c2f7f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gonz=C3=A1lez?= Date: Thu, 7 Sep 2023 13:32:47 +0100 Subject: [PATCH 19/35] #openid-connect-linkedin add firebase requirement for OIDC (cherry picked from commit 8ee81454a4c8cc063cc831c48e0cd42718ef02aa) --- composer.json | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/composer.json b/composer.json index 322604a..cbe7ad8 100644 --- a/composer.json +++ b/composer.json @@ -44,7 +44,8 @@ "cakephp/authorization": "^3.0", "cakephp/cakephp-codesniffer": "^5.0", "cakephp/authentication": "^3.0", - "yubico/u2flib-server": "^1.0" + "yubico/u2flib-server": "^1.0", + "firebase/php-jwt": "^6.8" }, "suggest": { }, From f8cb404956484d450ec6255bb4cc2709fad3ecd3 Mon Sep 17 00:00:00 2001 From: Alberto Rodriguez Date: Thu, 14 Sep 2023 15:29:37 -0400 Subject: [PATCH 20/35] feat: tests for OpenID. WIP (cherry picked from commit d3f825e1a40d9b8dacc59d088efaf907deadc6c5) --- .../Mapper/LinkedInOpenIDConnectTest.php | 81 +++++ .../Service/OpenIDConnectServiceTest.php | 280 ++++++++++++++++++ 2 files changed, 361 insertions(+) create mode 100644 tests/TestCase/Social/Mapper/LinkedInOpenIDConnectTest.php create mode 100644 tests/TestCase/Social/Service/OpenIDConnectServiceTest.php diff --git a/tests/TestCase/Social/Mapper/LinkedInOpenIDConnectTest.php b/tests/TestCase/Social/Mapper/LinkedInOpenIDConnectTest.php new file mode 100644 index 0000000..5e95926 --- /dev/null +++ b/tests/TestCase/Social/Mapper/LinkedInOpenIDConnectTest.php @@ -0,0 +1,81 @@ + 'test-token', + 'expires' => 1490988496, + ]); + $rawData = [ + 'sub' => '1', + 'token' => $token, + 'email' => 'test@gmail.com', + 'given_name' => 'Test', + 'family_name' => 'User', + 'industry' => 'Computer Software', + 'location' => [ + 'country' => [ + 'code' => 'es', + ], + 'name' => 'Spain', + ], + 'picture' => 'https://media.licdn.com/mpr/mprx/test.jpg', + + + 'bio' => 'The best test user in the world.', + 'publicProfileUrl' => 'https://www.linkedin.com/in/test', + ]; + $providerMapper = new LinkedInOpenIDConnect(); + $user = $providerMapper($rawData); + + $this->assertEquals([ + 'id' => '1', + 'username' => null, + 'full_name' => null, + 'first_name' => 'Test', + 'last_name' => 'User', + 'email' => 'test@gmail.com', + 'avatar' => 'https://media.licdn.com/mpr/mprx/test.jpg', + 'gender' => null, + 'link' => 'https://www.linkedin.com', + 'bio' => 'The best test user in the world.', + 'locale' => null, + 'validated' => true, + 'credentials' => [ + 'token' => 'test-token', + 'secret' => null, + 'expires' => 1490988496, + ], + 'raw' => $rawData, + ], $user); + } +} diff --git a/tests/TestCase/Social/Service/OpenIDConnectServiceTest.php b/tests/TestCase/Social/Service/OpenIDConnectServiceTest.php new file mode 100644 index 0000000..1d22ffc --- /dev/null +++ b/tests/TestCase/Social/Service/OpenIDConnectServiceTest.php @@ -0,0 +1,280 @@ +Provider = $this->getMockBuilder( + \League\OAuth2\Client\Provider\LinkedIn::class + )->setConstructorArgs([ + [ + 'id' => '1', + 'firstName' => 'first', + 'lastName' => 'last', + ], + [], + ])->setMethods([ + 'getAccessToken', 'getState', 'getAuthorizationUrl', 'getResourceOwner', + ])->getMock(); + + $config = [ + 'service' => OpenIDConnectService::class, + 'className' => $this->Provider, + 'mapper' => \CakeDC\Auth\Social\Mapper\LinkedInOpenIDConnect::class, + 'authParams' => ['scope' => ['public_profile', 'email', 'user_birthday', 'user_gender', 'user_link']], + 'options' => [ + 'state' => '__TEST_STATE__', + ], + 'collaborators' => [], + 'signature' => null, + 'mapFields' => [], + 'path' => [ + 'plugin' => 'CakeDC/Users', + 'controller' => 'Users', + 'action' => 'socialLogin', + 'prefix' => null, + ], + ]; + + $this->Service = $this->getMockBuilder( + \CakeDC\Auth\Social\Service\OpenIDConnectService::class + )->setConstructorArgs([ + $config, + ])->onlyMethods([ + 'getIdTokenKeys', + ])->getMock(); + + //new OpenIDConnectService($config); + $this->Request = ServerRequestFactory::fromGlobals(); + } + + /** + * teardown any static object changes and restore them. + * + * @return void + */ + public function tearDown(): void + { + parent::tearDown(); + + unset($this->Provider, $this->Service, $this->Request); + } + + /** + * Test construct + * + * @return void + */ + public function testConstruct() + { + $service = new OpenIDConnectService([ + 'className' => \League\OAuth2\Client\Provider\LinkedIn::class, + 'mapper' => \CakeDC\Auth\Social\Mapper\LinkedInOpenIDConnect::class, + 'authParams' => ['scope' => ['public_profile', 'email', 'user_birthday', 'user_gender', 'user_link']], + 'options' => [], + 'collaborators' => [], + 'signature' => null, + 'mapFields' => [], + 'path' => [ + 'plugin' => 'CakeDC/Users', + 'controller' => 'Users', + 'action' => 'socialLogin', + 'prefix' => null, + ], + ]); + $this->assertInstanceOf(ServiceInterface::class, $service); + } + + /** + * Test GetUser InvalidRequest + * + * @return void + */ + public function testGetUserInvalidRequest() + { + $this->Request = $this->Request->withQueryParams([ + 'code' => 'ZPO9972j3092304230', + 'state' => '__TEST_STATE__', + ]); + + $this->expectException(BadRequestException::class, 'Invalid OAuth2 state'); + + $this->Service->getUser($this->Request); + } + + /** + * Test GetUser MisingIdToken + * + * @return void + */ + public function testGetUserMisingIdToken() + { + $this->Request = $this->Request->withQueryParams([ + 'code' => 'ZPO9972j3092304230', + 'state' => '__TEST_STATE__', + ]); + + $this->Request->getSession()->write('oauth2state', '__TEST_STATE__'); + + $token = new \League\OAuth2\Client\Token\AccessToken([ + 'access_token' => 'test-token', + 'expires' => 1490988496, + ]); + + $this->Provider->expects($this->once()) + ->method('getAccessToken') + ->with( + $this->equalTo('authorization_code'), + $this->equalTo(['code' => 'ZPO9972j3092304230']) + ) + ->will($this->returnValue($token)); + + $this->expectException(BadRequestException::class, 'Missing id_token in response'); + + $this->Service->getUser($this->Request); + } + + /** + * Test GetUser InvalidIdToken + * + * @return void + */ + public function testGetUserInvalidIdToken() + { + $this->Request = $this->Request->withQueryParams([ + 'code' => 'ZPO9972j3092304230', + 'state' => '__TEST_STATE__', + ]); + + $this->Request->getSession()->write('oauth2state', '__TEST_STATE__'); + + $token = new \League\OAuth2\Client\Token\AccessToken([ + 'access_token' => 'test-token', + 'expires' => 1490988496, + 'id_token' => 'invalid-jwt', + ]); + + $this->Provider->expects($this->once()) + ->method('getAccessToken') + ->with( + $this->equalTo('authorization_code'), + $this->equalTo(['code' => 'ZPO9972j3092304230']) + ) + ->will($this->returnValue($token)); + + $this->expectException(BadRequestException::class, 'Invalid id token. Key may not be empty'); + + $this->Service->getUser($this->Request); + } + + /** + * Test GetUser + * + * @return void + */ + public function testGetUser() + { + $this->Request = $this->Request->withQueryParams([ + 'code' => 'ZPO9972j3092304230', + 'state' => '__TEST_STATE__', + ]); + + $this->Request->getSession()->write('oauth2state', '__TEST_STATE__'); + + $key = 'example_key'; + $alg = 'HS256'; + $payload = [ + 'iat' => 1490988496, + 'iss' => 'https://www.linkedin.com/', + ]; + $kid = 'd929668a-bab1-4c69-9598-4373149723ff'; + $jwt = JWT::encode($payload, $key, $alg, $kid); + + $token = new \League\OAuth2\Client\Token\AccessToken([ + 'access_token' => 'test-token', + 'expires' => 1490988496, + 'id_token' => $jwt, + ]); + + $this->Provider->expects($this->once()) + ->method('getAccessToken') + ->with( + $this->equalTo('authorization_code'), + $this->equalTo(['code' => 'ZPO9972j3092304230']) + ) + ->will($this->returnValue($token)); + + $jwksData = [ + $kid => new Key($key, $alg), + ]; + + $this->Service->expects($this->once()) + ->method('getIdTokenKeys') + ->will($this->returnValue($jwksData)); + + $actual = $this->Service->getUser($this->Request); + + $expected = [ + 'token' => $token, + 'iat' => 1490988496, + 'iss' => 'https://www.linkedin.com/', + ]; + + $this->assertEquals($expected, $actual); + } +} From 73d90f164213193e8810e1c816fd31e3a70bc9c9 Mon Sep 17 00:00:00 2001 From: Alberto Rodriguez Date: Sat, 30 Sep 2023 13:26:21 -0400 Subject: [PATCH 21/35] test: add test (cherry picked from commit ad6e98b127692bdf3f4c4a71c91eb321de10d568) --- src/Social/Service/OpenIDConnectService.php | 9 ++++- .../Service/OpenIDConnectServiceTest.php | 37 ++++++++++++++++++- 2 files changed, 43 insertions(+), 3 deletions(-) diff --git a/src/Social/Service/OpenIDConnectService.php b/src/Social/Service/OpenIDConnectService.php index 3cac93f..f797168 100644 --- a/src/Social/Service/OpenIDConnectService.php +++ b/src/Social/Service/OpenIDConnectService.php @@ -63,7 +63,7 @@ protected function getIdTokenKeys(): array $this->getConfig('openid.baseUrl') ); } - $client = new Client(); + $client = $this->getHttpClient(); $jwksData = $client->get($jwksUri)->getJson(); if (!$jwksData) { throw new BadRequestException( @@ -77,8 +77,13 @@ protected function getIdTokenKeys(): array public function discover(): array { $openidUrl = $this->getConfig('openid.url'); - $client = new Client(); + $client = $this->getHttpClient(); return $client->get($openidUrl)->getJson(); } + + protected function getHttpClient(): Client + { + return new Client(); + } } diff --git a/tests/TestCase/Social/Service/OpenIDConnectServiceTest.php b/tests/TestCase/Social/Service/OpenIDConnectServiceTest.php index 1d22ffc..14a56d6 100644 --- a/tests/TestCase/Social/Service/OpenIDConnectServiceTest.php +++ b/tests/TestCase/Social/Service/OpenIDConnectServiceTest.php @@ -34,7 +34,7 @@ class OpenIDConnectServiceTest extends TestCase { /** - * @var \CakeDC\Auth\Social\Service\OAuth2Service + * @var \CakeDC\Auth\Social\Service\OpenIDConnectService */ public $Service; @@ -48,6 +48,11 @@ class OpenIDConnectServiceTest extends TestCase */ public $Request; + /** + * @var \Cake\Http\Client + */ + public $Client; + /** * Setup the test case, backup the static object values so they can be restored. * Specifically backs up the contents of Configure and paths in App if they have @@ -59,6 +64,12 @@ public function setUp(): void { parent::setUp(); + $this->Client = $this->getMockBuilder( + \Cake\Http\Client::class + )->onlyMethods([ + 'get', + ])->getMock(); + $this->Provider = $this->getMockBuilder( \League\OAuth2\Client\Provider\LinkedIn::class )->setConstructorArgs([ @@ -97,8 +108,13 @@ public function setUp(): void $config, ])->onlyMethods([ 'getIdTokenKeys', + 'getHttpClient', ])->getMock(); + $this->Service->expects($this->any()) + ->method('getHttpClient') + ->will($this->returnValue($this->Client)); + //new OpenIDConnectService($config); $this->Request = ServerRequestFactory::fromGlobals(); } @@ -277,4 +293,23 @@ public function testGetUser() $this->assertEquals($expected, $actual); } + + /** + * Test discover + * + * @return void + */ + public function testDiscover() + { + $arrayTest = ['test' => 'test']; + $response = new \Cake\Http\Client\Response([], json_encode($arrayTest)); + + $this->Client->expects($this->once()) + ->method('get') + ->will($this->returnValue($response)); + + $actual = $this->Service->discover(); + + $this->assertEquals($arrayTest, $actual); + } } From 2546a37285e75dfb34b1ed38fa391b061ffdc460 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gonz=C3=A1lez?= Date: Tue, 22 Apr 2025 17:40:55 +0100 Subject: [PATCH 22/35] #openid-connect-linkedin ignore (cherry picked from commit 891a7b731b5bbf3c570c5bc1d706b59786c0629e) --- .gitignore | 1 + 1 file changed, 1 insertion(+) diff --git a/.gitignore b/.gitignore index 4722bb4..f242c89 100644 --- a/.gitignore +++ b/.gitignore @@ -3,3 +3,4 @@ /.idea composer.lock .php_cs.cache +.phpunit.result.cache From aa7e7b82f09f2f45ffa1bd9d9c94d5810656850a Mon Sep 17 00:00:00 2001 From: Yevgeny Tomenko Date: Thu, 5 Sep 2024 05:19:26 +0300 Subject: [PATCH 23/35] Add OTPRule and className rule config in Rbac permissions Partial cherry-pick of 5d4e5df (implements CachedRbac functionality): only OTPRule, the className/options rule config branch in Rbac and its use in the default permissions are taken. CachedRbac is not included. (cherry picked from commit 5d4e5df0e54202d35b82aa9918a21717e7941b94) --- config/permissions.php | 12 +++----- src/Rbac/Permissions/AbstractProvider.php | 12 +++----- src/Rbac/Rbac.php | 6 ++++ src/Rbac/Rules/OTPRule.php | 36 +++++++++++++++++++++++ tests/TestCase/Rbac/RbacTest.php | 7 +++-- 5 files changed, 54 insertions(+), 19 deletions(-) create mode 100644 src/Rbac/Rules/OTPRule.php diff --git a/config/permissions.php b/config/permissions.php index 930b853..46d453a 100644 --- a/config/permissions.php +++ b/config/permissions.php @@ -105,14 +105,10 @@ 'plugin' => 'CakeDC/Users', 'controller' => 'Users', 'action' => 'resetOneTimePasswordAuthenticator', - 'allowed' => function (array $user, $role, \Cake\Http\ServerRequest $request) { - $userId = \Cake\Utility\Hash::get($request->getAttribute('params'), 'pass.0'); - if (!empty($userId) && !empty($user)) { - return $userId === $user['id']; - } - - return false; - } + 'allowed' => [ + 'className' => \CakeDC\Auth\Rbac\Rules\OTPRule::class, + 'option' => [] + ], ], //all roles allowed to Pages/display [ diff --git a/src/Rbac/Permissions/AbstractProvider.php b/src/Rbac/Permissions/AbstractProvider.php index 60a52d8..150697f 100644 --- a/src/Rbac/Permissions/AbstractProvider.php +++ b/src/Rbac/Permissions/AbstractProvider.php @@ -99,14 +99,10 @@ public function __construct(array $config = []) 'plugin' => 'CakeDC/Users', 'controller' => 'Users', 'action' => 'resetOneTimePasswordAuthenticator', - 'allowed' => function (array $user, string $role, ServerRequest $request): bool { - $userId = Hash::get($request->getAttribute('params'), 'pass.0'); - if (!empty($userId) && !empty($user)) { - return $userId === $user['id']; - } - - return false; - }, + 'allowed' => [ + 'className' => \CakeDC\Auth\Rbac\Rules\OTPRule::class, + 'option' => [] + ], ], //all roles allowed to Pages/display [ diff --git a/src/Rbac/Rbac.php b/src/Rbac/Rbac.php index 635f8ed..466d04e 100644 --- a/src/Rbac/Rbac.php +++ b/src/Rbac/Rbac.php @@ -24,6 +24,7 @@ use CakeDC\Auth\Rbac\Permissions\AbstractProvider; use CakeDC\Auth\Rbac\Permissions\ConfigProvider; use CakeDC\Auth\Rbac\Rules\Rule; +use CakeDC\Auth\Rbac\Rules\RuleRegistry; use Psr\Http\Message\ServerRequestInterface; use Psr\Log\LogLevel; use RuntimeException; @@ -221,6 +222,11 @@ protected function _matchPermission(array $permission, array|ArrayAccess $user, $return = (bool)call_user_func($value, $user, $role, $request); } elseif ($value instanceof Rule) { $return = $value->allowed($user, $role, $request); + } elseif (is_array($value) && array_key_exists('className', $value)) { + $rule = RuleRegistry::get($value['className'], $value['options'] ?? []); + if ($rule instanceof Rule) { + $return = (bool)$rule->allowed($user, $role, $request); + } } elseif ($key === 'bypassAuth' && $value === true) { $return = true; } elseif ($key === 'allowed') { diff --git a/src/Rbac/Rules/OTPRule.php b/src/Rbac/Rules/OTPRule.php new file mode 100644 index 0000000..58eadee --- /dev/null +++ b/src/Rbac/Rules/OTPRule.php @@ -0,0 +1,36 @@ +getAttribute('params'), 'pass.0'); + if (!empty($userId) && !empty($user)) { + return $userId === $user['id']; + } + + return false; + } +} diff --git a/tests/TestCase/Rbac/RbacTest.php b/tests/TestCase/Rbac/RbacTest.php index 61a6918..e685b19 100644 --- a/tests/TestCase/Rbac/RbacTest.php +++ b/tests/TestCase/Rbac/RbacTest.php @@ -98,7 +98,10 @@ public function setUp(): void 'plugin' => 'CakeDC/Users', 'controller' => 'Users', 'action' => 'resetOneTimePasswordAuthenticator', - 'allowed' => true, + 'allowed' => [ + 'className' => \CakeDC\Auth\Rbac\Rules\OTPRule::class, + 'option' => [] + ], ], //all roles allowed to Pages/display [ @@ -133,8 +136,6 @@ public function testConstructGetDefaultPermissions() { $this->rbac = new Rbac(); $result = $this->rbac->getPermissions(); - $this->assertTrue(is_callable($result[4]['allowed'])); - $result[4]['allowed'] = true; $this->assertSame($this->defaultPermissions, $result); } From 6bf92621af0b0ce9fe445f714f98d16c0b5167e2 Mon Sep 17 00:00:00 2001 From: Adam Rusinowski Date: Fri, 30 Oct 2026 13:04:27 +0100 Subject: [PATCH 24/35] fix: review fixes for the integrated pull requests, curate composer dependencies - 2FA: encode the query params of string verify urls, U2FProcessor::getUrlByType() returns array|string|null like the interface. - OIDC: validate the id token iss, aud and nonce claims, cache the discovery document and the key set with `openid.cache`. - Rbac: fix the OTPRule signature, only treat arrays with a Rule `className` as rule config. - Keycloak: drop the global social login listener and the runtime role config write, clean up the mapper and add tests. - Docs, changelog and composer suggestions for the new providers. - composer.json: require cakephp/authentication ^3.3 and CakePHP ^5.4, curate the dev dependencies for PHP 8.2 to 8.5 (lowest and highest), psalm 6 phar with a baseline, remove the stan-setup script. - Tests: replace docblock PHPUnit metadata with attributes. --- .github/workflows/ci.yml | 2 +- CHANGELOG.md | 25 + Docs/Documentation/Rbac.md | 12 + Docs/Documentation/Social.md | 54 +- Docs/Documentation/TwoFactor.md | 4 + composer.json | 54 +- config/auth.php | 31 +- config/permissions.php | 2 +- psalm-baseline.xml | 538 ++++++++++++++++++ psalm.xml | 25 +- .../TwoFactorProcessor/U2FProcessor.php | 4 +- src/Event/SocialLoginListener.php | 45 -- src/Middleware/TwoFactorMiddleware.php | 4 +- src/Rbac/Permissions/AbstractProvider.php | 7 +- src/Rbac/Rbac.php | 22 +- src/Rbac/Rules/OTPRule.php | 18 +- src/Social/MapUser.php | 16 - src/Social/Mapper/Keycloak.php | 108 ++-- src/Social/Mapper/LinkedInOpenIDConnect.php | 12 +- src/Social/Service/OpenIDConnectService.php | 164 +++++- .../Authenticator/CookieAuthenticatorTest.php | 1 - .../Authenticator/FormAuthenticatorTest.php | 4 +- .../Middleware/RbacMiddlewareTest.php | 12 - .../Middleware/TwoFactorMiddlewareTest.php | 57 +- .../TestCase/Policy/CollectionPolicyTest.php | 1 - tests/TestCase/Policy/SuperuserPolicyTest.php | 1 - tests/TestCase/Rbac/RbacTest.php | 59 +- tests/TestCase/Rbac/Rules/OTPRuleTest.php | 50 ++ tests/TestCase/Social/Mapper/KeycloakTest.php | 126 ++++ .../Mapper/LinkedInOpenIDConnectTest.php | 9 +- .../Service/OpenIDConnectServiceTest.php | 194 +++++-- .../TestCase/Traits/IsAuthorizedTraitTest.php | 1 - 32 files changed, 1359 insertions(+), 303 deletions(-) create mode 100644 psalm-baseline.xml delete mode 100644 src/Event/SocialLoginListener.php create mode 100644 tests/TestCase/Rbac/Rules/OTPRuleTest.php create mode 100644 tests/TestCase/Social/Mapper/KeycloakTest.php diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index a5241ea..60e5714 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -110,7 +110,7 @@ jobs: key: ${{ runner.os }}-composer-${{ steps.key-date.outputs.date }}-${{ hashFiles('composer.json') }}-${{ matrix.prefer-lowest }} - name: composer install - run: composer stan-setup + run: composer update - name: Run PHP CodeSniffer run: composer cs-check diff --git a/CHANGELOG.md b/CHANGELOG.md index 927a9c3..099b336 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,31 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). ## [Unreleased] +### Added +- Keycloak social login mapper `CakeDC\Auth\Social\Mapper\Keycloak`, with realm roles mapped by the + `rolesMap` provider config, and a disabled `keycloak` provider in `config/auth.php`. +- `CakeDC\Auth\Social\Service\OpenIDConnectService` and the `LinkedInOpenIDConnect` mapper and + provider. The id token `iss`, `aud` and `nonce` claims are validated, the discovery document and the + key set can be cached with `openid.cache`. Requires `firebase/php-jwt`. +- `CakeDC\Auth\Rbac\Rules\OTPRule`, used by the default `resetOneTimePasswordAuthenticator` permission. +- Rbac permission values can be a rule config array `['className' => Rule::class, 'options' => []]`. + Arrays with a `className` key that is not a `Rule` class keep the previous matching behavior. +- The 2FA verify url (`TwoFactorProcessorInterface::getUrlByType()`) can be a string url. The return + type is now `array|string|null`; custom callers of `getUrlByType()` must handle strings. + +### Changed +- Requires CakePHP `^5.4` (PHP `>=8.2` unchanged). +- `cakephp/authentication` `^3.3` moved from require-dev/suggest to `require`, the authenticators, + identifiers, 2FA and social login depend on it. +- Dev dependencies curated: no more `@stable` constraints, minimum versions raised to the ones the + test suite passes with on PHP 8.2 (`--prefer-lowest`) up to 8.5. PHPUnit `^11.5 || ^12.5`, + PHPStan `^2.3`, Psalm `^6.20` (`psalm/phar` in require-dev, `stan-setup` script removed), + `robthree/twofactorauth` `^3.0.1`, `endroid/qr-code` `^6.0`. +- Removed the unused `yubico/u2flib-server` dev dependency (U2F is deprecated). +- `suggest` lists the optional packages needed by each feature. +- The default `resetOneTimePasswordAuthenticator` permission uses `OTPRule` instead of a closure. It + compares the user id as string, so integer ids are matched too. + ### Fixed - `ReCaptchaTrait::validateReCaptchaFromRequest()` treats a missing or empty `g-recaptcha-response` as an invalid captcha (returns `false`) instead of passing `null` to the diff --git a/Docs/Documentation/Rbac.md b/Docs/Documentation/Rbac.md index e1514e8..62a7625 100644 --- a/Docs/Documentation/Rbac.md +++ b/Docs/Documentation/Rbac.md @@ -93,6 +93,18 @@ For example, the above ownership callback is included in CakeDC\Users as `Owner` ``` Check the [Owner Rule](OwnerRule.md) documentation for more details +You can also define a rule as an array with the rule class name and its options. The rule is +created with the RuleRegistry. Unlike a closure, this permission can be serialized: + +```php +'allowed' => [ + 'className' => \CakeDC\Auth\Rbac\Rules\OTPRule::class, + 'options' => [], +], +``` + +The array is used as a rule only when `className` is a class implementing `\CakeDC\Auth\Rbac\Rules\Rule`. + ## Creating rule classes The only requirement is to implement `\CakeDC\Auth\Rbac\Rules\Rule` interface which has one method: diff --git a/Docs/Documentation/Social.md b/Docs/Documentation/Social.md index ed74a1a..6dfbb79 100644 --- a/Docs/Documentation/Social.md +++ b/Docs/Documentation/Social.md @@ -18,6 +18,7 @@ We have mappers to allow you a quick start with these providers: - Tumblr - Twitter - Github +- Keycloak You must define 'options.redirectUri', 'options.clientId' and 'options.clientSecret' for any provider you want to enable. eg, @@ -126,11 +127,10 @@ Add the Keycloak provider configuration to your `config/users.php` file: 'CakeDc-Worker' => 'user' ], 'authParams' => ['scope' => ['openid', 'roles']], - 'skipSocialAccountValidation' => true, 'options' => [ 'redirectUri' => Router::fullBaseUrl() . '/auth/keycloak', - 'linkSocialUri' => Router::fullBaseUrl() . '/auth/link-social/keycloak', - 'callbackLinkSocialUri' => Router::fullBaseUrl() . '/auth/callback-link-social/keycloak', + 'linkSocialUri' => Router::fullBaseUrl() . '/link-social/keycloak', + 'callbackLinkSocialUri' => Router::fullBaseUrl() . '/callback-link-social/keycloak', 'realm' => env('KEYCLOAK_REALM', null), 'clientId' => env('KEYCLOAK_CLIENT_ID', null), 'clientSecret' => env('KEYCLOAK_CLIENT_SECRET', null), @@ -157,11 +157,22 @@ Add the Keycloak provider configuration to your `config/users.php` file: ### Role Mapping -The plugin maps Keycloak roles to application roles using the `rolesMap` configuration. When a user logs in, their Keycloak roles are checked against this map and the corresponding application role is assigned. +The `CakeDC\Auth\Social\Mapper\Keycloak` mapper reads the realm roles from `realm_access.roles` +and maps them to an application role using the `rolesMap` provider configuration. The keys are +Keycloak roles (compared case-insensitive), the values are application roles. The first entry of +`rolesMap` the user has wins, so list the most privileged roles first. The mapped role is +returned in the `roles` field of the mapped user. + +The login fails with an `UnexpectedValueException` when the userinfo has no roles or none of the +user roles is in `rolesMap`. + +The mapper does not change the user role by itself. Use an event listener in your application to +apply it, see below. ### Event Listener for Role Updates -You can create a custom event listener to update user roles during login: +Create an event listener in your application to update the role of existing users during login +and register it in your `Application::bootstrap()` with `EventManager::instance()->on(new SocialLoginListener());`: ```php [ + // ... + 'openid' => [ + // the jwks_uri of the discovery document must start with this url + 'baseUrl' => 'https://www.linkedin.com/', + // discovery document + 'url' => 'https://www.linkedin.com/oauth/.well-known/openid-configuration', + // expected issuer, null to use the issuer of the discovery document + 'issuer' => null, + // send a nonce in the authorization request and validate it in the id token + 'nonce' => true, + // cache config for the discovery document and the key set, null to disable the cache + 'cache' => null, + ], +], +``` diff --git a/Docs/Documentation/TwoFactor.md b/Docs/Documentation/TwoFactor.md index 0c85cff..3751f78 100644 --- a/Docs/Documentation/TwoFactor.md +++ b/Docs/Documentation/TwoFactor.md @@ -17,6 +17,10 @@ You can disable it by adding this to any config file: To get a list of available providers please visit [RobThree/TwoFactorAuth](https://robthree.github.io/TwoFactorAuth/qr-codes.html) documentation. +The url of each processor (`OneTimePasswordAuthenticator.verifyAction`, `Webauthn2fa.startAction`, +`U2f.startAction`) can be a routing array or a string url. The query params of the login request +are appended to it. + Processors ------------- diff --git a/composer.json b/composer.json index cbe7ad8..d5cbeec 100644 --- a/composer.json +++ b/composer.json @@ -27,27 +27,36 @@ }, "require": { "php": ">=8.2", - "cakephp/cakephp": "^5.3" + "cakephp/authentication": "^3.3", + "cakephp/cakephp": "^5.4" }, "require-dev": { - "phpstan/phpstan": "^2.2.2,<2.2.6", - "phpunit/phpunit": "^10.5 || ^11.1 || ^12.5", - "endroid/qr-code": "^6.0 || ^5.0", - "league/oauth2-facebook": "@stable", - "league/oauth2-instagram": "@stable", - "league/oauth2-google": "@stable", - "league/oauth2-linkedin": "@stable", - "luchianenco/oauth2-amazon": "^1.1", - "google/recaptcha": "@stable", - "robthree/twofactorauth": "^3.0 || ^2.0", - "league/oauth1-client": "^1.7", - "cakephp/authorization": "^3.0", - "cakephp/cakephp-codesniffer": "^5.0", - "cakephp/authentication": "^3.0", - "yubico/u2flib-server": "^1.0", - "firebase/php-jwt": "^6.8" + "cakephp/authorization": "^3.5", + "cakephp/cakephp-codesniffer": "^5.3", + "endroid/qr-code": "^6.0", + "firebase/php-jwt": "^7.0", + "google/recaptcha": "^1.3", + "league/oauth1-client": "^1.11", + "league/oauth2-client": "^2.8", + "league/oauth2-facebook": "^2.2", + "league/oauth2-google": "^4.0 || ^5.0", + "league/oauth2-instagram": "^3.1", + "league/oauth2-linkedin": "^5.1", + "luchianenco/oauth2-amazon": "^1.1 || ^3.0", + "phpstan/phpstan": "^2.3", + "phpunit/phpunit": "^11.5 || ^12.5", + "psalm/phar": "^6.20", + "robthree/twofactorauth": "^3.0.1" }, "suggest": { + "cakephp/authorization": "Required by RbacPolicy, CollectionPolicy and SuperuserPolicy", + "endroid/qr-code": "QR code provider for the one time password authenticator", + "firebase/php-jwt": "Required by OpenIDConnectService", + "google/recaptcha": "Required by ReCaptchaTrait and the reCaptcha check of FormAuthenticator", + "league/oauth1-client": "Required by the Twitter social login (OAuth1Service)", + "league/oauth2-client": "Required by the OAuth2 social login (OAuth2Service), install the provider package you use", + "robthree/twofactorauth": "Required by the one time password (TOTP) two factor authentication", + "stevenmaguire/oauth2-keycloak": "Keycloak social login provider" }, "autoload": { "psr-4": { @@ -68,18 +77,19 @@ "analyse": [ "@stan", "@psalm" - ], + ], "cs-check": "phpcs -n -p --standard=vendor/cakephp/cakephp-codesniffer/CakePHP ./src ./tests", "cs-fix": "phpcbf --standard=vendor/cakephp/cakephp-codesniffer/CakePHP ./src ./tests", "test": "phpunit --stderr", "stan": "vendor/bin/phpstan analyse src/", - "psalm": "php vendor/psalm/phar/psalm.phar --show-info=false src/ ", - "stan-setup": "cp composer.json composer.backup && composer require --dev phpstan/phpstan:^1.9.0 psalm/phar:^5.1.0 && mv composer.backup composer.json", + "psalm": "php vendor/psalm/phar/psalm.phar --show-info=false", "coverage-test": "phpunit --stderr --coverage-clover=clover.xml" }, "config": { "allow-plugins": { "dealerdirect/phpcodesniffer-composer-installer": true - } - } + }, + "sort-packages": true + }, + "prefer-stable": true } diff --git a/config/auth.php b/config/auth.php index 3c170af..49ceb60 100644 --- a/config/auth.php +++ b/config/auth.php @@ -100,26 +100,25 @@ ], ], 'keycloak' => [ - 'service' => 'CakeDC\Auth\Social\Service\OAuth2Service', - 'className' => 'Stevenmaguire\OAuth2\Client\Provider\Keycloak', - 'mapper' => 'CakeDC\Auth\Social\Mapper\Keycloak', - 'rolesMap' => [ - 'CakeDc-Admin' => 'Admin', - 'CakeDc-User' => 'User', - 'CakeDc-Worker' => 'User' - ], - 'authParams' => ['scope' => ['openid','roles']], - 'skipSocialAccountValidation' => true, - 'options' => [ - 'redirectUri' => Router::fullBaseUrl() . '/auth/keycloak', - 'linkSocialUri' => Router::fullBaseUrl() . '/auth/link-social/keycloak', - 'callbackLinkSocialUri' => Router::fullBaseUrl() . '/auth/callback-link-social/keycloak', - ] + 'service' => 'CakeDC\Auth\Social\Service\OAuth2Service', + 'className' => 'Stevenmaguire\OAuth2\Client\Provider\Keycloak', + 'mapper' => 'CakeDC\Auth\Social\Mapper\Keycloak', + 'rolesMap' => [ + 'CakeDc-Admin' => 'admin', + 'CakeDc-User' => 'user', + 'CakeDc-Worker' => 'user', + ], + 'authParams' => ['scope' => ['openid', 'roles']], + 'options' => [ + 'redirectUri' => Router::fullBaseUrl() . '/auth/keycloak', + 'linkSocialUri' => Router::fullBaseUrl() . '/link-social/keycloak', + 'callbackLinkSocialUri' => Router::fullBaseUrl() . '/callback-link-social/keycloak', + ], ], ], 'TwoFactorProcessors' => [ \CakeDC\Auth\Authentication\TwoFactorProcessor\OneTimePasswordProcessor::class, - \CakeDC\Auth\Authentication\TwoFactorProcessor\Webauthn2faProcessor::class + \CakeDC\Auth\Authentication\TwoFactorProcessor\Webauthn2faProcessor::class, ], 'OneTimePasswordAuthenticator' => [ 'checker' => \CakeDC\Auth\Authentication\DefaultOneTimePasswordAuthenticationChecker::class, diff --git a/config/permissions.php b/config/permissions.php index 46d453a..26ae7a9 100644 --- a/config/permissions.php +++ b/config/permissions.php @@ -107,7 +107,7 @@ 'action' => 'resetOneTimePasswordAuthenticator', 'allowed' => [ 'className' => \CakeDC\Auth\Rbac\Rules\OTPRule::class, - 'option' => [] + 'options' => [], ], ], //all roles allowed to Pages/display diff --git a/psalm-baseline.xml b/psalm-baseline.xml new file mode 100644 index 0000000..24c63dc --- /dev/null +++ b/psalm-baseline.xml @@ -0,0 +1,538 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + getU2fAuthenticationChecker()]]> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + getMessage(), + )]]> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + getHeader('Accept')]]> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + $this->getConfig('autoload_config'), + ])]]> + + + + + + + + + + + + + + + + + + + + + + + + + + + $id, + $this->getConfig('ownerForeignKey') => $userId, + ]]]> + + + getParsedBody()]]> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + _mapFields)]]> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + _mapFields['avatar']))]]> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/psalm.xml b/psalm.xml index 8e3d4fd..6f7ce96 100644 --- a/psalm.xml +++ b/psalm.xml @@ -2,6 +2,7 @@ + + @@ -27,10 +30,6 @@ - - - - @@ -70,10 +69,6 @@ - - - - @@ -81,17 +76,8 @@ - - - - - - - - - @@ -109,11 +95,6 @@ - - - - - diff --git a/src/Authentication/TwoFactorProcessor/U2FProcessor.php b/src/Authentication/TwoFactorProcessor/U2FProcessor.php index 77c95fa..23158f6 100644 --- a/src/Authentication/TwoFactorProcessor/U2FProcessor.php +++ b/src/Authentication/TwoFactorProcessor/U2FProcessor.php @@ -98,9 +98,9 @@ public function proceed(ServerRequestInterface $request, ResultInterface $result * Generates 2fa url, if enable. * * @param string $type Processor type. - * @return array|null + * @return array|string|null */ - public function getUrlByType(string $type): ?array + public function getUrlByType(string $type): array|string|null { if ($type == $this->getType()) { return Configure::read('U2f.startAction'); diff --git a/src/Event/SocialLoginListener.php b/src/Event/SocialLoginListener.php deleted file mode 100644 index b426805..0000000 --- a/src/Event/SocialLoginListener.php +++ /dev/null @@ -1,45 +0,0 @@ - - */ - public function implementedEvents(): array - { - return [ - /** - * Event name directly used from CakeDC/Users plugin - * Original source: CakeDC\Users\Plugin::EVENT_SOCIAL_LOGIN_EXISTING_ACCOUNT - * If the constant is changed in the CakeDC/Users plugin, this string must be updated accordingly - */ - 'CakeDC.Users.Social.afterIdentify' => 'changeRole', - ]; - } - - /** - * Szerepkör módosítása Keycloak bejelentkezés esetén - * - * @param \Cake\Event\EventInterface $event Az esemény objektum - * @return \Cake\Datasource\EntityInterface|null - */ - public function changeRole(EventInterface $event) - { - $data = $event->getData('data'); - $userEntity = $event->getData('userEntity'); - if (isset($data['provider']) && $data['provider'] === 'keycloak' && isset($data['roles'])) { - $userEntity->set('role', $data['roles']); - return $userEntity; - } - - return null; - } -} \ No newline at end of file diff --git a/src/Middleware/TwoFactorMiddleware.php b/src/Middleware/TwoFactorMiddleware.php index 5d95cac..188d727 100644 --- a/src/Middleware/TwoFactorMiddleware.php +++ b/src/Middleware/TwoFactorMiddleware.php @@ -57,8 +57,8 @@ public function process(ServerRequestInterface $request, RequestHandlerInterface $url = array_merge($url, [ '?' => $params, ]); - } else { - $url .= '?' . implode('&', array_map(fn ($k, $v) => "$k=$v", array_keys($params), array_values($params))); + } elseif ($params) { + $url .= (str_contains($url, '?') ? '&' : '?') . http_build_query($params); } $url = Router::url($url); diff --git a/src/Rbac/Permissions/AbstractProvider.php b/src/Rbac/Permissions/AbstractProvider.php index 150697f..f7f195d 100644 --- a/src/Rbac/Permissions/AbstractProvider.php +++ b/src/Rbac/Permissions/AbstractProvider.php @@ -14,9 +14,8 @@ namespace CakeDC\Auth\Rbac\Permissions; use Cake\Core\InstanceConfigTrait; -use Cake\Http\ServerRequest; use Cake\Log\LogTrait; -use Cake\Utility\Hash; +use CakeDC\Auth\Rbac\Rules\OTPRule; /** * Class AbstractProvider, handles getting permission from different sources, @@ -100,8 +99,8 @@ public function __construct(array $config = []) 'controller' => 'Users', 'action' => 'resetOneTimePasswordAuthenticator', 'allowed' => [ - 'className' => \CakeDC\Auth\Rbac\Rules\OTPRule::class, - 'option' => [] + 'className' => OTPRule::class, + 'options' => [], ], ], //all roles allowed to Pages/display diff --git a/src/Rbac/Rbac.php b/src/Rbac/Rbac.php index 466d04e..73eb893 100644 --- a/src/Rbac/Rbac.php +++ b/src/Rbac/Rbac.php @@ -222,11 +222,9 @@ protected function _matchPermission(array $permission, array|ArrayAccess $user, $return = (bool)call_user_func($value, $user, $role, $request); } elseif ($value instanceof Rule) { $return = $value->allowed($user, $role, $request); - } elseif (is_array($value) && array_key_exists('className', $value)) { - $rule = RuleRegistry::get($value['className'], $value['options'] ?? []); - if ($rule instanceof Rule) { - $return = (bool)$rule->allowed($user, $role, $request); - } + } elseif ($this->_isRuleConfig($value)) { + $rule = RuleRegistry::get($value['className'], (array)($value['options'] ?? [])); + $return = $rule->allowed($user, $role, $request); } elseif ($key === 'bypassAuth' && $value === true) { $return = true; } elseif ($key === 'allowed') { @@ -262,6 +260,20 @@ protected function _matchPermission(array $permission, array|ArrayAccess $user, return null; } + /** + * Check if the value is a rule config array, `['className' => Rule::class, 'options' => []]` + * + * @param mixed $value Permission value. + * @return bool + */ + protected function _isRuleConfig(mixed $value): bool + { + return is_array($value) && + isset($value['className']) && + is_string($value['className']) && + is_a($value['className'], Rule::class, true); + } + /** * Check if rule matched or '*' present in rule matching anything * diff --git a/src/Rbac/Rules/OTPRule.php b/src/Rbac/Rules/OTPRule.php index 58eadee..cb68f59 100644 --- a/src/Rbac/Rules/OTPRule.php +++ b/src/Rbac/Rules/OTPRule.php @@ -13,24 +13,26 @@ namespace CakeDC\Auth\Rbac\Rules; -use App\Model\Entity\AppGroup; -use Cake\ORM\TableRegistry; +use ArrayAccess; use Cake\Utility\Hash; -use CakeDC\Auth\Rbac\Rules\AbstractRule; use Psr\Http\Message\ServerRequestInterface; +/** + * Allows a user to act on its own record, the user id is the first passed param. + * Used for the reset one time password authenticator action. + */ class OTPRule extends AbstractRule { /** * @inheritDoc */ - public function allowed($user, $role, ServerRequestInterface $request) + public function allowed(array|ArrayAccess $user, string $role, ServerRequestInterface $request): bool { - $userId = \Cake\Utility\Hash::get($request->getAttribute('params'), 'pass.0'); - if (!empty($userId) && !empty($user)) { - return $userId === $user['id']; + $userId = Hash::get((array)$request->getAttribute('params'), 'pass.0'); + if (empty($userId) || empty($user['id'])) { + return false; } - return false; + return (string)$userId === (string)$user['id']; } } diff --git a/src/Social/MapUser.php b/src/Social/MapUser.php index 4ae7cf6..7391e4f 100644 --- a/src/Social/MapUser.php +++ b/src/Social/MapUser.php @@ -15,25 +15,9 @@ use CakeDC\Auth\Social\Service\ServiceInterface; use InvalidArgumentException; -use Cake\Event\EventManager; -use CakeDC\Auth\Event\SocialLoginListener; - class MapUser { - /** - * Constructor - * - * Initializes the MapUser class and registers the SocialLoginListener - * to handle social login events. - */ - public function __construct() - { - - $listener = new SocialLoginListener(); - EventManager::instance()->on($listener); - - } /** * Map social user user data * diff --git a/src/Social/Mapper/Keycloak.php b/src/Social/Mapper/Keycloak.php index eb2bf21..6e29133 100644 --- a/src/Social/Mapper/Keycloak.php +++ b/src/Social/Mapper/Keycloak.php @@ -2,19 +2,27 @@ declare(strict_types=1); /** - * Copyright 2010 - 2019, Cake Development Corporation (https://www.cakedc.com) + * Copyright 2010 - 2026, Cake Development Corporation (https://www.cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2010 - 2019, Cake Development Corporation (https://www.cakedc.com) + * @copyright Copyright 2010 - 2026, Cake Development Corporation (https://www.cakedc.com) * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ - namespace CakeDC\Auth\Social\Mapper; + use Cake\Core\Configure; +use Cake\Utility\Hash; +use UnexpectedValueException; +/** + * Keycloak Mapper + * + * The `roles` field holds the application role mapped from the Keycloak realm roles, + * using the `rolesMap` provider config (`OAuth.providers.keycloak.rolesMap`). + */ class Keycloak extends AbstractMapper { /** @@ -25,67 +33,83 @@ class Keycloak extends AbstractMapper protected array $_mapFields = [ 'first_name' => 'given_name', 'last_name' => 'family_name', + 'full_name' => 'name', 'email' => 'email', 'username' => 'preferred_username', 'id' => 'sub', 'link' => 'website', - 'roles' => 'realm_access', - 'validated' => 'email_verified' + 'roles' => 'realm_access.roles', + 'validated' => 'email_verified', ]; - + /** - * Map Keycloak roles to CakeDC roles + * Map Keycloak realm roles to application roles. The first matching entry wins. * - * @var array + * @var array */ protected array $_rolesMap = [ 'CakeDc-Admin' => 'admin', 'CakeDc-User' => 'user', - 'CakeDc-Worker' => 'user' + 'CakeDc-Worker' => 'user', ]; - + /** * Constructor + * + * @param mixed $mapFields map fields, defaults to `OAuth.providers.keycloak.mapFields` + * @param array|null $rolesMap roles map, defaults to `OAuth.providers.keycloak.rolesMap` */ - public function __construct() + public function __construct(mixed $mapFields = null, ?array $rolesMap = null) { - $configRoleMap = Configure::read('OAuth.providers.keycloak.rolesMap'); - $configMapFields = Configure::read('OAuth.providers.keycloak.mapFields'); - if (!empty($configRoleMap) && is_array($configRoleMap)) { - $this->_rolesMap = $configRoleMap; - } - if (!empty($configMapFields) && is_array($configMapFields)) { - $this->_mapFields = $configMapFields; + $mapFields ??= Configure::read('OAuth.providers.keycloak.mapFields') ?: null; + $rolesMap ??= Configure::read('OAuth.providers.keycloak.rolesMap'); + if (is_array($rolesMap) && $rolesMap) { + $this->_rolesMap = $rolesMap; } + parent::__construct($mapFields); } - function _roles(array $data): string - { // Client Scopes > roles > Mappers > realm roles -> Add to userinfo := Enable - if (is_null($data[$this->_mapFields['roles']])) { - throw new \Exception("No roles in UserInfo token. Set realm roles 'Add to userinfo' field to ON in Client scopes or check the roles field in _mapFields"); + /** + * Get the application role from the Keycloak realm roles + * + * Requires the realm roles mapper of the `roles` client scope to have "Add to userinfo" enabled. + * + * @param mixed $rawData raw data + * @throws \UnexpectedValueException when there are no roles or none of them is mapped + * @return string + */ + protected function _roles(mixed $rawData): string + { + $keycloakRoles = Hash::get($rawData, $this->_mapFields['roles']); + if (!is_array($keycloakRoles)) { + throw new UnexpectedValueException( + 'No roles in Keycloak userinfo. Enable "Add to userinfo" for the realm roles mapper ' . + 'or check the `roles` map field', + ); } - - $keycloakRoles = $data[$this->_mapFields['roles']]['roles']; - - // Ignore case when comparing roles - $mappedRoles = []; - foreach ($keycloakRoles as $keycloakRole) { - foreach (array_keys($this->_rolesMap) as $mapKey) { - if (strcasecmp($keycloakRole, $mapKey) === 0) { - $mappedRoles[] = $mapKey; - break; + + foreach ($this->_rolesMap as $keycloakRole => $role) { + foreach ($keycloakRoles as $userRole) { + if (is_string($userRole) && strcasecmp($userRole, $keycloakRole) === 0) { + return $role; } } } - - if (empty($mappedRoles)) { - throw new \Exception("No mappable role found in Keycloak. Available roles in map: " . implode(', ', array_keys($this->_rolesMap)) . ' / '. implode(', ', ($keycloakRoles))); - } - - $keycloakRole = array_pop($mappedRoles); - $role = $this->_rolesMap[$keycloakRole]; - // Set the cakedc default user role from keycloak roles - Configure::write('Users.Registration.defaultRole', $role); - return $role; + + throw new UnexpectedValueException(sprintf( + 'No mapped role found in Keycloak roles. Mapped roles: %s', + implode(', ', array_keys($this->_rolesMap)), + )); + } + + /** + * Keycloak reports the email verification status + * + * @param mixed $rawData raw data + * @return bool + */ + protected function _validated(mixed $rawData): bool + { + return (bool)Hash::get($rawData, $this->_mapFields['validated']); } } diff --git a/src/Social/Mapper/LinkedInOpenIDConnect.php b/src/Social/Mapper/LinkedInOpenIDConnect.php index cd190ab..3c80a17 100644 --- a/src/Social/Mapper/LinkedInOpenIDConnect.php +++ b/src/Social/Mapper/LinkedInOpenIDConnect.php @@ -13,6 +13,9 @@ namespace CakeDC\Auth\Social\Mapper; +/** + * LinkedIn OpenID Connect Mapper + */ class LinkedInOpenIDConnect extends AbstractMapper { /** @@ -20,7 +23,7 @@ class LinkedInOpenIDConnect extends AbstractMapper * * @var array */ - protected $_mapFields = [ + protected array $_mapFields = [ 'avatar' => 'picture', 'first_name' => 'given_name', 'last_name' => 'family_name', @@ -29,10 +32,13 @@ class LinkedInOpenIDConnect extends AbstractMapper 'id' => 'sub', ]; + /** + * There is no way to retrieve the public profile url from the id token + * + * @return string + */ protected function _link(): string { - // no way to retrieve the public url from the users profile - return 'https://www.linkedin.com'; } } diff --git a/src/Social/Service/OpenIDConnectService.php b/src/Social/Service/OpenIDConnectService.php index f797168..e4844e6 100644 --- a/src/Social/Service/OpenIDConnectService.php +++ b/src/Social/Service/OpenIDConnectService.php @@ -1,31 +1,95 @@ [ 'baseUrl' => 'https://www.linkedin.com/', 'url' => 'https://www.linkedin.com/oauth/.well-known/openid-configuration', + 'issuer' => null, + 'nonce' => true, + 'cache' => null, 'jwk' => [ 'defaultAlgorithm' => 'RS256', ], ], ]; + /** + * @inheritDoc + */ + public function getAuthorizationUrl(ServerRequestInterface $request): string + { + if (!$request instanceof ServerRequest) { + throw new BadMethodCallException('Request must be an instance of ServerRequest'); + } + if (!$this->getConfig('openid.nonce')) { + return parent::getAuthorizationUrl($request); + } + $nonce = bin2hex(random_bytes(16)); + $request->getSession()->write(self::SESSION_NONCE_KEY, $nonce); + $authParams = $this->getConfig('authParams', []); + $this->setConfig('authParams', ['nonce' => $nonce] + $authParams, false); + try { + return parent::getAuthorizationUrl($request); + } finally { + $this->setConfig('authParams', $authParams, false); + } + } + + /** + * Get the user from the validated id token + * + * @param \Psr\Http\Message\ServerRequestInterface $request Request object. + * @throws \Cake\Http\Exception\BadRequestException when state or id token are invalid + * @return array + */ public function getUser(ServerRequestInterface $request): array { if (!$request instanceof ServerRequest) { - throw new \BadMethodCallException('Request must be an instance of ServerRequest'); + throw new BadMethodCallException('Request must be an instance of ServerRequest'); } if (!$this->validate($request)) { throw new BadRequestException('Invalid OAuth2 state'); @@ -40,48 +104,118 @@ public function getUser(ServerRequestInterface $request): array throw new BadRequestException('Missing id_token in response'); } try { - $idTokenDecoded = JWT::decode($idToken, $this->getIdTokenKeys()); - - return ['token' => $token] + (array)$idTokenDecoded; - } catch (\Exception $ex) { + $claims = (array)JWT::decode($idToken, $this->getIdTokenKeys()); + } catch (Exception $ex) { throw new BadRequestException('Invalid id token. ' . $ex->getMessage()); } + $this->validateClaims($request, $claims); + + return ['token' => $token] + $claims; } + /** + * Validates the `iss`, `aud` and `nonce` claims of the id token + * + * @param \Cake\Http\ServerRequest $request Request object. + * @param array $claims Decoded id token claims. + * @throws \Cake\Http\Exception\BadRequestException when a claim is invalid + * @return void + */ + protected function validateClaims(ServerRequest $request, array $claims): void + { + $issuer = $this->getConfig('openid.issuer') ?? ($this->discover()['issuer'] ?? null); + if (!$issuer || ($claims['iss'] ?? null) !== $issuer) { + throw new BadRequestException('Invalid id token. Unexpected issuer'); + } + + $clientId = $this->getConfig('options.clientId'); + $audience = (array)($claims['aud'] ?? []); + if (!$clientId || !in_array($clientId, $audience, true)) { + throw new BadRequestException('Invalid id token. Unexpected audience'); + } + + if ($this->getConfig('openid.nonce')) { + $session = $request->getSession(); + $nonce = $session->read(self::SESSION_NONCE_KEY); + $session->delete(self::SESSION_NONCE_KEY); + if (!is_string($nonce) || !hash_equals($nonce, (string)($claims['nonce'] ?? ''))) { + throw new BadRequestException('Invalid id token. Nonce mismatch'); + } + } + } + + /** + * Get the keys used to verify the id token signature + * + * @return array + */ protected function getIdTokenKeys(): array { $discoverData = $this->discover(); $jwksUri = $discoverData['jwks_uri'] ?? null; if (!$jwksUri) { throw new BadRequestException( - 'No `jwks_uri` in discover data. Unable to retrieve the JWT signature public key' + 'No `jwks_uri` in discover data. Unable to retrieve the JWT signature public key', ); } - if (strpos($jwksUri, $this->getConfig('openid.baseUrl')) !== 0) { + if (!str_starts_with($jwksUri, (string)$this->getConfig('openid.baseUrl'))) { throw new BadRequestException( 'Invalid `jwks_uri` in discover data. It is not pointing to ' . - $this->getConfig('openid.baseUrl') + $this->getConfig('openid.baseUrl'), ); } - $client = $this->getHttpClient(); - $jwksData = $client->get($jwksUri)->getJson(); + $jwksData = $this->fetchJson($jwksUri); if (!$jwksData) { throw new BadRequestException( - 'Unable to retrieve jwks. Not found in the `jwks_uri` contents' + 'Unable to retrieve jwks. Not found in the `jwks_uri` contents', ); } return JWK::parseKeySet($jwksData, $this->getConfig('openid.jwk.defaultAlgorithm')); } + /** + * Get the OpenID discovery document + * + * @return array + */ public function discover(): array { - $openidUrl = $this->getConfig('openid.url'); - $client = $this->getHttpClient(); + return $this->fetchJson($this->getConfig('openid.url')); + } + + /** + * Fetch a json document, using the `openid.cache` cache config when set + * + * @param string $url Url of the document. + * @return array + */ + protected function fetchJson(string $url): array + { + $fetch = fn(): array => (array)$this->getHttpClient()->get($url)->getJson(); + $cacheConfig = $this->getConfig('openid.cache'); + if (!$cacheConfig) { + return $fetch(); + } + + $key = 'cakedc_auth_oidc_' . md5($url); + $data = Cache::read($key, $cacheConfig); + if (is_array($data) && $data) { + return $data; + } + $data = $fetch(); + if ($data) { + Cache::write($key, $data, $cacheConfig); + } - return $client->get($openidUrl)->getJson(); + return $data; } + /** + * Get the http client + * + * @return \Cake\Http\Client + */ protected function getHttpClient(): Client { return new Client(); diff --git a/tests/TestCase/Authenticator/CookieAuthenticatorTest.php b/tests/TestCase/Authenticator/CookieAuthenticatorTest.php index d0c02f7..f12ffd4 100644 --- a/tests/TestCase/Authenticator/CookieAuthenticatorTest.php +++ b/tests/TestCase/Authenticator/CookieAuthenticatorTest.php @@ -51,7 +51,6 @@ public static function dataProviderPersistIdentity() * @param string $field Remember me field. * @param array $post Post data * @param array $session Session data for CookieAuth key - * @dataProvider dataProviderPersistIdentity * @return void */ #[DataProvider('dataProviderPersistIdentity')] diff --git a/tests/TestCase/Authenticator/FormAuthenticatorTest.php b/tests/TestCase/Authenticator/FormAuthenticatorTest.php index 0504e98..7e91a9d 100644 --- a/tests/TestCase/Authenticator/FormAuthenticatorTest.php +++ b/tests/TestCase/Authenticator/FormAuthenticatorTest.php @@ -320,7 +320,7 @@ public function testAuthenticateTokenlessRecaptchaFailsCleanly() $request = ServerRequestFactory::fromGlobals( ['REQUEST_URI' => '/testpath', 'REMOTE_ADDR' => '127.0.0.1'], [], - ['username' => 'marcelo', 'password' => 'password'] + ['username' => 'marcelo', 'password' => 'password'], ); $baseResult = new Result( @@ -329,7 +329,7 @@ public function testAuthenticateTokenlessRecaptchaFailsCleanly() 'username' => 'marcelo', 'role' => 'user', ], - Result::SUCCESS + Result::SUCCESS, ); $BaseAuthenticator->expects($this->once()) ->method('authenticate') diff --git a/tests/TestCase/Middleware/RbacMiddlewareTest.php b/tests/TestCase/Middleware/RbacMiddlewareTest.php index 6cd0904..452a3bb 100644 --- a/tests/TestCase/Middleware/RbacMiddlewareTest.php +++ b/tests/TestCase/Middleware/RbacMiddlewareTest.php @@ -52,9 +52,6 @@ public function tearDown(): void unset($this->rbacMiddleware); } - /** - * @test - */ public function testInvokeForbidden() { $this->expectException(ForbiddenException::class); @@ -72,9 +69,6 @@ public function testInvokeForbidden() $rbacMiddleware->process($request, $handler); } - /** - * @test - */ public function testInvokeForbiddenAjax() { $this->expectException(ForbiddenException::class); @@ -92,9 +86,6 @@ public function testInvokeForbiddenAjax() $rbacMiddleware->process($request, $handler); } - /** - * @test - */ public function testInvokeRedirect() { $request = new ServerRequest(); @@ -117,9 +108,6 @@ public function testInvokeRedirect() $this->assertSame('http://localhost/login', $response->getHeaderLine('Location')); } - /** - * @test - */ public function testInvokeAllowed() { $request = new ServerRequest(); diff --git a/tests/TestCase/Middleware/TwoFactorMiddlewareTest.php b/tests/TestCase/Middleware/TwoFactorMiddlewareTest.php index b50a300..15045ab 100644 --- a/tests/TestCase/Middleware/TwoFactorMiddlewareTest.php +++ b/tests/TestCase/Middleware/TwoFactorMiddlewareTest.php @@ -24,6 +24,7 @@ use CakeDC\Auth\Authentication\AuthenticationService; use CakeDC\Auth\Middleware\TwoFactorMiddleware; use PHPUnit\Framework\Attributes\AllowMockObjectsWithoutExpectations; +use PHPUnit\Framework\Attributes\DataProvider; /** * Class OneTimePasswordAuthenticatorMiddlewareTest @@ -57,7 +58,7 @@ public function tearDown(): void } /** - * @test middleware when dont't need to processed to one time password verify + * Test middleware when dont't need to processed to one time password verify */ public function testInvokeNotNeeded() { @@ -95,7 +96,7 @@ public function testInvokeNotNeeded() } /** - * @test middleware when dont't need to processed to one time password verify + * Test middleware when dont't need to processed to one time password verify */ public function testInvokeNeedVerify() { @@ -146,4 +147,56 @@ public function testInvokeNeedVerify() $this->assertEquals($expected, $actual->getHeader('Location')); $this->assertSame(1, $request->getSession()->read('CookieAuth.remember_me')); } + + /** + * @return array + */ + public static function stringVerifyActionProvider(): array + { + return [ + 'no query' => ['/verify', [], '/verify'], + 'query' => ['/verify', ['redirect' => '/posts/view/1'], '/verify?redirect=%2Fposts%2Fview%2F1'], + 'existing query' => ['/verify?step=2', ['a' => 'b c'], '/verify?step=2&a=b+c'], + 'full url' => ['https://example.com/verify', ['a' => '1'], 'https://example.com/verify?a=1'], + ]; + } + + /** + * Test middleware redirect when the verify action is a string url + * @param string $verifyAction configured verify action + * @param array $query request query params + * @param string $expected expected location + * @return void + */ + #[DataProvider('stringVerifyActionProvider')] + public function testInvokeNeedVerifyStringUrl(string $verifyAction, array $query, string $expected): void + { + $request = ServerRequestFactory::fromGlobals( + ['REQUEST_URI' => '/login'], + $query, + ['username' => 'user-1', 'password' => 'password'], + ); + $handler = $this->getMockBuilder(Runner::class) + ->onlyMethods(['handle']) + ->getMock(); + $handler->expects($this->never()) + ->method('handle'); + Configure::write('OneTimePasswordAuthenticator.verifyAction', $verifyAction); + $service = $this->getMockBuilder(AuthenticationService::class)->setConstructorArgs([ + [ + 'authenticators' => [ + 'Authentication.Session' => [ + 'identifier' => 'Authentication.Password', + ], + ], + ], + ])->onlyMethods(['getResult'])->getMock(); + $service->expects($this->any()) + ->method('getResult') + ->willReturn(new Result(null, AuthenticationService::NEED_TWO_FACTOR_VERIFY)); + + $actual = $this->TwoFactorMiddleware->process($request->withAttribute('authentication', $service), $handler); + + $this->assertSame([$expected], $actual->getHeader('Location')); + } } diff --git a/tests/TestCase/Policy/CollectionPolicyTest.php b/tests/TestCase/Policy/CollectionPolicyTest.php index 31bc8b1..a310cf8 100644 --- a/tests/TestCase/Policy/CollectionPolicyTest.php +++ b/tests/TestCase/Policy/CollectionPolicyTest.php @@ -49,7 +49,6 @@ public static function dataProviderCanAccess() * @param bool $isSuperuser Is this a super user * @param string $rbacBehavior 'never', 'true', or 'false' * @param bool $expected The expected result; - * @dataProvider dataProviderCanAccess * @return void */ #[DataProvider('dataProviderCanAccess')] diff --git a/tests/TestCase/Policy/SuperuserPolicyTest.php b/tests/TestCase/Policy/SuperuserPolicyTest.php index 9e32e0c..a855b59 100644 --- a/tests/TestCase/Policy/SuperuserPolicyTest.php +++ b/tests/TestCase/Policy/SuperuserPolicyTest.php @@ -48,7 +48,6 @@ public static function dataProviderCanAccess() * @param array $userData custom user data for testing. * @param bool $expected The expected result. * @param array $config policy configurations. - * @dataProvider dataProviderCanAccess * @return void */ #[DataProvider('dataProviderCanAccess')] diff --git a/tests/TestCase/Rbac/RbacTest.php b/tests/TestCase/Rbac/RbacTest.php index e685b19..bd014ba 100644 --- a/tests/TestCase/Rbac/RbacTest.php +++ b/tests/TestCase/Rbac/RbacTest.php @@ -16,6 +16,7 @@ use Cake\Http\ServerRequest; use Cake\TestSuite\TestCase; use CakeDC\Auth\Rbac\Rbac; +use CakeDC\Auth\Rbac\Rules\OTPRule; use CakeDC\Auth\Rbac\Rules\Owner; use CakeDC\Auth\Test\App\Auth\Rule\SampleRule; use Exception; @@ -99,8 +100,8 @@ public function setUp(): void 'controller' => 'Users', 'action' => 'resetOneTimePasswordAuthenticator', 'allowed' => [ - 'className' => \CakeDC\Auth\Rbac\Rules\OTPRule::class, - 'option' => [] + 'className' => OTPRule::class, + 'options' => [], ], ], //all roles allowed to Pages/display @@ -129,9 +130,6 @@ public function tearDown(): void unset($this->rbac); } - /** - * @covers \CakeDC\Auth\Rbac\Rbac::__construct - */ public function testConstructGetDefaultPermissions() { $this->rbac = new Rbac(); @@ -139,9 +137,6 @@ public function testConstructGetDefaultPermissions() $this->assertSame($this->defaultPermissions, $result); } - /** - * @covers \CakeDC\Auth\Rbac\Rbac::__construct - */ public function testConstructBadProvider() { $this->expectException(RuntimeException::class); @@ -151,9 +146,6 @@ public function testConstructBadProvider() ]); } - /** - * @covers \CakeDC\Auth\Rbac\Rbac::__construct - */ public function testConstructSetPermissions() { $this->rbac = new Rbac([ @@ -173,9 +165,6 @@ protected function assertConstructorPermissions($instance, $config, $permissions $this->assertEquals($permissions, $resultPermissions); } - /** - * @dataProvider providerAuthorize - */ #[DataProvider('providerAuthorize')] public function testAuthorize($permissions, $user, $requestParams, $expected) { @@ -1198,7 +1187,6 @@ function () { } /** - * @dataProvider badPermissionProvider * @param array $permissions * @param array $user * @param array $requestParams @@ -1367,6 +1355,47 @@ protected function _requestFromArray($params) ->withParam('_ext', $params['_ext'] ?? null); } + /** + * A `['className' => Rule::class, 'options' => []]` value is resolved through the RuleRegistry + * + * @return void + */ + public function testRuleConfig(): void + { + $permissions = [[ + 'controller' => 'Users', + 'action' => 'resetOneTimePasswordAuthenticator', + 'allowed' => ['className' => OTPRule::class, 'options' => []], + ]]; + $this->rbac = new Rbac(['permissions' => $permissions]); + $request = $this->_requestFromArray([ + 'controller' => 'Users', + 'action' => 'resetOneTimePasswordAuthenticator', + ])->withParam('pass', ['1']); + + $this->assertTrue($this->rbac->checkPermissions(['id' => 1, 'role' => 'user'], $request)); + $this->assertFalse($this->rbac->checkPermissions(['id' => 2, 'role' => 'user'], $request)); + } + + /** + * An array with a `className` key that is not a Rule keeps the value matching behavior + * + * @return void + */ + public function testRuleConfigNotARule(): void + { + $permissions = [[ + 'role' => ['className' => 'admin'], + 'controller' => '*', + 'action' => '*', + ]]; + $this->rbac = new Rbac(['permissions' => $permissions]); + $request = $this->_requestFromArray(['controller' => 'Posts', 'action' => 'index']); + + $this->assertTrue($this->rbac->checkPermissions(['id' => 1, 'role' => 'admin'], $request)); + $this->assertFalse($this->rbac->checkPermissions(['id' => 1, 'role' => 'user'], $request)); + } + public function testGetPermissions() { $permissions = ['test']; diff --git a/tests/TestCase/Rbac/Rules/OTPRuleTest.php b/tests/TestCase/Rbac/Rules/OTPRuleTest.php new file mode 100644 index 0000000..caddf86 --- /dev/null +++ b/tests/TestCase/Rbac/Rules/OTPRuleTest.php @@ -0,0 +1,50 @@ + + */ + public static function allowedProvider(): array + { + return [ + 'own uuid' => [['id' => '00000000-0000-0000-0000-000000000001'], ['00000000-0000-0000-0000-000000000001'], true], + 'own integer id' => [['id' => 1], ['1'], true], + 'other user' => [['id' => 1], ['2'], false], + 'no pass' => [['id' => 1], [], false], + 'no user id' => [[], ['1'], false], + ]; + } + + /** + * @param array $user user + * @param array $pass passed params + * @param bool $expected expected result + * @return void + */ + #[DataProvider('allowedProvider')] + public function testAllowed(array $user, array $pass, bool $expected): void + { + $request = (new ServerRequest())->withParam('pass', $pass); + + $this->assertSame($expected, (new OTPRule())->allowed($user, 'user', $request)); + } +} diff --git a/tests/TestCase/Social/Mapper/KeycloakTest.php b/tests/TestCase/Social/Mapper/KeycloakTest.php new file mode 100644 index 0000000..a241b27 --- /dev/null +++ b/tests/TestCase/Social/Mapper/KeycloakTest.php @@ -0,0 +1,126 @@ + new AccessToken([ + 'access_token' => 'test-token', + 'expires' => 1490988496, + ]), + 'sub' => 'f4b8c1a2', + 'preferred_username' => 'test', + 'name' => 'Test User', + 'given_name' => 'Test', + 'family_name' => 'User', + 'email' => 'test@example.com', + 'email_verified' => false, + 'website' => 'https://example.com', + 'realm_access' => ['roles' => $roles], + ]; + } + + /** + * @return void + */ + public function testMap(): void + { + $rawData = $this->rawData(); + $user = (new Keycloak())($rawData); + + $this->assertEquals([ + 'id' => 'f4b8c1a2', + 'username' => 'test', + 'full_name' => 'Test User', + 'first_name' => 'Test', + 'last_name' => 'User', + 'email' => 'test@example.com', + 'avatar' => null, + 'gender' => null, + 'link' => 'https://example.com', + 'bio' => null, + 'locale' => null, + 'validated' => false, + 'roles' => 'user', + 'credentials' => [ + 'token' => 'test-token', + 'secret' => null, + 'expires' => 1490988496, + ], + 'raw' => $rawData, + ], $user); + } + + /** + * The first matching rolesMap entry wins, roles are compared case-insensitive + * + * @return void + */ + public function testRolesMapOrder(): void + { + $user = (new Keycloak())($this->rawData(['cakedc-user', 'CAKEDC-ADMIN'])); + + $this->assertSame('admin', $user['roles']); + } + + /** + * @return void + */ + public function testRolesMapFromConfig(): void + { + Configure::write('OAuth.providers.keycloak.rolesMap', ['manager' => 'superuser']); + $user = (new Keycloak())($this->rawData(['Manager'])); + + $this->assertSame('superuser', $user['roles']); + $this->assertSame('user', (new Keycloak(null, ['CakeDc-User' => 'user']))($this->rawData())['roles']); + } + + /** + * @return void + */ + public function testNoMappedRole(): void + { + $this->expectException(UnexpectedValueException::class); + $this->expectExceptionMessage('No mapped role found in Keycloak roles'); + + (new Keycloak())($this->rawData(['offline_access'])); + } + + /** + * @return void + */ + public function testMissingRoles(): void + { + $rawData = $this->rawData(); + unset($rawData['realm_access']); + + $this->expectException(UnexpectedValueException::class); + $this->expectExceptionMessage('No roles in Keycloak userinfo'); + + (new Keycloak())($rawData); + } +} diff --git a/tests/TestCase/Social/Mapper/LinkedInOpenIDConnectTest.php b/tests/TestCase/Social/Mapper/LinkedInOpenIDConnectTest.php index 5e95926..5afe689 100644 --- a/tests/TestCase/Social/Mapper/LinkedInOpenIDConnectTest.php +++ b/tests/TestCase/Social/Mapper/LinkedInOpenIDConnectTest.php @@ -14,8 +14,8 @@ namespace CakeDC\Auth\Test\TestCase\Social\Mapper; use Cake\TestSuite\TestCase; -use CakeDC\Auth\Social\Mapper\LinkedIn; use CakeDC\Auth\Social\Mapper\LinkedInOpenIDConnect; +use League\OAuth2\Client\Token\AccessToken; class LinkedInOpenIDConnectTest extends TestCase { @@ -31,14 +31,14 @@ public function tearDown(): void public function testMap() { - $token = new \League\OAuth2\Client\Token\AccessToken([ + $token = new AccessToken([ 'access_token' => 'test-token', 'expires' => 1490988496, ]); $rawData = [ 'sub' => '1', 'token' => $token, - 'email' => 'test@gmail.com', + 'email' => 'test@gmail.com', 'given_name' => 'Test', 'family_name' => 'User', 'industry' => 'Computer Software', @@ -49,8 +49,7 @@ public function testMap() 'name' => 'Spain', ], 'picture' => 'https://media.licdn.com/mpr/mprx/test.jpg', - - + 'bio' => 'The best test user in the world.', 'publicProfileUrl' => 'https://www.linkedin.com/in/test', ]; diff --git a/tests/TestCase/Social/Service/OpenIDConnectServiceTest.php b/tests/TestCase/Social/Service/OpenIDConnectServiceTest.php index 14a56d6..e3d9c56 100644 --- a/tests/TestCase/Social/Service/OpenIDConnectServiceTest.php +++ b/tests/TestCase/Social/Service/OpenIDConnectServiceTest.php @@ -1,5 +1,4 @@ Client = $this->getMockBuilder( - \Cake\Http\Client::class + Client::class, )->onlyMethods([ 'get', ])->getMock(); $this->Provider = $this->getMockBuilder( - \League\OAuth2\Client\Provider\LinkedIn::class + LinkedIn::class, )->setConstructorArgs([ [ 'id' => '1', @@ -79,17 +78,21 @@ public function setUp(): void 'lastName' => 'last', ], [], - ])->setMethods([ + ])->onlyMethods([ 'getAccessToken', 'getState', 'getAuthorizationUrl', 'getResourceOwner', ])->getMock(); $config = [ 'service' => OpenIDConnectService::class, 'className' => $this->Provider, - 'mapper' => \CakeDC\Auth\Social\Mapper\LinkedInOpenIDConnect::class, + 'mapper' => LinkedInOpenIDConnect::class, 'authParams' => ['scope' => ['public_profile', 'email', 'user_birthday', 'user_gender', 'user_link']], 'options' => [ 'state' => '__TEST_STATE__', + 'clientId' => '__CLIENT_ID__', + ], + 'openid' => [ + 'issuer' => 'https://www.linkedin.com/oauth', ], 'collaborators' => [], 'signature' => null, @@ -103,7 +106,7 @@ public function setUp(): void ]; $this->Service = $this->getMockBuilder( - \CakeDC\Auth\Social\Service\OpenIDConnectService::class + OpenIDConnectService::class, )->setConstructorArgs([ $config, ])->onlyMethods([ @@ -113,7 +116,7 @@ public function setUp(): void $this->Service->expects($this->any()) ->method('getHttpClient') - ->will($this->returnValue($this->Client)); + ->willReturn($this->Client); //new OpenIDConnectService($config); $this->Request = ServerRequestFactory::fromGlobals(); @@ -139,8 +142,8 @@ public function tearDown(): void public function testConstruct() { $service = new OpenIDConnectService([ - 'className' => \League\OAuth2\Client\Provider\LinkedIn::class, - 'mapper' => \CakeDC\Auth\Social\Mapper\LinkedInOpenIDConnect::class, + 'className' => LinkedIn::class, + 'mapper' => LinkedInOpenIDConnect::class, 'authParams' => ['scope' => ['public_profile', 'email', 'user_birthday', 'user_gender', 'user_link']], 'options' => [], 'collaborators' => [], @@ -168,7 +171,8 @@ public function testGetUserInvalidRequest() 'state' => '__TEST_STATE__', ]); - $this->expectException(BadRequestException::class, 'Invalid OAuth2 state'); + $this->expectException(BadRequestException::class); + $this->expectExceptionMessage('Invalid OAuth2 state'); $this->Service->getUser($this->Request); } @@ -187,7 +191,7 @@ public function testGetUserMisingIdToken() $this->Request->getSession()->write('oauth2state', '__TEST_STATE__'); - $token = new \League\OAuth2\Client\Token\AccessToken([ + $token = new AccessToken([ 'access_token' => 'test-token', 'expires' => 1490988496, ]); @@ -196,11 +200,12 @@ public function testGetUserMisingIdToken() ->method('getAccessToken') ->with( $this->equalTo('authorization_code'), - $this->equalTo(['code' => 'ZPO9972j3092304230']) + $this->equalTo(['code' => 'ZPO9972j3092304230']), ) - ->will($this->returnValue($token)); + ->willReturn($token); - $this->expectException(BadRequestException::class, 'Missing id_token in response'); + $this->expectException(BadRequestException::class); + $this->expectExceptionMessage('Missing id_token in response'); $this->Service->getUser($this->Request); } @@ -219,7 +224,7 @@ public function testGetUserInvalidIdToken() $this->Request->getSession()->write('oauth2state', '__TEST_STATE__'); - $token = new \League\OAuth2\Client\Token\AccessToken([ + $token = new AccessToken([ 'access_token' => 'test-token', 'expires' => 1490988496, 'id_token' => 'invalid-jwt', @@ -229,69 +234,130 @@ public function testGetUserInvalidIdToken() ->method('getAccessToken') ->with( $this->equalTo('authorization_code'), - $this->equalTo(['code' => 'ZPO9972j3092304230']) + $this->equalTo(['code' => 'ZPO9972j3092304230']), ) - ->will($this->returnValue($token)); + ->willReturn($token); - $this->expectException(BadRequestException::class, 'Invalid id token. Key may not be empty'); + $this->expectException(BadRequestException::class); + $this->expectExceptionMessage('Invalid id token. Key may not be empty'); $this->Service->getUser($this->Request); } /** - * Test GetUser + * Build a signed id token and prepare the request, provider and key set mocks * - * @return void + * @param array $payload id token claims + * @return \League\OAuth2\Client\Token\AccessToken */ - public function testGetUser() + protected function prepareIdToken(array $payload): AccessToken { $this->Request = $this->Request->withQueryParams([ 'code' => 'ZPO9972j3092304230', 'state' => '__TEST_STATE__', ]); - $this->Request->getSession()->write('oauth2state', '__TEST_STATE__'); + $this->Request->getSession()->write(OpenIDConnectService::SESSION_NONCE_KEY, '__NONCE__'); - $key = 'example_key'; + $key = 'example_key_with_at_least_32_bytes!'; $alg = 'HS256'; - $payload = [ - 'iat' => 1490988496, - 'iss' => 'https://www.linkedin.com/', - ]; $kid = 'd929668a-bab1-4c69-9598-4373149723ff'; - $jwt = JWT::encode($payload, $key, $alg, $kid); - - $token = new \League\OAuth2\Client\Token\AccessToken([ + $token = new AccessToken([ 'access_token' => 'test-token', 'expires' => 1490988496, - 'id_token' => $jwt, + 'id_token' => JWT::encode($payload, $key, $alg, $kid), ]); $this->Provider->expects($this->once()) ->method('getAccessToken') ->with( $this->equalTo('authorization_code'), - $this->equalTo(['code' => 'ZPO9972j3092304230']) + $this->equalTo(['code' => 'ZPO9972j3092304230']), ) - ->will($this->returnValue($token)); - - $jwksData = [ - $kid => new Key($key, $alg), - ]; - + ->willReturn($token); $this->Service->expects($this->once()) ->method('getIdTokenKeys') - ->will($this->returnValue($jwksData)); + ->willReturn([$kid => new Key($key, $alg)]); - $actual = $this->Service->getUser($this->Request); + return $token; + } - $expected = [ - 'token' => $token, + /** + * Test GetUser + * + * @return void + */ + public function testGetUser() + { + $payload = [ 'iat' => 1490988496, - 'iss' => 'https://www.linkedin.com/', + 'iss' => 'https://www.linkedin.com/oauth', + 'aud' => '__CLIENT_ID__', + 'nonce' => '__NONCE__', ]; + $token = $this->prepareIdToken($payload); - $this->assertEquals($expected, $actual); + $actual = $this->Service->getUser($this->Request); + + $this->assertEquals(['token' => $token] + $payload, $actual); + $this->assertNull($this->Request->getSession()->read(OpenIDConnectService::SESSION_NONCE_KEY)); + } + + /** + * @return array + */ + public static function invalidClaimsProvider(): array + { + $valid = [ + 'iss' => 'https://www.linkedin.com/oauth', + 'aud' => '__CLIENT_ID__', + 'nonce' => '__NONCE__', + ]; + + return [ + 'wrong issuer' => [['iss' => 'https://evil.example.com'] + $valid, 'Unexpected issuer'], + 'missing issuer' => [array_diff_key($valid, ['iss' => true]), 'Unexpected issuer'], + 'wrong audience' => [['aud' => 'other-client'] + $valid, 'Unexpected audience'], + 'missing audience' => [array_diff_key($valid, ['aud' => true]), 'Unexpected audience'], + 'wrong nonce' => [['nonce' => 'other'] + $valid, 'Nonce mismatch'], + 'missing nonce' => [array_diff_key($valid, ['nonce' => true]), 'Nonce mismatch'], + ]; + } + + /** + * Test GetUser with invalid id token claims + * + * @param array $payload id token claims + * @param string $message expected error + * @return void + */ + #[DataProvider('invalidClaimsProvider')] + public function testGetUserInvalidClaims(array $payload, string $message): void + { + $this->prepareIdToken($payload); + + $this->expectException(BadRequestException::class); + $this->expectExceptionMessage($message); + + $this->Service->getUser($this->Request); + } + + /** + * Test the authorization url carries a nonce stored in session + * + * @return void + */ + public function testGetAuthorizationUrlNonce(): void + { + $this->Provider->expects($this->once()) + ->method('getAuthorizationUrl') + ->with($this->callback(fn(array $params): bool => !empty($params['nonce']) && + $params['nonce'] === $this->Request->getSession()->read(OpenIDConnectService::SESSION_NONCE_KEY) && + $params['scope'] === ['public_profile', 'email', 'user_birthday', 'user_gender', 'user_link'])) + ->willReturn('http://example.com/auth'); + + $this->assertSame('http://example.com/auth', $this->Service->getAuthorizationUrl($this->Request)); + $this->assertArrayNotHasKey('nonce', $this->Service->getConfig('authParams')); } /** @@ -302,14 +368,34 @@ public function testGetUser() public function testDiscover() { $arrayTest = ['test' => 'test']; - $response = new \Cake\Http\Client\Response([], json_encode($arrayTest)); + $response = new Response([], json_encode($arrayTest)); $this->Client->expects($this->once()) ->method('get') - ->will($this->returnValue($response)); + ->willReturn($response); $actual = $this->Service->discover(); $this->assertEquals($arrayTest, $actual); } + + /** + * Test discover uses the configured cache + * + * @return void + */ + public function testDiscoverCached(): void + { + Cache::setConfig('_oidc_test_', ['className' => 'Array']); + $this->Service->setConfig('openid.cache', '_oidc_test_'); + $arrayTest = ['issuer' => 'https://www.linkedin.com/oauth']; + + $this->Client->expects($this->once()) + ->method('get') + ->willReturn(new Response([], json_encode($arrayTest))); + + $this->assertEquals($arrayTest, $this->Service->discover()); + $this->assertEquals($arrayTest, $this->Service->discover()); + Cache::drop('_oidc_test_'); + } } diff --git a/tests/TestCase/Traits/IsAuthorizedTraitTest.php b/tests/TestCase/Traits/IsAuthorizedTraitTest.php index 5c0f8d0..d1ec6c6 100644 --- a/tests/TestCase/Traits/IsAuthorizedTraitTest.php +++ b/tests/TestCase/Traits/IsAuthorizedTraitTest.php @@ -81,7 +81,6 @@ public function testIsAuthorizedEmpty() * * @param mixed $url The url to test. * @param bool $authorize Is authorized? - * @dataProvider dataProviderIsAuthorized * @return void */ #[DataProvider('dataProviderIsAuthorized')] From 8bfb49282e1e1cff928a298a6b0090991dadfd34 Mon Sep 17 00:00:00 2001 From: Adam Rusinowski Date: Fri, 6 Nov 2026 16:58:11 +0100 Subject: [PATCH 25/35] fix: address code review findings, add missing tests - Rbac: an `allowed` or `bypassAuth` rule config whose className is not a Rule throws instead of allowing every logged in user. - OIDC: fetch the key set again when a token uses an unknown key id, fetch the discovery document once per instance, check response status, log decode errors and return a generic message, clear error without firebase/php-jwt. New tests verify RS256 tokens against a served key set. - Keycloak: no default roles map, case-sensitive role names. - LinkedIn OIDC: map `validated` from the `email_verified` claim. - Routing: use the CakePHP 5 `{provider}` placeholder, `/:provider` never matched. - SuperuserPolicy: read the role of entity identities in the `Auth.Authorization.checked` event. - OneTimeTokenAuthenticator: only join token arrays that are a list of strings. - Tests for OneTimeTokenAuthenticator, SuperuserPolicy events, OneTimePasswordAuthenticatorComponent configuration errors and plugin routes. --- Docs/Documentation/Social.md | 15 +- src/AuthPlugin.php | 2 +- .../OneTimeTokenAuthenticator.php | 6 +- src/Plugin.php | 2 +- src/Policy/SuperuserPolicy.php | 2 +- src/Rbac/Rbac.php | 32 +- src/Social/Mapper/Keycloak.php | 21 +- src/Social/Mapper/LinkedInOpenIDConnect.php | 14 + src/Social/Service/OpenIDConnectService.php | 74 +++- .../OneTimeTokenAuthenticatorTest.php | 115 ++++++ ...TimePasswordAuthenticatorComponentTest.php | 36 ++ .../Middleware/TwoFactorMiddlewareTest.php | 1 + tests/TestCase/PluginTest.php | 117 ++++++ tests/TestCase/Policy/SuperuserPolicyTest.php | 86 ++++ tests/TestCase/Rbac/RbacTest.php | 38 ++ tests/TestCase/Social/Mapper/KeycloakTest.php | 36 +- .../Mapper/LinkedInOpenIDConnectTest.php | 20 + .../Service/OpenIDConnectServiceTest.php | 384 +++++++++++++++++- 18 files changed, 961 insertions(+), 40 deletions(-) create mode 100644 tests/TestCase/Authenticator/OneTimeTokenAuthenticatorTest.php create mode 100644 tests/TestCase/PluginTest.php diff --git a/Docs/Documentation/Social.md b/Docs/Documentation/Social.md index 6dfbb79..3fbca13 100644 --- a/Docs/Documentation/Social.md +++ b/Docs/Documentation/Social.md @@ -159,12 +159,17 @@ Add the Keycloak provider configuration to your `config/users.php` file: The `CakeDC\Auth\Social\Mapper\Keycloak` mapper reads the realm roles from `realm_access.roles` and maps them to an application role using the `rolesMap` provider configuration. The keys are -Keycloak roles (compared case-insensitive), the values are application roles. The first entry of -`rolesMap` the user has wins, so list the most privileged roles first. The mapped role is -returned in the `roles` field of the mapped user. +Keycloak roles (compared case-sensitive, as in Keycloak), the values are application roles. The +first entry of `rolesMap` the user has wins, so list the most privileged roles first. The mapped +role is returned in the `roles` field of the mapped user. -The login fails with an `UnexpectedValueException` when the userinfo has no roles or none of the -user roles is in `rolesMap`. +Without a `rolesMap` the `roles` field is `null` and no role is required. When a `rolesMap` is set, +the login fails with an `UnexpectedValueException` when the userinfo has no roles or none of the +user roles is in `rolesMap`, so only users with a mapped role can log in. + +The mapper reads `OAuth.providers.keycloak.rolesMap` and `OAuth.providers.keycloak.mapFields`. When +the provider uses another key, pass a mapper instance instead of the class name: +`'mapper' => new \CakeDC\Auth\Social\Mapper\Keycloak(null, ['MyRealm-Admin' => 'admin'])`. The mapper does not change the user role by itself. Use an event listener in your application to apply it, see below. diff --git a/src/AuthPlugin.php b/src/AuthPlugin.php index 761a5ec..38e34fa 100644 --- a/src/AuthPlugin.php +++ b/src/AuthPlugin.php @@ -35,7 +35,7 @@ public function routes(RouteBuilder $routes): void if (is_array($oauthPath)) { $routes->scope('/auth', function ($routes) use ($oauthPath): void { $routes->connect( - '/:provider', + '/{provider}', $oauthPath, ['provider' => implode('|', array_keys(Configure::read('OAuth.providers')))], ); diff --git a/src/Authenticator/OneTimeTokenAuthenticator.php b/src/Authenticator/OneTimeTokenAuthenticator.php index 21c842a..dcf5f45 100644 --- a/src/Authenticator/OneTimeTokenAuthenticator.php +++ b/src/Authenticator/OneTimeTokenAuthenticator.php @@ -20,11 +20,13 @@ public function authenticate(ServerRequestInterface $request): ResultInterface { /** @var \Cake\Http\ServerRequest $request */ $token = $request->getQuery('token') ?: $request->getData('token'); + // The CakeDC/Users token form posts one input per character, `token[0]`, `token[1]`... if (is_array($token)) { - $token = join($token); + $isStringList = array_filter($token, 'is_string') === $token; + $token = $isStringList ? implode('', $token) : null; } - if (!$token) { + if (!is_string($token) || $token === '') { return new Result(null, Result::FAILURE_CREDENTIALS_MISSING); } diff --git a/src/Plugin.php b/src/Plugin.php index 8210531..59a2c96 100644 --- a/src/Plugin.php +++ b/src/Plugin.php @@ -32,7 +32,7 @@ public function routes(RouteBuilder $routes): void if (is_array($oauthPath)) { $routes->scope('/auth', function ($routes) use ($oauthPath): void { $routes->connect( - '/:provider', + '/{provider}', $oauthPath, ['provider' => implode('|', array_keys(Configure::read('OAuth.providers')))], ); diff --git a/src/Policy/SuperuserPolicy.php b/src/Policy/SuperuserPolicy.php index 0598ac7..ddfab1d 100644 --- a/src/Policy/SuperuserPolicy.php +++ b/src/Policy/SuperuserPolicy.php @@ -65,7 +65,7 @@ public function canAccess(?IdentityInterface $identity, ServerRequestInterface $ $emitEvents = Configure::read('CakeDC/Auth.emitEvents', false); if ($allowed && $emitEvents) { - $role = is_array($user) ? ($user['role'] ?? null) : null; + $role = $user['role'] ?? null; EventManager::instance()->dispatch(new Event('Auth.Authorization.checked', $this, [ 'allowed' => true, 'policy' => static::class, diff --git a/src/Rbac/Rbac.php b/src/Rbac/Rbac.php index 73eb893..ee6f7e0 100644 --- a/src/Rbac/Rbac.php +++ b/src/Rbac/Rbac.php @@ -25,6 +25,7 @@ use CakeDC\Auth\Rbac\Permissions\ConfigProvider; use CakeDC\Auth\Rbac\Rules\Rule; use CakeDC\Auth\Rbac\Rules\RuleRegistry; +use InvalidArgumentException; use Psr\Http\Message\ServerRequestInterface; use Psr\Log\LogLevel; use RuntimeException; @@ -222,9 +223,11 @@ protected function _matchPermission(array $permission, array|ArrayAccess $user, $return = (bool)call_user_func($value, $user, $role, $request); } elseif ($value instanceof Rule) { $return = $value->allowed($user, $role, $request); - } elseif ($this->_isRuleConfig($value)) { - $rule = RuleRegistry::get($value['className'], (array)($value['options'] ?? [])); - $return = $rule->allowed($user, $role, $request); + } elseif ( + $this->_isRuleConfig($value) || + (in_array($key, ['allowed', 'bypassAuth'], true) && is_array($value) && isset($value['className'])) + ) { + $return = $this->_ruleFromConfig($value)->allowed($user, $role, $request); } elseif ($key === 'bypassAuth' && $value === true) { $return = true; } elseif ($key === 'allowed') { @@ -274,6 +277,29 @@ protected function _isRuleConfig(mixed $value): bool is_a($value['className'], Rule::class, true); } + /** + * Get the rule instance for a rule config array + * + * An `allowed` or `bypassAuth` array with a `className` key is always a rule config, a class that + * does not exist or is not a Rule throws instead of evaluating the array as a truthy value. + * + * @param array $config Rule config, `['className' => Rule::class, 'options' => []]`. + * @throws \InvalidArgumentException when `className` is not a Rule class + * @return \CakeDC\Auth\Rbac\Rules\Rule + */ + protected function _ruleFromConfig(array $config): Rule + { + if (!$this->_isRuleConfig($config)) { + throw new InvalidArgumentException(sprintf( + 'Permission rule `%s` is not a class implementing %s', + is_string($config['className']) ? $config['className'] : get_debug_type($config['className']), + Rule::class, + )); + } + + return RuleRegistry::get($config['className'], (array)($config['options'] ?? [])); + } + /** * Check if rule matched or '*' present in rule matching anything * diff --git a/src/Social/Mapper/Keycloak.php b/src/Social/Mapper/Keycloak.php index 6e29133..6c350d4 100644 --- a/src/Social/Mapper/Keycloak.php +++ b/src/Social/Mapper/Keycloak.php @@ -21,7 +21,8 @@ * Keycloak Mapper * * The `roles` field holds the application role mapped from the Keycloak realm roles, - * using the `rolesMap` provider config (`OAuth.providers.keycloak.rolesMap`). + * using the `rolesMap` provider config (`OAuth.providers.keycloak.rolesMap`). Without a + * roles map the `roles` field is null. */ class Keycloak extends AbstractMapper { @@ -47,11 +48,7 @@ class Keycloak extends AbstractMapper * * @var array */ - protected array $_rolesMap = [ - 'CakeDc-Admin' => 'admin', - 'CakeDc-User' => 'user', - 'CakeDc-Worker' => 'user', - ]; + protected array $_rolesMap = []; /** * Constructor @@ -73,13 +70,17 @@ public function __construct(mixed $mapFields = null, ?array $rolesMap = null) * Get the application role from the Keycloak realm roles * * Requires the realm roles mapper of the `roles` client scope to have "Add to userinfo" enabled. + * Role names are case-sensitive, as in Keycloak. * * @param mixed $rawData raw data - * @throws \UnexpectedValueException when there are no roles or none of them is mapped - * @return string + * @throws \UnexpectedValueException when a roles map is set and there are no roles or none of them is mapped + * @return string|null The mapped role, null when no roles map is set */ - protected function _roles(mixed $rawData): string + protected function _roles(mixed $rawData): ?string { + if (!$this->_rolesMap) { + return null; + } $keycloakRoles = Hash::get($rawData, $this->_mapFields['roles']); if (!is_array($keycloakRoles)) { throw new UnexpectedValueException( @@ -90,7 +91,7 @@ protected function _roles(mixed $rawData): string foreach ($this->_rolesMap as $keycloakRole => $role) { foreach ($keycloakRoles as $userRole) { - if (is_string($userRole) && strcasecmp($userRole, $keycloakRole) === 0) { + if ($userRole === $keycloakRole) { return $role; } } diff --git a/src/Social/Mapper/LinkedInOpenIDConnect.php b/src/Social/Mapper/LinkedInOpenIDConnect.php index 3c80a17..2eacf3e 100644 --- a/src/Social/Mapper/LinkedInOpenIDConnect.php +++ b/src/Social/Mapper/LinkedInOpenIDConnect.php @@ -13,6 +13,8 @@ namespace CakeDC\Auth\Social\Mapper; +use Cake\Utility\Hash; + /** * LinkedIn OpenID Connect Mapper */ @@ -30,8 +32,20 @@ class LinkedInOpenIDConnect extends AbstractMapper 'email' => 'email', 'link' => 'link', 'id' => 'sub', + 'validated' => 'email_verified', ]; + /** + * The id token reports the email verification status + * + * @param mixed $rawData raw data + * @return bool + */ + protected function _validated(mixed $rawData): bool + { + return (bool)Hash::get($rawData, $this->_mapFields['validated']); + } + /** * There is no way to retrieve the public profile url from the id token * diff --git a/src/Social/Service/OpenIDConnectService.php b/src/Social/Service/OpenIDConnectService.php index e4844e6..2329bb0 100644 --- a/src/Social/Service/OpenIDConnectService.php +++ b/src/Social/Service/OpenIDConnectService.php @@ -18,13 +18,19 @@ use Cake\Http\Client; use Cake\Http\Exception\BadRequestException; use Cake\Http\ServerRequest; +use Cake\Log\LogTrait; use Exception; use Firebase\JWT\JWK; use Firebase\JWT\JWT; use Psr\Http\Message\ServerRequestInterface; +use Psr\Log\LogLevel; +use RuntimeException; +use UnexpectedValueException; class OpenIDConnectService extends OAuth2Service { + use LogTrait; + /** * Session key used to store the nonce sent in the authorization request * @@ -32,6 +38,13 @@ class OpenIDConnectService extends OAuth2Service */ public const SESSION_NONCE_KEY = 'oidcnonce'; + /** + * Discovery document, fetched once per instance + * + * @var array|null + */ + protected ?array $discoveryDocument = null; + /** * Default configuration. `openid` defaults target LinkedIn, override them per provider. * @@ -103,10 +116,15 @@ public function getUser(ServerRequestInterface $request): array if (!$idToken) { throw new BadRequestException('Missing id_token in response'); } + if (!class_exists(JWT::class)) { + throw new RuntimeException('OpenIDConnectService requires the firebase/php-jwt package'); + } try { - $claims = (array)JWT::decode($idToken, $this->getIdTokenKeys()); + $claims = $this->decodeIdToken($idToken); } catch (Exception $ex) { - throw new BadRequestException('Invalid id token. ' . $ex->getMessage()); + $this->log('Invalid OpenID Connect id token: ' . $ex->getMessage(), LogLevel::WARNING); + + throw new BadRequestException('Invalid id token'); } $this->validateClaims($request, $claims); @@ -144,12 +162,35 @@ protected function validateClaims(ServerRequest $request, array $claims): void } } + /** + * Decode the id token and verify its signature + * + * When the token is signed with a key that is not in the cached key set, the provider may have + * rotated its keys, so the key set is fetched again once, bypassing the cache. + * + * @param string $idToken Encoded id token. + * @return array + */ + protected function decodeIdToken(string $idToken): array + { + try { + return (array)JWT::decode($idToken, $this->getIdTokenKeys()); + } catch (UnexpectedValueException $ex) { + if (!$this->getConfig('openid.cache') || !str_contains($ex->getMessage(), '"kid" invalid')) { + throw $ex; + } + + return (array)JWT::decode($idToken, $this->getIdTokenKeys(true)); + } + } + /** * Get the keys used to verify the id token signature * + * @param bool $refresh Fetch the key set again instead of reading it from the cache. * @return array */ - protected function getIdTokenKeys(): array + protected function getIdTokenKeys(bool $refresh = false): array { $discoverData = $this->discover(); $jwksUri = $discoverData['jwks_uri'] ?? null; @@ -164,7 +205,7 @@ protected function getIdTokenKeys(): array $this->getConfig('openid.baseUrl'), ); } - $jwksData = $this->fetchJson($jwksUri); + $jwksData = $this->fetchJson($jwksUri, $refresh); if (!$jwksData) { throw new BadRequestException( 'Unable to retrieve jwks. Not found in the `jwks_uri` contents', @@ -175,31 +216,44 @@ protected function getIdTokenKeys(): array } /** - * Get the OpenID discovery document + * Get the OpenID discovery document, fetched once per service instance * * @return array */ public function discover(): array { - return $this->fetchJson($this->getConfig('openid.url')); + return $this->discoveryDocument ??= $this->fetchJson($this->getConfig('openid.url')); } /** * Fetch a json document, using the `openid.cache` cache config when set * * @param string $url Url of the document. - * @return array + * @param bool $refresh Ignore the cached document and fetch it again. + * @return array The document, empty when the request failed. */ - protected function fetchJson(string $url): array + protected function fetchJson(string $url, bool $refresh = false): array { - $fetch = fn(): array => (array)$this->getHttpClient()->get($url)->getJson(); + $fetch = function () use ($url): array { + $response = $this->getHttpClient()->get($url); + if (!$response->isOk()) { + $this->log( + sprintf('OpenID Connect request to %s failed with status %s', $url, $response->getStatusCode()), + LogLevel::WARNING, + ); + + return []; + } + + return (array)$response->getJson(); + }; $cacheConfig = $this->getConfig('openid.cache'); if (!$cacheConfig) { return $fetch(); } $key = 'cakedc_auth_oidc_' . md5($url); - $data = Cache::read($key, $cacheConfig); + $data = $refresh ? null : Cache::read($key, $cacheConfig); if (is_array($data) && $data) { return $data; } diff --git a/tests/TestCase/Authenticator/OneTimeTokenAuthenticatorTest.php b/tests/TestCase/Authenticator/OneTimeTokenAuthenticatorTest.php new file mode 100644 index 0000000..5713f13 --- /dev/null +++ b/tests/TestCase/Authenticator/OneTimeTokenAuthenticatorTest.php @@ -0,0 +1,115 @@ + + */ + public static array $receivedTokens = []; + + /** + * @var \CakeDC\Auth\Authenticator\OneTimeTokenAuthenticator + */ + protected OneTimeTokenAuthenticator $Authenticator; + + /** + * @return void + */ + public function setUp(): void + { + parent::setUp(); + static::$receivedTokens = []; + $table = new class (['alias' => 'TokenUsers', 'table' => 'users']) extends Table { + /** + * @param string $token one time token + * @return \Cake\ORM\Entity|null + */ + public function loginWithToken(string $token): ?Entity + { + OneTimeTokenAuthenticatorTest::$receivedTokens[] = $token; + + return $token === 'valid-token' ? new Entity(['id' => 1, 'username' => 'user-1']) : null; + } + }; + $this->getTableLocator()->set('TokenUsers', $table); + Configure::write('Users.table', 'TokenUsers'); + $this->Authenticator = new OneTimeTokenAuthenticator(new IdentifierCollection()); + } + + /** + * @return array}> + */ + public static function authenticateProvider(): array + { + return [ + 'valid query token' => [['token' => 'valid-token'], [], Result::SUCCESS, ['valid-token']], + 'valid post token' => [[], ['token' => 'valid-token'], Result::SUCCESS, ['valid-token']], + 'query token wins' => [ + ['token' => 'invalid-token'], + ['token' => 'valid-token'], + Result::FAILURE_CREDENTIALS_MISSING, + ['invalid-token'], + ], + 'invalid token' => [['token' => 'invalid-token'], [], Result::FAILURE_CREDENTIALS_MISSING, ['invalid-token']], + 'per character inputs are joined' => [ + [], + ['token' => ['v', 'a', 'l', 'i', 'd', '-', 't', 'o', 'k', 'e', 'n']], + Result::SUCCESS, + ['valid-token'], + ], + 'nested array token' => [['token' => ['valid-', ['token']]], [], Result::FAILURE_CREDENTIALS_MISSING, []], + 'no token' => [[], [], Result::FAILURE_CREDENTIALS_MISSING, []], + 'empty token' => [['token' => ''], ['token' => ''], Result::FAILURE_CREDENTIALS_MISSING, []], + ]; + } + + /** + * @param array $query query params + * @param array $data post data + * @param string $status expected result status + * @param array $lookups tokens passed to the users table + * @return void + */ + #[DataProvider('authenticateProvider')] + public function testAuthenticate(array $query, array $data, string $status, array $lookups): void + { + $request = (new ServerRequest(['url' => '/login'])) + ->withQueryParams($query) + ->withParsedBody($data); + + $result = $this->Authenticator->authenticate($request); + + $this->assertSame($status, $result->getStatus()); + $this->assertSame($lookups, static::$receivedTokens); + if ($status === Result::SUCCESS) { + $this->assertSame('user-1', $result->getData()['username']); + } else { + $this->assertNull($result->getData()); + } + } +} diff --git a/tests/TestCase/Controller/Component/OneTimePasswordAuthenticatorComponentTest.php b/tests/TestCase/Controller/Component/OneTimePasswordAuthenticatorComponentTest.php index 0f0990b..8ed0368 100644 --- a/tests/TestCase/Controller/Component/OneTimePasswordAuthenticatorComponentTest.php +++ b/tests/TestCase/Controller/Component/OneTimePasswordAuthenticatorComponentTest.php @@ -22,6 +22,7 @@ use Cake\Utility\Security; use CakeDC\Auth\Controller\Component\OneTimePasswordAuthenticatorComponent; use PHPUnit\Framework\MockObject\MockObject; +use RuntimeException; class OneTimePasswordAuthenticatorComponentTest extends TestCase { @@ -133,4 +134,39 @@ public function testVerifyCode() $verified = $this->Controller->OneTimePasswordAuthenticator->verifyCode($secret, $verificationCode); $this->assertTrue($verified); } + + /** + * Test a configuration error is reported with the package hint and the original error + * + * @return void + */ + public function testInitializeConfigurationError(): void + { + Configure::write('OneTimePasswordAuthenticator.digits', 'not-a-number'); + + try { + new OneTimePasswordAuthenticatorComponent($this->Registry); + $this->fail('RuntimeException was not thrown'); + } catch (RuntimeException $ex) { + $this->assertStringContainsString('An error has occurred configuring OneTimePasswordAuthenticator', $ex->getMessage()); + $this->assertStringContainsString('robthree/twofactorauth', $ex->getMessage()); + $this->assertNotNull($ex->getPrevious()); + $this->assertStringContainsString($ex->getPrevious()->getMessage(), $ex->getMessage()); + } + } + + /** + * Test the authenticator is not created when the one time password login is disabled + * + * @return void + */ + public function testInitializeLoginDisabled(): void + { + Configure::write('OneTimePasswordAuthenticator.login', false); + Configure::write('OneTimePasswordAuthenticator.digits', 'not-a-number'); + + $component = new OneTimePasswordAuthenticatorComponent($this->Registry); + + $this->assertFalse(isset($component->tfa)); + } } diff --git a/tests/TestCase/Middleware/TwoFactorMiddlewareTest.php b/tests/TestCase/Middleware/TwoFactorMiddlewareTest.php index 15045ab..b879208 100644 --- a/tests/TestCase/Middleware/TwoFactorMiddlewareTest.php +++ b/tests/TestCase/Middleware/TwoFactorMiddlewareTest.php @@ -163,6 +163,7 @@ public static function stringVerifyActionProvider(): array /** * Test middleware redirect when the verify action is a string url + * * @param string $verifyAction configured verify action * @param array $query request query params * @param string $expected expected location diff --git a/tests/TestCase/PluginTest.php b/tests/TestCase/PluginTest.php new file mode 100644 index 0000000..e7d7456 --- /dev/null +++ b/tests/TestCase/PluginTest.php @@ -0,0 +1,117 @@ + 'CakeDC/Users', + 'controller' => 'Users', + 'action' => 'socialLogin', + 'prefix' => null, + ]); + Configure::write('OAuth.providers', ['facebook' => [], 'keycloak' => []]); + } + + /** + * @return array}> + */ + public static function pluginProvider(): array + { + return [ + 'AuthPlugin' => [AuthPlugin::class], + 'Plugin' => [Plugin::class], + ]; + } + + /** + * Load the plugin routes + * + * @param class-string<\Cake\Core\BasePlugin> $pluginClass plugin class + * @return void + */ + protected function connectPluginRoutes(string $pluginClass): void + { + /** @var \Cake\Core\BasePlugin $plugin */ + $plugin = new $pluginClass(); + $this->assertInstanceOf(BasePlugin::class, $plugin); + $plugin->routes(Router::createRouteBuilder('/')); + } + + /** + * Test the social login route accepts the configured providers + * + * @param class-string<\Cake\Core\BasePlugin> $pluginClass plugin class + * @return void + */ + #[DataProvider('pluginProvider')] + public function testSocialLoginRoute(string $pluginClass): void + { + $this->connectPluginRoutes($pluginClass); + + $params = Router::parseRequest(new ServerRequest(['url' => '/auth/keycloak'])); + + $this->assertSame('CakeDC/Users', $params['plugin']); + $this->assertSame('Users', $params['controller']); + $this->assertSame('socialLogin', $params['action']); + $this->assertSame('keycloak', $params['provider']); + } + + /** + * Test the social login route rejects providers that are not configured + * + * @param class-string<\Cake\Core\BasePlugin> $pluginClass plugin class + * @return void + */ + #[DataProvider('pluginProvider')] + public function testSocialLoginRouteUnknownProvider(string $pluginClass): void + { + $this->connectPluginRoutes($pluginClass); + + $this->expectException(MissingRouteException::class); + Router::parseRequest(new ServerRequest(['url' => '/auth/unknown'])); + } + + /** + * Test no route is connected without an `OAuth.path` array + * + * @param class-string<\Cake\Core\BasePlugin> $pluginClass plugin class + * @return void + */ + #[DataProvider('pluginProvider')] + public function testNoSocialLoginRouteWithoutPath(string $pluginClass): void + { + Configure::write('OAuth.path', null); + $this->connectPluginRoutes($pluginClass); + + $this->assertSame([], Router::routes()); + } +} diff --git a/tests/TestCase/Policy/SuperuserPolicyTest.php b/tests/TestCase/Policy/SuperuserPolicyTest.php index a855b59..e6ccf0a 100644 --- a/tests/TestCase/Policy/SuperuserPolicyTest.php +++ b/tests/TestCase/Policy/SuperuserPolicyTest.php @@ -15,6 +15,9 @@ use Authorization\AuthorizationServiceInterface; use Authorization\IdentityDecorator; +use Cake\Core\Configure; +use Cake\Event\EventInterface; +use Cake\Event\EventManager; use Cake\Http\ServerRequestFactory; use Cake\ORM\Entity; use Cake\TestSuite\TestCase; @@ -65,4 +68,87 @@ public function testCanAccess($userData, $expected, $config = []) $actual = $policy->canAccess($request->getAttribute('identity'), $request); $this->assertSame($expected, $actual); } + + /** + * @return array + */ + public static function checkedEventProvider(): array + { + return [ + 'superuser entity, events enabled' => [true, true, true], + 'superuser array, events enabled' => [false, true, true], + 'superuser, events disabled' => [true, false, false], + ]; + } + + /** + * Test the `Auth.Authorization.checked` event for superusers + * + * @param bool $entity identity data is an entity + * @param bool $emitEvents `CakeDC/Auth.emitEvents` value + * @param bool $dispatched event expected + * @return void + */ + #[DataProvider('checkedEventProvider')] + public function testCheckedEvent(bool $entity, bool $emitEvents, bool $dispatched): void + { + Configure::write('CakeDC/Auth.emitEvents', $emitEvents); + $events = []; + $listener = function (EventInterface $event) use (&$events): void { + $events[] = $event; + }; + EventManager::instance()->on('Auth.Authorization.checked', $listener); + $userData = ['id' => 1, 'role' => 'admin', 'is_superuser' => true]; + $user = $entity ? new Entity($userData) : $userData; + $identity = new IdentityDecorator($this->createStub(AuthorizationServiceInterface::class), $user); + $request = ServerRequestFactory::fromGlobals(); + + try { + $this->assertTrue((new SuperuserPolicy())->canAccess($identity, $request)); + } finally { + EventManager::instance()->off('Auth.Authorization.checked', $listener); + } + + if (!$dispatched) { + $this->assertSame([], $events); + + return; + } + $this->assertCount(1, $events); + $this->assertSame([ + 'allowed' => true, + 'policy' => SuperuserPolicy::class, + 'role' => 'admin', + 'user' => $user, + 'request' => $request, + 'permission' => null, + 'reason' => 'SuperuserPolicy allowed', + ], $events[0]->getData()); + } + + /** + * Test no event is dispatched when the user is not a superuser + * + * @return void + */ + public function testCheckedEventNotSuperuser(): void + { + Configure::write('CakeDC/Auth.emitEvents', true); + $events = []; + $listener = function (EventInterface $event) use (&$events): void { + $events[] = $event; + }; + EventManager::instance()->on('Auth.Authorization.checked', $listener); + $identity = new IdentityDecorator( + $this->createStub(AuthorizationServiceInterface::class), + new Entity(['id' => 1, 'is_superuser' => false]), + ); + + try { + $this->assertFalse((new SuperuserPolicy())->canAccess($identity, ServerRequestFactory::fromGlobals())); + } finally { + EventManager::instance()->off('Auth.Authorization.checked', $listener); + } + $this->assertSame([], $events); + } } diff --git a/tests/TestCase/Rbac/RbacTest.php b/tests/TestCase/Rbac/RbacTest.php index bd014ba..36f78f2 100644 --- a/tests/TestCase/Rbac/RbacTest.php +++ b/tests/TestCase/Rbac/RbacTest.php @@ -20,10 +20,12 @@ use CakeDC\Auth\Rbac\Rules\Owner; use CakeDC\Auth\Test\App\Auth\Rule\SampleRule; use Exception; +use InvalidArgumentException; use PHPUnit\Framework\Attributes\DataProvider; use Psr\Log\LogLevel; use ReflectionClass; use RuntimeException; +use stdClass; class RbacTest extends TestCase { @@ -1396,6 +1398,42 @@ public function testRuleConfigNotARule(): void $this->assertFalse($this->rbac->checkPermissions(['id' => 1, 'role' => 'user'], $request)); } + /** + * An `allowed` or `bypassAuth` rule config with a class that is not a Rule must not allow access + * + * @return void + */ + #[DataProvider('ruleConfigInvalidClassProvider')] + public function testRuleConfigInvalidClass(string $key, mixed $className): void + { + $permissions = [[ + 'controller' => 'Users', + 'action' => 'resetOneTimePasswordAuthenticator', + $key => ['className' => $className], + ]]; + $this->rbac = new Rbac(['permissions' => $permissions]); + $request = $this->_requestFromArray([ + 'controller' => 'Users', + 'action' => 'resetOneTimePasswordAuthenticator', + ]); + + $this->expectException(InvalidArgumentException::class); + $this->rbac->checkPermissions(['id' => 1, 'role' => 'user'], $request); + } + + /** + * @return array + */ + public static function ruleConfigInvalidClassProvider(): array + { + return [ + 'missing class' => ['allowed', 'App\Rbac\MissingRule'], + 'not a rule' => ['allowed', stdClass::class], + 'not a string' => ['allowed', 123], + 'bypassAuth' => ['bypassAuth', stdClass::class], + ]; + } + public function testGetPermissions() { $permissions = ['test']; diff --git a/tests/TestCase/Social/Mapper/KeycloakTest.php b/tests/TestCase/Social/Mapper/KeycloakTest.php index a241b27..81ec8d0 100644 --- a/tests/TestCase/Social/Mapper/KeycloakTest.php +++ b/tests/TestCase/Social/Mapper/KeycloakTest.php @@ -21,6 +21,18 @@ class KeycloakTest extends TestCase { + /** + * @return void + */ + public function setUp(): void + { + parent::setUp(); + Configure::write('OAuth.providers.keycloak.rolesMap', [ + 'CakeDc-Admin' => 'admin', + 'CakeDc-User' => 'user', + ]); + } + /** * @param array $roles realm roles * @return array @@ -76,15 +88,31 @@ public function testMap(): void } /** - * The first matching rolesMap entry wins, roles are compared case-insensitive + * The first matching rolesMap entry wins, roles are compared case-sensitive * * @return void */ public function testRolesMapOrder(): void { - $user = (new Keycloak())($this->rawData(['cakedc-user', 'CAKEDC-ADMIN'])); - + $user = (new Keycloak())($this->rawData(['CakeDc-User', 'CakeDc-Admin'])); $this->assertSame('admin', $user['roles']); + + $user = (new Keycloak())($this->rawData(['cakedc-admin', 'CakeDc-User'])); + $this->assertSame('user', $user['roles']); + } + + /** + * Without a roles map the role is not mapped and the login is not blocked + * + * @return void + */ + public function testNoRolesMap(): void + { + Configure::delete('OAuth.providers.keycloak.rolesMap'); + $rawData = $this->rawData(['offline_access']); + unset($rawData['realm_access']); + + $this->assertNull((new Keycloak())($rawData)['roles']); } /** @@ -92,7 +120,7 @@ public function testRolesMapOrder(): void */ public function testRolesMapFromConfig(): void { - Configure::write('OAuth.providers.keycloak.rolesMap', ['manager' => 'superuser']); + Configure::write('OAuth.providers.keycloak.rolesMap', ['Manager' => 'superuser']); $user = (new Keycloak())($this->rawData(['Manager'])); $this->assertSame('superuser', $user['roles']); diff --git a/tests/TestCase/Social/Mapper/LinkedInOpenIDConnectTest.php b/tests/TestCase/Social/Mapper/LinkedInOpenIDConnectTest.php index 5afe689..6eb74bd 100644 --- a/tests/TestCase/Social/Mapper/LinkedInOpenIDConnectTest.php +++ b/tests/TestCase/Social/Mapper/LinkedInOpenIDConnectTest.php @@ -39,6 +39,7 @@ public function testMap() 'sub' => '1', 'token' => $token, 'email' => 'test@gmail.com', + 'email_verified' => true, 'given_name' => 'Test', 'family_name' => 'User', 'industry' => 'Computer Software', @@ -77,4 +78,23 @@ public function testMap() 'raw' => $rawData, ], $user); } + + /** + * An unverified email is not validated + * + * @return void + */ + public function testMapEmailNotVerified(): void + { + $rawData = [ + 'sub' => '1', + 'token' => new AccessToken(['access_token' => 'test-token']), + 'email' => 'test@gmail.com', + 'email_verified' => false, + ]; + + $this->assertFalse((new LinkedInOpenIDConnect())($rawData)['validated']); + unset($rawData['email_verified']); + $this->assertFalse((new LinkedInOpenIDConnect())($rawData)['validated']); + } } diff --git a/tests/TestCase/Social/Service/OpenIDConnectServiceTest.php b/tests/TestCase/Social/Service/OpenIDConnectServiceTest.php index e3d9c56..8f9eee9 100644 --- a/tests/TestCase/Social/Service/OpenIDConnectServiceTest.php +++ b/tests/TestCase/Social/Service/OpenIDConnectServiceTest.php @@ -18,6 +18,7 @@ use Cake\Http\Client\Response; use Cake\Http\Exception\BadRequestException; use Cake\Http\ServerRequestFactory; +use Cake\Log\Log; use Cake\TestSuite\TestCase; use CakeDC\Auth\Social\Mapper\LinkedInOpenIDConnect; use CakeDC\Auth\Social\Service\OpenIDConnectService; @@ -239,7 +240,7 @@ public function testGetUserInvalidIdToken() ->willReturn($token); $this->expectException(BadRequestException::class); - $this->expectExceptionMessage('Invalid id token. Key may not be empty'); + $this->expectExceptionMessage('Invalid id token'); $this->Service->getUser($this->Request); } @@ -368,7 +369,7 @@ public function testGetAuthorizationUrlNonce(): void public function testDiscover() { $arrayTest = ['test' => 'test']; - $response = new Response([], json_encode($arrayTest)); + $response = new Response(['HTTP/1.1 200 OK'], json_encode($arrayTest)); $this->Client->expects($this->once()) ->method('get') @@ -392,10 +393,387 @@ public function testDiscoverCached(): void $this->Client->expects($this->once()) ->method('get') - ->willReturn(new Response([], json_encode($arrayTest))); + ->willReturn(new Response(['HTTP/1.1 200 OK'], json_encode($arrayTest))); $this->assertEquals($arrayTest, $this->Service->discover()); $this->assertEquals($arrayTest, $this->Service->discover()); + + $service = $this->getMockBuilder(OpenIDConnectService::class) + ->setConstructorArgs([$this->Service->getConfig()]) + ->onlyMethods(['getHttpClient']) + ->getMock(); + $service->expects($this->never())->method('getHttpClient'); + $this->assertEquals($arrayTest, $service->discover()); Cache::drop('_oidc_test_'); } + + /** + * Test discover returns an empty document when the request fails + * + * @return void + */ + public function testDiscoverFailedRequest(): void + { + $this->Client->expects($this->once()) + ->method('get') + ->willReturn(new Response(['HTTP/1.1 500 Internal Server Error'], json_encode(['issuer' => 'x']))); + + $this->assertSame([], $this->Service->discover()); + } + + /** + * Test the key set is fetched again, bypassing the cache, when the token key id is unknown + * + * @return void + */ + public function testGetUserKeyRotation(): void + { + $this->Service->setConfig('openid.cache', '_oidc_test_'); + $this->Request = $this->Request->withQueryParams([ + 'code' => 'ZPO9972j3092304230', + 'state' => '__TEST_STATE__', + ]); + $this->Request->getSession()->write('oauth2state', '__TEST_STATE__'); + $this->Request->getSession()->write(OpenIDConnectService::SESSION_NONCE_KEY, '__NONCE__'); + + $key = 'example_key_with_at_least_32_bytes!'; + $payload = [ + 'iss' => 'https://www.linkedin.com/oauth', + 'aud' => '__CLIENT_ID__', + 'nonce' => '__NONCE__', + 'sub' => 'user-id', + ]; + $token = new AccessToken([ + 'access_token' => 'test-token', + 'expires' => 1490988496, + 'id_token' => JWT::encode($payload, $key, 'HS256', 'new-kid'), + ]); + $this->Provider->expects($this->once()) + ->method('getAccessToken') + ->willReturn($token); + $refreshes = []; + $this->Service->expects($this->exactly(2)) + ->method('getIdTokenKeys') + ->willReturnCallback(function (bool $refresh = false) use ($key, &$refreshes): array { + $refreshes[] = $refresh; + + return [$refresh ? 'new-kid' : 'old-kid' => new Key($key, 'HS256')]; + }); + + $user = $this->Service->getUser($this->Request); + + $this->assertSame([false, true], $refreshes); + $this->assertSame('user-id', $user['sub']); + } + + /** + * Jwks uri served by the mocked http client + * + * @var string + */ + protected const JWKS_URI = 'https://www.linkedin.com/oauth/openid/jwks'; + + /** + * Generate an RSA key pair + * + * @param string $kid key id + * @return array{private: \OpenSSLAsymmetricKey, jwk: array} + */ + protected function rsaKey(string $kid): array + { + $key = openssl_pkey_new(['private_key_bits' => 2048, 'private_key_type' => OPENSSL_KEYTYPE_RSA]); + $details = openssl_pkey_get_details($key); + $encode = fn(string $value): string => rtrim(strtr(base64_encode($value), '+/', '-_'), '='); + + return [ + 'private' => $key, + 'jwk' => [ + 'kty' => 'RSA', + 'alg' => 'RS256', + 'use' => 'sig', + 'kid' => $kid, + 'n' => $encode($details['rsa']['n']), + 'e' => $encode($details['rsa']['e']), + ], + ]; + } + + /** + * Service that only mocks the http client, so the key set is fetched and parsed + * + * @param array $responses responses by url + * @param array $requested urls requested, filled by the mocked client + * @return \CakeDC\Auth\Social\Service\OpenIDConnectService + */ + protected function serviceWithHttp(array $responses, array &$requested = []): OpenIDConnectService + { + $this->Client->expects($this->any()) + ->method('get') + ->willReturnCallback(function (string $url) use ($responses, &$requested): Response { + $requested[] = $url; + + return $responses[$url] ?? new Response(['HTTP/1.1 404 Not Found'], ''); + }); + $service = $this->getMockBuilder(OpenIDConnectService::class) + ->setConstructorArgs([$this->Service->getConfig()]) + ->onlyMethods(['getHttpClient']) + ->getMock(); + $service->expects($this->any()) + ->method('getHttpClient') + ->willReturn($this->Client); + + return $service; + } + + /** + * Json response + * + * @param array $data body + * @return \Cake\Http\Client\Response + */ + protected function jsonResponse(array $data): Response + { + return new Response(['HTTP/1.1 200 OK', 'Content-Type: application/json'], json_encode($data)); + } + + /** + * Discovery and key set responses + * + * @param array $keys jwk keys + * @param string $jwksUri jwks uri in the discovery document + * @return array + */ + protected function oidcResponses(array $keys, string $jwksUri = self::JWKS_URI): array + { + return [ + 'https://www.linkedin.com/oauth/.well-known/openid-configuration' => $this->jsonResponse([ + 'issuer' => 'https://www.linkedin.com/oauth', + 'jwks_uri' => $jwksUri, + ]), + self::JWKS_URI => $this->jsonResponse(['keys' => $keys]), + ]; + } + + /** + * Prepare the callback request and the provider token response for an id token + * + * @param string $idToken encoded id token + * @return void + */ + protected function prepareCallback(string $idToken): void + { + $this->Request = $this->Request->withQueryParams([ + 'code' => 'ZPO9972j3092304230', + 'state' => '__TEST_STATE__', + ]); + $this->Request->getSession()->write('oauth2state', '__TEST_STATE__'); + $this->Request->getSession()->write(OpenIDConnectService::SESSION_NONCE_KEY, '__NONCE__'); + $this->Provider->expects($this->once()) + ->method('getAccessToken') + ->willReturn(new AccessToken([ + 'access_token' => 'test-token', + 'id_token' => $idToken, + ])); + } + + /** + * Valid id token claims + * + * @return array + */ + protected function validClaims(): array + { + return [ + 'iss' => 'https://www.linkedin.com/oauth', + 'aud' => '__CLIENT_ID__', + 'nonce' => '__NONCE__', + 'sub' => 'user-id', + 'exp' => time() + 300, + ]; + } + + /** + * Assert getUser fails with the generic error and logs the reason + * + * @param \CakeDC\Auth\Social\Service\OpenIDConnectService $service service + * @param string $logged expected text in the log + * @return void + */ + protected function assertInvalidIdToken(OpenIDConnectService $service, string $logged): void + { + Log::setConfig('_oidc_test_', ['className' => 'Array', 'levels' => ['warning']]); + try { + $service->getUser($this->Request); + $this->fail('BadRequestException was not thrown'); + } catch (BadRequestException $ex) { + $this->assertSame('Invalid id token', $ex->getMessage()); + $this->assertStringContainsString($logged, implode("\n", Log::engine('_oidc_test_')->read())); + } finally { + Log::drop('_oidc_test_'); + } + } + + /** + * Test a RS256 id token is verified with the key set from the discovery document + * + * @return void + */ + public function testGetUserRs256(): void + { + $key = $this->rsaKey('key-1'); + $requested = []; + $service = $this->serviceWithHttp($this->oidcResponses([$key['jwk']]), $requested); + $this->prepareCallback(JWT::encode($this->validClaims(), $key['private'], 'RS256', 'key-1')); + + $user = $service->getUser($this->Request); + + $this->assertSame('user-id', $user['sub']); + $this->assertSame([ + 'https://www.linkedin.com/oauth/.well-known/openid-configuration', + self::JWKS_URI, + ], $requested); + } + + /** + * @return array + */ + public static function rejectedIdTokenProvider(): array + { + return [ + 'signed with another key' => ['otherKey', 'Signature verification failed'], + 'algorithm mismatch' => ['hs256', 'Incorrect key for this algorithm'], + 'unsigned' => ['none', 'Algorithm not supported'], + 'unknown key id without cache' => ['unknownKid', '"kid" invalid'], + 'expired' => ['expired', 'Expired token'], + ]; + } + + /** + * Test id tokens that must be rejected by the signature verification + * + * @param string $case token case + * @param string $logged expected logged reason + * @return void + */ + #[DataProvider('rejectedIdTokenProvider')] + public function testGetUserRejectedIdToken(string $case, string $logged): void + { + $key = $this->rsaKey('key-1'); + $requested = []; + $service = $this->serviceWithHttp($this->oidcResponses([$key['jwk']]), $requested); + $claims = $this->validClaims(); + $encode = fn(array $data): string => rtrim(strtr(base64_encode(json_encode($data)), '+/', '-_'), '='); + $idToken = match ($case) { + 'otherKey' => JWT::encode($claims, $this->rsaKey('key-1')['private'], 'RS256', 'key-1'), + 'hs256' => JWT::encode($claims, str_repeat('s', 32), 'HS256', 'key-1'), + 'none' => $encode(['alg' => 'none', 'typ' => 'JWT', 'kid' => 'key-1']) . '.' . $encode($claims) . '.', + 'unknownKid' => JWT::encode($claims, $key['private'], 'RS256', 'key-2'), + 'expired' => JWT::encode(['exp' => time() - 300] + $claims, $key['private'], 'RS256', 'key-1'), + }; + $this->prepareCallback($idToken); + + $this->assertInvalidIdToken($service, $logged); + $this->assertCount(2, $requested, 'The key set is not fetched again without cache'); + } + + /** + * Test the key set is not fetched from a jwks uri outside of `openid.baseUrl` + * + * @return void + */ + public function testGetUserForeignJwksUri(): void + { + $key = $this->rsaKey('key-1'); + $requested = []; + $service = $this->serviceWithHttp( + $this->oidcResponses([$key['jwk']], 'https://evil.example.com/jwks'), + $requested, + ); + $this->prepareCallback(JWT::encode($this->validClaims(), $key['private'], 'RS256', 'key-1')); + + $this->assertInvalidIdToken($service, 'Invalid `jwks_uri` in discover data'); + $this->assertNotContains('https://evil.example.com/jwks', $requested); + } + + /** + * Test a discovery document without `jwks_uri` + * + * @return void + */ + public function testGetUserMissingJwksUri(): void + { + $key = $this->rsaKey('key-1'); + $responses = $this->oidcResponses([$key['jwk']]); + $responses['https://www.linkedin.com/oauth/.well-known/openid-configuration'] = $this->jsonResponse([ + 'issuer' => 'https://www.linkedin.com/oauth', + ]); + $service = $this->serviceWithHttp($responses); + $this->prepareCallback(JWT::encode($this->validClaims(), $key['private'], 'RS256', 'key-1')); + + $this->assertInvalidIdToken($service, 'No `jwks_uri` in discover data'); + } + + /** + * Test a key set request that fails + * + * @return void + */ + public function testGetUserJwksRequestFailed(): void + { + $key = $this->rsaKey('key-1'); + $responses = $this->oidcResponses([$key['jwk']]); + $responses[self::JWKS_URI] = new Response(['HTTP/1.1 503 Service Unavailable'], ''); + $service = $this->serviceWithHttp($responses); + $this->prepareCallback(JWT::encode($this->validClaims(), $key['private'], 'RS256', 'key-1')); + + $this->assertInvalidIdToken($service, 'Unable to retrieve jwks'); + } + + /** + * Test a cached key set without the token key id is fetched again + * + * @return void + */ + public function testGetUserCachedKeySetRotation(): void + { + Cache::setConfig('_oidc_test_', ['className' => 'Array']); + $oldKey = $this->rsaKey('old-key'); + $newKey = $this->rsaKey('new-key'); + Cache::write('cakedc_auth_oidc_' . md5(self::JWKS_URI), ['keys' => [$oldKey['jwk']]], '_oidc_test_'); + $requested = []; + $service = $this->serviceWithHttp($this->oidcResponses([$oldKey['jwk'], $newKey['jwk']]), $requested); + $service->setConfig('openid.cache', '_oidc_test_'); + $this->prepareCallback(JWT::encode($this->validClaims(), $newKey['private'], 'RS256', 'new-key')); + + try { + $user = $service->getUser($this->Request); + $cached = Cache::read('cakedc_auth_oidc_' . md5(self::JWKS_URI), '_oidc_test_'); + } finally { + Cache::drop('_oidc_test_'); + } + + $this->assertSame('user-id', $user['sub']); + $this->assertSame([ + 'https://www.linkedin.com/oauth/.well-known/openid-configuration', + self::JWKS_URI, + ], $requested); + $this->assertSame(['old-key', 'new-key'], array_column($cached['keys'], 'kid')); + } + + /** + * Test the authorization url has no nonce when `openid.nonce` is disabled + * + * @return void + */ + public function testGetAuthorizationUrlWithoutNonce(): void + { + $this->Service->setConfig('openid.nonce', false); + $this->Provider->expects($this->once()) + ->method('getAuthorizationUrl') + ->with($this->callback(fn(array $params): bool => !isset($params['nonce']))) + ->willReturn('http://example.com/auth'); + + $this->assertSame('http://example.com/auth', $this->Service->getAuthorizationUrl($this->Request)); + $this->assertNull($this->Request->getSession()->read(OpenIDConnectService::SESSION_NONCE_KEY)); + } } From 99dab391d633e921f6ed6addebeb205e4a974591 Mon Sep 17 00:00:00 2001 From: Adam Rusinowski Date: Fri, 6 Nov 2026 16:58:12 +0100 Subject: [PATCH 26/35] ci: make static analysis blocking, test lowest dependencies, update actions - cs-check, psalm and phpstan fail the build (no more continue-on-error) - add a PHP 8.2 lowest dependencies job, the prefer-lowest matrix entry was never set - comment out the Codecov upload: uploads failed without a token since 2024 - replace the deprecated ::set-output cache steps with ramsey/composer-install - actions/checkout v5, ubuntu-24.04 for both jobs, no coverage driver - read-only token permissions, cancel superseded runs, skip pull_request runs for branches of this repository (already tested by push) - only install the PHP extensions the tests use --- .github/workflows/ci.yml | 104 +++++++++++++++++---------------------- 1 file changed, 44 insertions(+), 60 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 60e5714..268a052 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -5,29 +5,43 @@ on: push: pull_request: +permissions: + contents: read + +concurrency: + group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: true + jobs: testsuite: + # Pull requests from branches of this repository are already tested by the push event + if: github.event_name == 'push' || github.event.pull_request.head.repo.full_name != github.repository runs-on: ubuntu-24.04 strategy: fail-fast: false matrix: php-version: ['8.2', '8.3', '8.4', '8.5'] db-type: [sqlite, mysql, pgsql] - prefer-lowest: [''] + dependencies: [highest] + include: + - php-version: '8.2' + db-type: sqlite + dependencies: lowest + + name: PHP ${{ matrix.php-version }}, ${{ matrix.db-type }}, ${{ matrix.dependencies }} dependencies steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v5 with: persist-credentials: false - - name: Setup MySQL latest + - name: Setup MySQL if: matrix.db-type == 'mysql' run: | sudo service mysql start mysql -h 127.0.0.1 -u root -proot -e 'CREATE DATABASE cakephp;' - - - name: Setup PostgreSQL latest + - name: Setup PostgreSQL if: matrix.db-type == 'pgsql' run: docker run --rm --name=postgres -e POSTGRES_PASSWORD=postgres -e POSTGRES_DB=cakephp -p 5432:5432 -d postgres @@ -35,31 +49,14 @@ jobs: uses: shivammathur/setup-php@v2 with: php-version: ${{ matrix.php-version }} - extensions: mbstring, intl, apcu, memcached, redis, pdo_${{ matrix.db-type }}, ${{ matrix.db-type }} - ini-values: apc.enable_cli = 1 - coverage: pcov - - - name: Get composer cache directory - id: composer-cache - run: echo "::set-output name=dir::$(composer config cache-files-dir)" - - - name: Get date part for cache key - id: key-date - run: echo "::set-output name=date::$(date +'%Y-%m')" - - - name: Cache composer dependencies - uses: actions/cache@v4 - with: - path: ${{ steps.composer-cache.outputs.dir }} - key: ${{ runner.os }}-composer-${{ steps.key-date.outputs.date }}-${{ hashFiles('composer.json') }}-${{ matrix.prefer-lowest }} + extensions: mbstring, intl, pdo_${{ matrix.db-type }} + coverage: none - name: Composer install - run: | - if ${{ matrix.prefer-lowest == 'prefer-lowest' }}; then - composer update --prefer-lowest --prefer-stable - else - composer update - fi + uses: ramsey/composer-install@v3 + with: + dependency-versions: ${{ matrix.dependencies }} + composer-options: --prefer-stable - name: Setup problem matchers for PHPUnit if: matrix.php-version == '8.2' && matrix.db-type == 'mysql' @@ -70,58 +67,45 @@ jobs: if [[ ${{ matrix.db-type }} == 'sqlite' ]]; then export DB_URL='sqlite:///:memory:'; fi if [[ ${{ matrix.db-type }} == 'mysql' ]]; then export DB_URL='mysql://root:root@127.0.0.1/cakephp?encoding=utf8'; fi if [[ ${{ matrix.db-type }} == 'pgsql' ]]; then export DB_URL='postgres://postgres:postgres@127.0.0.1/postgres'; fi - if [[ ${{ matrix.php-version }} == '8.2' ]]; then - export CODECOVERAGE=1 && vendor/bin/phpunit --coverage-clover=coverage.xml - else - vendor/bin/phpunit - fi - - - name: Submit code coverage - if: matrix.php-version == '8.2' - uses: codecov/codecov-action@v1 + vendor/bin/phpunit + + # Codecov is disabled: uploads need a CODECOV_TOKEN secret. To enable it, set `coverage: pcov` + # for PHP 8.2, run `vendor/bin/phpunit --coverage-clover=coverage.xml` and uncomment this step. + # - name: Submit code coverage + # if: matrix.php-version == '8.2' && matrix.db-type == 'sqlite' && matrix.dependencies == 'highest' + # uses: codecov/codecov-action@v5 + # with: + # token: ${{ secrets.CODECOV_TOKEN }} + # files: coverage.xml + # fail_ci_if_error: true cs-stan: name: Coding Standard & Static Analysis - runs-on: ubuntu-22.04 + if: github.event_name == 'push' || github.event.pull_request.head.repo.full_name != github.repository + runs-on: ubuntu-24.04 steps: - - uses: actions/checkout@v2 + - uses: actions/checkout@v5 + with: + persist-credentials: false - name: Setup PHP uses: shivammathur/setup-php@v2 with: php-version: '8.2' - extensions: mbstring, intl, apcu, memcached, redis - tools: cs2pr + extensions: mbstring, intl coverage: none - - name: Get composer cache directory - id: composer-cache - run: echo "::set-output name=dir::$(composer config cache-files-dir)" - - - name: Get date part for cache key - id: key-date - run: echo "::set-output name=date::$(date +'%Y-%m')" - - - name: Cache composer dependencies - uses: actions/cache@v4 - with: - path: ${{ steps.composer-cache.outputs.dir }} - key: ${{ runner.os }}-composer-${{ steps.key-date.outputs.date }}-${{ hashFiles('composer.json') }}-${{ matrix.prefer-lowest }} - - - name: composer install - run: composer update + - name: Composer install + uses: ramsey/composer-install@v3 - name: Run PHP CodeSniffer run: composer cs-check - continue-on-error: true - name: Run psalm if: success() || failure() run: composer psalm - continue-on-error: true - name: Run phpstan if: success() || failure() run: composer stan - continue-on-error: true From ab2c02e2f83ca66b05944431b08f34d631b6882e Mon Sep 17 00:00:00 2001 From: Adam Rusinowski Date: Fri, 6 Nov 2026 17:12:17 +0100 Subject: [PATCH 27/35] refactor: deprecate Plugin in favor of AuthPlugin `Plugin` and `AuthPlugin` held the same route code. `Plugin` now extends `AuthPlugin` and is deprecated, CakePHP 5.3 expects the `AuthPlugin` name. --- psalm-baseline.xml | 5 ----- src/Plugin.php | 23 ++--------------------- 2 files changed, 2 insertions(+), 26 deletions(-) diff --git a/psalm-baseline.xml b/psalm-baseline.xml index 24c63dc..72d9925 100644 --- a/psalm-baseline.xml +++ b/psalm-baseline.xml @@ -1,10 +1,5 @@ - - - - - diff --git a/src/Plugin.php b/src/Plugin.php index 59a2c96..ee8b6dd 100644 --- a/src/Plugin.php +++ b/src/Plugin.php @@ -12,31 +12,12 @@ */ namespace CakeDC\Auth; -use Cake\Core\BasePlugin; -use Cake\Core\Configure; -use Cake\Routing\RouteBuilder; - /** * Class Plugin * * @package CakeDC\Auth + * @deprecated 11.1.0 Use \CakeDC\Auth\AuthPlugin instead, the plugin class name expected since CakePHP 5.3. */ -class Plugin extends BasePlugin +class Plugin extends AuthPlugin { - /** - * @inheritDoc - */ - public function routes(RouteBuilder $routes): void - { - $oauthPath = Configure::read('OAuth.path'); - if (is_array($oauthPath)) { - $routes->scope('/auth', function ($routes) use ($oauthPath): void { - $routes->connect( - '/{provider}', - $oauthPath, - ['provider' => implode('|', array_keys(Configure::read('OAuth.providers')))], - ); - }); - } - } } From 1cfc3f7c06a0b31d40796663412dd1b3d2f10ac1 Mon Sep 17 00:00:00 2001 From: Adam Rusinowski Date: Fri, 6 Nov 2026 17:58:01 +0100 Subject: [PATCH 28/35] fix(test): BaseTestTrait data provider attribute, CSV parsing - testPermissions() declares its data provider with #[DataProvider('provider')], PHPUnit 12 ignores the docblock annotation. - testPermissions() returns void, it failed with a missing array return value. - Empty CSV lines are skipped, rows without the "Response Contains" column work, str_getcsv() gets an explicit escape (PHP 8.4 deprecation). - The CSV path can be changed by overriding _permissionsCsvPath(). --- src/Test/BaseTestTrait.php | 48 +++++++++--- tests/TestCase/Test/BaseTestTraitTest.php | 95 +++++++++++++++++++++++ 2 files changed, 133 insertions(+), 10 deletions(-) create mode 100644 tests/TestCase/Test/BaseTestTraitTest.php diff --git a/src/Test/BaseTestTrait.php b/src/Test/BaseTestTrait.php index 1503aa3..dd0e0fd 100644 --- a/src/Test/BaseTestTrait.php +++ b/src/Test/BaseTestTrait.php @@ -6,6 +6,7 @@ use Cake\Console\ConsoleIo; use Cake\Core\Configure; use Cake\ORM\TableRegistry; +use PHPUnit\Framework\Attributes\DataProvider; trait BaseTestTrait { @@ -51,11 +52,17 @@ protected function _isVerboseOrDebug(): bool * @param string $method Request method. * @param string $ajax Ajax value * @param string $responseCode Reponse code. - * @param string $responseContains Text the response should contains. + * @param string $responseContains Text the response should contains, empty to expect an empty body. * @throws \PHPUnit\Exception */ - protected function _testPermissions(string $url, string $username, string $method, string $ajax, string $responseCode, string $responseContains): void - { + protected function _testPermissions( + string $url, + string $username, + string $method, + string $ajax, + string $responseCode, + string $responseContains = '', + ): void { if ($this->_isVerboseOrDebug()) { (new ConsoleIo())->info(__( "\nUrl: {0} Username: {1} Method: {2} Ajax?: {3} Response Code: {4} Response Contains: {5} ", @@ -94,22 +101,43 @@ protected function _testPermissions(string $url, string $username, string $metho /** * Test permissions * + * The test class must define a static `provider()` method returning the CSV file names, for example + * `[['admin.csv'], ['user.csv']]`. The files are read from `tests/Provider`. + * * @param string $csv CSV name - * @return array - * @dataProvider provider + * @return void */ - public function testPermissions(string $csv): array + #[DataProvider('provider')] + public function testPermissions(string $csv): void { - $this->assertTrue(file_exists(TESTS . 'Provider' . DS . $csv)); - $rows = array_map('str_getcsv', file(TESTS . 'Provider' . DS . $csv)); + $path = $this->_permissionsCsvPath($csv); + $this->assertFileExists($path); + $rows = array_map( + fn(string $line): array => str_getcsv($line, ',', '"', ''), + (array)file($path, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES), + ); foreach ($rows as $row) { - if ($row[0][0] === '#') { + if (!isset($row[0]) || trim($row[0]) === '' || $row[0][0] === '#') { continue; } - [$url, $username, $method, $ajax, $responseCode, $responseContains] = array_pad($row, 6, null); + [$url, $username, $method, $ajax, $responseCode, $responseContains] = array_map( + 'strval', + array_pad($row, 6, ''), + ); $this->setUp(); $this->_testPermissions($url, $username, $method, $ajax, $responseCode, $responseContains); $this->tearDown(); } } + + /** + * Path of a permissions CSV file + * + * @param string $csv CSV name + * @return string + */ + protected function _permissionsCsvPath(string $csv): string + { + return TESTS . 'Provider' . DS . $csv; + } } diff --git a/tests/TestCase/Test/BaseTestTraitTest.php b/tests/TestCase/Test/BaseTestTraitTest.php new file mode 100644 index 0000000..e98471a --- /dev/null +++ b/tests/TestCase/Test/BaseTestTraitTest.php @@ -0,0 +1,95 @@ +csvPath; + } + + protected function _testPermissions( + string $url, + string $username, + string $method, + string $ajax, + string $responseCode, + string $responseContains = '', + ): void { + $this->calls[] = func_get_args(); + } + }; + $case->csvPath = $csv; + + try { + $case->testPermissions('permissions.csv'); + } finally { + unlink($csv); + } + + $this->assertSame([ + ['/admin/posts', 'admin', 'get', 'no-ajax', '200', 'Posts'], + ['/posts/delete/1', 'user', 'post', 'ajax', '403', ''], + ], $case->calls); + } + + /** + * Test the data provider is declared with an attribute, PHPUnit 12 ignores docblock annotations + * + * @return void + */ + public function testPermissionsDataProviderAttribute(): void + { + $attributes = (new ReflectionMethod(BaseTestTrait::class, 'testPermissions')) + ->getAttributes(DataProvider::class); + + $this->assertCount(1, $attributes); + $this->assertSame(['provider'], $attributes[0]->getArguments()); + } +} From 1d2ac3731af1931224ba2c780e46147145cb032a Mon Sep 17 00:00:00 2001 From: Adam Rusinowski Date: Sat, 7 Nov 2026 19:27:23 +0100 Subject: [PATCH 29/35] 11.1: deprecations, review fixes, stricter static analysis, docs Deprecate legacy social mappers, fix Azure validated, Keycloak mapFields, OIDC config and checks, TwoFactorMiddleware and ServiceFactory errors, BaseTestTrait. PHPStan level 8, Psalm level 2 baseline, PHPCS warnings. Docs, changelog and copyright years. --- CHANGELOG.md | 119 ++++- Docs/Documentation/Authentication.md | 31 +- Docs/Documentation/Authorization.md | 63 ++- Docs/Documentation/MigrationGuide.md | 39 +- Docs/Documentation/OwnerRule.md | 2 +- Docs/Documentation/Rbac.md | 68 ++- Docs/Documentation/SimpleRbacAuthorize.md | 54 --- Docs/Documentation/Social.md | 68 +-- Docs/Documentation/SuperuserAuthorize.md | 18 - Docs/Documentation/Testing.md | 29 +- Docs/Documentation/TwoFactor.md | 24 +- Docs/Home.md | 13 +- LICENSE.txt | 2 +- README.md | 44 +- composer.json | 2 +- config/auth.php | 13 +- phpstan.neon | 11 +- psalm-baseline.xml | 448 ++---------------- psalm.xml | 100 +--- src/AuthPlugin.php | 5 +- src/Authentication/AuthenticationService.php | 11 +- ...ltOneTimePasswordAuthenticationChecker.php | 5 +- ...DefaultWebauthn2FAuthenticationChecker.php | 5 +- src/Authentication/Failure.php | 5 +- src/Authentication/FailureInterface.php | 5 +- ...mePasswordAuthenticationCheckerFactory.php | 14 +- ...PasswordAuthenticationCheckerInterface.php | 5 +- .../OneTimePasswordProcessor.php | 5 +- .../TwoFactorProcessor/U2FProcessor.php | 5 +- .../Webauthn2faProcessor.php | 5 +- .../TwoFactorProcessorCollection.php | 18 +- .../TwoFactorProcessorInterface.php | 5 +- .../TwoFactorProcessorLoader.php | 5 +- ...Webauthn2fAuthenticationCheckerFactory.php | 14 +- ...bauthn2fAuthenticationCheckerInterface.php | 5 +- src/Authenticator/CookieAuthenticator.php | 4 +- src/Authenticator/FormAuthenticator.php | 19 +- .../OneTimeTokenAuthenticator.php | 10 + src/Authenticator/SocialAuthenticator.php | 4 +- src/Authenticator/TwoFactorAuthenticator.php | 4 +- .../OneTimePasswordAuthenticatorComponent.php | 5 +- src/Exception/InvalidProviderException.php | 4 +- src/Exception/InvalidSettingsException.php | 4 +- src/Identifier/SocialIdentifier.php | 4 +- src/Middleware/RbacMiddleware.php | 4 +- src/Middleware/SocialAuthMiddleware.php | 4 +- src/Middleware/TwoFactorMiddleware.php | 11 +- src/Plugin.php | 5 +- src/Policy/CollectionPolicy.php | 4 +- src/Policy/PolicyInterface.php | 4 +- src/Policy/RbacPolicy.php | 4 +- src/Policy/SuperuserPolicy.php | 5 +- src/Rbac/PermissionMatchResult.php | 4 +- src/Rbac/Permissions/AbstractProvider.php | 4 +- src/Rbac/Permissions/ConfigProvider.php | 4 +- src/Rbac/Rbac.php | 35 +- src/Rbac/RbacInterface.php | 4 +- src/Rbac/Rules/AbstractRule.php | 9 +- src/Rbac/Rules/OTPRule.php | 6 +- src/Rbac/Rules/Owner.php | 10 +- src/Rbac/Rules/Rule.php | 5 +- src/Rbac/Rules/RuleRegistry.php | 8 +- src/Social/MapUser.php | 5 +- src/Social/Mapper/AbstractMapper.php | 10 +- src/Social/Mapper/Amazon.php | 4 +- src/Social/Mapper/Azure.php | 19 +- src/Social/Mapper/Cognito.php | 4 +- src/Social/Mapper/Facebook.php | 4 +- src/Social/Mapper/Github.php | 4 +- src/Social/Mapper/Google.php | 4 +- src/Social/Mapper/Instagram.php | 22 +- src/Social/Mapper/Keycloak.php | 6 +- src/Social/Mapper/LinkedIn.php | 27 +- src/Social/Mapper/LinkedInOpenIDConnect.php | 4 +- src/Social/Mapper/Pinterest.php | 26 +- src/Social/Mapper/Tumblr.php | 23 +- src/Social/Mapper/Twitter.php | 6 +- src/Social/ProviderConfig.php | 8 +- src/Social/Service/OAuth1Service.php | 11 +- src/Social/Service/OAuth2Service.php | 15 +- src/Social/Service/OAuthServiceAbstract.php | 4 +- src/Social/Service/OpenIDConnectService.php | 40 +- src/Social/Service/ServiceFactory.php | 9 +- src/Social/Service/ServiceInterface.php | 4 +- src/Test/BaseTestTrait.php | 35 +- src/Traits/IsAuthorizedTrait.php | 4 +- src/Traits/ReCaptchaTrait.php | 4 +- .../TwoFactorProcessorCollectionTest.php | 54 +++ .../Middleware/TwoFactorMiddlewareTest.php | 39 ++ tests/TestCase/Rbac/RbacTest.php | 42 ++ .../TestCase/Rbac/Rules/RuleRegistryTest.php | 12 + tests/TestCase/Social/Mapper/AzureTest.php | 36 +- .../Social/Mapper/DeprecatedMappersTest.php | 69 +++ .../TestCase/Social/Mapper/InstagramTest.php | 5 +- tests/TestCase/Social/Mapper/KeycloakTest.php | 18 + tests/TestCase/Social/Mapper/LinkedInTest.php | 5 +- .../Social/Service/OAuth1ServiceTest.php | 20 + .../Social/Service/OAuth2ServiceTest.php | 20 + .../Service/OpenIDConnectServiceTest.php | 60 +++ .../Social/Service/ServiceFactoryTest.php | 70 +++ tests/TestCase/Test/BaseTestTraitTest.php | 131 +++++ tests/bootstrap.php | 8 +- 102 files changed, 1452 insertions(+), 892 deletions(-) delete mode 100644 Docs/Documentation/SimpleRbacAuthorize.md delete mode 100644 Docs/Documentation/SuperuserAuthorize.md create mode 100644 tests/TestCase/Authentication/TwoFactorProcessorCollectionTest.php create mode 100644 tests/TestCase/Social/Mapper/DeprecatedMappersTest.php diff --git a/CHANGELOG.md b/CHANGELOG.md index 099b336..93e95d0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,16 +4,59 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). -## [Unreleased] +## [11.1.0] - Unreleased +### Upgrade notes +No public API was removed, the changes below are compatible for applications using the plugin as +documented. Check these behavior changes when upgrading: + +- Requires CakePHP `^5.4`. +- Azure social login: `validated` is only `true` with the `email_verified` or `xms_edov` claim. With + CakeDC/Users, Azure users without these claims are no longer treated as having a verified email. +- The `LinkedIn`, `Instagram`, `Pinterest` and `Tumblr` mappers raise a deprecation warning. Test + suites that fail on deprecations fail until the provider is changed or the warning is ignored with + `Error.ignoredDeprecationPaths`. +- `BaseTestTrait`: the `provider()` method of the test class must be static, and the test user is + stored at `Auth.Authenticators.Session.sessionKey` (`Auth` by default) instead of `Auth.User`. + Applications whose session authenticator reads `Auth.User` set that config key to `Auth.User`. +- The default `resetOneTimePasswordAuthenticator` permission allows users with integer ids to reset + their own one time password authenticator, the old closure always denied them. +- Code calling `TwoFactorProcessorInterface::getUrlByType()` must handle a string url. +- An `allowed` or `bypassAuth` array with a `className` that is not a `Rule` throws an + `InvalidArgumentException`, it allowed every logged in user before. +- Configuration errors throw `InvalidArgumentException` (or `JsonException` for rule options that can + not be encoded) instead of a `TypeError`. Requests without a social `provider` param get a 404 + instead of a 500. +- The Rbac match reason (debug log and `Auth.Rbac.checked` event) says `result = true` or + `result = false` instead of `1` or an empty string. + +### Security +- The `Azure` social mapper trusted any `upn` as a validated email (the "nOAuth" pattern). `validated` + is now only `true` with the `email_verified` or `xms_edov` claim. +- An Rbac `allowed` or `bypassAuth` rule config whose `className` is missing or is not a `Rule` + allowed every logged in user. It now throws an `InvalidArgumentException`. +- The OpenID Connect service validates the id token signature and its `iss`, `aud`, `azp` and `nonce` + claims, only loads the key set from a `jwks_uri` on the scheme, host and port of `openid.baseUrl`, and + the `LinkedInOpenIDConnect` mapper reads `validated` from `email_verified`. +- A partial Keycloak `mapFields` config dropped the `roles` field, so the `rolesMap` check let users + without a mapped role log in. The configured fields are now merged over the mapper fields. +- The `Tumblr` mapper is deprecated: its user id is a crc32 of the nickname, so two users can get the + same id. + ### Added - Keycloak social login mapper `CakeDC\Auth\Social\Mapper\Keycloak`, with realm roles mapped by the - `rolesMap` provider config, and a disabled `keycloak` provider in `config/auth.php`. + `rolesMap` provider config (case-sensitive, no default map), and a disabled `keycloak` provider in + `config/auth.php` with a commented example roles map. - `CakeDC\Auth\Social\Service\OpenIDConnectService` and the `LinkedInOpenIDConnect` mapper and - provider. The id token `iss`, `aud` and `nonce` claims are validated, the discovery document and the - key set can be cached with `openid.cache`. Requires `firebase/php-jwt`. + provider. The id token `iss`, `aud`, `azp` and `nonce` claims are validated, the discovery document and the + key set can be cached with `openid.cache` (the key set is fetched again when a token uses an unknown + key id). The LinkedIn mapper reads `validated` from `email_verified`. Requires `firebase/php-jwt`. - `CakeDC\Auth\Rbac\Rules\OTPRule`, used by the default `resetOneTimePasswordAuthenticator` permission. - Rbac permission values can be a rule config array `['className' => Rule::class, 'options' => []]`. - Arrays with a `className` key that is not a `Rule` class keep the previous matching behavior. + Arrays with a `className` key that is not a `Rule` class keep the previous matching behavior, except + for `allowed` and `bypassAuth`: there such an array throws an `InvalidArgumentException` instead of + allowing every logged in user. In `bypassAuth`, a rule config (like a `Rule`) is only evaluated for + logged in users, only `true` or a callable opens a permission to anonymous requests. The array form requires this version, older versions treat it as + allowed for every logged in user, so do not copy the new `config/permissions.php` to older apps. - The 2FA verify url (`TwoFactorProcessorInterface::getUrlByType()`) can be a string url. The return type is now `array|string|null`; custom callers of `getUrlByType()` must handle strings. @@ -27,18 +70,80 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 `robthree/twofactorauth` `^3.0.1`, `endroid/qr-code` `^6.0`. - Removed the unused `yubico/u2flib-server` dev dependency (U2F is deprecated). - `suggest` lists the optional packages needed by each feature. +- Static analysis: PHPStan level 8 (was 6), with stale path ignores reported. Psalm level 2 set + explicitly, without unused code detection and `ClassMustBeFinal` (plugin classes are extension + points) and without the blanket `info` downgrades, baseline reduced from 143 to 36 entries. PHPCS + warnings fail `composer cs-check` (no more `-n`). +- Invalid class names fail with an `InvalidArgumentException` instead of a `TypeError`: a + `FormAuthenticator` `baseClassName` that is not an authenticator, a two factor processor class that + does not implement `TwoFactorProcessorInterface`, a social provider `className` of the wrong type. - The default `resetOneTimePasswordAuthenticator` permission uses `OTPRule` instead of a closure. It - compares the user id as string, so integer ids are matched too. + compares the user id as string, so users with integer ids can now reset their own one time password + authenticator. The old closure compared a string with an integer and always denied them. Other users + are still denied. + +### Deprecated +- The `LinkedIn` (LinkedIn retired the API, use `linkedInOpenIDConnect`), `Instagram` (Basic Display + API shut down), `Pinterest` (API v1 fields) and `Tumblr` (crc32 user id) social mappers emit a + deprecation warning and will be removed in 12.0. +- `CakeDC\Auth\Plugin` extends `CakeDC\Auth\AuthPlugin` and is deprecated, load the plugin with + `AuthPlugin` (or by its name `CakeDC/Auth`). ### Fixed - `ReCaptchaTrait::validateReCaptchaFromRequest()` treats a missing or empty `g-recaptcha-response` as an invalid captcha (returns `false`) instead of passing `null` to the non-nullable `validateReCaptcha(string ...)`, which raised a `TypeError` (HTTP 500). A tokenless request — e.g. a programmatic JSON client — now fails the reCaptcha check cleanly. +- The `/auth/{provider}` social login route connected by the plugin used the CakePHP 4 `:provider` + placeholder and never matched on CakePHP 5. +- The `Auth.Authorization.checked` event of `SuperuserPolicy` had a null `role` for entity identities. +- `TwoFactorMiddleware` raised a `TypeError` when the request had no authentication result, it now + passes the request on. +- `ServiceFactory::createFromRequest()` raised a `TypeError` without a `provider` route param, it now + throws a `NotFoundException`. +- The provider `openid` settings (`url`, `baseUrl`, `issuer`, `nonce`, `cache`) reach the + `OpenIDConnectService` built by `ServiceFactory`, `ProviderConfig` dropped them before. +- `RuleRegistry` throws a `JsonException` for rule options that can not be encoded, `md5()` raised a + `TypeError` before. +- The Rbac match reason logged `result = 1` or `result = ` (empty), it now logs `true` or `false`. +- `BaseTestTrait` stored the logged in user under `Auth.User`, so with the `Auth` session key of + cakephp/authentication the identity had no `role` and `RbacPolicy` checked the default role. The + user is now stored at `Auth.Authenticators.Session.sessionKey` (`Auth` by default). +- `BaseTestTrait::testPermissions()` uses a `#[DataProvider]` attribute (PHPUnit 12 ignores the docblock + annotation), returns `void` instead of failing with a missing `array` return, skips empty CSV lines, + and a row without the `Response Contains` column no longer raises a `TypeError`: as for an empty + column, the response body must then be empty. The `method` and `Ajax?` columns are case-insensitive, + `POST` ran a GET request before. The `provider()` method of the test class must be static. +- A partial `OAuth.providers.keycloak.mapFields` replaced the whole Keycloak field map, losing `id`, + `roles` and `validated`, so the `rolesMap` check let every user in. The configured fields are now + merged over the mapper fields. +- `OneTimeTokenAuthenticator` treats a token array that is not a flat list of strings as a missing + token, instead of joining it with an "Array to string conversion" warning. + +## [11.0.0] - 2026-08-22 +### Changed +- Requires CakePHP `^5.3` and PHP `>=8.2`. +- PHPUnit `^10.5 || ^11.1 || ^12.5` and PHPStan 2 for development, tests updated and PHPUnit notices + and deprecations fixed. +- Identifiers are configured per authenticator (`identifier` option) instead of with + `AuthenticationService::loadIdentifier()`, see the Authentication documentation. -## [10.1.2] - 2025-09-26 +### Added +- `CakeDC\Auth\AuthPlugin` plugin class, as expected by CakePHP 5.3. `CakeDC\Auth\Plugin` is kept. +- `Auth.Rbac.checked` and `Auth.Authorization.checked` events from `Rbac` and `SuperuserPolicy`, + enabled with `CakeDC/Auth.emitEvents`. +- `U2FProcessor` two factor processor, deprecated: use Webauthn instead. + +## [10.1.4] - 2025-09-26 - Github social login +## [10.1.3] - 2025-03-07 +- Callbacks can be used for `bypassAuth` in permissions. +- Fixed deprecations in tests. + +## [10.1.2] - 2025-03-06 +- Two factor authentication errors keep the previous exception. + ## [10.0.0] - 2024-02-09 - Two factor processors introduced. Prvided way to add new two factor processors on client level. CakePHP 5.0 version. diff --git a/Docs/Documentation/Authentication.md b/Docs/Documentation/Authentication.md index 100c426..2fc592b 100644 --- a/Docs/Documentation/Authentication.md +++ b/Docs/Documentation/Authentication.md @@ -5,7 +5,8 @@ offers an improved way to handle authentication, we have created some additional - social auth; - reCaptcha in form; - cookie login with session; - - two-factor (one-time password) authentication + - two-factor (one-time password and Webauthn) authentication; + - one time token (magic link) login. Custom Authenticators --------------------- @@ -17,7 +18,7 @@ like in social authentication. - keyCheckEnabledRecaptcha, config key used to check if reCaptcha is enabled. Default, 'Users.reCaptcha.login' - baseClassName, optional fullname class for base form authenticator -- **SocialAuthenticaor**, allows to authenticate a user with social provider (facebook, google, twitter, etc). +- **SocialAuthenticator**, allows to authenticate a user with social provider (facebook, google, twitter, etc). You need to use the middleware `CakeDC\Auth\Middleware\SocialAuthMiddleware` and identifier `CakeDC\Auth\Identifier\SocialIdentifier` to make this authenticator work correctly. Check how enabled social authentication at [users plugin.](https://github.com/CakeDC/Users) @@ -27,6 +28,14 @@ Check how enabled social authentication at [users plugin.](https://github.com/Ca - loginUrl: The login URL, string or array of URLs. Default is null and all pages will be checked. - urlChecker: The URL checker class or object. Default is DefaultUrlChecker. +- **OneTimeTokenAuthenticator**, logs in a user with a one time token (magic link), read from the +`token` query param or the posted `token` field. A token posted as one input per character +(`token[0]`, `token[1]`...) is joined. The user is found with the `loginWithToken($token)` method of +the users table configured in `Users.table`, provided by the CakeDC/Users plugin. + +All authenticators use the identifiers of cakephp/authentication 3.x, configured per authenticator +with the `identifier` option. + Authentication Service ---------------------- @@ -40,30 +49,29 @@ Sample usage: 'email', - 'password' => 'password' + 'password' => 'password', ]; // Load the authenticators, you want session first @@ -92,15 +100,12 @@ class Application extends BaseApplication implements AuthenticationServiceProvid * @param \Cake\Http\MiddlewareQueue $middlewareQueue The middleware queue to set in your App Class * @return \Cake\Http\MiddlewareQueue */ - public function middleware($middlewareQueue) + public function middleware(MiddlewareQueue $middlewareQueue): MiddlewareQueue { // Various other middlewares for error handling, routing etc. added here. // Add the authentication middleware - $authentication = new AuthenticationMiddleware($this); - - // Add the middleware to the middleware queue - $middlewareQueue->add($authentication); + $middlewareQueue->add(new AuthenticationMiddleware($this)); return $middlewareQueue; } diff --git a/Docs/Documentation/Authorization.md b/Docs/Documentation/Authorization.md index eabbe8a..bf74501 100644 --- a/Docs/Documentation/Authorization.md +++ b/Docs/Documentation/Authorization.md @@ -6,7 +6,7 @@ with [Request Authorization Middleware](https://github.com/cakephp/authorization - CollectionPolicy, check permission with a list of policies, stop at first success - RbacPolicy, check permissions using the `CakeDC\Auth\Rbac\Rbac` - - SuperuserPolicy, check if user is 'superuser' and allow all; + - SuperuserPolicy, check if user is 'superuser' and allow all. RbacPolicy ---------- @@ -40,39 +40,56 @@ SuperuserPolicy This policy allow all for a superuser. Configurations: - superuser_field, superuser field in the users entity, default, is_superuser -If the current user 'superuser_field' is true, he'll get full permissions in your app. +If the current user 'superuser_field' is true, they get full permissions in your app. + +Events +------ + +When `CakeDC/Auth.emitEvents` is `true`, `Rbac` dispatches `Auth.Rbac.checked` after each permission +check and `SuperuserPolicy` dispatches `Auth.Authorization.checked` when a superuser is allowed. +The event data holds `allowed`, `role`, `user`, `request`, `permission` and `reason` +(`Auth.Rbac.checked` also holds the `PermissionMatchResult` as `result`, +`Auth.Authorization.checked` holds the `policy` class). Use them for audit logs, for example: + +```php +\Cake\Event\EventManager::instance()->on('Auth.Rbac.checked', function (\Cake\Event\EventInterface $event) { + if (!$event->getData('allowed')) { + \Cake\Log\Log::info((string)$event->getData('reason'), ['scope' => 'rbac']); + } +}); +``` Using the policies ------------------ At your Application::middleware add the authorization and request authorization middlewares: - -``` + +```php $middlewareQueue->add(new AuthorizationMiddleware($this, Configure::read('Auth.AuthorizationMiddleware'))); $middlewareQueue->add(new RequestAuthorizationMiddleware()); ``` As usual create or update the Application::getAuthorizationService method: - -``` + +```php public function getAuthorizationService(ServerRequestInterface $request): AuthorizationServiceInterface { $map = new MapResolver(); - $map->map( - ServerRequest::class, - new CollectionPolicy([ - SuperuserPolicy::class,//First check super user policy - RbacPolicy::class, Only check with rbac if user is not super user - ]) - ); - - $orm = new OrmResolver(); - - $resolver = new ResolverCollection([ - $map, - $orm - ]); - - return new AuthorizationService($resolver); - } + $map->map( + ServerRequest::class, + new CollectionPolicy([ + SuperuserPolicy::class, // First check the superuser policy + RbacPolicy::class, // Only check with rbac if the user is not a superuser + ]), + ); + + $orm = new OrmResolver(); + + $resolver = new ResolverCollection([ + $map, + $orm, + ]); + + return new AuthorizationService($resolver); + } ``` diff --git a/Docs/Documentation/MigrationGuide.md b/Docs/Documentation/MigrationGuide.md index 79688e8..cf8a649 100644 --- a/Docs/Documentation/MigrationGuide.md +++ b/Docs/Documentation/MigrationGuide.md @@ -40,4 +40,41 @@ Please check [Authentication](Authentication.md) and [Authorization](Authorizati 4.x to 5.x ---------- * Required cakephp 4 -* Renamed \CakeDC\Auth\Test\BaseTraitTest to \CakeDC\Auth\Test\BaseTestTrait \ No newline at end of file +* Renamed \CakeDC\Auth\Test\BaseTraitTest to \CakeDC\Auth\Test\BaseTestTrait + +9.x to 10.x +----------- +* Requires CakePHP 5 and PHP 8.1 +* Two factor processors, configured in `TwoFactorProcessors`, see [Two Factor](TwoFactor.md) + +10.x to 11.0 +------------ +* Requires CakePHP 5.3 and PHP 8.2 +* Identifiers are configured per authenticator with the `identifier` option, instead of + `AuthenticationService::loadIdentifier()`, see [Authentication](Authentication.md) +* The plugin class is `CakeDC\Auth\AuthPlugin` +* `Auth.Rbac.checked` and `Auth.Authorization.checked` events, enabled with `CakeDC/Auth.emitEvents`, + see [Authorization](Authorization.md#events) +* `U2FProcessor` is back as a deprecated processor, use Webauthn instead + +11.0 to 11.1 +------------ +* Requires CakePHP 5.4, and `cakephp/authentication` 3.3 is a dependency of the plugin +* `CakeDC\Auth\Plugin` is deprecated, load the plugin with `CakeDC\Auth\AuthPlugin` +* `TwoFactorProcessorInterface::getUrlByType()` returns `array|string|null`. Implementations + returning `?array` keep working, code calling it must handle string urls +* The default `resetOneTimePasswordAuthenticator` permission uses the `OTPRule`. Users with integer + ids can now reset their own one time password authenticator, the previous closure always denied + them +* An `allowed` or `bypassAuth` array with a `className` key must be a valid rule config, a class that + is not a `Rule` throws an `InvalidArgumentException` +* `BaseTestTrait::testPermissions()` uses a `#[DataProvider]` attribute, the `provider()` method of + your test class must be static +* The `LinkedIn`, `Instagram`, `Pinterest` and `Tumblr` mappers are deprecated and will be removed in + 12.0. Switch the `linkedIn` provider to `linkedInOpenIDConnect` +* The `Azure` mapper only sets `validated` when the `email_verified` or `xms_edov` claim is `true`. + Before, any `upn` was trusted as a validated email +* `BaseTestTrait` stores the logged in user at `Auth.Authenticators.Session.sessionKey` (`Auth` by + default) instead of `Auth.User`. Set `sessionKey` to `Auth.User` to keep the previous layout +* New: Keycloak mapper, OpenID Connect service and LinkedIn OpenID Connect provider, see + [Social](Social.md) diff --git a/Docs/Documentation/OwnerRule.md b/Docs/Documentation/OwnerRule.md index 64c4cc4..c188f16 100644 --- a/Docs/Documentation/OwnerRule.md +++ b/Docs/Documentation/OwnerRule.md @@ -4,7 +4,7 @@ Owner Rule Setup --------------- -SimpleRbacAuthorize will pick and use specific Rule classes (implementing the \CakeDC\Auth\Auth\Rules\Rule interface). +Rbac will pick and use specific Rule classes (implementing the `\CakeDC\Auth\Rbac\Rules\Rule` interface). You only need to create your own permission rules, implement the required interface and pass the instance in the 'allowed' param. diff --git a/Docs/Documentation/Rbac.md b/Docs/Documentation/Rbac.md index 62a7625..17204ea 100644 --- a/Docs/Documentation/Rbac.md +++ b/Docs/Documentation/Rbac.md @@ -2,7 +2,7 @@ Rbac ==== The Rbac class is provided to allow permission matching based on request params and a set of rules. -This class was extracted initially from SimpleRbacAuthorize to allow using it from Middlewares. +It is used by the `RbacMiddleware` and by the `RbacPolicy` (see [Authorization](Authorization.md)). Along with the original extraction, new classes for permission providers were created too, to allow using other sources to provide the permissions array, for example the database or a cache engine. @@ -13,7 +13,7 @@ Setup Create an instance of the Rbac class and use `checkPermissions` method ```php $rbac = new Rbac(); - $isAuthorized = $this->rbac->checkPermissions($userData, $request); + $isAuthorized = $rbac->checkPermissions($userData, $request); ``` You can define the actual permissions array in the constructor options (key `permissions`), @@ -23,6 +23,34 @@ configuration file. Extend `AbstractProvider` class and use the `permissions_provider_class` config key to let the Rbac use your own permissions provider, for example to read the permissions from the database. +Configuration options: + +* `autoload_config`: configuration file read by the default provider, `permissions` by default +* `role_field`: user field holding the role, `role` by default +* `default_role`: role used when the user has no role, `user` by default +* `permissions_provider_class`: permissions provider, `ConfigProvider` by default +* `permissions`: permissions array, overrides the provider +* `log`: log the permission matching at debug level, `false` by default + +When `CakeDC/Auth.emitEvents` is `true`, every check dispatches the `Auth.Rbac.checked` event, see +[Authorization](Authorization.md#events). + +RbacMiddleware +-------------- + +`CakeDC\Auth\Middleware\RbacMiddleware` checks the permissions of every request. Add it after the +authentication and routing middlewares: + +```php +$middlewareQueue->add(new \CakeDC\Auth\Middleware\RbacMiddleware(null, [ + // RbacMiddleware::UNAUTHORIZED_BEHAVIOR_THROW, _REDIRECT or _AUTO (throw for json requests) + 'unauthorizedBehavior' => \CakeDC\Auth\Middleware\RbacMiddleware::UNAUTHORIZED_BEHAVIOR_REDIRECT, + 'unauthorizedRedirect' => ['plugin' => 'CakeDC/Users', 'controller' => 'Users', 'action' => 'login'], +])); +``` + +The Rbac instance is stored in the `rbac` request attribute, the `RbacPolicy` reuses it. + Permission rules syntax ----------------- @@ -53,13 +81,13 @@ Permission rules syntax * The `*` is checked and if found the result is inverted * The final boolean value is **the result of permission** checker. This means if it is `false` then no other permissions are checked and the user is denied access. And if it is `true`, you need at least an user identified, or it'll deny your access attempt. For this reason the `allowed` key must be placed at the end of permission since no other rules are executed after it -* ONLY when using Rbac within the Middleware implementation: Another special key is `bypassAuth`, if set to true will allow the request, even if there is no user data. Note this won't work with the regular AuthComponent setup, and you'll require using `AuthComponent::allow` method to specify public actions. +* Another special key is `bypassAuth`. If it is `true`, or a callable `($user, $role, $request)` returning `true`, the request is allowed even if there is no user data. Use it for public actions. A `Rule` or a rule config array in `bypassAuth` is only evaluated for logged in users. **Notes**: -* For Superadmin access (permission to access ALL THE THINGS in your app) there is a specific Authorize Object provided +* For Superadmin access (permission to access ALL THE THINGS in your app) use the `SuperuserPolicy`, see [Authorization](Authorization.md) * Permissions that do not have `controller` and/or `action` keys (or the inverted versions) are automatically discarded in order to prevent errors. -* If you need to match all controllers/actions you should explicitly do `'contoller' => '*'` +* If you need to match all controllers/actions you should explicitly do `'controller' => '*'` * Key `user` (or the inverted version) is illegal (as it's impossible to match an array) and any permission containing it will be discarded * If the permission is discarded for the reasons stated above, a debug message will be logged @@ -73,21 +101,23 @@ You could use a callback in your 'allowed' to process complex authentication, li Example *ownership* callback, to allow users to edit their own Posts: ```php - 'allowed' => function (array $user, $role, \Cake\Http\ServerRequest $request) { - $postId = \Cake\Utility\Hash::get($request->params, 'pass.0'); - $post = \Cake\ORM\TableRegistry::get('Posts')->get($postId); - $userId = $user['id']; - if (!empty($post->user_id) && !empty($userId)) { - return $post->user_id === $userId; + 'allowed' => function (array|\ArrayAccess $user, string $role, \Cake\Http\ServerRequest $request): bool { + $postId = $request->getParam('pass.0'); + if (empty($postId) || empty($user['id'])) { + return false; } - return false; + $post = \Cake\ORM\TableRegistry::getTableLocator()->get('Posts')->find() + ->where(['id' => $postId]) + ->first(); + + return $post !== null && (string)$post->user_id === (string)$user['id']; } ``` ### Permission Rules: If you see that you are duplicating logic in your callbacks, you can create rule class to re-use the logic. -For example, the above ownership callback is included in CakeDC\Users as `Owner` rule +For example, the above ownership callback is included in this plugin as the `Owner` rule ```php 'allowed' => new \CakeDC\Auth\Rbac\Rules\Owner() //will pick by default the post id from the first pass param ``` @@ -110,17 +140,21 @@ The array is used as a rule only when `className` is a class implementing `\Cake The only requirement is to implement `\CakeDC\Auth\Rbac\Rules\Rule` interface which has one method: ```php -class YourRule implements \CakeDC\Auth\Rbac\Rules\Rule +use ArrayAccess; +use CakeDC\Auth\Rbac\Rules\Rule; +use Psr\Http\Message\ServerRequestInterface; + +class YourRule implements Rule { /** * Check the current entity is owned by the logged in user * - * @param array $user Auth array with the logged in data + * @param \ArrayAccess|array $user Auth array with the logged in data * @param string $role role of the user - * @param Request $request current request, used to get a default table if not provided + * @param \Psr\Http\Message\ServerRequestInterface $request current request * @return bool */ - public function allowed(array $user, $role, Request $request) + public function allowed(array|ArrayAccess $user, string $role, ServerRequestInterface $request): bool { // Your logic here } diff --git a/Docs/Documentation/SimpleRbacAuthorize.md b/Docs/Documentation/SimpleRbacAuthorize.md deleted file mode 100644 index e9d3f0c..0000000 --- a/Docs/Documentation/SimpleRbacAuthorize.md +++ /dev/null @@ -1,54 +0,0 @@ -SimpleRbacAuthorize -============= - -Setup ---------------- - -SimpleRbacAuthorize is configured by default, but you can customize the way it works easily - -Example, in your AppController, you can configure the way the SimpleRbac works by setting the options: - -```php -$config['Auth']['authorize']['CakeDC/Users.SimpleRbac'] = [ - // autoload permissions.php - 'autoload_config' => 'permissions', - // role field in the Users table - 'role_field' => 'role', - // default role, used in new users registered and also as role matcher when no role is available - 'default_role' => 'user', - /* - * This is a quick roles-permissions implementation - * Rules are evaluated top-down, first matching rule will apply - * Each line define - * [ - * 'role' => 'admin', - * 'plugin', (optional, default = null) - * 'prefix', (optional, default = null) - * 'extension', (optional, default = null) - * 'controller', - * 'action', - * 'allowed' (optional, default = true) - * ] - * You could use '*' to match anything - * Suggestion: put your rules into a specific config file - */ - 'permissions' => [], // you could set an array of permissions or load them using a file 'autoload_config' - // log will default to the 'debug' value, matched rbac rules will be logged in debug.log by default when debug enabled - 'log' => false - ]; -``` - -This is the default configuration, based on it the Authorize object will first check your ```config/permissions.php``` -file and load the permissions using the configuration key ```Users.SimpleRbac.permissions```, there is an -example file you can copy into your ```config/permissions.php``` under the Plugin's config directory. - -If you don't want to use a file for configuring the permissions, you just need to tweak the configuration and set -```'autoload_config' => false,``` then define all your rules in AppController (not a good practice as the rules -tend to grow over time). - -The Users Plugin will use the field ```role``` field in the Users Table to match the role of the user and -check if there is a rule allowing him to access the url. - -The ```default_role``` will be used to set the role of the registered users by default. - -Check [Rbac](Rbac.md) for permissions and rules configuration and examples. diff --git a/Docs/Documentation/Social.md b/Docs/Documentation/Social.md index 3fbca13..047518c 100644 --- a/Docs/Documentation/Social.md +++ b/Docs/Documentation/Social.md @@ -1,21 +1,23 @@ Social Layer ============ -The social layer provide a easier way to handle social provider authentication -with provides using OAuth1 or OAuth2. The idea is to provide a base -interface for both OAuth and OAuth2. +The social layer provides an easier way to handle social provider authentication +with providers using OAuth1, OAuth2 or OpenID Connect. The idea is to provide a base +interface for all of them. ***Make sure to load the bootstap.php file of this plugin!*** We have mappers to allow you a quick start with these providers: - Amazon +- Azure (the email is only validated with the `email_verified` or `xms_edov` claim) +- Cognito - Facebook - Google -- Instagram -- LinkedIn (Deprecated, they switched to OpenID-Connect) -- LinkedInOpenIDConnect (New, OIDC based authentication) -- Pinterest -- Tumblr +- Instagram (Deprecated, the Instagram Basic Display API was shut down) +- LinkedIn (Deprecated, LinkedIn retired this API, use LinkedInOpenIDConnect) +- LinkedInOpenIDConnect (OIDC based authentication) +- Pinterest (Deprecated, reads fields of the retired API v1) +- Tumblr (Deprecated, the user id is a crc32 of the nickname) - Twitter - Github - Keycloak @@ -25,9 +27,9 @@ You must define 'options.redirectUri', 'options.clientId' and for facebook you could add these at your bootstrap.php: ```php -\Cake\Configure\Configure::write('OAuth.providers.facebook.options.redirectUri', $redirectUrl); -\Cake\Configure\Configure::write('OAuth.providers.facebook.options.clientId', 'myFacebookAppClientId'); -\Cake\Configure\Configure::write('OAuth.providers.facebook.options.clientSecret', 'myFacebookAppClientSecret'); +\Cake\Core\Configure::write('OAuth.providers.facebook.options.redirectUri', $redirectUrl); +\Cake\Core\Configure::write('OAuth.providers.facebook.options.clientId', 'myFacebookAppClientId'); +\Cake\Core\Configure::write('OAuth.providers.facebook.options.clientSecret', 'myFacebookAppClientSecret'); ``` ***Make sure to load the bootstap.php file of this plugin, cause we need @@ -49,10 +51,10 @@ use CakeDC\Auth\Social\Service\ServiceFactory; * * @param string $alias of the provider. * - * @throws \Cake\Http\Exception\NotFoundException Quando o provider informado não existe - * @return \Cake\Http\Response Redirects on successful + * @throws \Cake\Http\Exception\NotFoundException When the provider does not exist + * @return \Cake\Http\Response Redirects on successful */ - public function social($alias = null) + public function social(?string $alias = null): \Cake\Http\Response { return $this->redirect( (new ServiceFactory()) @@ -66,10 +68,10 @@ use CakeDC\Auth\Social\Service\ServiceFactory; * * @param string $alias of the provider. * - * @throws \Cake\Http\Exception\NotFoundException Quando o provider informado não existe - * @return \Cake\Http\Response Redirects to profile if okay or error + * @throws \Cake\Http\Exception\NotFoundException When the provider does not exist + * @return \Cake\Http\Response|null Redirects to profile if okay or error */ - public function callbackSocial($alias = null) + public function callbackSocial(?string $alias = null): ?\Cake\Http\Response { try { $server = (new ServiceFactory()) @@ -77,7 +79,7 @@ use CakeDC\Auth\Social\Service\ServiceFactory; ->createFromProvider($alias); if (!$server->isGetUserStep($this->request)) { - $this->Flash->error($message); + $this->Flash->error(__('Could not get the user from the provider')); return $this->redirect(['action' => 'profile']); } @@ -86,14 +88,16 @@ use CakeDC\Auth\Social\Service\ServiceFactory; //your code } catch (\Exception $e) { - $this->log($log); + $this->log($e->getMessage()); } + + return null; } ``` Working with cakephp/authentication ----------------------------------- If you're using the new cakephp/authentication we recommend you to use -the SocialAuthenticator and SocialMiddleware provided in this plugin. For more +the SocialAuthenticator and SocialAuthMiddleware provided in this plugin. For more details of how to handle social authentication with cakephp/authentication, please check how we implemented at CakeDC/Users plugins. @@ -121,10 +125,10 @@ Add the Keycloak provider configuration to your `config/users.php` file: 'service' => 'CakeDC\Auth\Social\Service\OAuth2Service', 'className' => 'Stevenmaguire\OAuth2\Client\Provider\Keycloak', 'mapper' => 'CakeDC\Auth\Social\Mapper\Keycloak', + // replace with the realm roles of your Keycloak server 'rolesMap' => [ - 'CakeDc-Admin' => 'admin', - 'CakeDc-User' => 'user', - 'CakeDc-Worker' => 'user' + 'example-realm-admin' => 'admin', + 'example-realm-user' => 'user', ], 'authParams' => ['scope' => ['openid', 'roles']], 'options' => [ @@ -149,7 +153,7 @@ Add the Keycloak provider configuration to your `config/users.php` file: - Configure the `realm_roles` mapper with "Add to userinfo" set to ON 2. **Realm Roles**: - - Create roles that match your configuration (e.g., `CakeDc-Admin`, `CakeDc-User`, `CakeDc-Worker`) + - Create roles that match your configuration (e.g., `example-realm-admin`, `example-realm-user`) - Assign these roles to users or groups in Keycloak 3. **User Attributes**: @@ -167,11 +171,13 @@ Without a `rolesMap` the `roles` field is `null` and no role is required. When a the login fails with an `UnexpectedValueException` when the userinfo has no roles or none of the user roles is in `rolesMap`, so only users with a mapped role can log in. -The mapper reads `OAuth.providers.keycloak.rolesMap` and `OAuth.providers.keycloak.mapFields`. When +The mapper reads `OAuth.providers.keycloak.rolesMap` and `OAuth.providers.keycloak.mapFields`, the +configured `mapFields` are merged over the mapper fields. When the provider uses another key, pass a mapper instance instead of the class name: `'mapper' => new \CakeDC\Auth\Social\Mapper\Keycloak(null, ['MyRealm-Admin' => 'admin'])`. -The mapper does not change the user role by itself. Use an event listener in your application to +The mapper does not change the user role by itself. CakeDC/Users creates new users with its +`Users.Registration.defaultRole`, the mapped role is not used for them. Use an event listener in your application to apply it, see below. ### Event Listener for Role Updates @@ -185,14 +191,14 @@ namespace App\Event; use Cake\Event\EventInterface; use Cake\Event\EventListenerInterface; -use CakeDC\Users\Plugin; +use CakeDC\Users\UsersPlugin; class SocialLoginListener implements EventListenerInterface { public function implementedEvents(): array { return [ - Plugin::EVENT_SOCIAL_LOGIN_EXISTING_ACCOUNT => 'changeRole', + UsersPlugin::EVENT_SOCIAL_LOGIN_EXISTING_ACCOUNT => 'changeRole', ]; } @@ -236,14 +242,16 @@ composer require firebase/php-jwt ``` The service validates the token signature with the provider key set, and the `iss`, `aud` -(must contain `options.clientId`) and `nonce` claims. Configure it with the `openid` key of the +(must contain `options.clientId`), `azp` (must be `options.clientId` when present, required when `aud` +has several values) and `nonce` claims. Configure it with the `openid` key of the provider: ```php 'linkedInOpenIDConnect' => [ // ... 'openid' => [ - // the jwks_uri of the discovery document must start with this url + // the jwks_uri of the discovery document must use this scheme, host and port, and a path below it. + // The defaults are for LinkedIn, set baseUrl, url and issuer for any other provider 'baseUrl' => 'https://www.linkedin.com/', // discovery document 'url' => 'https://www.linkedin.com/oauth/.well-known/openid-configuration', diff --git a/Docs/Documentation/SuperuserAuthorize.md b/Docs/Documentation/SuperuserAuthorize.md deleted file mode 100644 index 7db2cb0..0000000 --- a/Docs/Documentation/SuperuserAuthorize.md +++ /dev/null @@ -1,18 +0,0 @@ -SuperuserAuthorize -============= - -Setup ---------------- - -SuperuserAuthorize is here to provide full permissions to specific "SUPER" users in your app. - -```php -$config['Auth']['authorize']['Users.Superuser'] = [ - //superuser field in the Users table - 'superuser_field' => 'is_superuser', - ]; -``` - -If the current user 'superuser_field' is true, he'll get full permissions in your app. - -Note if you don't have superusers, you can disable the SuperuserAuthorize in AuthComponent initialization \ No newline at end of file diff --git a/Docs/Documentation/Testing.md b/Docs/Documentation/Testing.md index 47e265e..af9819e 100644 --- a/Docs/Documentation/Testing.md +++ b/Docs/Documentation/Testing.md @@ -6,21 +6,31 @@ This plugins provides a way to easily check your permissions and roles configura Setup ----- -Create a new test class and extends to `IntegrationTestCase` +Create a new test class extending `TestCase`, with the `IntegrationTestTrait` and the +`BaseTestTrait`, and the fixtures of your users table: ```php -class PermissionsTest extends IntegrationTestCase +use Cake\TestSuite\IntegrationTestTrait; +use Cake\TestSuite\TestCase; +use CakeDC\Auth\Test\BaseTestTrait; + +class PermissionsTest extends TestCase { - use \CakeDC\Auth\Test\BaseTestTrait; + use BaseTestTrait; + use IntegrationTestTrait; + + protected array $fixtures = ['app.Users']; } ``` -Now you need to define a `provider` method and it must return an array with the filenames. Note that each filename must be an array itself. We recommend to create one file per roles to keep things as clean as possible but it is up to you. +Now you need to define a static `provider` method returning an array with the filenames. Note that +each filename must be an array itself. We recommend to create one file per role to keep things as +clean as possible but it is up to you. ```php /** * @return array */ -public function provider() +public static function provider(): array { return [ ['first.csv'], @@ -30,12 +40,17 @@ public function provider() } ``` -Finally you only need to create CSV files in `tests/Provider` folder. +The `testPermissions` test of the trait runs once per file. The users are found by username in the +table configured in `Users.table` (`Users` by default) and stored in the session at the key of the +session authenticator, `Auth.Authenticators.Session.sessionKey` (`Auth` by default). + +Finally you only need to create CSV files in `tests/Provider` folder. Lines starting with `#` and +empty lines are skipped. CSV file template ----------------- -Each line must include `url`, `username`, `method` (`GET` or `POST`), `Ajax?` (`ajax` or `no-ajax`), `Response Code Expected` (`200`, `302`, `404`, etc) and it may include `Response Contains` with anything present in response body. +Each line must include `url`, `username`, `method` (`GET` or `POST`, case-insensitive), `Ajax?` (`ajax` or `no-ajax`), `Response Code Expected` (`200`, `302`, `404`, etc) and it may include `Response Contains` with anything present in response body. Without it, the response body must be empty. ```csv ######## URL,USERNAME,METHOD,AJAX?,RESPONSE CODE EXPECTED,RESPONSE CONTAINS /admin/my-url,administrator,get,no-ajax,200,my-page-content diff --git a/Docs/Documentation/TwoFactor.md b/Docs/Documentation/TwoFactor.md index 3751f78..3b24c9c 100644 --- a/Docs/Documentation/TwoFactor.md +++ b/Docs/Documentation/TwoFactor.md @@ -6,15 +6,27 @@ Two-factor authentication (2FA) is an identity and access management security me Configuration ------------- -Processors defined as Configure storage with key `TwoFactorProcessors` +The processors are listed in the `TwoFactorProcessors` Configure key, see `config/auth.php`. -By default `\RobThree\Auth\Providers\Qr\EndroidQrCodeProvider` is used. +The one time password processor is configured with the `OneTimePasswordAuthenticator` key: -You can disable it by adding this to any config file: +* `login`: enable the one time password verification, `false` by default +* `verifyAction`: url of the verify action +* `checker`: class deciding if the verification is required, `DefaultOneTimePasswordAuthenticationChecker` by default +* `issuer`: issuer shown in the authenticator app +* `digits`: number of digits of the codes, `6` by default +* `period`: seconds a code is valid, `30` by default +* `algorithm`: `\RobThree\Auth\Algorithm` case, `Sha1` by default +* `qrcodeprovider`: QR code provider, `\RobThree\Auth\Providers\Qr\EndroidQrCodeProvider` by default +* `rngprovider`: random number generator provider, `null` for the default one -`OneTimePasswordAuthenticator.qrcodeprovider` => `YOUR QR CODE PROVIDER` +The default QR code provider needs `endroid/qr-code`. To use another one, set +`OneTimePasswordAuthenticator.qrcodeprovider` in any config file. To get a list of available +providers please visit [RobThree/TwoFactorAuth](https://robthree.github.io/TwoFactorAuth/qr-codes.html) +documentation. -To get a list of available providers please visit [RobThree/TwoFactorAuth](https://robthree.github.io/TwoFactorAuth/qr-codes.html) documentation. +The Webauthn processor is configured with the `Webauthn2fa` key: `enabled`, `appName`, `id` (defaults +to the current domain), `checker` and `startAction`. The url of each processor (`OneTimePasswordAuthenticator.verifyAction`, `Webauthn2fa.startAction`, @@ -26,3 +38,5 @@ Processors * `OneTimePassword` - Authenticator is an authenticator app used as part of a two-factor/multi-factor authentication (2FA/MFA) scheme. It acts as an example of a “something you have” factor by generating one-time passwords (OTPs) on a smartphone or other mobile device. * `Webauthn2fa` - WebAuthn is a browser-based API that allows for web applications to simplify and secure user authentication by using registered devices (phones, laptops, etc) as factors. It uses public key cryptography to protect users from advanced phishing attacks. +* `U2F` - Deprecated, browsers no longer support U2F, use Webauthn instead. Configured with the `U2f` + key (`enabled`, `startAction`). diff --git a/Docs/Home.md b/Docs/Home.md index 2aeb858..cee3432 100644 --- a/Docs/Home.md +++ b/Docs/Home.md @@ -1,11 +1,10 @@ Home ==== -* [Authentication](Documentation/Authentication.md) - * [Two Factor](Documentation/TwoFactor.md) -* [Authorization](Documentation/Authorization.md) -* [Social](Documentation/Social.md) -* [SimpleRbacAuthorize](Documentation/SimpleRbacAuthorize.md) RBAC Authorize based on configuration - * [Rbac](Documentation/Rbac.md) Standalone RBAC permissions class +* [Authentication](Documentation/Authentication.md) Authenticators, identifiers and the authentication service + * [Two Factor](Documentation/TwoFactor.md) One time password and Webauthn two factor authentication +* [Authorization](Documentation/Authorization.md) RbacPolicy, SuperuserPolicy and CollectionPolicy + * [Rbac](Documentation/Rbac.md) RBAC permissions, used by RbacPolicy and RbacMiddleware * [OwnerRule](Documentation/OwnerRule.md) Rule to define ownership related permissions +* [Social](Documentation/Social.md) Social login with OAuth1, OAuth2 and OpenID Connect providers +* [Testing](Documentation/Testing.md) Test your permissions and roles configuration * [MigrationGuide](Documentation/MigrationGuide.md) Migration guide - diff --git a/LICENSE.txt b/LICENSE.txt index 21f3349..3fa6282 100644 --- a/LICENSE.txt +++ b/LICENSE.txt @@ -1,6 +1,6 @@ The MIT License -Copyright 2009-2019 +Copyright 2009-2026 Cake Development Corporation 1785 E. Sahara Avenue, Suite 490-423 Las Vegas, Nevada 89104 diff --git a/README.md b/README.md index 35af70b..dfb9202 100644 --- a/README.md +++ b/README.md @@ -6,9 +6,11 @@ CakeDC Auth Plugin Software License Build Status + Total Downloads @@ -21,25 +23,39 @@ CakeDC Auth Objects is a refactor of the existing Auth objects present in the Ca to let anyone else use them in their projects. It covers the following features: -* RBAC -* Remember me (Cookie) -* ApiAuthenticate for simple token based login +* RBAC: permissions based on roles, prefixes, plugins, controllers and actions, with custom rules, + enforced by `RbacMiddleware` or by the `RbacPolicy`, `SuperuserPolicy` and `CollectionPolicy` + policies for [cakephp/authorization](https://github.com/cakephp/authorization) +* Authenticators for [cakephp/authentication](https://github.com/cakephp/authentication): form login + with reCaptcha, remember me cookie, one time token (magic link) and social login +* Two factor authentication: one time password (Google Authenticator and similar apps) and Webauthn +* Social login with OAuth1, OAuth2 and OpenID Connect providers: Amazon, Azure, Cognito, + Facebook, Github, Google, Keycloak, LinkedIn (OpenID Connect) and Twitter. The Instagram, LinkedIn + (legacy), Pinterest and Tumblr mappers are deprecated Requirements ------------ -* CakePHP 5.4.0+ -* PHP 8.2+ +Version 11.x requires: -Versions and branches ---------------------- +* PHP 8.2 or higher +* CakePHP 5.4 or higher +* [cakephp/authentication](https://github.com/cakephp/authentication) 3.3 or higher -| CakePHP | CakeDC Auth Plugin | Tag | Notes | -| :-------------: | :------------------------: | :--: | :---- | -| ^5.4 | [11.0](https://github.com/cakedc/auth/tree/11.next-cake5.4) | 11.0.0 | stable | -| ^4.3 | [7.0](https://github.com/cakedc/auth/tree/7.next-cake4) | 7.0.0 | stable | -| ^4.0 <4.3 | [6.0](https://github.com/cakedc/auth/tree/6.next-cake4) | 6.0.2 | stable | -| ^3.7 <4.0.0 | [5.0](https://github.com/cakedc/auth/tree/5.next) | 5.0.0 | stable | +Optional features need additional packages, for example `cakephp/authorization` for the policies, +`league/oauth2-client` and the provider packages for social login, or `robthree/twofactorauth` for +one time passwords. See the `suggest` section of `composer.json` for the full list. + +Supported versions +------------------ + +| CakeDC Auth | Branch | Latest tag | CakePHP | PHP | Support | +| :---------- | :----- | :--------- | :------ | :-- | :------ | +| 11.x | [11.next-cake5.4](https://github.com/cakedc/auth/tree/11.next-cake5.4) | 11.1.0 | ^5.4 | >= 8.2 | Bug and security fixes | +| 10.x | [10.next-cake5](https://github.com/cakedc/auth/tree/10.next-cake5) | 10.1.4 | ^5.0 | >= 8.1 | Security fixes only | +| 9.x | [9.next-cake4](https://github.com/cakedc/auth/tree/9.next-cake4) | 9.1.0 | ^4.3 | >= 7.4 | Security fixes only | + +Version 11.0.0 supports CakePHP ^5.3. Older versions are not supported, upgrade to one of the versions above. Documentation @@ -63,6 +79,6 @@ If you'd like to contribute new features, enhancements or bug fixes to the plugi License ------- -Copyright 2017 Cake Development Corporation (CakeDC). All rights reserved. +Copyright 2017 - 2026 Cake Development Corporation (CakeDC). All rights reserved. Licensed under the [MIT](http://www.opensource.org/licenses/mit-license.php) License. Redistributions of the source code included in this repository must retain the copyright notice found in each file. diff --git a/composer.json b/composer.json index d5cbeec..e9f9427 100644 --- a/composer.json +++ b/composer.json @@ -78,7 +78,7 @@ "@stan", "@psalm" ], - "cs-check": "phpcs -n -p --standard=vendor/cakephp/cakephp-codesniffer/CakePHP ./src ./tests", + "cs-check": "phpcs -p --standard=vendor/cakephp/cakephp-codesniffer/CakePHP ./src ./tests", "cs-fix": "phpcbf --standard=vendor/cakephp/cakephp-codesniffer/CakePHP ./src ./tests", "test": "phpunit --stderr", "stan": "vendor/bin/phpstan analyse src/", diff --git a/config/auth.php b/config/auth.php index 49ceb60..593eed4 100644 --- a/config/auth.php +++ b/config/auth.php @@ -36,7 +36,7 @@ 'callbackLinkSocialUri' => Router::fullBaseUrl() . '/callback-link-social/twitter', ], ], - // Deprecated, LinkedIn switched to OpenID-Connect and OAuth2 is no longer working properly + // Deprecated: LinkedIn retired this API, use linkedInOpenIDConnect 'linkedIn' => [ 'service' => 'CakeDC\Auth\Social\Service\OAuth2Service', 'className' => 'League\OAuth2\Client\Provider\LinkedIn', @@ -58,6 +58,7 @@ 'defaultScopes' => ['email', 'openid', 'profile'], ], ], + // Deprecated: the Instagram Basic Display API was shut down 'instagram' => [ 'service' => 'CakeDC\Auth\Social\Service\OAuth2Service', 'className' => 'League\OAuth2\Client\Provider\Instagram', @@ -103,11 +104,11 @@ 'service' => 'CakeDC\Auth\Social\Service\OAuth2Service', 'className' => 'Stevenmaguire\OAuth2\Client\Provider\Keycloak', 'mapper' => 'CakeDC\Auth\Social\Mapper\Keycloak', - 'rolesMap' => [ - 'CakeDc-Admin' => 'admin', - 'CakeDc-User' => 'user', - 'CakeDc-Worker' => 'user', - ], + // Keycloak realm role => application role, the first match wins. Without a map no role is set. + // 'rolesMap' => [ + // 'example-realm-admin' => 'admin', + // 'example-realm-user' => 'user', + // ], 'authParams' => ['scope' => ['openid', 'roles']], 'options' => [ 'redirectUri' => Router::fullBaseUrl() . '/auth/keycloak', diff --git a/phpstan.neon b/phpstan.neon index 9438ba6..d1eb790 100644 --- a/phpstan.neon +++ b/phpstan.neon @@ -1,12 +1,9 @@ parameters: - level: 6 + level: 8 treatPhpDocTypesAsCertain: false bootstrapFiles: - tests/bootstrap.php ignoreErrors: - - - identifier: new.static - reportUnmatched: false - identifier: missingType.iterableValue reportUnmatched: false @@ -17,14 +14,14 @@ parameters: # Public library trait identifier: trait.unused path: src/Traits/IsAuthorizedTrait.php - reportUnmatched: false + reportUnmatched: true - # Testsuite library trait identifier: trait.unused path: src/Test/BaseTestTrait.php - reportUnmatched: false + reportUnmatched: true - # U2F deprecated - classes removed but processor retained identifier: class.notFound path: src/Authentication/TwoFactorProcessor/U2FProcessor.php - reportUnmatched: false + reportUnmatched: true diff --git a/psalm-baseline.xml b/psalm-baseline.xml index 72d9925..b344076 100644 --- a/psalm-baseline.xml +++ b/psalm-baseline.xml @@ -1,292 +1,100 @@ + + + + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + - - - getU2fAuthenticationChecker()]]> - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - getMessage(), - )]]> - - - - - - - - - - - - - - - - - - - + + + - - - - - - getHeader('Accept')]]> - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + @@ -297,29 +105,12 @@ ])]]> - - - - - - - - - - - - - - - - - $id, @@ -329,205 +120,32 @@ getParsedBody()]]> - - - - - - - - - - + + + - - - - - - + + + - - - - - - - - _mapFields)]]> - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - _mapFields['avatar']))]]> - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/psalm.xml b/psalm.xml index 6f7ce96..16d7cc4 100644 --- a/psalm.xml +++ b/psalm.xml @@ -1,12 +1,18 @@ + @@ -17,93 +23,7 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + - \ No newline at end of file + diff --git a/src/AuthPlugin.php b/src/AuthPlugin.php index 38e34fa..6f58535 100644 --- a/src/AuthPlugin.php +++ b/src/AuthPlugin.php @@ -2,14 +2,15 @@ declare(strict_types=1); /** - * Copyright 2010 - 2019, Cake Development Corporation (https://www.cakedc.com) + * Copyright 2010 - 2026, Cake Development Corporation (https://www.cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2010 - 2019, Cake Development Corporation (https://www.cakedc.com) + * @copyright Copyright 2010 - 2026, Cake Development Corporation (https://www.cakedc.com) * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ + namespace CakeDC\Auth; use Cake\Core\BasePlugin; diff --git a/src/Authentication/AuthenticationService.php b/src/Authentication/AuthenticationService.php index 53f5763..94dcf4d 100644 --- a/src/Authentication/AuthenticationService.php +++ b/src/Authentication/AuthenticationService.php @@ -2,12 +2,12 @@ declare(strict_types=1); /** - * Copyright 2010 - 2019, Cake Development Corporation (https://www.cakedc.com) + * Copyright 2010 - 2026, Cake Development Corporation (https://www.cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2010 - 2019, Cake Development Corporation (https://www.cakedc.com) + * @copyright Copyright 2010 - 2026, Cake Development Corporation (https://www.cakedc.com) * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ @@ -46,8 +46,11 @@ class AuthenticationService extends BaseService * @param \Authentication\Authenticator\ResultInterface $result The original result * @return \Authentication\Authenticator\ResultInterface The result object. */ - protected function proceed2FA(TwoFactorProcessorInterface $processor, ServerRequestInterface $request, ResultInterface $result): ResultInterface - { + protected function proceed2FA( + TwoFactorProcessorInterface $processor, + ServerRequestInterface $request, + ResultInterface $result, + ): ResultInterface { $result = $processor->proceed($request, $result); $this->_successfulAuthenticator = null; diff --git a/src/Authentication/DefaultOneTimePasswordAuthenticationChecker.php b/src/Authentication/DefaultOneTimePasswordAuthenticationChecker.php index bed9cc9..2f7c7e8 100644 --- a/src/Authentication/DefaultOneTimePasswordAuthenticationChecker.php +++ b/src/Authentication/DefaultOneTimePasswordAuthenticationChecker.php @@ -2,14 +2,15 @@ declare(strict_types=1); /** - * Copyright 2010 - 2019, Cake Development Corporation (https://www.cakedc.com) + * Copyright 2010 - 2026, Cake Development Corporation (https://www.cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2010 - 2019, Cake Development Corporation (https://www.cakedc.com) + * @copyright Copyright 2010 - 2026, Cake Development Corporation (https://www.cakedc.com) * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ + namespace CakeDC\Auth\Authentication; use Cake\Core\Configure; diff --git a/src/Authentication/DefaultWebauthn2FAuthenticationChecker.php b/src/Authentication/DefaultWebauthn2FAuthenticationChecker.php index 670c902..cab241a 100644 --- a/src/Authentication/DefaultWebauthn2FAuthenticationChecker.php +++ b/src/Authentication/DefaultWebauthn2FAuthenticationChecker.php @@ -2,14 +2,15 @@ declare(strict_types=1); /** - * Copyright 2010 - 2019, Cake Development Corporation (https://www.cakedc.com) + * Copyright 2010 - 2026, Cake Development Corporation (https://www.cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2010 - 2018, Cake Development Corporation (https://www.cakedc.com) + * @copyright Copyright 2010 - 2026, Cake Development Corporation (https://www.cakedc.com) * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ + namespace CakeDC\Auth\Authentication; use Cake\Core\Configure; diff --git a/src/Authentication/Failure.php b/src/Authentication/Failure.php index 0086358..f7e4e9b 100644 --- a/src/Authentication/Failure.php +++ b/src/Authentication/Failure.php @@ -2,14 +2,15 @@ declare(strict_types=1); /** - * Copyright 2010 - 2019, Cake Development Corporation (https://www.cakedc.com) + * Copyright 2010 - 2026, Cake Development Corporation (https://www.cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2010 - 2019, Cake Development Corporation (https://www.cakedc.com) + * @copyright Copyright 2010 - 2026, Cake Development Corporation (https://www.cakedc.com) * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ + namespace CakeDC\Auth\Authentication; use Authentication\Authenticator\AuthenticatorInterface; diff --git a/src/Authentication/FailureInterface.php b/src/Authentication/FailureInterface.php index e4b42a0..26ad875 100644 --- a/src/Authentication/FailureInterface.php +++ b/src/Authentication/FailureInterface.php @@ -2,14 +2,15 @@ declare(strict_types=1); /** - * Copyright 2010 - 2019, Cake Development Corporation (https://www.cakedc.com) + * Copyright 2010 - 2026, Cake Development Corporation (https://www.cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2010 - 2019, Cake Development Corporation (https://www.cakedc.com) + * @copyright Copyright 2010 - 2026, Cake Development Corporation (https://www.cakedc.com) * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ + namespace CakeDC\Auth\Authentication; use Authentication\Authenticator\AuthenticatorInterface; diff --git a/src/Authentication/OneTimePasswordAuthenticationCheckerFactory.php b/src/Authentication/OneTimePasswordAuthenticationCheckerFactory.php index 80bd889..870845b 100644 --- a/src/Authentication/OneTimePasswordAuthenticationCheckerFactory.php +++ b/src/Authentication/OneTimePasswordAuthenticationCheckerFactory.php @@ -2,14 +2,15 @@ declare(strict_types=1); /** - * Copyright 2010 - 2019, Cake Development Corporation (https://www.cakedc.com) + * Copyright 2010 - 2026, Cake Development Corporation (https://www.cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2010 - 2019, Cake Development Corporation (https://www.cakedc.com) + * @copyright Copyright 2010 - 2026, Cake Development Corporation (https://www.cakedc.com) * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ + namespace CakeDC\Auth\Authentication; use Cake\Core\Configure; @@ -30,12 +31,15 @@ class OneTimePasswordAuthenticationCheckerFactory public function build(): OneTimePasswordAuthenticationCheckerInterface { $className = Configure::read('OneTimePasswordAuthenticator.checker'); - $interfaces = class_implements($className); $required = OneTimePasswordAuthenticationCheckerInterface::class; - if (in_array($required, $interfaces)) { + if (is_string($className) && is_subclass_of($className, $required)) { return new $className(); } - throw new InvalidArgumentException("Invalid config for 'OneTimePasswordAuthenticator.checker', '$className' does not implement '$required'"); + throw new InvalidArgumentException(sprintf( + "Invalid config for 'OneTimePasswordAuthenticator.checker', '%s' does not implement '%s'", + is_string($className) ? $className : get_debug_type($className), + $required, + )); } } diff --git a/src/Authentication/OneTimePasswordAuthenticationCheckerInterface.php b/src/Authentication/OneTimePasswordAuthenticationCheckerInterface.php index 81f41cc..e061038 100644 --- a/src/Authentication/OneTimePasswordAuthenticationCheckerInterface.php +++ b/src/Authentication/OneTimePasswordAuthenticationCheckerInterface.php @@ -2,14 +2,15 @@ declare(strict_types=1); /** - * Copyright 2010 - 2019, Cake Development Corporation (https://www.cakedc.com) + * Copyright 2010 - 2026, Cake Development Corporation (https://www.cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2010 - 2018, Cake Development Corporation (https://www.cakedc.com) + * @copyright Copyright 2010 - 2026, Cake Development Corporation (https://www.cakedc.com) * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ + namespace CakeDC\Auth\Authentication; interface OneTimePasswordAuthenticationCheckerInterface diff --git a/src/Authentication/TwoFactorProcessor/OneTimePasswordProcessor.php b/src/Authentication/TwoFactorProcessor/OneTimePasswordProcessor.php index 401f98f..ad3075d 100644 --- a/src/Authentication/TwoFactorProcessor/OneTimePasswordProcessor.php +++ b/src/Authentication/TwoFactorProcessor/OneTimePasswordProcessor.php @@ -2,14 +2,15 @@ declare(strict_types=1); /** - * Copyright 2010 - 2024, Cake Development Corporation (https://www.cakedc.com) + * Copyright 2010 - 2026, Cake Development Corporation (https://www.cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2010 - 2024, Cake Development Corporation (https://www.cakedc.com) + * @copyright Copyright 2010 - 2026, Cake Development Corporation (https://www.cakedc.com) * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ + namespace CakeDC\Auth\Authentication\TwoFactorProcessor; use Authentication\Authenticator\Result; diff --git a/src/Authentication/TwoFactorProcessor/U2FProcessor.php b/src/Authentication/TwoFactorProcessor/U2FProcessor.php index 23158f6..1d55dd8 100644 --- a/src/Authentication/TwoFactorProcessor/U2FProcessor.php +++ b/src/Authentication/TwoFactorProcessor/U2FProcessor.php @@ -2,14 +2,15 @@ declare(strict_types=1); /** - * Copyright 2010 - 2024, Cake Development Corporation (https://www.cakedc.com) + * Copyright 2010 - 2026, Cake Development Corporation (https://www.cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2010 - 2024, Cake Development Corporation (https://www.cakedc.com) + * @copyright Copyright 2010 - 2026, Cake Development Corporation (https://www.cakedc.com) * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ + namespace CakeDC\Auth\Authentication\TwoFactorProcessor; use Authentication\Authenticator\Result; diff --git a/src/Authentication/TwoFactorProcessor/Webauthn2faProcessor.php b/src/Authentication/TwoFactorProcessor/Webauthn2faProcessor.php index b23d686..ab357f3 100644 --- a/src/Authentication/TwoFactorProcessor/Webauthn2faProcessor.php +++ b/src/Authentication/TwoFactorProcessor/Webauthn2faProcessor.php @@ -2,14 +2,15 @@ declare(strict_types=1); /** - * Copyright 2010 - 2024, Cake Development Corporation (https://www.cakedc.com) + * Copyright 2010 - 2026, Cake Development Corporation (https://www.cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2010 - 2024, Cake Development Corporation (https://www.cakedc.com) + * @copyright Copyright 2010 - 2026, Cake Development Corporation (https://www.cakedc.com) * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ + namespace CakeDC\Auth\Authentication\TwoFactorProcessor; use Authentication\Authenticator\Result; diff --git a/src/Authentication/TwoFactorProcessorCollection.php b/src/Authentication/TwoFactorProcessorCollection.php index bd6f2e9..fdd0566 100644 --- a/src/Authentication/TwoFactorProcessorCollection.php +++ b/src/Authentication/TwoFactorProcessorCollection.php @@ -2,18 +2,20 @@ declare(strict_types=1); /** - * Copyright 2010 - 2024, Cake Development Corporation (https://www.cakedc.com) + * Copyright 2010 - 2026, Cake Development Corporation (https://www.cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2010 - 2024, Cake Development Corporation (https://www.cakedc.com) + * @copyright Copyright 2010 - 2026, Cake Development Corporation (https://www.cakedc.com) * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ + namespace CakeDC\Auth\Authentication; use ArrayIterator; use Countable; +use InvalidArgumentException; use IteratorAggregate; use Traversable; @@ -60,7 +62,14 @@ public function clear() public function addMany(array $processors) { foreach ($processors as $processor) { - if (is_string($processor) && is_subclass_of($processor, TwoFactorProcessorInterface::class)) { + if (is_string($processor)) { + if (!is_subclass_of($processor, TwoFactorProcessorInterface::class)) { + throw new InvalidArgumentException(sprintf( + 'Two factor processor %s does not implement %s', + $processor, + TwoFactorProcessorInterface::class, + )); + } $processor = new $processor(); } $this->add($processor); @@ -88,8 +97,7 @@ public function add(TwoFactorProcessorInterface $processor) /** * Implementation of IteratorAggregate. * - * @return \Traversable - * @psalm-return \Traversable + * @return \Traversable */ public function getIterator(): Traversable { diff --git a/src/Authentication/TwoFactorProcessorInterface.php b/src/Authentication/TwoFactorProcessorInterface.php index ccedd22..978ec5f 100644 --- a/src/Authentication/TwoFactorProcessorInterface.php +++ b/src/Authentication/TwoFactorProcessorInterface.php @@ -2,14 +2,15 @@ declare(strict_types=1); /** - * Copyright 2010 - 2024, Cake Development Corporation (https://www.cakedc.com) + * Copyright 2010 - 2026, Cake Development Corporation (https://www.cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2010 - 2024, Cake Development Corporation (https://www.cakedc.com) + * @copyright Copyright 2010 - 2026, Cake Development Corporation (https://www.cakedc.com) * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ + namespace CakeDC\Auth\Authentication; use Authentication\Authenticator\ResultInterface; diff --git a/src/Authentication/TwoFactorProcessorLoader.php b/src/Authentication/TwoFactorProcessorLoader.php index fe7bea7..5b5c025 100644 --- a/src/Authentication/TwoFactorProcessorLoader.php +++ b/src/Authentication/TwoFactorProcessorLoader.php @@ -2,14 +2,15 @@ declare(strict_types=1); /** - * Copyright 2010 - 2024, Cake Development Corporation (https://www.cakedc.com) + * Copyright 2010 - 2026, Cake Development Corporation (https://www.cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2010 - 2024, Cake Development Corporation (https://www.cakedc.com) + * @copyright Copyright 2010 - 2026, Cake Development Corporation (https://www.cakedc.com) * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ + namespace CakeDC\Auth\Authentication; use Cake\Core\Configure; diff --git a/src/Authentication/Webauthn2fAuthenticationCheckerFactory.php b/src/Authentication/Webauthn2fAuthenticationCheckerFactory.php index 3f12aa0..0be5cc2 100644 --- a/src/Authentication/Webauthn2fAuthenticationCheckerFactory.php +++ b/src/Authentication/Webauthn2fAuthenticationCheckerFactory.php @@ -2,14 +2,15 @@ declare(strict_types=1); /** - * Copyright 2010 - 2019, Cake Development Corporation (https://www.cakedc.com) + * Copyright 2010 - 2026, Cake Development Corporation (https://www.cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2010 - 2018, Cake Development Corporation (https://www.cakedc.com) + * @copyright Copyright 2010 - 2026, Cake Development Corporation (https://www.cakedc.com) * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ + namespace CakeDC\Auth\Authentication; use Cake\Core\Configure; @@ -30,12 +31,15 @@ class Webauthn2fAuthenticationCheckerFactory public function build(): Webauthn2fAuthenticationCheckerInterface { $className = Configure::read('Webauthn2fa.checker'); - $interfaces = class_implements($className); $required = Webauthn2fAuthenticationCheckerInterface::class; - if (in_array($required, $interfaces)) { + if (is_string($className) && is_subclass_of($className, $required)) { return new $className(); } - throw new InvalidArgumentException("Invalid config for 'Webauthn2fa.checker', '$className' does not implement '$required'"); + throw new InvalidArgumentException(sprintf( + "Invalid config for 'Webauthn2fa.checker', '%s' does not implement '%s'", + is_string($className) ? $className : get_debug_type($className), + $required, + )); } } diff --git a/src/Authentication/Webauthn2fAuthenticationCheckerInterface.php b/src/Authentication/Webauthn2fAuthenticationCheckerInterface.php index aff57ee..59219de 100644 --- a/src/Authentication/Webauthn2fAuthenticationCheckerInterface.php +++ b/src/Authentication/Webauthn2fAuthenticationCheckerInterface.php @@ -2,14 +2,15 @@ declare(strict_types=1); /** - * Copyright 2010 - 2019, Cake Development Corporation (https://www.cakedc.com) + * Copyright 2010 - 2026, Cake Development Corporation (https://www.cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2010 - 2019, Cake Development Corporation (https://www.cakedc.com) + * @copyright Copyright 2010 - 2026, Cake Development Corporation (https://www.cakedc.com) * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ + namespace CakeDC\Auth\Authentication; interface Webauthn2fAuthenticationCheckerInterface diff --git a/src/Authenticator/CookieAuthenticator.php b/src/Authenticator/CookieAuthenticator.php index 6698cb8..c33967a 100644 --- a/src/Authenticator/CookieAuthenticator.php +++ b/src/Authenticator/CookieAuthenticator.php @@ -2,12 +2,12 @@ declare(strict_types=1); /** - * Copyright 2010 - 2019, Cake Development Corporation (https://www.cakedc.com) + * Copyright 2010 - 2026, Cake Development Corporation (https://www.cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2010 - 2019, Cake Development Corporation (https://www.cakedc.com) + * @copyright Copyright 2010 - 2026, Cake Development Corporation (https://www.cakedc.com) * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ diff --git a/src/Authenticator/FormAuthenticator.php b/src/Authenticator/FormAuthenticator.php index 62462de..31600cc 100644 --- a/src/Authenticator/FormAuthenticator.php +++ b/src/Authenticator/FormAuthenticator.php @@ -2,12 +2,12 @@ declare(strict_types=1); /** - * Copyright 2010 - 2019, Cake Development Corporation (https://www.cakedc.com) + * Copyright 2010 - 2026, Cake Development Corporation (https://www.cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2010 - 2019, Cake Development Corporation (https://www.cakedc.com) + * @copyright Copyright 2010 - 2026, Cake Development Corporation (https://www.cakedc.com) * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ @@ -23,6 +23,7 @@ use CakeDC\Auth\Traits\ReCaptchaTrait; use InvalidArgumentException; use Psr\Http\Message\ServerRequestInterface; +use function Cake\I18n\__; class FormAuthenticator implements AuthenticatorInterface { @@ -83,8 +84,10 @@ public function getBaseAuthenticator(): AuthenticatorInterface * @param array $config Configuration settings. * @return \Authentication\Authenticator\AuthenticatorInterface */ - protected function createBaseAuthenticator(IdentifierInterface $identifier, array $config = []): AuthenticatorInterface - { + protected function createBaseAuthenticator( + IdentifierInterface $identifier, + array $config = [], + ): AuthenticatorInterface { unset($config['keyCheckEnabledRecaptcha']); if (!isset($config['baseClassName'])) { return new BaseFormAuthenticator($identifier, $config); @@ -95,6 +98,11 @@ protected function createBaseAuthenticator(IdentifierInterface $identifier, arra if (!class_exists($className)) { throw new InvalidArgumentException(__('Base class for FormAuthenticator {0} does not exist', $className)); } + if (!is_subclass_of($className, AuthenticatorInterface::class)) { + throw new InvalidArgumentException( + __('Base class for FormAuthenticator {0} must implement AuthenticatorInterface', $className), + ); + } return new $className($identifier, $config); } @@ -112,7 +120,8 @@ public function authenticate(ServerRequestInterface $request): ResultInterface { $result = $this->getBaseAuthenticator()->authenticate($request); $checkKey = $this->getConfig('keyCheckEnabledRecaptcha'); - if (!Configure::read($checkKey) || in_array($result->getStatus(), [Result::FAILURE_OTHER, Result::FAILURE_CREDENTIALS_MISSING])) { + $skippedStatuses = [Result::FAILURE_OTHER, Result::FAILURE_CREDENTIALS_MISSING]; + if (!Configure::read($checkKey) || in_array($result->getStatus(), $skippedStatuses)) { return $result; } diff --git a/src/Authenticator/OneTimeTokenAuthenticator.php b/src/Authenticator/OneTimeTokenAuthenticator.php index dcf5f45..59cf017 100644 --- a/src/Authenticator/OneTimeTokenAuthenticator.php +++ b/src/Authenticator/OneTimeTokenAuthenticator.php @@ -1,6 +1,16 @@ getAttribute('authentication'); - $status = $service->getResult() ? $service->getResult()->getStatus() : null; + $result = $service instanceof AuthenticationServiceInterface ? $service->getResult() : null; + if ($result === null) { + return $handler->handle($request); + } + $status = $result->getStatus(); $processors = TwoFactorProcessorLoader::processors(); $url = null; foreach ($processors as $processor) { diff --git a/src/Plugin.php b/src/Plugin.php index ee8b6dd..103b267 100644 --- a/src/Plugin.php +++ b/src/Plugin.php @@ -2,14 +2,15 @@ declare(strict_types=1); /** - * Copyright 2010 - 2019, Cake Development Corporation (https://www.cakedc.com) + * Copyright 2010 - 2026, Cake Development Corporation (https://www.cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2010 - 2019, Cake Development Corporation (https://www.cakedc.com) + * @copyright Copyright 2010 - 2026, Cake Development Corporation (https://www.cakedc.com) * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ + namespace CakeDC\Auth; /** diff --git a/src/Policy/CollectionPolicy.php b/src/Policy/CollectionPolicy.php index 2c7e68d..6aa23e0 100644 --- a/src/Policy/CollectionPolicy.php +++ b/src/Policy/CollectionPolicy.php @@ -2,12 +2,12 @@ declare(strict_types=1); /** - * Copyright 2010 - 2019, Cake Development Corporation (https://www.cakedc.com) + * Copyright 2010 - 2026, Cake Development Corporation (https://www.cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2010 - 2019, Cake Development Corporation (https://www.cakedc.com) + * @copyright Copyright 2010 - 2026, Cake Development Corporation (https://www.cakedc.com) * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ diff --git a/src/Policy/PolicyInterface.php b/src/Policy/PolicyInterface.php index 690b5ea..8d51ef6 100644 --- a/src/Policy/PolicyInterface.php +++ b/src/Policy/PolicyInterface.php @@ -2,12 +2,12 @@ declare(strict_types=1); /** - * Copyright 2010 - 2019, Cake Development Corporation (https://www.cakedc.com) + * Copyright 2010 - 2026, Cake Development Corporation (https://www.cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2010 - 2019, Cake Development Corporation (https://www.cakedc.com) + * @copyright Copyright 2010 - 2026, Cake Development Corporation (https://www.cakedc.com) * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ diff --git a/src/Policy/RbacPolicy.php b/src/Policy/RbacPolicy.php index 929d91a..12a5d78 100644 --- a/src/Policy/RbacPolicy.php +++ b/src/Policy/RbacPolicy.php @@ -2,12 +2,12 @@ declare(strict_types=1); /** - * Copyright 2010 - 2019, Cake Development Corporation (https://www.cakedc.com) + * Copyright 2010 - 2026, Cake Development Corporation (https://www.cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2010 - 2019, Cake Development Corporation (https://www.cakedc.com) + * @copyright Copyright 2010 - 2026, Cake Development Corporation (https://www.cakedc.com) * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ diff --git a/src/Policy/SuperuserPolicy.php b/src/Policy/SuperuserPolicy.php index ddfab1d..5c149bf 100644 --- a/src/Policy/SuperuserPolicy.php +++ b/src/Policy/SuperuserPolicy.php @@ -2,14 +2,15 @@ declare(strict_types=1); /** - * Copyright 2010 - 2019, Cake Development Corporation (https://www.cakedc.com) + * Copyright 2010 - 2026, Cake Development Corporation (https://www.cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2010 - 2019, Cake Development Corporation (https://www.cakedc.com) + * @copyright Copyright 2010 - 2026, Cake Development Corporation (https://www.cakedc.com) * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ + namespace CakeDC\Auth\Policy; use Authorization\IdentityInterface; diff --git a/src/Rbac/PermissionMatchResult.php b/src/Rbac/PermissionMatchResult.php index d556be7..310f27f 100644 --- a/src/Rbac/PermissionMatchResult.php +++ b/src/Rbac/PermissionMatchResult.php @@ -2,12 +2,12 @@ declare(strict_types=1); /** - * Copyright 2010 - 2019, Cake Development Corporation (https://www.cakedc.com) + * Copyright 2010 - 2026, Cake Development Corporation (https://www.cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2010 - 2019, Cake Development Corporation (https://www.cakedc.com) + * @copyright Copyright 2010 - 2026, Cake Development Corporation (https://www.cakedc.com) * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ diff --git a/src/Rbac/Permissions/AbstractProvider.php b/src/Rbac/Permissions/AbstractProvider.php index f7f195d..ed0efc8 100644 --- a/src/Rbac/Permissions/AbstractProvider.php +++ b/src/Rbac/Permissions/AbstractProvider.php @@ -2,12 +2,12 @@ declare(strict_types=1); /** - * Copyright 2010 - 2019, Cake Development Corporation (https://www.cakedc.com) + * Copyright 2010 - 2026, Cake Development Corporation (https://www.cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2010 - 2019, Cake Development Corporation (https://www.cakedc.com) + * @copyright Copyright 2010 - 2026, Cake Development Corporation (https://www.cakedc.com) * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ diff --git a/src/Rbac/Permissions/ConfigProvider.php b/src/Rbac/Permissions/ConfigProvider.php index 17b429e..40e3ace 100644 --- a/src/Rbac/Permissions/ConfigProvider.php +++ b/src/Rbac/Permissions/ConfigProvider.php @@ -2,12 +2,12 @@ declare(strict_types=1); /** - * Copyright 2010 - 2019, Cake Development Corporation (https://www.cakedc.com) + * Copyright 2010 - 2026, Cake Development Corporation (https://www.cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2010 - 2019, Cake Development Corporation (https://www.cakedc.com) + * @copyright Copyright 2010 - 2026, Cake Development Corporation (https://www.cakedc.com) * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ diff --git a/src/Rbac/Rbac.php b/src/Rbac/Rbac.php index ee6f7e0..dcdb7d0 100644 --- a/src/Rbac/Rbac.php +++ b/src/Rbac/Rbac.php @@ -2,12 +2,12 @@ declare(strict_types=1); /** - * Copyright 2010 - 2019, Cake Development Corporation (https://www.cakedc.com) + * Copyright 2010 - 2026, Cake Development Corporation (https://www.cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2010 - 2019, Cake Development Corporation (https://www.cakedc.com) + * @copyright Copyright 2010 - 2026, Cake Development Corporation (https://www.cakedc.com) * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ @@ -90,7 +90,9 @@ public function __construct(array $config = []) } else { $permissionsProviderClass = $this->getConfig('permissions_provider_class'); if (!is_subclass_of($permissionsProviderClass, AbstractProvider::class)) { - throw new RuntimeException(sprintf('Class "%s" must extend AbstractProvider', $permissionsProviderClass)); + throw new RuntimeException( + sprintf('Class "%s" must extend AbstractProvider', $permissionsProviderClass), + ); } $permissionsProvider = new $permissionsProviderClass([ 'autoload_config' => $this->getConfig('autoload_config'), @@ -178,8 +180,12 @@ public function checkPermissions(array|ArrayAccess $user, ServerRequestInterface * @return \CakeDC\Auth\Rbac\PermissionMatchResult|null Null if permission is discarded, PermissionMatchResult if a final * result is produced */ - protected function _matchPermission(array $permission, array|ArrayAccess $user, string $role, ServerRequestInterface $request): ?PermissionMatchResult - { + protected function _matchPermission( + array $permission, + array|ArrayAccess $user, + string $role, + ServerRequestInterface $request, + ): ?PermissionMatchResult { $issetController = isset($permission['controller']) || isset($permission['*controller']); $issetAction = isset($permission['action']) || isset($permission['*action']); $issetUser = isset($permission['user']) || isset($permission['*user']); @@ -248,9 +254,9 @@ protected function _matchPermission(array $permission, array|ArrayAccess $user, if ($key === 'allowed' || $key === 'bypassAuth') { $reason = sprintf( 'For %s --> Rule matched %s with result = %s', - json_encode($reserved), - json_encode($permission), - $return, + $this->_encodeForReason($reserved), + $this->_encodeForReason($permission), + $return ? 'true' : 'false', ); return new PermissionMatchResult($return, $reason); @@ -277,6 +283,19 @@ protected function _isRuleConfig(mixed $value): bool is_a($value['className'], Rule::class, true); } + /** + * Encode a value as json for the match reason + * + * @param mixed $value Value to encode. + * @return string + */ + protected function _encodeForReason(mixed $value): string + { + $json = json_encode($value, JSON_PARTIAL_OUTPUT_ON_ERROR); + + return $json === false ? 'null' : $json; + } + /** * Get the rule instance for a rule config array * diff --git a/src/Rbac/RbacInterface.php b/src/Rbac/RbacInterface.php index 58a4d02..4e04695 100644 --- a/src/Rbac/RbacInterface.php +++ b/src/Rbac/RbacInterface.php @@ -2,12 +2,12 @@ declare(strict_types=1); /** - * Copyright 2010 - 2019, Cake Development Corporation (https://www.cakedc.com) + * Copyright 2010 - 2026, Cake Development Corporation (https://www.cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2010 - 2019, Cake Development Corporation (https://www.cakedc.com) + * @copyright Copyright 2010 - 2026, Cake Development Corporation (https://www.cakedc.com) * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ diff --git a/src/Rbac/Rules/AbstractRule.php b/src/Rbac/Rules/AbstractRule.php index 513c0a7..7f62c8f 100644 --- a/src/Rbac/Rules/AbstractRule.php +++ b/src/Rbac/Rules/AbstractRule.php @@ -2,14 +2,15 @@ declare(strict_types=1); /** - * Copyright 2010 - 2019, Cake Development Corporation (https://www.cakedc.com) + * Copyright 2010 - 2026, Cake Development Corporation (https://www.cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2010 - 2019, Cake Development Corporation (https://www.cakedc.com) + * @copyright Copyright 2010 - 2026, Cake Development Corporation (https://www.cakedc.com) * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ + namespace CakeDC\Auth\Rbac\Rules; use ArrayAccess; @@ -81,7 +82,9 @@ protected function _getTableFromRequest(ServerRequestInterface $request): Table $modelClass = ($plugin ? $plugin . '.' : '') . $controller; if (empty($modelClass)) { - throw new OutOfBoundsException('Missing Table alias, we could not extract a default table from the request'); + throw new OutOfBoundsException( + 'Missing Table alias, we could not extract a default table from the request', + ); } return $this->fetchTable($modelClass); diff --git a/src/Rbac/Rules/OTPRule.php b/src/Rbac/Rules/OTPRule.php index cb68f59..3c96bff 100644 --- a/src/Rbac/Rules/OTPRule.php +++ b/src/Rbac/Rules/OTPRule.php @@ -1,13 +1,13 @@ getParsedBody() ?: []; break; default: - throw new RuntimeException(sprintf('TypeTableKey "%s" is invalid, please use "params", "data" or "query"', $tableKeyType)); + throw new RuntimeException(sprintf( + 'TypeTableKey "%s" is invalid, please use "params", "data" or "query"', + $tableKeyType, + )); } return Hash::get($requestKeyTypeData, $this->getConfig('tableIdParamsKey')); diff --git a/src/Rbac/Rules/Rule.php b/src/Rbac/Rules/Rule.php index 9721a92..62d032c 100644 --- a/src/Rbac/Rules/Rule.php +++ b/src/Rbac/Rules/Rule.php @@ -2,14 +2,15 @@ declare(strict_types=1); /** - * Copyright 2010 - 2019, Cake Development Corporation (https://www.cakedc.com) + * Copyright 2010 - 2026, Cake Development Corporation (https://www.cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2010 - 2019, Cake Development Corporation (https://www.cakedc.com) + * @copyright Copyright 2010 - 2026, Cake Development Corporation (https://www.cakedc.com) * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ + namespace CakeDC\Auth\Rbac\Rules; use ArrayAccess; diff --git a/src/Rbac/Rules/RuleRegistry.php b/src/Rbac/Rules/RuleRegistry.php index cd15f3f..ee25dbc 100644 --- a/src/Rbac/Rules/RuleRegistry.php +++ b/src/Rbac/Rules/RuleRegistry.php @@ -1,13 +1,13 @@ _mapFields)->each(function (string $mappedField, string $field) use (&$result, $rawData): void { + $mapField = function (string $mappedField, string $field) use (&$result, $rawData): void { $value = Hash::get($rawData, $mappedField); $function = '_' . Inflector::camelize($field); if (method_exists($this, $function)) { $value = $this->{$function}($rawData); } $result[$field] = $value; - }); + }; + collection($this->_mapFields)->each($mapField); $token = $rawData['token'] ?? null; if (empty($token) || !is_array($token) && !$token instanceof AccessToken) { return false; diff --git a/src/Social/Mapper/Amazon.php b/src/Social/Mapper/Amazon.php index 8676f5e..2908fac 100644 --- a/src/Social/Mapper/Amazon.php +++ b/src/Social/Mapper/Amazon.php @@ -2,12 +2,12 @@ declare(strict_types=1); /** - * Copyright 2010 - 2019, Cake Development Corporation (https://www.cakedc.com) + * Copyright 2010 - 2026, Cake Development Corporation (https://www.cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2010 - 2019, Cake Development Corporation (https://www.cakedc.com) + * @copyright Copyright 2010 - 2026, Cake Development Corporation (https://www.cakedc.com) * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ diff --git a/src/Social/Mapper/Azure.php b/src/Social/Mapper/Azure.php index 2a944a1..d4615de 100644 --- a/src/Social/Mapper/Azure.php +++ b/src/Social/Mapper/Azure.php @@ -2,12 +2,12 @@ declare(strict_types=1); /** - * Copyright 2010 - 2019, Cake Development Corporation (https://www.cakedc.com) + * Copyright 2010 - 2026, Cake Development Corporation (https://www.cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2010 - 2019, Cake Development Corporation (https://www.cakedc.com) + * @copyright Copyright 2010 - 2026, Cake Development Corporation (https://www.cakedc.com) * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ @@ -37,4 +37,19 @@ protected function _link(mixed $rawData): string { return '#'; } + + /** + * The email is only validated when Azure reports it as verified + * + * `upn` and `email` can be set by any tenant administrator, so their presence does not prove + * the user owns the email. Only the `email_verified` and `xms_edov` (email domain owner verified) + * claims are trusted. + * + * @param mixed $rawData raw data + * @return bool + */ + protected function _validated(mixed $rawData): bool + { + return ($rawData['email_verified'] ?? null) === true || ($rawData['xms_edov'] ?? null) === true; + } } diff --git a/src/Social/Mapper/Cognito.php b/src/Social/Mapper/Cognito.php index a6b5dc9..7fb30e5 100644 --- a/src/Social/Mapper/Cognito.php +++ b/src/Social/Mapper/Cognito.php @@ -2,12 +2,12 @@ declare(strict_types=1); /** - * Copyright 2010 - 2019, Cake Development Corporation (https://www.cakedc.com) + * Copyright 2010 - 2026, Cake Development Corporation (https://www.cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2010 - 2019, Cake Development Corporation (https://www.cakedc.com) + * @copyright Copyright 2010 - 2026, Cake Development Corporation (https://www.cakedc.com) * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ diff --git a/src/Social/Mapper/Facebook.php b/src/Social/Mapper/Facebook.php index 8cbdd58..8e8beaa 100644 --- a/src/Social/Mapper/Facebook.php +++ b/src/Social/Mapper/Facebook.php @@ -2,12 +2,12 @@ declare(strict_types=1); /** - * Copyright 2010 - 2019, Cake Development Corporation (https://www.cakedc.com) + * Copyright 2010 - 2026, Cake Development Corporation (https://www.cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2010 - 2019, Cake Development Corporation (https://www.cakedc.com) + * @copyright Copyright 2010 - 2026, Cake Development Corporation (https://www.cakedc.com) * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ diff --git a/src/Social/Mapper/Github.php b/src/Social/Mapper/Github.php index ed27d63..4356dbc 100644 --- a/src/Social/Mapper/Github.php +++ b/src/Social/Mapper/Github.php @@ -2,12 +2,12 @@ declare(strict_types=1); /** - * Copyright 2010 - 2025, Cake Development Corporation (https://www.cakedc.com) + * Copyright 2010 - 2026, Cake Development Corporation (https://www.cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2010 - 2025, Cake Development Corporation (https://www.cakedc.com) + * @copyright Copyright 2010 - 2026, Cake Development Corporation (https://www.cakedc.com) * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ diff --git a/src/Social/Mapper/Google.php b/src/Social/Mapper/Google.php index 5a2443f..8bdbada 100644 --- a/src/Social/Mapper/Google.php +++ b/src/Social/Mapper/Google.php @@ -2,12 +2,12 @@ declare(strict_types=1); /** - * Copyright 2010 - 2019, Cake Development Corporation (https://www.cakedc.com) + * Copyright 2010 - 2026, Cake Development Corporation (https://www.cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2010 - 2019, Cake Development Corporation (https://www.cakedc.com) + * @copyright Copyright 2010 - 2026, Cake Development Corporation (https://www.cakedc.com) * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ diff --git a/src/Social/Mapper/Instagram.php b/src/Social/Mapper/Instagram.php index 590fe2f..167f480 100644 --- a/src/Social/Mapper/Instagram.php +++ b/src/Social/Mapper/Instagram.php @@ -2,24 +2,42 @@ declare(strict_types=1); /** - * Copyright 2010 - 2019, Cake Development Corporation (https://www.cakedc.com) + * Copyright 2010 - 2026, Cake Development Corporation (https://www.cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2010 - 2019, Cake Development Corporation (https://www.cakedc.com) + * @copyright Copyright 2010 - 2026, Cake Development Corporation (https://www.cakedc.com) * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Auth\Social\Mapper; use Cake\Utility\Hash; +use function Cake\Core\deprecationWarning; /** * Instagram Mapper + * + * @deprecated 11.1.0 The Instagram Basic Display API was shut down, there is no replacement for user login. Use the `facebook` provider for a Meta login. */ class Instagram extends AbstractMapper { + /** + * Constructor + * + * @param mixed $mapFields map fields + */ + public function __construct(mixed $mapFields = null) + { + deprecationWarning( + '11.1.0', + 'The Instagram mapper is deprecated, the Instagram Basic Display API was shut ' . + 'down. Use the `facebook` provider for a Meta login.', + ); + parent::__construct($mapFields); + } + /** * Url constants */ diff --git a/src/Social/Mapper/Keycloak.php b/src/Social/Mapper/Keycloak.php index 6c350d4..6799fe4 100644 --- a/src/Social/Mapper/Keycloak.php +++ b/src/Social/Mapper/Keycloak.php @@ -53,7 +53,7 @@ class Keycloak extends AbstractMapper /** * Constructor * - * @param mixed $mapFields map fields, defaults to `OAuth.providers.keycloak.mapFields` + * @param mixed $mapFields map fields merged over the Keycloak map, defaults to `OAuth.providers.keycloak.mapFields` * @param array|null $rolesMap roles map, defaults to `OAuth.providers.keycloak.rolesMap` */ public function __construct(mixed $mapFields = null, ?array $rolesMap = null) @@ -63,6 +63,10 @@ public function __construct(mixed $mapFields = null, ?array $rolesMap = null) if (is_array($rolesMap) && $rolesMap) { $this->_rolesMap = $rolesMap; } + // A partial map must not drop the `id`, `roles` and `validated` fields the role check depends on + if (is_array($mapFields)) { + $mapFields = array_merge($this->_mapFields, $mapFields); + } parent::__construct($mapFields); } diff --git a/src/Social/Mapper/LinkedIn.php b/src/Social/Mapper/LinkedIn.php index ecb5347..6cc68e1 100644 --- a/src/Social/Mapper/LinkedIn.php +++ b/src/Social/Mapper/LinkedIn.php @@ -2,19 +2,42 @@ declare(strict_types=1); /** - * Copyright 2010 - 2019, Cake Development Corporation (https://www.cakedc.com) + * Copyright 2010 - 2026, Cake Development Corporation (https://www.cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2010 - 2019, Cake Development Corporation (https://www.cakedc.com) + * @copyright Copyright 2010 - 2026, Cake Development Corporation (https://www.cakedc.com) * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Auth\Social\Mapper; +use function Cake\Core\deprecationWarning; + +/** + * LinkedIn Mapper + * + * @deprecated 11.1.0 LinkedIn retired the legacy Sign In with LinkedIn API, use the `linkedInOpenIDConnect` provider with the `LinkedInOpenIDConnect` mapper instead. + */ class LinkedIn extends AbstractMapper { + /** + * Constructor + * + * @param mixed $mapFields map fields + */ + public function __construct(mixed $mapFields = null) + { + deprecationWarning( + '11.1.0', + 'The LinkedIn mapper is deprecated, LinkedIn retired the legacy Sign In API. Use ' . + 'the `linkedInOpenIDConnect` provider with ' . + '`CakeDC\\Auth\\Social\\Mapper\\LinkedInOpenIDConnect` instead.', + ); + parent::__construct($mapFields); + } + /** * Map for provider fields * diff --git a/src/Social/Mapper/LinkedInOpenIDConnect.php b/src/Social/Mapper/LinkedInOpenIDConnect.php index 2eacf3e..ad86381 100644 --- a/src/Social/Mapper/LinkedInOpenIDConnect.php +++ b/src/Social/Mapper/LinkedInOpenIDConnect.php @@ -2,12 +2,12 @@ declare(strict_types=1); /** - * Copyright 2010 - 2019, Cake Development Corporation (https://www.cakedc.com) + * Copyright 2010 - 2026, Cake Development Corporation (https://www.cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2010 - 2019, Cake Development Corporation (https://www.cakedc.com) + * @copyright Copyright 2010 - 2026, Cake Development Corporation (https://www.cakedc.com) * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ diff --git a/src/Social/Mapper/Pinterest.php b/src/Social/Mapper/Pinterest.php index 94f7f84..5a0dcd6 100644 --- a/src/Social/Mapper/Pinterest.php +++ b/src/Social/Mapper/Pinterest.php @@ -2,19 +2,41 @@ declare(strict_types=1); /** - * Copyright 2010 - 2019, Cake Development Corporation (https://www.cakedc.com) + * Copyright 2010 - 2026, Cake Development Corporation (https://www.cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2010 - 2019, Cake Development Corporation (https://www.cakedc.com) + * @copyright Copyright 2010 - 2026, Cake Development Corporation (https://www.cakedc.com) * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Auth\Social\Mapper; +use function Cake\Core\deprecationWarning; + +/** + * Pinterest Mapper + * + * @deprecated 11.1.0 The mapper reads fields of the retired Pinterest API v1. + */ class Pinterest extends AbstractMapper { + /** + * Constructor + * + * @param mixed $mapFields map fields + */ + public function __construct(mixed $mapFields = null) + { + deprecationWarning( + '11.1.0', + 'The Pinterest mapper is deprecated, it reads fields of the retired Pinterest API ' . + 'v1.', + ); + parent::__construct($mapFields); + } + /** * Map for provider fields * diff --git a/src/Social/Mapper/Tumblr.php b/src/Social/Mapper/Tumblr.php index 0766465..74b3a80 100644 --- a/src/Social/Mapper/Tumblr.php +++ b/src/Social/Mapper/Tumblr.php @@ -2,22 +2,41 @@ declare(strict_types=1); /** - * Copyright 2010 - 2019, Cake Development Corporation (https://www.cakedc.com) + * Copyright 2010 - 2026, Cake Development Corporation (https://www.cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2010 - 2019, Cake Development Corporation (https://www.cakedc.com) + * @copyright Copyright 2010 - 2026, Cake Development Corporation (https://www.cakedc.com) * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Auth\Social\Mapper; +use function Cake\Core\deprecationWarning; + /** * Tumblr Mapper + * + * @deprecated 11.1.0 The user id is a crc32 of the nickname, it can collide and changes when the blog is renamed. */ class Tumblr extends AbstractMapper { + /** + * Constructor + * + * @param mixed $mapFields map fields + */ + public function __construct(mixed $mapFields = null) + { + deprecationWarning( + '11.1.0', + 'The Tumblr mapper is deprecated, its user id is a crc32 of the nickname, which ' . + 'can collide and changes when the blog is renamed.', + ); + parent::__construct($mapFields); + } + /** * Map for provider fields * diff --git a/src/Social/Mapper/Twitter.php b/src/Social/Mapper/Twitter.php index a472f3f..19cd4b8 100644 --- a/src/Social/Mapper/Twitter.php +++ b/src/Social/Mapper/Twitter.php @@ -2,12 +2,12 @@ declare(strict_types=1); /** - * Copyright 2010 - 2019, Cake Development Corporation (https://www.cakedc.com) + * Copyright 2010 - 2026, Cake Development Corporation (https://www.cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2010 - 2019, Cake Development Corporation (https://www.cakedc.com) + * @copyright Copyright 2010 - 2026, Cake Development Corporation (https://www.cakedc.com) * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ @@ -61,6 +61,6 @@ protected function _link(mixed $rawData): string */ protected function _avatar(mixed $rawData): string { - return str_replace('normal', 'bigger', Hash::get($rawData, $this->_mapFields['avatar'])); + return str_replace('normal', 'bigger', (string)Hash::get($rawData, $this->_mapFields['avatar'])); } } diff --git a/src/Social/ProviderConfig.php b/src/Social/ProviderConfig.php index 99abcc7..c560c31 100644 --- a/src/Social/ProviderConfig.php +++ b/src/Social/ProviderConfig.php @@ -2,12 +2,12 @@ declare(strict_types=1); /** - * Copyright 2010 - 2019, Cake Development Corporation (https://www.cakedc.com) + * Copyright 2010 - 2026, Cake Development Corporation (https://www.cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2010 - 2019, Cake Development Corporation (https://www.cakedc.com) + * @copyright Copyright 2010 - 2026, Cake Development Corporation (https://www.cakedc.com) * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ @@ -83,8 +83,10 @@ protected function _normalizeConfig(array &$config, string $alias, array $parent 'signature' => null, 'mapFields' => [], ] + $parent; + // OpenIDConnectService settings, only kept when the provider defines them + $optional = ['openid' => true]; - $config = array_intersect_key($config, $defaults); + $config = array_intersect_key($config, $defaults + $optional); $config += $defaults; array_walk($config, [$this, '_validateConfig']); diff --git a/src/Social/Service/OAuth1Service.php b/src/Social/Service/OAuth1Service.php index 8f5be8c..e86519c 100644 --- a/src/Social/Service/OAuth1Service.php +++ b/src/Social/Service/OAuth1Service.php @@ -2,12 +2,12 @@ declare(strict_types=1); /** - * Copyright 2010 - 2019, Cake Development Corporation (https://www.cakedc.com) + * Copyright 2010 - 2026, Cake Development Corporation (https://www.cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2010 - 2019, Cake Development Corporation (https://www.cakedc.com) + * @copyright Copyright 2010 - 2026, Cake Development Corporation (https://www.cakedc.com) * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ @@ -15,6 +15,7 @@ use BadMethodCallException; use Cake\Http\ServerRequest; +use InvalidArgumentException; use League\OAuth1\Client\Server\Server; use Psr\Http\Message\ServerRequestInterface; @@ -124,8 +125,12 @@ protected function setProvider(array $config): void $this->provider = $config['className']; } else { $class = $config['className']; + $provider = new $class($config['options'], $config['signature']); + if (!$provider instanceof Server) { + throw new InvalidArgumentException(sprintf('Provider class %s must extend %s', $class, Server::class)); + } - $this->provider = new $class($config['options'], $config['signature']); + $this->provider = $provider; } } } diff --git a/src/Social/Service/OAuth2Service.php b/src/Social/Service/OAuth2Service.php index aa090c2..ca8b0ff 100644 --- a/src/Social/Service/OAuth2Service.php +++ b/src/Social/Service/OAuth2Service.php @@ -2,12 +2,12 @@ declare(strict_types=1); /** - * Copyright 2010 - 2019, Cake Development Corporation (https://www.cakedc.com) + * Copyright 2010 - 2026, Cake Development Corporation (https://www.cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2010 - 2019, Cake Development Corporation (https://www.cakedc.com) + * @copyright Copyright 2010 - 2026, Cake Development Corporation (https://www.cakedc.com) * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ @@ -16,6 +16,7 @@ use BadMethodCallException; use Cake\Http\Exception\BadRequestException; use Cake\Http\ServerRequest; +use InvalidArgumentException; use League\OAuth2\Client\Provider\AbstractProvider; use Psr\Http\Message\ServerRequestInterface; @@ -137,8 +138,14 @@ protected function setProvider(array $config): void $this->provider = $config['className']; } else { $class = $config['className']; - - $this->provider = new $class($config['options'], $config['collaborators']); + $provider = new $class($config['options'], $config['collaborators']); + if (!$provider instanceof AbstractProvider) { + throw new InvalidArgumentException( + sprintf('Provider class %s must extend %s', $class, AbstractProvider::class), + ); + } + + $this->provider = $provider; } } } diff --git a/src/Social/Service/OAuthServiceAbstract.php b/src/Social/Service/OAuthServiceAbstract.php index 736a9b3..bca279c 100644 --- a/src/Social/Service/OAuthServiceAbstract.php +++ b/src/Social/Service/OAuthServiceAbstract.php @@ -2,12 +2,12 @@ declare(strict_types=1); /** - * Copyright 2010 - 2019, Cake Development Corporation (https://www.cakedc.com) + * Copyright 2010 - 2026, Cake Development Corporation (https://www.cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2010 - 2019, Cake Development Corporation (https://www.cakedc.com) + * @copyright Copyright 2010 - 2026, Cake Development Corporation (https://www.cakedc.com) * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ diff --git a/src/Social/Service/OpenIDConnectService.php b/src/Social/Service/OpenIDConnectService.php index 2329bb0..fd2332d 100644 --- a/src/Social/Service/OpenIDConnectService.php +++ b/src/Social/Service/OpenIDConnectService.php @@ -48,7 +48,8 @@ class OpenIDConnectService extends OAuth2Service /** * Default configuration. `openid` defaults target LinkedIn, override them per provider. * - * - `openid.baseUrl`: the `jwks_uri` from the discovery document must start with it. + * - `openid.baseUrl`: the `jwks_uri` from the discovery document must use its scheme, host and port, + * and a path below its path. * - `openid.url`: discovery document url. * - `openid.issuer`: expected `iss` claim, null to use the discovery document `issuer`. * - `openid.nonce`: send a nonce in the authorization request and validate it in the id token. @@ -151,6 +152,10 @@ protected function validateClaims(ServerRequest $request, array $claims): void if (!$clientId || !in_array($clientId, $audience, true)) { throw new BadRequestException('Invalid id token. Unexpected audience'); } + $authorizedParty = $claims['azp'] ?? null; + if (($authorizedParty !== null || count($audience) > 1) && $authorizedParty !== $clientId) { + throw new BadRequestException('Invalid id token. Unexpected authorized party'); + } if ($this->getConfig('openid.nonce')) { $session = $request->getSession(); @@ -199,7 +204,7 @@ protected function getIdTokenKeys(bool $refresh = false): array 'No `jwks_uri` in discover data. Unable to retrieve the JWT signature public key', ); } - if (!str_starts_with($jwksUri, (string)$this->getConfig('openid.baseUrl'))) { + if (!is_string($jwksUri) || !$this->isTrustedUrl($jwksUri, (string)$this->getConfig('openid.baseUrl'))) { throw new BadRequestException( 'Invalid `jwks_uri` in discover data. It is not pointing to ' . $this->getConfig('openid.baseUrl'), @@ -215,6 +220,37 @@ protected function getIdTokenKeys(bool $refresh = false): array return JWK::parseKeySet($jwksData, $this->getConfig('openid.jwk.defaultAlgorithm')); } + /** + * Check the url uses the scheme, host and port of the base url, and a path below its path + * + * @param string $url Url to check. + * @param string $baseUrl Trusted base url, `openid.baseUrl`. + * @return bool + */ + protected function isTrustedUrl(string $url, string $baseUrl): bool + { + $target = parse_url($url); + $base = parse_url($baseUrl); + if (!is_array($target) || !is_array($base)) { + return false; + } + $targetHost = strtolower($target['host'] ?? ''); + $baseHost = strtolower($base['host'] ?? ''); + if ($baseHost === '' || $targetHost !== $baseHost) { + return false; + } + if ( + strtolower($target['scheme'] ?? '') !== strtolower($base['scheme'] ?? '') || + ($target['port'] ?? null) !== ($base['port'] ?? null) + ) { + return false; + } + $basePath = rtrim($base['path'] ?? '', '/'); + $path = $target['path'] ?? '/'; + + return $basePath === '' || $path === $basePath || str_starts_with($path, $basePath . '/'); + } + /** * Get the OpenID discovery document, fetched once per service instance * diff --git a/src/Social/Service/ServiceFactory.php b/src/Social/Service/ServiceFactory.php index 596048f..710f9bc 100644 --- a/src/Social/Service/ServiceFactory.php +++ b/src/Social/Service/ServiceFactory.php @@ -2,12 +2,12 @@ declare(strict_types=1); /** - * Copyright 2010 - 2019, Cake Development Corporation (https://www.cakedc.com) + * Copyright 2010 - 2026, Cake Development Corporation (https://www.cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2010 - 2019, Cake Development Corporation (https://www.cakedc.com) + * @copyright Copyright 2010 - 2026, Cake Development Corporation (https://www.cakedc.com) * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ @@ -73,7 +73,10 @@ public function createFromProvider(string $provider): ServiceInterface public function createFromRequest(ServerRequestInterface $request): ServiceInterface { $params = $request->getAttribute('params'); - $provider = $params['provider'] ?? null; + $provider = is_array($params) ? ($params['provider'] ?? null) : null; + if (!is_string($provider) || $provider === '') { + throw new NotFoundException('Provider not found'); + } return $this->createFromProvider($provider); } diff --git a/src/Social/Service/ServiceInterface.php b/src/Social/Service/ServiceInterface.php index e43b11b..ebac5d1 100644 --- a/src/Social/Service/ServiceInterface.php +++ b/src/Social/Service/ServiceInterface.php @@ -2,12 +2,12 @@ declare(strict_types=1); /** - * Copyright 2010 - 2019, Cake Development Corporation (https://www.cakedc.com) + * Copyright 2010 - 2026, Cake Development Corporation (https://www.cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2010 - 2019, Cake Development Corporation (https://www.cakedc.com) + * @copyright Copyright 2010 - 2026, Cake Development Corporation (https://www.cakedc.com) * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ diff --git a/src/Test/BaseTestTrait.php b/src/Test/BaseTestTrait.php index dd0e0fd..8f1f724 100644 --- a/src/Test/BaseTestTrait.php +++ b/src/Test/BaseTestTrait.php @@ -1,11 +1,22 @@ get(Configure::read('Users.table', 'Users'))->get($id)->toArray(); - $this->session(['Auth' => ['User' => $data]]); + $this->session($this->_authSessionData($data)); } /** @@ -33,7 +44,23 @@ public function loginAsUserName(string $username): void { $data = TableRegistry::getTableLocator() ->get(Configure::read('Users.table', 'Users'))->findByUsername($username)->first()->toArray(); - $this->session(['Auth' => ['User' => $data]]); + $this->session($this->_authSessionData($data)); + } + + /** + * Session data of the logged in user + * + * The user is stored at the session key of the session authenticator, read from + * `Auth.Authenticators.Session.sessionKey` (CakeDC/Users configuration), `Auth` by default. + * + * @param array $user User data. + * @return array + */ + protected function _authSessionData(array $user): array + { + $sessionKey = (string)Configure::read('Auth.Authenticators.Session.sessionKey', 'Auth'); + + return Hash::insert([], $sessionKey, $user); } /** @@ -75,10 +102,10 @@ protected function _testPermissions( ), 0); } $this->loginAsUserName($username); - if ($ajax === 'ajax') { + if (strtolower($ajax) === 'ajax') { $_SERVER['HTTP_X_REQUESTED_WITH'] = 'XMLHttpRequest'; } - if ($method === 'post') { + if (strtolower($method) === 'post') { $this->enableCsrfToken(); $this->enableSecurityToken(); $this->post($url); diff --git a/src/Traits/IsAuthorizedTrait.php b/src/Traits/IsAuthorizedTrait.php index 865311d..9258d4d 100644 --- a/src/Traits/IsAuthorizedTrait.php +++ b/src/Traits/IsAuthorizedTrait.php @@ -2,12 +2,12 @@ declare(strict_types=1); /** - * Copyright 2010 - 2019, Cake Development Corporation (https://www.cakedc.com) + * Copyright 2010 - 2026, Cake Development Corporation (https://www.cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2010 - 2019, Cake Development Corporation (https://www.cakedc.com) + * @copyright Copyright 2010 - 2026, Cake Development Corporation (https://www.cakedc.com) * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ diff --git a/src/Traits/ReCaptchaTrait.php b/src/Traits/ReCaptchaTrait.php index a3a2371..c189a4f 100644 --- a/src/Traits/ReCaptchaTrait.php +++ b/src/Traits/ReCaptchaTrait.php @@ -2,12 +2,12 @@ declare(strict_types=1); /** - * Copyright 2010 - 2019, Cake Development Corporation (https://www.cakedc.com) + * Copyright 2010 - 2026, Cake Development Corporation (https://www.cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2010 - 2019, Cake Development Corporation (https://www.cakedc.com) + * @copyright Copyright 2010 - 2026, Cake Development Corporation (https://www.cakedc.com) * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ diff --git a/tests/TestCase/Authentication/TwoFactorProcessorCollectionTest.php b/tests/TestCase/Authentication/TwoFactorProcessorCollectionTest.php new file mode 100644 index 0000000..0410e5c --- /dev/null +++ b/tests/TestCase/Authentication/TwoFactorProcessorCollectionTest.php @@ -0,0 +1,54 @@ +assertCount(2, $collection); + foreach ($collection as $processor) { + $this->assertInstanceOf(OneTimePasswordProcessor::class, $processor); + } + } + + /** + * Test a class name that is not a two factor processor throws + * + * @return void + */ + public function testAddManyInvalidClass(): void + { + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('does not implement'); + + new TwoFactorProcessorCollection([stdClass::class]); + } +} diff --git a/tests/TestCase/Middleware/TwoFactorMiddlewareTest.php b/tests/TestCase/Middleware/TwoFactorMiddlewareTest.php index b879208..a701401 100644 --- a/tests/TestCase/Middleware/TwoFactorMiddlewareTest.php +++ b/tests/TestCase/Middleware/TwoFactorMiddlewareTest.php @@ -200,4 +200,43 @@ public function testInvokeNeedVerifyStringUrl(string $verifyAction, array $query $this->assertSame([$expected], $actual->getHeader('Location')); } + + /** + * @return array + */ + public static function noAuthenticationResultProvider(): array + { + return [ + 'no authentication service' => [false], + 'service without result' => [true], + ]; + } + + /** + * Test the request is passed on when there is no authentication result + * + * @param bool $withService add an authentication service without result + * @return void + */ + #[DataProvider('noAuthenticationResultProvider')] + public function testInvokeWithoutAuthenticationResult(bool $withService): void + { + $request = new ServerRequest(); + if ($withService) { + $service = $this->getMockBuilder(AuthenticationService::class) + ->onlyMethods(['getResult']) + ->getMock(); + $service->method('getResult')->willReturn(null); + $request = $request->withAttribute('authentication', $service); + } + $response = (new Response())->withStringBody('next'); + $handler = $this->getMockBuilder(Runner::class) + ->onlyMethods(['handle']) + ->getMock(); + $handler->expects($this->once()) + ->method('handle') + ->willReturn($response); + + $this->assertSame($response, $this->TwoFactorMiddleware->process($request, $handler)); + } } diff --git a/tests/TestCase/Rbac/RbacTest.php b/tests/TestCase/Rbac/RbacTest.php index 36f78f2..3149361 100644 --- a/tests/TestCase/Rbac/RbacTest.php +++ b/tests/TestCase/Rbac/RbacTest.php @@ -1440,4 +1440,46 @@ public function testGetPermissions() $this->rbac->setPermissions($permissions); $this->assertSame($permissions, $this->rbac->getPermissions()); } + + /** + * Test the match reason reports the result as true or false + * + * @return void + */ + public function testMatchReasonResult(): void + { + $request = $this->_requestFromArray(['controller' => 'Posts', 'action' => 'index']); + $user = ['id' => 1, 'role' => 'user']; + $method = (new ReflectionClass(Rbac::class))->getMethod('_matchPermission'); + + $allowed = $method->invoke(new Rbac(), [ + 'role' => 'user', 'controller' => 'Posts', 'action' => 'index', 'allowed' => true, + ], $user, 'user', $request); + $denied = $method->invoke(new Rbac(), [ + 'role' => 'user', 'controller' => 'Posts', 'action' => 'index', 'allowed' => false, + ], $user, 'user', $request); + + $this->assertStringEndsWith('with result = true', $allowed->getReason()); + $this->assertStringEndsWith('with result = false', $denied->getReason()); + } + + /** + * Only `true` or a callable in `bypassAuth` opens a permission to anonymous requests. A rule or + * rule config is only evaluated for logged in users. + * + * @return void + */ + public function testBypassAuthRuleOnlyForLoggedInUsers(): void + { + $request = $this->_requestFromArray(['controller' => 'Pages', 'action' => 'display']); + foreach ([new SampleRule(), ['className' => SampleRule::class]] as $bypass) { + $rbac = new Rbac(['permissions' => [[ + 'controller' => 'Pages', + 'action' => 'display', + 'bypassAuth' => $bypass, + ]]]); + $this->assertFalse($rbac->checkPermissions([], $request)); + $this->assertTrue($rbac->checkPermissions(['id' => 1, 'role' => 'user'], $request)); + } + } } diff --git a/tests/TestCase/Rbac/Rules/RuleRegistryTest.php b/tests/TestCase/Rbac/Rules/RuleRegistryTest.php index 4558e64..bc983f2 100644 --- a/tests/TestCase/Rbac/Rules/RuleRegistryTest.php +++ b/tests/TestCase/Rbac/Rules/RuleRegistryTest.php @@ -16,6 +16,7 @@ use Cake\TestSuite\TestCase; use CakeDC\Auth\Rbac\Rules\Owner; use CakeDC\Auth\Rbac\Rules\RuleRegistry; +use JsonException; /** * @property Owner Owner @@ -54,4 +55,15 @@ public function testClear() RuleRegistry::clear(); $this->assertEmpty(RuleRegistry::toArray()); } + + /** + * Rule options that can not be encoded throw a JsonException + * + * @return void + */ + public function testGetOptionsNotEncodable(): void + { + $this->expectException(JsonException::class); + RuleRegistry::get(Owner::class, ['value' => INF]); + } } diff --git a/tests/TestCase/Social/Mapper/AzureTest.php b/tests/TestCase/Social/Mapper/AzureTest.php index 795df00..d48c0fe 100644 --- a/tests/TestCase/Social/Mapper/AzureTest.php +++ b/tests/TestCase/Social/Mapper/AzureTest.php @@ -16,6 +16,7 @@ use Cake\TestSuite\TestCase; use CakeDC\Auth\Social\Mapper\Azure; use League\OAuth2\Client\Token\AccessToken; +use PHPUnit\Framework\Attributes\DataProvider; class AzureTest extends TestCase { @@ -67,7 +68,7 @@ public function testMap() 'link' => '#', 'bio' => null, 'locale' => null, - 'validated' => true, + 'validated' => false, 'credentials' => [ 'token' => 'test-token', 'secret' => null, @@ -76,4 +77,37 @@ public function testMap() 'raw' => $rawData, ], $user); } + + /** + * @return array + */ + public static function validatedProvider(): array + { + return [ + 'only upn' => [[], false], + 'email_verified true' => [['email_verified' => true], true], + 'email_verified false' => [['email_verified' => false], false], + 'email_verified string' => [['email_verified' => 'true'], false], + 'xms_edov true' => [['xms_edov' => true], true], + ]; + } + + /** + * The email is only validated when Azure reports it as verified + * + * @param array $claims extra claims + * @param bool $expected expected validated value + * @return void + */ + #[DataProvider('validatedProvider')] + public function testValidated(array $claims, bool $expected): void + { + $rawData = $claims + [ + 'token' => new AccessToken(['access_token' => 'test-token']), + 'sub' => 'user-id', + 'upn' => 'test@example.com', + ]; + + $this->assertSame($expected, (new Azure())($rawData)['validated']); + } } diff --git a/tests/TestCase/Social/Mapper/DeprecatedMappersTest.php b/tests/TestCase/Social/Mapper/DeprecatedMappersTest.php new file mode 100644 index 0000000..f372a1e --- /dev/null +++ b/tests/TestCase/Social/Mapper/DeprecatedMappersTest.php @@ -0,0 +1,69 @@ +}> + */ + public static function deprecatedMapperProvider(): array + { + return [ + 'LinkedIn' => [LinkedIn::class], + 'Instagram' => [Instagram::class], + 'Pinterest' => [Pinterest::class], + 'Tumblr' => [Tumblr::class], + ]; + } + + /** + * Test the deprecated mappers emit a deprecation warning and still work + * + * @param class-string<\CakeDC\Auth\Social\Mapper\AbstractMapper> $className mapper class + * @return void + */ + #[DataProvider('deprecatedMapperProvider')] + public function testDeprecationWarning(string $className): void + { + $mapper = null; + $this->deprecated(function () use (&$mapper, $className): void { + $mapper = new $className(); + }); + + $this->assertInstanceOf(AbstractMapper::class, $mapper); + } + + /** + * Test the deprecation warning is raised + * + * @param class-string<\CakeDC\Auth\Social\Mapper\AbstractMapper> $className mapper class + * @return void + */ + #[DataProvider('deprecatedMapperProvider')] + public function testDeprecationMessage(string $className): void + { + $this->expectDeprecationMessageMatches('/mapper is deprecated/', function () use ($className): void { + new $className(); + }); + } +} diff --git a/tests/TestCase/Social/Mapper/InstagramTest.php b/tests/TestCase/Social/Mapper/InstagramTest.php index d9766e6..5587340 100644 --- a/tests/TestCase/Social/Mapper/InstagramTest.php +++ b/tests/TestCase/Social/Mapper/InstagramTest.php @@ -49,7 +49,10 @@ public function testMap() ], 'bio' => '', ]; - $providerMapper = new Instagram(); + $providerMapper = null; + $this->deprecated(function () use (&$providerMapper): void { + $providerMapper = new Instagram(); + }); $user = $providerMapper($rawData); $this->assertEquals([ 'id' => '1', diff --git a/tests/TestCase/Social/Mapper/KeycloakTest.php b/tests/TestCase/Social/Mapper/KeycloakTest.php index 81ec8d0..d6e8c90 100644 --- a/tests/TestCase/Social/Mapper/KeycloakTest.php +++ b/tests/TestCase/Social/Mapper/KeycloakTest.php @@ -151,4 +151,22 @@ public function testMissingRoles(): void (new Keycloak())($rawData); } + + /** + * A partial mapFields config is merged over the Keycloak map, the role check keeps working + * + * @return void + */ + public function testPartialMapFieldsKeepRoleCheck(): void + { + Configure::write('OAuth.providers.keycloak.mapFields', ['username' => 'email']); + + $user = (new Keycloak())($this->rawData(['CakeDc-Admin'])); + $this->assertSame('test@example.com', $user['username']); + $this->assertSame('f4b8c1a2', $user['id']); + $this->assertSame('admin', $user['roles']); + + $this->expectException(UnexpectedValueException::class); + (new Keycloak())($this->rawData(['nobody'])); + } } diff --git a/tests/TestCase/Social/Mapper/LinkedInTest.php b/tests/TestCase/Social/Mapper/LinkedInTest.php index 2e3fc64..74c4260 100644 --- a/tests/TestCase/Social/Mapper/LinkedInTest.php +++ b/tests/TestCase/Social/Mapper/LinkedInTest.php @@ -52,7 +52,10 @@ public function testMap() 'pictureUrl' => 'https://media.licdn.com/mpr/mprx/test.jpg', 'publicProfileUrl' => 'https://www.linkedin.com/in/test', ]; - $providerMapper = new LinkedIn(); + $providerMapper = null; + $this->deprecated(function () use (&$providerMapper): void { + $providerMapper = new LinkedIn(); + }); $user = $providerMapper($rawData); $this->assertEquals([ 'id' => '1', diff --git a/tests/TestCase/Social/Service/OAuth1ServiceTest.php b/tests/TestCase/Social/Service/OAuth1ServiceTest.php index f751a4e..ae229d4 100644 --- a/tests/TestCase/Social/Service/OAuth1ServiceTest.php +++ b/tests/TestCase/Social/Service/OAuth1ServiceTest.php @@ -13,6 +13,7 @@ namespace CakeDC\Auth\Test\TestCase\Social\Service; +use Cake\Collection\Collection; use Cake\Core\Configure; use Cake\Http\ServerRequest; use Cake\Http\ServerRequestFactory; @@ -21,6 +22,7 @@ use CakeDC\Auth\Social\Mapper\Twitter as TwitterMapper; use CakeDC\Auth\Social\Service\OAuth1Service; use CakeDC\Auth\Social\Service\ServiceInterface; +use InvalidArgumentException; use Laminas\Diactoros\Uri; use League\OAuth1\Client\Credentials\TemporaryCredentials; use League\OAuth1\Client\Credentials\TokenCredentials; @@ -360,4 +362,22 @@ public function testGetUser() ]; $this->assertEquals($expected, $actual); } + + /** + * Test a provider className of the wrong type throws + * + * @return void + */ + public function testConstructInvalidProviderClass(): void + { + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('must extend'); + + new OAuth1Service([ + 'className' => Collection::class, + 'mapper' => null, + 'options' => [], + 'signature' => null, + ]); + } } diff --git a/tests/TestCase/Social/Service/OAuth2ServiceTest.php b/tests/TestCase/Social/Service/OAuth2ServiceTest.php index 09afdfe..30a0523 100644 --- a/tests/TestCase/Social/Service/OAuth2ServiceTest.php +++ b/tests/TestCase/Social/Service/OAuth2ServiceTest.php @@ -13,6 +13,7 @@ namespace CakeDC\Auth\Test\TestCase\Social\Service; +use Cake\Collection\Collection; use Cake\Core\Configure; use Cake\Http\Exception\BadRequestException; use Cake\Http\ServerRequest; @@ -22,6 +23,7 @@ use CakeDC\Auth\Social\Mapper\Facebook as FacebookMapper; use CakeDC\Auth\Social\Service\OAuth2Service; use CakeDC\Auth\Social\Service\ServiceInterface; +use InvalidArgumentException; use Laminas\Diactoros\Uri; use League\OAuth2\Client\Provider\Facebook; use League\OAuth2\Client\Provider\FacebookUser; @@ -406,4 +408,22 @@ public function testGetUserWithoutCode() $this->expectException(BadRequestException::class); $this->Service->getUser($this->Request); } + + /** + * Test a provider className of the wrong type throws + * + * @return void + */ + public function testConstructInvalidProviderClass(): void + { + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('must extend'); + + new OAuth2Service([ + 'className' => Collection::class, + 'mapper' => null, + 'options' => [], + 'collaborators' => [], + ]); + } } diff --git a/tests/TestCase/Social/Service/OpenIDConnectServiceTest.php b/tests/TestCase/Social/Service/OpenIDConnectServiceTest.php index 8f9eee9..4d3e81b 100644 --- a/tests/TestCase/Social/Service/OpenIDConnectServiceTest.php +++ b/tests/TestCase/Social/Service/OpenIDConnectServiceTest.php @@ -29,6 +29,7 @@ use League\OAuth2\Client\Token\AccessToken; use PHPUnit\Framework\Attributes\AllowMockObjectsWithoutExpectations; use PHPUnit\Framework\Attributes\DataProvider; +use ReflectionMethod; #[AllowMockObjectsWithoutExpectations] class OpenIDConnectServiceTest extends TestCase @@ -322,6 +323,11 @@ public static function invalidClaimsProvider(): array 'missing audience' => [array_diff_key($valid, ['aud' => true]), 'Unexpected audience'], 'wrong nonce' => [['nonce' => 'other'] + $valid, 'Nonce mismatch'], 'missing nonce' => [array_diff_key($valid, ['nonce' => true]), 'Nonce mismatch'], + 'other authorized party' => [['azp' => 'other-client'] + $valid, 'Unexpected authorized party'], + 'several audiences without azp' => [ + ['aud' => ['__CLIENT_ID__', 'other-client']] + $valid, + 'Unexpected authorized party', + ], ]; } @@ -776,4 +782,58 @@ public function testGetAuthorizationUrlWithoutNonce(): void $this->assertSame('http://example.com/auth', $this->Service->getAuthorizationUrl($this->Request)); $this->assertNull($this->Request->getSession()->read(OpenIDConnectService::SESSION_NONCE_KEY)); } + + /** + * Test a token for several audiences is valid when `azp` is the client id + * + * @return void + */ + public function testGetUserSeveralAudiencesWithAuthorizedParty(): void + { + $payload = [ + 'iss' => 'https://www.linkedin.com/oauth', + 'aud' => ['__CLIENT_ID__', 'other-client'], + 'azp' => '__CLIENT_ID__', + 'nonce' => '__NONCE__', + ]; + $this->prepareIdToken($payload); + + $this->assertSame('__CLIENT_ID__', $this->Service->getUser($this->Request)['azp']); + } + + /** + * @return array + */ + public static function trustedUrlProvider(): array + { + return [ + 'same host' => ['https://www.linkedin.com/oauth/openid/jwks', 'https://www.linkedin.com/', true], + 'below base path' => ['https://idp.example/realms/a/certs', 'https://idp.example/realms/a', true], + 'base path itself' => ['https://idp.example/realms/a', 'https://idp.example/realms/a/', true], + 'host case' => ['https://IDP.example/certs', 'https://idp.example', true], + 'host prefix' => ['https://idp.example.evil.com/certs', 'https://idp.example', false], + 'user info trick' => ['https://idp.example@evil.com/certs', 'https://idp.example', false], + 'other scheme' => ['http://idp.example/certs', 'https://idp.example', false], + 'other port' => ['https://idp.example:8443/certs', 'https://idp.example', false], + 'sibling path' => ['https://idp.example/realms/ab/certs', 'https://idp.example/realms/a', false], + 'empty base url' => ['https://evil.com/certs', '', false], + 'relative url' => ['/certs', 'https://idp.example', false], + ]; + } + + /** + * Test the jwks_uri must use the scheme, host and port of `openid.baseUrl` + * + * @param string $url url to check + * @param string $baseUrl base url + * @param bool $expected expected result + * @return void + */ + #[DataProvider('trustedUrlProvider')] + public function testIsTrustedUrl(string $url, string $baseUrl, bool $expected): void + { + $method = new ReflectionMethod(OpenIDConnectService::class, 'isTrustedUrl'); + + $this->assertSame($expected, $method->invoke($this->Service, $url, $baseUrl)); + } } diff --git a/tests/TestCase/Social/Service/ServiceFactoryTest.php b/tests/TestCase/Social/Service/ServiceFactoryTest.php index ca90fc8..5d60211 100644 --- a/tests/TestCase/Social/Service/ServiceFactoryTest.php +++ b/tests/TestCase/Social/Service/ServiceFactoryTest.php @@ -18,12 +18,16 @@ use Cake\Http\ServerRequestFactory; use Cake\TestSuite\TestCase; use CakeDC\Auth\Social\Mapper\Facebook as FacebookMapper; +use CakeDC\Auth\Social\Mapper\LinkedInOpenIDConnect; use CakeDC\Auth\Social\Mapper\Twitter as TwitterMapper; use CakeDC\Auth\Social\Service\OAuth1Service; use CakeDC\Auth\Social\Service\OAuth2Service; +use CakeDC\Auth\Social\Service\OpenIDConnectService; use CakeDC\Auth\Social\Service\ServiceFactory; use League\OAuth1\Client\Server\Twitter; use League\OAuth2\Client\Provider\Facebook; +use League\OAuth2\Client\Provider\GenericProvider; +use PHPUnit\Framework\Attributes\DataProvider; class ServiceFactoryTest extends TestCase { @@ -268,4 +272,70 @@ public function testCreateFromRequestProviderNotEnabled() $this->expectException(NotFoundException::class); $this->Factory->createFromRequest($request); } + + /** + * @return array + */ + public static function missingProviderParamsProvider(): array + { + return [ + 'no params' => [[]], + 'no provider' => [['controller' => 'Users', 'action' => 'socialLogin']], + 'empty provider' => [['provider' => '']], + ]; + } + + /** + * Test createFromRequest without a provider route param + * + * @param mixed $params request params + * @return void + */ + #[DataProvider('missingProviderParamsProvider')] + public function testCreateFromRequestMissingProvider(mixed $params): void + { + $request = ServerRequestFactory::fromGlobals()->withAttribute('params', $params); + + $this->expectException(NotFoundException::class); + $this->expectExceptionMessage('Provider not found'); + $this->Factory->createFromRequest($request); + } + + /** + * Test the provider `openid` config reaches the OpenID Connect service, merged with its defaults + * + * @return void + */ + public function testCreateFromProviderOpenIdConfig(): void + { + Configure::write('OAuth.providers.customOidc', [ + 'service' => OpenIDConnectService::class, + 'className' => GenericProvider::class, + 'mapper' => LinkedInOpenIDConnect::class, + 'options' => [ + 'redirectUri' => '/auth/customOidc', + 'linkSocialUri' => '/link-social/customOidc', + 'callbackLinkSocialUri' => '/callback-link-social/customOidc', + 'clientId' => 'client-id', + 'clientSecret' => 'secret', + 'urlAuthorize' => 'https://idp.example/auth', + 'urlAccessToken' => 'https://idp.example/token', + 'urlResourceOwnerDetails' => 'https://idp.example/userinfo', + ], + 'openid' => [ + 'baseUrl' => 'https://idp.example/', + 'url' => 'https://idp.example/.well-known/openid-configuration', + 'issuer' => 'https://idp.example', + 'cache' => 'default', + ], + ]); + + $service = $this->Factory->createFromProvider('customOidc'); + + $this->assertSame('https://idp.example/.well-known/openid-configuration', $service->getConfig('openid.url')); + $this->assertSame('https://idp.example', $service->getConfig('openid.issuer')); + $this->assertSame('default', $service->getConfig('openid.cache')); + $this->assertTrue($service->getConfig('openid.nonce')); + $this->assertSame('RS256', $service->getConfig('openid.jwk.defaultAlgorithm')); + } } diff --git a/tests/TestCase/Test/BaseTestTraitTest.php b/tests/TestCase/Test/BaseTestTraitTest.php index e98471a..ccb73fc 100644 --- a/tests/TestCase/Test/BaseTestTraitTest.php +++ b/tests/TestCase/Test/BaseTestTraitTest.php @@ -13,6 +13,7 @@ namespace CakeDC\Auth\Test\TestCase\Test; +use Cake\Core\Configure; use CakeDC\Auth\Test\BaseTestTrait; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\TestCase; @@ -92,4 +93,134 @@ public function testPermissionsDataProviderAttribute(): void $this->assertCount(1, $attributes); $this->assertSame(['provider'], $attributes[0]->getArguments()); } + + /** + * @return array + */ + public static function authSessionDataProvider(): array + { + $user = ['id' => 1, 'role' => 'admin']; + + return [ + 'default key' => [null, ['Auth' => $user]], + 'CakeDC/Users key' => ['Auth', ['Auth' => $user]], + 'nested key' => ['Auth.User', ['Auth' => ['User' => $user]]], + ]; + } + + /** + * Test the user is stored at the session key of the session authenticator + * + * @param string|null $sessionKey `Auth.Authenticators.Session.sessionKey` value + * @param array $expected expected session data + * @return void + */ + #[DataProvider('authSessionDataProvider')] + public function testAuthSessionData(?string $sessionKey, array $expected): void + { + $backup = Configure::read('Auth.Authenticators.Session.sessionKey'); + if ($sessionKey === null) { + Configure::delete('Auth.Authenticators.Session.sessionKey'); + } else { + Configure::write('Auth.Authenticators.Session.sessionKey', $sessionKey); + } + $case = new class ('testAuthSessionData') extends TestCase { + use BaseTestTrait; + + /** + * @return array + */ + public static function provider(): array + { + return []; + } + + public function sessionData(array $user): array + { + return $this->_authSessionData($user); + } + }; + + try { + $this->assertSame($expected, $case->sessionData(['id' => 1, 'role' => 'admin'])); + } finally { + Configure::write('Auth.Authenticators.Session.sessionKey', $backup); + } + } + + /** + * Test the CSV method and ajax columns are case-insensitive + * + * @return void + */ + public function testPermissionsMethodCaseInsensitive(): void + { + $case = new class ('testPermissions') extends TestCase { + use BaseTestTrait; + + public array $requests = []; + + /** + * @return array + */ + public static function provider(): array + { + return []; + } + + public function request(string $method, string $ajax): void + { + $this->_testPermissions('/posts/add', 'user', $method, $ajax, '200', 'ok'); + } + + public function loginAsUserName(string $username): void + { + } + + public function get(string $url): void + { + $this->requests[] = ['get', $url, $_SERVER['HTTP_X_REQUESTED_WITH'] ?? null]; + } + + public function post(string $url): void + { + $this->requests[] = ['post', $url, $_SERVER['HTTP_X_REQUESTED_WITH'] ?? null]; + } + + public function enableCsrfToken(): void + { + } + + public function enableSecurityToken(): void + { + } + + public function assertResponseOk(): void + { + } + + public function assertResponseContains(string $content): void + { + } + }; + + $backup = $_SERVER['HTTP_X_REQUESTED_WITH'] ?? null; + try { + unset($_SERVER['HTTP_X_REQUESTED_WITH']); + $case->request('POST', 'AJAX'); + unset($_SERVER['HTTP_X_REQUESTED_WITH']); + $case->request('Get', 'no-ajax'); + } finally { + if ($backup === null) { + unset($_SERVER['HTTP_X_REQUESTED_WITH']); + } else { + $_SERVER['HTTP_X_REQUESTED_WITH'] = $backup; + } + } + + $this->assertSame([ + ['post', '/posts/add', 'XMLHttpRequest'], + ['get', '/posts/add', null], + ], $case->requests); + } } diff --git a/tests/bootstrap.php b/tests/bootstrap.php index fb2ad8f..c7821a0 100644 --- a/tests/bootstrap.php +++ b/tests/bootstrap.php @@ -84,9 +84,11 @@ ini_set('intl.default_locale', 'en_US'); -@mkdir(TMP . 'cache/models'); -@mkdir(TMP . 'cache/persistent'); -@mkdir(TMP . 'cache/views'); +foreach (['models', 'persistent', 'views'] as $cacheDir) { + if (!is_dir(TMP . 'cache/' . $cacheDir)) { + mkdir(TMP . 'cache/' . $cacheDir, 0777, true); + } +} $cache = [ 'default' => [ From 737019d8d7277fd1a668bf2dc97c8de4170c9968 Mon Sep 17 00:00:00 2001 From: Alberto Rodriguez Date: Fri, 13 Nov 2026 17:54:41 -0400 Subject: [PATCH 30/35] fix(rbac): throw for malformed allowed and bypassAuth rule configs --- Docs/Documentation/MigrationGuide.md | 4 ++-- Docs/Documentation/Rbac.md | 9 +++++---- src/Rbac/Rbac.php | 5 +++-- tests/TestCase/Rbac/RbacTest.php | 17 +++++++++++------ 4 files changed, 21 insertions(+), 14 deletions(-) diff --git a/Docs/Documentation/MigrationGuide.md b/Docs/Documentation/MigrationGuide.md index cf8a649..44c3354 100644 --- a/Docs/Documentation/MigrationGuide.md +++ b/Docs/Documentation/MigrationGuide.md @@ -66,8 +66,8 @@ Please check [Authentication](Authentication.md) and [Authorization](Authorizati * The default `resetOneTimePasswordAuthenticator` permission uses the `OTPRule`. Users with integer ids can now reset their own one time password authenticator, the previous closure always denied them -* An `allowed` or `bypassAuth` array with a `className` key must be a valid rule config, a class that - is not a `Rule` throws an `InvalidArgumentException` +* Any array in `allowed` or `bypassAuth` must be a valid rule config. A missing `className`, a class + that does not exist, or a class that is not a `Rule` throws an `InvalidArgumentException` * `BaseTestTrait::testPermissions()` uses a `#[DataProvider]` attribute, the `provider()` method of your test class must be static * The `LinkedIn`, `Instagram`, `Pinterest` and `Tumblr` mappers are deprecated and will be removed in diff --git a/Docs/Documentation/Rbac.md b/Docs/Documentation/Rbac.md index 17204ea..a061c35 100644 --- a/Docs/Documentation/Rbac.md +++ b/Docs/Documentation/Rbac.md @@ -76,12 +76,13 @@ Permission rules syntax * A callable/object (see below) * If any of rules fail, the permission is discarded and the next one is evaluated * A very special key `allowed` exists which has the following behaviour: - * If `expected_value` is a callable/object then it's executed and the result is casted to boolean - * If `expected_value` is **not** a callable/object then it's simply casted to boolean + * If `expected_value` is a callable/object or a rule config array, it's executed and the result is casted to boolean + * If `expected_value` is an array without a valid rule config (`className` implementing `Rule`), an `InvalidArgumentException` is thrown + * Any other `expected_value` is simply casted to boolean * The `*` is checked and if found the result is inverted * The final boolean value is **the result of permission** checker. This means if it is `false` then no other permissions are checked and the user is denied access. And if it is `true`, you need at least an user identified, or it'll deny your access attempt. For this reason the `allowed` key must be placed at the end of permission since no other rules are executed after it -* Another special key is `bypassAuth`. If it is `true`, or a callable `($user, $role, $request)` returning `true`, the request is allowed even if there is no user data. Use it for public actions. A `Rule` or a rule config array in `bypassAuth` is only evaluated for logged in users. +* Another special key is `bypassAuth`. If it is `true`, or a callable `($user, $role, $request)` returning `true`, the request is allowed even if there is no user data. Use it for public actions. A `Rule` or any array in `bypassAuth` must be a valid rule config; an invalid or incomplete one throws an `InvalidArgumentException`. A rule config in `bypassAuth` is only evaluated for logged in users. **Notes**: @@ -133,7 +134,7 @@ created with the RuleRegistry. Unlike a closure, this permission can be serializ ], ``` -The array is used as a rule only when `className` is a class implementing `\CakeDC\Auth\Rbac\Rules\Rule`. +An array in `allowed` or `bypassAuth` is always treated as a rule config. Its `className` must be a class implementing `\CakeDC\Auth\Rbac\Rules\Rule`; a missing class, a class that does not exist, or a class that is not a `Rule` throws an `InvalidArgumentException`. ## Creating rule classes diff --git a/src/Rbac/Rbac.php b/src/Rbac/Rbac.php index dcdb7d0..cdd9a2b 100644 --- a/src/Rbac/Rbac.php +++ b/src/Rbac/Rbac.php @@ -231,7 +231,7 @@ protected function _matchPermission( $return = $value->allowed($user, $role, $request); } elseif ( $this->_isRuleConfig($value) || - (in_array($key, ['allowed', 'bypassAuth'], true) && is_array($value) && isset($value['className'])) + (in_array($key, ['allowed', 'bypassAuth'], true) && is_array($value)) ) { $return = $this->_ruleFromConfig($value)->allowed($user, $role, $request); } elseif ($key === 'bypassAuth' && $value === true) { @@ -309,9 +309,10 @@ protected function _encodeForReason(mixed $value): string protected function _ruleFromConfig(array $config): Rule { if (!$this->_isRuleConfig($config)) { + $className = $config['className'] ?? null; throw new InvalidArgumentException(sprintf( 'Permission rule `%s` is not a class implementing %s', - is_string($config['className']) ? $config['className'] : get_debug_type($config['className']), + is_string($className) ? $className : get_debug_type($className), Rule::class, )); } diff --git a/tests/TestCase/Rbac/RbacTest.php b/tests/TestCase/Rbac/RbacTest.php index 3149361..0e32ee2 100644 --- a/tests/TestCase/Rbac/RbacTest.php +++ b/tests/TestCase/Rbac/RbacTest.php @@ -1404,12 +1404,12 @@ public function testRuleConfigNotARule(): void * @return void */ #[DataProvider('ruleConfigInvalidClassProvider')] - public function testRuleConfigInvalidClass(string $key, mixed $className): void + public function testRuleConfigInvalidClass(string $key, mixed $value): void { $permissions = [[ 'controller' => 'Users', 'action' => 'resetOneTimePasswordAuthenticator', - $key => ['className' => $className], + $key => $value, ]]; $this->rbac = new Rbac(['permissions' => $permissions]); $request = $this->_requestFromArray([ @@ -1427,10 +1427,15 @@ public function testRuleConfigInvalidClass(string $key, mixed $className): void public static function ruleConfigInvalidClassProvider(): array { return [ - 'missing class' => ['allowed', 'App\Rbac\MissingRule'], - 'not a rule' => ['allowed', stdClass::class], - 'not a string' => ['allowed', 123], - 'bypassAuth' => ['bypassAuth', stdClass::class], + 'missing class' => ['allowed', ['className' => 'App\Rbac\MissingRule']], + 'not a rule' => ['allowed', ['className' => stdClass::class]], + 'not a string' => ['allowed', ['className' => 123]], + 'bypassAuth' => ['bypassAuth', ['className' => stdClass::class]], + 'missing className key' => ['allowed', ['options' => []]], + 'null className' => ['allowed', ['className' => null]], + 'className case typo' => ['allowed', ['classname' => OTPRule::class]], + 'list of configs' => ['allowed', [['className' => OTPRule::class]]], + 'bypassAuth missing className' => ['bypassAuth', ['options' => []]], ]; } From b432b4d624cb73ab7dd9d185053fb06b94882ba3 Mon Sep 17 00:00:00 2001 From: Alberto Rodriguez Date: Fri, 13 Nov 2026 17:57:57 -0400 Subject: [PATCH 31/35] fix(social): keep rolesMap for provider aliases using the Keycloak mapper --- CHANGELOG.md | 3 ++ Docs/Documentation/Social.md | 7 ++-- src/Social/MapUser.php | 8 +++-- src/Social/ProviderConfig.php | 2 +- tests/TestCase/Social/MapUserTest.php | 38 ++++++++++++++++++++ tests/TestCase/Social/ProviderConfigTest.php | 25 +++++++++++++ 6 files changed, 76 insertions(+), 7 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 93e95d0..980f9f3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -117,6 +117,9 @@ documented. Check these behavior changes when upgrading: - A partial `OAuth.providers.keycloak.mapFields` replaced the whole Keycloak field map, losing `id`, `roles` and `validated`, so the `rolesMap` check let every user in. The configured fields are now merged over the mapper fields. +- The Keycloak `rolesMap` was only read from `OAuth.providers.keycloak`, so a provider alias with + `mapper => Keycloak::class` ignored its own roles map. `ProviderConfig` now keeps the provider + `rolesMap` and `MapUser` passes it to the mapper. - `OneTimeTokenAuthenticator` treats a token array that is not a flat list of strings as a missing token, instead of joining it with an "Array to string conversion" warning. diff --git a/Docs/Documentation/Social.md b/Docs/Documentation/Social.md index 047518c..a1b08f1 100644 --- a/Docs/Documentation/Social.md +++ b/Docs/Documentation/Social.md @@ -171,9 +171,10 @@ Without a `rolesMap` the `roles` field is `null` and no role is required. When a the login fails with an `UnexpectedValueException` when the userinfo has no roles or none of the user roles is in `rolesMap`, so only users with a mapped role can log in. -The mapper reads `OAuth.providers.keycloak.rolesMap` and `OAuth.providers.keycloak.mapFields`, the -configured `mapFields` are merged over the mapper fields. When -the provider uses another key, pass a mapper instance instead of the class name: +The mapper reads the `rolesMap` of the provider configuration, so it works with any provider alias +(e.g. `OAuth.providers.staffSso.rolesMap` with `'mapper' => Keycloak::class`). The `mapFields` still +default to `OAuth.providers.keycloak.mapFields`; when the provider uses another key and needs custom +map fields, pass a mapper instance instead of the class name: `'mapper' => new \CakeDC\Auth\Social\Mapper\Keycloak(null, ['MyRealm-Admin' => 'admin'])`. The mapper does not change the user role by itself. CakeDC/Users creates new users with its diff --git a/src/Social/MapUser.php b/src/Social/MapUser.php index 1fa8a42..6109e23 100644 --- a/src/Social/MapUser.php +++ b/src/Social/MapUser.php @@ -30,7 +30,8 @@ public function __invoke(ServiceInterface $service, mixed $data): mixed { $mapper = $service->getConfig('mapper'); if (is_string($mapper)) { - $mapper = $this->buildMapper($mapper); + $rolesMap = $service->getConfig('rolesMap'); + $mapper = $this->buildMapper($mapper, is_array($rolesMap) ? $rolesMap : null); } $user = $mapper($data); @@ -43,14 +44,15 @@ public function __invoke(ServiceInterface $service, mixed $data): mixed * Build the mapper object * * @param string $className of mapper + * @param array|null $rolesMap provider roles map * @return object */ - protected function buildMapper(string $className): object + protected function buildMapper(string $className, ?array $rolesMap = null): object { if (!class_exists($className)) { throw new InvalidArgumentException(__('Provider mapper class {0} does not exist', $className)); } - return new $className(); + return new $className(null, $rolesMap); } } diff --git a/src/Social/ProviderConfig.php b/src/Social/ProviderConfig.php index c560c31..a102541 100644 --- a/src/Social/ProviderConfig.php +++ b/src/Social/ProviderConfig.php @@ -84,7 +84,7 @@ protected function _normalizeConfig(array &$config, string $alias, array $parent 'mapFields' => [], ] + $parent; // OpenIDConnectService settings, only kept when the provider defines them - $optional = ['openid' => true]; + $optional = ['openid' => true, 'rolesMap' => true]; $config = array_intersect_key($config, $defaults + $optional); $config += $defaults; diff --git a/tests/TestCase/Social/MapUserTest.php b/tests/TestCase/Social/MapUserTest.php index 61b1d5a..a21155b 100644 --- a/tests/TestCase/Social/MapUserTest.php +++ b/tests/TestCase/Social/MapUserTest.php @@ -16,6 +16,7 @@ use Cake\Core\Configure; use Cake\TestSuite\TestCase; use CakeDC\Auth\Social\Mapper\Facebook as FacebookMapper; +use CakeDC\Auth\Social\Mapper\Keycloak as KeycloakMapper; use CakeDC\Auth\Social\MapUser; use CakeDC\Auth\Social\Service\OAuth2Service; use CakeDC\Auth\Social\Service\ServiceFactory; @@ -140,6 +141,43 @@ public function testMap() $this->assertEquals($expected, $actual); } + /** + * The Keycloak mapper uses the rolesMap of any provider alias + */ + public function testMapKeycloakRolesMapFromProviderAlias() + { + Configure::write('OAuth.providers.staffSso', [ + 'service' => OAuth2Service::class, + 'className' => Facebook::class, + 'mapper' => KeycloakMapper::class, + 'options' => [ + 'state' => '__TEST_STATE__', + 'graphApiVersion' => 'v2.8', + 'redirectUri' => '/auth/staffSso', + 'linkSocialUri' => '/link-social/staffSso', + 'callbackLinkSocialUri' => '/callback-link-social/staffSso', + 'clientId' => '10003030300303', + 'clientSecret' => 'secretpassword', + ], + 'rolesMap' => ['CakeDc-Admin' => 'admin'], + ]); + $service = (new ServiceFactory())->createFromProvider('staffSso'); + $rawData = [ + 'token' => new AccessToken([ + 'access_token' => 'test-token', + 'expires' => 1490988496, + ]), + 'sub' => '1', + 'email' => 'test@example.com', + 'realm_access' => ['roles' => ['CakeDc-Admin']], + ]; + + $user = (new MapUser())($service, $rawData); + + $this->assertSame('admin', $user['roles']); + $this->assertSame('staffSso', $user['provider']); + } + /** * Test base map, invalid mapper */ diff --git a/tests/TestCase/Social/ProviderConfigTest.php b/tests/TestCase/Social/ProviderConfigTest.php index c75edfc..a202fae 100644 --- a/tests/TestCase/Social/ProviderConfigTest.php +++ b/tests/TestCase/Social/ProviderConfigTest.php @@ -19,6 +19,7 @@ use CakeDC\Auth\Exception\InvalidSettingsException; use CakeDC\Auth\Social\Mapper\Amazon as AmazonMapper; use CakeDC\Auth\Social\Mapper\Facebook as FacebookMapper; +use CakeDC\Auth\Social\Mapper\Keycloak as KeycloakMapper; use CakeDC\Auth\Social\Mapper\Twitter as TwitterMapper; use CakeDC\Auth\Social\ProviderConfig; use CakeDC\Auth\Social\Service\OAuth1Service; @@ -166,6 +167,30 @@ public function testWithCustomConfig() $this->assertEquals($expected, $actual); } + /** + * A provider alias keeps its own rolesMap + * + * @return void + */ + public function testRolesMapKeptForProviderAlias() + { + Configure::write('OAuth.providers.staffSso', [ + 'service' => OAuth2Service::class, + 'className' => Facebook::class, + 'mapper' => KeycloakMapper::class, + 'options' => [ + 'redirectUri' => '/auth/staffSso', + 'clientId' => '10003030300303', + 'clientSecret' => 'secretpassword', + ], + 'rolesMap' => ['Manager' => 'superuser'], + ]); + + $config = (new ProviderConfig())->getConfig('staffSso'); + + $this->assertSame(['Manager' => 'superuser'], $config['rolesMap']); + } + /** * Test with providers enabled * From c780827e12c2da03090708789307a23c1b380665 Mon Sep 17 00:00:00 2001 From: Alberto Rodriguez Date: Fri, 13 Nov 2026 17:59:57 -0400 Subject: [PATCH 32/35] fix(openid): reject dot segments in jwks_uri paths --- CHANGELOG.md | 5 +++-- Docs/Documentation/Social.md | 1 + src/Social/Service/OpenIDConnectService.php | 21 +++++++++++++++++++ .../Service/OpenIDConnectServiceTest.php | 3 +++ 4 files changed, 28 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 980f9f3..b6d5d2e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -35,8 +35,9 @@ documented. Check these behavior changes when upgrading: - An Rbac `allowed` or `bypassAuth` rule config whose `className` is missing or is not a `Rule` allowed every logged in user. It now throws an `InvalidArgumentException`. - The OpenID Connect service validates the id token signature and its `iss`, `aud`, `azp` and `nonce` - claims, only loads the key set from a `jwks_uri` on the scheme, host and port of `openid.baseUrl`, and - the `LinkedInOpenIDConnect` mapper reads `validated` from `email_verified`. + claims, only loads the key set from a `jwks_uri` on the scheme, host and port of `openid.baseUrl` + and a path below it without `.` or `..` segments (raw or percent-encoded), and the + `LinkedInOpenIDConnect` mapper reads `validated` from `email_verified`. - A partial Keycloak `mapFields` config dropped the `roles` field, so the `rolesMap` check let users without a mapped role log in. The configured fields are now merged over the mapper fields. - The `Tumblr` mapper is deprecated: its user id is a crc32 of the nickname, so two users can get the diff --git a/Docs/Documentation/Social.md b/Docs/Documentation/Social.md index a1b08f1..2befcf8 100644 --- a/Docs/Documentation/Social.md +++ b/Docs/Documentation/Social.md @@ -252,6 +252,7 @@ provider: // ... 'openid' => [ // the jwks_uri of the discovery document must use this scheme, host and port, and a path below it. + // Dot segments (`.` or `..`, raw or percent-encoded) are rejected. // The defaults are for LinkedIn, set baseUrl, url and issuer for any other provider 'baseUrl' => 'https://www.linkedin.com/', // discovery document diff --git a/src/Social/Service/OpenIDConnectService.php b/src/Social/Service/OpenIDConnectService.php index fd2332d..218ea25 100644 --- a/src/Social/Service/OpenIDConnectService.php +++ b/src/Social/Service/OpenIDConnectService.php @@ -247,10 +247,31 @@ protected function isTrustedUrl(string $url, string $baseUrl): bool } $basePath = rtrim($base['path'] ?? '', '/'); $path = $target['path'] ?? '/'; + if ($this->hasDotSegments($path)) { + return false; + } return $basePath === '' || $path === $basePath || str_starts_with($path, $basePath . '/'); } + /** + * Check whether the path contains a dot segment, raw or percent-encoded + * + * @param string $path Url path. + * @return bool + */ + protected function hasDotSegments(string $path): bool + { + foreach (explode('/', $path) as $segment) { + $segment = rawurldecode($segment); + if ($segment === '.' || $segment === '..' || str_contains($segment, '/') || str_contains($segment, '\\')) { + return true; + } + } + + return false; + } + /** * Get the OpenID discovery document, fetched once per service instance * diff --git a/tests/TestCase/Social/Service/OpenIDConnectServiceTest.php b/tests/TestCase/Social/Service/OpenIDConnectServiceTest.php index 4d3e81b..29b00b2 100644 --- a/tests/TestCase/Social/Service/OpenIDConnectServiceTest.php +++ b/tests/TestCase/Social/Service/OpenIDConnectServiceTest.php @@ -816,6 +816,9 @@ public static function trustedUrlProvider(): array 'other scheme' => ['http://idp.example/certs', 'https://idp.example', false], 'other port' => ['https://idp.example:8443/certs', 'https://idp.example', false], 'sibling path' => ['https://idp.example/realms/ab/certs', 'https://idp.example/realms/a', false], + 'dot segment' => ['https://idp.example/realms/a/../b/certs', 'https://idp.example/realms/a', false], + 'single dot segment' => ['https://idp.example/realms/a/./certs', 'https://idp.example/realms/a', false], + 'encoded dot segment' => ['https://idp.example/realms/a/%2e%2e/b/certs', 'https://idp.example/realms/a', false], 'empty base url' => ['https://evil.com/certs', '', false], 'relative url' => ['/certs', 'https://idp.example', false], ]; From 1f4a3795e7e508050c95267f42493ea4d91964b4 Mon Sep 17 00:00:00 2001 From: Alberto Rodriguez Date: Fri, 13 Nov 2026 18:02:06 -0400 Subject: [PATCH 33/35] fix(social): require a boolean true for validated email claims --- CHANGELOG.md | 2 ++ Docs/Documentation/MigrationGuide.md | 2 ++ Docs/Documentation/Social.md | 2 +- src/Social/Mapper/Keycloak.php | 2 +- src/Social/Mapper/LinkedInOpenIDConnect.php | 2 +- tests/TestCase/Social/Mapper/KeycloakTest.php | 32 +++++++++++++++++ .../Mapper/LinkedInOpenIDConnectTest.php | 35 +++++++++++++++++++ 7 files changed, 74 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index b6d5d2e..7eb3be6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -91,6 +91,8 @@ documented. Check these behavior changes when upgrading: `AuthPlugin` (or by its name `CakeDC/Auth`). ### Fixed +- The `LinkedInOpenIDConnect` and `Keycloak` mappers only treat a JSON boolean `true` as a validated + email. A string claim like `"false"` was cast to `true` before. - `ReCaptchaTrait::validateReCaptchaFromRequest()` treats a missing or empty `g-recaptcha-response` as an invalid captcha (returns `false`) instead of passing `null` to the non-nullable `validateReCaptcha(string ...)`, which raised a `TypeError` (HTTP 500). A tokenless diff --git a/Docs/Documentation/MigrationGuide.md b/Docs/Documentation/MigrationGuide.md index 44c3354..795c5c8 100644 --- a/Docs/Documentation/MigrationGuide.md +++ b/Docs/Documentation/MigrationGuide.md @@ -74,6 +74,8 @@ Please check [Authentication](Authentication.md) and [Authorization](Authorizati 12.0. Switch the `linkedIn` provider to `linkedInOpenIDConnect` * The `Azure` mapper only sets `validated` when the `email_verified` or `xms_edov` claim is `true`. Before, any `upn` was trusted as a validated email +* The `LinkedInOpenIDConnect` and `Keycloak` mappers only set `validated` when `email_verified` is + the JSON boolean `true`. String or numeric values are not accepted * `BaseTestTrait` stores the logged in user at `Auth.Authenticators.Session.sessionKey` (`Auth` by default) instead of `Auth.User`. Set `sessionKey` to `Auth.User` to keep the previous layout * New: Keycloak mapper, OpenID Connect service and LinkedIn OpenID Connect provider, see diff --git a/Docs/Documentation/Social.md b/Docs/Documentation/Social.md index 2befcf8..2d1b87a 100644 --- a/Docs/Documentation/Social.md +++ b/Docs/Documentation/Social.md @@ -15,7 +15,7 @@ We have mappers to allow you a quick start with these providers: - Google - Instagram (Deprecated, the Instagram Basic Display API was shut down) - LinkedIn (Deprecated, LinkedIn retired this API, use LinkedInOpenIDConnect) -- LinkedInOpenIDConnect (OIDC based authentication) +- LinkedInOpenIDConnect (OIDC based authentication; the email is only validated with the boolean `email_verified` claim) - Pinterest (Deprecated, reads fields of the retired API v1) - Tumblr (Deprecated, the user id is a crc32 of the nickname) - Twitter diff --git a/src/Social/Mapper/Keycloak.php b/src/Social/Mapper/Keycloak.php index 6799fe4..741bbaf 100644 --- a/src/Social/Mapper/Keycloak.php +++ b/src/Social/Mapper/Keycloak.php @@ -115,6 +115,6 @@ protected function _roles(mixed $rawData): ?string */ protected function _validated(mixed $rawData): bool { - return (bool)Hash::get($rawData, $this->_mapFields['validated']); + return Hash::get($rawData, $this->_mapFields['validated']) === true; } } diff --git a/src/Social/Mapper/LinkedInOpenIDConnect.php b/src/Social/Mapper/LinkedInOpenIDConnect.php index ad86381..68ca046 100644 --- a/src/Social/Mapper/LinkedInOpenIDConnect.php +++ b/src/Social/Mapper/LinkedInOpenIDConnect.php @@ -43,7 +43,7 @@ class LinkedInOpenIDConnect extends AbstractMapper */ protected function _validated(mixed $rawData): bool { - return (bool)Hash::get($rawData, $this->_mapFields['validated']); + return Hash::get($rawData, $this->_mapFields['validated']) === true; } /** diff --git a/tests/TestCase/Social/Mapper/KeycloakTest.php b/tests/TestCase/Social/Mapper/KeycloakTest.php index d6e8c90..9756b5c 100644 --- a/tests/TestCase/Social/Mapper/KeycloakTest.php +++ b/tests/TestCase/Social/Mapper/KeycloakTest.php @@ -17,6 +17,7 @@ use Cake\TestSuite\TestCase; use CakeDC\Auth\Social\Mapper\Keycloak; use League\OAuth2\Client\Token\AccessToken; +use PHPUnit\Framework\Attributes\DataProvider; use UnexpectedValueException; class KeycloakTest extends TestCase @@ -152,6 +153,37 @@ public function testMissingRoles(): void (new Keycloak())($rawData); } + /** + * Only a boolean true validates the email + * + * @return array + */ + public static function validatedProvider(): array + { + return [ + 'boolean true' => [true, true], + 'boolean false' => [false, false], + 'string true' => ['true', false], + 'string false' => ['false', false], + 'integer one' => [1, false], + 'null' => [null, false], + ]; + } + + /** + * @param mixed $value email_verified claim + * @param bool $expected expected validated value + * @return void + */ + #[DataProvider('validatedProvider')] + public function testValidated(mixed $value, bool $expected): void + { + $rawData = $this->rawData(); + $rawData['email_verified'] = $value; + + $this->assertSame($expected, (new Keycloak())($rawData)['validated']); + } + /** * A partial mapFields config is merged over the Keycloak map, the role check keeps working * diff --git a/tests/TestCase/Social/Mapper/LinkedInOpenIDConnectTest.php b/tests/TestCase/Social/Mapper/LinkedInOpenIDConnectTest.php index 6eb74bd..c861d7b 100644 --- a/tests/TestCase/Social/Mapper/LinkedInOpenIDConnectTest.php +++ b/tests/TestCase/Social/Mapper/LinkedInOpenIDConnectTest.php @@ -16,6 +16,7 @@ use Cake\TestSuite\TestCase; use CakeDC\Auth\Social\Mapper\LinkedInOpenIDConnect; use League\OAuth2\Client\Token\AccessToken; +use PHPUnit\Framework\Attributes\DataProvider; class LinkedInOpenIDConnectTest extends TestCase { @@ -97,4 +98,38 @@ public function testMapEmailNotVerified(): void unset($rawData['email_verified']); $this->assertFalse((new LinkedInOpenIDConnect())($rawData)['validated']); } + + /** + * Only a boolean true validates the email + * + * @return array + */ + public static function validatedProvider(): array + { + return [ + 'boolean true' => [true, true], + 'boolean false' => [false, false], + 'string true' => ['true', false], + 'string false' => ['false', false], + 'integer one' => [1, false], + 'null' => [null, false], + ]; + } + + /** + * @param mixed $value email_verified claim + * @param bool $expected expected validated value + * @return void + */ + #[DataProvider('validatedProvider')] + public function testValidated(mixed $value, bool $expected): void + { + $rawData = [ + 'sub' => '1', + 'token' => new AccessToken(['access_token' => 'test-token']), + 'email_verified' => $value, + ]; + + $this->assertSame($expected, (new LinkedInOpenIDConnect())($rawData)['validated']); + } } From 6170a226320195f262e7befba3b103427180646a Mon Sep 17 00:00:00 2001 From: Alberto Rodriguez Date: Fri, 13 Nov 2026 18:05:41 -0400 Subject: [PATCH 34/35] fix(auth): only join a flat list of one time token characters --- Docs/Documentation/Authentication.md | 5 +++-- .../OneTimeTokenAuthenticator.php | 2 +- .../OneTimeTokenAuthenticatorTest.php | 18 ++++++++++++++++++ 3 files changed, 22 insertions(+), 3 deletions(-) diff --git a/Docs/Documentation/Authentication.md b/Docs/Documentation/Authentication.md index 2fc592b..979f33e 100644 --- a/Docs/Documentation/Authentication.md +++ b/Docs/Documentation/Authentication.md @@ -29,8 +29,9 @@ Check how enabled social authentication at [users plugin.](https://github.com/Ca - urlChecker: The URL checker class or object. Default is DefaultUrlChecker. - **OneTimeTokenAuthenticator**, logs in a user with a one time token (magic link), read from the -`token` query param or the posted `token` field. A token posted as one input per character -(`token[0]`, `token[1]`...) is joined. The user is found with the `loginWithToken($token)` method of +`token` query param or the posted `token` field. A token posted as one input per character in a flat, +zero-based list (`token[0]`, `token[1]`...) is joined; any other array shape is treated as a missing +token. The user is found with the `loginWithToken($token)` method of the users table configured in `Users.table`, provided by the CakeDC/Users plugin. All authenticators use the identifiers of cakephp/authentication 3.x, configured per authenticator diff --git a/src/Authenticator/OneTimeTokenAuthenticator.php b/src/Authenticator/OneTimeTokenAuthenticator.php index 59cf017..55a3178 100644 --- a/src/Authenticator/OneTimeTokenAuthenticator.php +++ b/src/Authenticator/OneTimeTokenAuthenticator.php @@ -32,7 +32,7 @@ public function authenticate(ServerRequestInterface $request): ResultInterface $token = $request->getQuery('token') ?: $request->getData('token'); // The CakeDC/Users token form posts one input per character, `token[0]`, `token[1]`... if (is_array($token)) { - $isStringList = array_filter($token, 'is_string') === $token; + $isStringList = array_is_list($token) && array_filter($token, 'is_string') === $token; $token = $isStringList ? implode('', $token) : null; } diff --git a/tests/TestCase/Authenticator/OneTimeTokenAuthenticatorTest.php b/tests/TestCase/Authenticator/OneTimeTokenAuthenticatorTest.php index 5713f13..a5dcfea 100644 --- a/tests/TestCase/Authenticator/OneTimeTokenAuthenticatorTest.php +++ b/tests/TestCase/Authenticator/OneTimeTokenAuthenticatorTest.php @@ -83,6 +83,24 @@ public static function authenticateProvider(): array ['valid-token'], ], 'nested array token' => [['token' => ['valid-', ['token']]], [], Result::FAILURE_CREDENTIALS_MISSING, []], + 'associative array token' => [ + [], + ['token' => [ + 'a' => 'v', 'b' => 'a', 'c' => 'l', 'd' => 'i', 'e' => 'd', 'f' => '-', + 'g' => 't', 'h' => 'o', 'i' => 'k', 'j' => 'e', 'k' => 'n', + ]], + Result::FAILURE_CREDENTIALS_MISSING, + [], + ], + 'non zero based list token' => [ + [], + ['token' => [ + 1 => 'v', 2 => 'a', 3 => 'l', 4 => 'i', 5 => 'd', 6 => '-', + 7 => 't', 8 => 'o', 9 => 'k', 10 => 'e', 11 => 'n', + ]], + Result::FAILURE_CREDENTIALS_MISSING, + [], + ], 'no token' => [[], [], Result::FAILURE_CREDENTIALS_MISSING, []], 'empty token' => [['token' => ''], ['token' => ''], Result::FAILURE_CREDENTIALS_MISSING, []], ]; From 8426479774f8b2b4e0d3da4198a82ee72f8af21c Mon Sep 17 00:00:00 2001 From: Alberto Rodriguez Date: Fri, 13 Nov 2026 18:09:07 -0400 Subject: [PATCH 35/35] test(openid): cover a cached key set without the token kid --- .../Service/OpenIDConnectServiceTest.php | 30 +++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/tests/TestCase/Social/Service/OpenIDConnectServiceTest.php b/tests/TestCase/Social/Service/OpenIDConnectServiceTest.php index 29b00b2..f686d85 100644 --- a/tests/TestCase/Social/Service/OpenIDConnectServiceTest.php +++ b/tests/TestCase/Social/Service/OpenIDConnectServiceTest.php @@ -766,6 +766,36 @@ public function testGetUserCachedKeySetRotation(): void $this->assertSame(['old-key', 'new-key'], array_column($cached['keys'], 'kid')); } + /** + * Test a cached key set that still misses the token key id after the refresh is rejected + * + * @return void + */ + public function testGetUserCachedKeySetRefreshStillMissingKid(): void + { + Cache::setConfig('_oidc_test_', ['className' => 'Array']); + $oldKey = $this->rsaKey('old-key'); + $newKey = $this->rsaKey('new-key'); + Cache::write('cakedc_auth_oidc_' . md5(self::JWKS_URI), ['keys' => [$oldKey['jwk']]], '_oidc_test_'); + $requested = []; + $service = $this->serviceWithHttp($this->oidcResponses([$oldKey['jwk']]), $requested); + $service->setConfig('openid.cache', '_oidc_test_'); + $this->prepareCallback(JWT::encode($this->validClaims(), $newKey['private'], 'RS256', 'new-key')); + + try { + $this->assertInvalidIdToken($service, '"kid" invalid'); + $cached = Cache::read('cakedc_auth_oidc_' . md5(self::JWKS_URI), '_oidc_test_'); + } finally { + Cache::drop('_oidc_test_'); + } + + $this->assertSame([ + 'https://www.linkedin.com/oauth/.well-known/openid-configuration', + self::JWKS_URI, + ], $requested); + $this->assertSame(['old-key'], array_column($cached['keys'], 'kid')); + } + /** * Test the authorization url has no nonce when `openid.nonce` is disabled *