//! A member the workspace blocked (portal#74) is refused, everyone else is //! let in, and support is never asked about. Runs the real entitlement //! middleware against a fake tenant registry and a live Mongo (for the agent //! itself); skips cleanly without one. #![allow(clippy::expect_used, clippy::unwrap_used)] mod common; use std::sync::{Arc, Mutex}; use axum::body::Body; use axum::extract::{Request, State}; use axum::http::StatusCode; use axum::middleware::{from_fn, from_fn_with_state, Next}; use axum::routing::{get, post}; use axum::{Json, Router}; use tower::ServiceExt; use compliance_agent::agent::ComplianceAgent; use compliance_agent::api::server::require_entitlement; use compliance_agent::database::DatabasePool; use compliance_core::{OrgRole, StaffAccess, TenantContext, TenantStatus}; use common::dev_config; /// The bodies the fake registry's entitlement check received. type Seen = Arc>>; /// A registry that blocks the member `u-blocked`. async fn fake_registry(seen: Seen) -> String { let app = Router::new() .route( "/v1/internal/entitlements/check", post(|State(seen): State, Json(body): Json| async move { let blocked = body["user_id"].as_str() == Some("u-blocked"); seen.lock().unwrap().push(body); Json(if blocked { serde_json::json!({ "allowed": false, "status": "active", "reason": "member_blocked" }) } else { serde_json::json!({ "allowed": true, "status": "active" }) }) }), ) .route( "/v1/tenants/{id}", get(|| async { Json(serde_json::json!({ "id": "t-1", "slug": "acme", "name": "Acme", "status": "active" })) }), ) .with_state(seen); 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.unwrap() }); format!("http://{addr}") } fn member(user: &str) -> TenantContext { TenantContext { tenant_id: "t-1".into(), tenant_slug: "acme".into(), org_roles: vec![OrgRole::ItAdmin], products: vec!["compliance-scanner".into()], plan: "starter".into(), status: TenantStatus::Active, user_id: user.into(), user_name: None, staff: None, api_key: None, } } /// An agent whose registry is `registry`, or `None` without Mongo. async fn agent(registry: &str) -> Option> { let uri = std::env::var("TEST_MONGODB_URI") .unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into()); let db_name = format!("blk_{}", &uuid::Uuid::new_v4().simple().to_string()[..10]); let Ok(pool) = DatabasePool::connect(&uri, &db_name).await else { eprintln!("SKIP member_blocked: 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))) } /// GET /r as `ctx` through the entitlement middleware. async fn call(agent: Arc, ctx: TenantContext) -> (StatusCode, serde_json::Value) { 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("/r", get(|| async { "ok" })) .layer(from_fn_with_state(agent, require_entitlement)) .layer(from_fn(inject)); let resp = app .oneshot(Request::builder().uri("/r").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 a_blocked_member_is_refused_and_others_are_not() { let seen: Seen = Arc::default(); let base = fake_registry(seen.clone()).await; let Some(agent) = agent(&base).await else { return; }; // A blocked member: 403 MEMBER_BLOCKED. let (status, body) = call(agent.clone(), member("u-blocked")).await; assert_eq!(status, StatusCode::FORBIDDEN); assert_eq!(body["error"], "MEMBER_BLOCKED"); // Anyone else in the same tenant: let in, and the registry was asked // about that person (by their Keycloak sub). let (status, _) = call(agent.clone(), member("u-ok")).await; assert_eq!(status, StatusCode::OK); assert_eq!(seen.lock().unwrap().last().unwrap()["user_id"], "u-ok"); // Support takes its own path: the entitlement check (and with it the // block check) is not asked at all. let calls = seen.lock().unwrap().len(); let mut support = member("staff-1"); support.staff = Some(StaffAccess { user_id: "staff-1".into(), user_name: Some("Support".into()), }); let (status, _) = call(agent.clone(), support).await; assert_eq!(status, StatusCode::OK); assert_eq!(seen.lock().unwrap().len(), calls); } #[tokio::test] async fn an_unreachable_registry_still_refuses_as_before() { // Not a block decision: the entitlement check itself fails closed when // the registry cannot be asked (MVP-1.2); the block check adds nothing. let Some(agent) = agent("http://127.0.0.1:9").await else { return; }; let (status, body) = call(agent, member("u-ok")).await; assert_eq!(status, StatusCode::SERVICE_UNAVAILABLE); assert_eq!(body["error"], "entitlement_unavailable"); }