"""Every script the viewer pages load from a CDN is pinned to an exact version and carries an integrity hash.
python -I tests/test_viewer_cdn_integrity.py
Reads viewer/*.html as text: no browser, no network, standard library only. The hashes themselves were computed
from the CDN files (openssl dgst -sha384 -binary FILE | openssl base64 -A); this test checks that every remote URL
has one, in the right form, and that the import map and the modulepreload links agree.
"""
from __future__ import annotations
import base64
import json
from pathlib import Path
import re
import unittest
ROOT = Path(__file__).resolve().parents[1]
VIEWER = ROOT / "viewer"
_URL = re.compile(r"https?://[^\s\"'<>\\]+")
# Quoted attribute values may hold '>' (the fallback writes a whole ', re.S)
_MODULE = re.compile(r'', re.S)
_IMPORT_FROM = re.compile(r"""^\s*import\b[^;]*?\bfrom\s*["']([^"']+)["']""", re.M)
# An exact release: three@0.160.0 on npm CDNs, three.js/r128 on cdnjs. A range, a tag or no version fails.
_EXACT_VERSION = re.compile(r"@\d+\.\d+\.\d+/|/r\d+/")
def _sri_ok(value: str) -> bool:
algo, _, digest = value.partition("-")
sizes = {"sha256": 32, "sha384": 48, "sha512": 64}
if algo not in ("sha384", "sha512"):
return False
try:
return len(base64.b64decode(digest, validate=True)) == sizes[algo]
except ValueError:
return False
def _attrs(text: str) -> dict[str, str]:
return {k.lower(): v[1:-1] for k, v in _ATTR.findall(text)}
def problems(html: str) -> list[str]:
"""What is wrong with the remote scripts of one viewer page; empty when every one is pinned and hashed."""
out: list[str] = []
covered: set[str] = set() # remote URLs whose bytes are checked by an integrity hash
prefixes: set[str] = set() # import map prefixes ("three/addons/" -> a CDN folder)
preload: dict[str, str] = {}
for kind, raw in _TAG.findall(html):
attrs = _attrs(raw)
urls = _URL.findall(raw)
if not urls:
continue
integrity = attrs.get("integrity", "")
if not _sri_ok(integrity):
out.append(f"<{kind}> loading {urls[0]} has no sha384/sha512 integrity hash")
continue
if attrs.get("crossorigin") != "anonymous":
out.append(f"<{kind}> loading {urls[0]} needs crossorigin=\"anonymous\" for its integrity check")
if kind.lower() == "link":
if attrs.get("rel") != "modulepreload":
out.append(f" loading {urls[0]} is not a modulepreload")
preload[attrs.get("href", "")] = integrity
# A '
self.assertIn("no sha384/sha512 integrity hash", problems(html)[0])
def test_classic_script_with_integrity_but_floating_version(self):
html = f''
self.assertEqual(problems(html), ["https://cdn.example/lib@1/x.js is not pinned to an exact version"])
def test_integrity_needs_crossorigin(self):
html = f''
self.assertIn("crossorigin", problems(html)[0])
def test_sha256_and_bad_base64_are_rejected(self):
for value in ("sha256-" + base64.b64encode(bytes(32)).decode(), "sha384-abc", "sha384-" + "A" * 63 + "!"):
html = f''
self.assertTrue(problems(html), value)
def test_fallback_must_reuse_the_hash(self):
bad = (f'")
self.assertIn("does not reuse", problems(bad)[0])
good = (f'")
self.assertEqual(problems(good), [])
def test_import_map_without_integrity(self):
html = ('\n'
'')
found = problems(html)
self.assertIn("import map entry lib -> https://cdn.example/lib@1.2.3/lib.js has no integrity hash", found)
def test_import_through_prefix_needs_a_hash(self):
html = ('\n'
f'\n'
'')
found = problems(html)
self.assertIn("module import lib/a.js -> https://cdn.example/lib@1.2.3/a.js has no integrity hash", found)
def test_preload_and_map_must_agree(self):
other = "sha384-" + base64.b64encode(bytes([1]) * 48).decode()
html = ('\n'
f'')
self.assertIn("disagree", problems(html)[0])
if __name__ == "__main__":
unittest.main()