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
182pub(crate) fn validate_account_name(name: &str) -> Result<(), ApiError> {
183 let n = name.trim();
184 if n.is_empty() || n.len() > 64 {
185 return Err(ApiError::localized(
186 StatusCode::BAD_REQUEST,
187 "name must be 1–64 characters",
188 "err_name_length",
189 ));
190 }
191 Ok(())
192}
193
194/// Hash a password off the async executor. Argon2 is slow by design, so
195/// running it inline would block a tokio worker thread for the whole cost.
196pub(crate) async fn hash_password(pw: &str) -> Result<String, ApiError> {
197 let pw = pw.to_string();
198 let _slot = crate::auth::ARGON2_SLOTS.acquire().await;
199 tokio::task::spawn_blocking(move || crate::auth::hash_password(&pw))
200 .await
201 .map_err(|_| {
202 ApiError::localized(
203 StatusCode::INTERNAL_SERVER_ERROR,
204 "internal error",
205 "err_internal",
206 )
207 })?
208 .map_err(|e| {
209 ApiError::new(
210 StatusCode::INTERNAL_SERVER_ERROR,
211 format!("hashing failed: {e}"),
212 )
213 })
214}
215
216pub(crate) fn validate_password(pw: &str) -> Result<(), ApiError> {
217 if pw.len() < 8 {
218 return Err(ApiError::localized(
219 StatusCode::BAD_REQUEST,
220 "password must be at least 8 characters",
221 "err_password_short",
222 ));
223 }
224 Ok(())
225}
226
227/// Extractor for admin-only routes: a signed-in user who is an admin.
228/// Built on [`SessionUser`], so a share token never grants admin.
229pub struct AdminUser {
230 pub user: User,
231}
232
233impl<S> FromRequestParts<S> for AdminUser
234where
235 S: HasState + Send + Sync,
236{
237 type Rejection = ApiError;
238
239 async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> {
240 let auth = SessionUser::from_request_parts(parts, state).await?;
241 if !auth.user.is_admin {
242 return Err(ApiError::localized(
243 StatusCode::FORBIDDEN,
244 "admin only",
245 "err_admin_only",
246 ));
247 }
248 Ok(AdminUser { user: auth.user })
249 }
250}
251