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