fastapi-core 0.3.0

Core types and traits for the FastAPI Rust framework
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
904
905
906
907
908
909
910
911
912
913
//! Static file serving for fastapi_rust.
//!
//! This module provides utilities for serving static files from directories.
//! It includes security measures, caching support, and various configuration options.
//!
//! # Features
//!
//! - Directory mounting at path prefix
//! - Index file support (index.html by default)
//! - Content-Type detection from file extension
//! - ETag generation for caching
//! - Last-Modified headers
//! - Optional directory listing
//! - Symlink handling (configurable)
//! - Path traversal prevention
//! - Hidden file exclusion
//!
//! # Example
//!
//! ```ignore
//! use fastapi_core::static_files::{StaticFiles, StaticFilesConfig};
//!
//! // Basic usage - serve ./public at /static
//! let static_handler = StaticFiles::new("./public")
//!     .prefix("/static");
//!
//! // Advanced configuration
//! let static_handler = StaticFiles::with_config(StaticFilesConfig {
//!     directory: "./assets".into(),
//!     prefix: "/assets".into(),
//!     index_files: vec!["index.html".into(), "index.htm".into()],
//!     show_hidden: false,
//!     follow_symlinks: false,
//!     enable_etag: true,
//!     enable_last_modified: true,
//!     directory_listing: false,
//!     ..Default::default()
//! });
//! ```
//!
//! # Security
//!
//! This module implements several security measures:
//!
//! - **Path traversal prevention**: Requests containing `..` or attempting to
//!   escape the root directory are rejected with 403 Forbidden.
//! - **Hidden file exclusion**: Files starting with `.` are not served by default.
//! - **Symlink protection**: Symlinks are not followed by default to prevent
//!   serving files outside the intended directory.

use std::path::{Path, PathBuf};
use std::time::SystemTime;

use crate::response::{Response, ResponseBody, StatusCode, mime_type_for_extension};

/// Configuration for static file serving.
#[derive(Debug, Clone)]
#[allow(clippy::struct_excessive_bools)]
pub struct StaticFilesConfig {
    /// Root directory to serve files from.
    pub directory: PathBuf,
    /// URL path prefix (e.g., "/static").
    pub prefix: String,
    /// Index files to look for in directories.
    pub index_files: Vec<String>,
    /// Whether to serve hidden files (starting with `.`).
    pub show_hidden: bool,
    /// Whether to follow symlinks.
    pub follow_symlinks: bool,
    /// Whether to generate ETag headers.
    pub enable_etag: bool,
    /// Whether to add Last-Modified headers.
    pub enable_last_modified: bool,
    /// Whether to enable directory listing.
    pub directory_listing: bool,
    /// Custom 404 page path (relative to directory).
    pub not_found_page: Option<String>,
    /// Additional headers to add to all responses.
    pub extra_headers: Vec<(String, String)>,
}

impl Default for StaticFilesConfig {
    fn default() -> Self {
        Self {
            directory: PathBuf::from("."),
            prefix: String::new(),
            index_files: vec!["index.html".to_string()],
            show_hidden: false,
            follow_symlinks: false,
            enable_etag: true,
            enable_last_modified: true,
            directory_listing: false,
            not_found_page: None,
            extra_headers: Vec::new(),
        }
    }
}

impl StaticFilesConfig {
    /// Create a new configuration with the given directory.
    #[must_use]
    pub fn new(directory: impl Into<PathBuf>) -> Self {
        Self {
            directory: directory.into(),
            ..Default::default()
        }
    }

    /// Set the URL path prefix.
    #[must_use]
    pub fn prefix(mut self, prefix: impl Into<String>) -> Self {
        self.prefix = prefix.into();
        self
    }

    /// Set the index files to look for.
    #[must_use]
    pub fn index_files(mut self, files: Vec<String>) -> Self {
        self.index_files = files;
        self
    }

    /// Enable or disable showing hidden files.
    #[must_use]
    pub fn show_hidden(mut self, show: bool) -> Self {
        self.show_hidden = show;
        self
    }

    /// Enable or disable following symlinks.
    #[must_use]
    pub fn follow_symlinks(mut self, follow: bool) -> Self {
        self.follow_symlinks = follow;
        self
    }

    /// Enable or disable ETag generation.
    #[must_use]
    pub fn enable_etag(mut self, enable: bool) -> Self {
        self.enable_etag = enable;
        self
    }

    /// Enable or disable Last-Modified headers.
    #[must_use]
    pub fn enable_last_modified(mut self, enable: bool) -> Self {
        self.enable_last_modified = enable;
        self
    }

    /// Enable or disable directory listing.
    #[must_use]
    pub fn directory_listing(mut self, enable: bool) -> Self {
        self.directory_listing = enable;
        self
    }

    /// Set a custom 404 page.
    #[must_use]
    pub fn not_found_page(mut self, page: impl Into<String>) -> Self {
        self.not_found_page = Some(page.into());
        self
    }

    /// Add an extra header to all responses.
    #[must_use]
    pub fn header(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
        self.extra_headers.push((name.into(), value.into()));
        self
    }
}

/// Static file server.
///
/// Serves files from a directory with various security and caching features.
///
/// # Example
///
/// ```ignore
/// use fastapi_core::static_files::StaticFiles;
///
/// let handler = StaticFiles::new("./public")
///     .prefix("/static")
///     .index_file("index.html");
/// ```
#[derive(Debug, Clone)]
pub struct StaticFiles {
    config: StaticFilesConfig,
}

impl StaticFiles {
    /// Create a new static file server for the given directory.
    #[must_use]
    pub fn new(directory: impl Into<PathBuf>) -> Self {
        Self {
            config: StaticFilesConfig::new(directory),
        }
    }

    /// Create a static file server with full configuration.
    #[must_use]
    pub fn with_config(config: StaticFilesConfig) -> Self {
        Self { config }
    }

    /// Set the URL path prefix.
    #[must_use]
    pub fn prefix(mut self, prefix: impl Into<String>) -> Self {
        self.config.prefix = prefix.into();
        self
    }

    /// Set the index file to look for in directories.
    #[must_use]
    pub fn index_file(mut self, file: impl Into<String>) -> Self {
        self.config.index_files = vec![file.into()];
        self
    }

    /// Enable directory listing.
    #[must_use]
    pub fn enable_directory_listing(mut self) -> Self {
        self.config.directory_listing = true;
        self
    }

    /// Enable following symlinks.
    #[must_use]
    pub fn follow_symlinks(mut self) -> Self {
        self.config.follow_symlinks = true;
        self
    }

    /// Serve a request for a static file.
    ///
    /// # Arguments
    ///
    /// * `request_path` - The URL path of the request (e.g., "/static/css/style.css")
    ///
    /// # Returns
    ///
    /// A response containing the file contents, or an error response (404, 403, etc.)
    pub fn serve(&self, request_path: &str) -> Response {
        // Strip prefix from path
        let path_without_prefix = self.strip_prefix(request_path);

        // Security: prevent path traversal
        if !is_safe_path(path_without_prefix) {
            return Response::with_status(StatusCode::FORBIDDEN)
                .header("content-type", b"text/plain".to_vec())
                .body(ResponseBody::Bytes(b"Forbidden: Invalid path".to_vec()));
        }

        // Build the full file path
        let file_path = self
            .config
            .directory
            .join(path_without_prefix.trim_start_matches('/'));

        // Canonicalize to resolve any remaining path tricks
        let Some(canonical_path) = self.resolve_path(&file_path) else {
            return self.not_found_response();
        };

        // Ensure the resolved path is within our directory
        let Ok(canonical_dir) = self.config.directory.canonicalize() else {
            return self.not_found_response();
        };

        if !canonical_path.starts_with(&canonical_dir) {
            return Response::with_status(StatusCode::FORBIDDEN)
                .header("content-type", b"text/plain".to_vec())
                .body(ResponseBody::Bytes(
                    b"Forbidden: Path traversal detected".to_vec(),
                ));
        }

        // Check for hidden path components before serving
        if !self.config.show_hidden && has_hidden_component(&canonical_path) {
            return self.not_found_response();
        }

        // Check if it's a directory
        if canonical_path.is_dir() {
            return self.serve_directory(&canonical_path, request_path);
        }

        // Serve the file
        self.serve_file(&canonical_path)
    }

    /// Strip the URL prefix from the request path.
    fn strip_prefix<'a>(&self, path: &'a str) -> &'a str {
        if self.config.prefix.is_empty() {
            return path;
        }

        path.strip_prefix(&self.config.prefix).unwrap_or(path)
    }

    /// Resolve the file path, handling symlinks according to config.
    fn resolve_path(&self, path: &Path) -> Option<PathBuf> {
        if self.config.follow_symlinks {
            // Follow symlinks - use canonicalize which resolves all symlinks
            path.canonicalize().ok()
        } else {
            // Don't follow symlinks - check each path component
            if !path.exists() {
                return None;
            }

            // Walk from the root directory to the target, checking for symlinks
            let canonical_dir = self.config.directory.canonicalize().ok()?;
            let relative_path = path.strip_prefix(&self.config.directory).ok()?;

            let mut current = canonical_dir.clone();
            for component in relative_path.components() {
                current.push(component);

                // Check if this component is a symlink
                let metadata = std::fs::symlink_metadata(&current).ok()?;
                if metadata.file_type().is_symlink() {
                    return None; // Reject any symlink in the path
                }
            }

            // Return the built path (without following symlinks)
            Some(current)
        }
    }

    /// Serve a directory (index file or listing).
    fn serve_directory(&self, dir_path: &Path, request_path: &str) -> Response {
        // Try index files
        for index_file in &self.config.index_files {
            // Security: validate index file path to prevent traversal
            if !is_safe_path(index_file) {
                continue;
            }
            let index_path = dir_path.join(index_file);
            // Verify the resolved path is still within the directory
            if let Ok(canonical) = index_path.canonicalize() {
                if !canonical.starts_with(dir_path) {
                    continue;
                }
                if canonical.is_file() {
                    return self.serve_file(&canonical);
                }
            }
        }

        // Directory listing if enabled
        if self.config.directory_listing {
            return self.generate_directory_listing(dir_path, request_path);
        }

        // No index file and no listing - return 404
        self.not_found_response()
    }

    /// Serve a single file.
    fn serve_file(&self, file_path: &Path) -> Response {
        // Check for hidden files in any path component (not just the leaf)
        if !self.config.show_hidden && has_hidden_component(file_path) {
            return self.not_found_response();
        }

        // Read file contents
        let Ok(contents) = std::fs::read(file_path) else {
            return self.not_found_response();
        };

        // Get file metadata for caching headers
        let metadata = std::fs::metadata(file_path).ok();

        // Determine content type
        let content_type = file_path
            .extension()
            .and_then(|ext| ext.to_str())
            .map(mime_type_for_extension)
            .unwrap_or("application/octet-stream");

        let mut response = Response::ok()
            .header("content-type", content_type.as_bytes().to_vec())
            .header("accept-ranges", b"bytes".to_vec());

        // Add ETag if enabled
        if self.config.enable_etag {
            let etag = generate_etag(&contents);
            response = response.header("etag", etag.into_bytes());
        }

        // Add Last-Modified if enabled
        if self.config.enable_last_modified {
            if let Some(ref meta) = metadata {
                if let Ok(modified) = meta.modified() {
                    let http_date = format_http_date(modified);
                    response = response.header("last-modified", http_date.into_bytes());
                }
            }
        }

        // Add extra headers
        for (name, value) in &self.config.extra_headers {
            response = response.header(name.clone(), value.clone().into_bytes());
        }

        response.body(ResponseBody::Bytes(contents))
    }

    /// Generate a directory listing HTML page.
    fn generate_directory_listing(&self, dir_path: &Path, request_path: &str) -> Response {
        let mut entries = Vec::new();

        // Add parent directory link if not at root
        if request_path != "/" && request_path != self.config.prefix {
            entries.push(DirectoryEntry {
                name: "..".to_string(),
                is_dir: true,
                size: 0,
                modified: None,
            });
        }

        // Read directory entries
        if let Ok(read_dir) = std::fs::read_dir(dir_path) {
            for entry in read_dir.flatten() {
                let name = entry.file_name().to_string_lossy().to_string();

                // Skip hidden files if not showing them
                if !self.config.show_hidden && name.starts_with('.') {
                    continue;
                }

                if let Ok(metadata) = entry.metadata() {
                    entries.push(DirectoryEntry {
                        name,
                        is_dir: metadata.is_dir(),
                        size: metadata.len(),
                        modified: metadata.modified().ok(),
                    });
                }
            }
        }

        // Sort: directories first, then by name
        entries.sort_by(|a, b| match (a.is_dir, b.is_dir) {
            (true, false) => std::cmp::Ordering::Less,
            (false, true) => std::cmp::Ordering::Greater,
            _ => a.name.cmp(&b.name),
        });

        // Generate HTML
        let html = generate_listing_html(request_path, &entries);

        Response::ok()
            .header("content-type", b"text/html; charset=utf-8".to_vec())
            .body(ResponseBody::Bytes(html.into_bytes()))
    }

    /// Generate a 404 response, optionally using custom page.
    fn not_found_response(&self) -> Response {
        if let Some(ref not_found_path) = self.config.not_found_page {
            // Security: validate path to prevent traversal
            if is_safe_path(not_found_path) {
                let path = self.config.directory.join(not_found_path);
                // Verify the resolved path is within the configured directory
                if let Ok(canonical) = path.canonicalize() {
                    if let Ok(base_canonical) = self.config.directory.canonicalize() {
                        if canonical.starts_with(&base_canonical) {
                            if let Ok(contents) = std::fs::read(&canonical) {
                                let content_type = canonical
                                    .extension()
                                    .and_then(|ext| ext.to_str())
                                    .map(mime_type_for_extension)
                                    .unwrap_or("text/html; charset=utf-8");

                                return Response::with_status(StatusCode::NOT_FOUND)
                                    .header("content-type", content_type.as_bytes().to_vec())
                                    .body(ResponseBody::Bytes(contents));
                            }
                        }
                    }
                }
            }
        }

        Response::with_status(StatusCode::NOT_FOUND)
            .header("content-type", b"text/plain".to_vec())
            .body(ResponseBody::Bytes(b"Not Found".to_vec()))
    }
}

/// Check if any component of a path starts with `.` (hidden file/directory).
fn has_hidden_component(path: &Path) -> bool {
    path.components().any(|c| {
        c.as_os_str()
            .to_str()
            .is_some_and(|s| s.starts_with('.') && s != "." && s != "..")
    })
}

/// Check if a path is safe (no path traversal attempts).
fn is_safe_path(path: &str) -> bool {
    // Reject paths with null bytes
    if path.contains('\0') {
        return false;
    }

    // Decode percent-encoded characters first to catch encoded traversal
    let decoded = percent_decode(path);

    // Reject paths with null bytes in decoded form
    if decoded.contains('\0') {
        return false;
    }

    // Reject paths with .. components (check decoded path)
    for component in decoded.split('/') {
        if component == ".." {
            return false;
        }
    }

    true
}

/// Simple percent-decoding for path safety checks.
///
/// Decodes percent-encoded bytes into a string. Invalid UTF-8 sequences
/// are replaced with the Unicode replacement character.
fn percent_decode(s: &str) -> String {
    let bytes = s.as_bytes();
    let mut decoded_bytes = Vec::with_capacity(bytes.len());
    let mut i = 0;

    while i < bytes.len() {
        if bytes[i] == b'%' && i + 2 < bytes.len() {
            let hi = hex_val(bytes[i + 1]);
            let lo = hex_val(bytes[i + 2]);
            if let (Some(h), Some(l)) = (hi, lo) {
                decoded_bytes.push((h << 4) | l);
                i += 3;
                continue;
            }
        }
        decoded_bytes.push(bytes[i]);
        i += 1;
    }

    String::from_utf8_lossy(&decoded_bytes).into_owned()
}

fn hex_val(b: u8) -> Option<u8> {
    match b {
        b'0'..=b'9' => Some(b - b'0'),
        b'a'..=b'f' => Some(b - b'a' + 10),
        b'A'..=b'F' => Some(b - b'A' + 10),
        _ => None,
    }
}

/// Generate an ETag from file contents using FNV-1a hash.
fn generate_etag(contents: &[u8]) -> String {
    const FNV_OFFSET_BASIS: u64 = 0xcbf29ce484222325;
    const FNV_PRIME: u64 = 0x100000001b3;

    let mut hash = FNV_OFFSET_BASIS;
    for &byte in contents {
        hash ^= u64::from(byte);
        hash = hash.wrapping_mul(FNV_PRIME);
    }

    format!("\"{:016x}\"", hash)
}

/// Format a SystemTime as an HTTP date (RFC 7231).
fn format_http_date(time: SystemTime) -> String {
    match time.duration_since(std::time::UNIX_EPOCH) {
        Ok(duration) => {
            let secs = duration.as_secs();
            let days = secs / 86400;
            let remaining_secs = secs % 86400;
            let hours = remaining_secs / 3600;
            let minutes = (remaining_secs % 3600) / 60;
            let seconds = remaining_secs % 60;

            let day_of_week = ((days + 4) % 7) as usize;
            let day_names = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];

            let (year, month, day) = days_to_date(days);
            let month_names = [
                "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
            ];

            format!(
                "{}, {:02} {} {} {:02}:{:02}:{:02} GMT",
                day_names[day_of_week],
                day,
                month_names[(month - 1) as usize],
                year,
                hours,
                minutes,
                seconds
            )
        }
        Err(_) => "Thu, 01 Jan 1970 00:00:00 GMT".to_string(),
    }
}

/// Convert days since UNIX epoch to (year, month, day).
fn days_to_date(days: u64) -> (u64, u64, u64) {
    let mut remaining_days = days;
    let mut year = 1970u64;

    loop {
        let days_in_year = if is_leap_year(year) { 366 } else { 365 };
        if remaining_days < days_in_year {
            break;
        }
        remaining_days -= days_in_year;
        year += 1;
    }

    let leap = is_leap_year(year);
    let month_days: [u64; 12] = if leap {
        [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
    } else {
        [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
    };

    let mut month = 1u64;
    for &days_in_month in &month_days {
        if remaining_days < days_in_month {
            break;
        }
        remaining_days -= days_in_month;
        month += 1;
    }

    (year, month, remaining_days + 1)
}

/// Check if a year is a leap year.
fn is_leap_year(year: u64) -> bool {
    (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)
}

/// Directory entry for listing.
struct DirectoryEntry {
    name: String,
    is_dir: bool,
    size: u64,
    modified: Option<SystemTime>,
}

/// Generate HTML for directory listing.
fn generate_listing_html(path: &str, entries: &[DirectoryEntry]) -> String {
    let mut html = String::new();

    html.push_str("<!DOCTYPE html>\n<html>\n<head>\n");
    html.push_str("<meta charset=\"utf-8\">\n");
    html.push_str(&format!("<title>Index of {}</title>\n", escape_html(path)));
    html.push_str("<style>\n");
    html.push_str("body { font-family: monospace; margin: 20px; }\n");
    html.push_str("h1 { border-bottom: 1px solid #ccc; padding-bottom: 10px; }\n");
    html.push_str("table { border-collapse: collapse; width: 100%; }\n");
    html.push_str("th, td { text-align: left; padding: 8px; border-bottom: 1px solid #eee; }\n");
    html.push_str("th { background: #f5f5f5; }\n");
    html.push_str("a { text-decoration: none; color: #0066cc; }\n");
    html.push_str("a:hover { text-decoration: underline; }\n");
    html.push_str(".dir { font-weight: bold; }\n");
    html.push_str(".size { text-align: right; }\n");
    html.push_str("</style>\n");
    html.push_str("</head>\n<body>\n");

    html.push_str(&format!("<h1>Index of {}</h1>\n", escape_html(path)));
    html.push_str("<table>\n");
    html.push_str("<tr><th>Name</th><th>Size</th><th>Modified</th></tr>\n");

    for entry in entries {
        let href = if entry.name == ".." {
            parent_path(path)
        } else if entry.is_dir {
            format!("{}/{}/", path.trim_end_matches('/'), &entry.name)
        } else {
            format!("{}/{}", path.trim_end_matches('/'), &entry.name)
        };

        let class = if entry.is_dir { " class=\"dir\"" } else { "" };
        let display_name = if entry.is_dir {
            format!("{}/", &entry.name)
        } else {
            entry.name.clone()
        };

        let size_str = if entry.is_dir {
            "-".to_string()
        } else {
            format_size(entry.size)
        };

        let modified_str = entry
            .modified
            .map(|t| format_http_date(t))
            .unwrap_or_else(|| "-".to_string());

        html.push_str(&format!(
            "<tr><td{}><a href=\"{}\">{}</a></td><td class=\"size\">{}</td><td>{}</td></tr>\n",
            class,
            escape_html(&href),
            escape_html(&display_name),
            size_str,
            modified_str
        ));
    }

    html.push_str("</table>\n");
    html.push_str("<hr>\n<p>fastapi_rust static file server</p>\n");
    html.push_str("</body>\n</html>");

    html
}

/// Get the parent path.
fn parent_path(path: &str) -> String {
    let trimmed = path.trim_end_matches('/');
    match trimmed.rfind('/') {
        Some(pos) if pos > 0 => format!("{}/", &trimmed[..pos]),
        _ => "/".to_string(),
    }
}

/// Escape HTML special characters.
fn escape_html(s: &str) -> String {
    s.replace('&', "&amp;")
        .replace('<', "&lt;")
        .replace('>', "&gt;")
        .replace('"', "&quot;")
}

/// Format file size for display.
#[allow(clippy::cast_precision_loss)]
fn format_size(size: u64) -> String {
    const KB: u64 = 1024;
    const MB: u64 = 1024 * KB;
    const GB: u64 = 1024 * MB;

    if size >= GB {
        format!("{:.1}G", size as f64 / GB as f64)
    } else if size >= MB {
        format!("{:.1}M", size as f64 / MB as f64)
    } else if size >= KB {
        format!("{:.1}K", size as f64 / KB as f64)
    } else {
        format!("{}", size)
    }
}

// ============================================================================
// Tests
// ============================================================================

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn safe_path_normal() {
        assert!(is_safe_path("/static/css/style.css"));
        assert!(is_safe_path("/images/logo.png"));
        assert!(is_safe_path("/"));
        assert!(is_safe_path(""));
    }

    #[test]
    fn safe_path_traversal_blocked() {
        assert!(!is_safe_path("/../etc/passwd"));
        assert!(!is_safe_path("/static/../../../etc/passwd"));
        assert!(!is_safe_path(".."));
        assert!(!is_safe_path("/.."));
    }

    #[test]
    fn safe_path_encoded_traversal_blocked() {
        assert!(!is_safe_path("/%2e%2e/etc/passwd"));
        assert!(!is_safe_path("/static/%2e%2e/%2e%2e/etc/passwd"));
    }

    #[test]
    fn safe_path_allows_double_dots_in_filename() {
        // Legitimate filenames with double dots should be allowed
        assert!(is_safe_path("/files/test..data.txt"));
        assert!(is_safe_path("/files/archive..tar.gz"));
        assert!(is_safe_path("/files/version..1.2.txt"));
    }

    #[test]
    fn safe_path_null_byte_blocked() {
        assert!(!is_safe_path("/static/file\0.txt"));
    }

    #[test]
    fn percent_decode_works() {
        assert_eq!(percent_decode("%2e%2e"), "..");
        assert_eq!(percent_decode("%2F"), "/");
        assert_eq!(percent_decode("hello%20world"), "hello world");
        assert_eq!(percent_decode("normal"), "normal");
    }

    #[test]
    fn etag_generation() {
        let contents = b"Hello, World!";
        let etag = generate_etag(contents);
        assert!(etag.starts_with('"'));
        assert!(etag.ends_with('"'));
        assert_eq!(etag.len(), 18); // 16 hex chars + 2 quotes
    }

    #[test]
    fn etag_deterministic() {
        let contents = b"test data";
        let etag1 = generate_etag(contents);
        let etag2 = generate_etag(contents);
        assert_eq!(etag1, etag2);
    }

    #[test]
    fn etag_different_for_different_content() {
        let etag1 = generate_etag(b"content 1");
        let etag2 = generate_etag(b"content 2");
        assert_ne!(etag1, etag2);
    }

    #[test]
    fn format_size_bytes() {
        assert_eq!(format_size(0), "0");
        assert_eq!(format_size(100), "100");
        assert_eq!(format_size(1023), "1023");
    }

    #[test]
    fn format_size_kb() {
        assert_eq!(format_size(1024), "1.0K");
        assert_eq!(format_size(2048), "2.0K");
        assert_eq!(format_size(1536), "1.5K");
    }

    #[test]
    fn format_size_mb() {
        assert_eq!(format_size(1024 * 1024), "1.0M");
        assert_eq!(format_size(5 * 1024 * 1024), "5.0M");
    }

    #[test]
    fn format_size_gb() {
        assert_eq!(format_size(1024 * 1024 * 1024), "1.0G");
        assert_eq!(format_size(2 * 1024 * 1024 * 1024), "2.0G");
    }

    #[test]
    fn escape_html_special_chars() {
        assert_eq!(escape_html("<script>"), "&lt;script&gt;");
        assert_eq!(escape_html("a & b"), "a &amp; b");
        assert_eq!(escape_html("\"quoted\""), "&quot;quoted&quot;");
    }

    #[test]
    fn parent_path_normal() {
        assert_eq!(parent_path("/static/css/"), "/static/");
        assert_eq!(parent_path("/static/"), "/");
        assert_eq!(parent_path("/"), "/");
    }

    #[test]
    fn config_builder() {
        let config = StaticFilesConfig::new("./public")
            .prefix("/static")
            .show_hidden(false)
            .directory_listing(true);

        assert_eq!(config.directory, PathBuf::from("./public"));
        assert_eq!(config.prefix, "/static");
        assert!(!config.show_hidden);
        assert!(config.directory_listing);
    }

    #[test]
    fn static_files_builder() {
        let handler = StaticFiles::new("./assets")
            .prefix("/assets")
            .index_file("index.htm")
            .enable_directory_listing();

        assert_eq!(handler.config.prefix, "/assets");
        assert_eq!(handler.config.index_files, vec!["index.htm"]);
        assert!(handler.config.directory_listing);
    }

    #[test]
    fn leap_year_detection() {
        assert!(!is_leap_year(1900)); // Divisible by 100 but not 400
        assert!(is_leap_year(2000)); // Divisible by 400
        assert!(is_leap_year(2024)); // Divisible by 4 but not 100
        assert!(!is_leap_year(2023)); // Not divisible by 4
    }

    #[test]
    fn http_date_format() {
        let date = format_http_date(std::time::UNIX_EPOCH);
        assert_eq!(date, "Thu, 01 Jan 1970 00:00:00 GMT");
    }
}