Files
pruefwerk/compliance-agent/src/secrets.rs
T
sharang 6611c5b691
CI / Check (push) Skipped
CI / Detect Changes (push) Successful in 4s
CI / Deploy Docs (push) Successful in 1m8s
CI / Deploy MCP (push) Successful in 3m52s
CI / Deploy Dashboard (push) Successful in 5m38s
CI / Deploy Agent (push) Successful in 7m6s
feat(security): seal tenant credentials at rest, never return them (#260) (#302)
2026-09-21 16:28:54 +00:00

77 lines
2.7 KiB
Rust

//! Tenant credentials at rest (#260).
//!
//! Git tokens, tracker tokens, webhook secrets and pentest passwords are sealed
//! 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 futures_util::TryStreamExt;
use mongodb::bson::{doc, to_bson, Document};
use compliance_core::models::OnboardedTarget;
pub use compliance_core::secret_box::{SecretBox, SecretError};
use crate::database::{Database, DatabasePool};
use crate::error::AgentError;
/// 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.
///
/// # Returns
///
/// How many targets were rewritten.
///
/// # Errors
///
/// Returns an error if the tenant databases cannot be listed. A tenant whose
/// targets cannot be read or written is logged and skipped.
pub async fn seal_stored_credentials(
pool: &DatabasePool,
secrets: &SecretBox,
) -> Result<u64, AgentError> {
if !secrets.has_key() {
return Ok(0);
}
let mut sealed = 0;
for db in pool.existing_tenant_dbs().await? {
match seal_tenant_targets(&db, secrets).await {
Ok(count) => sealed += count,
Err(e) => tracing::error!(
database = db.inner().name(),
"sealing stored credentials failed: {e}"
),
}
}
Ok(sealed)
}
/// The `$set` that writes back every part of a target holding credentials.
fn credential_fields(target: &OnboardedTarget) -> Result<Document, AgentError> {
let bson = |e: mongodb::bson::ser::Error| AgentError::Other(e.to_string());
Ok(doc! { "$set": {
"webhook_secret": to_bson(&target.webhook_secret).map_err(bson)?,
"artifacts": to_bson(&target.artifacts).map_err(bson)?,
"scan_config": to_bson(&target.scan_config).map_err(bson)?,
} })
}
/// Seal the plain-text credentials of one tenant's targets.
async fn seal_tenant_targets(db: &Database, secrets: &SecretBox) -> Result<u64, AgentError> {
// Streamed, so a tenant with many targets never sits in memory at once. A
// rewritten target that the cursor meets again is already sealed.
let mut cursor = db.onboarded_targets().find(doc! {}).await?;
let mut sealed = 0;
while let Some(mut target) = cursor.try_next().await? {
let Some(id) = target.id else { continue };
if !secrets.seal_unsealed(&mut target)? {
continue;
}
db.onboarded_targets()
.update_one(doc! { "_id": id }, credential_fields(&target)?)
.await?;
sealed += 1;
}
Ok(sealed)
}