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