ans-verify 0.1.3

ANS Trust Verification library for the Agent Name Service
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
//! SCITT-specific caches for verified receipts and status tokens.
//!
//! These caches are independent of the existing [`BadgeCache`](crate::BadgeCache).
//! They store already-verified artifacts received from remote agents in HTTP
//! headers. The verifier side does NOT proactively refresh — when a cached token
//! expires, the next request from that agent will carry a fresh token, or the
//! verifier falls back to badge.
//!
//! - [`ReceiptCache`]: Fixed TTL (default 24h). Receipts are immutable Merkle proofs.
//! - [`StatusTokenCache`]: Per-entry TTL derived from the token's `exp` claim.

use std::fmt;
use std::sync::Arc;
use std::time::{Duration, Instant};

use moka::future::Cache;
use moka::policy::Expiry;
use uuid::Uuid;

use super::receipt::VerifiedReceipt;
use super::status_token::VerifiedStatusToken;

/// Default receipt cache TTL: 24 hours.
///
/// Receipts are immutable (append-only Merkle proofs). The spec says "cache
/// indefinitely" — 24h is a conservative operational default to bound memory.
const DEFAULT_RECEIPT_TTL: Duration = Duration::from_secs(24 * 60 * 60);

/// Default maximum cache entries.
const DEFAULT_MAX_ENTRIES: u64 = 1000;

/// Cache for verified SCITT receipts, keyed by agent ID.
///
/// Receipts are immutable proofs of append-only log inclusion. They use a
/// fixed TTL (default 24h) since the receipt content never changes — only
/// the tree grows. This cache is used on the verifier side to avoid
/// re-verifying receipts that have already been validated from remote
/// agents' HTTP headers.
pub struct ReceiptCache {
    cache: Cache<Uuid, Arc<VerifiedReceipt>>,
    ttl: Duration,
}

impl fmt::Debug for ReceiptCache {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("ReceiptCache")
            .field("ttl", &self.ttl)
            .field("entry_count", &self.cache.entry_count())
            .finish()
    }
}

impl ReceiptCache {
    /// Create a new receipt cache with the given TTL and max capacity.
    pub fn new(ttl: Duration, max_entries: u64) -> Self {
        let cache = Cache::builder()
            .max_capacity(max_entries)
            .time_to_live(ttl)
            .build();
        Self { cache, ttl }
    }

    /// Create a new receipt cache with default settings (24h TTL, 1000 entries).
    pub fn with_defaults() -> Self {
        Self::new(DEFAULT_RECEIPT_TTL, DEFAULT_MAX_ENTRIES)
    }

    /// Get a cached receipt by agent ID.
    pub async fn get(&self, agent_id: &Uuid) -> Option<Arc<VerifiedReceipt>> {
        self.cache.get(agent_id).await
    }

    /// Insert a verified receipt into the cache.
    pub async fn insert(&self, agent_id: Uuid, receipt: Arc<VerifiedReceipt>) {
        self.cache.insert(agent_id, receipt).await;
    }

    /// Invalidate a cached receipt.
    pub async fn invalidate(&self, agent_id: &Uuid) {
        self.cache.invalidate(agent_id).await;
    }

    /// Returns the number of entries in the cache.
    pub fn entry_count(&self) -> u64 {
        self.cache.entry_count()
    }

    /// Returns the configured TTL.
    pub fn ttl(&self) -> Duration {
        self.ttl
    }
}

impl Default for ReceiptCache {
    fn default() -> Self {
        Self::with_defaults()
    }
}

/// Per-entry expiry policy for status tokens.
///
/// Each status token carries its own `exp` claim (Unix timestamp). The cache
/// entry's TTL is set to the remaining time until `exp`, ensuring tokens are
/// evicted precisely when they expire rather than on a uniform schedule.
struct StatusTokenExpiry;

impl Expiry<Uuid, Arc<VerifiedStatusToken>> for StatusTokenExpiry {
    fn expire_after_create(
        &self,
        _key: &Uuid,
        value: &Arc<VerifiedStatusToken>,
        _created_at: Instant,
    ) -> Option<Duration> {
        let now = chrono::Utc::now().timestamp();
        let remaining = (value.payload.exp - now).max(0).cast_unsigned();
        Some(Duration::from_secs(remaining))
    }

    // On read: keep the current expiration (don't reset on access).

    fn expire_after_update(
        &self,
        _key: &Uuid,
        value: &Arc<VerifiedStatusToken>,
        _updated_at: Instant,
        _duration_until_expiry: Option<Duration>,
    ) -> Option<Duration> {
        // Recalculate TTL from the new token's exp claim.
        let now = chrono::Utc::now().timestamp();
        let remaining = (value.payload.exp - now).max(0).cast_unsigned();
        Some(Duration::from_secs(remaining))
    }
}

/// Cache for verified SCITT status tokens, keyed by agent ID.
///
/// Uses per-entry TTL derived from each token's `exp` claim via the Moka
/// [`Expiry`] trait. When a token expires, the cache automatically evicts it.
/// The verifier does not proactively refresh — the next request from that agent
/// will carry a fresh token in its headers.
pub struct StatusTokenCache {
    cache: Cache<Uuid, Arc<VerifiedStatusToken>>,
}

impl fmt::Debug for StatusTokenCache {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("StatusTokenCache")
            .field("entry_count", &self.cache.entry_count())
            .finish()
    }
}

impl StatusTokenCache {
    /// Create a new status token cache with the given max capacity.
    pub fn new(max_entries: u64) -> Self {
        let cache = Cache::builder()
            .max_capacity(max_entries)
            .expire_after(StatusTokenExpiry)
            .build();
        Self { cache }
    }

    /// Create a new status token cache with default settings (1000 entries).
    pub fn with_defaults() -> Self {
        Self::new(DEFAULT_MAX_ENTRIES)
    }

    /// Get a cached status token by agent ID.
    pub async fn get(&self, agent_id: &Uuid) -> Option<Arc<VerifiedStatusToken>> {
        self.cache.get(agent_id).await
    }

    /// Insert a verified status token into the cache.
    ///
    /// The entry's TTL is automatically derived from the token's `exp` claim.
    pub async fn insert(&self, agent_id: Uuid, token: Arc<VerifiedStatusToken>) {
        self.cache.insert(agent_id, token).await;
    }

    /// Invalidate a cached status token.
    pub async fn invalidate(&self, agent_id: &Uuid) {
        self.cache.invalidate(agent_id).await;
    }

    /// Returns the number of entries in the cache.
    pub fn entry_count(&self) -> u64 {
        self.cache.entry_count()
    }
}

impl Default for StatusTokenCache {
    fn default() -> Self {
        Self::with_defaults()
    }
}

#[allow(clippy::unwrap_used, clippy::expect_used)]
#[cfg(test)]
mod tests {
    use std::collections::BTreeMap;

    use ans_types::{BadgeStatus, CertFingerprint, StatusTokenPayload};

    use super::*;

    fn make_verified_receipt(tree_size: u64, leaf_index: u64) -> VerifiedReceipt {
        VerifiedReceipt {
            tree_size,
            leaf_index,
            root_hash: [0u8; 32],
            event_bytes: b"test-event".to_vec(),
            key_id: [0xDE, 0xAD, 0xBE, 0xEF],
            iss: None,
            iat: None,
        }
    }

    fn make_verified_token(exp: i64) -> VerifiedStatusToken {
        let fp = CertFingerprint::from_bytes([0u8; 32]);
        VerifiedStatusToken {
            payload: StatusTokenPayload::new(
                Uuid::nil(),
                BadgeStatus::Active,
                0,
                exp,
                ans_types::AnsName::parse("ans://v1.0.0.agent.example.com").unwrap(),
                vec![],
                vec![ans_types::CertEntry::new(
                    fp,
                    ans_types::CertType::X509DvServer,
                )],
                BTreeMap::new(),
            ),
            key_id: [0xDE, 0xAD, 0xBE, 0xEF],
        }
    }

    // ── ReceiptCache tests ──────────────────────────────────────────────────

    #[tokio::test]
    async fn receipt_cache_insert_and_get() {
        let cache = ReceiptCache::with_defaults();
        let agent_id = Uuid::new_v4();
        let receipt = Arc::new(make_verified_receipt(10, 3));

        cache.insert(agent_id, receipt.clone()).await;
        let cached = cache.get(&agent_id).await;

        assert!(cached.is_some());
        let cached = cached.unwrap();
        assert_eq!(cached.tree_size, 10);
        assert_eq!(cached.leaf_index, 3);
    }

    #[tokio::test]
    async fn receipt_cache_miss() {
        let cache = ReceiptCache::with_defaults();
        let result = cache.get(&Uuid::new_v4()).await;
        assert!(result.is_none());
    }

    #[tokio::test]
    async fn receipt_cache_invalidate() {
        let cache = ReceiptCache::with_defaults();
        let agent_id = Uuid::new_v4();
        let receipt = Arc::new(make_verified_receipt(1, 0));

        cache.insert(agent_id, receipt).await;
        assert!(cache.get(&agent_id).await.is_some());

        cache.invalidate(&agent_id).await;
        assert!(cache.get(&agent_id).await.is_none());
    }

    #[tokio::test]
    async fn receipt_cache_entry_count() {
        let cache = ReceiptCache::with_defaults();
        assert_eq!(cache.entry_count(), 0);

        let id1 = Uuid::new_v4();
        let id2 = Uuid::new_v4();
        cache
            .insert(id1, Arc::new(make_verified_receipt(1, 0)))
            .await;
        cache
            .insert(id2, Arc::new(make_verified_receipt(2, 1)))
            .await;

        // Moka updates entry count asynchronously; run pending tasks
        cache.cache.run_pending_tasks().await;
        assert_eq!(cache.entry_count(), 2);
    }

    #[tokio::test]
    async fn receipt_cache_custom_ttl() {
        let cache = ReceiptCache::new(Duration::from_secs(1), 100);
        assert_eq!(cache.ttl(), Duration::from_secs(1));
    }

    #[tokio::test]
    async fn receipt_cache_overwrite() {
        let cache = ReceiptCache::with_defaults();
        let agent_id = Uuid::new_v4();

        cache
            .insert(agent_id, Arc::new(make_verified_receipt(5, 2)))
            .await;
        cache
            .insert(agent_id, Arc::new(make_verified_receipt(10, 7)))
            .await;

        let cached = cache.get(&agent_id).await.unwrap();
        assert_eq!(cached.tree_size, 10);
        assert_eq!(cached.leaf_index, 7);
    }

    // ── StatusTokenCache tests ──────────────────────────────────────────────

    #[tokio::test]
    async fn token_cache_insert_and_get() {
        let cache = StatusTokenCache::with_defaults();
        let agent_id = Uuid::new_v4();
        // Token expires far in the future
        let token = Arc::new(make_verified_token(4_102_444_800));

        cache.insert(agent_id, token.clone()).await;
        let cached = cache.get(&agent_id).await;

        assert!(cached.is_some());
        assert_eq!(cached.unwrap().payload.status, BadgeStatus::Active);
    }

    #[tokio::test]
    async fn token_cache_miss() {
        let cache = StatusTokenCache::with_defaults();
        let result = cache.get(&Uuid::new_v4()).await;
        assert!(result.is_none());
    }

    #[tokio::test]
    async fn token_cache_invalidate() {
        let cache = StatusTokenCache::with_defaults();
        let agent_id = Uuid::new_v4();
        let token = Arc::new(make_verified_token(4_102_444_800));

        cache.insert(agent_id, token).await;
        assert!(cache.get(&agent_id).await.is_some());

        cache.invalidate(&agent_id).await;
        assert!(cache.get(&agent_id).await.is_none());
    }

    #[tokio::test]
    async fn token_cache_already_expired_evicted() {
        let cache = StatusTokenCache::with_defaults();
        let agent_id = Uuid::new_v4();
        // Token already expired (year 2000)
        let token = Arc::new(make_verified_token(946_684_800));

        cache.insert(agent_id, token).await;
        // Run pending tasks so moka processes the zero-TTL eviction
        cache.cache.run_pending_tasks().await;

        // Should be evicted immediately (or on next access)
        let cached = cache.get(&agent_id).await;
        assert!(cached.is_none(), "already-expired token should be evicted");
    }

    #[tokio::test]
    async fn token_cache_entry_count() {
        let cache = StatusTokenCache::with_defaults();
        assert_eq!(cache.entry_count(), 0);

        let id1 = Uuid::new_v4();
        let id2 = Uuid::new_v4();
        cache
            .insert(id1, Arc::new(make_verified_token(4_102_444_800)))
            .await;
        cache
            .insert(id2, Arc::new(make_verified_token(4_102_444_800)))
            .await;

        cache.cache.run_pending_tasks().await;
        assert_eq!(cache.entry_count(), 2);
    }

    #[tokio::test]
    async fn token_cache_overwrite_with_new_expiry() {
        let cache = StatusTokenCache::with_defaults();
        let agent_id = Uuid::new_v4();

        // Insert with far-future expiry
        cache
            .insert(agent_id, Arc::new(make_verified_token(4_102_444_800)))
            .await;

        // Overwrite with different expiry
        let new_exp = chrono::Utc::now().timestamp() + 3600; // 1 hour from now
        cache
            .insert(agent_id, Arc::new(make_verified_token(new_exp)))
            .await;

        let cached = cache.get(&agent_id).await.unwrap();
        assert_eq!(cached.payload.exp, new_exp);
    }

    // ── StatusTokenExpiry unit tests ────────────────────────────────────────

    #[test]
    fn expiry_future_token_returns_positive_duration() {
        let expiry = StatusTokenExpiry;
        let exp = chrono::Utc::now().timestamp() + 3600; // 1 hour from now
        let token = Arc::new(make_verified_token(exp));

        let duration = expiry.expire_after_create(&Uuid::nil(), &token, Instant::now());
        assert!(duration.is_some());
        let dur = duration.unwrap();
        // Should be roughly 3600 seconds (allow 10s tolerance for test execution)
        assert!(dur.as_secs() >= 3590);
        assert!(dur.as_secs() <= 3610);
    }

    #[test]
    fn expiry_past_token_returns_zero_duration() {
        let expiry = StatusTokenExpiry;
        // Token expired in the past
        let token = Arc::new(make_verified_token(946_684_800));

        let duration = expiry.expire_after_create(&Uuid::nil(), &token, Instant::now());
        assert!(duration.is_some());
        assert_eq!(duration.unwrap(), Duration::from_secs(0));
    }

    #[test]
    fn expiry_exactly_now_returns_zero() {
        let expiry = StatusTokenExpiry;
        let now = chrono::Utc::now().timestamp();
        let token = Arc::new(make_verified_token(now));

        let duration = expiry.expire_after_create(&Uuid::nil(), &token, Instant::now());
        assert!(duration.is_some());
        // 0 or 1 second depending on timing
        assert!(duration.unwrap().as_secs() <= 1);
    }
}