magento2 icon indicating copy to clipboard operation
magento2 copied to clipboard

Incorrect JavaScript File Loading Order After Enabling CSP module

Open 0m3r opened this issue 4 months ago • 1 comments

I am encountering an issue with the loading order of JavaScript files (require.js, mixins.js, requirejs-config.js) after enabling Content Security Policy (CSP) in Magento 2. This appears to be breaking JavaScript bundling, causing improper execution order and related issues.

Reproduction Steps:

  1. Enable CSP in Magento 2.
  2. Notice the incorrect loading order of JavaScript files: require.js, mixins.js, requirejs-config.js.
  3. This issue also affects JavaScript bundling functionality, leading to performance degradation.

Screenshots:

  • Before enabling CSP: Correct file order (Screenshot below) Screenshot before CSP

  • After enabling CSP: Incorrect file loading order Screenshot after CSP

Cause:

It seems that the issue is related to CSP configurations interfering with the loading order and possibly the integrity attribute (hash) of JavaScript assets, specifically in how property groups are handled within GroupedCollection.

In this file, the integrity attributes (hash) should be ignored when grouping properties.

Proposed Workaround: (doesn't work properly broke integrity :( )

I suggest modifying the grouping logic to disregard the integrity attribute when comparing asset properties.

Example workaround code:

private function clearGroupProperties(array $properties)
{
    if (isset($properties['attributes']['integrity'])) {
        unset($properties['attributes']['integrity']);
    }
    return $properties;
}

/**
 * Retrieve existing or new group matching the properties
 *
 * @param array $properties
 * @return PropertyGroup
 */
private function getGroupFor(array $properties)
{
    /** @var $existingGroup PropertyGroup */
    foreach ($this->groups as $existingGroup) {
        $existingGroupProperties = $existingGroup->getProperties();
        if ($this->clearGroupProperties($existingGroupProperties) == $this->clearGroupProperties($properties)) {
            return $existingGroup;
        }
    }
    /** @var $newGroup PropertyGroup */
    $newGroup = $this->propertyFactory->create(['properties' => $properties]);
    $this->groups[] = $newGroup;
    return $newGroup;
}

Expected Outcome:

  • After this modification, JavaScript files should load in the correct order.
  • JavaScript bundling should function correctly even with CSP enabled.

0m3r avatar Oct 17 '24 14:10 0m3r