1mod 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
49pub const SPEC_PATH: &str = "/api-docs/openapi.json";
51
52pub const UI_PATH: &str = "/swagger-ui";
54
55pub const SWAGGER_UI_VERSION: &str = "5.34.1";
57
58pub 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
64const CSS_INTEGRITY: &str =
66 "sha384-4c3vsE5f+trhFyHrFrLM1fFGUn531NIaC7dcqEWIJdoRQJ5CkJbSuSCwXLpaS1KF";
67
68const JS_INTEGRITY: &str =
70 "sha384-XFYN47VzPiDY6qPtxYKg0nqUeW/upo20xf1j2SUE7gT/i35FJB4cuS/71Iegzk8Z";
71
72fn 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("<"),
79 '>' => escaped.push_str(">"),
80 '"' => escaped.push_str("""),
81 '\'' => escaped.push_str("'"),
82 other => escaped.push(other),
83 }
84 }
85 escaped
86}
87
88#[must_use]
90pub fn swagger_html(title: &str, spec_url: &str) -> String {
91 let title = escape_html(title);
92 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
117pub 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
142pub 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#[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 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("<script>alert(1)</script>"));
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&b<c>d"e'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}