From 4b8add03806892528d3a3163cae387ecb8e7e3f3 Mon Sep 17 00:00:00 2001 From: piquel Date: Sun, 22 Nov 2026 23:05:20 +0100 Subject: [PATCH] refactor(store): store errors keep their sources instead of going through anyhow --- Cargo.lock | 1 - apps/piqueld/src/operations.rs | 5 +- crates/piqueld-store/Cargo.toml | 1 - crates/piqueld-store/src/lib.rs | 2 +- crates/piqueld-store/src/secret/key.rs | 6 +- crates/piqueld-store/src/secret/mod.rs | 10 ++- crates/piqueld-store/src/secret/tests.rs | 4 +- crates/piqueld-store/src/secrets/error.rs | 89 ++++++++++++++++++++ crates/piqueld-store/src/secrets/generate.rs | 13 +-- crates/piqueld-store/src/secrets/mod.rs | 80 +++++++++--------- 10 files changed, 152 insertions(+), 59 deletions(-) create mode 100644 crates/piqueld-store/src/secrets/error.rs diff --git a/Cargo.lock b/Cargo.lock index 5fd944a01..9f660f950 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2864,7 +2864,6 @@ dependencies = [ name = "piqueld-store" version = "0.1.0" dependencies = [ - "anyhow", "base64 0.22.1", "chacha20poly1305", "futures-util", diff --git a/apps/piqueld/src/operations.rs b/apps/piqueld/src/operations.rs index fc48ac040..0ef5bcf20 100644 --- a/apps/piqueld/src/operations.rs +++ b/apps/piqueld/src/operations.rs @@ -362,7 +362,10 @@ impl OperationError { .push(format!("Docker operation: {operation}")); } } - if let Some(failure) = error.downcast_ref::() { + if let Some(failure) = error + .downcast_ref::() + .and_then(piqueld_store::secrets::SecretError::key_failure) + { diagnostic.causes.push(failure.fact().into()); } if let Some(error) = error.downcast_ref::() { diff --git a/crates/piqueld-store/Cargo.toml b/crates/piqueld-store/Cargo.toml index 139cba5e4..5b8cbc2dc 100644 --- a/crates/piqueld-store/Cargo.toml +++ b/crates/piqueld-store/Cargo.toml @@ -20,7 +20,6 @@ include = ["/build.rs", "/migrations", "/src", "/LICENSE"] testing = [] [dependencies] -anyhow.workspace = true base64.workspace = true chacha20poly1305.workspace = true futures-util.workspace = true diff --git a/crates/piqueld-store/src/lib.rs b/crates/piqueld-store/src/lib.rs index 6c64002c5..64b8fa712 100644 --- a/crates/piqueld-store/src/lib.rs +++ b/crates/piqueld-store/src/lib.rs @@ -108,7 +108,7 @@ pub enum StoreError { Validation(#[from] piqueld_core::ValidationErrors), /// Secret ciphertext or its master key could not be used. #[error("secret storage is unavailable")] - SecretSource(#[source] anyhow::Error), + SecretSource(#[source] secrets::SecretError), /// Required values were discarded during lost-key recovery. #[error( "secret values unavailable: {names}; supply replacement values and start a new deployment" diff --git a/crates/piqueld-store/src/secret/key.rs b/crates/piqueld-store/src/secret/key.rs index 8388bf46c..3c1812734 100644 --- a/crates/piqueld-store/src/secret/key.rs +++ b/crates/piqueld-store/src/secret/key.rs @@ -85,7 +85,7 @@ impl Store { format!("{path} is private; the first secret write binds it to the database"), ), Err(error) => { - let step = match KeyFailure::of(&error) { + let step = match error.key_failure() { Some(KeyFailure::NotPrivate) => format!( "Make {path} a regular file owned by the daemon user with mode 0600." ), @@ -93,7 +93,7 @@ impl Store { "Restore the original {path} from backup, or discard every stored value with `piquelctl secrets recover-key`." ), }; - check(CheckStatus::Fail, format!("{error:#}")).next_step(step) + check(CheckStatus::Fail, error.chain()).next_step(step) } }) } @@ -249,7 +249,7 @@ impl Store { let verifier = Self::secret_key_verifier_on(&mut *tx).await?; let key = match SecretCipher::load(&self.secret_key_path, true) { Ok(cipher) => Ok(cipher), - Err(error) => match KeyFailure::of(&error) { + Err(error) => match error.key_failure() { Some(failure) if failure.lost() => Err(failure), _ => return Err(StoreError::SecretSource(error)), }, diff --git a/crates/piqueld-store/src/secret/mod.rs b/crates/piqueld-store/src/secret/mod.rs index fbeef3370..23988e40d 100644 --- a/crates/piqueld-store/src/secret/mod.rs +++ b/crates/piqueld-store/src/secret/mod.rs @@ -13,8 +13,7 @@ pub use stored::SecretPrecondition; use super::{ Attribution, EnvironmentId, NormalizedApplication, Operation, Store, StoreError, new_id, now_ms, }; -use crate::secrets::{Envelope, Generate, SecretCipher, SecretOwner}; -use anyhow::Context; +use crate::secrets::{Envelope, Generate, SecretCipher, SecretError, SecretOwner}; use piqueld_core::{ ApplicationId, api::SecretMetadata, @@ -307,9 +306,12 @@ impl Store { let generator = secret.generate.clone(); let mut value = tokio::task::spawn_blocking(move || generator.generate()) .await - .map_err(anyhow::Error::from) + .map_err(SecretError::Task) .and_then(|value| value) - .with_context(|| format!("generate secret {}", secret.name)) + .map_err(|source| SecretError::Generating { + name: secret.name.clone(), + source: Box::new(source), + }) .map_err(StoreError::SecretSource)?; Ok(std::mem::take(&mut *value)) } diff --git a/crates/piqueld-store/src/secret/tests.rs b/crates/piqueld-store/src/secret/tests.rs index 0be22793a..8c5281ca8 100644 --- a/crates/piqueld-store/src/secret/tests.rs +++ b/crates/piqueld-store/src/secret/tests.rs @@ -481,7 +481,7 @@ async fn key_recovery_keeps_values_behind_a_corrupt_verifier() { panic!("recovery refused expected"); }; assert!(matches!( - crate::secrets::KeyFailure::of(&error), + error.key_failure(), Some(crate::secrets::KeyFailure::VerifierCorrupt) )); assert!(key.exists()); @@ -532,7 +532,7 @@ async fn writes_bind_only_the_key_of_values_without_a_verifier() { panic!("a wrong key must not be bound"); }; assert!(matches!( - crate::secrets::KeyFailure::of(&error), + error.key_failure(), Some(crate::secrets::KeyFailure::AuthenticationFailed) )); std::fs::remove_file(&key).unwrap(); diff --git a/crates/piqueld-store/src/secrets/error.rs b/crates/piqueld-store/src/secrets/error.rs new file mode 100644 index 000000000..5a7ccac3b --- /dev/null +++ b/crates/piqueld-store/src/secrets/error.rs @@ -0,0 +1,89 @@ +//! The error of loading the master key and of encrypting or generating secrets. +use super::KeyFailure; +use std::error::Error; +use thiserror::Error; + +/// Why the master key or a secret value could not be used. +#[derive(Debug, Error)] +pub enum SecretError { + /// The master key is missing, not private, the wrong length, or does not + /// authenticate what is stored. + #[error(transparent)] + Key(#[from] KeyFailure), + /// A filesystem operation on the master key failed. + #[error("{action}")] + Io { + /// What was being done. + action: &'static str, + /// What the operating system said. + #[source] + source: std::io::Error, + }, + /// Opening the master key without following symlinks failed. + #[error("{action}")] + Open { + /// What was being done. + action: &'static str, + /// What the operating system said. + #[source] + source: rustix::io::Errno, + }, + /// The master key's file has no parent directory to install into or sync. + #[error("locate secret key directory")] + NoKeyDirectory, + /// The encrypted value's nonce is not the length of an `XChaCha20-Poly1305` nonce. + #[error("invalid encrypted secret nonce")] + InvalidNonce, + /// The cipher refused to encrypt a value. + #[error("secret encryption failed")] + Encryption, + /// The operating system's random source failed. + #[error("read random secret bytes")] + Random(#[source] getrandom::Error), + /// OpenSSL could not generate or encode an RSA key. + #[error("{action}")] + Rsa { + /// What was being done. + action: &'static str, + /// What OpenSSL reported. + #[source] + source: openssl::error::ErrorStack, + }, + /// The task generating a value did not finish. + #[error("secret generation task failed")] + Task(#[source] tokio::task::JoinError), + /// Generating the declared secret `name` failed. + #[error("generate secret {name}")] + Generating { + /// The secret's declared name. + name: String, + /// Why generating it failed. + #[source] + source: Box, + }, +} + +impl SecretError { + /// A filesystem failure while `action`. + pub(crate) fn io(action: &'static str) -> impl FnOnce(std::io::Error) -> Self { + move |source| Self::Io { action, source } + } + + /// The master-key failure this is, if it is one. + #[must_use] + pub const fn key_failure(&self) -> Option { + match self { + Self::Key(failure) => Some(*failure), + _ => None, + } + } + + /// This error and its causes, joined as `outer: inner`. + #[must_use] + pub fn chain(&self) -> String { + std::iter::successors(Some(self as &dyn Error), |error| (*error).source()) + .map(ToString::to_string) + .collect::>() + .join(": ") + } +} diff --git a/crates/piqueld-store/src/secrets/generate.rs b/crates/piqueld-store/src/secrets/generate.rs index f9f570938..7472b50b2 100644 --- a/crates/piqueld-store/src/secrets/generate.rs +++ b/crates/piqueld-store/src/secrets/generate.rs @@ -1,5 +1,5 @@ //! Values for secrets that manifests declare instead of setting manually. -use anyhow::Context; +use super::SecretError; use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD}; use openssl::{pkey::PKey, rsa::Rsa}; use piqueld_core::manifest::{SecretEncoding, SecretGenerator}; @@ -11,15 +11,15 @@ pub(crate) trait Generate { /// Returns a new value: random bytes as lowercase hex or unpadded /// `base64url` text, or an RSA private key as PKCS#8 PEM. Fails when the /// operating system's random source or OpenSSL key generation fails. - fn generate(&self) -> anyhow::Result>>; + fn generate(&self) -> Result>, SecretError>; } impl Generate for SecretGenerator { - fn generate(&self) -> anyhow::Result>> { + fn generate(&self) -> Result>, SecretError> { match *self { Self::Random { bytes, encoding } => { let mut raw = Zeroizing::new(vec![0; usize::from(bytes)]); - getrandom::fill(&mut raw).context("read random secret bytes")?; + getrandom::fill(&mut raw).map_err(SecretError::Random)?; Ok(match encoding { SecretEncoding::Hex => { const DIGITS: &[u8; 16] = b"0123456789abcdef"; @@ -36,10 +36,11 @@ impl Generate for SecretGenerator { }) } Self::Rsa { bits } => { - let key = Rsa::generate(u32::from(bits)).context("generate RSA key")?; + let rsa = |action| move |source| SecretError::Rsa { action, source }; + let key = Rsa::generate(u32::from(bits)).map_err(rsa("generate RSA key"))?; let pem = PKey::from_rsa(key) .and_then(|key| key.private_key_to_pem_pkcs8()) - .context("encode RSA key as PKCS#8 PEM")?; + .map_err(rsa("encode RSA key as PKCS#8 PEM"))?; Ok(Zeroizing::new(pem)) } } diff --git a/crates/piqueld-store/src/secrets/mod.rs b/crates/piqueld-store/src/secrets/mod.rs index 7e1b8e259..e0ccf9a60 100644 --- a/crates/piqueld-store/src/secrets/mod.rs +++ b/crates/piqueld-store/src/secrets/mod.rs @@ -1,5 +1,7 @@ //! Authenticated encryption for application secrets. Values never enter API metadata. +mod error; mod generate; +pub use error::SecretError; pub(crate) use generate::Generate; use chacha20poly1305::{ @@ -44,11 +46,6 @@ pub enum KeyFailure { } impl KeyFailure { - /// The failure `error` carries, if it is one. - pub(crate) fn of(error: &anyhow::Error) -> Option { - error.downcast_ref().copied() - } - /// Whether loading the key failed for good, so that only discarding the /// values it encrypted recovers: it is missing or the wrong length. A key /// that is merely not private is fixed on the host instead. A key that @@ -121,11 +118,13 @@ impl SecretCipher { /// access, holding exactly 32 bytes. /// /// Called under the store writer lock; a key bound to the database is never regenerated. - pub(crate) fn load(path: &Path, bound: bool) -> anyhow::Result { - use anyhow::{Context, bail}; - if !path.try_exists().context("inspect secret master key")? { + pub(crate) fn load(path: &Path, bound: bool) -> Result { + if !path + .try_exists() + .map_err(SecretError::io("inspect secret master key"))? + { if bound { - bail!(KeyFailure::Missing); + return Err(KeyFailure::Missing.into()); } Self::generate(path)?; } @@ -133,77 +132,78 @@ impl SecretCipher { } /// Writes a new key to `path`, which must not exist yet. - fn generate(path: &Path) -> anyhow::Result<()> { - use anyhow::Context; - let parent = path.parent().context("locate secret key directory")?; - let mut temporary = - tempfile::NamedTempFile::new_in(parent).context("create private secret key file")?; + fn generate(path: &Path) -> Result<(), SecretError> { + let parent = path.parent().ok_or(SecretError::NoKeyDirectory)?; + let mut temporary = tempfile::NamedTempFile::new_in(parent) + .map_err(SecretError::io("create private secret key file"))?; let mut key = XChaCha20Poly1305::generate_key(&mut OsRng); let result = temporary.write_all(key.as_slice()); key.zeroize(); - result.context("write secret master key")?; + result.map_err(SecretError::io("write secret master key"))?; temporary .as_file() .sync_all() - .context("sync secret master key")?; + .map_err(SecretError::io("sync secret master key"))?; temporary .persist_noclobber(path) - .map_err(|e| e.error) - .context("install secret master key")?; + .map_err(|e| SecretError::io("install secret master key")(e.error))?; Self::sync_directory(path) } /// Opens an existing key without creating or changing anything, as the /// installation check does. - pub(crate) fn open(path: &Path) -> anyhow::Result { - use anyhow::{Context, bail}; + pub(crate) fn open(path: &Path) -> Result { let descriptor = rustix::fs::open( path, rustix::fs::OFlags::RDONLY | rustix::fs::OFlags::CLOEXEC | rustix::fs::OFlags::NOFOLLOW, rustix::fs::Mode::empty(), ) - .context("open secret master key without following symlinks")?; + .map_err(|source| SecretError::Open { + action: "open secret master key without following symlinks", + source, + })?; let file = File::from(descriptor); - let metadata = file.metadata()?; + let metadata = file + .metadata() + .map_err(SecretError::io("inspect secret master key"))?; if !metadata.is_file() || metadata.mode() & 0o077 != 0 || metadata.uid() != rustix::process::geteuid().as_raw() { - bail!(KeyFailure::NotPrivate); + return Err(KeyFailure::NotPrivate.into()); } // One byte more than a key tells a longer file apart. let mut bytes = Zeroizing::new(Vec::with_capacity(KEY_BYTES + 1)); file.take(KEY_BYTES as u64 + 1) .read_to_end(&mut bytes) - .context("read secret master key")?; + .map_err(SecretError::io("read secret master key"))?; if bytes.len() != KEY_BYTES { - bail!(KeyFailure::InvalidLength); + return Err(KeyFailure::InvalidLength.into()); } - Ok(Self(XChaCha20Poly1305::new_from_slice(&bytes).map_err( - |_| anyhow::anyhow!("invalid secret key length"), - )?)) + Ok(Self( + XChaCha20Poly1305::new_from_slice(&bytes).map_err(|_| KeyFailure::InvalidLength)?, + )) } /// Moves an unusable key aside after its values were discarded, so the next value /// write generates a fresh key. The file is kept rather than deleted: it may belong /// to a different database backup. A missing key needs nothing. - pub(crate) fn retire(path: &Path, now_ms: i64) -> anyhow::Result<()> { - use anyhow::Context; + pub(crate) fn retire(path: &Path, now_ms: i64) -> Result<(), SecretError> { let mut retired = path.as_os_str().to_owned(); retired.push(format!(".retired-{now_ms}")); match std::fs::rename(path, &retired) { Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(()), - result => result.context("move unusable secret master key aside")?, + result => result.map_err(SecretError::io("move unusable secret master key aside"))?, } Self::sync_directory(path) } /// Syncs the directory holding the key at `path`, so that installing or /// moving the key survives a crash. - fn sync_directory(path: &Path) -> anyhow::Result<()> { - use anyhow::Context; - File::open(path.parent().context("locate secret key directory")?)? + fn sync_directory(path: &Path) -> Result<(), SecretError> { + File::open(path.parent().ok_or(SecretError::NoKeyDirectory)?) + .map_err(SecretError::io("open secret key directory"))? .sync_all() - .context("sync secret key directory") + .map_err(SecretError::io("sync secret key directory")) } /// Associated data binding a ciphertext to its owner, secret name, and /// generation, so a value cannot be moved to another secret or version. @@ -223,7 +223,7 @@ impl SecretCipher { name: &str, generation: i64, plaintext: &[u8], - ) -> anyhow::Result { + ) -> Result { let nonce = XChaCha20Poly1305::generate_nonce(&mut OsRng); let aad = Self::context(owner, name, generation); let ciphertext = self @@ -235,7 +235,7 @@ impl SecretCipher { aad: &aad, }, ) - .map_err(|_| anyhow::anyhow!("secret encryption failed"))?; + .map_err(|_| SecretError::Encryption)?; Ok(Envelope { nonce: nonce.to_vec(), ciphertext, @@ -249,9 +249,9 @@ impl SecretCipher { name: &str, generation: i64, envelope: &Envelope, - ) -> anyhow::Result>> { + ) -> Result>, SecretError> { if envelope.nonce.len() != NONCE_BYTES { - anyhow::bail!("invalid encrypted secret nonce"); + return Err(SecretError::InvalidNonce); } let aad = Self::context(owner, name, generation); let plaintext = self @@ -267,7 +267,7 @@ impl SecretCipher { Ok(Zeroizing::new(plaintext)) } /// Proves this key matches the database by decrypting its stored verifier. - pub(crate) fn verify(&self, verifier: &Envelope) -> anyhow::Result<()> { + pub(crate) fn verify(&self, verifier: &Envelope) -> Result<(), SecretError> { self.decrypt(SecretOwner::KeyVerifier, "key-verification", 1, verifier) .map(drop) }