fix: injecte le nonce CSP dans les pages /docs et /redoc générées par FastAPI (BUG-106)
CI / lint (push) Successful in 2m46s
CI / security (push) Successful in 2m1s
CI / test (push) Successful in 4m40s
CI / build (push) Successful in 1m52s
CI / e2e (push) Successful in 15m57s

This commit is contained in:
2026-10-02 22:04:25 -04:00
parent d2734dc8ce
commit d6fa8c7bb1
12 changed files with 84 additions and 14 deletions
+32
View File
@@ -80,3 +80,35 @@ def test_nonce_matches_injected_html(client):
nonce = _nonce_of(resp.headers.get("content-security-policy"))
assert nonce, path
assert f'nonce="{nonce}"' in resp.text, path
def test_docs_inline_script_nonced(client):
"""BUG-106 : /docs (script inline d'init Swagger) porte le nonce de son
en-tête — sinon script-src sans 'unsafe-inline' rend la page blanche."""
resp = client.get("/docs")
assert resp.status_code == 200
nonce = _nonce_of(resp.headers.get("content-security-policy"))
assert nonce
assert f'nonce="{nonce}"' in resp.text, "/docs : script inline sans nonce"
# Le bundle externe (jsdelivr) reste tel quel, couvert par script-src.
assert "<script src=" in resp.text
def test_redoc_served_with_csp(client):
"""/redoc n'a aucun script inline (bundle externe seul) : il est servi
avec sa CSP sans aucune injection nécessaire."""
resp = client.get("/redoc")
assert resp.status_code == 200
assert _nonce_of(resp.headers.get("content-security-policy"))
assert "<script src=" in resp.text
assert "<script nonce=" not in resp.text
def test_docs_external_bundle_not_nonced(client):
"""L'injection ne touche que les balises <script> exécutables sans src."""
from backend.csp import inject_csp_nonce
html = '<script src="https://cdn.jsdelivr.net/npm/swagger-ui-dist@5/x.js"></script><script>init()</script>'
out = inject_csp_nonce(html, NONCE)
assert out.count(f'nonce="{NONCE}"') == 1
assert '<script src="https://cdn.jsdelivr.net/npm/swagger-ui-dist@5/x.js">' in out