From 80eb7f462cf1b7baa8aca572411e87665cec52b6 Mon Sep 17 00:00:00 2001 From: Sharang Parnerkar Date: Fri, 25 Sep 2026 09:59:17 +0000 Subject: [PATCH] feat(ingest): password-protected archives; 7z and rar refused clearly (#370) (#388) --- .../src/api/handlers/onboarding.rs | 140 ++++++++++- .../src/api/handlers/werkbank_jobs.rs | 3 +- compliance-agent/src/api/routes.rs | 6 +- compliance-agent/src/error.rs | 8 + compliance-agent/src/ingest/archive.rs | 229 ++++++++++++++++-- compliance-agent/src/ingest/mod.rs | 179 +++++++++++++- compliance-agent/src/pipeline/orchestrator.rs | 27 ++- compliance-agent/src/pipeline/plc/sbom.rs | 4 +- compliance-agent/tests/archive_password.rs | 126 ++++++++++ .../tests/fixtures/archives/sample.7z | Bin 0 -> 195 bytes .../tests/fixtures/archives/zipcrypto.zip | Bin 0 -> 363 bytes compliance-dashboard/src/i18n/texts.rs | 44 ++++ .../src/infrastructure/onboarding.rs | 99 ++++++++ compliance-dashboard/src/pages/onboarding.rs | 56 ++++- compliance-dashboard/src/pages/targets.rs | 70 +++++- 15 files changed, 936 insertions(+), 55 deletions(-) create mode 100644 compliance-agent/tests/archive_password.rs create mode 100644 compliance-agent/tests/fixtures/archives/sample.7z create mode 100644 compliance-agent/tests/fixtures/archives/zipcrypto.zip diff --git a/compliance-agent/src/api/handlers/onboarding.rs b/compliance-agent/src/api/handlers/onboarding.rs index 660150d..874192a 100644 --- a/compliance-agent/src/api/handlers/onboarding.rs +++ b/compliance-agent/src/api/handlers/onboarding.rs @@ -12,8 +12,8 @@ use mongodb::bson::{doc, oid::ObjectId, to_bson}; use serde::{Deserialize, Serialize}; use compliance_core::models::{ - ArtifactKind, ComplianceProfile, Credentials, Finding, OnboardedTarget, PlcFormat, ScanRun, - TargetType, + ArtifactKind, ComplianceProfile, Credentials, DetectedFact, Finding, OnboardedTarget, + PlcFormat, ScanRun, TargetType, }; use compliance_core::scan_matrix::{applicable_scans, supports_pentest}; use compliance_core::tenant_ctx::TenantCtx; @@ -586,8 +586,21 @@ pub async fn upload_artifact( }; // Non-file kinds (git repo, live URL, container ref, text) use the JSON // add-artifact endpoint, not upload. - let artifact = uploaded_artifact(kind, plc_format, &filename, &upload.path, upload.size) + let mut artifact = uploaded_artifact(kind, plc_format, &filename, &upload.path, upload.size) .ok_or(StatusCode::BAD_REQUEST)?; + if kind != ArtifactKind::FirmwareImage { + match archive_check(upload.path.clone()).await? { + // 7z and rar are never unpacked: say so now, not after a scan. + ArchiveCheck::Unsupported => return Err(StatusCode::UNSUPPORTED_MEDIA_TYPE), + // Kept, and marked: the dashboard asks for the password. + ArchiveCheck::Encrypted => { + artifact + .detected + .push(DetectedFact::new(ARCHIVE_ENCRYPTED_FACT, "true", "upload")) + } + ArchiveCheck::Plain => {} + } + } let artifact_bson = to_bson(&artifact).map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; db.onboarded_targets() @@ -602,6 +615,127 @@ pub async fn upload_artifact( get_target(Extension(agent), tenant, Path(id)).await } +/// The fact an upload records on a password-protected archive. +pub const ARCHIVE_ENCRYPTED_FACT: &str = "archive_encrypted"; + +/// What an uploaded file is, as far as unpacking goes. +enum ArchiveCheck { + /// A 7z or rar archive: refused. + Unsupported, + /// A zip with encrypted entries: needs a password. + Encrypted, + /// Anything else: a plain archive or a single file. + Plain, +} + +/// Check the uploaded file at `path` (on a blocking thread: it reads the file). +/// +/// # Errors +/// +/// 500 when the file cannot be read. +async fn archive_check(path: std::path::PathBuf) -> Result { + use crate::ingest::archive::{self, ArchiveFormat, ExtractError}; + + tokio::task::spawn_blocking(move || { + if archive::unsupported_format(&path)?.is_some() { + return Ok(ArchiveCheck::Unsupported); + } + if ArchiveFormat::sniff(&path)? != Some(ArchiveFormat::Zip) { + return Ok(ArchiveCheck::Plain); + } + Ok(match archive::zip_encryption(&path, None) { + Err(ExtractError::PasswordRequired) => ArchiveCheck::Encrypted, + // A zip that does not open is reported by the scan, like before. + _ => ArchiveCheck::Plain, + }) + }) + .await + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)? + .map_err(|_: std::io::Error| StatusCode::INTERNAL_SERVER_ERROR) +} + +/// The body of [`set_archive_password`]. +#[derive(Debug, Deserialize)] +pub struct ArchivePasswordRequest { + /// The archive's password. + pub password: String, +} + +/// PUT /api/v1/targets/{id}/artifacts/{artifact_id}/archive-password — set the +/// password of an uploaded, password-protected archive. +/// +/// The password is checked against the stored file first, then stored sealed +/// like a git token; the API never returns it. It travels in this JSON body, +/// never in the upload's URL. +/// +/// # Errors +/// +/// 404 without the target or artifact; 409 when the artifact is not a +/// password-protected zip; 422 when the password does not open it; 503 when +/// the deployment has no key to seal it with. +#[tracing::instrument(skip_all, fields(target_id = %id, artifact_id = %artifact_id))] +pub async fn set_archive_password( + Extension(agent): AgentExt, + tenant: TenantCtx, + Path((id, artifact_id)): Path<(String, String)>, + Json(req): Json, +) -> Result { + use crate::ingest::archive::{self, ArchiveFormat, ExtractError}; + + let oid = parse_oid(&id)?; + let db = tenant_db(&agent, &tenant).await?; + let target = db + .onboarded_targets() + .find_one(doc! { "_id": oid }) + .await + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)? + .ok_or(StatusCode::NOT_FOUND)?; + let artifact = target + .artifacts + .iter() + .find(|a| a.id == artifact_id) + .ok_or(StatusCode::NOT_FOUND)?; + let path = crate::ingest::local_source(artifact).map_err(|_| StatusCode::CONFLICT)?; + + let password = req.password.clone(); + let checked = tokio::task::spawn_blocking(move || { + if ArchiveFormat::sniff(&path).ok().flatten() != Some(ArchiveFormat::Zip) { + return Err(StatusCode::CONFLICT); + } + match archive::zip_encryption(&path, Some(password.as_bytes())) { + Ok(true) => Ok(()), + Ok(false) => Err(StatusCode::CONFLICT), + Err(ExtractError::WrongPassword) => Err(StatusCode::UNPROCESSABLE_ENTITY), + Err(_) => Err(StatusCode::CONFLICT), + } + }) + .await + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; + checked?; + + let sealed = agent.secrets.seal(&req.password).map_err(|e| { + tracing::error!("sealing an archive password: {e}"); + StatusCode::SERVICE_UNAVAILABLE + })?; + let auth = compliance_core::models::ArtifactAuth { + method: crate::ingest::ARCHIVE_PASSWORD_METHOD.to_string(), + secret: Some(sealed), + ..Default::default() + }; + let auth = to_bson(&auth).map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; + db.onboarded_targets() + .update_one( + doc! { "_id": oid, "artifacts.id": &artifact_id }, + doc! { "$set": { + "artifacts.$.auth": auth, + "updated_at": mongodb::bson::DateTime::now(), + } }, + ) + .await + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; + Ok(StatusCode::NO_CONTENT) +} + /// Write one multipart field to `dest` as its chunks arrive, refusing more than /// `max` bytes. Returns the number of bytes written. /// diff --git a/compliance-agent/src/api/handlers/werkbank_jobs.rs b/compliance-agent/src/api/handlers/werkbank_jobs.rs index 643a770..3a9d00a 100644 --- a/compliance-agent/src/api/handlers/werkbank_jobs.rs +++ b/compliance-agent/src/api/handlers/werkbank_jobs.rs @@ -295,7 +295,8 @@ pub async fn enqueue( // Extract the control-logic program from the target's PLC-source artifacts // (same selection as the in-process PLC scan). let ctx = crate::ingest::IngestContext::from_config(&agent.config, &req.tenant, &req.target_id); - let ingest_set = crate::ingest::ingest_all(&target, &ctx).map_err(internal)?; + // An artifact that cannot be read simply offers no program below. + let ingest_set = crate::ingest::ingest_all(&target, &ctx); let program = target .artifacts .iter() diff --git a/compliance-agent/src/api/routes.rs b/compliance-agent/src/api/routes.rs index 3aa860d..1f7bee6 100644 --- a/compliance-agent/src/api/routes.rs +++ b/compliance-agent/src/api/routes.rs @@ -1,5 +1,5 @@ use axum::extract::DefaultBodyLimit; -use axum::routing::{delete, get, patch, post}; +use axum::routing::{delete, get, patch, post, put}; use axum::Router; use crate::api::handlers; @@ -44,6 +44,10 @@ pub fn build_router() -> Router { crate::targets::MAX_UPLOAD_BYTES as usize + MULTIPART_OVERHEAD, )), ) + .route( + "/api/v1/targets/{id}/artifacts/{artifact_id}/archive-password", + put(handlers::onboarding::set_archive_password), + ) .route( "/api/v1/targets/{id}/applicable-scans", get(handlers::onboarding::applicable_scans_for_target), diff --git a/compliance-agent/src/error.rs b/compliance-agent/src/error.rs index a1915d9..73e2e61 100644 --- a/compliance-agent/src/error.rs +++ b/compliance-agent/src/error.rs @@ -33,6 +33,14 @@ pub enum AgentError { #[error("Dynamic-execution error: {0}")] Exec(#[from] werkbank_exec::ExecError), + /// An uploaded archive is password-protected and no password is set. + #[error("the archive is password-protected; set its password on the target")] + ArchivePasswordRequired, + + /// The password set for an uploaded archive does not open it. + #[error("the archive password set on the target does not open it")] + ArchivePasswordWrong, + #[error("{0}")] Other(String), } diff --git a/compliance-agent/src/ingest/archive.rs b/compliance-agent/src/ingest/archive.rs index a9acde1..7227bbd 100644 --- a/compliance-agent/src/ingest/archive.rs +++ b/compliance-agent/src/ingest/archive.rs @@ -5,6 +5,12 @@ //! [`ExtractLimits`], and nothing an archive says about its own paths or sizes //! is trusted: entries that would leave the destination are skipped, and the //! byte budget counts what is actually written. +//! +//! A password-protected zip (ZipCrypto or AES) is decrypted with the +//! password stored on the artifact; a missing or wrong one is its own error, +//! so the customer is asked for it instead of seeing a failed scan. 7z and +//! rar are not unpacked; [`unsupported_format`] names them so the upload can +//! say so. use std::fs::{self, File}; use std::io::{self, Read}; @@ -42,6 +48,86 @@ impl Default for ExtractLimits { } } +/// Why an archive could not be unpacked. +#[derive(Debug, thiserror::Error)] +pub enum ExtractError { + /// The archive is encrypted and no password is set for it. + #[error("the archive is password-protected and no password is set")] + PasswordRequired, + /// The archive is encrypted and the stored password does not open it. + #[error("the archive password is wrong")] + WrongPassword, + /// Anything else: corrupt, too large, or the disk failed. + #[error(transparent)] + Other(#[from] AgentError), +} + +impl From for ExtractError { + fn from(e: io::Error) -> Self { + Self::Other(e.into()) + } +} + +/// Archive formats recognised but not unpacked, by their leading bytes. +const UNSUPPORTED_FORMATS: &[(&[u8], &str)] = + &[(b"7z\xBC\xAF\x27\x1C", "7z"), (b"Rar!\x1A\x07", "rar")]; + +/// The name of an archive format ingest does not unpack (7z, rar), when the +/// file at `path` is one; `None` otherwise. +/// +/// # Errors +/// +/// Returns an error when the file cannot be opened or read. +pub fn unsupported_format(path: &Path) -> io::Result> { + let head = leading_block(File::open(path)?)?; + Ok(UNSUPPORTED_FORMATS + .iter() + .find(|(magic, _)| head.starts_with(magic)) + .map(|(_, name)| *name)) +} + +/// Whether the zip at `path` is password-protected, checking `password` +/// against it when one is given. +/// +/// The smallest encrypted entry is read in full: ZipCrypto accepts about one +/// wrong password in 256 at the header, and only the entry's checksum tells. +/// +/// # Returns +/// +/// `false` for a zip without encrypted entries (a password is then not +/// needed); `true` when it is encrypted and `password` opens it. +/// +/// # Errors +/// +/// [`ExtractError::PasswordRequired`] when it is encrypted and no password is +/// given, [`ExtractError::WrongPassword`] when the password does not open it, +/// [`ExtractError::Other`] when it is not a readable zip. +pub fn zip_encryption(path: &Path, password: Option<&[u8]>) -> Result { + let mut zip = zip::ZipArchive::new(File::open(path)?) + .map_err(|e| AgentError::Other(format!("open zip: {e}")))?; + let mut smallest: Option<(usize, u64)> = None; + for i in 0..zip.len() { + let Ok(entry) = zip.by_index_raw(i) else { + continue; + }; + if entry.encrypted() + && !entry.is_dir() + && smallest.is_none_or(|(_, size)| entry.size() < size) + { + smallest = Some((i, entry.size())); + } + } + let Some((index, _)) = smallest else { + return Ok(false); + }; + let password = password.ok_or(ExtractError::PasswordRequired)?; + let mut entry = zip + .by_index_decrypt(index, password) + .map_err(|_| ExtractError::WrongPassword)?; + io::copy(&mut entry, &mut io::sink()).map_err(|_| ExtractError::WrongPassword)?; + Ok(true) +} + /// The archive formats ingest unpacks. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum ArchiveFormat { @@ -104,27 +190,31 @@ fn is_tar_header(block: &[u8]) -> bool { } /// Unpack `archive` of the given `format` into `dest` (created if needed), -/// refusing archives that exceed `limits`. +/// refusing archives that exceed `limits`. `password` opens encrypted zip +/// entries; tar has no encryption and ignores it. /// /// On any error the partly written `dest` is removed, so a caller never finds /// half an archive (or half a bomb) left behind in the working directory. /// /// # Errors /// -/// Returns an error when the archive is corrupt, an entry cannot be written, or -/// the archive exceeds `limits`. +/// [`ExtractError::PasswordRequired`] or [`ExtractError::WrongPassword`] for +/// an encrypted zip without the right password; [`ExtractError::Other`] when +/// the archive is corrupt, an entry cannot be written, or the archive exceeds +/// `limits`. pub fn extract( format: ArchiveFormat, archive: &Path, dest: &Path, limits: ExtractLimits, -) -> Result<(), AgentError> { + password: Option<&[u8]>, +) -> Result<(), ExtractError> { let result = File::open(archive) - .map_err(AgentError::from) + .map_err(ExtractError::from) .and_then(|file| match format { - ArchiveFormat::Zip => extract_zip(file, dest, limits), - ArchiveFormat::Tar => extract_tar(file, dest, limits), - ArchiveFormat::TarGz => extract_tar(GzDecoder::new(file), dest, limits), + ArchiveFormat::Zip => extract_zip(file, dest, limits, password), + ArchiveFormat::Tar => Ok(extract_tar(file, dest, limits)?), + ArchiveFormat::TarGz => Ok(extract_tar(GzDecoder::new(file), dest, limits)?), }); if result.is_err() { let _ = fs::remove_dir_all(dest); @@ -132,18 +222,31 @@ pub fn extract( result } -fn extract_zip(file: File, dest: &Path, limits: ExtractLimits) -> Result<(), AgentError> { +fn extract_zip( + file: File, + dest: &Path, + limits: ExtractLimits, + password: Option<&[u8]>, +) -> Result<(), ExtractError> { let mut zip = zip::ZipArchive::new(file).map_err(|e| AgentError::Other(format!("open zip: {e}")))?; if zip.len() > limits.max_entries { - return Err(too_many_entries(limits)); + return Err(too_many_entries(limits).into()); } fs::create_dir_all(dest)?; let mut budget = Budget::new(limits); for i in 0..zip.len() { - let mut entry = zip - .by_index(i) - .map_err(|e| AgentError::Other(format!("read zip entry: {e}")))?; + let entry = match password { + Some(password) => zip.by_index_decrypt(i, password), + None => zip.by_index(i), + }; + let mut entry = entry.map_err(|e| match e { + zip::result::ZipError::UnsupportedArchive(zip::result::ZipError::PASSWORD_REQUIRED) => { + ExtractError::PasswordRequired + } + zip::result::ZipError::InvalidPassword => ExtractError::WrongPassword, + other => AgentError::Other(format!("read zip entry: {other}")).into(), + })?; // `enclosed_name` returns `None` for traversal-unsafe paths — skip them. let Some(rel) = entry.enclosed_name() else { continue; @@ -152,7 +255,13 @@ fn extract_zip(file: File, dest: &Path, limits: ExtractLimits) -> Result<(), Age if entry.is_dir() { fs::create_dir_all(&out)?; } else { - budget.write(&mut entry, &out)?; + let encrypted = entry.encrypted(); + budget.write(&mut entry, &out).map_err(|e| match e { + // ZipCrypto lets about one wrong password in 256 past its + // header check; the entry's checksum then fails on reading. + AgentError::Io(_) if encrypted => ExtractError::WrongPassword, + other => other.into(), + })?; } } Ok(()) @@ -305,6 +414,86 @@ mod tests { w.finish().expect("finish").into_inner() } + /// A zip whose one file is AES-256 encrypted with `password`. + fn aes_zip(password: &str) -> Vec { + let mut w = zip::ZipWriter::new(io::Cursor::new(Vec::new())); + let opts: zip::write::SimpleFileOptions = Default::default(); + w.start_file( + "src/main.c", + opts.with_aes_encryption(zip::AesMode::Aes256, password), + ) + .expect("start"); + w.write_all(b"int main(void) { return 0; }\n") + .expect("write"); + w.finish().expect("finish").into_inner() + } + + /// Made with `zip -P pilot-2026` (the crate cannot write ZipCrypto). + const ZIPCRYPTO: &[u8] = include_bytes!("../../tests/fixtures/archives/zipcrypto.zip"); + const SEVEN_ZIP: &[u8] = include_bytes!("../../tests/fixtures/archives/sample.7z"); + + #[test] + fn an_encrypted_zip_asks_for_its_password_and_opens_with_it() { + let s = Scratch::new(); + for (name, bytes, password) in [ + ("aes.zip", aes_zip("s3cret"), "s3cret"), + ("zipcrypto.zip", ZIPCRYPTO.to_vec(), "pilot-2026"), + ] { + let archive = file_with(s.path(), name, &bytes); + let dest = s.path().join(format!("out-{name}")); + + assert!(matches!( + zip_encryption(&archive, None), + Err(ExtractError::PasswordRequired) + )); + assert!(matches!( + zip_encryption(&archive, Some(b"wrong")), + Err(ExtractError::WrongPassword) + )); + assert!(matches!( + zip_encryption(&archive, Some(password.as_bytes())), + Ok(true) + )); + + assert!(matches!( + extract(ArchiveFormat::Zip, &archive, &dest, roomy(), None), + Err(ExtractError::PasswordRequired) + )); + assert!(!dest.exists(), "{name}: nothing is left half-written"); + assert!(matches!( + extract(ArchiveFormat::Zip, &archive, &dest, roomy(), Some(b"wrong")), + Err(ExtractError::WrongPassword) + )); + extract( + ArchiveFormat::Zip, + &archive, + &dest, + roomy(), + Some(password.as_bytes()), + ) + .expect("the right password opens it"); + assert!(dest.join("src/main.c").is_file(), "{name}"); + } + } + + #[test] + fn a_plain_zip_needs_no_password() { + let s = Scratch::new(); + let archive = file_with(s.path(), "plain.zip", &zip_bytes(&[("a.c", b"int a;")])); + assert!(matches!(zip_encryption(&archive, None), Ok(false))); + } + + #[test] + fn seven_zip_and_rar_are_named_as_unsupported() { + let s = Scratch::new(); + let seven = file_with(s.path(), "a.7z", SEVEN_ZIP); + let rar = file_with(s.path(), "a.rar", b"Rar!\x1A\x07\x01\x00rest"); + let zip = file_with(s.path(), "a.zip", &zip_bytes(&[("a.c", b"int a;")])); + assert_eq!(unsupported_format(&seven).expect("read"), Some("7z")); + assert_eq!(unsupported_format(&rar).expect("read"), Some("rar")); + assert_eq!(unsupported_format(&zip).expect("read"), None); + } + fn file_with(dir: &Path, name: &str, bytes: &[u8]) -> PathBuf { let p = dir.join(name); fs::write(&p, bytes).expect("write"); @@ -345,7 +534,7 @@ mod tests { ] { let archive = file_with(s.path(), name, &bytes); let dest = s.path().join(format!("out-{name}")); - extract(format, &archive, &dest, roomy()).expect("extract"); + extract(format, &archive, &dest, roomy(), None).expect("extract"); assert_eq!( fs::read_to_string(dest.join("proj/Core/Src/main.c")).expect("read"), "int main(void);", @@ -377,7 +566,7 @@ mod tests { let archive = file_with(s.path(), "evil.tar", &builder.into_inner().expect("tar")); let dest = s.path().join("out"); - extract(ArchiveFormat::Tar, &archive, &dest, roomy()).expect("extract"); + extract(ArchiveFormat::Tar, &archive, &dest, roomy(), None).expect("extract"); assert!(dest.join("ok.txt").is_file()); assert!(!s.path().join("escape.txt").exists()); assert!(!dest.join("abs.txt").exists()); @@ -398,7 +587,7 @@ mod tests { max_entries: 100, max_total_bytes: 2 * 1024 * 1024, }; - let err = extract(ArchiveFormat::TarGz, &archive, &dest, limits).expect_err("refuse"); + let err = extract(ArchiveFormat::TarGz, &archive, &dest, limits, None).expect_err("refuse"); assert!(err.to_string().contains("expands beyond"), "{err}"); assert!(!dest.exists(), "partial output must be removed"); } @@ -417,7 +606,7 @@ mod tests { ] { let archive = file_with(s.path(), name, &bytes); let dest = s.path().join(format!("out-{name}")); - let err = extract(format, &archive, &dest, limits).expect_err("refuse"); + let err = extract(format, &archive, &dest, limits, None).expect_err("refuse"); assert!(err.to_string().contains("entries"), "{format}: {err}"); assert!(!dest.exists()); } @@ -434,7 +623,7 @@ mod tests { Some(ArchiveFormat::TarGz) ); let dest = s.path().join("out"); - assert!(extract(ArchiveFormat::TarGz, &archive, &dest, roomy()).is_err()); + assert!(extract(ArchiveFormat::TarGz, &archive, &dest, roomy(), None).is_err()); assert!(!dest.exists()); } @@ -449,7 +638,7 @@ mod tests { }; let archive = file_with(s.path(), "t", &tar_bytes(files)); let dest = s.path().join("out"); - extract(ArchiveFormat::Tar, &archive, &dest, limits).expect("at the limit is fine"); + extract(ArchiveFormat::Tar, &archive, &dest, limits, None).expect("at the limit is fine"); assert_eq!(fs::read(dest.join("c")).expect("read").len(), 1024); } } diff --git a/compliance-agent/src/ingest/mod.rs b/compliance-agent/src/ingest/mod.rs index 6bb0505..3da46ec 100644 --- a/compliance-agent/src/ingest/mod.rs +++ b/compliance-agent/src/ingest/mod.rs @@ -72,6 +72,32 @@ pub struct IngestedArtifact { pub struct IngestSet { /// The ingested artifacts, keyed by [`Artifact::id`]. pub by_artifact: HashMap, + /// The artifacts that could not be ingested. The others still are: one + /// broken upload does not cost the target its repository. + pub failures: Vec, +} + +/// An artifact that could not be ingested, and why. +#[derive(Debug)] +pub struct IngestFailure { + /// The artifact's [`Artifact::id`]. + pub artifact_id: String, + /// What the user called it: the file name, or the URL. + pub artifact_name: String, + /// What went wrong. + pub error: AgentError, +} + +impl IngestFailure { + /// The skipped-stage id to record it under: a missing or wrong archive + /// password has its own, so the dashboard can say what to do. + pub fn stage(&self) -> &'static str { + match self.error { + AgentError::ArchivePasswordRequired => "archive_password_required", + AgentError::ArchivePasswordWrong => "archive_password_wrong", + _ => "ingest", + } + } } impl IngestSet { @@ -90,17 +116,30 @@ impl IngestSet { } } -/// Ingest every artifact on a target. -pub fn ingest_all( - target: &OnboardedTarget, - ctx: &IngestContext<'_>, -) -> Result { - let mut by_artifact = HashMap::new(); +/// Ingest every artifact on a target. An artifact that fails is recorded in +/// [`IngestSet::failures`], and the rest are still ingested. +pub fn ingest_all(target: &OnboardedTarget, ctx: &IngestContext<'_>) -> IngestSet { + let mut by_artifact = HashMap::with_capacity(target.artifacts.len()); + let mut failures = Vec::new(); for artifact in &target.artifacts { - let ingested = ingest_artifact(artifact, ctx)?; - by_artifact.insert(artifact.id.clone(), ingested); + match ingest_artifact(artifact, ctx) { + Ok(ingested) => { + by_artifact.insert(artifact.id.clone(), ingested); + } + Err(error) => failures.push(IngestFailure { + artifact_id: artifact.id.clone(), + artifact_name: artifact + .display_name + .clone() + .unwrap_or_else(|| artifact.source_ref.clone()), + error, + }), + } + } + IngestSet { + by_artifact, + failures, } - Ok(IngestSet { by_artifact }) } /// Ingest a single artifact, dispatching on its kind. @@ -193,12 +232,30 @@ fn ingest_blob( let mut facts = Vec::new(); let working_path = if extract { + if let Some(format) = archive::unsupported_format(&stored)? { + return Err(AgentError::Other(format!( + "{format} archives are not supported; upload a zip, tar or tar.gz" + ))); + } let dest = blob::work_dir(base, ctx.target_id, &artifact.id); + let password = archive_password(artifact, &ctx.secrets); match archive::ArchiveFormat::sniff(&stored)? { Some(format) => { - match archive::extract(format, &stored, &dest, archive::ExtractLimits::default()) { + match archive::extract( + format, + &stored, + &dest, + archive::ExtractLimits::default(), + password.as_deref().map(str::as_bytes), + ) { Ok(()) => project_root(dest), - Err(e) => { + Err(archive::ExtractError::PasswordRequired) => { + return Err(AgentError::ArchivePasswordRequired) + } + Err(archive::ExtractError::WrongPassword) => { + return Err(AgentError::ArchivePasswordWrong) + } + Err(archive::ExtractError::Other(e)) => { let reason = format!("the uploaded {format} archive could not be unpacked: {e}"); if artifact.kind == ArtifactKind::SourceArchive { @@ -321,7 +378,7 @@ fn metadata_only(artifact: &Artifact, fact: DetectedFact) -> IngestedArtifact { /// (`/data/compliance-scanner/ssh/id_ed25519`, another tenant's checkout) and /// have it ingested as their own artifact. Blob artifacts now have to be /// uploaded. -fn local_source(artifact: &Artifact) -> Result { +pub(crate) fn local_source(artifact: &Artifact) -> Result { let Some(stored) = artifact.stored_path.as_deref() else { return Err(AgentError::Other(format!( "artifact {} has no uploaded content — upload the file instead of \ @@ -344,6 +401,19 @@ fn local_source(artifact: &Artifact) -> Result { /// is no agent-wide SSH key to fall back to any more, because one shared key /// authenticated every tenant's clone (see /// [`crate::pipeline::git::reject_ssh_url`]). +/// The auth method under which an archive's password is stored. +pub const ARCHIVE_PASSWORD_METHOD: &str = "archive_password"; + +/// The password of a password-protected archive artifact, opened; `None` +/// when none is set. +fn archive_password(artifact: &Artifact, secrets: &SecretBox) -> Option { + artifact + .auth + .as_ref() + .filter(|a| a.method == ARCHIVE_PASSWORD_METHOD) + .and_then(|a| secrets.open_opt(a.secret.as_ref(), "archive password")) +} + fn credentials_for(artifact: &Artifact, secrets: &SecretBox) -> RepoCredentials { let auth = artifact.auth.as_ref(); RepoCredentials { @@ -493,7 +563,7 @@ mod tests { .artifacts .push(Artifact::live_url("https://example.com/x")); - let set = ingest_all(&target, &ctx).expect("ingest all"); + let set = ingest_all(&target, &ctx); assert_eq!(set.by_artifact.len(), 2); // Only the firmware artifact yields a working path. assert_eq!(set.working_paths().len(), 1); @@ -546,6 +616,89 @@ mod tests { /// A single uploaded PLC file (not an archive) must land in a working dir /// under its original name so the PLC scanner can discover it by extension /// and report a readable path — the demo's upload → scan path. + /// A source-archive artifact for `bytes`, as the upload handler stores it. + fn uploaded_archive(dir: &Path, name: &str, bytes: &[u8]) -> Artifact { + let path = dir.join(name); + std::fs::create_dir_all(dir).expect("mkdir uploads"); + std::fs::write(&path, bytes).expect("write upload"); + let mut artifact = Artifact::source_archive(name); + artifact.stored_path = Some(path.to_string_lossy().to_string()); + artifact + } + + const ZIPCRYPTO: &[u8] = include_bytes!("../../tests/fixtures/archives/zipcrypto.zip"); + const SEVEN_ZIP: &[u8] = include_bytes!("../../tests/fixtures/archives/sample.7z"); + + #[test] + fn a_password_protected_archive_opens_with_its_stored_password() { + let scratch = Scratch::new(); + let store = scratch.0.join("store"); + let ctx = ctx_for(&store, "t-pw"); + let mut artifact = uploaded_archive(&scratch.0.join("uploads"), "fw.zip", ZIPCRYPTO); + + assert!(matches!( + ingest_artifact(&artifact, &ctx), + Err(AgentError::ArchivePasswordRequired) + )); + + // Without a key the box keeps values as they are, like a dev agent. + artifact.auth = Some(ArtifactAuth { + method: ARCHIVE_PASSWORD_METHOD.into(), + secret: Some("wrong".into()), + ..Default::default() + }); + assert!(matches!( + ingest_artifact(&artifact, &ctx), + Err(AgentError::ArchivePasswordWrong) + )); + + artifact.auth = Some(ArtifactAuth { + method: ARCHIVE_PASSWORD_METHOD.into(), + secret: Some("pilot-2026".into()), + ..Default::default() + }); + let out = ingest_artifact(&artifact, &ctx).expect("opens"); + let root = out.working_path.expect("working path"); + assert!(root.join("main.c").is_file(), "{root:?}"); + } + + #[test] + fn a_7z_upload_is_refused_by_name() { + let scratch = Scratch::new(); + let store = scratch.0.join("store"); + let ctx = ctx_for(&store, "t-7z"); + let artifact = uploaded_archive(&scratch.0.join("uploads"), "fw.7z", SEVEN_ZIP); + let Err(err) = ingest_artifact(&artifact, &ctx) else { + panic!("a 7z upload must be refused"); + }; + assert!( + err.to_string().contains("7z archives are not supported"), + "{err}" + ); + } + + #[test] + fn one_failing_artifact_does_not_cost_the_others() { + let scratch = Scratch::new(); + let store = scratch.0.join("store"); + let ctx = ctx_for(&store, "t-mixed"); + let uploads = scratch.0.join("uploads"); + let mut target = OnboardedTarget::new("mixed".into(), TargetType::FirmwareRtos); + target + .artifacts + .push(uploaded_archive(&uploads, "locked.zip", ZIPCRYPTO)); + target + .artifacts + .push(Artifact::live_url("https://example.com/x")); + + let set = ingest_all(&target, &ctx); + + assert_eq!(set.by_artifact.len(), 1, "the URL is still ingested"); + assert_eq!(set.failures.len(), 1); + assert_eq!(set.failures[0].stage(), "archive_password_required"); + assert_eq!(set.failures[0].artifact_name, "locked.zip"); + } + #[test] fn single_uploaded_plc_file_is_materialized_and_scannable() { use compliance_core::models::PlcFormat; diff --git a/compliance-agent/src/pipeline/orchestrator.rs b/compliance-agent/src/pipeline/orchestrator.rs index 8bedfdd..2408613 100644 --- a/compliance-agent/src/pipeline/orchestrator.rs +++ b/compliance-agent/src/pipeline/orchestrator.rs @@ -753,7 +753,8 @@ impl PipelineOrchestrator { let ctx = crate::ingest::IngestContext::from_config(&self.config, &self.tenant_id, target_id); - let ingest_set = crate::ingest::ingest_all(target, &ctx)?; + // Failures are recorded once, by classification, which runs first. + let ingest_set = crate::ingest::ingest_all(target, &ctx); // Every PLC-source artifact on the target: dedicated PLC projects plus any // code artifacts (git repo / source archive) holding PLCopen XML / ST // exports. A target can carry several (e.g. one POU export per file). @@ -907,7 +908,8 @@ impl PipelineOrchestrator { // artifacts holding PLCopen XML / ST exports). let ctx = crate::ingest::IngestContext::from_config(&self.config, &self.tenant_id, target_id); - let ingest_set = crate::ingest::ingest_all(target, &ctx)?; + // Failures are recorded once, by classification, which runs first. + let ingest_set = crate::ingest::ingest_all(target, &ctx); let program = target .artifacts .iter() @@ -1188,14 +1190,19 @@ impl PipelineOrchestrator { .await; let ctx = crate::ingest::IngestContext::from_config(&self.config, &self.tenant_id, target_id); - let ingest_set = match crate::ingest::ingest_all(target, &ctx) { - Ok(set) => set, - Err(e) => { - tracing::warn!(target_id, error = %e, "Unified pipeline: ingest for classification failed"); - self.skip_stage(scan_run_id, "ingest", &e.to_string()).await; - return std::collections::HashMap::new(); - } - }; + let ingest_set = crate::ingest::ingest_all(target, &ctx); + // Each artifact that could not be read is recorded with its reason; a + // missing or wrong archive password under its own stage, so the + // dashboard can ask for it. The others are still classified and scanned. + for failure in &ingest_set.failures { + tracing::warn!(target_id, artifact = %failure.artifact_id, error = %failure.error, "Unified pipeline: artifact not ingested"); + self.skip_stage( + scan_run_id, + failure.stage(), + &format!("{}: {}", failure.artifact_name, failure.error), + ) + .await; + } let working_paths = ingest_set.working_paths(); let mut detected_firmware = false; match crate::classify::classify_target( diff --git a/compliance-agent/src/pipeline/plc/sbom.rs b/compliance-agent/src/pipeline/plc/sbom.rs index 86f5a03..b2a4bec 100644 --- a/compliance-agent/src/pipeline/plc/sbom.rs +++ b/compliance-agent/src/pipeline/plc/sbom.rs @@ -76,7 +76,9 @@ pub fn projectarchive_sbom(archive: &Path, repo_id: &str) -> Vec { let mut seen: BTreeSet<(String, String)> = BTreeSet::new(); let mut entries = Vec::new(); for i in 0..zip.len() { - let Ok(entry) = zip.by_index(i) else { + // Only the entry names are read, and a zip never encrypts those: the + // raw entry lists a password-protected archive's components too. + let Ok(entry) = zip.by_index_raw(i) else { continue; }; // Entry paths use `\` (Windows-authored) and/or `/` separators; the diff --git a/compliance-agent/tests/archive_password.rs b/compliance-agent/tests/archive_password.rs new file mode 100644 index 0000000..7084d52 --- /dev/null +++ b/compliance-agent/tests/archive_password.rs @@ -0,0 +1,126 @@ +//! Password-protected archives (#370): the upload marks them, the password is +//! checked against the file before it is stored, and 7z/rar are refused. +//! Drives the real API against a live Mongo (`TEST_MONGODB_URI`). + +#![allow(clippy::expect_used, clippy::unwrap_used)] + +mod common; + +use common::TestServer; + +/// Made with `zip -P pilot-2026`. +const ZIPCRYPTO: &[u8] = include_bytes!("fixtures/archives/zipcrypto.zip"); +const SEVEN_ZIP: &[u8] = include_bytes!("fixtures/archives/sample.7z"); + +async fn create_target(server: &TestServer) -> String { + let created: serde_json::Value = server + .post( + "/api/v1/targets", + &serde_json::json!({ "name": "sensor", "target_type": "firmware_rtos" }), + ) + .await + .json() + .await + .unwrap(); + created["data"]["_id"]["$oid"].as_str().unwrap().to_string() +} + +async fn upload(server: &TestServer, id: &str, name: &str, bytes: &[u8]) -> reqwest::Response { + let form = reqwest::multipart::Form::new() + .text("kind", "source_archive") + .part( + "file", + reqwest::multipart::Part::bytes(bytes.to_vec()).file_name(name.to_string()), + ); + server + .client + .post(format!( + "{}/api/v1/targets/{id}/artifacts/upload", + server.base_url + )) + .multipart(form) + .send() + .await + .unwrap() +} + +async fn set_password(server: &TestServer, id: &str, artifact: &str, password: &str) -> u16 { + server + .client + .put(format!( + "{}/api/v1/targets/{id}/artifacts/{artifact}/archive-password", + server.base_url + )) + .json(&serde_json::json!({ "password": password })) + .send() + .await + .unwrap() + .status() + .as_u16() +} + +#[tokio::test] +async fn an_encrypted_upload_is_marked_and_takes_only_its_password() { + let server = TestServer::start().await; + let id = create_target(&server).await; + + // Arrange: the upload is kept, and marked as needing a password. + let target: serde_json::Value = upload(&server, &id, "firmware.zip", ZIPCRYPTO) + .await + .json() + .await + .unwrap(); + let artifact = &target["data"]["artifacts"][0]; + let artifact_id = artifact["id"].as_str().unwrap().to_string(); + assert!( + artifact["detected"] + .as_array() + .unwrap() + .iter() + .any(|f| f["key"] == "archive_encrypted"), + "{artifact}" + ); + + // Act + let wrong = set_password(&server, &id, &artifact_id, "guess").await; + let right = set_password(&server, &id, &artifact_id, "pilot-2026").await; + + // Assert: only the right one is stored, and it is never returned. + assert_eq!(wrong, 422); + assert_eq!(right, 204); + let stored: serde_json::Value = server + .get(&format!("/api/v1/targets/{id}")) + .await + .json() + .await + .unwrap(); + let auth = &stored["data"]["artifacts"][0]["auth"]; + assert_eq!(auth["method"], "archive_password"); + assert!(auth["secret"].is_null(), "{auth}"); + assert!(!stored.to_string().contains("pilot-2026")); + + server.cleanup().await; +} + +#[tokio::test] +async fn a_plain_upload_needs_no_password_and_7z_is_refused() { + let server = TestServer::start().await; + let id = create_target(&server).await; + + let plain: serde_json::Value = + upload(&server, &id, "main.c", b"int main(void) { return 0; }\n") + .await + .json() + .await + .unwrap(); + let artifact_id = plain["data"]["artifacts"][0]["id"] + .as_str() + .unwrap() + .to_string(); + let seven = upload(&server, &id, "firmware.7z", SEVEN_ZIP).await; + + assert_eq!(set_password(&server, &id, &artifact_id, "x").await, 409); + assert_eq!(seven.status().as_u16(), 415); + + server.cleanup().await; +} diff --git a/compliance-agent/tests/fixtures/archives/sample.7z b/compliance-agent/tests/fixtures/archives/sample.7z new file mode 100644 index 0000000000000000000000000000000000000000..ecb5007daf5a50479309924e055fca630b05b95b GIT binary patch literal 195 zcmXr7+Ou9=hJoc_WGZ_z0|Y2Q>CA*zyo?MonRz7&xrv#18fE#JDVhq^3Pq_UrA2uP z2G$C-TtKCb#_a3(FUVf1nQ!mzs4KVNnlXpbw0o(2+_QrlEbJJ5rwQ3bzIByYb=j-* z&A!i%&iwc^SxCjM^WL1hu3_6Jo9~Oip=dj4@|I<1uG`<${#4NUE$*{Wq670Y(Zw^D o9RQjy&Zfx7nZ&@(&B(y0%*@Eh8p|NSz`#?+#i)NPK7fG%0AsE}Z2$lO literal 0 HcmV?d00001 diff --git a/compliance-agent/tests/fixtures/archives/zipcrypto.zip b/compliance-agent/tests/fixtures/archives/zipcrypto.zip new file mode 100644 index 0000000000000000000000000000000000000000..58c96cf37c9bad8bb7ab96194e4d3ec4ab89c28f GIT binary patch literal 363 zcmWIWW@h1H0D%Kxma$+4lwe_yVJI$2)(;KgWME!ywk->UODnh;7+GF0GcbUO0I+UO zsP2!|&UuWqkU%=V=;Y;%B69 ze>J^iSeL!+-TpR>S8e1b8zt$uZ+{yad!60t{~*K}?8OSRr1)@CL*r>>h!b f#0WHFNuwRqB$&5wna9covXco2X94NmAPxfnldVu= literal 0 HcmV?d00001 diff --git a/compliance-dashboard/src/i18n/texts.rs b/compliance-dashboard/src/i18n/texts.rs index fb49f62..8aae70f 100644 --- a/compliance-dashboard/src/i18n/texts.rs +++ b/compliance-dashboard/src/i18n/texts.rs @@ -29,6 +29,42 @@ pub mod common { de: "Niedrig", en: "Low", }; + pub const ARCHIVE_PASSWORD: Text = Text { + de: "Archiv-Passwort (nur bei passwortgeschützten Archiven)", + en: "Archive password (only for password-protected archives)", + }; + pub const PASSWORD_NEEDED: Text = Text { + de: "Das Archiv ist passwortgeschützt. Bitte das Passwort eingeben.", + en: "The archive is password-protected. Please enter its password.", + }; + pub const PASSWORD_WRONG: Text = Text { + de: "Das Passwort öffnet das Archiv nicht.", + en: "The password does not open the archive.", + }; + pub const PASSWORD_SAVED: Text = Text { + de: "Passwort gespeichert", + en: "Password saved", + }; + pub const PASSWORD_SET: Text = Text { + de: "Passwort gesetzt", + en: "Password set", + }; + pub const PASSWORD_MISSING: Text = Text { + de: "Passwort fehlt", + en: "Password missing", + }; + pub const SAVE_PASSWORD: Text = Text { + de: "Passwort speichern", + en: "Save password", + }; + pub const NOT_ENCRYPTED: Text = Text { + de: "Dieses Archiv braucht kein Passwort.", + en: "This archive needs no password.", + }; + pub const UNSUPPORTED_ARCHIVE: Text = Text { + de: "7z- und RAR-Archive werden nicht unterstützt. Bitte als zip, tar oder tar.gz hochladen.", + en: "7z and RAR archives are not supported. Please upload a zip, tar or tar.gz.", + }; pub const NOT_AVAILABLE_HERE: Text = Text { de: "In dieser Umgebung nicht verfügbar", en: "Not available in this environment", @@ -285,6 +321,14 @@ pub mod scans { de: "Git-Submodule", en: "Git submodules", }, + "archive_password_required" => Text { + de: "Archiv-Passwort fehlt (unter „Prüfobjekte“ eingeben)", + en: "Archive password missing (enter it under Targets)", + }, + "archive_password_wrong" => Text { + de: "Archiv-Passwort falsch (unter „Prüfobjekte“ ändern)", + en: "Archive password wrong (change it under Targets)", + }, "code_scan" => Text { de: "Codeanalyse", en: "Code analysis", diff --git a/compliance-dashboard/src/infrastructure/onboarding.rs b/compliance-dashboard/src/infrastructure/onboarding.rs index 70db1fb..7a610ca 100644 --- a/compliance-dashboard/src/infrastructure/onboarding.rs +++ b/compliance-dashboard/src/infrastructure/onboarding.rs @@ -27,6 +27,89 @@ pub struct ArtifactInputDto { /// never returns the token itself, and this is never sent. #[serde(skip)] pub has_token: bool, + /// The stored artifact's id, for setting its archive password. Display + /// only, never sent. + #[serde(skip)] + pub artifact_id: String, + /// Whether this is a password-protected archive, and if its password is + /// set. Display only, never sent. + #[serde(skip)] + pub archive_password: ArchivePassword, +} + +/// A stored archive's password state, as the target editor shows it. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub enum ArchivePassword { + /// Not a password-protected archive. + #[default] + NotNeeded, + /// Password-protected, and no password is set. + Missing, + /// Password-protected, and a password is set. + Set, +} + +impl ArchivePassword { + /// The state of a stored artifact (as the agent returns it). + pub fn of(artifact: &serde_json::Value) -> Self { + let encrypted = artifact["detected"] + .as_array() + .is_some_and(|facts| facts.iter().any(|f| f["key"] == ARCHIVE_ENCRYPTED_FACT)); + let set = artifact["auth"]["method"] == ARCHIVE_PASSWORD_METHOD; + match (encrypted, set) { + (_, true) => Self::Set, + (true, false) => Self::Missing, + (false, false) => Self::NotNeeded, + } + } +} + +/// The fact the agent records on a password-protected upload. +const ARCHIVE_ENCRYPTED_FACT: &str = "archive_encrypted"; +/// The auth method under which the agent stores an archive password. +const ARCHIVE_PASSWORD_METHOD: &str = "archive_password"; + +/// The marker in an upload error for a 7z or rar archive, which the agent +/// refuses; the page shows [`crate::i18n::texts::common::UNSUPPORTED_ARCHIVE`]. +pub const UNSUPPORTED_ARCHIVE: &str = "unsupported_archive"; + +/// What setting an archive password did. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +pub enum PasswordOutcome { + /// It opens the archive and is stored. + Saved, + /// It does not open the archive; nothing was stored. + Wrong, + /// The artifact is not a password-protected archive. + NotEncrypted, +} + +/// Set the password of an uploaded, password-protected archive. It travels in +/// the request body, never in a URL, and the agent checks it against the file +/// before storing it sealed. +#[server] +pub async fn set_archive_password( + id: String, + artifact_id: String, + password: String, +) -> Result { + let resp = super::agent_client::agent_request( + reqwest::Method::PUT, + &format!("/api/v1/targets/{id}/artifacts/{artifact_id}/archive-password"), + ) + .await? + .json(&serde_json::json!({ "password": password })) + .send() + .await + .map_err(|e| ServerFnError::new(e.to_string()))?; + match resp.status().as_u16() { + 204 => Ok(PasswordOutcome::Saved), + 422 => Ok(PasswordOutcome::Wrong), + 409 => Ok(PasswordOutcome::NotEncrypted), + code => Err(ServerFnError::new(format!( + "the agent refused the password ({code})" + ))), + } } #[derive(Debug, Clone, Serialize, Deserialize, Default)] @@ -305,6 +388,7 @@ pub async fn upload_target_artifact( if !resp.status().is_success() { return Err(ServerFnError::new(match resp.status().as_u16() { 413 => "file is larger than the 512 MiB upload limit".to_string(), + 415 => UNSUPPORTED_ARCHIVE.to_string(), code => format!("upload rejected by the agent ({code})"), })); } @@ -421,6 +505,21 @@ pub async fn trigger_target_scan(id: String) -> Result, filename: String, file: dioxus::html::FileData, + /// The archive's password, if it has one; sent after the upload. + password: String, } /// The opt-in scans of an applicable-scans list: applicable and unblocked, @@ -312,6 +315,7 @@ pub fn OnboardingPage() -> Element { plc_format, filename: fname, file: data, + password: String::new(), }); new_file.set(None); } @@ -357,6 +361,7 @@ pub fn OnboardingPage() -> Element { kind, source_ref: new_source(), plc_format: None, + ..Default::default() }); new_source.set(String::new()); new_token.set(String::new()); @@ -407,6 +412,17 @@ pub fn OnboardingPage() -> Element { span { style: "opacity: 0.7;", "{kind_label(&pf.kind)} ({tx::FILE_SUFFIX.get(lang)}): " } "{pf.filename} ({format_bytes(pf.file.size(), lang)})" } + // Firmware images are never unpacked; archives may be locked. + if pf.kind != "firmware_image" { + input { + r#type: "password", + autocomplete: "off", + placeholder: common::ARCHIVE_PASSWORD.get(lang), + style: "flex: 1; min-width: 180px; margin: 0 8px;", + value: "{pf.password}", + oninput: move |e| pending_files.write()[i].password = e.value(), + } + } button { class: "btn btn-ghost-danger btn-sm", onclick: move |_| { pending_files.write().remove(i); }, @@ -679,7 +695,7 @@ pub fn OnboardingPage() -> Element { for (i, pf) in files.into_iter().enumerate() { let fname = pf.filename.clone(); uploading.set(Some((i + 1, total, fname.clone()))); - if let Err(e) = upload_target_artifact( + match upload_target_artifact( id.clone(), pf.kind, pf.plc_format, @@ -687,7 +703,39 @@ pub fn OnboardingPage() -> Element { ) .await { - upload_errors.write().push(format!("{fname}: {e}")); + Err(e) => { + let e = e.to_string(); + let msg = if e.contains(UNSUPPORTED_ARCHIVE) { + common::UNSUPPORTED_ARCHIVE.get(lang).to_string() + } else { + e + }; + upload_errors.write().push(format!("{fname}: {msg}")); + } + // A locked archive: store its password, or ask + // for it before the scan starts. + Ok(resp) => { + let uploaded = resp.data["artifacts"] + .as_array() + .and_then(|a| a.last()) + .cloned() + .unwrap_or_default(); + if ArchivePassword::of(&uploaded) == ArchivePassword::Missing { + let problem = if pf.password.is_empty() { + Some(common::PASSWORD_NEEDED.get(lang).to_string()) + } else { + let artifact_id = uploaded["id"].as_str().unwrap_or_default().to_string(); + match set_archive_password(id.clone(), artifact_id, pf.password.clone()).await { + Ok(PasswordOutcome::Saved | PasswordOutcome::NotEncrypted) => None, + Ok(PasswordOutcome::Wrong) => Some(common::PASSWORD_WRONG.get(lang).to_string()), + Err(e) => Some(e.to_string()), + } + }; + if let Some(problem) = problem { + upload_errors.write().push(format!("{fname}: {problem}")); + } + } + } } } uploading.set(None); diff --git a/compliance-dashboard/src/pages/targets.rs b/compliance-dashboard/src/pages/targets.rs index 32ad196..60186f4 100644 --- a/compliance-dashboard/src/pages/targets.rs +++ b/compliance-dashboard/src/pages/targets.rs @@ -17,8 +17,9 @@ use crate::components::toast::{ToastType, Toasts}; use crate::i18n::texts::{common, kinds, scans as scan_texts, targets as tx}; use crate::i18n::{use_lang, Lang}; use crate::infrastructure::onboarding::{ - delete_target, fetch_applicable_scans, fetch_targets, trigger_target_scan, update_target, - validate_artifact_ref, validate_target_name, ArtifactInputDto, + delete_target, fetch_applicable_scans, fetch_targets, set_archive_password, + trigger_target_scan, update_target, validate_artifact_ref, validate_target_name, + ArchivePassword, ArtifactInputDto, PasswordOutcome, }; use crate::infrastructure::platform::{stage_tone, use_source_only, SourceOnlyNote}; @@ -255,6 +256,14 @@ pub fn TargetsPage() -> Element { } } } + if a.archive_password != ArchivePassword::NotNeeded { + ArchivePasswordField { + target_id: edit_id().unwrap_or_default(), + artifact_id: a.artifact_id.clone(), + state: a.archive_password, + on_saved: move |_| edit_arts.write()[i].archive_password = ArchivePassword::Set, + } + } button { class: "btn btn-ghost btn-ghost-danger btn-sm", onclick: move |_| { edit_arts.write().remove(i); }, @@ -507,6 +516,8 @@ pub fn TargetsPage() -> Element { .and_then(|x| x.get("method")) .and_then(|m| m.as_str()) == Some("token"), + artifact_id: str_at(a, "id").to_string(), + archive_password: ArchivePassword::of(a), ..Default::default() }) .collect(); @@ -624,3 +635,58 @@ pub fn TargetsPage() -> Element { } } } + +/// The password of a stored, password-protected archive: its state, and a +/// field that checks and saves a new one at once (not with the editor's Save, +/// which never carries credentials). +#[component] +fn ArchivePasswordField( + target_id: String, + artifact_id: String, + state: ArchivePassword, + on_saved: EventHandler<()>, +) -> Element { + let lang = use_lang()(); + let mut password = use_signal(String::new); + let mut note = use_signal(|| Option::::None); + let (badge, label) = if state == ArchivePassword::Set { + ("badge badge-neutral", common::PASSWORD_SET) + } else { + ("badge badge-medium", common::PASSWORD_MISSING) + }; + rsx! { + span { class: "{badge}", {label.get(lang)} } + input { + r#type: "password", + autocomplete: "off", + placeholder: common::ARCHIVE_PASSWORD.get(lang), + style: "flex: 1; min-width: 180px;", + value: "{password}", + oninput: move |e| password.set(e.value()), + } + button { + class: "btn btn-ghost btn-sm", + disabled: password().is_empty(), + onclick: move |_| { + let (target_id, artifact_id, pw) = (target_id.clone(), artifact_id.clone(), password()); + spawn(async move { + let text = match set_archive_password(target_id, artifact_id, pw).await { + Ok(PasswordOutcome::Saved) => { + password.set(String::new()); + on_saved.call(()); + common::PASSWORD_SAVED.get(lang).to_string() + } + Ok(PasswordOutcome::Wrong) => common::PASSWORD_WRONG.get(lang).to_string(), + Ok(PasswordOutcome::NotEncrypted) => common::NOT_ENCRYPTED.get(lang).to_string(), + Err(e) => e.to_string(), + }; + note.set(Some(text)); + }); + }, + {common::SAVE_PASSWORD.get(lang)} + } + if let Some(text) = note() { + span { style: "font-size: 0.85em; opacity: 0.8;", "{text}" } + } + } +}