use axum::http::header::CONTENT_SECURITY_POLICY;
use axum::response::{Html, IntoResponse, Response};
pub const DOCS_HTML: &str = r#"<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Delonix Seiva — API reference</title>
</head>
<body>
<script id="api-reference" data-url="/openapi.json"></script>
<script src="https://cdn.jsdelivr.net/npm/@scalar/api-reference"></script>
</body>
</html>
"#;
pub const DOCS_CSP: &str = "default-src 'none'; \
script-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net; \
style-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net; \
img-src 'self' data: https://cdn.jsdelivr.net; \
font-src 'self' data: https://cdn.jsdelivr.net; \
connect-src 'self' https://cdn.jsdelivr.net; \
frame-ancestors 'none'";
pub async fn docs_handler() -> Response {
([(CONTENT_SECURITY_POLICY, DOCS_CSP)], Html(DOCS_HTML)).into_response()
}
#[cfg(test)]
mod tests {
use crate::{router, Health};
use axum::body::Body;
use axum::http::{Request, StatusCode};
use tower::ServiceExt;
#[tokio::test]
async fn docs_page_is_served_and_points_at_the_spec() {
let app = router(Health::starting());
let res = app
.oneshot(Request::builder().uri("/docs").body(Body::empty()).unwrap())
.await
.unwrap();
assert_eq!(res.status(), StatusCode::OK);
assert!(res.headers()["content-type"]
.to_str()
.unwrap()
.starts_with("text/html"));
let bytes = axum::body::to_bytes(res.into_body(), usize::MAX)
.await
.unwrap();
let body = String::from_utf8(bytes.to_vec()).unwrap();
assert!(body.contains("/openapi.json"));
assert!(body.contains("@scalar/api-reference"));
}
#[tokio::test]
async fn docs_csp_permits_scalar_instead_of_the_strict_default() {
let app = router(Health::starting());
let res = app
.oneshot(Request::builder().uri("/docs").body(Body::empty()).unwrap())
.await
.unwrap();
let csp = res.headers()["content-security-policy"].to_str().unwrap();
assert!(
csp.contains("https://cdn.jsdelivr.net"),
"the /docs CSP must allow Scalar's CDN, got: {csp}"
);
assert_ne!(
csp, "default-src 'none'; frame-ancestors 'none'",
"the /docs page must not inherit the API's blank-page CSP"
);
}
}