Skip to main content

hyprstream_rpc/proof/
mod.rs

1//! v16 proof-CWT wire support — canonical parser, replay admission, response binding.
2//!
3//! This module implements the `hs-rpc-proof-v1` profile: a CWT claims set
4//! (RFC 8392) signed as a COSE object (RFC 9052) that proves one RPC request's
5//! integrity, freshness, credential binding, and response binding.
6//!
7//! The wire contract is the frozen gate-2 CDDL at
8//! `docs/standards/v16/hyprstream-proof-cwt.cddl` and the private-label
9//! registry at `docs/standards/v16/private-label-registry.md`. Canonical test
10//! vectors are in `docs/standards/v16/vectors/`.
11//!
12//! # Layout
13//!
14//! - [`claims`] — proof CWT claims-set types and bounded CBOR decode.
15//! - [`enrollment`] — per-entry enrolled signer-suite resolution for
16//!   authenticated and response proofs.
17//! - [`plan`] — canonical signature-plan types and validation.
18//! - [`policy`] — generated per-method signature policy (suite, disposition,
19//!   approver threshold) resolved for the decoded leaf.
20//! - [`parser`] — bounded COSE object parse, header/`crit` validation, and
21//!   proof-vector decode.
22//! - [`replay`] — replay admission store, partitioned by disposition.
23//! - [`challenge`] — rotating server challenge for unattributed proofs.
24//! - [`response`] — response proof binding types.
25
26pub mod admission;
27pub mod build;
28pub mod cbor_audit;
29pub mod challenge;
30pub mod claims;
31pub mod enrollment;
32pub mod parser;
33pub mod plan;
34pub mod policy;
35pub mod recipient_binding;
36pub mod response;
37mod thumbprint;
38pub mod verify;
39
40#[cfg(test)]
41mod tests;
42
43// ---------------------------------------------------------------------------
44// Profile constants — frozen by the gate-2 CDDL.
45// ---------------------------------------------------------------------------
46
47/// Media type for the request-proof CWT (RFC 6838 vendor tree, `+cwt` suffix).
48pub const PROOF_TYP: &str = "application/vnd.hyprstream.proof+cwt";
49
50/// Media type for the response-proof CWT.
51pub const RESPONSE_PROOF_TYP: &str = "application/vnd.hyprstream.response-proof+cwt";
52
53/// Cryptographic domain separator for request proofs — inside every
54/// `Sig_structure`.
55pub const REQUEST_PROOF_DOMAIN: &str = "hs-rpc-request-proof-v1";
56
57/// Cryptographic domain separator for response proofs.
58pub const RESPONSE_PROOF_DOMAIN: &str = "hs-rpc-response-proof-v1";
59
60/// Versioned suite ID for standalone Ed25519.
61pub const SUITE_CLASSICAL: &str = "hs-cose-sign-ed25519-v1";
62
63/// Versioned suite ID for the weakly-non-separable Ed25519 + ML-DSA-65 hybrid.
64pub const SUITE_HYBRID: &str = "hs-cose-sign-ed25519-mldsa65-wns-v1";
65
66// --- proof-v1 caps (exact; raising one is an incompatible profile revision) ---
67
68/// Maximum signer groups per plan.
69pub const MAX_SIGNER_GROUPS: usize = 8;
70/// Maximum components per signer group.
71pub const MAX_COMPONENTS_PER_GROUP: usize = 2;
72/// Maximum signature entries per proof.
73pub const MAX_SIGNATURE_ENTRIES: usize = 16;
74/// Maximum encoded bytes for a suite ID.
75pub const MAX_SUITE_ID_BYTES: usize = 64;
76/// Maximum bytes for a key ID.
77pub const MAX_KID_BYTES: usize = 64;
78/// Maximum bytes for a canonical service domain (proof `aud`).
79///
80/// Gate-2 amendment 7: the proof audience is the one canonical RPC service
81/// domain, capped and canonicalized by the single shared
82/// [`crate::envelope::MAX_SERVICE_DOMAIN_BYTES`] rule — not a second identity
83/// cap. Re-exported here so proof code reads one constant.
84pub use crate::envelope::MAX_SERVICE_DOMAIN_BYTES;
85/// Ceiling on the `hs_logical_signer_group` value (Gate-2 amendment 6:
86/// `uint .le 255`). A group ID above this denies at parse time.
87pub const MAX_SIGNER_GROUP_ID: u64 = 255;
88/// Maximum Cap'n Proto body bytes signed by the proof.
89pub const MAX_BODY_BYTES: usize = 1_048_576; // 1 MiB
90/// Maximum total encoded COSE object size.
91pub const MAX_COSE_OBJECT_BYTES: usize = 2_097_152; // 2 MiB
92/// Request ID size in bytes (CWT `cti`).
93pub const REQUEST_ID_SIZE: usize = 16;
94/// Credential hash size in bytes (SHA-256).
95pub const CREDENTIAL_HASH_SIZE: usize = 32;
96/// Minimum server-challenge size in bytes.
97pub const MIN_CHALLENGE_BYTES: usize = 16;
98/// Maximum server-challenge size in bytes.
99pub const MAX_CHALLENGE_BYTES: usize = 64;
100
101/// W1 (design §4.5) verifier-clock freshness bounds. All three are
102/// VERIFIER-CLOCK bounds, never issued lifetime (`exp - iat`): a proof is
103/// fresh iff `|iat - now| <= MAX_CLOCK_SKEW_SECS`, `now < exp`, and
104/// `exp - now` is within the disposition maximum.
105pub const MAX_CLOCK_SKEW_SECS: u64 = 30;
106/// Maximum remaining lifetime for an authenticated (credential-bound) proof.
107pub const MAX_REMAINING_LIFETIME_AUTHENTICATED_SECS: u64 = 300;
108/// Maximum remaining lifetime for an unattributed (self-asserted) proof.
109pub const MAX_REMAINING_LIFETIME_UNATTRIBUTED_SECS: u64 = 30;
110
111// --- private-use CWT claim keys (checked registry) ---
112
113pub const CLAIM_CREDENTIAL_HASH: i64 = -70001;
114pub const CLAIM_CAPNP_SCHEMA_ID: i64 = -70002;
115pub const CLAIM_CAPNP_BODY_BYTES: i64 = -70003;
116pub const CLAIM_RESPONSE_BINDING: i64 = -70004;
117/// Deferred-Federate-only source extension binding every forwarded response
118/// recipient. Generic proof parsing rejects it; it is not in the frozen
119/// public v16 registry.
120pub const CLAIM_FEDERATE_RECIPIENT_BINDING: i64 = -70009;
121
122// --- private-use COSE header parameters ---
123
124pub const HEADER_HS_DOMAIN: i64 = -70100;
125pub const HEADER_HS_SIGNATURE_PLAN: i64 = -70101;
126pub const HEADER_HS_LOGICAL_SIGNER_GROUP: i64 = -70102;
127pub const HEADER_HS_UNATTRIBUTED_KEY_SET: i64 = -70103;
128
129// --- registered CWT claim keys used by this profile ---
130
131pub const CWT_CLAIM_AUD: i64 = 3;
132pub const CWT_CLAIM_EXP: i64 = 4;
133pub const CWT_CLAIM_IAT: i64 = 6;
134pub const CWT_CLAIM_CTI: i64 = 7;
135pub const CWT_CLAIM_NONCE: i64 = 10; // RFC 9711
136
137// --- registered COSE header parameters used by this profile ---
138
139pub const COSE_HEADER_ALG: i64 = 1;
140pub const COSE_HEADER_CRIT: i64 = 2;
141pub const COSE_HEADER_KID: i64 = 4;
142pub const COSE_HEADER_TYP: i64 = 16; // RFC 9596
143
144// --- COSE algorithm identifiers ---
145
146pub const ALG_ED25519: i64 = -19;
147pub const ALG_ML_DSA_65: i64 = -49;
148
149/// Interim project-private COSE algorithm ID for the ML-KEM-768 response
150/// recipient (Gate-2 amendment 5: `hs-kem-ml-kem-768-v1 = -70200`). This is
151/// enforced exactly; a future registered COSE value is an explicit
152/// incompatible profile revision, not a silent alternative.
153pub const ALG_ML_KEM_768: i64 = -70200;
154
155/// A 128-bit request identifier — the CWT `cti` claim.
156pub type RequestId = [u8; REQUEST_ID_SIZE];
157
158/// SHA-256 credential hash.
159pub type CredentialHash = [u8; CREDENTIAL_HASH_SIZE];
160
161/// The kind of proof, determined by which `typ`/`hs_domain` pair it carries.
162#[derive(Debug, Clone, Copy, PartialEq, Eq)]
163pub enum ProofKind {
164    /// Request proof (`hs-rpc-request-proof-v1`).
165    Request,
166    /// Response proof (`hs-rpc-response-proof-v1`).
167    Response,
168}
169
170impl ProofKind {
171    pub fn typ(self) -> &'static str {
172        match self {
173            Self::Request => PROOF_TYP,
174            Self::Response => RESPONSE_PROOF_TYP,
175        }
176    }
177
178    pub fn domain(self) -> &'static str {
179        match self {
180            Self::Request => REQUEST_PROOF_DOMAIN,
181            Self::Response => RESPONSE_PROOF_DOMAIN,
182        }
183    }
184}
185
186/// Whether `presented` is a request- or response-proof CWT rather than a
187/// credential.
188///
189/// A proof CWT and a credential are disjoint by construction (§4.2): a
190/// verifier MUST reject a token whose protected type does not match the slot
191/// it was presented in. This is the credential slot's half of that rule, and
192/// it covers both presentations — a compact-serialization token whose header
193/// `typ` names a proof media type, and a raw COSE object carrying the proof
194/// `typ` header (the shape a CWT credential slot would accept).
195///
196/// It is a cheap, bounded structural check: it never verifies a signature and
197/// never consults an issuer key, because a proof presented as a credential
198/// must be refused before any key material is resolved.
199pub fn is_proof_typed_credential(presented: &[u8]) -> bool {
200    // Compact serialization: header.payload.signature, header is base64url JSON.
201    if let Ok(text) = std::str::from_utf8(presented) {
202        if let Some((header_b64, rest)) = text.split_once('.') {
203            if rest.contains('.') && header_b64.len() <= 4096 {
204                use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine as _};
205                if let Ok(bytes) = URL_SAFE_NO_PAD.decode(header_b64) {
206                    if let Ok(value) = serde_json::from_slice::<serde_json::Value>(&bytes) {
207                        if let Some(typ) = value.get("typ").and_then(|t| t.as_str()) {
208                            if typ == PROOF_TYP || typ == RESPONSE_PROOF_TYP {
209                                return true;
210                            }
211                        }
212                    }
213                }
214            }
215        }
216    }
217
218    // COSE object: the bounded parser establishes the typ/domain pair, so a
219    // proof presented where a CWT credential is expected is refused by the
220    // same rule that admits it in the proof slot.
221    parser::ParsedProof::parse(presented).is_ok()
222}
223
224/// Disposition of a proof relative to credential presence. Determines the
225/// replay key and partition.
226#[derive(Debug, Clone, Copy, PartialEq, Eq)]
227pub enum ProofDisposition {
228    /// A credential was presented and the proof is `cnf`-bound.
229    Authenticated,
230    /// No credential — self-asserted key set, system-low clearance.
231    Unattributed,
232}