bookly/tests/test_server.py

77 lines
2.7 KiB
Python

"""Server and static asset tests for Bookly's HTTP surface.
Goal: verify the shared Datadog RUM bootstrap is exposed on both public HTML
pages, and verify the Content-Security-Policy permits only the Datadog
origins required for RUM and Session Replay.
"""
from __future__ import annotations
from pathlib import Path
from fastapi.testclient import TestClient
import server
client = TestClient(server.app)
_REPO_ROOT = Path(__file__).resolve().parent.parent
_DATADOG_SCRIPT_ORIGIN = "https://www.datadoghq-browser-agent.com"
_DATADOG_RUM_INTAKE_ORIGIN = "https://browser-intake-datadoghq.com"
def _read_repo_text(relative_path: str) -> str:
path = _REPO_ROOT / relative_path
assert path.is_file(), f"expected file at {path}"
text = path.read_text(encoding="utf-8")
assert text, f"expected non-empty file at {path}"
return text
def test_static_index_html_loads_shared_rum_bootstrap():
response = client.get("/static/index.html")
assert response.status_code == 200
assert "/static/rum.js" in response.text
def test_architecture_page_loads_shared_rum_bootstrap():
response = client.get("/architecture")
assert response.status_code == 200
assert "/static/rum.js" in response.text
def test_static_page_csp_allows_only_required_datadog_origins():
response = client.get("/static/index.html")
csp = response.headers["content-security-policy"]
assert response.status_code == 200
assert f"script-src 'self' {_DATADOG_SCRIPT_ORIGIN}" in csp
assert f"connect-src 'self' {_DATADOG_RUM_INTAKE_ORIGIN}" in csp
assert "worker-src blob:" in csp
assert "style-src 'self'" in csp
def test_architecture_page_csp_keeps_inline_styles_and_datadog_allowlist():
response = client.get("/architecture")
csp = response.headers["content-security-policy"]
assert response.status_code == 200
assert f"script-src 'self' {_DATADOG_SCRIPT_ORIGIN}" in csp
assert f"connect-src 'self' {_DATADOG_RUM_INTAKE_ORIGIN}" in csp
assert "worker-src blob:" in csp
assert "style-src 'self' 'unsafe-inline'" in csp
def test_rum_bootstrap_file_contains_expected_exact_configuration():
rum_js = _read_repo_text("static/rum.js")
assert "bookly.codyborders.com" in rum_js
assert "ad60336f-85fe-4631-9469-973180243552" in rum_js
assert "pube161402da279b685acbb640a4366129b" in rum_js
assert 'service: "csb"' in rum_js
assert 'env: "prod"' in rum_js
assert 'version: "0.1"' in rum_js
assert "https://www.datadoghq-browser-agent.com/us1/v6/datadog-rum.js" in rum_js
def test_runtime_injection_leaves_architecture_artifact_unchanged():
architecture_html = _read_repo_text("static/architecture.html")
assert "/static/rum.js" not in architecture_html