use std::fs;
use std::path::{Path, PathBuf};
use axum::Router;
use axum::body::Body;
use axum::extract::{Path as UrlPath, State};
use axum::http::{Method, Request, StatusCode, Uri, header};
use axum::response::Response;
use handlebars::handlebars_helper;
use serde_json::json;
use tower::ServiceExt;
use crate::analytics::AnalyticsConfig;
use crate::assets::generate::generate_static_assets_in;
use crate::assets::{CacheBuster, CacheBusterError, Phase};
use crate::environment::Environment;
use crate::templates::{
BaseTemplateData, BaseTemplateDataParams, Fallback, PageTemplateData, SiteEntity, ThemeColor,
};
use crate::templates::TemplateError;
use super::{FrontendParams, NotFound, Pages, Shutdown, WebServer, WebServerError, WebServerState};
handlebars_helper!(shout: |word: str| word.to_uppercase());
async fn thing(State(state): State<WebServerState>, UrlPath(slug): UrlPath<String>) -> Response {
state.not_found(json!({ "hint": format!("no thing {slug}") }))
}
const STYLESHEET: &str = "static/stylesheet/main.css";
fn fixture() -> PathBuf {
Path::new(env!("CARGO_MANIFEST_DIR")).join("src/webserver/into_router_tests/site")
}
fn scratch_site(name: &str) -> PathBuf {
let root: PathBuf = std::env::temp_dir().join(format!("wsb-into-router-{name}"));
let _ = fs::remove_dir_all(&root);
copy_tree(&fixture(), &root);
root
}
fn built_site(name: &str) -> PathBuf {
let root: PathBuf = scratch_site(name);
generate_static_assets_in(&root, Phase::NonScripts).expect("the fixture builds");
root
}
fn copy_tree(from: &Path, to: &Path) {
fs::create_dir_all(to).expect("scratch directory");
for entry in fs::read_dir(from).expect("fixture directory") {
let path: PathBuf = entry.expect("fixture entry").path();
let target: PathBuf = to.join(path.file_name().expect("named entry"));
if path.is_dir() {
copy_tree(&path, &target);
} else {
fs::copy(&path, &target).expect("fixture file");
}
}
}
fn frontend() -> FrontendParams {
frontend_with(
Pages::new()
.static_page(PageTemplateData::new("home", "Home", "/"), ())
.dynamic_page("/things/{slug}", axum::routing::get(thing))
.unlisted(),
)
}
fn frontend_with(pages: Pages) -> FrontendParams {
frontend_with_analytics(pages, AnalyticsConfig::new("fixture"))
}
fn frontend_with_analytics(pages: Pages, analytics: AnalyticsConfig) -> FrontendParams {
FrontendParams::new(
BaseTemplateData::new(BaseTemplateDataParams {
project: String::from("Fixture"),
description: String::from("A site that exists to be booted."),
author: String::from("Fixture Author"),
base_url: String::from("https://fixture.example"),
twitter_username: String::from("fixture"),
social_image: String::from("static/image/social/card.webp"),
social_image_alt: String::from("Fixture card"),
theme_color: ThemeColor::light_dark("#ffffff", "#000000"),
theme_fallback: Fallback::Dark,
site_entity: SiteEntity::person("Fixture Author"),
language_code: String::from("en"),
country_code: String::from("US"),
see_also: Vec::new(),
copyright_start: String::from("2026"),
style_sheets: vec![String::from(STYLESHEET)],
scripts: Vec::new(),
})
.with_site(json!({
"phone": "(555) 010-0000",
"nav": [
{ "href": "/", "label": "Home" },
{ "href": "/things", "label": "Things" },
],
})),
pages,
analytics,
"https://abc123@o4504844394627072.ingest.sentry.io/4504862450515968",
)
.with_helper("shout", shout)
}
fn site_router(root: &Path) -> Result<Router, WebServerError> {
site_router_with(root, frontend())
}
fn site_router_with(root: &Path, params: FrontendParams) -> Result<Router, WebServerError> {
WebServer::new("127.0.0.1", 0, Environment::Local)
.root_dir(root)
.frontend(params)
.into_router(Shutdown::manual())
}
async fn get(router: &Router, uri: &str) -> Response {
request(router, Method::GET, uri).await
}
async fn request(router: &Router, method: Method, uri: &str) -> Response {
router
.clone()
.oneshot(
Request::builder()
.method(method)
.uri(uri)
.body(Body::empty())
.expect("a valid request"),
)
.await
.expect("a router never fails")
}
async fn text(response: Response) -> String {
let bytes: axum::body::Bytes = axum::body::to_bytes(response.into_body(), usize::MAX)
.await
.expect("a readable body");
String::from_utf8(bytes.to_vec()).expect("a UTF-8 body")
}
#[tokio::test]
async fn a_page_renders_and_links_its_stylesheet_by_its_hashed_url() {
let root: PathBuf = built_site("page");
let router: Router = site_router(&root).expect("the built site boots");
let hashed: String = CacheBuster::load_in(&root)
.expect("the manifest the build wrote")
.get_file(STYLESHEET);
let response: Response = get(&router, "/").await;
assert_eq!(StatusCode::OK, response.status());
let body: String = text(response).await;
assert!(body.contains("home of Fixture"), "{body}");
assert!(body.contains(&format!("/{hashed}")), "{body}");
}
#[tokio::test]
async fn a_hashed_asset_is_served_from_the_root_and_cached_forever() {
let root: PathBuf = built_site("static");
let router: Router = site_router(&root).expect("the built site boots");
let hashed: String = CacheBuster::load_in(&root)
.expect("the manifest the build wrote")
.get_file(STYLESHEET);
let response: Response = get(&router, &format!("/{hashed}")).await;
assert_eq!(StatusCode::OK, response.status());
let cache_control: &str = response
.headers()
.get(header::CACHE_CONTROL)
.and_then(|value| value.to_str().ok())
.unwrap_or_default();
assert!(cache_control.contains("immutable"), "{cache_control}");
let expected: String =
fs::read_to_string(fixture().join(STYLESHEET)).expect("the fixture stylesheet");
let actual: String = text(response).await;
assert_eq!(expected, actual);
}
#[tokio::test]
async fn a_static_miss_is_a_404_that_is_never_cached() {
let root: PathBuf = built_site("static-miss");
let router: Router = site_router(&root).expect("the built site boots");
let response: Response = get(&router, "/static/stylesheet/main.0000000000.css").await;
assert_eq!(StatusCode::NOT_FOUND, response.status());
let cache_control: &str = response
.headers()
.get(header::CACHE_CONTROL)
.and_then(|value| value.to_str().ok())
.unwrap_or_default();
assert!(cache_control.contains("no-store"), "{cache_control}");
assert!(!cache_control.contains("immutable"), "{cache_control}");
}
#[tokio::test]
async fn a_generated_icon_is_served_at_its_well_known_path() {
let root: PathBuf = built_site("icon");
let router: Router = site_router(&root).expect("the built site boots");
let expected: StatusCode = StatusCode::OK;
let actual: StatusCode = get(&router, "/favicon.ico").await.status();
assert_eq!(expected, actual);
}
#[tokio::test]
async fn an_unknown_path_renders_the_sites_own_404_page_with_its_site_data() {
let root: PathBuf = built_site("not-found");
let router: Router = site_router(&root).expect("the built site boots");
let response: Response = get(&router, "/no-such-page").await;
assert_eq!(StatusCode::NOT_FOUND, response.status());
let cache_control: &str = response
.headers()
.get(header::CACHE_CONTROL)
.and_then(|value| value.to_str().ok())
.unwrap_or_default();
assert!(cache_control.contains("no-store"), "{cache_control}");
let body: String = text(response).await;
assert!(body.contains("fixture 404"), "{body}");
assert!(body.contains("call (555) 010-0000"), "{body}");
assert!(body.contains("noindex, follow"), "{body}");
assert!(!body.contains(" hint "), "{body}");
}
#[tokio::test]
async fn the_fallback_404_renders_what_the_projects_hook_returns_for_the_requested_uri() {
let root: PathBuf = built_site("not-found-hook");
let params: FrontendParams = frontend().with_not_found(NotFound::with(
|_state: WebServerState, uri: Uri| async move { json!({ "hint": uri.path() }) },
));
let router: Router = site_router_with(&root, params).expect("the built site boots");
let response: Response = get(&router, "/blgo/rust").await;
assert_eq!(StatusCode::NOT_FOUND, response.status());
let body: String = text(response).await;
assert!(body.contains("fixture 404 hint /blgo/rust"), "{body}");
assert!(body.contains("call (555) 010-0000"), "{body}");
}
#[tokio::test]
async fn a_handler_whose_resource_is_missing_returns_the_same_404_with_its_own_data() {
let root: PathBuf = built_site("handler-not-found");
let router: Router = site_router(&root).expect("the built site boots");
let response: Response = get(&router, "/things/nope").await;
assert_eq!(StatusCode::NOT_FOUND, response.status());
let body: String = text(response).await;
assert!(body.contains("fixture 404 hint no thing nope"), "{body}");
assert!(body.contains("call (555) 010-0000"), "{body}");
assert!(body.contains("noindex, follow"), "{body}");
}
#[tokio::test]
async fn every_page_gets_the_site_data_and_its_own_nav_item_highlighted() {
let root: PathBuf = built_site("site-data");
let router: Router = site_router(&root).expect("the built site boots");
let body: String = text(get(&router, "/").await).await;
assert!(body.contains("call (555) 010-0000"), "{body}");
assert!(
body.contains(r#"<a href="/" class="active">Home</a>"#),
"{body}"
);
assert!(body.contains(r#"<a href="/things">Things</a>"#), "{body}");
}
#[tokio::test]
async fn a_projects_own_helper_renders() {
let root: PathBuf = built_site("helper");
let router: Router = site_router(&root).expect("the built site boots");
let body: String = text(get(&router, "/").await).await;
assert!(body.contains("home of Fixture, LOUD"), "{body}");
}
#[tokio::test]
async fn a_project_helper_named_like_a_built_in_is_refused_at_boot() {
let root: PathBuf = built_site("helper-collision");
let params: FrontendParams = frontend().with_helper("join", shout);
let error: WebServerError =
site_router_with(&root, params).expect_err("a built-in cannot be overridden");
assert!(
matches!(
error,
WebServerError::Template(TemplateError::ReservedHelper { ref name }) if name == "join"
),
"{error}"
);
}
#[tokio::test]
async fn a_handler_404_on_a_server_with_no_frontend_is_still_a_404() {
let router: Router = WebServer::new("127.0.0.1", 0, Environment::Local)
.root_dir(std::env::temp_dir().join("wsb-into-router-no-such-root"))
.merge(Router::new().route(
"/things/{slug}",
axum::routing::get(
|State(state): State<WebServerState>| async move { state.not_found(()) },
),
))
.into_router(Shutdown::manual())
.expect("a sidecar always boots");
let response: Response = get(&router, "/things/nope").await;
assert_eq!(StatusCode::NOT_FOUND, response.status());
let expected: String = String::from("404");
let actual: String = text(response).await;
assert_eq!(expected, actual);
}
#[tokio::test]
async fn a_site_whose_build_never_ran_fails_to_boot_instead_of_serving_unhashed_links() {
let root: PathBuf = scratch_site("unbuilt");
let error: WebServerError = site_router(&root).expect_err("no manifest, no boot");
assert!(
matches!(
error,
WebServerError::CacheBuster(CacheBusterError::MissingManifest { .. })
),
"{error}"
);
}
#[tokio::test]
async fn a_server_with_no_frontend_boots_from_a_root_holding_nothing() {
let root: PathBuf = std::env::temp_dir().join("wsb-into-router-no-such-root");
let router: Router = WebServer::new("127.0.0.1", 0, Environment::Local)
.root_dir(root)
.into_router(Shutdown::manual())
.expect("a sidecar always boots");
let expected: StatusCode = StatusCode::OK;
let actual: StatusCode = get(&router, "/api/v1/health").await.status();
assert_eq!(expected, actual);
}
fn slash_pages() -> Pages {
Pages::new()
.static_page(PageTemplateData::new("home", "Home", "/"), ())
.static_page(PageTemplateData::new("home", "About", "/about"), ())
.dynamic_page("/plain", axum::routing::any(|| async { "plain" }))
.dynamic_page("/docs/", axum::routing::get(|| async { "docs" }))
.dynamic_page("/things/{slug}", axum::routing::get(thing))
.unlisted()
.dynamic_page(
"/files/{*path}",
axum::routing::get(|UrlPath(path): UrlPath<String>| async move { path }),
)
.unlisted()
.dynamic_page(
"/private",
axum::routing::get(|| async { "secret" }).layer(axum::middleware::from_fn(
|request: Request<Body>, next: axum::middleware::Next| async move {
if request.headers().contains_key(header::AUTHORIZATION) {
next.run(request).await
} else {
axum::response::IntoResponse::into_response(StatusCode::UNAUTHORIZED)
}
},
)),
)
}
fn location(response: &Response) -> &str {
response
.headers()
.get(header::LOCATION)
.and_then(|value| value.to_str().ok())
.unwrap_or_default()
}
#[tokio::test]
async fn every_page_redirects_its_other_trailing_slash_form_to_the_declared_one() {
let root: PathBuf = built_site("slash-redirects");
let router: Router =
site_router_with(&root, frontend_with(slash_pages())).expect("the built site boots");
for (requested, expected) in [
("/about/", "/about"),
("/plain/?q=x&y=1", "/plain?q=x&y=1"),
("/things/some-slug/", "/things/some-slug"),
("/docs?q=x", "/docs/?q=x"),
] {
let response: Response = get(&router, requested).await;
assert_eq!(
StatusCode::PERMANENT_REDIRECT,
response.status(),
"{requested}"
);
assert_eq!(expected, location(&response), "{requested}");
}
assert_eq!(StatusCode::OK, get(&router, "/about").await.status());
assert_eq!(StatusCode::OK, get(&router, "/docs/").await.status());
}
#[tokio::test]
async fn a_redirect_keeps_the_method_so_a_post_is_not_turned_into_a_get() {
let root: PathBuf = built_site("slash-method");
let router: Router =
site_router_with(&root, frontend_with(slash_pages())).expect("the built site boots");
let response: Response = request(&router, Method::POST, "/plain/").await;
assert_eq!(StatusCode::PERMANENT_REDIRECT, response.status());
assert_eq!("/plain", location(&response));
}
#[tokio::test]
async fn a_misslashed_url_to_a_missing_resource_redirects_first_then_404s_at_the_canonical_path() {
let root: PathBuf = built_site("slash-not-found");
let router: Router =
site_router_with(&root, frontend_with(slash_pages())).expect("the built site boots");
let redirect: Response = get(&router, "/things/nope/").await;
assert_eq!(StatusCode::PERMANENT_REDIRECT, redirect.status());
assert_eq!("/things/nope", location(&redirect));
let response: Response = get(&router, "/things/nope").await;
assert_eq!(StatusCode::NOT_FOUND, response.status());
let body: String = text(response).await;
assert!(body.contains("fixture 404 hint no thing nope"), "{body}");
}
#[tokio::test]
async fn a_guarded_page_redirects_without_its_guard_and_the_guard_still_answers_at_the_canonical_path()
{
let root: PathBuf = built_site("slash-guarded");
let router: Router =
site_router_with(&root, frontend_with(slash_pages())).expect("the built site boots");
let redirect: Response = get(&router, "/private/").await;
assert_eq!(StatusCode::PERMANENT_REDIRECT, redirect.status());
assert_eq!("/private", location(&redirect));
assert_eq!(
StatusCode::UNAUTHORIZED,
get(&router, "/private").await.status()
);
}
#[tokio::test]
async fn the_root_a_wildcard_and_an_undeclared_path_get_no_alias() {
let root: PathBuf = built_site("slash-exempt");
let router: Router =
site_router_with(&root, frontend_with(slash_pages())).expect("the built site boots");
assert_eq!(StatusCode::OK, get(&router, "/").await.status());
let wildcard: Response = get(&router, "/files/a/b/").await;
assert_eq!(StatusCode::OK, wildcard.status());
assert_eq!("a/b/", text(wildcard).await);
let response: Response = get(&router, "/nope/").await;
assert_eq!(StatusCode::NOT_FOUND, response.status());
let body: String = text(response).await;
assert!(body.contains("fixture 404"), "{body}");
}
#[tokio::test]
async fn two_pages_differing_only_by_a_trailing_slash_are_refused_at_boot() {
let root: PathBuf = built_site("slash-duplicate");
let pages: Pages = Pages::new()
.dynamic_page("/blog", axum::routing::get(|| async { "a" }))
.dynamic_page("/blog/", axum::routing::get(|| async { "b" }));
let error: WebServerError =
site_router_with(&root, frontend_with(pages)).expect_err("both forms cannot be routed");
assert!(
matches!(
error,
WebServerError::DuplicatePagePath { ref first, ref second }
if first == "/blog" && second == "/blog/"
),
"{error}"
);
}
fn cache_router() -> Router {
use axum::http::HeaderValue;
use axum::response::IntoResponse;
use axum::routing::get as get_route;
let routes: Router<WebServerState> = Router::new()
.route("/plain", get_route(|| async { "plain" }))
.route(
"/chosen",
get_route(|| async {
(
[(
header::CACHE_CONTROL,
HeaderValue::from_static("public, max-age=300"),
)],
"chosen",
)
.into_response()
}),
);
WebServer::new("127.0.0.1", 0, Environment::Local)
.merge(routes)
.into_router(Shutdown::manual())
.expect("a router with no frontend always boots")
}
fn cache_control(response: &Response) -> &str {
response
.headers()
.get(header::CACHE_CONTROL)
.and_then(|value| value.to_str().ok())
.unwrap_or_default()
}
#[tokio::test]
async fn a_route_that_sets_no_cache_policy_is_never_cached() {
let response: Response = get(&cache_router(), "/plain").await;
assert_eq!(StatusCode::OK, response.status());
assert!(
cache_control(&response).contains("no-store"),
"{}",
cache_control(&response)
);
}
#[tokio::test]
async fn a_route_that_sets_its_own_cache_policy_keeps_it() {
let response: Response = get(&cache_router(), "/chosen").await;
assert_eq!(StatusCode::OK, response.status());
assert_eq!("public, max-age=300", cache_control(&response));
assert!(!response.headers().contains_key(header::PRAGMA));
}
fn analytics_home() -> Pages {
Pages::new().static_page(PageTemplateData::new("home", "Home", "/"), ())
}
fn analytics_router(name: &str, environment: Environment, analytics: AnalyticsConfig) -> Router {
let root: PathBuf = built_site(name);
WebServer::new("127.0.0.1", 0, environment)
.root_dir(&root)
.frontend(frontend_with_analytics(analytics_home(), analytics))
.into_router(Shutdown::manual())
.expect("the built site boots")
}
fn analytics_script_path(body: &str) -> Option<String> {
let stub: usize = body.find("window.plausible")?;
let before: &str = &body[..stub];
let start: usize = before.rfind("<script defer src=\"")? + "<script defer src=\"".len();
let end: usize = start + before[start..].find('"')?;
Some(before[start..end].to_string())
}
#[tokio::test]
async fn production_with_an_id_renders_the_analytics_script_tag() {
let router: Router = analytics_router(
"analytics-prod",
Environment::Production,
AnalyticsConfig::new("pa-fixture"),
);
let body: String = text(get(&router, "/").await).await;
let path: String = analytics_script_path(&body).expect("a script tag");
assert!(path.starts_with("/script/fixture-"), "{path}");
assert!(
body.contains("plausible.init({ endpoint: \"/api/v1/fixture-"),
"{body}"
);
}
#[tokio::test]
async fn local_mode_renders_no_analytics_and_its_proxy_routes_404_even_with_an_id() {
let production: Router = analytics_router(
"analytics-ref",
Environment::Production,
AnalyticsConfig::new("pa-fixture"),
);
let path: String =
analytics_script_path(&text(get(&production, "/").await).await).expect("a script tag");
let event_path: String = path
.replace("/script/", "/api/v1/")
.trim_end_matches(".js")
.to_string();
let router: Router = analytics_router(
"analytics-local",
Environment::Local,
AnalyticsConfig::new("pa-fixture"),
);
let body: String = text(get(&router, "/").await).await;
assert!(!body.contains("plausible"), "{body}");
assert!(!body.contains(&path), "{body}");
assert_eq!(StatusCode::NOT_FOUND, get(&router, &path).await.status());
assert_eq!(
StatusCode::NOT_FOUND,
request(&router, Method::POST, &event_path).await.status()
);
}
#[tokio::test]
async fn an_unset_or_empty_id_renders_no_analytics_in_production() {
let production: Router = analytics_router(
"analytics-unset-ref",
Environment::Production,
AnalyticsConfig::new("pa-fixture"),
);
let path: String =
analytics_script_path(&text(get(&production, "/").await).await).expect("a script tag");
let event_path: String = path
.replace("/script/", "/api/v1/")
.trim_end_matches(".js")
.to_string();
for (name, analytics) in [
("analytics-unset", AnalyticsConfig::disabled()),
("analytics-empty", AnalyticsConfig::new("")),
] {
let router: Router = analytics_router(name, Environment::Production, analytics);
let body: String = text(get(&router, "/").await).await;
assert!(!body.contains("plausible"), "{name}: {body}");
assert!(!body.contains(&path), "{name}: {body}");
assert_eq!(StatusCode::NOT_FOUND, get(&router, &path).await.status());
assert_eq!(
StatusCode::NOT_FOUND,
request(&router, Method::POST, &event_path).await.status()
);
}
}