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_request(&self, request: &Frame) -> bool {
449 self.config_runtime.is_some()
450 && request.header.ty == FrameType::Request
451 && serde_json::from_slice::<ControlOpProbe>(&request.body).is_ok_and(|probe| {
452 matches!(
453 probe.op.as_str(),
454 "config.plan" | "config.stamp" | "config.unstamp" | "config.rollback"
455 )
456 })
457 }
458
459 pub(crate) fn config_desktop_review_response(
460 &self,
461 connection: ConnectionId,
462 response: &Frame,
463 ) -> Option<subc_control::config::ConfigPlanView> {
464 if self.config_runtime.is_none() || response.header.ty != FrameType::Response {
465 return None;
466 }
467 let probe: ControlOpProbe = serde_json::from_slice(&response.body).ok()?;
468 if !matches!(
469 probe.op.as_str(),
470 "config.plan" | "config.stamp" | "config.unstamp" | "config.rollback"
471 ) || !matches!(self.config_desktop_identity(connection), Ok(true))
472 {
473 return None;
474 }
475 match serde_json::from_slice::<ConfigControlResponse>(&response.body).ok()? {
476 ConfigControlResponse::Plan { view }
477 | ConfigControlResponse::Stamp { view }
478 | ConfigControlResponse::Unstamp { view }
479 | ConfigControlResponse::Rollback { view } => Some(view),
480 _ => None,
481 }
482 }
483
484 pub(crate) async fn config_desktop_review_delivered(
485 &self,
486 connection: ConnectionId,
487 view: subc_control::config::ConfigPlanView,
488 ) {
489 if !matches!(self.config_desktop_identity(connection), Ok(true)) {
490 return;
491 }
492 let Some(runtime) = self.config_runtime.clone() else {
493 return;
494 };
495 let peers = self.captured_peers.clone();
496 let _ = config_work(runtime, move |owner| {
497 owner.desktop_view_delivered_when(connection, &view, || {
498 peers
499 .lock()
500 .unwrap_or_else(|p| p.into_inner())
501 .contains_key(&connection)
502 })
503 })
504 .await;
505 }
506
507 pub(crate) async fn deliver_config_desktop_review(
508 &self,
509 ctx: &RouteCtx,
510 response: Frame,
511 view: subc_control::config::ConfigPlanView,
512 ) -> Result<(), RouterError> {
513 ctx.egress.send_flushed(response).await?;
514 self.config_desktop_review_delivered(ctx.connection_id, view)
515 .await;
516 Ok(())
517 }
518
519 pub fn with_config_review_admission(
520 mut self,
521 admission: Arc<dyn crate::config_gate::ReviewAdmission>,
522 ) -> Self {
523 self.config_review_admission = admission;
524 self.config_review_admission_is_default = false;
525 self
526 }
527
528 pub(super) fn review_admission(&self) -> Arc<dyn crate::config_gate::ReviewAdmission> {
529 if self.config_runtime.is_some() && self.config_review_admission_is_default {
530 Arc::new(admission::SupervisedReviewAdmission(self.clone()))
531 } else {
532 self.config_review_admission.clone()
533 }
534 }
535
536 pub(super) async fn handle_config_gate_request(
537 &self,
538 ctx: &RouteCtx,
539 frame: Frame,
540 ) -> Result<Vec<Frame>, RouterError> {
541 let request = match serde_json::from_slice::<ConfigControlRequest>(&frame.body) {
542 Ok(request) => request,
543 Err(error) => {
544 return Ok(vec![control_error_frame(
545 &frame,
546 "invalid_control_body",
547 format!("malformed config control body: {error}"),
548 )?])
549 }
550 };
551 debug_assert!(privileged_operation(&request).is_none());
552 let Some(runtime) = self.config_runtime.clone() else {
553 return Ok(vec![control_error_frame(
554 &frame,
555 "config_gate_inactive",
556 "no config store configured",
557 )?]);
558 };
559 if !self.config_owner_connection(ctx.connection_id) {
560 return Ok(vec![control_error_frame(
561 &frame,
562 "owner_required",
563 "configuration control requires a kernel-observed owner-user connection",
564 )?]);
565 }
566 let result = self
567 .execute_config_request(ctx, &frame, runtime, request)
568 .await;
569 match result {
570 Ok(response) => Ok(vec![control_response_body_frame(
571 &frame,
572 &response,
573 "ConfigControlResponse",
574 )?]),
575 Err(error) => Ok(vec![config_error_frame(&frame, error)?]),
576 }
577 }
578
579 fn config_owner_connection(&self, connection: ConnectionId) -> bool {
580 let peers = self
581 .observed_peers
582 .lock()
583 .unwrap_or_else(|p| p.into_inner());
584 let Some(peer) = peers.get(&connection) else {
585 return false;
586 };
587 #[cfg(unix)]
588 {
589 peer.uid == Some(subc_os::effective_uid())
590 }
591 #[cfg(windows)]
592 {
593 subc_os::named_pipe::current_user_sid_string()
594 .ok()
595 .as_ref()
596 .is_some_and(|sid| peer.sid.as_ref() == Some(sid))
597 }
598 #[cfg(not(any(unix, windows)))]
599 {
600 let _ = peer;
601 false
602 }
603 }
604
605 async fn execute_config_request(
606 &self,
607 ctx: &RouteCtx,
608 frame: &Frame,
609 runtime: Arc<crate::config_gate::runtime::RuntimeOwner>,
610 request: ConfigControlRequest,
611 ) -> std::result::Result<ConfigControlResponse, GateError> {
612 match request {
613 ConfigControlRequest::PlaceProgram {
614 module_id,
615 path,
616 sha256,
617 manifest,
618 } => {
619 let gate = runtime.module_gate(&module_id)?;
620 let _guard = gate.lock().await;
621 let generation = config_work(runtime, move |owner| {
622 owner.place_program_with_manifest(&module_id, &path, &sha256, manifest.as_ref())
623 })
624 .await?;
625 Ok(ConfigControlResponse::ProgramPlaced { generation })
626 }
627 ConfigControlRequest::Status {} => {
628 let snapshot = runtime.polled_snapshot()?;
629 let captured = snapshot.clone();
630 let mut status = runtime
631 .on_blocking(move |owner| owner.polled_status_from(&captured))
632 .await?;
633 let phone = self
634 .config_phone_surface_checked(false, Some(&snapshot))
635 .await;
636 let facts = self.config_approval_facts_with_phone(ctx, phone).await;
637 status
638 .missing_approval_surfaces
639 .extend(crate::config_gate::missing_surfaces(
640 &facts,
641 matches!(status.state.as_str(), "store_missing" | "store_unverified"),
642 ));
643 if let Err(error) = self.config_desktop_identity(ctx.connection_id) {
644 status.missing_approval_surfaces.push(error.code);
645 }
646 self.report_daemon_configuration(&snapshot.approved_daemon, &mut status)
647 .await?;
648 Ok(ConfigControlResponse::Status { status })
649 }
650 ConfigControlRequest::History {} => {
651 let (generations, pruned) = config_work(runtime, |owner| owner.history()).await?;
652 Ok(ConfigControlResponse::History {
653 generations,
654 pruned,
655 })
656 }
657 ConfigControlRequest::Apply { digest } => {
658 let connection = ctx.connection_id;
659 let corr = frame.header.corr;
660 #[cfg(all(test, unix))]
661 runtime.pause_approval_claim_for_test().await;
662 let request_guard = runtime.claim_approval_request(connection, corr)?;
663 if self.rescan.is_none() {
664 return Err(GateError::new(
665 "supervisor_reconcile_unavailable",
666 "configuration commit requires the supervisor owner",
667 ));
668 }
669 let facts = self.config_approval_facts(ctx).await;
670 let cancellation = request_guard.request.clone();
671 let (challenge, mut attempt_guard) = config_work(runtime.clone(), move |owner| {
672 let challenge =
673 owner.begin_approval_for_request(&digest, &facts, Some(&cancellation))?;
674 let guard = phone::ApprovalAttemptGuard::new(&owner, challenge.attempt());
677 owner.track_reserved_approval_request(
678 challenge.attempt(),
679 connection,
680 corr,
681 &cancellation,
682 )?;
683 Ok((challenge, guard))
684 })
685 .await
686 .map_err(|error| {
687 if error.code == "approval_surface_unavailable" {
688 self.config_desktop_identity(ctx.connection_id)
689 .err()
690 .unwrap_or(error)
691 } else {
692 error
693 }
694 })?;
695 request_guard.request.ensure_live()?;
696 let reply = match &challenge {
697 ApprovalChallenge::Desktop { .. } | ApprovalChallenge::OsPrompt { .. } => {
698 ApprovalReply::Presence(
699 self.confirm_config_gate_presence(ctx, frame, &challenge)
700 .await,
701 )
702 }
703 ApprovalChallenge::Phone {
704 attempt,
705 connection,
706 deadline,
707 request,
708 } => {
709 self.config_phone_rpc(
710 &runtime,
711 *attempt,
712 ConnectionId::new(*connection),
713 *deadline,
714 request,
715 )
716 .await?
717 }
718 };
719 let attempt = challenge.attempt();
720 let window = matches!(challenge, ApprovalChallenge::Phone { .. }).then(|| {
721 Arc::new(crate::config_gate::runtime::ApprovalCommitWindow::new(
722 Instant::now() + CONFIG_APPROVAL_COMMIT_TIMEOUT,
723 ))
724 });
725 attempt_guard.commit_window = window.clone();
726 let checked_phone = self.config_phone_surface().await;
727 let locks = async {
728 let operation = self.supervisor.operation_lock().lock_owned().await;
729 let module_gates = runtime.approval_commit_gates(attempt).await?;
730 let current_phone = self.config_phone_surface_snapshot().await;
731 let phone = checked_phone.filter(|phone| Some(phone) == current_phone.as_ref());
732 let facts = self.config_approval_facts_with_phone(ctx, phone).await;
733 Ok::<_, GateError>((operation, module_gates, facts))
734 };
735 let (operation, module_gates, facts) = if let Some(window) = &window {
736 timeout_at(window.deadline, locks)
737 .await
738 .map_err(|_| GateError::commit_timeout())??
739 } else {
740 locks.await?
741 };
742 let now = now_ms();
743 let publish_window = window.clone();
744 let publication_request = request_guard.request.clone();
745 let exit_runtime = runtime.clone();
746 let work = config_work(runtime, move |owner| {
747 let _owned_gates = (operation, module_gates);
748 owner.finish_approval_with_commit_window(
749 attempt,
750 &facts,
751 reply,
752 now,
753 publish_window,
754 publication_request,
755 )
756 });
757 tokio::pin!(work);
758 let generation = if let Some(window) = window {
759 tokio::select! {
760 result = &mut work => result?,
761 _ = tokio::time::sleep_until(window.deadline) => {
762 if window.expire() { return Err(GateError::commit_timeout()); }
763 work.await?
764 }
765 }
766 } else {
767 work.await?
768 };
769 let approval_runtime = exit_runtime.clone();
770 if let Some(approval) = config_work(approval_runtime, move |owner| {
771 owner.development_approval(generation)
772 })
773 .await?
774 {
775 self.publish_development_approval(&approval);
776 return Ok(ConfigControlResponse::Applied {
777 generation,
778 restart_required: false,
779 });
780 }
781 #[cfg(test)]
782 self.pause_before_apply_reconcile_for_test().await;
783 self.reconcile_authority_exit(exit_runtime.clone(), generation)
784 .await?;
785 let restart_required = self
786 .daemon_restart_required(&exit_runtime, generation)
787 .await?;
788 Ok(ConfigControlResponse::Applied {
789 generation,
790 restart_required,
791 })
792 }
793 request => {
794 let kind = match request {
795 ConfigControlRequest::Plan {} => PlanKind::Change,
796 ConfigControlRequest::Stamp {} => PlanKind::Stamp,
797 ConfigControlRequest::Unstamp {} => PlanKind::Unstamp,
798 ConfigControlRequest::Rollback { generation } => PlanKind::Rollback(generation),
799 _ => {
800 return Err(GateError::new(
801 "unsupported_control_frame",
802 "unknown configuration operation",
803 ))
804 }
805 };
806 let mut prepared =
807 config_work(runtime.clone(), move |owner| owner.prepare(kind)).await?;
808 let mut fields = Vec::new();
809 let mut unavailable_rereviews = Vec::new();
810 for (module, captured) in &prepared.candidate.modules {
811 if !prepared.review_modules.contains(module) {
812 continue;
813 }
814 let base = prepared.bases.get(module);
815 let reply: std::result::Result<Vec<u8>, GateError> = async {
816 let registration = self
817 .registry
818 .get_module(module)
819 .map_err(|_| {
820 GateError::new("config_unavailable", "registry is unavailable")
821 })?
822 .ok_or_else(|| {
823 GateError::new(
824 "module_review_unavailable",
825 format!("{module}: no active reviewer"),
826 )
827 })?;
828 let admission = self.review_admission();
829 let reviewer = registration.clone();
830 config_work(runtime.clone(), move |_| admission.check(&reviewer)).await?;
831 if !registration
832 .control_ops
833 .iter()
834 .any(|op| op == "config.review")
835 {
836 return Err(GateError::new(
837 "module_review_unavailable",
838 format!("{module}: config.review is not opted in"),
839 ));
840 }
841 let request = subc_protocol::config::ConfigReviewRequest::new(
842 base.map_or(0, |b| b.generation),
843 captured.view.layers.clone(),
844 base.cloned(),
845 );
846 let bytes = serde_json::to_vec(&request).map_err(|_| {
847 GateError::new(
848 "config_unavailable",
849 "could not encode immutable review",
850 )
851 })?;
852 self.config_rpc(
853 &runtime,
854 module,
855 registration.connection_id,
856 "config.review",
857 bytes,
858 )
859 .await
860 }
861 .await;
862 let reply = match reply {
863 Ok(reply) => reply,
864 Err(_) if prepared.rereview_modules.contains(module) => {
867 unavailable_rereviews.push(module.clone());
868 continue;
869 }
870 Err(error) => return Err(error),
871 };
872 let reply = serde_json::from_slice(&reply).map_err(|_| {
873 GateError::new(
874 "module_review_invalid",
875 format!("{module}: malformed config.review reply"),
876 )
877 })?;
878 fields.extend(crate::config_gate::review::checked_fields(
879 module,
880 &captured.schema,
881 base,
882 prepared.base_schemas.get(module),
883 &captured.view,
884 reply,
885 )?);
886 }
887 for module in unavailable_rereviews {
888 prepared.review_modules.remove(&module);
889 prepared.rereview_modules.remove(&module);
890 }
891 let view = config_work(runtime, move |owner| {
892 owner.finish_plan(prepared, move |old, new| {
893 let mut changeset = crate::config_gate::runtime::daemon_review(old, new)?;
894 changeset.fields = fields;
895 let mut effects: std::collections::BTreeMap<String,std::collections::BTreeMap<String,Vec<String>>> = Default::default();
896 for field in &changeset.fields {
897 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();
898 effects.entry(field.module_id.clone()).or_default().entry(kind).or_default().push(field.path.clone());
899 }
900 if changeset.fields.iter().any(|field| field.apply != subc_config::ApplyKind::Live) {
901 changeset.apply_plan = serde_json::json!({"daemon_effects":changeset.apply_plan,"modules":effects});
902 }
903 Ok(changeset)
904 })
905 })
906 .await?;
907 Ok(match kind {
908 PlanKind::Change => ConfigControlResponse::Plan { view },
909 PlanKind::Stamp => ConfigControlResponse::Stamp { view },
910 PlanKind::Unstamp => ConfigControlResponse::Unstamp { view },
911 PlanKind::Rollback(_) => ConfigControlResponse::Rollback { view },
912 })
913 }
914 }
915 }
916
917 async fn config_approval_facts(&self, ctx: &RouteCtx) -> ApprovalFacts {
918 let phone = self.config_phone_surface().await;
919 self.config_approval_facts_with_phone(ctx, phone).await
920 }
921
922 async fn config_approval_facts_with_phone(
923 &self,
924 ctx: &RouteCtx,
925 phone: Option<crate::config_gate::PhoneSurface>,
926 ) -> ApprovalFacts {
927 let os_policy = crate::config_gate::os_prompt_policy_present();
928 #[cfg(any(test, feature = "test-support"))]
929 let os_policy = os_policy
930 || self
931 .config_runtime
932 .as_ref()
933 .is_some_and(|owner| owner.os_prompt_policy_for_tests());
934 let desktop = self
935 .config_desktop_identity(ctx.connection_id)
936 .unwrap_or(false);
937 ApprovalFacts {
938 connection: ctx.connection_id.get(),
939 owner_uid: self.config_owner_connection(ctx.connection_id),
940 desktop_app: desktop,
941 attested_operator_app: desktop && !cfg!(feature = "dev-desktop-approval"),
942 os_prompt_available: config_os_prompt_available(
943 self.forwarding.operator_confirms().config_gate_ready(),
944 os_policy,
945 ),
946 phone,
947 caller: self.resolve_caller(ctx.connection_id).await,
948 }
949 }
950
951 async fn config_phone_surface(&self) -> Option<crate::config_gate::PhoneSurface> {
954 self.config_phone_surface_checked(true, None).await
955 }
956
957 async fn config_phone_surface_snapshot(&self) -> Option<crate::config_gate::PhoneSurface> {
958 self.config_phone_surface_checked(false, None).await
959 }
960
961 async fn config_phone_surface_checked(
962 &self,
963 content: bool,
964 publication: Option<&crate::config_gate::runtime::Published>,
965 ) -> Option<crate::config_gate::PhoneSurface> {
966 if self.config_runtime.as_ref().is_some_and(|owner| {
967 publication.map_or_else(|| owner.is_recovering(), |view| view.is_recovering())
968 }) {
969 return None;
970 }
971 if !self.operator_app_policy.phone_enabled {
972 return None;
973 }
974 let runtime = self.config_runtime.as_ref()?;
975 let (_, registrations) = self.registry.list_modules_with_nonce_verification().ok()?;
976 let (registration, verified) = registrations
977 .into_iter()
978 .find(|(registration, _)| registration.manifest.module_id == "callosum")?;
979 if !verified
980 || !registration.ready
981 || !registration
982 .control_ops
983 .iter()
984 .any(|op| op == subc_protocol::consent::CONSENT_V1)
985 {
986 return None;
987 }
988 let _spawn = self
989 .supervisor
990 .registration_spawn(registration.connection_id)?;
991 if !self
992 .forwarding
993 .active_module_endpoint("callosum")
994 .ok()
995 .flatten()
996 .is_some_and(|endpoint| endpoint.connection_id == registration.connection_id)
997 {
998 return None;
999 }
1000 let module = self.supervisor.get("callosum")?;
1004 let status = module.status().ok()?;
1005 let (spec, _) = module.configuration().ok()?;
1006 if !self.supervisor.registration_snapshot_is_current_live(
1007 &self.registry,
1008 "callosum",
1009 registration.connection_id,
1010 None,
1011 ) || !spec.reserved
1012 || !status.enabled
1013 || !status.process_alive
1014 || !status.registration_active
1015 {
1016 return None;
1017 }
1018 let connection = registration.connection_id;
1019 let approved = if content {
1020 runtime
1021 .on_blocking(move |owner| owner.approved_phone_entry(connection))
1022 .await
1023 .ok()??
1024 } else {
1025 if let Some(snapshot) = publication {
1026 runtime.polled_phone_entry_from(snapshot, connection)?
1027 } else {
1028 runtime.polled_phone_entry(connection)?
1029 }
1030 };
1031 if !approved.enabled || approved.module_spec() != spec {
1032 return None;
1033 }
1034 if content {
1035 let supervisor = self.supervisor.clone();
1036 let registry = self.registry.clone();
1037 if !runtime
1038 .on_blocking(move |_| {
1039 Ok(supervisor
1040 .registration_is_current_live(®istry, "callosum", connection, None))
1041 })
1042 .await
1043 .ok()?
1044 {
1045 return None;
1046 }
1047 }
1048 if !self.supervisor.registration_snapshot_is_current_live(
1049 &self.registry,
1050 "callosum",
1051 registration.connection_id,
1052 None,
1053 ) {
1054 return None;
1055 }
1056 Some(crate::config_gate::PhoneSurface {
1057 module_id: "callosum".into(),
1058 connection: connection.get(),
1059 spawn_generation: status.spawn_generation,
1060 enabled_by_policy: true,
1061 opted_in: true,
1062 approved_declaration: true,
1063 reserved: true,
1064 channel_registered: true,
1065 program_admitted: true,
1066 active_registration: true,
1067 })
1068 }
1069
1070 async fn config_rpc(
1071 &self,
1072 runtime: &Arc<crate::config_gate::runtime::RuntimeOwner>,
1073 module: &str,
1074 expected_connection: ConnectionId,
1075 op: &str,
1076 bytes: Vec<u8>,
1077 ) -> std::result::Result<Vec<u8>, GateError> {
1078 let gate = runtime.module_gate(module)?;
1079 let pending = {
1080 let _gate = gate.lock().await;
1081 let registration = self
1082 .registry
1083 .get_module(module)
1084 .map_err(|_| GateError::new("config_unavailable", "registry unavailable"))?
1085 .ok_or_else(|| {
1086 GateError::new(
1087 "module_review_unavailable",
1088 format!("{module}: no active target"),
1089 )
1090 })?;
1091 let pending = self
1092 .forwarding
1093 .begin_module_control_rpc_for(module, op, Instant::now() + CONFIG_REVIEW_TIMEOUT)
1094 .map_err(|_| {
1095 GateError::new(
1096 "module_review_unavailable",
1097 format!("{module}: target unavailable"),
1098 )
1099 })?;
1100 if pending.endpoint.connection_id != registration.connection_id
1101 || registration.connection_id != expected_connection
1102 {
1103 let _ = self
1104 .forwarding
1105 .cancel_module_control_rpc(pending.endpoint, pending.corr);
1106 return Err(GateError::new(
1107 "not_delivery_target",
1108 "registry and forwarding targets differ",
1109 ));
1110 }
1111 pending
1112 };
1113 let PendingModuleControlRpc {
1114 endpoint,
1115 module_sink,
1116 negotiated_ver,
1117 corr,
1118 receiver,
1119 } = pending;
1120 let mut guard = ModuleControlRpcGuard::new(self.forwarding.clone(), endpoint, corr);
1121 let deadline = Instant::now() + CONFIG_REVIEW_TIMEOUT;
1122 let frame = Frame::build_with_version(
1123 negotiated_ver,
1124 FrameType::Request,
1125 control_flags(),
1126 0,
1127 0,
1128 corr,
1129 bytes,
1130 )
1131 .map_err(|_| GateError::new("config_unavailable", "could not encode config request"))?;
1132 timeout_at(deadline, module_sink.send(frame))
1133 .await
1134 .map_err(|_| {
1135 GateError::new(
1136 "config_review_timeout",
1137 format!("{module}: config.review exceeded its 30-second deadline; plan remains unapproved"),
1138 )
1139 })?
1140 .map_err(|_| {
1141 GateError::new(
1142 "module_review_unavailable",
1143 format!("{module}: target disconnected"),
1144 )
1145 })?;
1146 let outcome = timeout_at(deadline, receiver)
1147 .await
1148 .map_err(|_| {
1149 GateError::new(
1150 "config_review_timeout",
1151 format!("{module}: config.review exceeded its 30-second deadline; plan remains unapproved"),
1152 )
1153 })?
1154 .map_err(|_| {
1155 GateError::new(
1156 "module_review_unavailable",
1157 format!("{module}: target disconnected"),
1158 )
1159 })?;
1160 guard.disarm();
1161 match outcome {
1162 ModuleControlRpcOutcome::RawResponse(bytes) => Ok(bytes),
1163 ModuleControlRpcOutcome::DeadlineElapsed => Err(GateError::new("config_review_timeout",format!("{module}: config.review exceeded its 30-second deadline; plan remains unapproved"))),
1164 _ => Err(GateError::new(
1165 "module_review_unavailable",
1166 format!("{module}: config request was not answered"),
1167 )),
1168 }
1169 }
1170
1171 pub async fn confirm_config_gate_presence(
1174 &self,
1175 ctx: &RouteCtx,
1176 frame: &Frame,
1177 challenge: &ApprovalChallenge,
1178 ) -> PresenceDecision {
1179 let Some(text) = challenge.prompt() else {
1180 return PresenceDecision::Unavailable;
1181 };
1182 let caller = self.resolve_caller(ctx.connection_id).await;
1183 let key = crate::operator_confirm::DeclineKey::for_caller(&caller, ctx.connection_id);
1184 let outcome = self
1187 .forwarding
1188 .operator_confirms()
1189 .approve_config_gate(ctx, frame, text.to_owned(), caller.description(), key)
1190 .await;
1191 PresenceDecision::from_operator_outcome(&outcome)
1192 }
1193}
1194
1195fn config_os_prompt_available(provider_ready: bool, policy_present: bool) -> bool {
1196 provider_ready && policy_present
1197}
1198
1199async fn config_work<T: Send + 'static>(
1200 runtime: Arc<crate::config_gate::runtime::RuntimeOwner>,
1201 work: impl FnOnce(Arc<crate::config_gate::runtime::RuntimeOwner>) -> std::result::Result<T, GateError>
1202 + Send
1203 + 'static,
1204) -> std::result::Result<T, GateError> {
1205 runtime
1206 .on_blocking(move |owner| {
1207 let result = work(owner.clone());
1208 owner.notify_delivery_changed();
1209 result
1210 })
1211 .await
1212}
1213
1214pub(super) fn config_error_frame(frame: &Frame, error: GateError) -> Result<Frame, RouterError> {
1215 control_error_body_frame(
1216 frame,
1217 ErrorBody {
1218 code: error.code,
1219 message: error.detail,
1220 detail: None,
1221 },
1222 )
1223}
1224
1225fn now_ms() -> u64 {
1226 std::time::SystemTime::now()
1227 .duration_since(std::time::UNIX_EPOCH)
1228 .unwrap_or_default()
1229 .as_millis()
1230 .min(u128::from(u64::MAX)) as u64
1231}
1232
1233#[cfg(test)]
1234mod tests;
1235
1236#[cfg(test)]
1237mod desktop_tests;