From 827980e53256b7ff8f5d3b0ed666a9729b25af9b Mon Sep 17 00:00:00 2001 From: Sharang Parnerkar <30073382+mighty840@users.noreply.github.com> Date: Wed, 23 Sep 2026 14:17:33 +0200 Subject: [PATCH] feat(targets): git tokens for private repositories, kept across edits (#303, #304) #303: no API path stored credentials on an artifact, so a private repository could not be cloned. Artifact inputs (create, add, update) now take an optional `token` and `username`; the token is sealed with SecretBox, never returned, and can be replaced (a value) or removed (an empty string). Left out, it is kept. #304: editing a target rebuilt every artifact from its input and dropped the git token, the uploaded file and the ingest record; enabling a scan replaced the whole scan config and dropped the issue tracker. An edited artifact now keeps what its stored counterpart (same kind and source) holds, and a scan-config update changes only the fields it names. Dashboard: a token (and optional username) field for git repositories in the wizard and the target editor, "token set" where one is stored, and a remove button. The editor also keeps a PLC project's format; it sent none, which reset a .projectarchive to PLCopen XML on every edit. Tests: unit tests for sealing, keeping, replacing and clearing a token, keeping an upload across an edit, and a scan-config merge; an integration test (MongoDB) that renames a target and enables a scan and finds both the git token and the tracker token still stored. Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_01EYKjxacrr6K88DruUmP48p --- compliance-agent/src/api/handlers/mod.rs | 1 + .../src/api/handlers/onboarding.rs | 110 +++---- .../src/api/handlers/target_input.rs | 299 ++++++++++++++++++ compliance-agent/tests/credentials.rs | 77 +++++ compliance-dashboard/src/i18n/texts.rs | 38 +++ .../src/infrastructure/onboarding.rs | 31 ++ compliance-dashboard/src/pages/onboarding.rs | 44 ++- compliance-dashboard/src/pages/targets.rs | 60 +++- 8 files changed, 581 insertions(+), 79 deletions(-) create mode 100644 compliance-agent/src/api/handlers/target_input.rs diff --git a/compliance-agent/src/api/handlers/mod.rs b/compliance-agent/src/api/handlers/mod.rs index 39d6139..69d7d09 100644 --- a/compliance-agent/src/api/handlers/mod.rs +++ b/compliance-agent/src/api/handlers/mod.rs @@ -17,6 +17,7 @@ pub mod platform; pub use pentest_handlers as pentest; pub mod sbom; pub mod scans; +pub mod target_input; pub mod werkbank_jobs; // Re-export all handler functions so routes.rs can use `handlers::function_name` diff --git a/compliance-agent/src/api/handlers/onboarding.rs b/compliance-agent/src/api/handlers/onboarding.rs index 4651439..0ed0c16 100644 --- a/compliance-agent/src/api/handlers/onboarding.rs +++ b/compliance-agent/src/api/handlers/onboarding.rs @@ -12,45 +12,22 @@ use mongodb::bson::{doc, oid::ObjectId, to_bson}; use serde::{Deserialize, Serialize}; use compliance_core::models::{ - Artifact, ArtifactKind, ComplianceProfile, Credentials, OnboardedTarget, PlcFormat, ScanRun, - TargetScanConfig, TargetType, + ArtifactKind, ComplianceProfile, Credentials, OnboardedTarget, PlcFormat, ScanRun, TargetType, }; use compliance_core::scan_matrix::{applicable_scans, supports_pentest}; use compliance_core::tenant_ctx::TenantCtx; use crate::agent::ComplianceAgent; use crate::classify::{classify_target, MockFirmwareDetector}; -use crate::secrets::{SecretBox, SecretError}; +use crate::secrets::SecretError; use crate::targets::{upload_dest, uploaded_artifact, MAX_UPLOAD_BYTES}; use super::dto::tenant_db; +use super::target_input::{merge_artifacts, ArtifactInput, ScanConfigUpdate}; use super::{collect_cursor_async, ApiResponse, PaginationParams}; type AgentExt = Extension>; -/// A client-supplied artifact spec. The server builds the [`Artifact`] (and its -/// id) from it, so clients never set internal fields. -#[derive(Deserialize)] -pub struct ArtifactInput { - pub kind: ArtifactKind, - pub source_ref: String, - #[serde(default)] - pub branch: Option, - #[serde(default)] - pub plc_format: Option, -} - -impl ArtifactInput { - fn build(&self) -> Artifact { - crate::targets::reference_artifact( - self.kind, - self.source_ref.clone(), - self.branch.clone(), - self.plc_format, - ) - } -} - #[derive(Deserialize)] pub struct CreateTargetRequest { pub name: String, @@ -65,10 +42,12 @@ pub struct CreateTargetRequest { pub struct UpdateTargetRequest { pub name: Option, pub target_type: Option, - pub scan_config: Option, + /// Fields left out keep their stored values. + pub scan_config: Option, pub compliance_profile: Option, pub scan_schedule: Option, - /// Replace the target's artifacts wholesale (used by the dashboard editor). + /// The target's artifacts (the dashboard editor sends all of them). Each + /// keeps the token and uploaded file of the stored artifact it matches. #[serde(default)] pub artifacts: Option>, } @@ -89,32 +68,6 @@ pub struct ApplicableScansResponse { pub pentest_supported: bool, } -/// Seal the credentials of a scan config sent in an update. The API never -/// returns credentials, so one left out keeps the stored value (see -/// [`SecretBox::take_update`]). -fn seal_scan_config_credentials( - secrets: &SecretBox, - incoming: &mut TargetScanConfig, - stored: &TargetScanConfig, -) -> Result<(), SecretError> { - if let Some(tracker) = incoming.issue_tracker.as_mut() { - let kept = stored.issue_tracker.as_ref().and_then(|t| t.token.as_ref()); - secrets.take_update(&mut tracker.token, kept)?; - } - if let Some(pentest) = incoming.pentest.as_mut() { - let kept = stored.pentest.as_ref().map(|p| &p.auth); - secrets.take_update( - &mut pentest.auth.password, - kept.and_then(|a| a.password.as_ref()), - )?; - secrets.take_update( - &mut pentest.auth.imap_password, - kept.and_then(|a| a.imap_password.as_ref()), - )?; - } - Ok(()) -} - fn parse_oid(id: &str) -> Result { ObjectId::parse_str(id).map_err(|_| StatusCode::BAD_REQUEST) } @@ -221,7 +174,10 @@ pub async fn create_target( ) -> Result>, StatusCode> { let mut target = OnboardedTarget::new(req.name, req.target_type); target.description = req.description; - target.artifacts = req.artifacts.iter().map(ArtifactInput::build).collect(); + target.artifacts = merge_artifacts(&agent.secrets, &req.artifacts, &[]).map_err(|e| { + tracing::error!("storing a credential: {e}"); + StatusCode::SERVICE_UNAVAILABLE + })?; let db = tenant_db(&agent, &tenant).await?; let res = db @@ -287,19 +243,26 @@ pub async fn update_target( to_bson(&tt).map_err(|_| StatusCode::BAD_REQUEST)?, ); } - if let Some(mut sc) = req.scan_config { - let stored = db - .onboarded_targets() - .find_one(doc! { "_id": oid }) - .await - .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)? - .ok_or(StatusCode::NOT_FOUND)?; - seal_scan_config_credentials(&agent.secrets, &mut sc, &stored.scan_config).map_err( - |e| { - tracing::error!("storing a credential: {e}"); - StatusCode::SERVICE_UNAVAILABLE - }, - )?; + // Both merge with what is stored, so the stored target is read once. + let stored = if req.scan_config.is_some() || req.artifacts.is_some() { + Some( + db.onboarded_targets() + .find_one(doc! { "_id": oid }) + .await + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)? + .ok_or(StatusCode::NOT_FOUND)?, + ) + } else { + None + }; + let credential_error = |e: SecretError| { + tracing::error!("storing a credential: {e}"); + StatusCode::SERVICE_UNAVAILABLE + }; + if let (Some(update), Some(stored)) = (req.scan_config, stored.as_ref()) { + let sc = update + .apply(&agent.secrets, &stored.scan_config) + .map_err(credential_error)?; set.insert( "scan_config", to_bson(&sc).map_err(|_| StatusCode::BAD_REQUEST)?, @@ -314,8 +277,9 @@ pub async fn update_target( if let Some(ss) = req.scan_schedule { set.insert("scan_schedule", ss); } - if let Some(arts) = req.artifacts { - let built: Vec = arts.iter().map(ArtifactInput::build).collect(); + if let (Some(arts), Some(stored)) = (req.artifacts, stored.as_ref()) { + let built = + merge_artifacts(&agent.secrets, &arts, &stored.artifacts).map_err(credential_error)?; set.insert( "artifacts", to_bson(&built).map_err(|_| StatusCode::BAD_REQUEST)?, @@ -463,7 +427,11 @@ pub async fn add_artifact( ) -> Result>, StatusCode> { let oid = parse_oid(&id)?; let db = tenant_db(&agent, &tenant).await?; - let artifact = to_bson(&input.build()).map_err(|_| StatusCode::BAD_REQUEST)?; + let artifact = input.build(&agent.secrets, None).map_err(|e| { + tracing::error!("storing a credential: {e}"); + StatusCode::SERVICE_UNAVAILABLE + })?; + let artifact = to_bson(&artifact).map_err(|_| StatusCode::BAD_REQUEST)?; db.onboarded_targets() .update_one( doc! { "_id": oid }, diff --git a/compliance-agent/src/api/handlers/target_input.rs b/compliance-agent/src/api/handlers/target_input.rs new file mode 100644 index 0000000..572ef0c --- /dev/null +++ b/compliance-agent/src/api/handlers/target_input.rs @@ -0,0 +1,299 @@ +//! What a client may send to create or change a target, and how it combines +//! with what is stored. +//! +//! The API never returns a credential, so a client that echoes a target back +//! (the dashboard's editor does) cannot send its git token or its uploaded +//! file. Anything left out therefore keeps its stored value: an artifact keeps +//! its token and its uploaded file, and a scan config keeps every field the +//! request does not name (#304). + +use serde::Deserialize; + +use compliance_core::models::{ + Artifact, ArtifactAuth, ArtifactKind, Environment, IssueTrackerConfig, PentestConfig, + PentestStrategy, PlcFormat, ScanType, TargetScanConfig, +}; + +use crate::secrets::{SecretBox, SecretError}; + +/// The auth method of a git access token. +const TOKEN_METHOD: &str = "token"; + +/// A client-supplied artifact spec. The server builds the [`Artifact`] (and its +/// id) from it, so clients never set internal fields. +#[derive(Debug, Deserialize)] +pub struct ArtifactInput { + pub kind: ArtifactKind, + pub source_ref: String, + #[serde(default)] + pub branch: Option, + #[serde(default)] + pub plc_format: Option, + /// A git access token for a private repository (#303). Sent: stored + /// sealed. Sent empty: removed. Left out: the stored one is kept. + #[serde(default)] + pub token: Option, + /// The username that goes with `token`; the clone uses `x-access-token` + /// when there is none. + #[serde(default)] + pub username: Option, +} + +impl ArtifactInput { + /// The artifact to store. `stored` is the artifact this input updates, if + /// any: its id, uploaded file, ingest record and credentials carry over. + /// + /// # Errors + /// + /// [`SecretError::NoKey`] when a new token arrives and the deployment has + /// no key to seal it with. + pub fn build( + &self, + secrets: &SecretBox, + stored: Option<&Artifact>, + ) -> Result { + let mut artifact = crate::targets::reference_artifact( + self.kind, + self.source_ref.clone(), + self.branch.clone(), + self.plc_format, + ); + if let Some(stored) = stored { + artifact.id = stored.id.clone(); + artifact.display_name = stored.display_name.clone(); + artifact.stored_path = stored.stored_path.clone(); + artifact.content_hash = stored.content_hash.clone(); + artifact.size_bytes = stored.size_bytes; + artifact.detected = stored.detected.clone(); + artifact.ingested_at = stored.ingested_at; + artifact.auth = stored.auth.clone(); + } + if self.kind == ArtifactKind::GitRepo { + artifact.auth = self.git_auth(secrets, stored.and_then(|s| s.auth.as_ref()))?; + } + Ok(artifact) + } + + /// The git credentials after this input: the token sealed, kept or + /// removed (see [`SecretBox::take_update`]), with its username. + fn git_auth( + &self, + secrets: &SecretBox, + stored: Option<&ArtifactAuth>, + ) -> Result, SecretError> { + let mut secret = self.token.clone(); + secrets.take_update(&mut secret, stored.and_then(|a| a.secret.as_ref()))?; + let Some(secret) = secret else { + return Ok(None); + }; + let username = self + .username + .clone() + .filter(|u| !u.trim().is_empty()) + .or_else(|| stored.and_then(|a| a.username.clone())); + Ok(Some(ArtifactAuth { + method: TOKEN_METHOD.to_string(), + username, + secret: Some(secret), + ..Default::default() + })) + } +} + +/// Build the artifacts of an update from `inputs`, carrying over what each +/// stored artifact holds that a client cannot send. An input matches the first +/// stored artifact of the same kind and source that no earlier input took. +/// +/// # Errors +/// +/// As [`ArtifactInput::build`]. +pub fn merge_artifacts( + secrets: &SecretBox, + inputs: &[ArtifactInput], + stored: &[Artifact], +) -> Result, SecretError> { + let mut taken = vec![false; stored.len()]; + inputs + .iter() + .map(|input| { + let matched = stored.iter().enumerate().position(|(i, a)| { + !taken[i] && a.kind == input.kind && a.source_ref == input.source_ref + }); + if let Some(i) = matched { + taken[i] = true; + } + input.build(secrets, matched.map(|i| &stored[i])) + }) + .collect() +} + +/// A change to a target's scan config. A field left out keeps its stored +/// value: enabling a scan must not remove the issue tracker (#304). +#[derive(Debug, Default, Deserialize)] +pub struct ScanConfigUpdate { + pub enabled_scans: Option>, + pub disabled_scans: Option>, + pub environment: Option, + pub allow_destructive: Option, + pub strategy: Option, + pub pentest: Option, + pub issue_tracker: Option, +} + +impl ScanConfigUpdate { + /// `stored` with this update applied. Credentials in a sent tracker or + /// pentest block are sealed; one left out of the block keeps the stored + /// value (the API never returns them). + /// + /// # Errors + /// + /// [`SecretError::NoKey`] when a new credential arrives without a key. + pub fn apply( + self, + secrets: &SecretBox, + stored: &TargetScanConfig, + ) -> Result { + let mut merged = stored.clone(); + if let Some(v) = self.enabled_scans { + merged.enabled_scans = v; + } + if let Some(v) = self.disabled_scans { + merged.disabled_scans = v; + } + if let Some(v) = self.environment { + merged.environment = v; + } + if let Some(v) = self.allow_destructive { + merged.allow_destructive = v; + } + if let Some(v) = self.strategy { + merged.strategy = Some(v); + } + if let Some(mut tracker) = self.issue_tracker { + let kept = stored.issue_tracker.as_ref().and_then(|t| t.token.as_ref()); + secrets.take_update(&mut tracker.token, kept)?; + merged.issue_tracker = Some(tracker); + } + if let Some(mut pentest) = self.pentest { + let kept = stored.pentest.as_ref().map(|p| &p.auth); + secrets.take_update( + &mut pentest.auth.password, + kept.and_then(|a| a.password.as_ref()), + )?; + secrets.take_update( + &mut pentest.auth.imap_password, + kept.and_then(|a| a.imap_password.as_ref()), + )?; + merged.pentest = Some(pentest); + } + Ok(merged) + } +} + +#[cfg(test)] +#[allow(clippy::expect_used, clippy::unwrap_used)] +mod tests { + use super::*; + + fn secrets() -> SecretBox { + SecretBox::from_key(&[7u8; 32]).expect("32-byte key") + } + + fn input(kind: ArtifactKind, source_ref: &str) -> ArtifactInput { + ArtifactInput { + kind, + source_ref: source_ref.to_string(), + branch: None, + plc_format: None, + token: None, + username: None, + } + } + + fn git_input(token: Option<&str>) -> ArtifactInput { + ArtifactInput { + branch: Some("main".to_string()), + token: token.map(String::from), + ..input(ArtifactKind::GitRepo, "https://git.example.com/acme/fw.git") + } + } + + #[test] + fn a_new_git_token_is_stored_sealed() { + let s = secrets(); + let artifact = git_input(Some("pat-123")).build(&s, None).unwrap(); + let auth = artifact.auth.expect("auth"); + assert_eq!(auth.method, TOKEN_METHOD); + let sealed = auth.secret.expect("secret"); + assert!(SecretBox::is_sealed(&sealed)); + assert_eq!(s.open(&sealed).unwrap(), "pat-123"); + } + + #[test] + fn an_edit_without_the_token_keeps_it_and_the_upload() { + let s = secrets(); + let mut stored = git_input(Some("pat-123")).build(&s, None).unwrap(); + stored.content_hash = Some("abc".into()); + let upload = Artifact { + stored_path: Some("/data/uploads/fw.tar.gz".into()), + ..crate::targets::reference_artifact( + ArtifactKind::SourceArchive, + "fw.tar.gz".into(), + None, + None, + ) + }; + let stored_all = vec![stored.clone(), upload.clone()]; + + // What the dashboard's editor sends: no token, no stored path. + let inputs = vec![ + git_input(None), + input(ArtifactKind::SourceArchive, "fw.tar.gz"), + ]; + let merged = merge_artifacts(&s, &inputs, &stored_all).unwrap(); + + assert_eq!(merged[0].id, stored.id); + assert_eq!( + merged[0].auth.as_ref().unwrap().secret, + stored.auth.unwrap().secret + ); + assert_eq!(merged[0].content_hash.as_deref(), Some("abc")); + assert_eq!(merged[1].id, upload.id); + assert_eq!(merged[1].stored_path, upload.stored_path); + } + + #[test] + fn a_token_can_be_replaced_or_cleared() { + let s = secrets(); + let stored = git_input(Some("old")).build(&s, None).unwrap(); + + let replaced = git_input(Some("new")).build(&s, Some(&stored)).unwrap(); + let secret = replaced.auth.unwrap().secret.unwrap(); + assert_eq!(s.open(&secret).unwrap(), "new"); + + let cleared = git_input(Some("")).build(&s, Some(&stored)).unwrap(); + assert!(cleared.auth.is_none()); + } + + #[test] + fn enabling_a_scan_keeps_the_tracker_and_its_token() { + let s = secrets(); + let stored = TargetScanConfig { + issue_tracker: Some(IssueTrackerConfig { + token: Some(s.seal("tracker-pat").unwrap()), + ..Default::default() + }), + ..Default::default() + }; + let update = ScanConfigUpdate { + enabled_scans: Some(vec![ScanType::IcsProbe]), + ..Default::default() + }; + let merged = update.apply(&s, &stored).unwrap(); + assert_eq!(merged.enabled_scans, vec![ScanType::IcsProbe]); + assert_eq!( + merged.issue_tracker.unwrap().token, + stored.issue_tracker.unwrap().token + ); + } +} diff --git a/compliance-agent/tests/credentials.rs b/compliance-agent/tests/credentials.rs index 8b78779..036e729 100644 --- a/compliance-agent/tests/credentials.rs +++ b/compliance-agent/tests/credentials.rs @@ -185,6 +185,83 @@ async fn a_tracker_token_is_stored_sealed_and_never_returned() { h.cleanup().await; } +/// The sealed git token of the stored target's first artifact. +fn stored_git_token(target: &Document) -> Option { + target + .get_array("artifacts") + .ok()? + .first()? + .as_document()? + .get_document("auth") + .ok()? + .get_str("secret") + .ok() + .map(String::from) +} + +#[tokio::test] +async fn a_git_token_survives_editing_the_target_and_enabling_a_scan() { + let Some(h) = start().await else { return }; + let secrets = SecretBox::from_hex(TEST_SECRETS_KEY).unwrap(); + let repo = "https://git.example.com/acme/fw.git"; + + // Arrange: a private repository onboarded with a token, and a tracker. + let created = h + .send( + reqwest::Method::POST, + "/api/v1/targets", + serde_json::json!({ + "name": "fw", + "target_type": "firmware_bare_metal", + "artifacts": [{ "kind": "git_repo", "source_ref": repo, "token": "git-secret" }], + }), + ) + .await; + assert!(!created.contains("git-secret"), "token leaked: {created}"); + let created: serde_json::Value = serde_json::from_str(&created).unwrap(); + let id = created["data"]["_id"]["$oid"].as_str().unwrap().to_string(); + let path = format!("/api/v1/targets/{id}"); + h.send( + reqwest::Method::PATCH, + &path, + tracker_update(Some("tracker-secret")), + ) + .await; + let token = stored_git_token(&h.stored(&id).await).expect("git token stored"); + assert!(SecretBox::is_sealed(&token)); + assert_eq!(secrets.open(&token).unwrap(), "git-secret"); + let tracker = stored_tracker_token(&h.stored(&id).await).expect("tracker token"); + + // Act: what the dashboard's editor sends (every artifact, no token), then + // what "enable opt-in scans" sends. + let renamed = h + .send( + reqwest::Method::PATCH, + &path, + serde_json::json!({ + "name": "fw-renamed", + "artifacts": [{ "kind": "git_repo", "source_ref": repo, "branch": "main" }], + }), + ) + .await; + h.send( + reqwest::Method::PATCH, + &path, + serde_json::json!({ "scan_config": { "enabled_scans": ["icsprobe"] } }), + ) + .await; + + // Assert: both credentials are still stored, and none is returned. + let stored = h.stored(&id).await; + assert_eq!(stored_git_token(&stored).as_ref(), Some(&token)); + assert_eq!(stored_tracker_token(&stored).as_ref(), Some(&tracker)); + assert!(!renamed.contains("git-secret") && !renamed.contains("enc:v1:")); + let renamed: serde_json::Value = serde_json::from_str(&renamed).unwrap(); + assert_eq!(renamed["data"]["artifacts"][0]["auth"]["method"], "token"); + + h.cleanup().await; +} + #[tokio::test] async fn credentials_stored_before_sealing_are_sealed_at_startup() { let Some(h) = start().await else { return }; diff --git a/compliance-dashboard/src/i18n/texts.rs b/compliance-dashboard/src/i18n/texts.rs index a5b4bbf..26401bf 100644 --- a/compliance-dashboard/src/i18n/texts.rs +++ b/compliance-dashboard/src/i18n/texts.rs @@ -503,6 +503,26 @@ pub mod targets { de: "+ Hinzufügen", en: "+ Add", }; + pub const TOKEN: Text = Text { + de: "Zugangstoken", + en: "Access token", + }; + pub const TOKEN_SET: Text = Text { + de: "Token gesetzt", + en: "token set", + }; + pub const NEW_TOKEN: Text = Text { + de: "Neues Token (leer lassen, um es zu behalten)", + en: "New token (leave empty to keep it)", + }; + pub const REMOVE_TOKEN: Text = Text { + de: "Token entfernen", + en: "Remove token", + }; + pub const TOKEN_REMOVED: Text = Text { + de: "Token wird beim Speichern entfernt", + en: "token is removed on save", + }; } /// Target types and artifact kinds, keyed by their API value. @@ -772,6 +792,24 @@ pub mod onboarding { de: "+ Hinzufügen", en: "+ Add", }; + pub const TOKEN: Text = Text { + de: "Zugangstoken (nur für private Repositories)", + en: "Access token (private repositories only)", + }; + pub const USERNAME: Text = Text { + de: "Benutzername (optional)", + en: "Username (optional)", + }; + pub const TOKEN_HINT: Text = Text { + de: "Ein Token mit Leserecht auf das Repository. Es wird verschlüsselt \ + gespeichert und nie wieder angezeigt.", + en: "A token with read access to the repository. It is stored encrypted \ + and never shown again.", + }; + pub const TOKEN_SET: Text = Text { + de: "Token gesetzt", + en: "token set", + }; pub const SELECTED: Text = Text { de: "Ausgewählt", en: "Selected", diff --git a/compliance-dashboard/src/infrastructure/onboarding.rs b/compliance-dashboard/src/infrastructure/onboarding.rs index 092f8b9..a75aa99 100644 --- a/compliance-dashboard/src/infrastructure/onboarding.rs +++ b/compliance-dashboard/src/infrastructure/onboarding.rs @@ -13,6 +13,17 @@ pub struct ArtifactInputDto { pub branch: Option, #[serde(skip_serializing_if = "Option::is_none")] pub plc_format: Option, + /// A git access token to store (#303): a value replaces the stored one, + /// an empty string removes it, and `None` keeps it. + #[serde(skip_serializing_if = "Option::is_none")] + pub token: Option, + /// The username for `token` (`x-access-token` when unset). + #[serde(skip_serializing_if = "Option::is_none")] + pub username: Option, + /// Whether a token is stored for this artifact. Display only: the agent + /// never returns the token itself, and this is never sent. + #[serde(skip)] + pub has_token: bool, } #[derive(Debug, Clone, Serialize, Deserialize, Default)] @@ -403,6 +414,26 @@ pub async fn trigger_target_scan(id: String) -> Result, error: Option<&str>) -> DemoSeedResult { DemoSeedResult { name: "plc-pump-station".into(), diff --git a/compliance-dashboard/src/pages/onboarding.rs b/compliance-dashboard/src/pages/onboarding.rs index 481dee6..24e29f7 100644 --- a/compliance-dashboard/src/pages/onboarding.rs +++ b/compliance-dashboard/src/pages/onboarding.rs @@ -115,6 +115,8 @@ pub fn OnboardingPage() -> Element { let mut new_kind = use_signal(|| "git_repo".to_string()); let mut new_source = use_signal(String::new); let mut new_branch = use_signal(|| "main".to_string()); + let mut new_token = use_signal(String::new); + let mut new_username = use_signal(String::new); // File-upload artifacts (PLC project, firmware image, ...). let mut new_plc_format = use_signal(|| "plcopen_xml".to_string()); let mut new_file = use_signal(|| Option::<(String, dioxus::html::FileData)>::None); @@ -344,20 +346,50 @@ pub fn OnboardingPage() -> Element { if !new_source().trim().is_empty() && validate_artifact_ref(&kind, &new_source()).is_none() { - let branch = if kind == "git_repo" { Some(new_branch()) } else { None }; + let git = kind == "git_repo"; + let non_empty = |v: String| (git && !v.trim().is_empty()).then_some(v); + let token = non_empty(new_token()); artifacts.write().push(ArtifactInputDto { + branch: git.then_some(new_branch()), + has_token: token.is_some(), + token, + username: non_empty(new_username()), kind, source_ref: new_source(), - branch, plc_format: None, }); new_source.set(String::new()); + new_token.set(String::new()); + new_username.set(String::new()); } }, {tx::ADD.get(lang)} } } } + if new_kind() == "git_repo" { + div { style: "display: flex; gap: 8px; flex-wrap: wrap; align-items: flex-end; margin-top: 8px;", + div { class: "form-group", style: "margin: 0; flex: 1; min-width: 240px;", + label { {tx::TOKEN.get(lang)} } + input { + r#type: "password", + autocomplete: "off", + value: "{new_token}", + oninput: move |e| new_token.set(e.value()), + } + } + div { class: "form-group", style: "margin: 0;", + label { {tx::USERNAME.get(lang)} } + input { + r#type: "text", + placeholder: "x-access-token", + value: "{new_username}", + oninput: move |e| new_username.set(e.value()), + } + } + } + div { style: "font-size: 0.8em; opacity: 0.7; margin-top: 4px;", {tx::TOKEN_HINT.get(lang)} } + } if is_file_kind(&new_kind()) { if let Some((fname, data)) = new_file() { div { style: "font-size: 0.85em; opacity: 0.7; margin-top: 6px;", @@ -391,6 +423,9 @@ pub fn OnboardingPage() -> Element { span { span { style: "opacity: 0.7;", "{kind_label(&a.kind)}: " } "{a.source_ref}" + if a.has_token { + span { class: "badge badge-neutral", style: "margin-left: 6px;", {tx::TOKEN_SET.get(lang)} } + } } button { class: "btn btn-ghost-danger btn-sm", @@ -416,7 +451,10 @@ pub fn OnboardingPage() -> Element { div { strong { "{tx::ARTIFACTS.get(lang)}:" } } ul { for a in artifacts() { - li { "{kind_label(&a.kind)}: {a.source_ref}" } + li { + "{kind_label(&a.kind)}: {a.source_ref}" + if a.has_token { " ({tx::TOKEN_SET.get(lang)})" } + } } for pf in pending_files() { li { "{kind_label(&pf.kind)}: {pf.filename} ({format_bytes(pf.file.size(), lang)})" } diff --git a/compliance-dashboard/src/pages/targets.rs b/compliance-dashboard/src/pages/targets.rs index 444f75f..ef03593 100644 --- a/compliance-dashboard/src/pages/targets.rs +++ b/compliance-dashboard/src/pages/targets.rs @@ -126,6 +126,7 @@ pub fn TargetsPage() -> Element { let mut e_kind = use_signal(|| "git_repo".to_string()); let mut e_source = use_signal(String::new); let mut e_branch = use_signal(|| "main".to_string()); + let mut e_token = use_signal(String::new); let mut targets = use_resource(move || async move { fetch_targets().await.ok() }); let lang = use_lang()(); @@ -224,10 +225,34 @@ pub fn TargetsPage() -> Element { } label { style: "font-weight: 600;", {tx::ARTIFACTS.get(lang)} } for (i, a) in edit_arts().iter().enumerate() { - div { style: "display: flex; justify-content: space-between; align-items: center; padding: 4px 0;", + div { style: "display: flex; justify-content: space-between; align-items: center; gap: 8px; padding: 4px 0; flex-wrap: wrap;", span { style: "font-size: 0.9em;", span { style: "opacity: 0.7;", "{kinds::artifact_kind(&a.kind, lang)}: " } span { style: "font-family: monospace;", "{a.source_ref}" } + if a.token.as_deref() == Some("") { + span { class: "badge badge-medium", style: "margin-left: 6px;", {tx::TOKEN_REMOVED.get(lang)} } + } else if a.has_token { + span { class: "badge badge-neutral", style: "margin-left: 6px;", {tx::TOKEN_SET.get(lang)} } + } + } + if a.kind == "git_repo" { + input { + r#type: "password", + autocomplete: "off", + placeholder: tx::NEW_TOKEN.get(lang), + style: "flex: 1; min-width: 180px;", + oninput: move |e| { + let v = e.value(); + edit_arts.write()[i].token = (!v.is_empty()).then_some(v); + }, + } + if a.has_token { + button { + class: "btn btn-ghost btn-sm", + onclick: move |_| { edit_arts.write()[i].token = Some(String::new()); }, + {tx::REMOVE_TOKEN.get(lang)} + } + } } button { class: "btn btn-ghost btn-ghost-danger btn-sm", @@ -264,6 +289,15 @@ pub fn TargetsPage() -> Element { oninput: move |e| e_branch.set(e.value()), } } + div { class: "form-group", style: "margin: 0;", + label { {tx::TOKEN.get(lang)} } + input { + r#type: "password", + autocomplete: "off", + value: "{e_token}", + oninput: move |e| e_token.set(e.value()), + } + } } button { class: "btn btn-secondary", @@ -273,14 +307,18 @@ pub fn TargetsPage() -> Element { if !e_source().trim().is_empty() && validate_artifact_ref(&kind, &e_source()).is_none() { - let branch = if kind == "git_repo" { Some(e_branch()) } else { None }; + let git = kind == "git_repo"; + let token = (git && !e_token().trim().is_empty()).then_some(e_token()); edit_arts.write().push(ArtifactInputDto { + branch: git.then_some(e_branch()), + has_token: token.is_some(), + token, kind, source_ref: e_source(), - branch, - plc_format: None, + ..Default::default() }); e_source.set(String::new()); + e_token.set(String::new()); } }, {tx::ADD_ARTIFACT.get(lang)} @@ -456,7 +494,19 @@ pub fn TargetsPage() -> Element { .and_then(|g| g.get("default_branch")) .and_then(|b| b.as_str()) .map(String::from), - plc_format: None, + // Kept, or an edit would reset a project + // archive to PLCopen XML. + plc_format: a + .get("plc") + .and_then(|p| p.get("format")) + .and_then(|f| f.as_str()) + .map(String::from), + has_token: a + .get("auth") + .and_then(|x| x.get("method")) + .and_then(|m| m.as_str()) + == Some("token"), + ..Default::default() }) .collect(); edit_arts.set(arts); -- 2.54.1