Files
pruefwerk/compliance-dashboard/src/infrastructure/agent_client.rs
T
Sharang ParnerkarandClaude Opus 5.5 4d3035a8c7
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 / Check (pull_request) Successful in 7m6s
feat(support): BreakPilot support can open any tenant, attributed and audited
Staff with the realm role BREAKPILOT_ADMIN or SUPPORT_ENGINEER (company
sign-in) can open any customer tenant in the dashboard without being
invited, as the AVV allows.

- Agent: a support token names the tenant in X-Pruefwerk-Tenant (UUID
  only; ignored for every other token, so customers cannot switch). The
  context stays read-only until the registry confirms the tenant, which
  also sets its slug and ladder status: archived and halted tenants stay
  closed. Without a registry there is no support access.
- Support without a chosen tenant gets 428 tenant_not_selected on
  tenant routes, not a 401, so the dashboard never loops to the login.
- Every support change, refused ones included, goes to the registry's
  audit log (method, path, status; never the body). Opening a tenant is
  logged through POST /api/v1/support/session.
- Status history records a display name and a support flag: the customer
  reads "BreakPilot-Support (name)"; everyone else's changes now show a
  name instead of a user id. Manual findings name their reporter.
- Scans support starts run as ScanTrigger::Support and are not counted
  as the customer's usage.
- Dashboard: support lands on a searchable tenant picker; a banner shows
  while a tenant is open, with "Mandant wechseln".

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EYKjxacrr6K88DruUmP48p
2026-09-29 09:29:20 +02:00

395 lines
14 KiB
Rust

//! Authenticated HTTP client for talking to the compliance-agent.
//!
//! Every dashboard server function that hits `comp-dev.breakpilot.com/api/v1/*`
//! must go through here so the Keycloak access token from the user's
//! session is attached as `Authorization: Bearer <token>`. Without it
//! the agent's M7.1 `require_jwt_auth` middleware rejects with 401
//! "Missing authorization header".
//!
//! When Keycloak is not configured (dev convenience), the helper
//! returns an unauthenticated builder — matching the agent's
//! pass-through behavior in the same state.
//!
//! **Token refresh**: KC access tokens are short-lived (5 min default
//! in the certifai realm). Before attaching, we decode the JWT's `exp`
//! claim and proactively refresh via the stored refresh_token if the
//! access token is expired or about to expire. The session is updated
//! with the new pair. If refresh fails, we send the (stale) token
//! anyway — the agent's 401 will surface to the UI, which can prompt
//! re-login.
use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine};
use dioxus::prelude::ServerFnError;
use dioxus_fullstack::FullstackContext;
use reqwest::Method;
use super::auth::LOGGED_IN_USER_SESS_KEY;
use super::server_state::ServerState;
use super::user_state::UserStateInner;
/// Seconds before the JWT's `exp` time at which we consider it stale
/// enough to refresh. Covers clock skew + the round-trip to the agent
/// so the token doesn't expire mid-flight.
const REFRESH_SKEW_SECS: i64 = 30;
/// Build a `RequestBuilder` for `<agent_api_url><path>` with the
/// session's access token attached. `path` should include a leading
/// `/`, e.g. `"/api/v1/repositories"`.
pub async fn agent_request(
method: Method,
path: &str,
) -> Result<reqwest::RequestBuilder, ServerFnError> {
let state: ServerState = FullstackContext::extract().await?;
let url = format!("{}{}", state.agent_api_url, path);
let mut req = reqwest::Client::new().request(method, &url);
req = attach_token(req, &state).await?;
Ok(req)
}
/// Parse an agent response as JSON. A non-2xx status becomes an error that
/// carries the agent's own `error` message (or the status text), so the user
/// reads why a request was refused instead of a JSON parse error.
///
/// # Errors
///
/// The refusal for a non-2xx status, or the parse error for a malformed body.
pub async fn json_or_error<T: serde::de::DeserializeOwned>(
resp: reqwest::Response,
) -> Result<T, ServerFnError> {
let status = resp.status();
if !status.is_success() {
let body = resp.text().await.unwrap_or_default();
return Err(ServerFnError::new(refusal_message(status, &body)));
}
resp.json()
.await
.map_err(|e| ServerFnError::new(e.to_string()))
}
/// The response itself when the agent accepted the request, else the refusal
/// (as for [`json_or_error`]); for a body the caller streams on.
///
/// # Errors
///
/// The refusal for a non-2xx status.
pub async fn ok_response(resp: reqwest::Response) -> Result<reqwest::Response, ServerFnError> {
let status = resp.status();
if status.is_success() {
return Ok(resp);
}
let body = resp.text().await.unwrap_or_default();
Err(ServerFnError::new(refusal_message(status, &body)))
}
/// Check an agent response whose body the caller does not need.
///
/// # Errors
///
/// The refusal for a non-2xx status, as for [`json_or_error`].
pub async fn ok_or_error(resp: reqwest::Response) -> Result<(), ServerFnError> {
let status = resp.status();
if status.is_success() {
return Ok(());
}
let body = resp.text().await.unwrap_or_default();
Err(ServerFnError::new(refusal_message(status, &body)))
}
/// The message for a refused request: the agent's `error` field when it sent
/// one, else the status text, with the status code.
fn refusal_message(status: reqwest::StatusCode, body: &str) -> String {
let message = serde_json::from_str::<serde_json::Value>(body)
.ok()
.and_then(|v| v.get("error").and_then(|e| e.as_str()).map(String::from))
.filter(|m| !m.trim().is_empty())
.unwrap_or_else(|| {
status
.canonical_reason()
.unwrap_or("request failed")
.to_string()
});
format!("{message} ({})", status.as_u16())
}
/// Same as [`agent_request`] but for `GET`. Convenience for the common case.
pub async fn agent_get(path: &str) -> Result<reqwest::RequestBuilder, ServerFnError> {
agent_request(Method::GET, path).await
}
/// One refresh at a time per session: the requests a page makes at once
/// would otherwise all refresh with the same refresh token, and Keycloak,
/// which rotates it, rejects every one after the first (`invalid_grant`).
static REFRESH_LOCKS: std::sync::LazyLock<
std::sync::Mutex<std::collections::HashMap<String, std::sync::Arc<tokio::sync::Mutex<()>>>>,
> = std::sync::LazyLock::new(Default::default);
/// The refresh lock of the session `key`, dropping locks no request holds.
fn refresh_lock(key: &str) -> std::sync::Arc<tokio::sync::Mutex<()>> {
let mut locks = REFRESH_LOCKS
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
locks.retain(|k, lock| k == key || std::sync::Arc::strong_count(lock) > 1);
locks.entry(key.to_string()).or_default().clone()
}
/// The signed-in user with an access token that is still valid, refreshing
/// it when it is about to expire. `Ok(None)` when no one is signed in, or when
/// Keycloak refused the refresh: the sign-in has run out, and the session's
/// user is removed so the next check sends the browser to the login.
///
/// # Errors
///
/// The session could not be read.
pub(crate) async fn current_user(
state: &ServerState,
session: &tower_sessions::Session,
) -> Result<Option<UserStateInner>, ServerFnError> {
let read = || async {
session
.get::<UserStateInner>(LOGGED_IN_USER_SESS_KEY)
.await
.map_err(|e| ServerFnError::new(format!("session read failed: {e}")))
};
let Some(user) = read().await? else {
return Ok(None);
};
if !token_needs_refresh(&user.access_token) {
return Ok(Some(user));
}
let key = session.id().map(|id| id.to_string()).unwrap_or_default();
let lock = refresh_lock(&key);
let _held = lock.lock().await;
// Another request of this session may have refreshed while this one
// waited: use its token.
let Some(mut user) = read().await? else {
return Ok(None);
};
if !token_needs_refresh(&user.access_token) {
return Ok(Some(user));
}
match refresh_tokens(state, &user.refresh_token).await {
Ok((access, refresh)) => {
user.access_token = access;
if let Some(refresh) = refresh {
user.refresh_token = refresh;
}
if let Err(e) = session.insert(LOGGED_IN_USER_SESS_KEY, &user).await {
tracing::warn!("Failed to persist refreshed tokens: {e}");
}
Ok(Some(user))
}
Err(RefreshError::Rejected(reason)) => {
tracing::info!("Sign-in expired, refresh rejected: {reason}");
if let Err(e) = session
.remove::<UserStateInner>(LOGGED_IN_USER_SESS_KEY)
.await
{
tracing::warn!("Failed to clear the expired sign-in: {e}");
}
Ok(None)
}
Err(RefreshError::Unreachable(reason)) => {
// Keycloak could not be asked: the stale token may still pass,
// and the next request tries again.
tracing::warn!("Token refresh failed: {reason}; sending current token anyway");
Ok(Some(user))
}
}
}
/// Attach the signed-in user's bearer token when Keycloak is configured.
///
/// # Errors
///
/// [`super::auth_check::SESSION_EXPIRED`] when the sign-in has run out; the session could not be
/// read.
async fn attach_token(
req: reqwest::RequestBuilder,
state: &ServerState,
) -> Result<reqwest::RequestBuilder, ServerFnError> {
if state.keycloak.is_none() {
return Ok(req);
}
let session: tower_sessions::Session = FullstackContext::extract().await?;
match current_user(state, &session).await? {
Some(user) => Ok(with_support_tenant(
req.bearer_auth(&user.access_token),
&user,
)),
None => Err(ServerFnError::new(super::auth_check::SESSION_EXPIRED)),
}
}
/// Name the tenant BreakPilot support has opened, when it has; the agent
/// honours the header only for a support role.
fn with_support_tenant(
req: reqwest::RequestBuilder,
user: &UserStateInner,
) -> reqwest::RequestBuilder {
match &user.support_tenant {
Some(tenant) => req.header(compliance_core::SUPPORT_TENANT_HEADER, &tenant.id),
None => req,
}
}
/// Decode the JWT's payload (no signature verification — the agent
/// does that) and check the `exp` claim. Treats malformed tokens as
/// expired so the refresh path runs.
fn token_needs_refresh(jwt: &str) -> bool {
let Some(payload_b64) = jwt.split('.').nth(1) else {
return true;
};
let Ok(bytes) = URL_SAFE_NO_PAD.decode(payload_b64) else {
return true;
};
#[derive(serde::Deserialize)]
struct ExpClaim {
exp: i64,
}
let Ok(claims) = serde_json::from_slice::<ExpClaim>(&bytes) else {
return true;
};
let now = chrono::Utc::now().timestamp();
claims.exp - REFRESH_SKEW_SECS <= now
}
/// Why a refresh gave no new token.
#[derive(Debug)]
enum RefreshError {
/// Keycloak refused it (the refresh token expired or was revoked): the
/// sign-in is over.
Rejected(String),
/// Keycloak could not be asked, or answered with something unreadable.
Unreachable(String),
}
/// Exchange a refresh_token for a new access_token. Returns the new
/// access_token and (optionally) the new refresh_token KC issued.
/// KC may rotate refresh_tokens on use; we honor whatever it sends.
async fn refresh_tokens(
state: &ServerState,
refresh_token: &str,
) -> Result<(String, Option<String>), RefreshError> {
let kc = state
.keycloak
.ok_or_else(|| RefreshError::Unreachable("Keycloak not configured".to_string()))?;
if refresh_token.is_empty() {
return Err(RefreshError::Rejected(
"no refresh_token in session".to_string(),
));
}
#[derive(serde::Deserialize)]
struct TokenResp {
access_token: String,
refresh_token: Option<String>,
}
let resp = reqwest::Client::new()
.post(kc.token_endpoint())
.form(&[
("grant_type", "refresh_token"),
("client_id", kc.client_id.as_str()),
("refresh_token", refresh_token),
])
.send()
.await
.map_err(|e| RefreshError::Unreachable(format!("refresh request failed: {e}")))?;
let status = resp.status();
if status.is_client_error() {
let body = resp.text().await.unwrap_or_default();
return Err(RefreshError::Rejected(format!("{status}: {body}")));
}
if !status.is_success() {
return Err(RefreshError::Unreachable(format!(
"refresh answered {status}"
)));
}
let r: TokenResp = resp
.json()
.await
.map_err(|e| RefreshError::Unreachable(format!("refresh response parse failed: {e}")))?;
Ok((r.access_token, r.refresh_token))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_session_has_one_refresh_lock_and_unused_ones_go() {
let a = refresh_lock("session-a");
assert!(std::sync::Arc::ptr_eq(&a, &refresh_lock("session-a")));
drop(a);
let _b = refresh_lock("session-b");
let locks = REFRESH_LOCKS
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
assert!(
!locks.contains_key("session-a"),
"a lock no one holds is dropped"
);
}
#[test]
fn a_refusal_says_what_the_agent_said() {
let status = reqwest::StatusCode::BAD_REQUEST;
assert_eq!(
refusal_message(status, r#"{"error":"name already in use"}"#),
"name already in use (400)"
);
assert_eq!(refusal_message(status, "<html>"), "Bad Request (400)");
assert_eq!(
refusal_message(reqwest::StatusCode::FORBIDDEN, r#"{"error":""}"#),
"Forbidden (403)"
);
}
use base64::Engine;
/// Build a JWT-shaped string (header.payload.sig) with the given
/// payload. Signature is bogus — we never verify it locally.
fn make_jwt(payload: &serde_json::Value) -> String {
let payload_b64 = URL_SAFE_NO_PAD.encode(serde_json::to_vec(payload).unwrap());
format!("hdr.{payload_b64}.sig")
}
#[test]
fn token_needs_refresh_true_when_expired() {
let exp = chrono::Utc::now().timestamp() - 60;
let jwt = make_jwt(&serde_json::json!({ "exp": exp }));
assert!(token_needs_refresh(&jwt));
}
#[test]
fn token_needs_refresh_true_within_skew_window() {
// 10 seconds left; less than the 30s skew → must refresh.
let exp = chrono::Utc::now().timestamp() + 10;
let jwt = make_jwt(&serde_json::json!({ "exp": exp }));
assert!(token_needs_refresh(&jwt));
}
#[test]
fn token_needs_refresh_false_with_plenty_of_life() {
let exp = chrono::Utc::now().timestamp() + 600;
let jwt = make_jwt(&serde_json::json!({ "exp": exp }));
assert!(!token_needs_refresh(&jwt));
}
#[test]
fn token_needs_refresh_true_on_malformed_jwt() {
assert!(token_needs_refresh(""));
assert!(token_needs_refresh("not.a.jwt"));
assert!(token_needs_refresh("only-one-segment"));
assert!(token_needs_refresh("hdr.not-base64!.sig"));
}
#[test]
fn token_needs_refresh_true_when_exp_missing() {
let jwt = make_jwt(&serde_json::json!({ "sub": "abc" }));
assert!(token_needs_refresh(&jwt));
}
}