Skip to main content

runner_manager_agent/
oci.rs

1//! Rootless Podman-compatible provider for dependency-isolated Linux runners.
2//! The runtime is installed by the operator; this adapter never starts a native
3//! runner for an isolated policy and never grants a host filesystem mount.
4
5use std::collections::BTreeMap;
6use std::io::Write;
7use std::path::{Path, PathBuf};
8use std::process::{Child, Command, Stdio};
9use std::sync::Mutex;
10
11use runner_manager_domain::attempt::{FailureReason, IsolationProviderFailure, RunnerAttempt};
12use runner_manager_domain::execution::{
13    AttemptExecution, Backend, ExecutionPolicy, ImageReference,
14};
15use runner_manager_domain::model::{AttemptId, HostId};
16use runner_manager_domain::policy::ScalePolicy;
17use runner_manager_github::jit::EncodedJitConfig;
18
19use crate::lifecycle::{
20    EnvironmentIdentity, EnvironmentState, ExecutionProvider, NativeProcesses, OneTimeJitHandoff,
21    PreparedEnvironment, ProcessStartFailure, ProviderCapability, ProviderDestroy, ProviderStop,
22    ResolvedEnvironment,
23};
24
25const HOST_LABEL: &str = "io.runner-manager.host";
26const ATTEMPT_LABEL: &str = "io.runner-manager.attempt";
27const GENERATION_LABEL: &str = "io.runner-manager.generation";
28const IMAGE_LABEL: &str = "io.runner-manager.image";
29const BOOTSTRAP: &str = "IFS= read -r jit || exit 43; export ACTIONS_RUNNER_INPUT_JITCONFIG=\"$jit\"; unset jit; cd /runner || exit 44; exec ./bin/Runner.Listener run";
30const OCI_RUNTIME_ENV: &str = "RUNNER_MANAGER_OCI_RUNTIME";
31const BOUNDED_STORAGE_SCHEMA: u64 = 1;
32const BOUNDED_STORAGE_MODE: &str = "exclusive-filesystem-pool";
33const QUOTA_PROBE_MIB: u64 = 1024;
34
35/// The Podman service socket a rootful engine listens on.
36pub const ROOTFUL_SOCKET: &str = "/run/podman/podman.sock";
37
38/// How many host ids each isolated container's user namespace gets with a
39/// rootful engine: enough for any image's accounts, and 32768 containers in
40/// the conventional `containers` subordinate range.
41const AUTO_USERNS_SIZE: u64 = 65536;
42
43/// The operator's isolation settings, in `config/isolation.json`.
44#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
45#[serde(default, deny_unknown_fields)]
46pub struct IsolationSettings {
47    /// Whether an isolated job must have a hard writable-layer quota. Only
48    /// XFS with project quotas, or an attested bounded-storage helper, can
49    /// enforce one; elsewhere `false` lets isolated jobs run without it, so a
50    /// job can fill the engine's storage.
51    pub disk_quota_required: bool,
52}
53
54impl Default for IsolationSettings {
55    fn default() -> Self {
56        Self {
57            disk_quota_required: true,
58        }
59    }
60}
61
62impl IsolationSettings {
63    /// The file in the configuration directory.
64    pub const FILE: &'static str = "isolation.json";
65
66    /// The settings in `config_dir`, or the defaults when there are none.
67    ///
68    /// # Errors
69    ///
70    /// When the file cannot be read or does not parse.
71    pub fn load(config_dir: &Path) -> std::io::Result<Self> {
72        runner_manager_platform::settings_file::load(&config_dir.join(Self::FILE))
73    }
74
75    /// Writes the settings into `config_dir`.
76    ///
77    /// # Errors
78    ///
79    /// When the file cannot be written.
80    pub fn save(&self, config_dir: &Path) -> std::io::Result<()> {
81        runner_manager_platform::settings_file::save(&config_dir.join(Self::FILE), self)
82    }
83}
84
85/// How the provider reaches Podman.
86#[derive(Debug, Clone, PartialEq, Eq)]
87pub enum Engine {
88    /// Podman run by this process's own unprivileged account.
89    Rootless,
90    /// The system's rootful Podman service, reached as a client through its
91    /// socket. A Linux boot service runs this way: its sandbox forbids the
92    /// namespaces rootless Podman creates, and every container instead gets a
93    /// user namespace of its own (`--userns=auto`), so its root is an
94    /// unprivileged host id no other container shares.
95    Rootful(PathBuf),
96}
97
98#[derive(Debug)]
99pub struct OciProcesses {
100    host: HostId,
101    native: NativeProcesses,
102    runtime: String,
103    runtime_configuration_valid: bool,
104    engine: Engine,
105    /// Whether an isolated job must have a hard writable-layer quota.
106    disk_quota_required: bool,
107    /// Where a rootful engine's subordinate id ranges are read from.
108    subordinate_ids: [PathBuf; 2],
109    attached: Mutex<BTreeMap<AttemptId, Child>>,
110}
111
112impl OciProcesses {
113    #[must_use]
114    pub fn new(host: HostId) -> Self {
115        let (runtime, runtime_configuration_valid) = match std::env::var(OCI_RUNTIME_ENV) {
116            Ok(runtime) if operator_runtime_is_trusted(Path::new(&runtime)) => (runtime, true),
117            Ok(_) => ("/runner-manager-invalid-oci-runtime".into(), false),
118            Err(std::env::VarError::NotPresent) => ("podman".into(), true),
119            Err(std::env::VarError::NotUnicode(_)) => {
120                ("/runner-manager-invalid-oci-runtime".into(), false)
121            }
122        };
123        Self {
124            host,
125            native: NativeProcesses::new(),
126            runtime,
127            runtime_configuration_valid,
128            engine: Self::engine_for_this_process(),
129            disk_quota_required: true,
130            subordinate_ids: [PathBuf::from("/etc/subuid"), PathBuf::from("/etc/subgid")],
131            attached: Mutex::new(BTreeMap::new()),
132        }
133    }
134
135    /// The engine this process reaches: the rootful service for `root` on
136    /// Linux, rootless Podman for anyone else.
137    #[must_use]
138    pub fn engine_for_this_process() -> Engine {
139        #[cfg(target_os = "linux")]
140        if runner_manager_platform::host_fitness::is_elevated() {
141            return Engine::Rootful(PathBuf::from(ROOTFUL_SOCKET));
142        }
143        Engine::Rootless
144    }
145
146    /// Applies `settings`.
147    pub fn apply(&mut self, settings: IsolationSettings) {
148        self.disk_quota_required = settings.disk_quota_required;
149    }
150
151    /// Whether this host can run isolated jobs at all, before any image.
152    #[must_use]
153    pub fn host_capability(&self) -> ProviderCapability {
154        self.ready()
155    }
156
157    fn command(&self) -> Command {
158        let mut command = Command::new(&self.runtime);
159        if let Engine::Rootful(socket) = &self.engine {
160            command
161                .arg("--remote")
162                .arg("--url")
163                .arg(format!("unix://{}", socket.display()));
164        }
165        command.stdin(Stdio::null()).stderr(Stdio::null());
166        command
167    }
168
169    fn output(&self, args: &[&str]) -> Result<String, FailureReason> {
170        let output = self
171            .command()
172            .args(args)
173            .output()
174            .map_err(|_| provider_failure())?;
175        if !output.status.success() || output.stdout.len() > 64 * 1024 {
176            return Err(provider_failure());
177        }
178        String::from_utf8(output.stdout).map_err(|_| provider_failure())
179    }
180
181    fn status(&self, args: &[&str]) -> Result<(), FailureReason> {
182        let status = self
183            .command()
184            .args(args)
185            .stdout(Stdio::null())
186            .status()
187            .map_err(|_| provider_failure())?;
188        if status.success() {
189            Ok(())
190        } else {
191            Err(provider_failure())
192        }
193    }
194
195    fn ready(&self) -> ProviderCapability {
196        self.ready_for(QUOTA_PROBE_MIB)
197    }
198
199    fn ready_for(&self, requested_mib: u64) -> ProviderCapability {
200        self.readiness(requested_mib)
201            .err()
202            .unwrap_or(ProviderCapability::Ready)
203    }
204
205    /// Whether a `requested_mib` writable-layer quota is enforced for isolated
206    /// jobs, or why they cannot run.
207    fn readiness(&self, requested_mib: u64) -> Result<bool, ProviderCapability> {
208        if !cfg!(target_os = "linux") {
209            return Err(ProviderCapability::Unsupported);
210        }
211        if !self.runtime_configuration_valid {
212            return Err(ProviderCapability::PermissionDenied);
213        }
214        let info = match self.command().args(["info", "--format=json"]).output() {
215            Ok(output) if output.status.success() && output.stdout.len() <= 64 * 1024 => {
216                match String::from_utf8(output.stdout) {
217                    Ok(info) => info,
218                    Err(_) => return Err(ProviderCapability::Degraded),
219                }
220            }
221            Ok(_) => return Err(ProviderCapability::PermissionDenied),
222            Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
223                return Err(ProviderCapability::NotInstalled);
224            }
225            Err(_) => return Err(ProviderCapability::Degraded),
226        };
227        let Ok(info) = serde_json::from_str::<serde_json::Value>(&info) else {
228            return Err(ProviderCapability::Degraded);
229        };
230        let rootless = info
231            .pointer("/host/security/rootless")
232            .and_then(serde_json::Value::as_bool);
233        let rootful = matches!(self.engine, Engine::Rootful(_));
234        if rootless != Some(!rootful) {
235            return Err(ProviderCapability::PermissionDenied);
236        }
237        if rootful && !rootful_ranges_sufficient(&self.subordinate_ids) {
238            return Err(ProviderCapability::PermissionDenied);
239        }
240        let mappings = ["/host/idMappings/uidmap", "/host/idMappings/gidmap"];
241        if !rootful
242            && mappings.iter().any(|path| {
243                info.pointer(path)
244                    .and_then(serde_json::Value::as_array)
245                    .is_none_or(|ranges| {
246                        !ranges.iter().any(|range| {
247                            range
248                                .get("size")
249                                .and_then(serde_json::Value::as_u64)
250                                .is_some_and(|size| size >= 65536)
251                        })
252                    })
253            })
254        {
255            return Err(ProviderCapability::PermissionDenied);
256        }
257        if info
258            .pointer("/host/cgroupVersion")
259            .and_then(serde_json::Value::as_str)
260            != Some("v2")
261        {
262            return Err(ProviderCapability::Degraded);
263        }
264        let Some(controllers) = info
265            .pointer("/host/cgroupControllers")
266            .and_then(serde_json::Value::as_array)
267        else {
268            return Err(ProviderCapability::Degraded);
269        };
270        if ["cpu", "memory", "pids"].iter().any(|needed| {
271            !controllers
272                .iter()
273                .any(|controller| controller.as_str() == Some(needed))
274        }) {
275            return Err(ProviderCapability::Degraded);
276        }
277        let Some(graph_root) = info
278            .pointer("/store/graphRoot")
279            .and_then(serde_json::Value::as_str)
280        else {
281            return Err(ProviderCapability::Degraded);
282        };
283        let Some(run_root) = info
284            .pointer("/store/runRoot")
285            .and_then(serde_json::Value::as_str)
286        else {
287            return Err(ProviderCapability::Degraded);
288        };
289        if !graph_root.starts_with('/')
290            || !run_root.starts_with('/')
291            || graph_root.starts_with("/mnt/")
292            || run_root.starts_with("/mnt/")
293        {
294            return Err(ProviderCapability::PermissionDenied);
295        }
296        let backing_filesystem = info
297            .pointer("/store/graphStatus/Backing Filesystem")
298            .and_then(serde_json::Value::as_str);
299        let storage_size = format!("size={requested_mib}m");
300        let without_quota = if self.disk_quota_required {
301            Err(ProviderCapability::DiskQuotaUnavailable)
302        } else {
303            Ok(false)
304        };
305        let quota_probe =
306            match self.output(&["--storage-opt", &storage_size, "info", "--format=json"]) {
307                Ok(output) => output,
308                Err(_) => return without_quota,
309            };
310        // Native Podman writable-layer quotas require XFS project quotas. XFS
311        // alone is insufficient: rootless quota setup can still fail with
312        // EPERM, which the command above catches before allocation or JIT.
313        if backing_filesystem == Some("xfs") {
314            return Ok(true);
315        }
316        // Managed WSL can instead use an operator-provisioned runtime helper.
317        // The helper routes every `size=...` create into an exclusive finite
318        // filesystem and attests that contract in the quota-probe response.
319        // Plain Podman on extfs has no attestation and remains fail-closed.
320        let Ok(quota_info) = serde_json::from_str::<serde_json::Value>(&quota_probe) else {
321            return without_quota;
322        };
323        if bounded_storage_attested(&quota_info, graph_root, run_root, requested_mib) {
324            Ok(true)
325        } else {
326            without_quota
327        }
328    }
329
330    fn capability_or(&self, fallback: FailureReason) -> FailureReason {
331        let capability = self.ready();
332        if capability == ProviderCapability::Ready {
333            fallback
334        } else {
335            capability.refusal()
336        }
337    }
338
339    fn image_ready(&self, image: &ImageReference) -> Result<(), FailureReason> {
340        let Some((_, expected)) = image.as_str().rsplit_once("@sha256:") else {
341            return Err(image_failure());
342        };
343        self.status(&["pull", "--quiet", image.as_str()])
344            .map_err(|_| self.capability_or(image_failure()))?;
345        let digests = self
346            .output(&[
347                "image",
348                "inspect",
349                "--format",
350                "{{json .RepoDigests}}",
351                image.as_str(),
352            ])
353            .map_err(|_| self.capability_or(image_failure()))?;
354        let values: Vec<String> =
355            serde_json::from_str(digests.trim()).map_err(|_| image_failure())?;
356        if !values
357            .iter()
358            .any(|value| value.ends_with(&format!("@sha256:{expected}")))
359        {
360            return Err(image_failure());
361        }
362        Ok(())
363    }
364
365    fn isolated_identity(
366        &self,
367        attempt: &RunnerAttempt,
368        id: String,
369    ) -> Result<EnvironmentIdentity, FailureReason> {
370        let AttemptExecution::Isolated {
371            provider_kind: Backend::Oci,
372            resolved_image,
373            generation,
374            ..
375        } = attempt.execution()
376        else {
377            return Err(ownership_failure());
378        };
379        Ok(EnvironmentIdentity::Isolated {
380            host: self.host,
381            attempt: attempt.id,
382            provider_kind: Backend::Oci,
383            environment_id: id,
384            resolved_image: resolved_image.clone(),
385            generation: generation.clone(),
386        })
387    }
388
389    fn environment_id<'a>(&self, attempt: &'a RunnerAttempt) -> Result<&'a str, FailureReason> {
390        let AttemptExecution::Isolated {
391            provider_kind: Backend::Oci,
392            environment_id: Some(id),
393            ..
394        } = attempt.execution()
395        else {
396            return Err(ownership_failure());
397        };
398        Ok(id)
399    }
400
401    fn labels(&self, id: &str) -> Result<BTreeMap<String, String>, FailureReason> {
402        let labels = self.output(&[
403            "container",
404            "inspect",
405            "--format",
406            "{{json .Config.Labels}}",
407            id,
408        ])?;
409        serde_json::from_str(labels.trim()).map_err(|_| ownership_failure())
410    }
411
412    fn exists(&self, id: &str) -> Result<bool, FailureReason> {
413        let status = self
414            .command()
415            .args(["container", "exists", id])
416            .stdout(Stdio::null())
417            .status()
418            .map_err(|_| provider_failure())?;
419        match status.code() {
420            Some(0) => Ok(true),
421            Some(1) => Ok(false),
422            _ => Err(provider_failure()),
423        }
424    }
425
426    fn check_ownership(&self, attempt: &RunnerAttempt) -> Result<bool, FailureReason> {
427        let id = self.environment_id(attempt)?;
428        let labels = self.labels(id)?;
429        let AttemptExecution::Isolated { resolved_image, .. } = attempt.execution() else {
430            return Err(ownership_failure());
431        };
432        Ok(self.matches_attempt_labels(&labels, attempt)
433            && labels
434                .get(IMAGE_LABEL)
435                .is_some_and(|value| value == resolved_image.as_str()))
436    }
437
438    fn matches_attempt_labels(
439        &self,
440        labels: &BTreeMap<String, String>,
441        attempt: &RunnerAttempt,
442    ) -> bool {
443        let AttemptExecution::Isolated { generation, .. } = attempt.execution() else {
444            return false;
445        };
446        labels.get(HOST_LABEL) == Some(&self.host.to_string())
447            && labels.get(ATTEMPT_LABEL) == Some(&attempt.id.to_string())
448            && labels.get(GENERATION_LABEL) == Some(generation)
449    }
450
451    fn state(&self, attempt: &RunnerAttempt) -> Result<EnvironmentState, FailureReason> {
452        if !self.exists(self.environment_id(attempt)?)? {
453            return Ok(EnvironmentState::Missing);
454        }
455        if !self.check_ownership(attempt)? {
456            return Err(ownership_failure());
457        }
458        let status = self.output(&[
459            "container",
460            "inspect",
461            "--format",
462            "{{.State.Status}}",
463            self.environment_id(attempt)?,
464        ])?;
465        match status.trim() {
466            "running" => Ok(EnvironmentState::Running),
467            "created" | "configured" => Ok(EnvironmentState::Starting),
468            "exited" | "stopped" => Ok(EnvironmentState::Exited),
469            _ => Err(provider_failure()),
470        }
471    }
472
473    fn reap_attached(&self, attempt: AttemptId) {
474        let child = self
475            .attached
476            .lock()
477            .unwrap_or_else(std::sync::PoisonError::into_inner)
478            .remove(&attempt);
479        if let Some(mut child) = child {
480            if child.try_wait().ok().flatten().is_none() {
481                let _ = child.kill();
482            }
483            let _ = child.wait();
484        }
485    }
486}
487
488/// Whether `/etc/subuid` and `/etc/subgid` give the `containers` account the
489/// subordinate ids `--userns=auto` hands out: one namespace per concurrent
490/// container, for as many as the runner pool can run.
491fn rootful_ranges_sufficient(files: &[PathBuf]) -> bool {
492    let needed = containers_range_needed();
493    files.iter().all(|file| containers_range(file) >= needed)
494}
495
496/// How many subordinate ids the `containers` account needs for a rootful
497/// engine: one `--userns=auto` namespace for each runner the pool can run.
498#[must_use]
499pub fn containers_range_needed() -> u64 {
500    AUTO_USERNS_SIZE * u64::from(runner_manager_platform::runner_account::POOL_SIZE)
501}
502
503/// How many subordinate ids `file` (`/etc/subuid` or `/etc/subgid`) gives the
504/// `containers` account that `--userns=auto` allocates from; 0 when none.
505#[must_use]
506pub fn containers_range(file: &Path) -> u64 {
507    std::fs::read_to_string(file).map_or(0, |text| {
508        text.lines()
509            .filter_map(|line| line.strip_prefix("containers:"))
510            .filter_map(|range| range.split(':').nth(1)?.trim().parse::<u64>().ok())
511            .sum()
512    })
513}
514
515#[cfg(unix)]
516fn operator_runtime_is_trusted(path: &Path) -> bool {
517    use std::os::unix::fs::{MetadataExt, PermissionsExt};
518
519    if !path.is_absolute() {
520        return false;
521    }
522    let Ok(canonical) = std::fs::canonicalize(path) else {
523        return false;
524    };
525    if canonical == Path::new("/mnt") || canonical.starts_with("/mnt/") {
526        return false;
527    }
528    let Ok(metadata) = canonical.metadata() else {
529        return false;
530    };
531    let mode = metadata.permissions().mode();
532    metadata.is_file() && metadata.uid() == 0 && mode & 0o111 != 0 && mode & 0o022 == 0
533}
534
535#[cfg(not(unix))]
536fn operator_runtime_is_trusted(_path: &Path) -> bool {
537    false
538}
539
540fn bounded_storage_attested(
541    info: &serde_json::Value,
542    graph_root: &str,
543    run_root: &str,
544    requested_mib: u64,
545) -> bool {
546    info.pointer("/host/security/rootless")
547        .and_then(serde_json::Value::as_bool)
548        == Some(true)
549        && info
550            .pointer("/store/graphRoot")
551            .and_then(serde_json::Value::as_str)
552            == Some(graph_root)
553        && info
554            .pointer("/store/runRoot")
555            .and_then(serde_json::Value::as_str)
556            == Some(run_root)
557        && info
558            .pointer("/runnerManagerStorage/schema")
559            .and_then(serde_json::Value::as_u64)
560            == Some(BOUNDED_STORAGE_SCHEMA)
561        && info
562            .pointer("/runnerManagerStorage/mode")
563            .and_then(serde_json::Value::as_str)
564            == Some(BOUNDED_STORAGE_MODE)
565        && info
566            .pointer("/runnerManagerStorage/requestedMiB")
567            .and_then(serde_json::Value::as_u64)
568            == Some(requested_mib)
569        && info
570            .pointer("/runnerManagerStorage/hardCap")
571            .and_then(serde_json::Value::as_bool)
572            == Some(true)
573}
574
575fn provider_failure() -> FailureReason {
576    FailureReason::IsolationProvider(IsolationProviderFailure::RuntimeOperationFailed)
577}
578fn image_failure() -> FailureReason {
579    FailureReason::IsolationProvider(IsolationProviderFailure::ImageUnavailableOrIncompatible)
580}
581fn ownership_failure() -> FailureReason {
582    FailureReason::IsolationProvider(IsolationProviderFailure::OwnershipMismatch)
583}
584
585#[cfg(test)]
586fn retained_after_restart(state: EnvironmentState) -> bool {
587    matches!(state, EnvironmentState::Starting | EnvironmentState::Exited)
588}
589
590impl ExecutionProvider for OciProcesses {
591    fn probe(&self, policy: &ScalePolicy) -> ProviderCapability {
592        if policy.execution_policy().is_native() {
593            return ProviderCapability::Ready;
594        }
595        let ExecutionPolicy::Isolated {
596            backend,
597            image,
598            resources,
599        } = policy.execution_policy()
600        else {
601            return ProviderCapability::Unsupported;
602        };
603        if !matches!(backend, Backend::Auto | Backend::Oci) {
604            return ProviderCapability::Unsupported;
605        }
606        let capability = self.ready_for(u64::from(resources.disk_mib));
607        if capability != ProviderCapability::Ready {
608            return capability;
609        }
610        if self.image_ready(image).is_err() {
611            let capability = self.ready_for(u64::from(resources.disk_mib));
612            if capability == ProviderCapability::Ready {
613                ProviderCapability::ImageUnavailableOrIncompatible
614            } else {
615                capability
616            }
617        } else {
618            ProviderCapability::Ready
619        }
620    }
621
622    fn resolve(&self, policy: &ScalePolicy) -> Result<Option<ResolvedEnvironment>, FailureReason> {
623        let ExecutionPolicy::Isolated {
624            backend,
625            image,
626            resources,
627        } = policy.execution_policy()
628        else {
629            return Ok(None);
630        };
631        if !matches!(backend, Backend::Auto | Backend::Oci) {
632            return Err(ProviderCapability::Unsupported.refusal());
633        }
634        let capability = self.ready_for(u64::from(resources.disk_mib));
635        if capability != ProviderCapability::Ready {
636            return Err(capability.refusal());
637        }
638        self.image_ready(image)?;
639        Ok(Some(ResolvedEnvironment {
640            provider_kind: Backend::Oci,
641            image: image.clone(),
642        }))
643    }
644
645    fn prepare(
646        &self,
647        attempt: &RunnerAttempt,
648        policy: &ScalePolicy,
649    ) -> Result<PreparedEnvironment, FailureReason> {
650        let ExecutionPolicy::Isolated { resources, .. } = policy.execution_policy() else {
651            return ExecutionProvider::prepare(&self.native, attempt, policy);
652        };
653        let AttemptExecution::Isolated {
654            provider_kind: Backend::Oci,
655            resolved_image,
656            generation,
657            ..
658        } = attempt.execution()
659        else {
660            return Err(ownership_failure());
661        };
662        // Managed WSL must keep runner bytes in the distribution's Linux FS.
663        if attempt
664            .runtime_path()
665            .to_str()
666            .is_none_or(|path| !path.starts_with('/') || path.starts_with("/mnt/"))
667        {
668            return Err(FailureReason::IsolationProvider(
669                IsolationProviderFailure::UnsafeRuntimePath,
670            ));
671        }
672        let quota = self
673            .readiness(u64::from(resources.disk_mib))
674            .map_err(ProviderCapability::refusal)?;
675        let name = format!(
676            "rm-{}-{}",
677            attempt.id,
678            &generation[..generation.len().min(8)]
679        );
680        let cpu = format!("{:.3}", f64::from(resources.cpu_millis) / 1000.0);
681        let memory = format!("{}m", resources.memory_mib);
682        let disk = format!("size={}m", resources.disk_mib);
683        let host_label = format!("{HOST_LABEL}={}", self.host);
684        let attempt_label = format!("{ATTEMPT_LABEL}={}", attempt.id);
685        let generation_label = format!("{GENERATION_LABEL}={generation}");
686        let image_label = format!("{IMAGE_LABEL}={}", resolved_image.as_str());
687        let userns = match self.engine {
688            Engine::Rootless => "--userns=keep-id".to_owned(),
689            Engine::Rootful(_) => format!("--userns=auto:size={AUTO_USERNS_SIZE}"),
690        };
691        let mut arguments = vec![
692            "create",
693            "--interactive",
694            "--name",
695            &name,
696            "--pull=never",
697            "--entrypoint=sh",
698            "--log-driver=none",
699            "--image-volume=ignore",
700            "--http-proxy=false",
701            &userns,
702            "--user=0",
703            "--cap-drop=all",
704            "--cap-add=CHOWN",
705            "--cap-add=SETUID",
706            "--cap-add=SETGID",
707            "--cap-add=DAC_OVERRIDE",
708            "--cap-add=FOWNER",
709            "--security-opt=no-new-privileges",
710            "--network=slirp4netns",
711            "--pids-limit=128",
712            "--cpus",
713            &cpu,
714            "--memory",
715            &memory,
716            "--label",
717            &host_label,
718            "--label",
719            &attempt_label,
720            "--label",
721            &generation_label,
722            "--label",
723            &image_label,
724        ];
725        // Only where the storage enforces it: elsewhere `create` would fail,
726        // and running without one was the operator's explicit choice.
727        if quota {
728            arguments.extend(["--storage-opt", disk.as_str()]);
729        }
730        arguments.extend([resolved_image.as_str(), "-c", BOOTSTRAP]);
731        let id = self
732            .output(&arguments)
733            .map_err(|reason| self.capability_or(reason))?
734            .trim()
735            .to_owned();
736        if id.is_empty() || !id.bytes().all(|byte| byte.is_ascii_hexdigit()) {
737            return Err(self.capability_or(provider_failure()));
738        }
739        let identity = self.isolated_identity(attempt, id.clone())?;
740        // The package copy is host-to-guest only; no host path is mounted.
741        let source = format!("{}/.", attempt.runtime_path().display());
742        let destination = format!("{id}:/runner");
743        if self.status(&["cp", &source, &destination]).is_err() {
744            // Roll back before returning without a journalled environment ID.
745            // An unavailable runtime leaves a labelled orphan for enumeration.
746            if self
747                .labels(&id)
748                .is_ok_and(|labels| self.matches_attempt_labels(&labels, attempt))
749            {
750                let _ = self.status(&["rm", "--force", &id]);
751            }
752            return Err(self.capability_or(provider_failure()));
753        }
754        Ok(PreparedEnvironment::isolated(attempt.id, identity))
755    }
756
757    fn start(
758        &self,
759        prepared: PreparedEnvironment,
760        attempt: &RunnerAttempt,
761        handoff: OneTimeJitHandoff<'_>,
762    ) -> Result<EnvironmentIdentity, ProcessStartFailure> {
763        if attempt.execution().is_native() {
764            return ExecutionProvider::start(&self.native, prepared, attempt, handoff);
765        }
766        let Some(identity @ EnvironmentIdentity::Isolated { .. }) = prepared.identity().cloned()
767        else {
768            return Err(ProcessStartFailure::before_spawn(ownership_failure()));
769        };
770        let EnvironmentIdentity::Isolated { environment_id, .. } = &identity else {
771            unreachable!()
772        };
773        if self.environment_id(attempt).ok() != Some(environment_id.as_str())
774            || self.check_ownership(attempt) != Ok(true)
775        {
776            return Err(ProcessStartFailure::before_spawn(ownership_failure()));
777        }
778        let config = handoff.consume();
779        let payload = config.expose();
780        if payload.is_empty()
781            || payload.len() > 64 * 1024
782            || payload
783                .bytes()
784                .any(|byte| byte == b'\n' || byte == b'\r' || byte == 0)
785        {
786            return Err(ProcessStartFailure::before_spawn(
787                FailureReason::IsolationProvider(IsolationProviderFailure::JitHandoffRejected),
788            ));
789        }
790        let mut command = self.command();
791        let mut child = command
792            .args([
793                "start",
794                "--attach",
795                "--interactive",
796                "--sig-proxy=false",
797                environment_id,
798            ])
799            .stdin(Stdio::piped())
800            .stdout(Stdio::null())
801            .stderr(Stdio::null())
802            .spawn()
803            .map_err(|_| ProcessStartFailure::before_spawn(provider_failure()))?;
804        let write = child.stdin.take().is_some_and(|mut stdin| {
805            stdin.write_all(payload.as_bytes()).is_ok() && stdin.write_all(b"\n").is_ok()
806        });
807        if !write {
808            let _ = child.kill();
809            let _ = child.wait();
810            return Err(ProcessStartFailure::before_spawn(provider_failure()));
811        }
812        self.attached
813            .lock()
814            .unwrap_or_else(std::sync::PoisonError::into_inner)
815            .insert(attempt.id, child);
816        Ok(identity)
817    }
818
819    fn inspect(&self, attempt: &RunnerAttempt) -> Result<EnvironmentState, FailureReason> {
820        if attempt.execution().is_native() {
821            return ExecutionProvider::inspect(&self.native, attempt);
822        }
823        self.state(attempt)
824    }
825
826    fn recover(&self, attempt: &RunnerAttempt) -> Result<EnvironmentState, FailureReason> {
827        let AttemptExecution::Isolated {
828            environment_id: None,
829            generation,
830            ..
831        } = attempt.execution()
832        else {
833            return self.inspect(attempt);
834        };
835        let filters = [
836            format!("label={HOST_LABEL}={}", self.host),
837            format!("label={ATTEMPT_LABEL}={}", attempt.id),
838            format!("label={GENERATION_LABEL}={generation}"),
839        ];
840        let ids = self.output(&[
841            "ps",
842            "--all",
843            "--no-trunc",
844            "--filter",
845            &filters[0],
846            "--filter",
847            &filters[1],
848            "--filter",
849            &filters[2],
850            "--format",
851            "{{.ID}}",
852        ])?;
853        if ids.trim().is_empty() {
854            Ok(EnvironmentState::Missing)
855        } else {
856            Ok(EnvironmentState::Starting)
857        }
858    }
859
860    fn stop(&self, attempt: &RunnerAttempt) -> Result<ProviderStop, FailureReason> {
861        if attempt.execution().is_native() {
862            return ExecutionProvider::stop(&self.native, attempt);
863        }
864        if !self.exists(self.environment_id(attempt)?)? {
865            return Ok(ProviderStop::Stopped);
866        }
867        if self.state(attempt)? == EnvironmentState::Exited {
868            return Ok(ProviderStop::Stopped);
869        }
870        if !self.check_ownership(attempt)? {
871            return Err(ownership_failure());
872        }
873        self.status(&["stop", "--time=10", self.environment_id(attempt)?])
874            .map_err(|reason| self.capability_or(reason))?;
875        Ok(ProviderStop::Stopped)
876    }
877
878    fn destroy(&self, attempt: &RunnerAttempt) -> Result<ProviderDestroy, FailureReason> {
879        if attempt.execution().is_native() {
880            return ExecutionProvider::destroy(&self.native, attempt);
881        }
882        if !self.exists(self.environment_id(attempt)?)? {
883            self.reap_attached(attempt.id);
884            return Ok(ProviderDestroy::Destroyed);
885        }
886        if !self.check_ownership(attempt)? {
887            return Err(ownership_failure());
888        }
889        self.status(&["rm", "--force", self.environment_id(attempt)?])
890            .map_err(|reason| self.capability_or(reason))?;
891        self.reap_attached(attempt.id);
892        Ok(ProviderDestroy::Destroyed)
893    }
894
895    fn owns(&self, attempt: &RunnerAttempt) -> Result<bool, FailureReason> {
896        if attempt.execution().is_native() {
897            Ok(true)
898        } else {
899            if !self.exists(self.environment_id(attempt)?)? {
900                return Ok(false);
901            }
902            self.check_ownership(attempt)
903        }
904    }
905
906    fn enumerate_owned(&self, host: HostId) -> Vec<EnvironmentIdentity> {
907        // Recovery discovery must still work when a capability has degraded
908        // since creation. A failed readiness probe is not evidence of absence.
909        if host != self.host {
910            return Vec::new();
911        }
912        let filter = format!("label={HOST_LABEL}={host}");
913        let Ok(ids) = self.output(&[
914            "ps",
915            "--all",
916            "--no-trunc",
917            "--filter",
918            &filter,
919            "--format",
920            "{{.ID}}",
921        ]) else {
922            return Vec::new();
923        };
924        ids.lines()
925            .filter_map(|id| {
926                if id.is_empty() || !id.bytes().all(|byte| byte.is_ascii_hexdigit()) {
927                    return None;
928                }
929                let labels = self.labels(id).ok()?;
930                if labels.get(HOST_LABEL)? != &host.to_string() {
931                    return None;
932                }
933                let attempt =
934                    AttemptId::from_uuid(uuid::Uuid::parse_str(labels.get(ATTEMPT_LABEL)?).ok()?);
935                let generation = labels.get(GENERATION_LABEL)?.clone();
936                let resolved_image = ImageReference::new(labels.get(IMAGE_LABEL)?.clone()).ok()?;
937                Some(EnvironmentIdentity::Isolated {
938                    host,
939                    attempt,
940                    provider_kind: Backend::Oci,
941                    environment_id: id.to_owned(),
942                    resolved_image,
943                    generation,
944                })
945            })
946            .collect()
947    }
948
949    fn spawn(
950        &self,
951        attempt: &RunnerAttempt,
952        config: &EncodedJitConfig,
953    ) -> Result<u32, ProcessStartFailure> {
954        if !attempt.execution().is_native() {
955            return Err(ProcessStartFailure::before_spawn(ownership_failure()));
956        }
957        self.native.spawn(attempt, config)
958    }
959    fn is_alive(&self, attempt: &RunnerAttempt) -> Result<bool, FailureReason> {
960        if !attempt.execution().is_native() {
961            return Err(ownership_failure());
962        }
963        self.native.is_alive(attempt)
964    }
965    fn recovered_pid(&self, attempt: &RunnerAttempt) -> Result<Option<u32>, FailureReason> {
966        if !attempt.execution().is_native() {
967            return Err(ownership_failure());
968        }
969        self.native.recovered_pid(attempt)
970    }
971    fn completed_successfully(&self, attempt: &RunnerAttempt) -> bool {
972        if attempt.execution().is_native() {
973            return self.native.completed_successfully(attempt);
974        }
975        self.attached
976            .lock()
977            .unwrap_or_else(std::sync::PoisonError::into_inner)
978            .get_mut(&attempt.id)
979            .and_then(|child| child.try_wait().ok().flatten())
980            .is_some_and(|status| status.success())
981    }
982    fn record_terminate_intent(&self, attempt: &RunnerAttempt) -> Result<(), FailureReason> {
983        if !attempt.execution().is_native() {
984            return Err(ownership_failure());
985        }
986        self.native.record_terminate_intent(attempt)
987    }
988    fn has_terminate_intent(&self, attempt: &RunnerAttempt) -> bool {
989        attempt.execution().is_native() && self.native.has_terminate_intent(attempt)
990    }
991    fn terminate(&self, attempt: &RunnerAttempt) -> Result<(), FailureReason> {
992        if !attempt.execution().is_native() {
993            return Err(ownership_failure());
994        }
995        self.native.terminate(attempt)
996    }
997}
998
999#[cfg(test)]
1000mod boundary_tests {
1001    use super::*;
1002    use runner_manager_domain::model::Clock;
1003    use runner_manager_testkit::{clock::FakeClock, fixtures};
1004
1005    #[test]
1006    fn restart_recovery_accepts_only_retained_container_states() {
1007        assert!(retained_after_restart(EnvironmentState::Starting));
1008        assert!(retained_after_restart(EnvironmentState::Exited));
1009        assert!(!retained_after_restart(EnvironmentState::Running));
1010        assert!(!retained_after_restart(EnvironmentState::Missing));
1011    }
1012
1013    #[test]
1014    fn isolated_attempt_cannot_use_native_compatibility_methods() {
1015        let root = tempfile::tempdir().unwrap();
1016        let policy = fixtures::policy().build();
1017        let mut attempt = RunnerAttempt::allocate(
1018            AttemptId::new_random(),
1019            policy.id,
1020            root.path(),
1021            FakeClock::default().now(),
1022        );
1023        attempt
1024            .allocate_execution(AttemptExecution::Isolated {
1025                provider_kind: Backend::Oci,
1026                environment_id: None,
1027                resolved_image: ImageReference::new(format!(
1028                    "registry.example/runner@sha256:{}",
1029                    "a".repeat(64)
1030                ))
1031                .unwrap(),
1032                generation: "generation-1".into(),
1033            })
1034            .unwrap();
1035        let provider = OciProcesses::new(HostId::from_u128(1));
1036        let config = EncodedJitConfig::new("test-jit");
1037        let failure = provider.spawn(&attempt, &config).unwrap_err();
1038        assert_eq!(failure.reason, ownership_failure());
1039        assert!(failure.live_pid.is_none());
1040        assert_eq!(provider.is_alive(&attempt), Err(ownership_failure()));
1041        assert_eq!(provider.recovered_pid(&attempt), Err(ownership_failure()));
1042        assert_eq!(
1043            provider.record_terminate_intent(&attempt),
1044            Err(ownership_failure())
1045        );
1046        assert!(!provider.has_terminate_intent(&attempt));
1047        assert_eq!(provider.terminate(&attempt), Err(ownership_failure()));
1048    }
1049}
1050
1051#[cfg(all(test, target_os = "linux"))]
1052mod tests {
1053    use super::*;
1054    use runner_manager_domain::attempt::{AttemptOutcome, AttemptState};
1055    use runner_manager_domain::execution::ResourceLimits;
1056    use runner_manager_domain::model::Clock;
1057    use runner_manager_domain::store::{SqliteStore, Store};
1058    use runner_manager_testkit::{clock::FakeClock, fixtures};
1059    use std::io::Read;
1060    use std::os::unix::fs::PermissionsExt;
1061    use std::path::{Path, PathBuf};
1062    use std::time::{Duration, Instant};
1063
1064    fn fixture(info: &str) -> (tempfile::TempDir, OciProcesses) {
1065        fixture_with_quota(info, true)
1066    }
1067
1068    fn fixture_with_quota(info: &str, quota_ok: bool) -> (tempfile::TempDir, OciProcesses) {
1069        let root = tempfile::tempdir().unwrap();
1070        let path = root.path().join("podman");
1071        let quota_gate = if quota_ok {
1072            ""
1073        } else {
1074            "if [ \"$1\" = \"--storage-opt\" ]; then exit 1; fi\n"
1075        };
1076        let script = format!(
1077            "#!/bin/sh\n{quota_gate}printf '%s' '{}'\n",
1078            info.replace('\'', "'\\''")
1079        );
1080        std::fs::write(&path, script).unwrap();
1081        std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o700)).unwrap();
1082        let mut provider = OciProcesses::new(HostId::from_u128(1));
1083        provider.runtime = path.to_string_lossy().into_owned();
1084        (root, provider)
1085    }
1086
1087    fn info(rootless: bool, graph_root: &str, subuids: u64) -> String {
1088        serde_json::json!({
1089            "host": {
1090                "security": {"rootless": rootless},
1091                "cgroupVersion": "v2",
1092                "cgroupControllers": ["cpu", "memory", "pids"],
1093                "idMappings": {
1094                    "uidmap": [{"size": 1}, {"size": subuids}],
1095                    "gidmap": [{"size": 1}, {"size": subuids}]
1096                }
1097            },
1098            "store": {
1099                "graphRoot": graph_root,
1100                "runRoot": "/run/user/1000/containers",
1101                "graphStatus": {"Backing Filesystem": "xfs"}
1102            }
1103        })
1104        .to_string()
1105    }
1106
1107    /// A rootful-engine provider over the fixture runtime, with `range` ids
1108    /// in the `containers` subordinate ranges.
1109    fn rootful_fixture(
1110        info: &str,
1111        quota_ok: bool,
1112        range: u64,
1113    ) -> (tempfile::TempDir, OciProcesses) {
1114        let (root, mut provider) = fixture_with_quota(info, quota_ok);
1115        let ranges = root.path().join("subids");
1116        std::fs::write(
1117            &ranges,
1118            format!("ivan:100000:65536\ncontainers:2147483647:{range}\n"),
1119        )
1120        .unwrap();
1121        provider.subordinate_ids = [ranges.clone(), ranges];
1122        provider.engine = Engine::Rootful(PathBuf::from(ROOTFUL_SOCKET));
1123        (root, provider)
1124    }
1125
1126    #[test]
1127    fn a_rootful_engine_needs_rootful_podman_and_room_for_every_runner() {
1128        let rootful_info = info(false, "/var/lib/containers/storage", 1);
1129        let (_root, provider) = rootful_fixture(&rootful_info, true, 2_147_483_648);
1130        assert_eq!(provider.ready(), ProviderCapability::Ready);
1131        assert_eq!(provider.readiness(1024), Ok(true), "xfs enforces the quota");
1132
1133        let (_root, provider) = rootful_fixture(&rootful_info, true, 65_536);
1134        assert_eq!(
1135            provider.ready(),
1136            ProviderCapability::PermissionDenied,
1137            "one namespace's worth of ids cannot hold a namespace per runner"
1138        );
1139
1140        let rootless_info = info(true, "/home/ivan/.local/share/containers", 65536);
1141        let (_root, provider) = rootful_fixture(&rootless_info, true, 2_147_483_648);
1142        assert_eq!(provider.ready(), ProviderCapability::PermissionDenied);
1143    }
1144
1145    #[test]
1146    fn storage_without_a_quota_is_refused_unless_the_operator_accepted_it() {
1147        let ext4 = info(false, "/var/lib/containers/storage", 1).replace("xfs", "extfs");
1148        let (_root, provider) = rootful_fixture(&ext4, false, 2_147_483_648);
1149        assert_eq!(provider.ready(), ProviderCapability::DiskQuotaUnavailable);
1150        let mut provider = provider;
1151        provider.apply(IsolationSettings {
1152            disk_quota_required: false,
1153        });
1154        assert_eq!(provider.readiness(1024), Ok(false));
1155    }
1156
1157    #[test]
1158    fn rootless_probe_refuses_rootful_and_drvfs_storage() {
1159        let (_root, provider) = fixture(&info(false, "/home/ivan/.local/share/containers", 65536));
1160        assert_eq!(provider.ready(), ProviderCapability::PermissionDenied);
1161        let (_root, provider) = fixture(&info(true, "/mnt/c/containers", 65536));
1162        assert_eq!(provider.ready(), ProviderCapability::PermissionDenied);
1163        let (_root, provider) = fixture(&info(true, "/home/ivan/.local/share/containers", 1));
1164        assert_eq!(provider.ready(), ProviderCapability::PermissionDenied);
1165        let (_root, provider) = fixture(&info(true, "/home/ivan/.local/share/containers", 65536));
1166        assert_eq!(provider.ready(), ProviderCapability::Ready);
1167        let no_pids = info(true, "/home/ivan/.local/share/containers", 65536)
1168            .replace("\"pids\"", "\"missing\"");
1169        let (_root, provider) = fixture(&no_pids);
1170        assert_eq!(provider.ready(), ProviderCapability::Degraded);
1171        let extfs = info(true, "/home/ivan/.local/share/containers", 65536).replace(
1172            "\"Backing Filesystem\":\"xfs\"",
1173            "\"Backing Filesystem\":\"extfs\"",
1174        );
1175        let (_root, provider) = fixture(&extfs);
1176        assert_eq!(provider.ready(), ProviderCapability::DiskQuotaUnavailable);
1177        let mut bounded: serde_json::Value = serde_json::from_str(&extfs).unwrap();
1178        bounded["runnerManagerStorage"] = serde_json::json!({
1179            "schema": BOUNDED_STORAGE_SCHEMA,
1180            "mode": BOUNDED_STORAGE_MODE,
1181            "requestedMiB": QUOTA_PROBE_MIB,
1182            "hardCap": true
1183        });
1184        let (_root, provider) = fixture(&bounded.to_string());
1185        assert_eq!(provider.ready(), ProviderCapability::Ready);
1186        assert_eq!(
1187            provider.ready_for(2048),
1188            ProviderCapability::DiskQuotaUnavailable,
1189            "the helper must attest the exact requested size"
1190        );
1191        bounded["runnerManagerStorage"]["hardCap"] = serde_json::json!(false);
1192        let (_root, provider) = fixture(&bounded.to_string());
1193        assert_eq!(provider.ready(), ProviderCapability::DiskQuotaUnavailable);
1194        let (_root, provider) = fixture_with_quota(
1195            &info(true, "/home/ivan/.local/share/containers", 65536),
1196            false,
1197        );
1198        assert_eq!(provider.ready(), ProviderCapability::DiskQuotaUnavailable);
1199    }
1200
1201    #[test]
1202    fn missing_operator_runtime_is_not_treated_as_ready() {
1203        let mut provider = OciProcesses::new(HostId::from_u128(1));
1204        provider.runtime = "/a/path/that/cannot/be/podman".into();
1205        assert_eq!(provider.ready(), ProviderCapability::NotInstalled);
1206    }
1207
1208    #[test]
1209    fn recovery_discovers_owned_container_when_capability_degrades() {
1210        let root = tempfile::tempdir().unwrap();
1211        let path = root.path().join("podman");
1212        let host = HostId::from_u128(1);
1213        let attempt = AttemptId::new_random();
1214        let generation = "generation-1";
1215        let image = format!("registry.example/runner@sha256:{}", "a".repeat(64));
1216        let id = "b".repeat(64);
1217        let degraded_info = info(true, "/home/ivan/.local/share/containers", 65536)
1218            .replace("\"pids\"", "\"missing\"");
1219        let labels = BTreeMap::from([
1220            (HOST_LABEL, host.to_string()),
1221            (ATTEMPT_LABEL, attempt.to_string()),
1222            (GENERATION_LABEL, generation.to_owned()),
1223            (IMAGE_LABEL, image),
1224        ]);
1225        let labels = serde_json::to_string(&labels).unwrap();
1226        let script = format!(
1227            "#!/bin/sh\ncase \"$1\" in\n  info) printf '%s' '{degraded_info}' ;;\n  ps) printf '%s\\n' '{id}' ;;\n  container) printf '%s' '{labels}' ;;\n  *) exit 1 ;;\nesac\n"
1228        );
1229        std::fs::write(&path, script).unwrap();
1230        std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o700)).unwrap();
1231        let mut provider = OciProcesses::new(host);
1232        provider.runtime = path.to_string_lossy().into_owned();
1233        assert_eq!(provider.ready(), ProviderCapability::Degraded);
1234        let owned = provider.enumerate_owned(host);
1235        assert_eq!(owned.len(), 1);
1236        assert!(matches!(
1237            &owned[0],
1238            EnvironmentIdentity::Isolated {
1239                host: found_host,
1240                attempt: found_attempt,
1241                environment_id,
1242                generation: found_generation,
1243                ..
1244            } if *found_host == host && *found_attempt == attempt
1245                && environment_id == &id && found_generation == generation
1246        ));
1247    }
1248
1249    #[test]
1250    fn native_start_still_delegates_to_the_existing_process_supervisor() {
1251        let root = tempfile::tempdir().unwrap();
1252        let runtime = root.path().join("runtime");
1253        let bin = runtime.join("bin");
1254        std::fs::create_dir_all(&bin).unwrap();
1255        let listener = bin.join("Runner.Listener");
1256        std::fs::write(&listener, "#!/bin/sh\nsleep 10\n").unwrap();
1257        std::fs::set_permissions(&listener, std::fs::Permissions::from_mode(0o700)).unwrap();
1258        let policy = fixtures::policy()
1259            .repository("octo/repo")
1260            .autoscale("home", 1)
1261            .active()
1262            .build();
1263        let attempt = RunnerAttempt::allocate(
1264            AttemptId::new_random(),
1265            policy.id,
1266            &runtime,
1267            FakeClock::default().now(),
1268        );
1269        let provider = OciProcesses::new(HostId::from_u128(1));
1270        let prepared = provider.prepare(&attempt, &policy).unwrap();
1271        let config = EncodedJitConfig::new("native-test-jit");
1272        let identity = provider
1273            .start(prepared, &attempt, OneTimeJitHandoff::new(&config))
1274            .unwrap();
1275        assert!(matches!(identity, EnvironmentIdentity::NativeProcess(_)));
1276        provider.stop(&attempt).unwrap();
1277    }
1278
1279    const LIVE_IMAGE_ENV: &str = "RUNNER_MANAGER_OCI_ACCEPTANCE_IMAGE";
1280    const LIVE_HOST: u128 = 0x00ac_ce7a_ce00_0000_0000_0000_0000_0001;
1281    const LIVE_PACKAGE: &str = "runner-manager-oci-conflict";
1282
1283    fn live_runtime() -> String {
1284        std::env::var(OCI_RUNTIME_ENV).unwrap_or_else(|_| "podman".into())
1285    }
1286
1287    fn podman(args: &[&str]) -> std::process::Output {
1288        Command::new(live_runtime())
1289            .args(args)
1290            .output()
1291            .unwrap_or_else(|error| panic!("podman {args:?} did not execute: {error}"))
1292    }
1293
1294    fn podman_ok(args: &[&str]) -> String {
1295        let output = podman(args);
1296        assert!(
1297            output.status.success(),
1298            "podman {args:?} failed: {}",
1299            String::from_utf8_lossy(&output.stderr)
1300        );
1301        String::from_utf8(output.stdout).expect("podman emitted UTF-8")
1302    }
1303
1304    fn write_listener(runtime: &Path) {
1305        let bin = runtime.join("bin");
1306        std::fs::create_dir_all(&bin).unwrap();
1307        let listener = bin.join("Runner.Listener");
1308        // The real runner consumes the same environment variable. This fixture
1309        // proves the provider's stdin-to-bootstrap handoff, then removes it
1310        // before the long-lived child exists so the sentinel is not retained
1311        // in the process environment or writable layer.
1312        std::fs::write(
1313            &listener,
1314            "#!/bin/sh\n\
1315             test -n \"${ACTIONS_RUNNER_INPUT_JITCONFIG:-}\" || exit 70\n\
1316             unset ACTIONS_RUNNER_INPUT_JITCONFIG\n\
1317             : > /tmp/runner-manager-jit-received\n\
1318             exec sleep 600\n",
1319        )
1320        .unwrap();
1321        std::fs::set_permissions(&listener, std::fs::Permissions::from_mode(0o700)).unwrap();
1322    }
1323
1324    fn build_conflicting_package(runtime: &Path, version: &str) -> PathBuf {
1325        let root = runtime.join(format!("package-{version}"));
1326        let debian = root.join("DEBIAN");
1327        let bin = root.join("usr/local/bin");
1328        std::fs::create_dir_all(&debian).unwrap();
1329        std::fs::create_dir_all(&bin).unwrap();
1330        std::fs::write(
1331            debian.join("control"),
1332            format!(
1333                "Package: {LIVE_PACKAGE}\nVersion: {version}\nArchitecture: all\n\
1334                 Maintainer: Runner Manager acceptance <nobody@example.invalid>\n\
1335                 Description: isolated package database acceptance fixture\n"
1336            ),
1337        )
1338        .unwrap();
1339        let tool = bin.join("runner-manager-conflict");
1340        std::fs::write(&tool, format!("#!/bin/sh\nprintf '%s\\n' '{version}'\n")).unwrap();
1341        std::fs::set_permissions(&tool, std::fs::Permissions::from_mode(0o755)).unwrap();
1342        let package = runtime.join("conflict.deb");
1343        let output = Command::new("dpkg-deb")
1344            .args(["--build", "--root-owner-group"])
1345            .arg(&root)
1346            .arg(&package)
1347            .output()
1348            .expect("dpkg-deb must be installed by the native acceptance job");
1349        assert!(
1350            output.status.success(),
1351            "dpkg-deb failed: {}",
1352            String::from_utf8_lossy(&output.stderr)
1353        );
1354        package
1355    }
1356
1357    fn isolated_policy(image: ImageReference) -> ScalePolicy {
1358        let mut policy = fixtures::policy()
1359            .repository("octo/oci-native-acceptance")
1360            .autoscale("isolated", 3)
1361            .active()
1362            .build();
1363        policy
1364            .set_execution_policy(ExecutionPolicy::Isolated {
1365                backend: Backend::Oci,
1366                image,
1367                resources: ResourceLimits {
1368                    cpu_millis: 1000,
1369                    memory_mib: 512,
1370                    disk_mib: 1024,
1371                },
1372            })
1373            .unwrap();
1374        policy
1375    }
1376
1377    fn prepare_live_attempt(
1378        provider: &OciProcesses,
1379        policy: &ScalePolicy,
1380        image: &ImageReference,
1381        version: Option<&str>,
1382        generation: &str,
1383        production_quota_path: bool,
1384    ) -> (
1385        tempfile::TempDir,
1386        RunnerAttempt,
1387        PreparedEnvironment,
1388        String,
1389    ) {
1390        let runtime = tempfile::tempdir().unwrap();
1391        write_listener(runtime.path());
1392        if let Some(version) = version {
1393            build_conflicting_package(runtime.path(), version);
1394        }
1395        let mut attempt = RunnerAttempt::allocate(
1396            AttemptId::new_random(),
1397            policy.id,
1398            runtime.path(),
1399            FakeClock::default().now(),
1400        );
1401        attempt
1402            .allocate_execution(AttemptExecution::Isolated {
1403                provider_kind: Backend::Oci,
1404                environment_id: None,
1405                resolved_image: image.clone(),
1406                generation: generation.into(),
1407            })
1408            .unwrap();
1409        if production_quota_path {
1410            let prepared = provider.prepare(&attempt, policy).unwrap();
1411            let EnvironmentIdentity::Isolated { environment_id, .. } =
1412                prepared.identity().cloned().expect("isolated identity")
1413            else {
1414                panic!("OCI prepare returned a native identity")
1415            };
1416            return (runtime, attempt, prepared, environment_id);
1417        }
1418        let ExecutionPolicy::Isolated { resources, .. } = policy.execution_policy() else {
1419            panic!("structural acceptance needs an isolated policy")
1420        };
1421        let name = format!("rm-{}-{}", attempt.id, generation);
1422        let cpu = format!("{:.3}", f64::from(resources.cpu_millis) / 1000.0);
1423        let memory = format!("{}m", resources.memory_mib);
1424        let host_label = format!("{HOST_LABEL}={}", provider.host);
1425        let attempt_label = format!("{ATTEMPT_LABEL}={}", attempt.id);
1426        let generation_label = format!("{GENERATION_LABEL}={generation}");
1427        let image_label = format!("{IMAGE_LABEL}={}", image.as_str());
1428        // Rootless Podman cannot initialize XFS project quotas because project
1429        // IDs are not namespaced and an unprivileged user cannot create the
1430        // backing block-device node. The acceptance first proves the production
1431        // provider refuses that missing hard cap. This second, explicitly
1432        // structural fixture omits only --storage-opt so the remaining real
1433        // container boundary can still be measured on the hard-bounded loop FS.
1434        let environment_id = provider
1435            .output(&[
1436                "create",
1437                "--interactive",
1438                "--name",
1439                &name,
1440                "--pull=never",
1441                "--entrypoint=sh",
1442                "--log-driver=none",
1443                "--image-volume=ignore",
1444                "--http-proxy=false",
1445                "--userns=keep-id",
1446                "--user=0",
1447                "--cap-drop=all",
1448                "--cap-add=CHOWN",
1449                "--cap-add=SETUID",
1450                "--cap-add=SETGID",
1451                "--cap-add=DAC_OVERRIDE",
1452                "--cap-add=FOWNER",
1453                "--security-opt=no-new-privileges",
1454                "--network=slirp4netns",
1455                "--pids-limit=128",
1456                "--cpus",
1457                &cpu,
1458                "--memory",
1459                &memory,
1460                "--label",
1461                &host_label,
1462                "--label",
1463                &attempt_label,
1464                "--label",
1465                &generation_label,
1466                "--label",
1467                &image_label,
1468                image.as_str(),
1469                "-c",
1470                BOOTSTRAP,
1471            ])
1472            .unwrap()
1473            .trim()
1474            .to_owned();
1475        assert!(!environment_id.is_empty());
1476        let source = format!("{}/.", attempt.runtime_path().display());
1477        let destination = format!("{environment_id}:/runner");
1478        provider.status(&["cp", &source, &destination]).unwrap();
1479        let identity = provider
1480            .isolated_identity(&attempt, environment_id.clone())
1481            .unwrap();
1482        let prepared = PreparedEnvironment::isolated(attempt.id, identity);
1483        (runtime, attempt, prepared, environment_id)
1484    }
1485
1486    fn start_live_attempt(
1487        provider: &OciProcesses,
1488        attempt: &mut RunnerAttempt,
1489        prepared: PreparedEnvironment,
1490        environment_id: &str,
1491        sentinel: &str,
1492    ) {
1493        attempt
1494            .prepared_environment(environment_id.to_owned())
1495            .unwrap();
1496        let config = EncodedJitConfig::new(sentinel);
1497        provider
1498            .start(prepared, attempt, OneTimeJitHandoff::new(&config))
1499            .unwrap();
1500        let deadline = Instant::now() + Duration::from_secs(20);
1501        loop {
1502            let received = podman(&[
1503                "exec",
1504                environment_id,
1505                "test",
1506                "-f",
1507                "/tmp/runner-manager-jit-received",
1508            ]);
1509            if received.status.success() {
1510                break;
1511            }
1512            assert!(Instant::now() < deadline, "listener did not consume JIT");
1513            std::thread::sleep(Duration::from_millis(100));
1514        }
1515    }
1516
1517    fn inspect_controls(environment_id: &str, image: &ImageReference, sentinel: &str) {
1518        let raw = podman_ok(&["container", "inspect", environment_id]);
1519        assert!(
1520            !raw.contains(sentinel),
1521            "JIT sentinel reached inspect metadata"
1522        );
1523        assert!(!raw.contains("/run/podman/podman.sock"));
1524        assert!(!raw.contains("/var/run/docker.sock"));
1525        let inspect: serde_json::Value = serde_json::from_str(&raw).unwrap();
1526        let item = &inspect[0];
1527        assert_eq!(
1528            item.pointer("/Mounts")
1529                .and_then(|v| v.as_array())
1530                .map(Vec::len),
1531            Some(0)
1532        );
1533        assert!(
1534            item.pointer("/HostConfig/Devices")
1535                .is_none_or(|value| value.is_null() || value.as_array().is_some_and(Vec::is_empty)),
1536            "host devices were attached: {}",
1537            item["HostConfig"]["Devices"]
1538        );
1539        assert!(
1540            item.pointer("/HostConfig/Binds")
1541                .is_none_or(|value| value.is_null() || value.as_array().is_some_and(Vec::is_empty)),
1542            "host bind mounts were attached: {}",
1543            item["HostConfig"]["Binds"]
1544        );
1545        assert_eq!(item["HostConfig"]["PidsLimit"].as_i64(), Some(128));
1546        assert_eq!(
1547            item["HostConfig"]["Memory"].as_u64(),
1548            Some(512 * 1024 * 1024)
1549        );
1550        assert_eq!(
1551            item["Config"]["Labels"][IMAGE_LABEL].as_str(),
1552            Some(image.as_str())
1553        );
1554        let command = item["Config"]["CreateCommand"]
1555            .as_array()
1556            .expect("Podman records create command");
1557        for forbidden in ["--device", "--mount", "--volume", "-v", "--privileged"] {
1558            assert!(
1559                !command.iter().any(|part| part.as_str() == Some(forbidden)),
1560                "forbidden create option {forbidden} was present"
1561            );
1562        }
1563        let socket_check = podman(&[
1564            "exec",
1565            environment_id,
1566            "sh",
1567            "-c",
1568            "test ! -S /run/podman/podman.sock && test ! -S /var/run/docker.sock",
1569        ]);
1570        assert!(
1571            socket_check.status.success(),
1572            "a host runtime socket is visible"
1573        );
1574        let logs = podman(&["logs", environment_id]);
1575        assert!(!String::from_utf8_lossy(&logs.stdout).contains(sentinel));
1576        assert!(!String::from_utf8_lossy(&logs.stderr).contains(sentinel));
1577        let history = podman_ok(&["history", "--no-trunc", image.as_str()]);
1578        assert!(
1579            !history.contains(sentinel),
1580            "JIT sentinel reached image history"
1581        );
1582    }
1583
1584    fn assert_export_excludes(environment_id: &str, sentinel: &str) {
1585        let mut child = Command::new(live_runtime())
1586            .args(["export", environment_id])
1587            .stdout(Stdio::piped())
1588            .stderr(Stdio::piped())
1589            .spawn()
1590            .expect("podman export starts");
1591        let mut bytes = Vec::new();
1592        child
1593            .stdout
1594            .take()
1595            .unwrap()
1596            .read_to_end(&mut bytes)
1597            .unwrap();
1598        let output = child.wait_with_output().unwrap();
1599        assert!(
1600            output.status.success(),
1601            "podman export failed: {}",
1602            String::from_utf8_lossy(&output.stderr)
1603        );
1604        assert!(
1605            !bytes
1606                .windows(sentinel.len())
1607                .any(|window| window == sentinel.as_bytes()),
1608            "JIT sentinel reached the container root filesystem"
1609        );
1610    }
1611
1612    fn wait_for_container_file(environment_id: &str, path: &str, deadline: Instant) -> bool {
1613        loop {
1614            if podman(&["exec", environment_id, "test", "-f", path])
1615                .status
1616                .success()
1617            {
1618                return true;
1619            }
1620            if Instant::now() >= deadline {
1621                return false;
1622            }
1623            std::thread::sleep(Duration::from_millis(250));
1624        }
1625    }
1626
1627    fn assert_live_jit_absent(environment_id: &str, image: &ImageReference, jit: &str) {
1628        let inspect = podman_ok(&["container", "inspect", environment_id]);
1629        assert!(
1630            !inspect.contains(jit),
1631            "JIT reached container inspect metadata"
1632        );
1633
1634        let top = podman(&["top", environment_id, "pid,args"]);
1635        assert!(top.status.success(), "container process listing failed");
1636        assert!(
1637            !top.stdout
1638                .windows(jit.len())
1639                .any(|window| window == jit.as_bytes()),
1640            "JIT reached the container process listing"
1641        );
1642
1643        let logs = podman(&["logs", environment_id]);
1644        assert!(
1645            !logs
1646                .stdout
1647                .windows(jit.len())
1648                .any(|window| window == jit.as_bytes())
1649        );
1650        assert!(
1651            !logs
1652                .stderr
1653                .windows(jit.len())
1654                .any(|window| window == jit.as_bytes())
1655        );
1656        let history = podman_ok(&["history", "--no-trunc", image.as_str()]);
1657        assert!(!history.contains(jit), "JIT reached image history");
1658    }
1659
1660    fn stop_and_destroy(provider: &OciProcesses, attempt: &RunnerAttempt) {
1661        assert_eq!(provider.stop(attempt).unwrap(), ProviderStop::Stopped);
1662        assert_eq!(
1663            provider.destroy(attempt).unwrap(),
1664            ProviderDestroy::Destroyed
1665        );
1666        assert_eq!(
1667            provider.inspect(attempt).unwrap(),
1668            EnvironmentState::Missing
1669        );
1670    }
1671
1672    fn run_live_rootless_acceptance(production_quota_path: bool) {
1673        let image = ImageReference::new(
1674            std::env::var(LIVE_IMAGE_ENV)
1675                .unwrap_or_else(|_| panic!("{LIVE_IMAGE_ENV} must name a pinned image digest")),
1676        )
1677        .unwrap();
1678        let provider = OciProcesses::new(HostId::from_u128(LIVE_HOST));
1679        let policy = isolated_policy(image.clone());
1680
1681        if production_quota_path {
1682            assert_eq!(provider.probe(&policy), ProviderCapability::Ready);
1683            let resolution = provider.resolve(&policy).unwrap().unwrap();
1684            assert_eq!(resolution.provider_kind, Backend::Oci);
1685            assert_eq!(resolution.image, image);
1686        } else {
1687            assert_eq!(
1688                provider.probe(&policy),
1689                ProviderCapability::DiskQuotaUnavailable
1690            );
1691            assert_eq!(
1692                provider.resolve(&policy),
1693                Err(ProviderCapability::DiskQuotaUnavailable.refusal()),
1694                "the production provider must fail before image allocation or JIT"
1695            );
1696            provider.image_ready(&image).unwrap();
1697        }
1698        assert!(
1699            !Command::new("dpkg-query")
1700                .args(["-W", LIVE_PACKAGE])
1701                .status()
1702                .unwrap()
1703                .success(),
1704            "acceptance package unexpectedly exists on the host"
1705        );
1706
1707        let (_runtime_one, mut one, prepared_one, id_one) = prepare_live_attempt(
1708            &provider,
1709            &policy,
1710            &image,
1711            Some("1.0"),
1712            "native-one",
1713            production_quota_path,
1714        );
1715        let sentinel_one = "rm-jit-sentinel-native-one-8eeb09c26b8a";
1716        start_live_attempt(&provider, &mut one, prepared_one, &id_one, sentinel_one);
1717        inspect_controls(&id_one, &image, sentinel_one);
1718        podman_ok(&["exec", &id_one, "dpkg", "-i", "/runner/conflict.deb"]);
1719        assert_eq!(
1720            podman_ok(&[
1721                "exec",
1722                &id_one,
1723                "dpkg-query",
1724                "-W",
1725                "-f=${Version}",
1726                LIVE_PACKAGE,
1727            ])
1728            .trim(),
1729            "1.0"
1730        );
1731        assert_eq!(
1732            podman_ok(&["exec", &id_one, "/usr/local/bin/runner-manager-conflict"]).trim(),
1733            "1.0"
1734        );
1735
1736        let (_runtime_two, mut two, prepared_two, id_two) = prepare_live_attempt(
1737            &provider,
1738            &policy,
1739            &image,
1740            Some("2.0"),
1741            "native-two",
1742            production_quota_path,
1743        );
1744        let sentinel_two = "rm-jit-sentinel-native-two-62b2db40633b";
1745        start_live_attempt(&provider, &mut two, prepared_two, &id_two, sentinel_two);
1746        inspect_controls(&id_two, &image, sentinel_two);
1747        podman_ok(&["exec", &id_two, "dpkg", "-i", "/runner/conflict.deb"]);
1748        assert_eq!(
1749            podman_ok(&[
1750                "exec",
1751                &id_two,
1752                "dpkg-query",
1753                "-W",
1754                "-f=${Version}",
1755                LIVE_PACKAGE,
1756            ])
1757            .trim(),
1758            "2.0"
1759        );
1760        assert_eq!(
1761            podman_ok(&["exec", &id_one, "/usr/local/bin/runner-manager-conflict"]).trim(),
1762            "1.0",
1763            "the second package install mutated its sibling"
1764        );
1765        assert_export_excludes(&id_one, sentinel_one);
1766        assert_export_excludes(&id_two, sentinel_two);
1767
1768        // Prove the loopback store's hard upper bound with real writes. A
1769        // fallocate-only probe may fail because an overlay does not implement
1770        // allocation, which says nothing about the backing filesystem's cap.
1771        // `dd` writes zeroes through fuse-overlayfs until ext4/XFS returns
1772        // ENOSPC; `df` records that the same filesystem reached zero available
1773        // bytes. Remove the partial file before Podman needs to journal the
1774        // process exit or destroy the container.
1775        let oversize_mib = if production_quota_path {
1776            "1100"
1777        } else {
1778            "7168"
1779        };
1780        let exhaustion = podman(&[
1781            "exec",
1782            &id_one,
1783            "sh",
1784            "-c",
1785            "set +e; printf 'RM_FS_BEFORE '; df -B1 --output=size,used,avail / | tail -n 1; dd if=/dev/zero of=/backing-store-cap bs=1M count=\"$1\" conv=fsync status=none; status=$?; printf 'RM_FS_FULL '; df -B1 --output=size,used,avail / | tail -n 1; rm -f /backing-store-cap; sync; exit \"$status\"",
1786            "sh",
1787            oversize_mib,
1788        ]);
1789        assert!(
1790            !exhaustion.status.success(),
1791            "the backing-store hard cap allowed an oversized allocation"
1792        );
1793        let exhaustion_stdout = String::from_utf8(exhaustion.stdout).unwrap();
1794        let exhaustion_stderr = String::from_utf8(exhaustion.stderr).unwrap();
1795        assert!(
1796            exhaustion_stderr.contains("No space left on device"),
1797            "the write failed without ENOSPC: {exhaustion_stderr}"
1798        );
1799        let df_line = |marker: &str| {
1800            exhaustion_stdout
1801                .lines()
1802                .find_map(|line| line.strip_prefix(marker))
1803                .map(|line| {
1804                    line.split_whitespace()
1805                        .map(|value| value.parse().expect("df emitted integer byte counts"))
1806                        .collect::<Vec<u64>>()
1807                })
1808                .unwrap_or_else(|| {
1809                    panic!("the write did not emit {marker:?} df evidence: {exhaustion_stdout}")
1810                })
1811        };
1812        let before = df_line("RM_FS_BEFORE ");
1813        let full = df_line("RM_FS_FULL ");
1814        assert_eq!(
1815            before.len(),
1816            3,
1817            "unexpected initial df evidence: {before:?}"
1818        );
1819        assert_eq!(full.len(), 3, "unexpected full df evidence: {full:?}");
1820        assert!(
1821            full[1] >= before[1] + 512 * 1024 * 1024,
1822            "the ENOSPC probe did not perform substantial writes: before={before:?} full={full:?}"
1823        );
1824        assert!(
1825            full[2] <= 1024 * 1024,
1826            "ENOSPC left more than 1 MiB available: {full:?}"
1827        );
1828        stop_and_destroy(&provider, &one);
1829        stop_and_destroy(&provider, &two);
1830
1831        let (_runtime_fresh, mut fresh, prepared_fresh, id_fresh) = prepare_live_attempt(
1832            &provider,
1833            &policy,
1834            &image,
1835            None,
1836            "native-fresh",
1837            production_quota_path,
1838        );
1839        start_live_attempt(
1840            &provider,
1841            &mut fresh,
1842            prepared_fresh,
1843            &id_fresh,
1844            "rm-jit-sentinel-native-fresh-c1b9f470d09e",
1845        );
1846        assert!(
1847            !podman(&["exec", &id_fresh, "dpkg-query", "-W", LIVE_PACKAGE])
1848                .status
1849                .success(),
1850            "a fresh sibling inherited the earlier package database"
1851        );
1852        assert!(
1853            !podman(&[
1854                "exec",
1855                &id_fresh,
1856                "test",
1857                "-e",
1858                "/usr/local/bin/runner-manager-conflict",
1859            ])
1860            .status
1861            .success(),
1862            "a fresh sibling inherited an earlier writable-layer file"
1863        );
1864        stop_and_destroy(&provider, &fresh);
1865
1866        // Simulate the crash gap after create and before the environment ID is
1867        // journalled. Recovery discovers and quarantines exactly the labelled
1868        // orphan; after the durable identity is restored, normal destroy owns
1869        // and removes it.
1870        let (_runtime_orphan, mut orphan, prepared_orphan, orphan_id) = prepare_live_attempt(
1871            &provider,
1872            &policy,
1873            &image,
1874            None,
1875            "native-orphan",
1876            production_quota_path,
1877        );
1878        assert_eq!(
1879            provider.recover(&orphan).unwrap(),
1880            EnvironmentState::Starting
1881        );
1882        let owned = provider.enumerate_owned(HostId::from_u128(LIVE_HOST));
1883        assert_eq!(owned.len(), 1, "recovery did not isolate one owned orphan");
1884        assert!(matches!(
1885            &owned[0],
1886            EnvironmentIdentity::Isolated { environment_id, .. } if environment_id == &orphan_id
1887        ));
1888        orphan.prepared_environment(orphan_id).unwrap();
1889        assert_eq!(
1890            provider.destroy(&orphan).unwrap(),
1891            ProviderDestroy::Destroyed
1892        );
1893        assert!(
1894            provider
1895                .enumerate_owned(HostId::from_u128(LIVE_HOST))
1896                .is_empty()
1897        );
1898        drop(prepared_orphan);
1899
1900        assert!(
1901            !Command::new("dpkg-query")
1902                .args(["-W", LIVE_PACKAGE])
1903                .status()
1904                .unwrap()
1905                .success(),
1906            "container package installation mutated the host package database"
1907        );
1908    }
1909
1910    const RESTART_FIXTURE_ENV: &str = "RUNNER_MANAGER_OCI_RESTART_FIXTURE";
1911
1912    fn restart_fixture_root() -> PathBuf {
1913        let root = PathBuf::from(std::env::var(RESTART_FIXTURE_ENV).unwrap_or_else(|_| {
1914            panic!("{RESTART_FIXTURE_ENV} must name the durable fixture root")
1915        }));
1916        assert!(root.is_absolute() && !root.starts_with("/mnt"));
1917        root
1918    }
1919
1920    fn restart_attempt(
1921        root: &Path,
1922        policy: &ScalePolicy,
1923        image: &ImageReference,
1924        suffix: &str,
1925        id: u128,
1926        generation: &str,
1927    ) -> RunnerAttempt {
1928        let runtime = root.join("runtimes").join(suffix);
1929        std::fs::create_dir_all(&runtime).unwrap();
1930        write_listener(&runtime);
1931        let mut attempt = RunnerAttempt::allocate(
1932            AttemptId::from_u128(id),
1933            policy.id,
1934            runtime,
1935            FakeClock::default().now(),
1936        );
1937        attempt
1938            .allocate_execution(AttemptExecution::Isolated {
1939                provider_kind: Backend::Oci,
1940                environment_id: None,
1941                resolved_image: image.clone(),
1942                generation: generation.into(),
1943            })
1944            .unwrap();
1945        attempt
1946    }
1947
1948    fn prepare_restart_resource(
1949        provider: &OciProcesses,
1950        policy: &ScalePolicy,
1951        attempt: &mut RunnerAttempt,
1952    ) -> (PreparedEnvironment, String) {
1953        attempt.begin_prepare(FakeClock::default().now()).unwrap();
1954        let prepared = provider.prepare(attempt, policy).unwrap();
1955        let EnvironmentIdentity::Isolated { environment_id, .. } =
1956            prepared.identity().cloned().expect("isolated identity")
1957        else {
1958            panic!("OCI prepare returned a native identity")
1959        };
1960        (prepared, environment_id)
1961    }
1962
1963    #[test]
1964    #[ignore = "seeds real managed-WSL resources for the terminate/restart acceptance"]
1965    fn live_rootless_managed_wsl_restart_seed() {
1966        let root = restart_fixture_root();
1967        std::fs::create_dir_all(&root).unwrap();
1968        let journal = SqliteStore::open(root.join("attempts.sqlite3")).unwrap();
1969        let image = ImageReference::new(
1970            std::env::var(LIVE_IMAGE_ENV)
1971                .unwrap_or_else(|_| panic!("{LIVE_IMAGE_ENV} must name a pinned image digest")),
1972        )
1973        .unwrap();
1974        let provider = OciProcesses::new(HostId::from_u128(LIVE_HOST));
1975        let policy = isolated_policy(image.clone());
1976        let nonce = std::env::var("RUNNER_MANAGER_OCI_RESTART_NONCE").expect(
1977            "RUNNER_MANAGER_OCI_RESTART_NONCE must contain the non-secret acceptance nonce",
1978        );
1979        assert!(nonce.starts_with("rm-reboot-nonce-") && nonce.len() == 48);
1980        assert_eq!(provider.probe(&policy), ProviderCapability::Ready);
1981
1982        let clock = FakeClock::default();
1983        let mut prepared = restart_attempt(
1984            &root,
1985            &policy,
1986            &image,
1987            "prepared",
1988            0xd101,
1989            "restart-prepared",
1990        );
1991        let (_prepared_handle, prepared_id) =
1992            prepare_restart_resource(&provider, &policy, &mut prepared);
1993        prepared.prepared_environment(prepared_id).unwrap();
1994        prepared.mark_prepared(clock.now()).unwrap();
1995        journal.record_attempt(&prepared).unwrap();
1996
1997        let mut running =
1998            restart_attempt(&root, &policy, &image, "running", 0xd102, "restart-running");
1999        let (running_handle, running_id) =
2000            prepare_restart_resource(&provider, &policy, &mut running);
2001        running.prepared_environment(running_id.clone()).unwrap();
2002        running.mark_prepared(clock.now()).unwrap();
2003        running.jit_received(clock.now()).unwrap();
2004        provider
2005            .start(
2006                running_handle,
2007                &running,
2008                OneTimeJitHandoff::new(&EncodedJitConfig::new(&nonce)),
2009            )
2010            .unwrap();
2011        running.started_isolated(clock.now()).unwrap();
2012        assert!(wait_for_container_file(
2013            &running_id,
2014            "/tmp/runner-manager-jit-received",
2015            Instant::now() + Duration::from_secs(60),
2016        ));
2017        journal.record_attempt(&running).unwrap();
2018        inspect_controls(&running_id, &image, &nonce);
2019        assert_export_excludes(&running_id, &nonce);
2020
2021        let mut deferred = restart_attempt(
2022            &root,
2023            &policy,
2024            &image,
2025            "cleanup-deferred",
2026            0xd103,
2027            "restart-deferred",
2028        );
2029        let (_deferred_handle, deferred_id) =
2030            prepare_restart_resource(&provider, &policy, &mut deferred);
2031        deferred.prepared_environment(deferred_id).unwrap();
2032        deferred.mark_prepared(clock.now()).unwrap();
2033        deferred.jit_received(clock.now()).unwrap();
2034        deferred.started_isolated(clock.now()).unwrap();
2035        deferred
2036            .conclude(AttemptOutcome::Orphaned, clock.now())
2037            .unwrap();
2038        deferred.begin_destroy(clock.now()).unwrap();
2039        deferred.defer_cleanup(clock.now()).unwrap();
2040        journal.record_attempt(&deferred).unwrap();
2041
2042        let mut orphaned = restart_attempt(
2043            &root,
2044            &policy,
2045            &image,
2046            "orphaned",
2047            0xd104,
2048            "restart-orphaned",
2049        );
2050        let (_orphaned_handle, orphaned_id) =
2051            prepare_restart_resource(&provider, &policy, &mut orphaned);
2052        orphaned.prepared_environment(orphaned_id).unwrap();
2053        orphaned.mark_prepared(clock.now()).unwrap();
2054        orphaned
2055            .conclude(AttemptOutcome::Orphaned, clock.now())
2056            .unwrap();
2057        journal.record_attempt(&orphaned).unwrap();
2058
2059        // Crash gap: the provider resource exists, but its ID was never put in
2060        // the journal. Recovery may adopt only the resource carrying this exact
2061        // attempt and generation label.
2062        let mut orphan = restart_attempt(
2063            &root,
2064            &policy,
2065            &image,
2066            "crash-gap-orphan",
2067            0xd105,
2068            "restart-orphan",
2069        );
2070        let (_orphan_handle, _orphan_id) =
2071            prepare_restart_resource(&provider, &policy, &mut orphan);
2072        journal.record_attempt(&orphan).unwrap();
2073
2074        let attempts = journal.uncleaned_ephemeral_attempts().unwrap();
2075        assert_eq!(attempts.len(), 5);
2076        assert!(attempts.iter().all(RunnerAttempt::counts_against_capacity));
2077        assert_eq!(
2078            provider.enumerate_owned(HostId::from_u128(LIVE_HOST)).len(),
2079            5
2080        );
2081        assert!(
2082            !std::fs::read(root.join("attempts.sqlite3"))
2083                .unwrap()
2084                .windows(nonce.len())
2085                .any(|window| window == nonce.as_bytes()),
2086            "the non-secret JIT stand-in reached the durable attempt journal"
2087        );
2088        std::fs::write(root.join("registration-count"), "0\n").unwrap();
2089        std::fs::write(
2090            root.join("seed-complete"),
2091            "prepared starting cleanup_deferred orphaned crash_gap\n",
2092        )
2093        .unwrap();
2094        std::fs::write(
2095            root.join("security-scan-complete"),
2096            "inspect logs history export journal: nonce absent; github registrations=0\n",
2097        )
2098        .unwrap();
2099    }
2100
2101    #[test]
2102    #[ignore = "recovers real managed-WSL resources after the distribution restarts"]
2103    fn live_rootless_managed_wsl_restart_recover() {
2104        let root = restart_fixture_root();
2105        assert!(root.join("seed-complete").is_file());
2106        let journal = SqliteStore::open(root.join("attempts.sqlite3")).unwrap();
2107        let provider = OciProcesses::new(HostId::from_u128(LIVE_HOST));
2108        let nonce = std::env::var("RUNNER_MANAGER_OCI_RESTART_NONCE")
2109            .expect("RUNNER_MANAGER_OCI_RESTART_NONCE must survive in the Windows manifest");
2110        let mut attempts = journal.uncleaned_ephemeral_attempts().unwrap();
2111        assert_eq!(attempts.len(), 5, "the durable journal lost an attempt");
2112        assert!(attempts.iter().all(RunnerAttempt::counts_against_capacity));
2113        let image = match attempts[0].execution() {
2114            AttemptExecution::Isolated { resolved_image, .. } => resolved_image.clone(),
2115            _ => unreachable!(),
2116        };
2117        let owned = provider.enumerate_owned(HostId::from_u128(LIVE_HOST));
2118        assert_eq!(owned.len(), 5, "the remounted provider lost a resource");
2119
2120        for identity in &owned {
2121            let EnvironmentIdentity::Isolated { environment_id, .. } = identity else {
2122                unreachable!()
2123            };
2124            let inspect = podman_ok(&["container", "inspect", environment_id]);
2125            assert!(
2126                !inspect.contains(&nonce),
2127                "nonce reached durable inspect metadata"
2128            );
2129            let logs = podman(&["logs", environment_id]);
2130            assert!(
2131                !logs
2132                    .stdout
2133                    .windows(nonce.len())
2134                    .any(|window| window == nonce.as_bytes())
2135            );
2136            assert!(
2137                !logs
2138                    .stderr
2139                    .windows(nonce.len())
2140                    .any(|window| window == nonce.as_bytes())
2141            );
2142            assert_export_excludes(environment_id, &nonce);
2143        }
2144        let history = podman_ok(&["history", "--no-trunc", image.as_str()]);
2145        assert!(
2146            !history.contains(&nonce),
2147            "nonce reached durable image history"
2148        );
2149        assert!(
2150            !std::fs::read(root.join("attempts.sqlite3"))
2151                .unwrap()
2152                .windows(nonce.len())
2153                .any(|window| window == nonce.as_bytes()),
2154            "nonce reached the durable attempt journal"
2155        );
2156
2157        let clock = FakeClock::default();
2158        for attempt in &mut attempts {
2159            if attempt.state() == AttemptState::Preparing {
2160                let AttemptExecution::Isolated {
2161                    resolved_image,
2162                    generation,
2163                    ..
2164                } = attempt.execution()
2165                else {
2166                    unreachable!()
2167                };
2168                let mut wrong_generation = RunnerAttempt::allocate(
2169                    attempt.id,
2170                    attempt.policy_id,
2171                    attempt.runtime_path(),
2172                    clock.now(),
2173                );
2174                wrong_generation
2175                    .allocate_execution(AttemptExecution::Isolated {
2176                        provider_kind: Backend::Oci,
2177                        environment_id: None,
2178                        resolved_image: resolved_image.clone(),
2179                        generation: format!("{generation}-wrong"),
2180                    })
2181                    .unwrap();
2182                assert_eq!(
2183                    provider.recover(&wrong_generation).unwrap(),
2184                    EnvironmentState::Missing,
2185                    "a different generation adopted the crash-gap resource"
2186                );
2187                assert_eq!(
2188                    provider.recover(attempt).unwrap(),
2189                    EnvironmentState::Starting
2190                );
2191                let identity = owned
2192                    .iter()
2193                    .find(|identity| {
2194                        matches!(identity, EnvironmentIdentity::Isolated {
2195                            attempt: found_attempt,
2196                            generation: found_generation,
2197                            ..
2198                        } if found_attempt == &attempt.id && found_generation == generation)
2199                    })
2200                    .cloned()
2201                    .expect("the exact crash-gap identity is enumerable");
2202                let EnvironmentIdentity::Isolated { environment_id, .. } = identity else {
2203                    unreachable!()
2204                };
2205                attempt.prepared_environment(environment_id).unwrap();
2206                attempt.mark_prepared(clock.now()).unwrap();
2207            }
2208
2209            let state_after_restart = provider.inspect(attempt).unwrap();
2210            assert!(
2211                retained_after_restart(state_after_restart),
2212                "the remounted provider did not retain a recoverable resource: {state_after_restart:?}"
2213            );
2214            match attempt.state() {
2215                AttemptState::Prepared => {
2216                    attempt
2217                        .conclude(AttemptOutcome::Orphaned, clock.now())
2218                        .unwrap();
2219                    attempt.begin_destroy(clock.now()).unwrap();
2220                }
2221                AttemptState::Starting => {
2222                    attempt
2223                        .conclude(AttemptOutcome::Orphaned, clock.now())
2224                        .unwrap();
2225                    attempt.begin_destroy(clock.now()).unwrap();
2226                }
2227                AttemptState::Orphaned | AttemptState::CleanupDeferred => {
2228                    attempt.begin_destroy(clock.now()).unwrap()
2229                }
2230                state => panic!("unexpected restart state {state}"),
2231            }
2232            assert_eq!(
2233                provider.destroy(attempt).unwrap(),
2234                ProviderDestroy::Destroyed
2235            );
2236            attempt.clean_isolated(clock.now()).unwrap();
2237            journal.record_attempt(attempt).unwrap();
2238        }
2239
2240        assert!(journal.uncleaned_ephemeral_attempts().unwrap().is_empty());
2241        assert!(
2242            provider
2243                .enumerate_owned(HostId::from_u128(LIVE_HOST))
2244                .is_empty()
2245        );
2246        assert_eq!(
2247            std::fs::read_to_string(root.join("registration-count")).unwrap(),
2248            "0\n",
2249            "restart recovery attempted a second JIT registration"
2250        );
2251        std::fs::write(
2252            root.join("recovery-complete"),
2253            "adopted destroyed capacity=0 registrations=0\n",
2254        )
2255        .unwrap();
2256    }
2257
2258    #[test]
2259    #[ignore = "requires the CI-provisioned native rootless Podman/XFS project-quota fixture"]
2260    fn live_rootless_native_acceptance() {
2261        run_live_rootless_acceptance(false);
2262    }
2263
2264    #[test]
2265    #[ignore = "requires a root-owned bounded-storage helper fixture"]
2266    fn live_rootless_bounded_storage_acceptance() {
2267        run_live_rootless_acceptance(true);
2268    }
2269
2270    #[test]
2271    #[ignore = "requires a queued same-repository Actions job and a real JIT config on stdin"]
2272    fn live_rootless_github_jit_acceptance() {
2273        let image = ImageReference::new(
2274            std::env::var(LIVE_IMAGE_ENV)
2275                .unwrap_or_else(|_| panic!("{LIVE_IMAGE_ENV} must name a pinned image digest")),
2276        )
2277        .unwrap();
2278        let runner_root = PathBuf::from(
2279            std::env::var("RUNNER_MANAGER_OCI_JIT_RUNNER_DIR")
2280                .expect("RUNNER_MANAGER_OCI_JIT_RUNNER_DIR must name the extracted runner package"),
2281        );
2282        assert!(runner_root.is_absolute());
2283        assert!(!runner_root.starts_with("/mnt"));
2284        assert!(runner_root.join("bin/Runner.Listener").is_file());
2285
2286        let mut jit = String::new();
2287        std::io::stdin()
2288            .read_to_string(&mut jit)
2289            .expect("JIT stdin could not be read");
2290        while matches!(jit.as_bytes().last(), Some(b'\n' | b'\r')) {
2291            jit.pop();
2292        }
2293        assert!(!jit.is_empty(), "JIT stdin was empty");
2294        assert!(
2295            jit.len() <= 64 * 1024,
2296            "JIT stdin exceeded the provider limit"
2297        );
2298        assert!(
2299            !jit.bytes()
2300                .any(|byte| byte == b'\n' || byte == b'\r' || byte == 0),
2301            "JIT stdin contained a forbidden delimiter"
2302        );
2303
2304        let provider = OciProcesses::new(HostId::from_u128(LIVE_HOST));
2305        let policy = isolated_policy(image.clone());
2306        assert_eq!(provider.probe(&policy), ProviderCapability::Ready);
2307        let resolution = provider.resolve(&policy).unwrap().unwrap();
2308        assert_eq!(resolution.provider_kind, Backend::Oci);
2309        assert_eq!(resolution.image, image);
2310
2311        let mut attempt = RunnerAttempt::allocate(
2312            AttemptId::new_random(),
2313            policy.id,
2314            &runner_root,
2315            FakeClock::default().now(),
2316        );
2317        attempt
2318            .allocate_execution(AttemptExecution::Isolated {
2319                provider_kind: Backend::Oci,
2320                environment_id: None,
2321                resolved_image: image.clone(),
2322                generation: "github-jit".into(),
2323            })
2324            .unwrap();
2325        let prepared = provider.prepare(&attempt, &policy).unwrap();
2326        let EnvironmentIdentity::Isolated { environment_id, .. } =
2327            prepared.identity().cloned().expect("isolated identity")
2328        else {
2329            panic!("OCI prepare returned a native identity")
2330        };
2331        attempt
2332            .prepared_environment(environment_id.clone())
2333            .unwrap();
2334        let config = EncodedJitConfig::new(std::mem::take(&mut jit));
2335        provider
2336            .start(prepared, &attempt, OneTimeJitHandoff::new(&config))
2337            .unwrap();
2338
2339        let started = wait_for_container_file(
2340            &environment_id,
2341            "/tmp/runner-manager-actions-job-started",
2342            Instant::now() + Duration::from_secs(300),
2343        );
2344        assert!(
2345            started,
2346            "the queued Actions job was not claimed within five minutes"
2347        );
2348        assert_live_jit_absent(&environment_id, &image, config.expose());
2349        assert!(
2350            podman(&[
2351                "exec",
2352                &environment_id,
2353                "touch",
2354                "/tmp/runner-manager-provider-inspected",
2355            ])
2356            .status
2357            .success(),
2358            "could not release the Actions job after provider-side inspection"
2359        );
2360
2361        let completed = wait_for_container_file(
2362            &environment_id,
2363            "/tmp/runner-manager-actions-job-complete",
2364            Instant::now() + Duration::from_secs(600),
2365        );
2366        assert!(
2367            completed,
2368            "the Actions marker step did not complete within ten minutes"
2369        );
2370        let exit_deadline = Instant::now() + Duration::from_secs(120);
2371        while provider.inspect(&attempt).unwrap() != EnvironmentState::Exited {
2372            assert!(
2373                Instant::now() < exit_deadline,
2374                "the one-time runner did not exit after its job"
2375            );
2376            std::thread::sleep(Duration::from_millis(250));
2377        }
2378        assert_export_excludes(&environment_id, config.expose());
2379        assert_eq!(
2380            provider.destroy(&attempt).unwrap(),
2381            ProviderDestroy::Destroyed
2382        );
2383        assert_eq!(
2384            provider.inspect(&attempt).unwrap(),
2385            EnvironmentState::Missing
2386        );
2387        eprintln!("live GitHub JIT job completed through the OCI provider; evidence is redacted");
2388    }
2389
2390    #[test]
2391    #[ignore = "requires a real rootless Podman fixture with unavailable writable-layer quota"]
2392    fn live_rootless_quota_refusal_is_typed_before_jit() {
2393        let provider = OciProcesses::new(HostId::from_u128(1));
2394        assert_eq!(provider.ready(), ProviderCapability::DiskQuotaUnavailable);
2395    }
2396}