Skip to main content

backbone_bucket/presentation/http/
file_share_handler.rs

1//! FileShare REST handlers
2//!
3//! Generated by metaphor-schema. Do not edit manually.
4//!
5//! Uses Axum and backbone-core's BackboneCrudHandler for all 12 CRUD endpoints.
6
7use std::collections::HashMap;
8use std::sync::Arc;
9
10use axum::Router;
11use serde::{Deserialize, Serialize};
12use uuid::Uuid;
13use chrono::{DateTime, Utc};
14
15// Backbone framework imports
16use backbone_core::http::{ApiResponse, BackboneCrudHandler};
17
18// Auth integration (optional)
19#[cfg(feature = "auth")]
20use backbone_auth::middleware::AuthContext;
21#[cfg(feature = "auth")]
22use backbone_auth::AuthMiddleware;
23
24// Domain imports
25use crate::domain::entity::*;
26use crate::application::service::{FileShareService, ServiceError};
27
28// DTO imports
29use crate::presentation::dto::{CreateFileShareDto, UpdateFileShareDto, PatchFileShareDto, FileShareResponseDto};
30
31use crate::domain::state_machine::{FileShareState, FileShareStateMachine, FileShareTransition};
32
33/// Application error type
34#[derive(Debug, thiserror::Error)]
35pub enum FileShareError {
36    #[error("Not found: {0}")]
37    NotFound(String),
38    #[error("Validation error: {0}")]
39    Validation(String),
40    #[error("Database error: {0}")]
41    Database(String),
42    #[error("Internal error: {0}")]
43    Internal(String),
44    // Domain-specific errors from hook rules
45    #[error("Share token must be 32-64 characters: {0}")]
46    InvalidTokenLength(String),
47    #[error("Share token must be alphanumeric: {0}")]
48    InvalidTokenChars(String),
49    #[error("Cannot share inactive or quarantined files: {0}")]
50    FileNotActive(String),
51    #[error("Only file owner can create shares: {0}")]
52    NotFileOwner(String),
53    #[error("Expiration date must be in the future: {0}")]
54    ExpiredDate(String),
55    #[error("Maximum downloads must be positive: {0}")]
56    InvalidMaxDownloads(String),
57    #[error("User shares must specify recipients: {0}")]
58    MissingRecipients(String),
59    #[error("Cannot modify inactive shares: {0}")]
60    ShareInactive(String),
61}
62
63impl From<ServiceError> for FileShareError {
64    fn from(err: ServiceError) -> Self {
65        match err {
66            ServiceError::NotFound => Self::NotFound(err.to_string()),
67            ServiceError::Validation(ref msg) => Self::Validation(msg.clone()),
68            ServiceError::AlreadyExists(ref msg) => Self::Validation(msg.clone()),
69            ServiceError::Repository(ref e) => Self::Database(e.to_string()),
70            ServiceError::Internal(ref msg) => Self::Internal(msg.clone()),
71            ServiceError::Violations(_) => Self::Validation(err.to_string()),
72        }
73    }
74}
75
76impl axum::response::IntoResponse for FileShareError {
77    fn into_response(self) -> axum::response::Response {
78        use axum::http::StatusCode;
79        use axum::Json;
80
81        let (status, code) = match &self {
82            Self::NotFound(_) => (StatusCode::NOT_FOUND, "FILESHARE_NOT_FOUND"),
83            Self::Validation(_) => (StatusCode::BAD_REQUEST, "FILESHARE_VALIDATION_ERROR"),
84            Self::Database(_) => (StatusCode::INTERNAL_SERVER_ERROR, "FILESHARE_DATABASE_ERROR"),
85            Self::Internal(_) => (StatusCode::INTERNAL_SERVER_ERROR, "FILESHARE_INTERNAL_ERROR"),
86            Self::InvalidTokenLength(_) => (StatusCode::UNPROCESSABLE_ENTITY, "FILESHARE_INVALID_TOKEN_LENGTH"),
87            Self::InvalidTokenChars(_) => (StatusCode::UNPROCESSABLE_ENTITY, "FILESHARE_INVALID_TOKEN_CHARS"),
88            Self::FileNotActive(_) => (StatusCode::UNPROCESSABLE_ENTITY, "FILESHARE_FILE_NOT_ACTIVE"),
89            Self::NotFileOwner(_) => (StatusCode::UNPROCESSABLE_ENTITY, "FILESHARE_NOT_FILE_OWNER"),
90            Self::ExpiredDate(_) => (StatusCode::UNPROCESSABLE_ENTITY, "FILESHARE_EXPIRED_DATE"),
91            Self::InvalidMaxDownloads(_) => (StatusCode::UNPROCESSABLE_ENTITY, "FILESHARE_INVALID_MAX_DOWNLOADS"),
92            Self::MissingRecipients(_) => (StatusCode::UNPROCESSABLE_ENTITY, "FILESHARE_MISSING_RECIPIENTS"),
93            Self::ShareInactive(_) => (StatusCode::UNPROCESSABLE_ENTITY, "FILESHARE_SHARE_INACTIVE"),
94        };
95
96        let body = serde_json::json!({
97            "success": false,
98            "error": code,
99            "message": self.to_string(),
100        });
101
102        (status, Json(body)).into_response()
103    }
104}
105
106/// Domain-specific error codes for FileShare
107pub mod file_share_errors {
108    pub const INVALID_TOKEN_LENGTH: &str = "FILESHARE_INVALID_TOKEN_LENGTH";
109    pub const INVALID_TOKEN_CHARS: &str = "FILESHARE_INVALID_TOKEN_CHARS";
110    pub const FILE_NOT_ACTIVE: &str = "FILESHARE_FILE_NOT_ACTIVE";
111    pub const NOT_FILE_OWNER: &str = "FILESHARE_NOT_FILE_OWNER";
112    pub const EXPIRED_DATE: &str = "FILESHARE_EXPIRED_DATE";
113    pub const INVALID_MAX_DOWNLOADS: &str = "FILESHARE_INVALID_MAX_DOWNLOADS";
114    pub const MISSING_RECIPIENTS: &str = "FILESHARE_MISSING_RECIPIENTS";
115    pub const SHARE_INACTIVE: &str = "FILESHARE_SHARE_INACTIVE";
116}
117
118// =============================================================================
119// Route Configuration
120// =============================================================================
121
122/// Create Axum router with all 16 Backbone endpoints for FileShare.
123///
124/// # Routes
125///
126/// | Method | Path | Description |
127/// |--------|------|-------------|
128/// | GET | /file_shares | List with pagination |
129/// | POST | /file_shares | Create new |
130/// | GET | /file_shares/:id | Get by ID |
131/// | PUT | /file_shares/:id | Full update |
132/// | PATCH | /file_shares/:id | Partial update |
133/// | DELETE | /file_shares/:id | Soft delete |
134/// | POST | /file_shares/bulk | Bulk create |
135/// | POST | /file_shares/upsert | Upsert |
136/// | GET | /file_shares/trash | List deleted |
137/// | POST | /file_shares/:id/restore | Restore |
138/// | DELETE | /file_shares/empty | Empty trash |
139/// | GET | /file_shares/:id/deleted | Get deleted by ID |
140/// | DELETE | /file_shares/trash/:id | Permanent delete from trash |
141/// | GET | /file_shares/count | Count active entities |
142/// | GET | /file_shares/trash/count | Count deleted entities |
143///
144/// # Example
145///
146/// ```text
147/// let service = Arc::new(FileShareService::with_repository(repository));
148/// let router = create_file_share_routes(service);
149/// ```
150pub fn create_file_share_routes(service: Arc<FileShareService>) -> Router {
151    BackboneCrudHandler::<FileShareService, FileShare, CreateFileShareDto, UpdateFileShareDto, FileShareResponseDto>::routes(
152        service,
153        "/file_shares",
154    )
155}
156
157/// Create Axum router with only the read (GET) endpoints for FileShare.
158///
159/// Safe for public, unauthenticated exposure (e.g., reference data).
160/// Mutations must be served separately via `create_file_share_write_routes`,
161/// typically wrapped in an auth middleware layer.
162pub fn create_file_share_read_routes(service: Arc<FileShareService>) -> Router {
163    BackboneCrudHandler::<FileShareService, FileShare, CreateFileShareDto, UpdateFileShareDto, FileShareResponseDto>::read_routes(
164        service,
165        "/file_shares",
166    )
167}
168
169/// Create Axum router with only the write (mutation) endpoints for FileShare.
170///
171/// These routes must NOT be publicly exposed. Wrap them with an auth
172/// middleware before nesting into the application router.
173///
174/// # This is unguarded generic CRUD, not a validated write path
175///
176/// These are plain create/update/patch/delete mutations over the entity row —
177/// they bypass all business invariants. If the module exposes a validated write
178/// service (e.g. a command router over its domain engine), serve THAT instead
179/// for any mutation that must respect domain rules.
180pub fn create_file_share_write_routes(service: Arc<FileShareService>) -> Router {
181    BackboneCrudHandler::<FileShareService, FileShare, CreateFileShareDto, UpdateFileShareDto, FileShareResponseDto>::write_routes(
182        service,
183        "/file_shares",
184    )
185}
186
187/// Create authenticated routes with auth middleware.
188///
189/// Requires the `auth` feature flag. The `AuthMiddleware` implementation
190/// is responsible for extracting and validating tokens, then providing
191/// an `AuthContext` via request extensions.
192#[cfg(feature = "auth")]
193pub fn create_protected_file_share_routes<A: AuthMiddleware + Send + Sync + 'static>(
194    service: Arc<FileShareService>,
195    auth: Arc<A>,
196) -> Router {
197    use axum::middleware;
198    use axum::response::IntoResponse;
199
200    let auth_layer = auth.clone();
201    create_file_share_routes(service)
202        .layer(middleware::from_fn(move |mut req: axum::extract::Request, next: axum::middleware::Next| {
203            let auth = auth_layer.clone();
204            async move {
205                let token = req.headers()
206                    .get(axum::http::header::AUTHORIZATION)
207                    .and_then(|h| h.to_str().ok())
208                    .and_then(|raw| raw.strip_prefix("Bearer ").or_else(|| raw.strip_prefix("bearer ")))
209                    .unwrap_or("");
210                match auth.authenticate(token).await {
211                    Ok(ctx) => {
212                        req.extensions_mut().insert(ctx);
213                        next.run(req).await
214                    }
215                    Err(_) => {
216                        (axum::http::StatusCode::UNAUTHORIZED,
217                         axum::Json(serde_json::json!({
218                             "success": false,
219                             "error": "unauthorized",
220                             "message": "Authentication required"
221                         }))
222                        ).into_response()
223                    }
224                }
225            }
226        }))
227}
228
229// =============================================================================
230// State Transition Handlers
231// =============================================================================
232
233/// Execute expire transition on a FileShare.
234///
235/// POST /file_shares/:id/transitions/expire
236pub async fn expire_transition(
237    axum::extract::State(service): axum::extract::State<Arc<FileShareService>>,
238    axum::extract::Path(id): axum::extract::Path<String>,
239    #[cfg(feature = "auth")] axum::Extension(auth): axum::Extension<AuthContext>,
240) -> impl axum::response::IntoResponse {
241    use axum::{http::StatusCode, Json};
242
243    // Get current entity
244    let entity = match service.get_by_id(&id).await {
245        Ok(Some(e)) => e,
246        Ok(None) => return (StatusCode::NOT_FOUND, Json(ApiResponse::<serde_json::Value>::not_found("FileShare", &id))),
247        Err(e) => return (StatusCode::INTERNAL_SERVER_ERROR, Json(ApiResponse::<serde_json::Value>::error(e.to_string()))),
248    };
249
250    // Check permission (if auth enabled)
251    #[cfg(feature = "auth")]
252    {
253        let allowed_roles = FileShareTransition::Expire.allowed_roles();
254        let has_specific_perm = auth.permissions.iter().any(|p| p == "file_share:transition:expire");
255        let has_update_perm = auth.permissions.iter().any(|p| p == "file_share:update");
256        let has_role = auth.roles.iter().any(|r| allowed_roles.contains(&r.as_str()));
257        if !has_specific_perm && !has_role {
258            if !has_update_perm {
259                return (StatusCode::FORBIDDEN, Json(ApiResponse::<serde_json::Value>::error("Insufficient permissions for expire transition")));
260            }
261            tracing::warn!(target: "backbone::write_guard", entity = "FileShare", verb = "expire", code = "transition_by_update_permission", "a transition granted only by file_share:update, running in shadow; it needs file_share:transition:expire or a role of ["system"]");
262        }
263    }
264
265    // Create state machine from entity's actual status and validate transition
266    let current_state: FileShareState = match entity.status.to_string().parse() {
267        Ok(s) => s,
268        Err(_) => return (StatusCode::CONFLICT, Json(ApiResponse::<serde_json::Value>::error("The stored state is not a state of this machine"))),
269    };
270    let sm = FileShareStateMachine::from_state(current_state);
271    if !sm.can_transition(FileShareTransition::Expire) {
272        return (StatusCode::BAD_REQUEST, Json(ApiResponse::<serde_json::Value>::error("Transition not allowed from current state")));
273    }
274
275    // Guard `expires_at != null && expires_at <= now()` not compiled (reads the writer, the time or the row before the write); the transition is not checked against it.
276    // Apply transition via partial update
277    let mut fields: HashMap<String, serde_json::Value> = HashMap::new();
278    fields.insert("status".to_string(), serde_json::Value::String("expired".to_string()));
279
280    match backbone_core::write_guard::as_transition("expire", service.partial_update(&id, fields)).await {
281        Ok(Some(updated)) => {
282            let response: FileShareResponseDto = updated.into();
283            (StatusCode::OK, Json(ApiResponse::ok(backbone_core::http::without_secrets::<FileShare, _>(response))))
284        }
285        Ok(None) => (StatusCode::NOT_FOUND, Json(ApiResponse::<serde_json::Value>::not_found("FileShare", &id))),
286        Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, Json(ApiResponse::<serde_json::Value>::error(e.to_string()))),
287    }
288}
289
290/// Execute exhaust transition on a FileShare.
291///
292/// POST /file_shares/:id/transitions/exhaust
293pub async fn exhaust_transition(
294    axum::extract::State(service): axum::extract::State<Arc<FileShareService>>,
295    axum::extract::Path(id): axum::extract::Path<String>,
296    #[cfg(feature = "auth")] axum::Extension(auth): axum::Extension<AuthContext>,
297) -> impl axum::response::IntoResponse {
298    use axum::{http::StatusCode, Json};
299
300    // Get current entity
301    let entity = match service.get_by_id(&id).await {
302        Ok(Some(e)) => e,
303        Ok(None) => return (StatusCode::NOT_FOUND, Json(ApiResponse::<serde_json::Value>::not_found("FileShare", &id))),
304        Err(e) => return (StatusCode::INTERNAL_SERVER_ERROR, Json(ApiResponse::<serde_json::Value>::error(e.to_string()))),
305    };
306
307    // Check permission (if auth enabled)
308    #[cfg(feature = "auth")]
309    {
310        let allowed_roles = FileShareTransition::Exhaust.allowed_roles();
311        let has_specific_perm = auth.permissions.iter().any(|p| p == "file_share:transition:exhaust");
312        let has_update_perm = auth.permissions.iter().any(|p| p == "file_share:update");
313        let has_role = auth.roles.iter().any(|r| allowed_roles.contains(&r.as_str()));
314        if !has_specific_perm && !has_role {
315            if !has_update_perm {
316                return (StatusCode::FORBIDDEN, Json(ApiResponse::<serde_json::Value>::error("Insufficient permissions for exhaust transition")));
317            }
318            tracing::warn!(target: "backbone::write_guard", entity = "FileShare", verb = "exhaust", code = "transition_by_update_permission", "a transition granted only by file_share:update, running in shadow; it needs file_share:transition:exhaust or a role of ["system"]");
319        }
320    }
321
322    // Create state machine from entity's actual status and validate transition
323    let current_state: FileShareState = match entity.status.to_string().parse() {
324        Ok(s) => s,
325        Err(_) => return (StatusCode::CONFLICT, Json(ApiResponse::<serde_json::Value>::error("The stored state is not a state of this machine"))),
326    };
327    let sm = FileShareStateMachine::from_state(current_state);
328    if !sm.can_transition(FileShareTransition::Exhaust) {
329        return (StatusCode::BAD_REQUEST, Json(ApiResponse::<serde_json::Value>::error("Transition not allowed from current state")));
330    }
331
332    {
333        use backbone_core::row_rule as r;
334        let row = &serde_json::to_value(&entity).unwrap_or_default();
335        let state = row.get("status").and_then(|v| v.as_str()).unwrap_or_default();
336        // Guard: max_downloads != null && download_count >= max_downloads
337        if ["active"].contains(&state) && !r::holds(&r::and(r::is_not_null(r::field(row, "max_downloads")), r::ge(r::field(row, "download_count"), r::field(row, "max_downloads")))) {
338            return (StatusCode::UNPROCESSABLE_ENTITY, Json(ApiResponse::<serde_json::Value>::error("The exhaust transition's guard does not hold: max_downloads != null && download_count >= max_downloads")));
339        }
340    }
341
342    // Apply transition via partial update
343    let mut fields: HashMap<String, serde_json::Value> = HashMap::new();
344    fields.insert("status".to_string(), serde_json::Value::String("exhausted".to_string()));
345
346    match backbone_core::write_guard::as_transition("exhaust", service.partial_update(&id, fields)).await {
347        Ok(Some(updated)) => {
348            let response: FileShareResponseDto = updated.into();
349            (StatusCode::OK, Json(ApiResponse::ok(backbone_core::http::without_secrets::<FileShare, _>(response))))
350        }
351        Ok(None) => (StatusCode::NOT_FOUND, Json(ApiResponse::<serde_json::Value>::not_found("FileShare", &id))),
352        Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, Json(ApiResponse::<serde_json::Value>::error(e.to_string()))),
353    }
354}
355
356/// Execute revoke transition on a FileShare.
357///
358/// POST /file_shares/:id/transitions/revoke
359pub async fn revoke_transition(
360    axum::extract::State(service): axum::extract::State<Arc<FileShareService>>,
361    axum::extract::Path(id): axum::extract::Path<String>,
362    #[cfg(feature = "auth")] axum::Extension(auth): axum::Extension<AuthContext>,
363) -> impl axum::response::IntoResponse {
364    use axum::{http::StatusCode, Json};
365
366    // Get current entity
367    let entity = match service.get_by_id(&id).await {
368        Ok(Some(e)) => e,
369        Ok(None) => return (StatusCode::NOT_FOUND, Json(ApiResponse::<serde_json::Value>::not_found("FileShare", &id))),
370        Err(e) => return (StatusCode::INTERNAL_SERVER_ERROR, Json(ApiResponse::<serde_json::Value>::error(e.to_string()))),
371    };
372
373    // Check permission (if auth enabled)
374    #[cfg(feature = "auth")]
375    {
376        let allowed_roles = FileShareTransition::Revoke.allowed_roles();
377        let has_specific_perm = auth.permissions.iter().any(|p| p == "file_share:transition:revoke");
378        let has_update_perm = auth.permissions.iter().any(|p| p == "file_share:update");
379        let has_role = auth.roles.iter().any(|r| allowed_roles.contains(&r.as_str()));
380        if !has_specific_perm && !has_role {
381            if !has_update_perm {
382                return (StatusCode::FORBIDDEN, Json(ApiResponse::<serde_json::Value>::error("Insufficient permissions for revoke transition")));
383            }
384            tracing::warn!(target: "backbone::write_guard", entity = "FileShare", verb = "revoke", code = "transition_by_update_permission", "a transition granted only by file_share:update, running in shadow; it needs file_share:transition:revoke or a role of ["admin", "owner"]");
385        }
386    }
387
388    // Create state machine from entity's actual status and validate transition
389    let current_state: FileShareState = match entity.status.to_string().parse() {
390        Ok(s) => s,
391        Err(_) => return (StatusCode::CONFLICT, Json(ApiResponse::<serde_json::Value>::error("The stored state is not a state of this machine"))),
392    };
393    let sm = FileShareStateMachine::from_state(current_state);
394    if !sm.can_transition(FileShareTransition::Revoke) {
395        return (StatusCode::BAD_REQUEST, Json(ApiResponse::<serde_json::Value>::error("Transition not allowed from current state")));
396    }
397
398    // Guard `$actor.id == owner_id || $actor.has_role('admin')` not compiled (reads the writer, the time or the row before the write); the transition is not checked against it.
399    // Apply transition via partial update
400    let mut fields: HashMap<String, serde_json::Value> = HashMap::new();
401    fields.insert("status".to_string(), serde_json::Value::String("revoked".to_string()));
402
403    match backbone_core::write_guard::as_transition("revoke", service.partial_update(&id, fields)).await {
404        Ok(Some(updated)) => {
405            let response: FileShareResponseDto = updated.into();
406            (StatusCode::OK, Json(ApiResponse::ok(backbone_core::http::without_secrets::<FileShare, _>(response))))
407        }
408        Ok(None) => (StatusCode::NOT_FOUND, Json(ApiResponse::<serde_json::Value>::not_found("FileShare", &id))),
409        Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, Json(ApiResponse::<serde_json::Value>::error(e.to_string()))),
410    }
411}
412
413/// Create routes for state transitions.
414pub fn create_file_share_transition_routes(service: Arc<FileShareService>) -> Router {
415    use axum::routing::post;
416
417    Router::new()
418        .route("/file_shares/:id/transitions/expire", post(expire_transition))
419        .route("/file_shares/:id/transitions/exhaust", post(exhaust_transition))
420        .route("/file_shares/:id/transitions/revoke", post(revoke_transition))
421        .with_state(service)
422}
423