#![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::openapi::{
redoc::{Redoc, Servable},
utoipa,
};
#[cfg(feature = "http-stack")]
use footing::http::{HttpMiddlewareConfig, HttpMiddlewareSettings, HttpMiddlewareStack};
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]
#[cfg(feature = "http-stack")]
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]
#[cfg(feature = "http-stack")]
async fn documentation_preset_preserves_access_control_and_separate_api_headers() {
for config in [
HttpMiddlewareConfig::documentation(),
HttpMiddlewareSettings::documentation().build().unwrap(),
] {
let docs = OpenApiDocs::new(
OpenApi::new(Info::new("test", "1"), Paths::new()),
"/docs",
DocsUi::RapiDoc(DocsAssets::local("/* RapiDoc */")),
)
.into_router::<()>()
.unwrap()
.route_layer(middleware::from_fn(authorize_docs));
let app = HttpMiddlewareStack::builder(HttpMiddlewareConfig::standard())
.build()
.unwrap()
.apply(Router::new().route("/api", get(|| async { "ok" })))
.merge(
HttpMiddlewareStack::builder(config)
.build()
.unwrap()
.apply(docs),
);
let api = fetch(app.clone(), "/api").await;
assert_eq!(api.headers()["cross-origin-opener-policy"], "same-origin");
assert!(!api.headers().contains_key("content-security-policy"));
for path in [
"/docs/",
"/docs/openapi.json",
"/docs/ui.js",
"/docs/oauth-receiver.html",
"/docs/oauth-receiver.js",
] {
assert_eq!(
fetch(app.clone(), path).await.status(),
StatusCode::UNAUTHORIZED,
"{path}"
);
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, "{path}");
assert!(
!response
.headers()
.contains_key("cross-origin-opener-policy"),
"{path}"
);
assert_eq!(response.headers()["x-content-type-options"], "nosniff");
let csp = response.headers()["content-security-policy"]
.to_str()
.unwrap();
let directives: Vec<_> = csp.split("; ").collect();
for directive in [
"default-src 'none'",
"script-src 'self'",
"connect-src 'self'",
"style-src 'self' 'unsafe-inline'",
"worker-src 'self' blob:",
"frame-ancestors 'none'",
] {
assert!(directives.contains(&directive), "{path}: {csp}");
}
}
}
}
#[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("<html lang=\"en\">"));
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_languages_and_documents_are_independent_between_routes() {
let mut chinese = OpenApi::new(Info::new("库存 API", "1"), Paths::new());
chinese.info.description = Some("查询和管理库存。".to_owned());
let mut english = OpenApi::new(Info::new("Inventory API", "1"), Paths::new());
english.info.description = Some("Query and manage inventory.".to_owned());
let app = OpenApiDocs::new(
chinese,
"/zh",
DocsUi::RapiDoc(DocsAssets::local("/* RapiDoc */")),
)
.with_lang("zh-CN")
.with_template(
r#"<!doctype html><html lang="{{lang}}"><head><title>{{title}}</title>{{head}}</head><body><main>{{body}}</main></body></html>"#,
)
.into_router()
.unwrap()
.merge(
OpenApiDocs::new(
english,
"/en",
DocsUi::Redoc(DocsAssets::local("/* ReDoc */")),
)
.with_lang("en")
.into_router()
.unwrap(),
);
for (path, lang, title, description) in [
("zh", "zh-CN", "库存 API", "查询和管理库存。"),
("en", "en", "Inventory API", "Query and manage inventory."),
] {
let html =
String::from_utf8(bytes(fetch(app.clone(), &format!("/{path}/")).await).await).unwrap();
assert!(html.contains(&format!("<html lang=\"{lang}\">")));
assert!(html.contains(&format!("<title>{title}</title>")));
assert!(html.contains("<p role=\"status\" lang=\"en\">"));
let document: Value = serde_json::from_slice(
&bytes(fetch(app.clone(), &format!("/{path}/openapi.json")).await).await,
)
.unwrap();
assert_eq!(document["info"]["title"], title);
assert_eq!(document["info"]["description"], description);
}
let callback =
String::from_utf8(bytes(fetch(app, "/zh/oauth-receiver.html").await).await).unwrap();
assert!(callback.contains("<html lang=\"en\">"));
}
#[tokio::test]
async fn page_language_is_escaped_without_reinterpreting_template_slots() {
let lang =
r#"zh-CN"'><script>window.compromised=true</script>& {{lang}} {{title}} {{head}} {{body}}"#;
let app = component("/docs")
.with_lang(lang)
.with_title("{{lang}}")
.with_template(
r#"<!doctype html><html lang="{{lang}}"><head><title>{{title}}</title>{{head}}</head><body><main>{{body}}</main></body></html>"#,
)
.into_router()
.unwrap();
let html = String::from_utf8(bytes(fetch(app, "/docs/").await).await).unwrap();
assert!(html.contains(
r#"<html lang="zh-CN"'><script>window.compromised=true</script>& {{lang}} {{title}} {{head}} {{body}}">"#,
));
assert!(html.contains("<title>{{lang}}</title>"));
assert!(!html.contains("<script>window.compromised"));
assert_eq!(html.matches("id=\"docs-container\"").count(), 1);
}
#[tokio::test]
async fn page_language_preserves_empty_and_caller_supplied_values() {
for lang in ["", "ZH-cn", " zh-CN "] {
let app = component("/docs").with_lang(lang).into_router().unwrap();
let html = String::from_utf8(bytes(fetch(app, "/docs/").await).await).unwrap();
assert!(html.contains(&format!("<html lang=\"{lang}\">")));
}
}
#[tokio::test]
async fn conditional_documentation_requests_preserve_authentication_and_resource_headers() {
let app = Router::new().nest(
"/api",
component("/docs")
.into_router()
.unwrap()
.route_layer(middleware::from_fn(authorize_docs)),
);
for resource in [
"",
"openapi.json",
"options.json",
"init.js",
"page.css",
"ui.js",
] {
let path = format!("/api/docs/{resource}");
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);
let etag = response.headers()["etag"].clone();
let content_type = response.headers()["content-type"].clone();
assert!(etag.to_str().unwrap().starts_with("W/\""));
assert!(!bytes(response).await.is_empty());
for method in ["GET", "HEAD"] {
for authenticated in [false, true] {
let mut request = Request::builder()
.method(method)
.uri(&path)
.header("if-none-match", &etag);
if authenticated {
request = request.header("authorization", "Bearer test-access");
}
let response = app
.clone()
.oneshot(request.body(Body::empty()).unwrap())
.await
.unwrap();
if !authenticated {
assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
continue;
}
assert_eq!(response.status(), StatusCode::NOT_MODIFIED, "{path}");
assert_eq!(response.headers()["etag"], etag);
assert_eq!(response.headers()["cache-control"], "private, no-cache");
assert_eq!(response.headers()["content-type"], content_type);
assert!(
!response.headers().contains_key("content-length"),
"{path}: {method}"
);
assert!(bytes(response).await.is_empty());
}
}
}
}
#[tokio::test]
async fn documentation_strong_preconditions_precede_cache_revalidation() {
let app = component("/docs").into_router().unwrap();
for path in ["/docs/", "/docs/openapi.json", "/docs/ui.js"] {
let original = fetch(app.clone(), path).await;
let etag = original.headers()["etag"].to_str().unwrap().to_owned();
for method in ["GET", "HEAD"] {
for condition in [&etag, etag.strip_prefix("W/").unwrap(), "\"other\""] {
let response = app
.clone()
.oneshot(
Request::builder()
.method(method)
.uri(path)
.header("if-match", condition)
.header("if-none-match", &etag)
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(response.status(), StatusCode::PRECONDITION_FAILED);
assert_eq!(response.headers()["cache-control"], "no-store");
assert!(bytes(response).await.is_empty());
}
for revalidate in [false, true] {
let mut request = Request::builder()
.method(method)
.uri(path)
.header("if-match", " * ");
if revalidate {
request = request.header("if-none-match", &etag);
}
let response = app
.clone()
.oneshot(request.body(Body::empty()).unwrap())
.await
.unwrap();
assert_eq!(
response.status(),
if revalidate {
StatusCode::NOT_MODIFIED
} else {
StatusCode::OK
}
);
}
}
}
}
#[tokio::test]
async fn documentation_etags_follow_content_and_parse_conditional_header_lists() {
let app = component("/docs").into_router().unwrap();
let response = fetch(app.clone(), "/docs/openapi.json").await;
let etag = response.headers()["etag"].to_str().unwrap().to_owned();
let strong = etag.strip_prefix("W/").unwrap();
let body = bytes(response).await;
let cases = [
(etag.clone(), true),
(strong.to_owned(), true),
(format!("\"other\", {etag}"), true),
(format!(" , W/\"other,tag\", , {strong}, "), true),
("*".into(), true),
("\"other,*,tag\"".into(), false),
("\"other\"".into(), false),
(format!("{strong}junk"), false),
(format!("{strong}, unquoted"), false),
(format!("w/{strong}"), false),
];
for (value, matched) in cases {
let response = app
.clone()
.oneshot(
Request::get("/docs/openapi.json")
.header("if-none-match", value)
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(
response.status(),
if matched {
StatusCode::NOT_MODIFIED
} else {
StatusCode::OK
}
);
assert_eq!(
bytes(response).await,
if matched { vec![] } else { body.clone() }
);
}
let response = app
.clone()
.oneshot(
Request::get("/docs/openapi.json")
.header("if-none-match", "\"other\"")
.header("if-none-match", &etag)
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(response.status(), StatusCode::NOT_MODIFIED);
let original_page = fetch(app, "/docs/").await;
let changed = component("/docs")
.with_title("Changed page")
.into_router()
.unwrap();
let changed_page = fetch(changed.clone(), "/docs/").await;
assert_ne!(
original_page.headers()["etag"],
changed_page.headers()["etag"]
);
assert_eq!(
fetch(changed, "/docs/openapi.json").await.headers()["etag"],
etag
);
}
#[tokio::test]
#[cfg(feature = "http-stack")]
async fn weak_documentation_validators_work_with_outer_compression() {
let document = OpenApi::new(
Info::new("Repeated title ".repeat(500), "1".to_owned()),
Paths::new(),
);
let docs = OpenApiDocs::new(
document,
"/docs",
DocsUi::Redoc(DocsAssets::local("/* local */")),
)
.into_router()
.unwrap()
.route_layer(middleware::from_fn(authorize_docs));
let app = HttpMiddlewareStack::builder(HttpMiddlewareConfig::standard())
.build()
.unwrap()
.apply(docs);
let original = app
.clone()
.oneshot(
Request::get("/docs/openapi.json")
.header("authorization", "Bearer test-access")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
let etag = original.headers()["etag"].clone();
let response = app
.clone()
.oneshot(
Request::get("/docs/openapi.json")
.header("accept-encoding", "gzip")
.header("authorization", "Bearer test-access")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(response.headers()["content-encoding"], "gzip");
assert_eq!(response.headers()["etag"], etag);
for method in ["GET", "HEAD"] {
for authenticated in [false, true] {
let mut request = Request::builder()
.method(method)
.uri("/docs/openapi.json")
.header("accept-encoding", "gzip")
.header("if-none-match", &etag);
if authenticated {
request = request.header("authorization", "Bearer test-access");
}
let response = app
.clone()
.oneshot(request.body(Body::empty()).unwrap())
.await
.unwrap();
if !authenticated {
assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
continue;
}
assert_eq!(response.status(), StatusCode::NOT_MODIFIED);
assert_eq!(response.headers()["etag"], etag);
assert_eq!(response.headers()["vary"], "accept-encoding");
assert!(!response.headers().contains_key("content-length"));
assert!(!response.headers().contains_key("content-encoding"));
assert!(bytes(response).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 lang=\"{{lang}}\"><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_preserve_false_and_zero() {
let app = component("/docs").with_options(json!({
"sanitize": false,
"hideDownloadButtons": false,
"schemasExpansionLevel": 0,
"jsonSamplesExpandLevel": 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"
);
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 legacy_redoc_options_report_their_canonical_replacements() {
for (legacy, canonical) in [
("untrustedSpec", "sanitize"),
("hideDownloadButton", "hideDownloadButtons"),
("schemaExpansionLevel", "schemasExpansionLevel"),
("jsonSampleExpandLevel", "jsonSamplesExpandLevel"),
] {
for preset in [false, true] {
for with_canonical in [false, true] {
let mut options = json!({(legacy): false});
if with_canonical {
options[canonical] = json!(true);
}
let docs = component("/docs").with_options(options);
let docs = if preset { docs } else { docs.without_preset() };
let error = docs.into_router::<()>().unwrap_err();
assert!(matches!(error, DocsError::InvalidOptions(_)));
assert_eq!(
error.to_string(),
format!("invalid documentation options: use {canonical} instead of {legacy}")
);
}
}
}
}
#[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(_))
));
}
let valid_template = "{{lang}}{{title}}{{head}}{{body}}";
for slot in ["{{lang}}", "{{title}}", "{{head}}", "{{body}}"] {
for template in [
valid_template.replace(slot, ""),
format!("{valid_template}{slot}"),
] {
assert!(
matches!(
component("/docs")
.with_template(template)
.into_router::<()>(),
Err(DocsError::InvalidTemplate(invalid)) if invalid == slot
),
"{slot}"
);
}
}
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", "microlighter", "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 let Some(etag) = response.headers().get("etag") {
let conditional = app
.clone()
.oneshot(
Request::builder()
.method(method)
.uri(path)
.header("authorization", "Bearer test-access")
.header("if-none-match", etag)
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(conditional.status(), StatusCode::NOT_MODIFIED);
assert_eq!(conditional.headers()["cache-control"], "no-store");
assert!(bytes(conditional).await.is_empty());
}
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 response = fetch(
rapidoc().into_router().unwrap(),
"/interactive/options.json",
)
.await;
let defaults: Value = serde_json::from_slice(&bytes(response).await).unwrap();
assert_eq!(defaults["persist-auth"], false);
assert_eq!(defaults["oauth-receiver"], "oauth-receiver.html");
assert_eq!(defaults["theme"], "cobalt");
assert!(defaults.get("primary-color").is_none());
let hostile = "\"</script><script>alert(1)</script> {{body}} & 中文";
let overrides = json!({
"theme": "jade",
"color-scheme": "light",
"primary-color": "#8b2252",
"schema-expand-level": 3,
"persist-auth": true,
"allow-try": false,
"heading-text": hostile,
"filter-operations": "GET /items/** !badge:internal",
});
let app = rapidoc()
.with_title(hostile)
.with_options(overrides.clone())
.with_template("<!doctype html><html lang=\"{{lang}}\"><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 src=\"./ui.js\" type=\"module\"></script>"));
assert!(html.contains("<script src=\"./init.js\" type=\"module\"></script>"));
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!(options.get("load-fonts").is_none());
assert!(options.get("regular-font").is_none());
assert!(options.get("mono-font").is_none());
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!(options.get("disableSearch").is_none());
let html = String::from_utf8(bytes(fetch(app.clone(), "/reference/").await).await).unwrap();
assert!(html.contains("data-ui=\"redoc\""));
assert!(html.contains("<script src=\"./ui.js\" defer></script>"));
assert!(html.contains("<script src=\"./init.js\" defer></script>"));
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!({"color-scheme": "light"}))
.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!({"color-scheme": "light"}));
}
#[tokio::test]
async fn oauth_callback_resources_preserve_mounting_and_application_access_control() {
for (mount, prefix) in [("/docs", "/service"), ("/", "/service/docs/")] {
let docs = OpenApiDocs::new(
OpenApi::new(Info::new("API", "1"), Paths::new()),
mount,
DocsUi::RapiDoc(DocsAssets::local("/* RapiDoc */")),
)
.into_router()
.unwrap()
.route_layer(middleware::from_fn(authorize_docs));
let app = Router::new().nest(prefix, docs);
for (name, content_type) in [
("oauth-receiver.html", "text/html; charset=utf-8"),
("oauth-receiver.js", "text/javascript; charset=utf-8"),
] {
let path = format!("/service/docs/{name}?code=private-code&state=state");
assert_eq!(
fetch(app.clone(), &path).await.status(),
StatusCode::UNAUTHORIZED
);
for method in ["GET", "HEAD"] {
let response = app
.clone()
.oneshot(
Request::builder()
.method(method)
.uri(&path)
.header("authorization", "Bearer test-access")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(response.status(), StatusCode::OK);
assert_eq!(response.headers()["content-type"], content_type);
if name.ends_with(".html") {
assert_eq!(response.headers()["cache-control"], "no-store");
assert_eq!(response.headers()["referrer-policy"], "no-referrer");
}
let body = bytes(response).await;
if method == "HEAD" {
assert!(body.is_empty());
} else {
let body = String::from_utf8(body).unwrap();
assert!(!body.is_empty());
assert!(!body.contains("private-code"));
assert!(!body.contains("<script>"));
}
}
}
}
}
#[test]
fn rapidoc_rejects_invalid_executable_reserved_and_removed_attributes() {
for options in [
json!(null),
json!([]),
json!({"theme": {"colors": {}}}),
json!({"theme": null}),
json!({"theme": ["a", "b"]}),
json!({"onload": "alert(1)"}),
json!({"onclick": "alert(1)"}),
json!({"on-nav-tag-click": "show-description"}),
json!({"spec-url": "https://example.com/other.json"}),
json!({"match-paths": "/items"}),
json!({"match-type": "regex"}),
json!({"remove-endpoints-with-badge-label-as": "internal"}),
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}"
);
}
}