#![cfg(feature = "openapi")]
use axum::{
Json, Router,
body::{Body, to_bytes},
extract::State,
http::{Request, StatusCode},
middleware::{self, Next},
response::{IntoResponse, Response},
routing::get,
};
use footing::http::{
HttpMiddlewareConfig, HttpMiddlewareStack,
openapi::{
redoc::{Redoc, Servable},
utoipa,
},
};
use tower::ServiceExt;
use utoipa::openapi::{Info, OpenApi, path::Paths};
#[derive(Clone)]
struct AppState {
document: OpenApi,
}
fn docs() -> Router<AppState> {
Router::new()
.route(
"/openapi.json",
get(|State(state): State<AppState>| async move { Json(state.document) }),
)
.merge(Redoc::with_url("/docs", "/openapi.json"))
}
#[tokio::test]
async fn redoc_loads_json_without_interpolating_document_text_into_html() {
let description = "Example: </script><script>document.title = 'unexpected';</script>";
let mut document = OpenApi::new(Info::new("Inventory API", "1.0.0"), Paths::new());
document.info.description = Some(description.to_owned());
let app = HttpMiddlewareStack::builder(HttpMiddlewareConfig::standard())
.build()
.unwrap()
.apply(docs())
.with_state(AppState { document });
let response = app
.clone()
.oneshot(Request::get("/docs").body(Body::empty()).unwrap())
.await
.unwrap();
assert_eq!(response.status(), StatusCode::OK);
assert_eq!(
response.headers()["content-type"],
"text/html; charset=utf-8"
);
assert_eq!(response.headers()["x-content-type-options"], "nosniff");
let html = String::from_utf8(
to_bytes(response.into_body(), 64 * 1024)
.await
.unwrap()
.to_vec(),
)
.unwrap();
assert!(html.contains("Redoc.init("));
assert!(html.contains("\"/openapi.json\""));
assert!(!html.contains(description));
assert!(!html.contains("$spec"));
assert!(!html.contains("$config"));
let response = app
.oneshot(Request::get("/openapi.json").body(Body::empty()).unwrap())
.await
.unwrap();
assert_eq!(response.status(), StatusCode::OK);
assert_eq!(response.headers()["content-type"], "application/json");
let json: serde_json::Value =
serde_json::from_slice(&to_bytes(response.into_body(), 64 * 1024).await.unwrap()).unwrap();
assert_eq!(json["openapi"], "3.1.0");
assert_eq!(json["info"]["description"], description);
}
async fn authorize_docs(request: Request<Body>, next: Next) -> Response {
if request
.headers()
.get("authorization")
.is_some_and(|value| value == "Bearer test-access")
{
next.run(request).await
} else {
StatusCode::UNAUTHORIZED.into_response()
}
}
#[tokio::test]
async fn documentation_access_control_covers_the_page_and_specification() {
let document = OpenApi::new(Info::new("Private API", "1.0.0"), Paths::new());
let app = docs()
.route_layer(middleware::from_fn(authorize_docs))
.with_state(AppState { document });
for path in ["/docs", "/openapi.json"] {
let response = app
.clone()
.oneshot(Request::get(path).body(Body::empty()).unwrap())
.await
.unwrap();
assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
let response = app
.clone()
.oneshot(
Request::get(path)
.header("authorization", "Bearer test-access")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(response.status(), StatusCode::OK);
}
}
#[tokio::test]
async fn custom_template_and_options_are_available_through_the_reexport() {
let redoc = Redoc::with_url_and_config(
"/reference",
"/schema.json",
|| serde_json::json!({"disableSearch": true}),
)
.custom_html(
r#"<!doctype html>
<div id="redoc"></div>
<script src="/assets/redoc.js"></script>
<script>Redoc.init($spec, $config, document.getElementById('redoc'));</script>"#,
);
let app = Router::<()>::new().merge(redoc);
let response = app
.oneshot(Request::get("/reference").body(Body::empty()).unwrap())
.await
.unwrap();
assert_eq!(response.status(), StatusCode::OK);
let html = String::from_utf8(
to_bytes(response.into_body(), 64 * 1024)
.await
.unwrap()
.to_vec(),
)
.unwrap();
assert!(html.contains(r#"src="/assets/redoc.js""#));
assert!(html.contains(r#""disableSearch":true"#));
assert!(html.contains(r#""/schema.json""#));
assert!(!html.contains("cdn.redoc.ly"));
}
use footing::http::openapi::{DocsAssets, DocsError, DocsUi, OpenApiDocs};
use serde_json::{Value, json};
fn component(path: &str) -> OpenApiDocs {
OpenApiDocs::new(
OpenApi::new(Info::new("Inventory API", "1.0.0"), Paths::new()),
path,
DocsUi::Redoc(DocsAssets::local("window.Redoc = {};")),
)
}
async fn fetch(app: Router, path: &str) -> Response {
app.oneshot(Request::get(path).body(Body::empty()).unwrap())
.await
.unwrap()
}
async fn bytes(response: Response) -> Vec<u8> {
to_bytes(response.into_body(), 2 * 1024 * 1024)
.await
.unwrap()
.to_vec()
}
#[tokio::test]
async fn component_routes_work_under_nested_prefixes_and_preserve_redirect_queries() {
for ui in local_uis() {
let docs = OpenApiDocs::new(
OpenApi::new(Info::new("API", "1"), Paths::new()),
"/reference/",
ui,
)
.into_router::<AppState>()
.unwrap();
let app = Router::new().nest("/service", docs).with_state(AppState {
document: OpenApi::new(Info::new("State", "1"), Paths::new()),
});
let response = fetch(app.clone(), "/service/reference?lang=zh").await;
assert_eq!(response.status(), StatusCode::PERMANENT_REDIRECT);
assert_eq!(response.headers()["location"], "reference/?lang=zh");
for (path, content_type) in [
("", "text/html; charset=utf-8"),
("openapi.json", "application/json"),
("options.json", "application/json"),
("init.js", "text/javascript; charset=utf-8"),
("page.css", "text/css; charset=utf-8"),
("ui.js", "text/javascript; charset=utf-8"),
] {
let response = fetch(app.clone(), &format!("/service/reference/{path}")).await;
assert_eq!(response.status(), StatusCode::OK, "{path}");
assert_eq!(response.headers()["content-type"], content_type);
assert_eq!(response.headers()["cache-control"], "private, no-cache");
assert_eq!(response.headers()["x-content-type-options"], "nosniff");
}
let html = String::from_utf8(bytes(fetch(app.clone(), "/service/reference/").await).await)
.unwrap();
assert!(html.contains("src=\"./ui.js\""));
assert!(html.contains("src=\"./init.js\""));
assert!(!html.contains("<script>"));
assert!(!html.contains("<style>"));
let head = app
.oneshot(
Request::head("/service/reference/openapi.json")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(head.status(), StatusCode::OK);
assert!(bytes(head).await.is_empty());
}
}
#[tokio::test]
async fn page_options_and_document_data_do_not_become_html_or_template_slots() {
let hostile = "</script><script>window.compromised=true</script> \" & {{body}} {{head}} $spec \u{2028} 䏿–‡";
let mut document = OpenApi::new(Info::new("API", "1"), Paths::new());
document.info.description = Some(hostile.to_owned());
let app = OpenApiDocs::new(document, "/", DocsUi::Redoc(DocsAssets::local("/* local */")))
.with_title(hostile)
.with_options(json!({"custom": hostile, "theme": {"typography": {"fontSize": "16px"}}}))
.with_template("<!doctype html><html><head><title>{{title}}</title>{{head}}</head><body><main>{{body}}</main></body></html>")
.into_router().unwrap();
let html = String::from_utf8(bytes(fetch(app.clone(), "/").await).await).unwrap();
assert!(!html.contains("<script>window.compromised"));
assert!(html.contains("</script>"));
assert!(html.contains("{{body}} {{head}} $spec"));
assert_eq!(html.matches("id=\"docs-container\"").count(), 1);
let options: Value =
serde_json::from_slice(&bytes(fetch(app.clone(), "/options.json").await).await).unwrap();
assert_eq!(options["custom"], hostile);
assert_eq!(options["theme"]["typography"]["fontSize"], "16px");
assert_eq!(
options["theme"]["typography"]["headings"]["fontFamily"],
"system-ui, sans-serif"
);
let document: Value =
serde_json::from_slice(&bytes(fetch(app, "/openapi.json").await).await).unwrap();
assert_eq!(document["info"]["description"], hostile);
}
#[tokio::test]
async fn native_options_override_presets_and_legacy_aliases_preserve_false_and_zero() {
let app = component("/docs").with_options(json!({
"untrustedSpec": false,
"hideDownloadButton": true,
"hideDownloadButtons": false,
"schemaExpansionLevel": 0,
"jsonSampleExpandLevel": 0,
"showExtensions": ["x-team"],
"theme": {"typography": {"headings": {"fontWeight": 700}}, "sidebar": {"width": "300px"}},
"custom": null,
})).into_router().unwrap();
let options: Value =
serde_json::from_slice(&bytes(fetch(app, "/docs/options.json").await).await).unwrap();
assert_eq!(options["sanitize"], false);
assert_eq!(options["hideDownloadButtons"], false);
assert_eq!(options["schemasExpansionLevel"], 0);
assert_eq!(options["jsonSamplesExpandLevel"], "0");
assert_eq!(options["showExtensions"], json!(["x-team"]));
assert!(options.get("custom").unwrap().is_null());
assert_eq!(
options["theme"]["typography"]["headings"]["fontWeight"],
700
);
assert_eq!(
options["theme"]["typography"]["headings"]["fontFamily"],
"system-ui, sans-serif"
);
assert!(options.get("schemaExpansionLevel").is_none());
let app = component("/docs")
.with_options(json!({"disableSearch": true}))
.without_preset()
.into_router()
.unwrap();
let options: Value =
serde_json::from_slice(&bytes(fetch(app, "/docs/options.json").await).await).unwrap();
assert_eq!(options, json!({"disableSearch": true}));
}
#[test]
fn invalid_component_configuration_fails_before_serving() {
for path in [
"",
"docs",
"//",
"/a//b",
"/a/../b",
"/./docs",
"/docs?query",
"/docs#fragment",
"/{id}",
"/{*path}",
"/%2e",
"/a\\b",
"/docs\n",
"/:legacy",
] {
assert!(
matches!(
component(path).into_router::<()>(),
Err(DocsError::InvalidPath(_))
),
"{path}"
);
}
for options in [
json!(null),
json!([]),
json!(false),
json!({"theme": null}),
json!({"theme": []}),
] {
assert!(matches!(
component("/docs").with_options(options).into_router::<()>(),
Err(DocsError::InvalidOptions(_))
));
}
for template in ["{{title}}{{head}}", "{{title}}{{head}}{{body}}{{body}}"] {
assert!(matches!(
component("/docs")
.with_template(template)
.into_router::<()>(),
Err(DocsError::InvalidTemplate(_))
));
}
for url in [
"",
"javascript:alert(1)",
"data:text/javascript,alert(1)",
"//cdn.example.com/redoc.js",
"https://example.com/\nredoc.js",
"https://example.com\\redoc.js",
] {
let document = OpenApi::new(Info::new("API", "1"), Paths::new());
assert!(
matches!(
OpenApiDocs::new(document, "/docs", DocsUi::Redoc(DocsAssets::url(url)))
.into_router::<()>(),
Err(DocsError::InvalidAssetUrl(_))
),
"{url}"
);
}
}
#[tokio::test]
async fn url_assets_remain_explicit_and_local_instances_do_not_share_documents() {
let document = OpenApi::new(Info::new("External assets", "1"), Paths::new());
let a = OpenApiDocs::new(
document,
"/a",
DocsUi::Redoc(DocsAssets::url("/static/redoc.js?x=1&y=2")),
)
.into_router()
.unwrap();
let b = component("/b")
.with_title("Other page")
.into_router()
.unwrap();
let app = a.merge(b);
let html = String::from_utf8(bytes(fetch(app.clone(), "/a/").await).await).unwrap();
assert!(html.contains("src=\"/static/redoc.js?x=1&y=2\""));
assert_eq!(
fetch(app.clone(), "/a/ui.js").await.status(),
StatusCode::NOT_FOUND
);
let a: Value =
serde_json::from_slice(&bytes(fetch(app.clone(), "/a/openapi.json").await).await).unwrap();
let b: Value =
serde_json::from_slice(&bytes(fetch(app, "/b/openapi.json").await).await).unwrap();
assert_eq!(a["info"]["title"], "External assets");
assert_eq!(b["info"]["title"], "Inventory API");
}
#[cfg(any(feature = "redoc-embedded", feature = "rapidoc-embedded"))]
#[tokio::test]
async fn embedded_routes_and_notices_share_authentication_and_allow_cache_overrides() {
let cases = [
#[cfg(feature = "redoc-embedded")]
(
DocsUi::embedded_redoc(),
&["Redoc", "React", "styled-components", "lunr", "DOMPurify"][..],
),
#[cfg(feature = "rapidoc-embedded")]
(
DocsUi::embedded_rapidoc(),
&["RapiDoc", "lit", "marked", "Prism", "openapi-parser"][..],
),
];
for (ui, dependencies) in cases {
let document = OpenApi::new(Info::new("Private", "1"), Paths::new());
let app = OpenApiDocs::new(document, "/docs", ui)
.into_router()
.unwrap()
.route_layer(middleware::from_fn(authorize_docs))
.layer(middleware::map_response(
|mut response: Response| async move {
response
.headers_mut()
.insert("cache-control", "no-store".parse().unwrap());
response
},
));
for path in [
"/docs",
"/docs/",
"/docs/openapi.json",
"/docs/options.json",
"/docs/init.js",
"/docs/page.css",
"/docs/ui.js",
"/docs/ui.LICENSE.txt",
] {
for method in ["GET", "HEAD"] {
let response = app
.clone()
.oneshot(
Request::builder()
.method(method)
.uri(path)
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(response.status(), StatusCode::UNAUTHORIZED, "{path}");
let response = app
.clone()
.oneshot(
Request::builder()
.method(method)
.uri(path)
.header("authorization", "Bearer test-access")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert!(
response.status().is_success() || response.status().is_redirection(),
"{path}"
);
assert_eq!(response.headers()["cache-control"], "no-store");
if path.ends_with("ui.LICENSE.txt") && method == "GET" {
let notices = String::from_utf8(bytes(response).await).unwrap();
for dependency in dependencies {
assert!(notices.to_lowercase().contains(&dependency.to_lowercase()));
}
}
}
}
}
}
fn local_uis() -> [DocsUi; 2] {
[
DocsUi::Redoc(DocsAssets::local("/* ReDoc */")),
DocsUi::RapiDoc(DocsAssets::local("/* RapiDoc */")),
]
}
fn rapidoc() -> OpenApiDocs {
OpenApiDocs::new(
OpenApi::new(Info::new("Interactive API", "1"), Paths::new()),
"/interactive",
DocsUi::RapiDoc(DocsAssets::local("/* RapiDoc */")),
)
}
#[tokio::test]
async fn renderer_selection_keeps_native_options_and_documents_independent() {
let hostile = "\"</script><script>alert(1)</script> {{body}} & 䏿–‡";
let overrides = json!({
"theme": "dark",
"primary-color": "#8b2252",
"regular-font": "monospace",
"schema-expand-level": 3,
"persist-auth": false,
"allow-try": false,
"on-nav-tag-click": "show-description",
"heading-text": hostile,
});
let app = rapidoc()
.with_title(hostile)
.with_options(overrides.clone())
.with_template("<!doctype html><html><head><title>{{title}}</title>{{head}}</head><body><main>{{body}}</main></body></html>")
.into_router().unwrap()
.merge(component("/reference").into_router().unwrap());
let html = String::from_utf8(bytes(fetch(app.clone(), "/interactive/").await).await).unwrap();
assert!(html.contains("data-ui=\"rapidoc\""));
assert!(html.contains("src=\"./ui.js\""));
assert!(html.contains("</script>"));
assert!(!html.contains("<script>alert(1)"));
assert!(!html.contains("<rapi-doc")); let options: Value =
serde_json::from_slice(&bytes(fetch(app.clone(), "/interactive/options.json").await).await)
.unwrap();
for (key, value) in overrides.as_object().unwrap() {
assert_eq!(&options[key], value, "{key}");
}
assert_eq!(options["load-fonts"], false);
assert_eq!(options["allow-search"], true);
assert_eq!(options["allow-spec-file-download"], true);
assert!(options.get("allow-spec-url-load").is_none());
assert_eq!(options["render-style"], "focused");
assert_eq!(options["mono-font"], "ui-monospace, monospace");
assert!(options.get("disableSearch").is_none());
let html = String::from_utf8(bytes(fetch(app.clone(), "/reference/").await).await).unwrap();
assert!(html.contains("data-ui=\"redoc\""));
let options: Value =
serde_json::from_slice(&bytes(fetch(app.clone(), "/reference/options.json").await).await)
.unwrap();
assert_eq!(options["disableSearch"], false);
assert!(options.get("load-fonts").is_none());
for (path, title) in [
("interactive", "Interactive API"),
("reference", "Inventory API"),
] {
let doc: Value = serde_json::from_slice(
&bytes(fetch(app.clone(), &format!("/{path}/openapi.json")).await).await,
)
.unwrap();
assert_eq!(doc["info"]["title"], title);
}
let app = rapidoc()
.with_options(json!({"theme": "dark"}))
.without_preset()
.into_router()
.unwrap();
let options: Value =
serde_json::from_slice(&bytes(fetch(app, "/interactive/options.json").await).await)
.unwrap();
assert_eq!(options, json!({"theme": "dark"}));
}
#[test]
fn rapidoc_rejects_invalid_or_executable_attributes_and_reserved_spec_url() {
for options in [
json!(null),
json!([]),
json!({"theme": {"colors": {}}}),
json!({"theme": null}),
json!({"regular-font": ["a", "b"]}),
json!({"onload": "alert(1)"}),
json!({"onclick": "alert(1)"}),
json!({"spec-url": "https://example.com/other.json"}),
json!({"loadFonts": false}),
json!({"a\" onclick=\"": "test"}),
json!({"": "value"}),
json!({"style": "display:none"}),
] {
assert!(
matches!(
rapidoc().with_options(options.clone()).into_router::<()>(),
Err(DocsError::InvalidOptions(_))
),
"{options}"
);
}
}