Skip to main content

powerio_archive/
package.rs

1//! Deterministic rebuilt ZIPs; never a claim of original-container fidelity.
2use crate::{ArchiveLimits, Result, limit, malformed, validate_path};
3use powerio_core::ArtifactPath;
4use std::{
5    collections::BTreeMap,
6    io::{Cursor, Seek, SeekFrom, Write},
7    sync::Arc,
8};
9
10struct BoundedOutput {
11    inner: Cursor<Vec<u8>>,
12    limit: u64,
13}
14impl Write for BoundedOutput {
15    fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
16        if self.inner.position().saturating_add(bytes.len() as u64) > self.limit {
17            return Err(std::io::Error::other("ZIP output byte limit exceeded"));
18        }
19        self.inner.write(bytes)
20    }
21    fn flush(&mut self) -> std::io::Result<()> {
22        Ok(())
23    }
24}
25impl Seek for BoundedOutput {
26    fn seek(&mut self, position: SeekFrom) -> std::io::Result<u64> {
27        self.inner.seek(position)
28    }
29}
30/// Sorted paths, fixed timestamps/permissions and stored payloads yield the same
31/// bytes for the same files with this writer version. Limits apply to both
32/// source payloads and the complete output (including ZIP metadata). All names
33/// obey the same portable collision policy as archive admission.
34pub fn deterministic_zip(
35    files: &[(ArtifactPath, Arc<[u8]>)],
36    limits: ArchiveLimits,
37) -> Result<Vec<u8>> {
38    if files.len() > limits.max_entries() {
39        return Err(limit("bundle file limit exceeded"));
40    }
41    let mut sorted: Vec<_> = files.iter().collect();
42    sorted.sort_by(|a, b| a.0.cmp(&b.0));
43    let mut nodes = BTreeMap::new();
44    let mut total = 0u64;
45    for (path, bytes) in &sorted {
46        validate_path(path.as_str(), false, &mut nodes)?;
47        total = total
48            .checked_add(bytes.len() as u64)
49            .ok_or_else(|| limit("bundle byte overflow"))?;
50        if total > limits.max_expanded_bytes() {
51            return Err(limit("bundle payload limit exceeded"));
52        }
53    }
54    let minimum_output = sorted.iter().try_fold(22u64, |total, (path, bytes)| {
55        total
56            .checked_add(76 + 2 * path.as_str().len() as u64)?
57            .checked_add(bytes.len() as u64)
58    });
59    if minimum_output.is_none_or(|size| size > limits.max_input_bytes()) {
60        return Err(limit("bundle plus ZIP metadata exceeds output limit"));
61    }
62    let mut writer = zip::ZipWriter::new(BoundedOutput {
63        inner: Cursor::new(Vec::new()),
64        limit: limits.max_input_bytes(),
65    });
66    let options = zip::write::SimpleFileOptions::default()
67        .compression_method(zip::CompressionMethod::Stored)
68        .last_modified_time(zip::DateTime::default())
69        .unix_permissions(0o644);
70    for (path, bytes) in sorted {
71        writer
72            .start_file(path.as_str(), options)
73            .map_err(|e| malformed(e.to_string()))?;
74        writer.write_all(bytes).map_err(|e| limit(e.to_string()))?;
75    }
76    Ok(writer
77        .finish()
78        .map_err(|e| limit(e.to_string()))?
79        .inner
80        .into_inner())
81}