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
@@ -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