Skip to content
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

Adds csp nonce support for TagRenderer class #88

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
18 changes: 18 additions & 0 deletions src/Asset/NonceNullProvider.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
<?php
declare(strict_types=1);

namespace Symfony\WebpackEncoreBundle\Asset;


use Symfony\WebpackEncoreBundle\Asset\NonceProviderInterface;

final class NonceNullProvider implements NonceProviderInterface
{
/**
* @inheritDoc
*/
public function getNonceValue(): string
{
return '';
}
}
22 changes: 22 additions & 0 deletions src/Asset/NonceProviderInterface.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
<?php

/*
* This file is part of the Symfony WebpackEncoreBundle package.
* (c) Fabien Potencier <fabien@symfony.com>
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\WebpackEncoreBundle\Asset;



interface NonceProviderInterface
{
/**
* Returns a nonce attribute value
*
* @return string
*/
public function getNonceValue(): string;
}
19 changes: 14 additions & 5 deletions src/Asset/TagRenderer.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@
*/
class TagRenderer implements ResetInterface
{
private const NONCE_ATTRIBUTE_NAME = 'nonce';

private $entrypointLookupCollection;

private $packages;
Expand All @@ -26,10 +28,13 @@ class TagRenderer implements ResetInterface

private $renderedFiles = [];

private $nonceProvider;

public function __construct(
$entrypointLookupCollection,
Packages $packages,
array $defaultAttributes = []
array $defaultAttributes = [],
NonceProviderInterface $nonceProvider = null
) {
if ($entrypointLookupCollection instanceof EntrypointLookupInterface) {
@trigger_error(sprintf('The "$entrypointLookupCollection" argument in method "%s()" must be an instance of EntrypointLookupCollection.', __METHOD__), E_USER_DEPRECATED);
Expand All @@ -47,7 +52,7 @@ public function __construct(

$this->packages = $packages;
$this->defaultAttributes = $defaultAttributes;

$this->nonceProvider = $nonceProvider;
$this->reset();
}

Expand All @@ -67,7 +72,7 @@ public function renderWebpackScriptTags(string $entryName, string $packageName =

$scriptTags[] = sprintf(
'<script %s></script>',
$this->convertArrayToAttributes($attributes)
$this->convertArrayToAttributes($attributes,'script')
);

$this->renderedFiles['scripts'][] = $attributes['src'];
Expand All @@ -93,7 +98,7 @@ public function renderWebpackLinkTags(string $entryName, string $packageName = n

$scriptTags[] = sprintf(
'<link %s>',
$this->convertArrayToAttributes($attributes)
$this->convertArrayToAttributes($attributes,'link')
);

$this->renderedFiles['styles'][] = $attributes['href'];
Expand Down Expand Up @@ -142,8 +147,12 @@ private function getEntrypointLookup(string $buildName): EntrypointLookupInterfa
return $this->entrypointLookupCollection->getEntrypointLookup($buildName);
}

private function convertArrayToAttributes(array $attributesMap): string
private function convertArrayToAttributes(array $attributesMap,string $targetTag=''): string
{
if (\in_array($targetTag,['script','style'],true) && null !== $this->nonceProvider && $this->nonceProvider->getNonceValue() != '') {
$attributesMap = array_merge([self::NONCE_ATTRIBUTE_NAME => $this->nonceProvider->getNonceValue()], $attributesMap);
}

return implode(' ', array_map(
function ($key, $value) {
return sprintf('%s="%s"', $key, htmlentities($value));
Expand Down
8 changes: 8 additions & 0 deletions src/DependencyInjection/Configuration.php
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,14 @@ public function getConfigTreeBuilder()
->info('Enable caching of the entry point file(s)')
->defaultFalse()
->end()
->booleanNode('nonce_enable')
->info('Enable attrbute in script and style tag')
->defaultFalse()
->end()
->scalarNode('nonce_provider')
->info('Nonce provider class')
->defaultNull()
->end()
->booleanNode('strict_mode')
->info('Throw an exception if the entrypoints.json file is missing or an entry is missing from the data')
->defaultTrue()
Expand Down
17 changes: 17 additions & 0 deletions src/DependencyInjection/WebpackEncoreExtension.php
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,8 @@ public function load(array $configs, ContainerBuilder $container)

$container->getDefinition('webpack_encore.tag_renderer')
->replaceArgument(2, $defaultAttributes);



if ($config['preload']) {
if (!class_exists(AddLinkHeaderListener::class)) {
Expand All @@ -77,6 +79,21 @@ public function load(array $configs, ContainerBuilder $container)
} else {
$container->removeDefinition('webpack_encore.preload_assets_event_listener');
}

if (false !== $config['nonce_enable']) {

if (empty($config['nonce_provider'])) {
throw new \LogicException('If nonce_enable it is true must be provide nonce_provider service class');
}

$serviceId = $config['nonce_provider'];
$serviceNonceProvider = new Reference($serviceId);

$container->getDefinition('webpack_encore.tag_renderer')
->replaceArgument(3, $serviceNonceProvider);

}

}

private function entrypointFactory(ContainerBuilder $container, string $name, string $path, bool $cacheEnabled, bool $strictMode): Reference
Expand Down
3 changes: 3 additions & 0 deletions src/Resources/config/services.xml
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,14 @@

<service id="Symfony\WebpackEncoreBundle\Asset\EntrypointLookupCollectionInterface" alias="webpack_encore.entrypoint_lookup_collection" />

<service id="webpack_encore.asset.nonce_provider" class="Symfony\WebpackEncoreBundle\Asset\NonceNullProvider" />

<service id="webpack_encore.tag_renderer" class="Symfony\WebpackEncoreBundle\Asset\TagRenderer">
<tag name="kernel.reset" method="reset" />
<argument type="service" id="webpack_encore.entrypoint_lookup_collection" />
<argument type="service" id="assets.packages" />
<argument type="collection" />
<argument type="service" id="webpack_encore.asset.nonce_provider" />
</service>

<service id="webpack_encore.twig_entry_files_extension" class="Symfony\WebpackEncoreBundle\Twig\EntryFilesTwigExtension">
Expand Down
131 changes: 99 additions & 32 deletions tests/Asset/TagRendererTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,32 +14,17 @@
use Symfony\WebpackEncoreBundle\Asset\EntrypointLookupCollection;
use Symfony\WebpackEncoreBundle\Asset\EntrypointLookupInterface;
use Symfony\WebpackEncoreBundle\Asset\IntegrityDataProviderInterface;
use Symfony\WebpackEncoreBundle\Asset\NonceNullProvider;
use Symfony\WebpackEncoreBundle\Asset\NonceProviderInterface;
use Symfony\WebpackEncoreBundle\Asset\TagRenderer;

class TagRendererTest extends TestCase
{
public function testRenderScriptTagsWithDefaultAttributes()
{
$entrypointLookup = $this->createMock(EntrypointLookupInterface::class);
$entrypointLookup->expects($this->once())
->method('getJavaScriptFiles')
->willReturn(['/build/file1.js', '/build/file2.js']);
$entrypointCollection = $this->createMock(EntrypointLookupCollection::class);
$entrypointCollection->expects($this->once())
->method('getEntrypointLookup')
->withConsecutive(['_default'])
->will($this->onConsecutiveCalls($entrypointLookup));
$entrypointCollection = $this->getMockEntryPointLookup();

$packages = $this->createMock(Packages::class);
$packages->expects($this->exactly(2))
->method('getUrl')
->withConsecutive(
['/build/file1.js', 'custom_package'],
['/build/file2.js', 'custom_package']
)
->willReturnCallback(function ($path) {
return 'http://localhost:8080'.$path;
});
$packages = $this->getMockPackges();
$renderer = new TagRenderer($entrypointCollection, $packages, []);

$output = $renderer->renderWebpackScriptTags('my_entry', 'custom_package');
Expand Down Expand Up @@ -69,7 +54,7 @@ public function testRenderScriptTagsWithBadFilename()
$packages->expects($this->once())
->method('getUrl')
->willReturnCallback(function ($path) {
return 'http://localhost:8080'.$path;
return 'http://localhost:8080' . $path;
});
$renderer = new TagRenderer($entrypointCollection, $packages, ['crossorigin' => 'anonymous']);

Expand Down Expand Up @@ -115,7 +100,7 @@ public function testRenderScriptTagsWithinAnEntryPointCollection()
['/build/file3.js', 'specific_package']
)
->willReturnCallback(function ($path) {
return 'http://localhost:8080'.$path;
return 'http://localhost:8080' . $path;
});
$renderer = new TagRenderer($entrypointCollection, $packages, ['crossorigin' => 'anonymous']);

Expand Down Expand Up @@ -157,16 +142,7 @@ public function testRenderScriptTagsWithHashes()
->withConsecutive(['_default'])
->will($this->onConsecutiveCalls($entrypointLookup));

$packages = $this->createMock(Packages::class);
$packages->expects($this->exactly(2))
->method('getUrl')
->withConsecutive(
['/build/file1.js', 'custom_package'],
['/build/file2.js', 'custom_package']
)
->willReturnCallback(function ($path) {
return 'http://localhost:8080'.$path;
});
$packages = $this->getMockPackges();
$renderer = new TagRenderer($entrypointCollection, $packages, ['crossorigin' => 'anonymous']);

$output = $renderer->renderWebpackScriptTags('my_entry', 'custom_package');
Expand Down Expand Up @@ -198,7 +174,7 @@ public function testGetRenderedFilesAndReset()
$packages->expects($this->any())
->method('getUrl')
->willReturnCallback(function ($path) {
return 'http://localhost:8080'.$path;
return 'http://localhost:8080' . $path;
});
$renderer = new TagRenderer($entrypointCollection, $packages);

Expand All @@ -211,4 +187,95 @@ public function testGetRenderedFilesAndReset()
$this->assertEmpty($renderer->getRenderedScripts());
$this->assertEmpty($renderer->getRenderedStyles());
}

/**
* @dataProvider nonceProvider()
*/
public function testRenderScriptWithNonceNullNonce($nonceProvider): void
{
$entrypointCollection = $this->getMockEntryPointLookup();

$packages = $this->getMockPackges();

$renderer = new TagRenderer($entrypointCollection, $packages, [], $nonceProvider);

$output = $renderer->renderWebpackScriptTags('my_entry', 'custom_package');
$this->assertStringContainsString(
'<script src="http://localhost:8080/build/file1.js"></script>',
$output
);

$this->assertStringContainsString(
'<script src="http://localhost:8080/build/file2.js"></script>',
$output
);

}

public function testRenderScriptWithCustomNonce(): void
{
$entrypointCollection = $this->getMockEntryPointLookup();

$packages = $this->getMockPackges();

$customNonce = (new class implements NonceProviderInterface {
/**
* @inheritDoc
*/
public function getNonceValue(): string
{
return '123456-nonce';
}
});

$renderer = new TagRenderer($entrypointCollection, $packages, [], $customNonce);

$output = $renderer->renderWebpackScriptTags('my_entry', 'custom_package');
$this->assertStringContainsString(
'<script nonce="123456-nonce" src="http://localhost:8080/build/file1.js"></script>',
$output
);

$this->assertStringContainsString(
'<script nonce="123456-nonce" src="http://localhost:8080/build/file2.js"></script>',
$output
);

}


private function getMockEntryPointLookup()
{
$entrypointLookup = $this->createMock(EntrypointLookupInterface::class);
$entrypointLookup->expects($this->once())
->method('getJavaScriptFiles')
->willReturn(['/build/file1.js', '/build/file2.js']);
$entrypointCollection = $this->createMock(EntrypointLookupCollection::class);
$entrypointCollection->expects($this->once())
->method('getEntrypointLookup')
->withConsecutive(['_default'])
->will($this->onConsecutiveCalls($entrypointLookup));
return $entrypointCollection;
}

private function getMockPackges()
{
$packages = $this->createMock(Packages::class);
$packages->expects($this->exactly(2))
->method('getUrl')
->withConsecutive(
['/build/file1.js', 'custom_package'],
['/build/file2.js', 'custom_package']
)
->willReturnCallback(function ($path) {
return 'http://localhost:8080' . $path;
});
return $packages;
}

public function nonceProvider(): \Generator
{
yield [ new NonceNullProvider()];
yield [ null ];
}
}