1#[cfg(all(test, target_os = "macos"))]
5use crate::peer_identity_lane::CheckPoint;
6#[cfg(any(target_os = "macos", test))]
7use crate::peer_identity_lane::PeerIdentityError;
8#[cfg(target_os = "macos")]
9use crate::peer_identity_lane::PeerIdentityLane;
10use semver::Version;
11#[cfg(target_os = "macos")]
12use std::{
13 sync::{Arc, Mutex},
14 time::{Duration, Instant},
15};
16use subc_os::local_peer::{CapturedPeer, ObservedPeer};
17use subc_protocol::peer::OperatorApp;
18#[cfg(target_os = "macos")]
19use tokio::sync::watch;
20
21#[cfg(target_os = "macos")]
22pub(crate) mod dev_builds;
23
24pub const MACOS_OPERATOR_APP_ENABLED: bool = true;
25pub const WINDOWS_OPERATOR_APP_ENABLED: bool = false;
26pub const LINUX_OPERATOR_APP_ENABLED: bool = false;
27pub const PHONE_OPERATOR_ENABLED: bool = false;
28pub(crate) const EVIDENCE_BUDGET: std::time::Duration = std::time::Duration::from_millis(200);
29
30pub const RELEASE_FLOOR: Version = Version::new(u64::MAX, u64::MAX, u64::MAX);
32
33fn effective_release_floor() -> Version {
34 #[cfg(feature = "dev-desktop-approval")]
35 {
36 option_env!("SUBC_DEV_OPERATOR_APP_FLOOR")
37 .and_then(|floor| Version::parse(floor).ok())
38 .unwrap_or(RELEASE_FLOOR)
39 }
40 #[cfg(not(feature = "dev-desktop-approval"))]
41 {
42 RELEASE_FLOOR
43 }
44}
45
46#[cfg(feature = "dev-desktop-approval")]
47pub(crate) fn development_floor_diagnostic() -> Option<String> {
48 option_env!("SUBC_DEV_OPERATOR_APP_FLOOR")
49 .map(|_| format!("SUBC_DEV_OPERATOR_APP_FLOOR={}", effective_release_floor()))
50}
51
52pub const MACOS_REQUIREMENT: &str = concat!(
55 "anchor apple generic and certificate 1[field.1.2.840.113635.100.6.2.6] exists ",
56 "and certificate leaf[field.1.2.840.113635.100.6.1.13] exists ",
57 "and certificate leaf[subject.OU] = \"5R5846NBPW\" ",
58 "and identifier \"io.cortexkit.alfonso.desktop\" ",
59 "and entitlement[\"com.apple.security.get-task-allow\"] absent ",
60 "and entitlement[\"com.apple.security.cs.disable-library-validation\"] absent ",
61 "and entitlement[\"com.apple.security.cs.allow-dyld-environment-variables\"] absent"
62);
63
64#[derive(Clone, Copy, Debug)]
65#[non_exhaustive]
66pub struct CompiledApp {
67 pub id: Option<&'static str>,
68 pub macos_bundle_id: &'static str,
69 pub macos_executable: &'static str,
70 pub macos_bundle: &'static str,
71 pub windows_executable: &'static str,
72 pub linux_executable: &'static str,
73 pub windows_publisher: Option<&'static str>,
74 pub windows_path: Option<&'static str>,
75 pub linux_path: Option<&'static str>,
76 pub linux_release_index_identity: Option<&'static str>,
77}
78
79pub const COMPILED_APP: CompiledApp = CompiledApp {
80 id: Some("alfonso-desktop"),
81 macos_bundle_id: "io.cortexkit.alfonso.desktop",
82 macos_executable: "Alfonso",
83 macos_bundle: "Alfonso.app",
84 windows_executable: "Alfonso.exe",
85 linux_executable: "alfonso",
86 windows_publisher: None,
87 windows_path: None,
88 linux_path: None,
89 linux_release_index_identity: None,
90};
91
92pub fn meets_release_floor(version: Option<&str>, floor: &Version) -> bool {
93 *floor != RELEASE_FLOOR
95 && version
96 .and_then(|version| Version::parse(version).ok())
97 .is_some_and(|version| version.cmp_precedence(floor).is_ge())
98}
99
100#[allow(dead_code)]
107#[derive(Clone, Copy, Debug, PartialEq, Eq)]
108pub(crate) enum AppOpenPlatform {
109 MacOS,
110 Windows,
111 Linux,
112 Other,
113}
114
115impl AppOpenPlatform {
116 pub fn current() -> Self {
117 #[cfg(target_os = "macos")]
118 return Self::MacOS;
119 #[cfg(windows)]
120 return Self::Windows;
121 #[cfg(target_os = "linux")]
122 return Self::Linux;
123 #[cfg(not(any(target_os = "macos", windows, target_os = "linux")))]
124 return Self::Other;
125 }
126}
127
128#[derive(Clone, Debug)]
129pub(crate) struct OperatorAppStamp {
130 pub app: OperatorApp,
131 #[cfg(target_os = "macos")]
132 peer: CapturedPeer,
133 #[cfg(target_os = "macos")]
134 macos_rule: MacStampRule,
135 generation: std::sync::Arc<StampGeneration>,
136 #[cfg(all(test, target_os = "macos"))]
137 pub(crate) delivery_fixture: bool,
138 pub(crate) launch_incarnation: Option<u64>,
142}
143
144#[derive(Debug, Default)]
145struct StampGeneration {
146 #[cfg(target_os = "macos")]
147 flight: Mutex<Option<RouteStampCheck>>,
148 #[cfg(target_os = "macos")]
149 last_warning: Mutex<[Option<Instant>; 4]>,
150}
151
152#[cfg(target_os = "macos")]
153#[derive(Clone, Copy, Debug)]
154pub(crate) enum RouteStampFailure {
155 LaneBusy,
156 Deadline,
157 CheckFailed,
158 CheckRunning,
159}
160
161#[cfg(target_os = "macos")]
162impl RouteStampFailure {
163 pub(crate) fn reason(self) -> &'static str {
164 match self {
165 Self::LaneBusy => "lane_busy",
166 Self::Deadline => "deadline",
167 Self::CheckFailed => "check_failed",
168 Self::CheckRunning => "check_running",
169 }
170 }
171}
172
173#[cfg(target_os = "macos")]
174impl From<PeerIdentityError> for RouteStampFailure {
175 fn from(error: PeerIdentityError) -> Self {
176 match error {
177 PeerIdentityError::Busy => Self::LaneBusy,
178 PeerIdentityError::Deadline => Self::Deadline,
179 PeerIdentityError::CheckFailed => Self::CheckFailed,
180 }
181 }
182}
183
184#[cfg(target_os = "macos")]
185type RouteStampResult = Result<bool, RouteStampFailure>;
186
187#[cfg(target_os = "macos")]
188#[derive(Clone, Debug)]
189struct RouteStampCheck {
190 deadline: Instant,
191 revocation_revision: Option<u64>,
192 result: watch::Receiver<Option<RouteStampResult>>,
193 running: bool,
194}
195
196#[cfg(target_os = "macos")]
197struct RouteStampFlight {
198 generation: Arc<StampGeneration>,
199 result: watch::Receiver<Option<RouteStampResult>>,
200}
201
202#[cfg(target_os = "macos")]
203impl RouteStampFlight {
204 fn start_native(&self) -> Result<NativeStampCheck<'_>, RouteStampFailure> {
205 let mut flight = self
206 .generation
207 .flight
208 .lock()
209 .unwrap_or_else(|p| p.into_inner());
210 let current = flight
211 .as_mut()
212 .filter(|current| current.result.same_channel(&self.result))
213 .filter(|current| Instant::now() < current.deadline)
214 .ok_or(RouteStampFailure::Deadline)?;
215 current.running = true;
216 Ok(NativeStampCheck(self))
217 }
218
219 fn clear(&self, native_finished: bool) {
220 let mut flight = self
221 .generation
222 .flight
223 .lock()
224 .unwrap_or_else(|p| p.into_inner());
225 if flight.as_ref().is_some_and(|current| {
226 current.result.same_channel(&self.result) && (native_finished || !current.running)
227 }) {
228 *flight = None;
229 }
230 }
231}
232
233#[cfg(target_os = "macos")]
234struct NativeStampCheck<'a>(&'a RouteStampFlight);
235
236#[cfg(target_os = "macos")]
237impl Drop for NativeStampCheck<'_> {
238 fn drop(&mut self) {
239 self.0.clear(true);
240 }
241}
242
243#[cfg(target_os = "macos")]
244#[derive(Clone, Debug)]
245enum MacStampRule {
246 Release {
247 requirement: &'static str,
248 floor: Version,
249 },
250 Dev {
251 cdhash: [u8; 20],
252 opened: dev_builds::ConnectionOpened,
253 trusted_builds: std::sync::Arc<dev_builds::TrustedBuilds>,
254 },
255}
256
257impl OperatorAppStamp {
258 #[cfg(any(test, feature = "test-support"))]
259 pub(crate) fn fixture(app: &str, pid: u32) -> Self {
260 Self {
261 app: OperatorApp::new(app, pid),
262 #[cfg(target_os = "macos")]
263 peer: ObservedPeer::Unobserved.into(),
264 #[cfg(target_os = "macos")]
265 macos_rule: MacStampRule::Release {
266 requirement: MACOS_REQUIREMENT,
267 floor: RELEASE_FLOOR,
268 },
269 generation: Default::default(),
270 #[cfg(all(test, target_os = "macos"))]
271 delivery_fixture: false,
272 launch_incarnation: None,
273 }
274 }
275
276 #[cfg(windows)]
280 pub(crate) fn launch_stamp(app: OperatorApp, _peer: CapturedPeer, incarnation: u64) -> Self {
281 Self {
282 app,
283 generation: Default::default(),
284 launch_incarnation: Some(incarnation),
285 }
286 }
287
288 pub(crate) fn delivery_enabled(&self, policy: &OperatorAppPolicy) -> bool {
292 if self.launch_incarnation.is_some() {
293 policy.windows_enabled
294 } else {
295 policy.macos_enabled
296 }
297 }
298
299 pub(crate) async fn revalidate_with_launches(
302 &self,
303 launches: &crate::app_open::LaunchTable,
304 ) -> bool {
305 if let Some(incarnation) = self.launch_incarnation {
306 return launches.is_live_incarnation(&self.app.app, incarnation);
307 }
308 self.revalidate_native().await
309 }
310
311 #[cfg(all(test, target_os = "macos"))]
312 pub(crate) fn revalidate(&self) -> bool {
313 matches!(self.check_requirement(), Ok(true))
314 }
315
316 pub(crate) fn same_generation(&self, other: &Self) -> bool {
317 std::sync::Arc::ptr_eq(&self.generation, &other.generation)
318 }
319
320 #[cfg(target_os = "macos")]
321 pub(crate) fn is_dev_build(&self) -> bool {
322 matches!(self.macos_rule, MacStampRule::Dev { .. })
323 }
324
325 #[cfg(target_os = "macos")]
326 pub(crate) fn dev_revocation_revision(&self) -> Option<u64> {
327 match &self.macos_rule {
328 MacStampRule::Dev { trusted_builds, .. } => Some(trusted_builds.revocation_revision()),
329 MacStampRule::Release { .. } => None,
330 }
331 }
332
333 #[cfg(target_os = "macos")]
334 pub(crate) fn dev_hash(&self) -> Option<String> {
335 match self.macos_rule {
336 MacStampRule::Dev { cdhash, .. } => Some(dev_builds::format_hash(cdhash)),
337 MacStampRule::Release { .. } => None,
338 }
339 }
340
341 #[cfg(target_os = "macos")]
344 pub(crate) fn dev_store_diagnostic(&self) -> Option<subc_control::ConnectionDevBuild> {
345 let MacStampRule::Dev {
346 cdhash,
347 opened,
348 trusted_builds,
349 } = &self.macos_rule
350 else {
351 return None;
352 };
353 let cdhash = dev_builds::format_hash(*cdhash);
354 match trusted_builds.was_trusted_at(&cdhash, *opened) {
355 Err(reason) => Some(subc_control::ConnectionDevBuild::Unavailable {
356 reason: reason.into(),
357 }),
358 Ok(false) => Some(subc_control::ConnectionDevBuild::Untrusted { cdhash }),
359 Ok(true) => None,
360 }
361 }
362
363 async fn revalidate_native(&self) -> bool {
364 #[cfg(target_os = "macos")]
365 if self.peer.has_audit_token() {
366 let stamp = self.clone();
367 return PeerIdentityLane::native()
368 .run(move || matches!(stamp.check_requirement(), Ok(true)))
369 .await
370 .unwrap_or(false);
371 }
372 false
373 }
374
375 #[cfg(target_os = "macos")]
376 pub(crate) async fn revalidate_route(&self, policy: &OperatorAppPolicy) -> RouteStampResult {
377 if !self.peer.has_audit_token() {
378 return Err(RouteStampFailure::CheckFailed);
379 }
380 let stamp = self.clone();
381 #[cfg(test)]
382 let lane = policy.test_lane.clone();
383 self.share_route_check(policy, move || {
384 #[cfg(test)]
385 if let Some(lane) = &lane {
386 lane.probe_check(CheckPoint::RevalidationStarted);
387 }
388 let result = stamp.check_requirement();
389 #[cfg(test)]
390 if let Some(lane) = &lane {
391 lane.probe_check(CheckPoint::RevalidationChecked);
392 }
393 result
394 })
395 .await
396 }
397
398 #[cfg(target_os = "macos")]
399 async fn share_route_check(
400 &self,
401 policy: &OperatorAppPolicy,
402 work: impl FnOnce() -> RouteStampResult + Send + 'static,
403 ) -> RouteStampResult {
404 let revocation_revision = self.dev_revocation_revision();
405 let mut check = {
406 let mut flight = self
407 .generation
408 .flight
409 .lock()
410 .unwrap_or_else(|p| p.into_inner());
411 let now = Instant::now();
412 if let Some(active) = flight.as_ref().filter(|active| now < active.deadline) {
413 if active.revocation_revision != revocation_revision {
416 return Ok(false);
417 }
418 active.clone()
419 } else {
420 if flight.as_ref().is_some_and(|expired| expired.running) {
421 return Err(RouteStampFailure::CheckRunning);
422 }
423 let deadline = now + EVIDENCE_BUDGET;
424 let (publish, result) = watch::channel(None);
425 let check = RouteStampCheck {
426 deadline,
427 revocation_revision,
428 result,
429 running: false,
430 };
431 *flight = Some(check.clone());
432 let flight = Arc::new(RouteStampFlight {
433 generation: self.generation.clone(),
434 result: check.result.clone(),
435 });
436 let policy = policy.clone();
437 tokio::spawn(async move {
440 let native = flight.clone();
441 let result = policy
442 .peer_identity_lane()
443 .run_with_admission(deadline, Admission::Wait, move || {
444 let _running = native.start_native()?;
445 work()
446 })
447 .await
448 .map_err(RouteStampFailure::from)
449 .and_then(|result| result);
450 flight.clear(false);
451 publish.send_replace(Some(result));
452 });
453 check
454 }
455 };
456 let result = tokio::time::timeout_at(
457 check.deadline.into(),
458 check.result.wait_for(Option::is_some),
459 )
460 .await
461 .map_err(|_| RouteStampFailure::Deadline)?
462 .map_err(|_| RouteStampFailure::CheckFailed)?;
463 if Instant::now() >= check.deadline {
464 return Err(RouteStampFailure::Deadline);
465 }
466 if self.dev_revocation_revision() != revocation_revision {
467 return Ok(false);
468 }
469 result.expect("only a completed check wakes the waiter")
470 }
471
472 #[cfg(target_os = "macos")]
473 pub(crate) fn should_warn_route_check(&self, failure: RouteStampFailure) -> bool {
474 let mut warnings = self
475 .generation
476 .last_warning
477 .lock()
478 .unwrap_or_else(|p| p.into_inner());
479 let last = &mut warnings[failure as usize];
480 let now = Instant::now();
481 if last.is_some_and(|previous| now.duration_since(previous) < Duration::from_secs(60)) {
482 return false;
483 }
484 *last = Some(now);
485 true
486 }
487
488 #[cfg(target_os = "macos")]
489 fn check_requirement(&self) -> RouteStampResult {
490 use subc_os::local_peer::AppBundleError::VerifierUnavailable;
491 match &self.macos_rule {
492 MacStampRule::Release { requirement, floor } => {
493 match self.peer.check_sealed_app(requirement) {
494 Ok(code) => Ok(meets_release_floor(code.short_version.as_deref(), floor)),
495 Err(VerifierUnavailable) => Err(RouteStampFailure::CheckFailed),
496 Err(_) => Ok(false),
497 }
498 }
499 MacStampRule::Dev {
500 cdhash,
501 opened,
502 trusted_builds,
503 } => match self.peer.check_dev_app(dev_builds::IDENTIFIER) {
504 Some(Err(VerifierUnavailable)) => Err(RouteStampFailure::CheckFailed),
505 Some(Ok(code)) if code.cdhash == *cdhash => trusted_builds
506 .was_trusted_at(&dev_builds::format_hash(*cdhash), *opened)
507 .map_err(|_| RouteStampFailure::CheckFailed),
508 _ => Ok(false),
509 },
510 }
511 }
512}
513
514#[derive(Default)]
515pub(crate) struct RecognitionEvidence {
516 pub stamp: Option<(OperatorAppStamp, ObservedPeer)>,
517 pub dev_build: Option<subc_control::ConnectionDevBuild>,
518}
519
520#[derive(Clone, Copy, Debug, PartialEq, Eq)]
521pub(crate) enum Admission {
522 Immediate,
523 Wait,
524}
525
526pub(crate) struct ImmediateAdmissionRefused;
527
528#[cfg(target_os = "macos")]
529#[derive(Debug, Default)]
530enum RecognitionPhase {
531 #[default]
532 Queued,
533 Running,
534 Returned(Instant),
535}
536
537#[cfg(target_os = "macos")]
538#[derive(Debug, Default)]
539pub(crate) struct RecognitionProgress {
540 phase: Mutex<RecognitionPhase>,
541}
542
543#[cfg(target_os = "macos")]
544impl RecognitionProgress {
545 fn start(&self, deadline: Instant) -> Option<RunningRecognition<'_>> {
546 let mut phase = self.phase.lock().unwrap_or_else(|p| p.into_inner());
547 if Instant::now() >= deadline {
548 return None;
549 }
550 *phase = RecognitionPhase::Running;
551 Some(RunningRecognition(self))
552 }
553
554 pub(crate) fn is_running(&self) -> bool {
555 matches!(
556 *self.phase.lock().unwrap_or_else(|p| p.into_inner()),
557 RecognitionPhase::Running
558 )
559 }
560
561 pub(crate) fn returned_after(&self, arrived: Instant) -> bool {
562 matches!(*self.phase.lock().unwrap_or_else(|p| p.into_inner()), RecognitionPhase::Returned(at) if arrived <= at)
563 }
564
565 #[cfg(test)]
566 pub(crate) fn complete_for_test(&self, deadline: Instant) {
567 drop(
568 self.start(deadline)
569 .expect("staged check must finish before its deadline"),
570 );
571 }
572}
573
574#[cfg(target_os = "macos")]
575struct RunningRecognition<'a>(&'a RecognitionProgress);
576
577#[cfg(target_os = "macos")]
578impl Drop for RunningRecognition<'_> {
579 fn drop(&mut self) {
580 let returned = Instant::now();
581 *self.0.phase.lock().unwrap_or_else(|p| p.into_inner()) =
582 RecognitionPhase::Returned(returned);
583 }
584}
585
586#[derive(Clone, Debug)]
587pub(crate) struct OperatorAppPolicy {
588 pub macos_enabled: bool,
589 pub windows_enabled: bool,
590 pub linux_enabled: bool,
591 pub phone_enabled: bool,
592 app: CompiledApp,
593 #[cfg(target_os = "macos")]
594 requirement: &'static str,
595 #[cfg(target_os = "macos")]
596 pub(crate) trusted_builds: std::sync::Arc<dev_builds::TrustedBuilds>,
597 floor: Version,
598 #[cfg(all(test, target_os = "macos"))]
599 requirement_checks: std::sync::Arc<std::sync::atomic::AtomicUsize>,
600 #[cfg(test)]
601 pub(crate) test_lane: Option<std::sync::Arc<crate::peer_identity_lane::PeerIdentityLane>>,
602 pub windows_path: Option<std::path::PathBuf>,
606 pub linux_path: Option<std::path::PathBuf>,
607 #[cfg_attr(not(windows), allow(dead_code))]
613 pub windows_breakaway: bool,
614 #[cfg_attr(not(target_os = "linux"), allow(dead_code))]
619 pub linux_force_direct: bool,
620}
621
622impl Default for OperatorAppPolicy {
623 fn default() -> Self {
624 Self {
625 macos_enabled: MACOS_OPERATOR_APP_ENABLED,
626 windows_enabled: WINDOWS_OPERATOR_APP_ENABLED,
627 linux_enabled: LINUX_OPERATOR_APP_ENABLED,
628 phone_enabled: PHONE_OPERATOR_ENABLED,
629 app: COMPILED_APP,
630 #[cfg(target_os = "macos")]
631 requirement: MACOS_REQUIREMENT,
632 #[cfg(target_os = "macos")]
633 trusted_builds: Default::default(),
634 floor: effective_release_floor(),
635 #[cfg(all(test, target_os = "macos"))]
636 requirement_checks: Default::default(),
637 #[cfg(test)]
638 test_lane: None,
639 windows_path: COMPILED_APP.windows_path.map(std::path::PathBuf::from),
640 linux_path: COMPILED_APP.linux_path.map(std::path::PathBuf::from),
641 windows_breakaway: true,
642 linux_force_direct: false,
643 }
644 }
645}
646
647impl OperatorAppPolicy {
648 pub(crate) fn app_id(&self) -> Option<&'static str> {
654 self.app.id
655 }
656
657 #[cfg(windows)]
658 pub(crate) fn release_floor(&self) -> &Version {
659 &self.floor
660 }
661
662 pub(crate) fn installed_path(&self, platform: AppOpenPlatform) -> Option<std::path::PathBuf> {
663 match platform {
664 AppOpenPlatform::Windows => self.windows_path.clone(),
665 AppOpenPlatform::Linux => self.linux_path.clone(),
666 AppOpenPlatform::MacOS | AppOpenPlatform::Other => None,
667 }
668 }
669
670 pub(crate) fn switch_enabled(&self, platform: AppOpenPlatform) -> bool {
671 match platform {
672 AppOpenPlatform::MacOS => self.macos_enabled,
673 AppOpenPlatform::Windows => self.windows_enabled,
674 AppOpenPlatform::Linux => self.linux_enabled,
675 AppOpenPlatform::Other => false,
676 }
677 }
678
679 #[cfg(windows)]
684 pub(crate) fn windows_publisher(&self) -> Option<&'static str> {
685 self.app.windows_publisher
686 }
687
688 #[cfg(test)]
689 pub(crate) fn stamp(&self, peer: CapturedPeer) -> Option<OperatorAppStamp> {
690 #[cfg(target_os = "macos")]
691 if !self.macos_enabled {
692 return None;
693 }
694 #[cfg(target_os = "macos")]
695 return self.config_identity(peer);
696 #[cfg(not(target_os = "macos"))]
697 {
698 let _ = peer;
699 None
700 }
701 }
702
703 #[cfg(target_os = "macos")]
704 pub(crate) fn config_identity(&self, peer: CapturedPeer) -> Option<OperatorAppStamp> {
705 if self.floor == RELEASE_FLOOR {
706 return None;
707 }
708 let app = self.app.id?;
709 let ObservedPeer::Observed(observation) = peer.observation() else {
710 return None;
711 };
712 let pid = observation.pid;
713 #[cfg(test)]
714 self.requirement_checks
715 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
716 let code = peer.check_sealed_app(self.requirement).ok()?;
717 if !meets_release_floor(code.short_version.as_deref(), &self.floor) {
718 return None;
719 }
720 Some(OperatorAppStamp {
721 app: OperatorApp::new(app, pid),
722 peer,
723 macos_rule: MacStampRule::Release {
724 requirement: self.requirement,
725 floor: self.floor.clone(),
726 },
727 generation: Default::default(),
728 #[cfg(test)]
729 delivery_fixture: false,
730 launch_incarnation: None,
731 })
732 }
733
734 pub(crate) fn may_recognize(&self, peer: &CapturedPeer) -> bool {
735 #[cfg(test)]
736 if self.test_lane.is_some() {
737 return true;
738 }
739 (self.macos_enabled || self.floor != RELEASE_FLOOR)
740 && self.app.id.is_some()
741 && peer.has_audit_token()
742 }
743
744 #[cfg(target_os = "macos")]
745 fn recognize_code(
746 &self,
747 peer: CapturedPeer,
748 opened: dev_builds::ConnectionOpened,
749 ) -> Option<RecognitionEvidence> {
750 use subc_control::ConnectionDevBuild;
751
752 if let Some(stamp) = self.config_identity(peer.clone()) {
753 return Some(RecognitionEvidence {
754 stamp: Some((stamp, peer.observe_code())),
755 dev_build: None,
756 });
757 }
758 if !self.macos_enabled {
759 return None;
760 }
761 let app = self.app.id?;
762 let ObservedPeer::Observed(observation) = peer.observation() else {
763 return None;
764 };
765 let dev_build = match peer.check_dev_app(dev_builds::IDENTIFIER)? {
766 Err(error) => ConnectionDevBuild::Ineligible {
767 reason: error.message(),
768 },
769 Ok(code) => {
770 let cdhash = dev_builds::format_hash(code.cdhash);
771 if let Err(reason) = dev_builds::version(&code) {
772 ConnectionDevBuild::Ineligible {
773 reason: reason.into(),
774 }
775 } else {
776 match self.trusted_builds.was_trusted_at(&cdhash, opened) {
777 Err(reason) => ConnectionDevBuild::Unavailable {
778 reason: reason.into(),
779 },
780 Ok(false) => ConnectionDevBuild::Untrusted { cdhash },
781 Ok(true) => {
782 let stamp = OperatorAppStamp {
783 app: OperatorApp::new(app, observation.pid),
784 peer: peer.clone(),
785 macos_rule: MacStampRule::Dev {
786 cdhash: code.cdhash,
787 opened,
788 trusted_builds: self.trusted_builds.clone(),
789 },
790 generation: Default::default(),
791 #[cfg(test)]
792 delivery_fixture: false,
793 launch_incarnation: None,
794 };
795 return Some(RecognitionEvidence {
796 stamp: Some((stamp, peer.observe_code())),
797 dev_build: None,
798 });
799 }
800 }
801 }
802 }
803 };
804 Some(RecognitionEvidence {
805 stamp: None,
806 dev_build: Some(dev_build),
807 })
808 }
809
810 #[cfg(target_os = "macos")]
811 fn peer_identity_lane(&self) -> &PeerIdentityLane {
812 #[cfg(test)]
813 if let Some(lane) = &self.test_lane {
814 return lane;
815 }
816 PeerIdentityLane::native()
817 }
818
819 pub(crate) async fn recognize(
820 &self,
821 peer: CapturedPeer,
822 deadline: std::time::Instant,
823 admission: Admission,
824 #[cfg(target_os = "macos")] opened: dev_builds::ConnectionOpened,
825 #[cfg(target_os = "macos")] progress: Arc<RecognitionProgress>,
826 ) -> Result<Option<RecognitionEvidence>, ImmediateAdmissionRefused> {
827 #[cfg(not(target_os = "macos"))]
828 let _ = &peer;
829 #[cfg(all(test, not(target_os = "macos")))]
830 let result =
831 match &self.test_lane {
832 Some(lane) => {
833 lane.run_with_admission(deadline, admission, || {
834 Some(RecognitionEvidence::default())
835 })
836 .await
837 }
838 None => return Ok(None),
839 };
840 #[cfg(target_os = "macos")]
841 let result = {
842 let policy = self.clone();
843 self.peer_identity_lane()
844 .run_with_admission(deadline, admission, move || {
845 #[cfg(test)]
846 if !peer.has_audit_token() {
847 return Some(RecognitionEvidence::default());
848 }
849 let result = {
850 let _running = progress.start(deadline)?;
851 #[cfg(test)]
852 policy
853 .peer_identity_lane()
854 .probe_check(CheckPoint::RecognitionStarted);
855 policy.recognize_code(peer, opened).unwrap_or_default()
856 };
857 #[cfg(test)]
858 policy
859 .peer_identity_lane()
860 .probe_check(CheckPoint::RecognitionReturned);
861 Some(result)
862 })
863 .await
864 };
865 #[cfg(any(target_os = "macos", test))]
866 {
867 match result {
868 Err(PeerIdentityError::Busy) if admission == Admission::Immediate => {
869 Err(ImmediateAdmissionRefused)
870 }
871 result => Ok(result.ok().flatten()),
872 }
873 }
874 #[cfg(not(any(target_os = "macos", test)))]
875 {
876 let _ = (deadline, admission);
877 Ok(None)
878 }
879 }
880}
881
882#[cfg(any(test, feature = "test-support"))]
886#[derive(Clone, Debug)]
887pub struct TestOperatorAppPolicy {
888 pub macos_enabled: bool,
889 pub windows_enabled: bool,
890 pub linux_enabled: bool,
891 pub app: &'static str,
892 pub requirement: &'static str,
893 pub floor: Version,
894 pub windows_publisher: Option<&'static str>,
895 pub windows_path: Option<std::path::PathBuf>,
896 pub linux_path: Option<std::path::PathBuf>,
897 pub windows_breakaway: bool,
898 pub linux_force_direct: bool,
899}
900
901#[cfg(any(test, feature = "test-support"))]
902impl From<TestOperatorAppPolicy> for OperatorAppPolicy {
903 fn from(test: TestOperatorAppPolicy) -> Self {
904 Self {
905 macos_enabled: test.macos_enabled,
906 windows_enabled: test.windows_enabled,
907 linux_enabled: test.linux_enabled,
908 phone_enabled: PHONE_OPERATOR_ENABLED,
909 app: CompiledApp {
910 id: Some(test.app),
911 windows_publisher: test.windows_publisher,
912 ..COMPILED_APP
913 },
914 #[cfg(target_os = "macos")]
915 requirement: test.requirement,
916 #[cfg(target_os = "macos")]
917 trusted_builds: Default::default(),
918 floor: test.floor,
919 #[cfg(all(test, target_os = "macos"))]
920 requirement_checks: Default::default(),
921 #[cfg(test)]
922 test_lane: None,
923 windows_path: test.windows_path,
924 linux_path: test.linux_path,
925 windows_breakaway: test.windows_breakaway,
926 linux_force_direct: test.linux_force_direct,
927 }
928 }
929}
930
931#[cfg(test)]
932mod tests;