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