-
-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathtest_http_security.py
More file actions
59 lines (45 loc) · 1.98 KB
/
Copy pathtest_http_security.py
File metadata and controls
59 lines (45 loc) · 1.98 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
"""Baseline response headers must cover success and short-circuit responses."""
import pytest
pytest.importorskip("fastapi")
from fastapi import FastAPI
from fastapi.responses import JSONResponse
from fastapi.testclient import TestClient
from engraphis import http_security
def _client(monkeypatch, *, csp=None, hsts=None):
if csp is None:
monkeypatch.delenv("ENGRAPHIS_CSP", raising=False)
else:
monkeypatch.setenv("ENGRAPHIS_CSP", csp)
if hsts is None:
monkeypatch.delenv("ENGRAPHIS_HSTS", raising=False)
else:
monkeypatch.setenv("ENGRAPHIS_HSTS", hsts)
app = FastAPI()
@app.get("/")
def root():
return {"ok": True}
@app.get("/custom")
def custom():
return JSONResponse({"ok": True}, headers={"Referrer-Policy": "no-referrer"})
http_security.install(app)
http_security.install(app) # idempotent
return TestClient(app)
def test_baseline_headers_apply_without_hsts_on_plain_http(monkeypatch):
response = _client(monkeypatch).get("/")
assert response.headers["X-Content-Type-Options"] == "nosniff"
assert response.headers["X-Frame-Options"] == "DENY"
assert "frame-ancestors 'none'" in response.headers["Content-Security-Policy"]
assert "Strict-Transport-Security" not in response.headers
def test_https_proxy_response_gets_hsts_and_route_override_wins(monkeypatch):
monkeypatch.setenv("ENGRAPHIS_FORWARDED_ALLOW_IPS", "*")
response = _client(monkeypatch).get(
"/custom", headers={"X-Forwarded-Proto": "https"}
)
assert response.headers["Strict-Transport-Security"] == http_security.DEFAULT_HSTS
assert response.headers["Referrer-Policy"] == "no-referrer"
def test_empty_environment_overrides_disable_csp_and_hsts(monkeypatch):
response = _client(monkeypatch, csp="", hsts="").get(
"/", headers={"X-Forwarded-Proto": "https"}
)
assert "Content-Security-Policy" not in response.headers
assert "Strict-Transport-Security" not in response.headers