e20e7f1c6e
CI / Check (pull_request) Successful in 8m4s
CI / Detect Changes (pull_request) Has been skipped
CI / Deploy Agent (pull_request) Has been skipped
CI / Deploy Dashboard (pull_request) Has been skipped
CI / Deploy Docs (pull_request) Has been skipped
CI / Deploy MCP (pull_request) Has been skipped
Adds two cross-tenant operator endpoints on top of the M7.2-D
DatabasePool primitives:
- GET /api/v1/admin/tenants → list tenant DBs
- DELETE /api/v1/admin/tenants/{tenant_id} → drop (GDPR delete)
Auth is a static bearer (ADMIN_API_TOKEN env), explicitly NOT a
Keycloak JWT — the whole point is to operate across tenants and a
customer JWT always carries a single tenant_id, which would be a
semantic conflict. Comparison is constant-time to avoid byte-level
timing probes.
Design
- ADMIN_API_TOKEN env on the agent. When unset, the admin routes
aren't mounted at all (404 rather than 401). An operator who
hasn't opted in can't fingerprint the surface.
- Admin sub-router is built in start_api_server when the token is
configured, then merged into the main router with its own
require_admin_token middleware.
- compliance-core::auth gains a PUBLIC_PREFIXES list. Paths under
/api/v1/admin/ bypass require_jwt_auth so the customer JWT path
and the admin token path never collide.
- require_tenant_status passes through naturally — admin requests
carry no TenantContext.
Files
- compliance-core/src/auth.rs — PUBLIC_PREFIXES + prefix-aware skip.
- compliance-core/src/config.rs — admin_api_token + tenant_registry_url
fields on AgentConfig. tenant_registry_url is added now so the
scheduler→registry PR doesn't have to bump the config shape again.
- compliance-agent/src/config.rs — env wiring for both.
- compliance-agent/src/api/handlers/admin.rs (new) — list_tenant_dbs,
drop_tenant_db, require_admin_token middleware, tokens_eq helper
with a small test.
- compliance-agent/src/api/server.rs — conditional admin sub-router
+ merge.
- Test harness fixtures updated for the two new config fields.
Test plan
- cargo fmt --all clean
- cargo clippy --workspace --exclude compliance-dashboard
-- -D warnings clean
- cargo test -p compliance-core --lib — 7 pass
- cargo test -p compliance-agent --lib — 229 pass (+1 new for
tokens_eq)
Production
- Set ADMIN_API_TOKEN in orca-infra (per-secret, NOT committed) when
ready to expose these endpoints. Without the env, the routes
literally don't exist on the binary.
- Long-term: replace the static bearer with a dedicated admin realm
in Keycloak. Token rotation is just an env change + restart for
now; revocation responsiveness is zero.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
180 lines
6.2 KiB
Rust
180 lines
6.2 KiB
Rust
// Shared test harness for E2E / integration tests.
|
|
//
|
|
// Spins up the agent API server on a random port with an isolated test
|
|
// database. Each test gets a fresh database that is dropped on cleanup.
|
|
|
|
use std::sync::Arc;
|
|
|
|
use compliance_agent::agent::ComplianceAgent;
|
|
use compliance_agent::api;
|
|
use compliance_agent::database::DatabasePool;
|
|
use compliance_core::AgentConfig;
|
|
use secrecy::SecretString;
|
|
|
|
/// A running test server with a unique database.
|
|
pub struct TestServer {
|
|
pub base_url: String,
|
|
pub client: reqwest::Client,
|
|
db_name: String,
|
|
mongodb_uri: String,
|
|
}
|
|
|
|
impl TestServer {
|
|
/// Start an agent API server on a random port with an isolated database.
|
|
pub async fn start() -> Self {
|
|
let mongodb_uri = std::env::var("TEST_MONGODB_URI")
|
|
.unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into());
|
|
|
|
// Unique database name per test run to avoid collisions
|
|
let db_name = format!("test_{}", uuid::Uuid::new_v4().simple());
|
|
|
|
let db_pool = DatabasePool::connect(&mongodb_uri, &db_name)
|
|
.await
|
|
.expect("Failed to build DatabasePool");
|
|
|
|
let config = AgentConfig {
|
|
mongodb_uri: mongodb_uri.clone(),
|
|
mongodb_database: db_name.clone(),
|
|
litellm_url: std::env::var("TEST_LITELLM_URL")
|
|
.unwrap_or_else(|_| "http://localhost:4000".into()),
|
|
litellm_api_key: SecretString::from(String::new()),
|
|
litellm_model: "gpt-4o".into(),
|
|
litellm_embed_model: "text-embedding-3-small".into(),
|
|
agent_port: 0, // not used — we bind ourselves
|
|
scan_schedule: String::new(),
|
|
cve_monitor_schedule: String::new(),
|
|
git_clone_base_path: "/tmp/compliance-scanner-tests/repos".into(),
|
|
ssh_key_path: "/tmp/compliance-scanner-tests/ssh/id_ed25519".into(),
|
|
github_token: None,
|
|
github_webhook_secret: None,
|
|
gitlab_url: None,
|
|
gitlab_token: None,
|
|
gitlab_webhook_secret: None,
|
|
jira_url: None,
|
|
jira_email: None,
|
|
jira_api_token: None,
|
|
jira_project_key: None,
|
|
searxng_url: None,
|
|
nvd_api_key: None,
|
|
keycloak_url: None,
|
|
keycloak_realm: None,
|
|
keycloak_admin_username: None,
|
|
keycloak_admin_password: None,
|
|
pentest_verification_email: None,
|
|
pentest_imap_host: None,
|
|
pentest_imap_port: None,
|
|
pentest_imap_tls: false,
|
|
pentest_imap_username: None,
|
|
pentest_imap_password: None,
|
|
admin_api_token: None,
|
|
tenant_registry_url: None,
|
|
};
|
|
|
|
let agent = ComplianceAgent::new(config, db_pool);
|
|
|
|
// Build the router with the agent extension. After M7.2-B every
|
|
// handler takes a TenantCtx extractor; without KC in the test
|
|
// harness, the dev-tenant injector mounts a synthetic context so
|
|
// tests run end-to-end against `<db_name>_dev`.
|
|
let app = api::routes::build_router()
|
|
.layer(axum::extract::Extension(Arc::new(agent)))
|
|
.layer(axum::middleware::from_fn(api::server::inject_dev_tenant))
|
|
.layer(tower_http::cors::CorsLayer::permissive());
|
|
|
|
// Bind to port 0 to get a random available port
|
|
let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
|
|
.await
|
|
.expect("Failed to bind test server");
|
|
let port = listener.local_addr().expect("no local addr").port();
|
|
|
|
tokio::spawn(async move {
|
|
axum::serve(listener, app).await.ok();
|
|
});
|
|
|
|
let base_url = format!("http://127.0.0.1:{port}");
|
|
let client = reqwest::Client::builder()
|
|
.timeout(std::time::Duration::from_secs(30))
|
|
.build()
|
|
.expect("Failed to build HTTP client");
|
|
|
|
// Wait for server to be ready
|
|
for _ in 0..50 {
|
|
if client
|
|
.get(format!("{base_url}/api/v1/health"))
|
|
.send()
|
|
.await
|
|
.is_ok()
|
|
{
|
|
break;
|
|
}
|
|
tokio::time::sleep(std::time::Duration::from_millis(50)).await;
|
|
}
|
|
|
|
Self {
|
|
base_url,
|
|
client,
|
|
db_name,
|
|
mongodb_uri,
|
|
}
|
|
}
|
|
|
|
/// GET helper
|
|
pub async fn get(&self, path: &str) -> reqwest::Response {
|
|
self.client
|
|
.get(format!("{}{path}", self.base_url))
|
|
.send()
|
|
.await
|
|
.expect("GET request failed")
|
|
}
|
|
|
|
/// POST helper with JSON body
|
|
pub async fn post(&self, path: &str, body: &serde_json::Value) -> reqwest::Response {
|
|
self.client
|
|
.post(format!("{}{path}", self.base_url))
|
|
.json(body)
|
|
.send()
|
|
.await
|
|
.expect("POST request failed")
|
|
}
|
|
|
|
/// PATCH helper with JSON body
|
|
pub async fn patch(&self, path: &str, body: &serde_json::Value) -> reqwest::Response {
|
|
self.client
|
|
.patch(format!("{}{path}", self.base_url))
|
|
.json(body)
|
|
.send()
|
|
.await
|
|
.expect("PATCH request failed")
|
|
}
|
|
|
|
/// DELETE helper
|
|
pub async fn delete(&self, path: &str) -> reqwest::Response {
|
|
self.client
|
|
.delete(format!("{}{path}", self.base_url))
|
|
.send()
|
|
.await
|
|
.expect("DELETE request failed")
|
|
}
|
|
|
|
/// Get the unique database name for direct MongoDB access in tests.
|
|
pub fn db_name(&self) -> &str {
|
|
&self.db_name
|
|
}
|
|
|
|
/// Drop every per-tenant database belonging to this test run.
|
|
/// Post-M7.2-D the agent never opens a `db_name` directly —
|
|
/// data lives only in `<db_name>_<tenant>` per-tenant databases.
|
|
pub async fn cleanup(&self) {
|
|
if let Ok(client) = mongodb::Client::with_uri_str(&self.mongodb_uri).await {
|
|
if let Ok(names) = client.list_database_names().await {
|
|
let prefix = format!("{}_", self.db_name);
|
|
for name in names {
|
|
if name.starts_with(&prefix) {
|
|
client.database(&name).drop().await.ok();
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|