axa-openapi-docs 0.1.1

Serve OpenAPI documents and a pinned Swagger UI from Axum services.
Documentation
//! Serve `OpenAPI` documents and a pinned Swagger UI, and check a document against the routes a
//! service mounts.
//!
//! This works with a document generated by [`utoipa`] or one written by hand,
//! because both end up as JSON:
//!
//! ```
//! use axa_openapi_docs::{SPEC_PATH, UI_PATH, router, with_bearer_auth};
//! use axum::Router;
//! use serde_json::json;
//!
//! let mut spec = json!({
//!     "openapi": "3.1.0",
//!     "info": { "title": "Places", "version": "1.0.0" },
//!     "paths": {},
//! });
//! with_bearer_auth(&mut spec);
//!
//! let app: Router = Router::new().merge(router(spec, "Places"));
//! assert_eq!(SPEC_PATH, "/api-docs/openapi.json");
//! assert_eq!(UI_PATH, "/swagger-ui");
//! ```
//!
//! Both routes are public by design, so a service using `axa-paseto-auth` lists
//! them with `public_path`. A deployment that does not want its API described
//! publicly should simply not mount them.
//!
//! # The Swagger UI page
//!
//! The page loads Swagger UI from a CDN, which keeps the binary small, and that
//! makes the CDN part of the supply chain. So the page names one exact version
//! and carries a Subresource Integrity hash for each file, and the browser
//! refuses anything that does not match. The hashes in this crate were checked
//! against the package published on npm.

mod routes;

use axum::{
    Json, Router,
    http::header,
    response::{Html, IntoResponse},
    routing::get,
};
pub use routes::{Drift, dangling_refs, drift, shape};
use serde_json::{Value, json};
pub use utoipa;
use utoipa::OpenApi;

/// Where the document is served.
pub const SPEC_PATH: &str = "/api-docs/openapi.json";

/// Where the Swagger UI page is served.
pub const UI_PATH: &str = "/swagger-ui";

/// The exact Swagger UI version the page loads.
pub const SWAGGER_UI_VERSION: &str = "5.34.1";

/// The page's own policy, because `axa` sends a stricter one by default that would blank it. It
/// allows inline script for the page's one-line start-up, which holds nothing a caller supplies.
pub const PAGE_CSP: &str = "default-src 'none'; script-src 'unsafe-inline' https://unpkg.com; \
     style-src 'unsafe-inline' https://unpkg.com; img-src data: https:; connect-src 'self'; \
     base-uri 'none'; form-action 'none'; frame-ancestors 'none'";

/// Subresource Integrity hash of `swagger-ui.css`.
const CSS_INTEGRITY: &str =
    "sha384-4c3vsE5f+trhFyHrFrLM1fFGUn531NIaC7dcqEWIJdoRQJ5CkJbSuSCwXLpaS1KF";

/// Subresource Integrity hash of `swagger-ui-bundle.js`.
const JS_INTEGRITY: &str =
    "sha384-XFYN47VzPiDY6qPtxYKg0nqUeW/upo20xf1j2SUE7gT/i35FJB4cuS/71Iegzk8Z";

/// Escape text for HTML.
fn escape_html(text: &str) -> String {
    let mut escaped = String::with_capacity(text.len());
    for c in text.chars() {
        match c {
            '&' => escaped.push_str("&"),
            '<' => escaped.push_str("&lt;"),
            '>' => escaped.push_str("&gt;"),
            '"' => escaped.push_str("&quot;"),
            '\'' => escaped.push_str("&#39;"),
            other => escaped.push(other),
        }
    }
    escaped
}

/// The Swagger UI page for the document at `spec_url`.
#[must_use]
pub fn swagger_html(title: &str, spec_url: &str) -> String {
    let title = escape_html(title);
    // A JSON string is a valid JavaScript string, and escaping `<` keeps it
    // from closing the script element.
    let spec_url = json!(spec_url).to_string().replace('<', "\\u003c");
    let base = format!("https://unpkg.com/swagger-ui-dist@{SWAGGER_UI_VERSION}");
    format!(
        r#"<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <title>{title}</title>
  <link rel="stylesheet" href="{base}/swagger-ui.css" integrity="{CSS_INTEGRITY}" crossorigin="anonymous" />
</head>
<body>
  <div id="swagger-ui"></div>
  <script src="{base}/swagger-ui-bundle.js" integrity="{JS_INTEGRITY}" crossorigin="anonymous"></script>
  <script>
    window.ui = SwaggerUIBundle({{ url: {spec_url}, dom_id: '#swagger-ui' }});
  </script>
</body>
</html>
"#
    )
}

/// A router serving `spec` at [`SPEC_PATH`] and the page at [`UI_PATH`].
pub fn router<S>(spec: Value, title: &str) -> Router<S>
where
    S: Clone + Send + Sync + 'static,
{
    let page = swagger_html(title, SPEC_PATH);
    Router::new()
        .route(
            SPEC_PATH,
            get(move || {
                let spec = spec.clone();
                async move { Json(spec).into_response() }
            }),
        )
        .route(
            UI_PATH,
            get(move || {
                let page = page.clone();
                async move {
                    ([(header::CONTENT_SECURITY_POLICY, PAGE_CSP)], Html(page)).into_response()
                }
            }),
        )
}

/// Declare bearer authentication on a document, required by default.
///
/// An operation can opt out with its own empty `security` list. Other members
/// of `components` are left alone.
pub fn with_bearer_auth(spec: &mut Value) {
    let scheme = json!({ "type": "http", "scheme": "bearer", "bearerFormat": "PASETO" });
    let Some(root) = spec.as_object_mut() else {
        return;
    };
    let schemes = root
        .entry("components")
        .or_insert_with(|| json!({}))
        .as_object_mut()
        .map(|components| {
            components
                .entry("securitySchemes")
                .or_insert_with(|| json!({}))
        })
        .and_then(Value::as_object_mut);
    if let Some(schemes) = schemes {
        schemes.insert("bearer".to_string(), scheme);
    }
    root.insert("security".to_string(), json!([{ "bearer": [] }]));
}

/// The JSON for a `utoipa` document.
///
/// `null` if the document cannot be encoded as JSON, which would be a defect in the
/// `utoipa` types rather than in anything a caller supplied.
#[must_use]
pub fn spec_of<T: OpenApi>() -> Value {
    serde_json::to_value(T::openapi()).unwrap_or(Value::Null)
}

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

    fn spec() -> Value {
        json!({ "openapi": "3.1.0", "info": { "title": "T", "version": "1" }, "paths": {} })
    }

    async fn get_path(path: &str) -> axum::response::Response {
        let app: Router = router(spec(), "Places");
        let request = Request::builder().uri(path).body(Body::empty()).unwrap();
        app.oneshot(request).await.unwrap()
    }

    #[tokio::test]
    async fn the_document_is_served_as_json() {
        let response = get_path(SPEC_PATH).await;
        assert_eq!(response.status(), StatusCode::OK);
        assert_eq!(response.headers()[header::CONTENT_TYPE], "application/json");
        let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)
            .await
            .unwrap();
        let served: Value = serde_json::from_slice(&bytes).unwrap();
        assert_eq!(served, spec());
    }

    #[tokio::test]
    async fn the_page_is_served_as_html() {
        let response = get_path(UI_PATH).await;
        assert_eq!(response.status(), StatusCode::OK);
        let content_type = response.headers()[header::CONTENT_TYPE].to_str().unwrap();
        assert!(content_type.starts_with("text/html"), "{content_type}");
    }

    #[tokio::test]
    async fn the_page_sets_a_policy_that_lets_it_load() {
        use tower::ServiceExt as _;
        let request = axum::http::Request::builder()
            .uri(UI_PATH)
            .body(axum::body::Body::empty())
            .unwrap();
        let app: Router = router(spec(), "Places");
        let response = app.oneshot(request).await.unwrap();
        let policy = response.headers()[header::CONTENT_SECURITY_POLICY]
            .to_str()
            .unwrap();
        assert!(
            policy.contains("script-src 'unsafe-inline' https://unpkg.com"),
            "{policy}"
        );
        assert!(policy.contains("connect-src 'self'"), "{policy}");
    }

    #[test]
    fn the_page_pins_an_exact_version_with_integrity_hashes() {
        let page = swagger_html("T", SPEC_PATH);
        assert!(page.contains("swagger-ui-dist@5.34.1/swagger-ui-bundle.js"));
        assert!(page.contains(&format!(r#"integrity="{CSS_INTEGRITY}""#)));
        assert!(page.contains(&format!(r#"integrity="{JS_INTEGRITY}""#)));
        assert!(!page.contains("swagger-ui-dist@5/"));
        // Every remote file carries a hash: two files, two hashes.
        assert_eq!(page.matches("unpkg.com").count(), 2);
        assert_eq!(page.matches("integrity=").count(), 2);
    }

    #[test]
    fn the_title_cannot_inject_markup() {
        let page = swagger_html("<script>alert(1)</script>", SPEC_PATH);
        assert!(!page.contains("<script>alert"));
        assert!(page.contains("&lt;script&gt;alert(1)&lt;/script&gt;"));
    }

    #[test]
    fn the_spec_url_cannot_break_out_of_the_script() {
        let page = swagger_html("T", "</script><script>alert(1)</script>");
        assert!(!page.contains("<script>alert"));
    }

    #[test]
    fn html_special_characters_are_escaped() {
        assert_eq!(
            escape_html(r#"a&b<c>d"e'f"#),
            "a&amp;b&lt;c&gt;d&quot;e&#39;f"
        );
    }

    #[test]
    fn bearer_auth_is_declared_and_required() {
        let mut spec = spec();
        with_bearer_auth(&mut spec);
        assert_eq!(
            spec["components"]["securitySchemes"]["bearer"]["scheme"],
            "bearer"
        );
        assert_eq!(spec["security"], json!([{ "bearer": [] }]));
    }

    #[test]
    fn bearer_auth_keeps_other_components() {
        let mut spec = spec();
        spec["components"]["schemas"] = json!({ "Place": {} });
        with_bearer_auth(&mut spec);
        assert!(spec["components"]["schemas"]["Place"].is_object());
    }

    #[test]
    fn a_utoipa_document_becomes_json() {
        #[derive(OpenApi)]
        #[openapi(info(title = "Places", version = "1.2.3"))]
        struct Doc;

        let spec = spec_of::<Doc>();
        assert_eq!(spec["info"]["title"], "Places");
        assert_eq!(spec["info"]["version"], "1.2.3");
    }
}