feat(retention): deleting a target or erasing a tenant removes its files (#289) #355
No files matched your search
@@ -294,7 +294,23 @@ pub async fn update_target(
|
||||
get_target(Extension(agent), tenant, Path(id)).await
|
||||
}
|
||||
|
||||
/// DELETE /api/v1/targets/{id} — remove the target and its findings/scans.
|
||||
/// Remove a deleted target's clones, uploads, work trees and blobs from disk.
|
||||
/// Best-effort: a path that cannot be removed is logged, and the deletion of
|
||||
/// the records stands.
|
||||
async fn remove_target_files(agent: &ComplianceAgent, tenant_id: &str, target: &OnboardedTarget) {
|
||||
let config = agent.config.clone();
|
||||
let paths = crate::retention::target_paths(&config, tenant_id, target);
|
||||
let removal = tokio::task::spawn_blocking(move || crate::retention::remove(&config, &paths))
|
||||
.await
|
||||
.unwrap_or_default();
|
||||
for failure in &removal.failed {
|
||||
tracing::warn!("target files not removed: {failure}");
|
||||
}
|
||||
tracing::info!(removed = removal.removed, "target files removed");
|
||||
}
|
||||
|
||||
/// DELETE /api/v1/targets/{id} — remove the target, its findings/scans and
|
||||
/// its files on disk.
|
||||
#[tracing::instrument(skip_all, fields(target_id = %id))]
|
||||
pub async fn delete_target(
|
||||
Extension(agent): AgentExt,
|
||||
@@ -303,10 +319,19 @@ pub async fn delete_target(
|
||||
) -> Result<Json<serde_json::Value>, StatusCode> {
|
||||
let oid = parse_oid(&id)?;
|
||||
let db = tenant_db(&agent, &tenant).await?;
|
||||
// Read first: its name and artifacts say where its files are on disk.
|
||||
let stored = db
|
||||
.onboarded_targets()
|
||||
.find_one(doc! { "_id": oid })
|
||||
.await
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
db.onboarded_targets()
|
||||
.delete_one(doc! { "_id": oid })
|
||||
.await
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
if let Some(target) = stored {
|
||||
remove_target_files(&agent, &tenant.0.tenant_id, &target).await;
|
||||
}
|
||||
// Cascade all data keyed by repo_id == target id (best-effort).
|
||||
let db = &db;
|
||||
let _ = db.findings().delete_many(doc! { "repo_id": &id }).await;
|
||||
|
||||
@@ -247,7 +247,8 @@ pub async fn export(
|
||||
}
|
||||
|
||||
/// `DELETE /api/v1/platform/tenants/{id}/data` — GDPR erasure: drops the
|
||||
/// tenant database. Requires `{"confirm": "<slug or id>"}`.
|
||||
/// tenant database and removes its code from disk (clones, uploads, work
|
||||
/// trees, blobs, runner artifacts). Requires `{"confirm": "<slug or id>"}`.
|
||||
pub async fn delete_data(
|
||||
State(st): State<PlatformState>,
|
||||
Path(tenant_id): Path<String>,
|
||||
@@ -257,17 +258,43 @@ pub async fn delete_data(
|
||||
if confirm.is_empty() {
|
||||
return Err(StatusCode::BAD_REQUEST);
|
||||
}
|
||||
// Where the tenant's code lies on disk, read before its records go.
|
||||
let config = st.agent.config.clone();
|
||||
let mut paths = crate::retention::tenant_paths(&config, &tenant_id);
|
||||
let db = st
|
||||
.agent
|
||||
.db_pool
|
||||
.for_tenant_id(&tenant_id)
|
||||
.await
|
||||
.map_err(internal)?;
|
||||
let targets: Vec<compliance_core::models::OnboardedTarget> =
|
||||
match db.onboarded_targets().find(mongodb::bson::doc! {}).await {
|
||||
Ok(cursor) => super::collect_cursor_async(cursor).await,
|
||||
Err(e) => return Err(internal(e)),
|
||||
};
|
||||
for target in &targets {
|
||||
paths.extend(crate::retention::target_paths(&config, &tenant_id, target));
|
||||
}
|
||||
st.agent
|
||||
.db_pool
|
||||
.drop_tenant(&tenant_id)
|
||||
.await
|
||||
.map_err(internal)?;
|
||||
let removal = tokio::task::spawn_blocking(move || crate::retention::remove(&config, &paths))
|
||||
.await
|
||||
.unwrap_or_default();
|
||||
for failure in &removal.failed {
|
||||
tracing::warn!(tenant_id, "tenant files not removed: {failure}");
|
||||
}
|
||||
if let Some(r) = &st.agent.registry {
|
||||
r.invalidate(&tenant_id);
|
||||
}
|
||||
Ok(Json(
|
||||
serde_json::json!({ "status": "deleted", "tenant_id": tenant_id }),
|
||||
))
|
||||
Ok(Json(serde_json::json!({
|
||||
"status": "deleted",
|
||||
"tenant_id": tenant_id,
|
||||
"files_removed": removal.removed,
|
||||
"files_not_removed": removal.failed.len(),
|
||||
})))
|
||||
}
|
||||
|
||||
/// `POST /api/v1/platform/tenants/demo/reset` — drops and re-creates the
|
||||
|
||||
@@ -18,6 +18,7 @@ pub mod pentest;
|
||||
pub mod pipeline;
|
||||
pub mod rag;
|
||||
pub mod registry;
|
||||
pub mod retention;
|
||||
pub mod scan_gate;
|
||||
pub mod scheduler;
|
||||
pub mod secrets;
|
||||
|
||||
@@ -0,0 +1,195 @@
|
||||
//! What a target or a tenant leaves on disk, and removing it (#289).
|
||||
//!
|
||||
//! A customer's source code sits in clones, uploads, unpacked work trees and
|
||||
//! content-addressed blobs. Deleting a target or erasing a tenant must remove
|
||||
//! those too, not only the database records: on a small node it is disk, and
|
||||
//! for customer code it is GDPR erasure. Only paths inside the configured
|
||||
//! base directories are ever removed.
|
||||
|
||||
use std::io::ErrorKind;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use compliance_core::models::{ArtifactKind, OnboardedTarget};
|
||||
use compliance_core::AgentConfig;
|
||||
|
||||
use crate::pipeline::git::clone_dir;
|
||||
use crate::tenant_path::tenant_segment;
|
||||
|
||||
/// What a removal did.
|
||||
#[derive(Debug, Default, PartialEq, Eq)]
|
||||
pub struct Removal {
|
||||
/// Paths that existed and were removed.
|
||||
pub removed: usize,
|
||||
/// Paths that could not be removed, with why.
|
||||
pub failed: Vec<String>,
|
||||
}
|
||||
|
||||
/// Every path on disk that holds data of `target` (of `tenant_id`).
|
||||
pub fn target_paths(
|
||||
config: &AgentConfig,
|
||||
tenant_id: &str,
|
||||
target: &OnboardedTarget,
|
||||
) -> Vec<PathBuf> {
|
||||
let artifacts = Path::new(&config.artifact_store_base_path);
|
||||
let clones = Path::new(&config.git_clone_base_path);
|
||||
let target_id = target.id.map(|id| id.to_hex()).unwrap_or_default();
|
||||
let mut paths = Vec::new();
|
||||
if !target_id.is_empty() {
|
||||
paths.push(artifacts.join("uploads").join(&target_id));
|
||||
paths.push(artifacts.join("work").join(&target_id));
|
||||
}
|
||||
// The scan clones under the target's name, ingest under the artifact id.
|
||||
paths.push(clone_dir(clones, tenant_id, &target.name));
|
||||
for artifact in &target.artifacts {
|
||||
match artifact.kind {
|
||||
ArtifactKind::GitRepo => paths.push(clone_dir(clones, tenant_id, &artifact.id)),
|
||||
_ => {
|
||||
// A blob is a cache of the upload, keyed by its sha256.
|
||||
if let Some(sha) = artifact.content_hash.as_deref().filter(|s| is_sha256(s)) {
|
||||
paths.push(artifacts.join("blobs").join(&sha[..2]).join(sha));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
paths
|
||||
}
|
||||
|
||||
/// The directories that hold only `tenant_id`'s data: its clones and its
|
||||
/// runner artifacts. Per-target paths come from [`target_paths`].
|
||||
pub fn tenant_paths(config: &AgentConfig, tenant_id: &str) -> Vec<PathBuf> {
|
||||
let segment = tenant_segment(tenant_id);
|
||||
vec![
|
||||
Path::new(&config.git_clone_base_path).join(&segment),
|
||||
Path::new(&config.artifact_store_base_path)
|
||||
.join("tenants")
|
||||
.join(&segment),
|
||||
]
|
||||
}
|
||||
|
||||
/// Remove `paths` (files or directories). A path outside both base
|
||||
/// directories is refused, and one that is already gone is not an error.
|
||||
/// Blocking; call it from `spawn_blocking`.
|
||||
pub fn remove(config: &AgentConfig, paths: &[PathBuf]) -> Removal {
|
||||
let bases = [
|
||||
Path::new(&config.artifact_store_base_path),
|
||||
Path::new(&config.git_clone_base_path),
|
||||
];
|
||||
let mut removal = Removal::default();
|
||||
for path in paths {
|
||||
let inside = bases
|
||||
.iter()
|
||||
.any(|base| path.starts_with(base) && path != *base);
|
||||
if !inside {
|
||||
removal
|
||||
.failed
|
||||
.push(format!("{}: outside the data directories", path.display()));
|
||||
continue;
|
||||
}
|
||||
let result = match std::fs::symlink_metadata(path) {
|
||||
Ok(meta) if meta.is_dir() => std::fs::remove_dir_all(path),
|
||||
Ok(_) => std::fs::remove_file(path),
|
||||
Err(e) => Err(e),
|
||||
};
|
||||
match result {
|
||||
Ok(()) => removal.removed += 1,
|
||||
Err(e) if e.kind() == ErrorKind::NotFound => {}
|
||||
Err(e) => removal.failed.push(format!("{}: {e}", path.display())),
|
||||
}
|
||||
}
|
||||
removal
|
||||
}
|
||||
|
||||
fn is_sha256(s: &str) -> bool {
|
||||
s.len() == 64 && s.bytes().all(|b| b.is_ascii_hexdigit())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[allow(clippy::expect_used)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use compliance_core::models::{Artifact, TargetType};
|
||||
|
||||
fn config(root: &Path) -> AgentConfig {
|
||||
AgentConfig {
|
||||
artifact_store_base_path: root.join("artifacts").to_string_lossy().into(),
|
||||
git_clone_base_path: root.join("repos").to_string_lossy().into(),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deleting_a_target_removes_its_code_and_nothing_else() {
|
||||
let root = std::env::temp_dir().join(format!("cs-retention-{}", uuid::Uuid::new_v4()));
|
||||
let cfg = config(&root);
|
||||
let mut target = OnboardedTarget::new("sensor-node".into(), TargetType::FirmwareRtos);
|
||||
target.id = Some(mongodb::bson::oid::ObjectId::new());
|
||||
let id = target.id.map(|i| i.to_hex()).unwrap_or_default();
|
||||
let sha = "ab".repeat(32);
|
||||
let mut upload = Artifact::source_archive("fw.tar.gz");
|
||||
upload.content_hash = Some(sha.clone());
|
||||
let repo = Artifact::git_repo("https://git.example.com/fw.git", "main");
|
||||
target.artifacts = vec![upload, repo.clone()];
|
||||
|
||||
let paths = target_paths(&cfg, "t1", &target);
|
||||
let own = [
|
||||
root.join("artifacts/uploads").join(&id).join("x_fw.tar.gz"),
|
||||
root.join("artifacts/work").join(&id).join("a1/main.c"),
|
||||
root.join("artifacts/blobs").join(&sha[..2]).join(&sha),
|
||||
clone_dir(&root.join("repos"), "t1", "sensor-node").join("README"),
|
||||
clone_dir(&root.join("repos"), "t1", &repo.id).join("README"),
|
||||
];
|
||||
let other = root.join("artifacts/uploads/other-target/keep.zip");
|
||||
for file in own.iter().chain([&other]) {
|
||||
std::fs::create_dir_all(file.parent().expect("parent")).expect("mkdir");
|
||||
std::fs::write(file, b"x").expect("write");
|
||||
}
|
||||
|
||||
let removal = remove(&cfg, &paths);
|
||||
|
||||
assert!(removal.failed.is_empty(), "{:?}", removal.failed);
|
||||
assert_eq!(removal.removed, 5);
|
||||
for file in &own {
|
||||
assert!(!file.exists(), "{} survived", file.display());
|
||||
}
|
||||
assert!(other.exists(), "another target's upload is kept");
|
||||
// Removing again finds nothing and is not an error.
|
||||
assert_eq!(remove(&cfg, &paths), Removal::default());
|
||||
std::fs::remove_dir_all(&root).ok();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nothing_outside_the_data_directories_is_touched() {
|
||||
let root = std::env::temp_dir().join(format!("cs-retention-{}", uuid::Uuid::new_v4()));
|
||||
let cfg = config(&root);
|
||||
let outside = root.join("elsewhere/secret.txt");
|
||||
std::fs::create_dir_all(outside.parent().expect("parent")).expect("mkdir");
|
||||
std::fs::write(&outside, b"x").expect("write");
|
||||
|
||||
let removal = remove(
|
||||
&cfg,
|
||||
&[
|
||||
outside.clone(),
|
||||
root.join("artifacts"),
|
||||
PathBuf::from("/etc/passwd"),
|
||||
],
|
||||
);
|
||||
|
||||
assert_eq!(removal.removed, 0);
|
||||
assert_eq!(removal.failed.len(), 3, "{:?}", removal.failed);
|
||||
assert!(outside.exists());
|
||||
std::fs::remove_dir_all(&root).ok();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_tenant_owns_its_clones_and_runner_artifacts() {
|
||||
let cfg = config(Path::new("/data"));
|
||||
let paths = tenant_paths(&cfg, "acme");
|
||||
assert_eq!(
|
||||
paths,
|
||||
[
|
||||
PathBuf::from("/data/repos/acme"),
|
||||
PathBuf::from("/data/artifacts/tenants/acme"),
|
||||
]
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
//! Deleting a target removes its files from disk, not only its records
|
||||
//! (#289). Drives the real API against a live Mongo (`TEST_MONGODB_URI`).
|
||||
|
||||
#![allow(clippy::expect_used, clippy::unwrap_used)]
|
||||
|
||||
mod common;
|
||||
|
||||
use common::TestServer;
|
||||
|
||||
#[tokio::test]
|
||||
async fn deleting_a_target_removes_its_upload() {
|
||||
let server = TestServer::start().await;
|
||||
let created: serde_json::Value = server
|
||||
.post(
|
||||
"/api/v1/targets",
|
||||
&serde_json::json!({ "name": "to-delete", "target_type": "firmware_rtos" }),
|
||||
)
|
||||
.await
|
||||
.json()
|
||||
.await
|
||||
.unwrap();
|
||||
let id = created["data"]["_id"]["$oid"].as_str().unwrap().to_string();
|
||||
let form = reqwest::multipart::Form::new()
|
||||
.text("kind", "source_archive")
|
||||
.part(
|
||||
"file",
|
||||
reqwest::multipart::Part::bytes(b"int main(void) { return 0; }\n".to_vec())
|
||||
.file_name("main.c"),
|
||||
);
|
||||
let uploaded = server
|
||||
.client
|
||||
.post(format!(
|
||||
"{}/api/v1/targets/{id}/artifacts/upload",
|
||||
server.base_url
|
||||
))
|
||||
.multipart(form)
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(uploaded.status().is_success(), "{}", uploaded.status());
|
||||
// The test config's artifact store (see common::dev_config).
|
||||
let upload_dir =
|
||||
std::path::Path::new("/tmp/compliance-scanner-tests/artifacts/uploads").join(&id);
|
||||
assert!(upload_dir.exists(), "the upload is on disk");
|
||||
|
||||
let deleted = server.delete(&format!("/api/v1/targets/{id}")).await;
|
||||
|
||||
assert!(deleted.status().is_success());
|
||||
assert!(!upload_dir.exists(), "the upload is gone with the target");
|
||||
server.cleanup().await;
|
||||
}
|
||||
@@ -27,6 +27,7 @@ export default withMermaid(defineConfig({
|
||||
{ text: 'Demo Targets', link: '/guide/demo-targets' },
|
||||
{ text: 'Understanding Findings', link: '/guide/findings' },
|
||||
{ text: 'Findings from Manual Tests', link: '/guide/manual-findings' },
|
||||
{ text: 'Data and Retention', link: '/guide/data-retention' },
|
||||
{ text: 'SBOM & Licenses', link: '/guide/sbom' },
|
||||
{ text: 'Issues & Tracking', link: '/guide/issues' },
|
||||
{ text: 'Webhooks & PR Reviews', link: '/guide/webhooks' },
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
# Data and Retention
|
||||
|
||||
What Prüfwerk keeps about a target, where, and when it is removed.
|
||||
|
||||
| Data | Where | Removed when |
|
||||
|---|---|---|
|
||||
| Target, findings, SBOM, CVE alerts, scan runs, code graph | the tenant's MongoDB database | the target is deleted (its records), or the tenant is erased (the whole database) |
|
||||
| Uploaded files (archives, firmware images, PLC projects) | `ARTIFACT_STORE_BASE_PATH/uploads/<target>/` | the target is deleted, or the tenant is erased |
|
||||
| Unpacked upload trees | `ARTIFACT_STORE_BASE_PATH/work/<target>/` | the target is deleted, or the tenant is erased |
|
||||
| Content-addressed copies of uploads | `ARTIFACT_STORE_BASE_PATH/blobs/<sha>` | the target is deleted, or the tenant is erased (a cache: a scan recreates it from the upload) |
|
||||
| Git clones (scan and ingest) | `GIT_CLONE_BASE_PATH/<tenant>/` | the target is deleted (its clones), or the tenant is erased (all of them) |
|
||||
| Werkbank runner artifacts | `ARTIFACT_STORE_BASE_PATH/tenants/<tenant>/` | the tenant is erased |
|
||||
|
||||
Deleting a target (`DELETE /api/v1/targets/{id}`, or **Delete** on the
|
||||
targets page) removes its records and its files. Erasing a tenant
|
||||
(`DELETE /api/v1/platform/tenants/{id}/data`, confirmed) drops its database
|
||||
and removes every file listed above; the response says how many paths were
|
||||
removed and how many could not be. Only paths inside the two configured base
|
||||
directories are ever removed.
|
||||
|
||||
Evidence packs are built on request and not stored.
|
||||
|
||||
Not yet in place: a time-based sweep of files left behind by an interrupted
|
||||
deletion.
|
||||
Reference in new issue
Block a user