Skip to main content

subc_daemon/config_gate/
approval.rs

1use crate::caller_identity::CallerIdentity;
2use crate::privileged_prompt::gate_prompt_text;
3use subc_config::{Digest, RecordedValue};
4use subc_protocol::consent::{ConsentRequest, ConsentResponse};
5
6use super::{ConfigGate, GateError, GateSnapshot, InputKey, PendingPlan, PlanKind, Result};
7
8/// One phone card may wait for five minutes, including its outbound write.
9pub const CONFIG_PHONE_APPROVAL_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(300);
10use crate::config_store::ConfigStore;
11
12/// Observed facts from the active registration, its approved declaration/entry,
13/// and the supervisor's current spawn. A claimed module id alone proves none of
14/// these. The owner re-reads every fact when a consent reply arrives.
15#[derive(Clone, Debug, PartialEq, Eq)]
16pub struct PhoneSurface {
17    pub module_id: String,
18    pub connection: u64,
19    pub spawn_generation: u64,
20    pub enabled_by_policy: bool,
21    pub opted_in: bool,
22    pub approved_declaration: bool,
23    pub reserved: bool,
24    pub channel_registered: bool,
25    pub program_admitted: bool,
26    pub active_registration: bool,
27}
28impl PhoneSurface {
29    fn trusted(&self) -> bool {
30        self.module_id == "callosum"
31            && self.enabled_by_policy
32            && self.opted_in
33            && self.approved_declaration
34            && self.reserved
35            && self.channel_registered
36            && self.program_admitted
37            && self.active_registration
38    }
39}
40
41/// Built from daemon-observed peer/app state, never deserialized from a request.
42/// Under the development feature, a same-user local connection may present a
43/// complete desktop review without app attestation. Its channel records that
44/// weaker check explicitly; OS presence is still required.
45#[derive(Clone)]
46pub struct ApprovalFacts {
47    pub connection: u64,
48    pub owner_uid: bool,
49    pub desktop_app: bool,
50    pub attested_operator_app: bool,
51    pub os_prompt_available: bool,
52    pub phone: Option<PhoneSurface>,
53    pub caller: CallerIdentity,
54}
55impl ApprovalFacts {
56    fn desktop(&self) -> bool {
57        self.desktop_channel().is_some()
58    }
59    fn desktop_channel(&self) -> Option<subc_config::ApprovalChannel> {
60        if !self.owner_uid {
61            None
62        } else if self.attested_operator_app {
63            Some(subc_config::ApprovalChannel::AttestedDesktop)
64        } else if cfg!(feature = "dev-desktop-approval") && self.desktop_app {
65            Some(subc_config::ApprovalChannel::UnverifiedDevelopmentDesktop)
66        } else {
67            None
68        }
69    }
70}
71
72#[derive(Clone, Debug)]
73pub enum ApprovalChallenge {
74    Desktop {
75        attempt: u64,
76        prompt: String,
77    },
78    OsPrompt {
79        attempt: u64,
80        prompt: String,
81    },
82    Phone {
83        attempt: u64,
84        connection: u64,
85        deadline: tokio::time::Instant,
86        request: Box<ConsentRequest>,
87    },
88}
89impl ApprovalChallenge {
90    pub fn attempt(&self) -> u64 {
91        match self {
92            Self::Desktop { attempt, .. }
93            | Self::OsPrompt { attempt, .. }
94            | Self::Phone { attempt, .. } => *attempt,
95        }
96    }
97    pub fn prompt(&self) -> Option<&str> {
98        match self {
99            Self::Desktop { prompt, .. } | Self::OsPrompt { prompt, .. } => Some(prompt),
100            Self::Phone { .. } => None,
101        }
102    }
103}
104
105#[derive(Clone, Copy, Debug, PartialEq, Eq)]
106pub enum PresenceDecision {
107    InteractiveApproval,
108    Declined,
109    Unavailable,
110}
111
112pub enum ApprovalReply {
113    Presence(PresenceDecision),
114    Phone {
115        connection: u64,
116        correlation: u64,
117        response: Option<ConsentResponse>,
118    },
119}
120
121pub(super) enum Surface {
122    Desktop {
123        channel: subc_config::ApprovalChannel,
124    },
125    Os,
126    Phone {
127        facts: PhoneSurface,
128        request: Box<ConsentRequest>,
129        correlation: Option<u64>,
130    },
131}
132pub(super) struct Attempt {
133    digest: Digest,
134    caller: u64,
135    surface: Surface,
136}
137
138fn unavailable() -> GateError {
139    GateError::new(
140        "approval_surface_unavailable",
141        "required trusted review surface is unavailable",
142    )
143}
144fn declined() -> GateError {
145    GateError::new("approval_declined", "approval was declined or unanswered")
146}
147
148impl PendingPlan {
149    fn desktop_only(&self) -> bool {
150        if self.recovery && self.kind == PlanKind::Unstamp {
151            return false;
152        }
153        self.kind == PlanKind::Stamp
154            || self.callosum_entry_changed
155            || self
156                .view
157                .plan
158                .changeset
159                .launch_manifests
160                .contains_key("callosum")
161            || self
162                .changed
163                .iter()
164                .any(|key| key.module() == Some("callosum"))
165            || self
166                .view
167                .plan
168                .changeset
169                .fields
170                .iter()
171                .any(|field| field.module_id == "callosum")
172    }
173
174    fn small_prompt(&self, caller: &CallerIdentity) -> Option<String> {
175        if self.recovery && self.kind == PlanKind::Unstamp {
176            return gate_prompt_text("Config files become authoritative again", &[], caller);
177        }
178        let changes = &self.view.plan.changeset;
179        if self.kind != PlanKind::Change
180            || self.desktop_only()
181            || changes.fields.len() != 1
182            || !changes.policy_changes.is_empty()
183            || !changes.launch_manifests.is_empty()
184            || !changes.affected_projects.is_empty()
185            || !changes.apply_plan["review"].is_null()
186            || self.changed.len() != 1
187            || self
188                .changed
189                .iter()
190                .any(|key| !matches!(key, InputKey::Layer { .. }))
191        {
192            return None;
193        }
194        let field = &changes.fields[0];
195        if self
196            .changed
197            .iter()
198            .any(|key| key.module() != Some(field.module_id.as_str()))
199        {
200            return None;
201        }
202        if field.project_id.is_some() || !field.reasons.is_empty() {
203            return None;
204        }
205        let scalar = |value: &RecordedValue| match value {
206            RecordedValue::Value { value }
207                if value.is_boolean() || value.is_number() || value.is_string() =>
208            {
209                // Inspect the original string too: JSON escaping would otherwise
210                // hide a sanitizer substitution behind printable backslashes.
211                if let Some(text) = value.as_str() {
212                    gate_prompt_text(text, &[], &CallerIdentity::default())?;
213                }
214                serde_json::to_string(value).ok()
215            }
216            _ => None,
217        };
218        let old = scalar(&field.old)?;
219        let new = scalar(&field.new)?;
220        let effect = serde_json::to_value(field.apply).ok()?;
221        let old_source = serde_json::to_value(field.old_source).ok()?;
222        let new_source = serde_json::to_value(field.new_source).ok()?;
223        let description = format!(
224            "Set {} {} from {old} ({}) to {new} ({}); {}",
225            field.module_id,
226            field.path,
227            old_source.as_str()?,
228            new_source.as_str()?,
229            effect.as_str()?
230        );
231        gate_prompt_text(&description, &[&field.module_id, &field.path], caller)
232    }
233}
234
235impl ConfigGate {
236    pub(crate) fn has_open_approval(&self, digest: &Digest) -> bool {
237        self.attempts
238            .values()
239            .any(|attempt| &attempt.digest == digest)
240    }
241
242    pub(crate) fn approval_digest(&self, attempt: u64) -> Result<Digest> {
243        self.attempts
244            .get(&attempt)
245            .map(|attempt| attempt.digest.clone())
246            .ok_or_else(unavailable)
247    }
248
249    pub(crate) fn connection_approval_digests(&self, connection: u64) -> Vec<Digest> {
250        self.attempts
251            .values()
252            .filter(|attempt| attempt.caller == connection)
253            .map(|attempt| attempt.digest.clone())
254            .collect()
255    }
256    pub(crate) fn approval_modules(
257        &self,
258        attempt: u64,
259    ) -> Result<std::collections::BTreeSet<String>> {
260        let attempt = self.attempts.get(&attempt).ok_or_else(unavailable)?;
261        self.plan_modules(&attempt.digest)
262    }
263
264    pub(crate) fn approval_gate_modules(
265        &self,
266        attempt: u64,
267    ) -> Result<std::collections::BTreeSet<String>> {
268        let pending = self.attempts.get(&attempt).ok_or_else(unavailable)?;
269        let mut modules = self.plan_modules(&pending.digest)?;
270        if matches!(pending.surface, Surface::Phone { .. }) {
271            modules.insert("callosum".into());
272        }
273        Ok(modules)
274    }
275
276    pub(crate) fn cancel_connection_approvals(&mut self, connection: u64) -> Vec<u64> {
277        let ids = self
278            .attempts
279            .iter()
280            .filter_map(|(id, attempt)| (attempt.caller == connection).then_some(*id))
281            .collect();
282        self.attempts
283            .retain(|_, attempt| attempt.caller != connection);
284        ids
285    }
286    /// Select a required surface. Legacy `log` policy and operator-app shortcuts
287    /// are deliberately absent: neither proves review of an immutable plan.
288    pub fn begin_approval(
289        &mut self,
290        digest: &Digest,
291        store: &mut ConfigStore,
292        current: &GateSnapshot,
293        facts: &ApprovalFacts,
294    ) -> Result<ApprovalChallenge> {
295        let plan = self
296            .plans
297            .get(digest)
298            .ok_or_else(|| GateError::new("plan_unknown", "plan is absent or already applied"))?;
299        if !plan.view.refusals.is_empty() {
300            return Err(GateError::new(
301                "plan_refused",
302                "the plan contains refused edits",
303            ));
304        }
305        Self::fresh(plan, store, current)?;
306        if !facts.owner_uid {
307            return Err(unavailable());
308        }
309        if self.attempts.len() >= 4 {
310            return Err(GateError::new("config_busy", "approval queue is full"));
311        }
312        self.next_attempt = self.next_attempt.checked_add(1).ok_or_else(unavailable)?;
313        let id = self.next_attempt;
314        let (surface, challenge) = if let Some(channel) = facts
315            .desktop_channel()
316            .filter(|_| !(plan.recovery && plan.kind == PlanKind::Unstamp))
317        {
318            if !facts.os_prompt_available {
319                return Err(unavailable());
320            }
321            let prompt =
322                gate_prompt_text(&format!("Approve config plan {digest}"), &[], &facts.caller)
323                    .ok_or_else(unavailable)?;
324            (
325                Surface::Desktop { channel },
326                ApprovalChallenge::Desktop {
327                    attempt: id,
328                    prompt,
329                },
330            )
331        } else if plan.desktop_only() {
332            return Err(unavailable());
333        } else if let Some(prompt) = plan.small_prompt(&facts.caller) {
334            if !facts.os_prompt_available {
335                return Err(unavailable());
336            }
337            (
338                Surface::Os,
339                ApprovalChallenge::OsPrompt {
340                    attempt: id,
341                    prompt,
342                },
343            )
344        } else {
345            let phone = facts
346                .phone
347                .as_ref()
348                .filter(|phone| !plan.recovery && phone.trusted())
349                .ok_or_else(unavailable)?;
350            let request =
351                Box::new(ConsentRequest::new(plan.view.plan.clone()).map_err(GateError::invalid)?);
352            (
353                Surface::Phone {
354                    facts: phone.clone(),
355                    request: request.clone(),
356                    correlation: None,
357                },
358                ApprovalChallenge::Phone {
359                    attempt: id,
360                    connection: phone.connection,
361                    deadline: tokio::time::Instant::now() + CONFIG_PHONE_APPROVAL_TIMEOUT,
362                    request,
363                },
364            )
365        };
366        self.attempts.insert(
367            id,
368            Attempt {
369                digest: digest.clone(),
370                caller: facts.connection,
371                surface,
372            },
373        );
374        Ok(challenge)
375    }
376
377    /// Complete under the commit lock after a fresh snapshot and active-surface
378    /// lookup. The transport must match a response frame, not an unsolicited
379    /// request. A wrong answer consumes this attempt, never the pending plan.
380    pub fn finish_approval(
381        &mut self,
382        attempt: u64,
383        reply: ApprovalReply,
384        store: &mut ConfigStore,
385        current: &GateSnapshot,
386        facts: &ApprovalFacts,
387        now_ms: u64,
388    ) -> Result<u64> {
389        self.finish_approval_with_precommit(
390            attempt,
391            reply,
392            store,
393            current,
394            facts,
395            now_ms,
396            || Ok(()),
397        )
398    }
399
400    #[allow(clippy::too_many_arguments)]
401    pub(super) fn finish_approval_with_precommit(
402        &mut self,
403        attempt: u64,
404        reply: ApprovalReply,
405        store: &mut ConfigStore,
406        current: &GateSnapshot,
407        facts: &ApprovalFacts,
408        now_ms: u64,
409        before_commit: impl FnOnce() -> Result<()>,
410    ) -> Result<u64> {
411        let pending = self.attempts.remove(&attempt).ok_or_else(unavailable)?;
412        if !facts.owner_uid || facts.connection != pending.caller {
413            return Err(unavailable());
414        }
415        let channel = match (&pending.surface, reply) {
416            (Surface::Desktop { channel }, ApprovalReply::Presence(decision)) => {
417                if facts.desktop_channel() != Some(*channel) {
418                    return Err(unavailable());
419                }
420                presence(decision)?;
421                *channel
422            }
423            (Surface::Os, ApprovalReply::Presence(decision)) => {
424                presence(decision)?;
425                subc_config::ApprovalChannel::OsPrompt
426            }
427            (
428                Surface::Phone {
429                    facts: sent,
430                    request,
431                    correlation: sent_correlation,
432                },
433                ApprovalReply::Phone {
434                    connection,
435                    correlation,
436                    response,
437                },
438            ) => {
439                let current = facts
440                    .phone
441                    .as_ref()
442                    .filter(|phone| phone.trusted())
443                    .ok_or_else(unavailable)?;
444                if current != sent
445                    || connection != sent.connection
446                    || Some(correlation) != *sent_correlation
447                {
448                    return Err(unavailable());
449                }
450                let response = response.ok_or_else(declined)?;
451                if !response.approves(request) {
452                    return Err(declined());
453                }
454                subc_config::ApprovalChannel::PhoneCard
455            }
456            _ => return Err(unavailable()),
457        };
458        let plan = self
459            .plans
460            .get(&pending.digest)
461            .ok_or_else(|| GateError::new("plan_unknown", "plan is absent or already applied"))?;
462        Self::fresh(plan, store, current)?;
463        self.commit(
464            &pending.digest,
465            channel,
466            store,
467            current,
468            now_ms,
469            before_commit,
470        )
471    }
472
473    /// Bind the transport's allocated correlation exactly once, before sending.
474    /// Attempt ids and endpoint-scoped wire correlations are different counters.
475    pub(crate) fn bind_phone_rpc(
476        &mut self,
477        attempt: u64,
478        connection: u64,
479        correlation: u64,
480    ) -> Result<()> {
481        let pending = self.attempts.get_mut(&attempt).ok_or_else(unavailable)?;
482        match &mut pending.surface {
483            Surface::Phone {
484                facts,
485                correlation: bound,
486                ..
487            } if facts.connection == connection && bound.is_none() => {
488                *bound = Some(correlation);
489                Ok(())
490            }
491            _ => Err(unavailable()),
492        }
493    }
494
495    pub(crate) fn cancel_approval(&mut self, attempt: u64) {
496        self.attempts.remove(&attempt);
497    }
498
499    pub(crate) fn phone_approval_digests(&self, connection: u64) -> Vec<Digest> {
500        self.attempts.values().filter(|attempt| {
501            matches!(&attempt.surface, Surface::Phone { facts, .. } if facts.connection == connection)
502        }).map(|attempt| attempt.digest.clone()).collect()
503    }
504
505    /// The owner wakes each waiting client with surface-unavailable when the
506    /// supervised callosum connection exits or is replaced by a swap. An old
507    /// phone card must not remain pending until its response deadline.
508    pub fn invalidate_phone(&mut self, connection: u64) -> Vec<u64> {
509        let ids: Vec<_> = self.attempts.iter().filter_map(|(id, attempt)| {
510            matches!(&attempt.surface, Surface::Phone { facts, .. } if facts.connection == connection).then_some(*id)
511        }).collect();
512        for id in &ids {
513            self.attempts.remove(id);
514        }
515        ids
516    }
517}
518
519fn presence(decision: PresenceDecision) -> Result<()> {
520    match decision {
521        PresenceDecision::InteractiveApproval => Ok(()),
522        PresenceDecision::Declined => Err(declined()),
523        PresenceDecision::Unavailable => Err(unavailable()),
524    }
525}
526
527/// Availability is a daemon observation (on Linux, test the per-user action
528/// file as well as provider readiness); missing policy is never a silent grant.
529pub fn missing_surfaces(facts: &ApprovalFacts, recovery: bool) -> Vec<String> {
530    let mut missing = Vec::new();
531    if !facts.desktop() {
532        missing.push("desktop (required for stamp)".into());
533    }
534    if recovery || !facts.phone.as_ref().is_some_and(PhoneSurface::trusted) {
535        missing.push(
536            if recovery {
537                "phone (unavailable in recovery)"
538            } else {
539                "phone"
540            }
541            .into(),
542        );
543    }
544    if !facts.os_prompt_available {
545        missing.push("OS prompt (Linux requires the per-user polkit action file)".into());
546    }
547    missing
548}
549
550/// A present policy is a prerequisite, not a promise that an interactive agent
551/// is reachable. The provider's actual outcome remains authoritative.
552pub fn os_prompt_policy_present() -> bool {
553    #[cfg(target_os = "linux")]
554    {
555        std::path::Path::new(&subc_presence::polkit::action_path(subc_os::effective_uid()))
556            .is_file()
557    }
558    #[cfg(not(target_os = "linux"))]
559    {
560        cfg!(any(target_os = "macos", windows))
561    }
562}