Files
pruefwerk/compliance-agent/tests/credentials.rs
T
Sharang ParnerkarandClaude Opus 5 b89f31e2d3
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) Canceled after 6m28s
feat(security): seal tenant credentials at rest, never return them (#260)
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) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EYKjxacrr6K88DruUmP48p
2026-09-21 18:03:00 +02:00

297 lines
9.8 KiB
Rust

//! 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<ComplianceAgent>,
}
async fn start() -> Option<Harness> {
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<String> {
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::<Sha256>::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;
}