Skip to main content

macula_rust/frame/
request.rs

1//! Requests (D25): a CALL or STREAM_OPEN, a signed object under
2//! MACULA-PQ-REQUEST-V1 by the caller's identity key, with routing fields
3//! outside the signature.
4
5use sha2::{Digest, Sha384};
6
7use crate::cbor::Value;
8use crate::node_key::{node_id_of, NodeKey};
9use crate::profile::Profile;
10use crate::signed_object::{sign_object, verify_object};
11
12use super::sealed::{clear_or_sealed, sealed_field, Sealed, SealedContext};
13use super::{
14    bounded_text, check_payload, entry, fixed, has_fields, identity_signer, object_refusal,
15    protocol_uint, read_fields, received_frame, text_of, uint, FrameError, Rule, StreamMode,
16    MAX_PROCEDURE_BYTES, MAX_PROTOCOL_INT, PROTOCOL_VERSION, REQUEST_LABEL,
17};
18
19/// The bound on a request's proofs (D7, chain transport): eight tokens, 256
20/// KiB in all, none repeated.
21pub const MAX_PROOFS: usize = 8;
22pub const MAX_PROOFS_BYTES: usize = 256 * 1024;
23
24const CALL: &str = "call";
25const STREAM_OPEN: &str = "stream_open";
26
27/// A request's frame type.
28#[derive(Debug, Clone, Copy, PartialEq, Eq)]
29pub enum RequestType {
30    Call,
31    StreamOpen,
32}
33
34impl RequestType {
35    fn name(self) -> &'static str {
36        match self {
37            RequestType::Call => CALL,
38            RequestType::StreamOpen => STREAM_OPEN,
39        }
40    }
41}
42
43/// A request as its caller gives it: `sealed` is the payload sealed end to
44/// end, carried in place of `payload`, which is then not sent, and `None` for
45/// a clear request; `mode` is a STREAM_OPEN's and `None` for a CALL; `token` is `None` when the request carries none; `proofs` are the
46/// tokens of the delegation chain the token rests on, empty for none;
47/// `source_route` and `retry_budget` are routing fields outside the
48/// signature.
49#[derive(Debug, Clone, PartialEq)]
50pub struct RequestSpec {
51    pub request_id: [u8; 16],
52    pub realm: [u8; 32],
53    pub procedure: String,
54    pub target: [u8; 32],
55    pub deadline: u64,
56    pub payload: Value,
57    pub sealed: Option<Sealed>,
58    pub mode: Option<StreamMode>,
59    pub token: Option<Vec<u8>>,
60    pub proofs: Vec<Vec<u8>>,
61    pub source_route: Option<Vec<u8>>,
62    pub retry_budget: Option<u64>,
63}
64
65/// A CALL or STREAM_OPEN whose request verified: its fields, the caller's key
66/// as carried, and `request_hash`, the SHA-384 of its tbs, which replies and
67/// stream frames name. A sealed request's payload is in `sealed`, and its
68/// `payload` is null.
69#[derive(Debug, Clone, PartialEq)]
70pub struct VerifiedRequest {
71    pub frame_type: RequestType,
72    pub key: Vec<u8>,
73    pub request_hash: [u8; 48],
74    pub caller: [u8; 32],
75    pub request_id: [u8; 16],
76    pub realm: [u8; 32],
77    pub procedure: String,
78    pub target: [u8; 32],
79    pub deadline: u64,
80    pub payload: Value,
81    pub sealed: Option<Sealed>,
82    pub mode: Option<StreamMode>,
83    pub token: Option<Vec<u8>>,
84    pub proofs: Option<Vec<Vec<u8>>>,
85}
86
87/// Signs a CALL with the caller's identity key: caller is the key's key id.
88/// Refused, in this order: a key that is not an identity key, a procedure over
89/// 512 bytes, a sealed payload of another shape than a request's or a clear
90/// payload the wire cannot carry, a deadline or retry budget of
91/// 2^53 or more, or a stream mode, which a CALL does not carry; then proofs
92/// outside their bound.
93pub fn sign_call(spec: &RequestSpec, key: &NodeKey) -> Result<Value, FrameError> {
94    sign_request(RequestType::Call, spec, key)
95}
96
97/// Signs a STREAM_OPEN, which carries `spec.mode`, with [`sign_call`]'s
98/// checks, the last of them refusing no mode.
99pub fn sign_stream_open(spec: &RequestSpec, key: &NodeKey) -> Result<Value, FrameError> {
100    sign_request(RequestType::StreamOpen, spec, key)
101}
102
103fn sign_request(
104    frame_type: RequestType,
105    spec: &RequestSpec,
106    key: &NodeKey,
107) -> Result<Value, FrameError> {
108    identity_signer(key)?;
109    bounded_text("procedure", spec.procedure.as_bytes(), MAX_PROCEDURE_BYTES)?;
110    match &spec.sealed {
111        Some(sealed) if !sealed.shaped(SealedContext::Request) => {
112            return Err(FrameError::SealedShape)
113        }
114        Some(_) => {}
115        None => check_payload(&spec.payload)?,
116    }
117    if spec.deadline >= MAX_PROTOCOL_INT || spec.retry_budget.is_some_and(|b| b >= MAX_PROTOCOL_INT)
118    {
119        return Err(FrameError::OutOfRange(
120            "a deadline or retry budget of 2^53 or more".into(),
121        ));
122    }
123    match (frame_type, spec.mode) {
124        (RequestType::Call, Some(_)) => {
125            return Err(FrameError::OutOfRange(
126                "a CALL carries no stream mode".into(),
127            ))
128        }
129        (RequestType::StreamOpen, None) => {
130            return Err(FrameError::OutOfRange(
131                "a STREAM_OPEN carries one of the three stream modes".into(),
132            ))
133        }
134        _ => {}
135    }
136    let proofs = proofs_value(&spec.proofs);
137    if !proofs_within_bound(&proofs) {
138        return Err(FrameError::ProofsOutOfBound);
139    }
140    let mut fields = vec![
141        entry("frame_type", Value::text(frame_type.name())),
142        entry("caller", Value::Bytes(key.key_id().to_vec())),
143        entry("request_id", Value::Bytes(spec.request_id.to_vec())),
144        entry("realm", Value::Bytes(spec.realm.to_vec())),
145        entry("procedure", Value::text(spec.procedure.clone())),
146        entry("target", Value::Bytes(spec.target.to_vec())),
147        entry("deadline", uint(spec.deadline)),
148        match &spec.sealed {
149            Some(sealed) => entry("sealed", sealed.value()),
150            None => entry("payload", spec.payload.clone()),
151        },
152    ];
153    if let Some(mode) = spec.mode {
154        fields.push(entry("mode", Value::text(mode.name())));
155    }
156    if let Some(token) = &spec.token {
157        fields.push(entry("token", Value::Bytes(token.clone())));
158    }
159    if !spec.proofs.is_empty() {
160        fields.push(entry("proofs", proofs));
161    }
162    let request = sign_object(REQUEST_LABEL, &fields, key).map_err(object_refusal)?;
163    let mut frame = vec![
164        entry("version", Value::Int(i128::from(PROTOCOL_VERSION))),
165        entry("frame_type", Value::text(frame_type.name())),
166        entry("request", request.to_value()),
167    ];
168    if let Some(route) = &spec.source_route {
169        frame.push(entry("source_route", Value::Bytes(route.clone())));
170    }
171    if let Some(budget) = spec.retry_budget {
172        frame.push(entry("retry_budget", uint(budget)));
173    }
174    Ok(Value::Map(frame))
175}
176
177const REQUEST_ROUTES: &[(&str, Rule)] = &[
178    ("source_route", Rule::AnyBytes),
179    ("retry_budget", Rule::ProtocolUint),
180];
181
182/// Verifies a received CALL or STREAM_OPEN under the connection's `profile`:
183/// the frame's shape, the request's signature and fields, and caller as the
184/// key id of its key. A station checks this before it routes, and a provider
185/// before its own checks, which stay with the caller: its node_id as target,
186/// the deadline window, replays and tokens.
187pub fn verify_request(frame: &Value, profile: Profile) -> Result<VerifiedRequest, FrameError> {
188    let (frame_type, object) = received_frame(
189        frame,
190        "request",
191        Rule::CarriedObject,
192        REQUEST_ROUTES,
193        &[CALL, STREAM_OPEN],
194    )
195    .ok_or(FrameError::Malformed)?;
196    let frame_type = if frame_type == CALL {
197        RequestType::Call
198    } else {
199        RequestType::StreamOpen
200    };
201    let verified = verify_object(REQUEST_LABEL, &object, profile).map_err(object_refusal)?;
202    let fields =
203        read_fields(&verified.fields, &request_table(frame_type)).ok_or(FrameError::Malformed)?;
204    let has_mode = fields.contains_key("mode");
205    if !has_fields(
206        &fields,
207        &[
208            "frame_type",
209            "caller",
210            "request_id",
211            "realm",
212            "procedure",
213            "target",
214            "deadline",
215        ],
216    ) || !clear_or_sealed(&fields, "payload")
217        || has_mode != (frame_type == RequestType::StreamOpen)
218    {
219        return Err(FrameError::Malformed);
220    }
221    let request = VerifiedRequest {
222        frame_type,
223        request_hash: Sha384::digest(&verified.tbs).into(),
224        caller: fixed(&fields["caller"]),
225        request_id: fixed(&fields["request_id"]),
226        realm: fixed(&fields["realm"]),
227        procedure: text_of(&fields["procedure"]),
228        target: fixed(&fields["target"]),
229        deadline: protocol_uint(&fields["deadline"]).unwrap_or(0),
230        payload: fields.get("payload").cloned().unwrap_or(Value::Null),
231        sealed: sealed_field(&fields, SealedContext::Request),
232        mode: fields
233            .get("mode")
234            .and_then(|m| StreamMode::parse(&text_of(m))),
235        token: fields.get("token").map(super::bytes_of),
236        proofs: fields.get("proofs").map(|p| match p {
237            Value::List(items) => items.iter().map(super::bytes_of).collect(),
238            _ => Vec::new(),
239        }),
240        key: verified.key,
241    };
242    if request.caller != node_id_of(&request.key, profile) {
243        return Err(FrameError::KeyIdMismatch);
244    }
245    Ok(request)
246}
247
248fn request_table(frame_type: RequestType) -> Vec<(&'static str, Rule)> {
249    vec![
250        (
251            "frame_type",
252            Rule::TextIn(match frame_type {
253                RequestType::Call => &[CALL],
254                RequestType::StreamOpen => &[STREAM_OPEN],
255            }),
256        ),
257        ("alg", Rule::Any),
258        ("caller", Rule::BytesOf(32)),
259        ("request_id", Rule::BytesOf(16)),
260        ("realm", Rule::BytesOf(32)),
261        ("procedure", Rule::TextWithin(MAX_PROCEDURE_BYTES)),
262        ("target", Rule::BytesOf(32)),
263        ("deadline", Rule::ProtocolUint),
264        ("payload", Rule::Any),
265        ("sealed", Rule::Sealed(SealedContext::Request)),
266        (
267            "mode",
268            Rule::TextIn(&["server_stream", "client_stream", "bidi"]),
269        ),
270        ("token", Rule::AnyBytes),
271        ("proofs", Rule::Proofs),
272    ]
273}
274
275/// Whether `fields` read as a CALL's under the request table, where a
276/// delegation chain's proofs are bounded: the reading the shared decoding
277/// rule vectors name `request_fields`.
278pub fn request_fields_accepted(fields: &Value) -> bool {
279    read_fields(fields, &request_table(RequestType::Call)).is_some()
280}
281
282fn proofs_value(proofs: &[Vec<u8>]) -> Value {
283    Value::List(proofs.iter().map(|p| Value::Bytes(p.clone())).collect())
284}
285
286/// macula's bytes_set rule for proofs: a list of at most [`MAX_PROOFS`] byte
287/// strings, [`MAX_PROOFS_BYTES`] in all, none repeated.
288pub(super) fn proofs_within_bound(v: &Value) -> bool {
289    let Value::List(items) = v else {
290        return false;
291    };
292    if items.len() > MAX_PROOFS {
293        return false;
294    }
295    let mut seen = std::collections::HashSet::with_capacity(items.len());
296    let mut total = 0;
297    for item in items {
298        let Value::Bytes(b) = item else {
299            return false;
300        };
301        if !seen.insert(b.as_slice()) {
302            return false;
303        }
304        total += b.len();
305    }
306    total <= MAX_PROOFS_BYTES
307}