use super::*;
use crate::operator_apps::{OperatorAppStamp, EVIDENCE_BUDGET};
use subc_os::local_peer::CapturedPeer;
use tokio::sync::watch;
#[derive(Debug)]
pub(super) struct PeerCapture {
peer: CapturedPeer,
#[cfg(target_os = "macos")]
opened: crate::operator_apps::dev_builds::ConnectionOpened,
recognized: Mutex<Option<Recognition>>,
#[cfg(target_os = "macos")]
revoked: std::sync::OnceLock<String>,
}
impl PeerCapture {
pub(super) fn observed_pid(&self) -> Option<u32> {
match self.peer.observation() {
subc_os::local_peer::ObservedPeer::Observed(peer) => Some(peer.pid),
subc_os::local_peer::ObservedPeer::Unobserved => None,
}
}
#[cfg(target_os = "macos")]
pub(super) fn local_caller(&self) -> Option<subc_os::socket_peer::SocketPeer> {
Some(subc_os::socket_peer::SocketPeer {
pid: self.observed_pid()?,
executable: self.peer.running_executable()?,
})
}
}
#[derive(Clone, Debug)]
struct Recognition {
deadline: std::time::Instant,
verdict: watch::Receiver<RecognitionVerdict>,
}
#[derive(Debug)]
enum RecognitionVerdict {
Pending,
Retry(Option<subc_control::ConnectionDevBuild>),
Complete {
stamp: Option<OperatorAppStamp>,
dev_build: Option<subc_control::ConnectionDevBuild>,
},
}
#[derive(Default)]
struct RecognizedPeer {
fresh: Option<OperatorAppStamp>,
dev_build: Option<subc_control::ConnectionDevBuild>,
}
impl From<CapturedPeer> for PeerCapture {
fn from(peer: CapturedPeer) -> Self {
Self {
peer,
#[cfg(target_os = "macos")]
opened: crate::operator_apps::dev_builds::ConnectionOpened::now(),
recognized: Default::default(),
#[cfg(target_os = "macos")]
revoked: Default::default(),
}
}
}
type StampMap = Mutex<HashMap<ConnectionId, OperatorAppStamp>>;
impl ControlHandler {
pub(crate) fn record_captured_peer(&self, connection: ConnectionId, peer: CapturedPeer) {
self.record_observed_peer(connection, peer.observation().clone());
#[cfg(windows)]
{
if let Some(identity) = self.config_windows_launch_identity(&peer) {
self.config_desktop_stamps
.lock()
.unwrap_or_else(|p| p.into_inner())
.insert(connection, identity);
}
if let Some(stamp) = self.stamp_windows_launch(&peer) {
self.operator_apps
.lock()
.unwrap_or_else(|p| p.into_inner())
.insert(connection, stamp);
}
}
self.captured_peers
.lock()
.unwrap_or_else(|p| p.into_inner())
.insert(connection, Arc::new(peer.into()));
}
async fn recognize_peer(&self, connection: ConnectionId) -> RecognizedPeer {
let capture = self
.captured_peers
.lock()
.unwrap_or_else(|p| p.into_inner())
.get(&connection)
.cloned();
let Some(capture) =
capture.filter(|capture| self.operator_app_policy.may_recognize(&capture.peer))
else {
return RecognizedPeer::default();
};
let recognition = {
let mut slot = capture.recognized.lock().unwrap_or_else(|p| p.into_inner());
let restart = slot
.as_ref()
.is_some_and(|active| match &*active.verdict.borrow() {
RecognitionVerdict::Complete { .. } => false,
RecognitionVerdict::Pending => std::time::Instant::now() >= active.deadline,
RecognitionVerdict::Retry(_) => true,
});
if restart {
*slot = None;
}
if let Some(active) = slot.as_ref() {
if let RecognitionVerdict::Complete { dev_build, .. } = &*active.verdict.borrow() {
return RecognizedPeer {
fresh: None,
dev_build: dev_build.clone(),
};
}
active.clone()
} else {
let deadline = std::time::Instant::now() + EVIDENCE_BUDGET;
let (tx, verdict) = watch::channel(RecognitionVerdict::Pending);
let handler = self.clone();
let capture = capture.clone();
tokio::spawn(async move {
#[cfg(target_os = "macos")]
let revision = handler
.operator_app_policy
.trusted_builds
.revocation_revision();
let mut verified = None;
let mut dev_build = None;
let mut complete = false;
if let Some(evidence) = handler
.operator_app_policy
.recognize(
capture.peer.clone(),
deadline,
#[cfg(target_os = "macos")]
capture.opened,
)
.await
{
let captures = handler
.captured_peers
.lock()
.unwrap_or_else(|p| p.into_inner());
if std::time::Instant::now() < deadline
&& captures
.get(&connection)
.is_some_and(|live| Arc::ptr_eq(live, &capture))
{
#[cfg(target_os = "macos")]
if evidence
.stamp
.as_ref()
.is_some_and(|(stamp, _)| stamp.is_dev_build())
&& revision
!= handler
.operator_app_policy
.trusted_builds
.revocation_revision()
{
tx.send_replace(RecognitionVerdict::Retry(None));
return;
}
dev_build = evidence.dev_build;
complete = !matches!(
dev_build,
Some(subc_control::ConnectionDevBuild::Unavailable { .. })
);
if let Some((stamp, observed)) = evidence.stamp {
handler.record_observed_peer(connection, observed);
verified = Some(stamp.clone());
#[cfg(target_os = "macos")]
if !stamp.is_dev_build() {
handler
.config_desktop_stamps
.lock()
.unwrap_or_else(|p| p.into_inner())
.insert(connection, stamp.clone());
}
if stamp.delivery_enabled(&handler.operator_app_policy) {
handler
.operator_apps
.lock()
.unwrap_or_else(|p| p.into_inner())
.insert(connection, stamp);
}
}
}
}
tx.send_replace(if complete {
RecognitionVerdict::Complete {
stamp: verified,
dev_build,
}
} else {
RecognitionVerdict::Retry(dev_build)
});
});
let active = Recognition { deadline, verdict };
*slot = Some(active.clone());
active
}
};
let mut verdict = recognition.verdict.clone();
let waiting = matches!(*verdict.borrow_and_update(), RecognitionVerdict::Pending);
if waiting
&& !matches!(
tokio::time::timeout_at(recognition.deadline.into(), verdict.changed()).await,
Ok(Ok(()))
)
{
return RecognizedPeer::default();
}
let result = match &*verdict.borrow() {
RecognitionVerdict::Complete { stamp, dev_build } => RecognizedPeer {
fresh: stamp.clone(),
dev_build: dev_build.clone(),
},
RecognitionVerdict::Retry(dev_build) => RecognizedPeer {
fresh: None,
dev_build: dev_build.clone(),
},
RecognitionVerdict::Pending => RecognizedPeer::default(),
};
result
}
async fn recognize_operator_peer(&self, connection: ConnectionId) -> RecognizedPeer {
if self.operator_app_policy.macos_enabled {
self.recognize_peer(connection).await
} else {
RecognizedPeer::default()
}
}
#[cfg(target_os = "macos")]
fn revoked_build_diagnostic(
&self,
connection: ConnectionId,
) -> Option<subc_control::ConnectionDevBuild> {
let capture = self
.captured_peers
.lock()
.unwrap_or_else(|p| p.into_inner())
.get(&connection)
.cloned()?;
Some(subc_control::ConnectionDevBuild::Untrusted {
cdhash: capture.revoked.get()?.clone(),
})
}
fn cached_stamp(stamps: &StampMap, connection: ConnectionId) -> Option<OperatorAppStamp> {
stamps
.lock()
.unwrap_or_else(|p| p.into_inner())
.get(&connection)
.cloned()
}
#[cfg(target_os = "macos")]
pub(super) fn close_revoked_app_connections(&self, cdhash: &str) {
let captures = self
.captured_peers
.lock()
.unwrap_or_else(|p| p.into_inner());
let mut stamps = self.operator_apps.lock().unwrap_or_else(|p| p.into_inner());
stamps.retain(|connection, stamp| {
if stamp.dev_hash().as_deref() != Some(cdhash) {
return true;
}
if let Some(capture) = captures.get(connection) {
let _ = capture.revoked.set(cdhash.into());
}
self.forwarding.request_connection_close(
*connection,
CloseReason::new("app_untrusted", "The desktop build's trust was removed."),
);
false
});
}
async fn current_stamp(
&self,
stamps: &StampMap,
connection: ConnectionId,
delivery_required: bool,
) -> Option<OperatorAppStamp> {
let fresh = if delivery_required {
self.recognize_operator_peer(connection).await.fresh
} else {
self.recognize_peer(connection).await.fresh
};
let stamp = Self::cached_stamp(stamps, connection)?;
if delivery_required && !stamp.delivery_enabled(&self.operator_app_policy) {
return None;
}
let freshly_verified = fresh.is_some_and(|fresh| fresh.same_generation(&stamp));
if !freshly_verified && !stamp.revalidate_with_launches(&self.launch_table).await {
return None;
}
Self::cached_stamp(stamps, connection).filter(|current| stamp.same_generation(current))
}
#[cfg(not(feature = "dev-desktop-approval"))]
pub(super) async fn has_current_config_desktop_stamp(&self, connection: ConnectionId) -> bool {
self.current_stamp(&self.config_desktop_stamps, connection, false)
.await
.is_some()
}
pub(super) async fn operator_shortcut_stamp(
&self,
connection: ConnectionId,
) -> Option<OperatorAppStamp> {
self.current_stamp(&self.operator_apps, connection, true)
.await
}
pub(super) async fn route_operator_app(
&self,
connection: ConnectionId,
capabilities: Option<&CapabilityDeclarations>,
harness: &str,
) -> Option<OperatorAppStamp> {
#[cfg(not(feature = "test-support"))]
let _ = harness;
if capabilities.is_some_and(|caps| {
caps.provides
.iter()
.any(|cap| cap == OPERATOR_APP_CAPABILITY)
}) {
let fresh = self.recognize_operator_peer(connection).await.fresh;
let stamp = self.deliverable_stamp(connection, fresh).await;
#[cfg(feature = "test-support")]
if stamp.is_none() && self.test_operator_app_harness.as_deref() == Some(harness) {
let pid = self
.captured_peers
.lock()
.unwrap_or_else(|p| p.into_inner())
.get(&connection)
.and_then(|capture| capture.observed_pid())
.unwrap_or(0);
return Some(OperatorAppStamp::fixture("alfonso-desktop", pid));
}
return stamp;
}
None
}
async fn deliverable_stamp(
&self,
connection: ConnectionId,
fresh: Option<OperatorAppStamp>,
) -> Option<OperatorAppStamp> {
let stamp = Self::cached_stamp(&self.operator_apps, connection)?;
if !stamp.delivery_enabled(&self.operator_app_policy) {
return None;
}
#[cfg(all(test, target_os = "macos"))]
if stamp.delivery_fixture {
return Some(stamp);
}
#[cfg(not(target_os = "macos"))]
let _ = fresh;
#[cfg(target_os = "macos")]
{
if !fresh.is_some_and(|fresh| fresh.same_generation(&stamp))
&& !stamp.revalidate_with_launches(&self.launch_table).await
{
return None;
}
return Self::cached_stamp(&self.operator_apps, connection)
.filter(|current| stamp.same_generation(current));
}
#[cfg(not(target_os = "macos"))]
Some(stamp)
}
pub(super) async fn handle_connection_describe(
&self,
ctx: &RouteCtx,
frame: Frame,
) -> Result<Vec<Frame>, RouterError> {
if serde_json::from_slice::<subc_control::ConnectionDescribeRequest>(&frame.body).is_err() {
return Ok(vec![control_error_frame(
&frame,
"invalid_control_body",
"malformed connection.describe body",
)?]);
}
let local = self
.local_connections
.lock()
.unwrap_or_else(|p| p.into_inner())
.contains(&ctx.connection_id);
let recognized = self.recognize_operator_peer(ctx.connection_id).await;
let stamp = self
.deliverable_stamp(ctx.connection_id, recognized.fresh)
.await;
let operator_app = self.connection_operator_app(stamp.as_ref());
let mut reply = subc_control::ConnectionDescribeReply::new(local, operator_app);
if reply.operator_app.is_none() {
reply.dev_build = recognized.dev_build;
#[cfg(target_os = "macos")]
{
if reply.dev_build.is_none() {
if let Some(stamp) = Self::cached_stamp(&self.operator_apps, ctx.connection_id)
.filter(OperatorAppStamp::is_dev_build)
{
reply.dev_build = crate::peer_identity_lane::PeerIdentityLane::native()
.run(move || stamp.dev_store_diagnostic())
.await
.flatten();
}
}
if let Some(revoked) = self.revoked_build_diagnostic(ctx.connection_id) {
reply.dev_build = Some(revoked);
}
}
}
Ok(vec![control_response_body_frame(
&frame,
&reply,
ops::CONNECTION_DESCRIBE,
)?])
}
}
impl ControlHandler {
pub(super) async fn handle_operator_confirm(
&self,
ctx: &RouteCtx,
frame: Frame,
) -> Result<Vec<Frame>, RouterError> {
use crate::operator_confirm::{audit, Outcome, ShortcutContext};
let registration = self
.registry
.get_module_by_connection(ctx.connection_id)
.map_err(|err| RouterError::backend(0, frame.header.corr, err.to_string()))?;
let Some(registration) = registration else {
let outcome = Outcome::refusal("not_registered");
audit("", "", "", &outcome, Duration::ZERO, Duration::ZERO, false);
return Ok(vec![outcome.frame(&frame)]);
};
let request = match serde_json::from_slice::<OperatorConfirmRequest>(&frame.body) {
Ok(request) => request,
Err(_) => {
let outcome = Outcome::refusal("invalid_control_body");
audit("", "", "", &outcome, Duration::ZERO, Duration::ZERO, false);
return Ok(vec![outcome.frame(&frame)]);
}
};
let declared = matches!(
request.kind,
Some(subc_protocol::session::OperatorConfirmKind::Operation)
) && request.operation.as_ref().is_some_and(|operation| {
registration
.manifest
.confirm_operations
.as_ref()
.is_some_and(|operations| operations.contains(operation))
});
let module_id = registration.manifest.module_id;
let nonce = self
.hello_launch_nonces
.lock()
.unwrap_or_else(|p| p.into_inner())
.nonce(ctx.connection_id)
.map(str::to_owned);
let nonce_proven = self
.confirm_channel_proven(ctx.connection_id, &module_id)
.unwrap_or_else(|| {
nonce.as_deref().is_some_and(|nonce| {
self.supervisor
.spawned_consumer_authorized(&module_id, nonce)
})
});
let route = (request.route_channel, request.route_epoch);
let candidate = if nonce_proven
&& crate::operator_confirm::valid_summary(&request.summary)
&& declared
{
self.forwarding
.with_operator_route(ctx.connection_id, route.0, route.1, |binding| {
binding.map(|binding| {
(
binding.flow.clone(),
binding.client_connection_id,
ShortcutContext::phone_fingerprint(&self.operator_app_policy, binding),
)
})
})
.map_err(RouterError::Forwarding)?
} else {
None
};
let shortcut = if let Some((flow, opener, phone)) = candidate {
let stamp = if phone.is_none() {
self.operator_shortcut_stamp(opener).await
} else {
None
};
(phone.is_some() || stamp.is_some()).then(|| {
(
flow,
self.shortcut_context(stamp, phone, Some(route), opener),
)
})
} else {
None
};
let confirms = self.forwarding.operator_confirms();
self.forwarding
.with_operator_route(ctx.connection_id, route.0, route.1, |binding| {
let shortcut = shortcut.and_then(|(flow, context)| {
binding
.filter(|current| {
Arc::ptr_eq(¤t.flow, &flow)
&& context.stamp.as_ref().is_none_or(|stamp| {
current
.operator_app
.as_ref()
.map_or(stamp.launch_incarnation.is_none(), |bound| {
bound.same_generation(stamp)
})
})
})
.map(|_| context)
});
confirms.admit_with_shortcut(
ctx,
frame,
module_id,
nonce_proven,
request,
binding,
shortcut,
)
})
.map_err(RouterError::Forwarding)
}
pub(super) fn shortcut_context(
&self,
stamp: Option<OperatorAppStamp>,
phone_fingerprint: Option<String>,
route: Option<(u16, u32)>,
stamp_owner: ConnectionId,
) -> crate::operator_confirm::ShortcutContext {
crate::operator_confirm::ShortcutContext {
ledger: self.activity.clone(),
forwarding: self.forwarding.clone(),
launches: self.launch_table.clone(),
stamp,
phone_fingerprint,
route,
connections: self.operator_apps.clone(),
stamp_owner: Some(stamp_owner),
#[cfg(test)]
hooks: Default::default(),
}
}
}