1use crate::download::{DownloadOptions, TrackedReader, is_transient_request_error, local_file_url};
2use crate::identity::{FileIdentity, VerifiedFile};
3use crate::keys::decode_public_key;
4use crate::manifest::{COMPONENT_ABI_VERSION, COMPONENT_MANIFEST_SCHEMA};
5use crate::stamp;
6use crate::{ComponentError, ComponentLockEntry, ComponentManifest, ComponentSignature};
7use base64::Engine as _;
8use ed25519_dalek::Signature;
9use flate2::read::GzDecoder;
10use sha2::{Digest as _, Sha256};
11use std::borrow::Cow;
12use std::collections::BTreeMap;
13use std::fs::{self, File, OpenOptions};
14use std::io::{Read, Seek as _, SeekFrom, Write as _};
15use std::path::{Component, Path, PathBuf};
16use std::sync::Arc;
17
18pub(crate) type UrlOverride = Arc<dyn Fn(&ComponentLockEntry) -> String + Send + Sync>;
20
21#[derive(Clone, Debug)]
22pub enum TrustPolicy {
23 DigestOnly,
24 EmbeddedKeys(BTreeMap<String, String>),
25}
26
27#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
35pub enum SignaturePolicy {
36 #[default]
37 AllowUnsigned,
38 Require,
39}
40
41#[derive(Clone)]
42pub struct ArtifactCache {
43 pub(crate) root: PathBuf,
44 trust: TrustPolicy,
45 offline: bool,
46 pub(crate) download: DownloadOptions,
47 url_override: Option<UrlOverride>,
48 verified_stamp: bool,
49 signatures: SignaturePolicy,
50}
51
52impl std::fmt::Debug for ArtifactCache {
53 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
54 f.debug_struct("ArtifactCache")
55 .field("root", &self.root)
56 .field("trust", &self.trust)
57 .field("offline", &self.offline)
58 .field("download", &self.download)
59 .field("url_override", &self.url_override.as_ref().map(|_| "<fn>"))
60 .field("verified_stamp", &self.verified_stamp)
61 .field("signatures", &self.signatures)
62 .finish()
63 }
64}
65
66#[derive(Clone, Debug, PartialEq, Eq)]
67pub struct CachedArtifact {
68 pub root: PathBuf,
69 pub library: PathBuf,
70 pub manifest: ComponentManifest,
71}
72
73impl ArtifactCache {
74 pub fn new(root: impl Into<PathBuf>, trust: TrustPolicy) -> Self {
75 Self {
76 root: root.into(),
77 trust,
78 offline: false,
79 download: DownloadOptions::default(),
80 url_override: None,
81 verified_stamp: false,
82 signatures: SignaturePolicy::AllowUnsigned,
83 }
84 }
85
86 #[must_use]
90 pub fn with_signature_policy(mut self, policy: SignaturePolicy) -> Self {
91 self.signatures = policy;
92 self
93 }
94
95 #[must_use]
97 pub fn with_download_options(mut self, options: DownloadOptions) -> Self {
98 self.download = options;
99 self
100 }
101
102 #[must_use]
103 pub fn download_options(&self) -> &DownloadOptions {
104 &self.download
105 }
106
107 #[must_use]
113 pub fn with_url_override(
114 mut self,
115 resolve: impl Fn(&ComponentLockEntry) -> String + Send + Sync + 'static,
116 ) -> Self {
117 self.url_override = Some(Arc::new(resolve));
118 self
119 }
120
121 #[must_use]
137 pub fn with_verified_stamp(mut self, enabled: bool) -> Self {
138 self.verified_stamp = enabled;
139 self
140 }
141
142 fn resolve_url(&self, entry: &ComponentLockEntry) -> String {
143 match &self.url_override {
144 Some(resolve) => resolve(entry),
145 None => entry.url.clone(),
146 }
147 }
148
149 #[must_use]
154 pub fn offline(mut self, offline: bool) -> Self {
155 self.offline = offline;
156 self
157 }
158
159 #[must_use]
160 pub fn root(&self) -> &Path {
161 &self.root
162 }
163
164 pub fn object_path(&self, entry: &ComponentLockEntry) -> Result<PathBuf, ComponentError> {
165 Ok(self.root.join("sha256").join(canonical_entry(entry)?.sha256.as_str()))
166 }
167
168 pub fn verify_cached(&self, entry: &ComponentLockEntry) -> Result<CachedArtifact, ComponentError> {
177 self.verify_cached_file(entry).map(|(cached, _)| cached)
178 }
179
180 pub(crate) fn verify_cached_file(
183 &self,
184 entry: &ComponentLockEntry,
185 ) -> Result<(CachedArtifact, VerifiedFile), ComponentError> {
186 let entry = canonical_entry(entry)?;
187 let destination = self.object_path(&entry)?;
188 self.verify_cached_at(&entry, &destination)
189 }
190
191 pub fn install(&self, entry: &ComponentLockEntry) -> Result<CachedArtifact, ComponentError> {
192 self.install_verified(entry).map(|(cached, _)| cached)
193 }
194
195 pub(crate) fn install_verified(
197 &self,
198 entry: &ComponentLockEntry,
199 ) -> Result<(CachedArtifact, VerifiedFile), ComponentError> {
200 let entry = canonical_entry(entry)?;
201 let entry: &ComponentLockEntry = &entry;
202 let destination = self.object_path(entry)?;
203 let mut damaged = None;
204 if destination.is_dir() {
205 match self.verify_cached_at(entry, &destination) {
206 Ok(verified) => {
207 self.touch_used(&entry.sha256);
208 return Ok(verified);
209 }
210 Err(error) => damaged = Some(error),
211 }
212 }
213 let url = self.resolve_url(entry);
214 if let Some(path) = local_file_url(&url) {
215 return self.install_reader_verified(entry, File::open(path?)?);
216 }
217 if self.offline {
218 return match damaged {
219 Some(source) => Err(ComponentError::CachedObjectInvalid {
220 component: entry.identity.component.clone(),
221 source: Box::new(source),
222 }),
223 None => Err(ComponentError::Offline {
224 component: entry.identity.component.clone(),
225 url,
226 }),
227 };
228 }
229 let attempts = self.download.max_attempts.max(1);
230 let mut attempt = 1;
231 loop {
232 if self.download.is_cancelled() {
233 return Err(ComponentError::Cancelled);
234 }
235 let (error, transient) = match self.download_once(entry, &url) {
236 Ok(verified) => return Ok(verified),
237 Err(failure) => failure,
238 };
239 if !transient || attempt >= attempts {
240 return Err(error);
241 }
242 std::thread::sleep(self.download.backoff_delay(attempt));
243 attempt += 1;
244 }
245 }
246
247 fn download_once(
249 &self,
250 entry: &ComponentLockEntry,
251 url: &str,
252 ) -> Result<(CachedArtifact, VerifiedFile), (ComponentError, bool)> {
253 let tls = self.download.tls_config(url).map_err(|error| (error, false))?;
254 let response = ureq::get(url)
255 .config()
256 .tls_config(tls)
257 .timeout_connect(Some(self.download.connect_timeout))
258 .timeout_global(Some(self.download.total_timeout))
259 .build()
260 .header(
261 "User-Agent",
262 concat!("alef-component-runtime/", env!("CARGO_PKG_VERSION")),
263 )
264 .call()
265 .map_err(|error| {
266 let transient = is_transient_request_error(&error);
267 (
268 ComponentError::Download {
269 url: url.to_owned(),
270 message: error.to_string(),
271 },
272 transient,
273 )
274 })?;
275 let mut body = TrackedReader::new(response.into_body().into_reader());
276 let result = self.install_reader_verified(entry, &mut body);
277 result.map_err(|error| {
278 let transient = body.read_failed && matches!(error, ComponentError::Io(_));
279 (error, transient)
280 })
281 }
282
283 pub fn install_from_reader(
286 &self,
287 entry: &ComponentLockEntry,
288 reader: impl Read,
289 ) -> Result<CachedArtifact, ComponentError> {
290 self.install_reader_verified(entry, reader).map(|(cached, _)| cached)
291 }
292
293 fn install_reader_verified(
294 &self,
295 entry: &ComponentLockEntry,
296 reader: impl Read,
297 ) -> Result<(CachedArtifact, VerifiedFile), ComponentError> {
298 let entry = canonical_entry(entry)?;
299 let verified = self.install_stream(&entry, reader)?;
300 self.touch_used(&entry.sha256);
301 Ok(verified)
302 }
303
304 fn install_stream(
305 &self,
306 entry: &ComponentLockEntry,
307 mut reader: impl Read,
308 ) -> Result<(CachedArtifact, VerifiedFile), ComponentError> {
309 let expected = decode_digest(&entry.sha256)?;
310 let objects = self.root.join("sha256");
311 create_private_dir_all(&objects)?;
312 let lock = self.digest_lock_file(&entry.sha256)?;
313 lock.lock()?;
314
315 let destination = self.object_path(entry)?;
316 if destination.is_dir()
317 && let Ok(verified) = self.verify_cached_at(entry, &destination)
318 {
319 return Ok(verified);
320 }
321
322 let mut archive = tempfile::NamedTempFile::new_in(&objects)?;
323 let mut hasher = Sha256::new();
324 let mut copied = 0_u64;
325 let mut buffer = [0_u8; 64 * 1024];
326 loop {
327 if self.download.is_cancelled() {
328 return Err(ComponentError::Cancelled);
329 }
330 let count = reader.read(&mut buffer)?;
331 if count == 0 {
332 break;
333 }
334 archive.write_all(&buffer[..count])?;
335 hasher.update(&buffer[..count]);
336 copied += count as u64;
337 if copied > entry.size {
338 return Err(ComponentError::SizeMismatch {
339 expected: entry.size,
340 actual: copied,
341 });
342 }
343 self.download.report(copied, entry.size);
344 }
345 if entry.size != copied {
346 return Err(ComponentError::SizeMismatch {
347 expected: entry.size,
348 actual: copied,
349 });
350 }
351 let actual: [u8; 32] = hasher.finalize().into();
352 if actual != expected {
353 return Err(ComponentError::DigestMismatch {
354 expected: entry.sha256.clone(),
355 actual: hex::encode(actual),
356 });
357 }
358
359 archive.as_file_mut().seek(SeekFrom::Start(0))?;
360 let staging = tempfile::Builder::new().prefix(".install-").tempdir_in(&objects)?;
361 extract_safely(archive.as_file_mut(), staging.path())?;
362 let (cached, verified) = self.verify_installation(entry, staging.path(), None)?;
363 #[cfg(windows)]
367 drop(verified);
368
369 if destination.exists() {
370 fs::remove_dir_all(&destination)?;
371 }
372 let _ = fs::remove_file(self.stamp_path(&entry.sha256));
373 let staging_path = staging.keep();
374 if let Err(error) = fs::rename(&staging_path, &destination) {
375 let _ = fs::remove_dir_all(&staging_path);
376 return Err(ComponentError::Io(error));
377 }
378 let library = destination.join(&cached.manifest.library.file);
379 #[cfg(not(windows))]
381 let verified = verified.relocated(library.clone());
382 #[cfg(windows)]
385 let (_, verified) = self.verify_installation(entry, &destination, None)?;
386 if self.stamp_enabled()
389 && let Ok(stamp) = verified
390 .metadata()
391 .and_then(|metadata| stamp::from_metadata(&entry.sha256, &metadata))
392 {
393 stamp::write(&self.stamp_path(&entry.sha256), &stamp);
394 }
395 Ok((
396 CachedArtifact {
397 root: destination.clone(),
398 library,
399 manifest: cached.manifest,
400 },
401 verified,
402 ))
403 }
404
405 pub(crate) fn digest_lock_file(&self, sha256: &str) -> std::io::Result<File> {
410 OpenOptions::new()
411 .read(true)
412 .write(true)
413 .create(true)
414 .truncate(false)
415 .open(self.objects_dir().join(format!("{sha256}.lock")))
416 }
417
418 pub(crate) fn stamp_path(&self, sha256: &str) -> PathBuf {
419 self.root.join("sha256").join(format!("{sha256}.verified"))
420 }
421
422 fn verify_cached_at(
424 &self,
425 entry: &ComponentLockEntry,
426 root: &Path,
427 ) -> Result<(CachedArtifact, VerifiedFile), ComponentError> {
428 let stamp_path = self.stamp_path(&entry.sha256);
429 self.verify_installation(entry, root, self.stamp_enabled().then_some(stamp_path.as_path()))
430 }
431
432 fn stamp_enabled(&self) -> bool {
436 self.verified_stamp && is_private_dir(&self.root) && is_private_dir(&self.objects_dir())
437 }
438
439 fn verify_installation(
440 &self,
441 entry: &ComponentLockEntry,
442 root: &Path,
443 stamp_path: Option<&Path>,
444 ) -> Result<(CachedArtifact, VerifiedFile), ComponentError> {
445 let manifest_bytes = fs::read(root.join("component.json"))?;
446 if sha256(&manifest_bytes) != decode_digest(&entry.manifest_sha256)? {
447 return Err(ComponentError::ManifestDigestMismatch);
448 }
449 let manifest: ComponentManifest = serde_json::from_slice(&manifest_bytes)?;
450 if manifest.canonical_bytes()? != manifest_bytes {
451 return Err(ComponentError::NonCanonicalManifest);
452 }
453 if manifest.schema_version != COMPONENT_MANIFEST_SCHEMA || manifest.abi_version != COMPONENT_ABI_VERSION {
454 return Err(ComponentError::UnsupportedManifest);
455 }
456 if manifest.identity != entry.identity {
457 return Err(ComponentError::ManifestIdentityMismatch);
458 }
459 let library_relative = safe_relative_path(&manifest.library.file)?;
460 let library = root.join(&library_relative);
461 let missing = |error: std::io::Error| {
462 if error.kind() == std::io::ErrorKind::NotFound {
463 ComponentError::MissingLibrary(library.clone())
464 } else {
465 ComponentError::Io(error)
466 }
467 };
468 let file = File::open(&library).map_err(missing)?;
472 let metadata = file.metadata()?;
473 if metadata.len() != manifest.library.size {
474 return Err(ComponentError::SizeMismatch {
475 expected: manifest.library.size,
476 actual: metadata.len(),
477 });
478 }
479 let trusted = stamp_path.is_some_and(|path| stamp::matches(path, &entry.sha256, &metadata));
480 if !trusted {
481 let expected_library = decode_digest(&manifest.library.sha256)?;
482 let (actual_library, hashed) = sha256_reader((&file).take(manifest.library.size.saturating_add(1)))?;
485 if hashed != manifest.library.size {
486 return Err(ComponentError::SizeMismatch {
487 expected: manifest.library.size,
488 actual: hashed,
489 });
490 }
491 if expected_library != actual_library {
492 return Err(ComponentError::DigestMismatch {
493 expected: manifest.library.sha256.clone(),
494 actual: hex::encode(actual_library),
495 });
496 }
497 }
498 self.verify_manifest_signature(entry, root, &manifest_bytes)?;
499 if let Some(path) = stamp_path
501 && !trusted
502 && file
503 .metadata()
504 .is_ok_and(|after| FileIdentity::of(&after) == FileIdentity::of(&metadata))
505 && let Ok(stamp) = stamp::from_metadata(&entry.sha256, &metadata)
506 {
507 stamp::write(path, &stamp);
508 }
509 let verified = VerifiedFile::new(library.clone(), file, &metadata);
510 Ok((
511 CachedArtifact {
512 root: root.to_owned(),
513 library,
514 manifest,
515 },
516 verified,
517 ))
518 }
519
520 fn verify_manifest_signature(
521 &self,
522 entry: &ComponentLockEntry,
523 root: &Path,
524 manifest_bytes: &[u8],
525 ) -> Result<(), ComponentError> {
526 let required = self.signatures == SignaturePolicy::Require;
527 let TrustPolicy::EmbeddedKeys(keys) = &self.trust else {
528 return if required {
529 Err(ComponentError::SignatureRequired)
530 } else {
531 Ok(())
532 };
533 };
534 if entry.key_id.is_empty() && keys.is_empty() {
535 return if required {
536 Err(ComponentError::SignatureRequired)
537 } else {
538 Ok(())
539 };
540 }
541 let signature_bytes = fs::read(root.join("component.sig")).map_err(|error| {
542 if error.kind() == std::io::ErrorKind::NotFound {
543 ComponentError::SignatureRequired
544 } else {
545 ComponentError::Io(error)
546 }
547 })?;
548 let signature: ComponentSignature = serde_json::from_slice(&signature_bytes)?;
549 if signature.algorithm != "ed25519" {
550 return Err(ComponentError::UnsupportedSignatureAlgorithm(signature.algorithm));
551 }
552 if signature.key_id != entry.key_id {
553 return Err(ComponentError::SignatureKeyMismatch);
554 }
555 let encoded_key = keys
556 .get(&signature.key_id)
557 .ok_or_else(|| ComponentError::UnknownSignatureKey(signature.key_id.clone()))?;
558 let key = decode_public_key(encoded_key)?;
559 let raw_signature = base64::engine::general_purpose::STANDARD
560 .decode(&signature.signature)
561 .map_err(|_| ComponentError::InvalidSignatureEncoding)?;
562 let signature = Signature::from_slice(&raw_signature).map_err(|_| ComponentError::InvalidSignatureEncoding)?;
563 key.verify_strict(manifest_bytes, &signature)
566 .map_err(|_| ComponentError::SignatureVerification)
567 }
568}
569
570fn create_private_dir_all(path: &Path) -> std::io::Result<()> {
573 #[cfg(unix)]
574 {
575 use std::os::unix::fs::DirBuilderExt as _;
576 fs::DirBuilder::new().recursive(true).mode(0o700).create(path)
577 }
578 #[cfg(not(unix))]
579 {
580 fs::create_dir_all(path)
581 }
582}
583
584pub(crate) fn is_private_dir(path: &Path) -> bool {
588 #[cfg(unix)]
589 {
590 use std::os::unix::fs::MetadataExt as _;
591 let user = unsafe { libc::geteuid() };
593 fs::metadata(path)
594 .is_ok_and(|metadata| metadata.is_dir() && metadata.uid() == user && metadata.mode() & 0o022 == 0)
595 }
596 #[cfg(not(unix))]
597 {
598 fs::metadata(path).is_ok_and(|metadata| metadata.is_dir())
599 }
600}
601
602pub(crate) fn canonical_entry(entry: &ComponentLockEntry) -> Result<Cow<'_, ComponentLockEntry>, ComponentError> {
606 decode_digest(&entry.sha256)?;
607 if entry.sha256.bytes().any(|byte| byte.is_ascii_uppercase()) {
608 let mut owned = entry.clone();
609 owned.sha256.make_ascii_lowercase();
610 Ok(Cow::Owned(owned))
611 } else {
612 Ok(Cow::Borrowed(entry))
613 }
614}
615
616pub(crate) fn canonical_digest(value: &str) -> Result<String, ComponentError> {
618 decode_digest(value)?;
619 Ok(value.to_ascii_lowercase())
620}
621
622pub(crate) fn decode_digest(value: &str) -> Result<[u8; 32], ComponentError> {
623 let bytes = hex::decode(value).map_err(|_| ComponentError::InvalidDigest(value.to_owned()))?;
624 bytes
625 .try_into()
626 .map_err(|_| ComponentError::InvalidDigest(value.to_owned()))
627}
628
629fn sha256(bytes: &[u8]) -> [u8; 32] {
630 Sha256::digest(bytes).into()
631}
632
633const HASH_CHUNK: usize = 64 * 1024;
635
636fn sha256_reader(mut reader: impl Read) -> std::io::Result<([u8; 32], u64)> {
639 let mut hasher = Sha256::new();
640 let mut buffer = vec![0_u8; HASH_CHUNK];
641 let mut total = 0_u64;
642 loop {
643 let count = match reader.read(&mut buffer) {
644 Ok(0) => break,
645 Ok(count) => count,
646 Err(error) if error.kind() == std::io::ErrorKind::Interrupted => continue,
647 Err(error) => return Err(error),
648 };
649 hasher.update(&buffer[..count]);
650 total += count as u64;
651 }
652 Ok((hasher.finalize().into(), total))
653}
654
655const RESERVED_LIBRARY_NAMES: [&str; 2] = ["component.json", "component.sig"];
658
659fn safe_relative_path(value: &str) -> Result<PathBuf, ComponentError> {
660 let path = Path::new(value);
661 let safe = !path.as_os_str().is_empty()
662 && path
663 .components()
664 .all(|component| matches!(component, Component::Normal(_)))
665 && !RESERVED_LIBRARY_NAMES
666 .iter()
667 .any(|reserved| value.eq_ignore_ascii_case(reserved));
668 if safe {
669 Ok(path.to_owned())
670 } else {
671 Err(ComponentError::UnsafeLibraryPath(value.to_owned()))
672 }
673}
674
675const METADATA_ENTRY_SIZE_CEILING: u64 = 64 * 1024;
679const LIBRARY_SIZE_HEADROOM: u64 = 4096;
682const MAX_ARCHIVE_ENTRIES: usize = 3;
685
686fn extract_safely(reader: impl Read, destination: &Path) -> Result<(), ComponentError> {
698 let decoder = GzDecoder::new(reader);
699 let mut archive = tar::Archive::new(decoder);
700 let mut entries = archive.entries()?;
701
702 let mut first = entries
703 .next()
704 .ok_or_else(|| ComponentError::UnsafeArchiveEntry("archive is empty".to_owned()))??;
705 let first_path = first.path()?.into_owned();
706 if first_path != Path::new("component.json") || !first.header().entry_type().is_file() {
707 return Err(ComponentError::UnsafeArchiveEntry(first_path.display().to_string()));
708 }
709 let manifest_bytes = read_bounded_entry(&mut first, METADATA_ENTRY_SIZE_CEILING)?;
710 fs::write(destination.join("component.json"), &manifest_bytes)?;
711 let manifest: ComponentManifest = serde_json::from_slice(&manifest_bytes)?;
712 let library_relative = safe_relative_path(&manifest.library.file)?;
713 let library_ceiling = manifest.library.size.saturating_add(LIBRARY_SIZE_HEADROOM);
714
715 let mut seen_library = false;
716 let mut entry_count = 1_usize;
717 for entry in entries {
718 entry_count += 1;
719 if entry_count > MAX_ARCHIVE_ENTRIES {
720 return Err(ComponentError::TooManyArchiveEntries {
721 max: MAX_ARCHIVE_ENTRIES,
722 actual: entry_count,
723 });
724 }
725 let mut entry = entry?;
726 let path = entry.path()?.into_owned();
727 let is_safe_relative = !path.as_os_str().is_empty()
728 && path
729 .components()
730 .all(|component| matches!(component, Component::Normal(_)));
731 if !is_safe_relative || !entry.header().entry_type().is_file() {
732 return Err(ComponentError::UnsafeArchiveEntry(path.display().to_string()));
733 }
734 if path == Path::new("component.sig") {
735 let bytes = read_bounded_entry(&mut entry, METADATA_ENTRY_SIZE_CEILING)?;
736 fs::write(destination.join("component.sig"), bytes)?;
737 } else if path == library_relative && !seen_library {
738 seen_library = true;
739 stream_library_entry(&mut entry, destination, &library_relative, library_ceiling, &manifest)?;
740 } else {
741 return Err(ComponentError::UnsafeArchiveEntry(path.display().to_string()));
742 }
743 }
744 if !seen_library {
745 return Err(ComponentError::MissingLibrary(destination.join(&library_relative)));
746 }
747 Ok(())
748}
749
750fn read_bounded_entry<R: Read>(entry: &mut tar::Entry<'_, R>, ceiling: u64) -> Result<Vec<u8>, ComponentError> {
753 let declared = entry.header().size()?;
754 if declared > ceiling {
755 return Err(ComponentError::ExtractedSizeExceeded {
756 limit: ceiling,
757 actual: declared,
758 });
759 }
760 let mut buffer = Vec::new();
761 entry.read_to_end(&mut buffer)?;
762 Ok(buffer)
763}
764
765fn stream_library_entry<R: Read>(
769 entry: &mut tar::Entry<'_, R>,
770 destination: &Path,
771 relative: &Path,
772 ceiling: u64,
773 manifest: &ComponentManifest,
774) -> Result<(), ComponentError> {
775 let declared = entry.header().size()?;
776 if declared > ceiling {
777 return Err(ComponentError::ExtractedSizeExceeded {
778 limit: ceiling,
779 actual: declared,
780 });
781 }
782 let target = destination.join(relative);
783 if let Some(parent) = target.parent() {
784 fs::create_dir_all(parent)?;
785 }
786 let mut file = File::create(&target)?;
787 let mut hasher = Sha256::new();
788 let mut buffer = [0_u8; 64 * 1024];
789 let mut copied = 0_u64;
790 loop {
791 let count = entry.read(&mut buffer)?;
792 if count == 0 {
793 break;
794 }
795 copied += count as u64;
796 if copied > ceiling {
797 return Err(ComponentError::ExtractedSizeExceeded {
798 limit: ceiling,
799 actual: copied,
800 });
801 }
802 hasher.update(&buffer[..count]);
803 file.write_all(&buffer[..count])?;
804 }
805 if copied != manifest.library.size {
806 return Err(ComponentError::SizeMismatch {
807 expected: manifest.library.size,
808 actual: copied,
809 });
810 }
811 let actual: [u8; 32] = hasher.finalize().into();
812 let expected = decode_digest(&manifest.library.sha256)?;
813 if actual != expected {
814 return Err(ComponentError::DigestMismatch {
815 expected: manifest.library.sha256.clone(),
816 actual: hex::encode(actual),
817 });
818 }
819 Ok(())
820}
821
822#[cfg(test)]
823mod archive_tests;
824#[cfg(test)]
825mod signature_tests;
826#[cfg(test)]
827mod tests;