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;
pub const SPEC_PATH: &str = "/api-docs/openapi.json";
pub const UI_PATH: &str = "/swagger-ui";
pub const SWAGGER_UI_VERSION: &str = "5.34.1";
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'";
const CSS_INTEGRITY: &str =
"sha384-4c3vsE5f+trhFyHrFrLM1fFGUn531NIaC7dcqEWIJdoRQJ5CkJbSuSCwXLpaS1KF";
const JS_INTEGRITY: &str =
"sha384-XFYN47VzPiDY6qPtxYKg0nqUeW/upo20xf1j2SUE7gT/i35FJB4cuS/71Iegzk8Z";
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("<"),
'>' => escaped.push_str(">"),
'"' => escaped.push_str("""),
'\'' => escaped.push_str("'"),
other => escaped.push(other),
}
}
escaped
}
#[must_use]
pub fn swagger_html(title: &str, spec_url: &str) -> String {
let title = escape_html(title);
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>
"#
)
}
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()
}
}),
)
}
pub fn with_bearer_auth(spec: &mut Value) {
let scheme = json!({ "type": "http", "scheme": "bearer", "bearerFormat": "PASETO" });
spec["components"]["securitySchemes"]["bearer"] = scheme;
spec["security"] = json!([{ "bearer": [] }]);
}
#[must_use]
pub fn spec_of<T: OpenApi>() -> Value {
serde_json::to_value(T::openapi()).expect("an OpenAPI document encodes as JSON")
}
#[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/"));
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("<script>alert(1)</script>"));
}
#[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&b<c>d"e'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");
}
}