Skip to main content

vcon_server/
commands.rs

1//! The commands other than `serve`: tenants, keys and the audit logs. Each
2//! takes the data directory as its work shares it, opens the registry with
3//! recovery when it runs alone and without when it may run beside a server,
4//! and prints what the matching admin route answers: one JSON object a
5//! line.
6
7use std::fmt;
8use std::io::{self, Write};
9use std::sync::Arc;
10
11use crate::access::{Scope, Scopes};
12use crate::audit::{Actor, AuditError};
13use crate::backend;
14use crate::clock::{Clock, SystemClock};
15use crate::config::{Config, StorageError};
16use crate::datadir::{self, LockError, Sharing, Work};
17use crate::envelope::{Key, KeyError};
18use crate::fs::OsFs;
19use crate::ids::{KeyId, TenantId, UserId};
20use crate::key_wrap::FileWrap;
21use crate::key_wrap::blob::BackendKind;
22use crate::retention::Retention;
23use crate::roles::{Role, Roles};
24use crate::store::ExamineError;
25use crate::tenants::{
26    self, BackupError, Identity, KeyLife, OpenFailure, RegistryError, Removal, TenantError,
27    TenantExamination, Tenants, Unexamined, UserError,
28};
29use time::OffsetDateTime;
30use time::format_description::well_known::Rfc3339;
31
32/// A command, as written on the command line.
33#[derive(Debug, Clone, PartialEq, Eq)]
34pub enum Command {
35    TenantCreate {
36        name: String,
37        retention: Option<String>,
38    },
39    TenantList,
40    /// `retention` is a period, or `default` for the server's.
41    TenantSetRetention {
42        id: String,
43        retention: String,
44    },
45    TenantRemove {
46        id: String,
47        force: bool,
48        override_holds: bool,
49    },
50    /// `metadata` is `none`, `counts` or `full`.
51    TenantSetMetadata {
52        id: String,
53        metadata: String,
54    },
55    /// Sets the roles a membership in the tenant may be given; `roles`
56    /// None removes the cap.
57    TenantSetRoleCap {
58        id: String,
59        roles: Option<Vec<String>>,
60    },
61    /// Prints the tenant's role cap.
62    TenantRoleCap {
63        id: String,
64    },
65    /// Moves every tenant's sealed objects from the data directory to the
66    /// bucket `storage.objects = "s3"` names. Runs only while no server
67    /// does.
68    StorageMoveObjects,
69    /// Writes the tenant's kept versions as Parquet files to `to`, a
70    /// directory or an `s3://bucket/prefix`, beside a running server.
71    /// `since` and `until` are RFC 3339 times.
72    ExportParquet {
73        tenant: String,
74        to: String,
75        since: Option<String>,
76        until: Option<String>,
77    },
78    KeyCreate {
79        owner: Owner,
80        label: String,
81        /// When the key expires: by default, in a number of days, or never.
82        life: KeyLife,
83    },
84    KeyList {
85        tenant: Option<String>,
86    },
87    KeyRevoke {
88        id: String,
89    },
90    /// Makes a user. `identity` is the issuer and subject an identity
91    /// provider knows the user by; None makes a local account.
92    UserAdd {
93        label: String,
94        identity: Option<(String, String)>,
95    },
96    UserList,
97    UserDeactivate {
98        id: String,
99    },
100    /// Gives a user roles in a tenant, or the operator role.
101    MembershipGrant {
102        user: String,
103        place: Place,
104    },
105    /// Takes roles from a user's membership; with no role named, all of
106    /// them.
107    MembershipRevoke {
108        user: String,
109        place: Place,
110    },
111    AuditExport {
112        log: Log,
113        since: Option<i64>,
114    },
115    /// Rotates a tenant's key.
116    RekeyTenant {
117        id: String,
118    },
119    /// Rotates the master key to the one in `new_master`; with
120    /// `to_backend`, moves the registry root to the backend it names, which
121    /// in this release is `file`, the master key file `new_master`.
122    RekeyMaster {
123        new_master: std::path::PathBuf,
124        to_backend: Option<String>,
125    },
126    /// Examines every tenant and reports what needs attention.
127    Check,
128    /// Writes a consistent copy of the data directory to `to`, which must
129    /// not exist, beside a running server.
130    Backup {
131        to: std::path::PathBuf,
132    },
133}
134
135/// Whose key `key create` makes.
136#[derive(Debug, Clone, PartialEq, Eq)]
137pub enum Owner {
138    Tenant { id: String, scopes: Vec<String> },
139    Operator,
140}
141
142/// Where a membership is: in a tenant, with the roles the command names,
143/// or as an operator, whose one role the command does not name.
144#[derive(Debug, Clone, PartialEq, Eq)]
145pub enum Place {
146    Tenant { id: String, roles: Vec<String> },
147    Operator,
148}
149
150/// Which audit log `audit export` writes.
151#[derive(Debug, Clone, PartialEq, Eq)]
152pub enum Log {
153    Tenant(String),
154    Admin,
155}
156
157impl Command {
158    /// The work this command does in the data directory.
159    pub fn work(&self) -> Work {
160        match self {
161            Command::TenantCreate { .. } => Work::TenantCreate,
162            Command::TenantList => Work::TenantList,
163            Command::TenantSetRetention { .. } => Work::TenantSetRetention,
164            Command::TenantRemove { .. } => Work::TenantRemove,
165            Command::TenantSetMetadata { .. } => Work::TenantSetMetadata,
166            Command::TenantSetRoleCap { .. } => Work::TenantSetRoleCap,
167            Command::TenantRoleCap { .. } => Work::TenantRoleCap,
168            Command::ExportParquet { .. } => Work::ExportParquet,
169            Command::StorageMoveObjects => Work::StorageMoveObjects,
170            Command::KeyCreate { .. } => Work::KeyCreate,
171            Command::KeyList { .. } => Work::KeyList,
172            Command::KeyRevoke { .. } => Work::KeyRevoke,
173            Command::UserAdd { .. } => Work::UserAdd,
174            Command::UserList => Work::UserList,
175            Command::UserDeactivate { .. } => Work::UserDeactivate,
176            Command::MembershipGrant { .. } => Work::MembershipGrant,
177            Command::MembershipRevoke { .. } => Work::MembershipRevoke,
178            Command::AuditExport { .. } => Work::AuditExport,
179            Command::RekeyTenant { .. } => Work::RekeyTenant,
180            Command::RekeyMaster { .. } => Work::RekeyMaster,
181            Command::Check => Work::Check,
182            Command::Backup { .. } => Work::Backup,
183        }
184    }
185}
186
187/// Why a command did not complete.
188#[derive(Debug)]
189pub enum CommandError {
190    DataDir(LockError),
191    MasterKey(KeyError),
192    /// server.sqlite was made under another master key.
193    WrongMasterKey,
194    /// The registry in the catalog database was made under another master
195    /// key.
196    WrongDatabaseKey,
197    /// A period that is neither like 7y, 18m or 90d nor, where allowed,
198    /// `default`.
199    BadPeriod(String),
200    Tenant(TenantError),
201    /// The registry could not be opened.
202    Open(RegistryError),
203    /// No key has this id.
204    UnknownKey,
205    /// A user or membership command was refused.
206    User(UserError),
207    /// The output could not be written.
208    Output(io::Error),
209    /// The new master key is the one already in use.
210    SameMasterKey,
211    /// `--to-backend` names a key backend this release does not move keys
212    /// to.
213    BackendLater(BackendKind),
214    /// `--to-backend` names no key backend.
215    NoSuchBackend(String),
216    /// `check` found this many problems; its report says which.
217    CheckFound(usize),
218    Backup(BackupError),
219    /// The storage the configuration names cannot be used.
220    Storage(StorageError),
221    /// Not `none`, `counts` or `full`.
222    BadLevel(String),
223    /// Not an RFC 3339 time.
224    BadTime(String),
225    /// Neither a directory nor an `s3://bucket/prefix`.
226    BadTarget(String),
227    /// An `s3://` target with no `[export.s3]` or `[storage.s3]` table, or
228    /// in a build without S3.
229    NoS3,
230    Export(crate::export::ExportError),
231    /// Moving a tenant's objects to the bucket stopped; what was moved
232    /// stays moved, and running the command again moves the rest.
233    Move {
234        tenant: TenantId,
235        why: String,
236    },
237}
238
239impl fmt::Display for CommandError {
240    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
241        match self {
242            CommandError::DataDir(e) => write!(f, "{e}"),
243            CommandError::MasterKey(KeyError::Refused(why)) => {
244                write!(f, "the master key cannot be read: {why}")
245            }
246            CommandError::MasterKey(e) => write!(f, "the master key cannot be read: {e:?}"),
247            CommandError::Open(e) => write!(
248                f,
249                "the registry cannot be opened: {}",
250                crate::tenants::with_causes(e)
251            ),
252            CommandError::WrongMasterKey | CommandError::Tenant(TenantError::WrongKey) => {
253                f.write_str("the master key is not the one server.sqlite was made under")
254            }
255            CommandError::WrongDatabaseKey => f.write_str(crate::tenants::WRONG_DATABASE_KEY),
256            CommandError::BadPeriod(text) => write!(
257                f,
258                "{text:?} is not a period such as 7y, 18m or 90d (or, for set-retention, default)"
259            ),
260            CommandError::UnknownKey => f.write_str("no key has this id"),
261            CommandError::User(e) => f.write_str(match e {
262                UserError::CliOnly => "only the command line may do this",
263                UserError::BadLabel => {
264                    "a user label is 1 to 128 characters, with no control characters and no space at either end"
265                }
266                UserError::BadIdentity => {
267                    "an issuer is an https:// URL of at most 255 bytes with no query or fragment, and a subject is 1 to 255 ASCII characters with no space at either end"
268                }
269                UserError::IdentityTaken => "an active user has this issuer and subject",
270                UserError::NoUser => "no user has this id",
271                UserError::Deactivated => "the user is deactivated",
272                UserError::NoTenant => "no tenant has this id",
273                UserError::Closing => "the tenant is being removed",
274                UserError::BadRoles => {
275                    "a tenant membership's roles are one or more of reader, producer, records, legal, auditor and tenant-admin; an operator membership holds operator alone"
276                }
277                UserError::OverCap => "a role named is outside the tenant's role cap",
278                UserError::BadCap => {
279                    "a role cap is one or more of reader, producer, records, legal, auditor and tenant-admin"
280                }
281                UserError::NoMembership => "the user has no such membership",
282                UserError::Registry(_) => "the data could not be read or written",
283            }),
284            CommandError::Output(e) => write!(f, "the output could not be written: {e}"),
285            CommandError::SameMasterKey => {
286                f.write_str("the new master key is the one already in use")
287            }
288            CommandError::BackendLater(kind) => write!(
289                f,
290                "--to-backend {kind}: this release moves the keys only to a master key file \
291                 (--to-backend file)"
292            ),
293            CommandError::NoSuchBackend(name) => write!(
294                f,
295                "--to-backend {name} is not a key backend: file, aws-kms, gcp-kms, \
296                 azure-key-vault, vault-transit, openbao-transit or pkcs11"
297            ),
298            CommandError::CheckFound(n) => write!(f, "check found {n} problem(s); see its report"),
299            CommandError::Storage(e) => write!(f, "the storage cannot be used: {e}"),
300            CommandError::BadLevel(text) => write!(
301                f,
302                "{text:?} is not a metadata level: none, counts or full"
303            ),
304            CommandError::BadTime(text) => write!(
305                f,
306                "{text:?} is not an RFC 3339 time such as 2026-11-05T00:00:00Z"
307            ),
308            CommandError::BadTarget(text) => write!(
309                f,
310                "{text:?} is not a directory or an s3://bucket/prefix"
311            ),
312            CommandError::NoS3 => f.write_str(
313                "an s3:// target needs an [export.s3] or [storage.s3] table, in a build with the s3 feature",
314            ),
315            CommandError::Export(e) => write!(f, "{e}"),
316            CommandError::Move { tenant, why } => write!(
317                f,
318                "moving tenant {tenant}'s objects to the bucket stopped: {why}; what moved stays \
319                 moved, and running storage move-objects again moves the rest"
320            ),
321            CommandError::Backup(e) => f.write_str(match e {
322                BackupError::Exists => {
323                    "the backup's path already exists; a backup is written to a new directory"
324                }
325                BackupError::KeptChanging => {
326                    "tenants were removed or versions purged during each try; try again"
327                }
328                BackupError::Io => "the backup could not be written, or the data could not be read",
329                BackupError::AuditFailed => "the audit record could not be written",
330                BackupError::NoFileBackup => tenants::NO_FILE_BACKUP,
331            }),
332            CommandError::Tenant(e) => f.write_str(match e {
333                TenantError::NotFound => "no tenant has this id",
334                TenantError::NameTaken => "another tenant has this name",
335                TenantError::BadName => {
336                    "a tenant name is 1 to 128 characters, with no control characters and no space at either end"
337                }
338                TenantError::HoldsVcons => "the tenant holds vCons; add --force to remove them too",
339                TenantError::UnderHold => {
340                    "a vCon of the tenant is under a legal hold; only --override-holds removes it"
341                }
342                TenantError::BadScopes => {
343                    "a tenant key's scopes are one or more of write, read, delete, legal, audit and tenant_admin, each named once"
344                }
345                TenantError::BadExpiry => {
346                    "a key expires in 1 to 365 days, or never where keys.no_expiry allows it"
347                }
348                TenantError::LimitReached => {
349                    "the master key has wrapped all the tenant keys it may; run rekey master"
350                }
351                TenantError::AuditFailed => "the audit record could not be written",
352                TenantError::Closing => "the tenant is being removed",
353                TenantError::CliOnly => "only the command line may do this",
354                TenantError::BadSetting(_) => {
355                    "a setting's name or value is not one the tenant may set"
356                }
357                TenantError::WrongKey => unreachable!("matched above"),
358                TenantError::NoFileBackup => {
359                    "the registry is kept in PostgreSQL, which this backend does not copy into a file; back up the catalog database with pg_dump"
360                }
361                TenantError::Io => "the data could not be read or written",
362            }),
363        }
364    }
365}
366
367/// Runs `command` against the data directory `config` names, writing its
368/// answer to `out`.
369/// `vcon-server migrate`: makes or brings up to date the schema of the
370/// PostgreSQL catalog `config` names, and prints what it did. It uses no
371/// data directory and no master key.
372///
373/// # Errors
374///
375/// [`CommandError::Storage`] when the catalog is local, this build has no
376/// PostgreSQL support, or the migration was refused.
377pub fn migrate(config: &Config, out: &mut dyn Write) -> Result<(), CommandError> {
378    let done = backend::migrate_for_command(&config.catalog).map_err(CommandError::Storage)?;
379    line(out, &done)
380}
381
382pub fn run(config: &Config, command: &Command, out: &mut dyn Write) -> Result<(), CommandError> {
383    let sharing = command.work().sharing();
384    let _lock = datadir::lock(&config.data_dir, sharing).map_err(CommandError::DataDir)?;
385    let master = Key::load_master(&config.master_key).map_err(CommandError::MasterKey)?;
386    // With the catalogs in PostgreSQL the command holds the locks of its
387    // kind on the database, as it holds the data directory's: beside a
388    // server, or alone.
389    let catalogs = backend::catalog_for(&config.catalog, sharing).map_err(CommandError::Storage)?;
390    run_and_give_up(config, command, master, &catalogs, out)
391}
392
393/// Runs `command` on `catalogs`, and then gives up the command's locks on
394/// the catalog database, done or refused, while the connections still
395/// answer: the next command or server finds the database free at once.
396pub(crate) fn run_and_give_up(
397    config: &Config,
398    command: &Command,
399    master: Key,
400    catalogs: &backend::Catalogs,
401    out: &mut dyn Write,
402) -> Result<(), CommandError> {
403    let done = run_on(config, command, master, catalogs, out);
404    catalogs.give_up_locks();
405    done
406}
407
408/// Whether `command` opens the registry and its tenants as a command
409/// beside a server does: without start-up recovery, and with each tenant
410/// catalog's commits synced inside COMMIT (Durability::Beside). A command
411/// beside a running server must not run recovery: it would take the
412/// server's work in progress for a crash's leftovers. Nor does `check`,
413/// which reports what recovery would remove. Every other command holds
414/// the data directory alone and opens as a server does, recovery and the
415/// group sync of each tenant's commits included.
416pub(crate) fn opens_beside(command: &Command) -> bool {
417    command.work().sharing() == Sharing::Beside || matches!(command, Command::Check)
418}
419
420/// [`run`], with the data directory locked and the catalogs reached.
421fn run_on(
422    config: &Config,
423    command: &Command,
424    master: Key,
425    catalogs: &backend::Catalogs,
426    out: &mut dyn Write,
427) -> Result<(), CommandError> {
428    // A master rotation renames over server.sqlite, so nothing may hold it
429    // open: it runs before the registry is opened.
430    if let Command::RekeyMaster {
431        new_master,
432        to_backend,
433    } = command
434    {
435        return rekey_master(
436            config,
437            &master,
438            new_master,
439            to_backend.as_deref(),
440            catalogs,
441            out,
442        );
443    }
444    // Refused before anything is opened or claimed: a PostgreSQL catalog
445    // has no objects in a data directory to move.
446    if matches!(command, Command::StorageMoveObjects) && catalogs.server().is_some() {
447        return Err(nothing_to_move_on_a_database());
448    }
449    let open = if opens_beside(command) {
450        Tenants::open_beside_in
451    } else {
452        Tenants::open_in
453    };
454    let objects = backend::objects_for(&config.storage, &config.data_dir, catalogs)
455        .map_err(CommandError::Storage)?;
456    // The bucket the objects move to, for `storage move-objects`.
457    #[cfg(feature = "s3")]
458    let bucket = match &objects {
459        backend::ObjectPlace::S3(s3) => Some(s3.clone()),
460        backend::ObjectPlace::Local => None,
461    };
462    let tenants = open(
463        &config.data_dir,
464        master,
465        Arc::new(OsFs),
466        Arc::new(SystemClock),
467        objects,
468        catalogs,
469    )
470    .map_err(|e| match e {
471        RegistryError::WrongKey => CommandError::WrongMasterKey,
472        RegistryError::WrongDatabaseKey => CommandError::WrongDatabaseKey,
473        other => CommandError::Open(other),
474    })?;
475    tenants.allow_no_expiry(config.keys_no_expiry);
476    let who = Actor::Cli;
477    match command {
478        Command::TenantCreate { name, retention } => {
479            let retention = retention.as_deref().map(period).transpose()?;
480            let id = tenants.create(who, name, retention)?;
481            line(out, &serde_json::json!({ "id": id.to_string() }))
482        }
483        Command::TenantList => {
484            for tenant in tenants.list(who)? {
485                line(out, &tenant.to_json())?;
486            }
487            Ok(())
488        }
489        Command::TenantSetRetention { id, retention } => {
490            let retention = match retention.as_str() {
491                "default" => None,
492                text => Some(period(text)?),
493            };
494            let id = tenant_id(id)?;
495            tenants.set_retention(who, id, retention)?;
496            line(
497                out,
498                &serde_json::json!({
499                    "id": id.to_string(),
500                    "retention": retention.map(|r| r.to_string()),
501                }),
502            )
503        }
504        Command::TenantRemove {
505            id,
506            force,
507            override_holds,
508        } => {
509            let removal = match (force, override_holds) {
510                (_, true) => Removal::ForceOverridingHolds,
511                (true, false) => Removal::Force,
512                (false, false) => Removal::Empty,
513            };
514            Ok(tenants.remove(who, tenant_id(id)?, removal)?)
515        }
516        Command::KeyCreate { owner, label, life } => {
517            let (tenant, scopes) = match owner {
518                Owner::Tenant { id, scopes } => (
519                    Some(tenant_id(id)?),
520                    Scopes::named(scopes).ok_or(CommandError::Tenant(TenantError::BadScopes))?,
521                ),
522                Owner::Operator => (None, Scopes::of(&[Scope::Admin])),
523            };
524            let made = tenants.create_key_for(who, tenant, scopes, label, *life)?;
525            let shown = made
526                .to_json()
527                .ok_or(CommandError::Tenant(TenantError::Io))?;
528            line(out, &shown)
529        }
530        Command::KeyList { tenant } => {
531            let tenant = tenant.as_deref().map(tenant_id).transpose()?;
532            for key in tenants.list_keys(who, tenant)? {
533                let shown = key.to_json().ok_or(CommandError::Tenant(TenantError::Io))?;
534                line(out, &shown)?;
535            }
536            Ok(())
537        }
538        Command::KeyRevoke { id } => {
539            let id = KeyId::parse(id).ok_or(CommandError::UnknownKey)?;
540            tenants.revoke_key(who, id).map_err(|e| match e {
541                TenantError::NotFound => CommandError::UnknownKey,
542                other => CommandError::Tenant(other),
543            })
544        }
545        Command::UserAdd { label, identity } => {
546            let identity = identity.as_ref().map(|(issuer, subject)| Identity {
547                issuer: issuer.clone(),
548                subject: subject.clone(),
549            });
550            let id = tenants.add_user(who, label, identity.as_ref())?;
551            line(out, &serde_json::json!({ "id": id.to_string() }))
552        }
553        Command::UserList => {
554            for user in tenants.list_users(who)? {
555                let shown = user
556                    .to_json()
557                    .ok_or(CommandError::Tenant(TenantError::Io))?;
558                line(out, &shown)?;
559            }
560            Ok(())
561        }
562        Command::UserDeactivate { id } => Ok(tenants.deactivate_user(who, user_id(id)?)?),
563        Command::MembershipGrant { user, place } => {
564            let user = user_id(user)?;
565            let (tenant, roles) = match place {
566                Place::Tenant { id, roles } => (Some(tenant_id(id)?), named_roles(roles)?),
567                Place::Operator => (None, Roles::of(&[Role::Operator])),
568            };
569            let held = tenants.grant_membership(who, user, tenant, roles)?;
570            membership_line(out, user, tenant, held)
571        }
572        Command::MembershipRevoke { user, place } => {
573            let user = user_id(user)?;
574            // No role named takes every role the membership holds.
575            let (tenant, roles) = match place {
576                Place::Tenant { id, roles } if roles.is_empty() => (Some(tenant_id(id)?), None),
577                Place::Tenant { id, roles } => (Some(tenant_id(id)?), Some(named_roles(roles)?)),
578                Place::Operator => (None, None),
579            };
580            let left = tenants.revoke_membership(who, user, tenant, roles)?;
581            membership_line(out, user, tenant, left)
582        }
583        Command::TenantSetMetadata { id, metadata } => {
584            let level = crate::export::Metadata::parse(metadata)
585                .ok_or_else(|| CommandError::BadLevel(metadata.clone()))?;
586            let id = tenant_id(id)?;
587            tenants.set_metadata(who, id, level)?;
588            line(
589                out,
590                &serde_json::json!({ "id": id.to_string(), "metadata": level.as_str() }),
591            )
592        }
593        Command::TenantSetRoleCap { id, roles } => {
594            // A name that is no role's is refused as a cap that names
595            // operator is: neither can be a cap.
596            let cap = roles
597                .as_ref()
598                .map(|names| Roles::named(names).ok_or(CommandError::User(UserError::BadCap)))
599                .transpose()?;
600            let id = tenant_id(id)?;
601            tenants.set_role_cap(who, id, cap)?;
602            role_cap_line(out, id, cap)
603        }
604        Command::TenantRoleCap { id } => {
605            let id = tenant_id(id)?;
606            let cap = tenants.role_cap(who, id)?;
607            role_cap_line(out, id, cap)
608        }
609        Command::ExportParquet {
610            tenant,
611            to,
612            since,
613            until,
614        } => export_parquet(
615            config,
616            &tenants,
617            tenant,
618            to,
619            since.as_deref(),
620            until.as_deref(),
621            out,
622        ),
623        Command::RekeyTenant { id } => Ok(tenants.rekey_tenant(who, tenant_id(id)?)?),
624        Command::RekeyMaster { .. } => unreachable!("rotated before the registry is opened"),
625        Command::Check => check(config, &tenants, out),
626        #[cfg(feature = "s3")]
627        Command::StorageMoveObjects => match bucket {
628            Some(s3) => move_objects(config, &tenants, &s3, out),
629            None => Err(not_a_bucket()),
630        },
631        #[cfg(not(feature = "s3"))]
632        Command::StorageMoveObjects => Err(not_a_bucket()),
633        Command::Backup { to } => {
634            let done = tenants.backup(who, to).map_err(CommandError::Backup)?;
635            line(
636                out,
637                &serde_json::json!({
638                    "tenants": done.tenants,
639                    "versions": done.versions,
640                    "tries": done.tries,
641                }),
642            )
643        }
644        Command::AuditExport { log, since } => {
645            let exported = match log {
646                Log::Admin => tenants.export_admin(*since, out),
647                Log::Tenant(id) => tenants.store(tenant_id(id)?)?.export(*since, out),
648            };
649            exported.map_err(|e| match e {
650                AuditError::Write(e) => CommandError::Output(e),
651                AuditError::Sqlite(_) | AuditError::Database(_) => {
652                    CommandError::Tenant(TenantError::Io)
653                }
654            })
655        }
656    }
657}
658
659impl From<TenantError> for CommandError {
660    fn from(e: TenantError) -> CommandError {
661        CommandError::Tenant(e)
662    }
663}
664
665impl From<UserError> for CommandError {
666    /// A registry failure is the error every other command gives for it.
667    fn from(e: UserError) -> CommandError {
668        match e {
669            UserError::Registry(e) => CommandError::Tenant(e),
670            other => CommandError::User(other),
671        }
672    }
673}
674
675/// A user id as written; text that is no id names no user.
676fn user_id(text: &str) -> Result<UserId, CommandError> {
677    UserId::parse(text).ok_or(CommandError::User(UserError::NoUser))
678}
679
680/// The roles `names` name; a name that is no role's is refused as roles
681/// no membership can hold.
682fn named_roles(names: &[String]) -> Result<Roles, CommandError> {
683    Roles::named(names).ok_or(CommandError::User(UserError::BadRoles))
684}
685
686/// The line a role cap command prints: the tenant, and the roles of its
687/// cap or null for no cap.
688fn role_cap_line(
689    out: &mut dyn Write,
690    tenant: TenantId,
691    cap: Option<Roles>,
692) -> Result<(), CommandError> {
693    line(
694        out,
695        &serde_json::json!({
696            "id": tenant.to_string(),
697            "role_cap": cap.map(Roles::names),
698        }),
699    )
700}
701
702/// The line a membership command prints: the user, the tenant (null for
703/// an operator membership) and the roles the membership now holds.
704fn membership_line(
705    out: &mut dyn Write,
706    user: UserId,
707    tenant: Option<TenantId>,
708    roles: Roles,
709) -> Result<(), CommandError> {
710    line(
711        out,
712        &serde_json::json!({
713            "user": user.to_string(),
714            "tenant": tenant.map(|t| t.to_string()),
715            "roles": roles.names(),
716        }),
717    )
718}
719
720/// Exports a tenant's kept versions as Parquet files and prints what was
721/// written. Every argument is checked before anything is written.
722fn export_parquet(
723    config: &Config,
724    tenants: &Tenants,
725    tenant: &str,
726    to: &str,
727    since: Option<&str>,
728    until: Option<&str>,
729    out: &mut dyn Write,
730) -> Result<(), CommandError> {
731    use crate::export::target::Place;
732    use crate::export::{self, Plan};
733    let time = |text: Option<&str>| {
734        text.map(|t| {
735            OffsetDateTime::parse(t, &Rfc3339)
736                .map(crate::clock::nanos)
737                .map_err(|_| CommandError::BadTime(t.to_owned()))
738        })
739        .transpose()
740    };
741    let (since, until) = (time(since)?, time(until)?);
742    let place = Place::parse(to).ok_or_else(|| CommandError::BadTarget(to.to_owned()))?;
743    let id = tenant_id(tenant)?;
744    let level = tenants.metadata(id)?;
745    let target: Box<dyn export::Target> = match place {
746        Place::Dir(dir) => Box::new(export::DirTarget::new(&dir, Arc::new(OsFs))),
747        Place::S3 { bucket, prefix } => s3_target(config, &bucket, &prefix)?,
748    };
749    let store = tenants.store(id)?;
750    let plan = Plan {
751        level,
752        since,
753        until,
754        sizes: export::SIZES,
755        limits: vcon::read::Limits::new(config.inflated_limit),
756    };
757    let done = export::export(&store, &plan, target.as_ref(), SystemClock.now())
758        .map_err(CommandError::Export)?;
759    line(
760        out,
761        &serde_json::json!({
762            "tenant": id.to_string(),
763            "metadata": level.as_str(),
764            "to": target.describe(),
765            "manifest": done.manifest,
766            "seq": done.seq,
767            "files": done.files.len(),
768            "rows": done.rows,
769            "bytes": done.bytes,
770            "skipped": done.skipped,
771            "unread": done.unread,
772        }),
773    )
774}
775
776/// The bucket target `--to` names, reached through `[export.s3]`, else
777/// `[storage.s3]`'s service and keys.
778#[cfg(feature = "s3")]
779fn s3_target(
780    config: &Config,
781    bucket: &str,
782    prefix: &str,
783) -> Result<Box<dyn crate::export::Target>, CommandError> {
784    use crate::config::{ExportS3, ObjectStore};
785    let (service, table) = match (&config.export.s3, &config.storage.objects) {
786        (Some(service), _) => (service.clone(), "export.s3"),
787        (None, ObjectStore::S3(storage)) => (ExportS3::from(storage), "storage.s3"),
788        (None, ObjectStore::Local) => return Err(CommandError::NoS3),
789    };
790    let target = crate::export::s3::S3Target::connect(&service.for_bucket(bucket, prefix), table)
791        .map_err(CommandError::Storage)?;
792    Ok(Box::new(target))
793}
794
795#[cfg(not(feature = "s3"))]
796fn s3_target(
797    _config: &Config,
798    _bucket: &str,
799    _prefix: &str,
800) -> Result<Box<dyn crate::export::Target>, CommandError> {
801    Err(CommandError::NoS3)
802}
803
804/// How many rows of a table a master rotation in PostgreSQL reads and
805/// writes in one statement.
806#[cfg(feature = "postgres")]
807const REKEY_MASTER_BATCH: i64 = 1_000;
808
809/// The refusal of `storage move-objects` with the catalogs in PostgreSQL.
810fn nothing_to_move_on_a_database() -> CommandError {
811    CommandError::Storage(StorageError(
812        "storage move-objects moves the objects of a data directory's catalogs to the bucket; \
813         with catalog.backend = \"postgres\" every object is in the bucket from its first \
814         write and there is nothing to move: to move a data directory's objects, run it with \
815         the [catalog] and [catalog.postgres] tables removed"
816            .to_owned(),
817    ))
818}
819
820/// What the operator does after `rekey master`.
821const AFTER_REKEY_MASTER: &str = "point master_key in the configuration at the new key file, \
822                                  start the server, then destroy every copy of the old master key";
823
824/// The key backend `--to-backend` names, when this release moves keys to
825/// it: the master key file only.
826fn to_backend(name: &str) -> Result<(), CommandError> {
827    if name == "file" {
828        return Ok(());
829    }
830    Err(match BackendKind::from_name(name) {
831        Some(kind) => CommandError::BackendLater(kind),
832        None => CommandError::NoSuchBackend(name.to_owned()),
833    })
834}
835
836/// Rotates the master key, or with `to_backend` moves the registry root to
837/// that backend (in this release the master key file `new_master`), and
838/// says what the operator does next.
839fn rekey_master(
840    config: &Config,
841    master: &Key,
842    new_master: &std::path::Path,
843    to_backend: Option<&str>,
844    catalogs: &backend::Catalogs,
845    out: &mut dyn Write,
846) -> Result<(), CommandError> {
847    if let Some(name) = to_backend {
848        self::to_backend(name)?;
849    }
850    let new =
851        Key::load_master_named(new_master, "--new-master").map_err(CommandError::MasterKey)?;
852    if new.id() == master.id() {
853        return Err(CommandError::SameMasterKey);
854    }
855    // The master key file is the source: a registry whose root a key
856    // backend wraps is not under it.
857    tenants::refuse_wrapped_root(&config.data_dir, catalogs).map_err(CommandError::Open)?;
858    let moved = match catalogs {
859        backend::Catalogs::Local => Some(
860            tenants::rekey_root(
861                &config.data_dir,
862                &FileWrap::borrowing(master),
863                &FileWrap::borrowing(&new),
864                None,
865                SystemClock.now(),
866            )
867            .map_err(|e| match e {
868                TenantError::WrongKey => CommandError::WrongMasterKey,
869                other => CommandError::Tenant(other),
870            })?,
871        ),
872        // The registry's rows are made again under the new key in one
873        // transaction, with this command's locks held: no server and no
874        // other command has the database.
875        #[cfg(feature = "postgres")]
876        backend::Catalogs::Postgres(database) => {
877            backend::postgres::PgRegistry::rekey_master(database, master, &new, REKEY_MASTER_BATCH)
878                .map_err(|e| match e {
879                    TenantError::WrongKey => CommandError::WrongDatabaseKey,
880                    other => CommandError::Tenant(other),
881                })?;
882            None
883        }
884    };
885    let master_key_id = new.id().to_string();
886    if to_backend.is_none() {
887        return line(
888            out,
889            &serde_json::json!({
890                "master_key_id": master_key_id,
891                "next": AFTER_REKEY_MASTER,
892            }),
893        );
894    }
895    let mut report = serde_json::json!({
896        "backend": "file",
897        "master_key_id": master_key_id,
898        "next": AFTER_REKEY_MASTER,
899    });
900    // A PostgreSQL registry moves in one transaction, which does not say
901    // whether a run before had moved it.
902    match moved {
903        Some(tenants::Moved::Tenants(n)) => {
904            report["moved"] = true.into();
905            report["tenants"] = n.into();
906        }
907        Some(tenants::Moved::Already) => report["moved"] = false.into(),
908        None => {}
909    }
910    line(out, &report)
911}
912
913/// Examines every tenant, prints a line for each and a summary, and fails
914/// when anything needs the operator.
915/// The refusal of `storage move-objects` with the objects kept in the data
916/// directory.
917fn not_a_bucket() -> CommandError {
918    CommandError::Storage(StorageError(
919        "storage move-objects moves the objects to the bucket that storage.objects = \"s3\" \
920         names; this configuration keeps them in the data directory"
921            .to_owned(),
922    ))
923}
924
925/// `storage move-objects`: each tenant's object files, under its directory
926/// in the data directory, moved to the bucket, as `backend::migrate` does;
927/// one line per tenant with what moved and what `check` then finds missing,
928/// and a total.
929#[cfg(feature = "s3")]
930fn move_objects(
931    config: &Config,
932    tenants: &Tenants,
933    s3: &Arc<crate::backend::s3::S3>,
934    out: &mut dyn Write,
935) -> Result<(), CommandError> {
936    use crate::backend::migrate::MoveError;
937    let mut total = 0;
938    for id in tenants.ids()? {
939        let dir = config
940            .data_dir
941            .join("tenants")
942            .join(id.to_string())
943            .join("objects");
944        let moved = if dir.exists() {
945            let from = crate::backend::local::LocalObjects::new(dir, Arc::new(OsFs));
946            crate::backend::migrate::move_objects(&from, &s3.tenant(id)).map_err(|e| {
947                let why = match e {
948                    MoveError::From(e) => {
949                        format!("an object file could not be read or removed: {e}")
950                    }
951                    MoveError::To(e) => format!("the bucket could not be written or read: {e}"),
952                    MoveError::Differs(version) => format!(
953                        "version {version} read back from the bucket differs from its file, \
954                         which stays in the data directory"
955                    ),
956                };
957                CommandError::Move { tenant: id, why }
958            })?
959        } else {
960            0
961        };
962        let missing = tenants
963            .store(id)?
964            .check()
965            .map_err(|e| CommandError::Move {
966                tenant: id,
967                why: format!("the objects in the bucket could not be checked: {e:?}"),
968            })?
969            .len();
970        total += moved;
971        line(
972            out,
973            &serde_json::json!({ "tenant": id.to_string(), "moved": moved, "missing": missing }),
974        )?;
975    }
976    line(out, &serde_json::json!({ "moved": total }))
977}
978
979fn check(config: &Config, tenants: &Tenants, out: &mut dyn Write) -> Result<(), CommandError> {
980    let now = SystemClock.now();
981    let found = tenants.examine(config.retention_default, now)?;
982    let time = |at: Option<OffsetDateTime>| at.and_then(|at| at.format(&Rfc3339).ok());
983    let mut total = 0;
984    for tenant in &found.tenants {
985        let named = problems(
986            tenant,
987            config.purge_interval,
988            now,
989            config.storage.parquet.is_some(),
990        );
991        total += named.len();
992        let store = tenant.store.as_ref().ok();
993        line(
994            out,
995            &serde_json::json!({
996                "tenant": tenant.id.to_string(),
997                "name": tenant.name,
998                "versions": store.map(|s| s.versions),
999                "packed": store.map(|s| s.packed),
1000                "damaged": store.map(|s| s.damaged.iter().map(ToString::to_string).collect::<Vec<_>>()),
1001                "leftovers": store.map(|s| &s.leftovers),
1002                "past_due": store.map(|s| s.due),
1003                "oldest_past_due": time(store.and_then(|s| s.oldest_due_since)),
1004                "purges_awaiting_rotation": store.map(|s| s.purges_since_key),
1005                "oldest_purge_awaiting_rotation": time(store.and_then(|s| s.oldest_purge_since_key)),
1006                "rotation_stopped": tenant.rotation_stopped,
1007                "problems": named,
1008            }),
1009        )?;
1010    }
1011    line(
1012        out,
1013        &serde_json::json!({
1014            "tenants": found.tenants.len(),
1015            "removed_tenants_awaiting_master_rotation": found.removed_since_master,
1016            "oldest_removal_awaiting_master_rotation": time(found.oldest_removed_since_master),
1017            "problems": total,
1018        }),
1019    )?;
1020    match total {
1021        0 => Ok(()),
1022        n => Err(CommandError::CheckFound(n)),
1023    }
1024}
1025
1026/// What in one tenant's examination needs the operator. A stalled sweep is
1027/// one whose oldest due version has waited longer than `purge_interval`;
1028/// a shorter wait is the next sweep's work. Packed versions are a problem
1029/// when the configuration has no `[storage.parquet]` (`parquet` false),
1030/// since `serve` then refuses to start. Leftover files and work waiting
1031/// for rotation are reported but are not problems.
1032pub fn problems(
1033    tenant: &TenantExamination,
1034    purge_interval: std::time::Duration,
1035    now: OffsetDateTime,
1036    parquet: bool,
1037) -> Vec<String> {
1038    let mut found = Vec::new();
1039    if tenant.rotation_stopped {
1040        found.push("a key rotation was stopped part way; run rekey tenant again".to_owned());
1041    }
1042    match &tenant.store {
1043        Err(Unexamined::Open(OpenFailure::WrongKey)) => {
1044            found.push("its catalog does not open under its tenant key".to_owned());
1045        }
1046        Err(Unexamined::Open(OpenFailure::Access { path, error })) => {
1047            found.push(format!(
1048                "its catalog cannot be opened: {}: {error}",
1049                path.display()
1050            ));
1051        }
1052        Err(Unexamined::Open(OpenFailure::Refused(e))) => {
1053            found.push(format!("its catalog cannot be opened: {e:?}"));
1054        }
1055        Err(Unexamined::Examine(ExamineError::Objects { kind, os_error })) => {
1056            let number = os_error
1057                .map(|n| format!(" (os error {n})"))
1058                .unwrap_or_default();
1059            found.push(format!("its objects cannot be read: {kind}{number}"));
1060        }
1061        Err(Unexamined::Examine(ExamineError::Failed(e))) => {
1062            found.push(format!("it could not be examined: {e:?}"));
1063        }
1064        Ok(store) => {
1065            if store.packed > 0 && !parquet {
1066                found.push(format!(
1067                    "{} version(s) are packed into Parquet files, and the configuration has no \
1068                     [storage.parquet]: serve refuses to start until the table is put back",
1069                    store.packed
1070                ));
1071            }
1072            for version in &store.damaged {
1073                found.push(format!("version {version} is missing or does not open"));
1074            }
1075            if let Some(since) = store.oldest_due_since
1076                && now - since > purge_interval
1077            {
1078                found.push(format!(
1079                    "{} version(s) due for purge, the oldest longer than purge_interval: the sweep is not keeping up",
1080                    store.due
1081                ));
1082            }
1083        }
1084    }
1085    found
1086}
1087
1088/// A period as a command line writes it.
1089fn period(text: &str) -> Result<Retention, CommandError> {
1090    Retention::parse(text).ok_or_else(|| CommandError::BadPeriod(text.to_owned()))
1091}
1092
1093/// A tenant id as a command line writes it; one that does not parse names
1094/// no tenant.
1095fn tenant_id(text: &str) -> Result<TenantId, CommandError> {
1096    TenantId::parse(text).ok_or(CommandError::Tenant(TenantError::NotFound))
1097}
1098
1099/// Writes one JSON object as a line.
1100fn line(out: &mut dyn Write, value: &serde_json::Value) -> Result<(), CommandError> {
1101    writeln!(out, "{value}").map_err(CommandError::Output)
1102}
1103
1104#[cfg(test)]
1105mod tests {
1106    use serde_json::{Value, json};
1107
1108    use super::*;
1109    use crate::store::Caller;
1110    use crate::store::testing::vcon;
1111
1112    const UUID: &str = "01a07da8-c2bb-83e5-b9a2-279e0d16bc46";
1113
1114    // Which opener each command uses: a command alone on the data
1115    // directory opens as a server does (recovery, group sync); one beside
1116    // a server, and `check`, open beside.
1117
1118    #[test]
1119    fn a_tenant_create_opens_as_the_directory_s_only_writer() {
1120        let command = Command::TenantCreate {
1121            name: "acme".to_owned(),
1122            retention: None,
1123        };
1124        assert!(!opens_beside(&command), "alone: recovery and group sync");
1125    }
1126
1127    #[test]
1128    fn a_tenant_removal_opens_as_the_directory_s_only_writer() {
1129        let command = Command::TenantRemove {
1130            id: "t".to_owned(),
1131            force: false,
1132            override_holds: false,
1133        };
1134        assert!(!opens_beside(&command), "alone: recovery and group sync");
1135    }
1136
1137    #[test]
1138    fn a_tenant_rekey_opens_as_the_directory_s_only_writer() {
1139        let command = Command::RekeyTenant { id: "t".to_owned() };
1140        assert!(!opens_beside(&command), "alone: recovery and group sync");
1141    }
1142
1143    #[test]
1144    fn moving_objects_opens_as_the_directory_s_only_writer() {
1145        assert!(
1146            !opens_beside(&Command::StorageMoveObjects),
1147            "alone: recovery and group sync"
1148        );
1149    }
1150
1151    #[test]
1152    fn a_tenant_list_opens_beside_a_server() {
1153        assert!(
1154            opens_beside(&Command::TenantList),
1155            "beside: no recovery, commits synced inside COMMIT"
1156        );
1157    }
1158
1159    #[test]
1160    fn an_audit_export_opens_beside_a_server() {
1161        let command = Command::AuditExport {
1162            log: Log::Admin,
1163            since: None,
1164        };
1165        assert!(
1166            opens_beside(&command),
1167            "beside: no recovery, commits synced inside COMMIT"
1168        );
1169    }
1170
1171    #[test]
1172    fn a_key_create_opens_beside_a_server() {
1173        let command = Command::KeyCreate {
1174            owner: Owner::Operator,
1175            label: "ops".to_owned(),
1176            life: KeyLife::default(),
1177        };
1178        assert!(
1179            opens_beside(&command),
1180            "beside: no recovery, commits synced inside COMMIT"
1181        );
1182    }
1183
1184    #[test]
1185    fn a_backup_opens_beside_a_server() {
1186        let command = Command::Backup {
1187            to: std::path::PathBuf::from("/nonexistent/backup"),
1188        };
1189        assert!(
1190            opens_beside(&command),
1191            "beside: no recovery, commits synced inside COMMIT"
1192        );
1193    }
1194
1195    /// `check` runs alone, but opens beside: it reports what recovery would
1196    /// remove, so it must not run recovery.
1197    #[test]
1198    fn check_runs_alone_and_still_opens_beside() {
1199        assert_eq!(
1200            Command::Check.work().sharing(),
1201            Sharing::Alone,
1202            "check holds the directory alone"
1203        );
1204        assert!(opens_beside(&Command::Check), "and opens without recovery");
1205    }
1206
1207    struct Setup {
1208        _dir: tempfile::TempDir,
1209        config: Config,
1210    }
1211
1212    fn chmod(path: &std::path::Path, mode: u32) {
1213        use std::os::unix::fs::PermissionsExt;
1214        std::fs::set_permissions(path, std::fs::Permissions::from_mode(mode)).expect("chmod");
1215    }
1216
1217    fn setup() -> Setup {
1218        let dir = tempfile::tempdir().expect("temp dir");
1219        let data = dir.path().join("data");
1220        std::fs::create_dir(&data).expect("data dir");
1221        let master = dir.path().join("master.key");
1222        std::fs::write(&master, [0x5a; 32]).expect("master key file");
1223        chmod(&master, 0o600);
1224        let config = crate::config::parse(&format!(
1225            "listen = \"127.0.0.1:1\"\ndata_dir = {data:?}\nmaster_key = {master:?}\n\
1226             [tls]\ncert = \"c\"\nkey = \"k\"\n"
1227        ))
1228        .expect("a configuration");
1229        Setup { _dir: dir, config }
1230    }
1231
1232    impl Setup {
1233        /// Runs `command` and parses each line it prints.
1234        fn run(&self, command: Command) -> Result<Vec<Value>, CommandError> {
1235            let mut out = Vec::new();
1236            run(&self.config, &command, &mut out)?;
1237            Ok(String::from_utf8(out)
1238                .expect("text")
1239                .lines()
1240                .map(|line| serde_json::from_str(line).expect("a JSON line"))
1241                .collect())
1242        }
1243
1244        fn create(&self, name: &str) -> String {
1245            let out = self
1246                .run(Command::TenantCreate {
1247                    name: name.to_owned(),
1248                    retention: None,
1249                })
1250                .expect("made");
1251            out[0]["id"].as_str().expect("an id").to_owned()
1252        }
1253
1254        /// The registry as a test reads it, with the command's locks free.
1255        fn tenants(&self) -> Tenants {
1256            Tenants::open_beside(
1257                &self.config.data_dir,
1258                Key::load_master(&self.config.master_key).expect("master"),
1259                Arc::new(OsFs),
1260                Arc::new(SystemClock),
1261            )
1262            .expect("opens")
1263        }
1264
1265        fn tenant_dirs(&self) -> Vec<String> {
1266            let mut names: Vec<String> = std::fs::read_dir(self.config.data_dir.join("tenants"))
1267                .expect("tenants dir")
1268                .map(|e| e.expect("entry").file_name().to_string_lossy().into_owned())
1269                .collect();
1270            names.sort();
1271            names
1272        }
1273    }
1274
1275    /// `key create` for a tenant key that reads, with this life.
1276    fn key_with(s: &Setup, tenant: &str, life: KeyLife) -> Result<Vec<Value>, CommandError> {
1277        s.run(Command::KeyCreate {
1278            owner: Owner::Tenant {
1279                id: tenant.to_owned(),
1280                scopes: vec!["read".to_owned()],
1281            },
1282            label: "dated".to_owned(),
1283            life,
1284        })
1285    }
1286
1287    fn rfc3339(value: &Value) -> time::OffsetDateTime {
1288        time::OffsetDateTime::parse(
1289            value.as_str().expect("a time as text"),
1290            &time::format_description::well_known::Rfc3339,
1291        )
1292        .expect("RFC 3339")
1293    }
1294
1295    /// The second a key was made in. A key's expiry is a whole second:
1296    /// its life is counted from here.
1297    fn made_in(value: &Value) -> time::OffsetDateTime {
1298        rfc3339(value)
1299            .replace_nanosecond(0)
1300            .expect("zero is in range")
1301    }
1302
1303    #[test]
1304    fn key_create_prints_the_expiry_of_the_key_it_makes() {
1305        let s = setup();
1306        let tenant = s.create("acme");
1307        let made = key_with(&s, &tenant, KeyLife::Default).expect("made");
1308        let listed = s.run(Command::KeyList { tenant: None }).expect("listed");
1309        assert_eq!(
1310            rfc3339(&made[0]["expires_at"]) - made_in(&listed[0]["created_at"]),
1311            time::Duration::days(90),
1312            "the default life"
1313        );
1314        assert_eq!(
1315            made[0]["expires_at"], listed[0]["expires_at"],
1316            "the list shows the same expiry"
1317        );
1318        assert!(listed[0]["last_used_at"].is_null(), "a key never used");
1319    }
1320
1321    #[test]
1322    fn key_create_makes_a_key_for_the_days_asked_or_with_no_expiry() {
1323        let s = setup();
1324        let tenant = s.create("acme");
1325        let week = key_with(&s, &tenant, KeyLife::Days(7)).expect("made");
1326        let never = key_with(&s, &tenant, KeyLife::Never).expect("made");
1327        let listed = s.run(Command::KeyList { tenant: None }).expect("listed");
1328        assert_eq!(
1329            rfc3339(&week[0]["expires_at"]) - made_in(&listed[0]["created_at"]),
1330            time::Duration::days(7),
1331            "seven days"
1332        );
1333        assert!(
1334            never[0]["expires_at"].is_null(),
1335            "no expiry is printed as null"
1336        );
1337        assert!(listed[1]["expires_at"].is_null(), "and listed as null");
1338    }
1339
1340    #[test]
1341    fn key_create_refuses_days_outside_1_to_365() {
1342        let s = setup();
1343        let tenant = s.create("acme");
1344        for days in [0, 366] {
1345            assert!(
1346                matches!(
1347                    key_with(&s, &tenant, KeyLife::Days(days)),
1348                    Err(CommandError::Tenant(TenantError::BadExpiry))
1349                ),
1350                "{days} days"
1351            );
1352        }
1353        let listed = s.run(Command::KeyList { tenant: None }).expect("listed");
1354        assert_eq!(listed.len(), 0, "no key was made");
1355    }
1356
1357    #[test]
1358    fn key_create_refuses_no_expiry_where_the_configuration_says_so() {
1359        let mut s = setup();
1360        let tenant = s.create("acme");
1361        s.config.keys_no_expiry = false;
1362        assert!(
1363            matches!(
1364                key_with(&s, &tenant, KeyLife::Never),
1365                Err(CommandError::Tenant(TenantError::BadExpiry))
1366            ),
1367            "a tenant key"
1368        );
1369        let operator = s.run(Command::KeyCreate {
1370            owner: Owner::Operator,
1371            label: "ops".to_owned(),
1372            life: KeyLife::Never,
1373        });
1374        assert!(
1375            matches!(operator, Err(CommandError::Tenant(TenantError::BadExpiry))),
1376            "an operator key"
1377        );
1378        assert!(
1379            key_with(&s, &tenant, KeyLife::Default).is_ok(),
1380            "a key with an expiry is still made"
1381        );
1382    }
1383
1384    #[test]
1385    fn an_operator_key_may_have_no_expiry_by_default() {
1386        let s = setup();
1387        let made = s
1388            .run(Command::KeyCreate {
1389                owner: Owner::Operator,
1390                label: "ops".to_owned(),
1391                life: KeyLife::Never,
1392            })
1393            .expect("made");
1394        assert!(made[0]["expires_at"].is_null(), "no expiry");
1395    }
1396
1397    fn tenant_error(result: Result<Vec<Value>, CommandError>) -> TenantError {
1398        match result {
1399            Err(CommandError::Tenant(e)) => e,
1400            // What a command prints is not shown: `key create` prints a token.
1401            Ok(_) => panic!("the command succeeded, and a tenant error was expected"),
1402            Err(other) => panic!("not a tenant error: {other:?}"),
1403        }
1404    }
1405
1406    #[test]
1407    fn tenant_create_prints_the_new_id_and_list_shows_it() {
1408        let s = setup();
1409        let out = s
1410            .run(Command::TenantCreate {
1411                name: "acme".to_owned(),
1412                retention: Some("18m".to_owned()),
1413            })
1414            .expect("made");
1415        assert_eq!(out.len(), 1);
1416        let id = out[0]["id"].as_str().expect("an id").to_owned();
1417        assert!(TenantId::parse(&id).is_some(), "{id}");
1418        assert_eq!(out[0], json!({ "id": id }));
1419        let beta = s.create("beta");
1420        assert_eq!(
1421            s.run(Command::TenantList).expect("listed"),
1422            [
1423                json!({ "id": id, "name": "acme", "retention": "18m", "metadata": "none" }),
1424                json!({ "id": beta, "name": "beta", "retention": null, "metadata": "none" }),
1425            ]
1426        );
1427    }
1428
1429    #[test]
1430    fn a_bad_period_is_refused_before_anything_is_made() {
1431        let s = setup();
1432        let error = s
1433            .run(Command::TenantCreate {
1434                name: "acme".to_owned(),
1435                retention: Some("7w".to_owned()),
1436            })
1437            .expect_err("refused");
1438        assert!(
1439            matches!(&error, CommandError::BadPeriod(p) if p == "7w"),
1440            "{error:?}"
1441        );
1442        assert!(error.to_string().contains("7w"), "{error}");
1443        assert_eq!(
1444            s.run(Command::TenantList).expect("listed"),
1445            Vec::<Value>::new()
1446        );
1447        let id = s.create("acme");
1448        let error = s
1449            .run(Command::TenantSetRetention {
1450                id,
1451                retention: "forever".to_owned(),
1452            })
1453            .expect_err("refused");
1454        assert!(matches!(&error, CommandError::BadPeriod(p) if p == "forever"));
1455    }
1456
1457    #[test]
1458    fn set_retention_takes_a_period_or_default() {
1459        let s = setup();
1460        let id = s.create("acme");
1461        let set = |retention: &str| {
1462            s.run(Command::TenantSetRetention {
1463                id: id.clone(),
1464                retention: retention.to_owned(),
1465            })
1466            .expect("set")
1467        };
1468        assert_eq!(set("90d"), [json!({ "id": id, "retention": "90d" })]);
1469        assert_eq!(
1470            s.run(Command::TenantList).expect("listed")[0]["retention"],
1471            "90d"
1472        );
1473        assert_eq!(set("default"), [json!({ "id": id, "retention": null })]);
1474        assert_eq!(
1475            s.run(Command::TenantList).expect("listed")[0]["retention"],
1476            Value::Null
1477        );
1478    }
1479
1480    #[test]
1481    fn an_unknown_or_malformed_tenant_is_not_found() {
1482        let s = setup();
1483        for id in [TenantId::generate().to_string(), "not-an-id".to_owned()] {
1484            assert_eq!(
1485                tenant_error(s.run(Command::TenantSetRetention {
1486                    id: id.clone(),
1487                    retention: "7y".to_owned()
1488                })),
1489                TenantError::NotFound
1490            );
1491            assert_eq!(
1492                tenant_error(s.run(Command::TenantRemove {
1493                    id: id.clone(),
1494                    force: true,
1495                    override_holds: false
1496                })),
1497                TenantError::NotFound
1498            );
1499            assert_eq!(
1500                tenant_error(s.run(Command::KeyCreate {
1501                    owner: Owner::Tenant {
1502                        id: id.clone(),
1503                        scopes: vec!["read".to_owned()]
1504                    },
1505                    label: "l".to_owned(),
1506                    life: KeyLife::Default,
1507                })),
1508                TenantError::NotFound
1509            );
1510            assert_eq!(
1511                tenant_error(s.run(Command::KeyList {
1512                    tenant: Some(id.clone())
1513                })),
1514                TenantError::NotFound
1515            );
1516            assert_eq!(
1517                tenant_error(s.run(Command::AuditExport {
1518                    log: Log::Tenant(id.clone()),
1519                    since: None
1520                })),
1521                TenantError::NotFound
1522            );
1523        }
1524    }
1525
1526    /// Without --force a tenant holding vCons stays; --force does not pass
1527    /// a legal hold; --override-holds does.
1528    #[test]
1529    fn remove_goes_as_far_as_its_flags_allow() {
1530        let s = setup();
1531        let empty = s.create("empty");
1532        let full = s.create("full");
1533        {
1534            let tenants = s.tenants();
1535            let store = tenants
1536                .store(TenantId::parse(&full).expect("id"))
1537                .expect("store");
1538            let caller = Caller { key: KeyId([1; 8]) };
1539            let (found, body) = vcon(UUID, "kept");
1540            store.create(&caller, &found, &body).expect("stored");
1541            store.set_hold(&caller, found.uuid, true).expect("held");
1542        }
1543        let remove = |id: &str, force, override_holds| {
1544            s.run(Command::TenantRemove {
1545                id: id.to_owned(),
1546                force,
1547                override_holds,
1548            })
1549        };
1550        assert_eq!(
1551            remove(&empty, false, false).expect("removed"),
1552            Vec::<Value>::new()
1553        );
1554        assert_eq!(
1555            tenant_error(remove(&full, false, false)),
1556            TenantError::HoldsVcons
1557        );
1558        assert_eq!(
1559            tenant_error(remove(&full, true, false)),
1560            TenantError::UnderHold
1561        );
1562        assert_eq!(
1563            remove(&full, true, true).expect("removed"),
1564            Vec::<Value>::new()
1565        );
1566        assert_eq!(
1567            s.run(Command::TenantList).expect("listed"),
1568            Vec::<Value>::new()
1569        );
1570        assert_eq!(s.tenant_dirs(), Vec::<String>::new());
1571    }
1572
1573    #[test]
1574    fn keys_are_made_listed_and_revoked() {
1575        let s = setup();
1576        let tenant = s.create("acme");
1577        let made = s
1578            .run(Command::KeyCreate {
1579                owner: Owner::Tenant {
1580                    id: tenant.clone(),
1581                    scopes: vec!["write".to_owned(), "read".to_owned()],
1582                },
1583                label: "producer".to_owned(),
1584                life: KeyLife::Default,
1585            })
1586            .expect("made");
1587        let id = made[0]["id"].as_str().expect("id").to_owned();
1588        let token = made[0]["token"].as_str().expect("token").to_owned();
1589        assert_eq!(made.len(), 1);
1590        assert_eq!(made[0].as_object().expect("object").len(), 3);
1591        assert!(
1592            token.starts_with(&format!("vcs_{id}_")),
1593            "the token starts with vcs_ and the key's id {id}"
1594        );
1595        let operator = s
1596            .run(Command::KeyCreate {
1597                owner: Owner::Operator,
1598                label: "ops".to_owned(),
1599                life: KeyLife::Default,
1600            })
1601            .expect("made")[0]["id"]
1602            .as_str()
1603            .expect("id")
1604            .to_owned();
1605
1606        let listed = s.run(Command::KeyList { tenant: None }).expect("listed");
1607        assert_eq!(listed.len(), 2);
1608        assert_eq!(listed[0]["id"], id.as_str());
1609        assert_eq!(listed[0]["tenant"], tenant.as_str());
1610        assert_eq!(listed[0]["scopes"], json!(["write", "read"]));
1611        assert_eq!(listed[0]["label"], "producer");
1612        assert_eq!(listed[0]["revoked_at"], Value::Null);
1613        assert!(
1614            listed[0]["created_at"]
1615                .as_str()
1616                .is_some_and(|t| t.ends_with('Z'))
1617        );
1618        assert!(
1619            listed.iter().all(|k| k.get("token").is_none()),
1620            "never a token"
1621        );
1622        assert_eq!(listed[1]["id"], operator.as_str());
1623        assert_eq!(listed[1]["tenant"], Value::Null);
1624        assert_eq!(listed[1]["scopes"], json!(["admin"]));
1625
1626        let own = s
1627            .run(Command::KeyList {
1628                tenant: Some(tenant.clone()),
1629            })
1630            .expect("listed");
1631        assert_eq!(own, listed[..1]);
1632
1633        assert_eq!(
1634            s.run(Command::KeyRevoke { id: id.clone() })
1635                .expect("revoked"),
1636            Vec::<Value>::new()
1637        );
1638        let listed = s.run(Command::KeyList { tenant: None }).expect("listed");
1639        assert!(listed[0]["revoked_at"].as_str().is_some(), "{listed:?}");
1640        assert_eq!(listed[1]["revoked_at"], Value::Null);
1641    }
1642
1643    #[test]
1644    fn bad_scopes_and_unknown_keys_are_refused() {
1645        let s = setup();
1646        let tenant = s.create("acme");
1647        for scopes in [
1648            vec!["superuser"],
1649            vec!["read", "superuser"],
1650            vec!["read", "read"],
1651            vec!["admin"],
1652            vec![],
1653        ] {
1654            let error = s.run(Command::KeyCreate {
1655                owner: Owner::Tenant {
1656                    id: tenant.clone(),
1657                    scopes: scopes.iter().map(|s| (*s).to_owned()).collect(),
1658                },
1659                label: "l".to_owned(),
1660                life: KeyLife::Default,
1661            });
1662            assert_eq!(tenant_error(error), TenantError::BadScopes, "{scopes:?}");
1663        }
1664        assert_eq!(
1665            s.run(Command::KeyList { tenant: None }).expect("listed"),
1666            Vec::<Value>::new()
1667        );
1668        for id in ["0123456789abcdef".to_owned(), "nope".to_owned()] {
1669            assert!(
1670                matches!(
1671                    s.run(Command::KeyRevoke { id }),
1672                    Err(CommandError::UnknownKey)
1673                ),
1674                "unknown"
1675            );
1676        }
1677    }
1678
1679    #[test]
1680    fn audit_export_writes_either_log_from_a_sequence_number() {
1681        let s = setup();
1682        let tenant = s.create("acme");
1683        s.run(Command::TenantList).expect("listed");
1684        s.run(Command::KeyCreate {
1685            owner: Owner::Tenant {
1686                id: tenant.clone(),
1687                scopes: vec!["read".to_owned()],
1688            },
1689            label: "l".to_owned(),
1690            life: KeyLife::Default,
1691        })
1692        .expect("made");
1693
1694        let admin = s
1695            .run(Command::AuditExport {
1696                log: Log::Admin,
1697                since: None,
1698            })
1699            .expect("exported");
1700        let actions: Vec<&str> = admin
1701            .iter()
1702            .map(|r| r["action"].as_str().expect("action"))
1703            .collect();
1704        assert_eq!(actions, ["tenant_create", "tenant_list", "key_create"]);
1705        assert!(admin.iter().all(|r| r["actor"] == "cli"));
1706        let since = admin[0]["seq"].as_i64().expect("seq");
1707        let later = s
1708            .run(Command::AuditExport {
1709                log: Log::Admin,
1710                since: Some(since),
1711            })
1712            .expect("exported");
1713        assert_eq!(later, admin[1..]);
1714
1715        let own = s
1716            .run(Command::AuditExport {
1717                log: Log::Tenant(tenant),
1718                since: None,
1719            })
1720            .expect("exported");
1721        let actions: Vec<&str> = own
1722            .iter()
1723            .map(|r| r["action"].as_str().expect("action"))
1724            .collect();
1725        assert_eq!(actions, ["key_create"]);
1726    }
1727
1728    #[test]
1729    fn rekey_tenant_rotates_the_key_and_prints_nothing() {
1730        let s = setup();
1731        let id = s.create("acme");
1732        let tenant = TenantId::parse(&id).expect("id");
1733        let before = s.tenants().tenant_key_id_for_test(tenant);
1734        assert_eq!(
1735            s.run(Command::RekeyTenant { id: id.clone() })
1736                .expect("rekeyed"),
1737            Vec::<Value>::new()
1738        );
1739        assert_ne!(s.tenants().tenant_key_id_for_test(tenant), before);
1740        assert_eq!(
1741            tenant_error(s.run(Command::RekeyTenant {
1742                id: TenantId::generate().to_string()
1743            })),
1744            TenantError::NotFound
1745        );
1746        let server = datadir::lock(&s.config.data_dir, Sharing::Serve).expect("a server");
1747        assert!(matches!(
1748            s.run(Command::RekeyTenant { id }),
1749            Err(CommandError::DataDir(LockError::InUse(Sharing::Alone)))
1750        ));
1751        drop(server);
1752    }
1753
1754    #[test]
1755    fn rekey_master_moves_the_data_to_the_new_master_key() {
1756        let mut s = setup();
1757        s.create("acme");
1758        let new_file = s.config.master_key.with_file_name("new.key");
1759        std::fs::write(&new_file, [0x5c; 32]).expect("new key");
1760        chmod(&new_file, 0o600);
1761        assert!(matches!(
1762            s.run(Command::RekeyMaster {
1763                new_master: s.config.master_key.clone(),
1764                to_backend: None,
1765            }),
1766            Err(CommandError::SameMasterKey)
1767        ));
1768        let server = datadir::lock(&s.config.data_dir, Sharing::Serve).expect("a server");
1769        assert!(matches!(
1770            s.run(Command::RekeyMaster {
1771                new_master: new_file.clone(),
1772                to_backend: None,
1773            }),
1774            Err(CommandError::DataDir(LockError::InUse(Sharing::Alone)))
1775        ));
1776        drop(server);
1777        let out = s
1778            .run(Command::RekeyMaster {
1779                new_master: new_file.clone(),
1780                to_backend: None,
1781            })
1782            .expect("rotated");
1783        let new_id = Key::load_master(&new_file).expect("key").id().to_string();
1784        assert_eq!(out.len(), 1);
1785        assert_eq!(out[0]["master_key_id"], new_id.as_str());
1786        assert!(
1787            out[0]["next"]
1788                .as_str()
1789                .is_some_and(|n| n.contains("destroy"))
1790        );
1791        assert!(matches!(
1792            s.run(Command::TenantList),
1793            Err(CommandError::WrongMasterKey)
1794        ));
1795        s.config.master_key = new_file;
1796        assert_eq!(s.run(Command::TenantList).expect("listed").len(), 1);
1797    }
1798
1799    mod check {
1800        use time::macros::datetime;
1801
1802        use super::*;
1803        use crate::ids::VersionId;
1804        use crate::store::{Examination, StoreError};
1805
1806        const NOW: OffsetDateTime = datetime!(2026-10-25 12:00 UTC);
1807        const HOUR: std::time::Duration = std::time::Duration::from_secs(3600);
1808
1809        fn sound() -> Examination {
1810            Examination {
1811                versions: 3,
1812                packed: 0,
1813                damaged: vec![],
1814                leftovers: vec!["a.tmp".to_owned()],
1815                due: 0,
1816                oldest_due_since: None,
1817                purges_since_key: 4,
1818                oldest_purge_since_key: Some(datetime!(2026-10-01 00:00 UTC)),
1819            }
1820        }
1821
1822        fn tenant(store: Result<Examination, Unexamined>, stopped: bool) -> TenantExamination {
1823            TenantExamination {
1824                id: TenantId([1; 16]),
1825                name: "acme".to_owned(),
1826                rotation_stopped: stopped,
1827                store,
1828            }
1829        }
1830
1831        #[test]
1832        fn leftovers_and_work_waiting_for_rotation_are_not_problems() {
1833            assert_eq!(
1834                problems(&tenant(Ok(sound()), false), HOUR, NOW, true),
1835                Vec::<String>::new()
1836            );
1837        }
1838
1839        #[test]
1840        fn each_problem_is_named() {
1841            let damaged = Examination {
1842                damaged: vec![VersionId([2; 16]), VersionId([3; 16])],
1843                ..sound()
1844            };
1845            assert_eq!(
1846                problems(&tenant(Ok(damaged), false), HOUR, NOW, true),
1847                [
1848                    "version 02020202020202020202020202020202 is missing or does not open",
1849                    "version 03030303030303030303030303030303 is missing or does not open",
1850                ],
1851                "one line per damaged version, in its order"
1852            );
1853            assert_eq!(
1854                problems(&tenant(Ok(sound()), true), HOUR, NOW, true),
1855                ["a key rotation was stopped part way; run rekey tenant again"],
1856                "a stopped rotation is named with the command that finishes it"
1857            );
1858            assert_eq!(
1859                problems(
1860                    &tenant(
1861                        Err(Unexamined::Open(OpenFailure::Refused(TenantError::Io))),
1862                        false
1863                    ),
1864                    HOUR,
1865                    NOW,
1866                    true,
1867                ),
1868                ["its catalog cannot be opened: Io"],
1869                "a refused catalog names the refusal, not a key"
1870            );
1871        }
1872
1873        /// Only a catalog its key does not open is a key problem; one the
1874        /// process may not open is named with its path and the system's
1875        /// error.
1876        #[test]
1877        fn a_key_problem_and_an_access_problem_are_told_apart() {
1878            let key = problems(
1879                &tenant(Err(Unexamined::Open(OpenFailure::WrongKey)), false),
1880                HOUR,
1881                NOW,
1882                true,
1883            );
1884            assert_eq!(key, ["its catalog does not open under its tenant key"]);
1885            let access = OpenFailure::Access {
1886                path: std::path::PathBuf::from("/srv/data/tenants/01/catalog.sqlite"),
1887                error: std::io::Error::from_raw_os_error(libc::EACCES),
1888            };
1889            assert_eq!(
1890                problems(
1891                    &tenant(Err(Unexamined::Open(access)), false),
1892                    HOUR,
1893                    NOW,
1894                    true
1895                ),
1896                [
1897                    "its catalog cannot be opened: /srv/data/tenants/01/catalog.sqlite: Permission denied (os error 13)"
1898                ]
1899            );
1900        }
1901
1902        /// Packed versions with no `[storage.parquet]` in the
1903        /// configuration are a problem, named with the setting; with the
1904        /// table, or with nothing packed, they are not.
1905        #[test]
1906        fn packed_versions_without_storage_parquet_are_a_problem() {
1907            let packed = Examination {
1908                packed: 2,
1909                ..sound()
1910            };
1911            assert_eq!(
1912                problems(&tenant(Ok(packed.clone()), false), HOUR, NOW, false),
1913                [
1914                    "2 version(s) are packed into Parquet files, and the configuration has no [storage.parquet]: serve refuses to start until the table is put back"
1915                ],
1916                "without the table"
1917            );
1918            assert_eq!(
1919                problems(&tenant(Ok(packed), false), HOUR, NOW, true),
1920                Vec::<String>::new(),
1921                "with the table"
1922            );
1923            assert_eq!(
1924                problems(&tenant(Ok(sound()), false), HOUR, NOW, false),
1925                Vec::<String>::new(),
1926                "nothing packed"
1927            );
1928        }
1929
1930        /// A Store that opened and whose objects the storage did not read
1931        /// is named as that, with the error's kind and the system's error
1932        /// number when there is one, and never as a catalog that does not
1933        /// open; any other failed examination says so with its error.
1934        #[test]
1935        fn objects_that_cannot_be_read_are_told_apart_from_a_catalog() {
1936            let unread = |kind, os_error| {
1937                problems(
1938                    &tenant(
1939                        Err(Unexamined::Examine(ExamineError::Objects {
1940                            kind,
1941                            os_error,
1942                        })),
1943                        false,
1944                    ),
1945                    HOUR,
1946                    NOW,
1947                    true,
1948                )
1949            };
1950            assert_eq!(
1951                unread(std::io::ErrorKind::PermissionDenied, Some(libc::EACCES)),
1952                ["its objects cannot be read: permission denied (os error 13)"],
1953                "a file the process may not read"
1954            );
1955            assert_eq!(
1956                unread(std::io::ErrorKind::TimedOut, None),
1957                ["its objects cannot be read: timed out"],
1958                "a service's failure has a kind and no system error number"
1959            );
1960            assert_eq!(
1961                problems(
1962                    &tenant(
1963                        Err(Unexamined::Examine(ExamineError::Failed(StoreError::Io))),
1964                        false
1965                    ),
1966                    HOUR,
1967                    NOW,
1968                    true,
1969                ),
1970                ["it could not be examined: Io"],
1971                "any other failure, with its error"
1972            );
1973        }
1974
1975        #[test]
1976        fn a_sweep_is_stalled_only_once_a_version_waited_longer_than_the_interval() {
1977            let waited = |since| Examination {
1978                due: 1,
1979                oldest_due_since: Some(since),
1980                ..sound()
1981            };
1982            let ok = waited(datetime!(2026-10-25 11:00 UTC));
1983            assert_eq!(
1984                problems(&tenant(Ok(ok), false), HOUR, NOW, true),
1985                Vec::<String>::new()
1986            );
1987            let stalled = waited(datetime!(2026-10-25 10:59:59 UTC));
1988            assert_eq!(
1989                problems(&tenant(Ok(stalled), false), HOUR, NOW, true),
1990                [
1991                    "1 version(s) due for purge, the oldest longer than purge_interval: the sweep is not keeping up"
1992                ],
1993                "one second past purge_interval is a stalled sweep"
1994            );
1995        }
1996
1997        #[test]
1998        fn check_reports_each_tenant_and_a_summary_and_exits_1_on_a_problem() {
1999            let s = setup();
2000            let id = s.create("acme");
2001            let out = s.run(Command::Check).expect("nothing wrong");
2002            assert_eq!(out.len(), 2);
2003            assert_eq!(out[0]["tenant"], id.as_str());
2004            assert_eq!(out[0]["problems"], json!([]));
2005            assert_eq!(out[1]["tenants"], 1);
2006            assert_eq!(out[1]["problems"], 0);
2007
2008            let tenant = TenantId::parse(&id).expect("id");
2009            let version = {
2010                let tenants = s.tenants();
2011                let store = tenants.store(tenant).expect("store");
2012                let (found, body) = vcon(UUID, "kept");
2013                let Ok(crate::store::Created::New(v)) =
2014                    store.create(&Caller { key: KeyId([1; 8]) }, &found, &body)
2015                else {
2016                    panic!("stored")
2017                };
2018                v
2019            };
2020            let objects = s.config.data_dir.join("tenants").join(&id).join("objects");
2021            std::fs::remove_file(objects.join(version.to_string())).expect("remove");
2022            std::fs::write(objects.join(format!("{version}.tmp")), b"x").expect("leftover");
2023            let mut printed = Vec::new();
2024            let found = run(&s.config, &Command::Check, &mut printed);
2025            assert!(
2026                matches!(found, Err(CommandError::CheckFound(1))),
2027                "{found:?}"
2028            );
2029            let lines: Vec<Value> = String::from_utf8(printed)
2030                .expect("text")
2031                .lines()
2032                .map(|l| serde_json::from_str(l).expect("json"))
2033                .collect();
2034            assert_eq!(lines[0]["damaged"], json!([version.to_string()]));
2035            assert_eq!(lines[0]["leftovers"], json!([format!("{version}.tmp")]));
2036            assert_eq!(lines[1]["problems"], 1);
2037            assert!(
2038                objects.join(format!("{version}.tmp")).exists(),
2039                "check reports leftovers; it does not remove them"
2040            );
2041            let server = datadir::lock(&s.config.data_dir, Sharing::Serve).expect("a server");
2042            assert!(matches!(
2043                s.run(Command::Check),
2044                Err(CommandError::DataDir(LockError::InUse(Sharing::Alone)))
2045            ));
2046            drop(server);
2047        }
2048    }
2049
2050    /// The commands that run alone are refused while a server holds the
2051    /// data directory; the others run beside it.
2052    #[test]
2053    fn beside_a_server_only_the_beside_commands_run() {
2054        let s = setup();
2055        let tenant = s.create("acme");
2056        let server = datadir::lock(&s.config.data_dir, Sharing::Serve).expect("a server");
2057        for command in [
2058            Command::TenantCreate {
2059                name: "beta".to_owned(),
2060                retention: None,
2061            },
2062            Command::TenantRemove {
2063                id: tenant.clone(),
2064                force: true,
2065                override_holds: false,
2066            },
2067        ] {
2068            assert!(
2069                matches!(
2070                    s.run(command.clone()),
2071                    Err(CommandError::DataDir(LockError::InUse(Sharing::Alone)))
2072                ),
2073                "{command:?}"
2074            );
2075        }
2076        s.run(Command::TenantList).expect("beside");
2077        s.run(Command::TenantSetRetention {
2078            id: tenant.clone(),
2079            retention: "1y".to_owned(),
2080        })
2081        .expect("beside");
2082        s.run(Command::KeyList { tenant: None }).expect("beside");
2083        let made = s
2084            .run(Command::KeyCreate {
2085                owner: Owner::Operator,
2086                label: "l".to_owned(),
2087                life: KeyLife::Default,
2088            })
2089            .expect("beside");
2090        s.run(Command::KeyRevoke {
2091            id: made[0]["id"].as_str().expect("an id").to_owned(),
2092        })
2093        .expect("beside");
2094        s.run(Command::AuditExport {
2095            log: Log::Admin,
2096            since: None,
2097        })
2098        .expect("beside");
2099        s.run(Command::Backup {
2100            to: s._dir.path().join("backup"),
2101        })
2102        .expect("beside");
2103        drop(server);
2104        assert_eq!(s.run(Command::TenantList).expect("listed").len(), 1);
2105    }
2106
2107    /// A command beside a server opens without recovery, so a create the
2108    /// server has in progress stays; one that runs alone recovers.
2109    #[test]
2110    fn only_a_command_that_runs_alone_recovers() {
2111        let s = setup();
2112        s.create("acme");
2113        let in_progress = TenantId::generate().to_string();
2114        std::fs::create_dir(s.config.data_dir.join("tenants").join(&in_progress))
2115            .expect("a directory with no row");
2116        s.run(Command::TenantList).expect("listed");
2117        s.run(Command::KeyList { tenant: None }).expect("listed");
2118        assert!(
2119            s.tenant_dirs().contains(&in_progress),
2120            "left by beside commands"
2121        );
2122        s.create("beta");
2123        assert!(
2124            !s.tenant_dirs().contains(&in_progress),
2125            "removed by an alone command"
2126        );
2127    }
2128
2129    #[test]
2130    fn a_master_key_other_users_may_read_stops_every_command() {
2131        let s = setup();
2132        s.create("acme");
2133        chmod(&s.config.master_key, 0o644);
2134        let error = s.run(Command::TenantList).expect_err("refused");
2135        let path = s.config.master_key.display();
2136        assert_eq!(
2137            error.to_string(),
2138            format!(
2139                "the master key cannot be read: master_key {path}: other users may read or \
2140                 change the file (mode 0644); run `chmod 600 {path}`, or `chmod 640 {path}` for \
2141                 a group that only reads it"
2142            ),
2143            "the command stops with the rule's text, naming the key, the file and the fix"
2144        );
2145    }
2146
2147    #[test]
2148    fn rekey_master_refuses_a_new_key_other_users_may_read_under_its_option() {
2149        let s = setup();
2150        s.create("acme");
2151        let new_file = s.config.master_key.with_file_name("new.key");
2152        std::fs::write(&new_file, [0x5c; 32]).expect("new key");
2153        chmod(&new_file, 0o644);
2154        let error = s
2155            .run(Command::RekeyMaster {
2156                new_master: new_file.clone(),
2157                to_backend: None,
2158            })
2159            .expect_err("refused");
2160        assert!(
2161            error
2162                .to_string()
2163                .contains(&format!("--new-master {}: other users", new_file.display())),
2164            "{error}"
2165        );
2166    }
2167
2168    /// A second master key file beside the configuration's, mode 0600.
2169    fn new_master_file(s: &Setup) -> std::path::PathBuf {
2170        let new_file = s.config.master_key.with_file_name("new.key");
2171        std::fs::write(&new_file, [0x5d; 32]).expect("new key");
2172        chmod(&new_file, 0o600);
2173        new_file
2174    }
2175
2176    fn to_file(new_master: &std::path::Path) -> Command {
2177        Command::RekeyMaster {
2178            new_master: new_master.to_path_buf(),
2179            to_backend: Some("file".to_owned()),
2180        }
2181    }
2182
2183    #[test]
2184    fn rekey_master_to_backend_file_moves_the_data_to_the_new_master_key() {
2185        let mut s = setup();
2186        s.create("acme");
2187        let new_file = new_master_file(&s);
2188        let out = s.run(to_file(&new_file)).expect("moved");
2189        let new_id = Key::load_master(&new_file).expect("key").id().to_string();
2190        assert_eq!(out.len(), 1, "one line: {out:?}");
2191        assert_eq!(out[0]["backend"], "file", "the target backend");
2192        assert_eq!(out[0]["master_key_id"], new_id.as_str(), "the new key");
2193        assert_eq!(out[0]["moved"], true, "server.sqlite moved");
2194        assert_eq!(out[0]["tenants"], 1, "one tenant");
2195        assert!(
2196            out[0]["next"]
2197                .as_str()
2198                .is_some_and(|n| n.contains("destroy every copy of the old master key")),
2199            "what comes next: {out:?}"
2200        );
2201        s.config.master_key = new_file;
2202        assert_eq!(
2203            s.run(Command::TenantList).expect("listed").len(),
2204            1,
2205            "the tenant opens under the new key"
2206        );
2207    }
2208
2209    #[test]
2210    fn rekey_master_to_backend_file_run_again_says_nothing_was_left() {
2211        let s = setup();
2212        s.create("acme");
2213        let new_file = new_master_file(&s);
2214        s.run(to_file(&new_file)).expect("moved");
2215        let out = s.run(to_file(&new_file));
2216        // The configuration still names the old key: the data is under the
2217        // new one, so nothing is left to move.
2218        let out = out.expect("a run after completion succeeds");
2219        assert_eq!(out[0]["moved"], false, "nothing moved: {out:?}");
2220        assert!(out[0].get("tenants").is_none(), "no count: {out:?}");
2221    }
2222
2223    #[test]
2224    fn rekey_master_to_a_backend_this_release_lacks_is_refused_by_name() {
2225        let s = setup();
2226        s.create("acme");
2227        let new_file = new_master_file(&s);
2228        let before = std::fs::read(s.config.data_dir.join("server.sqlite")).expect("read");
2229        let error = s
2230            .run(Command::RekeyMaster {
2231                new_master: new_file,
2232                to_backend: Some("vault-transit".to_owned()),
2233            })
2234            .expect_err("refused");
2235        assert!(
2236            matches!(error, CommandError::BackendLater(BackendKind::VaultTransit)),
2237            "{error:?}"
2238        );
2239        assert_eq!(
2240            error.to_string(),
2241            "--to-backend vault-transit: this release moves the keys only to a master key file \
2242             (--to-backend file)",
2243            "the text"
2244        );
2245        assert_eq!(
2246            std::fs::read(s.config.data_dir.join("server.sqlite")).expect("read"),
2247            before,
2248            "nothing changed"
2249        );
2250    }
2251
2252    #[test]
2253    fn rekey_master_to_an_unknown_backend_is_refused() {
2254        let s = setup();
2255        let new_file = new_master_file(&s);
2256        let error = s
2257            .run(Command::RekeyMaster {
2258                new_master: new_file,
2259                to_backend: Some("filez".to_owned()),
2260            })
2261            .expect_err("refused");
2262        assert!(
2263            matches!(&error, CommandError::NoSuchBackend(name) if name == "filez"),
2264            "{error:?}"
2265        );
2266        assert_eq!(
2267            error.to_string(),
2268            "--to-backend filez is not a key backend: file, aws-kms, gcp-kms, azure-key-vault, \
2269             vault-transit, openbao-transit or pkcs11",
2270            "the text names every backend"
2271        );
2272    }
2273
2274    #[test]
2275    fn rekey_master_to_backend_file_with_the_same_key_is_refused() {
2276        let s = setup();
2277        assert!(
2278            matches!(
2279                s.run(to_file(&s.config.master_key.clone())),
2280                Err(CommandError::SameMasterKey)
2281            ),
2282            "the key in use"
2283        );
2284    }
2285
2286    #[test]
2287    fn rekey_master_to_backend_file_is_refused_while_a_server_runs() {
2288        let s = setup();
2289        let new_file = new_master_file(&s);
2290        let server = datadir::lock(&s.config.data_dir, Sharing::Serve).expect("a server");
2291        assert!(
2292            matches!(
2293                s.run(to_file(&new_file)),
2294                Err(CommandError::DataDir(LockError::InUse(Sharing::Alone)))
2295            ),
2296            "the data directory is in use"
2297        );
2298        drop(server);
2299    }
2300
2301    #[test]
2302    fn rekey_master_refuses_a_registry_whose_root_a_backend_wraps() {
2303        for to_backend in [None, Some("file".to_owned())] {
2304            let s = setup();
2305            s.create("acme");
2306            let new_file = new_master_file(&s);
2307            let reference = crate::key_wrap::blob::WrapRef::new(BackendKind::Pkcs11, "vcon-1")
2308                .expect("a reference");
2309            let blob = crate::key_wrap::blob::Blob::new(reference, vec![1])
2310                .expect("a blob")
2311                .encode();
2312            std::fs::write(s.config.data_dir.join(tenants::ROOT_FILE), blob).expect("write");
2313            let before = std::fs::read(s.config.data_dir.join("server.sqlite")).expect("read");
2314            let error = s
2315                .run(Command::RekeyMaster {
2316                    new_master: new_file,
2317                    to_backend: to_backend.clone(),
2318                })
2319                .expect_err("refused");
2320            assert!(
2321                matches!(
2322                    error,
2323                    CommandError::Open(RegistryError::RootWrapped(Some(BackendKind::Pkcs11), _))
2324                ),
2325                "{to_backend:?}: {error:?}"
2326            );
2327            assert_eq!(
2328                std::fs::read(s.config.data_dir.join("server.sqlite")).expect("read"),
2329                before,
2330                "{to_backend:?}: nothing changed"
2331            );
2332        }
2333    }
2334
2335    #[test]
2336    fn rekey_master_to_backend_file_with_no_tenants_moves_the_empty_registry() {
2337        let mut s = setup();
2338        s.run(Command::TenantList).expect("makes the registry");
2339        let new_file = new_master_file(&s);
2340        let out = s.run(to_file(&new_file)).expect("moved");
2341        assert_eq!(out[0]["tenants"], 0, "no tenant: {out:?}");
2342        s.config.master_key = new_file;
2343        assert_eq!(
2344            s.run(Command::TenantList).expect("listed").len(),
2345            0,
2346            "opens under the new key"
2347        );
2348    }
2349
2350    #[cfg(feature = "s3")]
2351    #[test]
2352    fn an_export_secret_other_users_may_read_is_refused_under_export_s3() {
2353        let s = setup();
2354        let secret = s.config.master_key.with_file_name("export.secret");
2355        std::fs::write(&secret, "k3y-0123\n").expect("secret");
2356        chmod(&secret, 0o644);
2357        let mut config = s.config.clone();
2358        config.export = crate::config::parse(&format!(
2359            "listen = \"127.0.0.1:1\"\ndata_dir = \"/d\"\nmaster_key = \"/m\"\n\
2360             [tls]\ncert = \"c\"\nkey = \"k\"\n\
2361             [export.s3]\nendpoint = \"http://127.0.0.1:9\"\nregion = \"eu-west-3\"\n\
2362             access_key_id = \"id\"\nsecret_access_key_file = {secret:?}\nallow_http = true\n"
2363        ))
2364        .expect("a configuration")
2365        .export;
2366        let error = s3_target(&config, "vcon", "").err().expect("refused");
2367        let text = error.to_string();
2368        assert!(
2369            text.contains(&format!(
2370                "export.s3.secret_access_key_file {}: other users",
2371                secret.display()
2372            )),
2373            "{text}"
2374        );
2375        assert!(!text.contains("k3y"), "{text}");
2376    }
2377
2378    /// A user or membership command that fails in the registry says what
2379    /// every other command says for the same failure.
2380    #[test]
2381    fn a_user_commands_registry_failure_is_the_registrys_error() {
2382        for (failure, words) in [
2383            (
2384                TenantError::AuditFailed,
2385                "the audit record could not be written",
2386            ),
2387            (
2388                TenantError::WrongKey,
2389                "is not the one server.sqlite was made under",
2390            ),
2391        ] {
2392            let error = CommandError::from(UserError::Registry(failure));
2393            assert!(
2394                matches!(error, CommandError::Tenant(e) if e == failure),
2395                "{failure:?} is carried as the registry's error: {error:?}"
2396            );
2397            assert!(error.to_string().contains(words), "{error}");
2398        }
2399        assert!(
2400            matches!(
2401                CommandError::from(UserError::NoUser),
2402                CommandError::User(UserError::NoUser)
2403            ),
2404            "a refusal stays a user error"
2405        );
2406    }
2407
2408    #[test]
2409    fn a_wrong_master_key_is_named() {
2410        let s = setup();
2411        s.create("acme");
2412        std::fs::write(&s.config.master_key, [0x5b; 32]).expect("another key");
2413        let error = s.run(Command::TenantList).expect_err("refused");
2414        assert!(matches!(error, CommandError::WrongMasterKey), "{error:?}");
2415        assert!(error.to_string().contains("master key"), "{error}");
2416        std::fs::write(&s.config.master_key, [0x5a; 31]).expect("short key");
2417        let error = s.run(Command::TenantList).expect_err("refused");
2418        assert!(matches!(error, CommandError::MasterKey(_)), "{error:?}");
2419    }
2420
2421    #[test]
2422    fn backup_prints_what_it_copied_and_check_finds_the_copy_whole() {
2423        let s = setup();
2424        s.create("acme");
2425        s.create("globex");
2426        let to = s._dir.path().join("backup");
2427        let out = s.run(Command::Backup { to: to.clone() }).expect("backs up");
2428        assert_eq!(
2429            out,
2430            [serde_json::json!({ "tenants": 2, "versions": 0, "tries": 1 })]
2431        );
2432        let copy = Setup {
2433            _dir: tempfile::tempdir().expect("temp dir"),
2434            config: Config {
2435                data_dir: to,
2436                ..s.config.clone()
2437            },
2438        };
2439        let checked = copy.run(Command::Check).expect("check finds no problem");
2440        assert_eq!(checked.last().expect("a summary")["problems"], 0);
2441        let names: Vec<_> = copy
2442            .run(Command::TenantList)
2443            .expect("lists")
2444            .iter()
2445            .map(|t| t["name"].clone())
2446            .collect();
2447        assert_eq!(names, ["acme", "globex"]);
2448    }
2449
2450    #[test]
2451    fn a_backup_path_already_there_is_refused() {
2452        let s = setup();
2453        let to = s._dir.path().join("backup");
2454        std::fs::create_dir(&to).expect("dir");
2455        let error = s.run(Command::Backup { to }).expect_err("refused");
2456        assert!(
2457            matches!(error, CommandError::Backup(BackupError::Exists)),
2458            "{error:?}"
2459        );
2460    }
2461
2462    /// Words the message of `error` must hold to say what went wrong. The
2463    /// matches have no catch-all arm, so a new error fails to compile here
2464    /// until its words are given.
2465    fn says(error: &CommandError) -> &'static str {
2466        match error {
2467            CommandError::DataDir(_) => "the data directory is in use",
2468            CommandError::MasterKey(_) => "the master key cannot be read",
2469            // The step, the file and the error under it, all three.
2470            CommandError::Open(_) => "opening /srv/data/server.sqlite failed: disk I/O error",
2471            CommandError::WrongMasterKey => "is not the one server.sqlite was made under",
2472            CommandError::WrongDatabaseKey => {
2473                "is not the one the registry in the catalog database was made under"
2474            }
2475            CommandError::BadPeriod(_) => "\"7w\" is not a period",
2476            CommandError::UnknownKey => "no key has this id",
2477            CommandError::User(e) => match e {
2478                UserError::CliOnly => "command line",
2479                UserError::BadLabel => "a user label is",
2480                UserError::BadIdentity => "an issuer is an https:// URL",
2481                UserError::IdentityTaken => "an active user has this issuer and subject",
2482                UserError::NoUser => "no user has this id",
2483                UserError::Deactivated => "the user is deactivated",
2484                UserError::NoTenant => "no tenant has this id",
2485                UserError::Closing => "being removed",
2486                UserError::BadRoles => "reader, producer, records, legal, auditor and tenant-admin",
2487                UserError::OverCap => "outside the tenant's role cap",
2488                UserError::BadCap => "a role cap is one or more of",
2489                UserError::NoMembership => "the user has no such membership",
2490                UserError::Registry(_) => "could not be read or written",
2491            },
2492            CommandError::Output(_) => "the output could not be written",
2493            CommandError::SameMasterKey => "already in use",
2494            CommandError::BackendLater(_) => "only to a master key file",
2495            CommandError::NoSuchBackend(_) => "is not a key backend",
2496            CommandError::CheckFound(_) => "check found 2 problem(s)",
2497            CommandError::Storage(_) => "the storage cannot be used: bucket \"vcon\"",
2498            CommandError::BadLevel(_) => "\"most\" is not a metadata level",
2499            CommandError::BadTime(_) => "\"yesterday\" is not an RFC 3339 time",
2500            CommandError::BadTarget(_) => "\"s3://\" is not a directory or an s3://bucket/prefix",
2501            CommandError::NoS3 => "[export.s3] or [storage.s3]",
2502            CommandError::Export(_) => "another export wrote",
2503            CommandError::Move { .. } => "running storage move-objects again moves the rest",
2504            CommandError::Backup(e) => match e {
2505                BackupError::Exists => "already exists",
2506                BackupError::KeptChanging => "try again",
2507                BackupError::Io => "could not be written",
2508                BackupError::AuditFailed => "audit record",
2509                BackupError::NoFileBackup => "back up the catalog database with pg_dump",
2510            },
2511            CommandError::Tenant(e) => match e {
2512                TenantError::NotFound => "no tenant",
2513                TenantError::NameTaken => "another tenant has this name",
2514                TenantError::BadName => "a tenant name is",
2515                TenantError::HoldsVcons => "--force",
2516                TenantError::UnderHold => "--override-holds",
2517                TenantError::LimitReached => "rekey master",
2518                TenantError::AuditFailed => "audit record",
2519                TenantError::Closing => "being removed",
2520                TenantError::CliOnly => "command line",
2521                TenantError::BadScopes => "scopes",
2522                TenantError::BadExpiry => "1 to 365 days",
2523                TenantError::BadSetting(_) => "setting",
2524                // Display folds a registry made under another master key
2525                // into WrongMasterKey's message.
2526                TenantError::WrongKey => "is not the one server.sqlite was made under",
2527                TenantError::NoFileBackup => "back up the catalog database with pg_dump",
2528                TenantError::Io => "could not be read or written",
2529            },
2530        }
2531    }
2532
2533    /// With the objects kept in the data directory there is no bucket to
2534    /// move them to: the command is refused, naming the setting.
2535    #[test]
2536    fn storage_move_objects_needs_a_bucket() {
2537        let s = setup();
2538        s.create("acme");
2539        let error = s.run(Command::StorageMoveObjects).expect_err("refused");
2540        assert!(
2541            error.to_string().contains("storage.objects = \"s3\""),
2542            "names the setting: {error}"
2543        );
2544    }
2545
2546    /// Against the test service: a data directory's objects move to the
2547    /// bucket, byte for byte; the vCon then reads back from the bucket, no
2548    /// object file is left, and a second run moves nothing.
2549    #[cfg(feature = "backend-tests")]
2550    #[test]
2551    fn storage_move_objects_moves_each_tenants_objects_to_the_bucket() {
2552        use crate::backend::Objects;
2553        let s = setup();
2554        let id = s.create("acme");
2555        store_one(&s, &id);
2556        let tenant = TenantId::parse(&id).expect("an id");
2557        let local = s.config.data_dir.join("tenants").join(&id).join("objects");
2558        let files = || std::fs::read_dir(&local).expect("listed").count();
2559        assert_eq!(files(), 1, "one object file");
2560        let (bucket, mut settings) = crate::backend::s3::remote::bucket(false);
2561        let secret = crate::backend::s3::remote::secret_file();
2562        settings.secret_access_key_file = Some(secret.1.clone());
2563        let mut config = s.config.clone();
2564        config.storage = crate::config::Storage {
2565            objects: crate::config::ObjectStore::S3(settings),
2566            parquet: None,
2567        };
2568        let moving = |config: &Config| -> Vec<Value> {
2569            let mut out = Vec::new();
2570            run(config, &Command::StorageMoveObjects, &mut out).expect("moved");
2571            String::from_utf8(out)
2572                .expect("text")
2573                .lines()
2574                .map(|l| serde_json::from_str(l).expect("a JSON line"))
2575                .collect()
2576        };
2577        assert_eq!(
2578            moving(&config),
2579            [
2580                json!({"tenant": id, "moved": 1, "missing": 0}),
2581                json!({"moved": 1})
2582            ],
2583            "one object moved, and nothing missing"
2584        );
2585        assert_eq!(files(), 0, "no object file is left");
2586        assert_eq!(
2587            bucket.tenant(tenant).list().expect("listed").len(),
2588            1,
2589            "the object is in the bucket"
2590        );
2591        let tenants = Tenants::open_beside_in(
2592            &config.data_dir,
2593            Key::load_master(&config.master_key).expect("master"),
2594            Arc::new(OsFs),
2595            Arc::new(SystemClock),
2596            crate::backend::ObjectPlace::S3(bucket.clone()),
2597            &crate::backend::Catalogs::Local,
2598        )
2599        .expect("opens");
2600        let (_, body) = vcon(UUID, "exported");
2601        assert_eq!(
2602            tenants
2603                .store(tenant)
2604                .expect("its store")
2605                .get(&Caller { key: KeyId([7; 8]) }, UUID.parse().expect("uuid"))
2606                .expect("reads")
2607                .body,
2608            body,
2609            "the vCon reads back from the bucket"
2610        );
2611        drop(tenants);
2612        assert_eq!(
2613            moving(&config),
2614            [
2615                json!({"tenant": id, "moved": 0, "missing": 0}),
2616                json!({"moved": 0})
2617            ],
2618            "a second run moves nothing"
2619        );
2620    }
2621
2622    /// One vCon stored in the tenant `id`.
2623    fn store_one(s: &Setup, id: &str) {
2624        let store = s
2625            .tenants()
2626            .store(TenantId::parse(id).expect("an id"))
2627            .expect("the store");
2628        let (found, body) = vcon(UUID, "exported");
2629        store
2630            .create(&Caller { key: KeyId([7; 8]) }, &found, &body)
2631            .expect("stored");
2632    }
2633
2634    #[test]
2635    fn tenant_set_metadata_prints_the_level_and_list_shows_it() {
2636        let s = setup();
2637        let id = s.create("acme");
2638        let out = s
2639            .run(Command::TenantSetMetadata {
2640                id: id.clone(),
2641                metadata: "counts".to_owned(),
2642            })
2643            .expect("set");
2644        assert_eq!(
2645            out,
2646            [json!({ "id": id, "metadata": "counts" })],
2647            "the command prints the tenant and its level"
2648        );
2649        assert_eq!(
2650            s.run(Command::TenantList).expect("listed")[0]["metadata"],
2651            "counts",
2652            "the list shows the level"
2653        );
2654        assert!(
2655            matches!(
2656                s.run(Command::TenantSetMetadata {
2657                    id: id.clone(),
2658                    metadata: "most".to_owned(),
2659                }),
2660                Err(CommandError::BadLevel(text)) if text == "most"
2661            ),
2662            "a level that is not one is refused, naming it"
2663        );
2664        assert_eq!(
2665            tenant_error(s.run(Command::TenantSetMetadata {
2666                id: TenantId::generate().to_string(),
2667                metadata: "full".to_owned(),
2668            })),
2669            TenantError::NotFound,
2670            "a tenant id no tenant has is not found"
2671        );
2672    }
2673
2674    /// The export runs beside a server, at the tenant's level, and prints
2675    /// one line; it is refused beside a command that runs alone.
2676    #[test]
2677    fn export_parquet_runs_beside_a_server_and_prints_what_it_wrote() {
2678        let s = setup();
2679        let id = s.create("acme");
2680        store_one(&s, &id);
2681        s.run(Command::TenantSetMetadata {
2682            id: id.clone(),
2683            metadata: "counts".to_owned(),
2684        })
2685        .expect("set");
2686        let to = s._dir.path().join("export");
2687        let export = Command::ExportParquet {
2688            tenant: id.clone(),
2689            to: to.display().to_string(),
2690            since: Some("2000-01-01T00:00:00Z".to_owned()),
2691            until: None,
2692        };
2693        let server = datadir::lock(&s.config.data_dir, Sharing::Serve).expect("a server");
2694        let out = s.run(export.clone()).expect("exports beside a server");
2695        drop(server);
2696        assert_eq!(out.len(), 1, "{out:?}");
2697        let line = &out[0];
2698        let manifest = format!("tenant={id}/manifest/00000000000000000001.json");
2699        assert_eq!(line["tenant"], id, "the line names the tenant");
2700        assert_eq!(
2701            line["metadata"], "counts",
2702            "the export is at the tenant's level"
2703        );
2704        assert_eq!(
2705            line["to"],
2706            to.display().to_string(),
2707            "the line names the target"
2708        );
2709        assert_eq!(line["manifest"], manifest, "the line names the manifest");
2710        assert_eq!(line["seq"], 1, "the first export to the target");
2711        assert_eq!(line["files"], 1, "one store date, one file");
2712        assert_eq!(line["rows"], 1, "the one vCon stored");
2713        assert_eq!(line["skipped"], 0, "nothing was purged during the run");
2714        assert_eq!(line["unread"], 0, "every body was read");
2715        let m: Value =
2716            serde_json::from_slice(&std::fs::read(to.join(&manifest)).expect("the manifest"))
2717                .expect("JSON");
2718        assert_eq!(m["bytes"], line["bytes"], "the bytes the manifest names");
2719        assert_eq!(
2720            m["since"], "2000-01-01T00:00:00Z",
2721            "the manifest records --since"
2722        );
2723        let alone = datadir::lock(&s.config.data_dir, Sharing::Alone).expect("alone");
2724        assert!(
2725            matches!(
2726                s.run(export),
2727                Err(CommandError::DataDir(LockError::InUse(Sharing::Beside)))
2728            ),
2729            "an export does not run beside a command that runs alone"
2730        );
2731        drop(alone);
2732    }
2733
2734    #[test]
2735    fn export_parquet_refuses_a_bad_time_target_or_tenant() {
2736        let s = setup();
2737        let id = s.create("acme");
2738        let export = |to: &str, since: Option<&str>, until: Option<&str>| Command::ExportParquet {
2739            tenant: id.clone(),
2740            to: to.to_owned(),
2741            since: since.map(str::to_owned),
2742            until: until.map(str::to_owned),
2743        };
2744        let dir = s._dir.path().join("out").display().to_string();
2745        assert!(
2746            matches!(
2747                s.run(export(&dir, Some("yesterday"), None)),
2748                Err(CommandError::BadTime(t)) if t == "yesterday"
2749            ),
2750            "a word that is not an RFC 3339 time is refused, naming it"
2751        );
2752        assert!(
2753            matches!(
2754                s.run(export(&dir, None, Some("2026-13-01T00:00:00Z"))),
2755                Err(CommandError::BadTime(_))
2756            ),
2757            "a month 13 is not a time"
2758        );
2759        assert!(
2760            matches!(
2761                s.run(export("s3://", None, None)),
2762                Err(CommandError::BadTarget(t)) if t == "s3://"
2763            ),
2764            "an s3:// URL with no bucket is refused, naming it"
2765        );
2766        assert!(
2767            matches!(
2768                s.run(export("s3://reports/vcon", None, None)),
2769                Err(CommandError::NoS3)
2770            ),
2771            "no S3 service is configured"
2772        );
2773        assert_eq!(
2774            tenant_error(s.run(Command::ExportParquet {
2775                tenant: TenantId::generate().to_string(),
2776                to: dir.clone(),
2777                since: None,
2778                until: None,
2779            })),
2780            TenantError::NotFound,
2781            "an unknown tenant is not found"
2782        );
2783        assert!(
2784            !std::path::Path::new(&dir).exists(),
2785            "a refused export writes nothing"
2786        );
2787    }
2788
2789    #[test]
2790    fn each_error_says_what_went_wrong() {
2791        let tenant = [
2792            TenantError::NotFound,
2793            TenantError::NameTaken,
2794            TenantError::BadName,
2795            TenantError::HoldsVcons,
2796            TenantError::UnderHold,
2797            TenantError::LimitReached,
2798            TenantError::AuditFailed,
2799            TenantError::Closing,
2800            TenantError::CliOnly,
2801            TenantError::BadScopes,
2802            TenantError::BadExpiry,
2803            TenantError::BadSetting(crate::settings::SettingError::UnknownName),
2804            TenantError::WrongKey,
2805            TenantError::NoFileBackup,
2806            TenantError::Io,
2807        ]
2808        .map(CommandError::Tenant);
2809        let backup = [
2810            BackupError::Exists,
2811            BackupError::KeptChanging,
2812            BackupError::Io,
2813            BackupError::AuditFailed,
2814            BackupError::NoFileBackup,
2815        ]
2816        .map(CommandError::Backup);
2817        let rest = [
2818            CommandError::DataDir(LockError::InUse(Sharing::Alone)),
2819            CommandError::MasterKey(crate::envelope::KeyError::WrongSize),
2820            CommandError::Open(RegistryError::failed(
2821                tenants::OpenStep::OpenCatalog,
2822                std::path::PathBuf::from("/srv/data/server.sqlite"),
2823                io::Error::other("disk I/O error"),
2824            )),
2825            CommandError::WrongMasterKey,
2826            CommandError::WrongDatabaseKey,
2827            CommandError::BadPeriod("7w".to_owned()),
2828            CommandError::UnknownKey,
2829            CommandError::Output(io::Error::other("closed")),
2830            CommandError::SameMasterKey,
2831            CommandError::BackendLater(BackendKind::Pkcs11),
2832            CommandError::NoSuchBackend("hsm".to_owned()),
2833            CommandError::CheckFound(2),
2834            CommandError::Storage(StorageError(
2835                "bucket \"vcon\" cannot be reached or read".to_owned(),
2836            )),
2837            CommandError::BadLevel("most".to_owned()),
2838            CommandError::BadTime("yesterday".to_owned()),
2839            CommandError::BadTarget("s3://".to_owned()),
2840            CommandError::NoS3,
2841            CommandError::Export(crate::export::ExportError::Raced("m".to_owned())),
2842            CommandError::Move {
2843                tenant: TenantId([1; 16]),
2844                why: "the bucket could not be written".to_owned(),
2845            },
2846        ];
2847        let user = [
2848            UserError::CliOnly,
2849            UserError::BadLabel,
2850            UserError::BadIdentity,
2851            UserError::IdentityTaken,
2852            UserError::NoUser,
2853            UserError::Deactivated,
2854            UserError::NoTenant,
2855            UserError::Closing,
2856            UserError::BadRoles,
2857            UserError::NoMembership,
2858            UserError::Registry(TenantError::Io),
2859        ]
2860        .map(CommandError::User);
2861        for error in tenant.into_iter().chain(backup).chain(rest).chain(user) {
2862            let text = error.to_string();
2863            assert!(text.contains(says(&error)), "{error:?}: {text}");
2864        }
2865    }
2866}