refactor(security): move SecretBox into compliance-core (#260)
CI / Check (push) Skipped
CI / Detect Changes (pull_request) Skipped
CI / Deploy Agent (pull_request) Skipped
CI / Deploy Dashboard (pull_request) Skipped
CI / Deploy Docs (pull_request) Skipped
CI / Deploy MCP (pull_request) Skipped
CI / Check (pull_request) Successful in 6m12s

The dashboard seals its session records with the same scheme, so the crypto
moves to `compliance_core::secret_box` behind a `secrets` feature. The agent's
`secrets` module keeps the startup sealing pass and re-exports the type.
`from_key` takes raw key bytes, and `has_key` replaces the private field check.
The agent no longer depends on aes-gcm directly.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EYKjxacrr6K88DruUmP48p
This commit is contained in:
Sharang ParnerkarandClaude Opus 5 committed 2026-09-21 18:11:13 +02:00
1 parent b89f31e2d3
commit 00bae6ec82
6 files changed
+373 -339

No files matched your search

Generated
+2 -1
View File
@@ -659,7 +659,6 @@ dependencies = [
name = "compliance-agent"
version = "0.1.0"
dependencies = [
"aes-gcm",
"axum",
"base64",
"chrono",
@@ -709,7 +708,9 @@ dependencies = [
name = "compliance-core"
version = "0.1.0"
dependencies = [
"aes-gcm",
"axum",
"base64",
"bson",
"chrono",
"hex",
+2 -3
View File
@@ -7,7 +7,7 @@ edition = "2021"
workspace = true
[dependencies]
compliance-core = { workspace = true, features = ["mongodb", "telemetry", "axum"] }
compliance-core = { workspace = true, features = ["mongodb", "telemetry", "axum", "secrets"] }
control-map = { workspace = true }
compliance-graph = { path = "../compliance-graph" }
compliance-dast = { path = "../compliance-dast" }
@@ -57,7 +57,6 @@ urlencoding = "2"
futures-util = "0.3"
jsonwebtoken = "9"
zip = { workspace = true }
aes-gcm = { workspace = true }
tokio-tungstenite = { version = "0.26", features = ["rustls-tls-webpki-roots"] }
futures-core = "0.3"
dashmap = { workspace = true }
@@ -65,7 +64,7 @@ tokio-stream = { workspace = true }
rand = { workspace = true }
[dev-dependencies]
compliance-core = { workspace = true, features = ["mongodb", "axum"] }
compliance-core = { workspace = true, features = ["mongodb", "axum", "secrets"] }
tower = { version = "0.5", features = ["util"] }
reqwest = { workspace = true }
serde_json = { workspace = true }
+6 -335
View File
@@ -1,228 +1,19 @@
//! Tenant credentials at rest (#260).
//!
//! Git tokens, tracker tokens, webhook secrets and pentest passwords are sealed
//! with AES-256-GCM under `SECRETS_ENCRYPTION_KEY` before they are written, and
//! opened only where they are used. Without a key the agent refuses to store a
//! credential rather than write it in plain text.
//!
//! A sealed value reads `enc:v1:<base64 of nonce + ciphertext>`. The prefix
//! tells it apart from a value stored before sealing existed, which
//! [`seal_stored_credentials`] converts at startup.
//! with [`SecretBox`] under `SECRETS_ENCRYPTION_KEY` before they are written,
//! and opened only where they are used. [`seal_stored_credentials`] converts
//! values stored before sealing existed.
use std::fmt;
use aes_gcm::aead::{Aead, AeadCore, KeyInit, OsRng};
use aes_gcm::{Aes256Gcm, Nonce};
use base64::Engine;
use futures_util::TryStreamExt;
use mongodb::bson::{doc, to_bson, Document};
use secrecy::ExposeSecret;
use compliance_core::models::{Credentials, OnboardedTarget};
use compliance_core::AgentConfig;
use compliance_core::models::OnboardedTarget;
pub use compliance_core::secret_box::{SecretBox, SecretError};
use crate::database::{Database, DatabasePool};
use crate::error::AgentError;
/// Marks a sealed value and its format version.
const SEALED_PREFIX: &str = "enc:v1:";
/// AES-GCM nonce length in bytes.
const NONCE_LEN: usize = 12;
/// Why a credential could not be sealed or opened.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum SecretError {
#[error("SECRETS_ENCRYPTION_KEY is not set; refusing to store a credential in plain text")]
NoKey,
#[error("SECRETS_ENCRYPTION_KEY must be 64 hex characters (a 32-byte key)")]
MalformedKey,
#[error("a stored credential cannot be decrypted (wrong key or corrupted value)")]
Undecryptable,
#[error("sealing a credential failed")]
SealFailed,
}
/// Seals and opens stored credentials under the deployment's key.
#[derive(Clone)]
pub struct SecretBox {
cipher: Option<Aes256Gcm>,
}
impl fmt::Debug for SecretBox {
// Never print key material, only whether there is a key.
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("SecretBox")
.field("has_key", &self.cipher.is_some())
.finish()
}
}
impl SecretBox {
/// A box that can open legacy plain-text values but seals nothing.
pub fn without_key() -> Self {
Self { cipher: None }
}
/// Build the box from a hex-encoded 32-byte key.
///
/// # Errors
///
/// [`SecretError::MalformedKey`] unless `key_hex` is exactly 64 hex digits.
pub fn from_hex(key_hex: &str) -> Result<Self, SecretError> {
let key = hex::decode(key_hex.trim()).map_err(|_| SecretError::MalformedKey)?;
let cipher = Aes256Gcm::new_from_slice(&key).map_err(|_| SecretError::MalformedKey)?;
Ok(Self {
cipher: Some(cipher),
})
}
/// Check the format of `config.secrets_encryption_key`, so startup can
/// refuse a malformed key instead of running unable to store credentials.
///
/// # Errors
///
/// [`SecretError::MalformedKey`] if a key is set but malformed.
pub fn check_config(config: &AgentConfig) -> Result<(), SecretError> {
match &config.secrets_encryption_key {
Some(key) => Self::from_hex(key.expose_secret()).map(drop),
None => Ok(()),
}
}
/// The box for `config.secrets_encryption_key`. No key, or a malformed one
/// (which startup already refused, see [`Self::check_config`]), gives a
/// box that seals nothing, so storing a credential fails closed.
pub fn from_config(config: &AgentConfig) -> Self {
let Some(key) = &config.secrets_encryption_key else {
return Self::without_key();
};
Self::from_hex(key.expose_secret()).unwrap_or_else(|e| {
tracing::error!("{e}");
Self::without_key()
})
}
/// Whether `value` is already sealed.
pub fn is_sealed(value: &str) -> bool {
value.starts_with(SEALED_PREFIX)
}
/// Seal a credential for storage. Each call uses a fresh random nonce, so
/// sealing the same value twice gives different output.
///
/// # Errors
///
/// [`SecretError::NoKey`] when the deployment has no key.
pub fn seal(&self, plaintext: &str) -> Result<String, SecretError> {
let cipher = self.cipher.as_ref().ok_or(SecretError::NoKey)?;
let nonce = Aes256Gcm::generate_nonce(&mut OsRng);
// Only fails for inputs beyond AES-GCM's 64 GiB message limit.
let ciphertext = cipher
.encrypt(&nonce, plaintext.as_bytes())
.map_err(|_| SecretError::SealFailed)?;
let mut combined = Vec::with_capacity(NONCE_LEN + ciphertext.len());
combined.extend_from_slice(&nonce);
combined.extend_from_slice(&ciphertext);
Ok(format!(
"{SEALED_PREFIX}{}",
base64::engine::general_purpose::STANDARD.encode(combined)
))
}
/// Open a stored credential. A value without the sealed prefix predates
/// sealing and is returned as-is (the startup pass converts those).
///
/// # Errors
///
/// [`SecretError::NoKey`] for a sealed value when the deployment has no
/// key, [`SecretError::Undecryptable`] when the key is wrong or the value
/// is corrupted.
pub fn open(&self, stored: &str) -> Result<String, SecretError> {
let Some(encoded) = stored.strip_prefix(SEALED_PREFIX) else {
return Ok(stored.to_string());
};
let cipher = self.cipher.as_ref().ok_or(SecretError::NoKey)?;
let combined = base64::engine::general_purpose::STANDARD
.decode(encoded)
.map_err(|_| SecretError::Undecryptable)?;
if combined.len() < NONCE_LEN {
return Err(SecretError::Undecryptable);
}
let (nonce, ciphertext) = combined.split_at(NONCE_LEN);
let plaintext = cipher
.decrypt(Nonce::from_slice(nonce), ciphertext)
.map_err(|_| SecretError::Undecryptable)?;
String::from_utf8(plaintext).map_err(|_| SecretError::Undecryptable)
}
/// Open an optional stored credential for use. A credential that cannot be
/// opened is logged and treated as absent, so the caller goes on without
/// it (a clone fails with an auth error, a webhook is rejected) instead of
/// using a wrong value.
pub fn open_opt(&self, stored: Option<&String>, what: &str) -> Option<String> {
let stored = stored?;
match self.open(stored) {
Ok(plaintext) => Some(plaintext),
Err(e) => {
tracing::error!(credential = what, "{e}");
None
}
}
}
/// Store a credential sent in an update: sent and non-empty is sealed, sent
/// empty removes it, and not sent keeps the `stored` (already sealed)
/// value. The API never returns credentials, so a client echoing a record
/// back without them must not erase them.
///
/// # Errors
///
/// [`SecretError::NoKey`] when a new value arrives and there is no key.
pub fn take_update(
&self,
incoming: &mut Option<String>,
stored: Option<&String>,
) -> Result<(), SecretError> {
*incoming = match incoming.take() {
None => stored.cloned(),
Some(value) if value.is_empty() => None,
Some(value) => Some(self.seal(&value)?),
};
Ok(())
}
/// Open every credential of a record read back from storage, so it can be
/// used. One that cannot be opened is logged and removed (see
/// [`Self::open_opt`]).
pub fn open_in_place<T: Credentials>(&self, record: &mut T) {
for slot in record.credentials_mut() {
*slot = self.open_opt(slot.as_ref(), "stored record");
}
}
/// Seal every credential of `record` that is not sealed yet.
///
/// # Returns
///
/// Whether anything changed.
///
/// # Errors
///
/// [`SecretError::NoKey`] if there is a plain-text credential and no key.
pub fn seal_unsealed<T: Credentials>(&self, record: &mut T) -> Result<bool, SecretError> {
let mut changed = false;
for slot in record.credentials_mut() {
let sealed = match slot.as_deref() {
Some(value) if !Self::is_sealed(value) => self.seal(value)?,
_ => continue,
};
*slot = Some(sealed);
changed = true;
}
Ok(changed)
}
}
/// Seal credentials that were stored in plain text before sealing existed,
/// in every tenant. Runs once at startup; a no-op without a key (dev), where
/// the values keep working because [`SecretBox::open`] passes them through.
@@ -239,7 +30,7 @@ pub async fn seal_stored_credentials(
pool: &DatabasePool,
secrets: &SecretBox,
) -> Result<u64, AgentError> {
if secrets.cipher.is_none() {
if !secrets.has_key() {
return Ok(0);
}
let mut sealed = 0;
@@ -283,123 +74,3 @@ async fn seal_tenant_targets(db: &Database, secrets: &SecretBox) -> Result<u64,
}
Ok(sealed)
}
#[cfg(test)]
#[allow(clippy::expect_used, clippy::unwrap_used)]
mod tests {
use super::*;
const KEY: &str = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";
const OTHER_KEY: &str = "abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789";
fn keyed() -> SecretBox {
SecretBox::from_hex(KEY).unwrap()
}
#[test]
fn seal_then_open_round_trips_with_a_fresh_nonce() {
let secrets = keyed();
let first = secrets.seal("pat-123").unwrap();
let second = secrets.seal("pat-123").unwrap();
assert!(SecretBox::is_sealed(&first));
assert!(!first.contains("pat-123"));
assert_ne!(first, second);
assert_eq!(secrets.open(&first).unwrap(), "pat-123");
}
#[test]
fn sealing_without_a_key_fails_instead_of_storing_plain_text() {
assert_eq!(
SecretBox::without_key().seal("pat"),
Err(SecretError::NoKey)
);
}
#[test]
fn malformed_keys_are_refused() {
for key in ["", "not-hex", &KEY[..62], &format!("{KEY}00")] {
assert_eq!(
SecretBox::from_hex(key).err(),
Some(SecretError::MalformedKey),
"{key:?}"
);
}
}
#[test]
fn a_wrong_key_or_tampered_value_does_not_open() {
let sealed = keyed().seal("pat").unwrap();
let other = SecretBox::from_hex(OTHER_KEY).unwrap();
assert_eq!(other.open(&sealed), Err(SecretError::Undecryptable));
assert_eq!(
SecretBox::without_key().open(&sealed),
Err(SecretError::NoKey)
);
assert_eq!(
keyed().open("enc:v1:bm90LWEtcmVhbC12YWx1ZQ=="),
Err(SecretError::Undecryptable)
);
}
#[test]
fn legacy_plain_text_still_opens() {
assert_eq!(keyed().open("legacy-token").unwrap(), "legacy-token");
}
#[test]
fn open_opt_treats_an_unopenable_value_as_absent() {
let sealed = keyed().seal("pat").unwrap();
let other = SecretBox::from_hex(OTHER_KEY).unwrap();
assert_eq!(other.open_opt(Some(&sealed), "test"), None);
assert_eq!(
keyed().open_opt(Some(&sealed), "test").as_deref(),
Some("pat")
);
assert_eq!(keyed().open_opt(None, "test"), None);
}
#[test]
fn take_update_keeps_seals_or_clears() {
let secrets = keyed();
let stored = secrets.seal("old").unwrap();
let mut not_sent = None;
secrets.take_update(&mut not_sent, Some(&stored)).unwrap();
assert_eq!(not_sent.as_ref(), Some(&stored));
let mut cleared = Some(String::new());
secrets.take_update(&mut cleared, Some(&stored)).unwrap();
assert_eq!(cleared, None);
let mut replaced = Some("new".to_string());
secrets.take_update(&mut replaced, Some(&stored)).unwrap();
let replaced = replaced.expect("sealed");
assert!(SecretBox::is_sealed(&replaced));
assert_eq!(secrets.open(&replaced).unwrap(), "new");
}
#[test]
fn seal_unsealed_seals_only_plain_values() {
use compliance_core::models::{IssueTrackerConfig, TargetType};
let secrets = keyed();
let mut target = OnboardedTarget::new("t".into(), TargetType::WebApp);
target.webhook_secret = Some(secrets.seal("hook").unwrap());
target.scan_config.issue_tracker = Some(IssueTrackerConfig {
token: Some("plain-tracker".into()),
..Default::default()
});
let already = target.webhook_secret.clone();
assert!(secrets.seal_unsealed(&mut target).unwrap());
assert_eq!(target.webhook_secret, already);
let token = target
.scan_config
.issue_tracker
.as_ref()
.and_then(|t| t.token.clone())
.expect("token");
assert_eq!(secrets.open(&token).unwrap(), "plain-tracker");
assert!(!secrets.seal_unsealed(&mut target).unwrap());
}
}
+9
View File
@@ -20,6 +20,13 @@ telemetry = [
]
# Pulls in the M7.1 Axum middleware + extractor. Consumers that don't
# embed an HTTP server (e.g. the wasm dashboard frontend) leave it off.
# Sealing stored credentials (`secret_box`): the agent's tenant credentials and
# the dashboard's session records.
secrets = [
"dep:aes-gcm",
"dep:base64",
"dep:tracing",
]
axum = [
"dep:axum",
"dep:jsonwebtoken",
@@ -50,6 +57,8 @@ axum = { version = "0.8", optional = true }
jsonwebtoken = { version = "9", optional = true }
reqwest = { workspace = true, optional = true }
tokio = { workspace = true, optional = true }
aes-gcm = { workspace = true, optional = true }
base64 = { workspace = true, optional = true }
[dev-dependencies]
# Parse the declarative TOML job specs in the Werkbank contract tests.
+2
View File
@@ -13,6 +13,8 @@ pub mod traits;
#[cfg(feature = "axum")]
pub mod auth;
#[cfg(feature = "secrets")]
pub mod secret_box;
#[cfg(feature = "axum")]
pub mod shutdown;
#[cfg(feature = "axum")]
+352
View File
@@ -0,0 +1,352 @@
//! Sealing stored credentials (#260).
//!
//! AES-256-GCM with a fresh random nonce per value. A sealed value reads
//! `enc:v1:<base64 of nonce + ciphertext>`; the prefix tells it apart from a
//! value stored before sealing existed. Without a key nothing can be sealed,
//! so a caller fails instead of storing plain text.
//!
//! The agent seals tenant credentials with `SECRETS_ENCRYPTION_KEY`; the
//! dashboard seals its session records with its session key.
use std::fmt;
use aes_gcm::aead::{Aead, AeadCore, KeyInit, OsRng};
use aes_gcm::{Aes256Gcm, Nonce};
use base64::Engine;
use secrecy::ExposeSecret;
use crate::config::AgentConfig;
use crate::models::Credentials;
/// Marks a sealed value and its format version.
const SEALED_PREFIX: &str = "enc:v1:";
/// AES-GCM nonce length in bytes.
const NONCE_LEN: usize = 12;
/// Why a credential could not be sealed or opened.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum SecretError {
#[error("SECRETS_ENCRYPTION_KEY is not set; refusing to store a credential in plain text")]
NoKey,
#[error("SECRETS_ENCRYPTION_KEY must be 64 hex characters (a 32-byte key)")]
MalformedKey,
#[error("a stored credential cannot be decrypted (wrong key or corrupted value)")]
Undecryptable,
#[error("sealing a credential failed")]
SealFailed,
}
/// Seals and opens stored credentials under the deployment's key.
#[derive(Clone)]
pub struct SecretBox {
cipher: Option<Aes256Gcm>,
}
impl fmt::Debug for SecretBox {
// Never print key material, only whether there is a key.
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("SecretBox")
.field("has_key", &self.cipher.is_some())
.finish()
}
}
impl SecretBox {
/// A box that can open legacy plain-text values but seals nothing.
pub fn without_key() -> Self {
Self { cipher: None }
}
/// Build the box from a raw 32-byte key.
///
/// # Errors
///
/// [`SecretError::MalformedKey`] unless `key` is exactly 32 bytes.
pub fn from_key(key: &[u8]) -> Result<Self, SecretError> {
let cipher = Aes256Gcm::new_from_slice(key).map_err(|_| SecretError::MalformedKey)?;
Ok(Self {
cipher: Some(cipher),
})
}
/// Build the box from a hex-encoded 32-byte key.
///
/// # Errors
///
/// [`SecretError::MalformedKey`] unless `key_hex` is exactly 64 hex digits.
pub fn from_hex(key_hex: &str) -> Result<Self, SecretError> {
let key = hex::decode(key_hex.trim()).map_err(|_| SecretError::MalformedKey)?;
Self::from_key(&key)
}
/// Check the format of `config.secrets_encryption_key`, so startup can
/// refuse a malformed key instead of running unable to store credentials.
///
/// # Errors
///
/// [`SecretError::MalformedKey`] if a key is set but malformed.
pub fn check_config(config: &AgentConfig) -> Result<(), SecretError> {
match &config.secrets_encryption_key {
Some(key) => Self::from_hex(key.expose_secret()).map(drop),
None => Ok(()),
}
}
/// The box for `config.secrets_encryption_key`. No key, or a malformed one
/// (which startup already refused, see [`Self::check_config`]), gives a
/// box that seals nothing, so storing a credential fails closed.
pub fn from_config(config: &AgentConfig) -> Self {
let Some(key) = &config.secrets_encryption_key else {
return Self::without_key();
};
Self::from_hex(key.expose_secret()).unwrap_or_else(|e| {
tracing::error!("{e}");
Self::without_key()
})
}
/// Whether this box can seal (a key is configured).
pub fn has_key(&self) -> bool {
self.cipher.is_some()
}
/// Whether `value` is already sealed.
pub fn is_sealed(value: &str) -> bool {
value.starts_with(SEALED_PREFIX)
}
/// Seal a credential for storage. Each call uses a fresh random nonce, so
/// sealing the same value twice gives different output.
///
/// # Errors
///
/// [`SecretError::NoKey`] when the deployment has no key.
pub fn seal(&self, plaintext: &str) -> Result<String, SecretError> {
let cipher = self.cipher.as_ref().ok_or(SecretError::NoKey)?;
let nonce = Aes256Gcm::generate_nonce(&mut OsRng);
// Only fails for inputs beyond AES-GCM's 64 GiB message limit.
let ciphertext = cipher
.encrypt(&nonce, plaintext.as_bytes())
.map_err(|_| SecretError::SealFailed)?;
let mut combined = Vec::with_capacity(NONCE_LEN + ciphertext.len());
combined.extend_from_slice(&nonce);
combined.extend_from_slice(&ciphertext);
Ok(format!(
"{SEALED_PREFIX}{}",
base64::engine::general_purpose::STANDARD.encode(combined)
))
}
/// Open a stored credential. A value without the sealed prefix predates
/// sealing and is returned as-is (the startup pass converts those).
///
/// # Errors
///
/// [`SecretError::NoKey`] for a sealed value when the deployment has no
/// key, [`SecretError::Undecryptable`] when the key is wrong or the value
/// is corrupted.
pub fn open(&self, stored: &str) -> Result<String, SecretError> {
let Some(encoded) = stored.strip_prefix(SEALED_PREFIX) else {
return Ok(stored.to_string());
};
let cipher = self.cipher.as_ref().ok_or(SecretError::NoKey)?;
let combined = base64::engine::general_purpose::STANDARD
.decode(encoded)
.map_err(|_| SecretError::Undecryptable)?;
if combined.len() < NONCE_LEN {
return Err(SecretError::Undecryptable);
}
let (nonce, ciphertext) = combined.split_at(NONCE_LEN);
let plaintext = cipher
.decrypt(Nonce::from_slice(nonce), ciphertext)
.map_err(|_| SecretError::Undecryptable)?;
String::from_utf8(plaintext).map_err(|_| SecretError::Undecryptable)
}
/// Open an optional stored credential for use. A credential that cannot be
/// opened is logged and treated as absent, so the caller goes on without
/// it (a clone fails with an auth error, a webhook is rejected) instead of
/// using a wrong value.
pub fn open_opt(&self, stored: Option<&String>, what: &str) -> Option<String> {
let stored = stored?;
match self.open(stored) {
Ok(plaintext) => Some(plaintext),
Err(e) => {
tracing::error!(credential = what, "{e}");
None
}
}
}
/// Store a credential sent in an update: sent and non-empty is sealed, sent
/// empty removes it, and not sent keeps the `stored` (already sealed)
/// value. The API never returns credentials, so a client echoing a record
/// back without them must not erase them.
///
/// # Errors
///
/// [`SecretError::NoKey`] when a new value arrives and there is no key.
pub fn take_update(
&self,
incoming: &mut Option<String>,
stored: Option<&String>,
) -> Result<(), SecretError> {
*incoming = match incoming.take() {
None => stored.cloned(),
Some(value) if value.is_empty() => None,
Some(value) => Some(self.seal(&value)?),
};
Ok(())
}
/// Open every credential of a record read back from storage, so it can be
/// used. One that cannot be opened is logged and removed (see
/// [`Self::open_opt`]).
pub fn open_in_place<T: Credentials>(&self, record: &mut T) {
for slot in record.credentials_mut() {
*slot = self.open_opt(slot.as_ref(), "stored record");
}
}
/// Seal every credential of `record` that is not sealed yet.
///
/// # Returns
///
/// Whether anything changed.
///
/// # Errors
///
/// [`SecretError::NoKey`] if there is a plain-text credential and no key.
pub fn seal_unsealed<T: Credentials>(&self, record: &mut T) -> Result<bool, SecretError> {
let mut changed = false;
for slot in record.credentials_mut() {
let sealed = match slot.as_deref() {
Some(value) if !Self::is_sealed(value) => self.seal(value)?,
_ => continue,
};
*slot = Some(sealed);
changed = true;
}
Ok(changed)
}
}
#[cfg(test)]
#[allow(clippy::expect_used, clippy::unwrap_used)]
mod tests {
use super::*;
const KEY: &str = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";
const OTHER_KEY: &str = "abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789";
fn keyed() -> SecretBox {
SecretBox::from_hex(KEY).unwrap()
}
#[test]
fn seal_then_open_round_trips_with_a_fresh_nonce() {
let secrets = keyed();
let first = secrets.seal("pat-123").unwrap();
let second = secrets.seal("pat-123").unwrap();
assert!(SecretBox::is_sealed(&first));
assert!(!first.contains("pat-123"));
assert_ne!(first, second);
assert_eq!(secrets.open(&first).unwrap(), "pat-123");
}
#[test]
fn sealing_without_a_key_fails_instead_of_storing_plain_text() {
assert_eq!(
SecretBox::without_key().seal("pat"),
Err(SecretError::NoKey)
);
}
#[test]
fn malformed_keys_are_refused() {
for key in ["", "not-hex", &KEY[..62], &format!("{KEY}00")] {
assert_eq!(
SecretBox::from_hex(key).err(),
Some(SecretError::MalformedKey),
"{key:?}"
);
}
}
#[test]
fn a_wrong_key_or_tampered_value_does_not_open() {
let sealed = keyed().seal("pat").unwrap();
let other = SecretBox::from_hex(OTHER_KEY).unwrap();
assert_eq!(other.open(&sealed), Err(SecretError::Undecryptable));
assert_eq!(
SecretBox::without_key().open(&sealed),
Err(SecretError::NoKey)
);
assert_eq!(
keyed().open("enc:v1:bm90LWEtcmVhbC12YWx1ZQ=="),
Err(SecretError::Undecryptable)
);
}
#[test]
fn legacy_plain_text_still_opens() {
assert_eq!(keyed().open("legacy-token").unwrap(), "legacy-token");
}
#[test]
fn open_opt_treats_an_unopenable_value_as_absent() {
let sealed = keyed().seal("pat").unwrap();
let other = SecretBox::from_hex(OTHER_KEY).unwrap();
assert_eq!(other.open_opt(Some(&sealed), "test"), None);
assert_eq!(
keyed().open_opt(Some(&sealed), "test").as_deref(),
Some("pat")
);
assert_eq!(keyed().open_opt(None, "test"), None);
}
#[test]
fn take_update_keeps_seals_or_clears() {
let secrets = keyed();
let stored = secrets.seal("old").unwrap();
let mut not_sent = None;
secrets.take_update(&mut not_sent, Some(&stored)).unwrap();
assert_eq!(not_sent.as_ref(), Some(&stored));
let mut cleared = Some(String::new());
secrets.take_update(&mut cleared, Some(&stored)).unwrap();
assert_eq!(cleared, None);
let mut replaced = Some("new".to_string());
secrets.take_update(&mut replaced, Some(&stored)).unwrap();
let replaced = replaced.expect("sealed");
assert!(SecretBox::is_sealed(&replaced));
assert_eq!(secrets.open(&replaced).unwrap(), "new");
}
#[test]
fn seal_unsealed_seals_only_plain_values() {
use crate::models::{IssueTrackerConfig, OnboardedTarget, TargetType};
let secrets = keyed();
let mut target = OnboardedTarget::new("t".into(), TargetType::WebApp);
target.webhook_secret = Some(secrets.seal("hook").unwrap());
target.scan_config.issue_tracker = Some(IssueTrackerConfig {
token: Some("plain-tracker".into()),
..Default::default()
});
let already = target.webhook_secret.clone();
assert!(secrets.seal_unsealed(&mut target).unwrap());
assert_eq!(target.webhook_secret, already);
let token = target
.scan_config
.issue_tracker
.as_ref()
.and_then(|t| t.token.clone())
.expect("token");
assert_eq!(secrets.open(&token).unwrap(), "plain-tracker");
assert!(!secrets.seal_unsealed(&mut target).unwrap());
}
}