common.rs
⎇
Raw
1//! Authenticated-user extractor shared by all protected API routes.
2
3use std::sync::Arc;
4
5use api_types::P_SHARE;
6use axum::extract::FromRequestParts;
7use axum::http::StatusCode;
8use axum::http::request::Parts;
9
10use crate::auth::parse_session_cookie;
11use crate::db::{RootRow, ShareRow, User};
12use crate::error::{ApiError, AppState};
13
14/// Authorization for the file API: which roots the caller may touch.
15///
16/// Deliberately carries no [`User`]. A share visitor is anonymous, so there
17/// is no identity to expose here. A handler that trusted a user id from this
18/// extractor would treat a share visitor as the share's creator.
19pub struct AuthUser {
20 pub roots: Vec<RootRow>,
21 /// Present when authenticated via a public share token. The single entry
22 /// in `roots` is the shared item (its path is the share's `target`), so all
23 /// file operations are scoped to it.
24 pub share: Option<ShareRow>,
25}
26
27impl<S> FromRequestParts<S> for AuthUser
28where
29 S: HasState + Send + Sync,
30{
31 type Rejection = ApiError;
32
33 async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> {
34 let state = state.state();
35
36 // 1. Public share token (`?share=<token>` or `X-Share-Token`). Checked
37 // first: a request that explicitly carries a share token is a share
38 // request, even if a session is also present (so a signed-in user
39 // viewing a share link sees the shared scope).
40 if let Some(share_token) = share_token_from_request(parts) {
41 return match state.db.share_by_token(&share_token).await? {
42 Some(share) if !share.is_expired() => {
43 let roots = vec![RootRow {
44 id: share.id,
45 path: share.target.clone(),
46 mode: share.mode,
47 }];
48 Ok(AuthUser {
49 roots,
50 share: Some(share),
51 })
52 }
53 Some(_) => Err(ApiError::localized(
54 StatusCode::GONE,
55 "this share has expired",
56 "err_share_expired",
57 )),
58 None => Err(ApiError::localized(
59 StatusCode::NOT_FOUND,
60 "share not found",
61 "err_share_not_found",
62 )),
63 };
64 }
65
66 // 2. Signed-in session. Admins also get the whole server root,
67 // read-only, under `ADMIN_ROOT` (the folder picker in user
68 // management browses it).
69 let (user, mut roots) = session_auth(parts, state).await?;
70 if user.is_admin {
71 roots.push(RootRow {
72 id: api_types::ADMIN_ROOT,
73 path: ".".to_string(),
74 mode: api_types::Mode::Ro,
75 });
76 }
77 Ok(AuthUser { roots, share: None })
78 }
79}
80
81/// Extractor for routes that must never be reachable with a share token:
82/// share management and admin.
83///
84/// A share token only proves that the caller holds a share link. It says
85/// nothing about *who* the caller is, so it must not stand in for the share
86/// creator's identity. Requests that carry one are rejected outright instead
87/// of silently falling back to the session, so a share visitor cannot act as
88/// the creator by also having a cookie.
89pub struct SessionUser {
90 pub user: User,
91 pub roots: Vec<RootRow>,
92}
93
94impl<S> FromRequestParts<S> for SessionUser
95where
96 S: HasState + Send + Sync,
97{
98 type Rejection = ApiError;
99
100 async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> {
101 if share_token_from_request(parts).is_some() {
102 return Err(ApiError::localized(
103 StatusCode::FORBIDDEN,
104 "a share token cannot be used here; sign in instead",
105 "err_share_token_forbidden",
106 ));
107 }
108 let (user, roots) = session_auth(parts, state.state()).await?;
109 Ok(SessionUser { user, roots })
110 }
111}
112
113/// Authenticate via the session cookie only, returning the user and roots.
114async fn session_auth(parts: &Parts, state: &AppState) -> Result<(User, Vec<RootRow>), ApiError> {
115 let Some(token) = parse_session_cookie(&parts.headers) else {
116 return Err(ApiError::localized(
117 StatusCode::UNAUTHORIZED,
118 "not signed in",
119 "err_not_signed_in",
120 ));
121 };
122 let Some((user, roots)) = state.db.session_user_with_roots(&token).await? else {
123 return Err(ApiError::localized(
124 StatusCode::UNAUTHORIZED,
125 "session expired, please sign in again",
126 "err_session_expired",
127 ));
128 };
129 Ok((user, roots))
130}
131
132/// Extract the share token from a request, if present: a `?share=<token>`
133/// query param or an `X-Share-Token` header.
134fn share_token_from_request(parts: &Parts) -> Option<String> {
135 if let Some(q) = parts.uri.query() {
136 for pair in q.split('&') {
137 if let Some((k, v)) = pair.split_once('=')
138 && k == P_SHARE
139 && !v.is_empty()
140 {
141 return Some(v.to_string());
142 }
143 }
144 }
145 parts
146 .headers
147 .get("x-share-token")
148 .and_then(|v| v.to_str().ok())
149 .filter(|s| !s.is_empty())
150 .map(|s| s.to_string())
151}
152
153/// Lets the extractor pull the concrete state type out of a generic `S`.
154pub trait HasState {
155 fn state(&self) -> &AppState;
156}
157
158impl HasState for Arc<AppState> {
159 fn state(&self) -> &AppState {
160 self
161 }
162}
163
164// ---------------------------------------------------------------------------
165// Shared validation / naming helpers
166// ---------------------------------------------------------------------------
167
168/// Display name for a root path: the file/folder name, or the server root's
169/// own name when the path is the whole root (".").
170/// UI name of a root or share target `rel` (relative to the server root):
171/// its last path component, or the configured root name for `.`.
172pub(crate) fn display_name(state: &AppState, rel: &str) -> String {
173 if rel == "." {
174 return state.root_name.clone();
175 }
176 std::path::Path::new(rel)
177 .file_name()
178 .map(|s| s.to_string_lossy().into_owned())
179 .unwrap_or_else(|| rel.to_string())
180}
181
182/// A resolved absolute path re-expressed relative to the server root — the
183/// form `shares.target` is stored in, so share lookups and share revokes both
184/// speak the same spelling of a path.
185pub(crate) fn target_rel(state: &AppState, abs: &std::path::Path) -> String {
186 abs.strip_prefix(&state.root)
187 .map(|p| p.to_string_lossy().into_owned())
188 .unwrap_or_else(|_| ".".to_string())
189}
190
191pub(crate) fn validate_account_name(name: &str) -> Result<(), ApiError> {
192 let n = name.trim();
193 if n.is_empty() || n.len() > 64 {
194 return Err(ApiError::localized(
195 StatusCode::BAD_REQUEST,
196 "name must be 1–64 characters",
197 "err_name_length",
198 ));
199 }
200 Ok(())
201}
202
203/// Hash a password off the async executor. Argon2 is slow by design, so
204/// running it inline would block a tokio worker thread for the whole cost.
205pub(crate) async fn hash_password(pw: &str) -> Result<String, ApiError> {
206 let pw = pw.to_string();
207 let _slot = crate::auth::ARGON2_SLOTS.acquire().await;
208 tokio::task::spawn_blocking(move || crate::auth::hash_password(&pw))
209 .await
210 .map_err(|_| {
211 ApiError::localized(
212 StatusCode::INTERNAL_SERVER_ERROR,
213 "internal error",
214 "err_internal",
215 )
216 })?
217 .map_err(|e| {
218 ApiError::new(
219 StatusCode::INTERNAL_SERVER_ERROR,
220 format!("hashing failed: {e}"),
221 )
222 })
223}
224
225pub(crate) fn validate_password(pw: &str) -> Result<(), ApiError> {
226 if pw.len() < 8 {
227 return Err(ApiError::localized(
228 StatusCode::BAD_REQUEST,
229 "password must be at least 8 characters",
230 "err_password_short",
231 ));
232 }
233 Ok(())
234}
235
236/// Extractor for admin-only routes: a signed-in user who is an admin.
237/// Built on [`SessionUser`], so a share token never grants admin.
238pub struct AdminUser {
239 pub user: User,
240}
241
242impl<S> FromRequestParts<S> for AdminUser
243where
244 S: HasState + Send + Sync,
245{
246 type Rejection = ApiError;
247
248 async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> {
249 let auth = SessionUser::from_request_parts(parts, state).await?;
250 if !auth.user.is_admin {
251 return Err(ApiError::localized(
252 StatusCode::FORBIDDEN,
253 "admin only",
254 "err_admin_only",
255 ));
256 }
257 Ok(AdminUser { user: auth.user })
258 }
259}
260