use axum::routing::get;
use axum::Router;
use rustango::cors::CorsRouterExt as _;
pub mod auth;
pub mod changes;
pub mod documents;
pub mod error;
pub mod http_cache;
pub mod images;
pub mod locales;
pub mod menus;
pub mod pages;
pub mod openapi;
pub mod query;
pub mod search;
pub mod snippets;
pub mod tree;
pub const PREFIX: &str = "/api/v2";
const EXPOSED_HEADERS: [&str; 2] = ["etag", "allow"];
#[derive(Debug, Clone, Default)]
pub enum Cors {
#[default]
Disabled,
Origins(Vec<String>),
Any,
}
impl Cors {
#[must_use]
pub fn from_env() -> Self {
Self::parse(crate::config::var("API_CORS_ORIGINS").as_deref())
}
#[must_use]
pub fn parse(raw: Option<&str>) -> Self {
let Some(raw) = raw else {
return Self::Disabled;
};
if raw.trim() == "*" {
return Self::Any;
}
let origins: Vec<String> = raw
.split(',')
.map(str::trim)
.filter(|s| !s.is_empty())
.map(str::to_owned)
.collect();
if origins.is_empty() {
Self::Disabled
} else {
Self::Origins(origins)
}
}
}
pub fn router() -> Router {
router_with(&Cors::Disabled)
}
pub const ROUTE_PATHS: [&str; 15] = [
"/api/v2/pages/",
"/api/v2/pages/find/",
"/api/v2/pages/tree/",
"/api/v2/pages/{id}/",
"/api/v2/images/",
"/api/v2/images/{id}/",
"/api/v2/documents/",
"/api/v2/documents/{id}/",
"/api/v2/snippets/",
"/api/v2/snippets/{id}/",
"/api/v2/menus/",
"/api/v2/menus/{slug}/",
"/api/v2/locales/",
"/api/v2/search/",
"/api/v2/changes/",
];
pub fn router_with(cors: &Cors) -> Router {
let handlers = [
get(pages::list),
get(pages::find),
get(tree::tree),
get(pages::detail),
get(images::list),
get(images::detail),
get(documents::list),
get(documents::detail),
get(snippets::list),
get(snippets::detail),
get(menus::list),
get(menus::detail),
get(locales::list),
get(search::search),
get(changes::changes),
];
let mut r = Router::new();
for (path, route) in ROUTE_PATHS.iter().zip(handlers) {
r = r
.route(path, route.clone())
.route(path.trim_end_matches('/'), route);
}
r = r.route(openapi::PATH, get(openapi::serve));
r = r.route(auth::LOGIN_PATH, axum::routing::post(auth::login));
let r = r
.layer(axum::middleware::from_fn(error::method_not_allowed_json))
.layer(axum::middleware::from_fn(http_cache::layer));
const ALLOWED_METHODS: [&str; 4] = ["GET", "HEAD", "OPTIONS", "POST"];
const ALLOWED_HEADERS: [&str; 3] = ["content-type", "if-none-match", "authorization"];
match cors {
Cors::Disabled => r,
Cors::Any => r.cors(
rustango::cors::CorsLayer::new()
.allow_methods(ALLOWED_METHODS.to_vec())
.allow_headers(ALLOWED_HEADERS.to_vec())
.expose_headers(EXPOSED_HEADERS),
),
Cors::Origins(origins) => r.cors(
rustango::cors::CorsLayer::new()
.allow_origins(origins.clone())
.allow_methods(ALLOWED_METHODS.to_vec())
.allow_headers(ALLOWED_HEADERS.to_vec())
.expose_headers(EXPOSED_HEADERS)
.allow_credentials(true)
.max_age(std::time::Duration::from_secs(3600)),
),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn an_absent_value_leaves_cors_off() {
assert!(matches!(Cors::parse(None), Cors::Disabled));
}
#[test]
fn an_empty_or_whitespace_value_is_also_off() {
assert!(matches!(Cors::parse(Some("")), Cors::Disabled));
assert!(matches!(Cors::parse(Some(" , ,")), Cors::Disabled));
}
#[test]
fn a_comma_separated_list_is_parsed_and_trimmed() {
match Cors::parse(Some("https://a.example.com, https://b.example.com")) {
Cors::Origins(o) => {
assert_eq!(o, ["https://a.example.com", "https://b.example.com"]);
}
other => panic!("expected an allowlist, got {other:?}"),
}
}
#[test]
fn a_literal_star_is_the_reflect_any_mode() {
assert!(matches!(Cors::parse(Some("*")), Cors::Any));
assert!(matches!(Cors::parse(Some(" * ")), Cors::Any));
}
#[test]
fn the_default_is_disabled() {
assert!(matches!(Cors::default(), Cors::Disabled));
}
}