-
Notifications
You must be signed in to change notification settings - Fork 10
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Apply nonces to CSP in central module
- Loading branch information
1 parent
94f47aa
commit fe116cc
Showing
4 changed files
with
46 additions
and
38 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
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
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,42 @@ | ||
import secrets | ||
import typing as t | ||
from dataclasses import dataclass, field | ||
|
||
from werkzeug.datastructures import ContentSecurityPolicy | ||
|
||
|
||
def generate_nonce() -> str: | ||
return secrets.token_hex(32) | ||
|
||
|
||
def ensure_items(current_items: str | None, items: t.Iterable[str]) -> str: | ||
_cur = set(current_items.split()) if current_items else set() | ||
return " ".join(_cur | set(items)) | ||
|
||
|
||
@dataclass(frozen=True) | ||
class NonceInfo: | ||
|
||
"""struct to remember which nonces have been generated for inline scripts""" | ||
|
||
style_nonces: list[str] = field(default_factory=list) | ||
|
||
script_nonces: list[str] = field(default_factory=list) | ||
|
||
def add_style_nonce(self) -> str: | ||
self.style_nonces.append(n := generate_nonce()) | ||
return n | ||
|
||
def add_script_nonce(self) -> str: | ||
self.script_nonces.append(n := generate_nonce()) | ||
return n | ||
|
||
def apply_to_csp(self, csp: ContentSecurityPolicy) -> ContentSecurityPolicy: | ||
"""Add nonces to the CSP object""" | ||
csp.script_src = ensure_items( | ||
csp.script_src, (f"'nonce-{n}'" for n in self.script_nonces) | ||
) | ||
csp.style_src = ensure_items( | ||
csp.style_src, (f"'nonce-{n}'" for n in self.style_nonces) | ||
) | ||
return csp |
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