Skip to main content

subc_daemon/
operator_apps.rs

1//! Compiled operator-app policy. Configuration and caller-provided peer facts
2//! cannot enable shortcuts or establish an app's identity.
3
4use semver::Version;
5use subc_os::local_peer::{CapturedPeer, CodeRequirementOutcome, ObservedPeer};
6use subc_protocol::peer::OperatorApp;
7
8pub const MACOS_OPERATOR_APP_ENABLED: bool = false;
9pub const WINDOWS_OPERATOR_APP_ENABLED: bool = false;
10pub const LINUX_OPERATOR_APP_ENABLED: bool = false;
11pub const PHONE_OPERATOR_ENABLED: bool = false;
12
13/// No release is admitted until an enabling release replaces this sentinel.
14pub const RELEASE_FLOOR: Version = Version::new(u64::MAX, u64::MAX, u64::MAX);
15
16/// Hardened runtime is checked separately in the native verifier because it is
17/// a signed CodeDirectory flag, not a code-requirement language predicate.
18pub const MACOS_REQUIREMENT: &str = concat!(
19    "anchor apple generic and certificate 1[field.1.2.840.113635.100.6.2.6] exists ",
20    "and certificate leaf[field.1.2.840.113635.100.6.1.13] exists ",
21    "and certificate leaf[subject.OU] = \"5R5846NBPW\" ",
22    "and identifier \"io.cortexkit.alfonso.desktop\" ",
23    "and entitlement[\"com.apple.security.get-task-allow\"] absent ",
24    "and entitlement[\"com.apple.security.cs.disable-library-validation\"] absent ",
25    "and entitlement[\"com.apple.security.cs.allow-dyld-environment-variables\"] absent"
26);
27
28#[derive(Clone, Copy, Debug)]
29#[non_exhaustive]
30pub struct CompiledApp {
31    pub id: Option<&'static str>,
32    pub macos_bundle_id: &'static str,
33    pub macos_executable: &'static str,
34    pub macos_bundle: &'static str,
35    pub windows_executable: &'static str,
36    pub linux_executable: &'static str,
37    pub windows_publisher: Option<&'static str>,
38    pub windows_path: Option<&'static str>,
39    pub linux_path: Option<&'static str>,
40    pub linux_release_index_identity: Option<&'static str>,
41}
42
43pub const COMPILED_APP: CompiledApp = CompiledApp {
44    id: None,
45    macos_bundle_id: "io.cortexkit.alfonso.desktop",
46    macos_executable: "Alfonso",
47    macos_bundle: "Alfonso.app",
48    windows_executable: "Alfonso.exe",
49    linux_executable: "alfonso",
50    windows_publisher: None,
51    windows_path: None,
52    linux_path: None,
53    linux_release_index_identity: None,
54};
55
56pub fn meets_release_floor(version: Option<&str>, floor: &Version) -> bool {
57    // The reserved floor admits nothing, including its own numeric spelling.
58    *floor != RELEASE_FLOOR
59        && version
60            .and_then(|version| Version::parse(version).ok())
61            .is_some_and(|version| version.cmp_precedence(floor).is_ge())
62}
63
64/// The platform an `app.open` decision runs for. macOS never launches through
65/// the daemon; any other platform without a launcher falls back the same way.
66///
67/// Every variant is constructed: one per build in `AppOpenPlatform::current`,
68/// and the rest in tests, which drive every platform on every host. (Check
69/// builds without test code would otherwise call the idle variants dead.)
70#[allow(dead_code)]
71#[derive(Clone, Copy, Debug, PartialEq, Eq)]
72pub(crate) enum AppOpenPlatform {
73    MacOS,
74    Windows,
75    Linux,
76    Other,
77}
78
79impl AppOpenPlatform {
80    pub fn current() -> Self {
81        #[cfg(target_os = "macos")]
82        return Self::MacOS;
83        #[cfg(windows)]
84        return Self::Windows;
85        #[cfg(target_os = "linux")]
86        return Self::Linux;
87        #[cfg(not(any(target_os = "macos", windows, target_os = "linux")))]
88        return Self::Other;
89    }
90}
91
92#[derive(Clone, Debug)]
93pub(crate) struct OperatorAppStamp {
94    pub app: OperatorApp,
95    peer: CapturedPeer,
96    requirement: &'static str,
97    floor: Version,
98    /// The launch entry incarnation this stamp matched, present only for
99    /// stamps derived from a live Windows launch entry. macOS stamps carry
100    /// `None` and check the captured audit token instead.
101    pub(crate) launch_incarnation: Option<u64>,
102}
103
104impl OperatorAppStamp {
105    #[cfg(test)]
106    pub(crate) fn fixture(app: &str, pid: u32) -> Self {
107        Self {
108            app: OperatorApp::new(app, pid),
109            peer: ObservedPeer::Unobserved.into(),
110            requirement: MACOS_REQUIREMENT,
111            floor: RELEASE_FLOOR,
112            launch_incarnation: None,
113        }
114    }
115
116    /// A stamp for a pipe client whose pid matches a live Windows launch
117    /// entry. Linux never stamps, so every `Some` incarnation on the wire is
118    /// a Windows launch.
119    #[cfg(windows)]
120    pub(crate) fn launch_stamp(app: OperatorApp, peer: CapturedPeer, incarnation: u64) -> Self {
121        Self {
122            app,
123            peer,
124            requirement: MACOS_REQUIREMENT,
125            floor: RELEASE_FLOOR,
126            launch_incarnation: Some(incarnation),
127        }
128    }
129
130    /// Which platform switch gates delivering this stamp on `route.bind`.
131    /// The stamp is a connect-time fact; the switch is checked again at relay
132    /// so turning it off stops delivery without dropping connections.
133    pub(crate) fn delivery_enabled(&self, policy: &OperatorAppPolicy) -> bool {
134        if self.launch_incarnation.is_some() {
135            policy.windows_enabled
136        } else {
137            policy.macos_enabled
138        }
139    }
140
141    /// A bind-time stamp is not authority: Windows must still name its own live
142    /// launch entry, while macOS checks the captured process token again.
143    pub(crate) fn revalidate_with_launches(&self, launches: &crate::app_open::LaunchTable) -> bool {
144        if let Some(incarnation) = self.launch_incarnation {
145            return launches.is_live_incarnation(&self.app.app, incarnation);
146        }
147        self.revalidate()
148    }
149
150    pub(crate) fn revalidate(&self) -> bool {
151        matches!(self.peer.check_code_requirement(self.requirement),
152            CodeRequirementOutcome::Satisfied(code)
153                if meets_release_floor(code.short_version.as_deref(), &self.floor))
154    }
155}
156
157#[derive(Clone, Debug)]
158pub(crate) struct OperatorAppPolicy {
159    pub macos_enabled: bool,
160    pub windows_enabled: bool,
161    pub linux_enabled: bool,
162    pub phone_enabled: bool,
163    app: CompiledApp,
164    requirement: &'static str,
165    floor: Version,
166    /// Where the installed app lives. The production table leaves both unset;
167    /// a known app with no location answers `app_not_installed` once its
168    /// platform switch is on.
169    pub windows_path: Option<std::path::PathBuf>,
170    pub linux_path: Option<std::path::PathBuf>,
171    /// Whether the Windows spawn sets `CREATE_BREAKAWAY_FROM_JOB`.
172    /// Production always breaks away and fails closed when the job forbids
173    /// it. Tests can omit the bit where the job running them forbids it: a
174    /// test handler creates no module job, so a plain spawn is already
175    /// outside one. Read only by the Windows launcher.
176    #[cfg_attr(not(windows), allow(dead_code))]
177    pub windows_breakaway: bool,
178    /// Tests force the direct-spawn path so a Linux launch test never depends
179    /// on the build machine running a user manager. Production always prefers
180    /// a transient scope when one is available. Only the Linux launcher reads
181    /// it, so other platforms silence the idle field.
182    #[cfg_attr(not(target_os = "linux"), allow(dead_code))]
183    pub linux_force_direct: bool,
184}
185
186impl Default for OperatorAppPolicy {
187    fn default() -> Self {
188        Self {
189            macos_enabled: MACOS_OPERATOR_APP_ENABLED,
190            windows_enabled: WINDOWS_OPERATOR_APP_ENABLED,
191            linux_enabled: LINUX_OPERATOR_APP_ENABLED,
192            phone_enabled: PHONE_OPERATOR_ENABLED,
193            app: COMPILED_APP,
194            requirement: MACOS_REQUIREMENT,
195            floor: RELEASE_FLOOR,
196            windows_path: COMPILED_APP.windows_path.map(std::path::PathBuf::from),
197            linux_path: COMPILED_APP.linux_path.map(std::path::PathBuf::from),
198            windows_breakaway: true,
199            linux_force_direct: false,
200        }
201    }
202}
203
204impl OperatorAppPolicy {
205    /// The app id this policy launches and stamps, or `None` for the
206    /// production table. With the platform switch on, a `None` id answers
207    /// `app_unknown` on Windows and Linux; with every switch off, the daemon
208    /// answers `app_open_disabled` first. macOS answers `app_open_not_used`
209    /// before reaching it.
210    pub(crate) fn app_id(&self) -> Option<&'static str> {
211        self.app.id
212    }
213
214    #[cfg(windows)]
215    pub(crate) fn release_floor(&self) -> &Version {
216        &self.floor
217    }
218
219    pub(crate) fn installed_path(&self, platform: AppOpenPlatform) -> Option<std::path::PathBuf> {
220        match platform {
221            AppOpenPlatform::Windows => self.windows_path.clone(),
222            AppOpenPlatform::Linux => self.linux_path.clone(),
223            AppOpenPlatform::MacOS | AppOpenPlatform::Other => None,
224        }
225    }
226
227    pub(crate) fn switch_enabled(&self, platform: AppOpenPlatform) -> bool {
228        match platform {
229            AppOpenPlatform::MacOS => self.macos_enabled,
230            AppOpenPlatform::Windows => self.windows_enabled,
231            AppOpenPlatform::Linux => self.linux_enabled,
232            AppOpenPlatform::Other => false,
233        }
234    }
235
236    /// The expected Authenticode publisher for the installed Windows binary.
237    /// `None` (the production value until a certificate exists) verifies
238    /// nothing: with a test table the tests supply it, with the production
239    /// table `app.open` never reaches verification.
240    #[cfg(windows)]
241    pub(crate) fn windows_publisher(&self) -> Option<&'static str> {
242        self.app.windows_publisher
243    }
244
245    pub(crate) fn stamp(&self, peer: CapturedPeer) -> Option<OperatorAppStamp> {
246        if !self.macos_enabled {
247            return None;
248        }
249        self.config_identity(peer)
250    }
251
252    /// A trusted full-diff surface needs the same process identity and release
253    /// floor, but never gains the operator-app prompt exemption from this check.
254    pub(crate) fn config_identity(&self, peer: CapturedPeer) -> Option<OperatorAppStamp> {
255        if !cfg!(target_os = "macos") {
256            return None;
257        }
258        let app = self.app.id?;
259        let ObservedPeer::Observed(observation) = peer.observation() else {
260            return None;
261        };
262        let pid = observation.pid;
263        let CodeRequirementOutcome::Satisfied(code) = peer.check_code_requirement(self.requirement)
264        else {
265            return None;
266        };
267        if !meets_release_floor(code.short_version.as_deref(), &self.floor) {
268            return None;
269        }
270        Some(OperatorAppStamp {
271            app: OperatorApp::new(app, pid),
272            peer,
273            requirement: self.requirement,
274            floor: self.floor.clone(),
275            launch_incarnation: None,
276        })
277    }
278}
279
280/// Explicit per-handler fixture policy, compiled only for unit tests or builds
281/// with the `test-support` feature, and only in effect when a test passes it to
282/// a handler. No environment variable or daemon configuration key can select it.
283#[cfg(any(test, feature = "test-support"))]
284#[derive(Clone, Debug)]
285pub struct TestOperatorAppPolicy {
286    pub macos_enabled: bool,
287    pub windows_enabled: bool,
288    pub linux_enabled: bool,
289    pub app: &'static str,
290    pub requirement: &'static str,
291    pub floor: Version,
292    pub windows_publisher: Option<&'static str>,
293    pub windows_path: Option<std::path::PathBuf>,
294    pub linux_path: Option<std::path::PathBuf>,
295    pub windows_breakaway: bool,
296    pub linux_force_direct: bool,
297}
298
299#[cfg(any(test, feature = "test-support"))]
300impl From<TestOperatorAppPolicy> for OperatorAppPolicy {
301    fn from(test: TestOperatorAppPolicy) -> Self {
302        Self {
303            macos_enabled: test.macos_enabled,
304            windows_enabled: test.windows_enabled,
305            linux_enabled: test.linux_enabled,
306            phone_enabled: PHONE_OPERATOR_ENABLED,
307            app: CompiledApp {
308                id: Some(test.app),
309                windows_publisher: test.windows_publisher,
310                ..COMPILED_APP
311            },
312            requirement: test.requirement,
313            floor: test.floor,
314            windows_path: test.windows_path,
315            linux_path: test.linux_path,
316            windows_breakaway: test.windows_breakaway,
317            linux_force_direct: test.linux_force_direct,
318        }
319    }
320}
321
322#[cfg(test)]
323mod tests;