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
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
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
//! Observe-only assessment. Distinct from [`Guard`]; never an enforcement type.

use super::authority::{AuthorityError, PresentedAuthority, ReceivedAuthorization};
use super::call::Call;
use super::decision::{Denial, Retryability, SdkDenialKind};
use super::guard::Guard;
use crate::approval::ApprovalRequest;
use crate::constraints::ConstraintValue;
use chrono::{DateTime, Utc};
use sha2::{Digest, Sha256};
use std::collections::BTreeMap;
use std::fmt;

/// Assessment surface copied from a [`Guard`]. Cannot be used where `Guard` is required.
pub struct ObservingGuard {
    guard: Guard,
    expires_at: DateTime<Utc>,
    argument_shape: ArgumentShapePolicy,
}

impl Guard {
    /// Copies this guard's configuration. There is no reverse conversion.
    pub fn observe_until(&self, expires_at: DateTime<Utc>) -> ObservingGuard {
        ObservingGuard {
            guard: self.snapshot_for_observe(),
            expires_at,
            argument_shape: ArgumentShapePolicy::KeysAndClasses,
        }
    }
}

impl ObservingGuard {
    /// Start configuring an observer. An expiry is required.
    pub fn builder() -> ObservingGuardBuilder {
        ObservingGuardBuilder::default()
    }

    /// When this assessment window closes.
    pub fn expires_at(&self) -> DateTime<Utc> {
        self.expires_at
    }

    /// How argument information is summarized on each record. Default is
    /// keys and value classes — enough to draft constraints, not raw values.
    pub fn argument_shape_policy(mut self, policy: ArgumentShapePolicy) -> Self {
        self.argument_shape = policy;
        self
    }

    /// Run the full decision, record what it would have been, and run `op` regardless.
    ///
    /// This is assessment, not enforcement: the operation runs on a would-deny. After
    /// [`Self::expires_at`] it refuses to run at all, so a window cannot silently become
    /// a permanent bypass.
    pub fn observe<T, E>(
        &self,
        request: PresentedRequest<'_>,
        call: &Call<'_>,
        op: impl FnOnce() -> Result<T, E>,
    ) -> Result<Observed<T>, ObserveError<E>> {
        if self.guard.now() >= self.expires_at {
            return Err(ObserveError::Expired);
        }

        let outcome = match request {
            PresentedRequest::Holder(authority) => classify(self.guard.check(authority, call)),
            PresentedRequest::Received(received) => {
                classify(self.guard.check_received(received, call))
            }
            PresentedRequest::Missing => ObservedOutcome::WouldDenyNoAuthority,
            PresentedRequest::Malformed(err) => ObservedOutcome::WouldDeny(Denial::sdk(
                SdkDenialKind::AuthorityMalformed,
                Retryability::No,
                match err {
                    AuthorityError::EmptyChain => "authority chain is empty",
                    AuthorityError::SignerMismatch => "signer does not match leaf holder",
                    AuthorityError::MissingSignature => {
                        "received authorization is missing a signature"
                    }
                },
            )),
        };
        #[cfg(feature = "otel")]
        {
            let (otel_outcome, reason) = match &outcome {
                ObservedOutcome::WouldAllow => ("allow", "allowed"),
                ObservedOutcome::WouldDeny(denial) => ("deny", denial.code()),
                ObservedOutcome::WouldRequireApproval(_) => ("deny", "approval-required"),
                ObservedOutcome::WouldDenyNoAuthority => ("deny", "authority-missing"),
            };
            super::telemetry::record_authorize(otel_outcome, reason, true);
        }

        let value = op().map_err(ObserveError::Operation)?;
        let verdict = ObservationVerdict::from(&outcome);
        Ok(Observed {
            value,
            outcome,
            observation: ObservationRecord {
                observe_only: true,
                expires_at: self.expires_at,
                capability: call.capability().to_string(),
                verdict,
                argument_shape: summarize_args(call.constraint_args(), self.argument_shape),
            },
        })
    }
}

fn classify(result: Result<super::decision::Decision, Denial>) -> ObservedOutcome {
    match result {
        Ok(decision) => {
            let _ = decision.receipt;
            ObservedOutcome::WouldAllow
        }
        Err(denial) => {
            if let Some(request) = denial.approval_request().cloned() {
                ObservedOutcome::WouldRequireApproval(request)
            } else {
                ObservedOutcome::WouldDeny(denial)
            }
        }
    }
}

/// Construction from a [`Guard`] plus an explicit expiry. No independent policy.
#[derive(Default)]
pub struct ObservingGuardBuilder {
    guard: Option<Guard>,
    expires_at: Option<DateTime<Utc>>,
    argument_shape: ArgumentShapePolicy,
}

impl ObservingGuardBuilder {
    /// Observe using an existing guard's policy. Evidence is disabled on the copy.
    pub fn from_guard(guard: &Guard) -> Self {
        Self {
            guard: Some(guard.snapshot_for_observe()),
            expires_at: None,
            argument_shape: ArgumentShapePolicy::KeysAndClasses,
        }
    }

    /// How much argument information each record carries. Defaults to keys and value
    /// classes — enough to draft constraints, never raw values.
    pub fn argument_shape_policy(mut self, policy: ArgumentShapePolicy) -> Self {
        self.argument_shape = policy;
        self
    }

    /// When the assessment window closes. Required.
    pub fn expires_at(mut self, when: DateTime<Utc>) -> Self {
        self.expires_at = Some(when);
        self
    }

    /// Build the observer, or fail if the guard or expiry is missing.
    pub fn build(self) -> Result<ObservingGuard, ObserveBuildError> {
        let guard = self.guard.ok_or(ObserveBuildError::MissingGuard)?;
        let expires_at = self.expires_at.ok_or(ObserveBuildError::MissingExpiry)?;
        Ok(ObservingGuard {
            guard,
            expires_at,
            argument_shape: self.argument_shape,
        })
    }
}

/// What the caller actually presented — including nothing at all.
#[non_exhaustive]
pub enum PresentedRequest<'a> {
    /// A holder-side authority.
    Holder(&'a PresentedAuthority),
    /// Authorization received from a peer.
    Received(&'a ReceivedAuthorization<'a>),
    /// Authority was presented but failed structural validation.
    Malformed(AuthorityError),
    /// No authority was presented at all — the case an assessment most needs to see.
    Missing,
}

/// Result of an observation. The operation ran regardless of the would-outcome.
pub struct Observed<T> {
    /// What the operation returned. It ran regardless of the verdict.
    pub value: T,
    /// What an enforcing guard would have decided, with full detail.
    pub outcome: ObservedOutcome,
    /// Persistable summary of the same decision.
    pub observation: ObservationRecord,
}

/// What enforcement would have decided. Never an allow token.
#[non_exhaustive]
pub enum ObservedOutcome {
    /// The call would have been allowed.
    WouldAllow,
    /// The call would have been denied.
    WouldDeny(Denial),
    /// The call would have required approval, with the core's request descriptor.
    WouldRequireApproval(ApprovalRequest),
    /// No authority was presented.
    WouldDenyNoAuthority,
}

/// Persistable would-outcome. The full [`ObservedOutcome`] stays on [`Observed`].
#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum ObservationVerdict {
    /// The call would have been allowed.
    WouldAllow,
    /// The call would have been denied.
    WouldDeny,
    /// The call would have required approval.
    WouldRequireApproval,
    /// No authority was presented.
    WouldDenyNoAuthority,
}

impl From<&ObservedOutcome> for ObservationVerdict {
    fn from(outcome: &ObservedOutcome) -> Self {
        match outcome {
            ObservedOutcome::WouldAllow => Self::WouldAllow,
            ObservedOutcome::WouldDeny(_) => Self::WouldDeny,
            ObservedOutcome::WouldRequireApproval(_) => Self::WouldRequireApproval,
            ObservedOutcome::WouldDenyNoAuthority => Self::WouldDenyNoAuthority,
        }
    }
}

/// How much argument information an observation record may carry.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum ArgumentShapePolicy {
    /// Key names only.
    KeysOnly,
    /// Key names and value classes. Default — enough to draft constraints.
    #[default]
    KeysAndClasses,
    /// Key names, value classes, and SHA-256 of each value. Never raw values.
    KeysClassesAndHashes,
}

/// Privacy-safe argument summary for an assessment window.
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct ArgumentShape {
    keys: Vec<String>,
    classes: BTreeMap<String, ValueClass>,
    hashes: BTreeMap<String, String>,
}

impl ArgumentShape {
    /// Argument names seen, sorted.
    pub fn keys(&self) -> &[String] {
        &self.keys
    }

    /// Value class per argument. Empty under [`ArgumentShapePolicy::KeysOnly`].
    pub fn classes(&self) -> &BTreeMap<String, ValueClass> {
        &self.classes
    }

    /// SHA-256 per argument value. Empty unless the policy is
    /// [`ArgumentShapePolicy::KeysClassesAndHashes`].
    pub fn hashes(&self) -> &BTreeMap<String, String> {
        &self.hashes
    }
}

/// Coarse class of a constraint value. Not the value.
#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum ValueClass {
    /// A string value.
    String,
    /// An integer value.
    Integer,
    /// A floating-point value.
    Float,
    /// A boolean value.
    Boolean,
    /// A list value.
    List,
    /// An object value.
    Object,
    /// A null value.
    Null,
}

/// Labeled observe-only record. Not an authorization receipt.
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct ObservationRecord {
    observe_only: bool,
    expires_at: DateTime<Utc>,
    capability: String,
    verdict: ObservationVerdict,
    argument_shape: ArgumentShape,
}

impl ObservationRecord {
    /// Always true. Present so a persisted record is never mistaken for enforcement.
    pub fn is_observe_only(&self) -> bool {
        self.observe_only
    }

    /// When the assessment window closes.
    pub fn expires_at(&self) -> DateTime<Utc> {
        self.expires_at
    }

    /// Capability that was called.
    pub fn capability(&self) -> &str {
        &self.capability
    }

    /// What an enforcing guard would have decided.
    pub fn verdict(&self) -> ObservationVerdict {
        self.verdict
    }

    /// Argument summary, at the configured policy level.
    pub fn argument_shape(&self) -> &ArgumentShape {
        &self.argument_shape
    }

    /// The argument-shape policy this record was captured under.
    pub fn policy_mode(&self) -> &'static str {
        "observe"
    }
}

fn summarize_args(
    args: &std::collections::HashMap<String, ConstraintValue>,
    policy: ArgumentShapePolicy,
) -> ArgumentShape {
    let mut keys: Vec<String> = args.keys().cloned().collect();
    keys.sort();
    let mut classes = BTreeMap::new();
    let mut hashes = BTreeMap::new();
    if matches!(
        policy,
        ArgumentShapePolicy::KeysAndClasses | ArgumentShapePolicy::KeysClassesAndHashes
    ) {
        for (key, value) in args {
            classes.insert(key.clone(), value_class(value));
        }
    }
    if policy == ArgumentShapePolicy::KeysClassesAndHashes {
        for (key, value) in args {
            hashes.insert(key.clone(), hash_value(value));
        }
    }
    ArgumentShape {
        keys,
        classes,
        hashes,
    }
}

fn value_class(value: &ConstraintValue) -> ValueClass {
    match value {
        ConstraintValue::String(_) => ValueClass::String,
        ConstraintValue::Integer(_) => ValueClass::Integer,
        ConstraintValue::Float(_) => ValueClass::Float,
        ConstraintValue::Boolean(_) => ValueClass::Boolean,
        ConstraintValue::List(_) => ValueClass::List,
        ConstraintValue::Object(_) => ValueClass::Object,
        ConstraintValue::Null => ValueClass::Null,
    }
}

fn hash_value(value: &ConstraintValue) -> String {
    let mut hasher = Sha256::new();
    hash_into(&mut hasher, value);
    hex::encode(hasher.finalize())
}

fn hash_into(hasher: &mut Sha256, value: &ConstraintValue) {
    match value {
        ConstraintValue::String(s) => {
            hasher.update([1]);
            hasher.update(s.as_bytes());
        }
        ConstraintValue::Integer(i) => {
            hasher.update([2]);
            hasher.update(i.to_be_bytes());
        }
        ConstraintValue::Float(f) => {
            hasher.update([3]);
            hasher.update(f.to_bits().to_be_bytes());
        }
        ConstraintValue::Boolean(b) => {
            hasher.update([4]);
            hasher.update([u8::from(*b)]);
        }
        ConstraintValue::List(items) => {
            hasher.update([5]);
            hasher.update((items.len() as u32).to_be_bytes());
            for item in items {
                hash_into(hasher, item);
            }
        }
        ConstraintValue::Object(map) => {
            hasher.update([6]);
            hasher.update((map.len() as u32).to_be_bytes());
            for (key, item) in map {
                hasher.update(key.as_bytes());
                hasher.update([0]);
                hash_into(hasher, item);
            }
        }
        ConstraintValue::Null => hasher.update([7]),
    }
}

/// Failure while observing an already-built [`ObservingGuard`].
#[derive(Debug)]
#[non_exhaustive]
pub enum ObserveError<E> {
    /// The assessment window has closed. The operation did not run.
    Expired,
    /// The operation itself returned an error.
    Operation(E),
}

impl<E: fmt::Display> fmt::Display for ObserveError<E> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Expired => write!(f, "observation period has expired"),
            Self::Operation(err) => write!(f, "operation failed: {err}"),
        }
    }
}

impl<E: fmt::Debug + fmt::Display> std::error::Error for ObserveError<E> {}

/// Failure constructing an [`ObservingGuard`].
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum ObserveBuildError {
    /// No guard was supplied.
    MissingGuard,
    /// No expiry was supplied. An observer cannot be unbounded.
    MissingExpiry,
}

impl fmt::Display for ObserveBuildError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::MissingGuard => write!(
                f,
                "ObservingGuard requires configuration copied from a Guard"
            ),
            Self::MissingExpiry => write!(f, "ObservingGuard requires an explicit expiry"),
        }
    }
}

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

#[cfg(test)]
mod tests {
    use super::*;
    use crate::constraints::ConstraintSet;
    use crate::crypto::SigningKey;
    use crate::planes::Authorizer;
    use crate::sdk::signer::LocalSigner;
    use crate::sdk::{Call, 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, tool: &str) -> Warrant {
        Warrant::builder()
            .capability(tool, ConstraintSet::new())
            .holder(holder.public_key())
            .ttl(Duration::from_secs(300))
            .build(issuer)
            .expect("mint")
    }

    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()
            .expect("guard")
    }

    fn authority(chain: Vec<Warrant>, holder: SigningKey) -> PresentedAuthority {
        PresentedAuthority::new(chain, Arc::new(LocalSigner::new(holder))).expect("authority")
    }

    fn live(guard: &Guard) -> ObservingGuard {
        guard.observe_until(Utc::now() + chrono::Duration::hours(1))
    }

    #[test]
    fn missing_authority_is_a_finding_and_still_runs() {
        let issuer = SigningKey::generate();
        let observer = live(&guard_for(&issuer));
        let args = HashMap::new();
        let call = Call::borrowed("read", &args);
        let runs = AtomicUsize::new(0);
        let observed = observer
            .observe(PresentedRequest::Missing, &call, || {
                runs.fetch_add(1, Ordering::SeqCst);
                Ok::<_, &str>(())
            })
            .expect("observe");
        assert_eq!(runs.load(Ordering::SeqCst), 1);
        assert!(matches!(
            observed.outcome,
            ObservedOutcome::WouldDenyNoAuthority
        ));
        assert!(observed.observation.is_observe_only());
        assert_eq!(observed.observation.policy_mode(), "observe");
    }

    #[test]
    fn expired_observer_refuses_to_run() {
        let issuer = SigningKey::generate();
        let observer = guard_for(&issuer).observe_until(Utc::now() - chrono::Duration::seconds(1));
        let args = HashMap::new();
        let call = Call::borrowed("read", &args);
        let runs = AtomicUsize::new(0);
        let err = observer
            .observe(PresentedRequest::Missing, &call, || {
                runs.fetch_add(1, Ordering::SeqCst);
                Ok::<_, &str>(())
            })
            .err()
            .expect("expired");
        assert_eq!(runs.load(Ordering::SeqCst), 0);
        assert!(matches!(err, ObserveError::Expired));
    }

    #[test]
    fn holder_would_allow_matches_guard_and_runs() {
        let issuer = SigningKey::generate();
        let holder = SigningKey::generate();
        let presented = authority(vec![mint(&issuer, &holder, "read")], holder);
        let guard = guard_for(&issuer);
        let args = HashMap::new();
        let call = Call::borrowed("read", &args);
        assert!(guard.check(&presented, &call).is_ok());
        let runs = AtomicUsize::new(0);
        let observed = live(&guard)
            .observe(PresentedRequest::Holder(&presented), &call, || {
                runs.fetch_add(1, Ordering::SeqCst);
                Ok::<_, &str>(11)
            })
            .expect("observe");
        assert_eq!(runs.load(Ordering::SeqCst), 1);
        assert_eq!(observed.value, 11);
        assert!(matches!(observed.outcome, ObservedOutcome::WouldAllow));
        assert!(observed.observation.is_observe_only());
    }

    #[test]
    fn holder_would_deny_still_runs() {
        let issuer = SigningKey::generate();
        let holder = SigningKey::generate();
        let presented = authority(vec![mint(&issuer, &holder, "read")], holder);
        let guard = guard_for(&issuer);
        let args = HashMap::new();
        let call = Call::borrowed("write", &args);
        assert!(guard.check(&presented, &call).is_err());
        let runs = AtomicUsize::new(0);
        let observed = live(&guard)
            .observe(PresentedRequest::Holder(&presented), &call, || {
                runs.fetch_add(1, Ordering::SeqCst);
                Ok::<_, &str>(())
            })
            .expect("observe");
        assert_eq!(runs.load(Ordering::SeqCst), 1);
        assert!(matches!(observed.outcome, ObservedOutcome::WouldDeny(_)));
    }

    #[test]
    fn received_would_allow_matches_guard() {
        let issuer = SigningKey::generate();
        let holder = SigningKey::generate();
        let presented = authority(vec![mint(&issuer, &holder, "read")], holder);
        let guard = guard_for(&issuer);
        let args = HashMap::new();
        let call = Call::borrowed("read", &args);
        let decision = guard.check(&presented, &call).expect("holder allow");
        let _ = decision;
        let authorized = guard
            .guard(&presented, &call, |authorized| {
                Ok::<_, &str>(authorized.pop_signature().clone())
            })
            .expect("sign");
        let pop = authorized.value;
        let received = ReceivedAuthorization::new(presented.chain(), &pop, &[]).expect("received");
        assert!(guard.check_received(&received, &call).is_ok());
        let observed = live(&guard)
            .observe(PresentedRequest::Received(&received), &call, || {
                Ok::<_, &str>(())
            })
            .expect("observe");
        assert!(matches!(observed.outcome, ObservedOutcome::WouldAllow));
    }

    #[test]
    fn malformed_short_circuits_without_usable_authority() {
        let issuer = SigningKey::generate();
        let observer = live(&guard_for(&issuer));
        let args = HashMap::new();
        let call = Call::borrowed("read", &args);
        let observed = observer
            .observe(
                PresentedRequest::Malformed(AuthorityError::EmptyChain),
                &call,
                || Ok::<_, &str>(()),
            )
            .expect("observe");
        match observed.outcome {
            ObservedOutcome::WouldDeny(denial) => {
                assert_eq!(denial.sdk_kind(), Some(SdkDenialKind::AuthorityMalformed));
            }
            ObservedOutcome::WouldAllow
            | ObservedOutcome::WouldRequireApproval(_)
            | ObservedOutcome::WouldDenyNoAuthority => {
                panic!("expected malformed denial")
            }
        }
    }

    #[test]
    fn construction_requires_guard_and_expiry() {
        assert_eq!(
            ObservingGuard::builder().build().err().unwrap(),
            ObserveBuildError::MissingGuard
        );
        let issuer = SigningKey::generate();
        let guard = guard_for(&issuer);
        assert_eq!(
            ObservingGuardBuilder::from_guard(&guard)
                .build()
                .err()
                .unwrap(),
            ObserveBuildError::MissingExpiry
        );
        let observer = ObservingGuardBuilder::from_guard(&guard)
            .expires_at(Utc::now() + chrono::Duration::minutes(5))
            .build()
            .unwrap();
        assert!(observer.expires_at() > Utc::now());
    }

    #[test]
    fn argument_shape_summarizes_without_raw_values() {
        let issuer = SigningKey::generate();
        let holder = SigningKey::generate();
        let presented = authority(vec![mint(&issuer, &holder, "read")], holder);
        let mut args = HashMap::new();
        args.insert(
            "cluster".into(),
            crate::constraints::ConstraintValue::String("staging-web".into()),
        );
        let call = Call::borrowed("read", &args);
        let observed = live(&guard_for(&issuer))
            .observe(PresentedRequest::Holder(&presented), &call, || {
                Ok::<_, &str>(())
            })
            .unwrap();
        let shape = observed.observation.argument_shape();
        assert_eq!(shape.keys(), &["cluster".to_string()]);
        assert_eq!(shape.classes().get("cluster"), Some(&ValueClass::String));
        assert!(shape.hashes().is_empty());
        let debug = format!("{shape:?}");
        assert!(
            !debug.contains("staging-web"),
            "observe must not persist raw argument values: {debug}"
        );
        assert_eq!(
            observed.observation.verdict(),
            ObservationVerdict::WouldAllow
        );
    }

    #[test]
    fn no_receipt_and_no_reverse_conversion_in_source() {
        let src = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/src/sdk/observe.rs"));
        let deref_impl = format!("impl {}::ops::{}", "std", "Deref");
        let deref_fn = ["fn ", "deref("].concat();
        assert!(
            !src.contains(&deref_impl) && !src.contains(&deref_fn),
            "S29: ObservingGuard must not Deref to Guard"
        );
        assert!(
            !src.contains(&["fn into", "_guard"].concat()),
            "S29/S44: no reverse conversion"
        );
        let issuer = SigningKey::generate();
        let holder = SigningKey::generate();
        let presented = authority(vec![mint(&issuer, &holder, "read")], holder);
        let args = HashMap::new();
        let call = Call::borrowed("read", &args);
        let observed = live(&guard_for(&issuer))
            .observe(PresentedRequest::Holder(&presented), &call, || {
                Ok::<_, &str>(())
            })
            .unwrap();
        match observed.outcome {
            ObservedOutcome::WouldAllow => {}
            ObservedOutcome::WouldDeny(_)
            | ObservedOutcome::WouldRequireApproval(_)
            | ObservedOutcome::WouldDenyNoAuthority => {}
        }
        // Observation is not a Decision and carries no receipt field.
        let _ = observed.observation.is_observe_only();
    }
}