forked from PGScatalog/PGS_Catalog
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request PGScatalog#406 from PGScatalog/fix/csp_nonce_cache
Fix CSP "nonce" not being refreshed if the page is loaded from backend cache
- Loading branch information
Showing
2 changed files
with
31 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,24 @@ | ||
from django.core.cache.backends.locmem import LocMemCache | ||
import re | ||
|
||
|
||
class RemoveNonceFromCacheBackend(LocMemCache): | ||
"""If a page is cached on the server and contains CSP nonces, the value of the nonce | ||
if not refreshed making it not matching the nonce any new HTTP response header, and | ||
more problematically giving the same nonce to all clients. This subclass removes | ||
the nonce completely from a cached page, which will be put back downstream by the | ||
middleware with the correct value of the new request.""" | ||
def get(self, key, default=None, version=None): | ||
result = super().get(key, default, version) | ||
if result is not None: | ||
if (key.startswith('views.decorators.cache.cache_page') | ||
and hasattr(result, 'content') | ||
and 'text/html' in result.get('Content-Type', '')): | ||
# Remove every html nonce="..." attribute from cached content | ||
result.content = re.sub( | ||
r' nonce="[^"]+"', | ||
'', | ||
result.content.decode('utf-8'), | ||
flags=re.IGNORECASE | ||
).encode('utf-8') | ||
return result |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters