Skip to main content

aft_base/secret/
call_context.rs

1//! Route-independent facts installed by daemon-side code for one synchronous call.
2
3use crate::secret::{CallScopes, EligibilityForm, Ineligibility, SecretScope};
4use std::{cell::RefCell, path::PathBuf};
5
6#[derive(Default)]
7pub(crate) struct CallContext {
8    result_body: bool,
9    scopes: Option<Result<(CallScopes, EligibilityForm), Ineligibility>>,
10    consent_context: Option<(PathBuf, String)>,
11    audit_scope: Option<SecretScope>,
12}
13
14thread_local! {
15    static CURRENT: RefCell<CallContext> = RefCell::new(CallContext::default());
16}
17
18pub struct IdentityGuard(Option<(PathBuf, String)>, Option<SecretScope>);
19
20pub fn install_identity(
21    consent_context: Option<(PathBuf, String)>,
22    audit_scope: Option<SecretScope>,
23) -> IdentityGuard {
24    CURRENT.with(|slot| {
25        let mut context = slot.borrow_mut();
26        IdentityGuard(
27            std::mem::replace(&mut context.consent_context, consent_context),
28            std::mem::replace(&mut context.audit_scope, audit_scope),
29        )
30    })
31}
32
33impl Drop for IdentityGuard {
34    fn drop(&mut self) {
35        CURRENT.with(|slot| {
36            let mut context = slot.borrow_mut();
37            context.consent_context = self.0.take();
38            context.audit_scope = self.1.take();
39        });
40    }
41}
42
43pub fn current_secret_consent_context() -> Option<(PathBuf, String)> {
44    CURRENT.with(|slot| slot.borrow().consent_context.clone())
45}
46
47/// The eligibility answer for the tool call executing on this thread.
48/// An unresolved scope is never an eligible one.
49pub fn current_call_scopes() -> Result<(CallScopes, EligibilityForm), Ineligibility> {
50    CURRENT
51        .with(|slot| slot.borrow().scopes.clone())
52        .unwrap_or(Err(Ineligibility::NoScope))
53}
54
55pub fn current_secret_audit_scope() -> Option<SecretScope> {
56    current_call_scopes()
57        .ok()
58        .map(|(scopes, _)| scopes.authorization)
59        .or_else(|| CURRENT.with(|slot| slot.borrow().audit_scope.clone()))
60}
61
62/// Installs the eligibility answer for one call and restores the previous one
63/// when it drops, so the executor lane never carries a stale answer into the
64/// next call.
65pub struct SecretScopeGuard(Option<Result<(CallScopes, EligibilityForm), Ineligibility>>);
66
67impl SecretScopeGuard {
68    pub fn install(scopes: Option<Result<(CallScopes, EligibilityForm), Ineligibility>>) -> Self {
69        SecretScopeGuard(
70            CURRENT.with(|slot| std::mem::replace(&mut slot.borrow_mut().scopes, scopes)),
71        )
72    }
73}
74
75impl Drop for SecretScopeGuard {
76    fn drop(&mut self) {
77        CURRENT.with(|slot| slot.borrow_mut().scopes = self.0.take());
78    }
79}
80
81/// The executor installs the project binding policy; producers capture it before offloading.
82/// This flag records whether the caller negotiated the tool-result/v1 envelope.
83pub fn active() -> bool {
84    CURRENT.with(|slot| slot.borrow().result_body)
85}
86
87pub struct Guard(bool);
88
89pub fn enter(enabled: bool) -> Guard {
90    Guard(CURRENT.with(|slot| std::mem::replace(&mut slot.borrow_mut().result_body, enabled)))
91}
92
93impl Drop for Guard {
94    fn drop(&mut self) {
95        CURRENT.with(|slot| slot.borrow_mut().result_body = self.0);
96    }
97}
98
99thread_local! {
100    static FETCH_REPLY_DEADLINE: std::cell::Cell<Option<std::time::Instant>> = const { std::cell::Cell::new(None) };
101}
102
103/// The caller's reply deadline is independent of a fetch's network budget.
104pub struct FetchReplyDeadline(Option<std::time::Instant>);
105impl FetchReplyDeadline {
106    pub fn enter(deadline: std::time::Instant) -> Self {
107        Self(FETCH_REPLY_DEADLINE.with(|slot| slot.replace(Some(deadline))))
108    }
109}
110impl Drop for FetchReplyDeadline {
111    fn drop(&mut self) {
112        FETCH_REPLY_DEADLINE.with(|slot| slot.set(self.0));
113    }
114}
115pub(crate) fn current_fetch_reply_deadline() -> Option<std::time::Instant> {
116    FETCH_REPLY_DEADLINE.with(std::cell::Cell::get)
117}
118
119#[cfg(test)]
120mod tests {
121    use super::*;
122
123    #[test]
124    fn nested_call_facts_restore_without_leaking_to_the_next_call() {
125        assert!(!active());
126        assert_eq!(current_call_scopes(), Err(Ineligibility::NoScope));
127        {
128            let _result = enter(true);
129            let _scope = SecretScopeGuard::install(Some(Err(Ineligibility::FlowRead)));
130            let _identity = install_identity(None, None);
131            assert!(active());
132            assert_eq!(current_call_scopes(), Err(Ineligibility::FlowRead));
133            {
134                let _result = enter(false);
135                let _scope = SecretScopeGuard::install(None);
136                let _identity = install_identity(None, None);
137                assert!(!active());
138                assert_eq!(current_call_scopes(), Err(Ineligibility::NoScope));
139            }
140            assert!(active());
141            assert_eq!(current_call_scopes(), Err(Ineligibility::FlowRead));
142        }
143        assert!(!active());
144        assert_eq!(current_call_scopes(), Err(Ineligibility::NoScope));
145    }
146}