Skip to main content

loco_rs/controller/
mod.rs

1//! Manage web server routing
2//!
3//! # Example
4//!
5//! This example you can adding custom routes into your application by
6//! implementing routes trait from [`crate::app::Hooks`] and adding your
7//! endpoints to your application
8//!
9//! ```rust
10//! use async_trait::async_trait;
11//! use loco_rs::{
12//!    app::{AppContext, Hooks},
13//!    boot::{create_app, BootResult, StartMode},
14//!    config::Config,
15//!    controller::AppRoutes,
16//!    prelude::*,
17//!    task::Tasks,
18//!    environment::Environment,
19//!    Result,
20//! };
21//! use sea_orm::DatabaseConnection;
22//! use std::path::Path;
23//!
24//! /// this code block should be taken from the sea_orm migration model.
25//! pub struct App;
26//! pub use sea_orm_migration::prelude::*;
27//! pub struct Migrator;
28//! #[async_trait::async_trait]
29//! impl MigratorTrait for Migrator {
30//!     fn migrations() -> Vec<Box<dyn MigrationTrait>> {
31//!         vec![]
32//!     }
33//! }
34//!
35//! #[async_trait]
36//! impl Hooks for App {
37//!
38//!    fn app_name() -> &'static str {
39//!        env!("CARGO_CRATE_NAME")
40//!    }
41//!
42//!     fn routes(ctx: &AppContext) -> AppRoutes {
43//!         AppRoutes::with_default_routes()
44//!             // .add_route(controllers::notes::routes())
45//!     }
46//!
47//!     async fn boot(mode: StartMode, environment: &Environment, config: Config) -> Result<BootResult>{
48//!          create_app::<Self, Migrator>(mode, environment, config).await
49//!     }
50//!
51//!     async fn connect_workers(_ctx: &AppContext, _queue: &Queue) -> Result<()> {
52//!         Ok(())
53//!     }
54//!
55//!
56//!     fn register_tasks(tasks: &mut Tasks) {}
57//!
58//!     async fn truncate(_ctx: &AppContext) -> Result<()> {
59//!         Ok(())
60//!     }
61//!
62//!     async fn seed(_ctx: &AppContext, base: &Path) -> Result<()> {
63//!         Ok(())
64//!     }
65//! }
66//! ```
67
68pub use app_routes::{AppRoutes, ListRoutes};
69use axum::{
70    extract::FromRequest,
71    http::StatusCode,
72    response::{IntoResponse, Response},
73};
74use colored::Colorize;
75pub use routes::Routes;
76use serde::Serialize;
77
78#[cfg(feature = "with-db")]
79use crate::model::ModelError;
80use crate::{errors::Error, Result};
81
82mod app_routes;
83mod backtrace;
84mod describe;
85pub mod extractor;
86pub mod format;
87pub mod middleware;
88pub mod monitoring;
89mod routes;
90pub mod views;
91
92/// Create an unauthorized error with a specified message.
93///
94/// This function is used to generate an `Error::Unauthorized` variant with a
95/// custom message.
96///
97/// # Errors
98///
99/// returns unauthorized enum
100///
101/// # Example
102///
103/// ```rust
104/// use loco_rs::prelude::*;
105///
106/// async fn login() -> Result<Response> {
107///     let valid = false;
108///     if !valid {
109///         return unauthorized("unauthorized access");
110///     }
111///     format::json(())
112/// }
113/// ````
114pub fn unauthorized<T: Into<String>, U>(msg: T) -> Result<U> {
115    Err(Error::Unauthorized(msg.into()))
116}
117
118/// Return a bad request with a message
119///
120/// # Errors
121///
122/// This function will return an error result
123pub fn bad_request<T: Into<String>, U>(msg: T) -> Result<U> {
124    Err(Error::BadRequest(msg.into()))
125}
126
127/// return not found status code
128///
129/// # Errors
130/// Currently this function doesn't return any error. this is for feature
131/// functionality
132pub fn not_found<T>() -> Result<T> {
133    Err(Error::NotFound)
134}
135#[derive(Debug, Serialize)]
136/// Structure representing details about an error.
137pub struct ErrorDetail {
138    #[serde(skip_serializing_if = "Option::is_none")]
139    pub error: Option<String>,
140    #[serde(skip_serializing_if = "Option::is_none")]
141    pub description: Option<String>,
142    #[serde(skip_serializing_if = "Option::is_none")]
143    pub errors: Option<serde_json::Value>,
144}
145
146impl ErrorDetail {
147    /// Create a new `ErrorDetail` with the specified error and description.
148    #[must_use]
149    pub fn new<T1: Into<String> + AsRef<str>, T2: Into<String> + AsRef<str>>(
150        error: T1,
151        description: T2,
152    ) -> Self {
153        let description = (!description.as_ref().is_empty()).then(|| description.into());
154        Self {
155            error: Some(error.into()),
156            description,
157            errors: None,
158        }
159    }
160
161    /// Create an `ErrorDetail` with only an error reason and no description.
162    #[must_use]
163    pub fn with_reason<T: Into<String>>(error: T) -> Self {
164        Self {
165            error: Some(error.into()),
166            description: None,
167            errors: None,
168        }
169    }
170}
171
172#[derive(Debug, FromRequest)]
173#[from_request(via(axum::Json), rejection(Error))]
174pub struct Json<T>(pub T);
175
176impl<T: Serialize> IntoResponse for Json<T> {
177    fn into_response(self) -> axum::response::Response {
178        axum::Json(self.0).into_response()
179    }
180}
181
182/// Build the `(StatusCode, ErrorDetail)` pair for a validation error, shared
183/// by [`Error::Validation`] and <code>[Error::Model]([ModelError::Validation])</code>
184/// so both report the same shape.
185fn validation_error_response(
186    errors: &crate::validation::ModelValidationErrors,
187) -> (StatusCode, ErrorDetail) {
188    (
189        StatusCode::BAD_REQUEST,
190        ErrorDetail {
191            error: None,
192            description: None,
193            errors: Some(serde_json::to_value(&errors.errors).unwrap_or_default()),
194        },
195    )
196}
197
198impl IntoResponse for Error {
199    /// Convert an `Error` into an HTTP response.
200    #[allow(clippy::cognitive_complexity, clippy::too_many_lines)]
201    fn into_response(self) -> Response {
202        match &self {
203            Self::WithBacktrace {
204                inner,
205                backtrace: _,
206            } => {
207                tracing::error!(
208                error.msg = %inner,
209                error.details = ?inner,
210                "controller_error"
211                );
212            }
213            err => {
214                tracing::error!(
215                error.msg = %err,
216                error.details = ?err,
217                "controller_error"
218                );
219            }
220        }
221
222        let public_facing_error = match self {
223            Self::NotFound => (
224                StatusCode::NOT_FOUND,
225                ErrorDetail::new("not_found", "Resource was not found"),
226            ),
227            Self::Unauthorized(err) => {
228                tracing::warn!(err);
229                (
230                    StatusCode::UNAUTHORIZED,
231                    ErrorDetail::new(
232                        "unauthorized",
233                        "You do not have permission to access this resource",
234                    ),
235                )
236            }
237            Self::CustomError(status_code, data) => (status_code, data),
238            Self::WithBacktrace { inner, backtrace } => {
239                println!("\n{}", inner.to_string().red().underline());
240                backtrace::print_backtrace(&backtrace).unwrap();
241                // Delegate to the wrapped error's own response so the real HTTP
242                // status is preserved (e.g. internal errors stay 500) instead of
243                // being flattened to 400 whenever a backtrace was captured.
244                return (*inner).into_response();
245            }
246            Self::BadRequest(err) => (
247                StatusCode::BAD_REQUEST,
248                ErrorDetail::new("Bad Request", &err),
249            ),
250            Self::JsonRejection(err) => {
251                tracing::debug!(err = err.body_text(), "json rejection");
252                (err.status(), ErrorDetail::with_reason("Bad Request"))
253            }
254            Self::AxumFormRejection(err) => {
255                tracing::debug!(err = err.body_text(), "form rejection");
256                (err.status(), ErrorDetail::with_reason("Bad Request"))
257            }
258
259            Self::Validation(ref errors) => validation_error_response(errors),
260
261            #[cfg(feature = "with-db")]
262            Self::Model(ModelError::EntityNotFound) => (
263                StatusCode::NOT_FOUND,
264                ErrorDetail::new("not_found", "Resource was not found"),
265            ),
266            #[cfg(feature = "with-db")]
267            Self::Model(ModelError::EntityAlreadyExists) => (
268                StatusCode::CONFLICT,
269                ErrorDetail::new("conflict", "Resource already exists"),
270            ),
271            #[cfg(feature = "multi-tenancy")]
272            Self::Model(ModelError::TenantMismatch) => (
273                StatusCode::BAD_REQUEST,
274                ErrorDetail::new("tenant_mismatch", "Model belongs to a different tenant"),
275            ),
276            #[cfg(feature = "with-db")]
277            Self::Model(ModelError::Validation(ref errors)) => validation_error_response(errors),
278
279            // --- Internal / infrastructure errors: deliberately no `_` arm.
280            //
281            // `Error` is `#[non_exhaustive]` for downstream crates, but this
282            // match lives inside `loco_rs` itself, where an exhaustive match
283            // over a local enum is allowed. Keeping it exhaustive (instead of
284            // a trailing wildcard) means that adding a new `Error` variant
285            // anywhere in the crate is a compile error here until someone
286            // deliberately decides which HTTP status it should map to, rather
287            // than silently defaulting to 500. Every variant below is an
288            // internal/infrastructure error, so they are all mapped to the
289            // same generic 500 response.
290            Self::Message(_)
291            | Self::InternalServerError
292            | Self::QueueProviderMissing
293            | Self::TaskNotFound(_)
294            | Self::Scheduler(_)
295            | Self::Axum(_)
296            | Self::Tera(_)
297            | Self::JSON(_)
298            | Self::YAMLFile(_, _)
299            | Self::YAML(_)
300            | Self::Worker(_)
301            | Self::IO(_)
302            | Self::InvalidHeaderValue(_)
303            | Self::InvalidHeaderName(_)
304            | Self::InvalidMethod(_)
305            | Self::Storage(_)
306            | Self::Cache(_)
307            | Self::VersionCheck(_)
308            | Self::Any(_) => (
309                StatusCode::INTERNAL_SERVER_ERROR,
310                ErrorDetail::new("internal_server_error", "Internal Server Error"),
311            ),
312
313            #[cfg(feature = "mailer")]
314            Self::EmailSender(_) | Self::Smtp(_) | Self::ParseAddress(_) => (
315                StatusCode::INTERNAL_SERVER_ERROR,
316                ErrorDetail::new("internal_server_error", "Internal Server Error"),
317            ),
318
319            #[cfg(feature = "with-db")]
320            Self::DB(_) => (
321                StatusCode::INTERNAL_SERVER_ERROR,
322                ErrorDetail::new("internal_server_error", "Internal Server Error"),
323            ),
324
325            // Other `ModelError` variants are internal/infrastructure errors
326            // (DB, generic `Any`, free-form `Message`, and, when `auth`
327            // is enabled, `Jwt`) and are collapsed to 500 like their
328            // top-level counterparts.
329            #[cfg(feature = "with-db")]
330            Self::Model(ModelError::DbErr(_) | ModelError::Any(_) | ModelError::Message(_)) => (
331                StatusCode::INTERNAL_SERVER_ERROR,
332                ErrorDetail::new("internal_server_error", "Internal Server Error"),
333            ),
334            #[cfg(all(feature = "with-db", feature = "auth"))]
335            Self::Model(ModelError::Jwt(_)) => (
336                StatusCode::INTERNAL_SERVER_ERROR,
337                ErrorDetail::new("internal_server_error", "Internal Server Error"),
338            ),
339
340            #[cfg(feature = "worker_redis")]
341            Self::Redis(_) => (
342                StatusCode::INTERNAL_SERVER_ERROR,
343                ErrorDetail::new("internal_server_error", "Internal Server Error"),
344            ),
345
346            #[cfg(feature = "worker")]
347            Self::Sqlx(_) => (
348                StatusCode::INTERNAL_SERVER_ERROR,
349                ErrorDetail::new("internal_server_error", "Internal Server Error"),
350            ),
351
352            #[cfg(all(debug_assertions, feature = "generators"))]
353            Self::Generators(_) => (
354                StatusCode::INTERNAL_SERVER_ERROR,
355                ErrorDetail::new("internal_server_error", "Internal Server Error"),
356            ),
357        };
358
359        (public_facing_error.0, Json(public_facing_error.1)).into_response()
360    }
361}
362
363#[cfg(test)]
364mod tests {
365    use axum::body::to_bytes;
366
367    use super::*;
368
369    async fn response_json(err: Error) -> (StatusCode, serde_json::Value) {
370        let response = err.into_response();
371        let status = response.status();
372        let body = to_bytes(response.into_body(), 1024 * 1024)
373            .await
374            .expect("failed to read response body");
375        let json: serde_json::Value =
376            serde_json::from_slice(&body).expect("response body is not valid JSON");
377        (status, json)
378    }
379
380    #[cfg(feature = "with-db")]
381    #[tokio::test]
382    async fn model_entity_not_found_maps_to_404() {
383        let (status, json) = response_json(Error::Model(ModelError::EntityNotFound)).await;
384
385        assert_eq!(status, StatusCode::NOT_FOUND);
386        assert_eq!(
387            json,
388            serde_json::json!({
389                "error": "not_found",
390                "description": "Resource was not found"
391            })
392        );
393    }
394
395    #[cfg(feature = "with-db")]
396    #[tokio::test]
397    async fn model_entity_already_exists_maps_to_409() {
398        let (status, json) = response_json(Error::Model(ModelError::EntityAlreadyExists)).await;
399
400        assert_eq!(status, StatusCode::CONFLICT);
401        assert_eq!(
402            json,
403            serde_json::json!({
404                "error": "conflict",
405                "description": "Resource already exists"
406            })
407        );
408    }
409
410    #[cfg(feature = "multi-tenancy")]
411    #[tokio::test]
412    async fn model_tenant_mismatch_maps_to_400() {
413        let (status, json) = response_json(Error::Model(ModelError::TenantMismatch)).await;
414
415        assert_eq!(status, StatusCode::BAD_REQUEST);
416        assert_eq!(
417            json,
418            serde_json::json!({
419                "error": "tenant_mismatch",
420                "description": "Model belongs to a different tenant"
421            })
422        );
423    }
424
425    #[cfg(feature = "with-db")]
426    #[tokio::test]
427    async fn model_validation_maps_same_as_top_level_validation() {
428        use crate::validation::{ModelValidationErrors, ValidationError};
429        use std::collections::BTreeMap;
430
431        let mut errors: BTreeMap<String, Vec<ValidationError>> = BTreeMap::new();
432        errors.insert(
433            "username".to_string(),
434            vec![ValidationError {
435                code: "length".to_string(),
436                message: Some("username must be at least 3 characters".to_string()),
437                params: std::collections::HashMap::new(),
438            }],
439        );
440        let model_errors = ModelValidationErrors {
441            errors: errors.clone(),
442        };
443
444        let (model_status, model_json) =
445            response_json(Error::Model(ModelError::Validation(model_errors))).await;
446        let (top_level_status, top_level_json) =
447            response_json(Error::Validation(ModelValidationErrors { errors })).await;
448
449        assert_eq!(model_status, StatusCode::BAD_REQUEST);
450        assert_eq!(model_status, top_level_status);
451        assert_eq!(model_json, top_level_json);
452    }
453
454    #[tokio::test]
455    async fn axum_form_rejection_maps_to_4xx_not_500() {
456        #[derive(Debug, serde::Deserialize)]
457        struct Data {
458            #[allow(dead_code)]
459            email: String,
460        }
461
462        let request = axum::http::Request::builder()
463            .method(axum::http::Method::POST)
464            .uri("/")
465            .header(
466                axum::http::header::CONTENT_TYPE,
467                "application/x-www-form-urlencoded",
468            )
469            .body(axum::body::Body::from(""))
470            .unwrap();
471
472        let rejection = axum::extract::Form::<Data>::from_request(request, &())
473            .await
474            .expect_err("expected a form rejection for a missing required field");
475
476        let (status, json) = response_json(Error::AxumFormRejection(rejection)).await;
477
478        assert!(status.is_client_error(), "expected 4xx, got {status}");
479        assert_eq!(json, serde_json::json!({ "error": "Bad Request" }));
480    }
481
482    #[tokio::test]
483    async fn not_found_still_maps_to_404() {
484        let (status, json) = response_json(Error::NotFound).await;
485
486        assert_eq!(status, StatusCode::NOT_FOUND);
487        assert_eq!(
488            json,
489            serde_json::json!({
490                "error": "not_found",
491                "description": "Resource was not found"
492            })
493        );
494    }
495
496    #[tokio::test]
497    async fn infra_error_maps_to_500_with_standard_body() {
498        for err in [
499            Error::Message("boom".to_string()),
500            Error::InternalServerError,
501        ] {
502            let (status, json) = response_json(err).await;
503
504            assert_eq!(status, StatusCode::INTERNAL_SERVER_ERROR);
505            assert_eq!(
506                json,
507                serde_json::json!({
508                    "error": "internal_server_error",
509                    "description": "Internal Server Error"
510                })
511            );
512        }
513    }
514
515    #[tokio::test]
516    async fn bad_request_still_maps_to_400() {
517        let (status, json) = response_json(Error::BadRequest("x".to_string())).await;
518
519        assert_eq!(status, StatusCode::BAD_REQUEST);
520        assert_eq!(
521            json,
522            serde_json::json!({
523                "error": "Bad Request",
524                "description": "x"
525            })
526        );
527    }
528}