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};
20use crate::retention::Retention;
21use crate::store::ExamineError;
22use crate::tenants::{
23 self, BackupError, OpenFailure, RegistryError, Removal, TenantError, TenantExamination,
24 Tenants, Unexamined,
25};
26use time::OffsetDateTime;
27use time::format_description::well_known::Rfc3339;
28
29#[derive(Debug, Clone, PartialEq, Eq)]
31pub enum Command {
32 TenantCreate {
33 name: String,
34 retention: Option<String>,
35 },
36 TenantList,
37 TenantSetRetention {
39 id: String,
40 retention: String,
41 },
42 TenantRemove {
43 id: String,
44 force: bool,
45 override_holds: bool,
46 },
47 TenantSetMetadata {
49 id: String,
50 metadata: String,
51 },
52 StorageMoveObjects,
56 ExportParquet {
60 tenant: String,
61 to: String,
62 since: Option<String>,
63 until: Option<String>,
64 },
65 KeyCreate {
66 owner: Owner,
67 label: String,
68 },
69 KeyList {
70 tenant: Option<String>,
71 },
72 KeyRevoke {
73 id: String,
74 },
75 AuditExport {
76 log: Log,
77 since: Option<i64>,
78 },
79 RekeyTenant {
81 id: String,
82 },
83 RekeyMaster {
85 new_master: std::path::PathBuf,
86 },
87 Check,
89 Backup {
92 to: std::path::PathBuf,
93 },
94}
95
96#[derive(Debug, Clone, PartialEq, Eq)]
98pub enum Owner {
99 Tenant { id: String, scopes: Vec<String> },
100 Operator,
101}
102
103#[derive(Debug, Clone, PartialEq, Eq)]
105pub enum Log {
106 Tenant(String),
107 Admin,
108}
109
110impl Command {
111 pub fn work(&self) -> Work {
113 match self {
114 Command::TenantCreate { .. } => Work::TenantCreate,
115 Command::TenantList => Work::TenantList,
116 Command::TenantSetRetention { .. } => Work::TenantSetRetention,
117 Command::TenantRemove { .. } => Work::TenantRemove,
118 Command::TenantSetMetadata { .. } => Work::TenantSetMetadata,
119 Command::ExportParquet { .. } => Work::ExportParquet,
120 Command::StorageMoveObjects => Work::StorageMoveObjects,
121 Command::KeyCreate { .. } => Work::KeyCreate,
122 Command::KeyList { .. } => Work::KeyList,
123 Command::KeyRevoke { .. } => Work::KeyRevoke,
124 Command::AuditExport { .. } => Work::AuditExport,
125 Command::RekeyTenant { .. } => Work::RekeyTenant,
126 Command::RekeyMaster { .. } => Work::RekeyMaster,
127 Command::Check => Work::Check,
128 Command::Backup { .. } => Work::Backup,
129 }
130 }
131}
132
133#[derive(Debug)]
135pub enum CommandError {
136 DataDir(LockError),
137 MasterKey(KeyError),
138 WrongMasterKey,
140 BadPeriod(String),
143 Tenant(TenantError),
144 Open(RegistryError),
146 UnknownKey,
148 Output(io::Error),
150 SameMasterKey,
152 CheckFound(usize),
154 Backup(BackupError),
155 Storage(StorageError),
157 BadLevel(String),
159 BadTime(String),
161 BadTarget(String),
163 NoS3,
166 Export(crate::export::ExportError),
167 Move {
170 tenant: TenantId,
171 why: String,
172 },
173}
174
175impl fmt::Display for CommandError {
176 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
177 match self {
178 CommandError::DataDir(e) => write!(f, "{e}"),
179 CommandError::MasterKey(KeyError::Refused(why)) => {
180 write!(f, "the master key cannot be read: {why}")
181 }
182 CommandError::MasterKey(e) => write!(f, "the master key cannot be read: {e:?}"),
183 CommandError::Open(e) => write!(
184 f,
185 "the registry cannot be opened: {}",
186 crate::tenants::with_causes(e)
187 ),
188 CommandError::WrongMasterKey | CommandError::Tenant(TenantError::WrongKey) => {
189 f.write_str("the master key is not the one server.sqlite was made under")
190 }
191 CommandError::BadPeriod(text) => write!(
192 f,
193 "{text:?} is not a period such as 7y, 18m or 90d (or, for set-retention, default)"
194 ),
195 CommandError::UnknownKey => f.write_str("no key has this id"),
196 CommandError::Output(e) => write!(f, "the output could not be written: {e}"),
197 CommandError::SameMasterKey => {
198 f.write_str("the new master key is the one already in use")
199 }
200 CommandError::CheckFound(n) => write!(f, "check found {n} problem(s); see its report"),
201 CommandError::Storage(e) => write!(f, "the storage cannot be used: {e}"),
202 CommandError::BadLevel(text) => write!(
203 f,
204 "{text:?} is not a metadata level: none, counts or full"
205 ),
206 CommandError::BadTime(text) => write!(
207 f,
208 "{text:?} is not an RFC 3339 time such as 2026-11-05T00:00:00Z"
209 ),
210 CommandError::BadTarget(text) => write!(
211 f,
212 "{text:?} is not a directory or an s3://bucket/prefix"
213 ),
214 CommandError::NoS3 => f.write_str(
215 "an s3:// target needs an [export.s3] or [storage.s3] table, in a build with the s3 feature",
216 ),
217 CommandError::Export(e) => write!(f, "{e}"),
218 CommandError::Move { tenant, why } => write!(
219 f,
220 "moving tenant {tenant}'s objects to the bucket stopped: {why}; what moved stays \
221 moved, and running storage move-objects again moves the rest"
222 ),
223 CommandError::Backup(e) => f.write_str(match e {
224 BackupError::Exists => {
225 "the backup's path already exists; a backup is written to a new directory"
226 }
227 BackupError::KeptChanging => {
228 "tenants were removed or versions purged during each try; try again"
229 }
230 BackupError::Io => "the backup could not be written, or the data could not be read",
231 BackupError::AuditFailed => "the audit record could not be written",
232 }),
233 CommandError::Tenant(e) => f.write_str(match e {
234 TenantError::NotFound => "no tenant has this id",
235 TenantError::NameTaken => "another tenant has this name",
236 TenantError::BadName => {
237 "a tenant name is 1 to 128 characters, with no control characters and no space at either end"
238 }
239 TenantError::HoldsVcons => "the tenant holds vCons; add --force to remove them too",
240 TenantError::UnderHold => {
241 "a vCon of the tenant is under a legal hold; only --override-holds removes it"
242 }
243 TenantError::BadScopes => {
244 "a tenant key's scopes are one or more of write, read, delete, legal and audit, each named once"
245 }
246 TenantError::LimitReached => {
247 "the master key has wrapped all the tenant keys it may; run rekey master"
248 }
249 TenantError::AuditFailed => "the audit record could not be written",
250 TenantError::Closing => "the tenant is being removed",
251 TenantError::CliOnly => "only the command line may do this",
252 TenantError::WrongKey => unreachable!("matched above"),
253 TenantError::Io => "the data could not be read or written",
254 }),
255 }
256 }
257}
258
259pub fn migrate(config: &Config, out: &mut dyn Write) -> Result<(), CommandError> {
270 let done = backend::migrate_for_command(&config.catalog).map_err(CommandError::Storage)?;
271 line(out, &done)
272}
273
274pub fn run(config: &Config, command: &Command, out: &mut dyn Write) -> Result<(), CommandError> {
275 let sharing = command.work().sharing();
276 let _lock = datadir::lock(&config.data_dir, sharing).map_err(CommandError::DataDir)?;
277 let master = Key::load_master(&config.master_key).map_err(CommandError::MasterKey)?;
278 backend::catalog_for_command(&config.catalog).map_err(CommandError::Storage)?;
279 if let Command::RekeyMaster { new_master } = command {
282 return rekey_master(config, &master, new_master, out);
283 }
284 let open = if sharing == Sharing::Beside || matches!(command, Command::Check) {
288 Tenants::open_beside_in
289 } else {
290 Tenants::open_in
291 };
292 let objects =
293 backend::objects_for(&config.storage, &config.data_dir).map_err(CommandError::Storage)?;
294 #[cfg(feature = "s3")]
296 let bucket = match &objects {
297 backend::ObjectPlace::S3(s3) => Some(s3.clone()),
298 backend::ObjectPlace::Local => None,
299 };
300 let tenants = open(
301 &config.data_dir,
302 master,
303 Arc::new(OsFs),
304 Arc::new(SystemClock),
305 objects,
306 )
307 .map_err(|e| match e {
308 RegistryError::WrongKey => CommandError::WrongMasterKey,
309 other => CommandError::Open(other),
310 })?;
311 let who = Actor::Cli;
312 match command {
313 Command::TenantCreate { name, retention } => {
314 let retention = retention.as_deref().map(period).transpose()?;
315 let id = tenants.create(who, name, retention)?;
316 line(out, &serde_json::json!({ "id": id.to_string() }))
317 }
318 Command::TenantList => {
319 for tenant in tenants.list(who)? {
320 line(out, &tenant.to_json())?;
321 }
322 Ok(())
323 }
324 Command::TenantSetRetention { id, retention } => {
325 let retention = match retention.as_str() {
326 "default" => None,
327 text => Some(period(text)?),
328 };
329 let id = tenant_id(id)?;
330 tenants.set_retention(who, id, retention)?;
331 line(
332 out,
333 &serde_json::json!({
334 "id": id.to_string(),
335 "retention": retention.map(|r| r.to_string()),
336 }),
337 )
338 }
339 Command::TenantRemove {
340 id,
341 force,
342 override_holds,
343 } => {
344 let removal = match (force, override_holds) {
345 (_, true) => Removal::ForceOverridingHolds,
346 (true, false) => Removal::Force,
347 (false, false) => Removal::Empty,
348 };
349 Ok(tenants.remove(who, tenant_id(id)?, removal)?)
350 }
351 Command::KeyCreate { owner, label } => {
352 let (tenant, scopes) = match owner {
353 Owner::Tenant { id, scopes } => (
354 Some(tenant_id(id)?),
355 Scopes::named(scopes).ok_or(CommandError::Tenant(TenantError::BadScopes))?,
356 ),
357 Owner::Operator => (None, Scopes::of(&[Scope::Admin])),
358 };
359 let made = tenants.create_key(who, tenant, scopes, label)?;
360 line(
361 out,
362 &serde_json::json!({ "id": made.id.to_string(), "token": made.token }),
363 )
364 }
365 Command::KeyList { tenant } => {
366 let tenant = tenant.as_deref().map(tenant_id).transpose()?;
367 for key in tenants.list_keys(who, tenant)? {
368 let shown = key.to_json().ok_or(CommandError::Tenant(TenantError::Io))?;
369 line(out, &shown)?;
370 }
371 Ok(())
372 }
373 Command::KeyRevoke { id } => {
374 let id = KeyId::parse(id).ok_or(CommandError::UnknownKey)?;
375 tenants.revoke_key(who, id).map_err(|e| match e {
376 TenantError::NotFound => CommandError::UnknownKey,
377 other => CommandError::Tenant(other),
378 })
379 }
380 Command::TenantSetMetadata { id, metadata } => {
381 let level = crate::export::Metadata::parse(metadata)
382 .ok_or_else(|| CommandError::BadLevel(metadata.clone()))?;
383 let id = tenant_id(id)?;
384 tenants.set_metadata(who, id, level)?;
385 line(
386 out,
387 &serde_json::json!({ "id": id.to_string(), "metadata": level.as_str() }),
388 )
389 }
390 Command::ExportParquet {
391 tenant,
392 to,
393 since,
394 until,
395 } => export_parquet(
396 config,
397 &tenants,
398 tenant,
399 to,
400 since.as_deref(),
401 until.as_deref(),
402 out,
403 ),
404 Command::RekeyTenant { id } => Ok(tenants.rekey_tenant(who, tenant_id(id)?)?),
405 Command::RekeyMaster { .. } => unreachable!("rotated before the registry is opened"),
406 Command::Check => check(config, &tenants, out),
407 #[cfg(feature = "s3")]
408 Command::StorageMoveObjects => match bucket {
409 Some(s3) => move_objects(config, &tenants, &s3, out),
410 None => Err(not_a_bucket()),
411 },
412 #[cfg(not(feature = "s3"))]
413 Command::StorageMoveObjects => Err(not_a_bucket()),
414 Command::Backup { to } => {
415 let done = tenants.backup(who, to).map_err(CommandError::Backup)?;
416 line(
417 out,
418 &serde_json::json!({
419 "tenants": done.tenants,
420 "versions": done.versions,
421 "tries": done.tries,
422 }),
423 )
424 }
425 Command::AuditExport { log, since } => {
426 let exported = match log {
427 Log::Admin => tenants.export_admin(*since, out),
428 Log::Tenant(id) => tenants.store(tenant_id(id)?)?.export(*since, out),
429 };
430 exported.map_err(|e| match e {
431 AuditError::Write(e) => CommandError::Output(e),
432 AuditError::Sqlite(_) => CommandError::Tenant(TenantError::Io),
433 })
434 }
435 }
436}
437
438impl From<TenantError> for CommandError {
439 fn from(e: TenantError) -> CommandError {
440 CommandError::Tenant(e)
441 }
442}
443
444fn export_parquet(
447 config: &Config,
448 tenants: &Tenants,
449 tenant: &str,
450 to: &str,
451 since: Option<&str>,
452 until: Option<&str>,
453 out: &mut dyn Write,
454) -> Result<(), CommandError> {
455 use crate::export::target::Place;
456 use crate::export::{self, Plan};
457 let time = |text: Option<&str>| {
458 text.map(|t| {
459 OffsetDateTime::parse(t, &Rfc3339)
460 .map(crate::clock::nanos)
461 .map_err(|_| CommandError::BadTime(t.to_owned()))
462 })
463 .transpose()
464 };
465 let (since, until) = (time(since)?, time(until)?);
466 let place = Place::parse(to).ok_or_else(|| CommandError::BadTarget(to.to_owned()))?;
467 let id = tenant_id(tenant)?;
468 let level = tenants.metadata(id)?;
469 let target: Box<dyn export::Target> = match place {
470 Place::Dir(dir) => Box::new(export::DirTarget::new(&dir, Arc::new(OsFs))),
471 Place::S3 { bucket, prefix } => s3_target(config, &bucket, &prefix)?,
472 };
473 let store = tenants.store(id)?;
474 let plan = Plan {
475 level,
476 since,
477 until,
478 sizes: export::SIZES,
479 limits: vcon::read::Limits::new(config.inflated_limit),
480 };
481 let done = export::export(&store, &plan, target.as_ref(), SystemClock.now())
482 .map_err(CommandError::Export)?;
483 line(
484 out,
485 &serde_json::json!({
486 "tenant": id.to_string(),
487 "metadata": level.as_str(),
488 "to": target.describe(),
489 "manifest": done.manifest,
490 "seq": done.seq,
491 "files": done.files.len(),
492 "rows": done.rows,
493 "bytes": done.bytes,
494 "skipped": done.skipped,
495 "unread": done.unread,
496 }),
497 )
498}
499
500#[cfg(feature = "s3")]
503fn s3_target(
504 config: &Config,
505 bucket: &str,
506 prefix: &str,
507) -> Result<Box<dyn crate::export::Target>, CommandError> {
508 use crate::config::{ExportS3, ObjectStore};
509 let (service, table) = match (&config.export.s3, &config.storage.objects) {
510 (Some(service), _) => (service.clone(), "export.s3"),
511 (None, ObjectStore::S3(storage)) => (ExportS3::from(storage), "storage.s3"),
512 (None, ObjectStore::Local) => return Err(CommandError::NoS3),
513 };
514 let target = crate::export::s3::S3Target::connect(&service.for_bucket(bucket, prefix), table)
515 .map_err(CommandError::Storage)?;
516 Ok(Box::new(target))
517}
518
519#[cfg(not(feature = "s3"))]
520fn s3_target(
521 _config: &Config,
522 _bucket: &str,
523 _prefix: &str,
524) -> Result<Box<dyn crate::export::Target>, CommandError> {
525 Err(CommandError::NoS3)
526}
527
528fn rekey_master(
530 config: &Config,
531 master: &Key,
532 new_master: &std::path::Path,
533 out: &mut dyn Write,
534) -> Result<(), CommandError> {
535 let new =
536 Key::load_master_named(new_master, "--new-master").map_err(CommandError::MasterKey)?;
537 if new.id() == master.id() {
538 return Err(CommandError::SameMasterKey);
539 }
540 tenants::rekey_master(&config.data_dir, master, &new, SystemClock.now()).map_err(
541 |e| match e {
542 TenantError::WrongKey => CommandError::WrongMasterKey,
543 other => CommandError::Tenant(other),
544 },
545 )?;
546 line(
547 out,
548 &serde_json::json!({
549 "master_key_id": new.id().to_string(),
550 "next": "point master_key in the configuration at the new key file, start the server, then destroy every copy of the old master key",
551 }),
552 )
553}
554
555fn not_a_bucket() -> CommandError {
560 CommandError::Storage(StorageError(
561 "storage move-objects moves the objects to the bucket that storage.objects = \"s3\" \
562 names; this configuration keeps them in the data directory"
563 .to_owned(),
564 ))
565}
566
567#[cfg(feature = "s3")]
572fn move_objects(
573 config: &Config,
574 tenants: &Tenants,
575 s3: &Arc<crate::backend::s3::S3>,
576 out: &mut dyn Write,
577) -> Result<(), CommandError> {
578 use crate::backend::migrate::MoveError;
579 let mut total = 0;
580 for id in tenants.ids()? {
581 let dir = config
582 .data_dir
583 .join("tenants")
584 .join(id.to_string())
585 .join("objects");
586 let moved = if dir.exists() {
587 let from = crate::backend::local::LocalObjects::new(dir, Arc::new(OsFs));
588 crate::backend::migrate::move_objects(&from, &s3.tenant(id)).map_err(|e| {
589 let why = match e {
590 MoveError::From(e) => {
591 format!("an object file could not be read or removed: {e}")
592 }
593 MoveError::To(e) => format!("the bucket could not be written or read: {e}"),
594 MoveError::Differs(version) => format!(
595 "version {version} read back from the bucket differs from its file, \
596 which stays in the data directory"
597 ),
598 };
599 CommandError::Move { tenant: id, why }
600 })?
601 } else {
602 0
603 };
604 let missing = tenants
605 .store(id)?
606 .check()
607 .map_err(|e| CommandError::Move {
608 tenant: id,
609 why: format!("the objects in the bucket could not be checked: {e:?}"),
610 })?
611 .len();
612 total += moved;
613 line(
614 out,
615 &serde_json::json!({ "tenant": id.to_string(), "moved": moved, "missing": missing }),
616 )?;
617 }
618 line(out, &serde_json::json!({ "moved": total }))
619}
620
621fn check(config: &Config, tenants: &Tenants, out: &mut dyn Write) -> Result<(), CommandError> {
622 let now = SystemClock.now();
623 let found = tenants.examine(config.retention_default, now)?;
624 let time = |at: Option<OffsetDateTime>| at.and_then(|at| at.format(&Rfc3339).ok());
625 let mut total = 0;
626 for tenant in &found.tenants {
627 let named = problems(
628 tenant,
629 config.purge_interval,
630 now,
631 config.storage.parquet.is_some(),
632 );
633 total += named.len();
634 let store = tenant.store.as_ref().ok();
635 line(
636 out,
637 &serde_json::json!({
638 "tenant": tenant.id.to_string(),
639 "name": tenant.name,
640 "versions": store.map(|s| s.versions),
641 "packed": store.map(|s| s.packed),
642 "damaged": store.map(|s| s.damaged.iter().map(ToString::to_string).collect::<Vec<_>>()),
643 "leftovers": store.map(|s| &s.leftovers),
644 "past_due": store.map(|s| s.due),
645 "oldest_past_due": time(store.and_then(|s| s.oldest_due_since)),
646 "purges_awaiting_rotation": store.map(|s| s.purges_since_key),
647 "oldest_purge_awaiting_rotation": time(store.and_then(|s| s.oldest_purge_since_key)),
648 "rotation_stopped": tenant.rotation_stopped,
649 "problems": named,
650 }),
651 )?;
652 }
653 line(
654 out,
655 &serde_json::json!({
656 "tenants": found.tenants.len(),
657 "removed_tenants_awaiting_master_rotation": found.removed_since_master,
658 "oldest_removal_awaiting_master_rotation": time(found.oldest_removed_since_master),
659 "problems": total,
660 }),
661 )?;
662 match total {
663 0 => Ok(()),
664 n => Err(CommandError::CheckFound(n)),
665 }
666}
667
668pub fn problems(
675 tenant: &TenantExamination,
676 purge_interval: std::time::Duration,
677 now: OffsetDateTime,
678 parquet: bool,
679) -> Vec<String> {
680 let mut found = Vec::new();
681 if tenant.rotation_stopped {
682 found.push("a key rotation was stopped part way; run rekey tenant again".to_owned());
683 }
684 match &tenant.store {
685 Err(Unexamined::Open(OpenFailure::WrongKey)) => {
686 found.push("its catalog does not open under its tenant key".to_owned());
687 }
688 Err(Unexamined::Open(OpenFailure::Access { path, error })) => {
689 found.push(format!(
690 "its catalog cannot be opened: {}: {error}",
691 path.display()
692 ));
693 }
694 Err(Unexamined::Open(OpenFailure::Refused(e))) => {
695 found.push(format!("its catalog cannot be opened: {e:?}"));
696 }
697 Err(Unexamined::Examine(ExamineError::Objects { kind, os_error })) => {
698 let number = os_error
699 .map(|n| format!(" (os error {n})"))
700 .unwrap_or_default();
701 found.push(format!("its objects cannot be read: {kind}{number}"));
702 }
703 Err(Unexamined::Examine(ExamineError::Failed(e))) => {
704 found.push(format!("it could not be examined: {e:?}"));
705 }
706 Ok(store) => {
707 if store.packed > 0 && !parquet {
708 found.push(format!(
709 "{} version(s) are packed into Parquet files, and the configuration has no \
710 [storage.parquet]: serve refuses to start until the table is put back",
711 store.packed
712 ));
713 }
714 for version in &store.damaged {
715 found.push(format!("version {version} is missing or does not open"));
716 }
717 if let Some(since) = store.oldest_due_since
718 && now - since > purge_interval
719 {
720 found.push(format!(
721 "{} version(s) due for purge, the oldest longer than purge_interval: the sweep is not keeping up",
722 store.due
723 ));
724 }
725 }
726 }
727 found
728}
729
730fn period(text: &str) -> Result<Retention, CommandError> {
732 Retention::parse(text).ok_or_else(|| CommandError::BadPeriod(text.to_owned()))
733}
734
735fn tenant_id(text: &str) -> Result<TenantId, CommandError> {
738 TenantId::parse(text).ok_or(CommandError::Tenant(TenantError::NotFound))
739}
740
741fn line(out: &mut dyn Write, value: &serde_json::Value) -> Result<(), CommandError> {
743 writeln!(out, "{value}").map_err(CommandError::Output)
744}
745
746#[cfg(test)]
747mod tests {
748 use serde_json::{Value, json};
749
750 use super::*;
751 use crate::store::Caller;
752 use crate::store::testing::vcon;
753
754 const UUID: &str = "01a07da8-c2bb-83e5-b9a2-279e0d16bc46";
755
756 struct Setup {
757 _dir: tempfile::TempDir,
758 config: Config,
759 }
760
761 fn chmod(path: &std::path::Path, mode: u32) {
762 use std::os::unix::fs::PermissionsExt;
763 std::fs::set_permissions(path, std::fs::Permissions::from_mode(mode)).expect("chmod");
764 }
765
766 fn setup() -> Setup {
767 let dir = tempfile::tempdir().expect("temp dir");
768 let data = dir.path().join("data");
769 std::fs::create_dir(&data).expect("data dir");
770 let master = dir.path().join("master.key");
771 std::fs::write(&master, [0x5a; 32]).expect("master key file");
772 chmod(&master, 0o600);
773 let config = crate::config::parse(&format!(
774 "listen = \"127.0.0.1:1\"\ndata_dir = {data:?}\nmaster_key = {master:?}\n\
775 [tls]\ncert = \"c\"\nkey = \"k\"\n"
776 ))
777 .expect("a configuration");
778 Setup { _dir: dir, config }
779 }
780
781 impl Setup {
782 fn run(&self, command: Command) -> Result<Vec<Value>, CommandError> {
784 let mut out = Vec::new();
785 run(&self.config, &command, &mut out)?;
786 Ok(String::from_utf8(out)
787 .expect("text")
788 .lines()
789 .map(|line| serde_json::from_str(line).expect("a JSON line"))
790 .collect())
791 }
792
793 fn create(&self, name: &str) -> String {
794 let out = self
795 .run(Command::TenantCreate {
796 name: name.to_owned(),
797 retention: None,
798 })
799 .expect("made");
800 out[0]["id"].as_str().expect("an id").to_owned()
801 }
802
803 fn tenants(&self) -> Tenants {
805 Tenants::open_beside(
806 &self.config.data_dir,
807 Key::load_master(&self.config.master_key).expect("master"),
808 Arc::new(OsFs),
809 Arc::new(SystemClock),
810 )
811 .expect("opens")
812 }
813
814 fn tenant_dirs(&self) -> Vec<String> {
815 let mut names: Vec<String> = std::fs::read_dir(self.config.data_dir.join("tenants"))
816 .expect("tenants dir")
817 .map(|e| e.expect("entry").file_name().to_string_lossy().into_owned())
818 .collect();
819 names.sort();
820 names
821 }
822 }
823
824 fn tenant_error(result: Result<Vec<Value>, CommandError>) -> TenantError {
825 match result {
826 Err(CommandError::Tenant(e)) => e,
827 other => panic!("not a tenant error: {other:?}"),
828 }
829 }
830
831 #[test]
832 fn tenant_create_prints_the_new_id_and_list_shows_it() {
833 let s = setup();
834 let out = s
835 .run(Command::TenantCreate {
836 name: "acme".to_owned(),
837 retention: Some("18m".to_owned()),
838 })
839 .expect("made");
840 assert_eq!(out.len(), 1);
841 let id = out[0]["id"].as_str().expect("an id").to_owned();
842 assert!(TenantId::parse(&id).is_some(), "{id}");
843 assert_eq!(out[0], json!({ "id": id }));
844 let beta = s.create("beta");
845 assert_eq!(
846 s.run(Command::TenantList).expect("listed"),
847 [
848 json!({ "id": id, "name": "acme", "retention": "18m", "metadata": "none" }),
849 json!({ "id": beta, "name": "beta", "retention": null, "metadata": "none" }),
850 ]
851 );
852 }
853
854 #[test]
855 fn a_bad_period_is_refused_before_anything_is_made() {
856 let s = setup();
857 let error = s
858 .run(Command::TenantCreate {
859 name: "acme".to_owned(),
860 retention: Some("7w".to_owned()),
861 })
862 .expect_err("refused");
863 assert!(
864 matches!(&error, CommandError::BadPeriod(p) if p == "7w"),
865 "{error:?}"
866 );
867 assert!(error.to_string().contains("7w"), "{error}");
868 assert_eq!(
869 s.run(Command::TenantList).expect("listed"),
870 Vec::<Value>::new()
871 );
872 let id = s.create("acme");
873 let error = s
874 .run(Command::TenantSetRetention {
875 id,
876 retention: "forever".to_owned(),
877 })
878 .expect_err("refused");
879 assert!(matches!(&error, CommandError::BadPeriod(p) if p == "forever"));
880 }
881
882 #[test]
883 fn set_retention_takes_a_period_or_default() {
884 let s = setup();
885 let id = s.create("acme");
886 let set = |retention: &str| {
887 s.run(Command::TenantSetRetention {
888 id: id.clone(),
889 retention: retention.to_owned(),
890 })
891 .expect("set")
892 };
893 assert_eq!(set("90d"), [json!({ "id": id, "retention": "90d" })]);
894 assert_eq!(
895 s.run(Command::TenantList).expect("listed")[0]["retention"],
896 "90d"
897 );
898 assert_eq!(set("default"), [json!({ "id": id, "retention": null })]);
899 assert_eq!(
900 s.run(Command::TenantList).expect("listed")[0]["retention"],
901 Value::Null
902 );
903 }
904
905 #[test]
906 fn an_unknown_or_malformed_tenant_is_not_found() {
907 let s = setup();
908 for id in [TenantId::generate().to_string(), "not-an-id".to_owned()] {
909 assert_eq!(
910 tenant_error(s.run(Command::TenantSetRetention {
911 id: id.clone(),
912 retention: "7y".to_owned()
913 })),
914 TenantError::NotFound
915 );
916 assert_eq!(
917 tenant_error(s.run(Command::TenantRemove {
918 id: id.clone(),
919 force: true,
920 override_holds: false
921 })),
922 TenantError::NotFound
923 );
924 assert_eq!(
925 tenant_error(s.run(Command::KeyCreate {
926 owner: Owner::Tenant {
927 id: id.clone(),
928 scopes: vec!["read".to_owned()]
929 },
930 label: "l".to_owned()
931 })),
932 TenantError::NotFound
933 );
934 assert_eq!(
935 tenant_error(s.run(Command::KeyList {
936 tenant: Some(id.clone())
937 })),
938 TenantError::NotFound
939 );
940 assert_eq!(
941 tenant_error(s.run(Command::AuditExport {
942 log: Log::Tenant(id.clone()),
943 since: None
944 })),
945 TenantError::NotFound
946 );
947 }
948 }
949
950 #[test]
953 fn remove_goes_as_far_as_its_flags_allow() {
954 let s = setup();
955 let empty = s.create("empty");
956 let full = s.create("full");
957 {
958 let tenants = s.tenants();
959 let store = tenants
960 .store(TenantId::parse(&full).expect("id"))
961 .expect("store");
962 let caller = Caller { key: KeyId([1; 8]) };
963 let (found, body) = vcon(UUID, "kept");
964 store.create(&caller, &found, &body).expect("stored");
965 store.set_hold(&caller, found.uuid, true).expect("held");
966 }
967 let remove = |id: &str, force, override_holds| {
968 s.run(Command::TenantRemove {
969 id: id.to_owned(),
970 force,
971 override_holds,
972 })
973 };
974 assert_eq!(
975 remove(&empty, false, false).expect("removed"),
976 Vec::<Value>::new()
977 );
978 assert_eq!(
979 tenant_error(remove(&full, false, false)),
980 TenantError::HoldsVcons
981 );
982 assert_eq!(
983 tenant_error(remove(&full, true, false)),
984 TenantError::UnderHold
985 );
986 assert_eq!(
987 remove(&full, true, true).expect("removed"),
988 Vec::<Value>::new()
989 );
990 assert_eq!(
991 s.run(Command::TenantList).expect("listed"),
992 Vec::<Value>::new()
993 );
994 assert_eq!(s.tenant_dirs(), Vec::<String>::new());
995 }
996
997 #[test]
998 fn keys_are_made_listed_and_revoked() {
999 let s = setup();
1000 let tenant = s.create("acme");
1001 let made = s
1002 .run(Command::KeyCreate {
1003 owner: Owner::Tenant {
1004 id: tenant.clone(),
1005 scopes: vec!["write".to_owned(), "read".to_owned()],
1006 },
1007 label: "producer".to_owned(),
1008 })
1009 .expect("made");
1010 let id = made[0]["id"].as_str().expect("id").to_owned();
1011 let token = made[0]["token"].as_str().expect("token").to_owned();
1012 assert_eq!(made.len(), 1);
1013 assert_eq!(made[0].as_object().expect("object").len(), 2);
1014 assert!(token.starts_with(&format!("vcs_{id}_")), "{token}");
1015 let operator = s
1016 .run(Command::KeyCreate {
1017 owner: Owner::Operator,
1018 label: "ops".to_owned(),
1019 })
1020 .expect("made")[0]["id"]
1021 .as_str()
1022 .expect("id")
1023 .to_owned();
1024
1025 let listed = s.run(Command::KeyList { tenant: None }).expect("listed");
1026 assert_eq!(listed.len(), 2);
1027 assert_eq!(listed[0]["id"], id.as_str());
1028 assert_eq!(listed[0]["tenant"], tenant.as_str());
1029 assert_eq!(listed[0]["scopes"], json!(["write", "read"]));
1030 assert_eq!(listed[0]["label"], "producer");
1031 assert_eq!(listed[0]["revoked_at"], Value::Null);
1032 assert!(
1033 listed[0]["created_at"]
1034 .as_str()
1035 .is_some_and(|t| t.ends_with('Z'))
1036 );
1037 assert!(
1038 listed.iter().all(|k| k.get("token").is_none()),
1039 "never a token"
1040 );
1041 assert_eq!(listed[1]["id"], operator.as_str());
1042 assert_eq!(listed[1]["tenant"], Value::Null);
1043 assert_eq!(listed[1]["scopes"], json!(["admin"]));
1044
1045 let own = s
1046 .run(Command::KeyList {
1047 tenant: Some(tenant.clone()),
1048 })
1049 .expect("listed");
1050 assert_eq!(own, listed[..1]);
1051
1052 assert_eq!(
1053 s.run(Command::KeyRevoke { id: id.clone() })
1054 .expect("revoked"),
1055 Vec::<Value>::new()
1056 );
1057 let listed = s.run(Command::KeyList { tenant: None }).expect("listed");
1058 assert!(listed[0]["revoked_at"].as_str().is_some(), "{listed:?}");
1059 assert_eq!(listed[1]["revoked_at"], Value::Null);
1060 }
1061
1062 #[test]
1063 fn bad_scopes_and_unknown_keys_are_refused() {
1064 let s = setup();
1065 let tenant = s.create("acme");
1066 for scopes in [
1067 vec!["superuser"],
1068 vec!["read", "superuser"],
1069 vec!["read", "read"],
1070 vec!["admin"],
1071 vec![],
1072 ] {
1073 let error = s.run(Command::KeyCreate {
1074 owner: Owner::Tenant {
1075 id: tenant.clone(),
1076 scopes: scopes.iter().map(|s| (*s).to_owned()).collect(),
1077 },
1078 label: "l".to_owned(),
1079 });
1080 assert_eq!(tenant_error(error), TenantError::BadScopes, "{scopes:?}");
1081 }
1082 assert_eq!(
1083 s.run(Command::KeyList { tenant: None }).expect("listed"),
1084 Vec::<Value>::new()
1085 );
1086 for id in ["0123456789abcdef".to_owned(), "nope".to_owned()] {
1087 assert!(
1088 matches!(
1089 s.run(Command::KeyRevoke { id }),
1090 Err(CommandError::UnknownKey)
1091 ),
1092 "unknown"
1093 );
1094 }
1095 }
1096
1097 #[test]
1098 fn audit_export_writes_either_log_from_a_sequence_number() {
1099 let s = setup();
1100 let tenant = s.create("acme");
1101 s.run(Command::TenantList).expect("listed");
1102 s.run(Command::KeyCreate {
1103 owner: Owner::Tenant {
1104 id: tenant.clone(),
1105 scopes: vec!["read".to_owned()],
1106 },
1107 label: "l".to_owned(),
1108 })
1109 .expect("made");
1110
1111 let admin = s
1112 .run(Command::AuditExport {
1113 log: Log::Admin,
1114 since: None,
1115 })
1116 .expect("exported");
1117 let actions: Vec<&str> = admin
1118 .iter()
1119 .map(|r| r["action"].as_str().expect("action"))
1120 .collect();
1121 assert_eq!(actions, ["tenant_create", "tenant_list", "key_create"]);
1122 assert!(admin.iter().all(|r| r["actor"] == "cli"));
1123 let since = admin[0]["seq"].as_i64().expect("seq");
1124 let later = s
1125 .run(Command::AuditExport {
1126 log: Log::Admin,
1127 since: Some(since),
1128 })
1129 .expect("exported");
1130 assert_eq!(later, admin[1..]);
1131
1132 let own = s
1133 .run(Command::AuditExport {
1134 log: Log::Tenant(tenant),
1135 since: None,
1136 })
1137 .expect("exported");
1138 let actions: Vec<&str> = own
1139 .iter()
1140 .map(|r| r["action"].as_str().expect("action"))
1141 .collect();
1142 assert_eq!(actions, ["key_create"]);
1143 }
1144
1145 #[test]
1146 fn rekey_tenant_rotates_the_key_and_prints_nothing() {
1147 let s = setup();
1148 let id = s.create("acme");
1149 let tenant = TenantId::parse(&id).expect("id");
1150 let before = s.tenants().tenant_key_id_for_test(tenant);
1151 assert_eq!(
1152 s.run(Command::RekeyTenant { id: id.clone() })
1153 .expect("rekeyed"),
1154 Vec::<Value>::new()
1155 );
1156 assert_ne!(s.tenants().tenant_key_id_for_test(tenant), before);
1157 assert_eq!(
1158 tenant_error(s.run(Command::RekeyTenant {
1159 id: TenantId::generate().to_string()
1160 })),
1161 TenantError::NotFound
1162 );
1163 let server = datadir::lock(&s.config.data_dir, Sharing::Serve).expect("a server");
1164 assert!(matches!(
1165 s.run(Command::RekeyTenant { id }),
1166 Err(CommandError::DataDir(LockError::InUse(Sharing::Alone)))
1167 ));
1168 drop(server);
1169 }
1170
1171 #[test]
1172 fn rekey_master_moves_the_data_to_the_new_master_key() {
1173 let mut s = setup();
1174 s.create("acme");
1175 let new_file = s.config.master_key.with_file_name("new.key");
1176 std::fs::write(&new_file, [0x5c; 32]).expect("new key");
1177 chmod(&new_file, 0o600);
1178 assert!(matches!(
1179 s.run(Command::RekeyMaster {
1180 new_master: s.config.master_key.clone()
1181 }),
1182 Err(CommandError::SameMasterKey)
1183 ));
1184 let server = datadir::lock(&s.config.data_dir, Sharing::Serve).expect("a server");
1185 assert!(matches!(
1186 s.run(Command::RekeyMaster {
1187 new_master: new_file.clone()
1188 }),
1189 Err(CommandError::DataDir(LockError::InUse(Sharing::Alone)))
1190 ));
1191 drop(server);
1192 let out = s
1193 .run(Command::RekeyMaster {
1194 new_master: new_file.clone(),
1195 })
1196 .expect("rotated");
1197 let new_id = Key::load_master(&new_file).expect("key").id().to_string();
1198 assert_eq!(out.len(), 1);
1199 assert_eq!(out[0]["master_key_id"], new_id.as_str());
1200 assert!(
1201 out[0]["next"]
1202 .as_str()
1203 .is_some_and(|n| n.contains("destroy"))
1204 );
1205 assert!(matches!(
1206 s.run(Command::TenantList),
1207 Err(CommandError::WrongMasterKey)
1208 ));
1209 s.config.master_key = new_file;
1210 assert_eq!(s.run(Command::TenantList).expect("listed").len(), 1);
1211 }
1212
1213 mod check {
1214 use time::macros::datetime;
1215
1216 use super::*;
1217 use crate::ids::VersionId;
1218 use crate::store::{Examination, StoreError};
1219
1220 const NOW: OffsetDateTime = datetime!(2026-10-25 12:00 UTC);
1221 const HOUR: std::time::Duration = std::time::Duration::from_secs(3600);
1222
1223 fn sound() -> Examination {
1224 Examination {
1225 versions: 3,
1226 packed: 0,
1227 damaged: vec![],
1228 leftovers: vec!["a.tmp".to_owned()],
1229 due: 0,
1230 oldest_due_since: None,
1231 purges_since_key: 4,
1232 oldest_purge_since_key: Some(datetime!(2026-10-01 00:00 UTC)),
1233 }
1234 }
1235
1236 fn tenant(store: Result<Examination, Unexamined>, stopped: bool) -> TenantExamination {
1237 TenantExamination {
1238 id: TenantId([1; 16]),
1239 name: "acme".to_owned(),
1240 rotation_stopped: stopped,
1241 store,
1242 }
1243 }
1244
1245 #[test]
1246 fn leftovers_and_work_waiting_for_rotation_are_not_problems() {
1247 assert_eq!(
1248 problems(&tenant(Ok(sound()), false), HOUR, NOW, true),
1249 Vec::<String>::new()
1250 );
1251 }
1252
1253 #[test]
1254 fn each_problem_is_named() {
1255 let damaged = Examination {
1256 damaged: vec![VersionId([2; 16]), VersionId([3; 16])],
1257 ..sound()
1258 };
1259 assert_eq!(
1260 problems(&tenant(Ok(damaged), false), HOUR, NOW, true),
1261 [
1262 "version 02020202020202020202020202020202 is missing or does not open",
1263 "version 03030303030303030303030303030303 is missing or does not open",
1264 ],
1265 "one line per damaged version, in its order"
1266 );
1267 assert_eq!(
1268 problems(&tenant(Ok(sound()), true), HOUR, NOW, true),
1269 ["a key rotation was stopped part way; run rekey tenant again"],
1270 "a stopped rotation is named with the command that finishes it"
1271 );
1272 assert_eq!(
1273 problems(
1274 &tenant(
1275 Err(Unexamined::Open(OpenFailure::Refused(TenantError::Io))),
1276 false
1277 ),
1278 HOUR,
1279 NOW,
1280 true,
1281 ),
1282 ["its catalog cannot be opened: Io"],
1283 "a refused catalog names the refusal, not a key"
1284 );
1285 }
1286
1287 #[test]
1291 fn a_key_problem_and_an_access_problem_are_told_apart() {
1292 let key = problems(
1293 &tenant(Err(Unexamined::Open(OpenFailure::WrongKey)), false),
1294 HOUR,
1295 NOW,
1296 true,
1297 );
1298 assert_eq!(key, ["its catalog does not open under its tenant key"]);
1299 let access = OpenFailure::Access {
1300 path: std::path::PathBuf::from("/srv/data/tenants/01/catalog.sqlite"),
1301 error: std::io::Error::from_raw_os_error(libc::EACCES),
1302 };
1303 assert_eq!(
1304 problems(
1305 &tenant(Err(Unexamined::Open(access)), false),
1306 HOUR,
1307 NOW,
1308 true
1309 ),
1310 [
1311 "its catalog cannot be opened: /srv/data/tenants/01/catalog.sqlite: Permission denied (os error 13)"
1312 ]
1313 );
1314 }
1315
1316 #[test]
1320 fn packed_versions_without_storage_parquet_are_a_problem() {
1321 let packed = Examination {
1322 packed: 2,
1323 ..sound()
1324 };
1325 assert_eq!(
1326 problems(&tenant(Ok(packed.clone()), false), HOUR, NOW, false),
1327 [
1328 "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"
1329 ],
1330 "without the table"
1331 );
1332 assert_eq!(
1333 problems(&tenant(Ok(packed), false), HOUR, NOW, true),
1334 Vec::<String>::new(),
1335 "with the table"
1336 );
1337 assert_eq!(
1338 problems(&tenant(Ok(sound()), false), HOUR, NOW, false),
1339 Vec::<String>::new(),
1340 "nothing packed"
1341 );
1342 }
1343
1344 #[test]
1349 fn objects_that_cannot_be_read_are_told_apart_from_a_catalog() {
1350 let unread = |kind, os_error| {
1351 problems(
1352 &tenant(
1353 Err(Unexamined::Examine(ExamineError::Objects {
1354 kind,
1355 os_error,
1356 })),
1357 false,
1358 ),
1359 HOUR,
1360 NOW,
1361 true,
1362 )
1363 };
1364 assert_eq!(
1365 unread(std::io::ErrorKind::PermissionDenied, Some(libc::EACCES)),
1366 ["its objects cannot be read: permission denied (os error 13)"],
1367 "a file the process may not read"
1368 );
1369 assert_eq!(
1370 unread(std::io::ErrorKind::TimedOut, None),
1371 ["its objects cannot be read: timed out"],
1372 "a service's failure has a kind and no system error number"
1373 );
1374 assert_eq!(
1375 problems(
1376 &tenant(
1377 Err(Unexamined::Examine(ExamineError::Failed(StoreError::Io))),
1378 false
1379 ),
1380 HOUR,
1381 NOW,
1382 true,
1383 ),
1384 ["it could not be examined: Io"],
1385 "any other failure, with its error"
1386 );
1387 }
1388
1389 #[test]
1390 fn a_sweep_is_stalled_only_once_a_version_waited_longer_than_the_interval() {
1391 let waited = |since| Examination {
1392 due: 1,
1393 oldest_due_since: Some(since),
1394 ..sound()
1395 };
1396 let ok = waited(datetime!(2026-10-25 11:00 UTC));
1397 assert_eq!(
1398 problems(&tenant(Ok(ok), false), HOUR, NOW, true),
1399 Vec::<String>::new()
1400 );
1401 let stalled = waited(datetime!(2026-10-25 10:59:59 UTC));
1402 assert_eq!(
1403 problems(&tenant(Ok(stalled), false), HOUR, NOW, true),
1404 [
1405 "1 version(s) due for purge, the oldest longer than purge_interval: the sweep is not keeping up"
1406 ],
1407 "one second past purge_interval is a stalled sweep"
1408 );
1409 }
1410
1411 #[test]
1412 fn check_reports_each_tenant_and_a_summary_and_exits_1_on_a_problem() {
1413 let s = setup();
1414 let id = s.create("acme");
1415 let out = s.run(Command::Check).expect("nothing wrong");
1416 assert_eq!(out.len(), 2);
1417 assert_eq!(out[0]["tenant"], id.as_str());
1418 assert_eq!(out[0]["problems"], json!([]));
1419 assert_eq!(out[1]["tenants"], 1);
1420 assert_eq!(out[1]["problems"], 0);
1421
1422 let tenant = TenantId::parse(&id).expect("id");
1423 let version = {
1424 let tenants = s.tenants();
1425 let store = tenants.store(tenant).expect("store");
1426 let (found, body) = vcon(UUID, "kept");
1427 let Ok(crate::store::Created::New(v)) =
1428 store.create(&Caller { key: KeyId([1; 8]) }, &found, &body)
1429 else {
1430 panic!("stored")
1431 };
1432 v
1433 };
1434 let objects = s.config.data_dir.join("tenants").join(&id).join("objects");
1435 std::fs::remove_file(objects.join(version.to_string())).expect("remove");
1436 std::fs::write(objects.join(format!("{version}.tmp")), b"x").expect("leftover");
1437 let mut printed = Vec::new();
1438 let found = run(&s.config, &Command::Check, &mut printed);
1439 assert!(
1440 matches!(found, Err(CommandError::CheckFound(1))),
1441 "{found:?}"
1442 );
1443 let lines: Vec<Value> = String::from_utf8(printed)
1444 .expect("text")
1445 .lines()
1446 .map(|l| serde_json::from_str(l).expect("json"))
1447 .collect();
1448 assert_eq!(lines[0]["damaged"], json!([version.to_string()]));
1449 assert_eq!(lines[0]["leftovers"], json!([format!("{version}.tmp")]));
1450 assert_eq!(lines[1]["problems"], 1);
1451 assert!(
1452 objects.join(format!("{version}.tmp")).exists(),
1453 "check reports leftovers; it does not remove them"
1454 );
1455 let server = datadir::lock(&s.config.data_dir, Sharing::Serve).expect("a server");
1456 assert!(matches!(
1457 s.run(Command::Check),
1458 Err(CommandError::DataDir(LockError::InUse(Sharing::Alone)))
1459 ));
1460 drop(server);
1461 }
1462 }
1463
1464 #[test]
1467 fn beside_a_server_only_the_beside_commands_run() {
1468 let s = setup();
1469 let tenant = s.create("acme");
1470 let server = datadir::lock(&s.config.data_dir, Sharing::Serve).expect("a server");
1471 for command in [
1472 Command::TenantCreate {
1473 name: "beta".to_owned(),
1474 retention: None,
1475 },
1476 Command::TenantRemove {
1477 id: tenant.clone(),
1478 force: true,
1479 override_holds: false,
1480 },
1481 ] {
1482 assert!(
1483 matches!(
1484 s.run(command.clone()),
1485 Err(CommandError::DataDir(LockError::InUse(Sharing::Alone)))
1486 ),
1487 "{command:?}"
1488 );
1489 }
1490 s.run(Command::TenantList).expect("beside");
1491 s.run(Command::TenantSetRetention {
1492 id: tenant.clone(),
1493 retention: "1y".to_owned(),
1494 })
1495 .expect("beside");
1496 s.run(Command::KeyList { tenant: None }).expect("beside");
1497 let made = s
1498 .run(Command::KeyCreate {
1499 owner: Owner::Operator,
1500 label: "l".to_owned(),
1501 })
1502 .expect("beside");
1503 s.run(Command::KeyRevoke {
1504 id: made[0]["id"].as_str().expect("an id").to_owned(),
1505 })
1506 .expect("beside");
1507 s.run(Command::AuditExport {
1508 log: Log::Admin,
1509 since: None,
1510 })
1511 .expect("beside");
1512 s.run(Command::Backup {
1513 to: s._dir.path().join("backup"),
1514 })
1515 .expect("beside");
1516 drop(server);
1517 assert_eq!(s.run(Command::TenantList).expect("listed").len(), 1);
1518 }
1519
1520 #[test]
1523 fn only_a_command_that_runs_alone_recovers() {
1524 let s = setup();
1525 s.create("acme");
1526 let in_progress = TenantId::generate().to_string();
1527 std::fs::create_dir(s.config.data_dir.join("tenants").join(&in_progress))
1528 .expect("a directory with no row");
1529 s.run(Command::TenantList).expect("listed");
1530 s.run(Command::KeyList { tenant: None }).expect("listed");
1531 assert!(
1532 s.tenant_dirs().contains(&in_progress),
1533 "left by beside commands"
1534 );
1535 s.create("beta");
1536 assert!(
1537 !s.tenant_dirs().contains(&in_progress),
1538 "removed by an alone command"
1539 );
1540 }
1541
1542 #[test]
1543 fn a_master_key_other_users_may_read_stops_every_command() {
1544 let s = setup();
1545 s.create("acme");
1546 chmod(&s.config.master_key, 0o644);
1547 let error = s.run(Command::TenantList).expect_err("refused");
1548 let path = s.config.master_key.display();
1549 assert_eq!(
1550 error.to_string(),
1551 format!(
1552 "the master key cannot be read: master_key {path}: other users may read or \
1553 change the file (mode 0644); run `chmod 600 {path}`, or `chmod 640 {path}` for \
1554 a group that only reads it"
1555 ),
1556 "the command stops with the rule's text, naming the key, the file and the fix"
1557 );
1558 }
1559
1560 #[test]
1561 fn rekey_master_refuses_a_new_key_other_users_may_read_under_its_option() {
1562 let s = setup();
1563 s.create("acme");
1564 let new_file = s.config.master_key.with_file_name("new.key");
1565 std::fs::write(&new_file, [0x5c; 32]).expect("new key");
1566 chmod(&new_file, 0o644);
1567 let error = s
1568 .run(Command::RekeyMaster {
1569 new_master: new_file.clone(),
1570 })
1571 .expect_err("refused");
1572 assert!(
1573 error
1574 .to_string()
1575 .contains(&format!("--new-master {}: other users", new_file.display())),
1576 "{error}"
1577 );
1578 }
1579
1580 #[cfg(feature = "s3")]
1581 #[test]
1582 fn an_export_secret_other_users_may_read_is_refused_under_export_s3() {
1583 let s = setup();
1584 let secret = s.config.master_key.with_file_name("export.secret");
1585 std::fs::write(&secret, "k3y-0123\n").expect("secret");
1586 chmod(&secret, 0o644);
1587 let mut config = s.config.clone();
1588 config.export = crate::config::parse(&format!(
1589 "listen = \"127.0.0.1:1\"\ndata_dir = \"/d\"\nmaster_key = \"/m\"\n\
1590 [tls]\ncert = \"c\"\nkey = \"k\"\n\
1591 [export.s3]\nendpoint = \"http://127.0.0.1:9\"\nregion = \"eu-west-3\"\n\
1592 access_key_id = \"id\"\nsecret_access_key_file = {secret:?}\nallow_http = true\n"
1593 ))
1594 .expect("a configuration")
1595 .export;
1596 let error = s3_target(&config, "vcon", "").err().expect("refused");
1597 let text = error.to_string();
1598 assert!(
1599 text.contains(&format!(
1600 "export.s3.secret_access_key_file {}: other users",
1601 secret.display()
1602 )),
1603 "{text}"
1604 );
1605 assert!(!text.contains("k3y"), "{text}");
1606 }
1607
1608 #[test]
1609 fn a_wrong_master_key_is_named() {
1610 let s = setup();
1611 s.create("acme");
1612 std::fs::write(&s.config.master_key, [0x5b; 32]).expect("another key");
1613 let error = s.run(Command::TenantList).expect_err("refused");
1614 assert!(matches!(error, CommandError::WrongMasterKey), "{error:?}");
1615 assert!(error.to_string().contains("master key"), "{error}");
1616 std::fs::write(&s.config.master_key, [0x5a; 31]).expect("short key");
1617 let error = s.run(Command::TenantList).expect_err("refused");
1618 assert!(matches!(error, CommandError::MasterKey(_)), "{error:?}");
1619 }
1620
1621 #[test]
1622 fn backup_prints_what_it_copied_and_check_finds_the_copy_whole() {
1623 let s = setup();
1624 s.create("acme");
1625 s.create("globex");
1626 let to = s._dir.path().join("backup");
1627 let out = s.run(Command::Backup { to: to.clone() }).expect("backs up");
1628 assert_eq!(
1629 out,
1630 [serde_json::json!({ "tenants": 2, "versions": 0, "tries": 1 })]
1631 );
1632 let copy = Setup {
1633 _dir: tempfile::tempdir().expect("temp dir"),
1634 config: Config {
1635 data_dir: to,
1636 ..s.config.clone()
1637 },
1638 };
1639 let checked = copy.run(Command::Check).expect("check finds no problem");
1640 assert_eq!(checked.last().expect("a summary")["problems"], 0);
1641 let names: Vec<_> = copy
1642 .run(Command::TenantList)
1643 .expect("lists")
1644 .iter()
1645 .map(|t| t["name"].clone())
1646 .collect();
1647 assert_eq!(names, ["acme", "globex"]);
1648 }
1649
1650 #[test]
1651 fn a_backup_path_already_there_is_refused() {
1652 let s = setup();
1653 let to = s._dir.path().join("backup");
1654 std::fs::create_dir(&to).expect("dir");
1655 let error = s.run(Command::Backup { to }).expect_err("refused");
1656 assert!(
1657 matches!(error, CommandError::Backup(BackupError::Exists)),
1658 "{error:?}"
1659 );
1660 }
1661
1662 fn says(error: &CommandError) -> &'static str {
1666 match error {
1667 CommandError::DataDir(_) => "the data directory is in use",
1668 CommandError::MasterKey(_) => "the master key cannot be read",
1669 CommandError::Open(_) => "opening /srv/data/server.sqlite failed: disk I/O error",
1671 CommandError::WrongMasterKey => "is not the one server.sqlite was made under",
1672 CommandError::BadPeriod(_) => "\"7w\" is not a period",
1673 CommandError::UnknownKey => "no key has this id",
1674 CommandError::Output(_) => "the output could not be written",
1675 CommandError::SameMasterKey => "already in use",
1676 CommandError::CheckFound(_) => "check found 2 problem(s)",
1677 CommandError::Storage(_) => "the storage cannot be used: bucket \"vcon\"",
1678 CommandError::BadLevel(_) => "\"most\" is not a metadata level",
1679 CommandError::BadTime(_) => "\"yesterday\" is not an RFC 3339 time",
1680 CommandError::BadTarget(_) => "\"s3://\" is not a directory or an s3://bucket/prefix",
1681 CommandError::NoS3 => "[export.s3] or [storage.s3]",
1682 CommandError::Export(_) => "another export wrote",
1683 CommandError::Move { .. } => "running storage move-objects again moves the rest",
1684 CommandError::Backup(e) => match e {
1685 BackupError::Exists => "already exists",
1686 BackupError::KeptChanging => "try again",
1687 BackupError::Io => "could not be written",
1688 BackupError::AuditFailed => "audit record",
1689 },
1690 CommandError::Tenant(e) => match e {
1691 TenantError::NotFound => "no tenant",
1692 TenantError::NameTaken => "another tenant has this name",
1693 TenantError::BadName => "a tenant name is",
1694 TenantError::HoldsVcons => "--force",
1695 TenantError::UnderHold => "--override-holds",
1696 TenantError::LimitReached => "rekey master",
1697 TenantError::AuditFailed => "audit record",
1698 TenantError::Closing => "being removed",
1699 TenantError::CliOnly => "command line",
1700 TenantError::BadScopes => "scopes",
1701 TenantError::WrongKey => "is not the one server.sqlite was made under",
1704 TenantError::Io => "could not be read or written",
1705 },
1706 }
1707 }
1708
1709 #[test]
1712 fn storage_move_objects_needs_a_bucket() {
1713 let s = setup();
1714 s.create("acme");
1715 let error = s.run(Command::StorageMoveObjects).expect_err("refused");
1716 assert!(
1717 error.to_string().contains("storage.objects = \"s3\""),
1718 "names the setting: {error}"
1719 );
1720 }
1721
1722 #[cfg(feature = "backend-tests")]
1726 #[test]
1727 fn storage_move_objects_moves_each_tenants_objects_to_the_bucket() {
1728 use crate::backend::Objects;
1729 let s = setup();
1730 let id = s.create("acme");
1731 store_one(&s, &id);
1732 let tenant = TenantId::parse(&id).expect("an id");
1733 let local = s.config.data_dir.join("tenants").join(&id).join("objects");
1734 let files = || std::fs::read_dir(&local).expect("listed").count();
1735 assert_eq!(files(), 1, "one object file");
1736 let (bucket, mut settings) = crate::backend::s3::remote::bucket(false);
1737 let secret = crate::backend::s3::remote::secret_file();
1738 settings.secret_access_key_file = Some(secret.1.clone());
1739 let mut config = s.config.clone();
1740 config.storage = crate::config::Storage {
1741 objects: crate::config::ObjectStore::S3(settings),
1742 parquet: None,
1743 };
1744 let moving = |config: &Config| -> Vec<Value> {
1745 let mut out = Vec::new();
1746 run(config, &Command::StorageMoveObjects, &mut out).expect("moved");
1747 String::from_utf8(out)
1748 .expect("text")
1749 .lines()
1750 .map(|l| serde_json::from_str(l).expect("a JSON line"))
1751 .collect()
1752 };
1753 assert_eq!(
1754 moving(&config),
1755 [
1756 json!({"tenant": id, "moved": 1, "missing": 0}),
1757 json!({"moved": 1})
1758 ],
1759 "one object moved, and nothing missing"
1760 );
1761 assert_eq!(files(), 0, "no object file is left");
1762 assert_eq!(
1763 bucket.tenant(tenant).list().expect("listed").len(),
1764 1,
1765 "the object is in the bucket"
1766 );
1767 let tenants = Tenants::open_beside_in(
1768 &config.data_dir,
1769 Key::load_master(&config.master_key).expect("master"),
1770 Arc::new(OsFs),
1771 Arc::new(SystemClock),
1772 crate::backend::ObjectPlace::S3(bucket.clone()),
1773 )
1774 .expect("opens");
1775 let (_, body) = vcon(UUID, "exported");
1776 assert_eq!(
1777 tenants
1778 .store(tenant)
1779 .expect("its store")
1780 .get(&Caller { key: KeyId([7; 8]) }, UUID.parse().expect("uuid"))
1781 .expect("reads")
1782 .body,
1783 body,
1784 "the vCon reads back from the bucket"
1785 );
1786 drop(tenants);
1787 assert_eq!(
1788 moving(&config),
1789 [
1790 json!({"tenant": id, "moved": 0, "missing": 0}),
1791 json!({"moved": 0})
1792 ],
1793 "a second run moves nothing"
1794 );
1795 }
1796
1797 fn store_one(s: &Setup, id: &str) {
1799 let store = s
1800 .tenants()
1801 .store(TenantId::parse(id).expect("an id"))
1802 .expect("the store");
1803 let (found, body) = vcon(UUID, "exported");
1804 store
1805 .create(&Caller { key: KeyId([7; 8]) }, &found, &body)
1806 .expect("stored");
1807 }
1808
1809 #[test]
1810 fn tenant_set_metadata_prints_the_level_and_list_shows_it() {
1811 let s = setup();
1812 let id = s.create("acme");
1813 let out = s
1814 .run(Command::TenantSetMetadata {
1815 id: id.clone(),
1816 metadata: "counts".to_owned(),
1817 })
1818 .expect("set");
1819 assert_eq!(
1820 out,
1821 [json!({ "id": id, "metadata": "counts" })],
1822 "the command prints the tenant and its level"
1823 );
1824 assert_eq!(
1825 s.run(Command::TenantList).expect("listed")[0]["metadata"],
1826 "counts",
1827 "the list shows the level"
1828 );
1829 assert!(
1830 matches!(
1831 s.run(Command::TenantSetMetadata {
1832 id: id.clone(),
1833 metadata: "most".to_owned(),
1834 }),
1835 Err(CommandError::BadLevel(text)) if text == "most"
1836 ),
1837 "a level that is not one is refused, naming it"
1838 );
1839 assert_eq!(
1840 tenant_error(s.run(Command::TenantSetMetadata {
1841 id: TenantId::generate().to_string(),
1842 metadata: "full".to_owned(),
1843 })),
1844 TenantError::NotFound,
1845 "a tenant id no tenant has is not found"
1846 );
1847 }
1848
1849 #[test]
1852 fn export_parquet_runs_beside_a_server_and_prints_what_it_wrote() {
1853 let s = setup();
1854 let id = s.create("acme");
1855 store_one(&s, &id);
1856 s.run(Command::TenantSetMetadata {
1857 id: id.clone(),
1858 metadata: "counts".to_owned(),
1859 })
1860 .expect("set");
1861 let to = s._dir.path().join("export");
1862 let export = Command::ExportParquet {
1863 tenant: id.clone(),
1864 to: to.display().to_string(),
1865 since: Some("2000-01-01T00:00:00Z".to_owned()),
1866 until: None,
1867 };
1868 let server = datadir::lock(&s.config.data_dir, Sharing::Serve).expect("a server");
1869 let out = s.run(export.clone()).expect("exports beside a server");
1870 drop(server);
1871 assert_eq!(out.len(), 1, "{out:?}");
1872 let line = &out[0];
1873 let manifest = format!("tenant={id}/manifest/00000000000000000001.json");
1874 assert_eq!(line["tenant"], id, "the line names the tenant");
1875 assert_eq!(
1876 line["metadata"], "counts",
1877 "the export is at the tenant's level"
1878 );
1879 assert_eq!(
1880 line["to"],
1881 to.display().to_string(),
1882 "the line names the target"
1883 );
1884 assert_eq!(line["manifest"], manifest, "the line names the manifest");
1885 assert_eq!(line["seq"], 1, "the first export to the target");
1886 assert_eq!(line["files"], 1, "one store date, one file");
1887 assert_eq!(line["rows"], 1, "the one vCon stored");
1888 assert_eq!(line["skipped"], 0, "nothing was purged during the run");
1889 assert_eq!(line["unread"], 0, "every body was read");
1890 let m: Value =
1891 serde_json::from_slice(&std::fs::read(to.join(&manifest)).expect("the manifest"))
1892 .expect("JSON");
1893 assert_eq!(m["bytes"], line["bytes"], "the bytes the manifest names");
1894 assert_eq!(
1895 m["since"], "2000-01-01T00:00:00Z",
1896 "the manifest records --since"
1897 );
1898 let alone = datadir::lock(&s.config.data_dir, Sharing::Alone).expect("alone");
1899 assert!(
1900 matches!(
1901 s.run(export),
1902 Err(CommandError::DataDir(LockError::InUse(Sharing::Beside)))
1903 ),
1904 "an export does not run beside a command that runs alone"
1905 );
1906 drop(alone);
1907 }
1908
1909 #[test]
1910 fn export_parquet_refuses_a_bad_time_target_or_tenant() {
1911 let s = setup();
1912 let id = s.create("acme");
1913 let export = |to: &str, since: Option<&str>, until: Option<&str>| Command::ExportParquet {
1914 tenant: id.clone(),
1915 to: to.to_owned(),
1916 since: since.map(str::to_owned),
1917 until: until.map(str::to_owned),
1918 };
1919 let dir = s._dir.path().join("out").display().to_string();
1920 assert!(
1921 matches!(
1922 s.run(export(&dir, Some("yesterday"), None)),
1923 Err(CommandError::BadTime(t)) if t == "yesterday"
1924 ),
1925 "a word that is not an RFC 3339 time is refused, naming it"
1926 );
1927 assert!(
1928 matches!(
1929 s.run(export(&dir, None, Some("2026-13-01T00:00:00Z"))),
1930 Err(CommandError::BadTime(_))
1931 ),
1932 "a month 13 is not a time"
1933 );
1934 assert!(
1935 matches!(
1936 s.run(export("s3://", None, None)),
1937 Err(CommandError::BadTarget(t)) if t == "s3://"
1938 ),
1939 "an s3:// URL with no bucket is refused, naming it"
1940 );
1941 assert!(
1942 matches!(
1943 s.run(export("s3://reports/vcon", None, None)),
1944 Err(CommandError::NoS3)
1945 ),
1946 "no S3 service is configured"
1947 );
1948 assert_eq!(
1949 tenant_error(s.run(Command::ExportParquet {
1950 tenant: TenantId::generate().to_string(),
1951 to: dir.clone(),
1952 since: None,
1953 until: None,
1954 })),
1955 TenantError::NotFound,
1956 "an unknown tenant is not found"
1957 );
1958 assert!(
1959 !std::path::Path::new(&dir).exists(),
1960 "a refused export writes nothing"
1961 );
1962 }
1963
1964 #[test]
1965 fn each_error_says_what_went_wrong() {
1966 let tenant = [
1967 TenantError::NotFound,
1968 TenantError::NameTaken,
1969 TenantError::BadName,
1970 TenantError::HoldsVcons,
1971 TenantError::UnderHold,
1972 TenantError::LimitReached,
1973 TenantError::AuditFailed,
1974 TenantError::Closing,
1975 TenantError::CliOnly,
1976 TenantError::BadScopes,
1977 TenantError::WrongKey,
1978 TenantError::Io,
1979 ]
1980 .map(CommandError::Tenant);
1981 let backup = [
1982 BackupError::Exists,
1983 BackupError::KeptChanging,
1984 BackupError::Io,
1985 BackupError::AuditFailed,
1986 ]
1987 .map(CommandError::Backup);
1988 let rest = [
1989 CommandError::DataDir(LockError::InUse(Sharing::Alone)),
1990 CommandError::MasterKey(crate::envelope::KeyError::WrongSize),
1991 CommandError::Open(RegistryError::failed(
1992 tenants::OpenStep::OpenCatalog,
1993 std::path::PathBuf::from("/srv/data/server.sqlite"),
1994 io::Error::other("disk I/O error"),
1995 )),
1996 CommandError::WrongMasterKey,
1997 CommandError::BadPeriod("7w".to_owned()),
1998 CommandError::UnknownKey,
1999 CommandError::Output(io::Error::other("closed")),
2000 CommandError::SameMasterKey,
2001 CommandError::CheckFound(2),
2002 CommandError::Storage(StorageError(
2003 "bucket \"vcon\" cannot be reached or read".to_owned(),
2004 )),
2005 CommandError::BadLevel("most".to_owned()),
2006 CommandError::BadTime("yesterday".to_owned()),
2007 CommandError::BadTarget("s3://".to_owned()),
2008 CommandError::NoS3,
2009 CommandError::Export(crate::export::ExportError::Raced("m".to_owned())),
2010 CommandError::Move {
2011 tenant: TenantId([1; 16]),
2012 why: "the bucket could not be written".to_owned(),
2013 },
2014 ];
2015 for error in tenant.into_iter().chain(backup).chain(rest) {
2016 let text = error.to_string();
2017 assert!(text.contains(says(&error)), "{error:?}: {text}");
2018 }
2019 }
2020}