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_role {
257 if !has_update_perm {
258 return (StatusCode::FORBIDDEN, Json(ApiResponse::<BucketResponseDto>::error("Insufficient permissions for lock transition")));
259 }
260 tracing::warn!(target: "backbone::write_guard", entity = "Bucket", verb = "lock", code = "transition_by_update_permission", "a transition granted only by bucket:update, running in shadow; it needs bucket:transition:lock or a role of ["admin", "owner"]");
261 }
262 }
263
264 let current_state: BucketState = match entity.status.to_string().parse() {
266 Ok(s) => s,
267 Err(_) => return (StatusCode::CONFLICT, Json(ApiResponse::<BucketResponseDto>::error("The stored state is not a state of this machine"))),
268 };
269 let sm = BucketStateMachine::from_state(current_state);
270 if !sm.can_transition(BucketTransition::Lock) {
271 return (StatusCode::BAD_REQUEST, Json(ApiResponse::<BucketResponseDto>::error("Transition not allowed from current state")));
272 }
273
274 let mut fields: HashMap<String, serde_json::Value> = HashMap::new();
277 fields.insert("status".to_string(), serde_json::Value::String("readonly".to_string()));
278
279 match backbone_core::write_guard::as_transition("lock", service.partial_update(&id, fields)).await {
280 Ok(Some(updated)) => {
281 let response: BucketResponseDto = updated.into();
282 (StatusCode::OK, Json(ApiResponse::ok(response)))
283 }
284 Ok(None) => (StatusCode::NOT_FOUND, Json(ApiResponse::<BucketResponseDto>::not_found("Bucket", &id))),
285 Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, Json(ApiResponse::<BucketResponseDto>::error(e.to_string()))),
286 }
287}
288
289pub async fn unlock_transition(
293 axum::extract::State(service): axum::extract::State<Arc<BucketService>>,
294 axum::extract::Path(id): axum::extract::Path<String>,
295 #[cfg(feature = "auth")] axum::Extension(auth): axum::Extension<AuthContext>,
296) -> impl axum::response::IntoResponse {
297 use axum::{http::StatusCode, Json};
298
299 let entity = match service.get_by_id(&id).await {
301 Ok(Some(e)) => e,
302 Ok(None) => return (StatusCode::NOT_FOUND, Json(ApiResponse::<BucketResponseDto>::not_found("Bucket", &id))),
303 Err(e) => return (StatusCode::INTERNAL_SERVER_ERROR, Json(ApiResponse::<BucketResponseDto>::error(e.to_string()))),
304 };
305
306 #[cfg(feature = "auth")]
308 {
309 let allowed_roles = BucketTransition::Unlock.allowed_roles();
310 let has_specific_perm = auth.permissions.iter().any(|p| p == "bucket:transition:unlock");
311 let has_update_perm = auth.permissions.iter().any(|p| p == "bucket:update");
312 let has_role = auth.roles.iter().any(|r| allowed_roles.contains(&r.as_str()));
313 if !has_specific_perm && !has_role {
314 if !has_update_perm {
315 return (StatusCode::FORBIDDEN, Json(ApiResponse::<BucketResponseDto>::error("Insufficient permissions for unlock transition")));
316 }
317 tracing::warn!(target: "backbone::write_guard", entity = "Bucket", verb = "unlock", code = "transition_by_update_permission", "a transition granted only by bucket:update, running in shadow; it needs bucket:transition:unlock or a role of ["admin", "owner"]");
318 }
319 }
320
321 let current_state: BucketState = match entity.status.to_string().parse() {
323 Ok(s) => s,
324 Err(_) => return (StatusCode::CONFLICT, Json(ApiResponse::<BucketResponseDto>::error("The stored state is not a state of this machine"))),
325 };
326 let sm = BucketStateMachine::from_state(current_state);
327 if !sm.can_transition(BucketTransition::Unlock) {
328 return (StatusCode::BAD_REQUEST, Json(ApiResponse::<BucketResponseDto>::error("Transition not allowed from current state")));
329 }
330
331 let mut fields: HashMap<String, serde_json::Value> = HashMap::new();
334 fields.insert("status".to_string(), serde_json::Value::String("active".to_string()));
335
336 match backbone_core::write_guard::as_transition("unlock", service.partial_update(&id, fields)).await {
337 Ok(Some(updated)) => {
338 let response: BucketResponseDto = updated.into();
339 (StatusCode::OK, Json(ApiResponse::ok(response)))
340 }
341 Ok(None) => (StatusCode::NOT_FOUND, Json(ApiResponse::<BucketResponseDto>::not_found("Bucket", &id))),
342 Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, Json(ApiResponse::<BucketResponseDto>::error(e.to_string()))),
343 }
344}
345
346pub async fn archive_transition(
350 axum::extract::State(service): axum::extract::State<Arc<BucketService>>,
351 axum::extract::Path(id): axum::extract::Path<String>,
352 #[cfg(feature = "auth")] axum::Extension(auth): axum::Extension<AuthContext>,
353) -> impl axum::response::IntoResponse {
354 use axum::{http::StatusCode, Json};
355
356 let entity = match service.get_by_id(&id).await {
358 Ok(Some(e)) => e,
359 Ok(None) => return (StatusCode::NOT_FOUND, Json(ApiResponse::<BucketResponseDto>::not_found("Bucket", &id))),
360 Err(e) => return (StatusCode::INTERNAL_SERVER_ERROR, Json(ApiResponse::<BucketResponseDto>::error(e.to_string()))),
361 };
362
363 #[cfg(feature = "auth")]
365 {
366 let allowed_roles = BucketTransition::Archive.allowed_roles();
367 let has_specific_perm = auth.permissions.iter().any(|p| p == "bucket:transition:archive");
368 let has_update_perm = auth.permissions.iter().any(|p| p == "bucket:update");
369 let has_role = auth.roles.iter().any(|r| allowed_roles.contains(&r.as_str()));
370 if !has_specific_perm && !has_role {
371 if !has_update_perm {
372 return (StatusCode::FORBIDDEN, Json(ApiResponse::<BucketResponseDto>::error("Insufficient permissions for archive transition")));
373 }
374 tracing::warn!(target: "backbone::write_guard", entity = "Bucket", verb = "archive", code = "transition_by_update_permission", "a transition granted only by bucket:update, running in shadow; it needs bucket:transition:archive or a role of ["admin", "owner"]");
375 }
376 }
377
378 let current_state: BucketState = match entity.status.to_string().parse() {
380 Ok(s) => s,
381 Err(_) => return (StatusCode::CONFLICT, Json(ApiResponse::<BucketResponseDto>::error("The stored state is not a state of this machine"))),
382 };
383 let sm = BucketStateMachine::from_state(current_state);
384 if !sm.can_transition(BucketTransition::Archive) {
385 return (StatusCode::BAD_REQUEST, Json(ApiResponse::<BucketResponseDto>::error("Transition not allowed from current state")));
386 }
387
388 let mut fields: HashMap<String, serde_json::Value> = HashMap::new();
391 fields.insert("status".to_string(), serde_json::Value::String("archived".to_string()));
392
393 match backbone_core::write_guard::as_transition("archive", service.partial_update(&id, fields)).await {
394 Ok(Some(updated)) => {
395 let response: BucketResponseDto = updated.into();
396 (StatusCode::OK, Json(ApiResponse::ok(response)))
397 }
398 Ok(None) => (StatusCode::NOT_FOUND, Json(ApiResponse::<BucketResponseDto>::not_found("Bucket", &id))),
399 Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, Json(ApiResponse::<BucketResponseDto>::error(e.to_string()))),
400 }
401}
402
403pub async fn restore_transition(
407 axum::extract::State(service): axum::extract::State<Arc<BucketService>>,
408 axum::extract::Path(id): axum::extract::Path<String>,
409 #[cfg(feature = "auth")] axum::Extension(auth): axum::Extension<AuthContext>,
410) -> impl axum::response::IntoResponse {
411 use axum::{http::StatusCode, Json};
412
413 let entity = match service.get_by_id(&id).await {
415 Ok(Some(e)) => e,
416 Ok(None) => return (StatusCode::NOT_FOUND, Json(ApiResponse::<BucketResponseDto>::not_found("Bucket", &id))),
417 Err(e) => return (StatusCode::INTERNAL_SERVER_ERROR, Json(ApiResponse::<BucketResponseDto>::error(e.to_string()))),
418 };
419
420 #[cfg(feature = "auth")]
422 {
423 let allowed_roles = BucketTransition::Restore.allowed_roles();
424 let has_specific_perm = auth.permissions.iter().any(|p| p == "bucket:transition:restore");
425 let has_update_perm = auth.permissions.iter().any(|p| p == "bucket:update");
426 let has_role = auth.roles.iter().any(|r| allowed_roles.contains(&r.as_str()));
427 if !has_specific_perm && !has_role {
428 if !has_update_perm {
429 return (StatusCode::FORBIDDEN, Json(ApiResponse::<BucketResponseDto>::error("Insufficient permissions for restore transition")));
430 }
431 tracing::warn!(target: "backbone::write_guard", entity = "Bucket", verb = "restore", code = "transition_by_update_permission", "a transition granted only by bucket:update, running in shadow; it needs bucket:transition:restore or a role of ["admin", "owner"]");
432 }
433 }
434
435 let current_state: BucketState = match entity.status.to_string().parse() {
437 Ok(s) => s,
438 Err(_) => return (StatusCode::CONFLICT, Json(ApiResponse::<BucketResponseDto>::error("The stored state is not a state of this machine"))),
439 };
440 let sm = BucketStateMachine::from_state(current_state);
441 if !sm.can_transition(BucketTransition::Restore) {
442 return (StatusCode::BAD_REQUEST, Json(ApiResponse::<BucketResponseDto>::error("Transition not allowed from current state")));
443 }
444
445 let mut fields: HashMap<String, serde_json::Value> = HashMap::new();
448 fields.insert("status".to_string(), serde_json::Value::String("active".to_string()));
449
450 match backbone_core::write_guard::as_transition("restore", service.partial_update(&id, fields)).await {
451 Ok(Some(updated)) => {
452 let response: BucketResponseDto = updated.into();
453 (StatusCode::OK, Json(ApiResponse::ok(response)))
454 }
455 Ok(None) => (StatusCode::NOT_FOUND, Json(ApiResponse::<BucketResponseDto>::not_found("Bucket", &id))),
456 Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, Json(ApiResponse::<BucketResponseDto>::error(e.to_string()))),
457 }
458}
459
460pub async fn delete_transition(
464 axum::extract::State(service): axum::extract::State<Arc<BucketService>>,
465 axum::extract::Path(id): axum::extract::Path<String>,
466 #[cfg(feature = "auth")] axum::Extension(auth): axum::Extension<AuthContext>,
467) -> impl axum::response::IntoResponse {
468 use axum::{http::StatusCode, Json};
469
470 let entity = match service.get_by_id(&id).await {
472 Ok(Some(e)) => e,
473 Ok(None) => return (StatusCode::NOT_FOUND, Json(ApiResponse::<BucketResponseDto>::not_found("Bucket", &id))),
474 Err(e) => return (StatusCode::INTERNAL_SERVER_ERROR, Json(ApiResponse::<BucketResponseDto>::error(e.to_string()))),
475 };
476
477 #[cfg(feature = "auth")]
479 {
480 let allowed_roles = BucketTransition::Delete.allowed_roles();
481 let has_specific_perm = auth.permissions.iter().any(|p| p == "bucket:transition:delete");
482 let has_update_perm = auth.permissions.iter().any(|p| p == "bucket:update");
483 let has_role = auth.roles.iter().any(|r| allowed_roles.contains(&r.as_str()));
484 if !has_specific_perm && !has_role {
485 if !has_update_perm {
486 return (StatusCode::FORBIDDEN, Json(ApiResponse::<BucketResponseDto>::error("Insufficient permissions for delete transition")));
487 }
488 tracing::warn!(target: "backbone::write_guard", entity = "Bucket", verb = "delete", code = "transition_by_update_permission", "a transition granted only by bucket:update, running in shadow; it needs bucket:transition:delete or a role of ["admin", "owner"]");
489 }
490 }
491
492 let current_state: BucketState = match entity.status.to_string().parse() {
494 Ok(s) => s,
495 Err(_) => return (StatusCode::CONFLICT, Json(ApiResponse::<BucketResponseDto>::error("The stored state is not a state of this machine"))),
496 };
497 let sm = BucketStateMachine::from_state(current_state);
498 if !sm.can_transition(BucketTransition::Delete) {
499 return (StatusCode::BAD_REQUEST, Json(ApiResponse::<BucketResponseDto>::error("Transition not allowed from current state")));
500 }
501
502 let mut fields: HashMap<String, serde_json::Value> = HashMap::new();
505 fields.insert("status".to_string(), serde_json::Value::String("deleted".to_string()));
506
507 match backbone_core::write_guard::as_transition("delete", service.partial_update(&id, fields)).await {
508 Ok(Some(updated)) => {
509 let response: BucketResponseDto = updated.into();
510 (StatusCode::OK, Json(ApiResponse::ok(response)))
511 }
512 Ok(None) => (StatusCode::NOT_FOUND, Json(ApiResponse::<BucketResponseDto>::not_found("Bucket", &id))),
513 Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, Json(ApiResponse::<BucketResponseDto>::error(e.to_string()))),
514 }
515}
516
517pub fn create_bucket_transition_routes(service: Arc<BucketService>) -> Router {
519 use axum::routing::post;
520
521 Router::new()
522 .route("/buckets/:id/transitions/lock", post(lock_transition))
523 .route("/buckets/:id/transitions/unlock", post(unlock_transition))
524 .route("/buckets/:id/transitions/archive", post(archive_transition))
525 .route("/buckets/:id/transitions/restore", post(restore_transition))
526 .route("/buckets/:id/transitions/delete", post(delete_transition))
527 .with_state(service)
528}
529