Skip to main content

coqui_access_kit/
cache.rs

1//! Short-lived caches in front of a directory or an authorizer, to absorb bursts.
2//!
3//! [`Cached`] wraps a provider and answers a repeated [`Lookup`] or authorization from memory
4//! for [`CacheOptions::ttl`], or [`negative_ttl`](CacheOptions::negative_ttl) for an answer
5//! of "no such person" or "denied". A credential is never cached: [`Cached`] does not
6//! implement `Authenticator`. An error is never cached either.
7//!
8//! Needs the `cache` feature.
9
10use core::fmt;
11use core::hash::Hash;
12use std::sync::Arc;
13use std::time::{Duration, Instant};
14
15use coqui_access::guatiao::library::ProviderError;
16use coqui_access::{
17    AccountInfo, AccountPut, Accounts, AuthorizationDecision, AuthorizationRequest, Authorizer,
18    Description, Directory, Lookup, Person, PutOutcome, Waiting,
19};
20use coqui_builder::Describe;
21use moka::Expiry;
22use moka::sync::Cache;
23
24/// How long answers are kept, and how many.
25///
26/// The default keeps a found person or a grant 5 s, "not found" or a denial 1 s, and 10 000
27/// entries of each kind: a burst is answered once, and a change at the source is seen within
28/// seconds. A removed account or a withdrawn permission can still pass for up to `ttl` after
29/// the source changes unless [`Cached::invalidate`] is called; a new one can be refused for
30/// up to `negative_ttl`. As configuration, a duration reads `5` or `1.5` (seconds), `5s` or
31/// `250ms`.
32#[derive(Debug, Clone, Copy, PartialEq, Eq, Describe)]
33#[non_exhaustive]
34pub struct CacheOptions {
35    /// How long a person found or a grant is kept.
36    #[map(default = DEFAULT_TTL)]
37    pub ttl: Duration,
38    /// How long "no such person" or a denial is kept.
39    #[map(default = DEFAULT_NEGATIVE_TTL)]
40    pub negative_ttl: Duration,
41    /// The most answers kept of each kind (lookups, decisions); `0` keeps none.
42    #[map(default = DEFAULT_MAX_ENTRIES)]
43    pub max_entries: u64,
44}
45
46/// [`CacheOptions::ttl`] by default: 5 s.
47pub const DEFAULT_TTL: Duration = Duration::from_secs(5);
48/// [`CacheOptions::negative_ttl`] by default: 1 s.
49pub const DEFAULT_NEGATIVE_TTL: Duration = Duration::from_secs(1);
50/// [`CacheOptions::max_entries`] by default.
51pub const DEFAULT_MAX_ENTRIES: u64 = 10_000;
52
53impl Default for CacheOptions {
54    fn default() -> Self {
55        Self {
56            ttl: DEFAULT_TTL,
57            negative_ttl: DEFAULT_NEGATIVE_TTL,
58            max_entries: DEFAULT_MAX_ENTRIES,
59        }
60    }
61}
62
63impl CacheOptions {
64    /// Nothing is kept: every call reaches the provider.
65    pub const fn off() -> Self {
66        Self {
67            ttl: Duration::ZERO,
68            negative_ttl: Duration::ZERO,
69            max_entries: 0,
70        }
71    }
72
73    /// These options with `ttl`.
74    #[must_use]
75    pub const fn ttl(mut self, ttl: Duration) -> Self {
76        self.ttl = ttl;
77        self
78    }
79
80    /// These options with `negative_ttl`.
81    #[must_use]
82    pub const fn negative_ttl(mut self, negative_ttl: Duration) -> Self {
83        self.negative_ttl = negative_ttl;
84        self
85    }
86
87    /// These options with `max_entries`.
88    #[must_use]
89    pub const fn max_entries(mut self, max_entries: u64) -> Self {
90        self.max_entries = max_entries;
91        self
92    }
93
94    /// Whether answers are kept longer than the defaults, which widens the window in which a
95    /// revoked account or permission still passes: data for the host to report, not a
96    /// refusal.
97    pub fn exceeds_default(&self) -> bool {
98        self.ttl > DEFAULT_TTL || self.negative_ttl > DEFAULT_NEGATIVE_TTL
99    }
100
101    fn keeps_anything(&self) -> bool {
102        self.max_entries > 0 && !(self.ttl.is_zero() && self.negative_ttl.is_zero())
103    }
104}
105
106/// A cache as configuration: `true` (the defaults), `false` (off), or [`CacheOptions`].
107#[derive(Debug, Clone, Copy, PartialEq, Eq, Describe)]
108#[map(untagged)]
109pub enum CacheSetting {
110    /// On with the defaults, or off.
111    Enabled(bool),
112    /// On with these options.
113    Tuned(CacheOptions),
114}
115
116impl Default for CacheSetting {
117    fn default() -> Self {
118        Self::Enabled(true)
119    }
120}
121
122impl CacheSetting {
123    /// The options this setting means.
124    pub fn options(&self) -> CacheOptions {
125        match *self {
126            Self::Enabled(true) => CacheOptions::default(),
127            Self::Enabled(false) => CacheOptions::off(),
128            Self::Tuned(options) => options,
129        }
130    }
131}
132
133/// Keeps a positive answer `ttl` and a negative one `negative_ttl`.
134struct Lifetimes<V> {
135    ttl: Duration,
136    negative_ttl: Duration,
137    negative: fn(&V) -> bool,
138}
139
140impl<K, V> Expiry<K, V> for Lifetimes<V> {
141    fn expire_after_create(&self, _key: &K, value: &V, _created_at: Instant) -> Option<Duration> {
142        Some(if (self.negative)(value) {
143            self.negative_ttl
144        } else {
145            self.ttl
146        })
147    }
148}
149
150fn cache<K, V>(options: CacheOptions, negative: fn(&V) -> bool) -> Option<Cache<K, V>>
151where
152    K: Hash + Eq + Send + Sync + 'static,
153    V: Clone + Send + Sync + 'static,
154{
155    options.keeps_anything().then(|| {
156        Cache::builder()
157            .max_capacity(options.max_entries)
158            .expire_after(Lifetimes {
159                ttl: options.ttl,
160                negative_ttl: options.negative_ttl,
161                negative,
162            })
163            .build()
164    })
165}
166
167/// A decision's key: who (id, name, groups in order), what and on what.
168type DecisionKey = (String, String, Vec<String>, String, String, Vec<String>);
169
170/// A provider with its lookups and decisions kept for a short while.
171///
172/// It implements `Directory` and `Authorizer` for a provider that does, answering from memory
173/// within the [`CacheOptions`], and `Accounts` by delegating, clearing every kept answer when
174/// an account is put or removed. It holds the provider in an [`Arc`], so a host wraps a
175/// loaded plugin's handle. `Debug` shows counts only.
176///
177/// ```
178/// use std::sync::Arc;
179/// use coqui_access::{Directory, Lookup, Person};
180/// use coqui_access::guatiao::library::ProviderError;
181/// use coqui_access_kit::{CacheOptions, Cached};
182///
183/// struct One;
184/// impl Directory for One {
185///     fn lookup(&self, lookup: Lookup) -> Result<Option<Person>, ProviderError> {
186///         Ok((lookup.value == "alice").then(|| Person { id: "1".into(), ..Person::default() }))
187///     }
188/// }
189///
190/// let cached = Cached::new(Arc::new(One), CacheOptions::default());
191/// let alice = Lookup { by: "name".into(), value: "alice".into(), ..Lookup::default() };
192/// assert_eq!(cached.lookup(alice.clone()).unwrap().unwrap().id, "1");
193/// cached.invalidate(&alice);
194/// ```
195pub struct Cached<T: ?Sized> {
196    inner: Arc<T>,
197    options: CacheOptions,
198    lookups: Option<Cache<(String, String), Option<Person>>>,
199    decisions: Option<Cache<DecisionKey, AuthorizationDecision>>,
200}
201
202impl<T: ?Sized> fmt::Debug for Cached<T> {
203    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
204        let count = |cache: Option<u64>| cache.unwrap_or(0);
205        formatter
206            .debug_struct("Cached")
207            .field("options", &self.options)
208            .field(
209                "lookups",
210                &count(self.lookups.as_ref().map(Cache::entry_count)),
211            )
212            .field(
213                "decisions",
214                &count(self.decisions.as_ref().map(Cache::entry_count)),
215            )
216            .finish_non_exhaustive()
217    }
218}
219
220impl<T: ?Sized> Cached<T> {
221    /// `inner`, with its answers kept as `options` say. Nothing is asked yet.
222    pub fn new(inner: Arc<T>, options: CacheOptions) -> Self {
223        Self {
224            inner,
225            options,
226            lookups: cache(options, Option::is_none),
227            decisions: cache(options, |decision: &AuthorizationDecision| {
228                !decision.allowed
229            }),
230        }
231    }
232
233    /// The provider behind the cache.
234    pub fn inner(&self) -> &Arc<T> {
235        &self.inner
236    }
237
238    /// The options in force.
239    pub fn options(&self) -> CacheOptions {
240        self.options
241    }
242
243    /// Forgets what is kept for `lookup`, so the next one asks the provider.
244    pub fn invalidate(&self, lookup: &Lookup) {
245        if let Some(lookups) = &self.lookups {
246            lookups.invalidate(&(lookup.by.clone(), lookup.value.clone()));
247        }
248    }
249
250    /// Forgets every lookup and decision kept.
251    pub fn invalidate_all(&self) {
252        if let Some(lookups) = &self.lookups {
253            lookups.invalidate_all();
254        }
255        if let Some(decisions) = &self.decisions {
256            decisions.invalidate_all();
257        }
258    }
259}
260
261impl<T: Directory + ?Sized> Directory for Cached<T> {
262    fn lookup(&self, lookup: Lookup) -> Result<Option<Person>, ProviderError> {
263        let Some(lookups) = &self.lookups else {
264            return self.inner.lookup(lookup);
265        };
266        let key = (lookup.by.clone(), lookup.value.clone());
267        if let Some(kept) = lookups.get(&key) {
268            return Ok(kept);
269        }
270        let found = self.inner.lookup(lookup)?;
271        lookups.insert(key, found.clone());
272        Ok(found)
273    }
274
275    fn describe(&self) -> Result<Description, ProviderError> {
276        Directory::describe(&*self.inner)
277    }
278}
279
280impl<T: Authorizer + ?Sized> Authorizer for Cached<T> {
281    fn authorize(
282        &self,
283        request: AuthorizationRequest,
284    ) -> Result<AuthorizationDecision, ProviderError> {
285        let Some(decisions) = &self.decisions else {
286            return self.inner.authorize(request);
287        };
288        let mut groups = request.person.groups.clone();
289        groups.sort();
290        let key = (
291            request.person.id.clone(),
292            request.person.name.clone(),
293            groups,
294            request.action.clone(),
295            request.resource.clone(),
296            // The same resource under another parent may be decided otherwise.
297            request.ancestors.clone(),
298        );
299        if let Some(kept) = decisions.get(&key) {
300            return Ok(kept);
301        }
302        let decided = self.inner.authorize(request)?;
303        decisions.insert(key, decided.clone());
304        Ok(decided)
305    }
306}
307
308impl<T: Accounts + ?Sized> Accounts for Cached<T> {
309    fn accounts(&self) -> Result<Vec<AccountInfo>, ProviderError> {
310        self.inner.accounts()
311    }
312
313    fn put(&self, account: AccountPut) -> Result<PutOutcome, ProviderError> {
314        let outcome = self.inner.put(account);
315        self.invalidate_all();
316        outcome
317    }
318
319    fn remove(&self, name: String) -> Result<(), ProviderError> {
320        let removed = self.inner.remove(name);
321        self.invalidate_all();
322        removed
323    }
324
325    fn waiting(&self) -> Result<Vec<Waiting>, ProviderError> {
326        self.inner.waiting()
327    }
328}
329
330#[cfg(test)]
331mod tests;