cli_v1.rs (37703B)
1 //! One-pass command-line admission for the hardened Myc command contract. 2 3 use std::error::Error; 4 use std::ffi::OsString; 5 use std::fmt; 6 use std::num::NonZeroU64; 7 use std::path::{Component, Path, PathBuf}; 8 9 use clap::{Parser, Subcommand, ValueEnum}; 10 use radroots_runtime_paths::InstanceId; 11 use radroots_service_host::AdminOperationId; 12 use radroots_service_sqlite::BackupManifestSha256; 13 14 /// The exact bootstrap profile selected by the operator. 15 #[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize)] 16 #[serde(rename_all = "snake_case")] 17 pub enum MycBootstrapProfileV1 { 18 ServiceHost, 19 Interactive, 20 RepoLocal, 21 } 22 23 /// The only two governed command-result encodings. 24 #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, serde::Serialize)] 25 #[serde(rename_all = "snake_case")] 26 pub enum MycCliOutputModeV1 { 27 #[default] 28 Human, 29 Json, 30 } 31 32 /// The exact governed top-level Myc command inventory. 33 #[derive(PartialEq, Eq)] 34 pub enum MycCommandV1 { 35 Run, 36 Config(MycConfigCommandV1), 37 State(MycStateCommandV1), 38 Identity(MycIdentityCommandV1), 39 Status, 40 Doctor, 41 } 42 43 /// Governed configuration commands. 44 #[derive(PartialEq, Eq)] 45 pub enum MycConfigCommandV1 { 46 Init, 47 Validate, 48 Show, 49 Schema, 50 Apply(MycConfigApplyArgsV1), 51 } 52 53 /// Governed state commands. 54 #[derive(PartialEq, Eq)] 55 pub enum MycStateCommandV1 { 56 Init, 57 Status, 58 Backup(MycStateBackupArgsV1), 59 Restore(MycStateRestoreArgsV1), 60 Verify, 61 Migrate, 62 } 63 64 /// Governed identity commands. 65 #[derive(PartialEq, Eq)] 66 pub enum MycIdentityCommandV1 { 67 Init(MycIdentityCommandArgsV1), 68 Status(MycIdentityCommandArgsV1), 69 ExportPublic(MycIdentityCommandArgsV1), 70 } 71 72 /// Exact offline configuration-apply input. 73 #[derive(PartialEq, Eq)] 74 pub struct MycConfigApplyArgsV1 { 75 candidate_config: PathBuf, 76 } 77 78 impl MycConfigApplyArgsV1 { 79 #[must_use] 80 pub fn candidate_config(&self) -> &Path { 81 &self.candidate_config 82 } 83 } 84 85 impl fmt::Debug for MycConfigApplyArgsV1 { 86 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { 87 formatter.write_str("MycConfigApplyArgsV1([redacted])") 88 } 89 } 90 91 /// Exact online-or-offline state-backup input. 92 #[derive(PartialEq, Eq)] 93 pub struct MycStateBackupArgsV1 { 94 operation_id: Box<str>, 95 target: PathBuf, 96 expected_generation: u64, 97 } 98 99 impl MycStateBackupArgsV1 { 100 #[must_use] 101 pub fn operation_id(&self) -> &str { 102 &self.operation_id 103 } 104 105 #[must_use] 106 pub fn target(&self) -> &Path { 107 &self.target 108 } 109 110 #[must_use] 111 pub const fn expected_generation(&self) -> u64 { 112 self.expected_generation 113 } 114 } 115 116 impl fmt::Debug for MycStateBackupArgsV1 { 117 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { 118 formatter 119 .debug_struct("MycStateBackupArgsV1") 120 .field("operation_id", &"[redacted]") 121 .field("target", &"[redacted]") 122 .field("expected_generation", &self.expected_generation) 123 .finish() 124 } 125 } 126 127 /// Exact offline restore-verification input. 128 #[derive(PartialEq, Eq)] 129 pub struct MycStateRestoreArgsV1 { 130 manifest: PathBuf, 131 manifest_sha256: BackupManifestSha256, 132 bundle: PathBuf, 133 maximum_state_bytes: NonZeroU64, 134 } 135 136 impl MycStateRestoreArgsV1 { 137 #[must_use] 138 pub fn manifest(&self) -> &Path { 139 &self.manifest 140 } 141 142 #[must_use] 143 pub const fn manifest_sha256(&self) -> BackupManifestSha256 { 144 self.manifest_sha256 145 } 146 147 #[must_use] 148 pub fn bundle(&self) -> &Path { 149 &self.bundle 150 } 151 152 #[must_use] 153 pub const fn maximum_state_bytes(&self) -> NonZeroU64 { 154 self.maximum_state_bytes 155 } 156 } 157 158 impl fmt::Debug for MycStateRestoreArgsV1 { 159 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { 160 formatter.write_str("MycStateRestoreArgsV1([redacted])") 161 } 162 } 163 164 /// Role input required by every identity command. 165 #[derive(Clone, Copy, Debug, PartialEq, Eq)] 166 pub struct MycIdentityCommandArgsV1 { 167 role: crate::MycProviderRole, 168 } 169 170 impl MycIdentityCommandArgsV1 { 171 #[must_use] 172 pub const fn role(self) -> crate::MycProviderRole { 173 self.role 174 } 175 } 176 177 impl fmt::Debug for MycCommandV1 { 178 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { 179 formatter.write_str(match self { 180 Self::Run => "MycCommandV1::Run", 181 Self::Config(_) => "MycCommandV1::Config([redacted])", 182 Self::State(_) => "MycCommandV1::State([redacted])", 183 Self::Identity(_) => "MycCommandV1::Identity([redacted])", 184 Self::Status => "MycCommandV1::Status", 185 Self::Doctor => "MycCommandV1::Doctor", 186 }) 187 } 188 } 189 190 /// The only three process authorities selected by the hardened CLI. 191 #[derive(Clone, Copy, Debug, PartialEq, Eq)] 192 pub enum MycCliPrimaryAuthorityV1 { 193 Daemon, 194 Offline, 195 LiveUnixAdmin, 196 } 197 198 /// The closed offline operation classes selected before any state access. 199 #[derive(Clone, Copy, Debug, PartialEq, Eq)] 200 pub enum MycCliOfflineOperationV1 { 201 Config, 202 StateExclusive, 203 StateReadOnly, 204 IdentityExclusive, 205 IdentityReadOnly, 206 Doctor, 207 } 208 209 /// The closed Unix-admin operations reachable from the command inventory. 210 #[derive(Clone, Copy, Debug, PartialEq, Eq)] 211 pub enum MycCliAdminOperationV1 { 212 Status, 213 StateStatus, 214 StateBackup, 215 IdentityStatus, 216 IdentityPublic, 217 } 218 219 #[cfg(any(target_os = "linux", target_os = "macos"))] 220 impl MycCliAdminOperationV1 { 221 /// Returns the exact native Unix-admin route selected by this operation. 222 #[must_use] 223 pub const fn route(self) -> crate::MycAdminRoute { 224 match self { 225 Self::Status => crate::MycAdminRoute::Status, 226 Self::StateStatus => crate::MycAdminRoute::StateStatus, 227 Self::StateBackup => crate::MycAdminRoute::StateBackup, 228 Self::IdentityStatus => crate::MycAdminRoute::IdentityStatus, 229 Self::IdentityPublic => crate::MycAdminRoute::IdentityPublic, 230 } 231 } 232 } 233 234 /// A sealed, side-effect-free execution plan for one admitted CLI invocation. 235 /// 236 /// Construction is owned by [`plan_myc_cli_v1`]. A live mutation never carries 237 /// an offline fallback, while explicitly read-only status, backup, and public 238 /// identity operations may fall back only after later execution proves the 239 /// daemon writer lock is free. 240 /// 241 /// ```compile_fail 242 /// use myc::{MycCliExecutionPlanV1, MycCliPrimaryAuthorityV1}; 243 /// 244 /// let _ = MycCliExecutionPlanV1 { 245 /// primary_authority: MycCliPrimaryAuthorityV1::Offline, 246 /// offline_operation: None, 247 /// admin_operation: None, 248 /// daemon_unavailable_offline_fallback: true, 249 /// }; 250 /// ``` 251 #[derive(Clone, Copy, PartialEq, Eq)] 252 pub struct MycCliExecutionPlanV1 { 253 primary_authority: MycCliPrimaryAuthorityV1, 254 offline_operation: Option<MycCliOfflineOperationV1>, 255 admin_operation: Option<MycCliAdminOperationV1>, 256 daemon_unavailable_offline_fallback: bool, 257 } 258 259 impl MycCliExecutionPlanV1 { 260 /// Returns the authority that must be attempted first. 261 #[must_use] 262 pub const fn primary_authority(&self) -> MycCliPrimaryAuthorityV1 { 263 self.primary_authority 264 } 265 266 /// Returns the bounded offline operation, when the plan admits one. 267 #[must_use] 268 pub const fn offline_operation(&self) -> Option<MycCliOfflineOperationV1> { 269 self.offline_operation 270 } 271 272 /// Returns the bounded Unix-admin operation, when the plan admits one. 273 #[must_use] 274 pub const fn admin_operation(&self) -> Option<MycCliAdminOperationV1> { 275 self.admin_operation 276 } 277 278 /// Returns whether a missing daemon may fall back to read-only offline work. 279 #[must_use] 280 pub const fn allows_daemon_unavailable_offline_fallback(&self) -> bool { 281 self.daemon_unavailable_offline_fallback 282 } 283 } 284 285 impl fmt::Debug for MycCliExecutionPlanV1 { 286 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { 287 formatter 288 .debug_struct("MycCliExecutionPlanV1") 289 .field("primary_authority", &self.primary_authority) 290 .field("offline_operation", &self.offline_operation) 291 .field("admin_operation", &self.admin_operation) 292 .field( 293 "daemon_unavailable_offline_fallback", 294 &self.daemon_unavailable_offline_fallback, 295 ) 296 .finish() 297 } 298 } 299 300 /// Stable source-free classification for command-line admission failures. 301 #[derive(Clone, Copy, Debug, PartialEq, Eq)] 302 pub enum MycCliV1ErrorKind { 303 HelpRequested, 304 InvalidArguments, 305 InvalidInstance, 306 InvalidRepoLocalRoot, 307 UnexpectedRepoLocalRoot, 308 InvalidConfigPath, 309 InvalidCommandInput, 310 } 311 312 impl MycCliV1ErrorKind { 313 const fn message(self) -> &'static str { 314 match self { 315 Self::HelpRequested => "command-line help requested", 316 Self::InvalidArguments => "command-line arguments are invalid", 317 Self::InvalidInstance => "instance identifier is invalid", 318 Self::InvalidRepoLocalRoot => "repo-local profile requires a valid absolute root", 319 Self::UnexpectedRepoLocalRoot => { 320 "repo-local root is forbidden outside the repo-local profile" 321 } 322 Self::InvalidConfigPath => "configuration path must be absolute without traversal", 323 Self::InvalidCommandInput => "command input is invalid", 324 } 325 } 326 } 327 328 /// One safe command-line admission outcome requiring process-level handling. 329 #[derive(Clone, PartialEq, Eq)] 330 pub struct MycCliV1Error { 331 kind: MycCliV1ErrorKind, 332 help_text: Option<Box<str>>, 333 } 334 335 impl MycCliV1Error { 336 const fn new(kind: MycCliV1ErrorKind) -> Self { 337 Self { 338 kind, 339 help_text: None, 340 } 341 } 342 343 /// Returns the stable failure classification. 344 #[must_use] 345 pub const fn kind(&self) -> MycCliV1ErrorKind { 346 self.kind 347 } 348 349 /// Returns bounded static command help, without caller argument text. 350 /// The process owner may print this on stdout and return success without 351 /// executing a command. Display and Debug remain source-free diagnostics. 352 #[must_use] 353 pub fn help_text(&self) -> Option<&str> { 354 self.help_text.as_deref() 355 } 356 } 357 358 impl fmt::Debug for MycCliV1Error { 359 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { 360 formatter 361 .debug_struct("MycCliV1Error") 362 .field("kind", &self.kind) 363 .finish() 364 } 365 } 366 367 impl fmt::Display for MycCliV1Error { 368 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { 369 formatter.write_str(self.kind.message()) 370 } 371 } 372 373 impl Error for MycCliV1Error {} 374 375 /// A validated one-pass Myc bootstrap and command selection. 376 pub struct MycCliInvocationV1 { 377 profile: MycBootstrapProfileV1, 378 instance: InstanceId, 379 repo_local_root: Option<PathBuf>, 380 config_path: Option<PathBuf>, 381 output_mode: MycCliOutputModeV1, 382 command: MycCommandV1, 383 } 384 385 impl MycCliInvocationV1 { 386 /// Returns the explicitly selected bootstrap profile. 387 #[must_use] 388 pub const fn profile(&self) -> MycBootstrapProfileV1 { 389 self.profile 390 } 391 392 /// Returns the validated instance identifier. 393 #[must_use] 394 pub fn instance(&self) -> &InstanceId { 395 &self.instance 396 } 397 398 /// Returns the explicit repo-local root, when selected. 399 #[must_use] 400 pub fn repo_local_root(&self) -> Option<&Path> { 401 self.repo_local_root.as_deref() 402 } 403 404 /// Returns the optional explicit configuration path. 405 #[must_use] 406 pub fn config_path(&self) -> Option<&Path> { 407 self.config_path.as_deref() 408 } 409 410 /// Returns the exact result encoding selected once at admission. 411 #[must_use] 412 pub const fn output_mode(&self) -> MycCliOutputModeV1 { 413 self.output_mode 414 } 415 416 /// Returns the exact governed command selection. 417 #[must_use] 418 pub const fn command(&self) -> &MycCommandV1 { 419 &self.command 420 } 421 } 422 423 impl fmt::Debug for MycCliInvocationV1 { 424 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { 425 formatter 426 .debug_struct("MycCliInvocationV1") 427 .field("profile", &self.profile) 428 .field("instance", &"[redacted]") 429 .field( 430 "repo_local_root", 431 &self.repo_local_root.as_ref().map(|_| "[redacted]"), 432 ) 433 .field( 434 "config_path", 435 &self.config_path.as_ref().map(|_| "[redacted]"), 436 ) 437 .field("output_mode", &self.output_mode) 438 .field("command", &self.command) 439 .finish() 440 } 441 } 442 443 /// Parses the exact hardened Myc bootstrap and command tree once. 444 /// 445 /// The iterator must include the program name as its first element. Only bounded 446 /// static help is retained separately; all other dependency-owned diagnostics are 447 /// discarded so caller-controlled argument text cannot escape the error boundary. 448 pub fn parse_myc_cli_v1_from<I, T>(arguments: I) -> Result<MycCliInvocationV1, MycCliV1Error> 449 where 450 I: IntoIterator<Item = T>, 451 T: Into<OsString> + Clone, 452 { 453 let parsed = RawMycCliV1::try_parse_from(arguments).map_err(|error| { 454 if error.kind() == clap::error::ErrorKind::DisplayHelp { 455 let help = error.to_string(); 456 if help.len() <= 16 * 1024 { 457 return MycCliV1Error { 458 kind: MycCliV1ErrorKind::HelpRequested, 459 help_text: Some(help.into_boxed_str()), 460 }; 461 } 462 } 463 MycCliV1Error::new(MycCliV1ErrorKind::InvalidArguments) 464 })?; 465 let profile = parsed 466 .profile 467 .ok_or_else(|| MycCliV1Error::new(MycCliV1ErrorKind::InvalidArguments))? 468 .into(); 469 let instance = parsed 470 .instance 471 .ok_or_else(|| MycCliV1Error::new(MycCliV1ErrorKind::InvalidArguments))?; 472 let instance = InstanceId::new(instance) 473 .map_err(|_| MycCliV1Error::new(MycCliV1ErrorKind::InvalidInstance))?; 474 validate_bootstrap_paths( 475 profile, 476 parsed.repo_local_root.as_deref(), 477 parsed.config.as_deref(), 478 )?; 479 480 Ok(MycCliInvocationV1 { 481 profile, 482 instance, 483 repo_local_root: parsed.repo_local_root, 484 config_path: parsed.config, 485 output_mode: parsed.output.into(), 486 command: admit_command(parsed.command)?, 487 }) 488 } 489 490 /// Selects the sole permitted execution authority for an admitted command. 491 /// 492 /// This function performs no filesystem, database, socket, environment, task, 493 /// or process work. Later executors consume the plan without reparsing process 494 /// arguments. In particular, no live command receives direct SQLite authority. 495 #[must_use] 496 pub const fn plan_myc_cli_v1(invocation: &MycCliInvocationV1) -> MycCliExecutionPlanV1 { 497 match &invocation.command { 498 MycCommandV1::Run => daemon_plan(), 499 MycCommandV1::Config(_) => offline_plan(MycCliOfflineOperationV1::Config), 500 MycCommandV1::State(MycStateCommandV1::Init) 501 | MycCommandV1::State(MycStateCommandV1::Restore(_)) 502 | MycCommandV1::State(MycStateCommandV1::Verify) 503 | MycCommandV1::State(MycStateCommandV1::Migrate) => { 504 offline_plan(MycCliOfflineOperationV1::StateExclusive) 505 } 506 MycCommandV1::State(MycStateCommandV1::Status) => read_only_admin_plan( 507 MycCliAdminOperationV1::StateStatus, 508 MycCliOfflineOperationV1::StateReadOnly, 509 ), 510 MycCommandV1::State(MycStateCommandV1::Backup(_)) => read_only_admin_plan( 511 MycCliAdminOperationV1::StateBackup, 512 MycCliOfflineOperationV1::StateReadOnly, 513 ), 514 MycCommandV1::Identity(MycIdentityCommandV1::Init(_)) => { 515 offline_plan(MycCliOfflineOperationV1::IdentityExclusive) 516 } 517 MycCommandV1::Identity(MycIdentityCommandV1::Status(_)) => read_only_admin_plan( 518 MycCliAdminOperationV1::IdentityStatus, 519 MycCliOfflineOperationV1::IdentityReadOnly, 520 ), 521 MycCommandV1::Identity(MycIdentityCommandV1::ExportPublic(_)) => read_only_admin_plan( 522 MycCliAdminOperationV1::IdentityPublic, 523 MycCliOfflineOperationV1::IdentityReadOnly, 524 ), 525 MycCommandV1::Status => read_only_admin_plan( 526 MycCliAdminOperationV1::Status, 527 MycCliOfflineOperationV1::StateReadOnly, 528 ), 529 MycCommandV1::Doctor => offline_plan(MycCliOfflineOperationV1::Doctor), 530 } 531 } 532 533 const fn daemon_plan() -> MycCliExecutionPlanV1 { 534 MycCliExecutionPlanV1 { 535 primary_authority: MycCliPrimaryAuthorityV1::Daemon, 536 offline_operation: None, 537 admin_operation: None, 538 daemon_unavailable_offline_fallback: false, 539 } 540 } 541 542 const fn offline_plan(operation: MycCliOfflineOperationV1) -> MycCliExecutionPlanV1 { 543 MycCliExecutionPlanV1 { 544 primary_authority: MycCliPrimaryAuthorityV1::Offline, 545 offline_operation: Some(operation), 546 admin_operation: None, 547 daemon_unavailable_offline_fallback: false, 548 } 549 } 550 551 const fn read_only_admin_plan( 552 admin_operation: MycCliAdminOperationV1, 553 offline_operation: MycCliOfflineOperationV1, 554 ) -> MycCliExecutionPlanV1 { 555 MycCliExecutionPlanV1 { 556 primary_authority: MycCliPrimaryAuthorityV1::LiveUnixAdmin, 557 offline_operation: Some(offline_operation), 558 admin_operation: Some(admin_operation), 559 daemon_unavailable_offline_fallback: true, 560 } 561 } 562 563 fn validate_bootstrap_paths( 564 profile: MycBootstrapProfileV1, 565 repo_local_root: Option<&Path>, 566 config_path: Option<&Path>, 567 ) -> Result<(), MycCliV1Error> { 568 match (profile, repo_local_root) { 569 (MycBootstrapProfileV1::RepoLocal, Some(root)) if valid_absolute_path(root, true) => {} 570 (MycBootstrapProfileV1::RepoLocal, _) => { 571 return Err(MycCliV1Error::new(MycCliV1ErrorKind::InvalidRepoLocalRoot)); 572 } 573 (_, Some(_)) => { 574 return Err(MycCliV1Error::new( 575 MycCliV1ErrorKind::UnexpectedRepoLocalRoot, 576 )); 577 } 578 (_, None) => {} 579 } 580 581 if config_path.is_some_and(|path| !valid_absolute_path(path, true)) { 582 return Err(MycCliV1Error::new(MycCliV1ErrorKind::InvalidConfigPath)); 583 } 584 Ok(()) 585 } 586 587 fn valid_absolute_path(path: &Path, require_non_root: bool) -> bool { 588 path.is_absolute() 589 && (!require_non_root || path.parent().is_some()) 590 && path 591 .to_str() 592 .is_some_and(|value| !value.is_empty() && value.len() <= 4_096) 593 && !path 594 .components() 595 .any(|component| matches!(component, Component::ParentDir)) 596 } 597 598 #[derive(Parser)] 599 #[command(name = "myc", bin_name = "myc", disable_help_subcommand = true)] 600 struct RawMycCliV1 { 601 #[arg(long, global = true, value_enum)] 602 profile: Option<RawProfile>, 603 #[arg(long, global = true)] 604 instance: Option<String>, 605 #[arg(long = "repo-local-root", global = true)] 606 repo_local_root: Option<PathBuf>, 607 #[arg(long, global = true)] 608 config: Option<PathBuf>, 609 #[arg(long, global = true, value_enum, default_value_t = RawOutputMode::Human)] 610 output: RawOutputMode, 611 #[command(subcommand)] 612 command: RawCommand, 613 } 614 615 #[derive(Clone, Copy, ValueEnum)] 616 enum RawProfile { 617 ServiceHost, 618 Interactive, 619 RepoLocal, 620 } 621 622 #[derive(Clone, Copy, Default, ValueEnum)] 623 enum RawOutputMode { 624 #[default] 625 Human, 626 Json, 627 } 628 629 impl From<RawOutputMode> for MycCliOutputModeV1 { 630 fn from(value: RawOutputMode) -> Self { 631 match value { 632 RawOutputMode::Human => Self::Human, 633 RawOutputMode::Json => Self::Json, 634 } 635 } 636 } 637 638 impl From<RawProfile> for MycBootstrapProfileV1 { 639 fn from(value: RawProfile) -> Self { 640 match value { 641 RawProfile::ServiceHost => Self::ServiceHost, 642 RawProfile::Interactive => Self::Interactive, 643 RawProfile::RepoLocal => Self::RepoLocal, 644 } 645 } 646 } 647 648 #[derive(Subcommand)] 649 enum RawCommand { 650 Run, 651 Config { 652 #[command(subcommand)] 653 command: RawConfigCommand, 654 }, 655 State { 656 #[command(subcommand)] 657 command: RawStateCommand, 658 }, 659 Identity { 660 #[command(subcommand)] 661 command: RawIdentityCommand, 662 }, 663 Status, 664 Doctor, 665 } 666 667 #[derive(Subcommand)] 668 enum RawConfigCommand { 669 Init, 670 Validate, 671 Show, 672 Schema, 673 Apply { 674 #[arg(long = "candidate-config")] 675 candidate_config: PathBuf, 676 }, 677 } 678 679 #[derive(Subcommand)] 680 enum RawStateCommand { 681 Init, 682 Status, 683 Backup { 684 #[arg(long = "operation-id")] 685 operation_id: String, 686 #[arg(long)] 687 target: PathBuf, 688 #[arg(long = "expected-generation")] 689 expected_generation: u64, 690 #[arg(long, required = true)] 691 confirm: bool, 692 }, 693 Restore { 694 #[arg(long)] 695 manifest: PathBuf, 696 #[arg(long = "manifest-sha256")] 697 manifest_sha256: String, 698 #[arg(long)] 699 bundle: PathBuf, 700 #[arg(long = "maximum-state-bytes")] 701 maximum_state_bytes: u64, 702 #[arg(long, required = true)] 703 confirm: bool, 704 }, 705 Verify, 706 Migrate, 707 } 708 709 #[derive(Subcommand)] 710 enum RawIdentityCommand { 711 Init { 712 #[arg(long, value_enum)] 713 role: RawIdentityRole, 714 }, 715 Status { 716 #[arg(long, value_enum)] 717 role: RawIdentityRole, 718 }, 719 ExportPublic { 720 #[arg(long, value_enum)] 721 role: RawIdentityRole, 722 }, 723 } 724 725 #[derive(Clone, Copy, ValueEnum)] 726 enum RawIdentityRole { 727 Transport, 728 User, 729 Discovery, 730 } 731 732 impl From<RawIdentityRole> for crate::MycProviderRole { 733 fn from(value: RawIdentityRole) -> Self { 734 match value { 735 RawIdentityRole::Transport => Self::Transport, 736 RawIdentityRole::User => Self::User, 737 RawIdentityRole::Discovery => Self::Discovery, 738 } 739 } 740 } 741 742 fn admit_command(command: RawCommand) -> Result<MycCommandV1, MycCliV1Error> { 743 let invalid = || MycCliV1Error::new(MycCliV1ErrorKind::InvalidCommandInput); 744 Ok(match command { 745 RawCommand::Run => MycCommandV1::Run, 746 RawCommand::Config { command } => MycCommandV1::Config(match command { 747 RawConfigCommand::Init => MycConfigCommandV1::Init, 748 RawConfigCommand::Validate => MycConfigCommandV1::Validate, 749 RawConfigCommand::Show => MycConfigCommandV1::Show, 750 RawConfigCommand::Schema => MycConfigCommandV1::Schema, 751 RawConfigCommand::Apply { candidate_config } => { 752 if !valid_absolute_path(&candidate_config, true) { 753 return Err(invalid()); 754 } 755 MycConfigCommandV1::Apply(MycConfigApplyArgsV1 { candidate_config }) 756 } 757 }), 758 RawCommand::State { command } => MycCommandV1::State(match command { 759 RawStateCommand::Init => MycStateCommandV1::Init, 760 RawStateCommand::Status => MycStateCommandV1::Status, 761 RawStateCommand::Backup { 762 operation_id, 763 target, 764 expected_generation, 765 confirm, 766 } => { 767 if !confirm || !valid_absolute_path(&target, true) { 768 return Err(invalid()); 769 } 770 let operation_id = AdminOperationId::new(operation_id).map_err(|_| invalid())?; 771 MycStateCommandV1::Backup(MycStateBackupArgsV1 { 772 operation_id: operation_id.as_str().into(), 773 target, 774 expected_generation, 775 }) 776 } 777 RawStateCommand::Restore { 778 manifest, 779 manifest_sha256, 780 bundle, 781 maximum_state_bytes, 782 confirm, 783 } => { 784 if !confirm 785 || !valid_absolute_path(&manifest, true) 786 || !valid_absolute_path(&bundle, true) 787 { 788 return Err(invalid()); 789 } 790 if manifest_sha256.len() != 64 791 || manifest_sha256 792 .bytes() 793 .any(|byte| !matches!(byte, b'0'..=b'9' | b'a'..=b'f')) 794 { 795 return Err(invalid()); 796 } 797 let mut digest = [0_u8; 32]; 798 hex::decode_to_slice(manifest_sha256, &mut digest).map_err(|_| invalid())?; 799 let maximum_state_bytes = 800 NonZeroU64::new(maximum_state_bytes).ok_or_else(invalid)?; 801 MycStateCommandV1::Restore(MycStateRestoreArgsV1 { 802 manifest, 803 manifest_sha256: BackupManifestSha256::from_bytes(digest), 804 bundle, 805 maximum_state_bytes, 806 }) 807 } 808 RawStateCommand::Verify => MycStateCommandV1::Verify, 809 RawStateCommand::Migrate => MycStateCommandV1::Migrate, 810 }), 811 RawCommand::Identity { command } => MycCommandV1::Identity(match command { 812 RawIdentityCommand::Init { role } => { 813 MycIdentityCommandV1::Init(MycIdentityCommandArgsV1 { role: role.into() }) 814 } 815 RawIdentityCommand::Status { role } => { 816 MycIdentityCommandV1::Status(MycIdentityCommandArgsV1 { role: role.into() }) 817 } 818 RawIdentityCommand::ExportPublic { role } => { 819 MycIdentityCommandV1::ExportPublic(MycIdentityCommandArgsV1 { role: role.into() }) 820 } 821 }), 822 RawCommand::Status => MycCommandV1::Status, 823 RawCommand::Doctor => MycCommandV1::Doctor, 824 }) 825 } 826 827 #[cfg(test)] 828 mod tests { 829 use super::*; 830 831 fn parse(command: &[&str]) -> Result<MycCliInvocationV1, MycCliV1Error> { 832 let mut arguments = vec!["myc", "--profile", "service-host", "--instance", "primary"]; 833 arguments.extend_from_slice(command); 834 parse_myc_cli_v1_from(arguments) 835 } 836 837 #[test] 838 fn exact_command_inventory_parses() { 839 let vectors = [ 840 (&["run"][..], "run"), 841 (&["config", "init"][..], "config_init"), 842 (&["config", "validate"][..], "config_validate"), 843 (&["config", "show"][..], "config_show"), 844 (&["config", "schema"][..], "config_schema"), 845 ( 846 &["config", "apply", "--candidate-config", "/candidate.toml"][..], 847 "config_apply", 848 ), 849 (&["state", "init"][..], "state_init"), 850 (&["state", "status"][..], "state_status"), 851 ( 852 &[ 853 "state", 854 "backup", 855 "--operation-id", 856 "backup-01", 857 "--target", 858 "/backup/new", 859 "--expected-generation", 860 "7", 861 "--confirm", 862 ][..], 863 "state_backup", 864 ), 865 ( 866 &[ 867 "state", 868 "restore", 869 "--manifest", 870 "/backup/manifest.json", 871 "--manifest-sha256", 872 "1111111111111111111111111111111111111111111111111111111111111111", 873 "--bundle", 874 "/backup/bundle", 875 "--maximum-state-bytes", 876 "1048576", 877 "--confirm", 878 ][..], 879 "state_restore", 880 ), 881 (&["state", "verify"][..], "state_verify"), 882 (&["state", "migrate"][..], "state_migrate"), 883 ( 884 &["identity", "init", "--role", "transport"][..], 885 "identity_init", 886 ), 887 ( 888 &["identity", "status", "--role", "user"][..], 889 "identity_status", 890 ), 891 ( 892 &["identity", "export-public", "--role", "discovery"][..], 893 "identity_export_public", 894 ), 895 (&["status"][..], "status"), 896 (&["doctor"][..], "doctor"), 897 ]; 898 for (arguments, expected) in vectors { 899 assert_eq!( 900 command_name(parse(arguments).expect("command").command()), 901 expected 902 ); 903 } 904 } 905 906 fn command_name(command: &MycCommandV1) -> &'static str { 907 match command { 908 MycCommandV1::Run => "run", 909 MycCommandV1::Config(MycConfigCommandV1::Init) => "config_init", 910 MycCommandV1::Config(MycConfigCommandV1::Validate) => "config_validate", 911 MycCommandV1::Config(MycConfigCommandV1::Show) => "config_show", 912 MycCommandV1::Config(MycConfigCommandV1::Schema) => "config_schema", 913 MycCommandV1::Config(MycConfigCommandV1::Apply(_)) => "config_apply", 914 MycCommandV1::State(MycStateCommandV1::Init) => "state_init", 915 MycCommandV1::State(MycStateCommandV1::Status) => "state_status", 916 MycCommandV1::State(MycStateCommandV1::Backup(_)) => "state_backup", 917 MycCommandV1::State(MycStateCommandV1::Restore(_)) => "state_restore", 918 MycCommandV1::State(MycStateCommandV1::Verify) => "state_verify", 919 MycCommandV1::State(MycStateCommandV1::Migrate) => "state_migrate", 920 MycCommandV1::Identity(MycIdentityCommandV1::Init(_)) => "identity_init", 921 MycCommandV1::Identity(MycIdentityCommandV1::Status(_)) => "identity_status", 922 MycCommandV1::Identity(MycIdentityCommandV1::ExportPublic(_)) => { 923 "identity_export_public" 924 } 925 MycCommandV1::Status => "status", 926 MycCommandV1::Doctor => "doctor", 927 } 928 } 929 930 #[test] 931 fn profiles_and_paths_are_cross_bound() { 932 for profile in ["service-host", "interactive"] { 933 let invocation = parse_myc_cli_v1_from([ 934 "myc", 935 "--profile", 936 profile, 937 "--instance", 938 "north-01", 939 "--config", 940 "/etc/radroots/myc.toml", 941 "run", 942 ]) 943 .expect("production profile"); 944 assert_eq!(invocation.instance().as_str(), "north-01"); 945 assert_eq!( 946 invocation.config_path(), 947 Some(Path::new("/etc/radroots/myc.toml")) 948 ); 949 assert!(invocation.repo_local_root().is_none()); 950 } 951 952 let repo_local = parse_myc_cli_v1_from([ 953 "myc", 954 "--profile", 955 "repo-local", 956 "--instance", 957 "dev", 958 "--repo-local-root", 959 "/repo/radroots", 960 "config", 961 "validate", 962 ]) 963 .expect("repo local"); 964 assert_eq!(repo_local.profile(), MycBootstrapProfileV1::RepoLocal); 965 assert_eq!( 966 repo_local.repo_local_root(), 967 Some(Path::new("/repo/radroots")) 968 ); 969 } 970 971 #[test] 972 fn invalid_bootstrap_values_fail_with_stable_kinds() { 973 for value in ["Upper", "north-", "north.west"] { 974 let error = parse_myc_cli_v1_from([ 975 "myc", 976 "--profile", 977 "service-host", 978 "--instance", 979 value, 980 "run", 981 ]) 982 .expect_err("invalid instance"); 983 assert_eq!(error.kind(), MycCliV1ErrorKind::InvalidInstance); 984 } 985 assert_eq!( 986 parse_myc_cli_v1_from([ 987 "myc", 988 "--profile", 989 "service-host", 990 "--instance=-north", 991 "run", 992 ]) 993 .expect_err("invalid instance boundary") 994 .kind(), 995 MycCliV1ErrorKind::InvalidInstance 996 ); 997 assert_eq!( 998 parse_myc_cli_v1_from(["myc", "--profile", "service-host", "--instance=", "run",]) 999 .expect_err("empty instance") 1000 .kind(), 1001 MycCliV1ErrorKind::InvalidInstance 1002 ); 1003 let exact = "a".repeat(radroots_runtime_paths::INSTANCE_ID_MAX_BYTES); 1004 assert!( 1005 parse_myc_cli_v1_from([ 1006 "myc", 1007 "--profile", 1008 "service-host", 1009 "--instance", 1010 exact.as_str(), 1011 "run", 1012 ]) 1013 .is_ok() 1014 ); 1015 let overlong = "a".repeat(radroots_runtime_paths::INSTANCE_ID_MAX_BYTES + 1); 1016 assert_eq!( 1017 parse_myc_cli_v1_from([ 1018 "myc", 1019 "--profile", 1020 "service-host", 1021 "--instance", 1022 overlong.as_str(), 1023 "run", 1024 ]) 1025 .expect_err("overlong instance") 1026 .kind(), 1027 MycCliV1ErrorKind::InvalidInstance 1028 ); 1029 1030 let missing_root = 1031 parse_myc_cli_v1_from(["myc", "--profile", "repo-local", "--instance", "dev", "run"]) 1032 .expect_err("missing root"); 1033 assert_eq!(missing_root.kind(), MycCliV1ErrorKind::InvalidRepoLocalRoot); 1034 1035 let unexpected_root = parse_myc_cli_v1_from([ 1036 "myc", 1037 "--profile", 1038 "interactive", 1039 "--instance", 1040 "dev", 1041 "--repo-local-root", 1042 "/repo/radroots", 1043 "run", 1044 ]) 1045 .expect_err("unexpected root"); 1046 assert_eq!( 1047 unexpected_root.kind(), 1048 MycCliV1ErrorKind::UnexpectedRepoLocalRoot 1049 ); 1050 1051 for invalid in ["relative", "/", "/repo/../escape"] { 1052 let error = parse_myc_cli_v1_from([ 1053 "myc", 1054 "--profile", 1055 "repo-local", 1056 "--instance", 1057 "dev", 1058 "--repo-local-root", 1059 invalid, 1060 "run", 1061 ]) 1062 .expect_err("invalid root"); 1063 assert_eq!(error.kind(), MycCliV1ErrorKind::InvalidRepoLocalRoot); 1064 } 1065 1066 for invalid in ["relative.toml", "/", "/etc/../secret.toml"] { 1067 let error = parse_myc_cli_v1_from([ 1068 "myc", 1069 "--profile", 1070 "service-host", 1071 "--instance", 1072 "primary", 1073 "--config", 1074 invalid, 1075 "run", 1076 ]) 1077 .expect_err("invalid config path"); 1078 assert_eq!(error.kind(), MycCliV1ErrorKind::InvalidConfigPath); 1079 } 1080 } 1081 1082 #[test] 1083 fn restore_digest_is_exact_lowercase_hex_before_decode() { 1084 for digest in [ 1085 "1".repeat(63), 1086 "1".repeat(65), 1087 "A".repeat(64), 1088 "g".repeat(64), 1089 "1".repeat(1_048_576), 1090 ] { 1091 let error = parse_myc_cli_v1_from([ 1092 "myc", 1093 "--profile", 1094 "service-host", 1095 "--instance", 1096 "primary", 1097 "state", 1098 "restore", 1099 "--manifest", 1100 "/backup/manifest.json", 1101 "--manifest-sha256", 1102 digest.as_str(), 1103 "--bundle", 1104 "/backup/bundle", 1105 "--maximum-state-bytes", 1106 "1048576", 1107 "--confirm", 1108 ]) 1109 .expect_err("invalid digest"); 1110 assert_eq!(error.kind(), MycCliV1ErrorKind::InvalidCommandInput); 1111 } 1112 } 1113 1114 #[test] 1115 fn missing_unknown_and_prototype_arguments_fail_without_sources() { 1116 for arguments in [ 1117 vec!["myc", "run"], 1118 vec!["myc", "--profile", "service-host", "run"], 1119 vec!["myc", "--profile", "service-host", "--instance", "primary"], 1120 vec![ 1121 "myc", 1122 "--profile", 1123 "production", 1124 "--instance", 1125 "primary", 1126 "run", 1127 ], 1128 vec![ 1129 "myc", 1130 "--profile", 1131 "service-host", 1132 "--instance", 1133 "primary", 1134 "--env-file", 1135 "secret.env", 1136 "run", 1137 ], 1138 vec![ 1139 "myc", 1140 "--profile", 1141 "service-host", 1142 "--instance", 1143 "primary", 1144 "persistence", 1145 "backup", 1146 ], 1147 ] { 1148 let failure = parse_myc_cli_v1_from(arguments).expect_err("arguments must fail"); 1149 assert_eq!(failure.kind(), MycCliV1ErrorKind::InvalidArguments); 1150 assert!(Error::source(&failure).is_none()); 1151 } 1152 } 1153 1154 #[test] 1155 fn debug_and_errors_do_not_render_caller_values() { 1156 let instance = "sensitive-instance"; 1157 let config = "/sensitive/config.toml"; 1158 let invocation = parse_myc_cli_v1_from([ 1159 "myc", 1160 "--profile", 1161 "service-host", 1162 "--instance", 1163 instance, 1164 "--config", 1165 config, 1166 "doctor", 1167 ]) 1168 .expect("invocation"); 1169 let debug = format!("{invocation:?}"); 1170 assert!(!debug.contains(instance)); 1171 assert!(!debug.contains(config)); 1172 1173 let secret = "secret-cli-value"; 1174 let failure = 1175 parse_myc_cli_v1_from(["myc", "--profile", secret, "--instance", "primary", "run"]) 1176 .expect_err("invalid profile"); 1177 let rendered = format!("{failure} {failure:?}"); 1178 assert!(!rendered.contains(secret)); 1179 assert!(Error::source(&failure).is_none()); 1180 } 1181 }