Files
ai-agent/backend/core/csp.py
gabrielvidal 1f4ddfff79 fix(security): the gate refuses cross-site requests for every caller, reads the routed path, names Authelia users
A page on any *.gabvdl.xyz site could POST as the owner (Authelia cookie is
same-site, a body without Content-Type needs no preflight); `Host: x?` emptied
request.url.path and skipped the gate from the docker network; the Chrome
websocket checked neither Origin nor the Authelia user; any Authelia account
(the password-only bot) was the owner. Also: no served /openapi.json, a
bounded /share, declared and bounded bodies for guests and anonymous callers,
a CSP on the app shell, FastAPI 0.163 / Starlette 1.x (startup is a lifespan).
Co-Authored-By: Claude <noreply@anthropic.com>
2026-11-15 15:23:05 +01:00

87 lines
3.3 KiB
Python

"""The Content-Security-Policy the static route sends (main.py), since
2026-11-15 (docs/security.md → the second pass).
Two documents get one:
* **the app shell** (``index.html``, the owner's and the guest host's) —
``script-src 'self'`` plus the hash of each inline ``<script>`` the build
ships (the theme bootstrap), ``object-src 'none'``, ``base-uri 'self'``,
``frame-ancestors 'self'``. A script injected into the app's DOM, an inline
handler or a ``javascript:`` URL (a link, an iframe ``src``) does not run on
the app's origin. Nothing else is restricted: styles, images, connections
and frames stay as they were (forms keep inline ``style=""``, the ask-form
and deploy previews are cross-origin frames).
* **the sandbox frame page** (``sandbox-frame.html``, where a form's scripted
HTML is written — ``frontend/src/lib/sandboxFrame.ts``) — ``sandbox
allow-scripts …``: an opaque origin whoever loads it, however. It has no
``script-src``: the form author's scripts and CDN libraries are the point,
and they run with no access to the app. The flags are the frontend's
``SANDBOX`` (the ``<iframe>`` attribute); ``test_csp.py`` holds them equal.
Why the shell's policy forces that page to exist: a ``srcdoc`` or ``blob:``
document inherits its embedder's policy, so ``script-src 'self'`` on the shell
would have stopped every scripted form block.
"""
from __future__ import annotations
import base64
import hashlib
import pathlib
import re
import threading
SANDBOX_FRAME = "sandbox-frame.html"
SANDBOX_FLAGS = "allow-scripts allow-popups allow-popups-to-escape-sandbox"
SANDBOX_FRAME_CSP = f"sandbox {SANDBOX_FLAGS}; frame-ancestors 'self'"
# An inline script: a <script> element without a src attribute.
_INLINE_SCRIPT = re.compile(r"<script(?![^>]*\ssrc\s*=)[^>]*>(.*?)</script\s*>",
re.IGNORECASE | re.DOTALL)
_lock = threading.Lock()
_cache: dict[str, tuple[tuple[int, int], str]] = {}
def script_hashes(html: str) -> list[str]:
"""``'sha256-…'`` for each inline script of ``html``, as a browser
computes it (over the element's text, newlines normalised by the parser)."""
out: list[str] = []
for m in _INLINE_SCRIPT.finditer(html):
text = m.group(1).replace("\r\n", "\n").replace("\r", "\n")
if not text.strip():
continue
digest = base64.b64encode(hashlib.sha256(text.encode("utf-8")).digest()).decode()
src = f"'sha256-{digest}'"
if src not in out:
out.append(src)
return out
def shell_policy(html: str) -> str:
sources = " ".join(["'self'", *script_hashes(html)])
return (f"script-src {sources}; object-src 'none'; base-uri 'self'; "
"frame-ancestors 'self'")
def shell_csp(index: pathlib.Path) -> str:
"""The shell's policy for the built ``index.html`` (re-read when the file
changes: a deploy swaps the image, a dev build rewrites it)."""
try:
st = index.stat()
stamp = (st.st_mtime_ns, st.st_size)
except OSError:
return shell_policy("")
key = str(index)
with _lock:
hit = _cache.get(key)
if hit and hit[0] == stamp:
return hit[1]
try:
policy = shell_policy(index.read_text(encoding="utf-8"))
except (OSError, UnicodeDecodeError):
return shell_policy("")
with _lock:
_cache[key] = (stamp, policy)
return policy