Skip to main content

subc_daemon/
app_open.rs

1//! `app.open`: start a known operator app from its installed location.
2//!
3//! The decision order is fixed and checked top to bottom: `app_open_not_used`
4//! on macOS (which never launches through the daemon) and on platforms without
5//! a launcher, `app_open_disabled` when the platform switch is off,
6//! `app_unknown` for an app the compiled table does not name,
7//! `already_running` while a launch entry is live, `app_not_installed` when
8//! the installed file is missing, and only then verification and launch.
9//!
10//! Launch entries live in one table behind one lock. The lock is a leaf: take
11//! no other lock while holding it. An entry holds the daemon-generated incarnation id, the launched
12//! pid, and the platform liveness handle: a pidfd on Linux, the owned process
13//! handle on Windows. Liveness is read from that handle, never by reopening
14//! the numeric pid, so a reused pid confers nothing. On Windows the entry is
15//! published before the image is resumed, so a child that connects at once
16//! is matched. On Linux the entry is published after spawn and tracking, so
17//! the image may run first, which is safe because Linux connections are
18//! never stamped. Entries retire when no longer live. The table is memory-only: a daemon or installed-service
19//! restart drops it, and a relaunched daemon never mistakes an older process
20//! for its own launch. Connections from such a process are plain `direct`.
21//!
22//! Starting the app grants nothing by itself: a shortcut still needs a
23//! stamped connection. (A Windows stamp records the live entry's incarnation
24//! at connection time; nothing revalidates it yet.) So `app.open` is classified
25//! `None` in the privileged-operation classifier and neither prompts in
26//! `enforce` mode nor logs in `log` mode.
27
28use std::{
29    collections::HashMap,
30    path::PathBuf,
31    sync::{
32        atomic::{AtomicU64, Ordering},
33        Mutex, MutexGuard,
34    },
35};
36
37/// Filesystem paths only exist on platforms with a launcher; the decision and
38/// table code below names locations through `PathBuf` alone.
39#[cfg(any(windows, target_os = "linux"))]
40use std::path::Path;
41
42use semver::Version;
43
44use crate::{
45    control::ControlHandler,
46    operator_apps::{AppOpenPlatform, OperatorAppPolicy},
47    router::{RouteCtx, RouterError},
48    Frame,
49};
50
51/// One live-or-recently-live launch slot. At most one entry per app exists.
52pub(crate) struct LaunchEntry {
53    incarnation: u64,
54    pid: u32,
55    start_time: Option<u64>,
56    process: subc_os::Process,
57    child: Option<std::process::Child>,
58}
59
60impl LaunchEntry {
61    /// Whether the retained handle still reports this exact process alive.
62    /// The stored start time must match the current observation, so a pid the
63    /// kernel has since handed to another process reads as dead even on
64    /// platforms whose handle cannot pin the incarnation by itself.
65    fn is_live(&self) -> bool {
66        self.process
67            .observe()
68            .is_some_and(|observed| Some(observed.start_time) == self.start_time)
69    }
70
71    /// Release a retired entry's handles without signalling anything:
72    /// dropping the entry never stops a live child, and an exited direct
73    /// child is reaped so it never lingers as a zombie. The daemon never signals here: liveness-triggered retirement
74    /// follows an observed exit, and `retire` or a `publish` replacement only
75    /// drops the handles and reaps what already exited.
76    fn reap(self) {
77        if let Some(mut child) = self.child {
78            // Our own direct child, if it already exited: release its pid.
79            let _ = child.try_wait();
80        }
81    }
82
83    /// Stop a launch that failed after the child existed but before it could
84    /// run: kill the process the daemon still holds, then release it. Used
85    /// only on paths that refuse the launch, never on a running app.
86    #[cfg(windows)]
87    fn stop_rejected(mut self) {
88        if let Some(mut child) = self.child.take() {
89            let _ = child.kill();
90            while matches!(child.try_wait(), Ok(None)) {
91                std::thread::yield_now();
92            }
93        }
94        // Dropping `process` closes the retained handle; a suspended child
95        // killed above is already gone, and killing an exited child is a
96        // harmless error.
97    }
98}
99
100/// The pid and incarnation of a live launch entry, for replies and stamps.
101#[derive(Clone, Copy, Debug, PartialEq, Eq)]
102pub(crate) struct LiveLaunch {
103    pub incarnation: u64,
104    pub pid: u32,
105}
106
107/// One launch table for the daemon, behind one leaf lock. No other lock is
108/// taken while it is held.
109pub(crate) struct LaunchTable {
110    inner: Mutex<HashMap<String, LaunchEntry>>,
111    next_incarnation: AtomicU64,
112}
113
114/// The methods run per platform and in tests: `publish` and friends launch
115/// on Windows and Linux, while other builds only exercise them under test.
116/// (Check builds without test code would otherwise call the idle ones dead.)
117#[allow(dead_code)]
118impl LaunchTable {
119    pub fn new() -> Self {
120        Self {
121            inner: Mutex::new(HashMap::new()),
122            next_incarnation: AtomicU64::new(1),
123        }
124    }
125
126    fn lock(&self) -> MutexGuard<'_, HashMap<String, LaunchEntry>> {
127        self.inner
128            .lock()
129            .unwrap_or_else(|poisoned| poisoned.into_inner())
130    }
131
132    fn retire_locked(inner: &mut HashMap<String, LaunchEntry>, app: &str) {
133        if let Some(entry) = inner.remove(app) {
134            entry.reap();
135        }
136    }
137
138    /// The live entry for `app`, retiring it first when its handle reports
139    /// exit. A dead entry never matches again, even through an inherited
140    /// socket or pipe handle, and even after `app.open` launches a
141    /// replacement with a new incarnation.
142    pub fn live_entry(&self, app: &str) -> Option<LiveLaunch> {
143        let mut inner = self.lock();
144        let entry = inner.get(app)?;
145        if !entry.is_live() {
146            Self::retire_locked(&mut inner, app);
147            return None;
148        }
149        Some(LiveLaunch {
150            incarnation: entry.incarnation,
151            pid: entry.pid,
152        })
153    }
154
155    /// The incarnation whose entry is live for `pid`: a pipe client is
156    /// eligible only when its pid is that of a live launch entry.
157    pub fn match_live_pid(&self, app: &str, pid: u32) -> Option<u64> {
158        let live = self.live_entry(app)?;
159        (live.pid == pid).then_some(live.incarnation)
160    }
161
162    /// Whether `incarnation` is still the live entry for `app`. A later entry
163    /// for the same app never revalidates an older stamp.
164    pub fn is_live_incarnation(&self, app: &str, incarnation: u64) -> bool {
165        self.with_live_incarnation(app, incarnation, || ())
166            .is_some()
167    }
168
169    /// Keep retirement and replacement excluded until the caller commits its
170    /// decision. The caller already holds every other lock it needs.
171    pub(crate) fn with_live_incarnation<T>(
172        &self,
173        app: &str,
174        incarnation: u64,
175        commit: impl FnOnce() -> T,
176    ) -> Option<T> {
177        let mut inner = self.lock();
178        let entry = inner.get(app)?;
179        if !entry.is_live() {
180            Self::retire_locked(&mut inner, app);
181            return None;
182        }
183        (entry.incarnation == incarnation).then(commit)
184    }
185
186    /// Publish a launch entry, replacing any entry for the app. Callers retire
187    /// dead entries through the liveness check first, so a replaced entry was
188    /// already retired and its handles are closed here.
189    pub fn publish(
190        &self,
191        app: &str,
192        pid: u32,
193        process: subc_os::Process,
194        child: Option<std::process::Child>,
195    ) -> u64 {
196        let incarnation = self.next_incarnation.fetch_add(1, Ordering::Relaxed);
197        let start_time = process.observe().map(|observed| observed.start_time);
198        let mut inner = self.lock();
199        Self::retire_locked(&mut inner, app);
200        inner.insert(
201            app.to_owned(),
202            LaunchEntry {
203                incarnation,
204                pid,
205                start_time,
206                process,
207                child,
208            },
209        );
210        incarnation
211    }
212
213    /// Forget the entry without signalling the process: the launched app
214    /// survives a daemon or installed-service restart by design.
215    pub fn retire(&self, app: &str) {
216        Self::retire_locked(&mut self.lock(), app);
217    }
218
219    /// Take the entry for a launch that must be stopped after publishing,
220    /// such as a child that cannot be resumed. The caller stops the returned
221    /// entry; nothing else in the table refers to the pid afterwards.
222    #[cfg(windows)]
223    pub fn take(&self, app: &str) -> Option<LaunchEntry> {
224        self.lock().remove(app)
225    }
226}
227
228/// Why `app.open` refused to launch.
229#[derive(Debug)]
230pub(crate) struct AppOpenRefusal {
231    pub code: &'static str,
232    pub message: String,
233}
234
235impl AppOpenRefusal {
236    fn not_used(message: impl Into<String>) -> Self {
237        Self {
238            code: subc_control::APP_OPEN_NOT_USED,
239            message: message.into(),
240        }
241    }
242
243    fn disabled(message: impl Into<String>) -> Self {
244        Self {
245            code: subc_control::APP_OPEN_DISABLED,
246            message: message.into(),
247        }
248    }
249
250    fn unknown(message: impl Into<String>) -> Self {
251        Self {
252            code: subc_control::APP_UNKNOWN,
253            message: message.into(),
254        }
255    }
256
257    pub fn not_installed(message: impl Into<String>) -> Self {
258        Self {
259            code: subc_control::APP_NOT_INSTALLED,
260            message: message.into(),
261        }
262    }
263
264    /// Refusal when the installed binary fails the daemon's checks. Only the
265    /// Windows launch path verifies, and only with an injected test check:
266    /// production carries no verifier and fails closed here. Where the daemon
267    /// verifies, the test hook receives the expected publisher, the daemon
268    /// enforces the floor itself on the returned version, and the held
269    /// handle pins the file throughout.
270    #[cfg(windows)]
271    pub fn verification_failed(message: impl Into<String>) -> Self {
272        Self {
273            code: subc_control::APP_VERIFICATION_FAILED,
274            message: message.into(),
275        }
276    }
277}
278
279/// What the ordered checks decided, before any verification or process starts.
280pub(crate) enum AppOpenDecision {
281    Refuse(AppOpenRefusal),
282    AlreadyRunning { pid: u32 },
283    Launch { path: PathBuf },
284}
285
286/// The fixed order: `app_open_not_used` (macOS, or a platform without a
287/// launcher), `app_open_disabled` (platform switch off), `app_unknown`,
288/// retire-or-`already_running`, `app_not_installed`, then launch.
289pub(crate) fn decide_app_open(
290    policy: &OperatorAppPolicy,
291    table: &LaunchTable,
292    platform: AppOpenPlatform,
293    app: &str,
294) -> AppOpenDecision {
295    if matches!(platform, AppOpenPlatform::MacOS | AppOpenPlatform::Other) {
296        return AppOpenDecision::Refuse(AppOpenRefusal::not_used(
297            "this platform never launches apps through the daemon",
298        ));
299    }
300    if !policy.switch_enabled(platform) {
301        return AppOpenDecision::Refuse(AppOpenRefusal::disabled(
302            "app.open is switched off on this platform",
303        ));
304    }
305    if policy.app_id().is_none_or(|id| id != app) {
306        return AppOpenDecision::Refuse(AppOpenRefusal::unknown(format!(
307            "no compiled app named {app:?} on this platform"
308        )));
309    }
310    if let Some(live) = table.live_entry(app) {
311        // A live entry answers `already_running` even when the installed file
312        // has since vanished: the running process is what the caller asked
313        // about, and the next call after its exit relaunches and re-checks
314        // the install. The daemon starts nothing and relays nothing here.
315        return AppOpenDecision::AlreadyRunning { pid: live.pid };
316    }
317    let Some(path) = policy.installed_path(platform) else {
318        return AppOpenDecision::Refuse(AppOpenRefusal::not_installed(format!(
319            "no install location is compiled in for {app:?}"
320        )));
321    };
322    if !path.exists() {
323        return AppOpenDecision::Refuse(AppOpenRefusal::not_installed(format!(
324            "{} is not installed at {}",
325            app,
326            path.display()
327        )));
328    }
329    AppOpenDecision::Launch { path }
330}
331impl ControlHandler {
332    /// Serve one `app.open` call: run the ordered checks, then verify and
333    /// launch, or report the already-running pid. Like `operator.confirm`
334    /// this is probed before the module branch, so any connection can ask;
335    /// the launch itself grants nothing, and a shortcut still needs a stamped
336    /// connection.
337    pub(crate) async fn handle_app_open(
338        &self,
339        _ctx: &RouteCtx,
340        frame: Frame,
341    ) -> Result<Vec<Frame>, RouterError> {
342        // One launch at a time per handler: the liveness check in the
343        // decision and the later publish must not interleave across
344        // concurrent calls, or two calls could both launch and the second
345        // publish would orphan the first process. The guard covers the
346        // whole call; `app.open` is rare, so refusals sharing it cost
347        // nothing.
348        let _launch_guard = self.app_open_launch_lock.lock().await;
349        let request = match serde_json::from_slice::<subc_control::AppOpenRequest>(&frame.body) {
350            Ok(request) => request,
351            Err(_) => {
352                return Ok(vec![crate::control::control_error_frame(
353                    &frame,
354                    "invalid_control_body",
355                    "malformed app.open body",
356                )?]);
357            }
358        };
359        let app = request.app.clone();
360        let platform = AppOpenPlatform::current();
361        #[cfg(test)]
362        let platform = self.app_open_test_platform.unwrap_or(platform);
363        match decide_app_open(
364            &self.operator_app_policy,
365            &self.launch_table,
366            platform,
367            &app,
368        ) {
369            AppOpenDecision::Refuse(refusal) => Ok(vec![crate::control::control_error_frame(
370                &frame,
371                refusal.code,
372                refusal.message,
373            )?]),
374            AppOpenDecision::AlreadyRunning { pid } => {
375                // `already_running` starts nothing and relays nothing: on
376                // Windows it calls the optional attention hook (production
377                // only logs), and nothing at all happens on Linux.
378                #[cfg(windows)]
379                self.flash_running_app(pid);
380                Ok(vec![crate::control::control_response_body_frame(
381                    &frame,
382                    &subc_control::AppOpenReply::already_running(pid),
383                    "app.open",
384                )?])
385            }
386            AppOpenDecision::Launch { path } => {
387                let outcome = self.launch_app(&app, &path).await;
388                match outcome {
389                    Ok(pid) => Ok(vec![crate::control::control_response_body_frame(
390                        &frame,
391                        &subc_control::AppOpenReply::launched(pid),
392                        "app.open",
393                    )?]),
394                    Err(refusal) => Ok(vec![crate::control::control_error_frame(
395                        &frame,
396                        refusal.code,
397                        refusal.message,
398                    )?]),
399                }
400            }
401        }
402    }
403
404    async fn launch_app(&self, app: &str, path: &std::path::Path) -> Result<u32, AppOpenRefusal> {
405        #[cfg(test)]
406        if let Some(launch) = self.app_open_test_launch {
407            return launch();
408        }
409        #[cfg(windows)]
410        {
411            self.windows_launch_app(app, path).await
412        }
413        #[cfg(target_os = "linux")]
414        {
415            self.linux_launch_app(app, path).await
416        }
417        #[cfg(not(any(windows, target_os = "linux")))]
418        {
419            // The ordered platform check refuses before launching on these hosts.
420            let _ = (app, path);
421            Err(AppOpenRefusal::not_used(
422                "this platform has no app launcher",
423            ))
424        }
425    }
426}
427
428/// How a Linux launch is started. With `systemd-run` and a user bus the app
429/// runs in its own transient scope, so the daemon unit's `KillMode=mixed`
430/// cleanup never reaches it. Otherwise the child only gets its own process
431/// group: that separates signals but does not move it out of a service
432/// cgroup, so service cleanup can still stop it. Either way the daemon holds
433/// the pidfd for its launch entry.
434#[cfg(target_os = "linux")]
435#[derive(Clone, Copy, Debug, PartialEq, Eq)]
436pub(crate) enum LinuxLaunchStyle {
437    Scope,
438    Direct,
439}
440
441/// Pick the launch style from what the machine offers: a `systemd-run`
442/// binary plus a reachable user bus means a user manager is present.
443#[cfg(target_os = "linux")]
444pub(crate) fn select_linux_launch_style(
445    systemd_run_present: bool,
446    user_bus_present: bool,
447) -> LinuxLaunchStyle {
448    if systemd_run_present && user_bus_present {
449        LinuxLaunchStyle::Scope
450    } else {
451        LinuxLaunchStyle::Direct
452    }
453}
454
455/// Whether the current user has a systemd user manager: the runtime
456/// directory's bus socket exists. The system per-user path is checked too, so
457/// a detection made before `XDG_RUNTIME_DIR` is set still finds the manager.
458#[cfg(target_os = "linux")]
459fn user_bus_present() -> bool {
460    use std::os::unix::fs::FileTypeExt as _;
461
462    let uid = rustix::process::getuid().as_raw();
463    [
464        std::env::var_os("XDG_RUNTIME_DIR").map(PathBuf::from),
465        Some(PathBuf::from(format!("/run/user/{uid}"))),
466    ]
467    .into_iter()
468    .flatten()
469    .any(|dir| {
470        // The socket's presence is the manager's presence: no manager leaves
471        // no bus behind, and a missing path fails the check harmlessly.
472        std::fs::symlink_metadata(dir.join("bus"))
473            .is_ok_and(|metadata| metadata.file_type().is_socket())
474    })
475}
476
477/// Whether `name` names an executable regular file on `PATH`.
478#[cfg(target_os = "linux")]
479fn find_on_path(name: &str) -> bool {
480    use std::os::unix::fs::PermissionsExt as _;
481
482    let Some(path) = std::env::var_os("PATH") else {
483        return false;
484    };
485    std::env::split_paths(&path).any(|dir| {
486        let candidate = dir.join(name);
487        candidate.is_file()
488            && candidate
489                .metadata()
490                .is_ok_and(|metadata| metadata.permissions().mode() & 0o111 != 0)
491    })
492}
493
494/// The scope wrapper: `systemd-run` starts the scope and exits, so the app's
495/// pid is read from the wrapper's stdout. The wrapper echoes its own pid and
496/// execs the app, which keeps the pid; what the daemon opens the pidfd on is
497/// the app itself.
498#[cfg(target_os = "linux")]
499pub(crate) fn systemd_run_command(path: &Path) -> tokio::process::Command {
500    let mut command = tokio::process::Command::new("systemd-run");
501    command.args([
502        "--user",
503        "--scope",
504        "--",
505        "/bin/sh",
506        "-c",
507        "echo $$; exec \"$0\" \"$@\"",
508        &path.display().to_string(),
509    ]);
510    command
511}
512
513/// A clean launch environment still carries everything except the loader
514/// overrides: dropping `LD_PRELOAD`, `LD_LIBRARY_PATH` and `LD_AUDIT` keeps
515/// a same-user process from injecting code into the app, while keeping `HOME`,
516/// `DISPLAY`, `XDG_RUNTIME_DIR` and the rest the app needs to run. A fully
517/// cleared environment would break the app the same way it once broke
518/// supervised modules (which lost `HOME` and `XDG_RUNTIME_DIR` under an
519/// `env_clear` until the daemon stopped clearing).
520#[cfg(target_os = "linux")]
521fn scrub_app_environment(command: &mut std::process::Command) {
522    for key in ["LD_PRELOAD", "LD_LIBRARY_PATH", "LD_AUDIT"] {
523        command.env_remove(key);
524    }
525}
526
527#[cfg(target_os = "linux")]
528impl ControlHandler {
529    /// Launch the installed Linux app and record its entry. Under a user
530    /// manager the app runs in its own transient scope; without one it gets
531    /// its own process group. The entry is recorded but never stamped: no
532    /// connection from a launched process is ever eligible.
533    async fn linux_launch_app(&self, app: &str, path: &Path) -> Result<u32, AppOpenRefusal> {
534        let style = if self.operator_app_policy.linux_force_direct {
535            LinuxLaunchStyle::Direct
536        } else {
537            select_linux_launch_style(find_on_path("systemd-run"), user_bus_present())
538        };
539        match style {
540            LinuxLaunchStyle::Direct => self.linux_launch_direct(app, path, &[]),
541            LinuxLaunchStyle::Scope => self.linux_launch_scoped(app, path).await,
542        }
543    }
544
545    /// Start the app as our own child in its own process group, with a clean
546    /// environment, and hold its pidfd. The child is never waited on until
547    /// its entry retires, so its pid cannot be reused while tracked.
548    ///
549    /// `extra_env` exists for tests, which poison the loader overrides on the
550    /// command to prove the scrub removes them. Production always passes an
551    /// empty slice: the command otherwise inherits the daemon environment.
552    fn linux_launch_direct(
553        &self,
554        app: &str,
555        path: &Path,
556        extra_env: &[(&str, &str)],
557    ) -> Result<u32, AppOpenRefusal> {
558        use std::os::unix::process::CommandExt as _;
559
560        let mut command = std::process::Command::new(path);
561        // Test-only poison rides the command, never the process environment,
562        // so parallel tests spawning children cannot observe it.
563        for (key, value) in extra_env {
564            command.env(key, value);
565        }
566        // Our own process group, so nothing signaling the daemon's group
567        // reaches the app. This does not move the app out of a service
568        // cgroup, so a service manager's cleanup can still stop it (a session
569        // would need a post-fork `setsid` no safe code here can run). The
570        // group plus the pidfd are the containment.
571        command.process_group(0);
572        scrub_app_environment(&mut command);
573        command
574            .stdin(std::process::Stdio::null())
575            .stdout(std::process::Stdio::null())
576            .stderr(std::process::Stdio::null());
577        let mut child = command.spawn().map_err(|error| {
578            AppOpenRefusal::not_installed(format!(
579                "installed file {} could not be started: {error}",
580                path.display()
581            ))
582        })?;
583        let pid = child.id();
584        let process = subc_os::Process::open(pid).map_err(|error| {
585            AppOpenRefusal::not_installed(format!(
586                "launched process {pid} cannot be tracked: {error}"
587            ))
588        })?;
589        let Some(process) = process else {
590            // Exited before it could be tracked: stop anything left and
591            // refuse, rather than report a launch with no entry behind it.
592            let _ = child.kill();
593            while matches!(child.try_wait(), Ok(None)) {
594                std::thread::yield_now();
595            }
596            return Err(AppOpenRefusal::not_installed(format!(
597                "installed file {} exited before it could be tracked",
598                path.display()
599            )));
600        };
601        self.launch_table.publish(app, pid, process, Some(child));
602        Ok(pid)
603    }
604
605    /// Start the app in its own transient user scope and open a pidfd on the
606    /// reported pid. A scope child is not ours, so no `Child` is retained and
607    /// the user manager reaps it; the pidfd still reports its exit.
608    async fn linux_launch_scoped(&self, app: &str, path: &Path) -> Result<u32, AppOpenRefusal> {
609        use tokio::io::AsyncBufReadExt as _;
610
611        let mut command = systemd_run_command(path);
612        scrub_app_environment_std(&mut command);
613        command
614            .stdin(std::process::Stdio::null())
615            .stdout(std::process::Stdio::piped())
616            .stderr(std::process::Stdio::null())
617            .kill_on_drop(true);
618        let mut child = command.spawn().map_err(|error| {
619            AppOpenRefusal::not_installed(format!("transient scope could not start: {error}"))
620        })?;
621        let stdout = child.stdout.take().ok_or_else(|| {
622            AppOpenRefusal::not_installed("transient scope reported no pid".to_string())
623        })?;
624        let mut lines = tokio::io::BufReader::new(stdout).lines();
625        let pid_line = tokio::time::timeout(std::time::Duration::from_secs(10), lines.next_line())
626            .await
627            .map_err(|_| {
628                AppOpenRefusal::not_installed(
629                    "transient scope did not report its pid in time".to_string(),
630                )
631            })?
632            .map_err(|error| {
633                AppOpenRefusal::not_installed(format!(
634                    "transient scope pid could not be read: {error}"
635                ))
636            })?
637            .ok_or_else(|| {
638                AppOpenRefusal::not_installed(
639                    "transient scope exited without reporting its pid".to_string(),
640                )
641            })?;
642        let pid: u32 = pid_line.trim().parse().map_err(|_| {
643            AppOpenRefusal::not_installed(format!(
644                "transient scope reported an unparsable pid: {pid_line:?}"
645            ))
646        })?;
647        // Reap the scope starter: it exits once the scope runs. A timeout here
648        // kills the starter, never the scope, and refuses a launch whose
649        // bookkeeping did not finish.
650        let status = tokio::time::timeout(std::time::Duration::from_secs(10), child.wait())
651            .await
652            .map_err(|_| {
653                AppOpenRefusal::not_installed(
654                    "transient scope starter did not exit in time".to_string(),
655                )
656            })?
657            .map_err(|error| {
658                AppOpenRefusal::not_installed(format!(
659                    "transient scope starter could not be reaped: {error}"
660                ))
661            })?;
662        if !status.success() {
663            return Err(AppOpenRefusal::not_installed(format!(
664                "transient scope starter exited with {status}"
665            )));
666        }
667        let process = subc_os::Process::open(pid).map_err(|error| {
668            AppOpenRefusal::not_installed(format!(
669                "scoped process {pid} cannot be tracked: {error}"
670            ))
671        })?;
672        let Some(process) = process else {
673            return Err(AppOpenRefusal::not_installed(format!(
674                "scoped process {pid} exited before it could be tracked"
675            )));
676        };
677        self.launch_table.publish(app, pid, process, None);
678        Ok(pid)
679    }
680}
681
682/// Mirror of [`scrub_app_environment`] for a Tokio command: the scope starter
683/// passes its environment to the app, so the loader overrides are removed
684/// from the starter itself.
685#[cfg(target_os = "linux")]
686fn scrub_app_environment_std(command: &mut tokio::process::Command) {
687    for key in ["LD_PRELOAD", "LD_LIBRARY_PATH", "LD_AUDIT"] {
688        command.env_remove(key);
689    }
690}
691/// The request passed to the injected Windows check, beside the held
692/// capture: the publisher the file's signature must name, the floor its
693/// signed version must meet, and the installed path. The check receives the
694/// held capture and must read that, never reopen `path`, which is for
695/// messages only. Production carries no verifier yet and fails closed.
696///
697/// Public like `crate::operator_apps::TestOperatorAppPolicy`: it crosses
698/// the test-support boundary in `with_test_windows_verifier`.
699#[allow(dead_code)]
700#[derive(Clone, Debug)]
701pub struct WindowsVerifyRequest {
702    pub app: String,
703    pub publisher: Option<String>,
704    pub floor: Version,
705    pub path: PathBuf,
706}
707
708/// The Windows signature check, injected in tests. It answers the verified
709/// version string or the reason verification failed; the daemon enforces the
710/// floor itself on the returned version, so a below-floor binary is refused
711/// even when the checker passes it through. The check runs on the held
712/// capture; the test hook may ignore the handle. Production builds carry no
713/// checker: with the publisher unset, the production table never reaches
714/// verification, so an unverified binary never launches.
715#[allow(dead_code)]
716#[cfg(windows)]
717pub type WindowsVerifyFn = std::sync::Arc<
718    dyn Fn(&subc_os::ExecutableCapture, &WindowsVerifyRequest) -> Result<String, String>
719        + Send
720        + Sync,
721>;
722
723/// A test-only fault hook for opening the tracking handle on a launched pid.
724/// The daemon stops a launch it cannot track; the hook makes that open fail
725/// so a test can prove nothing is left running.
726#[allow(dead_code)]
727#[cfg(windows)]
728pub type WindowsTrackFn =
729    std::sync::Arc<dyn Fn(u32) -> std::io::Result<Option<subc_os::Process>> + Send + Sync>;
730
731/// The already-running attention request, injected in tests. The default only
732/// logs: starting nothing and relaying nothing is the guarantee, and the
733/// flash itself is best effort.
734#[allow(dead_code)]
735#[cfg(windows)]
736pub type WindowsFlashFn = std::sync::Arc<dyn Fn(u32) + Send + Sync>;
737
738/// What the Windows launch puts in `creation_flags`: suspended so the child
739/// cannot run before it is bound, without a console window, and breaking
740/// away so it never joins the daemon's root job (`winbase.h`).
741/// Tests can omit the breakaway bit where the sandbox job forbids it: a test
742/// handler creates no job, so a plain spawn is already outside one,
743/// while production always sets it and fails closed when the job forbids it.
744#[cfg(windows)]
745const CREATE_BREAKAWAY_FROM_JOB: u32 = 0x0100_0000;
746
747#[cfg(windows)]
748pub(crate) fn windows_creation_flags(breakaway: bool) -> u32 {
749    let mut flags = subc_jobobject::CONTAINMENT_CREATION_FLAGS;
750    if breakaway {
751        flags |= CREATE_BREAKAWAY_FROM_JOB;
752    }
753    flags
754}
755
756#[cfg(windows)]
757impl ControlHandler {
758    /// Call the optional attention hook for an already-running app. Only
759    /// Windows has one, and production only logs; Linux does nothing, and
760    /// macOS never reaches `already_running`.
761    fn flash_running_app(&self, pid: u32) {
762        #[cfg(windows)]
763        if let Some(flash) = self.windows_flash.as_ref() {
764            flash(pid);
765            return;
766        }
767        tracing::debug!(
768            pid,
769            "app already running; no window-flash primitive in this build"
770        );
771    }
772
773    /// Verify the held file's signature and floor. With no checker configured
774    /// verification fails closed: an unverified binary never launches, so a
775    /// substitution, a wrong publisher, an unsigned binary and a below-floor
776    /// binary are all refused with `app_verification_failed` and stamp
777    /// nothing. The check runs on the held capture; production carries no
778    /// checker and fails closed here.
779    fn verify_windows_image(
780        &self,
781        capture: &subc_os::ExecutableCapture,
782        request: WindowsVerifyRequest,
783    ) -> Result<String, AppOpenRefusal> {
784        #[cfg(windows)]
785        if let Some(verify) = self.windows_verify.as_ref() {
786            let version = verify(capture, &request).map_err(AppOpenRefusal::verification_failed)?;
787            if !crate::operator_apps::meets_release_floor(Some(&version), &request.floor) {
788                return Err(AppOpenRefusal::verification_failed(format!(
789                    "verified version {version} is below the release floor"
790                )));
791            }
792            return Ok(version);
793        }
794        Err(AppOpenRefusal::verification_failed(format!(
795            "this build carries no Authenticode verifier for {}",
796            request.app
797        )))
798    }
799
800    /// Open a tracking handle on the launched pid. Tests can fail this step
801    /// through `with_test_windows_track` to prove a launch that cannot be
802    /// tracked is stopped, never left running.
803    fn track_launched_process(&self, pid: u32) -> std::io::Result<Option<subc_os::Process>> {
804        #[cfg(windows)]
805        if let Some(track) = self.windows_track.as_ref() {
806            return track(pid);
807        }
808        subc_os::Process::open(pid)
809    }
810
811    /// Verify, launch suspended outside the daemon's root job, compare the image
812    /// identity, and resume or refuse. Every failure after the child exists
813    /// stops it and refuses, and a failure before that refuses with no child
814    /// to stop: no process is ever left running unverified, and
815    /// a substitution of the path or a parent directory between verification
816    /// and process creation fails the image comparison and stamps nothing.
817    async fn windows_launch_app(&self, app: &str, path: &Path) -> Result<u32, AppOpenRefusal> {
818        use std::os::windows::process::CommandExt as _;
819
820        // Pin the installed file with read sharing only: no write or delete
821        // sharing, so the name cannot be renamed or replaced while held. The
822        // canonicalization plus double open inside rejects a swapped leaf
823        // before anything runs.
824        let capture = subc_os::ExecutableCapture::open(path).map_err(|error| {
825            AppOpenRefusal::not_installed(format!(
826                "installed file {} cannot be opened: {error}",
827                path.display()
828            ))
829        })?;
830        let request = WindowsVerifyRequest {
831            app: app.to_owned(),
832            publisher: self
833                .operator_app_policy
834                .windows_publisher()
835                .map(str::to_owned),
836            floor: self.operator_app_policy.release_floor().clone(),
837            path: path.to_path_buf(),
838        };
839        // The signature and floor are checked on the held capture, before
840        // any process exists.
841        let _verified_version = self.verify_windows_image(&capture, request)?;
842        let mut command = std::process::Command::new(capture.path());
843        command
844            .stdin(std::process::Stdio::null())
845            .stdout(std::process::Stdio::null())
846            .stderr(std::process::Stdio::null());
847        // `creation_flags` replaces the whole mask; the composition lives
848        // in `windows_creation_flags` so tests can pin every bit.
849        command.creation_flags(windows_creation_flags(
850            self.operator_app_policy.windows_breakaway,
851        ));
852        // `app.open` sends no launch arguments: the wire carries only the app id.
853        #[cfg(test)]
854        self.windows_spawn_attempts.fetch_add(1, Ordering::Relaxed);
855        let mut child = command.spawn().map_err(|error| {
856            AppOpenRefusal::verification_failed(format!(
857                "installed file {} could not be started: {error}",
858                path.display()
859            ))
860        })?;
861        let pid = child.id();
862        // Bind the spawn handle while the child is still suspended: the file
863        // stays pinned across process creation, and the capture's identity is
864        // tied to the process handle returned by spawn, never a reopened pid.
865        let image = match capture.bind(&child) {
866            Ok(image) => image,
867            Err(error) => {
868                stop_rejected_child(&mut child);
869                return Err(AppOpenRefusal::verification_failed(format!(
870                    "launched process {pid} could not be bound to its image: {error}"
871                )));
872            }
873        };
874        // Compare the new process's image with the held handle. The disk
875        // identity must still name the verified file object, checked while
876        // the child is suspended and pinned to its start time on both sides,
877        // so a pid reused after exit can never pass. A mismatch stops the
878        // child and refuses: the replacement is never resumed and never
879        // stamped.
880        if !matches!(
881            image.agreement(image.start_time()),
882            subc_os::ImageAgreement::Match(_)
883        ) {
884            stop_rejected_child(&mut child);
885            return Err(AppOpenRefusal::verification_failed(format!(
886                "launched process {pid} does not match its verified image"
887            )));
888        }
889        let process = match self.track_launched_process(pid) {
890            Ok(Some(process)) => process,
891            Ok(None) => {
892                stop_rejected_child(&mut child);
893                return Err(AppOpenRefusal::verification_failed(format!(
894                    "launched process {pid} exited before it could be tracked"
895                )));
896            }
897            Err(error) => {
898                stop_rejected_child(&mut child);
899                return Err(AppOpenRefusal::verification_failed(format!(
900                    "launched process {pid} cannot be tracked: {error}"
901                )));
902            }
903        };
904        // Published before the image runs, so a child that connects at once
905        // is matched against this entry.
906        self.launch_table.publish(app, pid, process, Some(child));
907        // Resume the verified child. A child that cannot resume is stopped and
908        // its published entry retired, so it never matches: nothing unverified
909        // ever runs.
910        if let Err(error) = subc_jobobject::resume_main_thread(pid) {
911            if let Some(entry) = self.launch_table.take(app) {
912                entry.stop_rejected();
913            }
914            return Err(AppOpenRefusal::verification_failed(format!(
915                "launched process {pid} could not be resumed and was stopped: {error}"
916            )));
917        }
918        Ok(pid)
919    }
920
921    /// A pipe client is eligible only when its pid is that of a live launch
922    /// entry. The stamp records the entry's incarnation at connection time.
923    pub(crate) fn stamp_windows_launch(
924        &self,
925        peer: &subc_os::local_peer::CapturedPeer,
926    ) -> Option<crate::operator_apps::OperatorAppStamp> {
927        use subc_os::local_peer::ObservedPeer as OsPeer;
928
929        if !self.operator_app_policy.windows_enabled {
930            return None;
931        }
932        let app = self.operator_app_policy.app_id()?;
933        let OsPeer::Observed(observation) = peer.observation() else {
934            return None;
935        };
936        let incarnation = self.launch_table.match_live_pid(app, observation.pid)?;
937        Some(crate::operator_apps::OperatorAppStamp::launch_stamp(
938            subc_protocol::peer::OperatorApp::new(app, observation.pid),
939            peer.clone(),
940            incarnation,
941        ))
942    }
943}
944
945/// Stop a rejected Windows child synchronously: a suspended or freshly bound
946/// child that failed verification must not run, and relying on drop to reap
947/// it would report a failure while the process still exists.
948#[cfg(windows)]
949fn stop_rejected_child(child: &mut std::process::Child) {
950    let _ = child.kill();
951    while matches!(child.try_wait(), Ok(None)) {
952        std::thread::yield_now();
953    }
954}
955
956#[cfg(test)]
957mod tests;