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 method != "lenso.call" && method != "lenso.settled" {
122        return Err(ProtocolError::new("unsupported Authoring callback method"));
123    }
124    let session = decode_base64url_32("session", session)?;
125    let canonical_params = canonicalize_proof_value(params)?;
126    let mut message = Vec::with_capacity(
127        AUTHORING_CALLBACK_PROOF_DOMAIN.len()
128            + 1
129            + session.len()
130            + 1
131            + method.len()
132            + 1
133            + canonical_params.len(),
134    );
135    message.extend_from_slice(AUTHORING_CALLBACK_PROOF_DOMAIN);
136    message.push(0);
137    message.extend_from_slice(&session);
138    message.push(0);
139    message.extend_from_slice(method.as_bytes());
140    message.push(0);
141    message.extend_from_slice(&canonical_params);
142    Ok(message)
143}
144
145fn validate_loopback_http_origin(value: &str) -> Result<(), ProtocolError> {
146    let port = value
147        .strip_prefix("http://127.0.0.1:")
148        .or_else(|| value.strip_prefix("http://[::1]:"))
149        .and_then(|value| value.strip_suffix('/'))
150        .ok_or_else(|| {
151            ProtocolError::new("callback_origin must be an exact loopback HTTP origin")
152        })?;
153    if !port.as_bytes().first().is_some_and(u8::is_ascii_digit)
154        || port.starts_with('0')
155        || port
156            .parse::<u16>()
157            .ok()
158            .as_ref()
159            .is_none_or(|port| *port == 0)
160    {
161        return Err(ProtocolError::new(
162            "callback_origin must be an exact loopback HTTP origin",
163        ));
164    }
165    Ok(())
166}
167
168fn proof_message(domain: &[u8], digest: &[u8; 32], suffix: Option<&[u8; 32]>) -> Vec<u8> {
169    let mut message = Vec::with_capacity(domain.len() + 1 + 32 + suffix.map_or(0, |_| 32));
170    message.extend_from_slice(domain);
171    message.push(0);
172    message.extend_from_slice(digest);
173    if let Some(suffix) = suffix {
174        message.extend_from_slice(suffix);
175    }
176    message
177}
178
179fn write_canonical(value: &Value, output: &mut Vec<u8>) -> Result<(), ProtocolError> {
180    match value {
181        Value::Null => output.extend_from_slice(b"null"),
182        Value::Bool(true) => output.extend_from_slice(b"true"),
183        Value::Bool(false) => output.extend_from_slice(b"false"),
184        Value::String(value) => output.extend_from_slice(
185            serde_json::to_string(value)
186                .map_err(|error| ProtocolError::new(error.to_string()))?
187                .as_bytes(),
188        ),
189        Value::Number(number) => {
190            let encoded = if let Some(value) = number.as_u64() {
191                if value > MAX_SAFE_JSON_INTEGER {
192                    return Err(ProtocolError::new(
193                        "proof JSON integer exceeds the portable safe range",
194                    ));
195                }
196                value.to_string()
197            } else if let Some(value) = number.as_i64() {
198                if value.unsigned_abs() > MAX_SAFE_JSON_INTEGER {
199                    return Err(ProtocolError::new(
200                        "proof JSON integer exceeds the portable safe range",
201                    ));
202                }
203                value.to_string()
204            } else {
205                return Err(ProtocolError::new(
206                    "floating-point values are forbidden in proof JSON",
207                ));
208            };
209            output.extend_from_slice(encoded.as_bytes());
210        }
211        Value::Array(values) => {
212            output.push(b'[');
213            for (index, value) in values.iter().enumerate() {
214                if index > 0 {
215                    output.push(b',');
216                }
217                write_canonical(value, output)?;
218            }
219            output.push(b']');
220        }
221        Value::Object(values) => {
222            let mut entries = values.iter().collect::<Vec<_>>();
223            entries.sort_by(|(left, _), (right, _)| left.encode_utf16().cmp(right.encode_utf16()));
224            output.push(b'{');
225            for (index, (key, value)) in entries.into_iter().enumerate() {
226                if index > 0 {
227                    output.push(b',');
228                }
229                output.extend_from_slice(
230                    serde_json::to_string(key)
231                        .map_err(|error| ProtocolError::new(error.to_string()))?
232                        .as_bytes(),
233                );
234                output.push(b':');
235                write_canonical(value, output)?;
236            }
237            output.push(b'}');
238        }
239    }
240    Ok(())
241}