Skip to main content

lean_ctx_cloud/sync/
records.rs

1// SPDX-License-Identifier: Apache-2.0
2//! Verifying what the server sends for a clone and a tail (SPEC-ENGINE
3//! §3.4.3, C0 2.0 section 6 `records`): the signed snapshot manifest, the
4//! segment record stream with its envelope Merkle root, and tail pages.
5//!
6//! Nothing of a segment is imported unless its record count, seq run and
7//! envelope root all match the signed manifest. Inside a matching segment
8//! an event whose signature or body commitment fails is kept with
9//! `sig_invalid` and never folded.
10
11use serde_json::{Map, Value};
12
13use crate::events::sign;
14use crate::replica::log::StoredEvent;
15use lean_ctx_protocol::cloud::{canonical_json, signing_input_without_signature};
16
17/// Signature domain of a snapshot manifest.
18pub const SNAPSHOT_DOMAIN: &str = "leanctx.cloud.snapshot.v1\n";
19
20/// Why a segment is refused (refetched once, then `segment_unavailable`).
21#[derive(Debug, Clone, PartialEq, Eq)]
22pub enum SegmentError {
23    Shape(String),
24    Count { expected: u64, got: u64 },
25    SeqRun,
26    Root,
27}
28
29impl std::fmt::Display for SegmentError {
30    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
31        match self {
32            Self::Shape(what) => write!(f, "segment record shape: {what}"),
33            Self::Count { expected, got } => {
34                write!(f, "segment holds {got} records, manifest says {expected}")
35            }
36            Self::SeqRun => f.write_str("segment seq run has a gap or does not match"),
37            Self::Root => f.write_str("segment envelope root does not match the manifest"),
38        }
39    }
40}
41
42/// `blake3(0x00 ‖ canonical_json(signed envelope))`.
43pub fn leaf(envelope: &Value) -> Result<[u8; 32], SegmentError> {
44    let canonical = canonical_json(envelope).map_err(|e| SegmentError::Shape(e.to_string()))?;
45    let mut h = blake3::Hasher::new();
46    h.update(&[0]);
47    h.update(&canonical);
48    Ok(*h.finalize().as_bytes())
49}
50
51/// The Merkle root over leaves in seq order: inner `blake3(0x01 ‖ l ‖ r)`,
52/// an odd last node promoted unchanged.
53pub fn root(leaves: &[[u8; 32]]) -> Option<[u8; 32]> {
54    let mut level = leaves.to_vec();
55    if level.is_empty() {
56        return None;
57    }
58    while level.len() > 1 {
59        level = level
60            .chunks(2)
61            .map(|pair| match pair {
62                [l, r] => {
63                    let mut h = blake3::Hasher::new();
64                    h.update(&[1]);
65                    h.update(l);
66                    h.update(r);
67                    *h.finalize().as_bytes()
68                }
69                [single] => *single,
70                _ => unreachable!("chunks of two"),
71            })
72            .collect();
73    }
74    level.first().copied()
75}
76
77/// Whether `manifest` carries a valid signature of the Cloud snapshot key
78/// `public_key` whose key id it names.
79pub fn manifest_verifies(manifest: &Value, public_key: &[u8; 32]) -> bool {
80    use ed25519_dalek::{Signature, Verifier as _, VerifyingKey};
81    if manifest.get("key_id").and_then(Value::as_str) != Some(sign::key_id(public_key).as_str()) {
82        return false;
83    }
84    let Some(sig) = manifest
85        .get("signature")
86        .and_then(Value::as_str)
87        .and_then(|s| hex::decode(s).ok())
88        .and_then(|b| <[u8; 64]>::try_from(b).ok())
89    else {
90        return false;
91    };
92    let (Ok(key), Ok(input)) = (
93        VerifyingKey::from_bytes(public_key),
94        signing_input_without_signature(SNAPSHOT_DOMAIN, manifest),
95    ) else {
96        return false;
97    };
98    key.verify(&input, &Signature::from_bytes(&sig)).is_ok()
99}
100
101/// A manifest's segment entry.
102#[derive(Debug, Clone, PartialEq, Eq)]
103pub struct SegmentMeta {
104    pub n: u64,
105    pub seq_from: u64,
106    pub seq_to: u64,
107    pub count: u64,
108    pub envelope_root: String,
109}
110
111pub fn segments(manifest: &Value) -> Result<Vec<SegmentMeta>, SegmentError> {
112    let list = manifest
113        .get("segments")
114        .and_then(Value::as_array)
115        .ok_or_else(|| SegmentError::Shape("manifest without segments".into()))?;
116    list.iter()
117        .map(|s| {
118            let n = |k: &str| {
119                s.get(k)
120                    .and_then(Value::as_u64)
121                    .ok_or_else(|| SegmentError::Shape(format!("segment {k}")))
122            };
123            Ok(SegmentMeta {
124                n: n("n")?,
125                seq_from: n("seq_from")?,
126                seq_to: n("seq_to")?,
127                count: n("count")?,
128                envelope_root: s
129                    .get("envelope_root")
130                    .and_then(Value::as_str)
131                    .ok_or_else(|| SegmentError::Shape("segment envelope_root".into()))?
132                    .to_string(),
133            })
134        })
135        .collect()
136}
137
138/// The whole event of a record: envelope, server fields and body merged.
139fn event_of(record: &Value) -> Result<Value, SegmentError> {
140    let mut event: Map<String, Value> = record
141        .get("envelope")
142        .and_then(Value::as_object)
143        .cloned()
144        .ok_or_else(|| SegmentError::Shape("record without envelope".into()))?;
145    if let Some(fields) = record.get("server_fields").and_then(Value::as_object) {
146        for (k, v) in fields {
147            event.insert(k.clone(), v.clone());
148        }
149    }
150    if let Some(body) = record.get("body") {
151        event.insert("body".into(), body.clone());
152    }
153    if record.get("purged").and_then(Value::as_bool) == Some(true) {
154        event.insert("purged".into(), Value::Bool(true));
155    }
156    Ok(Value::Object(event))
157}
158
159/// Check one received event: signature (by the caller's signer rules,
160/// SPEC-ENGINE §3.3.5) and, when it carries a body, the body commitment
161/// keyed with the place key. `true` when it may fold.
162pub fn event_verifies(
163    event: &Value,
164    pk_id: &[u8; 32],
165    signature_ok: &dyn Fn(&Value) -> bool,
166) -> bool {
167    if !signature_ok(event) {
168        return false;
169    }
170    let Some(body) = event.get("body").filter(|b| !b.is_null()) else {
171        return true;
172    };
173    sign::body_commit(pk_id, body).ok().as_deref()
174        == event.get("body_commit").and_then(Value::as_str)
175}
176
177/// Verify a segment's records against its manifest entry and turn them into
178/// events to store. Withheld stubs (`{seq, withheld: true, leaf}`) count
179/// for the root by their leaf and are not stored.
180pub fn import_segment(
181    meta: &SegmentMeta,
182    records: &[Value],
183    pk_id: &[u8; 32],
184    signature_ok: &dyn Fn(&Value) -> bool,
185) -> Result<Vec<StoredEvent>, SegmentError> {
186    if records.len() as u64 != meta.count {
187        return Err(SegmentError::Count {
188            expected: meta.count,
189            got: records.len() as u64,
190        });
191    }
192    let mut leaves = Vec::with_capacity(records.len());
193    let mut events = Vec::new();
194    for (i, record) in records.iter().enumerate() {
195        let seq = record
196            .get("seq")
197            .and_then(Value::as_u64)
198            .ok_or_else(|| SegmentError::Shape("record without seq".into()))?;
199        if seq != meta.seq_from + i as u64 {
200            return Err(SegmentError::SeqRun);
201        }
202        if record.get("withheld").and_then(Value::as_bool) == Some(true) {
203            let l = record
204                .get("leaf")
205                .and_then(Value::as_str)
206                .and_then(|s| hex::decode(s).ok())
207                .and_then(|b| <[u8; 32]>::try_from(b).ok())
208                .ok_or_else(|| SegmentError::Shape("stub record without leaf".into()))?;
209            leaves.push(l);
210            continue;
211        }
212        let envelope = record
213            .get("envelope")
214            .ok_or_else(|| SegmentError::Shape("record without envelope".into()))?;
215        leaves.push(leaf(envelope)?);
216        let event = event_of(record)?;
217        let ok = event_verifies(&event, pk_id, signature_ok);
218        events.push(StoredEvent {
219            seq,
220            event,
221            sig_invalid: !ok,
222        });
223    }
224    if records
225        .last()
226        .and_then(|r| r.get("seq"))
227        .and_then(Value::as_u64)
228        != Some(meta.seq_to)
229    {
230        return Err(SegmentError::SeqRun);
231    }
232    if root(&leaves).map(hex::encode).as_deref() != Some(meta.envelope_root.as_str()) {
233        return Err(SegmentError::Root);
234    }
235    Ok(events)
236}
237
238/// One tail page (E4): verified events and where the next page starts.
239#[derive(Debug, Clone, PartialEq)]
240pub struct TailPage {
241    pub events: Vec<StoredEvent>,
242    pub next_since: Option<u64>,
243    pub head_seq: u64,
244    pub epoch: Option<u64>,
245}
246
247pub fn tail_page(
248    page: &Value,
249    pk_id: &[u8; 32],
250    signature_ok: &dyn Fn(&Value) -> bool,
251) -> Result<TailPage, SegmentError> {
252    let list = page
253        .get("events")
254        .and_then(Value::as_array)
255        .ok_or_else(|| SegmentError::Shape("tail without events".into()))?;
256    let mut events = Vec::with_capacity(list.len());
257    for event in list {
258        let seq = event
259            .get("seq")
260            .and_then(Value::as_u64)
261            .ok_or_else(|| SegmentError::Shape("tail event without seq".into()))?;
262        events.push(StoredEvent {
263            seq,
264            event: event.clone(),
265            sig_invalid: !event_verifies(event, pk_id, signature_ok),
266        });
267    }
268    Ok(TailPage {
269        events,
270        next_since: page.get("next_since").and_then(Value::as_u64),
271        head_seq: page.get("head_seq").and_then(Value::as_u64).unwrap_or(0),
272        epoch: page.get("epoch").and_then(Value::as_u64),
273    })
274}
275
276#[cfg(test)]
277#[path = "records_tests.rs"]
278mod tests;