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