1use crate::download::{DownloadOptions, TrackedReader, is_transient_request_error};
2use crate::keys::decode_public_key;
3use crate::manifest::{COMPONENT_ABI_VERSION, COMPONENT_MANIFEST_SCHEMA};
4use crate::stamp;
5use crate::{ComponentError, ComponentLockEntry, ComponentManifest, ComponentSignature};
6use base64::Engine as _;
7use ed25519_dalek::{Signature, Verifier as _};
8use flate2::read::GzDecoder;
9use fs2::FileExt as _;
10use sha2::{Digest as _, Sha256};
11use std::collections::BTreeMap;
12use std::fs::{self, File, OpenOptions};
13use std::io::{Read, Seek as _, SeekFrom, Write as _};
14use std::path::{Component, Path, PathBuf};
15use std::sync::Arc;
16
17pub(crate) type UrlOverride = Arc<dyn Fn(&ComponentLockEntry) -> String + Send + Sync>;
19
20#[derive(Clone, Debug)]
21pub enum TrustPolicy {
22 DigestOnly,
23 EmbeddedKeys(BTreeMap<String, String>),
24}
25
26#[derive(Clone)]
27pub struct ArtifactCache {
28 pub(crate) root: PathBuf,
29 trust: TrustPolicy,
30 offline: bool,
31 pub(crate) download: DownloadOptions,
32 url_override: Option<UrlOverride>,
33 verified_stamp: bool,
34}
35
36impl std::fmt::Debug for ArtifactCache {
37 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
38 f.debug_struct("ArtifactCache")
39 .field("root", &self.root)
40 .field("trust", &self.trust)
41 .field("offline", &self.offline)
42 .field("download", &self.download)
43 .field("url_override", &self.url_override.as_ref().map(|_| "<fn>"))
44 .field("verified_stamp", &self.verified_stamp)
45 .finish()
46 }
47}
48
49#[derive(Clone, Debug, PartialEq, Eq)]
50pub struct CachedArtifact {
51 pub root: PathBuf,
52 pub library: PathBuf,
53 pub manifest: ComponentManifest,
54}
55
56impl ArtifactCache {
57 pub fn new(root: impl Into<PathBuf>, trust: TrustPolicy) -> Self {
58 Self {
59 root: root.into(),
60 trust,
61 offline: false,
62 download: DownloadOptions::default(),
63 url_override: None,
64 verified_stamp: false,
65 }
66 }
67
68 #[must_use]
70 pub fn with_download_options(mut self, options: DownloadOptions) -> Self {
71 self.download = options;
72 self
73 }
74
75 #[must_use]
76 pub fn download_options(&self) -> &DownloadOptions {
77 &self.download
78 }
79
80 #[must_use]
86 pub fn with_url_override(
87 mut self,
88 resolve: impl Fn(&ComponentLockEntry) -> String + Send + Sync + 'static,
89 ) -> Self {
90 self.url_override = Some(Arc::new(resolve));
91 self
92 }
93
94 #[must_use]
108 pub fn with_verified_stamp(mut self, enabled: bool) -> Self {
109 self.verified_stamp = enabled;
110 self
111 }
112
113 fn resolve_url(&self, entry: &ComponentLockEntry) -> String {
114 match &self.url_override {
115 Some(resolve) => resolve(entry),
116 None => entry.url.clone(),
117 }
118 }
119
120 #[must_use]
125 pub fn offline(mut self, offline: bool) -> Self {
126 self.offline = offline;
127 self
128 }
129
130 #[must_use]
131 pub fn root(&self) -> &Path {
132 &self.root
133 }
134
135 pub fn object_path(&self, entry: &ComponentLockEntry) -> Result<PathBuf, ComponentError> {
136 decode_digest(&entry.sha256)?;
137 Ok(self.root.join("sha256").join(&entry.sha256))
138 }
139
140 pub fn verify_cached(&self, entry: &ComponentLockEntry) -> Result<CachedArtifact, ComponentError> {
149 let destination = self.object_path(entry)?;
150 self.verify_cached_at(entry, &destination)
151 }
152
153 pub fn install(&self, entry: &ComponentLockEntry) -> Result<CachedArtifact, ComponentError> {
154 let destination = self.object_path(entry)?;
155 let mut damaged = None;
156 if destination.is_dir() {
157 match self.verify_cached_at(entry, &destination) {
158 Ok(cached) => {
159 self.touch_used(&entry.sha256);
160 return Ok(cached);
161 }
162 Err(error) => damaged = Some(error),
163 }
164 }
165 let url = self.resolve_url(entry);
166 if let Some(path) = url.strip_prefix("file://") {
167 return self.install_from_reader(entry, File::open(path)?);
168 }
169 if self.offline {
170 return match damaged {
171 Some(source) => Err(ComponentError::CachedObjectInvalid {
172 component: entry.identity.component.clone(),
173 source: Box::new(source),
174 }),
175 None => Err(ComponentError::Offline {
176 component: entry.identity.component.clone(),
177 url,
178 }),
179 };
180 }
181 let attempts = self.download.max_attempts.max(1);
182 let mut attempt = 1;
183 loop {
184 if self.download.is_cancelled() {
185 return Err(ComponentError::Cancelled);
186 }
187 let (error, transient) = match self.download_once(entry, &url) {
188 Ok(cached) => return Ok(cached),
189 Err(failure) => failure,
190 };
191 if !transient || attempt >= attempts {
192 return Err(error);
193 }
194 std::thread::sleep(self.download.backoff_delay(attempt));
195 attempt += 1;
196 }
197 }
198
199 fn download_once(&self, entry: &ComponentLockEntry, url: &str) -> Result<CachedArtifact, (ComponentError, bool)> {
201 let tls = self.download.tls_config(url).map_err(|error| (error, false))?;
202 let response = ureq::get(url)
203 .config()
204 .tls_config(tls)
205 .timeout_connect(Some(self.download.connect_timeout))
206 .timeout_global(Some(self.download.total_timeout))
207 .build()
208 .header(
209 "User-Agent",
210 concat!("alef-component-runtime/", env!("CARGO_PKG_VERSION")),
211 )
212 .call()
213 .map_err(|error| {
214 let transient = is_transient_request_error(&error);
215 (
216 ComponentError::Download {
217 url: url.to_owned(),
218 message: error.to_string(),
219 },
220 transient,
221 )
222 })?;
223 let mut body = TrackedReader::new(response.into_body().into_reader());
224 let result = self.install_from_reader(entry, &mut body);
225 result.map_err(|error| {
226 let transient = body.read_failed && matches!(error, ComponentError::Io(_));
227 (error, transient)
228 })
229 }
230
231 pub fn install_from_reader(
234 &self,
235 entry: &ComponentLockEntry,
236 reader: impl Read,
237 ) -> Result<CachedArtifact, ComponentError> {
238 let cached = self.install_stream(entry, reader)?;
239 self.touch_used(&entry.sha256);
240 Ok(cached)
241 }
242
243 fn install_stream(
244 &self,
245 entry: &ComponentLockEntry,
246 mut reader: impl Read,
247 ) -> Result<CachedArtifact, ComponentError> {
248 let expected = decode_digest(&entry.sha256)?;
249 let objects = self.root.join("sha256");
250 fs::create_dir_all(&objects)?;
251 let lock_path = objects.join(format!("{}.lock", entry.sha256));
252 let lock = OpenOptions::new()
253 .read(true)
254 .write(true)
255 .create(true)
256 .truncate(false)
257 .open(lock_path)?;
258 lock.lock_exclusive()?;
259
260 let destination = self.object_path(entry)?;
261 if destination.is_dir()
262 && let Ok(cached) = self.verify_cached_at(entry, &destination)
263 {
264 return Ok(cached);
265 }
266
267 let mut archive = tempfile::NamedTempFile::new_in(&objects)?;
268 let mut hasher = Sha256::new();
269 let mut copied = 0_u64;
270 let mut buffer = [0_u8; 64 * 1024];
271 loop {
272 if self.download.is_cancelled() {
273 return Err(ComponentError::Cancelled);
274 }
275 let count = reader.read(&mut buffer)?;
276 if count == 0 {
277 break;
278 }
279 archive.write_all(&buffer[..count])?;
280 hasher.update(&buffer[..count]);
281 copied += count as u64;
282 if copied > entry.size {
283 return Err(ComponentError::SizeMismatch {
284 expected: entry.size,
285 actual: copied,
286 });
287 }
288 self.download.report(copied, entry.size);
289 }
290 if entry.size != copied {
291 return Err(ComponentError::SizeMismatch {
292 expected: entry.size,
293 actual: copied,
294 });
295 }
296 let actual: [u8; 32] = hasher.finalize().into();
297 if actual != expected {
298 return Err(ComponentError::DigestMismatch {
299 expected: entry.sha256.clone(),
300 actual: hex::encode(actual),
301 });
302 }
303
304 archive.as_file_mut().seek(SeekFrom::Start(0))?;
305 let staging = tempfile::Builder::new().prefix(".install-").tempdir_in(&objects)?;
306 extract_safely(archive.as_file_mut(), staging.path())?;
307 let cached = self.verify_installation(entry, staging.path(), None)?;
308
309 if destination.exists() {
310 fs::remove_dir_all(&destination)?;
311 }
312 let _ = fs::remove_file(self.stamp_path(&entry.sha256));
313 let staging_path = staging.keep();
314 if let Err(error) = fs::rename(&staging_path, &destination) {
315 let _ = fs::remove_dir_all(&staging_path);
316 return Err(ComponentError::Io(error));
317 }
318 let library = destination.join(&cached.manifest.library.file);
319 if self.verified_stamp
320 && let Ok(stamp) = stamp::capture(&entry.sha256, &library)
321 {
322 stamp::write(&self.stamp_path(&entry.sha256), &stamp);
323 }
324 Ok(CachedArtifact {
325 root: destination.clone(),
326 library,
327 manifest: cached.manifest,
328 })
329 }
330
331 pub(crate) fn stamp_path(&self, sha256: &str) -> PathBuf {
332 self.root.join("sha256").join(format!("{sha256}.verified"))
333 }
334
335 fn verify_cached_at(&self, entry: &ComponentLockEntry, root: &Path) -> Result<CachedArtifact, ComponentError> {
337 let stamp_path = self.stamp_path(&entry.sha256);
338 self.verify_installation(entry, root, self.verified_stamp.then_some(stamp_path.as_path()))
339 }
340
341 fn verify_installation(
342 &self,
343 entry: &ComponentLockEntry,
344 root: &Path,
345 stamp_path: Option<&Path>,
346 ) -> Result<CachedArtifact, ComponentError> {
347 let manifest_bytes = fs::read(root.join("component.json"))?;
348 if sha256(&manifest_bytes) != decode_digest(&entry.manifest_sha256)? {
349 return Err(ComponentError::ManifestDigestMismatch);
350 }
351 let manifest: ComponentManifest = serde_json::from_slice(&manifest_bytes)?;
352 if manifest.canonical_bytes()? != manifest_bytes {
353 return Err(ComponentError::NonCanonicalManifest);
354 }
355 if manifest.schema_version != COMPONENT_MANIFEST_SCHEMA || manifest.abi_version != COMPONENT_ABI_VERSION {
356 return Err(ComponentError::UnsupportedManifest);
357 }
358 if manifest.identity != entry.identity {
359 return Err(ComponentError::ManifestIdentityMismatch);
360 }
361 let library_relative = safe_relative_path(&manifest.library.file)?;
362 let library = root.join(&library_relative);
363 let trusted = stamp_path.is_some_and(|path| stamp::is_current(path, &entry.sha256, &library));
364 let before = if trusted || stamp_path.is_none() {
365 None
366 } else {
367 stamp::capture(&entry.sha256, &library).ok()
368 };
369 let missing = |error: std::io::Error| {
370 if error.kind() == std::io::ErrorKind::NotFound {
371 ComponentError::MissingLibrary(library.clone())
372 } else {
373 ComponentError::Io(error)
374 }
375 };
376 if trusted {
377 let size = fs::metadata(&library).map_err(missing)?.len();
378 if size != manifest.library.size {
379 return Err(ComponentError::SizeMismatch {
380 expected: manifest.library.size,
381 actual: size,
382 });
383 }
384 } else {
385 let library_bytes = fs::read(&library).map_err(missing)?;
386 if library_bytes.len() as u64 != manifest.library.size {
387 return Err(ComponentError::SizeMismatch {
388 expected: manifest.library.size,
389 actual: library_bytes.len() as u64,
390 });
391 }
392 let expected_library = decode_digest(&manifest.library.sha256)?;
393 let actual_library = sha256(&library_bytes);
394 if expected_library != actual_library {
395 return Err(ComponentError::DigestMismatch {
396 expected: manifest.library.sha256.clone(),
397 actual: hex::encode(actual_library),
398 });
399 }
400 }
401 self.verify_manifest_signature(entry, root, &manifest_bytes)?;
402 if let (Some(path), Some(before)) = (stamp_path, before)
404 && stamp::capture(&entry.sha256, &library).is_ok_and(|after| after == before)
405 {
406 stamp::write(path, &before);
407 }
408 Ok(CachedArtifact {
409 root: root.to_owned(),
410 library,
411 manifest,
412 })
413 }
414
415 fn verify_manifest_signature(
416 &self,
417 entry: &ComponentLockEntry,
418 root: &Path,
419 manifest_bytes: &[u8],
420 ) -> Result<(), ComponentError> {
421 let TrustPolicy::EmbeddedKeys(keys) = &self.trust else {
422 return Ok(());
423 };
424 if entry.key_id.is_empty() && keys.is_empty() {
425 return Ok(());
426 }
427 let signature_bytes = fs::read(root.join("component.sig")).map_err(|error| {
428 if error.kind() == std::io::ErrorKind::NotFound {
429 ComponentError::SignatureRequired
430 } else {
431 ComponentError::Io(error)
432 }
433 })?;
434 let signature: ComponentSignature = serde_json::from_slice(&signature_bytes)?;
435 if signature.algorithm != "ed25519" {
436 return Err(ComponentError::UnsupportedSignatureAlgorithm(signature.algorithm));
437 }
438 if signature.key_id != entry.key_id {
439 return Err(ComponentError::SignatureKeyMismatch);
440 }
441 let encoded_key = keys
442 .get(&signature.key_id)
443 .ok_or_else(|| ComponentError::UnknownSignatureKey(signature.key_id.clone()))?;
444 let key = decode_public_key(encoded_key)?;
445 let raw_signature = base64::engine::general_purpose::STANDARD
446 .decode(&signature.signature)
447 .map_err(|_| ComponentError::InvalidSignatureEncoding)?;
448 let signature = Signature::from_slice(&raw_signature).map_err(|_| ComponentError::InvalidSignatureEncoding)?;
449 key.verify(manifest_bytes, &signature)
450 .map_err(|_| ComponentError::SignatureVerification)
451 }
452}
453
454pub(crate) fn decode_digest(value: &str) -> Result<[u8; 32], ComponentError> {
455 let bytes = hex::decode(value).map_err(|_| ComponentError::InvalidDigest(value.to_owned()))?;
456 bytes
457 .try_into()
458 .map_err(|_| ComponentError::InvalidDigest(value.to_owned()))
459}
460
461fn sha256(bytes: &[u8]) -> [u8; 32] {
462 Sha256::digest(bytes).into()
463}
464
465fn safe_relative_path(value: &str) -> Result<PathBuf, ComponentError> {
466 let path = Path::new(value);
467 let safe = !path.as_os_str().is_empty()
468 && path
469 .components()
470 .all(|component| matches!(component, Component::Normal(_)));
471 if safe {
472 Ok(path.to_owned())
473 } else {
474 Err(ComponentError::UnsafeLibraryPath(value.to_owned()))
475 }
476}
477
478const METADATA_ENTRY_SIZE_CEILING: u64 = 64 * 1024;
482const LIBRARY_SIZE_HEADROOM: u64 = 4096;
485const MAX_ARCHIVE_ENTRIES: usize = 3;
488
489fn extract_safely(reader: impl Read, destination: &Path) -> Result<(), ComponentError> {
501 let decoder = GzDecoder::new(reader);
502 let mut archive = tar::Archive::new(decoder);
503 let mut entries = archive.entries()?;
504
505 let mut first = entries
506 .next()
507 .ok_or_else(|| ComponentError::UnsafeArchiveEntry("archive is empty".to_owned()))??;
508 let first_path = first.path()?.into_owned();
509 if first_path != Path::new("component.json") || !first.header().entry_type().is_file() {
510 return Err(ComponentError::UnsafeArchiveEntry(first_path.display().to_string()));
511 }
512 let manifest_bytes = read_bounded_entry(&mut first, METADATA_ENTRY_SIZE_CEILING)?;
513 fs::write(destination.join("component.json"), &manifest_bytes)?;
514 let manifest: ComponentManifest = serde_json::from_slice(&manifest_bytes)?;
515 let library_relative = safe_relative_path(&manifest.library.file)?;
516 let library_ceiling = manifest.library.size.saturating_add(LIBRARY_SIZE_HEADROOM);
517
518 let mut seen_library = false;
519 let mut entry_count = 1_usize;
520 for entry in entries {
521 entry_count += 1;
522 if entry_count > MAX_ARCHIVE_ENTRIES {
523 return Err(ComponentError::TooManyArchiveEntries {
524 max: MAX_ARCHIVE_ENTRIES,
525 actual: entry_count,
526 });
527 }
528 let mut entry = entry?;
529 let path = entry.path()?.into_owned();
530 let is_safe_relative = !path.as_os_str().is_empty()
531 && path
532 .components()
533 .all(|component| matches!(component, Component::Normal(_)));
534 if !is_safe_relative || !entry.header().entry_type().is_file() {
535 return Err(ComponentError::UnsafeArchiveEntry(path.display().to_string()));
536 }
537 if path == Path::new("component.sig") {
538 let bytes = read_bounded_entry(&mut entry, METADATA_ENTRY_SIZE_CEILING)?;
539 fs::write(destination.join("component.sig"), bytes)?;
540 } else if path == library_relative && !seen_library {
541 seen_library = true;
542 stream_library_entry(&mut entry, destination, &library_relative, library_ceiling, &manifest)?;
543 } else {
544 return Err(ComponentError::UnsafeArchiveEntry(path.display().to_string()));
545 }
546 }
547 if !seen_library {
548 return Err(ComponentError::MissingLibrary(destination.join(&library_relative)));
549 }
550 Ok(())
551}
552
553fn read_bounded_entry<R: Read>(entry: &mut tar::Entry<'_, R>, ceiling: u64) -> Result<Vec<u8>, ComponentError> {
556 let declared = entry.header().size()?;
557 if declared > ceiling {
558 return Err(ComponentError::ExtractedSizeExceeded {
559 limit: ceiling,
560 actual: declared,
561 });
562 }
563 let mut buffer = Vec::new();
564 entry.read_to_end(&mut buffer)?;
565 Ok(buffer)
566}
567
568fn stream_library_entry<R: Read>(
572 entry: &mut tar::Entry<'_, R>,
573 destination: &Path,
574 relative: &Path,
575 ceiling: u64,
576 manifest: &ComponentManifest,
577) -> Result<(), ComponentError> {
578 let declared = entry.header().size()?;
579 if declared > ceiling {
580 return Err(ComponentError::ExtractedSizeExceeded {
581 limit: ceiling,
582 actual: declared,
583 });
584 }
585 let target = destination.join(relative);
586 if let Some(parent) = target.parent() {
587 fs::create_dir_all(parent)?;
588 }
589 let mut file = File::create(&target)?;
590 let mut hasher = Sha256::new();
591 let mut buffer = [0_u8; 64 * 1024];
592 let mut copied = 0_u64;
593 loop {
594 let count = entry.read(&mut buffer)?;
595 if count == 0 {
596 break;
597 }
598 copied += count as u64;
599 if copied > ceiling {
600 return Err(ComponentError::ExtractedSizeExceeded {
601 limit: ceiling,
602 actual: copied,
603 });
604 }
605 hasher.update(&buffer[..count]);
606 file.write_all(&buffer[..count])?;
607 }
608 if copied != manifest.library.size {
609 return Err(ComponentError::SizeMismatch {
610 expected: manifest.library.size,
611 actual: copied,
612 });
613 }
614 let actual: [u8; 32] = hasher.finalize().into();
615 let expected = decode_digest(&manifest.library.sha256)?;
616 if actual != expected {
617 return Err(ComponentError::DigestMismatch {
618 expected: manifest.library.sha256.clone(),
619 actual: hex::encode(actual),
620 });
621 }
622 Ok(())
623}
624
625#[cfg(test)]
626mod tests;