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 pub(super) 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 if let Some(problem) = runtime
757 .on_blocking(move |owner| {
758 Ok(owner.policy_root_problem(&snapshot.approved_daemon))
759 })
760 .await?
761 {
762 status.warnings.push(problem);
763 }
764 Ok(ConfigControlResponse::Status { status })
765 }
766 ConfigControlRequest::History {} => {
767 let (generations, pruned) =
768 config_work(runtime, ConfigWake::None, |owner| owner.history()).await?;
769 Ok(ConfigControlResponse::History {
770 generations,
771 pruned,
772 })
773 }
774 ConfigControlRequest::Apply { digest } => {
775 if let Some(result) = self
776 .apply_unstamped_policy_root(ctx, frame, &runtime, &digest)
777 .await?
778 {
779 return Ok(result);
780 }
781 let apply_digest = digest.clone();
782 if let Some(generation) = runtime.apply_control_edits(apply_digest).await? {
783 return Ok(ConfigControlResponse::Applied {
784 generation,
785 restart_required: false,
786 });
787 }
788 let connection = ctx.connection_id;
789 let corr = frame.header.corr;
790 #[cfg(all(test, unix))]
791 runtime.pause_approval_claim_for_test().await;
792 let request_guard = runtime.claim_approval_request(connection, corr)?;
793 if self.rescan.is_none() {
794 return Err(GateError::new(
795 "supervisor_reconcile_unavailable",
796 "configuration commit requires the supervisor owner",
797 ));
798 }
799 let facts = self.config_approval_facts(ctx).await;
800 let cancellation = request_guard.request.clone();
801 let (challenge, mut attempt_guard) =
802 config_work(runtime.clone(), ConfigWake::Delivery, move |owner| {
803 let challenge = owner.begin_approval_for_request(
804 &digest,
805 &facts,
806 Some(&cancellation),
807 )?;
808 let guard = phone::ApprovalAttemptGuard::new(&owner, challenge.attempt());
811 owner.track_reserved_approval_request(
812 challenge.attempt(),
813 connection,
814 corr,
815 &cancellation,
816 )?;
817 Ok((challenge, guard))
818 })
819 .await?;
820 request_guard.request.ensure_live()?;
821 let reply = match &challenge {
822 ApprovalChallenge::Desktop { .. } | ApprovalChallenge::OsPrompt { .. } => {
823 ApprovalReply::Presence(
824 self.confirm_config_gate_presence(ctx, frame, &challenge)
825 .await,
826 )
827 }
828 ApprovalChallenge::Phone {
829 attempt,
830 connection,
831 deadline,
832 request,
833 } => {
834 self.config_phone_rpc(
835 &runtime,
836 *attempt,
837 ConnectionId::new(*connection),
838 *deadline,
839 request,
840 )
841 .await?
842 }
843 };
844 let attempt = challenge.attempt();
845 let window = matches!(challenge, ApprovalChallenge::Phone { .. }).then(|| {
846 Arc::new(crate::config_gate::runtime::ApprovalCommitWindow::new(
847 Instant::now() + CONFIG_APPROVAL_COMMIT_TIMEOUT,
848 ))
849 });
850 attempt_guard.commit_window = window.clone();
851 let checked_phone = self.config_phone_surface().await;
852 let locks = async {
853 let project_apply = runtime.recheck_capture_apply(attempt).await?;
857 let operation = self.supervisor.operation_lock().lock_owned().await;
858 let module_gates = runtime.approval_commit_gates(attempt).await?;
859 let current_phone = self.config_phone_surface_snapshot().await;
860 let phone = checked_phone.filter(|phone| Some(phone) == current_phone.as_ref());
861 let facts = self.config_approval_facts_with_phone(ctx, phone).await;
862 Ok::<_, GateError>((operation, module_gates, facts, project_apply))
863 };
864 let (operation, module_gates, facts, project_apply) = if let Some(window) = &window
865 {
866 timeout_at(window.deadline, locks)
867 .await
868 .map_err(|_| GateError::commit_timeout())??
869 } else {
870 locks.await?
871 };
872 let now = now_ms();
873 let publish_window = window.clone();
874 let publication_request = request_guard.request.clone();
875 let exit_runtime = runtime.clone();
876 let work = config_work(runtime, ConfigWake::Delivery, move |owner| {
877 let _owned_gates = (operation, module_gates);
878 let write_authority = project_apply.clone();
879 let generation = owner.finish_approval_with_commit_window(
880 attempt,
881 &facts,
882 reply,
883 now,
884 publish_window,
885 publication_request,
886 project_apply,
887 )?;
888 if let Some(authority) = write_authority {
889 tokio::spawn(async move {
892 owner
893 .write_approved_project_files(generation, authority)
894 .await
895 });
896 }
897 Ok(generation)
898 });
899 tokio::pin!(work);
900 let generation = if let Some(window) = window {
901 tokio::select! {
902 result = &mut work => result?,
903 _ = tokio::time::sleep_until(window.deadline) => {
904 if window.expire() { return Err(GateError::commit_timeout()); }
905 work.await?
906 }
907 }
908 } else {
909 work.await?
910 };
911 let approval_runtime = exit_runtime.clone();
912 if let Some(approval) =
913 config_work(approval_runtime, ConfigWake::None, move |owner| {
914 owner.development_approval(generation)
915 })
916 .await?
917 {
918 self.publish_development_approval(&approval);
919 return Ok(ConfigControlResponse::Applied {
920 generation,
921 restart_required: false,
922 });
923 }
924 #[cfg(test)]
925 self.pause_before_apply_reconcile_for_test().await;
926 self.reconcile_authority_exit(exit_runtime.clone(), generation)
927 .await?;
928 let restart_required = self
929 .daemon_restart_required(&exit_runtime, generation)
930 .await?;
931 Ok(ConfigControlResponse::Applied {
932 generation,
933 restart_required,
934 })
935 }
936 request => {
937 let (kind, edits) = match request {
938 ConfigControlRequest::Plan {
939 base_generations,
940 edits,
941 } => {
942 if edits.is_none() && base_generations.is_some() {
943 return Err(GateError::new(
944 "invalid_params",
945 "base_generations requires edits",
946 ));
947 }
948 let edits = edits
949 .map(|edits| {
950 base_generations.map(|base| (base, edits)).ok_or_else(|| {
951 GateError::new(
952 "invalid_params",
953 "edits requires base_generations",
954 )
955 })
956 })
957 .transpose()?;
958 (PlanKind::Change, edits)
959 }
960 ConfigControlRequest::Stamp {} => (PlanKind::Stamp, None),
961 ConfigControlRequest::Unstamp {} => (PlanKind::Unstamp, None),
962 ConfigControlRequest::Rollback { generation } => {
963 (PlanKind::Rollback(generation), None)
964 }
965 _ => {
966 return Err(GateError::new(
967 "unsupported_control_frame",
968 "unknown configuration operation",
969 ))
970 }
971 };
972 let mut prepared = match edits {
973 Some((base, edits)) => runtime.prepare_control_edits(base, edits).await?,
974 None => {
975 let prepared = runtime.prepare_capture(kind).await?;
976 runtime.notify_delivery_changed();
978 prepared
979 }
980 };
981 if prepared.capture_refused() {
982 let view = config_work(runtime, ConfigWake::None, move |owner| {
983 owner.capture_refusal(&prepared)?.ok_or_else(|| {
984 GateError::new("module_review_invalid", "project refusal is absent")
985 })
986 })
987 .await?;
988 return Ok(ConfigControlResponse::Plan { view });
989 }
990 let mut fields = Vec::new();
991 let mut edit_refusals = Vec::new();
992 let mut unavailable_rereviews = Vec::new();
993 for (module, captured) in &prepared.candidate.modules {
994 if !prepared.review_modules.contains(module) {
995 continue;
996 }
997 let base = prepared.bases.get(module);
998 let reply = self
999 .review_config_tuple(&runtime, module, base, &captured.view)
1000 .await;
1001 let reply = match reply {
1002 Ok(reply) => reply,
1003 Err(_) if prepared.rereview_modules.contains(module) => {
1006 unavailable_rereviews.push(module.clone());
1007 continue;
1008 }
1009 Err(error) => return Err(error),
1010 };
1011 let reply: subc_protocol::config::ConfigReviewReply =
1012 serde_json::from_slice(&reply).map_err(|_| {
1013 GateError::new(
1014 "module_review_invalid",
1015 format!("{module}: malformed config.review reply"),
1016 )
1017 })?;
1018 if prepared.is_edit_plan() && !reply.refusals.is_empty() {
1019 let before = edit_refusals.len();
1020 for refusal in &reply.refusals {
1021 for path in refusal
1022 .paths
1023 .iter()
1024 .filter(|path| path.starts_with('/') && path.len() <= 1024)
1025 {
1026 edit_refusals.push(subc_control::config::ConfigPlanRefusal {
1027 module_id: module.clone(),
1028 path: path.clone(),
1029 code: "module_review_refused".into(),
1030 message: "the module refused this field".into(),
1031 project_id: None,
1032 workspace_id: None,
1033 });
1034 }
1035 }
1036 if edit_refusals.len() == before {
1037 edit_refusals.push(subc_control::config::ConfigPlanRefusal {
1038 module_id: module.clone(),
1039 path: String::new(),
1040 code: "module_review_refused".into(),
1041 message: "the module refused the edits".into(),
1042 project_id: None,
1043 workspace_id: None,
1044 });
1045 }
1046 fields.extend(prepared.refused_fields(module)?);
1047 continue;
1048 }
1049 fields.extend(crate::config_gate::review::checked_fields(
1050 module,
1051 &captured.schema,
1052 base,
1053 prepared.base_schemas.get(module),
1054 &captured.view,
1055 reply,
1056 )?);
1057 }
1058 for module in unavailable_rereviews {
1059 prepared.review_modules.remove(&module);
1060 prepared.rereview_modules.remove(&module);
1061 }
1062 let mut project_replies = Vec::new();
1063 for (tuple, review) in prepared.project_reviews() {
1064 let bytes = self
1065 .review_config_tuple(
1066 &runtime,
1067 &tuple.module,
1068 review.base.as_ref(),
1069 &review.approval.view,
1070 )
1071 .await?;
1072 let reply: subc_protocol::config::ConfigReviewReply =
1073 serde_json::from_slice(&bytes).map_err(|_| {
1074 GateError::new(
1075 "module_review_invalid",
1076 format!("{}: malformed project config.review reply", tuple.module),
1077 )
1078 })?;
1079 project_replies.push((tuple.clone(), reply));
1080 }
1081 for (tuple, reply) in project_replies {
1082 if prepared.is_edit_plan() && !reply.refusals.is_empty() {
1083 prepared.refuse_project_review(&tuple, &reply);
1084 } else {
1085 fields.extend(prepared.accept_project_review(&tuple, reply)?);
1086 }
1087 }
1088 if prepared.capture_refused() {
1089 let view = runtime
1090 .on_blocking(move |owner| {
1091 owner.capture_refusal(&prepared)?.ok_or_else(|| {
1092 GateError::new("module_review_invalid", "project refusal is absent")
1093 })
1094 })
1095 .await?;
1096 return Ok(ConfigControlResponse::Plan { view });
1097 }
1098 prepared.add_edit_refusals(edit_refusals);
1099 let view = config_work(runtime, ConfigWake::Delivery, move |owner| {
1100 owner.finish_plan(prepared, move |old, new| {
1101 let mut changeset = crate::config_gate::runtime::daemon_review(old, new)?;
1102 changeset.fields = fields;
1103 let mut effects: std::collections::BTreeMap<String,std::collections::BTreeMap<String,Vec<String>>> = Default::default();
1104 for field in changeset.fields.iter().filter(|field| field.project_id.is_none()) {
1105 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();
1106 effects.entry(field.module_id.clone()).or_default().entry(kind).or_default().push(field.path.clone());
1107 }
1108 if changeset.fields.iter().any(|field| field.project_id.is_none() && field.apply != subc_config::ApplyKind::Live) {
1109 changeset.apply_plan = serde_json::json!({"daemon_effects":changeset.apply_plan,"modules":effects});
1110 }
1111 Ok(changeset)
1112 })
1113 })
1114 .await?;
1115 Ok(match kind {
1116 PlanKind::Change => ConfigControlResponse::Plan { view },
1117 PlanKind::Stamp => ConfigControlResponse::Stamp { view },
1118 PlanKind::Unstamp => ConfigControlResponse::Unstamp { view },
1119 PlanKind::Rollback(_) => ConfigControlResponse::Rollback { view },
1120 })
1121 }
1122 }
1123 }
1124
1125 async fn review_config_tuple(
1126 &self,
1127 runtime: &Arc<crate::config_gate::runtime::RuntimeOwner>,
1128 module: &str,
1129 base: Option<&subc_protocol::config::ConfigView>,
1130 candidate: &subc_protocol::config::ConfigView,
1131 ) -> Result<Vec<u8>, GateError> {
1132 #[cfg(test)]
1133 if let Some(reply) = &self.config_review_test_reply {
1134 return serde_json::to_vec(reply).map_err(|_| {
1135 GateError::new(
1136 "module_review_invalid",
1137 "could not encode the fixture review",
1138 )
1139 });
1140 }
1141 let registration = self
1142 .registry
1143 .get_module(module)
1144 .map_err(|_| GateError::new("config_unavailable", "registry is unavailable"))?
1145 .ok_or_else(|| {
1146 GateError::new(
1147 "module_review_unavailable",
1148 format!("{module}: no active reviewer"),
1149 )
1150 })?;
1151 let admission = self.review_admission();
1152 let reviewer = registration.clone();
1153 config_work(runtime.clone(), ConfigWake::None, move |_| {
1154 admission.check(&reviewer)
1155 })
1156 .await?;
1157 if !registration
1158 .control_ops
1159 .iter()
1160 .any(|op| op == "config.review")
1161 {
1162 return Err(GateError::new(
1163 "module_review_unavailable",
1164 format!("{module}: config.review is not opted in"),
1165 ));
1166 }
1167 let request = subc_protocol::config::ConfigReviewRequest::new(
1168 base.map_or(0, |view| view.generation),
1169 candidate.layers.clone(),
1170 base.cloned(),
1171 );
1172 let bytes = serde_json::to_vec(&request).map_err(|_| {
1173 GateError::new("config_unavailable", "could not encode immutable review")
1174 })?;
1175 self.config_rpc(
1176 runtime,
1177 module,
1178 registration.connection_id,
1179 "config.review",
1180 bytes,
1181 )
1182 .await
1183 }
1184
1185 async fn config_approval_facts(&self, ctx: &RouteCtx) -> ApprovalFacts {
1186 let phone = self.config_phone_surface().await;
1187 self.config_approval_facts_with_phone(ctx, phone).await
1188 }
1189
1190 async fn config_approval_facts_with_phone(
1191 &self,
1192 ctx: &RouteCtx,
1193 phone: Option<crate::config_gate::PhoneSurface>,
1194 ) -> ApprovalFacts {
1195 let os_policy = crate::config_gate::os_prompt_policy_present();
1196 #[cfg(any(test, feature = "test-support"))]
1197 let os_policy = os_policy
1198 || self
1199 .config_runtime
1200 .as_ref()
1201 .is_some_and(|owner| owner.os_prompt_policy_for_tests());
1202 let desktop = self
1203 .config_desktop_identity(ctx.connection_id)
1204 .await
1205 .unwrap_or(false);
1206 ApprovalFacts {
1207 connection: ctx.connection_id.get(),
1208 owner_uid: self.config_owner_connection(ctx.connection_id),
1209 desktop_app: desktop,
1210 attested_operator_app: desktop && !cfg!(feature = "dev-desktop-approval"),
1211 os_prompt_available: config_os_prompt_available(
1212 self.forwarding.operator_confirms().config_gate_ready(),
1213 os_policy,
1214 ),
1215 phone,
1216 caller: self.resolve_caller(ctx.connection_id).await,
1217 }
1218 }
1219
1220 async fn config_phone_surface(&self) -> Option<crate::config_gate::PhoneSurface> {
1223 self.config_phone_surface_checked(true, None).await
1224 }
1225
1226 async fn config_phone_surface_snapshot(&self) -> Option<crate::config_gate::PhoneSurface> {
1227 self.config_phone_surface_checked(false, None).await
1228 }
1229
1230 async fn config_phone_surface_checked(
1231 &self,
1232 content: bool,
1233 publication: Option<&crate::config_gate::runtime::Published>,
1234 ) -> Option<crate::config_gate::PhoneSurface> {
1235 if self.config_runtime.as_ref().is_some_and(|owner| {
1236 publication.map_or_else(|| owner.is_recovering(), |view| view.is_recovering())
1237 }) {
1238 return None;
1239 }
1240 if !self.operator_app_policy.phone_enabled {
1241 return None;
1242 }
1243 let runtime = self.config_runtime.as_ref()?;
1244 let (_, registrations) = self.registry.list_modules_with_nonce_verification().ok()?;
1245 let (registration, verified) = registrations
1246 .into_iter()
1247 .find(|(registration, _)| registration.manifest.module_id == "callosum")?;
1248 if !verified
1249 || !registration.ready
1250 || !registration
1251 .control_ops
1252 .iter()
1253 .any(|op| op == subc_protocol::consent::CONSENT_V1)
1254 {
1255 return None;
1256 }
1257 let _spawn = self
1258 .supervisor
1259 .registration_spawn(registration.connection_id)?;
1260 if !self
1261 .forwarding
1262 .active_module_endpoint("callosum")
1263 .ok()
1264 .flatten()
1265 .is_some_and(|endpoint| endpoint.connection_id == registration.connection_id)
1266 {
1267 return None;
1268 }
1269 let module = self.supervisor.get("callosum")?;
1273 let status = module.status().ok()?;
1274 let (spec, _) = module.configuration().ok()?;
1275 if !self.supervisor.registration_snapshot_is_current_live(
1276 &self.registry,
1277 "callosum",
1278 registration.connection_id,
1279 None,
1280 ) || !spec.reserved
1281 || !status.enabled
1282 || !status.process_alive
1283 || !status.registration_active
1284 {
1285 return None;
1286 }
1287 let connection = registration.connection_id;
1288 let approved = if content {
1289 runtime
1290 .on_blocking(move |owner| owner.approved_phone_entry(connection))
1291 .await
1292 .ok()??
1293 } else {
1294 if let Some(snapshot) = publication {
1295 runtime.polled_phone_entry_from(snapshot, connection)?
1296 } else {
1297 runtime.polled_phone_entry(connection)?
1298 }
1299 };
1300 if !approved.enabled || approved.module_spec() != spec {
1301 return None;
1302 }
1303 if content {
1304 let supervisor = self.supervisor.clone();
1305 let registry = self.registry.clone();
1306 if !runtime
1307 .on_blocking(move |_| {
1308 Ok(supervisor
1309 .registration_is_current_live(®istry, "callosum", connection, None))
1310 })
1311 .await
1312 .ok()?
1313 {
1314 return None;
1315 }
1316 }
1317 if !self.supervisor.registration_snapshot_is_current_live(
1318 &self.registry,
1319 "callosum",
1320 registration.connection_id,
1321 None,
1322 ) {
1323 return None;
1324 }
1325 Some(crate::config_gate::PhoneSurface {
1326 module_id: "callosum".into(),
1327 connection: connection.get(),
1328 spawn_generation: status.spawn_generation,
1329 enabled_by_policy: true,
1330 opted_in: true,
1331 approved_declaration: true,
1332 reserved: true,
1333 channel_registered: true,
1334 program_admitted: true,
1335 active_registration: true,
1336 })
1337 }
1338
1339 async fn config_rpc(
1340 &self,
1341 runtime: &Arc<crate::config_gate::runtime::RuntimeOwner>,
1342 module: &str,
1343 expected_connection: ConnectionId,
1344 op: &str,
1345 bytes: Vec<u8>,
1346 ) -> std::result::Result<Vec<u8>, GateError> {
1347 let gate = runtime.module_gate(module)?;
1348 let pending = {
1349 let _gate = gate.lock().await;
1350 let registration = self
1351 .registry
1352 .get_module(module)
1353 .map_err(|_| GateError::new("config_unavailable", "registry unavailable"))?
1354 .ok_or_else(|| {
1355 GateError::new(
1356 "module_review_unavailable",
1357 format!("{module}: no active target"),
1358 )
1359 })?;
1360 let pending = self
1361 .forwarding
1362 .begin_module_control_rpc_for(module, op, Instant::now() + CONFIG_REVIEW_TIMEOUT)
1363 .map_err(|_| {
1364 GateError::new(
1365 "module_review_unavailable",
1366 format!("{module}: target unavailable"),
1367 )
1368 })?;
1369 if pending.endpoint.connection_id != registration.connection_id
1370 || registration.connection_id != expected_connection
1371 {
1372 let _ = self
1373 .forwarding
1374 .cancel_module_control_rpc(pending.endpoint, pending.corr);
1375 return Err(GateError::new(
1376 "not_delivery_target",
1377 "registry and forwarding targets differ",
1378 ));
1379 }
1380 pending
1381 };
1382 let PendingModuleControlRpc {
1383 endpoint,
1384 module_sink,
1385 negotiated_ver,
1386 corr,
1387 receiver,
1388 } = pending;
1389 let mut guard = ModuleControlRpcGuard::new(self.forwarding.clone(), endpoint, corr);
1390 let deadline = Instant::now() + CONFIG_REVIEW_TIMEOUT;
1391 let frame = Frame::build_with_version(
1392 negotiated_ver,
1393 FrameType::Request,
1394 control_flags(),
1395 0,
1396 0,
1397 corr,
1398 bytes,
1399 )
1400 .map_err(|_| GateError::new("config_unavailable", "could not encode config request"))?;
1401 timeout_at(deadline, module_sink.send(frame))
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 let outcome = timeout_at(deadline, receiver)
1416 .await
1417 .map_err(|_| {
1418 GateError::new(
1419 "config_review_timeout",
1420 format!("{module}: config.review exceeded its 30-second deadline; plan remains unapproved"),
1421 )
1422 })?
1423 .map_err(|_| {
1424 GateError::new(
1425 "module_review_unavailable",
1426 format!("{module}: target disconnected"),
1427 )
1428 })?;
1429 guard.disarm();
1430 match outcome {
1431 ModuleControlRpcOutcome::RawResponse(bytes) => Ok(bytes),
1432 ModuleControlRpcOutcome::DeadlineElapsed => Err(GateError::new("config_review_timeout",format!("{module}: config.review exceeded its 30-second deadline; plan remains unapproved"))),
1433 _ => Err(GateError::new(
1434 "module_review_unavailable",
1435 format!("{module}: config request was not answered"),
1436 )),
1437 }
1438 }
1439
1440 pub async fn confirm_config_gate_presence(
1443 &self,
1444 ctx: &RouteCtx,
1445 frame: &Frame,
1446 challenge: &ApprovalChallenge,
1447 ) -> PresenceDecision {
1448 let Some(text) = challenge.prompt() else {
1449 return PresenceDecision::Unavailable;
1450 };
1451 let caller = self.resolve_caller(ctx.connection_id).await;
1452 let key = crate::operator_confirm::DeclineKey::for_caller(&caller, ctx.connection_id);
1453 let outcome = self
1456 .forwarding
1457 .operator_confirms()
1458 .approve_config_gate(ctx, frame, text.to_owned(), caller.description(), key)
1459 .await;
1460 PresenceDecision::from_operator_outcome(&outcome)
1461 }
1462}
1463
1464fn config_os_prompt_available(provider_ready: bool, policy_present: bool) -> bool {
1465 provider_ready && policy_present
1466}
1467
1468enum ConfigWake {
1469 None,
1470 Delivery,
1471}
1472
1473async fn config_work<T: Send + 'static>(
1474 runtime: Arc<crate::config_gate::runtime::RuntimeOwner>,
1475 wake: ConfigWake,
1476 work: impl FnOnce(Arc<crate::config_gate::runtime::RuntimeOwner>) -> std::result::Result<T, GateError>
1477 + Send
1478 + 'static,
1479) -> std::result::Result<T, GateError> {
1480 runtime
1481 .on_blocking(move |owner| {
1482 let result = work(owner.clone());
1483 if matches!(wake, ConfigWake::Delivery) {
1484 owner.notify_delivery_changed();
1485 }
1486 result
1487 })
1488 .await
1489}
1490
1491pub(super) fn config_error_frame(frame: &Frame, error: GateError) -> Result<Frame, RouterError> {
1492 control_error_body_frame(
1493 frame,
1494 ErrorBody {
1495 code: error.code,
1496 message: error.detail,
1497 detail: None,
1498 },
1499 )
1500}
1501
1502pub(super) fn now_ms() -> u64 {
1503 std::time::SystemTime::now()
1504 .duration_since(std::time::UNIX_EPOCH)
1505 .unwrap_or_default()
1506 .as_millis()
1507 .min(u128::from(u64::MAX)) as u64
1508}
1509
1510#[cfg(test)]
1511mod tests;
1512
1513#[cfg(test)]
1514mod desktop_tests;