1use 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#[derive(Debug, Clone, PartialEq, Eq)]
32pub enum Command {
33 TenantCreate {
34 name: String,
35 retention: Option<String>,
36 },
37 TenantList,
38 TenantSetRetention {
40 id: String,
41 retention: String,
42 },
43 TenantRemove {
44 id: String,
45 force: bool,
46 override_holds: bool,
47 },
48 TenantSetMetadata {
50 id: String,
51 metadata: String,
52 },
53 TenantSetRoleCap {
56 id: String,
57 roles: Option<Vec<String>>,
58 },
59 TenantRoleCap {
61 id: String,
62 },
63 StorageMoveObjects,
67 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 life: KeyLife,
81 },
82 KeyList {
83 tenant: Option<String>,
84 },
85 KeyRevoke {
86 id: String,
87 },
88 UserAdd {
91 label: String,
92 identity: Option<(String, String)>,
93 },
94 UserList,
95 UserDeactivate {
96 id: String,
97 },
98 MembershipGrant {
100 user: String,
101 place: Place,
102 },
103 MembershipRevoke {
106 user: String,
107 place: Place,
108 },
109 AuditExport {
110 log: Log,
111 since: Option<i64>,
112 },
113 RekeyTenant {
115 id: String,
116 },
117 RekeyMaster {
119 new_master: std::path::PathBuf,
120 },
121 Check,
123 Backup {
126 to: std::path::PathBuf,
127 },
128}
129
130#[derive(Debug, Clone, PartialEq, Eq)]
132pub enum Owner {
133 Tenant { id: String, scopes: Vec<String> },
134 Operator,
135}
136
137#[derive(Debug, Clone, PartialEq, Eq)]
140pub enum Place {
141 Tenant { id: String, roles: Vec<String> },
142 Operator,
143}
144
145#[derive(Debug, Clone, PartialEq, Eq)]
147pub enum Log {
148 Tenant(String),
149 Admin,
150}
151
152impl Command {
153 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#[derive(Debug)]
184pub enum CommandError {
185 DataDir(LockError),
186 MasterKey(KeyError),
187 WrongMasterKey,
189 WrongDatabaseKey,
192 BadPeriod(String),
195 Tenant(TenantError),
196 Open(RegistryError),
198 UnknownKey,
200 User(UserError),
202 Output(io::Error),
204 SameMasterKey,
206 CheckFound(usize),
208 Backup(BackupError),
209 Storage(StorageError),
211 BadLevel(String),
213 BadTime(String),
215 BadTarget(String),
217 NoS3,
220 Export(crate::export::ExportError),
221 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
347pub 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 let catalogs = backend::catalog_for(&config.catalog, sharing).map_err(CommandError::Storage)?;
370 run_and_give_up(config, command, master, &catalogs, out)
371}
372
373pub(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
388fn 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 if let Command::RekeyMaster { new_master } = command {
400 return rekey_master(config, &master, new_master, catalogs, out);
401 }
402 if matches!(command, Command::StorageMoveObjects) && catalogs.server().is_some() {
405 return Err(nothing_to_move_on_a_database());
406 }
407 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 #[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 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 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 fn from(e: UserError) -> CommandError {
629 match e {
630 UserError::Registry(e) => CommandError::Tenant(e),
631 other => CommandError::User(other),
632 }
633 }
634}
635
636fn user_id(text: &str) -> Result<UserId, CommandError> {
638 UserId::parse(text).ok_or(CommandError::User(UserError::NoUser))
639}
640
641fn named_roles(names: &[String]) -> Result<Roles, CommandError> {
644 Roles::named(names).ok_or(CommandError::User(UserError::BadRoles))
645}
646
647fn 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
663fn 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
681fn 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#[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#[cfg(feature = "postgres")]
768const REKEY_MASTER_BATCH: i64 = 1_000;
769
770fn 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
781fn 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 #[cfg(feature = "postgres")]
807 backend::Catalogs::Postgres(database) => {
808 backend::postgres::PgRegistry::rekey_master(
809 database,
810 master,
811 &new,
812 SystemClock.now(),
813 REKEY_MASTER_BATCH,
814 )
815 .map_err(|e| match e {
816 TenantError::WrongKey => CommandError::WrongDatabaseKey,
817 other => CommandError::Tenant(other),
818 })?;
819 }
820 }
821 line(
822 out,
823 &serde_json::json!({
824 "master_key_id": new.id().to_string(),
825 "next": "point master_key in the configuration at the new key file, start the server, then destroy every copy of the old master key",
826 }),
827 )
828}
829
830fn not_a_bucket() -> CommandError {
835 CommandError::Storage(StorageError(
836 "storage move-objects moves the objects to the bucket that storage.objects = \"s3\" \
837 names; this configuration keeps them in the data directory"
838 .to_owned(),
839 ))
840}
841
842#[cfg(feature = "s3")]
847fn move_objects(
848 config: &Config,
849 tenants: &Tenants,
850 s3: &Arc<crate::backend::s3::S3>,
851 out: &mut dyn Write,
852) -> Result<(), CommandError> {
853 use crate::backend::migrate::MoveError;
854 let mut total = 0;
855 for id in tenants.ids()? {
856 let dir = config
857 .data_dir
858 .join("tenants")
859 .join(id.to_string())
860 .join("objects");
861 let moved = if dir.exists() {
862 let from = crate::backend::local::LocalObjects::new(dir, Arc::new(OsFs));
863 crate::backend::migrate::move_objects(&from, &s3.tenant(id)).map_err(|e| {
864 let why = match e {
865 MoveError::From(e) => {
866 format!("an object file could not be read or removed: {e}")
867 }
868 MoveError::To(e) => format!("the bucket could not be written or read: {e}"),
869 MoveError::Differs(version) => format!(
870 "version {version} read back from the bucket differs from its file, \
871 which stays in the data directory"
872 ),
873 };
874 CommandError::Move { tenant: id, why }
875 })?
876 } else {
877 0
878 };
879 let missing = tenants
880 .store(id)?
881 .check()
882 .map_err(|e| CommandError::Move {
883 tenant: id,
884 why: format!("the objects in the bucket could not be checked: {e:?}"),
885 })?
886 .len();
887 total += moved;
888 line(
889 out,
890 &serde_json::json!({ "tenant": id.to_string(), "moved": moved, "missing": missing }),
891 )?;
892 }
893 line(out, &serde_json::json!({ "moved": total }))
894}
895
896fn check(config: &Config, tenants: &Tenants, out: &mut dyn Write) -> Result<(), CommandError> {
897 let now = SystemClock.now();
898 let found = tenants.examine(config.retention_default, now)?;
899 let time = |at: Option<OffsetDateTime>| at.and_then(|at| at.format(&Rfc3339).ok());
900 let mut total = 0;
901 for tenant in &found.tenants {
902 let named = problems(
903 tenant,
904 config.purge_interval,
905 now,
906 config.storage.parquet.is_some(),
907 );
908 total += named.len();
909 let store = tenant.store.as_ref().ok();
910 line(
911 out,
912 &serde_json::json!({
913 "tenant": tenant.id.to_string(),
914 "name": tenant.name,
915 "versions": store.map(|s| s.versions),
916 "packed": store.map(|s| s.packed),
917 "damaged": store.map(|s| s.damaged.iter().map(ToString::to_string).collect::<Vec<_>>()),
918 "leftovers": store.map(|s| &s.leftovers),
919 "past_due": store.map(|s| s.due),
920 "oldest_past_due": time(store.and_then(|s| s.oldest_due_since)),
921 "purges_awaiting_rotation": store.map(|s| s.purges_since_key),
922 "oldest_purge_awaiting_rotation": time(store.and_then(|s| s.oldest_purge_since_key)),
923 "rotation_stopped": tenant.rotation_stopped,
924 "problems": named,
925 }),
926 )?;
927 }
928 line(
929 out,
930 &serde_json::json!({
931 "tenants": found.tenants.len(),
932 "removed_tenants_awaiting_master_rotation": found.removed_since_master,
933 "oldest_removal_awaiting_master_rotation": time(found.oldest_removed_since_master),
934 "problems": total,
935 }),
936 )?;
937 match total {
938 0 => Ok(()),
939 n => Err(CommandError::CheckFound(n)),
940 }
941}
942
943pub fn problems(
950 tenant: &TenantExamination,
951 purge_interval: std::time::Duration,
952 now: OffsetDateTime,
953 parquet: bool,
954) -> Vec<String> {
955 let mut found = Vec::new();
956 if tenant.rotation_stopped {
957 found.push("a key rotation was stopped part way; run rekey tenant again".to_owned());
958 }
959 match &tenant.store {
960 Err(Unexamined::Open(OpenFailure::WrongKey)) => {
961 found.push("its catalog does not open under its tenant key".to_owned());
962 }
963 Err(Unexamined::Open(OpenFailure::Access { path, error })) => {
964 found.push(format!(
965 "its catalog cannot be opened: {}: {error}",
966 path.display()
967 ));
968 }
969 Err(Unexamined::Open(OpenFailure::Refused(e))) => {
970 found.push(format!("its catalog cannot be opened: {e:?}"));
971 }
972 Err(Unexamined::Examine(ExamineError::Objects { kind, os_error })) => {
973 let number = os_error
974 .map(|n| format!(" (os error {n})"))
975 .unwrap_or_default();
976 found.push(format!("its objects cannot be read: {kind}{number}"));
977 }
978 Err(Unexamined::Examine(ExamineError::Failed(e))) => {
979 found.push(format!("it could not be examined: {e:?}"));
980 }
981 Ok(store) => {
982 if store.packed > 0 && !parquet {
983 found.push(format!(
984 "{} version(s) are packed into Parquet files, and the configuration has no \
985 [storage.parquet]: serve refuses to start until the table is put back",
986 store.packed
987 ));
988 }
989 for version in &store.damaged {
990 found.push(format!("version {version} is missing or does not open"));
991 }
992 if let Some(since) = store.oldest_due_since
993 && now - since > purge_interval
994 {
995 found.push(format!(
996 "{} version(s) due for purge, the oldest longer than purge_interval: the sweep is not keeping up",
997 store.due
998 ));
999 }
1000 }
1001 }
1002 found
1003}
1004
1005fn period(text: &str) -> Result<Retention, CommandError> {
1007 Retention::parse(text).ok_or_else(|| CommandError::BadPeriod(text.to_owned()))
1008}
1009
1010fn tenant_id(text: &str) -> Result<TenantId, CommandError> {
1013 TenantId::parse(text).ok_or(CommandError::Tenant(TenantError::NotFound))
1014}
1015
1016fn line(out: &mut dyn Write, value: &serde_json::Value) -> Result<(), CommandError> {
1018 writeln!(out, "{value}").map_err(CommandError::Output)
1019}
1020
1021#[cfg(test)]
1022mod tests {
1023 use serde_json::{Value, json};
1024
1025 use super::*;
1026 use crate::store::Caller;
1027 use crate::store::testing::vcon;
1028
1029 const UUID: &str = "01a07da8-c2bb-83e5-b9a2-279e0d16bc46";
1030
1031 struct Setup {
1032 _dir: tempfile::TempDir,
1033 config: Config,
1034 }
1035
1036 fn chmod(path: &std::path::Path, mode: u32) {
1037 use std::os::unix::fs::PermissionsExt;
1038 std::fs::set_permissions(path, std::fs::Permissions::from_mode(mode)).expect("chmod");
1039 }
1040
1041 fn setup() -> Setup {
1042 let dir = tempfile::tempdir().expect("temp dir");
1043 let data = dir.path().join("data");
1044 std::fs::create_dir(&data).expect("data dir");
1045 let master = dir.path().join("master.key");
1046 std::fs::write(&master, [0x5a; 32]).expect("master key file");
1047 chmod(&master, 0o600);
1048 let config = crate::config::parse(&format!(
1049 "listen = \"127.0.0.1:1\"\ndata_dir = {data:?}\nmaster_key = {master:?}\n\
1050 [tls]\ncert = \"c\"\nkey = \"k\"\n"
1051 ))
1052 .expect("a configuration");
1053 Setup { _dir: dir, config }
1054 }
1055
1056 impl Setup {
1057 fn run(&self, command: Command) -> Result<Vec<Value>, CommandError> {
1059 let mut out = Vec::new();
1060 run(&self.config, &command, &mut out)?;
1061 Ok(String::from_utf8(out)
1062 .expect("text")
1063 .lines()
1064 .map(|line| serde_json::from_str(line).expect("a JSON line"))
1065 .collect())
1066 }
1067
1068 fn create(&self, name: &str) -> String {
1069 let out = self
1070 .run(Command::TenantCreate {
1071 name: name.to_owned(),
1072 retention: None,
1073 })
1074 .expect("made");
1075 out[0]["id"].as_str().expect("an id").to_owned()
1076 }
1077
1078 fn tenants(&self) -> Tenants {
1080 Tenants::open_beside(
1081 &self.config.data_dir,
1082 Key::load_master(&self.config.master_key).expect("master"),
1083 Arc::new(OsFs),
1084 Arc::new(SystemClock),
1085 )
1086 .expect("opens")
1087 }
1088
1089 fn tenant_dirs(&self) -> Vec<String> {
1090 let mut names: Vec<String> = std::fs::read_dir(self.config.data_dir.join("tenants"))
1091 .expect("tenants dir")
1092 .map(|e| e.expect("entry").file_name().to_string_lossy().into_owned())
1093 .collect();
1094 names.sort();
1095 names
1096 }
1097 }
1098
1099 fn key_with(s: &Setup, tenant: &str, life: KeyLife) -> Result<Vec<Value>, CommandError> {
1101 s.run(Command::KeyCreate {
1102 owner: Owner::Tenant {
1103 id: tenant.to_owned(),
1104 scopes: vec!["read".to_owned()],
1105 },
1106 label: "dated".to_owned(),
1107 life,
1108 })
1109 }
1110
1111 fn rfc3339(value: &Value) -> time::OffsetDateTime {
1112 time::OffsetDateTime::parse(
1113 value.as_str().expect("a time as text"),
1114 &time::format_description::well_known::Rfc3339,
1115 )
1116 .expect("RFC 3339")
1117 }
1118
1119 fn made_in(value: &Value) -> time::OffsetDateTime {
1122 rfc3339(value)
1123 .replace_nanosecond(0)
1124 .expect("zero is in range")
1125 }
1126
1127 #[test]
1128 fn key_create_prints_the_expiry_of_the_key_it_makes() {
1129 let s = setup();
1130 let tenant = s.create("acme");
1131 let made = key_with(&s, &tenant, KeyLife::Default).expect("made");
1132 let listed = s.run(Command::KeyList { tenant: None }).expect("listed");
1133 assert_eq!(
1134 rfc3339(&made[0]["expires_at"]) - made_in(&listed[0]["created_at"]),
1135 time::Duration::days(90),
1136 "the default life"
1137 );
1138 assert_eq!(
1139 made[0]["expires_at"], listed[0]["expires_at"],
1140 "the list shows the same expiry"
1141 );
1142 assert!(listed[0]["last_used_at"].is_null(), "a key never used");
1143 }
1144
1145 #[test]
1146 fn key_create_makes_a_key_for_the_days_asked_or_with_no_expiry() {
1147 let s = setup();
1148 let tenant = s.create("acme");
1149 let week = key_with(&s, &tenant, KeyLife::Days(7)).expect("made");
1150 let never = key_with(&s, &tenant, KeyLife::Never).expect("made");
1151 let listed = s.run(Command::KeyList { tenant: None }).expect("listed");
1152 assert_eq!(
1153 rfc3339(&week[0]["expires_at"]) - made_in(&listed[0]["created_at"]),
1154 time::Duration::days(7),
1155 "seven days"
1156 );
1157 assert!(
1158 never[0]["expires_at"].is_null(),
1159 "no expiry is printed as null"
1160 );
1161 assert!(listed[1]["expires_at"].is_null(), "and listed as null");
1162 }
1163
1164 #[test]
1165 fn key_create_refuses_days_outside_1_to_365() {
1166 let s = setup();
1167 let tenant = s.create("acme");
1168 for days in [0, 366] {
1169 assert!(
1170 matches!(
1171 key_with(&s, &tenant, KeyLife::Days(days)),
1172 Err(CommandError::Tenant(TenantError::BadExpiry))
1173 ),
1174 "{days} days"
1175 );
1176 }
1177 let listed = s.run(Command::KeyList { tenant: None }).expect("listed");
1178 assert_eq!(listed.len(), 0, "no key was made");
1179 }
1180
1181 #[test]
1182 fn key_create_refuses_no_expiry_where_the_configuration_says_so() {
1183 let mut s = setup();
1184 let tenant = s.create("acme");
1185 s.config.keys_no_expiry = false;
1186 assert!(
1187 matches!(
1188 key_with(&s, &tenant, KeyLife::Never),
1189 Err(CommandError::Tenant(TenantError::BadExpiry))
1190 ),
1191 "a tenant key"
1192 );
1193 let operator = s.run(Command::KeyCreate {
1194 owner: Owner::Operator,
1195 label: "ops".to_owned(),
1196 life: KeyLife::Never,
1197 });
1198 assert!(
1199 matches!(operator, Err(CommandError::Tenant(TenantError::BadExpiry))),
1200 "an operator key"
1201 );
1202 assert!(
1203 key_with(&s, &tenant, KeyLife::Default).is_ok(),
1204 "a key with an expiry is still made"
1205 );
1206 }
1207
1208 #[test]
1209 fn an_operator_key_may_have_no_expiry_by_default() {
1210 let s = setup();
1211 let made = s
1212 .run(Command::KeyCreate {
1213 owner: Owner::Operator,
1214 label: "ops".to_owned(),
1215 life: KeyLife::Never,
1216 })
1217 .expect("made");
1218 assert!(made[0]["expires_at"].is_null(), "no expiry");
1219 }
1220
1221 fn tenant_error(result: Result<Vec<Value>, CommandError>) -> TenantError {
1222 match result {
1223 Err(CommandError::Tenant(e)) => e,
1224 Ok(_) => panic!("the command succeeded, and a tenant error was expected"),
1226 Err(other) => panic!("not a tenant error: {other:?}"),
1227 }
1228 }
1229
1230 #[test]
1231 fn tenant_create_prints_the_new_id_and_list_shows_it() {
1232 let s = setup();
1233 let out = s
1234 .run(Command::TenantCreate {
1235 name: "acme".to_owned(),
1236 retention: Some("18m".to_owned()),
1237 })
1238 .expect("made");
1239 assert_eq!(out.len(), 1);
1240 let id = out[0]["id"].as_str().expect("an id").to_owned();
1241 assert!(TenantId::parse(&id).is_some(), "{id}");
1242 assert_eq!(out[0], json!({ "id": id }));
1243 let beta = s.create("beta");
1244 assert_eq!(
1245 s.run(Command::TenantList).expect("listed"),
1246 [
1247 json!({ "id": id, "name": "acme", "retention": "18m", "metadata": "none" }),
1248 json!({ "id": beta, "name": "beta", "retention": null, "metadata": "none" }),
1249 ]
1250 );
1251 }
1252
1253 #[test]
1254 fn a_bad_period_is_refused_before_anything_is_made() {
1255 let s = setup();
1256 let error = s
1257 .run(Command::TenantCreate {
1258 name: "acme".to_owned(),
1259 retention: Some("7w".to_owned()),
1260 })
1261 .expect_err("refused");
1262 assert!(
1263 matches!(&error, CommandError::BadPeriod(p) if p == "7w"),
1264 "{error:?}"
1265 );
1266 assert!(error.to_string().contains("7w"), "{error}");
1267 assert_eq!(
1268 s.run(Command::TenantList).expect("listed"),
1269 Vec::<Value>::new()
1270 );
1271 let id = s.create("acme");
1272 let error = s
1273 .run(Command::TenantSetRetention {
1274 id,
1275 retention: "forever".to_owned(),
1276 })
1277 .expect_err("refused");
1278 assert!(matches!(&error, CommandError::BadPeriod(p) if p == "forever"));
1279 }
1280
1281 #[test]
1282 fn set_retention_takes_a_period_or_default() {
1283 let s = setup();
1284 let id = s.create("acme");
1285 let set = |retention: &str| {
1286 s.run(Command::TenantSetRetention {
1287 id: id.clone(),
1288 retention: retention.to_owned(),
1289 })
1290 .expect("set")
1291 };
1292 assert_eq!(set("90d"), [json!({ "id": id, "retention": "90d" })]);
1293 assert_eq!(
1294 s.run(Command::TenantList).expect("listed")[0]["retention"],
1295 "90d"
1296 );
1297 assert_eq!(set("default"), [json!({ "id": id, "retention": null })]);
1298 assert_eq!(
1299 s.run(Command::TenantList).expect("listed")[0]["retention"],
1300 Value::Null
1301 );
1302 }
1303
1304 #[test]
1305 fn an_unknown_or_malformed_tenant_is_not_found() {
1306 let s = setup();
1307 for id in [TenantId::generate().to_string(), "not-an-id".to_owned()] {
1308 assert_eq!(
1309 tenant_error(s.run(Command::TenantSetRetention {
1310 id: id.clone(),
1311 retention: "7y".to_owned()
1312 })),
1313 TenantError::NotFound
1314 );
1315 assert_eq!(
1316 tenant_error(s.run(Command::TenantRemove {
1317 id: id.clone(),
1318 force: true,
1319 override_holds: false
1320 })),
1321 TenantError::NotFound
1322 );
1323 assert_eq!(
1324 tenant_error(s.run(Command::KeyCreate {
1325 owner: Owner::Tenant {
1326 id: id.clone(),
1327 scopes: vec!["read".to_owned()]
1328 },
1329 label: "l".to_owned(),
1330 life: KeyLife::Default,
1331 })),
1332 TenantError::NotFound
1333 );
1334 assert_eq!(
1335 tenant_error(s.run(Command::KeyList {
1336 tenant: Some(id.clone())
1337 })),
1338 TenantError::NotFound
1339 );
1340 assert_eq!(
1341 tenant_error(s.run(Command::AuditExport {
1342 log: Log::Tenant(id.clone()),
1343 since: None
1344 })),
1345 TenantError::NotFound
1346 );
1347 }
1348 }
1349
1350 #[test]
1353 fn remove_goes_as_far_as_its_flags_allow() {
1354 let s = setup();
1355 let empty = s.create("empty");
1356 let full = s.create("full");
1357 {
1358 let tenants = s.tenants();
1359 let store = tenants
1360 .store(TenantId::parse(&full).expect("id"))
1361 .expect("store");
1362 let caller = Caller { key: KeyId([1; 8]) };
1363 let (found, body) = vcon(UUID, "kept");
1364 store.create(&caller, &found, &body).expect("stored");
1365 store.set_hold(&caller, found.uuid, true).expect("held");
1366 }
1367 let remove = |id: &str, force, override_holds| {
1368 s.run(Command::TenantRemove {
1369 id: id.to_owned(),
1370 force,
1371 override_holds,
1372 })
1373 };
1374 assert_eq!(
1375 remove(&empty, false, false).expect("removed"),
1376 Vec::<Value>::new()
1377 );
1378 assert_eq!(
1379 tenant_error(remove(&full, false, false)),
1380 TenantError::HoldsVcons
1381 );
1382 assert_eq!(
1383 tenant_error(remove(&full, true, false)),
1384 TenantError::UnderHold
1385 );
1386 assert_eq!(
1387 remove(&full, true, true).expect("removed"),
1388 Vec::<Value>::new()
1389 );
1390 assert_eq!(
1391 s.run(Command::TenantList).expect("listed"),
1392 Vec::<Value>::new()
1393 );
1394 assert_eq!(s.tenant_dirs(), Vec::<String>::new());
1395 }
1396
1397 #[test]
1398 fn keys_are_made_listed_and_revoked() {
1399 let s = setup();
1400 let tenant = s.create("acme");
1401 let made = s
1402 .run(Command::KeyCreate {
1403 owner: Owner::Tenant {
1404 id: tenant.clone(),
1405 scopes: vec!["write".to_owned(), "read".to_owned()],
1406 },
1407 label: "producer".to_owned(),
1408 life: KeyLife::Default,
1409 })
1410 .expect("made");
1411 let id = made[0]["id"].as_str().expect("id").to_owned();
1412 let token = made[0]["token"].as_str().expect("token").to_owned();
1413 assert_eq!(made.len(), 1);
1414 assert_eq!(made[0].as_object().expect("object").len(), 3);
1415 assert!(
1416 token.starts_with(&format!("vcs_{id}_")),
1417 "the token starts with vcs_ and the key's id {id}"
1418 );
1419 let operator = s
1420 .run(Command::KeyCreate {
1421 owner: Owner::Operator,
1422 label: "ops".to_owned(),
1423 life: KeyLife::Default,
1424 })
1425 .expect("made")[0]["id"]
1426 .as_str()
1427 .expect("id")
1428 .to_owned();
1429
1430 let listed = s.run(Command::KeyList { tenant: None }).expect("listed");
1431 assert_eq!(listed.len(), 2);
1432 assert_eq!(listed[0]["id"], id.as_str());
1433 assert_eq!(listed[0]["tenant"], tenant.as_str());
1434 assert_eq!(listed[0]["scopes"], json!(["write", "read"]));
1435 assert_eq!(listed[0]["label"], "producer");
1436 assert_eq!(listed[0]["revoked_at"], Value::Null);
1437 assert!(
1438 listed[0]["created_at"]
1439 .as_str()
1440 .is_some_and(|t| t.ends_with('Z'))
1441 );
1442 assert!(
1443 listed.iter().all(|k| k.get("token").is_none()),
1444 "never a token"
1445 );
1446 assert_eq!(listed[1]["id"], operator.as_str());
1447 assert_eq!(listed[1]["tenant"], Value::Null);
1448 assert_eq!(listed[1]["scopes"], json!(["admin"]));
1449
1450 let own = s
1451 .run(Command::KeyList {
1452 tenant: Some(tenant.clone()),
1453 })
1454 .expect("listed");
1455 assert_eq!(own, listed[..1]);
1456
1457 assert_eq!(
1458 s.run(Command::KeyRevoke { id: id.clone() })
1459 .expect("revoked"),
1460 Vec::<Value>::new()
1461 );
1462 let listed = s.run(Command::KeyList { tenant: None }).expect("listed");
1463 assert!(listed[0]["revoked_at"].as_str().is_some(), "{listed:?}");
1464 assert_eq!(listed[1]["revoked_at"], Value::Null);
1465 }
1466
1467 #[test]
1468 fn bad_scopes_and_unknown_keys_are_refused() {
1469 let s = setup();
1470 let tenant = s.create("acme");
1471 for scopes in [
1472 vec!["superuser"],
1473 vec!["read", "superuser"],
1474 vec!["read", "read"],
1475 vec!["admin"],
1476 vec![],
1477 ] {
1478 let error = s.run(Command::KeyCreate {
1479 owner: Owner::Tenant {
1480 id: tenant.clone(),
1481 scopes: scopes.iter().map(|s| (*s).to_owned()).collect(),
1482 },
1483 label: "l".to_owned(),
1484 life: KeyLife::Default,
1485 });
1486 assert_eq!(tenant_error(error), TenantError::BadScopes, "{scopes:?}");
1487 }
1488 assert_eq!(
1489 s.run(Command::KeyList { tenant: None }).expect("listed"),
1490 Vec::<Value>::new()
1491 );
1492 for id in ["0123456789abcdef".to_owned(), "nope".to_owned()] {
1493 assert!(
1494 matches!(
1495 s.run(Command::KeyRevoke { id }),
1496 Err(CommandError::UnknownKey)
1497 ),
1498 "unknown"
1499 );
1500 }
1501 }
1502
1503 #[test]
1504 fn audit_export_writes_either_log_from_a_sequence_number() {
1505 let s = setup();
1506 let tenant = s.create("acme");
1507 s.run(Command::TenantList).expect("listed");
1508 s.run(Command::KeyCreate {
1509 owner: Owner::Tenant {
1510 id: tenant.clone(),
1511 scopes: vec!["read".to_owned()],
1512 },
1513 label: "l".to_owned(),
1514 life: KeyLife::Default,
1515 })
1516 .expect("made");
1517
1518 let admin = s
1519 .run(Command::AuditExport {
1520 log: Log::Admin,
1521 since: None,
1522 })
1523 .expect("exported");
1524 let actions: Vec<&str> = admin
1525 .iter()
1526 .map(|r| r["action"].as_str().expect("action"))
1527 .collect();
1528 assert_eq!(actions, ["tenant_create", "tenant_list", "key_create"]);
1529 assert!(admin.iter().all(|r| r["actor"] == "cli"));
1530 let since = admin[0]["seq"].as_i64().expect("seq");
1531 let later = s
1532 .run(Command::AuditExport {
1533 log: Log::Admin,
1534 since: Some(since),
1535 })
1536 .expect("exported");
1537 assert_eq!(later, admin[1..]);
1538
1539 let own = s
1540 .run(Command::AuditExport {
1541 log: Log::Tenant(tenant),
1542 since: None,
1543 })
1544 .expect("exported");
1545 let actions: Vec<&str> = own
1546 .iter()
1547 .map(|r| r["action"].as_str().expect("action"))
1548 .collect();
1549 assert_eq!(actions, ["key_create"]);
1550 }
1551
1552 #[test]
1553 fn rekey_tenant_rotates_the_key_and_prints_nothing() {
1554 let s = setup();
1555 let id = s.create("acme");
1556 let tenant = TenantId::parse(&id).expect("id");
1557 let before = s.tenants().tenant_key_id_for_test(tenant);
1558 assert_eq!(
1559 s.run(Command::RekeyTenant { id: id.clone() })
1560 .expect("rekeyed"),
1561 Vec::<Value>::new()
1562 );
1563 assert_ne!(s.tenants().tenant_key_id_for_test(tenant), before);
1564 assert_eq!(
1565 tenant_error(s.run(Command::RekeyTenant {
1566 id: TenantId::generate().to_string()
1567 })),
1568 TenantError::NotFound
1569 );
1570 let server = datadir::lock(&s.config.data_dir, Sharing::Serve).expect("a server");
1571 assert!(matches!(
1572 s.run(Command::RekeyTenant { id }),
1573 Err(CommandError::DataDir(LockError::InUse(Sharing::Alone)))
1574 ));
1575 drop(server);
1576 }
1577
1578 #[test]
1579 fn rekey_master_moves_the_data_to_the_new_master_key() {
1580 let mut s = setup();
1581 s.create("acme");
1582 let new_file = s.config.master_key.with_file_name("new.key");
1583 std::fs::write(&new_file, [0x5c; 32]).expect("new key");
1584 chmod(&new_file, 0o600);
1585 assert!(matches!(
1586 s.run(Command::RekeyMaster {
1587 new_master: s.config.master_key.clone()
1588 }),
1589 Err(CommandError::SameMasterKey)
1590 ));
1591 let server = datadir::lock(&s.config.data_dir, Sharing::Serve).expect("a server");
1592 assert!(matches!(
1593 s.run(Command::RekeyMaster {
1594 new_master: new_file.clone()
1595 }),
1596 Err(CommandError::DataDir(LockError::InUse(Sharing::Alone)))
1597 ));
1598 drop(server);
1599 let out = s
1600 .run(Command::RekeyMaster {
1601 new_master: new_file.clone(),
1602 })
1603 .expect("rotated");
1604 let new_id = Key::load_master(&new_file).expect("key").id().to_string();
1605 assert_eq!(out.len(), 1);
1606 assert_eq!(out[0]["master_key_id"], new_id.as_str());
1607 assert!(
1608 out[0]["next"]
1609 .as_str()
1610 .is_some_and(|n| n.contains("destroy"))
1611 );
1612 assert!(matches!(
1613 s.run(Command::TenantList),
1614 Err(CommandError::WrongMasterKey)
1615 ));
1616 s.config.master_key = new_file;
1617 assert_eq!(s.run(Command::TenantList).expect("listed").len(), 1);
1618 }
1619
1620 mod check {
1621 use time::macros::datetime;
1622
1623 use super::*;
1624 use crate::ids::VersionId;
1625 use crate::store::{Examination, StoreError};
1626
1627 const NOW: OffsetDateTime = datetime!(2026-10-25 12:00 UTC);
1628 const HOUR: std::time::Duration = std::time::Duration::from_secs(3600);
1629
1630 fn sound() -> Examination {
1631 Examination {
1632 versions: 3,
1633 packed: 0,
1634 damaged: vec![],
1635 leftovers: vec!["a.tmp".to_owned()],
1636 due: 0,
1637 oldest_due_since: None,
1638 purges_since_key: 4,
1639 oldest_purge_since_key: Some(datetime!(2026-10-01 00:00 UTC)),
1640 }
1641 }
1642
1643 fn tenant(store: Result<Examination, Unexamined>, stopped: bool) -> TenantExamination {
1644 TenantExamination {
1645 id: TenantId([1; 16]),
1646 name: "acme".to_owned(),
1647 rotation_stopped: stopped,
1648 store,
1649 }
1650 }
1651
1652 #[test]
1653 fn leftovers_and_work_waiting_for_rotation_are_not_problems() {
1654 assert_eq!(
1655 problems(&tenant(Ok(sound()), false), HOUR, NOW, true),
1656 Vec::<String>::new()
1657 );
1658 }
1659
1660 #[test]
1661 fn each_problem_is_named() {
1662 let damaged = Examination {
1663 damaged: vec![VersionId([2; 16]), VersionId([3; 16])],
1664 ..sound()
1665 };
1666 assert_eq!(
1667 problems(&tenant(Ok(damaged), false), HOUR, NOW, true),
1668 [
1669 "version 02020202020202020202020202020202 is missing or does not open",
1670 "version 03030303030303030303030303030303 is missing or does not open",
1671 ],
1672 "one line per damaged version, in its order"
1673 );
1674 assert_eq!(
1675 problems(&tenant(Ok(sound()), true), HOUR, NOW, true),
1676 ["a key rotation was stopped part way; run rekey tenant again"],
1677 "a stopped rotation is named with the command that finishes it"
1678 );
1679 assert_eq!(
1680 problems(
1681 &tenant(
1682 Err(Unexamined::Open(OpenFailure::Refused(TenantError::Io))),
1683 false
1684 ),
1685 HOUR,
1686 NOW,
1687 true,
1688 ),
1689 ["its catalog cannot be opened: Io"],
1690 "a refused catalog names the refusal, not a key"
1691 );
1692 }
1693
1694 #[test]
1698 fn a_key_problem_and_an_access_problem_are_told_apart() {
1699 let key = problems(
1700 &tenant(Err(Unexamined::Open(OpenFailure::WrongKey)), false),
1701 HOUR,
1702 NOW,
1703 true,
1704 );
1705 assert_eq!(key, ["its catalog does not open under its tenant key"]);
1706 let access = OpenFailure::Access {
1707 path: std::path::PathBuf::from("/srv/data/tenants/01/catalog.sqlite"),
1708 error: std::io::Error::from_raw_os_error(libc::EACCES),
1709 };
1710 assert_eq!(
1711 problems(
1712 &tenant(Err(Unexamined::Open(access)), false),
1713 HOUR,
1714 NOW,
1715 true
1716 ),
1717 [
1718 "its catalog cannot be opened: /srv/data/tenants/01/catalog.sqlite: Permission denied (os error 13)"
1719 ]
1720 );
1721 }
1722
1723 #[test]
1727 fn packed_versions_without_storage_parquet_are_a_problem() {
1728 let packed = Examination {
1729 packed: 2,
1730 ..sound()
1731 };
1732 assert_eq!(
1733 problems(&tenant(Ok(packed.clone()), false), HOUR, NOW, false),
1734 [
1735 "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"
1736 ],
1737 "without the table"
1738 );
1739 assert_eq!(
1740 problems(&tenant(Ok(packed), false), HOUR, NOW, true),
1741 Vec::<String>::new(),
1742 "with the table"
1743 );
1744 assert_eq!(
1745 problems(&tenant(Ok(sound()), false), HOUR, NOW, false),
1746 Vec::<String>::new(),
1747 "nothing packed"
1748 );
1749 }
1750
1751 #[test]
1756 fn objects_that_cannot_be_read_are_told_apart_from_a_catalog() {
1757 let unread = |kind, os_error| {
1758 problems(
1759 &tenant(
1760 Err(Unexamined::Examine(ExamineError::Objects {
1761 kind,
1762 os_error,
1763 })),
1764 false,
1765 ),
1766 HOUR,
1767 NOW,
1768 true,
1769 )
1770 };
1771 assert_eq!(
1772 unread(std::io::ErrorKind::PermissionDenied, Some(libc::EACCES)),
1773 ["its objects cannot be read: permission denied (os error 13)"],
1774 "a file the process may not read"
1775 );
1776 assert_eq!(
1777 unread(std::io::ErrorKind::TimedOut, None),
1778 ["its objects cannot be read: timed out"],
1779 "a service's failure has a kind and no system error number"
1780 );
1781 assert_eq!(
1782 problems(
1783 &tenant(
1784 Err(Unexamined::Examine(ExamineError::Failed(StoreError::Io))),
1785 false
1786 ),
1787 HOUR,
1788 NOW,
1789 true,
1790 ),
1791 ["it could not be examined: Io"],
1792 "any other failure, with its error"
1793 );
1794 }
1795
1796 #[test]
1797 fn a_sweep_is_stalled_only_once_a_version_waited_longer_than_the_interval() {
1798 let waited = |since| Examination {
1799 due: 1,
1800 oldest_due_since: Some(since),
1801 ..sound()
1802 };
1803 let ok = waited(datetime!(2026-10-25 11:00 UTC));
1804 assert_eq!(
1805 problems(&tenant(Ok(ok), false), HOUR, NOW, true),
1806 Vec::<String>::new()
1807 );
1808 let stalled = waited(datetime!(2026-10-25 10:59:59 UTC));
1809 assert_eq!(
1810 problems(&tenant(Ok(stalled), false), HOUR, NOW, true),
1811 [
1812 "1 version(s) due for purge, the oldest longer than purge_interval: the sweep is not keeping up"
1813 ],
1814 "one second past purge_interval is a stalled sweep"
1815 );
1816 }
1817
1818 #[test]
1819 fn check_reports_each_tenant_and_a_summary_and_exits_1_on_a_problem() {
1820 let s = setup();
1821 let id = s.create("acme");
1822 let out = s.run(Command::Check).expect("nothing wrong");
1823 assert_eq!(out.len(), 2);
1824 assert_eq!(out[0]["tenant"], id.as_str());
1825 assert_eq!(out[0]["problems"], json!([]));
1826 assert_eq!(out[1]["tenants"], 1);
1827 assert_eq!(out[1]["problems"], 0);
1828
1829 let tenant = TenantId::parse(&id).expect("id");
1830 let version = {
1831 let tenants = s.tenants();
1832 let store = tenants.store(tenant).expect("store");
1833 let (found, body) = vcon(UUID, "kept");
1834 let Ok(crate::store::Created::New(v)) =
1835 store.create(&Caller { key: KeyId([1; 8]) }, &found, &body)
1836 else {
1837 panic!("stored")
1838 };
1839 v
1840 };
1841 let objects = s.config.data_dir.join("tenants").join(&id).join("objects");
1842 std::fs::remove_file(objects.join(version.to_string())).expect("remove");
1843 std::fs::write(objects.join(format!("{version}.tmp")), b"x").expect("leftover");
1844 let mut printed = Vec::new();
1845 let found = run(&s.config, &Command::Check, &mut printed);
1846 assert!(
1847 matches!(found, Err(CommandError::CheckFound(1))),
1848 "{found:?}"
1849 );
1850 let lines: Vec<Value> = String::from_utf8(printed)
1851 .expect("text")
1852 .lines()
1853 .map(|l| serde_json::from_str(l).expect("json"))
1854 .collect();
1855 assert_eq!(lines[0]["damaged"], json!([version.to_string()]));
1856 assert_eq!(lines[0]["leftovers"], json!([format!("{version}.tmp")]));
1857 assert_eq!(lines[1]["problems"], 1);
1858 assert!(
1859 objects.join(format!("{version}.tmp")).exists(),
1860 "check reports leftovers; it does not remove them"
1861 );
1862 let server = datadir::lock(&s.config.data_dir, Sharing::Serve).expect("a server");
1863 assert!(matches!(
1864 s.run(Command::Check),
1865 Err(CommandError::DataDir(LockError::InUse(Sharing::Alone)))
1866 ));
1867 drop(server);
1868 }
1869 }
1870
1871 #[test]
1874 fn beside_a_server_only_the_beside_commands_run() {
1875 let s = setup();
1876 let tenant = s.create("acme");
1877 let server = datadir::lock(&s.config.data_dir, Sharing::Serve).expect("a server");
1878 for command in [
1879 Command::TenantCreate {
1880 name: "beta".to_owned(),
1881 retention: None,
1882 },
1883 Command::TenantRemove {
1884 id: tenant.clone(),
1885 force: true,
1886 override_holds: false,
1887 },
1888 ] {
1889 assert!(
1890 matches!(
1891 s.run(command.clone()),
1892 Err(CommandError::DataDir(LockError::InUse(Sharing::Alone)))
1893 ),
1894 "{command:?}"
1895 );
1896 }
1897 s.run(Command::TenantList).expect("beside");
1898 s.run(Command::TenantSetRetention {
1899 id: tenant.clone(),
1900 retention: "1y".to_owned(),
1901 })
1902 .expect("beside");
1903 s.run(Command::KeyList { tenant: None }).expect("beside");
1904 let made = s
1905 .run(Command::KeyCreate {
1906 owner: Owner::Operator,
1907 label: "l".to_owned(),
1908 life: KeyLife::Default,
1909 })
1910 .expect("beside");
1911 s.run(Command::KeyRevoke {
1912 id: made[0]["id"].as_str().expect("an id").to_owned(),
1913 })
1914 .expect("beside");
1915 s.run(Command::AuditExport {
1916 log: Log::Admin,
1917 since: None,
1918 })
1919 .expect("beside");
1920 s.run(Command::Backup {
1921 to: s._dir.path().join("backup"),
1922 })
1923 .expect("beside");
1924 drop(server);
1925 assert_eq!(s.run(Command::TenantList).expect("listed").len(), 1);
1926 }
1927
1928 #[test]
1931 fn only_a_command_that_runs_alone_recovers() {
1932 let s = setup();
1933 s.create("acme");
1934 let in_progress = TenantId::generate().to_string();
1935 std::fs::create_dir(s.config.data_dir.join("tenants").join(&in_progress))
1936 .expect("a directory with no row");
1937 s.run(Command::TenantList).expect("listed");
1938 s.run(Command::KeyList { tenant: None }).expect("listed");
1939 assert!(
1940 s.tenant_dirs().contains(&in_progress),
1941 "left by beside commands"
1942 );
1943 s.create("beta");
1944 assert!(
1945 !s.tenant_dirs().contains(&in_progress),
1946 "removed by an alone command"
1947 );
1948 }
1949
1950 #[test]
1951 fn a_master_key_other_users_may_read_stops_every_command() {
1952 let s = setup();
1953 s.create("acme");
1954 chmod(&s.config.master_key, 0o644);
1955 let error = s.run(Command::TenantList).expect_err("refused");
1956 let path = s.config.master_key.display();
1957 assert_eq!(
1958 error.to_string(),
1959 format!(
1960 "the master key cannot be read: master_key {path}: other users may read or \
1961 change the file (mode 0644); run `chmod 600 {path}`, or `chmod 640 {path}` for \
1962 a group that only reads it"
1963 ),
1964 "the command stops with the rule's text, naming the key, the file and the fix"
1965 );
1966 }
1967
1968 #[test]
1969 fn rekey_master_refuses_a_new_key_other_users_may_read_under_its_option() {
1970 let s = setup();
1971 s.create("acme");
1972 let new_file = s.config.master_key.with_file_name("new.key");
1973 std::fs::write(&new_file, [0x5c; 32]).expect("new key");
1974 chmod(&new_file, 0o644);
1975 let error = s
1976 .run(Command::RekeyMaster {
1977 new_master: new_file.clone(),
1978 })
1979 .expect_err("refused");
1980 assert!(
1981 error
1982 .to_string()
1983 .contains(&format!("--new-master {}: other users", new_file.display())),
1984 "{error}"
1985 );
1986 }
1987
1988 #[cfg(feature = "s3")]
1989 #[test]
1990 fn an_export_secret_other_users_may_read_is_refused_under_export_s3() {
1991 let s = setup();
1992 let secret = s.config.master_key.with_file_name("export.secret");
1993 std::fs::write(&secret, "k3y-0123\n").expect("secret");
1994 chmod(&secret, 0o644);
1995 let mut config = s.config.clone();
1996 config.export = crate::config::parse(&format!(
1997 "listen = \"127.0.0.1:1\"\ndata_dir = \"/d\"\nmaster_key = \"/m\"\n\
1998 [tls]\ncert = \"c\"\nkey = \"k\"\n\
1999 [export.s3]\nendpoint = \"http://127.0.0.1:9\"\nregion = \"eu-west-3\"\n\
2000 access_key_id = \"id\"\nsecret_access_key_file = {secret:?}\nallow_http = true\n"
2001 ))
2002 .expect("a configuration")
2003 .export;
2004 let error = s3_target(&config, "vcon", "").err().expect("refused");
2005 let text = error.to_string();
2006 assert!(
2007 text.contains(&format!(
2008 "export.s3.secret_access_key_file {}: other users",
2009 secret.display()
2010 )),
2011 "{text}"
2012 );
2013 assert!(!text.contains("k3y"), "{text}");
2014 }
2015
2016 #[test]
2019 fn a_user_commands_registry_failure_is_the_registrys_error() {
2020 for (failure, words) in [
2021 (
2022 TenantError::AuditFailed,
2023 "the audit record could not be written",
2024 ),
2025 (
2026 TenantError::WrongKey,
2027 "is not the one server.sqlite was made under",
2028 ),
2029 ] {
2030 let error = CommandError::from(UserError::Registry(failure));
2031 assert!(
2032 matches!(error, CommandError::Tenant(e) if e == failure),
2033 "{failure:?} is carried as the registry's error: {error:?}"
2034 );
2035 assert!(error.to_string().contains(words), "{error}");
2036 }
2037 assert!(
2038 matches!(
2039 CommandError::from(UserError::NoUser),
2040 CommandError::User(UserError::NoUser)
2041 ),
2042 "a refusal stays a user error"
2043 );
2044 }
2045
2046 #[test]
2047 fn a_wrong_master_key_is_named() {
2048 let s = setup();
2049 s.create("acme");
2050 std::fs::write(&s.config.master_key, [0x5b; 32]).expect("another key");
2051 let error = s.run(Command::TenantList).expect_err("refused");
2052 assert!(matches!(error, CommandError::WrongMasterKey), "{error:?}");
2053 assert!(error.to_string().contains("master key"), "{error}");
2054 std::fs::write(&s.config.master_key, [0x5a; 31]).expect("short key");
2055 let error = s.run(Command::TenantList).expect_err("refused");
2056 assert!(matches!(error, CommandError::MasterKey(_)), "{error:?}");
2057 }
2058
2059 #[test]
2060 fn backup_prints_what_it_copied_and_check_finds_the_copy_whole() {
2061 let s = setup();
2062 s.create("acme");
2063 s.create("globex");
2064 let to = s._dir.path().join("backup");
2065 let out = s.run(Command::Backup { to: to.clone() }).expect("backs up");
2066 assert_eq!(
2067 out,
2068 [serde_json::json!({ "tenants": 2, "versions": 0, "tries": 1 })]
2069 );
2070 let copy = Setup {
2071 _dir: tempfile::tempdir().expect("temp dir"),
2072 config: Config {
2073 data_dir: to,
2074 ..s.config.clone()
2075 },
2076 };
2077 let checked = copy.run(Command::Check).expect("check finds no problem");
2078 assert_eq!(checked.last().expect("a summary")["problems"], 0);
2079 let names: Vec<_> = copy
2080 .run(Command::TenantList)
2081 .expect("lists")
2082 .iter()
2083 .map(|t| t["name"].clone())
2084 .collect();
2085 assert_eq!(names, ["acme", "globex"]);
2086 }
2087
2088 #[test]
2089 fn a_backup_path_already_there_is_refused() {
2090 let s = setup();
2091 let to = s._dir.path().join("backup");
2092 std::fs::create_dir(&to).expect("dir");
2093 let error = s.run(Command::Backup { to }).expect_err("refused");
2094 assert!(
2095 matches!(error, CommandError::Backup(BackupError::Exists)),
2096 "{error:?}"
2097 );
2098 }
2099
2100 fn says(error: &CommandError) -> &'static str {
2104 match error {
2105 CommandError::DataDir(_) => "the data directory is in use",
2106 CommandError::MasterKey(_) => "the master key cannot be read",
2107 CommandError::Open(_) => "opening /srv/data/server.sqlite failed: disk I/O error",
2109 CommandError::WrongMasterKey => "is not the one server.sqlite was made under",
2110 CommandError::WrongDatabaseKey => {
2111 "is not the one the registry in the catalog database was made under"
2112 }
2113 CommandError::BadPeriod(_) => "\"7w\" is not a period",
2114 CommandError::UnknownKey => "no key has this id",
2115 CommandError::User(e) => match e {
2116 UserError::CliOnly => "command line",
2117 UserError::BadLabel => "a user label is",
2118 UserError::BadIdentity => "an issuer is an https:// URL",
2119 UserError::IdentityTaken => "an active user has this issuer and subject",
2120 UserError::NoUser => "no user has this id",
2121 UserError::Deactivated => "the user is deactivated",
2122 UserError::NoTenant => "no tenant has this id",
2123 UserError::Closing => "being removed",
2124 UserError::BadRoles => "reader, producer, records, legal, auditor and tenant-admin",
2125 UserError::OverCap => "outside the tenant's role cap",
2126 UserError::BadCap => "a role cap is one or more of",
2127 UserError::NoMembership => "the user has no such membership",
2128 UserError::Registry(_) => "could not be read or written",
2129 },
2130 CommandError::Output(_) => "the output could not be written",
2131 CommandError::SameMasterKey => "already in use",
2132 CommandError::CheckFound(_) => "check found 2 problem(s)",
2133 CommandError::Storage(_) => "the storage cannot be used: bucket \"vcon\"",
2134 CommandError::BadLevel(_) => "\"most\" is not a metadata level",
2135 CommandError::BadTime(_) => "\"yesterday\" is not an RFC 3339 time",
2136 CommandError::BadTarget(_) => "\"s3://\" is not a directory or an s3://bucket/prefix",
2137 CommandError::NoS3 => "[export.s3] or [storage.s3]",
2138 CommandError::Export(_) => "another export wrote",
2139 CommandError::Move { .. } => "running storage move-objects again moves the rest",
2140 CommandError::Backup(e) => match e {
2141 BackupError::Exists => "already exists",
2142 BackupError::KeptChanging => "try again",
2143 BackupError::Io => "could not be written",
2144 BackupError::AuditFailed => "audit record",
2145 BackupError::NoFileBackup => "back up the catalog database with pg_dump",
2146 },
2147 CommandError::Tenant(e) => match e {
2148 TenantError::NotFound => "no tenant",
2149 TenantError::NameTaken => "another tenant has this name",
2150 TenantError::BadName => "a tenant name is",
2151 TenantError::HoldsVcons => "--force",
2152 TenantError::UnderHold => "--override-holds",
2153 TenantError::LimitReached => "rekey master",
2154 TenantError::AuditFailed => "audit record",
2155 TenantError::Closing => "being removed",
2156 TenantError::CliOnly => "command line",
2157 TenantError::BadScopes => "scopes",
2158 TenantError::BadExpiry => "1 to 365 days",
2159 TenantError::BadSetting(_) => "setting",
2160 TenantError::WrongKey => "is not the one server.sqlite was made under",
2163 TenantError::NoFileBackup => "back up the catalog database with pg_dump",
2164 TenantError::Io => "could not be read or written",
2165 },
2166 }
2167 }
2168
2169 #[test]
2172 fn storage_move_objects_needs_a_bucket() {
2173 let s = setup();
2174 s.create("acme");
2175 let error = s.run(Command::StorageMoveObjects).expect_err("refused");
2176 assert!(
2177 error.to_string().contains("storage.objects = \"s3\""),
2178 "names the setting: {error}"
2179 );
2180 }
2181
2182 #[cfg(feature = "backend-tests")]
2186 #[test]
2187 fn storage_move_objects_moves_each_tenants_objects_to_the_bucket() {
2188 use crate::backend::Objects;
2189 let s = setup();
2190 let id = s.create("acme");
2191 store_one(&s, &id);
2192 let tenant = TenantId::parse(&id).expect("an id");
2193 let local = s.config.data_dir.join("tenants").join(&id).join("objects");
2194 let files = || std::fs::read_dir(&local).expect("listed").count();
2195 assert_eq!(files(), 1, "one object file");
2196 let (bucket, mut settings) = crate::backend::s3::remote::bucket(false);
2197 let secret = crate::backend::s3::remote::secret_file();
2198 settings.secret_access_key_file = Some(secret.1.clone());
2199 let mut config = s.config.clone();
2200 config.storage = crate::config::Storage {
2201 objects: crate::config::ObjectStore::S3(settings),
2202 parquet: None,
2203 };
2204 let moving = |config: &Config| -> Vec<Value> {
2205 let mut out = Vec::new();
2206 run(config, &Command::StorageMoveObjects, &mut out).expect("moved");
2207 String::from_utf8(out)
2208 .expect("text")
2209 .lines()
2210 .map(|l| serde_json::from_str(l).expect("a JSON line"))
2211 .collect()
2212 };
2213 assert_eq!(
2214 moving(&config),
2215 [
2216 json!({"tenant": id, "moved": 1, "missing": 0}),
2217 json!({"moved": 1})
2218 ],
2219 "one object moved, and nothing missing"
2220 );
2221 assert_eq!(files(), 0, "no object file is left");
2222 assert_eq!(
2223 bucket.tenant(tenant).list().expect("listed").len(),
2224 1,
2225 "the object is in the bucket"
2226 );
2227 let tenants = Tenants::open_beside_in(
2228 &config.data_dir,
2229 Key::load_master(&config.master_key).expect("master"),
2230 Arc::new(OsFs),
2231 Arc::new(SystemClock),
2232 crate::backend::ObjectPlace::S3(bucket.clone()),
2233 &crate::backend::Catalogs::Local,
2234 )
2235 .expect("opens");
2236 let (_, body) = vcon(UUID, "exported");
2237 assert_eq!(
2238 tenants
2239 .store(tenant)
2240 .expect("its store")
2241 .get(&Caller { key: KeyId([7; 8]) }, UUID.parse().expect("uuid"))
2242 .expect("reads")
2243 .body,
2244 body,
2245 "the vCon reads back from the bucket"
2246 );
2247 drop(tenants);
2248 assert_eq!(
2249 moving(&config),
2250 [
2251 json!({"tenant": id, "moved": 0, "missing": 0}),
2252 json!({"moved": 0})
2253 ],
2254 "a second run moves nothing"
2255 );
2256 }
2257
2258 fn store_one(s: &Setup, id: &str) {
2260 let store = s
2261 .tenants()
2262 .store(TenantId::parse(id).expect("an id"))
2263 .expect("the store");
2264 let (found, body) = vcon(UUID, "exported");
2265 store
2266 .create(&Caller { key: KeyId([7; 8]) }, &found, &body)
2267 .expect("stored");
2268 }
2269
2270 #[test]
2271 fn tenant_set_metadata_prints_the_level_and_list_shows_it() {
2272 let s = setup();
2273 let id = s.create("acme");
2274 let out = s
2275 .run(Command::TenantSetMetadata {
2276 id: id.clone(),
2277 metadata: "counts".to_owned(),
2278 })
2279 .expect("set");
2280 assert_eq!(
2281 out,
2282 [json!({ "id": id, "metadata": "counts" })],
2283 "the command prints the tenant and its level"
2284 );
2285 assert_eq!(
2286 s.run(Command::TenantList).expect("listed")[0]["metadata"],
2287 "counts",
2288 "the list shows the level"
2289 );
2290 assert!(
2291 matches!(
2292 s.run(Command::TenantSetMetadata {
2293 id: id.clone(),
2294 metadata: "most".to_owned(),
2295 }),
2296 Err(CommandError::BadLevel(text)) if text == "most"
2297 ),
2298 "a level that is not one is refused, naming it"
2299 );
2300 assert_eq!(
2301 tenant_error(s.run(Command::TenantSetMetadata {
2302 id: TenantId::generate().to_string(),
2303 metadata: "full".to_owned(),
2304 })),
2305 TenantError::NotFound,
2306 "a tenant id no tenant has is not found"
2307 );
2308 }
2309
2310 #[test]
2313 fn export_parquet_runs_beside_a_server_and_prints_what_it_wrote() {
2314 let s = setup();
2315 let id = s.create("acme");
2316 store_one(&s, &id);
2317 s.run(Command::TenantSetMetadata {
2318 id: id.clone(),
2319 metadata: "counts".to_owned(),
2320 })
2321 .expect("set");
2322 let to = s._dir.path().join("export");
2323 let export = Command::ExportParquet {
2324 tenant: id.clone(),
2325 to: to.display().to_string(),
2326 since: Some("2000-01-01T00:00:00Z".to_owned()),
2327 until: None,
2328 };
2329 let server = datadir::lock(&s.config.data_dir, Sharing::Serve).expect("a server");
2330 let out = s.run(export.clone()).expect("exports beside a server");
2331 drop(server);
2332 assert_eq!(out.len(), 1, "{out:?}");
2333 let line = &out[0];
2334 let manifest = format!("tenant={id}/manifest/00000000000000000001.json");
2335 assert_eq!(line["tenant"], id, "the line names the tenant");
2336 assert_eq!(
2337 line["metadata"], "counts",
2338 "the export is at the tenant's level"
2339 );
2340 assert_eq!(
2341 line["to"],
2342 to.display().to_string(),
2343 "the line names the target"
2344 );
2345 assert_eq!(line["manifest"], manifest, "the line names the manifest");
2346 assert_eq!(line["seq"], 1, "the first export to the target");
2347 assert_eq!(line["files"], 1, "one store date, one file");
2348 assert_eq!(line["rows"], 1, "the one vCon stored");
2349 assert_eq!(line["skipped"], 0, "nothing was purged during the run");
2350 assert_eq!(line["unread"], 0, "every body was read");
2351 let m: Value =
2352 serde_json::from_slice(&std::fs::read(to.join(&manifest)).expect("the manifest"))
2353 .expect("JSON");
2354 assert_eq!(m["bytes"], line["bytes"], "the bytes the manifest names");
2355 assert_eq!(
2356 m["since"], "2000-01-01T00:00:00Z",
2357 "the manifest records --since"
2358 );
2359 let alone = datadir::lock(&s.config.data_dir, Sharing::Alone).expect("alone");
2360 assert!(
2361 matches!(
2362 s.run(export),
2363 Err(CommandError::DataDir(LockError::InUse(Sharing::Beside)))
2364 ),
2365 "an export does not run beside a command that runs alone"
2366 );
2367 drop(alone);
2368 }
2369
2370 #[test]
2371 fn export_parquet_refuses_a_bad_time_target_or_tenant() {
2372 let s = setup();
2373 let id = s.create("acme");
2374 let export = |to: &str, since: Option<&str>, until: Option<&str>| Command::ExportParquet {
2375 tenant: id.clone(),
2376 to: to.to_owned(),
2377 since: since.map(str::to_owned),
2378 until: until.map(str::to_owned),
2379 };
2380 let dir = s._dir.path().join("out").display().to_string();
2381 assert!(
2382 matches!(
2383 s.run(export(&dir, Some("yesterday"), None)),
2384 Err(CommandError::BadTime(t)) if t == "yesterday"
2385 ),
2386 "a word that is not an RFC 3339 time is refused, naming it"
2387 );
2388 assert!(
2389 matches!(
2390 s.run(export(&dir, None, Some("2026-13-01T00:00:00Z"))),
2391 Err(CommandError::BadTime(_))
2392 ),
2393 "a month 13 is not a time"
2394 );
2395 assert!(
2396 matches!(
2397 s.run(export("s3://", None, None)),
2398 Err(CommandError::BadTarget(t)) if t == "s3://"
2399 ),
2400 "an s3:// URL with no bucket is refused, naming it"
2401 );
2402 assert!(
2403 matches!(
2404 s.run(export("s3://reports/vcon", None, None)),
2405 Err(CommandError::NoS3)
2406 ),
2407 "no S3 service is configured"
2408 );
2409 assert_eq!(
2410 tenant_error(s.run(Command::ExportParquet {
2411 tenant: TenantId::generate().to_string(),
2412 to: dir.clone(),
2413 since: None,
2414 until: None,
2415 })),
2416 TenantError::NotFound,
2417 "an unknown tenant is not found"
2418 );
2419 assert!(
2420 !std::path::Path::new(&dir).exists(),
2421 "a refused export writes nothing"
2422 );
2423 }
2424
2425 #[test]
2426 fn each_error_says_what_went_wrong() {
2427 let tenant = [
2428 TenantError::NotFound,
2429 TenantError::NameTaken,
2430 TenantError::BadName,
2431 TenantError::HoldsVcons,
2432 TenantError::UnderHold,
2433 TenantError::LimitReached,
2434 TenantError::AuditFailed,
2435 TenantError::Closing,
2436 TenantError::CliOnly,
2437 TenantError::BadScopes,
2438 TenantError::BadExpiry,
2439 TenantError::BadSetting(crate::settings::SettingError::UnknownName),
2440 TenantError::WrongKey,
2441 TenantError::NoFileBackup,
2442 TenantError::Io,
2443 ]
2444 .map(CommandError::Tenant);
2445 let backup = [
2446 BackupError::Exists,
2447 BackupError::KeptChanging,
2448 BackupError::Io,
2449 BackupError::AuditFailed,
2450 BackupError::NoFileBackup,
2451 ]
2452 .map(CommandError::Backup);
2453 let rest = [
2454 CommandError::DataDir(LockError::InUse(Sharing::Alone)),
2455 CommandError::MasterKey(crate::envelope::KeyError::WrongSize),
2456 CommandError::Open(RegistryError::failed(
2457 tenants::OpenStep::OpenCatalog,
2458 std::path::PathBuf::from("/srv/data/server.sqlite"),
2459 io::Error::other("disk I/O error"),
2460 )),
2461 CommandError::WrongMasterKey,
2462 CommandError::WrongDatabaseKey,
2463 CommandError::BadPeriod("7w".to_owned()),
2464 CommandError::UnknownKey,
2465 CommandError::Output(io::Error::other("closed")),
2466 CommandError::SameMasterKey,
2467 CommandError::CheckFound(2),
2468 CommandError::Storage(StorageError(
2469 "bucket \"vcon\" cannot be reached or read".to_owned(),
2470 )),
2471 CommandError::BadLevel("most".to_owned()),
2472 CommandError::BadTime("yesterday".to_owned()),
2473 CommandError::BadTarget("s3://".to_owned()),
2474 CommandError::NoS3,
2475 CommandError::Export(crate::export::ExportError::Raced("m".to_owned())),
2476 CommandError::Move {
2477 tenant: TenantId([1; 16]),
2478 why: "the bucket could not be written".to_owned(),
2479 },
2480 ];
2481 let user = [
2482 UserError::CliOnly,
2483 UserError::BadLabel,
2484 UserError::BadIdentity,
2485 UserError::IdentityTaken,
2486 UserError::NoUser,
2487 UserError::Deactivated,
2488 UserError::NoTenant,
2489 UserError::Closing,
2490 UserError::BadRoles,
2491 UserError::NoMembership,
2492 UserError::Registry(TenantError::Io),
2493 ]
2494 .map(CommandError::User);
2495 for error in tenant.into_iter().chain(backup).chain(rest).chain(user) {
2496 let text = error.to_string();
2497 assert!(text.contains(says(&error)), "{error:?}: {text}");
2498 }
2499 }
2500}