1use crate::secret::SecretScope;
15
16#[cfg(any(test, feature = "test-support"))]
17pub static TEST_TRANSPORT_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
18
19pub const SECRET_CONSENT_KIND: &str = "secret_use";
21
22#[derive(Clone, PartialEq, Eq)]
24pub struct SecretConsentRequest {
25 pub scope: SecretScope,
27 pub project_root: std::path::PathBuf,
29 pub session: String,
31 pub label: String,
33 pub request_id: String,
35 pub statement_b64url: String,
37 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#[derive(Clone, PartialEq, Eq)]
55pub enum ConsentOutcome {
56 Answered,
59 AnsweredOnce,
62 Declined,
63 Expired,
64 Cancelled,
66 Indeterminate,
69 Pending,
72 Unavailable {
75 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
98pub trait SecretConsentTransport: Send + Sync + 'static {
105 fn runtime(&self) -> Option<tokio::runtime::Handle> {
107 None
108 }
109 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 fn file(&self, request: &SecretConsentRequest) -> ConsentOutcome;
146
147 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 fn withhold(&self, request: &SecretConsentRequest) -> ConsentOutcome;
158
159 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
168static 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
176pub 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 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
218pub 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#[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 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#[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 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 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#[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
604pub 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
614pub 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;