From 0dd43be4803a367e1e5a08cbccd85db71474aeaf Mon Sep 17 00:00:00 2001 From: Sharang Parnerkar <30073382+mighty840@users.noreply.github.com> Date: Sat, 14 Nov 2026 11:04:09 +0100 Subject: [PATCH] fix(pentest): delete test users only in the target's identity provider (#999) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The cleanup of an auto-register session deleted the test user in Prüfwerk's own Keycloak realm, through the agent's master-realm admin login, whatever identity provider the target used. It never ran only because the username was never recorded. - Cleanup acts only on admin access given for the session (`config.auth.cleanup`: Keycloak realm client, Auth0 M2M app, Okta token), sealed like the other session credentials and checked by the net guard; the agent's KEYCLOAK_ADMIN_* settings are gone. - The user is found by the session's own plus-addressed e-mail and deleted only when exactly one account carries exactly that address. The prompt now gives the LLM that exact address. - The test user is written to the stored session; a user that cannot be deleted is recorded as left behind and named in the report. - Firebase and Custom are not cleaned up (supersedes #17). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Q9inRcu428A2iNjDHPEAT9 --- .../api/handlers/pentest_handlers/session.rs | 51 +- compliance-agent/src/config.rs | 2 - compliance-agent/src/pentest/cleanup.rs | 935 ++++++++++-------- compliance-agent/src/pentest/orchestrator.rs | 105 +- .../src/pentest/prompt_builder.rs | 18 +- .../src/pentest/report/html/scope.rs | 49 +- compliance-core/src/config.rs | 4 - compliance-core/src/models/credentials.rs | 32 +- compliance-core/src/models/pentest.rs | 67 +- compliance-core/tests/models.rs | 34 + docs/features/pentest.md | 1 + docs/reference/tools.md | 2 +- 12 files changed, 813 insertions(+), 487 deletions(-) diff --git a/compliance-agent/src/api/handlers/pentest_handlers/session.rs b/compliance-agent/src/api/handlers/pentest_handlers/session.rs index 2a2f38b..7210a21 100644 --- a/compliance-agent/src/api/handlers/pentest_handlers/session.rs +++ b/compliance-agent/src/api/handlers/pentest_handlers/session.rs @@ -86,6 +86,13 @@ pub async fn create_session( if let Err(e) = agent.net_guard.check_url(&config.app_url) { return Err((StatusCode::BAD_REQUEST, e.to_string())); } + // The test-user cleanup talks to the target's identity provider, also + // a tenant-chosen URL. + if let Some(access) = &config.auth.cleanup { + if let Err(e) = agent.net_guard.check_url(&access.base_url()) { + return Err((StatusCode::BAD_REQUEST, e.to_string())); + } + } // Look up or auto-create DastTarget by app_url let target = match db @@ -187,35 +194,21 @@ pub async fn create_session( } } - // Pre-populate test user record for auto-register sessions - if let Some(ref cfg) = session.config { - if cfg.auth.mode == AuthMode::AutoRegister { - let verification_email = cfg.auth.verification_email.clone(); - // Build plus-addressed email for this session - let test_email = verification_email.as_deref().map(|email| { - let parts: Vec<&str> = email.splitn(2, '@').collect(); - if parts.len() == 2 { - format!("{}+{}@{}", parts[0], session_id_str, parts[1]) - } else { - email.to_string() - } - }); - - // Detect identity provider from keycloak config - let provider = if agent.config.keycloak_url.is_some() { - Some(compliance_core::models::pentest::IdentityProvider::Keycloak) - } else { - None - }; - - session.test_user = Some(compliance_core::models::pentest::TestUserRecord { - username: None, // LLM will choose; updated after registration - email: test_email, - provider_user_id: None, - provider, - cleaned_up: false, - }); - } + // The test user an auto-register session registers, kept on the + // stored session so cleanup and the report find it. + if let Some(cfg) = &session.config { + session.test_user = crate::pentest::cleanup::planned_test_user(cfg, &session_id_str); + } + if let (Some(sid), Some(test_user)) = (session.id, &session.test_user) { + let record = mongodb::bson::to_bson(test_user) + .map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?; + db.pentest_sessions() + .update_one( + doc! { "_id": sid }, + doc! { "$set": { "test_user": record } }, + ) + .await + .map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, format!("DB error: {e}")))?; } let initial_message = config diff --git a/compliance-agent/src/config.rs b/compliance-agent/src/config.rs index c17b67b..7918236 100644 --- a/compliance-agent/src/config.rs +++ b/compliance-agent/src/config.rs @@ -87,8 +87,6 @@ fn build_config(app_env: AppEnv) -> Result { .unwrap_or_else(|| "/data/compliance-scanner/artifacts".to_string()), keycloak_url: env_var_opt("KEYCLOAK_URL"), keycloak_realm: env_var_opt("KEYCLOAK_REALM"), - keycloak_admin_username: env_var_opt("KEYCLOAK_ADMIN_USERNAME"), - keycloak_admin_password: env_secret_opt("KEYCLOAK_ADMIN_PASSWORD"), pentest_verification_email: env_var_opt("PENTEST_VERIFICATION_EMAIL"), pentest_imap_host: env_var_opt("PENTEST_IMAP_HOST"), pentest_imap_port: env_var_opt("PENTEST_IMAP_PORT").and_then(|p| p.parse().ok()), diff --git a/compliance-agent/src/pentest/cleanup.rs b/compliance-agent/src/pentest/cleanup.rs index 02a19fc..e3a3b12 100644 --- a/compliance-agent/src/pentest/cleanup.rs +++ b/compliance-agent/src/pentest/cleanup.rs @@ -1,458 +1,611 @@ -use compliance_core::models::pentest::{IdentityProvider, TestUserRecord}; -use compliance_core::AgentConfig; -use secrecy::ExposeSecret; -use tracing::{info, warn}; +//! Deleting the test user an auto-register pentest session registered (#999). +//! +//! Cleanup acts only on the target's own identity provider, with the admin +//! access given for that session ([`TestUserCleanup`]); the agent's own +//! identity provider is never asked. The user is found by the session's own +//! e-mail address (`base+{session_id}@domain`) and deleted only when exactly +//! one account carries exactly that address. -/// Attempt to delete a test user created during a pentest session. +use compliance_core::models::pentest::{PentestConfig, TestUserCleanup, TestUserRecord}; +use serde_json::Value; +use tracing::info; + +/// What became of a test user. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum CleanupOutcome { + /// Deleted from the target's identity provider (or already deleted). + Deleted, + /// No account carries the session's e-mail address: registration never + /// completed, so nothing is left to delete. + NotRegistered, + /// Still in the target's identity provider, for the reason given; it has + /// to be deleted by hand. + LeftBehind(String), +} + +/// The test user an auto-register session will register, keyed by its own +/// plus-addressed e-mail address. `None` for other modes, and when no +/// verification address is known (the user could not be found again). /// -/// Routes to the appropriate identity provider based on `TestUserRecord.provider`. -/// Falls back to browser-based cleanup if no API credentials are available. +/// # Arguments /// -/// Returns `Ok(true)` if the user was deleted, `Ok(false)` if skipped, `Err` on failure. +/// * `config` - the session's wizard configuration, server defaults merged in +/// * `session_id` - the session's id, which makes the address unique +pub fn planned_test_user(config: &PentestConfig, session_id: &str) -> Option { + use compliance_core::models::pentest::AuthMode; + if config.auth.mode != AuthMode::AutoRegister { + return None; + } + let base = config.auth.verification_email.as_deref()?; + let (local, domain) = base.split_once('@')?; + Some(TestUserRecord { + email: Some(format!("{local}+{session_id}@{domain}")), + provider: config.auth.cleanup.as_ref().map(TestUserCleanup::provider), + ..Default::default() + }) +} + +/// Delete `user` from the identity provider `access` names. +/// +/// # Arguments +/// +/// * `user` - the session's test user +/// * `access` - admin access to the target's identity provider, if given +/// * `http` - a client for tenant-chosen URLs (guarded) +/// +/// # Returns +/// +/// What became of the user; [`CleanupOutcome::LeftBehind`] whenever this +/// session cannot delete it safely (no access given, no address to find it +/// by, several accounts with the address). +/// +/// # Errors +/// +/// A message when the identity provider refuses or cannot be reached. pub async fn cleanup_test_user( user: &TestUserRecord, - config: &AgentConfig, + access: Option<&TestUserCleanup>, http: &reqwest::Client, -) -> Result { +) -> Result { if user.cleaned_up { - return Ok(false); + return Ok(CleanupOutcome::Deleted); } - - let provider = user.provider.as_ref(); - - match provider { - Some(IdentityProvider::Keycloak) => cleanup_keycloak(user, config, http).await, - Some(IdentityProvider::Auth0) => cleanup_auth0(user, config, http).await, - Some(IdentityProvider::Okta) => cleanup_okta(user, config, http).await, - Some(IdentityProvider::Firebase) => { - warn!("Firebase user cleanup not yet implemented"); - Ok(false) + let Some(access) = access else { + return Ok(left_behind( + "no admin access to the target's identity provider was given", + )); + }; + let Some(email) = user.email.as_deref().filter(|e| !e.is_empty()) else { + return Ok(left_behind( + "the session has no e-mail address to find the test user by", + )); + }; + match access { + TestUserCleanup::Keycloak { + base_url, + realm, + client_id, + client_secret, + } => { + let Some(secret) = client_secret else { + return Ok(left_behind("the Keycloak client secret is missing")); + }; + let client = KeycloakAdmin { + base: base_url.trim_end_matches('/'), + realm: &urlencoding::encode(realm), + client_id, + secret, + }; + client.delete_by_email(http, email).await } - Some(IdentityProvider::Custom) | None => { - // For custom/unknown providers, try Keycloak if configured, else skip - if config.keycloak_url.is_some() && config.keycloak_admin_username.is_some() { - cleanup_keycloak(user, config, http).await - } else { - warn!( - username = user.username.as_deref(), - "No identity provider configured for cleanup — skipping" - ); - Ok(false) - } + TestUserCleanup::Auth0 { + domain, + client_id, + client_secret, + } => { + let Some(secret) = client_secret else { + return Ok(left_behind("the Auth0 client secret is missing")); + }; + auth0_delete_by_email(http, domain, client_id, secret, email).await + } + TestUserCleanup::Okta { domain, api_token } => { + let Some(token) = api_token else { + return Ok(left_behind("the Okta API token is missing")); + }; + okta_delete_by_email(http, domain, token, email).await } } } -/// Delete a user from Keycloak via the Admin REST API. +fn left_behind(reason: &str) -> CleanupOutcome { + CleanupOutcome::LeftBehind(reason.to_string()) +} + +/// The accounts a search returned, narrowed to the one carrying `email`. +#[derive(Debug, PartialEq, Eq)] +enum Match { + One(String), + None, + Several, +} + +/// Pick the single account whose address is `email` (ignoring case, as +/// identity providers store it). A provider's search may match on a prefix or +/// a substring, so its answer alone is never trusted. /// -/// Flow: get admin token → search user by username → delete by ID. -async fn cleanup_keycloak( - user: &TestUserRecord, - config: &AgentConfig, - http: &reqwest::Client, -) -> Result { - let base_url = config - .keycloak_url - .as_deref() - .ok_or("KEYCLOAK_URL not configured")?; - let realm = config - .keycloak_realm - .as_deref() - .ok_or("KEYCLOAK_REALM not configured")?; - let admin_user = config - .keycloak_admin_username - .as_deref() - .ok_or("KEYCLOAK_ADMIN_USERNAME not configured")?; - let admin_pass = config - .keycloak_admin_password - .as_ref() - .ok_or("KEYCLOAK_ADMIN_PASSWORD not configured")?; - - let username = user - .username - .as_deref() - .ok_or("No username in test user record")?; - - info!(username, realm, "Cleaning up Keycloak test user"); - - // Step 1: Get admin access token - let token_url = format!("{base_url}/realms/master/protocol/openid-connect/token"); - let token_resp = http - .post(&token_url) - .form(&[ - ("grant_type", "password"), - ("client_id", "admin-cli"), - ("username", admin_user), - ("password", admin_pass.expose_secret()), - ]) - .send() - .await - .map_err(|e| format!("Keycloak token request failed: {e}"))?; - - if !token_resp.status().is_success() { - let status = token_resp.status(); - let body = token_resp.text().await.unwrap_or_default(); - return Err(format!("Keycloak admin auth failed ({status}): {body}")); - } - - let token_body: serde_json::Value = token_resp - .json() - .await - .map_err(|e| format!("Failed to parse Keycloak token: {e}"))?; - let access_token = token_body - .get("access_token") - .and_then(|v| v.as_str()) - .ok_or("No access_token in Keycloak response")?; - - // Step 2: Search for user by username - let search_url = - format!("{base_url}/admin/realms/{realm}/users?username={username}&exact=true"); - let search_resp = http - .get(&search_url) - .bearer_auth(access_token) - .send() - .await - .map_err(|e| format!("Keycloak user search failed: {e}"))?; - - if !search_resp.status().is_success() { - let status = search_resp.status(); - let body = search_resp.text().await.unwrap_or_default(); - return Err(format!("Keycloak user search failed ({status}): {body}")); - } - - let users: Vec = search_resp - .json() - .await - .map_err(|e| format!("Failed to parse Keycloak users: {e}"))?; - - let user_id = users - .first() - .and_then(|u| u.get("id")) - .and_then(|v| v.as_str()) - .ok_or_else(|| format!("User '{username}' not found in Keycloak realm '{realm}'"))?; - - // Step 3: Delete the user - let delete_url = format!("{base_url}/admin/realms/{realm}/users/{user_id}"); - let delete_resp = http - .delete(&delete_url) - .bearer_auth(access_token) - .send() - .await - .map_err(|e| format!("Keycloak user delete failed: {e}"))?; - - if delete_resp.status().is_success() || delete_resp.status().as_u16() == 204 { - info!(username, user_id, "Keycloak test user deleted"); - Ok(true) - } else { - let status = delete_resp.status(); - let body = delete_resp.text().await.unwrap_or_default(); - Err(format!("Keycloak delete failed ({status}): {body}")) +/// # Arguments +/// +/// * `accounts` - the search result +/// * `id_of` / `email_of` - where an account keeps its id and address +fn single_match( + accounts: &[Value], + email: &str, + id_of: fn(&Value) -> Option<&str>, + email_of: fn(&Value) -> Option<&str>, +) -> Match { + let mut ids = accounts + .iter() + .filter(|a| email_of(a).is_some_and(|e| e.eq_ignore_ascii_case(email))) + .filter_map(id_of); + match (ids.next(), ids.next()) { + (Some(id), None) => Match::One(id.to_string()), + (None, _) => Match::None, + (Some(_), Some(_)) => Match::Several, } } -/// Delete a user from Auth0 via the Management API. -/// -/// Requires `AUTH0_DOMAIN`, `AUTH0_CLIENT_ID`, `AUTH0_CLIENT_SECRET` env vars. -async fn cleanup_auth0( - user: &TestUserRecord, - _config: &AgentConfig, - http: &reqwest::Client, -) -> Result { - let domain = std::env::var("AUTH0_DOMAIN").map_err(|_| "AUTH0_DOMAIN not set")?; - let client_id = std::env::var("AUTH0_CLIENT_ID").map_err(|_| "AUTH0_CLIENT_ID not set")?; - let client_secret = - std::env::var("AUTH0_CLIENT_SECRET").map_err(|_| "AUTH0_CLIENT_SECRET not set")?; +/// The response, or an error naming `what` with its status and body. +async fn ok_or_error( + response: Result, + what: &str, +) -> Result { + let response = response.map_err(|e| format!("{what} failed: {e}"))?; + if response.status().is_success() { + return Ok(response); + } + let status = response.status(); + let body = response.text().await.unwrap_or_default(); + Err(format!("{what} failed ({status}): {body}")) +} - let email = user - .email - .as_deref() - .ok_or("No email in test user record for Auth0 lookup")?; - - info!(email, "Cleaning up Auth0 test user"); - - // Get management API token - let token_resp = http - .post(format!("https://{domain}/oauth/token")) - .json(&serde_json::json!({ - "grant_type": "client_credentials", - "client_id": client_id, - "client_secret": client_secret, - "audience": format!("https://{domain}/api/v2/"), - })) - .send() - .await - .map_err(|e| format!("Auth0 token request failed: {e}"))?; - - let token_body: serde_json::Value = token_resp +/// The JSON body of a successful response. +async fn json_of( + response: Result, + what: &str, +) -> Result { + ok_or_error(response, what) + .await? .json() .await - .map_err(|e| format!("Failed to parse Auth0 token: {e}"))?; - let access_token = token_body - .get("access_token") - .and_then(|v| v.as_str()) - .ok_or("No access_token in Auth0 response")?; + .map_err(|e| format!("{what}: unreadable answer: {e}")) +} - // Search for user by email - let encoded_email = urlencoding::encode(email); - let search_url = format!("https://{domain}/api/v2/users-by-email?email={encoded_email}"); - let search_resp = http - .get(&search_url) - .bearer_auth(access_token) - .send() - .await - .map_err(|e| format!("Auth0 user search failed: {e}"))?; +/// The `access_token` of a token response. +fn access_token(body: &Value, what: &str) -> Result { + body.get("access_token") + .and_then(Value::as_str) + .map(str::to_string) + .ok_or_else(|| format!("{what}: no access_token in the answer")) +} - let users: Vec = search_resp - .json() - .await - .map_err(|e| format!("Failed to parse Auth0 users: {e}"))?; +/// One Keycloak realm, through a client's service account. +struct KeycloakAdmin<'a> { + base: &'a str, + /// Already URL-encoded. + realm: &'a str, + client_id: &'a str, + secret: &'a str, +} - let user_id = users - .first() - .and_then(|u| u.get("user_id")) - .and_then(|v| v.as_str()) - .ok_or_else(|| format!("User with email '{email}' not found in Auth0"))?; +impl KeycloakAdmin<'_> { + async fn delete_by_email( + &self, + http: &reqwest::Client, + email: &str, + ) -> Result { + let Self { + base, + realm, + client_id, + secret, + } = self; + // The realm's own token endpoint: a token for this realm only. + let token = json_of( + http.post(format!( + "{base}/realms/{realm}/protocol/openid-connect/token" + )) + .form(&[ + ("grant_type", "client_credentials"), + ("client_id", client_id), + ("client_secret", secret), + ]) + .send() + .await, + "Keycloak token request", + ) + .await?; + let token = access_token(&token, "Keycloak token request")?; - // Delete - let encoded_id = urlencoding::encode(user_id); - let delete_resp = http - .delete(format!("https://{domain}/api/v2/users/{encoded_id}")) - .bearer_auth(access_token) - .send() - .await - .map_err(|e| format!("Auth0 user delete failed: {e}"))?; + let users = json_of( + http.get(format!( + "{base}/admin/realms/{realm}/users?email={}&exact=true", + urlencoding::encode(email) + )) + .bearer_auth(&token) + .send() + .await, + "Keycloak user search", + ) + .await?; + let accounts = users.as_array().map(Vec::as_slice).unwrap_or_default(); + let id = match single_match( + accounts, + email, + |a| a.get("id").and_then(Value::as_str), + |a| a.get("email").and_then(Value::as_str), + ) { + Match::One(id) => id, + Match::None => return Ok(CleanupOutcome::NotRegistered), + Match::Several => return Ok(several()), + }; - if delete_resp.status().is_success() || delete_resp.status().as_u16() == 204 { - info!(email, user_id, "Auth0 test user deleted"); - Ok(true) - } else { - let status = delete_resp.status(); - let body = delete_resp.text().await.unwrap_or_default(); - Err(format!("Auth0 delete failed ({status}): {body}")) + ok_or_error( + http.delete(format!( + "{base}/admin/realms/{realm}/users/{}", + urlencoding::encode(&id) + )) + .bearer_auth(&token) + .send() + .await, + "Keycloak user delete", + ) + .await?; + info!(user_id = %id, "Keycloak test user deleted"); + Ok(CleanupOutcome::Deleted) } } -/// Delete a user from Okta via the Users API. -/// -/// Requires `OKTA_DOMAIN`, `OKTA_API_TOKEN` env vars. -async fn cleanup_okta( - user: &TestUserRecord, - _config: &AgentConfig, +fn several() -> CleanupOutcome { + left_behind("several accounts carry the session's e-mail address; none was deleted") +} + +/// Delete the Auth0 user with `email` through the Management API. +async fn auth0_delete_by_email( http: &reqwest::Client, -) -> Result { - let domain = std::env::var("OKTA_DOMAIN").map_err(|_| "OKTA_DOMAIN not set")?; - let api_token = std::env::var("OKTA_API_TOKEN").map_err(|_| "OKTA_API_TOKEN not set")?; + domain: &str, + client_id: &str, + secret: &str, + email: &str, +) -> Result { + let token = json_of( + http.post(format!("https://{domain}/oauth/token")) + .json(&serde_json::json!({ + "grant_type": "client_credentials", + "client_id": client_id, + "client_secret": secret, + "audience": format!("https://{domain}/api/v2/"), + })) + .send() + .await, + "Auth0 token request", + ) + .await?; + let token = access_token(&token, "Auth0 token request")?; - let username = user - .username - .as_deref() - .or(user.email.as_deref()) - .ok_or("No username/email in test user record for Okta lookup")?; - - info!(username, "Cleaning up Okta test user"); - - // Search user - let encoded = urlencoding::encode(username); - let search_url = format!("https://{domain}/api/v1/users?search=profile.login+eq+\"{encoded}\""); - let search_resp = http - .get(&search_url) - .header("Authorization", format!("SSWS {api_token}")) - .send() - .await - .map_err(|e| format!("Okta user search failed: {e}"))?; - - let users: Vec = search_resp - .json() - .await - .map_err(|e| format!("Failed to parse Okta users: {e}"))?; - - let user_id = users - .first() - .and_then(|u| u.get("id")) - .and_then(|v| v.as_str()) - .ok_or_else(|| format!("User '{username}' not found in Okta"))?; - - // Deactivate first (required by Okta before delete) - let _ = http - .post(format!( - "https://{domain}/api/v1/users/{user_id}/lifecycle/deactivate" + let users = json_of( + http.get(format!( + "https://{domain}/api/v2/users-by-email?email={}", + urlencoding::encode(email) )) - .header("Authorization", format!("SSWS {api_token}")) + .bearer_auth(&token) .send() - .await; + .await, + "Auth0 user search", + ) + .await?; + let accounts = users.as_array().map(Vec::as_slice).unwrap_or_default(); + let id = match single_match( + accounts, + email, + |a| a.get("user_id").and_then(Value::as_str), + |a| a.get("email").and_then(Value::as_str), + ) { + Match::One(id) => id, + Match::None => return Ok(CleanupOutcome::NotRegistered), + Match::Several => return Ok(several()), + }; - // Delete - let delete_resp = http - .delete(format!("https://{domain}/api/v1/users/{user_id}")) - .header("Authorization", format!("SSWS {api_token}")) + ok_or_error( + http.delete(format!( + "https://{domain}/api/v2/users/{}", + urlencoding::encode(&id) + )) + .bearer_auth(&token) .send() - .await - .map_err(|e| format!("Okta user delete failed: {e}"))?; + .await, + "Auth0 user delete", + ) + .await?; + info!(user_id = %id, "Auth0 test user deleted"); + Ok(CleanupOutcome::Deleted) +} - if delete_resp.status().is_success() || delete_resp.status().as_u16() == 204 { - info!(username, user_id, "Okta test user deleted"); - Ok(true) - } else { - let status = delete_resp.status(); - let body = delete_resp.text().await.unwrap_or_default(); - Err(format!("Okta delete failed ({status}): {body}")) - } +/// Deactivate and delete the Okta user with `email` (Okta deletes only a +/// deactivated user). +async fn okta_delete_by_email( + http: &reqwest::Client, + domain: &str, + token: &str, + email: &str, +) -> Result { + let auth = format!("SSWS {token}"); + let search = format!("profile.email eq \"{email}\""); + let users = json_of( + http.get(format!( + "https://{domain}/api/v1/users?search={}", + urlencoding::encode(&search) + )) + .header("Authorization", &auth) + .send() + .await, + "Okta user search", + ) + .await?; + let accounts = users.as_array().map(Vec::as_slice).unwrap_or_default(); + let id = match single_match( + accounts, + email, + |a| a.get("id").and_then(Value::as_str), + |a| a.pointer("/profile/email").and_then(Value::as_str), + ) { + Match::One(id) => id, + Match::None => return Ok(CleanupOutcome::NotRegistered), + Match::Several => return Ok(several()), + }; + let user_url = format!("https://{domain}/api/v1/users/{}", urlencoding::encode(&id)); + + ok_or_error( + http.post(format!("{user_url}/lifecycle/deactivate")) + .header("Authorization", &auth) + .send() + .await, + "Okta user deactivate", + ) + .await?; + ok_or_error( + http.delete(&user_url) + .header("Authorization", &auth) + .send() + .await, + "Okta user delete", + ) + .await?; + info!(user_id = %id, "Okta test user deleted"); + Ok(CleanupOutcome::Deleted) } #[cfg(test)] +#[allow(clippy::expect_used, clippy::unwrap_used)] mod tests { - use super::*; - use compliance_core::models::pentest::{IdentityProvider, TestUserRecord}; - use secrecy::SecretString; + use std::sync::{Arc, Mutex}; - fn make_config_no_keycloak() -> AgentConfig { - // Dev defaults: no Keycloak, so `cleanup_test_user` takes the - // "identity provider not configured" path. - AgentConfig { - keycloak_url: None, - keycloak_realm: None, - keycloak_audience: None, + use axum::extract::{Path, Query, State}; + use axum::routing::{delete, get, post}; + use axum::{Form, Json, Router}; + use compliance_core::models::pentest::{AuthMode, IdentityProvider, PentestAuthConfig}; + use serde_json::json; + + use super::*; + + const EMAIL: &str = "pentest+6af8@mail.example.com"; + + fn user() -> TestUserRecord { + TestUserRecord { + email: Some(EMAIL.into()), + provider: Some(IdentityProvider::Keycloak), ..Default::default() } } - #[tokio::test] - async fn already_cleaned_up_returns_false() { - let user = TestUserRecord { - username: Some("test".into()), - email: None, - provider_user_id: None, - provider: Some(IdentityProvider::Keycloak), - cleaned_up: true, - }; - let config = make_config_no_keycloak(); - let http = reqwest::Client::new(); - let result = cleanup_test_user(&user, &config, &http).await; - assert_eq!(result, Ok(false)); + fn keycloak(base_url: &str) -> TestUserCleanup { + TestUserCleanup::Keycloak { + base_url: base_url.into(), + realm: "app".into(), + client_id: "cleanup".into(), + client_secret: Some("s3cret".into()), + } + } + + /// Every request a fake Keycloak saw, as `METHOD path`. + type Seen = Arc>>; + + /// A fake Keycloak with one realm `app` whose user search answers + /// `accounts`, recording every request. + async fn fake_keycloak(accounts: Value, seen: Seen) -> String { + type St = (Value, Seen); + async fn token( + State((_, seen)): State, + Path(realm): Path, + Form(form): Form>, + ) -> Json { + assert_eq!(form["grant_type"], "client_credentials"); + assert_eq!(form["client_id"], "cleanup"); + assert_eq!(form["client_secret"], "s3cret"); + seen.lock().unwrap().push(format!("POST token {realm}")); + Json(json!({ "access_token": "tok" })) + } + async fn search( + State((accounts, seen)): State, + Path(realm): Path, + Query(q): Query>, + ) -> Json { + seen.lock() + .unwrap() + .push(format!("GET users {realm} {}", q["email"])); + Json(accounts) + } + async fn remove(State((_, seen)): State, Path((realm, id)): Path<(String, String)>) { + seen.lock() + .unwrap() + .push(format!("DELETE users {realm} {id}")); + } + let app = Router::new() + .route("/realms/{realm}/protocol/openid-connect/token", post(token)) + .route("/admin/realms/{realm}/users", get(search)) + .route("/admin/realms/{realm}/users/{id}", delete(remove)) + .with_state((accounts, 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}") } #[tokio::test] - async fn firebase_returns_false_not_implemented() { - let user = TestUserRecord { - username: Some("test".into()), - email: None, - provider_user_id: None, - provider: Some(IdentityProvider::Firebase), - cleaned_up: false, - }; - let config = make_config_no_keycloak(); - let http = reqwest::Client::new(); - let result = cleanup_test_user(&user, &config, &http).await; - assert_eq!(result, Ok(false)); + async fn without_access_to_the_targets_provider_nothing_is_asked() { + let outcome = cleanup_test_user(&user(), None, &reqwest::Client::new()) + .await + .unwrap(); + assert!(matches!(outcome, CleanupOutcome::LeftBehind(r) if r.contains("no admin access"))); } #[tokio::test] - async fn no_provider_no_keycloak_skips() { - let user = TestUserRecord { - username: Some("test".into()), - email: None, - provider_user_id: None, - provider: None, - cleaned_up: false, - }; - let config = make_config_no_keycloak(); - let http = reqwest::Client::new(); - let result = cleanup_test_user(&user, &config, &http).await; - assert_eq!(result, Ok(false)); + async fn deletes_the_one_account_with_the_sessions_address_in_the_given_realm() { + let seen: Seen = Arc::default(); + let accounts = json!([ + { "id": "u-other", "email": "pentest@mail.example.com" }, + { "id": "u-test", "email": "Pentest+6af8@mail.example.com" }, + ]); + let base = fake_keycloak(accounts, seen.clone()).await; + + let outcome = cleanup_test_user(&user(), Some(&keycloak(&base)), &reqwest::Client::new()) + .await + .unwrap(); + + assert_eq!(outcome, CleanupOutcome::Deleted); + assert_eq!( + *seen.lock().unwrap(), + [ + "POST token app".to_string(), + format!("GET users app {EMAIL}"), + "DELETE users app u-test".to_string(), + ] + ); } #[tokio::test] - async fn custom_provider_no_keycloak_skips() { - let user = TestUserRecord { - username: Some("test".into()), - email: None, - provider_user_id: None, - provider: Some(IdentityProvider::Custom), - cleaned_up: false, - }; - let config = make_config_no_keycloak(); - let http = reqwest::Client::new(); - let result = cleanup_test_user(&user, &config, &http).await; - assert_eq!(result, Ok(false)); + async fn several_accounts_with_the_address_are_left_alone() { + let seen: Seen = Arc::default(); + let accounts = json!([ + { "id": "a", "email": EMAIL }, + { "id": "b", "email": EMAIL }, + ]); + let base = fake_keycloak(accounts, seen.clone()).await; + + let outcome = cleanup_test_user(&user(), Some(&keycloak(&base)), &reqwest::Client::new()) + .await + .unwrap(); + + assert!(matches!(outcome, CleanupOutcome::LeftBehind(r) if r.contains("several"))); + assert!(seen + .lock() + .unwrap() + .iter() + .all(|r| !r.starts_with("DELETE"))); } #[tokio::test] - async fn keycloak_missing_config_returns_error() { - let user = TestUserRecord { - username: Some("test".into()), - email: None, - provider_user_id: None, - provider: Some(IdentityProvider::Keycloak), - cleaned_up: false, - }; - let config = make_config_no_keycloak(); - let http = reqwest::Client::new(); - let result = cleanup_test_user(&user, &config, &http).await; - assert!(result.is_err()); - assert!(result - .as_ref() - .err() - .is_some_and(|e| e.contains("KEYCLOAK_URL"))); + async fn a_search_that_only_resembles_the_address_deletes_nothing() { + let seen: Seen = Arc::default(); + let accounts = json!([{ "id": "real", "email": "pentest+6af8@mail.example.com.evil" }]); + let base = fake_keycloak(accounts, seen.clone()).await; + + let outcome = cleanup_test_user(&user(), Some(&keycloak(&base)), &reqwest::Client::new()) + .await + .unwrap(); + + assert_eq!(outcome, CleanupOutcome::NotRegistered); + assert!(seen + .lock() + .unwrap() + .iter() + .all(|r| !r.starts_with("DELETE"))); } #[tokio::test] - async fn keycloak_missing_username_returns_error() { - let user = TestUserRecord { - username: None, - email: Some("test@example.com".into()), - provider_user_id: None, - provider: Some(IdentityProvider::Keycloak), - cleaned_up: false, - }; - let mut config = make_config_no_keycloak(); - config.keycloak_url = Some("http://localhost:8080".into()); - config.keycloak_realm = Some("test".into()); - config.keycloak_admin_username = Some("admin".into()); - config.keycloak_admin_password = Some(SecretString::from("pass".to_string())); - let http = reqwest::Client::new(); - let result = cleanup_test_user(&user, &config, &http).await; - assert!(result.is_err()); - assert!(result - .as_ref() - .err() - .is_some_and(|e| e.contains("username"))); + async fn a_user_already_deleted_is_not_asked_for_again() { + let mut done = user(); + done.cleaned_up = true; + // An unreachable base URL: any request would fail the test. + let outcome = cleanup_test_user( + &done, + Some(&keycloak("http://127.0.0.1:1")), + &reqwest::Client::new(), + ) + .await + .unwrap(); + assert_eq!(outcome, CleanupOutcome::Deleted); } #[tokio::test] - async fn auth0_missing_env_returns_error() { - let user = TestUserRecord { - username: None, - email: Some("test@example.com".into()), - provider_user_id: None, - provider: Some(IdentityProvider::Auth0), - cleaned_up: false, + async fn a_missing_secret_or_address_leaves_the_user_behind() { + let no_secret = TestUserCleanup::Okta { + domain: "example.okta.com".into(), + api_token: None, }; - let config = make_config_no_keycloak(); - let http = reqwest::Client::new(); - let result = cleanup_test_user(&user, &config, &http).await; - assert!(result.is_err()); - assert!(result - .as_ref() - .err() - .is_some_and(|e| e.contains("AUTH0_DOMAIN"))); + let outcome = cleanup_test_user(&user(), Some(&no_secret), &reqwest::Client::new()) + .await + .unwrap(); + assert!(matches!(outcome, CleanupOutcome::LeftBehind(r) if r.contains("token"))); + + let no_email = TestUserRecord::default(); + let outcome = cleanup_test_user( + &no_email, + Some(&keycloak("http://127.0.0.1:1")), + &reqwest::Client::new(), + ) + .await + .unwrap(); + assert!(matches!(outcome, CleanupOutcome::LeftBehind(r) if r.contains("e-mail"))); } - #[tokio::test] - async fn okta_missing_env_returns_error() { - let user = TestUserRecord { - username: Some("test".into()), - email: None, - provider_user_id: None, - provider: Some(IdentityProvider::Okta), - cleaned_up: false, - }; - let config = make_config_no_keycloak(); - let http = reqwest::Client::new(); - let result = cleanup_test_user(&user, &config, &http).await; - assert!(result.is_err()); - assert!(result - .as_ref() - .err() - .is_some_and(|e| e.contains("OKTA_DOMAIN"))); + #[test] + fn single_match_reads_nested_addresses() { + let accounts = vec![json!({ "id": "o1", "profile": { "email": EMAIL } })]; + let found = single_match( + &accounts, + EMAIL, + |a| a.get("id").and_then(Value::as_str), + |a| a.pointer("/profile/email").and_then(Value::as_str), + ); + assert_eq!(found, Match::One("o1".into())); + } + + fn config(mode: AuthMode, email: Option<&str>) -> PentestConfig { + serde_json::from_value(json!({ "app_url": "https://app.example.com" })) + .map(|mut c: PentestConfig| { + c.auth = PentestAuthConfig { + mode, + verification_email: email.map(str::to_string), + cleanup: Some(keycloak("https://login.example.com")), + ..Default::default() + }; + c + }) + .unwrap() + } + + #[test] + fn the_planned_test_user_carries_the_sessions_own_address() { + let planned = planned_test_user( + &config(AuthMode::AutoRegister, Some("pentest@mail.example.com")), + "6af8", + ) + .unwrap(); + assert_eq!(planned.email.as_deref(), Some(EMAIL)); + assert_eq!(planned.provider, Some(IdentityProvider::Keycloak)); + assert!(!planned.cleaned_up); + + assert!(planned_test_user(&config(AuthMode::Manual, Some("a@b.c")), "6af8").is_none()); + assert!(planned_test_user(&config(AuthMode::AutoRegister, None), "6af8").is_none()); } } diff --git a/compliance-agent/src/pentest/orchestrator.rs b/compliance-agent/src/pentest/orchestrator.rs index 86b4cac..ff510ac 100644 --- a/compliance-agent/src/pentest/orchestrator.rs +++ b/compliance-agent/src/pentest/orchestrator.rs @@ -14,6 +14,7 @@ use crate::database::Database; use crate::llm::{ ChatMessage, LlmClient, LlmResponse, ToolCallRequest, ToolCallRequestFunction, ToolDefinition, }; +use crate::pentest::cleanup::CleanupOutcome; /// Maximum duration for a single pentest session before timeout const SESSION_TIMEOUT: Duration = Duration::from_secs(30 * 60); // 30 minutes @@ -24,6 +25,8 @@ pub struct PentestOrchestrator { pub(crate) db: Database, pub(crate) event_tx: broadcast::Sender, pub(crate) pause_rx: Option>, + /// Outbound policy for tenant-chosen URLs, the test-user cleanup's too. + pub(crate) net_guard: NetGuard, } impl PentestOrchestrator { @@ -42,6 +45,55 @@ impl PentestOrchestrator { db, event_tx, pause_rx, + net_guard, + } + } + + /// Delete the session's test user with the access given for the target's + /// identity provider, and record on the session what became of it. + async fn clean_up_test_user( + &self, + session_id: Option, + test_user: &TestUserRecord, + access: Option<&TestUserCleanup>, + ) { + let outcome = match compliance_core::guarded_net::guarded_client_builder(self.net_guard) + .timeout(std::time::Duration::from_secs(30)) + .build() + { + Ok(http) => crate::pentest::cleanup::cleanup_test_user(test_user, access, &http).await, + Err(e) => Err(format!("no HTTP client: {e}")), + }; + let left_behind = match outcome { + Ok(CleanupOutcome::Deleted) | Ok(CleanupOutcome::NotRegistered) => None, + Ok(CleanupOutcome::LeftBehind(reason)) => Some(reason), + Err(e) => Some(format!("cleanup failed: {e}")), + }; + match &left_behind { + None => tracing::info!("Pentest test user deleted"), + Some(reason) => { + tracing::warn!(reason = %reason, "Pentest test user left behind"); + let _ = self.event_tx.send(PentestEvent::Message { + content: format!( + "The test user {} is still registered with the application ({reason}); \ + delete it by hand.", + test_user.email.as_deref().unwrap_or("(unknown)") + ), + }); + } + } + if let Some(sid) = session_id { + let _ = self + .db + .pentest_sessions() + .update_one( + doc! { "_id": sid }, + doc! { "$set": { + "test_user.cleaned_up": left_behind.is_none(), + "test_user.left_behind": left_behind, + } }, + ) + .await; } } @@ -499,55 +551,12 @@ impl PentestOrchestrator { .await; } - // Clean up test user via identity provider API if requested - if session - .config - .as_ref() - .is_some_and(|c| c.auth.cleanup_test_user) + // Delete the test user in the target's identity provider if asked. + if let (Some(cfg), Some(test_user)) = (session.config.as_ref(), session.test_user.as_ref()) { - if let Some(ref test_user) = session.test_user { - let http = reqwest::Client::new(); - // We need the AgentConfig — read from env since orchestrator doesn't hold it - let config = crate::config::load_config(); - match config { - Ok(cfg) => { - match crate::pentest::cleanup::cleanup_test_user(test_user, &cfg, &http) - .await - { - Ok(true) => { - tracing::info!( - username = test_user.username.as_deref(), - "Test user cleaned up via provider API" - ); - // Mark as cleaned up in DB - if let Some(sid) = session.id { - let _ = self - .db - .pentest_sessions() - .update_one( - doc! { "_id": sid }, - doc! { "$set": { "test_user.cleaned_up": true } }, - ) - .await; - } - } - Ok(false) => { - tracing::info!( - "Test user cleanup skipped (no provider configured)" - ); - } - Err(e) => { - tracing::warn!(error = %e, "Test user cleanup failed"); - let _ = self.event_tx.send(PentestEvent::Error { - message: format!("Test user cleanup failed: {e}"), - }); - } - } - } - Err(e) => { - tracing::warn!(error = %e, "Could not load config for cleanup"); - } - } + if cfg.auth.cleanup_test_user { + self.clean_up_test_user(session.id, test_user, cfg.auth.cleanup.as_ref()) + .await; } } diff --git a/compliance-agent/src/pentest/prompt_builder.rs b/compliance-agent/src/pentest/prompt_builder.rs index d6b3d2d..ba7aae3 100644 --- a/compliance-agent/src/pentest/prompt_builder.rs +++ b/compliance-agent/src/pentest/prompt_builder.rs @@ -6,7 +6,8 @@ use compliance_core::models::sbom::SbomEntry; use super::orchestrator::PentestOrchestrator; /// Build additional prompt sections from PentestConfig when present. -fn build_config_sections(config: &PentestConfig) -> String { +/// `test_email` is the address an auto-register session registers with. +fn build_config_sections(config: &PentestConfig, test_email: Option<&str>) -> String { let mut sections = String::new(); // Authentication section @@ -35,13 +36,11 @@ fn build_config_sections(config: &PentestConfig) -> String { "- **Registration URL**: Not provided — use Playwright to discover the registration page.\n", ); } - if let Some(ref email) = config.auth.verification_email { + if let Some(email) = test_email { sections.push_str(&format!( - "- **Verification Email**: Use plus-addressing from `{email}` \ - (e.g. `{base}+{{session_id}}@{domain}`) for email verification. \ - The system will poll the IMAP mailbox for verification links.\n", - base = email.split('@').next().unwrap_or(email), - domain = email.split('@').nth(1).unwrap_or("example.com"), + "- **E-mail address**: Register with exactly `{email}` (no other \ + address): the system polls its mailbox for verification links and \ + finds the test account by it afterwards.\n", )); } sections.push_str( @@ -245,7 +244,10 @@ impl PentestOrchestrator { let config_sections = session .config .as_ref() - .map(build_config_sections) + .map(|c| { + let test_email = session.test_user.as_ref().and_then(|u| u.email.as_deref()); + build_config_sections(c, test_email) + }) .unwrap_or_default(); format!( diff --git a/compliance-agent/src/pentest/report/html/scope.rs b/compliance-agent/src/pentest/report/html/scope.rs index 598a43c..cede99b 100644 --- a/compliance-agent/src/pentest/report/html/scope.rs +++ b/compliance-agent/src/pentest/report/html/scope.rs @@ -1,5 +1,5 @@ use super::{html_escape, tool_category}; -use compliance_core::models::pentest::{AuthMode, PentestConfig, PentestSession}; +use compliance_core::models::pentest::{AuthMode, PentestConfig, PentestSession, TestUserRecord}; pub(super) fn scope( session: &PentestSession, @@ -43,6 +43,9 @@ pub(super) fn scope( AuthMode::AutoRegister => "Auto-register", }; rows.push_str(&format!("Auth Mode{auth_mode}")); + if let Some(user) = &session.test_user { + rows.push_str(&test_user_row(user)); + } if !cfg.scope_exclusions.is_empty() { let excl = cfg .scope_exclusions @@ -125,3 +128,47 @@ pub(super) fn scope( success_rate = session.success_rate(), ) } + +/// The report row for the session's test user: deleted, or still registered +/// with the application and to be deleted by hand. +fn test_user_row(user: &TestUserRecord) -> String { + let email = html_escape(user.email.as_deref().unwrap_or("(unknown)")); + let state = match (&user.left_behind, user.cleaned_up) { + (Some(reason), _) => format!( + "Left behind: still registered with the application, \ + delete it by hand ({})", + html_escape(reason) + ), + (None, true) => "Deleted after the test".to_string(), + (None, false) => "Not deleted (cleanup was not requested)".to_string(), + }; + format!("Test User{email} — {state}") +} + +#[cfg(test)] +mod test_user_tests { + use super::*; + + #[test] + fn a_left_behind_test_user_is_named_with_its_reason() { + let user = TestUserRecord { + email: Some("pentest+1@mail.example.com".into()), + left_behind: Some("no admin access ".into()), + ..Default::default() + }; + let row = test_user_row(&user); + assert!(row.contains("pentest+1@mail.example.com")); + assert!(row.contains("Left behind")); + assert!(row.contains("no admin access <given>")); + } + + #[test] + fn a_deleted_test_user_says_so() { + let user = TestUserRecord { + email: Some("pentest+1@mail.example.com".into()), + cleaned_up: true, + ..Default::default() + }; + assert!(test_user_row(&user).contains("Deleted after the test")); + } +} diff --git a/compliance-core/src/config.rs b/compliance-core/src/config.rs index 530bd77..527f52c 100644 --- a/compliance-core/src/config.rs +++ b/compliance-core/src/config.rs @@ -39,8 +39,6 @@ pub struct AgentConfig { pub artifact_store_base_path: String, pub keycloak_url: Option, pub keycloak_realm: Option, - pub keycloak_admin_username: Option, - pub keycloak_admin_password: Option, // Pentest defaults pub pentest_verification_email: Option, pub pentest_imap_host: Option, @@ -349,8 +347,6 @@ impl Default for AgentConfig { artifact_store_base_path: "/data/compliance-scanner/artifacts".to_string(), 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, diff --git a/compliance-core/src/models/credentials.rs b/compliance-core/src/models/credentials.rs index 67d0267..7f48f68 100644 --- a/compliance-core/src/models/credentials.rs +++ b/compliance-core/src/models/credentials.rs @@ -10,7 +10,7 @@ use super::dast::{DastAuthConfig, DastTarget}; use super::onboarding::{ Artifact, ArtifactAuth, IssueTrackerConfig, OnboardedTarget, TargetScanConfig, }; -use super::pentest::{PentestAuthConfig, PentestConfig, PentestSession}; +use super::pentest::{PentestAuthConfig, PentestConfig, PentestSession, TestUserCleanup}; /// A record that carries stored credentials. pub trait Credentials { @@ -88,7 +88,20 @@ impl Credentials for IssueTrackerConfig { impl Credentials for PentestAuthConfig { fn credentials_mut(&mut self) -> Vec<&mut Option> { - vec![&mut self.password, &mut self.imap_password] + let mut slots = vec![&mut self.password, &mut self.imap_password]; + slots.extend(self.cleanup.credentials_mut()); + slots + } +} + +impl Credentials for TestUserCleanup { + fn credentials_mut(&mut self) -> Vec<&mut Option> { + match self { + Self::Keycloak { client_secret, .. } | Self::Auth0 { client_secret, .. } => { + vec![client_secret] + } + Self::Okta { api_token, .. } => vec![api_token], + } } } @@ -218,6 +231,12 @@ mod tests { username: Some("tester".into()), password: Some("pw".into()), imap_password: Some("imap".into()), + cleanup: Some(TestUserCleanup::Keycloak { + base_url: "https://login.example.com".into(), + realm: "app".into(), + client_id: "cleanup".into(), + client_secret: Some("kc-secret".into()), + }), ..Default::default() }, custom_headers: HashMap::new(), @@ -239,5 +258,14 @@ mod tests { assert_eq!(auth.username.as_deref(), Some("tester")); assert_eq!(auth.password, None); assert_eq!(auth.imap_password, None); + assert_eq!( + auth.cleanup, + Some(TestUserCleanup::Keycloak { + base_url: "https://login.example.com".into(), + realm: "app".into(), + client_id: "cleanup".into(), + client_secret: None, + }) + ); } } diff --git a/compliance-core/src/models/pentest.rs b/compliance-core/src/models/pentest.rs index 0379033..98a17f4 100644 --- a/compliance-core/src/models/pentest.rs +++ b/compliance-core/src/models/pentest.rs @@ -110,6 +110,66 @@ pub struct PentestAuthConfig { pub imap_password: Option, #[serde(default)] pub cleanup_test_user: bool, + /// Admin access to the target's own identity provider, given for this + /// session, so the test user can be deleted afterwards. Without it the + /// test user is left behind and the report says so: the agent never uses + /// its own identity provider for this. + #[serde(default)] + pub cleanup: Option, +} + +/// Where and how the test user of an auto-register session is deleted: the +/// target's identity provider, with credentials given for the session. +/// +/// The user is looked up by the session's own e-mail address +/// (`base+{session_id}@domain`), which no real account carries. +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] +#[serde(tag = "provider", rename_all = "snake_case")] +pub enum TestUserCleanup { + /// A Keycloak realm, through a confidential client whose service account + /// may manage that realm's users (`realm-management: manage-users`). + Keycloak { + /// Keycloak's base URL, e.g. `https://login.example.com`. + base_url: String, + /// The realm the test user registered in. + realm: String, + client_id: String, + client_secret: Option, + }, + /// An Auth0 tenant, through a machine-to-machine application with the + /// Management API scopes `read:users` and `delete:users`. + Auth0 { + /// The tenant's domain, e.g. `example.eu.auth0.com`. + domain: String, + client_id: String, + client_secret: Option, + }, + /// An Okta org, through an API token allowed to manage users. + Okta { + /// The org's domain, e.g. `example.okta.com`. + domain: String, + api_token: Option, + }, +} + +impl TestUserCleanup { + /// The identity provider this cleanup acts on. + pub fn provider(&self) -> IdentityProvider { + match self { + Self::Keycloak { .. } => IdentityProvider::Keycloak, + Self::Auth0 { .. } => IdentityProvider::Auth0, + Self::Okta { .. } => IdentityProvider::Okta, + } + } + + /// The URL the cleanup talks to, for the outbound check before a session + /// starts. + pub fn base_url(&self) -> String { + match self { + Self::Keycloak { base_url, .. } => base_url.trim_end_matches('/').to_string(), + Self::Auth0 { domain, .. } | Self::Okta { domain, .. } => format!("https://{domain}"), + } + } } /// Full wizard configuration for a pentest session @@ -150,7 +210,8 @@ pub struct PentestConfig { pub skip_mode: bool, } -/// Identity provider type for cleanup routing +/// The identity provider that holds a test user. `Firebase` and `Custom` +/// remain so older session records still read; neither is cleaned up. #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] #[serde(rename_all = "snake_case")] pub enum IdentityProvider { @@ -176,6 +237,10 @@ pub struct TestUserRecord { /// Whether cleanup has been completed #[serde(default)] pub cleaned_up: bool, + /// Why the test user was not deleted, when cleanup was asked for: it is + /// still in the target's identity provider and has to go by hand. + #[serde(default)] + pub left_behind: Option, } /// A pentest session initiated via the chat interface diff --git a/compliance-core/tests/models.rs b/compliance-core/tests/models.rs index b13679b..01fe8e3 100644 --- a/compliance-core/tests/models.rs +++ b/compliance-core/tests/models.rs @@ -466,6 +466,7 @@ fn pentest_config_serde_roundtrip() { imap_username: None, imap_password: None, cleanup_test_user: true, + cleanup: None, }, custom_headers: [("X-Token".to_string(), "abc".to_string())] .into_iter() @@ -525,6 +526,7 @@ fn test_user_record_serde_roundtrip() { provider_user_id: Some("kc-uuid-123".into()), provider: Some(pentest::IdentityProvider::Keycloak), cleaned_up: false, + left_behind: None, }; let json = serde_json::to_string(&r).unwrap(); let back: pentest::TestUserRecord = serde_json::from_str(&json).unwrap(); @@ -559,6 +561,7 @@ fn pentest_session_with_test_user() { provider_user_id: None, provider: Some(pentest::IdentityProvider::Auth0), cleaned_up: false, + left_behind: None, }); let bson_doc = bson::to_document(&s).unwrap(); let back: pentest::PentestSession = bson::from_document(bson_doc).unwrap(); @@ -605,3 +608,34 @@ fn opt_bson_datetime_roundtrip_with_some() { let back: pentest::PentestSession = bson::from_document(bson_doc).unwrap(); assert!(back.completed_at.is_some()); } + +#[test] +fn test_user_cleanup_is_tagged_by_provider() { + let access: pentest::TestUserCleanup = serde_json::from_value(serde_json::json!({ + "provider": "keycloak", + "base_url": "https://login.example.com/", + "realm": "app", + "client_id": "cleanup", + "client_secret": "s" + })) + .unwrap(); + assert_eq!(access.provider(), pentest::IdentityProvider::Keycloak); + assert_eq!(access.base_url(), "https://login.example.com"); + + let okta: pentest::TestUserCleanup = serde_json::from_value(serde_json::json!({ + "provider": "okta", "domain": "example.okta.com", "api_token": "t" + })) + .unwrap(); + assert_eq!(okta.base_url(), "https://example.okta.com"); +} + +#[test] +fn an_older_test_user_record_still_reads() { + let back: pentest::TestUserRecord = serde_json::from_value(serde_json::json!({ + "username": null, "email": "a+1@b.c", "provider_user_id": null, + "provider": "firebase", "cleaned_up": false + })) + .unwrap(); + assert_eq!(back.left_behind, None); + assert_eq!(back.provider, Some(pentest::IdentityProvider::Firebase)); +} diff --git a/docs/features/pentest.md b/docs/features/pentest.md index 2055030..e8eb090 100644 --- a/docs/features/pentest.md +++ b/docs/features/pentest.md @@ -32,6 +32,7 @@ Click **New Pentest** on the dashboard to open the 4-step onboarding wizard: - **Registration URL** (optional) — auto-discovered via Playwright if omitted - **Verification Email** (optional) — override the agent's default mailbox. Uses plus-addressing (`base+sessionid@domain`) and polls IMAP for verification links - **IMAP Settings** — collapsible section to override host/port/credentials + - **Delete the test user afterwards** — deletes the account in the application's own identity provider when the session ends. It needs admin access to that provider, given for the session through the API (`config.auth.cleanup`): a Keycloak realm (a client whose service account may manage users), an Auth0 tenant (a machine-to-machine application with `read:users` and `delete:users`) or an Okta org (an API token). The account is found by the session's own address and deleted only if exactly one account carries it. Without that access, or if the provider refuses, the report lists the test user as **left behind**, to be deleted by hand. Prüfwerk never uses its own login service for this. ### Step 3 — Strategy & Instructions diff --git a/docs/reference/tools.md b/docs/reference/tools.md index ed59a95..c98e3e1 100644 --- a/docs/reference/tools.md +++ b/docs/reference/tools.md @@ -417,6 +417,7 @@ Every connection the agent opens, in one place. **Guarded** means: the HTTP clie | Git remotes (clone, fetch, submodules, linked artifacts) | `pipeline/git.rs`, `ingest/` | `check_git_url` and the resolved address before every clone and fetch; redirects off | | Gitea API of a git source or tracker (managed Git) | `git_source/gitea.rs`, `trackers/gitea.rs` | guarded | | DAST and pentest targets | `api/handlers/dast.rs`, `pentest/orchestrator.rs`, `compliance-dast` | base URL checked with `check_url`; the DAST tools share a guarded client | +| The target's identity provider, for deleting a pentest test user (Keycloak, Auth0, Okta; given per session) | `pentest/cleanup.rs` | URL checked with `check_url` when the session is created; guarded client | ### Operator-configured services (not guarded) @@ -428,7 +429,6 @@ These are set by the operator in the agent's environment, not by a tenant, and o | Tenant registry (entitlements, projects) | `registry.rs` | `TENANT_REGISTRY_URL` | | breakpilot-compliance OSCAL catalog | `controls/oscal_provider.rs` | `BREAKPILOT_BASE_URL` | | GitLab and Jira issue trackers | `trackers/gitlab.rs`, `trackers/jira.rs` | `GITLAB_URL`, `JIRA_URL` | -| Identity providers for pentest test-user cleanup (Keycloak, Auth0, Okta) | `pentest/cleanup.rs` | `KEYCLOAK_URL`, `AUTH0_DOMAIN`, `OKTA_DOMAIN` | | Headless Chrome for PDF reports | `pentest/report/pdf.rs` | `CHROME_WS_URL` | | MongoDB | `database.rs` | `MONGODB_URI` | | ClamAV service (clamd, plain TCP; the tree's files are streamed to it) | `pipeline/clamav.rs` | `CLAMD_ADDRESS` | -- 2.54.1