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