Skip to main content

hyprstream_rpc/proof/
response.rs

1//! Response binding types — the client's commitment to how the response must
2//! be produced.
3//!
4//! In a request proof the map is the client's commitment. It is `null` when
5//! the response is neither encrypted nor streamed. In a response proof it is
6//! the realized binding and MUST equal the request's map where both are
7//! present.
8//!
9//! Gate-2 amendments 3 + 4 make the two dimensions orthogonal and the map
10//! four-field: `{1: root_type_id, 2: response_kind, 3: protection_mode,
11//! 4: kem_recipient-or-null}`, with `response_kind = {1: unary, 2: stream_setup}`
12//! and `protection_mode = {1: cleartext, 2: encrypted}`. The KEM recipient is
13//! non-null iff `protection_mode == encrypted`, independent of `response_kind`.
14//! The cleartext MAP alternative is stream_setup-only: a cleartext unary
15//! response is neither encrypted nor streamed and is encoded as a null
16//! `response_binding`, never a map (canonical vector N-27).
17
18use anyhow::{bail, Result};
19use ciborium::value::Value as CborValue;
20
21use super::ALG_ML_KEM_768;
22
23/// How the response is delivered (Gate-2 amendment 4, axis 1).
24#[derive(Debug, Clone, Copy, PartialEq, Eq)]
25pub enum ResponseKind {
26    /// A single unary response.
27    Unary,
28    /// A stream is set up.
29    StreamSetup,
30}
31
32impl ResponseKind {
33    fn from_u64(v: u64) -> Result<Self> {
34        match v {
35            1 => Ok(Self::Unary),
36            2 => Ok(Self::StreamSetup),
37            _ => bail!("response_kind: invalid value {v}"),
38        }
39    }
40}
41
42/// Whether the response is encrypted (Gate-2 amendment 4, axis 2). Orthogonal
43/// to [`ResponseKind`].
44#[derive(Debug, Clone, Copy, PartialEq, Eq)]
45pub enum ProtectionMode {
46    /// Response bytes are cleartext.
47    Cleartext,
48    /// Response bytes are encrypted to the carried KEM recipient.
49    Encrypted,
50}
51
52impl ProtectionMode {
53    fn from_u64(v: u64) -> Result<Self> {
54        match v {
55            1 => Ok(Self::Cleartext),
56            2 => Ok(Self::Encrypted),
57            _ => bail!("protection_mode: invalid value {v}"),
58        }
59    }
60}
61
62/// ML-KEM-768 recipient material for an encrypted response.
63#[derive(Debug, Clone, PartialEq, Eq)]
64pub struct KemRecipient {
65    /// COSE KEM algorithm identifier — exactly the interim private-use
66    /// `hs-kem-ml-kem-768-v1` value ([`ALG_ML_KEM_768`], −70200).
67    pub alg: i64,
68    /// ML-KEM-768 encapsulation key (1184 bytes).
69    pub encapsulation_key: Vec<u8>,
70    /// Key ID of the recipient key (1..64 bytes).
71    pub kid: Vec<u8>,
72}
73
74/// Response binding map carried in the `response_binding` claim (−70004).
75#[derive(Debug, Clone, PartialEq, Eq)]
76pub struct ResponseBinding {
77    /// Cap'n Proto 64-bit type ID of the response root type (map key 1).
78    pub root_type_id: u64,
79    /// How the response is delivered (map key 2).
80    pub response_kind: ResponseKind,
81    /// Whether the response is encrypted (map key 3).
82    pub protection_mode: ProtectionMode,
83    /// KEM recipient material (map key 4), non-null iff
84    /// `protection_mode == Encrypted`.
85    pub kem_recipient: Option<KemRecipient>,
86}
87
88impl ResponseBinding {
89    /// Decode from a CBOR value: either `null` (no binding) or the response
90    /// binding map.
91    pub fn decode(v: &CborValue) -> Result<Option<Self>> {
92        match v {
93            CborValue::Null => Ok(None),
94            _ => Ok(Some(Self::decode_map(v)?)),
95        }
96    }
97
98    fn decode_map(v: &CborValue) -> Result<Self> {
99        let map = match v {
100            CborValue::Map(m) => m,
101            _ => bail!("response_binding: expected map or null"),
102        };
103
104        let mut root_type_id = None;
105        let mut response_kind = None;
106        let mut protection_mode = None;
107        let mut kem_recipient = None;
108
109        for (key, val) in map.iter() {
110            let ik = match key {
111                CborValue::Integer(i) => i128::from(*i),
112                _ => bail!("response_binding: non-integer key"),
113            };
114            match ik {
115                1 => {
116                    root_type_id = Some(decode_uint(val, "root_type_id")?);
117                }
118                2 => {
119                    let k = decode_uint(val, "response_kind")?;
120                    response_kind = Some(ResponseKind::from_u64(k)?);
121                }
122                3 => {
123                    let p = decode_uint(val, "protection_mode")?;
124                    protection_mode = Some(ProtectionMode::from_u64(p)?);
125                }
126                4 => {
127                    kem_recipient = match val {
128                        CborValue::Null => None,
129                        _ => Some(KemRecipient::decode(val)?),
130                    };
131                }
132                _ => bail!("response_binding: unknown key {ik}"),
133            }
134        }
135
136        let root_type_id = root_type_id
137            .ok_or_else(|| anyhow::anyhow!("response_binding: missing root_type_id"))?;
138        let response_kind = response_kind
139            .ok_or_else(|| anyhow::anyhow!("response_binding: missing response_kind"))?;
140        let protection_mode = protection_mode
141            .ok_or_else(|| anyhow::anyhow!("response_binding: missing protection_mode"))?;
142
143        // The KEM recipient is present iff the response is encrypted — the two
144        // axes are orthogonal, so this relation depends only on protection_mode.
145        match protection_mode {
146            ProtectionMode::Encrypted => {
147                if kem_recipient.is_none() {
148                    bail!("response_binding: encrypted protection_mode requires kem_recipient");
149                }
150            }
151            ProtectionMode::Cleartext => {
152                if kem_recipient.is_some() {
153                    bail!(
154                        "response_binding: cleartext protection_mode must not carry kem_recipient"
155                    );
156                }
157                // The cleartext MAP alternative is streamed-but-not-encrypted
158                // only: a cleartext UNARY response is neither encrypted nor
159                // streamed, so it uses the null `response_binding` encoding,
160                // never a map (canonical vector N-27).
161                if response_kind != ResponseKind::StreamSetup {
162                    bail!(
163                        "response_binding: cleartext unary must use the null encoding; \
164                         the map form is stream_setup only"
165                    );
166                }
167            }
168        }
169
170        Ok(Self {
171            root_type_id,
172            response_kind,
173            protection_mode,
174            kem_recipient,
175        })
176    }
177}
178
179impl KemRecipient {
180    fn decode(v: &CborValue) -> Result<Self> {
181        let map = match v {
182            CborValue::Map(m) => m,
183            _ => bail!("kem_recipient: expected map"),
184        };
185        let mut alg = None;
186        let mut encapsulation_key = None;
187        let mut kid = None;
188
189        for (key, val) in map.iter() {
190            let ik = match key {
191                CborValue::Integer(i) => i128::from(*i),
192                _ => bail!("kem_recipient: non-integer key"),
193            };
194            match ik {
195                1 => {
196                    alg = Some(decode_int(val, "kem alg")?);
197                }
198                2 => {
199                    let k = decode_bstr(val, "encapsulation_key")?;
200                    if k.len() != 1184 {
201                        bail!(
202                            "kem_recipient: encapsulation_key must be 1184 bytes, got {}",
203                            k.len()
204                        );
205                    }
206                    encapsulation_key = Some(k);
207                }
208                3 => {
209                    let k = decode_bstr(val, "kem kid")?;
210                    if k.is_empty() || k.len() > 64 {
211                        bail!("kem_recipient: kid must be 1..64 bytes");
212                    }
213                    kid = Some(k);
214                }
215                _ => bail!("kem_recipient: unknown key {ik}"),
216            }
217        }
218
219        let alg = alg.ok_or_else(|| anyhow::anyhow!("kem_recipient: missing alg"))?;
220        // Gate-2 amendment 5: the algorithm is exactly the project-private
221        // ML-KEM-768 value. Any other value denies — a registered COSE value is
222        // an explicit incompatible profile revision, not accepted here.
223        if alg != ALG_ML_KEM_768 {
224            bail!(
225                "kem_recipient: alg must be exactly {ALG_ML_KEM_768} (hs-kem-ml-kem-768-v1), got {alg}"
226            );
227        }
228        let encapsulation_key = encapsulation_key
229            .ok_or_else(|| anyhow::anyhow!("kem_recipient: missing encapsulation_key"))?;
230        let kid = kid.ok_or_else(|| anyhow::anyhow!("kem_recipient: missing kid"))?;
231
232        Ok(Self {
233            alg,
234            encapsulation_key,
235            kid,
236        })
237    }
238}
239
240fn decode_uint(v: &CborValue, name: &str) -> Result<u64> {
241    match v {
242        CborValue::Integer(i) if i128::from(*i) >= 0 => Ok(i128::from(*i) as u64),
243        _ => bail!("{name}: must be non-negative uint"),
244    }
245}
246
247fn decode_int(v: &CborValue, name: &str) -> Result<i64> {
248    match v {
249        CborValue::Integer(i) => Ok(i128::from(*i) as i64),
250        _ => bail!("{name}: must be integer"),
251    }
252}
253
254fn decode_bstr(v: &CborValue, name: &str) -> Result<Vec<u8>> {
255    match v {
256        CborValue::Bytes(b) => Ok(b.clone()),
257        _ => bail!("{name}: must be bstr"),
258    }
259}
260
261#[cfg(test)]
262mod tests {
263    #![allow(clippy::unwrap_used, clippy::expect_used)]
264    use super::*;
265
266    fn encapsulation_key() -> Vec<u8> {
267        vec![0x11u8; 1184]
268    }
269
270    fn kem_map(alg: i64) -> CborValue {
271        CborValue::Map(vec![
272            (CborValue::Integer(1.into()), CborValue::Integer(alg.into())),
273            (
274                CborValue::Integer(2.into()),
275                CborValue::Bytes(encapsulation_key()),
276            ),
277            (
278                CborValue::Integer(3.into()),
279                CborValue::Bytes(b"kem-1".to_vec()),
280            ),
281        ])
282    }
283
284    /// The amended four-field binding with orthogonal axes decodes, and the KEM
285    /// recipient sits at key 4 with the exact −70200 algorithm.
286    #[test]
287    fn four_field_encrypted_unary_binding_decodes() {
288        let v = CborValue::Map(vec![
289            (CborValue::Integer(1.into()), CborValue::Integer(42.into())),
290            (CborValue::Integer(2.into()), CborValue::Integer(1.into())), // unary
291            (CborValue::Integer(3.into()), CborValue::Integer(2.into())), // encrypted
292            (CborValue::Integer(4.into()), kem_map(ALG_ML_KEM_768)),
293        ]);
294        let b = ResponseBinding::decode(&v).unwrap().unwrap();
295        assert_eq!(b.root_type_id, 42);
296        assert_eq!(b.response_kind, ResponseKind::Unary);
297        assert_eq!(b.protection_mode, ProtectionMode::Encrypted);
298        assert_eq!(b.kem_recipient.as_ref().unwrap().alg, ALG_ML_KEM_768);
299    }
300
301    /// The two axes are orthogonal: an encrypted stream setup is a valid
302    /// combination and still carries a recipient.
303    #[test]
304    fn encrypted_stream_setup_is_a_valid_orthogonal_combination() {
305        let v = CborValue::Map(vec![
306            (CborValue::Integer(1.into()), CborValue::Integer(7.into())),
307            (CborValue::Integer(2.into()), CborValue::Integer(2.into())), // stream_setup
308            (CborValue::Integer(3.into()), CborValue::Integer(2.into())), // encrypted
309            (CborValue::Integer(4.into()), kem_map(ALG_ML_KEM_768)),
310        ]);
311        let b = ResponseBinding::decode(&v).unwrap().unwrap();
312        assert_eq!(b.response_kind, ResponseKind::StreamSetup);
313        assert_eq!(b.protection_mode, ProtectionMode::Encrypted);
314        assert!(b.kem_recipient.is_some());
315    }
316
317    /// Cleartext binding carries no recipient at key 4.
318    #[test]
319    fn cleartext_stream_setup_binding_forbids_recipient() {
320        let ok = CborValue::Map(vec![
321            (CborValue::Integer(1.into()), CborValue::Integer(9.into())),
322            (CborValue::Integer(2.into()), CborValue::Integer(2.into())), // stream_setup
323            (CborValue::Integer(3.into()), CborValue::Integer(1.into())), // cleartext
324            (CborValue::Integer(4.into()), CborValue::Null),
325        ]);
326        assert!(ResponseBinding::decode(&ok).unwrap().is_some());
327
328        let bad = CborValue::Map(vec![
329            (CborValue::Integer(1.into()), CborValue::Integer(9.into())),
330            (CborValue::Integer(2.into()), CborValue::Integer(2.into())), // stream_setup
331            (CborValue::Integer(3.into()), CborValue::Integer(1.into())), // cleartext
332            (CborValue::Integer(4.into()), kem_map(ALG_ML_KEM_768)),
333        ]);
334        assert!(ResponseBinding::decode(&bad).is_err());
335    }
336
337    /// The cleartext MAP alternative is stream_setup-only: a cleartext unary
338    /// response is neither encrypted nor streamed and is encoded as a null
339    /// `response_binding`, never a map (canonical vector N-27).
340    #[test]
341    fn cleartext_unary_map_denies() {
342        let v = CborValue::Map(vec![
343            (CborValue::Integer(1.into()), CborValue::Integer(9.into())),
344            (CborValue::Integer(2.into()), CborValue::Integer(1.into())), // unary
345            (CborValue::Integer(3.into()), CborValue::Integer(1.into())), // cleartext
346            (CborValue::Integer(4.into()), CborValue::Null),
347        ]);
348        let err = ResponseBinding::decode(&v).unwrap_err().to_string();
349        assert!(
350            err.contains("null encoding"),
351            "cleartext unary map must deny on the null-encoding rule, got: {err}"
352        );
353    }
354
355    /// Encrypted binding without a recipient denies.
356    #[test]
357    fn encrypted_binding_requires_recipient() {
358        let v = CborValue::Map(vec![
359            (CborValue::Integer(1.into()), CborValue::Integer(9.into())),
360            (CborValue::Integer(2.into()), CborValue::Integer(1.into())),
361            (CborValue::Integer(3.into()), CborValue::Integer(2.into())), // encrypted
362            (CborValue::Integer(4.into()), CborValue::Null),
363        ]);
364        assert!(ResponseBinding::decode(&v).is_err());
365    }
366
367    /// A KEM recipient with any algorithm other than −70200 denies.
368    #[test]
369    fn kem_recipient_alg_must_be_exactly_ml_kem_768() {
370        let v = CborValue::Map(vec![
371            (CborValue::Integer(1.into()), CborValue::Integer(9.into())),
372            (CborValue::Integer(2.into()), CborValue::Integer(1.into())),
373            (CborValue::Integer(3.into()), CborValue::Integer(2.into())),
374            (CborValue::Integer(4.into()), kem_map(-70199)),
375        ]);
376        assert!(ResponseBinding::decode(&v).is_err());
377    }
378
379    /// The pre-amendment three-field encoding (combined mode at key 2, KEM at
380    /// key 3, no protection_mode) is rejected by the four-field parser — the
381    /// exact shape the pre-re-issue P-4 fixture carried, now re-issued at the
382    /// amended four-field binding; the old shape must still deny.
383    #[test]
384    fn pre_amendment_three_field_binding_is_rejected() {
385        let v = CborValue::Map(vec![
386            (CborValue::Integer(1.into()), CborValue::Integer(9.into())),
387            (CborValue::Integer(2.into()), CborValue::Integer(2.into())), // old combined "unary encrypted"
388            (CborValue::Integer(3.into()), kem_map(ALG_ML_KEM_768)),      // old kem at key 3
389        ]);
390        assert!(ResponseBinding::decode(&v).is_err());
391    }
392}