feat(supplier): the portal invites a supplier for one component (#1027) #1047
No files matched your search
@@ -33,6 +33,7 @@ pub mod sbom_ecosystems;
|
||||
pub mod scan_changes;
|
||||
pub mod scans;
|
||||
pub mod supplier;
|
||||
pub mod supplier_invites;
|
||||
pub mod support;
|
||||
pub mod target_input;
|
||||
pub mod vex;
|
||||
|
||||
@@ -699,6 +699,11 @@ 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;
|
||||
|
||||
// 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 {
|
||||
|
||||
@@ -462,6 +462,10 @@ pub struct PlatformTarget {
|
||||
pub open_vulnerabilities: u64,
|
||||
/// Its projects that the registry still lists.
|
||||
pub project_ids: Vec<String>,
|
||||
/// Who supplies it, for a component bought in (#1025): the targets a
|
||||
/// supplier can be invited for (#1027). Left out for the tenant's own.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub supplier: Option<compliance_core::models::SupplierComponent>,
|
||||
}
|
||||
|
||||
/// Open findings of each target in `target_ids`, in one query.
|
||||
@@ -582,6 +586,7 @@ pub async fn list_targets(
|
||||
},
|
||||
name: t.name,
|
||||
target_type: t.target_type,
|
||||
supplier: t.supplier,
|
||||
id,
|
||||
}
|
||||
})
|
||||
|
||||
@@ -0,0 +1,379 @@
|
||||
//! Supplier invites (#1027): the customer invites a supplier, through the
|
||||
//! portal, to upload the SBOM of one bought-in component.
|
||||
//!
|
||||
//! The portal owns the secret link and the mail; Prüfwerk keeps the invite in
|
||||
//! the tenant's own database (so the tenant export and erasure cover it, the
|
||||
//! supplier's address included) and refuses what an expired or withdrawn
|
||||
//! invite would allow. The portal calls these endpoints with its platform
|
||||
//! service token ([`super::platform::require_platform_token`]).
|
||||
//!
|
||||
//! 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).
|
||||
|
||||
use axum::extract::{Path, Query, State};
|
||||
use axum::http::StatusCode;
|
||||
use axum::Json;
|
||||
use chrono::{DateTime, Utc};
|
||||
use futures_util::TryStreamExt;
|
||||
use mongodb::bson::{doc, oid::ObjectId, DateTime as BsonDateTime};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use super::platform::PlatformState;
|
||||
use crate::database::Database;
|
||||
|
||||
/// How long an invite is valid, in days from when it is made.
|
||||
pub const INVITE_LIFETIME_DAYS: i64 = 90;
|
||||
|
||||
/// The longest e-mail address accepted (RFC 5321's path limit).
|
||||
const MAX_EMAIL_LEN: usize = 254;
|
||||
|
||||
/// The longest `invited_by` / `withdrawn_by` accepted: a portal user's id.
|
||||
const MAX_ACTOR_LEN: usize = 200;
|
||||
|
||||
/// An invite as stored, in the tenant's [`SupplierInvite::COLLECTION`].
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||
pub struct SupplierInvite {
|
||||
/// Its id, which the portal keys its secret link by.
|
||||
#[serde(rename = "_id")]
|
||||
pub id: ObjectId,
|
||||
/// The target (a supplier component) the invite is for.
|
||||
pub target_id: String,
|
||||
/// Who was invited: the supplier's e-mail address, lower case.
|
||||
pub email: String,
|
||||
/// The portal user who sent it.
|
||||
pub invited_by: String,
|
||||
/// When it was made.
|
||||
pub created_at: BsonDateTime,
|
||||
/// When it stops being valid.
|
||||
pub expires_at: BsonDateTime,
|
||||
/// When it was withdrawn; `None` while it is not.
|
||||
#[serde(default)]
|
||||
pub withdrawn_at: Option<BsonDateTime>,
|
||||
/// The portal user who withdrew it.
|
||||
#[serde(default)]
|
||||
pub withdrawn_by: Option<String>,
|
||||
}
|
||||
|
||||
/// Whether an invite still allows an upload.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum InviteState {
|
||||
/// Uploads are accepted.
|
||||
Active,
|
||||
/// Past `expires_at`.
|
||||
Expired,
|
||||
/// Withdrawn by the customer (this wins over expiry).
|
||||
Withdrawn,
|
||||
}
|
||||
|
||||
impl SupplierInvite {
|
||||
/// The collection, in the tenant's own database.
|
||||
pub const COLLECTION: &'static str = "supplier_invites";
|
||||
|
||||
/// A new invite for `target_id`, made at `now`.
|
||||
pub fn new(target_id: String, email: String, invited_by: String, now: DateTime<Utc>) -> Self {
|
||||
Self {
|
||||
id: ObjectId::new(),
|
||||
target_id,
|
||||
email,
|
||||
invited_by,
|
||||
created_at: now.into(),
|
||||
expires_at: (now + chrono::Duration::days(INVITE_LIFETIME_DAYS)).into(),
|
||||
withdrawn_at: None,
|
||||
withdrawn_by: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Its state at `now`.
|
||||
pub fn state(&self, now: DateTime<Utc>) -> InviteState {
|
||||
if self.withdrawn_at.is_some() {
|
||||
InviteState::Withdrawn
|
||||
} else if now >= self.expires_at.to_chrono() {
|
||||
InviteState::Expired
|
||||
} else {
|
||||
InviteState::Active
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// An invite as the portal reads it.
|
||||
#[derive(Debug, Clone, PartialEq, Serialize)]
|
||||
pub struct InviteView {
|
||||
/// The invite's id.
|
||||
pub id: String,
|
||||
/// The target it is for.
|
||||
pub target_id: String,
|
||||
/// The supplier's e-mail address.
|
||||
pub email: String,
|
||||
/// The portal user who sent it.
|
||||
pub invited_by: String,
|
||||
/// When it was made.
|
||||
pub created_at: DateTime<Utc>,
|
||||
/// When it stops being valid.
|
||||
pub expires_at: DateTime<Utc>,
|
||||
/// When it was withdrawn, if it was.
|
||||
pub withdrawn_at: Option<DateTime<Utc>>,
|
||||
/// Who withdrew it, if anyone did.
|
||||
pub withdrawn_by: Option<String>,
|
||||
/// Whether it still allows an upload.
|
||||
pub state: InviteState,
|
||||
}
|
||||
|
||||
impl InviteView {
|
||||
/// The view of `invite` at `now`.
|
||||
fn of(invite: SupplierInvite, now: DateTime<Utc>) -> Self {
|
||||
Self {
|
||||
state: invite.state(now),
|
||||
id: invite.id.to_hex(),
|
||||
target_id: invite.target_id,
|
||||
email: invite.email,
|
||||
invited_by: invite.invited_by,
|
||||
created_at: invite.created_at.to_chrono(),
|
||||
expires_at: invite.expires_at.to_chrono(),
|
||||
withdrawn_at: invite.withdrawn_at.map(BsonDateTime::to_chrono),
|
||||
withdrawn_by: invite.withdrawn_by,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The body of an invite: which component, whom, and who invites.
|
||||
#[derive(Debug, Deserialize)]
|
||||
pub struct CreateInvite {
|
||||
/// The supplier component's target id.
|
||||
pub target_id: String,
|
||||
/// The supplier's e-mail address.
|
||||
pub email: String,
|
||||
/// The portal user who invites.
|
||||
pub invited_by: String,
|
||||
}
|
||||
|
||||
/// The body of a withdrawal.
|
||||
#[derive(Debug, Deserialize)]
|
||||
pub struct WithdrawInvite {
|
||||
/// The portal user who withdraws it.
|
||||
pub withdrawn_by: String,
|
||||
}
|
||||
|
||||
/// The query of the invite list: one target's, or all of them.
|
||||
#[derive(Debug, Default, Deserialize)]
|
||||
pub struct InviteFilter {
|
||||
/// Only this target's invites.
|
||||
#[serde(default)]
|
||||
pub target: Option<String>,
|
||||
}
|
||||
|
||||
/// `email` trimmed and in lower case, or `None` when it is not an address
|
||||
/// with one `@` between a non-empty local part and a domain holding a dot.
|
||||
fn normalized_email(email: &str) -> Option<String> {
|
||||
let email = email.trim().to_lowercase();
|
||||
let (local, domain) = email.split_once('@')?;
|
||||
let plausible = !local.is_empty()
|
||||
&& domain.contains('.')
|
||||
&& !domain.starts_with('.')
|
||||
&& !domain.ends_with('.')
|
||||
&& !domain.contains('@')
|
||||
&& email.len() <= MAX_EMAIL_LEN
|
||||
&& !email.chars().any(|c| c.is_whitespace() || c.is_control());
|
||||
plausible.then_some(email)
|
||||
}
|
||||
|
||||
/// `actor` trimmed, or `None` when it is empty or too long.
|
||||
fn normalized_actor(actor: &str) -> Option<String> {
|
||||
let actor = actor.trim();
|
||||
(!actor.is_empty() && actor.len() <= MAX_ACTOR_LEN).then(|| actor.to_string())
|
||||
}
|
||||
|
||||
fn invites(db: &Database) -> mongodb::Collection<SupplierInvite> {
|
||||
db.inner().collection(SupplierInvite::COLLECTION)
|
||||
}
|
||||
|
||||
fn internal<E: std::fmt::Display>(e: E) -> StatusCode {
|
||||
tracing::error!("supplier invite endpoint failed: {e}");
|
||||
StatusCode::INTERNAL_SERVER_ERROR
|
||||
}
|
||||
|
||||
/// `POST /api/v1/platform/tenants/{id}/supplier-invites`: invite a supplier
|
||||
/// to upload the SBOM of one supplier component. Answers 201 with the
|
||||
/// invite, whose `id` the portal keys its secret link by.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// 404 when the tenant has no such target; 422 when the target is not a
|
||||
/// supplier component, or the address or the inviting user is not usable.
|
||||
pub async fn create_invite(
|
||||
State(st): State<PlatformState>,
|
||||
Path(tenant_id): Path<String>,
|
||||
Json(body): Json<CreateInvite>,
|
||||
) -> Result<(StatusCode, Json<InviteView>), StatusCode> {
|
||||
let target = ObjectId::parse_str(body.target_id.trim()).map_err(|_| StatusCode::NOT_FOUND)?;
|
||||
// Looked up without creating anything: an unknown tenant just has no target.
|
||||
let lookup = st.agent.db_pool.for_existing_tenant_id(&tenant_id);
|
||||
let stored = lookup
|
||||
.onboarded_targets()
|
||||
.find_one(doc! { "_id": target })
|
||||
.await
|
||||
.map_err(internal)?
|
||||
.ok_or(StatusCode::NOT_FOUND)?;
|
||||
if stored.supplier.is_none() {
|
||||
return Err(StatusCode::UNPROCESSABLE_ENTITY);
|
||||
}
|
||||
let (Some(email), Some(invited_by)) = (
|
||||
normalized_email(&body.email),
|
||||
normalized_actor(&body.invited_by),
|
||||
) else {
|
||||
return Err(StatusCode::UNPROCESSABLE_ENTITY);
|
||||
};
|
||||
let now = Utc::now();
|
||||
let invite = SupplierInvite::new(target.to_hex(), email, invited_by, now);
|
||||
let db = st
|
||||
.agent
|
||||
.db_pool
|
||||
.for_tenant_id(&tenant_id)
|
||||
.await
|
||||
.map_err(internal)?;
|
||||
invites(&db).insert_one(&invite).await.map_err(internal)?;
|
||||
Ok((StatusCode::CREATED, Json(InviteView::of(invite, now))))
|
||||
}
|
||||
|
||||
/// `GET /api/v1/platform/tenants/{id}/supplier-invites[?target=<id>]`: the
|
||||
/// tenant's invites, newest first, each with its state.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// 500 when the database cannot be read.
|
||||
pub async fn list_invites(
|
||||
State(st): State<PlatformState>,
|
||||
Path(tenant_id): Path<String>,
|
||||
Query(filter): Query<InviteFilter>,
|
||||
) -> Result<Json<Vec<InviteView>>, StatusCode> {
|
||||
let db = st.agent.db_pool.for_existing_tenant_id(&tenant_id);
|
||||
let query = match filter.target.as_deref().map(str::trim) {
|
||||
Some(target) if !target.is_empty() => doc! { "target_id": target },
|
||||
_ => doc! {},
|
||||
};
|
||||
let now = Utc::now();
|
||||
let listed: Vec<SupplierInvite> = invites(&db)
|
||||
.find(query)
|
||||
.sort(doc! { "created_at": -1, "_id": -1 })
|
||||
.await
|
||||
.map_err(internal)?
|
||||
.try_collect()
|
||||
.await
|
||||
.map_err(internal)?;
|
||||
Ok(Json(
|
||||
listed.into_iter().map(|i| InviteView::of(i, now)).collect(),
|
||||
))
|
||||
}
|
||||
|
||||
/// `POST /api/v1/platform/tenants/{id}/supplier-invites/{invite}/withdraw`:
|
||||
/// withdraw an invite, so its link allows nothing more. Withdrawing one
|
||||
/// already withdrawn keeps the first withdrawal.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// 404 when the tenant has no such invite; 422 without a usable
|
||||
/// `withdrawn_by`.
|
||||
pub async fn withdraw_invite(
|
||||
State(st): State<PlatformState>,
|
||||
Path((tenant_id, invite_id)): Path<(String, String)>,
|
||||
Json(body): Json<WithdrawInvite>,
|
||||
) -> Result<Json<InviteView>, StatusCode> {
|
||||
let id = ObjectId::parse_str(invite_id.trim()).map_err(|_| StatusCode::NOT_FOUND)?;
|
||||
let by = normalized_actor(&body.withdrawn_by).ok_or(StatusCode::UNPROCESSABLE_ENTITY)?;
|
||||
let db = st.agent.db_pool.for_existing_tenant_id(&tenant_id);
|
||||
let now = Utc::now();
|
||||
// Only an invite not yet withdrawn is changed; either way it is read back.
|
||||
invites(&db)
|
||||
.update_one(
|
||||
doc! { "_id": id, "withdrawn_at": null },
|
||||
doc! { "$set": {
|
||||
"withdrawn_at": BsonDateTime::from(now),
|
||||
"withdrawn_by": by,
|
||||
} },
|
||||
)
|
||||
.await
|
||||
.map_err(internal)?;
|
||||
let invite = invites(&db)
|
||||
.find_one(doc! { "_id": id })
|
||||
.await
|
||||
.map_err(internal)?
|
||||
.ok_or(StatusCode::NOT_FOUND)?;
|
||||
Ok(Json(InviteView::of(invite, now)))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn invite_at(now: DateTime<Utc>) -> SupplierInvite {
|
||||
SupplierInvite::new("t1".into(), "a@b.example".into(), "u1".into(), now)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_invite_is_active_for_ninety_days() {
|
||||
let now = Utc::now();
|
||||
let invite = invite_at(now);
|
||||
assert_eq!(
|
||||
invite.expires_at.to_chrono() - invite.created_at.to_chrono(),
|
||||
chrono::Duration::days(90)
|
||||
);
|
||||
assert_eq!(invite.state(now), InviteState::Active);
|
||||
let last = now + chrono::Duration::days(90) - chrono::Duration::seconds(1);
|
||||
assert_eq!(invite.state(last), InviteState::Active);
|
||||
assert_eq!(
|
||||
invite.state(now + chrono::Duration::days(90)),
|
||||
InviteState::Expired
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_withdrawn_invite_stays_withdrawn_after_it_expires() {
|
||||
let now = Utc::now();
|
||||
let mut invite = invite_at(now);
|
||||
invite.withdrawn_at = Some(now.into());
|
||||
assert_eq!(invite.state(now), InviteState::Withdrawn);
|
||||
assert_eq!(
|
||||
invite.state(now + chrono::Duration::days(200)),
|
||||
InviteState::Withdrawn
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_address_is_kept_in_lower_case_and_nonsense_is_refused() {
|
||||
assert_eq!(
|
||||
normalized_email(" SBOM@Antrieb.Example "),
|
||||
Some("sbom@antrieb.example".into())
|
||||
);
|
||||
for bad in [
|
||||
"",
|
||||
"no-at.example",
|
||||
"@antrieb.example",
|
||||
"a@localhost",
|
||||
"a@.example",
|
||||
"a@example.",
|
||||
"a@b@c.example",
|
||||
"a b@c.example",
|
||||
] {
|
||||
assert_eq!(normalized_email(bad), None, "{bad}");
|
||||
}
|
||||
let long = format!("{}@b.example", "a".repeat(250));
|
||||
assert_eq!(normalized_email(&long), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_actor_is_required_and_bounded() {
|
||||
assert_eq!(normalized_actor(" u-1 "), Some("u-1".into()));
|
||||
assert_eq!(normalized_actor(" "), None);
|
||||
assert_eq!(normalized_actor(&"u".repeat(201)), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_invite_round_trips_through_bson() {
|
||||
let invite = invite_at(Utc::now());
|
||||
let stored = mongodb::bson::to_document(&invite).expect("bson");
|
||||
assert!(stored.get_datetime("expires_at").is_ok(), "a BSON date");
|
||||
let back: SupplierInvite = mongodb::bson::from_document(stored).expect("back");
|
||||
assert_eq!(back, invite);
|
||||
}
|
||||
}
|
||||
@@ -18,6 +18,7 @@ use compliance_core::{OrgRole, TenantContext, TenantStatus};
|
||||
use crate::agent::ComplianceAgent;
|
||||
use crate::api::handlers;
|
||||
use crate::api::handlers::platform::{self, PlatformState};
|
||||
use crate::api::handlers::supplier_invites;
|
||||
use crate::api::{role_gate, routes};
|
||||
use crate::error::AgentError;
|
||||
|
||||
@@ -365,6 +366,16 @@ pub async fn start_api_server(
|
||||
.put(platform::put_git_source)
|
||||
.delete(platform::delete_git_source),
|
||||
)
|
||||
// Supplier invites (#1027): the portal invites a supplier to upload
|
||||
// one component's SBOM.
|
||||
.route(
|
||||
"/api/v1/platform/tenants/{id}/supplier-invites",
|
||||
get(supplier_invites::list_invites).post(supplier_invites::create_invite),
|
||||
)
|
||||
.route(
|
||||
"/api/v1/platform/tenants/{id}/supplier-invites/{invite}/withdraw",
|
||||
post(supplier_invites::withdraw_invite),
|
||||
)
|
||||
.layer(middleware::from_fn_with_state(
|
||||
platform_state.clone(),
|
||||
platform::require_platform_token,
|
||||
|
||||
@@ -205,6 +205,20 @@ async fn delete_repo_cascades_sast_findings_and_sbom() {
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
// Supplier invites (#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! {
|
||||
"target_id": target,
|
||||
"email": "sbom@supplier.example",
|
||||
"invited_by": "user-1",
|
||||
"created_at": now,
|
||||
"expires_at": now,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
assert_eq!(count_docs(&server, "findings").await, 1);
|
||||
assert_eq!(count_docs(&server, "sbom_entries").await, 1);
|
||||
|
||||
@@ -214,6 +228,7 @@ async fn delete_repo_cascades_sast_findings_and_sbom() {
|
||||
// Both should be gone
|
||||
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);
|
||||
|
||||
server.cleanup().await;
|
||||
}
|
||||
@@ -0,0 +1,269 @@
|
||||
//! 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
|
||||
//! reachable.
|
||||
|
||||
#![allow(clippy::expect_used, clippy::unwrap_used)]
|
||||
|
||||
mod common;
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use axum::routing::{get, post};
|
||||
use axum::Router;
|
||||
use mongodb::bson::doc;
|
||||
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::database::{Database, DatabasePool};
|
||||
use compliance_core::models::{OnboardedTarget, SupplierComponent, TargetType};
|
||||
|
||||
use common::dev_config;
|
||||
|
||||
const TENANT: &str = "invites";
|
||||
const OTHER: &str = "invites-other";
|
||||
|
||||
struct Harness {
|
||||
base_url: String,
|
||||
client: reqwest::Client,
|
||||
pool: DatabasePool,
|
||||
db: Database,
|
||||
}
|
||||
|
||||
async fn start() -> 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]);
|
||||
let Ok(pool) = DatabasePool::connect(&uri, &db_name).await else {
|
||||
eprintln!("SKIP supplier_invites: no MongoDB reachable at {uri}");
|
||||
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 state = PlatformState { agent, jwks: None };
|
||||
let app = Router::new()
|
||||
.route(
|
||||
"/api/v1/platform/tenants/{id}/targets",
|
||||
get(platform::list_targets),
|
||||
)
|
||||
.route(
|
||||
"/api/v1/platform/tenants/{id}/supplier-invites",
|
||||
get(supplier_invites::list_invites).post(supplier_invites::create_invite),
|
||||
)
|
||||
.route(
|
||||
"/api/v1/platform/tenants/{id}/supplier-invites/{invite}/withdraw",
|
||||
post(supplier_invites::withdraw_invite),
|
||||
)
|
||||
.with_state(state);
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let port = listener.local_addr().unwrap().port();
|
||||
tokio::spawn(async move {
|
||||
axum::serve(listener, app).await.ok();
|
||||
});
|
||||
Some(Harness {
|
||||
base_url: format!("http://127.0.0.1:{port}"),
|
||||
client: reqwest::Client::new(),
|
||||
pool,
|
||||
db,
|
||||
})
|
||||
}
|
||||
|
||||
impl Harness {
|
||||
async fn target(&self, name: &str, supplier: bool) -> String {
|
||||
let mut target = OnboardedTarget::new(name.into(), TargetType::FirmwareRtos);
|
||||
target.supplier = supplier.then(|| SupplierComponent {
|
||||
name: "Test Antriebstechnik".into(),
|
||||
product: Some("DR-4".into()),
|
||||
version: Some("1.1".into()),
|
||||
csaf_provider: None,
|
||||
});
|
||||
let id = self
|
||||
.db
|
||||
.onboarded_targets()
|
||||
.insert_one(&target)
|
||||
.await
|
||||
.unwrap()
|
||||
.inserted_id;
|
||||
id.as_object_id().unwrap().to_hex()
|
||||
}
|
||||
|
||||
async fn call(&self, method: reqwest::Method, path: &str, body: Option<Value>) -> (u16, Value) {
|
||||
let mut req = self.client.request(
|
||||
method,
|
||||
format!("{}/api/v1/platform/tenants/{path}", self.base_url),
|
||||
);
|
||||
if let Some(body) = body {
|
||||
req = req.json(&body);
|
||||
}
|
||||
let resp = req.send().await.unwrap();
|
||||
let status = resp.status().as_u16();
|
||||
(status, resp.json().await.unwrap_or_default())
|
||||
}
|
||||
|
||||
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(
|
||||
reqwest::Method::POST,
|
||||
&format!("{tenant}/supplier-invites"),
|
||||
Some(body),
|
||||
)
|
||||
.await
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_supplier_is_invited_for_a_supplier_component_only() {
|
||||
let Some(h) = start().await else { return };
|
||||
let bought = h.target("Antriebsregler DR-4", true).await;
|
||||
let own = h.target("Eigene Steuerung", false).await;
|
||||
|
||||
let (status, invite) = h.invite(TENANT, &bought, " SBOM@Antrieb.Example ").await;
|
||||
assert_eq!(status, 201, "{invite}");
|
||||
assert_eq!(invite["email"], "sbom@antrieb.example");
|
||||
assert_eq!(invite["target_id"], bought.as_str());
|
||||
assert_eq!(invite["invited_by"], "user-1");
|
||||
assert_eq!(invite["state"], "active");
|
||||
let created: chrono::DateTime<chrono::Utc> =
|
||||
invite["created_at"].as_str().unwrap().parse().unwrap();
|
||||
let expires: chrono::DateTime<chrono::Utc> =
|
||||
invite["expires_at"].as_str().unwrap().parse().unwrap();
|
||||
assert_eq!(expires - created, chrono::Duration::days(90));
|
||||
|
||||
// The tenant's own component, nonsense, and another tenant's target.
|
||||
assert_eq!(h.invite(TENANT, &own, "a@b.example").await.0, 422);
|
||||
assert_eq!(h.invite(TENANT, &bought, "no address").await.0, 422);
|
||||
assert_eq!(h.invite(TENANT, "not-an-id", "a@b.example").await.0, 404);
|
||||
assert_eq!(h.invite(OTHER, &bought, "a@b.example").await.0, 404);
|
||||
let no_actor = json!({ "target_id": bought, "email": "a@b.example", "invited_by": " " });
|
||||
let (status, _) = h
|
||||
.call(
|
||||
reqwest::Method::POST,
|
||||
&format!("{TENANT}/supplier-invites"),
|
||||
Some(no_actor),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(status, 422);
|
||||
let stored =
|
||||
h.db.inner()
|
||||
.collection::<SupplierInvite>(SupplierInvite::COLLECTION)
|
||||
.count_documents(doc! {})
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(stored, 1, "a refused invite stores nothing");
|
||||
let other = h.pool.list_tenant_ids().await.unwrap();
|
||||
assert!(
|
||||
!other.iter().any(|t| t == OTHER),
|
||||
"an invite to an unknown tenant creates no database"
|
||||
);
|
||||
|
||||
// The portal's target list says which targets a supplier can be invited for.
|
||||
let (status, targets) = h
|
||||
.call(reqwest::Method::GET, &format!("{TENANT}/targets"), None)
|
||||
.await;
|
||||
assert_eq!(status, 200);
|
||||
let listed = targets["items"].as_array().unwrap();
|
||||
let supplier_of = |id: &str| {
|
||||
listed
|
||||
.iter()
|
||||
.find(|t| t["id"] == id)
|
||||
.map(|t| t["supplier"]["name"].clone())
|
||||
.unwrap()
|
||||
};
|
||||
assert_eq!(supplier_of(&bought), "Test Antriebstechnik");
|
||||
assert_eq!(supplier_of(&own), Value::Null);
|
||||
|
||||
h.pool.drop_tenant(TENANT).await.ok();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn invites_are_listed_with_their_state_and_withdrawn_once() {
|
||||
let Some(h) = start().await else { return };
|
||||
let first = h.target("Antriebsregler DR-4", true).await;
|
||||
let second = h.target("HMI-Panel HP-7", true).await;
|
||||
let (_, active) = h.invite(TENANT, &first, "sbom@antrieb.example").await;
|
||||
let (_, other) = h.invite(TENANT, &second, "psirt@display.example").await;
|
||||
// One made long ago: past its 90 days.
|
||||
let old = SupplierInvite::new(
|
||||
second.clone(),
|
||||
"old@display.example".into(),
|
||||
"user-2".into(),
|
||||
chrono::Utc::now() - chrono::Duration::days(91),
|
||||
);
|
||||
h.db.inner()
|
||||
.collection::<SupplierInvite>(SupplierInvite::COLLECTION)
|
||||
.insert_one(&old)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let (status, all) = h
|
||||
.call(
|
||||
reqwest::Method::GET,
|
||||
&format!("{TENANT}/supplier-invites"),
|
||||
None,
|
||||
)
|
||||
.await;
|
||||
assert_eq!(status, 200);
|
||||
let states: Vec<(&str, &str)> = all
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.map(|i| (i["email"].as_str().unwrap(), i["state"].as_str().unwrap()))
|
||||
.collect();
|
||||
assert_eq!(
|
||||
states,
|
||||
[
|
||||
("psirt@display.example", "active"),
|
||||
("sbom@antrieb.example", "active"),
|
||||
("old@display.example", "expired"),
|
||||
],
|
||||
"newest first"
|
||||
);
|
||||
let (_, of_second) = h
|
||||
.call(
|
||||
reqwest::Method::GET,
|
||||
&format!("{TENANT}/supplier-invites?target={second}"),
|
||||
None,
|
||||
)
|
||||
.await;
|
||||
assert_eq!(of_second.as_array().unwrap().len(), 2);
|
||||
|
||||
let withdraw = |id: &str, by: &str| {
|
||||
let path = format!("{TENANT}/supplier-invites/{id}/withdraw");
|
||||
let body = json!({ "withdrawn_by": by });
|
||||
let h = &h;
|
||||
async move { h.call(reqwest::Method::POST, &path, Some(body)).await }
|
||||
};
|
||||
let id = active["id"].as_str().unwrap();
|
||||
let (status, withdrawn) = withdraw(id, "user-1").await;
|
||||
assert_eq!(status, 200, "{withdrawn}");
|
||||
assert_eq!(withdrawn["state"], "withdrawn");
|
||||
assert_eq!(withdrawn["withdrawn_by"], "user-1");
|
||||
let (status, again) = withdraw(id, "user-3").await;
|
||||
assert_eq!(status, 200);
|
||||
assert_eq!(
|
||||
again["withdrawn_by"], "user-1",
|
||||
"the first withdrawal is kept"
|
||||
);
|
||||
assert_eq!(again["withdrawn_at"], withdrawn["withdrawn_at"]);
|
||||
|
||||
assert_eq!(withdraw(other["id"].as_str().unwrap(), " ").await.0, 422);
|
||||
assert_eq!(
|
||||
withdraw(&mongodb::bson::oid::ObjectId::new().to_hex(), "user-1")
|
||||
.await
|
||||
.0,
|
||||
404
|
||||
);
|
||||
assert_eq!(withdraw("nonsense", "user-1").await.0, 404);
|
||||
let (status, _) = h
|
||||
.call(
|
||||
reqwest::Method::POST,
|
||||
&format!("{OTHER}/supplier-invites/{id}/withdraw"),
|
||||
Some(json!({ "withdrawn_by": "user-1" })),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(status, 404, "another tenant's invite is not found");
|
||||
|
||||
h.pool.drop_tenant(TENANT).await.ok();
|
||||
}
|
||||
@@ -129,6 +129,26 @@ form, and it is stored only when you save it as your own statement.
|
||||
three numbers with the artifact, for the target editor to show.
|
||||
- **A new version from the supplier:** upload it to the same target. It
|
||||
replaces the previous one.
|
||||
- **Inviting the supplier to upload it:** in the portal, you can invite a
|
||||
supplier by e-mail to upload the SBOM of one supplier component. The link
|
||||
is valid for 90 days and also takes the component's later versions. You
|
||||
can withdraw it at any time. The portal holds the link and sends the mail.
|
||||
Prüfwerk keeps each invite with your workspace's data, including the
|
||||
supplier's address, so the workspace export and erasure cover it. Deleting
|
||||
the target deletes its invites. The portal calls the platform API with its
|
||||
service token:
|
||||
- `POST /api/v1/platform/tenants/{id}/supplier-invites` with
|
||||
`{"target_id", "email", "invited_by"}` creates an invite. It answers
|
||||
`201` with its `id`, and `422` for a target without a supplier.
|
||||
- `GET /api/v1/platform/tenants/{id}/supplier-invites[?target=<id>]` lists
|
||||
the invites, newest first. Each one's `state` is `active`, `expired` or
|
||||
`withdrawn`.
|
||||
- `POST …/supplier-invites/{invite}/withdraw` with `{"withdrawn_by"}`
|
||||
withdraws an invite. A second withdrawal keeps the first.
|
||||
|
||||
`GET /api/v1/platform/tenants/{id}/targets` names each supplier
|
||||
component's `supplier`: these are the targets a supplier can be invited
|
||||
for.
|
||||
- **The supplier and its advisories:** a target can name its supplier: the
|
||||
supplier's name, its name for the product, the version in use, and its CSAF
|
||||
provider (`supplier` in the target API, with `provider-metadata.json` as an
|
||||
|
||||
Reference in new issue
Block a user