forge
Explore
Log in

Don't you dare go Hollow

in

Clone
★ 0

0 watching0 forksRustAGPL-3.0528.7 KiB9215377Tahinli27 days ago37 commits

security.rs145 lines, 5.2 KiBHistoryRawDownload
1//! The security headers of every response, and the Content-Security-Policy they carry.
2//!
3//! The policy allows scripts and styles from the origin itself and nothing else. No page may use an
4//! inline script, an inline style or an inline event handler: all behaviour lives in
5//! `crates/in-web/assets/*.js`. Changing [`CSP`] is a security change, so keep it in step with
6//! `docs/conventions.md` section 5.
7
8use topcoat::context::Cx;
9use topcoat::router::request::uri;
10use topcoat::router::response::response_headers;
11use topcoat::router::{
12 Body, HeaderMap, HeaderName, HeaderValue, Layer, LayerFuture, Next, Path, header,
13};
14
15/// The Content-Security-Policy of every response.
16pub const CSP: &str = "default-src 'self'; img-src 'self' data:; style-src 'self'; script-src 'self'; \
17 form-action 'self'; frame-ancestors 'none'; base-uri 'none'";
18
19/// Path prefix of the public share pages and their bytes. The token is in the path, so these pages send no
20/// referrer and ask search engines not to index them (architecture section 8).
21pub const SHARE_PREFIX: &str = "/s/";
22
23/// `Referrer-Policy` of the public share pages: the token in the URL must never reach another site.
24const SHARE_REFERRER: &str = "no-referrer";
25
26/// `X-Robots-Tag` of the public share pages.
27const SHARE_ROBOTS: &str = "noindex";
28
29/// The headers of `base` as they apply to a request for `path`: on a public share path the referrer and
30/// robots headers are replaced, everywhere else `base` is used as it is.
31fn for_path(base: &HeaderMap, path: &str) -> HeaderMap {
32 let mut headers = base.clone();
33 if path.starts_with(SHARE_PREFIX) {
34 headers.insert(
35 header::REFERRER_POLICY,
36 HeaderValue::from_static(SHARE_REFERRER),
37 );
38 headers.insert(
39 HeaderName::from_static("x-robots-tag"),
40 HeaderValue::from_static(SHARE_ROBOTS),
41 );
42 }
43 headers
44}
45
46/// One year, in seconds. Sent only when the public origin is https.
47const HSTS: &str = "max-age=31536000";
48
49/// The headers that every response carries, for an instance at `base_url`.
50pub fn headers_for(base_url: &str) -> HeaderMap {
51 let mut headers = HeaderMap::new();
52 headers.insert(
53 header::X_CONTENT_TYPE_OPTIONS,
54 HeaderValue::from_static("nosniff"),
55 );
56 headers.insert(header::X_FRAME_OPTIONS, HeaderValue::from_static("DENY"));
57 headers.insert(
58 header::REFERRER_POLICY,
59 HeaderValue::from_static("same-origin"),
60 );
61 headers.insert(
62 header::CONTENT_SECURITY_POLICY,
63 HeaderValue::from_static(CSP),
64 );
65 if base_url.starts_with("https://") {
66 headers.insert(
67 header::STRICT_TRANSPORT_SECURITY,
68 HeaderValue::from_static(HSTS),
69 );
70 }
71 headers
72}
73
74/// Adds a fixed set of headers to every response of the router.
75///
76/// It uses the per-request response headers, which the router applies after the layers have run,
77/// so error responses (404, 500) carry them as well.
78pub struct SecurityHeaders {
79 headers: HeaderMap,
80}
81
82impl SecurityHeaders {
83 /// A layer that adds `headers` to every response.
84 pub fn new(headers: HeaderMap) -> Self {
85 Self { headers }
86 }
87}
88
89impl Layer for SecurityHeaders {
90 fn path(&self) -> Option<&Path> {
91 None
92 }
93
94 fn handle<'a>(&'a self, cx: &'a Cx, body: Body, next: Next<'a>) -> LayerFuture<'a> {
95 Box::pin(async move {
96 let path = uri(cx).path().to_owned();
97 let headers = for_path(&self.headers, &path);
98 match next.run(cx, body).await {
99 // A header the route set itself wins: byte responses carry their own sandboxed
100 // policy, and two policies would apply both (the page one forbids framing).
101 Ok(mut response) => {
102 let response_map = response.headers_mut();
103 for (name, value) in &headers {
104 if !response_map.contains_key(name) {
105 response_map.insert(name.clone(), value.clone());
106 }
107 }
108 Ok(response)
109 }
110 // Errors become responses after the layers have run; the per-request slot gives
111 // them the headers too.
112 Err(error) => {
113 response_headers(cx).extend(headers);
114 Err(error)
115 }
116 }
117 })
118 }
119}
120
121#[cfg(test)]
122mod tests {
123 use super::*;
124
125 #[test]
126 fn share_paths_send_no_referrer_and_no_index() {
127 let base = headers_for("https://in.example.com");
128 let share = for_path(&base, "/s/abc");
129 assert_eq!(share[header::REFERRER_POLICY], "no-referrer");
130 assert_eq!(share["x-robots-tag"], "noindex");
131 let drive = for_path(&base, "/drive");
132 assert_eq!(drive[header::REFERRER_POLICY], "same-origin");
133 assert!(!drive.contains_key("x-robots-tag"));
134 }
135
136 #[test]
137 fn hsts_only_for_https_origins() {
138 assert!(
139 headers_for("https://in.example.com").contains_key(header::STRICT_TRANSPORT_SECURITY)
140 );
141 assert!(
142 !headers_for("http://127.0.0.1:7650").contains_key(header::STRICT_TRANSPORT_SECURITY)
143 );
144 }
145}