duracelltomi / gtm4wp

Google Tag Manager plugin for WordPress
https://gtm4wp.com/
GNU General Public License v3.0
147 stars 95 forks source link

How to add nonce for CSP? gtm4wp_get_the_gtm_tag filter is deprecated. #351

Open gettonet opened 3 months ago

gettonet commented 3 months ago

Hello,

given the fact gtm4wp_get_the_gtm_tag filter is deprecated, we cannot add nonce to gtm4wp scripts and include in website Content Security Policy. Why is this filter deprecated, do you plan to get it back in future releases, or do you recommend some other way of adding the gtm4wp scripts to CSP, apart from creating a hash for every single (dynamic) script?

duracelltomi commented 3 months ago

This filter was removed because it introduced some security risks.

If you want to alter the container code in any way, you should turn off the container code in plugin options and add your own container code using the GTM4WP_WPACTION_AFTER_CONTAINER_CODE / gtm4wp_after_container_code filter which fires regardless of whether container code is turned on or off in plugin settings.

Just make sure to output the full header script.

gettonet commented 3 months ago

Datalayer script is making it impossible to add to CSP as hash, as it is dynamically created and it's different on every page:


<script data-cfasync="false" data-pagespeed-no-defer' . ( $has_html5_support ? ' type="text/javascript"' : '' ) . ( $add_cookiebot_ignore ? ' data-cookieconsent="ignore"' : '' ) . '>';

    if ( '' !== $gtm4wp_options[ GTM4WP_OPTION_GTM_CODE ] ) {
        $gtm4wp_datalayer_data = array();
        $gtm4wp_datalayer_data = (array) apply_filters( GTM4WP_WPFILTER_COMPILE_DATALAYER, $gtm4wp_datalayer_data );

        echo '
    var dataLayer_content = ' . wp_json_encode( $gtm4wp_datalayer_data, JSON_UNESCAPED_UNICODE | JSON_NUMERIC_CHECK ) . ';';

        echo '
    ' . esc_js( $gtm4wp_datalayer_name ) . '.push( dataLayer_content );';
    }

    echo '
</script>';

It is not the container itself, as it can be added to CSP as hash. But what to do with datalayer script? Wouldn't it be worth considering adding a filter for nonce?

duracelltomi commented 3 months ago

I can of course.

What about adding a filter like gtm4wp_get_csp_nonce and what is returned is added to the Githubissues.

  • Githubissues is a development platform for aggregating issues.