style: cargo fmt --all

This commit is contained in:
Dionisio
2026-03-03 01:49:18 +01:00
parent 1df52fd702
commit efcf88c4d7
29 changed files with 2754 additions and 2732 deletions
+15 -29
View File
@@ -351,27 +351,23 @@ impl CalDavAdapter {
username
))))?;
xml_writer.write_event(Event::End(BytesEnd::new("D:href")))?;
xml_writer
.write_event(Event::End(BytesEnd::new("D:current-user-principal")))?;
xml_writer.write_event(Event::End(BytesEnd::new("D:current-user-principal")))?;
// calendar-home-set
xml_writer
.write_event(Event::Start(BytesStart::new("C:calendar-home-set")))?;
xml_writer.write_event(Event::Start(BytesStart::new("C:calendar-home-set")))?;
xml_writer.write_event(Event::Start(BytesStart::new("D:href")))?;
xml_writer.write_event(Event::Text(BytesText::new(&format!(
"/caldav/{}/",
username
))))?;
xml_writer.write_event(Event::End(BytesEnd::new("D:href")))?;
xml_writer
.write_event(Event::End(BytesEnd::new("C:calendar-home-set")))?;
xml_writer.write_event(Event::End(BytesEnd::new("C:calendar-home-set")))?;
}
PropFindType::PropName => {
xml_writer.write_event(Event::Empty(BytesStart::new("D:resourcetype")))?;
xml_writer
.write_event(Event::Empty(BytesStart::new("D:current-user-principal")))?;
xml_writer
.write_event(Event::Empty(BytesStart::new("C:calendar-home-set")))?;
xml_writer.write_event(Event::Empty(BytesStart::new("C:calendar-home-set")))?;
}
PropFindType::Prop(props) => {
Self::write_root_requested_props(xml_writer, username, props)?;
@@ -404,9 +400,8 @@ impl CalDavAdapter {
xml_writer.write_event(Event::End(BytesEnd::new("D:resourcetype")))?;
}
("DAV:", "current-user-principal") => {
xml_writer.write_event(Event::Start(BytesStart::new(
"D:current-user-principal",
)))?;
xml_writer
.write_event(Event::Start(BytesStart::new("D:current-user-principal")))?;
xml_writer.write_event(Event::Start(BytesStart::new("D:href")))?;
xml_writer.write_event(Event::Text(BytesText::new(&format!(
"/caldav/principals/{}/",
@@ -417,16 +412,14 @@ impl CalDavAdapter {
.write_event(Event::End(BytesEnd::new("D:current-user-principal")))?;
}
("urn:ietf:params:xml:ns:caldav", "calendar-home-set") => {
xml_writer
.write_event(Event::Start(BytesStart::new("C:calendar-home-set")))?;
xml_writer.write_event(Event::Start(BytesStart::new("C:calendar-home-set")))?;
xml_writer.write_event(Event::Start(BytesStart::new("D:href")))?;
xml_writer.write_event(Event::Text(BytesText::new(&format!(
"/caldav/{}/",
username
))))?;
xml_writer.write_event(Event::End(BytesEnd::new("D:href")))?;
xml_writer
.write_event(Event::End(BytesEnd::new("C:calendar-home-set")))?;
xml_writer.write_event(Event::End(BytesEnd::new("C:calendar-home-set")))?;
}
("DAV:", "displayname") => {
xml_writer.write_event(Event::Start(BytesStart::new("D:displayname")))?;
@@ -452,10 +445,7 @@ impl CalDavAdapter {
}
/// Write standard properties for a principal resource.
fn write_principal_props<W: Write>(
xml_writer: &mut Writer<W>,
username: &str,
) -> Result<()> {
fn write_principal_props<W: Write>(xml_writer: &mut Writer<W>, username: &str) -> Result<()> {
// resourcetype — principal
xml_writer.write_event(Event::Start(BytesStart::new("D:resourcetype")))?;
xml_writer.write_event(Event::Empty(BytesStart::new("D:collection")))?;
@@ -510,9 +500,8 @@ impl CalDavAdapter {
xml_writer.write_event(Event::End(BytesEnd::new("D:displayname")))?;
}
("DAV:", "current-user-principal") => {
xml_writer.write_event(Event::Start(BytesStart::new(
"D:current-user-principal",
)))?;
xml_writer
.write_event(Event::Start(BytesStart::new("D:current-user-principal")))?;
xml_writer.write_event(Event::Start(BytesStart::new("D:href")))?;
xml_writer.write_event(Event::Text(BytesText::new(&format!(
"/caldav/principals/{}/",
@@ -523,16 +512,14 @@ impl CalDavAdapter {
.write_event(Event::End(BytesEnd::new("D:current-user-principal")))?;
}
("urn:ietf:params:xml:ns:caldav", "calendar-home-set") => {
xml_writer
.write_event(Event::Start(BytesStart::new("C:calendar-home-set")))?;
xml_writer.write_event(Event::Start(BytesStart::new("C:calendar-home-set")))?;
xml_writer.write_event(Event::Start(BytesStart::new("D:href")))?;
xml_writer.write_event(Event::Text(BytesText::new(&format!(
"/caldav/{}/",
username
))))?;
xml_writer.write_event(Event::End(BytesEnd::new("D:href")))?;
xml_writer
.write_event(Event::End(BytesEnd::new("C:calendar-home-set")))?;
xml_writer.write_event(Event::End(BytesEnd::new("C:calendar-home-set")))?;
}
("urn:ietf:params:xml:ns:caldav", "calendar-user-address-set") => {
xml_writer.write_event(Event::Start(BytesStart::new(
@@ -544,9 +531,8 @@ impl CalDavAdapter {
username
))))?;
xml_writer.write_event(Event::End(BytesEnd::new("D:href")))?;
xml_writer.write_event(Event::End(BytesEnd::new(
"C:calendar-user-address-set",
)))?;
xml_writer
.write_event(Event::End(BytesEnd::new("C:calendar-user-address-set")))?;
}
_ => {
let prop_name = if prop.namespace == "http://calendarserver.org/ns/" {
+13 -11
View File
@@ -356,7 +356,11 @@ mod tests {
</D:propfind>"#;
let result = WebDavAdapter::parse_propfind(Cursor::new(xml));
assert!(result.is_ok(), "Failed to parse PROPFIND: {:?}", result.err());
assert!(
result.is_ok(),
"Failed to parse PROPFIND: {:?}",
result.err()
);
let request = result.unwrap();
match request.prop_find_type {
@@ -431,7 +435,11 @@ mod tests {
"/caldav/",
"testuser",
);
assert!(result.is_ok(), "Failed to generate root propfind: {:?}", result.err());
assert!(
result.is_ok(),
"Failed to generate root propfind: {:?}",
result.err()
);
let xml_str = String::from_utf8(output).expect("Invalid UTF-8");
@@ -511,11 +519,8 @@ mod tests {
};
let mut output = Vec::new();
let result = CalDavAdapter::generate_principal_propfind_response(
&mut output,
&request,
"testuser",
);
let result =
CalDavAdapter::generate_principal_propfind_response(&mut output, &request, "testuser");
assert!(result.is_ok(), "Failed: {:?}", result.err());
let xml_str = String::from_utf8(output).expect("Invalid UTF-8");
@@ -576,10 +581,7 @@ mod tests {
);
// displayname should be populated
assert!(
xml_str.contains("Personal"),
"Should contain calendar name"
);
assert!(xml_str.contains("Personal"), "Should contain calendar name");
// supported-calendar-component-set should have VEVENT
assert!(
@@ -132,9 +132,9 @@ impl AppPasswordService {
let password_hash = self.hasher.hash_password(&plain_token).await?;
// Calculate expiration
let expires_at = request.expires_in_days.map(|days| {
Utc::now() + Duration::days(days as i64)
});
let expires_at = request
.expires_in_days
.map(|days| Utc::now() + Duration::days(days as i64));
// Create entity
let app_password = AppPassword::new(
@@ -148,9 +148,7 @@ impl AppPasswordService {
let saved = self.repo.create(app_password).await?;
let expires_str = saved
.expires_at
.map(|dt| dt.to_rfc3339());
let expires_str = saved.expires_at.map(|dt| dt.to_rfc3339());
let curl_example = format!(
"curl -u '{}:{}' -X PROPFIND {}/webdav/",
@@ -225,7 +223,11 @@ impl AppPasswordService {
/// Also invalidates **all** cached Basic Auth entries for the owning user
/// so that the revocation takes effect immediately (instead of waiting
/// up to `BASIC_AUTH_CACHE_TTL_SECS`).
pub async fn revoke(&self, user_id: &str, id: &str) -> Result<AppPasswordRevokeResponseDto, DomainError> {
pub async fn revoke(
&self,
user_id: &str,
id: &str,
) -> Result<AppPasswordRevokeResponseDto, DomainError> {
let ap = self.repo.get_by_id(id).await?;
if ap.user_id != user_id {
return Err(DomainError::unauthorized(
@@ -241,7 +243,11 @@ impl AppPasswordService {
.invalidate_entries_if(move |_key, val| val.user_id == uid)
.ok();
tracing::debug!("Revoked app password {} — auth cache entries for user {} invalidated", id, user_id);
tracing::debug!(
"Revoked app password {} — auth cache entries for user {} invalidated",
id,
user_id
);
Ok(AppPasswordRevokeResponseDto {
status: "revoked".to_string(),
@@ -270,19 +276,12 @@ impl AppPasswordService {
// ── 1. Compute cache key = blake3("username:password") ────────
// The plain-text password is never stored; only the 32-byte
// cryptographic digest is used as lookup key.
let cache_key: [u8; 32] = blake3::hash(
format!("{}:{}", username, password).as_bytes(),
)
.into();
let cache_key: [u8; 32] =
blake3::hash(format!("{}:{}", username, password).as_bytes()).into();
// ── 2. Cache hit → return immediately ────────────────────────
if let Some(cached) = self.auth_cache.get(&cache_key).await {
return Ok((
cached.user_id,
cached.username,
cached.email,
cached.role,
));
return Ok((cached.user_id, cached.username, cached.email, cached.role));
}
// ── 3. Cache miss → full verification ────────────────────────
@@ -294,10 +293,7 @@ impl AppPasswordService {
.map_err(|_| DomainError::unauthorized("Invalid username or app password"))?;
// Get all active app passwords for this user
let app_passwords = self
.repo
.get_active_by_user_id(user.id())
.await?;
let app_passwords = self.repo.get_active_by_user_id(user.id()).await?;
if app_passwords.is_empty() {
return Err(DomainError::unauthorized(
@@ -307,7 +303,11 @@ impl AppPasswordService {
// Try each app password hash (Argon2id — CPU-intensive)
for ap in &app_passwords {
if let Ok(true) = self.hasher.verify_password(password, &ap.password_hash).await {
if let Ok(true) = self
.hasher
.verify_password(password, &ap.password_hash)
.await
{
// Update last_used_at (fire-and-forget; don't fail auth on touch error)
let _ = self.repo.touch_last_used(&ap.id).await;
@@ -321,12 +321,7 @@ impl AppPasswordService {
// ── 4. Cache the successful result ────────────────────
self.auth_cache.insert(cache_key, result.clone()).await;
return Ok((
result.user_id,
result.username,
result.email,
result.role,
));
return Ok((result.user_id, result.username, result.email, result.role));
}
}
+9 -3
View File
@@ -138,7 +138,9 @@ impl BatchOperationService {
let target_folder = target_folder.clone();
async move {
let copy_result = mgmt.copy_file(&file_id, target_folder.map(|s| s.to_string())).await;
let copy_result = mgmt
.copy_file(&file_id, target_folder.map(|s| s.to_string()))
.await;
(file_id, copy_result)
}
}))
@@ -201,7 +203,9 @@ impl BatchOperationService {
let target_folder = target_folder.clone();
async move {
let move_result = mgmt.move_file(&file_id, target_folder.map(|s| s.to_string())).await;
let move_result = mgmt
.move_file(&file_id, target_folder.map(|s| s.to_string()))
.await;
(file_id, move_result)
}
}))
@@ -578,7 +582,9 @@ impl BatchOperationService {
let caller = caller.clone();
async move {
let dto = MoveFolderDto { parent_id: target.map(|s| s.to_string()) };
let dto = MoveFolderDto {
parent_id: target.map(|s| s.to_string()),
};
let move_result = folder_service.move_folder(&folder_id, dto, &caller).await;
(folder_id, move_result)
}
+12 -14
View File
@@ -11,11 +11,13 @@
use std::sync::Arc;
use crate::application::dtos::device_auth_dto::*;
use crate::application::ports::auth_ports::{DeviceCodeStoragePort, TokenServicePort, UserStoragePort};
use crate::application::ports::auth_ports::SessionStoragePort;
use crate::application::ports::auth_ports::{
DeviceCodeStoragePort, TokenServicePort, UserStoragePort,
};
use crate::common::errors::{DomainError, ErrorKind};
use crate::domain::entities::device_code::{DeviceCode, DeviceCodeStatus};
use crate::domain::entities::session::Session;
use crate::application::ports::auth_ports::SessionStoragePort;
/// Default device code lifetime: 15 minutes (RFC 8628 recommends 5-30 min).
const DEVICE_CODE_LIFETIME_SECS: i64 = 900;
@@ -149,11 +151,7 @@ impl DeviceAuthService {
///
/// * `user_code` — the code from the verification page
/// * `user_id` — the authenticated user's ID (from session/JWT)
pub async fn approve(
&self,
user_code: &str,
user_id: &str,
) -> Result<(), DomainError> {
pub async fn approve(&self, user_code: &str, user_id: &str) -> Result<(), DomainError> {
let normalized = user_code.trim().to_uppercase().replace(' ', "");
let mut dc = self
@@ -180,8 +178,8 @@ impl DeviceAuthService {
let session = Session::new(
user_id.to_string(),
refresh_token.clone(),
None, // ip_address
Some(format!("device:{}", dc.client_name())), // user_agent
None, // ip_address
Some(format!("device:{}", dc.client_name())), // user_agent
self.token_service.refresh_token_expiry_days(),
);
self.session_storage.create_session(session).await?;
@@ -226,10 +224,7 @@ impl DeviceAuthService {
/// Client polls for tokens. Returns:
/// - `Ok(DeviceTokenSuccessDto)` if authorized
/// - `Err` with specific RFC 8628 error codes for pending/slow_down/expired/denied
pub async fn poll(
&self,
device_code: &str,
) -> Result<DeviceTokenSuccessDto, DevicePollError> {
pub async fn poll(&self, device_code: &str) -> Result<DeviceTokenSuccessDto, DevicePollError> {
let mut dc = self
.device_code_storage
.get_by_device_code(device_code)
@@ -240,7 +235,10 @@ impl DeviceAuthService {
if dc.is_expired() && dc.status() == DeviceCodeStatus::Pending {
let mut expired_dc = dc.clone();
expired_dc.mark_expired();
let _ = self.device_code_storage.update_device_code(expired_dc).await;
let _ = self
.device_code_storage
.update_device_code(expired_dc)
.await;
return Err(DevicePollError::ExpiredToken);
}
+20 -12
View File
@@ -398,12 +398,16 @@ impl FolderUseCase for FolderService {
}
// Rename folder — UPDATE RETURNING gives us the updated row directly
let folder = self.folder_storage.rename_folder(id, dto.name).await.map_err(|e| {
DomainError::internal_error(
"FolderStorage",
format!("Failed to rename folder with ID: {}: {}", id, e),
)
})?;
let folder = self
.folder_storage
.rename_folder(id, dto.name)
.await
.map_err(|e| {
DomainError::internal_error(
"FolderStorage",
format!("Failed to rename folder with ID: {}: {}", id, e),
)
})?;
Ok(FolderDto::from(folder))
}
@@ -455,12 +459,16 @@ impl FolderUseCase for FolderService {
// Move folder — UPDATE RETURNING gives us the updated row directly
let parent_ref = dto.parent_id.as_deref();
let folder = self.folder_storage.move_folder(id, parent_ref).await.map_err(|e| {
DomainError::internal_error(
"FolderStorage",
format!("Failed to move folder with ID: {}: {}", id, e),
)
})?;
let folder = self
.folder_storage
.move_folder(id, parent_ref)
.await
.map_err(|e| {
DomainError::internal_error(
"FolderStorage",
format!("Failed to move folder with ID: {}: {}", id, e),
)
})?;
Ok(FolderDto::from(folder))
}
+1 -1
View File
@@ -3,8 +3,8 @@ pub mod app_password_service;
pub mod auth_application_service;
pub mod batch_operations;
pub mod calendar_service;
pub mod device_auth_service;
pub mod contact_service;
pub mod device_auth_service;
pub mod favorites_service;
pub mod file_management_service;
pub mod file_retrieval_service;
+2 -1
View File
@@ -636,7 +636,8 @@ impl AppConfig {
{
config.auth.rate_limit.register_max_requests = val;
}
if let Ok(v) = env::var("OXICLOUD_RATE_LIMIT_REGISTER_WINDOW_SECS").map(|v| v.parse::<u64>())
if let Ok(v) =
env::var("OXICLOUD_RATE_LIMIT_REGISTER_WINDOW_SECS").map(|v| v.parse::<u64>())
&& let Ok(val) = v
{
config.auth.rate_limit.register_window_secs = val;
+10 -7
View File
@@ -603,10 +603,11 @@ impl AppServiceFactory {
Arc::new(crate::infrastructure::repositories::UserPgRepository::new(
pool.clone(),
));
let session_repo: Arc<dyn crate::application::ports::auth_ports::SessionStoragePort> =
Arc::new(crate::infrastructure::repositories::SessionPgRepository::new(
pool.clone(),
));
let session_repo: Arc<
dyn crate::application::ports::auth_ports::SessionStoragePort,
> = Arc::new(
crate::infrastructure::repositories::SessionPgRepository::new(pool.clone()),
);
let base_url = self.config.base_url();
let device_auth_svc = Arc::new(DeviceAuthService::new(
@@ -625,8 +626,9 @@ impl AppServiceFactory {
use crate::application::services::app_password_service::AppPasswordService;
use crate::infrastructure::repositories::AppPasswordPgRepository;
let app_pw_repo: Arc<dyn crate::application::ports::auth_ports::AppPasswordStoragePort> =
Arc::new(AppPasswordPgRepository::new(pool.clone()));
let app_pw_repo: Arc<
dyn crate::application::ports::auth_ports::AppPasswordStoragePort,
> = Arc::new(AppPasswordPgRepository::new(pool.clone()));
let hasher: Arc<dyn crate::application::ports::auth_ports::PasswordHasherPort> =
Arc::new(
crate::infrastructure::services::password_hasher::Argon2PasswordHasher::new(
@@ -818,7 +820,8 @@ pub struct ApplicationServices {
pub struct AuthServices {
pub token_service: Arc<dyn crate::application::ports::auth_ports::TokenServicePort>,
pub auth_application_service: Arc<AuthApplicationService>,
pub login_lockout: Arc<crate::infrastructure::services::login_lockout_service::LoginLockoutService>,
pub login_lockout:
Arc<crate::infrastructure::services::login_lockout_service::LoginLockoutService>,
}
/// Global application state for dependency injection
+1 -6
View File
@@ -242,12 +242,7 @@ impl DeviceCode {
}
/// Authorize this device code for a specific user, storing the tokens.
pub fn authorize(
&mut self,
user_id: String,
access_token: String,
refresh_token: String,
) {
pub fn authorize(&mut self, user_id: String, access_token: String, refresh_token: String) {
self.status = DeviceCodeStatus::Authorized;
self.user_id = Some(user_id);
self.access_token = Some(access_token);
+3 -2
View File
@@ -3,6 +3,7 @@ pub mod pg;
// Re-exportar para facilitar acceso
pub use pg::{
AppPasswordPgRepository, DeviceCodePgRepository, FileBlobReadRepository, FileBlobWriteRepository,
FolderDbRepository, SessionPgRepository, TrashDbRepository, UserPgRepository,
AppPasswordPgRepository, DeviceCodePgRepository, FileBlobReadRepository,
FileBlobWriteRepository, FolderDbRepository, SessionPgRepository, TrashDbRepository,
UserPgRepository,
};
@@ -86,10 +86,7 @@ impl AppPasswordStoragePort for AppPasswordPgRepository {
Ok(row.into())
}
async fn get_active_by_user_id(
&self,
user_id: &str,
) -> Result<Vec<AppPassword>, DomainError> {
async fn get_active_by_user_id(&self, user_id: &str) -> Result<Vec<AppPassword>, DomainError> {
let rows = sqlx::query_as::<_, AppPasswordRow>(
r#"
SELECT id, user_id, label, password_hash, prefix, scopes,
@@ -103,9 +100,7 @@ impl AppPasswordStoragePort for AppPasswordPgRepository {
.bind(user_id)
.fetch_all(self.pool())
.await
.map_err(|e| {
DomainError::internal_error("AppPasswordPg", format!("get_active: {e}"))
})?;
.map_err(|e| DomainError::internal_error("AppPasswordPg", format!("get_active: {e}")))?;
Ok(rows.into_iter().map(|r| r.into()).collect())
}
@@ -115,21 +110,16 @@ impl AppPasswordStoragePort for AppPasswordPgRepository {
.bind(id)
.execute(self.pool())
.await
.map_err(|e| {
DomainError::internal_error("AppPasswordPg", format!("touch: {e}"))
})?;
.map_err(|e| DomainError::internal_error("AppPasswordPg", format!("touch: {e}")))?;
Ok(())
}
async fn revoke(&self, id: &str) -> Result<(), DomainError> {
let result =
sqlx::query("UPDATE auth.app_passwords SET active = FALSE WHERE id = $1")
.bind(id)
.execute(self.pool())
.await
.map_err(|e| {
DomainError::internal_error("AppPasswordPg", format!("revoke: {e}"))
})?;
let result = sqlx::query("UPDATE auth.app_passwords SET active = FALSE WHERE id = $1")
.bind(id)
.execute(self.pool())
.await
.map_err(|e| DomainError::internal_error("AppPasswordPg", format!("revoke: {e}")))?;
if result.rows_affected() == 0 {
return Err(DomainError::not_found("AppPassword", id));
@@ -114,11 +114,9 @@ impl DeviceCodeStoragePort for DeviceCodePgRepository {
.fetch_one(self.pool.as_ref())
.await
.map_err(|e| match e {
sqlx::Error::RowNotFound => DomainError::new(
ErrorKind::NotFound,
"DeviceCode",
"Device code not found",
),
sqlx::Error::RowNotFound => {
DomainError::new(ErrorKind::NotFound, "DeviceCode", "Device code not found")
}
_ => DomainError::new(
ErrorKind::DatabaseError,
"DeviceCode",
@@ -268,10 +268,18 @@ impl FolderRepository for FolderDbRepository {
limit: usize,
include_total: bool,
) -> Result<(Vec<Folder>, Option<usize>), DomainError> {
let rows: Vec<(String, String, String, Option<String>, String, i64, i64, i64)> =
if let Some(pid) = parent_id {
sqlx::query_as(
r#"
let rows: Vec<(
String,
String,
String,
Option<String>,
String,
i64,
i64,
i64,
)> = if let Some(pid) = parent_id {
sqlx::query_as(
r#"
SELECT id::text, name, path, parent_id::text, user_id,
EXTRACT(EPOCH FROM created_at)::bigint,
EXTRACT(EPOCH FROM updated_at)::bigint,
@@ -281,15 +289,15 @@ impl FolderRepository for FolderDbRepository {
ORDER BY name
LIMIT $2 OFFSET $3
"#,
)
.bind(pid)
.bind(limit as i64)
.bind(offset as i64)
.fetch_all(self.pool())
.await
} else {
sqlx::query_as(
r#"
)
.bind(pid)
.bind(limit as i64)
.bind(offset as i64)
.fetch_all(self.pool())
.await
} else {
sqlx::query_as(
r#"
SELECT id::text, name, path, parent_id::text, user_id,
EXTRACT(EPOCH FROM created_at)::bigint,
EXTRACT(EPOCH FROM updated_at)::bigint,
@@ -299,13 +307,13 @@ impl FolderRepository for FolderDbRepository {
ORDER BY name
LIMIT $1 OFFSET $2
"#,
)
.bind(limit as i64)
.bind(offset as i64)
.fetch_all(self.pool())
.await
}
.map_err(|e| DomainError::internal_error("FolderDb", format!("paginate: {e}")))?;
)
.bind(limit as i64)
.bind(offset as i64)
.fetch_all(self.pool())
.await
}
.map_err(|e| DomainError::internal_error("FolderDb", format!("paginate: {e}")))?;
// total_count is identical in every row; 0 when the result set is empty.
let total = if include_total {
@@ -333,10 +341,18 @@ impl FolderRepository for FolderDbRepository {
limit: usize,
include_total: bool,
) -> Result<(Vec<Folder>, Option<usize>), DomainError> {
let rows: Vec<(String, String, String, Option<String>, String, i64, i64, i64)> =
if let Some(pid) = parent_id {
sqlx::query_as(
r#"
let rows: Vec<(
String,
String,
String,
Option<String>,
String,
i64,
i64,
i64,
)> = if let Some(pid) = parent_id {
sqlx::query_as(
r#"
SELECT id::text, name, path, parent_id::text, user_id,
EXTRACT(EPOCH FROM created_at)::bigint,
EXTRACT(EPOCH FROM updated_at)::bigint,
@@ -346,16 +362,16 @@ impl FolderRepository for FolderDbRepository {
ORDER BY name
LIMIT $3 OFFSET $4
"#,
)
.bind(pid)
.bind(owner_id)
.bind(limit as i64)
.bind(offset as i64)
.fetch_all(self.pool())
.await
} else {
sqlx::query_as(
r#"
)
.bind(pid)
.bind(owner_id)
.bind(limit as i64)
.bind(offset as i64)
.fetch_all(self.pool())
.await
} else {
sqlx::query_as(
r#"
SELECT id::text, name, path, parent_id::text, user_id,
EXTRACT(EPOCH FROM created_at)::bigint,
EXTRACT(EPOCH FROM updated_at)::bigint,
@@ -365,16 +381,14 @@ impl FolderRepository for FolderDbRepository {
ORDER BY name
LIMIT $2 OFFSET $3
"#,
)
.bind(owner_id)
.bind(limit as i64)
.bind(offset as i64)
.fetch_all(self.pool())
.await
}
.map_err(|e| {
DomainError::internal_error("FolderDb", format!("paginate_by_owner: {e}"))
})?;
)
.bind(owner_id)
.bind(limit as i64)
.bind(offset as i64)
.fetch_all(self.pool())
.await
}
.map_err(|e| DomainError::internal_error("FolderDb", format!("paginate_by_owner: {e}")))?;
let total = if include_total {
Some(rows.first().map_or(0, |r| r.7) as usize)
@@ -867,10 +881,7 @@ impl FolderRepository for FolderDbRepository {
user_id: &str,
) -> Result<Vec<Folder>, DomainError> {
let (where_extra, name_pattern) = match name_contains {
Some(name) if name.len() >= 3 => (
" AND fo.name ILIKE $3",
Some(format!("%{}%", name)),
),
Some(name) if name.len() >= 3 => (" AND fo.name ILIKE $3", Some(format!("%{}%", name))),
_ => ("", None),
};
+3 -1
View File
@@ -335,7 +335,9 @@ mod tests {
let claims1 = service.validate_token(&token).expect("Should validate");
// Second call: cache hit — skips HMAC, returns cloned claims
let claims2 = service.validate_token(&token).expect("Should validate from cache");
let claims2 = service
.validate_token(&token)
.expect("Should validate from cache");
assert_eq!(claims1.sub, claims2.sub);
assert_eq!(claims1.username, claims2.username);
@@ -73,12 +73,9 @@ impl LoginLockoutService {
/// Record a failed login attempt. Returns the new failure count.
pub fn record_failure(&self, username: &str) -> u32 {
let key = username.to_lowercase();
let new_count = self
.cache
.get(&key)
.map(|r| r.count + 1)
.unwrap_or(1);
self.cache.insert(key.clone(), FailureRecord { count: new_count });
let new_count = self.cache.get(&key).map(|r| r.count + 1).unwrap_or(1);
self.cache
.insert(key.clone(), FailureRecord { count: new_count });
if new_count >= self.max_failures {
tracing::warn!(
+1 -1
View File
@@ -1,11 +1,11 @@
pub mod chunked_upload_service;
pub mod compression_service;
pub mod dedup_service;
pub mod login_lockout_service;
pub mod file_content_cache;
pub mod file_system_i18n_service;
pub mod image_transcode_service;
pub mod jwt_service;
pub mod login_lockout_service;
pub mod oidc_service;
pub mod password_hasher;
pub mod path_resolver_service;
@@ -54,19 +54,22 @@ impl PathResolverService {
// Single round-trip: folder branch ∪ file branch, LIMIT 1.
// Column order: resource_type, id, name, path, parent_id, user_id,
// created_at, modified_at, size, mime_type, folder_id
let row = sqlx::query_as::<_, (
String, // resource_type
String, // id
String, // name
String, // path
Option<String>, // parent_id (folder) / NULL (file)
Option<String>, // user_id
i64, // created_at epoch
i64, // modified_at epoch
Option<i64>, // size (NULL for folder)
Option<String>, // mime_type (NULL for folder)
Option<String>, // folder_id (NULL for folder)
)>(
let row = sqlx::query_as::<
_,
(
String, // resource_type
String, // id
String, // name
String, // path
Option<String>, // parent_id (folder) / NULL (file)
Option<String>, // user_id
i64, // created_at epoch
i64, // modified_at epoch
Option<i64>, // size (NULL for folder)
Option<String>, // mime_type (NULL for folder)
Option<String>, // folder_id (NULL for folder)
),
>(
r#"
SELECT resource_type, id, name, path, parent_id, user_id,
created_at, modified_at, size, mime_type, folder_id
@@ -114,16 +117,27 @@ impl PathResolverService {
LIMIT 1
"#,
)
.bind(path) // $1 — full path for folder lookup
.bind(filename) // $2 — filename for file lookup
.bind(path) // $1 — full path for folder lookup
.bind(filename) // $2 — filename for file lookup
.bind(&folder_path) // $3 — parent folder path for file lookup
.fetch_optional(self.pool.as_ref())
.await
.map_err(|e| DomainError::internal_error("PathResolver", format!("resolve: {e}")))?
.ok_or_else(|| DomainError::not_found("Resource", path))?;
let (resource_type, id, name, res_path, parent_id, user_id,
created_at, modified_at, size, mime_type, folder_id) = row;
let (
resource_type,
id,
name,
res_path,
parent_id,
user_id,
created_at,
modified_at,
size,
mime_type,
folder_id,
) = row;
match resource_type.as_str() {
"folder" => Ok(ResolvedResource::Folder(FolderDto {
+4 -12
View File
@@ -41,9 +41,7 @@ fn cookie_secure() -> bool {
/// Build a `Set-Cookie` header value.
fn build_cookie(name: &str, value: &str, path: &str, max_age_secs: i64) -> String {
let secure = if cookie_secure() { "; Secure" } else { "" };
format!(
"{name}={value}; HttpOnly; SameSite=Lax; Path={path}; Max-Age={max_age_secs}{secure}",
)
format!("{name}={value}; HttpOnly; SameSite=Lax; Path={path}; Max-Age={max_age_secs}{secure}",)
}
/// Append `Set-Cookie` headers for both access and refresh tokens.
@@ -83,9 +81,7 @@ pub fn append_auth_cookies(
pub fn append_clear_cookies(headers: &mut HeaderMap) {
for (name, path) in [(ACCESS_COOKIE, "/"), (REFRESH_COOKIE, "/api/auth")] {
let secure = if cookie_secure() { "; Secure" } else { "" };
let val = format!(
"{name}=; HttpOnly; SameSite=Lax; Path={path}; Max-Age=0{secure}",
);
let val = format!("{name}=; HttpOnly; SameSite=Lax; Path={path}; Max-Age=0{secure}",);
if let Ok(hv) = HeaderValue::from_str(&val) {
headers.append(SET_COOKIE, hv);
}
@@ -122,9 +118,7 @@ pub fn generate_csrf_token() -> String {
/// via `document.cookie` and echo it back in the `X-CSRF-Token` header.
fn build_csrf_cookie(value: &str, max_age_secs: i64) -> String {
let secure = if cookie_secure() { "; Secure" } else { "" };
format!(
"{CSRF_COOKIE}={value}; SameSite=Lax; Path=/; Max-Age={max_age_secs}{secure}",
)
format!("{CSRF_COOKIE}={value}; SameSite=Lax; Path=/; Max-Age={max_age_secs}{secure}",)
}
/// Append a CSRF double-submit cookie alongside the auth cookies.
@@ -139,9 +133,7 @@ pub fn append_csrf_cookie(headers: &mut HeaderMap, access_expiry_secs: i64) {
/// Clear the CSRF cookie (on logout).
pub fn append_clear_csrf_cookie(headers: &mut HeaderMap) {
let secure = if cookie_secure() { "; Secure" } else { "" };
let val = format!(
"{CSRF_COOKIE}=; SameSite=Lax; Path=/; Max-Age=0{secure}",
);
let val = format!("{CSRF_COOKIE}=; SameSite=Lax; Path=/; Max-Age=0{secure}",);
if let Ok(hv) = HeaderValue::from_str(&val) {
headers.append(SET_COOKIE, hv);
}
+3 -12
View File
@@ -197,10 +197,7 @@ async fn login(
auth_response.expires_in,
state.core.config.auth.refresh_token_expiry_secs,
);
cookie_auth::append_csrf_cookie(
response.headers_mut(),
auth_response.expires_in,
);
cookie_auth::append_csrf_cookie(response.headers_mut(), auth_response.expires_in);
Ok(response)
}
Err(err) => {
@@ -253,10 +250,7 @@ async fn refresh_token(
auth_response.expires_in,
state.core.config.auth.refresh_token_expiry_secs,
);
cookie_auth::append_csrf_cookie(
response.headers_mut(),
auth_response.expires_in,
);
cookie_auth::append_csrf_cookie(response.headers_mut(), auth_response.expires_in);
Ok(response)
}
@@ -522,9 +516,6 @@ async fn oidc_exchange(
auth_response.expires_in,
state.core.config.auth.refresh_token_expiry_secs,
);
cookie_auth::append_csrf_cookie(
response.headers_mut(),
auth_response.expires_in,
);
cookie_auth::append_csrf_cookie(response.headers_mut(), auth_response.expires_in);
Ok(response)
}
+28 -50
View File
@@ -52,11 +52,10 @@ pub fn caldav_routes() -> Router<Arc<AppState>> {
/// Creates RFC 6764 well-known discovery routes.
/// These are public (no auth) and simply redirect to the CalDAV root.
pub fn well_known_routes() -> Router<Arc<AppState>> {
Router::new()
.route(
"/.well-known/caldav",
axum::routing::any(handle_well_known_caldav),
)
Router::new().route(
"/.well-known/caldav",
axum::routing::any(handle_well_known_caldav),
)
}
async fn handle_well_known_caldav() -> Response<Body> {
@@ -114,13 +113,9 @@ fn extract_caldav_path(uri_path: &str) -> String {
} else if uri_path.ends_with("/caldav") {
""
} else {
uri_path
.trim_start_matches('/')
.trim_end_matches('/')
uri_path.trim_start_matches('/').trim_end_matches('/')
};
percent_decode_str(encoded)
.decode_utf8_lossy()
.into_owned()
percent_decode_str(encoded).decode_utf8_lossy().into_owned()
}
// ─── Helper: extract user from request ───────────────────────────────
@@ -198,9 +193,7 @@ async fn handle_propfind(
calendar_service
.list_my_calendars(&user.id)
.await
.map_err(|e| {
AppError::internal_error(format!("Failed to list calendars: {}", e))
})?
.map_err(|e| AppError::internal_error(format!("Failed to list calendars: {}", e)))?
};
let base_href = "/caldav/";
@@ -221,9 +214,7 @@ async fn handle_propfind(
.unwrap())
} else if path.starts_with("principals/") || path == "principals" {
// Principal resource — return user principal properties
let username = path
.strip_prefix("principals/")
.unwrap_or(&user.username);
let username = path.strip_prefix("principals/").unwrap_or(&user.username);
let username = if username.is_empty() {
&user.username
} else {
@@ -255,9 +246,7 @@ async fn handle_propfind(
if parts.len() == 1 {
// Single path segment: try as calendar ID first, fall back to user home
let calendar_result = calendar_service
.get_calendar(first_segment, &user.id)
.await;
let calendar_result = calendar_service.get_calendar(first_segment, &user.id).await;
if let Ok(calendar) = calendar_result {
// Valid calendar ID — return calendar collection
@@ -281,9 +270,7 @@ async fn handle_propfind(
base_href,
&depth,
)
.map_err(|e| {
AppError::internal_error(format!("Failed to generate XML: {}", e))
})?;
.map_err(|e| AppError::internal_error(format!("Failed to generate XML: {}", e)))?;
Ok(Response::builder()
.status(StatusCode::MULTI_STATUS)
@@ -293,12 +280,13 @@ async fn handle_propfind(
} else {
// Not a calendar ID — treat as user calendar home (e.g. /caldav/{username}/)
// List all calendars for this user
let calendars = calendar_service
.list_my_calendars(&user.id)
.await
.map_err(|e| {
AppError::internal_error(format!("Failed to list calendars: {}", e))
})?;
let calendars =
calendar_service
.list_my_calendars(&user.id)
.await
.map_err(|e| {
AppError::internal_error(format!("Failed to list calendars: {}", e))
})?;
let base_href = &format!("/caldav/{}/", first_segment);
let mut response_body = Vec::new();
@@ -309,9 +297,7 @@ async fn handle_propfind(
&propfind_request,
base_href,
)
.map_err(|e| {
AppError::internal_error(format!("Failed to generate XML: {}", e))
})?;
.map_err(|e| AppError::internal_error(format!("Failed to generate XML: {}", e)))?;
Ok(Response::builder()
.status(StatusCode::MULTI_STATUS)
@@ -324,9 +310,7 @@ async fn handle_propfind(
let rest = parts[1];
// Check if first_segment is a valid calendar ID
let calendar_result = calendar_service
.get_calendar(first_segment, &user.id)
.await;
let calendar_result = calendar_service.get_calendar(first_segment, &user.id).await;
let (calendar_id, event_path) = if calendar_result.is_ok() {
// first_segment is a calendar ID, rest is event path
@@ -341,9 +325,7 @@ async fn handle_propfind(
let cal = calendar_service
.get_calendar(sub_parts[0], &user.id)
.await
.map_err(|e| {
AppError::not_found(format!("Calendar not found: {}", e))
})?;
.map_err(|e| AppError::not_found(format!("Calendar not found: {}", e)))?;
let events = if depth != "0" {
calendar_service
@@ -354,8 +336,7 @@ async fn handle_propfind(
vec![]
};
let base_href =
&format!("/caldav/{}/{}/", first_segment, sub_parts[0]);
let base_href = &format!("/caldav/{}/{}/", first_segment, sub_parts[0]);
let mut response_body = Vec::new();
CalDavAdapter::generate_calendar_collection_propfind(
@@ -387,16 +368,12 @@ async fn handle_propfind(
let events = calendar_service
.list_events(calendar_id, None, None, &user.id)
.await
.map_err(|e| {
AppError::internal_error(format!("Failed to list events: {}", e))
})?;
.map_err(|e| AppError::internal_error(format!("Failed to list events: {}", e)))?;
let event = events
.iter()
.find(|e| e.ical_uid == ical_uid)
.ok_or_else(|| {
AppError::not_found(format!("Event not found: {}", ical_uid))
})?;
.ok_or_else(|| AppError::not_found(format!("Event not found: {}", ical_uid)))?;
let base_href = &format!("/caldav/{}/", calendar_id);
let report_type = CalDavReportType::CalendarMultiget {
@@ -411,9 +388,7 @@ async fn handle_propfind(
&report_type,
base_href,
)
.map_err(|e| {
AppError::internal_error(format!("Failed to generate XML: {}", e))
})?;
.map_err(|e| AppError::internal_error(format!("Failed to generate XML: {}", e)))?;
Ok(Response::builder()
.status(StatusCode::MULTI_STATUS)
@@ -718,7 +693,10 @@ fn generate_event_ical(event: &crate::application::dtos::calendar_dto::CalendarE
}
/// Writes a VEVENT block directly into `buf` — zero intermediate allocations.
fn write_vevent(buf: &mut String, event: &crate::application::dtos::calendar_dto::CalendarEventDto) {
fn write_vevent(
buf: &mut String,
event: &crate::application::dtos::calendar_dto::CalendarEventDto,
) {
let _ = write!(
buf,
"BEGIN:VEVENT\r\nUID:{}\r\nSUMMARY:{}\r\nDTSTART:{}\r\nDTEND:{}\r\n",
@@ -99,9 +99,7 @@ fn extract_carddav_path(uri_path: &str) -> String {
} else if uri_path.ends_with("/carddav") {
""
} else {
uri_path
.trim_start_matches('/')
.trim_end_matches('/')
uri_path.trim_start_matches('/').trim_end_matches('/')
};
percent_encoding::percent_decode_str(encoded)
.decode_utf8_lossy()
@@ -92,8 +92,8 @@ async fn device_token(
match device_service.poll(&body.device_code).await {
Ok(tokens) => Ok((StatusCode::OK, Json(tokens)).into_response()),
Err(poll_err) => {
let status = StatusCode::from_u16(poll_err.http_status())
.unwrap_or(StatusCode::BAD_REQUEST);
let status =
StatusCode::from_u16(poll_err.http_status()).unwrap_or(StatusCode::BAD_REQUEST);
let error_body = serde_json::json!({
"error": poll_err.error_code(),
"error_description": poll_err.description()
@@ -166,9 +166,7 @@ async fn device_verify_action(
Json(serde_json::json!({ "status": "denied" })),
))
}
_ => Err(AppError::bad_request(
"action must be 'approve' or 'deny'",
)),
_ => Err(AppError::bad_request("action must be 'approve' or 'deny'")),
}
}
+1 -1
View File
@@ -2,11 +2,11 @@ pub mod admin_handler;
pub mod app_password_handler;
pub mod auth_handler;
pub mod batch_handler;
pub mod device_auth_handler;
pub mod caldav_handler;
pub mod carddav_handler;
pub mod chunked_upload_handler;
pub mod dedup_handler;
pub mod device_auth_handler;
pub mod favorites_handler;
pub mod file_handler;
pub mod folder_handler;
+82 -26
View File
@@ -28,7 +28,7 @@ use crate::common::di::AppState;
use crate::infrastructure::services::path_resolver_service::ResolvedResource;
use crate::interfaces::errors::AppError;
use crate::interfaces::middleware::auth::CurrentUser;
use percent_encoding::{percent_decode_str, utf8_percent_encode, NON_ALPHANUMERIC, AsciiSet};
use percent_encoding::{AsciiSet, NON_ALPHANUMERIC, percent_decode_str, utf8_percent_encode};
use std::sync::Arc;
/// Characters that MUST NOT be percent-encoded inside a URI path segment.
@@ -115,9 +115,7 @@ fn extract_webdav_path(uri: &axum::http::Uri) -> String {
trimmed.trim_end_matches('/')
};
// Decode percent-encoded characters (e.g. %20 → space)
percent_decode_str(encoded)
.decode_utf8_lossy()
.into_owned()
percent_decode_str(encoded).decode_utf8_lossy().into_owned()
}
async fn handle_webdav_methods_root(
@@ -324,8 +322,13 @@ async fn handle_propfind(
let mut xml_writer = Writer::new(&mut buf);
WebDavAdapter::write_multistatus_start(&mut xml_writer)
.map_err(|e| AppError::internal_error(format!("XML write error: {}", e)))?;
WebDavAdapter::write_file_entry(&mut xml_writer, &file, &propfind_request, &base_href)
.map_err(|e| AppError::internal_error(format!("XML write error: {}", e)))?;
WebDavAdapter::write_file_entry(
&mut xml_writer,
&file,
&propfind_request,
&base_href,
)
.map_err(|e| AppError::internal_error(format!("XML write error: {}", e)))?;
WebDavAdapter::write_multistatus_end(&mut xml_writer)
.map_err(|e| AppError::internal_error(format!("XML write error: {}", e)))?;
}
@@ -358,8 +361,13 @@ async fn handle_propfind(
let mut xml_writer = Writer::new(&mut buf);
WebDavAdapter::write_multistatus_start(&mut xml_writer)
.map_err(|e| AppError::internal_error(format!("XML write error: {}", e)))?;
WebDavAdapter::write_file_entry(&mut xml_writer, &file, &propfind_request, &base_href)
.map_err(|e| AppError::internal_error(format!("XML write error: {}", e)))?;
WebDavAdapter::write_file_entry(
&mut xml_writer,
&file,
&propfind_request,
&base_href,
)
.map_err(|e| AppError::internal_error(format!("XML write error: {}", e)))?;
WebDavAdapter::write_multistatus_end(&mut xml_writer)
.map_err(|e| AppError::internal_error(format!("XML write error: {}", e)))?;
}
@@ -910,13 +918,17 @@ async fn handle_delete(
folder_service
.delete_folder(&folder.id, caller_id)
.await
.map_err(|e| AppError::internal_error(format!("Failed to delete folder: {}", e)))?;
.map_err(|e| {
AppError::internal_error(format!("Failed to delete folder: {}", e))
})?;
}
Ok(ResolvedResource::File(file)) => {
file_management_service
.delete_file(&file.id)
.await
.map_err(|e| AppError::internal_error(format!("Failed to delete file: {}", e)))?;
.map_err(|e| {
AppError::internal_error(format!("Failed to delete file: {}", e))
})?;
}
Err(_) => return Err(AppError::not_found(format!("Resource not found: {}", path))),
}
@@ -1002,8 +1014,14 @@ async fn handle_move(
let dest_exists = if let Some(resolver) = &state.path_resolver {
resolver.exists(&destination_path).await.unwrap_or(false)
} else {
folder_service.get_folder_by_path(&destination_path).await.is_ok()
|| file_retrieval_service.get_file_by_path(&destination_path).await.is_ok()
folder_service
.get_folder_by_path(&destination_path)
.await
.is_ok()
|| file_retrieval_service
.get_file_by_path(&destination_path)
.await
.is_ok()
};
if dest_exists {
return Err(AppError::precondition_failed(
@@ -1044,7 +1062,9 @@ async fn handle_move(
folder.owner_id.as_deref().unwrap_or("webdav"),
)
.await
.map_err(|e| AppError::internal_error(format!("Failed to move folder: {}", e)))?;
.map_err(|e| {
AppError::internal_error(format!("Failed to move folder: {}", e))
})?;
if folder.name != dest_folder_name {
let rename_dto = crate::application::dtos::folder_dto::RenameFolderDto {
@@ -1057,7 +1077,9 @@ async fn handle_move(
folder.owner_id.as_deref().unwrap_or("webdav"),
)
.await
.map_err(|e| AppError::internal_error(format!("Failed to rename folder: {}", e)))?;
.map_err(|e| {
AppError::internal_error(format!("Failed to rename folder: {}", e))
})?;
}
}
Ok(ResolvedResource::File(file)) => {
@@ -1080,16 +1102,25 @@ async fn handle_move(
file_management_service
.move_file(&file.id, Some(dest_parent_path.to_string()))
.await
.map_err(|e| AppError::internal_error(format!("Failed to move file: {}", e)))?;
.map_err(|e| {
AppError::internal_error(format!("Failed to move file: {}", e))
})?;
}
if file.name != dest_filename {
file_management_service
.rename_file(&file.id, dest_filename)
.await
.map_err(|e| AppError::internal_error(format!("Failed to rename file: {}", e)))?;
.map_err(|e| {
AppError::internal_error(format!("Failed to rename file: {}", e))
})?;
}
}
Err(_) => return Err(AppError::not_found(format!("Resource not found: {}", source_path))),
Err(_) => {
return Err(AppError::not_found(format!(
"Resource not found: {}",
source_path
)));
}
}
} else {
// Fallback: legacy double-query path
@@ -1137,13 +1168,17 @@ async fn handle_move(
folder.owner_id.as_deref().unwrap_or("webdav"),
)
.await
.map_err(|e| AppError::internal_error(format!("Failed to rename folder: {}", e)))?;
.map_err(|e| {
AppError::internal_error(format!("Failed to rename folder: {}", e))
})?;
}
} else {
let file = file_retrieval_service
.get_file_by_path(&source_path)
.await
.map_err(|_e| AppError::not_found(format!("Resource not found: {}", source_path)))?;
.map_err(|_e| {
AppError::not_found(format!("Resource not found: {}", source_path))
})?;
let dest_filename = destination_path
.split('/')
@@ -1170,7 +1205,9 @@ async fn handle_move(
file_management_service
.rename_file(&file.id, dest_filename)
.await
.map_err(|e| AppError::internal_error(format!("Failed to rename file: {}", e)))?;
.map_err(|e| {
AppError::internal_error(format!("Failed to rename file: {}", e))
})?;
}
}
}
@@ -1240,8 +1277,14 @@ async fn handle_copy(
let dest_exists = if let Some(resolver) = &state.path_resolver {
resolver.exists(&destination_path).await.unwrap_or(false)
} else {
folder_service.get_folder_by_path(&destination_path).await.is_ok()
|| file_retrieval_service.get_file_by_path(&destination_path).await.is_ok()
folder_service
.get_folder_by_path(&destination_path)
.await
.is_ok()
|| file_retrieval_service
.get_file_by_path(&destination_path)
.await
.is_ok()
};
if dest_exists {
return Err(AppError::precondition_failed(
@@ -1296,7 +1339,10 @@ async fn handle_copy(
.create_folder(create_dto)
.await
.map_err(|e| {
AppError::internal_error(format!("Failed to create destination folder: {}", e))
AppError::internal_error(format!(
"Failed to create destination folder: {}",
e
))
})?;
}
}
@@ -1322,7 +1368,12 @@ async fn handle_copy(
.await
.map_err(|e| AppError::internal_error(format!("Failed to copy file: {}", e)))?;
}
Err(_) => return Err(AppError::not_found(format!("Resource not found: {}", source_path))),
Err(_) => {
return Err(AppError::not_found(format!(
"Resource not found: {}",
source_path
)));
}
}
} else {
// Fallback: legacy double-query path
@@ -1371,14 +1422,19 @@ async fn handle_copy(
.create_folder(create_dto)
.await
.map_err(|e| {
AppError::internal_error(format!("Failed to create destination folder: {}", e))
AppError::internal_error(format!(
"Failed to create destination folder: {}",
e
))
})?;
}
} else {
let file = file_retrieval_service
.get_file_by_path(&source_path)
.await
.map_err(|_e| AppError::not_found(format!("Resource not found: {}", source_path)))?;
.map_err(|_e| {
AppError::not_found(format!("Resource not found: {}", source_path))
})?;
let dest_parent_path = if let Some(idx) = destination_path.rfind('/') {
&destination_path[..idx]
+5 -9
View File
@@ -205,10 +205,7 @@ pub async fn auth_middleware(
}
Err(e) => {
tracing::warn!("Bearer token validation failed: {}", e);
return Err(AuthError::InvalidToken(format!(
"Invalid token: {}",
e
)));
return Err(AuthError::InvalidToken(format!("Invalid token: {}", e)));
}
}
}
@@ -273,7 +270,9 @@ pub async fn auth_middleware(
{
use crate::interfaces::api::cookie_auth;
if let Some(token_str) = cookie_auth::extract_cookie_value(&headers, cookie_auth::ACCESS_COOKIE) {
if let Some(token_str) =
cookie_auth::extract_cookie_value(&headers, cookie_auth::ACCESS_COOKIE)
{
if !token_str.is_empty() {
tracing::debug!("Processing cookie-based authentication");
@@ -281,10 +280,7 @@ pub async fn auth_middleware(
let token_service = &auth_service.token_service;
match token_service.validate_token(&token_str) {
Ok(claims) => {
tracing::debug!(
"Cookie token validated for user: {}",
claims.username
);
tracing::debug!("Cookie token validated for user: {}", claims.username);
let current_user = CurrentUser {
id: claims.sub,
username: claims.username,
+2 -4
View File
@@ -40,10 +40,8 @@ pub async fn csrf_middleware(request: Request, next: Next) -> Result<Response, R
}
// Extract the CSRF token from the cookie.
let cookie_token = cookie_auth::extract_cookie_value(
request.headers(),
cookie_auth::CSRF_COOKIE,
);
let cookie_token =
cookie_auth::extract_cookie_value(request.headers(), cookie_auth::CSRF_COOKIE);
// Extract the CSRF token from the request header.
let header_token = request
+2 -8
View File
@@ -62,12 +62,7 @@ impl RateLimiter {
// moka's entry API lets us atomically read-modify-write.
// On first access the entry is inserted with count = 1 and the TTL
// starts. Subsequent accesses within the window increment the count.
let count = self
.cache
.entry(key)
.or_insert_with(|| 0)
.into_value()
+ 1;
let count = self.cache.entry(key).or_insert_with(|| 0).into_value() + 1;
// Write back the incremented value. Because `or_insert_with` returns
// the *existing* value when the key was already present, we must always
@@ -75,8 +70,7 @@ impl RateLimiter {
// insert still governs eviction because moka uses insert-time TTL.
// However, on re-insert moka resets the TTL — for rate limiting this
// is fine because it means the window "slides" forward on activity.
self.cache
.insert(ip.to_string(), count);
self.cache.insert(ip.to_string(), count);
if count > self.max_requests {
Err(())
+27 -13
View File
@@ -170,13 +170,15 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
);
}
if config.features.enable_auth {
use interfaces::api::handlers::auth_handler::{auth_routes, login_route, register_route, refresh_route};
use oxicloud::interfaces::api::handlers::device_auth_handler;
use interfaces::api::handlers::auth_handler::{
auth_routes, login_route, refresh_route, register_route,
};
use oxicloud::interfaces::api::handlers::app_password_handler;
use oxicloud::interfaces::api::handlers::device_auth_handler;
use oxicloud::interfaces::middleware::auth::auth_middleware;
use oxicloud::interfaces::middleware::csrf::csrf_middleware;
use oxicloud::interfaces::middleware::rate_limit::{
RateLimiter, rate_limit_login, rate_limit_register, rate_limit_refresh,
RateLimiter, rate_limit_login, rate_limit_refresh, rate_limit_register,
};
// ── Rate limiters (IP-based, in-memory via moka) ────────────────
@@ -198,28 +200,40 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
));
tracing::info!(
"Rate limiting enabled — login: {}/{} s, register: {}/{} s, refresh: {}/{} s",
rl.login_max_requests, rl.login_window_secs,
rl.register_max_requests, rl.register_window_secs,
rl.refresh_max_requests, rl.refresh_window_secs,
rl.login_max_requests,
rl.login_window_secs,
rl.register_max_requests,
rl.register_window_secs,
rl.refresh_max_requests,
rl.refresh_window_secs,
);
// Auth routes split by rate-limit policy
let auth_login = login_route()
.layer(axum::middleware::from_fn_with_state(login_limiter.clone(), rate_limit_login))
.layer(axum::middleware::from_fn_with_state(
login_limiter.clone(),
rate_limit_login,
))
.with_state(app_state.clone());
let auth_register = register_route()
.layer(axum::middleware::from_fn_with_state(register_limiter.clone(), rate_limit_register))
.layer(axum::middleware::from_fn_with_state(
register_limiter.clone(),
rate_limit_register,
))
.with_state(app_state.clone());
let auth_refresh = refresh_route()
.layer(axum::middleware::from_fn_with_state(refresh_limiter.clone(), rate_limit_refresh))
.layer(axum::middleware::from_fn_with_state(
refresh_limiter.clone(),
rate_limit_refresh,
))
.with_state(app_state.clone());
// Remaining auth routes (status, OIDC, protected /me, /logout, etc.)
let auth_router = auth_routes().with_state(app_state.clone());
// Device Authorization Grant (RFC 8628)
// Public endpoints: /api/auth/device/authorize + /api/auth/device/token
let device_public = device_auth_handler::device_auth_public_routes()
.with_state(app_state.clone());
let device_public =
device_auth_handler::device_auth_public_routes().with_state(app_state.clone());
// Protected endpoints: /api/auth/device/verify, /api/auth/device/devices
let device_protected = device_auth_handler::device_auth_protected_routes()
.layer(axum::middleware::from_fn(csrf_middleware))
@@ -325,8 +339,8 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
// ── Security headers ─────────────────────────────────────────────────
// Applied globally so every response (API, static, DAV) carries them.
use axum::http::header::HeaderName;
use axum::http::HeaderValue;
use axum::http::header::HeaderName;
app = app
.layer(SetResponseHeaderLayer::overriding(
@@ -347,7 +361,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
frame-src *; \
frame-ancestors 'none'; \
base-uri 'self'; \
form-action 'self'"
form-action 'self'",
),
))
.layer(SetResponseHeaderLayer::overriding(