agentmux_srv_core/backend/agent_archive/
reader.rs1use std::collections::HashSet;
11use std::io::{Read, Seek, Write};
12
13use sha2::{Digest, Sha256};
14use zip::ZipArchive;
15
16use super::manifest::{chunk_count, valid_part_path, Manifest, SignatureState, CHUNK_BYTES, FORMAT, KIND, MANIFEST_NAME};
17use super::{ArchiveError, Limits};
18
19const MAX_MANIFEST_BYTES: u64 = 16 << 20;
21
22pub struct ArchiveReader<R: Read + Seek> {
23 zip: ZipArchive<R>,
24 manifest: Manifest,
25 signature: SignatureState,
26}
27
28impl<R: Read + Seek> ArchiveReader<R> {
29 pub fn open(input: R, limits: Limits) -> Result<Self, ArchiveError> {
30 let mut zip = ZipArchive::new(input).map_err(|e| ArchiveError::NotAnArchive(e.to_string()))?;
31 let manifest = read_manifest(&mut zip)?;
32 check_manifest(&manifest, &limits)?;
33 check_entries(&mut zip, &manifest)?;
34 let signature = check_signature(&manifest);
35 Ok(Self { zip, manifest, signature })
36 }
37
38 pub fn manifest(&self) -> &Manifest {
39 &self.manifest
40 }
41
42 pub fn signature(&self) -> &SignatureState {
43 &self.signature
44 }
45
46 pub fn read_part(&mut self, path: &str, sink: &mut dyn Write) -> Result<(), ArchiveError> {
49 let part = self.manifest.part(path).ok_or_else(|| ArchiveError::NoSuchPart(path.to_string()))?.clone();
50 let entry = self.zip.by_name(path).map_err(|e| ArchiveError::Io(e.to_string()))?;
51 let mut source = entry.take(part.size + 1);
53 let mut whole = Sha256::new();
54 let mut buf = vec![0u8; CHUNK_BYTES as usize];
55 let mut at = 0u64;
56 let mut index = 0usize;
57 loop {
58 let n = fill(&mut source, &mut buf).map_err(|e| ArchiveError::Io(e.to_string()))?;
59 if n == 0 {
60 break;
61 }
62 at += n as u64;
63 if at > part.size {
64 return Err(ArchiveError::PartChanged(path.to_string(), "longer than the manifest says".to_string()));
65 }
66 let want = part.chunks.get(index).ok_or_else(|| ArchiveError::PartChanged(path.to_string(), "more chunks than the manifest lists".to_string()))?;
67 if &hex::encode(Sha256::digest(&buf[..n])) != want {
68 return Err(ArchiveError::PartChanged(path.to_string(), format!("chunk {index} does not match its hash")));
69 }
70 whole.update(&buf[..n]);
71 sink.write_all(&buf[..n]).map_err(|e| ArchiveError::Io(e.to_string()))?;
72 index += 1;
73 if (n as u64) < CHUNK_BYTES {
74 break;
75 }
76 }
77 if at != part.size || index as u64 != chunk_count(part.size) {
78 return Err(ArchiveError::PartChanged(path.to_string(), "shorter than the manifest says".to_string()));
79 }
80 if hex::encode(whole.finalize()) != part.sha256 {
81 return Err(ArchiveError::PartChanged(path.to_string(), "the whole part does not match its hash".to_string()));
82 }
83 Ok(())
84 }
85
86 pub fn read_part_bytes(&mut self, path: &str, max: u64) -> Result<Vec<u8>, ArchiveError> {
88 let size = self.manifest.part(path).ok_or_else(|| ArchiveError::NoSuchPart(path.to_string()))?.size;
89 if size > max {
90 return Err(ArchiveError::PartTooBig(path.to_string(), max));
91 }
92 let mut out = Vec::with_capacity(size as usize);
93 self.read_part(path, &mut out)?;
94 Ok(out)
95 }
96
97 pub fn verify_all(&mut self) -> Result<(), ArchiveError> {
99 let paths: Vec<String> = self.manifest.parts.iter().map(|p| p.path.clone()).collect();
100 for path in paths {
101 self.read_part(&path, &mut std::io::sink())?;
102 }
103 Ok(())
104 }
105}
106
107fn read_manifest<R: Read + Seek>(zip: &mut ZipArchive<R>) -> Result<Manifest, ArchiveError> {
108 let entry = zip.by_name(MANIFEST_NAME).map_err(|_| ArchiveError::NoManifest)?;
109 if entry.size() > MAX_MANIFEST_BYTES {
110 return Err(ArchiveError::Malformed("the manifest is too large".to_string()));
111 }
112 let mut bytes = Vec::new();
113 entry.take(MAX_MANIFEST_BYTES + 1).read_to_end(&mut bytes).map_err(|e| ArchiveError::Io(e.to_string()))?;
114 if bytes.len() as u64 > MAX_MANIFEST_BYTES {
115 return Err(ArchiveError::Malformed("the manifest is too large".to_string()));
116 }
117 let loose: serde_json::Value = serde_json::from_slice(&bytes).map_err(|e| ArchiveError::Malformed(e.to_string()))?;
119 if loose.get("kind").and_then(|k| k.as_str()) != Some(KIND) {
120 return Err(ArchiveError::WrongKind(loose.get("kind").and_then(|k| k.as_str()).unwrap_or("none").to_string()));
121 }
122 let format = loose.get("format").and_then(|f| f.as_u64()).unwrap_or(0);
123 if format > u64::from(FORMAT) {
124 return Err(ArchiveError::TooNew { archive: format as u32, supported: FORMAT });
125 }
126 serde_json::from_slice(&bytes).map_err(|e| ArchiveError::Malformed(e.to_string()))
127}
128
129fn check_manifest(m: &Manifest, limits: &Limits) -> Result<(), ArchiveError> {
130 if m.format == 0 {
131 return Err(ArchiveError::Malformed("format 0".to_string()));
132 }
133 if m.parts.len() > limits.max_parts {
134 return Err(ArchiveError::TooManyParts(limits.max_parts));
135 }
136 let mut seen = HashSet::new();
137 let mut total = 0u64;
138 for p in &m.parts {
139 if !valid_part_path(&p.path) {
140 return Err(ArchiveError::BadPath(p.path.clone()));
141 }
142 if !seen.insert(p.path.as_str()) {
143 return Err(ArchiveError::DuplicatePart(p.path.clone()));
144 }
145 if p.size > limits.max_part_bytes {
146 return Err(ArchiveError::PartTooBig(p.path.clone(), limits.max_part_bytes));
147 }
148 total = total.saturating_add(p.size);
149 if total > limits.max_total_bytes {
150 return Err(ArchiveError::TooBig(limits.max_total_bytes));
151 }
152 if p.chunks.len() as u64 != chunk_count(p.size) {
153 return Err(ArchiveError::Malformed(format!("{}: {} chunk hashes for {} bytes", p.path, p.chunks.len(), p.size)));
154 }
155 if !is_hex(&p.sha256) || p.chunks.iter().any(|c| !is_hex(c)) {
156 return Err(ArchiveError::Malformed(format!("{}: a hash is not 64 hex digits", p.path)));
157 }
158 }
159 Ok(())
160}
161
162fn is_hex(s: &str) -> bool {
163 s.len() == 64 && s.bytes().all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
164}
165
166fn check_entries<R: Read + Seek>(zip: &mut ZipArchive<R>, m: &Manifest) -> Result<(), ArchiveError> {
169 let mut names: HashSet<String> = m.parts.iter().map(|p| p.path.clone()).collect();
170 names.insert(MANIFEST_NAME.to_string());
171 let mut found = HashSet::new();
172 for i in 0..zip.len() {
173 let entry = zip.by_index_raw(i).map_err(|e| ArchiveError::Io(e.to_string()))?;
174 let name = entry.name().to_string();
175 if entry.is_dir() || entry.is_symlink() || entry.unix_mode().is_some_and(|mode| mode & 0o170000 != 0 && mode & 0o170000 != 0o100000) {
176 return Err(ArchiveError::NotPlainFile(name));
177 }
178 if !names.contains(&name) {
179 return Err(ArchiveError::UnlistedEntry(name));
180 }
181 if !found.insert(name.clone()) {
182 return Err(ArchiveError::DuplicatePart(name));
183 }
184 if name != MANIFEST_NAME {
185 let part = m.part(&name).ok_or_else(|| ArchiveError::UnlistedEntry(name.clone()))?;
186 if entry.size() != part.size {
187 return Err(ArchiveError::PartChanged(name, "the file's own size differs from the manifest".to_string()));
188 }
189 }
190 }
191 if let Some(missing) = names.iter().find(|n| !found.contains(*n)) {
192 return Err(ArchiveError::MissingEntry(missing.clone()));
193 }
194 Ok(())
195}
196
197fn check_signature(m: &Manifest) -> SignatureState {
198 use base64::Engine;
199 let Some(sig) = &m.signature else { return SignatureState::Unsigned };
200 let b64 = base64::engine::general_purpose::STANDARD;
201 let (Ok(key), Ok(value)) = (b64.decode(&sig.public_key), b64.decode(&sig.value)) else { return SignatureState::Invalid };
202 let (Ok(key), Ok(value)) = (<[u8; 32]>::try_from(key.as_slice()), <[u8; 64]>::try_from(value.as_slice())) else { return SignatureState::Invalid };
203 if sig.alg != "ed25519" {
204 return SignatureState::Invalid;
205 }
206 let Ok(verifying) = ed25519_dalek::VerifyingKey::from_bytes(&key) else { return SignatureState::Invalid };
207 let signature = ed25519_dalek::Signature::from_bytes(&value);
208 match ed25519_dalek::Verifier::verify(&verifying, &m.signed_bytes(), &signature) {
209 Ok(()) => SignatureState::Valid { public_key: key },
210 Err(_) => SignatureState::Invalid,
211 }
212}
213
214fn fill(source: &mut dyn Read, buf: &mut [u8]) -> std::io::Result<usize> {
215 let mut at = 0;
216 while at < buf.len() {
217 match source.read(&mut buf[at..]) {
218 Ok(0) => break,
219 Ok(n) => at += n,
220 Err(e) if e.kind() == std::io::ErrorKind::Interrupted => {}
221 Err(e) => return Err(e),
222 }
223 }
224 Ok(at)
225}