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