static-import.py (2571B)
1 import os, sys, json 2 from urllib.parse import unquote 3 4 from wptserve.utils import isomorphic_decode 5 import importlib 6 subresource = importlib.import_module("common.security-features.subresource.subresource") 7 8 def get_csp_value(value): 9 ''' 10 Returns actual CSP header values (e.g. "worker-src 'self'") for the 11 given string used in PolicyDelivery's value (e.g. "worker-src-self"). 12 ''' 13 14 # script-src 15 # Test-related scripts like testharness.js and inline scripts containing 16 # test bodies. 17 # 'unsafe-inline' is added as a workaround here. This is probably not so 18 # bad, as it shouldn't intefere non-inline-script requests that we want to 19 # test. 20 if value == 'script-src-wildcard': 21 return "script-src * 'unsafe-inline'" 22 if value == 'script-src-self': 23 return "script-src 'self' 'unsafe-inline'" 24 # Workaround for "script-src 'none'" would be more complicated, because 25 # - "script-src 'none' 'unsafe-inline'" is handled somehow differently from 26 # "script-src 'none'", i.e. 27 # https://w3c.github.io/webappsec-csp/#match-url-to-source-list Step 3 28 # handles the latter but not the former. 29 # - We need nonce- or path-based additional values to allow same-origin 30 # test scripts like testharness.js. 31 # Therefore, we disable 'script-src-none' tests for now in 32 # `/content-security-policy/spec.src.json`. 33 if value == 'script-src-none': 34 return "script-src 'none'" 35 36 # worker-src 37 if value == 'worker-src-wildcard': 38 return 'worker-src *' 39 if value == 'worker-src-self': 40 return "worker-src 'self'" 41 if value == 'worker-src-none': 42 return "worker-src 'none'" 43 raise Exception('Invalid delivery_value: %s' % value) 44 45 def generate_payload(request): 46 import_url = unquote(isomorphic_decode(request.GET[b'import_url'])) 47 return subresource.get_template(u"static-import.js.template") % { 48 u"import_url": import_url 49 } 50 51 def main(request, response): 52 def payload_generator(_): return generate_payload(request) 53 maybe_additional_headers = {} 54 if b'contentSecurityPolicy' in request.GET: 55 csp = unquote(isomorphic_decode(request.GET[b'contentSecurityPolicy'])) 56 maybe_additional_headers[b'Content-Security-Policy'] = get_csp_value(csp) 57 subresource.respond(request, 58 response, 59 payload_generator = payload_generator, 60 content_type = b"application/javascript", 61 maybe_additional_headers = maybe_additional_headers)