Files
pruefwerk/compliance-dast/src/cdp.rs
T
sharang 12206bfac5
CI / Check (push) Skipped
CI / Agent integration (push) Skipped
CI / Detect Changes (push) Successful in 3s
CI / Deploy Dashboard (push) Skipped
CI / Deploy Docs (push) Skipped
CI / Deploy MCP (push) Skipped
CI / Deploy Agent (push) Successful in 5m48s
fix(dast): each browser tab gets its own browser context (#1004)
2026-11-16 08:16:50 +00:00

247 lines
8.9 KiB
Rust

//! One Chrome tab driven over the Chrome DevTools Protocol (CDP).
//!
//! Each tab lives in its own browser context, Chrome's equivalent of a fresh
//! profile: its cookies and storage are invisible to every other tab, so one
//! scan's or pentest session's login never shows up in another's.
use std::time::Duration;
use futures_util::{SinkExt, StreamExt};
use serde_json::{json, Value};
use tokio_tungstenite::tungstenite::Message;
type WsStream =
tokio_tungstenite::WebSocketStream<tokio_tungstenite::MaybeTlsStream<tokio::net::TcpStream>>;
/// How long one CDP command may take to answer.
const COMMAND_TIMEOUT: Duration = Duration::from_secs(30);
/// A tab in its own browser context, closed with [`CdpTab::close`].
pub(crate) struct CdpTab {
ws: WsStream,
next_id: u64,
session_id: String,
target_id: String,
context_id: String,
}
impl CdpTab {
/// Open a blank tab in a new browser context of the Chrome at
/// `CHROME_WS_URL`, with the `Page` and `Runtime` domains on.
///
/// # Errors
///
/// Why Chrome cannot be reached or refused a command.
pub(crate) async fn open() -> Result<Self, String> {
let ws_url = std::env::var("CHROME_WS_URL").map_err(|_| {
"CHROME_WS_URL not set — headless Chrome is required for browser actions".to_string()
})?;
// `/json/version` names the browser's own WebSocket endpoint.
let http_url = ws_url
.replacen("ws://", "http://", 1)
.replacen("wss://", "https://", 1);
let version_url = format!("{}/json/version", http_url.trim_end_matches('/'));
let version: Value = reqwest::get(&version_url)
.await
.map_err(|e| format!("Cannot reach Chrome at {version_url}: {e}"))?
.json()
.await
.map_err(|e| format!("Invalid /json/version response: {e}"))?;
let browser_ws = version["webSocketDebuggerUrl"]
.as_str()
.ok_or_else(|| "No webSocketDebuggerUrl in /json/version".to_string())?;
let (ws, _) = tokio_tungstenite::connect_async(browser_ws)
.await
.map_err(|e| format!("WebSocket connect failed: {e}"))?;
let mut tab = Self {
ws,
next_id: 1,
session_id: String::new(),
target_id: String::new(),
context_id: String::new(),
};
let context = tab
.browser(
"Target.createBrowserContext",
json!({ "disposeOnDetach": true }),
)
.await?;
tab.context_id = string_at(&context, "browserContextId")?;
let target = tab
.browser(
"Target.createTarget",
json!({ "url": "about:blank", "browserContextId": tab.context_id }),
)
.await?;
tab.target_id = string_at(&target, "targetId")?;
let attached = tab
.browser(
"Target.attachToTarget",
json!({ "targetId": tab.target_id, "flatten": true }),
)
.await?;
tab.session_id = string_at(&attached, "sessionId")?;
for domain in ["Page.enable", "Runtime.enable"] {
tab.call(domain, json!({})).await?;
}
Ok(tab)
}
/// Send `method` to the tab and return the command's `result`.
///
/// # Errors
///
/// The CDP error, a broken connection, or no answer in time.
pub(crate) async fn call(&mut self, method: &str, params: Value) -> Result<Value, String> {
let message = json!({
"id": self.next_id,
"sessionId": self.session_id,
"method": method,
"params": params,
});
self.send(message).await
}
/// Evaluate `expression` in the page and return its value as a string
/// (JSON for anything that is not a string; empty for `undefined`).
///
/// # Errors
///
/// As [`Self::call`].
pub(crate) async fn evaluate(&mut self, expression: &str) -> Result<String, String> {
let resp = self
.call(
"Runtime.evaluate",
json!({ "expression": expression, "returnByValue": true }),
)
.await?;
Ok(match resp.get("result").and_then(|r| r.get("value")) {
Some(Value::String(s)) => s.clone(),
Some(v) => v.to_string(),
None => String::new(),
})
}
/// Close the tab and dispose of its browser context with every cookie in
/// it. Best effort: Chrome also disposes of the context when the
/// connection drops.
pub(crate) async fn close(&mut self) {
let _ = self
.browser("Target.closeTarget", json!({ "targetId": self.target_id }))
.await;
let _ = self
.browser(
"Target.disposeBrowserContext",
json!({ "browserContextId": self.context_id }),
)
.await;
let _ = self.ws.close(None).await;
}
/// Send `method` to the browser itself rather than the tab.
async fn browser(&mut self, method: &str, params: Value) -> Result<Value, String> {
let message = json!({ "id": self.next_id, "method": method, "params": params });
self.send(message).await
}
async fn send(&mut self, message: Value) -> Result<Value, String> {
let id = self.next_id;
self.next_id += 1;
self.ws
.send(Message::Text(message.to_string().into()))
.await
.map_err(|e| format!("WS send failed: {e}"))?;
let deadline = tokio::time::Instant::now() + COMMAND_TIMEOUT;
loop {
let msg = tokio::time::timeout_at(deadline, self.ws.next())
.await
.map_err(|_| format!("Timeout waiting for CDP response id={id}"))?
.ok_or_else(|| "WebSocket closed unexpectedly".to_string())?
.map_err(|e| format!("WebSocket read error: {e}"))?;
// Events and other commands' answers share the socket; skip them.
let Message::Text(text) = msg else { continue };
let Ok(val) = serde_json::from_str::<Value>(&text) else {
continue;
};
if val.get("id").and_then(Value::as_u64) != Some(id) {
continue;
}
if let Some(err) = val.get("error") {
return Err(format!("CDP error: {err}"));
}
return Ok(val.get("result").cloned().unwrap_or(Value::Null));
}
}
}
/// The string field `key` of a CDP result.
fn string_at(result: &Value, key: &str) -> Result<String, String> {
result
.get(key)
.and_then(Value::as_str)
.map(str::to_string)
.ok_or_else(|| format!("No {key} in CDP response"))
}
// Needs a real Chrome: set `CHROME_WS_URL` (e.g. `chromedp/headless-shell`
// on the host network). Without it the test passes without checking.
#[cfg(test)]
#[allow(clippy::unwrap_used)]
mod tests {
use std::sync::{Arc, Mutex};
use axum::extract::{Request, State};
use axum::http::header::{COOKIE, SET_COOKIE};
use axum::response::IntoResponse;
use axum::Router;
use super::*;
/// The `Cookie` header of every request the site saw.
type Seen = Arc<Mutex<Vec<Option<String>>>>;
/// A site that sets a cookie on every answer and records what came back.
async fn cookie_site(seen: Seen) -> String {
async fn any(State(seen): State<Seen>, request: Request) -> impl IntoResponse {
let cookie = request
.headers()
.get(COOKIE)
.and_then(|v| v.to_str().ok())
.map(str::to_string);
seen.lock().unwrap().push(cookie);
([(SET_COOKIE, "visited=1; Path=/")], "<html></html>")
}
let app = Router::new().fallback(any).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}/")
}
#[tokio::test]
async fn tabs_do_not_share_cookies() {
if std::env::var("CHROME_WS_URL").is_err() {
return;
}
let seen: Seen = Arc::default();
let site = cookie_site(seen.clone()).await;
let mut first = CdpTab::open().await.unwrap();
let mut second = CdpTab::open().await.unwrap();
let navigate = json!({ "url": site });
first.call("Page.navigate", navigate.clone()).await.unwrap();
first.call("Page.navigate", navigate.clone()).await.unwrap();
second.call("Page.navigate", navigate).await.unwrap();
first.close().await;
second.close().await;
let seen = seen.lock().unwrap().clone();
assert_eq!(
seen,
[None, Some("visited=1".to_string()), None],
"the first tab keeps its cookie, the second never sees it"
);
}
}