225 lines
7.7 KiB
Rust
225 lines
7.7 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;
|
|
|
|
/// Insert a new target for `tenant_id` and emit the `target.added` usage
|
|
/// event. Returns the stored record with its id set.
|
|
pub async fn create_target(
|
|
agent: &ComplianceAgent,
|
|
db: &Database,
|
|
tenant_id: &str,
|
|
mut target: OnboardedTarget,
|
|
) -> Result<OnboardedTarget, AgentError> {
|
|
let res = db.onboarded_targets().insert_one(&target).await?;
|
|
target.id = res.inserted_id.as_object_id();
|
|
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),
|
|
_ => 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),
|
|
}
|
|
}
|
|
|
|
/// 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 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());
|
|
}
|
|
}
|
|
}
|