Skip to main content

adk_auth/web_bot_auth/
directory.rs

1//! Key directory sources and the verifier's directory cache. Spec 3.5 §7.3.
2//!
3//! A verifier resolves the origin a `Signature-Agent` member names to its key directory at
4//! `/.well-known/http-message-signatures-directory` (draft-ietf-webbotauth-httpsig-protocol-00
5//! §5.5). [`HttpKeyDirectorySource`] fetches it under the draft's SSRF guidance (§6.7): https
6//! only, public addresses only, no redirects, a timeout and a size limit.
7//! [`InMemoryKeyDirectorySource`] serves directories from memory for tests and for keys
8//! configured out of band.
9
10use std::collections::HashMap;
11use std::sync::Arc;
12use std::sync::atomic::{AtomicUsize, Ordering};
13use std::time::Duration;
14
15use adk_core::Clock;
16use adk_core::egress::{EgressPolicy, GuardedClient, find_denial};
17use async_trait::async_trait;
18use chrono::{DateTime, Utc};
19use tokio::sync::{Mutex, RwLock};
20
21use super::keys::{DirectoryKey, KeyDirectory};
22use super::{DIRECTORY_MEDIA_TYPE, DIRECTORY_WELL_KNOWN_PATH, WebBotAuthError};
23
24/// A key directory and how long it may be cached.
25#[derive(Debug, Clone, PartialEq, Eq)]
26pub struct FetchedDirectory {
27    /// The directory.
28    pub directory: KeyDirectory,
29    /// The HTTP cache lifetime of the response (RFC 9111 §4.2.1), when it declared one.
30    pub max_age: Option<Duration>,
31}
32
33/// Resolves a directory origin to its key directory (draft §5.5).
34///
35/// `origin` is an ASCII-serialised origin such as `https://bot.example`. Implementations
36/// return [`WebBotAuthError::DirectoryUnavailable`] or [`WebBotAuthError::MalformedDirectory`]
37/// when no directory can be read, and [`WebBotAuthError::EgressRefused`] when policy forbids the
38/// fetch. Spec 3.5 §7.3.
39///
40/// # Example
41///
42/// ```rust
43/// use std::time::Duration;
44/// use adk_auth::web_bot_auth::{Ed25519SigningKey, InMemoryKeyDirectorySource, KeyDirectory, KeyDirectorySource};
45///
46/// # #[tokio::main(flavor = "current_thread")]
47/// # async fn main() {
48/// let key = Ed25519SigningKey::generate().unwrap();
49/// let source = InMemoryKeyDirectorySource::new();
50/// source.insert("https://bot.example", KeyDirectory::from_keys([&key]), Some(Duration::from_secs(300))).await;
51/// let fetched = source.fetch("https://bot.example").await.unwrap();
52/// assert!(fetched.directory.find(key.thumbprint()).is_some());
53/// # }
54/// ```
55#[async_trait]
56pub trait KeyDirectorySource: Send + Sync {
57    /// Fetches the key directory published at `origin`.
58    async fn fetch(&self, origin: &str) -> Result<FetchedDirectory, WebBotAuthError>;
59}
60
61/// Directories held in memory, keyed by origin.
62#[derive(Debug, Default)]
63pub struct InMemoryKeyDirectorySource {
64    directories: RwLock<HashMap<String, FetchedDirectory>>,
65    fetches: AtomicUsize,
66}
67
68impl InMemoryKeyDirectorySource {
69    /// Creates an empty source.
70    pub fn new() -> Self {
71        Self::default()
72    }
73
74    /// Publishes `directory` at `origin` with an optional cache lifetime.
75    pub async fn insert(&self, origin: &str, directory: KeyDirectory, max_age: Option<Duration>) {
76        self.directories
77            .write()
78            .await
79            .insert(origin.to_string(), FetchedDirectory { directory, max_age });
80    }
81
82    /// Removes the directory at `origin`, so later fetches fail as unavailable.
83    pub async fn remove(&self, origin: &str) {
84        self.directories.write().await.remove(origin);
85    }
86
87    /// How many times [`fetch`](KeyDirectorySource::fetch) has been called.
88    pub fn fetch_count(&self) -> usize {
89        self.fetches.load(Ordering::SeqCst)
90    }
91}
92
93#[async_trait]
94impl KeyDirectorySource for InMemoryKeyDirectorySource {
95    async fn fetch(&self, origin: &str) -> Result<FetchedDirectory, WebBotAuthError> {
96        self.fetches.fetch_add(1, Ordering::SeqCst);
97        self.directories.read().await.get(origin).cloned().ok_or_else(|| {
98            WebBotAuthError::DirectoryUnavailable {
99                origin: origin.to_string(),
100                reason: "no directory is published at this origin".into(),
101            }
102        })
103    }
104}
105
106/// Fetches key directories over HTTPS under the draft's SSRF guidance (§6.7).
107///
108/// Defaults: https only and public addresses only ([`EgressPolicy::default`]), checked by a
109/// [`GuardedClient`] on the URL and again on every resolved address; no proxy; no redirects
110/// (§5.5); a 5 s timeout;
111/// 64 KiB and 64 keys at most; the response must be `200 OK` with media type
112/// `application/http-message-signatures-directory+json`.
113///
114/// # Example
115///
116/// ```rust
117/// use std::time::Duration;
118/// use adk_auth::web_bot_auth::HttpKeyDirectorySource;
119///
120/// let source = HttpKeyDirectorySource::builder()
121///     .timeout(Duration::from_secs(3))
122///     .max_bytes(32 * 1024)
123///     .build()
124///     .unwrap();
125/// # let _ = source;
126/// ```
127#[derive(Debug, Clone)]
128pub struct HttpKeyDirectorySource {
129    client: GuardedClient,
130    max_bytes: usize,
131    max_keys: usize,
132}
133
134impl HttpKeyDirectorySource {
135    /// Creates a source with the default limits.
136    ///
137    /// # Errors
138    ///
139    /// Returns [`WebBotAuthError::InvalidConfig`] when the HTTP client cannot be built.
140    pub fn new() -> Result<Self, WebBotAuthError> {
141        Self::builder().build()
142    }
143
144    /// Starts a builder with the default limits.
145    pub fn builder() -> HttpKeyDirectorySourceBuilder {
146        HttpKeyDirectorySourceBuilder {
147            egress: EgressPolicy::default(),
148            timeout: Duration::from_secs(5),
149            max_bytes: 64 * 1024,
150            max_keys: 64,
151        }
152    }
153}
154
155/// Builds an [`HttpKeyDirectorySource`].
156#[derive(Debug, Clone)]
157pub struct HttpKeyDirectorySourceBuilder {
158    egress: EgressPolicy,
159    timeout: Duration,
160    max_bytes: usize,
161    max_keys: usize,
162}
163
164impl HttpKeyDirectorySourceBuilder {
165    /// Sets the egress policy. [`EgressPolicy::allow_private_networks`] admits loopback,
166    /// private addresses and plain http (never cloud metadata), for tests and in-cluster
167    /// directories only.
168    pub fn egress_policy(mut self, egress: EgressPolicy) -> Self {
169        self.egress = egress;
170        self
171    }
172
173    /// Sets the wall-clock limit for one fetch.
174    pub fn timeout(mut self, timeout: Duration) -> Self {
175        self.timeout = timeout;
176        self
177    }
178
179    /// Sets the largest directory body accepted.
180    pub fn max_bytes(mut self, max_bytes: usize) -> Self {
181        self.max_bytes = max_bytes;
182        self
183    }
184
185    /// Sets the largest number of keys a directory may list.
186    pub fn max_keys(mut self, max_keys: usize) -> Self {
187        self.max_keys = max_keys;
188        self
189    }
190
191    /// Builds the source.
192    ///
193    /// # Errors
194    ///
195    /// Returns [`WebBotAuthError::InvalidConfig`] when the HTTP client cannot be built.
196    pub fn build(self) -> Result<HttpKeyDirectorySource, WebBotAuthError> {
197        let client = GuardedClient::builder(self.egress)
198            .redirects(0)
199            .timeout(self.timeout)
200            .connect_timeout(self.timeout.min(Duration::from_secs(5)))
201            .user_agent(concat!("adk-rust-web-bot-auth/", env!("CARGO_PKG_VERSION")))
202            .build()
203            .map_err(|e| WebBotAuthError::InvalidConfig { reason: e.to_string() })?;
204        Ok(HttpKeyDirectorySource { client, max_bytes: self.max_bytes, max_keys: self.max_keys })
205    }
206}
207
208#[async_trait]
209impl KeyDirectorySource for HttpKeyDirectorySource {
210    async fn fetch(&self, origin: &str) -> Result<FetchedDirectory, WebBotAuthError> {
211        let unavailable = |reason: String| WebBotAuthError::DirectoryUnavailable {
212            origin: origin.to_string(),
213            reason,
214        };
215        let malformed = |reason: String| WebBotAuthError::MalformedDirectory {
216            origin: origin.to_string(),
217            reason,
218        };
219        let refused =
220            |reason: String| WebBotAuthError::EgressRefused { origin: origin.to_string(), reason };
221        let url = format!("{origin}{DIRECTORY_WELL_KNOWN_PATH}");
222        if let Err(e) = reqwest::Url::parse(&url) {
223            return Err(WebBotAuthError::InvalidConfig {
224                reason: format!("`{origin}` is not an origin: {e}"),
225            });
226        }
227        let mut response = self
228            .client
229            .get(&url)
230            .map_err(|denial| refused(denial.to_string()))?
231            .header(reqwest::header::ACCEPT, DIRECTORY_MEDIA_TYPE)
232            .send()
233            .await
234            .map_err(|error| match find_denial(&error) {
235                Some(denial) => refused(denial.to_string()),
236                None => unavailable(error.without_url().to_string()),
237            })?;
238        let status = response.status();
239        if status != reqwest::StatusCode::OK {
240            return Err(unavailable(format!(
241                "it answered {status}; a directory answers 200 OK and redirects are not followed"
242            )));
243        }
244        let media_type = response
245            .headers()
246            .get(reqwest::header::CONTENT_TYPE)
247            .and_then(|value| value.to_str().ok())
248            .and_then(|value| value.split(';').next())
249            .map(|value| value.trim().to_ascii_lowercase());
250        if media_type.as_deref() != Some(DIRECTORY_MEDIA_TYPE) {
251            return Err(malformed(format!(
252                "media type is {}, not {DIRECTORY_MEDIA_TYPE}",
253                media_type.as_deref().unwrap_or("absent")
254            )));
255        }
256        if response.content_length().is_some_and(|length| length > self.max_bytes as u64) {
257            return Err(malformed(format!("it is larger than {} bytes", self.max_bytes)));
258        }
259        let max_age = cache_lifetime(response.headers());
260        let mut body = Vec::new();
261        while let Some(chunk) =
262            response.chunk().await.map_err(|e| unavailable(e.without_url().to_string()))?
263        {
264            if body.len() + chunk.len() > self.max_bytes {
265                return Err(malformed(format!("it is larger than {} bytes", self.max_bytes)));
266            }
267            body.extend_from_slice(&chunk);
268        }
269        let directory = KeyDirectory::parse(&body, self.max_keys).map_err(malformed)?;
270        Ok(FetchedDirectory { directory, max_age })
271    }
272}
273
274/// The freshness lifetime of a response (RFC 9111 §4.2.1, less its `Age`): `no-store` and
275/// `no-cache` give zero, then `max-age`, then `Expires` minus `Date`.
276fn cache_lifetime(headers: &reqwest::header::HeaderMap) -> Option<Duration> {
277    let header = |name: reqwest::header::HeaderName| {
278        headers.get(name).and_then(|value| value.to_str().ok()).map(str::to_string)
279    };
280    let mut lifetime = None;
281    if let Some(cache_control) = header(reqwest::header::CACHE_CONTROL) {
282        for directive in cache_control.split(',').map(|d| d.trim().to_ascii_lowercase()) {
283            if directive == "no-store" || directive == "no-cache" {
284                return Some(Duration::ZERO);
285            }
286            if lifetime.is_none() {
287                lifetime = directive
288                    .strip_prefix("max-age=")
289                    .and_then(|v| v.trim_matches('"').parse::<u64>().ok())
290                    .map(Duration::from_secs);
291            }
292        }
293    }
294    if lifetime.is_none()
295        && let Some(expires) = header(reqwest::header::EXPIRES)
296    {
297        let date = header(reqwest::header::DATE).and_then(|d| httpdate::parse_http_date(&d).ok());
298        lifetime = Some(match (httpdate::parse_http_date(&expires), date) {
299            (Ok(expires), Some(date)) => expires.duration_since(date).unwrap_or_default(),
300            (Ok(_), None) | (Err(_), _) => Duration::ZERO,
301        });
302    }
303    let age = header(reqwest::header::AGE).and_then(|a| a.parse::<u64>().ok()).unwrap_or(0);
304    lifetime.map(|lifetime| lifetime.saturating_sub(Duration::from_secs(age)))
305}
306
307/// How the verifier caches key directories (draft Appendix C.4–C.5).
308///
309/// A directory is fresh for its HTTP cache lifetime clamped to `min_ttl..=max_ttl`, or
310/// `default_ttl` when the response declares none. A failed refresh never evicts a cached
311/// directory (draft §6.10): the stale copy keeps verifying for up to `stale_if_error` past its
312/// freshness. A failed fetch with nothing cached is remembered for `negative_ttl`, so a burst of
313/// requests naming a broken directory fetches it once.
314///
315/// # Example
316///
317/// ```rust
318/// use std::time::Duration;
319/// use adk_auth::web_bot_auth::DirectoryCachePolicy;
320///
321/// let policy = DirectoryCachePolicy { max_ttl: Duration::from_secs(3600), ..Default::default() };
322/// assert_eq!(policy.min_ttl, Duration::from_secs(60));
323/// ```
324#[derive(Debug, Clone, Copy, PartialEq, Eq)]
325pub struct DirectoryCachePolicy {
326    /// Shortest time a directory is cached, and the least age before an unknown `keyid` may
327    /// trigger a refetch. Default 60 s.
328    pub min_ttl: Duration,
329    /// Longest time a directory is cached. Default 24 h.
330    pub max_ttl: Duration,
331    /// Lifetime when the response declares none. Default 5 min.
332    pub default_ttl: Duration,
333    /// How long a stale directory keeps verifying while refreshes fail. Default 1 h.
334    pub stale_if_error: Duration,
335    /// How long a failed fetch is remembered. Default 30 s (the draft caps it at 5 min).
336    pub negative_ttl: Duration,
337    /// Most origins held at once; the oldest entry is evicted beyond it. Default 10,000.
338    pub max_entries: usize,
339}
340
341impl Default for DirectoryCachePolicy {
342    fn default() -> Self {
343        Self {
344            min_ttl: Duration::from_secs(60),
345            max_ttl: Duration::from_secs(24 * 60 * 60),
346            default_ttl: Duration::from_secs(5 * 60),
347            stale_if_error: Duration::from_secs(60 * 60),
348            negative_ttl: Duration::from_secs(30),
349            max_entries: 10_000,
350        }
351    }
352}
353
354#[derive(Debug, Clone)]
355enum CacheEntry {
356    Directory {
357        directory: Arc<KeyDirectory>,
358        fetched_at: DateTime<Utc>,
359        fresh_until: DateTime<Utc>,
360    },
361    Failed {
362        error: WebBotAuthError,
363        until: DateTime<Utc>,
364        stale: Option<Box<CacheEntry>>,
365    },
366}
367
368/// The verifier's per-origin directory cache: fresh hits, coalesced fetches, stale-on-error and
369/// negative caching.
370pub(crate) struct DirectoryCache {
371    source: Arc<dyn KeyDirectorySource>,
372    policy: DirectoryCachePolicy,
373    clock: Arc<dyn Clock>,
374    entries: RwLock<HashMap<String, CacheEntry>>,
375    inflight: Mutex<HashMap<String, Arc<Mutex<()>>>>,
376}
377
378impl std::fmt::Debug for DirectoryCache {
379    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
380        f.debug_struct("DirectoryCache").field("policy", &self.policy).finish_non_exhaustive()
381    }
382}
383
384impl DirectoryCache {
385    pub(crate) fn new(
386        source: Arc<dyn KeyDirectorySource>,
387        policy: DirectoryCachePolicy,
388        clock: Arc<dyn Clock>,
389    ) -> Self {
390        Self {
391            source,
392            policy,
393            clock,
394            entries: RwLock::new(HashMap::new()),
395            inflight: Mutex::new(HashMap::new()),
396        }
397    }
398
399    /// The key `keyid` from the directory at `origin`.
400    pub(crate) async fn key(
401        &self,
402        origin: &str,
403        keyid: &str,
404    ) -> Result<DirectoryKey, WebBotAuthError> {
405        if let Lookup::Done(result) = self.lookup(origin, keyid).await {
406            return result;
407        }
408        // Concurrent misses for one origin share a single fetch (draft Appendix C.3).
409        let lock = {
410            let mut inflight = self.inflight.lock().await;
411            Arc::clone(inflight.entry(origin.to_string()).or_default())
412        };
413        let result = {
414            let _guard = lock.lock().await;
415            // Another task may have refreshed the entry while this one waited.
416            match self.lookup(origin, keyid).await {
417                Lookup::Done(result) => result,
418                Lookup::Fetch => self.refresh(origin, keyid).await,
419            }
420        };
421        let mut inflight = self.inflight.lock().await;
422        if inflight.get(origin).is_some_and(|l| Arc::strong_count(l) <= 2) {
423            inflight.remove(origin);
424        }
425        result
426    }
427
428    async fn lookup(&self, origin: &str, keyid: &str) -> Lookup {
429        let now = self.clock.now();
430        let entries = self.entries.read().await;
431        match entries.get(origin) {
432            Some(CacheEntry::Directory { directory, fetched_at, fresh_until })
433                if now < *fresh_until =>
434            {
435                match directory.find(keyid) {
436                    Some(key) => Lookup::Done(Ok(key.clone())),
437                    // An unknown keyid may be a key added since; refetch once the entry is old
438                    // enough that a stream of invented keyids cannot force a fetch per request.
439                    None if now - *fetched_at >= chrono_duration(self.policy.min_ttl) => {
440                        Lookup::Fetch
441                    }
442                    None => Lookup::Done(Err(unknown_key(origin, keyid))),
443                }
444            }
445            Some(CacheEntry::Failed { error, until, stale }) if now < *until => {
446                match stale.as_deref().and_then(|stale| self.usable_stale(stale, now)) {
447                    Some(directory) => Lookup::Done(
448                        directory.find(keyid).cloned().ok_or_else(|| unknown_key(origin, keyid)),
449                    ),
450                    None => Lookup::Done(Err(error.clone())),
451                }
452            }
453            Some(CacheEntry::Directory { .. } | CacheEntry::Failed { .. }) | None => Lookup::Fetch,
454        }
455    }
456
457    fn usable_stale(&self, entry: &CacheEntry, now: DateTime<Utc>) -> Option<Arc<KeyDirectory>> {
458        match entry {
459            CacheEntry::Directory { directory, fresh_until, .. }
460                if now < *fresh_until + chrono_duration(self.policy.stale_if_error) =>
461            {
462                Some(Arc::clone(directory))
463            }
464            CacheEntry::Directory { .. } | CacheEntry::Failed { .. } => None,
465        }
466    }
467
468    async fn refresh(&self, origin: &str, keyid: &str) -> Result<DirectoryKey, WebBotAuthError> {
469        let fetched = self.source.fetch(origin).await;
470        let now = self.clock.now();
471        let mut entries = self.entries.write().await;
472        match fetched {
473            Ok(fetched) => {
474                let ttl = fetched
475                    .max_age
476                    .unwrap_or(self.policy.default_ttl)
477                    .clamp(self.policy.min_ttl, self.policy.max_ttl.max(self.policy.min_ttl));
478                let directory = Arc::new(fetched.directory);
479                let key = directory.find(keyid).cloned();
480                // A directory that resolves is evidence and replaces what was cached (draft §4.4).
481                self.insert(
482                    &mut entries,
483                    origin,
484                    CacheEntry::Directory {
485                        directory,
486                        fetched_at: now,
487                        fresh_until: now + chrono_duration(ttl),
488                    },
489                    now,
490                );
491                tracing::debug!(
492                    directory.origin = origin,
493                    cache.ttl_secs = ttl.as_secs(),
494                    "key directory fetched"
495                );
496                key.ok_or_else(|| unknown_key(origin, keyid))
497            }
498            Err(error) => {
499                // A failed fetch is not evidence and never evicts a cached directory (draft §6.10).
500                let stale = match entries.remove(origin) {
501                    Some(entry @ CacheEntry::Directory { .. }) => Some(Box::new(entry)),
502                    Some(CacheEntry::Failed { stale, .. }) => stale,
503                    None => None,
504                };
505                let usable = stale.as_deref().and_then(|entry| self.usable_stale(entry, now));
506                tracing::warn!(directory.origin = origin, error = %error, stale = usable.is_some(), "key directory fetch failed");
507                let result = match &usable {
508                    Some(directory) => {
509                        directory.find(keyid).cloned().ok_or_else(|| unknown_key(origin, keyid))
510                    }
511                    None => Err(error.clone()),
512                };
513                let until = now + chrono_duration(self.policy.negative_ttl);
514                self.insert(&mut entries, origin, CacheEntry::Failed { error, until, stale }, now);
515                result
516            }
517        }
518    }
519
520    fn insert(
521        &self,
522        entries: &mut HashMap<String, CacheEntry>,
523        origin: &str,
524        entry: CacheEntry,
525        now: DateTime<Utc>,
526    ) {
527        if entries.len() >= self.policy.max_entries && !entries.contains_key(origin) {
528            entries.retain(|_, entry| match entry {
529                CacheEntry::Directory { fresh_until, .. } => *fresh_until > now,
530                CacheEntry::Failed { until, .. } => *until > now,
531            });
532            if entries.len() >= self.policy.max_entries {
533                let oldest = entries
534                    .iter()
535                    .min_by_key(|(_, entry)| match entry {
536                        CacheEntry::Directory { fetched_at, .. } => *fetched_at,
537                        CacheEntry::Failed { until, .. } => *until,
538                    })
539                    .map(|(origin, _)| origin.clone());
540                if let Some(oldest) = oldest {
541                    entries.remove(&oldest);
542                }
543            }
544        }
545        entries.insert(origin.to_string(), entry);
546    }
547}
548
549enum Lookup {
550    Done(Result<DirectoryKey, WebBotAuthError>),
551    Fetch,
552}
553
554fn unknown_key(origin: &str, keyid: &str) -> WebBotAuthError {
555    WebBotAuthError::UnknownKey { origin: origin.to_string(), keyid: keyid.to_string() }
556}
557
558fn chrono_duration(duration: Duration) -> chrono::Duration {
559    chrono::Duration::from_std(duration).unwrap_or(chrono::Duration::MAX)
560}
561
562#[cfg(test)]
563mod tests {
564    use super::*;
565    use reqwest::header::{HeaderMap, HeaderValue};
566
567    fn headers(pairs: &[(&'static str, &str)]) -> HeaderMap {
568        let mut map = HeaderMap::new();
569        for (name, value) in pairs {
570            map.append(*name, HeaderValue::from_str(value).unwrap());
571        }
572        map
573    }
574
575    #[test]
576    fn cache_lifetime_reads_cache_control_expires_and_age() {
577        assert_eq!(
578            cache_lifetime(&headers(&[("cache-control", "public, max-age=86400")])),
579            Some(Duration::from_secs(86_400))
580        );
581        assert_eq!(
582            cache_lifetime(&headers(&[("cache-control", "max-age=600, no-cache")])),
583            Some(Duration::ZERO)
584        );
585        assert_eq!(
586            cache_lifetime(&headers(&[("cache-control", "max-age=600"), ("age", "100")])),
587            Some(Duration::from_secs(500))
588        );
589        assert_eq!(
590            cache_lifetime(&headers(&[
591                ("date", "Sun, 25 Oct 2026 02:00:00 GMT"),
592                ("expires", "Sun, 25 Oct 2026 03:00:00 GMT"),
593            ])),
594            Some(Duration::from_secs(3600))
595        );
596        assert_eq!(cache_lifetime(&headers(&[("expires", "0")])), Some(Duration::ZERO));
597        assert_eq!(cache_lifetime(&headers(&[])), None);
598    }
599
600    #[test]
601    fn defaults_follow_the_draft_ssrf_guidance() {
602        let builder = HttpKeyDirectorySource::builder();
603        assert_eq!(builder.egress, EgressPolicy::public_only());
604        assert_eq!(builder.timeout, Duration::from_secs(5));
605        assert_eq!(builder.max_bytes, 64 * 1024);
606        assert_eq!(builder.max_keys, 64);
607        assert_eq!(
608            DirectoryCachePolicy::default(),
609            DirectoryCachePolicy {
610                min_ttl: Duration::from_secs(60),
611                max_ttl: Duration::from_secs(86_400),
612                default_ttl: Duration::from_secs(300),
613                stale_if_error: Duration::from_secs(3600),
614                negative_ttl: Duration::from_secs(30),
615                max_entries: 10_000,
616            }
617        );
618    }
619
620    #[tokio::test]
621    async fn the_cache_evicts_the_oldest_origin_beyond_max_entries() {
622        let clock = adk_core::ManualClock::new(chrono::Utc::now());
623        let source = Arc::new(InMemoryKeyDirectorySource::new());
624        let key = super::super::Ed25519SigningKey::generate().unwrap();
625        for origin in ["https://a.example", "https://b.example", "https://c.example"] {
626            source.insert(origin, KeyDirectory::from_keys([&key]), None).await;
627        }
628        let policy = DirectoryCachePolicy { max_entries: 2, ..DirectoryCachePolicy::default() };
629        let cache = DirectoryCache::new(source.clone(), policy, Arc::new(clock.clone()));
630        for origin in ["https://a.example", "https://b.example", "https://c.example"] {
631            cache.key(origin, key.thumbprint()).await.unwrap();
632            clock.advance(Duration::from_secs(1));
633        }
634        assert_eq!(cache.entries.read().await.len(), 2);
635        assert!(!cache.entries.read().await.contains_key("https://a.example"));
636        cache.key("https://a.example", key.thumbprint()).await.unwrap();
637        assert_eq!(source.fetch_count(), 4);
638    }
639
640    #[tokio::test]
641    async fn egress_refuses_non_public_origins() {
642        let source = HttpKeyDirectorySource::new().unwrap();
643        for origin in [
644            "https://127.0.0.1",
645            "https://10.0.0.1",
646            "https://169.254.169.254",
647            "https://[::1]",
648            "https://localhost",
649            "https://api.localhost",
650            "http://bot.example",
651            "https://[::ffff:169.254.169.254]",
652            "https://168.63.129.16",
653        ] {
654            assert!(
655                matches!(source.fetch(origin).await, Err(WebBotAuthError::EgressRefused { .. })),
656                "{origin} must be refused"
657            );
658        }
659        assert!(source.client.get("https://bot.example/.well-known/x").is_ok());
660    }
661}