From bd0c70af178d10285e2dd84cea0cb37ad26d0ff2 Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Mon, 29 Jun 2026 17:31:23 +0200 Subject: [PATCH] feat(matomo): configurable tracking scope (sub default / root) Add a per-deployment Matomo tracking scope, defaulting to per-subdomain: - services.matomo.tracking.scope 'sub' (default) registers one Matomo site per consumer subdomain with an isolated cookie; 'root' keeps the prior behaviour of one shared site per registrable base domain with cross-subdomain linking. - sys-front-inj-matomo derives matomo_site_domain (full host vs registrable base) and the shared matomo_site_url from it; getSitesId / addSite and the tracking snippet (setCookieDomain / setDomains / enableCrossDomainLinking) all follow the scope. - The matomo Playwright env emits MATOMO_TRACKING_SCOPE; the SitesManager test matches the consumer's full host in 'sub' and its base domain in 'root'. - variants.yml variant 0 sets scope=root so the matrix exercises both flavours (every other deploy runs the sub default). Co-Authored-By: Claude Opus 4.8 --- roles/sys-front-inj-matomo/tasks/inject.yml | 3 +-- roles/sys-front-inj-matomo/tasks/inject_apply.yml | 3 +-- .../templates/matomo-tracking.js.j2 | 11 +++++++---- roles/sys-front-inj-matomo/vars/main.yml | 6 +++++- roles/web-app-matomo/files/playwright/_shared.js | 10 +++++++++- .../web-app-matomo/files/playwright/tracking.spec.js | 7 ++++--- roles/web-app-matomo/meta/services.yml | 2 ++ roles/web-app-matomo/meta/variants.yml | 3 +++ roles/web-app-matomo/templates/playwright.env.j2 | 2 ++ 9 files changed, 34 insertions(+), 13 deletions(-) diff --git a/roles/sys-front-inj-matomo/tasks/inject.yml b/roles/sys-front-inj-matomo/tasks/inject.yml index 9ec6d15077..61ad2a7c6a 100644 --- a/roles/sys-front-inj-matomo/tasks/inject.yml +++ b/roles/sys-front-inj-matomo/tasks/inject.yml @@ -1,8 +1,7 @@ --- - name: "🔎 Check if site {{ domain }} is already registered at Matomo" uri_retry: - url: "{{ matomo_index_php_url }}?module=API&method=SitesManager.getSitesIdFromSiteUrl&url={{ lookup('tls', application_id, 'protocols.web') }}://{{ base_domain - }}&format=json&token_auth={{ matomo_effective_token }}" + url: "{{ matomo_index_php_url }}?module=API&method=SitesManager.getSitesIdFromSiteUrl&url={{ matomo_site_url }}&format=json&token_auth={{ matomo_effective_token }}" method: GET return_content: true status_code: 200 diff --git a/roles/sys-front-inj-matomo/tasks/inject_apply.yml b/roles/sys-front-inj-matomo/tasks/inject_apply.yml index 5f6e28d9aa..7423df4633 100644 --- a/roles/sys-front-inj-matomo/tasks/inject_apply.yml +++ b/roles/sys-front-inj-matomo/tasks/inject_apply.yml @@ -13,8 +13,7 @@ uri_retry: url: "{{ matomo_index_php_url }}" method: POST - body: "module=API&method=SitesManager.addSite&siteName={{ base_domain }}&urls={{ lookup('tls', application_id, 'protocols.web') }}://{{ base_domain }}&format=json&token_auth={{ - matomo_effective_token }}" + body: "module=API&method=SitesManager.addSite&siteName={{ matomo_site_domain }}&urls={{ matomo_site_url }}&format=json&token_auth={{ matomo_effective_token }}" body_format: form-urlencoded status_code: 200 return_content: true diff --git a/roles/sys-front-inj-matomo/templates/matomo-tracking.js.j2 b/roles/sys-front-inj-matomo/templates/matomo-tracking.js.j2 index c9d80e05d0..1f9f20e116 100644 --- a/roles/sys-front-inj-matomo/templates/matomo-tracking.js.j2 +++ b/roles/sys-front-inj-matomo/templates/matomo-tracking.js.j2 @@ -1,11 +1,14 @@ var _paq = window._paq = window._paq || []; _paq.push(["setDocumentTitle", document.domain + "/" + document.title]); // Chromium may reject explicitly dotted cookie domains in embedded/cross-site -// flows. The bare parent domain still covers all subdomains, so prefer it for -// the cookie while keeping the wider local-domain match list below. -_paq.push(["setCookieDomain", "{{base_domain}}"]); -_paq.push(["setDomains", [".{{base_domain}}"]]); +// flows, so set the bare domain for the cookie. +_paq.push(["setCookieDomain", "{{ matomo_site_domain }}"]); +{% if matomo_tracking_scope == 'root' %} +_paq.push(["setDomains", [".{{ matomo_site_domain }}"]]); _paq.push(["enableCrossDomainLinking"]); +{% else %} +_paq.push(["setDomains", ["{{ matomo_site_domain }}"]]); +{% endif %} _paq.push(["trackPageView"]); _paq.push(["trackAllContentImpressions"]); _paq.push(["enableLinkTracking"]); diff --git a/roles/sys-front-inj-matomo/vars/main.yml b/roles/sys-front-inj-matomo/vars/main.yml index 42c439f8c2..ad20805310 100644 --- a/roles/sys-front-inj-matomo/vars/main.yml +++ b/roles/sys-front-inj-matomo/vars/main.yml @@ -1,3 +1,7 @@ --- -base_domain: "{{ domain | regex_replace('^(?:.*\\.)?(.+\\..+)$', '\\1') }}" +matomo_tracking_scope: "{{ lookup('config', 'web-app-matomo', 'services.matomo.tracking.scope') }}" +matomo_site_domain: >- + {{ domain if matomo_tracking_scope == 'sub' + else (domain | regex_replace('^(?:.*\\.)?(.+\\..+)$', '\\1')) }} +matomo_site_url: "{{ lookup('tls', application_id, 'protocols.web') }}://{{ matomo_site_domain }}" matomo_index_php_url: "{{ lookup('tls', 'web-app-matomo', 'url.base') }}index.php" diff --git a/roles/web-app-matomo/files/playwright/_shared.js b/roles/web-app-matomo/files/playwright/_shared.js index 6586e07166..d1b1514d21 100644 --- a/roles/web-app-matomo/files/playwright/_shared.js +++ b/roles/web-app-matomo/files/playwright/_shared.js @@ -14,6 +14,7 @@ const biberUsername = decodeDotenvQuotedValue(process.env.BIBER_USERNAME); const biberPassword = decodeDotenvQuotedValue(process.env.BIBER_PASSWORD); const canonicalDomain = decodeDotenvQuotedValue(process.env.CANONICAL_DOMAIN); const matomoApiToken = decodeDotenvQuotedValue(process.env.MATOMO_API_TOKEN); +const matomoTrackingScope = (process.env.MATOMO_TRACKING_SCOPE || "sub").trim().toLowerCase(); const matomoCanonicalDomain = (() => { try { @@ -76,13 +77,18 @@ function hostOf(value) { } } -// MUST mirror sys-front-inj-matomo/vars/main.yml base_domain: matomo registers one shared site per registrable domain, not per subdomain +// MUST mirror sys-front-inj-matomo matomo_site_domain in root scope: one shared site per registrable domain, not per subdomain function baseDomainOf(host) { return String(host || "") .toLowerCase() .replace(/^(?:.*\.)?(.+\..+)$/, "$1"); } +// Tracking-site needle for a consumer host: full subdomain in 'sub' scope (one site per subdomain), registrable base in 'root' scope (one shared site) +function siteNeedleFor(host) { + return matomoTrackingScope === "root" ? baseDomainOf(host) : hostOf(host); +} + async function setupMatomoPage(page) { await page.setViewportSize({ width: 1440, height: 1100 }); @@ -126,11 +132,13 @@ module.exports = { biberPassword, canonicalDomain, matomoApiToken, + matomoTrackingScope, matomoCanonicalDomain, matomoTargetRoles, attachDiagnostics, hostOf, baseDomainOf, + siteNeedleFor, setupMatomoPage, loginAsAdmin, }; diff --git a/roles/web-app-matomo/files/playwright/tracking.spec.js b/roles/web-app-matomo/files/playwright/tracking.spec.js index f00f9395a8..15f8827eb2 100644 --- a/roles/web-app-matomo/files/playwright/tracking.spec.js +++ b/roles/web-app-matomo/files/playwright/tracking.spec.js @@ -3,10 +3,11 @@ const { test, expect } = require("@playwright/test"); const { appBaseUrl, matomoApiToken, + matomoTrackingScope, matomoCanonicalDomain, matomoTargetRoles, hostOf, - baseDomainOf, + siteNeedleFor, setupMatomoPage, loginAsAdmin, } = require("./_shared"); @@ -47,7 +48,7 @@ test("matomo SitesManager registers a tracker site for every consumer role", asy const failures = []; for (const target of matomoTargetRoles) { - const needle = baseDomainOf(target.canonical_domain); + const needle = siteNeedleFor(target.canonical_domain); if (!needle) { failures.push(`${target.id}: empty canonical_domain in MATOMO_TARGET_ROLES_JSON`); continue; @@ -60,7 +61,7 @@ test("matomo SitesManager registers a tracker site for every consumer role", asy return candidates.some((c) => hostOf(c) === needle); }); if (!matchingSite) { - failures.push(`${target.id}: no Matomo site main_url / alias_urls host equals base domain "${needle}" (canonical "${target.canonical_domain}")`); + failures.push(`${target.id}: no Matomo site main_url / alias_urls host equals tracking site domain "${needle}" (scope "${matomoTrackingScope}", canonical "${target.canonical_domain}")`); } } diff --git a/roles/web-app-matomo/meta/services.yml b/roles/web-app-matomo/meta/services.yml index a8fe8f5421..f36f69a8a1 100644 --- a/roles/web-app-matomo/meta/services.yml +++ b/roles/web-app-matomo/meta/services.yml @@ -30,6 +30,8 @@ matomo: mem_limit: 1g pids_limit: 512 site_name: Matomo on {{ DOMAIN_PRIMARY }} + tracking: + scope: sub token: description: Created by {{ SOFTWARE_NAME }} excluded_ips: "{{ networks.internet.values() | list }}" diff --git a/roles/web-app-matomo/meta/variants.yml b/roles/web-app-matomo/meta/variants.yml index 94cc30966c..cc453eb19f 100644 --- a/roles/web-app-matomo/meta/variants.yml +++ b/roles/web-app-matomo/meta/variants.yml @@ -22,6 +22,9 @@ prometheus: enabled: true shared: true + matomo: + tracking: + scope: root - services: css: enabled: false diff --git a/roles/web-app-matomo/templates/playwright.env.j2 b/roles/web-app-matomo/templates/playwright.env.j2 index fbbbb667b6..21b30d259f 100644 --- a/roles/web-app-matomo/templates/playwright.env.j2 +++ b/roles/web-app-matomo/templates/playwright.env.j2 @@ -21,6 +21,8 @@ MATOMO_BASE_URL={{ lookup('tls', 'web-app-matomo', 'url.base') | dotenv_quote }} # Tracker-target list: every role declaring services.matomo.{enabled,shared}. Spec parameterises one tracker-presence assertion per entry. MATOMO_TARGET_ROLES_JSON={{ lookup('roles_with_service', 'matomo') | to_json | dotenv_quote }} +MATOMO_TRACKING_SCOPE={{ lookup('config', application_id, 'services.matomo.tracking.scope') | string | lower }} + OIDC_ISSUER_URL={{ OIDC.CLIENT.ISSUER_URL | dotenv_quote }}