Skip to main content

hyprstream_rpc/proof/
claims.rs

1//! Proof CWT claims-set types and bounded deterministic-CBOR decode.
2//!
3//! The generic claims set is a closed profile of RFC 8392 CWT: registered
4//! claims (`aud`, `exp`, `iat`, `cti`, `Nonce`) carry registered semantics,
5//! and four private-use claims (−70001…−70004) carry Hyprstream bindings. The
6//! unpublished −70009 recipient extension is accepted only by the dedicated
7//! deferred-Federate decoder, never by generic proof-v1 decoding.
8
9use anyhow::{bail, Result};
10use ciborium::value::Value as CborValue;
11
12#[allow(unused_imports)]
13use super::{
14    CredentialHash, RequestId, CLAIM_CAPNP_BODY_BYTES, CLAIM_CAPNP_SCHEMA_ID,
15    CLAIM_CREDENTIAL_HASH, CLAIM_RESPONSE_BINDING, CREDENTIAL_HASH_SIZE, CWT_CLAIM_AUD,
16    CWT_CLAIM_CTI, CWT_CLAIM_EXP, CWT_CLAIM_IAT, CWT_CLAIM_NONCE, MAX_BODY_BYTES,
17    MAX_CHALLENGE_BYTES, MAX_SERVICE_DOMAIN_BYTES, MIN_CHALLENGE_BYTES, REQUEST_ID_SIZE,
18};
19use crate::proof::{recipient_binding::FederateRecipientBinding, response::ResponseBinding};
20
21/// Decoded proof-CWT claims set.
22#[derive(Debug, Clone)]
23pub struct ProofClaims {
24    /// Canonical service domain (CWT `aud`).
25    pub aud: String,
26    /// Proof expiry, integer Unix seconds (CWT `exp`).
27    pub exp: u64,
28    /// Proof issuance, integer Unix seconds (CWT `iat`).
29    pub iat: u64,
30    /// 128-bit request identifier (CWT `cti`).
31    pub request_id: RequestId,
32    /// Server challenge (CWT `Nonce`, RFC 9711). Present exactly when the
33    /// profile requires a challenge.
34    pub nonce: Option<Vec<u8>>,
35    /// SHA-256 of the exact credential bytes, or `None` when no credential is
36    /// presented (encoded as CBOR `null`).
37    pub credential_hash: Option<CredentialHash>,
38    /// Cap'n Proto 64-bit root type ID of the signed body.
39    pub capnp_schema_id: u64,
40    /// Exact Cap'n Proto body bytes (`capnp_body_bytes`, claim −70003 — the one
41    /// neutral name used for both request and response proof bodies).
42    pub capnp_body_bytes: Vec<u8>,
43    /// Response binding map, or `None` when unbound (encoded as CBOR `null`).
44    pub response_binding: Option<ResponseBinding>,
45    /// Optional deferred-Federate source extension binding all forwarded
46    /// response recipients (claim −70009). Generic proof-v1 paths reject it.
47    pub federate_recipient_binding: Option<FederateRecipientBinding>,
48}
49
50impl ProofClaims {
51    /// Decode a claims payload from a CBOR byte string.
52    ///
53    /// Enforces:
54    /// - RFC 8949 core deterministic encoding (no indefinite lengths, no
55    ///   non-minimal integers, no tags, no floating-point values, sorted unique
56    ///   map keys).
57    /// - Closed claim set: unknown claim keys deny.
58    /// - Every listed claim is present (absent claims deny).
59    /// - Proof-v1 size caps on `aud`, body bytes, challenge.
60    pub fn decode(payload: &[u8]) -> Result<Self> {
61        Self::decode_with_federate_extension(payload, false)
62    }
63
64    pub(crate) fn decode_deferred_federate(payload: &[u8]) -> Result<Self> {
65        Self::decode_with_federate_extension(payload, true)
66    }
67
68    fn decode_with_federate_extension(payload: &[u8], allow_extension: bool) -> Result<Self> {
69        // Raw-byte deterministic audit BEFORE ciborium deserialization
70        // (ciborium resolves indefinite lengths and non-minimal integers
71        // transparently, destroying the evidence).
72        super::cbor_audit::audit_deterministic(payload)?;
73
74        let value: CborValue = ciborium::de::from_reader(&mut std::io::Cursor::new(payload))
75            .map_err(|e| anyhow::anyhow!("proof claims: CBOR decode failed: {e}"))?;
76
77        let map = match &value {
78            CborValue::Map(m) => m,
79            _ => bail!("proof claims: expected CBOR map"),
80        };
81
82        // Collect known keys; deny unknown keys.
83        let mut aud = None;
84        let mut exp = None;
85        let mut iat = None;
86        let mut cti = None;
87        let mut nonce = None;
88        let mut credential_hash = None;
89        let mut capnp_schema_id = None;
90        let mut capnp_body_bytes = None;
91        let mut response_binding = None;
92        let mut federate_recipient_binding = None;
93
94        for (key, val) in map.iter() {
95            let ik = match key {
96                CborValue::Integer(i) => i128::from(*i),
97                _ => bail!("proof claims: non-integer claim key"),
98            };
99            match ik {
100                x if x == CWT_CLAIM_AUD as i128 => {
101                    let domain = decode_text(val, "aud", 1, MAX_SERVICE_DOMAIN_BYTES)?;
102                    // The aud names a canonical service domain: the shared
103                    // `validate_service_domain` syntax (lowercase ASCII,
104                    // constrained punctuation), never normalized here —
105                    // canonical vectors N-29/N-30 deny on this rule.
106                    crate::envelope::validate_service_domain(&domain)?;
107                    aud = Some(domain);
108                }
109                x if x == CWT_CLAIM_EXP as i128 => {
110                    exp = Some(decode_uint(val, "exp")?);
111                }
112                x if x == CWT_CLAIM_IAT as i128 => {
113                    iat = Some(decode_uint(val, "iat")?);
114                }
115                x if x == CWT_CLAIM_CTI as i128 => {
116                    cti = Some(decode_bstr_fixed(val, "cti", REQUEST_ID_SIZE)?);
117                }
118                x if x == CWT_CLAIM_NONCE as i128 => {
119                    nonce = Some(decode_bstr_range(
120                        val,
121                        "Nonce",
122                        MIN_CHALLENGE_BYTES,
123                        MAX_CHALLENGE_BYTES,
124                    )?);
125                }
126                x if x == CLAIM_CREDENTIAL_HASH as i128 => {
127                    credential_hash = Some(decode_credential_hash(val)?);
128                }
129                x if x == CLAIM_CAPNP_SCHEMA_ID as i128 => {
130                    capnp_schema_id = Some(decode_uint(val, "capnp_schema_id")?);
131                }
132                x if x == CLAIM_CAPNP_BODY_BYTES as i128 => {
133                    let b = decode_bstr(val, "capnp_body_bytes")?;
134                    if b.len() > MAX_BODY_BYTES {
135                        bail!(
136                            "proof claims: capnp_body_bytes exceeds {} bytes",
137                            MAX_BODY_BYTES
138                        );
139                    }
140                    capnp_body_bytes = Some(b);
141                }
142                x if x == CLAIM_RESPONSE_BINDING as i128 => {
143                    response_binding = Some(ResponseBinding::decode(val)?);
144                }
145                x if x == super::CLAIM_FEDERATE_RECIPIENT_BINDING as i128 => {
146                    if !allow_extension {
147                        bail!("proof claims: unknown claim key {}", ik);
148                    }
149                    federate_recipient_binding = Some(FederateRecipientBinding::decode(val)?);
150                }
151                _ => bail!("proof claims: unknown claim key {}", ik),
152            }
153        }
154
155        // Every listed claim is always present (Nonce is the exception).
156        let aud = aud.ok_or_else(|| anyhow::anyhow!("proof claims: missing aud"))?;
157        let exp = exp.ok_or_else(|| anyhow::anyhow!("proof claims: missing exp"))?;
158        let iat = iat.ok_or_else(|| anyhow::anyhow!("proof claims: missing iat"))?;
159        let request_id = cti.ok_or_else(|| anyhow::anyhow!("proof claims: missing cti"))?;
160        let credential_hash = credential_hash
161            .ok_or_else(|| anyhow::anyhow!("proof claims: missing credential_hash"))?;
162        let capnp_schema_id = capnp_schema_id
163            .ok_or_else(|| anyhow::anyhow!("proof claims: missing capnp_schema_id"))?;
164        let capnp_body_bytes = capnp_body_bytes
165            .ok_or_else(|| anyhow::anyhow!("proof claims: missing capnp_body_bytes"))?;
166        let response_binding = response_binding
167            .ok_or_else(|| anyhow::anyhow!("proof claims: missing response_binding"))?;
168
169        Ok(Self {
170            aud,
171            exp,
172            iat,
173            request_id,
174            nonce,
175            credential_hash,
176            capnp_schema_id,
177            capnp_body_bytes,
178            response_binding,
179            federate_recipient_binding,
180        })
181    }
182}
183
184/// Decode a `credential_hash` claim: either `null` (no credential) or a
185/// 32-byte bstr.
186fn decode_credential_hash(val: &CborValue) -> Result<Option<CredentialHash>> {
187    match val {
188        CborValue::Null => Ok(None),
189        CborValue::Bytes(b) => {
190            if b.len() != CREDENTIAL_HASH_SIZE {
191                bail!(
192                    "proof claims: credential_hash must be {} bytes, got {}",
193                    CREDENTIAL_HASH_SIZE,
194                    b.len()
195                );
196            }
197            let mut arr = [0u8; CREDENTIAL_HASH_SIZE];
198            arr.copy_from_slice(b);
199            Ok(Some(arr))
200        }
201        _ => bail!("proof claims: credential_hash must be bstr or null"),
202    }
203}
204
205// ---------------------------------------------------------------------------
206// Typed CBOR extractors — deterministic encoding is enforced at the byte
207// level by `cbor_audit::audit_deterministic` before ciborium deserialization.
208// ---------------------------------------------------------------------------
209
210fn decode_text(v: &CborValue, name: &str, min_bytes: usize, max_bytes: usize) -> Result<String> {
211    match v {
212        CborValue::Text(s) => {
213            if s.len() < min_bytes {
214                bail!("proof claims: {name} must be at least {min_bytes} bytes");
215            }
216            if s.len() > max_bytes {
217                bail!("proof claims: {name} exceeds {max_bytes} bytes");
218            }
219            Ok(s.clone())
220        }
221        _ => bail!("proof claims: {name} must be text"),
222    }
223}
224
225fn decode_uint(v: &CborValue, name: &str) -> Result<u64> {
226    match v {
227        CborValue::Integer(i) => {
228            if i128::from(*i) < 0 {
229                bail!("proof claims: {name} must be unsigned");
230            }
231            Ok(i128::from(*i) as u64)
232        }
233        _ => bail!("proof claims: {name} must be uint"),
234    }
235}
236
237fn decode_bstr(v: &CborValue, name: &str) -> Result<Vec<u8>> {
238    match v {
239        CborValue::Bytes(b) => Ok(b.clone()),
240        _ => bail!("proof claims: {name} must be bstr"),
241    }
242}
243
244fn decode_bstr_fixed<const N: usize>(v: &CborValue, name: &str, size: usize) -> Result<[u8; N]> {
245    let b = decode_bstr(v, name)?;
246    // We need to verify b.len() == size, but N is the array size.
247    // For our use, N == size always (REQUEST_ID_SIZE etc.).
248    if b.len() != size {
249        bail!("proof claims: {name} must be {size} bytes, got {}", b.len());
250    }
251    // N is the compile-time size; at runtime we checked against `size`.
252    // Since N == size for all call sites, this is safe.
253    let mut arr = [0u8; N];
254    arr.copy_from_slice(&b[..N]);
255    Ok(arr)
256}
257
258fn decode_bstr_range(v: &CborValue, name: &str, min: usize, max: usize) -> Result<Vec<u8>> {
259    let b = decode_bstr(v, name)?;
260    if b.len() < min || b.len() > max {
261        bail!(
262            "proof claims: {name} must be {min}..{max} bytes, got {}",
263            b.len()
264        );
265    }
266    Ok(b)
267}