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