1use 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
42pub const CHUNK_SUFFIX: &str = "#chunks";
44
45pub const VALUE_VERSION: u32 = 1;
47
48pub const CHUNK_MAX: usize = PAGE_BUDGET - 4 * 1024;
50
51pub 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
60pub fn base_type(typ: &str) -> Option<&str> {
62 typ.strip_suffix(CHUNK_SUFFIX)
63}
64
65#[derive(Debug, Clone, PartialEq, Eq)]
67pub struct Limits {
68 pub inline_max: usize,
70 pub chunk_size: usize,
72 pub record_max: usize,
74 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#[derive(Debug, Clone, Default, PartialEq, Eq)]
99pub struct RecordOptions {
100 pub sealed: bool,
103 pub limits: Limits,
104}
105
106#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
108pub struct Value {
109 pub v: u32,
111 #[serde(default, skip_serializing_if = "Option::is_none")]
113 pub seal: Option<SealInfo>,
114 #[serde(default, skip_serializing_if = "Vec::is_empty", with = "crate::bytes")]
116 pub body: Vec<u8>,
117 #[serde(default, skip_serializing_if = "Option::is_none")]
119 pub blob: Option<Blob>,
120}
121
122#[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#[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 #[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 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#[derive(Debug, Clone, PartialEq, Eq)]
161pub enum RecordValue {
162 Ready(zeroize::Zeroizing<Vec<u8>>),
164 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
177pub type Chunk<'a> = ([u8; 32], &'a [u8]);
179
180pub 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
187pub 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
213pub(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 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 pub fn options(&self, typ: &str) -> RecordOptions {
240 self.records.get(typ).cloned().unwrap_or_default()
241 }
242
243 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 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 pub fn read(&self, e: &LogEntry) -> Result<RecordValue> {
293 self.read_scheme(e).map(|(v, _)| v)
294 }
295
296 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
323pub 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#[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
344pub 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
350pub 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
359pub 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
366pub 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
376pub 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
382pub 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
391pub 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 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 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 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 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 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 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 assert_eq!(assemble(&log, "notes", &blob).unwrap(), RecordValue::Pending { missing: blob.chunk_ids() });
536 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 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 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}