Skip to main content

weirdnet_sync/
record.rs

1//! Record values larger than one page, and values sealed per record.
2//!
3//! A [`LogEntry`]'s `op` is what every version of this crate reads. Since 0.4 an entry
4//! may also carry a [`Value`]: then `op` is only a fallback (empty, or a preview the
5//! application chose) and the full value is in the `Value`, either inline (`body`) or
6//! split into content-addressed chunks ([`Blob`]). Older peers ignore the field, keep
7//! the fallback and never see a chunk, so nothing they hold changes meaning.
8//!
9//! Chunks are ordinary log entries of the companion type [`chunk_type`]`(typ)`
10//! (`<typ>#chunks`), keyed by the BLAKE3 hash of their bytes. They are pulled right after
11//! their type ([`Limits::eager_chunks`]) or on demand ([`crate::pull_chunks`]), and
12//! reassembled only when every chunk and the whole value match their hashes.
13//!
14//! A type configured [`RecordOptions::sealed`] has every value sealed under a key derived
15//! for that record from the head epoch key ([`record_key`]). Only members of the head
16//! rotation hold that key, so a device revoked before the write cannot open it, even
17//! with the seed and every older key. Members keep older epoch keys and admitted devices
18//! receive them, so values sealed before a rotation stay readable;
19//! [`crate::SyncState::reseal_stale`] moves them to the head key. Sealing happens before
20//! chunking, so chunks of a sealed value are ciphertext.
21//!
22//! Since 0.8.4 a value may instead be sealed under a key derived from the type's
23//! [`SyncKey`] under the head rotation ([`scoped_record_key`]), which a
24//! service device granted the type holds ([`crate::EpochKeys::get_scoped`]) without any
25//! epoch key. The rule ([`crate::SyncState::seals_scoped`]): a service device always seals
26//! type-scoped; a full device seals type-scoped while an active service device is granted
27//! the type ([`crate::Roster::service_granted`]) and with the epoch key otherwise, so 0.7.1
28//! to 0.8.3 devices keep reading what it writes when no service device shares the type.
29//! Readers try both keys, so no marker goes on the wire. A service device revoked before a
30//! rotation gets no scoped key for it and cannot open what is sealed under it.
31use crate::error::{Result, SyncError};
32use crate::log::{LogEntry, OpLog};
33use crate::protocol::{KeyRef, PAGE_BUDGET};
34use crate::rotation::KeyStatus;
35use crate::seal::SyncKey;
36use serde::{Deserialize, Serialize};
37use std::borrow::Cow;
38use std::collections::BTreeMap;
39use weirdnet_keys::{Key32, Sealed, kdf};
40use zeroize::Zeroizing;
41
42/// Suffix of the companion type that carries a type's chunks.
43pub const CHUNK_SUFFIX: &str = "#chunks";
44
45/// Newest [`Value`] format this crate reads.
46pub const VALUE_VERSION: u32 = 1;
47
48/// Largest chunk (and inline value) that still fits a page with room to spare.
49pub const CHUNK_MAX: usize = PAGE_BUDGET - 4 * 1024;
50
51/// The companion type holding `typ`'s chunks.
52pub fn chunk_type(typ: &str) -> String {
53    format!("{typ}{CHUNK_SUFFIX}")
54}
55
56pub fn is_chunk_type(typ: &str) -> bool {
57    typ.ends_with(CHUNK_SUFFIX)
58}
59
60/// The type a companion chunk type belongs to.
61pub fn base_type(typ: &str) -> Option<&str> {
62    typ.strip_suffix(CHUNK_SUFFIX)
63}
64
65/// Per-type size limits for [`crate::SyncState::write`].
66#[derive(Debug, Clone, PartialEq, Eq)]
67pub struct Limits {
68    /// Values (after sealing) up to this size go inline in one entry; larger ones are chunked.
69    pub inline_max: usize,
70    /// Chunk size for larger values.
71    pub chunk_size: usize,
72    /// Largest value accepted at all.
73    pub record_max: usize,
74    /// `pull_from` also pulls this type's chunks when an entry is still missing some.
75    /// Off: the application calls [`crate::pull_chunks`] when it needs the value.
76    pub eager_chunks: bool,
77}
78
79impl Default for Limits {
80    fn default() -> Self {
81        Self { inline_max: 32 * 1024, chunk_size: 48 * 1024, record_max: 16 * 1024 * 1024, eager_chunks: true }
82    }
83}
84
85impl Limits {
86    pub fn check(&self) -> Result<()> {
87        let max_chunks = self.record_max.div_ceil(self.chunk_size.max(1));
88        if self.chunk_size < 1024 || self.chunk_size > CHUNK_MAX || self.inline_max > CHUNK_MAX || max_chunks * 32 > CHUNK_MAX {
89            return Err(SyncError::Protocol(format!(
90                "limits out of range: chunk_size 1 KiB..={CHUNK_MAX}, inline_max <= {CHUNK_MAX}, record_max / chunk_size * 32 <= {CHUNK_MAX}"
91            )));
92        }
93        Ok(())
94    }
95}
96
97/// How a record type is written: sealed or not, and its limits.
98#[derive(Debug, Clone, Default, PartialEq, Eq)]
99pub struct RecordOptions {
100    /// Seal every value under a per-record key from the head rotation (its epoch key, or
101    /// since 0.8.4 the type's scoped key; see [`crate::SyncState::seals_scoped`]).
102    pub sealed: bool,
103    pub limits: Limits,
104}
105
106/// The full value of an entry whose `op` is only a fallback.
107#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
108pub struct Value {
109    /// Format version; a reader refuses one newer than [`VALUE_VERSION`].
110    pub v: u32,
111    /// Set when the payload is sealed (see [`SealInfo`]).
112    #[serde(default, skip_serializing_if = "Option::is_none")]
113    pub seal: Option<SealInfo>,
114    /// The payload, when it is inline.
115    #[serde(default, skip_serializing_if = "Vec::is_empty", with = "crate::bytes")]
116    pub body: Vec<u8>,
117    /// The payload, when it is chunked.
118    #[serde(default, skip_serializing_if = "Option::is_none")]
119    pub blob: Option<Blob>,
120}
121
122/// Which key a sealed payload is under: the rotation `key` at `epoch`, and the nonce.
123#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
124pub struct SealInfo {
125    pub epoch: u32,
126    pub key: String,
127    #[serde(with = "crate::bytes")]
128    pub nonce: Vec<u8>,
129}
130
131/// A chunked payload: its length, BLAKE3 hash, and the chunk hashes in order.
132#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
133pub struct Blob {
134    pub len: u64,
135    #[serde(with = "crate::bytes")]
136    pub hash: Vec<u8>,
137    /// Concatenated 32-byte chunk hashes.
138    #[serde(with = "crate::bytes")]
139    pub chunks: Vec<u8>,
140}
141
142impl Blob {
143    pub fn chunk_hashes(&self) -> impl Iterator<Item = &[u8]> {
144        self.chunks.chunks(32)
145    }
146
147    pub fn chunk_ids(&self) -> Vec<String> {
148        self.chunk_hashes().map(hex::encode).collect()
149    }
150}
151
152impl Value {
153    /// Rough encoded size, for page budgeting.
154    pub fn wire_size(&self) -> usize {
155        96 + self.body.len() + self.blob.as_ref().map_or(0, |b| 64 + b.chunks.len()) + self.seal.as_ref().map_or(0, |s| 64 + s.key.len())
156    }
157}
158
159/// What [`crate::SyncState::read`] found.
160#[derive(Debug, Clone, PartialEq, Eq)]
161pub enum RecordValue {
162    /// The full value.
163    Ready(zeroize::Zeroizing<Vec<u8>>),
164    /// Chunks not held yet (hex hashes); pull them and read again.
165    Pending { missing: Vec<String> },
166}
167
168impl RecordValue {
169    pub fn ready(self) -> Option<zeroize::Zeroizing<Vec<u8>>> {
170        match self {
171            RecordValue::Ready(v) => Some(v),
172            RecordValue::Pending { .. } => None,
173        }
174    }
175}
176
177/// One chunk of a payload: its BLAKE3 hash and bytes.
178pub type Chunk<'a> = ([u8; 32], &'a [u8]);
179
180/// Split a payload into chunks of `chunk_size`; returns the blob and the chunks.
181pub fn split(payload: &[u8], chunk_size: usize) -> (Blob, Vec<Chunk<'_>>) {
182    let parts: Vec<Chunk<'_>> = payload.chunks(chunk_size.max(1)).map(|c| (*blake3::hash(c).as_bytes(), c)).collect();
183    let chunks = parts.iter().flat_map(|(h, _)| h.iter().copied()).collect();
184    (Blob { len: payload.len() as u64, hash: blake3::hash(payload).as_bytes().to_vec(), chunks }, parts)
185}
186
187/// Reassemble a blob from `log`'s chunks of `typ`, checking every chunk hash, the length
188/// and the whole hash.
189pub fn assemble(log: &OpLog, typ: &str, blob: &Blob) -> Result<RecordValue> {
190    if !blob.chunks.len().is_multiple_of(32) || blob.hash.len() != 32 {
191        return Err(SyncError::Protocol("malformed blob".into()));
192    }
193    let ctyp = chunk_type(typ);
194    let mut missing = Vec::new();
195    let mut out = zeroize::Zeroizing::new(Vec::with_capacity(blob.len.min(64 * 1024 * 1024) as usize));
196    for h in blob.chunk_hashes() {
197        match log.chunk(&ctyp, h) {
198            Some(bytes) if missing.is_empty() => out.extend_from_slice(bytes),
199            Some(_) => {}
200            None => missing.push(hex::encode(h)),
201        }
202    }
203    if !missing.is_empty() {
204        missing.dedup();
205        return Ok(RecordValue::Pending { missing });
206    }
207    if out.len() as u64 != blob.len || blake3::hash(&out).as_bytes()[..] != blob.hash[..] {
208        return Err(SyncError::Protocol("blob does not match its hash".into()));
209    }
210    Ok(RecordValue::Ready(out))
211}
212
213/// The payload of an entry's value: inline body, or the reassembled blob.
214pub(crate) fn payload(log: &OpLog, e: &LogEntry, v: &Value) -> Result<RecordValue> {
215    if v.v > VALUE_VERSION {
216        return Err(SyncError::Protocol(format!("value format {} is newer than {VALUE_VERSION}", v.v)));
217    }
218    match &v.blob {
219        Some(b) => assemble(log, &e.typ, b),
220        None => Ok(RecordValue::Ready(zeroize::Zeroizing::new(v.body.clone()))),
221    }
222}
223
224impl crate::net::SyncState {
225    /// Set how `typ` is written. Adds `typ` to [`crate::SyncState::types`] if missing.
226    pub fn configure(&mut self, typ: &str, opts: RecordOptions) -> Result<()> {
227        opts.limits.check()?;
228        if is_chunk_type(typ) {
229            return Err(SyncError::Protocol("chunk types are not configured directly".into()));
230        }
231        if !self.types.iter().any(|t| t == typ) {
232            self.types.push(typ.to_string());
233        }
234        self.records.insert(typ.to_string(), opts);
235        Ok(())
236    }
237
238    /// The options for `typ` ([`RecordOptions::default`] when not configured).
239    pub fn options(&self, typ: &str) -> RecordOptions {
240        self.records.get(typ).cloned().unwrap_or_default()
241    }
242
243    /// A local write of a whole value: sealed when the type is sealed, chunked when it
244    /// is larger than [`Limits::inline_max`]. Older peers see an empty `op` for a
245    /// sealed or chunked value; use [`crate::SyncState::write_with_fallback`] to give
246    /// them something. Returns the entry's seq.
247    pub fn write(&mut self, now_ms: u64, typ: &str, record_id: &str, value: &[u8]) -> Result<u64> {
248        self.write_with_fallback(now_ms, typ, record_id, value, Vec::new())
249    }
250
251    /// Like [`crate::SyncState::write`], with the `op` older peers (and apps that
252    /// do not call [`crate::SyncState::read`]) see when the value is sealed or chunked,
253    /// for example a clipped preview. A value written plain ignores `fallback`. The
254    /// fallback itself is never sealed: for a sealed type, leave it empty or make it
255    /// something safe to show.
256    pub fn write_with_fallback(&mut self, now_ms: u64, typ: &str, record_id: &str, value: &[u8], fallback: Vec<u8>) -> Result<u64> {
257        if is_chunk_type(typ) {
258            return Err(SyncError::Protocol("chunk types are written by the crate".into()));
259        }
260        let opts = self.options(typ);
261        let limits = &opts.limits;
262        if value.len() > limits.record_max {
263            return Err(SyncError::Protocol(format!("value of {} bytes is over record_max {}", value.len(), limits.record_max)));
264        }
265        if fallback.len() > limits.inline_max {
266            return Err(SyncError::Protocol("fallback is over inline_max".into()));
267        }
268        let (seal, payload) = self.seal_payload(&opts, typ, record_id, value)?;
269        if seal.is_none() && payload.len() <= limits.inline_max {
270            return Ok(self.local_op(now_ms, typ, record_id, payload.to_vec()));
271        }
272        let mut v = Value { v: VALUE_VERSION, seal, body: Vec::new(), blob: None };
273        if payload.len() <= limits.inline_max {
274            v.body = payload.to_vec();
275        } else {
276            let ctyp = chunk_type(typ);
277            let (blob, parts) = split(&payload, limits.chunk_size);
278            for (h, bytes) in parts {
279                if !self.log.has_own_chunk(&self.our_node, &ctyp, &h) {
280                    self.local_op(now_ms, &ctyp, &hex::encode(h), bytes.to_vec());
281                }
282            }
283            v.blob = Some(blob);
284        }
285        let hlc = self.tick(now_ms);
286        Ok(self.log.append_value(self.our_node.clone(), hlc, typ, record_id, fallback, v).seq)
287    }
288
289    /// The full value of `e`: its `op`, its inline value, or its reassembled chunks,
290    /// opened when sealed. `Pending` lists chunks still to pull. An entry of a sealed
291    /// type that is not sealed is refused.
292    pub fn read(&self, e: &LogEntry) -> Result<RecordValue> {
293        self.read_scheme(e).map(|(v, _)| v)
294    }
295
296    /// [`crate::SyncState::read`], plus whether a sealed value opened under the
297    /// type-scoped record key (`Some(true)`), the epoch key (`Some(false)`), or is not
298    /// sealed or not ready (`None`).
299    fn read_scheme(&self, e: &LogEntry) -> Result<(RecordValue, Option<bool>)> {
300        let sealed_type = self.options(&e.typ).sealed;
301        let Some(v) = &e.value else {
302            if sealed_type {
303                return Err(SyncError::Protocol("unsealed entry in a sealed type".into()));
304            }
305            return Ok((RecordValue::Ready(zeroize::Zeroizing::new(e.op.clone())), None));
306        };
307        if sealed_type && v.seal.is_none() {
308            return Err(SyncError::Protocol("unsealed entry in a sealed type".into()));
309        }
310        match payload(&self.log, e, v)? {
311            RecordValue::Ready(p) => match &v.seal {
312                Some(s) => {
313                    let (plain, scoped) = self.open_payload(s, e, &p)?;
314                    Ok((RecordValue::Ready(plain), Some(scoped)))
315                }
316                None => Ok((RecordValue::Ready(p), None)),
317            },
318            pending => Ok((pending, None)),
319        }
320    }
321}
322
323/// Per-record key: `HKDF-SHA256(epoch key, salt = user id,
324/// info = weirdnet-sync/v1/record/<type>/e<n>/k<rotation id>/<record id>)`.
325pub fn record_key(epoch_key: &Key32, user_id: &str, typ: &str, record_id: &str, epoch: u32, id: &str) -> Result<Key32> {
326    let info = format!("weirdnet-sync/v1/record/{typ}/e{epoch}/k{id}/{record_id}");
327    Ok(kdf::hkdf(&epoch_key.0, Some(user_id.as_bytes()), info.as_bytes())?)
328}
329
330/// Which record a sealed value belongs to: its type, record id and writer node.
331#[derive(Debug, Clone, Copy, PartialEq, Eq)]
332pub struct RecordRef<'a> {
333    pub typ: &'a str,
334    pub record_id: &'a str,
335    pub node: &'a str,
336}
337
338impl<'a> RecordRef<'a> {
339    pub fn of(e: &'a LogEntry) -> Self {
340        Self { typ: &e.typ, record_id: &e.record_id, node: &e.node_id.0 }
341    }
342}
343
344/// Associated data of a sealed record: type, epoch, rotation, writer node and record id,
345/// so a sealed value cannot be moved to another record, type, key or writer.
346pub fn record_aad(r: &RecordRef<'_>, epoch: u32, id: &str) -> Vec<u8> {
347    format!("weirdnet-sync/v1/record|v{VALUE_VERSION}|{}|e{epoch}|k{id}|{}|{}", r.typ, r.node, r.record_id).into_bytes()
348}
349
350/// Seal `plain` for record `r` under rotation `id`'s epoch key.
351pub fn seal_record(epoch_key: &Key32, user_id: &str, r: &RecordRef<'_>, epoch: u32, id: &str, plain: &[u8]) -> Result<(SealInfo, Vec<u8>)> {
352    let key = record_key(epoch_key, user_id, r.typ, r.record_id, epoch, id)?;
353    let s = weirdnet_keys::seal(&key, plain, &record_aad(r, epoch, id))?;
354    let nonce = hex::decode(&s.nonce).map_err(|_| SyncError::Crypto("bad nonce".into()))?;
355    let ct = hex::decode(&s.ct).map_err(|_| SyncError::Crypto("bad ciphertext".into()))?;
356    Ok((SealInfo { epoch, key: id.to_string(), nonce }, ct))
357}
358
359/// Open a value sealed for record `r`.
360pub fn open_record(epoch_key: &Key32, user_id: &str, r: &RecordRef<'_>, seal: &SealInfo, ct: &[u8]) -> Result<Zeroizing<Vec<u8>>> {
361    let key = record_key(epoch_key, user_id, r.typ, r.record_id, seal.epoch, &seal.key)?;
362    let sealed = Sealed { nonce: hex::encode(&seal.nonce), ct: hex::encode(ct) };
363    Ok(weirdnet_keys::open(&key, &sealed, &record_aad(r, seal.epoch, &seal.key))?)
364}
365
366/// Per-record key under a type's [`SyncKey`] (since 0.8.4): `HKDF-SHA256(SyncKey(type)
367/// under rotation id, salt = user id,
368/// info = weirdnet-sync/v1/record-scoped/<type>/e<n>/k<rotation id>/<record id>)`.
369/// `type_key` is [`crate::rotated_sync_key`] of the rotation's epoch key on a full device,
370/// or the scoped key a service device holds ([`crate::EpochKeys::sync_key`] gives either).
371pub fn scoped_record_key(type_key: &SyncKey, user_id: &str, typ: &str, record_id: &str, epoch: u32, id: &str) -> Result<Key32> {
372    let info = format!("weirdnet-sync/v1/record-scoped/{typ}/e{epoch}/k{id}/{record_id}");
373    Ok(kdf::hkdf(&type_key.0, Some(user_id.as_bytes()), info.as_bytes())?)
374}
375
376/// Associated data of a record sealed under a type-scoped key (since 0.8.4): as
377/// [`record_aad`], under its own label.
378pub fn scoped_record_aad(r: &RecordRef<'_>, epoch: u32, id: &str) -> Vec<u8> {
379    format!("weirdnet-sync/v1/record-scoped|v{VALUE_VERSION}|{}|e{epoch}|k{id}|{}|{}", r.typ, r.node, r.record_id).into_bytes()
380}
381
382/// Seal `plain` for record `r` under rotation `id`'s type-scoped key (since 0.8.4).
383pub fn seal_record_scoped(type_key: &SyncKey, user_id: &str, r: &RecordRef<'_>, epoch: u32, id: &str, plain: &[u8]) -> Result<(SealInfo, Vec<u8>)> {
384    let key = scoped_record_key(type_key, user_id, r.typ, r.record_id, epoch, id)?;
385    let s = weirdnet_keys::seal(&key, plain, &scoped_record_aad(r, epoch, id))?;
386    let nonce = hex::decode(&s.nonce).map_err(|_| SyncError::Crypto("bad nonce".into()))?;
387    let ct = hex::decode(&s.ct).map_err(|_| SyncError::Crypto("bad ciphertext".into()))?;
388    Ok((SealInfo { epoch, key: id.to_string(), nonce }, ct))
389}
390
391/// Open a value sealed for record `r` under a type-scoped key (since 0.8.4).
392pub fn open_record_scoped(type_key: &SyncKey, user_id: &str, r: &RecordRef<'_>, seal: &SealInfo, ct: &[u8]) -> Result<Zeroizing<Vec<u8>>> {
393    let key = scoped_record_key(type_key, user_id, r.typ, r.record_id, seal.epoch, &seal.key)?;
394    let sealed = Sealed { nonce: hex::encode(&seal.nonce), ct: hex::encode(ct) };
395    Ok(weirdnet_keys::open(&key, &sealed, &scoped_record_aad(r, seal.epoch, &seal.key))?)
396}
397
398impl crate::net::SyncState {
399    /// Whether a sealed write of `typ` here uses the type-scoped record key
400    /// ([`seal_record_scoped`]) rather than the epoch key ([`seal_record`]) (since 0.8.4).
401    /// A service device always does (it holds no epoch key). A full device does while an
402    /// active service device is granted `typ` ([`crate::Roster::service_granted`]), so that
403    /// device can open it; otherwise it seals with the epoch key, as 0.7.1 to 0.8.3 do and
404    /// read. [`crate::SyncState::reseal_stale`] follows the same rule.
405    pub fn seals_scoped(&self, typ: &str) -> bool {
406        self.is_service() || self.roster.service_granted(typ)
407    }
408
409    fn seal_payload<'a>(&self, opts: &RecordOptions, typ: &str, record_id: &str, value: &'a [u8]) -> Result<(Option<SealInfo>, Cow<'a, [u8]>)> {
410        if !opts.sealed {
411            return Ok((None, Cow::Borrowed(value)));
412        }
413        if self.key_status() == KeyStatus::Revoked {
414            return Err(SyncError::Refused("revoked".into()));
415        }
416        let KeyRef { epoch, id: Some(id) } = self.current_key() else {
417            // Seed-derived keys are held by every seed holder, revoked or not: never seal under them.
418            return Err(SyncError::Refused("no-epoch-key".into()));
419        };
420        let r = RecordRef { typ, record_id, node: &self.our_node.0 };
421        let (seal, ct) = if self.seals_scoped(typ) {
422            let k = self.keys.sync_key(&self.user_id, typ, epoch, &id).map_err(|_| SyncError::Refused("no-epoch-key".into()))?;
423            seal_record_scoped(&k, &self.user_id, &r, epoch, &id, value)?
424        } else {
425            let key = self.keys.get(&id).ok_or_else(|| SyncError::Refused("no-epoch-key".into()))?;
426            seal_record(key, &self.user_id, &r, epoch, &id, value)?
427        };
428        Ok((Some(seal), Cow::Owned(ct)))
429    }
430
431    /// Open a sealed payload; also says whether it was under the type-scoped key. A full
432    /// device tries both keys (the one it would seal with first); a service device has
433    /// only the type-scoped one.
434    fn open_payload(&self, s: &SealInfo, e: &LogEntry, ct: &[u8]) -> Result<(Zeroizing<Vec<u8>>, bool)> {
435        let r = RecordRef::of(e);
436        let scoped = || -> Result<Zeroizing<Vec<u8>>> {
437            let k = self.keys.sync_key(&self.user_id, &e.typ, s.epoch, &s.key)?;
438            open_record_scoped(&k, &self.user_id, &r, s, ct)
439        };
440        let Some(epoch_key) = self.keys.get(&s.key) else {
441            if !self.keys.has(&s.key) {
442                return Err(SyncError::Crypto("sealed under an epoch key this device does not hold".into()));
443            }
444            return scoped().map(|p| (p, true)).map_err(|_| {
445                SyncError::Crypto("does not open under this type's scoped key (sealed under the epoch key, or the type is not granted)".into())
446            });
447        };
448        let legacy = || open_record(epoch_key, &self.user_id, &r, s, ct);
449        if self.seals_scoped(&e.typ) {
450            scoped().map(|p| (p, true)).or_else(|_| legacy().map(|p| (p, false)))
451        } else {
452            legacy().map(|p| (p, false)).or_else(|_| scoped().map(|p| (p, true)))
453        }
454    }
455
456    /// The latest entry of every record of `typ` (by HLC).
457    pub fn latest_entries(&self, typ: &str) -> Vec<&LogEntry> {
458        let mut latest: BTreeMap<&str, &LogEntry> = BTreeMap::new();
459        for e in self.log.iter().filter(|e| e.typ == typ) {
460            let slot = latest.entry(e.record_id.as_str()).or_insert(e);
461            if e.hlc.cmp_total(&slot.hlc).is_gt() {
462                *slot = e;
463            }
464        }
465        latest.into_values().collect()
466    }
467
468    /// Re-seal, under the head rotation, every record of sealed `typ` whose latest
469    /// entry is sealed under an older key, or (since 0.8.4) under the other scheme than a
470    /// write here would use now ([`crate::SyncState::seals_scoped`]), and readable here.
471    /// After a service device is granted `typ`, a full device's run moves records sealed
472    /// with the epoch key to the type-scoped key so that device can open them; once no
473    /// service device is granted `typ` any more, it moves them back. Members keep older
474    /// epoch keys (and admitted devices receive them), so old entries stay readable by
475    /// full devices without it. The new entry is a later write of the same value, so run
476    /// it after syncing. A device revoked earlier keeps whatever it could already read;
477    /// change the secret itself when that matters. Returns the re-sealed record ids.
478    pub fn reseal_stale(&mut self, now_ms: u64, typ: &str) -> Result<Vec<String>> {
479        if !self.options(typ).sealed {
480            return Ok(Vec::new());
481        }
482        let Some(head) = self.current_key().id else { return Err(SyncError::Refused("no-epoch-key".into())) };
483        let want_scoped = self.seals_scoped(typ);
484        let mut todo = Vec::new();
485        for e in self.latest_entries(typ) {
486            let Some(s) = e.value.as_ref().and_then(|v| v.seal.as_ref()) else { continue };
487            // Under the head with no epoch key: type-scoped already (nothing else opens here).
488            if s.key == head && !self.keys.has_epoch_key(&head) {
489                continue;
490            }
491            if let Ok((RecordValue::Ready(plain), Some(scoped))) = self.read_scheme(e)
492                && (s.key != head || scoped != want_scoped)
493            {
494                todo.push((e.record_id.clone(), plain, e.op.clone()));
495            }
496        }
497        let mut done = Vec::new();
498        for (rid, plain, fallback) in todo {
499            self.write_with_fallback(now_ms, typ, &rid, &plain, fallback)?;
500            done.push(rid);
501        }
502        Ok(done)
503    }
504}
505
506#[cfg(test)]
507mod tests {
508    use super::*;
509    use crate::hlc::{Hlc, NodeId};
510    use crate::log::Page;
511    use crate::protocol::{decode, encode};
512
513    fn n(s: &str) -> NodeId {
514        NodeId::new(s)
515    }
516
517    fn entry(node: &str, seq: u64, typ: &str, rid: &str, op: Vec<u8>, value: Option<Value>) -> LogEntry {
518        LogEntry { node_id: n(node), seq, hlc: Hlc::new(seq, 0, n(node)), typ: typ.into(), record_id: rid.into(), op, value }
519    }
520
521    fn big(len: usize) -> Vec<u8> {
522        (0..len).map(|i| (i * 31 % 251) as u8).collect()
523    }
524
525    #[test]
526    fn a_split_value_reassembles_only_from_matching_chunks() {
527        let data = big(200_000);
528        let (blob, parts) = split(&data, 64 * 1024);
529        assert_eq!(blob.len, 200_000);
530        assert_eq!(parts.len(), 4);
531        assert_eq!(blob.chunk_ids().len(), 4);
532        let ctyp = chunk_type("notes");
533        let mut log = OpLog::new();
534        // Nothing yet: every chunk is pending.
535        assert_eq!(assemble(&log, "notes", &blob).unwrap(), RecordValue::Pending { missing: blob.chunk_ids() });
536        // A chunk entry under the right id but with other bytes is not that chunk.
537        let (h0, _) = parts[0];
538        let forged = entry("x", 1, &ctyp, &hex::encode(h0), vec![0u8; 10], None);
539        log.integrate(&Page { node_id: n("x"), from_seq: 1, to_seq: 1, ops: vec![forged] });
540        assert!(log.chunk(&ctyp, &h0).is_none());
541        let page: Vec<LogEntry> =
542            parts.iter().enumerate().map(|(i, (h, b))| entry("a", i as u64 + 1, &ctyp, &hex::encode(h), b.to_vec(), None)).collect();
543        log.integrate(&Page { node_id: n("a"), from_seq: 1, to_seq: 3, ops: page[..3].to_vec() });
544        assert_eq!(assemble(&log, "notes", &blob).unwrap(), RecordValue::Pending { missing: vec![hex::encode(parts[3].0)] });
545        log.integrate(&Page { node_id: n("a"), from_seq: 4, to_seq: 4, ops: page[3..].to_vec() });
546        assert_eq!(&assemble(&log, "notes", &blob).unwrap().ready().unwrap()[..], &data[..]);
547        // A manifest whose whole hash or length disagrees with its chunks is refused.
548        let bad = Blob { hash: blake3::hash(b"other").as_bytes().to_vec(), ..blob.clone() };
549        assert!(assemble(&log, "notes", &bad).is_err());
550        let bad = Blob { len: 5, ..blob.clone() };
551        assert!(assemble(&log, "notes", &bad).is_err());
552        let bad = Blob { chunks: blob.chunks[..40].to_vec(), ..blob };
553        assert!(assemble(&log, "notes", &bad).is_err());
554    }
555
556    #[test]
557    fn entries_keep_the_0_3_wire_shape_and_old_peers_drop_the_value() {
558        #[derive(Serialize, Deserialize, PartialEq, Debug)]
559        struct EntryV03 {
560            node_id: NodeId,
561            seq: u64,
562            hlc: Hlc,
563            typ: String,
564            record_id: String,
565            #[serde(with = "crate::bytes")]
566            op: Vec<u8>,
567        }
568        let plain = entry("a", 1, "notes", "r", b"hi".to_vec(), None);
569        let old: EntryV03 = decode(&encode(&plain).unwrap()).unwrap();
570        assert_eq!(encode(&old).unwrap(), encode(&plain).unwrap(), "no value field on a plain entry");
571        let back: LogEntry = decode(&encode(&old).unwrap()).unwrap();
572        assert_eq!(back, plain);
573        // A chunked entry reaches an old peer as its fallback, in a page it can decode.
574        let (blob, _) = split(&big(100_000), 32 * 1024);
575        let v = Value { v: VALUE_VERSION, seal: None, body: Vec::new(), blob: Some(blob) };
576        let rich = entry("a", 2, "notes", "r", b"preview".to_vec(), Some(v));
577        #[derive(Deserialize)]
578        struct PageV03 {
579            ops: Vec<EntryV03>,
580        }
581        let page = Page { node_id: n("a"), from_seq: 1, to_seq: 2, ops: vec![plain, rich] };
582        let old: PageV03 = decode(&encode(&page).unwrap()).unwrap();
583        assert_eq!(old.ops[1].op, b"preview");
584        assert_eq!(old.ops.len(), 2);
585    }
586
587    #[test]
588    fn a_newer_value_format_is_refused_not_misread() {
589        #[derive(Serialize)]
590        struct Future {
591            v: u32,
592            body: serde_bytes_like::B,
593            zstd: bool,
594        }
595        mod serde_bytes_like {
596            pub struct B(pub Vec<u8>);
597            impl serde::Serialize for B {
598                fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
599                    s.serialize_bytes(&self.0)
600                }
601            }
602        }
603        let v: Value = decode(&encode(&Future { v: 2, body: serde_bytes_like::B(b"x".to_vec()), zstd: true }).unwrap()).unwrap();
604        assert_eq!(v.v, 2, "unknown fields are skipped, the version is kept");
605        let e = entry("a", 1, "notes", "r", vec![], Some(v));
606        assert!(payload(&OpLog::new(), &e, e.value.as_ref().unwrap()).is_err());
607    }
608
609    #[test]
610    fn limits_stay_inside_a_page() {
611        assert!(Limits::default().check().is_ok());
612        assert!(Limits { chunk_size: CHUNK_MAX + 1, ..Default::default() }.check().is_err());
613        assert!(Limits { chunk_size: 512, ..Default::default() }.check().is_err());
614        assert!(Limits { inline_max: CHUNK_MAX + 1, ..Default::default() }.check().is_err());
615        assert!(Limits { record_max: usize::MAX / 2, ..Default::default() }.check().is_err());
616        assert!(Limits { chunk_size: 8 * 1024, record_max: 1024 * 1024, ..Default::default() }.check().is_ok());
617    }
618
619    #[test]
620    fn a_sealed_value_opens_only_for_its_record_writer_and_key() {
621        let k = Key32::random().unwrap();
622        let r = RecordRef { typ: "secrets", record_id: "mcp/github", node: "peer-a" };
623        let (seal, ct) = seal_record(&k, "user-1", &r, 2, "rot1", b"token").unwrap();
624        assert_eq!(&open_record(&k, "user-1", &r, &seal, &ct).unwrap()[..], b"token");
625        for other in [RecordRef { record_id: "mcp/other", ..r }, RecordRef { node: "peer-b", ..r }, RecordRef { typ: "notes", ..r }] {
626            assert!(open_record(&k, "user-1", &other, &seal, &ct).is_err(), "{other:?}");
627        }
628        assert!(open_record(&k, "user-2", &r, &seal, &ct).is_err());
629        assert!(open_record(&k, "user-1", &r, &SealInfo { key: "rot2".into(), ..seal.clone() }, &ct).is_err());
630        assert!(open_record(&k, "user-1", &r, &SealInfo { epoch: 3, ..seal.clone() }, &ct).is_err());
631        assert!(open_record(&Key32::random().unwrap(), "user-1", &r, &seal, &ct).is_err());
632        let mut bad = ct.clone();
633        bad[0] ^= 1;
634        assert!(open_record(&k, "user-1", &r, &seal, &bad).is_err());
635    }
636}