fob-bundler 0.2.2

Fob bundler - Rolldown-based bundling on top of fob foundation
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
//! Secure file writing utilities for bundle output.
//!
//! This module provides atomic, secure file writing with comprehensive path validation
//! to prevent directory traversal attacks and ensure data integrity during write operations.
//!
//! # Security Features
//!
//! - **Path Validation**: All paths are validated to prevent directory traversal (`..` components)
//! - **Atomic Writes**: Uses temp files + rename for atomic operations
//! - **Automatic Rollback**: If any write fails, all previously written files are deleted
//! - **Directory Creation**: Automatically creates parent directories with `mkdir -p` behavior
//!
//! # Design Rationale
//!
//! ## Why Atomic Writes?
//!
//! When writing multiple files as part of a bundle, we need to ensure that either all files
//! are written successfully or none are written at all. This prevents partial bundle states
//! that could break applications. We achieve this by:
//!
//! 1. Writing to temporary files first (`.tmp` suffix)
//! 2. Tracking all temp files written
//! 3. If all writes succeed, rename temp files to final names atomically
//! 4. If any write fails, delete all temp files and return an error
//!
//! On most file systems, `rename()` is atomic - the file either appears with its full
//! contents or doesn't appear at all. This prevents race conditions and partial reads.
//!
//! ## Why Path Validation?
//!
//! User-controlled file paths are a security vulnerability. Without validation, an attacker
//! could:
//!
//! - Use `../../../etc/passwd` to write to sensitive system files
//! - Use absolute paths to write anywhere on the filesystem
//! - Use symlink attacks to overwrite protected files
//!
//! We prevent this by normalizing all paths and ensuring they're contained within the
//! output directory.

use std::fs;
use std::path::{Path, PathBuf};

use path_clean::PathClean;
use rolldown::BundleOutput;
use rolldown_common::Output;

use crate::{Error, Result};

/// Writes a bundle to disk with security checks and atomic guarantees.
///
/// # Arguments
///
/// * `output` - The bundle output containing assets to write
/// * `dir` - Target directory for output files
/// * `overwrite` - If `true`, overwrites existing files; if `false`, errors on conflicts
///
/// # Returns
///
/// Returns `Ok(())` on success, or an error if:
/// - Path validation fails (directory traversal attempt)
/// - File already exists and `overwrite` is `false`
/// - Any I/O operation fails
///
/// # Atomic Guarantees
///
/// This function provides atomic writes - either all files are written successfully or
/// none are written. If any operation fails, all previously written files are rolled back.
///
/// # Security
///
/// - Validates all paths to prevent directory traversal
/// - Normalizes paths using `path_clean` to resolve `.` and `..` components
/// - Ensures all output paths are within the specified directory
///
/// # Examples
///
/// ```no_run
/// use fob_bundler::output::writer::write_bundle_to;
/// use std::path::Path;
/// # use rolldown::BundleOutput;
/// # use fob_bundler::Result;
///
/// # fn example(output: &BundleOutput) -> Result<()> {
/// // Write bundle, error if files exist
/// write_bundle_to(output, Path::new("dist"), false)?;
///
/// // Force overwrite existing files
/// write_bundle_to(output, Path::new("dist"), true)?;
/// # Ok(())
/// # }
/// ```
pub fn write_bundle_to(output: &BundleOutput, dir: &Path, overwrite: bool) -> Result<()> {
    eprintln!("[DEBUG] write_bundle_to called with dir: {}", dir.display());
    eprintln!("[DEBUG] output.assets.len(): {}", output.assets.len());

    // Validate and normalize the output directory
    let dir = validate_and_normalize_dir(dir)?;
    eprintln!("[DEBUG] Normalized dir: {}", dir.display());

    // Create the output directory if it doesn't exist
    fs::create_dir_all(&dir).map_err(|e| {
        Error::WriteFailure(format!(
            "Failed to create output directory '{}': {}",
            dir.display(),
            e
        ))
    })?;

    // Collect all file operations to perform
    let mut operations = Vec::new();
    eprintln!(
        "[DEBUG] Starting to iterate over {} assets",
        output.assets.len()
    );
    for (idx, output_item) in output.assets.iter().enumerate() {
        eprintln!(
            "[DEBUG] Processing asset[{}]: type={:?}",
            idx,
            std::mem::discriminant(output_item)
        );
        // Only process assets (skip chunks if present)
        if let Output::Asset(asset) = output_item {
            eprintln!("[DEBUG] Found Asset: filename='{}'", asset.filename);
            let filename = asset.filename.as_str();
            let target_path = validate_output_path(&dir, filename)?;
            eprintln!("[DEBUG] Asset target_path: {}", target_path.display());

            // Check if file exists when overwrite is disabled
            if !overwrite && target_path.exists() {
                return Err(Error::OutputExists(format!(
                    "File already exists: '{}'. Use overwrite=true to replace.",
                    target_path.display()
                )));
            }

            operations.push((target_path, asset.source.as_bytes()));
        } else if let Output::Chunk(chunk) = output_item {
            eprintln!(
                "[DEBUG] Found Chunk: filename='{}', code_len={}",
                chunk.filename,
                chunk.code.len()
            );
            let filename = chunk.filename.as_str();
            let target_path = validate_output_path(&dir, filename)?;
            eprintln!("[DEBUG] Chunk target_path: {}", target_path.display());

            // Check if file exists when overwrite is disabled
            if !overwrite && target_path.exists() {
                return Err(Error::OutputExists(format!(
                    "File already exists: '{}'. Use overwrite=true to replace.",
                    target_path.display()
                )));
            }

            operations.push((target_path, chunk.code.as_bytes()));
        } else {
            eprintln!("[DEBUG] WARNING: Unknown output type!");
        }
    }
    eprintln!("[DEBUG] Collected {} operations to write", operations.len());
    for (i, (path, content)) in operations.iter().enumerate() {
        eprintln!(
            "[DEBUG] Operation[{}]: {} ({} bytes)",
            i,
            path.display(),
            content.len()
        );
    }

    // Write all files atomically
    eprintln!(
        "[DEBUG] About to call write_files_atomic with {} operations",
        operations.len()
    );
    write_files_atomic(&operations)?;
    eprintln!("[DEBUG] write_files_atomic completed successfully");

    Ok(())
}

/// Validates and normalizes a directory path.
///
/// This ensures the path is safe to use as an output directory by:
/// - Normalizing the path (resolving `.` and `..`)
/// - Converting to absolute path
/// - Checking for suspicious patterns
fn validate_and_normalize_dir(dir: &Path) -> Result<PathBuf> {
    // Clean the path to resolve . and .. components
    let cleaned = dir.clean();

    // Convert to absolute path
    let absolute = if cleaned.is_absolute() {
        cleaned
    } else {
        std::env::current_dir()
            .map_err(|e| {
                Error::InvalidOutputPath(format!("Failed to get current directory: {}", e))
            })?
            .join(&cleaned)
            .clean()
    };

    Ok(absolute)
}

/// Validates an output path to prevent directory traversal attacks.
///
/// # Security
///
/// This function prevents attacks like:
/// - `../../../etc/passwd` - escaping the output directory
/// - `/etc/passwd` - absolute paths outside output directory
/// - `dir/../../../etc/passwd` - complex traversal patterns
///
/// It works by:
/// 1. Cleaning both the base directory and the filename
/// 2. Joining them together
/// 3. Cleaning the result again to resolve any remaining `..`
/// 4. Checking that the final path is still under the base directory
fn validate_output_path(base_dir: &Path, filename: &str) -> Result<PathBuf> {
    // Reject paths that look suspicious upfront
    if filename.contains('\0') {
        return Err(Error::InvalidOutputPath(
            "Filename contains null byte".to_string(),
        ));
    }

    // On Windows, check for device names
    #[cfg(target_os = "windows")]
    {
        let upper = filename.to_uppercase();
        let device_names = [
            "CON", "PRN", "AUX", "NUL", "COM1", "COM2", "COM3", "COM4", "COM5", "COM6", "COM7",
            "COM8", "COM9", "LPT1", "LPT2", "LPT3", "LPT4", "LPT5", "LPT6", "LPT7", "LPT8", "LPT9",
        ];
        for device in &device_names {
            if upper == *device || upper.starts_with(&format!("{}.", device)) {
                return Err(Error::InvalidOutputPath(format!(
                    "Filename is a reserved device name: {}",
                    filename
                )));
            }
        }
    }

    // Clean the filename path
    let filename_path = Path::new(filename).clean();

    // Join with base directory and clean again
    let full_path = base_dir.join(&filename_path).clean();

    // Ensure the final path is still under base_dir
    // This is the critical security check that prevents directory traversal
    if !full_path.starts_with(base_dir) {
        return Err(Error::InvalidOutputPath(format!(
            "Path '{}' escapes output directory '{}' (resolved to '{}')",
            filename,
            base_dir.display(),
            full_path.display()
        )));
    }

    Ok(full_path)
}

/// Writes multiple files atomically with automatic rollback on failure.
///
/// # Atomic Guarantees
///
/// This function uses a two-phase commit:
/// 1. Write all content to temporary files (`.tmp` suffix)
/// 2. If all writes succeed, rename temp files to final names
/// 3. If any operation fails, delete all temp files
///
/// The `rename()` operation is atomic on most filesystems, so readers will never
/// see partial file contents.
fn write_files_atomic(operations: &[(PathBuf, &[u8])]) -> Result<()> {
    eprintln!(
        "[DEBUG] write_files_atomic: {} operations",
        operations.len()
    );
    let mut temp_files = Vec::new();

    // Phase 1: Write to temporary files
    for (idx, (target_path, content)) in operations.iter().enumerate() {
        eprintln!(
            "[DEBUG] Phase 1[{}/{}]: Writing temp file for {}",
            idx + 1,
            operations.len(),
            target_path.display()
        );
        // Create parent directories if needed
        if let Some(parent) = target_path.parent() {
            fs::create_dir_all(parent).map_err(|e| {
                cleanup_temp_files(&temp_files);
                Error::WriteFailure(format!(
                    "Failed to create directory '{}': {}",
                    parent.display(),
                    e
                ))
            })?;
        }

        // Write to temporary file
        let temp_path = target_path.with_extension("tmp");
        eprintln!(
            "[DEBUG] Writing temp file: {} ({} bytes)",
            temp_path.display(),
            content.len()
        );
        fs::write(&temp_path, content).map_err(|e| {
            eprintln!(
                "[DEBUG] ERROR writing temp file {}: {}",
                temp_path.display(),
                e
            );
            cleanup_temp_files(&temp_files);
            Error::WriteFailure(format!(
                "Failed to write temporary file '{}': {}",
                temp_path.display(),
                e
            ))
        })?;
        eprintln!(
            "[DEBUG] Temp file written successfully: {}",
            temp_path.display()
        );
        temp_files.push((temp_path, target_path.clone()));
    }

    // Phase 2: Rename temp files to final names (atomic operation)
    eprintln!("[DEBUG] Phase 2: Renaming {} temp files", temp_files.len());
    for (idx, (temp_path, target_path)) in temp_files.iter().enumerate() {
        eprintln!(
            "[DEBUG] Renaming[{}/{}]: {} -> {}",
            idx + 1,
            temp_files.len(),
            temp_path.display(),
            target_path.display()
        );
        fs::rename(temp_path, target_path).map_err(|e| {
            eprintln!(
                "[DEBUG] ERROR renaming {} to {}: {}",
                temp_path.display(),
                target_path.display(),
                e
            );
            // On failure, try to clean up temp files
            cleanup_temp_files(&temp_files);
            Error::WriteFailure(format!(
                "Failed to rename '{}' to '{}': {}",
                temp_path.display(),
                target_path.display(),
                e
            ))
        })?;
        eprintln!("[DEBUG] Successfully renamed to: {}", target_path.display());
    }
    eprintln!(
        "[DEBUG] write_files_atomic completed: {} files written",
        operations.len()
    );
    Ok(())
}

/// Cleans up temporary files on error.
///
/// Best-effort cleanup - errors are logged but not propagated since we're
/// already in an error state.
fn cleanup_temp_files(temp_files: &[(PathBuf, PathBuf)]) {
    for (temp_path, _) in temp_files {
        if temp_path.exists() {
            if let Err(e) = fs::remove_file(temp_path) {
                eprintln!(
                    "Warning: Failed to clean up temporary file '{}': {}",
                    temp_path.display(),
                    e
                );
            }
        }
    }
}

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

    #[test]
    fn test_validate_output_path_normal() {
        let base = Path::new("/tmp/output");
        let result = validate_output_path(base, "index.js");
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), Path::new("/tmp/output/index.js"));
    }

    #[test]
    fn test_validate_output_path_nested() {
        let base = Path::new("/tmp/output");
        let result = validate_output_path(base, "dist/bundle.js");
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), Path::new("/tmp/output/dist/bundle.js"));
    }

    #[test]
    fn test_validate_output_path_traversal_simple() {
        let base = Path::new("/tmp/output");
        let result = validate_output_path(base, "../etc/passwd");
        assert!(result.is_err());
        assert!(matches!(result.unwrap_err(), Error::InvalidOutputPath(_)));
    }

    #[test]
    fn test_validate_output_path_traversal_complex() {
        let base = Path::new("/tmp/output");
        let result = validate_output_path(base, "safe/../../../../../../etc/passwd");
        assert!(result.is_err());
    }

    #[test]
    fn test_validate_output_path_null_byte() {
        let base = Path::new("/tmp/output");
        let result = validate_output_path(base, "file\0name.js");
        assert!(result.is_err());
    }

    #[test]
    fn test_validate_output_path_current_dir() {
        let base = Path::new("/tmp/output");
        let result = validate_output_path(base, "./index.js");
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), Path::new("/tmp/output/index.js"));
    }
}