Skip to content
This repository has been archived by the owner on Jul 3, 2020. It is now read-only.

Added ability to set multiple assertions and their condition for permissions #320

Open
wants to merge 12 commits into
base: master
Choose a base branch
from
61 changes: 61 additions & 0 deletions docs/06. Using the Authorization Service.md
Original file line number Diff line number Diff line change
Expand Up @@ -187,6 +187,67 @@ return [

Now, every time you check for `myPermission`, `myAssertion` will be checked as well.



### Multiple assertions
For convenience you can create instance of ZfcRbac\Assertion\AssertionSet class that can hold multiple assertions as well as specify condition for the check.

There are 2 conditions AND and OR.

If 'AND' condition is specified (this is default) all of the assertions in the set must pass the check.
If 'OR' condition is specified at least one of the assertions in the set must pass the check.

See the usage example here:

Create a factory for your assertion set.
```php

use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
use ZfcRbac\Assertion\AssertionSet;

class MyAssertionSetFactory implements FactoryInterface
{
/**
* {@inheritDoc}
* @return \ZfcRbac\Assertion\AssertionSet
*/
public function createService(ServiceLocatorInterface $serviceLocator)
{
$assertionManager = $serviceLocator->get('ZfcRbac\Assertion\AssertionPluginManager');
$assertion1 = $assertionManager->get('myAssertion1');
$assertion2 = $assertionManager->get('myAssertion2');

// create instance, set condition and add assertions
$assertionSet = new AssertionSet();
$assertionSet->setCondition(AssertionSet::CONDITION_OR);
$assertionSet->setAssertions([$assertion1, $assertion2]);
return $assertionSet;
}
}

```

Add it to assertion manager and then add it to assertion map:

```php
return [
'zfc_rbac' => [
'assertion_manager' => [
'factories' => [
'myAssertionSet' => MyAssertionSetFactory::class
]
],

'assertion_map' => [
'myPermission' => 'myAssertion', // single assertion
'myPermission2' => 'myAssertionSet' // multiple assertions in set
]
]
];
```


### Checking permissions in a service

So let's check for a permission, shall we?
Expand Down
183 changes: 183 additions & 0 deletions src/ZfcRbac/Assertion/AssertionSet.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,183 @@
<?php
/*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the MIT license.
*/
namespace ZfcRbac\Assertion;

use ZfcRbac\Exception\InvalidArgumentException;
use ZfcRbac\Service\AuthorizationService;

/**
* Assertion set to hold and process multiple assertions
*
* @author David Havl
* @licence MIT
*/

class AssertionSet implements AssertionInterface, \IteratorAggregate
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think most of the setters/getters are not required and/or can be private or removed only assert() method is required by interface so why expose those while we can build AssertionSet thought constructor?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

They are not required but I think it may be a good idea to have them, in case people want to use the class their way (see docs).

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't think anyone would want to modify this after it is added to AuthorizationService and even if they want this is not a good practice.
@basz @prolic @bakura10 what you think?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Of course not after it is added to AuthorizationService, but when specifying assertion map. See my other comment bellow.

{
/**
* Condition constants
*/
const CONDITION_OR = 'OR';
const CONDITION_AND = 'AND';

/**
* @var $assertions array
*/
protected $assertions = [];

/**
* @var $condition string
*/
protected $condition = 'AND';
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

AssertionSet::CONDITION_AND instead of AND


/**
* Constructor.
*
* @param AssertionInterface[] $assertions An array of assertions.
*/
public function __construct(array $assertions = array())
{
foreach ($assertions as $name => $assertion) {
$this->setAssertion($assertion, is_int($name) ? null : $name);
}
}

/**
* Set assertions.
*
* @param AssertionInterface[] $assertions The assertions to set
*
* @return $this
*/
public function setAssertions($assertions)
{
foreach ($assertions as $name => $assertion) {
$this->setAssertion($assertion, is_int($name) ? null : $name);
}
return $this;
}

/**
* Set an assertion.
*
* @param AssertionInterface $assertion The assertion instance
*
* @param string $name A name/alias
*
* @return $this
*/
public function setAssertion(AssertionInterface $assertion, $name = null)
{
if (null !== $name) {
$this->assertions[$name] = $assertion;
}
$this->assertions[] = $assertion;
return $this;
}

/**
* Returns true if the assertion if defined.
*
* @param string $name The assertion name
*
* @return bool true if the assertion is defined, false otherwise
*/
public function hasAssertion($name)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

not sure but do we use this somewhere outside this class?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes people can when they use the class directly (see docs).

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

okey maybe they could but still not convinced. Even if they want to modify it what is bad I think they could create new one instead. because reusing same set on different permissions and randomly modify them at the same time can lead to big problems. And if users would want those evil methods they could extend the class anyway no? so why add those we don't want to maintain +6 methods for just in case users would need them.
but again @basz @prolic @bakura10 @danizord what you think?

Copy link
Author

@DavidHavl DavidHavl Oct 28, 2016

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not sure you understand. This is to be used for example when creating assertion map. I was imagining usage of it for example like this:

Creating a factory where one can do anything they want

use Interop\Container\ContainerInterface;
use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
use ZfcRbac\Assertion\AssertionSet;

class MyAssertionSetFactory implements FactoryInterface
{
    /**
     * {@inheritDoc}
     *
     * @return AssertionSet
     */
    public function __invoke(ContainerInterface $container, $name, array $options = null)
    {
        $assertionManager = $container->get('ZfcRbac\Assertion\AssertionPluginManager');
        $assertion1 = $assertionManager->get('myAssertion1');
        $assertion2 = $assertionManager->get('myAssertion2');

        // create instance, set condition and add assertions
        $assertionSet = new AssertionSet();
        $assertionSet->setCondition(AssertionSet::CONDITION_OR);
        $assertionSet->setAssertions([$assertion1, $assertion2]);
        return $assertionSet;
    }

    /**
     * {@inheritDoc}
     *
     * For use with zend-servicemanager v2; proxies to __invoke().
     *
     * @param ServiceLocatorInterface $container
     * @return \ZfcRbac\Assertion\AssertionSet
     */
    public function createService(ServiceLocatorInterface $container)
    {
        // Retrieve the parent container when under zend-servicemanager v2
        if (method_exists($container, 'getServiceLocator')) {
            $container = $container->getServiceLocator() ?: $container;
        }

        return $this($container, AssertionSet::class);
    }
}

And then add it to assertion manager and assertion map config:

return [
    'zfc_rbac' => [
        'assertion_manager' => [
            'factories' => [
                'myAssertionSet' => MyAssertionSetFactory::class
            ]
        ],

        'assertion_map' => [
            'myPermission'  => 'myAssertion', // single assertion
            'myPermission2' => 'myAssertionSet' // multiple assertions in set
        ]
    ]
];

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

you could do the same without those methods:

$assertionManager = $container->get('ZfcRbac\Assertion\AssertionPluginManager');
$assertion1 = $assertionManager->get('myAssertion1');
$assertion2 = $assertionManager->get('myAssertion2');

// create instance, set condition and add assertions
 $assertionSet = new AssertionSet([
    'assertions' => [$assertion1, $assertion2],
    'condition' => AssertionSet::CONDITION_OR
]);

and this would prevent from changing later.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

+1 for immutable approach. That makes unit testing way easier and confident since you don't need to test a lot of possible different states.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fair enough. That is a good point.
Will rewrite.
Thanks.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I said but will repeat: not good that we can't do this:

$assertionSet = new AssertionSet([
    'assertions' => ['myAssertion1', 'myAssertion2'],
    'condition' => AssertionSet::CONDITION_OR
]);

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@svycka great, I am working on it.

{
return isset($this->assertions[$name]);
}

/**
* Gets a assertion value.
*
* @param string $name The assertion name
*
* @return AssertionInterface The assertion instance
*
* @throws InvalidArgumentException if the assertion is not defined
*/
public function getAssertion($name)
{
if (!$this->hasAssertion($name)) {
throw new InvalidArgumentException(sprintf('The assertion "%s" is not defined.', $name));
}
return $this->assertions[$name];
}

/**
* @return string
*/
public function getCondition()
{
return $this->condition;
}

/**
* Set condition
*
* @param string $condition
*/
public function setCondition($condition)
{
$this->condition = $condition;
}

/**
* Retrieve an external iterator
* @return \ArrayIterator
*/
public function getIterator()
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think there's no reason to expose this method and other getters?

{
return new \ArrayIterator($this->assertions);
}

/**
* Check if assertions are successful
*
* @param AuthorizationService $authorizationService
* @param mixed $context
* @return bool
*/
public function assert(AuthorizationService $authorizationService, $context = null)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

maybe not logical but it's possible to have zero assertions here then maybe return true by default or throw exception?

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

An empty assertion is not logical indeed and should either return FALSE or an exception.

Better to have defensive defaults.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good point. Thanx.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done

{
if (self::CONDITION_AND === $this->condition) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

if this class not a final then maybe AssertionSet::CONDITION_AND

foreach ($this->assertions as $assertion) {
if (!$assertion->assert($authorizationService, $context)) {
return false;
}
}

return true;
}

if (self::CONDITION_OR === $this->condition) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

if this class not a final then maybe AssertionSet::CONDITION_OR

foreach ($this->assertions as $assertion) {
if ($assertion->assert($authorizationService, $context)) {
return true;
}
}

return false;
}

throw new InvalidArgumentException(sprintf(
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should probably be checked at construction time

'Condition must be either "AND" or "OR", %s given',
is_object($this->condition) ? get_class($this->condition) : gettype($this->condition)
));
}
}
4 changes: 0 additions & 4 deletions src/ZfcRbac/Service/AuthorizationService.php
Original file line number Diff line number Diff line change
Expand Up @@ -122,19 +122,15 @@ public function getIdentity()
public function isGranted($permission, $context = null)
{
$roles = $this->roleService->getIdentityRoles();

if (empty($roles)) {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

no need to remove these empty lines

return false;
}

if (!$this->rbac->isGranted($roles, $permission)) {
return false;
}

if ($this->hasAssertion($permission)) {
return $this->assert($this->assertions[(string) $permission], $context);
}

return true;
}

Expand Down
48 changes: 48 additions & 0 deletions tests/ZfcRbacTest/Asset/SimpleFalseAssertion.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
<?php
/*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the MIT license.
*/

namespace ZfcRbacTest\Asset;

use ZfcRbac\Assertion\AssertionInterface;
use ZfcRbac\Service\AuthorizationService;

class SimpleFalseAssertion implements AssertionInterface
{
/**
* @var bool
*/
protected $called = false;

/**
* {@inheritDoc}
*/
public function assert(AuthorizationService $authorization, $context = null)
{
$this->called = true;

return false;
}

/**
* @return bool
*/
public function getCalled()
{
return $this->called;
}
}
48 changes: 48 additions & 0 deletions tests/ZfcRbacTest/Asset/SimpleTrueAssertion.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
<?php
/*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the MIT license.
*/

namespace ZfcRbacTest\Asset;

use ZfcRbac\Assertion\AssertionInterface;
use ZfcRbac\Service\AuthorizationService;

class SimpleTrueAssertion implements AssertionInterface
{
/**
* @var bool
*/
protected $called = false;

/**
* {@inheritDoc}
*/
public function assert(AuthorizationService $authorization, $context = null)
{
$this->called = true;

return true;
}

/**
* @return bool
*/
public function getCalled()
{
return $this->called;
}
}
Loading