forge
Explore
Log in

Don't you dare go Hollow

im

Clone
★ 0

0 watching0 forksRustAGPL-3.0542.8 KiBb9f0726Tahinli27 days ago34 commits

security.rs219 lines, 8.6 KiBHistoryRawDownload
1//! The security headers of every response, the cache policy that goes with them, and the
2//! Content-Security-Policy they carry.
3//!
4//! The policy allows scripts and styles from the origin itself and nothing else. No page may use an
5//! inline script, an inline style or an inline event handler: all behaviour lives in
6//! `crates/im-web/assets/*.js`. Changing [`CSP`] is a security change, so keep it in step with
7//! `docs/conventions.md` section 5.
8//!
9//! Cache policy by path: pages (everything that is not a static asset or a photo) are `no-store`,
10//! so a page with a secret (recovery codes, a TOTP secret) is never kept by a browser or a proxy.
11//! Assets set their own long-lived policy. A photo that has its bytes sets its own `private` policy
12//! and its own CSP (see `pages/photo.rs`), and this layer leaves both alone. A photo's redirect or
13//! error (sign-in, 404) is a page to the browser, so it gets the page headers.
14
15use topcoat::context::Cx;
16use topcoat::router::request::uri;
17use topcoat::router::response::response_headers;
18use topcoat::router::{Body, HeaderMap, HeaderValue, Layer, LayerFuture, Next, Path, header};
19
20/// The Content-Security-Policy of every response.
21pub const CSP: &str = "default-src 'self'; img-src 'self' data:; style-src 'self'; script-src 'self'; \
22 form-action 'self'; frame-ancestors 'none'; base-uri 'none'";
23
24/// One year, in seconds. Sent only when the public origin is https.
25const HSTS: &str = "max-age=31536000";
26
27/// The cache policy of every page: nothing is stored, not even for going back in the history.
28const NO_STORE: &str = "no-store";
29
30/// The referrer policy of the pages that carry a single-use token in their path. The token must never leave
31/// the site in a `Referer` header, so these pages send none at all.
32const NO_REFERRER: &str = "no-referrer";
33
34/// True for the pages whose path holds a token or starts an account link: the reset request and every
35/// `/reset/`, `/invite/` and `/email/` page.
36pub fn token_path(path: &str) -> bool {
37 path == "/forgot"
38 || path.starts_with("/reset/")
39 || path.starts_with("/invite/")
40 || path.starts_with("/email/")
41}
42
43/// The headers that every response carries, for an instance at `base_url`.
44pub fn headers_for(base_url: &str) -> HeaderMap {
45 let mut headers = HeaderMap::new();
46 headers.insert(
47 header::X_CONTENT_TYPE_OPTIONS,
48 HeaderValue::from_static("nosniff"),
49 );
50 headers.insert(header::X_FRAME_OPTIONS, HeaderValue::from_static("DENY"));
51 headers.insert(
52 header::REFERRER_POLICY,
53 HeaderValue::from_static("same-origin"),
54 );
55 headers.insert(
56 header::CONTENT_SECURITY_POLICY,
57 HeaderValue::from_static(CSP),
58 );
59 if base_url.starts_with("https://") {
60 headers.insert(
61 header::STRICT_TRANSPORT_SECURITY,
62 HeaderValue::from_static(HSTS),
63 );
64 }
65 headers
66}
67
68/// What kind of answer a path gets, which decides its headers.
69#[derive(Clone, Copy, Debug, PartialEq, Eq)]
70pub enum Answer {
71 /// A static file under `/assets/`, with its own cache policy.
72 Asset,
73 /// A profile photo under `/photo/`. An answer with bytes has its own cache policy and CSP; a redirect or
74 /// error has the page headers.
75 Photo,
76 /// Public OpenID metadata (discovery and the key set). Not secret, so it may be cached; the handler
77 /// sets the short cache policy.
78 Public,
79 /// Everything else: pages, forms, streams. Never stored.
80 Page,
81}
82
83/// The kind of answer for a request path.
84pub fn answer_for(path: &str) -> Answer {
85 if path.starts_with("/assets/") {
86 Answer::Asset
87 } else if path.starts_with("/photo/") {
88 Answer::Photo
89 } else if path == "/.well-known/openid-configuration" || path == "/jwks.json" {
90 Answer::Public
91 } else {
92 Answer::Page
93 }
94}
95
96/// Adds the security headers to every response, and `Cache-Control: no-store` to every page and every
97/// photo answer that is not a photo's bytes.
98///
99/// It uses the per-request response headers, which the router applies after the layers have run,
100/// so error responses (404, 500, the sign-in redirect) carry them as well. A header the route set
101/// itself is never replaced, so a photo with bytes keeps its own CSP and cache policy.
102pub struct SecurityHeaders {
103 headers: HeaderMap,
104}
105
106impl SecurityHeaders {
107 /// A layer that adds `headers` to every response.
108 pub fn new(headers: HeaderMap) -> Self {
109 Self { headers }
110 }
111}
112
113impl Layer for SecurityHeaders {
114 fn path(&self) -> Option<&Path> {
115 None
116 }
117
118 fn handle<'a>(&'a self, cx: &'a Cx, body: Body, next: Next<'a>) -> LayerFuture<'a> {
119 Box::pin(async move {
120 let path = uri(cx).path();
121 let answer = answer_for(path);
122 let mut headers = self.headers.clone();
123 if matches!(answer, Answer::Page | Answer::Photo) {
124 headers.insert(header::CACHE_CONTROL, HeaderValue::from_static(NO_STORE));
125 }
126 if answer == Answer::Page && token_path(path) {
127 headers.insert(
128 header::REFERRER_POLICY,
129 HeaderValue::from_static(NO_REFERRER),
130 );
131 }
132 match next.run(cx, body).await {
133 // A header the route set itself wins: a token answer that is already `no-store`, or a
134 // photo with its own stricter policy, must not get a second copy of the same header.
135 Ok(mut response) => {
136 let response_map = response.headers_mut();
137 for (name, value) in &headers {
138 if !response_map.contains_key(name) {
139 response_map.insert(name.clone(), value.clone());
140 }
141 }
142 Ok(response)
143 }
144 // Errors become responses after the layers have run; the per-request slot gives
145 // them the headers too.
146 Err(error) => {
147 response_headers(cx).extend(headers);
148 Err(error)
149 }
150 }
151 })
152 }
153}
154
155#[cfg(test)]
156mod tests {
157 use super::*;
158
159 #[test]
160 fn only_pages_are_marked_no_store() {
161 assert_eq!(answer_for("/login"), Answer::Page);
162 assert_eq!(answer_for("/account/profile"), Answer::Page);
163 assert_eq!(answer_for("/setup"), Answer::Page);
164 assert_eq!(answer_for("/photo/01HZ"), Answer::Photo);
165 assert_eq!(answer_for("/assets/main.css"), Answer::Asset);
166 assert_eq!(answer_for("/jwks.json"), Answer::Public);
167 // A prefix match on the segment only: a page whose name starts the same is still a page.
168 assert_eq!(answer_for("/photographs"), Answer::Page);
169 }
170
171 #[tokio::test]
172 async fn a_route_header_is_not_repeated_by_the_layer() {
173 let (_dir, state) = crate::boot::test_state().await;
174 for (method, path) in [("POST", "/token"), ("GET", "/photo/01HZ")] {
175 let request = http::Request::builder()
176 .method(method)
177 .uri(path)
178 .body(topcoat::router::Body::empty())
179 .expect("request");
180 let response = crate::boot::router(state.clone()).handle(request).await;
181 let headers = response.headers();
182 // A repeat is the bug under test. A photo redirect (to sign-in) is an error answer, so it
183 // carries the layer's Cache-Control and CSP once each.
184 let cache_control = headers.get_all(header::CACHE_CONTROL).iter().count();
185 assert!(cache_control <= 1, "Cache-Control repeated on {path}");
186 if path == "/token" || path == "/photo/01HZ" {
187 assert_eq!(cache_control, 1, "Cache-Control on {path}");
188 }
189 let csp = headers
190 .get_all(header::CONTENT_SECURITY_POLICY)
191 .iter()
192 .count();
193 assert!(csp <= 1, "CSP repeated on {path}");
194 if path == "/token" || path == "/photo/01HZ" {
195 assert_eq!(csp, 1, "CSP on {path}");
196 }
197 }
198 }
199
200 #[test]
201 fn token_pages_are_recognised() {
202 assert!(token_path("/reset/abc"));
203 assert!(token_path("/invite/abc"));
204 assert!(token_path("/email/abc"));
205 assert!(token_path("/forgot"));
206 assert!(!token_path("/login"));
207 assert!(!token_path("/resetting"));
208 }
209
210 #[test]
211 fn hsts_only_for_https_origins() {
212 assert!(
213 headers_for("https://im.example.com").contains_key(header::STRICT_TRANSPORT_SECURITY)
214 );
215 assert!(
216 !headers_for("http://127.0.0.1:7650").contains_key(header::STRICT_TRANSPORT_SECURITY)
217 );
218 }
219}