1use 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#[derive(Debug, Clone, PartialEq, Eq)]
26pub struct FetchedDirectory {
27 pub directory: KeyDirectory,
29 pub max_age: Option<Duration>,
31}
32
33#[async_trait]
56pub trait KeyDirectorySource: Send + Sync {
57 async fn fetch(&self, origin: &str) -> Result<FetchedDirectory, WebBotAuthError>;
59}
60
61#[derive(Debug, Default)]
63pub struct InMemoryKeyDirectorySource {
64 directories: RwLock<HashMap<String, FetchedDirectory>>,
65 fetches: AtomicUsize,
66}
67
68impl InMemoryKeyDirectorySource {
69 pub fn new() -> Self {
71 Self::default()
72 }
73
74 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 pub async fn remove(&self, origin: &str) {
84 self.directories.write().await.remove(origin);
85 }
86
87 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#[derive(Debug, Clone)]
128pub struct HttpKeyDirectorySource {
129 client: GuardedClient,
130 max_bytes: usize,
131 max_keys: usize,
132}
133
134impl HttpKeyDirectorySource {
135 pub fn new() -> Result<Self, WebBotAuthError> {
141 Self::builder().build()
142 }
143
144 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#[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 pub fn egress_policy(mut self, egress: EgressPolicy) -> Self {
169 self.egress = egress;
170 self
171 }
172
173 pub fn timeout(mut self, timeout: Duration) -> Self {
175 self.timeout = timeout;
176 self
177 }
178
179 pub fn max_bytes(mut self, max_bytes: usize) -> Self {
181 self.max_bytes = max_bytes;
182 self
183 }
184
185 pub fn max_keys(mut self, max_keys: usize) -> Self {
187 self.max_keys = max_keys;
188 self
189 }
190
191 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
274fn 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
325pub struct DirectoryCachePolicy {
326 pub min_ttl: Duration,
329 pub max_ttl: Duration,
331 pub default_ttl: Duration,
333 pub stale_if_error: Duration,
335 pub negative_ttl: Duration,
337 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
368pub(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 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 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 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 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 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 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}