Skip to main content

hyprstream_rpc/proof/
recipient_binding.rs

1//! Holder-proof binding for the two untrusted-rendezvous KEM recipients.
2//!
3//! This narrowly scoped source-slice extension is carried in CWT claim
4//! `-70009`; it is required only for deferred Federate admission. Other proof
5//! producers may omit it and retain the generic proof-v1 behavior. The two
6//! hybrid recipients are committed as SHA-256 of canonical
7//! `RecipientPublic::encode()` bytes; legacy `clientDhPublic` is bound as its
8//! exact 32-byte value. Absence is represented explicitly as CBOR null so a
9//! relay cannot add, remove, or replace any forwarded key.
10
11use anyhow::{bail, Result};
12use ciborium::value::Value as CborValue;
13use sha2::{Digest as _, Sha256};
14
15use crate::crypto::hybrid_kem::RecipientPublic;
16
17#[derive(Debug, Clone, PartialEq, Eq)]
18pub struct FederateRecipientBinding {
19    pub response: Option<[u8; 32]>,
20    pub stream: Option<[u8; 32]>,
21    pub client_dh_public: Option<[u8; 32]>,
22}
23
24impl FederateRecipientBinding {
25    pub(crate) fn decode(value: &CborValue) -> Result<Self> {
26        let CborValue::Map(fields) = value else {
27            bail!("federate recipient binding: expected map")
28        };
29        if fields.len() != 3 {
30            bail!("federate recipient binding: expected exactly three fields")
31        }
32        let mut response = None;
33        let mut stream = None;
34        let mut client_dh_public = None;
35        let mut saw_response = false;
36        let mut saw_stream = false;
37        let mut saw_client_dh_public = false;
38        for (key, value) in fields {
39            match key {
40                CborValue::Integer(key) if i128::from(*key) == 1 => {
41                    if saw_response {
42                        bail!("federate recipient binding: duplicate response key")
43                    }
44                    saw_response = true;
45                    response = decode_commitment(value, "response")?;
46                }
47                CborValue::Integer(key) if i128::from(*key) == 2 => {
48                    if saw_stream {
49                        bail!("federate recipient binding: duplicate stream key")
50                    }
51                    saw_stream = true;
52                    stream = decode_commitment(value, "stream")?;
53                }
54                CborValue::Integer(key) if i128::from(*key) == 3 => {
55                    if saw_client_dh_public {
56                        bail!("federate recipient binding: duplicate clientDhPublic key")
57                    }
58                    saw_client_dh_public = true;
59                    client_dh_public = decode_public_key(value, "clientDhPublic")?;
60                }
61                _ => bail!("federate recipient binding: unknown/non-integer key"),
62            }
63        }
64        if !saw_response || !saw_stream || !saw_client_dh_public {
65            bail!("federate recipient binding: missing recipient field")
66        }
67        Ok(Self {
68            response,
69            stream,
70            client_dh_public,
71        })
72    }
73
74    pub fn from_recipients(
75        response: Option<&RecipientPublic>,
76        stream: Option<&RecipientPublic>,
77        client_dh_public: Option<[u8; 32]>,
78    ) -> Result<Self> {
79        Ok(Self {
80            response: response.map(commitment).transpose()?,
81            stream: stream.map(commitment).transpose()?,
82            client_dh_public,
83        })
84    }
85
86    pub fn matches(
87        &self,
88        response: Option<&RecipientPublic>,
89        stream: Option<&RecipientPublic>,
90        client_dh_public: Option<[u8; 32]>,
91    ) -> bool {
92        Self::from_recipients(response, stream, client_dh_public)
93            .is_ok_and(|binding| self == &binding)
94    }
95}
96
97fn decode_public_key(value: &CborValue, name: &str) -> Result<Option<[u8; 32]>> {
98    match value {
99        CborValue::Null => Ok(None),
100        CborValue::Bytes(bytes) if bytes.len() == 32 => {
101            let mut public_key = [0; 32];
102            public_key.copy_from_slice(bytes);
103            Ok(Some(public_key))
104        }
105        CborValue::Bytes(_) => bail!("federate recipient binding: {name} must be 32 bytes"),
106        _ => bail!("federate recipient binding: {name} must be bstr or null"),
107    }
108}
109
110fn decode_commitment(value: &CborValue, name: &str) -> Result<Option<[u8; 32]>> {
111    match value {
112        CborValue::Null => Ok(None),
113        CborValue::Bytes(bytes) if bytes.len() == 32 => {
114            let mut commitment = [0; 32];
115            commitment.copy_from_slice(bytes);
116            Ok(Some(commitment))
117        }
118        CborValue::Bytes(_) => {
119            bail!("federate recipient binding: {name} commitment must be 32 bytes")
120        }
121        _ => bail!("federate recipient binding: {name} commitment must be bstr or null"),
122    }
123}
124
125fn commitment(recipient: &RecipientPublic) -> Result<[u8; 32]> {
126    recipient.validate()?;
127    Ok(Sha256::digest(recipient.encode()).into())
128}
129
130#[cfg(test)]
131mod tests {
132    use super::*;
133    use crate::crypto::hybrid_kem::{generate_recipient, SuiteId};
134
135    #[test]
136    fn recipient_binding_rejects_omitted_and_malformed_fields() {
137        let key = |value: i64| CborValue::Integer(value.into());
138        let omitted_client_dh =
139            CborValue::Map(vec![(key(1), CborValue::Null), (key(2), CborValue::Null)]);
140        assert!(FederateRecipientBinding::decode(&omitted_client_dh).is_err());
141
142        let malformed_client_dh = CborValue::Map(vec![
143            (key(1), CborValue::Null),
144            (key(2), CborValue::Null),
145            (key(3), CborValue::Bytes(vec![0x33; 31])),
146        ]);
147        assert!(FederateRecipientBinding::decode(&malformed_client_dh).is_err());
148    }
149
150    #[test]
151    fn recipient_binding_matches_only_the_forwarded_recipient_set() -> Result<()> {
152        let response = generate_recipient(SuiteId::HyKemX25519MlKem768)?.public();
153        let stream = generate_recipient(SuiteId::HyKemX25519MlKem768)?.public();
154        let replacement = generate_recipient(SuiteId::HyKemX25519MlKem768)?.public();
155        let client_dh = [0x33; 32];
156        let binding = FederateRecipientBinding::from_recipients(
157            Some(&response),
158            Some(&stream),
159            Some(client_dh),
160        )?;
161
162        assert!(binding.matches(Some(&response), Some(&stream), Some(client_dh)));
163        assert!(!binding.matches(Some(&replacement), Some(&stream), Some(client_dh)));
164        assert!(!binding.matches(Some(&response), Some(&replacement), Some(client_dh)));
165        assert!(!binding.matches(None, Some(&stream), Some(client_dh)));
166        assert!(!binding.matches(Some(&response), None, Some(client_dh)));
167        assert!(!binding.matches(Some(&response), Some(&stream), None));
168        assert!(!binding.matches(Some(&response), Some(&stream), Some([0x44; 32])));
169        Ok(())
170    }
171
172    #[test]
173    fn recipient_binding_decodes_only_a_closed_three_field_map() -> Result<()> {
174        let key = |value: i64| CborValue::Integer(value.into());
175        let valid = CborValue::Map(vec![
176            (key(1), CborValue::Bytes(vec![0x11; 32])),
177            (key(2), CborValue::Null),
178            (key(3), CborValue::Bytes(vec![0x33; 32])),
179        ]);
180        assert_eq!(
181            FederateRecipientBinding::decode(&valid)?,
182            FederateRecipientBinding {
183                response: Some([0x11; 32]),
184                stream: None,
185                client_dh_public: Some([0x33; 32]),
186            }
187        );
188
189        let duplicate = CborValue::Map(vec![
190            (key(1), CborValue::Null),
191            (key(1), CborValue::Null),
192            (key(2), CborValue::Null),
193            (key(3), CborValue::Null),
194        ]);
195        assert!(FederateRecipientBinding::decode(&duplicate).is_err());
196
197        let unknown = CborValue::Map(vec![
198            (key(1), CborValue::Null),
199            (key(2), CborValue::Null),
200            (key(4), CborValue::Null),
201        ]);
202        assert!(FederateRecipientBinding::decode(&unknown).is_err());
203
204        let wrong_type = CborValue::Map(vec![
205            (key(1), CborValue::Text("not bytes".into())),
206            (key(2), CborValue::Null),
207            (key(3), CborValue::Null),
208        ]);
209        assert!(FederateRecipientBinding::decode(&wrong_type).is_err());
210        Ok(())
211    }
212}