1use subc_control::config::{ConfigControlRequest, ConfigControlResponse};
2
3use super::*;
4mod admission;
5mod daemon_readers;
6pub(super) use daemon_readers::preview_approved_daemon;
7mod delivery_worker;
8mod phone;
9mod recovery;
10mod route_policy;
11mod widening;
12
13const CONFIG_REVIEW_TIMEOUT: Duration = Duration::from_secs(30);
15
16const CONFIG_APPROVAL_COMMIT_TIMEOUT: Duration = Duration::from_secs(30);
19use crate::config_gate::{
20 ApprovalChallenge, ApprovalFacts, ApprovalReply, GateError, PlanKind, PresenceDecision,
21};
22
23pub(super) fn is_config_op(op: &str) -> bool {
24 matches!(
25 op,
26 "config.status"
27 | "config.plan"
28 | "config.apply"
29 | "config.stamp"
30 | "config.unstamp"
31 | "config.history"
32 | "config.rollback"
33 | "config.place_program"
34 )
35}
36
37pub(super) fn is_module_config_op(op: &str) -> bool {
38 matches!(op, "config.declare" | "config.get" | "config.applied")
39}
40
41impl PrivilegedRequest for ConfigControlRequest {
42 fn privileged_operation(&self) -> Option<PrivilegedOperation<'_>> {
43 match self {
47 Self::Status {} => None,
48 Self::Plan {} => None,
49 Self::Apply { .. } => None,
50 Self::Stamp {} => None,
51 Self::Unstamp {} => None,
52 Self::History {} => None,
53 Self::Rollback { .. } => None,
54 Self::PlaceProgram { .. } => None,
55 _ => None,
56 }
57 }
58}
59
60impl ControlHandler {
61 #[cfg(feature = "test-support")]
62 pub(crate) fn with_config_os_prompt_policy_for_tests(self) -> Self {
63 if let Some(owner) = self.config_runtime.as_ref() {
64 owner.set_os_prompt_policy_for_tests();
65 }
66 self
67 }
68 fn config_delivery_target_current(
69 &self,
70 module: &str,
71 connection: ConnectionId,
72 active: bool,
73 correlation: u64,
74 ) -> Result<bool, RouterError> {
75 if active {
76 Ok(self
77 .registry
78 .get_module(module)
79 .map_err(|error| RouterError::backend(0, correlation, error.to_string()))?
80 .is_some_and(|target| target.connection_id == connection)
81 && self
82 .forwarding
83 .active_module_endpoint(module)
84 .map_err(RouterError::Forwarding)?
85 .is_some_and(|target| target.connection_id == connection))
86 } else {
87 Ok(self
88 .registry
89 .get_candidate(module)
90 .map_err(|error| RouterError::backend(0, correlation, error.to_string()))?
91 .is_some_and(|target| target.connection_id == connection))
92 }
93 }
94
95 pub(crate) fn defers_config_approval(&self, frame: &Frame) -> bool {
96 frame.header.channel == 0
97 && frame.header.ty == FrameType::Request
98 && matches!(
99 serde_json::from_slice::<ConfigControlRequest>(&frame.body),
100 Ok(ConfigControlRequest::Apply { .. })
101 )
102 }
103
104 pub(crate) fn reserve_config_approval(
105 &self,
106 ctx: &RouteCtx,
107 frame: &Frame,
108 ) -> std::result::Result<Option<crate::config_gate::runtime::ApprovalRequestGuard>, GateError>
109 {
110 if self.defers_config_approval(frame) {
111 if let Some(owner) = &self.config_runtime {
112 return owner
113 .reserve_approval_request(ctx.connection_id, frame.header.corr)
114 .map(Some);
115 }
116 }
117 Ok(None)
118 }
119
120 pub(super) fn cancel_config_approval(&self, caller: ConnectionId, correlation: u64) -> bool {
121 use crate::config_gate::runtime::CancelApprovalRequest;
122 let Some(owner) = &self.config_runtime else {
123 return false;
124 };
125 match owner.cancel_approval_request_outcome(caller, correlation) {
126 CancelApprovalRequest::Unknown => false,
127 CancelApprovalRequest::Withdrawn | CancelApprovalRequest::AlreadyReported => true,
128 CancelApprovalRequest::TooLate => {
129 if let Some(activity) = &self.activity {
130 activity.config_cancel_too_late(caller, correlation);
131 }
132 true
133 }
134 }
135 }
136
137 pub(super) async fn handle_module_config_request(
138 &self,
139 ctx: &RouteCtx,
140 frame: Frame,
141 op: &str,
142 ) -> Result<Vec<Frame>, RouterError> {
143 let Some(runtime) = self.config_runtime.clone() else {
144 return Ok(vec![control_error_frame(
145 &frame,
146 "config_gate_inactive",
147 "no config store configured",
148 )?]);
149 };
150 let registration = self
151 .registry
152 .get_module_by_connection(ctx.connection_id)
153 .map_err(|error| RouterError::backend(0, frame.header.corr, error.to_string()))?;
154 let Some(registration) = registration else {
155 return Ok(vec![control_error_frame(
156 &frame,
157 "not_registered",
158 "module config operations require a registered connection",
159 )?]);
160 };
161 let module = registration.manifest.module_id.clone();
162 let gate = runtime
163 .module_gate(&module)
164 .map_err(|e| RouterError::backend(0, frame.header.corr, e.to_string()))?;
165 let _gate = gate.lock().await;
166 let active = self
167 .registry
168 .get_module(&module)
169 .map_err(|error| RouterError::backend(0, frame.header.corr, error.to_string()))?
170 .is_some_and(|r| r.connection_id == ctx.connection_id)
171 && self
172 .forwarding
173 .active_module_endpoint(&module)
174 .map_err(RouterError::Forwarding)?
175 .is_some_and(|target| target.connection_id == ctx.connection_id);
176 let candidate = self
177 .registry
178 .get_candidate(&module)
179 .map_err(|error| RouterError::backend(0, frame.header.corr, error.to_string()))?
180 .is_some_and(|r| r.connection_id == ctx.connection_id);
181 if !active && !candidate {
182 return Ok(vec![control_error_frame(
183 &frame,
184 "not_delivery_target",
185 "connection is no longer the active or candidate delivery target",
186 )?]);
187 }
188 let body = frame.body.clone();
189 let connection = ctx.connection_id;
190 let mut delivered_view = None;
191 let result = match op {
192 "config.declare" => {
193 let declaration = serde_json::from_slice(&body).map_err(|_| {
194 GateError::new("invalid_control_body", "malformed config.declare request")
195 });
196 match declaration {
197 Ok(declaration) => {
198 config_work(runtime.clone(), move |owner| {
199 owner.declare(connection, &module, declaration, active)?;
200 Ok(serde_json::json!({"op":"config.declare"}))
201 })
202 .await
203 }
204 Err(error) => Err(error),
205 }
206 }
207 "config.get" => {
208 let request = serde_json::from_slice(&body).map_err(|_| {
209 GateError::new("invalid_control_body", "malformed config.get request")
210 });
211 match request {
212 Ok(request) => {
213 let module_id = module.clone();
214 match config_work(runtime.clone(), move |owner| {
215 owner.module_get(connection, &module_id, request)
216 })
217 .await
218 {
219 Ok(reply) => {
220 let encoded = serde_json::to_value(&reply).map_err(|_| {
221 GateError::new(
222 "config_unavailable",
223 "could not encode config view",
224 )
225 });
226 delivered_view = Some(reply);
227 encoded
228 }
229 Err(error) => Err(error),
230 }
231 }
232 Err(error) => Err(error),
233 }
234 }
235 "config.applied" => {
236 match serde_json::from_slice::<subc_protocol::config::ConfigAppliedRequest>(&body) {
237 Ok(request) => {
238 config_work(runtime.clone(), move |owner| {
239 owner.module_applied(connection, &module, request)?;
240 Ok(serde_json::json!({"op":"config.applied"}))
241 })
242 .await
243 }
244 Err(_) => Err(GateError::new(
245 "invalid_control_body",
246 "malformed config.applied request",
247 )),
248 }
249 }
250 _ => Err(GateError::new(
251 "invalid_control_body",
252 "unsupported module configuration operation",
253 )),
254 };
255 match result {
256 Ok(response) => {
257 let response =
258 control_response_body_frame(&frame, &response, "module config response")?;
259 if let Some(view) = delivered_view {
260 use crate::config_gate::runtime::delivery::CONFIG_LIVE_ACK_TIMEOUT;
261 let selected = view
262 .pending
263 .as_ref()
264 .and_then(|view| view.attempt.map(|attempt| (view.generation, attempt)));
265 let window = runtime
266 .on_blocking(move |owner| {
267 if active {
268 if let Some((generation, attempt)) = selected {
269 owner.delivery_write_started(
270 connection,
271 generation,
272 attempt,
273 tokio::time::Instant::now(),
274 )?;
275 }
276 }
277 owner.delivery_window(connection)
278 })
279 .await
280 .map_err(|error| {
281 RouterError::backend(0, frame.header.corr, error.to_string())
282 })?;
283 let write_deadline = window
284 .filter(|window| selected == Some((window.generation, window.attempt)))
285 .and_then(|window| window.deadline)
286 .map_or(
287 tokio::time::Instant::now() + CONFIG_LIVE_ACK_TIMEOUT,
288 |deadline| {
289 deadline.min(tokio::time::Instant::now() + CONFIG_LIVE_ACK_TIMEOUT)
290 },
291 );
292 drop(_gate);
293 let flushed =
294 tokio::time::timeout_at(write_deadline, ctx.egress.send_flushed(response))
295 .await;
296 let flushed_at = tokio::time::Instant::now();
297 let _gate = gate.lock().await;
298 let current_window = runtime
299 .on_blocking(move |owner| owner.delivery_window(connection))
300 .await
301 .ok()
302 .flatten();
303 if !self.config_delivery_target_current(
306 ®istration.manifest.module_id,
307 connection,
308 active,
309 frame.header.corr,
310 )? || selected.is_some_and(|selected| {
311 current_window
312 .is_none_or(|window| selected != (window.generation, window.attempt))
313 }) {
314 return Ok(vec![]);
315 }
316 match flushed {
317 Ok(Ok(())) => {}
318 failed => {
319 if active {
320 if let Some((generation, attempt)) = selected {
321 let module = registration.manifest.module_id.clone();
322 let _ = config_work(runtime.clone(), move |owner| {
323 owner.delivery_timeout(
324 connection, &module, generation, attempt,
325 )
326 })
327 .await;
328 }
329 }
330 return match failed {
331 Ok(Err(error)) => Err(error),
332 _ => Ok(vec![]),
333 };
334 }
335 }
336 let module = registration.manifest.module_id.clone();
337 let delivered = config_work(runtime.clone(), move |owner| {
338 owner.module_view_delivered(connection, &module, &view, flushed_at, active)
339 })
340 .await;
341 if let Err(error) = delivered {
342 if matches!(
343 error.code.as_str(),
344 "delivery_superseded" | "not_delivery_target"
345 ) {
346 return Ok(vec![]);
347 }
348 if error.code == "delivery_expired" {
349 if active {
350 if let Some((generation, attempt)) = selected {
351 let module = registration.manifest.module_id.clone();
352 let _ = config_work(runtime.clone(), move |owner| {
353 owner.delivery_timeout(
354 connection, &module, generation, attempt,
355 )
356 })
357 .await;
358 }
359 }
360 } else {
361 return Err(RouterError::backend(
362 0,
363 frame.header.corr,
364 error.to_string(),
365 ));
366 }
367 }
368 Ok(vec![])
369 } else {
370 Ok(vec![response])
371 }
372 }
373 Err(error) => {
374 if error.code == "anchor_pending" {
375 let _ = config_work(runtime.clone(), move |owner| {
376 owner.anchor_pending_served(connection)
377 })
378 .await;
379 }
380 Ok(vec![config_error_frame(&frame, error)?])
381 }
382 }
383 }
384 pub fn with_config_runtime(
385 mut self,
386 runtime: Arc<crate::config_gate::runtime::RuntimeOwner>,
387 ) -> Self {
388 self.supervisor.install_binding_retirement(&runtime);
389 let _ = runtime.set_activity(self.activity.clone());
390 runtime.install_module_route_authority(Arc::new(route_policy::ModuleRouteAuthority(
391 self.clone(),
392 Arc::downgrade(&runtime),
393 )));
394 runtime.install_mark_publisher(Arc::new(caller_attestation::ControlMarkPublisher(
395 self.clone(),
396 )));
397 self.config_runtime = Some(runtime);
398 self
399 }
400
401 pub(crate) fn with_explicit_config_store(
403 self,
404 runtime: Arc<crate::config_gate::runtime::RuntimeOwner>,
405 ) -> Self {
406 let mut handler = self.with_config_runtime(runtime);
407 let capability = subc_protocol::config::CONFIG_GATE_CAPABILITY;
408 if !handler
409 .subc_capabilities
410 .iter()
411 .any(|present| present == capability)
412 {
413 let mut capabilities = handler.subc_capabilities.to_vec();
414 capabilities.push(capability.to_owned());
415 handler.subc_capabilities = capabilities.into();
416 }
417 handler
418 }
419
420 fn config_desktop_identity(
421 &self,
422 connection: ConnectionId,
423 ) -> std::result::Result<bool, GateError> {
424 if !self.config_owner_connection(connection) {
425 return Ok(false);
426 }
427 #[cfg(feature = "dev-desktop-approval")]
428 {
429 Ok(self
432 .local_connections
433 .lock()
434 .unwrap_or_else(|p| p.into_inner())
435 .contains(&connection))
436 }
437 #[cfg(not(feature = "dev-desktop-approval"))]
438 {
439 Ok(self
440 .config_desktop_stamps
441 .lock()
442 .unwrap_or_else(|p| p.into_inner())
443 .get(&connection)
444 .is_some_and(|stamp| stamp.revalidate_with_launches(&self.launch_table)))
445 }
446 }
447
448 pub(crate) fn config_desktop_review_response(
449 &self,
450 connection: ConnectionId,
451 response: &Frame,
452 ) -> Option<subc_control::config::ConfigPlanView> {
453 if self.config_runtime.is_none() || response.header.ty != FrameType::Response {
454 return None;
455 }
456 let probe: ControlOpProbe = serde_json::from_slice(&response.body).ok()?;
457 if !matches!(
458 probe.op.as_str(),
459 "config.plan" | "config.stamp" | "config.unstamp" | "config.rollback"
460 ) || !matches!(self.config_desktop_identity(connection), Ok(true))
461 {
462 return None;
463 }
464 match serde_json::from_slice::<ConfigControlResponse>(&response.body).ok()? {
465 ConfigControlResponse::Plan { view }
466 | ConfigControlResponse::Stamp { view }
467 | ConfigControlResponse::Unstamp { view }
468 | ConfigControlResponse::Rollback { view } => Some(view),
469 _ => None,
470 }
471 }
472
473 pub(crate) async fn config_desktop_review_delivered(
474 &self,
475 connection: ConnectionId,
476 view: subc_control::config::ConfigPlanView,
477 ) {
478 if !matches!(self.config_desktop_identity(connection), Ok(true)) {
479 return;
480 }
481 let Some(runtime) = self.config_runtime.clone() else {
482 return;
483 };
484 let peers = self.captured_peers.clone();
485 let _ = config_work(runtime, move |owner| {
486 owner.desktop_view_delivered_when(connection, &view, || {
487 peers
488 .lock()
489 .unwrap_or_else(|p| p.into_inner())
490 .contains_key(&connection)
491 })
492 })
493 .await;
494 }
495
496 pub(crate) async fn deliver_config_desktop_review(
497 &self,
498 ctx: &RouteCtx,
499 response: Frame,
500 view: subc_control::config::ConfigPlanView,
501 ) -> Result<(), RouterError> {
502 ctx.egress.send_flushed(response).await?;
503 self.config_desktop_review_delivered(ctx.connection_id, view)
504 .await;
505 Ok(())
506 }
507
508 pub fn with_config_review_admission(
509 mut self,
510 admission: Arc<dyn crate::config_gate::ReviewAdmission>,
511 ) -> Self {
512 self.config_review_admission = admission;
513 self.config_review_admission_is_default = false;
514 self
515 }
516
517 pub(super) fn review_admission(&self) -> Arc<dyn crate::config_gate::ReviewAdmission> {
518 if self.config_runtime.is_some() && self.config_review_admission_is_default {
519 Arc::new(admission::SupervisedReviewAdmission(self.clone()))
520 } else {
521 self.config_review_admission.clone()
522 }
523 }
524
525 pub(super) async fn handle_config_gate_request(
526 &self,
527 ctx: &RouteCtx,
528 frame: Frame,
529 ) -> Result<Vec<Frame>, RouterError> {
530 let request = match serde_json::from_slice::<ConfigControlRequest>(&frame.body) {
531 Ok(request) => request,
532 Err(error) => {
533 return Ok(vec![control_error_frame(
534 &frame,
535 "invalid_control_body",
536 format!("malformed config control body: {error}"),
537 )?])
538 }
539 };
540 debug_assert!(privileged_operation(&request).is_none());
541 let Some(runtime) = self.config_runtime.clone() else {
542 return Ok(vec![control_error_frame(
543 &frame,
544 "config_gate_inactive",
545 "no config store configured",
546 )?]);
547 };
548 if !self.config_owner_connection(ctx.connection_id) {
549 return Ok(vec![control_error_frame(
550 &frame,
551 "owner_required",
552 "configuration control requires a kernel-observed owner-user connection",
553 )?]);
554 }
555 let result = self
556 .execute_config_request(ctx, &frame, runtime, request)
557 .await;
558 match result {
559 Ok(response) => Ok(vec![control_response_body_frame(
560 &frame,
561 &response,
562 "ConfigControlResponse",
563 )?]),
564 Err(error) => Ok(vec![config_error_frame(&frame, error)?]),
565 }
566 }
567
568 fn config_owner_connection(&self, connection: ConnectionId) -> bool {
569 let peers = self
570 .observed_peers
571 .lock()
572 .unwrap_or_else(|p| p.into_inner());
573 let Some(peer) = peers.get(&connection) else {
574 return false;
575 };
576 #[cfg(unix)]
577 {
578 peer.uid == Some(subc_os::effective_uid())
579 }
580 #[cfg(windows)]
581 {
582 subc_os::named_pipe::current_user_sid_string()
583 .ok()
584 .as_ref()
585 .is_some_and(|sid| peer.sid.as_ref() == Some(sid))
586 }
587 #[cfg(not(any(unix, windows)))]
588 {
589 let _ = peer;
590 false
591 }
592 }
593
594 async fn execute_config_request(
595 &self,
596 ctx: &RouteCtx,
597 frame: &Frame,
598 runtime: Arc<crate::config_gate::runtime::RuntimeOwner>,
599 request: ConfigControlRequest,
600 ) -> std::result::Result<ConfigControlResponse, GateError> {
601 match request {
602 ConfigControlRequest::PlaceProgram {
603 module_id,
604 path,
605 sha256,
606 manifest,
607 } => {
608 let gate = runtime.module_gate(&module_id)?;
609 let _guard = gate.lock().await;
610 let generation = config_work(runtime, move |owner| {
611 owner.place_program_with_manifest(&module_id, &path, &sha256, manifest.as_ref())
612 })
613 .await?;
614 Ok(ConfigControlResponse::ProgramPlaced { generation })
615 }
616 ConfigControlRequest::Status {} => {
617 let snapshot = runtime.polled_snapshot()?;
618 let captured = snapshot.clone();
619 let mut status = runtime
620 .on_blocking(move |owner| owner.polled_status_from(&captured))
621 .await?;
622 let phone = self
623 .config_phone_surface_checked(false, Some(&snapshot))
624 .await;
625 let facts = self.config_approval_facts_with_phone(ctx, phone).await;
626 status
627 .missing_approval_surfaces
628 .extend(crate::config_gate::missing_surfaces(
629 &facts,
630 matches!(status.state.as_str(), "store_missing" | "store_unverified"),
631 ));
632 if let Err(error) = self.config_desktop_identity(ctx.connection_id) {
633 status.missing_approval_surfaces.push(error.code);
634 }
635 self.report_daemon_configuration(&snapshot.approved_daemon, &mut status)
636 .await?;
637 Ok(ConfigControlResponse::Status { status })
638 }
639 ConfigControlRequest::History {} => {
640 let (generations, pruned) = config_work(runtime, |owner| owner.history()).await?;
641 Ok(ConfigControlResponse::History {
642 generations,
643 pruned,
644 })
645 }
646 ConfigControlRequest::Apply { digest } => {
647 let connection = ctx.connection_id;
648 let corr = frame.header.corr;
649 #[cfg(all(test, unix))]
650 runtime.pause_approval_claim_for_test().await;
651 let request_guard = runtime.claim_approval_request(connection, corr)?;
652 if self.rescan.is_none() {
653 return Err(GateError::new(
654 "supervisor_reconcile_unavailable",
655 "configuration commit requires the supervisor owner",
656 ));
657 }
658 let facts = self.config_approval_facts(ctx).await;
659 let cancellation = request_guard.request.clone();
660 let (challenge, mut attempt_guard) = config_work(runtime.clone(), move |owner| {
661 let challenge =
662 owner.begin_approval_for_request(&digest, &facts, Some(&cancellation))?;
663 let guard = phone::ApprovalAttemptGuard::new(&owner, challenge.attempt());
666 owner.track_reserved_approval_request(
667 challenge.attempt(),
668 connection,
669 corr,
670 &cancellation,
671 )?;
672 Ok((challenge, guard))
673 })
674 .await
675 .map_err(|error| {
676 if error.code == "approval_surface_unavailable" {
677 self.config_desktop_identity(ctx.connection_id)
678 .err()
679 .unwrap_or(error)
680 } else {
681 error
682 }
683 })?;
684 request_guard.request.ensure_live()?;
685 let reply = match &challenge {
686 ApprovalChallenge::Desktop { .. } | ApprovalChallenge::OsPrompt { .. } => {
687 ApprovalReply::Presence(
688 self.confirm_config_gate_presence(ctx, frame, &challenge)
689 .await,
690 )
691 }
692 ApprovalChallenge::Phone {
693 attempt,
694 connection,
695 deadline,
696 request,
697 } => {
698 self.config_phone_rpc(
699 &runtime,
700 *attempt,
701 ConnectionId::new(*connection),
702 *deadline,
703 request,
704 )
705 .await?
706 }
707 };
708 let attempt = challenge.attempt();
709 let window = matches!(challenge, ApprovalChallenge::Phone { .. }).then(|| {
710 Arc::new(crate::config_gate::runtime::ApprovalCommitWindow::new(
711 Instant::now() + CONFIG_APPROVAL_COMMIT_TIMEOUT,
712 ))
713 });
714 attempt_guard.commit_window = window.clone();
715 let checked_phone = self.config_phone_surface().await;
716 let locks = async {
717 let operation = self.supervisor.operation_lock().lock_owned().await;
718 let module_gates = runtime.approval_commit_gates(attempt).await?;
719 let current_phone = self.config_phone_surface_snapshot().await;
720 let phone = checked_phone.filter(|phone| Some(phone) == current_phone.as_ref());
721 let facts = self.config_approval_facts_with_phone(ctx, phone).await;
722 Ok::<_, GateError>((operation, module_gates, facts))
723 };
724 let (operation, module_gates, facts) = if let Some(window) = &window {
725 timeout_at(window.deadline, locks)
726 .await
727 .map_err(|_| GateError::commit_timeout())??
728 } else {
729 locks.await?
730 };
731 let now = now_ms();
732 let publish_window = window.clone();
733 let publication_request = request_guard.request.clone();
734 let exit_runtime = runtime.clone();
735 let work = config_work(runtime, move |owner| {
736 let _owned_gates = (operation, module_gates);
737 owner.finish_approval_with_commit_window(
738 attempt,
739 &facts,
740 reply,
741 now,
742 publish_window,
743 publication_request,
744 )
745 });
746 tokio::pin!(work);
747 let generation = if let Some(window) = window {
748 tokio::select! {
749 result = &mut work => result?,
750 _ = tokio::time::sleep_until(window.deadline) => {
751 if window.expire() { return Err(GateError::commit_timeout()); }
752 work.await?
753 }
754 }
755 } else {
756 work.await?
757 };
758 let approval_runtime = exit_runtime.clone();
759 if let Some(approval) = config_work(approval_runtime, move |owner| {
760 owner.development_approval(generation)
761 })
762 .await?
763 {
764 self.publish_development_approval(&approval);
765 return Ok(ConfigControlResponse::Applied {
766 generation,
767 restart_required: false,
768 });
769 }
770 #[cfg(test)]
771 self.pause_before_apply_reconcile_for_test().await;
772 self.reconcile_authority_exit(exit_runtime.clone(), generation)
773 .await?;
774 let restart_required = self
775 .daemon_restart_required(&exit_runtime, generation)
776 .await?;
777 Ok(ConfigControlResponse::Applied {
778 generation,
779 restart_required,
780 })
781 }
782 request => {
783 let kind = match request {
784 ConfigControlRequest::Plan {} => PlanKind::Change,
785 ConfigControlRequest::Stamp {} => PlanKind::Stamp,
786 ConfigControlRequest::Unstamp {} => PlanKind::Unstamp,
787 ConfigControlRequest::Rollback { generation } => PlanKind::Rollback(generation),
788 _ => {
789 return Err(GateError::new(
790 "unsupported_control_frame",
791 "unknown configuration operation",
792 ))
793 }
794 };
795 let mut prepared =
796 config_work(runtime.clone(), move |owner| owner.prepare(kind)).await?;
797 let mut fields = Vec::new();
798 let mut unavailable_rereviews = Vec::new();
799 for (module, captured) in &prepared.candidate.modules {
800 if !prepared.review_modules.contains(module) {
801 continue;
802 }
803 let base = prepared.bases.get(module);
804 let reply: std::result::Result<Vec<u8>, GateError> = async {
805 let registration = self
806 .registry
807 .get_module(module)
808 .map_err(|_| {
809 GateError::new("config_unavailable", "registry is unavailable")
810 })?
811 .ok_or_else(|| {
812 GateError::new(
813 "module_review_unavailable",
814 format!("{module}: no active reviewer"),
815 )
816 })?;
817 let admission = self.review_admission();
818 let reviewer = registration.clone();
819 config_work(runtime.clone(), move |_| admission.check(&reviewer)).await?;
820 if !registration
821 .control_ops
822 .iter()
823 .any(|op| op == "config.review")
824 {
825 return Err(GateError::new(
826 "module_review_unavailable",
827 format!("{module}: config.review is not opted in"),
828 ));
829 }
830 let request = subc_protocol::config::ConfigReviewRequest::new(
831 base.map_or(0, |b| b.generation),
832 captured.view.layers.clone(),
833 base.cloned(),
834 );
835 let bytes = serde_json::to_vec(&request).map_err(|_| {
836 GateError::new(
837 "config_unavailable",
838 "could not encode immutable review",
839 )
840 })?;
841 self.config_rpc(
842 &runtime,
843 module,
844 registration.connection_id,
845 "config.review",
846 bytes,
847 )
848 .await
849 }
850 .await;
851 let reply = match reply {
852 Ok(reply) => reply,
853 Err(_) if prepared.rereview_modules.contains(module) => {
856 unavailable_rereviews.push(module.clone());
857 continue;
858 }
859 Err(error) => return Err(error),
860 };
861 let reply = serde_json::from_slice(&reply).map_err(|_| {
862 GateError::new(
863 "module_review_invalid",
864 format!("{module}: malformed config.review reply"),
865 )
866 })?;
867 fields.extend(crate::config_gate::review::checked_fields(
868 module,
869 &captured.schema,
870 base,
871 prepared.base_schemas.get(module),
872 &captured.view,
873 reply,
874 )?);
875 }
876 for module in unavailable_rereviews {
877 prepared.review_modules.remove(&module);
878 prepared.rereview_modules.remove(&module);
879 }
880 let view = config_work(runtime, move |owner| {
881 owner.finish_plan(prepared, move |old, new| {
882 let mut changeset = crate::config_gate::runtime::daemon_review(old, new)?;
883 changeset.fields = fields;
884 let mut effects: std::collections::BTreeMap<String,std::collections::BTreeMap<String,Vec<String>>> = Default::default();
885 for field in &changeset.fields {
886 let kind = serde_json::to_value(field.apply).map_err(|_| GateError::new("schema_invalid", "could not encode apply kind"))?.as_str().ok_or_else(|| GateError::new("schema_invalid","apply kind is not a string"))?.to_owned();
887 effects.entry(field.module_id.clone()).or_default().entry(kind).or_default().push(field.path.clone());
888 }
889 if changeset.fields.iter().any(|field| field.apply != subc_config::ApplyKind::Live) {
890 changeset.apply_plan = serde_json::json!({"daemon_effects":changeset.apply_plan,"modules":effects});
891 }
892 Ok(changeset)
893 })
894 })
895 .await?;
896 Ok(match kind {
897 PlanKind::Change => ConfigControlResponse::Plan { view },
898 PlanKind::Stamp => ConfigControlResponse::Stamp { view },
899 PlanKind::Unstamp => ConfigControlResponse::Unstamp { view },
900 PlanKind::Rollback(_) => ConfigControlResponse::Rollback { view },
901 })
902 }
903 }
904 }
905
906 async fn config_approval_facts(&self, ctx: &RouteCtx) -> ApprovalFacts {
907 let phone = self.config_phone_surface().await;
908 self.config_approval_facts_with_phone(ctx, phone).await
909 }
910
911 async fn config_approval_facts_with_phone(
912 &self,
913 ctx: &RouteCtx,
914 phone: Option<crate::config_gate::PhoneSurface>,
915 ) -> ApprovalFacts {
916 let os_policy = crate::config_gate::os_prompt_policy_present();
917 #[cfg(any(test, feature = "test-support"))]
918 let os_policy = os_policy
919 || self
920 .config_runtime
921 .as_ref()
922 .is_some_and(|owner| owner.os_prompt_policy_for_tests());
923 let desktop = self
924 .config_desktop_identity(ctx.connection_id)
925 .unwrap_or(false);
926 ApprovalFacts {
927 connection: ctx.connection_id.get(),
928 owner_uid: self.config_owner_connection(ctx.connection_id),
929 desktop_app: desktop,
930 attested_operator_app: desktop && !cfg!(feature = "dev-desktop-approval"),
931 os_prompt_available: config_os_prompt_available(
932 self.forwarding.operator_confirms().config_gate_ready(),
933 os_policy,
934 ),
935 phone,
936 caller: self.resolve_caller(ctx.connection_id).await,
937 }
938 }
939
940 async fn config_phone_surface(&self) -> Option<crate::config_gate::PhoneSurface> {
943 self.config_phone_surface_checked(true, None).await
944 }
945
946 async fn config_phone_surface_snapshot(&self) -> Option<crate::config_gate::PhoneSurface> {
947 self.config_phone_surface_checked(false, None).await
948 }
949
950 async fn config_phone_surface_checked(
951 &self,
952 content: bool,
953 publication: Option<&crate::config_gate::runtime::Published>,
954 ) -> Option<crate::config_gate::PhoneSurface> {
955 if self.config_runtime.as_ref().is_some_and(|owner| {
956 publication.map_or_else(|| owner.is_recovering(), |view| view.is_recovering())
957 }) {
958 return None;
959 }
960 if !self.operator_app_policy.phone_enabled {
961 return None;
962 }
963 let runtime = self.config_runtime.as_ref()?;
964 let (_, registrations) = self.registry.list_modules_with_nonce_verification().ok()?;
965 let (registration, verified) = registrations
966 .into_iter()
967 .find(|(registration, _)| registration.manifest.module_id == "callosum")?;
968 if !verified
969 || !registration.ready
970 || !registration
971 .control_ops
972 .iter()
973 .any(|op| op == subc_protocol::consent::CONSENT_V1)
974 {
975 return None;
976 }
977 let _spawn = self
978 .supervisor
979 .registration_spawn(registration.connection_id)?;
980 if !self
981 .forwarding
982 .active_module_endpoint("callosum")
983 .ok()
984 .flatten()
985 .is_some_and(|endpoint| endpoint.connection_id == registration.connection_id)
986 {
987 return None;
988 }
989 let module = self.supervisor.get("callosum")?;
993 let status = module.status().ok()?;
994 let (spec, _) = module.configuration().ok()?;
995 if !self.supervisor.registration_snapshot_is_current_live(
996 &self.registry,
997 "callosum",
998 registration.connection_id,
999 None,
1000 ) || !spec.reserved
1001 || !status.enabled
1002 || !status.process_alive
1003 || !status.registration_active
1004 {
1005 return None;
1006 }
1007 let connection = registration.connection_id;
1008 let approved = if content {
1009 runtime
1010 .on_blocking(move |owner| owner.approved_phone_entry(connection))
1011 .await
1012 .ok()??
1013 } else {
1014 if let Some(snapshot) = publication {
1015 runtime.polled_phone_entry_from(snapshot, connection)?
1016 } else {
1017 runtime.polled_phone_entry(connection)?
1018 }
1019 };
1020 if !approved.enabled || approved.module_spec() != spec {
1021 return None;
1022 }
1023 if content {
1024 let supervisor = self.supervisor.clone();
1025 let registry = self.registry.clone();
1026 if !runtime
1027 .on_blocking(move |_| {
1028 Ok(supervisor
1029 .registration_is_current_live(®istry, "callosum", connection, None))
1030 })
1031 .await
1032 .ok()?
1033 {
1034 return None;
1035 }
1036 }
1037 if !self.supervisor.registration_snapshot_is_current_live(
1038 &self.registry,
1039 "callosum",
1040 registration.connection_id,
1041 None,
1042 ) {
1043 return None;
1044 }
1045 Some(crate::config_gate::PhoneSurface {
1046 module_id: "callosum".into(),
1047 connection: connection.get(),
1048 spawn_generation: status.spawn_generation,
1049 enabled_by_policy: true,
1050 opted_in: true,
1051 approved_declaration: true,
1052 reserved: true,
1053 channel_registered: true,
1054 program_admitted: true,
1055 active_registration: true,
1056 })
1057 }
1058
1059 async fn config_rpc(
1060 &self,
1061 runtime: &Arc<crate::config_gate::runtime::RuntimeOwner>,
1062 module: &str,
1063 expected_connection: ConnectionId,
1064 op: &str,
1065 bytes: Vec<u8>,
1066 ) -> std::result::Result<Vec<u8>, GateError> {
1067 let gate = runtime.module_gate(module)?;
1068 let pending = {
1069 let _gate = gate.lock().await;
1070 let registration = self
1071 .registry
1072 .get_module(module)
1073 .map_err(|_| GateError::new("config_unavailable", "registry unavailable"))?
1074 .ok_or_else(|| {
1075 GateError::new(
1076 "module_review_unavailable",
1077 format!("{module}: no active target"),
1078 )
1079 })?;
1080 let pending = self
1081 .forwarding
1082 .begin_module_control_rpc_for(module, op, Instant::now() + CONFIG_REVIEW_TIMEOUT)
1083 .map_err(|_| {
1084 GateError::new(
1085 "module_review_unavailable",
1086 format!("{module}: target unavailable"),
1087 )
1088 })?;
1089 if pending.endpoint.connection_id != registration.connection_id
1090 || registration.connection_id != expected_connection
1091 {
1092 let _ = self
1093 .forwarding
1094 .cancel_module_control_rpc(pending.endpoint, pending.corr);
1095 return Err(GateError::new(
1096 "not_delivery_target",
1097 "registry and forwarding targets differ",
1098 ));
1099 }
1100 pending
1101 };
1102 let PendingModuleControlRpc {
1103 endpoint,
1104 module_sink,
1105 negotiated_ver,
1106 corr,
1107 receiver,
1108 } = pending;
1109 let mut guard = ModuleControlRpcGuard::new(self.forwarding.clone(), endpoint, corr);
1110 let deadline = Instant::now() + CONFIG_REVIEW_TIMEOUT;
1111 let frame = Frame::build_with_version(
1112 negotiated_ver,
1113 FrameType::Request,
1114 control_flags(),
1115 0,
1116 0,
1117 corr,
1118 bytes,
1119 )
1120 .map_err(|_| GateError::new("config_unavailable", "could not encode config request"))?;
1121 timeout_at(deadline, module_sink.send(frame))
1122 .await
1123 .map_err(|_| {
1124 GateError::new(
1125 "config_review_timeout",
1126 format!("{module}: config.review exceeded its 30-second deadline; plan remains unapproved"),
1127 )
1128 })?
1129 .map_err(|_| {
1130 GateError::new(
1131 "module_review_unavailable",
1132 format!("{module}: target disconnected"),
1133 )
1134 })?;
1135 let outcome = timeout_at(deadline, receiver)
1136 .await
1137 .map_err(|_| {
1138 GateError::new(
1139 "config_review_timeout",
1140 format!("{module}: config.review exceeded its 30-second deadline; plan remains unapproved"),
1141 )
1142 })?
1143 .map_err(|_| {
1144 GateError::new(
1145 "module_review_unavailable",
1146 format!("{module}: target disconnected"),
1147 )
1148 })?;
1149 guard.disarm();
1150 match outcome {
1151 ModuleControlRpcOutcome::RawResponse(bytes) => Ok(bytes),
1152 ModuleControlRpcOutcome::DeadlineElapsed => Err(GateError::new("config_review_timeout",format!("{module}: config.review exceeded its 30-second deadline; plan remains unapproved"))),
1153 _ => Err(GateError::new(
1154 "module_review_unavailable",
1155 format!("{module}: config request was not answered"),
1156 )),
1157 }
1158 }
1159
1160 pub async fn confirm_config_gate_presence(
1163 &self,
1164 ctx: &RouteCtx,
1165 frame: &Frame,
1166 challenge: &ApprovalChallenge,
1167 ) -> PresenceDecision {
1168 let Some(text) = challenge.prompt() else {
1169 return PresenceDecision::Unavailable;
1170 };
1171 let caller = self.resolve_caller(ctx.connection_id).await;
1172 let key = crate::operator_confirm::DeclineKey::for_caller(&caller, ctx.connection_id);
1173 let outcome = self
1176 .forwarding
1177 .operator_confirms()
1178 .approve_config_gate(ctx, frame, text.to_owned(), caller.description(), key)
1179 .await;
1180 PresenceDecision::from_operator_outcome(&outcome)
1181 }
1182}
1183
1184fn config_os_prompt_available(provider_ready: bool, policy_present: bool) -> bool {
1185 provider_ready && policy_present
1186}
1187
1188async fn config_work<T: Send + 'static>(
1189 runtime: Arc<crate::config_gate::runtime::RuntimeOwner>,
1190 work: impl FnOnce(Arc<crate::config_gate::runtime::RuntimeOwner>) -> std::result::Result<T, GateError>
1191 + Send
1192 + 'static,
1193) -> std::result::Result<T, GateError> {
1194 runtime
1195 .on_blocking(move |owner| {
1196 let result = work(owner.clone());
1197 owner.notify_delivery_changed();
1198 result
1199 })
1200 .await
1201}
1202
1203pub(super) fn config_error_frame(frame: &Frame, error: GateError) -> Result<Frame, RouterError> {
1204 control_error_body_frame(
1205 frame,
1206 ErrorBody {
1207 code: error.code,
1208 message: error.detail,
1209 detail: None,
1210 },
1211 )
1212}
1213
1214fn now_ms() -> u64 {
1215 std::time::SystemTime::now()
1216 .duration_since(std::time::UNIX_EPOCH)
1217 .unwrap_or_default()
1218 .as_millis()
1219 .min(u128::from(u64::MAX)) as u64
1220}
1221
1222#[cfg(test)]
1223mod tests;
1224
1225#[cfg(test)]
1226mod desktop_tests;