210 lines
6.9 KiB
Rust
210 lines
6.9 KiB
Rust
//! Restart recovery and the Werkbank lease sweep across tenants (#259).
|
|
//!
|
|
//! Runs against a real MongoDB because both walk every tenant database and
|
|
//! rely on `update_many` semantics. Skips cleanly when no Mongo is reachable
|
|
//! (set `TEST_MONGODB_URI` to point at one; defaults to the local dev cluster).
|
|
|
|
#![allow(clippy::expect_used, clippy::unwrap_used)]
|
|
|
|
use std::time::Duration;
|
|
|
|
use chrono::{TimeZone, Utc};
|
|
use mongodb::bson::doc;
|
|
|
|
use compliance_agent::database::{Database, DatabasePool};
|
|
use compliance_agent::lifecycle::{
|
|
recover_orphaned_runs, sweep_werkbank_leases, INTERRUPTED_MESSAGE,
|
|
};
|
|
use compliance_agent::werkbank::JobQueue;
|
|
use compliance_core::models::dast::{DastScanRun, DastScanStatus};
|
|
use compliance_core::models::graph::{GraphBuildRun, GraphBuildStatus};
|
|
use compliance_core::models::pentest::{PentestSession, PentestStatus, PentestStrategy};
|
|
use compliance_core::models::werkbank::{Executor, InputRef, Job, JobStatus};
|
|
use compliance_core::models::{ScanRun, ScanRunStatus, ScanTrigger};
|
|
|
|
const TENANT_A: &str = "00000000-0000-0000-0000-0000000000aa";
|
|
const TENANT_B: &str = "00000000-0000-0000-0000-0000000000bb";
|
|
|
|
/// A pool over a unique db prefix with two tenant databases, or `None` if no
|
|
/// Mongo is reachable.
|
|
async fn setup() -> Option<(DatabasePool, Database, Database)> {
|
|
let uri = std::env::var("TEST_MONGODB_URI")
|
|
.unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into());
|
|
// Short and unique: parallel runs must not see each other's tenants, and
|
|
// Mongo caps database names at 63 bytes.
|
|
let prefix = format!("lc_{}", &uuid::Uuid::new_v4().simple().to_string()[..10]);
|
|
let Ok(pool) = DatabasePool::connect(&uri, &prefix).await else {
|
|
eprintln!("SKIP lifecycle: no MongoDB reachable at {uri}");
|
|
return None;
|
|
};
|
|
let a = pool.for_tenant_id(TENANT_A).await.expect("tenant A db");
|
|
let b = pool.for_tenant_id(TENANT_B).await.expect("tenant B db");
|
|
Some((pool, a, b))
|
|
}
|
|
|
|
async fn teardown(pool: &DatabasePool) {
|
|
for tenant in [TENANT_A, TENANT_B] {
|
|
pool.drop_tenant(tenant).await.ok();
|
|
}
|
|
}
|
|
|
|
fn run_with(status: ScanRunStatus) -> ScanRun {
|
|
let mut run = ScanRun::new("repo-1".into(), ScanTrigger::Manual);
|
|
run.status = status;
|
|
run
|
|
}
|
|
|
|
fn session_with(status: PentestStatus) -> PentestSession {
|
|
let mut session = PentestSession::new("target-1".into(), PentestStrategy::Quick);
|
|
session.status = status;
|
|
session
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn restart_closes_open_runs_in_every_tenant_and_nothing_else() {
|
|
let Some((pool, a, b)) = setup().await else {
|
|
return;
|
|
};
|
|
let now = Utc.timestamp_opt(1_800_000_000, 0).unwrap();
|
|
|
|
// Arrange: tenant A has one open record of each kind plus finished ones
|
|
// that must not change; tenant B has a single open scan.
|
|
let open_scan = a
|
|
.scan_runs()
|
|
.insert_one(run_with(ScanRunStatus::Running))
|
|
.await
|
|
.unwrap()
|
|
.inserted_id;
|
|
let done_scan = a
|
|
.scan_runs()
|
|
.insert_one(run_with(ScanRunStatus::Completed))
|
|
.await
|
|
.unwrap()
|
|
.inserted_id;
|
|
a.graph_builds()
|
|
.insert_one(GraphBuildRun::new("repo-1".into()))
|
|
.await
|
|
.unwrap();
|
|
a.dast_scan_runs()
|
|
.insert_one(DastScanRun::new("target-1".into()))
|
|
.await
|
|
.unwrap();
|
|
let paused = a
|
|
.pentest_sessions()
|
|
.insert_one(session_with(PentestStatus::Paused))
|
|
.await
|
|
.unwrap()
|
|
.inserted_id;
|
|
a.pentest_sessions()
|
|
.insert_one(session_with(PentestStatus::Completed))
|
|
.await
|
|
.unwrap();
|
|
let open_in_b = b
|
|
.scan_runs()
|
|
.insert_one(run_with(ScanRunStatus::Running))
|
|
.await
|
|
.unwrap()
|
|
.inserted_id;
|
|
|
|
// Act
|
|
let closed = recover_orphaned_runs(&pool, now).await.unwrap();
|
|
|
|
// Assert: 4 open records in A (scan, graph, DAST, paused pentest) + 1 in B.
|
|
assert_eq!(closed, 5);
|
|
|
|
let scan = a
|
|
.scan_runs()
|
|
.find_one(doc! { "_id": &open_scan })
|
|
.await
|
|
.unwrap()
|
|
.expect("scan run");
|
|
assert_eq!(scan.status, ScanRunStatus::Interrupted);
|
|
assert_eq!(scan.error_message.as_deref(), Some(INTERRUPTED_MESSAGE));
|
|
assert_eq!(scan.completed_at, Some(now));
|
|
|
|
let untouched = a
|
|
.scan_runs()
|
|
.find_one(doc! { "_id": &done_scan })
|
|
.await
|
|
.unwrap()
|
|
.expect("finished scan run");
|
|
assert_eq!(untouched.status, ScanRunStatus::Completed);
|
|
assert_eq!(untouched.error_message, None);
|
|
|
|
let graph = a.graph_builds().find_one(doc! {}).await.unwrap().unwrap();
|
|
assert_eq!(graph.status, GraphBuildStatus::Failed);
|
|
let dast = a.dast_scan_runs().find_one(doc! {}).await.unwrap().unwrap();
|
|
assert_eq!(dast.status, DastScanStatus::Failed);
|
|
assert_eq!(dast.error_message.as_deref(), Some(INTERRUPTED_MESSAGE));
|
|
|
|
let session = a
|
|
.pentest_sessions()
|
|
.find_one(doc! { "_id": &paused })
|
|
.await
|
|
.unwrap()
|
|
.expect("paused session");
|
|
assert_eq!(session.status, PentestStatus::Failed);
|
|
assert_eq!(
|
|
a.pentest_sessions()
|
|
.count_documents(doc! { "status": "completed" })
|
|
.await
|
|
.unwrap(),
|
|
1
|
|
);
|
|
|
|
let in_b = b
|
|
.scan_runs()
|
|
.find_one(doc! { "_id": &open_in_b })
|
|
.await
|
|
.unwrap()
|
|
.expect("tenant B scan run");
|
|
assert_eq!(in_b.status, ScanRunStatus::Interrupted);
|
|
|
|
// A second start finds nothing left to close.
|
|
assert_eq!(recover_orphaned_runs(&pool, now).await.unwrap(), 0);
|
|
|
|
teardown(&pool).await;
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn sweep_requeues_expired_leases_in_every_tenant() {
|
|
let Some((pool, a, b)) = setup().await else {
|
|
return;
|
|
};
|
|
let t0 = Utc.timestamp_opt(1_800_000_000, 0).unwrap();
|
|
|
|
// Arrange: one leased job per tenant, each with a 10 s lease.
|
|
for (db, id) in [(&a, "job-a"), (&b, "job-b")] {
|
|
let queue = JobQueue::new(db);
|
|
let job = Job::plc_provision(id, "tenant", "target-1", InputRef::blob("sha256:abc"), 180);
|
|
queue.enqueue(job, t0).await.unwrap();
|
|
queue
|
|
.lease(
|
|
"runner-1",
|
|
Executor::Docker,
|
|
&[],
|
|
Duration::from_secs(10),
|
|
t0,
|
|
)
|
|
.await
|
|
.unwrap()
|
|
.expect("lease");
|
|
}
|
|
|
|
// Act: before the leases expire nothing moves; after, both are requeued.
|
|
let early = sweep_werkbank_leases(&pool, t0, 3).await.unwrap();
|
|
let late = sweep_werkbank_leases(&pool, t0 + chrono::Duration::seconds(60), 3)
|
|
.await
|
|
.unwrap();
|
|
|
|
// Assert
|
|
assert_eq!((early.requeued, early.expired), (0, 0));
|
|
assert_eq!((late.requeued, late.expired), (2, 0));
|
|
for (db, id) in [(&a, "job-a"), (&b, "job-b")] {
|
|
let record = JobQueue::new(db).get(id).await.unwrap().expect("job");
|
|
assert_eq!(record.status, JobStatus::Queued);
|
|
}
|
|
|
|
teardown(&pool).await;
|
|
}
|