Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 17 additions & 1 deletion features/authorization/deny.feature
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,8 @@ Feature: Authorization checking
{
"title": "Special Title",
"description": "Description",
"owner": "dunglas"
"owner": "dunglas",
"adminOnlyProperty": "secret"
}
"""
Then the response status code should be 201
Expand Down Expand Up @@ -100,3 +101,18 @@ Feature: Authorization checking
}
"""
Then the response status code should be 200

Scenario: An admin retrieves a resource with an admin only viewable property
When I add "Accept" header equal to "application/ld+json"
And I add "Content-Type" header equal to "application/ld+json"
And I add "Authorization" header equal to "Basic YWRtaW46a2l0dGVu"
And I send a "GET" request to "/secured_dummies"
Then the response status code should be 200
And the response should contain "adminOnlyProperty"

Scenario: A user retrieves a resource with an admin only viewable property
When I add "Accept" header equal to "application/ld+json"
And I add "Authorization" header equal to "Basic ZHVuZ2xhczprZXZpbg=="
And I send a "GET" request to "/secured_dummies"
Then the response status code should be 200
And the response should not contain "adminOnlyProperty"
6 changes: 3 additions & 3 deletions features/graphql/authorization.feature
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ Feature: Authorization checking
When I send the following GraphQL request:
"""
mutation {
createSecuredDummy(input: {owner: "me", title: "Hi", description: "Desc", clientMutationId: "auth"}) {
createSecuredDummy(input: {owner: "me", title: "Hi", description: "Desc", adminOnlyProperty: "secret", clientMutationId: "auth"}) {
securedDummy {
title
owner
Expand All @@ -112,7 +112,7 @@ Feature: Authorization checking
And I send the following GraphQL request:
"""
mutation {
createSecuredDummy(input: {owner: "someone", title: "Hi", description: "Desc"}) {
createSecuredDummy(input: {owner: "someone", title: "Hi", description: "Desc", adminOnlyProperty: "secret"}) {
securedDummy {
id
title
Expand All @@ -131,7 +131,7 @@ Feature: Authorization checking
And I send the following GraphQL request:
"""
mutation {
createSecuredDummy(input: {owner: "dunglas", title: "Hi", description: "Desc"}) {
createSecuredDummy(input: {owner: "dunglas", title: "Hi", description: "Desc", adminOnlyProperty: "secret"}) {
securedDummy {
id
title
Expand Down
8 changes: 8 additions & 0 deletions src/Annotation/ApiProperty.php
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
* @Attribute("openapiContext", type="array"),
* @Attribute("jsonldContext", type="array"),
* @Attribute("push", type="bool"),
* @Attribute("security", type="string"),
* @Attribute("swaggerContext", type="array")
* )
*/
Expand Down Expand Up @@ -118,6 +119,13 @@ final class ApiProperty
*/
private $push;

/**
* @see https://github.com/Haehnchen/idea-php-annotation-plugin/issues/112
*
* @var string
*/
private $security;

/**
* @see https://github.com/Haehnchen/idea-php-annotation-plugin/issues/112
*
Expand Down
2 changes: 1 addition & 1 deletion src/Bridge/Symfony/Bundle/Resources/config/api.xml
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,7 @@
<argument>null</argument>
<argument type="tagged" tag="api_platform.data_transformer" on-invalid="ignore" />
<argument type="service" id="api_platform.metadata.resource.metadata_factory" on-invalid="ignore" />
<argument>false</argument>
<argument type="service" id="api_platform.security.resource_access_checker" />

<!-- Run before serializer.normalizer.json_serializable -->
<tag name="serializer.normalizer" priority="-895" />
Expand Down
2 changes: 1 addition & 1 deletion src/Bridge/Symfony/Bundle/Resources/config/hal.xml
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@
<argument type="collection" />
<argument type="tagged" tag="api_platform.data_transformer" on-invalid="ignore" />
<argument type="service" id="api_platform.metadata.resource.metadata_factory" on-invalid="ignore" />
<argument>false</argument>
<argument type="service" id="api_platform.security.resource_access_checker" />

<!-- Run before serializer.normalizer.json_serializable -->
<tag name="serializer.normalizer" priority="-890" />
Expand Down
2 changes: 1 addition & 1 deletion src/Bridge/Symfony/Bundle/Resources/config/jsonapi.xml
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@
<argument type="service" id="api_platform.metadata.resource.metadata_factory" />
<argument type="collection" />
<argument type="tagged" tag="api_platform.data_transformer" on-invalid="ignore" />
<argument>false</argument>
<argument type="service" id="api_platform.security.resource_access_checker" />

<!-- Run before serializer.normalizer.json_serializable -->
<tag name="serializer.normalizer" priority="-890" />
Expand Down
2 changes: 1 addition & 1 deletion src/Bridge/Symfony/Bundle/Resources/config/jsonld.xml
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@
<argument type="service" id="serializer.mapping.class_metadata_factory" on-invalid="ignore" />
<argument type="collection" />
<argument type="tagged" tag="api_platform.data_transformer" on-invalid="ignore" />
<argument>false</argument>
<argument type="service" id="api_platform.security.resource_access_checker" />

<!-- Run before serializer.normalizer.json_serializable -->
<tag name="serializer.normalizer" priority="-890" />
Expand Down
5 changes: 3 additions & 2 deletions src/JsonApi/Serializer/ItemNormalizer.php
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
use ApiPlatform\Core\Metadata\Property\Factory\PropertyNameCollectionFactoryInterface;
use ApiPlatform\Core\Metadata\Property\PropertyMetadata;
use ApiPlatform\Core\Metadata\Resource\Factory\ResourceMetadataFactoryInterface;
use ApiPlatform\Core\Security\ResourceAccessCheckerInterface;
use ApiPlatform\Core\Serializer\AbstractItemNormalizer;
use ApiPlatform\Core\Serializer\CacheKeyTrait;
use ApiPlatform\Core\Serializer\ContextTrait;
Expand Down Expand Up @@ -49,9 +50,9 @@ final class ItemNormalizer extends AbstractItemNormalizer

private $componentsCache = [];

public function __construct(PropertyNameCollectionFactoryInterface $propertyNameCollectionFactory, PropertyMetadataFactoryInterface $propertyMetadataFactory, IriConverterInterface $iriConverter, ResourceClassResolverInterface $resourceClassResolver, ?PropertyAccessorInterface $propertyAccessor, ?NameConverterInterface $nameConverter, ResourceMetadataFactoryInterface $resourceMetadataFactory, array $defaultContext = [], iterable $dataTransformers = [])
public function __construct(PropertyNameCollectionFactoryInterface $propertyNameCollectionFactory, PropertyMetadataFactoryInterface $propertyMetadataFactory, IriConverterInterface $iriConverter, ResourceClassResolverInterface $resourceClassResolver, ?PropertyAccessorInterface $propertyAccessor, ?NameConverterInterface $nameConverter, ResourceMetadataFactoryInterface $resourceMetadataFactory, array $defaultContext = [], iterable $dataTransformers = [], ResourceAccessCheckerInterface $resourceAccessChecker = null)
{
parent::__construct($propertyNameCollectionFactory, $propertyMetadataFactory, $iriConverter, $resourceClassResolver, $propertyAccessor, $nameConverter, null, null, false, $defaultContext, $dataTransformers, $resourceMetadataFactory);
parent::__construct($propertyNameCollectionFactory, $propertyMetadataFactory, $iriConverter, $resourceClassResolver, $propertyAccessor, $nameConverter, null, null, false, $defaultContext, $dataTransformers, $resourceMetadataFactory, $resourceAccessChecker);
}

/**
Expand Down
5 changes: 3 additions & 2 deletions src/JsonLd/Serializer/ItemNormalizer.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
use ApiPlatform\Core\Metadata\Property\Factory\PropertyMetadataFactoryInterface;
use ApiPlatform\Core\Metadata\Property\Factory\PropertyNameCollectionFactoryInterface;
use ApiPlatform\Core\Metadata\Resource\Factory\ResourceMetadataFactoryInterface;
use ApiPlatform\Core\Security\ResourceAccessCheckerInterface;
use ApiPlatform\Core\Serializer\AbstractItemNormalizer;
use ApiPlatform\Core\Serializer\ContextTrait;
use ApiPlatform\Core\Util\ClassInfoTrait;
Expand All @@ -43,9 +44,9 @@ final class ItemNormalizer extends AbstractItemNormalizer

private $contextBuilder;

public function __construct(ResourceMetadataFactoryInterface $resourceMetadataFactory, PropertyNameCollectionFactoryInterface $propertyNameCollectionFactory, PropertyMetadataFactoryInterface $propertyMetadataFactory, IriConverterInterface $iriConverter, ResourceClassResolverInterface $resourceClassResolver, ContextBuilderInterface $contextBuilder, PropertyAccessorInterface $propertyAccessor = null, NameConverterInterface $nameConverter = null, ClassMetadataFactoryInterface $classMetadataFactory = null, array $defaultContext = [], iterable $dataTransformers = [])
public function __construct(ResourceMetadataFactoryInterface $resourceMetadataFactory, PropertyNameCollectionFactoryInterface $propertyNameCollectionFactory, PropertyMetadataFactoryInterface $propertyMetadataFactory, IriConverterInterface $iriConverter, ResourceClassResolverInterface $resourceClassResolver, ContextBuilderInterface $contextBuilder, PropertyAccessorInterface $propertyAccessor = null, NameConverterInterface $nameConverter = null, ClassMetadataFactoryInterface $classMetadataFactory = null, array $defaultContext = [], iterable $dataTransformers = [], ResourceAccessCheckerInterface $resourceAccessChecker = null)
{
parent::__construct($propertyNameCollectionFactory, $propertyMetadataFactory, $iriConverter, $resourceClassResolver, $propertyAccessor, $nameConverter, $classMetadataFactory, null, false, $defaultContext, $dataTransformers, $resourceMetadataFactory);
parent::__construct($propertyNameCollectionFactory, $propertyMetadataFactory, $iriConverter, $resourceClassResolver, $propertyAccessor, $nameConverter, $classMetadataFactory, null, false, $defaultContext, $dataTransformers, $resourceMetadataFactory, $resourceAccessChecker);

$this->contextBuilder = $contextBuilder;
}
Expand Down
24 changes: 23 additions & 1 deletion src/Serializer/AbstractItemNormalizer.php
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
use ApiPlatform\Core\Metadata\Property\Factory\PropertyNameCollectionFactoryInterface;
use ApiPlatform\Core\Metadata\Property\PropertyMetadata;
use ApiPlatform\Core\Metadata\Resource\Factory\ResourceMetadataFactoryInterface;
use ApiPlatform\Core\Security\ResourceAccessCheckerInterface;
use ApiPlatform\Core\Util\ClassInfoTrait;
use Symfony\Component\PropertyAccess\Exception\NoSuchPropertyException;
use Symfony\Component\PropertyAccess\PropertyAccess;
Expand Down Expand Up @@ -55,13 +56,14 @@ abstract class AbstractItemNormalizer extends AbstractObjectNormalizer
protected $propertyMetadataFactory;
protected $iriConverter;
protected $resourceClassResolver;
protected $resourceAccessChecker;
protected $propertyAccessor;
protected $itemDataProvider;
protected $allowPlainIdentifiers;
protected $dataTransformers = [];
protected $localCache = [];

public function __construct(PropertyNameCollectionFactoryInterface $propertyNameCollectionFactory, PropertyMetadataFactoryInterface $propertyMetadataFactory, IriConverterInterface $iriConverter, ResourceClassResolverInterface $resourceClassResolver, PropertyAccessorInterface $propertyAccessor = null, NameConverterInterface $nameConverter = null, ClassMetadataFactoryInterface $classMetadataFactory = null, ItemDataProviderInterface $itemDataProvider = null, bool $allowPlainIdentifiers = false, array $defaultContext = [], iterable $dataTransformers = [], ResourceMetadataFactoryInterface $resourceMetadataFactory = null)
public function __construct(PropertyNameCollectionFactoryInterface $propertyNameCollectionFactory, PropertyMetadataFactoryInterface $propertyMetadataFactory, IriConverterInterface $iriConverter, ResourceClassResolverInterface $resourceClassResolver, PropertyAccessorInterface $propertyAccessor = null, NameConverterInterface $nameConverter = null, ClassMetadataFactoryInterface $classMetadataFactory = null, ItemDataProviderInterface $itemDataProvider = null, bool $allowPlainIdentifiers = false, array $defaultContext = [], iterable $dataTransformers = [], ResourceMetadataFactoryInterface $resourceMetadataFactory = null, ResourceAccessCheckerInterface $resourceAccessChecker = null)
{
if (!isset($defaultContext['circular_reference_handler'])) {
$defaultContext['circular_reference_handler'] = function ($object) {
Expand All @@ -83,6 +85,7 @@ public function __construct(PropertyNameCollectionFactoryInterface $propertyName
$this->allowPlainIdentifiers = $allowPlainIdentifiers;
$this->dataTransformers = $dataTransformers;
$this->resourceMetadataFactory = $resourceMetadataFactory;
$this->resourceAccessChecker = $resourceAccessChecker;
}

/**
Expand Down Expand Up @@ -349,6 +352,25 @@ protected function getAllowedAttributes($classOrObject, array $context, $attribu
return $allowedAttributes;
}

/**
* {@inheritdoc}
*/
protected function isAllowedAttribute($classOrObject, $attribute, $format = null, array $context = [])
{
if (!parent::isAllowedAttribute($classOrObject, $attribute, $format, $context)) {
return false;
}

$options = $this->getFactoryOptions($context);
$propertyMetadata = $this->propertyMetadataFactory->create($context['resource_class'], $attribute, $options);
$security = $propertyMetadata->getAttribute('security');
if ($this->resourceAccessChecker && $security) {
return $this->resourceAccessChecker->isGranted($attribute, $security);
}

return true;
}

/**
* {@inheritdoc}
*/
Expand Down
5 changes: 3 additions & 2 deletions src/Serializer/ItemNormalizer.php
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
use ApiPlatform\Core\Metadata\Property\Factory\PropertyMetadataFactoryInterface;
use ApiPlatform\Core\Metadata\Property\Factory\PropertyNameCollectionFactoryInterface;
use ApiPlatform\Core\Metadata\Resource\Factory\ResourceMetadataFactoryInterface;
use ApiPlatform\Core\Security\ResourceAccessCheckerInterface;
use Psr\Log\LoggerInterface;
use Psr\Log\NullLogger;
use Symfony\Component\PropertyAccess\PropertyAccessorInterface;
Expand All @@ -36,9 +37,9 @@ class ItemNormalizer extends AbstractItemNormalizer
{
private $logger;

public function __construct(PropertyNameCollectionFactoryInterface $propertyNameCollectionFactory, PropertyMetadataFactoryInterface $propertyMetadataFactory, IriConverterInterface $iriConverter, ResourceClassResolverInterface $resourceClassResolver, PropertyAccessorInterface $propertyAccessor = null, NameConverterInterface $nameConverter = null, ClassMetadataFactoryInterface $classMetadataFactory = null, ItemDataProviderInterface $itemDataProvider = null, bool $allowPlainIdentifiers = false, LoggerInterface $logger = null, iterable $dataTransformers = [], ResourceMetadataFactoryInterface $resourceMetadataFactory = null)
public function __construct(PropertyNameCollectionFactoryInterface $propertyNameCollectionFactory, PropertyMetadataFactoryInterface $propertyMetadataFactory, IriConverterInterface $iriConverter, ResourceClassResolverInterface $resourceClassResolver, PropertyAccessorInterface $propertyAccessor = null, NameConverterInterface $nameConverter = null, ClassMetadataFactoryInterface $classMetadataFactory = null, ItemDataProviderInterface $itemDataProvider = null, bool $allowPlainIdentifiers = false, LoggerInterface $logger = null, iterable $dataTransformers = [], ResourceMetadataFactoryInterface $resourceMetadataFactory = null, ResourceAccessCheckerInterface $resourceAccessChecker = null)
{
parent::__construct($propertyNameCollectionFactory, $propertyMetadataFactory, $iriConverter, $resourceClassResolver, $propertyAccessor, $nameConverter, $classMetadataFactory, $itemDataProvider, $allowPlainIdentifiers, [], $dataTransformers, $resourceMetadataFactory);
parent::__construct($propertyNameCollectionFactory, $propertyMetadataFactory, $iriConverter, $resourceClassResolver, $propertyAccessor, $nameConverter, $classMetadataFactory, $itemDataProvider, $allowPlainIdentifiers, [], $dataTransformers, $resourceMetadataFactory, $resourceAccessChecker);

$this->logger = $logger ?: new NullLogger();
}
Expand Down
2 changes: 2 additions & 0 deletions tests/Annotation/ApiPropertyTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ public function testConstruct()
'fetchable' => true,
'fetchEager' => false,
'jsonldContext' => ['foo' => 'bar'],
'security' => 'is_granted(\'ROLE_ADMIN\')',
'swaggerContext' => ['foo' => 'baz'],
'openapiContext' => ['foo' => 'baz'],
'push' => true,
Expand All @@ -62,6 +63,7 @@ public function testConstruct()
'fetchable' => false,
'fetch_eager' => false,
'jsonld_context' => ['foo' => 'bar'],
'security' => 'is_granted(\'ROLE_ADMIN\')',
'swagger_context' => ['foo' => 'baz'],
'openapi_context' => ['foo' => 'baz'],
'push' => true,
Expand Down
21 changes: 20 additions & 1 deletion tests/Fixtures/TestBundle/Document/SecuredDummy.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@

namespace ApiPlatform\Core\Tests\Fixtures\TestBundle\Document;

use ApiPlatform\Core\Annotation\ApiProperty;
use ApiPlatform\Core\Annotation\ApiResource;
use Doctrine\ODM\MongoDB\Mapping\Annotations as ODM;
use Symfony\Component\Validator\Constraints as Assert;
Expand All @@ -26,7 +27,7 @@
* @ApiResource(
* attributes={"security"="is_granted('ROLE_USER')"},
* collectionOperations={
* "get",
* "get"={"security"="is_granted('ROLE_USER') or is_granted('ROLE_ADMIN')"},
* "get_from_data_provider_generator"={
* "method"="GET",
* "path"="custom_data_provider_generator",
Expand Down Expand Up @@ -72,6 +73,14 @@ class SecuredDummy
*/
private $description = '';

/**
* @var string The dummy secret property, only readable/writable by specific users
*
* @ODM\Field
* @ApiProperty(security="is_granted('ROLE_ADMIN')")
*/
private $adminOnlyProperty = '';

/**
* @var string The owner
*
Expand Down Expand Up @@ -105,6 +114,16 @@ public function setDescription(string $description)
$this->description = $description;
}

public function getAdminOnlyProperty(): ?string
{
return $this->adminOnlyProperty;
}

public function setAdminOnlyProperty(?string $adminOnlyProperty)
{
$this->adminOnlyProperty = $adminOnlyProperty;
}

public function getOwner(): string
{
return $this->owner;
Expand Down
21 changes: 20 additions & 1 deletion tests/Fixtures/TestBundle/Entity/SecuredDummy.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@

namespace ApiPlatform\Core\Tests\Fixtures\TestBundle\Entity;

use ApiPlatform\Core\Annotation\ApiProperty;
use ApiPlatform\Core\Annotation\ApiResource;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
Expand All @@ -25,7 +26,7 @@
* @ApiResource(
* attributes={"security"="is_granted('ROLE_USER')"},
* collectionOperations={
* "get",
* "get"={"security"="is_granted('ROLE_USER') or is_granted('ROLE_ADMIN')"},
* "get_from_data_provider_generator"={
* "method"="GET",
* "path"="custom_data_provider_generator",
Expand Down Expand Up @@ -73,6 +74,14 @@ class SecuredDummy
*/
private $description = '';

/**
* @var string The dummy secret property, only readable/writable by specific users
*
* @ORM\Column
* @ApiProperty(security="is_granted('ROLE_ADMIN')")
*/
private $adminOnlyProperty = '';

/**
* @var string The owner
*
Expand Down Expand Up @@ -106,6 +115,16 @@ public function setDescription(string $description)
$this->description = $description;
}

public function getAdminOnlyProperty(): ?string
{
return $this->adminOnlyProperty;
}

public function setAdminOnlyProperty(?string $adminOnlyProperty)
{
$this->adminOnlyProperty = $adminOnlyProperty;
}

public function getOwner(): string
{
return $this->owner;
Expand Down
Loading