webserver-base 0.2.7

A Rust library which contains shared logic for all of my webserver projects.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
//! [`WebServer::into_router`] against a real built site, from a root that is
//! not the working directory.
//!
//! That second half is the point. Every file path the server reads has to be
//! joined onto the root, and a missed join still passes wherever the root is the
//! working directory — which is every other test and every deploy. Here it never
//! is: `cargo test` runs from the crate, and the site is built in a scratch
//! directory from the source tree beside this file.

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};

// A project's own helper, which the fixture's home page calls.
handlebars_helper!(shout: |word: str| word.to_uppercase());

/// A matched route whose resource does not exist.
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";

/// The un-built source tree. Never built in place: hashing renames files.
fn fixture() -> PathBuf {
    Path::new(env!("CARGO_MANIFEST_DIR")).join("src/webserver/into_router_tests/site")
}

/// A fresh copy of the fixture, not yet built.
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
}

/// A copy of the fixture, run through the real asset pipeline.
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 {
    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,
        AnalyticsConfig::new("fixture"),
        "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() {
    // A hashed URL can be asked for before its file is deployed; caching that
    // 404 immutable would outlive the deploy by a year.
    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());

    // The fallback sits outside the never-cache layer, so it must stamp its
    // own headers.
    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}");
    // The header partial reads `{{site}}`; null data here was the original bug.
    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() {
    // The sidecar guarantee, through the new path: no templates, no icons, no
    // `static/`, and still a working health check.
    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);
}

/// Every page shape a trailing-slash alias has to cover, plus the two exempt.
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");

    // (requested, canonical): static, dynamic, parameterised, declared-with-slash.
    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");

    // The redirect says only that the route exists, which the 401 says anyway.
    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());

    // A wildcard already matches the slash form; it is served, not redirected.
    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}"
    );
}