steid

@jamesgill /

steid/src/infrastructure/web/security_headers.rs
Rust6.8 KBCode·Blame·History·Raw
1//! Security headers on every response.
2//!
3//! A layer rather than a per-handler concern: a page added without these would simply
4//! not have them, and nothing would fail. The same reasoning `context.rs` gives for
5//! preferring functions over middleware runs the other way here — this is a blanket
6//! property of every response, and the failure mode of forgetting it is silent.
7//!
8//! **It also counts every request**, which is not what the name says and is deliberate.
9//! `.discover()` allows one layer per path, so there can be only one layer at `/` — the
10//! same constraint that sent feed autodiscovery into `atom::discovered` rather than a
11//! layer of its own (see `progress.md`). A second layer somewhere deeper would count only
12//! its own subtree, and `steid_http_requests_total` has to mean *every* response or it
13//! means nothing. So this is the one thing that sees them all, and the counting rides
14//! along: one classification of the path and one relaxed atomic add, after the response
15//! already exists. If a page ever needs to contribute to `<head>` and this becomes the
16//! shared per-request layer that note anticipates, the counting belongs there with it.
17//!
18//! **And it caps the request body**, for exactly the same reason: Topcoat's `Form` and
19//! `Json` collect with no limit at all, so the ceiling has to be somewhere that every
20//! request passes through, and there is only one such place. See
21//! [`body_limit`](super::body_limit).
22
23use topcoat::{
24 Result,
25 context::CxBuilder,
26 router::{
27 Body, HeaderValue, IntoResponse, Next, Response,
28 header::{
29 CACHE_CONTROL, CONTENT_SECURITY_POLICY, REFERRER_POLICY, X_CONTENT_TYPE_OPTIONS,
30 X_FRAME_OPTIONS,
31 },
32 headers, layer, uri,
33 },
34};
35
36use crate::infrastructure::{metrics::metrics, web::body_limit};
37
38/// What the pages are actually allowed to do.
39///
40/// Steid renders **no JavaScript at all** — not a script tag on any page — so
41/// `default-src 'none'` is a policy the product can genuinely keep rather than a wish.
42/// That makes this far stricter than a typical site's CSP, and it is worth preserving:
43/// if a future feature needs script, weakening this is the cost, and it should be a
44/// deliberate decision rather than a quiet edit.
45///
46/// `'unsafe-inline'` for styles only, and only because Topcoat's icon macro emits
47/// `style="vertical-align: -0.125em"` on every icon. Inline *style* without inline
48/// *script* is a much smaller surface, but it is a framework constraint rather than a
49/// choice — a nonce or a hash would be better if Topcoat ever offers one.
50const POLICY: &str = "default-src 'none'; \
51 style-src 'self' 'unsafe-inline'; \
52 img-src 'self' data:; \
53 font-src 'self'; \
54 form-action 'self'; \
55 frame-ancestors 'none'; \
56 base-uri 'none'";
57
58#[layer("/")]
59async fn security_headers(cx: &mut CxBuilder, body: Body, next: Next<'_>) -> Result<Response> {
60 // Read before the request runs: a handler is free to rewrite the parts, and the path
61 // this counts under has to be the one that arrived.
62 let path = uri(cx).path().to_owned();
63
64 // And the third thing this layer does, for the reason the counting is here: one
65 // layer per path, so anything that must hold for *every* request has to be in this
66 // one. Topcoat's own body readers take `usize::MAX`, so without this a form endpoint
67 // holds whatever arrives — see `body_limit`. Refused bodies are counted too, which
68 // is why this runs before the counting rather than in front of the layer.
69 let body = match body_limit::capped(&path, headers(cx), body) {
70 Ok(body) => body,
71 Err(refused) => {
72 metrics().record_request(&path, refused.status().as_u16());
73 return Ok(*refused);
74 }
75 };
76
77 let mut response = match next.run(cx, body).await {
78 Ok(response) => response,
79 // **A handler's `Err` is not a response yet.** The router turns one into a 404 or
80 // a 500 *above* every layer, so propagating it with `?` here would mean the whole
81 // error half of the site is neither counted nor given a header — and
82 // `status="5xx"` climbing is the entire reason to scrape this.
83 //
84 // Building it here instead is the same conversion the router would have done, one
85 // frame lower. It also closes a hole that predates the counting: until now a 404
86 // went out with no CSP, no `X-Frame-Options` and no `Referrer-Policy`, because it
87 // never passed through this function at all.
88 Err(error) => error.into_response(cx)?,
89 };
90
91 metrics().record_request(&path, response.status().as_u16());
92
93 let headers = response.headers_mut();
94
95 // `entry().or_insert()`, never `insert()`: the raw-file endpoint sets its own,
96 // stricter `default-src 'none'; sandbox`, and a blanket overwrite here would
97 // quietly relax the one response that most needs locking down.
98 headers
99 .entry(CONTENT_SECURITY_POLICY)
100 .or_insert(HeaderValue::from_static(POLICY));
101
102 headers
103 .entry(X_CONTENT_TYPE_OPTIONS)
104 .or_insert(HeaderValue::from_static("nosniff"));
105
106 // `no-referrer`, not the usual `strict-origin-when-cross-origin`. A private
107 // repository's URL contains its name, and a README may link anywhere; sending the
108 // referrer would hand the name of a private repository to whatever the visitor
109 // clicked. Nothing here needs a referrer for its own sake.
110 headers
111 .entry(REFERRER_POLICY)
112 .or_insert(HeaderValue::from_static("no-referrer"));
113
114 // Redundant with `frame-ancestors` for anything current, kept for browsers that
115 // predate CSP. Cheap, and clickjacking a one-click control like "revoke token"
116 // is the realistic attack it stops.
117 headers
118 .entry(X_FRAME_OPTIONS)
119 .or_insert(HeaderValue::from_static("DENY"));
120
121 // Nothing said anything about caching before this, so a private repository's page
122 // was as cacheable as the front page — and every URL under `/{handle}/…` is the
123 // same shape whether what it renders is public or not, so a proxy has nothing to
124 // tell them apart by. `private` keeps it out of any shared cache; `no-cache` lets a
125 // browser keep it but never reuse it without asking, which is what stops the page
126 // somebody was signed in for coming back after they signed out.
127 //
128 // Not `no-store`, deliberately: the archive route answers `If-None-Match` from a
129 // commit id, and a response the browser was told not to store is one it has nothing
130 // to revalidate with. The one payload that genuinely must not be written down —
131 // the instance backup — sets `no-store, private` itself, and `or_insert` leaves it,
132 // as it leaves the asset routes' year-long `public, immutable`.
133 headers
134 .entry(CACHE_CONTROL)
135 .or_insert(HeaderValue::from_static("private, no-cache"));
136
137 Ok(response)
138}