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 pending_settings;
9mod phone;
10mod recovery;
11mod route_policy;
12mod settings;
13mod widening;
14
15pub(super) const CONFIG_SETTINGS_SURFACE_ENABLED: bool = true;
17
18const CONFIG_REVIEW_TIMEOUT: Duration = Duration::from_secs(30);
20
21const CONFIG_APPROVAL_COMMIT_TIMEOUT: Duration = Duration::from_secs(30);
24use crate::config_gate::{
25 ApprovalChallenge, ApprovalFacts, ApprovalReply, GateError, PlanKind, PresenceDecision,
26};
27
28pub(super) fn is_config_op(op: &str) -> bool {
29 matches!(
30 op,
31 "config.status"
32 | "config.modules"
33 | "config.schema"
34 | "config.show"
35 | "config.watch"
36 | "config.plan"
37 | "config.plan_get"
38 | "config.plan_discard"
39 | "config.revert"
40 | "config.apply"
41 | "config.stamp"
42 | "config.unstamp"
43 | "config.history"
44 | "config.rollback"
45 | "config.place_program"
46 )
47}
48
49pub(super) fn is_module_config_op(op: &str) -> bool {
50 matches!(op, "config.declare" | "config.get" | "config.applied")
51}
52
53fn log_module_config_refused(
58 op: &str,
59 module_id: &str,
60 code: &str,
61 message: &str,
62 connection_id: ConnectionId,
63) {
64 warn!(
65 target: "control",
66 op,
67 module_id = ?module_id,
68 code,
69 message = ?message,
70 connection_id = connection_id.get(),
71 "module config op refused"
72 );
73}
74
75fn log_module_config_admitted(module_id: &str, active: bool, connection_id: ConnectionId) {
78 info!(
79 target: "control",
80 module_id = ?module_id,
81 active,
82 connection_id = connection_id.get(),
83 "module settings declaration admitted"
84 );
85}
86
87impl PrivilegedRequest for ConfigControlRequest {
88 fn privileged_operation(&self) -> Option<PrivilegedOperation<'_>> {
89 match self {
93 Self::Status {} => None,
94 Self::Plan { .. } => None,
95 Self::Apply { .. } => None,
96 Self::Stamp {} => None,
97 Self::Unstamp {} => None,
98 Self::History {} => None,
99 Self::Rollback { .. } => None,
100 Self::PlaceProgram { .. } => None,
101 _ => None,
102 }
103 }
104}
105
106impl ControlHandler {
107 #[cfg(feature = "test-support")]
108 pub(crate) fn with_config_os_prompt_policy_for_tests(self) -> Self {
109 if let Some(owner) = self.config_runtime.as_ref() {
110 owner.set_os_prompt_policy_for_tests();
111 }
112 self
113 }
114 fn config_delivery_target_current(
115 &self,
116 module: &str,
117 connection: ConnectionId,
118 active: bool,
119 correlation: u64,
120 ) -> Result<bool, RouterError> {
121 if active {
122 Ok(self
123 .registry
124 .get_module(module)
125 .map_err(|error| RouterError::backend(0, correlation, error.to_string()))?
126 .is_some_and(|target| target.connection_id == connection)
127 && self
128 .forwarding
129 .active_module_endpoint(module)
130 .map_err(RouterError::Forwarding)?
131 .is_some_and(|target| target.connection_id == connection))
132 } else {
133 Ok(self
134 .registry
135 .get_candidate(module)
136 .map_err(|error| RouterError::backend(0, correlation, error.to_string()))?
137 .is_some_and(|target| target.connection_id == connection))
138 }
139 }
140
141 pub(crate) fn defers_config_approval(&self, frame: &Frame) -> bool {
142 frame.header.channel == 0
143 && frame.header.ty == FrameType::Request
144 && matches!(
145 serde_json::from_slice::<ConfigControlRequest>(&frame.body),
146 Ok(ConfigControlRequest::Apply { .. })
147 )
148 }
149
150 pub(crate) fn reserve_config_approval(
151 &self,
152 ctx: &RouteCtx,
153 frame: &Frame,
154 ) -> std::result::Result<Option<crate::config_gate::runtime::ApprovalRequestGuard>, GateError>
155 {
156 if self.defers_config_approval(frame) {
157 if let Some(owner) = &self.config_runtime {
158 return owner
159 .reserve_approval_request(ctx.connection_id, frame.header.corr)
160 .map(Some);
161 }
162 }
163 Ok(None)
164 }
165
166 pub(super) fn cancel_config_approval(&self, caller: ConnectionId, correlation: u64) -> bool {
167 use crate::config_gate::runtime::CancelApprovalRequest;
168 let Some(owner) = &self.config_runtime else {
169 return false;
170 };
171 match owner.cancel_approval_request_outcome(caller, correlation) {
172 CancelApprovalRequest::Unknown => false,
173 CancelApprovalRequest::Withdrawn | CancelApprovalRequest::AlreadyReported => true,
174 CancelApprovalRequest::TooLate => {
175 if let Some(activity) = &self.activity {
176 activity.config_cancel_too_late(caller, correlation);
177 }
178 true
179 }
180 }
181 }
182
183 pub(super) async fn handle_module_config_request(
184 &self,
185 ctx: &RouteCtx,
186 frame: Frame,
187 op: &str,
188 ) -> Result<Vec<Frame>, RouterError> {
189 let Some(runtime) = self.config_runtime.clone() else {
190 log_module_config_refused(
191 op,
192 "unknown",
193 "config_gate_inactive",
194 "no config store configured",
195 ctx.connection_id,
196 );
197 return Ok(vec![control_error_frame(
198 &frame,
199 "config_gate_inactive",
200 "no config store configured",
201 )?]);
202 };
203 let registration = self
204 .registry
205 .get_module_by_connection(ctx.connection_id)
206 .map_err(|error| RouterError::backend(0, frame.header.corr, error.to_string()))?;
207 let Some(registration) = registration else {
208 log_module_config_refused(
209 op,
210 "unknown",
211 "not_registered",
212 "module config operations require a registered connection",
213 ctx.connection_id,
214 );
215 return Ok(vec![control_error_frame(
216 &frame,
217 "not_registered",
218 "module config operations require a registered connection",
219 )?]);
220 };
221 let module = registration.manifest.module_id.clone();
222 let gate = runtime
223 .module_gate(&module)
224 .map_err(|e| RouterError::backend(0, frame.header.corr, e.to_string()))?;
225 let mut module_guard = Some(gate.lock().await);
226 let active = self
227 .registry
228 .get_module(&module)
229 .map_err(|error| RouterError::backend(0, frame.header.corr, error.to_string()))?
230 .is_some_and(|r| r.connection_id == ctx.connection_id)
231 && self
232 .forwarding
233 .active_module_endpoint(&module)
234 .map_err(RouterError::Forwarding)?
235 .is_some_and(|target| target.connection_id == ctx.connection_id);
236 let candidate = self
237 .registry
238 .get_candidate(&module)
239 .map_err(|error| RouterError::backend(0, frame.header.corr, error.to_string()))?
240 .is_some_and(|r| r.connection_id == ctx.connection_id);
241 if !active && !candidate {
242 log_module_config_refused(
243 op,
244 &module,
245 "not_delivery_target",
246 "connection is no longer the active or candidate delivery target",
247 ctx.connection_id,
248 );
249 return Ok(vec![control_error_frame(
250 &frame,
251 "not_delivery_target",
252 "connection is no longer the active or candidate delivery target",
253 )?]);
254 }
255 let body = frame.body.clone();
256 let connection = ctx.connection_id;
257 let mut delivered_view = None;
258 let result = match op {
259 "config.declare" => {
260 let declaration = serde_json::from_slice(&body).map_err(|_| {
261 GateError::new("invalid_control_body", "malformed config.declare request")
262 });
263 match declaration {
264 Ok(declaration) => {
265 config_work(runtime.clone(), ConfigWake::None, move |owner| {
266 owner.declare(connection, &module, declaration, active)?;
267 Ok(serde_json::json!({"op":"config.declare"}))
268 })
269 .await
270 }
271 Err(error) => Err(error),
272 }
273 }
274 "config.get" => {
275 let request =
276 serde_json::from_slice::<subc_protocol::config::ConfigGetRequest>(&body)
277 .map_err(|_| {
278 GateError::new("invalid_control_body", "malformed config.get request")
279 });
280 match request {
281 Ok(request) => {
282 let module_id = module.clone();
283 let get = async {
284 if runtime.project_settings_enabled() && request.project_id.is_some() {
285 let request = request.clone();
286 let module = module_id.clone();
287 let read = runtime
288 .on_blocking(move |owner| {
289 owner.begin_unstamped_project_get(
290 connection, module, request,
291 )
292 })
293 .await?;
294 if let Some(read) = read {
295 drop(module_guard.take());
297 let reply = runtime.read_unstamped_project(read).await?;
298 module_guard = Some(gate.lock().await);
299 return Ok(reply);
300 }
301 }
302 config_work(runtime.clone(), ConfigWake::None, move |owner| {
303 owner.module_get_for_rpc(connection, &module_id, request)
304 })
305 .await
306 };
307 match get.await {
308 Ok(reply) => {
309 let encoded = serde_json::to_value(&reply).map_err(|_| {
310 GateError::new(
311 "config_unavailable",
312 "could not encode config view",
313 )
314 });
315 delivered_view = Some(reply);
316 encoded
317 }
318 Err(error) => Err(error),
319 }
320 }
321 Err(error) => Err(error),
322 }
323 }
324 "config.applied" => {
325 match serde_json::from_slice::<subc_protocol::config::ConfigAppliedRequest>(&body) {
326 Ok(request) => {
327 config_work(runtime.clone(), ConfigWake::Delivery, move |owner| {
328 owner.module_applied(connection, &module, request)?;
329 Ok(serde_json::json!({"op":"config.applied"}))
330 })
331 .await
332 }
333 Err(_) => Err(GateError::new(
334 "invalid_control_body",
335 "malformed config.applied request",
336 )),
337 }
338 }
339 _ => Err(GateError::new(
340 "invalid_control_body",
341 "unsupported module configuration operation",
342 )),
343 };
344 match result {
345 Ok(response) => {
346 if op == "config.declare" {
347 log_module_config_admitted(
348 ®istration.manifest.module_id,
349 active,
350 connection,
351 );
352 }
353 let response =
354 control_response_body_frame(&frame, &response, "module config response")?;
355 if let Some(view) = delivered_view {
356 use crate::config_gate::runtime::delivery::CONFIG_LIVE_ACK_TIMEOUT;
357 let project = view
358 .pending
359 .as_ref()
360 .or(view.active.as_ref())
361 .and_then(|view| view.project_id.clone());
362 let selected = view
363 .pending
364 .as_ref()
365 .or(view
366 .active
367 .as_ref()
368 .filter(|_| view.declaration_pending.is_some()))
369 .and_then(|view| view.attempt.map(|attempt| (view.generation, attempt)));
370 let writing_project = project.clone();
371 let window = runtime
372 .on_blocking(move |owner| {
373 if active {
374 if let Some((generation, attempt)) = selected {
375 owner.delivery_write_started_for(
376 connection,
377 writing_project.as_deref(),
378 generation,
379 attempt,
380 tokio::time::Instant::now(),
381 )?;
382 }
383 }
384 owner.delivery_window_for(connection, writing_project.as_deref())
385 })
386 .await
387 .map_err(|error| {
388 RouterError::backend(0, frame.header.corr, error.to_string())
389 })?;
390 let write_deadline = window
391 .filter(|window| selected == Some((window.generation, window.attempt)))
392 .and_then(|window| window.deadline)
393 .map_or(
394 tokio::time::Instant::now() + CONFIG_LIVE_ACK_TIMEOUT,
395 |deadline| {
396 deadline.min(tokio::time::Instant::now() + CONFIG_LIVE_ACK_TIMEOUT)
397 },
398 );
399 if view.active.as_ref().is_some_and(|view| {
400 view.project_id.is_some()
401 && view.status == subc_protocol::config::ConfigStatus::Unstamped
402 }) && !self.config_delivery_target_current(
403 ®istration.manifest.module_id,
404 connection,
405 active,
406 frame.header.corr,
407 )? {
408 return Ok(vec![]);
409 }
410 drop(module_guard.take());
411 let flushed =
412 tokio::time::timeout_at(write_deadline, ctx.egress.send_flushed(response))
413 .await;
414 let flushed_at = tokio::time::Instant::now();
415 let _gate = gate.lock().await;
416 let current_project = project.clone();
417 let current_window = runtime
418 .on_blocking(move |owner| {
419 owner.delivery_window_for(connection, current_project.as_deref())
420 })
421 .await
422 .ok()
423 .flatten();
424 if !self.config_delivery_target_current(
427 ®istration.manifest.module_id,
428 connection,
429 active,
430 frame.header.corr,
431 )? || selected.is_some_and(|selected| {
432 current_window
433 .is_none_or(|window| selected != (window.generation, window.attempt))
434 }) {
435 return Ok(vec![]);
436 }
437 match flushed {
438 Ok(Ok(())) => {}
439 failed => {
440 if active {
441 if let Some((generation, attempt)) = selected {
442 let module = registration.manifest.module_id.clone();
443 let _ = config_work(
444 runtime.clone(),
445 ConfigWake::Delivery,
446 move |owner| {
447 owner.delivery_timeout_for(
448 connection, &module, project, generation, attempt,
449 )
450 },
451 )
452 .await;
453 }
454 }
455 return match failed {
456 Ok(Err(error)) => Err(error),
457 _ => Ok(vec![]),
458 };
459 }
460 }
461 let module = registration.manifest.module_id.clone();
462 let delivered = config_work(runtime.clone(), ConfigWake::None, move |owner| {
463 owner.module_view_delivered(connection, &module, &view, flushed_at, active)
464 })
465 .await;
466 if let Err(error) = delivered {
467 if matches!(
468 error.code.as_str(),
469 "delivery_superseded" | "not_delivery_target"
470 ) {
471 return Ok(vec![]);
472 }
473 if error.code == "delivery_expired" {
474 if active {
475 if let Some((generation, attempt)) = selected {
476 let module = registration.manifest.module_id.clone();
477 let _ = config_work(
478 runtime.clone(),
479 ConfigWake::Delivery,
480 move |owner| {
481 owner.delivery_timeout_for(
482 connection, &module, project, generation, attempt,
483 )
484 },
485 )
486 .await;
487 }
488 }
489 } else {
490 return Err(RouterError::backend(
491 0,
492 frame.header.corr,
493 error.to_string(),
494 ));
495 }
496 }
497 Ok(vec![])
498 } else {
499 Ok(vec![response])
500 }
501 }
502 Err(error) => {
503 if error.code == "anchor_pending" {
504 let _ = config_work(runtime.clone(), ConfigWake::Delivery, move |owner| {
505 owner.anchor_pending_served(connection)
506 })
507 .await;
508 }
509 if error.code != "anchor_pending" {
511 log_module_config_refused(
512 op,
513 ®istration.manifest.module_id,
514 &error.code,
515 &error.detail,
516 connection,
517 );
518 }
519 Ok(vec![
520 self.config_request_error_frame(&frame, op, true, error)?
521 ])
522 }
523 }
524 }
525 pub(super) fn capabilities_with_settings(&self) -> Vec<String> {
526 let mut capabilities = self.subc_capabilities.to_vec();
527 if CONFIG_SETTINGS_SURFACE_ENABLED {
528 if let Some(owner) = &self.config_runtime {
529 capabilities.push(subc_control::config::CONFIG_SETTINGS_CAPABILITY.to_owned());
530 if owner.project_settings_enabled() {
531 capabilities
532 .push(subc_control::config::CONFIG_SETTINGS_PROJECTS_CAPABILITY.to_owned());
533 }
534 }
535 }
536 capabilities
537 }
538
539 pub fn with_config_runtime(
540 mut self,
541 runtime: Arc<crate::config_gate::runtime::RuntimeOwner>,
542 ) -> Self {
543 self.supervisor.install_binding_retirement(&runtime);
544 let _ = runtime.set_activity(self.activity.clone());
545 runtime.install_module_route_authority(Arc::new(route_policy::ModuleRouteAuthority(
546 self.clone(),
547 Arc::downgrade(&runtime),
548 )));
549 runtime.install_mark_publisher(Arc::new(caller_attestation::ControlMarkPublisher(
550 self.clone(),
551 )));
552 self.config_runtime = Some(runtime);
553 self
554 }
555
556 pub(crate) fn with_explicit_config_store(
558 self,
559 runtime: Arc<crate::config_gate::runtime::RuntimeOwner>,
560 ) -> Self {
561 let mut handler = self.with_config_runtime(runtime);
562 let capability = subc_protocol::config::CONFIG_GATE_CAPABILITY;
563 if !handler
564 .subc_capabilities
565 .iter()
566 .any(|present| present == capability)
567 {
568 let mut capabilities = handler.subc_capabilities.to_vec();
569 capabilities.push(capability.to_owned());
570 handler.subc_capabilities = capabilities.into();
571 }
572 handler
573 }
574
575 async fn config_desktop_identity(
576 &self,
577 connection: ConnectionId,
578 ) -> std::result::Result<bool, GateError> {
579 if !self.config_owner_connection(connection) {
580 return Ok(false);
581 }
582 #[cfg(test)]
583 if self
584 .config_runtime
585 .as_ref()
586 .is_some_and(|owner| owner.has_trusted_review_connection_for_test(connection))
587 {
588 return Ok(true);
589 }
590 #[cfg(feature = "dev-desktop-approval")]
591 {
592 Ok(self
595 .local_connections
596 .lock()
597 .unwrap_or_else(|p| p.into_inner())
598 .contains(&connection))
599 }
600 #[cfg(not(feature = "dev-desktop-approval"))]
601 {
602 Ok(self.has_current_config_desktop_stamp(connection).await)
603 }
604 }
605
606 pub(crate) fn config_desktop_review_request(&self, request: &Frame) -> bool {
607 self.config_runtime.is_some()
608 && request.header.ty == FrameType::Request
609 && serde_json::from_slice::<ControlOpProbe>(&request.body).is_ok_and(|probe| {
610 matches!(
611 probe.op.as_str(),
612 "config.plan" | "config.stamp" | "config.unstamp" | "config.rollback"
613 )
614 })
615 }
616
617 pub(crate) async fn config_desktop_review_response(
618 &self,
619 connection: ConnectionId,
620 response: &Frame,
621 ) -> Option<subc_control::config::ConfigPlanView> {
622 if self.config_runtime.is_none() || response.header.ty != FrameType::Response {
623 return None;
624 }
625 let probe: ControlOpProbe = serde_json::from_slice(&response.body).ok()?;
626 if !matches!(
627 probe.op.as_str(),
628 "config.plan"
629 | "config.plan_get"
630 | "config.stamp"
631 | "config.unstamp"
632 | "config.rollback"
633 ) || !matches!(self.config_desktop_identity(connection).await, Ok(true))
634 {
635 return None;
636 }
637 match serde_json::from_slice::<ConfigControlResponse>(&response.body).ok()? {
638 ConfigControlResponse::Plan { view }
639 | ConfigControlResponse::PlanGet { view }
640 | ConfigControlResponse::Stamp { view }
641 | ConfigControlResponse::Unstamp { view }
642 | ConfigControlResponse::Rollback { view } => Some(view),
643 _ => None,
644 }
645 }
646
647 pub(crate) async fn config_desktop_review_delivered(
648 &self,
649 connection: ConnectionId,
650 view: subc_control::config::ConfigPlanView,
651 ) {
652 if !matches!(self.config_desktop_identity(connection).await, Ok(true)) {
653 return;
654 }
655 let Some(runtime) = self.config_runtime.clone() else {
656 return;
657 };
658 let peers = self.captured_peers.clone();
659 let _ = config_work(runtime, ConfigWake::Delivery, move |owner| {
660 owner.desktop_view_delivered_when(connection, &view, || {
661 peers
662 .lock()
663 .unwrap_or_else(|p| p.into_inner())
664 .contains_key(&connection)
665 })
666 })
667 .await;
668 }
669
670 pub(crate) async fn deliver_config_desktop_review(
671 &self,
672 ctx: &RouteCtx,
673 response: Frame,
674 view: subc_control::config::ConfigPlanView,
675 ) -> Result<(), RouterError> {
676 ctx.egress.send_flushed(response).await?;
677 self.config_desktop_review_delivered(ctx.connection_id, view)
678 .await;
679 Ok(())
680 }
681
682 pub fn with_config_review_admission(
683 mut self,
684 admission: Arc<dyn crate::config_gate::ReviewAdmission>,
685 ) -> Self {
686 self.config_review_admission = admission;
687 self.config_review_admission_is_default = false;
688 self
689 }
690
691 pub(super) fn review_admission(&self) -> Arc<dyn crate::config_gate::ReviewAdmission> {
692 if self.config_runtime.is_some() && self.config_review_admission_is_default {
693 Arc::new(admission::SupervisedReviewAdmission(self.clone()))
694 } else {
695 self.config_review_admission.clone()
696 }
697 }
698
699 pub(super) async fn handle_config_gate_request(
702 &self,
703 ctx: &RouteCtx,
704 frame: Frame,
705 op: &str,
706 ) -> Result<Vec<Frame>, RouterError> {
707 let request = match serde_json::from_slice::<ConfigControlRequest>(&frame.body) {
708 Ok(request) => request,
709 Err(error) => {
710 return Ok(vec![control_error_frame(
711 &frame,
712 "invalid_control_body",
713 format!("malformed config control body: {error}"),
714 )?])
715 }
716 };
717 debug_assert!(privileged_operation(&request).is_none());
718 let Some(runtime) = self.config_runtime.clone() else {
719 return Ok(vec![control_error_frame(
720 &frame,
721 "config_gate_inactive",
722 "no config store configured",
723 )?]);
724 };
725 if !self.config_owner_connection(ctx.connection_id) {
726 return Ok(vec![control_error_frame(
727 &frame,
728 "owner_required",
729 "configuration control requires a kernel-observed owner-user connection",
730 )?]);
731 }
732 if let ConfigControlRequest::Watch { modules, projects } = request {
733 let projects = projects == Some(true) && runtime.project_settings_enabled();
734 return self
735 .handle_config_settings_watch(ctx, frame, runtime, modules, projects)
736 .await;
737 }
738 let result = self
739 .execute_config_request(ctx, &frame, runtime, request)
740 .await;
741 match result {
742 Ok(response) => Ok(vec![control_response_body_frame(
743 &frame,
744 &response,
745 "ConfigControlResponse",
746 )?]),
747 Err(error) if error.code == subc_control::upgrade_in_place::UPGRADE_BUSY => {
748 Ok(vec![control_error_body_frame(
749 &frame,
750 ErrorBody::new(error.code, error.detail)
751 .with_detail(serde_json::json!({"reason":"upgrade"})),
752 )?])
753 }
754 Err(error) => Ok(vec![
755 self.config_request_error_frame(&frame, op, false, error)?
756 ]),
757 }
758 }
759
760 pub(super) fn config_owner_connection(&self, connection: ConnectionId) -> bool {
761 let peers = self
762 .observed_peers
763 .lock()
764 .unwrap_or_else(|p| p.into_inner());
765 let Some(peer) = peers.get(&connection) else {
766 return false;
767 };
768 #[cfg(unix)]
769 {
770 peer.uid == Some(subc_os::effective_uid())
771 }
772 #[cfg(windows)]
773 {
774 subc_os::named_pipe::current_user_sid_string()
775 .ok()
776 .as_ref()
777 .is_some_and(|sid| peer.sid.as_ref() == Some(sid))
778 }
779 #[cfg(not(any(unix, windows)))]
780 {
781 let _ = peer;
782 false
783 }
784 }
785
786 async fn execute_config_request(
787 &self,
788 ctx: &RouteCtx,
789 frame: &Frame,
790 runtime: Arc<crate::config_gate::runtime::RuntimeOwner>,
791 request: ConfigControlRequest,
792 ) -> std::result::Result<ConfigControlResponse, GateError> {
793 Box::pin(self.execute_config_request_from(ctx, frame, runtime, request, None)).await
794 }
795
796 async fn execute_config_request_from(
797 &self,
798 ctx: &RouteCtx,
799 frame: &Frame,
800 runtime: Arc<crate::config_gate::runtime::RuntimeOwner>,
801 request: ConfigControlRequest,
802 automatic: Option<pending_settings::AutomaticSettingsAttempt>,
803 ) -> std::result::Result<ConfigControlResponse, GateError> {
804 let settings = if matches!(
805 request,
806 ConfigControlRequest::Apply { .. } | ConfigControlRequest::PlaceProgram { .. }
807 ) {
808 self.upgrade_settings_guard()
809 .map_err(|body| GateError::new(&body.code, body.message))?
810 .map(Arc::new)
811 } else {
812 None
813 };
814 match request {
815 ConfigControlRequest::Modules {} => {
816 let known = self.config_settings_known_modules()?;
817 config_work(runtime, ConfigWake::None, move |owner| {
818 owner.settings_modules(known)
819 })
820 .await
821 }
822 ConfigControlRequest::Schema { module_id } => {
823 let known = self.config_settings_known_modules()?;
824 config_work(runtime, ConfigWake::None, move |owner| {
825 owner.settings_schema(known, module_id)
826 })
827 .await
828 }
829 ConfigControlRequest::Show {
830 module_id,
831 project_id,
832 through,
833 } => {
834 let known = self.config_settings_known_modules()?;
835 if let Some(project) = project_id {
836 return runtime
837 .settings_show_project(known, module_id, project, through)
838 .await;
839 }
840 config_work(runtime, ConfigWake::None, move |owner| {
841 owner.settings_show(known, module_id, through)
842 })
843 .await
844 }
845 ConfigControlRequest::PlanGet { digest } => {
846 let view = config_work(runtime, ConfigWake::None, move |owner| {
847 owner.plan_get(&digest)
848 })
849 .await?;
850 Ok(ConfigControlResponse::PlanGet { view })
851 }
852 ConfigControlRequest::PlanDiscard { digest } => {
853 config_work(runtime, ConfigWake::Delivery, move |owner| {
854 owner.plan_discard(&digest)
855 })
856 .await?;
857 Ok(ConfigControlResponse::PlanDiscard {})
858 }
859 ConfigControlRequest::Revert { digest } => {
860 let files = self.revert_config_plan(&runtime, digest).await?;
861 Ok(ConfigControlResponse::Revert { files })
862 }
863 ConfigControlRequest::PlaceProgram {
864 module_id,
865 path,
866 sha256,
867 manifest,
868 } => {
869 let gate = runtime.module_gate(&module_id)?;
870 let _guard = gate.lock().await;
871 let generation = config_work(runtime, ConfigWake::Delivery, move |owner| {
872 let _settings = settings;
873 owner.place_program_with_manifest(&module_id, &path, &sha256, manifest.as_ref())
874 })
875 .await?;
876 Ok(ConfigControlResponse::ProgramPlaced { generation })
877 }
878 ConfigControlRequest::Status {} => {
879 let snapshot = runtime.observed_snapshot()?;
880 let mut status = runtime.polled_status_from(snapshot.clone()).await?;
881 let phone = self
882 .config_phone_surface_checked(false, Some(&snapshot))
883 .await;
884 let facts = self.config_approval_facts_with_phone(ctx, phone).await;
885 status
886 .missing_approval_surfaces
887 .extend(crate::config_gate::missing_surfaces(
888 &facts,
889 matches!(status.state.as_str(), "store_missing" | "store_unverified"),
890 ));
891 self.report_daemon_configuration(&snapshot.approved_daemon, &mut status)
892 .await?;
893 if let Some(problem) = runtime
894 .on_blocking(move |owner| {
895 Ok(owner.policy_root_problem(&snapshot.approved_daemon))
896 })
897 .await?
898 {
899 status.warnings.push(problem);
900 }
901 Ok(ConfigControlResponse::Status { status })
902 }
903 ConfigControlRequest::History {} => {
904 let (generations, pruned) =
905 config_work(runtime, ConfigWake::None, |owner| owner.history()).await?;
906 Ok(ConfigControlResponse::History {
907 generations,
908 pruned,
909 })
910 }
911 ConfigControlRequest::Apply { digest } => {
912 let daemon_settings = automatic.is_some();
913 let order = automatic.as_ref().map_or_else(
914 || runtime.next_settings_request_order(),
915 |attempt| attempt.token,
916 );
917 if let Some(result) = self
918 .apply_unstamped_policy_root(ctx, frame, &runtime, &digest)
919 .await?
920 {
921 return Ok(result);
922 }
923 let apply_digest = digest.clone();
924 if let Some(generation) = runtime
925 .apply_control_edits(apply_digest, settings.clone())
926 .await?
927 {
928 return Ok(ConfigControlResponse::Applied {
929 generation,
930 restart_required: false,
931 });
932 }
933 let connection = ctx.connection_id;
934 let corr = frame.header.corr;
935 #[cfg(all(test, unix))]
936 runtime.pause_approval_claim_for_test().await;
937 let request_guard = runtime.claim_approval_request(connection, corr)?;
938 if self.rescan.is_none() {
939 return Err(GateError::new(
940 "supervisor_reconcile_unavailable",
941 "configuration commit requires the supervisor owner",
942 ));
943 }
944 let phone = self.config_phone_surface().await;
945 let facts = self.config_apply_facts(ctx, phone, daemon_settings).await;
946 let cancellation = request_guard.request.clone();
947 let (challenge, attempt_guard) =
948 config_work(runtime.clone(), ConfigWake::Delivery, move |owner| {
949 let challenge = owner.begin_settings_apply_for_request(
950 &digest,
951 &facts,
952 &cancellation,
953 order,
954 )?;
955 let guard = phone::ApprovalAttemptGuard::new(&owner, challenge.attempt());
958 owner.track_reserved_approval_request(
959 challenge.attempt(),
960 connection,
961 corr,
962 &cancellation,
963 )?;
964 Ok((challenge, guard))
965 })
966 .await?;
967 request_guard.request.ensure_live()?;
968 let feedback = automatic.and_then(|attempt| attempt.feedback);
969 if let Some(feedback) = &feedback {
970 let _ = feedback.send(pending_settings::CardFeedback::Filed);
971 }
972 let reply = match &challenge {
973 ApprovalChallenge::Desktop { .. } | ApprovalChallenge::OsPrompt { .. } => {
974 let attempt = challenge.attempt();
975 tokio::select! {
976 biased;
977 _ = runtime.wait_settings_attempt_replaced(attempt) => {
978 return Err(GateError::new("approval_surface_unavailable", "a newer settings approval took precedence"));
979 }
980 decision = async {
981 let _delivery = runtime.settings_phone_delivery.lock().await;
982 runtime.await_all_phone_withdrawals().await;
983 if !runtime.on_blocking(move |owner| owner.settings_attempt_active(attempt)).await? {
984 return Err(GateError::new("approval_surface_unavailable", "a newer settings approval took precedence"));
985 }
986 Ok(self.confirm_config_gate_presence(ctx, frame, &challenge).await)
987 } => ApprovalReply::Presence(decision?),
988 }
989 }
990 ApprovalChallenge::Phone {
991 attempt,
992 connection,
993 deadline,
994 request,
995 } => {
996 let _delivery = timeout_at(*deadline, async {
999 let guard = runtime.settings_phone_delivery.lock().await;
1000 runtime
1001 .await_phone_withdrawal(ConnectionId::new(*connection))
1002 .await;
1003 guard
1004 })
1005 .await
1006 .map_err(|_| {
1007 GateError::new(
1008 "approval_surface_unavailable",
1009 "the phone could not receive the settings card",
1010 )
1011 })?;
1012 let exchange = self
1013 .config_phone_rpc(
1014 &runtime,
1015 *attempt,
1016 ConnectionId::new(*connection),
1017 *deadline,
1018 request,
1019 )
1020 .await;
1021 if daemon_settings
1022 && Instant::now() >= *deadline
1023 && !matches!(
1024 &exchange,
1025 Ok(ApprovalReply::Phone {
1026 response: Some(_),
1027 ..
1028 })
1029 )
1030 {
1031 return Err(GateError::new(
1032 "settings_card_expired",
1033 "the settings card expired",
1034 ));
1035 }
1036 exchange?
1037 }
1038 };
1039 let attempt = challenge.attempt();
1040 if daemon_settings {
1041 let phone = self.config_phone_surface().await;
1042 let facts = self.config_apply_facts(ctx, phone, true).await;
1043 let operation = self.supervisor.operation_lock();
1044 let restore_settings = settings.clone();
1045 let declined = config_work(runtime.clone(), ConfigWake::None, move |owner| {
1046 let declined = owner.accept_settings_decline(attempt, &facts, &reply)?;
1047 let restore = declined.map(|digest| {
1050 let owner = owner.clone();
1051 tokio::spawn(async move {
1052 let _settings = restore_settings;
1053 let _operation = operation.lock_owned().await;
1054 let result = owner.revert_capture_plan(digest).await;
1055 if let Err(error) = &result {
1056 tracing::warn!(code = %error.code, detail = %error.detail, "declined settings could not be restored");
1057 }
1058 result
1059 })
1060 });
1061 #[cfg(test)]
1062 if restore.is_some() {
1063 owner.after_settings_decline_for_test();
1064 }
1065 Ok((restore, reply))
1066 })
1067 .await?;
1068 if let Some(restore) = declined.0 {
1069 if let Err(mut error) = restore
1070 .await
1071 .map_err(|error| GateError::new("config_unavailable", error))?
1072 {
1073 if error.code != "settings_keep_limit" {
1074 error.code = "settings_card_decline_unrestored".into();
1075 }
1076 return Err(error);
1077 }
1078 return Err(GateError::new(
1079 "settings_card_declined",
1080 "approval was declined",
1081 ));
1082 }
1083 Box::pin(self.finish_config_apply(
1085 ctx,
1086 runtime,
1087 challenge,
1088 attempt_guard,
1089 request_guard,
1090 declined.1,
1091 true,
1092 settings,
1093 ))
1094 .await
1095 } else {
1096 Box::pin(self.finish_config_apply(
1097 ctx,
1098 runtime,
1099 challenge,
1100 attempt_guard,
1101 request_guard,
1102 reply,
1103 false,
1104 settings,
1105 ))
1106 .await
1107 }
1108 }
1109 request => self.execute_config_plan(runtime, request).await,
1110 }
1111 }
1112
1113 #[allow(clippy::too_many_arguments)]
1114 async fn finish_config_apply(
1115 &self,
1116 ctx: &RouteCtx,
1117 runtime: Arc<crate::config_gate::runtime::RuntimeOwner>,
1118 challenge: ApprovalChallenge,
1119 mut attempt_guard: phone::ApprovalAttemptGuard,
1120 request_guard: crate::config_gate::runtime::ApprovalRequestGuard,
1121 reply: ApprovalReply,
1122 daemon_settings: bool,
1123 settings: Option<super::upgrade_in_place::SettingsPermit>,
1124 ) -> std::result::Result<ConfigControlResponse, GateError> {
1125 let attempt = challenge.attempt();
1126 let window = matches!(challenge, ApprovalChallenge::Phone { .. }).then(|| {
1127 Arc::new(crate::config_gate::runtime::ApprovalCommitWindow::new(
1128 Instant::now() + CONFIG_APPROVAL_COMMIT_TIMEOUT,
1129 ))
1130 });
1131 attempt_guard.commit_window = window.clone();
1132 let checked_phone = self.config_phone_surface().await;
1133 let locks = async {
1134 let project_apply = runtime.recheck_capture_apply(attempt).await?;
1138 let operation = self.supervisor.operation_lock().lock_owned().await;
1139 let module_gates = runtime.approval_commit_gates(attempt).await?;
1140 let current_phone = self.config_phone_surface_snapshot().await;
1141 let phone = checked_phone.filter(|phone| Some(phone) == current_phone.as_ref());
1142 let facts = self.config_apply_facts(ctx, phone, daemon_settings).await;
1143 Ok::<_, GateError>((operation, module_gates, facts, project_apply))
1144 };
1145 let (operation, module_gates, facts, project_apply) = if let Some(window) = &window {
1146 timeout_at(window.deadline, locks)
1147 .await
1148 .map_err(|_| GateError::commit_timeout())??
1149 } else {
1150 locks.await?
1151 };
1152 let now = now_ms();
1153 let publish_window = window.clone();
1154 let publication_request = request_guard.request.clone();
1155 let exit_runtime = runtime.clone();
1156 let work = config_work(runtime, ConfigWake::Delivery, move |owner| {
1157 let _owned_gates = (operation, module_gates);
1158 let write_authority = project_apply.clone();
1159 let generation = owner.finish_approval_with_commit_window(
1160 attempt,
1161 &facts,
1162 reply,
1163 now,
1164 publish_window,
1165 publication_request,
1166 project_apply,
1167 )?;
1168 if let Some(authority) = write_authority {
1169 tokio::spawn(async move {
1172 owner
1173 .write_approved_project_files(generation, authority, settings)
1174 .await
1175 });
1176 }
1177 Ok(generation)
1178 });
1179 tokio::pin!(work);
1180 let generation = if let Some(window) = window {
1181 tokio::select! {
1182 result = &mut work => result?,
1183 _ = tokio::time::sleep_until(window.deadline) => {
1184 if window.expire() { return Err(GateError::commit_timeout()); }
1185 work.await?
1186 }
1187 }
1188 } else {
1189 work.await?
1190 };
1191 let approval_runtime = exit_runtime.clone();
1192 if let Some(approval) = config_work(approval_runtime, ConfigWake::None, move |owner| {
1193 owner.development_approval(generation)
1194 })
1195 .await?
1196 {
1197 self.publish_development_approval(&approval);
1198 return Ok(ConfigControlResponse::Applied {
1199 generation,
1200 restart_required: false,
1201 });
1202 }
1203 #[cfg(test)]
1204 self.pause_before_apply_reconcile_for_test().await;
1205 self.reconcile_authority_exit(exit_runtime.clone(), generation)
1206 .await?;
1207 let restart_required = self
1208 .daemon_restart_required(&exit_runtime, generation)
1209 .await?;
1210 Ok(ConfigControlResponse::Applied {
1211 generation,
1212 restart_required,
1213 })
1214 }
1215
1216 async fn execute_config_plan(
1217 &self,
1218 runtime: Arc<crate::config_gate::runtime::RuntimeOwner>,
1219 request: ConfigControlRequest,
1220 ) -> std::result::Result<ConfigControlResponse, GateError> {
1221 let (kind, edits) = match request {
1222 ConfigControlRequest::Plan {
1223 base_generations,
1224 edits,
1225 } => {
1226 if edits.is_none() && base_generations.is_some() {
1227 return Err(GateError::new(
1228 "invalid_params",
1229 "base_generations requires edits",
1230 ));
1231 }
1232 let edits = edits
1233 .map(|edits| {
1234 base_generations.map(|base| (base, edits)).ok_or_else(|| {
1235 GateError::new("invalid_params", "edits requires base_generations")
1236 })
1237 })
1238 .transpose()?;
1239 (PlanKind::Change, edits)
1240 }
1241 ConfigControlRequest::Stamp {} => (PlanKind::Stamp, None),
1242 ConfigControlRequest::Unstamp {} => (PlanKind::Unstamp, None),
1243 ConfigControlRequest::Rollback { generation } => (PlanKind::Rollback(generation), None),
1244 _ => {
1245 return Err(GateError::new(
1246 "unsupported_control_frame",
1247 "unknown configuration operation",
1248 ))
1249 }
1250 };
1251 let prepared = match edits {
1252 Some((base, edits)) => runtime.prepare_control_edits(base, edits).await?,
1253 None => {
1254 let prepared = runtime.prepare_capture(kind).await?;
1255 runtime.notify_delivery_changed();
1257 prepared
1258 }
1259 };
1260 let view = self.review_config_plan(runtime, prepared).await?;
1261 Ok(match kind {
1262 PlanKind::Change => ConfigControlResponse::Plan { view },
1263 PlanKind::Stamp => ConfigControlResponse::Stamp { view },
1264 PlanKind::Unstamp => ConfigControlResponse::Unstamp { view },
1265 PlanKind::Rollback(_) => ConfigControlResponse::Rollback { view },
1266 })
1267 }
1268
1269 async fn review_config_plan(
1270 &self,
1271 runtime: Arc<crate::config_gate::runtime::RuntimeOwner>,
1272 mut prepared: crate::config_gate::runtime::PreparedPlan,
1273 ) -> std::result::Result<subc_control::config::ConfigPlanView, GateError> {
1274 if prepared.capture_refused() {
1275 let view = config_work(runtime, ConfigWake::None, move |owner| {
1276 owner.capture_refusal(&prepared)?.ok_or_else(|| {
1277 GateError::new("module_review_invalid", "project refusal is absent")
1278 })
1279 })
1280 .await?;
1281 return Ok(view);
1282 }
1283 let mut fields = Vec::new();
1284 let mut edit_refusals = Vec::new();
1285 let mut unavailable_rereviews = Vec::new();
1286 let mut accepted_paths = std::collections::BTreeSet::new();
1287 let mut review_refusal = None;
1288 let mut refused_paths = std::collections::BTreeSet::new();
1289 let review_base = prepared.settings_review_base();
1290 for (module, captured) in &prepared.candidate.modules {
1291 if !prepared.review_modules.contains(module) {
1292 continue;
1293 }
1294 let base = prepared.bases.get(module);
1295 let reply = self
1296 .review_config_tuple(&runtime, module, base, &captured.view)
1297 .await;
1298 let reply = match reply {
1299 Ok(reply) => reply,
1300 Err(_) if prepared.rereview_modules.contains(module) => {
1303 unavailable_rereviews.push(module.clone());
1304 continue;
1305 }
1306 Err(error) => {
1307 return Err(error.with_settings_review_paths(vec![captured.file.path.clone()]))
1308 }
1309 };
1310 let reply: subc_protocol::config::ConfigReviewReply = serde_json::from_slice(&reply)
1311 .map_err(|_| {
1312 GateError::new(
1313 "module_review_invalid",
1314 format!("{module}: malformed config.review reply"),
1315 )
1316 })?;
1317 if prepared.is_edit_plan() && !reply.refusals.is_empty() {
1318 refused_paths.insert(captured.file.path.clone());
1319 let before = edit_refusals.len();
1320 for refusal in &reply.refusals {
1321 for path in refusal
1322 .paths
1323 .iter()
1324 .filter(|path| path.starts_with('/') && path.len() <= 1024)
1325 {
1326 edit_refusals.push(subc_control::config::ConfigPlanRefusal {
1327 module_id: module.clone(),
1328 path: path.clone(),
1329 code: "module_review_refused".into(),
1330 message: "the module refused this field".into(),
1331 project_id: None,
1332 workspace_id: None,
1333 });
1334 }
1335 }
1336 if edit_refusals.len() == before {
1337 edit_refusals.push(subc_control::config::ConfigPlanRefusal {
1338 module_id: module.clone(),
1339 path: String::new(),
1340 code: "module_review_refused".into(),
1341 message: "the module refused the edits".into(),
1342 project_id: None,
1343 workspace_id: None,
1344 });
1345 }
1346 fields.extend(prepared.refused_fields(module)?);
1347 continue;
1348 }
1349 match crate::config_gate::review::checked_fields(
1350 module,
1351 &captured.schema,
1352 base,
1353 prepared.base_schemas.get(module),
1354 &captured.view,
1355 reply,
1356 ) {
1357 Ok(changes) => {
1358 accepted_paths.insert(captured.file.path.clone());
1359 fields.extend(changes);
1360 }
1361 Err(error) if error.code == "module_review_refused" => {
1362 refused_paths.insert(captured.file.path.clone());
1363 review_refusal.get_or_insert(error);
1364 }
1365 Err(error) => {
1366 return Err(error.with_settings_review_paths(vec![captured.file.path.clone()]))
1367 }
1368 }
1369 }
1370 for module in unavailable_rereviews {
1371 prepared.review_modules.remove(&module);
1372 prepared.rereview_modules.remove(&module);
1373 }
1374 let mut project_replies = Vec::new();
1375 for (tuple, review) in prepared.project_reviews() {
1376 let paths = || {
1377 review
1378 .approval
1379 .view
1380 .layers
1381 .iter()
1382 .filter_map(|layer| layer.path.as_ref().map(std::path::PathBuf::from))
1383 .collect()
1384 };
1385 let bytes = self
1386 .review_config_tuple(
1387 &runtime,
1388 &tuple.module,
1389 review.base.as_ref(),
1390 &review.approval.view,
1391 )
1392 .await
1393 .map_err(|error| error.with_settings_review_paths(paths()))?;
1394 let reply: subc_protocol::config::ConfigReviewReply = serde_json::from_slice(&bytes)
1395 .map_err(|_| {
1396 GateError::new(
1397 "module_review_invalid",
1398 format!("{}: malformed project config.review reply", tuple.module),
1399 )
1400 })?;
1401 let changed = crate::config_gate::review::changed_project_review_paths(
1402 review.base.as_ref(),
1403 &review.approval.view,
1404 );
1405 if prepared.is_edit_plan() {
1406 refused_paths.extend(crate::config_gate::review::attributed_review_refusals(
1407 review.base.as_ref(),
1408 &review.approval.view,
1409 &reply.refusals,
1410 ));
1411 }
1412 project_replies.push((tuple.clone(), reply, paths(), changed));
1413 }
1414 for (tuple, reply, paths, changed) in project_replies {
1415 if prepared.is_edit_plan() && !reply.refusals.is_empty() {
1416 prepared.refuse_project_review(&tuple, &reply);
1417 } else {
1418 match prepared.accept_project_review(&tuple, reply) {
1419 Ok(changes) => {
1420 accepted_paths.extend(changed);
1421 fields.extend(changes);
1422 }
1423 Err(error) if error.code == "module_review_refused" => {
1424 refused_paths.extend(error.settings_review_paths.iter().cloned());
1425 review_refusal.get_or_insert(error);
1426 }
1427 Err(error) => return Err(error.with_settings_review_paths(paths)),
1428 }
1429 }
1430 }
1431 accepted_paths.retain(|path| !refused_paths.contains(path));
1432 if !accepted_paths.is_empty() {
1433 config_work(runtime.clone(), ConfigWake::Delivery, move |owner| {
1434 owner.clear_settings_review_success(review_base, &accepted_paths)
1435 })
1436 .await?;
1437 }
1438 if let Some(error) = review_refusal {
1439 return Err(error.with_settings_review_paths(refused_paths.into_iter().collect()));
1440 }
1441 if prepared.capture_refused() {
1442 let view = runtime
1443 .on_blocking(move |owner| {
1444 owner.capture_refusal(&prepared)?.ok_or_else(|| {
1445 GateError::new("module_review_invalid", "project refusal is absent")
1446 })
1447 })
1448 .await?;
1449 return Ok(view);
1450 }
1451 prepared.add_edit_refusals(edit_refusals);
1452 fields.extend(prepared.unreviewed_fields()?);
1453 config_work(runtime, ConfigWake::Delivery, move |owner| {
1454 owner.finish_plan(prepared, move |old, new| {
1455 let mut changeset = crate::config_gate::runtime::daemon_review(old, new)?;
1456 changeset.fields = fields;
1457 let mut effects: std::collections::BTreeMap<String,std::collections::BTreeMap<String,Vec<String>>> = Default::default();
1458 for field in changeset.fields.iter().filter(|field| field.project_id.is_none()) {
1459 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();
1460 effects.entry(field.module_id.clone()).or_default().entry(kind).or_default().push(field.path.clone());
1461 }
1462 if changeset.fields.iter().any(|field| field.project_id.is_none() && !matches!(field.apply, subc_config::ApplyKind::Live | subc_config::ApplyKind::NewSessions)) {
1463 changeset.apply_plan = serde_json::json!({"daemon_effects":changeset.apply_plan,"modules":effects});
1464 }
1465 Ok(changeset)
1466 })
1467 })
1468 .await
1469 }
1470
1471 async fn review_config_tuple(
1472 &self,
1473 runtime: &Arc<crate::config_gate::runtime::RuntimeOwner>,
1474 module: &str,
1475 base: Option<&subc_protocol::config::ConfigView>,
1476 candidate: &subc_protocol::config::ConfigView,
1477 ) -> Result<Vec<u8>, GateError> {
1478 #[cfg(test)]
1479 if let Some(reply) = self
1480 .config_review_test_replies
1481 .get(module)
1482 .or(self.config_review_test_reply.as_ref())
1483 {
1484 if let Some(seen) = &self.config_review_test_seen {
1485 let _ = seen.send(module.into());
1486 }
1487 if self
1488 .config_review_test_refuse
1489 .lock()
1490 .unwrap()
1491 .contains(module)
1492 {
1493 let refusal = subc_protocol::config::ConfigReviewReply::new(
1494 vec![],
1495 vec![subc_protocol::config::ConfigReviewRefusal::new(
1496 "refused",
1497 vec!["/limit".into()],
1498 vec![],
1499 )],
1500 );
1501 return Ok(serde_json::to_vec(&refusal).unwrap());
1502 }
1503 use std::sync::atomic::Ordering;
1504 if self
1505 .config_review_test_fail_once
1506 .swap(false, Ordering::Relaxed)
1507 {
1508 return Err(GateError::new(
1509 "approval_surface_unavailable",
1510 "module reviewer temporarily unavailable",
1511 ));
1512 }
1513 return serde_json::to_vec(reply).map_err(|_| {
1514 GateError::new(
1515 "module_review_invalid",
1516 "could not encode the fixture review",
1517 )
1518 });
1519 }
1520 let registration = self
1521 .registry
1522 .get_module(module)
1523 .map_err(|_| GateError::new("config_unavailable", "registry is unavailable"))?
1524 .ok_or_else(|| {
1525 GateError::new(
1526 "module_review_unavailable",
1527 format!("{module}: no active reviewer"),
1528 )
1529 })?;
1530 let admission = self.review_admission();
1531 let reviewer = registration.clone();
1532 config_work(runtime.clone(), ConfigWake::None, move |_| {
1533 admission.check(&reviewer)
1534 })
1535 .await?;
1536 if !registration
1537 .control_ops
1538 .iter()
1539 .any(|op| op == "config.review")
1540 {
1541 return Err(GateError::new(
1542 "module_review_unavailable",
1543 format!("{module}: config.review is not opted in"),
1544 ));
1545 }
1546 let request = subc_protocol::config::ConfigReviewRequest::new(
1547 base.map_or(0, |view| view.generation),
1548 candidate.layers.clone(),
1549 base.cloned(),
1550 );
1551 let bytes = serde_json::to_vec(&request).map_err(|_| {
1552 GateError::new("config_unavailable", "could not encode immutable review")
1553 })?;
1554 self.config_rpc(
1555 runtime,
1556 module,
1557 registration.connection_id,
1558 "config.review",
1559 bytes,
1560 )
1561 .await
1562 }
1563
1564 #[cfg(test)]
1565 async fn config_approval_facts(&self, ctx: &RouteCtx) -> ApprovalFacts {
1566 let phone = self.config_phone_surface().await;
1567 self.config_approval_facts_with_phone(ctx, phone).await
1568 }
1569
1570 async fn config_apply_facts(
1571 &self,
1572 ctx: &RouteCtx,
1573 phone: Option<crate::config_gate::PhoneSurface>,
1574 daemon_settings: bool,
1575 ) -> ApprovalFacts {
1576 if daemon_settings {
1577 return ApprovalFacts {
1580 connection: ctx.connection_id.get(),
1581 owner_uid: true,
1582 desktop_app: false,
1583 attested_operator_app: false,
1584 os_prompt_available: false,
1585 phone,
1586 caller: crate::caller_identity::CallerIdentity::daemon_settings(),
1587 };
1588 }
1589 self.config_approval_facts_with_phone(ctx, phone).await
1590 }
1591
1592 async fn config_approval_facts_with_phone(
1593 &self,
1594 ctx: &RouteCtx,
1595 phone: Option<crate::config_gate::PhoneSurface>,
1596 ) -> ApprovalFacts {
1597 let os_policy = crate::config_gate::os_prompt_policy_present();
1598 #[cfg(any(test, feature = "test-support"))]
1599 let os_policy = os_policy
1600 || self
1601 .config_runtime
1602 .as_ref()
1603 .is_some_and(|owner| owner.os_prompt_policy_for_tests());
1604 let desktop = self
1605 .config_desktop_identity(ctx.connection_id)
1606 .await
1607 .unwrap_or(false);
1608 ApprovalFacts {
1609 connection: ctx.connection_id.get(),
1610 owner_uid: self.config_owner_connection(ctx.connection_id),
1611 desktop_app: desktop,
1612 attested_operator_app: desktop && !cfg!(feature = "dev-desktop-approval"),
1613 os_prompt_available: config_os_prompt_available(
1614 self.forwarding.operator_confirms().config_gate_ready(),
1615 os_policy,
1616 ),
1617 phone,
1618 caller: self.resolve_caller(ctx.connection_id).await,
1619 }
1620 }
1621
1622 async fn config_phone_surface(&self) -> Option<crate::config_gate::PhoneSurface> {
1625 self.config_phone_surface_checked(true, None).await
1626 }
1627
1628 async fn config_phone_surface_snapshot(&self) -> Option<crate::config_gate::PhoneSurface> {
1629 self.config_phone_surface_checked(false, None).await
1630 }
1631
1632 async fn config_phone_surface_checked(
1633 &self,
1634 content: bool,
1635 publication: Option<&crate::config_gate::runtime::Published>,
1636 ) -> Option<crate::config_gate::PhoneSurface> {
1637 if self.config_runtime.as_ref().is_some_and(|owner| {
1638 publication.map_or_else(|| owner.is_recovering(), |view| view.is_recovering())
1639 }) {
1640 return None;
1641 }
1642 if !self.operator_app_policy.phone_enabled {
1643 return None;
1644 }
1645 let runtime = self.config_runtime.as_ref()?;
1646 let (_, registrations) = self.registry.list_modules_with_nonce_verification().ok()?;
1647 let (registration, verified) = registrations
1648 .into_iter()
1649 .find(|(registration, _)| registration.manifest.module_id == "callosum")?;
1650 if !verified
1651 || !registration.ready
1652 || !registration
1653 .control_ops
1654 .iter()
1655 .any(|op| op == subc_protocol::consent::CONSENT_V1)
1656 {
1657 return None;
1658 }
1659 let _spawn = self
1660 .supervisor
1661 .registration_spawn(registration.connection_id)?;
1662 if !self
1663 .forwarding
1664 .active_module_endpoint("callosum")
1665 .ok()
1666 .flatten()
1667 .is_some_and(|endpoint| endpoint.connection_id == registration.connection_id)
1668 {
1669 return None;
1670 }
1671 let module = self.supervisor.get("callosum")?;
1675 let status = module.status().ok()?;
1676 let (spec, _) = module.configuration().ok()?;
1677 if !self.supervisor.registration_snapshot_is_current_live(
1678 &self.registry,
1679 "callosum",
1680 registration.connection_id,
1681 None,
1682 ) || !spec.reserved
1683 || !status.enabled
1684 || !status.process_alive
1685 || !status.registration_active
1686 {
1687 return None;
1688 }
1689 let connection = registration.connection_id;
1690 let approved = if content {
1691 runtime
1692 .on_blocking(move |owner| owner.approved_phone_entry(connection))
1693 .await
1694 .ok()??
1695 } else {
1696 if let Some(snapshot) = publication {
1697 runtime.polled_phone_entry_from(snapshot, connection)?
1698 } else {
1699 runtime.polled_phone_entry(connection)?
1700 }
1701 };
1702 if !approved.enabled || approved.module_spec() != spec {
1703 return None;
1704 }
1705 if content {
1706 let supervisor = self.supervisor.clone();
1707 let registry = self.registry.clone();
1708 if !runtime
1709 .on_blocking(move |_| {
1710 Ok(supervisor
1711 .registration_is_current_live(®istry, "callosum", connection, None))
1712 })
1713 .await
1714 .ok()?
1715 {
1716 return None;
1717 }
1718 }
1719 if !self.supervisor.registration_snapshot_is_current_live(
1720 &self.registry,
1721 "callosum",
1722 registration.connection_id,
1723 None,
1724 ) {
1725 return None;
1726 }
1727 Some(crate::config_gate::PhoneSurface {
1728 module_id: "callosum".into(),
1729 connection: connection.get(),
1730 spawn_generation: status.spawn_generation,
1731 enabled_by_policy: true,
1732 opted_in: true,
1733 approved_declaration: true,
1734 reserved: true,
1735 channel_registered: true,
1736 program_admitted: true,
1737 active_registration: true,
1738 })
1739 }
1740
1741 async fn config_rpc(
1742 &self,
1743 runtime: &Arc<crate::config_gate::runtime::RuntimeOwner>,
1744 module: &str,
1745 expected_connection: ConnectionId,
1746 op: &str,
1747 bytes: Vec<u8>,
1748 ) -> std::result::Result<Vec<u8>, GateError> {
1749 let gate = runtime.module_gate(module)?;
1750 let pending = {
1751 let _gate = gate.lock().await;
1752 let registration = self
1753 .registry
1754 .get_module(module)
1755 .map_err(|_| GateError::new("config_unavailable", "registry unavailable"))?
1756 .ok_or_else(|| {
1757 GateError::new(
1758 "module_review_unavailable",
1759 format!("{module}: no active target"),
1760 )
1761 })?;
1762 let pending = self
1763 .forwarding
1764 .begin_module_control_rpc_for(module, op, Instant::now() + CONFIG_REVIEW_TIMEOUT)
1765 .map_err(|_| {
1766 GateError::new(
1767 "module_review_unavailable",
1768 format!("{module}: target unavailable"),
1769 )
1770 })?;
1771 if pending.endpoint.connection_id != registration.connection_id
1772 || registration.connection_id != expected_connection
1773 {
1774 let _ = self
1775 .forwarding
1776 .cancel_module_control_rpc(pending.endpoint, pending.corr);
1777 return Err(GateError::new(
1778 "not_delivery_target",
1779 "registry and forwarding targets differ",
1780 ));
1781 }
1782 pending
1783 };
1784 let PendingModuleControlRpc {
1785 endpoint,
1786 module_sink,
1787 negotiated_ver,
1788 corr,
1789 receiver,
1790 } = pending;
1791 let mut guard = ModuleControlRpcGuard::new(self.forwarding.clone(), endpoint, corr);
1792 let deadline = Instant::now() + CONFIG_REVIEW_TIMEOUT;
1793 let frame = Frame::build_with_version(
1794 negotiated_ver,
1795 FrameType::Request,
1796 control_flags(),
1797 0,
1798 0,
1799 corr,
1800 bytes,
1801 )
1802 .map_err(|_| GateError::new("config_unavailable", "could not encode config request"))?;
1803 timeout_at(deadline, module_sink.send(frame))
1804 .await
1805 .map_err(|_| {
1806 GateError::new(
1807 "config_review_timeout",
1808 format!("{module}: config.review exceeded its 30-second deadline; plan remains unapproved"),
1809 )
1810 })?
1811 .map_err(|_| {
1812 GateError::new(
1813 "module_review_unavailable",
1814 format!("{module}: target disconnected"),
1815 )
1816 })?;
1817 let outcome = timeout_at(deadline, receiver)
1818 .await
1819 .map_err(|_| {
1820 GateError::new(
1821 "config_review_timeout",
1822 format!("{module}: config.review exceeded its 30-second deadline; plan remains unapproved"),
1823 )
1824 })?
1825 .map_err(|_| {
1826 GateError::new(
1827 "module_review_unavailable",
1828 format!("{module}: target disconnected"),
1829 )
1830 })?;
1831 guard.disarm();
1832 match outcome {
1833 ModuleControlRpcOutcome::RawResponse(bytes) => Ok(bytes),
1834 ModuleControlRpcOutcome::DeadlineElapsed => Err(GateError::new("config_review_timeout",format!("{module}: config.review exceeded its 30-second deadline; plan remains unapproved"))),
1835 _ => Err(GateError::new(
1836 "module_review_unavailable",
1837 format!("{module}: config request was not answered"),
1838 )),
1839 }
1840 }
1841
1842 pub async fn confirm_config_gate_presence(
1845 &self,
1846 ctx: &RouteCtx,
1847 frame: &Frame,
1848 challenge: &ApprovalChallenge,
1849 ) -> PresenceDecision {
1850 let Some(text) = challenge.prompt() else {
1851 return PresenceDecision::Unavailable;
1852 };
1853 let caller = self.resolve_caller(ctx.connection_id).await;
1854 let key = crate::operator_confirm::DeclineKey::for_caller(&caller, ctx.connection_id);
1855 let outcome = self
1858 .forwarding
1859 .operator_confirms()
1860 .approve_config_gate(ctx, frame, text.to_owned(), caller.description(), key)
1861 .await;
1862 PresenceDecision::from_operator_outcome(&outcome)
1863 }
1864}
1865
1866fn config_os_prompt_available(provider_ready: bool, policy_present: bool) -> bool {
1867 provider_ready && policy_present
1868}
1869
1870enum ConfigWake {
1871 None,
1872 Delivery,
1873}
1874
1875async fn config_work<T: Send + 'static>(
1876 runtime: Arc<crate::config_gate::runtime::RuntimeOwner>,
1877 wake: ConfigWake,
1878 work: impl FnOnce(Arc<crate::config_gate::runtime::RuntimeOwner>) -> std::result::Result<T, GateError>
1879 + Send
1880 + 'static,
1881) -> std::result::Result<T, GateError> {
1882 runtime
1883 .on_blocking(move |owner| {
1884 let result = work(owner.clone());
1885 if matches!(wake, ConfigWake::Delivery) {
1886 owner.notify_delivery_changed();
1887 }
1888 result
1889 })
1890 .await
1891}
1892
1893pub(super) fn config_error_frame(frame: &Frame, error: GateError) -> Result<Frame, RouterError> {
1894 control_error_body_frame(
1895 frame,
1896 ErrorBody {
1897 code: error.code,
1898 message: error.detail,
1899 detail: error.wire_detail.map(|detail| *detail),
1900 },
1901 )
1902}
1903
1904pub(super) fn now_ms() -> u64 {
1905 std::time::SystemTime::now()
1906 .duration_since(std::time::UNIX_EPOCH)
1907 .unwrap_or_default()
1908 .as_millis()
1909 .min(u128::from(u64::MAX)) as u64
1910}
1911
1912#[cfg(test)]
1913mod tests;
1914
1915#[cfg(test)]
1916mod desktop_tests;