feat(notify): mail the workspace when a scan finds something new (#360)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01DmXxNULoSNPvjF7buKipsB
This commit was merged in pull request #360.
This commit is contained in:
1 parent
33b1b3127c
commit
6a6587a074
2 files changed
+192
-1
No files matched your search
@@ -185,7 +185,7 @@ impl ComplianceAgent {
|
||||
let orchestrator = PipelineOrchestrator::new(
|
||||
self.config.clone(),
|
||||
tenant_id,
|
||||
db,
|
||||
db.clone(),
|
||||
self.llm.clone(),
|
||||
self.http.clone(),
|
||||
);
|
||||
@@ -197,9 +197,38 @@ impl ComplianceAgent {
|
||||
format!("scan:{tenant_id}:{target_id}:{}", started.timestamp()),
|
||||
serde_json::json!({ "target_id": target_id, "trigger": format!("{trigger:?}") }),
|
||||
);
|
||||
self.notify_new_findings(tenant_id, target_id, &db, started);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Tell the workspace (by mail, through the platform) when a scan found
|
||||
/// something that was not there before. "New" is what the pipeline
|
||||
/// inserted during this scan: it only inserts a finding whose fingerprint
|
||||
/// is not stored yet. Background and best-effort; no registry, no mail.
|
||||
fn notify_new_findings(
|
||||
&self,
|
||||
tenant_id: &str,
|
||||
target_id: &str,
|
||||
db: &crate::database::Database,
|
||||
started: chrono::DateTime<chrono::Utc>,
|
||||
) {
|
||||
let Some(registry) = self.registry.clone() else {
|
||||
return;
|
||||
};
|
||||
let (db, tenant_id, target_id) = (db.clone(), tenant_id.to_string(), target_id.to_string());
|
||||
tokio::spawn(async move {
|
||||
match new_findings_summary(&db, &tenant_id, &target_id, started).await {
|
||||
Ok(Some(n)) => {
|
||||
if let Err(e) = registry.notify_new_findings(&n).await {
|
||||
tracing::warn!(tenant_id, target_id, "findings notification failed: {e}");
|
||||
}
|
||||
}
|
||||
Ok(None) => {}
|
||||
Err(e) => tracing::warn!(tenant_id, target_id, "findings summary failed: {e}"),
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// Run a PR review: scan the diff and post review comments.
|
||||
pub async fn run_pr_review(
|
||||
&self,
|
||||
@@ -293,3 +322,119 @@ impl ComplianceAgent {
|
||||
self.session_pause.remove(session_id);
|
||||
}
|
||||
}
|
||||
|
||||
/// Findings of `target_id` first stored since `since`, by severity; `None`
|
||||
/// when there are none.
|
||||
async fn new_findings_summary(
|
||||
db: &crate::database::Database,
|
||||
tenant_id: &str,
|
||||
target_id: &str,
|
||||
since: chrono::DateTime<chrono::Utc>,
|
||||
) -> Result<Option<crate::registry::FindingsNotification>, mongodb::error::Error> {
|
||||
use mongodb::bson::doc;
|
||||
let since_bson = mongodb::bson::DateTime::from_chrono(since);
|
||||
let mut counts = [0u64; 5]; // critical, high, medium, low, info
|
||||
for (i, sev) in ["critical", "high", "medium", "low", "info"]
|
||||
.iter()
|
||||
.enumerate()
|
||||
{
|
||||
counts[i] = db
|
||||
.findings()
|
||||
.count_documents(doc! { "repo_id": target_id, "severity": *sev, "created_at": { "$gte": since_bson } })
|
||||
.await?;
|
||||
}
|
||||
let total: u64 = counts.iter().sum();
|
||||
if total == 0 {
|
||||
return Ok(None);
|
||||
}
|
||||
let name = match mongodb::bson::oid::ObjectId::parse_str(target_id) {
|
||||
Ok(oid) => db
|
||||
.onboarded_targets()
|
||||
.find_one(doc! { "_id": oid })
|
||||
.await?
|
||||
.map(|t| t.name)
|
||||
.unwrap_or_else(|| target_id.to_string()),
|
||||
Err(_) => target_id.to_string(),
|
||||
};
|
||||
Ok(Some(findings_notification(
|
||||
tenant_id,
|
||||
target_id,
|
||||
name,
|
||||
counts,
|
||||
since,
|
||||
dashboard_url(),
|
||||
)))
|
||||
}
|
||||
|
||||
/// The public dashboard origin (DASHBOARD_PUBLIC_URL), for the mail's link.
|
||||
fn dashboard_url() -> String {
|
||||
std::env::var("DASHBOARD_PUBLIC_URL").unwrap_or_default()
|
||||
}
|
||||
|
||||
fn findings_notification(
|
||||
tenant_id: &str,
|
||||
target_id: &str,
|
||||
target_name: String,
|
||||
counts: [u64; 5],
|
||||
since: chrono::DateTime<chrono::Utc>,
|
||||
dashboard: String,
|
||||
) -> crate::registry::FindingsNotification {
|
||||
let dashboard = dashboard.trim_end_matches('/');
|
||||
crate::registry::FindingsNotification {
|
||||
tenant_id: tenant_id.to_string(),
|
||||
key: format!("findings:{tenant_id}:{target_id}:{}", since.timestamp()),
|
||||
target_name,
|
||||
new_count: counts.iter().sum(),
|
||||
critical: counts[0],
|
||||
high: counts[1],
|
||||
medium: counts[2],
|
||||
low: counts[3] + counts[4],
|
||||
url: if dashboard.starts_with("https://") {
|
||||
format!("{dashboard}/findings?target={target_id}")
|
||||
} else {
|
||||
String::new()
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod notification_tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn summary_counts_and_link() {
|
||||
let since = chrono::DateTime::from_timestamp(1_700_000_000, 0).unwrap();
|
||||
let n = findings_notification(
|
||||
"t1",
|
||||
"tg1",
|
||||
"Pump".into(),
|
||||
[1, 2, 0, 3, 4],
|
||||
since,
|
||||
"https://pruefwerk.breakpilot.com/".into(),
|
||||
);
|
||||
assert_eq!(n.new_count, 10);
|
||||
assert_eq!((n.critical, n.high, n.medium, n.low), (1, 2, 0, 7));
|
||||
assert_eq!(n.key, "findings:t1:tg1:1700000000");
|
||||
assert_eq!(
|
||||
n.url,
|
||||
"https://pruefwerk.breakpilot.com/findings?target=tg1"
|
||||
);
|
||||
// no or non-https dashboard: the platform links its own page
|
||||
assert_eq!(
|
||||
findings_notification("t", "g", "x".into(), [0, 0, 1, 0, 0], since, String::new()).url,
|
||||
""
|
||||
);
|
||||
assert_eq!(
|
||||
findings_notification(
|
||||
"t",
|
||||
"g",
|
||||
"x".into(),
|
||||
[0, 0, 1, 0, 0],
|
||||
since,
|
||||
"http://x".into()
|
||||
)
|
||||
.url,
|
||||
""
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -313,6 +313,52 @@ impl RegistryClient {
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Ask the platform to tell the workspace about new findings
|
||||
/// (`POST /v1/notifications`, kind `findings.new`). The registry mails the
|
||||
/// people who run the workspace; `key` makes a retry harmless.
|
||||
pub async fn notify_new_findings(&self, n: &FindingsNotification) -> Result<(), String> {
|
||||
let resp = self
|
||||
.request(reqwest::Method::POST, "/v1/notifications")
|
||||
.await?
|
||||
.json(&serde_json::json!({
|
||||
"tenant_id": n.tenant_id,
|
||||
"kind": "findings.new",
|
||||
"idempotency_key": n.key,
|
||||
"data": {
|
||||
"target_name": n.target_name,
|
||||
"new_count": n.new_count,
|
||||
"critical": n.critical,
|
||||
"high": n.high,
|
||||
"medium": n.medium,
|
||||
"low": n.low,
|
||||
"url": n.url,
|
||||
},
|
||||
}))
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| format!("notification failed: {e}"))?;
|
||||
if !resp.status().is_success() {
|
||||
return Err(format!("notification returned {}", resp.status()));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// New findings of one scan, for [`RegistryClient::notify_new_findings`].
|
||||
#[derive(Debug, Clone, Default, PartialEq)]
|
||||
pub struct FindingsNotification {
|
||||
pub tenant_id: String,
|
||||
pub key: String,
|
||||
pub target_name: String,
|
||||
pub new_count: u64,
|
||||
pub critical: u64,
|
||||
pub high: u64,
|
||||
pub medium: u64,
|
||||
/// Low and info together.
|
||||
pub low: u64,
|
||||
/// Deep link into the dashboard; empty lets the platform link its own page.
|
||||
pub url: String,
|
||||
}
|
||||
|
||||
/// Ladder rungs on which scheduled work still makes sense. Restricted /
|
||||
|
||||
Reference in new issue
Block a user