Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 4 additions & 1 deletion apps/piqueld/src/operations.rs
Original file line number Diff line number Diff line change
Expand Up @@ -362,7 +362,10 @@ impl OperationError {
.push(format!("Docker operation: {operation}"));
}
}
if let Some(failure) = error.downcast_ref::<piqueld_store::secrets::KeyFailure>() {
if let Some(failure) = error
.downcast_ref::<piqueld_store::secrets::SecretError>()
.and_then(piqueld_store::secrets::SecretError::key_failure)
{
diagnostic.causes.push(failure.fact().into());
}
if let Some(error) = error.downcast_ref::<piqueld_docker::ErrorResponse>() {
Expand Down
1 change: 0 additions & 1 deletion crates/piqueld-store/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion crates/piqueld-store/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
6 changes: 3 additions & 3 deletions crates/piqueld-store/src/secret/key.rs
Original file line number Diff line number Diff line change
Expand Up @@ -85,15 +85,15 @@ 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."
),
_ => format!(
"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)
}
})
}
Expand Down Expand Up @@ -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)),
},
Expand Down
10 changes: 6 additions & 4 deletions crates/piqueld-store/src/secret/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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))
}
Expand Down
4 changes: 2 additions & 2 deletions crates/piqueld-store/src/secret/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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());
Expand Down Expand Up @@ -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();
Expand Down
89 changes: 89 additions & 0 deletions crates/piqueld-store/src/secrets/error.rs
Original file line number Diff line number Diff line change
@@ -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<SecretError>,
},
}

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<KeyFailure> {
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::<Vec<_>>()
.join(": ")
}
}
13 changes: 7 additions & 6 deletions crates/piqueld-store/src/secrets/generate.rs
Original file line number Diff line number Diff line change
@@ -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};
Expand All @@ -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<Zeroizing<Vec<u8>>>;
fn generate(&self) -> Result<Zeroizing<Vec<u8>>, SecretError>;
}

impl Generate for SecretGenerator {
fn generate(&self) -> anyhow::Result<Zeroizing<Vec<u8>>> {
fn generate(&self) -> Result<Zeroizing<Vec<u8>>, 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";
Expand All @@ -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))
}
}
Expand Down
Loading
Loading