Skip to main content

subc_daemon/control/
config_gate.rs

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
15/// Settings reads and user-layer edit plans are served together.
16pub(super) const CONFIG_SETTINGS_SURFACE_ENABLED: bool = true;
17
18/// Bound each immutable module review so an unanswered request cannot approve a plan.
19const CONFIG_REVIEW_TIMEOUT: Duration = Duration::from_secs(30);
20
21/// After a phone answer, lock waits and freshness work have thirty seconds to
22/// reach durable publication. Publication already started returns its real result.
23const 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        // The config gate binds trusted review and presence to its digest. The
56        // generic operator prompt would run twice, and its log/shortcut modes
57        // cannot substitute for config approval.
58        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                                    // No delivery or module gate may wait on a repository mount.
241                                    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                        &registration.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                    // A slow writer may finish after cutover or supersession.
363                    // Its receipt must not advance the replacement's attempt.
364                    if !self.config_delivery_target_current(
365                        &registration.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    /// Only bootstrap's explicit store-root path advertises configuration authority.
485    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(test)]
511        if self
512            .config_runtime
513            .as_ref()
514            .is_some_and(|owner| owner.has_trusted_review_connection_for_test(connection))
515        {
516            return Ok(true);
517        }
518        #[cfg(feature = "dev-desktop-approval")]
519        {
520            // Requesting and receiving the complete immutable review is the
521            // development caller's desktop presentation, not app attestation.
522            Ok(self
523                .local_connections
524                .lock()
525                .unwrap_or_else(|p| p.into_inner())
526                .contains(&connection))
527        }
528        #[cfg(not(feature = "dev-desktop-approval"))]
529        {
530            Ok(self.has_current_config_desktop_stamp(connection).await)
531        }
532    }
533
534    pub(crate) fn config_desktop_review_request(&self, request: &Frame) -> bool {
535        self.config_runtime.is_some()
536            && request.header.ty == FrameType::Request
537            && serde_json::from_slice::<ControlOpProbe>(&request.body).is_ok_and(|probe| {
538                matches!(
539                    probe.op.as_str(),
540                    "config.plan" | "config.stamp" | "config.unstamp" | "config.rollback"
541                )
542            })
543    }
544
545    pub(crate) async fn config_desktop_review_response(
546        &self,
547        connection: ConnectionId,
548        response: &Frame,
549    ) -> Option<subc_control::config::ConfigPlanView> {
550        if self.config_runtime.is_none() || response.header.ty != FrameType::Response {
551            return None;
552        }
553        let probe: ControlOpProbe = serde_json::from_slice(&response.body).ok()?;
554        if !matches!(
555            probe.op.as_str(),
556            "config.plan"
557                | "config.plan_get"
558                | "config.stamp"
559                | "config.unstamp"
560                | "config.rollback"
561        ) || !matches!(self.config_desktop_identity(connection).await, Ok(true))
562        {
563            return None;
564        }
565        match serde_json::from_slice::<ConfigControlResponse>(&response.body).ok()? {
566            ConfigControlResponse::Plan { view }
567            | ConfigControlResponse::PlanGet { view }
568            | ConfigControlResponse::Stamp { view }
569            | ConfigControlResponse::Unstamp { view }
570            | ConfigControlResponse::Rollback { view } => Some(view),
571            _ => None,
572        }
573    }
574
575    pub(crate) async fn config_desktop_review_delivered(
576        &self,
577        connection: ConnectionId,
578        view: subc_control::config::ConfigPlanView,
579    ) {
580        if !matches!(self.config_desktop_identity(connection).await, Ok(true)) {
581            return;
582        }
583        let Some(runtime) = self.config_runtime.clone() else {
584            return;
585        };
586        let peers = self.captured_peers.clone();
587        let _ = config_work(runtime, ConfigWake::Delivery, move |owner| {
588            owner.desktop_view_delivered_when(connection, &view, || {
589                peers
590                    .lock()
591                    .unwrap_or_else(|p| p.into_inner())
592                    .contains_key(&connection)
593            })
594        })
595        .await;
596    }
597
598    pub(crate) async fn deliver_config_desktop_review(
599        &self,
600        ctx: &RouteCtx,
601        response: Frame,
602        view: subc_control::config::ConfigPlanView,
603    ) -> Result<(), RouterError> {
604        ctx.egress.send_flushed(response).await?;
605        self.config_desktop_review_delivered(ctx.connection_id, view)
606            .await;
607        Ok(())
608    }
609
610    pub fn with_config_review_admission(
611        mut self,
612        admission: Arc<dyn crate::config_gate::ReviewAdmission>,
613    ) -> Self {
614        self.config_review_admission = admission;
615        self.config_review_admission_is_default = false;
616        self
617    }
618
619    pub(super) fn review_admission(&self) -> Arc<dyn crate::config_gate::ReviewAdmission> {
620        if self.config_runtime.is_some() && self.config_review_admission_is_default {
621            Arc::new(admission::SupervisedReviewAdmission(self.clone()))
622        } else {
623            self.config_review_admission.clone()
624        }
625    }
626
627    /// Config operations are channel-0 only, so callers are unscoped. Scoped
628    /// access rules must be enforced if a scoped path to these operations is added.
629    pub(super) async fn handle_config_gate_request(
630        &self,
631        ctx: &RouteCtx,
632        frame: Frame,
633        op: &str,
634    ) -> Result<Vec<Frame>, RouterError> {
635        let request = match serde_json::from_slice::<ConfigControlRequest>(&frame.body) {
636            Ok(request) => request,
637            Err(error) => {
638                return Ok(vec![control_error_frame(
639                    &frame,
640                    "invalid_control_body",
641                    format!("malformed config control body: {error}"),
642                )?])
643            }
644        };
645        debug_assert!(privileged_operation(&request).is_none());
646        let Some(runtime) = self.config_runtime.clone() else {
647            return Ok(vec![control_error_frame(
648                &frame,
649                "config_gate_inactive",
650                "no config store configured",
651            )?]);
652        };
653        if !self.config_owner_connection(ctx.connection_id) {
654            return Ok(vec![control_error_frame(
655                &frame,
656                "owner_required",
657                "configuration control requires a kernel-observed owner-user connection",
658            )?]);
659        }
660        if let ConfigControlRequest::Watch { modules, projects } = request {
661            let projects = projects == Some(true) && runtime.project_settings_enabled();
662            return self
663                .handle_config_settings_watch(ctx, frame, runtime, modules, projects)
664                .await;
665        }
666        let result = self
667            .execute_config_request(ctx, &frame, runtime, request)
668            .await;
669        match result {
670            Ok(response) => Ok(vec![control_response_body_frame(
671                &frame,
672                &response,
673                "ConfigControlResponse",
674            )?]),
675            Err(error) if error.code == subc_control::upgrade_in_place::UPGRADE_BUSY => {
676                Ok(vec![control_error_body_frame(
677                    &frame,
678                    ErrorBody::new(error.code, error.detail)
679                        .with_detail(serde_json::json!({"reason":"upgrade"})),
680                )?])
681            }
682            Err(error) => Ok(vec![
683                self.config_request_error_frame(&frame, op, false, error)?
684            ]),
685        }
686    }
687
688    pub(super) fn config_owner_connection(&self, connection: ConnectionId) -> bool {
689        let peers = self
690            .observed_peers
691            .lock()
692            .unwrap_or_else(|p| p.into_inner());
693        let Some(peer) = peers.get(&connection) else {
694            return false;
695        };
696        #[cfg(unix)]
697        {
698            peer.uid == Some(subc_os::effective_uid())
699        }
700        #[cfg(windows)]
701        {
702            subc_os::named_pipe::current_user_sid_string()
703                .ok()
704                .as_ref()
705                .is_some_and(|sid| peer.sid.as_ref() == Some(sid))
706        }
707        #[cfg(not(any(unix, windows)))]
708        {
709            let _ = peer;
710            false
711        }
712    }
713
714    async fn execute_config_request(
715        &self,
716        ctx: &RouteCtx,
717        frame: &Frame,
718        runtime: Arc<crate::config_gate::runtime::RuntimeOwner>,
719        request: ConfigControlRequest,
720    ) -> std::result::Result<ConfigControlResponse, GateError> {
721        Box::pin(self.execute_config_request_from(ctx, frame, runtime, request, None)).await
722    }
723
724    async fn execute_config_request_from(
725        &self,
726        ctx: &RouteCtx,
727        frame: &Frame,
728        runtime: Arc<crate::config_gate::runtime::RuntimeOwner>,
729        request: ConfigControlRequest,
730        automatic: Option<pending_settings::AutomaticSettingsAttempt>,
731    ) -> std::result::Result<ConfigControlResponse, GateError> {
732        let settings = if matches!(
733            request,
734            ConfigControlRequest::Apply { .. } | ConfigControlRequest::PlaceProgram { .. }
735        ) {
736            self.upgrade_settings_guard()
737                .map_err(|body| GateError::new(&body.code, body.message))?
738                .map(Arc::new)
739        } else {
740            None
741        };
742        match request {
743            ConfigControlRequest::Modules {} => {
744                let known = self.config_settings_known_modules()?;
745                config_work(runtime, ConfigWake::None, move |owner| {
746                    owner.settings_modules(known)
747                })
748                .await
749            }
750            ConfigControlRequest::Schema { module_id } => {
751                let known = self.config_settings_known_modules()?;
752                config_work(runtime, ConfigWake::None, move |owner| {
753                    owner.settings_schema(known, module_id)
754                })
755                .await
756            }
757            ConfigControlRequest::Show {
758                module_id,
759                project_id,
760                through,
761            } => {
762                let known = self.config_settings_known_modules()?;
763                if let Some(project) = project_id {
764                    return runtime
765                        .settings_show_project(known, module_id, project, through)
766                        .await;
767                }
768                config_work(runtime, ConfigWake::None, move |owner| {
769                    owner.settings_show(known, module_id, through)
770                })
771                .await
772            }
773            ConfigControlRequest::PlanGet { digest } => {
774                let view = config_work(runtime, ConfigWake::None, move |owner| {
775                    owner.plan_get(&digest)
776                })
777                .await?;
778                Ok(ConfigControlResponse::PlanGet { view })
779            }
780            ConfigControlRequest::PlanDiscard { digest } => {
781                config_work(runtime, ConfigWake::Delivery, move |owner| {
782                    owner.plan_discard(&digest)
783                })
784                .await?;
785                Ok(ConfigControlResponse::PlanDiscard {})
786            }
787            ConfigControlRequest::Revert { digest } => {
788                let files = self.revert_config_plan(&runtime, digest).await?;
789                Ok(ConfigControlResponse::Revert { files })
790            }
791            ConfigControlRequest::PlaceProgram {
792                module_id,
793                path,
794                sha256,
795                manifest,
796            } => {
797                let gate = runtime.module_gate(&module_id)?;
798                let _guard = gate.lock().await;
799                let generation = config_work(runtime, ConfigWake::Delivery, move |owner| {
800                    let _settings = settings;
801                    owner.place_program_with_manifest(&module_id, &path, &sha256, manifest.as_ref())
802                })
803                .await?;
804                Ok(ConfigControlResponse::ProgramPlaced { generation })
805            }
806            ConfigControlRequest::Status {} => {
807                let snapshot = runtime.observed_snapshot()?;
808                let mut status = runtime.polled_status_from(snapshot.clone()).await?;
809                let phone = self
810                    .config_phone_surface_checked(false, Some(&snapshot))
811                    .await;
812                let facts = self.config_approval_facts_with_phone(ctx, phone).await;
813                status
814                    .missing_approval_surfaces
815                    .extend(crate::config_gate::missing_surfaces(
816                        &facts,
817                        matches!(status.state.as_str(), "store_missing" | "store_unverified"),
818                    ));
819                self.report_daemon_configuration(&snapshot.approved_daemon, &mut status)
820                    .await?;
821                if let Some(problem) = runtime
822                    .on_blocking(move |owner| {
823                        Ok(owner.policy_root_problem(&snapshot.approved_daemon))
824                    })
825                    .await?
826                {
827                    status.warnings.push(problem);
828                }
829                Ok(ConfigControlResponse::Status { status })
830            }
831            ConfigControlRequest::History {} => {
832                let (generations, pruned) =
833                    config_work(runtime, ConfigWake::None, |owner| owner.history()).await?;
834                Ok(ConfigControlResponse::History {
835                    generations,
836                    pruned,
837                })
838            }
839            ConfigControlRequest::Apply { digest } => {
840                let daemon_settings = automatic.is_some();
841                let order = automatic.as_ref().map_or_else(
842                    || runtime.next_settings_request_order(),
843                    |attempt| attempt.token,
844                );
845                if let Some(result) = self
846                    .apply_unstamped_policy_root(ctx, frame, &runtime, &digest)
847                    .await?
848                {
849                    return Ok(result);
850                }
851                let apply_digest = digest.clone();
852                if let Some(generation) = runtime
853                    .apply_control_edits(apply_digest, settings.clone())
854                    .await?
855                {
856                    return Ok(ConfigControlResponse::Applied {
857                        generation,
858                        restart_required: false,
859                    });
860                }
861                let connection = ctx.connection_id;
862                let corr = frame.header.corr;
863                #[cfg(all(test, unix))]
864                runtime.pause_approval_claim_for_test().await;
865                let request_guard = runtime.claim_approval_request(connection, corr)?;
866                if self.rescan.is_none() {
867                    return Err(GateError::new(
868                        "supervisor_reconcile_unavailable",
869                        "configuration commit requires the supervisor owner",
870                    ));
871                }
872                let phone = self.config_phone_surface().await;
873                let facts = self.config_apply_facts(ctx, phone, daemon_settings).await;
874                let cancellation = request_guard.request.clone();
875                let (challenge, attempt_guard) =
876                    config_work(runtime.clone(), ConfigWake::Delivery, move |owner| {
877                        let challenge = owner.begin_settings_apply_for_request(
878                            &digest,
879                            &facts,
880                            &cancellation,
881                            order,
882                        )?;
883                        // The job owns slot cleanup even if its async caller drops
884                        // before this blocking result can be delivered.
885                        let guard = phone::ApprovalAttemptGuard::new(&owner, challenge.attempt());
886                        owner.track_reserved_approval_request(
887                            challenge.attempt(),
888                            connection,
889                            corr,
890                            &cancellation,
891                        )?;
892                        Ok((challenge, guard))
893                    })
894                    .await?;
895                request_guard.request.ensure_live()?;
896                let feedback = automatic.and_then(|attempt| attempt.feedback);
897                if let Some(feedback) = &feedback {
898                    let _ = feedback.send(pending_settings::CardFeedback::Filed);
899                }
900                let reply = match &challenge {
901                    ApprovalChallenge::Desktop { .. } | ApprovalChallenge::OsPrompt { .. } => {
902                        let attempt = challenge.attempt();
903                        tokio::select! {
904                            biased;
905                            _ = runtime.wait_settings_attempt_replaced(attempt) => {
906                                return Err(GateError::new("approval_surface_unavailable", "a newer settings approval took precedence"));
907                            }
908                            decision = async {
909                                let _delivery = runtime.settings_phone_delivery.lock().await;
910                                runtime.await_all_phone_withdrawals().await;
911                                if !runtime.on_blocking(move |owner| owner.settings_attempt_active(attempt)).await? {
912                                    return Err(GateError::new("approval_surface_unavailable", "a newer settings approval took precedence"));
913                                }
914                                Ok(self.confirm_config_gate_presence(ctx, frame, &challenge).await)
915                            } => ApprovalReply::Presence(decision?),
916                        }
917                    }
918                    ApprovalChallenge::Phone {
919                        attempt,
920                        connection,
921                        deadline,
922                        request,
923                    } => {
924                        // A withdrawn card sends its cancel before yielding this
925                        // slot, so a new phone request cannot overtake the cancel.
926                        let _delivery = timeout_at(*deadline, async {
927                            let guard = runtime.settings_phone_delivery.lock().await;
928                            runtime
929                                .await_phone_withdrawal(ConnectionId::new(*connection))
930                                .await;
931                            guard
932                        })
933                        .await
934                        .map_err(|_| {
935                            GateError::new(
936                                "approval_surface_unavailable",
937                                "the phone could not receive the settings card",
938                            )
939                        })?;
940                        let exchange = self
941                            .config_phone_rpc(
942                                &runtime,
943                                *attempt,
944                                ConnectionId::new(*connection),
945                                *deadline,
946                                request,
947                            )
948                            .await;
949                        if daemon_settings
950                            && Instant::now() >= *deadline
951                            && !matches!(
952                                &exchange,
953                                Ok(ApprovalReply::Phone {
954                                    response: Some(_),
955                                    ..
956                                })
957                            )
958                        {
959                            return Err(GateError::new(
960                                "settings_card_expired",
961                                "the settings card expired",
962                            ));
963                        }
964                        exchange?
965                    }
966                };
967                let attempt = challenge.attempt();
968                if daemon_settings {
969                    let phone = self.config_phone_surface().await;
970                    let facts = self.config_apply_facts(ctx, phone, true).await;
971                    let operation = self.supervisor.operation_lock();
972                    let restore_settings = settings.clone();
973                    let declined = config_work(runtime.clone(), ConfigWake::None, move |owner| {
974                        let declined = owner.accept_settings_decline(attempt, &facts, &reply)?;
975                        // This blocking job owns the accepted decision even if
976                        // the settings worker stops waiting for its result.
977                        let restore = declined.map(|digest| {
978                            let owner = owner.clone();
979                            tokio::spawn(async move {
980                                let _settings = restore_settings;
981                                let _operation = operation.lock_owned().await;
982                                let result = owner.revert_capture_plan(digest).await;
983                                if let Err(error) = &result {
984                                    tracing::warn!(code = %error.code, detail = %error.detail, "declined settings could not be restored");
985                                }
986                                result
987                            })
988                        });
989                        #[cfg(test)]
990                        if restore.is_some() {
991                            owner.after_settings_decline_for_test();
992                        }
993                        Ok((restore, reply))
994                    })
995                    .await?;
996                    if let Some(restore) = declined.0 {
997                        if let Err(mut error) = restore
998                            .await
999                            .map_err(|error| GateError::new("config_unavailable", error))?
1000                        {
1001                            if error.code != "settings_keep_limit" {
1002                                error.code = "settings_card_decline_unrestored".into();
1003                            }
1004                            return Err(error);
1005                        }
1006                        return Err(GateError::new(
1007                            "settings_card_declined",
1008                            "approval was declined",
1009                        ));
1010                    }
1011                    // Approval publication keeps several guards across awaits.
1012                    Box::pin(self.finish_config_apply(
1013                        ctx,
1014                        runtime,
1015                        challenge,
1016                        attempt_guard,
1017                        request_guard,
1018                        declined.1,
1019                        true,
1020                        settings,
1021                    ))
1022                    .await
1023                } else {
1024                    Box::pin(self.finish_config_apply(
1025                        ctx,
1026                        runtime,
1027                        challenge,
1028                        attempt_guard,
1029                        request_guard,
1030                        reply,
1031                        false,
1032                        settings,
1033                    ))
1034                    .await
1035                }
1036            }
1037            request => self.execute_config_plan(runtime, request).await,
1038        }
1039    }
1040
1041    #[allow(clippy::too_many_arguments)]
1042    async fn finish_config_apply(
1043        &self,
1044        ctx: &RouteCtx,
1045        runtime: Arc<crate::config_gate::runtime::RuntimeOwner>,
1046        challenge: ApprovalChallenge,
1047        mut attempt_guard: phone::ApprovalAttemptGuard,
1048        request_guard: crate::config_gate::runtime::ApprovalRequestGuard,
1049        reply: ApprovalReply,
1050        daemon_settings: bool,
1051        settings: Option<super::upgrade_in_place::SettingsPermit>,
1052    ) -> std::result::Result<ConfigControlResponse, GateError> {
1053        let attempt = challenge.attempt();
1054        let window = matches!(challenge, ApprovalChallenge::Phone { .. }).then(|| {
1055            Arc::new(crate::config_gate::runtime::ApprovalCommitWindow::new(
1056                Instant::now() + CONFIG_APPROVAL_COMMIT_TIMEOUT,
1057            ))
1058        });
1059        attempt_guard.commit_window = window.clone();
1060        let checked_phone = self.config_phone_surface().await;
1061        let locks = async {
1062            // A registry root can keep its worker busy until the I/O
1063            // returns. Do not hold supervisor or module gates while
1064            // waiting for that registry check.
1065            let project_apply = runtime.recheck_capture_apply(attempt).await?;
1066            let operation = self.supervisor.operation_lock().lock_owned().await;
1067            let module_gates = runtime.approval_commit_gates(attempt).await?;
1068            let current_phone = self.config_phone_surface_snapshot().await;
1069            let phone = checked_phone.filter(|phone| Some(phone) == current_phone.as_ref());
1070            let facts = self.config_apply_facts(ctx, phone, daemon_settings).await;
1071            Ok::<_, GateError>((operation, module_gates, facts, project_apply))
1072        };
1073        let (operation, module_gates, facts, project_apply) = if let Some(window) = &window {
1074            timeout_at(window.deadline, locks)
1075                .await
1076                .map_err(|_| GateError::commit_timeout())??
1077        } else {
1078            locks.await?
1079        };
1080        let now = now_ms();
1081        let publish_window = window.clone();
1082        let publication_request = request_guard.request.clone();
1083        let exit_runtime = runtime.clone();
1084        let work = config_work(runtime, ConfigWake::Delivery, move |owner| {
1085            let _owned_gates = (operation, module_gates);
1086            let write_authority = project_apply.clone();
1087            let generation = owner.finish_approval_with_commit_window(
1088                attempt,
1089                &facts,
1090                reply,
1091                now,
1092                publish_window,
1093                publication_request,
1094                project_apply,
1095            )?;
1096            if let Some(authority) = write_authority {
1097                // The publication job can finish after the control
1098                // request disconnects. It still owns this write-back.
1099                tokio::spawn(async move {
1100                    owner
1101                        .write_approved_project_files(generation, authority, settings)
1102                        .await
1103                });
1104            }
1105            Ok(generation)
1106        });
1107        tokio::pin!(work);
1108        let generation = if let Some(window) = window {
1109            tokio::select! {
1110                result = &mut work => result?,
1111                _ = tokio::time::sleep_until(window.deadline) => {
1112                    if window.expire() { return Err(GateError::commit_timeout()); }
1113                    work.await?
1114                }
1115            }
1116        } else {
1117            work.await?
1118        };
1119        let approval_runtime = exit_runtime.clone();
1120        if let Some(approval) = config_work(approval_runtime, ConfigWake::None, move |owner| {
1121            owner.development_approval(generation)
1122        })
1123        .await?
1124        {
1125            self.publish_development_approval(&approval);
1126            return Ok(ConfigControlResponse::Applied {
1127                generation,
1128                restart_required: false,
1129            });
1130        }
1131        #[cfg(test)]
1132        self.pause_before_apply_reconcile_for_test().await;
1133        self.reconcile_authority_exit(exit_runtime.clone(), generation)
1134            .await?;
1135        let restart_required = self
1136            .daemon_restart_required(&exit_runtime, generation)
1137            .await?;
1138        Ok(ConfigControlResponse::Applied {
1139            generation,
1140            restart_required,
1141        })
1142    }
1143
1144    async fn execute_config_plan(
1145        &self,
1146        runtime: Arc<crate::config_gate::runtime::RuntimeOwner>,
1147        request: ConfigControlRequest,
1148    ) -> std::result::Result<ConfigControlResponse, GateError> {
1149        let (kind, edits) = match request {
1150            ConfigControlRequest::Plan {
1151                base_generations,
1152                edits,
1153            } => {
1154                if edits.is_none() && base_generations.is_some() {
1155                    return Err(GateError::new(
1156                        "invalid_params",
1157                        "base_generations requires edits",
1158                    ));
1159                }
1160                let edits = edits
1161                    .map(|edits| {
1162                        base_generations.map(|base| (base, edits)).ok_or_else(|| {
1163                            GateError::new("invalid_params", "edits requires base_generations")
1164                        })
1165                    })
1166                    .transpose()?;
1167                (PlanKind::Change, edits)
1168            }
1169            ConfigControlRequest::Stamp {} => (PlanKind::Stamp, None),
1170            ConfigControlRequest::Unstamp {} => (PlanKind::Unstamp, None),
1171            ConfigControlRequest::Rollback { generation } => (PlanKind::Rollback(generation), None),
1172            _ => {
1173                return Err(GateError::new(
1174                    "unsupported_control_frame",
1175                    "unknown configuration operation",
1176                ))
1177            }
1178        };
1179        let prepared = match edits {
1180            Some((base, edits)) => runtime.prepare_control_edits(base, edits).await?,
1181            None => {
1182                let prepared = runtime.prepare_capture(kind).await?;
1183                // Preparing a plan can record observations that delivery reads.
1184                runtime.notify_delivery_changed();
1185                prepared
1186            }
1187        };
1188        let view = self.review_config_plan(runtime, prepared).await?;
1189        Ok(match kind {
1190            PlanKind::Change => ConfigControlResponse::Plan { view },
1191            PlanKind::Stamp => ConfigControlResponse::Stamp { view },
1192            PlanKind::Unstamp => ConfigControlResponse::Unstamp { view },
1193            PlanKind::Rollback(_) => ConfigControlResponse::Rollback { view },
1194        })
1195    }
1196
1197    async fn review_config_plan(
1198        &self,
1199        runtime: Arc<crate::config_gate::runtime::RuntimeOwner>,
1200        mut prepared: crate::config_gate::runtime::PreparedPlan,
1201    ) -> std::result::Result<subc_control::config::ConfigPlanView, GateError> {
1202        if prepared.capture_refused() {
1203            let view = config_work(runtime, ConfigWake::None, move |owner| {
1204                owner.capture_refusal(&prepared)?.ok_or_else(|| {
1205                    GateError::new("module_review_invalid", "project refusal is absent")
1206                })
1207            })
1208            .await?;
1209            return Ok(view);
1210        }
1211        let mut fields = Vec::new();
1212        let mut edit_refusals = Vec::new();
1213        let mut unavailable_rereviews = Vec::new();
1214        let mut accepted_paths = std::collections::BTreeSet::new();
1215        let mut review_refusal = None;
1216        let mut refused_paths = std::collections::BTreeSet::new();
1217        let review_base = prepared.settings_review_base();
1218        for (module, captured) in &prepared.candidate.modules {
1219            if !prepared.review_modules.contains(module) {
1220                continue;
1221            }
1222            let base = prepared.bases.get(module);
1223            let reply = self
1224                .review_config_tuple(&runtime, module, base, &captured.view)
1225                .await;
1226            let reply = match reply {
1227                Ok(reply) => reply,
1228                // A re-review the new program cannot answer now stays
1229                // pending in status; it does not hold up this plan.
1230                Err(_) if prepared.rereview_modules.contains(module) => {
1231                    unavailable_rereviews.push(module.clone());
1232                    continue;
1233                }
1234                Err(error) => {
1235                    return Err(error.with_settings_review_paths(vec![captured.file.path.clone()]))
1236                }
1237            };
1238            let reply: subc_protocol::config::ConfigReviewReply = serde_json::from_slice(&reply)
1239                .map_err(|_| {
1240                    GateError::new(
1241                        "module_review_invalid",
1242                        format!("{module}: malformed config.review reply"),
1243                    )
1244                })?;
1245            if prepared.is_edit_plan() && !reply.refusals.is_empty() {
1246                refused_paths.insert(captured.file.path.clone());
1247                let before = edit_refusals.len();
1248                for refusal in &reply.refusals {
1249                    for path in refusal
1250                        .paths
1251                        .iter()
1252                        .filter(|path| path.starts_with('/') && path.len() <= 1024)
1253                    {
1254                        edit_refusals.push(subc_control::config::ConfigPlanRefusal {
1255                            module_id: module.clone(),
1256                            path: path.clone(),
1257                            code: "module_review_refused".into(),
1258                            message: "the module refused this field".into(),
1259                            project_id: None,
1260                            workspace_id: None,
1261                        });
1262                    }
1263                }
1264                if edit_refusals.len() == before {
1265                    edit_refusals.push(subc_control::config::ConfigPlanRefusal {
1266                        module_id: module.clone(),
1267                        path: String::new(),
1268                        code: "module_review_refused".into(),
1269                        message: "the module refused the edits".into(),
1270                        project_id: None,
1271                        workspace_id: None,
1272                    });
1273                }
1274                fields.extend(prepared.refused_fields(module)?);
1275                continue;
1276            }
1277            match crate::config_gate::review::checked_fields(
1278                module,
1279                &captured.schema,
1280                base,
1281                prepared.base_schemas.get(module),
1282                &captured.view,
1283                reply,
1284            ) {
1285                Ok(changes) => {
1286                    accepted_paths.insert(captured.file.path.clone());
1287                    fields.extend(changes);
1288                }
1289                Err(error) if error.code == "module_review_refused" => {
1290                    refused_paths.insert(captured.file.path.clone());
1291                    review_refusal.get_or_insert(error);
1292                }
1293                Err(error) => {
1294                    return Err(error.with_settings_review_paths(vec![captured.file.path.clone()]))
1295                }
1296            }
1297        }
1298        for module in unavailable_rereviews {
1299            prepared.review_modules.remove(&module);
1300            prepared.rereview_modules.remove(&module);
1301        }
1302        let mut project_replies = Vec::new();
1303        for (tuple, review) in prepared.project_reviews() {
1304            let paths = || {
1305                review
1306                    .approval
1307                    .view
1308                    .layers
1309                    .iter()
1310                    .filter_map(|layer| layer.path.as_ref().map(std::path::PathBuf::from))
1311                    .collect()
1312            };
1313            let bytes = self
1314                .review_config_tuple(
1315                    &runtime,
1316                    &tuple.module,
1317                    review.base.as_ref(),
1318                    &review.approval.view,
1319                )
1320                .await
1321                .map_err(|error| error.with_settings_review_paths(paths()))?;
1322            let reply: subc_protocol::config::ConfigReviewReply = serde_json::from_slice(&bytes)
1323                .map_err(|_| {
1324                    GateError::new(
1325                        "module_review_invalid",
1326                        format!("{}: malformed project config.review reply", tuple.module),
1327                    )
1328                })?;
1329            let changed = crate::config_gate::review::changed_project_review_paths(
1330                review.base.as_ref(),
1331                &review.approval.view,
1332            );
1333            if prepared.is_edit_plan() {
1334                refused_paths.extend(crate::config_gate::review::attributed_review_refusals(
1335                    review.base.as_ref(),
1336                    &review.approval.view,
1337                    &reply.refusals,
1338                ));
1339            }
1340            project_replies.push((tuple.clone(), reply, paths(), changed));
1341        }
1342        for (tuple, reply, paths, changed) in project_replies {
1343            if prepared.is_edit_plan() && !reply.refusals.is_empty() {
1344                prepared.refuse_project_review(&tuple, &reply);
1345            } else {
1346                match prepared.accept_project_review(&tuple, reply) {
1347                    Ok(changes) => {
1348                        accepted_paths.extend(changed);
1349                        fields.extend(changes);
1350                    }
1351                    Err(error) if error.code == "module_review_refused" => {
1352                        refused_paths.extend(error.settings_review_paths.iter().cloned());
1353                        review_refusal.get_or_insert(error);
1354                    }
1355                    Err(error) => return Err(error.with_settings_review_paths(paths)),
1356                }
1357            }
1358        }
1359        accepted_paths.retain(|path| !refused_paths.contains(path));
1360        if !accepted_paths.is_empty() {
1361            config_work(runtime.clone(), ConfigWake::Delivery, move |owner| {
1362                owner.clear_settings_review_success(review_base, &accepted_paths)
1363            })
1364            .await?;
1365        }
1366        if let Some(error) = review_refusal {
1367            return Err(error.with_settings_review_paths(refused_paths.into_iter().collect()));
1368        }
1369        if prepared.capture_refused() {
1370            let view = runtime
1371                .on_blocking(move |owner| {
1372                    owner.capture_refusal(&prepared)?.ok_or_else(|| {
1373                        GateError::new("module_review_invalid", "project refusal is absent")
1374                    })
1375                })
1376                .await?;
1377            return Ok(view);
1378        }
1379        prepared.add_edit_refusals(edit_refusals);
1380        fields.extend(prepared.unreviewed_fields()?);
1381        config_work(runtime, ConfigWake::Delivery, move |owner| {
1382                    owner.finish_plan(prepared, move |old, new| {
1383                        let mut changeset = crate::config_gate::runtime::daemon_review(old, new)?;
1384                        changeset.fields = fields;
1385                        let mut effects: std::collections::BTreeMap<String,std::collections::BTreeMap<String,Vec<String>>> = Default::default();
1386                        for field in changeset.fields.iter().filter(|field| field.project_id.is_none()) {
1387                            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();
1388                            effects.entry(field.module_id.clone()).or_default().entry(kind).or_default().push(field.path.clone());
1389                        }
1390                        if changeset.fields.iter().any(|field| field.project_id.is_none() && field.apply != subc_config::ApplyKind::Live) {
1391                            changeset.apply_plan = serde_json::json!({"daemon_effects":changeset.apply_plan,"modules":effects});
1392                        }
1393                        Ok(changeset)
1394                    })
1395                })
1396                .await
1397    }
1398
1399    async fn review_config_tuple(
1400        &self,
1401        runtime: &Arc<crate::config_gate::runtime::RuntimeOwner>,
1402        module: &str,
1403        base: Option<&subc_protocol::config::ConfigView>,
1404        candidate: &subc_protocol::config::ConfigView,
1405    ) -> Result<Vec<u8>, GateError> {
1406        #[cfg(test)]
1407        if let Some(reply) = self
1408            .config_review_test_replies
1409            .get(module)
1410            .or(self.config_review_test_reply.as_ref())
1411        {
1412            if let Some(seen) = &self.config_review_test_seen {
1413                let _ = seen.send(module.into());
1414            }
1415            if self
1416                .config_review_test_refuse
1417                .lock()
1418                .unwrap()
1419                .contains(module)
1420            {
1421                let refusal = subc_protocol::config::ConfigReviewReply::new(
1422                    vec![],
1423                    vec![subc_protocol::config::ConfigReviewRefusal::new(
1424                        "refused",
1425                        vec!["/limit".into()],
1426                        vec![],
1427                    )],
1428                );
1429                return Ok(serde_json::to_vec(&refusal).unwrap());
1430            }
1431            use std::sync::atomic::Ordering;
1432            if self
1433                .config_review_test_fail_once
1434                .swap(false, Ordering::Relaxed)
1435            {
1436                return Err(GateError::new(
1437                    "approval_surface_unavailable",
1438                    "module reviewer temporarily unavailable",
1439                ));
1440            }
1441            return serde_json::to_vec(reply).map_err(|_| {
1442                GateError::new(
1443                    "module_review_invalid",
1444                    "could not encode the fixture review",
1445                )
1446            });
1447        }
1448        let registration = self
1449            .registry
1450            .get_module(module)
1451            .map_err(|_| GateError::new("config_unavailable", "registry is unavailable"))?
1452            .ok_or_else(|| {
1453                GateError::new(
1454                    "module_review_unavailable",
1455                    format!("{module}: no active reviewer"),
1456                )
1457            })?;
1458        let admission = self.review_admission();
1459        let reviewer = registration.clone();
1460        config_work(runtime.clone(), ConfigWake::None, move |_| {
1461            admission.check(&reviewer)
1462        })
1463        .await?;
1464        if !registration
1465            .control_ops
1466            .iter()
1467            .any(|op| op == "config.review")
1468        {
1469            return Err(GateError::new(
1470                "module_review_unavailable",
1471                format!("{module}: config.review is not opted in"),
1472            ));
1473        }
1474        let request = subc_protocol::config::ConfigReviewRequest::new(
1475            base.map_or(0, |view| view.generation),
1476            candidate.layers.clone(),
1477            base.cloned(),
1478        );
1479        let bytes = serde_json::to_vec(&request).map_err(|_| {
1480            GateError::new("config_unavailable", "could not encode immutable review")
1481        })?;
1482        self.config_rpc(
1483            runtime,
1484            module,
1485            registration.connection_id,
1486            "config.review",
1487            bytes,
1488        )
1489        .await
1490    }
1491
1492    #[cfg(test)]
1493    async fn config_approval_facts(&self, ctx: &RouteCtx) -> ApprovalFacts {
1494        let phone = self.config_phone_surface().await;
1495        self.config_approval_facts_with_phone(ctx, phone).await
1496    }
1497
1498    async fn config_apply_facts(
1499        &self,
1500        ctx: &RouteCtx,
1501        phone: Option<crate::config_gate::PhoneSurface>,
1502        daemon_settings: bool,
1503    ) -> ApprovalFacts {
1504        if daemon_settings {
1505            // Only the internal settings worker can select this origin. It still
1506            // needs a response from the trusted phone.
1507            return ApprovalFacts {
1508                connection: ctx.connection_id.get(),
1509                owner_uid: true,
1510                desktop_app: false,
1511                attested_operator_app: false,
1512                os_prompt_available: false,
1513                phone,
1514                caller: crate::caller_identity::CallerIdentity::daemon_settings(),
1515            };
1516        }
1517        self.config_approval_facts_with_phone(ctx, phone).await
1518    }
1519
1520    async fn config_approval_facts_with_phone(
1521        &self,
1522        ctx: &RouteCtx,
1523        phone: Option<crate::config_gate::PhoneSurface>,
1524    ) -> ApprovalFacts {
1525        let os_policy = crate::config_gate::os_prompt_policy_present();
1526        #[cfg(any(test, feature = "test-support"))]
1527        let os_policy = os_policy
1528            || self
1529                .config_runtime
1530                .as_ref()
1531                .is_some_and(|owner| owner.os_prompt_policy_for_tests());
1532        let desktop = self
1533            .config_desktop_identity(ctx.connection_id)
1534            .await
1535            .unwrap_or(false);
1536        ApprovalFacts {
1537            connection: ctx.connection_id.get(),
1538            owner_uid: self.config_owner_connection(ctx.connection_id),
1539            desktop_app: desktop,
1540            attested_operator_app: desktop && !cfg!(feature = "dev-desktop-approval"),
1541            os_prompt_available: config_os_prompt_available(
1542                self.forwarding.operator_confirms().config_gate_ready(),
1543                os_policy,
1544            ),
1545            phone,
1546            caller: self.resolve_caller(ctx.connection_id).await,
1547        }
1548    }
1549
1550    // The caller holds Callosum's module gate while allocating its RPC or
1551    // committing approval. This snapshot grants nothing until revalidated there.
1552    async fn config_phone_surface(&self) -> Option<crate::config_gate::PhoneSurface> {
1553        self.config_phone_surface_checked(true, None).await
1554    }
1555
1556    async fn config_phone_surface_snapshot(&self) -> Option<crate::config_gate::PhoneSurface> {
1557        self.config_phone_surface_checked(false, None).await
1558    }
1559
1560    async fn config_phone_surface_checked(
1561        &self,
1562        content: bool,
1563        publication: Option<&crate::config_gate::runtime::Published>,
1564    ) -> Option<crate::config_gate::PhoneSurface> {
1565        if self.config_runtime.as_ref().is_some_and(|owner| {
1566            publication.map_or_else(|| owner.is_recovering(), |view| view.is_recovering())
1567        }) {
1568            return None;
1569        }
1570        if !self.operator_app_policy.phone_enabled {
1571            return None;
1572        }
1573        let runtime = self.config_runtime.as_ref()?;
1574        let (_, registrations) = self.registry.list_modules_with_nonce_verification().ok()?;
1575        let (registration, verified) = registrations
1576            .into_iter()
1577            .find(|(registration, _)| registration.manifest.module_id == "callosum")?;
1578        if !verified
1579            || !registration.ready
1580            || !registration
1581                .control_ops
1582                .iter()
1583                .any(|op| op == subc_protocol::consent::CONSENT_V1)
1584        {
1585            return None;
1586        }
1587        let _spawn = self
1588            .supervisor
1589            .registration_spawn(registration.connection_id)?;
1590        if !self
1591            .forwarding
1592            .active_module_endpoint("callosum")
1593            .ok()
1594            .flatten()
1595            .is_some_and(|endpoint| endpoint.connection_id == registration.connection_id)
1596        {
1597            return None;
1598        }
1599        // Configuration approval requires a channel-bound phone launch.
1600        // Enabling configuration gating invalidates legacy launch nonces,
1601        // including an old registration whose process is still draining.
1602        let module = self.supervisor.get("callosum")?;
1603        let status = module.status().ok()?;
1604        let (spec, _) = module.configuration().ok()?;
1605        if !self.supervisor.registration_snapshot_is_current_live(
1606            &self.registry,
1607            "callosum",
1608            registration.connection_id,
1609            None,
1610        ) || !spec.reserved
1611            || !status.enabled
1612            || !status.process_alive
1613            || !status.registration_active
1614        {
1615            return None;
1616        }
1617        let connection = registration.connection_id;
1618        let approved = if content {
1619            runtime
1620                .on_blocking(move |owner| owner.approved_phone_entry(connection))
1621                .await
1622                .ok()??
1623        } else {
1624            if let Some(snapshot) = publication {
1625                runtime.polled_phone_entry_from(snapshot, connection)?
1626            } else {
1627                runtime.polled_phone_entry(connection)?
1628            }
1629        };
1630        if !approved.enabled || approved.module_spec() != spec {
1631            return None;
1632        }
1633        if content {
1634            let supervisor = self.supervisor.clone();
1635            let registry = self.registry.clone();
1636            if !runtime
1637                .on_blocking(move |_| {
1638                    Ok(supervisor
1639                        .registration_is_current_live(&registry, "callosum", connection, None))
1640                })
1641                .await
1642                .ok()?
1643            {
1644                return None;
1645            }
1646        }
1647        if !self.supervisor.registration_snapshot_is_current_live(
1648            &self.registry,
1649            "callosum",
1650            registration.connection_id,
1651            None,
1652        ) {
1653            return None;
1654        }
1655        Some(crate::config_gate::PhoneSurface {
1656            module_id: "callosum".into(),
1657            connection: connection.get(),
1658            spawn_generation: status.spawn_generation,
1659            enabled_by_policy: true,
1660            opted_in: true,
1661            approved_declaration: true,
1662            reserved: true,
1663            channel_registered: true,
1664            program_admitted: true,
1665            active_registration: true,
1666        })
1667    }
1668
1669    async fn config_rpc(
1670        &self,
1671        runtime: &Arc<crate::config_gate::runtime::RuntimeOwner>,
1672        module: &str,
1673        expected_connection: ConnectionId,
1674        op: &str,
1675        bytes: Vec<u8>,
1676    ) -> std::result::Result<Vec<u8>, GateError> {
1677        let gate = runtime.module_gate(module)?;
1678        let pending = {
1679            let _gate = gate.lock().await;
1680            let registration = self
1681                .registry
1682                .get_module(module)
1683                .map_err(|_| GateError::new("config_unavailable", "registry unavailable"))?
1684                .ok_or_else(|| {
1685                    GateError::new(
1686                        "module_review_unavailable",
1687                        format!("{module}: no active target"),
1688                    )
1689                })?;
1690            let pending = self
1691                .forwarding
1692                .begin_module_control_rpc_for(module, op, Instant::now() + CONFIG_REVIEW_TIMEOUT)
1693                .map_err(|_| {
1694                    GateError::new(
1695                        "module_review_unavailable",
1696                        format!("{module}: target unavailable"),
1697                    )
1698                })?;
1699            if pending.endpoint.connection_id != registration.connection_id
1700                || registration.connection_id != expected_connection
1701            {
1702                let _ = self
1703                    .forwarding
1704                    .cancel_module_control_rpc(pending.endpoint, pending.corr);
1705                return Err(GateError::new(
1706                    "not_delivery_target",
1707                    "registry and forwarding targets differ",
1708                ));
1709            }
1710            pending
1711        };
1712        let PendingModuleControlRpc {
1713            endpoint,
1714            module_sink,
1715            negotiated_ver,
1716            corr,
1717            receiver,
1718        } = pending;
1719        let mut guard = ModuleControlRpcGuard::new(self.forwarding.clone(), endpoint, corr);
1720        let deadline = Instant::now() + CONFIG_REVIEW_TIMEOUT;
1721        let frame = Frame::build_with_version(
1722            negotiated_ver,
1723            FrameType::Request,
1724            control_flags(),
1725            0,
1726            0,
1727            corr,
1728            bytes,
1729        )
1730        .map_err(|_| GateError::new("config_unavailable", "could not encode config request"))?;
1731        timeout_at(deadline, module_sink.send(frame))
1732            .await
1733            .map_err(|_| {
1734                GateError::new(
1735                    "config_review_timeout",
1736                    format!("{module}: config.review exceeded its 30-second deadline; plan remains unapproved"),
1737                )
1738            })?
1739            .map_err(|_| {
1740                GateError::new(
1741                    "module_review_unavailable",
1742                    format!("{module}: target disconnected"),
1743                )
1744            })?;
1745        let outcome = timeout_at(deadline, receiver)
1746            .await
1747            .map_err(|_| {
1748                GateError::new(
1749                    "config_review_timeout",
1750                    format!("{module}: config.review exceeded its 30-second deadline; plan remains unapproved"),
1751                )
1752            })?
1753            .map_err(|_| {
1754                GateError::new(
1755                    "module_review_unavailable",
1756                    format!("{module}: target disconnected"),
1757                )
1758            })?;
1759        guard.disarm();
1760        match outcome {
1761            ModuleControlRpcOutcome::RawResponse(bytes) => Ok(bytes),
1762            ModuleControlRpcOutcome::DeadlineElapsed => Err(GateError::new("config_review_timeout",format!("{module}: config.review exceeded its 30-second deadline; plan remains unapproved"))),
1763            _ => Err(GateError::new(
1764                "module_review_unavailable",
1765                format!("{module}: config request was not answered"),
1766            )),
1767        }
1768    }
1769
1770    /// Execute only the presence part of an engine-selected challenge. The
1771    /// runtime owner still rechecks the inputs and surface before committing.
1772    pub async fn confirm_config_gate_presence(
1773        &self,
1774        ctx: &RouteCtx,
1775        frame: &Frame,
1776        challenge: &ApprovalChallenge,
1777    ) -> PresenceDecision {
1778        let Some(text) = challenge.prompt() else {
1779            return PresenceDecision::Unavailable;
1780        };
1781        let caller = self.resolve_caller(ctx.connection_id).await;
1782        let key = crate::operator_confirm::DeclineKey::for_caller(&caller, ctx.connection_id);
1783        // Neither privileged_operator_prompt nor operator-app shortcut policy
1784        // is consulted: every desktop gate review requires OS presence.
1785        let outcome = self
1786            .forwarding
1787            .operator_confirms()
1788            .approve_config_gate(ctx, frame, text.to_owned(), caller.description(), key)
1789            .await;
1790        PresenceDecision::from_operator_outcome(&outcome)
1791    }
1792}
1793
1794fn config_os_prompt_available(provider_ready: bool, policy_present: bool) -> bool {
1795    provider_ready && policy_present
1796}
1797
1798enum ConfigWake {
1799    None,
1800    Delivery,
1801}
1802
1803async fn config_work<T: Send + 'static>(
1804    runtime: Arc<crate::config_gate::runtime::RuntimeOwner>,
1805    wake: ConfigWake,
1806    work: impl FnOnce(Arc<crate::config_gate::runtime::RuntimeOwner>) -> std::result::Result<T, GateError>
1807        + Send
1808        + 'static,
1809) -> std::result::Result<T, GateError> {
1810    runtime
1811        .on_blocking(move |owner| {
1812            let result = work(owner.clone());
1813            if matches!(wake, ConfigWake::Delivery) {
1814                owner.notify_delivery_changed();
1815            }
1816            result
1817        })
1818        .await
1819}
1820
1821pub(super) fn config_error_frame(frame: &Frame, error: GateError) -> Result<Frame, RouterError> {
1822    control_error_body_frame(
1823        frame,
1824        ErrorBody {
1825            code: error.code,
1826            message: error.detail,
1827            detail: error.wire_detail.map(|detail| *detail),
1828        },
1829    )
1830}
1831
1832pub(super) fn now_ms() -> u64 {
1833    std::time::SystemTime::now()
1834        .duration_since(std::time::UNIX_EPOCH)
1835        .unwrap_or_default()
1836        .as_millis()
1837        .min(u128::from(u64::MAX)) as u64
1838}
1839
1840#[cfg(test)]
1841mod tests;
1842
1843#[cfg(test)]
1844mod desktop_tests;