nelmio / NelmioSecurityBundle

Adds extra security-related features in your Symfony application
https://symfony.com/bundles/NelmioSecurityBundle/
MIT License
651 stars 85 forks source link

cspscript for encore_entry_script_tags and cspstyle for encore_entry_link_tags #314

Open thomas2411 opened 2 years ago

thomas2411 commented 2 years ago

cspscript and cspstyle works only for one script at a time. Both encore_entry_script_tags and encore_entry_link_tags generate multiple <script> and <style> tags by design. Do you think of any solution that could handle this situation? The only thing I can imagine is to add a new tags cspscripts and cspstyle to NelmioSecurityBundle which will handle multiple tags in a loop. What do you think about it?

sebbio commented 6 months ago

Any idea?

sebbio commented 6 months ago

I make like this and work fine: {{ encore_entry_link_tags('backend', null, '_default', {'nonce': csp_nonce('style')}) }}

oleg-andreyev commented 2 months ago

problem with csp_nonce it always generate new nonce and replaces prev. one and making it invalid.

imo it should behave similar to cspscript and cspstyle and pileup array of nonce.

micheh commented 2 months ago

For Webpack Encore, you can use an EventSubscriber to automatically add the nonce to the script or link tags.

For example (only script tags):

final class EncoreNonceSubscriber implements EventSubscriberInterface
{
    private ContentSecurityPolicyListener $csp;

    public function __construct(ContentSecurityPolicyListener $csp)
    {
        $this->csp = $csp;
    }

    public static function getSubscribedEvents(): array
    {
        return [RenderAssetTagEvent::class => 'onRenderAssetTag'];
    }

    public function onRenderAssetTag(RenderAssetTagEvent $event): void
    {
        if ($event->isScriptTag()) {
            $event->setAttribute('nonce', $this->csp->getNonce('script'));
        }
    }
}