miracle2k / webassets

Asset management for Python web development.
BSD 2-Clause "Simplified" License
924 stars 259 forks source link

Sub-resource integrity #521

Closed VorpalBlade closed 4 years ago

VorpalBlade commented 5 years ago

This pull request implements #494, by adding a flag to the Bundle.urls() method (calculate_sri) that defaults to false. When set to true it changes the return value from a list of URIs to a list of (using syntax based on Python 3's typing module):

{'uri': str, sri: Optional[str]}

For example:

[{'uri': '/a',
  'sri': 'sha384-OLBgp1GsljhM2TJ+sbHjaiH9txEUvgdDTAzHv2P24donTt6/529l+9Ua0vFImLlb'}]

This is then used by the jinja2 module to expose a new variable ASSERT_SRI. that can be used something like this:

{%- assets filters="cssutils", output="css/min.css", "css/reset.css", "css/site.css" -%}
    <link rel="stylesheet" href="{{ ASSET_URL }}" integrity="{{ ASSET_SRI }}">
{%- endassets -%}

Note that the SRI is not computed for remote resources, in that case None is returned. This should be handled properly, but obviously it is something that the template write will have to deal with if it can happen in their environment (and they also want to use the integrity features for local resources).

This could be extended in the future to download and calculate the hash for remote resources, but there is an inherent trust/security issue, should that resource change between builds when you don't expect it to, so I'm not sure it would be a good idea.

This has been tested on Python 2.7 and 3.7, I do not have easy ability to test anything else, and there seems to be some issue with failing unit tests in general for this project in the Travis CI setup.

miracle2k commented 4 years ago

Sorry for the delay in getting this merged. Good work.