1#![forbid(unsafe_code)]
2#![deny(missing_docs)]
3use eggpack_contract::{DistributionContract, ExpandedAssets};
5use eggpack_manifest::{ArtifactForm, ReleaseManifest};
6use serde::{Deserialize, Serialize};
7use std::collections::{BTreeMap, BTreeSet};
8use std::fmt;
9
10#[derive(Debug, Clone)]
12pub struct BootstrapSpec {
13 pub origin: String,
15 pub fixture_http: bool,
17}
18#[derive(Debug, Clone, PartialEq, Eq)]
20pub struct BootstrapError(String);
21impl fmt::Display for BootstrapError {
22 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
23 f.write_str(&self.0)
24 }
25}
26impl std::error::Error for BootstrapError {}
27fn fail(s: &str) -> BootstrapError {
28 BootstrapError(s.into())
29}
30struct Item {
31 os: String,
32 arch: String,
33 name: String,
34 install: String,
35 size: u64,
36 sha: String,
37}
38fn project(
39 c: &DistributionContract,
40 m: &ReleaseManifest,
41 s: &BootstrapSpec,
42) -> Result<Vec<Item>, BootstrapError> {
43 let loopback = s.origin.starts_with("http://127.0.0.1")
44 || s.origin.starts_with("http://localhost")
45 || s.origin.starts_with("http://[::1]");
46 if !(s.origin.starts_with("https://") || (s.fixture_http && loopback))
47 || s.origin
48 .contains(['\n', '\r', '\'', '"', '`', '$', '\\', '?', '#', ' ', '@'])
49 || s.origin.ends_with('/')
50 || s.origin.ends_with("https://")
51 {
52 return Err(fail(
53 "origin must be a fixed HTTPS URL (or explicit loopback fixture URL)",
54 ));
55 }
56 m.validate().map_err(|_| fail("invalid release manifest"))?;
57 if c.product.id != m.product_id {
58 return Err(fail("contract and manifest product mismatch"));
59 }
60 let mut seen = std::collections::HashSet::new();
61 let mut out = Vec::new();
62 for t in &m.targets {
63 let x = c
64 .resolve(&t.target)
65 .map_err(|_| fail("manifest target absent from contract"))?;
66 if x.triple != t.target || !seen.insert(t.target.as_str()) {
67 return Err(fail("manifest target is not unique and canonical"));
68 }
69 let exp = c
70 .expand(&t.target, &m.release_id)
71 .map_err(|_| fail("contract expansion failed"))?;
72 let (name, install, size, sha) = match (&exp.assets, &t.form) {
73 (ExpandedAssets::Direct(d), ArtifactForm::Direct { artifact, install })
74 if d.asset_file == artifact.name && d.install_name == *install =>
75 {
76 (
77 artifact.name.clone(),
78 install.clone(),
79 artifact.size,
80 artifact.sha256.clone(),
81 )
82 }
83 _ => return Err(fail("M001 requires matching direct artifact targets")),
84 };
85 if !safe_segment(&name) || !safe_segment(&install) {
86 return Err(fail(
87 "artifact and install basenames contain unsupported URL or platform characters",
88 ));
89 }
90 let (os, arch) = runtime_pair(&t.target)
91 .ok_or_else(|| fail("target has no unambiguous runtime OS/architecture mapping"))?;
92 out.push(Item {
93 os: os.into(),
94 arch: arch.into(),
95 name,
96 install,
97 size,
98 sha,
99 });
100 }
101 if out.len() != c.targets.len() {
102 return Err(fail("contract and manifest target sets differ"));
103 }
104 let mut pairs = std::collections::HashSet::new();
105 if out
106 .iter()
107 .any(|x| !pairs.insert((x.os.clone(), x.arch.clone())))
108 {
109 return Err(fail("runtime platform mapping is ambiguous"));
110 }
111 Ok(out)
112}
113fn safe_segment(s: &str) -> bool {
114 !s.is_empty()
115 && s.bytes()
116 .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'_' | b'-' | b'+'))
117}
118fn runtime_pair(t: &str) -> Option<(&'static str, &'static str)> {
119 let arch = if t.starts_with("x86_64-") {
120 "x86_64"
121 } else if t.starts_with("aarch64-") {
122 "aarch64"
123 } else if t.starts_with("armv7-") {
124 "armv7"
125 } else {
126 return None;
127 };
128 let os = if t.contains("-linux-") {
129 "linux"
130 } else if t.ends_with("-apple-darwin") {
131 "macos"
132 } else if t.contains("-windows-") {
133 "windows"
134 } else {
135 return None;
136 };
137 Some((os, arch))
138}
139pub fn render_posix(
141 c: &DistributionContract,
142 m: &ReleaseManifest,
143 s: &BootstrapSpec,
144) -> Result<String, BootstrapError> {
145 let items = project(c, m, s)?;
146 let mut cases = String::new();
147 for i in items {
148 cases.push_str(&format!(
149 " {}:{}) name={} install={} size={} sha={} ;;\n",
150 i.os,
151 i.arch,
152 shq(&i.name),
153 shq(&i.install),
154 i.size,
155 i.sha
156 ));
157 }
158 Ok(format!(
159 r##"#!/bin/sh
160set -eu
161os=$(uname -s | tr '[:upper:]' '[:lower:]')
162case "$os" in darwin) os=macos ;; esac
163arch=$(uname -m)
164case "$arch" in amd64) arch=x86_64 ;; arm64) arch=aarch64 ;; armv7l) arch=armv7 ;; esac
165case "$os:$arch" in
166{cases} *) echo 'unsupported platform' >&2; exit 2 ;;
167esac
168origin={origin}
169dest=${{1:-.}}
170mkdir -p "$dest"
171file="$dest/$install"
172[ ! -e "$file" ] || {{ echo 'destination already exists' >&2; exit 3; }}
173tmp=$(mktemp -d "$dest/.eggpack.XXXXXX") || exit 4
174trap 'rm -rf "$tmp"' 0
175trap 'exit 1' HUP INT TERM
176if command -v curl >/dev/null 2>&1; then curl --fail --silent --show-error --connect-timeout 10 --max-time 120 "$origin/$name" -o "$tmp/payload"; else echo 'curl is required' >&2; exit 5; fi
177actual=$(wc -c < "$tmp/payload" | tr -d ' ')
178[ "$actual" = "$size" ] || {{ echo 'size mismatch' >&2; exit 6; }}
179if command -v sha256sum >/dev/null 2>&1; then actual=$(sha256sum "$tmp/payload" | cut -d ' ' -f 1); elif command -v shasum >/dev/null 2>&1; then actual=$(shasum -a 256 "$tmp/payload" | cut -d ' ' -f 1); elif command -v openssl >/dev/null 2>&1; then actual=$(openssl dgst -sha256 "$tmp/payload" | sed 's/^.*= //'); else echo 'SHA-256 tool required' >&2; exit 7; fi
180[ "$actual" = "$sha" ] || {{ echo 'SHA-256 mismatch' >&2; exit 8; }}
181[ ! -e "$file" ] || {{ echo 'destination already exists' >&2; exit 3; }}
182chmod 755 "$tmp/payload"
183ln "$tmp/payload" "$file" || {{ echo 'destination already exists or filesystem does not support safe placement' >&2; exit 3; }}
184"##,
185 cases = cases,
186 origin = shq(&s.origin)
187 ))
188}
189fn shq(s: &str) -> String {
190 format!("'{}'", s.replace('\'', "'\\''"))
191}
192pub fn render_powershell(
194 c: &DistributionContract,
195 m: &ReleaseManifest,
196 s: &BootstrapSpec,
197) -> Result<String, BootstrapError> {
198 let items = project(c, m, s)?;
199 let mut cases = String::new();
200 for i in items {
201 cases.push_str(&format!(
202 " '{}:{}' {{ $name={}; $install={}; $size={}; $sha='{}' }}\n",
203 i.os,
204 i.arch,
205 psq(&i.name),
206 psq(&i.install),
207 i.size,
208 i.sha
209 ));
210 }
211 Ok(format!(
212 r#"$ErrorActionPreference = 'Stop'
213$os = if ($env:OS -eq 'Windows_NT') {{ 'windows' }} elseif ($IsMacOS) {{ 'macos' }} else {{ 'linux' }}
214$arch = [Runtime.InteropServices.RuntimeInformation]::OSArchitecture.ToString().ToLowerInvariant()
215switch ($arch) {{ 'x64' {{ $arch='x86_64' }} 'arm64' {{ $arch='aarch64' }} 'arm' {{ $arch='armv7' }} }}
216switch ("$os`:$arch") {{
217{cases} default {{ throw 'unsupported platform' }}
218}}
219$origin = {origin}
220$dest = if ($args.Count -gt 0) {{ $args[0] }} else {{ '.' }}
221New-Item -ItemType Directory -Force -Path $dest | Out-Null
222$file = Join-Path $dest $install
223if (Test-Path -LiteralPath $file) {{ throw 'destination already exists' }}
224$tmp = Join-Path $dest ('.eggpack-' + [Guid]::NewGuid().ToString('N'))
225New-Item -ItemType Directory -Path $tmp | Out-Null
226try {{
227 $payload = Join-Path $tmp 'payload'
228 Invoke-WebRequest -Uri "$origin/$name" -OutFile $payload -TimeoutSec 120 -MaximumRedirection 0
229 if ((Get-Item -LiteralPath $payload).Length -ne $size) {{ throw 'size mismatch' }}
230 if ((Get-FileHash -LiteralPath $payload -Algorithm SHA256).Hash.ToLowerInvariant() -ne $sha) {{ throw 'SHA-256 mismatch' }}
231 if (Test-Path -LiteralPath $file) {{ throw 'destination already exists' }}
232 [IO.File]::Move($payload, $file)
233}} finally {{ Remove-Item -LiteralPath $tmp -Recurse -Force -ErrorAction SilentlyContinue }}
234"#,
235 cases = cases,
236 origin = psq(&s.origin)
237 ))
238}
239fn psq(s: &str) -> String {
240 format!("'{}'", s.replace('\'', "''"))
241}
242
243#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
249#[serde(rename_all = "snake_case")]
250pub enum InstallMode {
251 Executable,
253 Data,
255}
256
257#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
259#[serde(rename_all = "snake_case")]
260pub enum BundleArchiveEncoding {
261 TarGzip,
263}
264
265#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
267#[serde(deny_unknown_fields)]
268pub struct TargetInstallPolicy {
269 #[serde(default)]
271 pub modes: BTreeMap<String, InstallMode>,
272 #[serde(default, skip_serializing_if = "Option::is_none")]
274 pub archive_encoding: Option<BundleArchiveEncoding>,
275}
276
277#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
279#[serde(deny_unknown_fields)]
280pub struct BootstrapInstallPolicyV1 {
281 pub schema_version: u32,
283 #[serde(default)]
285 pub targets: BTreeMap<String, TargetInstallPolicy>,
286}
287
288const MAX_POLICY_JSON: usize = 256 * 1024;
289const MAX_POLICY_TARGETS: usize = 256;
290const MAX_POLICY_ENTRIES: usize = 256;
291
292impl BootstrapInstallPolicyV1 {
293 pub fn empty() -> Self {
295 Self {
296 schema_version: 1,
297 targets: BTreeMap::new(),
298 }
299 }
300
301 pub fn from_toml(text: &str) -> Result<Self, BootstrapError> {
303 if text.len() > MAX_POLICY_JSON {
304 return Err(fail("install policy exceeds size bound"));
305 }
306 let value: Self = toml::from_str(text).map_err(|_| fail("invalid install policy TOML"))?;
307 value.validate_shape()?;
308 Ok(value)
309 }
310
311 pub fn from_json(text: &str) -> Result<Self, BootstrapError> {
313 if text.len() > MAX_POLICY_JSON {
314 return Err(fail("install policy exceeds size bound"));
315 }
316 let value: Self =
317 serde_json::from_str(text).map_err(|_| fail("invalid install policy JSON"))?;
318 value.validate_shape()?;
319 Ok(value)
320 }
321
322 fn validate_shape(&self) -> Result<(), BootstrapError> {
323 if self.schema_version != 1 || self.targets.len() > MAX_POLICY_TARGETS {
324 return Err(fail("invalid install policy version or target count"));
325 }
326 for (target, policy) in &self.targets {
327 if target.is_empty() || target.len() > 128 || policy.modes.len() > MAX_POLICY_ENTRIES {
328 return Err(fail("invalid install policy target or entry count"));
329 }
330 for name in policy.modes.keys() {
331 if !safe_segment(name) {
332 return Err(fail("install policy names contain unsupported characters"));
333 }
334 }
335 }
336 Ok(())
337 }
338}
339
340fn validate_origin(s: &BootstrapSpec) -> Result<(), BootstrapError> {
341 let loopback = s.origin.starts_with("http://127.0.0.1")
342 || s.origin.starts_with("http://localhost")
343 || s.origin.starts_with("http://[::1]");
344 if !(s.origin.starts_with("https://") || (s.fixture_http && loopback))
345 || s.origin
346 .contains(['\n', '\r', '\'', '"', '`', '$', '\\', '?', '#', ' ', '@'])
347 || s.origin.ends_with('/')
348 || s.origin.ends_with("https://")
349 {
350 return Err(fail(
351 "origin must be a fixed HTTPS URL (or explicit loopback fixture URL)",
352 ));
353 }
354 Ok(())
355}
356
357#[derive(Debug, Clone)]
358struct BundleEntryProjection {
359 name: String,
360 install: String,
361 size: u64,
362 sha: String,
363 mode: InstallMode,
364}
365
366#[derive(Debug, Clone)]
367struct ArchiveMemberProjection {
368 source: String,
369 install: String,
370 size: u64,
371 sha: String,
372 mode: InstallMode,
373}
374
375#[derive(Debug, Clone)]
376enum TargetProjection {
377 Direct {
378 os: String,
379 arch: String,
380 name: String,
381 install: String,
382 size: u64,
383 sha: String,
384 },
385 Bundle {
386 os: String,
387 arch: String,
388 entries: Vec<BundleEntryProjection>,
389 },
390 Archive {
391 os: String,
392 arch: String,
393 archive_name: String,
394 archive_size: u64,
395 archive_sha: String,
396 members: Vec<ArchiveMemberProjection>,
397 },
398}
399
400fn project_all(
401 c: &DistributionContract,
402 m: &ReleaseManifest,
403 s: &BootstrapSpec,
404 policy: &BootstrapInstallPolicyV1,
405) -> Result<Vec<TargetProjection>, BootstrapError> {
406 validate_origin(s)?;
407 policy.validate_shape()?;
408 m.validate().map_err(|_| fail("invalid release manifest"))?;
409 if policy.schema_version != 1 {
410 return Err(fail("invalid install policy version"));
411 }
412 if c.product.id != m.product_id {
413 return Err(fail("contract and manifest product mismatch"));
414 }
415 let mut seen_targets = BTreeSet::new();
416 let mut seen_platforms = BTreeSet::new();
417 let mut out = Vec::new();
418 for t in &m.targets {
419 let resolved = c
420 .resolve(&t.target)
421 .map_err(|_| fail("manifest target absent from contract"))?;
422 if resolved.triple != t.target || !seen_targets.insert(t.target.as_str()) {
423 return Err(fail("manifest target is not unique and canonical"));
424 }
425 let expanded = c
426 .expand(&t.target, &m.release_id)
427 .map_err(|_| fail("contract expansion failed"))?;
428 let target_policy = policy.targets.get(&t.target);
429 let (os, arch) = runtime_pair(&t.target)
430 .ok_or_else(|| fail("target has no unambiguous runtime OS/architecture mapping"))?;
431 if !seen_platforms.insert((os.to_string(), arch.to_string())) {
432 return Err(fail("runtime platform mapping is ambiguous"));
433 }
434 match (&expanded.assets, &t.form) {
435 (
436 eggpack_contract::ExpandedAssets::Direct(d),
437 ArtifactForm::Direct { artifact, install },
438 ) if d.asset_file == artifact.name && d.install_name == *install => {
439 if !safe_segment(&artifact.name) || !safe_segment(install) {
440 return Err(fail(
441 "artifact and install basenames contain unsupported URL or platform characters",
442 ));
443 }
444 if let Some(p) = target_policy {
445 if p.archive_encoding.is_some() {
446 return Err(fail("archive policy on non-archive target"));
447 }
448 if p.modes.len() != 1 || p.modes.get(install) != Some(&InstallMode::Executable)
449 {
450 return Err(fail(
451 "direct install policy must name the single executable install",
452 ));
453 }
454 }
455 out.push(TargetProjection::Direct {
456 os: os.into(),
457 arch: arch.into(),
458 name: artifact.name.clone(),
459 install: install.clone(),
460 size: artifact.size,
461 sha: artifact.sha256.clone(),
462 });
463 }
464 (eggpack_contract::ExpandedAssets::Bundle(b), ArtifactForm::Bundle { entries }) => {
465 let p =
466 target_policy.ok_or_else(|| fail("bundle target is missing install policy"))?;
467 if p.archive_encoding.is_some() {
468 return Err(fail("archive policy on non-archive target"));
469 }
470 if b.entries.len() != entries.len() {
471 return Err(fail("bundle contract and manifest entry counts differ"));
472 }
473 let mut manifest_by_asset: BTreeMap<(&str, &str), _> = BTreeMap::new();
475 for e in entries {
476 if !safe_segment(&e.artifact.name) || !safe_segment(&e.install) {
477 return Err(fail(
478 "artifact and install basenames contain unsupported URL or platform characters",
479 ));
480 }
481 if manifest_by_asset
482 .insert((e.artifact.name.as_str(), e.install.as_str()), e)
483 .is_some()
484 {
485 return Err(fail("duplicate bundle manifest entry"));
486 }
487 }
488 let mut projected = Vec::with_capacity(b.entries.len());
489 for contract_entry in &b.entries {
490 let key = (
491 contract_entry.asset_file.as_str(),
492 contract_entry.install_name.as_str(),
493 );
494 let manifest_entry = manifest_by_asset
495 .remove(&key)
496 .ok_or_else(|| fail("bundle contract and manifest entries differ"))?;
497 let mode = p.modes.get(&contract_entry.install_name).ok_or_else(|| {
498 fail("bundle install policy is missing or has extra install names")
499 })?;
500 projected.push(BundleEntryProjection {
501 name: manifest_entry.artifact.name.clone(),
502 install: manifest_entry.install.clone(),
503 size: manifest_entry.artifact.size,
504 sha: manifest_entry.artifact.sha256.clone(),
505 mode: *mode,
506 });
507 }
508 if !manifest_by_asset.is_empty() {
509 return Err(fail("bundle contract and manifest entries differ"));
510 }
511 if p.modes.len() != projected.len() {
512 return Err(fail(
513 "bundle install policy is missing or has extra install names",
514 ));
515 }
516 out.push(TargetProjection::Bundle {
517 os: os.into(),
518 arch: arch.into(),
519 entries: projected,
520 });
521 }
522 (
523 eggpack_contract::ExpandedAssets::Archive(a),
524 ArtifactForm::Archive { artifact, members },
525 ) => {
526 let p = target_policy
527 .ok_or_else(|| fail("archive target is missing install policy"))?;
528 if p.archive_encoding != Some(BundleArchiveEncoding::TarGzip) {
529 return Err(fail(
530 "archive target requires explicit TarGzip install policy",
531 ));
532 }
533 if !a.archive_file.ends_with(".tar.gz") {
534 return Err(fail("TarGzip archive filename must end in .tar.gz"));
535 }
536 if a.archive_file != artifact.name {
537 return Err(fail("archive contract and manifest filenames differ"));
538 }
539 if !safe_segment(&artifact.name) {
540 return Err(fail(
541 "artifact and install basenames contain unsupported URL or platform characters",
542 ));
543 }
544 if a.members.len() != members.len() {
545 return Err(fail("archive contract and manifest member counts differ"));
546 }
547 let mut manifest_by_source: BTreeMap<&str, _> = BTreeMap::new();
548 for member in members {
549 if manifest_by_source
551 .insert(member.source.as_str(), member)
552 .is_some()
553 {
554 return Err(fail("duplicate archive manifest member"));
555 }
556 }
557 let mut projected = Vec::with_capacity(a.members.len());
558 for contract_member in &a.members {
559 let manifest_member = manifest_by_source
560 .remove(contract_member.source.as_str())
561 .ok_or_else(|| {
562 fail("archive contract and manifest member sources differ")
563 })?;
564 if manifest_member.install != contract_member.install_name {
565 return Err(fail("archive contract and manifest install names differ"));
566 }
567 if !safe_segment(&manifest_member.install) {
568 return Err(fail(
569 "artifact and install basenames contain unsupported URL or platform characters",
570 ));
571 }
572 let mode = p.modes.get(&contract_member.install_name).ok_or_else(|| {
573 fail("archive install policy is missing or has extra install names")
574 })?;
575 projected.push(ArchiveMemberProjection {
576 source: manifest_member.source.clone(),
577 install: manifest_member.install.clone(),
578 size: manifest_member.bytes.size,
579 sha: manifest_member.bytes.sha256.clone(),
580 mode: *mode,
581 });
582 }
583 if !manifest_by_source.is_empty() {
584 return Err(fail("archive contract and manifest member sources differ"));
585 }
586 if p.modes.len() != projected.len() {
587 return Err(fail(
588 "archive install policy is missing or has extra install names",
589 ));
590 }
591 out.push(TargetProjection::Archive {
592 os: os.into(),
593 arch: arch.into(),
594 archive_name: artifact.name.clone(),
595 archive_size: artifact.size,
596 archive_sha: artifact.sha256.clone(),
597 members: projected,
598 });
599 }
600 _ => {
601 return Err(fail("contract and manifest forms differ for target"));
602 }
603 }
604 }
605 if out.len() != c.targets.len() {
606 return Err(fail("contract and manifest target sets differ"));
607 }
608 for extra in policy.targets.keys() {
609 if !seen_targets.contains(extra.as_str()) {
610 return Err(fail("install policy names an unknown target"));
611 }
612 }
613 out.sort_by(|a, b| {
614 let key = |p: &TargetProjection| match p {
615 TargetProjection::Direct { os, arch, .. }
616 | TargetProjection::Bundle { os, arch, .. }
617 | TargetProjection::Archive { os, arch, .. } => (os.clone(), arch.clone()),
618 };
619 key(a).cmp(&key(b))
620 });
621 Ok(out)
622}
623
624fn posix_mode(mode: InstallMode) -> &'static str {
625 match mode {
626 InstallMode::Executable => "755",
627 InstallMode::Data => "644",
628 }
629}
630
631const POSIX_SHA_SNIPPET: &str = "if command -v sha256sum >/dev/null 2>&1; then actual=$(sha256sum \"$file_arg\" | cut -d ' ' -f 1); elif command -v shasum >/dev/null 2>&1; then actual=$(shasum -a 256 \"$file_arg\" | cut -d ' ' -f 1); elif command -v openssl >/dev/null 2>&1; then actual=$(openssl dgst -sha256 \"$file_arg\" | sed 's/^.*= //'); else echo 'SHA-256 tool required' >&2; exit 7; fi";
632
633fn posix_verify_block(tmp_file: &str, size: u64, sha: &str) -> String {
634 let size_check = format!(
635 "actual=$(wc -c < {tmp} | tr -d ' ')\n [ \"$actual\" = \"{size}\" ] || {{ echo 'size mismatch' >&2; exit 6; }}\n",
636 tmp = tmp_file,
637 size = size
638 );
639 let sha_check = POSIX_SHA_SNIPPET.replace("$file_arg", tmp_file)
640 + &format!(
641 "\n [ \"$actual\" = {sha} ] || {{ echo 'SHA-256 mismatch' >&2; exit 8; }}\n",
642 sha = shq(sha)
643 );
644 size_check + &sha_check
645}
646
647fn posix_download_block(origin: &str, name: &str, tmp_file: &str) -> String {
648 format!(
649 " if command -v curl >/dev/null 2>&1; then curl --fail --silent --show-error --connect-timeout 10 --max-time 120 {origin}/{name} -o {tmp}; else echo 'curl is required' >&2; exit 5; fi\n",
650 origin = shq(origin),
651 name = shq(name),
652 tmp = tmp_file
653 )
654}
655
656pub fn render_posix_with_policy(
658 c: &DistributionContract,
659 m: &ReleaseManifest,
660 s: &BootstrapSpec,
661 policy: &BootstrapInstallPolicyV1,
662) -> Result<String, BootstrapError> {
663 let targets = project_all(c, m, s, policy)?;
664 let mut branches = String::new();
665 for target in &targets {
666 match target {
667 TargetProjection::Direct {
668 os,
669 arch,
670 name,
671 install,
672 size,
673 sha,
674 } => {
675 let tmp_file = "\"$tmp/payload\"";
676 branches.push_str(&format!(
677 " {os}:{arch})\n file=\"$dest\"/{install}\n [ ! -e \"$file\" ] || {{ echo 'destination already exists' >&2; exit 3; }}\n{download}{verify} [ ! -e \"$file\" ] || {{ echo 'destination already exists' >&2; exit 3; }}\n chmod 755 {payload}\n ln {payload} \"$file\" || {{ echo 'destination already exists or filesystem does not support safe placement' >&2; exit 3; }}\n exit 0\n ;;\n",
678 os = os,
679 arch = arch,
680 install = shq(install),
681 download = posix_download_block(&s.origin, name, tmp_file),
682 verify = posix_verify_block(tmp_file, *size, sha),
683 payload = tmp_file,
684 ));
685 }
686 TargetProjection::Bundle { os, arch, entries } => {
687 let mut block = format!(" {os}:{arch})\n");
688 for (index, entry) in entries.iter().enumerate() {
689 block.push_str(&format!(
690 " file{index}=\"$dest\"/{install}\n",
691 index = index,
692 install = shq(&entry.install)
693 ));
694 }
695 for index in 0..entries.len() {
696 block.push_str(&format!(
697 " [ ! -e \"$file{index}\" ] || {{ echo 'destination already exists' >&2; exit 3; }}\n",
698 index = index
699 ));
700 }
701 for (index, entry) in entries.iter().enumerate() {
702 let tmp_file = format!("\"$tmp/bundle-{index}\"", index = index);
703 block.push_str(&posix_download_block(&s.origin, &entry.name, &tmp_file));
704 block.push_str(&format!(
705 " {}",
706 posix_verify_block(&tmp_file, entry.size, &entry.sha)
707 .replace('\n', "\n ")
708 .trim_end()
709 ));
710 block.push('\n');
711 }
712 for index in 0..entries.len() {
713 block.push_str(&format!(
714 " [ ! -e \"$file{index}\" ] || {{ echo 'destination already exists' >&2; exit 3; }}\n",
715 index = index
716 ));
717 }
718 for (index, entry) in entries.iter().enumerate() {
719 block.push_str(&format!(
720 " chmod {mode} \"$tmp/bundle-{index}\"\n",
721 mode = posix_mode(entry.mode),
722 index = index
723 ));
724 }
725 for (index, _) in entries.iter().enumerate() {
726 if index == 0 {
727 block.push_str(&format!(
728 " ln \"$tmp/bundle-{index}\" \"$file{index}\" || {{ echo 'destination already exists or filesystem does not support safe placement' >&2; exit 3; }}\n",
729 index = index
730 ));
731 } else {
732 let mut rollback = String::new();
733 for prior in 0..index {
734 rollback.push_str(&format!(" \"$file{prior}\"", prior = prior));
735 }
736 block.push_str(&format!(
737 " ln \"$tmp/bundle-{index}\" \"$file{index}\" || {{ rm -f{rollback}; echo 'destination already exists or filesystem does not support safe placement' >&2; exit 3; }}\n",
738 index = index,
739 rollback = rollback
740 ));
741 }
742 }
743 block.push_str(" exit 0\n ;;\n");
744 branches.push_str(&block);
745 }
746 TargetProjection::Archive {
747 os,
748 arch,
749 archive_name,
750 archive_size,
751 archive_sha,
752 members,
753 } => {
754 let mut block = format!(" {os}:{arch})\n");
755 for (index, member) in members.iter().enumerate() {
756 block.push_str(&format!(
757 " dest{index}=\"$dest\"/{install}\n",
758 index = index,
759 install = shq(&member.install)
760 ));
761 }
762 for index in 0..members.len() {
763 block.push_str(&format!(
764 " [ ! -e \"$dest{index}\" ] || {{ echo 'destination already exists' >&2; exit 3; }}\n",
765 index = index
766 ));
767 }
768 block.push_str(" if ! command -v tar >/dev/null 2>&1; then echo 'tar is required' >&2; exit 5; fi\n");
769 let archive_tmp = "\"$tmp/archive\"";
770 block.push_str(&posix_download_block(&s.origin, archive_name, archive_tmp));
771 block.push_str(&format!(
772 " {}",
773 posix_verify_block(archive_tmp, *archive_size, archive_sha)
774 .replace('\n', "\n ")
775 .trim_end()
776 ));
777 block.push('\n');
778 let mut expected_printf = String::from(" printf '%s\\n'");
779 for member in members {
780 expected_printf.push_str(&format!(" {}", shq(&member.source)));
781 }
782 expected_printf.push_str(" > \"$tmp/expected\"\n");
783 block.push_str(&expected_printf);
784 block.push_str(" if ! tar -tzf \"$tmp/archive\" > \"$tmp/listing\"; then echo 'archive listing failed' >&2; exit 6; fi\n");
785 block.push_str(" while IFS= read -r line; do case \"$line\" in '') echo 'unsafe archive member' >&2; exit 6 ;; /*) echo 'unsafe archive member' >&2; exit 6 ;; *\\\\*) echo 'unsafe archive member' >&2; exit 6 ;; *:* ) echo 'unsafe archive member' >&2; exit 6 ;; esac; case \"$line\" in *'..'*) echo 'unsafe archive member' >&2; exit 6 ;; esac; done < \"$tmp/listing\"\n");
786 block.push_str(" if ! LC_ALL=C sort \"$tmp/expected\" > \"$tmp/expected.sorted\"; then echo 'archive inventory failed' >&2; exit 6; fi\n");
787 block.push_str(" if ! LC_ALL=C sort \"$tmp/listing\" > \"$tmp/listing.sorted\"; then echo 'archive inventory failed' >&2; exit 6; fi\n");
788 block.push_str(" if ! cmp -s \"$tmp/expected.sorted\" \"$tmp/listing.sorted\"; then echo 'archive member inventory mismatch' >&2; exit 6; fi\n");
789 block.push_str(" mkdir -p \"$tmp/extracted\"\n");
790 block.push_str(" if ! tar -xzf \"$tmp/archive\" -C \"$tmp/extracted\"; then echo 'archive extraction failed' >&2; exit 6; fi\n");
791 for member in members {
792 block.push_str(&format!(
793 " member=\"$tmp/extracted\"/{source}\n [ ! -L \"$member\" ] || {{ echo 'symlink member rejected' >&2; exit 6; }}\n [ -f \"$member\" ] || {{ echo 'member is not a regular file' >&2; exit 6; }}\n",
794 source = shq(&member.source)
795 ));
796 let member_var = "\"$member\"";
797 block.push_str(&format!(
798 " {}",
799 posix_verify_block(member_var, member.size, &member.sha)
800 .replace('\n', "\n ")
801 .trim_end()
802 ));
803 block.push('\n');
804 block.push_str(&format!(
805 " chmod {mode} \"$member\"\n",
806 mode = posix_mode(member.mode)
807 ));
808 }
809 for index in 0..members.len() {
810 block.push_str(&format!(
811 " [ ! -e \"$dest{index}\" ] || {{ echo 'destination already exists' >&2; exit 3; }}\n",
812 index = index
813 ));
814 }
815 for (index, member) in members.iter().enumerate() {
816 if index == 0 {
817 block.push_str(&format!(
818 " ln \"$tmp/extracted\"/{source} \"$dest{index}\" || {{ echo 'destination already exists or filesystem does not support safe placement' >&2; exit 3; }}\n",
819 source = shq(&member.source),
820 index = index
821 ));
822 } else {
823 let mut rollback = String::new();
824 for prior in 0..index {
825 rollback.push_str(&format!(" \"$dest{prior}\"", prior = prior));
826 }
827 block.push_str(&format!(
828 " ln \"$tmp/extracted\"/{source} \"$dest{index}\" || {{ rm -f{rollback}; echo 'destination already exists or filesystem does not support safe placement' >&2; exit 3; }}\n",
829 source = shq(&member.source),
830 index = index,
831 rollback = rollback
832 ));
833 }
834 }
835 block.push_str(" exit 0\n ;;\n");
836 branches.push_str(&block);
837 }
838 }
839 }
840 Ok(format!(
841 r##"#!/bin/sh
842set -eu
843os=$(uname -s | tr '[:upper:]' '[:lower:]')
844case "$os" in darwin) os=macos ;; esac
845arch=$(uname -m)
846case "$arch" in amd64) arch=x86_64 ;; arm64) arch=aarch64 ;; armv7l) arch=armv7 ;; esac
847origin={origin}
848dest=${{1:-.}}
849mkdir -p "$dest"
850tmp=$(mktemp -d "$dest/.eggpack.XXXXXX") || exit 4
851trap 'rm -rf "$tmp"' 0
852trap 'exit 1' HUP INT TERM
853case "$os:$arch" in
854{branches} *) echo 'unsupported platform' >&2; exit 2 ;;
855esac
856"##,
857 origin = shq(&s.origin),
858 branches = branches
859 ))
860}
861
862fn ps_verify_block(payload_var: &str, size: u64, sha: &str) -> String {
863 format!(
864 " if ((Get-Item -LiteralPath {payload}).Length -ne {size}) {{ throw 'size mismatch' }}\n if ((Get-FileHash -LiteralPath {payload} -Algorithm SHA256).Hash.ToLowerInvariant() -ne {sha}) {{ throw 'SHA-256 mismatch' }}\n",
865 payload = payload_var,
866 size = size,
867 sha = psq(&sha.to_lowercase())
872 )
873}
874
875pub fn render_powershell_with_policy(
885 c: &DistributionContract,
886 m: &ReleaseManifest,
887 s: &BootstrapSpec,
888 policy: &BootstrapInstallPolicyV1,
889) -> Result<String, BootstrapError> {
890 let targets = project_all(c, m, s, policy)?;
891 let mut branches = String::new();
892 for target in &targets {
893 match target {
894 TargetProjection::Direct {
895 os,
896 arch,
897 name,
898 install,
899 size,
900 sha,
901 } => {
902 branches.push_str(&format!(
903 " '{os}:{arch}' {{\n $file = Join-Path $dest {install}\n if (Test-Path -LiteralPath $file) {{ throw 'destination already exists' }}\n $payload = Join-Path $tmp 'payload'\n Invoke-WebRequest -Uri \"$origin/{name}\" -OutFile $payload -TimeoutSec 120 -MaximumRedirection 0\n{verify} if (Test-Path -LiteralPath $file) {{ throw 'destination already exists' }}\n [IO.File]::Move($payload, $file)\n $created += $file\n }}\n",
904 os = os,
905 arch = arch,
906 install = psq(install),
907 name = name,
908 verify = ps_verify_block("$payload", *size, sha)
909 .lines()
910 .map(|l| format!(" {l}\n"))
911 .collect::<String>(),
912 ));
913 }
914 TargetProjection::Bundle { os, arch, entries } => {
915 let mut block = format!(" '{os}:{arch}' {{\n");
916 for (index, entry) in entries.iter().enumerate() {
917 block.push_str(&format!(
918 " $file{index} = Join-Path $dest {install}\n",
919 index = index,
920 install = psq(&entry.install)
921 ));
922 }
923 for index in 0..entries.len() {
924 block.push_str(&format!(
925 " if (Test-Path -LiteralPath $file{index}) {{ throw 'destination already exists' }}\n",
926 index = index
927 ));
928 }
929 for (index, entry) in entries.iter().enumerate() {
930 block.push_str(&format!(
931 " $payload{index} = Join-Path $tmp 'bundle-{index}'\n Invoke-WebRequest -Uri \"$origin/{name}\" -OutFile $payload{index} -TimeoutSec 120 -MaximumRedirection 0\n",
932 index = index,
933 name = entry.name
934 ));
935 block.push_str(
936 &ps_verify_block(
937 &format!("$payload{index}", index = index),
938 entry.size,
939 &entry.sha,
940 )
941 .lines()
942 .map(|l| format!(" {l}\n"))
943 .collect::<String>(),
944 );
945 }
946 for index in 0..entries.len() {
947 block.push_str(&format!(
948 " if (Test-Path -LiteralPath $file{index}) {{ throw 'destination already exists' }}\n",
949 index = index
950 ));
951 }
952 for (index, _) in entries.iter().enumerate() {
953 block.push_str(&format!(
954 " [IO.File]::Move($payload{index}, $file{index})\n $created += $file{index}\n",
955 index = index
956 ));
957 }
958 block.push_str(" }\n");
959 branches.push_str(&block);
960 }
961 TargetProjection::Archive {
962 os,
963 arch,
964 archive_name,
965 archive_size,
966 archive_sha,
967 members,
968 } => {
969 let mut block = format!(" '{os}:{arch}' {{\n");
970 for (index, member) in members.iter().enumerate() {
971 block.push_str(&format!(
972 " $dest{index} = Join-Path $dest {install}\n",
973 index = index,
974 install = psq(&member.install)
975 ));
976 }
977 for index in 0..members.len() {
978 block.push_str(&format!(
979 " if (Test-Path -LiteralPath $dest{index}) {{ throw 'destination already exists' }}\n",
980 index = index
981 ));
982 }
983 block.push_str(" if (-not (Get-Command tar.exe -ErrorAction SilentlyContinue)) { throw 'tar.exe is required' }\n");
984 block.push_str(&format!(
985 " $archive = Join-Path $tmp 'archive'\n Invoke-WebRequest -Uri \"$origin/{name}\" -OutFile $archive -TimeoutSec 120 -MaximumRedirection 0\n",
986 name = archive_name
987 ));
988 block.push_str(
989 &ps_verify_block("$archive", *archive_size, archive_sha)
990 .lines()
991 .map(|l| format!(" {l}\n"))
992 .collect::<String>(),
993 );
994 let expected_list = members
995 .iter()
996 .map(|member| psq(&member.source))
997 .collect::<Vec<_>>()
998 .join(", ");
999 block.push_str(&format!(
1000 " $expected = @({expected})\n $actual = & tar.exe -tzf $archive\n if ($LASTEXITCODE -ne 0) {{ throw 'archive listing failed' }}\n",
1001 expected = expected_list
1002 ));
1003 block.push_str(" foreach ($line in $actual) { if ([string]::IsNullOrEmpty($line)) { throw 'unsafe archive member' }; if ($line.StartsWith('/')) { throw 'unsafe archive member' }; if ($line.Contains('\\')) { throw 'unsafe archive member' }; if ($line.Contains(':')) { throw 'unsafe archive member' }; if ($line -match '\\.\\.') { throw 'unsafe archive member' } }\n");
1004 block.push_str(" $missing = @($expected | Where-Object { $actual -cnotcontains $_ }); if ($missing.Count -gt 0) { throw 'archive member inventory mismatch' }\n");
1009 block.push_str(" $extra = @($actual | Where-Object { $expected -cnotcontains $_ }); if ($extra.Count -gt 0) { throw 'archive member inventory mismatch' }\n");
1010 block.push_str(" $extractDir = Join-Path $tmp 'extracted'\n New-Item -ItemType Directory -Path $extractDir | Out-Null\n & tar.exe -xzf $archive -C $extractDir\n if ($LASTEXITCODE -ne 0) { throw 'archive extraction failed' }\n");
1011 for member in members {
1012 block.push_str(&format!(
1013 " $member = Join-Path $extractDir {source}\n if ((Get-Item -LiteralPath $member).LinkType) {{ throw 'symlink member rejected' }}\n if (-not (Test-Path -LiteralPath $member -PathType Leaf)) {{ throw 'member is not a regular file' }}\n",
1014 source = psq(&member.source)
1015 ));
1016 block.push_str(
1017 &ps_verify_block("$member", member.size, &member.sha)
1018 .lines()
1019 .map(|l| format!(" {l}\n"))
1020 .collect::<String>(),
1021 );
1022 }
1023 for index in 0..members.len() {
1024 block.push_str(&format!(
1025 " if (Test-Path -LiteralPath $dest{index}) {{ throw 'destination already exists' }}\n",
1026 index = index
1027 ));
1028 }
1029 for (index, member) in members.iter().enumerate() {
1030 block.push_str(&format!(
1031 " $member{index} = Join-Path $extractDir {source}\n [IO.File]::Move($member{index}, $dest{index})\n $created += $dest{index}\n",
1032 index = index,
1033 source = psq(&member.source)
1034 ));
1035 }
1036 block.push_str(" }\n");
1037 branches.push_str(&block);
1038 }
1039 }
1040 }
1041 Ok(format!(
1042 r#"$ErrorActionPreference = 'Stop'
1043$os = if ($env:OS -eq 'Windows_NT') {{ 'windows' }} elseif ($IsMacOS) {{ 'macos' }} else {{ 'linux' }}
1044$arch = [Runtime.InteropServices.RuntimeInformation]::OSArchitecture.ToString().ToLowerInvariant()
1045switch ($arch) {{ 'x64' {{ $arch='x86_64' }} 'arm64' {{ $arch='aarch64' }} 'arm' {{ $arch='armv7' }} }}
1046$origin = {origin}
1047$dest = if ($args.Count -gt 0) {{ $args[0] }} else {{ '.' }}
1048New-Item -ItemType Directory -Force -Path $dest | Out-Null
1049$tmp = Join-Path $dest ('.eggpack-' + [Guid]::NewGuid().ToString('N'))
1050New-Item -ItemType Directory -Path $tmp | Out-Null
1051$created = @()
1052try {{
1053 switch ("$os`:$arch") {{
1054{branches} default {{ throw 'unsupported platform' }}
1055 }}
1056}} catch {{
1057 foreach ($p in $created) {{ Remove-Item -LiteralPath $p -Force -ErrorAction SilentlyContinue }}
1058 throw
1059}} finally {{ Remove-Item -LiteralPath $tmp -Recurse -Force -ErrorAction SilentlyContinue }}
1060"#,
1061 origin = psq(&s.origin),
1062 branches = branches
1063 ))
1064}
1065
1066#[cfg(test)]
1067mod tests {
1068 use super::*;
1069 #[cfg(unix)]
1070 fn serve_once(body: &'static [u8], status: &'static str) -> String {
1071 use std::{
1072 io::{Read, Write},
1073 net::TcpListener,
1074 thread,
1075 };
1076 let listener = TcpListener::bind("127.0.0.1:0").unwrap();
1077 let address = listener.local_addr().unwrap();
1078 thread::spawn(move || {
1079 let (mut stream, _) = listener.accept().unwrap();
1080 let mut request = [0u8; 1024];
1081 let _ = stream.read(&mut request);
1082 write!(
1083 stream,
1084 "HTTP/1.1 {status}\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",
1085 body.len()
1086 )
1087 .unwrap();
1088 stream.write_all(body).unwrap();
1089 });
1090 format!("http://{address}/releases")
1091 }
1092 #[test]
1093 fn exact_direct_maps_render_stable_scripts_and_reject_bad_origin() {
1094 use std::process::Command;
1095 let c = DistributionContract::parse_toml_str(include_str!(
1096 "../../eggpack-contract/tests/fixtures/simple-direct.toml"
1097 ))
1098 .unwrap();
1099 let m = ReleaseManifest {
1100 schema_version: 1,
1101 product_id: "eggsact".into(),
1102 release_id: "1.2.6".into(),
1103 source_revision: "a".repeat(40),
1104 targets: vec![
1105 eggpack_manifest::TargetRecord {
1106 target: "x86_64-unknown-linux-gnu".into(),
1107 form: ArtifactForm::Direct {
1108 artifact: eggpack_manifest::ArtifactRecord {
1109 name: "eggsact-1.2.6-x86_64-unknown-linux-gnu".into(),
1110 size: 3,
1111 sha256:
1112 "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
1113 .into(),
1114 },
1115 install: "eggsact".into(),
1116 },
1117 },
1118 eggpack_manifest::TargetRecord {
1119 target: "aarch64-apple-darwin".into(),
1120 form: ArtifactForm::Direct {
1121 artifact: eggpack_manifest::ArtifactRecord {
1122 name: "eggsact-1.2.6-aarch64-apple-darwin".into(),
1123 size: 3,
1124 sha256:
1125 "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
1126 .into(),
1127 },
1128 install: "eggsact".into(),
1129 },
1130 },
1131 ],
1132 evidence_references: vec![],
1133 };
1134 let spec = BootstrapSpec {
1135 origin: "https://example.invalid/releases".into(),
1136 fixture_http: false,
1137 };
1138 let a = render_posix(&c, &m, &spec).unwrap();
1139 assert_eq!(a, render_posix(&c, &m, &spec).unwrap());
1140 assert!(a.contains("--connect-timeout 10 --max-time 120"));
1141 assert!(!a.contains("sudo"));
1142 #[cfg(unix)]
1143 assert!(std::process::Command::new("sh")
1144 .arg("-n")
1145 .arg("-c")
1146 .arg(&a)
1147 .status()
1148 .unwrap()
1149 .success());
1150 let ps = render_powershell(&c, &m, &spec).unwrap();
1151 assert!(ps.contains("Get-FileHash"));
1152 let ps_path =
1153 std::env::temp_dir().join(format!("eggpack-ps-parse-{}.ps1", std::process::id()));
1154 std::fs::write(&ps_path, &ps).unwrap();
1155 let shell = if cfg!(windows) {
1156 "powershell.exe"
1157 } else {
1158 "pwsh"
1159 };
1160 if Command::new(shell).arg("-Version").output().is_ok() {
1161 let parser = format!("$tokens=$null;$errors=$null;[System.Management.Automation.Language.Parser]::ParseFile({},[ref]$tokens,[ref]$errors)|Out-Null;if($errors.Count -gt 0){{exit 1}}", psq(&ps_path.to_string_lossy()));
1162 assert!(Command::new(shell)
1163 .args(["-NoProfile", "-NonInteractive", "-Command", &parser])
1164 .status()
1165 .unwrap()
1166 .success());
1167 }
1168 let _ = std::fs::remove_file(ps_path);
1169 let bad = BootstrapSpec {
1170 origin: "http://example.invalid".into(),
1171 fixture_http: true,
1172 };
1173 assert!(render_posix(&c, &m, &bad).is_err());
1174 }
1175 #[test]
1176 fn mismatch_fails_before_text_is_emitted() {
1177 let c = DistributionContract::parse_toml_str(include_str!(
1178 "../../eggpack-contract/tests/fixtures/simple-direct.toml"
1179 ))
1180 .unwrap();
1181 let m = ReleaseManifest {
1182 schema_version: 1,
1183 product_id: "other".into(),
1184 release_id: "1".into(),
1185 source_revision: "a".repeat(40),
1186 targets: vec![],
1187 evidence_references: vec![],
1188 };
1189 assert!(render_posix(
1190 &c,
1191 &m,
1192 &BootstrapSpec {
1193 origin: "https://x".into(),
1194 fixture_http: false
1195 }
1196 )
1197 .is_err());
1198 }
1199 #[cfg(unix)]
1200 #[test]
1201 fn generated_shell_installs_verified_bytes_and_refuses_existing_file() {
1202 use std::{fs, process::Command};
1203 let c = DistributionContract::parse_toml_str(include_str!(
1204 "../../eggpack-contract/tests/fixtures/simple-direct.toml"
1205 ))
1206 .unwrap();
1207 let m = ReleaseManifest {
1208 schema_version: 1,
1209 product_id: "eggsact".into(),
1210 release_id: "1.2.6".into(),
1211 source_revision: "a".repeat(40),
1212 targets: vec![
1213 eggpack_manifest::TargetRecord {
1214 target: "x86_64-unknown-linux-gnu".into(),
1215 form: ArtifactForm::Direct {
1216 artifact: eggpack_manifest::ArtifactRecord {
1217 name: "eggsact-1.2.6-x86_64-unknown-linux-gnu".into(),
1218 size: 3,
1219 sha256:
1220 "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
1221 .into(),
1222 },
1223 install: "eggsact".into(),
1224 },
1225 },
1226 eggpack_manifest::TargetRecord {
1227 target: "aarch64-apple-darwin".into(),
1228 form: ArtifactForm::Direct {
1229 artifact: eggpack_manifest::ArtifactRecord {
1230 name: "eggsact-1.2.6-aarch64-apple-darwin".into(),
1231 size: 3,
1232 sha256:
1233 "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
1234 .into(),
1235 },
1236 install: "eggsact".into(),
1237 },
1238 },
1239 ],
1240 evidence_references: vec![],
1241 };
1242 let origin = serve_once(b"abc", "200 OK");
1243 let script = render_posix(
1244 &c,
1245 &m,
1246 &BootstrapSpec {
1247 origin,
1248 fixture_http: true,
1249 },
1250 )
1251 .unwrap();
1252 let root =
1253 std::env::temp_dir().join(format!("eggpack-bootstrap-test-{}", std::process::id()));
1254 let dest = root.join("destination");
1255 fs::create_dir_all(&root).unwrap();
1256 let script_path = root.join("install.sh");
1257 fs::write(&script_path, script).unwrap();
1258 assert!(Command::new("sh")
1259 .arg(&script_path)
1260 .arg(&dest)
1261 .status()
1262 .unwrap()
1263 .success());
1264 assert_eq!(fs::read(dest.join("eggsact")).unwrap(), b"abc");
1265 assert!(!Command::new("sh")
1266 .arg(&script_path)
1267 .arg(&dest)
1268 .output()
1269 .unwrap()
1270 .status
1271 .success());
1272 let host_target = match (std::env::consts::OS, std::env::consts::ARCH) {
1273 ("macos", "aarch64") => "aarch64-apple-darwin",
1274 ("macos", _) => "x86_64-apple-darwin",
1275 (_, "aarch64") => "aarch64-unknown-linux-gnu",
1276 _ => "x86_64-unknown-linux-gnu",
1277 };
1278 let selected = m
1279 .targets
1280 .iter()
1281 .position(|target| target.target == host_target)
1282 .unwrap();
1283 if Command::new("pwsh").arg("-Version").output().is_ok() {
1284 let run_ps = |label: &str,
1285 manifest: &ReleaseManifest,
1286 body: &'static [u8],
1287 response: &'static str| {
1288 let origin = serve_once(body, response);
1289 let script = render_powershell(
1290 &c,
1291 manifest,
1292 &BootstrapSpec {
1293 origin,
1294 fixture_http: true,
1295 },
1296 )
1297 .unwrap();
1298 let script_path = root.join(format!("{label}.ps1"));
1299 let destination = root.join(format!("{label}-destination"));
1300 fs::write(&script_path, script).unwrap();
1301 let result = Command::new("pwsh")
1302 .arg("-NoProfile")
1303 .arg("-File")
1304 .arg(&script_path)
1305 .arg(&destination)
1306 .output()
1307 .unwrap();
1308 (result.status.success(), destination, script_path)
1309 };
1310 let (ok, ps_dest, ps_path) = run_ps("install", &m, b"abc", "200 OK");
1311 assert!(ok);
1312 assert_eq!(fs::read(ps_dest.join("eggsact")).unwrap(), b"abc");
1313 let repeat = Command::new("pwsh")
1314 .arg("-NoProfile")
1315 .arg("-File")
1316 .arg(&ps_path)
1317 .arg(&ps_dest)
1318 .output()
1319 .unwrap();
1320 assert!(!repeat.status.success());
1321 let mut bad_size_ps = m.clone();
1322 if let ArtifactForm::Direct { artifact, .. } = &mut bad_size_ps.targets[selected].form {
1323 artifact.size = 4;
1324 }
1325 let (ok, dest, _) = run_ps("bad-size-powershell", &bad_size_ps, b"abc", "200 OK");
1326 assert!(!ok);
1327 assert_eq!(fs::read_dir(dest).unwrap().count(), 0);
1328 let mut bad_digest_ps = m.clone();
1329 if let ArtifactForm::Direct { artifact, .. } = &mut bad_digest_ps.targets[selected].form
1330 {
1331 artifact.sha256 = "ff".repeat(32);
1332 }
1333 let (ok, dest, _) = run_ps("bad-digest-powershell", &bad_digest_ps, b"abc", "200 OK");
1334 assert!(!ok);
1335 assert_eq!(fs::read_dir(dest).unwrap().count(), 0);
1336 let (ok, dest, _) = run_ps("missing-powershell", &m, b"", "404 Not Found");
1337 assert!(!ok);
1338 assert_eq!(fs::read_dir(dest).unwrap().count(), 0);
1339 }
1340 let mut bad_size = m.clone();
1341 if let ArtifactForm::Direct { artifact, .. } = &mut bad_size.targets[selected].form {
1342 artifact.size = 4;
1343 }
1344 let origin = serve_once(b"abc", "200 OK");
1345 let bad_script = render_posix(
1346 &c,
1347 &bad_size,
1348 &BootstrapSpec {
1349 origin,
1350 fixture_http: true,
1351 },
1352 )
1353 .unwrap();
1354 let bad_path = root.join("bad-size.sh");
1355 let bad_dest = root.join("bad-size-dest");
1356 fs::write(&bad_path, bad_script).unwrap();
1357 assert!(!Command::new("sh")
1358 .arg(&bad_path)
1359 .arg(&bad_dest)
1360 .output()
1361 .unwrap()
1362 .status
1363 .success());
1364 assert_eq!(fs::read_dir(&bad_dest).unwrap().count(), 0);
1365 let mut bad_digest = m.clone();
1366 if let ArtifactForm::Direct { artifact, .. } = &mut bad_digest.targets[selected].form {
1367 artifact.sha256 = "ff".repeat(32);
1368 }
1369 let origin = serve_once(b"abc", "200 OK");
1370 let bad_script = render_posix(
1371 &c,
1372 &bad_digest,
1373 &BootstrapSpec {
1374 origin,
1375 fixture_http: true,
1376 },
1377 )
1378 .unwrap();
1379 let bad_path = root.join("bad-digest.sh");
1380 let bad_dest = root.join("bad-digest-dest");
1381 fs::write(&bad_path, bad_script).unwrap();
1382 assert!(!Command::new("sh")
1383 .arg(&bad_path)
1384 .arg(&bad_dest)
1385 .output()
1386 .unwrap()
1387 .status
1388 .success());
1389 assert_eq!(fs::read_dir(&bad_dest).unwrap().count(), 0);
1390 let origin = serve_once(b"", "404 Not Found");
1391 let missing_script = render_posix(
1392 &c,
1393 &m,
1394 &BootstrapSpec {
1395 origin,
1396 fixture_http: true,
1397 },
1398 )
1399 .unwrap();
1400 let missing_path = root.join("missing.sh");
1401 let missing_dest = root.join("missing-dest");
1402 fs::write(&missing_path, missing_script).unwrap();
1403 assert!(!Command::new("sh")
1404 .arg(&missing_path)
1405 .arg(&missing_dest)
1406 .output()
1407 .unwrap()
1408 .status
1409 .success());
1410 assert_eq!(fs::read_dir(&missing_dest).unwrap().count(), 0);
1411 fs::remove_dir_all(root).unwrap();
1412 }
1413
1414 use std::collections::HashMap;
1418
1419 fn sha_hex(bytes: &[u8]) -> String {
1420 use sha2::{Digest, Sha256};
1421 Sha256::digest(bytes)
1422 .iter()
1423 .map(|b| format!("{b:02x}"))
1424 .collect()
1425 }
1426
1427 fn serve_map(routes: HashMap<String, (Vec<u8>, String)>) -> String {
1428 use std::{
1429 io::{Read, Write},
1430 net::TcpListener,
1431 thread,
1432 };
1433 let listener = TcpListener::bind("127.0.0.1:0").unwrap();
1434 let address = listener.local_addr().unwrap();
1435 thread::spawn(move || {
1436 for stream in listener.incoming() {
1437 let Ok(mut stream) = stream else { break };
1438 let mut request = [0u8; 8192];
1439 let Ok(n) = stream.read(&mut request) else {
1440 continue;
1441 };
1442 let text = String::from_utf8_lossy(&request[..n]).to_string();
1443 let path = text
1444 .lines()
1445 .next()
1446 .unwrap_or("")
1447 .split_whitespace()
1448 .nth(1)
1449 .unwrap_or("/")
1450 .to_string();
1451 let key = path.split('?').next().unwrap_or("").to_string();
1454 let (body, status) = routes
1455 .get(&key)
1456 .cloned()
1457 .unwrap_or((vec![], "404 Not Found".into()));
1458 let _ = write!(
1459 stream,
1460 "HTTP/1.1 {status}\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",
1461 body.len()
1462 );
1463 let _ = stream.write_all(&body);
1464 }
1465 });
1466 format!("http://{address}/releases")
1467 }
1468
1469 fn bundle_contract() -> DistributionContract {
1470 DistributionContract::parse_toml_str(include_str!(
1471 "../../eggpack-contract/tests/fixtures/codegg-bundle.toml"
1472 ))
1473 .unwrap()
1474 }
1475
1476 fn host_triple() -> &'static str {
1477 match (std::env::consts::OS, std::env::consts::ARCH) {
1478 ("linux", "x86_64") => "x86_64-unknown-linux-gnu",
1479 ("linux", "aarch64") => "aarch64-unknown-linux-gnu",
1480 ("linux", _) => "x86_64-unknown-linux-gnu",
1481 ("macos", "aarch64") => "aarch64-apple-darwin",
1482 ("macos", _) => "x86_64-apple-darwin",
1483 ("windows", "x86_64") => "x86_64-pc-windows-msvc",
1484 ("windows", "aarch64") => "aarch64-pc-windows-msvc",
1485 _ => "x86_64-unknown-linux-gnu",
1486 }
1487 }
1488
1489 fn host_bundle_case() -> (
1490 DistributionContract,
1491 ReleaseManifest,
1492 BootstrapInstallPolicyV1,
1493 Vec<(String, Vec<u8>)>,
1494 ) {
1495 let triple = host_triple();
1496 let contract = DistributionContract::parse_toml_str(&format!(
1497 r#"schema_version = 1
1498[product]
1499id = "hostbundle"
1500[[targets]]
1501triple = "{triple}"
1502aliases = []
1503[targets.asset]
1504kind = "bundle"
1505[[targets.asset.entries]]
1506asset = "{{product}}-{{version}}-{{target}}-main"
1507install = "host-main"
1508[[targets.asset.entries]]
1509asset = "{{product}}-helper-{{version}}-{{target}}"
1510install = "host-helper"
1511[[targets.asset.entries]]
1512asset = "{{product}}-manifest-{{version}}.json"
1513install = "host-manifest.json"
1514[targets.checksum]
1515sidecar = "{{asset}}.sha256"
1516"#
1517 ))
1518 .unwrap();
1519 let bodies = [
1520 b"host-main-bytes".to_vec(),
1521 b"host-helper-bytes".to_vec(),
1522 b"{\"manifest\":true}".to_vec(),
1523 ];
1524 let expanded = contract.expand(triple, "1.0.0").unwrap();
1525 let bundle = match expanded.assets {
1526 eggpack_contract::ExpandedAssets::Bundle(b) => b,
1527 _ => panic!("bundle expected"),
1528 };
1529 let mut entries = Vec::new();
1530 let mut modes = BTreeMap::new();
1531 for (index, contract_entry) in bundle.entries.iter().enumerate() {
1532 let body = &bodies[index];
1533 entries.push(eggpack_manifest::BundleRecord {
1534 artifact: eggpack_manifest::ArtifactRecord {
1535 name: contract_entry.asset_file.clone(),
1536 size: body.len() as u64,
1537 sha256: sha_hex(body),
1538 },
1539 install: contract_entry.install_name.clone(),
1540 });
1541 let mode = if index == 2 {
1542 InstallMode::Data
1543 } else {
1544 InstallMode::Executable
1545 };
1546 modes.insert(contract_entry.install_name.clone(), mode);
1547 }
1548 let manifest = ReleaseManifest {
1549 schema_version: 1,
1550 product_id: "hostbundle".into(),
1551 release_id: "1.0.0".into(),
1552 source_revision: "a".repeat(40),
1553 targets: vec![eggpack_manifest::TargetRecord {
1554 target: triple.into(),
1555 form: ArtifactForm::Bundle { entries },
1556 }],
1557 evidence_references: vec![],
1558 };
1559 manifest.validate().unwrap();
1560 let policy = BootstrapInstallPolicyV1 {
1561 schema_version: 1,
1562 targets: [(
1563 triple.to_string(),
1564 TargetInstallPolicy {
1565 modes,
1566 archive_encoding: None,
1567 },
1568 )]
1569 .into_iter()
1570 .collect(),
1571 };
1572 let routes = bundle
1573 .entries
1574 .iter()
1575 .enumerate()
1576 .map(|(index, entry)| (entry.asset_file.clone(), bodies[index].clone()))
1577 .collect();
1578 (contract, manifest, policy, routes)
1579 }
1580
1581 #[allow(clippy::type_complexity)]
1582 fn host_archive_case() -> (
1583 DistributionContract,
1584 ReleaseManifest,
1585 BootstrapInstallPolicyV1,
1586 Vec<u8>,
1587 Vec<(String, Vec<u8>)>,
1588 ) {
1589 let triple = host_triple();
1590 let contract = DistributionContract::parse_toml_str(&format!(
1591 r#"schema_version = 1
1592[product]
1593id = "hostarchive"
1594[[targets]]
1595triple = "{triple}"
1596aliases = []
1597[targets.asset]
1598kind = "archive"
1599asset = "{{product}}-{{version}}-{{target}}.tar.gz"
1600[[targets.asset.members]]
1601source = "hostbin"
1602install = "hostbin"
1603[[targets.asset.members]]
1604source = "bin/host-helper"
1605install = "host-helper"
1606[targets.checksum]
1607sidecar = "{{asset}}.sha256"
1608"#
1609 ))
1610 .unwrap();
1611 let member_bodies = vec![
1612 ("hostbin".to_string(), b"hostbin-bytes".to_vec()),
1613 ("bin/host-helper".to_string(), b"host-helper-bytes".to_vec()),
1614 ];
1615 let archive_bytes = build_deterministic_tar_gz(&[
1616 ("hostbin", member_bodies[0].1.as_slice()),
1617 ("bin/host-helper", member_bodies[1].1.as_slice()),
1618 ]);
1619 let expanded = contract.expand(triple, "1.0.0").unwrap();
1620 let archive = match expanded.assets {
1621 eggpack_contract::ExpandedAssets::Archive(a) => a,
1622 _ => panic!("archive expected"),
1623 };
1624 let members = archive
1625 .members
1626 .iter()
1627 .map(|contract_member| {
1628 let body = member_bodies
1629 .iter()
1630 .find(|(source, _)| source == &contract_member.source)
1631 .unwrap();
1632 eggpack_manifest::ArchiveMemberRecord {
1633 source: contract_member.source.clone(),
1634 install: contract_member.install_name.clone(),
1635 bytes: eggpack_manifest::ByteEvidence {
1636 size: body.1.len() as u64,
1637 sha256: sha_hex(&body.1),
1638 },
1639 }
1640 })
1641 .collect::<Vec<_>>();
1642 let manifest = ReleaseManifest {
1643 schema_version: 1,
1644 product_id: "hostarchive".into(),
1645 release_id: "1.0.0".into(),
1646 source_revision: "b".repeat(40),
1647 targets: vec![eggpack_manifest::TargetRecord {
1648 target: triple.into(),
1649 form: ArtifactForm::Archive {
1650 artifact: eggpack_manifest::ArtifactRecord {
1651 name: archive.archive_file.clone(),
1652 size: archive_bytes.len() as u64,
1653 sha256: sha_hex(&archive_bytes),
1654 },
1655 members,
1656 },
1657 }],
1658 evidence_references: vec![],
1659 };
1660 manifest.validate().unwrap();
1661 let policy = BootstrapInstallPolicyV1 {
1662 schema_version: 1,
1663 targets: [(
1664 triple.to_string(),
1665 TargetInstallPolicy {
1666 modes: [
1667 ("hostbin".into(), InstallMode::Executable),
1668 ("host-helper".into(), InstallMode::Data),
1669 ]
1670 .into_iter()
1671 .collect(),
1672 archive_encoding: Some(BundleArchiveEncoding::TarGzip),
1673 },
1674 )]
1675 .into_iter()
1676 .collect(),
1677 };
1678 (contract, manifest, policy, archive_bytes, member_bodies)
1679 }
1680
1681 fn archive_contract() -> DistributionContract {
1682 DistributionContract::parse_toml_str(include_str!(
1683 "../../eggpack-contract/tests/fixtures/egress-archive.toml"
1684 ))
1685 .unwrap()
1686 }
1687
1688 fn bundle_manifest_and_bodies() -> (
1689 ReleaseManifest,
1690 Vec<(String, Vec<u8>)>,
1691 BootstrapInstallPolicyV1,
1692 ) {
1693 let bodies = vec![
1695 (b"codegg-main-bytes".to_vec(), "codegg"),
1696 (b"helper-bytes".to_vec(), "codegg-helper"),
1697 (b"{\"manifest\":true}".to_vec(), "codegg-manifest.json"),
1698 ];
1699 let contract = bundle_contract();
1700 let expanded = contract.expand("linux-x64", "2.4.0").unwrap();
1701 let bundle = match expanded.assets {
1702 eggpack_contract::ExpandedAssets::Bundle(b) => b,
1703 _ => panic!("bundle fixture changed"),
1704 };
1705 assert_eq!(bundle.entries.len(), 3);
1706 let mut manifest_entries = Vec::new();
1707 let mut policy_modes = BTreeMap::new();
1708 for (index, contract_entry) in bundle.entries.iter().enumerate() {
1709 let body = &bodies[index].0;
1710 manifest_entries.push(eggpack_manifest::BundleRecord {
1711 artifact: eggpack_manifest::ArtifactRecord {
1712 name: contract_entry.asset_file.clone(),
1713 size: body.len() as u64,
1714 sha256: sha_hex(body),
1715 },
1716 install: contract_entry.install_name.clone(),
1717 });
1718 let mode = if index == 2 {
1719 InstallMode::Data
1720 } else {
1721 InstallMode::Executable
1722 };
1723 policy_modes.insert(contract_entry.install_name.clone(), mode);
1724 }
1725 let manifest = ReleaseManifest {
1726 schema_version: 1,
1727 product_id: "codegg".into(),
1728 release_id: "2.4.0".into(),
1729 source_revision: "a".repeat(40),
1730 targets: vec![eggpack_manifest::TargetRecord {
1731 target: "x86_64-unknown-linux-gnu".into(),
1732 form: ArtifactForm::Bundle {
1733 entries: manifest_entries,
1734 },
1735 }],
1736 evidence_references: vec![],
1737 };
1738 manifest.validate().unwrap();
1739 let policy = BootstrapInstallPolicyV1 {
1740 schema_version: 1,
1741 targets: [(
1742 "x86_64-unknown-linux-gnu".into(),
1743 TargetInstallPolicy {
1744 modes: policy_modes,
1745 archive_encoding: None,
1746 },
1747 )]
1748 .into_iter()
1749 .collect(),
1750 };
1751 let route_bodies = bundle_entries_route_bodies(&contract, &manifest, &bodies);
1752 (manifest, route_bodies, policy)
1753 }
1754
1755 fn bundle_entries_route_bodies(
1756 contract: &DistributionContract,
1757 manifest: &ReleaseManifest,
1758 bodies: &[(Vec<u8>, &str)],
1759 ) -> Vec<(String, Vec<u8>)> {
1760 let expanded = contract.expand("linux-x64", &manifest.release_id).unwrap();
1761 let bundle = match expanded.assets {
1762 eggpack_contract::ExpandedAssets::Bundle(b) => b,
1763 _ => panic!("bundle expected"),
1764 };
1765 bundle
1766 .entries
1767 .iter()
1768 .enumerate()
1769 .map(|(index, entry)| (entry.asset_file.clone(), bodies[index].0.clone()))
1770 .collect()
1771 }
1772
1773 fn build_deterministic_tar_gz(members: &[(&str, &[u8])]) -> Vec<u8> {
1774 let file = Vec::new();
1775 let enc = flate2::GzBuilder::new()
1776 .mtime(0)
1777 .write(file, flate2::Compression::default());
1778 let mut archive = tar::Builder::new(enc);
1779 archive.mode(tar::HeaderMode::Deterministic);
1780 for (name, bytes) in members {
1781 let mut header = tar::Header::new_gnu();
1782 header.set_entry_type(tar::EntryType::Regular);
1783 header.set_path(name).unwrap();
1784 header.set_size(bytes.len() as u64);
1785 header.set_mode(0o755);
1786 header.set_uid(0);
1787 header.set_gid(0);
1788 header.set_mtime(0);
1789 header.set_cksum();
1790 archive.append(&header, *bytes).unwrap();
1791 }
1792 let enc = archive.into_inner().unwrap();
1793 enc.finish().unwrap()
1794 }
1795
1796 struct RawTarEntry<'a> {
1802 name: &'a str,
1803 kind: u8,
1804 linkname: &'a str,
1805 data: &'a [u8],
1806 }
1807
1808 fn build_raw_tar_gz(entries: &[RawTarEntry<'_>]) -> Vec<u8> {
1809 fn octal(value: u64, width: usize) -> Vec<u8> {
1810 let text = format!("{value:0width$o}", width = width - 1);
1811 let mut out = text.into_bytes();
1812 out.push(0);
1813 debug_assert_eq!(out.len(), width);
1814 out
1815 }
1816 let mut raw = Vec::new();
1817 for entry in entries {
1818 let mut header = [0u8; 512];
1819 let name = entry.name.as_bytes();
1820 assert!(
1821 !name.is_empty() && name.len() < 100,
1822 "raw name out of bounds"
1823 );
1824 header[..name.len()].copy_from_slice(name);
1825 header[100..108].copy_from_slice(&octal(0o755, 8));
1826 header[108..116].copy_from_slice(&octal(0, 8));
1827 header[116..124].copy_from_slice(&octal(0, 8));
1828 let size = if entry.kind == b'5' {
1829 0
1830 } else {
1831 entry.data.len() as u64
1832 };
1833 header[124..136].copy_from_slice(&octal(size, 12));
1834 header[136..148].copy_from_slice(&octal(0, 12));
1835 for b in header[148..156].iter_mut() {
1837 *b = b' ';
1838 }
1839 header[156] = entry.kind;
1840 let link = entry.linkname.as_bytes();
1841 assert!(link.len() < 100, "raw linkname out of bounds");
1842 header[157..157 + link.len()].copy_from_slice(link);
1843 header[257..262].copy_from_slice(b"ustar");
1844 header[263..265].copy_from_slice(b"00");
1845 let sum: u32 = header.iter().map(|b| *b as u32).sum();
1846 let text = format!("{sum:06o}\0 ");
1847 header[148..156].copy_from_slice(text.as_bytes());
1848 raw.extend_from_slice(&header);
1849 if entry.kind == b'0' {
1850 raw.extend_from_slice(entry.data);
1851 while raw.len() % 512 != 0 {
1852 raw.push(0);
1853 }
1854 }
1855 }
1856 raw.extend_from_slice(&[0u8; 1024]);
1857 let file = Vec::new();
1858 let mut enc = flate2::GzBuilder::new()
1859 .mtime(0)
1860 .write(file, flate2::Compression::default());
1861 use std::io::Write;
1862 enc.write_all(&raw).unwrap();
1863 enc.finish().unwrap()
1864 }
1865
1866 fn manifest_with_archive_bytes(manifest: &ReleaseManifest, bytes: &[u8]) -> ReleaseManifest {
1867 let mut updated = manifest.clone();
1868 if let ArtifactForm::Archive { artifact, .. } = &mut updated.targets[0].form {
1869 artifact.size = bytes.len() as u64;
1870 artifact.sha256 = sha_hex(bytes);
1871 } else {
1872 panic!("archive expected");
1873 }
1874 updated.validate().unwrap();
1875 updated
1876 }
1877
1878 fn pwsh_available() -> bool {
1879 std::process::Command::new("pwsh")
1880 .arg("-Version")
1881 .output()
1882 .is_ok()
1883 }
1884
1885 fn tar_exe_available() -> bool {
1886 #[cfg(windows)]
1887 {
1888 std::process::Command::new("tar.exe")
1889 .arg("--version")
1890 .output()
1891 .map(|o| o.status.success())
1892 .unwrap_or(false)
1893 || std::process::Command::new("pwsh")
1894 .args([
1895 "-NoProfile",
1896 "-NonInteractive",
1897 "-Command",
1898 "(Get-Command tar.exe -ErrorAction SilentlyContinue) -ne $null",
1899 ])
1900 .output()
1901 .map(|o| {
1902 o.status.success() && String::from_utf8_lossy(&o.stdout).trim() == "True"
1903 })
1904 .unwrap_or(false)
1905 }
1906 #[cfg(not(windows))]
1907 {
1908 std::process::Command::new("pwsh")
1911 .args([
1912 "-NoProfile",
1913 "-NonInteractive",
1914 "-Command",
1915 "(Get-Command tar.exe -ErrorAction SilentlyContinue) -ne $null",
1916 ])
1917 .output()
1918 .map(|o| o.status.success() && String::from_utf8_lossy(&o.stdout).trim() == "True")
1919 .unwrap_or(false)
1920 }
1921 }
1922
1923 #[allow(clippy::type_complexity)]
1924 fn archive_manifest_policy_and_archive() -> (
1925 ReleaseManifest,
1926 BootstrapInstallPolicyV1,
1927 Vec<u8>,
1928 Vec<(String, Vec<u8>)>,
1929 ) {
1930 let member_bodies = vec![
1932 ("egress".to_string(), b"egress-binary-bytes".to_vec()),
1933 (
1934 "bin/egress-helper".to_string(),
1935 b"helper-binary-bytes".to_vec(),
1936 ),
1937 ];
1938 let archive_bytes = build_deterministic_tar_gz(&[
1939 ("egress", member_bodies[0].1.as_slice()),
1940 ("bin/egress-helper", member_bodies[1].1.as_slice()),
1941 ]);
1942 let contract = archive_contract();
1943 let expanded = contract.expand("linux-x64", "3.1.0").unwrap();
1944 let archive = match expanded.assets {
1945 eggpack_contract::ExpandedAssets::Archive(a) => a,
1946 _ => panic!("archive expected"),
1947 };
1948 assert_eq!(archive.members.len(), 2);
1949 let members = archive
1950 .members
1951 .iter()
1952 .map(|contract_member| {
1953 let body = member_bodies
1954 .iter()
1955 .find(|(source, _)| source == &contract_member.source)
1956 .unwrap();
1957 eggpack_manifest::ArchiveMemberRecord {
1958 source: contract_member.source.clone(),
1959 install: contract_member.install_name.clone(),
1960 bytes: eggpack_manifest::ByteEvidence {
1961 size: body.1.len() as u64,
1962 sha256: sha_hex(&body.1),
1963 },
1964 }
1965 })
1966 .collect::<Vec<_>>();
1967 let manifest = ReleaseManifest {
1968 schema_version: 1,
1969 product_id: "egress".into(),
1970 release_id: "3.1.0".into(),
1971 source_revision: "b".repeat(40),
1972 targets: vec![eggpack_manifest::TargetRecord {
1973 target: "x86_64-unknown-linux-gnu".into(),
1974 form: ArtifactForm::Archive {
1975 artifact: eggpack_manifest::ArtifactRecord {
1976 name: archive.archive_file.clone(),
1977 size: archive_bytes.len() as u64,
1978 sha256: sha_hex(&archive_bytes),
1979 },
1980 members,
1981 },
1982 }],
1983 evidence_references: vec![],
1984 };
1985 manifest.validate().unwrap();
1986 let policy = BootstrapInstallPolicyV1 {
1987 schema_version: 1,
1988 targets: [(
1989 "x86_64-unknown-linux-gnu".into(),
1990 TargetInstallPolicy {
1991 modes: [
1992 ("egress".into(), InstallMode::Executable),
1993 ("egress-helper".into(), InstallMode::Data),
1994 ]
1995 .into_iter()
1996 .collect(),
1997 archive_encoding: Some(BundleArchiveEncoding::TarGzip),
1998 },
1999 )]
2000 .into_iter()
2001 .collect(),
2002 };
2003 (manifest, policy, archive_bytes, member_bodies)
2004 }
2005
2006 #[test]
2007 fn m002_policy_projection_matrix() {
2008 let bundle_contract = bundle_contract();
2009 let (bundle_manifest, _, bundle_policy) = bundle_manifest_and_bodies();
2010 let spec = BootstrapSpec {
2011 origin: "https://example.invalid/releases".into(),
2012 fixture_http: false,
2013 };
2014 let projected =
2016 project_all(&bundle_contract, &bundle_manifest, &spec, &bundle_policy).unwrap();
2017 assert_eq!(projected.len(), 1);
2018 assert!(matches!(projected[0], TargetProjection::Bundle { .. }));
2019
2020 let archive_contract = archive_contract();
2022 let (single_manifest, single_policy, _) = {
2024 let (m, p, _, _) = archive_manifest_policy_and_archive();
2025 (m, p, ())
2026 };
2027 assert!(project_all(&archive_contract, &single_manifest, &spec, &single_policy).is_err());
2029
2030 let mut unknown = single_manifest.clone();
2032 unknown.targets[0].target = "x86_64-pc-windows-gnu".into();
2033 assert!(project_all(&archive_contract, &unknown, &spec, &single_policy).is_err());
2034
2035 assert!(project_all(
2037 &bundle_contract,
2038 &bundle_manifest,
2039 &spec,
2040 &BootstrapInstallPolicyV1::empty()
2041 )
2042 .is_err());
2043
2044 let mut extra = bundle_policy.clone();
2046 extra.targets.insert(
2047 "aarch64-apple-darwin".into(),
2048 TargetInstallPolicy {
2049 modes: [("x".into(), InstallMode::Data)].into_iter().collect(),
2050 archive_encoding: None,
2051 },
2052 );
2053 assert!(project_all(&bundle_contract, &bundle_manifest, &spec, &extra).is_err());
2054
2055 assert!(
2057 BootstrapInstallPolicyV1::from_json(r#"{"schema_version":2,"targets":{}}"#).is_err()
2058 );
2059 assert!(BootstrapInstallPolicyV1::from_json(
2060 r#"{"schema_version":1,"targets":{},"extra":1}"#
2061 )
2062 .is_err());
2063 assert!(BootstrapInstallPolicyV1::from_toml("schema_version = 1\nunknown = 1").is_err());
2064
2065 let mut no_encoding = single_policy.clone();
2067 no_encoding
2068 .targets
2069 .get_mut("x86_64-unknown-linux-gnu")
2070 .unwrap()
2071 .archive_encoding = None;
2072 let single_target_contract = DistributionContract::parse_toml_str(
2075 r#"schema_version = 1
2076[product]
2077id = "egress"
2078[[targets]]
2079triple = "x86_64-unknown-linux-gnu"
2080aliases = []
2081[targets.asset]
2082kind = "archive"
2083asset = "{product}-{version}-{target}.tar.gz"
2084[[targets.asset.members]]
2085source = "egress"
2086install = "egress"
2087[targets.checksum]
2088sidecar = "{asset}.sha256"
2089"#,
2090 )
2091 .unwrap();
2092 let single_manifest_min = ReleaseManifest {
2093 schema_version: 1,
2094 product_id: "egress".into(),
2095 release_id: "3.1.0".into(),
2096 source_revision: "b".repeat(40),
2097 targets: vec![eggpack_manifest::TargetRecord {
2098 target: "x86_64-unknown-linux-gnu".into(),
2099 form: ArtifactForm::Archive {
2100 artifact: eggpack_manifest::ArtifactRecord {
2101 name: "egress-3.1.0-x86_64-unknown-linux-gnu.tar.gz".into(),
2102 size: 10,
2103 sha256: "ab".repeat(32),
2104 },
2105 members: vec![eggpack_manifest::ArchiveMemberRecord {
2106 source: "egress".into(),
2107 install: "egress".into(),
2108 bytes: eggpack_manifest::ByteEvidence {
2109 size: 3,
2110 sha256: "ab".repeat(32),
2111 },
2112 }],
2113 },
2114 }],
2115 evidence_references: vec![],
2116 };
2117 assert!(project_all(
2118 &single_target_contract,
2119 &single_manifest_min,
2120 &spec,
2121 &no_encoding
2122 )
2123 .is_err());
2124
2125 let mut archive_on_bundle = bundle_policy.clone();
2127 archive_on_bundle
2128 .targets
2129 .get_mut("x86_64-unknown-linux-gnu")
2130 .unwrap()
2131 .archive_encoding = Some(BundleArchiveEncoding::TarGzip);
2132 assert!(project_all(
2133 &bundle_contract,
2134 &bundle_manifest,
2135 &spec,
2136 &archive_on_bundle
2137 )
2138 .is_err());
2139
2140 let mut renamed = bundle_policy.clone();
2142 let modes = &mut renamed
2143 .targets
2144 .get_mut("x86_64-unknown-linux-gnu")
2145 .unwrap()
2146 .modes;
2147 let first_key = modes.keys().next().unwrap().clone();
2148 let first_mode = modes.remove(&first_key).unwrap();
2149 modes.insert("renamed-binary".into(), first_mode);
2150 assert!(project_all(&bundle_contract, &bundle_manifest, &spec, &renamed).is_err());
2151
2152 let direct_contract = DistributionContract::parse_toml_str(include_str!(
2154 "../../eggpack-contract/tests/fixtures/simple-direct.toml"
2155 ))
2156 .unwrap();
2157 let direct_manifest = ReleaseManifest {
2158 schema_version: 1,
2159 product_id: "eggsact".into(),
2160 release_id: "1.2.6".into(),
2161 source_revision: "a".repeat(40),
2162 targets: vec![
2163 eggpack_manifest::TargetRecord {
2164 target: "x86_64-unknown-linux-gnu".into(),
2165 form: ArtifactForm::Direct {
2166 artifact: eggpack_manifest::ArtifactRecord {
2167 name: "eggsact-1.2.6-x86_64-unknown-linux-gnu".into(),
2168 size: 3,
2169 sha256:
2170 "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
2171 .into(),
2172 },
2173 install: "eggsact".into(),
2174 },
2175 },
2176 eggpack_manifest::TargetRecord {
2177 target: "aarch64-apple-darwin".into(),
2178 form: ArtifactForm::Direct {
2179 artifact: eggpack_manifest::ArtifactRecord {
2180 name: "eggsact-1.2.6-aarch64-apple-darwin".into(),
2181 size: 3,
2182 sha256:
2183 "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
2184 .into(),
2185 },
2186 install: "eggsact".into(),
2187 },
2188 },
2189 ],
2190 evidence_references: vec![],
2191 };
2192 let old_posix = render_posix(&direct_contract, &direct_manifest, &spec).unwrap();
2193 assert!(old_posix.contains("curl --fail"));
2194 let new_posix = render_posix_with_policy(
2196 &direct_contract,
2197 &direct_manifest,
2198 &spec,
2199 &BootstrapInstallPolicyV1::empty(),
2200 )
2201 .unwrap();
2202 assert!(new_posix.contains("curl --fail"));
2203 assert_eq!(
2204 new_posix,
2205 render_posix_with_policy(
2206 &direct_contract,
2207 &direct_manifest,
2208 &spec,
2209 &BootstrapInstallPolicyV1::empty()
2210 )
2211 .unwrap()
2212 );
2213 }
2214
2215 #[cfg(unix)]
2216 #[test]
2217 fn m002_bundle_posix_runtime_matrix() {
2218 use std::{fs, os::unix::fs::PermissionsExt, process::Command};
2219 let (contract, manifest, policy, route_bodies) = host_bundle_case();
2220 let mut routes = HashMap::new();
2221 for (name, body) in &route_bodies {
2222 routes.insert(format!("/releases/{name}"), (body.clone(), "200 OK".into()));
2223 }
2224 let origin = serve_map(routes.clone());
2225 let spec = BootstrapSpec {
2226 origin: origin.clone(),
2227 fixture_http: true,
2228 };
2229 let script = render_posix_with_policy(&contract, &manifest, &spec, &policy).unwrap();
2230 assert_eq!(
2232 script,
2233 render_posix_with_policy(&contract, &manifest, &spec, &policy).unwrap()
2234 );
2235 assert!(Command::new("sh")
2237 .arg("-n")
2238 .arg("-c")
2239 .arg(&script)
2240 .status()
2241 .unwrap()
2242 .success());
2243 for forbidden in [
2244 "sudo",
2245 "Start-Process",
2246 "RunAs",
2247 "latest",
2248 "curl -L",
2249 "--location",
2250 "MaximumRedirection 1",
2251 ] {
2252 assert!(!script.contains(forbidden), "forbidden: {forbidden}");
2253 }
2254 assert!(!script
2255 .contains("curl --fail --silent --show-error --connect-timeout 10 --max-time 120 -L"));
2256
2257 let root = std::env::temp_dir().join(format!("eggpack-m002-bundle-{}", std::process::id()));
2258 let _ = fs::remove_dir_all(&root);
2259 fs::create_dir_all(&root).unwrap();
2260 let script_path = root.join("install.sh");
2261 fs::write(&script_path, &script).unwrap();
2262
2263 let dest = root.join("dest-ok");
2265 assert!(Command::new("sh")
2266 .arg(&script_path)
2267 .arg(&dest)
2268 .status()
2269 .unwrap()
2270 .success());
2271 let main_bytes = fs::read(dest.join("host-main")).unwrap();
2272 assert_eq!(main_bytes, b"host-main-bytes");
2273 assert_eq!(
2274 fs::read(dest.join("host-helper")).unwrap(),
2275 b"host-helper-bytes"
2276 );
2277 assert_eq!(
2278 fs::read(dest.join("host-manifest.json")).unwrap(),
2279 b"{\"manifest\":true}"
2280 );
2281 assert_eq!(
2282 fs::metadata(dest.join("host-main"))
2283 .unwrap()
2284 .permissions()
2285 .mode()
2286 & 0o777,
2287 0o755
2288 );
2289 assert_eq!(
2290 fs::metadata(dest.join("host-helper"))
2291 .unwrap()
2292 .permissions()
2293 .mode()
2294 & 0o777,
2295 0o755
2296 );
2297 assert_eq!(
2298 fs::metadata(dest.join("host-manifest.json"))
2299 .unwrap()
2300 .permissions()
2301 .mode()
2302 & 0o777,
2303 0o644
2304 );
2305 assert!(!Command::new("sh")
2307 .arg(&script_path)
2308 .arg(&dest)
2309 .output()
2310 .unwrap()
2311 .status
2312 .success());
2313
2314 let mut bad_size = manifest.clone();
2316 if let ArtifactForm::Bundle { entries } = &mut bad_size.targets[0].form {
2317 entries[0].artifact.size += 1;
2318 }
2319 let bad_script = render_posix_with_policy(&contract, &bad_size, &spec, &policy).unwrap();
2320 let bad_path = root.join("bad-size.sh");
2321 let bad_dest = root.join("bad-size-dest");
2322 fs::write(&bad_path, bad_script).unwrap();
2323 assert!(!Command::new("sh")
2324 .arg(&bad_path)
2325 .arg(&bad_dest)
2326 .output()
2327 .unwrap()
2328 .status
2329 .success());
2330 assert_eq!(fs::read_dir(&bad_dest).unwrap().count(), 0);
2331
2332 let mut bad_sha = manifest.clone();
2334 if let ArtifactForm::Bundle { entries } = &mut bad_sha.targets[0].form {
2335 entries[1].artifact.sha256 = "ff".repeat(32);
2336 }
2337 let bad_script = render_posix_with_policy(&contract, &bad_sha, &spec, &policy).unwrap();
2338 let bad_path = root.join("bad-sha.sh");
2339 let bad_dest = root.join("bad-sha-dest");
2340 fs::write(&bad_path, bad_script).unwrap();
2341 assert!(!Command::new("sh")
2342 .arg(&bad_path)
2343 .arg(&bad_dest)
2344 .output()
2345 .unwrap()
2346 .status
2347 .success());
2348 assert_eq!(fs::read_dir(&bad_dest).unwrap().count(), 0);
2349
2350 let mut missing_routes = routes.clone();
2352 let missing_name = route_bodies[0].0.clone();
2353 missing_routes.remove(&format!("/releases/{missing_name}"));
2354 let missing_origin = serve_map(missing_routes);
2355 let missing_spec = BootstrapSpec {
2356 origin: missing_origin,
2357 fixture_http: true,
2358 };
2359 let missing_script =
2360 render_posix_with_policy(&contract, &manifest, &missing_spec, &policy).unwrap();
2361 let missing_path = root.join("missing.sh");
2362 let missing_dest = root.join("missing-dest");
2363 fs::write(&missing_path, missing_script).unwrap();
2364 assert!(!Command::new("sh")
2365 .arg(&missing_path)
2366 .arg(&missing_dest)
2367 .output()
2368 .unwrap()
2369 .status
2370 .success());
2371 assert_eq!(fs::read_dir(&missing_dest).unwrap().count(), 0);
2372
2373 for existing in ["host-main", "host-manifest.json"] {
2375 let dest = root.join(format!("existing-{existing}"));
2376 fs::create_dir_all(&dest).unwrap();
2377 fs::write(dest.join(existing), b"sentinel").unwrap();
2378 assert!(!Command::new("sh")
2379 .arg(&script_path)
2380 .arg(&dest)
2381 .output()
2382 .unwrap()
2383 .status
2384 .success());
2385 assert_eq!(fs::read(dest.join(existing)).unwrap(), b"sentinel");
2386 assert_eq!(fs::read_dir(&dest).unwrap().count(), 1);
2388 }
2389
2390 let fake_bin = root.join("fake-bin");
2392 fs::create_dir_all(&fake_bin).unwrap();
2393 fs::write(
2394 fake_bin.join("ln"),
2395 "#!/bin/sh\ncount_file=\"$FAKE_LN_COUNT\"\ncount=$(cat \"$count_file\" 2>/dev/null || echo 0)\ncount=$((count+1))\necho \"$count\" > \"$count_file\"\nif [ \"$count\" -ge 2 ]; then echo 'injected ln failure' >&2; exit 1; fi\nexec /bin/ln \"$@\"\n",
2396 )
2397 .unwrap();
2398 {
2399 use std::os::unix::fs::PermissionsExt;
2400 let mut perms = fs::metadata(fake_bin.join("ln")).unwrap().permissions();
2401 perms.set_mode(0o755);
2402 fs::set_permissions(fake_bin.join("ln"), perms).unwrap();
2403 }
2404 for tool in [
2406 "curl",
2407 "sha256sum",
2408 "wc",
2409 "cut",
2410 "tr",
2411 "mktemp",
2412 "rm",
2413 "mkdir",
2414 "chmod",
2415 "cmp",
2416 "sort",
2417 "printf",
2418 "tar",
2419 "uname",
2420 "sh",
2421 ] {
2422 let src = format!("/usr/bin/{tool}");
2423 if std::path::Path::new(&src).exists() {
2424 let _ = std::os::unix::fs::symlink(&src, fake_bin.join(tool));
2425 }
2426 let sbin = format!("/bin/{tool}");
2427 if !std::path::Path::new(&fake_bin.join(tool)).exists()
2428 && std::path::Path::new(&sbin).exists()
2429 {
2430 let _ = std::os::unix::fs::symlink(&sbin, fake_bin.join(tool));
2431 }
2432 }
2433 let count_file = root.join("ln-count");
2434 fs::write(&count_file, b"0").unwrap();
2435 let rollback_dest = root.join("rollback-dest");
2436 let output = Command::new("sh")
2437 .arg(&script_path)
2438 .arg(&rollback_dest)
2439 .env("PATH", format!("{}:/usr/bin:/bin", fake_bin.display()))
2440 .env("FAKE_LN_COUNT", &count_file)
2441 .output()
2442 .unwrap();
2443 assert!(!output.status.success());
2444 if rollback_dest.exists() {
2446 let count = fs::read_dir(&rollback_dest).map(|d| d.count()).unwrap_or(0);
2447 assert_eq!(count, 0, "rollback must remove partial placement");
2448 }
2449
2450 fs::remove_dir_all(root).unwrap();
2451 }
2452
2453 #[cfg(unix)]
2454 #[test]
2455 fn powershell_emitted_literals_use_powershell_escaping() {
2456 assert_eq!(psq("abc"), "'abc'");
2461 assert_eq!(psq("ab'cd"), "'ab''cd'");
2462 assert_eq!(shq("ab'cd"), "'ab'\\''cd'");
2463
2464 let block = ps_verify_block("$payload", 7, "Ab'01");
2467 assert!(
2468 block.contains("-ne 'ab''01'"),
2469 "digest literal is not PowerShell-quoted: {block}"
2470 );
2471 assert!(
2472 !block.contains("'\\''"),
2473 "POSIX quoting leaked into the PowerShell emitter: {block}"
2474 );
2475 let digest = "ab".repeat(32);
2478 assert!(ps_verify_block("$p", 1, &digest).contains(&format!("-ne '{digest}'")));
2479 }
2480
2481 #[test]
2482 fn powershell_archive_inventory_comparison_is_case_sensitive() {
2483 let (contract, manifest, policy, archive_bytes, _) = host_archive_case();
2487 let archive_name = match &manifest.targets[0].form {
2488 ArtifactForm::Archive { artifact, .. } => artifact.name.clone(),
2489 _ => panic!("archive expected"),
2490 };
2491 let mut routes = HashMap::new();
2492 routes.insert(
2493 format!("/releases/{archive_name}"),
2494 (archive_bytes, "200 OK".into()),
2495 );
2496 let spec = BootstrapSpec {
2497 origin: serve_map(routes),
2498 fixture_http: true,
2499 };
2500 let script = render_powershell_with_policy(&contract, &manifest, &spec, &policy).unwrap();
2501 assert_eq!(script.matches("-cnotcontains").count(), 2, "{script}");
2502 assert!(
2503 !script.contains("$actual -notcontains") && !script.contains("$expected -notcontains"),
2504 "case-insensitive member inventory comparison emitted"
2505 );
2506 assert!(script.contains("$member = Join-Path $extractDir 'hostbin'"));
2510 assert!(script.contains("[IO.File]::Move($member0, $dest0)"));
2511 assert!(!script.contains("$file0"));
2512 }
2513
2514 #[test]
2515 fn powershell_direct_path_destination_is_the_exact_install_name() {
2516 let c = DistributionContract::parse_toml_str(include_str!(
2521 "../../eggpack-contract/tests/fixtures/simple-direct.toml"
2522 ))
2523 .unwrap();
2524 let direct = |target: &str| eggpack_manifest::TargetRecord {
2525 target: target.into(),
2526 form: ArtifactForm::Direct {
2527 artifact: eggpack_manifest::ArtifactRecord {
2528 name: format!("eggsact-1.2.6-{target}"),
2529 size: 3,
2530 sha256: "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
2531 .into(),
2532 },
2533 install: "eggsact".into(),
2534 },
2535 };
2536 let m = ReleaseManifest {
2537 schema_version: 1,
2538 product_id: "eggsact".into(),
2539 release_id: "1.2.6".into(),
2540 source_revision: "a".repeat(40),
2541 targets: vec![
2542 direct("x86_64-unknown-linux-gnu"),
2543 direct("aarch64-apple-darwin"),
2544 ],
2545 evidence_references: vec![],
2546 };
2547 let spec = BootstrapSpec {
2548 origin: "https://example.invalid/releases".into(),
2549 fixture_http: false,
2550 };
2551 let script = render_powershell(&c, &m, &spec).unwrap();
2552 assert!(script.contains("$install='eggsact'"), "{script}");
2555 assert!(
2556 script.contains("$file = Join-Path $dest $install"),
2557 "{script}"
2558 );
2559 assert!(
2560 script.contains("[IO.File]::Move($payload, $file)"),
2561 "{script}"
2562 );
2563 assert!(
2566 script.contains("-ne $size") && script.contains("-ne $sha"),
2567 "{script}"
2568 );
2569 assert!(
2570 !script.contains("Join-Path $dest '$"),
2571 "digest or artifact name leaked into the install path"
2572 );
2573 assert!(!script.contains("member_set_sha256"), "{script}");
2574 }
2575
2576 #[cfg(unix)]
2577 #[test]
2578 #[allow(clippy::type_complexity)]
2579 fn m002_archive_posix_runtime_matrix() {
2580 use std::{fs, os::unix::fs::PermissionsExt, process::Command};
2581 let (contract, manifest, policy, archive_bytes, member_bodies) = host_archive_case();
2583 let member_main = member_bodies[0].1.clone();
2584 let member_helper = member_bodies[1].1.clone();
2585 let archive_name = match &manifest.targets[0].form {
2586 ArtifactForm::Archive { artifact, .. } => artifact.name.clone(),
2587 _ => panic!("archive expected"),
2588 };
2589 let mut routes = HashMap::new();
2590 routes.insert(
2591 format!("/releases/{archive_name}"),
2592 (archive_bytes.clone(), "200 OK".into()),
2593 );
2594 let origin = serve_map(routes.clone());
2595 let spec = BootstrapSpec {
2596 origin,
2597 fixture_http: true,
2598 };
2599 let script = render_posix_with_policy(&contract, &manifest, &spec, &policy).unwrap();
2600 assert_eq!(
2601 script,
2602 render_posix_with_policy(&contract, &manifest, &spec, &policy).unwrap()
2603 );
2604 assert!(Command::new("sh")
2605 .arg("-n")
2606 .arg("-c")
2607 .arg(&script)
2608 .status()
2609 .unwrap()
2610 .success());
2611 assert!(!script.contains("sudo"));
2612 assert!(!script.contains("unzip"));
2613
2614 let root =
2615 std::env::temp_dir().join(format!("eggpack-m002-archive-{}", std::process::id()));
2616 let _ = fs::remove_dir_all(&root);
2617 fs::create_dir_all(&root).unwrap();
2618 let script_path = root.join("install.sh");
2619 fs::write(&script_path, &script).unwrap();
2620
2621 let dest = root.join("dest-ok");
2623 assert!(Command::new("sh")
2624 .arg(&script_path)
2625 .arg(&dest)
2626 .status()
2627 .unwrap()
2628 .success());
2629 assert_eq!(fs::read(dest.join("hostbin")).unwrap(), member_main);
2630 assert_eq!(fs::read(dest.join("host-helper")).unwrap(), member_helper);
2631 assert!(!dest.join("bin").exists());
2632 assert_eq!(
2633 fs::metadata(dest.join("hostbin"))
2634 .unwrap()
2635 .permissions()
2636 .mode()
2637 & 0o777,
2638 0o755
2639 );
2640 assert_eq!(
2641 fs::metadata(dest.join("host-helper"))
2642 .unwrap()
2643 .permissions()
2644 .mode()
2645 & 0o777,
2646 0o644
2647 );
2648
2649 for mutate_size in [true, false] {
2651 let mut bad = manifest.clone();
2652 if let ArtifactForm::Archive { artifact, .. } = &mut bad.targets[0].form {
2653 if mutate_size {
2654 artifact.size += 1;
2655 } else {
2656 artifact.sha256 = "ff".repeat(32);
2657 }
2658 }
2659 let bad_script = render_posix_with_policy(&contract, &bad, &spec, &policy).unwrap();
2660 let bad_path = root.join(format!("bad-archive-{mutate_size}.sh"));
2661 let bad_dest = root.join(format!("bad-archive-{mutate_size}-dest"));
2662 fs::write(&bad_path, bad_script).unwrap();
2663 assert!(!Command::new("sh")
2664 .arg(&bad_path)
2665 .arg(&bad_dest)
2666 .output()
2667 .unwrap()
2668 .status
2669 .success());
2670 assert_eq!(fs::read_dir(&bad_dest).unwrap().count(), 0);
2671 }
2672
2673 for mutate_size in [true, false] {
2675 let mut bad = manifest.clone();
2676 if let ArtifactForm::Archive { members, .. } = &mut bad.targets[0].form {
2677 if mutate_size {
2678 members[0].bytes.size += 1;
2679 } else {
2680 members[1].bytes.sha256 = "11".repeat(32);
2681 }
2682 }
2683 let bad_script = render_posix_with_policy(&contract, &bad, &spec, &policy).unwrap();
2684 let bad_path = root.join(format!("bad-member-{mutate_size}.sh"));
2685 let bad_dest = root.join(format!("bad-member-{mutate_size}-dest"));
2686 fs::write(&bad_path, bad_script).unwrap();
2687 assert!(!Command::new("sh")
2688 .arg(&bad_path)
2689 .arg(&bad_dest)
2690 .output()
2691 .unwrap()
2692 .status
2693 .success());
2694 if bad_dest.exists() {
2696 let installed = fs::read_dir(&bad_dest)
2697 .unwrap()
2698 .filter(|e| {
2699 let name = e
2700 .as_ref()
2701 .unwrap()
2702 .file_name()
2703 .to_string_lossy()
2704 .into_owned();
2705 !name.starts_with(".eggpack.")
2706 })
2707 .count();
2708 assert_eq!(installed, 0);
2709 }
2710 }
2711
2712 let tampered_cases: Vec<(&str, Vec<u8>, &str)> = vec![
2718 (
2719 "missing",
2720 build_deterministic_tar_gz(&[("hostbin", member_main.as_slice())]),
2721 "archive member inventory mismatch",
2722 ),
2723 (
2724 "extra",
2725 build_deterministic_tar_gz(&[
2726 ("hostbin", member_main.as_slice()),
2727 ("bin/host-helper", member_helper.as_slice()),
2728 ("extra-file", b"extra" as &[u8]),
2729 ]),
2730 "archive member inventory mismatch",
2731 ),
2732 (
2733 "traversal",
2734 build_raw_tar_gz(&[
2735 RawTarEntry {
2736 name: "hostbin",
2737 kind: b'0',
2738 linkname: "",
2739 data: member_main.as_slice(),
2740 },
2741 RawTarEntry {
2742 name: "../evil",
2743 kind: b'0',
2744 linkname: "",
2745 data: member_helper.as_slice(),
2746 },
2747 ]),
2748 "unsafe archive member",
2749 ),
2750 (
2751 "absolute",
2752 build_raw_tar_gz(&[
2753 RawTarEntry {
2754 name: "hostbin",
2755 kind: b'0',
2756 linkname: "",
2757 data: member_main.as_slice(),
2758 },
2759 RawTarEntry {
2760 name: "/abs",
2761 kind: b'0',
2762 linkname: "",
2763 data: member_helper.as_slice(),
2764 },
2765 ]),
2766 "unsafe archive member",
2767 ),
2768 (
2769 "backslash",
2770 build_raw_tar_gz(&[
2771 RawTarEntry {
2772 name: "hostbin",
2773 kind: b'0',
2774 linkname: "",
2775 data: member_main.as_slice(),
2776 },
2777 RawTarEntry {
2778 name: "bin\\evil",
2779 kind: b'0',
2780 linkname: "",
2781 data: member_helper.as_slice(),
2782 },
2783 ]),
2784 "unsafe archive member",
2785 ),
2786 (
2787 "symlink-inner",
2788 build_raw_tar_gz(&[
2789 RawTarEntry {
2790 name: "hostbin",
2791 kind: b'0',
2792 linkname: "",
2793 data: member_main.as_slice(),
2794 },
2795 RawTarEntry {
2796 name: "bin/host-helper",
2797 kind: b'2',
2798 linkname: "hostbin",
2799 data: &[],
2800 },
2801 ]),
2802 "symlink member rejected",
2803 ),
2804 (
2805 "directory",
2806 build_raw_tar_gz(&[
2807 RawTarEntry {
2808 name: "hostbin",
2809 kind: b'0',
2810 linkname: "",
2811 data: member_main.as_slice(),
2812 },
2813 RawTarEntry {
2814 name: "bin/host-helper",
2815 kind: b'5',
2816 linkname: "",
2817 data: &[],
2818 },
2819 ]),
2820 "member is not a regular file",
2821 ),
2822 ];
2823 for (label, bytes, expected_guard) in &tampered_cases {
2824 let tampered_manifest = manifest_with_archive_bytes(&manifest, bytes);
2825 let mut tampered_routes = HashMap::new();
2826 tampered_routes.insert(
2827 format!("/releases/{archive_name}"),
2828 (bytes.clone(), "200 OK".into()),
2829 );
2830 let tampered_origin = serve_map(tampered_routes);
2831 let tampered_spec = BootstrapSpec {
2832 origin: tampered_origin,
2833 fixture_http: true,
2834 };
2835 let tampered_script =
2836 render_posix_with_policy(&contract, &tampered_manifest, &tampered_spec, &policy)
2837 .unwrap();
2838 let tampered_path = root.join(format!("tampered-{label}.sh"));
2839 let tampered_dest = root.join(format!("tampered-{label}-dest"));
2840 fs::write(&tampered_path, &tampered_script).unwrap();
2841 let output = Command::new("sh")
2842 .arg(&tampered_path)
2843 .arg(&tampered_dest)
2844 .output()
2845 .unwrap();
2846 let stderr = String::from_utf8_lossy(&output.stderr);
2847 assert!(
2848 !output.status.success(),
2849 "tampered archive {label} must fail"
2850 );
2851 assert!(
2854 !stderr.contains("size mismatch") && !stderr.contains("SHA-256 mismatch"),
2855 "tampered archive {label} must pass outer digest, got: {stderr}"
2856 );
2857 assert!(
2858 stderr.contains(expected_guard),
2859 "tampered archive {label} must reach '{expected_guard}', got: {stderr}"
2860 );
2861 if tampered_dest.exists() {
2863 let installed = fs::read_dir(&tampered_dest)
2864 .unwrap()
2865 .filter(|e| {
2866 let name = e
2867 .as_ref()
2868 .unwrap()
2869 .file_name()
2870 .to_string_lossy()
2871 .into_owned();
2872 !name.starts_with(".eggpack.")
2873 })
2874 .count();
2875 assert_eq!(
2876 installed, 0,
2877 "tampered archive {label} must install nothing"
2878 );
2879 }
2880 let preserved = root.join(format!("tampered-{label}-preserved"));
2882 fs::create_dir_all(&preserved).unwrap();
2883 fs::write(preserved.join("hostbin"), b"sentinel").unwrap();
2884 assert!(!Command::new("sh")
2885 .arg(&tampered_path)
2886 .arg(&preserved)
2887 .output()
2888 .unwrap()
2889 .status
2890 .success());
2891 assert_eq!(fs::read(preserved.join("hostbin")).unwrap(), b"sentinel");
2892 }
2893
2894 {
2896 let file = Vec::new();
2897 let enc = flate2::GzBuilder::new()
2898 .mtime(0)
2899 .write(file, flate2::Compression::default());
2900 let mut archive = tar::Builder::new(enc);
2901 archive.mode(tar::HeaderMode::Deterministic);
2902 let mut header = tar::Header::new_gnu();
2903 header.set_entry_type(tar::EntryType::Regular);
2904 header.set_path("hostbin").unwrap();
2905 header.set_size(member_main.len() as u64);
2906 header.set_mode(0o755);
2907 header.set_uid(0);
2908 header.set_gid(0);
2909 header.set_mtime(0);
2910 header.set_cksum();
2911 archive.append(&header, member_main.as_slice()).unwrap();
2912 let mut link_header = tar::Header::new_gnu();
2913 link_header.set_entry_type(tar::EntryType::Symlink);
2914 link_header.set_path("bin/host-helper").unwrap();
2915 link_header.set_link_name("hostbin").unwrap();
2916 link_header.set_mode(0o777);
2917 link_header.set_uid(0);
2918 link_header.set_gid(0);
2919 link_header.set_mtime(0);
2920 link_header.set_cksum();
2921 archive.append(&link_header, &[][..]).unwrap();
2922 let enc = archive.into_inner().unwrap();
2923 let symlink_bytes = enc.finish().unwrap();
2924 let symlink_manifest = manifest_with_archive_bytes(&manifest, &symlink_bytes);
2925 let mut symlink_routes = HashMap::new();
2926 symlink_routes.insert(
2927 format!("/releases/{archive_name}"),
2928 (symlink_bytes, "200 OK".into()),
2929 );
2930 let symlink_origin = serve_map(symlink_routes);
2931 let symlink_spec = BootstrapSpec {
2932 origin: symlink_origin,
2933 fixture_http: true,
2934 };
2935 let symlink_script =
2936 render_posix_with_policy(&contract, &symlink_manifest, &symlink_spec, &policy)
2937 .unwrap();
2938 let symlink_path = root.join("symlink.sh");
2939 let symlink_dest = root.join("symlink-dest");
2940 fs::write(&symlink_path, symlink_script).unwrap();
2941 let output = Command::new("sh")
2942 .arg(&symlink_path)
2943 .arg(&symlink_dest)
2944 .output()
2945 .unwrap();
2946 let stderr = String::from_utf8_lossy(&output.stderr);
2947 assert!(!output.status.success());
2948 assert!(
2949 !stderr.contains("size mismatch") && !stderr.contains("SHA-256 mismatch"),
2950 "symlink case must pass outer digest, got: {stderr}"
2951 );
2952 assert!(
2953 stderr.contains("symlink member rejected"),
2954 "symlink case must reach type guard, got: {stderr}"
2955 );
2956 }
2957
2958 {
2961 let fake_bin = root.join("archive-fake-bin");
2962 fs::create_dir_all(&fake_bin).unwrap();
2963 fs::write(
2964 fake_bin.join("ln"),
2965 "#!/bin/sh\ncount_file=\"$FAKE_LN_COUNT\"\ncount=$(cat \"$count_file\" 2>/dev/null || echo 0)\ncount=$((count+1))\necho \"$count\" > \"$count_file\"\nif [ \"$count\" -ge 2 ]; then echo 'injected ln failure' >&2; exit 1; fi\nexec /bin/ln \"$@\"\n",
2966 )
2967 .unwrap();
2968 {
2969 use std::os::unix::fs::PermissionsExt;
2970 let mut perms = fs::metadata(fake_bin.join("ln")).unwrap().permissions();
2971 perms.set_mode(0o755);
2972 fs::set_permissions(fake_bin.join("ln"), perms).unwrap();
2973 }
2974 for tool in [
2975 "curl",
2976 "sha256sum",
2977 "wc",
2978 "cut",
2979 "tr",
2980 "mktemp",
2981 "rm",
2982 "mkdir",
2983 "chmod",
2984 "cmp",
2985 "sort",
2986 "printf",
2987 "tar",
2988 "uname",
2989 "sh",
2990 ] {
2991 for prefix in ["/usr/bin", "/bin"] {
2992 let src = format!("{prefix}/{tool}");
2993 if std::path::Path::new(&src).exists() && !fake_bin.join(tool).exists() {
2994 let _ = std::os::unix::fs::symlink(&src, fake_bin.join(tool));
2995 }
2996 }
2997 }
2998 let count_file = root.join("archive-ln-count");
2999 fs::write(&count_file, b"0").unwrap();
3000 let rollback_dest = root.join("archive-rollback-dest");
3004 let output = Command::new("sh")
3005 .arg(&script_path)
3006 .arg(&rollback_dest)
3007 .env("PATH", format!("{}:/usr/bin:/bin", fake_bin.display()))
3008 .env("FAKE_LN_COUNT", &count_file)
3009 .output()
3010 .unwrap();
3011 assert!(!output.status.success());
3012 if rollback_dest.exists() {
3013 let count = fs::read_dir(&rollback_dest)
3014 .map(|d| {
3015 d.filter(|e| {
3016 !e.as_ref()
3017 .unwrap()
3018 .file_name()
3019 .to_string_lossy()
3020 .starts_with(".eggpack.")
3021 })
3022 .count()
3023 })
3024 .unwrap_or(0);
3025 assert_eq!(count, 0, "archive rollback must remove partial placement");
3026 }
3027 }
3028
3029 {
3031 let empty_bin = root.join("empty-bin");
3032 fs::create_dir_all(&empty_bin).unwrap();
3033 for tool in [
3034 "curl",
3035 "sha256sum",
3036 "wc",
3037 "cut",
3038 "tr",
3039 "mktemp",
3040 "rm",
3041 "mkdir",
3042 "chmod",
3043 "cmp",
3044 "sort",
3045 "printf",
3046 "uname",
3047 ] {
3048 for prefix in ["/usr/bin", "/bin"] {
3049 let src = format!("{prefix}/{tool}");
3050 if std::path::Path::new(&src).exists() && !empty_bin.join(tool).exists() {
3051 let _ = std::os::unix::fs::symlink(&src, empty_bin.join(tool));
3052 }
3053 }
3054 }
3055 assert!(!empty_bin.join("tar").exists());
3057 let no_tar_dest = root.join("no-tar-dest");
3058 let output = Command::new("/bin/sh")
3059 .arg(&script_path)
3060 .arg(&no_tar_dest)
3061 .env("PATH", &empty_bin)
3062 .output()
3063 .unwrap();
3064 assert!(!output.status.success());
3065 let stderr = String::from_utf8_lossy(&output.stderr);
3066 assert!(stderr.contains("tar is required"));
3067 if no_tar_dest.exists() {
3068 let installed = fs::read_dir(&no_tar_dest)
3069 .unwrap()
3070 .filter(|e| {
3071 let name = e
3072 .as_ref()
3073 .unwrap()
3074 .file_name()
3075 .to_string_lossy()
3076 .into_owned();
3077 !name.starts_with(".eggpack.")
3078 })
3079 .count();
3080 assert_eq!(installed, 0);
3081 }
3082 }
3083
3084 {
3086 let dest = root.join("preexisting");
3087 fs::create_dir_all(&dest).unwrap();
3088 fs::write(dest.join("hostbin"), b"sentinel").unwrap();
3089 assert!(!Command::new("sh")
3090 .arg(&script_path)
3091 .arg(&dest)
3092 .output()
3093 .unwrap()
3094 .status
3095 .success());
3096 assert_eq!(fs::read(dest.join("hostbin")).unwrap(), b"sentinel");
3097 }
3098
3099 fs::remove_dir_all(root).unwrap();
3100 }
3101
3102 #[test]
3103 fn m002_powershell_static_and_runtime() {
3104 use std::{fs, process::Command};
3105 let (contract, manifest, policy, route_bodies) = host_bundle_case();
3106 let mut routes = HashMap::new();
3107 for (name, body) in &route_bodies {
3108 routes.insert(format!("/releases/{name}"), (body.clone(), "200 OK".into()));
3109 }
3110 let origin = serve_map(routes);
3111 let spec = BootstrapSpec {
3112 origin,
3113 fixture_http: true,
3114 };
3115 let ps_bundle =
3116 render_powershell_with_policy(&contract, &manifest, &spec, &policy).unwrap();
3117 assert_eq!(
3118 ps_bundle,
3119 render_powershell_with_policy(&contract, &manifest, &spec, &policy).unwrap()
3120 );
3121 for forbidden in [
3122 "sudo",
3123 "Start-Process",
3124 "RunAs",
3125 "latest",
3126 "-MaximumRedirection 1",
3127 ] {
3128 assert!(!ps_bundle.contains(forbidden));
3129 }
3130 assert!(ps_bundle.contains("-MaximumRedirection 0"));
3131 assert!(!ps_bundle.contains("curl"));
3132
3133 let shell = if cfg!(windows) {
3135 "powershell.exe"
3136 } else {
3137 "pwsh"
3138 };
3139 let parser_available = Command::new(shell).arg("-Version").output().is_ok();
3140 if parser_available {
3141 let ps_path =
3142 std::env::temp_dir().join(format!("eggpack-m002-{}.ps1", std::process::id()));
3143 fs::write(&ps_path, &ps_bundle).unwrap();
3144 let parser = format!("$tokens=$null;$errors=$null;[System.Management.Automation.Language.Parser]::ParseFile({},[ref]$tokens,[ref]$errors)|Out-Null;if($errors.Count -gt 0){{exit 1}}", psq(&ps_path.to_string_lossy()));
3145 assert!(Command::new(shell)
3146 .args(["-NoProfile", "-NonInteractive", "-Command", &parser])
3147 .status()
3148 .unwrap()
3149 .success());
3150 if Command::new("pwsh").arg("-Version").output().is_ok() {
3154 let root =
3155 std::env::temp_dir().join(format!("eggpack-m002-ps-{}", std::process::id()));
3156 let _ = fs::remove_dir_all(&root);
3157 fs::create_dir_all(&root).unwrap();
3158 let script_path = root.join("install.ps1");
3159 fs::write(&script_path, &ps_bundle).unwrap();
3160 let dest = root.join("dest-ok");
3161 let result = Command::new("pwsh")
3162 .arg("-NoProfile")
3163 .arg("-File")
3164 .arg(&script_path)
3165 .arg(&dest)
3166 .output()
3167 .unwrap();
3168 assert!(
3169 result.status.success(),
3170 "pwsh bundle install failed: {}",
3171 String::from_utf8_lossy(&result.stderr)
3172 );
3173 assert_eq!(
3174 fs::read(dest.join("host-main")).unwrap(),
3175 b"host-main-bytes"
3176 );
3177 let repeat = Command::new("pwsh")
3179 .arg("-NoProfile")
3180 .arg("-File")
3181 .arg(&script_path)
3182 .arg(&dest)
3183 .output()
3184 .unwrap();
3185 assert!(!repeat.status.success());
3186 let _ = fs::remove_dir_all(root);
3187 }
3188 let _ = fs::remove_file(ps_path);
3189 }
3190
3191 let (single_contract, archive_manifest, archive_policy, _, _) = host_archive_case();
3193 let archive_spec = BootstrapSpec {
3194 origin: "https://example.invalid/releases".into(),
3195 fixture_http: false,
3196 };
3197 let ps_archive = render_powershell_with_policy(
3198 &single_contract,
3199 &archive_manifest,
3200 &archive_spec,
3201 &archive_policy,
3202 )
3203 .unwrap();
3204 assert!(ps_archive.contains("tar.exe"));
3205 assert!(!ps_archive.contains("sudo"));
3206 assert!(ps_archive.contains("foreach ($p in $created)"));
3208 if parser_available {
3209 let ps_path =
3210 std::env::temp_dir().join(format!("eggpack-m002-arch-{}.ps1", std::process::id()));
3211 fs::write(&ps_path, &ps_archive).unwrap();
3212 let parser = format!("$tokens=$null;$errors=$null;[System.Management.Automation.Language.Parser]::ParseFile({},[ref]$tokens,[ref]$errors)|Out-Null;if($errors.Count -gt 0){{exit 1}}", psq(&ps_path.to_string_lossy()));
3213 assert!(Command::new(shell)
3214 .args(["-NoProfile", "-NonInteractive", "-Command", &parser])
3215 .status()
3216 .unwrap()
3217 .success());
3218 let _ = fs::remove_file(ps_path);
3219 }
3220 }
3221
3222 #[test]
3223 fn m002a_powershell_archive_runtime() {
3224 use std::{fs, process::Command};
3225 if cfg!(windows) {
3229 assert!(pwsh_available(), "pwsh 7 is required on the Windows lane");
3230 assert!(
3231 tar_exe_available(),
3232 "tar.exe is required on the Windows lane"
3233 );
3234 } else if !pwsh_available() || !tar_exe_available() {
3235 eprintln!("skip: pwsh + tar.exe unavailable on non-Windows lane");
3236 return;
3237 }
3238 let (contract, manifest, policy, archive_bytes, member_bodies) = host_archive_case();
3239 let member_main = member_bodies[0].1.clone();
3240 let member_helper = member_bodies[1].1.clone();
3241 let archive_name = match &manifest.targets[0].form {
3242 ArtifactForm::Archive { artifact, .. } => artifact.name.clone(),
3243 _ => panic!("archive expected"),
3244 };
3245 let mut routes = HashMap::new();
3246 routes.insert(
3247 format!("/releases/{archive_name}"),
3248 (archive_bytes.clone(), "200 OK".into()),
3249 );
3250 let origin = serve_map(routes);
3251 let spec = BootstrapSpec {
3252 origin,
3253 fixture_http: true,
3254 };
3255 let script = render_powershell_with_policy(&contract, &manifest, &spec, &policy).unwrap();
3256 assert_eq!(
3257 script,
3258 render_powershell_with_policy(&contract, &manifest, &spec, &policy).unwrap()
3259 );
3260 assert!(script.contains("tar.exe"));
3261 assert!(!script.contains("sudo"));
3262 assert!(!script.contains("Start-Process"));
3263 assert!(script.contains("-MaximumRedirection 0"));
3264
3265 let root =
3266 std::env::temp_dir().join(format!("eggpack-m002a-ps-arch-{}", std::process::id()));
3267 let _ = fs::remove_dir_all(&root);
3268 fs::create_dir_all(&root).unwrap();
3269 let script_path = root.join("install.ps1");
3270 fs::write(&script_path, &script).unwrap();
3271
3272 fn pwsh_run(script: &std::path::Path, dest: &std::path::Path) -> std::process::Output {
3273 Command::new("pwsh")
3274 .arg("-NoProfile")
3275 .arg("-NonInteractive")
3276 .arg("-File")
3277 .arg(script)
3278 .arg(dest)
3279 .output()
3280 .unwrap()
3281 }
3282 fn combined(output: &std::process::Output) -> String {
3283 format!(
3284 "{}{}",
3285 String::from_utf8_lossy(&output.stdout),
3286 String::from_utf8_lossy(&output.stderr)
3287 )
3288 }
3289 fn installed_files(dest: &std::path::Path) -> usize {
3290 if !dest.exists() {
3291 return 0;
3292 }
3293 fs::read_dir(dest)
3294 .unwrap()
3295 .filter(|e| {
3296 let name = e
3297 .as_ref()
3298 .unwrap()
3299 .file_name()
3300 .to_string_lossy()
3301 .into_owned();
3302 !name.starts_with(".eggpack-")
3303 })
3304 .count()
3305 }
3306
3307 let dest = root.join("dest-ok");
3309 let ok = pwsh_run(&script_path, &dest);
3310 assert!(
3311 ok.status.success(),
3312 "pwsh archive install failed: {}",
3313 combined(&ok)
3314 );
3315 assert_eq!(fs::read(dest.join("hostbin")).unwrap(), member_main);
3316 assert_eq!(fs::read(dest.join("host-helper")).unwrap(), member_helper);
3317 assert!(!dest.join("bin").exists());
3318 let repeat = pwsh_run(&script_path, &dest);
3320 assert!(!repeat.status.success());
3321 assert_eq!(fs::read(dest.join("hostbin")).unwrap(), member_main);
3322 assert_eq!(installed_files(&dest), 2);
3323
3324 for (label, mut bad) in [("size", manifest.clone()), ("sha", manifest.clone())] {
3326 if let ArtifactForm::Archive { artifact, .. } = &mut bad.targets[0].form {
3327 if label == "size" {
3328 artifact.size += 1;
3329 } else {
3330 artifact.sha256 = "ff".repeat(32);
3331 }
3332 }
3333 let bad_script =
3334 render_powershell_with_policy(&contract, &bad, &spec, &policy).unwrap();
3335 let bad_path = root.join(format!("bad-archive-{label}.ps1"));
3336 let bad_dest = root.join(format!("bad-archive-{label}-dest"));
3337 fs::write(&bad_path, &bad_script).unwrap();
3338 let out = pwsh_run(&bad_path, &bad_dest);
3339 assert!(!out.status.success(), "wrong archive {label} must fail");
3340 assert_eq!(installed_files(&bad_dest), 0);
3341 }
3342
3343 let inner_cases: Vec<(&str, Vec<u8>, &str)> = vec![
3345 (
3346 "missing",
3347 build_deterministic_tar_gz(&[("hostbin", member_main.as_slice())]),
3348 "archive member inventory mismatch",
3349 ),
3350 (
3351 "extra",
3352 build_deterministic_tar_gz(&[
3353 ("hostbin", member_main.as_slice()),
3354 ("bin/host-helper", member_helper.as_slice()),
3355 ("extra-file", b"extra" as &[u8]),
3356 ]),
3357 "archive member inventory mismatch",
3358 ),
3359 (
3360 "case-mismatch",
3365 build_deterministic_tar_gz(&[
3366 ("HOSTBIN", member_main.as_slice()),
3367 ("bin/host-helper", member_helper.as_slice()),
3368 ]),
3369 "archive member inventory mismatch",
3370 ),
3371 (
3372 "traversal",
3373 build_raw_tar_gz(&[
3374 RawTarEntry {
3375 name: "hostbin",
3376 kind: b'0',
3377 linkname: "",
3378 data: member_main.as_slice(),
3379 },
3380 RawTarEntry {
3381 name: "../evil",
3382 kind: b'0',
3383 linkname: "",
3384 data: member_helper.as_slice(),
3385 },
3386 ]),
3387 "unsafe archive member",
3388 ),
3389 (
3390 "absolute",
3391 build_raw_tar_gz(&[
3392 RawTarEntry {
3393 name: "hostbin",
3394 kind: b'0',
3395 linkname: "",
3396 data: member_main.as_slice(),
3397 },
3398 RawTarEntry {
3399 name: "/abs",
3400 kind: b'0',
3401 linkname: "",
3402 data: member_helper.as_slice(),
3403 },
3404 ]),
3405 "unsafe archive member",
3406 ),
3407 (
3408 "backslash",
3409 build_raw_tar_gz(&[
3410 RawTarEntry {
3411 name: "hostbin",
3412 kind: b'0',
3413 linkname: "",
3414 data: member_main.as_slice(),
3415 },
3416 RawTarEntry {
3417 name: "bin\\evil",
3418 kind: b'0',
3419 linkname: "",
3420 data: member_helper.as_slice(),
3421 },
3422 ]),
3423 "unsafe archive member",
3424 ),
3425 (
3426 "symlink",
3427 build_raw_tar_gz(&[
3428 RawTarEntry {
3429 name: "hostbin",
3430 kind: b'0',
3431 linkname: "",
3432 data: member_main.as_slice(),
3433 },
3434 RawTarEntry {
3435 name: "bin/host-helper",
3436 kind: b'2',
3437 linkname: "hostbin",
3438 data: &[],
3439 },
3440 ]),
3441 "symlink member rejected",
3442 ),
3443 (
3444 "directory",
3445 build_raw_tar_gz(&[
3446 RawTarEntry {
3447 name: "hostbin",
3448 kind: b'0',
3449 linkname: "",
3450 data: member_main.as_slice(),
3451 },
3452 RawTarEntry {
3453 name: "bin/host-helper",
3454 kind: b'5',
3455 linkname: "",
3456 data: &[],
3457 },
3458 ]),
3459 "member is not a regular file",
3460 ),
3461 ];
3462 for (label, bytes, expected_guard) in &inner_cases {
3463 let tampered_manifest = manifest_with_archive_bytes(&manifest, bytes);
3464 let mut tampered_routes = HashMap::new();
3465 tampered_routes.insert(
3466 format!("/releases/{archive_name}"),
3467 (bytes.clone(), "200 OK".into()),
3468 );
3469 let tampered_origin = serve_map(tampered_routes);
3470 let tampered_spec = BootstrapSpec {
3471 origin: tampered_origin,
3472 fixture_http: true,
3473 };
3474 let tampered_script = render_powershell_with_policy(
3475 &contract,
3476 &tampered_manifest,
3477 &tampered_spec,
3478 &policy,
3479 )
3480 .unwrap();
3481 let tampered_path = root.join(format!("tampered-{label}.ps1"));
3482 let tampered_dest = root.join(format!("tampered-{label}-dest"));
3483 fs::write(&tampered_path, &tampered_script).unwrap();
3484 let out = pwsh_run(&tampered_path, &tampered_dest);
3485 let text = combined(&out);
3486 assert!(!out.status.success(), "tampered archive {label} must fail");
3487 assert!(
3488 !text.contains("size mismatch") || text.contains(expected_guard),
3489 "tampered archive {label} must pass outer digest, got: {text}"
3490 );
3491 assert!(
3492 text.contains(expected_guard),
3493 "tampered archive {label} must reach '{expected_guard}', got: {text}"
3494 );
3495 assert_eq!(
3496 installed_files(&tampered_dest),
3497 0,
3498 "tampered archive {label} must install nothing"
3499 );
3500 }
3501
3502 for (label, mut bad) in [
3504 ("member-size", manifest.clone()),
3505 ("member-sha", manifest.clone()),
3506 ] {
3507 if let ArtifactForm::Archive { members, .. } = &mut bad.targets[0].form {
3508 if label == "member-size" {
3509 members[0].bytes.size += 1;
3510 } else {
3511 members[1].bytes.sha256 = "11".repeat(32);
3512 }
3513 }
3514 let bad_script =
3515 render_powershell_with_policy(&contract, &bad, &spec, &policy).unwrap();
3516 let bad_path = root.join(format!("{label}.ps1"));
3517 let bad_dest = root.join(format!("{label}-dest"));
3518 fs::write(&bad_path, &bad_script).unwrap();
3519 let out = pwsh_run(&bad_path, &bad_dest);
3520 assert!(!out.status.success(), "{label} must fail");
3521 assert_eq!(installed_files(&bad_dest), 0);
3522 }
3523
3524 {
3526 let no_tar_dest = root.join("no-tar-dest");
3527 let probe = Command::new("pwsh")
3528 .args([
3529 "-NoProfile",
3530 "-NonInteractive",
3531 "-Command",
3532 &format!(
3533 "$env:PATH=''; & {} {}",
3534 script_path.to_string_lossy(),
3535 no_tar_dest.to_string_lossy()
3536 ),
3537 ])
3538 .output()
3539 .unwrap();
3540 let text = combined(&probe);
3544 if text.contains("tar.exe is required") {
3545 assert!(!probe.status.success());
3546 assert_eq!(installed_files(&no_tar_dest), 0);
3547 } else {
3548 assert!(script.contains("tar.exe is required"));
3549 }
3550 }
3551
3552 {
3559 let dest = root.join("rollback-dest");
3560 fs::create_dir_all(&dest).unwrap();
3561 fs::write(dest.join("host-helper"), b"sentinel").unwrap();
3562 let out = pwsh_run(&script_path, &dest);
3563 assert!(
3564 !out.status.success(),
3565 "archive placement conflict must fail"
3566 );
3567 assert_eq!(fs::read(dest.join("host-helper")).unwrap(), b"sentinel");
3568 assert!(
3569 !dest.join("hostbin").exists(),
3570 "first archive file must be rolled back"
3571 );
3572 }
3573
3574 {
3576 let dest = root.join("preexisting");
3577 fs::create_dir_all(&dest).unwrap();
3578 fs::write(dest.join("hostbin"), b"sentinel").unwrap();
3579 let out = pwsh_run(&script_path, &dest);
3580 assert!(!out.status.success());
3581 assert_eq!(fs::read(dest.join("hostbin")).unwrap(), b"sentinel");
3582 assert_eq!(installed_files(&dest), 1);
3583 }
3584
3585 fs::remove_dir_all(root).unwrap();
3586 }
3587}