1use std::path::{Path, PathBuf};
7use std::sync::Arc;
8#[cfg(test)]
9use std::sync::{Mutex, MutexGuard};
10
11#[cfg(test)]
12use crate::backend::local::LocalConn;
13
14use uuid::Uuid;
15use vcon::read::Inspection;
16
17use crate::audit::{self, Action, Actor, Entry};
18use crate::backend::local::{LocalCatalog, LocalObjects};
19use crate::backend::{
20 Catalog, CatalogTx, CommitError, NewVersion, ObjectError, Objects, Packed, Packs,
21};
22use crate::catalog;
23use crate::clock::{Clock, nanos};
24use crate::envelope::{self, Context, Key, WrapLimit};
25use crate::fs::Fs;
26use crate::ids::{KeyId, TenantId, VersionId};
27use crate::retention::Retention;
28use crate::reveal::Part;
29
30mod backup;
31mod compact;
32mod examine;
33mod export;
34mod legal;
35mod list;
36mod manifest;
37pub(crate) mod packed;
38pub(crate) mod packer;
39mod purge;
40mod rekey;
41mod rewrite;
42
43pub use backup::{BackupError, Copied, TRIES};
44pub use examine::{Examination, ExamineError};
45pub use export::KeptVersion;
46pub use legal::{Legal, VersionInfo};
47pub use list::{Cursor, ListQuery, Listed, Listing};
48pub use purge::{Kept, PurgeReport, due};
49
50#[derive(Debug, Clone, Copy, PartialEq, Eq)]
52pub struct Caller {
53 pub key: KeyId,
54}
55
56#[derive(Debug, Clone, Copy, PartialEq, Eq)]
58pub enum Created {
59 New(VersionId),
61 Same(VersionId),
63}
64
65#[derive(Debug, Clone, PartialEq, Eq)]
67pub struct Stored {
68 pub version: VersionId,
69 pub form: vcon::Form,
70 pub gzip: bool,
72 pub body: Vec<u8>,
74}
75
76#[derive(Debug, Clone, Copy, PartialEq, Eq)]
78pub struct Counts {
79 pub versions: u64,
81 pub held: u64,
83}
84
85#[derive(Debug, Clone, Copy, PartialEq, Eq)]
87pub enum StoreError {
88 Conflict,
89 Gone,
90 NotFound,
91 NotDeleted,
92 PreconditionFailed,
93 Immutable,
94 LimitReached,
96 Damaged,
98 AuditFailed,
100 Io,
101}
102
103#[derive(Debug)]
106pub enum OpenError {
107 WrongKey,
109 Access {
112 path: PathBuf,
113 error: std::io::Error,
114 },
115 Store(StoreError),
117}
118
119impl From<OpenError> for StoreError {
120 fn from(_: OpenError) -> StoreError {
122 StoreError::Io
123 }
124}
125
126impl From<StoreError> for OpenError {
127 fn from(e: StoreError) -> OpenError {
128 OpenError::Store(e)
129 }
130}
131
132impl From<catalog::CatalogError> for OpenError {
133 fn from(e: catalog::CatalogError) -> OpenError {
134 match e {
135 catalog::CatalogError::WrongKey => OpenError::WrongKey,
136 catalog::CatalogError::Access { path, error } => OpenError::Access { path, error },
137 _ => OpenError::Store(StoreError::Io),
138 }
139 }
140}
141
142type Tx<'a> = Box<dyn CatalogTx + 'a>;
144
145pub struct Store {
147 tenant: TenantId,
148 tenant_key: Key,
149 catalog: Box<dyn Catalog>,
150 objects: Arc<dyn Objects>,
151 packs: Option<Arc<dyn Packs>>,
154 footers: packed::Footers,
156 fs: Arc<dyn Fs>,
158 clock: Arc<dyn Clock>,
159 #[cfg(test)]
161 objects_dir: PathBuf,
162 #[cfg(test)]
163 hooks: tests::Hooks,
164}
165
166impl Store {
167 pub fn open(
170 dir: &Path,
171 tenant: TenantId,
172 tenant_key: Key,
173 fs: Arc<dyn Fs>,
174 clock: Arc<dyn Clock>,
175 ) -> Result<Store, OpenError> {
176 let store = Store::open_beside(dir, tenant, tenant_key, fs, clock)?;
177 store.recover()?;
178 Ok(store)
179 }
180
181 pub fn open_beside(
185 dir: &Path,
186 tenant: TenantId,
187 tenant_key: Key,
188 fs: Arc<dyn Fs>,
189 clock: Arc<dyn Clock>,
190 ) -> Result<Store, OpenError> {
191 let catalog_key = envelope::catalog_key(&tenant_key).map_err(|_| StoreError::Io)?;
192 let catalog = LocalCatalog::open(&dir.join("catalog.sqlite"), catalog_key)?;
193 let objects = dir.join("objects");
194 fs.create_dir_all(&objects).map_err(|_| StoreError::Io)?;
195 catalog::may_use(&objects, libc::W_OK | libc::X_OK)?;
197 fs.sync_dir(dir).map_err(|_| StoreError::Io)?;
201 #[cfg_attr(
202 not(test),
203 allow(unused_mut, reason = "only tests set the objects directory after")
204 )]
205 let mut store = Store::with_backends(
206 tenant,
207 tenant_key,
208 Box::new(catalog),
209 Arc::new(LocalObjects::new(objects.clone(), fs.clone())),
210 None,
211 fs,
212 clock,
213 );
214 #[cfg(test)]
215 {
216 store.objects_dir = objects;
217 }
218 Ok(store)
219 }
220
221 #[cfg(feature = "s3")]
224 #[expect(
225 clippy::too_many_arguments,
226 reason = "each backend is its own argument"
227 )]
228 pub(crate) fn open_on(
229 tenant: TenantId,
230 tenant_key: Key,
231 catalog: Box<dyn Catalog>,
232 objects: Arc<dyn Objects>,
233 packs: Option<Arc<dyn Packs>>,
234 fs: Arc<dyn Fs>,
235 clock: Arc<dyn Clock>,
236 recover: bool,
237 ) -> Result<Store, OpenError> {
238 let store = Store::with_backends(tenant, tenant_key, catalog, objects, packs, fs, clock);
239 if recover {
240 store.recover()?;
241 }
242 Ok(store)
243 }
244
245 pub(crate) fn with_backends(
248 tenant: TenantId,
249 tenant_key: Key,
250 catalog: Box<dyn Catalog>,
251 objects: Arc<dyn Objects>,
252 packs: Option<Arc<dyn Packs>>,
253 fs: Arc<dyn Fs>,
254 clock: Arc<dyn Clock>,
255 ) -> Store {
256 Store {
257 tenant,
258 tenant_key,
259 catalog,
260 objects,
261 packs,
262 footers: packed::Footers::new(packed::FOOTERS),
263 fs,
264 clock,
265 #[cfg(test)]
266 objects_dir: PathBuf::new(),
267 #[cfg(test)]
268 hooks: tests::Hooks::default(),
269 }
270 }
271
272 fn recover(&self) -> Result<(), StoreError> {
277 self.catalog.recover()?;
278 let (places, files) = {
279 let mut tx = self.catalog.snapshot()?;
280 let places: std::collections::HashMap<VersionId, bool> = tx
281 .places()?
282 .into_iter()
283 .map(|(version, place)| (version, names_its_object(&place)))
284 .collect();
285 let files: std::collections::HashSet<_> = tx.pack_files()?.into_iter().collect();
286 (places, files)
287 };
288 let mut removed: u64 = 0;
289 for name in self.objects.list().map_err(io)? {
290 let (id, temporary) = match name.strip_suffix(".tmp") {
291 Some(id) => (id, true),
292 None => (name.as_str(), false),
293 };
294 let Some(version) = VersionId::parse(id) else {
295 continue;
296 };
297 if temporary || !places.get(&version).copied().unwrap_or(false) {
298 self.objects.remove_name(&name).map_err(io)?;
299 removed += 1;
300 }
301 }
302 if let Some(packs) = &self.packs {
303 let mut unnamed: u64 = 0;
304 for name in packs.list().map_err(io)? {
307 let Some((_, file)) = packed::parse_name(&name) else {
308 continue;
309 };
310 if !files.contains(&file) {
311 packs.remove(&name).map_err(io)?;
312 unnamed += 1;
313 }
314 }
315 if unnamed > 0 {
316 tracing::info!(
317 removed = unnamed,
318 "start-up recovery removed pack files that no catalog row names"
319 );
320 }
321 }
322 self.finish_purges()?;
323 self.publish()?;
324 if removed > 0 {
325 self.objects.sync().map_err(io)?;
326 tracing::info!(
329 removed,
330 "start-up recovery removed objects that no catalog row names"
331 );
332 }
333 Ok(())
334 }
335
336 pub fn create(
341 &self,
342 who: &Caller,
343 found: &Inspection,
344 body: &[u8],
345 ) -> Result<Created, StoreError> {
346 let uuid = found.uuid;
347 let entry = |status, version| Entry {
348 actor: Actor::Key(who.key),
349 action: Action::Create,
350 target: Some(uuid.to_string()),
351 version,
352 status,
353 };
354 let key_id = self.tenant_key.id();
355 {
356 let mut tx = self.catalog.immediate()?;
357 let refused = match state(&mut tx, uuid)? {
358 State::Gone => Some((410, None, StoreError::Gone)),
359 State::Live(current) => match self.read_version(&mut tx, uuid, current) {
360 Ok(stored) if stored == body => {
361 self.record(&mut tx, &entry(200, Some(current)))?;
362 commit(tx)?;
363 return Ok(Created::Same(current));
364 }
365 Ok(_) => Some((409, None, StoreError::Conflict)),
366 Err(StoreError::Damaged) => Some((500, Some(current), StoreError::Damaged)),
367 Err(e) => return Err(e),
368 },
369 State::Absent if envelope::wrap_limit(tx.wraps(key_id)?) == WrapLimit::Refuse => {
370 Some((503, None, StoreError::LimitReached))
371 }
372 State::Absent => {
375 tx.add_wrap(key_id)?;
376 None
377 }
378 };
379 if let Some((status, version, error)) = refused {
380 self.record(&mut tx, &entry(status, version))?;
381 commit(tx)?;
382 return Err(error);
383 }
384 commit(tx)?;
385 }
386
387 let (version, wrapped) = self.write_version(uuid, body)?;
388 self.pause();
389
390 let unknown = std::cell::Cell::new(false);
391 let committed = (|| {
392 let mut tx = self.catalog.immediate()?;
393 match state(&mut tx, uuid)? {
394 State::Absent => {}
395 lost => {
396 let (status, error) = match lost {
397 State::Gone => (410, StoreError::Gone),
398 _ => (409, StoreError::Conflict),
399 };
400 self.record(&mut tx, &entry(status, None))?;
401 commit(tx)?;
402 return Err(error);
403 }
404 }
405 let stored_at = nanos(self.clock.now());
408 tx.insert_version(&NewVersion {
409 version,
410 uuid,
411 form: form_name(found.form),
412 gzip: found.gzip,
413 size: i64::try_from(body.len()).map_err(io)?,
414 stored_at,
415 key: key_id,
416 wrapped: &wrapped,
417 })?;
418 tx.insert_vcon(uuid, version, stored_at)?;
419 self.record(&mut tx, &entry(201, Some(version)))?;
420 kept(tx.commit(), &unknown)?;
421 Ok(Created::New(version))
422 })();
423 self.drop_unless_kept(committed.is_err(), unknown.get(), version);
424 #[cfg(test)]
425 if committed.is_ok() {
426 self.forced_pack();
427 }
428 committed
429 }
430
431 pub fn get(&self, who: &Caller, uuid: Uuid) -> Result<Stored, StoreError> {
436 self.read_as(who, uuid, Action::Read)
437 }
438
439 pub fn reveal(&self, who: &Caller, uuid: Uuid, part: Part) -> Result<Stored, StoreError> {
443 self.read_as(who, uuid, Action::Reveal(part))
444 }
445
446 fn read_as(&self, who: &Caller, uuid: Uuid, action: Action) -> Result<Stored, StoreError> {
449 let entry = |status, version| Entry {
450 actor: Actor::Key(who.key),
451 action,
452 target: Some(uuid.to_string()),
453 version,
454 status,
455 };
456 let refuse = |mut tx: Tx, state: State| {
457 let (status, error) = match state {
458 State::Gone => (410, StoreError::Gone),
459 _ => (404, StoreError::NotFound),
460 };
461 self.record(&mut tx, &entry(status, None))?;
462 commit(tx)?;
463 Err(error)
464 };
465 loop {
466 let (version, row) = {
467 let mut tx = self.catalog.immediate()?;
468 match state(&mut tx, uuid)? {
469 State::Live(version) => (version, version_row(&mut tx, version)),
470 other => return refuse(tx, other),
471 }
472 };
473 let place = row.as_ref().ok().and_then(|r| r.place.clone());
474 #[cfg(test)]
475 {
476 let hook = self.hooks.before_read.lock().expect("hook").take();
477 if let Some(hook) = hook {
478 hook();
479 }
480 }
481 let opened = row.and_then(|row| {
482 let body = self.open_version(uuid, version, &row)?;
483 Ok(Stored {
484 version,
485 form: row.form,
486 gzip: row.gzip,
487 body,
488 })
489 });
490 self.pause();
491 let mut tx = self.catalog.immediate()?;
492 match state(&mut tx, uuid)? {
493 State::Live(now)
497 if now == version
498 && opened.is_err()
499 && place.is_some()
500 && version_row(&mut tx, version).ok().map(|r| r.place) != Some(place) =>
501 {
502 continue;
503 }
504 State::Live(now) if now == version => {
505 let status = if opened.is_ok() { 200 } else { 500 };
506 self.record(&mut tx, &entry(status, Some(version)))?;
507 commit(tx)?;
508 return opened;
509 }
510 State::Live(_) => continue,
511 other => return refuse(tx, other),
512 }
513 }
514 }
515
516 pub fn replace(
523 &self,
524 who: &Caller,
525 if_match: VersionId,
526 found: &Inspection,
527 body: &[u8],
528 ) -> Result<VersionId, StoreError> {
529 let uuid = found.uuid;
530 let entry = |status, version| Entry {
531 actor: Actor::Key(who.key),
532 action: Action::Replace,
533 target: Some(uuid.to_string()),
534 version,
535 status,
536 };
537 let key_id = self.tenant_key.id();
538 let refusal = |tx: &mut Tx| -> Result<Option<(u16, StoreError)>, StoreError> {
540 Ok(match state(tx, uuid)? {
541 State::Absent => Some((404, StoreError::NotFound)),
542 State::Gone => Some((410, StoreError::Gone)),
543 State::Live(current) if version_row(tx, current)?.form != vcon::Form::Unsigned => {
544 Some((409, StoreError::Immutable))
545 }
546 State::Live(current) if current != if_match => {
547 Some((412, StoreError::PreconditionFailed))
548 }
549 State::Live(_) => None,
550 })
551 };
552 {
553 let mut tx = self.catalog.immediate()?;
554 let refused = match refusal(&mut tx)? {
555 None if envelope::wrap_limit(tx.wraps(key_id)?) == WrapLimit::Refuse => {
556 Some((503, StoreError::LimitReached))
557 }
558 other => other,
559 };
560 if let Some((status, error)) = refused {
561 self.record(&mut tx, &entry(status, None))?;
562 commit(tx)?;
563 return Err(error);
564 }
565 tx.add_wrap(key_id)?;
566 commit(tx)?;
567 }
568
569 let (version, wrapped) = self.write_version(uuid, body)?;
570 self.pause();
571
572 let unknown = std::cell::Cell::new(false);
573 let committed = (|| {
574 let mut tx = self.catalog.immediate()?;
575 if let Some((status, error)) = refusal(&mut tx)? {
576 self.record(&mut tx, &entry(status, None))?;
577 commit(tx)?;
578 return Err(error);
579 }
580 let now = nanos(self.clock.now());
581 tx.insert_version(&NewVersion {
582 version,
583 uuid,
584 form: form_name(found.form),
585 gzip: found.gzip,
586 size: i64::try_from(body.len()).map_err(io)?,
587 stored_at: now,
588 key: key_id,
589 wrapped: &wrapped,
590 })?;
591 tx.hide_version(if_match, now)?;
592 tx.set_current(uuid, version)?;
593 self.record(&mut tx, &entry(200, Some(version)))?;
594 kept(tx.commit(), &unknown)?;
595 Ok(version)
596 })();
597 self.drop_unless_kept(committed.is_err(), unknown.get(), version);
598 #[cfg(test)]
599 if committed.is_ok() {
600 self.forced_pack();
601 }
602 committed
603 }
604
605 pub fn delete(&self, who: &Caller, uuid: Uuid, retention: Retention) -> Result<(), StoreError> {
613 let entry = |status| Entry {
614 actor: Actor::Key(who.key),
615 action: Action::Delete,
616 target: Some(uuid.to_string()),
617 version: None,
618 status,
619 };
620 {
621 let mut tx = self.catalog.immediate()?;
622 let outcome = match state(&mut tx, uuid)? {
623 State::Absent => Err(StoreError::NotFound),
624 State::Gone => Ok(()),
625 State::Live(_) => {
626 tx.mark_deleted(uuid, nanos(self.clock.now()))?;
627 Ok(())
628 }
629 };
630 let status = if outcome.is_ok() { 204 } else { 404 };
631 self.record(&mut tx, &entry(status))?;
632 commit(tx)?;
633 outcome?;
634 }
635 self.purge_hidden(Actor::Key(who.key), retention, Some(uuid))?;
638 Ok(())
639 }
640
641 pub fn check(&self) -> Result<Vec<VersionId>, StoreError> {
645 let versions = self.catalog.snapshot()?.places()?;
646 let present: std::collections::BTreeSet<String> =
647 self.objects.list().map_err(io)?.into_iter().collect();
648 let mut whole = std::collections::HashMap::new();
649 let mut missing = Vec::new();
650 for (version, place) in versions {
651 let kept = match place {
652 Err(_) => false,
653 Ok(None) => present.contains(&version.to_string()),
654 Ok(Some(packed)) => match whole.get(&packed.file) {
655 Some(&kept) => kept,
656 None => {
657 let kept = match &self.packs {
658 None => false,
659 Some(packs) => {
660 let name = crate::backend::pack::name(&packed.date, packed.file);
661 packs.size(&name).map_err(io)? == Some(packed.bytes)
662 }
663 };
664 whole.insert(packed.file, kept);
665 kept
666 }
667 },
668 };
669 if !kept {
670 missing.push(version);
671 }
672 }
673 Ok(missing)
674 }
675
676 fn write_version(&self, uuid: Uuid, body: &[u8]) -> Result<(VersionId, Vec<u8>), StoreError> {
680 let version = VersionId::generate();
681 let ctx = Context::Version {
682 tenant: self.tenant,
683 uuid,
684 version,
685 };
686 let data_key = Key::generate().map_err(|_| StoreError::Io)?;
687 let blob = envelope::seal(&data_key, &ctx, body);
688 let wrapped = envelope::wrap(&self.tenant_key, &ctx, &data_key);
689 self.objects.put(version, &blob).map_err(io)?;
690 Ok((version, wrapped))
691 }
692
693 fn drop_unless_kept(&self, failed: bool, unknown: bool, version: VersionId) {
699 if failed && !unknown {
700 let _ = self.objects.remove(version);
702 }
703 }
704
705 fn pause(&self) {
708 #[cfg(test)]
709 {
710 let hook = self.hooks.between.lock().expect("hook").take();
711 if let Some(hook) = hook {
712 hook();
713 }
714 }
715 }
716
717 fn read_version(
720 &self,
721 tx: &mut Tx,
722 uuid: Uuid,
723 version: VersionId,
724 ) -> Result<Vec<u8>, StoreError> {
725 self.read_or_why(tx, uuid, version)
726 .map_err(Unopened::into_store)
727 }
728
729 fn read_or_why(
731 &self,
732 tx: &mut Tx,
733 uuid: Uuid,
734 version: VersionId,
735 ) -> Result<Vec<u8>, Unopened> {
736 let row = version_row(tx, version)?;
737 self.open_or_why(uuid, version, &row)
738 }
739
740 fn open_version(
743 &self,
744 uuid: Uuid,
745 version: VersionId,
746 row: &VersionRow,
747 ) -> Result<Vec<u8>, StoreError> {
748 self.open_or_why(uuid, version, row)
749 .map_err(Unopened::into_store)
750 }
751
752 fn open_or_why(
755 &self,
756 uuid: Uuid,
757 version: VersionId,
758 row: &VersionRow,
759 ) -> Result<Vec<u8>, Unopened> {
760 let ctx = Context::Version {
761 tenant: self.tenant,
762 uuid,
763 version,
764 };
765 let data_key =
766 envelope::unwrap(&self.tenant_key, &ctx, &row.wrapped).map_err(key_failed)?;
767 let blob = match self.sealed_blob(version, row.place.as_ref()) {
768 Ok(blob) => blob,
769 Err(packed::Unread::Object(ObjectError::Io(e))) => return Err(Unopened::Storage(e)),
770 Err(other) => return Err(Unopened::Store(other.into_store())),
771 };
772 Ok(envelope::open(&data_key, &ctx, &blob).map_err(|_| StoreError::Damaged)?)
773 }
774
775 pub fn packed_versions(&self) -> Result<u64, StoreError> {
779 self.catalog.snapshot()?.count_packed()
780 }
781
782 pub fn counts(&self) -> Result<Counts, StoreError> {
784 let mut tx = self.catalog.snapshot()?;
785 Ok(Counts {
786 versions: tx.count_versions()?,
787 held: tx.count_held()?,
788 })
789 }
790
791 pub fn export(
794 &self,
795 since: Option<i64>,
796 out: &mut dyn std::io::Write,
797 ) -> Result<(), audit::AuditError> {
798 self.catalog.export(since.unwrap_or(0), out)
799 }
800
801 pub fn audit_page(
806 &self,
807 who: &Caller,
808 query: &audit::AuditQuery,
809 ) -> Result<Vec<u8>, StoreError> {
810 let mut tx = self.catalog.immediate()?;
811 let mut out = Vec::new();
812 let read = tx.audit_lines(query.after, Some(query.limit), &mut out);
813 self.record(
814 &mut tx,
815 &Entry {
816 actor: Actor::Key(who.key),
817 action: Action::AuditRead,
818 target: None,
819 version: None,
820 status: if read.is_ok() { 200 } else { 500 },
821 },
822 )?;
823 commit(tx)?;
824 read.map(|()| out).map_err(io)
825 }
826
827 pub fn log(&self, entry: &Entry) -> Result<(), StoreError> {
830 let mut tx = self.catalog.immediate()?;
831 self.record(&mut tx, entry)?;
832 commit(tx)
833 }
834
835 #[cfg(test)]
836 pub(crate) fn break_audit(&self) {
837 self.conn()
838 .execute_batch(
839 "CREATE TEMP TRIGGER no_audit BEFORE INSERT ON audit
840 BEGIN SELECT RAISE(ABORT, 'no audit'); END;",
841 )
842 .expect("trigger");
843 }
844
845 #[cfg(all(test, feature = "s3"))]
849 pub(crate) fn pack_after_every_write(&mut self, plan: packer::PackPlan) {
850 *self.hooks.pack_always.lock().expect("hook") = Some(plan);
851 }
852
853 #[cfg(test)]
854 fn forced_pack(&self) {
855 let plan = *self.hooks.pack_always.lock().expect("hook");
856 if let Some(plan) = plan {
857 self.pack(&plan).expect("the forced pack run");
858 }
859 }
860
861 #[cfg(test)]
862 pub(crate) fn on_backup_copied(&self, hook: tests::BackupHook) {
863 *self.hooks.copied.lock().expect("hook") = Some(hook);
864 }
865
866 #[cfg(test)]
867 pub(crate) fn conn_for_test(&self) -> MutexGuard<'_, LocalConn> {
868 self.conn()
869 }
870
871 #[cfg(test)]
872 pub(crate) fn records(&self) -> Vec<serde_json::Value> {
873 crate::audit::testing::exported(&self.conn(), None)
874 }
875
876 pub fn count(&self, entry: &Entry) -> Result<(), StoreError> {
880 let mut tx = self.catalog.immediate()?;
881 tx.count(entry, self.clock.now())
882 .map_err(|_| StoreError::AuditFailed)?;
883 commit(tx)
884 }
885
886 fn record(&self, tx: &mut Tx, entry: &Entry) -> Result<(), StoreError> {
888 tx.record(entry, self.clock.now())
889 .map_err(|_| StoreError::AuditFailed)
890 }
891
892 #[cfg(test)]
894 fn conn(&self) -> MutexGuard<'_, LocalConn> {
895 self.catalog.local_conn()
896 }
897}
898
899enum State {
900 Absent,
901 Live(VersionId),
902 Gone,
903}
904
905fn state(tx: &mut Tx, uuid: Uuid) -> Result<State, StoreError> {
908 if tx.tombstoned(uuid)? {
909 return Ok(State::Gone);
910 }
911 match tx.vcon_row(uuid)? {
912 None => Ok(State::Absent),
913 Some(row) if row.deleted_at.is_some() => Ok(State::Gone),
914 Some(row) => row.current.map(State::Live).ok_or(StoreError::Damaged),
915 }
916}
917
918fn names_its_object(place: &Result<Option<Packed>, StoreError>) -> bool {
923 !matches!(place, Ok(Some(_)))
924}
925
926struct VersionRow {
927 form: vcon::Form,
928 gzip: bool,
929 wrapped: Vec<u8>,
930 place: Option<Packed>,
931}
932
933fn version_row(tx: &mut Tx, version: VersionId) -> Result<VersionRow, StoreError> {
936 let row = tx.version_row(version)?.ok_or(StoreError::Damaged)?;
937 let form = match row.form.as_str() {
938 "unsigned" => vcon::Form::Unsigned,
939 "signed" => vcon::Form::Signed,
940 "encrypted" => vcon::Form::Encrypted,
941 _ => return Err(StoreError::Damaged),
942 };
943 Ok(VersionRow {
944 form,
945 gzip: row.gzip,
946 wrapped: row.wrapped,
947 place: row.place,
948 })
949}
950
951fn commit(tx: Tx) -> Result<(), StoreError> {
952 tx.commit().map_err(io)
953}
954
955fn kept(
958 outcome: Result<(), CommitError>,
959 unknown: &std::cell::Cell<bool>,
960) -> Result<(), StoreError> {
961 outcome.map_err(|e| {
962 unknown.set(e == CommitError::Unknown);
963 StoreError::Io
964 })
965}
966
967fn key_failed(e: envelope::KeyError) -> StoreError {
970 match e {
971 envelope::KeyError::Damaged => StoreError::Damaged,
972 _ => StoreError::Io,
973 }
974}
975
976fn read_failed(e: ObjectError) -> StoreError {
982 match e {
983 ObjectError::Missing => StoreError::Damaged,
984 ObjectError::Io(e) => {
985 storage_failed(&e);
986 StoreError::Io
987 }
988 }
989}
990
991fn storage_failed(e: &std::io::Error) {
995 tracing::warn!(
996 kind = %e.kind(),
997 os_error = e.raw_os_error(),
998 "a stored version's object could not be read"
999 );
1000}
1001
1002#[derive(Debug)]
1005enum Unopened {
1006 Store(StoreError),
1007 Storage(std::io::Error),
1008}
1009
1010impl Unopened {
1011 fn into_store(self) -> StoreError {
1014 match self {
1015 Unopened::Store(e) => e,
1016 Unopened::Storage(e) => read_failed(ObjectError::Io(e)),
1017 }
1018 }
1019}
1020
1021impl From<StoreError> for Unopened {
1022 fn from(e: StoreError) -> Unopened {
1023 Unopened::Store(e)
1024 }
1025}
1026
1027fn io<E>(_: E) -> StoreError {
1028 StoreError::Io
1029}
1030
1031fn form_name(form: vcon::Form) -> &'static str {
1033 form.as_str()
1034}
1035
1036impl From<ObjectError> for StoreError {
1037 fn from(_: ObjectError) -> StoreError {
1038 StoreError::Io
1039 }
1040}
1041
1042#[cfg(test)]
1043pub(crate) mod testing {
1044 use std::collections::BTreeSet;
1045
1046 use vcon::Form;
1047 use vcon::read::{Inspection, Limits, inspect};
1048
1049 pub(crate) fn vcon(uuid: &str, subject: &str) -> (Inspection, Vec<u8>) {
1051 let body = format!(
1052 r#"{{"uuid": "{uuid}", "created_at": "2026-10-23T12:00:00Z", "subject": "{subject}", "parties": []}}"#
1053 )
1054 .into_bytes();
1055 let found =
1056 inspect(&body, None, &Limits::new(1 << 20), &BTreeSet::new()).expect("a valid vCon");
1057 assert_eq!(found.form, Form::Unsigned);
1058 (found, body)
1059 }
1060}
1061
1062#[cfg(test)]
1063pub(crate) mod tests {
1064 use std::collections::BTreeSet;
1065
1066 use serde_json::Value;
1067 use time::macros::datetime;
1068 use vcon::read::{Limits, inspect};
1069
1070 use super::testing::vcon;
1071 use super::*;
1072 use crate::audit::testing::exported;
1073
1074 #[test]
1078 fn an_objects_directory_the_process_may_not_write_is_named() {
1079 use std::os::unix::fs::PermissionsExt;
1080 let f = fixture();
1081 let objects = f.dir.path().join("objects");
1082 let mode = |m| {
1083 std::fs::set_permissions(&objects, std::fs::Permissions::from_mode(m)).expect("chmod")
1084 };
1085 mode(0o500);
1086 let refused = f.open_or_why();
1087 mode(0o700);
1088 match refused {
1089 Err(OpenError::Access { path, error }) => {
1090 assert_eq!(path, objects);
1091 assert_eq!(error.kind(), std::io::ErrorKind::PermissionDenied);
1092 }
1093 other => panic!("{:?}", other.map(|_| "opened")),
1094 }
1095 assert!(f.open_or_why().is_ok(), "opens once allowed");
1096 }
1097 use crate::catalog::testing::columns_taking_null;
1098 use crate::clock::ManualClock;
1099 use rusqlite::{Connection, params};
1100
1101 use crate::catalog;
1102 use crate::fs::{CrashFs, Op};
1103
1104 const UUID: &str = "01a07da8-c2bb-83e5-b9a2-279e0d16bc46";
1105
1106 pub(crate) type BackupHook = Box<dyn FnMut(&Store) + Send>;
1108
1109 #[derive(Default)]
1111 pub(super) struct Hooks {
1112 pub(super) between: Mutex<Option<Box<dyn FnOnce() + Send>>>,
1116 pub(super) copied: Mutex<Option<BackupHook>>,
1119 pub(super) before_read: Mutex<Option<Box<dyn FnOnce() + Send>>>,
1122 pub(super) pack_always: Mutex<Option<super::packer::PackPlan>>,
1124 }
1125
1126 pub(crate) struct Fixture {
1127 pub(crate) dir: tempfile::TempDir,
1128 pub(crate) fs: Arc<CrashFs>,
1129 pub(crate) clock: Arc<ManualClock>,
1130 master: Key,
1133 wrapped: Vec<u8>,
1134 pub(crate) store: Store,
1135 pub(crate) caller: Caller,
1136 pub(crate) packs: Option<Arc<dyn Packs>>,
1139 }
1140
1141 pub(super) const TENANT: TenantId = TenantId([0x11; 16]);
1142
1143 impl Fixture {
1144 pub(super) fn open(&self) -> Result<Store, StoreError> {
1145 self.open_or_why().map_err(StoreError::from)
1146 }
1147
1148 pub(super) fn open_or_why(&self) -> Result<Store, OpenError> {
1150 let ctx = Context::Tenant { tenant: TENANT };
1151 let tenant_key = envelope::unwrap(&self.master, &ctx, &self.wrapped).expect("unwraps");
1152 let mut store = Store::open_beside(
1155 self.dir.path(),
1156 TENANT,
1157 tenant_key,
1158 self.fs.clone(),
1159 self.clock.clone(),
1160 )?;
1161 store.packs = self.packs.clone();
1162 store.recover()?;
1163 Ok(store)
1164 }
1165
1166 pub(crate) fn tenant_key(&self) -> Key {
1168 let ctx = Context::Tenant { tenant: TENANT };
1169 envelope::unwrap(&self.master, &ctx, &self.wrapped).expect("unwraps")
1170 }
1171
1172 pub(crate) fn tenant(&self) -> TenantId {
1173 TENANT
1174 }
1175
1176 pub(crate) fn store_objects_dir(&self) -> PathBuf {
1178 self.store.objects_dir.clone()
1179 }
1180
1181 pub(crate) fn open_beside_store(&self) -> Store {
1185 self.open_beside().expect("opens beside")
1186 }
1187
1188 fn open_beside(&self) -> Result<Store, StoreError> {
1190 let ctx = Context::Tenant { tenant: TENANT };
1191 let tenant_key = envelope::unwrap(&self.master, &ctx, &self.wrapped).expect("unwraps");
1192 Store::open_beside(
1193 self.dir.path(),
1194 TENANT,
1195 tenant_key,
1196 self.fs.clone(),
1197 self.clock.clone(),
1198 )
1199 .map_err(StoreError::from)
1200 }
1201
1202 pub(super) fn reopen(&mut self) {
1204 let placeholder = self.open().expect("opens");
1205 drop(std::mem::replace(&mut self.store, placeholder));
1206 self.store = self.open().expect("reopens");
1207 }
1208 }
1209
1210 pub(crate) fn fixture() -> Fixture {
1211 let dir = tempfile::tempdir().expect("temp dir");
1212 let fs = Arc::new(CrashFs::new(dir.path()));
1213 let clock = Arc::new(ManualClock::at(datetime!(2026-10-23 12:00 UTC)));
1214 let master = Key::generate().expect("master key");
1215 let tenant_key = Key::generate().expect("tenant key");
1216 let wrapped = envelope::wrap(&master, &Context::Tenant { tenant: TENANT }, &tenant_key);
1217 let store =
1218 Store::open(dir.path(), TENANT, tenant_key, fs.clone(), clock.clone()).expect("opens");
1219 let caller = Caller {
1220 key: Key::generate().expect("caller key").id(),
1221 };
1222 Fixture {
1223 dir,
1224 fs,
1225 clock,
1226 master,
1227 wrapped,
1228 store,
1229 caller,
1230 packs: None,
1231 }
1232 }
1233
1234 fn audit_log(store: &Store) -> Vec<Value> {
1235 exported(&store.conn(), None)
1236 }
1237
1238 fn count(store: &Store, sql: &str) -> i64 {
1239 store.conn().query_row(sql, [], |r| r.get(0)).expect(sql)
1240 }
1241
1242 fn wraps(store: &Store) -> i64 {
1243 store
1244 .conn()
1245 .query_row("SELECT coalesce(sum(wraps), 0) FROM key_use", [], |r| {
1246 r.get(0)
1247 })
1248 .expect("wraps")
1249 }
1250
1251 fn stored_body(f: &Fixture, uuid: Uuid, version: VersionId) -> Vec<u8> {
1253 let wrapped: Vec<u8> = f
1254 .store
1255 .conn()
1256 .query_row(
1257 "SELECT wrapped_key FROM version WHERE version = ?1",
1258 [version.0],
1259 |r| r.get(0),
1260 )
1261 .expect("row");
1262 let ctx = Context::Version {
1263 tenant: f.store.tenant,
1264 uuid,
1265 version,
1266 };
1267 let data_key = envelope::unwrap(&f.store.tenant_key, &ctx, &wrapped).expect("unwraps");
1268 let blob =
1269 f.fs.read(&f.store.objects_dir.join(version.to_string()))
1270 .expect("file");
1271 envelope::open(&data_key, &ctx, &blob).expect("opens")
1272 }
1273
1274 fn audit_page(f: &Fixture, after: i64, limit: u32) -> Result<Vec<u8>, StoreError> {
1275 f.store
1276 .audit_page(&f.caller, &audit::AuditQuery { after, limit })
1277 }
1278
1279 fn export_text(store: &Store, since: Option<i64>) -> Vec<u8> {
1280 let mut out = Vec::new();
1281 store.export(since, &mut out).expect("export");
1282 out
1283 }
1284
1285 #[test]
1286 fn an_audit_page_is_export_s_lines_and_records_its_read_after_them() {
1287 let f = fixture();
1288 for n in 0..3 {
1289 let (found, body) = vcon(&format!("01a07da8-c2bb-83e5-b9a2-27900000000{n}"), "x");
1290 f.store.create(&f.caller, &found, &body).expect("stored");
1291 }
1292 let before = export_text(&f.store, None);
1293 assert_eq!(audit_page(&f, 0, 1000), Ok(before.clone()));
1294 let read = audit_log(&f.store);
1295 assert_eq!(read.len(), 4, "three creates and the read");
1296 assert_eq!(read[3]["action"], "audit_read");
1297 assert_eq!(read[3]["actor"], f.caller.key.to_string());
1298 assert_eq!(read[3]["status"], 200);
1299 assert_eq!(read[3]["seq"], 4);
1300 assert_eq!(read[3]["target"], Value::Null);
1301 let lines: Vec<&[u8]> = before.split_inclusive(|b| *b == b'\n').collect();
1303 assert_eq!(audit_page(&f, 1, 2), Ok(lines[1..3].concat()));
1304 let tail = audit_page(&f, 4, 1000).expect("a page");
1306 assert_eq!(tail, export_text(&f.store, Some(4))[..tail.len()]);
1307 assert_eq!(String::from_utf8(tail).expect("UTF-8").lines().count(), 1);
1308 }
1309
1310 #[test]
1313 fn an_audit_page_that_cannot_be_read_is_a_failure_and_recorded() {
1314 let f = fixture();
1315 f.store
1316 .conn_for_test()
1317 .execute(
1318 "INSERT INTO audit (at, actor, action, status, count)
1319 VALUES ('2026-10-23T12:00:00Z', 'cli', 'read', 70000, 1)",
1320 [],
1321 )
1322 .expect("damaged");
1323 assert_eq!(audit_page(&f, 0, 10), Err(StoreError::Io));
1324 let mut recorded = Vec::new();
1325 f.store.export(Some(1), &mut recorded).expect("export");
1326 let recorded: Value = serde_json::from_slice(&recorded).expect("one record");
1327 assert_eq!(recorded["action"], "audit_read");
1328 assert_eq!(recorded["status"], 500);
1329 }
1330
1331 #[test]
1332 fn an_audit_page_whose_record_fails_is_refused() {
1333 let f = fixture();
1334 f.store.break_audit();
1335 assert_eq!(audit_page(&f, 0, 10), Err(StoreError::AuditFailed));
1336 }
1337
1338 #[test]
1339 fn a_new_vcon_is_written_in_order_and_recorded() {
1340 let f = fixture();
1341 let (found, body) = vcon(UUID, "first");
1342 let ops = f.fs.log().len();
1343 let Ok(Created::New(version)) = f.store.create(&f.caller, &found, &body) else {
1344 panic!("a new vCon")
1345 };
1346 let (tmp, done) = (
1347 f.store.objects_dir.join(format!("{version}.tmp")),
1348 f.store.objects_dir.join(version.to_string()),
1349 );
1350 assert_eq!(
1351 f.fs.log()[ops..],
1352 [
1353 Op::Write(tmp.clone()),
1354 Op::SyncFile(tmp.clone()),
1355 Op::Rename(tmp, done),
1356 Op::SyncDir(f.store.objects_dir.clone()),
1357 ]
1358 );
1359 assert_eq!(stored_body(&f, found.uuid, version), body);
1360 assert_eq!(
1361 count(
1362 &f.store,
1363 "SELECT count(*) FROM version WHERE hidden_at IS NULL"
1364 ),
1365 1
1366 );
1367 let current: Vec<u8> = f
1368 .store
1369 .conn()
1370 .query_row(
1371 "SELECT current FROM vcon WHERE uuid = ?1",
1372 [found.uuid.as_bytes()],
1373 |r| r.get(0),
1374 )
1375 .expect("vcon row");
1376 assert_eq!(current, version.0);
1377 assert_eq!(wraps(&f.store), 1, "one data key wrapped");
1378 let log = audit_log(&f.store);
1379 assert_eq!(log.len(), 1);
1380 assert_eq!(log[0]["action"], "create");
1381 assert_eq!(log[0]["actor"], f.caller.key.to_string());
1382 assert_eq!(log[0]["target"], UUID);
1383 assert_eq!(log[0]["version"], version.to_string());
1384 assert_eq!(log[0]["status"], 201);
1385 }
1386
1387 #[test]
1388 fn the_same_body_again_is_same_and_writes_nothing() {
1389 let f = fixture();
1390 let (found, body) = vcon(UUID, "first");
1391 let Ok(Created::New(version)) = f.store.create(&f.caller, &found, &body) else {
1392 panic!("a new vCon")
1393 };
1394 let ops = f.fs.log().len();
1395 assert_eq!(
1396 f.store.create(&f.caller, &found, &body),
1397 Ok(Created::Same(version))
1398 );
1399 assert_eq!(f.fs.log().len(), ops, "no file written");
1400 assert_eq!(count(&f.store, "SELECT count(*) FROM version"), 1);
1401 assert_eq!(wraps(&f.store), 1, "nothing wrapped");
1402 let log = audit_log(&f.store);
1403 assert_eq!(
1404 (log[1]["status"].clone(), log[1]["version"].clone()),
1405 (200.into(), version.to_string().into())
1406 );
1407 }
1408
1409 #[test]
1410 fn another_body_for_a_stored_uuid_is_a_conflict_and_writes_nothing() {
1411 let f = fixture();
1412 let (found, body) = vcon(UUID, "first");
1413 f.store.create(&f.caller, &found, &body).expect("stored");
1414 let ops = f.fs.log().len();
1415 let (found, other) = vcon(UUID, "other");
1417 assert_eq!(
1418 f.store.create(&f.caller, &found, &other),
1419 Err(StoreError::Conflict)
1420 );
1421 assert_eq!(f.fs.log().len(), ops, "no file written");
1422 assert_eq!(wraps(&f.store), 1, "nothing wrapped");
1423 assert_eq!(audit_log(&f.store)[1]["status"], 409);
1424 }
1425
1426 #[test]
1427 fn a_deleted_or_purged_uuid_is_gone_and_writes_nothing() {
1428 for sql in [
1429 "INSERT INTO vcon (uuid, current, deleted_at) VALUES (?1, NULL, 1)",
1430 "INSERT INTO tombstone (uuid, purged_at) VALUES (?1, 1)",
1431 ] {
1432 let f = fixture();
1433 let (found, body) = vcon(UUID, "first");
1434 f.store
1435 .conn()
1436 .execute(sql, [found.uuid.as_bytes()])
1437 .expect(sql);
1438 let ops = f.fs.log().len();
1439 assert_eq!(
1440 f.store.create(&f.caller, &found, &body),
1441 Err(StoreError::Gone),
1442 "{sql}"
1443 );
1444 assert_eq!(f.fs.log().len(), ops, "no file written");
1445 assert_eq!(wraps(&f.store), 0, "nothing wrapped");
1446 assert_eq!(audit_log(&f.store)[0]["status"], 410);
1447 }
1448 }
1449
1450 #[test]
1451 fn counts_include_hidden_versions_and_held_uuids() {
1452 let f = fixture();
1453 let none = Counts {
1454 versions: 0,
1455 held: 0,
1456 };
1457 assert_eq!(f.store.counts(), Ok(none));
1458 let (found, old) = stored(&f, "first");
1459 let (_, newer) = vcon(UUID, "second");
1460 f.store
1461 .replace(&f.caller, old, &found, &newer)
1462 .expect("replaced");
1463 f.store
1464 .delete(&f.caller, found.uuid, Retention::Years(7))
1465 .expect("deleted");
1466 let (other, body) = vcon("01a07da8-c2bb-83e5-b9a2-279e0d16bc47", "other");
1467 f.store.create(&f.caller, &other, &body).expect("stored");
1468 assert_eq!(
1469 f.store.counts(),
1470 Ok(Counts {
1471 versions: 3,
1472 held: 0
1473 }),
1474 "two hidden versions and a live one"
1475 );
1476 f.store
1477 .conn()
1478 .execute(
1479 "UPDATE vcon SET hold = 1 WHERE uuid = ?1",
1480 [found.uuid.as_bytes()],
1481 )
1482 .expect("a hold");
1483 assert_eq!(f.store.counts().map(|c| c.held), Ok(1));
1484 }
1485
1486 #[test]
1487 fn a_negative_wrap_count_is_damage_and_stores_nothing() {
1488 let f = fixture();
1489 f.store
1490 .conn()
1491 .execute(
1492 "INSERT INTO key_use (tenant_key_id, wraps) VALUES (?1, -1)",
1493 [f.store.tenant_key.id().bytes()],
1494 )
1495 .expect("a damaged count");
1496 let (found, body) = vcon(UUID, "first");
1497 let ops = f.fs.log().len();
1498 assert_eq!(
1499 f.store.create(&f.caller, &found, &body),
1500 Err(StoreError::Io)
1501 );
1502 assert_eq!(f.fs.log().len(), ops, "no file written");
1503 }
1504
1505 #[test]
1506 fn a_tenant_key_at_its_wrap_limit_refuses_new_vcons() {
1507 let f = fixture();
1508 f.store
1509 .conn()
1510 .execute(
1511 "INSERT INTO key_use (tenant_key_id, wraps) VALUES (?1, ?2)",
1512 params![f.store.tenant_key.id().bytes(), 1_i64 << 32],
1513 )
1514 .expect("at the limit");
1515 let (found, body) = vcon(UUID, "first");
1516 let ops = f.fs.log().len();
1517 assert_eq!(
1518 f.store.create(&f.caller, &found, &body),
1519 Err(StoreError::LimitReached)
1520 );
1521 assert_eq!(f.fs.log().len(), ops, "no file written");
1522 assert_eq!(audit_log(&f.store)[0]["status"], 503);
1523 }
1524
1525 #[test]
1526 fn a_missing_current_file_is_damage_not_a_conflict() {
1527 let f = fixture();
1528 let (found, body) = vcon(UUID, "first");
1529 let Ok(Created::New(version)) = f.store.create(&f.caller, &found, &body) else {
1530 panic!("a new vCon")
1531 };
1532 f.fs.remove(&f.store.objects_dir.join(version.to_string()))
1533 .expect("remove");
1534 assert_eq!(
1535 f.store.create(&f.caller, &found, &body),
1536 Err(StoreError::Damaged)
1537 );
1538 assert_eq!(audit_log(&f.store)[1]["status"], 500);
1539 }
1540
1541 #[test]
1542 fn a_racing_create_that_loses_gets_a_conflict_and_leaves_no_file() {
1543 let f = Arc::new(fixture());
1544 let (found, body) = vcon(UUID, "first");
1545 let winner = f.clone();
1546 *f.store.hooks.between.lock().expect("hook") = Some(Box::new(move || {
1547 let (found, other) = vcon(UUID, "second");
1548 assert!(matches!(
1549 winner.store.create(&winner.caller, &found, &other),
1550 Ok(Created::New(_))
1551 ));
1552 }));
1553 assert_eq!(
1554 f.store.create(&f.caller, &found, &body),
1555 Err(StoreError::Conflict)
1556 );
1557 assert_eq!(
1558 count(&f.store, "SELECT count(*) FROM version"),
1559 1,
1560 "only the winner"
1561 );
1562 assert_eq!(
1563 f.fs.list(&f.store.objects_dir).expect("list").len(),
1564 1,
1565 "the loser's file is gone"
1566 );
1567 assert_eq!(wraps(&f.store), 2, "both wraps are counted");
1568 let statuses: Vec<_> = audit_log(&f.store)
1569 .iter()
1570 .map(|r| r["status"].clone())
1571 .collect();
1572 assert_eq!(statuses, [201, 409]);
1573 }
1574
1575 #[test]
1576 fn a_create_whose_audit_record_fails_leaves_no_row_and_no_file() {
1577 let f = fixture();
1578 f.store
1580 .conn()
1581 .execute_batch(
1582 "CREATE TEMP TRIGGER no_audit BEFORE INSERT ON audit
1583 BEGIN SELECT RAISE(ABORT, 'audit fails'); END;",
1584 )
1585 .expect("trigger");
1586 let (found, body) = vcon(UUID, "first");
1587 assert_eq!(
1588 f.store.create(&f.caller, &found, &body),
1589 Err(StoreError::AuditFailed)
1590 );
1591 assert_eq!(count(&f.store, "SELECT count(*) FROM version"), 0);
1592 assert_eq!(count(&f.store, "SELECT count(*) FROM vcon"), 0);
1593 assert_eq!(
1594 f.fs.list(&f.store.objects_dir).expect("list"),
1595 Vec::<std::ffi::OsString>::new()
1596 );
1597 }
1598
1599 #[test]
1600 fn a_create_whose_commit_outcome_is_unknown_keeps_its_object() {
1601 let f = fixture();
1602 let (found, body) = vcon(UUID, "first");
1603 f.store.catalog.fail_commit(2, CommitError::Unknown);
1607 assert_eq!(
1608 f.store.create(&f.caller, &found, &body),
1609 Err(StoreError::Io),
1610 "a_create_whose_commit_outcome_is_unknown_keeps_its_object: f.store.create(&f.caller, &found, &body)"
1611 );
1612 let stored = f
1613 .store
1614 .get(&f.caller, found.uuid)
1615 .expect("the kept row reads");
1616 assert_eq!(
1617 stored.body, body,
1618 "a_create_whose_commit_outcome_is_unknown_keeps_its_object: stored.body"
1619 );
1620 assert_eq!(f.store.check(), Ok(Vec::new()), "no row without its object");
1621 drop(f.open().expect("reopens"));
1622 assert_eq!(
1623 f.store.get(&f.caller, found.uuid).map(|s| s.body),
1624 Ok(body),
1625 "recovery keeps an object a row names"
1626 );
1627 }
1628
1629 #[test]
1630 fn a_replace_whose_commit_outcome_is_unknown_keeps_its_object() {
1631 let f = fixture();
1632 let (found, body) = vcon(UUID, "first");
1633 let Ok(Created::New(first)) = f.store.create(&f.caller, &found, &body) else {
1634 panic!("a new vCon")
1635 };
1636 let (found, second) = vcon(UUID, "second");
1637 f.store.catalog.fail_commit(2, CommitError::Unknown);
1638 assert_eq!(
1639 f.store.replace(&f.caller, first, &found, &second),
1640 Err(StoreError::Io),
1641 "a_replace_whose_commit_outcome_is_unknown_keeps_its_object: f.store.replace(&f.caller, first, &found, &second)"
1642 );
1643 let stored = f
1644 .store
1645 .get(&f.caller, found.uuid)
1646 .expect("the kept row reads");
1647 assert_eq!(
1648 stored.body, second,
1649 "a_replace_whose_commit_outcome_is_unknown_keeps_its_object: stored.body"
1650 );
1651 assert_eq!(f.store.check(), Ok(Vec::new()), "no row without its object");
1652 }
1653
1654 #[test]
1655 fn a_create_whose_commit_rolls_back_leaves_no_object() {
1656 let f = fixture();
1657 let (found, body) = vcon(UUID, "first");
1658 f.store.catalog.fail_commit(2, CommitError::RolledBack);
1659 assert_eq!(
1660 f.store.create(&f.caller, &found, &body),
1661 Err(StoreError::Io),
1662 "a_create_whose_commit_rolls_back_leaves_no_object: f.store.create(&f.caller, &found, &body)"
1663 );
1664 assert_eq!(
1665 count(&f.store, "SELECT count(*) FROM version"),
1666 0,
1667 "a_create_whose_commit_rolls_back_leaves_no_object: count(&f.store, \"SELECT count(*) FROM version\")"
1668 );
1669 assert_eq!(
1670 f.fs.list(&f.store.objects_dir).expect("list"),
1671 Vec::<std::ffi::OsString>::new(),
1672 "a_create_whose_commit_rolls_back_leaves_no_object: f.fs.list(&f.store.objects_dir).expect(\"list\")"
1673 );
1674 }
1675
1676 fn get_entry_status(f: &Fixture) -> Value {
1677 audit_log(&f.store).last().expect("a record")["status"].clone()
1678 }
1679
1680 #[test]
1681 fn a_stored_vcon_reads_back_byte_for_byte_and_is_recorded() {
1682 let f = fixture();
1683 let (found, body) = vcon(UUID, "first");
1684 let Ok(Created::New(version)) = f.store.create(&f.caller, &found, &body) else {
1685 panic!("a new vCon")
1686 };
1687 let stored = f.store.get(&f.caller, found.uuid).expect("reads");
1688 assert_eq!(
1689 stored,
1690 Stored {
1691 version,
1692 form: vcon::Form::Unsigned,
1693 gzip: false,
1694 body
1695 }
1696 );
1697 let log = audit_log(&f.store);
1698 let read = log.last().expect("a record");
1699 assert_eq!(read["action"], "read");
1700 assert_eq!(read["status"], 200);
1701 assert_eq!(read["version"], version.to_string());
1702 assert_eq!(read["target"], UUID);
1703 }
1704
1705 #[test]
1706 fn a_uuid_never_stored_is_not_found() {
1707 let f = fixture();
1708 let (found, _) = vcon(UUID, "first");
1709 assert_eq!(
1710 f.store.get(&f.caller, found.uuid),
1711 Err(StoreError::NotFound)
1712 );
1713 assert_eq!(get_entry_status(&f), 404);
1714 }
1715
1716 #[test]
1717 fn a_deleted_or_purged_uuid_is_gone() {
1718 for sql in [
1719 "UPDATE vcon SET current = NULL, deleted_at = 1 WHERE uuid = ?1",
1720 "DELETE FROM vcon WHERE uuid = ?1; INSERT INTO tombstone (uuid, purged_at) VALUES (?1, 1)",
1721 ] {
1722 let f = fixture();
1723 let (found, body) = vcon(UUID, "first");
1724 f.store.create(&f.caller, &found, &body).expect("stored");
1725 for statement in sql.split("; ") {
1726 f.store
1727 .conn()
1728 .execute(statement, [found.uuid.as_bytes()])
1729 .expect(statement);
1730 }
1731 assert_eq!(
1732 f.store.get(&f.caller, found.uuid),
1733 Err(StoreError::Gone),
1734 "{sql}"
1735 );
1736 assert_eq!(get_entry_status(&f), 410);
1737 }
1738 }
1739
1740 #[test]
1741 fn a_missing_or_damaged_file_is_a_500_never_an_empty_body() {
1742 let f = fixture();
1743 let (found, body) = vcon(UUID, "first");
1744 let Ok(Created::New(version)) = f.store.create(&f.caller, &found, &body) else {
1745 panic!("a new vCon")
1746 };
1747 let file = f.store.objects_dir.join(version.to_string());
1748 let blob = f.fs.read(&file).expect("file");
1749 f.fs.remove(&file).expect("remove");
1750 assert_eq!(
1751 f.store.get(&f.caller, found.uuid),
1752 Err(StoreError::Damaged),
1753 "missing"
1754 );
1755 assert_eq!(get_entry_status(&f), 500);
1756 let mut bad = blob.clone();
1757 let last = bad.len() - 1;
1758 bad[last] ^= 1;
1759 f.fs.write_new(&file, &bad).expect("write");
1760 assert_eq!(
1761 f.store.get(&f.caller, found.uuid),
1762 Err(StoreError::Damaged),
1763 "tampered"
1764 );
1765 }
1766
1767 pub(super) type Fail = fn() -> ObjectError;
1769
1770 pub(super) struct ReadsFail {
1773 pub(super) inner: Arc<dyn Objects>,
1774 pub(super) fail: Fail,
1775 }
1776
1777 impl Objects for ReadsFail {
1778 fn put(&self, version: VersionId, blob: &[u8]) -> Result<(), ObjectError> {
1779 self.inner.put(version, blob)
1780 }
1781
1782 fn get(&self, _: VersionId) -> Result<Vec<u8>, ObjectError> {
1783 Err((self.fail)())
1784 }
1785
1786 fn remove(&self, version: VersionId) -> Result<(), ObjectError> {
1787 self.inner.remove(version)
1788 }
1789
1790 fn list(&self) -> Result<Vec<String>, ObjectError> {
1791 self.inner.list()
1792 }
1793
1794 fn remove_name(&self, name: &str) -> Result<(), ObjectError> {
1795 self.inner.remove_name(name)
1796 }
1797
1798 fn sync(&self) -> Result<(), ObjectError> {
1799 self.inner.sync()
1800 }
1801 }
1802
1803 struct ListFails {
1805 inner: Arc<dyn Objects>,
1806 fail: Fail,
1807 }
1808
1809 impl Objects for ListFails {
1810 fn put(&self, version: VersionId, blob: &[u8]) -> Result<(), ObjectError> {
1811 self.inner.put(version, blob)
1812 }
1813
1814 fn get(&self, version: VersionId) -> Result<Vec<u8>, ObjectError> {
1815 self.inner.get(version)
1816 }
1817
1818 fn remove(&self, version: VersionId) -> Result<(), ObjectError> {
1819 self.inner.remove(version)
1820 }
1821
1822 fn list(&self) -> Result<Vec<String>, ObjectError> {
1823 Err((self.fail)())
1824 }
1825
1826 fn remove_name(&self, name: &str) -> Result<(), ObjectError> {
1827 self.inner.remove_name(name)
1828 }
1829
1830 fn sync(&self) -> Result<(), ObjectError> {
1831 self.inner.sync()
1832 }
1833 }
1834
1835 #[test]
1840 fn a_listing_the_storage_fails_is_reported_with_its_kind() {
1841 let cases: [(Fail, ExamineError); 2] = [
1842 (
1843 || storage_failed(std::io::ErrorKind::PermissionDenied),
1844 ExamineError::Objects {
1845 kind: std::io::ErrorKind::PermissionDenied,
1846 os_error: None,
1847 },
1848 ),
1849 (
1850 || ObjectError::Missing,
1851 ExamineError::Failed(StoreError::Io),
1852 ),
1853 ];
1854 for (fail, expected) in cases {
1855 let mut f = fixture();
1856 let (found, body) = vcon(UUID, "first");
1857 f.store.create(&f.caller, &found, &body).expect("stored");
1858 f.store.objects = Arc::new(ListFails {
1859 inner: f.store.objects.clone(),
1860 fail,
1861 });
1862 assert_eq!(
1863 f.store
1864 .examine(
1865 Retention::Years(7),
1866 datetime!(2026-10-23 12:00 UTC),
1867 datetime!(2026-10-23 12:00 UTC),
1868 )
1869 .err(),
1870 Some(expected),
1871 "examine fails with the listing's failure"
1872 );
1873 }
1874 }
1875
1876 fn storage_failed(kind: std::io::ErrorKind) -> ObjectError {
1878 ObjectError::Io(std::io::Error::from(kind))
1879 }
1880
1881 #[test]
1885 fn a_read_the_storage_fails_is_io_and_only_a_missing_object_is_damage() {
1886 let cases: [(Fail, StoreError, &str); 5] = [
1887 (|| ObjectError::Missing, StoreError::Damaged, "missing"),
1888 (
1889 || ObjectError::Io(std::io::Error::from_raw_os_error(libc::EIO)),
1890 StoreError::Io,
1891 "EIO",
1892 ),
1893 (
1894 || storage_failed(std::io::ErrorKind::PermissionDenied),
1895 StoreError::Io,
1896 "permission denied",
1897 ),
1898 (
1899 || storage_failed(std::io::ErrorKind::ConnectionRefused),
1900 StoreError::Io,
1901 "connection refused",
1902 ),
1903 (
1904 || storage_failed(std::io::ErrorKind::TimedOut),
1905 StoreError::Io,
1906 "timed out",
1907 ),
1908 ];
1909 for (fail, expected, why) in cases {
1910 let mut f = fixture();
1911 let (found, body) = vcon(UUID, "first");
1912 let Ok(Created::New(version)) = f.store.create(&f.caller, &found, &body) else {
1913 panic!("a new vCon")
1914 };
1915 f.store.objects = Arc::new(ReadsFail {
1916 inner: f.store.objects.clone(),
1917 fail,
1918 });
1919 assert_eq!(
1920 f.store.get(&f.caller, found.uuid),
1921 Err(expected),
1922 "{why}: get"
1923 );
1924 assert_eq!(get_entry_status(&f), 500, "{why}: get is recorded");
1925 assert_eq!(
1926 f.store.create(&f.caller, &found, &body),
1927 Err(expected),
1928 "{why}: create of the same body"
1929 );
1930 for asked in [None, Some(version)] {
1931 assert_eq!(
1932 f.store.legal_get(&f.caller, found.uuid, asked).err(),
1933 Some(expected),
1934 "{why}: legal_get {asked:?}"
1935 );
1936 }
1937 let examined = f.store.examine(
1938 Retention::Years(7),
1939 datetime!(2026-10-23 12:00 UTC),
1940 datetime!(2026-10-23 12:00 UTC),
1941 );
1942 match expected {
1943 StoreError::Damaged => assert_eq!(
1944 examined.map(|e| e.damaged),
1945 Ok(vec![version]),
1946 "{why}: examine lists the version"
1947 ),
1948 _ => {
1949 let ObjectError::Io(failed) = fail() else {
1950 panic!("{why}: a storage failure")
1951 };
1952 assert_eq!(
1953 examined.err(),
1954 Some(ExamineError::Objects {
1955 kind: failed.kind(),
1956 os_error: failed.raw_os_error(),
1957 }),
1958 "{why}: examine fails with the storage's error kind, listing nothing as damaged"
1959 );
1960 }
1961 }
1962 }
1963 }
1964
1965 #[derive(Clone, Default)]
1967 pub(super) struct Capture(pub(super) Arc<Mutex<Vec<u8>>>);
1968
1969 impl std::io::Write for Capture {
1970 fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
1971 self.0.lock().expect("lock").extend_from_slice(bytes);
1972 Ok(bytes.len())
1973 }
1974
1975 fn flush(&mut self) -> std::io::Result<()> {
1976 Ok(())
1977 }
1978 }
1979
1980 impl<'a> tracing_subscriber::fmt::MakeWriter<'a> for Capture {
1981 type Writer = Capture;
1982
1983 fn make_writer(&'a self) -> Capture {
1984 self.clone()
1985 }
1986 }
1987
1988 const LEAKY: &str = "tenants/1111/objects/0e0e AKIAIOSFODNN7EXAMPLE wJalrXUtnFEMI";
1991
1992 #[test]
1996 fn a_failed_read_is_logged_by_its_kind_only() {
1997 let mut f = fixture();
1998 let (found, body) = vcon(UUID, "first");
1999 let Ok(Created::New(version)) = f.store.create(&f.caller, &found, &body) else {
2000 panic!("a new vCon")
2001 };
2002 f.store.objects = Arc::new(ReadsFail {
2003 inner: f.store.objects.clone(),
2004 fail: || {
2005 ObjectError::Io(std::io::Error::new(
2006 std::io::ErrorKind::PermissionDenied,
2007 LEAKY,
2008 ))
2009 },
2010 });
2011 let capture = Capture::default();
2012 let subscriber = tracing_subscriber::fmt()
2013 .with_writer(capture.clone())
2014 .with_ansi(false)
2015 .finish();
2016 let read =
2017 tracing::subscriber::with_default(subscriber, || f.store.get(&f.caller, found.uuid));
2018 assert_eq!(read, Err(StoreError::Io), "the read fails as Io");
2019 let log = String::from_utf8(capture.0.lock().expect("lock").clone()).expect("UTF-8");
2020 assert!(log.contains("WARN"), "a warning: {log}");
2021 assert!(
2022 log.contains("kind=permission denied"),
2023 "the kind is logged: {log}"
2024 );
2025 let version = version.to_string();
2027 let tenant = TENANT.to_string();
2028 for (what, value) in [
2029 ("the error's text", LEAKY),
2030 ("the object's key", "tenants/1111"),
2031 ("the access key id", "AKIAIOSFODNN7EXAMPLE"),
2032 ("the secret key", "wJalrXUtnFEMI"),
2033 ("the uuid", UUID),
2034 ("the version id", version.as_str()),
2035 ("the tenant id", tenant.as_str()),
2036 ] {
2037 assert!(!log.contains(value), "{what} is logged");
2038 }
2039
2040 f.store.objects = Arc::new(ReadsFail {
2042 inner: f.store.objects.clone(),
2043 fail: || ObjectError::Io(std::io::Error::from_raw_os_error(libc::EIO)),
2044 });
2045 let capture = Capture::default();
2046 let subscriber = tracing_subscriber::fmt()
2047 .with_writer(capture.clone())
2048 .with_ansi(false)
2049 .finish();
2050 tracing::subscriber::with_default(subscriber, || f.store.get(&f.caller, found.uuid))
2051 .expect_err("fails");
2052 let log = String::from_utf8(capture.0.lock().expect("lock").clone()).expect("UTF-8");
2053 assert!(
2054 log.contains(&format!("os_error={}", libc::EIO)),
2055 "the error number is logged: {log}"
2056 );
2057 }
2058
2059 #[test]
2062 fn only_a_wrapped_key_that_does_not_open_is_damage() {
2063 assert_eq!(
2064 key_failed(envelope::KeyError::Damaged),
2065 StoreError::Damaged,
2066 "a key that does not open"
2067 );
2068 assert_eq!(
2069 key_failed(envelope::KeyError::Memory(
2070 std::io::Error::from_raw_os_error(libc::ENOMEM)
2071 )),
2072 StoreError::Io,
2073 "a key page that cannot be locked"
2074 );
2075 }
2076
2077 #[test]
2078 fn a_read_racing_a_delete_never_returns_the_body() {
2079 let f = Arc::new(fixture());
2080 let (found, body) = vcon(UUID, "first");
2081 f.store.create(&f.caller, &found, &body).expect("stored");
2082 let deleter = f.clone();
2083 *f.store.hooks.between.lock().expect("hook") = Some(Box::new(move || {
2084 deleter
2085 .store
2086 .conn()
2087 .execute(
2088 "UPDATE vcon SET current = NULL, deleted_at = 1 WHERE uuid = ?1",
2089 [found.uuid.as_bytes()],
2090 )
2091 .expect("delete");
2092 }));
2093 assert_eq!(f.store.get(&f.caller, found.uuid), Err(StoreError::Gone));
2094 assert_eq!(get_entry_status(&f), 410);
2095 }
2096
2097 #[test]
2098 fn a_read_racing_a_new_version_starts_again_and_returns_the_new_one() {
2099 let f = Arc::new(fixture());
2100 let (found, body) = vcon(UUID, "first");
2101 f.store.create(&f.caller, &found, &body).expect("stored");
2102 let (_, newer) = vcon(UUID, "newer");
2103 let (version, wrapped) = f.store.write_version(found.uuid, &newer).expect("written");
2104 let writer = f.clone();
2105 *f.store.hooks.between.lock().expect("hook") = Some(Box::new(move || {
2106 let conn = writer.store.conn();
2107 conn.execute(
2108 "INSERT INTO version
2109 (version, uuid, form, gzip, size, stored_at, tenant_key_id, wrapped_key)
2110 VALUES (?1, ?2, 'unsigned', 0, 0, 0, ?3, ?4)",
2111 params![
2112 version.0,
2113 found.uuid.as_bytes(),
2114 writer.store.tenant_key.id().bytes(),
2115 wrapped
2116 ],
2117 )
2118 .expect("new version");
2119 conn.execute(
2120 "UPDATE vcon SET current = ?1 WHERE uuid = ?2",
2121 params![version.0, found.uuid.as_bytes()],
2122 )
2123 .expect("made current");
2124 }));
2125 let stored = f.store.get(&f.caller, found.uuid).expect("reads");
2126 assert_eq!((stored.version, stored.body), (version, newer));
2127 let reads = audit_log(&f.store)
2128 .iter()
2129 .filter(|r| r["action"] == "read")
2130 .count();
2131 assert_eq!(reads, 1, "one record for the one request");
2132 }
2133
2134 #[test]
2135 fn every_form_and_the_gzip_flag_read_back_as_stored() {
2136 use base64::Engine;
2137 use std::io::Write;
2138 let f = fixture();
2139 let uuids = [
2140 "01a07da8-c2bb-83e5-b9a2-279e0d16bc01",
2141 "01a07da8-c2bb-83e5-b9a2-279e0d16bc02",
2142 "01a07da8-c2bb-83e5-b9a2-279e0d16bc03",
2143 ];
2144 let (_, unsigned) = vcon(uuids[0], "plain");
2145 let mut gz = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default());
2146 gz.write_all(&unsigned).expect("gzip");
2147 let gzipped = gz.finish().expect("gzip");
2148 let (_, inner) = vcon(uuids[1], "signed");
2149 let signed = format!(
2150 r#"{{"payload": "{}", "signatures": [{{"header": {{}}}}]}}"#,
2151 base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(inner)
2152 )
2153 .into_bytes();
2154 let encrypted = format!(
2155 r#"{{"unprotected": {{"uuid": "{}"}}, "ciphertext": "x", "recipients": []}}"#,
2156 uuids[2]
2157 )
2158 .into_bytes();
2159 let cases = [
2160 (gzipped, vcon::Form::Unsigned, true),
2161 (signed, vcon::Form::Signed, false),
2162 (encrypted, vcon::Form::Encrypted, false),
2163 ];
2164 for (body, form, gzip) in cases {
2165 let found = inspect(&body, None, &Limits::new(1 << 20), &BTreeSet::new())
2166 .expect("a valid vCon");
2167 assert_eq!((found.form, found.gzip), (form, gzip));
2168 f.store.create(&f.caller, &found, &body).expect("stored");
2169 let stored = f.store.get(&f.caller, found.uuid).expect("reads");
2170 assert_eq!((stored.form, stored.gzip, stored.body), (form, gzip, body));
2171 }
2172 }
2173
2174 fn stored(f: &Fixture, subject: &str) -> (Inspection, VersionId) {
2176 let (found, body) = vcon(UUID, subject);
2177 let Ok(Created::New(version)) = f.store.create(&f.caller, &found, &body) else {
2178 panic!("a new vCon")
2179 };
2180 (found, version)
2181 }
2182
2183 #[test]
2184 fn a_replace_makes_a_new_current_version_and_hides_the_old_one() {
2185 let f = fixture();
2186 let (found, old) = stored(&f, "first");
2187 let (_, newer) = vcon(UUID, "second");
2188 let version = f
2189 .store
2190 .replace(&f.caller, old, &found, &newer)
2191 .expect("replaced");
2192 assert_ne!(version, old);
2193 let stored = f.store.get(&f.caller, found.uuid).expect("reads");
2194 assert_eq!((stored.version, stored.body), (version, newer));
2195 let hidden: Option<i64> = f
2196 .store
2197 .conn()
2198 .query_row(
2199 "SELECT hidden_at FROM version WHERE version = ?1",
2200 [old.0],
2201 |r| r.get(0),
2202 )
2203 .expect("the old row is kept");
2204 assert_eq!(
2205 hidden,
2206 Some(crate::clock::nanos(datetime!(2026-10-23 12:00 UTC))),
2207 "the old version is hidden at the replace's time"
2208 );
2209 assert!(
2210 f.fs.read(&f.store.objects_dir.join(old.to_string()))
2211 .is_ok(),
2212 "its file is kept"
2213 );
2214 let record = audit_log(&f.store)
2215 .into_iter()
2216 .find(|r| r["action"] == "replace")
2217 .expect("a replace record");
2218 assert_eq!(
2219 (record["status"].clone(), record["version"].clone()),
2220 (200.into(), version.to_string().into())
2221 );
2222 }
2223
2224 #[test]
2225 fn a_replace_of_a_missing_or_gone_uuid_is_refused() {
2226 let f = fixture();
2227 let (found, body) = vcon(UUID, "first");
2228 let any = VersionId([7; 16]);
2229 assert_eq!(
2230 f.store.replace(&f.caller, any, &found, &body),
2231 Err(StoreError::NotFound)
2232 );
2233 assert_eq!(get_entry_status(&f), 404);
2234 let (found, old) = stored(&f, "first");
2235 f.store
2236 .conn()
2237 .execute(
2238 "UPDATE vcon SET current = NULL, deleted_at = 1 WHERE uuid = ?1",
2239 [found.uuid.as_bytes()],
2240 )
2241 .expect("delete");
2242 assert_eq!(
2243 f.store.replace(&f.caller, old, &found, &body),
2244 Err(StoreError::Gone)
2245 );
2246 assert_eq!(get_entry_status(&f), 410);
2247 }
2248
2249 #[test]
2250 fn a_stale_if_match_is_refused_and_writes_nothing() {
2251 let f = fixture();
2252 let (found, _) = stored(&f, "first");
2253 let ops = f.fs.log().len();
2254 let (_, newer) = vcon(UUID, "second");
2255 assert_eq!(
2256 f.store
2257 .replace(&f.caller, VersionId([7; 16]), &found, &newer),
2258 Err(StoreError::PreconditionFailed)
2259 );
2260 assert_eq!(f.fs.log().len(), ops, "no file written");
2261 assert_eq!(wraps(&f.store), 1, "nothing wrapped");
2262 assert_eq!(get_entry_status(&f), 412);
2263 }
2264
2265 #[test]
2266 fn a_signed_or_encrypted_current_version_is_immutable() {
2267 use base64::Engine;
2268 let f = fixture();
2269 let (found, old) = stored(&f, "first");
2270 let (_, inner) = vcon(UUID, "signed");
2271 let signed = format!(
2272 r#"{{"payload": "{}", "signatures": [{{"header": {{}}}}]}}"#,
2273 base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(inner)
2274 )
2275 .into_bytes();
2276 let signed_found =
2277 inspect(&signed, None, &Limits::new(1 << 20), &BTreeSet::new()).expect("a signed vCon");
2278 let version = f
2279 .store
2280 .replace(&f.caller, old, &signed_found, &signed)
2281 .expect("an unsigned vCon may be replaced by a signed one");
2282 let (_, newer) = vcon(UUID, "second");
2283 let ops = f.fs.log().len();
2284 assert_eq!(
2285 f.store.replace(&f.caller, version, &found, &newer),
2286 Err(StoreError::Immutable)
2287 );
2288 assert_eq!(f.fs.log().len(), ops, "no file written");
2289 assert_eq!(get_entry_status(&f), 409);
2290
2291 let g = fixture();
2292 let encrypted = format!(
2293 r#"{{"unprotected": {{"uuid": "{UUID}"}}, "ciphertext": "x", "recipients": []}}"#
2294 )
2295 .into_bytes();
2296 let enc_found = inspect(&encrypted, None, &Limits::new(1 << 20), &BTreeSet::new())
2297 .expect("an encrypted vCon");
2298 let Ok(Created::New(enc_version)) = g.store.create(&g.caller, &enc_found, &encrypted)
2299 else {
2300 panic!("stored")
2301 };
2302 assert_eq!(
2303 g.store.replace(&g.caller, enc_version, &found, &newer),
2304 Err(StoreError::Immutable)
2305 );
2306 }
2307
2308 #[test]
2309 fn a_replace_at_the_wrap_limit_is_refused() {
2310 let f = fixture();
2311 let (found, old) = stored(&f, "first");
2312 f.store
2313 .conn()
2314 .execute("UPDATE key_use SET wraps = ?1", [1_i64 << 32])
2315 .expect("at the limit");
2316 let (_, newer) = vcon(UUID, "second");
2317 assert_eq!(
2318 f.store.replace(&f.caller, old, &found, &newer),
2319 Err(StoreError::LimitReached)
2320 );
2321 assert_eq!(get_entry_status(&f), 503);
2322 }
2323
2324 #[test]
2325 fn of_two_replaces_racing_on_one_version_the_second_to_commit_loses() {
2326 let f = Arc::new(fixture());
2327 let (found, old) = stored(&f, "first");
2328 let winner = f.clone();
2329 let racer = found;
2330 *f.store.hooks.between.lock().expect("hook") = Some(Box::new(move || {
2331 let (_, body) = vcon(UUID, "winner");
2332 winner
2333 .store
2334 .replace(&winner.caller, old, &racer, &body)
2335 .expect("wins");
2336 }));
2337 let (_, body) = vcon(UUID, "loser");
2338 assert_eq!(
2339 f.store.replace(&f.caller, old, &found, &body),
2340 Err(StoreError::PreconditionFailed)
2341 );
2342 assert_eq!(
2343 f.fs.list(&f.store.objects_dir).expect("list").len(),
2344 2,
2345 "first and winner only"
2346 );
2347 assert_eq!(wraps(&f.store), 3, "every wrap counted");
2348 assert_eq!(get_entry_status(&f), 412);
2349 }
2350
2351 #[test]
2352 fn two_threads_replacing_with_the_same_if_match_one_wins() {
2353 let f = Arc::new(fixture());
2354 let (_, old) = stored(&f, "first");
2355 let threads: Vec<_> = ["one", "two"]
2356 .into_iter()
2357 .map(|subject| {
2358 let f = f.clone();
2359 std::thread::spawn(move || {
2360 let (found, body) = vcon(UUID, subject);
2361 f.store.replace(&f.caller, old, &found, &body)
2362 })
2363 })
2364 .collect();
2365 let results: Vec<_> = threads
2366 .into_iter()
2367 .map(|t| t.join().expect("thread"))
2368 .collect();
2369 assert_eq!(
2370 results.iter().filter(|r| r.is_ok()).count(),
2371 1,
2372 "{results:?}"
2373 );
2374 assert!(
2375 results.contains(&Err(StoreError::PreconditionFailed)),
2376 "{results:?}"
2377 );
2378 }
2379
2380 #[test]
2381 fn a_replace_whose_audit_record_fails_changes_nothing() {
2382 let f = fixture();
2383 let (found, old) = stored(&f, "first");
2384 f.store
2385 .conn()
2386 .execute_batch(
2387 "CREATE TEMP TRIGGER no_audit BEFORE INSERT ON audit
2388 BEGIN SELECT RAISE(ABORT, 'audit fails'); END;",
2389 )
2390 .expect("trigger");
2391 let (_, newer) = vcon(UUID, "second");
2392 assert_eq!(
2393 f.store.replace(&f.caller, old, &found, &newer),
2394 Err(StoreError::AuditFailed)
2395 );
2396 f.store
2397 .conn()
2398 .execute_batch("DROP TRIGGER no_audit")
2399 .expect("drop trigger");
2400 assert_eq!(
2401 f.store.get(&f.caller, found.uuid).expect("reads").version,
2402 old
2403 );
2404 assert_eq!(
2405 f.fs.list(&f.store.objects_dir).expect("list").len(),
2406 1,
2407 "only the first file"
2408 );
2409 }
2410
2411 fn hidden_versions(f: &Fixture) -> i64 {
2412 count(
2413 &f.store,
2414 "SELECT count(*) FROM version WHERE hidden_at IS NOT NULL",
2415 )
2416 }
2417
2418 #[test]
2419 fn a_deleted_uuid_answers_gone_and_keeps_its_versions_hidden() {
2420 let f = fixture();
2421 let (found, old) = stored(&f, "first");
2422 let (_, newer) = vcon(UUID, "second");
2423 f.clock.set(datetime!(2026-10-23 13:00 UTC));
2424 let current = f
2425 .store
2426 .replace(&f.caller, old, &found, &newer)
2427 .expect("replaced");
2428 f.clock.set(datetime!(2026-10-23 14:00 UTC));
2429 assert_eq!(
2430 f.store.delete(&f.caller, found.uuid, Retention::Years(7)),
2431 Ok(())
2432 );
2433 let record = audit_log(&f.store).pop().expect("a record");
2434 assert_eq!(
2435 (record["action"].clone(), record["status"].clone()),
2436 ("delete".into(), 204.into())
2437 );
2438 let hidden_at = |version: VersionId| -> i64 {
2439 f.store
2440 .conn()
2441 .query_row(
2442 "SELECT hidden_at FROM version WHERE version = ?1",
2443 [version.0],
2444 |r| r.get(0),
2445 )
2446 .expect("hidden")
2447 };
2448 assert_eq!(
2449 hidden_at(old),
2450 nanos(datetime!(2026-10-23 13:00 UTC)),
2451 "hidden by the replace"
2452 );
2453 assert_eq!(
2454 hidden_at(current),
2455 nanos(datetime!(2026-10-23 14:00 UTC)),
2456 "hidden by the delete"
2457 );
2458 assert_eq!(f.store.get(&f.caller, found.uuid), Err(StoreError::Gone));
2459 let (_, body) = vcon(UUID, "third");
2460 assert_eq!(
2461 f.store.create(&f.caller, &found, &body),
2462 Err(StoreError::Gone)
2463 );
2464 assert_eq!(hidden_versions(&f), 2, "both versions hidden");
2465 assert_eq!(
2466 f.fs.list(&f.store.objects_dir).expect("list").len(),
2467 2,
2468 "files kept for legal reads"
2469 );
2470 let (current, deleted_at): (Option<Vec<u8>>, Option<i64>) = f
2471 .store
2472 .conn()
2473 .query_row(
2474 "SELECT current, deleted_at FROM vcon WHERE uuid = ?1",
2475 [found.uuid.as_bytes()],
2476 |r| Ok((r.get(0)?, r.get(1)?)),
2477 )
2478 .expect("row");
2479 assert_eq!(current, None);
2480 assert_eq!(deleted_at, Some(nanos(datetime!(2026-10-23 14:00 UTC))));
2481 }
2482
2483 #[test]
2484 fn deleting_a_deleted_or_purged_uuid_succeeds_again() {
2485 let f = fixture();
2486 let (found, _) = stored(&f, "first");
2487 f.store
2488 .delete(&f.caller, found.uuid, Retention::Years(7))
2489 .expect("deleted");
2490 assert_eq!(
2491 f.store.delete(&f.caller, found.uuid, Retention::Years(7)),
2492 Ok(())
2493 );
2494 assert_eq!(get_entry_status(&f), 204);
2495 let g = fixture();
2496 g.store
2497 .conn()
2498 .execute(
2499 "INSERT INTO tombstone (uuid, purged_at) VALUES (?1, 1)",
2500 [found.uuid.as_bytes()],
2501 )
2502 .expect("purged");
2503 assert_eq!(
2504 g.store.delete(&g.caller, found.uuid, Retention::Years(7)),
2505 Ok(())
2506 );
2507 assert_eq!(get_entry_status(&g), 204);
2508 }
2509
2510 #[test]
2511 fn deleting_a_uuid_never_stored_is_not_found() {
2512 let f = fixture();
2513 let (found, _) = vcon(UUID, "first");
2514 assert_eq!(
2515 f.store.delete(&f.caller, found.uuid, Retention::Years(7)),
2516 Err(StoreError::NotFound)
2517 );
2518 assert_eq!(get_entry_status(&f), 404);
2519 }
2520
2521 #[test]
2522 fn a_hold_does_not_stop_a_delete() {
2523 let f = fixture();
2524 let (found, _) = stored(&f, "first");
2525 f.store
2526 .conn()
2527 .execute(
2528 "UPDATE vcon SET hold = 1 WHERE uuid = ?1",
2529 [found.uuid.as_bytes()],
2530 )
2531 .expect("hold");
2532 assert_eq!(
2533 f.store.delete(&f.caller, found.uuid, Retention::Years(7)),
2534 Ok(())
2535 );
2536 assert_eq!(f.store.get(&f.caller, found.uuid), Err(StoreError::Gone));
2537 }
2538
2539 #[test]
2540 fn a_delete_whose_audit_record_fails_changes_nothing() {
2541 let f = fixture();
2542 let (found, version) = stored(&f, "first");
2543 f.store
2544 .conn()
2545 .execute_batch(
2546 "CREATE TEMP TRIGGER no_audit BEFORE INSERT ON audit
2547 BEGIN SELECT RAISE(ABORT, 'audit fails'); END;",
2548 )
2549 .expect("trigger");
2550 assert_eq!(
2551 f.store.delete(&f.caller, found.uuid, Retention::Years(7)),
2552 Err(StoreError::AuditFailed)
2553 );
2554 f.store
2555 .conn()
2556 .execute_batch("DROP TRIGGER no_audit")
2557 .expect("drop trigger");
2558 assert_eq!(
2559 f.store
2560 .get(&f.caller, found.uuid)
2561 .expect("still live")
2562 .version,
2563 version
2564 );
2565 assert_eq!(hidden_versions(&f), 0);
2566 }
2567
2568 #[test]
2569 fn only_the_optional_catalog_columns_may_be_empty() {
2570 let f = fixture();
2571 let conn = f.store.conn();
2572 let tables: [(&str, &[(&str, &str)]); 8] = [
2573 (
2574 "vcon",
2575 &[
2576 ("uuid", "x'01'"),
2577 ("current", "x'02'"),
2578 ("deleted_at", "1"),
2579 ("hold", "0"),
2580 ],
2581 ),
2582 (
2583 "version",
2584 &[
2585 ("version", "x'02'"),
2586 ("uuid", "x'01'"),
2587 ("form", "'unsigned'"),
2588 ("gzip", "0"),
2589 ("size", "1"),
2590 ("stored_at", "1"),
2591 ("hidden_at", "1"),
2592 ("tenant_key_id", "x'03'"),
2593 ("wrapped_key", "x'04'"),
2594 ("place_file", "x'05'"),
2595 ("place_group", "0"),
2596 ("place_row", "0"),
2597 ],
2598 ),
2599 (
2600 "parquet_file",
2601 &[
2602 ("file_id", "x'05'"),
2603 ("date", "'2026-10-23'"),
2604 ("rows", "1"),
2605 ("live_rows", "1"),
2606 ("bytes", "1"),
2607 ("created_at", "1"),
2608 ("unnamed_at", "1"),
2609 ],
2610 ),
2611 ("purge_pending", &[("file_id", "x'05'")]),
2612 ("manifest", &[("seq", "1"), ("published_at", "1")]),
2613 ("tombstone", &[("uuid", "x'01'"), ("purged_at", "1")]),
2614 ("key_use", &[("tenant_key_id", "x'03'"), ("wraps", "1")]),
2615 (
2616 "audit",
2617 &[
2618 ("at", "'2026-10-23T12:00Z'"),
2619 ("actor", "'cli'"),
2620 ("action", "'create'"),
2621 ("target", "'x'"),
2622 ("version", "'y'"),
2623 ("status", "201"),
2624 ("count", "1"),
2625 ],
2626 ),
2627 ];
2628 let may_be_empty: Vec<String> = tables
2629 .iter()
2630 .flat_map(|(table, row)| columns_taking_null(&conn, table, row))
2631 .collect();
2632 assert_eq!(
2633 may_be_empty,
2634 [
2635 "vcon.current",
2636 "vcon.deleted_at",
2637 "version.hidden_at",
2638 "version.place_file",
2639 "version.place_group",
2640 "version.place_row",
2641 "parquet_file.unnamed_at",
2642 "manifest.seq",
2644 "manifest.published_at",
2645 "audit.target",
2646 "audit.version",
2647 "audit.status"
2649 ]
2650 );
2651 }
2652
2653 #[test]
2654 fn a_new_stores_objects_directory_survives_a_crash() {
2655 let f = fixture();
2656 f.fs.crash();
2657 assert_eq!(
2658 f.fs.list(f.dir.path()).expect("list"),
2659 [std::ffi::OsString::from("objects")]
2660 );
2661 }
2662
2663 #[test]
2664 fn opening_removes_temporary_and_orphaned_files_and_nothing_else() {
2665 let mut f = fixture();
2666 let (found, version) = stored(&f, "first");
2667 let orphan = VersionId([0x0e; 16]);
2668 let objects = f.store.objects_dir.clone();
2669 for name in [
2670 format!("{orphan}"),
2671 format!("{orphan}.tmp"),
2672 format!("{version}.tmp"),
2673 "notes.txt".to_owned(),
2674 ] {
2675 f.fs.write_new(&objects.join(name), b"x").expect("write");
2676 }
2677 f.reopen();
2678 let names: Vec<String> =
2679 f.fs.list(&objects)
2680 .expect("list")
2681 .into_iter()
2682 .map(|n| n.to_string_lossy().into_owned())
2683 .collect();
2684 assert_eq!(names, [version.to_string(), "notes.txt".to_owned()]);
2685 assert_eq!(
2686 f.store
2687 .get(&f.caller, found.uuid)
2688 .expect("still reads")
2689 .version,
2690 version
2691 );
2692 let log = f.fs.log();
2693 let last_removal = log
2694 .iter()
2695 .rposition(|op| matches!(op, Op::Remove(_)))
2696 .expect("files were removed");
2697 assert!(
2698 log[last_removal..].contains(&Op::SyncDir(objects)),
2699 "the removals are synced"
2700 );
2701 }
2702
2703 #[test]
2706 fn opening_beside_a_server_removes_nothing() {
2707 let f = fixture();
2708 let (found, version) = stored(&f, "first");
2709 let orphan = VersionId([0x0e; 16]);
2710 let objects = f.store.objects_dir.clone();
2711 let mut written = vec![version.to_string()];
2712 for name in [
2713 format!("{orphan}"),
2714 format!("{orphan}.tmp"),
2715 format!("{version}.tmp"),
2716 ] {
2717 f.fs.write_new(&objects.join(&name), b"x").expect("write");
2718 written.push(name);
2719 }
2720 written.sort();
2721 let ops = f.fs.log().len();
2722 let beside = f.open_beside().expect("opens beside");
2723 let mut names: Vec<String> =
2724 f.fs.list(&objects)
2725 .expect("list")
2726 .into_iter()
2727 .map(|n| n.to_string_lossy().into_owned())
2728 .collect();
2729 names.sort();
2730 assert_eq!(names, written);
2731 assert!(
2732 !f.fs.log()[ops..]
2733 .iter()
2734 .any(|op| matches!(op, Op::Remove(_))),
2735 "nothing removed"
2736 );
2737 assert_eq!(
2738 beside.get(&f.caller, found.uuid).expect("reads").version,
2739 version
2740 );
2741 }
2742
2743 #[test]
2744 fn opening_checkpoints_the_wal_with_truncation() {
2745 let mut f = fixture();
2746 stored(&f, "first");
2747 let wal = f.dir.path().join("catalog.sqlite-wal");
2748 assert!(
2749 std::fs::metadata(&wal).expect("a WAL").len() > 0,
2750 "the WAL holds the write"
2751 );
2752 f.reopen();
2753 assert_eq!(std::fs::metadata(&wal).expect("a WAL").len(), 0);
2754 }
2755
2756 #[test]
2757 fn check_reports_a_version_whose_file_is_missing() {
2758 let f = fixture();
2759 let (_, version) = stored(&f, "first");
2760 assert_eq!(f.store.check(), Ok(vec![]));
2761 f.fs.remove(&f.store.objects_dir.join(version.to_string()))
2762 .expect("remove");
2763 assert_eq!(f.store.check(), Ok(vec![version]));
2764 }
2765
2766 #[test]
2767 fn opening_refuses_while_a_reader_stops_the_wal_from_being_truncated() {
2768 let f = fixture();
2769 stored(&f, "first");
2770 let ctx = Context::Tenant { tenant: TENANT };
2771 let tenant_key = envelope::unwrap(&f.master, &ctx, &f.wrapped).expect("unwraps");
2772 let catalog_key = envelope::catalog_key(&tenant_key).expect("catalog key");
2773 let mut reader = catalog::open(&f.dir.path().join("catalog.sqlite"), &catalog_key, "")
2774 .expect("a second connection");
2775 let read = reader.transaction().expect("read transaction");
2776 let _: i64 = read
2777 .query_row("SELECT count(*) FROM vcon", [], |r| r.get(0))
2778 .expect("a read holds a snapshot");
2779 assert!(matches!(f.open(), Err(StoreError::Io)));
2780 drop(read);
2781 assert!(f.open().is_ok(), "opens once the reader is done");
2782 }
2783
2784 const WRITE_STEPS: usize = 4;
2787
2788 fn assert_whole(f: &Fixture, step: usize) {
2790 assert_eq!(
2791 f.store.check(),
2792 Ok(vec![]),
2793 "a row without its file at step {step}"
2794 );
2795 for name in f.fs.list(&f.store.objects_dir).expect("list") {
2796 let name = name.to_string_lossy().into_owned();
2797 let version = VersionId::parse(&name)
2798 .unwrap_or_else(|| panic!("{name} left over at step {step}"));
2799 let rows = count(
2800 &f.store,
2801 &format!("SELECT count(*) FROM version WHERE hex(version) = upper('{version}')"),
2802 );
2803 assert_eq!(rows, 1, "{name} has no row at step {step}");
2804 }
2805 }
2806
2807 pub(super) fn second_connection(f: &Fixture) -> Connection {
2811 let ctx = Context::Tenant { tenant: TENANT };
2812 let tenant_key = envelope::unwrap(&f.master, &ctx, &f.wrapped).expect("unwraps");
2813 let catalog_key = envelope::catalog_key(&tenant_key).expect("catalog key");
2814 catalog::open(&f.dir.path().join("catalog.sqlite"), &catalog_key, "")
2815 .expect("second connection")
2816 }
2817
2818 fn die_before_commit(f: &Fixture) {
2819 let other = second_connection(f);
2820 let fs = f.fs.clone();
2821 *f.store.hooks.between.lock().expect("hook") = Some(Box::new(move || {
2822 fs.fail_from(0);
2823 other
2824 .execute_batch(
2825 "CREATE TRIGGER dead BEFORE INSERT ON audit
2826 BEGIN SELECT RAISE(ABORT, 'the process has died'); END;",
2827 )
2828 .expect("trigger");
2829 }));
2830 }
2831
2832 pub(super) fn restart(f: &mut Fixture) {
2833 f.fs.crash();
2834 f.store
2835 .conn()
2836 .execute_batch("DROP TRIGGER IF EXISTS dead")
2837 .expect("drop trigger");
2838 f.reopen();
2839 }
2840
2841 #[test]
2842 fn a_create_cut_off_at_any_step_leaves_no_vcon_or_the_whole_vcon() {
2843 let (found, body) = vcon(UUID, "first");
2844 for step in 0..=WRITE_STEPS {
2845 let mut f = fixture();
2846 f.fs.fail_from(f.fs.log().len() + step);
2847 let result = f.store.create(&f.caller, &found, &body);
2848 assert_eq!(
2849 result.is_ok(),
2850 step == WRITE_STEPS,
2851 "step {step}: {result:?}"
2852 );
2853 restart(&mut f);
2854 match f.store.get(&f.caller, found.uuid) {
2855 Ok(stored) => assert_eq!(stored.body, body, "step {step}"),
2856 Err(StoreError::NotFound) => {
2857 assert!(result.is_err(), "acknowledged, then lost, at step {step}")
2858 }
2859 other => panic!("half a vCon at step {step}: {other:?}"),
2860 }
2861 assert_whole(&f, step);
2862 }
2863 }
2864
2865 #[test]
2866 fn a_create_cut_off_between_its_file_and_its_commit_leaves_nothing() {
2867 let mut f = fixture();
2868 let (found, body) = vcon(UUID, "first");
2869 die_before_commit(&f);
2870 assert!(f.store.create(&f.caller, &found, &body).is_err());
2871 restart(&mut f);
2872 assert_eq!(
2873 f.store.get(&f.caller, found.uuid),
2874 Err(StoreError::NotFound)
2875 );
2876 assert_whole(&f, WRITE_STEPS);
2877 }
2878
2879 #[test]
2880 fn a_replace_cut_off_at_any_step_leaves_the_old_version_or_the_new() {
2881 let (found, old_body) = vcon(UUID, "first");
2882 let (_, new_body) = vcon(UUID, "second");
2883 for step in 0..=WRITE_STEPS {
2884 let mut f = fixture();
2885 let Ok(Created::New(old)) = f.store.create(&f.caller, &found, &old_body) else {
2886 panic!("stored")
2887 };
2888 f.fs.fail_from(f.fs.log().len() + step);
2889 let result = f.store.replace(&f.caller, old, &found, &new_body);
2890 assert_eq!(
2891 result.is_ok(),
2892 step == WRITE_STEPS,
2893 "step {step}: {result:?}"
2894 );
2895 restart(&mut f);
2896 let stored = f
2897 .store
2898 .get(&f.caller, found.uuid)
2899 .unwrap_or_else(|e| panic!("step {step}: {e:?}"));
2900 match result {
2901 Ok(new) => assert_eq!(
2902 (stored.version, stored.body),
2903 (new, new_body.clone()),
2904 "step {step}"
2905 ),
2906 Err(_) => assert_eq!(
2907 (stored.version, stored.body),
2908 (old, old_body.clone()),
2909 "step {step}"
2910 ),
2911 }
2912 assert_whole(&f, step);
2913 }
2914 }
2915
2916 #[test]
2917 fn a_replace_cut_off_between_its_file_and_its_commit_keeps_the_old_version() {
2918 let mut f = fixture();
2919 let (found, old) = stored(&f, "first");
2920 let (_, newer) = vcon(UUID, "second");
2921 die_before_commit(&f);
2922 assert!(f.store.replace(&f.caller, old, &found, &newer).is_err());
2923 restart(&mut f);
2924 assert_eq!(
2925 f.store.get(&f.caller, found.uuid).expect("reads").version,
2926 old
2927 );
2928 assert_eq!(hidden_versions(&f), 0);
2929 assert_whole(&f, WRITE_STEPS);
2930 }
2931
2932 #[test]
2933 fn a_delete_cut_off_before_its_commit_leaves_the_vcon_live() {
2934 let mut f = fixture();
2935 let (found, version) = stored(&f, "first");
2936 let other = second_connection(&f);
2937 other
2938 .execute_batch(
2939 "CREATE TRIGGER dead BEFORE INSERT ON audit
2940 BEGIN SELECT RAISE(ABORT, 'the process has died'); END;",
2941 )
2942 .expect("trigger");
2943 assert!(
2944 f.store
2945 .delete(&f.caller, found.uuid, Retention::Years(7))
2946 .is_err()
2947 );
2948 drop(other);
2949 restart(&mut f);
2950 assert_eq!(
2951 f.store
2952 .get(&f.caller, found.uuid)
2953 .expect("still live")
2954 .version,
2955 version
2956 );
2957 assert_eq!(hidden_versions(&f), 0);
2958 }
2959
2960 fn last_record(f: &Fixture) -> (String, Value, Value, Value) {
2962 let log = audit_log(&f.store);
2963 let last = log.last().expect("a record");
2964 (
2965 last["action"].as_str().expect("an action").to_owned(),
2966 last["status"].clone(),
2967 last["version"].clone(),
2968 last["target"].clone(),
2969 )
2970 }
2971
2972 #[test]
2973 fn a_reveal_reads_what_a_read_does_and_is_recorded_under_its_part() {
2974 let f = fixture();
2975 let (found, body) = vcon(UUID, "first");
2976 let Ok(Created::New(version)) = f.store.create(&f.caller, &found, &body) else {
2977 panic!("a new vCon")
2978 };
2979 let read = f.store.get(&f.caller, found.uuid).expect("reads");
2980 for part in Part::ALL {
2981 let revealed = f.store.reveal(&f.caller, found.uuid, part).expect("reads");
2982 assert_eq!(revealed, read, "{part:?}");
2983 assert_eq!(
2984 last_record(&f),
2985 (
2986 format!("reveal_{}", part.name()),
2987 200.into(),
2988 version.to_string().into(),
2989 UUID.into()
2990 ),
2991 "{part:?}"
2992 );
2993 }
2994 }
2995
2996 #[test]
2997 fn a_reveal_of_a_uuid_never_stored_is_not_found_and_recorded_as_the_reveal() {
2998 let f = fixture();
2999 let (found, _) = vcon(UUID, "first");
3000 assert_eq!(
3001 f.store.reveal(&f.caller, found.uuid, Part::Dialog),
3002 Err(StoreError::NotFound),
3003 "the answer"
3004 );
3005 assert_eq!(
3006 last_record(&f),
3007 (
3008 "reveal_dialog".to_owned(),
3009 404.into(),
3010 Value::Null,
3011 UUID.into()
3012 ),
3013 "the record"
3014 );
3015 }
3016
3017 #[test]
3018 fn a_reveal_of_a_deleted_vcon_is_gone_and_recorded_as_the_reveal() {
3019 let f = fixture();
3020 let (found, body) = vcon(UUID, "first");
3021 f.store.create(&f.caller, &found, &body).expect("stored");
3022 f.store
3023 .delete(&f.caller, found.uuid, Retention::Years(7))
3024 .expect("deleted");
3025 assert_eq!(
3026 f.store.reveal(&f.caller, found.uuid, Part::Parties),
3027 Err(StoreError::Gone),
3028 "the answer"
3029 );
3030 assert_eq!(
3031 last_record(&f),
3032 (
3033 "reveal_parties".to_owned(),
3034 410.into(),
3035 Value::Null,
3036 UUID.into()
3037 ),
3038 "the record"
3039 );
3040 }
3041
3042 #[test]
3043 fn a_reveal_of_a_version_whose_file_is_missing_is_damage_recorded_as_the_reveal() {
3044 let f = fixture();
3045 let (found, body) = vcon(UUID, "first");
3046 let Ok(Created::New(version)) = f.store.create(&f.caller, &found, &body) else {
3047 panic!("a new vCon")
3048 };
3049 f.fs.remove(&f.store.objects_dir.join(version.to_string()))
3050 .expect("remove");
3051 assert_eq!(
3052 f.store.reveal(&f.caller, found.uuid, Part::All),
3053 Err(StoreError::Damaged),
3054 "the answer"
3055 );
3056 assert_eq!(
3057 last_record(&f),
3058 (
3059 "reveal_all".to_owned(),
3060 500.into(),
3061 version.to_string().into(),
3062 UUID.into()
3063 ),
3064 "the record"
3065 );
3066 }
3067
3068 #[test]
3071 fn a_read_before_and_after_a_reveal_is_still_recorded_as_a_read() {
3072 let f = fixture();
3073 let (found, body) = vcon(UUID, "first");
3074 f.store.create(&f.caller, &found, &body).expect("stored");
3075 f.store.get(&f.caller, found.uuid).expect("reads");
3076 f.store
3077 .reveal(&f.caller, found.uuid, Part::Subject)
3078 .expect("reads");
3079 f.store.get(&f.caller, found.uuid).expect("reads");
3080 let actions: Vec<String> = audit_log(&f.store)
3081 .iter()
3082 .map(|r| r["action"].as_str().expect("an action").to_owned())
3083 .collect();
3084 assert_eq!(
3085 actions,
3086 ["create", "read", "reveal_subject", "read"],
3087 "the record"
3088 );
3089 }
3090}