This commit was merged in pull request #346.
This commit is contained in:
1 parent
8386032565
commit
fe318c2b85
8 files changed
+581
-79
No files matched your search
@@ -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`
|
||||
|
||||
@@ -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<Arc<ComplianceAgent>>;
|
||||
|
||||
/// 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<String>,
|
||||
#[serde(default)]
|
||||
pub plc_format: Option<PlcFormat>,
|
||||
}
|
||||
|
||||
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<String>,
|
||||
pub target_type: Option<TargetType>,
|
||||
pub scan_config: Option<TargetScanConfig>,
|
||||
/// Fields left out keep their stored values.
|
||||
pub scan_config: Option<ScanConfigUpdate>,
|
||||
pub compliance_profile: Option<ComplianceProfile>,
|
||||
pub scan_schedule: Option<String>,
|
||||
/// 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<Vec<ArtifactInput>>,
|
||||
}
|
||||
@@ -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, StatusCode> {
|
||||
ObjectId::parse_str(id).map_err(|_| StatusCode::BAD_REQUEST)
|
||||
}
|
||||
@@ -221,7 +174,10 @@ pub async fn create_target(
|
||||
) -> Result<Json<ApiResponse<OnboardedTarget>>, 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<Artifact> = 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<Json<ApiResponse<OnboardedTarget>>, 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 },
|
||||
|
||||
@@ -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<String>,
|
||||
#[serde(default)]
|
||||
pub plc_format: Option<PlcFormat>,
|
||||
/// 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<String>,
|
||||
/// The username that goes with `token`; the clone uses `x-access-token`
|
||||
/// when there is none.
|
||||
#[serde(default)]
|
||||
pub username: Option<String>,
|
||||
}
|
||||
|
||||
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<Artifact, SecretError> {
|
||||
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<Option<ArtifactAuth>, 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<Vec<Artifact>, 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<Vec<ScanType>>,
|
||||
pub disabled_scans: Option<Vec<ScanType>>,
|
||||
pub environment: Option<Environment>,
|
||||
pub allow_destructive: Option<bool>,
|
||||
pub strategy: Option<PentestStrategy>,
|
||||
pub pentest: Option<PentestConfig>,
|
||||
pub issue_tracker: Option<IssueTrackerConfig>,
|
||||
}
|
||||
|
||||
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<TargetScanConfig, SecretError> {
|
||||
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
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -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<String> {
|
||||
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 };
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -13,6 +13,17 @@ pub struct ArtifactInputDto {
|
||||
pub branch: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub plc_format: Option<String>,
|
||||
/// 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<String>,
|
||||
/// The username for `token` (`x-access-token` when unset).
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub username: Option<String>,
|
||||
/// 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<serde_json::Value, Server
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn a_token_is_sent_only_when_it_changes() {
|
||||
let kept = ArtifactInputDto {
|
||||
kind: "git_repo".into(),
|
||||
source_ref: "https://git.example.com/a.git".into(),
|
||||
has_token: true,
|
||||
..Default::default()
|
||||
};
|
||||
let json = serde_json::to_value(&kept).unwrap_or_default();
|
||||
assert!(json.get("token").is_none(), "{json}");
|
||||
assert!(json.get("has_token").is_none(), "{json}");
|
||||
|
||||
let removed = ArtifactInputDto {
|
||||
token: Some(String::new()),
|
||||
..kept
|
||||
};
|
||||
let json = serde_json::to_value(&removed).unwrap_or_default();
|
||||
assert_eq!(json["token"], "");
|
||||
}
|
||||
|
||||
fn result(status: &str, scan: Option<&str>, error: Option<&str>) -> DemoSeedResult {
|
||||
DemoSeedResult {
|
||||
name: "plc-pump-station".into(),
|
||||
|
||||
@@ -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)})" }
|
||||
|
||||
@@ -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);
|
||||
|
||||
Reference in new issue
Block a user