Merge main into the seasons work: keep the Google tag entry under the seasons entry
This commit is contained in:
commit
9a8aa49318
13 files changed
+135
-13
No files matched your search
+1
-1
@@ -302,7 +302,7 @@ def maintainer_section(site):
|
||||
<li>The records and the compiled index are public domain (CC0 1.0). Each track keeps the licence of its source.</li>
|
||||
<li>Every fact in a record names the page it was read on, and each record keeps a history of what changed and why.</li>
|
||||
<li>To correct a fact, suggest a trail or ask for a track or logo to be removed, {ask}. Every trail page has its own “Report a problem” link.</li>
|
||||
<li>The site has no ads, no accounts, no tracking and no analytics. Your theme, units and saved trails stay in your own browser. Maps load their tiles from OpenFreeMap.</li>
|
||||
<li>The site has no ads and no accounts. Your theme, units and saved trails stay in your own browser. Maps load their tiles from OpenFreeMap.</li>
|
||||
</ul>
|
||||
</section>
|
||||
"""
|
||||
|
||||
@@ -216,6 +216,17 @@ def skip_links(body):
|
||||
return out
|
||||
|
||||
|
||||
# The owner's Google tag, as given; only the container id comes from site.toml (google_tag).
|
||||
# The inline script's hash is in the Content-Security-Policy (web/static/_headers); a test keeps them equal.
|
||||
GOOGLE_TAG_INLINE = """
|
||||
window.dataLayer = window.dataLayer || [];
|
||||
function gtag(){dataLayer.push(arguments);}
|
||||
gtag('js', new Date());
|
||||
"""
|
||||
GOOGLE_TAG = ('<script async src="https://www.googletagmanager.com/gtm.js?id={id}"></script>\n'
|
||||
'<script>' + GOOGLE_TAG_INLINE + '</script>')
|
||||
|
||||
|
||||
def layout(title, body, *, path, description="", maps=False, outdoor=False, scripts=(), data=None, site=None,
|
||||
jsonld=None, og_type="website", noindex=False, image="", image_alt="", alternates=()):
|
||||
"""Return a complete HTML document.
|
||||
@@ -262,6 +273,8 @@ def layout(title, body, *, path, description="", maps=False, outdoor=False, scri
|
||||
f"<title>{esc(tag)}</title>",
|
||||
f'<meta name="description" content="{esc(description)}">',
|
||||
]
|
||||
if site.google_tag:
|
||||
head.append(GOOGLE_TAG.replace("{id}", esc(site.google_tag)))
|
||||
if noindex:
|
||||
head.append('<meta name="robots" content="noindex">')
|
||||
if canonical:
|
||||
|
||||
+5
-2
@@ -12,7 +12,7 @@ class Site:
|
||||
"""The settings every page needs. Build one with load()."""
|
||||
|
||||
def __init__(self, name, tagline, base_url="", repo_url="", repo_branch="main",
|
||||
contact_url="", name_lang=None, home_title="", maintainer_name="", maintainer_url=""):
|
||||
contact_url="", name_lang=None, home_title="", maintainer_name="", maintainer_url="", google_tag=""):
|
||||
if not name:
|
||||
raise ValueError("site.toml: name must not be empty")
|
||||
self.name = name
|
||||
@@ -27,6 +27,8 @@ class Site:
|
||||
# named in the structured data. Both are public by the owner's choice.
|
||||
self.maintainer_name = maintainer_name.strip()
|
||||
self.maintainer_url = maintainer_url.strip()
|
||||
# Google tag container id (GTM-XXXXXXX): when set, every page loads the tag; empty: none.
|
||||
self.google_tag = google_tag.strip()
|
||||
# record id -> language tag of its name ("fr"), for names that are not English
|
||||
self.name_lang = dict(name_lang or {})
|
||||
|
||||
@@ -123,7 +125,8 @@ def from_file(path):
|
||||
repo_branch=data.get("repo_branch", "main"),
|
||||
contact_url=data.get("contact_url", ""), name_lang=data.get("name_lang", {}),
|
||||
home_title=data.get("home_title", ""),
|
||||
maintainer_name=data.get("maintainer_name", ""), maintainer_url=data.get("maintainer_url", ""))
|
||||
maintainer_name=data.get("maintainer_name", ""), maintainer_url=data.get("maintainer_url", ""),
|
||||
google_tag=data.get("google_tag", ""))
|
||||
|
||||
|
||||
@functools.cache
|
||||
|
||||
@@ -40,6 +40,10 @@ contact_url = ""
|
||||
maintainer_name = "Stephen Waits"
|
||||
maintainer_url = "https://github.com/swaits"
|
||||
|
||||
# Google tag container id. When set, every page loads the tag (web/olt/layout.py) to count visits;
|
||||
# the Content-Security-Policy in web/static/_headers allows it. Empty: no tag.
|
||||
google_tag = "GTM-WWLZSH6Q"
|
||||
|
||||
# Language of record names that are not English, by record id (a BCP 47 tag).
|
||||
# Every place a page shows one of these names as text marks it with lang="..",
|
||||
# so screen readers pronounce it in that language.
|
||||
|
||||
+4
-2
@@ -13,7 +13,9 @@
|
||||
# Netlify applies all of them, so each header is set by one rule only
|
||||
# (web/tests/test_headers.py checks this against the built site).
|
||||
|
||||
# Security headers for every response. No inline scripts or style elements:
|
||||
# Security headers for every response. The one inline script is the Google tag's data-layer
|
||||
# setup (allowed by its hash, GOOGLE_TAG_INLINE in web/olt/layout.py) and its loader comes from
|
||||
# www.googletagmanager.com. Otherwise no inline scripts or style elements:
|
||||
# pages load same-origin scripts and styles, MapLibre and the contour add-on
|
||||
# run from blob: workers, map images are self/data:/blob:, fonts are
|
||||
# self-hosted, and tiles, glyphs and sprites are fetched from OpenFreeMap
|
||||
@@ -26,7 +28,7 @@
|
||||
/*
|
||||
X-Content-Type-Options: nosniff
|
||||
Referrer-Policy: strict-origin-when-cross-origin
|
||||
Content-Security-Policy: default-src 'self'; script-src 'self'; style-src 'self'; style-src-attr 'unsafe-inline'; worker-src 'self' blob:; child-src 'self' blob:; img-src 'self' data: blob:; font-src 'self'; connect-src 'self' https://tiles.openfreemap.org https://s3.amazonaws.com/elevation-tiles-prod/terrarium/; object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'none'
|
||||
Content-Security-Policy: default-src 'self'; script-src 'self' https://www.googletagmanager.com 'sha256-jYHg7tXSuuVUqjy+JeRT8vyG97+Spkw5IFHdQEBbmrw='; style-src 'self'; style-src-attr 'unsafe-inline'; worker-src 'self' blob:; child-src 'self' blob:; img-src 'self' data: blob: https://*.google-analytics.com https://*.googletagmanager.com; font-src 'self'; connect-src 'self' https://tiles.openfreemap.org https://*.google-analytics.com https://*.analytics.google.com https://*.googletagmanager.com https://s3.amazonaws.com/elevation-tiles-prod/terrarium/; object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'none'
|
||||
|
||||
# Site data. Matched by file type, not /data/*, so the pages under /data/
|
||||
# (/data/, /data/schema/, /data/changelog/) revalidate like every other page.
|
||||
|
||||
@@ -398,10 +398,13 @@ class HeadersTest(unittest.TestCase):
|
||||
csp = self.headers("/trails/john-muir/").get("content-security-policy", "")
|
||||
self.assertEqual(csp, self.headers("/").get("content-security-policy", ""))
|
||||
connect = re.search(r"connect-src ([^;]*)", csp).group(1).split()
|
||||
# The Google tag (layout.GOOGLE_TAG) reports to Google Analytics; nothing else is added.
|
||||
self.assertEqual(connect, ["'self'", "https://tiles.openfreemap.org",
|
||||
"https://*.google-analytics.com", "https://*.analytics.google.com",
|
||||
"https://*.googletagmanager.com",
|
||||
"https://s3.amazonaws.com/elevation-tiles-prod/terrarium/"])
|
||||
self.assertIn("worker-src 'self' blob:", csp)
|
||||
self.assertIn("img-src 'self' data: blob:;", csp)
|
||||
self.assertIn("img-src 'self' data: blob: https://*.google-analytics.com https://*.googletagmanager.com;", csp)
|
||||
with open(os.path.join(WEB, "assets", "map", "outdoor.json"), encoding="utf-8") as f:
|
||||
dem = json.load(f)["sources"]["olt-dem"]["tiles"][0]
|
||||
self.assertTrue(dem.startswith(connect[2]), dem)
|
||||
|
||||
@@ -223,7 +223,7 @@ class BuiltSiteTest(unittest.TestCase):
|
||||
def test_the_content_security_policy_stays_strict(self):
|
||||
csp = self.value("/index.html", "Content-Security-Policy")
|
||||
self.assertIn("default-src 'self'", csp)
|
||||
self.assertIn("script-src 'self';", csp)
|
||||
self.assertIn("script-src 'self' https://www.googletagmanager.com 'sha256-", csp)
|
||||
self.assertIn("style-src 'self';", csp)
|
||||
self.assertNotIn("unsafe-eval", csp)
|
||||
self.assertNotIn("script-src 'self' 'unsafe-inline'", csp)
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
"""The Google tag: on every built page exactly once, only when site.toml sets it, and allowed by the CSP."""
|
||||
import base64
|
||||
import hashlib
|
||||
import os
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
WEB = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
sys.path.insert(0, WEB)
|
||||
|
||||
from olt import layout, pages, site # noqa: E402
|
||||
|
||||
TAG_ID = "GTM-TEST1234"
|
||||
LOADER = f'<script async src="https://www.googletagmanager.com/gtm.js?id={TAG_ID}"></script>'
|
||||
|
||||
|
||||
def html_files(root):
|
||||
for base, _, names in os.walk(root):
|
||||
for n in names:
|
||||
if n.endswith(".html"):
|
||||
yield os.path.join(base, n)
|
||||
|
||||
|
||||
def build(out, tag):
|
||||
cfg = os.path.join(os.path.dirname(out), "site.toml")
|
||||
with open(os.path.join(WEB, "site.toml"), encoding="utf-8") as f:
|
||||
text = re.sub(r'(?m)^google_tag = .*\n', "", f.read())
|
||||
with open(cfg, "w", encoding="utf-8") as f:
|
||||
f.write((f'google_tag = "{tag}"\n' if tag else "") + text)
|
||||
code = ("import sys; sys.path.insert(0, %r); from olt import site; "
|
||||
"site.SITE_TOML = %r; site.load.cache_clear(); import build; build.main(['--out', %r])"
|
||||
% (WEB, cfg, out))
|
||||
subprocess.run([sys.executable, "-c", code], check=True, cwd=WEB,
|
||||
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
||||
|
||||
|
||||
class GoogleTagTest(unittest.TestCase):
|
||||
def test_every_built_page_has_the_tag_once_and_none_without_the_setting(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
on, off = os.path.join(tmp, "on", "site"), os.path.join(tmp, "off", "site")
|
||||
for out, tag in ((on, TAG_ID), (off, "")):
|
||||
os.makedirs(os.path.dirname(out))
|
||||
build(out, tag)
|
||||
pages_on = list(html_files(on))
|
||||
self.assertGreater(len(pages_on), 200)
|
||||
for name in ("404.html", os.path.join("saved", "index.html"), "index.html"):
|
||||
self.assertTrue(os.path.isfile(os.path.join(on, name)), name)
|
||||
for path in pages_on:
|
||||
with open(path, encoding="utf-8") as f:
|
||||
text = f.read()
|
||||
head = text[:text.index("</head>")]
|
||||
self.assertEqual(text.count("googletagmanager.com"), 1, path)
|
||||
self.assertEqual(text.count(LOADER), 1, path)
|
||||
self.assertEqual(text.count("gtag('js', new Date());"), 1, path)
|
||||
self.assertIn(LOADER, head, path)
|
||||
for path in html_files(off):
|
||||
with open(path, encoding="utf-8") as f:
|
||||
text = f.read()
|
||||
self.assertNotIn("googletagmanager", text, path)
|
||||
self.assertNotIn("gtag", text, path)
|
||||
|
||||
def test_the_real_setting_is_the_owners_container(self):
|
||||
self.assertEqual(site.load().google_tag, "GTM-WWLZSH6Q")
|
||||
|
||||
def test_the_policy_allows_the_tag_and_its_inline_script_by_hash(self):
|
||||
digest = base64.b64encode(hashlib.sha256(layout.GOOGLE_TAG_INLINE.encode()).digest()).decode()
|
||||
with open(os.path.join(WEB, "static", "_headers"), encoding="utf-8") as f:
|
||||
policy = next(l for l in f if "Content-Security-Policy:" in l)
|
||||
script_src = re.search(r"script-src ([^;]*);", policy).group(1)
|
||||
self.assertIn("https://www.googletagmanager.com", script_src)
|
||||
self.assertIn(f"'sha256-{digest}'", script_src)
|
||||
self.assertNotIn("unsafe-inline", script_src)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -112,8 +112,11 @@ class BuiltSiteTest(unittest.TestCase):
|
||||
target = resolve(OUT, url)
|
||||
if target and not os.path.isfile(target):
|
||||
missing.add((os.path.relpath(path, OUT), url))
|
||||
# The one external asset is the Google tag's loader (layout.GOOGLE_TAG).
|
||||
self.assertFalse(url.startswith(("http://", "https://")) and tag in ("script", "link")
|
||||
and a.get("rel") != "canonical", f"external asset {url} in {path}")
|
||||
and a.get("rel") != "canonical"
|
||||
and not url.startswith("https://www.googletagmanager.com/gtm.js?id="),
|
||||
f"external asset {url} in {path}")
|
||||
self.assertEqual(sorted(missing)[:20], [])
|
||||
|
||||
def test_no_inline_scripts(self):
|
||||
@@ -121,7 +124,10 @@ class BuiltSiteTest(unittest.TestCase):
|
||||
for a, body in parse(path).scripts:
|
||||
if a.get("type") in ("application/json", "application/ld+json"):
|
||||
continue
|
||||
self.assertTrue(a.get("src"), f"inline script in {path}")
|
||||
if not a.get("src"):
|
||||
# The one inline script is the Google tag's data-layer setup, allowed by its hash.
|
||||
self.assertEqual(body.strip(), layout.GOOGLE_TAG_INLINE.strip(), f"inline script in {path}")
|
||||
continue
|
||||
self.assertEqual(body.strip(), "", f"script with src and a body in {path}")
|
||||
|
||||
def test_style_attributes_only_carry_custom_properties(self):
|
||||
|
||||
@@ -128,10 +128,15 @@ class HeaderOnEveryPageTest(unittest.TestCase):
|
||||
for rel in self.files:
|
||||
doc = read_out(rel)
|
||||
self.assertNotIn("<style", doc, rel)
|
||||
inline = 0
|
||||
for tag, a, _ in tree(doc).tags:
|
||||
self.assertFalse([k for k in a if k.startswith("on")], f"{tag} in {rel}")
|
||||
if tag == "script":
|
||||
self.assertTrue(a.get("src") or a.get("type") in ("application/json", "application/ld+json"), rel)
|
||||
if tag == "script" and not (a.get("src") or a.get("type") in ("application/json", "application/ld+json")):
|
||||
inline += 1
|
||||
# The one inline script is the Google tag's data-layer setup, allowed by its hash.
|
||||
self.assertLessEqual(inline, 1, rel)
|
||||
if inline:
|
||||
self.assertIn("<script>" + layout.GOOGLE_TAG_INLINE + "</script>", doc, rel)
|
||||
|
||||
def test_the_switches_name_what_they_do(self):
|
||||
prefs = layout.prefs()
|
||||
|
||||
@@ -170,7 +170,10 @@ class JsonLdTest(unittest.TestCase):
|
||||
rules = serve.parse_headers(os.path.join(OUT, "_headers"))
|
||||
csp = next(v for pat, hs in rules if pat.match("/") for k, v in hs if k.lower() == "content-security-policy")
|
||||
script_src = re.search(r"script-src ([^;]*)", csp).group(1).split()
|
||||
self.assertEqual(script_src, ["'self'"])
|
||||
# Besides 'self': the Google tag's loader and the hash of its one inline script.
|
||||
self.assertEqual(script_src[:2], ["'self'", "https://www.googletagmanager.com"])
|
||||
self.assertEqual(len(script_src), 3)
|
||||
self.assertTrue(script_src[2].startswith("'sha256-"), script_src)
|
||||
self.assertNotIn("unsafe-inline", csp.replace("style-src-attr 'unsafe-inline'", ""))
|
||||
for path, doc in self.pages.items():
|
||||
self.assertNotRegex(doc, r'<script type="application/ld\+json"[^>]*\ssrc=', path)
|
||||
|
||||
@@ -74,7 +74,7 @@ class MaintainerSettings(unittest.TestCase):
|
||||
self.assertIn(f'<a href="{SITE.issue_chooser_url}">open an issue on GitHub</a>', body)
|
||||
section = body[body.index('id="who-maintains"'):]
|
||||
section = section[:section.index("</section>")]
|
||||
for claim in ("public domain", "names the page it was read on", "no ads, no accounts, no tracking and no analytics"):
|
||||
for claim in ("public domain", "names the page it was read on", "no ads and no accounts"):
|
||||
self.assertIn(claim, section)
|
||||
self.assertNotRegex(section, r"[\w.]+@[\w.]+", "no email address")
|
||||
|
||||
|
||||
Reference in new issue
Block a user