Skip to main content

loro_protocol/
elo.rs

1//! `%ELO` container and record header parsing (no crypto).
2//! Mirrors the TypeScript implementation in `packages/loro-protocol/src/e2ee.ts`
3//! for container decode and plaintext header parsing. This module is intentionally
4//! crypto-free; consumers can use the parsed `aad` (exact header bytes) and `iv`
5//! with their own AES-GCM bindings if desired.
6//! NOTE: `%ELO` support on the Rust side is work-in-progress; only the container
7//! and header parsing surface is considered stable today.
8
9use crate::bytes::BytesReader;
10
11#[derive(Debug, Clone, Copy, PartialEq, Eq)]
12#[repr(u8)]
13pub enum EloRecordKind {
14    DeltaSpan = 0x00,
15    Snapshot = 0x01,
16}
17
18#[derive(Debug, Clone, PartialEq, Eq)]
19pub struct EloDeltaHeader {
20    pub peer_id: Vec<u8>,
21    pub start: u64,
22    pub end: u64,
23    pub key_id: String,
24    pub iv: [u8; 12],
25}
26
27#[derive(Debug, Clone, PartialEq, Eq)]
28pub struct EloSnapshotHeader {
29    pub vv: Vec<(Vec<u8>, u64)>,
30    pub key_id: String,
31    pub iv: [u8; 12],
32}
33
34#[derive(Debug, Clone, PartialEq, Eq)]
35pub enum EloHeader {
36    Delta(EloDeltaHeader),
37    Snapshot(EloSnapshotHeader),
38}
39
40#[derive(Debug, Clone, PartialEq, Eq)]
41pub struct ParsedEloRecord<'a> {
42    pub kind: EloRecordKind,
43    pub header: EloHeader,
44    /// Exact header bytes as encoded on the wire; use as AAD for AES-GCM.
45    pub aad: &'a [u8],
46    /// Ciphertext bytes (ct||tag), as-is from the wire.
47    pub ct: &'a [u8],
48}
49
50/// Decode an ELO container into a list of record byte slices.
51/// The returned slices borrow from `data`.
52pub fn decode_elo_container<'a>(data: &'a [u8]) -> Result<Vec<&'a [u8]>, String> {
53    let mut r = BytesReader::new(data);
54    let n = usize::try_from(r.read_uleb128()?).map_err(|_| "length too large".to_string())?;
55    let mut out: Vec<&[u8]> = Vec::with_capacity(n);
56    for _ in 0..n {
57        out.push(r.read_var_bytes()?);
58    }
59    if r.remaining() != 0 {
60        return Err("ELO container has trailing bytes".into());
61    }
62    Ok(out)
63}
64
65/// Parse a single ELO record's plaintext header, returning header metadata, AAD
66/// (the exact header bytes), and a view of the ciphertext bytes.
67pub fn parse_elo_record_header<'a>(record: &'a [u8]) -> Result<ParsedEloRecord<'a>, String> {
68    let mut r = BytesReader::new(record);
69    let kind_byte = r.read_byte()?;
70    match kind_byte {
71        0x00 => parse_delta(&mut r, record),
72        0x01 => parse_snapshot(&mut r, record),
73        _ => Err(format!("Unknown ELO record kind: 0x{:02x}", kind_byte)),
74    }
75}
76
77fn parse_delta<'a>(
78    r: &mut BytesReader<'a>,
79    record: &'a [u8],
80) -> Result<ParsedEloRecord<'a>, String> {
81    let peer_id = r.read_var_bytes()?.to_vec();
82    let start = r.read_uleb128()?;
83    let end = r.read_uleb128()?;
84    let key_id = r.read_var_string()?;
85    let iv_bytes = r.read_var_bytes()?;
86    let aad_len = r.position();
87    let ct = r.read_var_bytes()?;
88    if r.remaining() != 0 {
89        return Err("ELO record trailing bytes".into());
90    }
91
92    // Invariants
93    if end <= start {
94        return Err("Invalid ELO delta span: end must be > start".into());
95    }
96    if iv_bytes.len() != 12 {
97        return Err("Invalid ELO delta span: IV must be 12 bytes".into());
98    }
99    if peer_id.len() > 64 {
100        return Err("Invalid ELO delta span: peerId too long".into());
101    }
102    if key_id.as_bytes().len() > 64 {
103        return Err("Invalid ELO delta span: keyId too long".into());
104    }
105
106    let mut iv = [0u8; 12];
107    iv.copy_from_slice(iv_bytes);
108
109    Ok(ParsedEloRecord {
110        kind: EloRecordKind::DeltaSpan,
111        header: EloHeader::Delta(EloDeltaHeader {
112            peer_id,
113            start,
114            end,
115            key_id,
116            iv,
117        }),
118        aad: &record[..aad_len],
119        ct,
120    })
121}
122
123fn parse_snapshot<'a>(
124    r: &mut BytesReader<'a>,
125    record: &'a [u8],
126) -> Result<ParsedEloRecord<'a>, String> {
127    let count =
128        usize::try_from(r.read_uleb128()?).map_err(|_| "vv length too large".to_string())?;
129    let mut vv: Vec<(Vec<u8>, u64)> = Vec::with_capacity(count);
130    for _ in 0..count {
131        let pid = r.read_var_bytes()?.to_vec();
132        let ctr = r.read_uleb128()?;
133        vv.push((pid, ctr));
134    }
135    let key_id = r.read_var_string()?;
136    let iv_bytes = r.read_var_bytes()?;
137    let aad_len = r.position();
138    let ct = r.read_var_bytes()?;
139    if r.remaining() != 0 {
140        return Err("ELO record trailing bytes".into());
141    }
142
143    if iv_bytes.len() != 12 {
144        return Err("Invalid ELO snapshot: IV must be 12 bytes".into());
145    }
146    if key_id.as_bytes().len() > 64 {
147        return Err("Invalid ELO snapshot: keyId too long".into());
148    }
149    // vv should be sorted by peer_id bytes ascending
150    if !is_sorted_by_bytes(&vv) {
151        return Err("Invalid ELO snapshot: vv not sorted by peer id bytes".into());
152    }
153
154    let mut iv = [0u8; 12];
155    iv.copy_from_slice(iv_bytes);
156
157    Ok(ParsedEloRecord {
158        kind: EloRecordKind::Snapshot,
159        header: EloHeader::Snapshot(EloSnapshotHeader { vv, key_id, iv }),
160        aad: &record[..aad_len],
161        ct,
162    })
163}
164
165fn is_sorted_by_bytes(vv: &[(Vec<u8>, u64)]) -> bool {
166    vv.windows(2).all(|w| {
167        let a = &w[0].0;
168        let b = &w[1].0;
169        compare_bytes(a, b) <= 0
170    })
171}
172
173fn compare_bytes(a: &[u8], b: &[u8]) -> i32 {
174    let n = a.len().min(b.len());
175    for i in 0..n {
176        let da = a[i];
177        let db = b[i];
178        if da != db {
179            return (da as i32) - (db as i32);
180        }
181    }
182    (a.len() as i32) - (b.len() as i32)
183}