nano-web 1.4.2

Static file server built with Rust with pre-compressed in-memory caching
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
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
use reqwest::StatusCode;
use std::fs;
use std::path::Path;
use tempfile::TempDir;
use tokio::time::{sleep, Duration};

/// Bind to port 0 and let the OS assign a free port, avoiding collisions in parallel test runs.
fn get_free_port() -> u16 {
    std::net::TcpListener::bind("127.0.0.1:0")
        .unwrap()
        .local_addr()
        .unwrap()
        .port()
}

// Helper to create a test server
fn create_test_server(
    temp_dir: &Path,
    port: u16,
    spa_mode: bool,
    dev_mode: bool,
) -> tokio::task::JoinHandle<()> {
    let config = nano_web::server::ServeConfig {
        public_dir: temp_dir.to_path_buf(),
        port,
        dev: dev_mode,
        spa_mode,
        config_prefix: "TEST_".to_string(),
        log_requests: false,
    };

    tokio::spawn(async move {
        nano_web::server::start_server(config).await.unwrap();
    })
}

#[tokio::test]
async fn test_spa_mode_fallback() {
    let temp_dir = TempDir::new().unwrap();
    let temp_path = temp_dir.path();

    // Create index.html
    fs::write(
        temp_path.join("index.html"),
        r#"<html><body><div id="app">SPA App</div></body></html>"#,
    )
    .unwrap();

    let port = get_free_port();
    let _server = create_test_server(temp_path, port, true, false);
    sleep(Duration::from_millis(100)).await;

    // Test that existing routes work
    let response = reqwest::get(format!("http://localhost:{port}/"))
        .await
        .unwrap();
    assert_eq!(response.status(), StatusCode::OK);
    let body = response.text().await.unwrap();
    assert!(body.contains("SPA App"));

    // Test that non-existent routes fallback to index.html (SPA behavior)
    let response = reqwest::get(format!("http://localhost:{port}/nonexistent/route"))
        .await
        .unwrap();
    assert_eq!(response.status(), StatusCode::OK);
    let body = response.text().await.unwrap();
    assert!(body.contains("SPA App")); // Should serve index.html
}

#[tokio::test]
async fn test_non_spa_mode_404() {
    let temp_dir = TempDir::new().unwrap();
    let temp_path = temp_dir.path();

    // Create index.html
    fs::write(
        temp_path.join("index.html"),
        "<html><body>Regular App</body></html>",
    )
    .unwrap();

    let port = get_free_port();
    let _server = create_test_server(temp_path, port, false, false);
    sleep(Duration::from_millis(100)).await;

    // Test that existing routes work
    let response = reqwest::get(format!("http://localhost:{port}/"))
        .await
        .unwrap();
    assert_eq!(response.status(), StatusCode::OK);

    // Test that non-existent routes return 404
    let response = reqwest::get(format!("http://localhost:{port}/nonexistent"))
        .await
        .unwrap();
    assert_eq!(response.status(), StatusCode::NOT_FOUND);
}

#[tokio::test]
async fn test_dev_mode_file_reloading() {
    let temp_dir = TempDir::new().unwrap();
    let temp_path = temp_dir.path();

    // Create initial file
    let test_file = temp_path.join("test.html");
    fs::write(&test_file, "<html><body>Version 1</body></html>").unwrap();

    let port = get_free_port();
    let _server = create_test_server(temp_path, port, false, true);
    sleep(Duration::from_millis(100)).await;

    // Test initial content
    let response = reqwest::get(format!("http://localhost:{port}/test.html"))
        .await
        .unwrap();
    let body = response.text().await.unwrap();
    assert!(body.contains("Version 1"));

    // Update file
    sleep(Duration::from_millis(50)).await; // Ensure different timestamp
    fs::write(&test_file, "<html><body>Version 2</body></html>").unwrap();

    // Test updated content (dev mode should reload)
    sleep(Duration::from_millis(50)).await;
    let response = reqwest::get(format!("http://localhost:{port}/test.html"))
        .await
        .unwrap();
    let body = response.text().await.unwrap();
    assert!(body.contains("Version 2"));
}

#[tokio::test]
#[allow(unsafe_code)]
async fn test_template_rendering() {
    let temp_dir = TempDir::new().unwrap();
    let temp_path = temp_dir.path();

    // SAFETY: single-threaded test context, cleaned up below
    unsafe { std::env::set_var("TEST_API_URL", "http://test.api.com") };

    // Create HTML file with template
    let template_content = r#"
    <html>
    <head>
        <script>
            window.ENV = JSON.parse("{{EscapedJson}}");
            window.API_URL = "{{env.API_URL}}";
        </script>
    </head>
    <body>Config injected</body>
    </html>
    "#;

    fs::write(temp_path.join("index.html"), template_content).unwrap();

    let port = get_free_port();
    let _server = create_test_server(temp_path, port, false, false);
    sleep(Duration::from_millis(100)).await;

    // Test that template is rendered
    let response = reqwest::get(format!("http://localhost:{port}/"))
        .await
        .unwrap();
    let body = response.text().await.unwrap();

    assert!(body.contains("http://test.api.com"));
    assert!(body.contains("window.ENV = JSON.parse"));
    assert!(!body.contains("{{EscapedJson}}")); // Template should be processed

    // SAFETY: single-threaded cleanup
    unsafe { std::env::remove_var("TEST_API_URL") };
}

#[tokio::test]
async fn test_health_endpoint() {
    let temp_dir = TempDir::new().unwrap();
    let temp_path = temp_dir.path();

    let port = get_free_port();
    let _server = create_test_server(temp_path, port, false, false);
    sleep(Duration::from_millis(100)).await;

    let response = reqwest::get(format!("http://localhost:{port}/_health"))
        .await
        .unwrap();
    assert_eq!(response.status(), StatusCode::OK);

    let body = response.text().await.unwrap();
    assert!(body.contains(r#""status":"ok""#));
}

#[tokio::test]
async fn test_compression_headers() {
    let temp_dir = TempDir::new().unwrap();
    let temp_path = temp_dir.path();

    // Create a larger file that should be compressed (needs to be >= 1024 bytes)
    let large_content = "x".repeat(2000);
    fs::write(temp_path.join("large.txt"), &large_content).unwrap();

    let port = get_free_port();
    let _server = create_test_server(temp_path, port, false, false);
    sleep(Duration::from_millis(100)).await;

    // Request with Accept-Encoding
    let client = reqwest::Client::new();
    let response = client
        .get(format!("http://localhost:{port}/large.txt"))
        .header("Accept-Encoding", "gzip, br")
        .send()
        .await
        .unwrap();

    assert_eq!(response.status(), StatusCode::OK);

    // Should have compression headers
    let headers = response.headers();
    assert!(
        headers.contains_key("content-encoding"),
        "Expected content-encoding header for compressed response"
    );
}

#[tokio::test]
async fn test_security_headers() {
    let temp_dir = TempDir::new().unwrap();
    let temp_path = temp_dir.path();

    fs::write(
        temp_path.join("test.html"),
        "<html><body>Test</body></html>",
    )
    .unwrap();

    let port = get_free_port();
    let _server = create_test_server(temp_path, port, false, false);
    sleep(Duration::from_millis(100)).await;

    let response = reqwest::get(format!("http://localhost:{port}/test.html"))
        .await
        .unwrap();
    let headers = response.headers();

    // Check security headers
    assert!(headers.contains_key("x-content-type-options"));
    assert!(headers.contains_key("x-frame-options"));
    assert_eq!(headers.get("x-frame-options").unwrap(), "SAMEORIGIN");
}

#[tokio::test]
async fn test_path_traversal_protection() {
    let temp_dir = TempDir::new().unwrap();
    let temp_path = temp_dir.path();

    fs::write(temp_path.join("safe.txt"), "safe content").unwrap();

    let port = get_free_port();
    let _server = create_test_server(temp_path, port, false, false);
    sleep(Duration::from_millis(100)).await;

    // Test path traversal attempts - hidden files should be blocked (except .well-known)
    let hidden_file_paths = ["/.env", "/.secret"];

    for path in hidden_file_paths {
        let url = format!("http://localhost:{port}{path}");
        let response = reqwest::get(&url).await.unwrap();

        // Should return 400 Bad Request for hidden files
        assert_eq!(response.status(), StatusCode::BAD_REQUEST, "Path: {path}");
    }

    // Test that normal path traversal (which gets normalized by HTTP stack) returns 404
    let normalized_paths = ["/../../../etc/passwd"];
    for path in normalized_paths {
        let url = format!("http://localhost:{port}{path}");
        let response = reqwest::get(&url).await.unwrap();

        // These get normalized by HTTP stack and just return 404 (not found)
        assert_eq!(response.status(), StatusCode::NOT_FOUND, "Path: {path}");
    }

    // Test that .well-known paths are allowed (but return 404 if file doesn't exist)
    let wellknown_paths = [
        "/.well-known/security.txt",
        "/.well-known/acme-challenge/token",
    ];
    for path in wellknown_paths {
        let url = format!("http://localhost:{port}{path}");
        let response = reqwest::get(&url).await.unwrap();

        // Should return 404 (not found) not 400 (bad request) - meaning path validation passed
        assert_eq!(response.status(), StatusCode::NOT_FOUND, "Path: {path}");
    }

    // But safe paths should work
    let response = reqwest::get(format!("http://localhost:{port}/safe.txt"))
        .await
        .unwrap();
    assert_eq!(response.status(), StatusCode::OK);
}

#[tokio::test]
async fn test_non_compressible_with_accept_encoding() {
    let temp_dir = TempDir::new().unwrap();
    let temp_path = temp_dir.path();

    // Create a fake PNG (non-compressible file type)
    let png_header = [0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A];
    fs::write(temp_path.join("image.png"), png_header).unwrap();

    let port = get_free_port();
    let _server = create_test_server(temp_path, port, false, false);
    sleep(Duration::from_millis(100)).await;

    // Request with Accept-Encoding header (like browsers do)
    let client = reqwest::Client::new();
    let response = client
        .get(format!("http://localhost:{port}/image.png"))
        .header("Accept-Encoding", "gzip, deflate, br, zstd")
        .send()
        .await
        .unwrap();

    assert_eq!(
        response.status(),
        StatusCode::OK,
        "Non-compressible file should return 200 even with Accept-Encoding"
    );
    assert_eq!(response.headers().get("content-type").unwrap(), "image/png");
}

#[tokio::test]
async fn test_head_returns_empty_body() {
    let temp_dir = TempDir::new().unwrap();
    let temp_path = temp_dir.path();

    fs::write(
        temp_path.join("test.html"),
        "<html><body>Hello</body></html>",
    )
    .unwrap();

    let port = get_free_port();
    let _server = create_test_server(temp_path, port, false, false);
    sleep(Duration::from_millis(100)).await;

    let client = reqwest::Client::new();
    let response = client
        .head(format!("http://localhost:{port}/test.html"))
        .send()
        .await
        .unwrap();

    assert_eq!(response.status(), StatusCode::OK);
    assert!(response.headers().contains_key("content-type"));
    assert!(response.headers().contains_key("etag"));

    // HEAD should return empty body
    let body = response.text().await.unwrap();
    assert!(body.is_empty());
}

#[tokio::test]
async fn test_etag_304_not_modified() {
    let temp_dir = TempDir::new().unwrap();
    let temp_path = temp_dir.path();

    fs::write(
        temp_path.join("test.html"),
        "<html><body>Cached</body></html>",
    )
    .unwrap();

    let port = get_free_port();
    let _server = create_test_server(temp_path, port, false, false);
    sleep(Duration::from_millis(100)).await;

    // First request to get the ETag
    let response = reqwest::get(format!("http://localhost:{port}/test.html"))
        .await
        .unwrap();
    assert_eq!(response.status(), StatusCode::OK);
    let etag = response
        .headers()
        .get("etag")
        .unwrap()
        .to_str()
        .unwrap()
        .to_string();

    // Second request with If-None-Match should return 304
    let client = reqwest::Client::builder()
        .no_gzip()
        .no_brotli()
        .no_deflate()
        .build()
        .unwrap();
    let response = client
        .get(format!("http://localhost:{port}/test.html"))
        .header("If-None-Match", &etag)
        .send()
        .await
        .unwrap();

    assert_eq!(response.status(), StatusCode::NOT_MODIFIED);
}

#[tokio::test]
async fn test_method_not_allowed() {
    let temp_dir = TempDir::new().unwrap();
    let temp_path = temp_dir.path();

    fs::write(temp_path.join("test.html"), "<html></html>").unwrap();

    let port = get_free_port();
    let _server = create_test_server(temp_path, port, false, false);
    sleep(Duration::from_millis(100)).await;

    let client = reqwest::Client::new();
    let response = client
        .post(format!("http://localhost:{port}/test.html"))
        .send()
        .await
        .unwrap();

    assert_eq!(response.status(), StatusCode::METHOD_NOT_ALLOWED);
}

#[tokio::test]
async fn test_new_security_headers() {
    let temp_dir = TempDir::new().unwrap();
    let temp_path = temp_dir.path();
    fs::write(
        temp_path.join("test.html"),
        "<html><body>Test</body></html>",
    )
    .unwrap();

    let port = get_free_port();
    let _server = create_test_server(temp_path, port, false, false);
    sleep(Duration::from_millis(100)).await;

    let response = reqwest::get(format!("http://localhost:{port}/test.html"))
        .await
        .unwrap();
    let headers = response.headers();

    assert_eq!(
        headers.get("strict-transport-security").unwrap(),
        "max-age=63072000; includeSubDomains"
    );
    assert_eq!(
        headers.get("permissions-policy").unwrap(),
        "camera=(), microphone=(), geolocation=()"
    );
    assert_eq!(headers.get("x-dns-prefetch-control").unwrap(), "off");
}

#[tokio::test]
async fn test_vary_header_on_compressed() {
    let temp_dir = TempDir::new().unwrap();
    let temp_path = temp_dir.path();
    let large_content = "x".repeat(2000);
    fs::write(temp_path.join("large.txt"), &large_content).unwrap();

    let port = get_free_port();
    let _server = create_test_server(temp_path, port, false, false);
    sleep(Duration::from_millis(100)).await;

    let client = reqwest::Client::new();
    let response = client
        .get(format!("http://localhost:{port}/large.txt"))
        .header("Accept-Encoding", "gzip, br")
        .send()
        .await
        .unwrap();

    assert_eq!(response.headers().get("vary").unwrap(), "Accept-Encoding");
}

#[tokio::test]
async fn test_content_length_header() {
    let temp_dir = TempDir::new().unwrap();
    let temp_path = temp_dir.path();
    let content = "Hello, World!";
    fs::write(temp_path.join("hello.txt"), content).unwrap();

    let port = get_free_port();
    let _server = create_test_server(temp_path, port, false, false);
    sleep(Duration::from_millis(100)).await;

    let client = reqwest::Client::builder()
        .no_gzip()
        .no_brotli()
        .no_deflate()
        .build()
        .unwrap();
    let response = client
        .get(format!("http://localhost:{port}/hello.txt"))
        .send()
        .await
        .unwrap();

    assert!(response.headers().contains_key("content-length"));
}

#[tokio::test]
async fn test_cache_control_values() {
    let temp_dir = TempDir::new().unwrap();
    let temp_path = temp_dir.path();
    fs::write(temp_path.join("page.html"), "<html></html>").unwrap();
    fs::write(temp_path.join("style.css"), "body{}").unwrap();
    fs::write(temp_path.join("data.json"), "{}").unwrap();

    let port = get_free_port();
    let _server = create_test_server(temp_path, port, false, false);
    sleep(Duration::from_millis(100)).await;

    // HTML: 15 minutes
    let resp = reqwest::get(format!("http://localhost:{port}/page.html"))
        .await
        .unwrap();
    assert_eq!(
        resp.headers().get("cache-control").unwrap(),
        "public, max-age=900"
    );

    // CSS: 1 year immutable (asset)
    let resp = reqwest::get(format!("http://localhost:{port}/style.css"))
        .await
        .unwrap();
    assert_eq!(
        resp.headers().get("cache-control").unwrap(),
        "public, max-age=31536000, immutable"
    );

    // JSON: 1 hour (other)
    let resp = reqwest::get(format!("http://localhost:{port}/data.json"))
        .await
        .unwrap();
    assert_eq!(
        resp.headers().get("cache-control").unwrap(),
        "public, max-age=3600"
    );
}