mini-static 0.5.0

A secure, async static file server with streaming, traversal protection, and connection limits.
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
use mini_static::Server;
use std::fs;
use std::time::Duration;
use tempfile::TempDir;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::TcpStream;

#[test]
fn server_new_canonicalizes_root() {
    let root = TempDir::new().unwrap();
    let result = Server::new(root.path());
    assert!(
        result.is_ok(),
        "Server::new should succeed with a valid root"
    );
}

#[test]
fn server_new_fails_with_invalid_root() {
    let result = Server::new(std::path::Path::new("/nonexistent/path/that/does/not/exist"));
    assert!(result.is_err(), "Server::new should fail with invalid root");
}

#[test]
fn server_multiple_resolves_without_root_recanonical() {
    let root = TempDir::new().unwrap();
    fs::write(root.path().join("file1.txt"), b"content1").unwrap();
    fs::write(root.path().join("file2.txt"), b"content2").unwrap();

    let server = Server::new(root.path()).unwrap();

    // Multiple resolve calls should all work
    let res1 = server.resolve("/file1.txt");
    let res2 = server.resolve("/file2.txt");
    let res3 = server.resolve("/file1.txt");

    assert!(res1.is_ok());
    assert!(res2.is_ok());
    assert!(res3.is_ok());
}

#[test]
fn server_rejects_traversal_on_multiple_requests() {
    let root = TempDir::new().unwrap();

    let server = Server::new(root.path()).unwrap();

    // Multiple traversal attempts should all be rejected
    let res1 = server.resolve("/../etc/passwd");
    let res2 = server.resolve("/../../etc/passwd");
    let res3 = server.resolve("/../etc/passwd");

    assert!(res1.is_err());
    assert!(res2.is_err());
    assert!(res3.is_err());
}

#[test]
fn server_handle_request_returns_404_for_missing() {
    let root = TempDir::new().unwrap();

    let server = Server::new(root.path()).unwrap();
    let response = server.handle_request("/nonexistent.txt");

    assert_eq!(response.status().as_u16(), 404);
    assert!(response
        .headers()
        .get("X-Content-Type-Options")
        .is_some());
}

#[test]
fn server_handle_request_returns_404_for_traversal() {
    let root = TempDir::new().unwrap();

    let server = Server::new(root.path()).unwrap();
    let response = server.handle_request("/../etc/passwd");

    assert_eq!(response.status().as_u16(), 404);
}

#[test]
fn server_resolve_with_canonical_root_direct() {
    let root = TempDir::new().unwrap();
    let test_file = root.path().join("test.txt");
    fs::write(&test_file, b"content").unwrap();

    let root_canon = root.path().canonicalize().unwrap();
    let result = mini_static::resolve_with_canonical_root(&root_canon, "/test.txt");

    assert!(result.is_ok());
}

#[test]
fn server_multiple_requests_same_effectiveness() {
    let root = TempDir::new().unwrap();
    fs::create_dir(root.path().join("subdir")).unwrap();
    fs::write(root.path().join("subdir/index.html"), b"<html></html>").unwrap();
    fs::write(root.path().join("file.txt"), b"content").unwrap();

    let server = Server::new(root.path()).unwrap();

    // Multiple different types of requests
    let dir_with_index = server.resolve("/subdir");
    let file = server.resolve("/file.txt");
    let missing = server.resolve("/missing.txt");
    let traversal = server.resolve("/../etc/passwd");

    assert!(dir_with_index.is_ok(), "directory with index should resolve");
    assert!(file.is_ok(), "regular file should resolve");
    assert!(missing.is_err(), "missing file should error");
    assert!(traversal.is_err(), "traversal should error");
}

#[tokio::test]
async fn server_header_read_timeout_closes_idle_connection() {
    let root = TempDir::new().unwrap();
    fs::write(root.path().join("test.txt"), b"hello world").unwrap();

    let server = Server::new(root.path()).unwrap();
    let header_timeout = Duration::from_millis(100);
    let (port, _handle) = server.run(header_timeout).await.unwrap();

    // Give the server a moment to start listening
    tokio::time::sleep(Duration::from_millis(10)).await;

    // Connect but send nothing - connection should timeout
    let addr = format!("127.0.0.1:{}", port);
    let mut stream = TcpStream::connect(&addr).await.unwrap();

    // Wait longer than the timeout
    tokio::time::sleep(Duration::from_millis(200)).await;

    // Try to read from the closed connection - should return empty (EOF)
    let mut buf = vec![0u8; 1024];
    match stream.read(&mut buf).await {
        Ok(n) => assert_eq!(n, 0, "read from timed-out connection should return EOF"),
        Err(e) => panic!("read from timed-out connection failed: {}", e),
    }

    // Verify a new connection still works
    let mut new_stream = TcpStream::connect(&addr).await.unwrap();
    new_stream
        .write_all(b"GET /test.txt HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n")
        .await
        .unwrap();

    let mut buf = vec![0u8; 1024];
    let n = new_stream.read(&mut buf).await.unwrap();
    let response = String::from_utf8_lossy(&buf[..n]);

    assert!(
        response.contains("HTTP/1.1 200"),
        "new connection should work and return 200, got: {}",
        response
    );
}

#[tokio::test]
async fn server_run_ephemeral_binds_to_loopback() {
    let root = TempDir::new().unwrap();
    fs::write(root.path().join("index.html"), b"<html>hello</html>").unwrap();

    let server = Server::new(root.path()).unwrap();
    let (port, _handle) = server.run_ephemeral().await.unwrap();

    // Give the server a moment to start listening
    tokio::time::sleep(Duration::from_millis(10)).await;

    // Verify we can connect to 127.0.0.1:port
    let addr = format!("127.0.0.1:{}", port);
    let mut stream = TcpStream::connect(&addr).await.unwrap();

    // Send a valid HTTP request
    stream
        .write_all(b"GET /index.html HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n")
        .await
        .unwrap();

    // Read to EOF rather than a single `read()`: the body now streams as its own
    // frame(s) separate from the header write, so a single `read()` can legitimately
    // return only the headers if the body frame hasn't been flushed yet.
    let mut response_data = Vec::new();
    stream.read_to_end(&mut response_data).await.unwrap();
    let response = String::from_utf8_lossy(&response_data);

    assert!(
        response.contains("HTTP/1.1 200"),
        "run_ephemeral should be accessible on loopback, got: {}",
        response
    );
    assert!(
        response.contains("hello"),
        "response should contain file content, got: {}",
        response
    );
}

#[tokio::test]
async fn server_streams_large_files_efficiently() {
    let root = TempDir::new().unwrap();

    // Create a 1MB test file with predictable content
    let large_content = vec![42u8; 1024 * 1024];
    fs::write(root.path().join("large.bin"), &large_content).unwrap();

    let server = Server::new(root.path()).unwrap();
    let (port, _handle) = server.run_ephemeral().await.unwrap();

    tokio::time::sleep(Duration::from_millis(10)).await;

    // Request the large file
    let addr = format!("127.0.0.1:{}", port);
    let mut stream = TcpStream::connect(&addr).await.unwrap();

    stream
        .write_all(b"GET /large.bin HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n")
        .await
        .unwrap();

    // Read the entire response
    let mut response_data = Vec::new();
    stream.read_to_end(&mut response_data).await.unwrap();

    let response_str = String::from_utf8_lossy(&response_data);

    // Verify the response headers are correct
    let header_part = response_str.split("\r\n\r\n").next().unwrap_or("");
    let headers_lowercase = header_part.to_lowercase();

    assert!(
        response_str.contains("HTTP/1.1 200"),
        "should return 200 OK"
    );
    assert!(
        headers_lowercase.contains("content-length: 1048576"),
        "Content-Length should be exactly 1MB, got headers: {}",
        header_part
    );

    // Verify the file content is correct
    // The body starts after the double CRLF in the headers
    if let Some(body_start) = response_data.windows(4).position(|w| w == b"\r\n\r\n") {
        let body = &response_data[body_start + 4..];
        assert_eq!(
            body.len(),
            1048576,
            "body should be exactly 1MB"
        );
        assert!(
            body.iter().all(|&b| b == 42),
            "file content should be preserved through streaming"
        );
    } else {
        panic!("could not find body separator in response");
    }
}

#[tokio::test]
async fn server_serves_non_ascii_filenames() {
    let root = TempDir::new().unwrap();

    // Create files with non-ASCII characters in their names
    // Using UTF-8 filenames directly (supported on modern filesystems)
    let filename = "café.txt";
    let content = "hello from café";
    fs::write(root.path().join(filename), content).unwrap();

    let server = Server::new(root.path()).unwrap();
    let (port, _handle) = server.run_ephemeral().await.unwrap();

    tokio::time::sleep(Duration::from_millis(10)).await;

    let addr = format!("127.0.0.1:{}", port);

    // Request the file using percent-encoded UTF-8 path
    // "café" in UTF-8 bytes: c3 a9 (for é) encoded as %C3%A9
    // So "café" becomes "caf%C3%A9"
    let encoded_path = format!("/caf%C3%A9.txt");
    let request = format!(
        "GET {} HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n",
        encoded_path
    );

    let mut stream = TcpStream::connect(&addr).await.unwrap();
    stream.write_all(request.as_bytes()).await.unwrap();

    let mut response_data = Vec::new();
    stream.read_to_end(&mut response_data).await.unwrap();
    let response = String::from_utf8_lossy(&response_data);

    assert!(
        response.contains("HTTP/1.1 200"),
        "non-ASCII filename should resolve correctly, got: {}",
        response
    );
    assert!(
        response.contains("hello from café"),
        "response should contain file content with non-ASCII chars"
    );
}

#[tokio::test]
async fn server_non_ascii_filenames_still_block_traversal() {
    let root = TempDir::new().unwrap();
    let subdir = root.path().join("subdir");
    fs::create_dir(&subdir).unwrap();

    // Create a file outside the allowed directory
    fs::write(root.path().join("secret.txt"), b"secret").unwrap();

    // Create a file in the subdirectory
    fs::write(subdir.join("public.txt"), b"public").unwrap();

    let server = Server::new(&subdir).unwrap();
    let (port, _handle) = server.run_ephemeral().await.unwrap();

    tokio::time::sleep(Duration::from_millis(10)).await;

    let addr = format!("127.0.0.1:{}", port);

    // Try to traverse up and access the secret file with various encodings
    // Including percent-encoded "../" sequences
    let traversal_attempts = vec![
        "/../secret.txt",           // Direct traversal
        "/%2E%2E/secret.txt",       // Percent-encoded ".." should still be blocked at segment level
    ];

    for attempt in traversal_attempts {
        let request = format!(
            "GET {} HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n",
            attempt
        );

        let mut stream = TcpStream::connect(&addr).await.unwrap();
        stream.write_all(request.as_bytes()).await.unwrap();

        let mut response_data = Vec::new();
        stream.read_to_end(&mut response_data).await.unwrap();
        let response = String::from_utf8_lossy(&response_data);

        assert!(
            response.contains("HTTP/1.1 404"),
            "traversal attempt {} should return 404, got: {}",
            attempt,
            response
        );
        assert!(
            !response.contains("secret"),
            "traversal attempt {} should not leak file content",
            attempt
        );
    }
}

#[tokio::test]
async fn server_with_max_connections_bounds_concurrent_connections() {
    let root = TempDir::new().unwrap();
    fs::write(root.path().join("test.txt"), b"content").unwrap();

    // With a limit of exactly 1, a second connection's request must wait for the
    // first connection's slot to free up rather than being served concurrently.
    let header_timeout = Duration::from_millis(150);
    let server = Server::new(root.path())
        .unwrap()
        .with_max_connections(1);
    let (port, _handle) = server.run(header_timeout).await.unwrap();

    tokio::time::sleep(Duration::from_millis(10)).await;
    let addr = format!("127.0.0.1:{}", port);

    // Connection A: opens a socket and sends nothing, occupying the single
    // connection slot until header_timeout closes it.
    let _blocking_conn = TcpStream::connect(&addr).await.unwrap();

    // Connection B: sends a real request while A still holds the only slot.
    let mut conn_b = TcpStream::connect(&addr).await.unwrap();
    conn_b
        .write_all(b"GET /test.txt HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n")
        .await
        .unwrap();

    // B must not be served yet: with no connection limit, the accept loop would
    // have spawned B's handler immediately regardless of A. A short read timeout
    // here would fail (return data) if the limit weren't being enforced.
    let mut buf = vec![0u8; 1024];
    let early_read = tokio::time::timeout(Duration::from_millis(60), conn_b.read(&mut buf)).await;
    assert!(
        early_read.is_err(),
        "connection B should still be waiting for a permit while A holds the only slot"
    );

    // Once A's header-read timeout closes it, its permit frees up and B proceeds.
    let n = tokio::time::timeout(Duration::from_millis(500), conn_b.read(&mut buf))
        .await
        .expect("connection B should be served once A's slot frees up")
        .unwrap();
    let response = String::from_utf8_lossy(&buf[..n]);
    assert!(
        response.contains("HTTP/1.1 200"),
        "connection B should succeed after A's slot is released, got: {}",
        response
    );
}

#[tokio::test]
async fn server_shutdown_drains_in_flight_and_stops_accepting() {
    let root = TempDir::new().unwrap();
    fs::write(root.path().join("test.txt"), b"content").unwrap();

    let server = Server::new(root.path()).unwrap();
    let (port, handle) = server.run_ephemeral().await.unwrap();

    tokio::time::sleep(Duration::from_millis(10)).await;
    let addr = format!("127.0.0.1:{}", port);

    // Complete a normal request first, so shutdown() below has nothing genuinely
    // in-flight to race against — the intent here is to verify shutdown() itself
    // completes (rather than hanging) and actually stops the listener, not to
    // reproduce the inherent (and, for a real SIGINT/SIGTERM, vanishingly rare)
    // race between "shutdown fires" and "a brand-new connection is still sitting
    // unaccepted," which `select!`'s fairness makes nondeterministic by design —
    // the same design mini-serve's identical accept/shutdown race has.
    let mut conn = TcpStream::connect(&addr).await.unwrap();
    conn.write_all(b"GET /test.txt HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n")
        .await
        .unwrap();
    let mut response_data = Vec::new();
    conn.read_to_end(&mut response_data).await.unwrap();
    let response = String::from_utf8_lossy(&response_data);
    assert!(
        response.contains("HTTP/1.1 200") && response.contains("content"),
        "request before shutdown should succeed normally, got: {}",
        response
    );

    // shutdown() must actually complete (not hang waiting on something that never
    // resolves) and must stop the accept loop.
    tokio::time::timeout(Duration::from_secs(2), handle.shutdown())
        .await
        .expect("shutdown() should complete promptly, not hang");

    let reconnect = TcpStream::connect(&addr).await;
    assert!(
        reconnect.is_err(),
        "server should stop accepting new connections after shutdown"
    );
}