Files
pruefwerk/compliance-agent/src/targets.rs
T
sharang dd46af6f24
CI / Check (push) Skipped
CI / Agent integration (push) Skipped
CI / Detect Changes (push) Successful in 4s
CI / Deploy Docs (push) Skipped
CI / Deploy MCP (push) Skipped
CI / Deploy Dashboard (push) Successful in 4m31s
CI / Deploy Agent (push) Successful in 6m2s
fix(metering): a demo target given the tenant's own sources counts under the cap (#1080)
2026-11-29 09:56:18 +00:00

336 lines
12 KiB
Rust

//! Target lifecycle shared by the onboarding API and the demo seeder:
//! create → attach/upload artifact → detect. The HTTP handlers in
//! [`crate::api::handlers::onboarding`] are thin wrappers over these so an
//! in-process caller (the seeder, `demo/reset`) takes the exact same path —
//! same records, same usage events — without an HTTP self-call.
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use mongodb::bson::{doc, oid::ObjectId, to_bson};
use compliance_core::models::{Artifact, ArtifactKind, OnboardedTarget, PlcFormat};
use crate::agent::ComplianceAgent;
use crate::classify::{classify_target, MockFirmwareDetector};
use crate::database::Database;
use crate::error::AgentError;
/// Whether one more counted target fits under `cap`: the active targets
/// other than demo ones are fewer.
///
/// # Errors
///
/// [`AgentError::TargetLimit`] when they are not; a database error.
async fn room_for_one(db: &Database, cap: u32) -> Result<(), AgentError> {
let counted = db
.onboarded_targets()
.count_documents(doc! { "archived_at": null, "demo": { "$ne": true } })
.await?;
if counted >= u64::from(cap) {
return Err(AgentError::TargetLimit(cap));
}
Ok(())
}
/// Make a demo target the tenant's own before its artifacts change: from
/// then on it counts under the plan's cap like any other target. Without
/// that, a demo target pointed at the tenant's own code would sit outside
/// the cap. A target that is not a demo one is left as it is, and an
/// archived one is not checked against the cap (it does not count yet).
///
/// # Errors
///
/// [`AgentError::TargetLimit`] when the plan has no room for one more
/// counted target; the target then stays a demo one. A database error.
pub async fn claim_demo(
agent: &ComplianceAgent,
db: &Database,
tenant_id: &str,
target: &OnboardedTarget,
) -> Result<(), AgentError> {
let Some(id) = target.id.filter(|_| target.demo) else {
return Ok(());
};
if target.archived_at.is_none() {
if let Some(cap) = agent.plan(tenant_id).await.and_then(|p| p.target_cap()) {
room_for_one(db, cap).await?;
}
}
db.onboarded_targets()
.update_one(doc! { "_id": id }, doc! { "$unset": { "demo": "" } })
.await?;
Ok(())
}
/// Whether two artifact lists point at the same sources: the same kinds and
/// references, in any order. Credentials, branches and scan state may
/// differ; the dashboard's editor sends every artifact on each save.
pub fn same_sources(a: &[Artifact], b: &[Artifact]) -> bool {
let mut taken = vec![false; b.len()];
a.len() == b.len()
&& a.iter().all(|x| {
let found = (0..b.len())
.find(|&i| !taken[i] && b[i].kind == x.kind && b[i].source_ref == x.source_ref);
found.map(|i| taken[i] = true).is_some()
})
}
/// Insert a new target for `tenant_id` and emit the `target.added` usage
/// event: what every way of adding a target does (the API, accepting a
/// supplier's SBOM release, Managed Git, the demo seeder), so each counts
/// the same under the plan. Returns the stored record with its id set.
///
/// # Errors
///
/// [`AgentError::TargetLimit`] when the plan has no room for another active
/// target (the entry plan's `extra_targets: 0`); demo targets are outside
/// that count. A database error.
pub async fn create_target(
agent: &ComplianceAgent,
db: &Database,
tenant_id: &str,
mut target: OnboardedTarget,
) -> Result<OnboardedTarget, AgentError> {
// The plan is read once for the cap and the billing. Without an answer
// from the registry the target is added, as a scan then runs unmetered.
let plan = agent.plan(tenant_id).await;
// Demo targets are outside the cap: neither refused nor counted.
if let Some(cap) = plan.and_then(|p| p.target_cap()).filter(|_| !target.demo) {
room_for_one(db, cap).await?;
}
let res = db.onboarded_targets().insert_one(&target).await?;
target.id = res.inserted_id.as_object_id();
// A target beyond the plan's included ones is extra from the start (t72).
if let Some(plan) = plan {
if let Some((_, billing)) = agent
.assign_billing(tenant_id, db, plan.billed_included())
.await
.into_iter()
.find(|(id, _)| Some(*id) == target.id)
{
target.billing = billing;
}
}
let target_id = target.id.map(|id| id.to_hex()).unwrap_or_default();
agent.emit_usage(
tenant_id,
"target.added",
format!("target:{tenant_id}:{target_id}"),
serde_json::json!({ "target_id": target_id, "target_type": format!("{:?}", target.target_type) }),
);
Ok(target)
}
/// Largest file one upload may carry.
pub const MAX_UPLOAD_BYTES: u64 = 512 * 1024 * 1024;
/// Where an uploaded file for `target_id` goes:
/// `<base>/uploads/<target_id>/<uuid>_<safe filename>`. Creates the directory.
///
/// # Errors
///
/// Returns an error if the upload directory cannot be created.
pub fn upload_dest(
agent: &ComplianceAgent,
target_id: &str,
filename: &str,
) -> Result<PathBuf, AgentError> {
let safe_name: String = filename
.chars()
.map(|c| {
if c.is_ascii_alphanumeric() || matches!(c, '.' | '-' | '_') {
c
} else {
'_'
}
})
.collect();
let dir = Path::new(&agent.config.artifact_store_base_path)
.join("uploads")
.join(target_id);
std::fs::create_dir_all(&dir)?;
Ok(dir.join(format!("{}_{safe_name}", uuid::Uuid::new_v4())))
}
/// Write bytes that are already in memory (the bundled demo fixtures) to their
/// upload location and return the path. User uploads are streamed instead.
///
/// # Errors
///
/// Returns an error if the directory or the file cannot be written.
pub fn store_upload(
agent: &ComplianceAgent,
target_id: &str,
filename: &str,
bytes: &[u8],
) -> Result<PathBuf, AgentError> {
let dest = upload_dest(agent, target_id, filename)?;
std::fs::write(&dest, bytes)?;
Ok(dest)
}
/// Build the artifact record for an uploaded file. `None` for kinds that are
/// references, not files (git repo, live URL, container ref, text) — those go
/// through [`Artifact`]'s constructors directly.
pub fn uploaded_artifact(
kind: ArtifactKind,
plc_format: Option<PlcFormat>,
filename: &str,
stored_path: &Path,
size_bytes: u64,
) -> Option<Artifact> {
let mut artifact = match kind {
ArtifactKind::PlcProject => {
Artifact::plc_project(filename, plc_format.unwrap_or(PlcFormat::PlcopenXml))
}
ArtifactKind::FirmwareImage => Artifact::firmware_image(filename),
ArtifactKind::SourceArchive => Artifact::source_archive(filename),
ArtifactKind::MobilePackage => Artifact::mobile_package(filename),
ArtifactKind::BuildOutput => Artifact::build_output(filename),
ArtifactKind::SupplierSbom => Artifact::supplier_sbom(filename),
_ => return None,
};
artifact.stored_path = Some(stored_path.to_string_lossy().to_string());
artifact.size_bytes = Some(size_bytes);
Some(artifact)
}
/// Build a reference-style artifact (git repo, live URL, container image,
/// plaintext) or a file artifact whose content is not uploaded here. The
/// onboarding API's `ArtifactInput` and the demo seeder share this so a seeded
/// target is indistinguishable from one a user onboarded.
pub fn reference_artifact(
kind: ArtifactKind,
source_ref: String,
branch: Option<String>,
plc_format: Option<PlcFormat>,
) -> Artifact {
match kind {
ArtifactKind::GitRepo => {
Artifact::git_repo(source_ref, branch.unwrap_or_else(|| "main".to_string()))
}
ArtifactKind::LiveUrl => Artifact::live_url(source_ref),
ArtifactKind::FirmwareImage => Artifact::firmware_image(source_ref),
ArtifactKind::SourceArchive => Artifact::source_archive(source_ref),
ArtifactKind::MobilePackage => Artifact::mobile_package(source_ref),
ArtifactKind::ContainerImage => Artifact::container_image(source_ref),
ArtifactKind::PlcProject => {
Artifact::plc_project(source_ref, plc_format.unwrap_or(PlcFormat::PlcopenXml))
}
ArtifactKind::PlaintextDescription => Artifact::plaintext(source_ref),
ArtifactKind::BuildOutput => Artifact::build_output(source_ref),
ArtifactKind::SupplierSbom => Artifact::supplier_sbom(source_ref),
}
}
/// Append an artifact to an existing target.
pub async fn attach_artifact(
db: &Database,
target_oid: ObjectId,
artifact: &Artifact,
) -> Result<(), AgentError> {
let artifact = to_bson(artifact).map_err(|e| AgentError::Other(e.to_string()))?;
db.onboarded_targets()
.update_one(
doc! { "_id": target_oid },
doc! { "$push": { "artifacts": artifact }, "$set": { "updated_at": mongodb::bson::DateTime::now() } },
)
.await?;
Ok(())
}
/// Lightweight detection: classify the target from its artifact kinds (no
/// ingest / clone), persist the classification and return the updated record.
/// `Ok(None)` when the target does not exist.
pub async fn detect_target(
db: &Database,
target_oid: ObjectId,
) -> Result<Option<OnboardedTarget>, AgentError> {
let Some(mut target) = db
.onboarded_targets()
.find_one(doc! { "_id": target_oid })
.await?
else {
return Ok(None);
};
// No ingested working paths here → kind-based classification only; the mock
// firmware detector is never invoked (no firmware working path present).
let empty = HashMap::new();
let detector = MockFirmwareDetector { detection: None };
let classification = classify_target(&target, &empty, &detector).await?;
let classification_bson =
to_bson(&classification).map_err(|e| AgentError::Other(e.to_string()))?;
db.onboarded_targets()
.update_one(
doc! { "_id": target_oid },
doc! { "$set": { "classification": classification_bson, "updated_at": mongodb::bson::DateTime::now() } },
)
.await?;
target.classification = Some(classification);
Ok(Some(target))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn only_another_source_changes_a_targets_sources() {
let repo = Artifact::git_repo("https://git.example/demo.git", "main");
let site = Artifact::live_url("https://demo.example");
let other_branch = Artifact::git_repo("https://git.example/demo.git", "dev");
let own = Artifact::git_repo("https://git.example/own.git", "main");
let both = [repo.clone(), site.clone()];
let reordered = [site, repo.clone()];
let just_repo = std::slice::from_ref(&repo);
let repo_twice = [repo.clone(), repo.clone()];
assert!(same_sources(&both, &reordered));
assert!(
same_sources(just_repo, &[other_branch]),
"a branch is no new source"
);
assert!(!same_sources(just_repo, &[own]));
assert!(!same_sources(just_repo, &both));
assert!(!same_sources(&repo_twice, just_repo));
}
#[test]
fn uploaded_artifact_records_stored_path_for_file_kinds() {
let a = uploaded_artifact(
ArtifactKind::PlcProject,
Some(PlcFormat::StructuredText),
"pump.st",
Path::new("/data/uploads/x/uuid_pump.st"),
42,
)
.expect("file kind");
assert_eq!(a.kind, ArtifactKind::PlcProject);
assert_eq!(a.source_ref, "pump.st");
assert_eq!(
a.stored_path.as_deref(),
Some("/data/uploads/x/uuid_pump.st")
);
assert_eq!(a.size_bytes, Some(42));
assert_eq!(
a.plc.as_ref().map(|p| p.format),
Some(PlcFormat::StructuredText)
);
}
#[test]
fn uploaded_artifact_rejects_reference_kinds() {
for kind in [
ArtifactKind::GitRepo,
ArtifactKind::LiveUrl,
ArtifactKind::ContainerImage,
ArtifactKind::PlaintextDescription,
] {
assert!(uploaded_artifact(kind, None, "f", Path::new("/p"), 1).is_none());
}
}
}