subc-daemon 0.54.25

Embeddable subc daemon: bootstrap, module supervision, and opaque-byte splice routing.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
//! Compiled operator-app policy. Configuration and caller-provided peer facts
//! cannot enable shortcuts or establish an app's identity.

#[cfg(all(test, target_os = "macos"))]
use crate::peer_identity_lane::CheckPoint;
#[cfg(any(target_os = "macos", test))]
use crate::peer_identity_lane::PeerIdentityError;
#[cfg(target_os = "macos")]
use crate::peer_identity_lane::PeerIdentityLane;
use semver::Version;
#[cfg(target_os = "macos")]
use std::{
    sync::{Arc, Mutex},
    time::{Duration, Instant},
};
use subc_os::local_peer::{CapturedPeer, ObservedPeer};
use subc_protocol::peer::OperatorApp;
#[cfg(target_os = "macos")]
use tokio::sync::watch;

#[cfg(target_os = "macos")]
pub(crate) mod dev_builds;

pub const MACOS_OPERATOR_APP_ENABLED: bool = true;
pub const WINDOWS_OPERATOR_APP_ENABLED: bool = false;
pub const LINUX_OPERATOR_APP_ENABLED: bool = false;
pub const PHONE_OPERATOR_ENABLED: bool = false;
pub(crate) const EVIDENCE_BUDGET: std::time::Duration = std::time::Duration::from_millis(200);

/// No release is admitted until an enabling release replaces this sentinel.
pub const RELEASE_FLOOR: Version = Version::new(u64::MAX, u64::MAX, u64::MAX);

fn effective_release_floor() -> Version {
    #[cfg(feature = "dev-desktop-approval")]
    {
        option_env!("SUBC_DEV_OPERATOR_APP_FLOOR")
            .and_then(|floor| Version::parse(floor).ok())
            .unwrap_or(RELEASE_FLOOR)
    }
    #[cfg(not(feature = "dev-desktop-approval"))]
    {
        RELEASE_FLOOR
    }
}

#[cfg(feature = "dev-desktop-approval")]
pub(crate) fn development_floor_diagnostic() -> Option<String> {
    option_env!("SUBC_DEV_OPERATOR_APP_FLOOR")
        .map(|_| format!("SUBC_DEV_OPERATOR_APP_FLOOR={}", effective_release_floor()))
}

/// Hardened runtime is checked separately in the native verifier because it is
/// a signed CodeDirectory flag, not a code-requirement language predicate.
pub const MACOS_REQUIREMENT: &str = concat!(
    "anchor apple generic and certificate 1[field.1.2.840.113635.100.6.2.6] exists ",
    "and certificate leaf[field.1.2.840.113635.100.6.1.13] exists ",
    "and certificate leaf[subject.OU] = \"5R5846NBPW\" ",
    "and identifier \"io.cortexkit.alfonso.desktop\" ",
    "and entitlement[\"com.apple.security.get-task-allow\"] absent ",
    "and entitlement[\"com.apple.security.cs.disable-library-validation\"] absent ",
    "and entitlement[\"com.apple.security.cs.allow-dyld-environment-variables\"] absent"
);

#[derive(Clone, Copy, Debug)]
#[non_exhaustive]
pub struct CompiledApp {
    pub id: Option<&'static str>,
    pub macos_bundle_id: &'static str,
    pub macos_executable: &'static str,
    pub macos_bundle: &'static str,
    pub windows_executable: &'static str,
    pub linux_executable: &'static str,
    pub windows_publisher: Option<&'static str>,
    pub windows_path: Option<&'static str>,
    pub linux_path: Option<&'static str>,
    pub linux_release_index_identity: Option<&'static str>,
}

pub const COMPILED_APP: CompiledApp = CompiledApp {
    id: Some("alfonso-desktop"),
    macos_bundle_id: "io.cortexkit.alfonso.desktop",
    macos_executable: "Alfonso",
    macos_bundle: "Alfonso.app",
    windows_executable: "Alfonso.exe",
    linux_executable: "alfonso",
    windows_publisher: None,
    windows_path: None,
    linux_path: None,
    linux_release_index_identity: None,
};

pub fn meets_release_floor(version: Option<&str>, floor: &Version) -> bool {
    // The reserved floor admits nothing, including its own numeric spelling.
    *floor != RELEASE_FLOOR
        && version
            .and_then(|version| Version::parse(version).ok())
            .is_some_and(|version| version.cmp_precedence(floor).is_ge())
}

/// The platform an `app.open` decision runs for. macOS never launches through
/// the daemon; any other platform without a launcher falls back the same way.
///
/// Every variant is constructed: one per build in `AppOpenPlatform::current`,
/// and the rest in tests, which drive every platform on every host. (Check
/// builds without test code would otherwise call the idle variants dead.)
#[allow(dead_code)]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum AppOpenPlatform {
    MacOS,
    Windows,
    Linux,
    Other,
}

impl AppOpenPlatform {
    pub fn current() -> Self {
        #[cfg(target_os = "macos")]
        return Self::MacOS;
        #[cfg(windows)]
        return Self::Windows;
        #[cfg(target_os = "linux")]
        return Self::Linux;
        #[cfg(not(any(target_os = "macos", windows, target_os = "linux")))]
        return Self::Other;
    }
}

#[derive(Clone, Debug)]
pub(crate) struct OperatorAppStamp {
    pub app: OperatorApp,
    #[cfg(target_os = "macos")]
    peer: CapturedPeer,
    #[cfg(target_os = "macos")]
    macos_rule: MacStampRule,
    generation: std::sync::Arc<StampGeneration>,
    #[cfg(all(test, target_os = "macos"))]
    pub(crate) delivery_fixture: bool,
    /// The launch entry incarnation this stamp matched, present only for
    /// stamps derived from a live Windows launch entry. macOS stamps carry
    /// `None` and check the captured audit token instead.
    pub(crate) launch_incarnation: Option<u64>,
}

#[derive(Debug, Default)]
struct StampGeneration {
    #[cfg(target_os = "macos")]
    flight: Mutex<Option<RouteStampCheck>>,
    #[cfg(target_os = "macos")]
    last_warning: Mutex<[Option<Instant>; 4]>,
}

#[cfg(target_os = "macos")]
#[derive(Clone, Copy, Debug)]
pub(crate) enum RouteStampFailure {
    LaneBusy,
    Deadline,
    CheckFailed,
    CheckRunning,
}

#[cfg(target_os = "macos")]
impl RouteStampFailure {
    pub(crate) fn reason(self) -> &'static str {
        match self {
            Self::LaneBusy => "lane_busy",
            Self::Deadline => "deadline",
            Self::CheckFailed => "check_failed",
            Self::CheckRunning => "check_running",
        }
    }
}

#[cfg(target_os = "macos")]
impl From<PeerIdentityError> for RouteStampFailure {
    fn from(error: PeerIdentityError) -> Self {
        match error {
            PeerIdentityError::Busy => Self::LaneBusy,
            PeerIdentityError::Deadline => Self::Deadline,
            PeerIdentityError::CheckFailed => Self::CheckFailed,
        }
    }
}

#[cfg(target_os = "macos")]
type RouteStampResult = Result<bool, RouteStampFailure>;

#[cfg(target_os = "macos")]
#[derive(Clone, Debug)]
struct RouteStampCheck {
    deadline: Instant,
    revocation_revision: Option<u64>,
    result: watch::Receiver<Option<RouteStampResult>>,
    running: bool,
}

#[cfg(target_os = "macos")]
struct RouteStampFlight {
    generation: Arc<StampGeneration>,
    result: watch::Receiver<Option<RouteStampResult>>,
}

#[cfg(target_os = "macos")]
impl RouteStampFlight {
    fn start_native(&self) -> Result<NativeStampCheck<'_>, RouteStampFailure> {
        let mut flight = self
            .generation
            .flight
            .lock()
            .unwrap_or_else(|p| p.into_inner());
        let current = flight
            .as_mut()
            .filter(|current| current.result.same_channel(&self.result))
            .filter(|current| Instant::now() < current.deadline)
            .ok_or(RouteStampFailure::Deadline)?;
        current.running = true;
        Ok(NativeStampCheck(self))
    }

    fn clear(&self, native_finished: bool) {
        let mut flight = self
            .generation
            .flight
            .lock()
            .unwrap_or_else(|p| p.into_inner());
        if flight.as_ref().is_some_and(|current| {
            current.result.same_channel(&self.result) && (native_finished || !current.running)
        }) {
            *flight = None;
        }
    }
}

#[cfg(target_os = "macos")]
struct NativeStampCheck<'a>(&'a RouteStampFlight);

#[cfg(target_os = "macos")]
impl Drop for NativeStampCheck<'_> {
    fn drop(&mut self) {
        self.0.clear(true);
    }
}

#[cfg(target_os = "macos")]
#[derive(Clone, Debug)]
enum MacStampRule {
    Release {
        requirement: &'static str,
        floor: Version,
    },
    Dev {
        cdhash: [u8; 20],
        opened: dev_builds::ConnectionOpened,
        trusted_builds: std::sync::Arc<dev_builds::TrustedBuilds>,
    },
}

impl OperatorAppStamp {
    #[cfg(any(test, feature = "test-support"))]
    pub(crate) fn fixture(app: &str, pid: u32) -> Self {
        Self {
            app: OperatorApp::new(app, pid),
            #[cfg(target_os = "macos")]
            peer: ObservedPeer::Unobserved.into(),
            #[cfg(target_os = "macos")]
            macos_rule: MacStampRule::Release {
                requirement: MACOS_REQUIREMENT,
                floor: RELEASE_FLOOR,
            },
            generation: Default::default(),
            #[cfg(all(test, target_os = "macos"))]
            delivery_fixture: false,
            launch_incarnation: None,
        }
    }

    /// A stamp for a pipe client whose pid matches a live Windows launch
    /// entry. Linux never stamps, so every `Some` incarnation on the wire is
    /// a Windows launch.
    #[cfg(windows)]
    pub(crate) fn launch_stamp(app: OperatorApp, _peer: CapturedPeer, incarnation: u64) -> Self {
        Self {
            app,
            generation: Default::default(),
            launch_incarnation: Some(incarnation),
        }
    }

    /// Which platform switch gates delivering this stamp on `route.bind`.
    /// The stamp is a connect-time fact; the switch is checked again at relay
    /// so turning it off stops delivery without dropping connections.
    pub(crate) fn delivery_enabled(&self, policy: &OperatorAppPolicy) -> bool {
        if self.launch_incarnation.is_some() {
            policy.windows_enabled
        } else {
            policy.macos_enabled
        }
    }

    /// A bind-time stamp is not authority: Windows must still name its own live
    /// launch entry, while macOS checks the captured process token again.
    pub(crate) async fn revalidate_with_launches(
        &self,
        launches: &crate::app_open::LaunchTable,
    ) -> bool {
        if let Some(incarnation) = self.launch_incarnation {
            return launches.is_live_incarnation(&self.app.app, incarnation);
        }
        self.revalidate_native().await
    }

    #[cfg(all(test, target_os = "macos"))]
    pub(crate) fn revalidate(&self) -> bool {
        matches!(self.check_requirement(), Ok(true))
    }

    pub(crate) fn same_generation(&self, other: &Self) -> bool {
        std::sync::Arc::ptr_eq(&self.generation, &other.generation)
    }

    #[cfg(target_os = "macos")]
    pub(crate) fn is_dev_build(&self) -> bool {
        matches!(self.macos_rule, MacStampRule::Dev { .. })
    }

    #[cfg(target_os = "macos")]
    pub(crate) fn dev_revocation_revision(&self) -> Option<u64> {
        match &self.macos_rule {
            MacStampRule::Dev { trusted_builds, .. } => Some(trusted_builds.revocation_revision()),
            MacStampRule::Release { .. } => None,
        }
    }

    #[cfg(target_os = "macos")]
    pub(crate) fn dev_hash(&self) -> Option<String> {
        match self.macos_rule {
            MacStampRule::Dev { cdhash, .. } => Some(dev_builds::format_hash(cdhash)),
            MacStampRule::Release { .. } => None,
        }
    }

    /// A previously verified build can lose keychain access. Report that as
    /// unavailable instead of treating the failed read as absence of trust.
    #[cfg(target_os = "macos")]
    pub(crate) fn dev_store_diagnostic(&self) -> Option<subc_control::ConnectionDevBuild> {
        let MacStampRule::Dev {
            cdhash,
            opened,
            trusted_builds,
        } = &self.macos_rule
        else {
            return None;
        };
        let cdhash = dev_builds::format_hash(*cdhash);
        match trusted_builds.was_trusted_at(&cdhash, *opened) {
            Err(reason) => Some(subc_control::ConnectionDevBuild::Unavailable {
                reason: reason.into(),
            }),
            Ok(false) => Some(subc_control::ConnectionDevBuild::Untrusted { cdhash }),
            Ok(true) => None,
        }
    }

    async fn revalidate_native(&self) -> bool {
        #[cfg(target_os = "macos")]
        if self.peer.has_audit_token() {
            let stamp = self.clone();
            return PeerIdentityLane::native()
                .run(move || matches!(stamp.check_requirement(), Ok(true)))
                .await
                .unwrap_or(false);
        }
        false
    }

    #[cfg(target_os = "macos")]
    pub(crate) async fn revalidate_route(&self, policy: &OperatorAppPolicy) -> RouteStampResult {
        if !self.peer.has_audit_token() {
            return Err(RouteStampFailure::CheckFailed);
        }
        let stamp = self.clone();
        #[cfg(test)]
        let lane = policy.test_lane.clone();
        self.share_route_check(policy, move || {
            #[cfg(test)]
            if let Some(lane) = &lane {
                lane.probe_check(CheckPoint::RevalidationStarted);
            }
            let result = stamp.check_requirement();
            #[cfg(test)]
            if let Some(lane) = &lane {
                lane.probe_check(CheckPoint::RevalidationChecked);
            }
            result
        })
        .await
    }

    #[cfg(target_os = "macos")]
    async fn share_route_check(
        &self,
        policy: &OperatorAppPolicy,
        work: impl FnOnce() -> RouteStampResult + Send + 'static,
    ) -> RouteStampResult {
        let revocation_revision = self.dev_revocation_revision();
        let mut check = {
            let mut flight = self
                .generation
                .flight
                .lock()
                .unwrap_or_else(|p| p.into_inner());
            let now = Instant::now();
            if let Some(active) = flight.as_ref().filter(|active| now < active.deadline) {
                // A bind starting after a revocation must not reuse a check
                // that already read the old trust list.
                if active.revocation_revision != revocation_revision {
                    return Ok(false);
                }
                active.clone()
            } else {
                if flight.as_ref().is_some_and(|expired| expired.running) {
                    return Err(RouteStampFailure::CheckRunning);
                }
                let deadline = now + EVIDENCE_BUDGET;
                let (publish, result) = watch::channel(None);
                let check = RouteStampCheck {
                    deadline,
                    revocation_revision,
                    result,
                    running: false,
                };
                *flight = Some(check.clone());
                let flight = Arc::new(RouteStampFlight {
                    generation: self.generation.clone(),
                    result: check.result.clone(),
                });
                let policy = policy.clone();
                // Let the check outlive any one bind. Once native work starts,
                // only its return can release the slot, even past the deadline.
                tokio::spawn(async move {
                    let native = flight.clone();
                    let result = policy
                        .peer_identity_lane()
                        .run_with_admission(deadline, Admission::Wait, move || {
                            let _running = native.start_native()?;
                            work()
                        })
                        .await
                        .map_err(RouteStampFailure::from)
                        .and_then(|result| result);
                    flight.clear(false);
                    publish.send_replace(Some(result));
                });
                check
            }
        };
        let result = tokio::time::timeout_at(
            check.deadline.into(),
            check.result.wait_for(Option::is_some),
        )
        .await
        .map_err(|_| RouteStampFailure::Deadline)?
        .map_err(|_| RouteStampFailure::CheckFailed)?;
        if Instant::now() >= check.deadline {
            return Err(RouteStampFailure::Deadline);
        }
        if self.dev_revocation_revision() != revocation_revision {
            return Ok(false);
        }
        result.expect("only a completed check wakes the waiter")
    }

    #[cfg(target_os = "macos")]
    pub(crate) fn should_warn_route_check(&self, failure: RouteStampFailure) -> bool {
        let mut warnings = self
            .generation
            .last_warning
            .lock()
            .unwrap_or_else(|p| p.into_inner());
        let last = &mut warnings[failure as usize];
        let now = Instant::now();
        if last.is_some_and(|previous| now.duration_since(previous) < Duration::from_secs(60)) {
            return false;
        }
        *last = Some(now);
        true
    }

    #[cfg(target_os = "macos")]
    fn check_requirement(&self) -> RouteStampResult {
        use subc_os::local_peer::AppBundleError::VerifierUnavailable;
        match &self.macos_rule {
            MacStampRule::Release { requirement, floor } => {
                match self.peer.check_sealed_app(requirement) {
                    Ok(code) => Ok(meets_release_floor(code.short_version.as_deref(), floor)),
                    Err(VerifierUnavailable) => Err(RouteStampFailure::CheckFailed),
                    Err(_) => Ok(false),
                }
            }
            MacStampRule::Dev {
                cdhash,
                opened,
                trusted_builds,
            } => match self.peer.check_dev_app(dev_builds::IDENTIFIER) {
                Some(Err(VerifierUnavailable)) => Err(RouteStampFailure::CheckFailed),
                Some(Ok(code)) if code.cdhash == *cdhash => trusted_builds
                    .was_trusted_at(&dev_builds::format_hash(*cdhash), *opened)
                    .map_err(|_| RouteStampFailure::CheckFailed),
                _ => Ok(false),
            },
        }
    }
}

#[derive(Default)]
pub(crate) struct RecognitionEvidence {
    pub stamp: Option<(OperatorAppStamp, ObservedPeer)>,
    pub dev_build: Option<subc_control::ConnectionDevBuild>,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Admission {
    Immediate,
    Wait,
}

pub(crate) struct ImmediateAdmissionRefused;

#[cfg(target_os = "macos")]
#[derive(Debug, Default)]
enum RecognitionPhase {
    #[default]
    Queued,
    Running,
    Returned(Instant),
}

#[cfg(target_os = "macos")]
#[derive(Debug, Default)]
pub(crate) struct RecognitionProgress {
    phase: Mutex<RecognitionPhase>,
}

#[cfg(target_os = "macos")]
impl RecognitionProgress {
    fn start(&self, deadline: Instant) -> Option<RunningRecognition<'_>> {
        let mut phase = self.phase.lock().unwrap_or_else(|p| p.into_inner());
        if Instant::now() >= deadline {
            return None;
        }
        *phase = RecognitionPhase::Running;
        Some(RunningRecognition(self))
    }

    pub(crate) fn is_running(&self) -> bool {
        matches!(
            *self.phase.lock().unwrap_or_else(|p| p.into_inner()),
            RecognitionPhase::Running
        )
    }

    pub(crate) fn returned_after(&self, arrived: Instant) -> bool {
        matches!(*self.phase.lock().unwrap_or_else(|p| p.into_inner()), RecognitionPhase::Returned(at) if arrived <= at)
    }

    #[cfg(test)]
    pub(crate) fn complete_for_test(&self, deadline: Instant) {
        drop(
            self.start(deadline)
                .expect("staged check must finish before its deadline"),
        );
    }
}

#[cfg(target_os = "macos")]
struct RunningRecognition<'a>(&'a RecognitionProgress);

#[cfg(target_os = "macos")]
impl Drop for RunningRecognition<'_> {
    fn drop(&mut self) {
        let returned = Instant::now();
        *self.0.phase.lock().unwrap_or_else(|p| p.into_inner()) =
            RecognitionPhase::Returned(returned);
    }
}

#[derive(Clone, Debug)]
pub(crate) struct OperatorAppPolicy {
    pub macos_enabled: bool,
    pub windows_enabled: bool,
    pub linux_enabled: bool,
    pub phone_enabled: bool,
    app: CompiledApp,
    #[cfg(target_os = "macos")]
    requirement: &'static str,
    #[cfg(target_os = "macos")]
    pub(crate) trusted_builds: std::sync::Arc<dev_builds::TrustedBuilds>,
    floor: Version,
    #[cfg(all(test, target_os = "macos"))]
    requirement_checks: std::sync::Arc<std::sync::atomic::AtomicUsize>,
    #[cfg(test)]
    pub(crate) test_lane: Option<std::sync::Arc<crate::peer_identity_lane::PeerIdentityLane>>,
    /// Where the installed app lives. The production table leaves both unset;
    /// a known app with no location answers `app_not_installed` once its
    /// platform switch is on.
    pub windows_path: Option<std::path::PathBuf>,
    pub linux_path: Option<std::path::PathBuf>,
    /// Whether the Windows spawn sets `CREATE_BREAKAWAY_FROM_JOB`.
    /// Production always breaks away and fails closed when the job forbids
    /// it. Tests can omit the bit where the job running them forbids it: a
    /// test handler creates no module job, so a plain spawn is already
    /// outside one. Read only by the Windows launcher.
    #[cfg_attr(not(windows), allow(dead_code))]
    pub windows_breakaway: bool,
    /// Tests force the direct-spawn path so a Linux launch test never depends
    /// on the build machine running a user manager. Production always prefers
    /// a transient scope when one is available. Only the Linux launcher reads
    /// it, so other platforms silence the idle field.
    #[cfg_attr(not(target_os = "linux"), allow(dead_code))]
    pub linux_force_direct: bool,
}

impl Default for OperatorAppPolicy {
    fn default() -> Self {
        Self {
            macos_enabled: MACOS_OPERATOR_APP_ENABLED,
            windows_enabled: WINDOWS_OPERATOR_APP_ENABLED,
            linux_enabled: LINUX_OPERATOR_APP_ENABLED,
            phone_enabled: PHONE_OPERATOR_ENABLED,
            app: COMPILED_APP,
            #[cfg(target_os = "macos")]
            requirement: MACOS_REQUIREMENT,
            #[cfg(target_os = "macos")]
            trusted_builds: Default::default(),
            floor: effective_release_floor(),
            #[cfg(all(test, target_os = "macos"))]
            requirement_checks: Default::default(),
            #[cfg(test)]
            test_lane: None,
            windows_path: COMPILED_APP.windows_path.map(std::path::PathBuf::from),
            linux_path: COMPILED_APP.linux_path.map(std::path::PathBuf::from),
            windows_breakaway: true,
            linux_force_direct: false,
        }
    }
}

impl OperatorAppPolicy {
    /// The cross-platform app id this policy launches and stamps.
    /// With the platform switch on, a `None` id answers
    /// `app_unknown` on Windows and Linux; with every switch off, the daemon
    /// answers `app_open_disabled` first. macOS answers `app_open_not_used`
    /// before reaching it.
    pub(crate) fn app_id(&self) -> Option<&'static str> {
        self.app.id
    }

    #[cfg(windows)]
    pub(crate) fn release_floor(&self) -> &Version {
        &self.floor
    }

    pub(crate) fn installed_path(&self, platform: AppOpenPlatform) -> Option<std::path::PathBuf> {
        match platform {
            AppOpenPlatform::Windows => self.windows_path.clone(),
            AppOpenPlatform::Linux => self.linux_path.clone(),
            AppOpenPlatform::MacOS | AppOpenPlatform::Other => None,
        }
    }

    pub(crate) fn switch_enabled(&self, platform: AppOpenPlatform) -> bool {
        match platform {
            AppOpenPlatform::MacOS => self.macos_enabled,
            AppOpenPlatform::Windows => self.windows_enabled,
            AppOpenPlatform::Linux => self.linux_enabled,
            AppOpenPlatform::Other => false,
        }
    }

    /// The expected Authenticode publisher for the installed Windows binary.
    /// `None` (the production value until a certificate exists) verifies
    /// nothing: with a test table the tests supply it, with the production
    /// table `app.open` never reaches verification.
    #[cfg(windows)]
    pub(crate) fn windows_publisher(&self) -> Option<&'static str> {
        self.app.windows_publisher
    }

    #[cfg(test)]
    pub(crate) fn stamp(&self, peer: CapturedPeer) -> Option<OperatorAppStamp> {
        #[cfg(target_os = "macos")]
        if !self.macos_enabled {
            return None;
        }
        #[cfg(target_os = "macos")]
        return self.config_identity(peer);
        #[cfg(not(target_os = "macos"))]
        {
            let _ = peer;
            None
        }
    }

    #[cfg(target_os = "macos")]
    pub(crate) fn config_identity(&self, peer: CapturedPeer) -> Option<OperatorAppStamp> {
        if self.floor == RELEASE_FLOOR {
            return None;
        }
        let app = self.app.id?;
        let ObservedPeer::Observed(observation) = peer.observation() else {
            return None;
        };
        let pid = observation.pid;
        #[cfg(test)]
        self.requirement_checks
            .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
        let code = peer.check_sealed_app(self.requirement).ok()?;
        if !meets_release_floor(code.short_version.as_deref(), &self.floor) {
            return None;
        }
        Some(OperatorAppStamp {
            app: OperatorApp::new(app, pid),
            peer,
            macos_rule: MacStampRule::Release {
                requirement: self.requirement,
                floor: self.floor.clone(),
            },
            generation: Default::default(),
            #[cfg(test)]
            delivery_fixture: false,
            launch_incarnation: None,
        })
    }

    pub(crate) fn may_recognize(&self, peer: &CapturedPeer) -> bool {
        #[cfg(test)]
        if self.test_lane.is_some() {
            return true;
        }
        (self.macos_enabled || self.floor != RELEASE_FLOOR)
            && self.app.id.is_some()
            && peer.has_audit_token()
    }

    #[cfg(target_os = "macos")]
    fn recognize_code(
        &self,
        peer: CapturedPeer,
        opened: dev_builds::ConnectionOpened,
    ) -> Option<RecognitionEvidence> {
        use subc_control::ConnectionDevBuild;

        if let Some(stamp) = self.config_identity(peer.clone()) {
            return Some(RecognitionEvidence {
                stamp: Some((stamp, peer.observe_code())),
                dev_build: None,
            });
        }
        if !self.macos_enabled {
            return None;
        }
        let app = self.app.id?;
        let ObservedPeer::Observed(observation) = peer.observation() else {
            return None;
        };
        let dev_build = match peer.check_dev_app(dev_builds::IDENTIFIER)? {
            Err(error) => ConnectionDevBuild::Ineligible {
                reason: error.message(),
            },
            Ok(code) => {
                let cdhash = dev_builds::format_hash(code.cdhash);
                if let Err(reason) = dev_builds::version(&code) {
                    ConnectionDevBuild::Ineligible {
                        reason: reason.into(),
                    }
                } else {
                    match self.trusted_builds.was_trusted_at(&cdhash, opened) {
                        Err(reason) => ConnectionDevBuild::Unavailable {
                            reason: reason.into(),
                        },
                        Ok(false) => ConnectionDevBuild::Untrusted { cdhash },
                        Ok(true) => {
                            let stamp = OperatorAppStamp {
                                app: OperatorApp::new(app, observation.pid),
                                peer: peer.clone(),
                                macos_rule: MacStampRule::Dev {
                                    cdhash: code.cdhash,
                                    opened,
                                    trusted_builds: self.trusted_builds.clone(),
                                },
                                generation: Default::default(),
                                #[cfg(test)]
                                delivery_fixture: false,
                                launch_incarnation: None,
                            };
                            return Some(RecognitionEvidence {
                                stamp: Some((stamp, peer.observe_code())),
                                dev_build: None,
                            });
                        }
                    }
                }
            }
        };
        Some(RecognitionEvidence {
            stamp: None,
            dev_build: Some(dev_build),
        })
    }

    #[cfg(target_os = "macos")]
    fn peer_identity_lane(&self) -> &PeerIdentityLane {
        #[cfg(test)]
        if let Some(lane) = &self.test_lane {
            return lane;
        }
        PeerIdentityLane::native()
    }

    pub(crate) async fn recognize(
        &self,
        peer: CapturedPeer,
        deadline: std::time::Instant,
        admission: Admission,
        #[cfg(target_os = "macos")] opened: dev_builds::ConnectionOpened,
        #[cfg(target_os = "macos")] progress: Arc<RecognitionProgress>,
    ) -> Result<Option<RecognitionEvidence>, ImmediateAdmissionRefused> {
        #[cfg(not(target_os = "macos"))]
        let _ = &peer;
        #[cfg(all(test, not(target_os = "macos")))]
        let result =
            match &self.test_lane {
                Some(lane) => {
                    lane.run_with_admission(deadline, admission, || {
                        Some(RecognitionEvidence::default())
                    })
                    .await
                }
                None => return Ok(None),
            };
        #[cfg(target_os = "macos")]
        let result = {
            let policy = self.clone();
            self.peer_identity_lane()
                .run_with_admission(deadline, admission, move || {
                    #[cfg(test)]
                    if !peer.has_audit_token() {
                        return Some(RecognitionEvidence::default());
                    }
                    let result = {
                        let _running = progress.start(deadline)?;
                        #[cfg(test)]
                        policy
                            .peer_identity_lane()
                            .probe_check(CheckPoint::RecognitionStarted);
                        policy.recognize_code(peer, opened).unwrap_or_default()
                    };
                    #[cfg(test)]
                    policy
                        .peer_identity_lane()
                        .probe_check(CheckPoint::RecognitionReturned);
                    Some(result)
                })
                .await
        };
        #[cfg(any(target_os = "macos", test))]
        {
            match result {
                Err(PeerIdentityError::Busy) if admission == Admission::Immediate => {
                    Err(ImmediateAdmissionRefused)
                }
                result => Ok(result.ok().flatten()),
            }
        }
        #[cfg(not(any(target_os = "macos", test)))]
        {
            let _ = (deadline, admission);
            Ok(None)
        }
    }
}

/// Explicit per-handler fixture policy, compiled only for unit tests or builds
/// with the `test-support` feature, and only in effect when a test passes it to
/// a handler. No environment variable or daemon configuration key can select it.
#[cfg(any(test, feature = "test-support"))]
#[derive(Clone, Debug)]
pub struct TestOperatorAppPolicy {
    pub macos_enabled: bool,
    pub windows_enabled: bool,
    pub linux_enabled: bool,
    pub app: &'static str,
    pub requirement: &'static str,
    pub floor: Version,
    pub windows_publisher: Option<&'static str>,
    pub windows_path: Option<std::path::PathBuf>,
    pub linux_path: Option<std::path::PathBuf>,
    pub windows_breakaway: bool,
    pub linux_force_direct: bool,
}

#[cfg(any(test, feature = "test-support"))]
impl From<TestOperatorAppPolicy> for OperatorAppPolicy {
    fn from(test: TestOperatorAppPolicy) -> Self {
        Self {
            macos_enabled: test.macos_enabled,
            windows_enabled: test.windows_enabled,
            linux_enabled: test.linux_enabled,
            phone_enabled: PHONE_OPERATOR_ENABLED,
            app: CompiledApp {
                id: Some(test.app),
                windows_publisher: test.windows_publisher,
                ..COMPILED_APP
            },
            #[cfg(target_os = "macos")]
            requirement: test.requirement,
            #[cfg(target_os = "macos")]
            trusted_builds: Default::default(),
            floor: test.floor,
            #[cfg(all(test, target_os = "macos"))]
            requirement_checks: Default::default(),
            #[cfg(test)]
            test_lane: None,
            windows_path: test.windows_path,
            linux_path: test.linux_path,
            windows_breakaway: test.windows_breakaway,
            linux_force_direct: test.linux_force_direct,
        }
    }
}

#[cfg(test)]
mod tests;