Skip to main content

axa_openapi_docs/
lib.rs

1//! Serve `OpenAPI` documents and a pinned Swagger UI, and check a document against the routes a
2//! service mounts.
3//!
4//! This works with a document generated by [`utoipa`] or one written by hand,
5//! because both end up as JSON:
6//!
7//! ```
8//! use axa_openapi_docs::{SPEC_PATH, UI_PATH, router, with_bearer_auth};
9//! use axum::Router;
10//! use serde_json::json;
11//!
12//! let mut spec = json!({
13//!     "openapi": "3.1.0",
14//!     "info": { "title": "Places", "version": "1.0.0" },
15//!     "paths": {},
16//! });
17//! with_bearer_auth(&mut spec);
18//!
19//! let app: Router = Router::new().merge(router(spec, "Places"));
20//! assert_eq!(SPEC_PATH, "/api-docs/openapi.json");
21//! assert_eq!(UI_PATH, "/swagger-ui");
22//! ```
23//!
24//! Both routes are public by design, so a service using `axa-paseto-auth` lists
25//! them with `public_path`. A deployment that does not want its API described
26//! publicly should simply not mount them.
27//!
28//! # The Swagger UI page
29//!
30//! The page loads Swagger UI from a CDN, which keeps the binary small, and that
31//! makes the CDN part of the supply chain. So the page names one exact version
32//! and carries a Subresource Integrity hash for each file, and the browser
33//! refuses anything that does not match. The hashes in this crate were checked
34//! against the package published on npm.
35
36mod routes;
37
38use axum::{
39    Json, Router,
40    http::header,
41    response::{Html, IntoResponse},
42    routing::get,
43};
44pub use routes::{Drift, dangling_refs, drift, shape};
45use serde_json::{Value, json};
46pub use utoipa;
47use utoipa::OpenApi;
48
49/// Where the document is served.
50pub const SPEC_PATH: &str = "/api-docs/openapi.json";
51
52/// Where the Swagger UI page is served.
53pub const UI_PATH: &str = "/swagger-ui";
54
55/// The exact Swagger UI version the page loads.
56pub const SWAGGER_UI_VERSION: &str = "5.34.1";
57
58/// The page's own policy, because `axa` sends a stricter one by default that would blank it. It
59/// allows inline script for the page's one-line start-up, which holds nothing a caller supplies.
60pub const PAGE_CSP: &str = "default-src 'none'; script-src 'unsafe-inline' https://unpkg.com; \
61     style-src 'unsafe-inline' https://unpkg.com; img-src data: https:; connect-src 'self'; \
62     base-uri 'none'; form-action 'none'; frame-ancestors 'none'";
63
64/// Subresource Integrity hash of `swagger-ui.css`.
65const CSS_INTEGRITY: &str =
66    "sha384-4c3vsE5f+trhFyHrFrLM1fFGUn531NIaC7dcqEWIJdoRQJ5CkJbSuSCwXLpaS1KF";
67
68/// Subresource Integrity hash of `swagger-ui-bundle.js`.
69const JS_INTEGRITY: &str =
70    "sha384-XFYN47VzPiDY6qPtxYKg0nqUeW/upo20xf1j2SUE7gT/i35FJB4cuS/71Iegzk8Z";
71
72/// Escape text for HTML.
73fn escape_html(text: &str) -> String {
74    let mut escaped = String::with_capacity(text.len());
75    for c in text.chars() {
76        match c {
77            '&' => escaped.push_str("&"),
78            '<' => escaped.push_str("&lt;"),
79            '>' => escaped.push_str("&gt;"),
80            '"' => escaped.push_str("&quot;"),
81            '\'' => escaped.push_str("&#39;"),
82            other => escaped.push(other),
83        }
84    }
85    escaped
86}
87
88/// The Swagger UI page for the document at `spec_url`.
89#[must_use]
90pub fn swagger_html(title: &str, spec_url: &str) -> String {
91    let title = escape_html(title);
92    // A JSON string is a valid JavaScript string, and escaping `<` keeps it
93    // from closing the script element.
94    let spec_url = json!(spec_url).to_string().replace('<', "\\u003c");
95    let base = format!("https://unpkg.com/swagger-ui-dist@{SWAGGER_UI_VERSION}");
96    format!(
97        r#"<!DOCTYPE html>
98<html lang="en">
99<head>
100  <meta charset="utf-8" />
101  <meta name="viewport" content="width=device-width, initial-scale=1" />
102  <title>{title}</title>
103  <link rel="stylesheet" href="{base}/swagger-ui.css" integrity="{CSS_INTEGRITY}" crossorigin="anonymous" />
104</head>
105<body>
106  <div id="swagger-ui"></div>
107  <script src="{base}/swagger-ui-bundle.js" integrity="{JS_INTEGRITY}" crossorigin="anonymous"></script>
108  <script>
109    window.ui = SwaggerUIBundle({{ url: {spec_url}, dom_id: '#swagger-ui' }});
110  </script>
111</body>
112</html>
113"#
114    )
115}
116
117/// A router serving `spec` at [`SPEC_PATH`] and the page at [`UI_PATH`].
118pub fn router<S>(spec: Value, title: &str) -> Router<S>
119where
120    S: Clone + Send + Sync + 'static,
121{
122    let page = swagger_html(title, SPEC_PATH);
123    Router::new()
124        .route(
125            SPEC_PATH,
126            get(move || {
127                let spec = spec.clone();
128                async move { Json(spec).into_response() }
129            }),
130        )
131        .route(
132            UI_PATH,
133            get(move || {
134                let page = page.clone();
135                async move {
136                    ([(header::CONTENT_SECURITY_POLICY, PAGE_CSP)], Html(page)).into_response()
137                }
138            }),
139        )
140}
141
142/// Declare bearer authentication on a document, required by default.
143///
144/// An operation can opt out with its own empty `security` list. Other members
145/// of `components` are left alone.
146pub fn with_bearer_auth(spec: &mut Value) {
147    let scheme = json!({ "type": "http", "scheme": "bearer", "bearerFormat": "PASETO" });
148    let Some(root) = spec.as_object_mut() else {
149        return;
150    };
151    let schemes = root
152        .entry("components")
153        .or_insert_with(|| json!({}))
154        .as_object_mut()
155        .map(|components| {
156            components
157                .entry("securitySchemes")
158                .or_insert_with(|| json!({}))
159        })
160        .and_then(Value::as_object_mut);
161    if let Some(schemes) = schemes {
162        schemes.insert("bearer".to_string(), scheme);
163    }
164    root.insert("security".to_string(), json!([{ "bearer": [] }]));
165}
166
167/// The JSON for a `utoipa` document.
168///
169/// `null` if the document cannot be encoded as JSON, which would be a defect in the
170/// `utoipa` types rather than in anything a caller supplied.
171#[must_use]
172pub fn spec_of<T: OpenApi>() -> Value {
173    serde_json::to_value(T::openapi()).unwrap_or(Value::Null)
174}
175
176#[cfg(test)]
177mod tests {
178    use super::*;
179    use axum::{
180        body::Body,
181        http::{Request, StatusCode, header},
182    };
183    use tower::ServiceExt;
184
185    fn spec() -> Value {
186        json!({ "openapi": "3.1.0", "info": { "title": "T", "version": "1" }, "paths": {} })
187    }
188
189    async fn get_path(path: &str) -> axum::response::Response {
190        let app: Router = router(spec(), "Places");
191        let request = Request::builder().uri(path).body(Body::empty()).unwrap();
192        app.oneshot(request).await.unwrap()
193    }
194
195    #[tokio::test]
196    async fn the_document_is_served_as_json() {
197        let response = get_path(SPEC_PATH).await;
198        assert_eq!(response.status(), StatusCode::OK);
199        assert_eq!(response.headers()[header::CONTENT_TYPE], "application/json");
200        let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)
201            .await
202            .unwrap();
203        let served: Value = serde_json::from_slice(&bytes).unwrap();
204        assert_eq!(served, spec());
205    }
206
207    #[tokio::test]
208    async fn the_page_is_served_as_html() {
209        let response = get_path(UI_PATH).await;
210        assert_eq!(response.status(), StatusCode::OK);
211        let content_type = response.headers()[header::CONTENT_TYPE].to_str().unwrap();
212        assert!(content_type.starts_with("text/html"), "{content_type}");
213    }
214
215    #[tokio::test]
216    async fn the_page_sets_a_policy_that_lets_it_load() {
217        use tower::ServiceExt as _;
218        let request = axum::http::Request::builder()
219            .uri(UI_PATH)
220            .body(axum::body::Body::empty())
221            .unwrap();
222        let app: Router = router(spec(), "Places");
223        let response = app.oneshot(request).await.unwrap();
224        let policy = response.headers()[header::CONTENT_SECURITY_POLICY]
225            .to_str()
226            .unwrap();
227        assert!(
228            policy.contains("script-src 'unsafe-inline' https://unpkg.com"),
229            "{policy}"
230        );
231        assert!(policy.contains("connect-src 'self'"), "{policy}");
232    }
233
234    #[test]
235    fn the_page_pins_an_exact_version_with_integrity_hashes() {
236        let page = swagger_html("T", SPEC_PATH);
237        assert!(page.contains("swagger-ui-dist@5.34.1/swagger-ui-bundle.js"));
238        assert!(page.contains(&format!(r#"integrity="{CSS_INTEGRITY}""#)));
239        assert!(page.contains(&format!(r#"integrity="{JS_INTEGRITY}""#)));
240        assert!(!page.contains("swagger-ui-dist@5/"));
241        // Every remote file carries a hash: two files, two hashes.
242        assert_eq!(page.matches("unpkg.com").count(), 2);
243        assert_eq!(page.matches("integrity=").count(), 2);
244    }
245
246    #[test]
247    fn the_title_cannot_inject_markup() {
248        let page = swagger_html("<script>alert(1)</script>", SPEC_PATH);
249        assert!(!page.contains("<script>alert"));
250        assert!(page.contains("&lt;script&gt;alert(1)&lt;/script&gt;"));
251    }
252
253    #[test]
254    fn the_spec_url_cannot_break_out_of_the_script() {
255        let page = swagger_html("T", "</script><script>alert(1)</script>");
256        assert!(!page.contains("<script>alert"));
257    }
258
259    #[test]
260    fn html_special_characters_are_escaped() {
261        assert_eq!(
262            escape_html(r#"a&b<c>d"e'f"#),
263            "a&amp;b&lt;c&gt;d&quot;e&#39;f"
264        );
265    }
266
267    #[test]
268    fn bearer_auth_is_declared_and_required() {
269        let mut spec = spec();
270        with_bearer_auth(&mut spec);
271        assert_eq!(
272            spec["components"]["securitySchemes"]["bearer"]["scheme"],
273            "bearer"
274        );
275        assert_eq!(spec["security"], json!([{ "bearer": [] }]));
276    }
277
278    #[test]
279    fn bearer_auth_keeps_other_components() {
280        let mut spec = spec();
281        spec["components"]["schemas"] = json!({ "Place": {} });
282        with_bearer_auth(&mut spec);
283        assert!(spec["components"]["schemas"]["Place"].is_object());
284    }
285
286    #[test]
287    fn a_utoipa_document_becomes_json() {
288        #[derive(OpenApi)]
289        #[openapi(info(title = "Places", version = "1.2.3"))]
290        struct Doc;
291
292        let spec = spec_of::<Doc>();
293        assert_eq!(spec["info"]["title"], "Places");
294        assert_eq!(spec["info"]["version"], "1.2.3");
295    }
296}