lenso_process_protocol/
proof.rs1use serde::Serialize;
2use serde_json::Value;
3use sha2::{Digest as _, Sha256};
4
5use super::{HandshakeIdentity, HandshakeParams, ProtocolError, decode_base64url_32};
6
7const HOST_PROOF_DOMAIN: &[u8] = b"lenso-process-host-v1";
8const CHILD_PROOF_DOMAIN: &[u8] = b"lenso-process-child-v1";
9const MAX_SAFE_JSON_INTEGER: u64 = 9_007_199_254_740_991;
10
11pub fn canonicalize_proof_value(value: &Value) -> Result<Vec<u8>, ProtocolError> {
13 let mut output = Vec::new();
14 write_canonical(value, &mut output)?;
15 Ok(output)
16}
17
18pub fn handshake_params_digest(params: &HandshakeParams) -> Result<[u8; 32], ProtocolError> {
20 #[derive(Serialize)]
21 struct ProofPayload<'a> {
22 identity: &'a HandshakeIdentity,
23 host_nonce: &'a str,
24 }
25
26 params.identity.validate()?;
27 decode_base64url_32("host_nonce", ¶ms.host_nonce)?;
28 let value = serde_json::to_value(ProofPayload {
29 identity: ¶ms.identity,
30 host_nonce: ¶ms.host_nonce,
31 })
32 .map_err(|error| ProtocolError::new(format!("cannot encode handshake proof: {error}")))?;
33 let canonical = canonicalize_proof_value(&value)?;
34 Ok(Sha256::digest(canonical).into())
35}
36
37#[must_use]
39pub fn host_proof_message(handshake_digest: &[u8; 32]) -> Vec<u8> {
40 proof_message(HOST_PROOF_DOMAIN, handshake_digest, None)
41}
42
43pub fn child_proof_message(
45 handshake_digest: &[u8; 32],
46 session: &str,
47) -> Result<Vec<u8>, ProtocolError> {
48 let session = decode_base64url_32("session", session)?;
49 Ok(proof_message(
50 CHILD_PROOF_DOMAIN,
51 handshake_digest,
52 Some(&session),
53 ))
54}
55
56fn proof_message(domain: &[u8], digest: &[u8; 32], suffix: Option<&[u8; 32]>) -> Vec<u8> {
57 let mut message = Vec::with_capacity(domain.len() + 1 + 32 + suffix.map_or(0, |_| 32));
58 message.extend_from_slice(domain);
59 message.push(0);
60 message.extend_from_slice(digest);
61 if let Some(suffix) = suffix {
62 message.extend_from_slice(suffix);
63 }
64 message
65}
66
67fn write_canonical(value: &Value, output: &mut Vec<u8>) -> Result<(), ProtocolError> {
68 match value {
69 Value::Null => output.extend_from_slice(b"null"),
70 Value::Bool(true) => output.extend_from_slice(b"true"),
71 Value::Bool(false) => output.extend_from_slice(b"false"),
72 Value::String(value) => output.extend_from_slice(
73 serde_json::to_string(value)
74 .map_err(|error| ProtocolError::new(error.to_string()))?
75 .as_bytes(),
76 ),
77 Value::Number(number) => {
78 let encoded = if let Some(value) = number.as_u64() {
79 if value > MAX_SAFE_JSON_INTEGER {
80 return Err(ProtocolError::new(
81 "proof JSON integer exceeds the portable safe range",
82 ));
83 }
84 value.to_string()
85 } else if let Some(value) = number.as_i64() {
86 if value.unsigned_abs() > MAX_SAFE_JSON_INTEGER {
87 return Err(ProtocolError::new(
88 "proof JSON integer exceeds the portable safe range",
89 ));
90 }
91 value.to_string()
92 } else {
93 return Err(ProtocolError::new(
94 "floating-point values are forbidden in proof JSON",
95 ));
96 };
97 output.extend_from_slice(encoded.as_bytes());
98 }
99 Value::Array(values) => {
100 output.push(b'[');
101 for (index, value) in values.iter().enumerate() {
102 if index > 0 {
103 output.push(b',');
104 }
105 write_canonical(value, output)?;
106 }
107 output.push(b']');
108 }
109 Value::Object(values) => {
110 let mut entries = values.iter().collect::<Vec<_>>();
111 entries.sort_by(|(left, _), (right, _)| left.encode_utf16().cmp(right.encode_utf16()));
112 output.push(b'{');
113 for (index, (key, value)) in entries.into_iter().enumerate() {
114 if index > 0 {
115 output.push(b',');
116 }
117 output.extend_from_slice(
118 serde_json::to_string(key)
119 .map_err(|error| ProtocolError::new(error.to_string()))?
120 .as_bytes(),
121 );
122 output.push(b':');
123 write_canonical(value, output)?;
124 }
125 output.push(b'}');
126 }
127 }
128 Ok(())
129}