//! Destructive authorization. //! //! A `DestructiveAuthorization` can only be produced by [`authorize`], which //! requires the caller to present the destructive preview and a final //! confirmation. Destructive functions take `&DestructiveAuthorization`, so a //! code path that skipped confirmation cannot compile against them. //! //! This is an internal correctness guard, not a security boundary against //! malicious code already running in the same privileged process. use crate::error::{ExecError, Result}; #[derive(Debug)] pub struct DestructiveAuthorization { _private: (), } impl DestructiveAuthorization { fn issue() -> Self { Self { _private: () } } } pub trait Confirmation { /// Show the destructive preview and require the confirmation phrase. fn confirm_erase(&self, preview: &str) -> Result; /// Final yes/no confirmation immediately before execution. fn confirm_final(&self, message: &str) -> Result; } /// Confirm unconditionally. Only used for unattended installs where the caller /// has explicitly opted in (e.g. `--yes` on a disposable VM disk). pub struct AutoConfirm; impl Confirmation for AutoConfirm { fn confirm_erase(&self, _preview: &str) -> Result { Ok(true) } fn confirm_final(&self, _message: &str) -> Result { Ok(true) } } /// Always refuse. Safe default for dry-run / plan modes. pub struct DenyConfirm; impl Confirmation for DenyConfirm { fn confirm_erase(&self, _preview: &str) -> Result { Ok(false) } fn confirm_final(&self, _message: &str) -> Result { Ok(false) } } /// Perform the full confirmation flow and issue a token only on approval. pub fn authorize( confirmation: &dyn Confirmation, destructive_preview: &str, final_message: &str, ) -> Result { if !confirmation.confirm_erase(destructive_preview)? { return Err(ExecError::NotAuthorized( "whole-disk erase was not confirmed".into(), )); } if !confirmation.confirm_final(final_message)? { return Err(ExecError::NotAuthorized( "installation was not confirmed".into(), )); } Ok(DestructiveAuthorization::issue()) } #[cfg(test)] mod tests { use super::*; #[test] fn auto_confirm_issues_token() { let auth = authorize(&AutoConfirm, "preview", "go?").unwrap(); let _ = &auth; } #[test] fn deny_confirm_refuses() { let err = authorize(&DenyConfirm, "preview", "go?").unwrap_err(); assert!(matches!(err, ExecError::NotAuthorized(_))); } }