From b89f31e2d3a848929314bc36e81daeb2a592ee61 Mon Sep 17 00:00:00 2001 From: Sharang Parnerkar <30073382+mighty840@users.noreply.github.com> Date: Mon, 21 Sep 2026 18:03:00 +0200 Subject: [PATCH] feat(security): seal tenant credentials at rest, never return them (#260) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Git tokens, tracker tokens, webhook secrets and pentest passwords were stored in plain text and returned by the API. The old crypto helper fell back to plain text when no key was set. - `secrets::SecretBox`: AES-256-GCM under `SECRETS_ENCRYPTION_KEY`, with sealed values stored as `enc:v1:…`. With no key it refuses to seal instead of storing plain text. The key is required when APP_ENV is hardened, and a malformed key stops startup in every environment. It replaces `pentest/crypto.rs`. - `compliance_core::models::Credentials` lists each record's credential fields once. The agent seals them before a write and redacts them from every target, DAST target and pentest-session response, including the MCP pentest tools. - `PATCH /targets/{id}`: a credential left out keeps its stored value, an empty string clears it, and a new one is sealed. A client echoing a redacted record back therefore cannot erase a token. - Pentest sessions are sealed before the first insert. Previously they were inserted in plain text and encrypted afterwards. - On startup the agent seals credentials that were stored in plain text. - Webhook receivers fail closed: a target without a usable secret gets 401 instead of unsigned acceptance. GitLab tokens are compared in constant time. New targets no longer get a webhook secret at creation; issuing one comes back with the webhook work. Part 1 of #260 (agent). Dashboard session hardening, the open redirect and the webhook proxy follow in a separate PR. Co-Authored-By: Claude Opus 5 (1M context) Claude-Session: https://claude.ai/code/session_01EYKjxacrr6K88DruUmP48p --- .env.example | 7 +- Cargo.lock | 1 + compliance-agent/Cargo.toml | 2 + compliance-agent/src/agent.rs | 8 +- compliance-agent/src/api/handlers/chat.rs | 3 +- compliance-agent/src/api/handlers/dast.rs | 5 +- compliance-agent/src/api/handlers/graph.rs | 3 +- .../src/api/handlers/onboarding.rs | 53 ++- .../api/handlers/pentest_handlers/session.rs | 71 +-- compliance-agent/src/config.rs | 5 + compliance-agent/src/error.rs | 3 + compliance-agent/src/ingest/mod.rs | 15 +- compliance-agent/src/lib.rs | 1 + compliance-agent/src/main.rs | 12 +- compliance-agent/src/pentest/crypto.rs | 117 ----- compliance-agent/src/pentest/mod.rs | 1 - .../src/pentest/prompt_builder.rs | 13 +- compliance-agent/src/pipeline/orchestrator.rs | 9 +- compliance-agent/src/pipeline/repo_view.rs | 15 +- compliance-agent/src/secrets.rs | 405 ++++++++++++++++++ compliance-agent/src/webhooks/gitea.rs | 24 +- compliance-agent/src/webhooks/github.rs | 24 +- compliance-agent/src/webhooks/gitlab.rs | 26 +- compliance-agent/src/webhooks/mod.rs | 13 + compliance-agent/tests/common/mod.rs | 5 + compliance-agent/tests/credentials.rs | 296 +++++++++++++ compliance-core/src/config.rs | 12 + compliance-core/src/models/credentials.rs | 243 +++++++++++ compliance-core/src/models/mod.rs | 2 + compliance-core/src/models/onboarding.rs | 17 +- compliance-mcp/src/tools/pentest.rs | 9 +- docs/guide/repositories.md | 1 - docs/guide/scanning.md | 2 +- docs/guide/webhooks.md | 15 +- 34 files changed, 1176 insertions(+), 262 deletions(-) delete mode 100644 compliance-agent/src/pentest/crypto.rs create mode 100644 compliance-agent/src/secrets.rs create mode 100644 compliance-agent/tests/credentials.rs create mode 100644 compliance-core/src/models/credentials.rs diff --git a/.env.example b/.env.example index 9c364d2..0f69a9d 100644 --- a/.env.example +++ b/.env.example @@ -66,8 +66,13 @@ WERKBANK_RUNNER_TOKEN= # unauthenticated as the `dev` tenant. Required in staging/production: # KEYCLOAK_URL, KEYCLOAK_REALM, KEYCLOAK_AUDIENCE, CORS_ALLOWED_ORIGINS, # TENANT_REGISTRY_URL, TENANT_REGISTRY_CLIENT_ID/_SECRET, -# PLATFORM_ALLOWED_CLIENTS (+ MCP_PORT for compliance-mcp). +# PLATFORM_ALLOWED_CLIENTS, SECRETS_ENCRYPTION_KEY (+ MCP_PORT for compliance-mcp). APP_ENV=dev +# 64 hex characters (32 bytes) that seal tenant credentials (git and tracker +# tokens, webhook secrets) at rest. Generate with `openssl rand -hex 32`. Without +# it the agent refuses to store a credential. Changing it makes every stored +# credential unreadable, so keep it with the database backups. +SECRETS_ENCRYPTION_KEY= # Catalog key this deployment serves; used for entitlement checks, usage # events and the platform handshake. PRODUCT_KEY=pruefwerk diff --git a/Cargo.lock b/Cargo.lock index 66f1c23..8221b70 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -688,6 +688,7 @@ dependencies = [ "serde", "serde_json", "sha2", + "subtle", "thiserror 2.0.18", "tokio", "tokio-cron-scheduler", diff --git a/compliance-agent/Cargo.toml b/compliance-agent/Cargo.toml index b4eed07..033c9a8 100644 --- a/compliance-agent/Cargo.toml +++ b/compliance-agent/Cargo.toml @@ -47,6 +47,8 @@ octocrab = "0.44" tokio-cron-scheduler = "0.13" dotenvy = "0.15" hmac = "0.12" +# Constant-time comparison of the GitLab webhook token. +subtle = "2.6" walkdir = "2" # Read-only XML tree parsing for PLCopen project files (POU extraction). roxmltree = "0.20" diff --git a/compliance-agent/src/agent.rs b/compliance-agent/src/agent.rs index 3482c6d..68356b4 100644 --- a/compliance-agent/src/agent.rs +++ b/compliance-agent/src/agent.rs @@ -11,6 +11,7 @@ use crate::llm::LlmClient; use crate::pipeline::orchestrator::PipelineOrchestrator; use crate::registry::RegistryClient; use crate::scan_gate::{Admission, HeldTarget, ScanGate}; +use crate::secrets::SecretBox; /// Default maximum concurrent pentest sessions. const DEFAULT_MAX_CONCURRENT_SESSIONS: usize = 5; @@ -38,6 +39,9 @@ pub struct ComplianceAgent { pub net_guard: NetGuard, /// Global scan slots and per-target coalescing (#258). pub scan_gate: Arc, + /// Seals tenant credentials before they are stored and opens them where + /// they are used (#260). + pub secrets: SecretBox, } impl ComplianceAgent { @@ -56,6 +60,7 @@ impl ComplianceAgent { let registry = RegistryClient::from_config(&config, http.clone()); let net_guard = NetGuard::from_env(config.app_env); let scan_gate = Arc::new(ScanGate::new(config.scan_concurrency)); + let secrets = SecretBox::from_config(&config); Self { config, db_pool, @@ -67,6 +72,7 @@ impl ComplianceAgent { registry, net_guard, scan_gate, + secrets, } } @@ -223,7 +229,7 @@ impl ComplianceAgent { let code = target.code_artifact().ok_or_else(|| { crate::error::AgentError::Other(format!("Target {repo_id} has no code artifact")) })?; - let repo = crate::pipeline::repo_view::RepoView::from_target(&target, code); + let repo = crate::pipeline::repo_view::RepoView::from_target(&target, code, &self.secrets); let orchestrator = PipelineOrchestrator::new( self.config.clone(), diff --git a/compliance-agent/src/api/handlers/chat.rs b/compliance-agent/src/api/handlers/chat.rs index 9500b49..a7764f0 100644 --- a/compliance-agent/src/api/handlers/chat.rs +++ b/compliance-agent/src/api/handlers/chat.rs @@ -204,7 +204,8 @@ pub async fn build_embeddings( return; } }; - let view = crate::pipeline::repo_view::RepoView::from_target(&repo, code); + let view = + crate::pipeline::repo_view::RepoView::from_target(&repo, code, &agent_clone.secrets); let creds = crate::pipeline::git::GitOps::make_repo_credentials(&view); let git_ops = crate::pipeline::git::GitOps::new( &agent_clone.config.git_clone_base_path, diff --git a/compliance-agent/src/api/handlers/dast.rs b/compliance-agent/src/api/handlers/dast.rs index 73ffbc8..7d93896 100644 --- a/compliance-agent/src/api/handlers/dast.rs +++ b/compliance-agent/src/api/handlers/dast.rs @@ -7,6 +7,7 @@ use mongodb::bson::doc; use serde::Deserialize; use compliance_core::models::dast::{DastFinding, DastScanRun, DastTarget, DastTargetType}; +use compliance_core::models::Credentials; use compliance_core::tenant_ctx::TenantCtx; use crate::agent::ComplianceAgent; @@ -74,7 +75,7 @@ pub async fn list_targets( }; Ok(Json(ApiResponse { - data: targets, + data: targets.redacted(), total: Some(total), page: Some(params.page), })) @@ -119,7 +120,7 @@ pub async fn add_target( ); Ok(Json(ApiResponse { - data: target, + data: target.redacted(), total: None, page: None, })) diff --git a/compliance-agent/src/api/handlers/graph.rs b/compliance-agent/src/api/handlers/graph.rs index dcf68f7..82f7718 100644 --- a/compliance-agent/src/api/handlers/graph.rs +++ b/compliance-agent/src/api/handlers/graph.rs @@ -412,7 +412,8 @@ pub async fn trigger_build( return; } }; - let view = crate::pipeline::repo_view::RepoView::from_target(&repo, code); + let view = + crate::pipeline::repo_view::RepoView::from_target(&repo, code, &agent_clone.secrets); let creds = crate::pipeline::git::GitOps::make_repo_credentials(&view); let git_ops = crate::pipeline::git::GitOps::new( &agent_clone.config.git_clone_base_path, diff --git a/compliance-agent/src/api/handlers/onboarding.rs b/compliance-agent/src/api/handlers/onboarding.rs index ba7791d..0ad4696 100644 --- a/compliance-agent/src/api/handlers/onboarding.rs +++ b/compliance-agent/src/api/handlers/onboarding.rs @@ -12,14 +12,15 @@ use mongodb::bson::{doc, oid::ObjectId, to_bson}; use serde::{Deserialize, Serialize}; use compliance_core::models::{ - Artifact, ArtifactKind, ComplianceProfile, OnboardedTarget, PlcFormat, TargetScanConfig, - TargetType, + Artifact, ArtifactKind, ComplianceProfile, Credentials, OnboardedTarget, PlcFormat, + TargetScanConfig, TargetType, }; use compliance_core::scan_matrix::{applicable_scans, supports_pentest}; use compliance_core::tenant_ctx::TenantCtx; use crate::agent::ComplianceAgent; use crate::classify::{classify_target, MockFirmwareDetector}; +use crate::secrets::{SecretBox, SecretError}; use crate::targets::{upload_dest, uploaded_artifact, MAX_UPLOAD_BYTES}; use super::dto::tenant_db; @@ -88,6 +89,32 @@ pub struct ApplicableScansResponse { pub pentest_supported: bool, } +/// Seal the credentials of a scan config sent in an update. The API never +/// returns credentials, so one left out keeps the stored value (see +/// [`SecretBox::take_update`]). +fn seal_scan_config_credentials( + secrets: &SecretBox, + incoming: &mut TargetScanConfig, + stored: &TargetScanConfig, +) -> Result<(), SecretError> { + if let Some(tracker) = incoming.issue_tracker.as_mut() { + let kept = stored.issue_tracker.as_ref().and_then(|t| t.token.as_ref()); + secrets.take_update(&mut tracker.token, kept)?; + } + if let Some(pentest) = incoming.pentest.as_mut() { + let kept = stored.pentest.as_ref().map(|p| &p.auth); + secrets.take_update( + &mut pentest.auth.password, + kept.and_then(|a| a.password.as_ref()), + )?; + secrets.take_update( + &mut pentest.auth.imap_password, + kept.and_then(|a| a.imap_password.as_ref()), + )?; + } + Ok(()) +} + fn parse_oid(id: &str) -> Result { ObjectId::parse_str(id).map_err(|_| StatusCode::BAD_REQUEST) } @@ -120,7 +147,7 @@ pub async fn list_targets( } }; Ok(Json(ApiResponse { - data: targets, + data: targets.redacted(), total: Some(total), page: Some(params.page), })) @@ -152,7 +179,7 @@ pub async fn create_target( serde_json::json!({ "target_id": target_id, "target_type": format!("{:?}", target.target_type) }), ); Ok(Json(ApiResponse { - data: target, + data: target.redacted(), total: None, page: None, })) @@ -174,7 +201,7 @@ pub async fn get_target( .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)? .ok_or(StatusCode::NOT_FOUND)?; Ok(Json(ApiResponse { - data: target, + data: target.redacted(), total: None, page: None, })) @@ -201,7 +228,19 @@ pub async fn update_target( to_bson(&tt).map_err(|_| StatusCode::BAD_REQUEST)?, ); } - if let Some(sc) = req.scan_config { + if let Some(mut sc) = req.scan_config { + let stored = db + .onboarded_targets() + .find_one(doc! { "_id": oid }) + .await + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)? + .ok_or(StatusCode::NOT_FOUND)?; + seal_scan_config_credentials(&agent.secrets, &mut sc, &stored.scan_config).map_err( + |e| { + tracing::error!("storing a credential: {e}"); + StatusCode::SERVICE_UNAVAILABLE + }, + )?; set.insert( "scan_config", to_bson(&sc).map_err(|_| StatusCode::BAD_REQUEST)?, @@ -608,7 +647,7 @@ pub async fn detect_target( target.classification = Some(classification); Ok(Json(ApiResponse { - data: target, + data: target.redacted(), total: None, page: None, })) diff --git a/compliance-agent/src/api/handlers/pentest_handlers/session.rs b/compliance-agent/src/api/handlers/pentest_handlers/session.rs index 5b543db..6796541 100644 --- a/compliance-agent/src/api/handlers/pentest_handlers/session.rs +++ b/compliance-agent/src/api/handlers/pentest_handlers/session.rs @@ -7,6 +7,7 @@ use mongodb::bson::doc; use serde::Deserialize; use compliance_core::models::pentest::*; +use compliance_core::models::Credentials; use compliance_core::tenant_ctx::TenantCtx; use crate::agent::ComplianceAgent; @@ -138,9 +139,15 @@ pub async fn create_session( } } + // Stored sealed; the orchestrator below works on the in-memory copy. + let mut stored = session.clone(); + agent + .secrets + .seal_unsealed(&mut stored) + .map_err(|e| (StatusCode::SERVICE_UNAVAILABLE, e.to_string()))?; let insert_result = db .pentest_sessions() - .insert_one(&session) + .insert_one(&stored) .await .map_err(|e| { ( @@ -211,43 +218,6 @@ pub async fn create_session( } } - // Encrypt credentials before they linger in memory - let mut session_for_task = session.clone(); - if let Some(ref mut cfg) = session_for_task.config { - cfg.auth.username = cfg - .auth - .username - .as_ref() - .map(|u| crate::pentest::crypto::encrypt(u)); - cfg.auth.password = cfg - .auth - .password - .as_ref() - .map(|p| crate::pentest::crypto::encrypt(p)); - } - - // Persist encrypted credentials to DB - if session_for_task.config.is_some() { - if let Some(sid) = session.id { - let _ = db - .pentest_sessions() - .update_one( - doc! { "_id": sid }, - doc! { "$set": { - "config.auth.username": session_for_task.config.as_ref() - .and_then(|c| c.auth.username.as_deref()) - .map(|s| mongodb::bson::Bson::String(s.to_string())) - .unwrap_or(mongodb::bson::Bson::Null), - "config.auth.password": session_for_task.config.as_ref() - .and_then(|c| c.auth.password.as_deref()) - .map(|s| mongodb::bson::Bson::String(s.to_string())) - .unwrap_or(mongodb::bson::Bson::Null), - }}, - ) - .await; - } - } - let initial_message = config .initial_instructions .clone() @@ -277,19 +247,8 @@ pub async fn create_session( drop(permit); }); - // Redact credentials in response - let mut response_session = session; - if let Some(ref mut cfg) = response_session.config { - if cfg.auth.username.is_some() { - cfg.auth.username = Some("********".to_string()); - } - if cfg.auth.password.is_some() { - cfg.auth.password = Some("********".to_string()); - } - } - Ok(Json(ApiResponse { - data: response_session, + data: session.redacted(), total: None, page: None, })) @@ -368,7 +327,7 @@ pub async fn create_session( }); Ok(Json(ApiResponse { - data: session, + data: session.redacted(), total: None, page: None, })) @@ -450,7 +409,7 @@ pub async fn list_sessions( }; Ok(Json(ApiResponse { - data: sessions, + data: sessions.redacted(), total: Some(total), page: Some(params.page), })) @@ -484,7 +443,7 @@ pub async fn get_session( } Ok(Json(ApiResponse { - data: session, + data: session.redacted(), total: None, page: None, })) @@ -505,7 +464,7 @@ pub async fn send_message( .map_err(|s| (s, "failed to acquire tenant database".to_string()))?; // Verify session exists and is running - let session = db + let mut session = db .pentest_sessions() .find_one(doc! { "_id": oid }) .await @@ -523,6 +482,8 @@ pub async fn send_message( format!("Session is {}, cannot send messages", session.status), )); } + // The orchestrator puts the test account's credentials into the prompt. + agent.secrets.open_in_place(&mut session); // Look up the target let target_oid = mongodb::bson::oid::ObjectId::parse_str(&session.target_id).map_err(|_| { @@ -656,7 +617,7 @@ pub async fn stop_session( })?; Ok(Json(ApiResponse { - data: updated, + data: updated.redacted(), total: None, page: None, })) diff --git a/compliance-agent/src/config.rs b/compliance-agent/src/config.rs index 9eecde9..45c8d6f 100644 --- a/compliance-agent/src/config.rs +++ b/compliance-agent/src/config.rs @@ -20,6 +20,10 @@ pub fn load_config() -> Result { let app_env = AppEnv::parse(&env_var_opt("APP_ENV").unwrap_or_default()).map_err(AgentError::Config)?; let config = build_config(app_env)?; + // A malformed key would leave every credential unstorable, so refuse to + // start in every environment, not only hardened ones. + crate::secrets::SecretBox::check_config(&config) + .map_err(|e| AgentError::Config(e.to_string()))?; if let Err(problems) = config.validate_deployment() { return Err(AgentError::Config(format!( "refusing to start in {}:\n - {}", @@ -82,6 +86,7 @@ fn build_config(app_env: AppEnv) -> Result { pentest_imap_username: env_var_opt("PENTEST_IMAP_USERNAME"), pentest_imap_password: env_secret_opt("PENTEST_IMAP_PASSWORD"), admin_api_token: env_secret_opt("ADMIN_API_TOKEN"), + secrets_encryption_key: env_secret_opt("SECRETS_ENCRYPTION_KEY"), tenant_registry_url: env_var_opt("TENANT_REGISTRY_URL"), plc_runtime: load_plc_runtime_config(), werkbank_runner_token: env_secret_opt("WERKBANK_RUNNER_TOKEN"), diff --git a/compliance-agent/src/error.rs b/compliance-agent/src/error.rs index 41a5df7..a1915d9 100644 --- a/compliance-agent/src/error.rs +++ b/compliance-agent/src/error.rs @@ -27,6 +27,9 @@ pub enum AgentError { #[error("Configuration error: {0}")] Config(String), + #[error(transparent)] + Secret(#[from] crate::secrets::SecretError), + #[error("Dynamic-execution error: {0}")] Exec(#[from] werkbank_exec::ExecError), diff --git a/compliance-agent/src/ingest/mod.rs b/compliance-agent/src/ingest/mod.rs index 53a6b66..6129327 100644 --- a/compliance-agent/src/ingest/mod.rs +++ b/compliance-agent/src/ingest/mod.rs @@ -16,6 +16,7 @@ use compliance_core::{AgentConfig, NetGuard}; use crate::error::AgentError; use crate::pipeline::git::{GitOps, RepoCredentials}; +use crate::secrets::SecretBox; /// The paths and identifiers an ingest needs. Decoupled from the full /// [`AgentConfig`] so ingest is testable without a complete config. @@ -31,6 +32,8 @@ pub struct IngestContext<'a> { pub target_id: &'a str, /// Where this deployment may fetch from (SSRF policy, #256). pub net_guard: NetGuard, + /// Opens the artifacts' sealed credentials (#260). + pub secrets: SecretBox, } impl<'a> IngestContext<'a> { @@ -42,6 +45,7 @@ impl<'a> IngestContext<'a> { tenant_id, target_id, net_guard: NetGuard::from_env(config.app_env), + secrets: SecretBox::from_config(config), } } } @@ -145,7 +149,7 @@ fn ingest_git( ctx.net_guard .check_git_url(&artifact.source_ref) .map_err(|e| AgentError::Other(e.to_string()))?; - let creds = credentials_for(artifact); + let creds = credentials_for(artifact, &ctx.secrets); let git_ops = GitOps::new(ctx.git_clone_base, ctx.tenant_id, creds); let repo_path = git_ops.clone_or_fetch(&artifact.source_ref, &artifact.id)?; let head = GitOps::get_head_sha(&repo_path).ok(); @@ -279,10 +283,10 @@ fn local_source(artifact: &Artifact) -> Result { /// is no agent-wide SSH key to fall back to any more, because one shared key /// authenticated every tenant's clone (see /// [`crate::pipeline::git::reject_ssh_url`]). -fn credentials_for(artifact: &Artifact) -> RepoCredentials { +fn credentials_for(artifact: &Artifact, secrets: &SecretBox) -> RepoCredentials { let auth = artifact.auth.as_ref(); RepoCredentials { - auth_token: auth.and_then(|a| a.secret.clone()), + auth_token: auth.and_then(|a| secrets.open_opt(a.secret.as_ref(), "git token")), auth_username: auth.and_then(|a| a.username.clone()), } } @@ -315,6 +319,7 @@ mod tests { tenant_id: "test-tenant", target_id, net_guard: NetGuard::public_only(), + secrets: SecretBox::without_key(), } } @@ -442,7 +447,7 @@ mod tests { secret: Some("pat".to_string()), ..Default::default() }); - let creds = credentials_for(&artifact); + let creds = credentials_for(&artifact, &SecretBox::without_key()); assert_eq!(creds.auth_token.as_deref(), Some("pat")); assert_eq!(creds.auth_username.as_deref(), Some("bob")); } @@ -453,7 +458,7 @@ mod tests { #[test] fn credentials_are_empty_without_artifact_auth() { let artifact = Artifact::git_repo("https://host/x.git", "main"); - let creds = credentials_for(&artifact); + let creds = credentials_for(&artifact, &SecretBox::without_key()); assert!(creds.auth_token.is_none()); assert!(creds.auth_username.is_none()); } diff --git a/compliance-agent/src/lib.rs b/compliance-agent/src/lib.rs index d4e8bb8..d702d3d 100644 --- a/compliance-agent/src/lib.rs +++ b/compliance-agent/src/lib.rs @@ -18,6 +18,7 @@ pub mod rag; pub mod registry; pub mod scan_gate; pub mod scheduler; +pub mod secrets; pub mod targets; pub mod tenant_path; #[allow(dead_code)] diff --git a/compliance-agent/src/main.rs b/compliance-agent/src/main.rs index 12b0064..931bd39 100644 --- a/compliance-agent/src/main.rs +++ b/compliance-agent/src/main.rs @@ -1,4 +1,4 @@ -use compliance_agent::{agent, api, config, database, lifecycle, scheduler, webhooks}; +use compliance_agent::{agent, api, config, database, lifecycle, scheduler, secrets, webhooks}; use compliance_core::shutdown; #[tokio::main] @@ -14,7 +14,7 @@ async fn main() -> Result<(), Box> { tracing::info!( chrome_ws_url = std::env::var("CHROME_WS_URL").ok().as_deref(), pentest_email = std::env::var("PENTEST_VERIFICATION_EMAIL").ok().as_deref(), - encryption_key_set = std::env::var("PENTEST_ENCRYPTION_KEY").is_ok(), + secrets_key_set = std::env::var("SECRETS_ENCRYPTION_KEY").is_ok(), "Loading configuration..." ); let config = config::load_config()?; @@ -36,6 +36,14 @@ async fn main() -> Result<(), Box> { Err(e) => tracing::error!("closing runs left open by the previous agent failed: {e}"), } + // Credentials stored before sealing existed are sealed now, before any + // handler can read one back. + match secrets::seal_stored_credentials(&agent.db_pool, &agent.secrets).await { + Ok(0) => {} + Ok(sealed) => tracing::info!(targets = sealed, "sealed stored credentials"), + Err(e) => tracing::error!("sealing stored credentials failed: {e}"), + } + // SIGTERM or Ctrl+C fires `stop`; each server then drains on its own. let (trigger, stop) = shutdown::channel(); tokio::spawn(async move { diff --git a/compliance-agent/src/pentest/crypto.rs b/compliance-agent/src/pentest/crypto.rs deleted file mode 100644 index 7364bcd..0000000 --- a/compliance-agent/src/pentest/crypto.rs +++ /dev/null @@ -1,117 +0,0 @@ -use aes_gcm::aead::AeadCore; -use aes_gcm::{ - aead::{Aead, KeyInit, OsRng}, - Aes256Gcm, Nonce, -}; -use base64::Engine; - -/// Load the 32-byte encryption key from PENTEST_ENCRYPTION_KEY env var. -/// Returns None if not set or invalid length. -pub fn load_encryption_key() -> Option<[u8; 32]> { - let hex_key = std::env::var("PENTEST_ENCRYPTION_KEY").ok()?; - let bytes = hex::decode(hex_key).ok()?; - if bytes.len() != 32 { - return None; - } - let mut key = [0u8; 32]; - key.copy_from_slice(&bytes); - Some(key) -} - -/// Encrypt a plaintext string. Returns base64-encoded nonce+ciphertext. -/// Returns the original string if no encryption key is available. -pub fn encrypt(plaintext: &str) -> String { - let Some(key_bytes) = load_encryption_key() else { - return plaintext.to_string(); - }; - let Ok(cipher) = Aes256Gcm::new_from_slice(&key_bytes) else { - return plaintext.to_string(); - }; - let nonce = Aes256Gcm::generate_nonce(&mut OsRng); - let Ok(ciphertext) = cipher.encrypt(&nonce, plaintext.as_bytes()) else { - return plaintext.to_string(); - }; - let mut combined = nonce.to_vec(); - combined.extend_from_slice(&ciphertext); - base64::engine::general_purpose::STANDARD.encode(&combined) -} - -/// Decrypt a base64-encoded nonce+ciphertext string. -/// Returns None if decryption fails. -pub fn decrypt(encrypted: &str) -> Option { - let key_bytes = load_encryption_key()?; - let cipher = Aes256Gcm::new_from_slice(&key_bytes).ok()?; - let combined = base64::engine::general_purpose::STANDARD - .decode(encrypted) - .ok()?; - if combined.len() < 12 { - return None; - } - let (nonce_bytes, ciphertext) = combined.split_at(12); - let nonce = Nonce::from_slice(nonce_bytes); - let plaintext = cipher.decrypt(nonce, ciphertext).ok()?; - String::from_utf8(plaintext).ok() -} - -#[cfg(test)] -mod tests { - use super::*; - use std::sync::Mutex; - - // Guard to serialize tests that touch env vars - static ENV_LOCK: Mutex<()> = Mutex::new(()); - - fn with_key(hex_key: &str, f: F) { - let _guard = ENV_LOCK.lock(); - unsafe { std::env::set_var("PENTEST_ENCRYPTION_KEY", hex_key) }; - f(); - unsafe { std::env::remove_var("PENTEST_ENCRYPTION_KEY") }; - } - - #[test] - fn round_trip() { - let key = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"; - with_key(key, || { - let plaintext = "my_secret_password"; - let encrypted = encrypt(plaintext); - assert_ne!(encrypted, plaintext); - let decrypted = decrypt(&encrypted); - assert_eq!(decrypted, Some(plaintext.to_string())); - }); - } - - #[test] - fn wrong_key_fails() { - let _guard = ENV_LOCK.lock(); - let key1 = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"; - let key2 = "abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789"; - let encrypted = { - unsafe { std::env::set_var("PENTEST_ENCRYPTION_KEY", key1) }; - let e = encrypt("secret"); - unsafe { std::env::remove_var("PENTEST_ENCRYPTION_KEY") }; - e - }; - unsafe { std::env::set_var("PENTEST_ENCRYPTION_KEY", key2) }; - assert!(decrypt(&encrypted).is_none()); - unsafe { std::env::remove_var("PENTEST_ENCRYPTION_KEY") }; - } - - #[test] - fn no_key_passthrough() { - let _guard = ENV_LOCK.lock(); - unsafe { std::env::remove_var("PENTEST_ENCRYPTION_KEY") }; - let result = encrypt("plain"); - assert_eq!(result, "plain"); - } - - #[test] - fn corrupted_ciphertext() { - let key = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"; - with_key(key, || { - assert!(decrypt("not-valid-base64!!!").is_none()); - // Valid base64 but wrong content - let garbage = base64::engine::general_purpose::STANDARD.encode(b"tooshort"); - assert!(decrypt(&garbage).is_none()); - }); - } -} diff --git a/compliance-agent/src/pentest/mod.rs b/compliance-agent/src/pentest/mod.rs index 44ed27a..a13ffe9 100644 --- a/compliance-agent/src/pentest/mod.rs +++ b/compliance-agent/src/pentest/mod.rs @@ -1,6 +1,5 @@ pub mod cleanup; mod context; -pub mod crypto; pub mod orchestrator; mod prompt_builder; pub mod report; diff --git a/compliance-agent/src/pentest/prompt_builder.rs b/compliance-agent/src/pentest/prompt_builder.rs index d06d50c..d50ab58 100644 --- a/compliance-agent/src/pentest/prompt_builder.rs +++ b/compliance-agent/src/pentest/prompt_builder.rs @@ -5,12 +5,6 @@ use compliance_core::models::sbom::SbomEntry; use super::orchestrator::PentestOrchestrator; -/// Attempt to decrypt a field; if decryption fails, return the original value -/// (which may be plaintext from before encryption was enabled). -fn decrypt_field(value: &str) -> String { - super::crypto::decrypt(value).unwrap_or_else(|| value.to_string()) -} - /// Build additional prompt sections from PentestConfig when present. fn build_config_sections(config: &PentestConfig) -> String { let mut sections = String::new(); @@ -20,13 +14,12 @@ fn build_config_sections(config: &PentestConfig) -> String { AuthMode::Manual => { sections.push_str("\n## Authentication\n"); sections.push_str("- **Mode**: Manual credentials\n"); + // Callers hand in opened credentials (`SecretBox::open_in_place`). if let Some(ref u) = config.auth.username { - let decrypted = decrypt_field(u); - sections.push_str(&format!("- **Username**: {decrypted}\n")); + sections.push_str(&format!("- **Username**: {u}\n")); } if let Some(ref p) = config.auth.password { - let decrypted = decrypt_field(p); - sections.push_str(&format!("- **Password**: {decrypted}\n")); + sections.push_str(&format!("- **Password**: {p}\n")); } sections.push_str( "Use these credentials to log in before testing authenticated endpoints.\n", diff --git a/compliance-agent/src/pipeline/orchestrator.rs b/compliance-agent/src/pipeline/orchestrator.rs index 9c4f38d..05452dd 100644 --- a/compliance-agent/src/pipeline/orchestrator.rs +++ b/compliance-agent/src/pipeline/orchestrator.rs @@ -19,6 +19,7 @@ use crate::pipeline::plan::build_scan_plan; use crate::pipeline::repo_view::RepoView; use crate::pipeline::sbom::SbomScanner; use crate::pipeline::semgrep::SemgrepScanner; +use crate::secrets::SecretBox; /// Context from graph analysis passed to LLM triage for enhanced filtering #[derive(Debug)] @@ -39,6 +40,8 @@ pub struct PipelineOrchestrator { pub(super) db: Database, pub(super) llm: Arc, pub(super) http: reqwest::Client, + /// Opens the target's sealed credentials (git and tracker tokens). + pub(super) secrets: SecretBox, } impl PipelineOrchestrator { @@ -49,12 +52,14 @@ impl PipelineOrchestrator { llm: Arc, http: reqwest::Client, ) -> Self { + let secrets = SecretBox::from_config(&config); Self { config, tenant_id: tenant_id.to_string(), db, llm, http, + secrets, } } @@ -528,7 +533,7 @@ impl PipelineOrchestrator { match target.code_artifact() { Some(code) if code.kind == ArtifactKind::GitRepo => { - let repo = RepoView::from_target(target, code); + let repo = RepoView::from_target(target, code, &self.secrets); let n = self.run_pipeline(&repo, scan_run_id).await?; self.finalize_target(target, &repo, n).await?; new_count += n; @@ -1269,7 +1274,7 @@ mod tests { target.artifacts.push(artifact); let code = target.code_artifact().expect("code artifact"); - let repo = RepoView::from_target(&target, code); + let repo = RepoView::from_target(&target, code, &SecretBox::without_key()); assert_eq!(repo.id, target.id); // preserved assert_eq!(repo.git_url, "https://git/acme.git"); diff --git a/compliance-agent/src/pipeline/repo_view.rs b/compliance-agent/src/pipeline/repo_view.rs index 5a4aa92..e31684a 100644 --- a/compliance-agent/src/pipeline/repo_view.rs +++ b/compliance-agent/src/pipeline/repo_view.rs @@ -10,6 +10,8 @@ use compliance_core::models::{Artifact, OnboardedTarget, TrackerType}; +use crate::secrets::SecretBox; + /// A flat, pipeline-facing view of a code target. Built from an onboarded /// target; never persisted. #[derive(Debug, Clone)] @@ -34,8 +36,11 @@ pub struct RepoView { } impl RepoView { - /// Project an onboarded target + its code artifact into a pipeline view. - pub fn from_target(target: &OnboardedTarget, code: &Artifact) -> Self { + /// Project an onboarded target + its code artifact into a pipeline view, + /// opening its sealed credentials for use. One that cannot be opened is + /// left out (and logged), so the clone or tracker call fails on auth + /// instead of sending a wrong value. + pub fn from_target(target: &OnboardedTarget, code: &Artifact, secrets: &SecretBox) -> Self { let mut view = Self { id: target.id, name: target.name.clone(), @@ -44,7 +49,7 @@ impl RepoView { local_path: None, scan_schedule: target.scan_schedule.clone(), webhook_enabled: target.webhook_enabled, - webhook_secret: target.webhook_secret.clone(), + webhook_secret: secrets.open_opt(target.webhook_secret.as_ref(), "webhook secret"), tracker_type: None, tracker_owner: None, tracker_repo: None, @@ -60,14 +65,14 @@ impl RepoView { view.local_path = git.local_path.clone(); } if let Some(auth) = &code.auth { - view.auth_token = auth.secret.clone(); + view.auth_token = secrets.open_opt(auth.secret.as_ref(), "git token"); view.auth_username = auth.username.clone(); } if let Some(it) = &target.scan_config.issue_tracker { view.tracker_type = it.tracker_type.clone(); view.tracker_owner = it.owner.clone(); view.tracker_repo = it.repo.clone(); - view.tracker_token = it.token.clone(); + view.tracker_token = secrets.open_opt(it.token.as_ref(), "tracker token"); } view } diff --git a/compliance-agent/src/secrets.rs b/compliance-agent/src/secrets.rs new file mode 100644 index 0000000..e277867 --- /dev/null +++ b/compliance-agent/src/secrets.rs @@ -0,0 +1,405 @@ +//! 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:`. The prefix +//! tells it apart from a value stored before sealing existed, which +//! [`seal_stored_credentials`] converts at startup. + +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 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, +} + +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 { + 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 { + 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 { + 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 { + 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, + 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(&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(&self, record: &mut T) -> Result { + 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. +/// +/// # 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 { + if secrets.cipher.is_none() { + 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 { + 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 { + // 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) +} + +#[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()); + } +} diff --git a/compliance-agent/src/webhooks/gitea.rs b/compliance-agent/src/webhooks/gitea.rs index 3f86b1e..072a0e9 100644 --- a/compliance-agent/src/webhooks/gitea.rs +++ b/compliance-agent/src/webhooks/gitea.rs @@ -39,17 +39,19 @@ pub async fn handle_gitea_webhook( } }; - // Verify HMAC-SHA256 signature using the per-repo secret - if let Some(secret) = &repo.webhook_secret { - let signature = headers - .get("x-gitea-signature") - .and_then(|v| v.to_str().ok()) - .unwrap_or(""); - - if !verify_signature(secret, &body, signature) { - tracing::warn!("Gitea webhook: invalid signature for repo {repo_id}"); - return StatusCode::UNAUTHORIZED; - } + // Verify HMAC-SHA256 signature using the per-repo secret. Fail closed: a + // target without a secret accepts no deliveries at all. + let Some(secret) = super::webhook_secret(&agent, &repo) else { + tracing::warn!("Gitea webhook: repo {repo_id} has no webhook secret; rejected"); + return StatusCode::UNAUTHORIZED; + }; + let signature = headers + .get("x-gitea-signature") + .and_then(|v| v.to_str().ok()) + .unwrap_or(""); + if !verify_signature(&secret, &body, signature) { + tracing::warn!("Gitea webhook: invalid signature for repo {repo_id}"); + return StatusCode::UNAUTHORIZED; } let event = headers diff --git a/compliance-agent/src/webhooks/github.rs b/compliance-agent/src/webhooks/github.rs index 4a50ecf..0b9f6c1 100644 --- a/compliance-agent/src/webhooks/github.rs +++ b/compliance-agent/src/webhooks/github.rs @@ -39,17 +39,19 @@ pub async fn handle_github_webhook( } }; - // Verify HMAC-SHA256 signature using the per-repo secret - if let Some(secret) = &repo.webhook_secret { - let signature = headers - .get("x-hub-signature-256") - .and_then(|v| v.to_str().ok()) - .unwrap_or(""); - - if !verify_signature(secret, &body, signature) { - tracing::warn!("GitHub webhook: invalid signature for repo {repo_id}"); - return StatusCode::UNAUTHORIZED; - } + // Verify HMAC-SHA256 signature using the per-repo secret. Fail closed: a + // target without a secret accepts no deliveries at all. + let Some(secret) = super::webhook_secret(&agent, &repo) else { + tracing::warn!("GitHub webhook: repo {repo_id} has no webhook secret; rejected"); + return StatusCode::UNAUTHORIZED; + }; + let signature = headers + .get("x-hub-signature-256") + .and_then(|v| v.to_str().ok()) + .unwrap_or(""); + if !verify_signature(&secret, &body, signature) { + tracing::warn!("GitHub webhook: invalid signature for repo {repo_id}"); + return StatusCode::UNAUTHORIZED; } let event = headers diff --git a/compliance-agent/src/webhooks/gitlab.rs b/compliance-agent/src/webhooks/gitlab.rs index 010767c..b65e88d 100644 --- a/compliance-agent/src/webhooks/gitlab.rs +++ b/compliance-agent/src/webhooks/gitlab.rs @@ -3,6 +3,7 @@ use std::sync::Arc; use axum::body::Bytes; use axum::extract::{Extension, Path}; use axum::http::{HeaderMap, StatusCode}; +use subtle::ConstantTimeEq; use compliance_core::models::ScanTrigger; @@ -35,17 +36,20 @@ pub async fn handle_gitlab_webhook( } }; - // GitLab sends the secret token in X-Gitlab-Token header (plain text comparison) - if let Some(secret) = &repo.webhook_secret { - let token = headers - .get("x-gitlab-token") - .and_then(|v| v.to_str().ok()) - .unwrap_or(""); - - if token != secret { - tracing::warn!("GitLab webhook: invalid token for repo {repo_id}"); - return StatusCode::UNAUTHORIZED; - } + // GitLab sends the secret itself in X-Gitlab-Token. Fail closed: a target + // without a secret accepts no deliveries at all. + let Some(secret) = super::webhook_secret(&agent, &repo) else { + tracing::warn!("GitLab webhook: repo {repo_id} has no webhook secret; rejected"); + return StatusCode::UNAUTHORIZED; + }; + let token = headers + .get("x-gitlab-token") + .and_then(|v| v.to_str().ok()) + .unwrap_or(""); + // Constant time, so response timing reveals nothing about the secret. + if !bool::from(token.as_bytes().ct_eq(secret.as_bytes())) { + tracing::warn!("GitLab webhook: invalid token for repo {repo_id}"); + return StatusCode::UNAUTHORIZED; } let payload: serde_json::Value = match serde_json::from_slice(&body) { diff --git a/compliance-agent/src/webhooks/mod.rs b/compliance-agent/src/webhooks/mod.rs index 1ea9d87..d31c808 100644 --- a/compliance-agent/src/webhooks/mod.rs +++ b/compliance-agent/src/webhooks/mod.rs @@ -4,3 +4,16 @@ pub mod gitlab; pub mod server; pub use server::start_webhook_server; + +use compliance_core::models::OnboardedTarget; + +use crate::agent::ComplianceAgent; + +/// The target's webhook secret, opened for verification. `None` when the +/// target has none or it cannot be opened; the receivers then reject the +/// delivery, because without a secret nothing proves who sent it. +fn webhook_secret(agent: &ComplianceAgent, target: &OnboardedTarget) -> Option { + agent + .secrets + .open_opt(target.webhook_secret.as_ref(), "webhook secret") +} diff --git a/compliance-agent/tests/common/mod.rs b/compliance-agent/tests/common/mod.rs index 56e0f02..b5c94e7 100644 --- a/compliance-agent/tests/common/mod.rs +++ b/compliance-agent/tests/common/mod.rs @@ -18,6 +18,10 @@ use secrecy::SecretString; /// The runner bearer token wired into the test config. pub const TEST_RUNNER_TOKEN: &str = "test-runner-token"; +/// The credential-sealing key wired into the test config (test-only value). +pub const TEST_SECRETS_KEY: &str = + "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"; + /// A minimal dev [`AgentConfig`] for tests: unauthenticated (no Keycloak), the /// Werkbank runner API enabled with [`TEST_RUNNER_TOKEN`]. pub fn dev_config(mongodb_uri: String, db_name: String) -> AgentConfig { @@ -33,6 +37,7 @@ pub fn dev_config(mongodb_uri: String, db_name: String) -> AgentConfig { artifact_store_base_path: "/tmp/compliance-scanner-tests/artifacts".into(), pentest_imap_tls: false, werkbank_runner_token: Some(SecretString::from(TEST_RUNNER_TOKEN.to_string())), + secrets_encryption_key: Some(SecretString::from(TEST_SECRETS_KEY.to_string())), // Unauthenticated dev: no Keycloak, no audience, no registry. keycloak_audience: None, ..Default::default() diff --git a/compliance-agent/tests/credentials.rs b/compliance-agent/tests/credentials.rs new file mode 100644 index 0000000..8b78779 --- /dev/null +++ b/compliance-agent/tests/credentials.rs @@ -0,0 +1,296 @@ +//! Tenant credentials are sealed at rest and never returned (#260). +//! +//! Drives the real target API against a live Mongo and checks the stored +//! documents directly: a tracker token sent in a PATCH is stored sealed, no +//! response carries it, echoing the record back without it keeps it, and the +//! webhook receivers reject a target without a secret. Skips cleanly when no +//! Mongo is reachable. + +#![allow(clippy::expect_used, clippy::unwrap_used)] + +mod common; + +use std::sync::Arc; + +use axum::body::Bytes; +use axum::extract::Path; +use axum::http::{HeaderMap, HeaderValue, StatusCode}; +use axum::{middleware, Extension}; +use hmac::{Hmac, Mac}; +use mongodb::bson::{doc, oid::ObjectId, Document}; +use sha2::Sha256; + +use compliance_agent::agent::ComplianceAgent; +use compliance_agent::api; +use compliance_agent::database::{Database, DatabasePool}; +use compliance_agent::secrets::{seal_stored_credentials, SecretBox}; +use compliance_agent::webhooks::github::handle_github_webhook; +use compliance_core::models::{IssueTrackerConfig, OnboardedTarget, TargetType}; + +use common::{dev_config, TEST_SECRETS_KEY}; + +/// The tenant `inject_dev_tenant` puts every request in. +const TENANT: &str = "dev"; + +struct Harness { + base_url: String, + client: reqwest::Client, + pool: DatabasePool, + db: Database, + agent: Arc, +} + +async fn start() -> Option { + let uri = std::env::var("TEST_MONGODB_URI") + .unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into()); + let db_name = format!("cred_{}", &uuid::Uuid::new_v4().simple().to_string()[..12]); + let Ok(pool) = DatabasePool::connect(&uri, &db_name).await else { + eprintln!("SKIP credentials: no MongoDB reachable at {uri}"); + return None; + }; + let db = pool.for_tenant_id(TENANT).await.expect("tenant db"); + let agent = Arc::new(ComplianceAgent::new(dev_config(uri, db_name), pool.clone())); + let app = api::routes::build_router() + .layer(Extension(agent.clone())) + .layer(middleware::from_fn(api::server::inject_dev_tenant)); + + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let port = listener.local_addr().unwrap().port(); + tokio::spawn(async move { + axum::serve(listener, app).await.ok(); + }); + Some(Harness { + base_url: format!("http://127.0.0.1:{port}"), + client: reqwest::Client::new(), + pool, + db, + agent, + }) +} + +impl Harness { + async fn send(&self, method: reqwest::Method, path: &str, body: serde_json::Value) -> String { + let resp = self + .client + .request(method, format!("{}{path}", self.base_url)) + .json(&body) + .send() + .await + .unwrap(); + assert!(resp.status().is_success(), "{path}: {}", resp.status()); + resp.text().await.unwrap() + } + + async fn stored(&self, id: &str) -> Document { + let oid = ObjectId::parse_str(id).unwrap(); + self.db + .raw_collection("onboarded_targets") + .find_one(doc! { "_id": oid }) + .await + .unwrap() + .expect("stored target") + } + + async fn cleanup(&self) { + self.pool.drop_tenant(TENANT).await.ok(); + } +} + +fn stored_tracker_token(target: &Document) -> Option { + target + .get_document("scan_config") + .ok()? + .get_document("issue_tracker") + .ok()? + .get_str("token") + .ok() + .map(str::to_string) +} + +fn tracker_update(token: Option<&str>) -> serde_json::Value { + let mut tracker = serde_json::json!({ + "tracker_type": "gitea", + "owner": "acme", + "repo": "web", + }); + if let Some(token) = token { + tracker["token"] = serde_json::json!(token); + } + serde_json::json!({ "scan_config": { "issue_tracker": tracker } }) +} + +#[tokio::test] +async fn a_tracker_token_is_stored_sealed_and_never_returned() { + let Some(h) = start().await else { return }; + let secrets = SecretBox::from_hex(TEST_SECRETS_KEY).unwrap(); + + // Arrange: a target, then a tracker token set through the API. + let created = h + .send( + reqwest::Method::POST, + "/api/v1/targets", + serde_json::json!({ "name": "web", "target_type": "web_app" }), + ) + .await; + let created: serde_json::Value = serde_json::from_str(&created).unwrap(); + let id = created["data"]["_id"]["$oid"].as_str().unwrap().to_string(); + let path = format!("/api/v1/targets/{id}"); + let patched = h + .send( + reqwest::Method::PATCH, + &path, + tracker_update(Some("tracker-secret")), + ) + .await; + + // Act + let fetched = h + .send(reqwest::Method::GET, &path, serde_json::json!({})) + .await; + let listed = h + .send( + reqwest::Method::GET, + "/api/v1/targets", + serde_json::json!({}), + ) + .await; + + // Assert: no response carries the token, the tracker itself is visible. + for body in [&patched, &fetched, &listed] { + assert!(!body.contains("tracker-secret"), "token leaked: {body}"); + assert!(!body.contains("enc:v1:"), "sealed value leaked: {body}"); + } + let fetched: serde_json::Value = serde_json::from_str(&fetched).unwrap(); + let tracker = &fetched["data"]["scan_config"]["issue_tracker"]; + assert_eq!(tracker["owner"], "acme"); + assert!(tracker["token"].is_null()); + + // Stored sealed, and it opens to what was sent. + let sealed = stored_tracker_token(&h.stored(&id).await).expect("token stored"); + assert!(SecretBox::is_sealed(&sealed)); + assert_eq!(secrets.open(&sealed).unwrap(), "tracker-secret"); + + // Echoing the record back without the token keeps it... + h.send(reqwest::Method::PATCH, &path, tracker_update(None)) + .await; + assert_eq!( + stored_tracker_token(&h.stored(&id).await).as_ref(), + Some(&sealed) + ); + // ...and an empty token removes it. + h.send(reqwest::Method::PATCH, &path, tracker_update(Some(""))) + .await; + assert_eq!(stored_tracker_token(&h.stored(&id).await), None); + + h.cleanup().await; +} + +#[tokio::test] +async fn credentials_stored_before_sealing_are_sealed_at_startup() { + let Some(h) = start().await else { return }; + + // Arrange: a target written the way older releases stored it. + let mut target = OnboardedTarget::new("legacy".into(), TargetType::WebApp); + target.webhook_secret = Some("plain-hook".into()); + target.scan_config.issue_tracker = Some(IssueTrackerConfig { + token: Some("plain-tracker".into()), + ..Default::default() + }); + let id = + h.db.onboarded_targets() + .insert_one(&target) + .await + .unwrap() + .inserted_id + .as_object_id() + .unwrap() + .to_hex(); + + // Act + let sealed = seal_stored_credentials(&h.pool, &h.agent.secrets) + .await + .unwrap(); + + // Assert: both values sealed, still usable, and a second pass is a no-op. + assert_eq!(sealed, 1); + let stored = h.stored(&id).await; + let hook = stored.get_str("webhook_secret").unwrap(); + let tracker = stored_tracker_token(&stored).unwrap(); + assert!(SecretBox::is_sealed(hook) && SecretBox::is_sealed(&tracker)); + assert_eq!(h.agent.secrets.open(hook).unwrap(), "plain-hook"); + assert_eq!(h.agent.secrets.open(&tracker).unwrap(), "plain-tracker"); + assert_eq!( + seal_stored_credentials(&h.pool, &h.agent.secrets) + .await + .unwrap(), + 0 + ); + + h.cleanup().await; +} + +/// `X-Hub-Signature-256` for `body` under `secret`. +fn github_signature(secret: &str, body: &[u8]) -> HeaderValue { + let mut mac = Hmac::::new_from_slice(secret.as_bytes()).unwrap(); + mac.update(body); + let hex = hex::encode(mac.finalize().into_bytes()); + HeaderValue::from_str(&format!("sha256={hex}")).unwrap() +} + +#[tokio::test] +async fn webhooks_for_a_target_without_a_secret_are_rejected() { + let Some(h) = start().await else { return }; + let body = Bytes::from_static(br#"{"zen":"ok"}"#); + + // Arrange: one target without a secret, one with a sealed secret. + let insert = |target: OnboardedTarget| { + let db = h.db.clone(); + async move { + db.onboarded_targets() + .insert_one(&target) + .await + .unwrap() + .inserted_id + .as_object_id() + .unwrap() + .to_hex() + } + }; + let unsecured = insert(OnboardedTarget::new("a".into(), TargetType::WebApp)).await; + let mut secured_target = OnboardedTarget::new("b".into(), TargetType::WebApp); + secured_target.webhook_secret = Some(h.agent.secrets.seal("hook-secret").unwrap()); + let secured = insert(secured_target).await; + + let deliver = |repo_id: String, signature: HeaderValue| { + let agent = h.agent.clone(); + let body = body.clone(); + async move { + let mut headers = HeaderMap::new(); + // A ping, so an accepted delivery starts no scan. + headers.insert("x-github-event", HeaderValue::from_static("ping")); + headers.insert("x-hub-signature-256", signature); + handle_github_webhook( + Extension(agent), + Path((TENANT.to_string(), repo_id)), + headers, + body, + ) + .await + } + }; + + // Act + Assert: no secret means rejected even when "signed"; a correct + // signature is accepted, a wrong one is not. + let any = github_signature("guess", &body); + assert_eq!( + deliver(unsecured, any.clone()).await, + StatusCode::UNAUTHORIZED + ); + assert_eq!( + deliver(secured.clone(), github_signature("hook-secret", &body)).await, + StatusCode::OK + ); + assert_eq!(deliver(secured, any).await, StatusCode::UNAUTHORIZED); + + h.cleanup().await; +} diff --git a/compliance-core/src/config.rs b/compliance-core/src/config.rs index 81d3deb..a2b3733 100644 --- a/compliance-core/src/config.rs +++ b/compliance-core/src/config.rs @@ -50,6 +50,10 @@ pub struct AgentConfig { /// mounted at all (defense-in-depth: ops endpoints never reach /// any auth path if no operator has explicitly opted in). pub admin_api_token: Option, + /// Hex-encoded 32-byte AES-256-GCM key that seals tenant credentials at + /// rest (`SECRETS_ENCRYPTION_KEY`). Without it the agent refuses to store + /// a credential instead of writing it in plain text. + pub secrets_encryption_key: Option, /// Live tenant-registry URL the scheduler consults for the list /// of tenants to iterate. When `None` or unreachable, scheduler /// falls back to `SCHEDULER_TENANT_IDS` env (M7.2-C). @@ -196,6 +200,11 @@ impl AgentConfig { "TENANT_REGISTRY_CLIENT_SECRET", "registry calls would go out unauthenticated", ); + require( + self.secrets_encryption_key.is_some(), + "SECRETS_ENCRYPTION_KEY", + "without it no tenant credential (git or tracker token) can be stored", + ); require( !self.platform_allowed_clients.is_empty(), "PLATFORM_ALLOWED_CLIENTS", @@ -252,6 +261,7 @@ impl Default for AgentConfig { pentest_imap_username: None, pentest_imap_password: None, admin_api_token: None, + secrets_encryption_key: None, tenant_registry_url: None, plc_runtime: PlcRuntimeConfig::default(), werkbank_runner_token: None, @@ -305,6 +315,7 @@ mod app_env_tests { "TENANT_REGISTRY_URL", "TENANT_REGISTRY_CLIENT_ID", "TENANT_REGISTRY_CLIENT_SECRET", + "SECRETS_ENCRYPTION_KEY", "PLATFORM_ALLOWED_CLIENTS", ] { assert!( @@ -326,6 +337,7 @@ mod app_env_tests { tenant_registry_client_id: Some("pruefwerk-svc-stage".to_string()), tenant_registry_client_secret: Some(secrecy::SecretString::from("s3cret".to_string())), platform_allowed_clients: vec!["tenant-registry-svc-stage".to_string()], + secrets_encryption_key: Some(secrecy::SecretString::from("00".repeat(32))), ..Default::default() }; assert!(cfg.validate_deployment().is_ok()); diff --git a/compliance-core/src/models/credentials.rs b/compliance-core/src/models/credentials.rs new file mode 100644 index 0000000..67d0267 --- /dev/null +++ b/compliance-core/src/models/credentials.rs @@ -0,0 +1,243 @@ +//! Which stored fields are credentials (#260). +//! +//! A tenant's git token, issue-tracker token, webhook secret and pentest +//! passwords live inside the records the API returns. [`Credentials`] names +//! those fields once, so the agent can seal every one before a write and strip +//! every one before a record leaves the service, and a field added later only +//! has to be listed here. + +use super::dast::{DastAuthConfig, DastTarget}; +use super::onboarding::{ + Artifact, ArtifactAuth, IssueTrackerConfig, OnboardedTarget, TargetScanConfig, +}; +use super::pentest::{PentestAuthConfig, PentestConfig, PentestSession}; + +/// A record that carries stored credentials. +pub trait Credentials { + /// Every credential field of the record, for sealing before a write. + fn credentials_mut(&mut self) -> Vec<&mut Option>; + + /// Remove every credential before the record leaves the service. + fn redact(&mut self) { + for slot in self.credentials_mut() { + *slot = None; + } + } + + /// The record without its credentials, for a handler's return value. + fn redacted(mut self) -> Self + where + Self: Sized, + { + self.redact(); + self + } +} + +impl Credentials for Option { + fn credentials_mut(&mut self) -> Vec<&mut Option> { + self.as_mut().map(T::credentials_mut).unwrap_or_default() + } + + fn redact(&mut self) { + if let Some(inner) = self { + inner.redact(); + } + } +} + +impl Credentials for Vec { + fn credentials_mut(&mut self) -> Vec<&mut Option> { + self.iter_mut().flat_map(T::credentials_mut).collect() + } + + fn redact(&mut self) { + self.iter_mut().for_each(T::redact); + } +} + +impl Credentials for ArtifactAuth { + fn credentials_mut(&mut self) -> Vec<&mut Option> { + vec![&mut self.secret] + } + + fn redact(&mut self) { + self.secret = None; + // Authentication headers (a cookie, an API-key header) are + // credentials too; nothing writes them through the API, so they are + // only ever removed, never sealed. + self.headers = None; + } +} + +impl Credentials for Artifact { + fn credentials_mut(&mut self) -> Vec<&mut Option> { + self.auth.credentials_mut() + } + + fn redact(&mut self) { + self.auth.redact(); + } +} + +impl Credentials for IssueTrackerConfig { + fn credentials_mut(&mut self) -> Vec<&mut Option> { + vec![&mut self.token] + } +} + +impl Credentials for PentestAuthConfig { + fn credentials_mut(&mut self) -> Vec<&mut Option> { + vec![&mut self.password, &mut self.imap_password] + } +} + +impl Credentials for PentestConfig { + fn credentials_mut(&mut self) -> Vec<&mut Option> { + self.auth.credentials_mut() + } +} + +impl Credentials for TargetScanConfig { + fn credentials_mut(&mut self) -> Vec<&mut Option> { + let mut slots = self.issue_tracker.credentials_mut(); + slots.extend(self.pentest.credentials_mut()); + slots + } +} + +impl Credentials for OnboardedTarget { + fn credentials_mut(&mut self) -> Vec<&mut Option> { + let mut slots = vec![&mut self.webhook_secret]; + slots.extend(self.artifacts.credentials_mut()); + slots.extend(self.scan_config.credentials_mut()); + slots + } + + fn redact(&mut self) { + self.webhook_secret = None; + self.artifacts.redact(); + self.scan_config.redact(); + } +} + +impl Credentials for DastAuthConfig { + fn credentials_mut(&mut self) -> Vec<&mut Option> { + vec![&mut self.password, &mut self.token] + } + + fn redact(&mut self) { + self.password = None; + self.token = None; + self.headers = None; + } +} + +impl Credentials for DastTarget { + fn credentials_mut(&mut self) -> Vec<&mut Option> { + self.auth_config.credentials_mut() + } + + fn redact(&mut self) { + self.auth_config.redact(); + } +} + +impl Credentials for PentestSession { + fn credentials_mut(&mut self) -> Vec<&mut Option> { + self.config.credentials_mut() + } +} + +#[cfg(test)] +#[allow(clippy::expect_used)] +mod tests { + use std::collections::HashMap; + + use super::*; + use crate::models::{PentestStrategy, TargetType, TrackerType}; + + fn target_with_every_credential() -> OnboardedTarget { + let mut target = OnboardedTarget::new("t".into(), TargetType::WebApp); + target.webhook_secret = Some("sec-hook".into()); + let mut artifact = Artifact::git_repo("https://example.com/r.git", "main"); + artifact.auth = Some(ArtifactAuth { + method: "token".into(), + username: Some("bob".into()), + secret: Some("sec-pat".into()), + headers: Some(HashMap::from([("Cookie".into(), "sec-cookie".into())])), + ..Default::default() + }); + target.artifacts.push(artifact); + target.scan_config.issue_tracker = Some(IssueTrackerConfig { + tracker_type: Some(TrackerType::Gitea), + owner: Some("acme".into()), + repo: Some("web".into()), + token: Some("sec-tracker".into()), + }); + target + } + + #[test] + fn every_target_credential_is_listed() { + let mut target = target_with_every_credential(); + let mut values: Vec = target + .credentials_mut() + .into_iter() + .filter_map(|slot| slot.clone()) + .collect(); + values.sort(); + assert_eq!(values, ["sec-hook", "sec-pat", "sec-tracker"]); + } + + #[test] + fn redacted_target_serializes_without_any_credential() { + let mut target = target_with_every_credential(); + target.redact(); + + let json = serde_json::to_string(&target).expect("serialize"); + for secret in ["sec-hook", "sec-pat", "sec-tracker", "sec-cookie"] { + assert!(!json.contains(secret), "{secret} leaked: {json}"); + } + // What identifies the credential stays, so the UI can say what is set. + assert!(json.contains("bob")); + assert!(json.contains("acme")); + } + + #[test] + fn redacted_pentest_session_drops_passwords_but_keeps_the_user() { + let mut session = PentestSession::new("target".into(), PentestStrategy::Quick); + session.config = Some(PentestConfig { + app_url: "https://example.com".into(), + git_repo_url: None, + branch: None, + commit_hash: None, + app_type: None, + rate_limit: None, + auth: PentestAuthConfig { + username: Some("tester".into()), + password: Some("pw".into()), + imap_password: Some("imap".into()), + ..Default::default() + }, + custom_headers: HashMap::new(), + strategy: None, + allow_destructive: false, + initial_instructions: None, + scope_exclusions: Vec::new(), + disclaimer_accepted: true, + disclaimer_accepted_at: None, + environment: Default::default(), + tester: Default::default(), + max_duration_minutes: None, + skip_mode: false, + }); + + session.redact(); + + let auth = &session.config.expect("config").auth; + assert_eq!(auth.username.as_deref(), Some("tester")); + assert_eq!(auth.password, None); + assert_eq!(auth.imap_password, None); + } +} diff --git a/compliance-core/src/models/mod.rs b/compliance-core/src/models/mod.rs index d1f3354..cc5125c 100644 --- a/compliance-core/src/models/mod.rs +++ b/compliance-core/src/models/mod.rs @@ -1,5 +1,6 @@ pub mod auth; pub mod chat; +pub mod credentials; pub mod cve; pub mod dast; pub mod embedding; @@ -21,6 +22,7 @@ pub mod werkbank; pub use auth::AuthInfo; pub use chat::{ChatMessage, ChatRequest, ChatResponse, SourceReference}; +pub use credentials::Credentials; pub use cve::{CveAlert, CveSource}; pub use dast::{ DastAuthConfig, DastEvidence, DastFinding, DastScanPhase, DastScanRun, DastScanStatus, diff --git a/compliance-core/src/models/onboarding.rs b/compliance-core/src/models/onboarding.rs index 7710a68..5934c8d 100644 --- a/compliance-core/src/models/onboarding.rs +++ b/compliance-core/src/models/onboarding.rs @@ -581,7 +581,9 @@ pub struct OnboardedTarget { /// Whether inbound webhooks are enabled for this target. #[serde(default)] pub webhook_enabled: bool, - /// HMAC secret for verifying inbound webhooks. + /// HMAC secret for verifying inbound webhooks, sealed at rest. `None` + /// until one is issued; the webhook receivers reject every delivery for a + /// target without one. #[serde(default, skip_serializing_if = "Option::is_none")] pub webhook_secret: Option, /// Cached count of findings across this target's scans. @@ -602,10 +604,11 @@ pub struct OnboardedTarget { } impl OnboardedTarget { - /// A new target of the given type with a freshly generated webhook secret. + /// A new target of the given type. It has no webhook secret: storing one + /// needs the agent's encryption key, and webhooks are off until a secret + /// is issued for the target. pub fn new(name: String, target_type: TargetType) -> Self { let now = Utc::now(); - let webhook_secret = uuid::Uuid::new_v4().to_string().replace('-', ""); Self { id: None, name, @@ -618,7 +621,7 @@ impl OnboardedTarget { external_refs: Vec::new(), scan_schedule: None, webhook_enabled: false, - webhook_secret: Some(webhook_secret), + webhook_secret: None, findings_count: 0, created_at: now, updated_at: now, @@ -698,11 +701,9 @@ mod tests { } #[test] - fn new_target_generates_webhook_secret() { + fn new_target_has_no_webhook_secret() { let t = OnboardedTarget::new("t".to_string(), TargetType::BackendService); - let secret = t.webhook_secret.expect("secret present"); - assert_eq!(secret.len(), 32); - assert!(!secret.contains('-')); + assert_eq!(t.webhook_secret, None); } #[test] diff --git a/compliance-mcp/src/tools/pentest.rs b/compliance-mcp/src/tools/pentest.rs index 740d0d4..d985140 100644 --- a/compliance-mcp/src/tools/pentest.rs +++ b/compliance-mcp/src/tools/pentest.rs @@ -1,3 +1,4 @@ +use compliance_core::models::{Credentials, PentestSession}; use mongodb::bson::doc; use rmcp::{model::*, ErrorData as McpError}; use schemars::JsonSchema; @@ -141,10 +142,11 @@ pub async fn list_pentest_sessions( .await .map_err(|e| McpError::internal_error(format!("cursor error: {e}"), None))? { - let session = cursor + let session: PentestSession = cursor .deserialize_current() .map_err(|e| McpError::internal_error(format!("deserialize error: {e}"), None))?; - results.push(session); + // The test account's password must not reach an LLM client. + results.push(session.redacted()); } let json = serde_json::to_string_pretty(&results) @@ -173,7 +175,8 @@ pub async fn get_pentest_session( .find_one(doc! { "_id": oid }) .await .map_err(|e| McpError::internal_error(format!("DB error: {e}"), None))? - .ok_or_else(|| McpError::invalid_params("session not found", None))?; + .ok_or_else(|| McpError::invalid_params("session not found", None))? + .redacted(); let json = serde_json::to_string_pretty(&session) .map_err(|e| McpError::internal_error(format!("json error: {e}"), None))?; diff --git a/docs/guide/repositories.md b/docs/guide/repositories.md index 73c6fac..59f47cf 100644 --- a/docs/guide/repositories.md +++ b/docs/guide/repositories.md @@ -68,7 +68,6 @@ From the edit modal you can: - Change the repository name, Git URL, or default branch - Add, modify, or remove issue tracker configuration -- View the webhook URL and secret for this repository (see [Webhooks & PR Reviews](/guide/webhooks)) ## Repository List diff --git a/docs/guide/scanning.md b/docs/guide/scanning.md index 87ee74d..d01ab86 100644 --- a/docs/guide/scanning.md +++ b/docs/guide/scanning.md @@ -30,7 +30,7 @@ Repositories are scanned automatically on a recurring schedule. By default, scan ### Webhook-Triggered Scans -When you configure a webhook in your Git hosting provider, scans are triggered automatically on push events. You can also get automated PR reviews. See [Webhooks & PR Reviews](/guide/webhooks) for setup instructions. +When you configure a webhook in your Git hosting provider, scans are triggered automatically on push events. You can also get automated PR reviews. Webhooks are not available in this release yet; see [Webhooks & PR Reviews](/guide/webhooks). ### When scans overlap diff --git a/docs/guide/webhooks.md b/docs/guide/webhooks.md index 518683d..56bac30 100644 --- a/docs/guide/webhooks.md +++ b/docs/guide/webhooks.md @@ -7,14 +7,17 @@ Webhooks let Prüfwerk respond to events in your Git repositories automatically. - **Automatic scans on push** -- every time code is pushed to your default branch, a scan is triggered automatically - **PR security reviews** -- when a pull request is opened or updated, Prüfwerk scans the changes and posts a review comment summarizing any security findings in the diff +::: warning Not available yet +Prüfwerk does not issue webhook secrets yet, and it rejects every webhook +delivery for a repository that has no secret, so webhooks cannot be set up in +this release. Scans run on their schedule or when you start them. The setup +below applies once webhook secrets can be issued again. +::: + ## Finding the Webhook URL and Secret -Each repository in Prüfwerk has its own webhook URL and secret: - -1. Go to **Repositories** -2. Click **Edit** on the repository you want to configure -3. In the edit modal, you will find the **Webhook URL** and **Webhook Secret** -4. Copy both values -- you will need them when configuring your Git hosting provider +Each repository gets its own webhook URL and secret. Prüfwerk stores the +secret encrypted and never returns it from the API. ## Setting Up Webhooks