Skip to main content

lenso_process_protocol/
proof.rs

1use serde::Serialize;
2use serde_json::Value;
3use sha2::{Digest as _, Sha256};
4
5use super::{
6    HandshakeIdentity, HandshakeParams, ProtocolError, authoring::InitializeParams,
7    decode_base64url_32,
8};
9
10const HOST_PROOF_DOMAIN: &[u8] = b"lenso-process-host-v1";
11const CHILD_PROOF_DOMAIN: &[u8] = b"lenso-process-child-v1";
12const AUTHORING_HOST_PROOF_DOMAIN: &[u8] = b"lenso-authoring-host-v2";
13const AUTHORING_CHILD_PROOF_DOMAIN: &[u8] = b"lenso-authoring-child-v2";
14const AUTHORING_CALLBACK_PROOF_DOMAIN: &[u8] = b"lenso-authoring-callback-v2";
15const MAX_SAFE_JSON_INTEGER: u64 = 9_007_199_254_740_991;
16
17/// Returns RFC 8785-compatible canonical bytes for the restricted proof profile.
18pub fn canonicalize_proof_value(value: &Value) -> Result<Vec<u8>, ProtocolError> {
19    let mut output = Vec::new();
20    write_canonical(value, &mut output)?;
21    Ok(output)
22}
23
24/// Computes the raw SHA-256 digest bound by host and child handshake proofs.
25pub fn handshake_params_digest(params: &HandshakeParams) -> Result<[u8; 32], ProtocolError> {
26    #[derive(Serialize)]
27    struct ProofPayload<'a> {
28        identity: &'a HandshakeIdentity,
29        host_nonce: &'a str,
30    }
31
32    params.identity.validate()?;
33    decode_base64url_32("host_nonce", &params.host_nonce)?;
34    let value = serde_json::to_value(ProofPayload {
35        identity: &params.identity,
36        host_nonce: &params.host_nonce,
37    })
38    .map_err(|error| ProtocolError::new(format!("cannot encode handshake proof: {error}")))?;
39    let canonical = canonicalize_proof_value(&value)?;
40    Ok(Sha256::digest(canonical).into())
41}
42
43/// Returns the exact bytes authenticated by `host_proof`.
44#[must_use]
45pub fn host_proof_message(handshake_digest: &[u8; 32]) -> Vec<u8> {
46    proof_message(HOST_PROOF_DOMAIN, handshake_digest, None)
47}
48
49/// Returns the exact bytes authenticated by `child_proof`.
50pub fn child_proof_message(
51    handshake_digest: &[u8; 32],
52    session: &str,
53) -> Result<Vec<u8>, ProtocolError> {
54    let session = decode_base64url_32("session", session)?;
55    Ok(proof_message(
56        CHILD_PROOF_DOMAIN,
57        handshake_digest,
58        Some(&session),
59    ))
60}
61
62/// Values bound by an Authoring V2 initialization handshake.
63#[derive(Clone, Copy, Debug)]
64pub struct AuthoringHandshakeProofInput<'a> {
65    /// Exact initialization admitted by the child.
66    pub initialize: &'a InitializeParams,
67    /// Exact loopback HTTP origin exposed by the Host callback listener.
68    pub callback_origin: &'a str,
69    /// Canonical 32-byte base64url Host nonce.
70    pub host_nonce: &'a str,
71}
72
73/// Returns the canonical bytes hashed before authenticating Authoring V2 initialization.
74pub fn authoring_handshake_proof_payload(
75    input: AuthoringHandshakeProofInput<'_>,
76) -> Result<Vec<u8>, ProtocolError> {
77    #[derive(Serialize)]
78    struct ProofPayload<'a> {
79        initialize: &'a InitializeParams,
80        callback_origin: &'a str,
81        host_nonce: &'a str,
82    }
83
84    input.initialize.validate()?;
85    validate_loopback_http_origin(input.callback_origin)?;
86    decode_base64url_32("host_nonce", input.host_nonce)?;
87    let value = serde_json::to_value(ProofPayload {
88        initialize: input.initialize,
89        callback_origin: input.callback_origin,
90        host_nonce: input.host_nonce,
91    })
92    .map_err(|error| ProtocolError::new(format!("cannot encode authoring proof: {error}")))?;
93    canonicalize_proof_value(&value)
94}
95
96/// Returns the exact bytes authenticated by the Authoring V2 Host proof.
97#[must_use]
98pub fn authoring_host_proof_message(handshake_digest: &[u8; 32]) -> Vec<u8> {
99    proof_message(AUTHORING_HOST_PROOF_DOMAIN, handshake_digest, None)
100}
101
102/// Returns the exact bytes authenticated by the Authoring V2 child proof.
103pub fn authoring_child_proof_message(
104    handshake_digest: &[u8; 32],
105    child_nonce: &str,
106) -> Result<Vec<u8>, ProtocolError> {
107    let child_nonce = decode_base64url_32("child_nonce", child_nonce)?;
108    Ok(proof_message(
109        AUTHORING_CHILD_PROOF_DOMAIN,
110        handshake_digest,
111        Some(&child_nonce),
112    ))
113}
114
115/// Returns the exact bytes authenticating one child-to-Host callback request.
116pub fn authoring_callback_proof_message(
117    session: &str,
118    method: &str,
119    params: &Value,
120) -> Result<Vec<u8>, ProtocolError> {
121    if !matches!(
122        method,
123        "lenso.call"
124            | "lenso.event.publish"
125            | "lenso.stream.open"
126            | "lenso.stream.send"
127            | "lenso.stream.receive"
128            | "lenso.stream.close_send"
129            | "lenso.stream.cancel"
130            | "lenso.settled"
131    ) {
132        return Err(ProtocolError::new("unsupported Authoring callback method"));
133    }
134    let session = decode_base64url_32("session", session)?;
135    let canonical_params = canonicalize_proof_value(params)?;
136    let mut message = Vec::with_capacity(
137        AUTHORING_CALLBACK_PROOF_DOMAIN.len()
138            + 1
139            + session.len()
140            + 1
141            + method.len()
142            + 1
143            + canonical_params.len(),
144    );
145    message.extend_from_slice(AUTHORING_CALLBACK_PROOF_DOMAIN);
146    message.push(0);
147    message.extend_from_slice(&session);
148    message.push(0);
149    message.extend_from_slice(method.as_bytes());
150    message.push(0);
151    message.extend_from_slice(&canonical_params);
152    Ok(message)
153}
154
155fn validate_loopback_http_origin(value: &str) -> Result<(), ProtocolError> {
156    let port = value
157        .strip_prefix("http://127.0.0.1:")
158        .or_else(|| value.strip_prefix("http://[::1]:"))
159        .and_then(|value| value.strip_suffix('/'))
160        .ok_or_else(|| {
161            ProtocolError::new("callback_origin must be an exact loopback HTTP origin")
162        })?;
163    if !port.as_bytes().first().is_some_and(u8::is_ascii_digit)
164        || port.starts_with('0')
165        || port
166            .parse::<u16>()
167            .ok()
168            .as_ref()
169            .is_none_or(|port| *port == 0)
170    {
171        return Err(ProtocolError::new(
172            "callback_origin must be an exact loopback HTTP origin",
173        ));
174    }
175    Ok(())
176}
177
178fn proof_message(domain: &[u8], digest: &[u8; 32], suffix: Option<&[u8; 32]>) -> Vec<u8> {
179    let mut message = Vec::with_capacity(domain.len() + 1 + 32 + suffix.map_or(0, |_| 32));
180    message.extend_from_slice(domain);
181    message.push(0);
182    message.extend_from_slice(digest);
183    if let Some(suffix) = suffix {
184        message.extend_from_slice(suffix);
185    }
186    message
187}
188
189fn write_canonical(value: &Value, output: &mut Vec<u8>) -> Result<(), ProtocolError> {
190    match value {
191        Value::Null => output.extend_from_slice(b"null"),
192        Value::Bool(true) => output.extend_from_slice(b"true"),
193        Value::Bool(false) => output.extend_from_slice(b"false"),
194        Value::String(value) => output.extend_from_slice(
195            serde_json::to_string(value)
196                .map_err(|error| ProtocolError::new(error.to_string()))?
197                .as_bytes(),
198        ),
199        Value::Number(number) => {
200            let encoded = if let Some(value) = number.as_u64() {
201                if value > MAX_SAFE_JSON_INTEGER {
202                    return Err(ProtocolError::new(
203                        "proof JSON integer exceeds the portable safe range",
204                    ));
205                }
206                value.to_string()
207            } else if let Some(value) = number.as_i64() {
208                if value.unsigned_abs() > MAX_SAFE_JSON_INTEGER {
209                    return Err(ProtocolError::new(
210                        "proof JSON integer exceeds the portable safe range",
211                    ));
212                }
213                value.to_string()
214            } else {
215                return Err(ProtocolError::new(
216                    "floating-point values are forbidden in proof JSON",
217                ));
218            };
219            output.extend_from_slice(encoded.as_bytes());
220        }
221        Value::Array(values) => {
222            output.push(b'[');
223            for (index, value) in values.iter().enumerate() {
224                if index > 0 {
225                    output.push(b',');
226                }
227                write_canonical(value, output)?;
228            }
229            output.push(b']');
230        }
231        Value::Object(values) => {
232            let mut entries = values.iter().collect::<Vec<_>>();
233            entries.sort_by(|(left, _), (right, _)| left.encode_utf16().cmp(right.encode_utf16()));
234            output.push(b'{');
235            for (index, (key, value)) in entries.into_iter().enumerate() {
236                if index > 0 {
237                    output.push(b',');
238                }
239                output.extend_from_slice(
240                    serde_json::to_string(key)
241                        .map_err(|error| ProtocolError::new(error.to_string()))?
242                        .as_bytes(),
243                );
244                output.push(b':');
245                write_canonical(value, output)?;
246            }
247            output.push(b'}');
248        }
249    }
250    Ok(())
251}