Skip to main content

aft_base/secret/
consent.rs

1//! The secret consent entry point AFT's own tools dispatch to.
2//!
3//! A secret consent is not a filesystem permission. It is filed for every
4//! eligible scope, including a bound codemode call, and it carries the vault's
5//! own request id and statement so the phone screen can show what the vault
6//! asked. Cingulate's allow alone grants nothing: the caller resolves again
7//! afterwards, and only a vault grant allows a substitution.
8//!
9//! Secret questions share the Cingulate transport with filesystem permission
10//! asks, but never become filesystem `AccessGrant`s. In particular, a bound
11//! codemode call may ask about a secret under its head's authorization scope
12//! even though it may not file a filesystem permission ask.
13
14use crate::secret::SecretScope;
15
16#[cfg(any(test, feature = "test-support"))]
17pub static TEST_TRANSPORT_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
18
19/// The consent kind a secret ask files under.
20pub const SECRET_CONSENT_KIND: &str = "secret_use";
21
22/// What the consent adapter is asked to file for one label.
23#[derive(Clone, PartialEq, Eq)]
24pub struct SecretConsentRequest {
25    /// The authorization scope the ask is filed under.
26    pub scope: SecretScope,
27    /// The originating route's project root, used only for the scoped transport.
28    pub project_root: std::path::PathBuf,
29    /// The originating route's session, used only for the scoped transport.
30    pub session: String,
31    /// The label the vault is waiting on.
32    pub label: String,
33    /// The vault's identifier for the pending decision.
34    pub request_id: String,
35    /// The vault's statement bytes, base64url without padding.
36    pub statement_b64url: String,
37    /// The vault's approval expiry for a shared card. Cingulate reads this
38    /// from the signed statement instead of from a separate field.
39    pub expires_at_ms: Option<u64>,
40}
41
42impl std::fmt::Debug for SecretConsentRequest {
43    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
44        f.debug_struct("SecretConsentRequest")
45            .field("scope", &self.scope)
46            .field("label", &self.label)
47            .field("request_id", &self.request_id)
48            .field("statement_b64url_len", &self.statement_b64url.len())
49            .finish()
50    }
51}
52
53/// What happened to a filed secret consent.
54#[derive(Clone, PartialEq, Eq)]
55pub enum ConsentOutcome {
56    /// Cingulate allowed this request. Retry the vault once; only its release
57    /// authorizes substitution.
58    Answered,
59    /// One-use approval. Preserve this distinction so a later card can be
60    /// announced as replacing a consumed one-use approval.
61    AnsweredOnce,
62    Declined,
63    Expired,
64    /// The card was withdrawn; this is not a phone answer.
65    Cancelled,
66    /// The card was answered, but no trustworthy decision could be read.
67    /// This must not be retained as a person's answer or a filing failure.
68    Indeterminate,
69    /// Still pending when the call's hold ended: the call ends
70    /// `access_pending` and the retried call asks again.
71    Pending,
72    /// The ask could not be filed or awaited: the call ends
73    /// `access_unavailable`.
74    Unavailable {
75        /// Plain-text detail with no key material.
76        detail: String,
77    },
78}
79
80impl std::fmt::Debug for ConsentOutcome {
81    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
82        match self {
83            ConsentOutcome::Answered => f.write_str("Answered"),
84            ConsentOutcome::AnsweredOnce => f.write_str("AnsweredOnce"),
85            ConsentOutcome::Declined => f.write_str("Declined"),
86            ConsentOutcome::Expired => f.write_str("Expired"),
87            ConsentOutcome::Cancelled => f.write_str("Cancelled"),
88            ConsentOutcome::Indeterminate => f.write_str("Indeterminate"),
89            ConsentOutcome::Pending => f.write_str("Pending"),
90            ConsentOutcome::Unavailable { detail } => f
91                .debug_struct("Unavailable")
92                .field("detail", detail)
93                .finish(),
94        }
95    }
96}
97
98/// What a dispatcher is asked to do with one secret consent.
99///
100/// This is the seam between the adapter and the transport: the dispatcher files
101/// the ask through the daemon's Cingulate client and reports what happened.
102/// The trait exists so the outcome table can be tested without a daemon, and
103/// so a later transport shape changes only the installed dispatcher.
104pub trait SecretConsentTransport: Send + Sync + 'static {
105    /// Keep cleanup on the daemon runtime, not a command's short-lived proxy.
106    fn runtime(&self) -> Option<tokio::runtime::Handle> {
107        None
108    }
109    /// Await one shared card. Production observes cancellation while awaiting
110    /// the Cingulate consent service and withdraws while the route is still
111    /// bound to the card's authorization scope.
112    fn wait(
113        self: std::sync::Arc<Self>,
114        request: SecretConsentRequest,
115        cancel: Cancellation,
116    ) -> std::pin::Pin<Box<dyn std::future::Future<Output = ConsentOutcome> + Send>> {
117        Box::pin(async move {
118            let worker = self.clone();
119            let ask = request.clone();
120            let held_cancel = cancel.clone();
121            let held = tokio::task::spawn_blocking(move || {
122                if held_cancel.is_cancelled() {
123                    ConsentOutcome::Cancelled
124                } else {
125                    worker.hold(&ask, &held_cancel)
126                }
127            });
128            let outcome = tokio::select! {
129                biased;
130                () = cancel.cancelled() => ConsentOutcome::Cancelled,
131                result = held => result.unwrap_or(ConsentOutcome::Unavailable { detail: "Cingulate could not settle the secret-use card".into() }),
132            };
133            if matches!(
134                outcome,
135                ConsentOutcome::Cancelled
136                    | ConsentOutcome::Unavailable { .. }
137                    | ConsentOutcome::Indeterminate
138            ) {
139                let _ = tokio::task::spawn_blocking(move || self.withhold(&request)).await;
140            }
141            outcome
142        })
143    }
144    /// File `request` and wait for the answer, or for the hold to end.
145    fn file(&self, request: &SecretConsentRequest) -> ConsentOutcome;
146
147    /// File once and hold a proxy request for the full approval window.
148    fn hold(&self, request: &SecretConsentRequest, cancel: &Cancellation) -> ConsentOutcome {
149        if cancel.is_cancelled() {
150            ConsentOutcome::Cancelled
151        } else {
152            self.file(request)
153        }
154    }
155
156    /// Settle a pending ask the call left behind.
157    fn withhold(&self, request: &SecretConsentRequest) -> ConsentOutcome;
158
159    /// Discard transport state for an expired vault request.
160    fn forget_expired(
161        &self,
162        _request: &SecretConsentRequest,
163    ) -> std::pin::Pin<Box<dyn std::future::Future<Output = ()> + Send + '_>> {
164        Box::pin(std::future::ready(()))
165    }
166}
167
168/// The dispatcher installed for this process.
169///
170/// `None` means no secret consent transport is connected. A pending vault
171/// answer then ends the call with `access_unavailable`, never a silent start.
172static TRANSPORT: std::sync::LazyLock<
173    std::sync::Mutex<Option<std::sync::Arc<dyn SecretConsentTransport>>>,
174> = std::sync::LazyLock::new(|| std::sync::Mutex::new(None));
175
176/// Install the secret consent transport.
177pub fn install_transport(transport: Option<std::sync::Arc<dyn SecretConsentTransport>>) {
178    drop(replace_transport(transport));
179}
180
181fn replace_transport(transport: Option<std::sync::Arc<dyn SecretConsentTransport>>) -> Cards {
182    let mut installed = TRANSPORT
183        .lock()
184        .unwrap_or_else(std::sync::PoisonError::into_inner);
185    let mut cards = CARDS
186        .lock()
187        .unwrap_or_else(std::sync::PoisonError::into_inner);
188    *installed = transport;
189    for card in cards
190        .values()
191        .filter(|card| card.outcome.borrow().is_none())
192    {
193        card.cancel.cancel();
194    }
195    std::mem::take(&mut *cards)
196}
197
198pub async fn shutdown() {
199    let cards = replace_transport(None);
200    // Give all withdrawals the same bounded window, rather than waiting a
201    // separate RPC timeout for each card before the daemon exits.
202    let _ = tokio::time::timeout(std::time::Duration::from_secs(10), async {
203        for card in cards.values() {
204            let mut outcome = card.outcome.subscribe();
205            let _ = outcome.wait_for(Option::is_some).await;
206        }
207    })
208    .await;
209}
210
211fn transport() -> Option<std::sync::Arc<dyn SecretConsentTransport>> {
212    TRANSPORT
213        .lock()
214        .unwrap_or_else(std::sync::PoisonError::into_inner)
215        .clone()
216}
217
218/// File `request` and report what happened.
219///
220/// The caller has already decided the asking call is eligible, so the scope in
221/// `request` is the one the daemon stamped.
222pub fn file_consent(request: &SecretConsentRequest) -> ConsentOutcome {
223    match transport() {
224        Some(transport) => transport.file(request),
225        None => ConsentOutcome::Unavailable {
226            detail: "no secret consent transport is connected".into(),
227        },
228    }
229}
230
231/// Cancellation shared by a request's labels and its approval worker.
232#[derive(Clone)]
233pub struct Cancellation(tokio::sync::watch::Sender<Option<CancellationReason>>);
234
235#[derive(Clone, Copy, Debug, PartialEq, Eq)]
236pub enum CancellationReason {
237    Expired,
238    Cancelled,
239}
240
241impl CancellationReason {
242    pub fn code(self) -> &'static str {
243        match self {
244            Self::Expired => "expired",
245            Self::Cancelled => "cancelled",
246        }
247    }
248}
249
250impl Default for Cancellation {
251    fn default() -> Self {
252        Self(tokio::sync::watch::channel(None).0)
253    }
254}
255impl Cancellation {
256    pub fn cancel(&self) {
257        self.cancel_with_reason(CancellationReason::Cancelled);
258    }
259    pub fn cancel_with_reason(&self, reason: CancellationReason) {
260        // Preserve the first cause when a deadline and a scope revocation race.
261        self.0.send_if_modified(|current| {
262            if current.is_none() {
263                *current = Some(reason);
264                true
265            } else {
266                false
267            }
268        });
269    }
270    pub fn reason(&self) -> Option<CancellationReason> {
271        *self.0.borrow()
272    }
273    pub fn is_cancelled(&self) -> bool {
274        self.reason().is_some()
275    }
276    pub async fn cancelled(&self) {
277        let mut receiver = self.0.subscribe();
278        loop {
279            if receiver.borrow_and_update().is_some() {
280                return;
281            }
282            if receiver.changed().await.is_err() {
283                return;
284            }
285        }
286    }
287}
288
289// The vault deduplicates within the stamped authorization scope. Ending one
290// run must not withdraw a card another run can use under that same authority.
291#[derive(Clone)]
292pub struct CardKey(pub SecretScope, pub String);
293
294impl CardKey {
295    fn identity(&self) -> (&str, &str, u64, &str) {
296        (
297            self.0.owner(),
298            self.0.reference(),
299            self.0.stamp().scope_epoch,
300            &self.1,
301        )
302    }
303}
304
305impl PartialEq for CardKey {
306    fn eq(&self, other: &Self) -> bool {
307        self.identity() == other.identity()
308    }
309}
310
311impl Eq for CardKey {}
312
313impl std::hash::Hash for CardKey {
314    fn hash<H: std::hash::Hasher>(&self, hasher: &mut H) {
315        std::hash::Hash::hash(&self.identity(), hasher);
316    }
317}
318
319type Cards = std::collections::HashMap<CardKey, std::sync::Arc<SharedCard>>;
320const MAX_CLIENTLESS_CARDS: usize = 32;
321const MAX_CARD_LIFETIME_MS: u64 = 600_000;
322
323struct SharedCard {
324    created: tokio::time::Instant,
325    statement: String,
326    expires: u64,
327    deadline: tokio::time::Instant,
328    outcome: tokio::sync::watch::Sender<Option<ConsentOutcome>>,
329    outcome_code: std::sync::Mutex<Option<&'static str>>,
330    cancel: Cancellation,
331    waiters: std::sync::atomic::AtomicUsize,
332}
333
334impl SharedCard {
335    fn is_pending(&self) -> bool {
336        !self.cancel.is_cancelled() && self.outcome.borrow().is_none()
337    }
338
339    fn is_clientless(&self) -> bool {
340        self.waiters.load(std::sync::atomic::Ordering::Acquire) == 0 && self.is_pending()
341    }
342}
343
344pub fn pending_scope_stamps() -> Vec<subc_protocol::scope::ScopeStamp> {
345    CARDS
346        .lock()
347        .unwrap_or_else(std::sync::PoisonError::into_inner)
348        .iter()
349        .filter(|(_, card)| card.is_pending())
350        .map(|(key, _)| key.0.stamp().clone())
351        .collect()
352}
353
354pub fn revoke_scope(stamp: &subc_protocol::scope::ScopeStamp) {
355    let cards = CARDS
356        .lock()
357        .unwrap_or_else(std::sync::PoisonError::into_inner);
358    for (key, card) in cards.iter() {
359        let held = key.0.stamp();
360        if held.owner == stamp.owner
361            && held.scope_ref == stamp.scope_ref
362            && held.scope_epoch == stamp.scope_epoch
363            && card.is_pending()
364        {
365            card.cancel.cancel();
366        }
367    }
368}
369
370pub fn record_outcome_code(scope: &SecretScope, request_id: &str, code: &str) {
371    let cards = CARDS
372        .lock()
373        .unwrap_or_else(std::sync::PoisonError::into_inner);
374    if let Some(card) = cards.get(&CardKey(scope.clone(), request_id.to_owned())) {
375        *card
376            .outcome_code
377            .lock()
378            .unwrap_or_else(std::sync::PoisonError::into_inner) =
379            Some(super::transport::diagnostics::safe_code(code));
380    }
381}
382static CARDS: std::sync::LazyLock<std::sync::Mutex<Cards>> =
383    std::sync::LazyLock::new(Default::default);
384
385struct Waiter<'a> {
386    card: std::sync::Arc<SharedCard>,
387    request_id: &'a str,
388    local_cancel: Option<&'a Cancellation>,
389}
390
391impl Drop for Waiter<'_> {
392    fn drop(&mut self) {
393        // Joins and answer publication use the same lock as eviction, so a
394        // joining waiter or a recorded phone answer rules out eviction.
395        let cards = CARDS
396            .lock()
397            .unwrap_or_else(std::sync::PoisonError::into_inner);
398        let last = self
399            .card
400            .waiters
401            .fetch_sub(1, std::sync::atomic::Ordering::AcqRel)
402            == 1;
403        if !self.card.is_pending() {
404            return;
405        }
406        // A cancelled fetch tool call or its reply deadline still withdraws
407        // the last waiter's card. An HTTP client closing its proxy socket does not.
408        if let Some(reason) = self.local_cancel.and_then(Cancellation::reason) {
409            if last {
410                self.card.cancel.cancel_with_reason(reason);
411            }
412            return;
413        }
414        if last {
415            let mut clientless = cards.values().filter(|card| card.is_clientless());
416            if let Some(oldest) = clientless.next() {
417                let (count, oldest) = clientless.fold((1, oldest), |(count, oldest), card| {
418                    (
419                        count + 1,
420                        if card.created < oldest.created {
421                            card
422                        } else {
423                            oldest
424                        },
425                    )
426                });
427                if count > MAX_CLIENTLESS_CARDS {
428                    oldest
429                        .cancel
430                        .cancel_with_reason(CancellationReason::Expired);
431                }
432            }
433        }
434        if !self.card.cancel.is_cancelled() {
435            crate::slog_info!(
436                "secret consent waiter dropped; card kept until expiry: request_id={:?} expires_at_ms={}",
437                self.request_id,
438                self.card.expires,
439            );
440        }
441    }
442}
443
444fn scope_inventory_changed() {
445    crate::scope_watch_events::changed(crate::scope_watch_events::Source::Parked);
446}
447
448async fn run_card(
449    key: CardKey,
450    card: std::sync::Arc<SharedCard>,
451    transport: std::sync::Arc<dyn SecretConsentTransport>,
452    request: SecretConsentRequest,
453) {
454    let wait = transport.clone().wait(request.clone(), card.cancel.clone());
455    let expiry = tokio::time::sleep_until(card.deadline);
456    tokio::pin!(wait, expiry);
457    let answer = tokio::select! {
458        biased;
459        () = &mut expiry => {
460            card.cancel.cancel_with_reason(CancellationReason::Expired);
461            wait.await
462        }
463        answer = &mut wait => answer,
464    };
465    {
466        let _cards = CARDS
467            .lock()
468            .unwrap_or_else(std::sync::PoisonError::into_inner);
469        card.outcome.send_replace(Some(answer));
470    }
471    scope_inventory_changed();
472    expiry.await;
473    transport.forget_expired(&request).await;
474    let mut cards = CARDS
475        .lock()
476        .unwrap_or_else(std::sync::PoisonError::into_inner);
477    if cards
478        .get(&key)
479        .is_some_and(|current| std::sync::Arc::ptr_eq(current, &card))
480    {
481        cards.remove(&key);
482    }
483}
484
485#[rustfmt::skip]
486test_support_visibility! {
487/// Each retry shares the recorded outcome of the secret-approval request
488/// without blocking another vault lookup or counting another waiter's queue time.
489#[cfg(any(test, feature = "test-support"))]
490pub(crate) async fn wait_consent(request: SecretConsentRequest) -> ConsentOutcome {
491    wait_consent_with_code(request, None).await.0
492}
493}
494
495pub(crate) async fn wait_consent_with_code(
496    mut request: SecretConsentRequest,
497    local_cancel: Option<&Cancellation>,
498) -> (ConsentOutcome, Option<&'static str>) {
499    let card = {
500        use std::collections::hash_map::Entry;
501        let installed = TRANSPORT
502            .lock()
503            .unwrap_or_else(std::sync::PoisonError::into_inner);
504        let Some(transport) = installed.clone() else {
505            return (
506                ConsentOutcome::Unavailable {
507                    detail: "no secret consent transport is connected".into(),
508                },
509                None,
510            );
511        };
512        let now = super::vault::now_ms();
513        let expires = request
514            .expires_at_ms
515            .unwrap_or(u64::MAX)
516            .min(now.saturating_add(MAX_CARD_LIFETIME_MS));
517        if expires <= now {
518            return (ConsentOutcome::Expired, None);
519        }
520        request.expires_at_ms = Some(expires);
521        let mut cards = CARDS
522            .lock()
523            .unwrap_or_else(std::sync::PoisonError::into_inner);
524        cards.retain(|_, card| {
525            card.waiters.load(std::sync::atomic::Ordering::Acquire) != 0
526                || !matches!(
527                    &*card.outcome.borrow(),
528                    Some(ConsentOutcome::Unavailable { .. } | ConsentOutcome::Indeterminate)
529                )
530        });
531        let key = CardKey(request.scope.clone(), request.request_id.clone());
532        let card = match cards.entry(key.clone()) {
533            Entry::Occupied(entry) => {
534                let card = entry.get();
535                if card.statement != request.statement_b64url {
536                    return (
537                        ConsentOutcome::Unavailable {
538                            detail: "Cingulate could not file the secret-use card".into(),
539                        },
540                        None,
541                    );
542                }
543                if tokio::time::Instant::now() >= card.deadline {
544                    return (ConsentOutcome::Expired, None);
545                }
546                if card.is_pending() {
547                    crate::slog_info!(
548                        "secret consent retry attached to existing card: request_id={:?}",
549                        request.request_id,
550                    );
551                }
552                card.clone()
553            }
554            Entry::Vacant(entry) => {
555                let runtime = transport
556                    .runtime()
557                    .unwrap_or_else(tokio::runtime::Handle::current);
558                let created = tokio::time::Instant::now();
559                let card = std::sync::Arc::new(SharedCard {
560                    created,
561                    statement: request.statement_b64url.clone(),
562                    expires,
563                    deadline: created + std::time::Duration::from_millis(expires - now),
564                    outcome: tokio::sync::watch::channel(None).0,
565                    outcome_code: Default::default(),
566                    cancel: Default::default(),
567                    waiters: Default::default(),
568                });
569                entry.insert(card.clone());
570                scope_inventory_changed();
571                runtime.spawn(run_card(key, card.clone(), transport, request.clone()));
572                card
573            }
574        };
575        card.waiters
576            .fetch_add(1, std::sync::atomic::Ordering::AcqRel);
577        card
578    };
579    let _waiter = Waiter {
580        card: card.clone(),
581        request_id: &request.request_id,
582        local_cancel,
583    };
584    let mut receiver = card.outcome.subscribe();
585    loop {
586        if let Some(answer) = receiver.borrow_and_update().clone() {
587            let code = *card
588                .outcome_code
589                .lock()
590                .unwrap_or_else(std::sync::PoisonError::into_inner);
591            return (answer, code);
592        }
593        if receiver.changed().await.is_err() {
594            return (
595                ConsentOutcome::Unavailable {
596                    detail: "Cingulate could not settle the secret-use card".into(),
597                },
598                None,
599            );
600        }
601    }
602}
603
604/// Settle a pending secret ask.
605pub fn withhold_consent(request: &SecretConsentRequest) -> ConsentOutcome {
606    match transport() {
607        Some(transport) => transport.withhold(request),
608        None => ConsentOutcome::Unavailable {
609            detail: "no secret consent transport is connected".into(),
610        },
611    }
612}
613
614/// The `consent.request` parameter shape a secret ask carries.
615///
616/// Cingulate renders the vault's statement, not filer-authored prose. Forward
617/// exactly one item without decoding or re-encoding the statement; the daemon
618/// carries the authorization stamp outside this body.
619///
620/// The body is exactly `{kind, secret_use}`: Cingulate decodes secret-use
621/// filings with unknown fields refused (`envelope_invalid`), and sets the
622/// card's expiry itself from the statements' `request_expires_at_ms`.
623pub fn request_params(request: &SecretConsentRequest) -> serde_json::Value {
624    serde_json::json!({
625        "kind": SECRET_CONSENT_KIND,
626        "secret_use": {
627            "items": [{
628                "request_id": request.request_id,
629                "statement_b64url": request.statement_b64url,
630            }],
631        },
632    })
633}
634
635#[cfg(test)]
636#[path = "consent_cancel_tests.rs"]
637mod cancellation_cache_tests;