Skip to content

Allow throwing an access denied exception on denormalization of secured properties #7221

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 10 commits into from
Jun 20, 2025
Merged
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
12 changes: 11 additions & 1 deletion src/Serializer/AbstractItemNormalizer.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@

use ApiPlatform\Metadata\ApiProperty;
use ApiPlatform\Metadata\CollectionOperationInterface;
use ApiPlatform\Metadata\Exception\AccessDeniedException;
use ApiPlatform\Metadata\Exception\InvalidArgumentException;
use ApiPlatform\Metadata\Exception\ItemNotFoundException;
use ApiPlatform\Metadata\IriConverterInterface;
Expand Down Expand Up @@ -266,18 +267,27 @@ public function denormalize(mixed $data, string $class, ?string $format = null,
$options = $this->getFactoryOptions($context);
$propertyNames = iterator_to_array($this->propertyNameCollectionFactory->create($resourceClass, $options));

$operation = $context['operation'] ?? null;
$throwOnAccessDenied = $operation?->getExtraProperties()['throw_on_access_denied'] ?? false;
$securityMessage = $operation?->getSecurityMessage() ?? null;

// Revert attributes that aren't allowed to be changed after a post-denormalize check
foreach (array_keys($data) as $attribute) {
$attribute = $this->nameConverter ? $this->nameConverter->denormalize((string) $attribute) : $attribute;
$propertyMetadata = $this->propertyMetadataFactory->create($resourceClass, $attribute, $options);
$attributeExtraProperties = $propertyMetadata->getExtraProperties() ?? [];
$throwOnPropertyAccessDenied = $attributeExtraProperties['throw_on_access_denied'] ?? $throwOnAccessDenied;
if (!\in_array($attribute, $propertyNames, true)) {
continue;
}

if (!$this->canAccessAttributePostDenormalize($object, $previousObject, $attribute, $context)) {
if ($throwOnPropertyAccessDenied) {
throw new AccessDeniedException($securityMessage ?? 'Access denied');
}
if (null !== $previousObject) {
$this->setValue($object, $attribute, $this->propertyAccessor->getValue($previousObject, $attribute));
} else {
$propertyMetadata = $this->propertyMetadataFactory->create($resourceClass, $attribute, $options);
$this->setValue($object, $attribute, $propertyMetadata->getDefault());
}
}
Expand Down
169 changes: 169 additions & 0 deletions src/Serializer/Tests/AbstractItemNormalizerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,14 @@

use ApiPlatform\Metadata\ApiProperty;
use ApiPlatform\Metadata\ApiResource;
use ApiPlatform\Metadata\Exception\AccessDeniedException;
use ApiPlatform\Metadata\Exception\InvalidArgumentException;
use ApiPlatform\Metadata\Exception\ItemNotFoundException;
use ApiPlatform\Metadata\Get;
use ApiPlatform\Metadata\GetCollection;
use ApiPlatform\Metadata\IriConverterInterface;
use ApiPlatform\Metadata\Operations;
use ApiPlatform\Metadata\Patch;
use ApiPlatform\Metadata\Property\Factory\PropertyMetadataFactoryInterface;
use ApiPlatform\Metadata\Property\Factory\PropertyNameCollectionFactoryInterface;
use ApiPlatform\Metadata\Property\PropertyNameCollection;
Expand Down Expand Up @@ -306,6 +308,173 @@ public function testNormalizePropertyAsIriWithUriTemplate(): void
]));
}

public function testDenormalizeWithSecuredPropertyAndThrowOnAccessDeniedExtraPropertyInAttributeMetaThrowsAccessDeniedExceptionWithSecurityMessage(): void
{
$data = [
'title' => 'foo',
'adminOnlyProperty' => 'secret',
];
$propertyNameCollectionFactoryProphecy = $this->prophesize(PropertyNameCollectionFactoryInterface::class);
$propertyNameCollectionFactoryProphecy->create(SecuredDummy::class, [])->willReturn(new PropertyNameCollection(['title', 'adminOnlyProperty']));

$propertyMetadataFactoryProphecy = $this->prophesize(PropertyMetadataFactoryInterface::class);

if (!method_exists(PropertyInfoExtractor::class, 'getType')) {
$propertyMetadataFactoryProphecy->create(SecuredDummy::class, 'title', [])->willReturn((new ApiProperty())->withBuiltinTypes([new LegacyType(LegacyType::BUILTIN_TYPE_STRING)])->withDescription('')->withReadable(false)->withWritable(true));
$propertyMetadataFactoryProphecy->create(SecuredDummy::class, 'adminOnlyProperty', [])->willReturn((new ApiProperty())->withBuiltinTypes([new LegacyType(LegacyType::BUILTIN_TYPE_STRING)])->withDescription('')->withReadable(true)->withSecurityPostDenormalize('is_granted(\'ROLE_ADMIN\')')->withExtraProperties(['throw_on_access_denied' => true]));
} else {
$propertyMetadataFactoryProphecy->create(SecuredDummy::class, 'title', [])->willReturn((new ApiProperty())->withNativeType(Type::string())->withDescription('')->withReadable(false)->withWritable(true));
$propertyMetadataFactoryProphecy->create(SecuredDummy::class, 'adminOnlyProperty', [])->willReturn((new ApiProperty())->withNativeType(Type::string())->withDescription('')->withReadable(true)->withSecurityPostDenormalize('is_granted(\'ROLE_ADMIN\')')->withExtraProperties(['throw_on_access_denied' => true]));
}

$iriConverterProphecy = $this->prophesize(IriConverterInterface::class);

$propertyAccessorProphecy = $this->prophesize(PropertyAccessorInterface::class);

$resourceClassResolverProphecy = $this->prophesize(ResourceClassResolverInterface::class);
$resourceClassResolverProphecy->getResourceClass(null, SecuredDummy::class)->willReturn(SecuredDummy::class);
$resourceClassResolverProphecy->isResourceClass(SecuredDummy::class)->willReturn(true);

$serializerProphecy = $this->prophesize(SerializerInterface::class);
$serializerProphecy->willImplement(NormalizerInterface::class);

$resourceAccessChecker = $this->prophesize(ResourceAccessCheckerInterface::class);
$resourceAccessChecker->isGranted(
SecuredDummy::class,
'is_granted(\'ROLE_ADMIN\')',
Argument::that(function (array $context) {
return \array_key_exists('property', $context)
&& \array_key_exists('object', $context)
&& \array_key_exists('previous_object', $context)
&& 'adminOnlyProperty' === $context['property']
&& null === $context['previous_object']
&& $context['object'] instanceof SecuredDummy;
})
)->willReturn(false);

$normalizer = new class($propertyNameCollectionFactoryProphecy->reveal(), $propertyMetadataFactoryProphecy->reveal(), $iriConverterProphecy->reveal(), $resourceClassResolverProphecy->reveal(), $propertyAccessorProphecy->reveal(), null, null, [], null, $resourceAccessChecker->reveal()) extends AbstractItemNormalizer {};
$normalizer->setSerializer($serializerProphecy->reveal());

$this->expectException(AccessDeniedException::class);
$this->expectExceptionMessage('Access denied');

$normalizer->denormalize($data, SecuredDummy::class);
}

public function testDenormalizeWithSecuredPropertyAndThrowOnAccessDeniedExtraPropertyInOperationAndSecurityMessageInOperationThrowsAccessDeniedExceptionWithSecurityMessage(): void
{
$data = [
'title' => 'foo',
'adminOnlyProperty' => 'secret',
];
$propertyNameCollectionFactoryProphecy = $this->prophesize(PropertyNameCollectionFactoryInterface::class);
$propertyNameCollectionFactoryProphecy->create(SecuredDummy::class, [])->willReturn(new PropertyNameCollection(['title', 'adminOnlyProperty']));

$propertyMetadataFactoryProphecy = $this->prophesize(PropertyMetadataFactoryInterface::class);

if (!method_exists(PropertyInfoExtractor::class, 'getType')) {
$propertyMetadataFactoryProphecy->create(SecuredDummy::class, 'title', [])->willReturn((new ApiProperty())->withBuiltinTypes([new LegacyType(LegacyType::BUILTIN_TYPE_STRING)])->withDescription('')->withReadable(false)->withWritable(true));
$propertyMetadataFactoryProphecy->create(SecuredDummy::class, 'adminOnlyProperty', [])->willReturn((new ApiProperty())->withBuiltinTypes([new LegacyType(LegacyType::BUILTIN_TYPE_STRING)])->withDescription('')->withReadable(true)->withSecurityPostDenormalize('is_granted(\'ROLE_ADMIN\')'));
} else {
$propertyMetadataFactoryProphecy->create(SecuredDummy::class, 'title', [])->willReturn((new ApiProperty())->withNativeType(Type::string())->withDescription('')->withReadable(false)->withWritable(true));
$propertyMetadataFactoryProphecy->create(SecuredDummy::class, 'adminOnlyProperty', [])->willReturn((new ApiProperty())->withNativeType(Type::string())->withDescription('')->withReadable(true)->withSecurityPostDenormalize('is_granted(\'ROLE_ADMIN\')'));
}

$iriConverterProphecy = $this->prophesize(IriConverterInterface::class);

$propertyAccessorProphecy = $this->prophesize(PropertyAccessorInterface::class);

$resourceClassResolverProphecy = $this->prophesize(ResourceClassResolverInterface::class);
$resourceClassResolverProphecy->getResourceClass(null, SecuredDummy::class)->willReturn(SecuredDummy::class);
$resourceClassResolverProphecy->isResourceClass(SecuredDummy::class)->willReturn(true);

$serializerProphecy = $this->prophesize(SerializerInterface::class);
$serializerProphecy->willImplement(NormalizerInterface::class);

$resourceAccessChecker = $this->prophesize(ResourceAccessCheckerInterface::class);
$resourceAccessChecker->isGranted(
SecuredDummy::class,
'is_granted(\'ROLE_ADMIN\')',
Argument::that(function (array $context) {
return \array_key_exists('property', $context)
&& \array_key_exists('object', $context)
&& \array_key_exists('previous_object', $context)
&& 'adminOnlyProperty' === $context['property']
&& null === $context['previous_object']
&& $context['object'] instanceof SecuredDummy;
})
)->willReturn(false);

$normalizer = new class($propertyNameCollectionFactoryProphecy->reveal(), $propertyMetadataFactoryProphecy->reveal(), $iriConverterProphecy->reveal(), $resourceClassResolverProphecy->reveal(), $propertyAccessorProphecy->reveal(), null, null, [], null, $resourceAccessChecker->reveal()) extends AbstractItemNormalizer {};
$normalizer->setSerializer($serializerProphecy->reveal());

$this->expectException(AccessDeniedException::class);
$this->expectExceptionMessage('Custom access denied message');

$operation = new Patch(securityMessage: 'Custom access denied message', extraProperties: ['throw_on_access_denied' => true]);

$normalizer->denormalize($data, SecuredDummy::class, 'json', [
'operation' => $operation,
]);
}

public function testDenormalizeWithSecuredPropertyAndThrowOnAccessDeniedExtraPropertyInOperationThrowsAccessDeniedException(): void
{
$data = [
'title' => 'foo',
'adminOnlyProperty' => 'secret',
];
$propertyNameCollectionFactoryProphecy = $this->prophesize(PropertyNameCollectionFactoryInterface::class);
$propertyNameCollectionFactoryProphecy->create(SecuredDummy::class, [])->willReturn(new PropertyNameCollection(['title', 'adminOnlyProperty']));

$propertyMetadataFactoryProphecy = $this->prophesize(PropertyMetadataFactoryInterface::class);

if (!method_exists(PropertyInfoExtractor::class, 'getType')) {
$propertyMetadataFactoryProphecy->create(SecuredDummy::class, 'title', [])->willReturn((new ApiProperty())->withBuiltinTypes([new LegacyType(LegacyType::BUILTIN_TYPE_STRING)])->withDescription('')->withReadable(false)->withWritable(true));
$propertyMetadataFactoryProphecy->create(SecuredDummy::class, 'adminOnlyProperty', [])->willReturn((new ApiProperty())->withBuiltinTypes([new LegacyType(LegacyType::BUILTIN_TYPE_STRING)])->withDescription('')->withReadable(true)->withSecurityPostDenormalize('is_granted(\'ROLE_ADMIN\')'));
} else {
$propertyMetadataFactoryProphecy->create(SecuredDummy::class, 'title', [])->willReturn((new ApiProperty())->withNativeType(Type::string())->withDescription('')->withReadable(false)->withWritable(true));
$propertyMetadataFactoryProphecy->create(SecuredDummy::class, 'adminOnlyProperty', [])->willReturn((new ApiProperty())->withNativeType(Type::string())->withDescription('')->withReadable(true)->withSecurityPostDenormalize('is_granted(\'ROLE_ADMIN\')'));
}

$iriConverterProphecy = $this->prophesize(IriConverterInterface::class);

$propertyAccessorProphecy = $this->prophesize(PropertyAccessorInterface::class);

$resourceClassResolverProphecy = $this->prophesize(ResourceClassResolverInterface::class);
$resourceClassResolverProphecy->getResourceClass(null, SecuredDummy::class)->willReturn(SecuredDummy::class);
$resourceClassResolverProphecy->isResourceClass(SecuredDummy::class)->willReturn(true);

$serializerProphecy = $this->prophesize(SerializerInterface::class);
$serializerProphecy->willImplement(NormalizerInterface::class);

$resourceAccessChecker = $this->prophesize(ResourceAccessCheckerInterface::class);
$resourceAccessChecker->isGranted(
SecuredDummy::class,
'is_granted(\'ROLE_ADMIN\')',
Argument::that(function (array $context) {
return \array_key_exists('property', $context)
&& \array_key_exists('object', $context)
&& \array_key_exists('previous_object', $context)
&& 'adminOnlyProperty' === $context['property']
&& null === $context['previous_object']
&& $context['object'] instanceof SecuredDummy;
})
)->willReturn(false);

$normalizer = new class($propertyNameCollectionFactoryProphecy->reveal(), $propertyMetadataFactoryProphecy->reveal(), $iriConverterProphecy->reveal(), $resourceClassResolverProphecy->reveal(), $propertyAccessorProphecy->reveal(), null, null, [], null, $resourceAccessChecker->reveal()) extends AbstractItemNormalizer {};
$normalizer->setSerializer($serializerProphecy->reveal());

$this->expectException(AccessDeniedException::class);
$this->expectExceptionMessage('Access denied');

$operation = new Patch(extraProperties: ['throw_on_access_denied' => true]);

$normalizer->denormalize($data, SecuredDummy::class, 'json', [
'operation' => $operation,
]);
}

public function testDenormalizeWithSecuredProperty(): void
{
$data = [
Expand Down
1 change: 1 addition & 0 deletions src/Serializer/Tests/ItemNormalizerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -323,6 +323,7 @@ public function testDenormalizeWithWrongId(): void
$propertyMetadata = (new ApiProperty())->withReadable(true)->withWritable(true);
$propertyMetadataFactoryProphecy = $this->prophesize(PropertyMetadataFactoryInterface::class);
$propertyMetadataFactoryProphecy->create(Dummy::class, 'name', [])->willReturn($propertyMetadata)->shouldBeCalled();
$propertyMetadataFactoryProphecy->create(Dummy::class, 'id', [])->willReturn($propertyMetadata)->shouldBeCalled();

$iriConverterProphecy = $this->prophesize(IriConverterInterface::class);
$iriConverterProphecy->getResourceFromIri('fail', $context + ['fetch_data' => true])->willThrow(new InvalidArgumentException());
Expand Down
Loading