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.
67 let (_user, roots) = session_auth(parts, state).await?;
68 Ok(AuthUser { roots, share: None })
69 }
70}
71
72/// Extractor for routes that must never be reachable with a share token:
73/// share management and admin.
74///
75/// A share token only proves that the caller holds a share link. It says
76/// nothing about *who* the caller is, so it must not stand in for the share
77/// creator's identity. Requests that carry one are rejected outright instead
78/// of silently falling back to the session, so a share visitor cannot act as
79/// the creator by also having a cookie.
80pub struct SessionUser {
81 pub user: User,
82 pub roots: Vec<RootRow>,
83}
84
85impl<S> FromRequestParts<S> for SessionUser
86where
87 S: HasState + Send + Sync,
88{
89 type Rejection = ApiError;
90
91 async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> {
92 if share_token_from_request(parts).is_some() {
93 return Err(ApiError::localized(
94 StatusCode::FORBIDDEN,
95 "a share token cannot be used here; sign in instead",
96 "err_share_token_forbidden",
97 ));
98 }
99 let (user, roots) = session_auth(parts, state.state()).await?;
100 Ok(SessionUser { user, roots })
101 }
102}
103
104/// Authenticate via the session cookie only, returning the user and roots.
105async fn session_auth(parts: &Parts, state: &AppState) -> Result<(User, Vec<RootRow>), ApiError> {
106 let Some(token) = parse_session_cookie(&parts.headers) else {
107 return Err(ApiError::localized(
108 StatusCode::UNAUTHORIZED,
109 "not signed in",
110 "err_not_signed_in",
111 ));
112 };
113 let Some(user) = state.db.session_user(&token).await? else {
114 return Err(ApiError::localized(
115 StatusCode::UNAUTHORIZED,
116 "session expired, please sign in again",
117 "err_session_expired",
118 ));
119 };
120 let roots = state.db.user_roots(user.id).await?;
121 Ok((user, roots))
122}
123
124/// Extract the share token from a request, if present: a `?share=<token>`
125/// query param or an `X-Share-Token` header.
126fn share_token_from_request(parts: &Parts) -> Option<String> {
127 if let Some(q) = parts.uri.query() {
128 for pair in q.split('&') {
129 if let Some((k, v)) = pair.split_once('=')
130 && k == P_SHARE
131 && !v.is_empty()
132 {
133 return Some(v.to_string());
134 }
135 }
136 }
137 parts
138 .headers
139 .get("x-share-token")
140 .and_then(|v| v.to_str().ok())
141 .filter(|s| !s.is_empty())
142 .map(|s| s.to_string())
143}
144
145/// Lets the extractor pull the concrete state type out of a generic `S`.
146pub trait HasState {
147 fn state(&self) -> &AppState;
148}
149
150impl HasState for Arc<AppState> {
151 fn state(&self) -> &AppState {
152 self
153 }
154}
155
156// ---------------------------------------------------------------------------
157// Shared validation / naming helpers
158// ---------------------------------------------------------------------------
159
160/// Display name for a root path: the file/folder name, or the server root's
161/// own name when the path is the whole root (".").
162pub(crate) fn display_name(server_root: &std::path::Path, rel: &str) -> String {
163 let name = if rel == "." {
164 server_root.file_name()
165 } else {
166 std::path::Path::new(rel)
167 .file_name()
168 .filter(|_| !std::path::Path::new(rel).as_os_str().is_empty())
169 };
170 name.map(|s| s.to_string_lossy().into_owned())
171 .unwrap_or_else(|| rel.to_string())
172}
173
174pub(crate) fn validate_account_name(name: &str) -> Result<(), ApiError> {
175 let n = name.trim();
176 if n.is_empty() || n.len() > 64 {
177 return Err(ApiError::localized(
178 StatusCode::BAD_REQUEST,
179 "name must be 1–64 characters",
180 "err_name_length",
181 ));
182 }
183 Ok(())
184}
185
186/// Hash a password off the async executor. Argon2 is slow by design, so
187/// running it inline would block a tokio worker thread for the whole cost.
188pub(crate) async fn hash_password(pw: &str) -> Result<String, ApiError> {
189 let pw = pw.to_string();
190 tokio::task::spawn_blocking(move || crate::auth::hash_password(&pw))
191 .await
192 .map_err(|_| {
193 ApiError::localized(
194 StatusCode::INTERNAL_SERVER_ERROR,
195 "internal error",
196 "err_internal",
197 )
198 })?
199 .map_err(|e| {
200 ApiError::new(
201 StatusCode::INTERNAL_SERVER_ERROR,
202 format!("hashing failed: {e}"),
203 )
204 })
205}
206
207pub(crate) fn validate_password(pw: &str) -> Result<(), ApiError> {
208 if pw.len() < 8 {
209 return Err(ApiError::localized(
210 StatusCode::BAD_REQUEST,
211 "password must be at least 8 characters",
212 "err_password_short",
213 ));
214 }
215 Ok(())
216}
217
218/// Extractor for admin-only routes: a signed-in user who is an admin.
219/// Built on [`SessionUser`], so a share token never grants admin.
220pub struct AdminUser {
221 pub user: User,
222}
223
224impl<S> FromRequestParts<S> for AdminUser
225where
226 S: HasState + Send + Sync,
227{
228 type Rejection = ApiError;
229
230 async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> {
231 let auth = SessionUser::from_request_parts(parts, state).await?;
232 if !auth.user.is_admin {
233 return Err(ApiError::localized(
234 StatusCode::FORBIDDEN,
235 "admin only",
236 "err_admin_only",
237 ));
238 }
239 Ok(AdminUser { user: auth.user })
240 }
241}
242