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