mini-static 0.16.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
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
use std::ffi::OsString;
use std::fs;
use std::path::{Path, PathBuf};

use crate::tool;

/// External tools mini-static knows how to invoke for CSS bundling/minification.
///
/// `#[non_exhaustive]` so a future preset (e.g. a second CSS tool) is an additive
/// variant, not a semver-breaking change for downstream `match` expressions.
///
/// # Installation
///
/// mini-static does not install or manage these binaries — only looks them up on
/// `PATH` at server startup and fails loudly if missing (see [`crate::Server::with_css_tool`]).
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CssTool {
    /// <https://lightningcss.dev>, invoked via its separately-installed `lightningcss`
    /// CLI (npm package `lightningcss-cli`) — a different artifact from the Rust
    /// `lightningcss` crate this refactor removes.
    ///
    /// # Trust boundary
    ///
    /// Bundling delegates `@import` resolution entirely to this CLI process, which
    /// resolves imports relative to the file being processed with no root boundary
    /// mini-static can inject. This is an accepted trade-off: CSS source folders are
    /// developer-authored build inputs, not request-time attacker input (unlike the
    /// HTTP path resolver in `resolve.rs`, which stays fully guarded). An `@import`
    /// escaping the intended source tree is a build misconfiguration to catch in
    /// review, not a runtime exploit surface. [`tool::TOOL_TIMEOUT`] is the bound that
    /// replaces the old in-process import-depth/file-count ceilings.
    LightningCss,
    /// Copies the entry file to the output file unchanged. Test-only: lets
    /// orchestration (discovery, concatenation, error handling, `SourcePipeline`
    /// wiring) be exercised against a real subprocess without depending on
    /// `lightningcss` being installed in CI.
    #[cfg(test)]
    TestEcho,
    /// Always fails with `ToolError::NotFound`. Test-only, for exercising the
    /// startup PATH-probe and hard-fail-on-missing-binary paths.
    #[cfg(test)]
    TestMissing,
}

impl CssTool {
    pub(crate) fn binary_name(&self) -> &'static str {
        match self {
            CssTool::LightningCss => "lightningcss",
            #[cfg(test)]
            CssTool::TestEcho => "cp",
            #[cfg(test)]
            CssTool::TestMissing => "definitely-not-a-real-binary-9f3c2a",
        }
    }

    pub(crate) fn install_hint(&self) -> &'static str {
        match self {
            CssTool::LightningCss => {
                "install via `npm install -g lightningcss-cli` (or add it as a project \
                 devDependency and put its bin/ on PATH)"
            }
            #[cfg(test)]
            CssTool::TestEcho | CssTool::TestMissing => "test-only tool, not installable",
        }
    }

    fn args(&self, bundle: bool, minify: bool, entry: &Path, output: &Path) -> Vec<OsString> {
        match self {
            CssTool::LightningCss => {
                let mut args = Vec::new();
                if bundle {
                    args.push(OsString::from("--bundle"));
                }
                if minify {
                    args.push(OsString::from("--minify"));
                }
                args.push(OsString::from("-o"));
                args.push(output.into());
                args.push(entry.into());
                args
            }
            #[cfg(test)]
            CssTool::TestEcho => vec![entry.into(), output.into()],
            #[cfg(test)]
            CssTool::TestMissing => vec![],
        }
    }
}

/// Configuration for [`crate::Server::with_css_tool`]: independent `bundle`/`minify`
/// toggles, all four combinations valid.
#[derive(Debug, Clone)]
pub struct CssOptions {
    bundle: bool,
    minify: bool,
    bundle_output_name: String,
}

impl CssOptions {
    /// Neither bundle nor minify — CSS is copied through unchanged.
    pub fn new() -> Self {
        CssOptions {
            bundle: false,
            minify: false,
            bundle_output_name: "styles.css".to_string(),
        }
    }

    /// Bundle every `.css` under the source folders into a single output file,
    /// resolving `@import` via the configured [`CssTool`].
    pub fn bundle(mut self, bundle: bool) -> Self {
        self.bundle = bundle;
        self
    }

    /// Minify CSS via the configured [`CssTool`].
    pub fn minify(mut self, minify: bool) -> Self {
        self.minify = minify;
        self
    }

    /// Output file name for bundle mode, under the server's output dir (default
    /// `styles.css`). Ignored when `bundle` is `false`.
    pub fn bundle_output_name(mut self, name: impl Into<String>) -> Self {
        self.bundle_output_name = name.into();
        self
    }

    pub(crate) fn is_bundle(&self) -> bool {
        self.bundle
    }

    pub(crate) fn is_minify(&self) -> bool {
        self.minify
    }

    pub(crate) fn output_file_name(&self) -> &str {
        &self.bundle_output_name
    }
}

impl Default for CssOptions {
    fn default() -> Self {
        Self::new()
    }
}

/// Errors from CSS tool orchestration: discovery, subprocess execution, and output
/// writing.
#[derive(Debug)]
pub(crate) enum CssError {
    ReadSource { path: PathBuf, reason: String },
    WriteOutput { path: PathBuf, reason: String },
    NoFilesFound(PathBuf),
    Tool(tool::ToolError),
}

impl std::fmt::Display for CssError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            CssError::ReadSource { path, reason } => {
                write!(f, "failed to read {}: {reason}", path.display())
            }
            CssError::WriteOutput { path, reason } => {
                write!(f, "failed to write {}: {reason}", path.display())
            }
            CssError::NoFilesFound(path) => write!(f, "no CSS files found in {}", path.display()),
            CssError::Tool(e) => write!(f, "{e}"),
        }
    }
}

impl std::error::Error for CssError {}

impl From<tool::ToolError> for CssError {
    fn from(e: tool::ToolError) -> Self {
        CssError::Tool(e)
    }
}

/// Bundle every `.css` file discovered under `source_dirs` into a single file at
/// `output_path`, per `options`. Each discovered file is run through `css_tool`
/// (bundle/minify per `options`) into a scratch file, then concatenated in sorted
/// path order — same shape as the old in-process bundler, just delegated per-file.
///
/// # Errors
///
/// Returns `Err` without touching `output_path` if discovery, any tool invocation, or
/// the final write fails — a broken rebuild leaves the previous good output in place
/// rather than serving a partial or corrupt bundle.
pub(crate) async fn build_css_bundle(
    css_tool: CssTool,
    options: &CssOptions,
    source_dirs: &[PathBuf],
    output_path: &Path,
) -> Result<(), CssError> {
    let css_files = find_css_files(source_dirs)?;
    if css_files.is_empty() {
        let first = source_dirs
            .first()
            .cloned()
            .unwrap_or_else(|| PathBuf::from("."));
        return Err(CssError::NoFilesFound(first));
    }

    let mut combined = Vec::new();
    for (index, file) in css_files.iter().enumerate() {
        if !options.bundle && !options.minify {
            let bytes = fs::read(file).map_err(|e| CssError::ReadSource {
                path: file.clone(),
                reason: e.to_string(),
            })?;
            combined.extend_from_slice(&bytes);
            continue;
        }

        let scratch = scratch_output_path(output_path, index);
        run_tool(css_tool, options.bundle, options.minify, file, &scratch).await?;
        let bytes = fs::read(&scratch).map_err(|e| CssError::ReadSource {
            path: scratch.clone(),
            reason: e.to_string(),
        })?;
        let _ = fs::remove_file(&scratch);
        combined.extend_from_slice(&bytes);
    }

    write_output(output_path, &combined)
}

/// Process a single CSS file (bundle disabled) into its mirrored `output` path.
///
/// A malformed source degrades to a raw copy rather than failing the pipeline — the
/// server must still serve the file and keep the browser in sync. The degradation is
/// logged, not silent.
pub(crate) async fn build_css_file(
    css_tool: CssTool,
    options: &CssOptions,
    source: &Path,
    output: &Path,
) -> Result<(), CssError> {
    if !options.minify || is_already_minified(source) {
        return copy_file(source, output);
    }

    if let Err(e) = run_tool(css_tool, false, true, source, output).await {
        eprintln!(
            "css tool: minify failed for {}, serving raw bytes: {e}",
            source.display()
        );
        return copy_file(source, output);
    }
    Ok(())
}

async fn run_tool(
    css_tool: CssTool,
    bundle: bool,
    minify: bool,
    entry: &Path,
    output: &Path,
) -> Result<(), tool::ToolError> {
    if let Some(parent) = output.parent() {
        let _ = fs::create_dir_all(parent);
    }
    let args = css_tool.args(bundle, minify, entry, output);
    tool::execute(
        css_tool.binary_name(),
        css_tool.install_hint(),
        css_tool.binary_name(),
        &args,
        output,
        tool::TOOL_TIMEOUT,
    )
    .await
}

/// True if `path`'s filename indicates it's already minified (`*.min.css`). Such
/// files should be served as-is — running a minifier on already-minified input is
/// wasted work at best and a correctness risk at worst.
fn is_already_minified(path: &Path) -> bool {
    path.file_name()
        .and_then(|name| name.to_str())
        .is_some_and(|name| name.ends_with(".min.css"))
}

fn scratch_output_path(output_path: &Path, index: usize) -> PathBuf {
    let file_name = output_path
        .file_name()
        .and_then(|n| n.to_str())
        .unwrap_or("output");
    output_path.with_file_name(format!(".{file_name}.{index}.building"))
}

fn write_output(output_path: &Path, bytes: &[u8]) -> Result<(), CssError> {
    if let Some(parent) = output_path.parent() {
        fs::create_dir_all(parent).map_err(|e| CssError::WriteOutput {
            path: output_path.to_path_buf(),
            reason: e.to_string(),
        })?;
    }
    fs::write(output_path, bytes).map_err(|e| CssError::WriteOutput {
        path: output_path.to_path_buf(),
        reason: e.to_string(),
    })
}

fn copy_file(source: &Path, output: &Path) -> Result<(), CssError> {
    if let Some(parent) = output.parent() {
        fs::create_dir_all(parent).map_err(|e| CssError::WriteOutput {
            path: output.to_path_buf(),
            reason: e.to_string(),
        })?;
    }
    fs::copy(source, output).map_err(|e| CssError::WriteOutput {
        path: output.to_path_buf(),
        reason: e.to_string(),
    })?;
    Ok(())
}

/// Find every `.css` file under `source_dirs`, recursively, sorted by path.
fn find_css_files(source_dirs: &[PathBuf]) -> Result<Vec<PathBuf>, CssError> {
    let mut files = Vec::new();
    for dir in source_dirs {
        let found = walk_for_extension(dir, "css").map_err(|e| CssError::ReadSource {
            path: dir.clone(),
            reason: e.to_string(),
        })?;
        files.extend(found);
    }
    files.sort();
    Ok(files)
}

fn walk_for_extension(dir: &Path, ext: &str) -> std::io::Result<Vec<PathBuf>> {
    let mut files = Vec::new();
    let mut dirs = vec![dir.to_path_buf()];

    while let Some(current_dir) = dirs.pop() {
        for entry in fs::read_dir(&current_dir)? {
            let entry = entry?;
            let path = entry.path();
            let file_type = entry.file_type()?;

            if file_type.is_dir() {
                dirs.push(path);
            } else if file_type.is_file() && path.extension().and_then(|s| s.to_str()) == Some(ext)
            {
                files.push(path);
            }
        }
    }

    Ok(files)
}

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

    #[tokio::test]
    async fn bundle_mode_concatenates_discovered_files_in_sorted_order() {
        let src = TempDir::new().unwrap();
        let out = TempDir::new().unwrap();
        let output = out.path().join("styles.css");

        fs::write(src.path().join("a.css"), "A").unwrap();
        fs::write(src.path().join("b.css"), "B").unwrap();

        let options = CssOptions::new().bundle(true).minify(true);
        build_css_bundle(
            CssTool::TestEcho,
            &options,
            &[src.path().to_path_buf()],
            &output,
        )
        .await
        .unwrap();

        let content = fs::read_to_string(&output).unwrap();
        assert_eq!(content, "AB", "files must concatenate in sorted path order");
    }

    #[tokio::test]
    async fn bundle_false_minify_false_is_a_passthrough_copy() {
        let src = TempDir::new().unwrap();
        let out = TempDir::new().unwrap();
        let output = out.path().join("styles.css");

        fs::write(src.path().join("only.css"), "body{color:red}").unwrap();

        let options = CssOptions::new();
        build_css_bundle(
            CssTool::TestMissing,
            &options,
            &[src.path().to_path_buf()],
            &output,
        )
        .await
        .unwrap();

        assert_eq!(fs::read_to_string(&output).unwrap(), "body{color:red}");
    }

    #[tokio::test]
    async fn no_css_files_is_an_error() {
        let src = TempDir::new().unwrap();
        let out = TempDir::new().unwrap();
        let output = out.path().join("styles.css");

        let result = build_css_bundle(
            CssTool::TestEcho,
            &CssOptions::new().bundle(true),
            &[src.path().to_path_buf()],
            &output,
        )
        .await;

        assert!(matches!(result, Err(CssError::NoFilesFound(_))));
    }

    #[tokio::test]
    async fn a_failing_tool_leaves_previous_bundle_output_untouched() {
        let src = TempDir::new().unwrap();
        let out = TempDir::new().unwrap();
        let output = out.path().join("styles.css");
        fs::write(&output, "/* previous good build */").unwrap();
        fs::write(src.path().join("a.css"), "A").unwrap();

        let result = build_css_bundle(
            CssTool::TestMissing,
            &CssOptions::new().bundle(true).minify(true),
            &[src.path().to_path_buf()],
            &output,
        )
        .await;

        assert!(result.is_err());
        assert_eq!(
            fs::read_to_string(&output).unwrap(),
            "/* previous good build */",
            "a failed rebuild must not overwrite the previous good bundle"
        );
    }

    #[tokio::test]
    async fn per_file_mode_with_minify_false_copies_through_unchanged() {
        let src = TempDir::new().unwrap();
        let out = TempDir::new().unwrap();
        let source = src.path().join("app.css");
        let output = out.path().join("app.css");
        fs::write(&source, "body{color:blue}").unwrap();

        build_css_file(CssTool::TestMissing, &CssOptions::new(), &source, &output)
            .await
            .unwrap();

        assert_eq!(fs::read_to_string(&output).unwrap(), "body{color:blue}");
    }

    #[tokio::test]
    async fn per_file_mode_already_minified_skips_the_tool() {
        let src = TempDir::new().unwrap();
        let out = TempDir::new().unwrap();
        let source = src.path().join("app.min.css");
        let output = out.path().join("app.min.css");
        fs::write(&source, "body{color:blue}").unwrap();

        // TestMissing would error if invoked; success proves the tool was skipped.
        build_css_file(
            CssTool::TestMissing,
            &CssOptions::new().minify(true),
            &source,
            &output,
        )
        .await
        .unwrap();

        assert_eq!(fs::read_to_string(&output).unwrap(), "body{color:blue}");
    }

    #[tokio::test]
    async fn per_file_mode_degrades_to_raw_copy_when_the_tool_fails() {
        let src = TempDir::new().unwrap();
        let out = TempDir::new().unwrap();
        let source = src.path().join("app.css");
        let output = out.path().join("app.css");
        fs::write(&source, "body{color:blue}").unwrap();

        build_css_file(
            CssTool::TestMissing,
            &CssOptions::new().minify(true),
            &source,
            &output,
        )
        .await
        .unwrap();

        assert_eq!(
            fs::read_to_string(&output).unwrap(),
            "body{color:blue}",
            "a failing tool must degrade to serving the raw source, not fail the pipeline"
        );
    }
}