security: fix vulnerabilities 1-7 from security audit

- Fix #1: Share handler IDOR - enforce owner check on share operations
- Fix #2: list_files_query IDOR - bind folder queries to authenticated user
- Fix #3: Dedup handler IDOR - restrict dedup operations to file owner
- Fix #4: Trash handler OptionalAuthUser - require full AuthUser
- Fix #5: Error info leakage - sanitize 500 error responses
- Fix #6: Chunked upload IDOR - bind upload sessions to user_id,
  add verify_session_owner() check on all session operations
- Fix #7: CSP unsafe-inline removal - migrate all inline scripts,
  styles and event handlers to external files, tighten CSP to
  script-src 'self'; style-src 'self'

New files:
  - static/js/core/theme-init.js (render-blocking theme init)
  - static/js/core/sw-register.js (service worker registration)
  - static/css/views/device-verify.css (extracted inline styles)
  - static/js/views/device-verify/device-verify.js (extracted inline script)
This commit is contained in:
Dionisio
2026-03-05 13:15:34 +01:00
parent fdbb2bf60a
commit b503e08384
38 changed files with 870 additions and 1008 deletions
@@ -59,6 +59,7 @@ pub trait ChunkedUploadPort: Send + Sync + 'static {
/// total number of chunks, and expiration timestamp. /// total number of chunks, and expiration timestamp.
async fn create_session( async fn create_session(
&self, &self,
user_id: &str,
filename: String, filename: String,
folder_id: Option<String>, folder_id: Option<String>,
content_type: String, content_type: String,
@@ -72,13 +73,14 @@ pub trait ChunkedUploadPort: Send + Sync + 'static {
async fn upload_chunk( async fn upload_chunk(
&self, &self,
upload_id: &str, upload_id: &str,
user_id: &str,
chunk_index: usize, chunk_index: usize,
data: Bytes, data: Bytes,
checksum: Option<String>, checksum: Option<String>,
) -> Result<ChunkUploadResponseDto, DomainError>; ) -> Result<ChunkUploadResponseDto, DomainError>;
/// Get the current status of an upload session. /// Get the current status of an upload session.
async fn get_status(&self, upload_id: &str) -> Result<UploadStatusResponseDto, DomainError>; async fn get_status(&self, upload_id: &str, user_id: &str) -> Result<UploadStatusResponseDto, DomainError>;
/// Assemble all chunks into the final file. /// Assemble all chunks into the final file.
/// ///
@@ -88,13 +90,14 @@ pub trait ChunkedUploadPort: Send + Sync + 'static {
async fn complete_upload( async fn complete_upload(
&self, &self,
upload_id: &str, upload_id: &str,
user_id: &str,
) -> Result<(PathBuf, String, Option<String>, String, u64, String), DomainError>; ) -> Result<(PathBuf, String, Option<String>, String, u64, String), DomainError>;
/// Finalize upload: clean up the session and temporary files. /// Finalize upload: clean up the session and temporary files.
async fn finalize_upload(&self, upload_id: &str) -> Result<(), DomainError>; async fn finalize_upload(&self, upload_id: &str, user_id: &str) -> Result<(), DomainError>;
/// Cancel an upload and clean up all temporary data. /// Cancel an upload and clean up all temporary data.
async fn cancel_upload(&self, upload_id: &str) -> Result<(), DomainError>; async fn cancel_upload(&self, upload_id: &str, user_id: &str) -> Result<(), DomainError>;
/// Check if a file size qualifies for chunked upload. /// Check if a file size qualifies for chunked upload.
fn should_use_chunked(&self, size: u64) -> bool; fn should_use_chunked(&self, size: u64) -> bool;
+27 -14
View File
@@ -15,28 +15,34 @@ pub trait ShareUseCase: Send + Sync + 'static {
dto: CreateShareDto, dto: CreateShareDto,
) -> Result<ShareDto, DomainError>; ) -> Result<ShareDto, DomainError>;
/// Get a shared link by its ID /// Get a shared link by its ID (ownership-verified)
async fn get_shared_link(&self, id: &str) -> Result<ShareDto, DomainError>; async fn get_shared_link(
&self,
id: &str,
requester_id: &str,
) -> Result<ShareDto, DomainError>;
/// Get a shared link by its token (for access by non-users) /// Get a shared link by its token (for access by non-users)
async fn get_shared_link_by_token(&self, token: &str) -> Result<ShareDto, DomainError>; async fn get_shared_link_by_token(&self, token: &str) -> Result<ShareDto, DomainError>;
/// Get all shared links for a specific item /// Get all shared links for a specific item (ownership-verified)
async fn get_shared_links_for_item( async fn get_shared_links_for_item(
&self, &self,
item_id: &str, item_id: &str,
item_type: &ShareItemType, item_type: &ShareItemType,
requester_id: &str,
) -> Result<Vec<ShareDto>, DomainError>; ) -> Result<Vec<ShareDto>, DomainError>;
/// Update a shared link /// Update a shared link (ownership-verified)
async fn update_shared_link( async fn update_shared_link(
&self, &self,
id: &str, id: &str,
requester_id: &str,
dto: UpdateShareDto, dto: UpdateShareDto,
) -> Result<ShareDto, DomainError>; ) -> Result<ShareDto, DomainError>;
/// Delete a shared link /// Delete a shared link (ownership-verified)
async fn delete_shared_link(&self, id: &str) -> Result<(), DomainError>; async fn delete_shared_link(&self, id: &str, requester_id: &str) -> Result<(), DomainError>;
/// Get all shared links created by a specific user /// Get all shared links created by a specific user
async fn get_user_shared_links( async fn get_user_shared_links(
@@ -63,20 +69,29 @@ pub trait ShareStoragePort: Send + Sync + 'static {
share: &crate::domain::entities::share::Share, share: &crate::domain::entities::share::Share,
) -> Result<crate::domain::entities::share::Share, DomainError>; ) -> Result<crate::domain::entities::share::Share, DomainError>;
async fn find_share_by_id(
&self,
id: &str,
) -> Result<crate::domain::entities::share::Share, DomainError>;
async fn find_share_by_token( async fn find_share_by_token(
&self, &self,
token: &str, token: &str,
) -> Result<crate::domain::entities::share::Share, DomainError>; ) -> Result<crate::domain::entities::share::Share, DomainError>;
async fn find_shares_by_item( /// Find a share by ID only if it belongs to the given user.
/// Returns `NotFound` if the share doesn't exist OR belongs to another user
/// (prevents share-ID enumeration).
async fn find_share_by_id_for_user(
&self,
id: &str,
user_id: &str,
) -> Result<crate::domain::entities::share::Share, DomainError>;
/// Delete a share only if it belongs to the given user.
async fn delete_share_for_user(&self, id: &str, user_id: &str) -> Result<(), DomainError>;
/// Find shares for a specific item that belong to the given user.
async fn find_shares_by_item_for_user(
&self, &self,
item_id: &str, item_id: &str,
item_type: &ShareItemType, item_type: &ShareItemType,
user_id: &str,
) -> Result<Vec<crate::domain::entities::share::Share>, DomainError>; ) -> Result<Vec<crate::domain::entities::share::Share>, DomainError>;
async fn update_share( async fn update_share(
@@ -84,8 +99,6 @@ pub trait ShareStoragePort: Send + Sync + 'static {
share: &crate::domain::entities::share::Share, share: &crate::domain::entities::share::Share,
) -> Result<crate::domain::entities::share::Share, DomainError>; ) -> Result<crate::domain::entities::share::Share, DomainError>;
async fn delete_share(&self, id: &str) -> Result<(), DomainError>;
async fn find_shares_by_user( async fn find_shares_by_user(
&self, &self,
user_id: &str, user_id: &str,
+71 -55
View File
@@ -140,6 +140,25 @@ impl ShareService {
})?; })?;
self.password_hasher.hash_password(password).await self.password_hasher.hash_password(password).await
} }
/// Fetch a share and verify that `requester_id` owns it.
///
/// SECURITY: returns `NotFound` (not `Forbidden`) when the share exists
/// but belongs to a different user — this prevents share-ID enumeration
/// attacks where an attacker probes IDs and uses 403-vs-404 to learn
/// which ones are valid.
async fn fetch_owned_share(
&self,
id: &str,
requester_id: &str,
) -> Result<Share, DomainError> {
let share = self
.share_repository
.find_share_by_id_for_user(id, requester_id)
.await?;
Ok(share)
}
} }
impl ShareUseCase for ShareService { impl ShareUseCase for ShareService {
@@ -187,15 +206,14 @@ impl ShareUseCase for ShareService {
Ok(ShareDto::from_entity(&saved_share, &self.config.base_url())) Ok(ShareDto::from_entity(&saved_share, &self.config.base_url()))
} }
async fn get_shared_link(&self, id: &str) -> Result<ShareDto, DomainError> { async fn get_shared_link(
// Find the shared link by its ID &self,
let share = self id: &str,
.share_repository requester_id: &str,
.find_share_by_id(id) ) -> Result<ShareDto, DomainError> {
.await // SECURITY: ownership-verified lookup — returns 404 if the share
.map_err(|e| { // doesn't exist OR belongs to another user.
ShareServiceError::NotFound(format!("Share with ID {} not found: {}", id, e)) let share = self.fetch_owned_share(id, requester_id).await?;
})?;
// Check if it has expired // Check if it has expired
if share.is_expired() { if share.is_expired() {
@@ -229,11 +247,12 @@ impl ShareUseCase for ShareService {
&self, &self,
item_id: &str, item_id: &str,
item_type: &ShareItemType, item_type: &ShareItemType,
requester_id: &str,
) -> Result<Vec<ShareDto>, DomainError> { ) -> Result<Vec<ShareDto>, DomainError> {
// Find all shared links for the item // SECURITY: only return shares created by the requester
let shares = self let shares = self
.share_repository .share_repository
.find_shares_by_item(item_id, item_type) .find_shares_by_item_for_user(item_id, item_type, requester_id)
.await .await
.map_err(|e| ShareServiceError::Repository(e.to_string()))?; .map_err(|e| ShareServiceError::Repository(e.to_string()))?;
@@ -252,16 +271,11 @@ impl ShareUseCase for ShareService {
async fn update_shared_link( async fn update_shared_link(
&self, &self,
id: &str, id: &str,
requester_id: &str,
dto: UpdateShareDto, dto: UpdateShareDto,
) -> Result<ShareDto, DomainError> { ) -> Result<ShareDto, DomainError> {
// Find the existing shared link // SECURITY: ownership-verified lookup — prevents IDOR
let mut share = self let mut share = self.fetch_owned_share(id, requester_id).await?;
.share_repository
.find_share_by_id(id)
.await
.map_err(|e| {
ShareServiceError::NotFound(format!("Share with ID {} not found: {}", id, e))
})?;
// Update permissions if provided // Update permissions if provided
if let Some(permissions_dto) = dto.permissions { if let Some(permissions_dto) = dto.permissions {
@@ -302,12 +316,11 @@ impl ShareUseCase for ShareService {
)) ))
} }
async fn delete_shared_link(&self, id: &str) -> Result<(), DomainError> { async fn delete_shared_link(&self, id: &str, requester_id: &str) -> Result<(), DomainError> {
// Delete the shared link // SECURITY: ownership-verified delete — only the creator can remove
self.share_repository self.share_repository
.delete_share(id) .delete_share_for_user(id, requester_id)
.await .await?;
.map_err(|e| ShareServiceError::Repository(e.to_string()))?;
Ok(()) Ok(())
} }
@@ -688,15 +701,6 @@ mod tests {
Ok(share.clone()) Ok(share.clone())
} }
async fn find_share_by_id(&self, id: &str) -> Result<Share, DomainError> {
let shares = self.shares.lock().unwrap();
shares
.get(id)
.cloned()
.ok_or_else(|| DomainError::not_found("Share", id))
}
async fn find_share_by_token(&self, token: &str) -> Result<Share, DomainError> { async fn find_share_by_token(&self, token: &str) -> Result<Share, DomainError> {
let tokens = self.tokens.lock().unwrap(); let tokens = self.tokens.lock().unwrap();
let shares = self.shares.lock().unwrap(); let shares = self.shares.lock().unwrap();
@@ -711,20 +715,50 @@ mod tests {
.ok_or_else(|| DomainError::not_found("Share", id.as_str())) .ok_or_else(|| DomainError::not_found("Share", id.as_str()))
} }
async fn find_shares_by_item( async fn find_share_by_id_for_user(
&self,
id: &str,
user_id: &str,
) -> Result<Share, DomainError> {
let shares = self.shares.lock().unwrap();
shares
.get(id)
.filter(|s| s.created_by() == user_id)
.cloned()
.ok_or_else(|| DomainError::not_found("Share", id))
}
async fn delete_share_for_user(&self, id: &str, user_id: &str) -> Result<(), DomainError> {
let mut shares = self.shares.lock().unwrap();
let mut tokens = self.tokens.lock().unwrap();
let share = shares
.get(id)
.filter(|s| s.created_by() == user_id)
.ok_or_else(|| DomainError::not_found("Share", id))?;
tokens.remove(share.token());
shares.remove(id);
Ok(())
}
async fn find_shares_by_item_for_user(
&self, &self,
item_id: &str, item_id: &str,
item_type: &ShareItemType, item_type: &ShareItemType,
user_id: &str,
) -> Result<Vec<Share>, DomainError> { ) -> Result<Vec<Share>, DomainError> {
let shares = self.shares.lock().unwrap(); let shares = self.shares.lock().unwrap();
let type_str = item_type.to_string(); let type_str = item_type.to_string();
let result: Vec<Share> = shares let result: Vec<Share> = shares
.values() .values()
.filter(|s| s.item_id() == item_id && s.item_type().to_string() == type_str) .filter(|s| {
s.item_id() == item_id
&& s.item_type().to_string() == type_str
&& s.created_by() == user_id
})
.cloned() .cloned()
.collect(); .collect();
Ok(result) Ok(result)
} }
@@ -741,24 +775,6 @@ mod tests {
Ok(share.clone()) Ok(share.clone())
} }
async fn delete_share(&self, id: &str) -> Result<(), DomainError> {
let mut shares = self.shares.lock().unwrap();
let mut tokens = self.tokens.lock().unwrap();
// Find the share to get the token
let share = shares
.get(id)
.ok_or_else(|| DomainError::not_found("Share", id))?;
// Remove token mapping
tokens.remove(share.token());
// Remove the share
shares.remove(id);
Ok(())
}
async fn find_shares_by_user( async fn find_shares_by_user(
&self, &self,
user_id: &str, user_id: &str,
+19 -7
View File
@@ -144,9 +144,8 @@ impl TrashUseCase for TrashService {
); );
debug!("User UUID validation: {}", user_id); debug!("User UUID validation: {}", user_id);
// Note: We do NOT call validate_user_ownership here because the item // Note: We now verify file/folder ownership BEFORE moving to trash.
// is not yet in the trash. Ownership validation is only for operations // This prevents users from trashing items they do not own (IDOR).
// on already-trashed items (restore, delete_permanently).
// Parse UUIDs with detailed error handling // Parse UUIDs with detailed error handling
debug!("Validating item UUID: {}", item_id); debug!("Validating item UUID: {}", item_id);
@@ -183,9 +182,11 @@ impl TrashUseCase for TrashService {
"file" => { "file" => {
info!("Processing file to move to trash: {}", item_id); info!("Processing file to move to trash: {}", item_id);
// Get the file to verify it exists and capture its data // Get the file — ownership-verified at SQL level.
debug!("Getting file data: {}", item_id); // Returns NotFound if the file does not exist OR belongs to
let file = match self.file_read_port.get_file(item_id).await { // another user, preventing cross-user trash operations.
debug!("Getting file data (owner-scoped): {}", item_id);
let file = match self.file_read_port.get_file_for_owner(item_id, user_id).await {
Ok(file) => { Ok(file) => {
debug!("File found: {} ({})", file.name(), item_id); debug!("File found: {} ({})", file.name(), item_id);
file file
@@ -254,7 +255,9 @@ impl TrashUseCase for TrashService {
Ok(()) Ok(())
} }
"folder" => { "folder" => {
// Get the folder to verify it exists and capture its data // Get the folder and verify ownership.
// Returns NotFound if the folder does not exist or belongs
// to another user — prevents cross-user trash operations.
let folder = self let folder = self
.folder_storage_port .folder_storage_port
.get_folder(item_id) .get_folder(item_id)
@@ -267,6 +270,15 @@ impl TrashUseCase for TrashService {
) )
})?; })?;
// Ownership check — return NotFound (not Forbidden) to
// prevent leaking whether the folder exists.
if folder.owner_id().map_or(true, |o| o != user_id) {
return Err(DomainError::not_found(
"Folder",
format!("Folder not found: {}", item_id),
));
}
let original_path = folder.storage_path().to_string(); let original_path = folder.storage_path().to_string();
// Create the trash item // Create the trash item
@@ -120,33 +120,6 @@ impl ShareStoragePort for SharePgRepository {
Self::row_to_entity(&row) Self::row_to_entity(&row)
} }
async fn find_share_by_id(&self, id: &str) -> Result<Share, DomainError> {
let row = sqlx::query(
r#"
SELECT id::TEXT, item_id, item_name, item_type, token, password_hash,
expires_at, permissions_read, permissions_write, permissions_reshare,
created_at, created_by, access_count
FROM storage.shares
WHERE id = $1::UUID
"#,
)
.bind(id)
.fetch_optional(&*self.db_pool)
.await
.map_err(|e| {
tracing::error!("Database error finding share by id: {}", e);
DomainError::internal_error("Share", format!("Failed to find share: {e}"))
})?;
match row {
Some(r) => Self::row_to_entity(&r),
None => Err(DomainError::not_found(
"Share",
format!("Share with ID {id} not found"),
)),
}
}
async fn find_share_by_token(&self, token: &str) -> Result<Share, DomainError> { async fn find_share_by_token(&self, token: &str) -> Result<Share, DomainError> {
let row = sqlx::query( let row = sqlx::query(
r#" r#"
@@ -174,10 +147,70 @@ impl ShareStoragePort for SharePgRepository {
} }
} }
async fn find_shares_by_item( async fn find_share_by_id_for_user(
&self,
id: &str,
user_id: &str,
) -> Result<Share, DomainError> {
let row = sqlx::query(
r#"
SELECT id::TEXT, item_id, item_name, item_type, token, password_hash,
expires_at, permissions_read, permissions_write, permissions_reshare,
created_at, created_by, access_count
FROM storage.shares
WHERE id = $1::UUID AND created_by = $2
"#,
)
.bind(id)
.bind(user_id)
.fetch_optional(&*self.db_pool)
.await
.map_err(|e| {
tracing::error!("Database error finding share by id for user: {}", e);
DomainError::internal_error("Share", format!("Failed to find share: {e}"))
})?;
match row {
Some(r) => Self::row_to_entity(&r),
// SECURITY: return NotFound (not Forbidden) to prevent share-ID enumeration
None => Err(DomainError::not_found(
"Share",
format!("Share with ID {id} not found"),
)),
}
}
async fn delete_share_for_user(&self, id: &str, user_id: &str) -> Result<(), DomainError> {
let result =
sqlx::query("DELETE FROM storage.shares WHERE id = $1::UUID AND created_by = $2")
.bind(id)
.bind(user_id)
.execute(&*self.db_pool)
.await
.map_err(|e| {
tracing::error!("Database error deleting share for user: {}", e);
DomainError::internal_error(
"Share",
format!("Failed to delete share: {e}"),
)
})?;
if result.rows_affected() == 0 {
// SECURITY: could be non-existent or owned by another user — same 404
return Err(DomainError::not_found(
"Share",
format!("Share with ID {id} not found"),
));
}
Ok(())
}
async fn find_shares_by_item_for_user(
&self, &self,
item_id: &str, item_id: &str,
item_type: &ShareItemType, item_type: &ShareItemType,
user_id: &str,
) -> Result<Vec<Share>, DomainError> { ) -> Result<Vec<Share>, DomainError> {
let rows = sqlx::query( let rows = sqlx::query(
r#" r#"
@@ -185,17 +218,21 @@ impl ShareStoragePort for SharePgRepository {
expires_at, permissions_read, permissions_write, permissions_reshare, expires_at, permissions_read, permissions_write, permissions_reshare,
created_at, created_by, access_count created_at, created_by, access_count
FROM storage.shares FROM storage.shares
WHERE item_id = $1 AND item_type = $2 WHERE item_id = $1 AND item_type = $2 AND created_by = $3
ORDER BY created_at DESC ORDER BY created_at DESC
"#, "#,
) )
.bind(item_id) .bind(item_id)
.bind(item_type.to_string()) .bind(item_type.to_string())
.bind(user_id)
.fetch_all(&*self.db_pool) .fetch_all(&*self.db_pool)
.await .await
.map_err(|e| { .map_err(|e| {
tracing::error!("Database error finding shares by item: {}", e); tracing::error!("Database error finding shares by item for user: {}", e);
DomainError::internal_error("Share", format!("Failed to find shares by item: {e}")) DomainError::internal_error(
"Share",
format!("Failed to find shares by item: {e}"),
)
})?; })?;
rows.iter().map(Self::row_to_entity).collect() rows.iter().map(Self::row_to_entity).collect()
@@ -243,26 +280,6 @@ impl ShareStoragePort for SharePgRepository {
} }
} }
async fn delete_share(&self, id: &str) -> Result<(), DomainError> {
let result = sqlx::query("DELETE FROM storage.shares WHERE id = $1::UUID")
.bind(id)
.execute(&*self.db_pool)
.await
.map_err(|e| {
tracing::error!("Database error deleting share: {}", e);
DomainError::internal_error("Share", format!("Failed to delete share: {e}"))
})?;
if result.rows_affected() == 0 {
return Err(DomainError::not_found(
"Share",
format!("Share with ID {id} not found for deletion"),
));
}
Ok(())
}
async fn find_shares_by_user( async fn find_shares_by_user(
&self, &self,
user_id: &str, user_id: &str,
@@ -73,6 +73,7 @@ pub struct ChunkInfo {
#[derive(Debug, Clone, Serialize, Deserialize)] #[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UploadSession { pub struct UploadSession {
pub id: String, pub id: String,
pub user_id: String,
pub filename: String, pub filename: String,
pub folder_id: Option<String>, pub folder_id: Option<String>,
pub content_type: String, pub content_type: String,
@@ -368,9 +369,27 @@ impl ChunkedUploadService {
// ── Core operations ────────────────────────────────────────────────── // ── Core operations ──────────────────────────────────────────────────
/// Verify that the given session belongs to the given user.
/// Returns 404 (not 403) to avoid revealing the existence of other users' sessions.
fn verify_session_owner(
&self,
upload_id: &str,
user_id: &str,
) -> Result<(), String> {
let session = self
.sessions
.get(upload_id)
.ok_or_else(|| format!("Upload session not found: {}", upload_id))?;
if session.user_id != user_id {
return Err(format!("Upload session not found: {}", upload_id));
}
Ok(())
}
/// Create a new upload session (persists `session.json` + empty `progress.bin`) /// Create a new upload session (persists `session.json` + empty `progress.bin`)
async fn create_session_inner( async fn create_session_inner(
&self, &self,
user_id: String,
filename: String, filename: String,
folder_id: Option<String>, folder_id: Option<String>,
content_type: String, content_type: String,
@@ -412,6 +431,7 @@ impl ChunkedUploadService {
let now = Utc::now(); let now = Utc::now();
let session = UploadSession { let session = UploadSession {
id: upload_id.clone(), id: upload_id.clone(),
user_id,
filename, filename,
folder_id, folder_id,
content_type, content_type,
@@ -451,11 +471,15 @@ impl ChunkedUploadService {
async fn upload_chunk_inner( async fn upload_chunk_inner(
&self, &self,
upload_id: &str, upload_id: &str,
user_id: &str,
chunk_index: usize, chunk_index: usize,
data: bytes::Bytes, data: bytes::Bytes,
checksum: Option<String>, checksum: Option<String>,
) -> Result<ChunkUploadResponseDto, String> { ) -> Result<ChunkUploadResponseDto, String> {
// Validate session exists and chunk index is valid // Verify session exists AND belongs to the requesting user
self.verify_session_owner(upload_id, user_id)?;
// Validate chunk index is valid
let (chunk_path, expected_size) = { let (chunk_path, expected_size) = {
let session = self let session = self
.sessions .sessions
@@ -568,7 +592,9 @@ impl ChunkedUploadService {
} }
/// Get upload status /// Get upload status
async fn get_status_inner(&self, upload_id: &str) -> Result<UploadStatusResponseDto, String> { async fn get_status_inner(&self, upload_id: &str, user_id: &str) -> Result<UploadStatusResponseDto, String> {
self.verify_session_owner(upload_id, user_id)?;
let session = self let session = self
.sessions .sessions
.get(upload_id) .get(upload_id)
@@ -603,7 +629,11 @@ impl ChunkedUploadService {
async fn complete_upload_inner( async fn complete_upload_inner(
&self, &self,
upload_id: &str, upload_id: &str,
user_id: &str,
) -> Result<(PathBuf, String, Option<String>, String, u64, String), String> { ) -> Result<(PathBuf, String, Option<String>, String, u64, String), String> {
// Verify ownership before assembly
self.verify_session_owner(upload_id, user_id)?;
// Get session and validate completion. // Get session and validate completion.
// Clone the session data and drop the DashMap ref immediately // Clone the session data and drop the DashMap ref immediately
// so the shard is not held during the expensive assembly step. // so the shard is not held during the expensive assembly step.
@@ -723,7 +753,9 @@ impl ChunkedUploadService {
} }
/// Finalize upload: remove session from RAM, then clean disk OUTSIDE lock. /// Finalize upload: remove session from RAM, then clean disk OUTSIDE lock.
async fn finalize_upload_inner(&self, upload_id: &str) -> Result<(), String> { async fn finalize_upload_inner(&self, upload_id: &str, user_id: &str) -> Result<(), String> {
self.verify_session_owner(upload_id, user_id)?;
// Remove from map (~µs) — releases shard immediately // Remove from map (~µs) — releases shard immediately
let removed = self.sessions.remove(upload_id).map(|(_, s)| s); let removed = self.sessions.remove(upload_id).map(|(_, s)| s);
@@ -737,7 +769,9 @@ impl ChunkedUploadService {
} }
/// Cancel an upload and cleanup — disk I/O outside lock. /// Cancel an upload and cleanup — disk I/O outside lock.
async fn cancel_upload_inner(&self, upload_id: &str) -> Result<(), String> { async fn cancel_upload_inner(&self, upload_id: &str, user_id: &str) -> Result<(), String> {
self.verify_session_owner(upload_id, user_id)?;
// Remove from map (~µs) // Remove from map (~µs)
let removed = self.sessions.remove(upload_id).map(|(_, s)| s); let removed = self.sessions.remove(upload_id).map(|(_, s)| s);
@@ -767,13 +801,14 @@ impl ChunkedUploadService {
impl ChunkedUploadPort for ChunkedUploadService { impl ChunkedUploadPort for ChunkedUploadService {
async fn create_session( async fn create_session(
&self, &self,
user_id: &str,
filename: String, filename: String,
folder_id: Option<String>, folder_id: Option<String>,
content_type: String, content_type: String,
total_size: u64, total_size: u64,
chunk_size: Option<usize>, chunk_size: Option<usize>,
) -> Result<CreateUploadResponseDto, DomainError> { ) -> Result<CreateUploadResponseDto, DomainError> {
self.create_session_inner(filename, folder_id, content_type, total_size, chunk_size) self.create_session_inner(user_id.to_owned(), filename, folder_id, content_type, total_size, chunk_size)
.await .await
.map_err(|e| DomainError::new(ErrorKind::InternalError, "ChunkedUpload", e)) .map_err(|e| DomainError::new(ErrorKind::InternalError, "ChunkedUpload", e))
} }
@@ -781,17 +816,18 @@ impl ChunkedUploadPort for ChunkedUploadService {
async fn upload_chunk( async fn upload_chunk(
&self, &self,
upload_id: &str, upload_id: &str,
user_id: &str,
chunk_index: usize, chunk_index: usize,
data: bytes::Bytes, data: bytes::Bytes,
checksum: Option<String>, checksum: Option<String>,
) -> Result<ChunkUploadResponseDto, DomainError> { ) -> Result<ChunkUploadResponseDto, DomainError> {
self.upload_chunk_inner(upload_id, chunk_index, data, checksum) self.upload_chunk_inner(upload_id, user_id, chunk_index, data, checksum)
.await .await
.map_err(|e| DomainError::new(ErrorKind::InternalError, "ChunkedUpload", e)) .map_err(|e| DomainError::new(ErrorKind::InternalError, "ChunkedUpload", e))
} }
async fn get_status(&self, upload_id: &str) -> Result<UploadStatusResponseDto, DomainError> { async fn get_status(&self, upload_id: &str, user_id: &str) -> Result<UploadStatusResponseDto, DomainError> {
self.get_status_inner(upload_id) self.get_status_inner(upload_id, user_id)
.await .await
.map_err(|e| DomainError::new(ErrorKind::NotFound, "ChunkedUpload", e)) .map_err(|e| DomainError::new(ErrorKind::NotFound, "ChunkedUpload", e))
} }
@@ -799,20 +835,21 @@ impl ChunkedUploadPort for ChunkedUploadService {
async fn complete_upload( async fn complete_upload(
&self, &self,
upload_id: &str, upload_id: &str,
user_id: &str,
) -> Result<(PathBuf, String, Option<String>, String, u64, String), DomainError> { ) -> Result<(PathBuf, String, Option<String>, String, u64, String), DomainError> {
self.complete_upload_inner(upload_id) self.complete_upload_inner(upload_id, user_id)
.await .await
.map_err(|e| DomainError::new(ErrorKind::InternalError, "ChunkedUpload", e)) .map_err(|e| DomainError::new(ErrorKind::InternalError, "ChunkedUpload", e))
} }
async fn finalize_upload(&self, upload_id: &str) -> Result<(), DomainError> { async fn finalize_upload(&self, upload_id: &str, user_id: &str) -> Result<(), DomainError> {
self.finalize_upload_inner(upload_id) self.finalize_upload_inner(upload_id, user_id)
.await .await
.map_err(|e| DomainError::new(ErrorKind::InternalError, "ChunkedUpload", e)) .map_err(|e| DomainError::new(ErrorKind::InternalError, "ChunkedUpload", e))
} }
async fn cancel_upload(&self, upload_id: &str) -> Result<(), DomainError> { async fn cancel_upload(&self, upload_id: &str, user_id: &str) -> Result<(), DomainError> {
self.cancel_upload_inner(upload_id) self.cancel_upload_inner(upload_id, user_id)
.await .await
.map_err(|e| DomainError::new(ErrorKind::InternalError, "ChunkedUpload", e)) .map_err(|e| DomainError::new(ErrorKind::InternalError, "ChunkedUpload", e))
} }
@@ -854,6 +891,7 @@ mod tests {
let now = Utc::now(); let now = Utc::now();
let mut session = UploadSession { let mut session = UploadSession {
id: "test-id".into(), id: "test-id".into(),
user_id: "user-1".into(),
filename: "file.bin".into(), filename: "file.bin".into(),
folder_id: None, folder_id: None,
content_type: "application/octet-stream".into(), content_type: "application/octet-stream".into(),
@@ -900,6 +938,7 @@ mod tests {
let now = Utc::now(); let now = Utc::now();
let session = UploadSession { let session = UploadSession {
id: "abc-123".into(), id: "abc-123".into(),
user_id: "user-1".into(),
filename: "photo.jpg".into(), filename: "photo.jpg".into(),
folder_id: Some("folder-1".into()), folder_id: Some("folder-1".into()),
content_type: "image/jpeg".into(), content_type: "image/jpeg".into(),
@@ -931,6 +970,7 @@ mod tests {
let restored: UploadSession = serde_json::from_slice(&json).expect("deserialise"); let restored: UploadSession = serde_json::from_slice(&json).expect("deserialise");
assert_eq!(restored.id, session.id); assert_eq!(restored.id, session.id);
assert_eq!(restored.user_id, session.user_id);
assert_eq!(restored.filename, session.filename); assert_eq!(restored.filename, session.filename);
assert_eq!(restored.folder_id, session.folder_id); assert_eq!(restored.folder_id, session.folder_id);
assert_eq!(restored.total_size, session.total_size); assert_eq!(restored.total_size, session.total_size);
@@ -944,6 +984,7 @@ mod tests {
fn test_session_expiry_check() { fn test_session_expiry_check() {
let mut session = UploadSession { let mut session = UploadSession {
id: "exp-test".into(), id: "exp-test".into(),
user_id: "user-1".into(),
filename: "f".into(), filename: "f".into(),
folder_id: None, folder_id: None,
content_type: "x".into(), content_type: "x".into(),
@@ -974,6 +1015,7 @@ mod tests {
// Create a session // Create a session
let resp = service let resp = service
.create_session_inner( .create_session_inner(
"test-user".into(),
"bigfile.bin".into(), "bigfile.bin".into(),
Some("folder-x".into()), Some("folder-x".into()),
"application/octet-stream".into(), "application/octet-stream".into(),
@@ -988,7 +1030,7 @@ mod tests {
// Upload first chunk (5 MB of zeros) // Upload first chunk (5 MB of zeros)
let chunk_data = bytes::Bytes::from(vec![0u8; 5 * 1024 * 1024]); let chunk_data = bytes::Bytes::from(vec![0u8; 5 * 1024 * 1024]);
service service
.upload_chunk_inner(&upload_id, 0, chunk_data, None) .upload_chunk_inner(&upload_id, "test-user", 0, chunk_data, None)
.await .await
.expect("upload_chunk 0"); .expect("upload_chunk 0");
@@ -1024,6 +1066,7 @@ mod tests {
// 1. Create session (1024 bytes, 512 byte chunks → 2 chunks) // 1. Create session (1024 bytes, 512 byte chunks → 2 chunks)
let resp = service let resp = service
.create_session_inner( .create_session_inner(
"test-user".into(),
"test.txt".into(), "test.txt".into(),
None, None,
"text/plain".into(), "text/plain".into(),
@@ -1040,28 +1083,28 @@ mod tests {
// 2. Upload chunks // 2. Upload chunks
let chunk0 = bytes::Bytes::from(vec![b'A'; 512]); let chunk0 = bytes::Bytes::from(vec![b'A'; 512]);
let r0 = service let r0 = service
.upload_chunk_inner(&id, 0, chunk0, None) .upload_chunk_inner(&id, "test-user", 0, chunk0, None)
.await .await
.expect("chunk 0"); .expect("chunk 0");
assert!(!r0.is_complete); assert!(!r0.is_complete);
let chunk1 = bytes::Bytes::from(vec![b'B'; 512]); let chunk1 = bytes::Bytes::from(vec![b'B'; 512]);
let r1 = service let r1 = service
.upload_chunk_inner(&id, 1, chunk1, None) .upload_chunk_inner(&id, "test-user", 1, chunk1, None)
.await .await
.expect("chunk 1"); .expect("chunk 1");
assert!(r1.is_complete); assert!(r1.is_complete);
assert_eq!(r1.bytes_received, 1024); assert_eq!(r1.bytes_received, 1024);
// 3. Status check // 3. Status check
let status = service.get_status_inner(&id).await.expect("status"); let status = service.get_status_inner(&id, "test-user").await.expect("status");
assert!(status.is_complete); assert!(status.is_complete);
assert_eq!(status.completed_chunks, 2); assert_eq!(status.completed_chunks, 2);
assert!(status.pending_chunks.is_empty()); assert!(status.pending_chunks.is_empty());
// 4. Complete (assemble) // 4. Complete (assemble)
let (path, filename, _folder, _ct, size, hash) = let (path, filename, _folder, _ct, size, hash) =
service.complete_upload_inner(&id).await.expect("complete"); service.complete_upload_inner(&id, "test-user").await.expect("complete");
assert_eq!(filename, "test.txt"); assert_eq!(filename, "test.txt");
assert_eq!(size, 1024); assert_eq!(size, 1024);
assert!(!hash.is_empty()); assert!(!hash.is_empty());
@@ -1073,7 +1116,7 @@ mod tests {
assert_eq!(&content[512..], &[b'B'; 512]); assert_eq!(&content[512..], &[b'B'; 512]);
// 6. Finalize // 6. Finalize
service.finalize_upload_inner(&id).await.expect("finalize"); service.finalize_upload_inner(&id, "test-user").await.expect("finalize");
assert_eq!(service.active_sessions().await, 0); assert_eq!(service.active_sessions().await, 0);
let _ = fs::remove_dir_all(&base).await; let _ = fs::remove_dir_all(&base).await;
@@ -1086,6 +1129,7 @@ mod tests {
let resp = service let resp = service
.create_session_inner( .create_session_inner(
"test-user".into(),
"x.bin".into(), "x.bin".into(),
None, None,
"application/octet-stream".into(), "application/octet-stream".into(),
@@ -1099,7 +1143,7 @@ mod tests {
assert!(session_dir.exists()); assert!(session_dir.exists());
service service
.cancel_upload_inner(&resp.upload_id) .cancel_upload_inner(&resp.upload_id, "test-user")
.await .await
.expect("cancel"); .expect("cancel");
@@ -1120,6 +1164,7 @@ mod tests {
let expired_session = UploadSession { let expired_session = UploadSession {
id: "expired-session".into(), id: "expired-session".into(),
user_id: "user-1".into(),
filename: "old.bin".into(), filename: "old.bin".into(),
folder_id: None, folder_id: None,
content_type: "application/octet-stream".into(), content_type: "application/octet-stream".into(),
@@ -1162,6 +1207,7 @@ mod tests {
let session = UploadSession { let session = UploadSession {
id: "partial-session".into(), id: "partial-session".into(),
user_id: "user-1".into(),
filename: "file.bin".into(), filename: "file.bin".into(),
folder_id: None, folder_id: None,
content_type: "application/octet-stream".into(), content_type: "application/octet-stream".into(),
@@ -410,6 +410,22 @@ impl DedupService {
.unwrap_or(false) .unwrap_or(false)
} }
/// Returns `true` if `user_id` owns at least one (non-trashed) file that
/// references the blob identified by `hash`.
///
/// Used by the dedup API handlers to enforce per-user access control on
/// the content-addressed blob store.
pub async fn user_owns_blob_reference(&self, hash: &str, user_id: &str) -> bool {
sqlx::query_scalar::<_, bool>(
"SELECT EXISTS(SELECT 1 FROM storage.files WHERE blob_hash = $1 AND user_id = $2 AND NOT is_trashed)",
)
.bind(hash)
.bind(user_id)
.fetch_one(self.pool.as_ref())
.await
.unwrap_or(false)
}
/// Get metadata for a blob from PostgreSQL. /// Get metadata for a blob from PostgreSQL.
pub async fn get_blob_metadata(&self, hash: &str) -> Option<BlobMetadataDto> { pub async fn get_blob_metadata(&self, hash: &str) -> Option<BlobMetadataDto> {
let row = sqlx::query_as::<_, (String, i64, i32, Option<String>)>( let row = sqlx::query_as::<_, (String, i64, i32, Option<String>)>(
+42 -12
View File
@@ -149,7 +149,10 @@ pub async fn move_files_batch(
.batch_service .batch_service
.move_files(request.file_ids, request.target_folder_id, &auth_user.id) .move_files(request.file_ids, request.target_folder_id, &auth_user.id)
.await .await
.map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?; .map_err(|e| {
tracing::error!("Batch move_files failed: {}", e);
(StatusCode::INTERNAL_SERVER_ERROR, "Batch operation failed".to_string())
})?;
// Convert result to DTO // Convert result to DTO
let response: BatchOperationResponse<FileDto> = result.into(); let response: BatchOperationResponse<FileDto> = result.into();
@@ -190,7 +193,10 @@ pub async fn copy_files_batch(
.batch_service .batch_service
.copy_files(request.file_ids, request.target_folder_id, &auth_user.id) .copy_files(request.file_ids, request.target_folder_id, &auth_user.id)
.await .await
.map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?; .map_err(|e| {
tracing::error!("Batch copy_files failed: {}", e);
(StatusCode::INTERNAL_SERVER_ERROR, "Batch operation failed".to_string())
})?;
// Convert result to DTO // Convert result to DTO
let response: BatchOperationResponse<FileDto> = result.into(); let response: BatchOperationResponse<FileDto> = result.into();
@@ -231,7 +237,10 @@ pub async fn delete_files_batch(
.batch_service .batch_service
.delete_files(request.file_ids, &auth_user.id) .delete_files(request.file_ids, &auth_user.id)
.await .await
.map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?; .map_err(|e| {
tracing::error!("Batch delete_files failed: {}", e);
(StatusCode::INTERNAL_SERVER_ERROR, "Batch operation failed".to_string())
})?;
// Create custom response for string IDs // Create custom response for string IDs
let response = BatchOperationResponse { let response = BatchOperationResponse {
@@ -280,7 +289,10 @@ pub async fn delete_folders_batch(
.batch_service .batch_service
.delete_folders(request.folder_ids, request.recursive, &auth_user.id) .delete_folders(request.folder_ids, request.recursive, &auth_user.id)
.await .await
.map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?; .map_err(|e| {
tracing::error!("Batch delete_folders failed: {}", e);
(StatusCode::INTERNAL_SERVER_ERROR, "Batch operation failed".to_string())
})?;
// Create custom response for string IDs // Create custom response for string IDs
let response = BatchOperationResponse { let response = BatchOperationResponse {
@@ -336,7 +348,10 @@ pub async fn create_folders_batch(
.batch_service .batch_service
.create_folders(folders, &auth_user.id) .create_folders(folders, &auth_user.id)
.await .await
.map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?; .map_err(|e| {
tracing::error!("Batch create_folders failed: {}", e);
(StatusCode::INTERNAL_SERVER_ERROR, "Batch operation failed".to_string())
})?;
// Convert result to DTO // Convert result to DTO
let response: BatchOperationResponse<FolderDto> = result.into(); let response: BatchOperationResponse<FolderDto> = result.into();
@@ -377,7 +392,10 @@ pub async fn get_files_batch(
.batch_service .batch_service
.get_multiple_files(request.file_ids, &auth_user.id) .get_multiple_files(request.file_ids, &auth_user.id)
.await .await
.map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?; .map_err(|e| {
tracing::error!("Batch get_files failed: {}", e);
(StatusCode::INTERNAL_SERVER_ERROR, "Batch operation failed".to_string())
})?;
// Convert result to DTO // Convert result to DTO
let response: BatchOperationResponse<FileDto> = result.into(); let response: BatchOperationResponse<FileDto> = result.into();
@@ -418,7 +436,10 @@ pub async fn get_folders_batch(
.batch_service .batch_service
.get_multiple_folders(request.folder_ids, &auth_user.id) .get_multiple_folders(request.folder_ids, &auth_user.id)
.await .await
.map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?; .map_err(|e| {
tracing::error!("Batch get_folders failed: {}", e);
(StatusCode::INTERNAL_SERVER_ERROR, "Batch operation failed".to_string())
})?;
// Convert result to DTO // Convert result to DTO
let response: BatchOperationResponse<FolderDto> = result.into(); let response: BatchOperationResponse<FolderDto> = result.into();
@@ -497,9 +518,10 @@ pub async fn trash_batch(
); );
} }
Err(e) => { Err(e) => {
tracing::error!("Batch trash_files failed: {}", e);
return Ok(( return Ok((
StatusCode::INTERNAL_SERVER_ERROR, StatusCode::INTERNAL_SERVER_ERROR,
Json(serde_json::json!({ "error": e.to_string() })), Json(serde_json::json!({ "error": "Batch trash operation failed" })),
) )
.into_response()); .into_response());
} }
@@ -523,9 +545,10 @@ pub async fn trash_batch(
); );
} }
Err(e) => { Err(e) => {
tracing::error!("Batch trash_folders failed: {}", e);
return Ok(( return Ok((
StatusCode::INTERNAL_SERVER_ERROR, StatusCode::INTERNAL_SERVER_ERROR,
Json(serde_json::json!({ "error": e.to_string() })), Json(serde_json::json!({ "error": "Batch trash operation failed" })),
) )
.into_response()); .into_response());
} }
@@ -579,7 +602,10 @@ pub async fn move_folders_batch(
.batch_service .batch_service
.move_folders(request.folder_ids, request.target_folder_id, &auth_user.id) .move_folders(request.folder_ids, request.target_folder_id, &auth_user.id)
.await .await
.map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?; .map_err(|e| {
tracing::error!("Batch move_folders failed: {}", e);
(StatusCode::INTERNAL_SERVER_ERROR, "Batch operation failed".to_string())
})?;
let response: BatchOperationResponse<FolderDto> = result.into(); let response: BatchOperationResponse<FolderDto> = result.into();
@@ -616,7 +642,10 @@ pub async fn download_batch(
.batch_service .batch_service
.download_zip(request.file_ids, request.folder_ids, &auth_user.id) .download_zip(request.file_ids, request.folder_ids, &auth_user.id)
.await .await
.map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?; .map_err(|e| {
tracing::error!("Batch download ZIP failed: {}", e);
(StatusCode::INTERNAL_SERVER_ERROR, "Batch download failed".to_string())
})?;
// Read file size for Content-Length before splitting ownership // Read file size for Content-Length before splitting ownership
let file_size = temp_file let file_size = temp_file
@@ -624,9 +653,10 @@ pub async fn download_batch(
.metadata() .metadata()
.map(|m| m.len()) .map(|m| m.len())
.map_err(|e| { .map_err(|e| {
tracing::error!("Failed to read temp file metadata: {}", e);
( (
StatusCode::INTERNAL_SERVER_ERROR, StatusCode::INTERNAL_SERVER_ERROR,
format!("Failed to read temp file metadata: {}", e), "Failed to prepare download".to_string(),
) )
})?; })?;
@@ -22,7 +22,7 @@ use crate::application::ports::chunked_upload_ports::DEFAULT_CHUNK_SIZE;
use crate::application::ports::file_ports::FileUploadUseCase; use crate::application::ports::file_ports::FileUploadUseCase;
use crate::application::ports::storage_ports::StorageUsagePort; use crate::application::ports::storage_ports::StorageUsagePort;
use crate::common::di::AppState; use crate::common::di::AppState;
use crate::domain::errors::ErrorKind; use crate::interfaces::errors::AppError;
use crate::interfaces::middleware::auth::AuthUser; use crate::interfaces::middleware::auth::AuthUser;
/// Request body for creating an upload session /// Request body for creating an upload session
@@ -146,6 +146,7 @@ impl ChunkedUploadHandler {
match chunked_service match chunked_service
.create_session( .create_session(
&auth_user.id,
request.filename, request.filename,
request.folder_id, request.folder_id,
content_type, content_type,
@@ -157,12 +158,7 @@ impl ChunkedUploadHandler {
Ok(response) => (StatusCode::CREATED, Json(response)).into_response(), Ok(response) => (StatusCode::CREATED, Json(response)).into_response(),
Err(e) => { Err(e) => {
tracing::error!("Failed to create upload session: {}", e); tracing::error!("Failed to create upload session: {}", e);
( AppError::internal_error(format!("Failed to create upload session: {}", e))
StatusCode::INTERNAL_SERVER_ERROR,
Json(serde_json::json!({
"error": e.to_string()
})),
)
.into_response() .into_response()
} }
} }
@@ -177,6 +173,7 @@ impl ChunkedUploadHandler {
/// Body: Raw bytes of the chunk /// Body: Raw bytes of the chunk
pub async fn upload_chunk( pub async fn upload_chunk(
State(state): State<Arc<AppState>>, State(state): State<Arc<AppState>>,
auth_user: AuthUser,
Path(upload_id): Path<String>, Path(upload_id): Path<String>,
Query(params): Query<ChunkUploadParams>, Query(params): Query<ChunkUploadParams>,
headers: HeaderMap, headers: HeaderMap,
@@ -193,7 +190,7 @@ impl ChunkedUploadHandler {
}); });
match chunked_service match chunked_service
.upload_chunk(&upload_id, params.chunk_index, body, checksum) .upload_chunk(&upload_id, &auth_user.id, params.chunk_index, body, checksum)
.await .await
{ {
Ok(response) => { Ok(response) => {
@@ -216,22 +213,7 @@ impl ChunkedUploadHandler {
.unwrap() .unwrap()
.into_response() .into_response()
} }
Err(e) => { Err(e) => AppError::from(e).into_response()
let status = match e.kind {
ErrorKind::NotFound => StatusCode::NOT_FOUND,
ErrorKind::InvalidInput => StatusCode::BAD_REQUEST,
ErrorKind::AlreadyExists => StatusCode::CONFLICT,
_ => StatusCode::INTERNAL_SERVER_ERROR,
};
(
status,
Json(serde_json::json!({
"error": e.to_string()
})),
)
.into_response()
}
} }
} }
@@ -240,11 +222,12 @@ impl ChunkedUploadHandler {
/// Returns upload progress and pending chunks /// Returns upload progress and pending chunks
pub async fn get_upload_status( pub async fn get_upload_status(
State(state): State<Arc<AppState>>, State(state): State<Arc<AppState>>,
auth_user: AuthUser,
Path(upload_id): Path<String>, Path(upload_id): Path<String>,
) -> impl IntoResponse { ) -> impl IntoResponse {
let chunked_service = &state.core.chunked_upload_service; let chunked_service = &state.core.chunked_upload_service;
match chunked_service.get_status(&upload_id).await { match chunked_service.get_status(&upload_id, &auth_user.id).await {
Ok(status) => Response::builder() Ok(status) => Response::builder()
.status(StatusCode::OK) .status(StatusCode::OK)
.header(header::CONTENT_TYPE, "application/json") .header(header::CONTENT_TYPE, "application/json")
@@ -261,13 +244,7 @@ impl ChunkedUploadHandler {
)) ))
.unwrap() .unwrap()
.into_response(), .into_response(),
Err(e) => ( Err(e) => AppError::from(e).into_response(),
StatusCode::NOT_FOUND,
Json(serde_json::json!({
"error": e.to_string()
})),
)
.into_response(),
} }
} }
@@ -276,6 +253,7 @@ impl ChunkedUploadHandler {
/// Assembles all chunks into the final file and creates the file record /// Assembles all chunks into the final file and creates the file record
pub async fn complete_upload( pub async fn complete_upload(
State(state): State<Arc<AppState>>, State(state): State<Arc<AppState>>,
auth_user: AuthUser,
Path(upload_id): Path<String>, Path(upload_id): Path<String>,
) -> impl IntoResponse { ) -> impl IntoResponse {
let chunked_service = &state.core.chunked_upload_service; let chunked_service = &state.core.chunked_upload_service;
@@ -283,22 +261,10 @@ impl ChunkedUploadHandler {
// Assemble chunks (hash-on-write: SHA-256 computed during assembly) // Assemble chunks (hash-on-write: SHA-256 computed during assembly)
let (assembled_path, filename, folder_id, content_type, total_size, hash) = let (assembled_path, filename, folder_id, content_type, total_size, hash) =
match chunked_service.complete_upload(&upload_id).await { match chunked_service.complete_upload(&upload_id, &auth_user.id).await {
Ok(result) => result, Ok(result) => result,
Err(e) => { Err(e) => {
let status = match e.kind { return AppError::from(e).into_response();
ErrorKind::NotFound => StatusCode::NOT_FOUND,
ErrorKind::InvalidInput | ErrorKind::AlreadyExists => StatusCode::CONFLICT,
_ => StatusCode::INTERNAL_SERVER_ERROR,
};
return (
status,
Json(serde_json::json!({
"error": e.to_string()
})),
)
.into_response();
} }
}; };
@@ -323,7 +289,7 @@ impl ChunkedUploadHandler {
{ {
Ok(file) => { Ok(file) => {
// Cleanup session // Cleanup session
let _ = chunked_service.finalize_upload(&upload_id).await; let _ = chunked_service.finalize_upload(&upload_id, &auth_user.id).await;
tracing::info!( tracing::info!(
"✅ CHUNKED UPLOAD COMPLETE: {} (ID: {}, {} bytes)", "✅ CHUNKED UPLOAD COMPLETE: {} (ID: {}, {} bytes)",
@@ -345,12 +311,7 @@ impl ChunkedUploadHandler {
} }
Err(e) => { Err(e) => {
tracing::error!("Failed to create file from assembled upload: {:?}", e); tracing::error!("Failed to create file from assembled upload: {:?}", e);
( AppError::internal_error(format!("Failed to create file: {}", e))
StatusCode::INTERNAL_SERVER_ERROR,
Json(serde_json::json!({
"error": format!("Failed to create file: {:?}", e)
})),
)
.into_response() .into_response()
} }
} }
@@ -361,18 +322,14 @@ impl ChunkedUploadHandler {
/// Cancels an in-progress upload and cleans up temp files /// Cancels an in-progress upload and cleans up temp files
pub async fn cancel_upload( pub async fn cancel_upload(
State(state): State<Arc<AppState>>, State(state): State<Arc<AppState>>,
auth_user: AuthUser,
Path(upload_id): Path<String>, Path(upload_id): Path<String>,
) -> impl IntoResponse { ) -> impl IntoResponse {
let chunked_service = &state.core.chunked_upload_service; let chunked_service = &state.core.chunked_upload_service;
match chunked_service.cancel_upload(&upload_id).await { match chunked_service.cancel_upload(&upload_id, &auth_user.id).await {
Ok(_) => StatusCode::NO_CONTENT.into_response(), Ok(_) => StatusCode::NO_CONTENT.into_response(),
Err(e) => ( Err(e) => AppError::internal_error(format!("Failed to cancel upload: {}", e))
StatusCode::INTERNAL_SERVER_ERROR,
Json(serde_json::json!({
"error": e.to_string()
})),
)
.into_response(), .into_response(),
} }
} }
+88 -98
View File
@@ -9,6 +9,7 @@ use serde::Serialize;
use crate::application::ports::dedup_ports::DedupResultDto; use crate::application::ports::dedup_ports::DedupResultDto;
use crate::common::di::AppState; use crate::common::di::AppState;
use crate::interfaces::middleware::auth::AuthUser;
use std::sync::Arc; use std::sync::Arc;
/// Global application state for dependency injection /// Global application state for dependency injection
@@ -72,14 +73,15 @@ pub struct StatsResponse {
pub struct DedupHandler; pub struct DedupHandler;
impl DedupHandler { impl DedupHandler {
/// Check if a blob with the given hash already exists /// Check if the authenticated user already has a file with the given hash.
/// ///
/// This endpoint allows clients to check if uploading a file is necessary /// User-scoped: only reveals whether **this user** owns a file that
/// by pre-computing the hash client-side and checking against the server. /// references the blob — never exposes global existence or ref_count.
/// ///
/// GET /api/dedup/check/{hash} /// GET /api/dedup/check/{hash}
pub async fn check_hash( pub async fn check_hash(
State(state): State<GlobalState>, State(state): State<GlobalState>,
auth_user: AuthUser,
Path(hash): Path<String>, Path(hash): Path<String>,
) -> impl IntoResponse { ) -> impl IntoResponse {
let dedup = &state.core.dedup_service; let dedup = &state.core.dedup_service;
@@ -96,35 +98,37 @@ impl DedupHandler {
.into_response(); .into_response();
} }
match dedup.get_blob_metadata(&hash).await { // Only reveal whether THIS user has the blob — no global oracle
Some(metadata) => { let user_has_it = dedup.user_owns_blob_reference(&hash, &auth_user.id).await;
let response = HashCheckResponse {
exists: true, if user_has_it {
hash, // Fetch size from metadata (safe — user owns a reference)
existing_size: Some(metadata.size), let size = dedup.get_blob_metadata(&hash).await.map(|m| m.size);
ref_count: Some(metadata.ref_count), let response = HashCheckResponse {
}; exists: true,
Response::builder() hash,
.status(StatusCode::OK) existing_size: size,
.header(header::CONTENT_TYPE, "application/json") ref_count: None, // Never expose global ref_count
.body(Body::from(serde_json::to_string(&response).unwrap())) };
.unwrap() Response::builder()
.into_response() .status(StatusCode::OK)
} .header(header::CONTENT_TYPE, "application/json")
None => { .body(Body::from(serde_json::to_string(&response).unwrap()))
let response = HashCheckResponse { .unwrap()
exists: false, .into_response()
hash, } else {
existing_size: None, let response = HashCheckResponse {
ref_count: None, exists: false,
}; hash,
Response::builder() existing_size: None,
.status(StatusCode::OK) ref_count: None,
.header(header::CONTENT_TYPE, "application/json") };
.body(Body::from(serde_json::to_string(&response).unwrap())) Response::builder()
.unwrap() .status(StatusCode::OK)
.into_response() .header(header::CONTENT_TYPE, "application/json")
} .body(Body::from(serde_json::to_string(&response).unwrap()))
.unwrap()
.into_response()
} }
} }
@@ -139,6 +143,7 @@ impl DedupHandler {
/// Returns information about whether the content was new or deduplicated. /// Returns information about whether the content was new or deduplicated.
pub async fn upload_with_dedup( pub async fn upload_with_dedup(
State(state): State<GlobalState>, State(state): State<GlobalState>,
_auth_user: AuthUser,
mut multipart: Multipart, mut multipart: Multipart,
) -> impl IntoResponse { ) -> impl IntoResponse {
let dedup = &state.core.dedup_service; let dedup = &state.core.dedup_service;
@@ -222,14 +227,13 @@ impl DedupHandler {
.into_response(); .into_response();
} }
Err(e) => { Err(e) => {
tracing::error!("❌ Dedup upload failed: {}", e); tracing::error!("Dedup upload failed: {}", e);
return Response::builder() return Response::builder()
.status(StatusCode::INTERNAL_SERVER_ERROR) .status(StatusCode::INTERNAL_SERVER_ERROR)
.header(header::CONTENT_TYPE, "application/json") .header(header::CONTENT_TYPE, "application/json")
.body(Body::from(format!( .body(Body::from(
r#"{{"error": "Upload failed: {}"}}"#, r#"{"error": "Upload failed"}"#,
e ))
)))
.unwrap() .unwrap()
.into_response(); .into_response();
} }
@@ -256,7 +260,20 @@ impl DedupHandler {
/// - Total references /// - Total references
/// - Bytes saved /// - Bytes saved
/// - Deduplication ratio /// - Deduplication ratio
pub async fn get_stats(State(state): State<GlobalState>) -> impl IntoResponse { pub async fn get_stats(
State(state): State<GlobalState>,
auth_user: AuthUser,
) -> impl IntoResponse {
// Admin-only — global dedup statistics are sensitive infrastructure data
if auth_user.role != "admin" {
return Response::builder()
.status(StatusCode::FORBIDDEN)
.header(header::CONTENT_TYPE, "application/json")
.body(Body::from(r#"{"error": "Admin role required"}"#))
.unwrap()
.into_response();
}
let dedup = &state.core.dedup_service; let dedup = &state.core.dedup_service;
let stats = dedup.get_stats().await; let stats = dedup.get_stats().await;
@@ -285,14 +302,16 @@ impl DedupHandler {
.into_response() .into_response()
} }
/// Retrieve content by hash /// Retrieve content by hash (user-scoped).
/// ///
/// GET /api/dedup/blob/{hash} /// GET /api/dedup/blob/{hash}
/// ///
/// Returns the raw content of a blob identified by its SHA-256 hash. /// Returns the raw content of a blob **only if** the authenticated user
/// Useful for retrieving deduplicated content. /// owns at least one file that references it. Returns 404 otherwise
/// (does not reveal whether the blob exists globally).
pub async fn get_blob( pub async fn get_blob(
State(state): State<GlobalState>, State(state): State<GlobalState>,
auth_user: AuthUser,
Path(hash): Path<String>, Path(hash): Path<String>,
) -> impl IntoResponse { ) -> impl IntoResponse {
let dedup = &state.core.dedup_service; let dedup = &state.core.dedup_service;
@@ -307,6 +326,16 @@ impl DedupHandler {
.into_response(); .into_response();
} }
// Verify the user owns at least one file referencing this blob
if !dedup.user_owns_blob_reference(&hash, &auth_user.id).await {
return Response::builder()
.status(StatusCode::NOT_FOUND)
.header(header::CONTENT_TYPE, "application/json")
.body(Body::from(r#"{"error": "Blob not found"}"#))
.unwrap()
.into_response();
}
// Get metadata first for content-type // Get metadata first for content-type
let metadata = dedup.get_blob_metadata(&hash).await; let metadata = dedup.get_blob_metadata(&hash).await;
let content_type = metadata let content_type = metadata
@@ -345,65 +374,26 @@ impl DedupHandler {
} }
} }
/// Remove a reference to a blob
///
/// DELETE /api/dedup/blob/{hash}
///
/// Decrements the reference count for a blob. If the reference count
/// reaches zero, the blob is deleted from storage.
pub async fn remove_reference(
State(state): State<GlobalState>,
Path(hash): Path<String>,
) -> impl IntoResponse {
let dedup = &state.core.dedup_service;
// Validate hash format
if hash.len() != 64 || !hash.chars().all(|c| c.is_ascii_hexdigit()) {
return Response::builder()
.status(StatusCode::BAD_REQUEST)
.header(header::CONTENT_TYPE, "application/json")
.body(Body::from(r#"{"error": "Invalid hash format"}"#))
.unwrap()
.into_response();
}
match dedup.remove_reference(&hash).await {
Ok(deleted) => {
let message = if deleted {
format!(
r#"{{"success": true, "deleted": true, "message": "Blob {} was deleted (ref_count reached 0)"}}"#,
hash
)
} else {
format!(
r#"{{"success": true, "deleted": false, "message": "Reference removed from blob {}"}}"#,
hash
)
};
Response::builder()
.status(StatusCode::OK)
.header(header::CONTENT_TYPE, "application/json")
.body(Body::from(message))
.unwrap()
.into_response()
}
Err(e) => Response::builder()
.status(StatusCode::INTERNAL_SERVER_ERROR)
.header(header::CONTENT_TYPE, "application/json")
.body(Body::from(format!(r#"{{"error": "{}"}}"#, e)))
.unwrap()
.into_response(),
}
}
/// Force recalculation of statistics from disk /// Force recalculation of statistics from disk
/// ///
/// POST /api/dedup/recalculate /// POST /api/dedup/recalculate
/// ///
/// Verifies integrity and returns current statistics. /// Verifies integrity and returns current statistics.
/// Useful for health checks and auditing. /// Useful for health checks and auditing.
pub async fn recalculate_stats(State(state): State<GlobalState>) -> impl IntoResponse { pub async fn recalculate_stats(
State(state): State<GlobalState>,
auth_user: AuthUser,
) -> impl IntoResponse {
// Admin-only — integrity verification is a privileged operation
if auth_user.role != "admin" {
return Response::builder()
.status(StatusCode::FORBIDDEN)
.header(header::CONTENT_TYPE, "application/json")
.body(Body::from(r#"{"error": "Admin role required"}"#))
.unwrap()
.into_response();
}
let dedup = &state.core.dedup_service; let dedup = &state.core.dedup_service;
// Verify integrity first // Verify integrity first
@@ -414,13 +404,13 @@ impl DedupHandler {
} }
} }
Err(e) => { Err(e) => {
tracing::error!("Dedup integrity verification failed: {}", e);
return Response::builder() return Response::builder()
.status(StatusCode::INTERNAL_SERVER_ERROR) .status(StatusCode::INTERNAL_SERVER_ERROR)
.header(header::CONTENT_TYPE, "application/json") .header(header::CONTENT_TYPE, "application/json")
.body(Body::from(format!( .body(Body::from(
r#"{{"error": "Verification failed: {}"}}"#, r#"{"error": "Verification failed"}"#,
e ))
)))
.unwrap() .unwrap()
.into_response(); .into_response();
} }
@@ -42,7 +42,7 @@ pub async fn get_favorites(
( (
StatusCode::INTERNAL_SERVER_ERROR, StatusCode::INTERNAL_SERVER_ERROR,
Json(serde_json::json!({ Json(serde_json::json!({
"error": format!("Failed to retrieve favorites: {}", err) "error": "Failed to retrieve favorites"
})), })),
) )
.into_response() .into_response()
@@ -86,7 +86,7 @@ pub async fn add_favorite(
( (
StatusCode::INTERNAL_SERVER_ERROR, StatusCode::INTERNAL_SERVER_ERROR,
Json(serde_json::json!({ Json(serde_json::json!({
"error": format!("Failed to add to favorites: {}", err) "error": "Failed to add to favorites"
})), })),
) )
} }
@@ -129,7 +129,7 @@ pub async fn remove_favorite(
( (
StatusCode::INTERNAL_SERVER_ERROR, StatusCode::INTERNAL_SERVER_ERROR,
Json(serde_json::json!({ Json(serde_json::json!({
"error": format!("Failed to remove from favorites: {}", err) "error": "Failed to remove from favorites"
})), })),
) )
} }
@@ -188,7 +188,7 @@ pub async fn batch_add_favorites(
( (
StatusCode::INTERNAL_SERVER_ERROR, StatusCode::INTERNAL_SERVER_ERROR,
Json(serde_json::json!({ Json(serde_json::json!({
"error": format!("Failed to batch add favorites: {}", err) "error": "Failed to batch add favorites"
})), })),
) )
.into_response() .into_response()
+14 -131
View File
@@ -17,6 +17,7 @@ use crate::application::ports::file_ports::{
use crate::application::ports::storage_ports::StorageUsagePort; use crate::application::ports::storage_ports::StorageUsagePort;
use crate::application::ports::thumbnail_ports::ThumbnailPort; use crate::application::ports::thumbnail_ports::ThumbnailPort;
use crate::common::di::AppState; use crate::common::di::AppState;
use crate::interfaces::errors::AppError;
use crate::interfaces::middleware::auth::AuthUser; use crate::interfaces::middleware::auth::AuthUser;
use std::sync::Arc; use std::sync::Arc;
@@ -291,13 +292,7 @@ impl FileHandler {
{ {
Ok(f) => f, Ok(f) => f,
Err(err) => { Err(err) => {
return ( return AppError::from(err).into_response();
StatusCode::NOT_FOUND,
Json(serde_json::json!({
"error": format!("File not found: {}", err)
})),
)
.into_response();
} }
}; };
@@ -331,13 +326,7 @@ impl FileHandler {
.into_response() .into_response()
} }
Err(err) => { Err(err) => {
tracing::error!("Thumbnail generation failed: {}", err); AppError::internal_error(format!("Thumbnail generation failed: {}", err))
(
StatusCode::INTERNAL_SERVER_ERROR,
Json(serde_json::json!({
"error": format!("Failed to generate thumbnail: {}", err)
})),
)
.into_response() .into_response()
} }
} }
@@ -366,20 +355,7 @@ impl FileHandler {
let file_dto = match retrieval.get_file_owned(&id, &auth_user.id).await { let file_dto = match retrieval.get_file_owned(&id, &auth_user.id).await {
Ok(f) => f, Ok(f) => f,
Err(err) => { Err(err) => {
let status = if err.to_string().contains("not found") return AppError::from(err).into_response();
|| err.to_string().contains("NotFound")
{
StatusCode::NOT_FOUND
} else {
StatusCode::INTERNAL_SERVER_ERROR
};
return (
status,
Json(serde_json::json!({
"error": err.to_string()
})),
)
.into_response();
} }
}; };
@@ -526,14 +502,7 @@ impl FileHandler {
.into_response(), .into_response(),
}, },
Err(err) => { Err(err) => {
tracing::error!("Error downloading file: {}", err); AppError::from(err).into_response()
(
StatusCode::INTERNAL_SERVER_ERROR,
Json(serde_json::json!({
"error": format!("Error reading file: {}", err)
})),
)
.into_response()
} }
} }
} }
@@ -547,6 +516,7 @@ impl FileHandler {
/// Axum-compatible handler wrapper around [`Self::list_files`]. /// Axum-compatible handler wrapper around [`Self::list_files`].
pub async fn list_files_query( pub async fn list_files_query(
State(state): State<GlobalState>, State(state): State<GlobalState>,
auth_user: AuthUser,
headers: HeaderMap, headers: HeaderMap,
Query(params): Query<HashMap<String, String>>, Query(params): Query<HashMap<String, String>>,
) -> impl IntoResponse { ) -> impl IntoResponse {
@@ -554,7 +524,7 @@ impl FileHandler {
tracing::info!("API: Listing files with folder_id: {:?}", folder_id); tracing::info!("API: Listing files with folder_id: {:?}", folder_id);
let retrieval = &state.applications.file_retrieval_service; let retrieval = &state.applications.file_retrieval_service;
match retrieval.list_files(folder_id).await { match retrieval.list_files_owned(folder_id, &auth_user.id).await {
Ok(files) => { Ok(files) => {
// Compute lightweight ETag from max modified_at + count // Compute lightweight ETag from max modified_at + count
let max_mod = files.iter().map(|f| f.modified_at).max().unwrap_or(0); let max_mod = files.iter().map(|f| f.modified_at).max().unwrap_or(0);
@@ -584,14 +554,7 @@ impl FileHandler {
resp resp
} }
Err(err) => { Err(err) => {
tracing::error!("Error listing files: {}", err); AppError::from(err).into_response()
(
StatusCode::INTERNAL_SERVER_ERROR,
Json(serde_json::json!({
"error": format!("Error listing files: {}", err)
})),
)
.into_response()
} }
} }
} }
@@ -664,23 +627,7 @@ impl FileHandler {
match result { match result {
Ok(_) => StatusCode::NO_CONTENT.into_response(), Ok(_) => StatusCode::NO_CONTENT.into_response(),
Err(err) => { Err(err) => AppError::from(err).into_response()
tracing::error!("Error deleting file: {}", err);
let status = if err.to_string().contains("not found")
|| err.to_string().contains("NotFound")
{
StatusCode::NOT_FOUND
} else {
StatusCode::INTERNAL_SERVER_ERROR
};
(
status,
Json(serde_json::json!({
"error": format!("Error deleting file: {}", err)
})),
)
.into_response()
}
} }
} }
@@ -712,25 +659,7 @@ impl FileHandler {
let mgmt = &state.applications.file_management_service; let mgmt = &state.applications.file_management_service;
match mgmt.rename_file_owned(&id, &auth_user.id, &new_name).await { match mgmt.rename_file_owned(&id, &auth_user.id, &new_name).await {
Ok(file_dto) => (StatusCode::OK, Json(file_dto)).into_response(), Ok(file_dto) => (StatusCode::OK, Json(file_dto)).into_response(),
Err(err) => { Err(err) => AppError::from(err).into_response()
tracing::error!("Error renaming file: {}", err);
let status = if err.to_string().contains("not found")
|| err.to_string().contains("NotFound")
{
StatusCode::NOT_FOUND
} else if err.to_string().contains("already exists") {
StatusCode::CONFLICT
} else {
StatusCode::INTERNAL_SERVER_ERROR
};
(
status,
Json(serde_json::json!({
"error": format!("Error renaming file: {}", err)
})),
)
.into_response()
}
} }
} }
@@ -750,23 +679,7 @@ impl FileHandler {
.await .await
{ {
Ok(file) => (StatusCode::OK, Json(file)).into_response(), Ok(file) => (StatusCode::OK, Json(file)).into_response(),
Err(err) => { Err(err) => AppError::from(err).into_response()
tracing::error!("Error moving file: {}", err);
let status = if err.to_string().contains("not found")
|| err.to_string().contains("NotFound")
{
StatusCode::NOT_FOUND
} else {
StatusCode::INTERNAL_SERVER_ERROR
};
(
status,
Json(serde_json::json!({
"error": format!("Error moving file: {}", err)
})),
)
.into_response()
}
} }
} }
@@ -785,16 +698,7 @@ impl FileHandler {
let mgmt = &state.applications.file_management_service; let mgmt = &state.applications.file_management_service;
match mgmt.move_file_owned(&id, &auth_user.id, folder_id).await { match mgmt.move_file_owned(&id, &auth_user.id, folder_id).await {
Ok(file_dto) => (StatusCode::OK, Json(file_dto)).into_response(), Ok(file_dto) => (StatusCode::OK, Json(file_dto)).into_response(),
Err(err) => { Err(err) => AppError::from(err).into_response()
tracing::error!("Error moving file: {}", err);
(
StatusCode::INTERNAL_SERVER_ERROR,
Json(serde_json::json!({
"error": format!("Error moving file: {}", err)
})),
)
.into_response()
}
} }
} }
@@ -831,33 +735,12 @@ impl FileHandler {
/// Build error response for DomainError. /// Build error response for DomainError.
fn domain_error_response(err: crate::common::errors::DomainError) -> Response<Body> { fn domain_error_response(err: crate::common::errors::DomainError) -> Response<Body> {
let status = match err.kind { AppError::from(err).into_response()
crate::common::errors::ErrorKind::NotFound => StatusCode::NOT_FOUND,
crate::common::errors::ErrorKind::QuotaExceeded => StatusCode::INSUFFICIENT_STORAGE,
_ => StatusCode::INTERNAL_SERVER_ERROR,
};
Response::builder()
.status(status)
.header(header::CONTENT_TYPE, "application/json")
.body(Body::from(
serde_json::json!({ "error": format!("Error: {}", err) }).to_string(),
))
.unwrap()
} }
/// Build a quota-specific error response with 507 status and structured body. /// Build a quota-specific error response with 507 status and structured body.
fn quota_error_response(err: crate::common::errors::DomainError) -> Response<Body> { fn quota_error_response(err: crate::common::errors::DomainError) -> Response<Body> {
Response::builder() AppError::from(err).into_response()
.status(StatusCode::INSUFFICIENT_STORAGE)
.header(header::CONTENT_TYPE, "application/json")
.body(Body::from(
serde_json::json!({
"error": err.message,
"error_type": "QuotaExceeded"
})
.to_string(),
))
.unwrap()
} }
/// Build response for cached/small files. /// Build response for cached/small files.
+14 -118
View File
@@ -18,7 +18,7 @@ use crate::application::ports::inbound::FolderUseCase;
use crate::application::ports::trash_ports::TrashUseCase; use crate::application::ports::trash_ports::TrashUseCase;
use crate::application::services::folder_service::FolderService; use crate::application::services::folder_service::FolderService;
use crate::common::di::AppState as GlobalAppState; use crate::common::di::AppState as GlobalAppState;
use crate::common::errors::ErrorKind; use crate::interfaces::errors::AppError;
use crate::interfaces::middleware::auth::AuthUser; use crate::interfaces::middleware::auth::AuthUser;
type AppState = Arc<FolderService>; type AppState = Arc<FolderService>;
@@ -69,15 +69,7 @@ impl FolderHandler {
match service.create_folder(dto).await { match service.create_folder(dto).await {
Ok(folder) => (StatusCode::CREATED, Json(folder)).into_response(), Ok(folder) => (StatusCode::CREATED, Json(folder)).into_response(),
Err(err) => { Err(err) => AppError::from(err).into_response()
let status = match err.kind {
ErrorKind::AlreadyExists => StatusCode::CONFLICT,
ErrorKind::NotFound => StatusCode::NOT_FOUND,
_ => StatusCode::INTERNAL_SERVER_ERROR,
};
(status, err.to_string()).into_response()
}
} }
} }
@@ -100,18 +92,11 @@ impl FolderHandler {
id, id,
owner owner
); );
return (StatusCode::NOT_FOUND, "Folder not found".to_string()).into_response(); return AppError::not_found("Folder not found").into_response();
} }
(StatusCode::OK, Json(folder)).into_response() (StatusCode::OK, Json(folder)).into_response()
} }
Err(err) => { Err(err) => AppError::from(err).into_response()
let status = match err.kind {
ErrorKind::NotFound => StatusCode::NOT_FOUND,
_ => StatusCode::INTERNAL_SERVER_ERROR,
};
(status, err.to_string()).into_response()
}
} }
} }
@@ -156,17 +141,7 @@ impl FolderHandler {
.await .await
{ {
Ok(paginated_result) => (StatusCode::OK, Json(paginated_result)).into_response(), Ok(paginated_result) => (StatusCode::OK, Json(paginated_result)).into_response(),
Err(err) => { Err(err) => AppError::from(err).into_response()
let status = match err.kind {
ErrorKind::NotFound => StatusCode::NOT_FOUND,
_ => StatusCode::INTERNAL_SERVER_ERROR,
};
(
status,
Json(serde_json::json!({ "error": err.to_string() })),
)
.into_response()
}
} }
} }
@@ -183,17 +158,7 @@ impl FolderHandler {
.await .await
{ {
Ok(folders) => (StatusCode::OK, Json(folders)).into_response(), Ok(folders) => (StatusCode::OK, Json(folders)).into_response(),
Err(err) => { Err(err) => AppError::from(err).into_response()
let status = match err.kind {
ErrorKind::NotFound => StatusCode::NOT_FOUND,
_ => StatusCode::INTERNAL_SERVER_ERROR,
};
(
status,
Json(serde_json::json!({ "error": err.to_string() })),
)
.into_response()
}
} }
} }
@@ -233,7 +198,7 @@ impl FolderHandler {
// Run both queries concurrently — no sequential wait. // Run both queries concurrently — no sequential wait.
let (folders_result, files_result) = tokio::join!( let (folders_result, files_result) = tokio::join!(
folder_service.list_folders_for_owner(Some(&id), &auth_user.id), folder_service.list_folders_for_owner(Some(&id), &auth_user.id),
file_service.list_files(Some(&id)) file_service.list_files_owned(Some(&id), &auth_user.id)
); );
match (folders_result, files_result) { match (folders_result, files_result) {
@@ -259,17 +224,7 @@ impl FolderHandler {
.insert(header::ETAG, header::HeaderValue::from_str(&etag).unwrap()); .insert(header::ETAG, header::HeaderValue::from_str(&etag).unwrap());
resp resp
} }
(Err(err), _) | (_, Err(err)) => { (Err(err), _) | (_, Err(err)) => AppError::from(err).into_response()
let status = match err.kind {
ErrorKind::NotFound => StatusCode::NOT_FOUND,
_ => StatusCode::INTERNAL_SERVER_ERROR,
};
(
status,
Json(serde_json::json!({ "error": err.to_string() })),
)
.into_response()
}
} }
} }
@@ -282,22 +237,7 @@ impl FolderHandler {
) -> impl IntoResponse { ) -> impl IntoResponse {
match service.rename_folder(&id, dto, &auth_user.id).await { match service.rename_folder(&id, dto, &auth_user.id).await {
Ok(folder) => (StatusCode::OK, Json(folder)).into_response(), Ok(folder) => (StatusCode::OK, Json(folder)).into_response(),
Err(err) => { Err(err) => AppError::from(err).into_response()
let status = match err.kind {
ErrorKind::NotFound => StatusCode::NOT_FOUND,
ErrorKind::AlreadyExists => StatusCode::CONFLICT,
_ => StatusCode::INTERNAL_SERVER_ERROR,
};
// Return a proper JSON error response
(
status,
Json(serde_json::json!({
"error": err.to_string()
})),
)
.into_response()
}
} }
} }
@@ -310,15 +250,7 @@ impl FolderHandler {
) -> impl IntoResponse { ) -> impl IntoResponse {
match service.move_folder(&id, dto, &auth_user.id).await { match service.move_folder(&id, dto, &auth_user.id).await {
Ok(folder) => (StatusCode::OK, Json(folder)).into_response(), Ok(folder) => (StatusCode::OK, Json(folder)).into_response(),
Err(err) => { Err(err) => AppError::from(err).into_response()
let status = match err.kind {
ErrorKind::NotFound => StatusCode::NOT_FOUND,
ErrorKind::AlreadyExists => StatusCode::CONFLICT,
_ => StatusCode::INTERNAL_SERVER_ERROR,
};
(status, err.to_string()).into_response()
}
} }
} }
@@ -330,14 +262,7 @@ impl FolderHandler {
) -> impl IntoResponse { ) -> impl IntoResponse {
match service.delete_folder(&id, &auth_user.id).await { match service.delete_folder(&id, &auth_user.id).await {
Ok(_) => StatusCode::NO_CONTENT.into_response(), Ok(_) => StatusCode::NO_CONTENT.into_response(),
Err(err) => { Err(err) => AppError::from(err).into_response()
let status = match err.kind {
ErrorKind::NotFound => StatusCode::NOT_FOUND,
_ => StatusCode::INTERNAL_SERVER_ERROR,
};
(status, err.to_string()).into_response()
}
} }
} }
@@ -376,20 +301,7 @@ impl FolderHandler {
StatusCode::NO_CONTENT.into_response() StatusCode::NO_CONTENT.into_response()
} }
Err(err) => { Err(err) => {
tracing::error!("Error deleting folder: {}", err); AppError::from(err).into_response()
let status = match err.kind {
ErrorKind::NotFound => StatusCode::NOT_FOUND,
_ => StatusCode::INTERNAL_SERVER_ERROR,
};
(
status,
Json(serde_json::json!({
"error": format!("Error deleting folder: {}", err)
})),
)
.into_response()
} }
} }
} }
@@ -487,30 +399,14 @@ impl FolderHandler {
} }
Err(err) => { Err(err) => {
tracing::error!("Error creating ZIP file: {}", err); tracing::error!("Error creating ZIP file: {}", err);
( AppError::internal_error(format!("Error creating ZIP file: {}", err))
StatusCode::INTERNAL_SERVER_ERROR,
Json(serde_json::json!({
"error": format!("Error creating ZIP file: {}", err)
})),
)
.into_response() .into_response()
} }
} }
} }
Err(err) => { Err(err) => {
tracing::error!("Folder not found: {}", err); tracing::error!("Folder not found: {}", err);
let status = match err.kind { AppError::from(err).into_response()
ErrorKind::NotFound => StatusCode::NOT_FOUND,
_ => StatusCode::INTERNAL_SERVER_ERROR,
};
(
status,
Json(serde_json::json!({
"error": format!("Error finding folder: {}", err)
})),
)
.into_response()
} }
} }
} }
+11 -5
View File
@@ -56,16 +56,22 @@ impl I18nHandler {
(StatusCode::OK, Json(response)).into_response() (StatusCode::OK, Json(response)).into_response()
} }
Err(err) => { Err(err) => {
let status = match &err { let (status, error_msg) = match &err {
I18nError::KeyNotFound(_) => StatusCode::NOT_FOUND, I18nError::KeyNotFound(_) => (StatusCode::NOT_FOUND, err.to_string()),
I18nError::InvalidLocale(_) => StatusCode::BAD_REQUEST, I18nError::InvalidLocale(_) => (StatusCode::BAD_REQUEST, err.to_string()),
I18nError::LoadError(_) => StatusCode::INTERNAL_SERVER_ERROR, I18nError::LoadError(_) => {
tracing::error!("I18n load error: {}", err);
(
StatusCode::INTERNAL_SERVER_ERROR,
"Translation loading error".to_string(),
)
}
}; };
let error = TranslationErrorDto { let error = TranslationErrorDto {
key: query.key, key: query.key,
locale: locale.unwrap_or(Locale::default()).as_str().to_string(), locale: locale.unwrap_or(Locale::default()).as_str().to_string(),
error: err.to_string(), error: error_msg,
}; };
(status, Json(error)).into_response() (status, Json(error)).into_response()
@@ -37,7 +37,7 @@ pub async fn get_recent_items(
( (
StatusCode::INTERNAL_SERVER_ERROR, StatusCode::INTERNAL_SERVER_ERROR,
Json(serde_json::json!({ Json(serde_json::json!({
"error": format!("Failed to retrieve recent items: {}", err) "error": "Failed to retrieve recent items"
})), })),
) )
.into_response() .into_response()
@@ -83,7 +83,7 @@ pub async fn record_item_access(
( (
StatusCode::INTERNAL_SERVER_ERROR, StatusCode::INTERNAL_SERVER_ERROR,
Json(serde_json::json!({ Json(serde_json::json!({
"error": format!("Failed to record access: {}", err) "error": "Failed to record access"
})), })),
) )
.into_response() .into_response()
@@ -129,7 +129,7 @@ pub async fn remove_from_recent(
( (
StatusCode::INTERNAL_SERVER_ERROR, StatusCode::INTERNAL_SERVER_ERROR,
Json(serde_json::json!({ Json(serde_json::json!({
"error": format!("Failed to remove from recents: {}", err) "error": "Failed to remove from recents"
})), })),
) )
.into_response() .into_response()
@@ -160,7 +160,7 @@ pub async fn clear_recent_items(
( (
StatusCode::INTERNAL_SERVER_ERROR, StatusCode::INTERNAL_SERVER_ERROR,
Json(serde_json::json!({ Json(serde_json::json!({
"error": format!("Failed to clear recent items: {}", err) "error": "Failed to clear recent items"
})), })),
) )
.into_response() .into_response()
@@ -74,7 +74,7 @@ impl SearchHandler {
error!("Search error: {}", err); error!("Search error: {}", err);
( (
StatusCode::INTERNAL_SERVER_ERROR, StatusCode::INTERNAL_SERVER_ERROR,
Json(json!({ "error": format!("Search error: {}", err) })), Json(json!({ "error": "Search error" })),
) )
.into_response() .into_response()
} }
@@ -115,7 +115,7 @@ impl SearchHandler {
error!("Search error: {}", err); error!("Search error: {}", err);
( (
StatusCode::INTERNAL_SERVER_ERROR, StatusCode::INTERNAL_SERVER_ERROR,
Json(json!({ "error": format!("Search error: {}", err) })), Json(json!({ "error": "Search error" })),
) )
.into_response() .into_response()
} }
@@ -159,7 +159,7 @@ impl SearchHandler {
error!("Suggestions error: {}", err); error!("Suggestions error: {}", err);
( (
StatusCode::INTERNAL_SERVER_ERROR, StatusCode::INTERNAL_SERVER_ERROR,
Json(json!({ "error": format!("Suggestions error: {}", err) })), Json(json!({ "error": "Suggestions error" })),
) )
.into_response() .into_response()
} }
@@ -195,7 +195,7 @@ impl SearchHandler {
error!("Error clearing search cache: {}", err); error!("Error clearing search cache: {}", err);
( (
StatusCode::INTERNAL_SERVER_ERROR, StatusCode::INTERNAL_SERVER_ERROR,
Json(json!({ "error": format!("Error clearing search cache: {}", err) })), Json(json!({ "error": "Error clearing search cache" })),
) )
.into_response() .into_response()
} }
+55 -93
View File
@@ -17,7 +17,8 @@ use crate::{
}, },
common::errors::ErrorKind, common::errors::ErrorKind,
domain::entities::share::ShareItemType, domain::entities::share::ShareItemType,
interfaces::middleware::auth::OptionalAuthUser, interfaces::errors::AppError,
interfaces::middleware::auth::AuthUser,
}; };
#[derive(Debug, Deserialize)] #[derive(Debug, Deserialize)]
@@ -36,40 +37,27 @@ pub struct VerifyPasswordRequest {
/// Create a new shared link /// Create a new shared link
pub async fn create_shared_link( pub async fn create_shared_link(
State(share_use_case): State<Arc<ShareService>>, State(share_use_case): State<Arc<ShareService>>,
auth_user: OptionalAuthUser, auth_user: AuthUser,
Json(dto): Json<CreateShareDto>, Json(dto): Json<CreateShareDto>,
) -> impl IntoResponse { ) -> impl IntoResponse {
let user_id = auth_user match share_use_case
.0 .create_shared_link(&auth_user.id, dto)
.map(|u| u.id) .await
.unwrap_or_else(|| "anonymous".to_string()); {
match share_use_case.create_shared_link(&user_id, dto).await {
Ok(share) => (StatusCode::CREATED, Json(share)).into_response(), Ok(share) => (StatusCode::CREATED, Json(share)).into_response(),
Err(err) => { Err(err) => AppError::from(err).into_response()
let status = match err.kind {
ErrorKind::NotFound => StatusCode::NOT_FOUND,
ErrorKind::InvalidInput => StatusCode::BAD_REQUEST,
_ => StatusCode::INTERNAL_SERVER_ERROR,
};
(status, Json(json!({ "error": err.to_string() }))).into_response()
}
} }
} }
/// Get information about a specific shared link by ID /// Get information about a specific shared link by ID
pub async fn get_shared_link( pub async fn get_shared_link(
State(share_use_case): State<Arc<ShareService>>, State(share_use_case): State<Arc<ShareService>>,
auth_user: AuthUser,
Path(id): Path<String>, Path(id): Path<String>,
) -> impl IntoResponse { ) -> impl IntoResponse {
match share_use_case.get_shared_link(&id).await { match share_use_case.get_shared_link(&id, &auth_user.id).await {
Ok(share) => (StatusCode::OK, Json(share)).into_response(), Ok(share) => (StatusCode::OK, Json(share)).into_response(),
Err(err) => { Err(err) => AppError::from(err).into_response()
let status = match err.kind {
ErrorKind::NotFound => StatusCode::NOT_FOUND,
_ => StatusCode::INTERNAL_SERVER_ERROR,
};
(status, Json(json!({ "error": err.to_string() }))).into_response()
}
} }
} }
@@ -77,13 +65,10 @@ pub async fn get_shared_link(
/// Supports optional filtering by item_id + item_type query params. /// Supports optional filtering by item_id + item_type query params.
pub async fn get_user_shares( pub async fn get_user_shares(
State(share_use_case): State<Arc<ShareService>>, State(share_use_case): State<Arc<ShareService>>,
auth_user: OptionalAuthUser, auth_user: AuthUser,
Query(query): Query<GetSharesQuery>, Query(query): Query<GetSharesQuery>,
) -> impl IntoResponse { ) -> impl IntoResponse {
let _user_id = auth_user let user_id = &auth_user.id;
.0
.map(|u| u.id)
.unwrap_or_else(|| "anonymous".to_string());
// If both item_id and item_type are provided, return shares for that specific item // If both item_id and item_type are provided, return shares for that specific item
if let (Some(item_id), Some(item_type_str)) = (&query.item_id, &query.item_type) { if let (Some(item_id), Some(item_type_str)) = (&query.item_id, &query.item_type) {
@@ -98,15 +83,11 @@ pub async fn get_user_shares(
} }
}; };
return match share_use_case return match share_use_case
.get_shared_links_for_item(item_id, &item_type) .get_shared_links_for_item(item_id, &item_type, user_id)
.await .await
{ {
Ok(shares) => (StatusCode::OK, Json(shares)).into_response(), Ok(shares) => (StatusCode::OK, Json(shares)).into_response(),
Err(err) => ( Err(err) => AppError::from(err).into_response(),
StatusCode::INTERNAL_SERVER_ERROR,
Json(json!({ "error": err.to_string() })),
)
.into_response(),
}; };
} }
@@ -115,53 +96,42 @@ pub async fn get_user_shares(
let per_page = query.per_page.unwrap_or(20); let per_page = query.per_page.unwrap_or(20);
match share_use_case match share_use_case
.get_user_shared_links(&_user_id, page, per_page) .get_user_shared_links(user_id, page, per_page)
.await .await
{ {
Ok(shares) => (StatusCode::OK, Json(shares)).into_response(), Ok(shares) => (StatusCode::OK, Json(shares)).into_response(),
Err(err) => ( Err(err) => AppError::from(err).into_response(),
StatusCode::INTERNAL_SERVER_ERROR,
Json(json!({ "error": err.to_string() })),
)
.into_response(),
} }
} }
/// Update a shared link's properties /// Update a shared link's properties
pub async fn update_shared_link( pub async fn update_shared_link(
State(share_use_case): State<Arc<ShareService>>, State(share_use_case): State<Arc<ShareService>>,
auth_user: AuthUser,
Path(id): Path<String>, Path(id): Path<String>,
Json(dto): Json<UpdateShareDto>, Json(dto): Json<UpdateShareDto>,
) -> impl IntoResponse { ) -> impl IntoResponse {
match share_use_case.update_shared_link(&id, dto).await { match share_use_case
.update_shared_link(&id, &auth_user.id, dto)
.await
{
Ok(share) => (StatusCode::OK, Json(share)).into_response(), Ok(share) => (StatusCode::OK, Json(share)).into_response(),
Err(err) => { Err(err) => AppError::from(err).into_response()
let status = match err.kind {
ErrorKind::NotFound => StatusCode::NOT_FOUND,
ErrorKind::AccessDenied => StatusCode::FORBIDDEN,
ErrorKind::InvalidInput => StatusCode::BAD_REQUEST,
_ => StatusCode::INTERNAL_SERVER_ERROR,
};
(status, Json(json!({ "error": err.to_string() }))).into_response()
}
} }
} }
/// Delete a shared link /// Delete a shared link
pub async fn delete_shared_link( pub async fn delete_shared_link(
State(share_use_case): State<Arc<ShareService>>, State(share_use_case): State<Arc<ShareService>>,
auth_user: AuthUser,
Path(id): Path<String>, Path(id): Path<String>,
) -> impl IntoResponse { ) -> impl IntoResponse {
match share_use_case.delete_shared_link(&id).await { match share_use_case
.delete_shared_link(&id, &auth_user.id)
.await
{
Ok(_) => StatusCode::NO_CONTENT.into_response(), Ok(_) => StatusCode::NO_CONTENT.into_response(),
Err(err) => { Err(err) => AppError::from(err).into_response()
let status = match err.kind {
ErrorKind::NotFound => StatusCode::NOT_FOUND,
ErrorKind::AccessDenied => StatusCode::FORBIDDEN,
_ => StatusCode::INTERNAL_SERVER_ERROR,
};
(status, Json(json!({ "error": err.to_string() }))).into_response()
}
} }
} }
@@ -177,28 +147,24 @@ pub async fn access_shared_item(
match share_use_case.get_shared_link_by_token(&token).await { match share_use_case.get_shared_link_by_token(&token).await {
Ok(item) => (StatusCode::OK, Json(item)).into_response(), Ok(item) => (StatusCode::OK, Json(item)).into_response(),
Err(err) => { Err(err) => {
let status = match err.kind { // Special handling for share access errors
ErrorKind::NotFound => StatusCode::NOT_FOUND, if err.kind == ErrorKind::AccessDenied {
ErrorKind::AccessDenied => { if err.message.contains("password") {
if err.message.contains("expired") { return (
StatusCode::GONE // HTTP 410 Gone for expired links StatusCode::UNAUTHORIZED,
} else if err.message.contains("password") { Json(json!({
return ( "error": "Password required",
StatusCode::UNAUTHORIZED, "requiresPassword": true
Json(json!({ })),
"error": "Password required", )
"requiresPassword": true .into_response();
})),
)
.into_response();
} else {
StatusCode::FORBIDDEN
}
} }
_ => StatusCode::INTERNAL_SERVER_ERROR, if err.message.contains("expired") {
}; return AppError::new(StatusCode::GONE, err.message, "Expired")
.into_response();
(status, Json(json!({ "error": err.to_string() }))).into_response() }
}
AppError::from(err).into_response()
} }
} }
} }
@@ -215,20 +181,16 @@ pub async fn verify_shared_item_password(
{ {
Ok(item) => (StatusCode::OK, Json(item)).into_response(), Ok(item) => (StatusCode::OK, Json(item)).into_response(),
Err(err) => { Err(err) => {
let status = match err.kind { if err.kind == ErrorKind::AccessDenied {
ErrorKind::NotFound => StatusCode::NOT_FOUND, if err.message.contains("expired") {
ErrorKind::AccessDenied => { return AppError::new(StatusCode::GONE, err.message, "Expired")
if err.message.contains("expired") { .into_response();
StatusCode::GONE
} else if err.message.contains("password") {
StatusCode::UNAUTHORIZED
} else {
StatusCode::FORBIDDEN
}
} }
_ => StatusCode::INTERNAL_SERVER_ERROR, if err.message.contains("password") {
}; return AppError::unauthorized("Invalid password").into_response();
(status, Json(json!({ "error": err.to_string() }))).into_response() }
}
AppError::from(err).into_response()
} }
} }
} }
+11 -71
View File
@@ -6,7 +6,7 @@ use tracing::{debug, error, instrument, warn};
use crate::application::ports::trash_ports::TrashUseCase; use crate::application::ports::trash_ports::TrashUseCase;
use crate::common::di::AppState; use crate::common::di::AppState;
use crate::interfaces::middleware::auth::{AuthUser, OptionalAuthUser}; use crate::interfaces::middleware::auth::AuthUser;
use std::sync::Arc; use std::sync::Arc;
/// Gets all items in the trash for the current user /// Gets all items in the trash for the current user
@@ -46,61 +46,7 @@ pub async fn get_trash_items(
( (
StatusCode::INTERNAL_SERVER_ERROR, StatusCode::INTERNAL_SERVER_ERROR,
Json(json!({ Json(json!({
"error": format!("Error retrieving trash items: {}", e) "error": "Error retrieving trash items"
})),
)
}
}
}
/// Moves an item (file or folder) to the trash (generic function, not used directly in routes)
#[instrument(skip_all)]
pub async fn move_to_trash(
State(state): State<Arc<AppState>>,
OptionalAuthUser(auth_user): OptionalAuthUser,
Path((item_type, item_id)): Path<(String, String)>,
) -> (StatusCode, Json<serde_json::Value>) {
let user_id = auth_user
.as_ref()
.map(|u| u.id.as_str())
.unwrap_or("anonymous");
debug!(
"Request to move to trash: type={}, id={}, user={}",
item_type, item_id, user_id
);
let trash_service = match state.trash_service.as_ref() {
Some(service) => service,
None => {
return (
StatusCode::NOT_IMPLEMENTED,
Json(json!({
"error": "Trash feature is not enabled"
})),
);
}
};
let result = trash_service
.move_to_trash(&item_id, &item_type, user_id)
.await;
match result {
Ok(_) => {
debug!("Item moved to trash successfully");
(
StatusCode::OK,
Json(json!({
"success": true,
"message": "Item moved to trash successfully"
})),
)
}
Err(e) => {
error!("Error moving item to trash: {:?}", e);
(
StatusCode::INTERNAL_SERVER_ERROR,
Json(json!({
"error": format!("Error moving item to trash: {}", e)
})), })),
) )
} }
@@ -111,13 +57,10 @@ pub async fn move_to_trash(
#[instrument(skip_all)] #[instrument(skip_all)]
pub async fn move_file_to_trash( pub async fn move_file_to_trash(
State(state): State<Arc<AppState>>, State(state): State<Arc<AppState>>,
OptionalAuthUser(auth_user): OptionalAuthUser, auth_user: AuthUser,
Path(item_id): Path<String>, Path(item_id): Path<String>,
) -> (StatusCode, Json<serde_json::Value>) { ) -> (StatusCode, Json<serde_json::Value>) {
let user_id = auth_user let user_id = &auth_user.id;
.as_ref()
.map(|u| u.id.as_str())
.unwrap_or("anonymous");
debug!( debug!(
"Request to move file to trash: id={}, user={}", "Request to move file to trash: id={}, user={}",
item_id, user_id item_id, user_id
@@ -154,7 +97,7 @@ pub async fn move_file_to_trash(
( (
StatusCode::INTERNAL_SERVER_ERROR, StatusCode::INTERNAL_SERVER_ERROR,
Json(json!({ Json(json!({
"error": format!("Error moving file to trash: {}", e) "error": "Error moving file to trash"
})), })),
) )
} }
@@ -165,13 +108,10 @@ pub async fn move_file_to_trash(
#[instrument(skip_all)] #[instrument(skip_all)]
pub async fn move_folder_to_trash( pub async fn move_folder_to_trash(
State(state): State<Arc<AppState>>, State(state): State<Arc<AppState>>,
OptionalAuthUser(auth_user): OptionalAuthUser, auth_user: AuthUser,
Path(item_id): Path<String>, Path(item_id): Path<String>,
) -> (StatusCode, Json<serde_json::Value>) { ) -> (StatusCode, Json<serde_json::Value>) {
let user_id = auth_user let user_id = &auth_user.id;
.as_ref()
.map(|u| u.id.as_str())
.unwrap_or("anonymous");
debug!( debug!(
"Request to move folder to trash: id={}, user={}", "Request to move folder to trash: id={}, user={}",
item_id, user_id item_id, user_id
@@ -210,7 +150,7 @@ pub async fn move_folder_to_trash(
( (
StatusCode::INTERNAL_SERVER_ERROR, StatusCode::INTERNAL_SERVER_ERROR,
Json(json!({ Json(json!({
"error": format!("Error moving folder to trash: {}", e) "error": "Error moving folder to trash"
})), })),
) )
} }
@@ -271,7 +211,7 @@ pub async fn restore_from_trash(
( (
StatusCode::INTERNAL_SERVER_ERROR, StatusCode::INTERNAL_SERVER_ERROR,
Json(json!({ Json(json!({
"error": format!("Error restoring item from trash: {}", e) "error": "Error restoring item from trash"
})), })),
) )
} }
@@ -334,7 +274,7 @@ pub async fn delete_permanently(
( (
StatusCode::INTERNAL_SERVER_ERROR, StatusCode::INTERNAL_SERVER_ERROR,
Json(json!({ Json(json!({
"error": format!("Error deleting item permanently: {}", e) "error": "Error deleting item permanently"
})), })),
) )
} }
@@ -378,7 +318,7 @@ pub async fn empty_trash(
( (
StatusCode::INTERNAL_SERVER_ERROR, StatusCode::INTERNAL_SERVER_ERROR,
Json(json!({ Json(json!({
"error": format!("Error emptying trash: {}", e) "error": "Error emptying trash"
})), })),
) )
} }
@@ -394,6 +394,7 @@ pub async fn get_editor_url(
AuthUser { AuthUser {
id: user_id, id: user_id,
username, username,
..
}: AuthUser, }: AuthUser,
Query(params): Query<EditorUrlParams>, Query(params): Query<EditorUrlParams>,
State(state): State<WopiState>, State(state): State<WopiState>,
+3 -4
View File
@@ -288,10 +288,9 @@ pub fn create_api_routes(app_state: &Arc<AppState>) -> Router<Arc<AppState>> {
"/blob/{hash}", "/blob/{hash}",
get(super::handlers::dedup_handler::DedupHandler::get_blob), get(super::handlers::dedup_handler::DedupHandler::get_blob),
) )
.route( // NOTE: remove_reference is intentionally NOT exposed as a public
"/blob/{hash}", // endpoint — ref_count management is an internal concern handled
delete(super::handlers::dedup_handler::DedupHandler::remove_reference), // automatically when files are deleted via the file API.
)
.route( .route(
"/recalculate", "/recalculate",
post(super::handlers::dedup_handler::DedupHandler::recalculate_stats), post(super::handlers::dedup_handler::DedupHandler::recalculate_stats),
+23 -1
View File
@@ -22,9 +22,14 @@ pub struct AppError {
} }
/// JSON response structure for errors. /// JSON response structure for errors.
///
/// Both `error` and `message` carry the same content for backwards compatibility:
/// - Legacy ad-hoc handlers returned `{"error": "..."}` (frontend reads `.error`)
/// - AppError returned `{"message": "..."}` (admin panel reads `.message`)
#[derive(Serialize)] #[derive(Serialize)]
pub struct ErrorResponse { pub struct ErrorResponse {
pub status: String, pub status: String,
pub error: String,
pub message: String, pub message: String,
pub error_type: String, pub error_type: String,
} }
@@ -133,9 +138,26 @@ impl From<DomainError> for AppError {
impl IntoResponse for AppError { impl IntoResponse for AppError {
fn into_response(self) -> Response { fn into_response(self) -> Response {
let status = self.status_code; let status = self.status_code;
// Sanitize 500 Internal Server Error to prevent information leakage.
// Log the full error server-side for debugging, return a generic
// message to the client. Other status codes (including 5xx like
// 501, 503, 507) keep their intentionally user-facing messages.
let client_message = if status == StatusCode::INTERNAL_SERVER_ERROR {
tracing::error!(
error_type = %self.error_type,
"Internal server error: {}",
self.message
);
"An internal error occurred. Please try again later.".to_string()
} else {
self.message
};
let error_response = ErrorResponse { let error_response = ErrorResponse {
status: status.to_string(), status: status.to_string(),
message: self.message, error: client_message.clone(),
message: client_message,
error_type: self.error_type, error_type: self.error_type,
}; };
+3
View File
@@ -24,6 +24,7 @@ pub struct CookieAuthenticated;
pub struct AuthUser { pub struct AuthUser {
pub id: String, pub id: String,
pub username: String, pub username: String,
pub role: String,
} }
/// Reusable extractor that gets the user_id of the authenticated user. /// Reusable extractor that gets the user_id of the authenticated user.
@@ -50,6 +51,7 @@ where
.map(|cu| AuthUser { .map(|cu| AuthUser {
id: cu.id.clone(), id: cu.id.clone(),
username: cu.username.clone(), username: cu.username.clone(),
role: cu.role.clone(),
}) })
.ok_or(AuthError::UserNotFound) .ok_or(AuthError::UserNotFound)
} }
@@ -108,6 +110,7 @@ where
|cu| AuthUser { |cu| AuthUser {
id: cu.id.clone(), id: cu.id.clone(),
username: cu.username.clone(), username: cu.username.clone(),
role: cu.role.clone(),
}, },
))) )))
} }
+4 -6
View File
@@ -354,16 +354,14 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
app = app app = app
.layer(SetResponseHeaderLayer::overriding( .layer(SetResponseHeaderLayer::overriding(
HeaderName::from_static("content-security-policy"), HeaderName::from_static("content-security-policy"),
// NOTE: script-src includes 'unsafe-inline' because several HTML // All inline scripts and styles have been migrated to external
// pages still use inline event handlers (onclick, onsubmit) and // files, so 'unsafe-inline' is no longer needed.
// <script> blocks. TODO: migrate these to external .js files so
// 'unsafe-inline' can be removed.
// frame-src is permissive (*) to allow WOPI editor iframes whose // frame-src is permissive (*) to allow WOPI editor iframes whose
// origin is configured at runtime (Collabora, OnlyOffice, etc.). // origin is configured at runtime (Collabora, OnlyOffice, etc.).
HeaderValue::from_static( HeaderValue::from_static(
"default-src 'self'; \ "default-src 'self'; \
script-src 'self' 'unsafe-inline'; \ script-src 'self'; \
style-src 'self' 'unsafe-inline'; \ style-src 'self'; \
img-src 'self' data: blob:; \ img-src 'self' data: blob:; \
connect-src 'self'; \ connect-src 'self'; \
font-src 'self' data:; \ font-src 'self' data:; \
+18 -18
View File
@@ -4,7 +4,7 @@
<meta charset="UTF-8"> <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>OxiCloud — Admin Panel</title> <title>OxiCloud — Admin Panel</title>
<script>if(localStorage.getItem('oxicloud_theme')==='dark')document.documentElement.setAttribute('data-theme','dark');</script> <script src="/js/core/theme-init.js"></script>
<script src="/js/core/icons.js" defer></script> <script src="/js/core/icons.js" defer></script>
<script src="/js/core/formatters.js" defer></script> <script src="/js/core/formatters.js" defer></script>
<script src="/js/core/csrf.js" defer></script> <script src="/js/core/csrf.js" defer></script>
@@ -41,9 +41,9 @@
<div id="main-content"> <div id="main-content">
<div class="admin-tabs"> <div class="admin-tabs">
<button class="admin-tab active" onclick="switchTab('dashboard',this)"><i class="fas fa-chart-pie"></i> Dashboard</button> <button class="admin-tab active" id="tab-btn-dashboard"><i class="fas fa-chart-pie"></i> Dashboard</button>
<button class="admin-tab" onclick="switchTab('users',this)"><i class="fas fa-users"></i> Users</button> <button class="admin-tab" id="tab-btn-users"><i class="fas fa-users"></i> Users</button>
<button class="admin-tab" onclick="switchTab('oidc',this)"><i class="fas fa-key"></i> SSO / OIDC</button> <button class="admin-tab" id="tab-btn-oidc"><i class="fas fa-key"></i> SSO / OIDC</button>
</div> </div>
<div id="tab-dashboard" class="tab-content active"> <div id="tab-dashboard" class="tab-content active">
@@ -79,7 +79,7 @@
</div> </div>
<div class="toggle-row toggle-row-strong"> <div class="toggle-row toggle-row-strong">
<label><i class="fas fa-user-plus icon-muted-right"></i> Allow public self-registration</label> <label><i class="fas fa-user-plus icon-muted-right"></i> Allow public self-registration</label>
<label class="switch"><input type="checkbox" id="ds-registration" checked onchange="toggleRegistration(this.checked)"><span class="slider"></span></label> <label class="switch"><input type="checkbox" id="ds-registration" checked><span class="slider"></span></label>
</div> </div>
<div class="warning" id="registration-warning"><i class="fas fa-exclamation-triangle"></i> Public registration is disabled. Only admins can create new users.</div> <div class="warning" id="registration-warning"><i class="fas fa-exclamation-triangle"></i> Public registration is disabled. Only admins can create new users.</div>
</div> </div>
@@ -87,7 +87,7 @@
<div id="tab-users" class="tab-content"> <div id="tab-users" class="tab-content">
<div class="admin-card"> <div class="admin-card">
<h2 class="h2-space-between"><span><i class="fas fa-users-cog"></i> User Management</span><button class="btn btn-primary" onclick="openCreateUserModal()"><i class="fas fa-user-plus"></i> Create User</button></h2> <h2 class="h2-space-between"><span><i class="fas fa-users-cog"></i> User Management</span><button class="btn btn-primary" id="btn-create-user"><i class="fas fa-user-plus"></i> Create User</button></h2>
<div class="table-wrap"> <div class="table-wrap">
<table> <table>
<thead> <thead>
@@ -107,8 +107,8 @@
<div class="pagination"> <div class="pagination">
<span id="users-info">—</span> <span id="users-info">—</span>
<div class="flex-gap-6"> <div class="flex-gap-6">
<button class="btn btn-sm btn-secondary" id="prev-btn" onclick="prevPage()" disabled><i class="fas fa-chevron-left"></i> Prev</button> <button class="btn btn-sm btn-secondary" id="prev-btn" disabled><i class="fas fa-chevron-left"></i> Prev</button>
<button class="btn btn-sm btn-secondary" id="next-btn" onclick="nextPage()">Next <i class="fas fa-chevron-right"></i></button> <button class="btn btn-sm btn-secondary" id="next-btn">Next <i class="fas fa-chevron-right"></i></button>
</div> </div>
</div> </div>
</div> </div>
@@ -132,7 +132,7 @@
<small>OpenID Connect issuer URL of your identity provider</small> <small>OpenID Connect issuer URL of your identity provider</small>
</div> </div>
<div class="oidc-discover-wrap"> <div class="oidc-discover-wrap">
<button class="btn btn-secondary btn-sm" id="discover-btn" onclick="testConnection()"><i class="fas fa-search"></i> Auto-discover</button> <button class="btn btn-secondary btn-sm" id="discover-btn"><i class="fas fa-search"></i> Auto-discover</button>
</div> </div>
<div id="discovery-result"></div> <div id="discovery-result"></div>
<div class="form-group"> <div class="form-group">
@@ -146,7 +146,7 @@
</div> </div>
<div class="form-group"> <div class="form-group">
<label>Callback URL <small class="small-muted">(register in your IdP)</small></label> <label>Callback URL <small class="small-muted">(register in your IdP)</small></label>
<div class="readonly-field"><span id="callback-url">—</span><button onclick="copyCallback()" title="Copy"><i class="fas fa-copy"></i></button></div> <div class="readonly-field"><span id="callback-url">—</span><button id="btn-copy-callback" title="Copy"><i class="fas fa-copy"></i></button></div>
</div> </div>
<details> <details>
<summary><i class="fas fa-sliders-h summary-icon-right"></i> Advanced Settings</summary> <summary><i class="fas fa-sliders-h summary-icon-right"></i> Advanced Settings</summary>
@@ -170,8 +170,8 @@
<div class="warning" id="password-warning"><i class="fas fa-exclamation-triangle"></i> This will prevent ALL password-based logins!</div> <div class="warning" id="password-warning"><i class="fas fa-exclamation-triangle"></i> This will prevent ALL password-based logins!</div>
</details> </details>
<div class="oidc-actions"> <div class="oidc-actions">
<button class="btn btn-secondary" onclick="testConnection()"><i class="fas fa-vial"></i> Test</button> <button class="btn btn-secondary" id="btn-test-oidc"><i class="fas fa-vial"></i> Test</button>
<button class="btn btn-primary" id="save-btn" onclick="saveOidcSettings()"><i class="fas fa-save"></i> Save</button> <button class="btn btn-primary" id="save-btn"><i class="fas fa-save"></i> Save</button>
</div> </div>
<div id="oidc-status" class="alert"></div> <div id="oidc-status" class="alert"></div>
</div> </div>
@@ -195,8 +195,8 @@
<small>Set to 0 for unlimited</small> <small>Set to 0 for unlimited</small>
</div> </div>
<div class="modal-actions"> <div class="modal-actions">
<button class="btn btn-secondary" onclick="closeQuotaModal()">Cancel</button> <button class="btn btn-secondary" id="btn-close-quota">Cancel</button>
<button class="btn btn-primary" onclick="saveQuota()"><i class="fas fa-save"></i> Save</button> <button class="btn btn-primary" id="btn-save-quota"><i class="fas fa-save"></i> Save</button>
</div> </div>
</div> </div>
</div> </div>
@@ -235,8 +235,8 @@
</div> </div>
<div id="cu-error" class="alert alert-no-margin"></div> <div id="cu-error" class="alert alert-no-margin"></div>
<div class="modal-actions"> <div class="modal-actions">
<button class="btn btn-secondary" onclick="closeCreateUserModal()">Cancel</button> <button class="btn btn-secondary" id="btn-close-create-user">Cancel</button>
<button class="btn btn-primary" id="cu-submit" onclick="submitCreateUser()"><i class="fas fa-user-plus"></i> Create</button> <button class="btn btn-primary" id="cu-submit"><i class="fas fa-user-plus"></i> Create</button>
</div> </div>
</div> </div>
</div> </div>
@@ -253,8 +253,8 @@
</div> </div>
<div id="rp-error" class="alert alert-no-margin"></div> <div id="rp-error" class="alert alert-no-margin"></div>
<div class="modal-actions"> <div class="modal-actions">
<button class="btn btn-secondary" onclick="closeResetPasswordModal()">Cancel</button> <button class="btn btn-secondary" id="btn-close-reset-pw">Cancel</button>
<button class="btn btn-primary" id="rp-submit" onclick="submitResetPassword()"><i class="fas fa-save"></i> Reset</button> <button class="btn btn-primary" id="rp-submit"><i class="fas fa-save"></i> Reset</button>
</div> </div>
</div> </div>
</div> </div>
+2
View File
@@ -20,3 +20,5 @@ html[dir='rtl'] .fa-sign-out-alt {
-webkit-transform: rotate(180deg); -webkit-transform: rotate(180deg);
transform: rotate(180deg); transform: rotate(180deg);
} }
/* Utility: hide elements without inline style="" (CSP-safe) */
.hidden { display: none; }
+5
View File
@@ -40,6 +40,11 @@
display: none; display: none;
} }
.dropzone-icon {
font-size: 32px;
margin-bottom: 10px;
}
.dropzone.active { .dropzone.active {
border-color: #ff5e3a; border-color: #ff5e3a;
background-color: rgba(255, 94, 58, 0.05); background-color: rgba(255, 94, 58, 0.05);
+5
View File
@@ -95,3 +95,8 @@
[data-theme="dark"] .upload-dropdown-item i { [data-theme="dark"] .upload-dropdown-item i {
color: #94a3b8; color: #94a3b8;
} }
.upload-caret {
margin-left: 4px;
font-size: 12px;
}
+2
View File
@@ -61,6 +61,8 @@
align-items: center; align-items: center;
border-bottom: 1px solid rgba(255,255,255,0.07); border-bottom: 1px solid rgba(255,255,255,0.07);
margin-bottom: 8px; margin-bottom: 8px;
text-decoration: none;
color: inherit;
} }
.logo { .logo {
+89
View File
@@ -0,0 +1,89 @@
/* device-verify.css — stand-alone styles for the device authorization page */
:root {
--primary: #2563eb;
--primary-hover: #1d4ed8;
--danger: #dc2626;
--danger-hover: #b91c1c;
--success: #16a34a;
--bg: #f8fafc;
--card: #ffffff;
--text: #1e293b;
--muted: #64748b;
--border: #e2e8f0;
--radius: 12px;
}
* { box-sizing: border-box; margin: 0; padding: 0; }
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
background: var(--bg);
color: var(--text);
display: flex;
justify-content: center;
align-items: center;
min-height: 100vh;
padding: 1rem;
}
.card {
background: var(--card);
border-radius: var(--radius);
box-shadow: 0 4px 24px rgba(0,0,0,0.08);
padding: 2.5rem;
max-width: 440px;
width: 100%;
}
.logo { text-align: center; margin-bottom: 1.5rem; }
.logo h1 { font-size: 1.5rem; font-weight: 700; }
.logo span { color: var(--primary); }
h2 { font-size: 1.15rem; margin-bottom: 0.5rem; }
p.subtitle { color: var(--muted); font-size: 0.9rem; margin-bottom: 1.5rem; }
label { display: block; font-weight: 600; font-size: 0.85rem; margin-bottom: 0.4rem; }
input[type="text"] {
width: 100%;
padding: 0.75rem 1rem;
font-size: 1.4rem;
letter-spacing: 0.15em;
text-align: center;
text-transform: uppercase;
border: 2px solid var(--border);
border-radius: 8px;
outline: none;
transition: border-color 0.2s;
}
input[type="text"]:focus { border-color: var(--primary); }
.device-info {
background: #f1f5f9;
border-radius: 8px;
padding: 1rem;
margin: 1rem 0;
}
.device-info .row { display: flex; justify-content: space-between; margin-bottom: 0.3rem; }
.device-info .label { color: var(--muted); font-size: 0.85rem; }
.device-info .value { font-weight: 600; font-size: 0.85rem; }
.actions { display: flex; gap: 0.75rem; margin-top: 1.25rem; }
button {
flex: 1;
padding: 0.75rem;
border: none;
border-radius: 8px;
font-size: 0.95rem;
font-weight: 600;
cursor: pointer;
transition: background 0.2s;
}
.btn-approve { background: var(--primary); color: #fff; }
.btn-approve:hover { background: var(--primary-hover); }
.btn-deny { background: var(--danger); color: #fff; }
.btn-deny:hover { background: var(--danger-hover); }
button:disabled { opacity: 0.5; cursor: not-allowed; }
.status {
text-align: center;
padding: 1rem;
border-radius: 8px;
margin-top: 1rem;
font-weight: 600;
}
.status.success { background: #dcfce7; color: var(--success); }
.status.denied { background: #fef2f2; color: var(--danger); }
.status.error { background: #fef2f2; color: var(--danger); }
.error-text { color: var(--danger); font-size: 0.85rem; margin-top: 0.5rem; }
.hidden { display: none !important; }
+10 -201
View File
@@ -4,97 +4,7 @@
<meta charset="UTF-8"> <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>OxiCloud — Authorize Device</title> <title>OxiCloud — Authorize Device</title>
<style> <link rel="stylesheet" href="/css/views/device-verify.css">
:root {
--primary: #2563eb;
--primary-hover: #1d4ed8;
--danger: #dc2626;
--danger-hover: #b91c1c;
--success: #16a34a;
--bg: #f8fafc;
--card: #ffffff;
--text: #1e293b;
--muted: #64748b;
--border: #e2e8f0;
--radius: 12px;
}
* { box-sizing: border-box; margin: 0; padding: 0; }
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
background: var(--bg);
color: var(--text);
display: flex;
justify-content: center;
align-items: center;
min-height: 100vh;
padding: 1rem;
}
.card {
background: var(--card);
border-radius: var(--radius);
box-shadow: 0 4px 24px rgba(0,0,0,0.08);
padding: 2.5rem;
max-width: 440px;
width: 100%;
}
.logo { text-align: center; margin-bottom: 1.5rem; }
.logo h1 { font-size: 1.5rem; font-weight: 700; }
.logo span { color: var(--primary); }
h2 { font-size: 1.15rem; margin-bottom: 0.5rem; }
p.subtitle { color: var(--muted); font-size: 0.9rem; margin-bottom: 1.5rem; }
label { display: block; font-weight: 600; font-size: 0.85rem; margin-bottom: 0.4rem; }
input[type="text"] {
width: 100%;
padding: 0.75rem 1rem;
font-size: 1.4rem;
letter-spacing: 0.15em;
text-align: center;
text-transform: uppercase;
border: 2px solid var(--border);
border-radius: 8px;
outline: none;
transition: border-color 0.2s;
}
input[type="text"]:focus { border-color: var(--primary); }
.device-info {
background: #f1f5f9;
border-radius: 8px;
padding: 1rem;
margin: 1rem 0;
display: none;
}
.device-info .row { display: flex; justify-content: space-between; margin-bottom: 0.3rem; }
.device-info .label { color: var(--muted); font-size: 0.85rem; }
.device-info .value { font-weight: 600; font-size: 0.85rem; }
.actions { display: flex; gap: 0.75rem; margin-top: 1.25rem; }
button {
flex: 1;
padding: 0.75rem;
border: none;
border-radius: 8px;
font-size: 0.95rem;
font-weight: 600;
cursor: pointer;
transition: background 0.2s;
}
.btn-approve { background: var(--primary); color: #fff; }
.btn-approve:hover { background: var(--primary-hover); }
.btn-deny { background: var(--danger); color: #fff; }
.btn-deny:hover { background: var(--danger-hover); }
button:disabled { opacity: 0.5; cursor: not-allowed; }
.status {
text-align: center;
padding: 1rem;
border-radius: 8px;
margin-top: 1rem;
font-weight: 600;
display: none;
}
.status.success { display: block; background: #dcfce7; color: var(--success); }
.status.denied { display: block; background: #fef2f2; color: var(--danger); }
.status.error { display: block; background: #fef2f2; color: var(--danger); }
.error-text { color: var(--danger); font-size: 0.85rem; margin-top: 0.5rem; display: none; }
</style>
</head> </head>
<body> <body>
<div class="card"> <div class="card">
@@ -108,9 +18,9 @@
<p class="subtitle">Enter the code displayed on your WebDAV/CalDAV client to grant access.</p> <p class="subtitle">Enter the code displayed on your WebDAV/CalDAV client to grant access.</p>
<label for="user-code">Device Code</label> <label for="user-code">Device Code</label>
<input type="text" id="user-code" placeholder="ABCD-1234" maxlength="9" autocomplete="off" autofocus /> <input type="text" id="user-code" placeholder="ABCD-1234" maxlength="9" autocomplete="off" autofocus />
<div id="error-text" class="error-text"></div> <div id="error-text" class="error-text hidden"></div>
<div id="device-info" class="device-info"> <div id="device-info" class="device-info hidden">
<div class="row"> <div class="row">
<span class="label">Client</span> <span class="label">Client</span>
<span class="value" id="info-client">—</span> <span class="value" id="info-client">—</span>
@@ -121,124 +31,23 @@
</div> </div>
</div> </div>
<div class="actions" id="action-buttons" style="display:none;"> <div class="actions hidden" id="action-buttons">
<button class="btn-deny" id="btn-deny" onclick="handleAction('deny')">Deny</button> <button class="btn-deny" id="btn-deny">Deny</button>
<button class="btn-approve" id="btn-approve" onclick="handleAction('approve')">Approve</button> <button class="btn-approve" id="btn-approve">Approve</button>
</div> </div>
</div> </div>
<!-- Step 2: Result --> <!-- Step 2: Result -->
<div id="status-success" class="status success"> <div id="status-success" class="status success hidden">
Device authorized successfully! You can close this page. Device authorized successfully! You can close this page.
</div> </div>
<div id="status-denied" class="status denied"> <div id="status-denied" class="status denied hidden">
Authorization denied. The client will not receive access. Authorization denied. The client will not receive access.
</div> </div>
<div id="status-error" class="status error" id="status-error-msg"></div> <div id="status-error" class="status error hidden"></div>
</div> </div>
<script src="/js/core/csrf.js"></script> <script src="/js/core/csrf.js"></script>
<script> <script src="/js/views/device-verify/device-verify.js"></script>
const API_BASE = window.location.origin;
const codeInput = document.getElementById('user-code');
const deviceInfo = document.getElementById('device-info');
const actionButtons = document.getElementById('action-buttons');
const errorText = document.getElementById('error-text');
let debounceTimer = null;
let currentCode = '';
// Pre-fill from URL query param (?code=ABCD-1234)
const params = new URLSearchParams(window.location.search);
if (params.get('code')) {
codeInput.value = params.get('code');
lookupCode(params.get('code'));
}
// Auto-insert hyphen and lookup on input
codeInput.addEventListener('input', (e) => {
let val = e.target.value.toUpperCase().replace(/[^A-Z0-9\-]/g, '');
// Auto-insert hyphen after 4 chars
if (val.length === 4 && !val.includes('-')) {
val = val + '-';
}
e.target.value = val;
errorText.style.display = 'none';
// Debounce lookup
clearTimeout(debounceTimer);
if (val.length >= 9) {
debounceTimer = setTimeout(() => lookupCode(val), 300);
} else {
deviceInfo.style.display = 'none';
actionButtons.style.display = 'none';
}
});
async function lookupCode(code) {
try {
const resp = await fetch(`${API_BASE}/api/auth/device/verify?code=${encodeURIComponent(code)}`, {
credentials: 'same-origin'
});
if (resp.status === 401) {
showError('You must be logged in to authorize a device. Please log in first.');
return;
}
if (!resp.ok) throw new Error('Lookup failed');
const data = await resp.json();
if (data.valid) {
currentCode = code;
document.getElementById('info-client').textContent = data.client_name || 'Unknown';
document.getElementById('info-scopes').textContent = data.scopes || 'all';
deviceInfo.style.display = 'block';
actionButtons.style.display = 'flex';
errorText.style.display = 'none';
} else {
deviceInfo.style.display = 'none';
actionButtons.style.display = 'none';
showError('Code not found or expired. Please check and try again.');
}
} catch (err) {
showError('Failed to verify code. Please try again.');
}
}
async function handleAction(action) {
const btnApprove = document.getElementById('btn-approve');
const btnDeny = document.getElementById('btn-deny');
btnApprove.disabled = true;
btnDeny.disabled = true;
try {
const resp = await fetch(`${API_BASE}/api/auth/device/verify`, {
method: 'POST',
credentials: 'same-origin',
headers: { 'Content-Type': 'application/json', ...getCsrfHeaders() },
body: JSON.stringify({ user_code: currentCode, action: action })
});
if (!resp.ok) {
const err = await resp.json().catch(() => ({}));
throw new Error(err.message || 'Action failed');
}
document.getElementById('step-code').style.display = 'none';
if (action === 'approve') {
document.getElementById('status-success').style.display = 'block';
} else {
document.getElementById('status-denied').style.display = 'block';
}
} catch (err) {
btnApprove.disabled = false;
btnDeny.disabled = false;
showError(err.message || 'Failed to process action.');
}
}
function showError(msg) {
errorText.textContent = msg;
errorText.style.display = 'block';
}
</script>
</body> </body>
</html> </html>
+13 -21
View File
@@ -5,7 +5,7 @@
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="viewport" content="width=device-width, initial-scale=1.0">
<title data-i18n="app.title">OxiCloud</title> <title data-i18n="app.title">OxiCloud</title>
<!-- Apply saved theme immediately to prevent flash of light mode --> <!-- Apply saved theme immediately to prevent flash of light mode -->
<script>if(localStorage.getItem('oxicloud_theme')==='dark')document.documentElement.setAttribute('data-theme','dark');</script> <script src="/js/core/theme-init.js"></script>
<!-- Styles --> <!-- Styles -->
<link rel="stylesheet" href="/css/main.css"> <link rel="stylesheet" href="/css/main.css">
@@ -47,22 +47,14 @@
<script defer src="/js/app/bootstrap.js"></script> <script defer src="/js/app/bootstrap.js"></script>
<!-- Service Worker Registration --> <!-- Service Worker Registration -->
<script> <script defer src="/js/core/sw-register.js"></script>
if ('serviceWorker' in navigator) {
window.addEventListener('load', () => {
navigator.serviceWorker.register('/sw.js')
.then(reg => console.log('Service Worker registered successfully'))
.catch(err => console.log('Service Worker registration failed:', err));
});
}
</script>
</head> </head>
<body> <body>
<!-- Mobile sidebar overlay --> <!-- Mobile sidebar overlay -->
<div class="sidebar-overlay" id="sidebar-overlay"></div> <div class="sidebar-overlay" id="sidebar-overlay"></div>
<!-- Sidebar --> <!-- Sidebar -->
<div class="sidebar" id="sidebar"> <div class="sidebar" id="sidebar">
<a href="/" class="logo-container" style="text-decoration:none;color:inherit;"> <a href="/" class="logo-container">
<div class="logo"> <div class="logo">
<svg viewBox="0 0 500 500"> <svg viewBox="0 0 500 500">
@@ -127,7 +119,7 @@
<div class="notif-wrapper" id="notif-wrapper"> <div class="notif-wrapper" id="notif-wrapper">
<button class="notif-bell-btn" id="notif-bell-btn" title="Notifications"> <button class="notif-bell-btn" id="notif-bell-btn" title="Notifications">
<i class="fas fa-bell"></i> <i class="fas fa-bell"></i>
<span class="notif-badge" id="notif-badge" style="display:none">0</span> <span class="notif-badge hidden" id="notif-badge">0</span>
</button> </button>
<div class="notif-panel" id="notif-panel"> <div class="notif-panel" id="notif-panel">
<div class="notif-panel-header"> <div class="notif-panel-header">
@@ -157,7 +149,7 @@
<div class="user-menu-email" id="user-menu-email">user@oxicloud.app</div> <div class="user-menu-email" id="user-menu-email">user@oxicloud.app</div>
</div> </div>
</div> </div>
<div class="user-menu-role-badge" id="user-menu-role-badge" style="display:none"> <div class="user-menu-role-badge hidden" id="user-menu-role-badge">
<span class="role-badge role-badge-admin"><i class="fas fa-shield-alt"></i> Admin</span> <span class="role-badge role-badge-admin"><i class="fas fa-shield-alt"></i> Admin</span>
</div> </div>
<div class="user-menu-storage"> <div class="user-menu-storage">
@@ -171,7 +163,7 @@
<div class="user-menu-storage-text" id="user-menu-storage-text">0% used</div> <div class="user-menu-storage-text" id="user-menu-storage-text">0% used</div>
</div> </div>
<div class="user-menu-divider"></div> <div class="user-menu-divider"></div>
<button class="user-menu-item user-menu-admin" id="user-menu-admin" style="display:none"> <button class="user-menu-item user-menu-admin hidden" id="user-menu-admin">
<i class="fas fa-cogs"></i> <i class="fas fa-cogs"></i>
<span data-i18n="user_menu.admin_panel">Admin panel</span> <span data-i18n="user_menu.admin_panel">Admin panel</span>
</button> </button>
@@ -179,7 +171,7 @@
<i class="fas fa-user-circle"></i> <i class="fas fa-user-circle"></i>
<span data-i18n="user_menu.profile">My profile</span> <span data-i18n="user_menu.profile">My profile</span>
</button> </button>
<div class="user-menu-divider" id="user-menu-admin-divider" style="display:none"></div> <div class="user-menu-divider hidden" id="user-menu-admin-divider"></div>
<button class="user-menu-item" id="user-menu-theme"> <button class="user-menu-item" id="user-menu-theme">
<i class="fas fa-moon"></i> <i class="fas fa-moon"></i>
<span data-i18n="user_menu.appearance">Appearance</span> <span data-i18n="user_menu.appearance">Appearance</span>
@@ -210,7 +202,7 @@
<button class="btn btn-primary" id="upload-btn"> <button class="btn btn-primary" id="upload-btn">
<i class="fas fa-cloud-upload-alt"></i> <i class="fas fa-cloud-upload-alt"></i>
<span data-i18n="actions.upload">Upload</span> <span data-i18n="actions.upload">Upload</span>
<i class="fas fa-caret-down" style="margin-left: 4px; font-size: 12px;"></i> <i class="fas fa-caret-down upload-caret"></i>
</button> </button>
<div class="upload-dropdown-menu" id="upload-dropdown-menu"> <div class="upload-dropdown-menu" id="upload-dropdown-menu">
<button class="upload-dropdown-item" id="upload-files-btn"> <button class="upload-dropdown-item" id="upload-files-btn">
@@ -240,10 +232,10 @@
</div> </div>
<div class="dropzone" id="dropzone"> <div class="dropzone" id="dropzone">
<i class="fas fa-cloud-upload-alt" style="font-size: 32px; margin-bottom: 10px;"></i> <i class="fas fa-cloud-upload-alt dropzone-icon"></i>
<p data-i18n="dropzone.drag_files">Drag files here or click to select</p> <p data-i18n="dropzone.drag_files">Drag files here or click to select</p>
<input type="file" id="file-input" style="display: none;" multiple> <input type="file" id="file-input" class="hidden" multiple>
<input type="file" id="folder-input" style="display: none;" webkitdirectory directory multiple> <input type="file" id="folder-input" class="hidden" webkitdirectory directory multiple>
<div class="upload-progress"> <div class="upload-progress">
<div class="progress-bar"> <div class="progress-bar">
<div class="progress-fill"></div> <div class="progress-fill"></div>
@@ -263,7 +255,7 @@
</div> </div>
<!-- List View (hidden by default) --> <!-- List View (hidden by default) -->
<div class="files-list-view" id="files-list-view" style="display: none;"> <div class="files-list-view hidden" id="files-list-view">
<div class="list-header"> <div class="list-header">
<div class="list-header-checkbox"><input type="checkbox" id="select-all-checkbox" title="Select all"></div> <div class="list-header-checkbox"><input type="checkbox" id="select-all-checkbox" title="Select all"></div>
<div data-i18n="files.name">Name</div> <div data-i18n="files.name">Name</div>
@@ -330,6 +322,6 @@
</div> </div>
<!-- Upload Progress Toast (hidden – driven by notification bell) --> <!-- Upload Progress Toast (hidden – driven by notification bell) -->
<div class="upload-toast" id="upload-toast" style="display:none"></div> <div class="upload-toast hidden" id="upload-toast"></div>
</body> </body>
</html> </html>
+8
View File
@@ -0,0 +1,8 @@
// Service Worker registration — runs after page load.
if ('serviceWorker' in navigator) {
window.addEventListener('load', function () {
navigator.serviceWorker.register('/sw.js')
.then(function () { /* registered */ })
.catch(function (err) { console.log('Service Worker registration failed:', err); });
});
}
+3
View File
@@ -0,0 +1,3 @@
// Apply saved theme immediately (render-blocking) to prevent FOUC.
// This file MUST be loaded without "defer" or "async".
if(localStorage.getItem('oxicloud_theme')==='dark')document.documentElement.setAttribute('data-theme','dark');
+25
View File
@@ -407,3 +407,28 @@ function showAccessDenied() {
} }
init(); init();
/* ── Event-listener wiring (replaces inline onclick/onchange) ── */
document.getElementById('tab-btn-dashboard').addEventListener('click', function(){ switchTab('dashboard', this); });
document.getElementById('tab-btn-users').addEventListener('click', function(){ switchTab('users', this); });
document.getElementById('tab-btn-oidc').addEventListener('click', function(){ switchTab('oidc', this); });
document.getElementById('ds-registration').addEventListener('change', function(){ toggleRegistration(this.checked); });
document.getElementById('btn-create-user').addEventListener('click', openCreateUserModal);
document.getElementById('prev-btn').addEventListener('click', prevPage);
document.getElementById('next-btn').addEventListener('click', nextPage);
document.getElementById('discover-btn').addEventListener('click', testConnection);
document.getElementById('btn-copy-callback').addEventListener('click', copyCallback);
document.getElementById('btn-test-oidc').addEventListener('click', testConnection);
document.getElementById('save-btn').addEventListener('click', saveOidcSettings);
document.getElementById('btn-close-quota').addEventListener('click', closeQuotaModal);
document.getElementById('btn-save-quota').addEventListener('click', saveQuota);
document.getElementById('btn-close-create-user').addEventListener('click', closeCreateUserModal);
document.getElementById('cu-submit').addEventListener('click', submitCreateUser);
document.getElementById('btn-close-reset-pw').addEventListener('click', closeResetPasswordModal);
document.getElementById('rp-submit').addEventListener('click', submitResetPassword);
@@ -0,0 +1,109 @@
// device-verify.js — Extracted from inline <script> in device-verify.html
(function () {
'use strict';
var API_BASE = window.location.origin;
var codeInput = document.getElementById('user-code');
var deviceInfo = document.getElementById('device-info');
var actionButtons = document.getElementById('action-buttons');
var errorText = document.getElementById('error-text');
var btnApprove = document.getElementById('btn-approve');
var btnDeny = document.getElementById('btn-deny');
var debounceTimer = null;
var currentCode = '';
// Pre-fill from URL query param (?code=ABCD-1234)
var params = new URLSearchParams(window.location.search);
if (params.get('code')) {
codeInput.value = params.get('code');
lookupCode(params.get('code'));
}
// Auto-insert hyphen and lookup on input
codeInput.addEventListener('input', function (e) {
var val = e.target.value.toUpperCase().replace(/[^A-Z0-9\-]/g, '');
// Auto-insert hyphen after 4 chars
if (val.length === 4 && val.indexOf('-') === -1) {
val = val + '-';
}
e.target.value = val;
errorText.classList.add('hidden');
// Debounce lookup
clearTimeout(debounceTimer);
if (val.length >= 9) {
debounceTimer = setTimeout(function () { lookupCode(val); }, 300);
} else {
deviceInfo.classList.add('hidden');
actionButtons.classList.add('hidden');
}
});
// Wire up approve / deny buttons (replaces inline onclick)
btnApprove.addEventListener('click', function () { handleAction('approve'); });
btnDeny.addEventListener('click', function () { handleAction('deny'); });
async function lookupCode(code) {
try {
var resp = await fetch(API_BASE + '/api/auth/device/verify?code=' + encodeURIComponent(code), {
credentials: 'same-origin'
});
if (resp.status === 401) {
showError('You must be logged in to authorize a device. Please log in first.');
return;
}
if (!resp.ok) throw new Error('Lookup failed');
var data = await resp.json();
if (data.valid) {
currentCode = code;
document.getElementById('info-client').textContent = data.client_name || 'Unknown';
document.getElementById('info-scopes').textContent = data.scopes || 'all';
deviceInfo.classList.remove('hidden');
actionButtons.classList.remove('hidden');
errorText.classList.add('hidden');
} else {
deviceInfo.classList.add('hidden');
actionButtons.classList.add('hidden');
showError('Code not found or expired. Please check and try again.');
}
} catch (_err) {
showError('Failed to verify code. Please try again.');
}
}
async function handleAction(action) {
btnApprove.disabled = true;
btnDeny.disabled = true;
try {
var resp = await fetch(API_BASE + '/api/auth/device/verify', {
method: 'POST',
credentials: 'same-origin',
headers: Object.assign({ 'Content-Type': 'application/json' }, getCsrfHeaders()),
body: JSON.stringify({ user_code: currentCode, action: action })
});
if (!resp.ok) {
var err = await resp.json().catch(function () { return {}; });
throw new Error(err.message || 'Action failed');
}
document.getElementById('step-code').classList.add('hidden');
if (action === 'approve') {
document.getElementById('status-success').classList.remove('hidden');
} else {
document.getElementById('status-denied').classList.remove('hidden');
}
} catch (err) {
btnApprove.disabled = false;
btnDeny.disabled = false;
showError(err.message || 'Failed to process action.');
}
}
function showError(msg) {
errorText.textContent = msg;
errorText.classList.remove('hidden');
}
})();
+3
View File
@@ -134,3 +134,6 @@ async function changePassword(e) {
} }
init(); init();
/* Wire up form handler (replaces inline onsubmit) */
document.getElementById('password-form').addEventListener('submit', changePassword);
+5 -5
View File
@@ -5,7 +5,7 @@
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="viewport" content="width=device-width, initial-scale=1.0">
<title data-i18n="app.title">OxiCloud - Login</title> <title data-i18n="app.title">OxiCloud - Login</title>
<!-- Apply saved theme immediately to prevent flash of light mode --> <!-- Apply saved theme immediately to prevent flash of light mode -->
<script>if(localStorage.getItem('oxicloud_theme')==='dark')document.documentElement.setAttribute('data-theme','dark');</script> <script src="/js/core/theme-init.js"></script>
<!-- Styles --> <!-- Styles -->
<link rel="stylesheet" href="/css/main.css"> <link rel="stylesheet" href="/css/main.css">
@@ -20,7 +20,7 @@
<body> <body>
<div class="auth-container"> <div class="auth-container">
<!-- Language Selector Panel - Shown first on fresh install --> <!-- Language Selector Panel - Shown first on fresh install -->
<div class="auth-panel language-selector-panel" id="language-panel" style="display: none;"> <div class="auth-panel language-selector-panel hidden" id="language-panel">
<div class="auth-logo"> <div class="auth-logo">
<div class="auth-logo-icon"> <div class="auth-logo-icon">
<svg viewBox="0 0 500 500"> <svg viewBox="0 0 500 500">
@@ -54,7 +54,7 @@
<button type="button" class="auth-button" id="language-continue">Continue</button> <button type="button" class="auth-button" id="language-continue">Continue</button>
</div> </div>
<div class="auth-panel" id="login-panel" style="display: none;"> <div class="auth-panel hidden" id="login-panel">
<div class="auth-logo"> <div class="auth-logo">
<div class="auth-logo-icon"> <div class="auth-logo-icon">
<svg viewBox="0 0 500 500"> <svg viewBox="0 0 500 500">
@@ -97,7 +97,7 @@
</form> </form>
<!-- SSO / OIDC login section (hidden by default, shown dynamically) --> <!-- SSO / OIDC login section (hidden by default, shown dynamically) -->
<div id="oidc-login-section" style="display: none;"> <div id="oidc-login-section" class="hidden">
<div class="auth-divider" id="auth-divider"> <div class="auth-divider" id="auth-divider">
<span data-i18n="auth.or">or</span> <span data-i18n="auth.or">or</span>
</div> </div>
@@ -118,7 +118,7 @@
</div> </div>
</div> </div>
<div class="auth-panel" id="register-panel" style="display: none;"> <div class="auth-panel hidden" id="register-panel">
<div class="auth-logo"> <div class="auth-logo">
<div class="auth-logo-icon"> <div class="auth-logo-icon">
<svg viewBox="0 0 500 500"> <svg viewBox="0 0 500 500">
+2 -2
View File
@@ -4,7 +4,7 @@
<meta charset="UTF-8"> <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>OxiCloud — My Profile</title> <title>OxiCloud — My Profile</title>
<script>if(localStorage.getItem('oxicloud_theme')==='dark')document.documentElement.setAttribute('data-theme','dark');</script> <script src="/js/core/theme-init.js"></script>
<script src="/js/core/icons.js" defer></script> <script src="/js/core/icons.js" defer></script>
<script src="/js/core/csrf.js" defer></script> <script src="/js/core/csrf.js" defer></script>
<link rel="stylesheet" href="/css/main.css"> <link rel="stylesheet" href="/css/main.css">
@@ -96,7 +96,7 @@
<div class="profile-card" id="password-section"> <div class="profile-card" id="password-section">
<h2><i class="fas fa-key"></i> Change Password</h2> <h2><i class="fas fa-key"></i> Change Password</h2>
<form id="password-form" onsubmit="return changePassword(event)"> <form id="password-form">
<div class="form-group"> <div class="form-group">
<label for="current-password">Current Password</label> <label for="current-password">Current Password</label>
<input type="password" id="current-password" required autocomplete="current-password"> <input type="password" id="current-password" required autocomplete="current-password">