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