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