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 #[test]
1035 fn key_create_prints_the_expiry_of_the_key_it_makes() {
1036 let s = setup();
1037 let tenant = s.create("acme");
1038 let made = key_with(&s, &tenant, KeyLife::Default).expect("made");
1039 let listed = s.run(Command::KeyList { tenant: None }).expect("listed");
1040 assert_eq!(
1041 rfc3339(&made[0]["expires_at"]) - rfc3339(&listed[0]["created_at"]),
1042 time::Duration::days(90),
1043 "the default life"
1044 );
1045 assert_eq!(
1046 made[0]["expires_at"], listed[0]["expires_at"],
1047 "the list shows the same expiry"
1048 );
1049 assert!(listed[0]["last_used_at"].is_null(), "a key never used");
1050 }
1051
1052 #[test]
1053 fn key_create_makes_a_key_for_the_days_asked_or_with_no_expiry() {
1054 let s = setup();
1055 let tenant = s.create("acme");
1056 let week = key_with(&s, &tenant, KeyLife::Days(7)).expect("made");
1057 let never = key_with(&s, &tenant, KeyLife::Never).expect("made");
1058 let listed = s.run(Command::KeyList { tenant: None }).expect("listed");
1059 assert_eq!(
1060 rfc3339(&week[0]["expires_at"]) - rfc3339(&listed[0]["created_at"]),
1061 time::Duration::days(7),
1062 "seven days"
1063 );
1064 assert!(
1065 never[0]["expires_at"].is_null(),
1066 "no expiry is printed as null"
1067 );
1068 assert!(listed[1]["expires_at"].is_null(), "and listed as null");
1069 }
1070
1071 #[test]
1072 fn key_create_refuses_days_outside_1_to_365() {
1073 let s = setup();
1074 let tenant = s.create("acme");
1075 for days in [0, 366] {
1076 assert!(
1077 matches!(
1078 key_with(&s, &tenant, KeyLife::Days(days)),
1079 Err(CommandError::Tenant(TenantError::BadExpiry))
1080 ),
1081 "{days} days"
1082 );
1083 }
1084 let listed = s.run(Command::KeyList { tenant: None }).expect("listed");
1085 assert_eq!(listed.len(), 0, "no key was made");
1086 }
1087
1088 #[test]
1089 fn key_create_refuses_no_expiry_where_the_configuration_says_so() {
1090 let mut s = setup();
1091 let tenant = s.create("acme");
1092 s.config.keys_no_expiry = false;
1093 assert!(
1094 matches!(
1095 key_with(&s, &tenant, KeyLife::Never),
1096 Err(CommandError::Tenant(TenantError::BadExpiry))
1097 ),
1098 "a tenant key"
1099 );
1100 let operator = s.run(Command::KeyCreate {
1101 owner: Owner::Operator,
1102 label: "ops".to_owned(),
1103 life: KeyLife::Never,
1104 });
1105 assert!(
1106 matches!(operator, Err(CommandError::Tenant(TenantError::BadExpiry))),
1107 "an operator key"
1108 );
1109 assert!(
1110 key_with(&s, &tenant, KeyLife::Default).is_ok(),
1111 "a key with an expiry is still made"
1112 );
1113 }
1114
1115 #[test]
1116 fn an_operator_key_may_have_no_expiry_by_default() {
1117 let s = setup();
1118 let made = s
1119 .run(Command::KeyCreate {
1120 owner: Owner::Operator,
1121 label: "ops".to_owned(),
1122 life: KeyLife::Never,
1123 })
1124 .expect("made");
1125 assert!(made[0]["expires_at"].is_null(), "no expiry");
1126 }
1127
1128 fn tenant_error(result: Result<Vec<Value>, CommandError>) -> TenantError {
1129 match result {
1130 Err(CommandError::Tenant(e)) => e,
1131 other => panic!("not a tenant error: {other:?}"),
1132 }
1133 }
1134
1135 #[test]
1136 fn tenant_create_prints_the_new_id_and_list_shows_it() {
1137 let s = setup();
1138 let out = s
1139 .run(Command::TenantCreate {
1140 name: "acme".to_owned(),
1141 retention: Some("18m".to_owned()),
1142 })
1143 .expect("made");
1144 assert_eq!(out.len(), 1);
1145 let id = out[0]["id"].as_str().expect("an id").to_owned();
1146 assert!(TenantId::parse(&id).is_some(), "{id}");
1147 assert_eq!(out[0], json!({ "id": id }));
1148 let beta = s.create("beta");
1149 assert_eq!(
1150 s.run(Command::TenantList).expect("listed"),
1151 [
1152 json!({ "id": id, "name": "acme", "retention": "18m", "metadata": "none" }),
1153 json!({ "id": beta, "name": "beta", "retention": null, "metadata": "none" }),
1154 ]
1155 );
1156 }
1157
1158 #[test]
1159 fn a_bad_period_is_refused_before_anything_is_made() {
1160 let s = setup();
1161 let error = s
1162 .run(Command::TenantCreate {
1163 name: "acme".to_owned(),
1164 retention: Some("7w".to_owned()),
1165 })
1166 .expect_err("refused");
1167 assert!(
1168 matches!(&error, CommandError::BadPeriod(p) if p == "7w"),
1169 "{error:?}"
1170 );
1171 assert!(error.to_string().contains("7w"), "{error}");
1172 assert_eq!(
1173 s.run(Command::TenantList).expect("listed"),
1174 Vec::<Value>::new()
1175 );
1176 let id = s.create("acme");
1177 let error = s
1178 .run(Command::TenantSetRetention {
1179 id,
1180 retention: "forever".to_owned(),
1181 })
1182 .expect_err("refused");
1183 assert!(matches!(&error, CommandError::BadPeriod(p) if p == "forever"));
1184 }
1185
1186 #[test]
1187 fn set_retention_takes_a_period_or_default() {
1188 let s = setup();
1189 let id = s.create("acme");
1190 let set = |retention: &str| {
1191 s.run(Command::TenantSetRetention {
1192 id: id.clone(),
1193 retention: retention.to_owned(),
1194 })
1195 .expect("set")
1196 };
1197 assert_eq!(set("90d"), [json!({ "id": id, "retention": "90d" })]);
1198 assert_eq!(
1199 s.run(Command::TenantList).expect("listed")[0]["retention"],
1200 "90d"
1201 );
1202 assert_eq!(set("default"), [json!({ "id": id, "retention": null })]);
1203 assert_eq!(
1204 s.run(Command::TenantList).expect("listed")[0]["retention"],
1205 Value::Null
1206 );
1207 }
1208
1209 #[test]
1210 fn an_unknown_or_malformed_tenant_is_not_found() {
1211 let s = setup();
1212 for id in [TenantId::generate().to_string(), "not-an-id".to_owned()] {
1213 assert_eq!(
1214 tenant_error(s.run(Command::TenantSetRetention {
1215 id: id.clone(),
1216 retention: "7y".to_owned()
1217 })),
1218 TenantError::NotFound
1219 );
1220 assert_eq!(
1221 tenant_error(s.run(Command::TenantRemove {
1222 id: id.clone(),
1223 force: true,
1224 override_holds: false
1225 })),
1226 TenantError::NotFound
1227 );
1228 assert_eq!(
1229 tenant_error(s.run(Command::KeyCreate {
1230 owner: Owner::Tenant {
1231 id: id.clone(),
1232 scopes: vec!["read".to_owned()]
1233 },
1234 label: "l".to_owned(),
1235 life: KeyLife::Default,
1236 })),
1237 TenantError::NotFound
1238 );
1239 assert_eq!(
1240 tenant_error(s.run(Command::KeyList {
1241 tenant: Some(id.clone())
1242 })),
1243 TenantError::NotFound
1244 );
1245 assert_eq!(
1246 tenant_error(s.run(Command::AuditExport {
1247 log: Log::Tenant(id.clone()),
1248 since: None
1249 })),
1250 TenantError::NotFound
1251 );
1252 }
1253 }
1254
1255 #[test]
1258 fn remove_goes_as_far_as_its_flags_allow() {
1259 let s = setup();
1260 let empty = s.create("empty");
1261 let full = s.create("full");
1262 {
1263 let tenants = s.tenants();
1264 let store = tenants
1265 .store(TenantId::parse(&full).expect("id"))
1266 .expect("store");
1267 let caller = Caller { key: KeyId([1; 8]) };
1268 let (found, body) = vcon(UUID, "kept");
1269 store.create(&caller, &found, &body).expect("stored");
1270 store.set_hold(&caller, found.uuid, true).expect("held");
1271 }
1272 let remove = |id: &str, force, override_holds| {
1273 s.run(Command::TenantRemove {
1274 id: id.to_owned(),
1275 force,
1276 override_holds,
1277 })
1278 };
1279 assert_eq!(
1280 remove(&empty, false, false).expect("removed"),
1281 Vec::<Value>::new()
1282 );
1283 assert_eq!(
1284 tenant_error(remove(&full, false, false)),
1285 TenantError::HoldsVcons
1286 );
1287 assert_eq!(
1288 tenant_error(remove(&full, true, false)),
1289 TenantError::UnderHold
1290 );
1291 assert_eq!(
1292 remove(&full, true, true).expect("removed"),
1293 Vec::<Value>::new()
1294 );
1295 assert_eq!(
1296 s.run(Command::TenantList).expect("listed"),
1297 Vec::<Value>::new()
1298 );
1299 assert_eq!(s.tenant_dirs(), Vec::<String>::new());
1300 }
1301
1302 #[test]
1303 fn keys_are_made_listed_and_revoked() {
1304 let s = setup();
1305 let tenant = s.create("acme");
1306 let made = s
1307 .run(Command::KeyCreate {
1308 owner: Owner::Tenant {
1309 id: tenant.clone(),
1310 scopes: vec!["write".to_owned(), "read".to_owned()],
1311 },
1312 label: "producer".to_owned(),
1313 life: KeyLife::Default,
1314 })
1315 .expect("made");
1316 let id = made[0]["id"].as_str().expect("id").to_owned();
1317 let token = made[0]["token"].as_str().expect("token").to_owned();
1318 assert_eq!(made.len(), 1);
1319 assert_eq!(made[0].as_object().expect("object").len(), 3);
1320 assert!(token.starts_with(&format!("vcs_{id}_")), "{token}");
1321 let operator = s
1322 .run(Command::KeyCreate {
1323 owner: Owner::Operator,
1324 label: "ops".to_owned(),
1325 life: KeyLife::Default,
1326 })
1327 .expect("made")[0]["id"]
1328 .as_str()
1329 .expect("id")
1330 .to_owned();
1331
1332 let listed = s.run(Command::KeyList { tenant: None }).expect("listed");
1333 assert_eq!(listed.len(), 2);
1334 assert_eq!(listed[0]["id"], id.as_str());
1335 assert_eq!(listed[0]["tenant"], tenant.as_str());
1336 assert_eq!(listed[0]["scopes"], json!(["write", "read"]));
1337 assert_eq!(listed[0]["label"], "producer");
1338 assert_eq!(listed[0]["revoked_at"], Value::Null);
1339 assert!(
1340 listed[0]["created_at"]
1341 .as_str()
1342 .is_some_and(|t| t.ends_with('Z'))
1343 );
1344 assert!(
1345 listed.iter().all(|k| k.get("token").is_none()),
1346 "never a token"
1347 );
1348 assert_eq!(listed[1]["id"], operator.as_str());
1349 assert_eq!(listed[1]["tenant"], Value::Null);
1350 assert_eq!(listed[1]["scopes"], json!(["admin"]));
1351
1352 let own = s
1353 .run(Command::KeyList {
1354 tenant: Some(tenant.clone()),
1355 })
1356 .expect("listed");
1357 assert_eq!(own, listed[..1]);
1358
1359 assert_eq!(
1360 s.run(Command::KeyRevoke { id: id.clone() })
1361 .expect("revoked"),
1362 Vec::<Value>::new()
1363 );
1364 let listed = s.run(Command::KeyList { tenant: None }).expect("listed");
1365 assert!(listed[0]["revoked_at"].as_str().is_some(), "{listed:?}");
1366 assert_eq!(listed[1]["revoked_at"], Value::Null);
1367 }
1368
1369 #[test]
1370 fn bad_scopes_and_unknown_keys_are_refused() {
1371 let s = setup();
1372 let tenant = s.create("acme");
1373 for scopes in [
1374 vec!["superuser"],
1375 vec!["read", "superuser"],
1376 vec!["read", "read"],
1377 vec!["admin"],
1378 vec![],
1379 ] {
1380 let error = s.run(Command::KeyCreate {
1381 owner: Owner::Tenant {
1382 id: tenant.clone(),
1383 scopes: scopes.iter().map(|s| (*s).to_owned()).collect(),
1384 },
1385 label: "l".to_owned(),
1386 life: KeyLife::Default,
1387 });
1388 assert_eq!(tenant_error(error), TenantError::BadScopes, "{scopes:?}");
1389 }
1390 assert_eq!(
1391 s.run(Command::KeyList { tenant: None }).expect("listed"),
1392 Vec::<Value>::new()
1393 );
1394 for id in ["0123456789abcdef".to_owned(), "nope".to_owned()] {
1395 assert!(
1396 matches!(
1397 s.run(Command::KeyRevoke { id }),
1398 Err(CommandError::UnknownKey)
1399 ),
1400 "unknown"
1401 );
1402 }
1403 }
1404
1405 #[test]
1406 fn audit_export_writes_either_log_from_a_sequence_number() {
1407 let s = setup();
1408 let tenant = s.create("acme");
1409 s.run(Command::TenantList).expect("listed");
1410 s.run(Command::KeyCreate {
1411 owner: Owner::Tenant {
1412 id: tenant.clone(),
1413 scopes: vec!["read".to_owned()],
1414 },
1415 label: "l".to_owned(),
1416 life: KeyLife::Default,
1417 })
1418 .expect("made");
1419
1420 let admin = s
1421 .run(Command::AuditExport {
1422 log: Log::Admin,
1423 since: None,
1424 })
1425 .expect("exported");
1426 let actions: Vec<&str> = admin
1427 .iter()
1428 .map(|r| r["action"].as_str().expect("action"))
1429 .collect();
1430 assert_eq!(actions, ["tenant_create", "tenant_list", "key_create"]);
1431 assert!(admin.iter().all(|r| r["actor"] == "cli"));
1432 let since = admin[0]["seq"].as_i64().expect("seq");
1433 let later = s
1434 .run(Command::AuditExport {
1435 log: Log::Admin,
1436 since: Some(since),
1437 })
1438 .expect("exported");
1439 assert_eq!(later, admin[1..]);
1440
1441 let own = s
1442 .run(Command::AuditExport {
1443 log: Log::Tenant(tenant),
1444 since: None,
1445 })
1446 .expect("exported");
1447 let actions: Vec<&str> = own
1448 .iter()
1449 .map(|r| r["action"].as_str().expect("action"))
1450 .collect();
1451 assert_eq!(actions, ["key_create"]);
1452 }
1453
1454 #[test]
1455 fn rekey_tenant_rotates_the_key_and_prints_nothing() {
1456 let s = setup();
1457 let id = s.create("acme");
1458 let tenant = TenantId::parse(&id).expect("id");
1459 let before = s.tenants().tenant_key_id_for_test(tenant);
1460 assert_eq!(
1461 s.run(Command::RekeyTenant { id: id.clone() })
1462 .expect("rekeyed"),
1463 Vec::<Value>::new()
1464 );
1465 assert_ne!(s.tenants().tenant_key_id_for_test(tenant), before);
1466 assert_eq!(
1467 tenant_error(s.run(Command::RekeyTenant {
1468 id: TenantId::generate().to_string()
1469 })),
1470 TenantError::NotFound
1471 );
1472 let server = datadir::lock(&s.config.data_dir, Sharing::Serve).expect("a server");
1473 assert!(matches!(
1474 s.run(Command::RekeyTenant { id }),
1475 Err(CommandError::DataDir(LockError::InUse(Sharing::Alone)))
1476 ));
1477 drop(server);
1478 }
1479
1480 #[test]
1481 fn rekey_master_moves_the_data_to_the_new_master_key() {
1482 let mut s = setup();
1483 s.create("acme");
1484 let new_file = s.config.master_key.with_file_name("new.key");
1485 std::fs::write(&new_file, [0x5c; 32]).expect("new key");
1486 chmod(&new_file, 0o600);
1487 assert!(matches!(
1488 s.run(Command::RekeyMaster {
1489 new_master: s.config.master_key.clone()
1490 }),
1491 Err(CommandError::SameMasterKey)
1492 ));
1493 let server = datadir::lock(&s.config.data_dir, Sharing::Serve).expect("a server");
1494 assert!(matches!(
1495 s.run(Command::RekeyMaster {
1496 new_master: new_file.clone()
1497 }),
1498 Err(CommandError::DataDir(LockError::InUse(Sharing::Alone)))
1499 ));
1500 drop(server);
1501 let out = s
1502 .run(Command::RekeyMaster {
1503 new_master: new_file.clone(),
1504 })
1505 .expect("rotated");
1506 let new_id = Key::load_master(&new_file).expect("key").id().to_string();
1507 assert_eq!(out.len(), 1);
1508 assert_eq!(out[0]["master_key_id"], new_id.as_str());
1509 assert!(
1510 out[0]["next"]
1511 .as_str()
1512 .is_some_and(|n| n.contains("destroy"))
1513 );
1514 assert!(matches!(
1515 s.run(Command::TenantList),
1516 Err(CommandError::WrongMasterKey)
1517 ));
1518 s.config.master_key = new_file;
1519 assert_eq!(s.run(Command::TenantList).expect("listed").len(), 1);
1520 }
1521
1522 mod check {
1523 use time::macros::datetime;
1524
1525 use super::*;
1526 use crate::ids::VersionId;
1527 use crate::store::{Examination, StoreError};
1528
1529 const NOW: OffsetDateTime = datetime!(2026-10-25 12:00 UTC);
1530 const HOUR: std::time::Duration = std::time::Duration::from_secs(3600);
1531
1532 fn sound() -> Examination {
1533 Examination {
1534 versions: 3,
1535 packed: 0,
1536 damaged: vec![],
1537 leftovers: vec!["a.tmp".to_owned()],
1538 due: 0,
1539 oldest_due_since: None,
1540 purges_since_key: 4,
1541 oldest_purge_since_key: Some(datetime!(2026-10-01 00:00 UTC)),
1542 }
1543 }
1544
1545 fn tenant(store: Result<Examination, Unexamined>, stopped: bool) -> TenantExamination {
1546 TenantExamination {
1547 id: TenantId([1; 16]),
1548 name: "acme".to_owned(),
1549 rotation_stopped: stopped,
1550 store,
1551 }
1552 }
1553
1554 #[test]
1555 fn leftovers_and_work_waiting_for_rotation_are_not_problems() {
1556 assert_eq!(
1557 problems(&tenant(Ok(sound()), false), HOUR, NOW, true),
1558 Vec::<String>::new()
1559 );
1560 }
1561
1562 #[test]
1563 fn each_problem_is_named() {
1564 let damaged = Examination {
1565 damaged: vec![VersionId([2; 16]), VersionId([3; 16])],
1566 ..sound()
1567 };
1568 assert_eq!(
1569 problems(&tenant(Ok(damaged), false), HOUR, NOW, true),
1570 [
1571 "version 02020202020202020202020202020202 is missing or does not open",
1572 "version 03030303030303030303030303030303 is missing or does not open",
1573 ],
1574 "one line per damaged version, in its order"
1575 );
1576 assert_eq!(
1577 problems(&tenant(Ok(sound()), true), HOUR, NOW, true),
1578 ["a key rotation was stopped part way; run rekey tenant again"],
1579 "a stopped rotation is named with the command that finishes it"
1580 );
1581 assert_eq!(
1582 problems(
1583 &tenant(
1584 Err(Unexamined::Open(OpenFailure::Refused(TenantError::Io))),
1585 false
1586 ),
1587 HOUR,
1588 NOW,
1589 true,
1590 ),
1591 ["its catalog cannot be opened: Io"],
1592 "a refused catalog names the refusal, not a key"
1593 );
1594 }
1595
1596 #[test]
1600 fn a_key_problem_and_an_access_problem_are_told_apart() {
1601 let key = problems(
1602 &tenant(Err(Unexamined::Open(OpenFailure::WrongKey)), false),
1603 HOUR,
1604 NOW,
1605 true,
1606 );
1607 assert_eq!(key, ["its catalog does not open under its tenant key"]);
1608 let access = OpenFailure::Access {
1609 path: std::path::PathBuf::from("/srv/data/tenants/01/catalog.sqlite"),
1610 error: std::io::Error::from_raw_os_error(libc::EACCES),
1611 };
1612 assert_eq!(
1613 problems(
1614 &tenant(Err(Unexamined::Open(access)), false),
1615 HOUR,
1616 NOW,
1617 true
1618 ),
1619 [
1620 "its catalog cannot be opened: /srv/data/tenants/01/catalog.sqlite: Permission denied (os error 13)"
1621 ]
1622 );
1623 }
1624
1625 #[test]
1629 fn packed_versions_without_storage_parquet_are_a_problem() {
1630 let packed = Examination {
1631 packed: 2,
1632 ..sound()
1633 };
1634 assert_eq!(
1635 problems(&tenant(Ok(packed.clone()), false), HOUR, NOW, false),
1636 [
1637 "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"
1638 ],
1639 "without the table"
1640 );
1641 assert_eq!(
1642 problems(&tenant(Ok(packed), false), HOUR, NOW, true),
1643 Vec::<String>::new(),
1644 "with the table"
1645 );
1646 assert_eq!(
1647 problems(&tenant(Ok(sound()), false), HOUR, NOW, false),
1648 Vec::<String>::new(),
1649 "nothing packed"
1650 );
1651 }
1652
1653 #[test]
1658 fn objects_that_cannot_be_read_are_told_apart_from_a_catalog() {
1659 let unread = |kind, os_error| {
1660 problems(
1661 &tenant(
1662 Err(Unexamined::Examine(ExamineError::Objects {
1663 kind,
1664 os_error,
1665 })),
1666 false,
1667 ),
1668 HOUR,
1669 NOW,
1670 true,
1671 )
1672 };
1673 assert_eq!(
1674 unread(std::io::ErrorKind::PermissionDenied, Some(libc::EACCES)),
1675 ["its objects cannot be read: permission denied (os error 13)"],
1676 "a file the process may not read"
1677 );
1678 assert_eq!(
1679 unread(std::io::ErrorKind::TimedOut, None),
1680 ["its objects cannot be read: timed out"],
1681 "a service's failure has a kind and no system error number"
1682 );
1683 assert_eq!(
1684 problems(
1685 &tenant(
1686 Err(Unexamined::Examine(ExamineError::Failed(StoreError::Io))),
1687 false
1688 ),
1689 HOUR,
1690 NOW,
1691 true,
1692 ),
1693 ["it could not be examined: Io"],
1694 "any other failure, with its error"
1695 );
1696 }
1697
1698 #[test]
1699 fn a_sweep_is_stalled_only_once_a_version_waited_longer_than_the_interval() {
1700 let waited = |since| Examination {
1701 due: 1,
1702 oldest_due_since: Some(since),
1703 ..sound()
1704 };
1705 let ok = waited(datetime!(2026-10-25 11:00 UTC));
1706 assert_eq!(
1707 problems(&tenant(Ok(ok), false), HOUR, NOW, true),
1708 Vec::<String>::new()
1709 );
1710 let stalled = waited(datetime!(2026-10-25 10:59:59 UTC));
1711 assert_eq!(
1712 problems(&tenant(Ok(stalled), false), HOUR, NOW, true),
1713 [
1714 "1 version(s) due for purge, the oldest longer than purge_interval: the sweep is not keeping up"
1715 ],
1716 "one second past purge_interval is a stalled sweep"
1717 );
1718 }
1719
1720 #[test]
1721 fn check_reports_each_tenant_and_a_summary_and_exits_1_on_a_problem() {
1722 let s = setup();
1723 let id = s.create("acme");
1724 let out = s.run(Command::Check).expect("nothing wrong");
1725 assert_eq!(out.len(), 2);
1726 assert_eq!(out[0]["tenant"], id.as_str());
1727 assert_eq!(out[0]["problems"], json!([]));
1728 assert_eq!(out[1]["tenants"], 1);
1729 assert_eq!(out[1]["problems"], 0);
1730
1731 let tenant = TenantId::parse(&id).expect("id");
1732 let version = {
1733 let tenants = s.tenants();
1734 let store = tenants.store(tenant).expect("store");
1735 let (found, body) = vcon(UUID, "kept");
1736 let Ok(crate::store::Created::New(v)) =
1737 store.create(&Caller { key: KeyId([1; 8]) }, &found, &body)
1738 else {
1739 panic!("stored")
1740 };
1741 v
1742 };
1743 let objects = s.config.data_dir.join("tenants").join(&id).join("objects");
1744 std::fs::remove_file(objects.join(version.to_string())).expect("remove");
1745 std::fs::write(objects.join(format!("{version}.tmp")), b"x").expect("leftover");
1746 let mut printed = Vec::new();
1747 let found = run(&s.config, &Command::Check, &mut printed);
1748 assert!(
1749 matches!(found, Err(CommandError::CheckFound(1))),
1750 "{found:?}"
1751 );
1752 let lines: Vec<Value> = String::from_utf8(printed)
1753 .expect("text")
1754 .lines()
1755 .map(|l| serde_json::from_str(l).expect("json"))
1756 .collect();
1757 assert_eq!(lines[0]["damaged"], json!([version.to_string()]));
1758 assert_eq!(lines[0]["leftovers"], json!([format!("{version}.tmp")]));
1759 assert_eq!(lines[1]["problems"], 1);
1760 assert!(
1761 objects.join(format!("{version}.tmp")).exists(),
1762 "check reports leftovers; it does not remove them"
1763 );
1764 let server = datadir::lock(&s.config.data_dir, Sharing::Serve).expect("a server");
1765 assert!(matches!(
1766 s.run(Command::Check),
1767 Err(CommandError::DataDir(LockError::InUse(Sharing::Alone)))
1768 ));
1769 drop(server);
1770 }
1771 }
1772
1773 #[test]
1776 fn beside_a_server_only_the_beside_commands_run() {
1777 let s = setup();
1778 let tenant = s.create("acme");
1779 let server = datadir::lock(&s.config.data_dir, Sharing::Serve).expect("a server");
1780 for command in [
1781 Command::TenantCreate {
1782 name: "beta".to_owned(),
1783 retention: None,
1784 },
1785 Command::TenantRemove {
1786 id: tenant.clone(),
1787 force: true,
1788 override_holds: false,
1789 },
1790 ] {
1791 assert!(
1792 matches!(
1793 s.run(command.clone()),
1794 Err(CommandError::DataDir(LockError::InUse(Sharing::Alone)))
1795 ),
1796 "{command:?}"
1797 );
1798 }
1799 s.run(Command::TenantList).expect("beside");
1800 s.run(Command::TenantSetRetention {
1801 id: tenant.clone(),
1802 retention: "1y".to_owned(),
1803 })
1804 .expect("beside");
1805 s.run(Command::KeyList { tenant: None }).expect("beside");
1806 let made = s
1807 .run(Command::KeyCreate {
1808 owner: Owner::Operator,
1809 label: "l".to_owned(),
1810 life: KeyLife::Default,
1811 })
1812 .expect("beside");
1813 s.run(Command::KeyRevoke {
1814 id: made[0]["id"].as_str().expect("an id").to_owned(),
1815 })
1816 .expect("beside");
1817 s.run(Command::AuditExport {
1818 log: Log::Admin,
1819 since: None,
1820 })
1821 .expect("beside");
1822 s.run(Command::Backup {
1823 to: s._dir.path().join("backup"),
1824 })
1825 .expect("beside");
1826 drop(server);
1827 assert_eq!(s.run(Command::TenantList).expect("listed").len(), 1);
1828 }
1829
1830 #[test]
1833 fn only_a_command_that_runs_alone_recovers() {
1834 let s = setup();
1835 s.create("acme");
1836 let in_progress = TenantId::generate().to_string();
1837 std::fs::create_dir(s.config.data_dir.join("tenants").join(&in_progress))
1838 .expect("a directory with no row");
1839 s.run(Command::TenantList).expect("listed");
1840 s.run(Command::KeyList { tenant: None }).expect("listed");
1841 assert!(
1842 s.tenant_dirs().contains(&in_progress),
1843 "left by beside commands"
1844 );
1845 s.create("beta");
1846 assert!(
1847 !s.tenant_dirs().contains(&in_progress),
1848 "removed by an alone command"
1849 );
1850 }
1851
1852 #[test]
1853 fn a_master_key_other_users_may_read_stops_every_command() {
1854 let s = setup();
1855 s.create("acme");
1856 chmod(&s.config.master_key, 0o644);
1857 let error = s.run(Command::TenantList).expect_err("refused");
1858 let path = s.config.master_key.display();
1859 assert_eq!(
1860 error.to_string(),
1861 format!(
1862 "the master key cannot be read: master_key {path}: other users may read or \
1863 change the file (mode 0644); run `chmod 600 {path}`, or `chmod 640 {path}` for \
1864 a group that only reads it"
1865 ),
1866 "the command stops with the rule's text, naming the key, the file and the fix"
1867 );
1868 }
1869
1870 #[test]
1871 fn rekey_master_refuses_a_new_key_other_users_may_read_under_its_option() {
1872 let s = setup();
1873 s.create("acme");
1874 let new_file = s.config.master_key.with_file_name("new.key");
1875 std::fs::write(&new_file, [0x5c; 32]).expect("new key");
1876 chmod(&new_file, 0o644);
1877 let error = s
1878 .run(Command::RekeyMaster {
1879 new_master: new_file.clone(),
1880 })
1881 .expect_err("refused");
1882 assert!(
1883 error
1884 .to_string()
1885 .contains(&format!("--new-master {}: other users", new_file.display())),
1886 "{error}"
1887 );
1888 }
1889
1890 #[cfg(feature = "s3")]
1891 #[test]
1892 fn an_export_secret_other_users_may_read_is_refused_under_export_s3() {
1893 let s = setup();
1894 let secret = s.config.master_key.with_file_name("export.secret");
1895 std::fs::write(&secret, "k3y-0123\n").expect("secret");
1896 chmod(&secret, 0o644);
1897 let mut config = s.config.clone();
1898 config.export = crate::config::parse(&format!(
1899 "listen = \"127.0.0.1:1\"\ndata_dir = \"/d\"\nmaster_key = \"/m\"\n\
1900 [tls]\ncert = \"c\"\nkey = \"k\"\n\
1901 [export.s3]\nendpoint = \"http://127.0.0.1:9\"\nregion = \"eu-west-3\"\n\
1902 access_key_id = \"id\"\nsecret_access_key_file = {secret:?}\nallow_http = true\n"
1903 ))
1904 .expect("a configuration")
1905 .export;
1906 let error = s3_target(&config, "vcon", "").err().expect("refused");
1907 let text = error.to_string();
1908 assert!(
1909 text.contains(&format!(
1910 "export.s3.secret_access_key_file {}: other users",
1911 secret.display()
1912 )),
1913 "{text}"
1914 );
1915 assert!(!text.contains("k3y"), "{text}");
1916 }
1917
1918 #[test]
1921 fn a_user_commands_registry_failure_is_the_registrys_error() {
1922 for (failure, words) in [
1923 (
1924 TenantError::AuditFailed,
1925 "the audit record could not be written",
1926 ),
1927 (
1928 TenantError::WrongKey,
1929 "is not the one server.sqlite was made under",
1930 ),
1931 ] {
1932 let error = CommandError::from(UserError::Registry(failure));
1933 assert!(
1934 matches!(error, CommandError::Tenant(e) if e == failure),
1935 "{failure:?} is carried as the registry's error: {error:?}"
1936 );
1937 assert!(error.to_string().contains(words), "{error}");
1938 }
1939 assert!(
1940 matches!(
1941 CommandError::from(UserError::NoUser),
1942 CommandError::User(UserError::NoUser)
1943 ),
1944 "a refusal stays a user error"
1945 );
1946 }
1947
1948 #[test]
1949 fn a_wrong_master_key_is_named() {
1950 let s = setup();
1951 s.create("acme");
1952 std::fs::write(&s.config.master_key, [0x5b; 32]).expect("another key");
1953 let error = s.run(Command::TenantList).expect_err("refused");
1954 assert!(matches!(error, CommandError::WrongMasterKey), "{error:?}");
1955 assert!(error.to_string().contains("master key"), "{error}");
1956 std::fs::write(&s.config.master_key, [0x5a; 31]).expect("short key");
1957 let error = s.run(Command::TenantList).expect_err("refused");
1958 assert!(matches!(error, CommandError::MasterKey(_)), "{error:?}");
1959 }
1960
1961 #[test]
1962 fn backup_prints_what_it_copied_and_check_finds_the_copy_whole() {
1963 let s = setup();
1964 s.create("acme");
1965 s.create("globex");
1966 let to = s._dir.path().join("backup");
1967 let out = s.run(Command::Backup { to: to.clone() }).expect("backs up");
1968 assert_eq!(
1969 out,
1970 [serde_json::json!({ "tenants": 2, "versions": 0, "tries": 1 })]
1971 );
1972 let copy = Setup {
1973 _dir: tempfile::tempdir().expect("temp dir"),
1974 config: Config {
1975 data_dir: to,
1976 ..s.config.clone()
1977 },
1978 };
1979 let checked = copy.run(Command::Check).expect("check finds no problem");
1980 assert_eq!(checked.last().expect("a summary")["problems"], 0);
1981 let names: Vec<_> = copy
1982 .run(Command::TenantList)
1983 .expect("lists")
1984 .iter()
1985 .map(|t| t["name"].clone())
1986 .collect();
1987 assert_eq!(names, ["acme", "globex"]);
1988 }
1989
1990 #[test]
1991 fn a_backup_path_already_there_is_refused() {
1992 let s = setup();
1993 let to = s._dir.path().join("backup");
1994 std::fs::create_dir(&to).expect("dir");
1995 let error = s.run(Command::Backup { to }).expect_err("refused");
1996 assert!(
1997 matches!(error, CommandError::Backup(BackupError::Exists)),
1998 "{error:?}"
1999 );
2000 }
2001
2002 fn says(error: &CommandError) -> &'static str {
2006 match error {
2007 CommandError::DataDir(_) => "the data directory is in use",
2008 CommandError::MasterKey(_) => "the master key cannot be read",
2009 CommandError::Open(_) => "opening /srv/data/server.sqlite failed: disk I/O error",
2011 CommandError::WrongMasterKey => "is not the one server.sqlite was made under",
2012 CommandError::BadPeriod(_) => "\"7w\" is not a period",
2013 CommandError::UnknownKey => "no key has this id",
2014 CommandError::User(e) => match e {
2015 UserError::CliOnly => "command line",
2016 UserError::BadLabel => "a user label is",
2017 UserError::BadIdentity => "an issuer is an https:// URL",
2018 UserError::IdentityTaken => "an active user has this issuer and subject",
2019 UserError::NoUser => "no user has this id",
2020 UserError::Deactivated => "the user is deactivated",
2021 UserError::NoTenant => "no tenant has this id",
2022 UserError::Closing => "being removed",
2023 UserError::BadRoles => "reader, producer, records, legal, auditor and tenant-admin",
2024 UserError::OverCap => "outside the tenant's role cap",
2025 UserError::BadCap => "a role cap is one or more of",
2026 UserError::NoMembership => "the user has no such membership",
2027 UserError::Registry(_) => "could not be read or written",
2028 },
2029 CommandError::Output(_) => "the output could not be written",
2030 CommandError::SameMasterKey => "already in use",
2031 CommandError::CheckFound(_) => "check found 2 problem(s)",
2032 CommandError::Storage(_) => "the storage cannot be used: bucket \"vcon\"",
2033 CommandError::BadLevel(_) => "\"most\" is not a metadata level",
2034 CommandError::BadTime(_) => "\"yesterday\" is not an RFC 3339 time",
2035 CommandError::BadTarget(_) => "\"s3://\" is not a directory or an s3://bucket/prefix",
2036 CommandError::NoS3 => "[export.s3] or [storage.s3]",
2037 CommandError::Export(_) => "another export wrote",
2038 CommandError::Move { .. } => "running storage move-objects again moves the rest",
2039 CommandError::Backup(e) => match e {
2040 BackupError::Exists => "already exists",
2041 BackupError::KeptChanging => "try again",
2042 BackupError::Io => "could not be written",
2043 BackupError::AuditFailed => "audit record",
2044 },
2045 CommandError::Tenant(e) => match e {
2046 TenantError::NotFound => "no tenant",
2047 TenantError::NameTaken => "another tenant has this name",
2048 TenantError::BadName => "a tenant name is",
2049 TenantError::HoldsVcons => "--force",
2050 TenantError::UnderHold => "--override-holds",
2051 TenantError::LimitReached => "rekey master",
2052 TenantError::AuditFailed => "audit record",
2053 TenantError::Closing => "being removed",
2054 TenantError::CliOnly => "command line",
2055 TenantError::BadScopes => "scopes",
2056 TenantError::BadExpiry => "1 to 365 days",
2057 TenantError::BadSetting(_) => "setting",
2058 TenantError::WrongKey => "is not the one server.sqlite was made under",
2061 TenantError::Io => "could not be read or written",
2062 },
2063 }
2064 }
2065
2066 #[test]
2069 fn storage_move_objects_needs_a_bucket() {
2070 let s = setup();
2071 s.create("acme");
2072 let error = s.run(Command::StorageMoveObjects).expect_err("refused");
2073 assert!(
2074 error.to_string().contains("storage.objects = \"s3\""),
2075 "names the setting: {error}"
2076 );
2077 }
2078
2079 #[cfg(feature = "backend-tests")]
2083 #[test]
2084 fn storage_move_objects_moves_each_tenants_objects_to_the_bucket() {
2085 use crate::backend::Objects;
2086 let s = setup();
2087 let id = s.create("acme");
2088 store_one(&s, &id);
2089 let tenant = TenantId::parse(&id).expect("an id");
2090 let local = s.config.data_dir.join("tenants").join(&id).join("objects");
2091 let files = || std::fs::read_dir(&local).expect("listed").count();
2092 assert_eq!(files(), 1, "one object file");
2093 let (bucket, mut settings) = crate::backend::s3::remote::bucket(false);
2094 let secret = crate::backend::s3::remote::secret_file();
2095 settings.secret_access_key_file = Some(secret.1.clone());
2096 let mut config = s.config.clone();
2097 config.storage = crate::config::Storage {
2098 objects: crate::config::ObjectStore::S3(settings),
2099 parquet: None,
2100 };
2101 let moving = |config: &Config| -> Vec<Value> {
2102 let mut out = Vec::new();
2103 run(config, &Command::StorageMoveObjects, &mut out).expect("moved");
2104 String::from_utf8(out)
2105 .expect("text")
2106 .lines()
2107 .map(|l| serde_json::from_str(l).expect("a JSON line"))
2108 .collect()
2109 };
2110 assert_eq!(
2111 moving(&config),
2112 [
2113 json!({"tenant": id, "moved": 1, "missing": 0}),
2114 json!({"moved": 1})
2115 ],
2116 "one object moved, and nothing missing"
2117 );
2118 assert_eq!(files(), 0, "no object file is left");
2119 assert_eq!(
2120 bucket.tenant(tenant).list().expect("listed").len(),
2121 1,
2122 "the object is in the bucket"
2123 );
2124 let tenants = Tenants::open_beside_in(
2125 &config.data_dir,
2126 Key::load_master(&config.master_key).expect("master"),
2127 Arc::new(OsFs),
2128 Arc::new(SystemClock),
2129 crate::backend::ObjectPlace::S3(bucket.clone()),
2130 )
2131 .expect("opens");
2132 let (_, body) = vcon(UUID, "exported");
2133 assert_eq!(
2134 tenants
2135 .store(tenant)
2136 .expect("its store")
2137 .get(&Caller { key: KeyId([7; 8]) }, UUID.parse().expect("uuid"))
2138 .expect("reads")
2139 .body,
2140 body,
2141 "the vCon reads back from the bucket"
2142 );
2143 drop(tenants);
2144 assert_eq!(
2145 moving(&config),
2146 [
2147 json!({"tenant": id, "moved": 0, "missing": 0}),
2148 json!({"moved": 0})
2149 ],
2150 "a second run moves nothing"
2151 );
2152 }
2153
2154 fn store_one(s: &Setup, id: &str) {
2156 let store = s
2157 .tenants()
2158 .store(TenantId::parse(id).expect("an id"))
2159 .expect("the store");
2160 let (found, body) = vcon(UUID, "exported");
2161 store
2162 .create(&Caller { key: KeyId([7; 8]) }, &found, &body)
2163 .expect("stored");
2164 }
2165
2166 #[test]
2167 fn tenant_set_metadata_prints_the_level_and_list_shows_it() {
2168 let s = setup();
2169 let id = s.create("acme");
2170 let out = s
2171 .run(Command::TenantSetMetadata {
2172 id: id.clone(),
2173 metadata: "counts".to_owned(),
2174 })
2175 .expect("set");
2176 assert_eq!(
2177 out,
2178 [json!({ "id": id, "metadata": "counts" })],
2179 "the command prints the tenant and its level"
2180 );
2181 assert_eq!(
2182 s.run(Command::TenantList).expect("listed")[0]["metadata"],
2183 "counts",
2184 "the list shows the level"
2185 );
2186 assert!(
2187 matches!(
2188 s.run(Command::TenantSetMetadata {
2189 id: id.clone(),
2190 metadata: "most".to_owned(),
2191 }),
2192 Err(CommandError::BadLevel(text)) if text == "most"
2193 ),
2194 "a level that is not one is refused, naming it"
2195 );
2196 assert_eq!(
2197 tenant_error(s.run(Command::TenantSetMetadata {
2198 id: TenantId::generate().to_string(),
2199 metadata: "full".to_owned(),
2200 })),
2201 TenantError::NotFound,
2202 "a tenant id no tenant has is not found"
2203 );
2204 }
2205
2206 #[test]
2209 fn export_parquet_runs_beside_a_server_and_prints_what_it_wrote() {
2210 let s = setup();
2211 let id = s.create("acme");
2212 store_one(&s, &id);
2213 s.run(Command::TenantSetMetadata {
2214 id: id.clone(),
2215 metadata: "counts".to_owned(),
2216 })
2217 .expect("set");
2218 let to = s._dir.path().join("export");
2219 let export = Command::ExportParquet {
2220 tenant: id.clone(),
2221 to: to.display().to_string(),
2222 since: Some("2000-01-01T00:00:00Z".to_owned()),
2223 until: None,
2224 };
2225 let server = datadir::lock(&s.config.data_dir, Sharing::Serve).expect("a server");
2226 let out = s.run(export.clone()).expect("exports beside a server");
2227 drop(server);
2228 assert_eq!(out.len(), 1, "{out:?}");
2229 let line = &out[0];
2230 let manifest = format!("tenant={id}/manifest/00000000000000000001.json");
2231 assert_eq!(line["tenant"], id, "the line names the tenant");
2232 assert_eq!(
2233 line["metadata"], "counts",
2234 "the export is at the tenant's level"
2235 );
2236 assert_eq!(
2237 line["to"],
2238 to.display().to_string(),
2239 "the line names the target"
2240 );
2241 assert_eq!(line["manifest"], manifest, "the line names the manifest");
2242 assert_eq!(line["seq"], 1, "the first export to the target");
2243 assert_eq!(line["files"], 1, "one store date, one file");
2244 assert_eq!(line["rows"], 1, "the one vCon stored");
2245 assert_eq!(line["skipped"], 0, "nothing was purged during the run");
2246 assert_eq!(line["unread"], 0, "every body was read");
2247 let m: Value =
2248 serde_json::from_slice(&std::fs::read(to.join(&manifest)).expect("the manifest"))
2249 .expect("JSON");
2250 assert_eq!(m["bytes"], line["bytes"], "the bytes the manifest names");
2251 assert_eq!(
2252 m["since"], "2000-01-01T00:00:00Z",
2253 "the manifest records --since"
2254 );
2255 let alone = datadir::lock(&s.config.data_dir, Sharing::Alone).expect("alone");
2256 assert!(
2257 matches!(
2258 s.run(export),
2259 Err(CommandError::DataDir(LockError::InUse(Sharing::Beside)))
2260 ),
2261 "an export does not run beside a command that runs alone"
2262 );
2263 drop(alone);
2264 }
2265
2266 #[test]
2267 fn export_parquet_refuses_a_bad_time_target_or_tenant() {
2268 let s = setup();
2269 let id = s.create("acme");
2270 let export = |to: &str, since: Option<&str>, until: Option<&str>| Command::ExportParquet {
2271 tenant: id.clone(),
2272 to: to.to_owned(),
2273 since: since.map(str::to_owned),
2274 until: until.map(str::to_owned),
2275 };
2276 let dir = s._dir.path().join("out").display().to_string();
2277 assert!(
2278 matches!(
2279 s.run(export(&dir, Some("yesterday"), None)),
2280 Err(CommandError::BadTime(t)) if t == "yesterday"
2281 ),
2282 "a word that is not an RFC 3339 time is refused, naming it"
2283 );
2284 assert!(
2285 matches!(
2286 s.run(export(&dir, None, Some("2026-13-01T00:00:00Z"))),
2287 Err(CommandError::BadTime(_))
2288 ),
2289 "a month 13 is not a time"
2290 );
2291 assert!(
2292 matches!(
2293 s.run(export("s3://", None, None)),
2294 Err(CommandError::BadTarget(t)) if t == "s3://"
2295 ),
2296 "an s3:// URL with no bucket is refused, naming it"
2297 );
2298 assert!(
2299 matches!(
2300 s.run(export("s3://reports/vcon", None, None)),
2301 Err(CommandError::NoS3)
2302 ),
2303 "no S3 service is configured"
2304 );
2305 assert_eq!(
2306 tenant_error(s.run(Command::ExportParquet {
2307 tenant: TenantId::generate().to_string(),
2308 to: dir.clone(),
2309 since: None,
2310 until: None,
2311 })),
2312 TenantError::NotFound,
2313 "an unknown tenant is not found"
2314 );
2315 assert!(
2316 !std::path::Path::new(&dir).exists(),
2317 "a refused export writes nothing"
2318 );
2319 }
2320
2321 #[test]
2322 fn each_error_says_what_went_wrong() {
2323 let tenant = [
2324 TenantError::NotFound,
2325 TenantError::NameTaken,
2326 TenantError::BadName,
2327 TenantError::HoldsVcons,
2328 TenantError::UnderHold,
2329 TenantError::LimitReached,
2330 TenantError::AuditFailed,
2331 TenantError::Closing,
2332 TenantError::CliOnly,
2333 TenantError::BadScopes,
2334 TenantError::BadExpiry,
2335 TenantError::BadSetting(crate::settings::SettingError::UnknownName),
2336 TenantError::WrongKey,
2337 TenantError::Io,
2338 ]
2339 .map(CommandError::Tenant);
2340 let backup = [
2341 BackupError::Exists,
2342 BackupError::KeptChanging,
2343 BackupError::Io,
2344 BackupError::AuditFailed,
2345 ]
2346 .map(CommandError::Backup);
2347 let rest = [
2348 CommandError::DataDir(LockError::InUse(Sharing::Alone)),
2349 CommandError::MasterKey(crate::envelope::KeyError::WrongSize),
2350 CommandError::Open(RegistryError::failed(
2351 tenants::OpenStep::OpenCatalog,
2352 std::path::PathBuf::from("/srv/data/server.sqlite"),
2353 io::Error::other("disk I/O error"),
2354 )),
2355 CommandError::WrongMasterKey,
2356 CommandError::BadPeriod("7w".to_owned()),
2357 CommandError::UnknownKey,
2358 CommandError::Output(io::Error::other("closed")),
2359 CommandError::SameMasterKey,
2360 CommandError::CheckFound(2),
2361 CommandError::Storage(StorageError(
2362 "bucket \"vcon\" cannot be reached or read".to_owned(),
2363 )),
2364 CommandError::BadLevel("most".to_owned()),
2365 CommandError::BadTime("yesterday".to_owned()),
2366 CommandError::BadTarget("s3://".to_owned()),
2367 CommandError::NoS3,
2368 CommandError::Export(crate::export::ExportError::Raced("m".to_owned())),
2369 CommandError::Move {
2370 tenant: TenantId([1; 16]),
2371 why: "the bucket could not be written".to_owned(),
2372 },
2373 ];
2374 let user = [
2375 UserError::CliOnly,
2376 UserError::BadLabel,
2377 UserError::BadIdentity,
2378 UserError::IdentityTaken,
2379 UserError::NoUser,
2380 UserError::Deactivated,
2381 UserError::NoTenant,
2382 UserError::Closing,
2383 UserError::BadRoles,
2384 UserError::NoMembership,
2385 UserError::Registry(TenantError::Io),
2386 ]
2387 .map(CommandError::User);
2388 for error in tenant.into_iter().chain(backup).chain(rest).chain(user) {
2389 let text = error.to_string();
2390 assert!(text.contains(says(&error)), "{error:?}: {text}");
2391 }
2392 }
2393}