feat(supplier): the supplier uploads an SBOM through its invite (#1027)

The second half of the phase 3 API: what the portal's supplier page shows
and the upload through an invite.

- `GET …/supplier-invites/{invite}/supplier-view`: the component by the
  customer's name for it, the link's end, the CSAF provider and the uploads
  through this invite, nothing else of the workspace.
- `POST …/supplier-invites/{invite}/sboms` (multipart `file`, optional
  `csaf_provider`): takes the customer's own upload path, now
  `onboarding::attach_upload`, so it is read and refused the same way, becomes
  the component's SBOM, replacing the one before, and starts a scan. A CSAF
  provider given with it (https only) becomes the component's.
- Every upload is recorded in `supplier_uploads` with its invite, time, file
  name and outcome; a refused one keeps its code. The invite list carries each
  invite's uploads and which one is current.
- An expired or withdrawn invite answers 410 and records nothing; a workspace
  the registry has read-only, halted or archived answers 403; an invite takes
  at most 20 uploads a day (429).
- Deleting a target deletes its uploads with its invites.

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 12:33:13 +01:00
1 parent dc14c77e84
commit de856bd5ba
7 files changed
+954 -37

No files matched your search

+96 -24
View File
@@ -79,12 +79,11 @@ impl SupplierInput {
return Ok(None);
}
let csaf_provider = text(self.csaf_provider);
if let Some(url) = &csaf_provider {
let https = reqwest::Url::parse(url)
.is_ok_and(|u| u.scheme() == "https" && u.host_str().is_some());
if !https {
return Err(StatusCode::UNPROCESSABLE_ENTITY);
}
if csaf_provider
.as_deref()
.is_some_and(|url| !is_https_url(url))
{
return Err(StatusCode::UNPROCESSABLE_ENTITY);
}
Ok(Some(compliance_core::models::SupplierComponent {
name,
@@ -95,10 +94,15 @@ impl SupplierInput {
}
}
/// Whether `url` is an https URL with a host: what a CSAF provider must be.
pub(super) fn is_https_url(url: &str) -> bool {
reqwest::Url::parse(url).is_ok_and(|u| u.scheme() == "https" && u.host_str().is_some())
}
/// Fetch the advisories of tenant `tenant_id`'s supplier providers now, in
/// the background, when `supplier` names one: a provider just set is then
/// matched by the next scan, not only after the nightly refresh.
fn refresh_supplier_csaf(
pub(super) fn refresh_supplier_csaf(
agent: &Arc<ComplianceAgent>,
tenant_id: &str,
supplier: Option<&compliance_core::models::SupplierComponent>,
@@ -699,11 +703,17 @@ pub async fn delete_target(
.embedding_builds()
.delete_many(doc! { "repo_id": &id })
.await;
// Its supplier invites: their links allow nothing once it is gone.
let _ = db
.raw_collection(super::supplier_invites::SupplierInvite::COLLECTION)
.delete_many(doc! { "target_id": &id })
.await;
// Its supplier invites and their uploads: the links allow nothing once
// it is gone.
for collection in [
super::supplier_invites::SupplierInvite::COLLECTION,
super::supplier_invites::SupplierUpload::COLLECTION,
] {
let _ = db
.raw_collection(collection)
.delete_many(doc! { "target_id": &id })
.await;
}
// DAST targets linked to this target, and all their downstream data.
for dast_target_id in ids_of(db.dast_targets(), doc! { "repo_id": &id }).await {
@@ -923,9 +933,47 @@ 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?;
Ok(get_target(Extension(agent), tenant, Path(id)).await?)
}
/// What [`attach_upload`] kept.
#[derive(Debug)]
pub(super) struct AttachedUpload {
/// The new artifact's id.
pub artifact_id: String,
/// What a supplier SBOM holds; `None` for any other kind.
pub summary: Option<SupplierSbomSummary>,
}
/// Keep `upload`, a file already on disk, as an artifact of kind `kind` of
/// `target`: what every upload does once its file has arrived, the customer's
/// and a supplier's through an invite (#1027) alike.
///
/// The file's hash is kept for change detection. A supplier SBOM is read and
/// refused when it cannot be, its summary is kept with it, and it replaces the
/// target's previous one. Any other archive is checked for a format that can
/// be unpacked and for encryption. The file is deleted unless the artifact
/// references it.
///
/// # Errors
///
/// 400 for a kind that is not uploaded as a file, 415 for an archive that
/// cannot be unpacked, the supplier SBOM's refusal ([`SupplierSbomSummary::of`]),
/// 500 when the file or the database fails.
pub(super) async fn attach_upload(
db: &crate::database::Database,
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, filename, &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.
@@ -936,6 +984,7 @@ pub async fn upload_artifact(
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
artifact.content_hash = Some(sha);
artifact.ingested_at = Some(chrono::Utc::now());
let mut summary = None;
if kind == ArtifactKind::SupplierSbom {
let path = upload.path.clone();
let read = tokio::task::spawn_blocking(move || {
@@ -943,9 +992,9 @@ pub async fn upload_artifact(
})
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
artifact
.detected
.extend(SupplierSbomSummary::of(read)?.facts());
let read = SupplierSbomSummary::of(read)?;
artifact.detected.extend(read.facts());
summary = Some(read);
} else if kind != ArtifactKind::FirmwareImage {
match archive_check(upload.path.clone()).await? {
// 7z and rar are never unpacked: say so now, not after a scan.
@@ -971,10 +1020,13 @@ pub async fn upload_artifact(
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
upload.keep();
if kind == ArtifactKind::SupplierSbom {
replace_supplier_sboms(&db, oid, &artifact_id, &stored_target.artifacts).await;
replace_supplier_sboms(db, oid, &artifact_id, &target.artifacts).await;
}
Ok(get_target(Extension(agent), tenant, Path(id)).await?)
Ok(AttachedUpload {
artifact_id,
summary,
})
}
/// Remove the target's supplier SBOMs other than the one just uploaded
@@ -1018,6 +1070,25 @@ pub struct UploadRefusal {
reason: Option<(String, &'static str)>,
}
impl UploadRefusal {
/// A refusal with its reason and code.
pub(super) fn because(
status: StatusCode,
error: impl Into<String>,
code: &'static str,
) -> Self {
Self {
status,
reason: Some((error.into(), code)),
}
}
/// Its code, when it gives one.
pub(super) fn code(&self) -> Option<&'static str> {
self.reason.as_ref().map(|(_, code)| *code)
}
}
impl From<StatusCode> for UploadRefusal {
fn from(status: StatusCode) -> Self {
Self {
@@ -1050,7 +1121,7 @@ pub const SBOM_STATEMENTS_FACT: &str = "sbom_statements";
/// What a readable supplier SBOM holds (#1025): what the wizard shows when the
/// file is added, and what its upload keeps with the artifact.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct SupplierSbomSummary {
/// The format and its version, such as `CycloneDX 1.5` or `SPDX 2.3`.
pub format: String,
@@ -1309,7 +1380,7 @@ pub async fn set_archive_password(
///
/// 413 past `max`, the multipart error's own status for a malformed or
/// over-limit body, 500 if the file cannot be written.
async fn stream_to_disk(
pub(super) async fn stream_to_disk(
field: &mut axum::extract::multipart::Field<'_>,
dest: &std::path::Path,
max: u64,
@@ -1338,14 +1409,15 @@ async fn stream_to_disk(
/// An uploaded file on disk that is deleted when dropped, unless [`Self::keep`]
/// is called once the artifact record references it. This is what stops a
/// rejected, oversized or half-received upload from being left on disk.
struct StoredUpload {
path: std::path::PathBuf,
size: u64,
pub(super) struct StoredUpload {
pub path: std::path::PathBuf,
pub size: u64,
keep: bool,
}
impl StoredUpload {
fn new(path: std::path::PathBuf) -> Self {
/// A file about to be written at `path`, deleted unless it is kept.
pub(super) fn new(path: std::path::PathBuf) -> Self {
Self {
path,
size: 0,
@@ -10,8 +10,16 @@
//! An invite is valid for [`INVITE_LIFETIME_DAYS`] from when it is made, and
//! serves the component's later SBOM versions until it expires or is
//! withdrawn (decided 2026-11-18).
//!
//! An upload through an invite takes the customer's own upload path
//! ([`super::onboarding::attach_upload`]): it becomes the component's SBOM and
//! starts a scan. Every upload, refused ones included, is recorded with the
//! invite it came through ([`SupplierUpload`]), for the customer and the
//! supplier to see.
use axum::extract::{Path, Query, State};
use std::collections::HashMap;
use axum::extract::{Multipart, Path, Query, State};
use axum::http::StatusCode;
use axum::Json;
use chrono::{DateTime, Utc};
@@ -19,8 +27,16 @@ use futures_util::TryStreamExt;
use mongodb::bson::{doc, oid::ObjectId, DateTime as BsonDateTime};
use serde::{Deserialize, Serialize};
use compliance_core::models::{ArtifactKind, OnboardedTarget, ScanTrigger};
use super::onboarding::{
attach_upload, is_https_url, refresh_supplier_csaf, stream_to_disk, StoredUpload,
SupplierSbomSummary, UploadRefusal,
};
use super::platform::PlatformState;
use crate::agent::ComplianceAgent;
use crate::database::Database;
use crate::pipeline::sbom::supplied::MAX_BYTES as MAX_SBOM_BYTES;
/// How long an invite is valid, in days from when it is made.
pub const INVITE_LIFETIME_DAYS: i64 = 90;
@@ -31,6 +47,13 @@ const MAX_EMAIL_LEN: usize = 254;
/// The longest `invited_by` / `withdrawn_by` accepted: a portal user's id.
const MAX_ACTOR_LEN: usize = 200;
/// The most uploads one invite takes in a day, refused ones included: each
/// accepted one starts a scan the customer pays for.
pub const MAX_UPLOADS_PER_DAY: u64 = 20;
/// The longest file name kept with an upload, in characters.
const MAX_FILENAME_CHARS: usize = 200;
/// An invite as stored, in the tenant's [`SupplierInvite::COLLECTION`].
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct SupplierInvite {
@@ -118,12 +141,15 @@ pub struct InviteView {
pub withdrawn_by: Option<String>,
/// Whether it still allows an upload.
pub state: InviteState,
/// What came through it, newest first.
pub uploads: Vec<UploadView>,
}
impl InviteView {
/// The view of `invite` at `now`.
fn of(invite: SupplierInvite, now: DateTime<Utc>) -> Self {
/// The view of `invite` at `now`, with its `uploads`.
fn of(invite: SupplierInvite, now: DateTime<Utc>, uploads: Vec<UploadView>) -> Self {
Self {
uploads,
state: invite.state(now),
id: invite.id.to_hex(),
target_id: invite.target_id,
@@ -137,6 +163,114 @@ impl InviteView {
}
}
/// An upload through an invite, as stored in [`SupplierUpload::COLLECTION`]:
/// accepted or refused, with what the file held.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct SupplierUpload {
/// Its id.
#[serde(rename = "_id")]
pub id: ObjectId,
/// The invite it came through.
pub invite_id: String,
/// The target it was for.
pub target_id: String,
/// When it arrived.
pub uploaded_at: BsonDateTime,
/// The file's name, as the supplier sent it.
pub filename: String,
/// Whether it became the component's SBOM.
pub accepted: bool,
/// Why it was refused: the code of the refusal.
#[serde(default)]
pub code: Option<String>,
/// What an accepted SBOM holds.
#[serde(default)]
pub summary: Option<SupplierSbomSummary>,
/// The artifact an accepted SBOM became.
#[serde(default)]
pub artifact_id: Option<String>,
/// The CSAF provider the supplier gave with it.
#[serde(default)]
pub csaf_provider: Option<String>,
}
impl SupplierUpload {
/// The collection, in the tenant's own database.
pub const COLLECTION: &'static str = "supplier_uploads";
/// A refused upload of `filename` through `invite`, with the refusal's code.
fn refused(invite: &SupplierInvite, filename: &str, code: &str) -> Self {
Self {
id: ObjectId::new(),
invite_id: invite.id.to_hex(),
target_id: invite.target_id.clone(),
uploaded_at: BsonDateTime::now(),
filename: filename.to_string(),
accepted: false,
code: Some(code.to_string()),
summary: None,
artifact_id: None,
csaf_provider: None,
}
}
}
/// An upload as the portal shows it, to the customer and to the supplier.
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct UploadView {
/// Its id.
pub id: String,
/// When it arrived.
pub uploaded_at: DateTime<Utc>,
/// The file's name.
pub filename: String,
/// Whether it became the component's SBOM.
pub accepted: bool,
/// Why it was refused: `too_large`, `too_many_components`, `empty`,
/// `unknown_format`, `malformed` or `csaf_provider`.
pub code: Option<String>,
/// What an accepted SBOM holds.
pub summary: Option<SupplierSbomSummary>,
/// The CSAF provider given with it.
pub csaf_provider: Option<String>,
/// Whether it is the component's SBOM now (a later one replaces it).
pub current: bool,
}
impl UploadView {
/// The view of `upload`; `current` is the target's SBOM artifact now.
fn of(upload: SupplierUpload, current: Option<&str>) -> Self {
Self {
current: upload.artifact_id.is_some() && upload.artifact_id.as_deref() == current,
id: upload.id.to_hex(),
uploaded_at: upload.uploaded_at.to_chrono(),
filename: upload.filename,
accepted: upload.accepted,
code: upload.code,
summary: upload.summary,
csaf_provider: upload.csaf_provider,
}
}
}
/// What the supplier sees of its invite: the component, until when the link
/// is valid, and its uploads. Nothing else of the customer's.
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct SupplierPage {
/// The component, by the customer's name for it.
pub component: String,
/// The supplier's name for the product, if the customer gave it.
pub product: Option<String>,
/// The version in use, if the customer gave it.
pub version: Option<String>,
/// Until when the link is valid.
pub expires_at: DateTime<Utc>,
/// The CSAF provider kept for the component.
pub csaf_provider: Option<String>,
/// Its uploads through this invite, newest first.
pub uploads: Vec<UploadView>,
}
/// The body of an invite: which component, whom, and who invites.
#[derive(Debug, Deserialize)]
pub struct CreateInvite {
@@ -188,6 +322,138 @@ fn invites(db: &Database) -> mongodb::Collection<SupplierInvite> {
db.inner().collection(SupplierInvite::COLLECTION)
}
fn uploads(db: &Database) -> mongodb::Collection<SupplierUpload> {
db.inner().collection(SupplierUpload::COLLECTION)
}
/// The id of `target`'s supplier SBOM now, if it has one.
fn current_sbom(target: &OnboardedTarget) -> Option<&str> {
target
.artifacts
.iter()
.find(|a| a.kind == ArtifactKind::SupplierSbom)
.map(|a| a.id.as_str())
}
/// `listed` as the portal reads them at `now`, each with its uploads.
async fn views(
db: &Database,
listed: Vec<SupplierInvite>,
now: DateTime<Utc>,
) -> Result<Vec<InviteView>, StatusCode> {
let ids: Vec<String> = listed.iter().map(|i| i.id.to_hex()).collect();
let mut by_invite: HashMap<String, Vec<SupplierUpload>> = HashMap::new();
let mut cursor = uploads(db)
.find(doc! { "invite_id": { "$in": &ids } })
.sort(doc! { "uploaded_at": -1, "_id": -1 })
.await
.map_err(internal)?;
while let Some(upload) = cursor.try_next().await.map_err(internal)? {
by_invite
.entry(upload.invite_id.clone())
.or_default()
.push(upload);
}
let target_ids: Vec<ObjectId> = listed
.iter()
.filter_map(|i| ObjectId::parse_str(&i.target_id).ok())
.collect();
let targets: Vec<OnboardedTarget> = db
.onboarded_targets()
.find(doc! { "_id": { "$in": target_ids } })
.await
.map_err(internal)?
.try_collect()
.await
.map_err(internal)?;
let current: HashMap<String, String> = targets
.iter()
.filter_map(|t| Some((t.id?.to_hex(), current_sbom(t)?.to_string())))
.collect();
Ok(listed
.into_iter()
.map(|invite| {
let sbom = current.get(&invite.target_id).map(String::as_str);
let uploads = by_invite
.remove(&invite.id.to_hex())
.unwrap_or_default()
.into_iter()
.map(|u| UploadView::of(u, sbom))
.collect();
InviteView::of(invite, now, uploads)
})
.collect())
}
/// The invite `invite_id` of the tenant behind `db` while it allows uploads.
///
/// # Errors
///
/// 404 when there is no such invite; 410 with the code `expired` or
/// `withdrawn` when it no longer allows anything.
async fn open_invite(db: &Database, invite_id: &str) -> Result<SupplierInvite, UploadRefusal> {
let id = ObjectId::parse_str(invite_id.trim()).map_err(|_| StatusCode::NOT_FOUND)?;
let invite = invites(db)
.find_one(doc! { "_id": id })
.await
.map_err(internal)?
.ok_or(StatusCode::NOT_FOUND)?;
match invite.state(Utc::now()) {
InviteState::Active => Ok(invite),
InviteState::Expired => Err(closed("expired")),
InviteState::Withdrawn => Err(closed("withdrawn")),
}
}
/// 410: the invite allows nothing more.
fn closed(code: &'static str) -> UploadRefusal {
UploadRefusal::because(StatusCode::GONE, "the invite is no longer valid", code)
}
/// Whether the tenant may change its data now: not when the registry has it
/// read-only, halted or archived. Without a registry (dev) it may.
///
/// # Errors
///
/// 403 with the code `read_only` when it may not; 503 when the registry
/// cannot answer (access is never widened on doubt).
async fn accepts_writes(agent: &ComplianceAgent, tenant_id: &str) -> Result<(), UploadRefusal> {
let Some(registry) = agent.registry.as_ref() else {
return Ok(());
};
let check = registry
.check_entitlement(tenant_id, None, None)
.await
.map_err(|e| {
tracing::error!(tenant_id, "entitlement check unavailable: {e}");
StatusCode::SERVICE_UNAVAILABLE
})?;
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());
if writable {
Ok(())
} else {
Err(UploadRefusal::because(
StatusCode::FORBIDDEN,
"the workspace takes no uploads now",
"read_only",
))
}
}
/// The name an upload is shown by: the last part of `name`, at most
/// [`MAX_FILENAME_CHARS`] long.
fn shown_filename(name: &str) -> String {
let base = name.rsplit(['/', '\\']).next().unwrap_or(name).trim();
let base = if base.is_empty() { "sbom" } else { base };
base.chars().take(MAX_FILENAME_CHARS).collect()
}
fn internal<E: std::fmt::Display>(e: E) -> StatusCode {
tracing::error!("supplier invite endpoint failed: {e}");
StatusCode::INTERNAL_SERVER_ERROR
@@ -233,7 +499,10 @@ pub async fn create_invite(
.await
.map_err(internal)?;
invites(&db).insert_one(&invite).await.map_err(internal)?;
Ok((StatusCode::CREATED, Json(InviteView::of(invite, now))))
Ok((
StatusCode::CREATED,
Json(InviteView::of(invite, now, Vec::new())),
))
}
/// `GET /api/v1/platform/tenants/{id}/supplier-invites[?target=<id>]`: the
@@ -261,9 +530,7 @@ pub async fn list_invites(
.try_collect()
.await
.map_err(internal)?;
Ok(Json(
listed.into_iter().map(|i| InviteView::of(i, now)).collect(),
))
Ok(Json(views(&db, listed, now).await?))
}
/// `POST /api/v1/platform/tenants/{id}/supplier-invites/{invite}/withdraw`:
@@ -299,7 +566,236 @@ pub async fn withdraw_invite(
.await
.map_err(internal)?
.ok_or(StatusCode::NOT_FOUND)?;
Ok(Json(InviteView::of(invite, now)))
let mut viewed = views(&db, vec![invite], now).await?;
viewed
.pop()
.map(Json)
.ok_or(StatusCode::INTERNAL_SERVER_ERROR)
}
/// `GET /api/v1/platform/tenants/{id}/supplier-invites/{invite}/supplier-view`:
/// what the supplier's upload page shows, while the invite is valid.
///
/// # Errors
///
/// 404 when there is no such invite, or its component is gone; 410 with the
/// code `expired` or `withdrawn`.
pub async fn supplier_view(
State(st): State<PlatformState>,
Path((tenant_id, invite_id)): Path<(String, String)>,
) -> Result<Json<SupplierPage>, UploadRefusal> {
let db = st.agent.db_pool.for_existing_tenant_id(&tenant_id);
let invite = open_invite(&db, &invite_id).await?;
let target = invite_target(&db, &invite).await?;
let sbom = current_sbom(&target).map(str::to_string);
let listed: Vec<UploadView> = uploads(&db)
.find(doc! { "invite_id": invite.id.to_hex() })
.sort(doc! { "uploaded_at": -1, "_id": -1 })
.await
.map_err(internal)?
.try_collect::<Vec<SupplierUpload>>()
.await
.map_err(internal)?
.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))
.unwrap_or_default();
Ok(Json(SupplierPage {
component: target.name,
product,
version,
expires_at: invite.expires_at.to_chrono(),
csaf_provider,
uploads: listed,
}))
}
/// The component `invite` is for.
///
/// # Errors
///
/// 404 when it is gone.
async fn invite_target(
db: &Database,
invite: &SupplierInvite,
) -> Result<OnboardedTarget, UploadRefusal> {
let id = ObjectId::parse_str(&invite.target_id).map_err(|_| StatusCode::NOT_FOUND)?;
Ok(db
.onboarded_targets()
.find_one(doc! { "_id": id })
.await
.map_err(internal)?
.ok_or(StatusCode::NOT_FOUND)?)
}
/// `POST /api/v1/platform/tenants/{id}/supplier-invites/{invite}/sboms`: the
/// supplier uploads an SBOM through its invite.
///
/// Multipart fields: `file` (exactly one) and, optionally, `csaf_provider`
/// (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).
///
/// # Errors
///
/// - 404: no such invite, or its component is gone.
/// - 410 (`expired`, `withdrawn`): the invite allows nothing more.
/// - 403 (`read_only`): the workspace takes no uploads now; 503 when the
/// registry cannot say.
/// - 429 (`too_many_uploads`): [`MAX_UPLOADS_PER_DAY`] reached.
/// - 400: no file, or more than one.
/// - 413 (`too_large`) and 422 (`too_many_components`, `empty`,
/// `unknown_format`, `malformed`, `csaf_provider`): refused, and recorded.
pub async fn upload_through_invite(
State(st): State<PlatformState>,
Path((tenant_id, invite_id)): Path<(String, String)>,
mut multipart: Multipart,
) -> Result<(StatusCode, Json<UploadView>), UploadRefusal> {
// Nothing is created before the invite is known to be valid.
let lookup = st.agent.db_pool.for_existing_tenant_id(&tenant_id);
let invite = open_invite(&lookup, &invite_id).await?;
accepts_writes(&st.agent, &tenant_id).await?;
let day_ago = BsonDateTime::from(Utc::now() - chrono::Duration::days(1));
let recent = uploads(&lookup)
.count_documents(
doc! { "invite_id": invite.id.to_hex(), "uploaded_at": { "$gte": day_ago } },
)
.await
.map_err(internal)?;
if recent >= MAX_UPLOADS_PER_DAY {
return Err(UploadRefusal::because(
StatusCode::TOO_MANY_REQUESTS,
"too many uploads through this invite today",
"too_many_uploads",
));
}
let target = invite_target(&lookup, &invite).await?;
let db = st
.agent
.db_pool
.for_tenant_id(&tenant_id)
.await
.map_err(internal)?;
let mut csaf_provider = None;
let mut filename = String::from("sbom");
let mut stored: Option<StoredUpload> = None;
while let Some(mut field) = multipart.next_field().await.map_err(|e| e.status())? {
match field.name().unwrap_or("") {
"csaf_provider" => {
let url = field.text().await.map_err(|e| e.status())?;
csaf_provider = Some(url.trim().to_string()).filter(|u| !u.is_empty());
}
"file" => {
if stored.is_some() {
return Err(StatusCode::BAD_REQUEST.into());
}
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);
match stream_to_disk(&mut field, &upload.path, MAX_SBOM_BYTES).await {
Ok(size) => upload.size = size,
Err(StatusCode::PAYLOAD_TOO_LARGE) => {
let refusal = UploadRefusal::because(
StatusCode::PAYLOAD_TOO_LARGE,
"the SBOM is larger than 20 MiB",
"too_large",
);
return Err(refused(&db, &invite, &filename, refusal).await);
}
Err(status) => return Err(status.into()),
}
stored = Some(upload);
}
_ => {}
}
}
let upload = stored.ok_or(StatusCode::BAD_REQUEST)?;
if csaf_provider
.as_deref()
.is_some_and(|url| !is_https_url(url))
{
let refusal = UploadRefusal::because(
StatusCode::UNPROCESSABLE_ENTITY,
"the CSAF provider must be an https URL",
"csaf_provider",
);
return Err(refused(&db, &invite, &filename, refusal).await);
}
let attached = match attach_upload(
&db,
&target,
ArtifactKind::SupplierSbom,
None,
&filename,
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()) {
supplier.csaf_provider = Some(url.clone());
let set = mongodb::bson::to_bson(&supplier).map_err(internal)?;
db.onboarded_targets()
.update_one(
doc! { "_id": target.id },
doc! { "$set": { "supplier": set } },
)
.await
.map_err(internal)?;
refresh_supplier_csaf(&st.agent, &tenant_id, Some(&supplier));
}
let record = SupplierUpload {
id: ObjectId::new(),
invite_id: invite.id.to_hex(),
target_id: invite.target_id.clone(),
uploaded_at: BsonDateTime::now(),
filename,
accepted: true,
code: None,
summary: attached.summary,
artifact_id: Some(attached.artifact_id.clone()),
csaf_provider,
};
uploads(&db).insert_one(&record).await.map_err(internal)?;
let (agent, target_id) = (st.agent.clone(), invite.target_id.clone());
tokio::spawn(async move {
if let Err(e) = agent
.run_target_scan(&tenant_id, &target_id, ScanTrigger::NewContent)
.await
{
tracing::error!(target_id, "scan after a supplier upload failed: {e}");
}
});
let current = Some(attached.artifact_id.as_str());
Ok((StatusCode::CREATED, Json(UploadView::of(record, current))))
}
/// 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.
async fn refused(
db: &Database,
invite: &SupplierInvite,
filename: &str,
refusal: UploadRefusal,
) -> UploadRefusal {
if let Some(code) = refusal.code() {
let record = SupplierUpload::refused(invite, filename, code);
if let Err(e) = uploads(db).insert_one(&record).await {
tracing::warn!(invite_id = %invite.id, "refused supplier upload not recorded: {e}");
}
}
refusal
}
#[cfg(test)]
@@ -361,6 +857,15 @@ mod tests {
assert_eq!(normalized_email(&long), None);
}
#[test]
fn an_upload_is_shown_by_its_file_name_only() {
assert_eq!(shown_filename("../../dr4.cdx.json"), "dr4.cdx.json");
assert_eq!(shown_filename("C:\\sbom\\dr4.json"), "dr4.json");
assert_eq!(shown_filename(" "), "sbom");
assert_eq!(shown_filename("dir/"), "sbom");
assert_eq!(shown_filename(&"ä".repeat(300)).chars().count(), 200);
}
#[test]
fn an_actor_is_required_and_bounded() {
assert_eq!(normalized_actor(" u-1 "), Some("u-1".into()));
+1 -1
View File
@@ -10,7 +10,7 @@ use crate::api::{handlers, openapi};
/// Allowance on top of the file itself for the multipart framing: boundaries,
/// part headers and the small `kind` / `plc_format` text fields.
const MULTIPART_OVERHEAD: usize = 1024 * 1024;
pub(crate) const MULTIPART_OVERHEAD: usize = 1024 * 1024;
/// The customer API, with its OpenAPI description at [`openapi::SPEC_PATH`]
/// (#1006).
+10
View File
@@ -376,6 +376,16 @@ pub async fn start_api_server(
"/api/v1/platform/tenants/{id}/supplier-invites/{invite}/withdraw",
post(supplier_invites::withdraw_invite),
)
.route(
"/api/v1/platform/tenants/{id}/supplier-invites/{invite}/supplier-view",
get(supplier_invites::supplier_view),
)
.route(
"/api/v1/platform/tenants/{id}/supplier-invites/{invite}/sboms",
post(supplier_invites::upload_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,
@@ -205,7 +205,8 @@ async fn delete_repo_cascades_sast_findings_and_sbom() {
.await
.unwrap();
// Supplier invites (#1027): the target's go, another target's stay.
// Supplier invites and their uploads (#1027): the target's go, another
// target's stay.
for target in [repo_id.as_str(), "another-target"] {
db.collection::<mongodb::bson::Document>("supplier_invites")
.insert_one(mongodb::bson::doc! {
@@ -217,6 +218,16 @@ async fn delete_repo_cascades_sast_findings_and_sbom() {
})
.await
.unwrap();
db.collection::<mongodb::bson::Document>("supplier_uploads")
.insert_one(mongodb::bson::doc! {
"invite_id": "invite-1",
"target_id": target,
"uploaded_at": now,
"filename": "sbom.cdx.json",
"accepted": true,
})
.await
.unwrap();
}
assert_eq!(count_docs(&server, "findings").await, 1);
@@ -229,6 +240,7 @@ async fn delete_repo_cascades_sast_findings_and_sbom() {
assert_eq!(count_docs(&server, "findings").await, 0);
assert_eq!(count_docs(&server, "sbom_entries").await, 0);
assert_eq!(count_docs(&server, "supplier_invites").await, 1);
assert_eq!(count_docs(&server, "supplier_uploads").await, 1);
server.cleanup().await;
}
+303 -3
View File
@@ -1,6 +1,7 @@
//! Supplier invites (#1027) against a live Mongo: the portal invites a
//! supplier for a supplier component only, lists the tenant's invites with
//! their state, and withdraws one once. Skips cleanly when no Mongo is
//! their state, and withdraws one once. The supplier uploads through a valid
//! invite only, and every upload is recorded. Skips cleanly when no Mongo is
//! reachable.
#![allow(clippy::expect_used, clippy::unwrap_used)]
@@ -16,9 +17,9 @@ use serde_json::{json, Value};
use compliance_agent::agent::ComplianceAgent;
use compliance_agent::api::handlers::platform::{self, PlatformState};
use compliance_agent::api::handlers::supplier_invites::{self, SupplierInvite};
use compliance_agent::api::handlers::supplier_invites::{self, SupplierInvite, SupplierUpload};
use compliance_agent::database::{Database, DatabasePool};
use compliance_core::models::{OnboardedTarget, SupplierComponent, TargetType};
use compliance_core::models::{ArtifactKind, OnboardedTarget, SupplierComponent, TargetType};
use common::dev_config;
@@ -56,6 +57,14 @@ async fn start() -> Option<Harness> {
"/api/v1/platform/tenants/{id}/supplier-invites/{invite}/withdraw",
post(supplier_invites::withdraw_invite),
)
.route(
"/api/v1/platform/tenants/{id}/supplier-invites/{invite}/supplier-view",
get(supplier_invites::supplier_view),
)
.route(
"/api/v1/platform/tenants/{id}/supplier-invites/{invite}/sboms",
post(supplier_invites::upload_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();
@@ -70,6 +79,20 @@ async fn start() -> Option<Harness> {
})
}
/// A CycloneDX SBOM listing `components` npm packages.
fn sbom(components: usize) -> Vec<u8> {
let listed: Vec<Value> = (0..components)
.map(|i| {
json!({ "type": "library", "name": format!("pkg{i}"), "version": "1.0.0",
"purl": format!("pkg:npm/pkg{i}@1.0.0") })
})
.collect();
serde_json::to_vec(
&json!({ "bomFormat": "CycloneDX", "specVersion": "1.5", "components": listed }),
)
.unwrap()
}
impl Harness {
async fn target(&self, name: &str, supplier: bool) -> String {
let mut target = OnboardedTarget::new(name.into(), TargetType::FirmwareRtos);
@@ -102,6 +125,56 @@ impl Harness {
(status, resp.json().await.unwrap_or_default())
}
async fn upload(
&self,
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 {
form = form.text("csaf_provider", url.to_string());
}
if let Some((name, bytes)) = file {
form = form.part(
"file",
reqwest::multipart::Part::bytes(bytes).file_name(name.to_string()),
);
}
let resp = self
.client
.post(format!(
"{}/api/v1/platform/tenants/{tenant}/supplier-invites/{invite}/sboms",
self.base_url
))
.multipart(form)
.send()
.await
.unwrap();
let status = resp.status().as_u16();
(status, resp.json().await.unwrap_or_default())
}
async fn supplier_view(&self, tenant: &str, invite: &str) -> (u16, Value) {
self.call(
reqwest::Method::GET,
&format!("{tenant}/supplier-invites/{invite}/supplier-view"),
None,
)
.await
}
async fn stored_target(&self, id: &str) -> OnboardedTarget {
let oid = mongodb::bson::oid::ObjectId::parse_str(id).unwrap();
self.db
.onboarded_targets()
.find_one(doc! { "_id": oid })
.await
.unwrap()
.unwrap()
}
async fn invite(&self, tenant: &str, target: &str, email: &str) -> (u16, Value) {
let body = json!({ "target_id": target, "email": email, "invited_by": "user-1" });
self.call(
@@ -267,3 +340,230 @@ async fn invites_are_listed_with_their_state_and_withdrawn_once() {
h.pool.drop_tenant(TENANT).await.ok();
}
#[tokio::test]
async fn a_supplier_uploads_versions_through_its_invite() {
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, page) = h.supplier_view(TENANT, id).await;
assert_eq!(status, 200, "{page}");
assert_eq!(page["component"], "Antriebsregler DR-4");
assert_eq!(page["product"], "DR-4");
assert_eq!(page["expires_at"], invite["expires_at"]);
assert_eq!(page["uploads"], json!([]));
assert!(page.get("email").is_none() && page.get("target_id").is_none());
let provider = "https://antrieb.example/.well-known/csaf/provider-metadata.json";
let (status, first) = h
.upload(
TENANT,
id,
Some(("dr4-1.0.cdx.json", sbom(2))),
Some(provider),
)
.await;
assert_eq!(status, 201, "{first}");
assert_eq!(first["accepted"], true);
assert_eq!(first["current"], true);
assert_eq!(first["filename"], "dr4-1.0.cdx.json");
assert_eq!(first["summary"]["components"], 2);
let stored = h.stored_target(&target).await;
let sboms: Vec<_> = stored
.artifacts
.iter()
.filter(|a| a.kind == ArtifactKind::SupplierSbom)
.collect();
assert_eq!(sboms.len(), 1, "the upload is the component's SBOM");
assert!(sboms[0].ingested_at.is_some());
assert_eq!(
stored.supplier.unwrap().csaf_provider.as_deref(),
Some(provider),
"the supplier's CSAF provider becomes the component's"
);
// A path in the name is not kept; the next version replaces the first.
let (status, second) = h
.upload(TENANT, id, Some(("../../dr4-1.1.cdx.json", sbom(3))), None)
.await;
assert_eq!(status, 201, "{second}");
assert_eq!(second["filename"], "dr4-1.1.cdx.json");
let stored = h.stored_target(&target).await;
let sboms: Vec<_> = stored
.artifacts
.iter()
.filter(|a| a.kind == ArtifactKind::SupplierSbom)
.collect();
assert_eq!(sboms.len(), 1, "a new version replaces the one before");
let (_, page) = h.supplier_view(TENANT, id).await;
let shown: Vec<(&str, bool)> = page["uploads"]
.as_array()
.unwrap()
.iter()
.map(|u| {
(
u["filename"].as_str().unwrap(),
u["current"].as_bool().unwrap(),
)
})
.collect();
assert_eq!(
shown,
[("dr4-1.1.cdx.json", true), ("dr4-1.0.cdx.json", false)]
);
assert_eq!(page["csaf_provider"], provider);
// The customer sees the same uploads with the invite.
let (_, all) = h
.call(
reqwest::Method::GET,
&format!("{TENANT}/supplier-invites"),
None,
)
.await;
assert_eq!(all[0]["uploads"].as_array().unwrap().len(), 2);
assert_eq!(all[0]["uploads"][0]["summary"]["components"], 3);
h.pool.drop_tenant(TENANT).await.ok();
}
#[tokio::test]
async fn a_refused_upload_is_recorded_with_its_code() {
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
.upload(
TENANT,
id,
Some(("dr4.csv", b"name,version".to_vec())),
None,
)
.await;
assert_eq!(
(status, body["code"].as_str()),
(422, Some("unknown_format"))
);
let (status, body) = h
.upload(
TENANT,
id,
Some(("dr4.cdx.json", sbom(1))),
Some("http://antrieb.example/provider-metadata.json"),
)
.await;
assert_eq!(
(status, body["code"].as_str()),
(422, Some("csaf_provider"))
);
// No file is the portal's mistake, not the supplier's: not recorded.
assert_eq!(h.upload(TENANT, id, None, None).await.0, 400);
let (_, page) = h.supplier_view(TENANT, id).await;
let codes: Vec<(&str, &str)> = page["uploads"]
.as_array()
.unwrap()
.iter()
.map(|u| {
assert_eq!(u["accepted"], false);
(u["filename"].as_str().unwrap(), u["code"].as_str().unwrap())
})
.collect();
assert_eq!(
codes,
[
("dr4.cdx.json", "csaf_provider"),
("dr4.csv", "unknown_format")
]
);
let stored = h.stored_target(&target).await;
assert!(stored.artifacts.is_empty(), "nothing refused is kept");
assert_eq!(stored.supplier.unwrap().csaf_provider, None);
h.pool.drop_tenant(TENANT).await.ok();
}
#[tokio::test]
async fn only_a_valid_invite_takes_an_upload() {
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().to_string();
let file = || Some(("dr4.cdx.json", sbom(1)));
// Another tenant, an unknown invite.
assert_eq!(h.upload(OTHER, &id, file(), None).await.0, 404);
assert_eq!(h.supplier_view(OTHER, &id).await.0, 404);
let unknown = mongodb::bson::oid::ObjectId::new().to_hex();
assert_eq!(h.upload(TENANT, &unknown, file(), None).await.0, 404);
// The day's uploads are capped.
let invites =
h.db.inner()
.collection::<SupplierInvite>(SupplierInvite::COLLECTION);
let stored = invites.find_one(doc! {}).await.unwrap().unwrap();
let records: Vec<SupplierUpload> = (0..supplier_invites::MAX_UPLOADS_PER_DAY)
.map(|_| SupplierUpload {
id: mongodb::bson::oid::ObjectId::new(),
invite_id: id.clone(),
target_id: target.clone(),
uploaded_at: mongodb::bson::DateTime::now(),
filename: "x".into(),
accepted: false,
code: Some("empty".into()),
summary: None,
artifact_id: None,
csaf_provider: None,
})
.collect();
let uploads =
h.db.inner()
.collection::<SupplierUpload>(SupplierUpload::COLLECTION);
uploads.insert_many(&records).await.unwrap();
let (status, body) = h.upload(TENANT, &id, file(), None).await;
assert_eq!(
(status, body["code"].as_str()),
(429, Some("too_many_uploads"))
);
uploads.delete_many(doc! {}).await.unwrap();
// Withdrawn, then one past its 90 days.
h.call(
reqwest::Method::POST,
&format!("{TENANT}/supplier-invites/{id}/withdraw"),
Some(json!({ "withdrawn_by": "user-1" })),
)
.await;
let (status, body) = h.upload(TENANT, &id, file(), None).await;
assert_eq!((status, body["code"].as_str()), (410, Some("withdrawn")));
let (status, body) = h.supplier_view(TENANT, &id).await;
assert_eq!((status, body["code"].as_str()), (410, Some("withdrawn")));
assert!(
body.get("component").is_none(),
"a closed invite shows nothing"
);
let old = SupplierInvite::new(
stored.target_id.clone(),
"old@antrieb.example".into(),
"user-2".into(),
chrono::Utc::now() - chrono::Duration::days(91),
);
invites.insert_one(&old).await.unwrap();
let (status, body) = h.upload(TENANT, &old.id.to_hex(), file(), None).await;
assert_eq!((status, body["code"].as_str()), (410, Some("expired")));
assert!(h.stored_target(&target).await.artifacts.is_empty());
assert_eq!(
uploads.count_documents(doc! {}).await.unwrap(),
0,
"closed: nothing recorded"
);
h.pool.drop_tenant(TENANT).await.ok();
}
+18
View File
@@ -145,6 +145,24 @@ form, and it is stored only when you save it as your own statement.
`withdrawn`.
- `POST …/supplier-invites/{invite}/withdraw` with `{"withdrawn_by"}`
withdraws an invite. A second withdrawal keeps the first.
- `GET …/supplier-invites/{invite}/supplier-view` is what the supplier's
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` (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.
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
workspace that takes no changes answers `403` (`read_only`). An invite
takes at most 20 uploads a day; more answer `429` (`too_many_uploads`).
`GET /api/v1/platform/tenants/{id}/targets` names each supplier
component's `supplier`: these are the targets a supplier can be invited