Skip to content

[AssetMapper] Allow adding integrity metadata to importmaps #60378

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

Open
wants to merge 1 commit into
base: 7.4
Choose a base branch
from
Open
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
1 change: 1 addition & 0 deletions src/Symfony/Bundle/FrameworkBundle/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ CHANGELOG
* Allow using their name without added suffix when using `#[Target]` for custom services
* Deprecate `Symfony\Bundle\FrameworkBundle\Console\Application::add()` in favor of `Symfony\Bundle\FrameworkBundle\Console\Application::addCommand()`
* Add `assertEmailAddressNotContains()` to the `MailerAssertionsTrait`
* Add `framework.asset_mapper.importmap_integrity_algorithms` option to add integrity metadata to importmaps

7.3
---
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -864,6 +864,7 @@ private function addAssetMapperSection(ArrayNodeDefinition $rootNode, callable $
->fixXmlConfig('excluded_pattern')
->fixXmlConfig('extension')
->fixXmlConfig('importmap_script_attribute')
->fixXmlConfig('importmap_integrity_algorithm')
->children()
// add array node called "paths" that will be an array of strings
->arrayNode('paths')
Expand Down Expand Up @@ -973,6 +974,12 @@ private function addAssetMapperSection(ArrayNodeDefinition $rootNode, callable $
->end()
->end()
->end()
->arrayNode('importmap_integrity_algorithms')
->info('Array of algorithms used to compute importmap resources integrity. They will all run for every asset.')
->beforeNormalization()->castToArray()->end()
->prototype('scalar')->end()
->defaultValue([])
->end()
->end()
->end()
->end()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1492,6 +1492,7 @@ private function registerAssetMapperConfiguration(array $config, ContainerBuilde
$container
->getDefinition('asset_mapper.mapped_asset_factory')
->replaceArgument(2, $config['vendor_dir'])
->setArgument(3, $config['importmap_integrity_algorithms'])
;

$container
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,7 @@
service('asset_mapper.public_assets_path_resolver'),
service('asset_mapper_compiler'),
abstract_arg('vendor directory'),
abstract_arg('integrity hash algorithms'),
])

->set('asset_mapper.cached_mapped_asset_factory', CachedMappedAssetFactory::class)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -208,6 +208,7 @@
<xsd:element name="extension" type="asset_mapper_extension" minOccurs="0" maxOccurs="unbounded" />
<xsd:element name="importmap-script-attribute" type="asset_mapper_attribute" minOccurs="0" maxOccurs="unbounded" />
<xsd:element name="precompress" type="asset_mapper_precompress" minOccurs="0" maxOccurs="1" />
<xsd:element name="importmap-integrity-algorithm" type="xsd:string" minOccurs="0" maxOccurs="unbounded" />
</xsd:sequence>
<xsd:attribute name="enabled" type="xsd:boolean" />
<xsd:attribute name="exclude-dotfiles" type="xsd:boolean" />
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -148,6 +148,7 @@ public function testAssetMapperCanBeEnabled()
'formats' => [],
'extensions' => interface_exists(CompressorInterface::class) ? CompressorInterface::DEFAULT_EXTENSIONS : [],
],
'importmap_integrity_algorithms' => [],
];

$this->assertEquals($defaultConfig, $config['asset_mapper']);
Expand Down Expand Up @@ -877,6 +878,7 @@ protected static function getBundleDefaultConfig()
'formats' => [],
'extensions' => interface_exists(CompressorInterface::class) ? CompressorInterface::DEFAULT_EXTENSIONS : [],
],
'importmap_integrity_algorithms' => [],
],
'cache' => [
'pools' => [],
Expand Down
5 changes: 5 additions & 0 deletions src/Symfony/Component/AssetMapper/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
CHANGELOG
=========

7.4
---

* Allow adding integrity metadata to importmaps

7.3
---

Expand Down
23 changes: 23 additions & 0 deletions src/Symfony/Component/AssetMapper/Factory/MappedAssetFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@

use Symfony\Component\AssetMapper\AssetMapperCompiler;
use Symfony\Component\AssetMapper\Exception\CircularAssetsException;
use Symfony\Component\AssetMapper\Exception\LogicException;
use Symfony\Component\AssetMapper\Exception\RuntimeException;
use Symfony\Component\AssetMapper\MappedAsset;
use Symfony\Component\AssetMapper\Path\PublicAssetsPathResolverInterface;
Expand All @@ -25,6 +26,7 @@ class MappedAssetFactory implements MappedAssetFactoryInterface
{
private const PREDIGESTED_REGEX = '/-([0-9a-zA-Z]{7,128}\.digested)/';
private const PUBLIC_DIGEST_LENGTH = 7;
private const INTEGRITY_HASH_ALGORITHMS = ['sha256', 'sha384', 'sha512'];

private array $assetsCache = [];
private array $assetsBeingCreated = [];
Expand All @@ -33,7 +35,11 @@ public function __construct(
private readonly PublicAssetsPathResolverInterface $assetsPathResolver,
private readonly AssetMapperCompiler $compiler,
private readonly string $vendorDir,
private readonly array $integrityHashAlgorithms = [],
) {
if ($unsupportedAlgorithms = array_diff($this->integrityHashAlgorithms, self::INTEGRITY_HASH_ALGORITHMS)) {
throw new LogicException(sprintf('Unsupported "%s" algorithm(s). Supported ones are "%s".', implode('", "', $unsupportedAlgorithms), implode('", "', self::INTEGRITY_HASH_ALGORITHMS)));
}
}

public function createMappedAsset(string $logicalPath, string $sourcePath): ?MappedAsset
Expand Down Expand Up @@ -63,6 +69,7 @@ public function createMappedAsset(string $logicalPath, string $sourcePath): ?Map
$asset->getDependencies(),
$asset->getFileDependencies(),
$asset->getJavaScriptImports(),
$this->getIntegrity($asset, $content),
);

$this->assetsCache[$logicalPath] = $asset;
Expand Down Expand Up @@ -131,4 +138,20 @@ private function isVendor(string $sourcePath): bool

return $sourcePath && $vendorDir && str_starts_with($sourcePath, $vendorDir);
}

private function getIntegrity(MappedAsset $asset, ?string $content): ?string
{
$integrity = null;

foreach ($this->integrityHashAlgorithms as $algorithm) {
$hash = null !== $content
? hash($algorithm, $content, true)
: hash_file($algorithm, $asset->sourcePath, true)
;

$integrity .= \sprintf('%s%s-%s', $integrity ? ' ' : '', $algorithm, base64_encode($hash));
}

return $integrity;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ public function getEntrypointNames(): array
/**
* @param string[] $entrypointNames
*
* @return array<string, array{path: string, type: string, preload?: bool}>
* @return array<string, array{path: string, type: string, integrity?: string, preload?: bool}>
*
* @internal
*/
Expand Down Expand Up @@ -83,7 +83,7 @@ public function getImportMapData(array $entrypointNames): array
/**
* @internal
*
* @return array<string, array{path: string, type: string}>
* @return array<string, array{path: string, type: string, integrity?: string}>
*/
public function getRawImportMapData(): array
{
Expand All @@ -104,9 +104,10 @@ public function getRawImportMapData(): array
throw $this->createMissingImportMapAssetException($entry);
}

$path = $asset->publicPath;
$data = ['path' => $path, 'type' => $entry->type->value];
$rawImportMapData[$entry->importName] = $data;
$rawImportMapData[$entry->importName] = ['path' => $asset->publicPath, 'type' => $entry->type->value];
if ($asset->integrity) {
$rawImportMapData[$entry->importName]['integrity'] = $asset->integrity;
}
}

return $rawImportMapData;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ public function render(string|array $entryPoint, array $attributes = []): string
$importMap = [];
$modulePreloads = [];
$cssLinks = [];
$integrity = [];
$polyfillPath = null;
foreach ($importMapData as $importName => $data) {
$path = $data['path'];
Expand All @@ -70,8 +71,12 @@ public function render(string|array $entryPoint, array $attributes = []): string
}

$preload = $data['preload'] ?? false;
$assetIntegrity = $data['integrity'] ?? false;
if ('css' !== $data['type']) {
$importMap[$importName] = $path;
if ($assetIntegrity) {
$integrity[$path] = $assetIntegrity;
}
if ($preload) {
$modulePreloads[] = $path;
}
Expand All @@ -96,7 +101,7 @@ public function render(string|array $entryPoint, array $attributes = []): string
}

$scriptAttributes = $attributes || $this->scriptAttributes ? ' '.$this->createAttributesString($attributes) : '';
$importMapJson = json_encode(['imports' => $importMap], \JSON_THROW_ON_ERROR | \JSON_PRETTY_PRINT | \JSON_UNESCAPED_SLASHES | \JSON_HEX_TAG);
$importMapJson = json_encode(['imports' => $importMap, ...$integrity ? ['integrity' => $integrity] : []], \JSON_THROW_ON_ERROR | \JSON_PRETTY_PRINT | \JSON_UNESCAPED_SLASHES | \JSON_HEX_TAG);
$output .= <<<HTML

<script type="importmap"$scriptAttributes>
Expand Down
1 change: 1 addition & 0 deletions src/Symfony/Component/AssetMapper/MappedAsset.php
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ public function __construct(
private array $dependencies = [],
private array $fileDependencies = [],
private array $javaScriptImports = [],
public readonly ?string $integrity = null,
) {
if (null !== $sourcePath) {
$this->sourcePath = $sourcePath;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
use Symfony\Component\AssetMapper\Compiler\CssAssetUrlCompiler;
use Symfony\Component\AssetMapper\Compiler\JavaScriptImportPathCompiler;
use Symfony\Component\AssetMapper\Exception\CircularAssetsException;
use Symfony\Component\AssetMapper\Exception\LogicException;
use Symfony\Component\AssetMapper\Factory\MappedAssetFactory;
use Symfony\Component\AssetMapper\ImportMap\ImportMapConfigReader;
use Symfony\Component\AssetMapper\MappedAsset;
Expand Down Expand Up @@ -148,7 +149,35 @@ public function testCreateMappedAssetInMissingVendor()
$this->assertFalse($asset->isVendor);
}

private function createFactory(?AssetCompilerInterface $extraCompiler = null, ?string $vendorDir = self::VENDOR_FIXTURES_DIR): MappedAssetFactory
public function testCreateMappedAssetWithoutIntegrity()
{
$factory = $this->createFactory();
$asset = $factory->createMappedAsset('file2.js', self::FIXTURES_DIR.'/dir1/file2.js');
$this->assertNull($asset->integrity);
}

public function testCreateMappedAssetWithOneIntegrityAlgorithm()
{
$factory = $this->createFactory(integrityHashAlgorithms: ['sha256']);
$asset = $factory->createMappedAsset('file2.js', self::FIXTURES_DIR.'/dir1/file2.js');
$this->assertSame('sha256-b8bze+0OP5qLVVEG0aUh25UkvNjZXLeugH9Jg7MvSz8=', $asset->integrity);
}

public function testCreateMappedAssetWithManyIntegrityAlgorithms()
{
$factory = $this->createFactory(integrityHashAlgorithms: ['sha256', 'sha384']);
$asset = $factory->createMappedAsset('file2.js', self::FIXTURES_DIR.'/dir1/file2.js');
$this->assertSame('sha256-b8bze+0OP5qLVVEG0aUh25UkvNjZXLeugH9Jg7MvSz8= sha384-2cpbxkWC8I4PKAhlQ+LaFmVek6qd8w35xUZ+QRGMzcSvX9SP2EgjLvKSawSmS9J7', $asset->integrity);
}

public function testCreateMappedAssetWithInvalidIntegrityAlgorithm()
{
$this->expectException(LogicException::class);
$this->expectExceptionMessage('Unsupported "sha1" algorithm(s). Supported ones are "sha256", "sha384", "sha512".');
$this->createFactory(integrityHashAlgorithms: ['sha1']);
}

private function createFactory(?AssetCompilerInterface $extraCompiler = null, ?string $vendorDir = self::VENDOR_FIXTURES_DIR, array $integrityHashAlgorithms = []): MappedAssetFactory
{
$compilers = [
new JavaScriptImportPathCompiler($this->createMock(ImportMapConfigReader::class)),
Expand All @@ -174,6 +203,7 @@ private function createFactory(?AssetCompilerInterface $extraCompiler = null, ?s
$pathResolver,
$compiler,
$vendorDir,
$integrityHashAlgorithms,
);

// mock the AssetMapper to behave like normal: by calling back to the factory
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,10 @@ public function testGetImportMapData()
path: 'styles/never_imported_css.css',
type: ImportMapType::CSS,
),
self::createLocalEntry(
'js_file_with_integrity',
path: 'js_file_with_integrity.js',
),
]);

$importedFile1 = new MappedAsset(
Expand Down Expand Up @@ -142,6 +146,13 @@ public function testGetImportMapData()
publicPathWithoutDigest: '/assets/styles/never_imported_css.css',
publicPath: '/assets/styles/never_imported_css-d1g35t.css',
);
$jsFileWithIntegrity = new MappedAsset(
'js_file_with_integrity.js',
'/path/to/js_file_with_integrity.js',
publicPathWithoutDigest: '/assets/js_file_with_integrity.js',
publicPath: '/assets/js_file_with_integrity-d1g35t.js',
integrity: 'sha384-base64-hash'
);
$this->mockAssetMapper([
new MappedAsset(
'entry1.js',
Expand Down Expand Up @@ -179,6 +190,7 @@ public function testGetImportMapData()
$importedCss2,
$importedCssInImportmap,
$neverImportedCss,
$jsFileWithIntegrity,
]);

$actualImportMapData = $manager->getImportMapData(['entry2', 'entry1']);
Expand Down Expand Up @@ -232,6 +244,11 @@ public function testGetImportMapData()
'path' => '/assets/styles/never_imported_css-d1g35t.css',
'type' => 'css',
],
'js_file_with_integrity' => [
'path' => '/assets/js_file_with_integrity-d1g35t.js',
'type' => 'js',
'integrity' => 'sha384-base64-hash',
],
], $actualImportMapData);

// now check the order
Expand All @@ -251,6 +268,7 @@ public function testGetImportMapData()
// importmap entries never imported
'entry3',
'never_imported_css',
'js_file_with_integrity',
], array_keys($actualImportMapData));
}

Expand Down Expand Up @@ -570,6 +588,31 @@ public static function getRawImportMapDataTests(): iterable
],
],
];

yield 'it adds integrity when it exists' => [
[
self::createLocalEntry(
'app',
path: './assets/app.js',
),
],
[
new MappedAsset(
'app.js',
// /fake/root is the mocked root directory
'/fake/root/assets/app.js',
publicPath: '/assets/app-d1g3st.js',
integrity: 'sha384-base64-hash',
),
],
[
'app' => [
'path' => '/assets/app-d1g3st.js',
'type' => 'js',
'integrity' => 'sha384-base64-hash',
],
],
];
}

public function testGetRawImportDataUsesCacheFile()
Expand Down
Loading