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