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