mod assets;
mod options;
mod page;
use axum::{
Router,
body::{Body, Bytes},
http::{HeaderMap, HeaderValue, StatusCode, Uri, header},
response::{IntoResponse, Redirect},
routing::{MethodRouter, get},
};
use serde_json::Value;
use sha2::{Digest, Sha256};
use thiserror::Error;
use utoipa::openapi::OpenApi;
use crate::result::{ClassifyError, ErrorCode, ErrorKind};
#[cfg(feature = "rapidoc-embedded")]
pub use assets::EMBEDDED_RAPIDOC_VERSION;
#[cfg(feature = "redoc-embedded")]
pub use assets::EMBEDDED_REDOC_VERSION;
pub use assets::{DocsAssets, DocsUi};
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum DocsError {
#[error("invalid documentation mount path: {0}")]
InvalidPath(String),
#[error("invalid documentation script URL: {0}")]
InvalidAssetUrl(String),
#[error("invalid documentation options: {0}")]
InvalidOptions(&'static str),
#[error("documentation template must contain exactly one {0} slot")]
InvalidTemplate(&'static str),
#[error("cannot serialize the OpenAPI document: {0}")]
Serialize(#[from] serde_json::Error),
}
impl ClassifyError for DocsError {
fn error_kind(&self) -> ErrorKind {
ErrorKind::Validation
}
fn error_code(&self) -> ErrorCode {
ErrorCode::internal(match self {
Self::InvalidPath(_) => "docs_invalid_path",
Self::InvalidAssetUrl(_) => "docs_invalid_asset_url",
Self::InvalidOptions(_) => "docs_invalid_options",
Self::InvalidTemplate(_) => "docs_invalid_template",
Self::Serialize(_) => "docs_serialization_failed",
})
}
}
#[must_use]
pub struct OpenApiDocs {
document: OpenApi,
path: String,
ui: DocsUi,
title: String,
lang: String,
options: Value,
preset: bool,
template: String,
}
impl std::fmt::Debug for OpenApiDocs {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("OpenApiDocs")
.field("path", &self.path)
.field("ui", &self.ui)
.field("title", &self.title)
.field("lang", &self.lang)
.field("preset", &self.preset)
.finish_non_exhaustive()
}
}
impl OpenApiDocs {
pub fn new(document: OpenApi, path: impl Into<String>, ui: DocsUi) -> Self {
Self {
title: document.info.title.clone(),
document,
path: path.into(),
ui,
lang: "en".to_owned(),
options: serde_json::json!({}),
preset: true,
template: include_str!("template.html").to_owned(),
}
}
pub fn with_title(mut self, title: impl Into<String>) -> Self {
self.title = title.into();
self
}
pub fn with_lang(mut self, lang: impl Into<String>) -> Self {
self.lang = lang.into();
self
}
pub fn with_options(mut self, options: Value) -> Self {
self.options = options;
self
}
pub fn without_preset(mut self) -> Self {
self.preset = false;
self
}
pub fn with_template(mut self, template: impl Into<String>) -> Self {
self.template = template.into();
self
}
pub fn into_router<S: Clone + Send + Sync + 'static>(self) -> Result<Router<S>, DocsError> {
let mount = mount_path(&self.path)?;
let options = options::resolve(self.options, self.preset, &self.ui)?;
let script_url = self.ui.assets().script_url()?;
let html = page::render(
&self.template,
&self.title,
&self.lang,
script_url,
&self.ui,
)?;
let mut router = Router::new()
.route(
&format!("{mount}/"),
resource("text/html; charset=utf-8", html),
)
.route(
&format!("{mount}/openapi.json"),
resource("application/json", serde_json::to_vec(&self.document)?),
)
.route(
&format!("{mount}/options.json"),
resource("application/json", serde_json::to_vec(&options)?),
)
.route(
&format!("{mount}/init.js"),
resource(
"text/javascript; charset=utf-8",
include_bytes!("init.js").as_slice(),
),
)
.route(
&format!("{mount}/page.css"),
resource(
"text/css; charset=utf-8",
include_bytes!("page.css").as_slice(),
),
);
if matches!(&self.ui, DocsUi::RapiDoc(_)) {
router = router
.route(
&format!("{mount}/oauth-receiver.html"),
resource(
"text/html; charset=utf-8",
include_bytes!("oauth-receiver.html").as_slice(),
)
.layer(axum::middleware::map_response(
|mut response: axum::response::Response| async move {
response.headers_mut().insert(
header::CACHE_CONTROL,
HeaderValue::from_static("no-store"),
);
response.headers_mut().insert(
header::REFERRER_POLICY,
HeaderValue::from_static("no-referrer"),
);
response
},
)),
)
.route(
&format!("{mount}/oauth-receiver.js"),
resource(
"text/javascript; charset=utf-8",
include_bytes!("oauth-receiver.js").as_slice(),
),
);
}
if !mount.is_empty() {
let leaf = mount.rsplit('/').next().unwrap_or_default().to_owned();
router = router.route(
mount,
get(move |uri: Uri| {
let mut location = format!("{leaf}/");
if let Some(query) = uri.query() {
location.push('?');
location.push_str(query);
}
async move {
(
[(header::CACHE_CONTROL, "private, no-cache")],
Redirect::permanent(&location),
)
}
}),
);
}
Ok(self.ui.into_assets().mount(router, mount))
}
}
fn mount_path(path: &str) -> Result<&str, DocsError> {
let mount = path.strip_suffix('/').unwrap_or(path);
if !path.starts_with('/')
|| !path
.bytes()
.all(|b| b.is_ascii_alphanumeric() || b"/-._~".contains(&b))
|| (!mount.is_empty()
&& mount[1..]
.split('/')
.any(|s| s.is_empty() || s == "." || s == ".."))
{
return Err(DocsError::InvalidPath(path.to_owned()));
}
Ok(mount)
}
fn resource<S: Clone + Send + Sync + 'static>(
content_type: &'static str,
bytes: impl Into<Bytes>,
) -> MethodRouter<S> {
let bytes = bytes.into();
let digest = Sha256::digest(&bytes);
let hex = crate::http::to_lower_hex(&digest);
let etag = format!("W/\"{hex}\"");
get(move |headers: HeaderMap| {
let mut if_match = headers.get_all(header::IF_MATCH).iter();
let precondition_failed = if_match.next().is_some_and(|value| {
value.as_bytes().trim_ascii() != b"*" || if_match.next().is_some()
});
let not_modified = headers
.get_all(header::IF_NONE_MATCH)
.iter()
.any(|value| matches_etag(value.as_bytes(), hex.as_bytes()));
let bytes = bytes.clone();
let etag = etag.clone();
async move {
let (status, body) = if precondition_failed {
(StatusCode::PRECONDITION_FAILED, Body::empty())
} else if not_modified {
(
StatusCode::NOT_MODIFIED,
Body::from_stream(Body::empty().into_data_stream()),
)
} else {
(StatusCode::OK, Body::from(bytes))
};
(
status,
[
(header::CONTENT_TYPE, content_type),
(
header::CACHE_CONTROL,
if precondition_failed {
"no-store"
} else {
"private, no-cache"
},
),
(header::X_CONTENT_TYPE_OPTIONS, "nosniff"),
(header::VARY, "accept-encoding"),
],
[(header::ETAG, etag)],
body,
)
.into_response()
}
})
}
fn matches_etag(mut value: &[u8], expected: &[u8]) -> bool {
if value.trim_ascii() == b"*" {
return true;
}
let mut matched = false;
loop {
value = value.trim_ascii_start();
if value.is_empty() {
return matched;
}
if let Some(rest) = value.strip_prefix(b",") {
value = rest;
continue;
}
let Some(tag) = value
.strip_prefix(b"W/")
.unwrap_or(value)
.strip_prefix(b"\"")
else {
return false;
};
let Some(end) = tag.iter().position(|byte| *byte == b'"') else {
return false;
};
let opaque = &tag[..end];
if !opaque
.iter()
.all(|byte| *byte == 0x21 || *byte >= 0x23 && *byte != 0x7f)
{
return false;
}
matched |= opaque == expected;
value = tag[end + 1..].trim_ascii_start();
if !value.is_empty() && !value.starts_with(b",") {
return false;
}
}
}