Skip to main content

vcon_server/
store.rs

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