ryuk 0.1.1

A Laravel-style full-stack web framework for Rust: axum, SeaORM and Inertia, with auth, queues, mail, storage, cache, scheduling and an MCP server.
Documentation
//! OpenAPI spec at `/openapi.json` and Scalar UI at `/docs`.
//!
//! ```
//! use ryuk::openapi::mount;
//! use utoipa_axum::{router::OpenApiRouter, routes};
//!
//! /// Say hello.
//! #[utoipa::path(get, path = "/hello", responses((status = 200, body = String)))]
//! async fn hello() -> &'static str { "hi" }
//!
//! let api = OpenApiRouter::new().routes(routes!(hello));
//! let app: axum::Router = mount(api, "My API", "1.0.0");
//! ```
use axum::{Json, Router, response::Html, routing::get};
use utoipa::openapi::OpenApi;
#[cfg(feature = "api")]
use utoipa::openapi::security::{
    AuthorizationCode, Flow, Http, HttpAuthScheme, OAuth2, Scopes, SecurityScheme,
};
use utoipa_axum::router::OpenApiRouter;
use utoipa_scalar::Scalar;

/// Mount `/openapi.json` + `/docs` for `router`. Always on: you called it, so you decided. `App` gates the
/// same routes off in production by default; see `App::docs`.
pub fn mount<S: Clone + Send + Sync + 'static>(
    router: OpenApiRouter<S>,
    title: &str,
    version: &str,
) -> Router<S> {
    let (router, api) = router.split_for_parts();
    router.merge(docs(api, title, version, true))
}

/// Whether `/docs` and `/openapi.json` are served: an explicit `App::docs(..)` wins, then
/// `OPENAPI_DOCS=true|false`, and otherwise they are on everywhere except production. The spec lists
/// every documented route, parameter and scope, which is reconnaissance for an attacker.
pub(crate) fn docs_enabled(explicit: Option<bool>, env: Option<&str>, production: bool) -> bool {
    explicit
        .or_else(|| env.and_then(|v| v.trim().parse::<bool>().ok()))
        .unwrap_or(!production)
}

/// `/openapi.json` + `/docs` routes serving `api` (title and version are set here); empty when `enabled` is false.
pub(crate) fn docs<S: Clone + Send + Sync + 'static>(
    mut api: OpenApi,
    title: &str,
    version: &str,
    enabled: bool,
) -> Router<S> {
    if !enabled {
        return Router::new();
    }
    api.info.title = title.into();
    api.info.version = version.into();
    // utoipa-axum pre-fills these with its own author's details.
    (api.info.description, api.info.contact, api.info.license) = (None, None, None);
    let html = Scalar::new(api.clone()).title(title.to_string()).to_html();
    Router::new()
        .route("/openapi.json", get(move || async move { Json(api) }))
        .route("/docs", get(move || async move { Html(html) }))
}

/// Adds the api group's security schemes: `api_key` always, `oauth2` when configured.
#[cfg(feature = "api")]
pub(crate) fn add_security(api: &mut OpenApi, oauth2: Option<&OAuth2Cfg>) {
    let c = api.components.get_or_insert_with(Default::default);
    let mut bearer = Http::new(HttpAuthScheme::Bearer);
    bearer.bearer_format = Some("API key".into());
    c.add_security_scheme("api_key", SecurityScheme::Http(bearer));
    if let Some(o) = oauth2 {
        let scopes = Scopes::from_iter(o.scopes.iter().cloned());
        c.add_security_scheme(
            "oauth2",
            SecurityScheme::OAuth2(OAuth2::new([Flow::AuthorizationCode(
                AuthorizationCode::new(&o.authorize_url, &o.token_url, scopes),
            )])),
        );
    }
}

/// Endpoints and scopes for the `oauth2` security scheme (`App::oauth2_scheme`).
#[cfg(feature = "api")]
pub(crate) struct OAuth2Cfg {
    pub authorize_url: String,
    pub token_url: String,
    pub scopes: Vec<(String, String)>,
}

#[cfg(test)]
mod tests {
    use super::*;
    use axum::{body::Body, http::Request};
    use tower::ServiceExt;
    use utoipa_axum::routes;

    #[utoipa::path(get, path = "/ping", responses((status = 200, body = String)))]
    async fn ping() -> &'static str {
        "pong"
    }

    #[test]
    fn docs_are_off_in_production_unless_asked_for() {
        // (explicit, env, production) -> served?
        for (explicit, env, production, want) in [
            (None, None, false, true),
            (None, None, true, false),
            (None, Some("true"), true, true),
            (None, Some(" TRUE "), true, false), // not a bool spelling: ignored, so the default stands
            (None, Some("false"), false, false),
            (None, Some("yes"), true, false),
            (Some(true), Some("false"), true, true),
            (Some(false), Some("true"), false, false),
        ] {
            assert_eq!(
                docs_enabled(explicit, env, production),
                want,
                "{explicit:?} {env:?} production={production}"
            );
        }
    }

    #[tokio::test]
    async fn serves_spec_and_docs() {
        let app: Router = mount(OpenApiRouter::new().routes(routes!(ping)), "T", "9.9.9");
        let get = |u: &'static str| Request::get(u).body(Body::empty()).unwrap();

        let res = app.clone().oneshot(get("/openapi.json")).await.unwrap();
        let bytes = axum::body::to_bytes(res.into_body(), usize::MAX)
            .await
            .unwrap();
        let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
        assert!(v["paths"]["/ping"].is_object());
        assert_eq!(v["info"]["title"], "T");
        assert_eq!(v["info"]["version"], "9.9.9");

        let res = app.oneshot(get("/docs")).await.unwrap();
        assert_eq!(res.status(), 200);
        assert!(
            res.headers()["content-type"]
                .to_str()
                .unwrap()
                .contains("text/html")
        );
    }
}