revault_lockbox_api 0.0.59

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
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
//! 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 {
    pub(crate) fn ensure_current(&self) -> crate::Result<()> {
        if let Some(error) = self.failure().map_err(source_io)? {
            return Err(source_io(error));
        }
        self.source.validate().map_err(|error| self.latch(error))?;
        if self.source.len() != self.length {
            return Err(self.latch(SourceError::VersionChanged));
        }
        Ok(())
    }

    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 truncate(&mut self, _: u64) -> 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::*;

    #[cfg(feature = "native-block-layout")]
    #[test]
    fn small_native_whole_reads_capture_once_and_preserve_source_failures() {
        use crate::{
            Compression, Encryption, LockboxCreateOptions, LockboxProtection, OwnerSigningKeyPair,
            Signing, SizePadding,
        };
        use std::io::Read;
        struct Probe {
            bytes: Vec<u8>,
            reads: Mutex<usize>,
            cancel_on_read: bool,
            cancelled: Mutex<bool>,
        }
        impl ReadAtSource for Probe {
            fn len(&self) -> u64 {
                self.bytes.len() as u64
            }
            fn validate(&self) -> Result<(), SourceError> {
                if *self.cancelled.lock().unwrap() {
                    Err(SourceError::Cancelled)
                } else {
                    Ok(())
                }
            }
            fn read_at(&self, offset: u64, out: &mut [u8]) -> Result<usize, SourceError> {
                *self.reads.lock().unwrap() += 1;
                out.copy_from_slice(&self.bytes[offset as usize..offset as usize + out.len()]);
                if self.cancel_on_read {
                    *self.cancelled.lock().unwrap() = true;
                }
                Ok(out.len())
            }
        }
        let signer = OwnerSigningKeyPair::generate().unwrap();
        let input = (0..4096).map(|n| (n % 251) as u8).collect::<Vec<_>>();
        let path = crate::LockboxPath::new("/small").unwrap();
        for encrypted in [false, true] {
            for signed in [false, true] {
                for compression in [Compression::None, Compression::default()] {
                    for size_padding in [SizePadding::Default, SizePadding::None] {
                        let mut archive =
                            crate::Lockbox::create_in_memory_with_options(LockboxCreateOptions {
                                compression,
                                size_padding,
                                ..LockboxCreateOptions::new(
                                    if encrypted {
                                        Encryption::Encrypted(LockboxProtection::ContentKey(
                                            crate::SecretVec::try_from_slice(&[67; 32]).unwrap(),
                                        ))
                                    } else {
                                        Encryption::None
                                    },
                                    if signed {
                                        Signing::Owner(&signer)
                                    } else {
                                        Signing::None
                                    },
                                )
                            })
                            .unwrap();
                        archive.add_file(&path, &input, false).unwrap();
                        archive.commit().unwrap();
                        let bytes = archive.to_bytes();
                        for case in 0..8 {
                            let through_handle = case >= 4;
                            let fault = case % 4;
                            let mut source_bytes = bytes.clone();
                            // Private source replacement supplies mid-read cancellation
                            // and corrupted bytes that public mutation APIs cannot emit.
                            if fault >= 2 {
                                let offset = source_bytes.windows(crate::page::PAGE_HEADER_LEN).position(crate::file_format::indexed_frame::block_page::is_native_header).unwrap();
                                if fault == 2 {
                                    source_bytes[offset + crate::page::PAGE_HEADER_LEN + 4] ^= 1;
                                } else {
                                    let len = crate::page::physical_page_size_from_page_slice(
                                        &source_bytes[offset..],
                                    )
                                    .unwrap();
                                    source_bytes.truncate(offset + len - 1);
                                }
                            }
                            let source = Arc::new(Probe {
                                bytes: source_bytes,
                                reads: Mutex::new(0),
                                cancel_on_read: fault == 1,
                                cancelled: Mutex::new(false),
                            });
                            let session = ExternalReader::new(
                                source.clone(),
                                ExternalReaderOptions::default(),
                            )
                            .unwrap();
                            crate::lockbox::block_frame_tests::replace_storage(
                                &mut archive,
                                crate::storage::StorageBackend::External(session.storage.clone()),
                            );
                            let read = || -> crate::Result<Vec<u8>> {
                                if !through_handle {
                                    return archive.get_file(&path);
                                }
                                let mut handle = archive.open_file(&path)?;
                                let mut bytes = Vec::new();
                                handle
                                    .read_to_end(&mut bytes)
                                    .map_err(|e| crate::Error::Io(e.to_string()))?;
                                Ok(bytes)
                            };
                            if fault == 0 {
                                assert_eq!(read().unwrap(), input);
                                assert_eq!(
                                    *source.reads.lock().unwrap(),
                                    1,
                                    "one bounded source read per cold small frame"
                                );
                                assert_eq!(read().unwrap(), input);
                                assert_eq!(
                                    *source.reads.lock().unwrap(),
                                    1,
                                    "warm read reuses verified cache"
                                );
                            } else if fault == 1 {
                                assert!(read().is_err());
                                *source.cancelled.lock().unwrap() = false;
                                assert!(
                                    read().is_err(),
                                    "terminal source failure must stay latched"
                                );
                                assert_eq!(*source.reads.lock().unwrap(), 1);
                            } else {
                                assert!(read().is_err());
                            }
                        }
                    }
                }
            }
        }
    }

    #[test]
    fn native_file_handle_retains_index_and_bounds_raw_reads_without_bypassing_failure_latch() {
        use crate::{
            Compression, Encryption, LockboxCreateOptions, LockboxProtection, OwnerSigningKeyPair,
            Signing, SizePadding,
        };
        use std::io::{Read, Seek, SeekFrom};
        struct Probe {
            bytes: Vec<u8>,
            cancelled: Mutex<bool>,
            reads: Mutex<Vec<(u64, usize)>>,
        }
        impl ReadAtSource for Probe {
            fn len(&self) -> u64 {
                self.bytes.len() as u64
            }
            fn validate(&self) -> Result<(), SourceError> {
                if *self.cancelled.lock().unwrap() {
                    Err(SourceError::Cancelled)
                } else {
                    Ok(())
                }
            }
            fn read_at(&self, offset: u64, out: &mut [u8]) -> Result<usize, SourceError> {
                self.reads.lock().unwrap().push((offset, out.len()));
                out.copy_from_slice(&self.bytes[offset as usize..offset as usize + out.len()]);
                Ok(out.len())
            }
        }
        let signer = OwnerSigningKeyPair::generate().unwrap();
        let input = (0..2 * 1024 * 1024 + 13)
            .map(|n| (n % 251) as u8)
            .collect::<Vec<_>>();
        for encrypted in [false, true] {
            for signed in [false, true] {
                for compression in [Compression::None, Compression::default()] {
                    for size_padding in [SizePadding::Default, SizePadding::None] {
                        let mut archive =
                            Lockbox::create_in_memory_with_options(LockboxCreateOptions {
                                compression,
                                size_padding,
                                ..LockboxCreateOptions::new(
                                    if encrypted {
                                        Encryption::Encrypted(LockboxProtection::ContentKey(
                                            SecretVec::try_from_slice(&[67; 32]).unwrap(),
                                        ))
                                    } else {
                                        Encryption::None
                                    },
                                    if signed {
                                        Signing::Owner(&signer)
                                    } else {
                                        Signing::None
                                    },
                                )
                            })
                            .unwrap();
                        archive.commit().unwrap();
                        // Unit-level injection: there is not yet a public writer for
                        // native block pages. Test the real public Read/Seek handle.
                        let paths =
                            crate::lockbox::block_frame_tests::install(&mut archive, &input);
                        let expected = &input[input.len() / 2..];
                        let source = Arc::new(Probe {
                            bytes: archive.to_bytes(),
                            cancelled: Mutex::new(false),
                            reads: Mutex::new(Vec::new()),
                        });
                        let session =
                            ExternalReader::new(source.clone(), ExternalReaderOptions::default())
                                .unwrap();
                        crate::lockbox::block_frame_tests::replace_storage(
                            &mut archive,
                            StorageBackend::External(session.storage.clone()),
                        );
                        archive.set_workload_profile(crate::WorkloadProfile::ExtractMany);
                        let mut reader = archive.open_file(&paths[1]).unwrap();
                        reader.seek(SeekFrom::Start(7)).unwrap();
                        let mut small = [0; 13];
                        reader.read_exact(&mut small).unwrap();
                        assert_eq!(small, expected[7..20]);
                        let initial = source.reads.lock().unwrap().clone();
                        assert_eq!(initial.len(), 4, "header, metadata, index, data");
                        if compression == Compression::None {
                            assert_eq!(initial[3].1, 16384 + if encrypted { 16 } else { 0 });
                        }
                        // A repeated read within the window needs no metadata,
                        // index, or data fetch, in either codec mode.
                        reader.seek(SeekFrom::Start(7)).unwrap();
                        reader.read_exact(&mut small).unwrap();
                        assert_eq!(small, expected[7..20]);
                        assert_eq!(*source.reads.lock().unwrap(), initial);
                        // Independent handles share authenticated cached blocks.
                        let mut second = archive.open_file(&paths[1]).unwrap();
                        second.seek(SeekFrom::Start(7)).unwrap();
                        second.read_exact(&mut small).unwrap();
                        assert_eq!(small, expected[7..20]);
                        assert_eq!(*source.reads.lock().unwrap(), initial);
                        drop(second);
                        reader.seek(SeekFrom::Start(32770)).unwrap();
                        reader.read_exact(&mut small).unwrap();
                        assert_eq!(small, expected[32770..32783]);
                        assert_eq!(
                            source.reads.lock().unwrap().len(),
                            initial.len() + usize::from(compression == Compression::None)
                        );
                        // Sequential consumption reuses the index and preserves bytes
                        // across windows and the unaligned packed-file boundary.
                        reader.rewind().unwrap();
                        let mut actual = Vec::new();
                        let mut buffer = [0; 65536];
                        loop {
                            let count = reader.read(&mut buffer).unwrap();
                            if count == 0 {
                                break;
                            }
                            actual.extend_from_slice(&buffer[..count]);
                        }
                        assert_eq!(actual, expected);
                        assert!(
                            source.reads.lock().unwrap()[4..]
                                .iter()
                                .all(|(offset, _)| *offset >= initial[3].0),
                            "sequential reads must not reload metadata or the index"
                        );
                        if compression != Compression::None {
                            assert_eq!(
                                source.reads.lock().unwrap().len(),
                                4,
                                "decode once per retained chunk"
                            );
                        }
                        reader.seek(SeekFrom::End(-13)).unwrap();
                        reader.read_exact(&mut small).unwrap();
                        if compression == Compression::None {
                            let before = source.reads.lock().unwrap().len();
                            let mut neighbor = archive.open_file(&paths[0]).unwrap();
                            let mut bytes = [0; 13];
                            neighbor.read_exact(&mut bytes).unwrap();
                            assert_eq!(bytes, input[..13]);
                            let reads = source.reads.lock().unwrap();
                            assert_eq!(
                                reads.len(),
                                before + 1,
                                "new raw handles reuse metadata/index but verify requested data"
                            );
                            assert_eq!(reads[before].1, 16384 + if encrypted { 16 } else { 0 });
                        }
                        assert_eq!(
                            archive.get_file(&paths[0]).unwrap(),
                            input[..input.len() / 2]
                        );
                        assert_eq!(
                            archive.decoded_compression_frame_cache_entries_for_tests(),
                            1
                        );
                        let before_cached = source.reads.lock().unwrap().len();
                        assert_eq!(
                            archive.read_file_range(&paths[1], 7, 13).unwrap(),
                            expected[7..20]
                        );
                        assert_eq!(source.reads.lock().unwrap().len(), before_cached,
                            "verified decoded cache hit reuses metadata and index without source reads");
                        if compression != Compression::None {
                            let before = source.reads.lock().unwrap().len();
                            let mut neighbor = archive.open_file(&paths[0]).unwrap();
                            let mut bytes = Vec::new();
                            neighbor.read_to_end(&mut bytes).unwrap();
                            assert_eq!(bytes, input[..input.len() / 2]);
                            assert_eq!(
                                source.reads.lock().unwrap().len(),
                                before,
                                "new compressed handles reuse the verified shared frame"
                            );
                        }
                        let count = source.reads.lock().unwrap().len();
                        *source.cancelled.lock().unwrap() = true;
                        reader.seek(SeekFrom::End(-13)).unwrap();
                        assert!(reader.read_exact(&mut small).is_err());
                        assert!(archive.get_file(&paths[0]).is_err());
                        *source.cancelled.lock().unwrap() = false;
                        assert!(archive.read_file_range(&paths[1], 7, 13).is_err());
                        assert!(
                            reader.read_exact(&mut small).is_err(),
                            "cache cannot clear terminal failure"
                        );
                        assert_eq!(source.reads.lock().unwrap().len(), count);
                        drop(reader);
                        let session =
                            ExternalReader::new(source.clone(), ExternalReaderOptions::default())
                                .unwrap();
                        crate::lockbox::block_frame_tests::replace_storage(
                            &mut archive,
                            StorageBackend::External(session.storage.clone()),
                        );
                        use crate::{
                            ContentStreamOrder::{Logical, Physical},
                            WorkloadProfile::{ExtractMany, Interactive},
                        };
                        for (profile, order, expected_reads) in [
                            (Interactive, Logical, 1),
                            (Interactive, Physical, 1),
                            (ExtractMany, Logical, 1),
                            (ExtractMany, Physical, 3),
                        ] {
                            archive.set_workload_profile(profile);
                            if matches!(profile, Interactive) {
                                let mut visited = 0;
                                assert!(archive
                                    .stream_content(
                                        crate::ContentStreamOptions { order },
                                        |_, _| {
                                            visited += 1;
                                            Err(crate::Error::Io("visitor stopped".into()))
                                        }
                                    )
                                    .is_err());
                                assert_eq!(visited, 1);
                            }
                            source.reads.lock().unwrap().clear();
                            let mut actual = Vec::new();
                            archive
                                .stream_content(
                                    crate::ContentStreamOptions { order },
                                    |_, reader| {
                                        reader.read_to_end(&mut actual).unwrap();
                                        Ok(())
                                    },
                                )
                                .unwrap();
                            assert_eq!(actual, input);
                            assert_eq!(source.reads.lock().unwrap().len(), expected_reads,
                                "packed stream reuses retained index; decoded-cache replacement reloads only metadata/index");
                        }
                        let mut visited = 0;
                        let result = archive.stream_content(Default::default(), |_, _| {
                            visited += 1;
                            *source.cancelled.lock().unwrap() = true;
                            Ok(())
                        });
                        assert!(result.is_err());
                        assert_eq!(
                            visited, 1,
                            "cancelled source cannot deliver its retained neighbor"
                        );
                        *source.cancelled.lock().unwrap() = false;
                        assert!(archive
                            .stream_content(Default::default(), |_, _| Ok(()))
                            .is_err());
                    }
                }
            }
        }
    }

    #[test]
    fn native_block_reader_preserves_external_failure_latching_in_every_mode() {
        use crate::file_format::indexed_frame::{encode_block_frame, BlockFrameReader};
        use crate::{Compression, EncryptionMode, LockboxFormatOptions, SigningMode, SizePadding};
        struct Probe {
            bytes: Vec<u8>,
            state: Mutex<u8>,
            reads: Mutex<Vec<(u64, usize)>>,
        }
        impl ReadAtSource for Probe {
            fn len(&self) -> u64 {
                self.bytes.len() as u64 + u64::from(*self.state.lock().unwrap() == 5)
            }
            fn validate(&self) -> Result<(), SourceError> {
                match *self.state.lock().unwrap() {
                    1 => Err(SourceError::Cancelled),
                    2 => Err(SourceError::VersionChanged),
                    _ => Ok(()),
                }
            }
            fn read_at(&self, offset: u64, out: &mut [u8]) -> Result<usize, SourceError> {
                self.reads.lock().unwrap().push((offset, out.len()));
                let state = *self.state.lock().unwrap();
                if state == 4 {
                    return Err(SourceError::MissingRange {
                        offset,
                        length: out.len(),
                    });
                }
                out.copy_from_slice(&self.bytes[offset as usize..offset as usize + out.len()]);
                Ok(out.len() - usize::from(state == 3 && !out.is_empty()))
            }
        }
        let key = [29; 32];
        for encrypted in [false, true] {
            for signed in [false, true] {
                for compressed in [false, true] {
                    let mode = crate::creation_options::FormatMode::new(LockboxFormatOptions {
                        encryption: if encrypted {
                            EncryptionMode::ChaCha20Poly1305
                        } else {
                            EncryptionMode::None
                        },
                        signing: if signed {
                            SigningMode::Owner
                        } else {
                            SigningMode::None
                        },
                        compression: if compressed {
                            Compression::default()
                        } else {
                            Compression::None
                        },
                        size_padding: SizePadding::Default,
                    });
                    let (descriptor, packet) = encode_block_frame(
                        crate::LockboxId::from_bytes([71; 16]),
                        31,
                        mode,
                        &[43; 32768],
                        &key,
                    )
                    .unwrap();
                    for failure in 1..=5 {
                        let source = Arc::new(Probe {
                            bytes: packet.clone(),
                            state: Mutex::new(0),
                            reads: Mutex::new(Vec::new()),
                        });
                        let session =
                            ExternalReader::new(source.clone(), ExternalReaderOptions::default())
                                .unwrap();
                        let backend = StorageBackend::External(session.storage.clone());
                        let reader =
                            BlockFrameReader::open(&descriptor, &backend, 0, packet.len(), &key)
                                .unwrap();
                        assert_eq!(
                            source.reads.lock().unwrap().len(),
                            1,
                            "open must read only the committed index"
                        );
                        assert_eq!(reader.read(7..19).unwrap(), [43; 12]);
                        assert_eq!(source.reads.lock().unwrap().len(), 2);
                        if !compressed {
                            assert_eq!(
                                source.reads.lock().unwrap()[1].1,
                                16384 + if encrypted { 16 } else { 0 }
                            );
                        }
                        *source.state.lock().unwrap() = failure;
                        if !encrypted && !compressed {
                            let mut direct = vec![88; 32768];
                            assert!(reader.read_aligned_raw_into(0..32768, &mut direct).is_err());
                            assert_eq!(
                                direct,
                                vec![0; 32768],
                                "direct I/O failures wipe the entire destination"
                            );
                        }
                        assert!(reader.read(7..19).is_err());
                        let latched = session.storage.failure().unwrap().unwrap();
                        match failure {
                            1 => assert_eq!(latched, SourceError::Cancelled),
                            2 | 5 => assert_eq!(latched, SourceError::VersionChanged),
                            3 => assert!(matches!(latched, SourceError::Unavailable(_))),
                            4 => assert!(matches!(latched, SourceError::MissingRange { .. })),
                            _ => unreachable!(),
                        }
                        *source.state.lock().unwrap() = 0;
                        let reads_before_retry = source.reads.lock().unwrap().len();
                        // Even empty reads after a cached index must reject the latch.
                        assert!(reader.read(0..0).is_err());
                        assert!(reader.read(7..19).is_err());
                        assert_eq!(source.reads.lock().unwrap().len(), reads_before_retry);
                        if failure == 4 {
                            // Only the checked external operation may reset a retryable
                            // MissingRange between attempts; the block reader cannot.
                            session.storage.clear_failure().unwrap();
                            assert_eq!(reader.read(7..19).unwrap(), [43; 12]);
                        }
                    }
                }
            }
        }
    }

    #[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!(storage.truncate(0).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());
    }
}