1use std::collections::HashMap;
8use std::sync::Arc;
9
10use axum::Router;
11use serde::{Deserialize, Serialize};
12use uuid::Uuid;
13
14use backbone_core::http::{ApiResponse, BackboneCrudHandler};
16
17#[cfg(feature = "auth")]
19use backbone_auth::middleware::AuthContext;
20#[cfg(feature = "auth")]
21use backbone_auth::AuthMiddleware;
22
23use crate::domain::entity::*;
25use crate::application::service::{BucketService, ServiceError};
26
27use crate::presentation::dto::{CreateBucketDto, UpdateBucketDto, PatchBucketDto, BucketResponseDto};
29
30use crate::domain::state_machine::{BucketState, BucketStateMachine, BucketTransition};
31
32#[derive(Debug, thiserror::Error)]
34pub enum BucketError {
35 #[error("Not found: {0}")]
36 NotFound(String),
37 #[error("Validation error: {0}")]
38 Validation(String),
39 #[error("Database error: {0}")]
40 Database(String),
41 #[error("Internal error: {0}")]
42 Internal(String),
43 #[error("Bucket name must be 1-255 characters: {0}")]
45 InvalidNameLength(String),
46 #[error("Bucket name must contain only alphanumeric characters, underscores, and hyphens: {0}")]
47 InvalidNameChars(String),
48 #[error("Bucket slug must be 1-255 characters: {0}")]
49 InvalidSlugLength(String),
50 #[error("Bucket slug must be lowercase with hyphens only: {0}")]
51 InvalidSlugChars(String),
52 #[error("Root path too long: {0}")]
53 PathTooLong(String),
54 #[error("Path traversal not allowed in root path: {0}")]
55 PathTraversal(String),
56 #[error("Cannot modify deleted buckets: {0}")]
57 BucketDeleted(String),
58 #[error("Bucket slug is already taken: {0}")]
59 SlugExists(String),
60}
61
62impl From<ServiceError> for BucketError {
63 fn from(err: ServiceError) -> Self {
64 match err {
65 ServiceError::NotFound => Self::NotFound(err.to_string()),
66 ServiceError::Validation(ref msg) => Self::Validation(msg.clone()),
67 ServiceError::AlreadyExists(ref msg) => Self::Validation(msg.clone()),
68 ServiceError::Repository(ref e) => Self::Database(e.to_string()),
69 ServiceError::Internal(ref msg) => Self::Internal(msg.clone()),
70 ServiceError::Violations(_) => Self::Validation(err.to_string()),
71 }
72 }
73}
74
75impl axum::response::IntoResponse for BucketError {
76 fn into_response(self) -> axum::response::Response {
77 use axum::http::StatusCode;
78 use axum::Json;
79
80 let (status, code) = match &self {
81 Self::NotFound(_) => (StatusCode::NOT_FOUND, "BUCKET_NOT_FOUND"),
82 Self::Validation(_) => (StatusCode::BAD_REQUEST, "BUCKET_VALIDATION_ERROR"),
83 Self::Database(_) => (StatusCode::INTERNAL_SERVER_ERROR, "BUCKET_DATABASE_ERROR"),
84 Self::Internal(_) => (StatusCode::INTERNAL_SERVER_ERROR, "BUCKET_INTERNAL_ERROR"),
85 Self::InvalidNameLength(_) => (StatusCode::UNPROCESSABLE_ENTITY, "BUCKET_INVALID_NAME_LENGTH"),
86 Self::InvalidNameChars(_) => (StatusCode::UNPROCESSABLE_ENTITY, "BUCKET_INVALID_NAME_CHARS"),
87 Self::InvalidSlugLength(_) => (StatusCode::UNPROCESSABLE_ENTITY, "BUCKET_INVALID_SLUG_LENGTH"),
88 Self::InvalidSlugChars(_) => (StatusCode::UNPROCESSABLE_ENTITY, "BUCKET_INVALID_SLUG_CHARS"),
89 Self::PathTooLong(_) => (StatusCode::UNPROCESSABLE_ENTITY, "BUCKET_PATH_TOO_LONG"),
90 Self::PathTraversal(_) => (StatusCode::UNPROCESSABLE_ENTITY, "BUCKET_PATH_TRAVERSAL"),
91 Self::BucketDeleted(_) => (StatusCode::UNPROCESSABLE_ENTITY, "BUCKET_BUCKET_DELETED"),
92 Self::SlugExists(_) => (StatusCode::UNPROCESSABLE_ENTITY, "BUCKET_SLUG_EXISTS"),
93 };
94
95 let body = serde_json::json!({
96 "success": false,
97 "error": code,
98 "message": self.to_string(),
99 });
100
101 (status, Json(body)).into_response()
102 }
103}
104
105pub mod bucket_errors {
107 pub const INVALID_NAME_LENGTH: &str = "BUCKET_INVALID_NAME_LENGTH";
108 pub const INVALID_NAME_CHARS: &str = "BUCKET_INVALID_NAME_CHARS";
109 pub const INVALID_SLUG_LENGTH: &str = "BUCKET_INVALID_SLUG_LENGTH";
110 pub const INVALID_SLUG_CHARS: &str = "BUCKET_INVALID_SLUG_CHARS";
111 pub const PATH_TOO_LONG: &str = "BUCKET_PATH_TOO_LONG";
112 pub const PATH_TRAVERSAL: &str = "BUCKET_PATH_TRAVERSAL";
113 pub const BUCKET_DELETED: &str = "BUCKET_BUCKET_DELETED";
114 pub const SLUG_EXISTS: &str = "BUCKET_SLUG_EXISTS";
115}
116
117pub fn create_bucket_routes(service: Arc<BucketService>) -> Router {
150 BackboneCrudHandler::<BucketService, Bucket, CreateBucketDto, UpdateBucketDto, BucketResponseDto>::routes(
151 service,
152 "/buckets",
153 )
154}
155
156pub fn create_bucket_read_routes(service: Arc<BucketService>) -> Router {
162 BackboneCrudHandler::<BucketService, Bucket, CreateBucketDto, UpdateBucketDto, BucketResponseDto>::read_routes(
163 service,
164 "/buckets",
165 )
166}
167
168pub fn create_bucket_write_routes(service: Arc<BucketService>) -> Router {
180 BackboneCrudHandler::<BucketService, Bucket, CreateBucketDto, UpdateBucketDto, BucketResponseDto>::write_routes(
181 service,
182 "/buckets",
183 )
184}
185
186#[cfg(feature = "auth")]
192pub fn create_protected_bucket_routes<A: AuthMiddleware + Send + Sync + 'static>(
193 service: Arc<BucketService>,
194 auth: Arc<A>,
195) -> Router {
196 use axum::middleware;
197 use axum::response::IntoResponse;
198
199 let auth_layer = auth.clone();
200 create_bucket_routes(service)
201 .layer(middleware::from_fn(move |mut req: axum::extract::Request, next: axum::middleware::Next| {
202 let auth = auth_layer.clone();
203 async move {
204 let token = req.headers()
205 .get(axum::http::header::AUTHORIZATION)
206 .and_then(|h| h.to_str().ok())
207 .and_then(|raw| raw.strip_prefix("Bearer ").or_else(|| raw.strip_prefix("bearer ")))
208 .unwrap_or("");
209 match auth.authenticate(token).await {
210 Ok(ctx) => {
211 req.extensions_mut().insert(ctx);
212 next.run(req).await
213 }
214 Err(_) => {
215 (axum::http::StatusCode::UNAUTHORIZED,
216 axum::Json(serde_json::json!({
217 "success": false,
218 "error": "unauthorized",
219 "message": "Authentication required"
220 }))
221 ).into_response()
222 }
223 }
224 }
225 }))
226}
227
228pub async fn lock_transition(
236 axum::extract::State(service): axum::extract::State<Arc<BucketService>>,
237 axum::extract::Path(id): axum::extract::Path<String>,
238 #[cfg(feature = "auth")] axum::Extension(auth): axum::Extension<AuthContext>,
239) -> impl axum::response::IntoResponse {
240 use axum::{http::StatusCode, Json};
241
242 let entity = match service.get_by_id(&id).await {
244 Ok(Some(e)) => e,
245 Ok(None) => return (StatusCode::NOT_FOUND, Json(ApiResponse::<BucketResponseDto>::not_found("Bucket", &id))),
246 Err(e) => return (StatusCode::INTERNAL_SERVER_ERROR, Json(ApiResponse::<BucketResponseDto>::error(e.to_string()))),
247 };
248
249 #[cfg(feature = "auth")]
251 {
252 let allowed_roles = BucketTransition::Lock.allowed_roles();
253 let has_specific_perm = auth.permissions.iter().any(|p| p == "bucket:transition:lock");
254 let has_update_perm = auth.permissions.iter().any(|p| p == "bucket:update");
255 let has_role = auth.roles.iter().any(|r| allowed_roles.contains(&r.as_str()));
256 if !has_specific_perm && !has_update_perm && !has_role {
257 return (StatusCode::FORBIDDEN, Json(ApiResponse::<BucketResponseDto>::error("Insufficient permissions for lock transition")));
258 }
259 }
260
261 let current_state: BucketState = entity.status.to_string().parse()
263 .unwrap_or(BucketState::default());
264 let sm = BucketStateMachine::from_state(current_state);
265 if !sm.can_transition(BucketTransition::Lock) {
266 return (StatusCode::BAD_REQUEST, Json(ApiResponse::<BucketResponseDto>::error("Transition not allowed from current state")));
267 }
268
269 let mut fields: HashMap<String, serde_json::Value> = HashMap::new();
271 fields.insert("status".to_string(), serde_json::Value::String("Readonly".to_string()));
272
273 match service.partial_update(&id, fields).await {
274 Ok(Some(updated)) => {
275 let response: BucketResponseDto = updated.into();
276 (StatusCode::OK, Json(ApiResponse::ok(response)))
277 }
278 Ok(None) => (StatusCode::NOT_FOUND, Json(ApiResponse::<BucketResponseDto>::not_found("Bucket", &id))),
279 Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, Json(ApiResponse::<BucketResponseDto>::error(e.to_string()))),
280 }
281}
282
283pub async fn unlock_transition(
287 axum::extract::State(service): axum::extract::State<Arc<BucketService>>,
288 axum::extract::Path(id): axum::extract::Path<String>,
289 #[cfg(feature = "auth")] axum::Extension(auth): axum::Extension<AuthContext>,
290) -> impl axum::response::IntoResponse {
291 use axum::{http::StatusCode, Json};
292
293 let entity = match service.get_by_id(&id).await {
295 Ok(Some(e)) => e,
296 Ok(None) => return (StatusCode::NOT_FOUND, Json(ApiResponse::<BucketResponseDto>::not_found("Bucket", &id))),
297 Err(e) => return (StatusCode::INTERNAL_SERVER_ERROR, Json(ApiResponse::<BucketResponseDto>::error(e.to_string()))),
298 };
299
300 #[cfg(feature = "auth")]
302 {
303 let allowed_roles = BucketTransition::Unlock.allowed_roles();
304 let has_specific_perm = auth.permissions.iter().any(|p| p == "bucket:transition:unlock");
305 let has_update_perm = auth.permissions.iter().any(|p| p == "bucket:update");
306 let has_role = auth.roles.iter().any(|r| allowed_roles.contains(&r.as_str()));
307 if !has_specific_perm && !has_update_perm && !has_role {
308 return (StatusCode::FORBIDDEN, Json(ApiResponse::<BucketResponseDto>::error("Insufficient permissions for unlock transition")));
309 }
310 }
311
312 let current_state: BucketState = entity.status.to_string().parse()
314 .unwrap_or(BucketState::default());
315 let sm = BucketStateMachine::from_state(current_state);
316 if !sm.can_transition(BucketTransition::Unlock) {
317 return (StatusCode::BAD_REQUEST, Json(ApiResponse::<BucketResponseDto>::error("Transition not allowed from current state")));
318 }
319
320 let mut fields: HashMap<String, serde_json::Value> = HashMap::new();
322 fields.insert("status".to_string(), serde_json::Value::String("Active".to_string()));
323
324 match service.partial_update(&id, fields).await {
325 Ok(Some(updated)) => {
326 let response: BucketResponseDto = updated.into();
327 (StatusCode::OK, Json(ApiResponse::ok(response)))
328 }
329 Ok(None) => (StatusCode::NOT_FOUND, Json(ApiResponse::<BucketResponseDto>::not_found("Bucket", &id))),
330 Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, Json(ApiResponse::<BucketResponseDto>::error(e.to_string()))),
331 }
332}
333
334pub async fn archive_transition(
338 axum::extract::State(service): axum::extract::State<Arc<BucketService>>,
339 axum::extract::Path(id): axum::extract::Path<String>,
340 #[cfg(feature = "auth")] axum::Extension(auth): axum::Extension<AuthContext>,
341) -> impl axum::response::IntoResponse {
342 use axum::{http::StatusCode, Json};
343
344 let entity = match service.get_by_id(&id).await {
346 Ok(Some(e)) => e,
347 Ok(None) => return (StatusCode::NOT_FOUND, Json(ApiResponse::<BucketResponseDto>::not_found("Bucket", &id))),
348 Err(e) => return (StatusCode::INTERNAL_SERVER_ERROR, Json(ApiResponse::<BucketResponseDto>::error(e.to_string()))),
349 };
350
351 #[cfg(feature = "auth")]
353 {
354 let allowed_roles = BucketTransition::Archive.allowed_roles();
355 let has_specific_perm = auth.permissions.iter().any(|p| p == "bucket:transition:archive");
356 let has_update_perm = auth.permissions.iter().any(|p| p == "bucket:update");
357 let has_role = auth.roles.iter().any(|r| allowed_roles.contains(&r.as_str()));
358 if !has_specific_perm && !has_update_perm && !has_role {
359 return (StatusCode::FORBIDDEN, Json(ApiResponse::<BucketResponseDto>::error("Insufficient permissions for archive transition")));
360 }
361 }
362
363 let current_state: BucketState = entity.status.to_string().parse()
365 .unwrap_or(BucketState::default());
366 let sm = BucketStateMachine::from_state(current_state);
367 if !sm.can_transition(BucketTransition::Archive) {
368 return (StatusCode::BAD_REQUEST, Json(ApiResponse::<BucketResponseDto>::error("Transition not allowed from current state")));
369 }
370
371 let mut fields: HashMap<String, serde_json::Value> = HashMap::new();
373 fields.insert("status".to_string(), serde_json::Value::String("Archived".to_string()));
374
375 match service.partial_update(&id, fields).await {
376 Ok(Some(updated)) => {
377 let response: BucketResponseDto = updated.into();
378 (StatusCode::OK, Json(ApiResponse::ok(response)))
379 }
380 Ok(None) => (StatusCode::NOT_FOUND, Json(ApiResponse::<BucketResponseDto>::not_found("Bucket", &id))),
381 Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, Json(ApiResponse::<BucketResponseDto>::error(e.to_string()))),
382 }
383}
384
385pub async fn restore_transition(
389 axum::extract::State(service): axum::extract::State<Arc<BucketService>>,
390 axum::extract::Path(id): axum::extract::Path<String>,
391 #[cfg(feature = "auth")] axum::Extension(auth): axum::Extension<AuthContext>,
392) -> impl axum::response::IntoResponse {
393 use axum::{http::StatusCode, Json};
394
395 let entity = match service.get_by_id(&id).await {
397 Ok(Some(e)) => e,
398 Ok(None) => return (StatusCode::NOT_FOUND, Json(ApiResponse::<BucketResponseDto>::not_found("Bucket", &id))),
399 Err(e) => return (StatusCode::INTERNAL_SERVER_ERROR, Json(ApiResponse::<BucketResponseDto>::error(e.to_string()))),
400 };
401
402 #[cfg(feature = "auth")]
404 {
405 let allowed_roles = BucketTransition::Restore.allowed_roles();
406 let has_specific_perm = auth.permissions.iter().any(|p| p == "bucket:transition:restore");
407 let has_update_perm = auth.permissions.iter().any(|p| p == "bucket:update");
408 let has_role = auth.roles.iter().any(|r| allowed_roles.contains(&r.as_str()));
409 if !has_specific_perm && !has_update_perm && !has_role {
410 return (StatusCode::FORBIDDEN, Json(ApiResponse::<BucketResponseDto>::error("Insufficient permissions for restore transition")));
411 }
412 }
413
414 let current_state: BucketState = entity.status.to_string().parse()
416 .unwrap_or(BucketState::default());
417 let sm = BucketStateMachine::from_state(current_state);
418 if !sm.can_transition(BucketTransition::Restore) {
419 return (StatusCode::BAD_REQUEST, Json(ApiResponse::<BucketResponseDto>::error("Transition not allowed from current state")));
420 }
421
422 let mut fields: HashMap<String, serde_json::Value> = HashMap::new();
424 fields.insert("status".to_string(), serde_json::Value::String("Active".to_string()));
425
426 match service.partial_update(&id, fields).await {
427 Ok(Some(updated)) => {
428 let response: BucketResponseDto = updated.into();
429 (StatusCode::OK, Json(ApiResponse::ok(response)))
430 }
431 Ok(None) => (StatusCode::NOT_FOUND, Json(ApiResponse::<BucketResponseDto>::not_found("Bucket", &id))),
432 Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, Json(ApiResponse::<BucketResponseDto>::error(e.to_string()))),
433 }
434}
435
436pub async fn delete_transition(
440 axum::extract::State(service): axum::extract::State<Arc<BucketService>>,
441 axum::extract::Path(id): axum::extract::Path<String>,
442 #[cfg(feature = "auth")] axum::Extension(auth): axum::Extension<AuthContext>,
443) -> impl axum::response::IntoResponse {
444 use axum::{http::StatusCode, Json};
445
446 let entity = match service.get_by_id(&id).await {
448 Ok(Some(e)) => e,
449 Ok(None) => return (StatusCode::NOT_FOUND, Json(ApiResponse::<BucketResponseDto>::not_found("Bucket", &id))),
450 Err(e) => return (StatusCode::INTERNAL_SERVER_ERROR, Json(ApiResponse::<BucketResponseDto>::error(e.to_string()))),
451 };
452
453 #[cfg(feature = "auth")]
455 {
456 let allowed_roles = BucketTransition::Delete.allowed_roles();
457 let has_specific_perm = auth.permissions.iter().any(|p| p == "bucket:transition:delete");
458 let has_update_perm = auth.permissions.iter().any(|p| p == "bucket:update");
459 let has_role = auth.roles.iter().any(|r| allowed_roles.contains(&r.as_str()));
460 if !has_specific_perm && !has_update_perm && !has_role {
461 return (StatusCode::FORBIDDEN, Json(ApiResponse::<BucketResponseDto>::error("Insufficient permissions for delete transition")));
462 }
463 }
464
465 let current_state: BucketState = entity.status.to_string().parse()
467 .unwrap_or(BucketState::default());
468 let sm = BucketStateMachine::from_state(current_state);
469 if !sm.can_transition(BucketTransition::Delete) {
470 return (StatusCode::BAD_REQUEST, Json(ApiResponse::<BucketResponseDto>::error("Transition not allowed from current state")));
471 }
472
473 let mut fields: HashMap<String, serde_json::Value> = HashMap::new();
475 fields.insert("status".to_string(), serde_json::Value::String("Deleted".to_string()));
476
477 match service.partial_update(&id, fields).await {
478 Ok(Some(updated)) => {
479 let response: BucketResponseDto = updated.into();
480 (StatusCode::OK, Json(ApiResponse::ok(response)))
481 }
482 Ok(None) => (StatusCode::NOT_FOUND, Json(ApiResponse::<BucketResponseDto>::not_found("Bucket", &id))),
483 Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, Json(ApiResponse::<BucketResponseDto>::error(e.to_string()))),
484 }
485}
486
487pub fn create_bucket_transition_routes(service: Arc<BucketService>) -> Router {
489 use axum::routing::post;
490
491 Router::new()
492 .route("/buckets/:id/transitions/lock", post(lock_transition))
493 .route("/buckets/:id/transitions/unlock", post(unlock_transition))
494 .route("/buckets/:id/transitions/archive", post(archive_transition))
495 .route("/buckets/:id/transitions/restore", post(restore_transition))
496 .route("/buckets/:id/transitions/delete", post(delete_transition))
497 .with_state(service)
498}