"""Hash only trusted source inline scripts at image build time for strict CSP.""" import base64 import hashlib import os from pathlib import Path import re root=Path('/build') hashes=[] for html in [root/'dtf-site.html',*(root/'local/static').glob('*.html')]: for attributes,body in re.findall(r']*)>(.*?)',html.read_text(),re.S|re.I): if not re.search(r'\bsrc\s*=',attributes,re.I): hashes.append("'sha256-"+base64.b64encode(hashlib.sha256(body.encode()).digest()).decode()+"'") template=Path(os.environ.get('NGINX_TEMPLATE', root/'local/nginx.conf.template')).read_text() (root/'default.conf.template').write_text(template.replace('@SCRIPT_HASHES@',' '.join(hashes)))