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