Skip to main content

vcon_server/
tenants.rs

1//! The registry of tenants: each one's id, name, retention period and
2//! wrapped tenant key, kept in `server.sqlite` under a catalog key derived
3//! from the master key, with the admin audit log beside them. Each tenant's
4//! vCons live in `tenants/<id>/`, in a Store of their own.
5
6use std::collections::HashMap;
7use std::path::{Path, PathBuf};
8use std::sync::{Arc, Mutex, MutexGuard};
9
10use time::OffsetDateTime;
11
12use crate::audit::{self, Action, Actor, Entry};
13#[cfg(test)]
14use crate::backend::local::LocalConn;
15use crate::backend::local::{LocalRegistry, LocalTenantSpace};
16use crate::backend::{
17    Catalogs, CommitError, Job, ObjectPlace, Registry, RegistryTx, TenantRow, TenantSpace,
18};
19use crate::clock::{Clock, from_nanos, nanos};
20use crate::envelope::{self, Key, WrapLimit};
21use crate::export::Metadata;
22use crate::fs::Fs;
23use crate::ids::TenantId;
24use crate::key_wrap::{FileWrap, KeyWrap};
25use crate::retention::Retention;
26use crate::store::pending::{self, Writers};
27use crate::store::{OpenError, Store};
28
29mod backup;
30mod examine;
31pub(crate) mod key_life;
32#[cfg(test)]
33mod key_wrap_tests;
34mod keys;
35mod rekey;
36mod role_cap;
37mod sessions;
38#[cfg(test)]
39mod statement_tests;
40mod tenant_admin;
41mod users;
42
43pub use backup::{Backup, BackupError, NO_FILE_BACKUP};
44pub use examine::{KeyOrder, RegistryExamination, RotationBacklog, TenantExamination, Unexamined};
45pub use key_life::KeyLife;
46pub use keys::{KeyInfo, NewKey};
47pub(crate) use rekey::MasterStep;
48pub use rekey::rekey_master;
49pub use sessions::{Proof, SessionError, SessionInfo, Started};
50pub use tenant_admin::MemberInfo;
51#[cfg(test)]
52pub(crate) use tests::{Fixture, fixture};
53pub use users::{Identity, MembershipInfo, UserError, UserInfo};
54
55/// A tenant's metadata column as read: NULL is `none`, and a level this
56/// build does not know is damage.
57fn stored_metadata(text: Option<String>) -> Result<Metadata, TenantError> {
58    match text {
59        None => Ok(Metadata::None),
60        Some(text) => Metadata::parse(&text).ok_or(TenantError::Io),
61    }
62}
63
64/// A tenant's retention column as read: None is the server default. A
65/// period that does not read back is damage, not the server default.
66fn stored_retention(text: Option<String>) -> Result<Option<Retention>, TenantError> {
67    text.map(|text| Retention::parse(&text).ok_or(TenantError::Io))
68        .transpose()
69}
70
71/// Why a Tenants call was refused or failed.
72#[derive(Debug, Clone, Copy, PartialEq, Eq)]
73pub enum TenantError {
74    /// No tenant has the id.
75    NotFound,
76    /// Another tenant has the name.
77    NameTaken,
78    /// The name breaks the naming rule (`good_name`).
79    BadName,
80    /// `Removal::Empty` was asked of a tenant that keeps versions.
81    HoldsVcons,
82    /// `Removal::Force` was asked of a tenant with a uuid under a legal
83    /// hold.
84    UnderHold,
85    /// The master key is at its wrap limit and must be rotated.
86    LimitReached,
87    /// The audit record could not be written, so nothing was done.
88    AuditFailed,
89    /// The tenant is being removed.
90    Closing,
91    /// Only the command line may do this: make an operator key.
92    CliOnly,
93    /// Scopes a key of its kind, or made by this caller, cannot hold.
94    BadScopes,
95    /// An expiry a new key cannot have: a number of days outside 1 to
96    /// 365, days and no expiry asked together, or no expiry where the
97    /// configuration refuses it (`keys.no_expiry`).
98    BadExpiry,
99    /// A change to a tenant's settings that the list of settings refuses.
100    BadSetting(crate::settings::SettingError),
101    /// server.sqlite was made under another master key.
102    WrongKey,
103    /// A copy of the registry into a local file was asked of a registry
104    /// kept in PostgreSQL, which is backed up with the database's own
105    /// tools (`pg_dump`).
106    NoFileBackup,
107    Io,
108}
109
110/// Why the registry did not open: the key it was made under, or the step
111/// that failed, on which file, with the error underneath as its source, so
112/// a failure says its cause.
113#[derive(Debug)]
114#[non_exhaustive]
115pub enum RegistryError {
116    /// server.sqlite was made under another master key.
117    WrongKey,
118    /// `step` failed on `path`.
119    Failed {
120        /// What was being done.
121        step: OpenStep,
122        /// The file or directory it was done to.
123        path: PathBuf,
124        /// The error underneath.
125        source: Box<dyn std::error::Error + Send + Sync>,
126    },
127    /// Start-up recovery failed.
128    Recovery(TenantError),
129    /// The registry in the catalog database was made under another master
130    /// key.
131    WrongDatabaseKey,
132    /// The registry in the catalog database could not be opened, and why.
133    Database(String),
134}
135
136/// What a start says when the catalog database names another master key.
137pub(crate) const WRONG_DATABASE_KEY: &str = "the master key is not the one the registry in the \
138                                             catalog database was made under";
139
140/// A step of opening the registry.
141#[derive(Debug, Clone, Copy, PartialEq, Eq)]
142#[non_exhaustive]
143pub enum OpenStep {
144    /// Deriving server.sqlite's key from the master key.
145    CatalogKey,
146    /// Opening, or making, server.sqlite.
147    OpenCatalog,
148    /// Making the tenants/ directory.
149    MakeTenantsDir,
150    /// Syncing the data directory.
151    SyncDataDir,
152}
153
154impl RegistryError {
155    pub(crate) fn failed(
156        step: OpenStep,
157        path: PathBuf,
158        source: impl std::error::Error + Send + Sync + 'static,
159    ) -> RegistryError {
160        RegistryError::Failed {
161            step,
162            path,
163            source: Box::new(source),
164        }
165    }
166}
167
168impl std::fmt::Display for RegistryError {
169    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
170        match self {
171            RegistryError::WrongKey => {
172                f.write_str("the master key is not the one server.sqlite was made under")
173            }
174            RegistryError::Failed { step, path, .. } => {
175                let doing = match step {
176                    OpenStep::CatalogKey => "the catalog key for",
177                    OpenStep::OpenCatalog => "opening",
178                    OpenStep::MakeTenantsDir => "making",
179                    OpenStep::SyncDataDir => "syncing",
180                };
181                write!(f, "{doing} {} failed", path.display())
182            }
183            RegistryError::Recovery(e) => write!(f, "start-up recovery failed: {e:?}"),
184            RegistryError::WrongDatabaseKey => f.write_str(WRONG_DATABASE_KEY),
185            RegistryError::Database(why) => write!(
186                f,
187                "the registry in the PostgreSQL database cannot be opened: {why}"
188            ),
189        }
190    }
191}
192
193impl std::error::Error for RegistryError {
194    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
195        match self {
196            RegistryError::Failed { source, .. } => Some(source.as_ref()),
197            RegistryError::WrongKey
198            | RegistryError::Recovery(_)
199            | RegistryError::WrongDatabaseKey
200            | RegistryError::Database(_) => None,
201        }
202    }
203}
204
205/// `error` and each error under it, as their Displays joined by ": ", for
206/// a report that gives the whole cause.
207pub(crate) fn with_causes(error: &dyn std::error::Error) -> String {
208    let mut text = error.to_string();
209    let mut under = error.source();
210    while let Some(cause) = under {
211        text.push_str(": ");
212        text.push_str(&cause.to_string());
213        under = cause.source();
214    }
215    text
216}
217
218/// Every caller but the two that report it sees what TenantError can say.
219impl From<RegistryError> for TenantError {
220    fn from(e: RegistryError) -> TenantError {
221        match e {
222            RegistryError::WrongKey | RegistryError::WrongDatabaseKey => TenantError::WrongKey,
223            RegistryError::Failed { .. } | RegistryError::Database(_) => TenantError::Io,
224            RegistryError::Recovery(e) => e,
225        }
226    }
227}
228
229/// Why a tenant's Store could not be had: the registry refused, its
230/// catalog does not open under its key, or this process may not use one of
231/// its files. Only `check` and `serve`'s start-up check tell these apart;
232/// every other caller sees `TenantError` (`From` below).
233#[derive(Debug)]
234pub enum OpenFailure {
235    Refused(TenantError),
236    WrongKey,
237    Access {
238        path: PathBuf,
239        error: std::io::Error,
240    },
241}
242
243impl From<OpenFailure> for TenantError {
244    fn from(f: OpenFailure) -> TenantError {
245        match f {
246            OpenFailure::Refused(e) => e,
247            OpenFailure::WrongKey | OpenFailure::Access { .. } => TenantError::Io,
248        }
249    }
250}
251
252impl From<TenantError> for OpenFailure {
253    fn from(e: TenantError) -> OpenFailure {
254        OpenFailure::Refused(e)
255    }
256}
257
258impl From<OpenError> for OpenFailure {
259    fn from(e: OpenError) -> OpenFailure {
260        match e {
261            OpenError::WrongKey => OpenFailure::WrongKey,
262            OpenError::Access { path, error } => OpenFailure::Access { path, error },
263            OpenError::Store(_) => OpenFailure::Refused(TenantError::Io),
264        }
265    }
266}
267
268/// A tenant as `list` shows it.
269#[derive(Debug, Clone, PartialEq, Eq)]
270pub struct TenantInfo {
271    pub id: TenantId,
272    pub name: String,
273    /// The tenant's own retention period, if it set one.
274    pub retention: Option<Retention>,
275    /// Which clear columns its Parquet files carry.
276    pub metadata: Metadata,
277    pub created_at: OffsetDateTime,
278}
279
280impl TenantInfo {
281    /// The tenant as the admin API and the command line show it: id, name,
282    /// its own retention period, null for the server default, and its
283    /// metadata level.
284    pub fn to_json(&self) -> serde_json::Value {
285        serde_json::json!({
286            "id": self.id.to_string(),
287            "name": self.name,
288            "retention": self.retention.map(|r| r.to_string()),
289            "metadata": self.metadata.as_str(),
290        })
291    }
292
293    /// How long the tenant's vCons are kept: its own period, else the
294    /// server's `default`.
295    pub fn kept_for(&self, default: Retention) -> Retention {
296        kept_for(self.retention, default)
297    }
298}
299
300/// How long a tenant's vCons are kept: its own period `own`, else the
301/// server's `default`. The one rule the sweep, `check` and TenantInfo use.
302pub(crate) fn kept_for(own: Option<Retention>, default: Retention) -> Retention {
303    own.unwrap_or(default)
304}
305
306/// How far `remove` may go.
307#[derive(Debug, Clone, Copy, PartialEq, Eq)]
308pub enum Removal {
309    /// Only a tenant that keeps no version.
310    Empty,
311    /// Its vCons too, unless a uuid is under a legal hold.
312    Force,
313    /// Even held vCons; only from the command line, with the server stopped.
314    ForceOverridingHolds,
315}
316
317/// A tenant's Store as the registry holds it.
318enum Slot {
319    Open(Arc<Store>),
320    /// Being removed: no new handle is handed out.
321    Closing,
322}
323
324/// The registry of tenants.
325pub struct Tenants {
326    /// Where each tenant's catalog and objects are kept.
327    space: Box<dyn TenantSpace>,
328    /// What holds the root server.sqlite's key is derived from, and wraps
329    /// and unwraps each tenant key.
330    wrap: Box<dyn KeyWrap>,
331    registry: Box<dyn Registry>,
332    /// Each tenant's Store, once a request has opened it.
333    stores: Mutex<HashMap<TenantId, Slot>>,
334    /// The recovery its Stores are opened with, and who else that
335    /// recovery assumes may be writing; none for a process opened beside
336    /// a server, whose recovery would take the server's work under way
337    /// for a crash's leftovers.
338    recovery: Option<Writers>,
339    fs: Arc<dyn Fs>,
340    clock: Arc<dyn Clock>,
341    /// Whether a key may be made with no expiry (`keys.no_expiry`).
342    no_expiry: std::sync::atomic::AtomicBool,
343    #[cfg(test)]
344    hooks: tests::Hooks,
345}
346
347impl Tenants {
348    /// Opens `<dir>/server.sqlite` under the master key's catalog key,
349    /// making it if new, and removes any tenant directory a crash left
350    /// without its row.
351    pub fn open(
352        dir: &Path,
353        master: Key,
354        fs: Arc<dyn Fs>,
355        clock: Arc<dyn Clock>,
356    ) -> Result<Tenants, RegistryError> {
357        Tenants::open_in(dir, master, fs, clock, ObjectPlace::Local, &Catalogs::Local)
358    }
359
360    /// Opens the registry as `open` does, with each tenant's objects kept
361    /// in `objects` and the registry and the tenants' catalogs kept in
362    /// `catalogs`: in `dir`, or in a database, where start-up recovery
363    /// removes the catalog rows and the bucket's objects of a tenant with
364    /// no row.
365    pub(crate) fn open_in(
366        dir: &Path,
367        master: Key,
368        fs: Arc<dyn Fs>,
369        clock: Arc<dyn Clock>,
370        objects: ObjectPlace,
371        catalogs: &Catalogs,
372    ) -> Result<Tenants, RegistryError> {
373        let registry = Tenants::opened(
374            dir,
375            Box::new(FileWrap::new(master)),
376            fs,
377            clock,
378            false,
379            objects,
380            catalogs,
381        )?;
382        // A process that opens the registry this way holds the data
383        // directory alone, or the database alone as a command alone does;
384        // a server on a database shares it with the other servers, whose
385        // work under way its recovery keeps.
386        registry
387            .recover(catalogs.writers())
388            .map_err(RegistryError::Recovery)?;
389        Ok(registry)
390    }
391
392    /// Opens the registry as a command running beside a server does:
393    /// without start-up recovery, here or in any Store it opens, which
394    /// would take the server's creates and writes in progress for a
395    /// crash's leftovers.
396    pub fn open_beside(
397        dir: &Path,
398        master: Key,
399        fs: Arc<dyn Fs>,
400        clock: Arc<dyn Clock>,
401    ) -> Result<Tenants, RegistryError> {
402        Tenants::opened(
403            dir,
404            Box::new(FileWrap::new(master)),
405            fs,
406            clock,
407            true,
408            ObjectPlace::Local,
409            &Catalogs::Local,
410        )
411    }
412
413    /// Opens the registry as `open_beside` does, with each tenant's objects
414    /// kept in `objects` and the catalogs in `catalogs`.
415    pub(crate) fn open_beside_in(
416        dir: &Path,
417        master: Key,
418        fs: Arc<dyn Fs>,
419        clock: Arc<dyn Clock>,
420        objects: ObjectPlace,
421        catalogs: &Catalogs,
422    ) -> Result<Tenants, RegistryError> {
423        Tenants::opened(
424            dir,
425            Box::new(FileWrap::new(master)),
426            fs,
427            clock,
428            true,
429            objects,
430            catalogs,
431        )
432    }
433
434    /// The one opener: the registry and the tenants' space of `catalogs`,
435    /// the files of `dir` or the rows of a database, behind the same
436    /// `Tenants`.
437    fn opened(
438        dir: &Path,
439        wrap: Box<dyn KeyWrap>,
440        fs: Arc<dyn Fs>,
441        clock: Arc<dyn Clock>,
442        beside: bool,
443        objects: ObjectPlace,
444        catalogs: &Catalogs,
445    ) -> Result<Tenants, RegistryError> {
446        let catalog_key = envelope::catalog_key(wrap.root()).map_err(|e| {
447            RegistryError::failed(OpenStep::CatalogKey, dir.join("server.sqlite"), e)
448        })?;
449        let (registry, space): crate::backend::Backends = match catalogs {
450            Catalogs::Local => (
451                Box::new(LocalRegistry::open(dir, catalog_key)?),
452                Box::new(LocalTenantSpace::open(dir, fs.clone(), objects)?),
453            ),
454            #[cfg(feature = "postgres")]
455            Catalogs::Postgres(database) => {
456                crate::backend::postgres::open(database, &catalog_key, objects, fs.clone())?
457            }
458        };
459        let recovery = (!beside).then(|| catalogs.writers());
460        Ok(Tenants::with_backends(
461            registry, space, wrap, fs, clock, recovery,
462        ))
463    }
464
465    /// The registry over the given backends, opened as `open_beside` opens
466    /// one when `recovery` is none, else without its start-up recovery
467    /// yet, which assumes the writers `recovery` names.
468    pub(crate) fn with_backends(
469        registry: Box<dyn Registry>,
470        space: Box<dyn TenantSpace>,
471        wrap: Box<dyn KeyWrap>,
472        fs: Arc<dyn Fs>,
473        clock: Arc<dyn Clock>,
474        recovery: Option<Writers>,
475    ) -> Tenants {
476        Tenants {
477            space,
478            wrap,
479            registry,
480            stores: Mutex::new(HashMap::new()),
481            recovery,
482            fs,
483            clock,
484            no_expiry: std::sync::atomic::AtomicBool::new(true),
485            #[cfg(test)]
486            hooks: tests::Hooks::default(),
487        }
488    }
489
490    /// Runs `hook` once in the next create, between its space and the
491    /// transaction that adds its row: where another server's recovery
492    /// would find the create under way.
493    #[cfg(all(test, feature = "postgres", feature = "backend-tests"))]
494    pub(crate) fn between_create(&self, hook: tests::CreateHook) {
495        *self.hooks.between.lock().expect("hook") = Some(hook);
496    }
497
498    /// Takes or renews the lease of `job` for `ttl` ([`Registry::lead`]):
499    /// true when this process holds it now. The catalogs' clock decides,
500    /// never this process's.
501    pub(crate) fn lead(&self, job: Job, ttl: std::time::Duration) -> Result<bool, TenantError> {
502        self.registry.lead(job, ttl)
503    }
504
505    /// Gives up the lease of `job` when this process holds it
506    /// ([`Registry::step_down`]).
507    pub(crate) fn step_down(&self, job: Job) -> Result<(), TenantError> {
508        self.registry.step_down(job)
509    }
510
511    /// The recovery a running server repeats at each of its sweeps
512    /// (design 7.4): the registry's, then each tenant's Store's, all with
513    /// other writers possibly at work, since this process writes while it
514    /// runs and other servers may too. A tenant whose Store cannot be
515    /// opened or recovered, such as one being removed, is counted and left
516    /// for the next sweep; the answer is how many were.
517    pub(crate) fn recover_all(&self) -> Result<u64, TenantError> {
518        self.recover(Writers::Maybe)?;
519        let mut failed = 0;
520        for id in self.ids()? {
521            let recovered = self
522                .store(id)
523                .map_err(|_| ())
524                .and_then(|store| store.recover(Writers::Maybe).map_err(|_| ()));
525            if recovered.is_err() {
526                failed += 1;
527            }
528        }
529        Ok(failed)
530    }
531
532    /// The registry's clock in `tx` ([`RegistryTx::clock_now`]), `host`
533    /// being this process's.
534    fn registry_now(&self, tx: &mut dyn RegistryTx, host: i64) -> Result<i64, TenantError> {
535        let now = tx.clock_now(host)?;
536        #[cfg(test)]
537        let now = {
538            let mut steps = self.hooks.clock_steps.lock().expect("hook");
539            if steps.is_empty() {
540                now
541            } else {
542                now + steps.remove(0)
543            }
544        };
545        Ok(now)
546    }
547
548    /// The time in `tx` by the registry's clock: what the transaction
549    /// writes as a time another server judges, and judges such a time by.
550    /// On a database it is the database's clock, so the host clocks of
551    /// the servers on it do not matter; on a data directory, this
552    /// process's.
553    pub(crate) fn now_in(&self, tx: &mut dyn RegistryTx) -> Result<i64, TenantError> {
554        self.registry_now(tx, nanos(self.clock.now()))
555    }
556
557    /// Removes each tenant space with no row: a create cut off before its
558    /// commit. A name that is not a tenant id is not ours and is left
559    /// alone. A removal a crash undoes is made again at the next start, so
560    /// none is synced.
561    ///
562    /// With other writers possibly at work (`writers`), a space whose
563    /// create is under way (store/pending.rs) is kept, by the order that
564    /// keeps a write's object: a creating row no create can still be under
565    /// way for is deleted first, so that create's last transaction refuses
566    /// to add its row; the spaces are listed next, and the rows read after:
567    /// a create adds its creating row before it makes its space, so every
568    /// space listed has its creating row or its tenant's row in that read.
569    pub(crate) fn recover(&self, writers: Writers) -> Result<(), TenantError> {
570        let host = nanos(self.clock.now());
571        let now = {
572            let mut tx = self.registry.immediate()?;
573            let now = self.registry_now(tx.as_mut(), host)?;
574            for (id, started_at) in tx.creating()? {
575                if !pending::under_way(writers, started_at, now) {
576                    tx.drop_creating(id)?;
577                }
578            }
579            commit(tx)?;
580            now
581        };
582        let present = self.space.present()?;
583        let (tenants, creating) = {
584            let mut tx = self.registry.snapshot()?;
585            let tenants: std::collections::HashSet<TenantId> =
586                tx.tenants()?.into_iter().map(|row| row.id).collect();
587            let creating: std::collections::HashSet<TenantId> = tx
588                .creating()?
589                .into_iter()
590                .filter(|(_, started_at)| pending::under_way(writers, *started_at, now))
591                .map(|(id, _)| id)
592                .collect();
593            (tenants, creating)
594        };
595        for id in present {
596            if pending::leftover(tenants.contains(&id), false, creating.contains(&id)) {
597                self.space.remove(id)?;
598            }
599        }
600        Ok(())
601    }
602
603    /// Makes a tenant: a new tenant key wrapped by the key-wrapping backend, the
604    /// tenant's directory and catalog, and then its row. A create that
605    /// fails after making its directory removes it if it can; any directory
606    /// left without a row, by a crash or a failed removal, goes at the next
607    /// start.
608    pub fn create(
609        &self,
610        who: Actor,
611        name: &str,
612        retention: Option<Retention>,
613    ) -> Result<TenantId, TenantError> {
614        let id = TenantId::generate();
615        let entry = |status, target: Option<TenantId>| Entry {
616            actor: who,
617            action: Action::TenantCreate,
618            target: target.map(|t| t.to_string()),
619            version: None,
620            status,
621        };
622        let master_id = self.wrap.key_id();
623        {
624            let mut tx = self.registry.immediate()?;
625            let refused = if !good_name(name) {
626                Some((422, TenantError::BadName))
627            } else if tx.name_taken(name)? {
628                Some((409, TenantError::NameTaken))
629            } else if envelope::wrap_limit(tx.master_wraps(master_id)?) == WrapLimit::Refuse {
630                Some((503, TenantError::LimitReached))
631            } else {
632                None
633            };
634            if let Some((status, error)) = refused {
635                self.record(&mut tx, &entry(status, None))?;
636                commit(tx)?;
637                return Err(error);
638            }
639            // The wrap is counted before it is made, so every wrap is
640            // counted once whether this create wins or loses.
641            let now = self.now_in(tx.as_mut())?;
642            tx.add_master_wrap(master_id, now)?;
643            // Before the space is made: until the row, recovery on another
644            // server keeps the space of a create under way.
645            tx.add_creating(id, now)?;
646            commit(tx)?;
647        }
648
649        let tenant_key = Key::generate().map_err(|_| TenantError::Io)?;
650        let key_id = tenant_key.id();
651        let wrapped = self.wrap.wrap(id, &tenant_key).map_err(io)?;
652        // The directory and its catalog are made before the row, and made
653        // durable: the directory's entry in `tenants/` by syncing it. Any
654        // step that fails once the directory may exist removes it.
655        let unknown = std::cell::Cell::new(false);
656        let made = (|| {
657            self.space
658                .make(id, tenant_key, self.clock.clone())
659                .map_err(|_| TenantError::Io)?;
660            #[cfg(test)]
661            {
662                let hook = self.hooks.between.lock().expect("hook").take();
663                if let Some(hook) = hook {
664                    hook(self);
665                }
666            }
667
668            let mut tx = self.registry.immediate()?;
669            if !tx.drop_creating(id)? {
670                // Recovery took this create for a leftover, and its space
671                // is removed or going: no row may name it.
672                return Err(TenantError::Io);
673            }
674            if tx.name_taken(name)? {
675                // A refusal's record commits.
676                self.record(&mut tx, &entry(409, None))?;
677                commit(tx)?;
678                return Err(TenantError::NameTaken);
679            }
680            let now = self.now_in(tx.as_mut())?;
681            tx.insert_tenant(&TenantRow {
682                id,
683                name: name.to_owned(),
684                retention: retention.map(|r| r.to_string()),
685                metadata: None,
686                role_cap: None,
687                created_at: now,
688                tenant_key_id: key_id,
689                wrapped: wrapped.clone(),
690                pending: None,
691                key_since: now,
692            })?;
693            self.record(&mut tx, &entry(201, Some(id)))?;
694            tx.commit().map_err(|e| {
695                unknown.set(e == CommitError::Unknown);
696                TenantError::Io
697            })?;
698            Ok(id)
699        })();
700        // After a commit whose outcome is unknown the directory stays: the
701        // row may be kept, and a row without its directory is a tenant
702        // that cannot open, while a directory without a row is removed at
703        // the next start.
704        if made.is_err() && !unknown.get() {
705            let _ = self.space.remove(id);
706            // The creating row goes after the space, so recovery never
707            // finds the space without it; a row left here is a leftover
708            // that recovery drops once its lease passes.
709            let begun = self.registry.immediate();
710            if let Ok(mut tx) = begun
711                && tx.drop_creating(id).is_ok()
712            {
713                let _ = tx.commit();
714            }
715        }
716        made
717    }
718
719    /// Every tenant, by name.
720    pub fn list(&self, who: Actor) -> Result<Vec<TenantInfo>, TenantError> {
721        let mut tx = self.registry.immediate()?;
722        let tenants = tx
723            .tenants()?
724            .into_iter()
725            .map(|row| {
726                Ok(TenantInfo {
727                    id: row.id,
728                    name: row.name,
729                    retention: stored_retention(row.retention)?,
730                    metadata: stored_metadata(row.metadata)?,
731                    created_at: from_nanos(row.created_at).ok_or(TenantError::Io)?,
732                })
733            })
734            .collect::<Result<Vec<_>, TenantError>>()?;
735        let entry = Entry {
736            actor: who,
737            action: Action::TenantList,
738            target: None,
739            version: None,
740            status: 200,
741        };
742        self.record(&mut tx, &entry)?;
743        commit(tx)?;
744        Ok(tenants)
745    }
746
747    /// Sets the tenant's retention period, or with None returns it to the
748    /// server default.
749    pub fn set_retention(
750        &self,
751        who: Actor,
752        id: TenantId,
753        retention: Option<Retention>,
754    ) -> Result<(), TenantError> {
755        let entry = |action, status| Entry {
756            actor: who,
757            action,
758            target: Some(id.to_string()),
759            version: None,
760            status,
761        };
762        let closing = matches!(self.stores().get(&id), Some(Slot::Closing));
763        {
764            let mut tx = self.registry.immediate()?;
765            let text = retention.map(|r| r.to_string());
766            let refused = if closing {
767                Some((503, TenantError::Closing))
768            } else if !tx.set_retention(id, text.as_deref())? {
769                Some((404, TenantError::NotFound))
770            } else {
771                None
772            };
773            let status = refused.map_or(200, |(status, _)| status);
774            self.record(&mut tx, &entry(Action::TenantRetention, status))?;
775            commit(tx)?;
776            if let Some((_, error)) = refused {
777                return Err(error);
778            }
779        }
780        self.copy_to_tenant(id, &entry(Action::Retention, 200))
781    }
782
783    /// Sets which clear columns the tenant's Parquet files carry.
784    pub fn set_metadata(
785        &self,
786        who: Actor,
787        id: TenantId,
788        level: Metadata,
789    ) -> Result<(), TenantError> {
790        let entry = |action, status| Entry {
791            actor: who,
792            action,
793            target: Some(id.to_string()),
794            version: None,
795            status,
796        };
797        let closing = matches!(self.stores().get(&id), Some(Slot::Closing));
798        {
799            let mut tx = self.registry.immediate()?;
800            let text = (level != Metadata::None).then(|| level.as_str());
801            let refused = if closing {
802                Some((503, TenantError::Closing))
803            } else if !tx.set_metadata(id, text)? {
804                Some((404, TenantError::NotFound))
805            } else {
806                None
807            };
808            let status = refused.map_or(200, |(status, _)| status);
809            self.record(&mut tx, &entry(Action::TenantMetadata, status))?;
810            commit(tx)?;
811            if let Some((_, error)) = refused {
812                return Err(error);
813            }
814        }
815        self.copy_to_tenant(id, &entry(Action::Metadata, 200))
816    }
817
818    /// The tenant's metadata level.
819    pub fn metadata(&self, id: TenantId) -> Result<Metadata, TenantError> {
820        let row = self.registry.snapshot()?.tenant(id)?;
821        stored_metadata(row.ok_or(TenantError::NotFound)?.metadata)
822    }
823
824    /// Writes the copy of an admin record that a tenant's own log keeps
825    /// too. The change it records has already committed with its admin
826    /// record, so a crash or failure here can lose only the copy; the
827    /// caller then answers that the audit failed, though the change
828    /// stands.
829    fn copy_to_tenant(&self, tenant: TenantId, entry: &Entry) -> Result<(), TenantError> {
830        let store = self.store(tenant).map_err(|_| TenantError::AuditFailed)?;
831        store.log(entry).map_err(|_| TenantError::AuditFailed)
832    }
833
834    /// Removes the tenant: its row and wrapped key, then its directory.
835    ///
836    /// The tenant is drained before it is looked at, so a write that lands
837    /// meanwhile counts: an `Empty` removal is then refused rather than
838    /// losing it. A refused or failed removal leaves the tenant served
839    /// again.
840    pub fn remove(&self, who: Actor, id: TenantId, removal: Removal) -> Result<(), TenantError> {
841        let entry = |status| Entry {
842            actor: who,
843            action: Action::TenantRemove,
844            target: Some(id.to_string()),
845            version: None,
846            status,
847        };
848        let drained = match self.drain(id) {
849            Ok(drained) => drained,
850            Err(error) => {
851                self.record_alone(&entry(503))?;
852                return Err(error);
853            }
854        };
855        let result = self.remove_drained(id, removal, drained, entry);
856        if result.is_err() {
857            self.stores().remove(&id);
858        }
859        result
860    }
861
862    fn remove_drained(
863        &self,
864        id: TenantId,
865        removal: Removal,
866        drained: Option<Store>,
867        entry: impl Fn(u16) -> Entry,
868    ) -> Result<(), TenantError> {
869        let store = match drained {
870            Some(store) => store,
871            None => match self.open_store(id).map_err(TenantError::from) {
872                Err(TenantError::NotFound) => {
873                    self.record_alone(&entry(404))?;
874                    return Err(TenantError::NotFound);
875                }
876                other => other?,
877            },
878        };
879        let counts = store.counts().map_err(io)?;
880        let refused = match removal {
881            Removal::Empty if counts.versions > 0 => Some(TenantError::HoldsVcons),
882            Removal::Force if counts.held > 0 => Some(TenantError::UnderHold),
883            _ => None,
884        };
885        if let Some(error) = refused {
886            self.record_alone(&entry(409))?;
887            return Err(error);
888        }
889        {
890            let mut tx = self.registry.immediate()?;
891            tx.delete_tenant(id, nanos(self.clock.now()))?;
892            // A membership, a setting and a session are in a tenant: none
893            // outlives its tenant.
894            tx.delete_memberships_in(id)?;
895            tx.delete_settings_in(id)?;
896            tx.delete_sessions_in(id)?;
897            self.record(&mut tx, &entry(204))?;
898            commit(tx)?;
899        }
900        // The removal stands with its commit. The Store is closed before
901        // its directory goes; a directory left here, by a crash or a
902        // failed removal, goes at the next start.
903        drop(store);
904        let _ = self.space.remove(id);
905        self.stores().remove(&id);
906        Ok(())
907    }
908
909    /// The tenant's Store, shared by every request to it.
910    pub fn store(&self, id: TenantId) -> Result<Arc<Store>, TenantError> {
911        self.store_or_why(id).map_err(TenantError::from)
912    }
913
914    /// `store`, saying why a Store that did not open did not.
915    pub fn store_or_why(&self, id: TenantId) -> Result<Arc<Store>, OpenFailure> {
916        // The Store is opened under this lock, so it is opened once: a
917        // second open's recovery could remove a write's temporary file.
918        let mut stores = self.stores();
919        match stores.get(&id) {
920            Some(Slot::Open(store)) => return Ok(store.clone()),
921            Some(Slot::Closing) => return Err(TenantError::Closing.into()),
922            None => {}
923        }
924        let store = Arc::new(self.open_store(id)?);
925        stores.insert(id, Slot::Open(store.clone()));
926        Ok(store)
927    }
928
929    /// Opens the tenant's Store under the key its row holds. Its callers
930    /// make sure no other Store of the tenant is open: `store` holds the
931    /// lock, and `remove` has drained the tenant.
932    fn open_store(&self, id: TenantId) -> Result<Store, OpenFailure> {
933        let wrapped = self
934            .registry
935            .snapshot()?
936            .tenant(id)?
937            .ok_or(TenantError::NotFound)?
938            .wrapped;
939        let tenant_key = self.wrap.unwrap(id, &wrapped).map_err(io)?;
940        #[cfg(test)]
941        {
942            let hook = self.hooks.opening.lock().expect("hook").take();
943            if let Some(hook) = hook {
944                hook();
945            }
946        }
947        self.space
948            .open(id, tenant_key, self.recovery, self.clock.clone())
949            .map_err(OpenFailure::from)
950    }
951
952    /// Marks the tenant closing, so no new handle is handed out, and waits
953    /// until every handle given out before is dropped. Handles are plain
954    /// `Arc`s, so the wait watches the count; requests are short and
955    /// removal is rare. A tenant already closing is refused, so two
956    /// removals never both hold its Store.
957    ///
958    /// Returns the tenant's Store if a request had opened it, now held
959    /// only here.
960    fn drain(&self, id: TenantId) -> Result<Option<Store>, TenantError> {
961        let slot = {
962            let mut stores = self.stores();
963            if matches!(stores.get(&id), Some(Slot::Closing)) {
964                return Err(TenantError::Closing);
965            }
966            stores.insert(id, Slot::Closing)
967        };
968        let Some(Slot::Open(mut store)) = slot else {
969            return Ok(None);
970        };
971        loop {
972            match Arc::try_unwrap(store) {
973                Ok(store) => return Ok(Some(store)),
974                Err(shared) => {
975                    store = shared;
976                    std::thread::sleep(std::time::Duration::from_millis(1));
977                }
978            }
979        }
980    }
981
982    fn stores(&self) -> MutexGuard<'_, HashMap<TenantId, Slot>> {
983        self.stores
984            .lock()
985            .expect("no thread panicked holding the stores")
986    }
987
988    /// Makes every audit insert on server.sqlite fail, for tests.
989    #[cfg(test)]
990    pub(crate) fn break_audit(&self) {
991        self.conn()
992            .execute_batch(
993                "CREATE TEMP TRIGGER no_audit BEFORE INSERT ON audit
994                 BEGIN SELECT RAISE(ABORT, 'no audit'); END;",
995            )
996            .expect("trigger");
997    }
998
999    /// Runs `hook`, with the job's name, as each of the server's background
1000    /// jobs (the purge sweep, the pack run) begins its step for a tenant,
1001    /// for tests that hold a job inside that step.
1002    #[cfg(test)]
1003    pub(crate) fn when_a_job_steps_for_test(&self, hook: tests::JobHook) {
1004        *self.hooks.job_step.lock().expect("hook") = Some(hook);
1005    }
1006
1007    /// Where a background job begins its step for a tenant: runs the hook
1008    /// a test set with `when_a_job_steps_for_test`.
1009    #[cfg(test)]
1010    pub(crate) fn job_steps_for_test(&self, job: &'static str) {
1011        let hook = self.hooks.job_step.lock().expect("hook").clone();
1012        if let Some(hook) = hook {
1013            hook(job);
1014        }
1015    }
1016
1017    /// server.sqlite's connection, for tests that damage it.
1018    #[cfg(test)]
1019    pub(crate) fn conn_for_test(&self) -> MutexGuard<'_, LocalConn> {
1020        self.conn()
1021    }
1022
1023    /// The id of the tenant's current key, for tests.
1024    #[cfg(test)]
1025    pub(crate) fn tenant_key_id_for_test(&self, id: TenantId) -> Vec<u8> {
1026        let row = self.registry.snapshot().expect("reads").tenant(id);
1027        let row = row.expect("reads").expect("the tenant's row");
1028        row.tenant_key_id.bytes().to_vec()
1029    }
1030
1031    /// The admin log as `export` writes it, for tests.
1032    #[cfg(test)]
1033    pub(crate) fn admin_records(&self) -> Vec<serde_json::Value> {
1034        crate::audit::testing::exported(&self.conn(), None)
1035    }
1036
1037    /// Marks the tenant closing, as a removal does, for tests that need a
1038    /// closing tenant without removing it.
1039    #[cfg(test)]
1040    pub(crate) fn close(&self, id: TenantId) {
1041        self.drain(id).expect("not closing yet");
1042    }
1043
1044    /// A tenant's own retention period, None when it uses the server
1045    /// default, read afresh so a change counts from the next call. It is
1046    /// read for the server's own use, such as a delete's purge, so nothing
1047    /// is recorded.
1048    pub fn retention(&self, id: TenantId) -> Result<Option<Retention>, TenantError> {
1049        let row = self.registry.snapshot()?.tenant(id)?;
1050        stored_retention(row.ok_or(TenantError::NotFound)?.retention)
1051    }
1052
1053    /// Every tenant's id, read for the server's own use, such as the purge
1054    /// sweep, so nothing is recorded.
1055    pub fn ids(&self) -> Result<Vec<TenantId>, TenantError> {
1056        Ok(self
1057            .registry
1058            .snapshot()?
1059            .tenants()?
1060            .into_iter()
1061            .map(|row| row.id)
1062            .collect())
1063    }
1064
1065    /// Writes the admin log after `since` as JSON lines, oldest first.
1066    /// Not recorded: reading the log changes nothing.
1067    pub fn export_admin(
1068        &self,
1069        since: Option<i64>,
1070        out: &mut dyn std::io::Write,
1071    ) -> Result<(), audit::AuditError> {
1072        self.registry.export(since.unwrap_or(0), out)
1073    }
1074
1075    /// A page of the admin log as JSON lines, the lines `export_admin`
1076    /// writes for the same records. The read is recorded as audit_read in
1077    /// the admin log, in the same transaction, after the page is read.
1078    pub fn audit_page(
1079        &self,
1080        who: Actor,
1081        query: &audit::AuditQuery,
1082    ) -> Result<Vec<u8>, TenantError> {
1083        let mut tx = self.registry.immediate()?;
1084        let mut out = Vec::new();
1085        let read = tx.audit_lines(query.after, Some(query.limit), &mut out);
1086        self.record(
1087            &mut tx,
1088            &Entry {
1089                actor: who,
1090                action: Action::AuditRead,
1091                target: None,
1092                version: None,
1093                status: if read.is_ok() { 200 } else { 500 },
1094            },
1095        )?;
1096        commit(tx)?;
1097        read.map(|()| out).map_err(io)
1098    }
1099
1100    /// Whether server.sqlite answers a query, for the health route.
1101    pub fn check(&self) -> Result<(), TenantError> {
1102        self.registry.snapshot()?.tenants().map(|_| ())
1103    }
1104
1105    /// Records an event in the admin log, in a transaction of its own.
1106    pub(crate) fn record_alone(&self, entry: &Entry) -> Result<(), TenantError> {
1107        let mut tx = self.registry.immediate()?;
1108        self.record(&mut tx, entry)?;
1109        commit(tx)
1110    }
1111
1112    /// Counts an event in the admin log, in a transaction of its own.
1113    pub(crate) fn count_admin(&self, entry: &Entry) -> Result<(), TenantError> {
1114        let mut tx = self.registry.immediate()?;
1115        tx.count(entry, self.clock.now())
1116            .map_err(|_| TenantError::AuditFailed)?;
1117        commit(tx)
1118    }
1119
1120    /// Counts `times` events of the minute of `at` in the admin log, in
1121    /// one transaction: what was added up in memory, written once.
1122    pub(crate) fn count_admin_many(
1123        &self,
1124        entry: &Entry,
1125        at: OffsetDateTime,
1126        times: u64,
1127    ) -> Result<(), TenantError> {
1128        let mut tx = self.registry.immediate()?;
1129        tx.count_many(entry, at, times)
1130            .map_err(|_| TenantError::AuditFailed)?;
1131        commit(tx)
1132    }
1133
1134    /// The time on the clock the registry and the stores read.
1135    pub(crate) fn now(&self) -> OffsetDateTime {
1136        self.clock.now()
1137    }
1138
1139    /// The time given is this process's clock, as for a Store's record:
1140    /// a database's log writes the transaction's reading of its own clock
1141    /// instead. A removal's record is judged against the time the master
1142    /// key's use began, which another server may have written.
1143    fn record(&self, tx: &mut RTx, entry: &Entry) -> Result<(), TenantError> {
1144        tx.record(entry, self.clock.now())
1145            .map_err(|_| TenantError::AuditFailed)
1146    }
1147
1148    /// The local registry's connection, for tests.
1149    #[cfg(test)]
1150    fn conn(&self) -> MutexGuard<'_, LocalConn> {
1151        self.registry
1152            .as_any()
1153            .downcast_ref::<LocalRegistry>()
1154            .expect("the test's registry is the local one")
1155            .local_conn()
1156    }
1157}
1158
1159/// A tenant's name is a label for people: 1 to 128 characters, none of
1160/// them a control character, and no white space at either end, so two
1161/// names that look alike are alike.
1162fn good_name(name: &str) -> bool {
1163    (1..=128).contains(&name.chars().count())
1164        && !name.chars().any(char::is_control)
1165        && name.trim() == name
1166}
1167
1168/// A registry transaction.
1169pub(crate) type RTx<'a> = Box<dyn RegistryTx + 'a>;
1170
1171pub(crate) fn commit(tx: RTx) -> Result<(), TenantError> {
1172    tx.commit().map_err(io)
1173}
1174
1175pub(crate) fn io<E>(_: E) -> TenantError {
1176    TenantError::Io
1177}
1178
1179#[cfg(test)]
1180mod tests {
1181    use std::ffi::OsString;
1182
1183    use rusqlite::{Connection, OptionalExtension, params};
1184
1185    use serde_json::Value;
1186    use time::macros::datetime;
1187
1188    use super::*;
1189    use crate::audit::testing::exported;
1190    use crate::catalog;
1191    use crate::catalog::testing::columns_taking_null;
1192    use crate::clock::ManualClock;
1193    use crate::envelope::Context;
1194    use crate::fs::{CrashFs, Op};
1195    use crate::ids::VersionId;
1196    use crate::store::testing::vcon;
1197    use crate::store::{Caller, Created, StoreError};
1198
1199    const MARKER: &str = "plain-record-marker-8d21e4";
1200    const UUID: &str = "01a07da8-c2bb-83e5-b9a2-279e0d16bc46";
1201
1202    fn caller() -> Caller {
1203        Caller {
1204            key: Key::generate().expect("key").id(),
1205        }
1206    }
1207
1208    /// What a create runs between its space and its row, given the
1209    /// `Tenants` creating.
1210    pub(crate) type CreateHook = Box<dyn FnOnce(&Tenants) + Send>;
1211
1212    /// What a backup runs at each try, after it copies server.sqlite.
1213    pub(super) type RegistryHook = Box<dyn FnMut(&Tenants) + Send>;
1214
1215    #[derive(Default)]
1216    pub(super) struct Hooks {
1217        /// Runs once, between a create's directory and catalog and the
1218        /// transaction that commits its row, given the `Tenants` creating.
1219        pub(super) between: Mutex<Option<CreateHook>>,
1220        /// Runs once, as `store` opens a tenant's Store.
1221        pub(super) opening: Mutex<Option<Box<dyn FnOnce() + Send>>>,
1222        /// Stops a key rotation, as a failure, after this step.
1223        pub(crate) rekey_stop: Mutex<Option<super::rekey::RekeyStep>>,
1224        /// Runs at each try of a backup, after server.sqlite is copied and
1225        /// before the tenants it lists are.
1226        pub(super) registry_copied: Mutex<Option<RegistryHook>>,
1227        /// Runs as a background job begins its step for a tenant.
1228        pub(super) job_step: Mutex<Option<JobHook>>,
1229        /// Nanoseconds added to the next readings of the registry's clock
1230        /// ([`Tenants::now_in`], recovery's too), one per reading, in
1231        /// order, as for a Store.
1232        pub(super) clock_steps: Mutex<Vec<i64>>,
1233    }
1234
1235    /// What a background job runs as it begins its step for a tenant, with
1236    /// the job's name.
1237    pub(crate) type JobHook = std::sync::Arc<dyn Fn(&'static str) + Send + Sync>;
1238
1239    impl Tenants {
1240        /// Adds `steps` to the next readings of the registry's clock, one
1241        /// per reading, in order ([`Hooks::clock_steps`]).
1242        pub(crate) fn step_clock(&self, steps: Vec<i64>) {
1243            *self.hooks.clock_steps.lock().expect("hook") = steps;
1244        }
1245
1246        /// Makes the registry's `nth` commit from now (1: the next) fail as
1247        /// `how`.
1248        pub(crate) fn fail_registry_commit(&self, nth: usize, how: CommitError) {
1249            self.registry.fail_commit(nth, how);
1250        }
1251    }
1252
1253    /// A master key kept wrapped, so a test can have it more than once.
1254    struct Master {
1255        holder: Key,
1256        wrapped: Vec<u8>,
1257    }
1258
1259    const CTX: Context = Context::Tenant {
1260        tenant: TenantId([0; 16]),
1261    };
1262
1263    impl Master {
1264        fn new() -> Master {
1265            let holder = Key::generate().expect("key");
1266            let wrapped = envelope::wrap(&holder, &CTX, &Key::generate().expect("key"));
1267            Master { holder, wrapped }
1268        }
1269
1270        fn key(&self) -> Key {
1271            envelope::unwrap(&self.holder, &CTX, &self.wrapped).expect("unwraps")
1272        }
1273    }
1274
1275    pub(crate) struct Fixture {
1276        pub(crate) dir: tempfile::TempDir,
1277        pub(crate) fs: Arc<CrashFs>,
1278        pub(crate) clock: Arc<ManualClock>,
1279        master: Master,
1280        pub(crate) tenants: Tenants,
1281    }
1282
1283    impl Fixture {
1284        fn open(&self) -> Result<Tenants, RegistryError> {
1285            Tenants::open(
1286                self.dir.path(),
1287                self.master.key(),
1288                self.fs.clone(),
1289                self.clock.clone(),
1290            )
1291        }
1292
1293        /// A crash, then a start: what was not synced is lost, and the
1294        /// registry is opened again.
1295        pub(crate) fn restart(&mut self) {
1296            self.fs.crash();
1297            let tenants = self.open().expect("opens again");
1298            drop(std::mem::replace(&mut self.tenants, tenants));
1299        }
1300
1301        pub(crate) fn conn(&self) -> MutexGuard<'_, Connection> {
1302            self.tenants.conn()
1303        }
1304
1305        /// The master key the registry was made under.
1306        pub(crate) fn master_key(&self) -> Key {
1307            self.master.key()
1308        }
1309
1310        pub(crate) fn tenants_dir(&self) -> PathBuf {
1311            self.dir.path().join("tenants")
1312        }
1313
1314        /// The tenant directories, as the filesystem shows them now.
1315        fn dirs(&self) -> Vec<OsString> {
1316            self.fs.list(&self.tenants_dir()).expect("list tenants")
1317        }
1318
1319        /// The one number a statement on server.sqlite answers.
1320        pub(crate) fn count(&self, sql: &str) -> i64 {
1321            self.conn().query_row(sql, [], |r| r.get(0)).expect(sql)
1322        }
1323
1324        pub(crate) fn master_wraps(&self) -> i64 {
1325            self.count("SELECT coalesce(sum(wraps), 0) FROM master_key_use")
1326        }
1327
1328        fn admin_log(&self) -> Vec<Value> {
1329            exported(&self.conn(), None)
1330        }
1331
1332        /// The tenant's key, unwrapped from its row.
1333        pub(crate) fn tenant_key(&self, id: TenantId) -> Key {
1334            let wrapped: Vec<u8> = self
1335                .conn()
1336                .query_row(
1337                    "SELECT wrapped_tenant_key FROM tenant WHERE id = ?1",
1338                    [id.0],
1339                    |r| r.get(0),
1340                )
1341                .expect("a row");
1342            envelope::unwrap(
1343                &self.master.key(),
1344                &Context::Tenant { tenant: id },
1345                &wrapped,
1346            )
1347            .expect("unwraps under the master key")
1348        }
1349
1350        /// The tenant's Store, opened as the registry would open it.
1351        pub(crate) fn store(&self, id: TenantId) -> Store {
1352            Store::open(
1353                &self.tenants_dir().join(id.to_string()),
1354                id,
1355                self.tenant_key(id),
1356                self.fs.clone(),
1357                self.clock.clone(),
1358            )
1359            .expect("the store opens")
1360        }
1361
1362        fn has_row(&self, id: TenantId) -> bool {
1363            self.conn()
1364                .query_row("SELECT 1 FROM tenant WHERE id = ?1", [id.0], |_| Ok(()))
1365                .optional()
1366                .expect("query")
1367                .is_some()
1368        }
1369
1370        /// A second connection to server.sqlite, as another writer.
1371        fn other(&self) -> Connection {
1372            let catalog_key = envelope::catalog_key(&self.master.key()).expect("catalog key");
1373            catalog::open(&self.dir.path().join("server.sqlite"), &catalog_key, "")
1374                .expect("second connection")
1375        }
1376    }
1377
1378    pub(crate) fn fixture() -> Fixture {
1379        let dir = tempfile::tempdir().expect("temp dir");
1380        let fs = Arc::new(CrashFs::new(dir.path()));
1381        let clock = Arc::new(ManualClock::at(datetime!(2026-10-23 12:00 UTC)));
1382        let master = Master::new();
1383        let tenants =
1384            Tenants::open(dir.path(), master.key(), fs.clone(), clock.clone()).expect("opens");
1385        Fixture {
1386            dir,
1387            fs,
1388            clock,
1389            master,
1390            tenants,
1391        }
1392    }
1393
1394    #[test]
1395    fn server_sqlite_is_a_catalog_under_the_master_keys_catalog_key() {
1396        let f = fixture();
1397        let conn = f.other();
1398        let tables: Vec<String> = conn
1399            .prepare("SELECT name FROM sqlite_master WHERE type = 'table' ORDER BY name")
1400            .expect("prepare")
1401            .query_map([], |r| r.get(0))
1402            .expect("query")
1403            .collect::<Result<_, _>>()
1404            .expect("names");
1405        assert_eq!(
1406            tables,
1407            [
1408                "api_key",
1409                "audit",
1410                "master_key_use",
1411                "membership",
1412                "session",
1413                "sqlite_sequence",
1414                "tenant",
1415                "tenant_setting",
1416                "user_account"
1417            ]
1418        );
1419    }
1420
1421    #[test]
1422    fn an_admin_audit_page_is_export_s_lines_and_records_its_read_after_them() {
1423        let f = fixture();
1424        for name in ["acme", "beta"] {
1425            f.tenants.create(Actor::Cli, name, None).expect("made");
1426        }
1427        let mut before = Vec::new();
1428        f.tenants.export_admin(None, &mut before).expect("export");
1429        let who = Actor::Key(Key::generate().expect("key").id());
1430        let query = |after, limit| audit::AuditQuery { after, limit };
1431        assert_eq!(
1432            f.tenants.audit_page(who, &query(0, 1000)),
1433            Ok(before.clone())
1434        );
1435        let read = exported(&f.conn(), None);
1436        let last = read.last().expect("records");
1437        assert_eq!(last["action"], "audit_read");
1438        assert_eq!(last["status"], 200);
1439        let lines: Vec<&[u8]> = before.split_inclusive(|b| *b == b'\n').collect();
1440        assert_eq!(
1441            f.tenants.audit_page(who, &query(1, 1)),
1442            Ok(lines[1].to_vec())
1443        );
1444        f.conn()
1445            .execute(
1446                "INSERT INTO audit (at, actor, action, status, count)
1447                 VALUES ('2026-10-23T12:00:00Z', 'cli', 'read', 70000, 1)",
1448                [],
1449            )
1450            .expect("damaged");
1451        assert_eq!(
1452            f.tenants.audit_page(who, &query(0, 1000)),
1453            Err(TenantError::Io)
1454        );
1455        let last = exported_last(&f);
1456        assert_eq!(last["action"], "audit_read");
1457        assert_eq!(last["status"], 500);
1458        f.tenants.break_audit();
1459        assert_eq!(
1460            f.tenants.audit_page(who, &query(0, 1000)),
1461            Err(TenantError::AuditFailed)
1462        );
1463    }
1464
1465    /// The admin log's last record, read past a damaged one.
1466    fn exported_last(f: &Fixture) -> Value {
1467        let conn = f.conn();
1468        let (action, status): (String, i64) = conn
1469            .query_row(
1470                "SELECT action, status FROM audit ORDER BY seq DESC LIMIT 1",
1471                [],
1472                |r| Ok((r.get(0)?, r.get(1)?)),
1473            )
1474            .expect("a record");
1475        serde_json::json!({"action": action, "status": status})
1476    }
1477
1478    /// What a registry that does not open says: everything a failure
1479    /// report shows of the error.
1480    fn said(dir: &Path) -> String {
1481        let error = Tenants::open(
1482            dir,
1483            Key::generate().expect("key"),
1484            Arc::new(crate::fs::OsFs),
1485            Arc::new(ManualClock::at(datetime!(2026-10-23 12:00 UTC))),
1486        )
1487        .err()
1488        .expect("it does not open");
1489        format!("{error:?}")
1490    }
1491
1492    /// A server.sqlite that cannot be opened names the file, the step and
1493    /// SQLite's error, not only "Io".
1494    #[test]
1495    fn a_server_sqlite_that_cannot_be_opened_names_the_file_and_the_cause() {
1496        let dir = tempfile::tempdir().expect("temp dir");
1497        std::fs::create_dir(dir.path().join("server.sqlite")).expect("a directory in its place");
1498        let said = said(dir.path());
1499        assert!(said.contains("server.sqlite"), "the file is named: {said}");
1500        assert!(said.contains("OpenCatalog"), "the step is named: {said}");
1501        assert!(
1502            said.contains("unable to open database file"),
1503            "SQLite's own error is kept: {said}"
1504        );
1505    }
1506
1507    /// A tenants/ that cannot be made names the directory and the system's
1508    /// error.
1509    #[test]
1510    fn a_tenants_directory_that_cannot_be_made_names_it_and_the_cause() {
1511        let dir = tempfile::tempdir().expect("temp dir");
1512        std::fs::write(dir.path().join("tenants"), b"").expect("a file in its place");
1513        let said = said(dir.path());
1514        assert!(said.contains("tenants"), "the directory is named: {said}");
1515        assert!(said.contains("MakeTenantsDir"), "the step is named: {said}");
1516        assert!(
1517            said.contains("File exists"),
1518            "the system's error is kept: {said}"
1519        );
1520    }
1521
1522    #[test]
1523    fn a_wrong_master_key_does_not_open_server_sqlite() {
1524        let f = fixture();
1525        let wrong = Tenants::open(
1526            f.dir.path(),
1527            Master::new().key(),
1528            f.fs.clone(),
1529            f.clock.clone(),
1530        );
1531        assert!(
1532            matches!(wrong, Err(RegistryError::WrongKey)),
1533            "a wrong key is told apart from every other failure: {:?}",
1534            wrong.err()
1535        );
1536        assert!(f.open().is_ok(), "the right key still opens it");
1537    }
1538
1539    #[test]
1540    fn only_the_optional_columns_may_be_empty() {
1541        let f = fixture();
1542        let conn = f.conn();
1543        let tenant = [
1544            ("id", "x'11'"),
1545            ("name", "'a'"),
1546            ("retention", "'7y'"),
1547            ("created_at", "1"),
1548            ("tenant_key_id", "x'22'"),
1549            ("wrapped_tenant_key", "x'33'"),
1550            ("pending_wrapped_tenant_key", "x'44'"),
1551            ("key_since", "1"),
1552        ];
1553        let key_use = [("master_key_id", "x'55'"), ("wraps", "1"), ("since", "1")];
1554        let api_key = [
1555            ("id", "x'66'"),
1556            ("tenant", "x'11'"),
1557            ("token_hash", "x'77'"),
1558            ("scopes", "'read'"),
1559            ("label", "'a'"),
1560            ("created_at", "1"),
1561            ("revoked_at", "2"),
1562        ];
1563        let mut may_be_empty = columns_taking_null(&conn, "tenant", &tenant);
1564        may_be_empty.extend(columns_taking_null(&conn, "master_key_use", &key_use));
1565        may_be_empty.extend(columns_taking_null(&conn, "api_key", &api_key));
1566        assert_eq!(
1567            may_be_empty,
1568            [
1569                "tenant.retention",
1570                "tenant.pending_wrapped_tenant_key",
1571                "api_key.tenant",
1572                "api_key.revoked_at"
1573            ]
1574        );
1575    }
1576
1577    #[test]
1578    fn a_name_belongs_to_one_tenant() {
1579        let f = fixture();
1580        let conn = f.conn();
1581        let add = |id: u8, name: &str| {
1582            conn.execute(
1583                "INSERT INTO tenant (id, name, created_at, tenant_key_id,
1584                     wrapped_tenant_key, key_since)
1585                 VALUES (?1, ?2, 1, x'22', x'33', 1)",
1586                params![[id; 16], name],
1587            )
1588        };
1589        add(1, "a").expect("the first tenant");
1590        add(2, "b").expect("another name");
1591        assert!(add(3, "a").is_err(), "a second tenant named a");
1592    }
1593
1594    /// Run while the connection is open, so the commits are still in the
1595    /// WAL.
1596    #[test]
1597    fn no_plain_record_reaches_server_sqlite_or_its_wal() {
1598        let f = fixture();
1599        f.tenants
1600            .create(Actor::Cli, MARKER, Some(Retention::Years(7)))
1601            .expect("a tenant");
1602        let wal = std::fs::metadata(f.dir.path().join("server.sqlite-wal")).expect("a WAL");
1603        assert!(wal.len() > 0, "the commits are in the WAL");
1604        for entry in std::fs::read_dir(f.dir.path()).expect("list") {
1605            let file = entry.expect("entry").path();
1606            if !file.is_file() {
1607                continue;
1608            }
1609            let bytes = std::fs::read(&file).expect("read");
1610            assert!(
1611                !bytes.windows(MARKER.len()).any(|w| w == MARKER.as_bytes()),
1612                "plain record in {}",
1613                file.display()
1614            );
1615        }
1616    }
1617
1618    #[test]
1619    fn a_new_registrys_tenants_directory_survives_a_crash() {
1620        let f = fixture();
1621        f.fs.crash();
1622        assert_eq!(
1623            f.fs.list(f.dir.path()).expect("list"),
1624            [OsString::from("tenants")]
1625        );
1626    }
1627
1628    /// A tenant row's columns, besides its id and wrapped key.
1629    struct Row {
1630        name: String,
1631        retention: Option<String>,
1632        created_at: i64,
1633        key_id: Vec<u8>,
1634        pending: Option<Vec<u8>>,
1635        key_since: i64,
1636    }
1637
1638    #[test]
1639    fn a_tenant_is_made_with_its_key_directory_catalog_and_row() {
1640        let f = fixture();
1641        let id = f
1642            .tenants
1643            .create(Actor::Cli, "acme", Some(Retention::Years(7)))
1644            .expect("made");
1645        f.clock.set(datetime!(2026-10-23 13:00 UTC));
1646        let other = f.tenants.create(Actor::Cli, "lab", None).expect("another");
1647        assert_ne!(id, other, "a new id each time");
1648
1649        let Row {
1650            name,
1651            retention,
1652            created_at,
1653            key_id,
1654            pending,
1655            key_since,
1656        } = f
1657            .conn()
1658            .query_row(
1659                "SELECT name, retention, created_at, tenant_key_id,
1660                     pending_wrapped_tenant_key, key_since
1661                 FROM tenant WHERE id = ?1",
1662                [id.0],
1663                |r| {
1664                    Ok(Row {
1665                        name: r.get(0)?,
1666                        retention: r.get(1)?,
1667                        created_at: r.get(2)?,
1668                        key_id: r.get(3)?,
1669                        pending: r.get(4)?,
1670                        key_since: r.get(5)?,
1671                    })
1672                },
1673            )
1674            .expect("a row");
1675        let now = nanos(datetime!(2026-10-23 12:00 UTC));
1676        assert_eq!(name, "acme");
1677        assert_eq!(retention.as_deref(), Some("7y"));
1678        assert_eq!((created_at, key_since), (now, now));
1679        assert_eq!(pending, None);
1680        let key = f.tenant_key(id);
1681        assert_eq!(key_id, key.id().bytes());
1682        let lab_retention: Option<String> = f
1683            .conn()
1684            .query_row(
1685                "SELECT retention FROM tenant WHERE id = ?1",
1686                [other.0],
1687                |r| r.get(0),
1688            )
1689            .expect("a row");
1690        assert_eq!(lab_retention, None, "no period means the server default");
1691
1692        let mut dirs = vec![
1693            OsString::from(id.to_string()),
1694            OsString::from(other.to_string()),
1695        ];
1696        dirs.sort();
1697        assert_eq!(f.dirs(), dirs);
1698        drop(f.store(id));
1699        let catalog_key = envelope::catalog_key(&key).expect("catalog key");
1700        let tenant_dir = f.tenants_dir().join(id.to_string());
1701        assert!(
1702            catalog::open(&tenant_dir.join("catalog.sqlite"), &catalog_key, "").is_ok(),
1703            "the catalog is under the tenant key's catalog key"
1704        );
1705
1706        let (wraps, since): (i64, i64) = f
1707            .conn()
1708            .query_row(
1709                "SELECT wraps, since FROM master_key_use WHERE master_key_id = ?1",
1710                [f.master.key().id().bytes()],
1711                |r| Ok((r.get(0)?, r.get(1)?)),
1712            )
1713            .expect("the master key's use");
1714        assert_eq!((wraps, since), (2, now));
1715
1716        let log = f.admin_log();
1717        assert_eq!(log.len(), 2);
1718        assert_eq!(log[0]["actor"], "cli");
1719        assert_eq!(log[0]["action"], "tenant_create");
1720        assert_eq!(log[0]["target"], id.to_string());
1721        assert_eq!(log[0]["status"], 201);
1722        assert_eq!(log[0]["at"], "2026-10-23T12:00:00Z");
1723    }
1724
1725    #[test]
1726    fn a_taken_name_is_refused_before_anything_is_made() {
1727        let f = fixture();
1728        f.tenants.create(Actor::Cli, "acme", None).expect("made");
1729        let ops = f.fs.log().len();
1730        assert_eq!(
1731            f.tenants.create(Actor::Cli, "acme", None),
1732            Err(TenantError::NameTaken)
1733        );
1734        assert_eq!(f.fs.log().len(), ops, "nothing made");
1735        assert_eq!(f.master_wraps(), 1, "nothing wrapped");
1736        assert_eq!(f.count("SELECT count(*) FROM tenant"), 1);
1737        let log = f.admin_log();
1738        assert_eq!(log[1]["action"], "tenant_create");
1739        assert_eq!(log[1]["status"], 409);
1740        assert_eq!(log[1]["target"], Value::Null, "no tenant was made");
1741    }
1742
1743    #[test]
1744    fn a_name_is_1_to_128_characters_without_controls_or_outer_spaces() {
1745        let long = "é".repeat(128);
1746        for name in ["acme", "a", "Acme Corp", "Acme — Europe", long.as_str()] {
1747            assert!(good_name(name), "{name:?}");
1748        }
1749        let longer = "é".repeat(129);
1750        for name in [
1751            "",
1752            " acme",
1753            "acme ",
1754            "ac\nme",
1755            "ac\tme",
1756            "acme\u{7f}",
1757            "\u{85}acme",
1758            "acme\u{3000}",
1759            longer.as_str(),
1760        ] {
1761            assert!(!good_name(name), "{name:?}");
1762        }
1763    }
1764
1765    #[test]
1766    fn a_bad_name_is_refused_and_recorded_before_anything_is_made() {
1767        let f = fixture();
1768        let ops = f.fs.log().len();
1769        assert_eq!(
1770            f.tenants.create(Actor::Cli, " acme", None),
1771            Err(TenantError::BadName)
1772        );
1773        assert_eq!(f.fs.log().len(), ops, "nothing made");
1774        assert_eq!(f.master_wraps(), 0, "nothing wrapped");
1775        assert_eq!(f.count("SELECT count(*) FROM tenant"), 0);
1776        let log = f.admin_records("tenant_create");
1777        assert_eq!(log.len(), 1);
1778        assert_eq!(log[0]["status"], 422);
1779        assert_eq!(log[0]["target"], Value::Null, "no tenant was made");
1780    }
1781
1782    #[test]
1783    fn a_master_key_at_its_wrap_limit_makes_no_tenant() {
1784        let f = fixture();
1785        f.conn()
1786            .execute(
1787                "INSERT INTO master_key_use (master_key_id, wraps, since) VALUES (?1, ?2, 1)",
1788                params![f.master.key().id().bytes(), 1_i64 << 32],
1789            )
1790            .expect("at the limit");
1791        let ops = f.fs.log().len();
1792        assert_eq!(
1793            f.tenants.create(Actor::Cli, "acme", None),
1794            Err(TenantError::LimitReached)
1795        );
1796        assert_eq!(f.fs.log().len(), ops, "nothing made");
1797        assert_eq!(f.master_wraps(), 1_i64 << 32, "nothing counted");
1798        assert_eq!(f.count("SELECT count(*) FROM tenant"), 0);
1799        assert_eq!(f.admin_log()[0]["status"], 503);
1800    }
1801
1802    #[test]
1803    fn a_negative_wrap_count_is_damage_and_makes_no_tenant() {
1804        let f = fixture();
1805        f.conn()
1806            .execute(
1807                "INSERT INTO master_key_use (master_key_id, wraps, since) VALUES (?1, -1, 1)",
1808                [f.master.key().id().bytes()],
1809            )
1810            .expect("a damaged count");
1811        let ops = f.fs.log().len();
1812        assert_eq!(
1813            f.tenants.create(Actor::Cli, "acme", None),
1814            Err(TenantError::Io)
1815        );
1816        assert_eq!(f.fs.log().len(), ops, "nothing made");
1817    }
1818
1819    #[test]
1820    fn a_name_taken_while_the_directory_is_made_loses_and_leaves_nothing() {
1821        let f = fixture();
1822        let other = f.other();
1823        *f.tenants.hooks.between.lock().expect("hook") = Some(Box::new(move |_| {
1824            other
1825                .execute(
1826                    "INSERT INTO tenant (id, name, created_at, tenant_key_id,
1827                         wrapped_tenant_key, key_since)
1828                     VALUES (x'01', 'acme', 1, x'02', x'03', 1)",
1829                    [],
1830                )
1831                .expect("another create wins the name");
1832        }));
1833        assert_eq!(
1834            f.tenants.create(Actor::Cli, "acme", None),
1835            Err(TenantError::NameTaken)
1836        );
1837        assert_eq!(f.dirs(), Vec::<OsString>::new(), "its directory is removed");
1838        assert_eq!(f.master_wraps(), 1, "its wrap is still counted");
1839        let log = f.admin_log();
1840        assert_eq!(log.len(), 1);
1841        assert_eq!(log[0]["status"], 409);
1842    }
1843
1844    #[test]
1845    fn a_create_whose_audit_record_fails_leaves_nothing() {
1846        let f = fixture();
1847        f.conn()
1848            .execute_batch(
1849                "CREATE TEMP TRIGGER no_audit BEFORE INSERT ON audit
1850                 BEGIN SELECT RAISE(ABORT, 'no audit'); END;",
1851            )
1852            .expect("trigger");
1853        assert_eq!(
1854            f.tenants.create(Actor::Cli, "acme", None),
1855            Err(TenantError::AuditFailed)
1856        );
1857        assert_eq!(f.count("SELECT count(*) FROM tenant"), 0);
1858        assert_eq!(f.dirs(), Vec::<OsString>::new(), "its directory is removed");
1859    }
1860
1861    #[test]
1862    fn a_create_whose_row_cannot_be_written_leaves_nothing() {
1863        let f = fixture();
1864        f.conn()
1865            .execute_batch(
1866                "CREATE TEMP TRIGGER no_row BEFORE INSERT ON tenant
1867                 BEGIN SELECT RAISE(ABORT, 'the disk has failed'); END;",
1868            )
1869            .expect("trigger");
1870        assert_eq!(
1871            f.tenants.create(Actor::Cli, "acme", None),
1872            Err(TenantError::Io)
1873        );
1874        assert_eq!(f.count("SELECT count(*) FROM tenant"), 0);
1875        assert_eq!(f.dirs(), Vec::<OsString>::new(), "its directory is removed");
1876    }
1877
1878    #[test]
1879    fn a_create_whose_commit_outcome_is_unknown_keeps_its_directory() {
1880        let f = fixture();
1881        // The wrap count commits first; the second commit, which adds the
1882        // row, is kept and then reported as failed, as a lost connection
1883        // reports a commit the database made.
1884        f.tenants.fail_registry_commit(2, CommitError::Unknown);
1885        assert_eq!(
1886            f.tenants.create(Actor::Cli, "acme", None),
1887            Err(TenantError::Io),
1888            "a_create_whose_commit_outcome_is_unknown_keeps_its_directory: f.tenants.create(Actor::Cli, \"acme\", None)"
1889        );
1890        assert_eq!(
1891            f.count("SELECT count(*) FROM tenant"),
1892            1,
1893            "a_create_whose_commit_outcome_is_unknown_keeps_its_directory: f.count(\"SELECT count(*) FROM tenant\")"
1894        );
1895        assert_eq!(
1896            f.dirs().len(),
1897            1,
1898            "the directory made for the kept row stays"
1899        );
1900        let id = f.tenants.ids().expect("ids")[0];
1901        let store = f.tenants.store(id).expect("the kept tenant opens");
1902        let (found, body) = vcon(UUID, "kept");
1903        store.create(&caller(), &found, &body).expect("stores");
1904    }
1905
1906    #[test]
1907    fn a_create_whose_commit_rolls_back_leaves_nothing() {
1908        let f = fixture();
1909        f.tenants.fail_registry_commit(2, CommitError::RolledBack);
1910        assert_eq!(
1911            f.tenants.create(Actor::Cli, "acme", None),
1912            Err(TenantError::Io),
1913            "a_create_whose_commit_rolls_back_leaves_nothing: f.tenants.create(Actor::Cli, \"acme\", None)"
1914        );
1915        assert_eq!(
1916            f.count("SELECT count(*) FROM tenant"),
1917            0,
1918            "a_create_whose_commit_rolls_back_leaves_nothing: f.count(\"SELECT count(*) FROM tenant\")"
1919        );
1920        assert_eq!(f.dirs(), Vec::<OsString>::new(), "its directory is removed");
1921    }
1922
1923    #[test]
1924    fn a_refusal_whose_audit_record_fails_is_an_audit_failure() {
1925        let f = fixture();
1926        f.tenants.create(Actor::Cli, "acme", None).expect("made");
1927        f.conn()
1928            .execute_batch(
1929                "CREATE TEMP TRIGGER no_audit BEFORE INSERT ON audit
1930                 BEGIN SELECT RAISE(ABORT, 'no audit'); END;",
1931            )
1932            .expect("trigger");
1933        assert_eq!(
1934            f.tenants.create(Actor::Cli, "acme", None),
1935            Err(TenantError::AuditFailed)
1936        );
1937    }
1938
1939    /// The steps of a create that the filesystem sees: the tenant's
1940    /// directory; the new catalog's WAL and then the tenant's directory
1941    /// synced when the catalog opens; its objects directory and the sync of
1942    /// the tenant's directory; start-up recovery's commit synced; the sync
1943    /// of `tenants/`. The row's commit follows them.
1944    const CREATE_STEPS: usize = 7;
1945
1946    #[test]
1947    fn a_create_writes_its_directories_in_order() {
1948        let f = fixture();
1949        let ops = f.fs.log().len();
1950        let id = f.tenants.create(Actor::Cli, "acme", None).expect("made");
1951        let dir = f.tenants_dir().join(id.to_string());
1952        let wal = dir.join("catalog.sqlite-wal");
1953        assert_eq!(
1954            f.fs.log()[ops..],
1955            [
1956                Op::CreateDir(dir.clone()),
1957                Op::SyncData(wal.clone()),
1958                Op::SyncDir(dir.clone()),
1959                Op::CreateDir(dir.join("objects")),
1960                Op::SyncDir(dir),
1961                Op::SyncData(wal),
1962                Op::SyncDir(f.tenants_dir()),
1963            ],
1964            "the WAL is synced, then its directory, before anything else is made"
1965        );
1966        assert_eq!(
1967            f.fs.log().len() - ops,
1968            CREATE_STEPS,
1969            "the steps a cut can hit"
1970        );
1971    }
1972
1973    #[test]
1974    fn a_create_cut_off_at_any_step_leaves_a_whole_tenant_or_none() {
1975        let uncut = {
1976            let f = fixture();
1977            let ops = f.fs.log().len();
1978            f.tenants.create(Actor::Cli, "acme", None).expect("made");
1979            f.fs.log()[ops..].to_vec()
1980        };
1981        assert_eq!(
1982            uncut.len(),
1983            CREATE_STEPS,
1984            "every step of a create: {uncut:?}"
1985        );
1986        for step in 0..=CREATE_STEPS {
1987            let mut f = fixture();
1988            f.fs.fail_from(f.fs.log().len() + step);
1989            let result = f.tenants.create(Actor::Cli, "acme", None);
1990            assert_eq!(
1991                result.is_ok(),
1992                step == CREATE_STEPS,
1993                "step {step}: {result:?}"
1994            );
1995            f.restart();
1996            match result {
1997                Ok(id) => {
1998                    assert!(f.has_row(id), "step {step}");
1999                    assert_eq!(f.dirs(), [OsString::from(id.to_string())]);
2000                    let store = f.store(id);
2001                    drop(store);
2002                }
2003                Err(_) => {
2004                    assert_eq!(f.count("SELECT count(*) FROM tenant"), 0, "step {step}");
2005                    assert_eq!(f.dirs(), Vec::<OsString>::new(), "step {step}");
2006                }
2007            }
2008        }
2009    }
2010
2011    #[test]
2012    fn a_create_cut_off_before_its_commit_leaves_no_tenant() {
2013        let mut f = fixture();
2014        let other = f.other();
2015        let fs = f.fs.clone();
2016        *f.tenants.hooks.between.lock().expect("hook") = Some(Box::new(move |_| {
2017            fs.fail_from(0);
2018            other
2019                .execute_batch(
2020                    "CREATE TRIGGER dead BEFORE INSERT ON audit
2021                     BEGIN SELECT RAISE(ABORT, 'the process has died'); END;",
2022                )
2023                .expect("trigger");
2024        }));
2025        assert!(f.tenants.create(Actor::Cli, "acme", None).is_err());
2026        assert_eq!(f.dirs().len(), 1, "the dead process removed nothing");
2027        f.conn()
2028            .execute_batch("DROP TRIGGER dead")
2029            .expect("drop trigger");
2030        f.restart();
2031        assert_eq!(f.count("SELECT count(*) FROM tenant"), 0);
2032        assert_eq!(f.dirs(), Vec::<OsString>::new(), "removed at start");
2033    }
2034
2035    /// The fixture clock's start, as the creates below begin.
2036    const START: OffsetDateTime = datetime!(2026-10-23 12:00 UTC);
2037
2038    /// `START` moved by `nanos` nanoseconds.
2039    fn start_plus(nanos: i64) -> OffsetDateTime {
2040        START + time::Duration::nanoseconds(nanos)
2041    }
2042
2043    impl Fixture {
2044        /// The creating rows of the registry: the creates under way.
2045        fn creating(&self) -> Vec<(TenantId, i64)> {
2046            self.tenants
2047                .registry
2048                .snapshot()
2049                .expect("a read begins")
2050                .creating()
2051                .expect("lists")
2052        }
2053
2054        /// Sets the hook between a create's space and its row to move the
2055        /// clock to `to` and run recovery with `writers`, as another
2056        /// process recovering at that time would.
2057        fn recover_between(&self, to: OffsetDateTime, writers: Writers) {
2058            let clock = self.clock.clone();
2059            *self.tenants.hooks.between.lock().expect("hook") =
2060                Some(Box::new(move |tenants: &Tenants| {
2061                    clock.set(to);
2062                    tenants.recover(writers).expect("recovery runs");
2063                }));
2064        }
2065    }
2066
2067    #[test]
2068    fn a_create_under_way_keeps_its_space_through_recovery_beside_other_writers() {
2069        let f = fixture();
2070        f.recover_between(START, Writers::Maybe);
2071        let id = f
2072            .tenants
2073            .create(Actor::Cli, "acme", None)
2074            .expect("the create commits");
2075        assert_eq!(f.dirs(), [OsString::from(id.to_string())], "its space kept");
2076        drop(f.store(id));
2077    }
2078
2079    /// Recovery reads the registry's clock once: a create a minute inside
2080    /// its lease at that reading is kept, though the clock passes the
2081    /// lease before recovery lists the spaces. Else its space would go
2082    /// while its creating row stays, and the create would add a tenant
2083    /// with no space.
2084    #[test]
2085    fn recovery_judges_every_creating_row_by_one_reading_of_the_clock() {
2086        let f = fixture();
2087        let minute = 60 * 1_000_000_000;
2088        let clock = f.clock.clone();
2089        let to = start_plus(pending::WRITE_LEASE - minute);
2090        // The steps are set in the create's pause, so that recovery's are
2091        // the next readings: the create reads the clock before it too.
2092        *f.tenants.hooks.between.lock().expect("hook") =
2093            Some(Box::new(move |tenants: &Tenants| {
2094                clock.set(to);
2095                tenants.step_clock(vec![0, 2 * minute]);
2096                tenants.recover(Writers::Maybe).expect("recovery runs");
2097            }));
2098        let id = f
2099            .tenants
2100            .create(Actor::Cli, "acme", None)
2101            .expect("the create commits");
2102        assert_eq!(
2103            f.dirs(),
2104            [OsString::from(id.to_string())],
2105            "its space was kept with its row"
2106        );
2107        drop(f.store(id));
2108    }
2109
2110    #[test]
2111    fn a_create_just_inside_its_lease_keeps_its_space() {
2112        let f = fixture();
2113        f.recover_between(start_plus(pending::WRITE_LEASE - 1), Writers::Maybe);
2114        let id = f
2115            .tenants
2116            .create(Actor::Cli, "acme", None)
2117            .expect("the create commits");
2118        assert_eq!(f.dirs(), [OsString::from(id.to_string())], "its space kept");
2119        drop(f.store(id));
2120    }
2121
2122    #[test]
2123    fn a_create_seen_from_a_clock_behind_is_still_under_way() {
2124        let f = fixture();
2125        f.recover_between(start_plus(1 - pending::WRITE_LEASE), Writers::Maybe);
2126        let id = f
2127            .tenants
2128            .create(Actor::Cli, "acme", None)
2129            .expect("a clock behind within the lease keeps it");
2130        assert_eq!(f.dirs(), [OsString::from(id.to_string())], "its space kept");
2131        drop(f.store(id));
2132    }
2133
2134    #[test]
2135    fn a_create_past_its_lease_is_a_leftover_and_adds_no_row() {
2136        let f = fixture();
2137        f.recover_between(start_plus(pending::WRITE_LEASE), Writers::Maybe);
2138        assert_eq!(
2139            f.tenants.create(Actor::Cli, "acme", None),
2140            Err(TenantError::Io),
2141            "recovery took its space, so the create is refused"
2142        );
2143        assert_eq!(f.count("SELECT count(*) FROM tenant"), 0, "no row");
2144        assert_eq!(f.dirs(), Vec::<OsString>::new(), "and no space");
2145        assert_eq!(f.creating(), Vec::new(), "nor a creating row");
2146    }
2147
2148    #[test]
2149    fn a_create_under_way_is_a_leftover_to_a_process_that_holds_the_registry_alone() {
2150        let f = fixture();
2151        f.recover_between(START, Writers::None);
2152        assert_eq!(
2153            f.tenants.create(Actor::Cli, "acme", None),
2154            Err(TenantError::Io),
2155            "with no other writer, the space is a leftover's"
2156        );
2157        assert_eq!(f.count("SELECT count(*) FROM tenant"), 0, "no row");
2158        assert_eq!(f.dirs(), Vec::<OsString>::new(), "and no space");
2159    }
2160
2161    #[test]
2162    fn a_create_records_itself_under_way_until_its_row() {
2163        let f = fixture();
2164        let seen = Arc::new(Mutex::new(Vec::new()));
2165        let into = seen.clone();
2166        *f.tenants.hooks.between.lock().expect("hook") =
2167            Some(Box::new(move |tenants: &Tenants| {
2168                *into.lock().expect("seen") = tenants
2169                    .registry
2170                    .snapshot()
2171                    .expect("a read begins")
2172                    .creating()
2173                    .expect("lists");
2174            }));
2175        let id = f.tenants.create(Actor::Cli, "acme", None).expect("made");
2176        assert_eq!(
2177            *seen.lock().expect("seen"),
2178            vec![(id, nanos(START))],
2179            "between its space and its row, the create is under way"
2180        );
2181        assert_eq!(f.creating(), Vec::new(), "the row's commit drops it");
2182    }
2183
2184    #[test]
2185    fn a_create_refused_for_its_name_leaves_no_creating_row() {
2186        let f = fixture();
2187        f.tenants.create(Actor::Cli, "acme", None).expect("made");
2188        assert_eq!(
2189            f.tenants.create(Actor::Cli, "acme", None),
2190            Err(TenantError::NameTaken),
2191            "the name is taken at the first step"
2192        );
2193        assert_eq!(f.creating(), Vec::new(), "a first-step refusal adds none");
2194        let other = f.other();
2195        *f.tenants.hooks.between.lock().expect("hook") = Some(Box::new(move |_| {
2196            other
2197                .execute(
2198                    "INSERT INTO tenant (id, name, created_at, tenant_key_id,
2199                         wrapped_tenant_key, key_since)
2200                     VALUES (x'01', 'beta', 1, x'02', x'03', 1)",
2201                    [],
2202                )
2203                .expect("another create wins the name");
2204        }));
2205        assert_eq!(
2206            f.tenants.create(Actor::Cli, "beta", None),
2207            Err(TenantError::NameTaken),
2208            "another create took the name before the row"
2209        );
2210        assert_eq!(f.creating(), Vec::new(), "nor a refusal at the row");
2211    }
2212
2213    #[test]
2214    fn a_create_whose_row_fails_leaves_no_creating_row() {
2215        let f = fixture();
2216        f.conn()
2217            .execute_batch(
2218                "CREATE TEMP TRIGGER no_tenant BEFORE INSERT ON tenant
2219                 BEGIN SELECT RAISE(ABORT, 'no row'); END;",
2220            )
2221            .expect("trigger");
2222        assert!(
2223            f.tenants.create(Actor::Cli, "acme", None).is_err(),
2224            "the row cannot be written"
2225        );
2226        assert_eq!(f.creating(), Vec::new(), "the failed create drops it");
2227        assert_eq!(f.dirs(), Vec::<OsString>::new(), "and its space");
2228    }
2229
2230    #[test]
2231    fn recovery_beside_other_writers_removes_a_space_with_no_row_and_no_create() {
2232        let f = fixture();
2233        let kept = f.tenants.create(Actor::Cli, "acme", None).expect("made");
2234        let orphan = TenantId::generate();
2235        f.fs.create_dir_all(&f.tenants_dir().join(orphan.to_string()))
2236            .expect("a directory");
2237        f.tenants.recover(Writers::Maybe).expect("recovery runs");
2238        assert_eq!(
2239            f.dirs(),
2240            [OsString::from(kept.to_string())],
2241            "no create is under way for the orphan"
2242        );
2243    }
2244
2245    #[test]
2246    fn recovery_drops_only_the_creating_rows_past_their_lease() {
2247        let f = fixture();
2248        {
2249            let mut tx = f.tenants.registry.immediate().expect("a write begins");
2250            tx.add_creating(TenantId([1; 16]), nanos(START) - pending::WRITE_LEASE)
2251                .expect("adds");
2252            tx.add_creating(TenantId([2; 16]), nanos(START) - pending::WRITE_LEASE + 1)
2253                .expect("adds");
2254            tx.commit().expect("commits");
2255        }
2256        f.tenants.recover(Writers::Maybe).expect("recovery runs");
2257        assert_eq!(
2258            f.creating(),
2259            vec![(TenantId([2; 16]), nanos(START) - pending::WRITE_LEASE + 1)],
2260            "the row inside the lease is a create under way"
2261        );
2262        f.tenants.recover(Writers::None).expect("recovery runs");
2263        assert_eq!(f.creating(), Vec::new(), "alone, every row is a leftover's");
2264    }
2265
2266    /// The recovery a running server repeats at each sweep: the leftover
2267    /// space goes without a restart, and the tenant's Store is recovered
2268    /// as one other writers may be using.
2269    #[test]
2270    fn a_running_server_s_recovery_removes_a_space_with_no_row_and_keeps_the_rest() {
2271        let f = fixture();
2272        let kept = f.tenants.create(Actor::Cli, "acme", None).expect("made");
2273        let orphan = TenantId::generate();
2274        let tenants = f.tenants_dir();
2275        for name in [orphan.to_string(), "notes".to_owned()] {
2276            f.fs.create_dir_all(&tenants.join(name))
2277                .expect("a directory");
2278        }
2279        f.tenants.recover_all().expect("recovery runs");
2280        assert_eq!(
2281            f.dirs(),
2282            [OsString::from(kept.to_string()), OsString::from("notes")],
2283            "the space with no row goes; the tenant and a name not ours stay"
2284        );
2285        drop(f.store(kept));
2286    }
2287
2288    #[test]
2289    fn a_running_server_s_recovery_keeps_a_write_under_way_in_this_process() {
2290        let f = fixture();
2291        let id = f.tenants.create(Actor::Cli, "acme", None).expect("made");
2292        let store = f.tenants.store(id).expect("its store");
2293        let (arrive, arrived) = std::sync::mpsc::channel();
2294        let (go, went) = std::sync::mpsc::channel::<()>();
2295        let wait = std::time::Duration::from_secs(60);
2296        store.on_between(Box::new(move || {
2297            arrive.send(()).expect("the test waits");
2298            went.recv_timeout(wait).expect("the test says go on");
2299        }));
2300        let (found, body) =
2301            crate::store::testing::vcon("0199e5c6-0d7a-7c11-8000-0000000000a1", "under way");
2302        let who = crate::store::Caller {
2303            key: crate::ids::KeyId([3; 8]),
2304        };
2305        std::thread::scope(|s| {
2306            let writing = s.spawn(|| store.create(&who, &found, &body));
2307            arrived.recv_timeout(wait).expect("the write is under way");
2308            f.tenants.recover_all().expect("recovery runs mid-write");
2309            go.send(()).expect("the write waits");
2310            writing.join().expect("joins").expect("the write commits");
2311        });
2312        store.get(&who, found.uuid).expect("its object was kept");
2313    }
2314
2315    #[test]
2316    fn opening_removes_only_tenant_directories_with_no_row() {
2317        let mut f = fixture();
2318        let kept = f.tenants.create(Actor::Cli, "acme", None).expect("made");
2319        let orphan = TenantId::generate();
2320        let tenants = f.tenants_dir();
2321        for name in [orphan.to_string(), "notes".to_owned()] {
2322            f.fs.create_dir_all(&tenants.join(name))
2323                .expect("a directory");
2324        }
2325        f.fs.sync_dir(&tenants).expect("sync");
2326        f.restart();
2327        assert_eq!(
2328            f.dirs(),
2329            [OsString::from(kept.to_string()), OsString::from("notes")]
2330        );
2331        drop(f.store(kept));
2332    }
2333
2334    /// The server's registry opens each tenant's Store with recovery, so a
2335    /// crash's leftovers in it go once the tenant is next used.
2336    #[test]
2337    fn a_servers_registry_opens_each_store_with_recovery() {
2338        let f = fixture();
2339        let id = f.tenants.create(Actor::Cli, "acme", None).expect("made");
2340        let objects = f.tenants_dir().join(id.to_string()).join("objects");
2341        let leftover = format!("{}.tmp", VersionId([0x0e; 16]));
2342        f.fs.write_new(&objects.join(&leftover), b"x")
2343            .expect("write");
2344        let tenants = f.open().expect("opens again");
2345        drop(tenants.store(id).expect("its store"));
2346        assert!(
2347            !f.fs
2348                .list(&objects)
2349                .expect("list")
2350                .contains(&OsString::from(leftover)),
2351            "the leftover is removed"
2352        );
2353    }
2354
2355    /// A command beside a running server must not take a create or a
2356    /// write the server has in progress for a crash's leftovers, in the
2357    /// registry or in a tenant's store.
2358    #[test]
2359    fn opening_beside_a_server_removes_nothing() {
2360        let f = fixture();
2361        let kept = f.tenants.create(Actor::Cli, "acme", None).expect("made");
2362        let orphan = TenantId::generate();
2363        let tenants = f.tenants_dir();
2364        f.fs.create_dir_all(&tenants.join(orphan.to_string()))
2365            .expect("a directory");
2366        f.fs.sync_dir(&tenants).expect("sync");
2367        let in_progress = tenants
2368            .join(kept.to_string())
2369            .join("objects")
2370            .join(format!("{}.tmp", VersionId([0x0e; 16])));
2371        f.fs.write_new(&in_progress, b"x").expect("write");
2372        let beside =
2373            Tenants::open_beside(f.dir.path(), f.master.key(), f.fs.clone(), f.clock.clone())
2374                .expect("opens beside");
2375        let mut expected = [
2376            OsString::from(kept.to_string()),
2377            OsString::from(orphan.to_string()),
2378        ];
2379        expected.sort();
2380        assert_eq!(f.dirs(), expected);
2381        drop(beside.store(kept).expect("its store"));
2382        assert!(
2383            f.fs.list(in_progress.parent().expect("objects"))
2384                .expect("list")
2385                .contains(&OsString::from(in_progress.file_name().expect("name"))),
2386            "the write in progress stays"
2387        );
2388    }
2389
2390    #[test]
2391    fn an_unknown_tenant_has_no_store() {
2392        let f = fixture();
2393        assert_eq!(
2394            f.tenants.store(TenantId::generate()).err(),
2395            Some(TenantError::NotFound)
2396        );
2397    }
2398
2399    #[test]
2400    fn every_request_to_a_tenant_shares_one_store() {
2401        let f = fixture();
2402        let id = f.tenants.create(Actor::Cli, "acme", None).expect("made");
2403        let a = f.tenants.store(id).expect("a store");
2404        let b = f.tenants.store(id).expect("the same store");
2405        assert!(Arc::ptr_eq(&a, &b));
2406        let (found, body) = vcon(UUID, "first");
2407        a.create(&caller(), &found, &body).expect("stored");
2408        assert_eq!(b.get(&caller(), found.uuid).expect("read").body, body);
2409    }
2410
2411    /// The first request opens the Store; one arriving meanwhile waits for
2412    /// it rather than opening a second.
2413    #[test]
2414    fn a_store_is_opened_once_even_by_requests_at_the_same_time() {
2415        let f = fixture();
2416        let id = f.tenants.create(Actor::Cli, "acme", None).expect("made");
2417        let (opening, is_opening) = std::sync::mpsc::channel();
2418        let (go, wait) = std::sync::mpsc::channel::<()>();
2419        *f.tenants.hooks.opening.lock().expect("hook") = Some(Box::new(move || {
2420            opening.send(()).expect("send");
2421            wait.recv_timeout(std::time::Duration::from_secs(30))
2422                .expect("go");
2423        }));
2424        // Everything the threads wait on is moved into the scope, so a
2425        // failed assertion drops it and the threads end instead of hanging.
2426        let tenants = &f.tenants;
2427        std::thread::scope(move |s| {
2428            let first = s.spawn(move || tenants.store(id).expect("the first"));
2429            is_opening
2430                .recv_timeout(std::time::Duration::from_secs(10))
2431                .expect("the first is opening");
2432            let (second_done, second) = std::sync::mpsc::channel();
2433            s.spawn(move || {
2434                second_done
2435                    .send(tenants.store(id).expect("the second"))
2436                    .expect("send");
2437            });
2438            assert!(
2439                second
2440                    .recv_timeout(std::time::Duration::from_millis(100))
2441                    .is_err(),
2442                "the second waits while the first opens"
2443            );
2444            go.send(()).expect("go");
2445            let first = first.join().expect("the first returns");
2446            let second = second
2447                .recv_timeout(std::time::Duration::from_secs(30))
2448                .expect("the second returns");
2449            assert!(Arc::ptr_eq(&first, &second));
2450        });
2451    }
2452
2453    #[test]
2454    fn a_tenant_key_that_does_not_unwrap_opens_no_store() {
2455        let f = fixture();
2456        let id = f.tenants.create(Actor::Cli, "acme", None).expect("made");
2457        f.conn()
2458            .execute(
2459                "UPDATE tenant SET wrapped_tenant_key = x'00' WHERE id = ?1",
2460                [id.0],
2461            )
2462            .expect("damage the wrapped key");
2463        assert_eq!(f.tenants.store(id).err(), Some(TenantError::Io));
2464    }
2465
2466    #[test]
2467    fn draining_refuses_new_requests_and_waits_for_those_in_flight() {
2468        let f = fixture();
2469        let id = f.tenants.create(Actor::Cli, "acme", None).expect("made");
2470        let (found, body) = vcon(UUID, "first");
2471        let held = f.tenants.store(id).expect("a request in flight");
2472        std::thread::scope(|s| {
2473            let (done, drained) = std::sync::mpsc::channel();
2474            let tenants = &f.tenants;
2475            s.spawn(move || {
2476                tenants.drain(id).expect("drains");
2477                done.send(()).expect("send");
2478            });
2479            let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
2480            while f.tenants.store(id).is_ok() {
2481                assert!(std::time::Instant::now() < deadline, "never closing");
2482                std::thread::yield_now();
2483            }
2484            assert_eq!(f.tenants.store(id).err(), Some(TenantError::Closing));
2485            assert!(
2486                drained
2487                    .recv_timeout(std::time::Duration::from_millis(100))
2488                    .is_err(),
2489                "the drain waits for the request in flight"
2490            );
2491            held.create(&caller(), &found, &body)
2492                .expect("the request in flight finishes");
2493            drop(held);
2494            drained
2495                .recv_timeout(std::time::Duration::from_secs(30))
2496                .expect("the drain ends once the last handle is dropped");
2497        });
2498        assert_eq!(f.tenants.store(id).err(), Some(TenantError::Closing));
2499    }
2500
2501    #[test]
2502    fn a_tenant_no_request_opened_drains_at_once() {
2503        let f = fixture();
2504        let id = f.tenants.create(Actor::Cli, "acme", None).expect("made");
2505        f.tenants.drain(id).expect("drains");
2506        assert_eq!(f.tenants.store(id).err(), Some(TenantError::Closing));
2507    }
2508
2509    impl Fixture {
2510        /// The tenant's own retention period, as its row holds it.
2511        fn own_retention(&self, id: TenantId) -> Option<String> {
2512            self.conn()
2513                .query_row("SELECT retention FROM tenant WHERE id = ?1", [id.0], |r| {
2514                    r.get(0)
2515                })
2516                .expect("a row")
2517        }
2518
2519        /// A second connection to the tenant's catalog.
2520        pub(crate) fn tenant_catalog(&self, id: TenantId) -> Connection {
2521            let catalog_key = envelope::catalog_key(&self.tenant_key(id)).expect("catalog key");
2522            catalog::open(
2523                &self
2524                    .tenants_dir()
2525                    .join(id.to_string())
2526                    .join("catalog.sqlite"),
2527                &catalog_key,
2528                "",
2529            )
2530            .expect("the tenant's catalog")
2531        }
2532
2533        /// The records with this action in the admin log.
2534        pub(crate) fn admin_records(&self, action: &str) -> Vec<Value> {
2535            self.admin_log()
2536                .into_iter()
2537                .filter(|r| r["action"] == action)
2538                .collect()
2539        }
2540    }
2541
2542    /// The rule the sweep and `check` both apply.
2543    #[test]
2544    fn retention_falls_back_to_the_server_default_when_unset() {
2545        let info = |retention| TenantInfo {
2546            id: TenantId([1; 16]),
2547            name: "acme".to_owned(),
2548            retention,
2549            metadata: Metadata::None,
2550            created_at: datetime!(2026-10-23 12:00 UTC),
2551        };
2552        assert_eq!(
2553            info(None).kept_for(Retention::Years(7)),
2554            Retention::Years(7)
2555        );
2556        assert_eq!(
2557            info(Some(Retention::Days(90))).kept_for(Retention::Years(7)),
2558            Retention::Days(90)
2559        );
2560    }
2561
2562    #[test]
2563    fn a_tenant_retention_is_read_afresh_and_not_recorded() {
2564        let f = fixture();
2565        let lab = f
2566            .tenants
2567            .create(Actor::Cli, "lab", Some(Retention::Months(18)))
2568            .expect("made");
2569        let acme = f.tenants.create(Actor::Cli, "acme", None).expect("made");
2570        let records = f.tenants.admin_records().len();
2571
2572        assert_eq!(f.tenants.retention(lab), Ok(Some(Retention::Months(18))));
2573        assert_eq!(f.tenants.retention(acme), Ok(None));
2574        f.tenants
2575            .set_retention(Actor::Cli, acme, Some(Retention::Days(0)))
2576            .expect("changed");
2577        assert_eq!(f.tenants.retention(acme), Ok(Some(Retention::Days(0))));
2578        assert_eq!(
2579            f.tenants.retention(TenantId([0xee; 16])),
2580            Err(TenantError::NotFound)
2581        );
2582        assert_eq!(
2583            f.tenants.admin_records().len(),
2584            records + 1,
2585            "only the retention change is recorded"
2586        );
2587        f.tenants
2588            .conn_for_test()
2589            .execute("UPDATE tenant SET retention = '7w' WHERE id = ?1", [lab.0])
2590            .expect("damaged");
2591        assert_eq!(
2592            f.tenants.retention(lab),
2593            Err(TenantError::Io),
2594            "a period that does not read back is damage"
2595        );
2596    }
2597
2598    #[test]
2599    fn ids_names_every_tenant_and_records_nothing() {
2600        let f = fixture();
2601        let a = f.tenants.create(Actor::Cli, "a", None).expect("made");
2602        let b = f.tenants.create(Actor::Cli, "b", None).expect("made");
2603        let records = f.tenants.admin_records().len();
2604
2605        let mut ids = f.tenants.ids().expect("ids");
2606        ids.sort_by_key(|id| id.0);
2607        let mut made = vec![a, b];
2608        made.sort_by_key(|id| id.0);
2609
2610        assert_eq!(ids, made);
2611        assert_eq!(f.tenants.admin_records().len(), records, "nothing recorded");
2612    }
2613
2614    #[test]
2615    fn list_shows_every_tenant_by_name_and_is_recorded() {
2616        let f = fixture();
2617        assert_eq!(f.tenants.list(Actor::Cli), Ok(Vec::new()));
2618        let lab = f
2619            .tenants
2620            .create(Actor::Cli, "lab", Some(Retention::Days(90)))
2621            .expect("made");
2622        f.clock.set(datetime!(2026-10-23 13:00 UTC));
2623        let acme = f.tenants.create(Actor::Cli, "acme", None).expect("made");
2624        assert_eq!(
2625            f.tenants.list(Actor::Cli),
2626            Ok(vec![
2627                TenantInfo {
2628                    id: acme,
2629                    name: "acme".to_owned(),
2630                    retention: None,
2631                    metadata: Metadata::None,
2632                    created_at: datetime!(2026-10-23 13:00 UTC),
2633                },
2634                TenantInfo {
2635                    id: lab,
2636                    name: "lab".to_owned(),
2637                    retention: Some(Retention::Days(90)),
2638                    metadata: Metadata::None,
2639                    created_at: datetime!(2026-10-23 12:00 UTC),
2640                },
2641            ])
2642        );
2643        let lists = f.admin_records("tenant_list");
2644        assert_eq!(lists.len(), 2, "one record per list");
2645        for record in lists {
2646            assert_eq!(record["actor"], "cli");
2647            assert_eq!(record["status"], 200);
2648            assert_eq!(record["target"], Value::Null);
2649        }
2650    }
2651
2652    #[test]
2653    fn a_stored_period_that_does_not_read_back_is_damage() {
2654        let f = fixture();
2655        let id = f.tenants.create(Actor::Cli, "acme", None).expect("made");
2656        f.conn()
2657            .execute("UPDATE tenant SET retention = '7w' WHERE id = ?1", [id.0])
2658            .expect("damage the period");
2659        assert_eq!(f.tenants.list(Actor::Cli), Err(TenantError::Io));
2660    }
2661
2662    #[test]
2663    fn a_list_whose_record_fails_shows_nothing() {
2664        let f = fixture();
2665        f.tenants.create(Actor::Cli, "acme", None).expect("made");
2666        f.conn()
2667            .execute_batch(
2668                "CREATE TEMP TRIGGER no_audit BEFORE INSERT ON audit
2669                 BEGIN SELECT RAISE(ABORT, 'no audit'); END;",
2670            )
2671            .expect("trigger");
2672        assert_eq!(f.tenants.list(Actor::Cli), Err(TenantError::AuditFailed));
2673    }
2674
2675    #[test]
2676    fn a_retention_change_is_kept_and_recorded_in_both_logs() {
2677        let f = fixture();
2678        let id = f.tenants.create(Actor::Cli, "acme", None).expect("made");
2679        f.clock.set(datetime!(2026-10-23 13:00 UTC));
2680        f.tenants
2681            .set_retention(Actor::Cli, id, Some(Retention::Months(18)))
2682            .expect("set");
2683        assert_eq!(f.own_retention(id).as_deref(), Some("18m"));
2684        f.tenants
2685            .set_retention(Actor::Cli, id, None)
2686            .expect("back to the default");
2687        assert_eq!(f.own_retention(id), None);
2688
2689        let admin = f.admin_records("tenant_retention");
2690        assert_eq!(admin.len(), 2);
2691        for record in &admin {
2692            assert_eq!(record["actor"], "cli");
2693            assert_eq!(record["target"], id.to_string());
2694            assert_eq!(record["status"], 200);
2695            assert_eq!(record["at"], "2026-10-23T13:00:00Z");
2696        }
2697        let copies: Vec<Value> = exported(&f.tenant_catalog(id), None)
2698            .into_iter()
2699            .filter(|r| r["action"] == "retention")
2700            .collect();
2701        assert_eq!(copies.len(), 2, "a copy in the tenant's log for each");
2702        for record in &copies {
2703            assert_eq!(record["actor"], "cli");
2704            assert_eq!(record["target"], id.to_string());
2705            assert_eq!(record["status"], 200);
2706        }
2707    }
2708
2709    impl Fixture {
2710        /// The tenant's metadata level, as its row holds it.
2711        fn own_metadata(&self, id: TenantId) -> Option<String> {
2712            self.conn()
2713                .query_row("SELECT metadata FROM tenant WHERE id = ?1", [id.0], |r| {
2714                    r.get(0)
2715                })
2716                .expect("a row")
2717        }
2718    }
2719
2720    /// A tenant's level is `none` until set; a change is kept, shown in
2721    /// the list, and recorded in the admin log and the tenant's own.
2722    #[test]
2723    fn a_metadata_level_is_none_until_set_and_each_change_is_recorded() {
2724        let f = fixture();
2725        let id = f.tenants.create(Actor::Cli, "acme", None).expect("made");
2726        assert_eq!(
2727            f.tenants.metadata(id),
2728            Ok(Metadata::None),
2729            "a new tenant is at none"
2730        );
2731        assert_eq!(f.own_metadata(id), None, "NULL is none");
2732        f.clock.set(datetime!(2026-10-23 13:00 UTC));
2733        f.tenants
2734            .set_metadata(Actor::Cli, id, Metadata::Full)
2735            .expect("set");
2736        assert_eq!(f.tenants.metadata(id), Ok(Metadata::Full), "the level set");
2737        assert_eq!(
2738            f.own_metadata(id).as_deref(),
2739            Some("full"),
2740            "the row holds the level's name"
2741        );
2742        let listed = f.tenants.list(Actor::Cli).expect("lists");
2743        assert_eq!(listed[0].to_json()["metadata"], "full", "shown in the list");
2744        f.tenants
2745            .set_metadata(Actor::Cli, id, Metadata::None)
2746            .expect("back to none");
2747        assert_eq!(f.own_metadata(id), None, "none is NULL again");
2748        assert_eq!(f.tenants.metadata(id), Ok(Metadata::None), "back to none");
2749
2750        let admin = f.admin_records("tenant_metadata");
2751        assert_eq!(admin.len(), 2, "one admin record per change");
2752        for record in &admin {
2753            assert_eq!(record["actor"], "cli", "the command line made the change");
2754            assert_eq!(
2755                record["target"],
2756                id.to_string(),
2757                "the record names the tenant"
2758            );
2759            assert_eq!(record["status"], 200, "the change succeeded");
2760            assert_eq!(record["at"], "2026-10-23T13:00:00Z", "at the clock's time");
2761        }
2762        let copies: Vec<Value> = exported(&f.tenant_catalog(id), None)
2763            .into_iter()
2764            .filter(|r| r["action"] == "metadata")
2765            .collect();
2766        assert_eq!(copies.len(), 2, "a copy in the tenant's log for each");
2767    }
2768
2769    #[test]
2770    fn a_metadata_change_for_an_unknown_or_closing_tenant_is_refused() {
2771        let f = fixture();
2772        let unknown = TenantId::generate();
2773        assert_eq!(
2774            f.tenants
2775                .set_metadata(Actor::Cli, unknown, Metadata::Counts),
2776            Err(TenantError::NotFound),
2777            "no tenant has the id"
2778        );
2779        assert_eq!(
2780            f.tenants.metadata(unknown),
2781            Err(TenantError::NotFound),
2782            "nor a level"
2783        );
2784        let id = f.tenants.create(Actor::Cli, "acme", None).expect("made");
2785        f.tenants.drain(id).expect("drains");
2786        assert_eq!(
2787            f.tenants.set_metadata(Actor::Cli, id, Metadata::Counts),
2788            Err(TenantError::Closing),
2789            "a closing tenant's level does not change"
2790        );
2791        assert_eq!(f.own_metadata(id), None, "unchanged");
2792        let statuses: Vec<Value> = f
2793            .admin_records("tenant_metadata")
2794            .iter()
2795            .map(|r| r["status"].clone())
2796            .collect();
2797        assert_eq!(
2798            statuses,
2799            [404, 503],
2800            "both refusals are recorded, each with its status"
2801        );
2802    }
2803
2804    /// A level this build does not know is damage, never taken as `none`.
2805    #[test]
2806    fn a_stored_metadata_level_this_build_does_not_know_is_an_error() {
2807        let f = fixture();
2808        let id = f.tenants.create(Actor::Cli, "acme", None).expect("made");
2809        f.conn()
2810            .execute("UPDATE tenant SET metadata = 'most' WHERE id = ?1", [id.0])
2811            .expect("update");
2812        assert_eq!(
2813            f.tenants.metadata(id),
2814            Err(TenantError::Io),
2815            "an unknown level is an error"
2816        );
2817    }
2818
2819    /// A registry made at schema version 2 gains the column at version 3,
2820    /// every tenant at `none`; one made at version 1 does too.
2821    #[test]
2822    fn an_older_registry_gains_the_metadata_column() {
2823        for from in [1, 2] {
2824            let mut f = fixture();
2825            let id = f.tenants.create(Actor::Cli, "acme", None).expect("made");
2826            f.conn()
2827                .execute_batch(&format!(
2828                    "ALTER TABLE tenant DROP COLUMN role_cap;
2829                     ALTER TABLE tenant DROP COLUMN metadata; DROP TABLE membership;
2830                     DROP TABLE user_account; DROP TABLE tenant_setting;
2831                     DROP TABLE session;
2832                     ALTER TABLE api_key DROP COLUMN last_used_at;
2833                     ALTER TABLE api_key DROP COLUMN expires_at;
2834                     PRAGMA user_version = {from};"
2835                ))
2836                .expect("back to the old schema");
2837            f.restart();
2838            let version: i64 = f
2839                .conn()
2840                .pragma_query_value(None, "user_version", |r| r.get(0))
2841                .expect("version");
2842            assert_eq!(version, catalog::SCHEMA_VERSION, "from {from}");
2843            assert_eq!(f.tenants.metadata(id), Ok(Metadata::None), "from {from}");
2844            f.tenants
2845                .set_metadata(Actor::Cli, id, Metadata::Counts)
2846                .expect("the column is there");
2847        }
2848    }
2849
2850    #[test]
2851    fn a_retention_change_for_an_unknown_tenant_is_not_found() {
2852        let f = fixture();
2853        let id = TenantId::generate();
2854        assert_eq!(
2855            f.tenants
2856                .set_retention(Actor::Cli, id, Some(Retention::Years(1))),
2857            Err(TenantError::NotFound)
2858        );
2859        let admin = f.admin_records("tenant_retention");
2860        assert_eq!(admin.len(), 1);
2861        assert_eq!(admin[0]["status"], 404);
2862        assert_eq!(admin[0]["target"], id.to_string());
2863    }
2864
2865    #[test]
2866    fn a_retention_change_for_a_closing_tenant_is_refused() {
2867        let f = fixture();
2868        let id = f.tenants.create(Actor::Cli, "acme", None).expect("made");
2869        f.tenants.drain(id).expect("drains");
2870        assert_eq!(
2871            f.tenants
2872                .set_retention(Actor::Cli, id, Some(Retention::Years(1))),
2873            Err(TenantError::Closing)
2874        );
2875        assert_eq!(f.own_retention(id), None, "unchanged");
2876        assert_eq!(f.admin_records("tenant_retention")[0]["status"], 503);
2877    }
2878
2879    #[test]
2880    fn a_retention_change_whose_admin_record_fails_changes_nothing() {
2881        let f = fixture();
2882        let id = f.tenants.create(Actor::Cli, "acme", None).expect("made");
2883        f.conn()
2884            .execute_batch(
2885                "CREATE TEMP TRIGGER no_audit BEFORE INSERT ON audit
2886                 BEGIN SELECT RAISE(ABORT, 'no audit'); END;",
2887            )
2888            .expect("trigger");
2889        assert_eq!(
2890            f.tenants
2891                .set_retention(Actor::Cli, id, Some(Retention::Years(1))),
2892            Err(TenantError::AuditFailed)
2893        );
2894        assert_eq!(f.own_retention(id), None, "unchanged");
2895        let copies = exported(&f.tenant_catalog(id), None)
2896            .into_iter()
2897            .filter(|r| r["action"] == "retention")
2898            .count();
2899        assert_eq!(copies, 0, "no copy of a change that was not made");
2900    }
2901
2902    /// The change commits with its admin record; a failed copy in the
2903    /// tenant's log leaves the change standing and answers AuditFailed.
2904    #[test]
2905    fn a_retention_change_whose_tenant_copy_fails_stands() {
2906        let f = fixture();
2907        let id = f.tenants.create(Actor::Cli, "acme", None).expect("made");
2908        f.tenant_catalog(id)
2909            .execute_batch(
2910                "CREATE TRIGGER dead BEFORE INSERT ON audit
2911                 BEGIN SELECT RAISE(ABORT, 'no audit'); END;",
2912            )
2913            .expect("trigger");
2914        assert_eq!(
2915            f.tenants
2916                .set_retention(Actor::Cli, id, Some(Retention::Years(10))),
2917            Err(TenantError::AuditFailed)
2918        );
2919        assert_eq!(
2920            f.own_retention(id).as_deref(),
2921            Some("10y"),
2922            "the change stands"
2923        );
2924        assert_eq!(f.admin_records("tenant_retention")[0]["status"], 200);
2925    }
2926
2927    /// A tenant with one vCon stored.
2928    fn with_vcon(f: &Fixture) -> TenantId {
2929        let id = f.tenants.create(Actor::Cli, "acme", None).expect("made");
2930        let (found, body) = vcon(UUID, "first");
2931        f.tenants
2932            .store(id)
2933            .expect("its store")
2934            .create(&caller(), &found, &body)
2935            .expect("stored");
2936        id
2937    }
2938
2939    fn hold(f: &Fixture, id: TenantId) {
2940        f.tenant_catalog(id)
2941            .execute("UPDATE vcon SET hold = 1", [])
2942            .expect("a hold");
2943    }
2944
2945    /// Waits until the tenant refuses new requests.
2946    fn until_closing(f: &Fixture, id: TenantId) {
2947        let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
2948        while f.tenants.store(id).is_ok() {
2949            assert!(std::time::Instant::now() < deadline, "never closing");
2950            std::thread::yield_now();
2951        }
2952    }
2953
2954    #[test]
2955    fn a_tenant_already_closing_cannot_be_drained_again() {
2956        let f = fixture();
2957        let id = f.tenants.create(Actor::Cli, "acme", None).expect("made");
2958        f.tenants.drain(id).expect("drains");
2959        assert_eq!(f.tenants.drain(id).err(), Some(TenantError::Closing));
2960    }
2961
2962    #[test]
2963    fn removing_an_unknown_tenant_is_not_found() {
2964        let f = fixture();
2965        let id = TenantId::generate();
2966        assert_eq!(
2967            f.tenants.remove(Actor::Cli, id, Removal::Empty),
2968            Err(TenantError::NotFound)
2969        );
2970        assert_eq!(f.tenants.store(id).err(), Some(TenantError::NotFound));
2971        let records = f.admin_records("tenant_remove");
2972        assert_eq!(records.len(), 1);
2973        assert_eq!(records[0]["status"], 404);
2974        assert_eq!(records[0]["target"], id.to_string());
2975    }
2976
2977    #[test]
2978    fn an_empty_tenant_is_removed_with_its_key_directory_and_row() {
2979        let f = fixture();
2980        let id = f.tenants.create(Actor::Cli, "acme", None).expect("made");
2981        drop(f.tenants.store(id).expect("opened by a request"));
2982        f.clock.set(datetime!(2026-10-23 13:00 UTC));
2983        f.tenants
2984            .remove(Actor::Cli, id, Removal::Empty)
2985            .expect("removed");
2986        assert!(!f.has_row(id), "its row and wrapped key are gone");
2987        assert_eq!(f.tenants.store(id).err(), Some(TenantError::NotFound));
2988        assert_eq!(f.dirs(), Vec::<OsString>::new(), "its directory is gone");
2989        assert_eq!(f.tenants.list(Actor::Cli), Ok(Vec::new()));
2990        let records = f.admin_records("tenant_remove");
2991        assert_eq!(records.len(), 1);
2992        assert_eq!(records[0]["actor"], "cli");
2993        assert_eq!(records[0]["target"], id.to_string());
2994        assert_eq!(records[0]["status"], 204);
2995        assert_eq!(records[0]["at"], "2026-10-23T13:00:00Z");
2996    }
2997
2998    #[test]
2999    fn an_empty_removal_is_refused_while_any_version_is_kept() {
3000        let f = fixture();
3001        let id = with_vcon(&f);
3002        let uuid = vcon(UUID, "first").0.uuid;
3003        f.tenants
3004            .store(id)
3005            .expect("its store")
3006            .delete(&caller(), uuid, Retention::Years(7))
3007            .expect("deleted, so only a hidden version is kept");
3008        assert_eq!(
3009            f.tenants.remove(Actor::Cli, id, Removal::Empty),
3010            Err(TenantError::HoldsVcons)
3011        );
3012        assert!(f.has_row(id));
3013        let store = f.tenants.store(id).expect("still served");
3014        assert_eq!(store.counts().map(|c| c.versions), Ok(1));
3015        assert_eq!(f.admin_records("tenant_remove")[0]["status"], 409);
3016    }
3017
3018    #[test]
3019    fn a_forced_removal_takes_the_vcons_too() {
3020        let f = fixture();
3021        let id = with_vcon(&f);
3022        f.tenants
3023            .remove(Actor::Cli, id, Removal::Force)
3024            .expect("removed");
3025        assert!(!f.has_row(id));
3026        assert_eq!(f.dirs(), Vec::<OsString>::new());
3027    }
3028
3029    #[test]
3030    fn a_forced_removal_is_refused_while_a_uuid_is_held() {
3031        let f = fixture();
3032        let id = with_vcon(&f);
3033        hold(&f, id);
3034        assert_eq!(
3035            f.tenants.remove(Actor::Cli, id, Removal::Force),
3036            Err(TenantError::UnderHold)
3037        );
3038        assert!(f.has_row(id));
3039        assert!(f.tenants.store(id).is_ok(), "still served");
3040        assert_eq!(f.admin_records("tenant_remove")[0]["status"], 409);
3041    }
3042
3043    #[test]
3044    fn overriding_holds_removes_a_held_tenant() {
3045        let f = fixture();
3046        let id = with_vcon(&f);
3047        hold(&f, id);
3048        f.tenants
3049            .remove(Actor::Cli, id, Removal::ForceOverridingHolds)
3050            .expect("removed");
3051        assert!(!f.has_row(id));
3052        assert_eq!(f.dirs(), Vec::<OsString>::new());
3053    }
3054
3055    /// The removal drains before it looks, so a write that lands meanwhile
3056    /// makes the tenant non-empty and the removal is refused: the write
3057    /// is never acknowledged and then lost.
3058    #[test]
3059    fn a_write_in_flight_during_an_empty_removal_is_kept() {
3060        let f = fixture();
3061        let id = f.tenants.create(Actor::Cli, "acme", None).expect("made");
3062        let (found, body) = vcon(UUID, "first");
3063        let held = f.tenants.store(id).expect("a request in flight");
3064        let tenants = &f.tenants;
3065        let fx = &f;
3066        let (found_ref, body_ref) = (&found, &body);
3067        let result = std::thread::scope(move |s| {
3068            let (done, removed) = std::sync::mpsc::channel();
3069            s.spawn(move || {
3070                done.send(tenants.remove(Actor::Cli, id, Removal::Empty))
3071                    .expect("send");
3072            });
3073            until_closing(fx, id);
3074            assert!(
3075                removed
3076                    .recv_timeout(std::time::Duration::from_millis(100))
3077                    .is_err(),
3078                "the removal waits for the write"
3079            );
3080            held.create(&caller(), found_ref, body_ref)
3081                .expect("the write is acknowledged");
3082            drop(held);
3083            removed
3084                .recv_timeout(std::time::Duration::from_secs(30))
3085                .expect("the removal ends")
3086        });
3087        assert_eq!(result, Err(TenantError::HoldsVcons));
3088        assert_eq!(
3089            f.tenants
3090                .store(id)
3091                .expect("still served")
3092                .get(&caller(), found.uuid)
3093                .expect("the write is kept")
3094                .body,
3095            body
3096        );
3097    }
3098
3099    #[test]
3100    fn a_second_removal_while_one_drains_is_refused() {
3101        let f = fixture();
3102        let id = f.tenants.create(Actor::Cli, "acme", None).expect("made");
3103        let held = f.tenants.store(id).expect("a request in flight");
3104        let tenants = &f.tenants;
3105        let fx = &f;
3106        std::thread::scope(move |s| {
3107            let first = s.spawn(move || tenants.remove(Actor::Cli, id, Removal::Force));
3108            until_closing(fx, id);
3109            assert_eq!(
3110                fx.tenants.remove(Actor::Cli, id, Removal::Empty),
3111                Err(TenantError::Closing)
3112            );
3113            drop(held);
3114            assert_eq!(first.join().expect("the first returns"), Ok(()));
3115        });
3116        let statuses: Vec<Value> = f
3117            .admin_records("tenant_remove")
3118            .into_iter()
3119            .map(|r| r["status"].clone())
3120            .collect();
3121        assert_eq!(statuses, [503, 204]);
3122    }
3123
3124    #[test]
3125    fn a_removal_whose_record_fails_removes_nothing() {
3126        let f = fixture();
3127        let id = f.tenants.create(Actor::Cli, "acme", None).expect("made");
3128        f.conn()
3129            .execute_batch(
3130                "CREATE TEMP TRIGGER no_audit BEFORE INSERT ON audit
3131                 BEGIN SELECT RAISE(ABORT, 'no audit'); END;",
3132            )
3133            .expect("trigger");
3134        assert_eq!(
3135            f.tenants.remove(Actor::Cli, id, Removal::Empty),
3136            Err(TenantError::AuditFailed)
3137        );
3138        assert!(f.has_row(id));
3139        assert_eq!(f.dirs().len(), 1);
3140        assert!(f.tenants.store(id).is_ok(), "served again");
3141    }
3142
3143    /// The row's commit is the removal; a directory a crash leaves after
3144    /// it goes at the next start.
3145    #[test]
3146    fn a_removal_cut_off_after_its_commit_finishes_at_the_next_start() {
3147        let mut f = fixture();
3148        let id = f.tenants.create(Actor::Cli, "acme", None).expect("made");
3149        drop(f.tenants.store(id).expect("opened by a request"));
3150        f.fs.fail_from(f.fs.log().len());
3151        assert_eq!(f.tenants.remove(Actor::Cli, id, Removal::Empty), Ok(()));
3152        assert_eq!(f.dirs().len(), 1, "the dead process removed nothing");
3153        f.restart();
3154        assert!(!f.has_row(id));
3155        assert_eq!(f.dirs(), Vec::<OsString>::new());
3156    }
3157
3158    #[test]
3159    fn removal_deletes_the_directory_on_disk() {
3160        let dir = tempfile::tempdir().expect("temp dir");
3161        let tenants = Tenants::open(
3162            dir.path(),
3163            Master::new().key(),
3164            Arc::new(crate::fs::OsFs),
3165            Arc::new(ManualClock::at(datetime!(2026-10-23 12:00 UTC))),
3166        )
3167        .expect("opens");
3168        let id = tenants.create(Actor::Cli, "acme", None).expect("made");
3169        let tenant_dir = dir.path().join("tenants").join(id.to_string());
3170        assert!(tenant_dir.join("catalog.sqlite").is_file());
3171        tenants
3172            .remove(Actor::Cli, id, Removal::Empty)
3173            .expect("removed");
3174        assert!(!tenant_dir.exists());
3175    }
3176
3177    #[test]
3178    fn two_tenants_keep_the_same_uuid_apart() {
3179        let f = fixture();
3180        let a = f.tenants.create(Actor::Cli, "a", None).expect("made");
3181        let b = f.tenants.create(Actor::Cli, "b", None).expect("made");
3182        let (found, kept_by_a) = vcon(UUID, "kept by a");
3183        let (_, kept_by_b) = vcon(UUID, "kept by b");
3184        let (store_a, store_b) = (
3185            f.tenants.store(a).expect("a's store"),
3186            f.tenants.store(b).expect("b's store"),
3187        );
3188        assert!(matches!(
3189            store_a.create(&caller(), &found, &kept_by_a),
3190            Ok(Created::New(_))
3191        ));
3192        assert!(matches!(
3193            store_b.create(&caller(), &found, &kept_by_b),
3194            Ok(Created::New(_))
3195        ));
3196        let read = |store: &Store| store.get(&caller(), found.uuid).map(|s| s.body);
3197        assert_eq!(read(&store_a), Ok(kept_by_a));
3198        assert_eq!(read(&store_b), Ok(kept_by_b.clone()));
3199        store_a
3200            .delete(&caller(), found.uuid, Retention::Years(7))
3201            .expect("a deletes its own");
3202        assert_eq!(read(&store_a), Err(StoreError::Gone));
3203        assert_eq!(read(&store_b), Ok(kept_by_b), "b's is untouched");
3204    }
3205
3206    /// A version's data key is wrapped for its tenant by id, so the
3207    /// tenant's Store must be opened under that id.
3208    #[test]
3209    fn a_tenants_data_keys_are_bound_to_its_own_id() {
3210        let f = fixture();
3211        let id = f.tenants.create(Actor::Cli, "acme", None).expect("made");
3212        let (found, body) = vcon(UUID, "first");
3213        let Ok(Created::New(version)) =
3214            f.tenants
3215                .store(id)
3216                .expect("its store")
3217                .create(&caller(), &found, &body)
3218        else {
3219            panic!("a new vCon")
3220        };
3221        let wrapped: Vec<u8> = f
3222            .tenant_catalog(id)
3223            .query_row(
3224                "SELECT wrapped_key FROM version WHERE version = ?1",
3225                [version.0],
3226                |r| r.get(0),
3227            )
3228            .expect("its row");
3229        let ctx = Context::Version {
3230            tenant: id,
3231            uuid: found.uuid,
3232            version,
3233        };
3234        assert!(envelope::unwrap(&f.tenant_key(id), &ctx, &wrapped).is_ok());
3235    }
3236
3237    /// The answers one tenant gets for a uuid, whatever another holds.
3238    fn answers(store: &Store) -> Vec<String> {
3239        let (found, body) = vcon(UUID, "b's own");
3240        let (_, newer) = vcon(UUID, "b's newer");
3241        let kind = |r: Result<Created, StoreError>| match r {
3242            Ok(Created::New(_)) => "new".to_owned(),
3243            Ok(Created::Same(_)) => "same".to_owned(),
3244            Err(e) => format!("{e:?}"),
3245        };
3246        let who = caller();
3247        let mut answers = vec![
3248            format!("{:?}", store.get(&who, found.uuid).map(|_| ())),
3249            format!("{:?}", store.delete(&who, found.uuid, Retention::Years(7))),
3250            kind(store.create(&who, &found, &body)),
3251            kind(store.create(&who, &found, &body)),
3252        ];
3253        let current = store.get(&who, found.uuid).expect("stored").version;
3254        answers.push(format!(
3255            "{:?}",
3256            store.replace(&who, current, &found, &newer).map(|_| ())
3257        ));
3258        answers.push(format!(
3259            "{:?}",
3260            store.delete(&who, found.uuid, Retention::Years(7))
3261        ));
3262        answers.push(format!("{:?}", store.get(&who, found.uuid).map(|_| ())));
3263        answers
3264    }
3265
3266    #[test]
3267    fn nothing_one_tenant_does_shows_whether_another_holds_a_uuid() {
3268        let alone = fixture();
3269        let b = alone.tenants.create(Actor::Cli, "b", None).expect("made");
3270        let expected = answers(&alone.tenants.store(b).expect("b's store"));
3271
3272        let f = fixture();
3273        let a = f.tenants.create(Actor::Cli, "a", None).expect("made");
3274        let b = f.tenants.create(Actor::Cli, "b", None).expect("made");
3275        let store_a = f.tenants.store(a).expect("a's store");
3276        let (found, body) = vcon(UUID, "a's");
3277        store_a
3278            .create(&caller(), &found, &body)
3279            .expect("a holds it");
3280        let (other, body) = vcon("01a07da8-c2bb-83e5-b9a2-279e0d16bc47", "a's other");
3281        store_a.create(&caller(), &other, &body).expect("stored");
3282        store_a
3283            .delete(&caller(), other.uuid, Retention::Years(7))
3284            .expect("and has deleted another");
3285        assert_eq!(answers(&f.tenants.store(b).expect("b's store")), expected);
3286        assert_eq!(
3287            expected,
3288            [
3289                "Err(NotFound)",
3290                "Err(NotFound)",
3291                "new",
3292                "same",
3293                "Ok(())",
3294                "Ok(())",
3295                "Err(Gone)"
3296            ]
3297        );
3298    }
3299}