diff --git a/.github/workflows/codecov.yml b/.github/workflows/codecov.yml index 89e83df..5cd87b3 100644 --- a/.github/workflows/codecov.yml +++ b/.github/workflows/codecov.yml @@ -15,14 +15,14 @@ jobs: - ubuntu-latest php: - - "8.2" - "8.3" - "8.4" - "8.5" + - "8.6" steps: - name: Checkout - uses: actions/checkout@v3 + uses: actions/checkout@v7 - name: Install PHP uses: shivammathur/setup-php@v2 @@ -36,7 +36,7 @@ jobs: run: echo "COMPOSER_CACHE_DIR=$(composer config cache-dir)" >> $GITHUB_ENV - name: Cache dependencies installed with composer - uses: actions/cache@v3 + uses: actions/cache@v6 with: path: ${{ env.COMPOSER_CACHE_DIR }} key: php${{ matrix.php }}-composer-${{ hashFiles('**/composer.json') }} @@ -49,6 +49,6 @@ jobs: run: vendor/bin/phpunit --colors=always --coverage-clover clover.xml - name: Send code coverage report to Codecov.io - uses: codecov/codecov-action@v3 + uses: codecov/codecov-action@v7 with: token: ${{ secrets.CODECOV_TOKEN }} diff --git a/.github/workflows/static-analysis.yml b/.github/workflows/static-analysis.yml index 9976515..8baba0f 100644 --- a/.github/workflows/static-analysis.yml +++ b/.github/workflows/static-analysis.yml @@ -15,14 +15,14 @@ jobs: - ubuntu-latest php: - - "8.2" - "8.3" - "8.4" - "8.5" + - "8.6" steps: - name: Checkout - uses: actions/checkout@v4 + uses: actions/checkout@v7 - name: Install PHP uses: shivammathur/setup-php@v2 @@ -36,7 +36,7 @@ jobs: run: echo "COMPOSER_CACHE_DIR=$(composer config cache-dir)" >> $GITHUB_ENV - name: Cache dependencies installed with composer - uses: actions/cache@v4 + uses: actions/cache@v6 with: path: ${{ env.COMPOSER_CACHE_DIR }} key: php${{ matrix.php }}-composer-${{ hashFiles('**/composer.json') }} @@ -47,4 +47,4 @@ jobs: run: composer install --prefer-dist --no-interaction --no-progress --optimize-autoloader --ansi - name: Run static analysis with PHPStan - run: vendor/bin/phpstan analyse + run: composer static-analysis diff --git a/.gitignore b/.gitignore index 4bfb766..45f8992 100644 --- a/.gitignore +++ b/.gitignore @@ -34,6 +34,7 @@ composer.phar /vendor/ .phpcs-cache .phpunit.result.cache +.phpunit.cache # Commit your application's lock file http://getcomposer.org/doc/01-basic-usage.md#composer-lock-the-lock-file # You may choose to ignore a library lock file http://getcomposer.org/doc/02-libraries.md#lock-file diff --git a/.laminas-ci.json b/.laminas-ci.json index 29216fa..e827682 100644 --- a/.laminas-ci.json +++ b/.laminas-ci.json @@ -1,3 +1,6 @@ { + "ignore_php_platform_requirements": { + "8.6": true + }, "backwardCompatibilityCheck": true } diff --git a/CHANGELOG.md b/CHANGELOG.md index 07b0228..0853a22 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,87 +1,620 @@ +# Changelog + +The dates of releases 2.0.0 to 4.2.1 are the dates of the tagged commits. + +## 5.0.0 - TBD + +### Changed + +* The package works with any PSR-11 container. `AssertionPluginManager` and `RoleProviderPluginManager` extend `Dot\Rbac\Plugin\AbstractPluginManager` instead of `Laminas\ServiceManager\AbstractPluginManager`. +* `isGranted()` accepts role names and role objects. +* `RoleServiceInterface` has the new method `resolveRoles()`. It replaces the protected method `RoleService::convertRoles()`. +* `Rbac` checks permissions only on roles that implement `PermissionRoleInterface`. +* `AuthorizationService::addAssertion()` accepts only `AssertionInterface` or a non-empty array. +* `RoleService` throws a `RuntimeException` for an identity that is not `null` and has no `getRoles()` method. +* PHPStan level 8. +* PHPUnit 12, with fixtures instead of mocks. + +### Added + +* PHP 8.6 support. +* `Dot\Rbac\Plugin\AbstractPluginManager` and `Dot\Rbac\Plugin\InvokableFactory`. +* `Dot\Rbac\Role\PermissionRoleInterface`. +* `Dot\Rbac\Role\RoleFlattener`. +* `Dot\Rbac\Factory\RbacFactory`. +* `psr/container` as a direct requirement. +* Documentation for version 5 and an upgrade guide. + +### Deprecated + +* Nothing + +### Removed + +* PHP 8.2 support. +* `laminas/laminas-servicemanager` requirement. +* Plugin manager support for `invokables`, `abstract_factories`, `delegators` and `shared`. + +### Fixed + +* Infinite recursion on a circular role hierarchy. +* `Error` when `isGranted()` gets role names. +* `TypeError` or `Error` for integer roles and roles named like a class. +* `Error` for an identity without `getRoles()`. +* `Error` for an empty assertion specification. +* `TypeError` for an assertion or role provider type that is not a string. +* Syntax error in the hierarchical configuration example. + +## 4.2.1 - 2025-10-31 + +### Changed + +* Nothing + +### Added + +* Nothing + +### Deprecated + +* Nothing + +### Removed + +* Nothing + +### Fixed + +* PHP version badge in `SECURITY.md` and the v3 documentation (#38). + +## 4.2.0 - 2025-10-31 + +### Changed + +* Nothing + +### Added + +* PHP 8.4 and 8.5 support (#34). + +### Deprecated + +* Nothing + +### Removed + +* PHP 8.1 support (#34). + +### Fixed + +* Nothing + +## 4.1.0 - 2025-03-14 + +### Changed + +* PHPStan replaces Psalm (#32). + +### Added + +* Nothing + +### Deprecated + +* Nothing + +### Removed + +* Psalm (#32). + +### Fixed + +* Nothing + +## 4.0.1 - 2025-01-28 + +### Changed + +* Psalm 6.x (#28). + +### Added + +* Nothing + +### Deprecated + +* Nothing + +### Removed + +* Nothing + +### Fixed + +* Nothing + +## 4.0.0 - 2025-01-23 + +### Changed + +* `laminas/laminas-servicemanager` 4.x (#26). + +### Added + +* `RoleProviderPluginManager` test. + +### Deprecated + +* Nothing + +### Removed + +* `laminas/laminas-servicemanager` 3.x support (#26). + +### Fixed + +* Nothing + +## 3.8.0 - 2025-10-31 + +### Changed + +* Nothing + +### Added + +* PHP 8.4 and 8.5 support (#36). + +### Deprecated + +* Nothing + +### Removed + +* PHP 8.1 support (#36). + +### Fixed + +* Nothing + +## 3.7.0 - 2025-03-11 + +### Changed + +* PHPStan replaces Psalm (#30). + +### Added + +* Nothing + +### Deprecated + +* Nothing + +### Removed + +* Psalm (#30). + +### Fixed + +* Nothing + +## 3.6.0 - 2024-05-03 + +### Changed + +* Code review. +* Documentation, workflows and `SECURITY.md`. + +### Added + +* Nothing + +### Deprecated + +* Nothing + +### Removed + +* Nothing + +### Fixed + +* Nothing + +## 3.5.2 - 2023-11-29 + +### Changed + +* Nothing + +### Added + +* PHP 8.3 support. + +### Deprecated + +* Nothing + +### Removed + +* Nothing + +### Fixed + +* Nothing + +## 3.5.1 - 2023-08-24 + +### Changed + +* Nothing + +### Added + +* Codecov. + +### Deprecated + +* Nothing + +### Removed + +* Nothing + +### Fixed + +* Nothing + +## 3.5.0 - 2023-08-11 + +### Changed + +* Return types on methods. +* README. + +### Added + +* Psalm, PHPUnit, Laminas coding standard and tests. + +### Deprecated + +* Nothing + +### Removed + +* PHP 7.4 and 8.0 support. +* Unnecessary code. + +### Fixed + +* Nothing + +## 3.4.0 - 2023-03-29 + +### Changed + +* Nothing + +### Added + +* Nothing + +### Deprecated + +* Nothing + +### Removed + +* `laminas/laminas-dependency-plugin`. + +### Fixed + +* Nothing + +## 3.3.0 - 2022-04-29 + +### Changed + +* Dependencies. + +### Added + +* README badges. + +### Deprecated + +* Nothing + +### Removed + +* Nothing + +### Fixed + +* Nothing + ## 3.2.0 - 2020-11-03 ### Changed + * Composer 2 compatibility. * Update composer.json to require version 2 of laminas/laminas-dependency-plugin to be Composer 2 compatible. ### Added + * Nothing ### Deprecated + * Nothing ### Removed + * Nothing ### Fixed + * bump min version of laminas/laminas-dependency-plugin * bump min version of dotkernel/dot-authorization +## 3.1.1 - 2020-05-25 + +### Changed + +* Nothing + +### Added + +* Nothing + +### Deprecated + +* Nothing + +### Removed + +* Nothing + +### Fixed + +* An unspecified issue (commit "fix some issue"). + +## 3.1.0 - 2020-05-15 + +### Changed + +* Compatibility with the 3.0 packages. + +### Added + +* Nothing + +### Deprecated + +* Nothing + +### Removed + +* Nothing + +### Fixed + +* Nothing + +## 3.0.1 - 2020-05-14 + +### Changed + +* `composer.json`. + +### Added + +* Nothing + +### Deprecated + +* Nothing + +### Removed + +* Nothing + +### Fixed + +* Nothing + +## 3.0.0 - 2020-05-14 + +### Changed + +* Zend to Laminas, Expressive to Mezzio. +* PHP 7.4 or higher. + +### Added + +* Nothing + +### Deprecated + +* Nothing + +### Removed + +* Nothing + +### Fixed + +* Nothing + +## 2.9.2 - 2024-03-27 + +### Changed + +* Nothing + +### Added + +* PHP 8.3 support (2.x line). + +### Deprecated + +* Nothing + +### Removed + +* Nothing + +### Fixed + +* Nothing + +## 2.9.1 - 2023-08-23 + +### Changed + +* Composer dependencies (2.x line). + +### Added + +* Nothing + +### Deprecated + +* Nothing + +### Removed + +* Nothing + +### Fixed + +* Nothing + +## 2.9.0 - 2023-02-13 + +### Changed + +* PHP 8 support and Composer cleanup (2.x line). + +### Added + +* Nothing + +### Deprecated + +* Nothing + +### Removed + +* Nothing + +### Fixed + +* Nothing + +## 2.0.0 - 2020-01-30 + +### Changed + +* Zend to Laminas, Expressive to Mezzio. + +### Added + +* Nothing + +### Deprecated + +* Nothing + +### Removed + +* Nothing + +### Fixed + +* Nothing + ## 0.2.1 - 2018-05-08 ### Changed + * updated dependencies ### Added + * Nothing ### Deprecated + * Nothing ### Removed + * Nothing ### Fixed -* Nothing +* Nothing ## 0.2.0 - 2017-03-17 ### Changed + * updated factories to use PSR11 container ### Added + * Nothing ### Deprecated + * Nothing ### Removed + * Nothing ### Fixed -* Nothing +* Nothing ## 0.1.1 - 2017-03-11 Updated php file headers doc blocks ### Added + * Nothing ### Deprecated + * Nothing ### Removed + * Nothing ### Fixed -* Nothing +* Nothing ## 0.1.0 - 2017-03-09 Initial tagged release ### Added + * Everything ### Deprecated + * Nothing ### Removed + * Nothing ### Fixed + * Nothing diff --git a/README.md b/README.md index f89ada2..e874f6e 100644 --- a/README.md +++ b/README.md @@ -1,30 +1,41 @@ # dot-rbac Rbac authorization model implements [dot-authorization](https://github.com/dotkernel/dot-authorization)'s `AuthorizationInterface`. -An authorization service is responsible for deciding if the authenticated identity or guest has access to certain parts of the application. +An authorization service decides if the authenticated identity or guest has access to certain parts of the application. -The RBAC model defines roles that can be assigned to users. -The authorization is done on a role basis, not a user basis as in ACL. -Each role can have one or multiple permissions/privileges assigned. -When deciding if a user is authorized, the requested permission is checked in all user roles, and if at least one role has that permission, access is granted. +The RBAC model defines roles that you assign to users. +The authorization uses roles, not users as in ACL. +Each role can have one or more permissions. +To decide if a user has access, the service looks for the requested permission in all the roles of the user. +If one role has the permission, the user has access. ## Documentation Documentation is available at: https://docs.dotkernel.org/dot-rbac/. +## Versions + +| Version | Container | PHP | +| --- | --- | --- | +| 5.x | Any PSR-11 container. `laminas/laminas-servicemanager` is not a requirement | 8.3 or higher | +| 4.x | `laminas/laminas-servicemanager` 4.x | 8.2 to 8.5 | +| 3.x | `laminas/laminas-servicemanager` 3.x | 8.2 to 8.5 | + +To upgrade from an older version, read the [upgrade guide](https://docs.dotkernel.org/dot-rbac/v5/upgrading/). + ## Badges ![OSS Lifecycle](https://img.shields.io/osslifecycle/dotkernel/dot-rbac) -![PHP from Packagist (specify version)](https://img.shields.io/packagist/php-v/dotkernel/dot-rbac/4.2.0) +![PHP from Packagist (specify version)](https://img.shields.io/packagist/php-v/dotkernel/dot-rbac/5.0.0) [![GitHub issues](https://img.shields.io/github/issues/dotkernel/dot-rbac)](https://github.com/dotkernel/dot-rbac/issues) [![GitHub forks](https://img.shields.io/github/forks/dotkernel/dot-rbac)](https://github.com/dotkernel/dot-rbac/network) [![GitHub stars](https://img.shields.io/github/stars/dotkernel/dot-rbac)](https://github.com/dotkernel/dot-rbac/stargazers) -[![GitHub license](https://img.shields.io/github/license/dotkernel/dot-rbac)](https://github.com/dotkernel/dot-rbac/blob/4.0/LICENSE.md) +[![GitHub license](https://img.shields.io/github/license/dotkernel/dot-rbac)](https://github.com/dotkernel/dot-rbac/blob/5.0/LICENSE.md) -[![Build Static](https://github.com/dotkernel/dot-rbac/actions/workflows/continuous-integration.yml/badge.svg?branch=4.0)](https://github.com/dotkernel/dot-rbac/actions/workflows/continuous-integration.yml) +[![Build Static](https://github.com/dotkernel/dot-rbac/actions/workflows/continuous-integration.yml/badge.svg?branch=5.0)](https://github.com/dotkernel/dot-rbac/actions/workflows/continuous-integration.yml) [![codecov](https://codecov.io/gh/dotkernel/dot-rbac/graph/badge.svg?token=GCK6C92N83)](https://codecov.io/gh/dotkernel/dot-rbac) -[![PHPStan](https://github.com/dotkernel/dot-rbac/actions/workflows/static-analysis.yml/badge.svg?branch=4.0)](https://github.com/dotkernel/dot-rbac/actions/workflows/static-analysis.yml) +[![PHPStan](https://github.com/dotkernel/dot-rbac/actions/workflows/static-analysis.yml/badge.svg?branch=5.0)](https://github.com/dotkernel/dot-rbac/actions/workflows/static-analysis.yml) ## Installation @@ -34,131 +45,137 @@ Run the following command in your project root directory: composer require dotkernel/dot-rbac ``` +The package works with any PSR-11 container that accepts a factory for each service key, for example Laminas Service Manager. +If your application uses Laminas Service Manager, require `laminas/laminas-servicemanager` in your application's `composer.json`. + ## Configuration -Even if the authorization service can be programmatically configured, we recommend using the configuration-based approach. -We further describe how to configure the module, using a configuration file. +You can configure the authorization service in code, but we recommend the configuration file. -First, you should enable the module in your application by merging this package's `ConfigProvider` with your application's config. -This ensures that all dependencies required by this module are registered in the service manager. -It also defines default config values for this module. +First, merge the `ConfigProvider` of this package with the configuration of your application. +The `ConfigProvider` registers all the services of this package in your container. +It also sets the default configuration values. -Create a configuration file in your `config/autoload` folder and change the module options as needed. +Then create a configuration file in your `config/autoload` folder and change the options as necessary. +The file `authorization.global.php.dist` in this repository is an example. ### authorization.global.php ```php -'dot_authorization' => [ - //name of the guest role to use if no identity is provided - 'guest_role' => 'guest', - - 'role_provider_manager' => [], - - //example for a flat RBAC model using the InMemoryRoleProvider - 'role_provider' => [ - 'type' => 'InMemory', - 'options' => [ - 'roles' => [ - 'admin' => [ - 'permissions' => [ - 'edit', - 'delete', - //etc.. - ] + [ + // the name of the guest role, used when there is no authenticated identity + 'guest_role' => 'guest', + + // more role providers, in the same format as 'assertion_manager' + 'role_provider_manager' => [], + + // a hierarchical RBAC model with the InMemoryRoleProvider + 'role_provider' => [ + 'type' => 'InMemory', + 'options' => [ + 'roles' => [ + 'admin' => [ + 'children' => ['user'], + 'permissions' => ['create', 'delete'], + ], + 'user' => [ + 'children' => ['guest'], + 'permissions' => ['edit'], + ], + 'guest' => [ + 'permissions' => ['view'], + ], ], - 'user' => [ - 'permissions' => [ - //... - ] - ] - ] + ], ], - ], - - //example for a hierarchical model, less to write, but it can be confusing sometimes - /*'role_provider' => [ - 'type' => 'InMemory', - 'options' => [ - 'roles' => [ - 'admin' => [ - 'children' => ['user'], - 'permissions' => ['create', 'delete'] - ], - 'user' => [ - 'children' => ['guest'] - 'permissions' => ['edit'] - ] - 'guest' => [ - 'permissions' => ['view'] - ] - ] - ] - ],*/ - - 'assertion_manager' => [ - 'factories' => [ - //EditAssertion::class => InvokableFactory::class, + + // the factories and aliases that create your assertions + 'assertion_manager' => [ + 'factories' => [ + EditAssertion::class => InvokableFactory::class, + ], + ], + + // the assertions and the permissions that they apply to + 'assertions' => [ + [ + 'type' => EditAssertion::class, + 'permissions' => ['edit'], + 'options' => [], + ], ], ], - - 'assertions' => [ - [ - 'type' => EditAssertion::class, - 'permissions' => ['edit'], - 'options' => [] - ] - ] -] +]; ``` +`App\Assertion\EditAssertion` is an example class. +Replace it with your own assertion, or remove the `assertion_manager` factory and the `assertions` entry. + +A role hierarchy must not have a cycle. +The `InMemoryRoleProvider` throws a `Dot\Rbac\Exception\RuntimeException` when it finds a cycle. + ## Usage -Whenever you need to check if someone is authorized to take some actions, inject the `AuthorizationInterface::class` service into your class, then call the `isGranted` method with the correct parameters. -There are two ways to call the isGranted method. +To check if someone has access to an action, inject the `AuthorizationInterface::class` service into your class. +Then call the `isGranted` method. +There are two ways to call the `isGranted` method. ### First method -Specify which roles you want to check. +Specify the roles that you want to check. +A role can be a role name or an object that implements `Dot\Authorization\Role\RoleInterface`. ```php -$isGranted = $this->authorizationService->isGranted($permission, $roles); +$isGranted = $this->authorizationService->isGranted('edit', ['admin', 'user']); ``` ### Second method -Do not specify the roles or send an empty array as the second parameter. -This will check if the authenticated identity has permission. +Do not specify the roles, or send an empty array as the second parameter. +The service then checks the roles of the authenticated identity. +If there is no authenticated identity, the service checks the guest role. ```php -$isGranted = $this->authorizationService->isGranted($permission); +$isGranted = $this->authorizationService->isGranted('edit'); ``` ## Customize the IdentityProvider -Whenever you request an authorization check on the authenticated identity, the identity will be provided to the `AuthorizationService` through a registered `IdentityProviderInterface` service. +When you check the authorization of the authenticated identity, the `AuthorizationService` gets the identity from the `IdentityProviderInterface` service. -This is because identity is authentication-dependent, so the module lets you overwrite this service, depending on your needs. -If you want to get the identity from other sources instead of the dot-authentication service, overwrite the `IdentityProviderInterface::class` service in the service manager with your own implementation of this interface. +The identity depends on the authentication, so you can replace this service. +The default implementation gets the identity from `Laminas\Authentication\AuthenticationService`. +To get the identity from a different source, register your own implementation of `IdentityProviderInterface` in your container. ## Custom role providers -Write your own role provider by implementing the `RoleProviderInterface` and register it in the `RoleProviderPluginManager`. -After that, you can use them in the configuration file, as described above. +To write your own role provider, implement `RoleProviderInterface`. +Then register a factory for it under `role_provider_manager.factories` in the configuration file. ## Creating assertions -Assertions are checked after permission is granted, right before returning the authorization result. -Assertions can have the last word in deciding if someone is authorized for the requested action. -A good assertion example could be an edit permission, but with the restriction that it should be able to edit the item just if the `user id` matches the item's `owner id`. -It is up to you to write the logic inside an assertion. +The service checks the assertions after it finds the permission, before it returns the result. +An assertion can deny access that the role permissions allow. +For example, an assertion can allow the `edit` permission only when the user id is the same as the owner id of the item. +You write the logic of the assertion. -An assertion has to implement the `AssertionInterface` and be registered in the `AssertionPluginManager`. +An assertion implements `AssertionInterface`. +Register a factory for it under `assertion_manager.factories` in the configuration file. -This interface defines the following method +The interface defines this method: ```php -public function assert(AuthorizationInterface $authorization, $context = null); +public function assert(AuthorizationInterface $authorization, mixed $context = null): bool; ``` -The context variable can be any external data that an assertion needs to decide the authorization status. -The assertion must return a boolean value, reflecting the assertion pass or failure status. +The `$context` parameter is the third parameter of `isGranted`. +It can be any data that the assertion needs to make the decision. +The assertion returns `true` to allow access and `false` to deny access. diff --git a/SECURITY.md b/SECURITY.md index ae23858..446e86d 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -4,6 +4,7 @@ | Version | Supported | PHP Version | |---------|--------------------|----------------------------------------------------------------------------------------------------------| +| 5.x | :white_check_mark: | ![PHP from Packagist (specify version)](https://img.shields.io/packagist/php-v/dotkernel/dot-rbac/5.0.0) | | 4.x | :white_check_mark: | ![PHP from Packagist (specify version)](https://img.shields.io/packagist/php-v/dotkernel/dot-rbac/4.2.0) | | 3.x | :x: | ![PHP from Packagist (specify version)](https://img.shields.io/packagist/php-v/dotkernel/dot-rbac/3.8.0) | | <= 2.x | :x: | | @@ -26,7 +27,6 @@ release prior to any public exposure; this helps protect the project's users and provides them with a chance to upgrade and/or update to protect their applications. - ## Policy If we verify a reported security vulnerability, our policy is: @@ -36,4 +36,3 @@ If we verify a reported security vulnerability, our policy is: - After patching the release branches, we will immediately issue new security fix releases for each patched release branch. - diff --git a/authorization.global.php.dist b/authorization.global.php.dist index 381ec47..8144189 100644 --- a/authorization.global.php.dist +++ b/authorization.global.php.dist @@ -2,66 +2,70 @@ declare(strict_types=1); +use Dot\Rbac\Plugin\InvokableFactory; + return [ 'dot_authorization' => [ - //name of the guest role to use if no identity is provided + // the name of the guest role, used when there is no authenticated identity 'guest_role' => 'guest', + // more role providers, in the same format as 'assertion_manager' 'role_provider_manager' => [], - //example for a flat RBAC model using the InMemoryRoleProvider + // a flat RBAC model with the InMemoryRoleProvider 'role_provider' => [ - 'type' => 'InMemory', + 'type' => 'InMemory', 'options' => [ 'roles' => [ 'admin' => [ 'permissions' => [ 'edit', 'delete', - //etc.. - ] + ], ], - 'user' => [ + 'user' => [ 'permissions' => [ - //... - ] - ] - ] + 'view', + ], + ], + ], ], ], - //example for a hierarchical model, less to write but it can be confusing sometimes + // a hierarchical RBAC model: a role also gets the permissions of its child roles /*'role_provider' => [ - 'type' => 'InMemory', + 'type' => 'InMemory', 'options' => [ 'roles' => [ 'admin' => [ - 'children' => ['user'], - 'permissions' => ['create', 'delete'] + 'children' => ['user'], + 'permissions' => ['create', 'delete'], + ], + 'user' => [ + 'children' => ['guest'], + 'permissions' => ['edit'], ], - 'user' => [ - 'children' => ['guest'] - 'permissions' => ['edit'] - ] 'guest' => [ - 'permissions' => ['view'] - ] - ] - ] + 'permissions' => ['view'], + ], + ], + ], ],*/ + // the factories and aliases that create your assertions 'assertion_manager' => [ 'factories' => [ - //EditAssertion::class => InvokableFactory::class, + // App\Assertion\EditAssertion::class => InvokableFactory::class, ], ], + // the assertions and the permissions that they apply to 'assertions' => [ - [ - 'type' => EditAssertion::class, + /*[ + 'type' => App\Assertion\EditAssertion::class, 'permissions' => ['edit'], - 'options' => [] - ] - ] - ] + 'options' => [], + ],*/ + ], + ], ]; diff --git a/composer.json b/composer.json index 861d8fb..ea789cc 100644 --- a/composer.json +++ b/composer.json @@ -22,17 +22,17 @@ } }, "require": { - "php": "~8.2.0 || ~8.3.0 || ~8.4.0 || ~8.5.0", - "dotkernel/dot-authorization": "^3.6.0", + "php": "~8.3.0 || ~8.4.0 || ~8.5.0 || ~8.6.0", + "dotkernel/dot-authorization": "^3.6.0 || ^4.0", "laminas/laminas-authentication": "^2.16.0", - "laminas/laminas-servicemanager": "^4.0", - "laminas/laminas-stdlib": "^3.7" + "laminas/laminas-stdlib": "^3.19", + "psr/container": "^1.1 || ^2.0" }, "require-dev": { "laminas/laminas-coding-standard": "^3.0", "phpstan/phpstan": "^2.1", "phpstan/phpstan-phpunit": "^2.0", - "phpunit/phpunit": "^10.2" + "phpunit/phpunit": "^12.5" }, "autoload": { "psr-4": { diff --git a/docs/book/v5/configuration.md b/docs/book/v5/configuration.md new file mode 100644 index 0000000..4526ebd --- /dev/null +++ b/docs/book/v5/configuration.md @@ -0,0 +1,118 @@ +# Configuration + +You can configure the authorization service in code, but we recommend the configuration file. +This page shows how to configure the package with a configuration file. + +First, merge the `ConfigProvider` of this package with the configuration of your application. +The `ConfigProvider` registers all the services of this package in your container. +It also sets the default configuration values. + +Then create a configuration file in your `config/autoload` folder and change the options as necessary. + +## authorization.global.php + +```php + [ + // the name of the guest role, used when there is no authenticated identity + 'guest_role' => 'guest', + + // more role providers, in the same format as 'assertion_manager' + 'role_provider_manager' => [], + + // a flat RBAC model with the InMemoryRoleProvider + 'role_provider' => [ + 'type' => 'InMemory', + 'options' => [ + 'roles' => [ + 'admin' => [ + 'permissions' => [ + 'edit', + 'delete', + ], + ], + 'user' => [ + 'permissions' => [ + 'view', + ], + ], + ], + ], + ], + + // the factories and aliases that create your assertions + 'assertion_manager' => [ + 'factories' => [ + EditAssertion::class => InvokableFactory::class, + ], + ], + + // the assertions and the permissions that they apply to + 'assertions' => [ + [ + 'type' => EditAssertion::class, + 'permissions' => ['edit'], + 'options' => [], + ], + ], + ], +]; +``` + +`App\Assertion\EditAssertion` is an example class. +Replace it with your own assertion, or remove the `assertion_manager` factory and the `assertions` entry. + +## A hierarchical model + +A role can have child roles. +A role then has its own permissions and the permissions of all its child roles. + +```php + [ + 'role_provider' => [ + 'type' => 'InMemory', + 'options' => [ + 'roles' => [ + 'admin' => [ + 'children' => ['user'], + 'permissions' => ['create', 'delete'], + ], + 'user' => [ + 'children' => ['guest'], + 'permissions' => ['edit'], + ], + 'guest' => [ + 'permissions' => ['view'], + ], + ], + ], + ], + ], +]; +``` + +A role hierarchy must not have a cycle. +For example, `admin` must not be a child of `user` when `user` is a child of `admin`. +The `InMemoryRoleProvider` throws a `Dot\Rbac\Exception\RuntimeException` when it finds a cycle. + +## Plugin managers + +The keys `assertion_manager` and `role_provider_manager` accept two keys: + +- `factories`: a map of plugin name to factory. A factory is a class name or a callable. It gets the container, the plugin name and the `options`. +- `aliases`: a map of alias to plugin name. + +Use `Dot\Rbac\Plugin\InvokableFactory` for a class that has no constructor arguments, or one array argument. +The `InMemoryRoleProvider` is registered by default, with the aliases `InMemory`, `inMemory` and `inmemory`. diff --git a/docs/book/v5/customization.md b/docs/book/v5/customization.md new file mode 100644 index 0000000..4095fb4 --- /dev/null +++ b/docs/book/v5/customization.md @@ -0,0 +1,72 @@ +# Customization + +## Customize the IdentityProvider + +When you check the authorization of the authenticated identity, the `AuthorizationService` gets the identity from the `IdentityProviderInterface` service. + +The identity depends on the authentication, so you can replace this service. +The default implementation gets the identity from `Laminas\Authentication\AuthenticationService`. +To get the identity from a different source, register your own implementation of `IdentityProviderInterface` in your container, under the key `Dot\Rbac\Identity\IdentityProviderInterface`. + +The identity must implement `Dot\Authorization\Identity\IdentityInterface`. +If the identity is `null`, the service uses the guest role. + +## Custom role providers + +To write your own role provider, implement `Dot\Rbac\Role\Provider\RoleProviderInterface`. +Then register a factory for it in the `role_provider_manager` configuration. + +```php +'role_provider_manager' => [ + 'factories' => [ + DatabaseRoleProvider::class => DatabaseRoleProviderFactory::class, + ], + 'aliases' => [ + 'Database' => DatabaseRoleProvider::class, + ], +], +'role_provider' => [ + 'type' => 'Database', + 'options' => [], +], +``` + +The factory gets the container, the plugin name and the `options`. + +```php +public function __invoke(ContainerInterface $container, string $requestedName, ?array $options = null): DatabaseRoleProvider +``` + +## Custom roles + +The `Rbac` service checks permissions only on roles that implement `Dot\Rbac\Role\PermissionRoleInterface`. +`Dot\Rbac\Role\Role` and `Dot\Rbac\Role\HierarchicalRole` implement it. +If you write your own role class, extend `Role` or implement `PermissionRoleInterface`. +To give a role child roles, implement `Dot\Rbac\Role\HierarchicalRoleInterface`. + +## Creating assertions + +The service checks the assertions after it finds the permission, before it returns the result. +An assertion can deny access that the role permissions allow. +For example, an assertion can allow the `edit` permission only when the user id is the same as the owner id of the item. +You write the logic of the assertion. + +An assertion implements `Dot\Rbac\Assertion\AssertionInterface`. +Register a factory for it in the `assertion_manager` configuration, then add it to `assertions`. +See [Configuration](configuration.md). + +The interface defines this method: + +```php +public function assert(AuthorizationInterface $authorization, mixed $context = null): bool; +``` + +The `$context` parameter is the third parameter of `isGranted`. +It can be any data that the assertion needs to make the decision. +The assertion returns `true` to allow access and `false` to deny access. + +You can also add an assertion in code: + +```php +$authorizationService->addAssertion('edit', new EditAssertion()); +``` diff --git a/docs/book/v5/installation.md b/docs/book/v5/installation.md new file mode 100644 index 0000000..619ab01 --- /dev/null +++ b/docs/book/v5/installation.md @@ -0,0 +1,13 @@ +# Installation + +Run the following command in your project root directory: + +```shell +composer require dotkernel/dot-rbac +``` + +Version 5 requires PHP 8.3 or higher. + +The package works with any PSR-11 container that accepts a factory for each service key, for example Laminas Service Manager. +The package does not install a container. +If your application uses Laminas Service Manager, require `laminas/laminas-servicemanager` in your application's `composer.json`. diff --git a/docs/book/v5/overview.md b/docs/book/v5/overview.md new file mode 100644 index 0000000..4273fae --- /dev/null +++ b/docs/book/v5/overview.md @@ -0,0 +1,19 @@ +# dot-rbac + +The rbac authorization service decides if the authenticated identity or guest has access to certain parts of the application. + +Version 5 works with any PSR-11 container. It does not require `laminas/laminas-servicemanager`. + +## Badges + +![OSS Lifecycle](https://img.shields.io/osslifecycle/dotkernel/dot-rbac) +![PHP from Packagist (specify version)](https://img.shields.io/packagist/php-v/dotkernel/dot-rbac/5.0.0) + +[![GitHub issues](https://img.shields.io/github/issues/dotkernel/dot-rbac)](https://github.com/dotkernel/dot-rbac/issues) +[![GitHub forks](https://img.shields.io/github/forks/dotkernel/dot-rbac)](https://github.com/dotkernel/dot-rbac/network) +[![GitHub stars](https://img.shields.io/github/stars/dotkernel/dot-rbac)](https://github.com/dotkernel/dot-rbac/stargazers) +[![GitHub license](https://img.shields.io/github/license/dotkernel/dot-rbac)](https://github.com/dotkernel/dot-rbac/blob/5.0/LICENSE.md) + +[![Build Static](https://github.com/dotkernel/dot-rbac/actions/workflows/continuous-integration.yml/badge.svg?branch=5.0)](https://github.com/dotkernel/dot-rbac/actions/workflows/continuous-integration.yml) +[![codecov](https://codecov.io/gh/dotkernel/dot-rbac/graph/badge.svg?token=GCK6C92N83)](https://codecov.io/gh/dotkernel/dot-rbac) +[![PHPStan](https://github.com/dotkernel/dot-rbac/actions/workflows/static-analysis.yml/badge.svg?branch=5.0)](https://github.com/dotkernel/dot-rbac/actions/workflows/static-analysis.yml) diff --git a/docs/book/v5/upgrading.md b/docs/book/v5/upgrading.md new file mode 100644 index 0000000..c6dbece --- /dev/null +++ b/docs/book/v5/upgrading.md @@ -0,0 +1,70 @@ +# Upgrading + +This page describes the changes that can break your code when you upgrade to version 5. + +## From 4.x to 5.x + +| Change | Symptom | Fix | +| --- | --- | --- | +| PHP 8.2 is not supported | Composer does not install 5.x | Use PHP 8.3 or higher | +| `laminas/laminas-servicemanager` is not a requirement | Class `Laminas\ServiceManager\...` not found, if your application uses it but does not require it | Add `laminas/laminas-servicemanager` to your application's `composer.json` | +| The plugin managers do not extend the Laminas `AbstractPluginManager` | Call to undefined method `get()`, `configure()` or `setFactory()` | Use `build()`, and the `factories` and `aliases` configuration | +| `InvalidServiceException` is not thrown | A `catch` block does not run | Catch `Dot\Rbac\Exception\InvalidArgumentException` or `Dot\Rbac\Exception\ExceptionInterface` | +| The plugin manager keys `invokables`, `abstract_factories`, `delegators` and `shared` are ignored | `Dot\Rbac\Exception\InvalidArgumentException`: "No factory is registered for plugin" | Register each plugin under `factories`, for example with `Dot\Rbac\Plugin\InvokableFactory` | +| `RoleServiceInterface::resolveRoles()` is new | Fatal error in your own implementation of the interface | Add the method | +| `RoleService::convertRoles()` is now the public method `resolveRoles()` | Call to undefined method `convertRoles()` in a subclass | Call `resolveRoles()` | +| `Rbac` checks permissions only on `PermissionRoleInterface` roles | Your own role class gets no permissions | Implement `Dot\Rbac\Role\PermissionRoleInterface` or extend `Dot\Rbac\Role\Role` | +| `AuthorizationService::addAssertion()` has a native parameter type | `TypeError` instead of `RuntimeException` for a wrong type | Send an `AssertionInterface` or a non-empty array | +| An empty assertion array is rejected | `Dot\Rbac\Exception\InvalidArgumentException` | Remove the empty assertion | +| An identity that is not `null` must have roles | `Dot\Rbac\Exception\RuntimeException`: "The identity must implement" | Return `null` for a guest. Return an `IdentityInterface` for an authenticated user | +| A circular role hierarchy throws an exception | `Dot\Rbac\Exception\RuntimeException` instead of a fatal error | Remove the cycle from the configuration | + +### Replacing the Laminas plugin manager features + +Version 4 plugin managers extend `Laminas\ServiceManager\AbstractPluginManager`. +Version 5 plugin managers extend `Dot\Rbac\Plugin\AbstractPluginManager`, which accepts only `factories` and `aliases`. + +Before, with Laminas `InvokableFactory` and `invokables`: + +```php +'assertion_manager' => [ + 'invokables' => [ + EditAssertion::class => EditAssertion::class, + ], + 'factories' => [ + OwnerAssertion::class => \Laminas\ServiceManager\Factory\InvokableFactory::class, + ], +], +``` + +After: + +```php +'assertion_manager' => [ + 'factories' => [ + EditAssertion::class => \Dot\Rbac\Plugin\InvokableFactory::class, + OwnerAssertion::class => \Dot\Rbac\Plugin\InvokableFactory::class, + ], +], +``` + +A factory class with the signature `__invoke(ContainerInterface $container, string $requestedName, ?array $options = null)` continues to work. +The Laminas `InvokableFactory` also continues to work if your application requires `laminas/laminas-servicemanager`. + +Before, with a direct call to the plugin manager: + +```php +$assertion = $container->get(AssertionPluginManager::class)->get(EditAssertion::class); +``` + +After: + +```php +$assertion = $container->get(AssertionPluginManager::class)->build(EditAssertion::class); +``` + +## From 3.x to 5.x + +Apply the changes from 4.x to 5.x. +Version 4.0.0 also changed `laminas/laminas-servicemanager` from 3.x to 4.x. +If your application uses Laminas Service Manager, upgrade it to 4.x. diff --git a/docs/book/v5/usage.md b/docs/book/v5/usage.md new file mode 100644 index 0000000..f56d8da --- /dev/null +++ b/docs/book/v5/usage.md @@ -0,0 +1,33 @@ +# Usage + +To check if someone has access to an action, inject the `AuthorizationInterface::class` service into your class. +Then call the `isGranted` method. +There are two ways to call the `isGranted` method. + +## First method + +Specify the roles that you want to check. +A role can be a role name or an object that implements `Dot\Authorization\Role\RoleInterface`. + +```php +$isGranted = $this->authorizationService->isGranted('edit', ['admin', 'user']); +``` + +## Second method + +Do not specify the roles, or send an empty array as the second parameter. +The service then checks the roles of the authenticated identity. +If there is no authenticated identity, the service checks the guest role. + +```php +$isGranted = $this->authorizationService->isGranted('edit'); +``` + +## Context for assertions + +The third parameter is the context. +The service sends the context to each assertion of the permission. + +```php +$isGranted = $this->authorizationService->isGranted('edit', [], $article); +``` diff --git a/mkdocs.yml b/mkdocs.yml index 8cbe81c..de3ea82 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -2,12 +2,20 @@ docs_dir: docs/book site_dir: docs/html extra: project: Packages - current_version: v4 + current_version: v5 versions: + - v5 - v4 - v3 nav: - Home: index.md + - v5: + - Overview: v5/overview.md + - Installation: v5/installation.md + - Configuration: v5/configuration.md + - Usage: v5/usage.md + - Customization: v5/customization.md + - Upgrading: v5/upgrading.md - v4: - Overview: v4/overview.md - Installation: v4/installation.md diff --git a/phpstan.neon b/phpstan.neon index 349be25..08d6acd 100644 --- a/phpstan.neon +++ b/phpstan.neon @@ -1,7 +1,7 @@ includes: - vendor/phpstan/phpstan-phpunit/extension.neon parameters: - level: 5 + level: 8 paths: - src - test diff --git a/phpunit.xml b/phpunit.xml index 2e567ca..95b6028 100644 --- a/phpunit.xml +++ b/phpunit.xml @@ -1,15 +1,25 @@ + xsi:noNamespaceSchemaLocation="vendor/phpunit/phpunit/phpunit.xsd" + bootstrap="vendor/autoload.php" + colors="true" + cacheDirectory=".phpunit.cache" + beStrictAboutCoverageMetadata="true" + beStrictAboutOutputDuringTests="true" + displayDetailsOnAllIssues="true" + failOnDeprecation="true" + failOnNotice="true" + failOnWarning="true" + failOnRisky="true" + failOnPhpunitDeprecation="true" + failOnPhpunitNotice="true" + failOnPhpunitWarning="true"> ./test - - + ./src diff --git a/src/Assertion/AssertionPluginManager.php b/src/Assertion/AssertionPluginManager.php index 2316cf9..dd96dd9 100644 --- a/src/Assertion/AssertionPluginManager.php +++ b/src/Assertion/AssertionPluginManager.php @@ -4,29 +4,15 @@ namespace Dot\Rbac\Assertion; -use Laminas\ServiceManager\AbstractPluginManager; -use Laminas\ServiceManager\Exception\InvalidServiceException; - -use function gettype; -use function is_object; -use function sprintf; +use Dot\Rbac\Plugin\AbstractPluginManager; /** - * @template-extends AbstractPluginManager + * @extends AbstractPluginManager */ class AssertionPluginManager extends AbstractPluginManager { - protected string $instanceOf = AssertionInterface::class; - - public function validate(mixed $instance): void + protected function getInstanceOf(): string { - if (! $instance instanceof $this->instanceOf) { - throw new InvalidServiceException(sprintf( - '%s can only create instances of %s; %s is invalid', - static::class, - $this->instanceOf, - is_object($instance) ? $instance::class : gettype($instance) - )); - } + return AssertionInterface::class; } } diff --git a/src/Assertion/Factory.php b/src/Assertion/Factory.php index 0d8953d..50eb022 100644 --- a/src/Assertion/Factory.php +++ b/src/Assertion/Factory.php @@ -5,9 +5,11 @@ namespace Dot\Rbac\Assertion; use Dot\Rbac\Exception\RuntimeException; -use Psr\Container\ContainerExceptionInterface; use Psr\Container\ContainerInterface; +use function get_debug_type; +use function is_array; +use function is_string; use function sprintf; class Factory @@ -19,21 +21,26 @@ public function __construct( } /** - * @throws ContainerExceptionInterface + * @param array $specs */ public function create(array $specs): AssertionInterface { - $type = $specs['type'] ?? ''; - if (empty($type)) { - throw new RuntimeException(sprintf('Invalid assertion type `%s`', $type)); + $type = $specs['type'] ?? null; + if (! is_string($type) || $type === '') { + throw new RuntimeException(sprintf('Invalid assertion type of type %s', get_debug_type($type))); } - return $this->getAssertionPluginManager()->build($type, $specs['options'] ?? null); + $options = $specs['options'] ?? null; + if ($options !== null && ! is_array($options)) { + throw new RuntimeException('Assertion options must be an array'); + } + + return $this->getAssertionPluginManager()->build($type, $options); } public function getAssertionPluginManager(): AssertionPluginManager { - if (! $this->assertionPluginManager) { + if ($this->assertionPluginManager === null) { $this->assertionPluginManager = new AssertionPluginManager($this->container, []); } diff --git a/src/Authorization/AuthorizationService.php b/src/Authorization/AuthorizationService.php index d253022..95b0364 100644 --- a/src/Authorization/AuthorizationService.php +++ b/src/Authorization/AuthorizationService.php @@ -5,17 +5,18 @@ namespace Dot\Rbac\Authorization; use Dot\Authorization\AuthorizationInterface; +use Dot\Authorization\Role\RoleInterface; use Dot\Rbac\Assertion\AssertionInterface; use Dot\Rbac\Assertion\Factory; -use Dot\Rbac\Exception\RuntimeException; +use Dot\Rbac\Exception\InvalidArgumentException; use Dot\Rbac\RbacInterface; use Dot\Rbac\Role\RoleServiceInterface; use function is_array; -use function sprintf; class AuthorizationService implements AuthorizationInterface { + /** @var array>> */ protected array $assertions = []; public function __construct( @@ -25,16 +26,13 @@ public function __construct( ) { } - public function addAssertion(string $permission, mixed $assertion): void + /** + * @param AssertionInterface|array $assertion + */ + public function addAssertion(string $permission, AssertionInterface|array $assertion): void { - if (! is_array($assertion) && ! $assertion instanceof AssertionInterface) { - throw new RuntimeException( - sprintf('Assertion must be an array or an instance of `%s`', AssertionInterface::class) - ); - } - - if (! isset($this->assertions[$permission])) { - $this->assertions[$permission] = []; + if ($assertion === []) { + throw new InvalidArgumentException('An assertion specification must not be empty'); } $this->assertions[$permission][] = $assertion; @@ -45,13 +43,18 @@ public function getIdentity(): mixed return $this->roleService->getIdentity(); } + /** + * @param array $roles + */ public function isGranted(string $permission, array $roles = [], mixed $context = null): bool { - if (empty($roles)) { + if ($roles === []) { $roles = $this->roleService->getIdentityRoles(); + } else { + $roles = $this->roleService->resolveRoles($roles); } - if (empty($roles)) { + if ($roles === []) { return false; } @@ -68,21 +71,24 @@ public function isGranted(string $permission, array $roles = [], mixed $context public function hasAssertion(string $permission): bool { - return isset($this->assertions[$permission]) && ! empty($this->assertions[$permission]); + return ! empty($this->assertions[$permission]); } + /** + * @param array> $assertions + */ protected function assert(array $assertions, mixed $context = null): bool { - $allow = true; foreach ($assertions as $assertion) { - if (is_array($assertion) && ! empty($assertion)) { + if (is_array($assertion)) { $assertion = $this->assertionFactory->create($assertion); } - if (($allow = $assertion->assert($this, $context)) === false) { - break; + if (! $assertion->assert($this, $context)) { + return false; } } - return $allow; + + return true; } } diff --git a/src/ConfigProvider.php b/src/ConfigProvider.php index 391e2c6..0d2bb62 100644 --- a/src/ConfigProvider.php +++ b/src/ConfigProvider.php @@ -11,6 +11,7 @@ use Dot\Rbac\Factory\AuthenticationIdentityProviderFactory; use Dot\Rbac\Factory\AuthorizationOptionsFactory; use Dot\Rbac\Factory\AuthorizationServiceFactory; +use Dot\Rbac\Factory\RbacFactory; use Dot\Rbac\Factory\RoleProviderPluginManagerFactory; use Dot\Rbac\Factory\RoleServiceFactory; use Dot\Rbac\Identity\AuthenticationIdentityProvider; @@ -19,10 +20,12 @@ use Dot\Rbac\Role\Provider\RoleProviderPluginManager; use Dot\Rbac\Role\RoleService; use Dot\Rbac\Role\RoleServiceInterface; -use Laminas\ServiceManager\Factory\InvokableFactory; class ConfigProvider { + /** + * @return array + */ public function __invoke(): array { return [ @@ -37,11 +40,14 @@ public function __invoke(): array ]; } + /** + * @return array> + */ public function getDependencyConfig(): array { return [ 'factories' => [ - Rbac::class => InvokableFactory::class, + Rbac::class => RbacFactory::class, AuthenticationIdentityProvider::class => AuthenticationIdentityProviderFactory::class, RoleProviderPluginManager::class => RoleProviderPluginManagerFactory::class, RoleService::class => RoleServiceFactory::class, diff --git a/src/Factory/AssertionPluginManagerFactory.php b/src/Factory/AssertionPluginManagerFactory.php index b1e1c55..3837035 100644 --- a/src/Factory/AssertionPluginManagerFactory.php +++ b/src/Factory/AssertionPluginManagerFactory.php @@ -17,7 +17,8 @@ class AssertionPluginManagerFactory */ public function __invoke(ContainerInterface $container): AssertionPluginManager { - $config = $container->get('config')['dot_authorization']['assertion_manager']; + $config = $container->get('config')['dot_authorization']['assertion_manager'] ?? []; + return new AssertionPluginManager($container, $config); } } diff --git a/src/Factory/AuthorizationOptionsFactory.php b/src/Factory/AuthorizationOptionsFactory.php index db10a95..739faff 100644 --- a/src/Factory/AuthorizationOptionsFactory.php +++ b/src/Factory/AuthorizationOptionsFactory.php @@ -17,6 +17,6 @@ class AuthorizationOptionsFactory */ public function __invoke(ContainerInterface $container): AuthorizationOptions { - return new AuthorizationOptions($container->get('config')['dot_authorization']); + return new AuthorizationOptions($container->get('config')['dot_authorization'] ?? null); } } diff --git a/src/Factory/AuthorizationServiceFactory.php b/src/Factory/AuthorizationServiceFactory.php index 8bdd293..b1e086d 100644 --- a/src/Factory/AuthorizationServiceFactory.php +++ b/src/Factory/AuthorizationServiceFactory.php @@ -7,6 +7,7 @@ use Dot\Rbac\Assertion\AssertionPluginManager; use Dot\Rbac\Assertion\Factory; use Dot\Rbac\Authorization\AuthorizationService; +use Dot\Rbac\Exception\RuntimeException; use Dot\Rbac\Options\AuthorizationOptions; use Dot\Rbac\RbacInterface; use Dot\Rbac\Role\RoleServiceInterface; @@ -15,6 +16,7 @@ use Psr\Container\NotFoundExceptionInterface; use function is_array; +use function is_string; class AuthorizationServiceFactory { @@ -30,12 +32,18 @@ public function __invoke(ContainerInterface $container): AuthorizationService $service = new AuthorizationService($rbac, $roleService, $assertionFactory); - /** @var AuthorizationOptions $moduleOptions */ $moduleOptions = $container->get(AuthorizationOptions::class); - $assertions = $moduleOptions->getAssertions(); - foreach ($assertions as $assertion) { - if (is_array($assertion) && isset($assertion['permissions']) && is_array($assertion['permissions'])) { - foreach ($assertion['permissions'] as $permission) { + if (! $moduleOptions instanceof AuthorizationOptions) { + throw new RuntimeException('The service ' . AuthorizationOptions::class . ' has an invalid type'); + } + + foreach ($moduleOptions->getAssertions() as $assertion) { + if (! is_array($assertion) || ! isset($assertion['permissions']) || ! is_array($assertion['permissions'])) { + continue; + } + + foreach ($assertion['permissions'] as $permission) { + if (is_string($permission)) { $service->addAssertion($permission, $assertion); } } diff --git a/src/Factory/RbacFactory.php b/src/Factory/RbacFactory.php new file mode 100644 index 0000000..7af2445 --- /dev/null +++ b/src/Factory/RbacFactory.php @@ -0,0 +1,16 @@ +get('config')['dot_authorization']['role_provider_manager']; + $config = $container->get('config')['dot_authorization']['role_provider_manager'] ?? []; + return new RoleProviderPluginManager($container, $config); } } diff --git a/src/Options/AuthorizationOptions.php b/src/Options/AuthorizationOptions.php index e76d0d5..fe357b2 100644 --- a/src/Options/AuthorizationOptions.php +++ b/src/Options/AuthorizationOptions.php @@ -7,15 +7,19 @@ use Laminas\Stdlib\AbstractOptions; /** - * @template TValue - * @template-extends AbstractOptions + * @extends AbstractOptions */ class AuthorizationOptions extends AbstractOptions { - protected string $guestRole = 'guest'; - protected array $assertions = []; + protected string $guestRole = 'guest'; + /** @var array */ + protected array $assertions = []; + /** @var array */ protected array $roleProvider = []; + /** + * @param array|null $options + */ public function __construct(?array $options) { $this->__strictMode__ = false; @@ -32,21 +36,33 @@ public function setGuestRole(string $guestRole): void $this->guestRole = $guestRole; } + /** + * @return array + */ public function getAssertions(): array { return $this->assertions; } + /** + * @param array $assertions + */ public function setAssertions(array $assertions): void { $this->assertions = $assertions; } + /** + * @return array + */ public function getRoleProvider(): array { return $this->roleProvider; } + /** + * @param array $roleProvider + */ public function setRoleProvider(array $roleProvider): void { $this->roleProvider = $roleProvider; diff --git a/src/Plugin/AbstractPluginManager.php b/src/Plugin/AbstractPluginManager.php new file mode 100644 index 0000000..7996634 --- /dev/null +++ b/src/Plugin/AbstractPluginManager.php @@ -0,0 +1,96 @@ + */ + protected array $aliases = []; + + /** @var array */ + protected array $factories = []; + + /** + * @param array{aliases?: array, factories?: array} $config + */ + public function __construct(protected ContainerInterface $container, array $config = []) + { + $this->aliases = ($config['aliases'] ?? []) + $this->aliases; + $this->factories = ($config['factories'] ?? []) + $this->factories; + } + + /** + * @return class-string + */ + abstract protected function getInstanceOf(): string; + + public function has(string $name): bool + { + return isset($this->factories[$this->aliases[$name] ?? $name]); + } + + /** + * @param array|null $options + * @return T + */ + public function build(string $name, ?array $options = null): object + { + $resolved = $this->aliases[$name] ?? $name; + if (! isset($this->factories[$resolved])) { + throw new InvalidArgumentException(sprintf( + 'No factory is registered for plugin "%s" in %s', + $name, + static::class + )); + } + + $factory = $this->factories[$resolved]; + if (is_string($factory) && class_exists($factory)) { + $factory = new $factory(); + } + + if (! is_callable($factory)) { + throw new RuntimeException(sprintf('The factory for plugin "%s" is not callable', $name)); + } + + $instance = $factory($this->container, $resolved, $options); + $this->validate($instance); + + return $instance; + } + + /** + * @phpstan-assert T $instance + */ + public function validate(mixed $instance): void + { + $instanceOf = $this->getInstanceOf(); + if (! $instance instanceof $instanceOf) { + throw new InvalidArgumentException(sprintf( + '%s can only create instances of %s; %s is invalid', + static::class, + $instanceOf, + get_debug_type($instance) + )); + } + } +} diff --git a/src/Plugin/InvokableFactory.php b/src/Plugin/InvokableFactory.php new file mode 100644 index 0000000..5ec96dc --- /dev/null +++ b/src/Plugin/InvokableFactory.php @@ -0,0 +1,21 @@ +|null $options + */ + public function __invoke(ContainerInterface $container, string $requestedName, ?array $options = null): object + { + return $options === null ? new $requestedName() : new $requestedName($options); + } +} diff --git a/src/Rbac.php b/src/Rbac.php index a749ccb..c2666c1 100644 --- a/src/Rbac.php +++ b/src/Rbac.php @@ -4,15 +4,20 @@ namespace Dot\Rbac; -use Dot\Rbac\Role\HierarchicalRoleInterface; +use Dot\Authorization\Role\RoleInterface; +use Dot\Rbac\Role\PermissionRoleInterface; +use Dot\Rbac\Role\RoleFlattener; use Generator; class Rbac implements RbacInterface { + /** + * @param array $roles + */ public function isGranted(string $permission, array $roles): bool { foreach ($this->flattenRoles($roles) as $role) { - if ($role->hasPermission($permission)) { + if ($role instanceof PermissionRoleInterface && $role->hasPermission($permission)) { return true; } } @@ -20,20 +25,12 @@ public function isGranted(string $permission, array $roles): bool return false; } + /** + * @param array $roles + * @return Generator + */ protected function flattenRoles(array $roles): Generator { - foreach ($roles as $role) { - yield $role; - - if (! $role instanceof HierarchicalRoleInterface) { - continue; - } - - $children = $this->flattenRoles($role->getChildren()); - - foreach ($children as $child) { - yield $child; - } - } + return RoleFlattener::flatten($roles); } } diff --git a/src/RbacInterface.php b/src/RbacInterface.php index 49503b9..84148fa 100644 --- a/src/RbacInterface.php +++ b/src/RbacInterface.php @@ -4,7 +4,12 @@ namespace Dot\Rbac; +use Dot\Authorization\Role\RoleInterface; + interface RbacInterface { + /** + * @param array $roles + */ public function isGranted(string $permission, array $roles): bool; } diff --git a/src/Role/HierarchicalRole.php b/src/Role/HierarchicalRole.php index 2d8d2a1..1595757 100644 --- a/src/Role/HierarchicalRole.php +++ b/src/Role/HierarchicalRole.php @@ -8,13 +8,17 @@ class HierarchicalRole extends Role implements HierarchicalRoleInterface { + /** @var array */ protected array $children = []; public function hasChildren(): bool { - return ! empty($this->children); + return $this->children !== []; } + /** + * @return array + */ public function getChildren(): array { return $this->children; diff --git a/src/Role/HierarchicalRoleInterface.php b/src/Role/HierarchicalRoleInterface.php index 02c023a..2312c9c 100644 --- a/src/Role/HierarchicalRoleInterface.php +++ b/src/Role/HierarchicalRoleInterface.php @@ -10,5 +10,8 @@ interface HierarchicalRoleInterface extends RoleInterface { public function hasChildren(): bool; + /** + * @return array + */ public function getChildren(): array; } diff --git a/src/Role/PermissionRoleInterface.php b/src/Role/PermissionRoleInterface.php new file mode 100644 index 0000000..5e1ee45 --- /dev/null +++ b/src/Role/PermissionRoleInterface.php @@ -0,0 +1,20 @@ + + */ + public function getPermissions(): array; + + public function hasPermission(string $permission): bool; +} diff --git a/src/Role/Provider/Factory.php b/src/Role/Provider/Factory.php index 797beca..59df205 100644 --- a/src/Role/Provider/Factory.php +++ b/src/Role/Provider/Factory.php @@ -5,9 +5,13 @@ namespace Dot\Rbac\Role\Provider; use Dot\Rbac\Exception\RuntimeException; -use Psr\Container\ContainerExceptionInterface; use Psr\Container\ContainerInterface; +use function get_debug_type; +use function is_array; +use function is_string; +use function sprintf; + class Factory { public function __construct( @@ -17,22 +21,30 @@ public function __construct( } /** - * @throws ContainerExceptionInterface + * @param array $specs */ public function create(array $specs): RoleProviderInterface { - $type = $specs['type'] ?? ''; - if (empty($type)) { + $type = $specs['type'] ?? null; + if ($type === null || $type === '') { throw new RuntimeException('Empty or no role provider set in config'); } - $roleProviderManager = $this->getRoleProviderPluginManager(); - return $roleProviderManager->build($type, $specs['options'] ?? null); + if (! is_string($type)) { + throw new RuntimeException(sprintf('Invalid role provider type of type %s', get_debug_type($type))); + } + + $options = $specs['options'] ?? null; + if ($options !== null && ! is_array($options)) { + throw new RuntimeException('Role provider options must be an array'); + } + + return $this->getRoleProviderPluginManager()->build($type, $options); } public function getRoleProviderPluginManager(): RoleProviderPluginManager { - if (! $this->roleProviderPluginManager) { + if ($this->roleProviderPluginManager === null) { $this->roleProviderPluginManager = new RoleProviderPluginManager($this->container, []); } diff --git a/src/Role/Provider/InMemoryRoleProvider.php b/src/Role/Provider/InMemoryRoleProvider.php index 0bca639..7ea5f2e 100644 --- a/src/Role/Provider/InMemoryRoleProvider.php +++ b/src/Role/Provider/InMemoryRoleProvider.php @@ -5,16 +5,30 @@ namespace Dot\Rbac\Role\Provider; use Dot\Authorization\Role\RoleInterface; +use Dot\Rbac\Exception\RuntimeException; use Dot\Rbac\Role\HierarchicalRole; use Dot\Rbac\Role\Role; use function is_array; +use function sprintf; +/** + * @phpstan-type RoleConfig array{children?: string|array, permissions?: array} + */ class InMemoryRoleProvider implements RoleProviderInterface { - protected array $roles = []; + /** @var array */ + protected array $roles = []; + + /** @var array */ protected array $rolesConfig = []; + /** @var array */ + private array $building = []; + + /** + * @param array{roles?: array}|null $options + */ public function __construct(?array $options = null) { $options = $options ?? []; @@ -23,6 +37,10 @@ public function __construct(?array $options = null) } } + /** + * @param array $roleNames + * @return array + */ public function getRoles(array $roleNames): array { $roles = []; @@ -46,21 +64,29 @@ public function getRole(string $roleName): RoleInterface return $role; } - $roleConfig = $this->rolesConfig[$roleName]; - if (isset($roleConfig['children'])) { - $role = new HierarchicalRole($roleName); - $childRoles = (array) $roleConfig['children']; - foreach ($childRoles as $childRole) { - $childRole = $this->getRole($childRole); - $role->addChild($childRole); - } - } else { - $role = new Role($roleName); + if (isset($this->building[$roleName])) { + throw new RuntimeException(sprintf('Circular role hierarchy found at role "%s"', $roleName)); } - $permissions = $roleConfig['permissions'] ?? []; - foreach ($permissions as $permission) { - $role->addPermission($permission); + + $this->building[$roleName] = true; + try { + $roleConfig = $this->rolesConfig[$roleName]; + if (isset($roleConfig['children'])) { + $role = new HierarchicalRole($roleName); + foreach ((array) $roleConfig['children'] as $childRole) { + $role->addChild($this->getRole($childRole)); + } + } else { + $role = new Role($roleName); + } + + foreach ($roleConfig['permissions'] ?? [] as $permission) { + $role->addPermission($permission); + } + } finally { + unset($this->building[$roleName]); } + $this->roles[$roleName] = $role; return $role; } diff --git a/src/Role/Provider/RoleProviderInterface.php b/src/Role/Provider/RoleProviderInterface.php index 2f91056..985f503 100644 --- a/src/Role/Provider/RoleProviderInterface.php +++ b/src/Role/Provider/RoleProviderInterface.php @@ -4,7 +4,13 @@ namespace Dot\Rbac\Role\Provider; +use Dot\Authorization\Role\RoleInterface; + interface RoleProviderInterface { + /** + * @param array $roleNames + * @return array + */ public function getRoles(array $roleNames): array; } diff --git a/src/Role/Provider/RoleProviderPluginManager.php b/src/Role/Provider/RoleProviderPluginManager.php index d11e0e7..820bdd6 100644 --- a/src/Role/Provider/RoleProviderPluginManager.php +++ b/src/Role/Provider/RoleProviderPluginManager.php @@ -4,25 +4,20 @@ namespace Dot\Rbac\Role\Provider; -use Laminas\ServiceManager\AbstractPluginManager; -use Laminas\ServiceManager\Exception\InvalidServiceException; -use Laminas\ServiceManager\Factory\InvokableFactory; - -use function gettype; -use function is_object; -use function sprintf; +use Dot\Rbac\Plugin\AbstractPluginManager; +use Dot\Rbac\Plugin\InvokableFactory; /** - * @template-extends AbstractPluginManager + * @extends AbstractPluginManager */ class RoleProviderPluginManager extends AbstractPluginManager { - protected string $instanceOf = RoleProviderInterface::class; - + /** @var array */ protected array $factories = [ InMemoryRoleProvider::class => InvokableFactory::class, ]; + /** @var array */ protected array $aliases = [ 'inmemoryroleprovider' => InMemoryRoleProvider::class, 'inMemoryRoleProvider' => InMemoryRoleProvider::class, @@ -32,15 +27,8 @@ class RoleProviderPluginManager extends AbstractPluginManager 'InMemory' => InMemoryRoleProvider::class, ]; - public function validate(mixed $instance): void + protected function getInstanceOf(): string { - if (! $instance instanceof $this->instanceOf) { - throw new InvalidServiceException(sprintf( - '%s can only create instances of %s; %s is invalid', - static::class, - $this->instanceOf, - is_object($instance) ? $instance::class : gettype($instance) - )); - } + return RoleProviderInterface::class; } } diff --git a/src/Role/Role.php b/src/Role/Role.php index 73fdcba..faa607a 100644 --- a/src/Role/Role.php +++ b/src/Role/Role.php @@ -4,10 +4,9 @@ namespace Dot\Rbac\Role; -use Dot\Authorization\Role\RoleInterface; - -class Role implements RoleInterface +class Role implements PermissionRoleInterface { + /** @var array */ protected array $permissions = []; public function __construct(protected string $name) @@ -19,6 +18,9 @@ public function getName(): string return $this->name; } + /** + * @return array + */ public function getPermissions(): array { return $this->permissions; diff --git a/src/Role/RoleFlattener.php b/src/Role/RoleFlattener.php new file mode 100644 index 0000000..72480d2 --- /dev/null +++ b/src/Role/RoleFlattener.php @@ -0,0 +1,51 @@ + $roles + * @return Generator + */ + public static function flatten(array $roles): Generator + { + $visited = []; + + return self::walk($roles, $visited); + } + + /** + * @param array $roles + * @param array $visited + * @return Generator + */ + private static function walk(array $roles, array &$visited): Generator + { + foreach ($roles as $role) { + $id = spl_object_id($role); + if (isset($visited[$id])) { + continue; + } + + $visited[$id] = true; + yield $role; + + if ($role instanceof HierarchicalRoleInterface) { + foreach (self::walk($role->getChildren(), $visited) as $child) { + yield $child; + } + } + } + } +} diff --git a/src/Role/RoleService.php b/src/Role/RoleService.php index 45d03e4..a090db5 100644 --- a/src/Role/RoleService.php +++ b/src/Role/RoleService.php @@ -4,7 +4,10 @@ namespace Dot\Rbac\Role; +use Dot\Authorization\Identity\IdentityInterface; use Dot\Authorization\Role\RoleInterface; +use Dot\Rbac\Exception\InvalidArgumentException; +use Dot\Rbac\Exception\RuntimeException; use Dot\Rbac\Identity\IdentityProviderInterface; use Dot\Rbac\Role\Provider\RoleProviderInterface; use Generator; @@ -12,7 +15,13 @@ use function array_intersect; use function array_merge; use function count; +use function get_debug_type; +use function is_array; +use function is_int; +use function is_object; +use function is_string; use function method_exists; +use function sprintf; class RoleService implements RoleServiceInterface { @@ -44,15 +53,19 @@ public function setGuestRole(string $guestRole): void $this->guestRole = $guestRole; } + /** + * @param array $roles + */ public function matchIdentityRoles(array $roles): bool { $identityRoles = $this->getIdentityRoles(); - if (empty($identityRoles)) { + if ($identityRoles === []) { return false; } + $roleNames = []; foreach ($roles as $role) { - $roleNames[] = $role instanceof RoleInterface ? $role->getName() : (string) $role; + $roleNames[] = $role instanceof RoleInterface ? $role->getName() : $role; } $identityRoleNames = []; @@ -63,13 +76,32 @@ public function matchIdentityRoles(array $roles): bool return count(array_intersect($roleNames, $identityRoleNames)) > 0; } + /** + * @return array + */ public function getIdentityRoles(): array { - if (! $identity = $this->getIdentity()) { - return $this->convertRoles([$this->guestRole]); + $identity = $this->getIdentity(); + if ($identity === null) { + return $this->resolveRoles([$this->guestRole]); + } + + if ($identity instanceof IdentityInterface) { + return $this->resolveRoles($identity->getRoles()); + } + + if (is_object($identity) && method_exists($identity, 'getRoles')) { + $roles = $identity->getRoles(); + if (is_array($roles)) { + return $this->resolveRoles($roles); + } } - return $this->convertRoles($identity->getRoles()); + throw new RuntimeException(sprintf( + 'The identity must implement %s, %s given', + IdentityInterface::class, + get_debug_type($identity) + )); } public function getIdentity(): mixed @@ -77,7 +109,11 @@ public function getIdentity(): mixed return $this->identityProvider->getIdentity(); } - protected function convertRoles(array $roles): array + /** + * @param array $roles + * @return array + */ + public function resolveRoles(array $roles): array { $collectedRoles = []; $toCollect = []; @@ -87,32 +123,35 @@ protected function convertRoles(array $roles): array continue; } - if (method_exists($role, 'getName')) { - $role = $role->getName(); + if (is_string($role) || is_int($role)) { + $toCollect[] = (string) $role; + continue; } - $toCollect[] = (string) $role; + + if (is_object($role) && method_exists($role, 'getName')) { + $name = $role->getName(); + if (is_string($name)) { + $toCollect[] = $name; + continue; + } + } + + throw new InvalidArgumentException(sprintf('Invalid role of type %s', get_debug_type($role))); } - if (empty($toCollect)) { + + if ($toCollect === []) { return $collectedRoles; } return array_merge($collectedRoles, $this->roleProvider->getRoles($toCollect)); } + /** + * @param array $roles + * @return Generator + */ protected function flattenRoles(array $roles): Generator { - foreach ($roles as $role) { - yield $role; - - if (! $role instanceof HierarchicalRoleInterface) { - continue; - } - - $children = $this->flattenRoles($role->getChildren()); - - foreach ($children as $child) { - yield $child; - } - } + return RoleFlattener::flatten($roles); } } diff --git a/src/Role/RoleServiceInterface.php b/src/Role/RoleServiceInterface.php index 4678d86..d54c587 100644 --- a/src/Role/RoleServiceInterface.php +++ b/src/Role/RoleServiceInterface.php @@ -4,13 +4,29 @@ namespace Dot\Rbac\Role; +use Dot\Authorization\Role\RoleInterface; + interface RoleServiceInterface { public function getIdentity(): mixed; public function getGuestRole(): string; + /** + * @return array + */ public function getIdentityRoles(): array; + /** + * @param array $roles + */ public function matchIdentityRoles(array $roles): bool; + + /** + * Converts role names to role objects. Role objects stay as they are. + * + * @param array $roles + * @return array + */ + public function resolveRoles(array $roles): array; } diff --git a/test/Assertion/AssertionPluginManagerTest.php b/test/Assertion/AssertionPluginManagerTest.php index 208e8f7..9544472 100644 --- a/test/Assertion/AssertionPluginManagerTest.php +++ b/test/Assertion/AssertionPluginManagerTest.php @@ -6,40 +6,40 @@ use Dot\Rbac\Assertion\AssertionInterface; use Dot\Rbac\Assertion\AssertionPluginManager; -use Laminas\ServiceManager\Exception\InvalidServiceException; -use PHPUnit\Framework\MockObject\Exception; +use Dot\Rbac\Exception\InvalidArgumentException; +use Dot\Rbac\Plugin\AbstractPluginManager; +use Dot\Rbac\Plugin\InvokableFactory; +use DotTest\Rbac\TestData\AllowAssertion; +use DotTest\Rbac\TestData\Container; +use DotTest\Rbac\TestData\IdentityProvider; +use PHPUnit\Framework\Attributes\CoversClass; +use PHPUnit\Framework\Attributes\UsesClass; use PHPUnit\Framework\TestCase; -use Psr\Container\ContainerExceptionInterface; -use Psr\Container\ContainerInterface; +#[CoversClass(AssertionPluginManager::class)] +#[UsesClass(AbstractPluginManager::class)] +#[UsesClass(InvokableFactory::class)] class AssertionPluginManagerTest extends TestCase { - /** - * @throws ContainerExceptionInterface - * @throws Exception - */ - public function testInstanceOf(): void + public function testBuildsAssertion(): void { - $container = $this->createMock(ContainerInterface::class); - $plugin = $this->createMock(AssertionInterface::class); + $manager = new AssertionPluginManager(new Container(), [ + 'factories' => [AllowAssertion::class => InvokableFactory::class], + ]); - $this->expectNotToPerformAssertions(); - - $assertionPluginManager = new AssertionPluginManager($container); - $assertionPluginManager->validate($plugin); + $this->assertInstanceOf(AllowAssertion::class, $manager->build(AllowAssertion::class)); } - /** - * @throws ContainerExceptionInterface - * @throws Exception - */ - public function testInvalidInstanceOf(): void + public function testRejectsOtherInstances(): void { - $container = $this->createMock(ContainerInterface::class); - - $this->expectException(InvalidServiceException::class); - - $assertionPluginManager = new AssertionPluginManager($container); - $assertionPluginManager->validate('test'); + $manager = new AssertionPluginManager(new Container(), [ + 'factories' => [IdentityProvider::class => InvokableFactory::class], + ]); + + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage( + AssertionPluginManager::class . ' can only create instances of ' . AssertionInterface::class + ); + $manager->build(IdentityProvider::class); } } diff --git a/test/Assertion/FactoryTest.php b/test/Assertion/FactoryTest.php index dd9b369..06e4b56 100644 --- a/test/Assertion/FactoryTest.php +++ b/test/Assertion/FactoryTest.php @@ -4,67 +4,73 @@ namespace DotTest\Rbac\Assertion; -use Dot\Authorization\AuthorizationInterface; -use Dot\Rbac\Assertion\AssertionInterface; use Dot\Rbac\Assertion\AssertionPluginManager; use Dot\Rbac\Assertion\Factory; use Dot\Rbac\Exception\RuntimeException; -use PHPUnit\Framework\MockObject\Exception; +use Dot\Rbac\Plugin\AbstractPluginManager; +use Dot\Rbac\Plugin\InvokableFactory; +use DotTest\Rbac\TestData\AllowAssertion; +use DotTest\Rbac\TestData\Container; +use DotTest\Rbac\TestData\ContextAssertion; +use PHPUnit\Framework\Attributes\CoversClass; +use PHPUnit\Framework\Attributes\DataProvider; +use PHPUnit\Framework\Attributes\UsesClass; use PHPUnit\Framework\TestCase; -use Psr\Container\ContainerExceptionInterface; -use Psr\Container\ContainerInterface; +#[CoversClass(Factory::class)] +#[UsesClass(AbstractPluginManager::class)] +#[UsesClass(AssertionPluginManager::class)] +#[UsesClass(InvokableFactory::class)] class FactoryTest extends TestCase { - /** - * @throws ContainerExceptionInterface - * @throws Exception - */ - public function testCreateRuntimeException(): void + public function testCreate(): void { - $container = $this->createMock(ContainerInterface::class); - $subject = new Factory($container); + $manager = new AssertionPluginManager(new Container(), [ + 'factories' => [ + AllowAssertion::class => InvokableFactory::class, + ContextAssertion::class => InvokableFactory::class, + ], + ]); + $subject = new Factory(new Container(), $manager); - $this->expectException(RuntimeException::class); - $this->expectExceptionMessage('Invalid assertion type'); - $subject->create([]); + $this->assertInstanceOf(AllowAssertion::class, $subject->create(['type' => AllowAssertion::class])); + $this->assertInstanceOf( + ContextAssertion::class, + $subject->create(['type' => ContextAssertion::class, 'options' => ['allowed' => 'mine']]) + ); } - /** - * @throws ContainerExceptionInterface - * @throws Exception - */ - public function testCreate(): void + public function testGetAssertionPluginManager(): void { - $container = $this->createMock(ContainerInterface::class); - $assertionPluginManager = $this->createMock(AssertionPluginManager::class); + $manager = new AssertionPluginManager(new Container()); + $this->assertSame($manager, (new Factory(new Container(), $manager))->getAssertionPluginManager()); - $assertionPluginManager->expects($this->once()) - ->method('build') - ->with('testType', null) - ->willReturn(new class implements AssertionInterface { - public function assert(AuthorizationInterface $authorization, mixed $context = null): bool - { - return true; - } - }); - $subject = new Factory($container, $assertionPluginManager); - - $result = $subject->create(['type' => 'testType']); - $this->assertContainsOnlyInstancesOf(AssertionInterface::class, [$result]); + $subject = new Factory(new Container()); + $this->assertSame($subject->getAssertionPluginManager(), $subject->getAssertionPluginManager()); } /** - * @throws Exception + * @return iterable, string}> */ - public function testGetAssertionPluginManager(): void + public static function invalidSpecsProvider(): iterable { - $container = $this->createMock(ContainerInterface::class); - $assertionPluginManager = $this->createMock(AssertionPluginManager::class); - - $subject = new Factory($container, $assertionPluginManager); + yield 'no type' => [[], 'Invalid assertion type of type null']; + yield 'empty type' => [['type' => ''], 'Invalid assertion type of type string']; + yield 'array type' => [['type' => ['x']], 'Invalid assertion type of type array']; + yield 'string options' => [ + ['type' => AllowAssertion::class, 'options' => 'x'], + 'Assertion options must be an array', + ]; + } - $result = $subject->getAssertionPluginManager(); - $this->assertContainsOnlyInstancesOf(AssertionPluginManager::class, [$result]); + /** + * @param array $specs + */ + #[DataProvider('invalidSpecsProvider')] + public function testCreateWithInvalidSpecsThrowsException(array $specs, string $message): void + { + $this->expectException(RuntimeException::class); + $this->expectExceptionMessage($message); + (new Factory(new Container()))->create($specs); } } diff --git a/test/Authorization/AuthorizationServiceTest.php b/test/Authorization/AuthorizationServiceTest.php index 2f52921..74bb69e 100644 --- a/test/Authorization/AuthorizationServiceTest.php +++ b/test/Authorization/AuthorizationServiceTest.php @@ -4,76 +4,168 @@ namespace DotTest\Rbac\Authorization; +use Dot\Rbac\Assertion\AssertionPluginManager; use Dot\Rbac\Assertion\Factory; use Dot\Rbac\Authorization\AuthorizationService; -use Dot\Rbac\Exception\RuntimeException; +use Dot\Rbac\Exception\InvalidArgumentException; +use Dot\Rbac\Plugin\AbstractPluginManager; +use Dot\Rbac\Plugin\InvokableFactory; use Dot\Rbac\Rbac; -use Dot\Rbac\RbacInterface; -use Dot\Rbac\Role\RoleServiceInterface; -use PHPUnit\Framework\MockObject\Exception; -use PHPUnit\Framework\MockObject\MockObject; +use Dot\Rbac\Role\HierarchicalRole; +use Dot\Rbac\Role\Provider\InMemoryRoleProvider; +use Dot\Rbac\Role\Role; +use Dot\Rbac\Role\RoleFlattener; +use Dot\Rbac\Role\RoleService; +use DotTest\Rbac\TestData\AllowAssertion; +use DotTest\Rbac\TestData\Container; +use DotTest\Rbac\TestData\ContextAssertion; +use DotTest\Rbac\TestData\DenyAssertion; +use DotTest\Rbac\TestData\Identity; +use DotTest\Rbac\TestData\IdentityProvider; +use PHPUnit\Framework\Attributes\CoversClass; +use PHPUnit\Framework\Attributes\UsesClass; use PHPUnit\Framework\TestCase; - +use TypeError; + +#[CoversClass(AuthorizationService::class)] +#[UsesClass(Rbac::class)] +#[UsesClass(RoleService::class)] +#[UsesClass(RoleFlattener::class)] +#[UsesClass(InMemoryRoleProvider::class)] +#[UsesClass(Role::class)] +#[UsesClass(HierarchicalRole::class)] +#[UsesClass(Factory::class)] +#[UsesClass(AbstractPluginManager::class)] +#[UsesClass(AssertionPluginManager::class)] +#[UsesClass(InvokableFactory::class)] class AuthorizationServiceTest extends TestCase { - public AuthorizationService $authorizationService; - public Rbac|MockObject $rbac; + public function testGuestPermissions(): void + { + $service = $this->createService(); + + $this->assertNull($service->getIdentity()); + $this->assertTrue($service->isGranted('view')); + $this->assertFalse($service->isGranted('edit')); + } + + public function testIdentityPermissionsIncludeChildren(): void + { + $service = $this->createService(new Identity(['admin'])); + + $this->assertTrue($service->isGranted('delete')); + $this->assertTrue($service->isGranted('edit')); + $this->assertTrue($service->isGranted('view')); + $this->assertFalse($service->isGranted('unknown')); + } - /** - * @throws Exception - */ - public function setUp(): void + public function testIsGrantedWithRoleNames(): void { - $this->rbac = $this->createMock(RbacInterface::class); - $roleServiceInterface = $this->createMock(RoleServiceInterface::class); - $factory = $this->createMock(Factory::class); + $service = $this->createService(); - $this->authorizationService = new AuthorizationService($this->rbac, $roleServiceInterface, $factory); + $this->assertTrue($service->isGranted('edit', ['user'])); + $this->assertFalse($service->isGranted('delete', ['user'])); + $this->assertTrue($service->isGranted('view', ['guest'])); + } + + public function testIsGrantedWithRoleObjects(): void + { + $role = new Role('custom'); + $role->addPermission('custom-permission'); + + $this->assertTrue($this->createService()->isGranted('custom-permission', [$role])); + } + + public function testIsGrantedWithoutIdentityRoles(): void + { + $this->assertFalse($this->createService(new Identity([]))->isGranted('view')); } public function testAddAssertion(): void { - $permission = 'testPermission'; - $assertion = ['testAssertion']; + $service = $this->createService(); + $this->assertFalse($service->hasAssertion('edit')); + + $service->addAssertion('edit', new AllowAssertion()); + $this->assertTrue($service->hasAssertion('edit')); + $this->assertFalse($service->hasAssertion('view')); + } - $this->authorizationService->addAssertion($permission, $assertion); - $this->assertTrue($this->authorizationService->hasAssertion('testPermission')); + public function testAddEmptyAssertionThrowsException(): void + { + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('An assertion specification must not be empty'); + $this->createService()->addAssertion('edit', []); } - public function testAddAssertionThrowException(): void + public function testAddAssertionWithWrongTypeThrowsTypeError(): void { - $permission = 'testPermission'; - $assertion = 'testAssertion'; - $this->expectException(RuntimeException::class); - $this->authorizationService->addAssertion($permission, $assertion); + $this->expectException(TypeError::class); + $this->createService()->addAssertion('edit', $this->invalidAssertion()); } - public function testIsGranted(): void + public function testAssertionAllowsAccess(): void { - $this->rbac->expects($this->once())->method('isGranted')->willReturn(true); + $assertion = new AllowAssertion(); + $service = $this->createService(); + $service->addAssertion('edit', $assertion); - $permission = 'testPermission'; - $roles = ['testRole']; - $context = 'context'; + $this->assertTrue($service->isGranted('edit', ['user'])); + $this->assertSame(1, $assertion->calls); + } + + public function testAssertionIsNotCalledWithoutPermission(): void + { + $assertion = new AllowAssertion(); + $service = $this->createService(); + $service->addAssertion('edit', $assertion); - $result = $this->authorizationService->isGranted($permission, $roles, $context); - $this->assertTrue($result); + $this->assertFalse($service->isGranted('edit', ['guest'])); + $this->assertSame(0, $assertion->calls); } - public function testIsGrantedEmptyRoles(): void + public function testAssertionDeniesAccess(): void { - $permission = 'testPermission'; + $after = new AllowAssertion(); + $service = $this->createService(); + $service->addAssertion('edit', new DenyAssertion()); + $service->addAssertion('edit', $after); - $result = $this->authorizationService->isGranted($permission); - $this->assertFalse($result); + $this->assertFalse($service->isGranted('edit', ['user'])); + $this->assertSame(0, $after->calls); } - public function testRbacIsGrantedFalse(): void + public function testAssertionFromSpecification(): void { - $permission = 'testPermission'; - $roles = ['testRole']; + $service = $this->createService(new Identity(['user'])); + $service->addAssertion('edit', ['type' => ContextAssertion::class, 'options' => ['allowed' => 'mine']]); - $result = $this->authorizationService->isGranted($permission, $roles); - $this->assertFalse($result); + $this->assertTrue($service->isGranted('edit', [], 'mine')); + $this->assertFalse($service->isGranted('edit', [], 'other')); + } + + private function invalidAssertion(): mixed + { + return 'testAssertion'; + } + + private function createService(mixed $identity = null): AuthorizationService + { + $roleProvider = new InMemoryRoleProvider([ + 'roles' => [ + 'admin' => ['children' => ['user'], 'permissions' => ['delete']], + 'user' => ['children' => ['guest'], 'permissions' => ['edit']], + 'guest' => ['permissions' => ['view']], + ], + ]); + $manager = new AssertionPluginManager(new Container(), [ + 'factories' => [ContextAssertion::class => InvokableFactory::class], + ]); + + return new AuthorizationService( + new Rbac(), + new RoleService(new IdentityProvider($identity), $roleProvider), + new Factory(new Container(), $manager) + ); } } diff --git a/test/ConfigProviderTest.php b/test/ConfigProviderTest.php index fc9fd92..08e56df 100644 --- a/test/ConfigProviderTest.php +++ b/test/ConfigProviderTest.php @@ -11,17 +11,21 @@ use Dot\Rbac\Identity\AuthenticationIdentityProvider; use Dot\Rbac\Identity\IdentityProviderInterface; use Dot\Rbac\Options\AuthorizationOptions; +use Dot\Rbac\Rbac; use Dot\Rbac\RbacInterface; use Dot\Rbac\Role\Provider\RoleProviderPluginManager; use Dot\Rbac\Role\RoleService; use Dot\Rbac\Role\RoleServiceInterface; +use PHPUnit\Framework\Attributes\CoversClass; use PHPUnit\Framework\TestCase; +#[CoversClass(ConfigProvider::class)] class ConfigProviderTest extends TestCase { + /** @var array */ protected array $config; - protected function setup(): void + protected function setUp(): void { $this->config = (new ConfigProvider())(); } @@ -29,17 +33,14 @@ protected function setup(): void public function testHasDependencies(): void { $this->assertArrayHasKey('dependencies', $this->config); - } - - public function testHasDotAuthorization(): void - { - $this->assertArrayHasKey('dot_authorization', $this->config); + $this->assertSame((new ConfigProvider())->getDependencyConfig(), $this->config['dependencies']); } public function testDependenciesHasFactories(): void { - $this->assertArrayHasKey('factories', $this->config['dependencies']); - $factories = $this->config['dependencies']['factories']; + $factories = (new ConfigProvider())->getDependencyConfig()['factories']; + + $this->assertArrayHasKey(Rbac::class, $factories); $this->assertArrayHasKey(AuthenticationIdentityProvider::class, $factories); $this->assertArrayHasKey(RoleProviderPluginManager::class, $factories); $this->assertArrayHasKey(RoleService::class, $factories); @@ -48,23 +49,27 @@ public function testDependenciesHasFactories(): void $this->assertArrayHasKey(AuthorizationService::class, $factories); } - public function testDotAuthorizationHasConfig(): void + public function testDependenciesHasAliases(): void { - $config = $this->config['dot_authorization']; - $this->assertArrayHasKey('guest_role', $config); - $this->assertArrayHasKey('assertions', $config); - $this->assertArrayHasKey('assertion_manager', $config); - $this->assertArrayHasKey('role_provider', $config); - $this->assertArrayHasKey('role_provider_manager', $config); + $aliases = (new ConfigProvider())->getDependencyConfig()['aliases']; + + $this->assertSame(Rbac::class, $aliases[RbacInterface::class]); + $this->assertSame(AuthorizationService::class, $aliases[AuthorizationInterface::class]); + $this->assertSame(RoleService::class, $aliases[RoleServiceInterface::class]); + $this->assertSame(AuthenticationIdentityProvider::class, $aliases[IdentityProviderInterface::class]); } - public function testDependenciesHasAliases(): void + public function testDotAuthorizationHasConfig(): void { - $this->assertArrayHasKey('aliases', $this->config['dependencies']); - $aliases = $this->config['dependencies']['aliases']; - $this->assertArrayHasKey(RbacInterface::class, $aliases); - $this->assertArrayHasKey(AuthorizationInterface::class, $aliases); - $this->assertArrayHasKey(RoleServiceInterface::class, $aliases); - $this->assertArrayHasKey(IdentityProviderInterface::class, $aliases); + $this->assertSame( + [ + 'guest_role' => 'guest', + 'assertions' => [], + 'assertion_manager' => [], + 'role_provider' => [], + 'role_provider_manager' => [], + ], + $this->config['dot_authorization'] + ); } } diff --git a/test/Factory/AssertionPluginManagerFactoryTest.php b/test/Factory/AssertionPluginManagerFactoryTest.php index 8854a9f..9c465bc 100644 --- a/test/Factory/AssertionPluginManagerFactoryTest.php +++ b/test/Factory/AssertionPluginManagerFactoryTest.php @@ -6,34 +6,39 @@ use Dot\Rbac\Assertion\AssertionPluginManager; use Dot\Rbac\Factory\AssertionPluginManagerFactory; -use PHPUnit\Framework\MockObject\Exception; +use Dot\Rbac\Plugin\AbstractPluginManager; +use Dot\Rbac\Plugin\InvokableFactory; +use DotTest\Rbac\TestData\AllowAssertion; +use DotTest\Rbac\TestData\Container; +use PHPUnit\Framework\Attributes\CoversClass; +use PHPUnit\Framework\Attributes\UsesClass; use PHPUnit\Framework\TestCase; -use Psr\Container\ContainerExceptionInterface; -use Psr\Container\ContainerInterface; -use Psr\Container\NotFoundExceptionInterface; +#[CoversClass(AssertionPluginManagerFactory::class)] +#[UsesClass(AbstractPluginManager::class)] +#[UsesClass(AssertionPluginManager::class)] class AssertionPluginManagerFactoryTest extends TestCase { - /** - * @throws ContainerExceptionInterface - * @throws Exception - * @throws NotFoundExceptionInterface - */ public function testCanCreateManager(): void { - $config = [ - 'dot_authorization' => [ - 'assertion_manager' => [], + $container = new Container([ + 'config' => [ + 'dot_authorization' => [ + 'assertion_manager' => [ + 'factories' => [AllowAssertion::class => InvokableFactory::class], + ], + ], ], - ]; - $container = $this->createMock(ContainerInterface::class); + ]); - $container->expects($this->once()) - ->method('get') - ->with('config') - ->willReturn($config); + $manager = (new AssertionPluginManagerFactory())($container); + $this->assertTrue($manager->has(AllowAssertion::class)); + } + + public function testCanCreateManagerWithoutConfig(): void + { + $manager = (new AssertionPluginManagerFactory())(new Container(['config' => []])); - $result = (new AssertionPluginManagerFactory())($container); - $this->assertSame(AssertionPluginManager::class, $result::class); + $this->assertFalse($manager->has(AllowAssertion::class)); } } diff --git a/test/Factory/AuthenticationIdentityProviderFactoryTest.php b/test/Factory/AuthenticationIdentityProviderFactoryTest.php index 8fd8d71..0555adb 100644 --- a/test/Factory/AuthenticationIdentityProviderFactoryTest.php +++ b/test/Factory/AuthenticationIdentityProviderFactoryTest.php @@ -6,39 +6,26 @@ use Dot\Rbac\Factory\AuthenticationIdentityProviderFactory; use Dot\Rbac\Identity\AuthenticationIdentityProvider; +use DotTest\Rbac\TestData\Container; +use DotTest\Rbac\TestData\Identity; use Laminas\Authentication\AuthenticationService; -use PHPUnit\Framework\MockObject\Exception; -use PHPUnit\Framework\MockObject\MockObject; +use Laminas\Authentication\Storage\NonPersistent; +use PHPUnit\Framework\Attributes\CoversClass; +use PHPUnit\Framework\Attributes\UsesClass; use PHPUnit\Framework\TestCase; -use Psr\Container\ContainerExceptionInterface; -use Psr\Container\ContainerInterface; -use Psr\Container\NotFoundExceptionInterface; +#[CoversClass(AuthenticationIdentityProviderFactory::class)] +#[UsesClass(AuthenticationIdentityProvider::class)] class AuthenticationIdentityProviderFactoryTest extends TestCase { - private ContainerInterface|MockObject $container; - - /** - * @throws Exception - */ - public function setUp(): void - { - $this->container = $this->createMock(ContainerInterface::class); - } - - /** - * @throws ContainerExceptionInterface - * @throws Exception - * @throws NotFoundExceptionInterface - */ public function testWillCreateService(): void { - $this->container->method('get') - ->willReturnMap([ - [AuthenticationService::class, $this->createMock(AuthenticationService::class)], - ]); + $identity = new Identity(['user']); + $storage = new NonPersistent(); + $storage->write($identity); + $container = new Container([AuthenticationService::class => new AuthenticationService($storage)]); - $result = (new AuthenticationIdentityProviderFactory())($this->container); - $this->assertSame(AuthenticationIdentityProvider::class, $result::class); + $provider = (new AuthenticationIdentityProviderFactory())($container); + $this->assertSame($identity, $provider->getIdentity()); } } diff --git a/test/Factory/AuthorizationOptionFactoryTest.php b/test/Factory/AuthorizationOptionFactoryTest.php index 05a90c3..a7de1e6 100644 --- a/test/Factory/AuthorizationOptionFactoryTest.php +++ b/test/Factory/AuthorizationOptionFactoryTest.php @@ -6,28 +6,33 @@ use Dot\Rbac\Factory\AuthorizationOptionsFactory; use Dot\Rbac\Options\AuthorizationOptions; -use PHPUnit\Framework\MockObject\Exception; +use DotTest\Rbac\TestData\Container; +use DotTest\Rbac\TestData\ContainerException; +use PHPUnit\Framework\Attributes\CoversClass; +use PHPUnit\Framework\Attributes\UsesClass; use PHPUnit\Framework\TestCase; -use Psr\Container\ContainerExceptionInterface; -use Psr\Container\ContainerInterface; -use Psr\Container\NotFoundExceptionInterface; +#[CoversClass(AuthorizationOptionsFactory::class)] +#[UsesClass(AuthorizationOptions::class)] class AuthorizationOptionFactoryTest extends TestCase { - /** - * @throws ContainerExceptionInterface - * @throws Exception - * @throws NotFoundExceptionInterface - */ - public function testCanCreateInterface(): void + public function testCanCreateOptions(): void { - $container = $this->createMock(ContainerInterface::class); - $container->expects($this->once()) - ->method('get') - ->with('config') - ->willReturn(['dot_authorization' => null]); - - $interface = (new AuthorizationOptionsFactory())($container); - $this->assertSame(AuthorizationOptions::class, $interface::class); + $container = new Container(['config' => ['dot_authorization' => ['guest_role' => 'visitor']]]); + + $this->assertSame('visitor', (new AuthorizationOptionsFactory())($container)->getGuestRole()); + } + + public function testCanCreateOptionsWithoutConfig(): void + { + $options = (new AuthorizationOptionsFactory())(new Container(['config' => []])); + + $this->assertSame('guest', $options->getGuestRole()); + } + + public function testContainerExceptionIsNotCaught(): void + { + $this->expectException(ContainerException::class); + (new AuthorizationOptionsFactory())(new Container([], ['config'])); } } diff --git a/test/Factory/AuthorizationServiceFactoryTest.php b/test/Factory/AuthorizationServiceFactoryTest.php index 3572089..a0a253a 100644 --- a/test/Factory/AuthorizationServiceFactoryTest.php +++ b/test/Factory/AuthorizationServiceFactoryTest.php @@ -5,48 +5,97 @@ namespace DotTest\Rbac\Factory; use Dot\Rbac\Assertion\AssertionPluginManager; +use Dot\Rbac\Assertion\Factory; use Dot\Rbac\Authorization\AuthorizationService; +use Dot\Rbac\Exception\RuntimeException; use Dot\Rbac\Factory\AuthorizationServiceFactory; use Dot\Rbac\Options\AuthorizationOptions; +use Dot\Rbac\Plugin\AbstractPluginManager; +use Dot\Rbac\Plugin\InvokableFactory; +use Dot\Rbac\Rbac; use Dot\Rbac\RbacInterface; +use Dot\Rbac\Role\Provider\InMemoryRoleProvider; +use Dot\Rbac\Role\Role; +use Dot\Rbac\Role\RoleFlattener; +use Dot\Rbac\Role\RoleService; use Dot\Rbac\Role\RoleServiceInterface; -use PHPUnit\Framework\MockObject\Exception; +use DotTest\Rbac\TestData\Container; +use DotTest\Rbac\TestData\ContextAssertion; +use DotTest\Rbac\TestData\IdentityProvider; +use PHPUnit\Framework\Attributes\CoversClass; +use PHPUnit\Framework\Attributes\UsesClass; use PHPUnit\Framework\TestCase; -use Psr\Container\ContainerExceptionInterface; -use Psr\Container\ContainerInterface; -use Psr\Container\NotFoundExceptionInterface; +#[CoversClass(AuthorizationServiceFactory::class)] +#[UsesClass(AuthorizationService::class)] +#[UsesClass(AuthorizationOptions::class)] +#[UsesClass(Factory::class)] +#[UsesClass(AbstractPluginManager::class)] +#[UsesClass(AssertionPluginManager::class)] +#[UsesClass(InvokableFactory::class)] +#[UsesClass(Rbac::class)] +#[UsesClass(RoleService::class)] +#[UsesClass(RoleFlattener::class)] +#[UsesClass(InMemoryRoleProvider::class)] +#[UsesClass(Role::class)] class AuthorizationServiceFactoryTest extends TestCase { + public function testAddsAssertionsFromOptions(): void + { + $service = (new AuthorizationServiceFactory())($this->createContainer([ + ['type' => ContextAssertion::class, 'permissions' => ['edit', 'delete']], + ['type' => ContextAssertion::class], + ['type' => ContextAssertion::class, 'permissions' => 'view'], + ['type' => ContextAssertion::class, 'permissions' => [1]], + 'not an array', + ])); + + $this->assertTrue($service->hasAssertion('edit')); + $this->assertTrue($service->hasAssertion('delete')); + $this->assertFalse($service->hasAssertion('view')); + $this->assertFalse($service->hasAssertion('1')); + + $this->assertTrue($service->isGranted('edit', ['user'], 'own')); + $this->assertFalse($service->isGranted('edit', ['user'], 'other')); + $this->assertTrue($service->isGranted('view', ['user'], 'other')); + } + + public function testInvalidOptionsServiceThrowsException(): void + { + $container = new Container([ + RbacInterface::class => new Rbac(), + RoleServiceInterface::class => $this->createRoleService(), + AssertionPluginManager::class => new AssertionPluginManager(new Container()), + AuthorizationOptions::class => [], + ]); + + $this->expectException(RuntimeException::class); + $this->expectExceptionMessage('has an invalid type'); + (new AuthorizationServiceFactory())($container); + } + /** - * @throws ContainerExceptionInterface - * @throws Exception - * @throws NotFoundExceptionInterface + * @param array $assertions */ - public function testWillCreateService(): void + private function createContainer(array $assertions): Container { - $container = $this->createMock(ContainerInterface::class); - - $rbac = $this->createMock(RbacInterface::class); - $roleService = $this->createMock(RoleServiceInterface::class); - $assertionPluginManager = $this->createMock(AssertionPluginManager::class); - $moduleOptions = $this->createMock(AuthorizationOptions::class); + $empty = new Container(); - $moduleOptions->method('getAssertions')->willReturn([ - 'permissions' => ['test'], - ['test1'], + return new Container([ + RbacInterface::class => new Rbac(), + RoleServiceInterface::class => $this->createRoleService(), + AssertionPluginManager::class => new AssertionPluginManager($empty, [ + 'factories' => [ContextAssertion::class => InvokableFactory::class], + ]), + AuthorizationOptions::class => new AuthorizationOptions(['assertions' => $assertions]), ]); + } - $container->expects($this->any())->method('get')->willReturnMap( - [ - [RbacInterface::class, $rbac], - [RoleServiceInterface::class, $roleService], - [AssertionPluginManager::class, $assertionPluginManager], - [AuthorizationOptions::class, $moduleOptions], - ], + private function createRoleService(): RoleService + { + return new RoleService( + new IdentityProvider(), + new InMemoryRoleProvider(['roles' => ['user' => ['permissions' => ['edit', 'view']]]]) ); - - $service = (new AuthorizationServiceFactory())($container); - $this->assertSame(AuthorizationService::class, $service::class); } } diff --git a/test/Factory/RbacFactoryTest.php b/test/Factory/RbacFactoryTest.php new file mode 100644 index 0000000..2b3f584 --- /dev/null +++ b/test/Factory/RbacFactoryTest.php @@ -0,0 +1,22 @@ +assertFalse((new RbacFactory())(new Container())->isGranted('view', [])); + } +} diff --git a/test/Factory/RoleProviderPluginManagerFactoryTest.php b/test/Factory/RoleProviderPluginManagerFactoryTest.php index 74a39e9..1e345dd 100644 --- a/test/Factory/RoleProviderPluginManagerFactoryTest.php +++ b/test/Factory/RoleProviderPluginManagerFactoryTest.php @@ -5,36 +5,30 @@ namespace DotTest\Rbac\Factory; use Dot\Rbac\Factory\RoleProviderPluginManagerFactory; +use Dot\Rbac\Plugin\AbstractPluginManager; use Dot\Rbac\Role\Provider\RoleProviderPluginManager; -use PHPUnit\Framework\MockObject\Exception; +use DotTest\Rbac\TestData\Container; +use PHPUnit\Framework\Attributes\CoversClass; +use PHPUnit\Framework\Attributes\UsesClass; use PHPUnit\Framework\TestCase; -use Psr\Container\ContainerExceptionInterface; -use Psr\Container\ContainerInterface; -use Psr\Container\NotFoundExceptionInterface; +#[CoversClass(RoleProviderPluginManagerFactory::class)] +#[UsesClass(AbstractPluginManager::class)] +#[UsesClass(RoleProviderPluginManager::class)] class RoleProviderPluginManagerFactoryTest extends TestCase { - /** - * @throws ContainerExceptionInterface - * @throws Exception - * @throws NotFoundExceptionInterface - */ public function testCanCreate(): void { - $container = $this->createMock(ContainerInterface::class); - - $config = [ - 'dot_authorization' => [ - 'role_provider_manager' => [], + $container = new Container([ + 'config' => [ + 'dot_authorization' => [ + 'role_provider_manager' => ['aliases' => ['memory' => 'InMemory']], + ], ], - ]; - - $container->expects($this->once()) - ->method('get') - ->with('config') - ->willReturn($config); + ]); - $service = (new RoleProviderPluginManagerFactory())($container); - $this->assertSame(RoleProviderPluginManager::class, $service::class); + $manager = (new RoleProviderPluginManagerFactory())($container); + $this->assertTrue($manager->has('InMemory')); + $this->assertFalse($manager->has('unknown')); } } diff --git a/test/Factory/RoleServiceFactoryTest.php b/test/Factory/RoleServiceFactoryTest.php index 14399b4..f79ce7c 100644 --- a/test/Factory/RoleServiceFactoryTest.php +++ b/test/Factory/RoleServiceFactoryTest.php @@ -4,70 +4,71 @@ namespace DotTest\Rbac\Factory; +use Dot\Authorization\Role\RoleInterface; +use Dot\Rbac\Exception\RuntimeException; use Dot\Rbac\Factory\RoleServiceFactory; use Dot\Rbac\Identity\IdentityProviderInterface; use Dot\Rbac\Options\AuthorizationOptions; +use Dot\Rbac\Plugin\AbstractPluginManager; +use Dot\Rbac\Plugin\InvokableFactory; +use Dot\Rbac\Role\Provider\Factory; +use Dot\Rbac\Role\Provider\InMemoryRoleProvider; +use Dot\Rbac\Role\Provider\RoleProviderPluginManager; +use Dot\Rbac\Role\Role; use Dot\Rbac\Role\RoleService; -use PHPUnit\Framework\MockObject\Exception; +use DotTest\Rbac\TestData\Container; +use DotTest\Rbac\TestData\IdentityProvider; +use PHPUnit\Framework\Attributes\CoversClass; +use PHPUnit\Framework\Attributes\UsesClass; use PHPUnit\Framework\TestCase; -use Psr\Container\ContainerExceptionInterface; -use Psr\Container\ContainerInterface; -use Psr\Container\NotFoundExceptionInterface; -use RuntimeException; +use function array_map; + +#[CoversClass(RoleServiceFactory::class)] +#[UsesClass(AuthorizationOptions::class)] +#[UsesClass(RoleService::class)] +#[UsesClass(Factory::class)] +#[UsesClass(AbstractPluginManager::class)] +#[UsesClass(RoleProviderPluginManager::class)] +#[UsesClass(InvokableFactory::class)] +#[UsesClass(InMemoryRoleProvider::class)] +#[UsesClass(Role::class)] class RoleServiceFactoryTest extends TestCase { - /** - * @throws ContainerExceptionInterface - * @throws Exception - * @throws NotFoundExceptionInterface - */ public function testWillCreateService(): void { - $container = $this->createMock(ContainerInterface::class); - - $authorizationOptions = $this->createMock(AuthorizationOptions::class); - $identityProvider = $this->createMock(IdentityProviderInterface::class); - $authorizationOptions->method('getRoleProvider')->willReturn( - [ - 'type' => 'inmemoryroleprovider', - 'option' => ['testOptions'], - ] - ); - - $container->expects($this->any())->method('get')->willReturnMap( - [ - [AuthorizationOptions::class, $authorizationOptions], - [IdentityProviderInterface::class, $identityProvider], - ] - ); + $options = new AuthorizationOptions([ + 'guest_role' => 'visitor', + 'role_provider' => [ + 'type' => 'inmemoryroleprovider', + 'options' => ['roles' => ['visitor' => ['permissions' => ['view']]]], + ], + ]); - $service = (new RoleServiceFactory())($container); + $service = (new RoleServiceFactory())($this->createContainer($options)); - $this->assertSame(RoleService::class, $service::class); + $this->assertSame('visitor', $service->getGuestRole()); + $roles = $service->getIdentityRoles(); + $this->assertSame(['visitor'], array_map(static fn (RoleInterface $role): string => $role->getName(), $roles)); + $this->assertInstanceOf(Role::class, $roles[0]); + $this->assertTrue($roles[0]->hasPermission('view')); } - /** - * @throws ContainerExceptionInterface - * @throws Exception - * @throws NotFoundExceptionInterface - */ - public function testWillNotCreateService(): void + public function testWillNotCreateServiceWithoutRoleProvider(): void { - $container = $this->createMock(ContainerInterface::class); - - $authorizationOptions = $this->createMock(AuthorizationOptions::class); - $identityProvider = $this->createMock(IdentityProviderInterface::class); $this->expectException(RuntimeException::class); - $authorizationOptions->method('getRoleProvider')->willReturn([]); + $this->expectExceptionMessage('No role provider was set for authorization'); + (new RoleServiceFactory())($this->createContainer(new AuthorizationOptions([]))); + } - $container->expects($this->any())->method('get')->willReturnMap( - [ - [AuthorizationOptions::class, $authorizationOptions], - [IdentityProviderInterface::class, $identityProvider], - ] - ); + private function createContainer(AuthorizationOptions $options): Container + { + $empty = new Container(); - (new RoleServiceFactory())($container); + return new Container([ + AuthorizationOptions::class => $options, + IdentityProviderInterface::class => new IdentityProvider(), + RoleProviderPluginManager::class => new RoleProviderPluginManager($empty), + ]); } } diff --git a/test/Identity/AuthenticationIdentityProviderTest.php b/test/Identity/AuthenticationIdentityProviderTest.php index 8636aab..c7fb085 100644 --- a/test/Identity/AuthenticationIdentityProviderTest.php +++ b/test/Identity/AuthenticationIdentityProviderTest.php @@ -5,20 +5,23 @@ namespace DotTest\Rbac\Identity; use Dot\Rbac\Identity\AuthenticationIdentityProvider; -use Laminas\Authentication\AuthenticationServiceInterface; -use PHPUnit\Framework\MockObject\Exception; +use DotTest\Rbac\TestData\Identity; +use Laminas\Authentication\AuthenticationService; +use Laminas\Authentication\Storage\NonPersistent; +use PHPUnit\Framework\Attributes\CoversClass; use PHPUnit\Framework\TestCase; +#[CoversClass(AuthenticationIdentityProvider::class)] class AuthenticationIdentityProviderTest extends TestCase { - /** - * @throws Exception - */ public function testGetIdentity(): void { - $identity = $this->createMock(AuthenticationServiceInterface::class); - $authIdentityProvider = new AuthenticationIdentityProvider($identity); + $storage = new NonPersistent(); + $provider = new AuthenticationIdentityProvider(new AuthenticationService($storage)); + $this->assertNull($provider->getIdentity()); - $this->assertNull($authIdentityProvider->getIdentity()); + $identity = new Identity(['user']); + $storage->write($identity); + $this->assertSame($identity, $provider->getIdentity()); } } diff --git a/test/Options/AuthorizationOptionsTest.php b/test/Options/AuthorizationOptionsTest.php index 2427af8..ca06301 100644 --- a/test/Options/AuthorizationOptionsTest.php +++ b/test/Options/AuthorizationOptionsTest.php @@ -5,23 +5,46 @@ namespace DotTest\Rbac\Options; use Dot\Rbac\Options\AuthorizationOptions; +use PHPUnit\Framework\Attributes\CoversClass; use PHPUnit\Framework\TestCase; +#[CoversClass(AuthorizationOptions::class)] class AuthorizationOptionsTest extends TestCase { public function testGettersAndSetters(): void { - $test = ['test' => 'testOption']; - - $authOptions = new AuthorizationOptions($test); + $authOptions = new AuthorizationOptions(['unknown' => 'is ignored']); + $this->assertSame('guest', $authOptions->getGuestRole()); + $this->assertSame([], $authOptions->getAssertions()); + $this->assertSame([], $authOptions->getRoleProvider()); $authOptions->setGuestRole('testRole'); $this->assertSame('testRole', $authOptions->getGuestRole()); - $authOptions->setRoleProvider(['test' => 'testRole']); - $this->assertSame(['test' => 'testRole'], $authOptions->getRoleProvider()); + $authOptions->setRoleProvider(['type' => 'InMemory']); + $this->assertSame(['type' => 'InMemory'], $authOptions->getRoleProvider()); + + $authOptions->setAssertions([['type' => 'Assertion', 'permissions' => ['edit']]]); + $this->assertSame([['type' => 'Assertion', 'permissions' => ['edit']]], $authOptions->getAssertions()); + } - $authOptions->setAssertions(['test' => 'assertionTest']); - $this->assertSame(['test' => 'assertionTest'], $authOptions->getAssertions()); + public function testOptionsFromConfiguration(): void + { + $authOptions = new AuthorizationOptions([ + 'guest_role' => 'visitor', + 'role_provider' => ['type' => 'InMemory'], + 'assertions' => [['type' => 'Assertion']], + 'assertion_manager' => [], + 'role_provider_manager' => [], + ]); + + $this->assertSame('visitor', $authOptions->getGuestRole()); + $this->assertSame(['type' => 'InMemory'], $authOptions->getRoleProvider()); + $this->assertSame([['type' => 'Assertion']], $authOptions->getAssertions()); + } + + public function testNullOptions(): void + { + $this->assertSame('guest', (new AuthorizationOptions(null))->getGuestRole()); } } diff --git a/test/Plugin/AbstractPluginManagerTest.php b/test/Plugin/AbstractPluginManagerTest.php new file mode 100644 index 0000000..77b04f1 --- /dev/null +++ b/test/Plugin/AbstractPluginManagerTest.php @@ -0,0 +1,116 @@ + [AllowAssertion::class => InvokableFactory::class], + ]); + + $this->assertTrue($manager->has(AllowAssertion::class)); + $first = $manager->build(AllowAssertion::class); + $this->assertInstanceOf(AllowAssertion::class, $first); + $this->assertNotSame($first, $manager->build(AllowAssertion::class)); + } + + public function testBuildWithAliasAndCallableFactory(): void + { + $container = new Container(['deny' => new DenyAssertion()]); + $manager = new AssertionPluginManager($container, [ + 'aliases' => ['deny-alias' => 'deny'], + 'factories' => [ + 'deny' => static function (ContainerInterface $container, string $requestedName): AssertionInterface { + $assertion = $container->get($requestedName); + self::assertInstanceOf(AssertionInterface::class, $assertion); + + return $assertion; + }, + ], + ]); + + $this->assertTrue($manager->has('deny-alias')); + $this->assertInstanceOf(DenyAssertion::class, $manager->build('deny-alias')); + } + + public function testFactoryGetsOptions(): void + { + $manager = new AssertionPluginManager(new Container(), [ + 'factories' => [ContextAssertion::class => InvokableFactory::class], + ]); + + $assertion = $manager->build(ContextAssertion::class, ['allowed' => 'mine']); + $this->assertInstanceOf(ContextAssertion::class, $assertion); + } + + public function testUnknownPluginThrowsException(): void + { + $manager = new AssertionPluginManager(new Container()); + + $this->assertFalse($manager->has('unknown')); + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage( + 'No factory is registered for plugin "unknown" in ' . AssertionPluginManager::class + ); + $manager->build('unknown'); + } + + public function testFactoryThatIsNotCallableThrowsException(): void + { + $manager = new AssertionPluginManager(new Container(), [ + 'factories' => [AllowAssertion::class => 'NotAClass\\Factory'], + ]); + + $this->expectException(RuntimeException::class); + $this->expectExceptionMessage('The factory for plugin "' . AllowAssertion::class . '" is not callable'); + $manager->build(AllowAssertion::class); + } + + public function testWrongInstanceThrowsException(): void + { + $manager = new AssertionPluginManager(new Container(), [ + 'factories' => ['bad' => static fn (): stdClass => new stdClass()], + ]); + + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage( + AssertionPluginManager::class . ' can only create instances of ' + . AssertionInterface::class . '; stdClass is invalid' + ); + $manager->build('bad'); + } + + public function testBuildRejectsString(): void + { + $manager = new AssertionPluginManager(new Container(), [ + 'factories' => ['text' => static fn (): string => 'test'], + ]); + + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('; string is invalid'); + $manager->build('text'); + } +} diff --git a/test/Plugin/InvokableFactoryTest.php b/test/Plugin/InvokableFactoryTest.php new file mode 100644 index 0000000..d2d9153 --- /dev/null +++ b/test/Plugin/InvokableFactoryTest.php @@ -0,0 +1,33 @@ +assertInstanceOf(AllowAssertion::class, $instance); + } + + public function testCreatesWithOptions(): void + { + $instance = (new InvokableFactory())(new Container(), ContextAssertion::class, ['allowed' => 'mine']); + $this->assertInstanceOf(ContextAssertion::class, $instance); + + $authorization = (new InvokableFactory())(new Container(), IdentityProvider::class, []); + $this->assertInstanceOf(IdentityProvider::class, $authorization); + } +} diff --git a/test/Role/HierarchicalRoleTest.php b/test/Role/HierarchicalRoleTest.php index 1225061..a38693d 100644 --- a/test/Role/HierarchicalRoleTest.php +++ b/test/Role/HierarchicalRoleTest.php @@ -4,26 +4,25 @@ namespace DotTest\Rbac\Role; -use Dot\Authorization\Role\RoleInterface; use Dot\Rbac\Role\HierarchicalRole; -use PHPUnit\Framework\MockObject\Exception; +use Dot\Rbac\Role\Role; +use PHPUnit\Framework\Attributes\CoversClass; +use PHPUnit\Framework\Attributes\UsesClass; use PHPUnit\Framework\TestCase; +#[CoversClass(HierarchicalRole::class)] +#[UsesClass(Role::class)] class HierarchicalRoleTest extends TestCase { - /** - * @throws Exception - */ public function testAccessors(): void { - $name = 'testName'; - - $hierarchicalRole = new HierarchicalRole($name); - + $hierarchicalRole = new HierarchicalRole('parent'); $this->assertFalse($hierarchicalRole->hasChildren()); - $child = $this->createMock(RoleInterface::class); + $this->assertSame([], $hierarchicalRole->getChildren()); + + $child = new Role('child'); $hierarchicalRole->addChild($child); $this->assertTrue($hierarchicalRole->hasChildren()); - $this->assertIsArray($hierarchicalRole->getChildren()); + $this->assertSame(['child' => $child], $hierarchicalRole->getChildren()); } } diff --git a/test/Role/Provider/FactoryTest.php b/test/Role/Provider/FactoryTest.php new file mode 100644 index 0000000..018c4ce --- /dev/null +++ b/test/Role/Provider/FactoryTest.php @@ -0,0 +1,73 @@ +create([ + 'type' => 'InMemory', + 'options' => ['roles' => ['admin' => ['permissions' => ['edit']]]], + ]); + + $this->assertInstanceOf(InMemoryRoleProvider::class, $provider); + $admin = $provider->getRole('admin'); + $this->assertInstanceOf(Role::class, $admin); + $this->assertTrue($admin->hasPermission('edit')); + } + + public function testGetRoleProviderPluginManager(): void + { + $manager = new RoleProviderPluginManager(new Container()); + + $this->assertSame($manager, (new Factory(new Container(), $manager))->getRoleProviderPluginManager()); + + $factory = new Factory(new Container()); + $this->assertSame($factory->getRoleProviderPluginManager(), $factory->getRoleProviderPluginManager()); + } + + /** + * @return iterable, string}> + */ + public static function invalidSpecsProvider(): iterable + { + yield 'no type' => [[], 'Empty or no role provider set in config']; + yield 'empty type' => [['type' => ''], 'Empty or no role provider set in config']; + yield 'array type' => [['type' => ['InMemory']], 'Invalid role provider type of type array']; + yield 'string options' => [['type' => 'InMemory', 'options' => 'x'], 'Role provider options must be an array']; + } + + /** + * @param array $specs + */ + #[DataProvider('invalidSpecsProvider')] + public function testCreateWithInvalidSpecsThrowsException(array $specs, string $message): void + { + $this->expectException(RuntimeException::class); + $this->expectExceptionMessage($message); + (new Factory(new Container()))->create($specs); + } +} diff --git a/test/Role/Provider/InMemoryRoleProviderTest.php b/test/Role/Provider/InMemoryRoleProviderTest.php index 036250a..bdd17f1 100644 --- a/test/Role/Provider/InMemoryRoleProviderTest.php +++ b/test/Role/Provider/InMemoryRoleProviderTest.php @@ -4,25 +4,100 @@ namespace DotTest\Rbac\Role\Provider; +use Dot\Rbac\Exception\RuntimeException; +use Dot\Rbac\Role\HierarchicalRole; use Dot\Rbac\Role\Provider\InMemoryRoleProvider; +use Dot\Rbac\Role\Role; +use PHPUnit\Framework\Attributes\CoversClass; +use PHPUnit\Framework\Attributes\UsesClass; use PHPUnit\Framework\TestCase; +#[CoversClass(InMemoryRoleProvider::class)] +#[UsesClass(Role::class)] +#[UsesClass(HierarchicalRole::class)] class InMemoryRoleProviderTest extends TestCase { - public function testGetRoles(): void + public function testGetRolesBuildsConfiguredRoles(): void { - $memoryRoleProvide = new InMemoryRoleProvider([ + $provider = new InMemoryRoleProvider([ 'roles' => [ - 'testRole' => [ - 'children' => ['testRoleChild1', 'testRoleChild2'], - 'permissions' => ['*'], + 'admin' => [ + 'permissions' => ['edit', 'delete'], ], ], ]); - $roles = ['roles', 'testRole']; - - $roles = $memoryRoleProvide->getRoles($roles); + $roles = $provider->getRoles(['admin', 'unknown']); $this->assertCount(2, $roles); + + $admin = $roles[0]; + $this->assertInstanceOf(Role::class, $admin); + $this->assertNotInstanceOf(HierarchicalRole::class, $admin); + $this->assertSame('admin', $admin->getName()); + $this->assertTrue($admin->hasPermission('edit')); + $this->assertTrue($admin->hasPermission('delete')); + + $unknown = $roles[1]; + $this->assertInstanceOf(Role::class, $unknown); + $this->assertSame('unknown', $unknown->getName()); + $this->assertSame([], $unknown->getPermissions()); + } + + public function testHierarchicalRoleInheritsChildren(): void + { + $provider = new InMemoryRoleProvider([ + 'roles' => [ + 'admin' => ['children' => ['user'], 'permissions' => ['delete']], + 'user' => ['children' => 'guest', 'permissions' => ['edit']], + 'guest' => ['permissions' => ['view']], + ], + ]); + + $admin = $provider->getRole('admin'); + $this->assertInstanceOf(HierarchicalRole::class, $admin); + $this->assertTrue($admin->hasPermission('delete')); + + $user = $admin->getChildren()['user']; + $this->assertInstanceOf(HierarchicalRole::class, $user); + $this->assertTrue($user->hasPermission('edit')); + $this->assertArrayHasKey('guest', $user->getChildren()); + } + + public function testRoleIsCached(): void + { + $provider = new InMemoryRoleProvider(['roles' => ['admin' => ['permissions' => ['edit']]]]); + + $this->assertSame($provider->getRole('admin'), $provider->getRole('admin')); + $this->assertSame($provider->getRole('unknown'), $provider->getRole('unknown')); + } + + public function testWithoutOptions(): void + { + $provider = new InMemoryRoleProvider(); + + $this->assertSame([], $provider->getRoles([])); + $this->assertSame('guest', $provider->getRole('guest')->getName()); + } + + public function testCircularHierarchyThrowsException(): void + { + $provider = new InMemoryRoleProvider([ + 'roles' => [ + 'a' => ['children' => ['b']], + 'b' => ['children' => ['a']], + ], + ]); + + $this->expectException(RuntimeException::class); + $this->expectExceptionMessage('Circular role hierarchy found at role "a"'); + $provider->getRoles(['a']); + } + + public function testSelfReferenceThrowsException(): void + { + $provider = new InMemoryRoleProvider(['roles' => ['a' => ['children' => ['a']]]]); + + $this->expectException(RuntimeException::class); + $provider->getRole('a'); } } diff --git a/test/Role/Provider/RoleProviderPluginManagerTest.php b/test/Role/Provider/RoleProviderPluginManagerTest.php index a92c55a..21d92a0 100644 --- a/test/Role/Provider/RoleProviderPluginManagerTest.php +++ b/test/Role/Provider/RoleProviderPluginManagerTest.php @@ -4,35 +4,69 @@ namespace DotTest\Rbac\Role\Provider; -use Dot\Rbac\Factory\RoleProviderPluginManagerFactory; +use Dot\Rbac\Exception\InvalidArgumentException; +use Dot\Rbac\Plugin\AbstractPluginManager; +use Dot\Rbac\Plugin\InvokableFactory; +use Dot\Rbac\Role\Provider\InMemoryRoleProvider; use Dot\Rbac\Role\Provider\RoleProviderInterface; use Dot\Rbac\Role\Provider\RoleProviderPluginManager; -use Laminas\ServiceManager\Exception\InvalidServiceException; -use PHPUnit\Framework\MockObject\Exception; +use Dot\Rbac\Role\Role; +use DotTest\Rbac\TestData\Container; +use PHPUnit\Framework\Attributes\CoversClass; +use PHPUnit\Framework\Attributes\DataProvider; +use PHPUnit\Framework\Attributes\UsesClass; use PHPUnit\Framework\TestCase; -use Psr\Container\ContainerExceptionInterface; -use Psr\Container\ContainerInterface; -use Psr\Container\NotFoundExceptionInterface; use function sprintf; +#[CoversClass(RoleProviderPluginManager::class)] +#[UsesClass(AbstractPluginManager::class)] +#[UsesClass(InvokableFactory::class)] +#[UsesClass(InMemoryRoleProvider::class)] +#[UsesClass(Role::class)] class RoleProviderPluginManagerTest extends TestCase { /** - * @throws ContainerExceptionInterface - * @throws NotFoundExceptionInterface - * @throws Exception + * @return iterable */ - public function testWillNotCreateInvalidPlugin(): void + public static function aliasProvider(): iterable { - $container = $this->createMock(ContainerInterface::class); + foreach ( + [ + 'inmemoryroleprovider', + 'inMemoryRoleProvider', + 'InMemoryRoleProvider', + 'inmemory', + 'inMemory', + 'InMemory', + InMemoryRoleProvider::class, + ] as $alias + ) { + yield $alias => [$alias]; + } + } + + #[DataProvider('aliasProvider')] + public function testBuildsInMemoryRoleProvider(string $alias): void + { + $provider = (new RoleProviderPluginManager(new Container()))->build( + $alias, + ['roles' => ['admin' => ['permissions' => ['edit']]]] + ); - $container->expects($this->once()) - ->method('get') - ->with('config') - ->willReturn(['dot_authorization' => ['role_provider_manager' => []]]); + $this->assertInstanceOf(InMemoryRoleProvider::class, $provider); + $admin = $provider->getRole('admin'); + $this->assertInstanceOf(Role::class, $admin); + $this->assertTrue($admin->hasPermission('edit')); + } - $this->expectException(InvalidServiceException::class); + public function testWillNotCreateInvalidPlugin(): void + { + $manager = new RoleProviderPluginManager(new Container(), [ + 'factories' => ['invalid' => static fn (): string => 'invalid'], + ]); + + $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage( sprintf( '%s can only create instances of %s; string is invalid', @@ -40,8 +74,6 @@ public function testWillNotCreateInvalidPlugin(): void RoleProviderInterface::class ) ); - - $service = (new RoleProviderPluginManagerFactory())($container); - $service->validate('invalid'); + $manager->build('invalid'); } } diff --git a/test/Role/RbacTest.php b/test/Role/RbacTest.php index c5d03a9..16ebf37 100644 --- a/test/Role/RbacTest.php +++ b/test/Role/RbacTest.php @@ -6,20 +6,61 @@ use Dot\Rbac\Rbac; use Dot\Rbac\Role\HierarchicalRole; +use Dot\Rbac\Role\Role; +use Dot\Rbac\Role\RoleFlattener; +use DotTest\Rbac\TestData\PlainRole; +use PHPUnit\Framework\Attributes\CoversClass; +use PHPUnit\Framework\Attributes\UsesClass; use PHPUnit\Framework\TestCase; +#[CoversClass(Rbac::class)] +#[UsesClass(Role::class)] +#[UsesClass(HierarchicalRole::class)] +#[UsesClass(RoleFlattener::class)] class RbacTest extends TestCase { public function testIsGranted(): void { $rbac = new Rbac(); + $role = new Role('testRole'); + $this->assertFalse($rbac->isGranted('permission', [$role])); - $permissions = 'permission'; - - $role = new HierarchicalRole('testRole'); - $this->assertFalse($rbac->isGranted($permissions, [$role])); $role->addPermission('permission'); + $this->assertTrue($rbac->isGranted('permission', [$role])); + } + + public function testIsGrantedWithoutRoles(): void + { + $this->assertFalse((new Rbac())->isGranted('permission', [])); + } + + public function testChildPermissionIsGranted(): void + { + $child = new Role('child'); + $child->addPermission('view'); + $parent = new HierarchicalRole('parent'); + $parent->addChild($child); + + $rbac = new Rbac(); + $this->assertTrue($rbac->isGranted('view', [$parent])); + $this->assertFalse($rbac->isGranted('view', [new HierarchicalRole('other')])); + } + + public function testCircularHierarchyTerminates(): void + { + $roleA = new HierarchicalRole('a'); + $roleB = new HierarchicalRole('b'); + $roleA->addChild($roleB); + $roleB->addChild($roleA); - $this->assertTrue($rbac->isGranted($permissions, [$role])); + $this->assertFalse((new Rbac())->isGranted('x', [$roleA])); + + $roleB->addPermission('x'); + $this->assertTrue((new Rbac())->isGranted('x', [$roleA])); + } + + public function testRoleWithoutPermissionInterfaceIsNotGranted(): void + { + $this->assertFalse((new Rbac())->isGranted('x', [new PlainRole('plain')])); } } diff --git a/test/Role/RoleFlattenerTest.php b/test/Role/RoleFlattenerTest.php new file mode 100644 index 0000000..727bf59 --- /dev/null +++ b/test/Role/RoleFlattenerTest.php @@ -0,0 +1,64 @@ +addChild($guest); + $admin = new HierarchicalRole('admin'); + $admin->addChild($user); + + $this->assertSame(['admin', 'user', 'guest'], $this->names([$admin])); + } + + public function testFlattenGivesSharedChildOneTime(): void + { + $guest = new Role('guest'); + $user = new HierarchicalRole('user'); + $user->addChild($guest); + + $this->assertSame(['user', 'guest'], $this->names([$user, $guest])); + } + + public function testFlattenStopsOnCycle(): void + { + $roleA = new HierarchicalRole('a'); + $roleB = new HierarchicalRole('b'); + $roleA->addChild($roleB); + $roleB->addChild($roleA); + + $this->assertSame(['a', 'b'], $this->names([$roleA])); + } + + /** + * @param array $roles + * @return list + */ + private function names(array $roles): array + { + return array_map( + static fn (RoleInterface $role): string => $role->getName(), + iterator_to_array(RoleFlattener::flatten($roles), false) + ); + } +} diff --git a/test/Role/RoleServiceTest.php b/test/Role/RoleServiceTest.php index 8974859..dde7b03 100644 --- a/test/Role/RoleServiceTest.php +++ b/test/Role/RoleServiceTest.php @@ -4,65 +4,178 @@ namespace DotTest\Rbac\Role; -use Dot\Rbac\Identity\IdentityProviderInterface; +use Dot\Authorization\Role\RoleInterface; +use Dot\Rbac\Exception\InvalidArgumentException; +use Dot\Rbac\Exception\RuntimeException; use Dot\Rbac\Role\HierarchicalRole; -use Dot\Rbac\Role\Provider\RoleProviderInterface; +use Dot\Rbac\Role\Provider\InMemoryRoleProvider; use Dot\Rbac\Role\Role; +use Dot\Rbac\Role\RoleFlattener; use Dot\Rbac\Role\RoleService; -use PHPUnit\Framework\MockObject\Exception; -use PHPUnit\Framework\MockObject\MockObject; +use DotTest\Rbac\TestData\Identity; +use DotTest\Rbac\TestData\IdentityProvider; +use DotTest\Rbac\TestData\NamedObject; +use PHPUnit\Framework\Attributes\CoversClass; +use PHPUnit\Framework\Attributes\UsesClass; use PHPUnit\Framework\TestCase; +use stdClass; +use function array_map; +use function array_values; + +#[CoversClass(RoleService::class)] +#[UsesClass(InMemoryRoleProvider::class)] +#[UsesClass(Role::class)] +#[UsesClass(HierarchicalRole::class)] +#[UsesClass(RoleFlattener::class)] class RoleServiceTest extends TestCase { - private RoleService $roleService; - private RoleProviderInterface|MockObject $roleProvider; + private InMemoryRoleProvider $roleProvider; - /** - * @throws Exception - */ public function setUp(): void { - $identityProvider = $this->createMock(IdentityProviderInterface::class); - $this->roleProvider = $this->createMock(RoleProviderInterface::class); + $this->roleProvider = new InMemoryRoleProvider([ + 'roles' => [ + 'admin' => ['children' => ['user'], 'permissions' => ['delete']], + 'user' => ['permissions' => ['edit']], + 'guest' => ['permissions' => ['view']], + ], + ]); + } + + public function testGuestRoleAccessors(): void + { + $roleService = $this->createRoleService(); + $this->assertSame('guest', $roleService->getGuestRole()); + + $roleService->setGuestRole('tester'); + $this->assertSame('tester', $roleService->getGuestRole()); + } + + public function testGuestRolesWithoutIdentity(): void + { + $roleService = $this->createRoleService(); + + $this->assertNull($roleService->getIdentity()); + $this->assertSame(['guest'], $this->names($roleService->getIdentityRoles())); + } + + public function testIdentityRolesAreResolved(): void + { + $user = new Role('custom'); + $roleService = $this->createRoleService(new Identity(['admin', $user])); + + $this->assertSame(['custom', 'admin'], $this->names($roleService->getIdentityRoles())); + } + + public function testIdentityWithGetRolesWithoutInterface(): void + { + $identity = new class { + /** + * @return list + */ + public function getRoles(): array + { + return ['user']; + } + }; + + $this->assertSame(['user'], $this->names($this->createRoleService($identity)->getIdentityRoles())); + } + + public function testIdentityWithoutRolesThrowsException(): void + { + $this->expectException(RuntimeException::class); + $this->expectExceptionMessage('The identity must implement'); + $this->createRoleService(new stdClass())->getIdentityRoles(); + } + + public function testFalsyIdentityIsNotTreatedAsGuest(): void + { + $this->expectException(RuntimeException::class); + $this->createRoleService('0')->getIdentityRoles(); + } + + public function testMatchIdentityRolesIncludesChildren(): void + { + $roleService = $this->createRoleService(new Identity(['admin'])); - $this->roleService = new RoleService($identityProvider, $this->roleProvider); + $this->assertTrue($roleService->matchIdentityRoles(['user'])); + $this->assertTrue($roleService->matchIdentityRoles([new Role('admin')])); + $this->assertFalse($roleService->matchIdentityRoles(['guest'])); } - public function testMatchIdentityRoles(): void + public function testMatchIdentityRolesForGuest(): void { - $this->roleProvider->expects($this->any())->method('getRoles') - ->willReturn( - [new HierarchicalRole('test')] - ); + $roleService = $this->createRoleService(); - $roles = ['roles']; - $this->roleService->setGuestRole('testRole'); + $this->assertTrue($roleService->matchIdentityRoles(['guest'])); + $this->assertFalse($roleService->matchIdentityRoles(['user'])); + } - $this->roleService->matchIdentityRoles($roles); + public function testMatchIdentityRolesWithoutIdentityRoles(): void + { + $this->assertFalse($this->createRoleService(new Identity([]))->matchIdentityRoles(['user'])); + } - $this->assertFalse($this->roleService->matchIdentityRoles($roles)); + public function testResolveRolesKeepsRoleObjects(): void + { + $role = new Role('custom'); + + $this->assertSame([$role], $this->createRoleService()->resolveRoles([$role])); } - public function testRoleServiceAccessor(): void + public function testIntegerRoleIsConverted(): void { - $this->roleService->setGuestRole('tester'); - $result = $this->roleService->getGuestRole(); - $this->assertSame('tester', $result); + $this->assertSame(['1'], $this->names($this->createRoleService()->resolveRoles([1]))); } - public function testMatchIdentityRolesWithRole(): void + public function testRoleNamedLikeClass(): void { - $this->roleProvider->expects($this->any())->method('getRoles') - ->willReturn( - [new Role('test')] - ); + $roles = $this->createRoleService()->resolveRoles(['ReflectionClass']); + + $this->assertSame(['ReflectionClass'], $this->names($roles)); + } - $roles = ['roles']; - $this->roleService->setGuestRole('testRole'); + public function testObjectWithGetNameIsConverted(): void + { + $roles = $this->createRoleService()->resolveRoles([new NamedObject('user')]); - $this->roleService->matchIdentityRoles($roles); + $this->assertSame(['user'], $this->names($roles)); + $this->assertInstanceOf(Role::class, $roles[0]); + $this->assertTrue($roles[0]->hasPermission('edit')); + } - $this->assertFalse($this->roleService->matchIdentityRoles($roles)); + public function testInvalidRoleThrowsException(): void + { + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('Invalid role of type array'); + $this->createRoleService()->resolveRoles([['admin']]); + } + + public function testSetters(): void + { + $roleService = $this->createRoleService(); + $roleService->setIdentityProvider(new IdentityProvider(new Identity(['user']))); + $roleService->setRoleProvider(new InMemoryRoleProvider()); + + $roles = $roleService->getIdentityRoles(); + $this->assertSame(['user'], $this->names($roles)); + $this->assertInstanceOf(Role::class, $roles[0]); + $this->assertSame([], $roles[0]->getPermissions()); + } + + private function createRoleService(mixed $identity = null): RoleService + { + return new RoleService(new IdentityProvider($identity), $this->roleProvider); + } + + /** + * @param array $roles + * @return list + */ + private function names(array $roles): array + { + return array_values(array_map(static fn (RoleInterface $role): string => $role->getName(), $roles)); } } diff --git a/test/Role/RoleTest.php b/test/Role/RoleTest.php index cf5a694..e9b15c4 100644 --- a/test/Role/RoleTest.php +++ b/test/Role/RoleTest.php @@ -5,17 +5,20 @@ namespace DotTest\Rbac\Role; use Dot\Rbac\Role\Role; +use PHPUnit\Framework\Attributes\CoversClass; use PHPUnit\Framework\TestCase; +#[CoversClass(Role::class)] class RoleTest extends TestCase { public function testRoleAccessors(): void { $role = new Role('testRole'); - $this->assertSame('testRole', $role->getName()); + $this->assertSame([], $role->getPermissions()); + $role->addPermission('testPermission'); - $this->assertIsArray($role->getPermissions()); + $this->assertSame(['testPermission' => 'testPermission'], $role->getPermissions()); $this->assertTrue($role->hasPermission('testPermission')); $this->assertFalse($role->hasPermission('noPermission')); } diff --git a/test/TestData/AllowAssertion.php b/test/TestData/AllowAssertion.php new file mode 100644 index 0000000..6c9629f --- /dev/null +++ b/test/TestData/AllowAssertion.php @@ -0,0 +1,20 @@ +calls++; + + return true; + } +} diff --git a/test/TestData/Container.php b/test/TestData/Container.php new file mode 100644 index 0000000..c5462bf --- /dev/null +++ b/test/TestData/Container.php @@ -0,0 +1,42 @@ + $services + * @param list $failing Identifiers for which get() throws a ContainerException. + */ + public function __construct(private readonly array $services = [], private readonly array $failing = []) + { + } + + public function get(string $id): mixed + { + if (in_array($id, $this->failing, true)) { + throw new ContainerException($id); + } + + if (! array_key_exists($id, $this->services)) { + throw new ServiceNotFoundException($id); + } + + return $this->services[$id]; + } + + public function has(string $id): bool + { + return array_key_exists($id, $this->services); + } +} diff --git a/test/TestData/ContainerException.php b/test/TestData/ContainerException.php new file mode 100644 index 0000000..bc2073e --- /dev/null +++ b/test/TestData/ContainerException.php @@ -0,0 +1,18 @@ +|null $options + */ + public function __construct(private readonly ?array $options = null) + { + } + + public function assert(AuthorizationInterface $authorization, mixed $context = null): bool + { + $allowed = $this->options['allowed'] ?? 'own'; + + return $context === $allowed; + } +} diff --git a/test/TestData/DenyAssertion.php b/test/TestData/DenyAssertion.php new file mode 100644 index 0000000..bdac4f2 --- /dev/null +++ b/test/TestData/DenyAssertion.php @@ -0,0 +1,16 @@ + $roles + */ + public function __construct(private readonly array $roles) + { + } + + /** + * @return array + */ + public function getRoles(): array + { + return $this->roles; + } +} diff --git a/test/TestData/IdentityProvider.php b/test/TestData/IdentityProvider.php new file mode 100644 index 0000000..2473ca6 --- /dev/null +++ b/test/TestData/IdentityProvider.php @@ -0,0 +1,19 @@ +identity; + } +} diff --git a/test/TestData/NamedObject.php b/test/TestData/NamedObject.php new file mode 100644 index 0000000..4a9c2e4 --- /dev/null +++ b/test/TestData/NamedObject.php @@ -0,0 +1,20 @@ +name; + } +} diff --git a/test/TestData/PlainRole.php b/test/TestData/PlainRole.php new file mode 100644 index 0000000..591ad30 --- /dev/null +++ b/test/TestData/PlainRole.php @@ -0,0 +1,27 @@ +name; + } + + public function hasPermission(string $permission): bool + { + return true; + } +} diff --git a/test/TestData/ServiceNotFoundException.php b/test/TestData/ServiceNotFoundException.php new file mode 100644 index 0000000..fe1f951 --- /dev/null +++ b/test/TestData/ServiceNotFoundException.php @@ -0,0 +1,18 @@ +