revault_lockbox_api 0.0.42

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
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
//! Read-only archives supplied by an immutable external byte source.
//!
//! Enabled by `external-source`. HTTP transport belongs to the embedding: bind
//! every range to one immutable revision, validate exact lengths and ranges, and
//! reject replacement. Use [`ExternalReader::try_read`] for every operation;
//! missing bytes cannot be mistaken for successful fallback or absent content.
//! Closures must be repeatable and must not publish results or perform external
//! side effects until `try_read` returns `Ok`.
//!
//! A borrowed handle cannot escape the checked operation:
//! ```compile_fail
//! use revault_lockbox_api::external_source::ExternalReader;
//! fn escape(reader: &mut ExternalReader) {
//!     let leaked = reader.try_read(|archive| Ok(archive));
//! }
//! ```
//! Writes are unavailable through the read-only handle:
//! ```compile_fail
//! use revault_lockbox_api::{LockboxPath, external_source::ExternalReader};
//! fn write(reader: &mut ExternalReader) {
//!     reader.try_read(|archive| archive.add_file(&LockboxPath::new("/x")?, b"x", false));
//! }
//! ```
//!
//! ```
//! use std::sync::Arc;
//! use revault_lockbox_api::{Encryption, Lockbox, LockboxCreateOptions, LockboxPath, Signing};
//! use revault_lockbox_api::external_source::{ExternalReader, ExternalReaderOptions,
//!     ExternalReadError, SourceError, SparseSource};
//! // Generate a public archive solely to demonstrate the retry contract.
//! let mut writer = Lockbox::create_in_memory_with_options(
//!     LockboxCreateOptions::new(Encryption::None, Signing::None))?;
//! let path = LockboxPath::new("/hello.txt")?;
//! writer.add_file(&path, b"hello", false)?;
//! writer.commit()?;
//! let bytes = writer.try_to_bytes()?;
//! let source = Arc::new(SparseSource::new(bytes.len() as u64,
//!     "immutable-revision-1".into(), 4096, bytes.len() + 4096)?);
//! let mut reader = ExternalReader::new(source.clone(), ExternalReaderOptions::default())?;
//! let contents = loop {
//!     match reader.try_read(|archive| archive.get_file(&path)) {
//!         Ok(contents) => break contents,
//!         Err(ExternalReadError::Source(SourceError::MissingRange {offset, length})) => {
//!             // In a browser, await an exact, revision-checked HTTP range here.
//!             let block = bytes[offset as usize..offset as usize + length].to_vec();
//!             source.supply("immutable-revision-1", offset, block)?;
//!         }
//!         Err(error) => return Err(error.into()),
//!     }
//! };
//! assert_eq!(contents, b"hello");
//! # Ok::<(), Box<dyn std::error::Error>>(())
//! ```
use crate::storage::{Storage, StorageBackend};
use crate::{Error, Lockbox, LockboxOptions, ReadOnly, SecretVec};
use std::collections::BTreeMap;
use std::fmt;
use std::sync::{Arc, Mutex};

/// A failure to obtain bytes from an immutable external source.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SourceError {
    /// Fetch this bounded range from the same revision, then retry the operation.
    MissingRange {
        /// Absolute byte offset in the archive.
        offset: u64,
        /// Exact number of bytes required (may include block alignment).
        length: usize,
    },
    /// The bytes no longer belong to the original revision. Create a new reader.
    VersionChanged,
    /// The reader or source has been cancelled and cannot be reused.
    Cancelled,
    /// Invalid transport data, a short read, or another terminal source failure.
    Unavailable(String),
}
impl fmt::Display for SourceError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{self:?}")
    }
}
impl std::error::Error for SourceError {}

/// An immutable random-access source. Implementations may fetch synchronously or
/// return `MissingRange` for an asynchronous caller to satisfy between attempts.
///
/// The length and byte contents MUST remain fixed for the lifetime of a reader.
/// A transport must verify source identity on every fetch, including refetches
/// after eviction. This contract does not authenticate unsigned archive content.
pub trait ReadAtSource: Send + Sync + 'static {
    /// Fixed logical archive length, without materializing its bytes.
    fn len(&self) -> u64;
    /// Whether the logical source is empty.
    fn is_empty(&self) -> bool {
        self.len() == 0
    }
    /// Read into `output`, returning the number of bytes actually supplied.
    /// Short successful reads are rejected by reVault as terminal failures.
    fn read_at(&self, offset: u64, output: &mut [u8]) -> Result<usize, SourceError>;
    /// Check cancellation or known revision failure, even on a decoded-cache hit.
    fn validate(&self) -> Result<(), SourceError> {
        Ok(())
    }
}

/// A source failure, a normal archive error, or an exhausted retry budget.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ExternalReadError {
    /// A structured source failure; only `MissingRange` is retryable.
    Source(SourceError),
    /// A normal archive validation, lookup, or decoding failure.
    Archive(Error),
    /// Too many consecutive incomplete attempts; create a new reader with an
    /// appropriate cache/operation size instead of retrying indefinitely.
    RetryLimitExceeded,
}
impl fmt::Display for ExternalReadError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{self:?}")
    }
}
impl std::error::Error for ExternalReadError {}

/// Resource limits for one external reader. Sparse block memory is separately
/// bounded by [`SparseSource`]; decoded-page memory uses `lockbox.cache_limit`.
#[derive(Debug, Clone, Copy)]
pub struct ExternalReaderOptions {
    /// Maximum size of one physical source read, before allocation (default 64 MiB).
    pub max_read_bytes: usize,
    /// Maximum consecutive attempts that need more data (default 4096).
    pub max_missing_attempts: usize,
    /// Maximum cumulative physical read bytes across an operation and its retries
    /// (default 256 MiB), including reads satisfied from the sparse cache.
    pub max_source_bytes_per_operation: u64,
    /// Existing decoded-page cache and workload options.
    pub lockbox: LockboxOptions,
}
impl Default for ExternalReaderOptions {
    fn default() -> Self {
        Self {
            max_read_bytes: 64 * 1024 * 1024,
            max_missing_attempts: 4096,
            max_source_bytes_per_operation: 256 * 1024 * 1024,
            lockbox: LockboxOptions::default(),
        }
    }
}

/// A serialized, read-only external archive session. No raw lockbox or file
/// handle can escape the operation's borrow. Every operation checks source
/// failures independently of internal fallback results.
pub struct ExternalReader {
    storage: ExternalStorage,
    archive: Option<Lockbox<ReadOnly>>,
    key: Option<SecretVec>,
    options: ExternalReaderOptions,
    missing_attempts: usize,
    terminal: Option<ExternalReadError>,
}
impl ExternalReader {
    /// Create a lazy reader for an unencrypted archive (signed or unsigned).
    pub fn new(
        source: Arc<dyn ReadAtSource>,
        options: ExternalReaderOptions,
    ) -> Result<Self, ExternalReadError> {
        if source.is_empty()
            || options.max_read_bytes == 0
            || options.max_missing_attempts == 0
            || options.max_source_bytes_per_operation == 0
        {
            return Err(ExternalReadError::Archive(Error::InvalidInput(
                "external source length and limits must be nonzero".into(),
            )));
        }
        Ok(Self {
            storage: ExternalStorage {
                length: source.len(),
                source,
                failure: Arc::new(Mutex::new(None)),
                max_read_bytes: options.max_read_bytes,
                max_operation_bytes: options.max_source_bytes_per_operation,
                operation_bytes: Arc::new(Mutex::new(0)),
            },
            archive: None,
            key: None,
            options,
            missing_attempts: 0,
            terminal: None,
        })
    }
    /// Create a reader with an already obtained content key. Password/contact
    /// discovery is deliberately not performed by downloading the whole archive.
    pub fn with_content_key(
        source: Arc<dyn ReadAtSource>,
        key: SecretVec,
        options: ExternalReaderOptions,
    ) -> Result<Self, ExternalReadError> {
        let mut reader = Self::new(source, options)?;
        reader.key = Some(key);
        Ok(reader)
    }
    /// Cancel this session and release its decoded cache and retained content key.
    pub fn cancel(&mut self) {
        self.archive = None;
        self.key = None;
        self.terminal = Some(ExternalReadError::Source(SourceError::Cancelled));
    }
    /// Attempt one repeatable read operation. Fetch `MissingRange` externally and
    /// call again; all other source failures terminate this reader. A failed
    /// source read invalidates the parsed archive, so fallback-created partial
    /// metadata is never reused. Closures must defer side effects until success.
    pub fn try_read<T>(
        &mut self,
        operation: impl FnOnce(&Lockbox<ReadOnly>) -> crate::Result<T>,
    ) -> Result<T, ExternalReadError> {
        if let Some(error) = &self.terminal {
            return Err(error.clone());
        }
        self.storage
            .clear_failure()
            .map_err(ExternalReadError::Source)?;
        let validation = self.storage.source.validate().and_then(|()| {
            if self.storage.source.len() == self.storage.length {
                Ok(())
            } else {
                Err(SourceError::VersionChanged)
            }
        });
        if let Err(error) = validation {
            return self.fail_source(error);
        }
        // Keep candidate state local until the complete operation is validated.
        // Unwinding a source or caller callback therefore also discards it.
        let mut candidate = self.archive.take();
        let result = (|| {
            if candidate.is_none() {
                let key = match &self.key {
                    Some(key) => key.try_clone()?,
                    None => {
                        let header = self.storage.read_at(0, crate::constants::HEADER_LEN)?;
                        let header = crate::file_format::current_header::read_header(&header)?;
                        if !header.format_mode.plaintext() {
                            return Err(Error::InvalidInput(
                                "this external archive requires a content key".into(),
                            ));
                        }
                        SecretVec::try_from_slice(&[0; 32])?
                    }
                };
                let archive = Lockbox::open_storage_with_secret_key_mode(
                    StorageBackend::External(self.storage.clone()),
                    key,
                    self.options.lockbox,
                    false,
                )?;
                // Never invoke a caller's closure on an incompletely opened archive.
                if self.storage.failure().map_err(source_io)?.is_some() {
                    return Err(Error::Io("incomplete external open".into()));
                }
                candidate = Some(archive.into_state());
            }
            operation(
                candidate
                    .as_ref()
                    .ok_or_else(|| Error::InvalidOperation("external archive not open".into()))?,
            )
        })();
        if let Err(error) = self.storage.source.validate() {
            return self.fail_source(error);
        }
        if self.storage.source.len() != self.storage.length {
            return self.fail_source(SourceError::VersionChanged);
        }
        if let Some(error) = self.storage.failure().map_err(ExternalReadError::Source)? {
            return self.fail_source(error);
        }
        self.missing_attempts = 0;
        *self
            .storage
            .operation_bytes
            .lock()
            .map_err(|_| ExternalReadError::Source(poisoned()))? = 0;
        if result.is_ok() {
            self.archive = candidate;
        }
        result.map_err(ExternalReadError::Archive)
    }
    fn fail_source<T>(&mut self, error: SourceError) -> Result<T, ExternalReadError> {
        self.archive = None;
        let error = match error {
            SourceError::MissingRange { offset, length }
                if length == 0
                    || length > self.storage.max_read_bytes
                    || offset
                        .checked_add(length as u64)
                        .is_none_or(|end| end > self.storage.length) =>
            {
                SourceError::Unavailable(
                    "external source requested an invalid missing range".into(),
                )
            }
            other => other,
        };
        let failure = if matches!(error, SourceError::MissingRange { .. }) {
            self.missing_attempts += 1;
            if self.missing_attempts >= self.options.max_missing_attempts {
                ExternalReadError::RetryLimitExceeded
            } else {
                ExternalReadError::Source(error)
            }
        } else {
            ExternalReadError::Source(error)
        };
        if !matches!(
            failure,
            ExternalReadError::Source(SourceError::MissingRange { .. })
        ) {
            self.key = None;
            self.terminal = Some(failure.clone());
        }
        Err(failure)
    }
}

fn source_io(error: SourceError) -> Error {
    Error::Io(error.to_string())
}
fn poisoned() -> SourceError {
    SourceError::Unavailable("external source state poisoned".into())
}

#[derive(Clone)]
pub(crate) struct ExternalStorage {
    source: Arc<dyn ReadAtSource>,
    length: u64,
    failure: Arc<Mutex<Option<SourceError>>>,
    max_read_bytes: usize,
    max_operation_bytes: u64,
    operation_bytes: Arc<Mutex<u64>>,
}
impl fmt::Debug for ExternalStorage {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("ExternalStorage")
            .field("length", &self.length)
            .finish_non_exhaustive()
    }
}
impl ExternalStorage {
    fn failure(&self) -> Result<Option<SourceError>, SourceError> {
        Ok(self.failure.lock().map_err(|_| poisoned())?.clone())
    }
    fn clear_failure(&self) -> Result<(), SourceError> {
        *self.failure.lock().map_err(|_| poisoned())? = None;
        Ok(())
    }
    fn latch(&self, error: SourceError) -> Error {
        if let Ok(mut failure) = self.failure.lock() {
            if failure.is_none() {
                *failure = Some(error.clone());
            }
        }
        source_io(error)
    }
    fn bounds(&self, offset: u64, len: usize) -> crate::Result<()> {
        if len > self.max_read_bytes {
            return Err(self.latch(SourceError::Unavailable(
                "external read exceeds configured byte limit".into(),
            )));
        }
        if offset
            .checked_add(len as u64)
            .is_none_or(|end| end > self.length)
        {
            return Err(self.latch(SourceError::Unavailable(
                "external read exceeds source length".into(),
            )));
        }
        Ok(())
    }
}
impl Storage for ExternalStorage {
    fn len(&self) -> crate::Result<u64> {
        Ok(self.length)
    }
    fn read_at(&self, offset: u64, len: usize) -> crate::Result<Vec<u8>> {
        self.bounds(offset, len)?;
        let mut bytes = vec![0; len];
        self.read_at_into(offset, &mut bytes)?;
        Ok(bytes)
    }
    fn read_at_into(&self, offset: u64, out: &mut [u8]) -> crate::Result<()> {
        if let Some(error) = self.failure().map_err(source_io)? {
            return Err(source_io(error));
        }
        self.bounds(offset, out.len())?;
        if out.is_empty() {
            return Ok(());
        }
        {
            let mut spent = self
                .operation_bytes
                .lock()
                .map_err(|_| self.latch(poisoned()))?;
            let next = spent
                .checked_add(out.len() as u64)
                .filter(|value| *value <= self.max_operation_bytes);
            let Some(next) = next else {
                return Err(self.latch(SourceError::Unavailable(
                    "external operation exceeds cumulative read budget".into(),
                )));
            };
            *spent = next;
        }
        let result = self.source.read_at(offset, out);
        match result {
            Ok(count) if count == out.len() => Ok(()),
            Ok(_) => Err(self.latch(SourceError::Unavailable(
                "external source returned a short or oversized read".into(),
            ))),
            Err(SourceError::MissingRange { offset, length })
                if length == 0
                    || length > self.max_read_bytes
                    || offset
                        .checked_add(length as u64)
                        .is_none_or(|end| end > self.length) =>
            {
                Err(self.latch(SourceError::Unavailable(
                    "external source requested an invalid missing range".into(),
                )))
            }
            Err(error) => Err(self.latch(error)),
        }
    }
    fn read_at_secure(
        &self,
        offset: u64,
        len: usize,
    ) -> crate::Result<crate::secret_vec::SecureVec> {
        self.bounds(offset, len)?;
        let mut out = crate::secret_vec::SecureVec::new();
        out.resize_zeroed(len)?;
        out.with_mut_bytes(|bytes| self.read_at_into(offset, bytes))??;
        Ok(out)
    }
    fn append(&mut self, _: &[u8]) -> crate::Result<u64> {
        Err(Error::InvalidOperation(
            "external archive is read-only".into(),
        ))
    }
    fn write_at(&mut self, _: u64, _: &[u8]) -> crate::Result<()> {
        Err(Error::InvalidOperation(
            "external archive is read-only".into(),
        ))
    }
    fn sync(&self) -> crate::Result<()> {
        Ok(())
    }
}

/// Shared, bounded LRU block cache for asynchronous range delivery. All supplied
/// blocks must have the fixed revision identifier and exact aligned length.
/// Eviction relies on the transport validating that revision again on refetch.
/// The budget covers stored payload bytes; metadata is bounded by block count.
#[derive(Clone)]
pub struct SparseSource {
    length: u64,
    revision: Arc<str>,
    block_bytes: usize,
    capacity_bytes: usize,
    state: Arc<Mutex<SparseState>>,
}
#[derive(Default)]
struct SparseState {
    blocks: BTreeMap<u64, (Vec<u8>, u64)>,
    bytes: usize,
    clock: u64,
    terminal: Option<SourceError>,
}
impl SparseState {
    fn tick(&mut self) -> u64 {
        if self.clock == u64::MAX {
            for (_, age) in self.blocks.values_mut() {
                *age = 0;
            }
            self.clock = 0;
        }
        self.clock += 1;
        self.clock
    }
}
impl SparseSource {
    /// Create an empty cache. Blocks must be at least 512 bytes; the budget must
    /// hold at least one block. No allocation proportional to archive size occurs.
    pub fn new(
        length: u64,
        revision: String,
        block_bytes: usize,
        capacity_bytes: usize,
    ) -> Result<Self, SourceError> {
        if length == 0 || revision.is_empty() || block_bytes < 512 || capacity_bytes < block_bytes {
            return Err(SourceError::Unavailable(
                "invalid sparse length, revision, block size or budget".into(),
            ));
        }
        Ok(Self {
            length,
            revision: revision.into(),
            block_bytes,
            capacity_bytes,
            state: Arc::new(Mutex::new(SparseState::default())),
        })
    }
    /// Insert one aligned complete block (the final block may be shorter).
    /// Conflicting bytes or revisions invalidate the source and discard its cache.
    pub fn supply(&self, revision: &str, offset: u64, bytes: Vec<u8>) -> Result<(), SourceError> {
        let mut state = self.state.lock().map_err(|_| poisoned())?;
        if let Some(error) = &state.terminal {
            return Err(error.clone());
        }
        if revision != self.revision.as_ref() {
            state.blocks.clear();
            state.bytes = 0;
            state.terminal = Some(SourceError::VersionChanged);
            return Err(SourceError::VersionChanged);
        }
        if offset >= self.length
            || offset % self.block_bytes as u64 != 0
            || bytes.len() != (self.length - offset).min(self.block_bytes as u64) as usize
        {
            return Err(SourceError::Unavailable(
                "expected one exact aligned sparse block".into(),
            ));
        }
        if let Some((previous, _)) = state.blocks.get(&offset) {
            if previous != &bytes {
                state.blocks.clear();
                state.bytes = 0;
                state.terminal = Some(SourceError::VersionChanged);
                return Err(SourceError::VersionChanged);
            }
            let age = state.tick();
            if let Some((_, previous_age)) = state.blocks.get_mut(&offset) {
                *previous_age = age;
            }
            return Ok(());
        }
        while state.bytes > self.capacity_bytes - bytes.len() {
            let oldest = state
                .blocks
                .iter()
                .min_by_key(|(_, (_, age))| *age)
                .map(|(&offset, _)| offset)
                .ok_or_else(|| {
                    SourceError::Unavailable("invalid sparse cache accounting".into())
                })?;
            if let Some((removed, _)) = state.blocks.remove(&oldest) {
                state.bytes -= removed.len();
            }
        }
        let age = state.tick();
        state.bytes += bytes.len();
        state.blocks.insert(offset, (bytes, age));
        Ok(())
    }
    /// Payload bytes currently retained, excluding decoded pages and in-flight I/O.
    pub fn cached_bytes(&self) -> Result<usize, SourceError> {
        Ok(self.state.lock().map_err(|_| poisoned())?.bytes)
    }
    /// Cancel every reader sharing this source and discard its cached blocks.
    pub fn cancel(&self) -> Result<(), SourceError> {
        let mut state = self.state.lock().map_err(|_| poisoned())?;
        state.blocks.clear();
        state.bytes = 0;
        state.terminal = Some(SourceError::Cancelled);
        Ok(())
    }
}
impl ReadAtSource for SparseSource {
    fn len(&self) -> u64 {
        self.length
    }
    fn validate(&self) -> Result<(), SourceError> {
        match &self.state.lock().map_err(|_| poisoned())?.terminal {
            Some(error) => Err(error.clone()),
            None => Ok(()),
        }
    }
    fn read_at(&self, offset: u64, output: &mut [u8]) -> Result<usize, SourceError> {
        let end = offset
            .checked_add(output.len() as u64)
            .filter(|end| *end <= self.length)
            .ok_or_else(|| SourceError::Unavailable("sparse read outside source".into()))?;
        let mut state = self.state.lock().map_err(|_| poisoned())?;
        if let Some(error) = &state.terminal {
            return Err(error.clone());
        }
        let mut position = offset;
        while position < end {
            let start = position / self.block_bytes as u64 * self.block_bytes as u64;
            let age = state.tick();
            let (bytes, last_used) =
                state
                    .blocks
                    .get_mut(&start)
                    .ok_or(SourceError::MissingRange {
                        offset: start,
                        length: (self.length - start).min(self.block_bytes as u64) as usize,
                    })?;
            let finish = end.min(start + bytes.len() as u64);
            output[(position - offset) as usize..(finish - offset) as usize]
                .copy_from_slice(&bytes[(position - start) as usize..(finish - start) as usize]);
            *last_used = age;
            position = finish;
        }
        Ok(output.len())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    #[test]
    fn backend_refuses_every_mutation_and_checks_limits_before_secure_allocation() {
        let source = Arc::new(SparseSource::new(4096, "v1".into(), 512, 512).unwrap());
        let mut storage = ExternalStorage {
            source,
            length: 4096,
            max_read_bytes: 1024,
            max_operation_bytes: 8192,
            operation_bytes: Arc::new(Mutex::new(0)),
            failure: Arc::new(Mutex::new(None)),
        };
        assert!(storage.append(b"x").is_err());
        assert!(storage.write_at(0, b"x").is_err());
        assert!(StorageBackend::External(storage.clone())
            .read_at_secure(0, usize::MAX)
            .is_err());
        assert!(matches!(
            storage.failure().unwrap(),
            Some(SourceError::Unavailable(_))
        ));
        assert!(StorageBackend::External(storage).is_read_only());
    }
}