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