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.restoring {
300 return Err(GateError::new(
301 "config_busy",
302 "the settings plan is being restored",
303 ));
304 }
305 if !plan.view.refusals.is_empty() {
306 return Err(GateError::new(
307 "plan_refused",
308 "the plan contains refused edits",
309 ));
310 }
311 Self::fresh(plan, store, current)?;
312 if !facts.owner_uid {
313 return Err(unavailable());
314 }
315 if self.attempts.len() >= 4 {
316 return Err(GateError::new("config_busy", "approval queue is full"));
317 }
318 self.next_attempt = self.next_attempt.checked_add(1).ok_or_else(unavailable)?;
319 let id = self.next_attempt;
320 let (surface, challenge) = if let Some(channel) = facts.desktop_channel().filter(|_| {
321 !(facts.caller.is_daemon_settings() || plan.recovery && plan.kind == PlanKind::Unstamp)
322 }) {
323 if !facts.os_prompt_available {
324 return Err(unavailable());
325 }
326 let prompt = if let Some(change) = plan
327 .edits
328 .as_ref()
329 .and_then(|edit| edit.policy_root.as_ref())
330 {
331 change.review.clone()
332 } else {
333 gate_prompt_text(&format!("Approve config plan {digest}"), &[], &facts.caller)
334 .ok_or_else(unavailable)?
335 };
336 (
337 Surface::Desktop { channel },
338 ApprovalChallenge::Desktop {
339 attempt: id,
340 prompt,
341 },
342 )
343 } else if plan.desktop_only() {
344 return Err(unavailable());
345 } else if let Some(prompt) = (!facts.caller.is_daemon_settings())
346 .then(|| plan.small_prompt(&facts.caller))
347 .flatten()
348 {
349 if !facts.os_prompt_available {
350 return Err(unavailable());
351 }
352 (
353 Surface::Os,
354 ApprovalChallenge::OsPrompt {
355 attempt: id,
356 prompt,
357 },
358 )
359 } else {
360 let phone = facts
361 .phone
362 .as_ref()
363 .filter(|phone| !plan.recovery && phone.trusted())
364 .ok_or_else(unavailable)?;
365 let request =
366 Box::new(ConsentRequest::new(plan.view.plan.clone()).map_err(GateError::invalid)?);
367 (
368 Surface::Phone {
369 facts: phone.clone(),
370 request: request.clone(),
371 correlation: None,
372 },
373 ApprovalChallenge::Phone {
374 attempt: id,
375 connection: phone.connection,
376 deadline: tokio::time::Instant::now() + CONFIG_PHONE_APPROVAL_TIMEOUT,
377 request,
378 },
379 )
380 };
381 self.attempts.insert(
382 id,
383 Attempt {
384 digest: digest.clone(),
385 caller: facts.connection,
386 surface,
387 },
388 );
389 Ok(challenge)
390 }
391
392 pub(super) fn settings_declined(
393 &self,
394 attempt: u64,
395 facts: &ApprovalFacts,
396 reply: &ApprovalReply,
397 ) -> bool {
398 let Some(pending) = self.attempts.get(&attempt) else {
399 return false;
400 };
401 if !facts.owner_uid
402 || !facts.caller.is_daemon_settings()
403 || facts.connection != pending.caller
404 {
405 return false;
406 }
407 match (&pending.surface, reply) {
408 (
409 Surface::Phone {
410 facts: sent,
411 request,
412 correlation: sent_id,
413 },
414 ApprovalReply::Phone {
415 connection,
416 correlation,
417 response: Some(response),
418 },
419 ) => {
420 facts.phone.as_ref().filter(|phone| phone.trusted()) == Some(sent)
421 && *connection == sent.connection
422 && Some(*correlation) == *sent_id
423 && response.decision == subc_protocol::consent::ConsentDecision::Declined
424 && response.plan_digest == request.plan_digest
425 && response.base_revision == request.base_revision
426 && response.input_vector == request.input_vector
427 }
428 _ => false,
429 }
430 }
431
432 pub fn finish_approval(
436 &mut self,
437 attempt: u64,
438 reply: ApprovalReply,
439 store: &mut ConfigStore,
440 current: &GateSnapshot,
441 facts: &ApprovalFacts,
442 now_ms: u64,
443 ) -> Result<u64> {
444 self.finish_approval_with_precommit(attempt, reply, store, current, facts, now_ms, || {
445 Ok(None)
446 })
447 }
448
449 #[allow(clippy::too_many_arguments)]
450 pub(super) fn finish_approval_with_precommit(
451 &mut self,
452 attempt: u64,
453 reply: ApprovalReply,
454 store: &mut ConfigStore,
455 current: &GateSnapshot,
456 facts: &ApprovalFacts,
457 now_ms: u64,
458 before_commit: impl FnOnce() -> Result<Option<crate::policy_root::ledger::Checkpoint>>,
459 ) -> Result<u64> {
460 let pending = self.attempts.remove(&attempt).ok_or_else(unavailable)?;
461 if !facts.owner_uid || facts.connection != pending.caller {
462 return Err(unavailable());
463 }
464 let channel = match (&pending.surface, reply) {
465 (Surface::Desktop { channel }, ApprovalReply::Presence(decision)) => {
466 if facts.desktop_channel() != Some(*channel) {
467 return Err(unavailable());
468 }
469 presence(decision)?;
470 *channel
471 }
472 (Surface::Os, ApprovalReply::Presence(decision)) => {
473 presence(decision)?;
474 subc_config::ApprovalChannel::OsPrompt
475 }
476 (
477 Surface::Phone {
478 facts: sent,
479 request,
480 correlation: sent_correlation,
481 },
482 ApprovalReply::Phone {
483 connection,
484 correlation,
485 response,
486 },
487 ) => {
488 let current = facts
489 .phone
490 .as_ref()
491 .filter(|phone| phone.trusted())
492 .ok_or_else(unavailable)?;
493 if current != sent
494 || connection != sent.connection
495 || Some(correlation) != *sent_correlation
496 {
497 return Err(unavailable());
498 }
499 let response = response.ok_or_else(declined)?;
500 if !response.approves(request) {
501 return Err(declined());
502 }
503 subc_config::ApprovalChannel::PhoneCard
504 }
505 _ => return Err(unavailable()),
506 };
507 let plan = self
508 .plans
509 .get(&pending.digest)
510 .ok_or_else(|| GateError::new("plan_unknown", "plan is absent or already applied"))?;
511 Self::fresh(plan, store, current)?;
512 self.commit(
513 &pending.digest,
514 channel,
515 store,
516 current,
517 now_ms,
518 before_commit,
519 )
520 }
521
522 pub(crate) fn bind_phone_rpc(
525 &mut self,
526 attempt: u64,
527 connection: u64,
528 correlation: u64,
529 ) -> Result<()> {
530 let pending = self.attempts.get_mut(&attempt).ok_or_else(unavailable)?;
531 match &mut pending.surface {
532 Surface::Phone {
533 facts,
534 correlation: bound,
535 ..
536 } if facts.connection == connection && bound.is_none() => {
537 *bound = Some(correlation);
538 Ok(())
539 }
540 _ => Err(unavailable()),
541 }
542 }
543
544 pub(crate) fn cancel_approval(&mut self, attempt: u64) {
545 self.attempts.remove(&attempt);
546 }
547
548 pub(crate) fn phone_approval_digests(&self, connection: u64) -> Vec<Digest> {
549 self.attempts.values().filter(|attempt| {
550 matches!(&attempt.surface, Surface::Phone { facts, .. } if facts.connection == connection)
551 }).map(|attempt| attempt.digest.clone()).collect()
552 }
553
554 pub fn invalidate_phone(&mut self, connection: u64) -> Vec<u64> {
558 let ids: Vec<_> = self.attempts.iter().filter_map(|(id, attempt)| {
559 matches!(&attempt.surface, Surface::Phone { facts, .. } if facts.connection == connection).then_some(*id)
560 }).collect();
561 for id in &ids {
562 self.attempts.remove(id);
563 }
564 ids
565 }
566}
567
568fn presence(decision: PresenceDecision) -> Result<()> {
569 match decision {
570 PresenceDecision::InteractiveApproval => Ok(()),
571 PresenceDecision::Declined => Err(declined()),
572 PresenceDecision::Unavailable => Err(unavailable()),
573 }
574}
575
576pub fn missing_surfaces(facts: &ApprovalFacts, recovery: bool) -> Vec<String> {
579 let mut missing = Vec::new();
580 if !facts.desktop() {
581 missing.push("desktop (required for stamp)".into());
582 }
583 if recovery || !facts.phone.as_ref().is_some_and(PhoneSurface::trusted) {
584 missing.push(
585 if recovery {
586 "phone (unavailable in recovery)"
587 } else {
588 "phone"
589 }
590 .into(),
591 );
592 }
593 if !facts.os_prompt_available {
594 missing.push("OS prompt (Linux requires the per-user polkit action file)".into());
595 }
596 missing
597}
598
599pub fn os_prompt_policy_present() -> bool {
602 #[cfg(target_os = "linux")]
603 {
604 std::path::Path::new(&subc_presence::polkit::action_path(subc_os::effective_uid()))
605 .is_file()
606 }
607 #[cfg(not(target_os = "linux"))]
608 {
609 cfg!(any(target_os = "macos", windows))
610 }
611}