pqfile 4.2.1

Quantum-resistant file encryption: ML-KEM (512/768/1024), hybrid X25519+ML-KEM-768, ML-DSA-65 signing, multi-recipient, Shamir sharing
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
use std::io::{self, Cursor, Read, Write};
use std::path::{Path, PathBuf};

use crate::encrypt;
use crate::error::PqfileError;
use crate::format::CHUNK_SIZE;
use crate::reader::PqfReader;

// Inner plaintext payload magic + version.
const PQFA_MAGIC: &[u8; 4] = b"PQFA";
const PQFA_VERSION: u8 = 1;

// Entry manifest header per file:
//   path_len: u16 LE
//   path:     [u8; path_len]  (UTF-8)
//   size:     u64 LE
//   mtime:    i64 LE          (Unix seconds, 0 if unavailable)
//   mode:     u32 LE          (Unix permissions, 0 on Windows)

/// Metadata for a single file in the archive.
#[non_exhaustive]
#[derive(Debug, Clone)]
pub struct ArchiveEntry {
    /// Relative path stored in the archive.
    pub path: String,
    /// Uncompressed size of the file in bytes.
    pub file_size: u64,
    /// Last-modification time as Unix seconds; 0 if unavailable.
    pub mtime_secs: i64,
    /// Unix permission bits; 0 on Windows.
    pub mode: u32,
}

/// Create an encrypted archive from a list of `(path_in_archive, source_path)` pairs.
///
/// Writes a standard `.pqf` stream to `writer` whose plaintext payload begins with
/// a `PQFA` header and manifest, followed by concatenated file contents.
#[must_use = "archive creation result must be checked for errors"]
pub fn create(
    pubkey_pem: &str,
    entries: &[(String, PathBuf)],
    writer: &mut dyn Write,
) -> Result<(), PqfileError> {
    // Collect metadata
    let mut manifest: Vec<ArchiveEntry> = Vec::with_capacity(entries.len());
    let mut total_size: u64 = 0;

    for (archive_path, src) in entries {
        let meta = std::fs::metadata(src)?;
        let file_size = meta.len();
        let mtime_secs = mtime_unix(&meta);
        let mode = unix_mode(&meta);
        let path_bytes = archive_path.as_bytes();
        if path_bytes.len() > u16::MAX as usize {
            return Err(bad_arg("archive entry path too long (> 65535 bytes)"));
        }
        manifest.push(ArchiveEntry {
            path: archive_path.clone(),
            file_size,
            mtime_secs,
            mode,
        });
        total_size += file_size;
    }

    // Serialize the manifest header
    let header_bytes = serialize_manifest(&manifest)?;
    let combined_size = header_bytes.len() as u64 + total_size;

    // Build a chain: header bytes → file 1 → file 2 → …
    let header_reader = Cursor::new(header_bytes);
    let mut chain: Box<dyn Read> = Box::new(header_reader);
    for (_, src) in entries {
        let f = std::fs::File::open(src)?;
        chain = Box::new(chain.chain(io::BufReader::new(f)));
    }

    encrypt::encrypt_stream(pubkey_pem, combined_size, CHUNK_SIZE, &mut chain, writer)
}

/// Extract a `.pqf` archive into `out_dir`, creating subdirectories as needed.
///
/// Each AEAD chunk is authenticated before its plaintext bytes are passed to
/// the file writer, but authentication is per-chunk rather than per-file. If
/// a crafted or truncated archive causes an authentication failure mid-stream,
/// partially-written files may already exist on disk. For security-sensitive
/// use cases prefer [`extract_to_memory`], which returns data only after the
/// entire decryption succeeds.
#[must_use = "extracted file paths must be used"]
pub fn extract<R: Read>(
    privkey_pem: &str,
    reader: R,
    out_dir: &Path,
    passphrase: Option<&str>,
) -> Result<Vec<PathBuf>, PqfileError> {
    let mut pqf = PqfReader::new(reader, privkey_pem, passphrase)?;

    // Read and verify PQFA header
    let manifest = read_manifest(&mut pqf)?;

    // Extract each entry
    let mut written = Vec::with_capacity(manifest.len());
    let mut buf = vec![0u8; CHUNK_SIZE];

    for entry in &manifest {
        let dest = safe_dest(out_dir, &entry.path)?;
        if let Some(parent) = dest.parent() {
            std::fs::create_dir_all(parent)?;
        }
        let mut out_file = std::fs::File::create(&dest)?;
        let mut remaining = entry.file_size;
        while remaining > 0 {
            let to_read = (remaining as usize).min(buf.len());
            let n = pqf.read(&mut buf[..to_read]).map_err(PqfileError::Io)?;
            if n == 0 {
                return Err(PqfileError::DecryptionFailure);
            }
            out_file.write_all(&buf[..n]).map_err(PqfileError::Io)?;
            remaining -= n as u64;
        }
        written.push(dest);
    }

    Ok(written)
}

/// List the archive manifest without decrypting file contents.
#[must_use = "archive manifest must be used"]
pub fn list<R: Read>(
    privkey_pem: &str,
    reader: R,
    passphrase: Option<&str>,
) -> Result<Vec<ArchiveEntry>, PqfileError> {
    let mut pqf = PqfReader::new(reader, privkey_pem, passphrase)?;
    read_manifest(&mut pqf)
}

/// Decrypt an archive and return all file contents in memory as `(path, data)` pairs.
///
/// Equivalent to [`extract`] but writes into `Vec<u8>` buffers rather than to disk.
/// Useful when no filesystem is available (e.g., WASM builds).
#[must_use = "extracted data must be used"]
pub fn extract_to_memory<R: Read>(
    privkey_pem: &str,
    reader: R,
    passphrase: Option<&str>,
) -> Result<Vec<(String, Vec<u8>)>, PqfileError> {
    let mut pqf = PqfReader::new(reader, privkey_pem, passphrase)?;
    let manifest = read_manifest(&mut pqf)?;
    let mut result = Vec::with_capacity(manifest.len());
    let mut buf = vec![0u8; CHUNK_SIZE];
    // Cap pre-allocation hint to 64 MiB per entry so a crafted (but AEAD-valid)
    // archive cannot force an OOM via a large file_size field before any bytes arrive.
    const MAX_PREALLOC: u64 = 64 * 1024 * 1024;
    for entry in &manifest {
        let mut data = Vec::with_capacity(entry.file_size.min(MAX_PREALLOC) as usize);
        let mut remaining = entry.file_size;
        while remaining > 0 {
            let to_read = (remaining as usize).min(buf.len());
            let n = pqf.read(&mut buf[..to_read]).map_err(PqfileError::Io)?;
            if n == 0 {
                return Err(PqfileError::DecryptionFailure);
            }
            data.extend_from_slice(&buf[..n]);
            remaining -= n as u64;
        }
        result.push((entry.path.clone(), data));
    }
    Ok(result)
}

/// Create an archive from in-memory file data as `(path_in_archive, data)` pairs.
///
/// Unlike [`create`], this variant does not require files to exist on disk and
/// works on all platforms including WASM.
#[must_use = "archive creation result must be checked for errors"]
pub fn create_from_memory(
    pubkey_pem: &str,
    entries: &[(String, Vec<u8>)],
    writer: &mut dyn Write,
) -> Result<(), PqfileError> {
    let manifest: Vec<ArchiveEntry> = entries
        .iter()
        .map(|(path, data)| ArchiveEntry {
            path: path.clone(),
            file_size: data.len() as u64,
            mtime_secs: 0,
            mode: 0,
        })
        .collect();

    let header_bytes = serialize_manifest(&manifest)?;
    let total_size =
        header_bytes.len() as u64 + entries.iter().map(|(_, d)| d.len() as u64).sum::<u64>();

    // Build a single contiguous payload buffer (header + all file data) so that
    // encrypt_stream receives a plain slice rather than a boxed chain of cloned Cursors.
    // This avoids one heap allocation per entry without increasing total memory use.
    let mut payload = Vec::with_capacity(total_size.min(256 * 1024 * 1024) as usize);
    payload.extend_from_slice(&header_bytes);
    for (_, data) in entries {
        payload.extend_from_slice(data);
    }

    crate::encrypt::encrypt_stream(
        pubkey_pem,
        total_size,
        CHUNK_SIZE,
        &mut payload.as_slice(),
        writer,
    )
}

// ── Manifest serialization ────────────────────────────────────────────────────

fn serialize_manifest(entries: &[ArchiveEntry]) -> Result<Vec<u8>, PqfileError> {
    let mut out = Vec::new();
    out.extend_from_slice(PQFA_MAGIC);
    out.push(PQFA_VERSION);
    let count = entries.len() as u32;
    out.extend_from_slice(&count.to_le_bytes());
    for e in entries {
        let path_bytes = e.path.as_bytes();
        out.extend_from_slice(&(path_bytes.len() as u16).to_le_bytes());
        out.extend_from_slice(path_bytes);
        out.extend_from_slice(&e.file_size.to_le_bytes());
        out.extend_from_slice(&e.mtime_secs.to_le_bytes());
        out.extend_from_slice(&e.mode.to_le_bytes());
    }
    Ok(out)
}

fn read_manifest<R: Read>(reader: &mut R) -> Result<Vec<ArchiveEntry>, PqfileError> {
    // Magic
    let mut magic = [0u8; 4];
    reader.read_exact(&mut magic).map_err(io_err)?;
    if &magic != PQFA_MAGIC {
        return Err(PqfileError::InvalidPem(
            "not a pqfile archive (missing PQFA magic)".into(),
        ));
    }
    // Version
    let mut ver = [0u8; 1];
    reader.read_exact(&mut ver).map_err(io_err)?;
    if ver[0] != PQFA_VERSION {
        return Err(PqfileError::UnsupportedVersion(ver[0]));
    }
    // Entry count
    let mut count_bytes = [0u8; 4];
    reader.read_exact(&mut count_bytes).map_err(io_err)?;
    let count = u32::from_le_bytes(count_bytes) as usize;
    const MAX_ARCHIVE_ENTRIES: usize = 65536;
    if count > MAX_ARCHIVE_ENTRIES {
        return Err(PqfileError::Io(std::io::Error::new(
            std::io::ErrorKind::InvalidData,
            format!("archive entry count {count} exceeds maximum ({MAX_ARCHIVE_ENTRIES})"),
        )));
    }

    let mut entries = Vec::with_capacity(count);
    let mut total_declared_size: u64 = 0;
    for _ in 0..count {
        let mut pl = [0u8; 2];
        reader.read_exact(&mut pl).map_err(io_err)?;
        let path_len = u16::from_le_bytes(pl) as usize;
        let mut path_bytes = vec![0u8; path_len];
        reader.read_exact(&mut path_bytes).map_err(io_err)?;
        let path = String::from_utf8(path_bytes)
            .map_err(|_| PqfileError::InvalidPem("archive path is not valid UTF-8".into()))?;

        let mut size_bytes = [0u8; 8];
        reader.read_exact(&mut size_bytes).map_err(io_err)?;
        let file_size = u64::from_le_bytes(size_bytes);
        if file_size > crate::format::MAX_ORIGINAL_SIZE {
            return Err(PqfileError::Io(std::io::Error::new(
                std::io::ErrorKind::InvalidData,
                format!(
                    "archive entry file_size {file_size} exceeds maximum ({})",
                    crate::format::MAX_ORIGINAL_SIZE
                ),
            )));
        }
        // Cap the running total so a crafted manifest with many valid-looking
        // entries cannot force an unbounded extraction.
        total_declared_size = total_declared_size.saturating_add(file_size);
        if total_declared_size > crate::format::MAX_ORIGINAL_SIZE {
            return Err(PqfileError::Io(std::io::Error::new(
                std::io::ErrorKind::InvalidData,
                format!(
                    "archive total declared size exceeds maximum ({})",
                    crate::format::MAX_ORIGINAL_SIZE
                ),
            )));
        }

        let mut mtime_bytes = [0u8; 8];
        reader.read_exact(&mut mtime_bytes).map_err(io_err)?;
        let mtime_secs = i64::from_le_bytes(mtime_bytes);

        let mut mode_bytes = [0u8; 4];
        reader.read_exact(&mut mode_bytes).map_err(io_err)?;
        let mode = u32::from_le_bytes(mode_bytes);

        entries.push(ArchiveEntry {
            path,
            file_size,
            mtime_secs,
            mode,
        });
    }
    Ok(entries)
}

// ── Path safety ───────────────────────────────────────────────────────────────

/// Returns `true` if `name` is a Windows reserved device name (CON, NUL, AUX, PRN,
/// COM1-COM9, LPT1-LPT9). On Windows, creating files with these names causes I/O to
/// be redirected to system devices rather than regular files.
fn is_windows_device_name(name: &std::ffi::OsStr) -> bool {
    let s = match name.to_str() {
        Some(s) => s.to_ascii_uppercase(),
        None => return false,
    };
    // Strip any extension (e.g. "NUL.txt" is still a device on Windows).
    let base = s.split('.').next().unwrap_or(&s);
    match base {
        "CON" | "PRN" | "AUX" | "NUL" => true,
        s if s.len() == 4 => {
            let (prefix, digit) = s.split_at(3);
            let d = digit
                .chars()
                .next()
                .is_some_and(|c| c.is_ascii_digit() && c != '0');
            matches!(prefix, "COM" | "LPT") && d
        }
        _ => false,
    }
}

/// Resolve `archive_path` inside `base`, rejecting path traversal attempts and
/// Windows reserved device names.
fn safe_dest(base: &Path, archive_path: &str) -> Result<PathBuf, PqfileError> {
    // Strip leading slashes and reject ".." components
    let mut dest = base.to_path_buf();
    for component in Path::new(archive_path).components() {
        match component {
            std::path::Component::Normal(c) => {
                if is_windows_device_name(c) {
                    return Err(bad_arg(&format!(
                        "archive entry '{archive_path}' contains a Windows reserved device name"
                    )));
                }
                dest.push(c);
            }
            std::path::Component::CurDir => {}
            _ => {
                return Err(bad_arg(&format!(
                    "archive entry '{archive_path}' contains unsafe path component"
                )))
            }
        }
    }
    Ok(dest)
}

// ── Platform helpers ──────────────────────────────────────────────────────────

#[cfg(unix)]
fn mtime_unix(meta: &std::fs::Metadata) -> i64 {
    use std::os::unix::fs::MetadataExt;
    meta.mtime()
}

#[cfg(not(unix))]
fn mtime_unix(meta: &std::fs::Metadata) -> i64 {
    meta.modified()
        .ok()
        .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
        .map(|d| d.as_secs() as i64)
        .unwrap_or(0)
}

#[cfg(unix)]
fn unix_mode(meta: &std::fs::Metadata) -> u32 {
    use std::os::unix::fs::MetadataExt;
    meta.mode()
}

#[cfg(not(unix))]
fn unix_mode(_meta: &std::fs::Metadata) -> u32 {
    0o644
}

fn bad_arg(msg: &str) -> PqfileError {
    PqfileError::Io(std::io::Error::new(std::io::ErrorKind::InvalidInput, msg))
}

fn io_err(e: io::Error) -> PqfileError {
    if e.kind() == io::ErrorKind::UnexpectedEof {
        PqfileError::DecryptionFailure
    } else {
        PqfileError::Io(e)
    }
}

// ── Tests ─────────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;
    use crate::keygen::keygen_bytes;
    use tempfile::tempdir;

    fn make_entries(dir: &Path, files: &[(&str, &[u8])]) -> Vec<(String, PathBuf)> {
        files
            .iter()
            .map(|(name, data)| {
                let p = dir.join(name);
                std::fs::write(&p, data).unwrap();
                (name.to_string(), p)
            })
            .collect()
    }

    #[test]
    fn archive_roundtrip_single_file() {
        let tmp = tempdir().unwrap();
        let (pub_pem, priv_pem) = keygen_bytes(768, None).unwrap();
        let entries = make_entries(tmp.path(), &[("hello.txt", b"hello world")]);

        let mut archive_bytes = Vec::new();
        create(&pub_pem, &entries, &mut archive_bytes).unwrap();

        let out_dir = tempdir().unwrap();
        let paths = extract(&priv_pem, archive_bytes.as_slice(), out_dir.path(), None).unwrap();
        assert_eq!(paths.len(), 1);
        assert_eq!(std::fs::read(&paths[0]).unwrap(), b"hello world");
    }

    #[test]
    fn archive_roundtrip_multiple_files() {
        let tmp = tempdir().unwrap();
        let (pub_pem, priv_pem) = keygen_bytes(768, None).unwrap();
        let files: Vec<(&str, &[u8])> = vec![
            ("a.txt", b"file a content"),
            ("b.bin", &[0xDE, 0xAD, 0xBE, 0xEF]),
            ("c.txt", b"another file"),
        ];
        let entries = make_entries(tmp.path(), &files);

        let mut archive_bytes = Vec::new();
        create(&pub_pem, &entries, &mut archive_bytes).unwrap();

        let out_dir = tempdir().unwrap();
        let paths = extract(&priv_pem, archive_bytes.as_slice(), out_dir.path(), None).unwrap();
        assert_eq!(paths.len(), 3);
        assert_eq!(std::fs::read(&paths[0]).unwrap(), b"file a content");
        assert_eq!(std::fs::read(&paths[1]).unwrap(), &[0xDE, 0xAD, 0xBE, 0xEF]);
        assert_eq!(std::fs::read(&paths[2]).unwrap(), b"another file");
    }

    #[test]
    fn archive_empty_file() {
        let tmp = tempdir().unwrap();
        let (pub_pem, priv_pem) = keygen_bytes(768, None).unwrap();
        let entries = make_entries(tmp.path(), &[("empty.dat", b"")]);

        let mut archive_bytes = Vec::new();
        create(&pub_pem, &entries, &mut archive_bytes).unwrap();

        let out_dir = tempdir().unwrap();
        let paths = extract(&priv_pem, archive_bytes.as_slice(), out_dir.path(), None).unwrap();
        assert_eq!(std::fs::read(&paths[0]).unwrap(), b"");
    }

    #[test]
    fn archive_list_without_extracting() {
        let tmp = tempdir().unwrap();
        let (pub_pem, priv_pem) = keygen_bytes(768, None).unwrap();
        let entries = make_entries(tmp.path(), &[("foo.txt", b"foo"), ("bar.txt", b"bar")]);

        let mut archive_bytes = Vec::new();
        create(&pub_pem, &entries, &mut archive_bytes).unwrap();

        let manifest = list(&priv_pem, archive_bytes.as_slice(), None).unwrap();
        assert_eq!(manifest.len(), 2);
        assert_eq!(manifest[0].path, "foo.txt");
        assert_eq!(manifest[0].file_size, 3);
        assert_eq!(manifest[1].path, "bar.txt");
    }

    #[test]
    fn archive_subdirectory_entries() {
        let tmp = tempdir().unwrap();
        let (pub_pem, priv_pem) = keygen_bytes(768, None).unwrap();
        std::fs::create_dir(tmp.path().join("sub")).unwrap();
        let src = tmp.path().join("sub").join("nested.txt");
        std::fs::write(&src, b"nested content").unwrap();
        let entries = vec![("sub/nested.txt".to_string(), src)];

        let mut archive_bytes = Vec::new();
        create(&pub_pem, &entries, &mut archive_bytes).unwrap();

        let out_dir = tempdir().unwrap();
        let paths = extract(&priv_pem, archive_bytes.as_slice(), out_dir.path(), None).unwrap();
        assert_eq!(std::fs::read(&paths[0]).unwrap(), b"nested content");
        assert!(paths[0].ends_with("sub/nested.txt") || paths[0].ends_with("sub\\nested.txt"));
    }

    #[test]
    fn archive_path_traversal_rejected() {
        let tmp = tempdir().unwrap();
        let (pub_pem, priv_pem) = keygen_bytes(768, None).unwrap();
        let src = tmp.path().join("evil.txt");
        std::fs::write(&src, b"evil").unwrap();
        let entries = vec![("../outside.txt".to_string(), src)];

        let mut archive_bytes = Vec::new();
        create(&pub_pem, &entries, &mut archive_bytes).unwrap();

        let out_dir = tempdir().unwrap();
        let result = extract(&priv_pem, archive_bytes.as_slice(), out_dir.path(), None);
        assert!(result.is_err(), "path traversal should be rejected");
    }

    #[test]
    fn archive_large_file_multi_chunk() {
        let tmp = tempdir().unwrap();
        let (pub_pem, priv_pem) = keygen_bytes(768, None).unwrap();
        let big: Vec<u8> = (0u8..=255).cycle().take(CHUNK_SIZE * 3 + 7).collect();
        let entries = make_entries(tmp.path(), &[("big.bin", &big)]);

        let mut archive_bytes = Vec::new();
        create(&pub_pem, &entries, &mut archive_bytes).unwrap();

        let out_dir = tempdir().unwrap();
        let paths = extract(&priv_pem, archive_bytes.as_slice(), out_dir.path(), None).unwrap();
        assert_eq!(std::fs::read(&paths[0]).unwrap(), big);
    }

    #[test]
    fn archive_rejects_oversized_file_size_entry() {
        // Craft a manifest with file_size > MAX_ORIGINAL_SIZE (1 TiB).
        let (pub_pem, priv_pem) = keygen_bytes(768, None).unwrap();
        let oversized: u64 = crate::format::MAX_ORIGINAL_SIZE + 1;

        // Build a raw PQFA payload with the bad file_size field.
        let mut manifest = Vec::new();
        manifest.extend_from_slice(b"PQFA"); // magic
        manifest.push(1u8); // version
        manifest.extend_from_slice(&1u32.to_le_bytes()); // 1 entry
                                                         // entry: path_len=8, path="evil.txt", file_size=oversized, mtime=0, mode=0
        manifest.extend_from_slice(&8u16.to_le_bytes());
        manifest.extend_from_slice(b"evil.txt");
        manifest.extend_from_slice(&oversized.to_le_bytes());
        manifest.extend_from_slice(&0i64.to_le_bytes());
        manifest.extend_from_slice(&0u32.to_le_bytes());

        let mut archive_bytes = Vec::new();
        crate::encrypt::encrypt_stream(
            &pub_pem,
            manifest.len() as u64,
            CHUNK_SIZE,
            &mut manifest.as_slice(),
            &mut archive_bytes,
        )
        .unwrap();

        let out_dir = tempdir().unwrap();
        let result = extract(&priv_pem, archive_bytes.as_slice(), out_dir.path(), None);
        assert!(result.is_err(), "oversized file_size should be rejected");
    }

    #[test]
    fn is_windows_device_name_detects_reserved_names() {
        use super::is_windows_device_name;
        use std::ffi::OsStr;
        for name in &["CON", "NUL", "AUX", "PRN", "COM1", "COM9", "LPT1", "LPT9"] {
            assert!(
                is_windows_device_name(OsStr::new(name)),
                "{name} should be detected"
            );
        }
        for name in &["file.txt", "data", "COM0", "LPT0", "CONSOLE", "NULL"] {
            assert!(
                !is_windows_device_name(OsStr::new(name)),
                "{name} should not be detected"
            );
        }
    }

    #[test]
    fn archive_rejects_windows_device_name_in_path() {
        // safe_dest should reject Windows device names regardless of platform.
        use super::safe_dest;
        use std::path::Path;
        let base = Path::new("/tmp/out");
        assert!(safe_dest(base, "NUL").is_err());
        assert!(safe_dest(base, "CON").is_err());
        assert!(safe_dest(base, "COM1").is_err());
        assert!(safe_dest(base, "subdir/NUL").is_err());
        // Normal names are still allowed.
        assert!(safe_dest(base, "normal.txt").is_ok());
        assert!(safe_dest(base, "subdir/file.dat").is_ok());
    }

    #[test]
    fn archive_rejects_manifest_whose_aggregate_size_exceeds_max() {
        // Craft a manifest where each entry's file_size is valid but their
        // sum exceeds MAX_ORIGINAL_SIZE. The aggregate guard should fire.
        let (pub_pem, priv_pem) = keygen_bytes(768, None).unwrap();
        let per_entry: u64 = crate::format::MAX_ORIGINAL_SIZE / 2 + 1;

        // Two entries each claiming (MAX/2 + 1) bytes: total > MAX.
        let mut manifest = Vec::new();
        manifest.extend_from_slice(b"PQFA");
        manifest.push(1u8);
        manifest.extend_from_slice(&2u32.to_le_bytes()); // 2 entries
        for name in &[b"a.txt" as &[u8], b"b.txt"] {
            manifest.extend_from_slice(&(name.len() as u16).to_le_bytes());
            manifest.extend_from_slice(name);
            manifest.extend_from_slice(&per_entry.to_le_bytes());
            manifest.extend_from_slice(&0i64.to_le_bytes());
            manifest.extend_from_slice(&0u32.to_le_bytes());
        }

        let mut archive_bytes = Vec::new();
        crate::encrypt::encrypt_stream(
            &pub_pem,
            manifest.len() as u64,
            CHUNK_SIZE,
            &mut manifest.as_slice(),
            &mut archive_bytes,
        )
        .unwrap();

        let out_dir = tempdir().unwrap();
        let result = extract(&priv_pem, archive_bytes.as_slice(), out_dir.path(), None);
        assert!(
            result.is_err(),
            "aggregate file_size exceeding MAX_ORIGINAL_SIZE must be rejected"
        );
    }
}