Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 30 additions & 0 deletions app/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
from __future__ import annotations

import os
import secrets
import threading
import time
from collections.abc import AsyncIterator
Expand Down Expand Up @@ -147,11 +148,40 @@ def is_allowed_s3_key(key: str) -> bool:
return key.startswith(ALLOWED_S3_KEY_ROOTS)


# Content-Security-Policy. Pages carry a handful of inline <script> blocks
# (theme bootstrap, loading bar, inbox and detail behaviour); each gets this
# response's nonce, and everything else loads from this origin. Scripts are
# the strict part: no inline handlers, no eval, no other origins, so injected
# markup cannot run script. Styles are 'self' only: the templates have no
# inline styles, and the sanitizer in s3_email.py strips style attributes and
# <style> blocks from email bodies before they are rendered. Email bodies may
# reference remote images, so img-src allows https: and data: (cid: images
# never resolve and are harmless). No form-action: Elcano-mode logout is a
# form POST that redirects to the auth host, and browsers apply form-action
# to that redirect. frame-ancestors 'none' mirrors X-Frame-Options: DENY.
CSP_NON_PAGE = "default-src 'none'; base-uri 'none'; frame-ancestors 'none'"


def csp_for_page(nonce: str) -> str:
return (
f"default-src 'self'; script-src 'self' 'nonce-{nonce}'; style-src 'self'; "
"img-src 'self' data: https:; font-src 'self'; connect-src 'self'; "
"object-src 'none'; base-uri 'none'; frame-ancestors 'none'"
)


@app.middleware("http")
async def security_headers(request: Request, call_next) -> Response:
# Caddy sets these too; keeping them here covers the legacy nginx path
# and direct loopback access.
request.state.csp_nonce = secrets.token_urlsafe(16)
response = await call_next(request)
if response.headers.get("content-type", "").startswith("text/html"):
response.headers["Content-Security-Policy"] = csp_for_page(
request.state.csp_nonce
)
else:
response.headers.setdefault("Content-Security-Policy", CSP_NON_PAGE)
response.headers.setdefault("X-Content-Type-Options", "nosniff")
response.headers.setdefault("X-Frame-Options", "DENY")
response.headers.setdefault("Referrer-Policy", "strict-origin-when-cross-origin")
Expand Down
4 changes: 2 additions & 2 deletions app/templates/base.html
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>{{ title or "Explorer" }}</title>
<script>
<script nonce="{{ request.state.csp_nonce }}">
(function () {
const storageKey = "flag-theme-preference";
let preference = null;
Expand Down Expand Up @@ -58,7 +58,7 @@ <h1 class="ds-app-header__title">{% block header_title %}Explorer{% endblock %}<
{% endblock %}
<main class="page">{% block content %}{% endblock %}</main>
</div>
<script>
<script nonce="{{ request.state.csp_nonce }}">
(function () {
const root = document.documentElement;
const toggle = document.getElementById("toggleTheme");
Expand Down
2 changes: 1 addition & 1 deletion app/templates/email_detail.html
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ <h1 class="message-thread__subject">{{ email.subject or "(no subject)" }}</h1>
</article>
</section>

<script>
<script nonce="{{ request.state.csp_nonce }}">
(function () {
const formatDates = () => {
const formatter = new Intl.DateTimeFormat(undefined, {
Expand Down
2 changes: 1 addition & 1 deletion app/templates/inbox.html
Original file line number Diff line number Diff line change
Expand Up @@ -319,7 +319,7 @@ <h3 class="empty-state__title">No emails matched this search</h3>
{% endif %}

<script src="/static/vendor/flatpickr/flatpickr.min.js"></script>
<script>
<script nonce="{{ request.state.csp_nonce }}">
(function () {
const form = document.getElementById("search-form");
const submitButton = document.getElementById("search-submit");
Expand Down
30 changes: 30 additions & 0 deletions tests/test_central_auth_endpoints.py
Original file line number Diff line number Diff line change
Expand Up @@ -365,3 +365,33 @@ def test_central_mode_refuses_to_start_without_the_auth_public_key(
monkeypatch.setenv("AUTH_SIGNING_PUBKEY", "not-32-bytes")
with pytest.raises(RuntimeError, match="AUTH_SIGNING_PUBKEY"):
CentralAuthProvider.from_env(FakeAuthClient)


def test_pages_carry_nonce_csp_and_other_responses_a_closed_one(central_client) -> None:
import re

client, _store = central_client
complete_login(client)

page = client.get("/", follow_redirects=False)
assert page.status_code == 200
csp = page.headers["content-security-policy"]
match = re.search(r"script-src 'self' 'nonce-([A-Za-z0-9_-]+)'", csp)
assert match, csp
nonce = match.group(1)
assert "default-src 'self'" in csp
assert "style-src 'self';" in csp
assert "img-src 'self' data: https:" in csp
assert "frame-ancestors 'none'" in csp
assert "form-action" not in csp
body = page.text
assert "<script>" not in body
assert body.count(f'<script nonce="{nonce}">') >= 1
assert not re.search(r' on[a-z]+="', body)
assert ' style="' not in body

second = client.get("/", follow_redirects=False)
assert second.headers["content-security-policy"] != csp

health = client.get("/health")
assert health.headers["content-security-policy"] == main.CSP_NON_PAGE