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