#!/usr/bin/env -S uv run --script # /// script # requires-python = ">=3.12" # dependencies = [] # /// """Check that HTML pages run and apply only the inline code their policy names by hash.""" import base64 import hashlib import re import sys import urllib.request def allowed(policy, directive, bodies): sources = re.search(directive + r"([^;]*)", policy)[1].split() assert "'unsafe-inline'" not in sources and "'self'" not in sources, policy hashes = {source[len("'sha256-"):-1] for source in sources if source.startswith("'sha256-")} for body in bodies: digest = base64.b64encode(hashlib.sha256(body.encode()).digest()).decode() assert digest in hashes, f'inline {directive} body not in policy: {body[:60]!r}' if not bodies: assert sources == ["'none'"], policy def check(policy, html): assert '", html, re.S) styles = re.findall(r"", html, re.S) allowed(policy, 'script-src', scripts) allowed(policy, 'style-src', styles) return len(scripts), len(styles) if __name__ == '__main__': base, *pages = sys.argv[1:] for page in pages: with urllib.request.urlopen(base + page) as response: scripts, styles = check(response.headers['content-security-policy'], response.read().decode()) print(f'{page}: {scripts} inline scripts and {styles} inline styles allowed by hash')