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