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_CONTACTS, PIM_INSTANCES, PIM_INVITATIONS, PIM_SYSTEM_EXPORT, SEARCH, SHARE,
9 SHARE_UNLOCK_SUFFIX, SHARES, SHARES_SUFFIX, 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 pim_views;
102mod search;
103mod shares;
104mod spa;
105
106pub fn router(state: Arc<AppState>) -> Router {
107 // Route patterns: the server side of the shared endpoint strings in
108 // `api_types` (axum copies them into the route table on insert).
109 let files_root = format!("{FILES}/{{root_id}}");
110 let files_item = format!("{FILES}/{{root_id}}/{{*path}}");
111 let shares_id = format!("{SHARES}/{{id}}");
112 let share_token = format!("{SHARE}/{{token}}");
113 let share_unlock = format!("{SHARE}/{{token}}{SHARE_UNLOCK_SUFFIX}");
114 let admin_user_id = format!("{ADMIN_USERS}/{{id}}");
115 let passkey_id = format!("{AUTH_PASSKEYS}/{{id}}");
116 let app_password_id = format!("{AUTH_APP_PASSWORDS}/{{id}}");
117 let passkey_register_finish = format!("{AUTH_PASSKEYS_REGISTER}{FINISH_SUFFIX}");
118 let passkey_login_finish = format!("{AUTH_PASSKEY_LOGIN}{FINISH_SUFFIX}");
119 let admin_share_id = format!("{ADMIN_SHARES}/{{id}}");
120 let admin_room_id = format!("{ADMIN_ROOMS}/{{id}}");
121 let pim_shares = format!("{PIM_COLLECTIONS}/{{id}}{SHARES_SUFFIX}");
122 let pim_share = format!("{PIM_COLLECTIONS}/{{id}}{SHARES_SUFFIX}/{{user_id}}");
123 let pim_links = format!("{PIM_COLLECTIONS}/{{id}}{LINKS_SUFFIX}");
124 let pim_link = format!("{PIM_COLLECTIONS}/{{id}}{LINKS_SUFFIX}/{{link_id}}");
125 let pim_import = format!("{PIM_COLLECTIONS}/{{id}}{IMPORT_SUFFIX}");
126 let pim_export = format!("{PIM_COLLECTIONS}/{{id}}{EXPORT_SUFFIX}");
127 let pim_collection = format!("{PIM_COLLECTIONS}/{{id}}");
128 let pim_object = format!("{PIM_COLLECTIONS}/{{id}}{OBJECTS_SUFFIX}/{{name}}");
129 let pim_photo = format!("{PIM_COLLECTIONS}/{{id}}{OBJECTS_SUFFIX}/{{name}}{PHOTO_SUFFIX}");
130 let admin_pim_link = format!("{ADMIN_PIM_LINKS}/{{id}}");
131 let feed = format!("{FEED}/{{file}}");
132 // A wildcard needs something to capture, so `/dav/` gets its own pattern:
133 // mount clients ask for it with the trailing slash, which matches neither
134 // the bare path nor `{*path}`.
135 let dav_root = format!("{DAV}/");
136 let dav_item = format!("{DAV}/{{*path}}");
137 let dav_share = format!("{DAV_SHARE}/{{*path}}");
138 let pim_root = format!("{PIM}/");
139 let pim_item = format!("{PIM}/{{*path}}");
140
141 Router::new()
142 .route(AUTH_LOGIN, post(auth::login))
143 .route(AUTH_LOGOUT, post(auth::logout))
144 .route(AUTH_ME, get(auth::me).put(auth::update_profile))
145 .route(AUTH_SETUP, post(auth::setup))
146 .route(
147 AUTH_PASSWORD,
148 post(passkeys::change_password).delete(passkeys::delete_password),
149 )
150 .route(AUTH_MODE, put(passkeys::set_mode))
151 // axum matches a literal segment before a parameter, so `/register`
152 // and `{id}` can both live under this path.
153 .route(AUTH_PASSKEYS, get(passkeys::list))
154 .route(AUTH_PASSKEYS_REGISTER, post(passkeys::register_begin))
155 .route(&passkey_register_finish, post(passkeys::register_finish))
156 .route(&passkey_id, delete(passkeys::delete))
157 .route(AUTH_PASSKEY_LOGIN, post(passkeys::login_begin))
158 .route(&passkey_login_finish, post(passkeys::login_finish))
159 .route(
160 AUTH_APP_PASSWORDS,
161 get(app_passwords::list).post(app_passwords::create),
162 )
163 .route(&app_password_id, delete(app_passwords::delete))
164 .route(SEARCH, get(search::search))
165 .route(
166 &files_root,
167 get(files::file_get)
168 .put(files::file_put)
169 .post(files::dispatch),
170 )
171 .route(
172 &files_item,
173 get(files::file_get)
174 .put(files::file_put)
175 .post(files::dispatch)
176 .delete(files::delete),
177 )
178 .route(SHARES, get(shares::list))
179 .route(SHARES, post(shares::create))
180 .route(&shares_id, delete(shares::delete))
181 .route(&share_token, get(shares::resolve))
182 .route(&share_unlock, post(shares::unlock))
183 .route(ADMIN_USERS, get(admin::list_users))
184 .route(ADMIN_USERS, post(admin::create_user))
185 .route(&admin_user_id, put(admin::update_user))
186 .route(&admin_user_id, delete(admin::delete_user))
187 .route(ADMIN_SHARES, get(admin::list_shares))
188 .route(&admin_share_id, delete(admin::delete_share))
189 .route(ADMIN_ROOMS, get(admin::list_rooms).post(admin::create_room))
190 .route(
191 &admin_room_id,
192 put(admin::update_room).delete(admin::delete_room),
193 )
194 .route(PIM_COLLECTIONS, get(pim_api::list).post(pim_api::create))
195 .route(
196 &pim_collection,
197 put(pim_api::update).delete(pim_api::delete),
198 )
199 .route(&pim_object, get(pim_views::object))
200 .route(PIM_INSTANCES, get(pim_views::instances))
201 .route(PIM_CONTACTS, get(pim_views::contacts))
202 .route(
203 PIM_INVITATIONS,
204 get(pim_views::invitations).post(pim_views::reply),
205 )
206 .route(&pim_shares, get(pim_api::shares).post(pim_api::share))
207 .route(&pim_share, delete(pim_api::unshare))
208 .route(&pim_links, get(pim_api::links).post(pim_api::create_link))
209 .route(&pim_link, delete(pim_api::delete_link))
210 .route(&pim_import, post(pim_api::import))
211 .route(&pim_export, get(pim_api::export))
212 .route(PIM_SYSTEM_EXPORT, get(pim_api::export_system))
213 .route(&pim_photo, get(pim_api::photo))
214 .route(ADMIN_PIM_LINKS, get(admin::list_pim_links))
215 .route(&admin_pim_link, delete(admin::delete_pim_link))
216 .route(&feed, get(pim_api::feed))
217 .route(ADMIN_SETTINGS, get(admin::get_settings))
218 .route(ADMIN_SETTINGS, put(admin::update_settings))
219 // `any`, not a method filter: WebDAV's verbs (PROPFIND, MKCOL, MOVE, …)
220 // are not in axum's `MethodFilter`, and a method router's fallback
221 // takes every one of them.
222 .route(DAV, any(dav::user))
223 .route(&dav_root, any(dav::user))
224 .route(&dav_item, any(dav::user))
225 .route(&dav_share, any(dav::share))
226 .route(WELL_KNOWN_CALDAV, any(pim::well_known))
227 .route(WELL_KNOWN_CARDDAV, any(pim::well_known))
228 .route(PIM, any(pim::handle))
229 .route(&pim_root, any(pim::handle))
230 .route(&pim_item, any(pim::handle))
231 .fallback(spa::fallback)
232 // The editor save body is checked against `MAX_TEXT_BYTES` in the
233 // handler; axum's default limit is the same 2 MiB, which would win
234 // with a plain 413 instead of the localized error.
235 .layer(axum::extract::DefaultBodyLimit::max(
236 files::MAX_TEXT_BYTES as usize + 64 * 1024,
237 ))
238 .with_state(state)
239 // Hard security headers on every response (API and static alike).
240 // CSP/XFO are `if_not_present` so file responses can substitute
241 // [`FILE_CSP`] or the same-origin-framable [`INLINE_CSP`]; everything
242 // else gets the app policy.
243 .layer(SetResponseHeaderLayer::if_not_present(
244 "content-security-policy".parse().unwrap(),
245 HeaderValue::from_static(CSP),
246 ))
247 .layer(SetResponseHeaderLayer::overriding(
248 "x-content-type-options".parse().unwrap(),
249 HeaderValue::from_static("nosniff"),
250 ))
251 .layer(SetResponseHeaderLayer::if_not_present(
252 "x-frame-options".parse().unwrap(),
253 HeaderValue::from_static("DENY"),
254 ))
255 // Not `no-referrer`: that makes browsers send `Origin: null` on
256 // same-origin POSTs, which breaks the passkey origin check.
257 .layer(SetResponseHeaderLayer::overriding(
258 "referrer-policy".parse().unwrap(),
259 HeaderValue::from_static("same-origin"),
260 ))
261}
262