Hi,

You may have come across the (relatively) new subresource integrity 
(SRI)[1] security feature that is available in Chrome and Firefox (its 
coming to Edge[2] and Safari[3]) - it enables a hash to be provided as an 
attribute on a linked JavaScript or CSS tag that the browser can test 
against once the file has downloaded to ensure that it hasn't been tampered 
with. Its main use case is for when you are using a third party CDN for 
your static files. I have been looking at how best to implement it in/with 
Django and believe that incorporating it into the 'staticfiles' framework 
may be the best we to go.

Currently 'ManifestStaticFilesStorage' and 'CachedStaticFilesStorage' store 
a simple dict mapping file path to path was a hash in the filename for 
cache busting. I would like to propose that this is changed to a mapping of 
file path to a tuple of (filepath_with_hash, hash_algo, file_hash_base64). 
This allows us to add the subresource integrity attribute to any linked 
file that is managed by either of those storages.

I have mocked up how this could be done [4], the changes I made 
to django/contrib/staticfiles/storage.py are here [5].

There is then a simple template tag that includes the SRI token:
{% static_sri_token 'path/to/file.js' %}
>>> sha256-ATJWBF9ZhO9FS8vr9wEhYO+W9vLtd3jRZVmEdC5EL0s=

or the whole attribute:
{% static_sri_attrs 'path/to/file.js' %}
>>> integrity="sha256-ATJWBF9ZhO9FS8vr9wEhYO+W9vLtd3jRZVmEdC5EL0s=" 
crossorigin="anonymous"

By incorporating this into Django rather than a third party app it would 
ensure that everyone gains access to this new security feature for free - 
it can be documented with the static files docs, encouraging its use and 
help to secure more peoples projects.

Please note that my code is just a proof of principle, and I would be very 
happy to hear if anyone has any thought on a better way of implementing the 
feature.

[1]: 
https://developer.mozilla.org/en-US/docs/Web/Security/Subresource_Integrity
[2]: 
https://developer.microsoft.com/en-us/microsoft-edge/platform/status/subresourceintegrity/
[3]: https://webkit.org/status/#feature-subresource-integrity
[4]: https://gist.github.com/samwillis/90b5391f9dafc0662ae2af7b8f827bd9
[5]: 
https://gist.github.com/samwillis/90b5391f9dafc0662ae2af7b8f827bd9/revisions#diff-80f99275da9c9dbb59bb177e83b9f13e

-- 
You received this message because you are subscribed to the Google Groups 
"Django developers  (Contributions to Django itself)" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-developers+unsubscr...@googlegroups.com.
To post to this group, send email to django-developers@googlegroups.com.
Visit this group at https://groups.google.com/group/django-developers.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-developers/26ac849d-d6d1-4e9e-aa14-d16b0552a43f%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to