Merge pull request #347 from abnvle/feat/share-folder-browsing

This commit is contained in:
Dionisio Pozo
2026-05-14 00:07:45 +02:00
committed by GitHub
12 changed files with 1592 additions and 131 deletions
+48 -46
View File
@@ -967,56 +967,15 @@ impl FileHandler {
/// Build a Content-Disposition header value.
///
/// Uses RFC 5987 `filename*=UTF-8''<percent-encoded>` to safely handle
/// filenames with quotes, non-ASCII characters, or other special chars.
/// A sanitised ASCII `filename=` fallback is included for legacy clients.
/// Build a `Content-Disposition` header value for an authenticated download,
/// honouring the `?inline=true|1` query param. Delegates to the shared
/// `build_content_disposition` so the share-link path produces identical
/// header values for the same `(name, mime)` pair.
fn content_disposition(name: &str, mime: &str, params: &HashMap<String, String>) -> String {
let force_inline = params
.get("inline")
.is_some_and(|v| v == "true" || v == "1");
let disposition = if force_inline
|| mime.starts_with("image/")
|| mime == "application/pdf"
|| mime.starts_with("video/")
|| mime.starts_with("audio/")
{
"inline"
} else {
"attachment"
};
// RFC 5987 percent-encode for filename* (attr-char safe set)
use percent_encoding::{AsciiSet, NON_ALPHANUMERIC, utf8_percent_encode};
// Characters that DON'T need encoding per RFC 5987 attr-char:
// ALPHA / DIGIT / "!" / "#" / "$" / "&" / "+" / "-" / "." /
// "^" / "_" / "`" / "|" / "~"
const RFC5987_SET: &AsciiSet = &NON_ALPHANUMERIC
.remove(b'!')
.remove(b'#')
.remove(b'$')
.remove(b'&')
.remove(b'+')
.remove(b'-')
.remove(b'.')
.remove(b'^')
.remove(b'_')
.remove(b'`')
.remove(b'|')
.remove(b'~');
let encoded = utf8_percent_encode(name, RFC5987_SET).to_string();
// ASCII fallback: strip anything outside printable ASCII and
// replace '"' and '\\' to prevent header injection.
let ascii_safe: String = name
.chars()
.filter(|c| c.is_ascii_graphic() || *c == ' ')
.map(|c| match c {
'"' | '\\' => '_',
_ => c,
})
.collect();
format!("{disposition}; filename=\"{ascii_safe}\"; filename*=UTF-8''{encoded}")
build_content_disposition(name, mime, force_inline)
}
/// Build a 201 Created JSON response.
@@ -1073,6 +1032,49 @@ pub struct MoveFilePayload {
pub folder_id: Option<String>,
}
/// RFC 5987-compliant `Content-Disposition` with both ASCII fallback and
/// `filename*=UTF-8''...` for non-ASCII filenames.
pub(super) fn build_content_disposition(name: &str, mime: &str, force_inline: bool) -> String {
let disposition = if force_inline
|| mime.starts_with("image/")
|| mime == "application/pdf"
|| mime.starts_with("video/")
|| mime.starts_with("audio/")
{
"inline"
} else {
"attachment"
};
use percent_encoding::{AsciiSet, NON_ALPHANUMERIC, utf8_percent_encode};
// RFC 5987 attr-char safe set (no encoding needed for these).
const RFC5987_SET: &AsciiSet = &NON_ALPHANUMERIC
.remove(b'!')
.remove(b'#')
.remove(b'$')
.remove(b'&')
.remove(b'+')
.remove(b'-')
.remove(b'.')
.remove(b'^')
.remove(b'_')
.remove(b'`')
.remove(b'|')
.remove(b'~');
let encoded = utf8_percent_encode(name, RFC5987_SET).to_string();
let ascii_safe: String = name
.chars()
.filter(|c| c.is_ascii_graphic() || *c == ' ')
.map(|c| match c {
'"' | '\\' => '_',
_ => c,
})
.collect();
format!("{disposition}; filename=\"{ascii_safe}\"; filename*=UTF-8''{encoded}")
}
// ── Route handlers (free functions) ──────────────────────────────────────────
//
// All annotated route functions live here rather than as methods on FileHandler
+406 -34
View File
@@ -8,12 +8,15 @@ use axum::{
http::{HeaderMap, StatusCode, header},
response::{IntoResponse, Response},
};
use http_range_header::parse_range_header;
use serde::Deserialize;
use serde_json::json;
use utoipa::ToSchema;
use crate::application::services::share_browse_service::ZipTarget;
use crate::application::services::share_service::ShareService;
use crate::infrastructure::services::share_unlock_cookie;
use crate::interfaces::api::handlers::file_handler::build_content_disposition;
use crate::{
application::{
dtos::share_dto::{CreateShareDto, UpdateShareDto},
@@ -27,6 +30,7 @@ use crate::{
interfaces::errors::AppError,
interfaces::middleware::auth::AuthUser,
};
use tokio_util::io::ReaderStream;
fn unlock_jwt_from_headers(headers: &HeaderMap, share_token: &str) -> Option<String> {
headers
@@ -370,46 +374,414 @@ pub async fn download_shared_file(
return AppError::bad_request("Download is only supported for file shares").into_response();
}
// 4. Retrieve file content via the internal (no-ownership-check) API
// 4. Stream the file with full Range / 304 / 416 / 206 support.
serve_share_file(
&state,
&share_dto.item_id,
share_dto.item_name.as_deref(),
&headers,
)
.await
}
/// Stream a file for a public share. Honours `If-None-Match` (304),
/// `Range` (206 / 416), and falls back to a 200 via `get_file_optimized`.
async fn serve_share_file(
state: &Arc<AppState>,
file_id: &str,
name_override: Option<&str>,
request_headers: &HeaderMap,
) -> Response {
let retrieval = &state.applications.file_retrieval_service;
let file_id = &share_dto.item_id;
match retrieval.get_file_optimized(file_id, false, true).await {
Ok((file_dto, content)) => {
let file_name = share_dto.item_name.as_deref().unwrap_or(&file_dto.name);
let disposition = format!(
"attachment; filename=\"{}\"",
file_name.replace('"', "\\\"")
);
let mime = file_dto.mime_type.clone();
let file_dto = match retrieval.get_file(file_id).await {
Ok(d) => d,
Err(err) => return AppError::from(err).into_response(),
};
match content {
OptimizedFileContent::Bytes { data, .. } => Response::builder()
.status(StatusCode::OK)
.header(header::CONTENT_TYPE, &*mime)
.header(header::CONTENT_DISPOSITION, &disposition)
.header(header::CONTENT_LENGTH, data.len())
.body(Body::from(data))
let display_name = name_override.unwrap_or(&file_dto.name);
let etag = format!("\"{}-{}\"", file_dto.id, file_dto.modified_at);
let mime = file_dto.mime_type.clone();
let disposition = build_content_disposition(display_name, &mime, false);
if let Some(inm) = request_headers.get(header::IF_NONE_MATCH)
&& let Ok(client_etag) = inm.to_str()
&& (client_etag == etag || client_etag == "*")
{
return Response::builder()
.status(StatusCode::NOT_MODIFIED)
.header(header::ETAG, &etag)
.header(
header::CACHE_CONTROL,
"private, max-age=3600, must-revalidate",
)
.header(header::VARY, "Cookie, Range")
.body(Body::empty())
.unwrap()
.into_response();
}
if let Some(range_hdr) = request_headers.get(header::RANGE)
&& let Ok(range_str) = range_hdr.to_str()
&& let Ok(ranges) = parse_range_header(range_str)
{
match ranges.validate(file_dto.size) {
Ok(valid_ranges) => {
if let Some(range) = valid_ranges.first() {
let start = *range.start();
let end = *range.end();
let length = end - start + 1;
match retrieval
.get_file_range_stream(file_id, start, Some(end + 1))
.await
{
Ok(stream) => {
return Response::builder()
.status(StatusCode::PARTIAL_CONTENT)
.header(header::CONTENT_TYPE, &*mime)
.header(header::CONTENT_DISPOSITION, &disposition)
.header(header::CONTENT_LENGTH, length)
.header(
header::CONTENT_RANGE,
format!("bytes {}-{}/{}", start, end, file_dto.size),
)
.header(header::ACCEPT_RANGES, "bytes")
.header(header::ETAG, &etag)
.header(
header::CACHE_CONTROL,
"private, max-age=3600, must-revalidate",
)
.header(header::VARY, "Cookie, Range")
.body(Body::from_stream(Box::into_pin(stream)))
.unwrap()
.into_response();
}
Err(err) => {
tracing::error!("share range stream error: {}", err);
}
}
}
}
Err(_) => {
return Response::builder()
.status(StatusCode::RANGE_NOT_SATISFIABLE)
.header(header::CONTENT_RANGE, format!("bytes */{}", file_dto.size))
.header(
header::CACHE_CONTROL,
"private, max-age=3600, must-revalidate",
)
.header(header::VARY, "Cookie, Range")
.body(Body::empty())
.unwrap()
.into_response(),
OptimizedFileContent::Mmap(mmap_data) => Response::builder()
.status(StatusCode::OK)
.header(header::CONTENT_TYPE, &*mime)
.header(header::CONTENT_DISPOSITION, &disposition)
.header(header::CONTENT_LENGTH, mmap_data.len())
.body(Body::from(mmap_data))
.unwrap()
.into_response(),
OptimizedFileContent::Stream(stream) => Response::builder()
.status(StatusCode::OK)
.header(header::CONTENT_TYPE, &*mime)
.header(header::CONTENT_DISPOSITION, &disposition)
.header(header::CONTENT_LENGTH, file_dto.size)
.body(Body::from_stream(stream))
.unwrap()
.into_response(),
.into_response();
}
}
}
match retrieval.get_file_optimized(file_id, false, true).await {
Ok((_, content)) => match content {
OptimizedFileContent::Bytes { data, .. } => Response::builder()
.status(StatusCode::OK)
.header(header::CONTENT_TYPE, &*mime)
.header(header::CONTENT_DISPOSITION, &disposition)
.header(header::CONTENT_LENGTH, data.len())
.header(header::ACCEPT_RANGES, "bytes")
.header(header::ETAG, &etag)
.header(
header::CACHE_CONTROL,
"private, max-age=3600, must-revalidate",
)
.header(header::VARY, "Cookie, Range")
.body(Body::from(data))
.unwrap()
.into_response(),
OptimizedFileContent::Mmap(mmap_data) => Response::builder()
.status(StatusCode::OK)
.header(header::CONTENT_TYPE, &*mime)
.header(header::CONTENT_DISPOSITION, &disposition)
.header(header::CONTENT_LENGTH, mmap_data.len())
.header(header::ACCEPT_RANGES, "bytes")
.header(header::ETAG, &etag)
.header(
header::CACHE_CONTROL,
"private, max-age=3600, must-revalidate",
)
.header(header::VARY, "Cookie, Range")
.body(Body::from(mmap_data))
.unwrap()
.into_response(),
OptimizedFileContent::Stream(stream) => Response::builder()
.status(StatusCode::OK)
.header(header::CONTENT_TYPE, &*mime)
.header(header::CONTENT_DISPOSITION, &disposition)
.header(header::CONTENT_LENGTH, file_dto.size)
.header(header::ACCEPT_RANGES, "bytes")
.header(header::ETAG, &etag)
.header(
header::CACHE_CONTROL,
"private, max-age=3600, must-revalidate",
)
.header(header::VARY, "Cookie, Range")
.body(Body::from_stream(stream))
.unwrap()
.into_response(),
},
Err(err) => AppError::from(err).into_response(),
}
}
// ── Public folder browsing endpoints ──────────────────────────────────────
fn sharing_disabled_response() -> Response {
AppError::new(
StatusCode::SERVICE_UNAVAILABLE,
"Sharing is disabled",
"Disabled",
)
.into_response()
}
fn share_browse_error_response(err: crate::common::errors::DomainError) -> Response {
if err.kind == ErrorKind::AccessDenied {
if err.message.contains("password") {
return (
StatusCode::UNAUTHORIZED,
Json(json!({
"error": "Password required",
"requiresPassword": true
})),
)
.into_response();
}
if err.message.contains("expired") {
return AppError::new(StatusCode::GONE, err.message, "Expired").into_response();
}
}
AppError::from(err).into_response()
}
#[utoipa::path(
get,
path = "/api/s/{token}/contents",
params(("token" = String, Path, description = "Share token")),
responses(
(status = 200, description = "Folder contents (sub-folders + files)"),
(status = 400, description = "Share is not a folder share"),
(status = 401, description = "Password required"),
(status = 410, description = "Share expired"),
(status = 503, description = "Sharing disabled")
),
tag = "shares"
)]
pub async fn list_share_contents_root(
State(state): State<Arc<AppState>>,
Path(token): Path<String>,
headers: HeaderMap,
) -> impl IntoResponse {
let Some(browse) = state.share_browse_service.clone() else {
return sharing_disabled_response();
};
let unlock_jwt = unlock_jwt_from_headers(&headers, &token);
match browse.list_root(&token, unlock_jwt.as_deref()).await {
Ok(listing) => (StatusCode::OK, Json(listing)).into_response(),
Err(err) => share_browse_error_response(err),
}
}
#[utoipa::path(
get,
path = "/api/s/{token}/contents/{folder_id}",
params(
("token" = String, Path, description = "Share token"),
("folder_id" = String, Path, description = "Subfolder ID (must be inside the share)")
),
responses(
(status = 200, description = "Subfolder contents"),
(status = 400, description = "Share is not a folder share"),
(status = 401, description = "Password required"),
(status = 404, description = "Subfolder not found or not in share scope"),
(status = 410, description = "Share expired"),
(status = 503, description = "Sharing disabled")
),
tag = "shares"
)]
pub async fn list_share_contents_subfolder(
State(state): State<Arc<AppState>>,
Path((token, folder_id)): Path<(String, String)>,
headers: HeaderMap,
) -> impl IntoResponse {
let Some(browse) = state.share_browse_service.clone() else {
return sharing_disabled_response();
};
let unlock_jwt = unlock_jwt_from_headers(&headers, &token);
match browse
.list_subfolder(&token, &folder_id, unlock_jwt.as_deref())
.await
{
Ok(listing) => (StatusCode::OK, Json(listing)).into_response(),
Err(err) => share_browse_error_response(err),
}
}
#[utoipa::path(
get,
path = "/api/s/{token}/file/{file_id}",
params(
("token" = String, Path, description = "Share token"),
("file_id" = String, Path, description = "File ID (must be inside the share)")
),
responses(
(status = 200, description = "File content (or 206 for Range request)"),
(status = 206, description = "Partial Content"),
(status = 304, description = "Not Modified"),
(status = 401, description = "Password required"),
(status = 404, description = "File not found or not in share scope"),
(status = 410, description = "Share expired"),
(status = 416, description = "Range not satisfiable")
),
tag = "shares"
)]
pub async fn download_share_file_in_folder(
State(state): State<Arc<AppState>>,
Path((token, file_id)): Path<(String, String)>,
headers: HeaderMap,
) -> impl IntoResponse {
let Some(browse) = state.share_browse_service.clone() else {
return sharing_disabled_response();
};
let unlock_jwt = unlock_jwt_from_headers(&headers, &token);
if let Err(err) = browse
.assert_file_in_share(&token, &file_id, unlock_jwt.as_deref())
.await
{
return share_browse_error_response(err);
}
serve_share_file(&state, &file_id, None, &headers).await
}
#[utoipa::path(
get,
path = "/api/s/{token}/zip",
params(("token" = String, Path, description = "Share token")),
responses(
(status = 200, description = "ZIP archive of the shared folder"),
(status = 400, description = "Share is not a folder share"),
(status = 401, description = "Password required"),
(status = 410, description = "Share expired"),
(status = 503, description = "Sharing or ZIP service disabled")
),
tag = "shares"
)]
pub async fn download_share_zip_root(
State(state): State<Arc<AppState>>,
Path(token): Path<String>,
headers: HeaderMap,
) -> impl IntoResponse {
serve_share_zip(state, token, None, headers).await
}
#[utoipa::path(
get,
path = "/api/s/{token}/zip/{folder_id}",
params(
("token" = String, Path, description = "Share token"),
("folder_id" = String, Path, description = "Subfolder ID (must be inside the share)")
),
responses(
(status = 200, description = "ZIP archive of the subfolder"),
(status = 401, description = "Password required"),
(status = 404, description = "Subfolder not found or not in share scope"),
(status = 410, description = "Share expired"),
(status = 503, description = "Sharing or ZIP service disabled")
),
tag = "shares"
)]
pub async fn download_share_zip_subfolder(
State(state): State<Arc<AppState>>,
Path((token, folder_id)): Path<(String, String)>,
headers: HeaderMap,
) -> impl IntoResponse {
serve_share_zip(state, token, Some(folder_id), headers).await
}
async fn serve_share_zip(
state: Arc<AppState>,
token: String,
folder_id: Option<String>,
headers: HeaderMap,
) -> Response {
let Some(browse) = state.share_browse_service.clone() else {
return sharing_disabled_response();
};
let zip_service = match &state.core.zip_service {
Some(svc) => svc,
None => {
return AppError::new(
StatusCode::SERVICE_UNAVAILABLE,
"ZIP service not initialized",
"Disabled",
)
.into_response();
}
};
let unlock_jwt = unlock_jwt_from_headers(&headers, &token);
let target: ZipTarget = match browse
.resolve_zip_target(&token, folder_id.as_deref(), unlock_jwt.as_deref())
.await
{
Ok(t) => t,
Err(err) => return share_browse_error_response(err),
};
let temp_file = match zip_service
.create_folder_zip(&target.folder_id, &target.display_name)
.await
{
Ok(f) => f,
Err(err) => {
tracing::error!("share zip: create_folder_zip failed: {}", err);
return AppError::internal_error(format!("ZIP creation failed: {}", err))
.into_response();
}
};
let file_size = match temp_file.as_file().metadata() {
Ok(m) => m.len(),
Err(e) => {
tracing::error!("share zip: temp metadata failed: {}", e);
return AppError::internal_error("ZIP creation failed").into_response();
}
};
// Reuse the existing fd: split off the std::File and the TempPath.
let (std_file, temp_path) = temp_file.into_parts();
let tokio_file = tokio::fs::File::from_std(std_file);
let stream = ReaderStream::new(tokio_file);
let body = Body::from_stream(stream);
let disposition = build_content_disposition(
&format!("{}.zip", target.display_name),
"application/zip",
false,
);
let mut response = Response::builder()
.status(StatusCode::OK)
.header(header::CONTENT_TYPE, "application/zip")
.header(header::CONTENT_DISPOSITION, disposition)
.header(header::CONTENT_LENGTH, file_size)
.header(header::CACHE_CONTROL, "private, no-store")
.header(header::VARY, "Cookie")
.body(body)
.unwrap();
// Keep TempPath alive until the body finishes streaming.
response.extensions_mut().insert(Arc::new(temp_path));
response
}
+26 -5
View File
@@ -104,11 +104,32 @@ pub fn create_public_api_routes(app_state: &Arc<AppState>) -> Router<Arc<AppStat
router = router.nest("/s", public_share_router);
// Download endpoint uses full AppState (needs FileRetrievalService)
router = router.route(
"/s/{token}/download",
get(share_handler::download_shared_file),
);
// AppState-backed share endpoints (download, contents, file, zip)
router = router
.route(
"/s/{token}/download",
get(share_handler::download_shared_file),
)
.route(
"/s/{token}/contents",
get(share_handler::list_share_contents_root),
)
.route(
"/s/{token}/contents/{folder_id}",
get(share_handler::list_share_contents_subfolder),
)
.route(
"/s/{token}/file/{file_id}",
get(share_handler::download_share_file_in_folder),
)
.route(
"/s/{token}/zip",
get(share_handler::download_share_zip_root),
)
.route(
"/s/{token}/zip/{folder_id}",
get(share_handler::download_share_zip_subfolder),
);
}
// i18n routes — no auth required (localization should be available before login)