diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index a5241ea..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 stan-setup
+ - 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
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
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 035502d..7eb3be6 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,11 +4,152 @@ 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 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
+ same id.
-## [10.1.2] - 2025-09-26
+### Added
+- Keycloak social login mapper `CakeDC\Auth\Social\Mapper\Keycloak`, with realm roles mapped by the
+ `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`, `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, 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.
+
+### 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.
+- 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 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
+- 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
+ 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.
+- 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.
+
+## [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.
+
+### 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..979f33e 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,15 @@ 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 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
+with the `identifier` option.
+
Authentication Service
----------------------
@@ -40,30 +50,29 @@ Sample usage:
'email',
- 'password' => 'password'
+ 'password' => 'password',
];
// Load the authenticators, you want session first
@@ -92,15 +101,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..795c5c8 100644
--- a/Docs/Documentation/MigrationGuide.md
+++ b/Docs/Documentation/MigrationGuide.md
@@ -40,4 +40,43 @@ 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
+* 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
+ 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
+ [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 e1514e8..a061c35 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
-----------------
@@ -48,18 +76,19 @@ 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
-* 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 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**:
-* 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,42 +102,60 @@ 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
```
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' => [],
+],
+```
+
+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
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 d99a65a..2d1b87a 100644
--- a/Docs/Documentation/Social.md
+++ b/Docs/Documentation/Social.md
@@ -1,31 +1,35 @@
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
-- Pinterest
-- Tumblr
+- Instagram (Deprecated, the Instagram Basic Display API was shut down)
+- LinkedIn (Deprecated, LinkedIn retired this API, use LinkedInOpenIDConnect)
+- 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
- Github
+- Keycloak
You must define 'options.redirectUri', 'options.clientId' and
'options.clientSecret' for any provider you want to enable. eg,
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
@@ -47,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())
@@ -58,16 +62,16 @@ use CakeDC\Auth\Social\Service\ServiceFactory;
->getAuthorizationUrl($this->request)
);
}
-
+
/**
* Callback to get user information from provider
*
* @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())
@@ -75,22 +79,190 @@ 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']);
}
$data = $server->getUser($this->request);
$data = (new MapUser())($server, $data);
-
+
//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.
\ 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:
+
+### 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:
+
+```php
+'OAuth' => [
+ 'providers' => [
+ 'keycloak' => [
+ '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' => [
+ 'example-realm-admin' => 'admin',
+ 'example-realm-user' => 'user',
+ ],
+ 'authParams' => ['scope' => ['openid', 'roles']],
+ 'options' => [
+ 'redirectUri' => Router::fullBaseUrl() . '/auth/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),
+ '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., `example-realm-admin`, `example-realm-user`)
+ - 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 `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-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.
+
+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 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
+`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
+
+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
+ '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.
+
+Working with OpenID Connect
+---------------------------
+
+`CakeDC\Auth\Social\Service\OpenIDConnectService` reads the user from the signed `id_token`
+instead of calling the provider user endpoint. It is used by the `linkedInOpenIDConnect` provider.
+It requires `firebase/php-jwt`:
+
+```bash
+composer require firebase/php-jwt
+```
+
+The service validates the token signature with the provider key set, and the `iss`, `aud`
+(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 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
+ '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/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 0c85cff..3b24c9c 100644
--- a/Docs/Documentation/TwoFactor.md
+++ b/Docs/Documentation/TwoFactor.md
@@ -6,19 +6,37 @@ 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`,
+`U2f.startAction`) can be a routing array or a string url. The query params of the login request
+are appended to it.
+
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
+
@@ -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 322604a..e9f9427 100644
--- a/composer.json
+++ b/composer.json
@@ -27,26 +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"
+ "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": {
@@ -67,18 +77,19 @@
"analyse": [
"@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/",
- "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 cf2ec4e..593eed4 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,8 +34,9 @@
'redirectUri' => Router::fullBaseUrl() . '/auth/twitter',
'linkSocialUri' => Router::fullBaseUrl() . '/link-social/twitter',
'callbackLinkSocialUri' => Router::fullBaseUrl() . '/callback-link-social/twitter',
- ]
+ ],
],
+ // Deprecated: LinkedIn retired this API, use linkedInOpenIDConnect
'linkedIn' => [
'service' => 'CakeDC\Auth\Social\Service\OAuth2Service',
'className' => 'League\OAuth2\Client\Provider\LinkedIn',
@@ -45,6 +47,18 @@
'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'],
+ ],
+ ],
+ // Deprecated: the Instagram Basic Display API was shut down
'instagram' => [
'service' => 'CakeDC\Auth\Social\Service\OAuth2Service',
'className' => 'League\OAuth2\Client\Provider\Instagram',
@@ -53,7 +67,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',
@@ -86,11 +100,27 @@
'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',
+ // 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',
+ 'linkSocialUri' => Router::fullBaseUrl() . '/link-social/keycloak',
+ 'callbackLinkSocialUri' => Router::fullBaseUrl() . '/callback-link-social/keycloak',
+ ],
+ ],
],
- 'TwoFactorProcessors' => [
+ 'TwoFactorProcessors' => [
\CakeDC\Auth\Authentication\TwoFactorProcessor\OneTimePasswordProcessor::class,
\CakeDC\Auth\Authentication\TwoFactorProcessor\Webauthn2faProcessor::class,
- ],
+ ],
'OneTimePasswordAuthenticator' => [
'checker' => \CakeDC\Auth\Authentication\DefaultOneTimePasswordAuthenticationChecker::class,
'verifyAction' => [
diff --git a/config/permissions.php b/config/permissions.php
index 930b853..26ae7a9 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,
+ 'options' => [],
+ ],
],
//all roles allowed to Pages/display
[
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
new file mode 100644
index 0000000..b344076
--- /dev/null
+++ b/psalm-baseline.xml
@@ -0,0 +1,151 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ getU2fAuthenticationChecker()]]>
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ getHeader('Accept')]]>
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ $this->getConfig('autoload_config'),
+ ])]]>
+
+
+
+
+
+
+
+
+
+ $id,
+ $this->getConfig('ownerForeignKey') => $userId,
+ ]]]>
+
+
+ getParsedBody()]]>
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/psalm.xml b/psalm.xml
index 8e3d4fd..16d7cc4 100644
--- a/psalm.xml
+++ b/psalm.xml
@@ -1,11 +1,18 @@
+
@@ -14,115 +21,9 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
+
+
+
-
\ No newline at end of file
+
diff --git a/src/AuthPlugin.php b/src/AuthPlugin.php
index 761a5ec..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;
@@ -35,7 +36,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/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 7e1c5f9..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;
@@ -92,9 +93,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/U2FProcessor.php b/src/Authentication/TwoFactorProcessor/U2FProcessor.php
index 77c95fa..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;
@@ -98,9 +99,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/Authentication/TwoFactorProcessor/Webauthn2faProcessor.php b/src/Authentication/TwoFactorProcessor/Webauthn2faProcessor.php
index 622ed06..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;
@@ -92,9 +93,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/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 0a1809a..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;
@@ -47,7 +48,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/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 21c842a..55a3178 100644
--- a/src/Authenticator/OneTimeTokenAuthenticator.php
+++ b/src/Authenticator/OneTimeTokenAuthenticator.php
@@ -1,6 +1,16 @@
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_is_list($token) && 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/Authenticator/SocialAuthenticator.php b/src/Authenticator/SocialAuthenticator.php
index d03ea4f..d9c6d26 100644
--- a/src/Authenticator/SocialAuthenticator.php
+++ b/src/Authenticator/SocialAuthenticator.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/TwoFactorAuthenticator.php b/src/Authenticator/TwoFactorAuthenticator.php
index eafbfb9..e90f9ea 100644
--- a/src/Authenticator/TwoFactorAuthenticator.php
+++ b/src/Authenticator/TwoFactorAuthenticator.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/Controller/Component/OneTimePasswordAuthenticatorComponent.php b/src/Controller/Component/OneTimePasswordAuthenticatorComponent.php
index 0c8c4dd..21edfc5 100644
--- a/src/Controller/Component/OneTimePasswordAuthenticatorComponent.php
+++ b/src/Controller/Component/OneTimePasswordAuthenticatorComponent.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)
*/
@@ -18,6 +18,7 @@
use RobThree\Auth\TwoFactorAuth;
use RuntimeException;
use Throwable;
+use function Cake\I18n\__d;
/**
* OneTimePasswordAuthenticator Component.
diff --git a/src/Exception/InvalidProviderException.php b/src/Exception/InvalidProviderException.php
index ed0d1c7..0a89dd8 100644
--- a/src/Exception/InvalidProviderException.php
+++ b/src/Exception/InvalidProviderException.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/Exception/InvalidSettingsException.php b/src/Exception/InvalidSettingsException.php
index e66757d..4c7b67e 100644
--- a/src/Exception/InvalidSettingsException.php
+++ b/src/Exception/InvalidSettingsException.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/Identifier/SocialIdentifier.php b/src/Identifier/SocialIdentifier.php
index 1561a0d..6047535 100644
--- a/src/Identifier/SocialIdentifier.php
+++ b/src/Identifier/SocialIdentifier.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/Middleware/RbacMiddleware.php b/src/Middleware/RbacMiddleware.php
index 56ceb6f..4e6e711 100644
--- a/src/Middleware/RbacMiddleware.php
+++ b/src/Middleware/RbacMiddleware.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/Middleware/SocialAuthMiddleware.php b/src/Middleware/SocialAuthMiddleware.php
index abe8384..372a9b7 100644
--- a/src/Middleware/SocialAuthMiddleware.php
+++ b/src/Middleware/SocialAuthMiddleware.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/Middleware/TwoFactorMiddleware.php b/src/Middleware/TwoFactorMiddleware.php
index 172376d..1a363c9 100644
--- a/src/Middleware/TwoFactorMiddleware.php
+++ b/src/Middleware/TwoFactorMiddleware.php
@@ -2,17 +2,18 @@
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\Middleware;
+use Authentication\AuthenticationServiceInterface;
use Cake\Http\Response;
use Cake\Routing\Router;
use CakeDC\Auth\Authentication\TwoFactorProcessorLoader;
@@ -30,7 +31,11 @@ class TwoFactorMiddleware implements MiddlewareInterface
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
{
$service = $request->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) {
@@ -52,9 +57,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,
+ ]);
+ } elseif ($params) {
+ $url .= (str_contains($url, '?') ? '&' : '?') . http_build_query($params);
+ }
+
$url = Router::url($url);
return (new Response())
diff --git a/src/Plugin.php b/src/Plugin.php
index 8210531..103b267 100644
--- a/src/Plugin.php
+++ b/src/Plugin.php
@@ -2,41 +2,23 @@
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;
-use Cake\Core\Configure;
-use Cake\Routing\RouteBuilder;
+namespace CakeDC\Auth;
/**
* 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')))],
- );
- });
- }
- }
}
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 0598ac7..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;
@@ -65,7 +66,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/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 60a52d8..ed0efc8 100644
--- a/src/Rbac/Permissions/AbstractProvider.php
+++ b/src/Rbac/Permissions/AbstractProvider.php
@@ -2,21 +2,20 @@
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\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,
@@ -99,14 +98,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' => OTPRule::class,
+ 'options' => [],
+ ],
],
//all roles allowed to Pages/display
[
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 635f8ed..cdd9a2b 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)
*/
@@ -24,6 +24,8 @@
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 InvalidArgumentException;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Log\LogLevel;
use RuntimeException;
@@ -88,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'),
@@ -176,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']);
@@ -221,6 +229,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) ||
+ (in_array($key, ['allowed', 'bypassAuth'], true) && is_array($value))
+ ) {
+ $return = $this->_ruleFromConfig($value)->allowed($user, $role, $request);
} elseif ($key === 'bypassAuth' && $value === true) {
$return = true;
} elseif ($key === 'allowed') {
@@ -241,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);
@@ -256,6 +269,57 @@ 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);
+ }
+
+ /**
+ * 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
+ *
+ * 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)) {
+ $className = $config['className'] ?? null;
+ throw new InvalidArgumentException(sprintf(
+ 'Permission rule `%s` is not a class implementing %s',
+ is_string($className) ? $className : get_debug_type($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/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
new file mode 100644
index 0000000..3c96bff
--- /dev/null
+++ b/src/Rbac/Rules/OTPRule.php
@@ -0,0 +1,38 @@
+getAttribute('params'), 'pass.0');
+ if (empty($userId) || empty($user['id'])) {
+ return false;
+ }
+
+ return (string)$userId === (string)$user['id'];
+ }
+}
diff --git a/src/Rbac/Rules/Owner.php b/src/Rbac/Rules/Owner.php
index c5772a3..596d7dd 100644
--- a/src/Rbac/Rules/Owner.php
+++ b/src/Rbac/Rules/Owner.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;
@@ -125,7 +126,10 @@ protected function getTableId(ServerRequestInterface $request): string
$requestKeyTypeData = $request->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 @@
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);
@@ -42,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/Mapper/AbstractMapper.php b/src/Social/Mapper/AbstractMapper.php
index e4fd1f7..6b48336 100644
--- a/src/Social/Mapper/AbstractMapper.php
+++ b/src/Social/Mapper/AbstractMapper.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 Cake\Utility\Hash;
use Cake\Utility\Inflector;
use League\OAuth2\Client\Token\AccessToken;
+use function Cake\Collection\collection;
/**
* AbstractMapper
@@ -102,14 +103,15 @@ protected function _validated(mixed $rawData): bool
protected function _map(mixed $rawData): mixed
{
$result = [];
- collection($this->_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
new file mode 100644
index 0000000..741bbaf
--- /dev/null
+++ b/src/Social/Mapper/Keycloak.php
@@ -0,0 +1,120 @@
+ 'given_name',
+ 'last_name' => 'family_name',
+ 'full_name' => 'name',
+ 'email' => 'email',
+ 'username' => 'preferred_username',
+ 'id' => 'sub',
+ 'link' => 'website',
+ 'roles' => 'realm_access.roles',
+ 'validated' => 'email_verified',
+ ];
+
+ /**
+ * Map Keycloak realm roles to application roles. The first matching entry wins.
+ *
+ * @var array
+ */
+ protected array $_rolesMap = [];
+
+ /**
+ * Constructor
+ *
+ * @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)
+ {
+ $mapFields ??= Configure::read('OAuth.providers.keycloak.mapFields') ?: null;
+ $rolesMap ??= Configure::read('OAuth.providers.keycloak.rolesMap');
+ 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);
+ }
+
+ /**
+ * 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 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
+ {
+ if (!$this->_rolesMap) {
+ return null;
+ }
+ $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',
+ );
+ }
+
+ foreach ($this->_rolesMap as $keycloakRole => $role) {
+ foreach ($keycloakRoles as $userRole) {
+ if ($userRole === $keycloakRole) {
+ 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 Hash::get($rawData, $this->_mapFields['validated']) === true;
+ }
+}
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
new file mode 100644
index 0000000..68ca046
--- /dev/null
+++ b/src/Social/Mapper/LinkedInOpenIDConnect.php
@@ -0,0 +1,58 @@
+ 'picture',
+ 'first_name' => 'given_name',
+ 'last_name' => 'family_name',
+ '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 Hash::get($rawData, $this->_mapFields['validated']) === true;
+ }
+
+ /**
+ * There is no way to retrieve the public profile url from the id token
+ *
+ * @return string
+ */
+ protected function _link(): string
+ {
+ return 'https://www.linkedin.com';
+ }
+}
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..a102541 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, 'rolesMap' => 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
new file mode 100644
index 0000000..218ea25
--- /dev/null
+++ b/src/Social/Service/OpenIDConnectService.php
@@ -0,0 +1,334 @@
+ [
+ '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');
+ }
+ 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');
+ }
+ if (!class_exists(JWT::class)) {
+ throw new RuntimeException('OpenIDConnectService requires the firebase/php-jwt package');
+ }
+ try {
+ $claims = $this->decodeIdToken($idToken);
+ } catch (Exception $ex) {
+ $this->log('Invalid OpenID Connect id token: ' . $ex->getMessage(), LogLevel::WARNING);
+
+ throw new BadRequestException('Invalid id token');
+ }
+ $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');
+ }
+ $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();
+ $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');
+ }
+ }
+ }
+
+ /**
+ * 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(bool $refresh = false): 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 (!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'),
+ );
+ }
+ $jwksData = $this->fetchJson($jwksUri, $refresh);
+ 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'));
+ }
+
+ /**
+ * 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'] ?? '/';
+ 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
+ *
+ * @return array
+ */
+ public function discover(): array
+ {
+ 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.
+ * @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, bool $refresh = false): array
+ {
+ $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 = $refresh ? null : Cache::read($key, $cacheConfig);
+ if (is_array($data) && $data) {
+ return $data;
+ }
+ $data = $fetch();
+ if ($data) {
+ Cache::write($key, $data, $cacheConfig);
+ }
+
+ return $data;
+ }
+
+ /**
+ * Get the http client
+ *
+ * @return \Cake\Http\Client
+ */
+ protected function getHttpClient(): Client
+ {
+ return new Client();
+ }
+}
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 1503aa3..8f1f724 100644
--- a/src/Test/BaseTestTrait.php
+++ b/src/Test/BaseTestTrait.php
@@ -1,11 +1,23 @@
get(Configure::read('Users.table', 'Users'))->get($id)->toArray();
- $this->session(['Auth' => ['User' => $data]]);
+ $this->session($this->_authSessionData($data));
}
/**
@@ -32,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);
}
/**
@@ -51,11 +79,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} ",
@@ -68,10 +102,10 @@ protected function _testPermissions(string $url, string $username, string $metho
), 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);
@@ -94,22 +128,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/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 007033b..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)
*/
@@ -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/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/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 e6ed09c..7e91a9d 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/Authenticator/OneTimeTokenAuthenticatorTest.php b/tests/TestCase/Authenticator/OneTimeTokenAuthenticatorTest.php
new file mode 100644
index 0000000..a5dcfea
--- /dev/null
+++ b/tests/TestCase/Authenticator/OneTimeTokenAuthenticatorTest.php
@@ -0,0 +1,133 @@
+
+ */
+ 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, []],
+ '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, []],
+ ];
+ }
+
+ /**
+ * @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/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..a701401 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,96 @@ 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'));
+ }
+
+ /**
+ * @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/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/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..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;
@@ -48,7 +51,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')]
@@ -66,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 61a6918..0e32ee2 100644
--- a/tests/TestCase/Rbac/RbacTest.php
+++ b/tests/TestCase/Rbac/RbacTest.php
@@ -16,13 +16,16 @@
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;
+use InvalidArgumentException;
use PHPUnit\Framework\Attributes\DataProvider;
use Psr\Log\LogLevel;
use ReflectionClass;
use RuntimeException;
+use stdClass;
class RbacTest extends TestCase
{
@@ -98,7 +101,10 @@ public function setUp(): void
'plugin' => 'CakeDC/Users',
'controller' => 'Users',
'action' => 'resetOneTimePasswordAuthenticator',
- 'allowed' => true,
+ 'allowed' => [
+ 'className' => OTPRule::class,
+ 'options' => [],
+ ],
],
//all roles allowed to Pages/display
[
@@ -126,21 +132,13 @@ public function tearDown(): void
unset($this->rbac);
}
- /**
- * @covers \CakeDC\Auth\Rbac\Rbac::__construct
- */
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);
}
- /**
- * @covers \CakeDC\Auth\Rbac\Rbac::__construct
- */
public function testConstructBadProvider()
{
$this->expectException(RuntimeException::class);
@@ -150,9 +148,6 @@ public function testConstructBadProvider()
]);
}
- /**
- * @covers \CakeDC\Auth\Rbac\Rbac::__construct
- */
public function testConstructSetPermissions()
{
$this->rbac = new Rbac([
@@ -172,9 +167,6 @@ protected function assertConstructorPermissions($instance, $config, $permissions
$this->assertEquals($permissions, $resultPermissions);
}
- /**
- * @dataProvider providerAuthorize
- */
#[DataProvider('providerAuthorize')]
public function testAuthorize($permissions, $user, $requestParams, $expected)
{
@@ -1197,7 +1189,6 @@ function () {
}
/**
- * @dataProvider badPermissionProvider
* @param array $permissions
* @param array $user
* @param array $requestParams
@@ -1366,10 +1357,134 @@ 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));
+ }
+
+ /**
+ * 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 $value): void
+ {
+ $permissions = [[
+ 'controller' => 'Users',
+ 'action' => 'resetOneTimePasswordAuthenticator',
+ $key => $value,
+ ]];
+ $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', ['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' => []]],
+ ];
+ }
+
public function testGetPermissions()
{
$permissions = ['test'];
$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/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/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/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/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
new file mode 100644
index 0000000..9756b5c
--- /dev/null
+++ b/tests/TestCase/Social/Mapper/KeycloakTest.php
@@ -0,0 +1,204 @@
+ 'admin',
+ 'CakeDc-User' => 'user',
+ ]);
+ }
+
+ /**
+ * @param array $roles realm roles
+ * @return array
+ */
+ protected function rawData(array $roles = ['offline_access', 'CakeDc-User']): array
+ {
+ return [
+ 'token' => 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-sensitive
+ *
+ * @return void
+ */
+ public function testRolesMapOrder(): void
+ {
+ $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']);
+ }
+
+ /**
+ * @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);
+ }
+
+ /**
+ * 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
+ *
+ * @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/LinkedInOpenIDConnectTest.php b/tests/TestCase/Social/Mapper/LinkedInOpenIDConnectTest.php
new file mode 100644
index 0000000..c861d7b
--- /dev/null
+++ b/tests/TestCase/Social/Mapper/LinkedInOpenIDConnectTest.php
@@ -0,0 +1,135 @@
+ 'test-token',
+ 'expires' => 1490988496,
+ ]);
+ $rawData = [
+ 'sub' => '1',
+ 'token' => $token,
+ 'email' => 'test@gmail.com',
+ 'email_verified' => true,
+ '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);
+ }
+
+ /**
+ * 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']);
+ }
+
+ /**
+ * 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']);
+ }
+}
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/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
*
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
new file mode 100644
index 0000000..f686d85
--- /dev/null
+++ b/tests/TestCase/Social/Service/OpenIDConnectServiceTest.php
@@ -0,0 +1,872 @@
+Client = $this->getMockBuilder(
+ Client::class,
+ )->onlyMethods([
+ 'get',
+ ])->getMock();
+
+ $this->Provider = $this->getMockBuilder(
+ LinkedIn::class,
+ )->setConstructorArgs([
+ [
+ 'id' => '1',
+ 'firstName' => 'first',
+ 'lastName' => 'last',
+ ],
+ [],
+ ])->onlyMethods([
+ 'getAccessToken', 'getState', 'getAuthorizationUrl', 'getResourceOwner',
+ ])->getMock();
+
+ $config = [
+ 'service' => OpenIDConnectService::class,
+ 'className' => $this->Provider,
+ '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,
+ 'mapFields' => [],
+ 'path' => [
+ 'plugin' => 'CakeDC/Users',
+ 'controller' => 'Users',
+ 'action' => 'socialLogin',
+ 'prefix' => null,
+ ],
+ ];
+
+ $this->Service = $this->getMockBuilder(
+ OpenIDConnectService::class,
+ )->setConstructorArgs([
+ $config,
+ ])->onlyMethods([
+ 'getIdTokenKeys',
+ 'getHttpClient',
+ ])->getMock();
+
+ $this->Service->expects($this->any())
+ ->method('getHttpClient')
+ ->willReturn($this->Client);
+
+ //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' => LinkedIn::class,
+ '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);
+ $this->expectExceptionMessage('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 AccessToken([
+ 'access_token' => 'test-token',
+ 'expires' => 1490988496,
+ ]);
+
+ $this->Provider->expects($this->once())
+ ->method('getAccessToken')
+ ->with(
+ $this->equalTo('authorization_code'),
+ $this->equalTo(['code' => 'ZPO9972j3092304230']),
+ )
+ ->willReturn($token);
+
+ $this->expectException(BadRequestException::class);
+ $this->expectExceptionMessage('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 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']),
+ )
+ ->willReturn($token);
+
+ $this->expectException(BadRequestException::class);
+ $this->expectExceptionMessage('Invalid id token');
+
+ $this->Service->getUser($this->Request);
+ }
+
+ /**
+ * Build a signed id token and prepare the request, provider and key set mocks
+ *
+ * @param array $payload id token claims
+ * @return \League\OAuth2\Client\Token\AccessToken
+ */
+ 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_with_at_least_32_bytes!';
+ $alg = 'HS256';
+ $kid = 'd929668a-bab1-4c69-9598-4373149723ff';
+ $token = new AccessToken([
+ 'access_token' => 'test-token',
+ 'expires' => 1490988496,
+ 'id_token' => JWT::encode($payload, $key, $alg, $kid),
+ ]);
+
+ $this->Provider->expects($this->once())
+ ->method('getAccessToken')
+ ->with(
+ $this->equalTo('authorization_code'),
+ $this->equalTo(['code' => 'ZPO9972j3092304230']),
+ )
+ ->willReturn($token);
+ $this->Service->expects($this->once())
+ ->method('getIdTokenKeys')
+ ->willReturn([$kid => new Key($key, $alg)]);
+
+ return $token;
+ }
+
+ /**
+ * Test GetUser
+ *
+ * @return void
+ */
+ public function testGetUser()
+ {
+ $payload = [
+ 'iat' => 1490988496,
+ 'iss' => 'https://www.linkedin.com/oauth',
+ 'aud' => '__CLIENT_ID__',
+ 'nonce' => '__NONCE__',
+ ];
+ $token = $this->prepareIdToken($payload);
+
+ $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'],
+ 'other authorized party' => [['azp' => 'other-client'] + $valid, 'Unexpected authorized party'],
+ 'several audiences without azp' => [
+ ['aud' => ['__CLIENT_ID__', 'other-client']] + $valid,
+ 'Unexpected authorized party',
+ ],
+ ];
+ }
+
+ /**
+ * 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'));
+ }
+
+ /**
+ * Test discover
+ *
+ * @return void
+ */
+ public function testDiscover()
+ {
+ $arrayTest = ['test' => 'test'];
+ $response = new Response(['HTTP/1.1 200 OK'], json_encode($arrayTest));
+
+ $this->Client->expects($this->once())
+ ->method('get')
+ ->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(['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 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
+ *
+ * @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));
+ }
+
+ /**
+ * 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],
+ '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],
+ ];
+ }
+
+ /**
+ * 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
new file mode 100644
index 0000000..ccb73fc
--- /dev/null
+++ b/tests/TestCase/Test/BaseTestTraitTest.php
@@ -0,0 +1,226 @@
+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());
+ }
+
+ /**
+ * @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/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')]
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);
+ }
+}
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' => [