#![forbid(unsafe_code)]
use crate::canonical::canonical_encode;
use crate::keyid::{KeyId, SignatureSuite};
use crate::message::CausedBy;
use crate::protocol::BEGIN_KEYWORD;
use crate::r4::Signer;
use crate::sexpr::{Atom, SExpr};
use alloc::collections::BTreeSet;
use alloc::string::String;
use alloc::vec::Vec;
use core::fmt;
pub const ATTEST_DOMAIN_TAG: &str = "cbcl-attest-v2";
pub const ATTEST_V3_DOMAIN_TAG: &str = "cbcl-attest-v3";
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct AttestationHeader {
pub content_hash: String,
pub performative: String,
pub from: KeyId,
pub to: BTreeSet<KeyId>,
pub thread: String,
pub caused_by: Option<CausedBy>,
}
pub fn attestation_sexpr(h: &AttestationHeader) -> SExpr {
use alloc::vec;
let mut items = vec![
SExpr::Atom(Atom::Symbol(String::from(ATTEST_DOMAIN_TAG))),
SExpr::Atom(Atom::Symbol(String::from(h.from.suite.as_str()))),
SExpr::Atom(Atom::Symbol(h.content_hash.clone())),
SExpr::Atom(Atom::Symbol(h.performative.clone())),
SExpr::Atom(Atom::Symbol(h.from.canonical_spelling())),
SExpr::List(
h.to.iter()
.map(|k| SExpr::Atom(Atom::Symbol(k.canonical_spelling())))
.collect(),
),
SExpr::Atom(Atom::Str(h.thread.clone())),
];
if let Some(cb) = &h.caused_by {
items.push(match cb {
CausedBy::Begin => SExpr::Atom(Atom::Symbol(String::from(BEGIN_KEYWORD))),
CausedBy::Single(hash) => SExpr::Atom(Atom::Symbol(hash.clone())),
CausedBy::Multiple(hashes) => SExpr::List(
hashes
.iter()
.map(|hash| SExpr::Atom(Atom::Symbol(hash.clone())))
.collect(),
),
});
}
SExpr::List(items)
}
pub fn attestation_preimage(h: &AttestationHeader) -> Vec<u8> {
canonical_encode(&attestation_sexpr(h))
}
pub fn attestation_v3_sexpr(suite: &SignatureSuite, root: &str) -> SExpr {
use alloc::vec;
SExpr::List(vec![
SExpr::Atom(Atom::Symbol(String::from(ATTEST_V3_DOMAIN_TAG))),
SExpr::Atom(Atom::Symbol(String::from(suite.as_str()))),
SExpr::Atom(Atom::Symbol(String::from(root))),
])
}
pub fn attestation_v3_preimage(suite: &SignatureSuite, root: &str) -> Vec<u8> {
canonical_encode(&attestation_v3_sexpr(suite, root))
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum SignatureDiscipline {
V1Full,
V2Attested,
V3Root,
}
impl SignatureDiscipline {
pub fn as_str(&self) -> &'static str {
match self {
SignatureDiscipline::V1Full => "v1",
SignatureDiscipline::V2Attested => ATTEST_DOMAIN_TAG,
SignatureDiscipline::V3Root => ATTEST_V3_DOMAIN_TAG,
}
}
pub fn parse(s: &str) -> Result<Self, AttestError> {
match s {
"v1" => Ok(SignatureDiscipline::V1Full),
ATTEST_DOMAIN_TAG => Ok(SignatureDiscipline::V2Attested),
ATTEST_V3_DOMAIN_TAG => Ok(SignatureDiscipline::V3Root),
other => Err(AttestError::UnknownDiscipline(String::from(other))),
}
}
}
impl fmt::Display for SignatureDiscipline {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum AttestError {
UnknownSuite(String),
UnknownDiscipline(String),
DisciplineMismatch {
marker: SignatureDiscipline,
input: SignatureDiscipline,
},
KeyMismatch,
InvalidSignature,
}
impl fmt::Display for AttestError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
AttestError::UnknownSuite(s) => write!(f, "unknown signature suite '{s}'"),
AttestError::UnknownDiscipline(s) => {
write!(f, "unknown signature discipline marker '{s}'")
}
AttestError::DisciplineMismatch { marker, input } => write!(
f,
"signature discipline mismatch: signature declares '{marker}', \
verification input requires '{input}'"
),
AttestError::KeyMismatch => f.write_str("key does not match attestation's from key"),
AttestError::InvalidSignature => f.write_str("signature verification failed"),
}
}
}
pub fn sign_attestation_v2(
signer: &dyn Signer,
header: &AttestationHeader,
) -> Result<Vec<u8>, AttestError> {
match &header.from.suite {
SignatureSuite::Ed25519 => Ok(signer.sign(&attestation_preimage(header))),
SignatureSuite::Other(s) => Err(AttestError::UnknownSuite(s.clone())),
}
}
pub fn verify_attestation_v2(
signer: &dyn Signer,
key: &KeyId,
header: &AttestationHeader,
sig: &[u8],
) -> Result<(), AttestError> {
if let SignatureSuite::Other(s) = &header.from.suite {
return Err(AttestError::UnknownSuite(s.clone()));
}
if let SignatureSuite::Other(s) = &key.suite {
return Err(AttestError::UnknownSuite(s.clone()));
}
if key != &header.from {
return Err(AttestError::KeyMismatch);
}
if signer.verify(&attestation_preimage(header), sig) {
Ok(())
} else {
Err(AttestError::InvalidSignature)
}
}
pub fn sign_attestation_v3(
suite: &SignatureSuite,
root: &str,
signer: &dyn Signer,
) -> Result<Vec<u8>, AttestError> {
match suite {
SignatureSuite::Ed25519 => Ok(signer.sign(&attestation_v3_preimage(suite, root))),
SignatureSuite::Other(s) => Err(AttestError::UnknownSuite(s.clone())),
}
}
pub fn verify_attestation_v3(
suite: &SignatureSuite,
root: &str,
sig: &[u8],
signer: &dyn Signer,
) -> Result<(), AttestError> {
if let SignatureSuite::Other(s) = suite {
return Err(AttestError::UnknownSuite(s.clone()));
}
if signer.verify(&attestation_v3_preimage(suite, root), sig) {
Ok(())
} else {
Err(AttestError::InvalidSignature)
}
}
#[derive(Debug, Clone, Copy)]
pub enum SigningInput<'a> {
V1Full(&'a [u8]),
V2Attested {
key: &'a KeyId,
header: &'a AttestationHeader,
},
V3Root {
suite: &'a SignatureSuite,
root: &'a str,
},
}
impl SigningInput<'_> {
pub fn discipline(&self) -> SignatureDiscipline {
match self {
SigningInput::V1Full(_) => SignatureDiscipline::V1Full,
SigningInput::V2Attested { .. } => SignatureDiscipline::V2Attested,
SigningInput::V3Root { .. } => SignatureDiscipline::V3Root,
}
}
}
pub fn verify_with_discipline(
marker: SignatureDiscipline,
input: &SigningInput<'_>,
signer: &dyn Signer,
sig: &[u8],
) -> Result<(), AttestError> {
match (marker, input) {
(SignatureDiscipline::V1Full, SigningInput::V1Full(bytes)) => {
if signer.verify(bytes, sig) {
Ok(())
} else {
Err(AttestError::InvalidSignature)
}
}
(SignatureDiscipline::V2Attested, SigningInput::V2Attested { key, header }) => {
verify_attestation_v2(signer, key, header, sig)
}
(SignatureDiscipline::V3Root, SigningInput::V3Root { suite, root }) => {
verify_attestation_v3(suite, root, sig, signer)
}
(marker, input) => Err(AttestError::DisciplineMismatch {
marker,
input: input.discipline(),
}),
}
}
#[cfg(test)]
mod tests {
use super::*;
use alloc::string::ToString;
use alloc::vec::Vec;
struct TestSigner {
secret: &'static [u8],
}
impl Signer for TestSigner {
fn sign(&self, data: &[u8]) -> Vec<u8> {
use sha2::{Digest, Sha256};
let mut h = Sha256::new();
h.update(self.secret);
h.update(data);
h.finalize().to_vec()
}
fn verify(&self, data: &[u8], sig: &[u8]) -> bool {
self.sign(data) == sig
}
}
const ALICE: TestSigner = TestSigner { secret: b"alice" };
const BOB: TestSigner = TestSigner { secret: b"bob" };
fn key(s: &str) -> KeyId {
KeyId::parse(s).unwrap()
}
fn header() -> AttestationHeader {
let mut to = BTreeSet::new();
to.insert(key("@bob"));
to.insert(key("@carol"));
AttestationHeader {
content_hash: String::from(
"f1220aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
),
performative: String::from("reveal-bid"),
from: key("@alice"),
to,
thread: String::from("conv-7"),
caused_by: Some(CausedBy::Single(String::from(
"f1220bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
))),
}
}
#[test]
fn preimage_is_domain_tagged_and_names_the_suite() {
let bytes = attestation_preimage(&header());
let s = core::str::from_utf8(&bytes).unwrap();
assert!(s.starts_with("(15:Scbcl-attest-v2"), "got: {s}");
assert!(s.contains("8:Sed25519"), "suite must be committed: {s}");
}
#[test]
fn preimage_is_deterministic_across_reconstruction() {
assert_eq!(
attestation_preimage(&header()),
attestation_preimage(&header())
);
}
#[test]
fn alias_key_spellings_reconstruct_identical_preimage() {
let mut explicit = header();
explicit.from = key("@ed25519:alice");
assert_eq!(
attestation_preimage(&header()),
attestation_preimage(&explicit)
);
}
#[test]
fn caused_by_forms_encode_distinctly() {
let mut begin = header();
begin.caused_by = Some(CausedBy::Begin);
let mut multi = header();
multi.caused_by = Some(CausedBy::Multiple(alloc::vec![
"f1220b".to_string(),
"f1220c".to_string(),
]));
let mut none = header();
none.caused_by = None;
let all = [
attestation_preimage(&header()),
attestation_preimage(&begin),
attestation_preimage(&multi),
attestation_preimage(&none),
];
for i in 0..all.len() {
for j in (i + 1)..all.len() {
assert_ne!(all[i], all[j], "caused-by forms {i} and {j} collide");
}
}
}
#[test]
fn verify_succeeds_from_header_alone() {
let h = header();
let sig = sign_attestation_v2(&ALICE, &h).unwrap();
assert_eq!(
verify_attestation_v2(&ALICE, &key("@alice"), &h, &sig),
Ok(())
);
}
#[test]
fn key_substitution_fails() {
let h = header();
let sig = sign_attestation_v2(&ALICE, &h).unwrap();
assert_eq!(
verify_attestation_v2(&ALICE, &key("@bob"), &h, &sig),
Err(AttestError::KeyMismatch)
);
let mut forged = h.clone();
forged.from = key("@bob");
assert_eq!(
verify_attestation_v2(&BOB, &key("@bob"), &forged, &sig),
Err(AttestError::InvalidSignature)
);
}
#[test]
fn hash_substitution_fails() {
let h = header();
let sig = sign_attestation_v2(&ALICE, &h).unwrap();
let mut tampered = h.clone();
tampered.content_hash =
String::from("f1220cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc");
assert_eq!(
verify_attestation_v2(&ALICE, &key("@alice"), &tampered, &sig),
Err(AttestError::InvalidSignature)
);
}
#[test]
fn header_field_tampering_fails() {
let h = header();
let sig = sign_attestation_v2(&ALICE, &h).unwrap();
let mut perf = h.clone();
perf.performative = String::from("commit-bid");
let mut to_widened = h.clone();
to_widened.to.insert(key("@mallory"));
let mut to_narrowed = h.clone();
to_narrowed.to.remove(&key("@carol"));
let mut thread = h.clone();
thread.thread = String::from("conv-8");
let mut caused = h.clone();
caused.caused_by = Some(CausedBy::Single(String::from(
"f1220dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd",
)));
let mut caused_dropped = h.clone();
caused_dropped.caused_by = None;
for (label, tampered) in [
("performative", perf),
("to-set widened", to_widened),
("to-set narrowed", to_narrowed),
("thread", thread),
("caused-by rewritten", caused),
("caused-by dropped", caused_dropped),
] {
assert_eq!(
verify_attestation_v2(&ALICE, &key("@alice"), &tampered, &sig),
Err(AttestError::InvalidSignature),
"tampered field must fail closed: {label}"
);
}
}
#[test]
fn v1_path_still_verifies_full_bytes() {
let bytes = b"(4:Stell4:Q@bob3:Qhi)";
let sig = ALICE.sign(bytes);
assert_eq!(
verify_with_discipline(
SignatureDiscipline::V1Full,
&SigningInput::V1Full(bytes),
&ALICE,
&sig
),
Ok(())
);
assert_eq!(
verify_with_discipline(
SignatureDiscipline::V1Full,
&SigningInput::V1Full(b"(other)"),
&ALICE,
&sig
),
Err(AttestError::InvalidSignature)
);
}
#[test]
fn v2_path_dispatches_through_discipline() {
let h = header();
let k = key("@alice");
let sig = sign_attestation_v2(&ALICE, &h).unwrap();
assert_eq!(
verify_with_discipline(
SignatureDiscipline::V2Attested,
&SigningInput::V2Attested {
key: &k,
header: &h
},
&ALICE,
&sig
),
Ok(())
);
}
#[test]
fn v1_signature_never_satisfies_v2_call() {
let h = header();
let k = key("@alice");
let v1_sig = ALICE.sign(b"(full-message-bytes)");
assert_eq!(
verify_with_discipline(
SignatureDiscipline::V1Full,
&SigningInput::V2Attested {
key: &k,
header: &h
},
&ALICE,
&v1_sig
),
Err(AttestError::DisciplineMismatch {
marker: SignatureDiscipline::V1Full,
input: SignatureDiscipline::V2Attested,
})
);
}
#[test]
fn v2_signature_never_satisfies_v1_call() {
let h = header();
let sig = sign_attestation_v2(&ALICE, &h).unwrap();
assert_eq!(
verify_with_discipline(
SignatureDiscipline::V2Attested,
&SigningInput::V1Full(b"(full-message-bytes)"),
&ALICE,
&sig
),
Err(AttestError::DisciplineMismatch {
marker: SignatureDiscipline::V2Attested,
input: SignatureDiscipline::V1Full,
})
);
}
#[test]
fn discipline_marker_roundtrip_and_unknown_rejection() {
for d in [
SignatureDiscipline::V1Full,
SignatureDiscipline::V2Attested,
SignatureDiscipline::V3Root,
] {
assert_eq!(SignatureDiscipline::parse(d.as_str()), Ok(d));
}
assert_eq!(
SignatureDiscipline::parse("v4-guess"),
Err(AttestError::UnknownDiscipline("v4-guess".to_string()))
);
}
#[test]
fn unknown_suite_is_typed_rejection_not_pass_not_panic() {
let mut h = header();
h.from = key("@pq-frodo:alice");
let err = AttestError::UnknownSuite("pq-frodo".to_string());
assert_eq!(sign_attestation_v2(&ALICE, &h), Err(err.clone()));
assert_eq!(
verify_attestation_v2(&ALICE, &key("@pq-frodo:alice"), &h, b"sig"),
Err(err)
);
}
#[test]
fn ed25519_sig_only_verifies_against_ed25519_attestation() {
let h = header();
let sig = sign_attestation_v2(&ALICE, &h).unwrap();
let mut resuited = h.clone();
resuited.from = key("@pq-frodo:alice");
assert_ne!(
attestation_preimage(&h),
attestation_preimage(&resuited),
"suite must be part of the committed bytes"
);
assert_eq!(
verify_attestation_v2(&ALICE, &key("@pq-frodo:alice"), &resuited, &sig),
Err(AttestError::UnknownSuite("pq-frodo".to_string()))
);
}
const ROOT: &str = "f12201234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef";
#[test]
fn v3_preimage_is_domain_tagged_and_names_the_suite() {
let bytes = attestation_v3_preimage(&SignatureSuite::Ed25519, ROOT);
let s = core::str::from_utf8(&bytes).unwrap();
assert!(s.starts_with("(15:Scbcl-attest-v3"), "got: {s}");
assert!(s.contains("8:Sed25519"), "suite must be committed: {s}");
assert!(s.contains(ROOT), "root must be committed: {s}");
}
#[test]
fn v3_verify_succeeds_from_suite_and_root_alone() {
let sig = sign_attestation_v3(&SignatureSuite::Ed25519, ROOT, &ALICE).unwrap();
assert_eq!(
verify_attestation_v3(&SignatureSuite::Ed25519, ROOT, &sig, &ALICE),
Ok(())
);
}
#[test]
fn v3_tampered_root_fails() {
let sig = sign_attestation_v3(&SignatureSuite::Ed25519, ROOT, &ALICE).unwrap();
let other = "f1220ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff";
assert_eq!(
verify_attestation_v3(&SignatureSuite::Ed25519, other, &sig, &ALICE),
Err(AttestError::InvalidSignature)
);
}
#[test]
fn v3_wrong_key_fails() {
let sig = sign_attestation_v3(&SignatureSuite::Ed25519, ROOT, &ALICE).unwrap();
assert_eq!(
verify_attestation_v3(&SignatureSuite::Ed25519, ROOT, &sig, &BOB),
Err(AttestError::InvalidSignature)
);
}
#[test]
fn v3_unknown_suite_is_typed_rejection() {
let pq = SignatureSuite::parse("pq-frodo");
let err = AttestError::UnknownSuite("pq-frodo".to_string());
assert_eq!(sign_attestation_v3(&pq, ROOT, &ALICE), Err(err.clone()));
assert_eq!(verify_attestation_v3(&pq, ROOT, b"sig", &ALICE), Err(err));
}
#[test]
fn v3_suite_is_committed_to_preimage() {
let ed = attestation_v3_preimage(&SignatureSuite::Ed25519, ROOT);
let pq = attestation_v3_preimage(&SignatureSuite::parse("pq-frodo"), ROOT);
assert_ne!(ed, pq, "suite must be part of the committed bytes");
}
#[test]
fn v3_path_dispatches_through_discipline() {
let sig = sign_attestation_v3(&SignatureSuite::Ed25519, ROOT, &ALICE).unwrap();
let suite = SignatureSuite::Ed25519;
assert_eq!(
verify_with_discipline(
SignatureDiscipline::V3Root,
&SigningInput::V3Root {
suite: &suite,
root: ROOT
},
&ALICE,
&sig
),
Ok(())
);
}
#[test]
fn v2_signature_never_satisfies_v3_call() {
let h = header();
let v2_sig = sign_attestation_v2(&ALICE, &h).unwrap();
let suite = SignatureSuite::Ed25519;
assert_eq!(
verify_with_discipline(
SignatureDiscipline::V2Attested,
&SigningInput::V3Root {
suite: &suite,
root: ROOT
},
&ALICE,
&v2_sig
),
Err(AttestError::DisciplineMismatch {
marker: SignatureDiscipline::V2Attested,
input: SignatureDiscipline::V3Root,
})
);
}
#[test]
fn v3_signature_never_satisfies_v2_call() {
let h = header();
let k = key("@alice");
let v3_sig = sign_attestation_v3(&SignatureSuite::Ed25519, ROOT, &ALICE).unwrap();
assert_eq!(
verify_with_discipline(
SignatureDiscipline::V3Root,
&SigningInput::V2Attested {
key: &k,
header: &h
},
&ALICE,
&v3_sig
),
Err(AttestError::DisciplineMismatch {
marker: SignatureDiscipline::V3Root,
input: SignatureDiscipline::V2Attested,
})
);
}
#[test]
fn v3_signature_never_satisfies_v1_call() {
let v3_sig = sign_attestation_v3(&SignatureSuite::Ed25519, ROOT, &ALICE).unwrap();
assert_eq!(
verify_with_discipline(
SignatureDiscipline::V3Root,
&SigningInput::V1Full(b"(full-message-bytes)"),
&ALICE,
&v3_sig
),
Err(AttestError::DisciplineMismatch {
marker: SignatureDiscipline::V3Root,
input: SignatureDiscipline::V1Full,
})
);
}
}