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