Skip to content

Commit f3efc94

Browse files
committed
feat: Create CSP class
1 parent 12cf7c0 commit f3efc94

File tree

1 file changed

+56
-0
lines changed

1 file changed

+56
-0
lines changed

http_csp/csp.py

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
from typing import Optional
2+
3+
4+
class CSP:
5+
base_uri: list[str]
6+
child_src: list[str]
7+
connect_src: list[str]
8+
default_src: list[str]
9+
font_src: list[str]
10+
form_action: list[str]
11+
frame_ancestors: list[str]
12+
frame_src: list[str]
13+
img_src: list[str]
14+
manifest_src: list[str]
15+
media_src: list[str]
16+
object_src: list[str]
17+
report_sample: list[str]
18+
report_to: list[str]
19+
sandbox: list[str]
20+
script_src: list[str]
21+
script_src_attr: list[str]
22+
script_src_elem: list[str]
23+
strict_dynamic: list[str]
24+
style_src: list[str]
25+
style_src_attr: list[str]
26+
style_src_elem: list[str]
27+
unsafe_hashes: list[str]
28+
upgrade_insecure_requests: list[str]
29+
worker_src: list[str]
30+
31+
def __init__(self, policy: Optional[str] = None):
32+
"""
33+
Initialize a CSP object from a Content Security Policy string.
34+
"""
35+
if not policy:
36+
return
37+
policy = policy.strip().removesuffix(";")
38+
policy_dict = {
39+
p.split()[0].replace("-", "_"): p.split()[1:] for p in policy.split(";")
40+
}
41+
for key in policy_dict.keys():
42+
if key not in self.__annotations__.keys():
43+
raise ValueError(
44+
f'"{key.replace("_", "-")}" is not a valid CSP directive'
45+
)
46+
self.__dict__ = policy_dict
47+
48+
def generate(self) -> str:
49+
"""
50+
Generate a Content Security Policy string.
51+
"""
52+
policy = "; ".join(
53+
[f'{k.replace("_", "-")} {(" ").join(v)}' for k, v in self.__dict__.items()]
54+
).strip()
55+
policy += ";"
56+
return policy

0 commit comments

Comments
 (0)