Skip to main content

proa_cli/rsjs/
final_compile.rs

1// Copyright Proa Labs, Inc.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Plan-sensitive final Cargo compilation and execution for RSJS roots.
5//!
6//! The final compiler is intentionally separate from descriptor compilation.
7//! A content-addressed plan is validated before Cargo starts, its [`PlanId`] is
8//! supplied to the final rustc wrapper. Artifacts share a wrapper-policy target
9//! namespace; generated RSJS witnesses expose the exact plan/map fingerprints
10//! to Cargo so only plan-sensitive units are invalidated.
11
12use std::collections::{BTreeMap, BTreeSet};
13use std::env;
14use std::ffi::{OsStr, OsString};
15use std::fs;
16use std::fs::{File, OpenOptions};
17use std::io::{self, BufRead, BufReader, Read, Write};
18use std::path::{Path, PathBuf};
19use std::process::{Command, ExitStatus, Stdio};
20use std::sync::atomic::{AtomicU64, Ordering};
21
22use object::{Architecture, BinaryFormat, Object as _};
23use rsjs_ir::abi::{FinalUnitId, InvocationId, LinkUnitId, PlanId, SemanticHash};
24use serde_json::Value;
25use sha2::{Digest, Sha256};
26use thiserror::Error;
27
28use crate::rsjs::build::{
29    acquire_descriptor_target_lease, scrub_wrapper_control_environment,
30    wrapper_control_environment, write_content_addressed_final_unit_map, CargoArtifactCollector,
31    CargoArtifactTarget, CargoCompilerArtifact, CargoMessageError, DescriptorCargoRunError,
32    DescriptorTargetLease, FinalUnitMapError, ValidatedDescriptorUnit,
33    COMPONENT_DESCRIPTOR_DIRS_ENV, FINAL_CARGO_UNIT_STATUS_ENV, FINAL_TARGET_DIR_ENV,
34    FINAL_UNIT_MAP_HASH_ENV, FINAL_UNIT_MAP_PATH_ENV, FINAL_WRAPPER_POLICY_VERSION,
35    SOURCE_EXCLUSION_DIR_ENV, WRAPPER_MODE_ENV, WRAPPER_MODE_FINAL_V2,
36};
37pub use crate::rsjs::build::{
38    FINAL_PHASE_ENV, FINAL_PLAN_FILE_HASH_ENV, FINAL_PLAN_ID_ENV, FINAL_PLAN_PATH_ENV,
39};
40use crate::rsjs::link::{transport_plan_json, TransportLinkPlan};
41use crate::rsjs::semantic_link::{
42    semantic_plan_json, SemanticLinkPlan, SEMANTIC_PLAN_FILE_SUFFIX, SEMANTIC_PLAN_FORMAT,
43};
44
45const PLAN_FILE_FORMAT: &str = "proa.rsjs.resolved_transport_plan";
46const TRANSPORT_PLAN_FILE_SUFFIX: &str = "transport-plan.json";
47static FINAL_SNAPSHOT_NONCE: AtomicU64 = AtomicU64::new(0);
48/// Linked-plan variants accepted by the final Cargo runner.
49pub trait FinalCargoPlan {
50    /// Strong plan identity used for Cargo invalidation.
51    fn final_plan_id(&self) -> PlanId;
52    /// Exact root graph identity.
53    fn final_link_unit(&self) -> LinkUnitId;
54    /// External JSON format discriminator.
55    fn final_plan_format(&self) -> &'static str;
56    /// Content-addressed filename suffix.
57    fn final_plan_file_suffix(&self) -> &'static str;
58    /// Complete deterministic JSON value expected at the linked-plan path.
59    fn final_plan_json(&self) -> Result<Value, String>;
60}
61
62impl FinalCargoPlan for TransportLinkPlan {
63    fn final_plan_id(&self) -> PlanId {
64        self.plan_id
65    }
66
67    fn final_link_unit(&self) -> LinkUnitId {
68        self.link_unit
69    }
70
71    fn final_plan_format(&self) -> &'static str {
72        PLAN_FILE_FORMAT
73    }
74
75    fn final_plan_file_suffix(&self) -> &'static str {
76        TRANSPORT_PLAN_FILE_SUFFIX
77    }
78
79    fn final_plan_json(&self) -> Result<Value, String> {
80        Ok(transport_plan_json(self))
81    }
82}
83
84impl FinalCargoPlan for SemanticLinkPlan {
85    fn final_plan_id(&self) -> PlanId {
86        self.plan_id
87    }
88
89    fn final_link_unit(&self) -> LinkUnitId {
90        self.link_unit
91    }
92
93    fn final_plan_format(&self) -> &'static str {
94        SEMANTIC_PLAN_FORMAT
95    }
96
97    fn final_plan_file_suffix(&self) -> &'static str {
98        SEMANTIC_PLAN_FILE_SUFFIX
99    }
100
101    fn final_plan_json(&self) -> Result<Value, String> {
102        semantic_plan_json(self).map_err(|error| error.to_string())
103    }
104}
105
106/// One root-specific final Cargo invocation.
107#[derive(Clone, Debug)]
108pub struct FinalCargoRequest {
109    /// Stable pre-Cargo invocation identity separating roots, features,
110    /// profiles, and target selections while remaining unchanged by sources.
111    pub invocation: InvocationId,
112    /// Cargo executable.
113    pub cargo: OsString,
114    /// Absolute `cargo-proa`/`proa` executable used as `RUSTC_WRAPPER`.
115    pub wrapper: PathBuf,
116    /// Absolute Cargo working directory.
117    pub working_directory: PathBuf,
118    /// Exact generated subtree excluded from both descriptor and final package
119    /// source-closure identities.
120    pub source_exclusion_directory: PathBuf,
121    /// Absolute parent for wrapper-policy-scoped final target directories.
122    pub target_root: PathBuf,
123    /// Exact content-addressed plan written by the linker.
124    pub plan_path: PathBuf,
125    /// Cargo arguments including subcommand and target selection.
126    ///
127    /// The runner owns `--message-format` and `--target-dir`.
128    pub cargo_args: Vec<OsString>,
129    /// Additional exact build environment.
130    pub environment: BTreeMap<OsString, OsString>,
131    /// Semantic fingerprint of the root descriptor unit before plan
132    /// specialization.
133    pub root_unit_fingerprint: SemanticHash,
134    /// Freshly validated descriptor units authorized for final identity
135    /// restoration.
136    pub descriptor_units: Vec<ValidatedDescriptorUnit>,
137}
138
139/// Path-free report for one final Cargo artifact.
140///
141/// Cargo's materialized artifact paths live in a reusable target and may be
142/// replaced by a later build. Only the leased runner sees those raw paths;
143/// durable linked outputs expose an immutable snapshot of the selected root.
144#[derive(Clone, Debug, PartialEq)]
145pub struct FinalCargoArtifactReport {
146    /// Cargo package ID, exactly as Cargo emitted it.
147    pub package_id: String,
148    /// Target identity reported by Cargo.
149    pub target: CargoArtifactTarget,
150    /// Profile object reported by Cargo.
151    pub profile: Value,
152    /// Enabled features, normalized for exact matching.
153    pub features: BTreeSet<String>,
154    /// Whether Cargo reused the artifact.
155    pub fresh: bool,
156}
157
158impl From<&CargoCompilerArtifact> for FinalCargoArtifactReport {
159    fn from(artifact: &CargoCompilerArtifact) -> Self {
160        Self {
161            package_id: artifact.package_id.clone(),
162            target: artifact.target.clone(),
163            profile: artifact.profile.clone(),
164            features: artifact.features.clone(),
165            fresh: artifact.fresh,
166        }
167    }
168}
169
170/// Successful plan-sensitive Cargo output.
171#[derive(Clone, Debug)]
172pub struct FinalCargoOutput {
173    /// Plan consumed by this compilation.
174    pub plan_id: PlanId,
175    /// Root unit specialized by `plan_id`.
176    pub final_unit_id: FinalUnitId,
177    /// Stable wrapper-policy-scoped target directory.
178    pub target_directory: PathBuf,
179    /// Content-addressed phase-invariant unit map consumed by the wrapper.
180    pub unit_map_path: PathBuf,
181    /// SHA-256 of the exact unit-map bytes.
182    pub unit_map_hash: String,
183    /// Tagged `sha256:<hex>` digest of the exact linked-plan bytes.
184    pub plan_file_hash: String,
185    /// Path-free reports from strictly parsed Cargo artifact messages.
186    pub cargo_artifacts: Vec<FinalCargoArtifactReport>,
187}
188
189/// One final Cargo result whose stable target remains exclusively leased.
190///
191/// The linked pipeline retains this lease through root attestation, launch
192/// dependency validation, and immutable snapshot publication. This prevents a
193/// concurrent build for the same invocation from replacing stable target
194/// paths while any of those operations still reads them. Once the selected
195/// root is represented only by a supported content-addressed snapshot, the
196/// pipeline consumes this value and releases the lease before execution.
197#[must_use = "final Cargo runs retain their target lease until consumed"]
198pub(crate) struct FinalCargoRun {
199    output: FinalCargoOutput,
200    cargo_artifacts: Vec<CargoCompilerArtifact>,
201    _target_lease: DescriptorTargetLease,
202}
203
204impl FinalCargoRun {
205    pub(crate) fn output(&self) -> &FinalCargoOutput {
206        &self.output
207    }
208
209    pub(crate) fn cargo_artifacts(&self) -> &[CargoCompilerArtifact] {
210        &self.cargo_artifacts
211    }
212
213    pub(crate) fn into_output(self) -> FinalCargoOutput {
214        self.output
215    }
216}
217
218/// Validate the plan and run one final, compile-only Cargo invocation.
219///
220/// An original `cargo run` request is compiled with `cargo build`; an original
221/// `cargo test` request is compiled with `cargo test --no-run`. Runtime
222/// arguments are never passed to Cargo here. Before optional execution, the
223/// linked pipeline attests the exact resulting root, validates its launch
224/// dependencies, and publishes a supported immutable snapshot.
225pub fn run_final_cargo<P: FinalCargoPlan>(
226    request: &FinalCargoRequest,
227    plan: &P,
228) -> Result<FinalCargoOutput, FinalCargoError> {
229    run_final_cargo_leased(request, plan).map(FinalCargoRun::into_output)
230}
231
232/// Run final Cargo while retaining exclusive authority over its stable target.
233///
234/// Callers that inspect materialized target paths must keep the returned lease
235/// alive until inspection finishes or the selected root has passed launch
236/// dependency validation and been published into immutable storage. The linked
237/// pipeline uses the latter path so optional execution does not retain the
238/// reusable target lease.
239pub(crate) fn run_final_cargo_leased<P: FinalCargoPlan>(
240    request: &FinalCargoRequest,
241    plan: &P,
242) -> Result<FinalCargoRun, FinalCargoError> {
243    validate_request(request)?;
244    let plan_file_hash = validate_plan_file(&request.plan_path, plan)?;
245    let plan_id = plan.final_plan_id();
246    let unit_map_directory = request.target_root.join("rsjs-final-unit-maps");
247    ensure_plain_managed_directory(&request.source_exclusion_directory, &unit_map_directory)?;
248    let unit_map = write_content_addressed_final_unit_map(
249        &unit_map_directory,
250        plan_id,
251        &plan_file_hash,
252        &request.descriptor_units,
253    )
254    .map_err(FinalCargoError::UnitMap)?;
255    ensure_plain_managed_file(&request.source_exclusion_directory, &unit_map.path)?;
256
257    let target_directory = final_target_directory(&request.target_root, request.invocation);
258    ensure_plain_managed_directory(&request.source_exclusion_directory, &target_directory)?;
259    let target_lease =
260        acquire_descriptor_target_lease(&target_directory).map_err(FinalCargoError::TargetLease)?;
261
262    let mut environment = request.environment.clone();
263    inject_plan_environment(
264        &mut environment,
265        request,
266        plan,
267        &plan_file_hash,
268        &unit_map.path,
269        &unit_map.content_hash,
270    )?;
271    let cargo_args = compile_only_cargo_arguments(&request.cargo_args)?;
272    let mut command = Command::new(&request.cargo);
273    command
274        .current_dir(&request.working_directory)
275        .args(&cargo_args)
276        .arg("--target-dir")
277        .arg(&target_directory)
278        .arg("--message-format=json-render-diagnostics");
279    scrub_wrapper_control_environment(&mut command);
280    command
281        .envs(&environment)
282        .env("RUSTC_WRAPPER", &request.wrapper)
283        .env_remove("RUSTC_WORKSPACE_WRAPPER")
284        .env(WRAPPER_MODE_ENV, WRAPPER_MODE_FINAL_V2)
285        .env(
286            SOURCE_EXCLUSION_DIR_ENV,
287            &request.source_exclusion_directory,
288        )
289        .env(FINAL_TARGET_DIR_ENV, &target_directory)
290        .env_remove("RSJS_DESCRIPTOR_PHASE")
291        .env_remove("RSJS_CARGO_UNIT_ID")
292        .stdout(Stdio::piped())
293        .stderr(Stdio::inherit());
294    let mut child = command
295        .spawn()
296        .map_err(|source| FinalCargoError::SpawnCargo {
297            program: PathBuf::from(&request.cargo),
298            source,
299        })?;
300    let stdout = child
301        .stdout
302        .take()
303        .ok_or(FinalCargoError::MissingCargoStdout)?;
304    let mut collector = CargoArtifactCollector::default();
305    let mut stdout = BufReader::new(stdout);
306    let mut cargo_line_number = 0_usize;
307    loop {
308        let mut bytes = Vec::new();
309        let read = match stdout.read_until(b'\n', &mut bytes) {
310            Ok(read) => read,
311            Err(source) => {
312                let _ = child.kill();
313                let _ = child.wait();
314                return Err(FinalCargoError::ReadCargoStdout(source));
315            }
316        };
317        if read == 0 {
318            break;
319        }
320        cargo_line_number += 1;
321        if bytes.last() == Some(&b'\n') {
322            bytes.pop();
323            if bytes.last() == Some(&b'\r') {
324                bytes.pop();
325            }
326        }
327        let line = match std::str::from_utf8(&bytes) {
328            Ok(line) => line,
329            Err(source) => {
330                let _ = child.kill();
331                let _ = child.wait();
332                return Err(FinalCargoError::NonUtf8CargoProtocol {
333                    line: cargo_line_number,
334                    source,
335                });
336            }
337        };
338        forward_rendered_cargo_diagnostic(line);
339        if let Err(source) = collector.ingest_line(line) {
340            let _ = child.kill();
341            let _ = child.wait();
342            return Err(FinalCargoError::CargoProtocol(source));
343        }
344    }
345    let status = child.wait().map_err(FinalCargoError::WaitForCargo)?;
346    if !status.success() {
347        return Err(FinalCargoError::CargoFailed(status));
348    }
349    let cargo_artifacts = collector.finish().map_err(FinalCargoError::CargoProtocol)?;
350    if cargo_artifacts.is_empty() {
351        return Err(FinalCargoError::NoCargoArtifacts);
352    }
353    let cargo_artifact_reports = cargo_artifacts
354        .iter()
355        .map(FinalCargoArtifactReport::from)
356        .collect();
357
358    Ok(FinalCargoRun {
359        output: FinalCargoOutput {
360            plan_id,
361            final_unit_id: FinalUnitId::for_plan(request.root_unit_fingerprint, plan_id),
362            target_directory,
363            unit_map_path: unit_map.path,
364            unit_map_hash: unit_map.content_hash,
365            plan_file_hash,
366            cargo_artifacts: cargo_artifact_reports,
367        },
368        cargo_artifacts,
369        _target_lease: target_lease,
370    })
371}
372
373fn validate_request(request: &FinalCargoRequest) -> Result<(), FinalCargoError> {
374    if !request.wrapper.is_absolute() {
375        return Err(FinalCargoError::RelativeWrapper(request.wrapper.clone()));
376    }
377    if !request.working_directory.is_absolute() {
378        return Err(FinalCargoError::RelativeWorkingDirectory(
379            request.working_directory.clone(),
380        ));
381    }
382    if !request.target_root.is_absolute() {
383        return Err(FinalCargoError::RelativeTargetRoot(
384            request.target_root.clone(),
385        ));
386    }
387    if !request.source_exclusion_directory.is_absolute() {
388        return Err(FinalCargoError::RelativeSourceExclusionDirectory(
389            request.source_exclusion_directory.clone(),
390        ));
391    }
392    if !request.plan_path.is_absolute() {
393        return Err(FinalCargoError::RelativePlanPath(request.plan_path.clone()));
394    }
395    if request.cargo_args.is_empty() {
396        return Err(FinalCargoError::MissingCargoArguments);
397    }
398    if env::var_os(COMPONENT_DESCRIPTOR_DIRS_ENV).is_some()
399        || request
400            .environment
401            .contains_key(OsStr::new(COMPONENT_DESCRIPTOR_DIRS_ENV))
402    {
403        return Err(FinalCargoError::UnsupportedEnvironment(
404            COMPONENT_DESCRIPTOR_DIRS_ENV,
405        ));
406    }
407    let cargo_args = compile_only_cargo_arguments(&request.cargo_args)?;
408    for argument in cargo_args {
409        let argument = argument.to_string_lossy();
410        if argument == "--target-dir"
411            || argument.starts_with("--target-dir=")
412            || argument == "--message-format"
413            || argument.starts_with("--message-format=")
414        {
415            return Err(FinalCargoError::ReservedCargoArgument(
416                argument.into_owned(),
417            ));
418        }
419    }
420    if let Some(name) = request
421        .environment
422        .keys()
423        .find(|name| name.to_str().is_some_and(wrapper_control_environment))
424    {
425        return Err(FinalCargoError::ReservedEnvironment(
426            name.to_string_lossy().into_owned(),
427        ));
428    }
429    for reserved in [
430        OsStr::new(FINAL_PHASE_ENV),
431        OsStr::new(FINAL_PLAN_PATH_ENV),
432        OsStr::new(FINAL_PLAN_ID_ENV),
433        OsStr::new(FINAL_PLAN_FILE_HASH_ENV),
434        OsStr::new(FINAL_UNIT_MAP_PATH_ENV),
435        OsStr::new(FINAL_UNIT_MAP_HASH_ENV),
436        OsStr::new(FINAL_CARGO_UNIT_STATUS_ENV),
437        OsStr::new(WRAPPER_MODE_ENV),
438        OsStr::new(SOURCE_EXCLUSION_DIR_ENV),
439        OsStr::new(FINAL_TARGET_DIR_ENV),
440        OsStr::new("RSJS_DESCRIPTOR_PHASE"),
441        OsStr::new("RSJS_CARGO_UNIT_ID"),
442    ] {
443        if request.environment.contains_key(reserved) {
444            return Err(FinalCargoError::ReservedEnvironment(
445                reserved.to_string_lossy().into_owned(),
446            ));
447        }
448    }
449    if env::var_os("RUSTC_WORKSPACE_WRAPPER").is_some()
450        || request
451            .environment
452            .contains_key(OsStr::new("RUSTC_WORKSPACE_WRAPPER"))
453    {
454        return Err(FinalCargoError::ExistingWorkspaceWrapper);
455    }
456    if env::var_os("RUSTC_WRAPPER").is_some()
457        || request
458            .environment
459            .contains_key(OsStr::new("RUSTC_WRAPPER"))
460    {
461        return Err(FinalCargoError::ExistingRustcWrapper);
462    }
463    ensure_plain_managed_directory(&request.source_exclusion_directory, &request.target_root)?;
464    ensure_plain_managed_file(&request.source_exclusion_directory, &request.plan_path)?;
465    Ok(())
466}
467
468/// Failure to confine a final-build path beneath its trusted generated-output
469/// boundary using only ordinary directories and regular files.
470#[derive(Debug, Error)]
471#[non_exhaustive]
472pub enum ManagedPathError {
473    /// Managed paths must have an unambiguous lexical spelling.
474    #[error("managed path contains `.` or `..`: `{0}`")]
475    NonNormalPath(PathBuf),
476    /// A managed output escaped the source-exclusion boundary.
477    #[error("managed path `{path}` is outside source exclusion `{exclusion}`")]
478    OutsideSourceExclusion {
479        /// Rejected output path.
480        path: PathBuf,
481        /// Trusted generated-output boundary.
482        exclusion: PathBuf,
483    },
484    /// A directory component could not be created.
485    #[error("failed to create managed directory `{path}`: {source}")]
486    CreateDirectory {
487        /// Directory being created.
488        path: PathBuf,
489        /// Filesystem failure.
490        #[source]
491        source: io::Error,
492    },
493    /// A managed path could not be inspected without following symlinks.
494    #[error("failed to inspect managed path `{path}`: {source}")]
495    Inspect {
496        /// Path being inspected.
497        path: PathBuf,
498        /// Filesystem failure.
499        #[source]
500        source: io::Error,
501    },
502    /// Directory traversal encountered a symlink or non-directory.
503    #[error("managed directory component is not a plain directory: `{0}`")]
504    NonDirectory(PathBuf),
505    /// A content-addressed input/output was a symlink or non-file.
506    #[error("managed file is not a plain regular file: `{0}`")]
507    NonFile(PathBuf),
508    /// A file path had no containing directory.
509    #[error("managed file has no parent directory: `{0}`")]
510    FileWithoutParent(PathBuf),
511}
512
513/// Create and validate `directory` one plain component at a time beneath the
514/// trusted source-exclusion boundary.
515///
516/// The boundary itself is the trust anchor. Every descendant is inspected via
517/// `symlink_metadata`, so a pre-existing symlink cannot redirect a unit-map or
518/// final-target write outside that boundary.
519pub(crate) fn ensure_plain_managed_directory(
520    source_exclusion: &Path,
521    directory: &Path,
522) -> Result<(), ManagedPathError> {
523    validate_normal_absolute_path(source_exclusion)?;
524    validate_normal_absolute_path(directory)?;
525    let relative = directory.strip_prefix(source_exclusion).map_err(|_| {
526        ManagedPathError::OutsideSourceExclusion {
527            path: directory.to_path_buf(),
528            exclusion: source_exclusion.to_path_buf(),
529        }
530    })?;
531
532    fs::create_dir_all(source_exclusion).map_err(|source| ManagedPathError::CreateDirectory {
533        path: source_exclusion.to_path_buf(),
534        source,
535    })?;
536    require_plain_directory(source_exclusion)?;
537
538    let mut current = source_exclusion.to_path_buf();
539    for component in relative.components() {
540        let std::path::Component::Normal(name) = component else {
541            return Err(ManagedPathError::NonNormalPath(directory.to_path_buf()));
542        };
543        current.push(name);
544        match fs::create_dir(&current) {
545            Ok(()) => {}
546            Err(source) if source.kind() == io::ErrorKind::AlreadyExists => {}
547            Err(source) => {
548                return Err(ManagedPathError::CreateDirectory {
549                    path: current,
550                    source,
551                });
552            }
553        }
554        require_plain_directory(&current)?;
555    }
556    Ok(())
557}
558
559pub(crate) fn ensure_plain_managed_file(
560    source_exclusion: &Path,
561    file: &Path,
562) -> Result<(), ManagedPathError> {
563    validate_normal_absolute_path(file)?;
564    let parent = file
565        .parent()
566        .ok_or_else(|| ManagedPathError::FileWithoutParent(file.to_path_buf()))?;
567    ensure_plain_managed_directory(source_exclusion, parent)?;
568    let metadata = fs::symlink_metadata(file).map_err(|source| ManagedPathError::Inspect {
569        path: file.to_path_buf(),
570        source,
571    })?;
572    if !metadata.file_type().is_file() {
573        return Err(ManagedPathError::NonFile(file.to_path_buf()));
574    }
575    Ok(())
576}
577
578fn validate_normal_absolute_path(path: &Path) -> Result<(), ManagedPathError> {
579    if !path.is_absolute()
580        || path.components().any(|component| {
581            matches!(
582                component,
583                std::path::Component::CurDir | std::path::Component::ParentDir
584            )
585        })
586    {
587        return Err(ManagedPathError::NonNormalPath(path.to_path_buf()));
588    }
589    Ok(())
590}
591
592fn require_plain_directory(path: &Path) -> Result<(), ManagedPathError> {
593    let metadata = fs::symlink_metadata(path).map_err(|source| ManagedPathError::Inspect {
594        path: path.to_path_buf(),
595        source,
596    })?;
597    if !metadata.file_type().is_dir() {
598        return Err(ManagedPathError::NonDirectory(path.to_path_buf()));
599    }
600    Ok(())
601}
602
603fn split_runtime_arguments(arguments: &[OsString]) -> (&[OsString], Option<&[OsString]>) {
604    match arguments
605        .iter()
606        .position(|argument| argument == OsStr::new("--"))
607    {
608        Some(index) => (&arguments[..index], Some(&arguments[index + 1..])),
609        None => (arguments, None),
610    }
611}
612
613fn compile_only_cargo_arguments(arguments: &[OsString]) -> Result<Vec<OsString>, FinalCargoError> {
614    let (compile_arguments, runtime_arguments) = split_runtime_arguments(arguments);
615    let mut compile_arguments = compile_arguments.to_vec();
616    let subcommand = compile_arguments
617        .first()
618        .cloned()
619        .ok_or(FinalCargoError::MissingCargoArguments)?;
620    match subcommand.as_os_str() {
621        value if value == OsStr::new("run") => {
622            compile_arguments[0] = OsString::from("build");
623        }
624        value if value == OsStr::new("test") => {
625            if !compile_arguments
626                .iter()
627                .any(|argument| argument == OsStr::new("--no-run"))
628            {
629                compile_arguments.push(OsString::from("--no-run"));
630            }
631        }
632        value if value == OsStr::new("build") || value == OsStr::new("check") => {
633            if runtime_arguments.is_some() {
634                return Err(FinalCargoError::RuntimeArgumentsForCompileOnlySubcommand(
635                    subcommand.clone(),
636                ));
637            }
638        }
639        _ => {
640            return Err(FinalCargoError::UnsupportedCargoSubcommand(
641                subcommand.clone(),
642            ));
643        }
644    }
645    Ok(compile_arguments)
646}
647
648fn validate_plan_file<P: FinalCargoPlan>(path: &Path, plan: &P) -> Result<String, FinalCargoError> {
649    let bytes = fs::read(path).map_err(|source| FinalCargoError::ReadPlan {
650        path: path.to_path_buf(),
651        source,
652    })?;
653    let value: Value =
654        serde_json::from_slice(&bytes).map_err(|source| FinalCargoError::ParsePlan {
655            path: path.to_path_buf(),
656            source,
657        })?;
658    let format = value.get("format").and_then(Value::as_str);
659    if format != Some(plan.final_plan_format()) {
660        return Err(FinalCargoError::PlanFormat {
661            actual: format.unwrap_or_default().to_string(),
662        });
663    }
664    let file_plan_id = value.get("plan_id").and_then(Value::as_str);
665    let expected_plan_id = plan.final_plan_id().to_string();
666    if file_plan_id != Some(expected_plan_id.as_str()) {
667        return Err(FinalCargoError::PlanIdMismatch {
668            expected: plan.final_plan_id(),
669            actual: file_plan_id.unwrap_or_default().to_string(),
670        });
671    }
672    let file_link_unit = value.get("link_unit_id").and_then(Value::as_str);
673    let expected_link_unit = plan.final_link_unit().to_string();
674    if file_link_unit != Some(expected_link_unit.as_str()) {
675        return Err(FinalCargoError::LinkUnitMismatch {
676            expected: expected_link_unit,
677            actual: file_link_unit.unwrap_or_default().to_string(),
678        });
679    }
680
681    let expected_name = format!("{}.{}", plan.final_plan_id(), plan.final_plan_file_suffix());
682    if path.file_name() != Some(OsStr::new(&expected_name)) {
683        return Err(FinalCargoError::PlanFilename {
684            path: path.to_path_buf(),
685            expected: expected_name,
686        });
687    }
688    let expected_value = plan
689        .final_plan_json()
690        .map_err(FinalCargoError::SerializeExpectedPlan)?;
691    if value != expected_value {
692        return Err(FinalCargoError::PlanContentMismatch);
693    }
694    Ok(exact_sha256_hex(&bytes))
695}
696
697fn inject_plan_environment<P: FinalCargoPlan>(
698    environment: &mut BTreeMap<OsString, OsString>,
699    request: &FinalCargoRequest,
700    plan: &P,
701    plan_file_hash: &str,
702    unit_map_path: &Path,
703    unit_map_hash: &str,
704) -> Result<(), FinalCargoError> {
705    let plan_path = request
706        .plan_path
707        .to_str()
708        .ok_or_else(|| FinalCargoError::NonUtf8PlanPath(request.plan_path.clone()))?;
709    environment.insert(OsString::from(FINAL_PHASE_ENV), OsString::from("1"));
710    environment.insert(
711        OsString::from(FINAL_PLAN_PATH_ENV),
712        OsString::from(plan_path),
713    );
714    environment.insert(
715        OsString::from(FINAL_PLAN_ID_ENV),
716        OsString::from(plan.final_plan_id().to_string()),
717    );
718    environment.insert(
719        OsString::from(FINAL_PLAN_FILE_HASH_ENV),
720        OsString::from(plan_file_hash),
721    );
722    environment.insert(
723        OsString::from(FINAL_UNIT_MAP_PATH_ENV),
724        unit_map_path.as_os_str().to_owned(),
725    );
726    environment.insert(
727        OsString::from(FINAL_UNIT_MAP_HASH_ENV),
728        OsString::from(unit_map_hash),
729    );
730
731    Ok(())
732}
733
734fn exact_sha256_hex(bytes: &[u8]) -> String {
735    use std::fmt::Write as _;
736
737    let digest: [u8; 32] = Sha256::digest(bytes).into();
738    let mut output = String::with_capacity(64);
739    for byte in digest {
740        let _ = write!(output, "{byte:02x}");
741    }
742    format!("sha256:{output}")
743}
744
745fn final_target_directory(target_root: &Path, invocation: InvocationId) -> PathBuf {
746    target_root
747        .join("rsjs-final")
748        .join(format!("wrapper-v{FINAL_WRAPPER_POLICY_VERSION}"))
749        .join(invocation.to_string())
750}
751
752/// Publish every materialized path for one selected root into immutable,
753/// content-addressed storage while the reusable Cargo target is still leased.
754pub(crate) fn snapshot_final_artifact(
755    source_exclusion: &Path,
756    snapshot_root: &Path,
757    target_directory: &Path,
758    artifact: &CargoCompilerArtifact,
759) -> Result<CargoCompilerArtifact, FinalCargoError> {
760    ensure_plain_managed_directory(source_exclusion, snapshot_root)?;
761
762    let mut snapshots = BTreeMap::new();
763    if let Some(executable) = &artifact.executable {
764        ensure_plain_managed_file(target_directory, executable)?;
765        snapshots.insert(
766            executable.clone(),
767            snapshot_final_file(
768                source_exclusion,
769                snapshot_root,
770                executable,
771                Some(target_directory),
772            )?,
773        );
774    }
775    for source in &artifact.filenames {
776        if artifact.executable.as_ref() == Some(source) {
777            continue;
778        }
779        ensure_plain_managed_file(target_directory, source)?;
780        snapshots.insert(
781            source.clone(),
782            snapshot_final_file(source_exclusion, snapshot_root, source, None)?,
783        );
784    }
785
786    let mut snapshot = artifact.clone();
787    snapshot.filenames = artifact
788        .filenames
789        .iter()
790        .map(|source| {
791            snapshots
792                .get(source)
793                .cloned()
794                .expect("every final filename was snapshotted")
795        })
796        .collect();
797    snapshot.executable = artifact.executable.as_ref().map(|source| {
798        snapshots
799            .get(source)
800            .cloned()
801            .expect("the final executable was snapshotted")
802    });
803    Ok(snapshot)
804}
805
806fn snapshot_final_file(
807    source_exclusion: &Path,
808    snapshot_root: &Path,
809    source: &Path,
810    launch_target_directory: Option<&Path>,
811) -> Result<PathBuf, FinalCargoError> {
812    let metadata = fs::symlink_metadata(source).map_err(|source_error| {
813        FinalCargoError::SnapshotArtifactIo {
814            path: source.to_path_buf(),
815            source: source_error,
816        }
817    })?;
818    if !metadata.file_type().is_file() {
819        return Err(FinalCargoError::SnapshotArtifactNotFile(
820            source.to_path_buf(),
821        ));
822    }
823    let file_name = source
824        .file_name()
825        .ok_or_else(|| FinalCargoError::SnapshotArtifactWithoutFilename(source.to_path_buf()))?;
826    let permissions = metadata.permissions();
827    let permission_identity = snapshot_permission_identity(&permissions);
828
829    let nonce = FINAL_SNAPSHOT_NONCE.fetch_add(1, Ordering::Relaxed);
830    let temporary = snapshot_root.join(format!(".snapshot.{}.{}.tmp", std::process::id(), nonce));
831    let mut input =
832        File::open(source).map_err(|source_error| FinalCargoError::SnapshotArtifactIo {
833            path: source.to_path_buf(),
834            source: source_error,
835        })?;
836    let mut output = OpenOptions::new()
837        .create_new(true)
838        .write(true)
839        .open(&temporary)
840        .map_err(|source_error| FinalCargoError::SnapshotArtifactIo {
841            path: temporary.clone(),
842            source: source_error,
843        })?;
844    let mut hash = Sha256::new();
845    let mut buffer = [0_u8; 64 * 1024];
846    let copy_result = (|| -> io::Result<()> {
847        loop {
848            let read = input.read(&mut buffer)?;
849            if read == 0 {
850                break;
851            }
852            hash.update(&buffer[..read]);
853            output.write_all(&buffer[..read])?;
854        }
855        output.sync_all()?;
856        drop(output);
857        fs::set_permissions(&temporary, permissions)?;
858        Ok(())
859    })();
860    if let Err(source_error) = copy_result {
861        let _ = fs::remove_file(&temporary);
862        return Err(FinalCargoError::SnapshotArtifactIo {
863            path: temporary,
864            source: source_error,
865        });
866    }
867
868    if let Some(target_directory) = launch_target_directory {
869        if let Err(error) = validate_executable_snapshot_contract(&temporary, target_directory) {
870            let _ = fs::remove_file(&temporary);
871            return Err(error);
872        }
873    }
874
875    let digest: [u8; 32] = hash.finalize().into();
876    let identity = format!("{}-{permission_identity}", hex_sha256(&digest));
877    let destination_directory = snapshot_root.join(identity);
878    ensure_plain_managed_directory(source_exclusion, &destination_directory)?;
879    let destination = destination_directory.join(file_name);
880    match fs::hard_link(&temporary, &destination) {
881        Ok(()) => {
882            fs::remove_file(&temporary).map_err(|source_error| {
883                FinalCargoError::SnapshotArtifactIo {
884                    path: temporary,
885                    source: source_error,
886                }
887            })?;
888        }
889        Err(source_error) if source_error.kind() == io::ErrorKind::AlreadyExists => {
890            let _ = fs::remove_file(&temporary);
891            let (existing_digest, existing_permissions) = snapshot_file_identity(&destination)?;
892            if existing_digest != digest || existing_permissions != permission_identity {
893                return Err(FinalCargoError::ConflictingSnapshotArtifact(destination));
894            }
895        }
896        Err(source_error) => {
897            let _ = fs::remove_file(&temporary);
898            return Err(FinalCargoError::SnapshotArtifactIo {
899                path: destination,
900                source: source_error,
901            });
902        }
903    }
904    ensure_plain_managed_file(source_exclusion, &destination)?;
905    Ok(destination)
906}
907
908/// Publish the exact wrapper bytes into the generated-output CAS before Cargo
909/// is allowed to reopen an executable path.
910///
911/// This uses the same lstat, one-open-file copy, relocation/dependency check,
912/// atomic publication, and existing-entry verification contract as final
913/// executable snapshots. The returned path is content addressed and can
914/// therefore be bound into the linked invocation identity without trusting the
915/// caller's mutable pathname.
916pub(crate) fn snapshot_wrapper_executable(
917    source_exclusion: &Path,
918    snapshot_root: &Path,
919    source: &Path,
920) -> Result<PathBuf, FinalCargoError> {
921    ensure_plain_managed_directory(source_exclusion, snapshot_root)?;
922    snapshot_final_file(
923        source_exclusion,
924        snapshot_root,
925        source,
926        Some(source_exclusion),
927    )
928}
929
930#[derive(Debug, Default)]
931struct ExecutableSnapshotDependencies {
932    libraries: BTreeSet<Vec<u8>>,
933    loader_paths: BTreeSet<Vec<u8>>,
934    interpreters: BTreeSet<Vec<u8>>,
935}
936
937fn validate_executable_snapshot_contract(
938    executable: &Path,
939    target_directory: &Path,
940) -> Result<(), FinalCargoError> {
941    let bytes = fs::read(executable).map_err(|source| FinalCargoError::SnapshotArtifactIo {
942        path: executable.to_path_buf(),
943        source,
944    })?;
945    let file = object::File::parse(bytes.as_slice()).map_err(|source| {
946        FinalCargoError::UnsupportedSnapshotExecutable {
947            path: executable.to_path_buf(),
948            reason: format!("the executable format could not be parsed: {source}"),
949        }
950    })?;
951    let format = file.format();
952    validate_snapshot_host_identity(executable, format, file.architecture())?;
953
954    let dependencies = executable_snapshot_dependencies(&file).map_err(|source| {
955        FinalCargoError::UnsupportedSnapshotExecutable {
956            path: executable.to_path_buf(),
957            reason: format!("the runtime dependency table could not be validated: {source}"),
958        }
959    })?;
960    if let Some(loader_path) = dependencies.loader_paths.into_iter().next() {
961        let loader_path = dependency_name(&loader_path).ok_or_else(|| {
962            FinalCargoError::UnsupportedSnapshotExecutable {
963                path: executable.to_path_buf(),
964                reason: "a loader search path is not valid UTF-8".to_string(),
965            }
966        })?;
967        if loader_path.is_empty() || loader_path_is_relative(loader_path) {
968            return Err(FinalCargoError::UnsupportedSnapshotDependency {
969                path: executable.to_path_buf(),
970                dependency: loader_path.to_string(),
971                reason:
972                    "it uses a relative loader search path whose meaning changes after relocation",
973            });
974        }
975        return Err(FinalCargoError::UnsupportedSnapshotDependency {
976            path: executable.to_path_buf(),
977            dependency: loader_path.to_string(),
978            reason: "custom loader search paths are outside the system-only snapshot contract",
979        });
980    }
981
982    for interpreter in dependencies.interpreters {
983        let interpreter = dependency_name(&interpreter).ok_or_else(|| {
984            FinalCargoError::UnsupportedSnapshotExecutable {
985                path: executable.to_path_buf(),
986                reason: "the program interpreter or dynamic loader is not valid UTF-8".to_string(),
987            }
988        })?;
989        validate_snapshot_interpreter(executable, target_directory, interpreter)?;
990    }
991
992    for dependency in dependencies.libraries {
993        let dependency = dependency_name(&dependency).ok_or_else(|| {
994            FinalCargoError::UnsupportedSnapshotExecutable {
995                path: executable.to_path_buf(),
996                reason: "a dynamic-library dependency name is not valid UTF-8".to_string(),
997            }
998        })?;
999        validate_snapshot_dependency(format, executable, target_directory, dependency)?;
1000    }
1001    Ok(())
1002}
1003
1004fn validate_snapshot_host_identity(
1005    executable: &Path,
1006    format: BinaryFormat,
1007    architecture: Architecture,
1008) -> Result<(), FinalCargoError> {
1009    if format != host_executable_format() {
1010        return Err(FinalCargoError::UnsupportedSnapshotExecutable {
1011            path: executable.to_path_buf(),
1012            reason: format!(
1013                "the {format:?} executable format is not the current host's supported launch format ({:?})",
1014                host_executable_format()
1015            ),
1016        });
1017    }
1018    let Some(host_architecture) = host_architecture() else {
1019        return Err(FinalCargoError::UnsupportedSnapshotExecutable {
1020            path: executable.to_path_buf(),
1021            reason: format!(
1022                "the current host architecture `{}` has no immutable launch-snapshot contract",
1023                std::env::consts::ARCH
1024            ),
1025        });
1026    };
1027    if architecture != host_architecture {
1028        return Err(FinalCargoError::UnsupportedSnapshotExecutable {
1029            path: executable.to_path_buf(),
1030            reason: format!(
1031                "the {architecture:?} executable architecture does not match the current host architecture {host_architecture:?}"
1032            ),
1033        });
1034    }
1035    Ok(())
1036}
1037
1038fn executable_snapshot_dependencies(
1039    file: &object::File<'_>,
1040) -> Result<ExecutableSnapshotDependencies, String> {
1041    match file {
1042        object::File::Elf32(file) => elf_snapshot_dependencies(file),
1043        object::File::Elf64(file) => elf_snapshot_dependencies(file),
1044        object::File::MachO32(file) => macho_snapshot_dependencies(file),
1045        object::File::MachO64(file) => macho_snapshot_dependencies(file),
1046        object::File::Pe32(_) | object::File::Pe64(_) => Err(
1047            "PE launch snapshots are disabled until normal and delay-load import tables share one authoritative validator"
1048                .to_string(),
1049        ),
1050        _ => {
1051            let mut dependencies = ExecutableSnapshotDependencies::default();
1052            for import in file.imports().map_err(|error| error.to_string())? {
1053                if import.library().is_empty() {
1054                    return Err(
1055                        "an imported symbol has no authoritative library identity".to_string(),
1056                    );
1057                }
1058                dependencies.libraries.insert(import.library().to_vec());
1059            }
1060            Ok(dependencies)
1061        }
1062    }
1063}
1064
1065fn elf_snapshot_dependencies<'data, Elf>(
1066    file: &object::read::elf::ElfFile<'data, Elf>,
1067) -> Result<ExecutableSnapshotDependencies, String>
1068where
1069    Elf: object::read::elf::FileHeader,
1070{
1071    use object::read::elf::{Dyn as _, ProgramHeader as _};
1072
1073    let mut dependencies = ExecutableSnapshotDependencies::default();
1074    let endian = file.endian();
1075    let data = file.data();
1076    let mut has_dynamic_segment = false;
1077    for segment in file.elf_program_headers() {
1078        has_dynamic_segment |= segment.p_type(endian) == object::elf::PT_DYNAMIC;
1079        if let Some(interpreter) = segment
1080            .interpreter(endian, data)
1081            .map_err(|error| error.to_string())?
1082        {
1083            dependencies.interpreters.insert(interpreter.to_vec());
1084        }
1085    }
1086    let sections = file.elf_section_table();
1087    let Some((dynamic, strings_index)) = sections
1088        .dynamic(endian, data)
1089        .map_err(|error| error.to_string())?
1090    else {
1091        if has_dynamic_segment {
1092            return Err(
1093                "ELF has a PT_DYNAMIC segment but no authoritative SHT_DYNAMIC table".to_string(),
1094            );
1095        }
1096        return Ok(dependencies);
1097    };
1098    let strings = sections
1099        .strings(endian, data, strings_index)
1100        .map_err(|error| error.to_string())?;
1101    for entry in dynamic {
1102        match entry.tag32(endian) {
1103            Some(object::elf::DT_NEEDED) => {
1104                dependencies.libraries.insert(
1105                    entry
1106                        .string(endian, strings)
1107                        .map_err(|error| error.to_string())?
1108                        .to_vec(),
1109                );
1110            }
1111            Some(object::elf::DT_RPATH | object::elf::DT_RUNPATH) => {
1112                dependencies.loader_paths.insert(
1113                    entry
1114                        .string(endian, strings)
1115                        .map_err(|error| error.to_string())?
1116                        .to_vec(),
1117                );
1118            }
1119            _ => {}
1120        }
1121    }
1122    Ok(dependencies)
1123}
1124
1125fn macho_snapshot_dependencies<'data, Mach>(
1126    file: &object::read::macho::MachOFile<'data, Mach>,
1127) -> Result<ExecutableSnapshotDependencies, String>
1128where
1129    Mach: object::read::macho::MachHeader,
1130{
1131    let mut dependencies = ExecutableSnapshotDependencies::default();
1132    let endian = file.endian();
1133    let mut commands = file
1134        .macho_load_commands()
1135        .map_err(|error| error.to_string())?;
1136    while let Some(command) = commands.next().map_err(|error| error.to_string())? {
1137        match command.variant().map_err(|error| error.to_string())? {
1138            object::read::macho::LoadCommandVariant::Dylib(dylib) => {
1139                dependencies.libraries.insert(
1140                    command
1141                        .string(endian, dylib.dylib.name)
1142                        .map_err(|error| error.to_string())?
1143                        .to_vec(),
1144                );
1145            }
1146            object::read::macho::LoadCommandVariant::Rpath(rpath) => {
1147                dependencies.loader_paths.insert(
1148                    command
1149                        .string(endian, rpath.path)
1150                        .map_err(|error| error.to_string())?
1151                        .to_vec(),
1152                );
1153            }
1154            object::read::macho::LoadCommandVariant::LoadDylinker(dylinker) => {
1155                dependencies.interpreters.insert(
1156                    command
1157                        .string(endian, dylinker.name)
1158                        .map_err(|error| error.to_string())?
1159                        .to_vec(),
1160                );
1161            }
1162            object::read::macho::LoadCommandVariant::DyldEnvironment(environment) => {
1163                dependencies.loader_paths.insert(
1164                    command
1165                        .string(endian, environment.name)
1166                        .map_err(|error| error.to_string())?
1167                        .to_vec(),
1168                );
1169            }
1170            _ => {}
1171        }
1172    }
1173    Ok(dependencies)
1174}
1175
1176fn host_executable_format() -> BinaryFormat {
1177    #[cfg(target_os = "windows")]
1178    {
1179        BinaryFormat::Pe
1180    }
1181    #[cfg(target_os = "macos")]
1182    {
1183        BinaryFormat::MachO
1184    }
1185    #[cfg(not(any(target_os = "windows", target_os = "macos")))]
1186    {
1187        BinaryFormat::Elf
1188    }
1189}
1190
1191fn host_architecture() -> Option<Architecture> {
1192    match std::env::consts::ARCH {
1193        "aarch64" => Some(Architecture::Aarch64),
1194        "arm" => Some(Architecture::Arm),
1195        "loongarch64" => Some(Architecture::LoongArch64),
1196        "mips" => Some(Architecture::Mips),
1197        "mips64" => Some(Architecture::Mips64),
1198        "powerpc" => Some(Architecture::PowerPc),
1199        "powerpc64" => Some(Architecture::PowerPc64),
1200        "riscv32" => Some(Architecture::Riscv32),
1201        "riscv64" => Some(Architecture::Riscv64),
1202        "s390x" => Some(Architecture::S390x),
1203        "sparc64" => Some(Architecture::Sparc64),
1204        "x86" => Some(Architecture::I386),
1205        "x86_64" => Some(Architecture::X86_64),
1206        _ => None,
1207    }
1208}
1209
1210fn dependency_name(bytes: &[u8]) -> Option<&str> {
1211    std::str::from_utf8(bytes).ok()
1212}
1213
1214fn validate_snapshot_dependency(
1215    format: BinaryFormat,
1216    executable: &Path,
1217    target_directory: &Path,
1218    dependency: &str,
1219) -> Result<(), FinalCargoError> {
1220    if dependency.is_empty() {
1221        return Err(FinalCargoError::UnsupportedSnapshotExecutable {
1222            path: executable.to_path_buf(),
1223            reason: "an imported dynamic library has an empty identity".to_string(),
1224        });
1225    }
1226    if rust_dynamic_dependency(dependency) {
1227        return Err(FinalCargoError::UnsupportedSnapshotDependency {
1228            path: executable.to_path_buf(),
1229            dependency: dependency.to_string(),
1230            reason: "Rust dynamic libraries are not copied into immutable launch snapshots",
1231        });
1232    }
1233    if loader_path_is_relative(dependency) {
1234        return Err(FinalCargoError::UnsupportedSnapshotDependency {
1235            path: executable.to_path_buf(),
1236            dependency: dependency.to_string(),
1237            reason: "it is relative to the original executable or loader search path",
1238        });
1239    }
1240
1241    let dependency_path = Path::new(dependency);
1242    if dependency_path.is_absolute() {
1243        if dependency_path.starts_with(target_directory) {
1244            return Err(FinalCargoError::UnsupportedSnapshotDependency {
1245                path: executable.to_path_buf(),
1246                dependency: dependency.to_string(),
1247                reason: "it points into the mutable final Cargo target",
1248            });
1249        }
1250        if platform_system_dependency(format, dependency) {
1251            return Ok(());
1252        }
1253        return Err(FinalCargoError::UnsupportedSnapshotDependency {
1254            path: executable.to_path_buf(),
1255            dependency: dependency.to_string(),
1256            reason: "non-system absolute dynamic libraries are outside the snapshot contract",
1257        });
1258    }
1259
1260    if platform_system_dependency(format, dependency) {
1261        return Ok(());
1262    }
1263    Err(FinalCargoError::UnsupportedSnapshotDependency {
1264        path: executable.to_path_buf(),
1265        dependency: dependency.to_string(),
1266        reason: "non-system dynamic libraries are not copied into immutable launch snapshots",
1267    })
1268}
1269
1270fn validate_snapshot_interpreter(
1271    executable: &Path,
1272    target_directory: &Path,
1273    interpreter: &str,
1274) -> Result<(), FinalCargoError> {
1275    let interpreter_path = Path::new(interpreter);
1276    let reason = if !interpreter_path.is_absolute() {
1277        Some("the program interpreter or dynamic-loader path is relative")
1278    } else if interpreter_path.starts_with(target_directory) {
1279        Some("the program interpreter or dynamic loader points into the mutable final Cargo target")
1280    } else if !platform_system_interpreter(interpreter) {
1281        Some("the program interpreter or dynamic loader is outside the host system-loader contract")
1282    } else {
1283        None
1284    };
1285    if let Some(reason) = reason {
1286        return Err(FinalCargoError::UnsupportedSnapshotDependency {
1287            path: executable.to_path_buf(),
1288            dependency: interpreter.to_string(),
1289            reason,
1290        });
1291    }
1292    Ok(())
1293}
1294
1295fn platform_system_interpreter(interpreter: &str) -> bool {
1296    interpreter.starts_with("/lib/")
1297        || interpreter.starts_with("/lib64/")
1298        || interpreter.starts_with("/usr/lib/")
1299        || interpreter.starts_with("/usr/lib64/")
1300        || matches!(interpreter, "/system/bin/linker" | "/system/bin/linker64")
1301}
1302
1303fn loader_path_is_relative(path: &str) -> bool {
1304    path.starts_with('@')
1305        || path.contains("$ORIGIN")
1306        || path.contains("${ORIGIN}")
1307        || path.split(':').any(|entry| {
1308            entry.is_empty()
1309                || entry.starts_with('@')
1310                || entry.contains("$ORIGIN")
1311                || entry.contains("${ORIGIN}")
1312                || (entry.contains('/') && !Path::new(entry).is_absolute())
1313        })
1314}
1315
1316fn rust_dynamic_dependency(dependency: &str) -> bool {
1317    let name = dependency
1318        .rsplit(['/', '\\'])
1319        .next()
1320        .unwrap_or(dependency)
1321        .to_ascii_lowercase();
1322    [
1323        "libstd-",
1324        "std-",
1325        "libtest-",
1326        "test-",
1327        "libpanic_",
1328        "panic_",
1329        "librustc_",
1330        "rustc_",
1331    ]
1332    .iter()
1333    .any(|prefix| name.starts_with(prefix))
1334        && [".so", ".dylib", ".dll"]
1335            .iter()
1336            .any(|suffix| name.contains(suffix))
1337}
1338
1339fn platform_system_dependency(format: BinaryFormat, dependency: &str) -> bool {
1340    match format {
1341        BinaryFormat::MachO => {
1342            dependency.starts_with("/usr/lib/")
1343                || dependency.starts_with("/System/Library/")
1344                || dependency.starts_with("/System/DriverKit/")
1345        }
1346        BinaryFormat::Elf => matches!(
1347            dependency,
1348            "ld-linux-x86-64.so.2"
1349                | "libc.so"
1350                | "libc.so.6"
1351                | "libdl.so"
1352                | "libdl.so.2"
1353                | "libgcc_s.so.1"
1354                | "libm.so"
1355                | "libm.so.6"
1356                | "libpthread.so"
1357                | "libpthread.so.0"
1358                | "libresolv.so"
1359                | "libresolv.so.2"
1360                | "librt.so"
1361                | "librt.so.1"
1362                | "libthr.so.3"
1363                | "libutil.so"
1364                | "libutil.so.1"
1365                | "libutil.so.9"
1366        ),
1367        BinaryFormat::Pe => {
1368            let dependency = dependency.to_ascii_lowercase();
1369            dependency.starts_with("api-ms-win-")
1370                || dependency.starts_with("ext-ms-win-")
1371                || matches!(
1372                    dependency.as_str(),
1373                    "advapi32.dll"
1374                        | "bcrypt.dll"
1375                        | "crypt32.dll"
1376                        | "gdi32.dll"
1377                        | "iphlpapi.dll"
1378                        | "kernel32.dll"
1379                        | "ncrypt.dll"
1380                        | "ntdll.dll"
1381                        | "ole32.dll"
1382                        | "secur32.dll"
1383                        | "shell32.dll"
1384                        | "ucrtbase.dll"
1385                        | "user32.dll"
1386                        | "userenv.dll"
1387                        | "ws2_32.dll"
1388                )
1389        }
1390        _ => false,
1391    }
1392}
1393
1394fn snapshot_file_identity(path: &Path) -> Result<([u8; 32], String), FinalCargoError> {
1395    let metadata =
1396        fs::symlink_metadata(path).map_err(|source| FinalCargoError::SnapshotArtifactIo {
1397            path: path.to_path_buf(),
1398            source,
1399        })?;
1400    if !metadata.file_type().is_file() {
1401        return Err(FinalCargoError::SnapshotArtifactNotFile(path.to_path_buf()));
1402    }
1403    let mut file = File::open(path).map_err(|source| FinalCargoError::SnapshotArtifactIo {
1404        path: path.to_path_buf(),
1405        source,
1406    })?;
1407    let mut hash = Sha256::new();
1408    let mut buffer = [0_u8; 64 * 1024];
1409    loop {
1410        let read =
1411            file.read(&mut buffer)
1412                .map_err(|source| FinalCargoError::SnapshotArtifactIo {
1413                    path: path.to_path_buf(),
1414                    source,
1415                })?;
1416        if read == 0 {
1417            break;
1418        }
1419        hash.update(&buffer[..read]);
1420    }
1421    Ok((
1422        hash.finalize().into(),
1423        snapshot_permission_identity(&metadata.permissions()),
1424    ))
1425}
1426
1427fn hex_sha256(digest: &[u8; 32]) -> String {
1428    use std::fmt::Write as _;
1429
1430    let mut output = String::with_capacity(64);
1431    for byte in digest {
1432        let _ = write!(output, "{byte:02x}");
1433    }
1434    output
1435}
1436
1437#[cfg(unix)]
1438fn snapshot_permission_identity(permissions: &fs::Permissions) -> String {
1439    use std::os::unix::fs::PermissionsExt as _;
1440    format!("mode-{:o}", permissions.mode())
1441}
1442
1443#[cfg(not(unix))]
1444fn snapshot_permission_identity(permissions: &fs::Permissions) -> String {
1445    format!("readonly-{}", u8::from(permissions.readonly()))
1446}
1447
1448fn forward_rendered_cargo_diagnostic(line: &str) {
1449    let Ok(value) = serde_json::from_str::<Value>(line) else {
1450        return;
1451    };
1452    if value.get("reason").and_then(Value::as_str) != Some("compiler-message") {
1453        return;
1454    }
1455    if let Some(rendered) = value
1456        .get("message")
1457        .and_then(|message| message.get("rendered"))
1458        .and_then(Value::as_str)
1459    {
1460        eprint!("{rendered}");
1461    }
1462}
1463
1464/// Final-compilation validation or Cargo failure.
1465#[derive(Debug, Error)]
1466pub enum FinalCargoError {
1467    /// Managed outputs must remain beneath the generated-output boundary and
1468    /// may not traverse symlinks or special filesystem entries.
1469    #[error(transparent)]
1470    ManagedPath(#[from] ManagedPathError),
1471    /// Stable final targets are serialized through the shared target lease.
1472    #[error("failed to acquire the final Cargo target lease: {0}")]
1473    TargetLease(DescriptorCargoRunError),
1474    /// A selected final root path had no filename for snapshot publication.
1475    #[error("selected final Cargo artifact has no filename: `{0}`")]
1476    SnapshotArtifactWithoutFilename(PathBuf),
1477    /// Only plain regular files can become immutable launch artifacts.
1478    #[error("selected final Cargo artifact is not a plain regular file: `{0}`")]
1479    SnapshotArtifactNotFile(PathBuf),
1480    /// Immutable launch artifact publication or validation failed.
1481    #[error("failed to publish final Cargo artifact snapshot `{path}`: {source}")]
1482    SnapshotArtifactIo {
1483        /// Source, temporary, or destination path involved.
1484        path: PathBuf,
1485        /// Filesystem failure.
1486        #[source]
1487        source: io::Error,
1488    },
1489    /// A content-addressed snapshot path contained different bytes or mode.
1490    #[error("content-addressed final Cargo artifact conflicts with `{0}`")]
1491    ConflictingSnapshotArtifact(PathBuf),
1492    /// Executable parsing or host-format validation could not prove that a
1493    /// relocated snapshot remains directly launchable.
1494    #[error("final executable `{path}` cannot become an immutable launch snapshot: {reason}")]
1495    UnsupportedSnapshotExecutable {
1496        /// Exact temporary snapshot bytes that were inspected.
1497        path: PathBuf,
1498        /// Focused fail-closed reason.
1499        reason: String,
1500    },
1501    /// A runtime library or loader path would retain mutable or
1502    /// relocation-sensitive state outside the selected snapshot.
1503    #[error(
1504        "final executable `{path}` cannot become an immutable launch snapshot because dependency `{dependency}` is unsupported: {reason}"
1505    )]
1506    UnsupportedSnapshotDependency {
1507        /// Exact temporary snapshot bytes that were inspected.
1508        path: PathBuf,
1509        /// Imported library or loader-search path.
1510        dependency: String,
1511        /// Focused contract violation.
1512        reason: &'static str,
1513    },
1514    /// Wrapper path must be invocation-stable.
1515    #[error("final Cargo wrapper path must be absolute: `{0}`")]
1516    RelativeWrapper(PathBuf),
1517    /// Cargo cwd must be explicit.
1518    #[error("final Cargo working directory must be absolute: `{0}`")]
1519    RelativeWorkingDirectory(PathBuf),
1520    /// Cross-phase package-source exclusion must be exact.
1521    #[error("final Cargo source exclusion directory must be absolute: `{0}`")]
1522    RelativeSourceExclusionDirectory(PathBuf),
1523    /// Target root must be explicit.
1524    #[error("final Cargo target root must be absolute: `{0}`")]
1525    RelativeTargetRoot(PathBuf),
1526    /// Plan path must be exact.
1527    #[error("final RSJS plan path must be absolute: `{0}`")]
1528    RelativePlanPath(PathBuf),
1529    /// Cargo invocation is empty.
1530    #[error("final Cargo invocation has no arguments")]
1531    MissingCargoArguments,
1532    /// Only known compile-only rewrites are accepted by the final runner.
1533    #[error("final Cargo subcommand {0:?} is unsupported; expected build, check, run, or test")]
1534    UnsupportedCargoSubcommand(OsString),
1535    /// Runtime suffixes have no meaning for already compile-only subcommands.
1536    #[error("final Cargo subcommand {0:?} may not contain runtime arguments after `--`")]
1537    RuntimeArgumentsForCompileOnlySubcommand(OsString),
1538    /// Runner-owned Cargo argument was supplied.
1539    #[error("final Cargo argument `{0}` is reserved")]
1540    ReservedCargoArgument(String),
1541    /// Runner-owned environment was supplied.
1542    #[error("final Cargo environment `{0}` is reserved")]
1543    ReservedEnvironment(String),
1544    /// Proc-macro filesystem fallbacks are not part of exact build identity.
1545    #[error("final Cargo environment `{0}` is unsupported by the exact linked pipeline")]
1546    UnsupportedEnvironment(&'static str),
1547    /// Existing wrappers are not represented by the current identity model.
1548    #[error("RUSTC_WORKSPACE_WRAPPER is set; unset both Cargo rustc wrapper variables before invoking cargo-proa")]
1549    ExistingWorkspaceWrapper,
1550    /// An inherited wrapper is outside final-target/cache identity.
1551    #[error(
1552        "RUSTC_WRAPPER is set; unset it before invoking cargo-proa so final compilation cannot diverge from descriptor cache identity"
1553    )]
1554    ExistingRustcWrapper,
1555    /// Plan bytes could not be read.
1556    #[error("failed to read final RSJS plan `{path}`: {source}")]
1557    ReadPlan {
1558        /// Exact path.
1559        path: PathBuf,
1560        /// I/O error.
1561        #[source]
1562        source: io::Error,
1563    },
1564    /// Plan JSON is invalid.
1565    #[error("failed to parse final RSJS plan `{path}`: {source}")]
1566    ParsePlan {
1567        /// Exact path.
1568        path: PathBuf,
1569        /// JSON error.
1570        #[source]
1571        source: serde_json::Error,
1572    },
1573    /// Wrong external plan format.
1574    #[error("unsupported final RSJS plan format `{actual}`")]
1575    PlanFormat {
1576        /// Rejected format.
1577        actual: String,
1578    },
1579    /// File names another PlanId.
1580    #[error("final plan ID mismatch: expected {expected}, found `{actual}`")]
1581    PlanIdMismatch {
1582        /// Expected ID.
1583        expected: PlanId,
1584        /// File ID.
1585        actual: String,
1586    },
1587    /// File names another root graph.
1588    #[error("final link-unit ID mismatch: expected {expected}, found `{actual}`")]
1589    LinkUnitMismatch {
1590        /// Expected ID.
1591        expected: String,
1592        /// File ID.
1593        actual: String,
1594    },
1595    /// Content-addressed filename disagrees with PlanId.
1596    #[error("final plan `{path}` must be named `{expected}`")]
1597    PlanFilename {
1598        /// Actual path.
1599        path: PathBuf,
1600        /// Required filename.
1601        expected: String,
1602    },
1603    /// The exact file and in-memory plan disagree despite sharing their
1604    /// top-level identifiers.
1605    #[error("final RSJS plan file does not match the complete in-memory linked plan")]
1606    PlanContentMismatch,
1607    /// The in-memory plan could not be deterministically serialized for exact
1608    /// comparison.
1609    #[error("failed to serialize the expected final RSJS plan: {0}")]
1610    SerializeExpectedPlan(String),
1611    /// Descriptor-to-final identity map construction failed.
1612    #[error(transparent)]
1613    UnitMap(FinalUnitMapError),
1614    /// Plan path cannot enter rustc's environment.
1615    #[error("final plan path is not UTF-8: `{0}`")]
1616    NonUtf8PlanPath(PathBuf),
1617    /// Cargo spawn failed.
1618    #[error("failed to run final Cargo `{program}`: {source}")]
1619    SpawnCargo {
1620        /// Cargo program.
1621        program: PathBuf,
1622        /// I/O error.
1623        #[source]
1624        source: io::Error,
1625    },
1626    /// Cargo stdout pipe was unavailable.
1627    #[error("final Cargo process has no piped stdout")]
1628    MissingCargoStdout,
1629    /// Cargo stdout failed.
1630    #[error("failed to read final Cargo stdout: {0}")]
1631    ReadCargoStdout(io::Error),
1632    /// Cargo's compile-only machine-readable protocol must remain UTF-8.
1633    #[error("final Cargo protocol line {line} is not UTF-8: {source}")]
1634    NonUtf8CargoProtocol {
1635        /// One-based Cargo protocol line.
1636        line: usize,
1637        /// UTF-8 validation error.
1638        #[source]
1639        source: std::str::Utf8Error,
1640    },
1641    /// Cargo wait failed.
1642    #[error("failed to wait for final Cargo: {0}")]
1643    WaitForCargo(io::Error),
1644    /// Cargo compilation failed.
1645    #[error("final Cargo stopped after the compiler diagnostic above ({0})")]
1646    CargoFailed(ExitStatus),
1647    /// Cargo JSON protocol failed.
1648    #[error(transparent)]
1649    CargoProtocol(CargoMessageError),
1650    /// Successful Cargo invocation emitted no artifacts.
1651    #[error("final Cargo compilation emitted no artifacts")]
1652    NoCargoArtifacts,
1653}
1654
1655#[cfg(test)]
1656mod tests {
1657    use super::*;
1658    use rsjs_ir::abi::{InvocationId, LinkUnitId};
1659    use rsjs_ir::build::LinkPlanMaterial;
1660
1661    fn plan() -> TransportLinkPlan {
1662        let material = LinkPlanMaterial {
1663            link_unit: LinkUnitId::derive("final-link-unit"),
1664            component_descriptors: Vec::new(),
1665            helper_descriptors: Vec::new(),
1666            payload: SemanticHash::derive("empty-final-payload"),
1667        };
1668        TransportLinkPlan {
1669            link_unit: material.link_unit,
1670            plan_id: material.plan_id(),
1671            material,
1672            components: Vec::new(),
1673            helpers: Vec::new(),
1674            shared_state_definitions: Vec::new(),
1675            shared_state_acquisitions: Vec::new(),
1676        }
1677    }
1678
1679    #[test]
1680    fn plan_environment_preserves_inherited_rustflags_byte_for_byte() {
1681        let plan = plan();
1682        let request = FinalCargoRequest {
1683            invocation: InvocationId::derive("fixture-final-cargo-request"),
1684            cargo: OsString::from("cargo"),
1685            wrapper: PathBuf::from("/fixture/cargo-proa"),
1686            working_directory: PathBuf::from("/fixture"),
1687            source_exclusion_directory: PathBuf::from("/fixture/target"),
1688            target_root: PathBuf::from("/fixture/target"),
1689            plan_path: PathBuf::from("/fixture/plan.json"),
1690            cargo_args: vec![OsString::from("build")],
1691            environment: BTreeMap::new(),
1692            root_unit_fingerprint: SemanticHash::derive("fixture"),
1693            descriptor_units: Vec::new(),
1694        };
1695        let plain = OsString::from("--cfg custom_cfg -C opt-level=1");
1696        let encoded = OsString::from("-Copt-level=2\u{1f}-Ctarget-cpu=native");
1697        let mut environment = BTreeMap::from([
1698            (OsString::from("RUSTFLAGS"), plain.clone()),
1699            (OsString::from("CARGO_ENCODED_RUSTFLAGS"), encoded.clone()),
1700        ]);
1701
1702        inject_plan_environment(
1703            &mut environment,
1704            &request,
1705            &plan,
1706            &format!("sha256:{}", "1".repeat(64)),
1707            Path::new("/fixture/unit-map.json"),
1708            &"2".repeat(64),
1709        )
1710        .unwrap();
1711
1712        assert_eq!(environment.get(OsStr::new("RUSTFLAGS")), Some(&plain));
1713        assert_eq!(
1714            environment.get(OsStr::new("CARGO_ENCODED_RUSTFLAGS")),
1715            Some(&encoded)
1716        );
1717    }
1718
1719    #[test]
1720    fn final_target_is_stable_within_one_wrapper_policy() {
1721        let root = Path::new("/fixture/final-target-root");
1722        let invocation = InvocationId::derive("stable-final-target");
1723        assert_eq!(
1724            final_target_directory(root, invocation),
1725            Path::new("/fixture/final-target-root")
1726                .join("rsjs-final")
1727                .join(format!("wrapper-v{FINAL_WRAPPER_POLICY_VERSION}"))
1728                .join(invocation.to_string())
1729        );
1730    }
1731
1732    #[test]
1733    fn snapshot_final_artifact_preserves_immutable_generations() {
1734        let temp = tempfile::TempDir::new().unwrap();
1735        let source_exclusion = temp.path().join("generated");
1736        let target_directory = source_exclusion.join("reusable-target");
1737        let snapshot_root = source_exclusion.join("snapshots");
1738        fs::create_dir_all(&target_directory).unwrap();
1739
1740        let source = target_directory.join("fixture-artifact");
1741        fs::write(&source, b"artifact-a\n").unwrap();
1742        #[cfg(unix)]
1743        {
1744            use std::os::unix::fs::PermissionsExt as _;
1745            fs::set_permissions(&source, fs::Permissions::from_mode(0o751)).unwrap();
1746        }
1747
1748        let artifact = CargoCompilerArtifact {
1749            package_id: "path+file:///fixture#snapshot_fixture@0.0.0".to_string(),
1750            manifest_path: temp.path().join("Cargo.toml"),
1751            target: CargoArtifactTarget {
1752                name: "snapshot_fixture".to_string(),
1753                kind: BTreeSet::from(["rlib".to_string()]),
1754                crate_types: BTreeSet::from(["rlib".to_string()]),
1755                src_path: temp.path().join("src/main.rs"),
1756                edition: "2021".to_string(),
1757            },
1758            profile: serde_json::json!({"opt_level":"0","test":false}),
1759            features: BTreeSet::new(),
1760            filenames: BTreeSet::from([source.clone()]),
1761            executable: None,
1762            fresh: false,
1763        };
1764
1765        let snapshot_a = snapshot_final_artifact(
1766            &source_exclusion,
1767            &snapshot_root,
1768            &target_directory,
1769            &artifact,
1770        )
1771        .unwrap();
1772        let path_a = snapshot_a.filenames.iter().next().unwrap();
1773        assert_eq!(fs::read(path_a).unwrap(), b"artifact-a\n");
1774
1775        fs::write(&source, b"artifact-b\n").unwrap();
1776        let snapshot_b = snapshot_final_artifact(
1777            &source_exclusion,
1778            &snapshot_root,
1779            &target_directory,
1780            &artifact,
1781        )
1782        .unwrap();
1783        let path_b = snapshot_b.filenames.iter().next().unwrap();
1784        assert_ne!(path_a, path_b);
1785        assert_eq!(fs::read(path_a).unwrap(), b"artifact-a\n");
1786        assert_eq!(fs::read(path_b).unwrap(), b"artifact-b\n");
1787
1788        let snapshot_b_again = snapshot_final_artifact(
1789            &source_exclusion,
1790            &snapshot_root,
1791            &target_directory,
1792            &artifact,
1793        )
1794        .unwrap();
1795        assert_eq!(snapshot_b_again.filenames, snapshot_b.filenames);
1796
1797        #[cfg(unix)]
1798        {
1799            use std::os::unix::fs::PermissionsExt as _;
1800            assert_eq!(
1801                fs::metadata(path_a).unwrap().permissions().mode() & 0o777,
1802                0o751
1803            );
1804            assert_eq!(
1805                fs::metadata(path_b).unwrap().permissions().mode() & 0o777,
1806                0o751
1807            );
1808        }
1809    }
1810
1811    #[cfg(not(target_os = "windows"))]
1812    #[test]
1813    fn ordinary_host_executable_can_be_snapshotted() {
1814        let temp = tempfile::TempDir::new().unwrap();
1815        let source_exclusion = temp.path().join("generated");
1816        let target_directory = source_exclusion.join("reusable-target");
1817        let snapshot_root = source_exclusion.join("snapshots");
1818        fs::create_dir_all(&target_directory).unwrap();
1819        let executable = compile_snapshot_fixture(&target_directory, false);
1820        let artifact = snapshot_fixture_artifact(temp.path(), executable.clone());
1821
1822        let snapshot = snapshot_final_artifact(
1823            &source_exclusion,
1824            &snapshot_root,
1825            &target_directory,
1826            &artifact,
1827        )
1828        .unwrap();
1829        let published = snapshot.executable.unwrap();
1830        assert_ne!(published, executable);
1831        assert!(published.is_file());
1832    }
1833
1834    #[cfg(not(target_os = "windows"))]
1835    #[test]
1836    fn dynamic_rust_executable_is_rejected_before_snapshot_publication() {
1837        let temp = tempfile::TempDir::new().unwrap();
1838        let source_exclusion = temp.path().join("generated");
1839        let target_directory = source_exclusion.join("reusable-target");
1840        let snapshot_root = source_exclusion.join("snapshots");
1841        fs::create_dir_all(&target_directory).unwrap();
1842        let executable = compile_snapshot_fixture(&target_directory, true);
1843        let artifact = snapshot_fixture_artifact(temp.path(), executable);
1844
1845        let error = snapshot_final_artifact(
1846            &source_exclusion,
1847            &snapshot_root,
1848            &target_directory,
1849            &artifact,
1850        )
1851        .unwrap_err();
1852        assert!(matches!(
1853            error,
1854            FinalCargoError::UnsupportedSnapshotDependency {
1855                dependency,
1856                reason,
1857                ..
1858            } if dependency.to_ascii_lowercase().contains("libstd")
1859                || reason.contains("relative loader search path")
1860        ));
1861        assert_eq!(fs::read_dir(&snapshot_root).unwrap().count(), 0);
1862    }
1863
1864    #[test]
1865    fn relative_loader_dependency_is_rejected_explicitly() {
1866        let executable = Path::new("/fixture/target/app");
1867        let target = Path::new("/fixture/target");
1868        assert!(matches!(
1869            validate_snapshot_dependency(
1870                BinaryFormat::MachO,
1871                executable,
1872                target,
1873                "@rpath/libfixture.dylib",
1874            ),
1875            Err(FinalCargoError::UnsupportedSnapshotDependency {
1876                dependency,
1877                reason,
1878                ..
1879            }) if dependency == "@rpath/libfixture.dylib" && reason.contains("relative")
1880        ));
1881    }
1882
1883    #[test]
1884    fn elf_system_loader_soname_is_an_allowed_runtime_dependency() {
1885        assert!(validate_snapshot_dependency(
1886            BinaryFormat::Elf,
1887            Path::new("/fixture/target/app"),
1888            Path::new("/fixture/target"),
1889            "ld-linux-x86-64.so.2",
1890        )
1891        .is_ok());
1892    }
1893
1894    #[test]
1895    fn executable_architecture_must_match_the_host() {
1896        let host = host_architecture().expect("the test host must have a supported architecture");
1897        let mismatch = if host == Architecture::X86_64 {
1898            Architecture::Aarch64
1899        } else {
1900            Architecture::X86_64
1901        };
1902        assert!(matches!(
1903            validate_snapshot_host_identity(
1904                Path::new("/fixture/target/app"),
1905                host_executable_format(),
1906                mismatch,
1907            ),
1908            Err(FinalCargoError::UnsupportedSnapshotExecutable { reason, .. })
1909                if reason.contains("does not match the current host architecture")
1910        ));
1911    }
1912
1913    #[test]
1914    fn interpreter_inside_mutable_target_is_rejected() {
1915        let executable = Path::new("/fixture/target/app");
1916        let target = Path::new("/fixture/target");
1917        assert!(matches!(
1918            validate_snapshot_interpreter(executable, target, "/fixture/target/ld.so"),
1919            Err(FinalCargoError::UnsupportedSnapshotDependency {
1920                dependency,
1921                reason,
1922                ..
1923            }) if dependency == "/fixture/target/ld.so" && reason.contains("mutable final Cargo target")
1924        ));
1925    }
1926
1927    #[cfg(not(target_os = "windows"))]
1928    fn compile_snapshot_fixture(target_directory: &Path, prefer_dynamic: bool) -> PathBuf {
1929        let source = target_directory.join(if prefer_dynamic {
1930            "dynamic-fixture.rs"
1931        } else {
1932            "static-fixture.rs"
1933        });
1934        fs::write(&source, "fn main() {}\n").unwrap();
1935        let executable = target_directory.join(if prefer_dynamic {
1936            "dynamic-fixture"
1937        } else {
1938            "static-fixture"
1939        });
1940        let rustc = std::env::var_os("RUSTC").unwrap_or_else(|| OsString::from("rustc"));
1941        let mut command = Command::new(rustc);
1942        command.arg(&source).arg("-o").arg(&executable);
1943        if prefer_dynamic {
1944            command.arg("-Cprefer-dynamic");
1945        }
1946        let status = command.status().unwrap();
1947        assert!(status.success(), "fixture rustc failed with {status}");
1948        executable
1949    }
1950
1951    fn snapshot_fixture_artifact(root: &Path, executable: PathBuf) -> CargoCompilerArtifact {
1952        CargoCompilerArtifact {
1953            package_id: "path+file:///fixture#snapshot_fixture@0.0.0".to_string(),
1954            manifest_path: root.join("Cargo.toml"),
1955            target: CargoArtifactTarget {
1956                name: "snapshot_fixture".to_string(),
1957                kind: BTreeSet::from(["bin".to_string()]),
1958                crate_types: BTreeSet::from(["bin".to_string()]),
1959                src_path: root.join("src/main.rs"),
1960                edition: "2021".to_string(),
1961            },
1962            profile: serde_json::json!({"opt_level":"0","test":false}),
1963            features: BTreeSet::new(),
1964            filenames: BTreeSet::from([executable.clone()]),
1965            executable: Some(executable),
1966            fresh: false,
1967        }
1968    }
1969
1970    #[test]
1971    fn final_cargo_rewrites_execution_requests_to_compile_only_arguments() {
1972        let arguments = vec![
1973            OsString::from("test"),
1974            OsString::from("-p"),
1975            OsString::from("demo"),
1976            OsString::from("--test"),
1977            OsString::from("http"),
1978            OsString::from("--"),
1979            OsString::from("--nocapture"),
1980            OsString::from("--target-dir"),
1981        ];
1982        assert_eq!(
1983            compile_only_cargo_arguments(&arguments).unwrap(),
1984            [
1985                OsString::from("test"),
1986                OsString::from("-p"),
1987                OsString::from("demo"),
1988                OsString::from("--test"),
1989                OsString::from("http"),
1990                OsString::from("--no-run"),
1991            ]
1992        );
1993        assert_eq!(
1994            compile_only_cargo_arguments(
1995                &["run", "-p", "demo", "--bin", "server", "--", "--probe",].map(OsString::from)
1996            )
1997            .unwrap(),
1998            [
1999                OsString::from("build"),
2000                OsString::from("-p"),
2001                OsString::from("demo"),
2002                OsString::from("--bin"),
2003                OsString::from("server"),
2004            ]
2005        );
2006        assert!(matches!(
2007            compile_only_cargo_arguments(&["build", "--", "ignored"].map(OsString::from)),
2008            Err(FinalCargoError::RuntimeArgumentsForCompileOnlySubcommand(subcommand))
2009                if subcommand == OsStr::new("build")
2010        ));
2011    }
2012
2013    #[test]
2014    fn final_unit_identity_changes_with_the_plan() {
2015        let fingerprint = SemanticHash::derive("root-unit");
2016        let first = FinalUnitId::for_plan(fingerprint, plan().plan_id);
2017        let second = FinalUnitId::for_plan(
2018            fingerprint,
2019            PlanId::derive(&InvocationId::derive("other-plan")),
2020        );
2021        assert_ne!(first, second);
2022    }
2023
2024    #[test]
2025    fn managed_final_paths_must_remain_beneath_source_exclusion() {
2026        let temp = tempfile::TempDir::new().unwrap();
2027        let exclusion = temp.path().join("generated");
2028        let outside = temp.path().join("outside/final");
2029
2030        assert!(matches!(
2031            ensure_plain_managed_directory(&exclusion, &outside),
2032            Err(ManagedPathError::OutsideSourceExclusion { .. })
2033        ));
2034    }
2035
2036    #[cfg(unix)]
2037    #[test]
2038    fn managed_final_paths_reject_symlinked_directories_and_plan_files() {
2039        use std::os::unix::fs::symlink;
2040
2041        let temp = tempfile::TempDir::new().unwrap();
2042        let exclusion = temp.path().join("generated");
2043        let outside = temp.path().join("outside");
2044        fs::create_dir_all(&outside).unwrap();
2045        ensure_plain_managed_directory(&exclusion, &exclusion).unwrap();
2046
2047        let redirected_target = exclusion.join("final-target");
2048        symlink(&outside, &redirected_target).unwrap();
2049        assert!(matches!(
2050            ensure_plain_managed_directory(&exclusion, &redirected_target),
2051            Err(ManagedPathError::NonDirectory(path)) if path == redirected_target
2052        ));
2053
2054        let plans = exclusion.join("plans");
2055        ensure_plain_managed_directory(&exclusion, &plans).unwrap();
2056        let real_plan = outside.join("plan.json");
2057        fs::write(&real_plan, b"{}").unwrap();
2058        let redirected_plan = plans.join("plan.json");
2059        symlink(&real_plan, &redirected_plan).unwrap();
2060        assert!(matches!(
2061            ensure_plain_managed_file(&exclusion, &redirected_plan),
2062            Err(ManagedPathError::NonFile(path)) if path == redirected_plan
2063        ));
2064    }
2065
2066    #[test]
2067    fn same_ids_cannot_authorize_different_plan_content() {
2068        let plan = plan();
2069        let temp = tempfile::TempDir::new().unwrap();
2070        let path = temp
2071            .path()
2072            .join(format!("{}.transport-plan.json", plan.plan_id));
2073        let mut value = transport_plan_json(&plan);
2074        value["payload_hash"] = Value::String(format!("sha256:{}", "ff".repeat(32)));
2075        fs::write(&path, serde_json::to_vec_pretty(&value).unwrap()).unwrap();
2076
2077        assert!(matches!(
2078            validate_plan_file(&path, &plan),
2079            Err(FinalCargoError::PlanContentMismatch)
2080        ));
2081    }
2082}