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