tenuo 0.3.3

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
//! Authorization receipts: signer, sink, and evidence policy.

use crate::crypto::{PublicKey, Signature, SigningKey};
use crate::receipt::{Receipt, RECEIPT_VERSION};
use crate::SIGNATURE_CONTEXT;
use std::fmt;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Mutex;

const DEFAULT_RECEIPT_CAPACITY: usize = 10_000;

/// How receipt persistence interacts with the authorization outcome.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum EvidencePolicy {
    #[default]
    /// Produce no receipts.
    Disabled,
    /// Produce receipts; a persistence failure is observable but does not change the outcome.
    BestEffort,
    /// Require durable evidence before the operation runs. Persistence failure denies.
    RequiredBeforeExecution,
}

/// Raw signature over a receipt's complete final signing bytes.
pub trait ReceiptSigner: Send + Sync {
    /// Public key receipts are signed under.
    fn public_key(&self) -> PublicKey;
    /// Sign a receipt over the request's exact bytes.
    fn sign_receipt(
        &self,
        request: &ReceiptSigningRequest<'_>,
    ) -> Result<Signature, ReceiptSignerError>;
}

/// Local non-blocking persistence. Remote durable sinks belong on the async surface.
pub trait ReceiptSink: Send + Sync {
    /// Store a receipt and return a reference to it.
    fn persist(&self, receipt: &Receipt) -> Result<ReceiptRef, ReceiptSinkError>;
}

/// `SIGNATURE_CONTEXT || RECEIPT_CONTEXT || version || payload`.
pub struct ReceiptSigningRequest<'a> {
    preimage: &'a [u8],
}

impl<'a> ReceiptSigningRequest<'a> {
    pub(crate) fn new(preimage: &'a [u8]) -> Self {
        Self { preimage }
    }

    /// Constant `"receipt"`. Lets one signer route by purpose.
    pub fn purpose(&self) -> &'static str {
        "receipt"
    }

    /// The exact message to sign, verbatim, with raw Ed25519.
    pub fn final_signing_bytes(&self) -> Vec<u8> {
        let mut out = Vec::with_capacity(SIGNATURE_CONTEXT.len() + self.preimage.len());
        out.extend_from_slice(SIGNATURE_CONTEXT);
        out.extend_from_slice(self.preimage);
        out
    }
}

/// In-process receipt key. `for_development` is not a production default.
pub struct LocalReceiptSigner {
    key: SigningKey,
}

impl LocalReceiptSigner {
    /// Sign receipts with an in-process key.
    pub fn new(key: SigningKey) -> Self {
        Self { key }
    }

    /// Per-process generated signer. Unattributed; not the production default.
    pub fn for_development() -> Self {
        Self {
            key: SigningKey::generate(),
        }
    }
}

impl ReceiptSigner for LocalReceiptSigner {
    fn public_key(&self) -> PublicKey {
        self.key.public_key()
    }

    fn sign_receipt(
        &self,
        request: &ReceiptSigningRequest<'_>,
    ) -> Result<Signature, ReceiptSignerError> {
        Ok(self.key.sign_raw(&request.final_signing_bytes()))
    }
}

/// In-memory sink for tests and local RequiredBeforeExecution.
pub struct MemoryReceiptSink {
    stored: Mutex<SinkBuf>,
    max: usize,
    deny_max: usize,
    overflowed: AtomicUsize,
}

struct SinkBuf {
    items: Vec<StoredReceipt>,
    allows: usize,
    denies: usize,
}

struct StoredReceipt {
    receipt: Receipt,
    deny: bool,
}

impl Default for MemoryReceiptSink {
    fn default() -> Self {
        Self::with_capacity(DEFAULT_RECEIPT_CAPACITY)
    }
}

impl MemoryReceiptSink {
    /// An empty in-memory sink. For tests.
    pub fn new() -> Self {
        Self::default()
    }

    /// Bound outbox. `max` is the cap for allow receipts and, separately,
    /// for deny receipts, so the buffer can hold up to `2 * max` items.
    /// A full side drops the new receipt, counts it, and returns
    /// [`ReceiptSinkError::Unavailable`]. Best-effort evidence swallows
    /// that error; RequiredBeforeExecution denies. A payload whose outcome
    /// cannot be read is rejected without consuming either budget.
    pub fn with_capacity(max: usize) -> Self {
        Self {
            stored: Mutex::new(SinkBuf {
                items: Vec::new(),
                allows: 0,
                denies: 0,
            }),
            max: max.max(1),
            deny_max: max.max(1),
            overflowed: AtomicUsize::new(0),
        }
    }

    /// Receipts dropped because the outbox was full.
    pub fn overflowed(&self) -> usize {
        self.overflowed.load(Ordering::Relaxed)
    }

    /// Everything stored so far.
    pub fn stored(&self) -> Vec<Receipt> {
        self.stored
            .lock()
            .map(|g| g.items.iter().map(|item| item.receipt.clone()).collect())
            .unwrap_or_default()
    }

    /// Unacknowledged receipts. Same as [`Self::stored`] after prefix drops.
    pub fn pending(&self) -> Vec<Receipt> {
        self.stored()
    }

    /// Receipts at and after `cursor` without removing them.
    pub fn peek_from(&self, cursor: usize) -> Vec<Receipt> {
        let stored = self.stored();
        if cursor >= stored.len() {
            return Vec::new();
        }
        stored[cursor..].to_vec()
    }

    /// Remove the first `count` stored receipts.
    pub fn drop_prefix(&self, count: usize) -> usize {
        let Ok(mut stored) = self.stored.lock() else {
            return 0;
        };
        let n = count.min(stored.items.len());
        let removed: Vec<bool> = stored.items.drain(..n).map(|item| item.deny).collect();
        for deny in removed {
            if deny {
                stored.denies = stored.denies.saturating_sub(1);
            } else {
                stored.allows = stored.allows.saturating_sub(1);
            }
        }
        n
    }
}

fn receipt_is_deny(receipt: &Receipt) -> Option<bool> {
    ciborium::from_reader::<crate::receipt::ReceiptPayload, _>(receipt.payload.as_slice())
        .ok()
        .map(|payload| payload.outcome == crate::receipt::Outcome::Deny)
}

impl ReceiptSink for MemoryReceiptSink {
    fn persist(&self, receipt: &Receipt) -> Result<ReceiptRef, ReceiptSinkError> {
        let deny = receipt_is_deny(receipt).ok_or(ReceiptSinkError::Unavailable)?;
        let mut stored = self
            .stored
            .lock()
            .map_err(|_| ReceiptSinkError::Unavailable)?;
        let (used, cap) = if deny {
            (stored.denies, self.deny_max)
        } else {
            (stored.allows, self.max)
        };
        if used >= cap {
            self.overflowed.fetch_add(1, Ordering::Relaxed);
            return Err(ReceiptSinkError::Unavailable);
        }
        stored.items.push(StoredReceipt {
            receipt: receipt.clone(),
            deny,
        });
        if deny {
            stored.denies += 1;
        } else {
            stored.allows += 1;
        }
        Ok(ReceiptRef {
            id: format!("mem:{}", stored.items.len()),
        })
    }
}

/// Handle returned by a sink. Not a capability.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ReceiptRef {
    /// Identifier the sink assigned to the stored receipt.
    pub id: String,
}

#[derive(Debug, Clone, PartialEq, Eq)]
/// Why a receipt could not be signed.
#[non_exhaustive]
pub enum ReceiptSignerError {
    /// The receipt signer could not be reached.
    Unavailable,
}

impl fmt::Display for ReceiptSignerError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Unavailable => write!(f, "receipt signer unavailable"),
        }
    }
}

impl std::error::Error for ReceiptSignerError {}

#[derive(Debug, Clone, PartialEq, Eq)]
/// Why a receipt could not be stored.
#[non_exhaustive]
pub enum ReceiptSinkError {
    /// The sink could not be reached.
    Unavailable,
}

impl fmt::Display for ReceiptSinkError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Unavailable => write!(f, "receipt sink unavailable"),
        }
    }
}

impl std::error::Error for ReceiptSinkError {}

pub(crate) fn sign_payload(
    payload_bytes: &[u8],
    signer: &dyn ReceiptSigner,
) -> Result<Receipt, ReceiptSignerError> {
    let preimage = Receipt::signing_preimage(RECEIPT_VERSION, payload_bytes);
    let request = ReceiptSigningRequest::new(&preimage);
    let signature = signer.sign_receipt(&request)?;
    Ok(Receipt {
        receipt_version: RECEIPT_VERSION,
        payload: payload_bytes.to_vec(),
        signer_key: signer.public_key(),
        signature,
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::crypto::SigningKey;
    use crate::receipt::{Receipt, ReceiptPayload};

    #[test]
    fn local_signer_verifies_against_core() {
        let signer = LocalReceiptSigner::for_development();
        let payload = ReceiptPayload::allow(
            vec![0xA1, 0x01, 0x02],
            "tool:read",
            1_700_000_000,
            "inv-1",
            [3u8; 64],
        );
        let bytes = payload.to_cbor().unwrap();
        let receipt = sign_payload(&bytes, &signer).unwrap();
        let verified = receipt.verify_signature().unwrap();
        assert_eq!(verified.action, "tool:read");
        assert_eq!(verified.request_id, "inv-1");
    }

    #[test]
    fn memory_sink_round_trips() {
        let sink = MemoryReceiptSink::new();
        let signer = LocalReceiptSigner::for_development();
        let payload = ReceiptPayload::allow(vec![0xA0], "tool:read", 1, "inv-2", [1u8; 64]);
        let receipt = sign_payload(&payload.to_cbor().unwrap(), &signer).unwrap();
        let reference = sink.persist(&receipt).unwrap();
        assert!(reference.id.starts_with("mem:"));
        assert_eq!(sink.stored().len(), 1);
        assert_eq!(sink.peek_from(0).len(), 1);
        assert_eq!(sink.peek_from(0).len(), 1);
        assert_eq!(sink.drop_prefix(1), 1);
        assert!(sink.pending().is_empty());
    }

    #[test]
    fn memory_sink_overflow_is_counted_and_unavailable() {
        let sink = MemoryReceiptSink::with_capacity(1);
        let signer = LocalReceiptSigner::for_development();
        let payload = ReceiptPayload::allow(vec![0xA0], "tool:read", 1, "inv-2", [1u8; 64]);
        let receipt = sign_payload(&payload.to_cbor().unwrap(), &signer).unwrap();
        assert!(sink.persist(&receipt).is_ok());
        assert_eq!(sink.persist(&receipt), Err(ReceiptSinkError::Unavailable));
        assert_eq!(sink.stored().len(), 1);
        assert_eq!(sink.overflowed(), 1);
    }

    #[test]
    fn deny_receipts_do_not_consume_allow_budget() {
        let sink = MemoryReceiptSink::with_capacity(1);
        let signer = LocalReceiptSigner::for_development();
        let deny = sign_payload(
            &ReceiptPayload::deny_before_pop(vec![0xA0], "tool:read", 1, "deny-1", "denied")
                .to_cbor()
                .unwrap(),
            &signer,
        )
        .unwrap();
        let allow = sign_payload(
            &ReceiptPayload::allow(vec![0xA0], "tool:read", 1, "inv-2", [1u8; 64])
                .to_cbor()
                .unwrap(),
            &signer,
        )
        .unwrap();
        assert!(sink.persist(&deny).is_ok());
        assert_eq!(sink.persist(&deny), Err(ReceiptSinkError::Unavailable));
        assert!(sink.persist(&allow).is_ok());
        assert_eq!(sink.stored().len(), 2);
        assert_eq!(sink.overflowed(), 1);
    }

    #[test]
    fn undecodable_payload_does_not_consume_allow_budget() {
        let sink = MemoryReceiptSink::with_capacity(1);
        let signer = LocalReceiptSigner::for_development();
        let mut garbage = sign_payload(
            &ReceiptPayload::allow(vec![0xA0], "tool:read", 1, "inv-2", [1u8; 64])
                .to_cbor()
                .unwrap(),
            &signer,
        )
        .unwrap();
        garbage.payload = vec![0xff, 0x00];
        assert_eq!(sink.persist(&garbage), Err(ReceiptSinkError::Unavailable));
        let allow = sign_payload(
            &ReceiptPayload::allow(vec![0xA0], "tool:read", 1, "inv-2", [1u8; 64])
                .to_cbor()
                .unwrap(),
            &signer,
        )
        .unwrap();
        assert!(sink.persist(&allow).is_ok());
        assert_eq!(sink.stored().len(), 1);
    }

    #[test]
    fn required_persist_failure_denies_without_running() {
        use crate::constraints::ConstraintSet;
        use crate::planes::Authorizer;
        use crate::sdk::signer::LocalSigner;
        use crate::sdk::{Call, Guard, PresentedAuthority, RevocationMode};
        use crate::warrant::Warrant;
        use std::collections::HashMap;
        use std::sync::atomic::{AtomicUsize, Ordering};
        use std::sync::Arc;
        use std::time::Duration;

        struct FailSink;
        impl ReceiptSink for FailSink {
            fn persist(&self, _: &Receipt) -> Result<ReceiptRef, ReceiptSinkError> {
                Err(ReceiptSinkError::Unavailable)
            }
        }

        let issuer = SigningKey::generate();
        let holder = SigningKey::generate();
        let warrant = Warrant::builder()
            .capability("read", ConstraintSet::new())
            .holder(holder.public_key())
            .ttl(Duration::from_secs(300))
            .build(&issuer)
            .unwrap();
        let mut authorizer = Authorizer::new();
        authorizer.add_trusted_root(issuer.public_key());
        let guard = Guard::builder()
            .authorizer(authorizer)
            .revocation(RevocationMode::TtlOnly {
                max_lifetime: Duration::from_secs(3600),
            })
            .evidence_policy(EvidencePolicy::RequiredBeforeExecution)
            .receipt_signer(Arc::new(LocalReceiptSigner::for_development()))
            .receipt_sink(Arc::new(FailSink))
            .build()
            .unwrap();
        let authority =
            PresentedAuthority::new(vec![warrant], Arc::new(LocalSigner::new(holder))).unwrap();
        let args = HashMap::new();
        let call = Call::borrowed("read", &args);
        let runs = AtomicUsize::new(0);
        let err = guard
            .guard(&authority, &call, |_| {
                runs.fetch_add(1, Ordering::SeqCst);
                Ok::<_, &str>(())
            })
            .err()
            .unwrap();
        assert_eq!(runs.load(Ordering::SeqCst), 0);
        match err {
            crate::sdk::GuardError::Denied(denial) => {
                assert_eq!(
                    denial.sdk_kind(),
                    Some(crate::sdk::SdkDenialKind::EvidenceUnavailable)
                );
            }
            crate::sdk::GuardError::Operation(_) => panic!("operation must not run"),
        }
    }

    #[test]
    fn best_effort_persist_failure_still_allows() {
        use crate::constraints::ConstraintSet;
        use crate::planes::Authorizer;
        use crate::sdk::signer::LocalSigner;
        use crate::sdk::{Call, Guard, PresentedAuthority, RevocationMode};
        use crate::warrant::Warrant;
        use std::collections::HashMap;
        use std::sync::Arc;
        use std::time::Duration;

        struct FailSink;
        impl ReceiptSink for FailSink {
            fn persist(&self, _: &Receipt) -> Result<ReceiptRef, ReceiptSinkError> {
                Err(ReceiptSinkError::Unavailable)
            }
        }

        let issuer = SigningKey::generate();
        let holder = SigningKey::generate();
        let warrant = Warrant::builder()
            .capability("read", ConstraintSet::new())
            .holder(holder.public_key())
            .ttl(Duration::from_secs(300))
            .build(&issuer)
            .unwrap();
        let mut authorizer = Authorizer::new();
        authorizer.add_trusted_root(issuer.public_key());
        let guard = Guard::builder()
            .authorizer(authorizer)
            .revocation(RevocationMode::TtlOnly {
                max_lifetime: Duration::from_secs(3600),
            })
            .evidence_policy(EvidencePolicy::BestEffort)
            .receipt_signer(Arc::new(LocalReceiptSigner::for_development()))
            .receipt_sink(Arc::new(FailSink))
            .build()
            .unwrap();
        let authority =
            PresentedAuthority::new(vec![warrant], Arc::new(LocalSigner::new(holder))).unwrap();
        let args = HashMap::new();
        let call = Call::borrowed("read", &args);
        let decision = guard.check(&authority, &call).expect("allow");
        assert!(decision.receipt.is_some());
        decision.receipt.unwrap().verify_signature().unwrap();
    }

    #[test]
    fn observer_does_not_emit_receipts() {
        use crate::constraints::ConstraintSet;
        use crate::planes::Authorizer;
        use crate::sdk::signer::LocalSigner;
        use crate::sdk::{Call, Guard, PresentedAuthority, PresentedRequest, RevocationMode};
        use crate::warrant::Warrant;
        use chrono::Utc;
        use std::collections::HashMap;
        use std::sync::Arc;
        use std::time::Duration;

        let issuer = SigningKey::generate();
        let holder = SigningKey::generate();
        let warrant = Warrant::builder()
            .capability("read", ConstraintSet::new())
            .holder(holder.public_key())
            .ttl(Duration::from_secs(300))
            .build(&issuer)
            .unwrap();
        let mut authorizer = Authorizer::new();
        authorizer.add_trusted_root(issuer.public_key());
        let sink = Arc::new(MemoryReceiptSink::new());
        let guard = Guard::builder()
            .authorizer(authorizer)
            .revocation(RevocationMode::TtlOnly {
                max_lifetime: Duration::from_secs(3600),
            })
            .evidence_policy(EvidencePolicy::BestEffort)
            .receipt_signer(Arc::new(LocalReceiptSigner::for_development()))
            .receipt_sink(sink.clone())
            .build()
            .unwrap();
        let authority =
            PresentedAuthority::new(vec![warrant], Arc::new(LocalSigner::new(holder))).unwrap();
        let args = HashMap::new();
        let call = Call::borrowed("read", &args);
        assert!(guard.check(&authority, &call).unwrap().receipt.is_some());
        assert_eq!(sink.stored().len(), 1);
        guard
            .observe_until(Utc::now() + chrono::Duration::hours(1))
            .observe(PresentedRequest::Holder(&authority), &call, || {
                Ok::<_, &str>(())
            })
            .unwrap();
        assert_eq!(sink.stored().len(), 1);
    }
}