footing 0.1.22

Feature-gated foundations for Rust backend services
Documentation
//! Documentation pages and their supporting routes.

mod assets;
mod options;
mod page;

use axum::{
    Router,
    body::Bytes,
    http::{Uri, header},
    response::Redirect,
    routing::{MethodRouter, get},
};
use serde_json::Value;
use thiserror::Error;
use utoipa::openapi::OpenApi;

use crate::result::{ClassifyError, ErrorCode, ErrorKind};

#[cfg(feature = "rapidoc-embedded")]
pub use assets::EMBEDDED_RAPIDOC_VERSION;
#[cfg(feature = "redoc-embedded")]
pub use assets::EMBEDDED_REDOC_VERSION;
pub use assets::{DocsAssets, DocsUi};

/// Invalid documentation route, options, or template.
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum DocsError {
    /// A mount path is not an absolute, literal URL path.
    #[error("invalid documentation mount path: {0}")]
    InvalidPath(String),
    /// A script URL is neither an HTTP(S) URL nor a relative URL.
    #[error("invalid documentation script URL: {0}")]
    InvalidAssetUrl(String),
    /// Native options have an invalid container type.
    #[error("invalid documentation options: {0}")]
    InvalidOptions(&'static str),
    /// A required template slot is missing or repeated.
    #[error("documentation template must contain exactly one {0} slot")]
    InvalidTemplate(&'static str),
    /// The OpenAPI document could not be serialized.
    #[error("cannot serialize the OpenAPI document: {0}")]
    Serialize(#[from] serde_json::Error),
}

impl ClassifyError for DocsError {
    fn error_kind(&self) -> ErrorKind {
        ErrorKind::Validation
    }

    fn error_code(&self) -> ErrorCode {
        ErrorCode::internal(match self {
            Self::InvalidPath(_) => "docs_invalid_path",
            Self::InvalidAssetUrl(_) => "docs_invalid_asset_url",
            Self::InvalidOptions(_) => "docs_invalid_options",
            Self::InvalidTemplate(_) => "docs_invalid_template",
            Self::Serialize(_) => "docs_serialization_failed",
        })
    }
}

/// Builds a ReDoc or RapiDoc page and all supporting routes.
///
/// Available with `openapi`; nothing is mounted until explicitly merged into
/// the application. Select the renderer and resource source with [`DocsUi`].
/// Native [`super::redoc::Redoc`] integration also remains available.
///
/// # Routes and access control
///
/// Mounting at `/docs` serves the page at `/docs/`, redirects `/docs`, and
/// serves `openapi.json`, `options.json`, `init.js`, `page.css`, and local
/// assets (`ui.js`, plus `ui.LICENSE.txt` for embedded bundles) below it.
/// All generated URLs are page-relative, including redirects, so nesting and
/// reverse proxies work when they preserve this layout. Forwarded headers are
/// not consulted.
/// Prefer mounting at `/docs` and nesting that router at `/api`. When mounting
/// at `/`, nest at `/api/docs/` with the trailing slash so relative resource URLs
/// resolve correctly. Axum then serves `/api/docs/`; the slashless `/api/docs`
/// entry does not match and is not redirected automatically.
///
/// Apply application authentication to the returned router **before** merging.
/// Page, JSON and local resources then share the same middleware. A bearer
/// header on the HTML request alone does not authenticate browser subrequests;
/// use a suitable cookie or HTTP authentication policy. Nothing enforces an
/// administrator role automatically. Responses default to
/// `Cache-Control: private, no-cache`; middleware can override it.
///
/// # Resources and CSP
///
/// Embedded bundles are version-pinned and require no build-time downloads.
/// Presets use system fonts; RapiDoc's preset disables CDN font loading.
/// Applications must localize any external references, images, CSS or URLs in
/// their own documents, overrides and templates for fully offline deployment.
/// Turning off presets restores each renderer's native defaults, including
/// RapiDoc's external fonts. OpenAPI content and native options are trusted
/// application input; neither renderer is an HTML sanitizer for arbitrary specs.
///
/// The generated page contains no inline scripts or interpolated JavaScript.
/// An external initializer fetches JSON options, then starts the selected UI.
/// Renderers create runtime styles; ReDoc additionally uses a Blob search worker.
/// See the documentation example for a CSP allowing these while forbidding inline
/// scripts. CSP and authorization remain application policy.
///
/// # Example
///
/// ```rust
/// use footing::http::openapi::{DocsAssets, DocsUi, OpenApiDocs, utoipa};
/// use utoipa::openapi::{OpenApi, Info, path::Paths};
///
/// let document = OpenApi::new(Info::new("Inventory API", "1"), Paths::new());
/// let ui = DocsUi::RapiDoc(DocsAssets::url("/static/rapidoc-min.js"));
/// let docs = OpenApiDocs::new(document, "/docs", ui)
///     .with_options(serde_json::json!({"theme": "dark", "primary-color": "#8b2252"}))
///     .into_router::<()>()?;
/// // Apply application authentication to docs before merging into the app.
/// let app = axum::Router::new().merge(docs);
/// # let _: axum::Router = app;
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[must_use]
pub struct OpenApiDocs {
    document: OpenApi,
    path: String,
    ui: DocsUi,
    title: String,
    options: Value,
    preset: bool,
    template: String,
}

impl std::fmt::Debug for OpenApiDocs {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("OpenApiDocs")
            .field("path", &self.path)
            .field("ui", &self.ui)
            .field("title", &self.title)
            .field("preset", &self.preset)
            .finish_non_exhaustive()
    }
}

impl OpenApiDocs {
    /// Creates an explicitly mounted page using the renderer's presentation preset.
    ///
    /// The title defaults to the document's `info.title`. Paths are validated by
    /// [`Self::into_router`]; `/`, `/docs`, and `/docs/` are supported. Parameters,
    /// wildcards, percent escapes, dot segments, and empty segments are rejected.
    pub fn new(document: OpenApi, path: impl Into<String>, ui: DocsUi) -> Self {
        Self {
            title: document.info.title.clone(),
            document,
            path: path.into(),
            ui,
            options: serde_json::json!({}),
            preset: true,
            template: include_str!("template.html").to_owned(),
        }
    }

    /// Replaces the page title. Text is HTML-escaped, never interpreted as markup.
    pub fn with_title(mut self, title: impl Into<String>) -> Self {
        self.title = title.into();
        self
    }

    /// Sets native options, replacing any previous caller overrides.
    ///
    /// Precedence: renderer defaults, footing preset, then caller options.
    /// ReDoc takes its native JSON object: objects merge recursively, while
    /// arrays, scalars and null replace previous values. The root and `theme`
    /// must be objects. Preset aliases are normalized; canonical names win.
    /// Existing upstream `redoc::Config` values can be passed with
    /// `with_options(config.load())` after importing that trait.
    ///
    /// RapiDoc takes native kebab-case attribute names, with string, boolean or
    /// number values. Values become strings through `setAttribute`; overrides
    /// replace preset attributes. For example `{"theme":"dark","allow-try":false}`.
    /// Event handlers and `spec-url` are rejected; the component owns the spec URL.
    /// Unknown attributes pass through for newer compatible bundles.
    ///
    /// Both presets enable search/downloads and use system fonts. ReDoc expands
    /// one schema level and two sample levels. RapiDoc uses focused mode with
    /// table schemas, expanded descriptions, the schema tab, colored method
    /// labels, method sorting and a blue primary color. It disables CDN fonts
    /// and keeps native theme selection, schema expansion and document loaders.
    /// RapiDoc persists authentication in browser localStorage; override
    /// `persist-auth` with `false` to disable it.
    /// Its try-it console remains available; disabling it is a UI preference,
    /// not an authorization boundary.
    pub fn with_options(mut self, options: Value) -> Self {
        self.options = options;
        self
    }

    /// Disables footing's preset while preserving the caller's native options.
    pub fn without_preset(mut self) -> Self {
        self.preset = false;
        self
    }

    /// Replaces the page template with trusted application HTML.
    ///
    /// Include exactly one `{{title}}` in an HTML text context, `{{head}}` in
    /// `<head>`, and `{{body}}` in `<body>`. Title text is escaped; head and body
    /// contain the component's generated elements. Slots are substituted once,
    /// so slot-like text inside a title or URL is not interpreted a second time.
    ///
    /// Applications own additional markup/scripts and their CSP, resource and
    /// trust requirements. This is not a sanitizer for arbitrary HTML. Custom
    /// templates must not change URL resolution with a `<base>` element.
    ///
    /// ```rust
    /// # use footing::http::openapi::{DocsAssets, DocsUi, OpenApiDocs};
    /// # use footing::http::openapi::utoipa::openapi::{OpenApi, Info, path::Paths};
    /// # let document = OpenApi::new(Info::new("Inventory API", "1"), Paths::new());
    /// # let docs = OpenApiDocs::new(document, "/docs", DocsUi::Redoc(DocsAssets::url("/static/redoc.js")));
    /// let docs = docs.with_title("Developer reference").with_template(r#"<!doctype html>
    /// <html lang="en">
    /// <head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
    /// <title>{{title}}</title>{{head}}</head>
    /// <body><header>Developer reference</header>{{body}}</body>
    /// </html>"#);
    /// # let _: axum::Router = docs.into_router()?;
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn with_template(mut self, template: impl Into<String>) -> Self {
        self.template = template.into();
        self
    }

    /// Validates configuration and creates the complete, composable route set.
    ///
    /// The document and options are serialized once and shared across requests.
    /// The state type is left to the application. Conflicts when merging this
    /// router with application routes follow Axum's normal panic behavior.
    ///
    /// Protect the complete route set using an application's authentication
    /// middleware. For applications that install [`crate::http::VerifiedAuthentication`]
    /// in an outer layer, [`crate::http::CurrentPrincipal`] rejects requests
    /// without a verified principal. Local assets share the same guard:
    ///
    /// ```no_run
    /// use axum::{Router, middleware};
    /// use footing::http::{CurrentPrincipal, openapi::{DocsAssets, DocsUi, OpenApiDocs}};
    /// # use footing::http::openapi::utoipa::openapi::{OpenApi, Info, path::Paths};
    /// # let document = OpenApi::new(Info::new("Inventory API", "1"), Paths::new());
    ///
    /// let assets = DocsAssets::local(std::fs::read("assets/redoc.standalone.js")?);
    /// let docs = OpenApiDocs::new(document, "/docs", DocsUi::Redoc(assets))
    ///     .into_router::<()>()?
    ///     .route_layer(middleware::from_extractor::<CurrentPrincipal>());
    /// let app = Router::new().merge(docs);
    /// // The outer authentication layer must validate credentials before this guard.
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn into_router<S: Clone + Send + Sync + 'static>(self) -> Result<Router<S>, DocsError> {
        let mount = mount_path(&self.path)?;
        let options = options::resolve(self.options, self.preset, &self.ui)?;
        let script_url = self.ui.assets().script_url()?;
        let html = page::render(&self.template, &self.title, script_url, self.ui.name())?;
        let mut router = Router::new()
            .route(
                &format!("{mount}/"),
                resource("text/html; charset=utf-8", html),
            )
            .route(
                &format!("{mount}/openapi.json"),
                resource("application/json", serde_json::to_vec(&self.document)?),
            )
            .route(
                &format!("{mount}/options.json"),
                resource("application/json", serde_json::to_vec(&options)?),
            )
            .route(
                &format!("{mount}/init.js"),
                resource(
                    "text/javascript; charset=utf-8",
                    include_bytes!("init.js").as_slice(),
                ),
            )
            .route(
                &format!("{mount}/page.css"),
                resource(
                    "text/css; charset=utf-8",
                    include_bytes!("page.css").as_slice(),
                ),
            );
        if !mount.is_empty() {
            let leaf = mount.rsplit('/').next().unwrap_or_default().to_owned();
            router = router.route(
                mount,
                get(move |uri: Uri| {
                    let mut location = format!("{leaf}/");
                    if let Some(query) = uri.query() {
                        location.push('?');
                        location.push_str(query);
                    }
                    async move {
                        (
                            [(header::CACHE_CONTROL, "private, no-cache")],
                            Redirect::permanent(&location),
                        )
                    }
                }),
            );
        }
        Ok(self.ui.into_assets().mount(router, mount))
    }
}

fn mount_path(path: &str) -> Result<&str, DocsError> {
    let mount = path.strip_suffix('/').unwrap_or(path);
    if !path.starts_with('/')
        || !path
            .bytes()
            .all(|b| b.is_ascii_alphanumeric() || b"/-._~".contains(&b))
        || (!mount.is_empty()
            && mount[1..]
                .split('/')
                .any(|s| s.is_empty() || s == "." || s == ".."))
    {
        return Err(DocsError::InvalidPath(path.to_owned()));
    }
    Ok(mount)
}

fn resource<S: Clone + Send + Sync + 'static>(
    content_type: &'static str,
    bytes: impl Into<Bytes>,
) -> MethodRouter<S> {
    let bytes = bytes.into();
    get(move || {
        let bytes = bytes.clone();
        async move {
            (
                [
                    (header::CONTENT_TYPE, content_type),
                    (header::CACHE_CONTROL, "private, no-cache"),
                    (header::X_CONTENT_TYPE_OPTIONS, "nosniff"),
                ],
                bytes,
            )
        }
    })
}