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(), ConfigWake::None, 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(), ConfigWake::None, move |owner| {
225 owner.module_get_for_rpc(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(), ConfigWake::Delivery, 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(
337 runtime.clone(),
338 ConfigWake::Delivery,
339 move |owner| {
340 owner.delivery_timeout(
341 connection, &module, generation, attempt,
342 )
343 },
344 )
345 .await;
346 }
347 }
348 return match failed {
349 Ok(Err(error)) => Err(error),
350 _ => Ok(vec![]),
351 };
352 }
353 }
354 let module = registration.manifest.module_id.clone();
355 let delivered = config_work(runtime.clone(), ConfigWake::None, move |owner| {
356 owner.module_view_delivered(connection, &module, &view, flushed_at, active)
357 })
358 .await;
359 if let Err(error) = delivered {
360 if matches!(
361 error.code.as_str(),
362 "delivery_superseded" | "not_delivery_target"
363 ) {
364 return Ok(vec![]);
365 }
366 if error.code == "delivery_expired" {
367 if active {
368 if let Some((generation, attempt)) = selected {
369 let module = registration.manifest.module_id.clone();
370 let _ = config_work(
371 runtime.clone(),
372 ConfigWake::Delivery,
373 move |owner| {
374 owner.delivery_timeout(
375 connection, &module, generation, attempt,
376 )
377 },
378 )
379 .await;
380 }
381 }
382 } else {
383 return Err(RouterError::backend(
384 0,
385 frame.header.corr,
386 error.to_string(),
387 ));
388 }
389 }
390 Ok(vec![])
391 } else {
392 Ok(vec![response])
393 }
394 }
395 Err(error) => {
396 if error.code == "anchor_pending" {
397 let _ = config_work(runtime.clone(), ConfigWake::Delivery, move |owner| {
398 owner.anchor_pending_served(connection)
399 })
400 .await;
401 }
402 Ok(vec![config_error_frame(&frame, error)?])
403 }
404 }
405 }
406 pub fn with_config_runtime(
407 mut self,
408 runtime: Arc<crate::config_gate::runtime::RuntimeOwner>,
409 ) -> Self {
410 self.supervisor.install_binding_retirement(&runtime);
411 let _ = runtime.set_activity(self.activity.clone());
412 runtime.install_module_route_authority(Arc::new(route_policy::ModuleRouteAuthority(
413 self.clone(),
414 Arc::downgrade(&runtime),
415 )));
416 runtime.install_mark_publisher(Arc::new(caller_attestation::ControlMarkPublisher(
417 self.clone(),
418 )));
419 self.config_runtime = Some(runtime);
420 self
421 }
422
423 pub(crate) fn with_explicit_config_store(
425 self,
426 runtime: Arc<crate::config_gate::runtime::RuntimeOwner>,
427 ) -> Self {
428 let mut handler = self.with_config_runtime(runtime);
429 let capability = subc_protocol::config::CONFIG_GATE_CAPABILITY;
430 if !handler
431 .subc_capabilities
432 .iter()
433 .any(|present| present == capability)
434 {
435 let mut capabilities = handler.subc_capabilities.to_vec();
436 capabilities.push(capability.to_owned());
437 handler.subc_capabilities = capabilities.into();
438 }
439 handler
440 }
441
442 async fn config_desktop_identity(
443 &self,
444 connection: ConnectionId,
445 ) -> std::result::Result<bool, GateError> {
446 if !self.config_owner_connection(connection) {
447 return Ok(false);
448 }
449 #[cfg(feature = "dev-desktop-approval")]
450 {
451 Ok(self
454 .local_connections
455 .lock()
456 .unwrap_or_else(|p| p.into_inner())
457 .contains(&connection))
458 }
459 #[cfg(not(feature = "dev-desktop-approval"))]
460 {
461 Ok(self.has_current_config_desktop_stamp(connection).await)
462 }
463 }
464
465 pub(crate) fn config_desktop_review_request(&self, request: &Frame) -> bool {
466 self.config_runtime.is_some()
467 && request.header.ty == FrameType::Request
468 && serde_json::from_slice::<ControlOpProbe>(&request.body).is_ok_and(|probe| {
469 matches!(
470 probe.op.as_str(),
471 "config.plan" | "config.stamp" | "config.unstamp" | "config.rollback"
472 )
473 })
474 }
475
476 pub(crate) async fn config_desktop_review_response(
477 &self,
478 connection: ConnectionId,
479 response: &Frame,
480 ) -> Option<subc_control::config::ConfigPlanView> {
481 if self.config_runtime.is_none() || response.header.ty != FrameType::Response {
482 return None;
483 }
484 let probe: ControlOpProbe = serde_json::from_slice(&response.body).ok()?;
485 if !matches!(
486 probe.op.as_str(),
487 "config.plan"
488 | "config.plan_get"
489 | "config.stamp"
490 | "config.unstamp"
491 | "config.rollback"
492 ) || !matches!(self.config_desktop_identity(connection).await, Ok(true))
493 {
494 return None;
495 }
496 match serde_json::from_slice::<ConfigControlResponse>(&response.body).ok()? {
497 ConfigControlResponse::Plan { view }
498 | ConfigControlResponse::PlanGet { view }
499 | ConfigControlResponse::Stamp { view }
500 | ConfigControlResponse::Unstamp { view }
501 | ConfigControlResponse::Rollback { view } => Some(view),
502 _ => None,
503 }
504 }
505
506 pub(crate) async fn config_desktop_review_delivered(
507 &self,
508 connection: ConnectionId,
509 view: subc_control::config::ConfigPlanView,
510 ) {
511 if !matches!(self.config_desktop_identity(connection).await, Ok(true)) {
512 return;
513 }
514 let Some(runtime) = self.config_runtime.clone() else {
515 return;
516 };
517 let peers = self.captured_peers.clone();
518 let _ = config_work(runtime, ConfigWake::Delivery, move |owner| {
519 owner.desktop_view_delivered_when(connection, &view, || {
520 peers
521 .lock()
522 .unwrap_or_else(|p| p.into_inner())
523 .contains_key(&connection)
524 })
525 })
526 .await;
527 }
528
529 pub(crate) async fn deliver_config_desktop_review(
530 &self,
531 ctx: &RouteCtx,
532 response: Frame,
533 view: subc_control::config::ConfigPlanView,
534 ) -> Result<(), RouterError> {
535 ctx.egress.send_flushed(response).await?;
536 self.config_desktop_review_delivered(ctx.connection_id, view)
537 .await;
538 Ok(())
539 }
540
541 pub fn with_config_review_admission(
542 mut self,
543 admission: Arc<dyn crate::config_gate::ReviewAdmission>,
544 ) -> Self {
545 self.config_review_admission = admission;
546 self.config_review_admission_is_default = false;
547 self
548 }
549
550 pub(super) fn review_admission(&self) -> Arc<dyn crate::config_gate::ReviewAdmission> {
551 if self.config_runtime.is_some() && self.config_review_admission_is_default {
552 Arc::new(admission::SupervisedReviewAdmission(self.clone()))
553 } else {
554 self.config_review_admission.clone()
555 }
556 }
557
558 pub(super) async fn handle_config_gate_request(
561 &self,
562 ctx: &RouteCtx,
563 frame: Frame,
564 ) -> Result<Vec<Frame>, RouterError> {
565 let request = match serde_json::from_slice::<ConfigControlRequest>(&frame.body) {
566 Ok(request) => request,
567 Err(error) => {
568 return Ok(vec![control_error_frame(
569 &frame,
570 "invalid_control_body",
571 format!("malformed config control body: {error}"),
572 )?])
573 }
574 };
575 debug_assert!(privileged_operation(&request).is_none());
576 let Some(runtime) = self.config_runtime.clone() else {
577 return Ok(vec![control_error_frame(
578 &frame,
579 "config_gate_inactive",
580 "no config store configured",
581 )?]);
582 };
583 if !self.config_owner_connection(ctx.connection_id) {
584 return Ok(vec![control_error_frame(
585 &frame,
586 "owner_required",
587 "configuration control requires a kernel-observed owner-user connection",
588 )?]);
589 }
590 if let ConfigControlRequest::Watch { modules, .. } = request {
591 return self
592 .handle_config_settings_watch(ctx, frame, runtime, modules)
593 .await;
594 }
595 let result = self
596 .execute_config_request(ctx, &frame, runtime, request)
597 .await;
598 match result {
599 Ok(response) => Ok(vec![control_response_body_frame(
600 &frame,
601 &response,
602 "ConfigControlResponse",
603 )?]),
604 Err(error) => Ok(vec![config_error_frame(&frame, error)?]),
605 }
606 }
607
608 fn config_owner_connection(&self, connection: ConnectionId) -> bool {
609 let peers = self
610 .observed_peers
611 .lock()
612 .unwrap_or_else(|p| p.into_inner());
613 let Some(peer) = peers.get(&connection) else {
614 return false;
615 };
616 #[cfg(unix)]
617 {
618 peer.uid == Some(subc_os::effective_uid())
619 }
620 #[cfg(windows)]
621 {
622 subc_os::named_pipe::current_user_sid_string()
623 .ok()
624 .as_ref()
625 .is_some_and(|sid| peer.sid.as_ref() == Some(sid))
626 }
627 #[cfg(not(any(unix, windows)))]
628 {
629 let _ = peer;
630 false
631 }
632 }
633
634 async fn execute_config_request(
635 &self,
636 ctx: &RouteCtx,
637 frame: &Frame,
638 runtime: Arc<crate::config_gate::runtime::RuntimeOwner>,
639 request: ConfigControlRequest,
640 ) -> std::result::Result<ConfigControlResponse, GateError> {
641 match request {
642 ConfigControlRequest::Modules {} => {
643 let known = self.config_settings_known_modules()?;
644 config_work(runtime, ConfigWake::None, move |owner| {
645 owner.settings_modules(known)
646 })
647 .await
648 }
649 ConfigControlRequest::Schema { module_id } => {
650 let known = self.config_settings_known_modules()?;
651 config_work(runtime, ConfigWake::None, move |owner| {
652 owner.settings_schema(known, module_id)
653 })
654 .await
655 }
656 ConfigControlRequest::Show {
657 module_id,
658 project_id,
659 through,
660 } => {
661 let known = self.config_settings_known_modules()?;
662 config_work(runtime, ConfigWake::None, move |owner| {
663 owner.settings_show(known, module_id, project_id, through)
664 })
665 .await
666 }
667 ConfigControlRequest::PlanGet { digest } => {
668 let view = config_work(runtime, ConfigWake::None, move |owner| {
669 owner.plan_get(&digest)
670 })
671 .await?;
672 Ok(ConfigControlResponse::PlanGet { view })
673 }
674 ConfigControlRequest::PlanDiscard { digest } => {
675 config_work(runtime, ConfigWake::Delivery, move |owner| {
676 owner.plan_discard(&digest)
677 })
678 .await?;
679 Ok(ConfigControlResponse::PlanDiscard {})
680 }
681 ConfigControlRequest::PlaceProgram {
682 module_id,
683 path,
684 sha256,
685 manifest,
686 } => {
687 let gate = runtime.module_gate(&module_id)?;
688 let _guard = gate.lock().await;
689 let generation = config_work(runtime, ConfigWake::Delivery, move |owner| {
690 owner.place_program_with_manifest(&module_id, &path, &sha256, manifest.as_ref())
691 })
692 .await?;
693 Ok(ConfigControlResponse::ProgramPlaced { generation })
694 }
695 ConfigControlRequest::Status {} => {
696 let snapshot = runtime.polled_snapshot()?;
697 let captured = snapshot.clone();
698 let mut status = runtime
699 .on_blocking(move |owner| owner.polled_status_from(&captured))
700 .await?;
701 let phone = self
702 .config_phone_surface_checked(false, Some(&snapshot))
703 .await;
704 let facts = self.config_approval_facts_with_phone(ctx, phone).await;
705 status
706 .missing_approval_surfaces
707 .extend(crate::config_gate::missing_surfaces(
708 &facts,
709 matches!(status.state.as_str(), "store_missing" | "store_unverified"),
710 ));
711 self.report_daemon_configuration(&snapshot.approved_daemon, &mut status)
712 .await?;
713 Ok(ConfigControlResponse::Status { status })
714 }
715 ConfigControlRequest::History {} => {
716 let (generations, pruned) =
717 config_work(runtime, ConfigWake::None, |owner| owner.history()).await?;
718 Ok(ConfigControlResponse::History {
719 generations,
720 pruned,
721 })
722 }
723 ConfigControlRequest::Apply { digest } => {
724 let apply_digest = digest.clone();
725 if let Some(generation) =
726 config_work(runtime.clone(), ConfigWake::Delivery, move |owner| {
727 owner.apply_unstamped_edits(&apply_digest)
728 })
729 .await?
730 {
731 return Ok(ConfigControlResponse::Applied {
732 generation,
733 restart_required: false,
734 });
735 }
736 let connection = ctx.connection_id;
737 let corr = frame.header.corr;
738 #[cfg(all(test, unix))]
739 runtime.pause_approval_claim_for_test().await;
740 let request_guard = runtime.claim_approval_request(connection, corr)?;
741 if self.rescan.is_none() {
742 return Err(GateError::new(
743 "supervisor_reconcile_unavailable",
744 "configuration commit requires the supervisor owner",
745 ));
746 }
747 let facts = self.config_approval_facts(ctx).await;
748 let cancellation = request_guard.request.clone();
749 let (challenge, mut attempt_guard) =
750 config_work(runtime.clone(), ConfigWake::Delivery, move |owner| {
751 let challenge = owner.begin_approval_for_request(
752 &digest,
753 &facts,
754 Some(&cancellation),
755 )?;
756 let guard = phone::ApprovalAttemptGuard::new(&owner, challenge.attempt());
759 owner.track_reserved_approval_request(
760 challenge.attempt(),
761 connection,
762 corr,
763 &cancellation,
764 )?;
765 Ok((challenge, guard))
766 })
767 .await?;
768 request_guard.request.ensure_live()?;
769 let reply = match &challenge {
770 ApprovalChallenge::Desktop { .. } | ApprovalChallenge::OsPrompt { .. } => {
771 ApprovalReply::Presence(
772 self.confirm_config_gate_presence(ctx, frame, &challenge)
773 .await,
774 )
775 }
776 ApprovalChallenge::Phone {
777 attempt,
778 connection,
779 deadline,
780 request,
781 } => {
782 self.config_phone_rpc(
783 &runtime,
784 *attempt,
785 ConnectionId::new(*connection),
786 *deadline,
787 request,
788 )
789 .await?
790 }
791 };
792 let attempt = challenge.attempt();
793 let window = matches!(challenge, ApprovalChallenge::Phone { .. }).then(|| {
794 Arc::new(crate::config_gate::runtime::ApprovalCommitWindow::new(
795 Instant::now() + CONFIG_APPROVAL_COMMIT_TIMEOUT,
796 ))
797 });
798 attempt_guard.commit_window = window.clone();
799 let checked_phone = self.config_phone_surface().await;
800 let locks = async {
801 let operation = self.supervisor.operation_lock().lock_owned().await;
802 let module_gates = runtime.approval_commit_gates(attempt).await?;
803 let current_phone = self.config_phone_surface_snapshot().await;
804 let phone = checked_phone.filter(|phone| Some(phone) == current_phone.as_ref());
805 let facts = self.config_approval_facts_with_phone(ctx, phone).await;
806 let project_apply = runtime.recheck_capture_apply(attempt).await?;
807 Ok::<_, GateError>((operation, module_gates, facts, project_apply))
808 };
809 let (operation, module_gates, facts, project_apply) = if let Some(window) = &window
810 {
811 timeout_at(window.deadline, locks)
812 .await
813 .map_err(|_| GateError::commit_timeout())??
814 } else {
815 locks.await?
816 };
817 let now = now_ms();
818 let publish_window = window.clone();
819 let publication_request = request_guard.request.clone();
820 let exit_runtime = runtime.clone();
821 let work = config_work(runtime, ConfigWake::Delivery, move |owner| {
822 let _owned_gates = (operation, module_gates);
823 owner.finish_approval_with_commit_window(
824 attempt,
825 &facts,
826 reply,
827 now,
828 publish_window,
829 publication_request,
830 project_apply,
831 )
832 });
833 tokio::pin!(work);
834 let generation = if let Some(window) = window {
835 tokio::select! {
836 result = &mut work => result?,
837 _ = tokio::time::sleep_until(window.deadline) => {
838 if window.expire() { return Err(GateError::commit_timeout()); }
839 work.await?
840 }
841 }
842 } else {
843 work.await?
844 };
845 let approval_runtime = exit_runtime.clone();
846 if let Some(approval) =
847 config_work(approval_runtime, ConfigWake::None, move |owner| {
848 owner.development_approval(generation)
849 })
850 .await?
851 {
852 self.publish_development_approval(&approval);
853 return Ok(ConfigControlResponse::Applied {
854 generation,
855 restart_required: false,
856 });
857 }
858 #[cfg(test)]
859 self.pause_before_apply_reconcile_for_test().await;
860 self.reconcile_authority_exit(exit_runtime.clone(), generation)
861 .await?;
862 let restart_required = self
863 .daemon_restart_required(&exit_runtime, generation)
864 .await?;
865 Ok(ConfigControlResponse::Applied {
866 generation,
867 restart_required,
868 })
869 }
870 request => {
871 let (kind, edits) = match request {
872 ConfigControlRequest::Plan {
873 base_generations,
874 edits,
875 } => {
876 if edits.is_none() && base_generations.is_some() {
877 return Err(GateError::new(
878 "invalid_params",
879 "base_generations requires edits",
880 ));
881 }
882 let edits = edits
883 .map(|edits| {
884 base_generations.map(|base| (base, edits)).ok_or_else(|| {
885 GateError::new(
886 "invalid_params",
887 "edits requires base_generations",
888 )
889 })
890 })
891 .transpose()?;
892 (PlanKind::Change, edits)
893 }
894 ConfigControlRequest::Stamp {} => (PlanKind::Stamp, None),
895 ConfigControlRequest::Unstamp {} => (PlanKind::Unstamp, None),
896 ConfigControlRequest::Rollback { generation } => {
897 (PlanKind::Rollback(generation), None)
898 }
899 _ => {
900 return Err(GateError::new(
901 "unsupported_control_frame",
902 "unknown configuration operation",
903 ))
904 }
905 };
906 let mut prepared = match edits {
907 Some((base, edits)) => {
908 config_work(runtime.clone(), ConfigWake::Delivery, move |owner| {
909 owner.prepare_edits(base, edits)
910 })
911 .await?
912 }
913 None => {
914 let prepared = runtime.prepare_capture(kind).await?;
915 runtime.notify_delivery_changed();
917 prepared
918 }
919 };
920 if prepared.capture_refused() {
921 let view = config_work(runtime, ConfigWake::None, move |owner| {
922 owner.capture_refusal(&prepared)?.ok_or_else(|| {
923 GateError::new("module_review_invalid", "project refusal is absent")
924 })
925 })
926 .await?;
927 return Ok(ConfigControlResponse::Plan { view });
928 }
929 let mut fields = Vec::new();
930 let mut edit_refusals = Vec::new();
931 let mut unavailable_rereviews = Vec::new();
932 for (module, captured) in &prepared.candidate.modules {
933 if !prepared.review_modules.contains(module) {
934 continue;
935 }
936 let base = prepared.bases.get(module);
937 let reply = self
938 .review_config_tuple(&runtime, module, base, &captured.view)
939 .await;
940 let reply = match reply {
941 Ok(reply) => reply,
942 Err(_) if prepared.rereview_modules.contains(module) => {
945 unavailable_rereviews.push(module.clone());
946 continue;
947 }
948 Err(error) => return Err(error),
949 };
950 let reply: subc_protocol::config::ConfigReviewReply =
951 serde_json::from_slice(&reply).map_err(|_| {
952 GateError::new(
953 "module_review_invalid",
954 format!("{module}: malformed config.review reply"),
955 )
956 })?;
957 if prepared.is_edit_plan() && !reply.refusals.is_empty() {
958 let before = edit_refusals.len();
959 for refusal in &reply.refusals {
960 for path in refusal
961 .paths
962 .iter()
963 .filter(|path| path.starts_with('/') && path.len() <= 1024)
964 {
965 edit_refusals.push(subc_control::config::ConfigPlanRefusal {
966 module_id: module.clone(),
967 path: path.clone(),
968 code: "module_review_refused".into(),
969 message: "the module refused this field".into(),
970 project_id: None,
971 workspace_id: None,
972 });
973 }
974 }
975 if edit_refusals.len() == before {
976 edit_refusals.push(subc_control::config::ConfigPlanRefusal {
977 module_id: module.clone(),
978 path: String::new(),
979 code: "module_review_refused".into(),
980 message: "the module refused the edits".into(),
981 project_id: None,
982 workspace_id: None,
983 });
984 }
985 fields.extend(prepared.refused_fields(module)?);
986 continue;
987 }
988 fields.extend(crate::config_gate::review::checked_fields(
989 module,
990 &captured.schema,
991 base,
992 prepared.base_schemas.get(module),
993 &captured.view,
994 reply,
995 )?);
996 }
997 for module in unavailable_rereviews {
998 prepared.review_modules.remove(&module);
999 prepared.rereview_modules.remove(&module);
1000 }
1001 let mut project_replies = Vec::new();
1002 for (tuple, review) in prepared.project_reviews() {
1003 let bytes = self
1004 .review_config_tuple(
1005 &runtime,
1006 &tuple.module,
1007 review.base.as_ref(),
1008 &review.approval.view,
1009 )
1010 .await?;
1011 let reply = serde_json::from_slice(&bytes).map_err(|_| {
1012 GateError::new(
1013 "module_review_invalid",
1014 format!("{}: malformed project config.review reply", tuple.module),
1015 )
1016 })?;
1017 project_replies.push((tuple.clone(), reply));
1018 }
1019 for (tuple, reply) in project_replies {
1020 fields.extend(prepared.accept_project_review(&tuple, reply)?);
1021 }
1022 prepared.add_edit_refusals(edit_refusals);
1023 let view = config_work(runtime, ConfigWake::Delivery, move |owner| {
1024 owner.finish_plan(prepared, move |old, new| {
1025 let mut changeset = crate::config_gate::runtime::daemon_review(old, new)?;
1026 changeset.fields = fields;
1027 let mut effects: std::collections::BTreeMap<String,std::collections::BTreeMap<String,Vec<String>>> = Default::default();
1028 for field in changeset.fields.iter().filter(|field| field.project_id.is_none()) {
1029 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();
1030 effects.entry(field.module_id.clone()).or_default().entry(kind).or_default().push(field.path.clone());
1031 }
1032 if changeset.fields.iter().any(|field| field.project_id.is_none() && field.apply != subc_config::ApplyKind::Live) {
1033 changeset.apply_plan = serde_json::json!({"daemon_effects":changeset.apply_plan,"modules":effects});
1034 }
1035 Ok(changeset)
1036 })
1037 })
1038 .await?;
1039 Ok(match kind {
1040 PlanKind::Change => ConfigControlResponse::Plan { view },
1041 PlanKind::Stamp => ConfigControlResponse::Stamp { view },
1042 PlanKind::Unstamp => ConfigControlResponse::Unstamp { view },
1043 PlanKind::Rollback(_) => ConfigControlResponse::Rollback { view },
1044 })
1045 }
1046 }
1047 }
1048
1049 async fn review_config_tuple(
1050 &self,
1051 runtime: &Arc<crate::config_gate::runtime::RuntimeOwner>,
1052 module: &str,
1053 base: Option<&subc_protocol::config::ConfigView>,
1054 candidate: &subc_protocol::config::ConfigView,
1055 ) -> Result<Vec<u8>, GateError> {
1056 #[cfg(test)]
1057 if let Some(reply) = &self.config_review_test_reply {
1058 return serde_json::to_vec(reply).map_err(|_| {
1059 GateError::new(
1060 "module_review_invalid",
1061 "could not encode the fixture review",
1062 )
1063 });
1064 }
1065 let registration = self
1066 .registry
1067 .get_module(module)
1068 .map_err(|_| GateError::new("config_unavailable", "registry is unavailable"))?
1069 .ok_or_else(|| {
1070 GateError::new(
1071 "module_review_unavailable",
1072 format!("{module}: no active reviewer"),
1073 )
1074 })?;
1075 let admission = self.review_admission();
1076 let reviewer = registration.clone();
1077 config_work(runtime.clone(), ConfigWake::None, move |_| {
1078 admission.check(&reviewer)
1079 })
1080 .await?;
1081 if !registration
1082 .control_ops
1083 .iter()
1084 .any(|op| op == "config.review")
1085 {
1086 return Err(GateError::new(
1087 "module_review_unavailable",
1088 format!("{module}: config.review is not opted in"),
1089 ));
1090 }
1091 let request = subc_protocol::config::ConfigReviewRequest::new(
1092 base.map_or(0, |view| view.generation),
1093 candidate.layers.clone(),
1094 base.cloned(),
1095 );
1096 let bytes = serde_json::to_vec(&request).map_err(|_| {
1097 GateError::new("config_unavailable", "could not encode immutable review")
1098 })?;
1099 self.config_rpc(
1100 runtime,
1101 module,
1102 registration.connection_id,
1103 "config.review",
1104 bytes,
1105 )
1106 .await
1107 }
1108
1109 async fn config_approval_facts(&self, ctx: &RouteCtx) -> ApprovalFacts {
1110 let phone = self.config_phone_surface().await;
1111 self.config_approval_facts_with_phone(ctx, phone).await
1112 }
1113
1114 async fn config_approval_facts_with_phone(
1115 &self,
1116 ctx: &RouteCtx,
1117 phone: Option<crate::config_gate::PhoneSurface>,
1118 ) -> ApprovalFacts {
1119 let os_policy = crate::config_gate::os_prompt_policy_present();
1120 #[cfg(any(test, feature = "test-support"))]
1121 let os_policy = os_policy
1122 || self
1123 .config_runtime
1124 .as_ref()
1125 .is_some_and(|owner| owner.os_prompt_policy_for_tests());
1126 let desktop = self
1127 .config_desktop_identity(ctx.connection_id)
1128 .await
1129 .unwrap_or(false);
1130 ApprovalFacts {
1131 connection: ctx.connection_id.get(),
1132 owner_uid: self.config_owner_connection(ctx.connection_id),
1133 desktop_app: desktop,
1134 attested_operator_app: desktop && !cfg!(feature = "dev-desktop-approval"),
1135 os_prompt_available: config_os_prompt_available(
1136 self.forwarding.operator_confirms().config_gate_ready(),
1137 os_policy,
1138 ),
1139 phone,
1140 caller: self.resolve_caller(ctx.connection_id).await,
1141 }
1142 }
1143
1144 async fn config_phone_surface(&self) -> Option<crate::config_gate::PhoneSurface> {
1147 self.config_phone_surface_checked(true, None).await
1148 }
1149
1150 async fn config_phone_surface_snapshot(&self) -> Option<crate::config_gate::PhoneSurface> {
1151 self.config_phone_surface_checked(false, None).await
1152 }
1153
1154 async fn config_phone_surface_checked(
1155 &self,
1156 content: bool,
1157 publication: Option<&crate::config_gate::runtime::Published>,
1158 ) -> Option<crate::config_gate::PhoneSurface> {
1159 if self.config_runtime.as_ref().is_some_and(|owner| {
1160 publication.map_or_else(|| owner.is_recovering(), |view| view.is_recovering())
1161 }) {
1162 return None;
1163 }
1164 if !self.operator_app_policy.phone_enabled {
1165 return None;
1166 }
1167 let runtime = self.config_runtime.as_ref()?;
1168 let (_, registrations) = self.registry.list_modules_with_nonce_verification().ok()?;
1169 let (registration, verified) = registrations
1170 .into_iter()
1171 .find(|(registration, _)| registration.manifest.module_id == "callosum")?;
1172 if !verified
1173 || !registration.ready
1174 || !registration
1175 .control_ops
1176 .iter()
1177 .any(|op| op == subc_protocol::consent::CONSENT_V1)
1178 {
1179 return None;
1180 }
1181 let _spawn = self
1182 .supervisor
1183 .registration_spawn(registration.connection_id)?;
1184 if !self
1185 .forwarding
1186 .active_module_endpoint("callosum")
1187 .ok()
1188 .flatten()
1189 .is_some_and(|endpoint| endpoint.connection_id == registration.connection_id)
1190 {
1191 return None;
1192 }
1193 let module = self.supervisor.get("callosum")?;
1197 let status = module.status().ok()?;
1198 let (spec, _) = module.configuration().ok()?;
1199 if !self.supervisor.registration_snapshot_is_current_live(
1200 &self.registry,
1201 "callosum",
1202 registration.connection_id,
1203 None,
1204 ) || !spec.reserved
1205 || !status.enabled
1206 || !status.process_alive
1207 || !status.registration_active
1208 {
1209 return None;
1210 }
1211 let connection = registration.connection_id;
1212 let approved = if content {
1213 runtime
1214 .on_blocking(move |owner| owner.approved_phone_entry(connection))
1215 .await
1216 .ok()??
1217 } else {
1218 if let Some(snapshot) = publication {
1219 runtime.polled_phone_entry_from(snapshot, connection)?
1220 } else {
1221 runtime.polled_phone_entry(connection)?
1222 }
1223 };
1224 if !approved.enabled || approved.module_spec() != spec {
1225 return None;
1226 }
1227 if content {
1228 let supervisor = self.supervisor.clone();
1229 let registry = self.registry.clone();
1230 if !runtime
1231 .on_blocking(move |_| {
1232 Ok(supervisor
1233 .registration_is_current_live(®istry, "callosum", connection, None))
1234 })
1235 .await
1236 .ok()?
1237 {
1238 return None;
1239 }
1240 }
1241 if !self.supervisor.registration_snapshot_is_current_live(
1242 &self.registry,
1243 "callosum",
1244 registration.connection_id,
1245 None,
1246 ) {
1247 return None;
1248 }
1249 Some(crate::config_gate::PhoneSurface {
1250 module_id: "callosum".into(),
1251 connection: connection.get(),
1252 spawn_generation: status.spawn_generation,
1253 enabled_by_policy: true,
1254 opted_in: true,
1255 approved_declaration: true,
1256 reserved: true,
1257 channel_registered: true,
1258 program_admitted: true,
1259 active_registration: true,
1260 })
1261 }
1262
1263 async fn config_rpc(
1264 &self,
1265 runtime: &Arc<crate::config_gate::runtime::RuntimeOwner>,
1266 module: &str,
1267 expected_connection: ConnectionId,
1268 op: &str,
1269 bytes: Vec<u8>,
1270 ) -> std::result::Result<Vec<u8>, GateError> {
1271 let gate = runtime.module_gate(module)?;
1272 let pending = {
1273 let _gate = gate.lock().await;
1274 let registration = self
1275 .registry
1276 .get_module(module)
1277 .map_err(|_| GateError::new("config_unavailable", "registry unavailable"))?
1278 .ok_or_else(|| {
1279 GateError::new(
1280 "module_review_unavailable",
1281 format!("{module}: no active target"),
1282 )
1283 })?;
1284 let pending = self
1285 .forwarding
1286 .begin_module_control_rpc_for(module, op, Instant::now() + CONFIG_REVIEW_TIMEOUT)
1287 .map_err(|_| {
1288 GateError::new(
1289 "module_review_unavailable",
1290 format!("{module}: target unavailable"),
1291 )
1292 })?;
1293 if pending.endpoint.connection_id != registration.connection_id
1294 || registration.connection_id != expected_connection
1295 {
1296 let _ = self
1297 .forwarding
1298 .cancel_module_control_rpc(pending.endpoint, pending.corr);
1299 return Err(GateError::new(
1300 "not_delivery_target",
1301 "registry and forwarding targets differ",
1302 ));
1303 }
1304 pending
1305 };
1306 let PendingModuleControlRpc {
1307 endpoint,
1308 module_sink,
1309 negotiated_ver,
1310 corr,
1311 receiver,
1312 } = pending;
1313 let mut guard = ModuleControlRpcGuard::new(self.forwarding.clone(), endpoint, corr);
1314 let deadline = Instant::now() + CONFIG_REVIEW_TIMEOUT;
1315 let frame = Frame::build_with_version(
1316 negotiated_ver,
1317 FrameType::Request,
1318 control_flags(),
1319 0,
1320 0,
1321 corr,
1322 bytes,
1323 )
1324 .map_err(|_| GateError::new("config_unavailable", "could not encode config request"))?;
1325 timeout_at(deadline, module_sink.send(frame))
1326 .await
1327 .map_err(|_| {
1328 GateError::new(
1329 "config_review_timeout",
1330 format!("{module}: config.review exceeded its 30-second deadline; plan remains unapproved"),
1331 )
1332 })?
1333 .map_err(|_| {
1334 GateError::new(
1335 "module_review_unavailable",
1336 format!("{module}: target disconnected"),
1337 )
1338 })?;
1339 let outcome = timeout_at(deadline, receiver)
1340 .await
1341 .map_err(|_| {
1342 GateError::new(
1343 "config_review_timeout",
1344 format!("{module}: config.review exceeded its 30-second deadline; plan remains unapproved"),
1345 )
1346 })?
1347 .map_err(|_| {
1348 GateError::new(
1349 "module_review_unavailable",
1350 format!("{module}: target disconnected"),
1351 )
1352 })?;
1353 guard.disarm();
1354 match outcome {
1355 ModuleControlRpcOutcome::RawResponse(bytes) => Ok(bytes),
1356 ModuleControlRpcOutcome::DeadlineElapsed => Err(GateError::new("config_review_timeout",format!("{module}: config.review exceeded its 30-second deadline; plan remains unapproved"))),
1357 _ => Err(GateError::new(
1358 "module_review_unavailable",
1359 format!("{module}: config request was not answered"),
1360 )),
1361 }
1362 }
1363
1364 pub async fn confirm_config_gate_presence(
1367 &self,
1368 ctx: &RouteCtx,
1369 frame: &Frame,
1370 challenge: &ApprovalChallenge,
1371 ) -> PresenceDecision {
1372 let Some(text) = challenge.prompt() else {
1373 return PresenceDecision::Unavailable;
1374 };
1375 let caller = self.resolve_caller(ctx.connection_id).await;
1376 let key = crate::operator_confirm::DeclineKey::for_caller(&caller, ctx.connection_id);
1377 let outcome = self
1380 .forwarding
1381 .operator_confirms()
1382 .approve_config_gate(ctx, frame, text.to_owned(), caller.description(), key)
1383 .await;
1384 PresenceDecision::from_operator_outcome(&outcome)
1385 }
1386}
1387
1388fn config_os_prompt_available(provider_ready: bool, policy_present: bool) -> bool {
1389 provider_ready && policy_present
1390}
1391
1392enum ConfigWake {
1393 None,
1394 Delivery,
1395}
1396
1397async fn config_work<T: Send + 'static>(
1398 runtime: Arc<crate::config_gate::runtime::RuntimeOwner>,
1399 wake: ConfigWake,
1400 work: impl FnOnce(Arc<crate::config_gate::runtime::RuntimeOwner>) -> std::result::Result<T, GateError>
1401 + Send
1402 + 'static,
1403) -> std::result::Result<T, GateError> {
1404 runtime
1405 .on_blocking(move |owner| {
1406 let result = work(owner.clone());
1407 if matches!(wake, ConfigWake::Delivery) {
1408 owner.notify_delivery_changed();
1409 }
1410 result
1411 })
1412 .await
1413}
1414
1415pub(super) fn config_error_frame(frame: &Frame, error: GateError) -> Result<Frame, RouterError> {
1416 control_error_body_frame(
1417 frame,
1418 ErrorBody {
1419 code: error.code,
1420 message: error.detail,
1421 detail: None,
1422 },
1423 )
1424}
1425
1426fn now_ms() -> u64 {
1427 std::time::SystemTime::now()
1428 .duration_since(std::time::UNIX_EPOCH)
1429 .unwrap_or_default()
1430 .as_millis()
1431 .min(u128::from(u64::MAX)) as u64
1432}
1433
1434#[cfg(test)]
1435mod tests;
1436
1437#[cfg(test)]
1438mod desktop_tests;