test_security_headers.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  1. """Integration tests for security_headers_middleware (#1191).
  2. Default behaviour is strict: ``X-Frame-Options: SAMEORIGIN`` plus
  3. ``frame-ancestors 'none'`` on the catch-all route, ``frame-ancestors 'self'``
  4. on /gcode-viewer/. Operators can opt into iframe embedding from trusted
  5. origins (e.g. Home Assistant on a different port) via the
  6. ``TRUSTED_FRAME_ORIGINS`` env var; when set, X-Frame-Options is dropped and
  7. ``frame-ancestors`` includes the allowlist.
  8. """
  9. from __future__ import annotations
  10. import pytest
  11. from httpx import AsyncClient
  12. # ─── helpers ──────────────────────────────────────────────────────────────
  13. def _parse_origins(value: str) -> tuple[str, ...]:
  14. """Re-import the parser with a specific env var set, return its result.
  15. Uses a fresh import so the module-level _TRUSTED_FRAME_ORIGINS is
  16. re-evaluated against the patched os.environ.
  17. """
  18. import os
  19. from backend.app import main as main_module
  20. old = os.environ.get("TRUSTED_FRAME_ORIGINS")
  21. try:
  22. if value is None:
  23. os.environ.pop("TRUSTED_FRAME_ORIGINS", None)
  24. else:
  25. os.environ["TRUSTED_FRAME_ORIGINS"] = value
  26. # Function reads from os.environ each call.
  27. return main_module._parse_trusted_frame_origins()
  28. finally:
  29. if old is None:
  30. os.environ.pop("TRUSTED_FRAME_ORIGINS", None)
  31. else:
  32. os.environ["TRUSTED_FRAME_ORIGINS"] = old
  33. # ─── env-var parsing ──────────────────────────────────────────────────────
  34. class TestParseTrustedFrameOrigins:
  35. """Unit tests for _parse_trusted_frame_origins."""
  36. def test_empty_env_returns_empty_tuple(self):
  37. assert _parse_origins("") == ()
  38. def test_unset_env_returns_empty_tuple(self):
  39. assert _parse_origins(None) == () # type: ignore[arg-type]
  40. def test_single_origin(self):
  41. assert _parse_origins("http://homeassistant.local:8123") == ("http://homeassistant.local:8123",)
  42. def test_multiple_origins(self):
  43. result = _parse_origins("http://homeassistant.local:8123,https://ha.example.com")
  44. assert result == ("http://homeassistant.local:8123", "https://ha.example.com")
  45. def test_whitespace_around_entries_stripped(self):
  46. result = _parse_origins(" http://a.local:1 , https://b.local:2 ")
  47. assert result == ("http://a.local:1", "https://b.local:2")
  48. def test_empty_segment_skipped(self):
  49. result = _parse_origins("http://a.local,,https://b.local")
  50. assert result == ("http://a.local", "https://b.local")
  51. def test_non_http_scheme_dropped(self):
  52. # ftp://, javascript:, file:// etc. — never a valid frame ancestor.
  53. assert _parse_origins("ftp://attacker.example,http://ok.local") == ("http://ok.local",)
  54. assert _parse_origins("javascript:alert(1)") == ()
  55. def test_missing_host_dropped(self):
  56. # "http://" with no host
  57. assert _parse_origins("http://") == ()
  58. def test_path_dropped(self):
  59. # frame-ancestors only takes scheme://host[:port], no path
  60. assert _parse_origins("http://ha.local/dashboard") == ()
  61. def test_query_or_fragment_dropped(self):
  62. assert _parse_origins("http://ha.local?foo=1") == ()
  63. assert _parse_origins("http://ha.local#frag") == ()
  64. def test_wildcard_in_host_dropped(self):
  65. # Wildcards would defeat the allowlist purpose; reject explicitly.
  66. assert _parse_origins("http://*.example.com") == ()
  67. def test_root_path_kept(self):
  68. # Trailing slash is a degenerate but harmless path; treat as bare host.
  69. assert _parse_origins("http://ha.local:8123/") == ("http://ha.local:8123",)
  70. # ─── HTTP integration: middleware emits expected headers ──────────────────
  71. @pytest.mark.asyncio
  72. @pytest.mark.integration
  73. async def test_default_headers_strict(async_client: AsyncClient, monkeypatch):
  74. """Without env var: X-Frame-Options=SAMEORIGIN and frame-ancestors 'none'."""
  75. monkeypatch.delenv("TRUSTED_FRAME_ORIGINS", raising=False)
  76. # Re-import the module-level constant so the middleware closes over the new value.
  77. from backend.app import main as main_module
  78. monkeypatch.setattr(main_module, "_TRUSTED_FRAME_ORIGINS", ())
  79. resp = await async_client.get("/api/v1/auth/status")
  80. assert resp.headers.get("X-Frame-Options") == "SAMEORIGIN"
  81. assert "frame-ancestors 'none'" in resp.headers.get("Content-Security-Policy", "")
  82. @pytest.mark.asyncio
  83. @pytest.mark.integration
  84. async def test_overlay_route_allows_same_origin_framing(async_client: AsyncClient, monkeypatch):
  85. """#1422 — the overlay is framed same-origin by the URL builder's preview.
  86. 'none' blocks that too, which is why the preview showed Firefox's "will not
  87. allow Firefox to display the page if another site has embedded it". 'self'
  88. permits only a framer on this origin — Bambuddy's own UI — so a
  89. clickjacking page on another host is refused exactly as before.
  90. """
  91. from backend.app import main as main_module
  92. monkeypatch.setattr(main_module, "_TRUSTED_FRAME_ORIGINS", ())
  93. resp = await async_client.get("/overlay/1")
  94. csp = resp.headers.get("Content-Security-Policy", "")
  95. assert "frame-ancestors 'self';" in csp
  96. # The legacy header already permitted same-origin framing; only the CSP was
  97. # blocking it. Assert it still says so rather than being dropped.
  98. assert resp.headers.get("X-Frame-Options") == "SAMEORIGIN"
  99. @pytest.mark.asyncio
  100. @pytest.mark.integration
  101. async def test_other_spa_routes_still_refuse_all_framing(async_client: AsyncClient, monkeypatch):
  102. """The #1422 carve-out is the overlay path only — everything else keeps
  103. 'none', including paths that merely start with something similar."""
  104. from backend.app import main as main_module
  105. monkeypatch.setattr(main_module, "_TRUSTED_FRAME_ORIGINS", ())
  106. for path in ("/", "/settings", "/printers", "/overlays", "/camwall"):
  107. resp = await async_client.get(path)
  108. csp = resp.headers.get("Content-Security-Policy", "")
  109. assert "frame-ancestors 'none'" in csp, f"{path} must not be framable"
  110. @pytest.mark.asyncio
  111. @pytest.mark.integration
  112. async def test_trusted_origins_relaxes_csp_and_drops_xfo(async_client: AsyncClient, monkeypatch):
  113. """With env var set: X-Frame-Options is absent, frame-ancestors lists the origins."""
  114. from backend.app import main as main_module
  115. monkeypatch.setattr(
  116. main_module,
  117. "_TRUSTED_FRAME_ORIGINS",
  118. ("http://homeassistant.local:8123",),
  119. )
  120. resp = await async_client.get("/api/v1/auth/status")
  121. assert "X-Frame-Options" not in resp.headers
  122. csp = resp.headers.get("Content-Security-Policy", "")
  123. assert "frame-ancestors 'self' http://homeassistant.local:8123;" in csp
  124. assert "'none'" not in csp.split("frame-ancestors")[1].split(";")[0]
  125. @pytest.mark.asyncio
  126. @pytest.mark.integration
  127. async def test_trusted_origins_applies_to_docs_branch(async_client: AsyncClient, monkeypatch):
  128. """The /docs CSP also honors the allowlist (consistent with main app)."""
  129. from backend.app import main as main_module
  130. monkeypatch.setattr(
  131. main_module,
  132. "_TRUSTED_FRAME_ORIGINS",
  133. ("https://ha.example.com",),
  134. )
  135. resp = await async_client.get("/docs")
  136. csp = resp.headers.get("Content-Security-Policy", "")
  137. assert "frame-ancestors 'self' https://ha.example.com;" in csp
  138. @pytest.mark.asyncio
  139. @pytest.mark.integration
  140. async def test_default_block_img_src_excludes_https(async_client: AsyncClient, monkeypatch):
  141. """#1333 regression guard: the default SPA CSP must NOT allow img-src https:.
  142. Bambuddy's policy for external images is a backend proxy (see
  143. /api/v1/makerworld/thumbnail and /api/v1/auth/oidc/providers/{id}/icon),
  144. not a CSP relaxation. If a future change adds ``https:`` to img-src to
  145. "fix" a broken-image, the proxy pattern silently degrades into a
  146. do-nothing layer and the entire SPA gains a hot-link surface.
  147. """
  148. from backend.app import main as main_module
  149. monkeypatch.setattr(main_module, "_TRUSTED_FRAME_ORIGINS", ())
  150. resp = await async_client.get("/api/v1/auth/status")
  151. csp = resp.headers.get("Content-Security-Policy", "")
  152. # Extract the img-src directive — splits on ';' for safety against
  153. # neighbouring directives that happen to contain the substring.
  154. img_src_directive = next(
  155. (d.strip() for d in csp.split(";") if d.strip().startswith("img-src")),
  156. "",
  157. )
  158. assert img_src_directive, f"img-src directive missing from CSP: {csp!r}"
  159. assert "https:" not in img_src_directive, (
  160. f"img-src must not allow arbitrary https: hosts (proxy external images instead); got: {img_src_directive!r}"
  161. )
  162. # Sanity: the legitimately allowed scheme sources are still present.
  163. assert "'self'" in img_src_directive
  164. assert "data:" in img_src_directive
  165. assert "blob:" in img_src_directive
  166. @pytest.mark.asyncio
  167. @pytest.mark.integration
  168. async def test_other_security_headers_unchanged(async_client: AsyncClient, monkeypatch):
  169. """Other headers (X-Content-Type-Options, Referrer-Policy) are not affected."""
  170. from backend.app import main as main_module
  171. # Test in both modes — headers should be the same regardless.
  172. for origins in [(), ("http://homeassistant.local:8123",)]:
  173. monkeypatch.setattr(main_module, "_TRUSTED_FRAME_ORIGINS", origins)
  174. resp = await async_client.get("/api/v1/auth/status")
  175. assert resp.headers.get("X-Content-Type-Options") == "nosniff"
  176. assert resp.headers.get("Referrer-Policy") == "strict-origin-when-cross-origin"
  177. # ─── #1460: nonce-based script-src so Cloudflare-injected scripts pass ────
  178. @pytest.mark.asyncio
  179. @pytest.mark.integration
  180. async def test_spa_csp_includes_per_request_script_nonce(async_client: AsyncClient):
  181. """SPA CSP must stamp a fresh `'nonce-…'` token into script-src (#1460).
  182. Cloudflare's bot-detection inline script is injected after our response
  183. leaves the app, with a per-load hash that defeats hash allowlisting. When
  184. a nonce is present in the CSP header, Cloudflare clones it onto its
  185. injected `<script>` and the CSP passes without `'unsafe-inline'`.
  186. """
  187. import re
  188. resp = await async_client.get("/api/v1/auth/status")
  189. csp = resp.headers.get("Content-Security-Policy", "")
  190. # Pull out the script-src directive (split on ';' so neighbours don't confuse us).
  191. script_src = next(
  192. (d.strip() for d in csp.split(";") if d.strip().startswith("script-src")),
  193. "",
  194. )
  195. assert script_src, f"script-src directive missing: {csp!r}"
  196. assert "'self'" in script_src, f"script-src must still allow 'self': {script_src!r}"
  197. # Nonce token is `'nonce-<base64url>'` where the inner value is
  198. # secrets.token_urlsafe(16) — about 22 url-safe chars.
  199. assert re.search(r"'nonce-[A-Za-z0-9_-]{16,}'", script_src), (
  200. f"script-src must include a 'nonce-…' token: {script_src!r}"
  201. )
  202. # We deliberately did NOT add 'unsafe-inline' alongside the nonce — that
  203. # would defeat the purpose of using a nonce in the first place.
  204. assert "'unsafe-inline'" not in script_src, (
  205. f"script-src must not relax to 'unsafe-inline' on the SPA route: {script_src!r}"
  206. )
  207. @pytest.mark.asyncio
  208. @pytest.mark.integration
  209. async def test_spa_csp_nonce_changes_per_request(async_client: AsyncClient):
  210. """A nonce is only useful if it's fresh per request (#1460)."""
  211. import re
  212. nonce_re = re.compile(r"'nonce-([A-Za-z0-9_-]+)'")
  213. nonces = set()
  214. for _ in range(5):
  215. resp = await async_client.get("/api/v1/auth/status")
  216. csp = resp.headers.get("Content-Security-Policy", "")
  217. m = nonce_re.search(csp)
  218. assert m, f"no nonce in CSP: {csp!r}"
  219. nonces.add(m.group(1))
  220. # 5 random 16-byte tokens collide with probability ~0 — anything less
  221. # than all-5-distinct means we're handing out a stale/global nonce.
  222. assert len(nonces) == 5, f"nonces should be per-request, got {nonces!r}"
  223. # ─── #1460: HEAD on PWA bootstrap routes (manifest / sw / sw-register) ───
  224. @pytest.mark.asyncio
  225. @pytest.mark.integration
  226. @pytest.mark.parametrize("path", ["/manifest.json", "/sw.js", "/sw-register.js"])
  227. async def test_pwa_bootstrap_routes_accept_head(async_client: AsyncClient, path: str):
  228. """Scanners and `curl -I` HEAD-probe these — must not 405 (#1460).
  229. Previously these were `@app.get` only, so HEAD returned 405 Method Not
  230. Allowed and looked like a manifest/SW server-side bug when debugging
  231. Cloudflare-fronted deployments.
  232. """
  233. resp = await async_client.head(path)
  234. # 200 if static asset is present in the test environment, 404 if it's
  235. # not packaged in this checkout — but never 405.
  236. assert resp.status_code != 405, f"HEAD {path} returned 405 — route must accept HEAD as well as GET"