1#![forbid(unsafe_code)]
45
46use crate::canonical::canonical_encode;
47use crate::keyid::{KeyId, SignatureSuite};
48use crate::message::CausedBy;
49use crate::protocol::BEGIN_KEYWORD;
50use crate::r4::Signer;
51use crate::sexpr::{Atom, SExpr};
52use alloc::collections::BTreeSet;
53use alloc::string::String;
54use alloc::vec::Vec;
55use core::fmt;
56
57pub const ATTEST_DOMAIN_TAG: &str = "cbcl-attest-v2";
61
62pub const ATTEST_V3_DOMAIN_TAG: &str = "cbcl-attest-v3";
75
76#[derive(Debug, Clone, PartialEq, Eq)]
87#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
88pub struct AttestationHeader {
89 pub content_hash: String,
91 pub performative: String,
93 pub from: KeyId,
95 pub to: BTreeSet<KeyId>,
97 pub thread: String,
99 pub caused_by: Option<CausedBy>,
102}
103
104pub fn attestation_sexpr(h: &AttestationHeader) -> SExpr {
110 use alloc::vec;
111 let mut items = vec![
112 SExpr::Atom(Atom::Symbol(String::from(ATTEST_DOMAIN_TAG))),
113 SExpr::Atom(Atom::Symbol(String::from(h.from.suite.as_str()))),
114 SExpr::Atom(Atom::Symbol(h.content_hash.clone())),
115 SExpr::Atom(Atom::Symbol(h.performative.clone())),
116 SExpr::Atom(Atom::Symbol(h.from.canonical_spelling())),
117 SExpr::List(
118 h.to.iter()
119 .map(|k| SExpr::Atom(Atom::Symbol(k.canonical_spelling())))
120 .collect(),
121 ),
122 SExpr::Atom(Atom::Str(h.thread.clone())),
123 ];
124 if let Some(cb) = &h.caused_by {
125 items.push(match cb {
128 CausedBy::Begin => SExpr::Atom(Atom::Symbol(String::from(BEGIN_KEYWORD))),
129 CausedBy::Single(hash) => SExpr::Atom(Atom::Symbol(hash.clone())),
130 CausedBy::Multiple(hashes) => SExpr::List(
131 hashes
132 .iter()
133 .map(|hash| SExpr::Atom(Atom::Symbol(hash.clone())))
134 .collect(),
135 ),
136 });
137 }
138 SExpr::List(items)
139}
140
141pub fn attestation_preimage(h: &AttestationHeader) -> Vec<u8> {
144 canonical_encode(&attestation_sexpr(h))
145}
146
147pub fn attestation_v3_sexpr(suite: &SignatureSuite, root: &str) -> SExpr {
160 use alloc::vec;
161 SExpr::List(vec![
162 SExpr::Atom(Atom::Symbol(String::from(ATTEST_V3_DOMAIN_TAG))),
163 SExpr::Atom(Atom::Symbol(String::from(suite.as_str()))),
164 SExpr::Atom(Atom::Symbol(String::from(root))),
165 ])
166}
167
168pub fn attestation_v3_preimage(suite: &SignatureSuite, root: &str) -> Vec<u8> {
171 canonical_encode(&attestation_v3_sexpr(suite, root))
172}
173
174#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
177#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
178pub enum SignatureDiscipline {
179 V1Full,
181 V2Attested,
183 V3Root,
186}
187
188impl SignatureDiscipline {
189 pub fn as_str(&self) -> &'static str {
191 match self {
192 SignatureDiscipline::V1Full => "v1",
193 SignatureDiscipline::V2Attested => ATTEST_DOMAIN_TAG,
194 SignatureDiscipline::V3Root => ATTEST_V3_DOMAIN_TAG,
195 }
196 }
197
198 pub fn parse(s: &str) -> Result<Self, AttestError> {
201 match s {
202 "v1" => Ok(SignatureDiscipline::V1Full),
203 ATTEST_DOMAIN_TAG => Ok(SignatureDiscipline::V2Attested),
204 ATTEST_V3_DOMAIN_TAG => Ok(SignatureDiscipline::V3Root),
205 other => Err(AttestError::UnknownDiscipline(String::from(other))),
206 }
207 }
208}
209
210impl fmt::Display for SignatureDiscipline {
211 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
212 f.write_str(self.as_str())
213 }
214}
215
216#[derive(Debug, Clone, PartialEq, Eq)]
219pub enum AttestError {
220 UnknownSuite(String),
223 UnknownDiscipline(String),
225 DisciplineMismatch {
229 marker: SignatureDiscipline,
231 input: SignatureDiscipline,
233 },
234 KeyMismatch,
236 InvalidSignature,
238}
239
240impl fmt::Display for AttestError {
241 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
242 match self {
243 AttestError::UnknownSuite(s) => write!(f, "unknown signature suite '{s}'"),
244 AttestError::UnknownDiscipline(s) => {
245 write!(f, "unknown signature discipline marker '{s}'")
246 }
247 AttestError::DisciplineMismatch { marker, input } => write!(
248 f,
249 "signature discipline mismatch: signature declares '{marker}', \
250 verification input requires '{input}'"
251 ),
252 AttestError::KeyMismatch => f.write_str("key does not match attestation's from key"),
253 AttestError::InvalidSignature => f.write_str("signature verification failed"),
254 }
255 }
256}
257
258pub fn sign_attestation_v2(
265 signer: &dyn Signer,
266 header: &AttestationHeader,
267) -> Result<Vec<u8>, AttestError> {
268 match &header.from.suite {
269 SignatureSuite::Ed25519 => Ok(signer.sign(&attestation_preimage(header))),
270 SignatureSuite::Other(s) => Err(AttestError::UnknownSuite(s.clone())),
271 }
272}
273
274pub fn verify_attestation_v2(
281 signer: &dyn Signer,
282 key: &KeyId,
283 header: &AttestationHeader,
284 sig: &[u8],
285) -> Result<(), AttestError> {
286 if let SignatureSuite::Other(s) = &header.from.suite {
293 return Err(AttestError::UnknownSuite(s.clone()));
294 }
295 if let SignatureSuite::Other(s) = &key.suite {
296 return Err(AttestError::UnknownSuite(s.clone()));
297 }
298 if key != &header.from {
299 return Err(AttestError::KeyMismatch);
300 }
301 if signer.verify(&attestation_preimage(header), sig) {
302 Ok(())
303 } else {
304 Err(AttestError::InvalidSignature)
305 }
306}
307
308pub fn sign_attestation_v3(
320 suite: &SignatureSuite,
321 root: &str,
322 signer: &dyn Signer,
323) -> Result<Vec<u8>, AttestError> {
324 match suite {
325 SignatureSuite::Ed25519 => Ok(signer.sign(&attestation_v3_preimage(suite, root))),
326 SignatureSuite::Other(s) => Err(AttestError::UnknownSuite(s.clone())),
327 }
328}
329
330pub fn verify_attestation_v3(
340 suite: &SignatureSuite,
341 root: &str,
342 sig: &[u8],
343 signer: &dyn Signer,
344) -> Result<(), AttestError> {
345 if let SignatureSuite::Other(s) = suite {
346 return Err(AttestError::UnknownSuite(s.clone()));
347 }
348 if signer.verify(&attestation_v3_preimage(suite, root), sig) {
349 Ok(())
350 } else {
351 Err(AttestError::InvalidSignature)
352 }
353}
354
355#[derive(Debug, Clone, Copy)]
358pub enum SigningInput<'a> {
359 V1Full(&'a [u8]),
361 V2Attested {
363 key: &'a KeyId,
364 header: &'a AttestationHeader,
365 },
366 V3Root {
368 suite: &'a SignatureSuite,
369 root: &'a str,
370 },
371}
372
373impl SigningInput<'_> {
374 pub fn discipline(&self) -> SignatureDiscipline {
376 match self {
377 SigningInput::V1Full(_) => SignatureDiscipline::V1Full,
378 SigningInput::V2Attested { .. } => SignatureDiscipline::V2Attested,
379 SigningInput::V3Root { .. } => SignatureDiscipline::V3Root,
380 }
381 }
382}
383
384pub fn verify_with_discipline(
392 marker: SignatureDiscipline,
393 input: &SigningInput<'_>,
394 signer: &dyn Signer,
395 sig: &[u8],
396) -> Result<(), AttestError> {
397 match (marker, input) {
398 (SignatureDiscipline::V1Full, SigningInput::V1Full(bytes)) => {
399 if signer.verify(bytes, sig) {
400 Ok(())
401 } else {
402 Err(AttestError::InvalidSignature)
403 }
404 }
405 (SignatureDiscipline::V2Attested, SigningInput::V2Attested { key, header }) => {
406 verify_attestation_v2(signer, key, header, sig)
407 }
408 (SignatureDiscipline::V3Root, SigningInput::V3Root { suite, root }) => {
409 verify_attestation_v3(suite, root, sig, signer)
410 }
411 (marker, input) => Err(AttestError::DisciplineMismatch {
412 marker,
413 input: input.discipline(),
414 }),
415 }
416}
417
418#[cfg(test)]
423mod tests {
424 use super::*;
425 use alloc::string::ToString;
426 use alloc::vec::Vec;
427
428 struct TestSigner {
433 secret: &'static [u8],
434 }
435
436 impl Signer for TestSigner {
437 fn sign(&self, data: &[u8]) -> Vec<u8> {
438 use sha2::{Digest, Sha256};
439 let mut h = Sha256::new();
440 h.update(self.secret);
441 h.update(data);
442 h.finalize().to_vec()
443 }
444 fn verify(&self, data: &[u8], sig: &[u8]) -> bool {
445 self.sign(data) == sig
446 }
447 }
448
449 const ALICE: TestSigner = TestSigner { secret: b"alice" };
450 const BOB: TestSigner = TestSigner { secret: b"bob" };
451
452 fn key(s: &str) -> KeyId {
453 KeyId::parse(s).unwrap()
454 }
455
456 fn header() -> AttestationHeader {
457 let mut to = BTreeSet::new();
458 to.insert(key("@bob"));
459 to.insert(key("@carol"));
460 AttestationHeader {
461 content_hash: String::from(
462 "f1220aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
463 ),
464 performative: String::from("reveal-bid"),
465 from: key("@alice"),
466 to,
467 thread: String::from("conv-7"),
468 caused_by: Some(CausedBy::Single(String::from(
469 "f1220bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
470 ))),
471 }
472 }
473
474 #[test]
477 fn preimage_is_domain_tagged_and_names_the_suite() {
478 let bytes = attestation_preimage(&header());
479 let s = core::str::from_utf8(&bytes).unwrap();
480 assert!(s.starts_with("(15:Scbcl-attest-v2"), "got: {s}");
482 assert!(s.contains("8:Sed25519"), "suite must be committed: {s}");
483 }
484
485 #[test]
486 fn preimage_is_deterministic_across_reconstruction() {
487 assert_eq!(
489 attestation_preimage(&header()),
490 attestation_preimage(&header())
491 );
492 }
493
494 #[test]
497 fn alias_key_spellings_reconstruct_identical_preimage() {
498 let mut explicit = header();
499 explicit.from = key("@ed25519:alice");
500 assert_eq!(
501 attestation_preimage(&header()),
502 attestation_preimage(&explicit)
503 );
504 }
505
506 #[test]
507 fn caused_by_forms_encode_distinctly() {
508 let mut begin = header();
509 begin.caused_by = Some(CausedBy::Begin);
510 let mut multi = header();
511 multi.caused_by = Some(CausedBy::Multiple(alloc::vec![
512 "f1220b".to_string(),
513 "f1220c".to_string(),
514 ]));
515 let mut none = header();
516 none.caused_by = None;
517 let all = [
518 attestation_preimage(&header()),
519 attestation_preimage(&begin),
520 attestation_preimage(&multi),
521 attestation_preimage(&none),
522 ];
523 for i in 0..all.len() {
524 for j in (i + 1)..all.len() {
525 assert_ne!(all[i], all[j], "caused-by forms {i} and {j} collide");
526 }
527 }
528 }
529
530 #[test]
533 fn verify_succeeds_from_header_alone() {
534 let h = header();
535 let sig = sign_attestation_v2(&ALICE, &h).unwrap();
536 assert_eq!(
539 verify_attestation_v2(&ALICE, &key("@alice"), &h, &sig),
540 Ok(())
541 );
542 }
543
544 #[test]
545 fn key_substitution_fails() {
546 let h = header();
547 let sig = sign_attestation_v2(&ALICE, &h).unwrap();
548 assert_eq!(
550 verify_attestation_v2(&ALICE, &key("@bob"), &h, &sig),
551 Err(AttestError::KeyMismatch)
552 );
553 let mut forged = h.clone();
556 forged.from = key("@bob");
557 assert_eq!(
558 verify_attestation_v2(&BOB, &key("@bob"), &forged, &sig),
559 Err(AttestError::InvalidSignature)
560 );
561 }
562
563 #[test]
564 fn hash_substitution_fails() {
565 let h = header();
566 let sig = sign_attestation_v2(&ALICE, &h).unwrap();
567 let mut tampered = h.clone();
568 tampered.content_hash =
569 String::from("f1220cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc");
570 assert_eq!(
571 verify_attestation_v2(&ALICE, &key("@alice"), &tampered, &sig),
572 Err(AttestError::InvalidSignature)
573 );
574 }
575
576 #[test]
577 fn header_field_tampering_fails() {
578 let h = header();
579 let sig = sign_attestation_v2(&ALICE, &h).unwrap();
580
581 let mut perf = h.clone();
582 perf.performative = String::from("commit-bid");
583
584 let mut to_widened = h.clone();
585 to_widened.to.insert(key("@mallory"));
586
587 let mut to_narrowed = h.clone();
588 to_narrowed.to.remove(&key("@carol"));
589
590 let mut thread = h.clone();
591 thread.thread = String::from("conv-8");
592
593 let mut caused = h.clone();
594 caused.caused_by = Some(CausedBy::Single(String::from(
595 "f1220dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd",
596 )));
597
598 let mut caused_dropped = h.clone();
599 caused_dropped.caused_by = None;
600
601 for (label, tampered) in [
602 ("performative", perf),
603 ("to-set widened", to_widened),
604 ("to-set narrowed", to_narrowed),
605 ("thread", thread),
606 ("caused-by rewritten", caused),
607 ("caused-by dropped", caused_dropped),
608 ] {
609 assert_eq!(
610 verify_attestation_v2(&ALICE, &key("@alice"), &tampered, &sig),
611 Err(AttestError::InvalidSignature),
612 "tampered field must fail closed: {label}"
613 );
614 }
615 }
616
617 #[test]
620 fn v1_path_still_verifies_full_bytes() {
621 let bytes = b"(4:Stell4:Q@bob3:Qhi)";
622 let sig = ALICE.sign(bytes);
623 assert_eq!(
624 verify_with_discipline(
625 SignatureDiscipline::V1Full,
626 &SigningInput::V1Full(bytes),
627 &ALICE,
628 &sig
629 ),
630 Ok(())
631 );
632 assert_eq!(
633 verify_with_discipline(
634 SignatureDiscipline::V1Full,
635 &SigningInput::V1Full(b"(other)"),
636 &ALICE,
637 &sig
638 ),
639 Err(AttestError::InvalidSignature)
640 );
641 }
642
643 #[test]
644 fn v2_path_dispatches_through_discipline() {
645 let h = header();
646 let k = key("@alice");
647 let sig = sign_attestation_v2(&ALICE, &h).unwrap();
648 assert_eq!(
649 verify_with_discipline(
650 SignatureDiscipline::V2Attested,
651 &SigningInput::V2Attested {
652 key: &k,
653 header: &h
654 },
655 &ALICE,
656 &sig
657 ),
658 Ok(())
659 );
660 }
661
662 #[test]
666 fn v1_signature_never_satisfies_v2_call() {
667 let h = header();
668 let k = key("@alice");
669 let v1_sig = ALICE.sign(b"(full-message-bytes)");
671 assert_eq!(
672 verify_with_discipline(
673 SignatureDiscipline::V1Full,
674 &SigningInput::V2Attested {
675 key: &k,
676 header: &h
677 },
678 &ALICE,
679 &v1_sig
680 ),
681 Err(AttestError::DisciplineMismatch {
682 marker: SignatureDiscipline::V1Full,
683 input: SignatureDiscipline::V2Attested,
684 })
685 );
686 }
687
688 #[test]
689 fn v2_signature_never_satisfies_v1_call() {
690 let h = header();
691 let sig = sign_attestation_v2(&ALICE, &h).unwrap();
692 assert_eq!(
693 verify_with_discipline(
694 SignatureDiscipline::V2Attested,
695 &SigningInput::V1Full(b"(full-message-bytes)"),
696 &ALICE,
697 &sig
698 ),
699 Err(AttestError::DisciplineMismatch {
700 marker: SignatureDiscipline::V2Attested,
701 input: SignatureDiscipline::V1Full,
702 })
703 );
704 }
705
706 #[test]
707 fn discipline_marker_roundtrip_and_unknown_rejection() {
708 for d in [
709 SignatureDiscipline::V1Full,
710 SignatureDiscipline::V2Attested,
711 SignatureDiscipline::V3Root,
712 ] {
713 assert_eq!(SignatureDiscipline::parse(d.as_str()), Ok(d));
714 }
715 assert_eq!(
716 SignatureDiscipline::parse("v4-guess"),
717 Err(AttestError::UnknownDiscipline("v4-guess".to_string()))
718 );
719 }
720
721 #[test]
724 fn unknown_suite_is_typed_rejection_not_pass_not_panic() {
725 let mut h = header();
726 h.from = key("@pq-frodo:alice");
727 let err = AttestError::UnknownSuite("pq-frodo".to_string());
728 assert_eq!(sign_attestation_v2(&ALICE, &h), Err(err.clone()));
729 assert_eq!(
730 verify_attestation_v2(&ALICE, &key("@pq-frodo:alice"), &h, b"sig"),
731 Err(err)
732 );
733 }
734
735 #[test]
739 fn ed25519_sig_only_verifies_against_ed25519_attestation() {
740 let h = header();
741 let sig = sign_attestation_v2(&ALICE, &h).unwrap();
742 let mut resuited = h.clone();
743 resuited.from = key("@pq-frodo:alice");
744 assert_ne!(
745 attestation_preimage(&h),
746 attestation_preimage(&resuited),
747 "suite must be part of the committed bytes"
748 );
749 assert_eq!(
750 verify_attestation_v2(&ALICE, &key("@pq-frodo:alice"), &resuited, &sig),
751 Err(AttestError::UnknownSuite("pq-frodo".to_string()))
752 );
753 }
754
755 const ROOT: &str = "f12201234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef";
758
759 #[test]
760 fn v3_preimage_is_domain_tagged_and_names_the_suite() {
761 let bytes = attestation_v3_preimage(&SignatureSuite::Ed25519, ROOT);
762 let s = core::str::from_utf8(&bytes).unwrap();
763 assert!(s.starts_with("(15:Scbcl-attest-v3"), "got: {s}");
765 assert!(s.contains("8:Sed25519"), "suite must be committed: {s}");
766 assert!(s.contains(ROOT), "root must be committed: {s}");
768 }
769
770 #[test]
773 fn v3_verify_succeeds_from_suite_and_root_alone() {
774 let sig = sign_attestation_v3(&SignatureSuite::Ed25519, ROOT, &ALICE).unwrap();
775 assert_eq!(
776 verify_attestation_v3(&SignatureSuite::Ed25519, ROOT, &sig, &ALICE),
777 Ok(())
778 );
779 }
780
781 #[test]
782 fn v3_tampered_root_fails() {
783 let sig = sign_attestation_v3(&SignatureSuite::Ed25519, ROOT, &ALICE).unwrap();
784 let other = "f1220ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff";
785 assert_eq!(
786 verify_attestation_v3(&SignatureSuite::Ed25519, other, &sig, &ALICE),
787 Err(AttestError::InvalidSignature)
788 );
789 }
790
791 #[test]
792 fn v3_wrong_key_fails() {
793 let sig = sign_attestation_v3(&SignatureSuite::Ed25519, ROOT, &ALICE).unwrap();
794 assert_eq!(
796 verify_attestation_v3(&SignatureSuite::Ed25519, ROOT, &sig, &BOB),
797 Err(AttestError::InvalidSignature)
798 );
799 }
800
801 #[test]
804 fn v3_unknown_suite_is_typed_rejection() {
805 let pq = SignatureSuite::parse("pq-frodo");
806 let err = AttestError::UnknownSuite("pq-frodo".to_string());
807 assert_eq!(sign_attestation_v3(&pq, ROOT, &ALICE), Err(err.clone()));
808 assert_eq!(verify_attestation_v3(&pq, ROOT, b"sig", &ALICE), Err(err));
809 }
810
811 #[test]
815 fn v3_suite_is_committed_to_preimage() {
816 let ed = attestation_v3_preimage(&SignatureSuite::Ed25519, ROOT);
817 let pq = attestation_v3_preimage(&SignatureSuite::parse("pq-frodo"), ROOT);
818 assert_ne!(ed, pq, "suite must be part of the committed bytes");
819 }
820
821 #[test]
822 fn v3_path_dispatches_through_discipline() {
823 let sig = sign_attestation_v3(&SignatureSuite::Ed25519, ROOT, &ALICE).unwrap();
824 let suite = SignatureSuite::Ed25519;
825 assert_eq!(
826 verify_with_discipline(
827 SignatureDiscipline::V3Root,
828 &SigningInput::V3Root {
829 suite: &suite,
830 root: ROOT
831 },
832 &ALICE,
833 &sig
834 ),
835 Ok(())
836 );
837 }
838
839 #[test]
843 fn v2_signature_never_satisfies_v3_call() {
844 let h = header();
845 let v2_sig = sign_attestation_v2(&ALICE, &h).unwrap();
846 let suite = SignatureSuite::Ed25519;
847 assert_eq!(
848 verify_with_discipline(
849 SignatureDiscipline::V2Attested,
850 &SigningInput::V3Root {
851 suite: &suite,
852 root: ROOT
853 },
854 &ALICE,
855 &v2_sig
856 ),
857 Err(AttestError::DisciplineMismatch {
858 marker: SignatureDiscipline::V2Attested,
859 input: SignatureDiscipline::V3Root,
860 })
861 );
862 }
863
864 #[test]
865 fn v3_signature_never_satisfies_v2_call() {
866 let h = header();
867 let k = key("@alice");
868 let v3_sig = sign_attestation_v3(&SignatureSuite::Ed25519, ROOT, &ALICE).unwrap();
869 assert_eq!(
870 verify_with_discipline(
871 SignatureDiscipline::V3Root,
872 &SigningInput::V2Attested {
873 key: &k,
874 header: &h
875 },
876 &ALICE,
877 &v3_sig
878 ),
879 Err(AttestError::DisciplineMismatch {
880 marker: SignatureDiscipline::V3Root,
881 input: SignatureDiscipline::V2Attested,
882 })
883 );
884 }
885
886 #[test]
888 fn v3_signature_never_satisfies_v1_call() {
889 let v3_sig = sign_attestation_v3(&SignatureSuite::Ed25519, ROOT, &ALICE).unwrap();
890 assert_eq!(
891 verify_with_discipline(
892 SignatureDiscipline::V3Root,
893 &SigningInput::V1Full(b"(full-message-bytes)"),
894 &ALICE,
895 &v3_sig
896 ),
897 Err(AttestError::DisciplineMismatch {
898 marker: SignatureDiscipline::V3Root,
899 input: SignatureDiscipline::V1Full,
900 })
901 );
902 }
903}