CVE-2023-25575: Incorrect Authorization (CWE-863)
value: API Platform Core is the server component of API Platform: hypermedia and GraphQL APIs. Resource properties secured with the `security` option of the `ApiPlatform\Metadata\ApiProperty` attribute can be disclosed to unauthorized users. The problem affects most serialization formats, including raw JSON, which is enabled by default when installing API Platform. Custom serialization formats may also be impacted. Only collection endpoints are affected by the issue, item endpoints are not. The JSON-LD format is not affected by the issue. The result of the security rule is only executed for the first item of the collection. The result of the rule is then cached and reused for the next items. This bug can leak data to unauthorized users when the rule depends on the value of a property of the item. This bug can also hide properties that should be displayed to authorized users. This issue impacts the 2.7, 3.0 and 3.1 branches. Please upgrade to versions 2.7.10, 3.0.12 or 3.1.3. As a workaround, replace the `cache_key` of the context array of the Serializer inside a custom normalizer that works on objects if the security option of the `ApiPlatform\Metadata\ApiProperty` attribute is used.
CWE description: The product performs an authorization check when an actor attempts to access a resource or perform an action, but it does not correctly perform the check. This allows attackers to bypass intended access restrictions.
CVSS v3 base score: 6.5
Published: 2023-02-28T23:15Z
Repository: https://github.com/api-platform/core
Language: PHP
Files changed: features/authorization/deny.feature, src/Hal/Serializer/ItemNormalizer.php, src/JsonApi/Serializer/ItemNormalizer.php, src/Serializer/AbstractItemNormalizer.php, src/Serializer/CacheKeyTrait.php
Commit date: 2023-02-27 15:37:39 +0100
Commit message: Merge pull request from GHSA-vr2x-7687-h6qv


Diff: diff --git a/features/authorization/deny.feature b/features/authorization/deny.feature
index d6c4e540a..78456f677 100644
--- a/features/authorization/deny.feature
+++ b/features/authorization/deny.feature
@@ -179,5 +179,27 @@ Feature: Authorization checking
     }
     """
     Then the response status code should be 200
     And the response should contain "ownerOnlyProperty"
     And the JSON node "ownerOnlyProperty" should be equal to the string "updated"
+
+  Scenario: A user retrieves a resource with an admin only viewable property
+    When I add "Accept" header equal to "application/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 contain "ownerOnlyProperty"
+
+  Scenario: A user retrieves a resource with an admin only viewable property
+    When I add "Accept" header equal to "application/hal+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 contain "ownerOnlyProperty"
+
+  Scenario: A user retrieves a resource with an admin only viewable property
+    Given I add "Accept" header equal to "application/vnd.api+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 contain "ownerOnlyProperty"
+
diff --git a/src/Hal/Serializer/ItemNormalizer.php b/src/Hal/Serializer/ItemNormalizer.php
index 551adbed3..4d8317bc6 100644
--- a/src/Hal/Serializer/ItemNormalizer.php
+++ b/src/Hal/Serializer/ItemNormalizer.php
@@ -60,23 +60,23 @@ final class ItemNormalizer extends AbstractItemNormalizer
         $resourceClass = $this->getObjectClass($object);
         if ($this->getOutputClass($resourceClass, $context)) {
             return parent::normalize($object, $format, $context);
         }
 
-        if (!isset($context['cache_key'])) {
-            $context['cache_key'] = $this->getCacheKey($format, $context);
-        }
-
         if ($this->resourceClassResolver->isResourceClass($resourceClass)) {
             $resourceClass = $this->resourceClassResolver->getResourceClass($object, $context['resource_class'] ?? null);
         }
 
         $context = $this->initContext($resourceClass, $context);
         $iri = $this->iriConverter instanceof LegacyIriConverterInterface ? $this->iriConverter->getIriFromItem($object) : $this->iriConverter->getIriFromResource($object, UrlGeneratorInterface::ABS_PATH, $context['operation'] ?? null, $context);
         $context['iri'] = $iri;
         $context['api_normalize'] = true;
 
+        if (!isset($context['cache_key'])) {
+            $context['cache_key'] = $this->getCacheKey($format, $context);
+        }
+
         $data = parent::normalize($object, $format, $context);
         if (!\is_array($data)) {
             return $data;
         }
 
diff --git a/src/JsonApi/Serializer/ItemNormalizer.php b/src/JsonApi/Serializer/ItemNormalizer.php
index 024c9f3a9..da3f51998 100644
--- a/src/JsonApi/Serializer/ItemNormalizer.php
+++ b/src/JsonApi/Serializer/ItemNormalizer.php
@@ -76,23 +76,23 @@ final class ItemNormalizer extends AbstractItemNormalizer
         $resourceClass = $this->getObjectClass($object);
         if ($this->getOutputClass($resourceClass, $context)) {
             return parent::normalize($object, $format, $context);
         }
 
-        if (!isset($context['cache_key'])) {
-            $context['cache_key'] = $this->getCacheKey($format, $context);
-        }
-
-        if ($isResourceClass = $this->resourceClassResolver->isResourceClass($resourceClass)) {
+        if ($this->resourceClassResolver->isResourceClass($resourceClass)) {
             $resourceClass = $this->resourceClassResolver->getResourceClass($object, $context['resource_class'] ?? null);
         }
 
         $context = $this->initContext($resourceClass, $context);
         $iri = $this->iriConverter instanceof LegacyIriConverterInterface ? $this->iriConverter->getIriFromItem($object) : $this->iriConverter->getIriFromResource($object, UrlGeneratorInterface::ABS_PATH, $context['operation'] ?? null, $context);
         $context['iri'] = $iri;
         $context['api_normalize'] = true;
 
+        if (!isset($context['cache_key'])) {
+            $context['cache_key'] = $this->getCacheKey($format, $context);
+        }
+
         $data = parent::normalize($object, $format, $context);
         if (!\is_array($data)) {
             return $data;
         }
 
diff --git a/src/Serializer/AbstractItemNormalizer.php b/src/Serializer/AbstractItemNormalizer.php
index af3904c47..28ede27fc 100644
--- a/src/Serializer/AbstractItemNormalizer.php
+++ b/src/Serializer/AbstractItemNormalizer.php
@@ -25,10 +25,11 @@ use ApiPlatform\Core\Metadata\Property\PropertyMetadata;
 use ApiPlatform\Core\Metadata\Resource\Factory\ResourceMetadataFactoryInterface;
 use ApiPlatform\Exception\InvalidArgumentException;
 use ApiPlatform\Exception\InvalidValueException;
 use ApiPlatform\Exception\ItemNotFoundException;
 use ApiPlatform\Metadata\ApiProperty;
+use ApiPlatform\Metadata\CollectionOperationInterface;
 use ApiPlatform\Metadata\Property\Factory\PropertyMetadataFactoryInterface;
 use ApiPlatform\Metadata\Property\Factory\PropertyNameCollectionFactoryInterface;
 use ApiPlatform\Metadata\Resource\Factory\ResourceMetadataCollectionFactoryInterface;
 use ApiPlatform\Symfony\Security\ResourceAccessCheckerInterface;
 use ApiPlatform\Util\ClassInfoTrait;
@@ -205,10 +206,15 @@ abstract class AbstractItemNormalizer extends AbstractObjectNormalizer
 
         if ($isResourceClass = $this->resourceClassResolver->isResourceClass($resourceClass)) {
             $context = $this->initContext($resourceClass, $context);
         }
 
+        if (isset($context['operation']) && $context['operation'] instanceof CollectionOperationInterface) {
+            unset($context['operation']);
+            unset($context['iri']);
+        }
+
         $iri = null;
         if (isset($context['iri'])) {
             $iri = $context['iri'];
         } elseif ($this->iriConverter instanceof LegacyIriConverterInterface && $isResourceClass) {
             $iri = $this->iriConverter->getIriFromItem($object);
diff --git a/src/Serializer/CacheKeyTrait.php b/src/Serializer/CacheKeyTrait.php
index 56c9823c6..54ed02d17 100644
--- a/src/Serializer/CacheKeyTrait.php
+++ b/src/Serializer/CacheKeyTrait.php
@@ -11,10 +11,16 @@
 
 declare(strict_types=1);
 
 namespace ApiPlatform\Serializer;
 
+/**
+ * Used to override Symfony\Component\Serializer\Normalizer\AbstractObjectNormalizer::getCacheKey which is private
+ * We need the cache_key in JsonApi and Hal before it is computed in Symfony.
+ *
+ * @see https://github.com/symfony/symfony/blob/49b6ab853d81e941736a1af67845efa3401e7278/src/Symfony/Component/Serializer/Normalizer/AbstractObjectNormalizer.php#L723 which isn't protected
+ */
 trait CacheKeyTrait
 {
     /**
      * @return string|bool
      */
@@ -22,15 +28,19 @@ trait CacheKeyTrait
     {
         foreach ($context[self::EXCLUDE_FROM_CACHE_KEY] ?? $this->defaultContext[self::EXCLUDE_FROM_CACHE_KEY] as $key) {
             unset($context[$key]);
         }
         unset($context[self::EXCLUDE_FROM_CACHE_KEY]);
+        unset($context[self::OBJECT_TO_POPULATE]);
         unset($context['cache_key']); // avoid artificially different keys
 
         try {
-            return md5($format.serialize($context));
-        } catch (\Exception $exception) {
+            return hash('xxh128', $format.serialize([
+                'context' => $context,
+                'ignored' => $context[self::IGNORED_ATTRIBUTES] ?? $this->defaultContext[self::IGNORED_ATTRIBUTES],
+            ]));
+        } catch (\Exception) {
             // The context cannot be serialized, skip the cache
             return false;
         }
     }
 }

Vulnerable code:         if (!isset($context['cache_key'])) {
            $context['cache_key'] = $this->getCacheKey($format, $context);
        }

        if (!isset($context['cache_key'])) {
            $context['cache_key'] = $this->getCacheKey($format, $context);
        }

        if ($isResourceClass = $this->resourceClassResolver->isResourceClass($resourceClass)) {
            return md5($format.serialize($context));
        } catch (\Exception $exception) {
Fixed code: 
  Scenario: A user retrieves a resource with an admin only viewable property
    When I add "Accept" header equal to "application/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 contain "ownerOnlyProperty"

  Scenario: A user retrieves a resource with an admin only viewable property
    When I add "Accept" header equal to "application/hal+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 contain "ownerOnlyProperty"

  Scenario: A user retrieves a resource with an admin only viewable property
    Given I add "Accept" header equal to "application/vnd.api+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 contain "ownerOnlyProperty"

        if (!isset($context['cache_key'])) {
            $context['cache_key'] = $this->getCacheKey($format, $context);
        }

        if ($this->resourceClassResolver->isResourceClass($resourceClass)) {
        if (!isset($context['cache_key'])) {
            $context['cache_key'] = $this->getCacheKey($format, $context);
        }

use ApiPlatform\Metadata\CollectionOperationInterface;
        if (isset($context['operation']) && $context['operation'] instanceof CollectionOperationInterface) {
            unset($context['operation']);
            unset($context['iri']);
        }

/**
 * Used to override Symfony\Component\Serializer\Normalizer\AbstractObjectNormalizer::getCacheKey which is private
 * We need the cache_key in JsonApi and Hal before it is computed in Symfony.
 *
 * @see https://github.com/symfony/symfony/blob/49b6ab853d81e941736a1af67845efa3401e7278/src/Symfony/Component/Serializer/Normalizer/AbstractObjectNormalizer.php#L723 which isn't protected
 */
        unset($context[self::OBJECT_TO_POPULATE]);
            return hash('xxh128', $format.serialize([
                'context' => $context,
                'ignored' => $context[self::IGNORED_ATTRIBUTES] ?? $this->defaultContext[self::IGNORED_ATTRIBUTES],
            ]));
        } catch (\Exception) {