feat(registry): connections between workspaces in the registry client (#1028) #1062

Merged
sharang merged 1 commits from feat/registry-connections into main 2026-11-19 12:12:03 +00:00
5 changed files with 377 additions and 0 deletions

No files matched your search

@@ -0,0 +1,69 @@
//! The workspace's connections to other workspaces (#1028), held by the
//! tenant registry (tenant-registry#138): whom a supplier can release an SBOM
//! to. A connection shows only its id and the other workspace's display
//! name, never the other tenant's id.
use axum::extract::Extension;
use axum::http::StatusCode;
use axum::Json;
use serde::Serialize;
use compliance_core::tenant_ctx::TenantCtx;
use super::dto::AgentExt;
use super::ApiResponse;
/// A connection as the workspace sees it.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct ConnectionView {
/// The connection's id.
pub id: String,
/// The other workspace's display name.
pub peer_name: String,
}
/// The workspace's active connections to other workspaces.
///
/// Each by its id and the other workspace's display name, by name; nothing
/// else of the other workspace. Connections are made and ended in the
/// portal. Without a registry (development) there are none.
#[utoipa::path(
get,
path = "/api/v1/connections",
tag = "Targets",
responses(
(status = 200, description = "The active connections (`data`)"),
(status = 503, description = "The registry cannot be asked"),
(status = 401, description = "No valid bearer token"),
)
)]
#[tracing::instrument(skip_all)]
pub async fn list_connections(
Extension(agent): AgentExt,
tenant: TenantCtx,
) -> Result<Json<ApiResponse<Vec<ConnectionView>>>, StatusCode> {
let connections = match agent.registry.as_ref() {
None => Vec::new(),
Some(registry) => registry
.active_connections(&tenant.0.tenant_id)
.await
.map_err(|e| {
tracing::error!(tenant_id = %tenant.0.tenant_id, "connections unavailable: {e}");
StatusCode::SERVICE_UNAVAILABLE
})?,
};
let mut views: Vec<ConnectionView> = connections
.into_iter()
.map(|c| ConnectionView {
id: c.id,
peer_name: c.peer_name,
})
.collect();
// One lowercase name per connection, not one per comparison.
views.sort_by_cached_key(|v| v.peer_name.to_lowercase());
Ok(Json(ApiResponse {
data: views,
total: None,
page: None,
}))
}
+1
View File
@@ -1,5 +1,6 @@
pub mod admin;
pub mod chat;
pub mod connections;
pub mod cve_history;
pub mod cve_matrix;
pub mod dast;
+1
View File
@@ -51,6 +51,7 @@ fn described_routes() -> OpenApiRouter {
.routes(routes!(handlers::machine::machine_cves))
.routes(routes!(handlers::machine::machine_scan_changes))
.routes(routes!(handlers::supply_chain::get_supply_chain))
.routes(routes!(handlers::connections::list_connections))
.routes(routes!(handlers::supply_chain::project_documents))
// The customer's arrangement of the supply chain (#1052).
.routes(routes!(
+139
View File
@@ -39,6 +39,46 @@ const TOKEN_MARGIN: Duration = Duration::from_secs(30);
/// client's 30 s.
const REQUEST_TIMEOUT: Duration = Duration::from_secs(5);
/// One of the tenant's active connections to another workspace (#1028,
/// tenant-registry#138), as a product reads it. The peer's tenant id is for
/// delivering to it inside the product; it is never shown to anyone.
#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
pub struct Connection {
/// The connection's id.
pub id: String,
/// The other workspace's tenant id.
pub peer_tenant_id: String,
/// The other workspace's display name: all either side sees of the other.
pub peer_name: String,
}
/// One connection as the registry checks it
/// (`GET /v1/internal/connections/{id}`).
#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
pub struct ConnectionState {
/// Whether it is active: accepted and not ended.
pub active: bool,
/// The two tenants it joins.
pub tenant_ids: Vec<String>,
}
impl ConnectionState {
/// The tenant on the other side from `tenant`, while the connection is
/// active and `tenant` is one of its two sides; `None` otherwise. What a
/// delivery asks right before it writes to another tenant's database.
pub fn peer_of(&self, tenant: &str) -> Option<&str> {
let [a, b] = self.tenant_ids.as_slice() else {
return None;
};
match (self.active, a == b) {
(false, _) | (_, true) => None,
_ if a == tenant => Some(b),
_ if b == tenant => Some(a),
_ => None,
}
}
}
/// A document of the tenant's store (Dokumentenablage), as the registry
/// lists it (`GET /v1/tenants/{id}/store`).
#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
@@ -586,6 +626,69 @@ impl RegistryClient {
Ok(page.items)
}
/// The tenant's active connections to other workspaces (#1028). Not
/// cached: a connection ended a second ago must not be offered.
///
/// # Errors
///
/// The registry could not be asked, or answered with an error.
pub async fn active_connections(&self, tenant_id: &str) -> Result<Vec<Connection>, String> {
#[derive(Deserialize)]
struct Page {
#[serde(default)]
items: Vec<Connection>,
}
let resp = self
.request(
reqwest::Method::GET,
&format!(
"/v1/internal/tenants/{}/connections?state=active",
urlencoding::encode(tenant_id)
),
)
.await?
.send()
.await
.map_err(|e| format!("connection list failed: {e}"))?;
if !resp.status().is_success() {
return Err(format!("connection list returned {}", resp.status()));
}
let page: Page = resp
.json()
.await
.map_err(|e| format!("connection list invalid: {e}"))?;
Ok(page.items)
}
/// Connection `id` as the registry knows it now; `None` when it knows no
/// such connection. Asked right before every delivery over it.
///
/// # Errors
///
/// The registry could not be asked, or answered with an error other than
/// 404.
pub async fn connection(&self, id: &str) -> Result<Option<ConnectionState>, String> {
let resp = self
.request(
reqwest::Method::GET,
&format!("/v1/internal/connections/{}", urlencoding::encode(id)),
)
.await?
.send()
.await
.map_err(|e| format!("connection check failed: {e}"))?;
if resp.status() == reqwest::StatusCode::NOT_FOUND {
return Ok(None);
}
if !resp.status().is_success() {
return Err(format!("connection check returned {}", resp.status()));
}
resp.json()
.await
.map(Some)
.map_err(|e| format!("connection check invalid: {e}"))
}
/// Verify a portal-issued API key (`bp_…`), valid or not, reusing a
/// verdict younger than [`API_KEY_TTL`].
///
@@ -713,6 +816,42 @@ pub fn scheduler_runs_for(status: &str) -> bool {
mod tests {
use super::*;
#[test]
fn a_connection_names_the_other_side_only_while_active_and_ours() {
let joined = |active: bool, ids: &[&str]| ConnectionState {
active,
tenant_ids: ids.iter().map(|t| t.to_string()).collect(),
};
let c = joined(true, &["supplier", "customer"]);
assert_eq!(c.peer_of("supplier"), Some("customer"));
assert_eq!(c.peer_of("customer"), Some("supplier"));
assert_eq!(
c.peer_of("someone else"),
None,
"a third tenant gets nothing"
);
assert_eq!(
joined(false, &["supplier", "customer"]).peer_of("supplier"),
None,
"ended"
);
assert_eq!(
joined(true, &["supplier", "supplier"]).peer_of("supplier"),
None,
"itself"
);
assert_eq!(
joined(true, &["supplier"]).peer_of("supplier"),
None,
"one side"
);
assert_eq!(
joined(true, &["a", "b", "c"]).peer_of("a"),
None,
"three sides"
);
}
#[test]
fn the_plan_sets_how_many_targets_are_included() {
let check = |limits: serde_json::Value| -> EntitlementCheck {
+167
View File
@@ -0,0 +1,167 @@
//! Connections between workspaces (#1028) against a fake tenant registry
//! (tenant-registry#138): the client lists a tenant's active connections and
//! checks one, and the workspace's list shows only each connection's id and
//! the other side's name. Needs a live Mongo for the agent itself; skips
//! cleanly without one.
#![allow(clippy::expect_used, clippy::unwrap_used)]
mod common;
use std::sync::Arc;
use axum::body::Body;
use axum::extract::{Path, Request};
use axum::http::StatusCode;
use axum::middleware::{from_fn, Next};
use axum::routing::get;
use axum::{Extension, Json, Router};
use tower::ServiceExt;
use compliance_agent::agent::ComplianceAgent;
use compliance_agent::api::handlers::connections::list_connections;
use compliance_agent::database::DatabasePool;
use compliance_core::{OrgRole, TenantContext, TenantStatus};
use common::dev_config;
/// A registry where tenant `t-1` is connected to two workspaces and
/// connection `c-ended` has ended; `t-down` cannot be listed.
async fn fake_registry() -> String {
let app = Router::new()
.route(
"/v1/internal/tenants/{id}/connections",
get(|Path(id): Path<String>| async move {
match id.as_str() {
"t-1" => Ok(Json(serde_json::json!({ "items": [
{ "id": "c-2", "peer_tenant_id": "t-3", "peer_name": "Muster Anlagenbau" },
{ "id": "c-1", "peer_tenant_id": "t-2", "peer_name": "beispiel Maschinenbau" },
] }))),
"t-down" => Err(StatusCode::INTERNAL_SERVER_ERROR),
_ => Ok(Json(serde_json::json!({ "items": [] }))),
}
}),
)
.route(
"/v1/internal/connections/{id}",
get(|Path(id): Path<String>| async move {
match id.as_str() {
"c-1" => Ok(Json(serde_json::json!({ "active": true, "tenant_ids": ["t-1", "t-2"] }))),
"c-ended" => Ok(Json(serde_json::json!({ "active": false, "tenant_ids": ["t-1", "t-2"] }))),
_ => Err(StatusCode::NOT_FOUND),
}
}),
);
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}")
}
/// An agent whose registry is `registry`, or `None` without Mongo.
async fn agent(registry: &str) -> Option<Arc<ComplianceAgent>> {
let uri = std::env::var("TEST_MONGODB_URI")
.unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into());
let db_name = format!("con_{}", &uuid::Uuid::new_v4().simple().to_string()[..10]);
let Ok(pool) = DatabasePool::connect(&uri, &db_name).await else {
eprintln!("SKIP connections: no MongoDB reachable at {uri}");
return None;
};
let mut config = dev_config(uri, db_name);
config.tenant_registry_url = Some(registry.to_string());
Some(Arc::new(ComplianceAgent::new(config, pool)))
}
fn member(tenant: &str) -> TenantContext {
TenantContext {
tenant_id: tenant.into(),
tenant_slug: "acme".into(),
org_roles: vec![OrgRole::ItAdmin],
products: vec!["compliance-scanner".into()],
plan: "starter".into(),
status: TenantStatus::Active,
user_id: "u-1".into(),
user_name: None,
staff: None,
api_key: None,
}
}
/// `GET /api/v1/connections` as a member of `tenant`.
async fn list(agent: Arc<ComplianceAgent>, tenant: &str) -> (StatusCode, serde_json::Value) {
let ctx = member(tenant);
let inject = move |mut req: Request, next: Next| {
let ctx = ctx.clone();
async move {
req.extensions_mut().insert(ctx);
next.run(req).await
}
};
let app = Router::new()
.route("/api/v1/connections", get(list_connections))
.layer(Extension(agent))
.layer(from_fn(inject));
let resp = app
.oneshot(
Request::builder()
.uri("/api/v1/connections")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
let status = resp.status();
let bytes = axum::body::to_bytes(resp.into_body(), 1 << 16)
.await
.unwrap();
(status, serde_json::from_slice(&bytes).unwrap_or_default())
}
#[tokio::test]
async fn the_client_lists_and_checks_connections() {
let base = fake_registry().await;
let Some(agent) = agent(&base).await else {
return;
};
let registry = agent.registry.clone().unwrap();
let listed = registry.active_connections("t-1").await.unwrap();
assert_eq!(listed.len(), 2);
assert_eq!(listed[1].peer_tenant_id, "t-2");
assert!(registry.active_connections("t-down").await.is_err());
let c1 = registry.connection("c-1").await.unwrap().unwrap();
assert_eq!(c1.peer_of("t-1"), Some("t-2"));
assert_eq!(c1.peer_of("t-9"), None, "a third workspace gets nothing");
let ended = registry.connection("c-ended").await.unwrap().unwrap();
assert_eq!(
ended.peer_of("t-1"),
None,
"an ended connection delivers nothing"
);
assert_eq!(registry.connection("c-unknown").await.unwrap(), None);
}
#[tokio::test]
async fn the_workspace_sees_each_connection_by_name_only() {
let base = fake_registry().await;
let Some(agent) = agent(&base).await else {
return;
};
let (status, body) = list(agent.clone(), "t-1").await;
assert_eq!(status, StatusCode::OK);
assert_eq!(
body["data"],
serde_json::json!([
{ "id": "c-1", "peer_name": "beispiel Maschinenbau" },
{ "id": "c-2", "peer_name": "Muster Anlagenbau" },
]),
"by name, without the other tenant's id"
);
assert!(!body.to_string().contains("t-2"));
let (status, _) = list(agent, "t-down").await;
assert_eq!(status, StatusCode::SERVICE_UNAVAILABLE);
}