fix: resolve all clippy warnings and convert integration_tests to custom cfg

- Add type aliases (FileRow, FolderRow, FolderRowPaginated, FolderRowOptUser) to reduce type complexity
- Simplify redundant closures in app_password_handler and webdav_handler
- Remove needless borrow in auth_handler
- Collapse nested if/let chains in login_lockout, webdav_lock, auth, rate_limit
- Box LockEntry in acquire() Err variant to fix large enum variant warning
- Rename DeviceCodeStatus::from_str to parse to avoid should_implement_trait lint
- Add #[allow(clippy::too_many_arguments)] and #[allow(clippy::result_unit_err)] where appropriate
- Convert integration_tests from cargo feature to custom cfg attribute
- Add check-cfg lint config in Cargo.toml for integration_tests cfg
This commit is contained in:
Diocrafts
2026-03-04 23:55:08 +01:00
parent b81b7f7a0e
commit ee86c3a128
53 changed files with 871 additions and 956 deletions
+1 -1
View File
@@ -6,10 +6,10 @@ use std::sync::Arc;
use crate::application::dtos::file_dto::FileDto;
use crate::application::ports::storage_ports::CopyFolderTreeResult;
use crate::common::errors::DomainError;
use crate::application::services::file_management_service::FileManagementService;
use crate::application::services::file_retrieval_service::FileRetrievalService;
use crate::application::services::file_upload_service::FileUploadService;
use crate::common::errors::DomainError;
// ─────────────────────────────────────────────────────
// Upload port
-1
View File
@@ -1,4 +1,3 @@
use crate::{
application::dtos::{
pagination::PaginatedResponseDto,
-1
View File
@@ -1,4 +1,3 @@
use crate::application::dtos::trash_dto::TrashedItemDto;
use crate::common::errors::Result;
@@ -7,8 +7,8 @@ use crate::application::services::auth_application_service::AuthApplicationServi
use crate::common::config::OidcConfig;
use crate::common::errors::{DomainError, ErrorKind};
use crate::domain::repositories::settings_repository::SettingsRepository;
use crate::infrastructure::services::oidc_service::OidcService;
use crate::infrastructure::repositories::pg::SettingsPgRepository;
use crate::infrastructure::services::oidc_service::OidcService;
/// Admin settings service — manages platform configuration in the database.
///
@@ -9,13 +9,13 @@ use crate::application::ports::auth_ports::{
};
use crate::common::errors::DomainError;
use crate::domain::entities::app_password::AppPassword;
use crate::infrastructure::repositories::pg::AppPasswordPgRepository;
use crate::infrastructure::repositories::pg::UserPgRepository;
use crate::infrastructure::services::password_hasher::Argon2PasswordHasher;
use chrono::{Duration, Utc};
use moka::future::Cache;
use std::sync::Arc;
use std::time::Duration as StdDuration;
use crate::infrastructure::repositories::pg::AppPasswordPgRepository;
use crate::infrastructure::services::password_hasher::Argon2PasswordHasher;
use crate::infrastructure::repositories::pg::UserPgRepository;
/// App password token length (32 random alphanumeric chars after prefix).
const TOKEN_LENGTH: usize = 32;
@@ -6,21 +6,21 @@ use crate::application::ports::auth_ports::{
UserStoragePort,
};
use crate::application::ports::inbound::FolderUseCase;
use crate::application::services::folder_service::FolderService;
use crate::common::config::OidcConfig;
use crate::common::errors::{DomainError, ErrorKind};
use crate::domain::entities::session::Session;
use crate::domain::entities::user::{User, UserRole};
use crate::infrastructure::repositories::pg::SessionPgRepository;
use crate::infrastructure::repositories::pg::UserPgRepository;
use crate::infrastructure::services::jwt_service::JwtTokenService;
use crate::infrastructure::services::oidc_service::OidcService;
use crate::infrastructure::services::password_hasher::Argon2PasswordHasher;
use moka::sync::Cache;
use std::path::PathBuf;
use std::sync::Arc;
use std::sync::RwLock;
use std::time::Duration;
use crate::infrastructure::services::password_hasher::Argon2PasswordHasher;
use crate::application::services::folder_service::FolderService;
use crate::infrastructure::services::jwt_service::JwtTokenService;
use crate::infrastructure::services::oidc_service::OidcService;
use crate::infrastructure::repositories::pg::SessionPgRepository;
use crate::infrastructure::repositories::pg::UserPgRepository;
/// Tracks a pending OIDC authorization flow (CSRF + PKCE + nonce)
#[derive(Clone)]
@@ -145,11 +145,7 @@ impl AuthApplicationService {
}
/// Configures the OIDC service
pub fn with_oidc(
self,
oidc_service: Arc<OidcService>,
oidc_config: OidcConfig,
) -> Self {
pub fn with_oidc(self, oidc_service: Arc<OidcService>, oidc_config: OidcConfig) -> Self {
{
let mut state = self.oidc.write().unwrap();
state.service = Some(oidc_service);
@@ -308,12 +304,7 @@ impl AuthApplicationService {
}
// Check email uniqueness
if self
.user_storage
.get_user_by_email(&email)
.await
.is_ok()
{
if self.user_storage.get_user_by_email(&email).await.is_ok() {
return Err(DomainError::new(
ErrorKind::AlreadyExists,
"User",
@@ -614,7 +605,6 @@ impl AuthApplicationService {
Ok(users.into_iter().map(UserDto::from).collect())
}
// ========================================================================
// Admin User Management Methods
// ========================================================================
+4 -4
View File
@@ -14,12 +14,12 @@ use crate::application::dtos::folder_dto::{FolderDto, MoveFolderDto};
use crate::application::ports::file_ports::{FileManagementUseCase, FileRetrievalUseCase};
use crate::application::ports::inbound::FolderUseCase;
use crate::application::ports::trash_ports::TrashUseCase;
use crate::application::services::folder_service::FolderService;
use crate::common::config::AppConfig;
use crate::common::errors::DomainError;
use crate::application::services::file_management_service::FileManagementService;
use crate::application::services::file_retrieval_service::FileRetrievalService;
use crate::application::services::folder_service::FolderService;
use crate::application::services::trash_service::TrashService;
use crate::common::config::AppConfig;
use crate::common::errors::DomainError;
/// Specific errors for batch operations
#[derive(Debug, Error)]
@@ -1007,7 +1007,7 @@ impl BatchOperationService {
}
}
#[cfg(feature = "integration_tests")]
#[cfg(integration_tests)]
mod tests {
use super::*;
use crate::common::stubs::{StubFileManagementUseCase, StubFileRetrievalUseCase};
@@ -19,9 +19,9 @@ use crate::common::errors::{DomainError, ErrorKind};
use crate::domain::entities::device_code::{DeviceCode, DeviceCodeStatus};
use crate::domain::entities::session::Session;
use crate::infrastructure::repositories::pg::DeviceCodePgRepository;
use crate::infrastructure::services::jwt_service::JwtTokenService;
use crate::infrastructure::repositories::pg::SessionPgRepository;
use crate::infrastructure::repositories::pg::UserPgRepository;
use crate::infrastructure::services::jwt_service::JwtTokenService;
/// Default device code lifetime: 15 minutes (RFC 8628 recommends 5-30 min).
const DEVICE_CODE_LIFETIME_SECS: i64 = 900;
@@ -3,9 +3,9 @@ use crate::application::dtos::favorites_dto::{
};
use crate::application::ports::favorites_ports::{FavoritesRepositoryPort, FavoritesUseCase};
use crate::common::errors::{DomainError, ErrorKind, Result};
use crate::infrastructure::repositories::pg::FavoritesPgRepository;
use std::sync::Arc;
use tracing::info;
use crate::infrastructure::repositories::pg::FavoritesPgRepository;
/// Implementation of the FavoritesUseCase for managing user favorites.
///
@@ -4,11 +4,11 @@ use crate::application::dtos::file_dto::FileDto;
use crate::application::ports::file_ports::FileManagementUseCase;
use crate::application::ports::storage_ports::{CopyFolderTreeResult, FileReadPort, FileWritePort};
use crate::application::ports::trash_ports::TrashUseCase;
use crate::application::services::trash_service::TrashService;
use crate::common::errors::DomainError;
use tracing::{error, info, warn};
use crate::infrastructure::repositories::pg::file_blob_read_repository::FileBlobReadRepository;
use crate::infrastructure::repositories::pg::file_blob_write_repository::FileBlobWriteRepository;
use crate::application::services::trash_service::TrashService;
use tracing::{error, info, warn};
/// Service for file management operations (move, delete).
///
@@ -7,10 +7,12 @@ use crate::application::dtos::file_dto::FileDto;
use crate::application::ports::file_ports::{FileRetrievalUseCase, OptimizedFileContent};
use crate::application::ports::storage_ports::FileReadPort;
use crate::common::errors::DomainError;
use tracing::{debug, info};
use crate::infrastructure::repositories::pg::file_blob_read_repository::FileBlobReadRepository;
use crate::infrastructure::services::file_content_cache::FileContentCache;
use crate::infrastructure::services::image_transcode_service::{ImageTranscodeService, OutputFormat};
use crate::infrastructure::services::image_transcode_service::{
ImageTranscodeService, OutputFormat,
};
use tracing::{debug, info};
/// Threshold below which files are served from RAM cache (10 MB).
const CACHE_THRESHOLD: u64 = 10 * 1024 * 1024;
@@ -1,15 +1,14 @@
use std::path::Path;
use std::sync::Arc;
use crate::application::dtos::file_dto::FileDto;
use crate::application::ports::file_ports::FileUploadUseCase;
use crate::application::ports::storage_ports::{FileReadPort, FileWritePort};
use crate::application::services::storage_usage_service::StorageUsageService;
use crate::common::errors::DomainError;
use tracing::{debug, info, warn};
use crate::infrastructure::repositories::pg::FileBlobReadRepository;
use crate::infrastructure::repositories::pg::FileBlobWriteRepository;
use crate::application::services::storage_usage_service::StorageUsageService;
use tracing::{debug, info, warn};
/// Helper function to extract username from folder path string.
/// e.g. "My Folder - user1/subfolder/file.txt" → "user1"
@@ -48,8 +47,7 @@ pub struct FileUploadService {
/// Read port — needed for WebDAV create_file / update_file
file_read: Option<Arc<FileBlobReadRepository>>,
/// Optional storage usage tracking
storage_usage_service:
Option<Arc<StorageUsageService>>,
storage_usage_service: Option<Arc<StorageUsageService>>,
}
impl FileUploadService {
+3 -3
View File
@@ -3,10 +3,10 @@ use crate::application::dtos::folder_dto::{
};
use crate::application::ports::inbound::FolderUseCase;
use crate::common::errors::{DomainError, ErrorKind};
use crate::domain::services::path_service::StoragePath;
use std::sync::Arc;
use crate::infrastructure::repositories::pg::folder_db_repository::FolderDbRepository;
use crate::domain::repositories::folder_repository::FolderRepository;
use crate::domain::services::path_service::StoragePath;
use crate::infrastructure::repositories::pg::folder_db_repository::FolderDbRepository;
use std::sync::Arc;
/// Implementation of the use case for folder operations
pub struct FolderService {
+272 -272
View File
@@ -1,272 +1,272 @@
//! Tests for IDOR (Insecure Direct Object Reference) protection.
//!
//! Verifies that ownership checks at the repository and service layers
//! correctly reject access when the caller is not the file owner.
use bytes::Bytes;
use futures::Stream;
use std::collections::HashMap;
use std::pin::Pin;
use std::sync::Mutex;
use crate::application::ports::storage_ports::{
FileReadPort,
};
use crate::common::errors::DomainError;
use crate::domain::entities::file::File;
use crate::domain::services::path_service::StoragePath;
// ═══════════════════════════════════════════════════════════════════════════
// Mock repositories
// ═══════════════════════════════════════════════════════════════════════════
/// A simple in-memory mock that maps (file_id → (File, owner_id)).
struct MockFileReadPort {
/// file_id → (File, owner_id)
files: Mutex<HashMap<String, (File, String)>>,
}
impl MockFileReadPort {
fn new() -> Self {
Self {
files: Mutex::new(HashMap::new()),
}
}
/// Insert a test file owned by `owner_id`.
fn insert(&self, id: &str, name: &str, owner_id: &str) {
let file = File::new(
id.to_string(),
name.to_string(),
StoragePath::from_string(&format!("/{}", name)),
42,
"text/plain".to_string(),
None,
)
.unwrap();
self.files
.lock()
.unwrap()
.insert(id.to_string(), (file, owner_id.to_string()));
}
}
impl FileReadPort for MockFileReadPort {
async fn get_file(&self, id: &str) -> Result<File, DomainError> {
let files = self.files.lock().unwrap();
files
.get(id)
.map(|(f, _)| f.clone())
.ok_or_else(|| DomainError::not_found("File", id.to_string()))
}
async fn get_file_for_owner(&self, id: &str, owner_id: &str) -> Result<File, DomainError> {
let files = self.files.lock().unwrap();
match files.get(id) {
Some((file, actual_owner)) if actual_owner == owner_id => Ok(file.clone()),
// Return NotFound regardless — do not leak existence
_ => Err(DomainError::not_found("File", id.to_string())),
}
}
async fn list_files(&self, _folder_id: Option<&str>) -> Result<Vec<File>, DomainError> {
Ok(Vec::new())
}
async fn get_file_stream(
&self,
_id: &str,
) -> Result<Box<dyn Stream<Item = Result<Bytes, std::io::Error>> + Send>, DomainError> {
unimplemented!()
}
async fn get_file_range_stream(
&self,
_id: &str,
_start: u64,
_end: Option<u64>,
) -> Result<Box<dyn Stream<Item = Result<Bytes, std::io::Error>> + Send>, DomainError> {
unimplemented!()
}
async fn get_file_path(&self, _id: &str) -> Result<StoragePath, DomainError> {
unimplemented!()
}
async fn get_parent_folder_id(&self, _path: &str) -> Result<String, DomainError> {
unimplemented!()
}
async fn get_blob_hash(&self, _file_id: &str) -> Result<String, DomainError> {
Ok(String::new())
}
async fn search_files_paginated(
&self,
_folder_id: Option<&str>,
_criteria: &crate::application::dtos::search_dto::SearchCriteriaDto,
_user_id: &str,
) -> Result<(Vec<File>, usize), DomainError> {
Ok((Vec::new(), 0))
}
async fn count_files(
&self,
_folder_id: Option<&str>,
_criteria: &crate::application::dtos::search_dto::SearchCriteriaDto,
_user_id: &str,
) -> Result<usize, DomainError> {
Ok(0)
}
async fn stream_files_in_subtree(
&self,
_folder_id: &str,
) -> Result<
Pin<Box<dyn Stream<Item = Result<File, DomainError>> + Send>>,
DomainError,
> {
Ok(Box::pin(futures::stream::empty()))
}
}
// ═══════════════════════════════════════════════════════════════════════════
// Tests — FileReadPort::get_file_for_owner (Repository layer, Solution C)
// ═══════════════════════════════════════════════════════════════════════════
#[tokio::test]
async fn get_file_for_owner_returns_file_for_correct_owner() {
let repo = MockFileReadPort::new();
repo.insert("file-1", "secret.txt", "alice");
let result = repo.get_file_for_owner("file-1", "alice").await;
assert!(result.is_ok(), "owner should be able to read own file");
assert_eq!(result.unwrap().id(), "file-1");
}
#[tokio::test]
async fn get_file_for_owner_rejects_wrong_owner() {
let repo = MockFileReadPort::new();
repo.insert("file-1", "secret.txt", "alice");
let result = repo.get_file_for_owner("file-1", "bob").await;
assert!(result.is_err(), "non-owner should be rejected");
// Must be NotFound, NOT Forbidden — avoids leaking existence
let err = result.unwrap_err();
let msg = format!("{}", err);
assert!(
msg.contains("not found") || msg.contains("NotFound"),
"error must be NotFound, got: {}",
msg
);
}
#[tokio::test]
async fn get_file_for_owner_returns_not_found_for_missing_file() {
let repo = MockFileReadPort::new();
let result = repo.get_file_for_owner("nonexistent", "alice").await;
assert!(result.is_err());
}
#[tokio::test]
async fn verify_file_owner_uses_default_impl() {
let repo = MockFileReadPort::new();
repo.insert("file-1", "secret.txt", "alice");
// Default impl delegates to get_file_for_owner and maps to ()
assert!(repo.verify_file_owner("file-1", "alice").await.is_ok());
assert!(repo.verify_file_owner("file-1", "bob").await.is_err());
}
// ═══════════════════════════════════════════════════════════════════════════
// Tests — FileManagementService _owned methods (Service layer, Solution B)
// ═══════════════════════════════════════════════════════════════════════════
//
// Note: FileManagementService::with_trash takes concrete types for the write
// repository (Arc<FileBlobWriteRepository>). We cannot construct real PG repos
// without a database. Instead, we test the verify_owner logic indirectly by
// testing the mock-based trait interactions at the port level, and document
// that integration tests hitting the real DB are the ultimate verification.
//
// The tests below verify the *contract*: _owned methods must call
// verify_owner before delegating, and verify_owner must fail-closed when
// no read repo is available.
#[tokio::test]
async fn verify_file_owner_delegates_to_read_port() {
// This test verifies the FileReadPort contract that verify_file_owner
// returns Ok for the correct owner and Err for others.
let read = MockFileReadPort::new();
read.insert("abc-123", "report.pdf", "user-42");
// Same user → Ok
let ok = read.verify_file_owner("abc-123", "user-42").await;
assert!(ok.is_ok(), "correct owner should pass verify_file_owner");
// Different user → Err
let err = read.verify_file_owner("abc-123", "attacker-99").await;
assert!(err.is_err(), "wrong owner should fail verify_file_owner");
}
#[tokio::test]
async fn owned_methods_require_ownership_check_first() {
// Simulate what the _owned methods do: verify_owner then delegate.
// We test with the mock read port to prove the sequence.
let read = MockFileReadPort::new();
read.insert("file-1", "data.csv", "owner-a");
// Step 1: verify_owner for correct owner → Ok
let step1 = read.verify_file_owner("file-1", "owner-a").await;
assert!(step1.is_ok());
// Step 2: verify_owner for attacker → Err, so the move/rename never executes
let step2 = read.verify_file_owner("file-1", "attacker").await;
assert!(step2.is_err());
}
// ═══════════════════════════════════════════════════════════════════════════
// Tests — Trait-level _owned method stubs (StubFileManagementUseCase)
// ═══════════════════════════════════════════════════════════════════════════
use crate::application::ports::file_ports::FileManagementUseCase;
use crate::common::stubs::StubFileManagementUseCase;
#[tokio::test]
async fn stub_move_file_owned_returns_ok() {
let stub = StubFileManagementUseCase;
let result = stub
.move_file_owned("file-1", "user-1", Some("folder-2".to_string()))
.await;
assert!(result.is_ok(), "stub should return Ok for move_file_owned");
}
#[tokio::test]
async fn stub_rename_file_owned_returns_ok() {
let stub = StubFileManagementUseCase;
let result = stub.rename_file_owned("file-1", "user-1", "new-name.txt").await;
assert!(result.is_ok(), "stub should return Ok for rename_file_owned");
}
use crate::application::ports::file_ports::FileRetrievalUseCase;
use crate::common::stubs::StubFileRetrievalUseCase;
#[tokio::test]
async fn stub_get_file_owned_returns_ok() {
let stub = StubFileRetrievalUseCase;
let result = stub.get_file_owned("file-1", "user-1").await;
assert!(result.is_ok(), "stub should return Ok for get_file_owned");
}
#[tokio::test]
async fn stub_get_file_optimized_owned_returns_ok() {
let stub = StubFileRetrievalUseCase;
let result = stub
.get_file_optimized_owned("file-1", "user-1", true, false)
.await;
assert!(
result.is_ok(),
"stub should return Ok for get_file_optimized_owned"
);
}
//! Tests for IDOR (Insecure Direct Object Reference) protection.
//!
//! Verifies that ownership checks at the repository and service layers
//! correctly reject access when the caller is not the file owner.
use bytes::Bytes;
use futures::Stream;
use std::collections::HashMap;
use std::pin::Pin;
use std::sync::Mutex;
use crate::application::ports::storage_ports::FileReadPort;
use crate::common::errors::DomainError;
use crate::domain::entities::file::File;
use crate::domain::services::path_service::StoragePath;
// ═══════════════════════════════════════════════════════════════════════════
// Mock repositories
// ═══════════════════════════════════════════════════════════════════════════
/// A simple in-memory mock that maps (file_id → (File, owner_id)).
struct MockFileReadPort {
/// file_id → (File, owner_id)
files: Mutex<HashMap<String, (File, String)>>,
}
impl MockFileReadPort {
fn new() -> Self {
Self {
files: Mutex::new(HashMap::new()),
}
}
/// Insert a test file owned by `owner_id`.
fn insert(&self, id: &str, name: &str, owner_id: &str) {
let file = File::new(
id.to_string(),
name.to_string(),
StoragePath::from_string(&format!("/{}", name)),
42,
"text/plain".to_string(),
None,
)
.unwrap();
self.files
.lock()
.unwrap()
.insert(id.to_string(), (file, owner_id.to_string()));
}
}
impl FileReadPort for MockFileReadPort {
async fn get_file(&self, id: &str) -> Result<File, DomainError> {
let files = self.files.lock().unwrap();
files
.get(id)
.map(|(f, _)| f.clone())
.ok_or_else(|| DomainError::not_found("File", id.to_string()))
}
async fn get_file_for_owner(&self, id: &str, owner_id: &str) -> Result<File, DomainError> {
let files = self.files.lock().unwrap();
match files.get(id) {
Some((file, actual_owner)) if actual_owner == owner_id => Ok(file.clone()),
// Return NotFound regardless — do not leak existence
_ => Err(DomainError::not_found("File", id.to_string())),
}
}
async fn list_files(&self, _folder_id: Option<&str>) -> Result<Vec<File>, DomainError> {
Ok(Vec::new())
}
async fn get_file_stream(
&self,
_id: &str,
) -> Result<Box<dyn Stream<Item = Result<Bytes, std::io::Error>> + Send>, DomainError> {
unimplemented!()
}
async fn get_file_range_stream(
&self,
_id: &str,
_start: u64,
_end: Option<u64>,
) -> Result<Box<dyn Stream<Item = Result<Bytes, std::io::Error>> + Send>, DomainError> {
unimplemented!()
}
async fn get_file_path(&self, _id: &str) -> Result<StoragePath, DomainError> {
unimplemented!()
}
async fn get_parent_folder_id(&self, _path: &str) -> Result<String, DomainError> {
unimplemented!()
}
async fn get_blob_hash(&self, _file_id: &str) -> Result<String, DomainError> {
Ok(String::new())
}
async fn search_files_paginated(
&self,
_folder_id: Option<&str>,
_criteria: &crate::application::dtos::search_dto::SearchCriteriaDto,
_user_id: &str,
) -> Result<(Vec<File>, usize), DomainError> {
Ok((Vec::new(), 0))
}
async fn count_files(
&self,
_folder_id: Option<&str>,
_criteria: &crate::application::dtos::search_dto::SearchCriteriaDto,
_user_id: &str,
) -> Result<usize, DomainError> {
Ok(0)
}
async fn stream_files_in_subtree(
&self,
_folder_id: &str,
) -> Result<Pin<Box<dyn Stream<Item = Result<File, DomainError>> + Send>>, DomainError> {
Ok(Box::pin(futures::stream::empty()))
}
}
// ═══════════════════════════════════════════════════════════════════════════
// Tests — FileReadPort::get_file_for_owner (Repository layer, Solution C)
// ═══════════════════════════════════════════════════════════════════════════
#[tokio::test]
async fn get_file_for_owner_returns_file_for_correct_owner() {
let repo = MockFileReadPort::new();
repo.insert("file-1", "secret.txt", "alice");
let result = repo.get_file_for_owner("file-1", "alice").await;
assert!(result.is_ok(), "owner should be able to read own file");
assert_eq!(result.unwrap().id(), "file-1");
}
#[tokio::test]
async fn get_file_for_owner_rejects_wrong_owner() {
let repo = MockFileReadPort::new();
repo.insert("file-1", "secret.txt", "alice");
let result = repo.get_file_for_owner("file-1", "bob").await;
assert!(result.is_err(), "non-owner should be rejected");
// Must be NotFound, NOT Forbidden — avoids leaking existence
let err = result.unwrap_err();
let msg = format!("{}", err);
assert!(
msg.contains("not found") || msg.contains("NotFound"),
"error must be NotFound, got: {}",
msg
);
}
#[tokio::test]
async fn get_file_for_owner_returns_not_found_for_missing_file() {
let repo = MockFileReadPort::new();
let result = repo.get_file_for_owner("nonexistent", "alice").await;
assert!(result.is_err());
}
#[tokio::test]
async fn verify_file_owner_uses_default_impl() {
let repo = MockFileReadPort::new();
repo.insert("file-1", "secret.txt", "alice");
// Default impl delegates to get_file_for_owner and maps to ()
assert!(repo.verify_file_owner("file-1", "alice").await.is_ok());
assert!(repo.verify_file_owner("file-1", "bob").await.is_err());
}
// ═══════════════════════════════════════════════════════════════════════════
// Tests — FileManagementService _owned methods (Service layer, Solution B)
// ═══════════════════════════════════════════════════════════════════════════
//
// Note: FileManagementService::with_trash takes concrete types for the write
// repository (Arc<FileBlobWriteRepository>). We cannot construct real PG repos
// without a database. Instead, we test the verify_owner logic indirectly by
// testing the mock-based trait interactions at the port level, and document
// that integration tests hitting the real DB are the ultimate verification.
//
// The tests below verify the *contract*: _owned methods must call
// verify_owner before delegating, and verify_owner must fail-closed when
// no read repo is available.
#[tokio::test]
async fn verify_file_owner_delegates_to_read_port() {
// This test verifies the FileReadPort contract that verify_file_owner
// returns Ok for the correct owner and Err for others.
let read = MockFileReadPort::new();
read.insert("abc-123", "report.pdf", "user-42");
// Same user → Ok
let ok = read.verify_file_owner("abc-123", "user-42").await;
assert!(ok.is_ok(), "correct owner should pass verify_file_owner");
// Different user → Err
let err = read.verify_file_owner("abc-123", "attacker-99").await;
assert!(err.is_err(), "wrong owner should fail verify_file_owner");
}
#[tokio::test]
async fn owned_methods_require_ownership_check_first() {
// Simulate what the _owned methods do: verify_owner then delegate.
// We test with the mock read port to prove the sequence.
let read = MockFileReadPort::new();
read.insert("file-1", "data.csv", "owner-a");
// Step 1: verify_owner for correct owner → Ok
let step1 = read.verify_file_owner("file-1", "owner-a").await;
assert!(step1.is_ok());
// Step 2: verify_owner for attacker → Err, so the move/rename never executes
let step2 = read.verify_file_owner("file-1", "attacker").await;
assert!(step2.is_err());
}
// ═══════════════════════════════════════════════════════════════════════════
// Tests — Trait-level _owned method stubs (StubFileManagementUseCase)
// ═══════════════════════════════════════════════════════════════════════════
use crate::application::ports::file_ports::FileManagementUseCase;
use crate::common::stubs::StubFileManagementUseCase;
#[tokio::test]
async fn stub_move_file_owned_returns_ok() {
let stub = StubFileManagementUseCase;
let result = stub
.move_file_owned("file-1", "user-1", Some("folder-2".to_string()))
.await;
assert!(result.is_ok(), "stub should return Ok for move_file_owned");
}
#[tokio::test]
async fn stub_rename_file_owned_returns_ok() {
let stub = StubFileManagementUseCase;
let result = stub
.rename_file_owned("file-1", "user-1", "new-name.txt")
.await;
assert!(
result.is_ok(),
"stub should return Ok for rename_file_owned"
);
}
use crate::application::ports::file_ports::FileRetrievalUseCase;
use crate::common::stubs::StubFileRetrievalUseCase;
#[tokio::test]
async fn stub_get_file_owned_returns_ok() {
let stub = StubFileRetrievalUseCase;
let result = stub.get_file_owned("file-1", "user-1").await;
assert!(result.is_ok(), "stub should return Ok for get_file_owned");
}
#[tokio::test]
async fn stub_get_file_optimized_owned_returns_ok() {
let stub = StubFileRetrievalUseCase;
let result = stub
.get_file_optimized_owned("file-1", "user-1", true, false)
.await;
assert!(
result.is_ok(),
"stub should return Ok for get_file_optimized_owned"
);
}
+2 -2
View File
@@ -20,10 +20,10 @@ pub mod trash_service;
pub mod wopi_lock_service;
pub mod wopi_token_service;
#[cfg(all(test, feature = "integration_tests"))]
mod trash_service_test;
#[cfg(test)]
mod idor_protection_test;
#[cfg(all(test, integration_tests))]
mod trash_service_test;
// Re-exportar para facilitar acceso
pub use file_management_service::FileManagementService;
+1 -1
View File
@@ -1,9 +1,9 @@
use crate::application::dtos::recent_dto::RecentItemDto;
use crate::application::ports::recent_ports::{RecentItemsRepositoryPort, RecentItemsUseCase};
use crate::common::errors::{DomainError, ErrorKind, Result};
use crate::infrastructure::repositories::pg::RecentItemsPgRepository;
use std::sync::Arc;
use tracing::info;
use crate::infrastructure::repositories::pg::RecentItemsPgRepository;
/// Implementation of the use case for managing recent items.
///
+2 -2
View File
@@ -15,10 +15,10 @@ use crate::application::ports::inbound::SearchUseCase;
use crate::application::ports::storage_ports::FileReadPort;
use crate::common::errors::Result;
use crate::domain::entities::folder::Folder;
use std::hash::{Hash, Hasher};
use crate::domain::repositories::folder_repository::FolderRepository;
use crate::infrastructure::repositories::pg::file_blob_read_repository::FileBlobReadRepository;
use crate::infrastructure::repositories::pg::folder_db_repository::FolderDbRepository;
use crate::domain::repositories::folder_repository::FolderRepository;
use std::hash::{Hash, Hasher};
/**
* High-performance search service implementation for files and folders.
+6 -6
View File
@@ -3,6 +3,11 @@ use std::sync::Arc;
use thiserror::Error;
use tokio::sync::Semaphore;
use crate::domain::repositories::folder_repository::FolderRepository;
use crate::infrastructure::repositories::pg::SharePgRepository;
use crate::infrastructure::repositories::pg::file_blob_read_repository::FileBlobReadRepository;
use crate::infrastructure::repositories::pg::folder_db_repository::FolderDbRepository;
use crate::infrastructure::services::password_hasher::Argon2PasswordHasher;
use crate::{
application::{
dtos::{
@@ -18,11 +23,6 @@ use crate::{
common::{config::AppConfig, errors::DomainError},
domain::entities::share::{Share, ShareItemType, SharePermissions},
};
use crate::infrastructure::services::password_hasher::Argon2PasswordHasher;
use crate::infrastructure::repositories::pg::file_blob_read_repository::FileBlobReadRepository;
use crate::infrastructure::repositories::pg::folder_db_repository::FolderDbRepository;
use crate::infrastructure::repositories::pg::SharePgRepository;
use crate::domain::repositories::folder_repository::FolderRepository;
#[derive(Debug, Error)]
pub enum ShareServiceError {
@@ -394,7 +394,7 @@ impl ShareUseCase for ShareService {
}
}
#[cfg(feature = "integration_tests")]
#[cfg(integration_tests)]
mod tests {
use super::*;
use crate::application::dtos::share_dto::SharePermissionsDto;
@@ -1,11 +1,11 @@
use crate::application::ports::auth_ports::UserStoragePort;
use crate::application::ports::storage_ports::StorageUsagePort;
use crate::common::errors::DomainError;
use crate::infrastructure::repositories::pg::UserPgRepository;
use sqlx::PgPool;
use std::sync::Arc;
use tokio::task;
use tracing::{debug, error, info};
use crate::infrastructure::repositories::pg::UserPgRepository;
/**
* Service for managing and updating user storage usage statistics.
+1 -1
View File
@@ -7,12 +7,12 @@ use crate::application::ports::storage_ports::{FileReadPort, FileWritePort};
use crate::application::ports::trash_ports::TrashUseCase;
use crate::common::errors::{DomainError, ErrorKind, Result};
use crate::domain::entities::trashed_item::{TrashedItem, TrashedItemType};
use crate::domain::repositories::folder_repository::FolderRepository;
use crate::domain::repositories::trash_repository::TrashRepository;
use crate::infrastructure::repositories::pg::file_blob_read_repository::FileBlobReadRepository;
use crate::infrastructure::repositories::pg::file_blob_write_repository::FileBlobWriteRepository;
use crate::infrastructure::repositories::pg::folder_db_repository::FolderDbRepository;
use crate::infrastructure::repositories::pg::trash_db_repository::TrashDbRepository;
use crate::domain::repositories::folder_repository::FolderRepository;
/**
* Application service for trash operations.
@@ -499,7 +499,7 @@ impl FolderRepository for MockFolderRepository {
}
}
#[cfg(feature = "integration_tests")]
#[cfg(integration_tests)]
mod tests {
use super::*;
use crate::application::ports::trash_ports::TrashUseCase;