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]
124 pub fn offline(mut self, offline: bool) -> Self {
125 self.offline = offline;
126 self
127 }
128
129 #[must_use]
130 pub fn root(&self) -> &Path {
131 &self.root
132 }
133
134 pub fn object_path(&self, entry: &ComponentLockEntry) -> Result<PathBuf, ComponentError> {
135 decode_digest(&entry.sha256)?;
136 Ok(self.root.join("sha256").join(&entry.sha256))
137 }
138
139 pub fn install(&self, entry: &ComponentLockEntry) -> Result<CachedArtifact, ComponentError> {
140 let destination = self.object_path(entry)?;
141 if destination.is_dir()
142 && let Ok(cached) = self.verify_cached(entry, &destination)
143 {
144 self.touch_used(&entry.sha256);
145 return Ok(cached);
146 }
147 let url = self.resolve_url(entry);
148 if let Some(path) = url.strip_prefix("file://") {
149 return self.install_from_reader(entry, File::open(path)?);
150 }
151 if self.offline {
152 return Err(ComponentError::Offline {
153 component: entry.identity.component.clone(),
154 url,
155 });
156 }
157 let attempts = self.download.max_attempts.max(1);
158 let mut attempt = 1;
159 loop {
160 if self.download.is_cancelled() {
161 return Err(ComponentError::Cancelled);
162 }
163 let (error, transient) = match self.download_once(entry, &url) {
164 Ok(cached) => return Ok(cached),
165 Err(failure) => failure,
166 };
167 if !transient || attempt >= attempts {
168 return Err(error);
169 }
170 std::thread::sleep(self.download.backoff_delay(attempt));
171 attempt += 1;
172 }
173 }
174
175 fn download_once(&self, entry: &ComponentLockEntry, url: &str) -> Result<CachedArtifact, (ComponentError, bool)> {
177 let tls = self.download.tls_config(url).map_err(|error| (error, false))?;
178 let response = ureq::get(url)
179 .config()
180 .tls_config(tls)
181 .timeout_connect(Some(self.download.connect_timeout))
182 .timeout_global(Some(self.download.total_timeout))
183 .build()
184 .header(
185 "User-Agent",
186 concat!("alef-component-runtime/", env!("CARGO_PKG_VERSION")),
187 )
188 .call()
189 .map_err(|error| {
190 let transient = is_transient_request_error(&error);
191 (
192 ComponentError::Download {
193 url: url.to_owned(),
194 message: error.to_string(),
195 },
196 transient,
197 )
198 })?;
199 let mut body = TrackedReader::new(response.into_body().into_reader());
200 let result = self.install_from_reader(entry, &mut body);
201 result.map_err(|error| {
202 let transient = body.read_failed && matches!(error, ComponentError::Io(_));
203 (error, transient)
204 })
205 }
206
207 pub fn install_from_reader(
210 &self,
211 entry: &ComponentLockEntry,
212 reader: impl Read,
213 ) -> Result<CachedArtifact, ComponentError> {
214 let cached = self.install_stream(entry, reader)?;
215 self.touch_used(&entry.sha256);
216 Ok(cached)
217 }
218
219 fn install_stream(
220 &self,
221 entry: &ComponentLockEntry,
222 mut reader: impl Read,
223 ) -> Result<CachedArtifact, ComponentError> {
224 let expected = decode_digest(&entry.sha256)?;
225 let objects = self.root.join("sha256");
226 fs::create_dir_all(&objects)?;
227 let lock_path = objects.join(format!("{}.lock", entry.sha256));
228 let lock = OpenOptions::new()
229 .read(true)
230 .write(true)
231 .create(true)
232 .truncate(false)
233 .open(lock_path)?;
234 lock.lock_exclusive()?;
235
236 let destination = self.object_path(entry)?;
237 if destination.is_dir()
238 && let Ok(cached) = self.verify_cached(entry, &destination)
239 {
240 return Ok(cached);
241 }
242
243 let mut archive = tempfile::NamedTempFile::new_in(&objects)?;
244 let mut hasher = Sha256::new();
245 let mut copied = 0_u64;
246 let mut buffer = [0_u8; 64 * 1024];
247 loop {
248 if self.download.is_cancelled() {
249 return Err(ComponentError::Cancelled);
250 }
251 let count = reader.read(&mut buffer)?;
252 if count == 0 {
253 break;
254 }
255 archive.write_all(&buffer[..count])?;
256 hasher.update(&buffer[..count]);
257 copied += count as u64;
258 if copied > entry.size {
259 return Err(ComponentError::SizeMismatch {
260 expected: entry.size,
261 actual: copied,
262 });
263 }
264 self.download.report(copied, entry.size);
265 }
266 if entry.size != copied {
267 return Err(ComponentError::SizeMismatch {
268 expected: entry.size,
269 actual: copied,
270 });
271 }
272 let actual: [u8; 32] = hasher.finalize().into();
273 if actual != expected {
274 return Err(ComponentError::DigestMismatch {
275 expected: entry.sha256.clone(),
276 actual: hex::encode(actual),
277 });
278 }
279
280 archive.as_file_mut().seek(SeekFrom::Start(0))?;
281 let staging = tempfile::Builder::new().prefix(".install-").tempdir_in(&objects)?;
282 extract_safely(archive.as_file_mut(), staging.path())?;
283 let cached = self.verify_installation(entry, staging.path(), None)?;
284
285 if destination.exists() {
286 fs::remove_dir_all(&destination)?;
287 }
288 let _ = fs::remove_file(self.stamp_path(&entry.sha256));
289 let staging_path = staging.keep();
290 if let Err(error) = fs::rename(&staging_path, &destination) {
291 let _ = fs::remove_dir_all(&staging_path);
292 return Err(ComponentError::Io(error));
293 }
294 let library = destination.join(&cached.manifest.library.file);
295 if self.verified_stamp
296 && let Ok(stamp) = stamp::capture(&entry.sha256, &library)
297 {
298 stamp::write(&self.stamp_path(&entry.sha256), &stamp);
299 }
300 Ok(CachedArtifact {
301 root: destination.clone(),
302 library,
303 manifest: cached.manifest,
304 })
305 }
306
307 pub(crate) fn stamp_path(&self, sha256: &str) -> PathBuf {
308 self.root.join("sha256").join(format!("{sha256}.verified"))
309 }
310
311 fn verify_cached(&self, entry: &ComponentLockEntry, root: &Path) -> Result<CachedArtifact, ComponentError> {
313 let stamp_path = self.stamp_path(&entry.sha256);
314 self.verify_installation(entry, root, self.verified_stamp.then_some(stamp_path.as_path()))
315 }
316
317 fn verify_installation(
318 &self,
319 entry: &ComponentLockEntry,
320 root: &Path,
321 stamp_path: Option<&Path>,
322 ) -> Result<CachedArtifact, ComponentError> {
323 let manifest_bytes = fs::read(root.join("component.json"))?;
324 if sha256(&manifest_bytes) != decode_digest(&entry.manifest_sha256)? {
325 return Err(ComponentError::ManifestDigestMismatch);
326 }
327 let manifest: ComponentManifest = serde_json::from_slice(&manifest_bytes)?;
328 if manifest.canonical_bytes()? != manifest_bytes {
329 return Err(ComponentError::NonCanonicalManifest);
330 }
331 if manifest.schema_version != COMPONENT_MANIFEST_SCHEMA || manifest.abi_version != COMPONENT_ABI_VERSION {
332 return Err(ComponentError::UnsupportedManifest);
333 }
334 if manifest.identity != entry.identity {
335 return Err(ComponentError::ManifestIdentityMismatch);
336 }
337 let library_relative = safe_relative_path(&manifest.library.file)?;
338 let library = root.join(&library_relative);
339 let trusted = stamp_path.is_some_and(|path| stamp::is_current(path, &entry.sha256, &library));
340 let before = if trusted || stamp_path.is_none() {
341 None
342 } else {
343 stamp::capture(&entry.sha256, &library).ok()
344 };
345 let missing = |error: std::io::Error| {
346 if error.kind() == std::io::ErrorKind::NotFound {
347 ComponentError::MissingLibrary(library.clone())
348 } else {
349 ComponentError::Io(error)
350 }
351 };
352 if trusted {
353 let size = fs::metadata(&library).map_err(missing)?.len();
354 if size != manifest.library.size {
355 return Err(ComponentError::SizeMismatch {
356 expected: manifest.library.size,
357 actual: size,
358 });
359 }
360 } else {
361 let library_bytes = fs::read(&library).map_err(missing)?;
362 if library_bytes.len() as u64 != manifest.library.size {
363 return Err(ComponentError::SizeMismatch {
364 expected: manifest.library.size,
365 actual: library_bytes.len() as u64,
366 });
367 }
368 let expected_library = decode_digest(&manifest.library.sha256)?;
369 let actual_library = sha256(&library_bytes);
370 if expected_library != actual_library {
371 return Err(ComponentError::DigestMismatch {
372 expected: manifest.library.sha256.clone(),
373 actual: hex::encode(actual_library),
374 });
375 }
376 }
377 self.verify_manifest_signature(entry, root, &manifest_bytes)?;
378 if let (Some(path), Some(before)) = (stamp_path, before)
380 && stamp::capture(&entry.sha256, &library).is_ok_and(|after| after == before)
381 {
382 stamp::write(path, &before);
383 }
384 Ok(CachedArtifact {
385 root: root.to_owned(),
386 library,
387 manifest,
388 })
389 }
390
391 fn verify_manifest_signature(
392 &self,
393 entry: &ComponentLockEntry,
394 root: &Path,
395 manifest_bytes: &[u8],
396 ) -> Result<(), ComponentError> {
397 let TrustPolicy::EmbeddedKeys(keys) = &self.trust else {
398 return Ok(());
399 };
400 if entry.key_id.is_empty() && keys.is_empty() {
401 return Ok(());
402 }
403 let signature_bytes = fs::read(root.join("component.sig")).map_err(|error| {
404 if error.kind() == std::io::ErrorKind::NotFound {
405 ComponentError::SignatureRequired
406 } else {
407 ComponentError::Io(error)
408 }
409 })?;
410 let signature: ComponentSignature = serde_json::from_slice(&signature_bytes)?;
411 if signature.algorithm != "ed25519" {
412 return Err(ComponentError::UnsupportedSignatureAlgorithm(signature.algorithm));
413 }
414 if signature.key_id != entry.key_id {
415 return Err(ComponentError::SignatureKeyMismatch);
416 }
417 let encoded_key = keys
418 .get(&signature.key_id)
419 .ok_or_else(|| ComponentError::UnknownSignatureKey(signature.key_id.clone()))?;
420 let key = decode_public_key(encoded_key)?;
421 let raw_signature = base64::engine::general_purpose::STANDARD
422 .decode(&signature.signature)
423 .map_err(|_| ComponentError::InvalidSignatureEncoding)?;
424 let signature = Signature::from_slice(&raw_signature).map_err(|_| ComponentError::InvalidSignatureEncoding)?;
425 key.verify(manifest_bytes, &signature)
426 .map_err(|_| ComponentError::SignatureVerification)
427 }
428}
429
430pub(crate) fn decode_digest(value: &str) -> Result<[u8; 32], ComponentError> {
431 let bytes = hex::decode(value).map_err(|_| ComponentError::InvalidDigest(value.to_owned()))?;
432 bytes
433 .try_into()
434 .map_err(|_| ComponentError::InvalidDigest(value.to_owned()))
435}
436
437fn sha256(bytes: &[u8]) -> [u8; 32] {
438 Sha256::digest(bytes).into()
439}
440
441fn safe_relative_path(value: &str) -> Result<PathBuf, ComponentError> {
442 let path = Path::new(value);
443 let safe = !path.as_os_str().is_empty()
444 && path
445 .components()
446 .all(|component| matches!(component, Component::Normal(_)));
447 if safe {
448 Ok(path.to_owned())
449 } else {
450 Err(ComponentError::UnsafeLibraryPath(value.to_owned()))
451 }
452}
453
454const METADATA_ENTRY_SIZE_CEILING: u64 = 64 * 1024;
458const LIBRARY_SIZE_HEADROOM: u64 = 4096;
461const MAX_ARCHIVE_ENTRIES: usize = 3;
464
465fn extract_safely(reader: impl Read, destination: &Path) -> Result<(), ComponentError> {
477 let decoder = GzDecoder::new(reader);
478 let mut archive = tar::Archive::new(decoder);
479 let mut entries = archive.entries()?;
480
481 let mut first = entries
482 .next()
483 .ok_or_else(|| ComponentError::UnsafeArchiveEntry("archive is empty".to_owned()))??;
484 let first_path = first.path()?.into_owned();
485 if first_path != Path::new("component.json") || !first.header().entry_type().is_file() {
486 return Err(ComponentError::UnsafeArchiveEntry(first_path.display().to_string()));
487 }
488 let manifest_bytes = read_bounded_entry(&mut first, METADATA_ENTRY_SIZE_CEILING)?;
489 fs::write(destination.join("component.json"), &manifest_bytes)?;
490 let manifest: ComponentManifest = serde_json::from_slice(&manifest_bytes)?;
491 let library_relative = safe_relative_path(&manifest.library.file)?;
492 let library_ceiling = manifest.library.size.saturating_add(LIBRARY_SIZE_HEADROOM);
493
494 let mut seen_library = false;
495 let mut entry_count = 1_usize;
496 for entry in entries {
497 entry_count += 1;
498 if entry_count > MAX_ARCHIVE_ENTRIES {
499 return Err(ComponentError::TooManyArchiveEntries {
500 max: MAX_ARCHIVE_ENTRIES,
501 actual: entry_count,
502 });
503 }
504 let mut entry = entry?;
505 let path = entry.path()?.into_owned();
506 let is_safe_relative = !path.as_os_str().is_empty()
507 && path
508 .components()
509 .all(|component| matches!(component, Component::Normal(_)));
510 if !is_safe_relative || !entry.header().entry_type().is_file() {
511 return Err(ComponentError::UnsafeArchiveEntry(path.display().to_string()));
512 }
513 if path == Path::new("component.sig") {
514 let bytes = read_bounded_entry(&mut entry, METADATA_ENTRY_SIZE_CEILING)?;
515 fs::write(destination.join("component.sig"), bytes)?;
516 } else if path == library_relative && !seen_library {
517 seen_library = true;
518 stream_library_entry(&mut entry, destination, &library_relative, library_ceiling, &manifest)?;
519 } else {
520 return Err(ComponentError::UnsafeArchiveEntry(path.display().to_string()));
521 }
522 }
523 if !seen_library {
524 return Err(ComponentError::MissingLibrary(destination.join(&library_relative)));
525 }
526 Ok(())
527}
528
529fn read_bounded_entry<R: Read>(entry: &mut tar::Entry<'_, R>, ceiling: u64) -> Result<Vec<u8>, ComponentError> {
532 let declared = entry.header().size()?;
533 if declared > ceiling {
534 return Err(ComponentError::ExtractedSizeExceeded {
535 limit: ceiling,
536 actual: declared,
537 });
538 }
539 let mut buffer = Vec::new();
540 entry.read_to_end(&mut buffer)?;
541 Ok(buffer)
542}
543
544fn stream_library_entry<R: Read>(
548 entry: &mut tar::Entry<'_, R>,
549 destination: &Path,
550 relative: &Path,
551 ceiling: u64,
552 manifest: &ComponentManifest,
553) -> Result<(), ComponentError> {
554 let declared = entry.header().size()?;
555 if declared > ceiling {
556 return Err(ComponentError::ExtractedSizeExceeded {
557 limit: ceiling,
558 actual: declared,
559 });
560 }
561 let target = destination.join(relative);
562 if let Some(parent) = target.parent() {
563 fs::create_dir_all(parent)?;
564 }
565 let mut file = File::create(&target)?;
566 let mut hasher = Sha256::new();
567 let mut buffer = [0_u8; 64 * 1024];
568 let mut copied = 0_u64;
569 loop {
570 let count = entry.read(&mut buffer)?;
571 if count == 0 {
572 break;
573 }
574 copied += count as u64;
575 if copied > ceiling {
576 return Err(ComponentError::ExtractedSizeExceeded {
577 limit: ceiling,
578 actual: copied,
579 });
580 }
581 hasher.update(&buffer[..count]);
582 file.write_all(&buffer[..count])?;
583 }
584 if copied != manifest.library.size {
585 return Err(ComponentError::SizeMismatch {
586 expected: manifest.library.size,
587 actual: copied,
588 });
589 }
590 let actual: [u8; 32] = hasher.finalize().into();
591 let expected = decode_digest(&manifest.library.sha256)?;
592 if actual != expected {
593 return Err(ComponentError::DigestMismatch {
594 expected: manifest.library.sha256.clone(),
595 actual: hex::encode(actual),
596 });
597 }
598 Ok(())
599}
600
601#[cfg(test)]
602mod tests;