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