Skip to main content

seiva_http/
docs.rs

1//! The interactive API-reference pages — Seiva's FastAPI `/docs` parity.
2//!
3//! FastAPI serves **Swagger UI** at `/docs` and **ReDoc** at `/redoc` out of the
4//! box, both rendering the service's own OpenAPI document. Seiva matches that and
5//! adds a third, modern renderer:
6//!
7//! | route      | renderer   | FastAPI analogue |
8//! |------------|------------|------------------|
9//! | `/docs`    | Swagger UI | `/docs`          |
10//! | `/redoc`   | ReDoc      | `/redoc`         |
11//! | `/scalar`  | Scalar     | — (bonus)        |
12//!
13//! Every page points at the **relative** `/openapi.json`, so it works behind any
14//! host or path prefix, and the document itself is generated from the facades
15//! linked into the binary (no hand-written spec, no per-handler annotations — the
16//! `async fn` contract *is* the source). The viewer bundles load from a CDN, as
17//! FastAPI's Swagger/ReDoc assets do; these are developer-facing documentation
18//! pages, not data-plane responses, so the CDN dependency is acceptable here.
19//!
20//! Because the framework's default response CSP is `default-src 'none'` (see
21//! [`security_headers`](crate::security_headers)), these pages would otherwise
22//! load nothing — the CDN script and the inline bootstrap would both be blocked
23//! and the page would render blank. So each handler sets its **own**, narrower
24//! CSP ([`DOCS_CSP`]) that permits exactly the CDN and the same-origin spec fetch;
25//! `security_headers` only fills in a header that is *absent*, so this scoped
26//! policy wins for the docs pages while every API/JSON response keeps the strict
27//! default.
28
29use axum::http::header::CONTENT_SECURITY_POLICY;
30use axum::response::{Html, IntoResponse, Response};
31
32/// `GET /docs` — **Swagger UI** over the service's `/openapi.json`. This is the
33/// FastAPI-identical route and renderer: the same page a FastAPI developer
34/// reaches at `/docs`, so the muscle memory transfers.
35pub const SWAGGER_HTML: &str = r##"<!doctype html>
36<html lang="en">
37  <head>
38    <meta charset="utf-8" />
39    <meta name="viewport" content="width=device-width, initial-scale=1" />
40    <title>Delonix Seiva — API reference (Swagger UI)</title>
41    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/swagger-ui-dist/swagger-ui.css" />
42  </head>
43  <body>
44    <div id="swagger-ui"></div>
45    <script src="https://cdn.jsdelivr.net/npm/swagger-ui-dist/swagger-ui-bundle.js"></script>
46    <script>
47      window.onload = function () {
48        window.ui = SwaggerUIBundle({
49          url: "/openapi.json",
50          dom_id: "#swagger-ui",
51          deepLinking: true,
52          tryItOutEnabled: true,
53        });
54      };
55    </script>
56  </body>
57</html>
58"##;
59
60/// Back-compat alias: the `/docs` page HTML. Historically this served Scalar;
61/// it now serves Swagger UI for FastAPI parity. Kept so downstream `pub use`
62/// sites keep compiling.
63pub const DOCS_HTML: &str = SWAGGER_HTML;
64
65/// `GET /redoc` — **ReDoc** over the service's `/openapi.json`. FastAPI's second
66/// built-in renderer; a three-pane reference that reads well for large APIs.
67pub const REDOC_HTML: &str = r#"<!doctype html>
68<html lang="en">
69  <head>
70    <meta charset="utf-8" />
71    <meta name="viewport" content="width=device-width, initial-scale=1" />
72    <title>Delonix Seiva — API reference (ReDoc)</title>
73  </head>
74  <body>
75    <redoc spec-url="/openapi.json"></redoc>
76    <script src="https://cdn.jsdelivr.net/npm/redoc/bundles/redoc.standalone.js"></script>
77  </body>
78</html>
79"#;
80
81/// `GET /scalar` — **Scalar**, a single-page modern API reference. Kept as a
82/// bonus renderer alongside the FastAPI-parity Swagger UI and ReDoc pages.
83pub const SCALAR_HTML: &str = r#"<!doctype html>
84<html lang="en">
85  <head>
86    <meta charset="utf-8" />
87    <meta name="viewport" content="width=device-width, initial-scale=1" />
88    <title>Delonix Seiva — API reference (Scalar)</title>
89  </head>
90  <body>
91    <script id="api-reference" data-url="/openapi.json"></script>
92    <script src="https://cdn.jsdelivr.net/npm/@scalar/api-reference"></script>
93  </body>
94</html>
95"#;
96
97/// The Content-Security-Policy for the documentation pages — narrower than a
98/// wildcard, wider than the API's `default-src 'none'`. It permits only what the
99/// viewers need: their scripts and styles from jsDelivr (plus the inline
100/// bootstrap), data/CDN images and fonts, a same-origin fetch of `/openapi.json`,
101/// and `blob:` web workers (ReDoc renders in a worker). Everything else stays
102/// denied, so the documentation pages are no softer than they must be.
103pub const DOCS_CSP: &str = "default-src 'none'; \
104    script-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net; \
105    style-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net; \
106    img-src 'self' data: https://cdn.jsdelivr.net; \
107    font-src 'self' data: https://cdn.jsdelivr.net; \
108    connect-src 'self' https://cdn.jsdelivr.net; \
109    worker-src 'self' blob:; \
110    child-src 'self' blob:; \
111    frame-ancestors 'none'";
112
113/// `GET /docs` — serves [`SWAGGER_HTML`] under the scoped [`DOCS_CSP`].
114pub async fn docs_handler() -> Response {
115    ([(CONTENT_SECURITY_POLICY, DOCS_CSP)], Html(SWAGGER_HTML)).into_response()
116}
117
118/// `GET /redoc` — serves [`REDOC_HTML`] under the scoped [`DOCS_CSP`].
119pub async fn redoc_handler() -> Response {
120    ([(CONTENT_SECURITY_POLICY, DOCS_CSP)], Html(REDOC_HTML)).into_response()
121}
122
123/// `GET /scalar` — serves [`SCALAR_HTML`] under the scoped [`DOCS_CSP`].
124pub async fn scalar_handler() -> Response {
125    ([(CONTENT_SECURITY_POLICY, DOCS_CSP)], Html(SCALAR_HTML)).into_response()
126}
127
128#[cfg(test)]
129mod tests {
130    use crate::{router, Health};
131    use axum::body::Body;
132    use axum::http::{Request, StatusCode};
133    use tower::ServiceExt; // for `oneshot`
134
135    async fn fetch(uri: &str) -> (StatusCode, String, String) {
136        let app = router(Health::starting());
137        let res = app
138            .oneshot(Request::builder().uri(uri).body(Body::empty()).unwrap())
139            .await
140            .unwrap();
141        let status = res.status();
142        let ctype = res
143            .headers()
144            .get("content-type")
145            .map(|v| v.to_str().unwrap().to_string())
146            .unwrap_or_default();
147        let csp = res
148            .headers()
149            .get("content-security-policy")
150            .map(|v| v.to_str().unwrap().to_string())
151            .unwrap_or_default();
152        let bytes = axum::body::to_bytes(res.into_body(), usize::MAX)
153            .await
154            .unwrap();
155        let body = String::from_utf8(bytes.to_vec()).unwrap();
156        assert_eq!(status, StatusCode::OK, "{uri} should be 200");
157        assert!(ctype.starts_with("text/html"), "{uri} should be html");
158        // Each page renders the service's OWN spec.
159        assert!(
160            body.contains("/openapi.json"),
161            "{uri} must point at the spec"
162        );
163        (status, body, csp)
164    }
165
166    #[tokio::test]
167    async fn docs_serves_swagger_ui() {
168        let (_s, body, _csp) = fetch("/docs").await;
169        assert!(
170            body.contains("swagger-ui") && body.contains("SwaggerUIBundle"),
171            "/docs must render Swagger UI (FastAPI parity)"
172        );
173    }
174
175    #[tokio::test]
176    async fn redoc_serves_redoc() {
177        let (_s, body, _csp) = fetch("/redoc").await;
178        assert!(body.contains("redoc"), "/redoc must render ReDoc");
179    }
180
181    #[tokio::test]
182    async fn scalar_serves_scalar() {
183        let (_s, body, _csp) = fetch("/scalar").await;
184        assert!(
185            body.contains("@scalar/api-reference"),
186            "/scalar must render Scalar"
187        );
188    }
189
190    #[tokio::test]
191    async fn docs_pages_carry_their_own_csp_not_the_blank_default() {
192        for uri in ["/docs", "/redoc", "/scalar"] {
193            let (_s, _body, csp) = fetch(uri).await;
194            assert!(
195                csp.contains("https://cdn.jsdelivr.net"),
196                "the {uri} CSP must allow the viewer CDN, got: {csp}"
197            );
198            assert_ne!(
199                csp, "default-src 'none'; frame-ancestors 'none'",
200                "the {uri} page must not inherit the API's blank-page CSP"
201            );
202        }
203    }
204}