返回 CodeWhale
compiled_host.rs
根目录 / crates / cli / src / update / compiled_host.rs
1 //! Optional companion delivery through the existing updater's locked source.
2 //! This is installation provenance, never a runtime or extension authority.
3 use super::*;
4 use codewhale_runtime::delivery_files::GuardedFile;
5 use std::collections::HashSet;
6
7 const CATALOG: &str = "codewhale-extension-hosts.json";
8 const RECEIPT: &str = "codewhale-extension-host.release.json";
9
10 #[derive(serde::Deserialize)]
11 struct Catalog {
12 schema: u64,
13 version: String,
14 source_sha: String,
15 bundle_sha256: String,
16 hosts: Vec<Host>,
17 }
18
19 #[derive(serde::Deserialize)]
20 struct Host {
21 target: String,
22 asset: String,
23 sha256: String,
24 notices_asset: String,
25 notices_sha256: String,
26 source_asset: String,
27 source_sha256: String,
28 runtime_version: String,
29 runtime_revision: String,
30 runtime_sha256: String,
31 webkit_revision: String,
32 bundle_sha256: String,
33 source_commit: String,
34 native_platform: String,
35 native_arch: String,
36 libc: String,
37 passed: u64,
38 failed: u64,
39 skipped: u64,
40 test_log_sha256: String,
41 native_passed: u64,
42 native_failed: u64,
43 native_skipped: u64,
44 native_log_sha256: String,
45 license_closure: String,
46 relink_source: String,
47 }
48
49 fn hex(value: &str, length: usize) -> bool {
50 value.len() == length
51 && value
52 .bytes()
53 .all(|b| b.is_ascii_hexdigit() && !b.is_ascii_uppercase())
54 }
55
56 fn version(value: &str) -> bool {
57 let (core, suffix) = value
58 .split_once('-')
59 .map_or((value, None), |(a, b)| (a, Some(b)));
60 let parts = core.split('.').collect::<Vec<_>>();
61 parts.len() == 3
62 && parts
63 .iter()
64 .all(|p| !p.is_empty() && p.bytes().all(|b| b.is_ascii_digit()))
65 && suffix.is_none_or(|s| {
66 !s.is_empty()
67 && s.bytes()
68 .all(|b| b.is_ascii_alphanumeric() || b == b'.' || b == b'-')
69 })
70 }
71
72 fn native_target(target: &str) -> Option<(&'static str, &'static str)> {
73 Some(match target {
74 "linux-x64" => ("linux", "x64"),
75 "linux-arm64" => ("linux", "arm64"),
76 "macos-x64" => ("darwin", "x64"),
77 "macos-arm64" => ("darwin", "arm64"),
78 "windows-x64" => ("win32", "x64"),
79 "windows-arm64" => ("win32", "arm64"),
80 _ => return None,
81 })
82 }
83
84 fn parse(bytes: &[u8], expected_version: &str) -> Result<Catalog> {
85 if bytes.len() > 64 * 1024 {
86 bail!("compiled host catalog exceeds 64 KiB");
87 }
88 let catalog: Catalog =
89 serde_json::from_slice(bytes).context("malformed compiled host catalog")?;
90 if catalog.schema != 1
91 || !version(&catalog.version)
92 || catalog.version != expected_version.trim_start_matches('v')
93 || !hex(&catalog.source_sha, 40)
94 || !hex(&catalog.bundle_sha256, 64)
95 || catalog.hosts.len() > 6
96 {
97 bail!("compiled host catalog does not identify this exact release");
98 }
99 let mut targets = HashSet::new();
100 for host in &catalog.hosts {
101 let (platform, arch) = native_target(&host.target)
102 .context("unsupported compiled host target; Android is not a qualified Codewhale delivery target")?;
103 let minimum_native = if platform == "win32" { 8 } else { 1 };
104 let stem = format!("codewhale-extension-host-{}", host.target);
105 let binary = format!("{stem}{}", if platform == "win32" { ".exe" } else { "" });
106 if !targets.insert(&host.target)
107 || host.asset != binary
108 || host.notices_asset != format!("{stem}-LICENSES.txt")
109 || host.source_asset != format!("{stem}-relink-source.tar.gz")
110 || [
111 &host.sha256,
112 &host.notices_sha256,
113 &host.source_sha256,
114 &host.runtime_sha256,
115 &host.test_log_sha256,
116 &host.native_log_sha256,
117 ]
118 .iter()
119 .any(|digest| !hex(digest, 64))
120 || !version(&host.runtime_version)
121 || !hex(&host.runtime_revision, 40)
122 || !hex(&host.webkit_revision, 40)
123 || host.bundle_sha256 != catalog.bundle_sha256
124 || host.source_commit != catalog.source_sha
125 || host.native_platform != platform
126 || host.native_arch != arch
127 || !(6..=9_007_199_254_740_991).contains(&host.passed)
128 || host.failed != 0
129 || host.skipped != 0
130 || !(minimum_native..=9_007_199_254_740_991).contains(&host.native_passed)
131 || host.native_failed != 0
132 || host.native_skipped != 0
133 || host.license_closure != "complete"
134 || host.relink_source != "complete"
135 || if platform == "linux" {
136 !matches!(host.libc.as_str(), "glibc" | "musl")
137 } else {
138 host.libc != "none"
139 }
140 {
141 bail!("compiled host is not a complete matching-native qualified payload");
142 }
143 }
144 Ok(catalog)
145 }
146
147 struct Replacement {
148 name: String,
149 staged: GuardedFile,
150 old: Option<GuardedFile>,
151 backup_name: String,
152 retired: bool,
153 published: bool,
154 }
155
156 pub(super) struct Prepared {
157 directory: PathBuf,
158 replacements: Vec<Replacement>,
159 }
160
161 impl Prepared {
162 fn verify_target(directory: &Path, replacement: &mut Replacement) -> Result<()> {
163 if let Some(old) = &mut replacement.old {
164 old.verify()?;
165 } else if GuardedFile::open(directory, &replacement.name)?.is_some() {
166 bail!(
167 "compiled host destination appeared: {}",
168 directory.join(&replacement.name).display()
169 );
170 }
171 replacement.staged.verify()?;
172 Ok(())
173 }
174
175 pub(super) fn recovery_paths(&self) -> Vec<PathBuf> {
176 self.replacements
177 .iter()
178 .filter(|replacement| replacement.retired)
179 .map(|replacement| self.directory.join(&replacement.backup_name))
180 .collect()
181 }
182
183 pub(super) fn publish(&mut self) -> Result<()> {
184 for replacement in &mut self.replacements {
185 Self::verify_target(&self.directory, replacement)?;
186 }
187 for replacement in &mut self.replacements {
188 Self::verify_target(&self.directory, replacement)?;
189 if let Some(old) = &mut replacement.old {
190 let result = old.move_to_vacant(&replacement.backup_name);
191 // A Unix name can change between comparison and rename. Record
192 // the move even when post-move identity validation rejects it.
193 replacement.retired = old.name() == replacement.backup_name;
194 result.with_context(|| {
195 format!(
196 "failed to retire {}; recovery at {}",
197 replacement.name,
198 self.directory.join(&replacement.backup_name).display()
199 )
200 })?;
201 }
202 let result = replacement.staged.move_to_vacant(&replacement.name);
203 replacement.published = replacement.staged.name() == replacement.name;
204 result.with_context(|| {
205 format!(
206 "failed to publish {}; no concurrent destination was overwritten",
207 replacement.name
208 )
209 })?;
210 }
211 Ok(())
212 }
213
214 pub(super) fn rollback(&mut self) -> Result<()> {
215 let mut failures = Vec::new();
216 for replacement in self.replacements.iter_mut().rev() {
217 let restored = (|| {
218 if replacement.published {
219 // The retained staged handle, not equal bytes, proves this
220 // entry is the one we published. Preserve changed entries.
221 replacement.staged.verify()?;
222 let recovery = GuardedFile::recovery_name();
223 let result = replacement.staged.move_to_vacant(&recovery);
224 replacement.published = replacement.staged.name() == replacement.name;
225 result?;
226 }
227 if replacement.retired {
228 // Restore the entry actually moved, even if a racing Unix
229 // replacement made retirement refuse its identity. A fresh
230 // protected handle retains that recovery object's identity.
231 let original = replacement.old.as_mut().context("retired handle missing")?;
232 if original.verify().is_ok() {
233 original.move_to_vacant(&replacement.name)?;
234 } else {
235 // On Unix the name moved may be a racing replacement;
236 // on either platform an observed writer may have changed
237 // the recovery bytes. Capture that actual recovery entry
238 // and restore it only if the old destination is vacant.
239 let mut recovery =
240 GuardedFile::open(&self.directory, &replacement.backup_name)?
241 .context("retired entry disappeared")?;
242 recovery.move_to_vacant(&replacement.name)?;
243 }
244 replacement.retired = false;
245 }
246 Ok::<_, anyhow::Error>(())
247 })();
248 if let Err(error) = restored {
249 failures.push(format!(
250 "{}: {} (retired entry {}; staged/published entry {})",
251 replacement.name,
252 error,
253 self.directory.join(&replacement.backup_name).display(),
254 self.directory.join(replacement.staged.name()).display()
255 ));
256 }
257 }
258 if !failures.is_empty() {
259 bail!(
260 "compiled host rollback needs attention; recovery bytes preserved: {}",
261 failures.join("; ")
262 );
263 }
264 Ok(())
265 }
266 }
267
268 #[cfg(any(unix, windows))]
269 pub(super) fn owned_for_uninstall(directory: &Path, target: &str) -> Result<Vec<GuardedFile>> {
270 let Some(mut receipt) = GuardedFile::open_bounded(directory, RECEIPT, 64 * 1024)? else {
271 return Ok(Vec::new());
272 };
273 receipt.verify_owned()?;
274 let catalog = parse(&receipt.read_bounded(64 * 1024)?, env!("CARGO_PKG_VERSION"))?;
275 let host = catalog
276 .hosts
277 .iter()
278 .find(|host| host.target == target)
279 .context("installed compiled-host receipt has no matching target")?;
280 let mut files = Vec::new();
281 let host_name = format!("codewhale-extension-host{}", std::env::consts::EXE_SUFFIX);
282 for (name, expected) in [
283 (host_name.as_str(), host.sha256.as_str()),
284 (
285 "codewhale-extension-host.LICENSES.txt",
286 host.notices_sha256.as_str(),
287 ),
288 (
289 "codewhale-extension-host.relink-source.tar.gz",
290 host.source_sha256.as_str(),
291 ),
292 ] {
293 if let Some(file) = GuardedFile::open(directory, name)? {
294 if file.sha256() != expected {
295 bail!(
296 "Preserved changed compiled-host file: {}",
297 directory.join(name).display()
298 );
299 }
300 files.push(file);
301 }
302 }
303 files.push(receipt);
304 Ok(files)
305 }
306
307 pub(super) fn required_for(current_exe: &Path) -> Result<bool> {
308 let directory = current_exe
309 .parent()
310 .context("updater executable has no parent")?;
311 Ok(
312 std::env::var("CODEWHALE_INSTALL_COMPILED_HOST").as_deref() == Ok("1")
313 || GuardedFile::open_bounded(directory, RECEIPT, 64 * 1024)?.is_some(),
314 )
315 }
316
317 pub(super) fn require_catalog_manifest(bytes: &[u8]) -> Result<()> {
318 let text = std::str::from_utf8(bytes).context("compiled host manifest is not UTF-8")?;
319 if !parse_checksum_manifest(text)?.contains_key(CATALOG) {
320 bail!("release source has no qualified compiled-host catalog");
321 }
322 Ok(())
323 }
324
325 pub(super) fn prepare(
326 download: &DownloadPlan,
327 release_version: &str,
328 target: &str,
329 current_exe: &Path,
330 proxy: Option<&Proxy>,
331 ) -> Result<Option<Prepared>> {
332 let directory = current_exe
333 .parent()
334 .context("updater executable has no parent")?;
335 let host_path = directory.join(format!(
336 "codewhale-extension-host{}",
337 std::env::consts::EXE_SUFFIX
338 ));
339 let receipt_path = directory.join(RECEIPT);
340 let mut receipt_file = GuardedFile::open_bounded(directory, RECEIPT, 64 * 1024)?;
341 let requested = std::env::var("CODEWHALE_INSTALL_COMPILED_HOST").as_deref() == Ok("1");
342 if receipt_file.is_none() && !requested {
343 return Ok(None);
344 }
345 let mut ownership = HashMap::new();
346 if let Some(mut receipt) = receipt_file.take() {
347 let old = parse(&receipt.read_bounded(64 * 1024)?, env!("CARGO_PKG_VERSION"))?;
348 let entry = old
349 .hosts
350 .iter()
351 .find(|host| host.target == target)
352 .context("installed host receipt has no matching target")?;
353 for (name, expected) in [
354 (
355 host_path
356 .file_name()
357 .and_then(|name| name.to_str())
358 .context("invalid host basename")?,
359 entry.sha256.as_str(),
360 ),
361 (
362 "codewhale-extension-host.LICENSES.txt",
363 entry.notices_sha256.as_str(),
364 ),
365 (
366 "codewhale-extension-host.relink-source.tar.gz",
367 entry.source_sha256.as_str(),
368 ),
369 ] {
370 let file = GuardedFile::open(directory, name)?
371 .with_context(|| format!("owned compiled host file missing: {name}"))?;
372 if file.sha256() != expected {
373 bail!("compiled host ownership changed: {name}");
374 }
375 ownership.insert(directory.join(name), file);
376 }
377 ownership.insert(receipt_path.clone(), receipt);
378 } else if GuardedFile::open(
379 directory,
380 host_path
381 .file_name()
382 .and_then(|name| name.to_str())
383 .context("invalid host basename")?,
384 )?
385 .is_some()
386 {
387 bail!(
388 "compiled host beside this CLI has no installation receipt; it was not replaced. Install into a fresh prefix or use Node"
389 );
390 }
391 let fetch = |name: &str| -> Result<Vec<u8>> {
392 let url = reqwest::Url::parse(&download.binary_url)?.join(name)?;
393 let bytes = download_url(url.as_str(), proxy)?;
394 verify_manifest_asset(download, name, &bytes)?;
395 Ok(bytes)
396 };
397 if !download.checksums.contains_key(CATALOG) {
398 bail!(
399 "compiled host requested/installed but the selected release source has no qualified catalog; no files were changed. Node remains available"
400 );
401 }
402 let catalog_bytes = fetch(CATALOG)?;
403 let catalog = parse(&catalog_bytes, release_version)?;
404 let host = catalog
405 .hosts
406 .iter()
407 .find(|host| host.target == target)
408 .context("release has no qualified compiled image for this target; use Node")?;
409 let payloads = [
410 (host.asset.as_str(), host_path, host.sha256.as_str(), true),
411 (
412 host.notices_asset.as_str(),
413 directory.join("codewhale-extension-host.LICENSES.txt"),
414 host.notices_sha256.as_str(),
415 false,
416 ),
417 (
418 host.source_asset.as_str(),
419 directory.join("codewhale-extension-host.relink-source.tar.gz"),
420 host.source_sha256.as_str(),
421 false,
422 ),
423 (
424 CATALOG,
425 receipt_path,
426 download
427 .checksums
428 .get(CATALOG)
429 .context("catalog checksum missing")?
430 .as_str(),
431 false,
432 ),
433 ];
434 let mut replacements = Vec::new();
435 for (name, path, expected, executable) in payloads {
436 let bytes = if name == CATALOG {
437 catalog_bytes.clone()
438 } else {
439 fetch(name)?
440 };
441 if sha256_hex(&bytes) != expected {
442 bail!("compiled host catalog and manifest disagree for {name}");
443 }
444 if executable && cfg!(target_os = "linux") {
445 let required = highest_required_glibc(&bytes);
446 let available = detect_host_glibc();
447 if (host.libc == "glibc" && available.is_none())
448 || required
449 .is_some_and(|required| available.is_none_or(|available| available < required))
450 || (host.libc == "musl" && required.is_some())
451 {
452 bail!(
453 "optional compiled Bun image has an incompatible libc floor; the CLI remains static musl. Use Node"
454 );
455 }
456 }
457 let old = ownership.remove(&path);
458 let filename = path
459 .file_name()
460 .and_then(|name| name.to_str())
461 .context("invalid compiled payload basename")?
462 .to_owned();
463 if old.is_none() && GuardedFile::open(directory, &filename)?.is_some() {
464 bail!("refusing unowned compiled host file {}", path.display());
465 }
466 let staged = GuardedFile::stage(directory, &bytes, executable)?;
467 if staged.sha256() != expected {
468 bail!("compiled host stage changed: {}", staged.name());
469 }
470 replacements.push(Replacement {
471 name: filename,
472 staged,
473 old,
474 backup_name: GuardedFile::recovery_name(),
475 retired: false,
476 published: false,
477 });
478 }
479 Ok(Some(Prepared {
480 directory: directory.to_path_buf(),
481 replacements,
482 }))
483 }
484
485 #[cfg(test)]
486 mod tests {
487 use super::*;
488
489 fn receipt() -> serde_json::Value {
490 serde_json::json!({
491 "schema":1,"version":"0.10.1","source_sha":"b".repeat(40),"bundle_sha256":"a".repeat(64),
492 "hosts":[{
493 "target":"linux-x64","asset":"codewhale-extension-host-linux-x64","sha256":"c".repeat(64),
494 "notices_asset":"codewhale-extension-host-linux-x64-LICENSES.txt","notices_sha256":"d".repeat(64),
495 "source_asset":"codewhale-extension-host-linux-x64-relink-source.tar.gz","source_sha256":"e".repeat(64),
496 "runtime_version":"1.4.0","runtime_revision":"f".repeat(40),"runtime_sha256":"1".repeat(64),"webkit_revision":"2".repeat(40),
497 "bundle_sha256":"a".repeat(64),"source_commit":"b".repeat(40),"native_platform":"linux","native_arch":"x64","libc":"glibc",
498 "passed":6,"failed":0,"skipped":0,"test_log_sha256":"3".repeat(64),"native_passed":1,"native_failed":0,"native_skipped":0,"native_log_sha256":"4".repeat(64),"license_closure":"complete","relink_source":"complete"
499 }]
500 })
501 }
502
503 #[test]
504 fn catalog_refuses_cross_native_or_skipped_containment_and_mixed_release() {
505 let valid = receipt();
506 assert!(parse(&serde_json::to_vec(&valid).unwrap(), "v0.10.1").is_ok());
507 for (key, value) in [
508 ("native_skipped", serde_json::json!(1)),
509 ("native_arch", serde_json::json!("arm64")),
510 ("native_passed", serde_json::json!(0)),
511 ("source_asset", serde_json::json!("../source.tar.gz")),
512 ("relink_source", serde_json::json!("pending")),
513 ] {
514 let mut invalid = valid.clone();
515 invalid["hosts"][0][key] = value;
516 assert!(
517 parse(&serde_json::to_vec(&invalid).unwrap(), "0.10.1").is_err(),
518 "{key}"
519 );
520 }
521 assert!(parse(&serde_json::to_vec(&valid).unwrap(), "0.10.2").is_err());
522 }
523
524 #[test]
525 fn catalog_requires_all_eight_current_windows_native_cases() {
526 let mut value = receipt();
527 let host = &mut value["hosts"][0];
528 for (key, field) in [
529 ("target", "windows-x64"),
530 ("asset", "codewhale-extension-host-windows-x64.exe"),
531 (
532 "notices_asset",
533 "codewhale-extension-host-windows-x64-LICENSES.txt",
534 ),
535 (
536 "source_asset",
537 "codewhale-extension-host-windows-x64-relink-source.tar.gz",
538 ),
539 ("native_platform", "win32"),
540 ("libc", "none"),
541 ] {
542 host[key] = serde_json::json!(field);
543 }
544 host["native_passed"] = serde_json::json!(7);
545 assert!(parse(&serde_json::to_vec(&value).unwrap(), "0.10.1").is_err());
546 value["hosts"][0]["native_passed"] = serde_json::json!(8);
547 assert!(parse(&serde_json::to_vec(&value).unwrap(), "0.10.1").is_ok());
548 }
549
550 fn prepared(directory: &Path, name: &str, old: Option<&[u8]>) -> Prepared {
551 if let Some(bytes) = old {
552 std::fs::write(directory.join(name), bytes).unwrap();
553 }
554 Prepared {
555 directory: directory.to_path_buf(),
556 replacements: vec![Replacement {
557 name: name.into(),
558 staged: GuardedFile::stage(directory, b"qualified", true).unwrap(),
559 old: GuardedFile::open(directory, name).unwrap(),
560 backup_name: GuardedFile::recovery_name(),
561 retired: false,
562 published: false,
563 }],
564 }
565 }
566
567 #[test]
568 fn publish_retires_no_companion_if_a_destination_changed() {
569 let directory = tempfile::tempdir().unwrap();
570 let mut prepared = prepared(directory.path(), "host", None);
571 std::fs::write(directory.path().join("host"), b"foreign").unwrap();
572 assert!(prepared.publish().is_err());
573 assert_eq!(
574 std::fs::read(directory.path().join("host")).unwrap(),
575 b"foreign"
576 );
577 }
578
579 #[cfg(unix)]
580 #[test]
581 fn same_byte_inode_swap_cannot_establish_ownership() {
582 let directory = tempfile::tempdir().unwrap();
583 let mut prepared = prepared(directory.path(), "host", Some(b"old"));
584 std::fs::rename(
585 directory.path().join("host"),
586 directory.path().join("original"),
587 )
588 .unwrap();
589 std::fs::write(directory.path().join("host"), b"old").unwrap();
590 assert!(prepared.publish().is_err());
591 assert_eq!(
592 std::fs::read(directory.path().join("host")).unwrap(),
593 b"old"
594 );
595 assert_eq!(
596 std::fs::read(directory.path().join("original")).unwrap(),
597 b"old"
598 );
599 }
600
601 #[cfg(unix)]
602 #[test]
603 fn changed_writer_refuses_retirement_and_preserves_original() {
604 let directory = tempfile::tempdir().unwrap();
605 let mut prepared = prepared(directory.path(), "host", Some(b"old"));
606 std::fs::write(directory.path().join("host"), b"concurrent").unwrap();
607 assert!(prepared.publish().is_err());
608 assert_eq!(
609 std::fs::read(directory.path().join("host")).unwrap(),
610 b"concurrent"
611 );
612 }
613
614 #[test]
615 fn successful_publication_and_rollback_preserve_both_versions() {
616 let directory = tempfile::tempdir().unwrap();
617 let mut prepared = prepared(directory.path(), "host", Some(b"old"));
618 prepared.publish().unwrap();
619 assert_eq!(
620 std::fs::read(directory.path().join("host")).unwrap(),
621 b"qualified"
622 );
623 prepared.rollback().unwrap();
624 assert_eq!(
625 std::fs::read(directory.path().join("host")).unwrap(),
626 b"old"
627 );
628 let recovered = directory
629 .path()
630 .join(prepared.replacements[0].staged.name());
631 assert_eq!(std::fs::read(recovered).unwrap(), b"qualified");
632 }
633
634 #[cfg(unix)]
635 #[test]
636 fn partial_rollback_preserves_changed_published_entry_and_recovers_other_slot() {
637 let directory = tempfile::tempdir().unwrap();
638 let mut first = prepared(directory.path(), "host", Some(b"old-host"));
639 let mut second = prepared(directory.path(), "notices", Some(b"old-notices"));
640 first.replacements.append(&mut second.replacements);
641 first.publish().unwrap();
642 let backup = directory.path().join(&first.replacements[0].backup_name);
643 std::fs::rename(
644 directory.path().join("host"),
645 directory.path().join("published-original"),
646 )
647 .unwrap();
648 // Same bytes must still fail identity; a digest-only rollback deletes it.
649 std::fs::write(directory.path().join("host"), b"qualified").unwrap();
650 let error = first.rollback().unwrap_err().to_string();
651 assert!(error.contains("recovery bytes preserved"));
652 assert_eq!(
653 std::fs::read(directory.path().join("host")).unwrap(),
654 b"qualified"
655 );
656 assert_eq!(std::fs::read(backup).unwrap(), b"old-host");
657 assert_eq!(
658 std::fs::read(directory.path().join("notices")).unwrap(),
659 b"old-notices"
660 );
661 }
662 }
663
663 lines RUST