ryuk-cli 0.1.1

The `ryuk` command: scaffold a Ryuk app (axum, SeaORM, Inertia/Svelte), generate controllers, models, jobs and mails, run migrations and the dev server.
use axum::{
    http::StatusCode,
    response::{IntoResponse, Response},
};

pub mod api;
pub mod api_keys;
pub mod auth;
pub mod orgs;
pub mod passkeys;
pub mod posts;
pub mod projects;
pub mod security;
pub mod social;
pub mod well_known;

/// Deserializes an email address trimmed and lowercased, so `Vic@Example.com` and `vic@example.com` are one
/// account on every database (MySQL compares case-insensitively, SQLite and PostgreSQL do not) and the
/// throttle, invitation and mail flows all key on the same text. Use on every email field of a form:
/// `#[serde(deserialize_with = "super::email")]`.
pub fn email<'de, D: serde::Deserializer<'de>>(d: D) -> Result<String, D::Error> {
    Ok(<String as serde::Deserialize>::deserialize(d)?.trim().to_lowercase())
}

/// Catch-all handler error: anything displayable becomes a generic 500 (the detail is only logged),
/// except a denied `gate.authorize(..)`, which keeps its 403 (or 404 after `deny_as_not_found`).
#[derive(Debug)]
pub enum AppError {
    Internal(String),
    Forbidden(ryuk::gate::Forbidden),
}

impl<E: std::error::Error + 'static> From<E> for AppError {
    fn from(e: E) -> Self {
        // `Forbidden` is an Error too; without this check `authorize(..).await?` would answer 500.
        match ryuk::gate::Forbidden::from_error(&e) {
            Some(f) => AppError::Forbidden(f),
            None => AppError::Internal(e.to_string()),
        }
    }
}

impl std::fmt::Display for AppError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            AppError::Forbidden(x) => write!(f, "{x}"),
            AppError::Internal(detail) => f.write_str(detail),
        }
    }
}

impl IntoResponse for AppError {
    fn into_response(self) -> Response {
        match self {
            AppError::Forbidden(f) => f.into_response(),
            AppError::Internal(detail) => {
                // Log the detail, never send it: database errors can leak schema and values.
                tracing::error!(error = %detail, "request failed");
                (StatusCode::INTERNAL_SERVER_ERROR, "Internal Server Error").into_response()
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::AppError;
    use axum::{http::StatusCode, response::IntoResponse};
    use ryuk::gate::Forbidden;

    fn status<E: std::error::Error + 'static>(e: E) -> StatusCode {
        AppError::from(e).into_response().status()
    }

    #[test]
    fn a_denied_gate_keeps_its_403_or_404_through_question_mark() {
        assert_eq!(status(Forbidden::new()), StatusCode::FORBIDDEN);
        assert_eq!(status(Forbidden::new().deny_as_not_found()), StatusCode::NOT_FOUND);
    }

    #[test]
    fn any_other_error_is_a_500_with_a_fixed_body() {
        let e = AppError::from(std::fmt::Error);
        assert!(matches!(e, AppError::Internal(_)));
        let r = e.into_response();
        assert_eq!(r.status(), StatusCode::INTERNAL_SERVER_ERROR);
    }
}