mini-static 0.14.6

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
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
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
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());
}

// The 404 responses for a missing file and for a traversal attempt are covered in
// `http_responses.rs`, which additionally asserts the two are byte-identical.

#[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 = "/caf%C3%A9.txt".to_string();
    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"
    );
}

#[tokio::test]
async fn server_honors_if_none_match_returns_304() {
    let root = TempDir::new().unwrap();
    fs::write(root.path().join("test.txt"), b"file 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);

    // First request to get the ETag
    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"), "first request should return 200, got: {}", response);
    assert!(response.to_lowercase().contains("etag:"), "should have ETag header, got: {}", response);

    // Extract ETag from response (case-insensitive)
    let etag = response
        .lines()
        .find(|line| line.to_lowercase().starts_with("etag:"))
        .and_then(|line| line.split(": ").nth(1))
        .expect("should have ETag header");

    // Second request with If-None-Match matching the ETag
    let mut conn = TcpStream::connect(&addr).await.unwrap();
    let request = format!(
        "GET /test.txt HTTP/1.1\r\nHost: localhost\r\nIf-None-Match: {}\r\nConnection: close\r\n\r\n",
        etag
    );
    conn.write_all(request.as_bytes()).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 304"),
        "matching If-None-Match should return 304, got: {}",
        response
    );
    assert!(!response.contains("file content"), "304 should have no body");

    handle.shutdown().await;
}

#[tokio::test]
async fn server_returns_200_on_if_none_match_mismatch() {
    let root = TempDir::new().unwrap();
    fs::write(root.path().join("test.txt"), b"file 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 with a non-matching If-None-Match
    let mut conn = TcpStream::connect(&addr).await.unwrap();
    conn.write_all(b"GET /test.txt HTTP/1.1\r\nHost: localhost\r\nIf-None-Match: \"wrong-etag\"\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"),
        "non-matching If-None-Match should return 200, got: {}",
        response
    );
    assert!(response.contains("file content"), "200 should have body");

    handle.shutdown().await;
}

#[tokio::test]
async fn no_cache_header_present_on_200_and_304_responses() {
    let root = TempDir::new().unwrap();
    fs::write(root.path().join("test.txt"), b"file 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);

    // First request: plain 200, no conditional headers.
    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"), "expected 200, got: {}", response);
    assert!(
        response.to_lowercase().contains("cache-control: no-cache"),
        "200 response should carry Cache-Control: no-cache, got: {}",
        response
    );

    let etag = response
        .lines()
        .find(|line| line.to_lowercase().starts_with("etag:"))
        .and_then(|line| line.split(": ").nth(1))
        .expect("should have ETag header")
        .to_string();

    // Second request: matching If-None-Match, expect 304 with the same header.
    let mut conn = TcpStream::connect(&addr).await.unwrap();
    let request = format!(
        "GET /test.txt HTTP/1.1\r\nHost: localhost\r\nIf-None-Match: {}\r\nConnection: close\r\n\r\n",
        etag
    );
    conn.write_all(request.as_bytes()).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 304"), "expected 304, got: {}", response);
    assert!(
        response.to_lowercase().contains("cache-control: no-cache"),
        "304 response should carry Cache-Control: no-cache, got: {}",
        response
    );

    handle.shutdown().await;
}

#[tokio::test]
async fn precompressed_sidecar_served_when_accept_encoding_matches() {
    let root = TempDir::new().unwrap();
    fs::write(root.path().join("app.js"), b"console.log('plain');").unwrap();
    fs::write(root.path().join("app.js.gz"), b"gzip-sidecar-bytes").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 with Accept-Encoding: gzip should get the sidecar's bytes.
    let mut conn = TcpStream::connect(&addr).await.unwrap();
    conn.write_all(b"GET /app.js HTTP/1.1\r\nHost: localhost\r\nAccept-Encoding: gzip\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"), "expected 200, got: {}", response);
    assert!(
        response.to_lowercase().contains("content-encoding: gzip"),
        "should carry Content-Encoding: gzip, got: {}",
        response
    );
    assert!(
        response.contains("gzip-sidecar-bytes"),
        "should serve the sidecar's bytes, got: {}",
        response
    );
    assert!(
        !response.contains("console.log('plain');"),
        "should not serve the plain file's bytes when a sidecar is chosen, got: {}",
        response
    );

    // Request with no Accept-Encoding should get the plain file unchanged.
    let mut conn = TcpStream::connect(&addr).await.unwrap();
    conn.write_all(b"GET /app.js 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"), "expected 200, got: {}", response);
    assert!(
        !response.to_lowercase().contains("content-encoding:"),
        "plain request should carry no Content-Encoding, got: {}",
        response
    );
    assert!(
        response.contains("console.log('plain');"),
        "should serve the plain file's bytes unchanged, got: {}",
        response
    );

    handle.shutdown().await;
}

#[tokio::test]
async fn etag_reflects_the_served_sidecar_variant() {
    let root = TempDir::new().unwrap();
    fs::write(root.path().join("app.js"), b"console.log('plain');").unwrap();
    fs::write(root.path().join("app.js.gz"), b"gzip-sidecar-bytes").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);

    // First request for the gzip variant: capture its ETag.
    let mut conn = TcpStream::connect(&addr).await.unwrap();
    conn.write_all(b"GET /app.js HTTP/1.1\r\nHost: localhost\r\nAccept-Encoding: gzip\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);
    let gzip_etag = response
        .lines()
        .find(|line| line.to_lowercase().starts_with("etag:"))
        .and_then(|line| line.split(": ").nth(1))
        .expect("should have ETag header")
        .to_string();

    // Sending that ETag back as If-None-Match with the same Accept-Encoding should 304.
    let mut conn = TcpStream::connect(&addr).await.unwrap();
    let request = format!(
        "GET /app.js HTTP/1.1\r\nHost: localhost\r\nAccept-Encoding: gzip\r\nIf-None-Match: {}\r\nConnection: close\r\n\r\n",
        gzip_etag
    );
    conn.write_all(request.as_bytes()).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 304"),
        "matching gzip-variant ETag should 304, got: {}",
        response
    );

    // The plain (no Accept-Encoding) variant must carry a different ETag.
    let mut conn = TcpStream::connect(&addr).await.unwrap();
    conn.write_all(b"GET /app.js 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);
    let plain_etag = response
        .lines()
        .find(|line| line.to_lowercase().starts_with("etag:"))
        .and_then(|line| line.split(": ").nth(1))
        .expect("should have ETag header")
        .to_string();

    assert_ne!(
        gzip_etag.trim(),
        plain_etag.trim(),
        "gzip and plain variants should have different ETags"
    );

    handle.shutdown().await;
}

async fn get_body(addr: &str, path: &str) -> String {
    let mut conn = TcpStream::connect(addr).await.unwrap();
    let request = format!("GET {path} HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n");
    conn.write_all(request.as_bytes()).await.unwrap();
    let mut response_data = Vec::new();
    conn.read_to_end(&mut response_data).await.unwrap();
    String::from_utf8_lossy(&response_data).into_owned()
}

#[tokio::test]
async fn with_minify_serves_minified_css() {
    let root = TempDir::new().unwrap();
    let source = "body {\n  /* comment */\n  color: red;\n}\n";
    fs::write(root.path().join("app.css"), source).unwrap();

    let server = Server::new(root.path()).unwrap().with_minify();
    let (port, handle) = server.run_ephemeral().await.unwrap();
    tokio::time::sleep(Duration::from_millis(10)).await;
    let addr = format!("127.0.0.1:{}", port);

    let response = get_body(&addr, "/app.css").await;
    assert!(response.contains("HTTP/1.1 200"), "expected 200, got: {}", response);
    assert!(!response.contains("comment"), "comment should be minified out, got: {}", response);
    assert!(
        !response.contains("  color"),
        "redundant whitespace should be minified out, got: {}",
        response
    );

    handle.shutdown().await;
}

#[tokio::test]
async fn head_content_length_matches_minified_get_body_length() {
    let root = TempDir::new().unwrap();
    // Enough redundant whitespace/comment that the minified size differs from disk.
    let source = "body {\n  /* comment */\n  color: red;\n}\n";
    fs::write(root.path().join("app.css"), source).unwrap();

    let server = Server::new(root.path()).unwrap().with_minify();
    let (port, handle) = server.run_ephemeral().await.unwrap();
    tokio::time::sleep(Duration::from_millis(10)).await;
    let addr = format!("127.0.0.1:{}", port);

    // GET first: establishes the minified size and populates the cache.
    let mut conn = TcpStream::connect(&addr).await.unwrap();
    conn.write_all(b"GET /app.css HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n")
        .await
        .unwrap();
    let mut get_response = Vec::new();
    conn.read_to_end(&mut get_response).await.unwrap();
    let get_response = String::from_utf8_lossy(&get_response);
    let get_content_length: usize = get_response
        .lines()
        .find(|line| line.to_lowercase().starts_with("content-length:"))
        .and_then(|line| line.split(':').nth(1))
        .and_then(|v| v.trim().parse().ok())
        .expect("GET response must have a Content-Length header");

    assert!(
        get_content_length < source.len(),
        "sanity check: minified content-length ({get_content_length}) should be smaller than the source ({} bytes)",
        source.len()
    );

    // HEAD to the same path must report the identical Content-Length — RFC 9110
    // requires HEAD's headers to match what GET would send, not the unminified
    // on-disk size.
    let mut conn = TcpStream::connect(&addr).await.unwrap();
    conn.write_all(b"HEAD /app.css HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n")
        .await
        .unwrap();
    let mut head_response = Vec::new();
    conn.read_to_end(&mut head_response).await.unwrap();
    let head_response = String::from_utf8_lossy(&head_response);
    let head_content_length: usize = head_response
        .lines()
        .find(|line| line.to_lowercase().starts_with("content-length:"))
        .and_then(|line| line.split(':').nth(1))
        .and_then(|v| v.trim().parse().ok())
        .expect("HEAD response must have a Content-Length header");

    assert_eq!(
        head_content_length, get_content_length,
        "HEAD's Content-Length must match what GET actually sends, not the on-disk size"
    );

    handle.shutdown().await;
}

#[tokio::test]
async fn minify_disabled_by_default_serves_unminified() {
    let root = TempDir::new().unwrap();
    let source = "body {\n  /* comment */\n  color: red;\n}\n";
    fs::write(root.path().join("app.css"), source).unwrap();

    // No `.with_minify()` call.
    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);

    let response = get_body(&addr, "/app.css").await;
    assert!(response.contains("HTTP/1.1 200"), "expected 200, got: {}", response);
    assert!(response.contains(source), "bytes must be byte-identical to disk when minify is off");

    handle.shutdown().await;
}

#[tokio::test]
async fn with_minify_bypasses_already_minified_files() {
    let root = TempDir::new().unwrap();
    let already_minified = "body{color:red}/* not really minified, just named .min.css */";
    fs::write(root.path().join("app.min.css"), already_minified).unwrap();

    let server = Server::new(root.path()).unwrap().with_minify();
    let (port, handle) = server.run_ephemeral().await.unwrap();
    tokio::time::sleep(Duration::from_millis(10)).await;
    let addr = format!("127.0.0.1:{}", port);

    let response = get_body(&addr, "/app.min.css").await;
    assert!(response.contains("HTTP/1.1 200"), "expected 200, got: {}", response);
    assert!(
        response.contains(already_minified),
        "*.min.css must be served byte-identical, not re-minified, got: {}",
        response
    );

    handle.shutdown().await;
}

#[tokio::test]
async fn precompressed_sidecar_takes_priority_over_minification() {
    let root = TempDir::new().unwrap();
    fs::write(root.path().join("app.js"), "function  f( ) {  return 1;  }").unwrap();
    fs::write(root.path().join("app.js.gz"), "gzip-sidecar-bytes").unwrap();

    let server = Server::new(root.path()).unwrap().with_minify();
    let (port, handle) = server.run_ephemeral().await.unwrap();
    tokio::time::sleep(Duration::from_millis(10)).await;
    let addr = format!("127.0.0.1:{}", port);

    let mut conn = TcpStream::connect(&addr).await.unwrap();
    conn.write_all(b"GET /app.js HTTP/1.1\r\nHost: localhost\r\nAccept-Encoding: gzip\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"), "expected 200, got: {}", response);
    assert!(
        response.contains("gzip-sidecar-bytes"),
        "sidecar bytes should win over minification, got: {}",
        response
    );

    handle.shutdown().await;
}

#[tokio::test]
async fn enabling_minify_invalidates_a_previously_cached_etag() {
    let root = TempDir::new().unwrap();
    let source = "body {\n  /* comment */\n  color: red;\n}\n";
    fs::write(root.path().join("app.css"), source).unwrap();

    // Simulates a client that already cached this file *before* the server ever
    // enabled minification (e.g. an already-deployed site turning the feature on).
    let unminified_server = Server::new(root.path()).unwrap();
    let (port, handle) = unminified_server.run_ephemeral().await.unwrap();
    tokio::time::sleep(Duration::from_millis(10)).await;
    let addr = format!("127.0.0.1:{}", port);

    let response = get_body(&addr, "/app.css").await;
    let stale_etag = response
        .lines()
        .find(|line| line.to_lowercase().starts_with("etag:"))
        .and_then(|line| line.split(": ").nth(1))
        .expect("should have ETag header")
        .trim()
        .to_string();
    handle.shutdown().await;

    // Same file, same mtime, minification now enabled — as if the file hasn't
    // changed but the server's configuration has.
    let minified_server = Server::new(root.path()).unwrap().with_minify();
    let (port, handle) = minified_server.run_ephemeral().await.unwrap();
    tokio::time::sleep(Duration::from_millis(10)).await;
    let addr = format!("127.0.0.1:{}", port);

    let mut conn = TcpStream::connect(&addr).await.unwrap();
    let request = format!(
        "GET /app.css HTTP/1.1\r\nHost: localhost\r\nIf-None-Match: {}\r\nConnection: close\r\n\r\n",
        stale_etag
    );
    conn.write_all(request.as_bytes()).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"),
        "the pre-minification ETag must not match post-minification — a 304 here would \
         mean the client keeps serving its stale unminified cached copy forever, got: {}",
        response
    );
    assert!(!response.contains("comment"), "the fresh 200 must actually be minified, got: {}", response);

    handle.shutdown().await;
}