revault_lockbox_api 0.0.48

reVault lockbox API to create and manage lockboxes
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
//! Experimental typed filesystem adapter over the authenticated shared tree.
//! Fresh export preserves its source. Filesystem and guarded variable transactions
//! and form snapshots are test-only; public activation, complete form mutation
//! and migration remain separate.
use super::dense_catalogue::{Catalogue, Metadata};
use super::dense_image::Image;
use super::*;
use crate::file_format::publication_anchor::{shared, FAILURE_REGION, REGION_LEN};
use shared::tree::{self, Tree};
mod reader;
pub(super) use reader::TreeImage;
mod resume;
pub(super) use resume::resume_path;
mod install;
pub(super) use install::{compact_path, compact_path_with};
mod compact;
pub(super) use compact::compact;
mod fresh;
pub(super) use fresh::from_candidate;
pub(super) mod forms;
mod mutation;
pub(super) mod variables;
pub(super) use mutation::{remove_files, update_files};

pub(super) struct AuditedTreeImage<S: Storage> {
    pub image: Image<S>,
    pub tree: Tree,
}
impl<S: Storage> AuditedTreeImage<S> {
    /// Credential bootstrap and typed records must refer to the same selected
    /// publication. A bounded zeroizing key copy allows guarded record allocation.
    pub fn open_credential(
        storage: S,
        archive: LockboxId,
        mode: FormatMode,
        owner: Option<&crate::OwnerSigningPublicKey>,
        credential: publication::bootstrap::Credential<'_>,
        slot: Option<u64>,
    ) -> Result<Self> {
        let opened = shared::credential_open(&storage, archive, mode, owner, credential, slot)?;
        // Catalogue decoding allocates guarded secret values. End the global
        // secure read guard first; keep only a bounded, zeroizing key copy for
        // this open operation, including every error path.
        let mut key = Zeroizing::new([0u8; 32]);
        opened.key.with_bytes(|bytes| {
            if bytes.len() != key.len() {
                return Err(Error::CorruptRecord);
            }
            key.copy_from_slice(bytes);
            Ok(())
        })??;
        let authority = owner.map_or(Authority::Symmetric(key.as_ref()), Authority::Owner);
        let image = Self::open(storage, archive, mode, &authority, Some(key.as_ref()))?;
        if image.image.anchor != opened.anchor {
            return Err(Error::CorruptRecord);
        }
        Ok(image)
    }

    pub fn open(
        storage: S,
        archive: LockboxId,
        mode: FormatMode,
        authority: &Authority<'_>,
        key: Option<&[u8]>,
    ) -> Result<Self> {
        Self::open_observed(storage, archive, mode, authority, key, |_| {})
    }

    /// Test-only stage observer; the ordinary reader uses a statically empty
    /// callback. All validation and owner verification use this same path.
    pub(super) fn open_observed(
        storage: S,
        archive: LockboxId,
        mode: FormatMode,
        authority: &Authority<'_>,
        key: Option<&[u8]>,
        mut stage: impl FnMut(&'static str),
    ) -> Result<Self> {
        let codec = Codec::shared_packed(archive, mode, key)?;
        stage("codec");
        let (catalogue, tree) = Catalogue::with_tree_borrowed(&codec, |visitor| {
            Tree::open_visit_borrowed_observed(
                &storage, archive, mode, authority, key, visitor, &mut stage,
            )
        })?;
        stage("typed_validation");
        catalogue.verify_padding(&storage, &codec)?;
        stage("pack_padding");
        let mut image = Image {
            storage,
            anchor: tree.anchor.clone(),
            value_key: super::dense_image::value_key_for(&catalogue, mode, key)?,
            catalogue,
            codec,
        };
        stage("value_key");
        if mode.plaintext() && mode.signed() {
            image.verify_all()?;
        }
        stage("owner_payload_verification");
        Ok(Self { image, tree })
    }
}

/// Called by the transition writer itself so no caller-supplied graph becomes
/// destructive-write authority. Re-authenticate storage and verify all payloads.
pub(crate) fn dense_base(
    storage: &impl Storage,
    archive: LockboxId,
    mode: FormatMode,
    authority: &Authority<'_>,
    key: Option<&[u8]>,
) -> Result<(Anchor, shared::ownership::Graph)> {
    let mut image = Image::open(
        allocation::compaction::View(storage),
        archive,
        mode,
        authority,
        key,
    )?;
    image.verify_all()?;
    let graph = image.catalogue.graph(&image.anchor)?;
    Ok((image.anchor, graph))
}

/// Recovery-only graph from an already owner-authenticated selected snapshot.
/// Do not require idle preparation or intact uncommitted vacant bytes here.
pub(crate) fn dense_recovery_graph(
    anchor: &Anchor,
    body: &[u8],
    key: Option<&[u8]>,
) -> Result<shared::ownership::Graph> {
    let codec = Codec::shared_packed(anchor.archive, anchor.mode, key)?;
    Catalogue::decode(body, &codec, anchor.sealed_len)?.graph(anchor)
}

pub(super) fn recover(
    storage: &mut impl Storage,
    archive: LockboxId,
    mode: FormatMode,
    authority: &Authority<'_>,
    key: Option<&[u8]>,
) -> Result<()> {
    let (anchor, body) = shared::snapshot(storage, archive, mode, authority, key)?;
    let session = crate::file_format::preparation_journal::compact::session::OverflowSession::open(
        storage, archive, mode, key,
    )?;
    if body.starts_with(b"RV4TRE01")
        || (session.active() && session.base() == shared::commitment(&anchor)?)
    {
        tree::recover_update(storage, archive, mode, authority, key)
    } else {
        super::dense_update::recover(storage, archive, mode, authority, key).map(|_| ())
    }
}

#[allow(clippy::too_many_arguments)]
pub(super) fn grow_dense(
    storage: &mut impl Storage,
    archive: LockboxId,
    mode: FormatMode,
    authority: &Authority<'_>,
    signer: Option<&OwnerSigningKeyPair>,
    key: Option<&[u8]>,
    entries: &[Metadata],
) -> Result<bool> {
    let mut image = Image::open(
        allocation::compaction::View(&*storage),
        archive,
        mode,
        authority,
        key,
    )?;
    image.catalogue.set_tree_metadata(entries)?;
    let records = image.catalogue.tree_records()?;
    drop(image);
    tree::grow_dense_records(storage, archive, mode, authority, signer, key, records)
}

#[allow(clippy::too_many_arguments)]
pub(super) fn return_inline(
    storage: &mut impl Storage,
    archive: LockboxId,
    mode: FormatMode,
    authority: &Authority<'_>,
    signer: Option<&OwnerSigningKeyPair>,
    key: Option<&[u8]>,
) -> Result<bool> {
    let (_, body) = shared::open_private(storage, archive, mode, authority, key)?;
    if !body.starts_with(b"RV4TRE01") {
        return super::dense_update::return_inline(storage, archive, mode, authority, signer, key);
    }
    let mut opened = AuditedTreeImage::open(
        allocation::compaction::View(&*storage),
        archive,
        mode,
        authority,
        key,
    )?;
    opened.image.verify_all()?;
    // Prove the target dense capacity before a possible relocation transaction.
    let sealed = opened
        .image
        .catalogue
        .packs
        .last()
        .map_or(REGION_LEN as u64, |pack| {
            pack.extent.start + pack.extent.len
        });
    opened.image.catalogue.vacant = opened.tree.graph.catalogue_vacant();
    opened
        .image
        .catalogue
        .vacant
        .retain(|entry| entry.span.start < sealed);
    for entry in &mut opened.image.catalogue.vacant {
        entry.span.len = entry.span.len.min(sealed - entry.span.start);
    }
    let body = opened
        .image
        .catalogue
        .dense_body_if_fits(&opened.image.codec, sealed)?
        .ok_or_else(|| Error::SecurityLimitExceeded("dense return capacity".into()))?;
    shared::encode_private(archive, mode, key, &body)?;
    if opened.tree.anchor.index.primary < sealed || opened.tree.anchor.index.mirror < sealed {
        let records = opened.image.catalogue.tree_records()?;
        drop(opened);
        tree::relocate_records(storage, archive, mode, authority, signer, key, records)?;
    } else {
        drop(opened);
    }
    let opened = AuditedTreeImage::open(
        allocation::compaction::View(&*storage),
        archive,
        mode,
        authority,
        key,
    )?;
    let anchor = opened.tree.anchor.clone();
    let mut catalogue = opened.image.catalogue;
    catalogue.vacant = opened.tree.graph.catalogue_vacant();
    super::dense_update::publish_catalogue(
        storage, archive, mode, authority, signer, key, anchor, catalogue, true,
    )?;
    Ok(true)
}

/// Read-only admission. A later cleanup error must never be mistaken for an
/// oversized catalogue and silently reported as a completed update.
pub(super) fn can_return_inline(
    storage: &impl Storage,
    archive: LockboxId,
    mode: FormatMode,
    authority: &Authority<'_>,
    key: Option<&[u8]>,
) -> Result<bool> {
    let mut opened = AuditedTreeImage::open(
        allocation::compaction::View(storage),
        archive,
        mode,
        authority,
        key,
    )?;
    let sealed = opened
        .image
        .catalogue
        .packs
        .last()
        .map_or(REGION_LEN as u64, |pack| {
            pack.extent.start + pack.extent.len
        });
    opened.image.catalogue.vacant = opened.tree.graph.catalogue_vacant();
    opened
        .image
        .catalogue
        .vacant
        .retain(|entry| entry.span.start < sealed);
    for entry in &mut opened.image.catalogue.vacant {
        entry.span.len = entry.span.len.min(sealed - entry.span.start);
    }
    let Some(body) = opened
        .image
        .catalogue
        .dense_body_if_fits(&opened.image.codec, sealed)?
    else {
        return Ok(false);
    };
    match shared::encode_private(archive, mode, key, &body) {
        Ok(_) => Ok(true),
        Err(Error::SecurityLimitExceeded(_)) => Ok(false),
        Err(error) => Err(error),
    }
}

/// Caller holds a stable snapshot and stages metadata/files until success.
/// Missing selected membership is fatal. Unavailable payloads are reported per
/// file; an unrelated corrupt file cannot replace owner publication authority.
pub(super) fn salvage_filesystem<S: Storage>(
    storage: &S,
    archive: LockboxId,
    mode: FormatMode,
    authority: &Authority<'_>,
    key: Option<&[u8]>,
    sink: &mut impl super::dense_image::FilesystemSink,
) -> Result<super::dense_image::SalvageReport> {
    let codec = Codec::shared_packed(archive, mode, key)?;
    let (catalogue, tree) = Catalogue::with_tree(&codec, |visitor| {
        Tree::salvage_visit(storage, archive, mode, authority, key, visitor)
    })?;
    sink.metadata(&catalogue.filesystem_metadata()?)?;
    super::dense_image::salvage_catalogue(storage, &tree.anchor, &catalogue, codec, sink)
}

/// Exclusive writer access; validate complete typed semantics before the raw
/// transaction can mirror or write anything. The old file set is unchanged.
#[allow(clippy::too_many_arguments)]
pub(super) fn replace_metadata(
    storage: &mut impl Storage,
    archive: LockboxId,
    mode: FormatMode,
    authority: &Authority<'_>,
    signer: Option<&OwnerSigningKeyPair>,
    key: Option<&[u8]>,
    entries: &[Metadata],
) -> Result<bool> {
    let (_, body) = shared::open_private(storage, archive, mode, authority, key)?;
    if !body.starts_with(b"RV4TRE01") {
        let mut image = Image::open(
            allocation::compaction::View(&*storage),
            archive,
            mode,
            authority,
            key,
        )?;
        image.catalogue.upgrade(&image.anchor)?;
        image.catalogue.set_tree_metadata(entries)?;
        let fits = match image
            .catalogue
            .dense_body_if_fits(&image.codec, image.anchor.sealed_len)?
        {
            Some(body) => match shared::encode_private(archive, mode, key, &body) {
                Ok(_) => true,
                Err(Error::SecurityLimitExceeded(_)) => false,
                Err(error) => return Err(error),
            },
            None => false,
        };
        let records = if fits {
            Vec::new()
        } else {
            image.catalogue.tree_records()?
        };
        shared::prepare(&image.anchor, authority, signer)?;
        drop(image);
        return if fits {
            super::dense_update::replace_filesystem_metadata(
                storage, archive, mode, authority, signer, key, entries,
            )
        } else {
            tree::grow_dense_records(storage, archive, mode, authority, signer, key, records)
        };
    }
    let mut opened = AuditedTreeImage::open(
        allocation::compaction::View(&*storage),
        archive,
        mode,
        authority,
        key,
    )?;
    opened.image.catalogue.set_tree_metadata(entries)?;
    let records = opened.image.catalogue.tree_records()?;
    drop(opened);
    tree::rewrite_records(storage, archive, mode, authority, signer, key, records)
}

/// Stable source/read lock and a fresh owned destination are required. This is
/// an experimental export, not an in-place migration or public format choice.
#[allow(clippy::too_many_arguments)]
pub(super) fn from_dense<S: Storage, T: Storage>(
    source: &S,
    destination: T,
    archive: LockboxId,
    mode: FormatMode,
    authority: &Authority<'_>,
    signer: Option<&OwnerSigningKeyPair>,
    key: Option<&[u8]>,
) -> Result<T> {
    let mut destination = Aligned(destination);
    if destination.len()? != 0 {
        return Err(Error::InvalidInput(
            "tree export destination must be empty".into(),
        ));
    }
    let mut opened = Image::open(
        allocation::compaction::View(source),
        archive,
        mode,
        authority,
        key,
    )?;
    let slots = shared::public_slots(source, &opened.anchor)?;
    opened.catalogue.filesystem_metadata()?;
    opened.verify_all()?;
    let base = shared::commitment(&opened.anchor)?;
    let result = (|| {
        destination.append(&vec![0; REGION_LEN])?;
        let mut rows = Vec::new();
        for pack in &mut opened.catalogue.packs {
            let bytes = crate::page_buffer::ZeroizingBytes::new(
                source.read_at(pack.extent.start, pack.extent.len as usize)?,
            );
            if crate::crypto::strong_checksum(&bytes) != pack.extent.digest {
                return Err(Error::CorruptRecord);
            }
            pack.extent.start = destination.append(&bytes)?;
            let name = [vec![2], pack.extent.start.to_be_bytes().to_vec()].concat();
            let value = [
                pack.extent.len.to_le_bytes().to_vec(),
                pack.extent.digest.to_vec(),
            ]
            .concat();
            rows.push(Entry::new(0, &name, &value)?);
        }
        let end = destination.len()?;
        let aligned = end.div_ceil(FAILURE_REGION) * FAILURE_REGION;
        if aligned > end {
            destination.append(&vec![0; (aligned - end) as usize])?;
            rows.push(Entry::new(
                0,
                &[vec![0], end.to_be_bytes().to_vec()].concat(),
                &(aligned - end).to_le_bytes(),
            )?);
        }
        rows.extend(opened.catalogue.tree_records()?);
        rows.sort_by(|a, b| (a.namespace, a.key.as_slice()).cmp(&(b.namespace, b.key.as_slice())));
        let root = Index::new(archive, mode, key)?
            .build_sorted(&mut destination, rows.into_iter().map(Ok))?
            .root;
        shared::initialize(
            &mut destination,
            archive,
            mode,
            authority,
            signer,
            key,
            &tree::manifest(root),
            &slots,
        )?;
        AuditedTreeImage::open(
            allocation::compaction::View(&destination),
            archive,
            mode,
            authority,
            key,
        )?
        .image
        .verify_all()?;
        if shared::commitment(&shared::open_private(source, archive, mode, authority, key)?.0)?
            != base
        {
            return Err(Error::CorruptRecord);
        }
        Ok(())
    })();
    if let Err(error) = result {
        if let Err(cleanup) = allocation::compaction::discard(&mut destination) {
            return Err(Error::InvalidOperation(format!(
                "tree export failed ({error}); destination cleanup failed ({cleanup})"
            )));
        }
        return Err(error);
    }
    Ok(destination.0)
}

#[derive(Clone, Debug)]
struct Aligned<S>(S);
impl<S: Storage> Storage for Aligned<S> {
    fn len(&self) -> Result<u64> {
        self.0.len()
    }
    fn read_at(&self, at: u64, len: usize) -> Result<Vec<u8>> {
        self.0.read_at(at, len)
    }
    fn read_at_into(&self, at: u64, out: &mut [u8]) -> Result<()> {
        self.0.read_at_into(at, out)
    }
    fn append(&mut self, bytes: &[u8]) -> Result<u64> {
        self.0.append(bytes)
    }
    fn append_pair(&mut self, bytes: &[u8]) -> Result<(u64, u64)> {
        if bytes.len() > FAILURE_REGION as usize || self.len()? % FAILURE_REGION != 0 {
            return Err(Error::CorruptRecord);
        }
        let primary = self.append(bytes)?;
        self.append(&vec![0; FAILURE_REGION as usize - bytes.len()])?;
        let mirror = self.append(bytes)?;
        self.append(&vec![0; FAILURE_REGION as usize - bytes.len()])?;
        Ok((primary, mirror))
    }
    fn write_at(&mut self, at: u64, bytes: &[u8]) -> Result<()> {
        self.0.write_at(at, bytes)
    }
    fn truncate(&mut self, len: u64) -> Result<()> {
        self.0.truncate(len)
    }
    fn sync(&self) -> Result<()> {
        self.0.sync()
    }
}