docgen-server 0.2.0

Live-reload preview server for docgen, the Cargo-only static documentation-site generator
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
//! In-process router + rebuild tests. No ports, no fs-timing — handlers are
//! exercised via `tower::ServiceExt::oneshot`, and rebuild-on-change is driven by
//! invoking `rebuild_and_reload` directly.

use std::fs;
use std::path::{Path, PathBuf};

use axum::body::Body;
use axum::http::{Request, StatusCode};
use http_body_util::BodyExt;
use tokio::sync::broadcast;
use tower::ServiceExt;

use docgen_build::{build_site, BuildMode, BuildOptions};
use docgen_server::{rebuild_and_reload, router, AppState, ReloadEvent};

/// Copy the `site-basic` fixture docs into `root/docs`.
fn setup_fixture(root: &Path) {
    let manifest = PathBuf::from(env!("CARGO_MANIFEST_DIR")); // crates/docgen-server
    let workspace = manifest.parent().unwrap().parent().unwrap();
    let fixture = workspace.join("fixtures/site-basic");
    fs::create_dir_all(root.join("docs/guide")).unwrap();
    fs::copy(fixture.join("docs/index.md"), root.join("docs/index.md")).unwrap();
    fs::copy(
        fixture.join("docs/guide/intro.md"),
        root.join("docs/guide/intro.md"),
    )
    .unwrap();
}

/// Build a fixture site + an `AppState` over a fresh tempdir out_dir, with the
/// dev-only assets emitted (mirrors `rebuild_and_reload`'s post-step).
fn state_with_built_site() -> (tempfile::TempDir, tempfile::TempDir, AppState) {
    let root = tempfile::tempdir().unwrap();
    setup_fixture(root.path());
    let out = tempfile::tempdir().unwrap();

    build_site(&BuildOptions {
        project_root: root.path(),
        out_dir: out.path(),
        mode: BuildMode::Dev,
    })
    .unwrap();
    docgen_assets::emit(&docgen_assets::dev_assets(), out.path()).unwrap();

    let docs_dir = root.path().join("docs").canonicalize().unwrap();
    let (reload_tx, _rx) = broadcast::channel(16);
    let state = AppState::new(
        root.path().to_path_buf(),
        out.path().to_path_buf(),
        docs_dir,
        4321,
        reload_tx,
    );
    (root, out, state)
}

#[tokio::test]
async fn serves_built_index_with_injected_dev_html() {
    let (_root, _out, state) = state_with_built_site();
    let app = router(state);

    let resp = app
        .oneshot(
            Request::builder()
                .uri("/")
                .header("host", "127.0.0.1:4321")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(resp.status(), StatusCode::OK);
    let body = resp.into_body().collect().await.unwrap().to_bytes();
    let html = String::from_utf8(body.to_vec()).unwrap();
    assert!(
        html.contains("<title>Home</title>"),
        "not the index: {html}"
    );
    // Serve-time injection added the reload client.
    assert!(html.contains("/__docgen/livereload.js"));
}

#[tokio::test]
async fn serves_static_asset_without_injection() {
    let (_root, _out, state) = state_with_built_site();
    let app = router(state);

    let resp = app
        .oneshot(
            Request::builder()
                .uri("/docgen.css")
                .header("host", "127.0.0.1:4321")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(resp.status(), StatusCode::OK);
    let ct = resp
        .headers()
        .get("content-type")
        .unwrap()
        .to_str()
        .unwrap()
        .to_string();
    assert!(ct.contains("css"), "unexpected content-type: {ct}");
    let body = resp.into_body().collect().await.unwrap().to_bytes();
    let css = String::from_utf8(body.to_vec()).unwrap();
    // Injection is HTML-only — css must not carry the reload client.
    assert!(!css.contains("/__docgen/livereload.js"));
}

#[tokio::test]
async fn unknown_path_404() {
    let (_root, _out, state) = state_with_built_site();
    let app = router(state);
    let resp = app
        .oneshot(
            Request::builder()
                .uri("/does/not/exist")
                .header("host", "127.0.0.1:4321")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(resp.status(), StatusCode::NOT_FOUND);
    // The 404 is the full styled app-shell page (so the user can navigate off via
    // the sidebar/search), with the dev reload client injected — not bare text.
    let ct = resp
        .headers()
        .get("content-type")
        .and_then(|v| v.to_str().ok())
        .unwrap_or("")
        .to_string();
    assert!(ct.contains("html"), "404 should be html, got {ct}");
    let body = resp.into_body().collect().await.unwrap().to_bytes();
    let html = String::from_utf8(body.to_vec()).unwrap();
    assert!(html.contains("docgen-sidebar"), "404 lacks the nav shell");
    assert!(html.contains("404"), "404 body missing the 404 marker");
    assert!(
        html.contains("/__docgen/livereload.js"),
        "404 missing dev injection"
    );
}

#[tokio::test]
async fn serves_dev_livereload_client_asset() {
    let (_root, _out, state) = state_with_built_site();
    let app = router(state);
    let resp = app
        .oneshot(
            Request::builder()
                .uri("/__docgen/livereload.js")
                .header("host", "127.0.0.1:4321")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(resp.status(), StatusCode::OK);
    let body = resp.into_body().collect().await.unwrap().to_bytes();
    let js = String::from_utf8(body.to_vec()).unwrap();
    assert!(js.contains("EventSource('/__docgen/livereload')"));
}

#[tokio::test]
async fn rejects_foreign_host_header_dns_rebinding() {
    // A DNS-rebinding attacker reaches the loopback bind but the rebound request
    // still carries the attacker hostname in Host -> must be 403, not served.
    let (_root, _out, state) = state_with_built_site();
    let app = router(state);
    let resp = app
        .oneshot(
            Request::builder()
                .uri("/")
                .header("host", "attacker.com:4321")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(resp.status(), StatusCode::FORBIDDEN);
}

#[tokio::test]
async fn rejects_missing_host_header() {
    // A request with no Host at all is not a loopback browser request.
    let (_root, _out, state) = state_with_built_site();
    let app = router(state);
    let resp = app
        .oneshot(Request::builder().uri("/").body(Body::empty()).unwrap())
        .await
        .unwrap();
    assert_eq!(resp.status(), StatusCode::FORBIDDEN);
}

#[tokio::test]
async fn accepts_localhost_host_header() {
    // `localhost:<port>` is an allowed loopback authority alongside 127.0.0.1.
    let (_root, _out, state) = state_with_built_site();
    let app = router(state);
    let resp = app
        .oneshot(
            Request::builder()
                .uri("/")
                .header("host", "localhost:4321")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(resp.status(), StatusCode::OK);
}

#[tokio::test]
async fn rejects_cross_site_origin_on_mutating_put() {
    // A PUT with a valid loopback Host but a cross-site Origin (the cross-origin
    // write a rebinding/preflight-skipping attacker would attempt) -> 403.
    let (root, _out, state) = state_with_built_site();
    let secret_before = fs::read_to_string(root.path().join("docs/index.md")).unwrap();
    let app = router(state);
    let resp = app
        .oneshot(
            Request::builder()
                .method("PUT")
                .uri("/__docgen/source")
                .header("host", "127.0.0.1:4321")
                .header("origin", "http://attacker.com")
                .header("content-type", "application/json")
                .body(Body::from(
                    serde_json::json!({ "path": "index.md", "source": "HACKED" }).to_string(),
                ))
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(resp.status(), StatusCode::FORBIDDEN);
    // The write never landed.
    assert_eq!(
        fs::read_to_string(root.path().join("docs/index.md")).unwrap(),
        secret_before
    );
}

#[tokio::test]
async fn livereload_endpoint_streams_reload_event() {
    use tokio::time::{timeout, Duration};

    // The load-bearing wire: GET /__docgen/livereload must be a 200 SSE stream,
    // and a broadcast Reload must arrive as an `event: reload` / `data: now` frame.
    let (_root, _out, state) = state_with_built_site();
    let tx = state.reload_tx.clone();
    let app = router(state);

    let resp = app
        .oneshot(
            Request::builder()
                .uri("/__docgen/livereload")
                .header("host", "127.0.0.1:4321")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(resp.status(), StatusCode::OK);
    let ct = resp
        .headers()
        .get("content-type")
        .unwrap()
        .to_str()
        .unwrap()
        .to_string();
    assert!(ct.contains("text/event-stream"), "not SSE: {ct}");

    // Drive a reload and read the first frame off the (otherwise endless) stream.
    let mut body = resp.into_body().into_data_stream();
    tx.send(ReloadEvent::Reload).unwrap();
    use futures::StreamExt as _;
    let chunk = timeout(Duration::from_secs(2), body.next())
        .await
        .expect("SSE frame timed out")
        .expect("stream ended")
        .expect("stream error");
    let frame = String::from_utf8(chunk.to_vec()).unwrap();
    assert!(frame.contains("event: reload"), "frame: {frame}");
    assert!(frame.contains("data: now"), "frame: {frame}");
}

#[tokio::test]
async fn rebuild_broadcasts_reload() {
    let (_root, _out, state) = state_with_built_site();
    let mut rx = state.reload_tx.subscribe();
    rebuild_and_reload(&state).unwrap();
    assert_eq!(rx.recv().await.unwrap(), ReloadEvent::Reload);
}

#[tokio::test]
async fn rebuild_regenerates_changed_page() {
    let (root, out, state) = state_with_built_site();

    let before = fs::read_to_string(out.path().join("index/index.html")).unwrap();
    assert!(before.contains("<title>Home</title>"));

    // Edit the source on disk, then rebuild directly (no watcher, no port).
    fs::write(
        root.path().join("docs/index.md"),
        "---\ntitle: Renamed Home\n---\n\nfresh body\n",
    )
    .unwrap();
    rebuild_and_reload(&state).unwrap();

    let after = fs::read_to_string(out.path().join("index/index.html")).unwrap();
    assert!(
        after.contains("Renamed Home"),
        "rebuild did not pick up the edit: {after}"
    );
}

#[tokio::test]
async fn failed_build_does_not_broadcast() {
    let (root, _out, state) = state_with_built_site();
    let mut rx = state.reload_tx.subscribe();

    // Remove the docs dir so discover fails -> hard build error.
    fs::remove_dir_all(root.path().join("docs")).unwrap();
    let res = rebuild_and_reload(&state);
    assert!(res.is_err(), "expected a hard build failure");
    // No reload was delivered for the failed build.
    assert!(rx.try_recv().is_err());
}

/// Build a custom site (given `docs/` files + a `docgen.toml`) and an `AppState`
/// honoring its `base`, mirroring how `serve` derives `AppState` from config.
fn state_with_site(
    files: &[(&str, &str)],
    toml: &str,
) -> (tempfile::TempDir, tempfile::TempDir, AppState) {
    let root = tempfile::tempdir().unwrap();
    fs::write(root.path().join("docgen.toml"), toml).unwrap();
    for (rel, body) in files {
        let path = root.path().join("docs").join(rel);
        fs::create_dir_all(path.parent().unwrap()).unwrap();
        fs::write(path, body).unwrap();
    }
    let out = tempfile::tempdir().unwrap();
    build_site(&BuildOptions {
        project_root: root.path(),
        out_dir: out.path(),
        mode: BuildMode::Dev,
    })
    .unwrap();
    docgen_assets::emit(&docgen_assets::dev_assets(), out.path()).unwrap();

    let docs_dir = root.path().join("docs").canonicalize().unwrap();
    let base = docgen_config::load(root.path()).unwrap().base;
    let (reload_tx, _rx) = broadcast::channel(16);
    let state = AppState::new(
        root.path().to_path_buf(),
        out.path().to_path_buf(),
        docs_dir,
        4321,
        reload_tx,
    )
    .with_base(&base);
    (root, out, state)
}

async fn get_status(app: axum::Router, uri: &str) -> StatusCode {
    app.oneshot(
        Request::builder()
            .uri(uri)
            .header("host", "127.0.0.1:4321")
            .body(Body::empty())
            .unwrap(),
    )
    .await
    .unwrap()
    .status()
}

/// Regression: a page whose slug contains non-ASCII characters is served for the
/// percent-encoded request a browser actually sends (the path must be decoded
/// before it is resolved against the Unicode dir on disk).
#[tokio::test]
async fn serves_non_ascii_slug_via_percent_encoded_request() {
    let (_root, _out, state) = state_with_site(
        &[("café/résumé.md", "---\ntitle: R\n---\n\nbody\n")],
        "base = \"\"\n",
    );
    let app = router(state);
    // Browser percent-encodes "café/résumé" as below.
    assert_eq!(
        get_status(app, "/caf%C3%A9/r%C3%A9sum%C3%A9").await,
        StatusCode::OK
    );
}

/// Regression: with a non-empty `base`, the dev server strips the prefix the
/// built HTML emits on every asset/page URL — otherwise every request 404s.
#[tokio::test]
async fn strips_base_prefix_from_requests() {
    let (_root, _out, state) = state_with_site(
        &[
            ("index.md", "---\ntitle: H\n---\n\nhome\n"),
            ("guide.md", "---\ntitle: G\n---\n\nbody\n"),
        ],
        "base = \"/docs\"\n",
    );
    let app = router(state.clone());
    // Asset + page + home under the base resolve.
    assert_eq!(
        get_status(app.clone(), "/docs/docgen.css").await,
        StatusCode::OK
    );
    assert_eq!(get_status(app.clone(), "/docs/guide").await, StatusCode::OK);
    assert_eq!(get_status(app, "/docs/").await, StatusCode::OK);
}