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
60
61
62
63
64
65
|
"""
The hub sends a Content-Security-Policy and the other protective headers on
every response — the SPA shell, its assets, and the API alike.
Second-review L5 / third-review M5: previously there were none, so an injection
that landed in the SPA (rendered third-party OG data, a federated group name,
chat content) had nothing stopping it from loading more code or exfiltrating.
"""
import pytest
from meshbay_hub.api.webapp import CSP
def _directive(csp: str, name: str) -> str:
for part in csp.split(";"):
part = part.strip()
if part == name or part.startswith(name + " "):
return part
return ""
@pytest.mark.asyncio
async def test_the_spa_shell_carries_the_policy(client):
r = await client.get("/")
assert r.headers["content-security-policy"] == CSP
assert r.headers["x-content-type-options"] == "nosniff"
assert r.headers["x-frame-options"] == "DENY"
assert "referrer-policy" in r.headers
@pytest.mark.asyncio
async def test_the_api_carries_the_headers_too(client):
r = await client.get("/v1/health")
assert r.status_code == 200
assert "content-security-policy" in r.headers
assert r.headers["x-content-type-options"] == "nosniff"
@pytest.mark.asyncio
async def test_even_a_404_carries_the_headers(client):
# The middleware runs on every response, so a probe for a missing path
# cannot be framed or content-sniffed either.
r = await client.get("/no/such/path")
assert r.status_code == 404
assert r.headers["x-frame-options"] == "DENY"
def test_the_policy_is_locked_down_where_it_matters():
assert "default-src 'none'" in CSP # covers object-src, etc.
assert _directive(CSP, "frame-ancestors") == "frame-ancestors 'none'"
assert _directive(CSP, "base-uri") == "base-uri 'none'"
script = _directive(CSP, "script-src")
# The hub's own origin must not be able to serve executable script (T3):
# 'self' and the wasm token are fine, a bare `https:` scheme is not.
assert "'self'" in script and "'wasm-unsafe-eval'" in script
assert "https:" not in script.split()
def test_recaptcha_is_the_only_external_origin():
hosts = {"https://www.google.com", "https://www.gstatic.com"}
for part in CSP.split(";"):
for tok in part.strip().split()[1:]:
if tok.startswith(("http://", "https://")):
assert tok in hosts, f"unexpected external origin in CSP: {tok}"
|