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    spec["components"]["securitySchemes"]["bearer"] = scheme;
149    spec["security"] = json!([{ "bearer": [] }]);
150}
151
152/// The JSON for a `utoipa` document.
153///
154/// # Panics
155///
156/// If the document cannot be encoded as JSON, which would be a defect in the
157/// `utoipa` types rather than in anything a caller supplied.
158#[must_use]
159pub fn spec_of<T: OpenApi>() -> Value {
160    serde_json::to_value(T::openapi()).expect("an OpenAPI document encodes as JSON")
161}
162
163#[cfg(test)]
164mod tests {
165    use super::*;
166    use axum::{
167        body::Body,
168        http::{Request, StatusCode, header},
169    };
170    use tower::ServiceExt;
171
172    fn spec() -> Value {
173        json!({ "openapi": "3.1.0", "info": { "title": "T", "version": "1" }, "paths": {} })
174    }
175
176    async fn get_path(path: &str) -> axum::response::Response {
177        let app: Router = router(spec(), "Places");
178        let request = Request::builder().uri(path).body(Body::empty()).unwrap();
179        app.oneshot(request).await.unwrap()
180    }
181
182    #[tokio::test]
183    async fn the_document_is_served_as_json() {
184        let response = get_path(SPEC_PATH).await;
185        assert_eq!(response.status(), StatusCode::OK);
186        assert_eq!(response.headers()[header::CONTENT_TYPE], "application/json");
187        let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)
188            .await
189            .unwrap();
190        let served: Value = serde_json::from_slice(&bytes).unwrap();
191        assert_eq!(served, spec());
192    }
193
194    #[tokio::test]
195    async fn the_page_is_served_as_html() {
196        let response = get_path(UI_PATH).await;
197        assert_eq!(response.status(), StatusCode::OK);
198        let content_type = response.headers()[header::CONTENT_TYPE].to_str().unwrap();
199        assert!(content_type.starts_with("text/html"), "{content_type}");
200    }
201
202    #[tokio::test]
203    async fn the_page_sets_a_policy_that_lets_it_load() {
204        use tower::ServiceExt as _;
205        let request = axum::http::Request::builder()
206            .uri(UI_PATH)
207            .body(axum::body::Body::empty())
208            .unwrap();
209        let app: Router = router(spec(), "Places");
210        let response = app.oneshot(request).await.unwrap();
211        let policy = response.headers()[header::CONTENT_SECURITY_POLICY]
212            .to_str()
213            .unwrap();
214        assert!(
215            policy.contains("script-src 'unsafe-inline' https://unpkg.com"),
216            "{policy}"
217        );
218        assert!(policy.contains("connect-src 'self'"), "{policy}");
219    }
220
221    #[test]
222    fn the_page_pins_an_exact_version_with_integrity_hashes() {
223        let page = swagger_html("T", SPEC_PATH);
224        assert!(page.contains("swagger-ui-dist@5.34.1/swagger-ui-bundle.js"));
225        assert!(page.contains(&format!(r#"integrity="{CSS_INTEGRITY}""#)));
226        assert!(page.contains(&format!(r#"integrity="{JS_INTEGRITY}""#)));
227        assert!(!page.contains("swagger-ui-dist@5/"));
228        // Every remote file carries a hash: two files, two hashes.
229        assert_eq!(page.matches("unpkg.com").count(), 2);
230        assert_eq!(page.matches("integrity=").count(), 2);
231    }
232
233    #[test]
234    fn the_title_cannot_inject_markup() {
235        let page = swagger_html("<script>alert(1)</script>", SPEC_PATH);
236        assert!(!page.contains("<script>alert"));
237        assert!(page.contains("&lt;script&gt;alert(1)&lt;/script&gt;"));
238    }
239
240    #[test]
241    fn the_spec_url_cannot_break_out_of_the_script() {
242        let page = swagger_html("T", "</script><script>alert(1)</script>");
243        assert!(!page.contains("<script>alert"));
244    }
245
246    #[test]
247    fn html_special_characters_are_escaped() {
248        assert_eq!(
249            escape_html(r#"a&b<c>d"e'f"#),
250            "a&amp;b&lt;c&gt;d&quot;e&#39;f"
251        );
252    }
253
254    #[test]
255    fn bearer_auth_is_declared_and_required() {
256        let mut spec = spec();
257        with_bearer_auth(&mut spec);
258        assert_eq!(
259            spec["components"]["securitySchemes"]["bearer"]["scheme"],
260            "bearer"
261        );
262        assert_eq!(spec["security"], json!([{ "bearer": [] }]));
263    }
264
265    #[test]
266    fn bearer_auth_keeps_other_components() {
267        let mut spec = spec();
268        spec["components"]["schemas"] = json!({ "Place": {} });
269        with_bearer_auth(&mut spec);
270        assert!(spec["components"]["schemas"]["Place"].is_object());
271    }
272
273    #[test]
274    fn a_utoipa_document_becomes_json() {
275        #[derive(OpenApi)]
276        #[openapi(info(title = "Places", version = "1.2.3"))]
277        struct Doc;
278
279        let spec = spec_of::<Doc>();
280        assert_eq!(spec["info"]["title"], "Places");
281        assert_eq!(spec["info"]["version"], "1.2.3");
282    }
283}