Problem/Motivation

This issue collects several related problems found while reviewing COOKiES. Most of them can cause tracking without consent or break JavaScript on live sites. Each fix is a separate commit in the merge request, so they can be reviewed one by one.

1. The consent callback (/cookies/consent/callback.json) accepts any input from any site

  • CSRF: the route accepts GET and form-encoded POST requests, so another website can trigger it in a visitor's browser (for example with an <img> tag or an auto-submitted form). For logged-in users with "Store consent for authenticated users" enabled, this overwrites their stored consent.
  • Unfiltered data: the consent data is passed unfiltered to hook_cookies_user_consent() and stored in the key/value store. That covers both the callback and hook_user_login(), where the data comes from the COOKiES cookie. Clients can store any keys and values of any size.

2. Scripts knocked out by the submodules break JS aggregation

On live sites with JS aggregation enabled, building aggregated JS files fails with:

Exception: Error trying to optimize JavaScript asset: modules/contrib/google_tag/js/gtag.js. Only file JavaScript assets with preprocessing enabled can be optimized. in Drupal\Core\Asset\JsOptimizer->optimize()

The submodules only set preprocess to FALSE on the scripts they knock out if doKnockOut() returns TRUE. Core builds JS aggregates lazily in a separate request (the JS asset controller), where doKnockOut() can return a different result than in the page request, for example because of the COOKiES UI block visibility conditions or the active theme. The asset groups then differ between the two requests:

  • Core redirects the aggregate URL to the hash of whichever group sits at the same position in the second request.
  • If that group is a single non-aggregated script, building it fails with the exception above.
  • Otherwise visitors silently get an aggregate with the wrong scripts.

This affects cookies_gtag, cookies_ga, cookies_matomo, cookies_facebook_pixel, cookies_recaptcha and cookies_asset_injector.

3. The knock-out of scripts is cached across pages with different knock-out states

Core caches the result of hook_js_alter() per theme, language and set of attached libraries, not per request. The submodules decide the knock-out in hook_js_alter() with doKnockOut(), which depends on the current request. So the cached result of one page can be reused on another page with a different knock-out state:

  • A tracking script can load without consent on a page that shows the COOKiES UI.
  • A script can stay blocked forever on a page without the UI.

Usually the COOKiES UI block attaches its own library, so the cache keys differ. They don't differ when scripts are knocked out but the block isn't rendered (for example a layout or page variant that skips the block's region), and in Ajax responses. On top of that, CookiesKnockOutService discarded the cacheability of the block access check.

4. cookies_matomo breaks JavaScript

Matomo 2.x adds matomo.js, which reads the global _paq variable as soon as it loads. _paq is defined by the inline tracking snippet, which COOKiES knocks out. Until consent is given, every page throws ReferenceError: _paq is not defined. With JS aggregation the error is thrown inside an aggregate, so it also stops all other JavaScript in that aggregate.

5. cookies_gtag lets Google Tag Manager track visitors without JavaScript

The google_tag module adds a GTM <noscript> iframe (on by default). COOKiES doesn't knock it out, so visitors without JavaScript, who can never give consent, are tracked by GTM.

6. Several tests fail on current core and dependencies

  • FunctionalCookiesStyleTest: it saves a service as raw config without an id, which current core rejects with an EntityMalformedException.
  • CookiesFacebookPixelFunctionalJavascriptTest: it uses the facebook_pixel 2.x settings form. Its script selector also matches cookies_facebook_pixel.js.
  • CookiesMatomoFunctionalJavascriptTest: it fails because of the _paq error described in point 4.

Steps to reproduce

1. Callback

  1. Enable "Store consent for authenticated users".
  2. While logged in, open /cookies/consent/callback.json?foo=bar (GET).
  3. The key/value entry cookies.consent.user:uid:<uid> now contains foo => bar.

2. JS aggregation

  1. Install matomo (2.x) and cookies_matomo, configure a site ID, and enable JS aggregation.
  2. Place the COOKiES UI block with the visibility condition "Hide for the listed pages: /node" (or any front page path).
  3. Open the front page and request one of its js_*.js aggregate URLs.
  4. The request is redirected to another aggregate. Depending on the group order it serves the wrong scripts or fails with the exception above (seen with google_tag 2.0.x, where gtag.js is aggregated by default).

3. Matomo

  1. Install matomo (2.x) and cookies_matomo, and configure a site ID.
  2. Enable JS aggregation.
  3. Visit the front page without having given consent. The browser console shows _paq is not defined, and other aggregated scripts don't run.

4. GTM noscript iframe

  1. Install google_tag and cookies_gtag, and configure a GTM-… container.
  2. View the page source without having given consent. It contains <noscript><iframe src="https://www.googletagmanager.com/ns.html?id=GTM-…">.

Proposed resolution

1. Consent callback

  • POST and JSON only: the cookies.callback route only accepts POST with _content_type_format: json. Browsers can't send such a request from another site without a CORS preflight, which protects against CSRF. Other methods get a 405, other content types a 415.
  • Size limit: request bodies over 64 KB are rejected with a 413.
  • Filtering: the new CookiesConfigService::filterConsent() keeps only known service IDs with boolean values. It runs before hook_cookies_user_consent() is invoked and before consent is stored, both in the callback and in hook_user_login().
  • Widget configuration: the widget always sends a JSON POST to the module's own callback route. Whether the configured callback URL points to that route is now detected by resolving the URL (base path, language prefix, alias, absolute URL on the current host). For this route, the deprecated callback_method setting is ignored. Custom callback URLs work as before and don't get the JSON header, so cross-origin custom callbacks don't suddenly need a CORS preflight.
  • Backwards compatibility: CookiesConfigService gets three new constructor arguments (path_processor_manager, router.route_provider, request_stack). They are optional and fall back to the container, so subclasses keep working.

2. Never aggregate knocked out scripts

All hook_js_alter() implementations of the submodules now always set preprocess to FALSE on the scripts they handle, independent of the knock-out. The asset groups are then the same in every request, and only the knock-out attributes (type, id, data-cookieconsent) depend on the knock-out.

3. Derive the JS knock-out from the attached libraries

  • Marker library: the new cookies_page_attachments() attaches the new, empty cookies/knock_out library on pages where scripts are knocked out. It adds the cacheability of the block access check to the page.
  • New method: CookiesKnockOutService::doKnockOutAssets(AttachedAssetsInterface $assets) returns TRUE if that library is attached, or already loaded for Ajax requests.
  • Submodules: all hook_js_alter() implementations use it instead of doKnockOut().
  • Why this works: the attached libraries are part of core's JS asset cache key and of the JS aggregate URLs. So the cached and the aggregated results always match the page.
  • Cacheability: CookiesKnockOutService::getCacheableMetadata() exposes the cacheability of doKnockOut().

4. Matomo

  • cookies_matomo_js_alter() also knocks out matomo.js.
  • After consent, cookies_matomo.js activates it right after the tracking snippet, so _paq exists when it runs.

5. Google Tag Manager noscript iframe

  • The new cookies_gtag_page_top() removes the GTM noscript iframe while the gtag service requires consent. It runs after google_tag_page_top() because of the module weight.
  • The cache metadata of the gtag service is added to the page, so changing that service's "consent required" setting updates the cached page.
  • Tested with google_tag 2.1.0.

6. Tests

  • New:
    • CookiesCallbackTest (functional): method, content type, size limit and consent filtering of the callback.
    • CookiesCallbackConfigTest (kernel): the callback method and headers for different callback URLs.
    • CookiesMatomoJsAlterTest (kernel): the knock-out depends on the attached libraries, not on the current request, and the script is never aggregated.
    • CookiesMatomoFunctionalTest::testJsAggregatesWithDifferentKnockOut(): the JS aggregates aren't redirected when the knock-out differs between the page request and the asset request.
    • CookiesMatomoFunctionalJavascriptTest::testMatomoJsCorrectlyKnockedWithJsAggregation(): matomo.js is knocked out separately and other JavaScript keeps working with JS aggregation enabled.
    • CookiesGtagFunctionalTest::testGtmNoscriptIframeKnockedOut(): the GTM noscript iframe is removed while consent is required.
  • Fixed: FunctionalCookiesStyleTest, CookiesFacebookPixelFunctionalJavascriptTest and CookiesMatomoFunctionalJavascriptTest.

Remaining tasks

  • Review.
  • Decide whether to backport to the 1.2.x branch.
  • Follow-up issues:
    • CookiesFunctionalJsGeneralTest::testCookiesBanner fails unless the cookiesjsr library is installed locally. It expects uppercase button text from the library's CSS, so it only passes when the random text has no lowercase letters.
    • TestCookiesAssetInjectorFunctionalJavascript never runs, because its file name doesn't end in Test.php, and it fails when run directly.
    • Ajax edge case: two Ajax responses that load the same new libraries, but come from pages with different knock-out states, can still share a JS asset cache entry. Core doesn't include already-loaded libraries in the cache key. Tracking scripts are normally loaded with the full page, so this is unlikely in practice.

User interface changes

None.

API changes

  • hook_cookies_user_consent() now only receives known service IDs with boolean values.
  • The cookies.callback route only accepts JSON POST requests. Custom code that called it via GET or with a form-encoded body must send JSON instead.
  • CookiesConfigService: new public method filterConsent() and three new optional constructor arguments.
  • CookiesKnockOutService:
    • New constant KNOCK_OUT_LIBRARY.
    • New public methods doKnockOutAssets() and getCacheableMetadata().
    • Contrib or custom modules that knock out scripts in hook_js_alter() should use doKnockOutAssets($assets) instead of doKnockOut(), and should always set preprocess to FALSE on those scripts.
  • New library cookies/knock_out. It has no assets and is only used as a marker.

Data model changes

None. Consent stored for authenticated users only contains known service IDs with boolean values from now on.

Release notes snippet

This release hardens the consent callback against CSRF and fixes several script blocking issues:

  • The consent callback only accepts JSON POST requests and filters the submitted consent to known services.
  • Knocked out scripts are never aggregated anymore, which fixes "Only file JavaScript assets with preprocessing enabled can be optimized" exceptions and wrong JS aggregates.
  • The knock-out of scripts no longer leaks between pages through core's JS asset cache.
  • cookies_matomo no longer breaks other JavaScript.
  • cookies_gtag no longer renders the Google Tag Manager noscript iframe before consent is given.

Custom code that knocks out scripts in hook_js_alter() should switch to CookiesKnockOutService::doKnockOutAssets(). Clear all caches after updating.

Issue fork cookies-3639384

Command icon Show commands

Start within a Git clone of the project using the version control instructions.

Or, if you do not have SSH keys set up on git.drupalcode.org:

Comments

grevil created an issue. See original summary.

grevil’s picture

Title: Harden COOKIES » Harden COOKIES, fix matomo and gtag
grevil’s picture

Title: Harden COOKIES, fix matomo and gtag » Harden the consent callback and fix several script blocking issues in the submodules (CSRF, JS aggregation errors, cache, Matomo, Google Tag Manager noscript iframe)
Issue summary: View changes

grevil’s picture

Status: Active » Fixed

Now that this issue is closed, review the contribution record.

As a contributor, attribute any organization that helped you, or if you volunteered your own time.

Maintainers, credit people who helped resolve this issue.