mod.rs
⎇
Raw
1use std::sync::Arc;
2
3use api_types::{
4 ADMIN_ROOMS, ADMIN_SETTINGS, ADMIN_SHARES, ADMIN_USERS, AUTH_APP_PASSWORDS, AUTH_LOGIN,
5 AUTH_LOGOUT, AUTH_ME, AUTH_MODE, AUTH_PASSKEY_LOGIN, AUTH_PASSKEYS, AUTH_PASSKEYS_REGISTER,
6 AUTH_PASSWORD, AUTH_SETUP, DAV, DAV_SHARE, EXPORT_SUFFIX, FEED, FILES, FINISH_SUFFIX,
7 IMPORT_SUFFIX, LINKS_SUFFIX, PIM, PIM_COLLECTIONS, SEARCH, SHARE, SHARE_UNLOCK_SUFFIX, SHARES,
8 SHARES_SUFFIX, WELL_KNOWN_CALDAV, WELL_KNOWN_CARDDAV,
9};
10use axum::Router;
11use axum::http::HeaderValue;
12use axum::routing::{any, delete, get, post, put};
13use tower_http::set_header::SetResponseHeaderLayer;
14
15use crate::error::AppState;
16
17/// Content-Security-Policy tuned to the built Trunk frontend.
18///
19/// * `script-src 'unsafe-inline'` — Trunk emits one inline bootstrap module
20/// in index.html; every real JS file also carries an SRI integrity hash.
21/// * `'wasm-unsafe-eval'` — compiling the same-origin WASM module.
22/// * `style-src 'unsafe-inline'` — the context menu sets an inline `style=`.
23/// * Everything else locked to the same origin; frames/plugins banned.
24const 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';";
25
26/// Content-Security-Policy for served *user files* that the browser would
27/// treat as a scripting document (HTML, SVG, XML). Lets such a file render as
28/// a real page — the "share an HTML page" flow — without letting it act as the
29/// app.
30///
31/// The security hinges on one omission: `allow-scripts` **without**
32/// `allow-same-origin`. That forces the document into a unique opaque origin,
33/// so its JavaScript cannot read the session cookie's origin, cannot touch
34/// `localStorage`, and cannot call `/api` as the viewer (the server sends no
35/// CORS headers, so every cross-origin read fails). Never add
36/// `allow-same-origin` here.
37///
38/// Also deliberately absent:
39/// * `allow-top-navigation` — a shared page cannot silently redirect the
40/// viewer elsewhere. `-by-user-activation` still lets links work on click.
41/// * `allow-popups-to-escape-sandbox` — a popup would drop the sandbox.
42///
43/// `connect-src *` is deliberate: a shared page may call third-party APIs.
44/// The trade-off is that it can also beacon (report that the link was opened,
45/// and anything the page itself contains). It cannot exfiltrate anything of
46/// the viewer's — the opaque origin means it has no session and no CORS read
47/// access to this server.
48pub(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;";
49
50/// Apply [`FILE_CSP`] to a response that declares a scriptable type.
51///
52/// The router's CSP layer is `if_not_present`, so without this such a response
53/// keeps the *app* policy: same origin, scripts allowed. A `GET` of a shared
54/// HTML file is a top-level navigation, which carries the session cookie under
55/// `SameSite=Lax`, so the page would then run as the viewer against `/api`.
56pub(crate) fn sandbox_scriptable<B>(resp: &mut axum::http::Response<B>) {
57 let scriptable = resp
58 .headers()
59 .get(axum::http::header::CONTENT_TYPE)
60 .and_then(|v| v.to_str().ok())
61 .is_some_and(is_scriptable_mime);
62 if scriptable {
63 resp.headers_mut().insert(
64 "content-security-policy",
65 HeaderValue::from_static(FILE_CSP),
66 );
67 }
68}
69
70/// Content-Security-Policy for inline (preview) files that are *not*
71/// scripting documents (PDF, media, …): the preview modal embeds them in a
72/// same-origin `<iframe>`. Scriptable files never get this — see [`FILE_CSP`].
73pub(crate) const INLINE_CSP: &str = "frame-ancestors 'self';";
74
75/// True for MIME types the browser parses as a scripting document. These are
76/// the responses that need [`FILE_CSP`]; everything else keeps the app policy.
77///
78/// This reads the *declared* type — the same value that becomes the
79/// `Content-Type` header — on purpose. If the sandbox decision and the render
80/// decision ever read different inputs, a file can be rendered as a scripting
81/// document without being sandboxed.
82pub(crate) fn is_scriptable_mime(mime: &str) -> bool {
83 let base = mime.split(';').next().unwrap_or("").trim();
84 matches!(
85 base,
86 "text/html" | "application/xhtml+xml" | "image/svg+xml" | "text/xml" | "application/xml"
87 ) || base.ends_with("+xml")
88}
89
90mod admin;
91mod app_passwords;
92mod auth;
93pub(crate) mod common;
94mod dav;
95mod files;
96mod passkeys;
97mod pim;
98mod pim_api;
99mod pim_schedule;
100mod search;
101mod shares;
102mod spa;
103
104pub fn router(state: Arc<AppState>) -> Router {
105 // Route patterns: the server side of the shared endpoint strings in
106 // `api_types` (axum copies them into the route table on insert).
107 let files_root = format!("{FILES}/{{root_id}}");
108 let files_item = format!("{FILES}/{{root_id}}/{{*path}}");
109 let shares_id = format!("{SHARES}/{{id}}");
110 let share_token = format!("{SHARE}/{{token}}");
111 let share_unlock = format!("{SHARE}/{{token}}{SHARE_UNLOCK_SUFFIX}");
112 let admin_user_id = format!("{ADMIN_USERS}/{{id}}");
113 let passkey_id = format!("{AUTH_PASSKEYS}/{{id}}");
114 let app_password_id = format!("{AUTH_APP_PASSWORDS}/{{id}}");
115 let passkey_register_finish = format!("{AUTH_PASSKEYS_REGISTER}{FINISH_SUFFIX}");
116 let passkey_login_finish = format!("{AUTH_PASSKEY_LOGIN}{FINISH_SUFFIX}");
117 let admin_share_id = format!("{ADMIN_SHARES}/{{id}}");
118 let admin_room_id = format!("{ADMIN_ROOMS}/{{id}}");
119 let pim_shares = format!("{PIM_COLLECTIONS}/{{id}}{SHARES_SUFFIX}");
120 let pim_share = format!("{PIM_COLLECTIONS}/{{id}}{SHARES_SUFFIX}/{{user_id}}");
121 let pim_links = format!("{PIM_COLLECTIONS}/{{id}}{LINKS_SUFFIX}");
122 let pim_link = format!("{PIM_COLLECTIONS}/{{id}}{LINKS_SUFFIX}/{{link_id}}");
123 let pim_import = format!("{PIM_COLLECTIONS}/{{id}}{IMPORT_SUFFIX}");
124 let pim_export = format!("{PIM_COLLECTIONS}/{{id}}{EXPORT_SUFFIX}");
125 let feed = format!("{FEED}/{{file}}");
126 // A wildcard needs something to capture, so `/dav/` gets its own pattern:
127 // mount clients ask for it with the trailing slash, which matches neither
128 // the bare path nor `{*path}`.
129 let dav_root = format!("{DAV}/");
130 let dav_item = format!("{DAV}/{{*path}}");
131 let dav_share = format!("{DAV_SHARE}/{{*path}}");
132 let pim_root = format!("{PIM}/");
133 let pim_item = format!("{PIM}/{{*path}}");
134
135 Router::new()
136 .route(AUTH_LOGIN, post(auth::login))
137 .route(AUTH_LOGOUT, post(auth::logout))
138 .route(AUTH_ME, get(auth::me).put(auth::update_profile))
139 .route(AUTH_SETUP, post(auth::setup))
140 .route(
141 AUTH_PASSWORD,
142 post(passkeys::change_password).delete(passkeys::delete_password),
143 )
144 .route(AUTH_MODE, put(passkeys::set_mode))
145 // axum matches a literal segment before a parameter, so `/register`
146 // and `{id}` can both live under this path.
147 .route(AUTH_PASSKEYS, get(passkeys::list))
148 .route(AUTH_PASSKEYS_REGISTER, post(passkeys::register_begin))
149 .route(&passkey_register_finish, post(passkeys::register_finish))
150 .route(&passkey_id, delete(passkeys::delete))
151 .route(AUTH_PASSKEY_LOGIN, post(passkeys::login_begin))
152 .route(&passkey_login_finish, post(passkeys::login_finish))
153 .route(
154 AUTH_APP_PASSWORDS,
155 get(app_passwords::list).post(app_passwords::create),
156 )
157 .route(&app_password_id, delete(app_passwords::delete))
158 .route(SEARCH, get(search::search))
159 .route(
160 &files_root,
161 get(files::file_get)
162 .put(files::file_put)
163 .post(files::dispatch),
164 )
165 .route(
166 &files_item,
167 get(files::file_get)
168 .put(files::file_put)
169 .post(files::dispatch)
170 .delete(files::delete),
171 )
172 .route(SHARES, get(shares::list))
173 .route(SHARES, post(shares::create))
174 .route(&shares_id, delete(shares::delete))
175 .route(&share_token, get(shares::resolve))
176 .route(&share_unlock, post(shares::unlock))
177 .route(ADMIN_USERS, get(admin::list_users))
178 .route(ADMIN_USERS, post(admin::create_user))
179 .route(&admin_user_id, put(admin::update_user))
180 .route(&admin_user_id, delete(admin::delete_user))
181 .route(ADMIN_SHARES, get(admin::list_shares))
182 .route(&admin_share_id, delete(admin::delete_share))
183 .route(ADMIN_ROOMS, get(admin::list_rooms).post(admin::create_room))
184 .route(
185 &admin_room_id,
186 put(admin::update_room).delete(admin::delete_room),
187 )
188 .route(PIM_COLLECTIONS, get(pim_api::list))
189 .route(&pim_shares, get(pim_api::shares).post(pim_api::share))
190 .route(&pim_share, delete(pim_api::unshare))
191 .route(&pim_links, get(pim_api::links).post(pim_api::create_link))
192 .route(&pim_link, delete(pim_api::delete_link))
193 .route(&pim_import, post(pim_api::import))
194 .route(
195 &pim_export,
196 get(pim_api::export).post(pim_api::export_to_root),
197 )
198 .route(&feed, get(pim_api::feed))
199 .route(ADMIN_SETTINGS, get(admin::get_settings))
200 .route(ADMIN_SETTINGS, put(admin::update_settings))
201 // `any`, not a method filter: WebDAV's verbs (PROPFIND, MKCOL, MOVE, …)
202 // are not in axum's `MethodFilter`, and a method router's fallback
203 // takes every one of them.
204 .route(DAV, any(dav::user))
205 .route(&dav_root, any(dav::user))
206 .route(&dav_item, any(dav::user))
207 .route(&dav_share, any(dav::share))
208 .route(WELL_KNOWN_CALDAV, any(pim::well_known))
209 .route(WELL_KNOWN_CARDDAV, any(pim::well_known))
210 .route(PIM, any(pim::handle))
211 .route(&pim_root, any(pim::handle))
212 .route(&pim_item, any(pim::handle))
213 .fallback(spa::fallback)
214 // The editor save body is checked against `MAX_TEXT_BYTES` in the
215 // handler; axum's default limit is the same 2 MiB, which would win
216 // with a plain 413 instead of the localized error.
217 .layer(axum::extract::DefaultBodyLimit::max(
218 files::MAX_TEXT_BYTES as usize + 64 * 1024,
219 ))
220 .with_state(state)
221 // Hard security headers on every response (API and static alike).
222 // CSP/XFO are `if_not_present` so file responses can substitute
223 // [`FILE_CSP`] or the same-origin-framable [`INLINE_CSP`]; everything
224 // else gets the app policy.
225 .layer(SetResponseHeaderLayer::if_not_present(
226 "content-security-policy".parse().unwrap(),
227 HeaderValue::from_static(CSP),
228 ))
229 .layer(SetResponseHeaderLayer::overriding(
230 "x-content-type-options".parse().unwrap(),
231 HeaderValue::from_static("nosniff"),
232 ))
233 .layer(SetResponseHeaderLayer::if_not_present(
234 "x-frame-options".parse().unwrap(),
235 HeaderValue::from_static("DENY"),
236 ))
237 // Not `no-referrer`: that makes browsers send `Origin: null` on
238 // same-origin POSTs, which breaks the passkey origin check.
239 .layer(SetResponseHeaderLayer::overriding(
240 "referrer-policy".parse().unwrap(),
241 HeaderValue::from_static("same-origin"),
242 ))
243}
244