Skip to main content

hyprstream_rpc/proof/
thumbprint.rs

1//! Frozen CDDL §7.1 replay namespace derivation. The preimages contain only
2//! arrays, text, byte strings and unsigned integers, encoded deterministically.
3
4use anyhow::{bail, Result};
5use ciborium::Value;
6use sha2::{Digest, Sha256};
7
8use super::{
9    plan::SignaturePlan, ALG_ED25519, HEADER_HS_SIGNATURE_PLAN, HEADER_HS_UNATTRIBUTED_KEY_SET,
10    MAX_COSE_OBJECT_BYTES,
11};
12
13const AUTHENTICATED_DOMAIN: &str = "hs-rpc-replay-primary-suite-v1";
14const KEY_SET_DOMAIN: &str = "hs-rpc-replay-key-set-v1";
15
16type GroupContent = (String, Vec<Vec<u8>>);
17
18// Infallible encoding of the restricted preimage grammar avoids changing the
19// enrolled-record API into a fallible serializer. All lengths are definite;
20// the argument always uses its shortest encoding (RFC 8949 §4.2.1).
21fn head(out: &mut Vec<u8>, major: u8, n: u64) {
22    let tag = major << 5;
23    match n {
24        0..=23 => out.push(tag | n as u8),
25        24..=0xff => out.extend_from_slice(&[tag | 24, n as u8]),
26        0x100..=0xffff => {
27            out.push(tag | 25);
28            out.extend_from_slice(&(n as u16).to_be_bytes());
29        }
30        0x10000..=0xffffffff => {
31            out.push(tag | 26);
32            out.extend_from_slice(&(n as u32).to_be_bytes());
33        }
34        _ => {
35            out.push(tag | 27);
36            out.extend_from_slice(&n.to_be_bytes());
37        }
38    }
39}
40
41fn text(out: &mut Vec<u8>, value: &str) {
42    head(out, 3, value.len() as u64);
43    out.extend_from_slice(value.as_bytes());
44}
45
46fn keys(out: &mut Vec<u8>, public_keys: &[Vec<u8>]) {
47    head(out, 4, public_keys.len() as u64);
48    for key in public_keys {
49        head(out, 2, key.len() as u64);
50        out.extend_from_slice(key);
51    }
52}
53
54pub(super) fn authenticated(suite: &str, public_keys: &[Vec<u8>], epoch: u64) -> [u8; 32] {
55    Sha256::digest(authenticated_preimage(suite, public_keys, epoch)).into()
56}
57
58fn authenticated_preimage(suite: &str, public_keys: &[Vec<u8>], epoch: u64) -> Vec<u8> {
59    let mut out = Vec::new();
60    head(&mut out, 4, 4);
61    text(&mut out, AUTHENTICATED_DOMAIN);
62    text(&mut out, suite);
63    keys(&mut out, public_keys);
64    head(&mut out, 0, epoch);
65    out
66}
67
68fn key_set_preimage(groups: &[GroupContent]) -> Vec<u8> {
69    let mut records = groups
70        .iter()
71        .map(|(suite, public_keys)| {
72            let mut record = Vec::new();
73            head(&mut record, 4, 2);
74            text(&mut record, suite);
75            keys(&mut record, public_keys);
76            record
77        })
78        .collect::<Vec<_>>();
79    // Byte-sort canonical records, never group_id/kid/plan positions. Preserve
80    // duplicate records: the namespace binds a multiset, not a deduplicated set.
81    records.sort();
82    let mut out = Vec::new();
83    head(&mut out, 4, 2);
84    text(&mut out, KEY_SET_DOMAIN);
85    head(&mut out, 4, records.len() as u64);
86    for record in records {
87        out.extend_from_slice(&record);
88    }
89    out
90}
91
92fn key_set(groups: &[GroupContent]) -> [u8; 32] {
93    Sha256::digest(key_set_preimage(groups)).into()
94}
95
96fn field(value: &Value, label: i64) -> Result<&Value> {
97    let Value::Map(map) = value else {
98        bail!("thumbprint: expected map");
99    };
100    map.iter()
101        .find_map(|(k, v)| match k {
102            Value::Integer(i) if i128::from(*i) == i128::from(label) => Some(v),
103            _ => None,
104        })
105        .ok_or_else(|| anyhow::anyhow!("thumbprint: missing label {label}"))
106}
107
108fn content_groups(plan: &SignaturePlan, key_set: &Value) -> Result<Vec<GroupContent>> {
109    let Value::Array(entries) = key_set else {
110        bail!("thumbprint: key set must be array");
111    };
112    plan.groups.iter().map(|group| {
113        let public_keys = group.components.iter().map(|component| {
114            let key = entries.iter().find(|key| {
115                matches!(field(key, 2), Ok(Value::Bytes(kid)) if *kid == component.kid)
116                    && matches!(field(key, 3), Ok(Value::Integer(alg)) if i128::from(*alg) == i128::from(component.alg))
117            }).ok_or_else(|| anyhow::anyhow!("thumbprint: missing component key"))?;
118            let label = if component.alg == ALG_ED25519 { -2 } else { -1 };
119            match field(key, label)? {
120                Value::Bytes(bytes) => Ok(bytes.clone()),
121                _ => bail!("thumbprint: public key must be bytes"),
122            }
123        }).collect::<Result<Vec<_>>>()?;
124        Ok((group.suite_id.clone(), public_keys))
125    }).collect()
126}
127
128pub(super) fn unattributed(protected_bytes: &[u8]) -> Result<[u8; 32]> {
129    if protected_bytes.len() > MAX_COSE_OBJECT_BYTES {
130        bail!("thumbprint: protected header exceeds proof size cap");
131    }
132    // Public callers do not necessarily come through ParsedProof. Audit before
133    // deserialization for bounded nesting, unique canonical map keys and no
134    // trailing data, then apply the same plan/key-set acceptance rules.
135    super::cbor_audit::audit_deterministic(protected_bytes)?;
136    let protected: Value = ciborium::de::from_reader(protected_bytes)?;
137    let plan = SignaturePlan::decode(field(&protected, HEADER_HS_SIGNATURE_PLAN)?)?;
138    let key_set_value = field(&protected, HEADER_HS_UNATTRIBUTED_KEY_SET)?;
139    super::parser::validate_unattributed_key_set(key_set_value, &plan)?;
140    Ok(key_set(&content_groups(&plan, key_set_value)?))
141}
142
143#[cfg(test)]
144mod tests {
145    use super::super::{
146        admission,
147        enrollment::{ComponentKey, EnrolledComponent, SignerRole, SignerSuiteRecord},
148        parser::ParsedProof,
149        SUITE_CLASSICAL, SUITE_HYBRID,
150    };
151    use super::*;
152
153    fn vectors() -> Result<serde_json::Value> {
154        Ok(serde_json::from_str(include_str!(
155            "../../../../docs/standards/v16/vectors/proof-v1-thumbprints.json"
156        ))?)
157    }
158    fn bytes(v: &serde_json::Value, name: &str) -> Result<Vec<u8>> {
159        Ok(hex::decode(v[name].as_str().ok_or_else(|| {
160            anyhow::anyhow!("missing fixture {name}")
161        })?)?)
162    }
163    fn encoded(v: &Value) -> Result<Vec<u8>> {
164        let mut out = Vec::new();
165        ciborium::ser::into_writer(v, &mut out)?;
166        Ok(out)
167    }
168    fn protected(wire: &[u8]) -> Result<Vec<u8>> {
169        let Value::Array(object) = ciborium::de::from_reader(wire)? else {
170            bail!("fixture object");
171        };
172        let Some(Value::Bytes(header)) = object.first() else {
173            bail!("fixture header");
174        };
175        Ok(header.clone())
176    }
177    fn field_mut(value: &mut Value, label: i64) -> Result<&mut Value> {
178        let Value::Map(map) = value else {
179            bail!("fixture map");
180        };
181        map.iter_mut()
182            .find_map(|(key, value)| match key {
183                Value::Integer(i) if i128::from(*i) == i128::from(label) => Some(value),
184                _ => None,
185            })
186            .ok_or_else(|| anyhow::anyhow!("missing fixture label"))
187    }
188    fn array_mut(v: &mut Value) -> Result<&mut Vec<Value>> {
189        match v {
190            Value::Array(a) => Ok(a),
191            _ => bail!("fixture array"),
192        }
193    }
194
195    #[test]
196    fn replay_thumbprint_authenticated_matches_frozen_vector() -> Result<()> {
197        let fixture = vectors()?;
198        let vector = &fixture["authenticated"];
199        let public_keys = vector["component_public_keys_hex"]
200            .as_array()
201            .ok_or_else(|| anyhow::anyhow!("fixture keys"))?
202            .iter()
203            .map(|key| {
204                Ok(hex::decode(
205                    key.as_str().ok_or_else(|| anyhow::anyhow!("fixture hex"))?,
206                )?)
207            })
208            .collect::<Result<Vec<_>>>()?;
209        let ed: [u8; 32] = public_keys[0].as_slice().try_into()?;
210        let record = SignerSuiteRecord {
211            principal: "fixture-primary".into(),
212            suite_id: SUITE_HYBRID.into(),
213            components: vec![
214                EnrolledComponent::new(
215                    b"ed".to_vec(),
216                    ComponentKey::Ed25519(ed25519_dalek::VerifyingKey::from_bytes(&ed)?),
217                ),
218                EnrolledComponent::new(
219                    b"pq".to_vec(),
220                    ComponentKey::MlDsa65(Box::new(crate::crypto::pq::ml_dsa_vk_from_bytes(
221                        &public_keys[1],
222                    )?)),
223                ),
224            ],
225            epoch: 1,
226            role: SignerRole::Primary,
227            approver_role: None,
228            enrollment_policy_id: "fixture".into(),
229            not_after: u64::MAX,
230            revoked: false,
231        };
232        assert_eq!(
233            authenticated_preimage(&record.suite_id, &public_keys, record.epoch),
234            bytes(vector, "preimage_hex")?
235        );
236        assert_eq!(
237            record.replay_thumbprint().as_slice(),
238            bytes(vector, "thumbprint_sha256")?
239        );
240        let mut renamed = record.clone();
241        renamed.principal = "other-label".into();
242        renamed.components[0].kid = b"other-kid".to_vec();
243        assert_eq!(record.replay_thumbprint(), renamed.replay_thumbprint());
244        renamed.epoch += 1;
245        assert_ne!(record.replay_thumbprint(), renamed.replay_thumbprint());
246        let mut reversed = record.clone();
247        reversed.components.reverse();
248        assert_ne!(record.replay_thumbprint(), reversed.replay_thumbprint());
249        Ok(())
250    }
251
252    #[test]
253    fn replay_thumbprint_public_helpers_match_vector_and_m1_labels() -> Result<()> {
254        let fixture = vectors()?;
255        let (_, wire) = super::super::tests::load_positive_vectors()
256            .into_iter()
257            .find(|(id, _)| id == "P-1")
258            .ok_or_else(|| anyhow::anyhow!("P-1"))?;
259        let original = ParsedProof::parse(&wire)?;
260        let expected = bytes(&fixture["unattributed"], "thumbprint_sha256")?;
261        assert_eq!(
262            original
263                .unattributed_replay_thumbprint()
264                .ok_or_else(|| anyhow::anyhow!("thumbprint"))?
265                .as_slice(),
266            expected
267        );
268        assert_eq!(
269            admission::unattributed_thumbprint(&original.protected_bytes)?.as_slice(),
270            expected
271        );
272        // Structural parser/helper tests: relabel headers consistently. Signatures
273        // are not re-signed or admitted; this only checks namespace derivation.
274        for change_group in [true, false] {
275            let mut object: Value = ciborium::de::from_reader(wire.as_slice())?;
276            let mut header: Value = ciborium::de::from_reader(original.protected_bytes.as_slice())?;
277            if change_group {
278                let plan = array_mut(field_mut(&mut header, HEADER_HS_SIGNATURE_PLAN)?)?;
279                *field_mut(&mut plan[0], 1)? = Value::Integer(77.into());
280                *field_mut(&mut header, super::super::HEADER_HS_LOGICAL_SIGNER_GROUP)? =
281                    Value::Integer(77.into());
282            } else {
283                let kid = Value::Bytes(b"renamed-key".to_vec());
284                let plan = array_mut(field_mut(&mut header, HEADER_HS_SIGNATURE_PLAN)?)?;
285                let components = array_mut(field_mut(&mut plan[0], 3)?)?;
286                *field_mut(&mut components[0], 2)? = kid.clone();
287                let entries = array_mut(field_mut(&mut header, HEADER_HS_UNATTRIBUTED_KEY_SET)?)?;
288                *field_mut(&mut entries[0], 2)? = kid.clone();
289                *field_mut(&mut header, 4)? = kid;
290            }
291            array_mut(&mut object)?[0] = Value::Bytes(encoded(&header)?);
292            let parsed = ParsedProof::parse(&encoded(&object)?)?;
293            assert_eq!(
294                parsed.unattributed_replay_thumbprint(),
295                original.unattributed_replay_thumbprint()
296            );
297            assert_eq!(
298                admission::unattributed_thumbprint(&parsed.protected_bytes)?.as_slice(),
299                expected
300            );
301        }
302        let mut header: Value = ciborium::de::from_reader(original.protected_bytes.as_slice())?;
303        let entries = array_mut(field_mut(&mut header, HEADER_HS_UNATTRIBUTED_KEY_SET)?)?;
304        let Value::Bytes(key) = field_mut(&mut entries[0], -2)? else {
305            bail!("fixture key");
306        };
307        key[0] ^= 1;
308        assert_ne!(
309            admission::unattributed_thumbprint(&encoded(&header)?)?.as_slice(),
310            expected
311        );
312        assert!(admission::unattributed_thumbprint(&vec![0; MAX_COSE_OBJECT_BYTES + 1]).is_err());
313        let mut trailing = original.protected_bytes.clone();
314        trailing.push(0);
315        assert!(admission::unattributed_thumbprint(&trailing).is_err());
316        Ok(())
317    }
318
319    #[test]
320    fn replay_thumbprint_r1_vector_order_and_multiset_distinctions() -> Result<()> {
321        let fixture = vectors()?;
322        let mut canonical = Vec::new();
323        for name in ["order_ab", "order_ba"] {
324            let vector = &fixture["group_order_canonicalization"][name];
325            let wire = bytes(vector, "cbor_hex")?;
326            let header_bytes = protected(&wire)?;
327            let header: Value = ciborium::de::from_reader(header_bytes.as_slice())?;
328            let plan = SignaturePlan::decode(field(&header, HEADER_HS_SIGNATURE_PLAN)?)?;
329            let groups = content_groups(&plan, field(&header, HEADER_HS_UNATTRIBUTED_KEY_SET)?)?;
330            assert_eq!(key_set_preimage(&groups), bytes(vector, "preimage_hex")?);
331            assert_eq!(
332                key_set(&groups).as_slice(),
333                bytes(vector, "thumbprint_sha256")?
334            );
335            // R1's derivation is exercised without widening the existing
336            // public one-group unattributed proof support for this repair.
337            assert!(ParsedProof::parse(&wire).is_err());
338            assert!(admission::unattributed_thumbprint(&header_bytes).is_err());
339            canonical.push(key_set(&groups));
340            assert_ne!(key_set(&groups), key_set(&groups[..1]));
341            let mut duplicate = groups.clone();
342            duplicate.push(groups[0].clone());
343            assert_ne!(key_set(&groups), key_set(&duplicate));
344            let mut changed = groups.clone();
345            changed[0].1[0][0] ^= 1;
346            assert_ne!(key_set(&groups), key_set(&changed));
347        }
348        assert_eq!(canonical[0], canonical[1]);
349        let classical = vec![(SUITE_CLASSICAL.to_owned(), vec![vec![1; 32]])];
350        let hybrid = vec![(SUITE_HYBRID.to_owned(), vec![vec![1; 32], vec![2; 1952]])];
351        assert_ne!(key_set(&classical), key_set(&hybrid));
352        let mut reversed = hybrid.clone();
353        reversed[0].1.reverse();
354        assert_ne!(key_set(&hybrid), key_set(&reversed));
355        Ok(())
356    }
357}