feat(supplier): the portal invites a supplier for one component (#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 5m16s
CI / Check (pull_request) Successful in 22m0s
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 5m16s
CI / Check (pull_request) Successful in 22m0s
Phase 3 of the supplier SBOM epic: the platform API the portal calls with its service token to invite a supplier, list the tenant's invites and withdraw one. - An invite is kept in the tenant's own database (`supplier_invites`), so the tenant export and erasure cover it, the supplier's address included. The portal owns the secret link and the mail and keys its link by the invite id. - Only a supplier component (a target with `supplier`) can be invited for; any other answers 422, an unknown target or tenant 404, and a lookup in an unknown tenant creates no database. - An invite is valid for 90 days and its state is `active`, `expired` or `withdrawn`; a second withdrawal keeps the first. - Deleting a target deletes its invites. - The portal's target list names each supplier component's `supplier`. The upload through an invite follows in its own PR. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Q9inRcu428A2iNjDHPEAT9
This commit is contained in:
1 parent
31b8cb9d37
commit
5ec891fa28
8 files changed
+705
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,
|
||||
|
||||
Reference in new issue
Block a user