Skip to main content

alef_component_runtime/
cache.rs

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
18/// Rewrites a lock entry's download URL at runtime; see [`ArtifactCache::with_url_override`].
19pub(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/// Whether a component lock must carry signatures.
28///
29/// [`SignaturePolicy::AllowUnsigned`] (the default) keeps the historical behaviour: a lock with no
30/// public keys and entries with no `key_id` is verified by digest alone, which only proves the
31/// bytes match a lock that could itself have been edited. [`SignaturePolicy::Require`] makes
32/// [`crate::ComponentManager::from_lock_with_signature_policy`] reject such a lock and the cache
33/// refuse any artifact whose manifest signature it did not verify.
34#[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    /// With [`SignaturePolicy::Require`], refuse every artifact whose manifest signature was not
87    /// verified against a key in this cache's [`TrustPolicy::EmbeddedKeys`], instead of accepting
88    /// a digest-only lock entry.
89    #[must_use]
90    pub fn with_signature_policy(mut self, policy: SignaturePolicy) -> Self {
91        self.signatures = policy;
92        self
93    }
94
95    /// Replace the download tuning (timeouts, retries, progress, cancellation).
96    #[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    /// Fetch artifacts from `resolve(entry)` instead of the lock entry's own `url`.
108    ///
109    /// Intended for air-gapped or corporate mirrors. Integrity never depends on the URL: the
110    /// archive size, SHA-256 and the manifest signature are still checked against the lock.
111    /// A returned `file://` URL is read from disk.
112    #[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    /// Trust a verified stamp instead of re-hashing an installed library on every process
122    /// start. Off by default.
123    ///
124    /// After the first full check a stamp (archive sha, size, mtime in nanoseconds, and on Unix
125    /// device, inode and ctime) is written next to the object. A later process that finds the
126    /// library still matching the stamp skips reading and hashing it; the manifest digest,
127    /// identity and signature are still verified every time.
128    ///
129    /// Still caught: replacing the file (new inode), size changes, and edits that change the
130    /// mtime or, on Unix, the ctime. Not caught: a same-size in-place edit that restores the
131    /// mtime on Windows, or by an attacker who can forge Unix ctime. Anyone able to do that can
132    /// already rewrite the cache (including the stamp), so the stamp is honoured only while the
133    /// cache root and its object directory are owned by the current user and not writable by
134    /// group or others (Unix); otherwise every verification hashes the library. The cache creates
135    /// its directories `0700`.
136    #[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    /// Disable network downloads: [`Self::install`] fails a missing artifact with
150    /// [`ComponentError::Offline`] instead of attempting a request, and a damaged installed
151    /// artifact with [`ComponentError::CachedObjectInvalid`]. An artifact already verified on
152    /// disk (or served via a `file://` URL) is unaffected.
153    #[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    /// Verify an installed object in place: checks it against the lock entry (skipping the
169    /// library hash when a current verified stamp says it is unchanged) but never downloads or
170    /// removes anything, and writes nothing but the verified stamp when the cache was built with
171    /// [`Self::with_verified_stamp(true)`].
172    ///
173    /// Unlike [`Self::install`], a failing check is reported instead of repaired, and the error
174    /// says which check failed (digest, size, manifest, signature) -- so a caller can tell
175    /// "installed and damaged" apart from "never installed" and log or report a repair.
176    pub fn verify_cached(&self, entry: &ComponentLockEntry) -> Result<CachedArtifact, ComponentError> {
177        self.verify_cached_file(entry).map(|(cached, _)| cached)
178    }
179
180    /// [`Self::verify_cached`], also returning the open, verified library, which is what a caller
181    /// that loads or executes the artifact must use (see [`VerifiedFile`]).
182    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    /// [`Self::install`], also returning the open, verified library (see [`VerifiedFile`]).
196    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    /// One request-and-install attempt; the flag says whether a failure is worth retrying.
248    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    /// Install an archive from `reader`, honouring this cache's progress and cancellation
284    /// settings (see [`DownloadOptions`]). Never retries: the reader cannot be rewound.
285    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        // Windows refuses to rename a directory while a file inside it is open, whatever share
364        // mode the file was opened with (ERROR_ACCESS_DENIED), so the staging descriptor is closed
365        // before the rename and the library is verified again at its installed path below.
366        #[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        // A rename keeps the inode, so the descriptor verified in staging is the installed file.
380        #[cfg(not(windows))]
381        let verified = verified.relocated(library.clone());
382        // The staging descriptor was closed for the rename, so the returned descriptor is a fresh
383        // one, fully hashed (no stamp) under the digest lock this install still holds.
384        #[cfg(windows)]
385        let (_, verified) = self.verify_installation(entry, &destination, None)?;
386        // Stamped from the verified descriptor, not the path: a file swapped in after the rename
387        // must not inherit the stamp.
388        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    /// Open (creating it if needed) the per-digest lock file every install and removal of that
406    /// object holds. Lock files are never deleted: unlinking one while another process waits on
407    /// it would let a third process lock a fresh file at the same path, and two writers would
408    /// then each believe they hold the object exclusively.
409    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    /// Verify an object already in the cache, using the verified stamp when enabled.
423    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    /// Whether the verified stamp may be read and written: it was requested, and only the
433    /// current user can write the cache. A stamp in a directory others can write vouches for
434    /// nothing, so such a cache is fully re-verified every time instead (ADR-0027).
435    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        // Every check below reads the library through this one descriptor, and the caller loads
469        // or executes that same file (see `identity`), so swapping the path afterwards cannot
470        // substitute unverified code.
471        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            // Bounded one byte past the declared size, so a file that grew after the metadata
483            // check is caught as a size mismatch rather than hashed without limit.
484            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        // Record the stamp only when the file did not change while it was being hashed.
500        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        // `verify_strict`, as the CLI uses: plain `verify` accepts signatures made with a
564        // small-order public key, which match every message.
565        key.verify_strict(manifest_bytes, &signature)
566            .map_err(|_| ComponentError::SignatureVerification)
567    }
568}
569
570/// Create `path` and any missing parents readable and writable only by the current user. Existing
571/// directories keep their permissions; [`is_private_dir`] decides what the cache trusts in them.
572fn 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
584/// Whether `path` is a directory owned by the current user that neither its group nor others can
585/// write. On non-Unix platforms permissions are ACLs this does not inspect, so it trusts the
586/// per-user cache location (`%LOCALAPPDATA%`) the host chose.
587pub(crate) fn is_private_dir(path: &Path) -> bool {
588    #[cfg(unix)]
589    {
590        use std::os::unix::fs::MetadataExt as _;
591        // SAFETY: `geteuid` takes no arguments, cannot fail and touches no memory.
592        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
602/// `entry` with its archive digest in lower case. Hex is case-insensitive, and the digest names the
603/// object's directory, lock and stamp, so one object must have one spelling: an upper-case lock
604/// entry would otherwise install a second copy beside the first, under a different lock.
605pub(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
616/// The lower-case spelling of a hex digest, after checking it is one.
617pub(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
633/// Size of the read buffer used to hash installed libraries.
634const HASH_CHUNK: usize = 64 * 1024;
635
636/// SHA-256 of everything `reader` yields, read in [`HASH_CHUNK`] pieces so a large library is
637/// never held in memory whole. Returns the digest and the number of bytes hashed.
638fn 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
655/// Names the archive's own metadata files occupy; a library under either would overwrite one
656/// during extraction. Compared case-insensitively for case-insensitive file systems.
657const 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
675/// Generous ceiling for the manifest and signature entries: both are small JSON documents,
676/// orders of magnitude smaller than any native component library, so a declared size above
677/// this already means the archive is not one `alef component package` produced.
678const METADATA_ENTRY_SIZE_CEILING: u64 = 64 * 1024;
679/// Headroom added to the manifest's declared library size before an oversized decompressed
680/// library entry is rejected, covering tar block padding around the real content.
681const LIBRARY_SIZE_HEADROOM: u64 = 4096;
682/// `alef component package` always writes at most three archive entries: the manifest, an
683/// optional signature, and the library. Anything else is not an archive this loader made.
684const MAX_ARCHIVE_ENTRIES: usize = 3;
685
686/// Extract a downloaded component archive, bounding how much a corrupted or malicious
687/// archive can force this to decompress, and rejecting anything that is not exactly the
688/// shape `alef component package` produces.
689///
690/// The manifest must be the first entry (`component.json`) because its declared
691/// `library.size` is what bounds the decompressed size of the library entry that follows --
692/// without reading it first there is nothing to size the library entry's ceiling against,
693/// and an attacker-supplied archive could otherwise reorder entries to smuggle an oversized
694/// library past a check performed too late. Every entry must be a regular file at a safe
695/// relative path (no absolute paths, `..`, or symlinks/hardlinks), and the total entry count
696/// is capped so a maliciously padded archive cannot force unbounded header parsing either.
697fn 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
750/// Read a small, fully-buffered entry (the manifest or its signature), rejecting it before
751/// any bytes are copied if its declared size already exceeds `ceiling`.
752fn 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
765/// Stream the library entry straight to disk in fixed-size chunks -- rather than buffering
766/// the whole (potentially large) decompressed library in memory -- hashing it as it is
767/// written so the digest is verified in the same pass instead of a second read from disk.
768fn 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;