guidebook 0.1.70

HonKit/GitBook compatible static book generator
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
//! Integration tests for guidebook build process
//!
//! Tests the full build pipeline by creating a book structure in a temp directory,
//! running the build process, and verifying the output.

use std::fs;
use std::process::{Command, Stdio};
use tempfile::tempdir;

/// Get the path to the guidebook binary built by cargo
fn guidebook_bin() -> String {
    // cargo test builds the binary in target/debug/
    let mut path = std::env::current_exe().unwrap();
    // Walk up from the test binary to the target directory
    path.pop(); // remove test binary name
    path.pop(); // remove deps/
    path.push("guidebook");
    path.to_string_lossy().to_string()
}

/// Create a minimal book structure for testing
fn create_test_book(dir: &std::path::Path) {
    // book.json
    fs::write(
        dir.join("book.json"),
        r#"{
    "title": "Test Book",
    "description": "A test book",
    "author": "Test Author"
}"#,
    )
    .unwrap();

    // SUMMARY.md
    fs::write(
        dir.join("SUMMARY.md"),
        r#"# Summary

* [Introduction](README.md)
* [Chapter 1](chapter1.md)
* [Chapter 2](chapter2/README.md)
"#,
    )
    .unwrap();

    // README.md
    fs::write(
        dir.join("README.md"),
        r#"# Test Book

Welcome to the test book!

This has a [link to chapter 1](chapter1.md).
"#,
    )
    .unwrap();

    // chapter1.md
    fs::write(
        dir.join("chapter1.md"),
        r#"# Chapter 1

This is chapter 1 content.

## Section 1.1

Some details here.

```rust
fn main() {
    println!("Hello, world!");
}
```
"#,
    )
    .unwrap();

    // chapter2/README.md
    fs::create_dir_all(dir.join("chapter2")).unwrap();
    fs::write(
        dir.join("chapter2/README.md"),
        r#"# Chapter 2

Nested chapter content.
"#,
    )
    .unwrap();

    // assets directory with a test file
    fs::create_dir_all(dir.join("assets")).unwrap();
    fs::write(dir.join("assets/test.txt"), "test asset content").unwrap();
}

#[test]
fn test_full_build() {
    let temp = tempdir().unwrap();
    let source = temp.path().join("book");
    let output = temp.path().join("output");
    fs::create_dir_all(&source).unwrap();

    create_test_book(&source);

    let status = Command::new(guidebook_bin())
        .arg("build")
        .arg(source.to_str().unwrap())
        .arg("-o")
        .arg(output.to_str().unwrap())
        .status()
        .expect("Failed to execute guidebook build");

    assert!(status.success(), "Build should succeed");

    // Verify index.html was generated
    let index = output.join("index.html");
    assert!(index.exists(), "index.html should be generated");
    let index_content = fs::read_to_string(&index).unwrap();
    assert!(
        index_content.contains("Test Book"),
        "index.html should contain the book title"
    );

    // Verify chapter1.html was generated
    let ch1 = output.join("chapter1.html");
    assert!(ch1.exists(), "chapter1.html should be generated");
    let ch1_content = fs::read_to_string(&ch1).unwrap();
    assert!(
        ch1_content.contains("Chapter 1"),
        "chapter1.html should contain the chapter title"
    );

    // Verify nested chapter was generated (README.md → README.html)
    let ch2 = output.join("chapter2/README.html");
    assert!(ch2.exists(), "chapter2/README.html should be generated");

    // Verify static assets (gitbook CSS/JS)
    let css = output.join("gitbook/gitbook.css");
    assert!(css.exists(), "gitbook.css should be generated");

    let js = output.join("gitbook/gitbook.js");
    assert!(js.exists(), "gitbook.js should be generated");

    // Verify search index
    let search_index = output.join("search_index.json");
    assert!(
        search_index.exists(),
        "search_index.json should be generated"
    );
    let search_content = fs::read_to_string(&search_index).unwrap();
    let search_json: serde_json::Value = serde_json::from_str(&search_content).unwrap();
    assert!(
        search_json.is_array(),
        "Search index should be a JSON array"
    );
    assert!(
        search_json.as_array().unwrap().len() >= 2,
        "Search index should have entries for chapters"
    );

    // Verify assets were copied
    let asset = output.join("assets/test.txt");
    assert!(
        asset.exists() || output.join("assets").join("test.txt").read_link().is_ok(),
        "Asset file should be copied or symlinked"
    );
}

#[test]
fn test_build_generates_valid_html() {
    let temp = tempdir().unwrap();
    let source = temp.path().join("book");
    let output = temp.path().join("output");
    fs::create_dir_all(&source).unwrap();

    create_test_book(&source);

    let status = Command::new(guidebook_bin())
        .arg("build")
        .arg(source.to_str().unwrap())
        .arg("-o")
        .arg(output.to_str().unwrap())
        .status()
        .expect("Failed to execute guidebook build");

    assert!(status.success());

    // Verify HTML structure
    let index = fs::read_to_string(output.join("index.html")).unwrap();
    assert!(
        index.contains("<!DOCTYPE html>") || index.contains("<!DOCTYPE HTML>"),
        "Should have DOCTYPE declaration"
    );
    assert!(index.contains("<html"), "Should have html tag");
    assert!(index.contains("</html>"), "Should have closing html tag");
    assert!(
        index.contains("<head>") || index.contains("<head "),
        "Should have head tag"
    );
    assert!(index.contains("<body"), "Should have body tag");
    assert!(index.contains("</body>"), "Should have closing body tag");
}

#[test]
fn test_build_with_code_blocks() {
    let temp = tempdir().unwrap();
    let source = temp.path().join("book");
    let output = temp.path().join("output");
    fs::create_dir_all(&source).unwrap();

    create_test_book(&source);

    let status = Command::new(guidebook_bin())
        .arg("build")
        .arg(source.to_str().unwrap())
        .arg("-o")
        .arg(output.to_str().unwrap())
        .status()
        .expect("Failed to execute guidebook build");

    assert!(status.success());

    let ch1 = fs::read_to_string(output.join("chapter1.html")).unwrap();
    // Code blocks should be wrapped in <pre><code>
    assert!(
        ch1.contains("<pre>") || ch1.contains("<code"),
        "Code blocks should be rendered as <pre><code>"
    );
}

#[test]
fn test_init_command() {
    let temp = tempdir().unwrap();
    let book_dir = temp.path().join("new-book");

    let status = Command::new(guidebook_bin())
        .arg("init")
        .arg(book_dir.to_str().unwrap())
        .status()
        .expect("Failed to execute guidebook init");

    assert!(status.success(), "Init should succeed");

    // Verify files were created
    assert!(
        book_dir.join("README.md").exists(),
        "README.md should be created"
    );
    assert!(
        book_dir.join("SUMMARY.md").exists(),
        "SUMMARY.md should be created"
    );
    assert!(
        book_dir.join("book.json").exists(),
        "book.json should be created"
    );

    // Verify the initialized book can be built
    let output = temp.path().join("output");
    let status = Command::new(guidebook_bin())
        .arg("build")
        .arg(book_dir.to_str().unwrap())
        .arg("-o")
        .arg(output.to_str().unwrap())
        .status()
        .expect("Failed to build initialized book");

    assert!(status.success(), "Building initialized book should succeed");
    assert!(
        output.join("index.html").exists(),
        "Built book should have index.html"
    );
}

#[test]
fn test_sidebar_navigation() {
    let temp = tempdir().unwrap();
    let source = temp.path().join("book");
    let output = temp.path().join("output");
    fs::create_dir_all(&source).unwrap();

    create_test_book(&source);

    let status = Command::new(guidebook_bin())
        .arg("build")
        .arg(source.to_str().unwrap())
        .arg("-o")
        .arg(output.to_str().unwrap())
        .status()
        .expect("Failed to execute guidebook build");

    assert!(status.success());

    let index = fs::read_to_string(output.join("index.html")).unwrap();
    // Sidebar should contain links to chapters
    assert!(
        index.contains("chapter1"),
        "Sidebar should link to chapter1"
    );
    assert!(
        index.contains("Chapter 1"),
        "Sidebar should display chapter title"
    );
}

// ── Serve path traversal tests ──

/// Find an available port by binding to port 0 and reading the assigned port.
fn find_available_port() -> u16 {
    std::net::TcpListener::bind("127.0.0.1:0")
        .unwrap()
        .local_addr()
        .unwrap()
        .port()
}

/// Start the serve command on a given port and return the child process
fn start_serve(source: &std::path::Path, port: u16) -> std::process::Child {
    Command::new(guidebook_bin())
        .arg("serve")
        .arg(source.to_str().unwrap())
        .arg("-p")
        .arg(port.to_string())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
        .expect("Failed to start guidebook serve")
}

/// Wait for the serve command to be ready by polling the port
fn wait_for_server(port: u16) -> bool {
    for _ in 0..100 {
        if std::net::TcpStream::connect(format!("127.0.0.1:{}", port)).is_ok() {
            return true;
        }
        std::thread::sleep(std::time::Duration::from_millis(200));
    }
    false
}

#[test]
fn test_serve_rejects_path_traversal() {
    let temp = tempdir().unwrap();
    let source = temp.path().join("book");
    fs::create_dir_all(&source).unwrap();
    create_test_book(&source);

    // Create a secret file outside the book output
    fs::write(temp.path().join("secret.txt"), "TOP SECRET").unwrap();

    let port = find_available_port();
    let mut child = start_serve(&source, port);

    if !wait_for_server(port) {
        child.kill().ok();
        panic!(
            "Server did not start on port {} within 20s — security tests cannot run",
            port
        );
    }

    let client = reqwest::blocking::Client::builder()
        .redirect(reqwest::redirect::Policy::none())
        .build()
        .unwrap();

    // Test various path traversal attempts
    let traversal_paths = vec![
        "/../secret.txt",
        "/..%2Fsecret.txt",
        "/%2e%2e/secret.txt",
        "/%2e%2e%2fsecret.txt",
        "/sub/../../secret.txt",
        "/..\\secret.txt",
    ];

    for path in &traversal_paths {
        let url = format!("http://127.0.0.1:{}{}", port, path);
        match client.get(&url).send() {
            Ok(resp) => {
                let status = resp.status().as_u16();
                let body = resp.text().unwrap_or_default();
                assert!(
                    status == 403 || status == 404,
                    "Path traversal '{}' should be blocked (got {} with body: {})",
                    path,
                    status,
                    &body[..body.len().min(100)]
                );
                assert!(
                    !body.contains("TOP SECRET"),
                    "Path traversal '{}' leaked secret content!",
                    path
                );
            }
            Err(_) => {
                // Connection error is acceptable (server might reject early)
            }
        }
    }

    // Verify normal access still works
    let resp = client
        .get(format!("http://127.0.0.1:{}/", port))
        .send()
        .unwrap();
    assert_eq!(resp.status().as_u16(), 200, "Normal access should work");

    // Also test double-encoded traversal in the same server session
    let url = format!("http://127.0.0.1:{}/..%252F..%252Fetc/passwd", port);
    if let Ok(resp) = client.get(&url).send() {
        let status = resp.status().as_u16();
        assert!(
            status == 403 || status == 404,
            "Double-encoded traversal should be blocked (got {})",
            status
        );
    }

    child.kill().ok();
    child.wait().ok();
}

// ── Multi-language build test ──

/// Create a multi-language book structure for testing
fn create_multilang_book(dir: &std::path::Path) {
    // LANGS.md at root
    fs::write(
        dir.join("LANGS.md"),
        "* [English](en/)\n* [Japanese](ja/)\n",
    )
    .unwrap();

    // book.json
    fs::write(dir.join("book.json"), r#"{"title": "Multi-lang Book"}"#).unwrap();

    // English
    let en = dir.join("en");
    fs::create_dir_all(&en).unwrap();
    fs::write(en.join("README.md"), "# English Intro\nWelcome\n").unwrap();
    fs::write(
        en.join("SUMMARY.md"),
        "# Summary\n\n* [Introduction](README.md)\n* [Chapter 1](ch1.md)\n",
    )
    .unwrap();
    fs::write(en.join("ch1.md"), "# Chapter 1\nEnglish content\n").unwrap();

    // Japanese
    let ja = dir.join("ja");
    fs::create_dir_all(&ja).unwrap();
    fs::write(ja.join("README.md"), "# Japanese Intro\nようこそ\n").unwrap();
    fs::write(
        ja.join("SUMMARY.md"),
        "# Summary\n\n* [Introduction](README.md)\n* [Chapter 1](ch1.md)\n",
    )
    .unwrap();
    fs::write(ja.join("ch1.md"), "# Chapter 1\n日本語コンテンツ\n").unwrap();
}

#[test]
fn test_multilang_build() {
    let temp = tempdir().unwrap();
    let source = temp.path().join("book");
    let output = temp.path().join("output");
    fs::create_dir_all(&source).unwrap();

    create_multilang_book(&source);

    let status = Command::new(guidebook_bin())
        .arg("build")
        .arg(source.to_str().unwrap())
        .arg("-o")
        .arg(output.to_str().unwrap())
        .status()
        .expect("Failed to execute guidebook build");

    assert!(status.success(), "Multi-language build should succeed");

    // Verify language index was generated
    let index = output.join("index.html");
    assert!(
        index.exists(),
        "Root index.html should be generated for language selection"
    );

    // Verify English output
    let en_index = output.join("en/index.html");
    assert!(en_index.exists(), "en/index.html should be generated");
    let en_content = fs::read_to_string(&en_index).unwrap();
    assert!(
        en_content.contains("English Intro") || en_content.contains("Welcome"),
        "English index should contain English content"
    );

    // Verify Japanese output
    let ja_index = output.join("ja/index.html");
    assert!(ja_index.exists(), "ja/index.html should be generated");
    let ja_content = fs::read_to_string(&ja_index).unwrap();
    assert!(
        ja_content.contains("Japanese Intro") || ja_content.contains("ようこそ"),
        "Japanese index should contain Japanese content"
    );

    // Verify chapter pages for both languages
    let en_ch1 = output.join("en/ch1.html");
    assert!(en_ch1.exists(), "en/ch1.html should be generated");

    let ja_ch1 = output.join("ja/ch1.html");
    assert!(ja_ch1.exists(), "ja/ch1.html should be generated");
}