mod.rs
⎇
Raw
1use std::sync::Arc;
2
3use api_types::{
4 ADMIN_SETTINGS, ADMIN_SHARES, ADMIN_USERS, AUTH_LOGIN, AUTH_LOGOUT, AUTH_ME, AUTH_SETUP, DAV,
5 DAV_SHARE, FILES, SEARCH, SHARE, SHARE_UNLOCK_SUFFIX, SHARES,
6};
7use axum::Router;
8use axum::http::HeaderValue;
9use axum::routing::{any, delete, get, post, put};
10use tower_http::set_header::SetResponseHeaderLayer;
11
12use crate::error::AppState;
13
14/// Content-Security-Policy tuned to the built Trunk frontend.
15///
16/// * `script-src 'unsafe-inline'` — Trunk emits one inline bootstrap module
17/// in index.html; every real JS file also carries an SRI integrity hash.
18/// * `'wasm-unsafe-eval'` — compiling the same-origin WASM module.
19/// * `style-src 'unsafe-inline'` — the context menu sets an inline `style=`.
20/// * Everything else locked to the same origin; frames/plugins banned.
21const CSP: &str = "default-src 'self'; script-src 'self' 'unsafe-inline' 'wasm-unsafe-eval'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:; media-src 'self' blob:; connect-src 'self'; font-src 'self' data:; object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'none';";
22
23/// Content-Security-Policy for served *user files* that the browser would
24/// treat as a scripting document (HTML, SVG, XML). Lets such a file render as
25/// a real page — the "share an HTML page" flow — without letting it act as the
26/// app.
27///
28/// The security hinges on one omission: `allow-scripts` **without**
29/// `allow-same-origin`. That forces the document into a unique opaque origin,
30/// so its JavaScript cannot read the session cookie's origin, cannot touch
31/// `localStorage`, and cannot call `/api` as the viewer (the server sends no
32/// CORS headers, so every cross-origin read fails). Never add
33/// `allow-same-origin` here.
34///
35/// Also deliberately absent:
36/// * `allow-top-navigation` — a shared page cannot silently redirect the
37/// viewer elsewhere. `-by-user-activation` still lets links work on click.
38/// * `allow-popups-to-escape-sandbox` — a popup would drop the sandbox.
39///
40/// `connect-src *` is deliberate: a shared page may call third-party APIs.
41/// The trade-off is that it can also beacon (report that the link was opened,
42/// and anything the page itself contains). It cannot exfiltrate anything of
43/// the viewer's — the opaque origin means it has no session and no CORS read
44/// access to this server.
45pub(crate) const FILE_CSP: &str = "default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:; media-src 'self' blob:; font-src 'self' data:; connect-src *; object-src 'none'; frame-ancestors 'none'; sandbox allow-scripts allow-forms allow-modals allow-downloads allow-popups allow-top-navigation-by-user-activation;";
46
47/// Apply [`FILE_CSP`] to a response that declares a scriptable type.
48///
49/// The router's CSP layer is `if_not_present`, so without this such a response
50/// keeps the *app* policy: same origin, scripts allowed. A `GET` of a shared
51/// HTML file is a top-level navigation, which carries the session cookie under
52/// `SameSite=Lax`, so the page would then run as the viewer against `/api`.
53pub(crate) fn sandbox_scriptable<B>(resp: &mut axum::http::Response<B>) {
54 let scriptable = resp
55 .headers()
56 .get(axum::http::header::CONTENT_TYPE)
57 .and_then(|v| v.to_str().ok())
58 .is_some_and(is_scriptable_mime);
59 if scriptable {
60 resp.headers_mut().insert(
61 "content-security-policy",
62 HeaderValue::from_static(FILE_CSP),
63 );
64 }
65}
66
67/// Content-Security-Policy for inline (preview) files that are *not*
68/// scripting documents (PDF, media, …): the preview modal embeds them in a
69/// same-origin `<iframe>`. Scriptable files never get this — see [`FILE_CSP`].
70pub(crate) const INLINE_CSP: &str = "frame-ancestors 'self';";
71
72/// True for MIME types the browser parses as a scripting document. These are
73/// the responses that need [`FILE_CSP`]; everything else keeps the app policy.
74///
75/// This reads the *declared* type — the same value that becomes the
76/// `Content-Type` header — on purpose. If the sandbox decision and the render
77/// decision ever read different inputs, a file can be rendered as a scripting
78/// document without being sandboxed.
79pub(crate) fn is_scriptable_mime(mime: &str) -> bool {
80 let base = mime.split(';').next().unwrap_or("").trim();
81 matches!(
82 base,
83 "text/html" | "application/xhtml+xml" | "image/svg+xml" | "text/xml" | "application/xml"
84 ) || base.ends_with("+xml")
85}
86
87mod admin;
88mod auth;
89mod common;
90mod dav;
91mod files;
92mod search;
93mod shares;
94mod spa;
95
96pub fn router(state: Arc<AppState>) -> Router {
97 // Route patterns: the server side of the shared endpoint strings in
98 // `api_types` (axum copies them into the route table on insert).
99 let files_root = format!("{FILES}/{{root_id}}");
100 let files_item = format!("{FILES}/{{root_id}}/{{*path}}");
101 let shares_id = format!("{SHARES}/{{id}}");
102 let share_token = format!("{SHARE}/{{token}}");
103 let share_unlock = format!("{SHARE}/{{token}}{SHARE_UNLOCK_SUFFIX}");
104 let admin_user_id = format!("{ADMIN_USERS}/{{id}}");
105 let admin_share_id = format!("{ADMIN_SHARES}/{{id}}");
106 // A wildcard needs something to capture, so `/dav/` gets its own pattern:
107 // mount clients ask for it with the trailing slash, which matches neither
108 // the bare path nor `{*path}`.
109 let dav_root = format!("{DAV}/");
110 let dav_item = format!("{DAV}/{{*path}}");
111 let dav_share = format!("{DAV_SHARE}/{{*path}}");
112
113 Router::new()
114 .route(AUTH_LOGIN, post(auth::login))
115 .route(AUTH_LOGOUT, post(auth::logout))
116 .route(AUTH_ME, get(auth::me).put(auth::update_profile))
117 .route(AUTH_SETUP, post(auth::setup))
118 .route(SEARCH, get(search::search))
119 .route(&files_root, get(files::list_root).put(files::file_put_root))
120 .route(&files_item, get(files::file_get))
121 .route(&files_item, put(files::file_put))
122 .route(&files_root, post(files::dispatch_root))
123 .route(&files_item, post(files::dispatch))
124 .route(&files_item, delete(files::delete))
125 .route(SHARES, get(shares::list))
126 .route(SHARES, post(shares::create))
127 .route(&shares_id, delete(shares::delete))
128 .route(&share_token, get(shares::resolve))
129 .route(&share_unlock, post(shares::unlock))
130 .route(ADMIN_USERS, get(admin::list_users))
131 .route(ADMIN_USERS, post(admin::create_user))
132 .route(&admin_user_id, put(admin::update_user))
133 .route(&admin_user_id, delete(admin::delete_user))
134 .route(ADMIN_SHARES, get(admin::list_shares))
135 .route(&admin_share_id, delete(admin::delete_share))
136 .route(ADMIN_SETTINGS, get(admin::get_settings))
137 .route(ADMIN_SETTINGS, put(admin::update_settings))
138 // `any`, not a method filter: WebDAV's verbs (PROPFIND, MKCOL, MOVE, …)
139 // are not in axum's `MethodFilter`, and a method router's fallback
140 // takes every one of them.
141 .route(DAV, any(dav::user))
142 .route(&dav_root, any(dav::user))
143 .route(&dav_item, any(dav::user))
144 .route(&dav_share, any(dav::share))
145 .fallback(spa::fallback)
146 // The editor save body is checked against `MAX_TEXT_BYTES` in the
147 // handler; axum's default limit is the same 2 MiB, which would win
148 // with a plain 413 instead of the localized error.
149 .layer(axum::extract::DefaultBodyLimit::max(
150 files::MAX_TEXT_BYTES as usize + 64 * 1024,
151 ))
152 .with_state(state)
153 // Hard security headers on every response (API and static alike).
154 // CSP/XFO are `if_not_present` so file responses can substitute
155 // [`FILE_CSP`] or the same-origin-framable [`INLINE_CSP`]; everything
156 // else gets the app policy.
157 .layer(SetResponseHeaderLayer::if_not_present(
158 "content-security-policy".parse().unwrap(),
159 HeaderValue::from_static(CSP),
160 ))
161 .layer(SetResponseHeaderLayer::overriding(
162 "x-content-type-options".parse().unwrap(),
163 HeaderValue::from_static("nosniff"),
164 ))
165 .layer(SetResponseHeaderLayer::if_not_present(
166 "x-frame-options".parse().unwrap(),
167 HeaderValue::from_static("DENY"),
168 ))
169 .layer(SetResponseHeaderLayer::overriding(
170 "referrer-policy".parse().unwrap(),
171 HeaderValue::from_static("no-referrer"),
172 ))
173}
174