Unverified Commit e239d3e3 authored by alexpott's avatar alexpott
Browse files

Issue #3175884 by gabesullice, mglaman, juagarc4: JSON:API link keys can collide

parent 6a910ad4
......@@ -94,7 +94,14 @@ protected function hashByHref(Link $link) {
if (!$this->hashSalt) {
$this->hashSalt = Crypt::randomBytesBase64();
}
return substr(str_replace(['-', '_'], '', Crypt::hashBase64($this->hashSalt . $link->getHref())), 0, 7);
$link_parameters = [
'href' => $link->getHref(),
] + $link->getTargetAttributes();
foreach ($link_parameters as $name => $value) {
$serialized_parameters[] = sprintf('%s="%s"', $name, implode(' ', (array) $value));
}
$b64_hash = Crypt::hashBase64($this->hashSalt . implode('; ', $serialized_parameters));
return substr(str_replace(['-', '_'], '', $b64_hash), 0, 7);
}
}
<?php
namespace Drupal\Tests\jsonapi\Kernel\Normalizer;
use Drupal\Core\Cache\CacheableMetadata;
use Drupal\Core\Url;
use Drupal\jsonapi\JsonApiResource\Link;
use Drupal\jsonapi\JsonApiResource\LinkCollection;
use Drupal\jsonapi\JsonApiResource\ResourceObject;
use Drupal\jsonapi\Normalizer\LinkCollectionNormalizer;
use Drupal\jsonapi\ResourceType\ResourceType;
use Drupal\KernelTests\KernelTestBase;
/**
* @coversDefaultClass \Drupal\jsonapi\Normalizer\LinkCollectionNormalizer
* @group jsonapi
*
* @internal
*/
class LinkCollectionNormalizerTest extends KernelTestBase {
/**
* The subject under test.
*
* @var \Symfony\Component\Serializer\Normalizer\NormalizerInterface
*/
protected $normalizer;
/**
* {@inheritDoc}
*/
protected static $modules = [
'jsonapi',
'serialization',
];
/**
* {@inheritDoc}
*/
protected function setUp(): void {
parent::setUp();
$this->normalizer = new LinkCollectionNormalizer();
$this->normalizer->setSerializer($this->container->get('jsonapi.serializer'));
}
/**
* Tests the link collection normalizer.
*/
public function testNormalize() {
$link_context = new ResourceObject(new CacheableMetadata(), new ResourceType('n/a', 'n/a', 'n/a'), 'n/a', NULL, [], new LinkCollection([]));
$link_collection = (new LinkCollection([]))
->withLink('related', new Link(new CacheableMetadata(), Url::fromUri('http://example.com/post/42'), 'related', ['title' => 'Most viewed']))
->withLink('related', new Link(new CacheableMetadata(), Url::fromUri('http://example.com/post/42'), 'related', ['title' => 'Top rated']))
->withContext($link_context);
$normalized = $this->normalizer->normalize($link_collection)->getNormalization();
$this->assertIsArray($normalized);
foreach (array_keys($normalized) as $key) {
$this->assertStringStartsWith('related', $key);
}
$this->assertSame([
[
'href' => 'http://example.com/post/42',
'meta' => [
'title' => 'Most viewed',
],
],
[
'href' => 'http://example.com/post/42',
'meta' => [
'title' => 'Top rated',
],
],
], array_values($normalized));
}
}
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment