tenuo 0.3.4

Task-scoped authorization for AI agents: signed warrants that constrain tools and arguments, narrow on delegation, and verify offline. Rust core of Tenuo.
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
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
//! Async counterparts. Trait definitions only; the caller brings the runtime.

use super::authority::{AuthorityError, PresentedAuthority, ReceivedAuthorization};
use super::call::Call;
use super::decision::{Denial, GuardError, Retryability, SdkDenialKind};
use super::guard::{AuthorizedCall, Guard, Guarded};
use super::signer::{HolderSigner, LocalSigner, PopSigningRequest, SignerError};
use crate::crypto::{PublicKey, Signature};
use crate::revocation_tracker::{RevocationError, RevocationUpdate};
use crate::warrant::Warrant;
use async_trait::async_trait;
use chrono::{DateTime, Utc};
use std::fmt;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;

/// Deadline and cancellation for one authorization attempt.
///
/// The host runtime may also drop the future. `control` is passed into the
/// operations this surface exists to wait on: remote PoP signing and remote
/// revocation fetch.
#[derive(Clone, Debug)]
pub struct AttemptControl {
    deadline: Option<DateTime<Utc>>,
    cancelled: Arc<AtomicBool>,
}

impl AttemptControl {
    /// No deadline, not cancelled.
    pub fn new() -> Self {
        Self {
            deadline: None,
            cancelled: Arc::new(AtomicBool::new(false)),
        }
    }

    /// Cancelable, with a deadline for the whole attempt.
    pub fn with_deadline(deadline: DateTime<Utc>) -> Self {
        Self {
            deadline: Some(deadline),
            cancelled: Arc::new(AtomicBool::new(false)),
        }
    }

    /// The attempt deadline, if any.
    pub fn deadline(&self) -> Option<DateTime<Utc>> {
        self.deadline
    }

    /// Request cancellation. Checked before the decision and before the operation runs.
    pub fn cancel(&self) {
        self.cancelled.store(true, Ordering::SeqCst);
    }

    /// Whether cancellation has been requested.
    pub fn is_cancelled(&self) -> bool {
        self.cancelled.load(Ordering::SeqCst)
    }
}

impl Default for AttemptControl {
    fn default() -> Self {
        Self::new()
    }
}

/// Async holder signer. Implementations may be remote; they must honor `control`.
///
/// Accepted by [`PresentedAsyncAuthority`] and therefore by
/// [`Guard::check_async`] / [`Guard::guard_async`]. The sync [`HolderSigner`]
/// path cannot be interrupted and is the wrong place to `block_on` a remote
/// call.
#[async_trait]
pub trait AsyncHolderSigner: Send + Sync {
    /// Public key of the holder this signer speaks for. Must equal the leaf holder.
    fn public_key(&self) -> PublicKey;
    /// Sign a proof of possession, honoring `control`.
    ///
    /// A remote implementation is expected to observe the deadline itself; the host can
    /// refuse before and after this call but cannot interrupt it.
    async fn sign_pop(
        &self,
        request: &PopSigningRequest<'_>,
        control: &AttemptControl,
    ) -> Result<Signature, SignerError>;
}

/// Remote SRL fetch for one async attempt. Called only when the tracker has
/// no fresh snapshot.
#[async_trait]
pub trait AsyncRevocationProvider: Send + Sync {
    /// Fetch a revocation update, honoring `control`.
    ///
    /// Called only when the local state is missing or stale. The result still passes the
    /// tracker's issuer, rollback, and equivocation checks before it can decide anything.
    async fn fetch(&self, control: &AttemptControl) -> Result<RevocationUpdate, RevocationError>;
}

/// Chain plus an async holder signer. The async Guard methods accept this type.
#[derive(Clone)]
pub struct PresentedAsyncAuthority {
    chain: Arc<[Warrant]>,
    signer: Arc<dyn AsyncHolderSigner>,
}

impl PresentedAsyncAuthority {
    /// Bind a chain to an async signer holding its leaf.
    ///
    /// Same validation as the synchronous form: non-empty chain, signer's key equals the
    /// leaf holder.
    pub fn new(
        chain: Vec<Warrant>,
        signer: Arc<dyn AsyncHolderSigner>,
    ) -> Result<Self, AuthorityError> {
        if chain.is_empty() {
            return Err(AuthorityError::EmptyChain);
        }
        let leaf = chain.last().expect("non-empty chain");
        if signer.public_key() != *leaf.authorized_holder() {
            return Err(AuthorityError::SignerMismatch);
        }
        Ok(Self {
            chain: chain.into(),
            signer,
        })
    }

    /// Wrap a sync authority. The adapter signs in-task; `control` can refuse
    /// before or after `sign_pop`, but cannot interrupt a blocking signer.
    pub fn from_sync(authority: &PresentedAuthority) -> Self {
        Self {
            chain: authority.chain_arc(),
            signer: Arc::new(SyncSignerAdapter(authority.signer_arc())),
        }
    }

    /// Last warrant in the chain.
    pub fn leaf(&self) -> &Warrant {
        self.chain.last().expect("non-empty chain")
    }

    /// Full chain, root first.
    pub fn chain(&self) -> &[Warrant] {
        &self.chain
    }

    /// Public key of the leaf holder.
    pub fn holder(&self) -> &PublicKey {
        self.leaf().authorized_holder()
    }

    pub(crate) fn signer(&self) -> &dyn AsyncHolderSigner {
        self.signer.as_ref()
    }

    pub(crate) fn signer_matches_leaf(&self) -> bool {
        self.signer.public_key() == *self.leaf().authorized_holder()
    }
}

impl fmt::Debug for PresentedAsyncAuthority {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("PresentedAsyncAuthority")
            .field("leaf_id", &self.leaf().id().to_string())
            .field("chain_depth", &self.chain.len())
            .field("holder", &self.holder().fingerprint())
            .finish()
    }
}

impl PresentedAuthority {
    /// View this authority as the type [`Guard::check_async`] accepts.
    pub fn as_async(&self) -> PresentedAsyncAuthority {
        PresentedAsyncAuthority::from_sync(self)
    }
}

struct SyncSignerAdapter(Arc<dyn HolderSigner>);

#[async_trait]
impl AsyncHolderSigner for SyncSignerAdapter {
    fn public_key(&self) -> PublicKey {
        self.0.public_key()
    }

    async fn sign_pop(
        &self,
        request: &PopSigningRequest<'_>,
        control: &AttemptControl,
    ) -> Result<Signature, SignerError> {
        if control.is_cancelled() {
            return Err(SignerError::Unavailable);
        }
        self.0.sign_pop(request)
    }
}

#[async_trait]
impl AsyncHolderSigner for LocalSigner {
    fn public_key(&self) -> PublicKey {
        HolderSigner::public_key(self)
    }

    async fn sign_pop(
        &self,
        request: &PopSigningRequest<'_>,
        control: &AttemptControl,
    ) -> Result<Signature, SignerError> {
        if control.is_cancelled() {
            return Err(SignerError::Unavailable);
        }
        HolderSigner::sign_pop(self, request)
    }
}

impl Guard {
    /// Decide, honoring deadline and cancellation.
    pub async fn check_async(
        &self,
        authority: &PresentedAsyncAuthority,
        call: &Call<'_>,
        control: &AttemptControl,
    ) -> Result<super::decision::Decision, Denial> {
        self.preflight_or_deny(authority.chain(), call, control)?;
        match self
            .authorize_holder_async(
                authority,
                &super::guard::AuthorizationAttempt::new(call),
                control,
            )
            .await
        {
            Ok(authorized) => {
                self.reject_or_deny(
                    authority.chain(),
                    call,
                    control,
                    Some(authorized.pop_signature()),
                )?;
                self.complete_allow(&authorized)
            }
            Err((denial, pop)) => {
                self.record_deny(&denial);
                #[cfg(feature = "receipts")]
                self.emit_deny_receipt(authority.chain(), call, &denial, pop.as_ref());
                Err(denial)
            }
        }
    }

    /// Decide over received authorization, honoring deadline and cancellation.
    pub async fn check_received_async(
        &self,
        received: &ReceivedAuthorization<'_>,
        call: &Call<'_>,
        control: &AttemptControl,
    ) -> Result<super::decision::Decision, Denial> {
        self.preflight_or_deny(received.chain(), call, control)?;
        match self.authorize_received(received, call) {
            Ok(authorized) => {
                self.reject_or_deny(
                    received.chain(),
                    call,
                    control,
                    Some(authorized.pop_signature()),
                )?;
                self.complete_allow(&authorized)
            }
            Err(denial) => {
                self.record_deny(&denial);
                #[cfg(feature = "receipts")]
                self.emit_deny_receipt(
                    received.chain(),
                    call,
                    &denial,
                    super::guard::verified_received_pop(&denial, received.signature()),
                );
                Err(denial)
            }
        }
    }

    /// Authorize with an async signer, then run `op` exactly once.
    pub async fn guard_async<T, E>(
        &self,
        authority: &PresentedAsyncAuthority,
        call: &Call<'_>,
        control: &AttemptControl,
        op: impl FnOnce(&AuthorizedCall<'_>) -> Result<T, E>,
    ) -> Result<Guarded<T>, GuardError<E>> {
        self.preflight_or_deny(authority.chain(), call, control)
            .map_err(GuardError::Denied)?;
        let authorized = self
            .authorize_holder_async(
                authority,
                &super::guard::AuthorizationAttempt::new(call),
                control,
            )
            .await
            .map_err(|(denial, pop)| {
                self.record_deny(&denial);
                #[cfg(feature = "receipts")]
                self.emit_deny_receipt(authority.chain(), call, &denial, pop.as_ref());
                GuardError::Denied(denial)
            })?;
        self.reject_or_deny(
            authority.chain(),
            call,
            control,
            Some(authorized.pop_signature()),
        )
        .map_err(GuardError::Denied)?;
        let decision = self
            .complete_allow(&authorized)
            .map_err(GuardError::Denied)?;
        let value = op(&authorized).map_err(GuardError::Operation)?;
        Ok(Guarded { value, decision })
    }

    /// Verify received authorization, then run `op` exactly once.
    pub async fn guard_received_async<T, E>(
        &self,
        received: &ReceivedAuthorization<'_>,
        call: &Call<'_>,
        control: &AttemptControl,
        op: impl FnOnce(&AuthorizedCall<'_>) -> Result<T, E>,
    ) -> Result<Guarded<T>, GuardError<E>> {
        self.preflight_or_deny(received.chain(), call, control)
            .map_err(GuardError::Denied)?;
        let authorized = self.authorize_received(received, call).map_err(|denial| {
            self.record_deny(&denial);
            #[cfg(feature = "receipts")]
            self.emit_deny_receipt(
                received.chain(),
                call,
                &denial,
                super::guard::verified_received_pop(&denial, received.signature()),
            );
            GuardError::Denied(denial)
        })?;
        self.reject_or_deny(
            received.chain(),
            call,
            control,
            Some(authorized.pop_signature()),
        )
        .map_err(GuardError::Denied)?;
        let decision = self
            .complete_allow(&authorized)
            .map_err(GuardError::Denied)?;
        let value = op(&authorized).map_err(GuardError::Operation)?;
        Ok(Guarded { value, decision })
    }

    fn preflight_or_deny(
        &self,
        chain: &[Warrant],
        call: &Call<'_>,
        control: &AttemptControl,
    ) -> Result<(), Denial> {
        self.preflight_async(control).inspect_err(|denial| {
            self.record_deny(denial);
            #[cfg(feature = "receipts")]
            self.emit_deny_receipt(chain, call, denial, None);
        })
    }

    fn reject_or_deny(
        &self,
        chain: &[Warrant],
        call: &Call<'_>,
        control: &AttemptControl,
        pop: Option<&Signature>,
    ) -> Result<(), Denial> {
        self.reject_if_cancelled(control).inspect_err(|denial| {
            self.record_deny(denial);
            #[cfg(feature = "receipts")]
            self.emit_deny_receipt(chain, call, denial, pop);
        })
    }

    pub(crate) fn preflight_async(&self, control: &AttemptControl) -> Result<(), Denial> {
        if control.is_cancelled() {
            return Err(Denial::sdk(
                SdkDenialKind::Cancelled,
                Retryability::AfterBackoff,
                "authorization cancelled",
            ));
        }
        let Some(deadline) = control.deadline() else {
            return Ok(());
        };
        let now = self.now();
        if now >= deadline {
            return Err(Denial::sdk(
                SdkDenialKind::DeadlineExceeded,
                Retryability::AfterBackoff,
                "authorization deadline exceeded",
            ));
        }
        let (window_secs, max_windows) = self.pop_window_config();
        let max_budget = chrono::Duration::seconds(window_secs.saturating_mul(max_windows as i64));
        if deadline - now > max_budget {
            return Err(Denial::sdk(
                SdkDenialKind::DeadlineExceeded,
                Retryability::No,
                "deadline exceeds PoP acceptance range",
            ));
        }
        Ok(())
    }

    fn reject_if_cancelled(&self, control: &AttemptControl) -> Result<(), Denial> {
        if control.is_cancelled() {
            return Err(Denial::sdk(
                SdkDenialKind::Cancelled,
                Retryability::AfterBackoff,
                "authorization cancelled",
            ));
        }
        if control
            .deadline()
            .is_some_and(|deadline| self.now() >= deadline)
        {
            return Err(Denial::sdk(
                SdkDenialKind::DeadlineExceeded,
                Retryability::AfterBackoff,
                "authorization deadline exceeded",
            ));
        }
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::constraints::ConstraintSet;
    use crate::crypto::SigningKey;
    use crate::planes::Authorizer;
    use crate::revocation::SignedRevocationList;
    use crate::revocation_tracker::RevocationTracker;
    use crate::sdk::RevocationMode;
    use crate::warrant::Warrant;
    use std::collections::HashMap;
    use std::sync::atomic::{AtomicUsize, Ordering};
    use std::sync::Arc;
    use std::time::Duration;

    fn mint(issuer: &SigningKey, holder: &SigningKey) -> Warrant {
        Warrant::builder()
            .capability("read", ConstraintSet::new())
            .holder(holder.public_key())
            .ttl(Duration::from_secs(300))
            .build(issuer)
            .unwrap()
    }

    fn guard_for(issuer: &SigningKey) -> Guard {
        let mut authorizer = Authorizer::new();
        authorizer.add_trusted_root(issuer.public_key());
        Guard::builder()
            .authorizer(authorizer)
            .revocation(RevocationMode::TtlOnly {
                max_lifetime: Duration::from_secs(3600),
            })
            .build()
            .unwrap()
    }

    struct Remote {
        key: SigningKey,
        signed: AtomicUsize,
    }

    #[async_trait]
    impl AsyncHolderSigner for Remote {
        fn public_key(&self) -> PublicKey {
            self.key.public_key()
        }

        async fn sign_pop(
            &self,
            request: &PopSigningRequest<'_>,
            control: &AttemptControl,
        ) -> Result<Signature, SignerError> {
            if control.is_cancelled() {
                return Err(SignerError::Unavailable);
            }
            self.signed.fetch_add(1, Ordering::SeqCst);
            Ok(self.key.sign_raw(&request.final_signing_bytes()))
        }
    }

    #[tokio::test]
    async fn cancelled_before_decision_does_not_run() {
        let issuer = SigningKey::generate();
        let holder = SigningKey::generate();
        let presented = PresentedAsyncAuthority::new(
            vec![mint(&issuer, &holder)],
            Arc::new(LocalSigner::new(holder)),
        )
        .unwrap();
        let guard = guard_for(&issuer);
        let args = HashMap::new();
        let call = Call::borrowed("read", &args);
        let control = AttemptControl::new();
        control.cancel();
        let runs = AtomicUsize::new(0);
        let err = guard
            .guard_async(&presented, &call, &control, |_| {
                runs.fetch_add(1, Ordering::SeqCst);
                Ok::<_, &str>(())
            })
            .await
            .err()
            .unwrap();
        assert_eq!(runs.load(Ordering::SeqCst), 0);
        match err {
            GuardError::Denied(denial) => {
                assert_eq!(denial.sdk_kind(), Some(SdkDenialKind::Cancelled));
            }
            GuardError::Operation(_) => panic!("operation must not run"),
        }
    }

    #[tokio::test]
    async fn oversized_deadline_is_rejected() {
        let issuer = SigningKey::generate();
        let holder = SigningKey::generate();
        let presented = PresentedAsyncAuthority::new(
            vec![mint(&issuer, &holder)],
            Arc::new(LocalSigner::new(holder)),
        )
        .unwrap();
        let guard = guard_for(&issuer);
        let args = HashMap::new();
        let call = Call::borrowed("read", &args);
        let control = AttemptControl::with_deadline(Utc::now() + chrono::Duration::hours(2));
        let err = guard
            .check_async(&presented, &call, &control)
            .await
            .err()
            .unwrap();
        assert_eq!(err.sdk_kind(), Some(SdkDenialKind::DeadlineExceeded));
        assert!(err.message().contains("PoP"));
    }

    #[tokio::test]
    async fn allow_async_runs_once() {
        let issuer = SigningKey::generate();
        let holder = SigningKey::generate();
        let presented = PresentedAsyncAuthority::new(
            vec![mint(&issuer, &holder)],
            Arc::new(LocalSigner::new(holder)),
        )
        .unwrap();
        let guard = guard_for(&issuer);
        let args = HashMap::new();
        let call = Call::borrowed("read", &args);
        let control = AttemptControl::new();
        let runs = AtomicUsize::new(0);
        let guarded = guard
            .guard_async(&presented, &call, &control, |_| {
                runs.fetch_add(1, Ordering::SeqCst);
                Ok::<_, &str>(3)
            })
            .await
            .unwrap();
        assert_eq!(guarded.value, 3);
        assert_eq!(runs.load(Ordering::SeqCst), 1);
    }

    #[tokio::test]
    async fn async_signer_is_the_one_that_signs() {
        let issuer = SigningKey::generate();
        let holder = SigningKey::generate();
        let remote = Arc::new(Remote {
            key: holder.clone(),
            signed: AtomicUsize::new(0),
        });
        let presented =
            PresentedAsyncAuthority::new(vec![mint(&issuer, &holder)], remote.clone()).unwrap();
        let guard = guard_for(&issuer);
        let args = HashMap::new();
        let call = Call::borrowed("read", &args);
        guard
            .check_async(&presented, &call, &AttemptControl::new())
            .await
            .unwrap();
        assert_eq!(remote.signed.load(Ordering::SeqCst), 1);
    }

    struct FetchOnce {
        update: RevocationUpdate,
        fetches: AtomicUsize,
    }

    #[async_trait]
    impl AsyncRevocationProvider for FetchOnce {
        async fn fetch(&self, _: &AttemptControl) -> Result<RevocationUpdate, RevocationError> {
            self.fetches.fetch_add(1, Ordering::SeqCst);
            Ok(self.update.clone())
        }
    }

    #[tokio::test]
    async fn stale_tracker_refreshes_through_async_provider() {
        let issuer = SigningKey::generate();
        let holder = SigningKey::generate();
        let warrant = mint(&issuer, &holder);
        let srl = SignedRevocationList::builder()
            .version(1)
            .build(&issuer)
            .unwrap();
        let tracker = Arc::new(
            RevocationTracker::with_in_memory_floors(
                vec![issuer.public_key()],
                Duration::from_secs(60),
                Duration::from_secs(5),
            )
            .unwrap(),
        );
        let provider = Arc::new(FetchOnce {
            update: RevocationUpdate {
                srl,
                fetched_at: Utc::now(),
            },
            fetches: AtomicUsize::new(0),
        });
        let mut authorizer = Authorizer::new();
        authorizer.add_trusted_root(issuer.public_key());
        let guard = Guard::builder()
            .authorizer(authorizer)
            .revocation(RevocationMode::SignedSrl)
            .revocation_tracker(tracker)
            .async_revocation_provider(provider.clone())
            .build()
            .unwrap();
        let presented =
            PresentedAsyncAuthority::new(vec![warrant], Arc::new(LocalSigner::new(holder)))
                .unwrap();
        let args = HashMap::new();
        let call = Call::borrowed("read", &args);
        guard
            .check_async(&presented, &call, &AttemptControl::new())
            .await
            .expect("refresh then allow");
        assert_eq!(provider.fetches.load(Ordering::SeqCst), 1);
    }
}