Skip to content

Prevent cloning generator when instanciating previous_data #2990

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 1 commit into from
Aug 19, 2019
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
6 changes: 6 additions & 0 deletions features/authorization/deny.feature
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,12 @@ Feature: Authorization checking
Then the response status code should be 200
And the response should be in JSON

Scenario: Data provider that's return generator has null previous object
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 "/custom_data_provider_generator"
Then the response status code should be 200

Scenario: A standard user cannot create a secured resource
When I add "Accept" header equal to "application/ld+json"
And I add "Content-Type" header equal to "application/ld+json"
Expand Down
4 changes: 3 additions & 1 deletion src/EventListener/ReadListener.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
use ApiPlatform\Core\Metadata\Resource\Factory\ResourceMetadataFactoryInterface;
use ApiPlatform\Core\Metadata\Resource\ToggleableOperationAttributeTrait;
use ApiPlatform\Core\Serializer\SerializerContextBuilderInterface;
use ApiPlatform\Core\Util\CloneTrait;
use ApiPlatform\Core\Util\RequestAttributesExtractor;
use ApiPlatform\Core\Util\RequestParser;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
Expand All @@ -35,6 +36,7 @@
*/
final class ReadListener
{
use CloneTrait;
use OperationDataProviderTrait;
use ToggleableOperationAttributeTrait;

Expand Down Expand Up @@ -115,6 +117,6 @@ public function onKernelRequest(GetResponseEvent $event): void
}

$request->attributes->set('data', $data);
$request->attributes->set('previous_data', \is_object($data) ? clone $data : $data);
$request->attributes->set('previous_data', $this->clone($data));
}
}
4 changes: 3 additions & 1 deletion src/GraphQl/Resolver/Factory/CollectionResolverFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
use ApiPlatform\Core\GraphQl\Serializer\ItemNormalizer;
use ApiPlatform\Core\Metadata\Resource\Factory\ResourceMetadataFactoryInterface;
use ApiPlatform\Core\Security\ResourceAccessCheckerInterface;
use ApiPlatform\Core\Util\CloneTrait;
use GraphQL\Error\Error;
use GraphQL\Type\Definition\ResolveInfo;
use Symfony\Component\HttpFoundation\RequestStack;
Expand All @@ -38,6 +39,7 @@
*/
final class CollectionResolverFactory implements ResolverFactoryInterface
{
use CloneTrait;
use FieldsToAttributesTrait;
use ResourceAccessCheckerTrait;

Expand Down Expand Up @@ -97,7 +99,7 @@ public function __invoke(string $resourceClass = null, string $rootClass = null,

$this->canAccess($this->resourceAccessChecker, $resourceMetadata, $resourceClass, $info, [
'object' => $collection,
'previous_object' => \is_object($collection) ? clone $collection : $collection,
'previous_object' => $this->clone($collection),
], $operationName ?? 'query');

if (!$this->paginationEnabled) {
Expand Down
4 changes: 3 additions & 1 deletion src/GraphQl/Resolver/Factory/ItemMutationResolverFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
use ApiPlatform\Core\Metadata\Resource\ResourceMetadata;
use ApiPlatform\Core\Security\ResourceAccessCheckerInterface;
use ApiPlatform\Core\Util\ClassInfoTrait;
use ApiPlatform\Core\Util\CloneTrait;
use ApiPlatform\Core\Validator\Exception\ValidationException;
use ApiPlatform\Core\Validator\ValidatorInterface;
use GraphQL\Error\Error;
Expand All @@ -41,6 +42,7 @@
final class ItemMutationResolverFactory implements ResolverFactoryInterface
{
use ClassInfoTrait;
use CloneTrait;
use FieldsToAttributesTrait;
use ResourceAccessCheckerTrait;

Expand Down Expand Up @@ -96,7 +98,7 @@ public function __invoke(string $resourceClass = null, string $rootClass = null,
throw Error::createLocatedError(sprintf('Item "%s" did not match expected type "%s".', $args['input']['id'], $resourceMetadata->getShortName()), $info->fieldNodes, $info->path);
}
}
$previousItem = \is_object($item) ? clone $item : $item;
$previousItem = $this->clone($item);

$inputMetadata = $resourceMetadata->getGraphqlAttribute($operationName, 'input', null, true);
$inputClass = null;
Expand Down
37 changes: 37 additions & 0 deletions src/Util/CloneTrait.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
<?php

/*
* This file is part of the API Platform project.
*
* (c) Kévin Dunglas <dunglas@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

declare(strict_types=1);

namespace ApiPlatform\Core\Util;

/**
* Clones given data if cloneable.
*
* @internal
*
* @author Quentin Barloy <quentin.barloy@gmail.com>
*/
trait CloneTrait
{
public function clone($data)
{
if (!\is_object($data)) {
return $data;
}

try {
return (new \ReflectionClass($data))->isCloneable() ? clone $data : null;
} catch (\ReflectionException $reflectionException) {
return null;
}
}
}
33 changes: 33 additions & 0 deletions tests/Fixtures/TestBundle/DataProvider/GeneratorDataProvider.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
<?php

/*
* This file is part of the API Platform project.
*
* (c) Kévin Dunglas <dunglas@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

declare(strict_types=1);

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

use ApiPlatform\Core\DataProvider\CollectionDataProviderInterface;
use ApiPlatform\Core\DataProvider\RestrictedDataProviderInterface;
use ApiPlatform\Core\Tests\Fixtures\TestBundle\Entity\SecuredDummy;

class GeneratorDataProvider implements CollectionDataProviderInterface, RestrictedDataProviderInterface
{
public function supports(string $resourceClass, string $operationName = null, array $context = []): bool
{
return SecuredDummy::class === $resourceClass && 'get_from_data_provider_generator' === $operationName;
}

public function getCollection(string $resourceClass, string $operationName = null)
{
yield from [new class() {
}, new class() {
}];
}
}
5 changes: 5 additions & 0 deletions tests/Fixtures/TestBundle/Document/SecuredDummy.php
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,11 @@
* attributes={"access_control"="is_granted('ROLE_USER')"},
* collectionOperations={
* "get",
* "get_from_data_provider_generator"={
* "method"="GET",
* "path"="custom_data_provider_generator",
* "access_control"="is_granted('ROLE_USER')"
* },
* "post"={"access_control"="is_granted('ROLE_ADMIN')"}
* },
* itemOperations={
Expand Down
5 changes: 5 additions & 0 deletions tests/Fixtures/TestBundle/Entity/SecuredDummy.php
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,11 @@
* attributes={"access_control"="is_granted('ROLE_USER')"},
* collectionOperations={
* "get",
* "get_from_data_provider_generator"={
* "method"="GET",
* "path"="custom_data_provider_generator",
* "access_control"="is_granted('ROLE_USER')"
* },
* "post"={"access_control"="is_granted('ROLE_ADMIN')"}
* },
* itemOperations={
Expand Down
5 changes: 5 additions & 0 deletions tests/Fixtures/app/config/config_test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,11 @@ services:
arguments: [ { 'name': 'ipartial', 'description': 'ipartial' } ]
tags: [ { name: 'api_platform.filter', id: 'related_to_dummy_friend.name' } ]

ApiPlatform\Core\Tests\Fixtures\TestBundle\DataProvider\GeneratorDataProvider:
public: false
tags:
- name: 'api_platform.item_data_provider'

ApiPlatform\Core\Tests\Fixtures\TestBundle\DataProvider\ProductItemDataProvider:
public: false
arguments:
Expand Down
49 changes: 49 additions & 0 deletions tests/Util/CloneTraitTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
<?php

/*
* This file is part of the API Platform project.
*
* (c) Kévin Dunglas <dunglas@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

declare(strict_types=1);

namespace ApiPlatform\Core\Tests\Util;

use ApiPlatform\Core\Util\CloneTrait;
use PHPUnit\Framework\TestCase;

/**
* @author Quentin Barloy <quentin.barloy@gmail.com>
*/
class CloneTraitTest extends TestCase
{
use CloneTrait;

public function testScalarClone(): void
{
$this->assertSame(5, $this->clone(5));
}

public function testObjectClone(): void
{
$data = new \stdClass();
$result = $this->clone($data);

$this->assertNotSame($data, $result);
$this->assertEquals($data, $result);
}

public function testGeneratorClone(): void
{
$this->assertNull($this->clone($this->generator()));
}

private function generator(): \Generator
{
yield 1;
}
}