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
8pub const CONFIG_PHONE_APPROVAL_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(300);
10use crate::config_store::ConfigStore;
11
12#[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#[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 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 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 = if let Some(change) = plan
322 .edits
323 .as_ref()
324 .and_then(|edit| edit.policy_root.as_ref())
325 {
326 change.review.clone()
327 } else {
328 gate_prompt_text(&format!("Approve config plan {digest}"), &[], &facts.caller)
329 .ok_or_else(unavailable)?
330 };
331 (
332 Surface::Desktop { channel },
333 ApprovalChallenge::Desktop {
334 attempt: id,
335 prompt,
336 },
337 )
338 } else if plan.desktop_only() {
339 return Err(unavailable());
340 } else if let Some(prompt) = plan.small_prompt(&facts.caller) {
341 if !facts.os_prompt_available {
342 return Err(unavailable());
343 }
344 (
345 Surface::Os,
346 ApprovalChallenge::OsPrompt {
347 attempt: id,
348 prompt,
349 },
350 )
351 } else {
352 let phone = facts
353 .phone
354 .as_ref()
355 .filter(|phone| !plan.recovery && phone.trusted())
356 .ok_or_else(unavailable)?;
357 let request =
358 Box::new(ConsentRequest::new(plan.view.plan.clone()).map_err(GateError::invalid)?);
359 (
360 Surface::Phone {
361 facts: phone.clone(),
362 request: request.clone(),
363 correlation: None,
364 },
365 ApprovalChallenge::Phone {
366 attempt: id,
367 connection: phone.connection,
368 deadline: tokio::time::Instant::now() + CONFIG_PHONE_APPROVAL_TIMEOUT,
369 request,
370 },
371 )
372 };
373 self.attempts.insert(
374 id,
375 Attempt {
376 digest: digest.clone(),
377 caller: facts.connection,
378 surface,
379 },
380 );
381 Ok(challenge)
382 }
383
384 pub fn finish_approval(
388 &mut self,
389 attempt: u64,
390 reply: ApprovalReply,
391 store: &mut ConfigStore,
392 current: &GateSnapshot,
393 facts: &ApprovalFacts,
394 now_ms: u64,
395 ) -> Result<u64> {
396 self.finish_approval_with_precommit(attempt, reply, store, current, facts, now_ms, || {
397 Ok(None)
398 })
399 }
400
401 #[allow(clippy::too_many_arguments)]
402 pub(super) fn finish_approval_with_precommit(
403 &mut self,
404 attempt: u64,
405 reply: ApprovalReply,
406 store: &mut ConfigStore,
407 current: &GateSnapshot,
408 facts: &ApprovalFacts,
409 now_ms: u64,
410 before_commit: impl FnOnce() -> Result<Option<crate::policy_root::ledger::Checkpoint>>,
411 ) -> Result<u64> {
412 let pending = self.attempts.remove(&attempt).ok_or_else(unavailable)?;
413 if !facts.owner_uid || facts.connection != pending.caller {
414 return Err(unavailable());
415 }
416 let channel = match (&pending.surface, reply) {
417 (Surface::Desktop { channel }, ApprovalReply::Presence(decision)) => {
418 if facts.desktop_channel() != Some(*channel) {
419 return Err(unavailable());
420 }
421 presence(decision)?;
422 *channel
423 }
424 (Surface::Os, ApprovalReply::Presence(decision)) => {
425 presence(decision)?;
426 subc_config::ApprovalChannel::OsPrompt
427 }
428 (
429 Surface::Phone {
430 facts: sent,
431 request,
432 correlation: sent_correlation,
433 },
434 ApprovalReply::Phone {
435 connection,
436 correlation,
437 response,
438 },
439 ) => {
440 let current = facts
441 .phone
442 .as_ref()
443 .filter(|phone| phone.trusted())
444 .ok_or_else(unavailable)?;
445 if current != sent
446 || connection != sent.connection
447 || Some(correlation) != *sent_correlation
448 {
449 return Err(unavailable());
450 }
451 let response = response.ok_or_else(declined)?;
452 if !response.approves(request) {
453 return Err(declined());
454 }
455 subc_config::ApprovalChannel::PhoneCard
456 }
457 _ => return Err(unavailable()),
458 };
459 let plan = self
460 .plans
461 .get(&pending.digest)
462 .ok_or_else(|| GateError::new("plan_unknown", "plan is absent or already applied"))?;
463 Self::fresh(plan, store, current)?;
464 self.commit(
465 &pending.digest,
466 channel,
467 store,
468 current,
469 now_ms,
470 before_commit,
471 )
472 }
473
474 pub(crate) fn bind_phone_rpc(
477 &mut self,
478 attempt: u64,
479 connection: u64,
480 correlation: u64,
481 ) -> Result<()> {
482 let pending = self.attempts.get_mut(&attempt).ok_or_else(unavailable)?;
483 match &mut pending.surface {
484 Surface::Phone {
485 facts,
486 correlation: bound,
487 ..
488 } if facts.connection == connection && bound.is_none() => {
489 *bound = Some(correlation);
490 Ok(())
491 }
492 _ => Err(unavailable()),
493 }
494 }
495
496 pub(crate) fn cancel_approval(&mut self, attempt: u64) {
497 self.attempts.remove(&attempt);
498 }
499
500 pub(crate) fn phone_approval_digests(&self, connection: u64) -> Vec<Digest> {
501 self.attempts.values().filter(|attempt| {
502 matches!(&attempt.surface, Surface::Phone { facts, .. } if facts.connection == connection)
503 }).map(|attempt| attempt.digest.clone()).collect()
504 }
505
506 pub fn invalidate_phone(&mut self, connection: u64) -> Vec<u64> {
510 let ids: Vec<_> = self.attempts.iter().filter_map(|(id, attempt)| {
511 matches!(&attempt.surface, Surface::Phone { facts, .. } if facts.connection == connection).then_some(*id)
512 }).collect();
513 for id in &ids {
514 self.attempts.remove(id);
515 }
516 ids
517 }
518}
519
520fn presence(decision: PresenceDecision) -> Result<()> {
521 match decision {
522 PresenceDecision::InteractiveApproval => Ok(()),
523 PresenceDecision::Declined => Err(declined()),
524 PresenceDecision::Unavailable => Err(unavailable()),
525 }
526}
527
528pub fn missing_surfaces(facts: &ApprovalFacts, recovery: bool) -> Vec<String> {
531 let mut missing = Vec::new();
532 if !facts.desktop() {
533 missing.push("desktop (required for stamp)".into());
534 }
535 if recovery || !facts.phone.as_ref().is_some_and(PhoneSurface::trusted) {
536 missing.push(
537 if recovery {
538 "phone (unavailable in recovery)"
539 } else {
540 "phone"
541 }
542 .into(),
543 );
544 }
545 if !facts.os_prompt_available {
546 missing.push("OS prompt (Linux requires the per-user polkit action file)".into());
547 }
548 missing
549}
550
551pub fn os_prompt_policy_present() -> bool {
554 #[cfg(target_os = "linux")]
555 {
556 std::path::Path::new(&subc_presence::polkit::action_path(subc_os::effective_uid()))
557 .is_file()
558 }
559 #[cfg(not(target_os = "linux"))]
560 {
561 cfg!(any(target_os = "macos", windows))
562 }
563}