fix(supplier): check through an invite, keep the customer's CSAF provider (#1027)
CI / Check (push) Skipped
CI / Detect Changes (pull_request) Skipped
CI / Deploy Agent (pull_request) Skipped
CI / Deploy Dashboard (pull_request) Skipped
CI / Deploy Docs (pull_request) Skipped
CI / Deploy MCP (pull_request) Skipped
CI / Agent integration (pull_request) Successful in 4m54s
CI / Check (pull_request) Successful in 21m35s

- `POST …/supplier-invites/{invite}/sboms/check`: the supplier page checks a
  file before it is uploaded, as the wizard does; nothing is stored.
- A CSAF provider from the supplier is set only when the component has none.
- A component whose supplier was removed takes no upload (404).
- A registry answer without a status limits nothing, as for a person's
  request; tested against a fake registry for every status.
- `attach_upload` takes the file name with the upload (five parameters).
- Tests: the same file name twice keeps the new file, an accepted upload
  starts a scan.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Q9inRcu428A2iNjDHPEAT9
This commit is contained in:
Sharang ParnerkarandClaude Opus 5.5 committed 2026-11-18 11:53:59 +01:00
1 parent 2f87227bae
commit c1f2d2b8ab
5 files changed
+245 -33

No files matched your search

@@ -922,7 +922,7 @@ pub async fn upload_artifact(
}
let dest = upload_dest(&agent, &id, &filename)
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
let mut upload = StoredUpload::new(dest);
let mut upload = StoredUpload::new(dest, filename.clone());
upload.size = stream_to_disk(&mut field, &upload.path, MAX_UPLOAD_BYTES).await?;
stored = Some(upload);
}
@@ -933,7 +933,7 @@ pub async fn upload_artifact(
let (Some(kind), Some(upload)) = (kind, stored) else {
return Err(StatusCode::BAD_REQUEST.into());
};
attach_upload(&db, &stored_target, kind, plc_format, &filename, upload).await?;
attach_upload(&db, &stored_target, kind, plc_format, upload).await?;
Ok(get_target(Extension(agent), tenant, Path(id)).await?)
}
@@ -967,13 +967,12 @@ pub(super) async fn attach_upload(
target: &OnboardedTarget,
kind: ArtifactKind,
plc_format: Option<PlcFormat>,
filename: &str,
upload: StoredUpload,
) -> Result<AttachedUpload, UploadRefusal> {
let oid = target.id.ok_or(StatusCode::INTERNAL_SERVER_ERROR)?;
// Non-file kinds (git repo, live URL, container ref, text) use the JSON
// add-artifact endpoint, not upload.
let mut artifact = uploaded_artifact(kind, plc_format, filename, &upload.path, upload.size)
let mut artifact = uploaded_artifact(kind, plc_format, &upload.name, &upload.path, upload.size)
.ok_or(StatusCode::BAD_REQUEST)?;
// What a scheduled scan compares to tell this upload from the files its
// last scan read (#465): without it, no upload was ever known unchanged.
@@ -1411,15 +1410,19 @@ pub(super) async fn stream_to_disk(
/// rejected, oversized or half-received upload from being left on disk.
pub(super) struct StoredUpload {
pub path: std::path::PathBuf,
/// The file's name, as it was sent.
pub name: String,
pub size: u64,
keep: bool,
}
impl StoredUpload {
/// A file about to be written at `path`, deleted unless it is kept.
pub(super) fn new(path: std::path::PathBuf) -> Self {
/// The file `name`, about to be written at `path`, deleted unless it is
/// kept.
pub(super) fn new(path: std::path::PathBuf, name: String) -> Self {
Self {
path,
name,
size: 0,
keep: false,
}
@@ -428,13 +428,15 @@ async fn accepts_writes(agent: &ComplianceAgent, tenant_id: &str) -> Result<(),
tracing::error!(tenant_id, "entitlement check unavailable: {e}");
StatusCode::SERVICE_UNAVAILABLE
})?;
// A status it does not name or Prüfwerk does not know limits nothing, as
// for a person's request (`require_entitlement`).
let status = check
.status
.as_deref()
.and_then(compliance_core::TenantStatus::parse);
let writable = check.allowed
&& !check.read_only
&& status.is_some_and(|s| !s.blocks_writes() && !s.is_halted() && !s.is_archived());
&& status.is_none_or(|s| !s.blocks_writes() && !s.is_halted() && !s.is_archived());
if writable {
Ok(())
} else {
@@ -578,8 +580,8 @@ pub async fn withdraw_invite(
///
/// # Errors
///
/// 404 when there is no such invite, or its component is gone; 410 with the
/// code `expired` or `withdrawn`.
/// 404 when there is no such invite, or its component is gone or no longer a
/// supplier component; 410 with the code `expired` or `withdrawn`.
pub async fn supplier_view(
State(st): State<PlatformState>,
Path((tenant_id, invite_id)): Path<(String, String)>,
@@ -599,7 +601,6 @@ pub async fn supplier_view(
.into_iter()
.map(|u| UploadView::of(u, sbom.as_deref()))
.collect();
// A target loses its invites with its supplier only when it is deleted.
let (product, version, csaf_provider) = target
.supplier
.map(|s| (s.product, s.version, s.csaf_provider))
@@ -614,11 +615,12 @@ pub async fn supplier_view(
}))
}
/// The component `invite` is for.
/// The component `invite` is for, while it is a supplier component.
///
/// # Errors
///
/// 404 when it is gone.
/// 404 when it is gone, or names no supplier any more (the customer removed
/// it in the target editor).
async fn invite_target(
db: &Database,
invite: &SupplierInvite,
@@ -626,7 +628,7 @@ async fn invite_target(
let id = ObjectId::parse_str(&invite.target_id).map_err(|_| StatusCode::NOT_FOUND)?;
Ok(db
.onboarded_targets()
.find_one(doc! { "_id": id })
.find_one(doc! { "_id": id, "supplier": { "$ne": null } })
.await
.map_err(internal)?
.ok_or(StatusCode::NOT_FOUND)?)
@@ -639,12 +641,13 @@ async fn invite_target(
/// (the supplier's `provider-metadata.json`, an https URL). An accepted SBOM
/// becomes the component's SBOM, replacing the one before, exactly as a
/// customer's upload does, and a scan starts. A CSAF provider given with it
/// becomes the component's. Every upload is recorded, refused ones with their
/// code; the answer is the record (201).
/// becomes the component's when it has none yet. Every upload is recorded,
/// refused ones with their code; the answer is the record (201).
///
/// # Errors
///
/// - 404: no such invite, or its component is gone.
/// - 404: no such invite, or its component is gone or no longer a supplier
/// component.
/// - 410 (`expired`, `withdrawn`): the invite allows nothing more.
/// - 403 (`read_only`): the workspace takes no uploads now; 503 when the
/// registry cannot say.
@@ -699,7 +702,7 @@ pub async fn upload_through_invite(
filename = shown_filename(field.file_name().unwrap_or_default());
let dest = crate::targets::upload_dest(&st.agent, &invite.target_id, &filename)
.map_err(internal)?;
let mut upload = StoredUpload::new(dest);
let mut upload = StoredUpload::new(dest, filename.clone());
match stream_to_disk(&mut field, &upload.path, MAX_SBOM_BYTES).await {
Ok(size) => upload.size = size,
Err(StatusCode::PAYLOAD_TOO_LARGE) => {
@@ -729,20 +732,18 @@ pub async fn upload_through_invite(
);
return Err(refused(&db, &invite, &filename, refusal).await);
}
let attached = match attach_upload(
&db,
&target,
ArtifactKind::SupplierSbom,
None,
&filename,
upload,
)
.await
let attached = match attach_upload(&db, &target, ArtifactKind::SupplierSbom, None, upload).await
{
Ok(attached) => attached,
Err(refusal) => return Err(refused(&db, &invite, &filename, refusal).await),
};
if let (Some(url), Some(mut supplier)) = (&csaf_provider, target.supplier.clone()) {
// Only a component without one takes the supplier's provider: one the
// customer set stays. The upload keeps what the supplier gave either way.
let unset = target
.supplier
.clone()
.filter(|supplier| supplier.csaf_provider.is_none());
if let (Some(url), Some(mut supplier)) = (&csaf_provider, unset) {
supplier.csaf_provider = Some(url.clone());
let set = mongodb::bson::to_bson(&supplier).map_err(internal)?;
db.onboarded_targets()
@@ -780,6 +781,25 @@ pub async fn upload_through_invite(
Ok((StatusCode::CREATED, Json(UploadView::of(record, current))))
}
/// `POST /api/v1/platform/tenants/{id}/supplier-invites/{invite}/sboms/check`:
/// what the supplier's page shows of a file before it is uploaded, through a
/// valid invite: the same check as `POST /api/v1/supplier-sboms/check`.
/// Nothing is stored or recorded.
///
/// # Errors
///
/// 404 and 410 as for [`upload_through_invite`]; the check's own refusals.
pub async fn check_through_invite(
State(st): State<PlatformState>,
Path((tenant_id, invite_id)): Path<(String, String)>,
multipart: Multipart,
) -> Result<Json<super::ApiResponse<SupplierSbomSummary>>, UploadRefusal> {
let db = st.agent.db_pool.for_existing_tenant_id(&tenant_id);
let invite = open_invite(&db, &invite_id).await?;
invite_target(&db, &invite).await?;
super::onboarding::check_supplier_sbom(multipart).await
}
/// Record `refusal` of an upload of `filename` through `invite`, when it has a
/// code the supplier can act on, and hand it back. A failed record is logged:
/// the refusal stands either way.
+6
View File
@@ -386,6 +386,12 @@ pub async fn start_api_server(
crate::pipeline::sbom::supplied::MAX_BYTES as usize + routes::MULTIPART_OVERHEAD,
)),
)
.route(
"/api/v1/platform/tenants/{id}/supplier-invites/{invite}/sboms/check",
post(supplier_invites::check_through_invite).layer(DefaultBodyLimit::max(
crate::pipeline::sbom::supplied::MAX_BYTES as usize + routes::MULTIPART_OVERHEAD,
)),
)
.layer(middleware::from_fn_with_state(
platform_state.clone(),
platform::require_platform_token,
+182 -4
View File
@@ -34,6 +34,11 @@ struct Harness {
}
async fn start() -> Option<Harness> {
start_with(None).await
}
/// The harness with `registry` as the agent's tenant registry.
async fn start_with(registry: Option<String>) -> Option<Harness> {
let uri = std::env::var("TEST_MONGODB_URI")
.unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into());
let db_name = format!("si_{}", &uuid::Uuid::new_v4().simple().to_string()[..12]);
@@ -42,7 +47,9 @@ async fn start() -> Option<Harness> {
return None;
};
let db = pool.for_tenant_id(TENANT).await.expect("tenant db");
let agent = Arc::new(ComplianceAgent::new(dev_config(uri, db_name), pool.clone()));
let mut config = dev_config(uri, db_name);
config.tenant_registry_url = registry;
let agent = Arc::new(ComplianceAgent::new(config, pool.clone()));
let state = PlatformState { agent, jwks: None };
let app = Router::new()
.route(
@@ -65,6 +72,10 @@ async fn start() -> Option<Harness> {
"/api/v1/platform/tenants/{id}/supplier-invites/{invite}/sboms",
post(supplier_invites::upload_through_invite),
)
.route(
"/api/v1/platform/tenants/{id}/supplier-invites/{invite}/sboms/check",
post(supplier_invites::check_through_invite),
)
.with_state(state);
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let port = listener.local_addr().unwrap().port();
@@ -131,6 +142,23 @@ impl Harness {
invite: &str,
file: Option<(&str, Vec<u8>)>,
csaf_provider: Option<&str>,
) -> (u16, Value) {
self.send_sbom("sboms", tenant, invite, file, csaf_provider)
.await
}
async fn check(&self, tenant: &str, invite: &str, bytes: Vec<u8>) -> (u16, Value) {
self.send_sbom("sboms/check", tenant, invite, Some(("x.json", bytes)), None)
.await
}
async fn send_sbom(
&self,
route: &str,
tenant: &str,
invite: &str,
file: Option<(&str, Vec<u8>)>,
csaf_provider: Option<&str>,
) -> (u16, Value) {
let mut form = reqwest::multipart::Form::new();
if let Some(url) = csaf_provider {
@@ -145,7 +173,7 @@ impl Harness {
let resp = self
.client
.post(format!(
"{}/api/v1/platform/tenants/{tenant}/supplier-invites/{invite}/sboms",
"{}/api/v1/platform/tenants/{tenant}/supplier-invites/{invite}/{route}",
self.base_url
))
.multipart(form)
@@ -397,6 +425,48 @@ async fn a_supplier_uploads_versions_through_its_invite() {
.filter(|a| a.kind == ArtifactKind::SupplierSbom)
.collect();
assert_eq!(sboms.len(), 1, "a new version replaces the one before");
// The same name again, and another provider: the file the new SBOM
// points to stays, and the provider the component has stays too.
let (status, third) = h
.upload(
TENANT,
id,
Some(("dr4-1.1.cdx.json", sbom(3))),
Some("https://other.example/provider-metadata.json"),
)
.await;
assert_eq!(status, 201, "{third}");
assert_eq!(
third["csaf_provider"], "https://other.example/provider-metadata.json",
"the upload keeps what the supplier gave"
);
let stored = h.stored_target(&target).await;
let kept = stored
.artifacts
.iter()
.find(|a| a.kind == ArtifactKind::SupplierSbom)
.and_then(|a| a.stored_path.clone())
.unwrap();
assert!(std::path::Path::new(&kept).exists(), "{kept}");
assert_eq!(
stored.supplier.unwrap().csaf_provider.as_deref(),
Some(provider),
"a provider the component has is not replaced"
);
// Each accepted upload starts a scan of the component.
let mut scans = 0;
for _ in 0..50 {
scans =
h.db.scan_runs()
.count_documents(doc! { "repo_id": &target })
.await
.unwrap();
if scans > 0 {
break;
}
tokio::time::sleep(std::time::Duration::from_millis(100)).await;
}
assert!(scans > 0, "a scan started");
let (_, page) = h.supplier_view(TENANT, id).await;
let shown: Vec<(&str, bool)> = page["uploads"]
@@ -412,7 +482,11 @@ async fn a_supplier_uploads_versions_through_its_invite() {
.collect();
assert_eq!(
shown,
[("dr4-1.1.cdx.json", true), ("dr4-1.0.cdx.json", false)]
[
("dr4-1.1.cdx.json", true),
("dr4-1.1.cdx.json", false),
("dr4-1.0.cdx.json", false)
]
);
assert_eq!(page["csaf_provider"], provider);
@@ -424,7 +498,7 @@ async fn a_supplier_uploads_versions_through_its_invite() {
None,
)
.await;
assert_eq!(all[0]["uploads"].as_array().unwrap().len(), 2);
assert_eq!(all[0]["uploads"].as_array().unwrap().len(), 3);
assert_eq!(all[0]["uploads"][0]["summary"]["components"], 3);
h.pool.drop_tenant(TENANT).await.ok();
@@ -567,3 +641,107 @@ async fn only_a_valid_invite_takes_an_upload() {
h.pool.drop_tenant(TENANT).await.ok();
}
#[tokio::test]
async fn the_supplier_page_checks_a_file_before_it_is_uploaded() {
let Some(h) = start().await else { return };
let target = h.target("Antriebsregler DR-4", true).await;
let (_, invite) = h.invite(TENANT, &target, "sbom@antrieb.example").await;
let id = invite["id"].as_str().unwrap();
let (status, body) = h.check(TENANT, id, sbom(4)).await;
assert_eq!(status, 200, "{body}");
assert_eq!(body["data"]["components"], 4);
let (status, body) = h.check(TENANT, id, b"name,version".to_vec()).await;
assert_eq!(
(status, body["code"].as_str()),
(422, Some("unknown_format"))
);
let count =
h.db.inner()
.collection::<SupplierUpload>(SupplierUpload::COLLECTION)
.count_documents(doc! {})
.await
.unwrap();
assert_eq!(count, 0, "a check records nothing");
// A component whose supplier was removed takes nothing more.
let oid = mongodb::bson::oid::ObjectId::parse_str(&target).unwrap();
h.db.onboarded_targets()
.update_one(doc! { "_id": oid }, doc! { "$unset": { "supplier": "" } })
.await
.unwrap();
assert_eq!(h.check(TENANT, id, sbom(1)).await.0, 404);
assert_eq!(h.supplier_view(TENANT, id).await.0, 404);
let (status, _) = h
.upload(TENANT, id, Some(("x.cdx.json", sbom(1))), None)
.await;
assert_eq!(status, 404);
assert!(h.stored_target(&target).await.artifacts.is_empty());
h.pool.drop_tenant(TENANT).await.ok();
}
/// A registry that answers each tenant's entitlement check as `answers` says.
async fn fake_registry(answers: Value) -> String {
let app = Router::new().route(
"/v1/internal/entitlements/check",
post(move |axum::Json(body): axum::Json<Value>| {
let answer = answers[body["tenant_id"].as_str().unwrap_or_default()].clone();
async move { axum::Json(answer) }
}),
);
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
tokio::spawn(async move { axum::serve(listener, app).await.ok() });
format!("http://{addr}")
}
#[tokio::test]
async fn a_workspace_that_takes_no_changes_takes_no_upload() {
let registry = fake_registry(json!({
"invites": { "allowed": true, "status": "active" },
"no-status": { "allowed": true },
"frozen": { "allowed": true, "status": "frozen" },
"read-only": { "allowed": true, "read_only": true, "status": "active" },
"halted": { "allowed": true, "status": "halted" },
"not-entitled": { "allowed": false, "status": "active" },
}))
.await;
let Some(h) = start_with(Some(registry)).await else {
return;
};
for (tenant, expected) in [
("invites", 201),
("no-status", 201),
("frozen", 403),
("read-only", 403),
("halted", 403),
("not-entitled", 403),
] {
let db = h.pool.for_tenant_id(tenant).await.unwrap();
let mut target = OnboardedTarget::new("DR-4".into(), TargetType::FirmwareRtos);
target.supplier = Some(SupplierComponent {
name: "Test Antriebstechnik".into(),
product: None,
version: None,
csaf_provider: None,
});
let id = db.onboarded_targets().insert_one(&target).await.unwrap();
let target = id.inserted_id.as_object_id().unwrap().to_hex();
let (_, invite) = h.invite(tenant, &target, "sbom@antrieb.example").await;
let (status, body) = h
.upload(
tenant,
invite["id"].as_str().unwrap(),
Some(("x.cdx.json", sbom(1))),
None,
)
.await;
assert_eq!(status, expected, "{tenant}: {body}");
if expected == 403 {
assert_eq!(body["code"], "read_only");
}
h.pool.drop_tenant(tenant).await.ok();
}
}
+7 -2
View File
@@ -149,18 +149,23 @@ form, and it is stored only when you save it as your own statement.
page shows: the component by your name for it, until when the link is
valid, the CSAF provider, and the uploads through this invite. Nothing
else of your workspace is in it.
- `POST …/supplier-invites/{invite}/sboms/check` checks a file the way
the wizard does, before it is uploaded. It stores and records nothing.
- `POST …/supplier-invites/{invite}/sboms` (multipart: `file`, optionally
`csaf_provider`) is the supplier's upload. It is read and refused exactly
as your own upload is. An accepted SBOM becomes the component's SBOM,
replacing the previous one, and starts a scan, which counts like your
own scans. A CSAF provider given with it becomes the component's.
own scans. A CSAF provider given with it becomes the component's only
if the component has none. One you set stays, and the upload shows what
the supplier gave.
Every upload is recorded with its invite, its time, the file name, and
whether it was accepted. A refused one keeps its `code`: `too_large`,
`too_many_components`, `empty`, `unknown_format`, `malformed`, or
`csaf_provider` for one that is not https. The supplier sees its uploads,
and each invite in the list carries them. An expired or withdrawn invite
answers `410` with `expired` or `withdrawn`, and records nothing. A
answers `410` with `expired` or `withdrawn`, and records nothing. So does
an invite for a component whose supplier you removed, with `404`. A
workspace that takes no changes answers `403` (`read_only`). An invite
takes at most 20 uploads a day; more answer `429` (`too_many_uploads`).