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