tenuo 0.3.2

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
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
//! Authorization receipts (v1).
//!
//! A receipt is a self-contained, signed record of one authorization decision:
//! which authority was presented, which tool was requested, what was decided,
//! and when. This module implements the artifact and its byte encoding.
//!
//! Two properties drive the shape of the code here:
//!
//! - **Self-containment.** The artifact carries the public key it was signed
//!   under, so a verifier can check the signature with no directory lookup and
//!   no live service. Whether that key was legitimately the enforcement
//!   point's is a separate, deliberately separate, question.
//! - **Verify before deserialize.** The signature covers the payload bytes
//!   exactly as received. Callers get the structured payload only after the
//!   signature checks out, so a malformed payload from an unauthenticated
//!   source is never parsed into a decision.

use serde::de::{Error as DeError, MapAccess, Visitor};
use serde::ser::SerializeMap;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use std::collections::HashSet;
use std::fmt;

use crate::crypto::{PublicKey, Signature, SigningKey};
use crate::domain::RECEIPT_CONTEXT;
use crate::error::{Error, Result};

/// The receipt format version this module produces.
pub const RECEIPT_VERSION: u8 = 1;

/// SHA-256 over the revocation list bytes exactly as loaded, for
/// [`ReceiptPayload::srl_hash`].
///
/// Hashes the wire bytes rather than a re-serialization so every
/// implementation derives the same commitment without having to agree on a
/// canonical re-encoding of a list it only ever received as bytes.
pub fn srl_commitment_digest(srl_bytes: &[u8]) -> [u8; 32] {
    use sha2::{Digest, Sha256};
    let mut hasher = Sha256::new();
    hasher.update(srl_bytes);
    hasher.finalize().into()
}

/// SHA-256 over the trusted root set, for [`ReceiptPayload::trusted_roots_hash`].
///
/// Keys are sorted before hashing so the commitment depends on the set and not
/// on the order an enforcement point happened to load it in. Duplicates are
/// collapsed for the same reason.
pub fn trusted_roots_digest(roots: &[[u8; 32]]) -> [u8; 32] {
    use sha2::{Digest, Sha256};
    let mut sorted: Vec<[u8; 32]> = roots.to_vec();
    sorted.sort_unstable();
    sorted.dedup();
    let mut hasher = Sha256::new();
    for key in &sorted {
        hasher.update(key);
    }
    hasher.finalize().into()
}

/// Canonical encoding of a host allow-policy, for
/// [`policy_commitment_digest`].
///
/// Deterministic CBOR of the field → constraint-expression map with keys
/// sorted, so the commitment describes the policy and not the order a host
/// happened to build it in.
///
/// The encoding is pinned here rather than left to callers. A caller-chosen
/// encoding is enough for one producer comparing against itself and useless
/// the moment a second implementation — a verifier, another runtime, a control
/// plane checking for drift — has to reproduce the digest from the same policy.
pub fn canonical_policy_bytes(policy: &serde_json::Value) -> Option<Vec<u8>> {
    use std::collections::BTreeMap;

    let object = policy.as_object()?;
    let sorted: BTreeMap<&String, &serde_json::Value> = object.iter().collect();
    let mut bytes = Vec::new();
    ciborium::into_writer(&sorted, &mut bytes).ok()?;
    Some(bytes)
}

/// SHA-256 over the host policy ceiling, for
/// [`ReceiptPayload::policy_definition_hash`].
///
/// Takes bytes produced by [`canonical_policy_bytes`]. Hashing a different
/// encoding produces a commitment nothing else can reproduce, which makes key
/// 11 unverifiable rather than merely inconvenient.
pub fn policy_commitment_digest(policy_bytes: &[u8]) -> [u8; 32] {
    use sha2::{Digest, Sha256};
    let mut hasher = Sha256::new();
    hasher.update(policy_bytes);
    hasher.finalize().into()
}

/// The decision an enforcement point reached.
///
/// Encoded as the text `"allow"` or `"deny"`. A boolean encoding is
/// non-conformant, which is why this is an enum rather than a `bool`: the wire
/// form cannot drift from the spec without changing this type.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Outcome {
    Allow,
    Deny,
}

impl Outcome {
    pub fn as_str(&self) -> &'static str {
        match self {
            Outcome::Allow => "allow",
            Outcome::Deny => "deny",
        }
    }
}

impl Serialize for Outcome {
    fn serialize<S: Serializer>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error> {
        serializer.serialize_str(self.as_str())
    }
}

impl<'de> Deserialize<'de> for Outcome {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> std::result::Result<Self, D::Error> {
        let s = String::deserialize(deserializer)?;
        match s.as_str() {
            "allow" => Ok(Outcome::Allow),
            "deny" => Ok(Outcome::Deny),
            other => Err(D::Error::custom(format!(
                "outcome must be \"allow\" or \"deny\", got {:?}",
                other
            ))),
        }
    }
}

/// The signed content of a receipt.
///
/// Encoded as a CBOR map with unsigned integer keys. Absent optional fields are
/// omitted from the map rather than encoded as null, so that two
/// implementations agree on the bytes of the same logical receipt.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ReceiptPayload {
    /// Key 0. Must equal [`RECEIPT_VERSION`] and the artifact's `receipt_version`.
    pub version: u8,

    /// Key 1. Deployment-assigned label for the enforcement point.
    ///
    /// Descriptive only, and deliberately so: `signer_key` is the
    /// cryptographic identity and the only field a verifier may key trust on.
    /// This is a human-readable aid for operators reading receipts, never a
    /// lookup key into an authorizer registry — two enforcement points may
    /// carry the same label, and the label may change without the key changing.
    /// Resolving a `signer_key` to a legitimate enforcement point is an
    /// out-of-band concern this artifact does not attempt to answer.
    pub authorizer_id: Option<String>,

    /// Key 2. CBOR-encoded warrant stack for the presented chain, as a byte string.
    pub warrant_chain: Vec<u8>,

    /// Key 3. `"tool:" || tool_name`.
    pub action: String,

    /// Key 4. The decision.
    pub outcome: Outcome,

    /// Key 5. Unix seconds at decision time. Also the basis for recovering PoP
    /// windows during forensic verification.
    pub timestamp: i64,

    /// Key 6. Root principal identifier when known.
    pub root_principal: Option<String>,

    /// Key 7. Commitment to the canonical request. Omitted, never zero-filled,
    /// when the arguments could not be canonicalized.
    pub request_hash: Option<[u8; 32]>,

    /// Key 8. The holder's proof-of-possession signature for this invocation.
    pub pop_signature: Option<[u8; 64]>,

    /// Key 9. Correlation handle for this decision.
    ///
    /// Set by the host from whatever identifier it already has — a JSON-RPC
    /// request id, a trace or span id, a workflow activity id — so a receipt
    /// can be matched against the host's own logs. Falls back to a derived
    /// value when the host supplies nothing.
    ///
    /// Not an identity guarantee: two invocations may legitimately carry the
    /// same handle, and nothing here enforces uniqueness. Distinguishing
    /// repeats is [`Self::prev_receipt_hash`]'s job, and matching a decision to
    /// the arguments it was made over is [`Self::request_hash`]'s — that one is
    /// content-addressed, so a match proves the arguments rather than asserting
    /// them.
    pub request_id: String,

    /// Key 10. Canonical kebab-case error name for a denial. Required when
    /// `outcome` is [`Outcome::Deny`].
    pub decision_code: Option<String>,

    /// Key 11. Commitment to the enforcement point's policy configuration in
    /// force at decision time.
    pub policy_definition_hash: Option<[u8; 32]>,

    /// Key 12. Version of the revocation list in force at decision time.
    ///
    /// Present only when the loaded list carries a version — a published,
    /// monotonic SRL. `None` alongside a present [`Self::srl_hash`] means the
    /// enforcement point held an unversioned list.
    pub srl_version: Option<u64>,

    /// Key 13. SHA-256 over the canonical bytes of the revocation list in
    /// force at decision time.
    ///
    /// Absent means the enforcement point had no revocation data loaded, which
    /// is a different claim from having loaded a list that revoked nothing. A
    /// verifier needs to tell those apart: the first says revocation was never
    /// consulted, the second says it was consulted and did not match. Without
    /// this field a stale or absent list is indistinguishable from a current
    /// one, and "the warrant was not revoked when this ran" is unfalsifiable.
    pub srl_hash: Option<[u8; 32]>,

    /// Key 14. SHA-256 over the previous receipt this signer emitted.
    ///
    /// Individually verifiable receipts do not make a *set* of receipts
    /// trustworthy: an enforcement point can decline to emit one for a decision
    /// it would rather forget, and nothing reveals the omission. Chaining makes
    /// deletion detectable — a missing link breaks every receipt after it — so
    /// the claim rises from "this decision happened" to "these are all the
    /// decisions". Absent on the first receipt from a signer, or when the
    /// deployment does not chain.
    pub prev_receipt_hash: Option<[u8; 32]>,

    /// Key 15. Commitment to the trusted root set in force at decision time.
    ///
    /// The embedded chain shows which root issued the authority, but not that
    /// the enforcement point had any business trusting that root when it
    /// decided. Together with keys 12 and 13 this pins the world the authorizer
    /// was operating in: which roots it honoured and which revocations it knew.
    /// See [`trusted_roots_digest`].
    pub trusted_roots_hash: Option<[u8; 32]>,
}

impl ReceiptPayload {
    /// Create a payload for an allowed decision.
    ///
    /// `pop_signature` is required rather than optional. Proof-of-possession is
    /// invariant I6, so an allow cannot have happened without one, and the PoP is
    /// what anchors the decision instant: because the holder signs over a
    /// timestamp window and the window is derived from `timestamp` during
    /// verification, the recorded instant is attested by a key the enforcement
    /// point does not hold. Comparing that window against the issuer-signed
    /// validity bounds is what makes "this warrant was live when this request was
    /// made" checkable rather than merely asserted. An allow without a PoP is
    /// evidence of nothing but the signer's word.
    pub fn allow(
        warrant_chain: Vec<u8>,
        action: impl Into<String>,
        timestamp: i64,
        request_id: impl Into<String>,
        pop_signature: [u8; 64],
    ) -> Self {
        Self {
            version: RECEIPT_VERSION,
            authorizer_id: None,
            warrant_chain,
            action: action.into(),
            outcome: Outcome::Allow,
            timestamp,
            root_principal: None,
            request_hash: None,
            pop_signature: Some(pop_signature),
            request_id: request_id.into(),
            decision_code: None,
            policy_definition_hash: None,
            srl_version: None,
            srl_hash: None,
            prev_receipt_hash: None,
            trusted_roots_hash: None,
        }
    }

    /// Create a payload for a denial that occurred *after* proof-of-possession
    /// verified — a constraint violation, a missing approval, and so on.
    ///
    /// The PoP is required here for the same reason it is on an allow: the
    /// enforcement point holds a valid one, and discarding it would throw away
    /// the only second-party attestation of when the request was made.
    ///
    /// `decision_code` must be a canonical kebab-case error name such as
    /// `"constraint-violation"`. It must not carry free text or argument values,
    /// which would reintroduce disclosure into a field intended to be safe to
    /// retain indefinitely.
    pub fn deny(
        warrant_chain: Vec<u8>,
        action: impl Into<String>,
        timestamp: i64,
        request_id: impl Into<String>,
        decision_code: impl Into<String>,
        pop_signature: [u8; 64],
    ) -> Self {
        Self {
            version: RECEIPT_VERSION,
            authorizer_id: None,
            warrant_chain,
            action: action.into(),
            outcome: Outcome::Deny,
            timestamp,
            root_principal: None,
            request_hash: None,
            pop_signature: Some(pop_signature),
            request_id: request_id.into(),
            decision_code: Some(decision_code.into()),
            policy_definition_hash: None,
            srl_version: None,
            srl_hash: None,
            prev_receipt_hash: None,
            trusted_roots_hash: None,
        }
    }

    /// Create a payload for a denial that occurred *at or before*
    /// proof-of-possession verification — a broken or untrusted chain, an expired
    /// warrant, or a PoP that was absent or did not verify.
    ///
    /// This is the only shape in which a receipt legitimately carries no
    /// `pop_signature`, because no valid one exists to record. Chain verification
    /// strictly precedes PoP evaluation, so which denials fall here is determined
    /// by where verification stopped, not by the reason code alone — that is why
    /// this is a distinct constructor rather than a rule a verifier can infer.
    ///
    /// A reader must not treat the absent PoP as "not checked": possession was
    /// checked and not established, which is a finding rather than a gap.
    pub fn deny_before_pop(
        warrant_chain: Vec<u8>,
        action: impl Into<String>,
        timestamp: i64,
        request_id: impl Into<String>,
        decision_code: impl Into<String>,
    ) -> Self {
        Self {
            version: RECEIPT_VERSION,
            authorizer_id: None,
            warrant_chain,
            action: action.into(),
            outcome: Outcome::Deny,
            timestamp,
            root_principal: None,
            request_hash: None,
            pop_signature: None,
            request_id: request_id.into(),
            decision_code: Some(decision_code.into()),
            policy_definition_hash: None,
            srl_version: None,
            srl_hash: None,
            prev_receipt_hash: None,
            trusted_roots_hash: None,
        }
    }

    /// Check the requirements that depend on other fields rather than on presence alone.
    ///
    /// An allow must carry a proof-of-possession and a denial must carry a
    /// reason. Neither is a presence check on its own field, so neither can be
    /// expressed in the payload's shape.
    ///
    /// Deserialization deliberately does not call this, so a malformed receipt
    /// can still be parsed and inspected — a tool reporting *which* claim is
    /// missing needs the payload in hand, which it cannot have if parsing
    /// rejected it outright.
    ///
    /// [`Receipt::verify_signature`] does call it. Parsing is for looking at a
    /// receipt; verification is for relying on one, and a signed allow that
    /// never established possession must not pass as evidence merely because
    /// the signature checks out.
    pub fn check_conditional_requirements(&self) -> Result<()> {
        if self.outcome == Outcome::Deny && self.decision_code.is_none() {
            return Err(Error::InvalidReceipt(
                "decision_code is required when outcome is \"deny\"".to_string(),
            ));
        }
        if self.outcome == Outcome::Allow && self.pop_signature.is_none() {
            return Err(Error::InvalidReceipt(
                "pop_signature is required when outcome is \"allow\"".to_string(),
            ));
        }
        Ok(())
    }

    /// Serialize to deterministic CBOR.
    pub fn to_cbor(&self) -> Result<Vec<u8>> {
        let mut bytes = Vec::new();
        ciborium::into_writer(self, &mut bytes).map_err(|e| {
            Error::InvalidReceipt(format!("failed to serialize receipt payload: {}", e))
        })?;
        Ok(bytes)
    }
}

impl Serialize for ReceiptPayload {
    fn serialize<S: Serializer>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error> {
        let optional_present = [
            self.authorizer_id.is_some(),
            self.root_principal.is_some(),
            self.request_hash.is_some(),
            self.pop_signature.is_some(),
            self.decision_code.is_some(),
            self.policy_definition_hash.is_some(),
            self.srl_version.is_some(),
            self.srl_hash.is_some(),
            self.prev_receipt_hash.is_some(),
            self.trusted_roots_hash.is_some(),
        ]
        .iter()
        .filter(|present| **present)
        .count();

        // Keys 0, 2, 3, 4, 5 and 9 are always present.
        let mut map = serializer.serialize_map(Some(6 + optional_present))?;

        map.serialize_entry(&0u8, &self.version)?;
        if let Some(authorizer_id) = &self.authorizer_id {
            map.serialize_entry(&1u8, authorizer_id)?;
        }
        map.serialize_entry(&2u8, serde_bytes::Bytes::new(&self.warrant_chain))?;
        map.serialize_entry(&3u8, &self.action)?;
        map.serialize_entry(&4u8, &self.outcome)?;
        map.serialize_entry(&5u8, &self.timestamp)?;
        if let Some(root_principal) = &self.root_principal {
            map.serialize_entry(&6u8, root_principal)?;
        }
        if let Some(request_hash) = &self.request_hash {
            map.serialize_entry(&7u8, serde_bytes::Bytes::new(request_hash))?;
        }
        if let Some(pop_signature) = &self.pop_signature {
            map.serialize_entry(&8u8, serde_bytes::Bytes::new(pop_signature))?;
        }
        map.serialize_entry(&9u8, &self.request_id)?;
        if let Some(decision_code) = &self.decision_code {
            map.serialize_entry(&10u8, decision_code)?;
        }
        if let Some(policy_definition_hash) = &self.policy_definition_hash {
            map.serialize_entry(&11u8, serde_bytes::Bytes::new(policy_definition_hash))?;
        }
        if let Some(srl_version) = &self.srl_version {
            map.serialize_entry(&12u8, srl_version)?;
        }
        if let Some(srl_hash) = &self.srl_hash {
            map.serialize_entry(&13u8, serde_bytes::Bytes::new(srl_hash))?;
        }
        if let Some(prev_receipt_hash) = &self.prev_receipt_hash {
            map.serialize_entry(&14u8, serde_bytes::Bytes::new(prev_receipt_hash))?;
        }
        if let Some(trusted_roots_hash) = &self.trusted_roots_hash {
            map.serialize_entry(&15u8, serde_bytes::Bytes::new(trusted_roots_hash))?;
        }
        map.end()
    }
}

impl<'de> Deserialize<'de> for ReceiptPayload {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> std::result::Result<Self, D::Error> {
        struct ReceiptPayloadVisitor;

        fn fixed<const N: usize, E: DeError>(
            bytes: Vec<u8>,
            field: &str,
        ) -> std::result::Result<[u8; N], E> {
            let len = bytes.len();
            bytes
                .try_into()
                .map_err(|_| E::custom(format!("{} must be {} bytes, got {}", field, N, len)))
        }

        impl<'de> Visitor<'de> for ReceiptPayloadVisitor {
            type Value = ReceiptPayload;

            fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
                formatter.write_str("CBOR map of receipt payload with integer keys")
            }

            fn visit_map<A: MapAccess<'de>>(
                self,
                mut map: A,
            ) -> std::result::Result<Self::Value, A::Error> {
                let mut seen = HashSet::new();

                let mut version = None;
                let mut authorizer_id = None;
                let mut warrant_chain: Option<Vec<u8>> = None;
                let mut action = None;
                let mut outcome = None;
                let mut timestamp = None;
                let mut root_principal = None;
                let mut request_hash = None;
                let mut pop_signature = None;
                let mut request_id = None;
                let mut decision_code = None;
                let mut policy_definition_hash = None;
                let mut srl_version = None;
                let mut srl_hash = None;
                let mut prev_receipt_hash = None;
                let mut trusted_roots_hash = None;

                while let Some(key) = map.next_key::<u8>()? {
                    if !seen.insert(key) {
                        return Err(A::Error::custom(format!("duplicate key {}", key)));
                    }
                    match key {
                        0 => version = Some(map.next_value()?),
                        1 => authorizer_id = Some(map.next_value()?),
                        2 => {
                            let bytes: serde_bytes::ByteBuf = map.next_value()?;
                            warrant_chain = Some(bytes.into_vec());
                        }
                        3 => action = Some(map.next_value()?),
                        4 => outcome = Some(map.next_value()?),
                        5 => timestamp = Some(map.next_value()?),
                        6 => root_principal = Some(map.next_value()?),
                        7 => {
                            let bytes: serde_bytes::ByteBuf = map.next_value()?;
                            request_hash = Some(fixed(bytes.into_vec(), "request_hash")?);
                        }
                        8 => {
                            let bytes: serde_bytes::ByteBuf = map.next_value()?;
                            pop_signature = Some(fixed(bytes.into_vec(), "pop_signature")?);
                        }
                        9 => request_id = Some(map.next_value()?),
                        10 => decision_code = Some(map.next_value()?),
                        11 => {
                            let bytes: serde_bytes::ByteBuf = map.next_value()?;
                            policy_definition_hash =
                                Some(fixed(bytes.into_vec(), "policy_definition_hash")?);
                        }
                        12 => srl_version = Some(map.next_value()?),
                        13 => {
                            let bytes: serde_bytes::ByteBuf = map.next_value()?;
                            srl_hash = Some(fixed(bytes.into_vec(), "srl_hash")?);
                        }
                        14 => {
                            let bytes: serde_bytes::ByteBuf = map.next_value()?;
                            prev_receipt_hash = Some(fixed(bytes.into_vec(), "prev_receipt_hash")?);
                        }
                        15 => {
                            let bytes: serde_bytes::ByteBuf = map.next_value()?;
                            trusted_roots_hash =
                                Some(fixed(bytes.into_vec(), "trusted_roots_hash")?);
                        }
                        _ => {
                            return Err(A::Error::custom(format!(
                                "unknown receipt payload key {}",
                                key
                            )));
                        }
                    }
                }

                Ok(ReceiptPayload {
                    version: version.ok_or_else(|| A::Error::custom("missing version"))?,
                    authorizer_id,
                    warrant_chain: warrant_chain
                        .ok_or_else(|| A::Error::custom("missing warrant_chain"))?,
                    action: action.ok_or_else(|| A::Error::custom("missing action"))?,
                    outcome: outcome.ok_or_else(|| A::Error::custom("missing outcome"))?,
                    timestamp: timestamp.ok_or_else(|| A::Error::custom("missing timestamp"))?,
                    root_principal,
                    request_hash,
                    pop_signature,
                    request_id: request_id.ok_or_else(|| A::Error::custom("missing request_id"))?,
                    decision_code,
                    policy_definition_hash,
                    srl_version,
                    srl_hash,
                    prev_receipt_hash,
                    trusted_roots_hash,
                })
            }
        }

        deserializer.deserialize_map(ReceiptPayloadVisitor)
    }
}

/// A signed authorization receipt.
///
/// Mirrors the shape of [`crate::approval::SignedApproval`]: a version readable
/// before parsing, the opaque signed bytes, the signer's public key extracted
/// for convenience, and the signature.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Receipt {
    /// Selects the preimage construction before any parsing. Unauthenticated by
    /// necessity, and cross-checked against payload key 0 during verification.
    pub receipt_version: u8,

    /// The exact deterministic CBOR bytes of the payload, carried opaquely.
    #[serde(with = "serde_bytes")]
    pub payload: Vec<u8>,

    /// Public key of the signing enforcement point (extracted for convenience;
    /// not itself signed).
    pub signer_key: PublicKey,

    /// Ed25519 signature over `RECEIPT_CONTEXT || receipt_version || payload`.
    pub signature: Signature,
}

impl Receipt {
    /// Sign a payload, producing a receipt.
    pub fn create(payload: &ReceiptPayload, signing_key: &SigningKey) -> Result<Self> {
        let payload_bytes = payload.to_cbor()?;
        let preimage = Self::signing_preimage(RECEIPT_VERSION, &payload_bytes);

        Ok(Self {
            receipt_version: RECEIPT_VERSION,
            payload: payload_bytes,
            signer_key: signing_key.public_key(),
            signature: signing_key.sign(&preimage),
        })
    }

    /// SHA-256 over this receipt's CBOR encoding, for the next receipt's
    /// [`ReceiptPayload::prev_receipt_hash`].
    ///
    /// Covers the signature as well as the payload, so a link commits to the
    /// exact artifact that was emitted rather than to content that could have
    /// been re-signed under a different key.
    pub fn digest(&self) -> Result<[u8; 32]> {
        use sha2::{Digest, Sha256};
        let mut bytes = Vec::new();
        ciborium::into_writer(self, &mut bytes)
            .map_err(|e| Error::InvalidReceipt(format!("failed to encode receipt: {}", e)))?;
        let mut hasher = Sha256::new();
        hasher.update(&bytes);
        Ok(hasher.finalize().into())
    }

    /// Verify the signature and return the payload.
    ///
    /// Verify the signature and return the parsed payload.
    ///
    /// This establishes *authenticity* only: that `signer_key` signed these
    /// payload bytes. It says nothing about whether that key was legitimately
    /// the enforcement point's, nor whether the chain, arguments, or decision
    /// hold up — those are separate claims produced by the claim-set verifier.
    /// Callers must not treat a successful return as authorization evidence.
    pub fn verify_signature(&self) -> Result<ReceiptPayload> {
        if self.receipt_version != RECEIPT_VERSION {
            return Err(Error::UnsupportedVersion(self.receipt_version));
        }

        let preimage = Self::signing_preimage(self.receipt_version, &self.payload);
        self.signer_key
            .verify(&preimage, &self.signature)
            .map_err(|e| Error::InvalidReceipt(format!("signature does not verify: {}", e)))?;

        let payload: ReceiptPayload = ciborium::from_reader(&self.payload[..])
            .map_err(|e| Error::InvalidReceipt(format!("failed to deserialize payload: {}", e)))?;

        // A payload version that disagrees with the artifact would let a
        // transport downgrade a receipt by rewriting the unauthenticated field.
        if payload.version != self.receipt_version {
            return Err(Error::InvalidReceipt(format!(
                "payload version {} does not match artifact version {}",
                payload.version, self.receipt_version
            )));
        }
        payload.check_conditional_requirements()?;

        Ok(payload)
    }

    /// Domain-separated signing preimage: `RECEIPT_CONTEXT || receipt_version || payload_bytes`.
    ///
    /// The Ed25519 message is `SIGNATURE_CONTEXT ||` this preimage. External
    /// signers must call [`SigningKey::sign_raw`] on those concatenated bytes.
    pub fn signing_preimage(receipt_version: u8, payload_bytes: &[u8]) -> Vec<u8> {
        let mut preimage = Vec::with_capacity(RECEIPT_CONTEXT.len() + 1 + payload_bytes.len());
        preimage.extend_from_slice(RECEIPT_CONTEXT);
        preimage.push(receipt_version);
        preimage.extend_from_slice(payload_bytes);
        preimage
    }
}

/// Verify an ordered run of receipts from one enforcement point.
///
/// Checks every signature, that one key signed them all (and that it is
/// `signer` when given), and that each receipt's `prev_receipt_hash` is the
/// digest of the receipt before it. The first receipt may link to one outside
/// the run. Returns the payloads in order.
/// Empty input is rejected because it provides no signed evidence.
///
/// A valid chain shows that no receipt inside the run was changed, removed,
/// or inserted. It does not show that newer receipts were not cut from the end;
/// export or anchor the latest digest elsewhere for that.
pub fn verify_chain(
    receipts: &[Receipt],
    signer: Option<&PublicKey>,
) -> Result<Vec<ReceiptPayload>> {
    if receipts.is_empty() {
        return Err(Error::InvalidReceipt("receipt chain is empty".to_string()));
    }
    let mut payloads = Vec::with_capacity(receipts.len());
    let mut previous: Option<[u8; 32]> = None;
    let expected = signer.or_else(|| receipts.first().map(|receipt| &receipt.signer_key));
    for (index, receipt) in receipts.iter().enumerate() {
        if Some(&receipt.signer_key) != expected {
            return Err(Error::InvalidReceipt(format!(
                "receipt {index} is signed by a different key"
            )));
        }
        let payload = receipt.verify_signature()?;
        if let Some(previous) = previous {
            if payload.prev_receipt_hash != Some(previous) {
                return Err(Error::InvalidReceipt(format!(
                    "receipt {index} does not link to the receipt before it"
                )));
            }
        }
        previous = Some(receipt.digest()?);
        payloads.push(payload);
    }
    Ok(payloads)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::crypto::SigningKey;

    fn chain(key: &SigningKey, length: usize) -> Vec<Receipt> {
        let mut receipts: Vec<Receipt> = Vec::new();
        for index in 0..length {
            let mut next = payload();
            next.request_id = format!("req-{index}");
            next.prev_receipt_hash = receipts.last().map(|receipt| receipt.digest().unwrap());
            receipts.push(Receipt::create(&next, key).unwrap());
        }
        receipts
    }

    #[test]
    fn verify_chain_rejects_empty_input() {
        let key = SigningKey::generate().public_key();
        for signer in [None, Some(&key)] {
            assert!(matches!(
                verify_chain(&[], signer),
                Err(Error::InvalidReceipt(reason)) if reason == "receipt chain is empty"
            ));
        }
    }

    #[test]
    fn verify_chain_detects_edits_gaps_and_foreign_signers() {
        let key = SigningKey::generate();
        let receipts = chain(&key, 4);
        let payloads = verify_chain(&receipts, Some(&key.public_key())).unwrap();
        assert_eq!(payloads.len(), 4);
        assert_eq!(payloads[3].request_id, "req-3");
        assert!(
            verify_chain(&receipts[1..], None).is_ok(),
            "a run may start mid-chain"
        );

        let mut gap = receipts.clone();
        gap.remove(2);
        assert!(verify_chain(&gap, None).is_err());

        let mut swapped = receipts.clone();
        swapped.swap(1, 2);
        assert!(verify_chain(&swapped, None).is_err());

        let other = SigningKey::generate();
        assert!(verify_chain(&receipts, Some(&other.public_key())).is_err());
        let mut mixed = receipts.clone();
        mixed[3] = chain(&other, 1).remove(0);
        assert!(verify_chain(&mixed, None).is_err());

        let mut tampered = receipts;
        tampered[1].payload[5] ^= 1;
        assert!(verify_chain(&tampered, None).is_err());
    }

    fn payload() -> ReceiptPayload {
        ReceiptPayload::allow(
            vec![0xA1, 0x01, 0x02],
            "tool:read_file",
            1_700_000_000,
            "req-1",
            [9u8; 64],
        )
    }

    fn full_payload() -> ReceiptPayload {
        ReceiptPayload {
            version: RECEIPT_VERSION,
            authorizer_id: Some("authorizer-1".to_string()),
            warrant_chain: vec![0xA1, 0x01, 0x02],
            action: "tool:delete_file".to_string(),
            outcome: Outcome::Deny,
            timestamp: 1_700_000_000,
            root_principal: Some("root@example.com".to_string()),
            request_hash: Some([7u8; 32]),
            pop_signature: Some([9u8; 64]),
            request_id: "req-2".to_string(),
            decision_code: Some("tool-not-authorized".to_string()),
            policy_definition_hash: Some([3u8; 32]),
            srl_version: Some(47),
            srl_hash: Some([5u8; 32]),
            prev_receipt_hash: Some([6u8; 32]),
            trusted_roots_hash: Some([8u8; 32]),
        }
    }

    /// An unversioned list still commits: key 13 present, key 12 absent. This
    /// is the shape produced by a plain `SignedRevocationList`, and it must not
    /// be confused with having loaded nothing at all.
    #[test]
    fn round_trips_an_unversioned_revocation_commitment() {
        let mut original = full_payload();
        original.srl_version = None;
        original.srl_hash = Some([5u8; 32]);

        let bytes = original.to_cbor().unwrap();
        let decoded: ReceiptPayload = ciborium::from_reader(&bytes[..]).unwrap();

        assert_eq!(original, decoded);
        assert_eq!(decoded.srl_version, None);
        assert_eq!(decoded.srl_hash, Some([5u8; 32]));
    }

    /// No revocation data loaded omits both keys rather than encoding null, so
    /// two implementations agree on the bytes of the same logical receipt.
    #[test]
    fn omits_revocation_keys_when_no_list_was_loaded() {
        let original = payload();
        assert_eq!(original.srl_version, None);
        assert_eq!(original.srl_hash, None);

        let bytes = original.to_cbor().unwrap();
        let map: ciborium::Value = ciborium::from_reader(&bytes[..]).unwrap();
        let keys: Vec<i128> = match map {
            ciborium::Value::Map(entries) => entries
                .iter()
                .filter_map(|(k, _)| k.as_integer().map(i128::from))
                .collect(),
            other => panic!("payload must encode as a CBOR map, got {:?}", other),
        };

        assert!(!keys.contains(&12), "key 12 must be omitted, not null");
        assert!(!keys.contains(&13), "key 13 must be omitted, not null");
    }

    #[test]
    fn rejects_an_srl_hash_that_is_not_32_bytes() {
        let mut bytes = Vec::new();
        ciborium::into_writer(
            &ciborium::Value::Map(vec![(
                ciborium::Value::Integer(13u8.into()),
                ciborium::Value::Bytes(vec![0u8; 31]),
            )]),
            &mut bytes,
        )
        .unwrap();

        let decoded: std::result::Result<ReceiptPayload, _> = ciborium::from_reader(&bytes[..]);
        let message = decoded.unwrap_err().to_string();
        assert!(
            message.contains("srl_hash") && message.contains("32"),
            "error must name the field and the expected length, got: {message}"
        );
    }

    /// Chaining is what makes omission detectable, so the link has to survive
    /// the round trip byte for byte.
    #[test]
    fn round_trips_the_chain_link_and_root_commitment() {
        let original = full_payload();
        let bytes = original.to_cbor().unwrap();
        let decoded: ReceiptPayload = ciborium::from_reader(&bytes[..]).unwrap();

        assert_eq!(decoded.prev_receipt_hash, Some([6u8; 32]));
        assert_eq!(decoded.trusted_roots_hash, Some([8u8; 32]));
    }

    /// The first receipt from a signer has nothing to point at, and a
    /// deployment that does not chain has nothing to say — both omit the key
    /// rather than encoding a zero hash that would look like a real link.
    #[test]
    fn omits_the_chain_link_when_there_is_no_predecessor() {
        let original = payload();
        assert_eq!(original.prev_receipt_hash, None);

        let bytes = original.to_cbor().unwrap();
        let map: ciborium::Value = ciborium::from_reader(&bytes[..]).unwrap();
        let keys: Vec<i128> = match map {
            ciborium::Value::Map(entries) => entries
                .iter()
                .filter_map(|(k, _)| k.as_integer().map(i128::from))
                .collect(),
            other => panic!("payload must encode as a CBOR map, got {:?}", other),
        };

        assert!(
            !keys.contains(&14),
            "key 14 must be omitted, not zero-filled"
        );
        assert!(
            !keys.contains(&15),
            "key 15 must be omitted, not zero-filled"
        );
    }

    /// The commitment must describe the set, not the order it was loaded in,
    /// or two enforcement points with identical trust would disagree.
    #[test]
    fn the_root_commitment_is_order_and_duplicate_independent() {
        let a = [1u8; 32];
        let b = [2u8; 32];

        assert_eq!(trusted_roots_digest(&[a, b]), trusted_roots_digest(&[b, a]));
        assert_eq!(
            trusted_roots_digest(&[a, b]),
            trusted_roots_digest(&[b, a, a])
        );
        assert_ne!(trusted_roots_digest(&[a]), trusted_roots_digest(&[a, b]));
    }

    /// An empty trust set is a real, distinguishable state — an enforcement
    /// point that trusts nothing is not the same as one that never said.
    #[test]
    fn an_empty_root_set_has_its_own_commitment() {
        assert_ne!(
            trusted_roots_digest(&[]),
            trusted_roots_digest(&[[1u8; 32]])
        );
    }

    #[test]
    fn rejects_a_chain_link_that_is_not_32_bytes() {
        let mut bytes = Vec::new();
        ciborium::into_writer(
            &ciborium::Value::Map(vec![(
                ciborium::Value::Integer(14u8.into()),
                ciborium::Value::Bytes(vec![0u8; 31]),
            )]),
            &mut bytes,
        )
        .unwrap();

        let decoded: std::result::Result<ReceiptPayload, _> = ciborium::from_reader(&bytes[..]);
        let message = decoded.unwrap_err().to_string();
        assert!(
            message.contains("prev_receipt_hash") && message.contains("32"),
            "error must name the field and expected length, got: {message}"
        );
    }

    #[test]
    fn round_trips_a_minimal_payload() {
        let original = payload();
        let bytes = original.to_cbor().unwrap();
        let decoded: ReceiptPayload = ciborium::from_reader(&bytes[..]).unwrap();
        assert_eq!(original, decoded);
    }

    #[test]
    fn round_trips_a_payload_with_every_field_present() {
        let original = full_payload();
        let bytes = original.to_cbor().unwrap();
        let decoded: ReceiptPayload = ciborium::from_reader(&bytes[..]).unwrap();
        assert_eq!(original, decoded);
    }

    #[test]
    fn encoding_is_deterministic() {
        let payload = full_payload();
        assert_eq!(payload.to_cbor().unwrap(), payload.to_cbor().unwrap());
    }

    #[test]
    fn absent_optional_fields_are_omitted_not_null() {
        let bytes = payload().to_cbor().unwrap();
        let value: ciborium::Value = ciborium::from_reader(&bytes[..]).unwrap();
        let entries = value.as_map().expect("payload must encode as a CBOR map");

        let keys: Vec<i128> = entries
            .iter()
            .map(|(k, _)| k.as_integer().expect("keys must be integers").into())
            .collect();
        assert_eq!(keys, vec![0, 2, 3, 4, 5, 8, 9]);
        assert!(entries.iter().all(|(_, v)| !v.is_null()));
    }

    #[test]
    fn integer_keys_are_encoded_in_numeric_order() {
        let bytes = full_payload().to_cbor().unwrap();
        let value: ciborium::Value = ciborium::from_reader(&bytes[..]).unwrap();
        let keys: Vec<i128> = value
            .as_map()
            .unwrap()
            .iter()
            .map(|(k, _)| k.as_integer().unwrap().into())
            .collect();
        assert_eq!(
            keys,
            vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
        );
    }

    #[test]
    fn byte_fields_encode_as_cbor_byte_strings_not_arrays() {
        let bytes = full_payload().to_cbor().unwrap();
        let value: ciborium::Value = ciborium::from_reader(&bytes[..]).unwrap();
        let entries = value.as_map().unwrap();

        for key in [2i128, 7, 8, 11, 13, 14, 15] {
            let (_, field) = entries
                .iter()
                .find(|(k, _)| i128::from(k.as_integer().unwrap()) == key)
                .unwrap();
            assert!(
                field.is_bytes(),
                "key {} must encode as a CBOR byte string, got {:?}",
                key,
                field
            );
        }
    }

    #[test]
    fn outcome_encodes_as_text_not_boolean() {
        let bytes = payload().to_cbor().unwrap();
        let value: ciborium::Value = ciborium::from_reader(&bytes[..]).unwrap();
        let (_, outcome) = value
            .as_map()
            .unwrap()
            .iter()
            .find(|(k, _)| i128::from(k.as_integer().unwrap()) == 4)
            .unwrap();
        assert_eq!(outcome.as_text(), Some("allow"));
    }

    #[test]
    fn rejects_a_boolean_outcome() {
        let encoded = ciborium::Value::Map(vec![
            (
                ciborium::Value::Integer(0.into()),
                ciborium::Value::Integer(1.into()),
            ),
            (
                ciborium::Value::Integer(2.into()),
                ciborium::Value::Bytes(vec![0xA1]),
            ),
            (
                ciborium::Value::Integer(3.into()),
                ciborium::Value::Text("tool:read".into()),
            ),
            (
                ciborium::Value::Integer(4.into()),
                ciborium::Value::Bool(true),
            ),
            (
                ciborium::Value::Integer(5.into()),
                ciborium::Value::Integer(1.into()),
            ),
            (
                ciborium::Value::Integer(9.into()),
                ciborium::Value::Text("req".into()),
            ),
        ]);
        let mut bytes = Vec::new();
        ciborium::into_writer(&encoded, &mut bytes).unwrap();

        let decoded: std::result::Result<ReceiptPayload, _> = ciborium::from_reader(&bytes[..]);
        assert!(decoded.is_err(), "a boolean outcome must be rejected");
    }

    #[test]
    fn rejects_unknown_payload_keys() {
        let mut bytes = Vec::new();
        let encoded = ciborium::Value::Map(vec![
            (
                ciborium::Value::Integer(0.into()),
                ciborium::Value::Integer(1.into()),
            ),
            (
                ciborium::Value::Integer(2.into()),
                ciborium::Value::Bytes(vec![0xA1]),
            ),
            (
                ciborium::Value::Integer(3.into()),
                ciborium::Value::Text("tool:read".into()),
            ),
            (
                ciborium::Value::Integer(4.into()),
                ciborium::Value::Text("allow".into()),
            ),
            (
                ciborium::Value::Integer(5.into()),
                ciborium::Value::Integer(1.into()),
            ),
            (
                ciborium::Value::Integer(9.into()),
                ciborium::Value::Text("req".into()),
            ),
            (
                ciborium::Value::Integer(99.into()),
                ciborium::Value::Text("surprise".into()),
            ),
        ]);
        ciborium::into_writer(&encoded, &mut bytes).unwrap();

        let decoded: std::result::Result<ReceiptPayload, _> = ciborium::from_reader(&bytes[..]);
        assert!(decoded.is_err(), "unknown keys must fail closed");
    }

    #[test]
    fn rejects_a_wrong_length_request_hash() {
        let mut bytes = Vec::new();
        let encoded = ciborium::Value::Map(vec![
            (
                ciborium::Value::Integer(0.into()),
                ciborium::Value::Integer(1.into()),
            ),
            (
                ciborium::Value::Integer(2.into()),
                ciborium::Value::Bytes(vec![0xA1]),
            ),
            (
                ciborium::Value::Integer(3.into()),
                ciborium::Value::Text("tool:read".into()),
            ),
            (
                ciborium::Value::Integer(4.into()),
                ciborium::Value::Text("allow".into()),
            ),
            (
                ciborium::Value::Integer(5.into()),
                ciborium::Value::Integer(1.into()),
            ),
            (
                ciborium::Value::Integer(7.into()),
                ciborium::Value::Bytes(vec![0u8; 31]),
            ),
            (
                ciborium::Value::Integer(9.into()),
                ciborium::Value::Text("req".into()),
            ),
        ]);
        ciborium::into_writer(&encoded, &mut bytes).unwrap();

        let decoded: std::result::Result<ReceiptPayload, _> = ciborium::from_reader(&bytes[..]);
        assert!(decoded.is_err(), "a 31-byte request_hash must be rejected");
    }

    #[test]
    fn signs_and_verifies() {
        let key = SigningKey::generate();
        let receipt = Receipt::create(&full_payload(), &key).unwrap();

        assert_eq!(receipt.receipt_version, RECEIPT_VERSION);
        assert_eq!(receipt.signer_key, key.public_key());
        assert_eq!(receipt.verify_signature().unwrap(), full_payload());
    }

    #[test]
    fn verification_fails_when_payload_is_tampered_with() {
        let key = SigningKey::generate();
        let mut receipt = Receipt::create(&full_payload(), &key).unwrap();

        let last = receipt.payload.len() - 1;
        receipt.payload[last] ^= 0xFF;

        assert!(receipt.verify_signature().is_err());
    }

    #[test]
    fn verification_fails_under_a_different_signer_key() {
        let key = SigningKey::generate();
        let other = SigningKey::generate();
        let mut receipt = Receipt::create(&full_payload(), &key).unwrap();

        receipt.signer_key = other.public_key();

        assert!(receipt.verify_signature().is_err());
    }

    #[test]
    fn domain_separation_rejects_a_signature_over_the_bare_payload() {
        let key = SigningKey::generate();
        let payload_bytes = full_payload().to_cbor().unwrap();

        let receipt = Receipt {
            receipt_version: RECEIPT_VERSION,
            payload: payload_bytes.clone(),
            signer_key: key.public_key(),
            signature: key.sign(&payload_bytes),
        };

        assert!(
            receipt.verify_signature().is_err(),
            "a signature omitting the domain context must not verify"
        );
    }

    #[test]
    fn artifact_version_cannot_be_downgraded_without_detection() {
        let key = SigningKey::generate();
        let mut receipt = Receipt::create(&full_payload(), &key).unwrap();

        receipt.receipt_version = 2;

        // Rewriting the unauthenticated field changes the preimage, so this is
        // caught at the signature rather than at the version cross-check.
        assert!(receipt.verify_signature().is_err());
    }

    #[test]
    fn payload_version_must_match_artifact_version() {
        let key = SigningKey::generate();
        let mut payload = full_payload();
        payload.version = 2;

        let payload_bytes = payload.to_cbor().unwrap();
        let preimage = Receipt::signing_preimage(RECEIPT_VERSION, &payload_bytes);
        let receipt = Receipt {
            receipt_version: RECEIPT_VERSION,
            payload: payload_bytes,
            signer_key: key.public_key(),
            signature: key.sign(&preimage),
        };

        let error = receipt.verify_signature().unwrap_err();
        assert!(
            error
                .to_string()
                .contains("does not match artifact version"),
            "expected a version mismatch, got: {}",
            error
        );
    }

    #[test]
    fn the_artifact_round_trips_through_cbor() {
        let key = SigningKey::generate();
        let receipt = Receipt::create(&full_payload(), &key).unwrap();

        let mut bytes = Vec::new();
        ciborium::into_writer(&receipt, &mut bytes).unwrap();
        let decoded: Receipt = ciborium::from_reader(&bytes[..]).unwrap();

        assert_eq!(decoded.verify_signature().unwrap(), full_payload());
    }

    #[test]
    fn a_denial_without_a_decision_code_is_rejected_by_the_conditional_check() {
        let mut payload = full_payload();
        payload.decision_code = None;

        assert!(payload.check_conditional_requirements().is_err());
        assert!(full_payload().check_conditional_requirements().is_ok());
    }

    #[test]
    fn an_allow_without_a_pop_signature_is_rejected_by_the_conditional_check() {
        let mut allowed = payload();
        allowed.pop_signature = None;

        assert!(allowed.check_conditional_requirements().is_err());
        assert!(payload().check_conditional_requirements().is_ok());
    }

    #[test]
    fn verification_rejects_a_signed_allow_without_pop_signature() {
        let signer = SigningKey::generate();
        let mut invalid = payload();
        invalid.pop_signature = None;

        let receipt = Receipt::create(&invalid, &signer).unwrap();
        let err = receipt.verify_signature().unwrap_err();
        assert!(
            err.to_string().contains("pop_signature is required"),
            "public verification must reject invalid receipt claims, got: {err}"
        );
    }

    #[test]
    fn verification_rejects_a_signed_deny_without_decision_code() {
        let signer = SigningKey::generate();
        let mut invalid = full_payload();
        invalid.outcome = Outcome::Deny;
        invalid.decision_code = None;

        let receipt = Receipt::create(&invalid, &signer).unwrap();
        let err = receipt.verify_signature().unwrap_err();
        assert!(
            err.to_string().contains("decision_code is required"),
            "public verification must reject invalid receipt claims, got: {err}"
        );
    }

    #[test]
    fn a_denial_before_pop_verification_may_omit_the_pop_signature() {
        let denied = ReceiptPayload::deny_before_pop(
            vec![0xA1, 0x01, 0x02],
            "tool:read_file",
            1_700_000_000,
            "req-3",
            "pop-signature-invalid",
        );

        assert!(denied.pop_signature.is_none());
        assert!(denied.check_conditional_requirements().is_ok());
    }
}