Files
skyg-linux-tracker/src/docs.rs
T

202 lines
7.9 KiB
Rust

//! The Redoc viewer for the generated OpenAPI document.
//!
//! Two static, public routes: `/docs` (a small HTML page) and
//! `/docs/redoc.standalone.js` (the vendored Redoc bundle, embedded in the
//! binary so nothing is fetched from a CDN). Neither carries any data about
//! the host. The page loads `GET /api/v1/openapi.json` itself and sends the
//! bearer token there, so the spec stays behind the normal auth.
//!
//! The bundle is Redoc 2.5.4 (MIT, `src/docs/REDOC-LICENSE` and
//! `redoc.standalone.js.LICENSE.txt`). Redoc 3 is an ES module with a
//! telemetry option; 2.x is a plain script with no outbound calls.
//!
//! It is stored gzipped (about 320 KiB instead of 1.1 MiB, under the repo's
//! 512 KiB file limit) and sent as is with `Content-Encoding: gzip`, so the
//! server never compresses at request time. The uncompressed file has sha256
//! `dcaf76612bc4a3fbcc923a8966dee2f6146a5f32e5ce1b6f02dd60cbbf89500b`. To
//! refresh it, fetch the new version and recompress deterministically:
//!
//! ```sh
//! curl -sSL https://cdn.jsdelivr.net/npm/redoc@VERSION/bundles/redoc.standalone.js \
//! | gzip -9 -n > src/docs/redoc.standalone.js.gz
//! ```
//!
//! Update the two license files and the version named here and in the
//! `redoc_js` description, then regenerate `docs/openapi.json`.
use std::sync::OnceLock;
use axum::body::Body;
use axum::http::{header, HeaderValue, StatusCode};
use axum::response::{IntoResponse, Response};
use base64::engine::general_purpose::STANDARD;
use base64::Engine;
use bytes::Bytes;
use sha2::{Digest, Sha256};
const TEMPLATE: &str = include_str!("docs/index.html");
const INIT_JS: &str = include_str!("docs/init.js");
const REDOC_JS_GZ: &[u8] = include_bytes!("docs/redoc.standalone.js.gz");
const INIT_MARKER: &str = "<!--INIT-->";
/// The page and the CSP that admits exactly its one inline script.
struct Page {
html: String,
csp: String,
}
fn built() -> &'static Page {
static PAGE: OnceLock<Page> = OnceLock::new();
PAGE.get_or_init(|| {
let hash = STANDARD.encode(Sha256::digest(INIT_JS.as_bytes()));
Page {
html: TEMPLATE.replace(INIT_MARKER, &format!("<script>{INIT_JS}</script>")),
// Redoc injects inline styles (styled-components) and runs its
// search index in a blob worker. `form-action 'none'` keeps the
// token field from ever submitting if the script did not load.
csp: format!(
"default-src 'none'; script-src 'self' 'sha256-{hash}'; \
style-src 'unsafe-inline'; img-src 'self' data: blob:; \
font-src 'self' data:; connect-src 'self'; worker-src blob:; \
child-src blob:; base-uri 'none'; form-action 'none'; \
frame-ancestors 'none'"
),
}
})
}
/// The API reference page.
#[utoipa::path(
get,
path = "/docs",
operation_id = "docs",
tag = "meta",
summary = "API reference (Redoc)",
description = "Public and unauthenticated: a static page that renders this document with the \
Redoc bundle embedded in the binary. The page itself holds no data about the \
host; it fetches `GET /api/v1/openapi.json` with the bearer token you enter \
(kept in `sessionStorage`, sent to this server only).",
security(()),
responses(
(status = 200, body = String, content_type = "text/html", description = "The viewer page")
)
)]
pub async fn page() -> Response {
let page = built();
let mut response = Response::new(Body::from(page.html.clone()));
let headers = response.headers_mut();
headers.insert(
header::CONTENT_TYPE,
HeaderValue::from_static("text/html; charset=utf-8"),
);
headers.insert(header::CACHE_CONTROL, HeaderValue::from_static("no-cache"));
headers.insert(
header::X_CONTENT_TYPE_OPTIONS,
HeaderValue::from_static("nosniff"),
);
headers.insert(
header::REFERRER_POLICY,
HeaderValue::from_static("no-referrer"),
);
headers.insert(header::X_FRAME_OPTIONS, HeaderValue::from_static("DENY"));
match HeaderValue::from_str(&page.csp) {
Ok(csp) => {
headers.insert(header::CONTENT_SECURITY_POLICY, csp);
}
// The policy is ASCII built from constants, so this cannot happen;
// serving the page without it would be worse than failing.
Err(_) => return StatusCode::INTERNAL_SERVER_ERROR.into_response(),
}
response
}
/// The embedded Redoc bundle.
#[utoipa::path(
get,
path = "/docs/redoc.standalone.js",
operation_id = "docs_redoc_js",
tag = "meta",
summary = "Embedded Redoc bundle",
description = "Public and unauthenticated: the vendored Redoc 2.5.4 standalone script that \
`/docs` loads. Served from the binary, never from a CDN, already gzipped \
(`Content-Encoding: gzip`).",
security(()),
responses(
(status = 200, body = String, content_type = "text/javascript", description = "The Redoc script")
)
)]
pub async fn redoc_js() -> Response {
let mut response = Response::new(Body::from(Bytes::from_static(REDOC_JS_GZ)));
let headers = response.headers_mut();
headers.insert(
header::CONTENT_TYPE,
HeaderValue::from_static("text/javascript; charset=utf-8"),
);
headers.insert(header::CONTENT_ENCODING, HeaderValue::from_static("gzip"));
headers.insert(
header::CACHE_CONTROL,
HeaderValue::from_static("public, max-age=3600"),
);
headers.insert(
header::X_CONTENT_TYPE_OPTIONS,
HeaderValue::from_static("nosniff"),
);
response
}
#[cfg(test)]
mod tests {
use super::*;
use axum::body::to_bytes;
#[tokio::test]
async fn page_is_html_with_a_policy_for_its_inline_script() {
let response = page().await;
assert_eq!(response.status(), StatusCode::OK);
assert_eq!(
response.headers()[header::CONTENT_TYPE],
"text/html; charset=utf-8"
);
let csp = response.headers()[header::CONTENT_SECURITY_POLICY]
.to_str()
.unwrap()
.to_owned();
let hash = STANDARD.encode(Sha256::digest(INIT_JS.as_bytes()));
assert!(csp.contains(&format!("'sha256-{hash}'")), "{csp}");
assert!(csp.contains("default-src 'none'"));
assert!(csp.contains("form-action 'none'"));
assert!(!csp.contains("unsafe-eval"));
let body = to_bytes(response.into_body(), usize::MAX).await.unwrap();
let html = String::from_utf8(body.to_vec()).unwrap();
assert!(!html.contains(INIT_MARKER), "the loader was not inlined");
assert!(html.contains(&format!("<script>{INIT_JS}</script>")));
assert!(html.contains("src=\"/docs/redoc.standalone.js\""));
}
#[tokio::test]
async fn page_pulls_nothing_from_other_origins() {
let html = built().html.as_str();
// The stylesheet may mention `https://` in a selector; no attribute may load from one.
assert!(!html.contains("=\"http"), "{html}");
assert!(!INIT_JS.contains("http://") && !INIT_JS.contains("https://"));
}
#[tokio::test]
async fn script_is_javascript_and_is_the_embedded_gzip_bundle() {
let response = redoc_js().await;
assert_eq!(response.status(), StatusCode::OK);
assert_eq!(
response.headers()[header::CONTENT_TYPE],
"text/javascript; charset=utf-8"
);
assert_eq!(response.headers()[header::CONTENT_ENCODING], "gzip");
let body = to_bytes(response.into_body(), usize::MAX).await.unwrap();
assert_eq!(body.as_ref(), REDOC_JS_GZ);
assert_eq!(body[..2], [0x1f, 0x8b], "not a gzip stream");
assert!(body.len() > 100_000, "the vendored bundle looks truncated");
// Keeps the file under the hygiene check's size limit.
assert!(body.len() < 512 * 1024);
}
}