subc-daemon 0.46.2

Embeddable subc daemon: bootstrap, module supervision, and opaque-byte splice routing.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
use crate::caller_identity::CallerIdentity;
use crate::privileged_prompt::gate_prompt_text;
use subc_config::{Digest, RecordedValue};
use subc_protocol::consent::{ConsentRequest, ConsentResponse};

use super::{ConfigGate, GateError, GateSnapshot, InputKey, PendingPlan, PlanKind, Result};

/// One phone card may wait for five minutes, including its outbound write.
pub const CONFIG_PHONE_APPROVAL_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(300);
use crate::config_store::ConfigStore;

/// Observed facts from the active registration, its approved declaration/entry,
/// and the supervisor's current spawn. A claimed module id alone proves none of
/// these. The owner re-reads every fact when a consent reply arrives.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PhoneSurface {
    pub module_id: String,
    pub connection: u64,
    pub spawn_generation: u64,
    pub enabled_by_policy: bool,
    pub opted_in: bool,
    pub approved_declaration: bool,
    pub reserved: bool,
    pub channel_registered: bool,
    pub program_admitted: bool,
    pub active_registration: bool,
}
impl PhoneSurface {
    fn trusted(&self) -> bool {
        self.module_id == "callosum"
            && self.enabled_by_policy
            && self.opted_in
            && self.approved_declaration
            && self.reserved
            && self.channel_registered
            && self.program_admitted
            && self.active_registration
    }
}

/// Built from daemon-observed peer/app state, never deserialized from a request.
/// Under the development feature, a same-user local connection may present a
/// complete desktop review without app attestation. Its channel records that
/// weaker check explicitly; OS presence is still required.
#[derive(Clone)]
pub struct ApprovalFacts {
    pub connection: u64,
    pub owner_uid: bool,
    pub desktop_app: bool,
    pub attested_operator_app: bool,
    pub os_prompt_available: bool,
    pub phone: Option<PhoneSurface>,
    pub caller: CallerIdentity,
}
impl ApprovalFacts {
    fn desktop(&self) -> bool {
        self.desktop_channel().is_some()
    }
    fn desktop_channel(&self) -> Option<subc_config::ApprovalChannel> {
        if !self.owner_uid {
            None
        } else if self.attested_operator_app {
            Some(subc_config::ApprovalChannel::AttestedDesktop)
        } else if cfg!(feature = "dev-desktop-approval") && self.desktop_app {
            Some(subc_config::ApprovalChannel::UnverifiedDevelopmentDesktop)
        } else {
            None
        }
    }
}

#[derive(Clone, Debug)]
pub enum ApprovalChallenge {
    Desktop {
        attempt: u64,
        prompt: String,
    },
    OsPrompt {
        attempt: u64,
        prompt: String,
    },
    Phone {
        attempt: u64,
        connection: u64,
        deadline: tokio::time::Instant,
        request: Box<ConsentRequest>,
    },
}
impl ApprovalChallenge {
    pub fn attempt(&self) -> u64 {
        match self {
            Self::Desktop { attempt, .. }
            | Self::OsPrompt { attempt, .. }
            | Self::Phone { attempt, .. } => *attempt,
        }
    }
    pub fn prompt(&self) -> Option<&str> {
        match self {
            Self::Desktop { prompt, .. } | Self::OsPrompt { prompt, .. } => Some(prompt),
            Self::Phone { .. } => None,
        }
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum PresenceDecision {
    InteractiveApproval,
    Declined,
    Unavailable,
}

pub enum ApprovalReply {
    Presence(PresenceDecision),
    Phone {
        connection: u64,
        correlation: u64,
        response: Option<ConsentResponse>,
    },
}

pub(super) enum Surface {
    Desktop {
        channel: subc_config::ApprovalChannel,
    },
    Os,
    Phone {
        facts: PhoneSurface,
        request: Box<ConsentRequest>,
        correlation: Option<u64>,
    },
}
pub(super) struct Attempt {
    digest: Digest,
    caller: u64,
    surface: Surface,
}

fn unavailable() -> GateError {
    GateError::new(
        "approval_surface_unavailable",
        "required trusted review surface is unavailable",
    )
}
fn declined() -> GateError {
    GateError::new("approval_declined", "approval was declined or unanswered")
}

impl PendingPlan {
    fn desktop_only(&self) -> bool {
        if self.recovery && self.kind == PlanKind::Unstamp {
            return false;
        }
        self.kind == PlanKind::Stamp
            || self.callosum_entry_changed
            || self
                .view
                .plan
                .changeset
                .launch_manifests
                .contains_key("callosum")
            || self
                .changed
                .iter()
                .any(|key| key.module() == Some("callosum"))
            || self
                .view
                .plan
                .changeset
                .fields
                .iter()
                .any(|field| field.module_id == "callosum")
    }

    fn small_prompt(&self, caller: &CallerIdentity) -> Option<String> {
        if self.recovery && self.kind == PlanKind::Unstamp {
            return gate_prompt_text("Config files become authoritative again", &[], caller);
        }
        let changes = &self.view.plan.changeset;
        if self.kind != PlanKind::Change
            || self.desktop_only()
            || changes.fields.len() != 1
            || !changes.policy_changes.is_empty()
            || !changes.launch_manifests.is_empty()
            || !changes.affected_projects.is_empty()
            || !changes.apply_plan["review"].is_null()
            || self.changed.len() != 1
            || self
                .changed
                .iter()
                .any(|key| !matches!(key, InputKey::Layer { .. }))
        {
            return None;
        }
        let field = &changes.fields[0];
        if self
            .changed
            .iter()
            .any(|key| key.module() != Some(field.module_id.as_str()))
        {
            return None;
        }
        if field.project_id.is_some() || !field.reasons.is_empty() {
            return None;
        }
        let scalar = |value: &RecordedValue| match value {
            RecordedValue::Value { value }
                if value.is_boolean() || value.is_number() || value.is_string() =>
            {
                // Inspect the original string too: JSON escaping would otherwise
                // hide a sanitizer substitution behind printable backslashes.
                if let Some(text) = value.as_str() {
                    gate_prompt_text(text, &[], &CallerIdentity::default())?;
                }
                serde_json::to_string(value).ok()
            }
            _ => None,
        };
        let old = scalar(&field.old)?;
        let new = scalar(&field.new)?;
        let effect = serde_json::to_value(field.apply).ok()?;
        let old_source = serde_json::to_value(field.old_source).ok()?;
        let new_source = serde_json::to_value(field.new_source).ok()?;
        let description = format!(
            "Set {} {} from {old} ({}) to {new} ({}); {}",
            field.module_id,
            field.path,
            old_source.as_str()?,
            new_source.as_str()?,
            effect.as_str()?
        );
        gate_prompt_text(&description, &[&field.module_id, &field.path], caller)
    }
}

impl ConfigGate {
    pub(crate) fn has_open_approval(&self, digest: &Digest) -> bool {
        self.attempts
            .values()
            .any(|attempt| &attempt.digest == digest)
    }

    pub(crate) fn approval_digest(&self, attempt: u64) -> Result<Digest> {
        self.attempts
            .get(&attempt)
            .map(|attempt| attempt.digest.clone())
            .ok_or_else(unavailable)
    }

    pub(crate) fn connection_approval_digests(&self, connection: u64) -> Vec<Digest> {
        self.attempts
            .values()
            .filter(|attempt| attempt.caller == connection)
            .map(|attempt| attempt.digest.clone())
            .collect()
    }
    pub(crate) fn approval_modules(
        &self,
        attempt: u64,
    ) -> Result<std::collections::BTreeSet<String>> {
        let attempt = self.attempts.get(&attempt).ok_or_else(unavailable)?;
        self.plan_modules(&attempt.digest)
    }

    pub(crate) fn approval_gate_modules(
        &self,
        attempt: u64,
    ) -> Result<std::collections::BTreeSet<String>> {
        let pending = self.attempts.get(&attempt).ok_or_else(unavailable)?;
        let mut modules = self.plan_modules(&pending.digest)?;
        if matches!(pending.surface, Surface::Phone { .. }) {
            modules.insert("callosum".into());
        }
        Ok(modules)
    }

    pub(crate) fn cancel_connection_approvals(&mut self, connection: u64) -> Vec<u64> {
        let ids = self
            .attempts
            .iter()
            .filter_map(|(id, attempt)| (attempt.caller == connection).then_some(*id))
            .collect();
        self.attempts
            .retain(|_, attempt| attempt.caller != connection);
        ids
    }
    /// Select a required surface. Legacy `log` policy and operator-app shortcuts
    /// are deliberately absent: neither proves review of an immutable plan.
    pub fn begin_approval(
        &mut self,
        digest: &Digest,
        store: &mut ConfigStore,
        current: &GateSnapshot,
        facts: &ApprovalFacts,
    ) -> Result<ApprovalChallenge> {
        let plan = self
            .plans
            .get(digest)
            .ok_or_else(|| GateError::new("plan_unknown", "plan is absent or already applied"))?;
        Self::fresh(plan, store, current)?;
        if !facts.owner_uid {
            return Err(unavailable());
        }
        if self.attempts.len() >= 4 {
            return Err(GateError::new("config_busy", "approval queue is full"));
        }
        self.next_attempt = self.next_attempt.checked_add(1).ok_or_else(unavailable)?;
        let id = self.next_attempt;
        let (surface, challenge) = if let Some(channel) = facts
            .desktop_channel()
            .filter(|_| !(plan.recovery && plan.kind == PlanKind::Unstamp))
        {
            if !facts.os_prompt_available {
                return Err(unavailable());
            }
            let prompt =
                gate_prompt_text(&format!("Approve config plan {digest}"), &[], &facts.caller)
                    .ok_or_else(unavailable)?;
            (
                Surface::Desktop { channel },
                ApprovalChallenge::Desktop {
                    attempt: id,
                    prompt,
                },
            )
        } else if plan.desktop_only() {
            return Err(unavailable());
        } else if let Some(prompt) = plan.small_prompt(&facts.caller) {
            if !facts.os_prompt_available {
                return Err(unavailable());
            }
            (
                Surface::Os,
                ApprovalChallenge::OsPrompt {
                    attempt: id,
                    prompt,
                },
            )
        } else {
            let phone = facts
                .phone
                .as_ref()
                .filter(|phone| !plan.recovery && phone.trusted())
                .ok_or_else(unavailable)?;
            let request =
                Box::new(ConsentRequest::new(plan.view.plan.clone()).map_err(GateError::invalid)?);
            (
                Surface::Phone {
                    facts: phone.clone(),
                    request: request.clone(),
                    correlation: None,
                },
                ApprovalChallenge::Phone {
                    attempt: id,
                    connection: phone.connection,
                    deadline: tokio::time::Instant::now() + CONFIG_PHONE_APPROVAL_TIMEOUT,
                    request,
                },
            )
        };
        self.attempts.insert(
            id,
            Attempt {
                digest: digest.clone(),
                caller: facts.connection,
                surface,
            },
        );
        Ok(challenge)
    }

    /// Complete under the commit lock after a fresh snapshot and active-surface
    /// lookup. The transport must match a response frame, not an unsolicited
    /// request. A wrong answer consumes this attempt, never the pending plan.
    pub fn finish_approval(
        &mut self,
        attempt: u64,
        reply: ApprovalReply,
        store: &mut ConfigStore,
        current: &GateSnapshot,
        facts: &ApprovalFacts,
        now_ms: u64,
    ) -> Result<u64> {
        self.finish_approval_with_precommit(
            attempt,
            reply,
            store,
            current,
            facts,
            now_ms,
            || Ok(()),
        )
    }

    #[allow(clippy::too_many_arguments)]
    pub(super) fn finish_approval_with_precommit(
        &mut self,
        attempt: u64,
        reply: ApprovalReply,
        store: &mut ConfigStore,
        current: &GateSnapshot,
        facts: &ApprovalFacts,
        now_ms: u64,
        before_commit: impl FnOnce() -> Result<()>,
    ) -> Result<u64> {
        let pending = self.attempts.remove(&attempt).ok_or_else(unavailable)?;
        if !facts.owner_uid || facts.connection != pending.caller {
            return Err(unavailable());
        }
        let channel = match (&pending.surface, reply) {
            (Surface::Desktop { channel }, ApprovalReply::Presence(decision)) => {
                if facts.desktop_channel() != Some(*channel) {
                    return Err(unavailable());
                }
                presence(decision)?;
                *channel
            }
            (Surface::Os, ApprovalReply::Presence(decision)) => {
                presence(decision)?;
                subc_config::ApprovalChannel::OsPrompt
            }
            (
                Surface::Phone {
                    facts: sent,
                    request,
                    correlation: sent_correlation,
                },
                ApprovalReply::Phone {
                    connection,
                    correlation,
                    response,
                },
            ) => {
                let current = facts
                    .phone
                    .as_ref()
                    .filter(|phone| phone.trusted())
                    .ok_or_else(unavailable)?;
                if current != sent
                    || connection != sent.connection
                    || Some(correlation) != *sent_correlation
                {
                    return Err(unavailable());
                }
                let response = response.ok_or_else(declined)?;
                if !response.approves(request) {
                    return Err(declined());
                }
                subc_config::ApprovalChannel::PhoneCard
            }
            _ => return Err(unavailable()),
        };
        let plan = self
            .plans
            .get(&pending.digest)
            .ok_or_else(|| GateError::new("plan_unknown", "plan is absent or already applied"))?;
        Self::fresh(plan, store, current)?;
        self.commit(
            &pending.digest,
            channel,
            store,
            current,
            now_ms,
            before_commit,
        )
    }

    /// Bind the transport's allocated correlation exactly once, before sending.
    /// Attempt ids and endpoint-scoped wire correlations are different counters.
    pub(crate) fn bind_phone_rpc(
        &mut self,
        attempt: u64,
        connection: u64,
        correlation: u64,
    ) -> Result<()> {
        let pending = self.attempts.get_mut(&attempt).ok_or_else(unavailable)?;
        match &mut pending.surface {
            Surface::Phone {
                facts,
                correlation: bound,
                ..
            } if facts.connection == connection && bound.is_none() => {
                *bound = Some(correlation);
                Ok(())
            }
            _ => Err(unavailable()),
        }
    }

    pub(crate) fn cancel_approval(&mut self, attempt: u64) {
        self.attempts.remove(&attempt);
    }

    pub(crate) fn phone_approval_digests(&self, connection: u64) -> Vec<Digest> {
        self.attempts.values().filter(|attempt| {
            matches!(&attempt.surface, Surface::Phone { facts, .. } if facts.connection == connection)
        }).map(|attempt| attempt.digest.clone()).collect()
    }

    /// The owner wakes each waiting client with surface-unavailable when the
    /// supervised callosum connection exits or is replaced by a swap. An old
    /// phone card must not remain pending until its response deadline.
    pub fn invalidate_phone(&mut self, connection: u64) -> Vec<u64> {
        let ids: Vec<_> = self.attempts.iter().filter_map(|(id, attempt)| {
            matches!(&attempt.surface, Surface::Phone { facts, .. } if facts.connection == connection).then_some(*id)
        }).collect();
        for id in &ids {
            self.attempts.remove(id);
        }
        ids
    }
}

fn presence(decision: PresenceDecision) -> Result<()> {
    match decision {
        PresenceDecision::InteractiveApproval => Ok(()),
        PresenceDecision::Declined => Err(declined()),
        PresenceDecision::Unavailable => Err(unavailable()),
    }
}

/// Availability is a daemon observation (on Linux, test the per-user action
/// file as well as provider readiness); missing policy is never a silent grant.
pub fn missing_surfaces(facts: &ApprovalFacts, recovery: bool) -> Vec<String> {
    let mut missing = Vec::new();
    if !facts.desktop() {
        missing.push("desktop (required for stamp)".into());
    }
    if recovery || !facts.phone.as_ref().is_some_and(PhoneSurface::trusted) {
        missing.push(
            if recovery {
                "phone (unavailable in recovery)"
            } else {
                "phone"
            }
            .into(),
        );
    }
    if !facts.os_prompt_available {
        missing.push("OS prompt (Linux requires the per-user polkit action file)".into());
    }
    missing
}

/// A present policy is a prerequisite, not a promise that an interactive agent
/// is reachable. The provider's actual outcome remains authoritative.
pub fn os_prompt_policy_present() -> bool {
    #[cfg(target_os = "linux")]
    {
        std::path::Path::new(&subc_presence::polkit::action_path(subc_os::effective_uid()))
            .is_file()
    }
    #[cfg(not(target_os = "linux"))]
    {
        cfg!(any(target_os = "macos", windows))
    }
}