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; the new catalog's WAL and then the tenant's directory
1740    /// synced when the catalog opens; its objects directory and the sync of
1741    /// the tenant's directory; start-up recovery's commit synced; the sync
1742    /// of `tenants/`. The row's commit follows them.
1743    const CREATE_STEPS: usize = 7;
1744
1745    #[test]
1746    fn a_create_writes_its_directories_in_order() {
1747        let f = fixture();
1748        let ops = f.fs.log().len();
1749        let id = f.tenants.create(Actor::Cli, "acme", None).expect("made");
1750        let dir = f.tenants_dir().join(id.to_string());
1751        let wal = dir.join("catalog.sqlite-wal");
1752        assert_eq!(
1753            f.fs.log()[ops..],
1754            [
1755                Op::CreateDir(dir.clone()),
1756                Op::SyncData(wal.clone()),
1757                Op::SyncDir(dir.clone()),
1758                Op::CreateDir(dir.join("objects")),
1759                Op::SyncDir(dir),
1760                Op::SyncData(wal),
1761                Op::SyncDir(f.tenants_dir()),
1762            ],
1763            "the WAL is synced, then its directory, before anything else is made"
1764        );
1765        assert_eq!(
1766            f.fs.log().len() - ops,
1767            CREATE_STEPS,
1768            "the steps a cut can hit"
1769        );
1770    }
1771
1772    #[test]
1773    fn a_create_cut_off_at_any_step_leaves_a_whole_tenant_or_none() {
1774        let uncut = {
1775            let f = fixture();
1776            let ops = f.fs.log().len();
1777            f.tenants.create(Actor::Cli, "acme", None).expect("made");
1778            f.fs.log()[ops..].to_vec()
1779        };
1780        assert_eq!(
1781            uncut.len(),
1782            CREATE_STEPS,
1783            "every step of a create: {uncut:?}"
1784        );
1785        for step in 0..=CREATE_STEPS {
1786            let mut f = fixture();
1787            f.fs.fail_from(f.fs.log().len() + step);
1788            let result = f.tenants.create(Actor::Cli, "acme", None);
1789            assert_eq!(
1790                result.is_ok(),
1791                step == CREATE_STEPS,
1792                "step {step}: {result:?}"
1793            );
1794            f.restart();
1795            match result {
1796                Ok(id) => {
1797                    assert!(f.has_row(id), "step {step}");
1798                    assert_eq!(f.dirs(), [OsString::from(id.to_string())]);
1799                    let store = f.store(id);
1800                    drop(store);
1801                }
1802                Err(_) => {
1803                    assert_eq!(f.count("SELECT count(*) FROM tenant"), 0, "step {step}");
1804                    assert_eq!(f.dirs(), Vec::<OsString>::new(), "step {step}");
1805                }
1806            }
1807        }
1808    }
1809
1810    #[test]
1811    fn a_create_cut_off_before_its_commit_leaves_no_tenant() {
1812        let mut f = fixture();
1813        let other = f.other();
1814        let fs = f.fs.clone();
1815        *f.tenants.hooks.between.lock().expect("hook") = Some(Box::new(move || {
1816            fs.fail_from(0);
1817            other
1818                .execute_batch(
1819                    "CREATE TRIGGER dead BEFORE INSERT ON audit
1820                     BEGIN SELECT RAISE(ABORT, 'the process has died'); END;",
1821                )
1822                .expect("trigger");
1823        }));
1824        assert!(f.tenants.create(Actor::Cli, "acme", None).is_err());
1825        assert_eq!(f.dirs().len(), 1, "the dead process removed nothing");
1826        f.conn()
1827            .execute_batch("DROP TRIGGER dead")
1828            .expect("drop trigger");
1829        f.restart();
1830        assert_eq!(f.count("SELECT count(*) FROM tenant"), 0);
1831        assert_eq!(f.dirs(), Vec::<OsString>::new(), "removed at start");
1832    }
1833
1834    #[test]
1835    fn opening_removes_only_tenant_directories_with_no_row() {
1836        let mut f = fixture();
1837        let kept = f.tenants.create(Actor::Cli, "acme", None).expect("made");
1838        let orphan = TenantId::generate();
1839        let tenants = f.tenants_dir();
1840        for name in [orphan.to_string(), "notes".to_owned()] {
1841            f.fs.create_dir_all(&tenants.join(name))
1842                .expect("a directory");
1843        }
1844        f.fs.sync_dir(&tenants).expect("sync");
1845        f.restart();
1846        assert_eq!(
1847            f.dirs(),
1848            [OsString::from(kept.to_string()), OsString::from("notes")]
1849        );
1850        drop(f.store(kept));
1851    }
1852
1853    /// The server's registry opens each tenant's Store with recovery, so a
1854    /// crash's leftovers in it go once the tenant is next used.
1855    #[test]
1856    fn a_servers_registry_opens_each_store_with_recovery() {
1857        let f = fixture();
1858        let id = f.tenants.create(Actor::Cli, "acme", None).expect("made");
1859        let objects = f.tenants_dir().join(id.to_string()).join("objects");
1860        let leftover = format!("{}.tmp", VersionId([0x0e; 16]));
1861        f.fs.write_new(&objects.join(&leftover), b"x")
1862            .expect("write");
1863        let tenants = f.open().expect("opens again");
1864        drop(tenants.store(id).expect("its store"));
1865        assert!(
1866            !f.fs
1867                .list(&objects)
1868                .expect("list")
1869                .contains(&OsString::from(leftover)),
1870            "the leftover is removed"
1871        );
1872    }
1873
1874    /// A command beside a running server must not take a create or a
1875    /// write the server has in progress for a crash's leftovers, in the
1876    /// registry or in a tenant's store.
1877    #[test]
1878    fn opening_beside_a_server_removes_nothing() {
1879        let f = fixture();
1880        let kept = f.tenants.create(Actor::Cli, "acme", None).expect("made");
1881        let orphan = TenantId::generate();
1882        let tenants = f.tenants_dir();
1883        f.fs.create_dir_all(&tenants.join(orphan.to_string()))
1884            .expect("a directory");
1885        f.fs.sync_dir(&tenants).expect("sync");
1886        let in_progress = tenants
1887            .join(kept.to_string())
1888            .join("objects")
1889            .join(format!("{}.tmp", VersionId([0x0e; 16])));
1890        f.fs.write_new(&in_progress, b"x").expect("write");
1891        let beside =
1892            Tenants::open_beside(f.dir.path(), f.master.key(), f.fs.clone(), f.clock.clone())
1893                .expect("opens beside");
1894        let mut expected = [
1895            OsString::from(kept.to_string()),
1896            OsString::from(orphan.to_string()),
1897        ];
1898        expected.sort();
1899        assert_eq!(f.dirs(), expected);
1900        drop(beside.store(kept).expect("its store"));
1901        assert!(
1902            f.fs.list(in_progress.parent().expect("objects"))
1903                .expect("list")
1904                .contains(&OsString::from(in_progress.file_name().expect("name"))),
1905            "the write in progress stays"
1906        );
1907    }
1908
1909    #[test]
1910    fn an_unknown_tenant_has_no_store() {
1911        let f = fixture();
1912        assert_eq!(
1913            f.tenants.store(TenantId::generate()).err(),
1914            Some(TenantError::NotFound)
1915        );
1916    }
1917
1918    #[test]
1919    fn every_request_to_a_tenant_shares_one_store() {
1920        let f = fixture();
1921        let id = f.tenants.create(Actor::Cli, "acme", None).expect("made");
1922        let a = f.tenants.store(id).expect("a store");
1923        let b = f.tenants.store(id).expect("the same store");
1924        assert!(Arc::ptr_eq(&a, &b));
1925        let (found, body) = vcon(UUID, "first");
1926        a.create(&caller(), &found, &body).expect("stored");
1927        assert_eq!(b.get(&caller(), found.uuid).expect("read").body, body);
1928    }
1929
1930    /// The first request opens the Store; one arriving meanwhile waits for
1931    /// it rather than opening a second.
1932    #[test]
1933    fn a_store_is_opened_once_even_by_requests_at_the_same_time() {
1934        let f = fixture();
1935        let id = f.tenants.create(Actor::Cli, "acme", None).expect("made");
1936        let (opening, is_opening) = std::sync::mpsc::channel();
1937        let (go, wait) = std::sync::mpsc::channel::<()>();
1938        *f.tenants.hooks.opening.lock().expect("hook") = Some(Box::new(move || {
1939            opening.send(()).expect("send");
1940            wait.recv_timeout(std::time::Duration::from_secs(30))
1941                .expect("go");
1942        }));
1943        // Everything the threads wait on is moved into the scope, so a
1944        // failed assertion drops it and the threads end instead of hanging.
1945        let tenants = &f.tenants;
1946        std::thread::scope(move |s| {
1947            let first = s.spawn(move || tenants.store(id).expect("the first"));
1948            is_opening
1949                .recv_timeout(std::time::Duration::from_secs(10))
1950                .expect("the first is opening");
1951            let (second_done, second) = std::sync::mpsc::channel();
1952            s.spawn(move || {
1953                second_done
1954                    .send(tenants.store(id).expect("the second"))
1955                    .expect("send");
1956            });
1957            assert!(
1958                second
1959                    .recv_timeout(std::time::Duration::from_millis(100))
1960                    .is_err(),
1961                "the second waits while the first opens"
1962            );
1963            go.send(()).expect("go");
1964            let first = first.join().expect("the first returns");
1965            let second = second
1966                .recv_timeout(std::time::Duration::from_secs(30))
1967                .expect("the second returns");
1968            assert!(Arc::ptr_eq(&first, &second));
1969        });
1970    }
1971
1972    #[test]
1973    fn a_tenant_key_that_does_not_unwrap_opens_no_store() {
1974        let f = fixture();
1975        let id = f.tenants.create(Actor::Cli, "acme", None).expect("made");
1976        f.conn()
1977            .execute(
1978                "UPDATE tenant SET wrapped_tenant_key = x'00' WHERE id = ?1",
1979                [id.0],
1980            )
1981            .expect("damage the wrapped key");
1982        assert_eq!(f.tenants.store(id).err(), Some(TenantError::Io));
1983    }
1984
1985    #[test]
1986    fn draining_refuses_new_requests_and_waits_for_those_in_flight() {
1987        let f = fixture();
1988        let id = f.tenants.create(Actor::Cli, "acme", None).expect("made");
1989        let (found, body) = vcon(UUID, "first");
1990        let held = f.tenants.store(id).expect("a request in flight");
1991        std::thread::scope(|s| {
1992            let (done, drained) = std::sync::mpsc::channel();
1993            let tenants = &f.tenants;
1994            s.spawn(move || {
1995                tenants.drain(id).expect("drains");
1996                done.send(()).expect("send");
1997            });
1998            let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
1999            while f.tenants.store(id).is_ok() {
2000                assert!(std::time::Instant::now() < deadline, "never closing");
2001                std::thread::yield_now();
2002            }
2003            assert_eq!(f.tenants.store(id).err(), Some(TenantError::Closing));
2004            assert!(
2005                drained
2006                    .recv_timeout(std::time::Duration::from_millis(100))
2007                    .is_err(),
2008                "the drain waits for the request in flight"
2009            );
2010            held.create(&caller(), &found, &body)
2011                .expect("the request in flight finishes");
2012            drop(held);
2013            drained
2014                .recv_timeout(std::time::Duration::from_secs(30))
2015                .expect("the drain ends once the last handle is dropped");
2016        });
2017        assert_eq!(f.tenants.store(id).err(), Some(TenantError::Closing));
2018    }
2019
2020    #[test]
2021    fn a_tenant_no_request_opened_drains_at_once() {
2022        let f = fixture();
2023        let id = f.tenants.create(Actor::Cli, "acme", None).expect("made");
2024        f.tenants.drain(id).expect("drains");
2025        assert_eq!(f.tenants.store(id).err(), Some(TenantError::Closing));
2026    }
2027
2028    impl Fixture {
2029        /// The tenant's own retention period, as its row holds it.
2030        fn own_retention(&self, id: TenantId) -> Option<String> {
2031            self.conn()
2032                .query_row("SELECT retention FROM tenant WHERE id = ?1", [id.0], |r| {
2033                    r.get(0)
2034                })
2035                .expect("a row")
2036        }
2037
2038        /// A second connection to the tenant's catalog.
2039        pub(crate) fn tenant_catalog(&self, id: TenantId) -> Connection {
2040            let catalog_key = envelope::catalog_key(&self.tenant_key(id)).expect("catalog key");
2041            catalog::open(
2042                &self
2043                    .tenants_dir()
2044                    .join(id.to_string())
2045                    .join("catalog.sqlite"),
2046                &catalog_key,
2047                "",
2048            )
2049            .expect("the tenant's catalog")
2050        }
2051
2052        /// The records with this action in the admin log.
2053        pub(crate) fn admin_records(&self, action: &str) -> Vec<Value> {
2054            self.admin_log()
2055                .into_iter()
2056                .filter(|r| r["action"] == action)
2057                .collect()
2058        }
2059    }
2060
2061    /// The rule the sweep and `check` both apply.
2062    #[test]
2063    fn retention_falls_back_to_the_server_default_when_unset() {
2064        let info = |retention| TenantInfo {
2065            id: TenantId([1; 16]),
2066            name: "acme".to_owned(),
2067            retention,
2068            metadata: Metadata::None,
2069            created_at: datetime!(2026-10-23 12:00 UTC),
2070        };
2071        assert_eq!(
2072            info(None).kept_for(Retention::Years(7)),
2073            Retention::Years(7)
2074        );
2075        assert_eq!(
2076            info(Some(Retention::Days(90))).kept_for(Retention::Years(7)),
2077            Retention::Days(90)
2078        );
2079    }
2080
2081    #[test]
2082    fn a_tenant_retention_is_read_afresh_and_not_recorded() {
2083        let f = fixture();
2084        let lab = f
2085            .tenants
2086            .create(Actor::Cli, "lab", Some(Retention::Months(18)))
2087            .expect("made");
2088        let acme = f.tenants.create(Actor::Cli, "acme", None).expect("made");
2089        let records = f.tenants.admin_records().len();
2090
2091        assert_eq!(f.tenants.retention(lab), Ok(Some(Retention::Months(18))));
2092        assert_eq!(f.tenants.retention(acme), Ok(None));
2093        f.tenants
2094            .set_retention(Actor::Cli, acme, Some(Retention::Days(0)))
2095            .expect("changed");
2096        assert_eq!(f.tenants.retention(acme), Ok(Some(Retention::Days(0))));
2097        assert_eq!(
2098            f.tenants.retention(TenantId([0xee; 16])),
2099            Err(TenantError::NotFound)
2100        );
2101        assert_eq!(
2102            f.tenants.admin_records().len(),
2103            records + 1,
2104            "only the retention change is recorded"
2105        );
2106        f.tenants
2107            .conn_for_test()
2108            .execute("UPDATE tenant SET retention = '7w' WHERE id = ?1", [lab.0])
2109            .expect("damaged");
2110        assert_eq!(
2111            f.tenants.retention(lab),
2112            Err(TenantError::Io),
2113            "a period that does not read back is damage"
2114        );
2115    }
2116
2117    #[test]
2118    fn ids_names_every_tenant_and_records_nothing() {
2119        let f = fixture();
2120        let a = f.tenants.create(Actor::Cli, "a", None).expect("made");
2121        let b = f.tenants.create(Actor::Cli, "b", None).expect("made");
2122        let records = f.tenants.admin_records().len();
2123
2124        let mut ids = f.tenants.ids().expect("ids");
2125        ids.sort_by_key(|id| id.0);
2126        let mut made = vec![a, b];
2127        made.sort_by_key(|id| id.0);
2128
2129        assert_eq!(ids, made);
2130        assert_eq!(f.tenants.admin_records().len(), records, "nothing recorded");
2131    }
2132
2133    #[test]
2134    fn list_shows_every_tenant_by_name_and_is_recorded() {
2135        let f = fixture();
2136        assert_eq!(f.tenants.list(Actor::Cli), Ok(Vec::new()));
2137        let lab = f
2138            .tenants
2139            .create(Actor::Cli, "lab", Some(Retention::Days(90)))
2140            .expect("made");
2141        f.clock.set(datetime!(2026-10-23 13:00 UTC));
2142        let acme = f.tenants.create(Actor::Cli, "acme", None).expect("made");
2143        assert_eq!(
2144            f.tenants.list(Actor::Cli),
2145            Ok(vec![
2146                TenantInfo {
2147                    id: acme,
2148                    name: "acme".to_owned(),
2149                    retention: None,
2150                    metadata: Metadata::None,
2151                    created_at: datetime!(2026-10-23 13:00 UTC),
2152                },
2153                TenantInfo {
2154                    id: lab,
2155                    name: "lab".to_owned(),
2156                    retention: Some(Retention::Days(90)),
2157                    metadata: Metadata::None,
2158                    created_at: datetime!(2026-10-23 12:00 UTC),
2159                },
2160            ])
2161        );
2162        let lists = f.admin_records("tenant_list");
2163        assert_eq!(lists.len(), 2, "one record per list");
2164        for record in lists {
2165            assert_eq!(record["actor"], "cli");
2166            assert_eq!(record["status"], 200);
2167            assert_eq!(record["target"], Value::Null);
2168        }
2169    }
2170
2171    #[test]
2172    fn a_stored_period_that_does_not_read_back_is_damage() {
2173        let f = fixture();
2174        let id = f.tenants.create(Actor::Cli, "acme", None).expect("made");
2175        f.conn()
2176            .execute("UPDATE tenant SET retention = '7w' WHERE id = ?1", [id.0])
2177            .expect("damage the period");
2178        assert_eq!(f.tenants.list(Actor::Cli), Err(TenantError::Io));
2179    }
2180
2181    #[test]
2182    fn a_list_whose_record_fails_shows_nothing() {
2183        let f = fixture();
2184        f.tenants.create(Actor::Cli, "acme", None).expect("made");
2185        f.conn()
2186            .execute_batch(
2187                "CREATE TEMP TRIGGER no_audit BEFORE INSERT ON audit
2188                 BEGIN SELECT RAISE(ABORT, 'no audit'); END;",
2189            )
2190            .expect("trigger");
2191        assert_eq!(f.tenants.list(Actor::Cli), Err(TenantError::AuditFailed));
2192    }
2193
2194    #[test]
2195    fn a_retention_change_is_kept_and_recorded_in_both_logs() {
2196        let f = fixture();
2197        let id = f.tenants.create(Actor::Cli, "acme", None).expect("made");
2198        f.clock.set(datetime!(2026-10-23 13:00 UTC));
2199        f.tenants
2200            .set_retention(Actor::Cli, id, Some(Retention::Months(18)))
2201            .expect("set");
2202        assert_eq!(f.own_retention(id).as_deref(), Some("18m"));
2203        f.tenants
2204            .set_retention(Actor::Cli, id, None)
2205            .expect("back to the default");
2206        assert_eq!(f.own_retention(id), None);
2207
2208        let admin = f.admin_records("tenant_retention");
2209        assert_eq!(admin.len(), 2);
2210        for record in &admin {
2211            assert_eq!(record["actor"], "cli");
2212            assert_eq!(record["target"], id.to_string());
2213            assert_eq!(record["status"], 200);
2214            assert_eq!(record["at"], "2026-10-23T13:00:00Z");
2215        }
2216        let copies: Vec<Value> = exported(&f.tenant_catalog(id), None)
2217            .into_iter()
2218            .filter(|r| r["action"] == "retention")
2219            .collect();
2220        assert_eq!(copies.len(), 2, "a copy in the tenant's log for each");
2221        for record in &copies {
2222            assert_eq!(record["actor"], "cli");
2223            assert_eq!(record["target"], id.to_string());
2224            assert_eq!(record["status"], 200);
2225        }
2226    }
2227
2228    impl Fixture {
2229        /// The tenant's metadata level, as its row holds it.
2230        fn own_metadata(&self, id: TenantId) -> Option<String> {
2231            self.conn()
2232                .query_row("SELECT metadata FROM tenant WHERE id = ?1", [id.0], |r| {
2233                    r.get(0)
2234                })
2235                .expect("a row")
2236        }
2237    }
2238
2239    /// A tenant's level is `none` until set; a change is kept, shown in
2240    /// the list, and recorded in the admin log and the tenant's own.
2241    #[test]
2242    fn a_metadata_level_is_none_until_set_and_each_change_is_recorded() {
2243        let f = fixture();
2244        let id = f.tenants.create(Actor::Cli, "acme", None).expect("made");
2245        assert_eq!(
2246            f.tenants.metadata(id),
2247            Ok(Metadata::None),
2248            "a new tenant is at none"
2249        );
2250        assert_eq!(f.own_metadata(id), None, "NULL is none");
2251        f.clock.set(datetime!(2026-10-23 13:00 UTC));
2252        f.tenants
2253            .set_metadata(Actor::Cli, id, Metadata::Full)
2254            .expect("set");
2255        assert_eq!(f.tenants.metadata(id), Ok(Metadata::Full), "the level set");
2256        assert_eq!(
2257            f.own_metadata(id).as_deref(),
2258            Some("full"),
2259            "the row holds the level's name"
2260        );
2261        let listed = f.tenants.list(Actor::Cli).expect("lists");
2262        assert_eq!(listed[0].to_json()["metadata"], "full", "shown in the list");
2263        f.tenants
2264            .set_metadata(Actor::Cli, id, Metadata::None)
2265            .expect("back to none");
2266        assert_eq!(f.own_metadata(id), None, "none is NULL again");
2267        assert_eq!(f.tenants.metadata(id), Ok(Metadata::None), "back to none");
2268
2269        let admin = f.admin_records("tenant_metadata");
2270        assert_eq!(admin.len(), 2, "one admin record per change");
2271        for record in &admin {
2272            assert_eq!(record["actor"], "cli", "the command line made the change");
2273            assert_eq!(
2274                record["target"],
2275                id.to_string(),
2276                "the record names the tenant"
2277            );
2278            assert_eq!(record["status"], 200, "the change succeeded");
2279            assert_eq!(record["at"], "2026-10-23T13:00:00Z", "at the clock's time");
2280        }
2281        let copies: Vec<Value> = exported(&f.tenant_catalog(id), None)
2282            .into_iter()
2283            .filter(|r| r["action"] == "metadata")
2284            .collect();
2285        assert_eq!(copies.len(), 2, "a copy in the tenant's log for each");
2286    }
2287
2288    #[test]
2289    fn a_metadata_change_for_an_unknown_or_closing_tenant_is_refused() {
2290        let f = fixture();
2291        let unknown = TenantId::generate();
2292        assert_eq!(
2293            f.tenants
2294                .set_metadata(Actor::Cli, unknown, Metadata::Counts),
2295            Err(TenantError::NotFound),
2296            "no tenant has the id"
2297        );
2298        assert_eq!(
2299            f.tenants.metadata(unknown),
2300            Err(TenantError::NotFound),
2301            "nor a level"
2302        );
2303        let id = f.tenants.create(Actor::Cli, "acme", None).expect("made");
2304        f.tenants.drain(id).expect("drains");
2305        assert_eq!(
2306            f.tenants.set_metadata(Actor::Cli, id, Metadata::Counts),
2307            Err(TenantError::Closing),
2308            "a closing tenant's level does not change"
2309        );
2310        assert_eq!(f.own_metadata(id), None, "unchanged");
2311        let statuses: Vec<Value> = f
2312            .admin_records("tenant_metadata")
2313            .iter()
2314            .map(|r| r["status"].clone())
2315            .collect();
2316        assert_eq!(
2317            statuses,
2318            [404, 503],
2319            "both refusals are recorded, each with its status"
2320        );
2321    }
2322
2323    /// A level this build does not know is damage, never taken as `none`.
2324    #[test]
2325    fn a_stored_metadata_level_this_build_does_not_know_is_an_error() {
2326        let f = fixture();
2327        let id = f.tenants.create(Actor::Cli, "acme", None).expect("made");
2328        f.conn()
2329            .execute("UPDATE tenant SET metadata = 'most' WHERE id = ?1", [id.0])
2330            .expect("update");
2331        assert_eq!(
2332            f.tenants.metadata(id),
2333            Err(TenantError::Io),
2334            "an unknown level is an error"
2335        );
2336    }
2337
2338    /// A registry made at schema version 2 gains the column at version 3,
2339    /// every tenant at `none`; one made at version 1 does too.
2340    #[test]
2341    fn an_older_registry_gains_the_metadata_column() {
2342        for from in [1, 2] {
2343            let mut f = fixture();
2344            let id = f.tenants.create(Actor::Cli, "acme", None).expect("made");
2345            f.conn()
2346                .execute_batch(&format!(
2347                    "ALTER TABLE tenant DROP COLUMN role_cap;
2348                     ALTER TABLE tenant DROP COLUMN metadata; DROP TABLE membership;
2349                     DROP TABLE user_account; DROP TABLE tenant_setting;
2350                     DROP TABLE session;
2351                     ALTER TABLE api_key DROP COLUMN last_used_at;
2352                     ALTER TABLE api_key DROP COLUMN expires_at;
2353                     PRAGMA user_version = {from};"
2354                ))
2355                .expect("back to the old schema");
2356            f.restart();
2357            let version: i64 = f
2358                .conn()
2359                .pragma_query_value(None, "user_version", |r| r.get(0))
2360                .expect("version");
2361            assert_eq!(version, catalog::SCHEMA_VERSION, "from {from}");
2362            assert_eq!(f.tenants.metadata(id), Ok(Metadata::None), "from {from}");
2363            f.tenants
2364                .set_metadata(Actor::Cli, id, Metadata::Counts)
2365                .expect("the column is there");
2366        }
2367    }
2368
2369    #[test]
2370    fn a_retention_change_for_an_unknown_tenant_is_not_found() {
2371        let f = fixture();
2372        let id = TenantId::generate();
2373        assert_eq!(
2374            f.tenants
2375                .set_retention(Actor::Cli, id, Some(Retention::Years(1))),
2376            Err(TenantError::NotFound)
2377        );
2378        let admin = f.admin_records("tenant_retention");
2379        assert_eq!(admin.len(), 1);
2380        assert_eq!(admin[0]["status"], 404);
2381        assert_eq!(admin[0]["target"], id.to_string());
2382    }
2383
2384    #[test]
2385    fn a_retention_change_for_a_closing_tenant_is_refused() {
2386        let f = fixture();
2387        let id = f.tenants.create(Actor::Cli, "acme", None).expect("made");
2388        f.tenants.drain(id).expect("drains");
2389        assert_eq!(
2390            f.tenants
2391                .set_retention(Actor::Cli, id, Some(Retention::Years(1))),
2392            Err(TenantError::Closing)
2393        );
2394        assert_eq!(f.own_retention(id), None, "unchanged");
2395        assert_eq!(f.admin_records("tenant_retention")[0]["status"], 503);
2396    }
2397
2398    #[test]
2399    fn a_retention_change_whose_admin_record_fails_changes_nothing() {
2400        let f = fixture();
2401        let id = f.tenants.create(Actor::Cli, "acme", None).expect("made");
2402        f.conn()
2403            .execute_batch(
2404                "CREATE TEMP TRIGGER no_audit BEFORE INSERT ON audit
2405                 BEGIN SELECT RAISE(ABORT, 'no audit'); END;",
2406            )
2407            .expect("trigger");
2408        assert_eq!(
2409            f.tenants
2410                .set_retention(Actor::Cli, id, Some(Retention::Years(1))),
2411            Err(TenantError::AuditFailed)
2412        );
2413        assert_eq!(f.own_retention(id), None, "unchanged");
2414        let copies = exported(&f.tenant_catalog(id), None)
2415            .into_iter()
2416            .filter(|r| r["action"] == "retention")
2417            .count();
2418        assert_eq!(copies, 0, "no copy of a change that was not made");
2419    }
2420
2421    /// The change commits with its admin record; a failed copy in the
2422    /// tenant's log leaves the change standing and answers AuditFailed.
2423    #[test]
2424    fn a_retention_change_whose_tenant_copy_fails_stands() {
2425        let f = fixture();
2426        let id = f.tenants.create(Actor::Cli, "acme", None).expect("made");
2427        f.tenant_catalog(id)
2428            .execute_batch(
2429                "CREATE TRIGGER dead BEFORE INSERT ON audit
2430                 BEGIN SELECT RAISE(ABORT, 'no audit'); END;",
2431            )
2432            .expect("trigger");
2433        assert_eq!(
2434            f.tenants
2435                .set_retention(Actor::Cli, id, Some(Retention::Years(10))),
2436            Err(TenantError::AuditFailed)
2437        );
2438        assert_eq!(
2439            f.own_retention(id).as_deref(),
2440            Some("10y"),
2441            "the change stands"
2442        );
2443        assert_eq!(f.admin_records("tenant_retention")[0]["status"], 200);
2444    }
2445
2446    /// A tenant with one vCon stored.
2447    fn with_vcon(f: &Fixture) -> TenantId {
2448        let id = f.tenants.create(Actor::Cli, "acme", None).expect("made");
2449        let (found, body) = vcon(UUID, "first");
2450        f.tenants
2451            .store(id)
2452            .expect("its store")
2453            .create(&caller(), &found, &body)
2454            .expect("stored");
2455        id
2456    }
2457
2458    fn hold(f: &Fixture, id: TenantId) {
2459        f.tenant_catalog(id)
2460            .execute("UPDATE vcon SET hold = 1", [])
2461            .expect("a hold");
2462    }
2463
2464    /// Waits until the tenant refuses new requests.
2465    fn until_closing(f: &Fixture, id: TenantId) {
2466        let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
2467        while f.tenants.store(id).is_ok() {
2468            assert!(std::time::Instant::now() < deadline, "never closing");
2469            std::thread::yield_now();
2470        }
2471    }
2472
2473    #[test]
2474    fn a_tenant_already_closing_cannot_be_drained_again() {
2475        let f = fixture();
2476        let id = f.tenants.create(Actor::Cli, "acme", None).expect("made");
2477        f.tenants.drain(id).expect("drains");
2478        assert_eq!(f.tenants.drain(id).err(), Some(TenantError::Closing));
2479    }
2480
2481    #[test]
2482    fn removing_an_unknown_tenant_is_not_found() {
2483        let f = fixture();
2484        let id = TenantId::generate();
2485        assert_eq!(
2486            f.tenants.remove(Actor::Cli, id, Removal::Empty),
2487            Err(TenantError::NotFound)
2488        );
2489        assert_eq!(f.tenants.store(id).err(), Some(TenantError::NotFound));
2490        let records = f.admin_records("tenant_remove");
2491        assert_eq!(records.len(), 1);
2492        assert_eq!(records[0]["status"], 404);
2493        assert_eq!(records[0]["target"], id.to_string());
2494    }
2495
2496    #[test]
2497    fn an_empty_tenant_is_removed_with_its_key_directory_and_row() {
2498        let f = fixture();
2499        let id = f.tenants.create(Actor::Cli, "acme", None).expect("made");
2500        drop(f.tenants.store(id).expect("opened by a request"));
2501        f.clock.set(datetime!(2026-10-23 13:00 UTC));
2502        f.tenants
2503            .remove(Actor::Cli, id, Removal::Empty)
2504            .expect("removed");
2505        assert!(!f.has_row(id), "its row and wrapped key are gone");
2506        assert_eq!(f.tenants.store(id).err(), Some(TenantError::NotFound));
2507        assert_eq!(f.dirs(), Vec::<OsString>::new(), "its directory is gone");
2508        assert_eq!(f.tenants.list(Actor::Cli), Ok(Vec::new()));
2509        let records = f.admin_records("tenant_remove");
2510        assert_eq!(records.len(), 1);
2511        assert_eq!(records[0]["actor"], "cli");
2512        assert_eq!(records[0]["target"], id.to_string());
2513        assert_eq!(records[0]["status"], 204);
2514        assert_eq!(records[0]["at"], "2026-10-23T13:00:00Z");
2515    }
2516
2517    #[test]
2518    fn an_empty_removal_is_refused_while_any_version_is_kept() {
2519        let f = fixture();
2520        let id = with_vcon(&f);
2521        let uuid = vcon(UUID, "first").0.uuid;
2522        f.tenants
2523            .store(id)
2524            .expect("its store")
2525            .delete(&caller(), uuid, Retention::Years(7))
2526            .expect("deleted, so only a hidden version is kept");
2527        assert_eq!(
2528            f.tenants.remove(Actor::Cli, id, Removal::Empty),
2529            Err(TenantError::HoldsVcons)
2530        );
2531        assert!(f.has_row(id));
2532        let store = f.tenants.store(id).expect("still served");
2533        assert_eq!(store.counts().map(|c| c.versions), Ok(1));
2534        assert_eq!(f.admin_records("tenant_remove")[0]["status"], 409);
2535    }
2536
2537    #[test]
2538    fn a_forced_removal_takes_the_vcons_too() {
2539        let f = fixture();
2540        let id = with_vcon(&f);
2541        f.tenants
2542            .remove(Actor::Cli, id, Removal::Force)
2543            .expect("removed");
2544        assert!(!f.has_row(id));
2545        assert_eq!(f.dirs(), Vec::<OsString>::new());
2546    }
2547
2548    #[test]
2549    fn a_forced_removal_is_refused_while_a_uuid_is_held() {
2550        let f = fixture();
2551        let id = with_vcon(&f);
2552        hold(&f, id);
2553        assert_eq!(
2554            f.tenants.remove(Actor::Cli, id, Removal::Force),
2555            Err(TenantError::UnderHold)
2556        );
2557        assert!(f.has_row(id));
2558        assert!(f.tenants.store(id).is_ok(), "still served");
2559        assert_eq!(f.admin_records("tenant_remove")[0]["status"], 409);
2560    }
2561
2562    #[test]
2563    fn overriding_holds_removes_a_held_tenant() {
2564        let f = fixture();
2565        let id = with_vcon(&f);
2566        hold(&f, id);
2567        f.tenants
2568            .remove(Actor::Cli, id, Removal::ForceOverridingHolds)
2569            .expect("removed");
2570        assert!(!f.has_row(id));
2571        assert_eq!(f.dirs(), Vec::<OsString>::new());
2572    }
2573
2574    /// The removal drains before it looks, so a write that lands meanwhile
2575    /// makes the tenant non-empty and the removal is refused: the write
2576    /// is never acknowledged and then lost.
2577    #[test]
2578    fn a_write_in_flight_during_an_empty_removal_is_kept() {
2579        let f = fixture();
2580        let id = f.tenants.create(Actor::Cli, "acme", None).expect("made");
2581        let (found, body) = vcon(UUID, "first");
2582        let held = f.tenants.store(id).expect("a request in flight");
2583        let tenants = &f.tenants;
2584        let fx = &f;
2585        let (found_ref, body_ref) = (&found, &body);
2586        let result = std::thread::scope(move |s| {
2587            let (done, removed) = std::sync::mpsc::channel();
2588            s.spawn(move || {
2589                done.send(tenants.remove(Actor::Cli, id, Removal::Empty))
2590                    .expect("send");
2591            });
2592            until_closing(fx, id);
2593            assert!(
2594                removed
2595                    .recv_timeout(std::time::Duration::from_millis(100))
2596                    .is_err(),
2597                "the removal waits for the write"
2598            );
2599            held.create(&caller(), found_ref, body_ref)
2600                .expect("the write is acknowledged");
2601            drop(held);
2602            removed
2603                .recv_timeout(std::time::Duration::from_secs(30))
2604                .expect("the removal ends")
2605        });
2606        assert_eq!(result, Err(TenantError::HoldsVcons));
2607        assert_eq!(
2608            f.tenants
2609                .store(id)
2610                .expect("still served")
2611                .get(&caller(), found.uuid)
2612                .expect("the write is kept")
2613                .body,
2614            body
2615        );
2616    }
2617
2618    #[test]
2619    fn a_second_removal_while_one_drains_is_refused() {
2620        let f = fixture();
2621        let id = f.tenants.create(Actor::Cli, "acme", None).expect("made");
2622        let held = f.tenants.store(id).expect("a request in flight");
2623        let tenants = &f.tenants;
2624        let fx = &f;
2625        std::thread::scope(move |s| {
2626            let first = s.spawn(move || tenants.remove(Actor::Cli, id, Removal::Force));
2627            until_closing(fx, id);
2628            assert_eq!(
2629                fx.tenants.remove(Actor::Cli, id, Removal::Empty),
2630                Err(TenantError::Closing)
2631            );
2632            drop(held);
2633            assert_eq!(first.join().expect("the first returns"), Ok(()));
2634        });
2635        let statuses: Vec<Value> = f
2636            .admin_records("tenant_remove")
2637            .into_iter()
2638            .map(|r| r["status"].clone())
2639            .collect();
2640        assert_eq!(statuses, [503, 204]);
2641    }
2642
2643    #[test]
2644    fn a_removal_whose_record_fails_removes_nothing() {
2645        let f = fixture();
2646        let id = f.tenants.create(Actor::Cli, "acme", None).expect("made");
2647        f.conn()
2648            .execute_batch(
2649                "CREATE TEMP TRIGGER no_audit BEFORE INSERT ON audit
2650                 BEGIN SELECT RAISE(ABORT, 'no audit'); END;",
2651            )
2652            .expect("trigger");
2653        assert_eq!(
2654            f.tenants.remove(Actor::Cli, id, Removal::Empty),
2655            Err(TenantError::AuditFailed)
2656        );
2657        assert!(f.has_row(id));
2658        assert_eq!(f.dirs().len(), 1);
2659        assert!(f.tenants.store(id).is_ok(), "served again");
2660    }
2661
2662    /// The row's commit is the removal; a directory a crash leaves after
2663    /// it goes at the next start.
2664    #[test]
2665    fn a_removal_cut_off_after_its_commit_finishes_at_the_next_start() {
2666        let mut f = fixture();
2667        let id = f.tenants.create(Actor::Cli, "acme", None).expect("made");
2668        drop(f.tenants.store(id).expect("opened by a request"));
2669        f.fs.fail_from(f.fs.log().len());
2670        assert_eq!(f.tenants.remove(Actor::Cli, id, Removal::Empty), Ok(()));
2671        assert_eq!(f.dirs().len(), 1, "the dead process removed nothing");
2672        f.restart();
2673        assert!(!f.has_row(id));
2674        assert_eq!(f.dirs(), Vec::<OsString>::new());
2675    }
2676
2677    #[test]
2678    fn removal_deletes_the_directory_on_disk() {
2679        let dir = tempfile::tempdir().expect("temp dir");
2680        let tenants = Tenants::open(
2681            dir.path(),
2682            Master::new().key(),
2683            Arc::new(crate::fs::OsFs),
2684            Arc::new(ManualClock::at(datetime!(2026-10-23 12:00 UTC))),
2685        )
2686        .expect("opens");
2687        let id = tenants.create(Actor::Cli, "acme", None).expect("made");
2688        let tenant_dir = dir.path().join("tenants").join(id.to_string());
2689        assert!(tenant_dir.join("catalog.sqlite").is_file());
2690        tenants
2691            .remove(Actor::Cli, id, Removal::Empty)
2692            .expect("removed");
2693        assert!(!tenant_dir.exists());
2694    }
2695
2696    #[test]
2697    fn two_tenants_keep_the_same_uuid_apart() {
2698        let f = fixture();
2699        let a = f.tenants.create(Actor::Cli, "a", None).expect("made");
2700        let b = f.tenants.create(Actor::Cli, "b", None).expect("made");
2701        let (found, kept_by_a) = vcon(UUID, "kept by a");
2702        let (_, kept_by_b) = vcon(UUID, "kept by b");
2703        let (store_a, store_b) = (
2704            f.tenants.store(a).expect("a's store"),
2705            f.tenants.store(b).expect("b's store"),
2706        );
2707        assert!(matches!(
2708            store_a.create(&caller(), &found, &kept_by_a),
2709            Ok(Created::New(_))
2710        ));
2711        assert!(matches!(
2712            store_b.create(&caller(), &found, &kept_by_b),
2713            Ok(Created::New(_))
2714        ));
2715        let read = |store: &Store| store.get(&caller(), found.uuid).map(|s| s.body);
2716        assert_eq!(read(&store_a), Ok(kept_by_a));
2717        assert_eq!(read(&store_b), Ok(kept_by_b.clone()));
2718        store_a
2719            .delete(&caller(), found.uuid, Retention::Years(7))
2720            .expect("a deletes its own");
2721        assert_eq!(read(&store_a), Err(StoreError::Gone));
2722        assert_eq!(read(&store_b), Ok(kept_by_b), "b's is untouched");
2723    }
2724
2725    /// A version's data key is wrapped for its tenant by id, so the
2726    /// tenant's Store must be opened under that id.
2727    #[test]
2728    fn a_tenants_data_keys_are_bound_to_its_own_id() {
2729        let f = fixture();
2730        let id = f.tenants.create(Actor::Cli, "acme", None).expect("made");
2731        let (found, body) = vcon(UUID, "first");
2732        let Ok(Created::New(version)) =
2733            f.tenants
2734                .store(id)
2735                .expect("its store")
2736                .create(&caller(), &found, &body)
2737        else {
2738            panic!("a new vCon")
2739        };
2740        let wrapped: Vec<u8> = f
2741            .tenant_catalog(id)
2742            .query_row(
2743                "SELECT wrapped_key FROM version WHERE version = ?1",
2744                [version.0],
2745                |r| r.get(0),
2746            )
2747            .expect("its row");
2748        let ctx = Context::Version {
2749            tenant: id,
2750            uuid: found.uuid,
2751            version,
2752        };
2753        assert!(envelope::unwrap(&f.tenant_key(id), &ctx, &wrapped).is_ok());
2754    }
2755
2756    /// The answers one tenant gets for a uuid, whatever another holds.
2757    fn answers(store: &Store) -> Vec<String> {
2758        let (found, body) = vcon(UUID, "b's own");
2759        let (_, newer) = vcon(UUID, "b's newer");
2760        let kind = |r: Result<Created, StoreError>| match r {
2761            Ok(Created::New(_)) => "new".to_owned(),
2762            Ok(Created::Same(_)) => "same".to_owned(),
2763            Err(e) => format!("{e:?}"),
2764        };
2765        let who = caller();
2766        let mut answers = vec![
2767            format!("{:?}", store.get(&who, found.uuid).map(|_| ())),
2768            format!("{:?}", store.delete(&who, found.uuid, Retention::Years(7))),
2769            kind(store.create(&who, &found, &body)),
2770            kind(store.create(&who, &found, &body)),
2771        ];
2772        let current = store.get(&who, found.uuid).expect("stored").version;
2773        answers.push(format!(
2774            "{:?}",
2775            store.replace(&who, current, &found, &newer).map(|_| ())
2776        ));
2777        answers.push(format!(
2778            "{:?}",
2779            store.delete(&who, found.uuid, Retention::Years(7))
2780        ));
2781        answers.push(format!("{:?}", store.get(&who, found.uuid).map(|_| ())));
2782        answers
2783    }
2784
2785    #[test]
2786    fn nothing_one_tenant_does_shows_whether_another_holds_a_uuid() {
2787        let alone = fixture();
2788        let b = alone.tenants.create(Actor::Cli, "b", None).expect("made");
2789        let expected = answers(&alone.tenants.store(b).expect("b's store"));
2790
2791        let f = fixture();
2792        let a = f.tenants.create(Actor::Cli, "a", None).expect("made");
2793        let b = f.tenants.create(Actor::Cli, "b", None).expect("made");
2794        let store_a = f.tenants.store(a).expect("a's store");
2795        let (found, body) = vcon(UUID, "a's");
2796        store_a
2797            .create(&caller(), &found, &body)
2798            .expect("a holds it");
2799        let (other, body) = vcon("01a07da8-c2bb-83e5-b9a2-279e0d16bc47", "a's other");
2800        store_a.create(&caller(), &other, &body).expect("stored");
2801        store_a
2802            .delete(&caller(), other.uuid, Retention::Years(7))
2803            .expect("and has deleted another");
2804        assert_eq!(answers(&f.tenants.store(b).expect("b's store")), expected);
2805        assert_eq!(
2806            expected,
2807            [
2808                "Err(NotFound)",
2809                "Err(NotFound)",
2810                "new",
2811                "same",
2812                "Ok(())",
2813                "Ok(())",
2814                "Err(Gone)"
2815            ]
2816        );
2817    }
2818}