Add CSP for HTML5 responses
This commit is contained in:
@@ -6,6 +6,15 @@ from fastapi.responses import Response, StreamingResponse
|
|||||||
from fastapi.staticfiles import StaticFiles
|
from fastapi.staticfiles import StaticFiles
|
||||||
|
|
||||||
HTML5_SECURITY_HEADERS = {"X-Content-Type-Options": "nosniff"}
|
HTML5_SECURITY_HEADERS = {"X-Content-Type-Options": "nosniff"}
|
||||||
|
HTML5_CONTENT_SECURITY_POLICY = (
|
||||||
|
"default-src 'self'; "
|
||||||
|
"script-src 'self'; "
|
||||||
|
"style-src 'self'; "
|
||||||
|
"connect-src 'self'; "
|
||||||
|
"img-src 'self' data:; "
|
||||||
|
"base-uri 'self'; "
|
||||||
|
"form-action 'self'"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
class Html5StaticFiles(StaticFiles):
|
class Html5StaticFiles(StaticFiles):
|
||||||
@@ -29,7 +38,11 @@ def html5_response(fragment: str) -> Response:
|
|||||||
return Response(
|
return Response(
|
||||||
fragment,
|
fragment,
|
||||||
media_type="text/html; charset=utf-8",
|
media_type="text/html; charset=utf-8",
|
||||||
headers={"Cache-Control": "no-cache, no-transform", **HTML5_SECURITY_HEADERS},
|
headers={
|
||||||
|
"Cache-Control": "no-cache, no-transform",
|
||||||
|
"Content-Security-Policy": HTML5_CONTENT_SECURITY_POLICY,
|
||||||
|
**HTML5_SECURITY_HEADERS,
|
||||||
|
},
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -57,6 +57,15 @@ def assert_html5_response_contract(response, *markers: str, full_page: bool = Fa
|
|||||||
assert "text/html" in response.headers["content-type"]
|
assert "text/html" in response.headers["content-type"]
|
||||||
assert response.headers["cache-control"] == "no-cache, no-transform"
|
assert response.headers["cache-control"] == "no-cache, no-transform"
|
||||||
assert response.headers["x-content-type-options"] == "nosniff"
|
assert response.headers["x-content-type-options"] == "nosniff"
|
||||||
|
assert response.headers["content-security-policy"] == (
|
||||||
|
"default-src 'self'; "
|
||||||
|
"script-src 'self'; "
|
||||||
|
"style-src 'self'; "
|
||||||
|
"connect-src 'self'; "
|
||||||
|
"img-src 'self' data:; "
|
||||||
|
"base-uri 'self'; "
|
||||||
|
"form-action 'self'"
|
||||||
|
)
|
||||||
assert_html5_contract(response.text, *markers, full_page=full_page)
|
assert_html5_contract(response.text, *markers, full_page=full_page)
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user