use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::Arc;
use std::time::{Duration, Instant};
use futures_util::{SinkExt, StreamExt};
use serde_json::Value;
use tokio::io::AsyncWriteExt;
use tokio::net::{TcpListener, TcpStream};
use tokio::sync::mpsc;
use crate::util::LockExt;
mod runtime;
use tokio::task::{JoinHandle, JoinSet};
use tokio_tungstenite::tungstenite::protocol::WebSocketConfig;
use tokio_tungstenite::tungstenite::Message;
use crate::error::{Error, Result};
const MAX_MESSAGE_BYTES: usize = 256 * 1024 * 1024;
const HEADER_LIMIT: usize = 16 * 1024;
const HEADER_TIMEOUT: Duration = Duration::from_secs(5);
#[derive(Debug, Clone, Default)]
#[non_exhaustive]
pub struct CdpProxyOptions {
pub log_path: Option<PathBuf>,
pub pass_through: bool,
pub runtime: RuntimeMode,
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum RuntimeMode {
Forward,
#[default]
Emulate,
}
pub(crate) type Adopter =
Arc<dyn Fn(String, bool) -> futures_util::future::BoxFuture<'static, Result<()>> + Send + Sync>;
const ADOPT_TIMEOUT: Duration = Duration::from_secs(10);
#[derive(Debug)]
pub struct CdpProxy {
ws_url: String,
http_url: String,
task: JoinHandle<()>,
}
impl CdpProxy {
pub fn ws_url(&self) -> &str {
&self.ws_url
}
pub fn http_url(&self) -> &str {
&self.http_url
}
pub fn close(self) {}
}
impl Drop for CdpProxy {
fn drop(&mut self) {
self.task.abort();
}
}
struct Shared {
upstream_host: String,
upstream_port: u16,
upstream_browser_path: String,
token: String,
port: u16,
log: Option<mpsc::Sender<String>>,
started: Instant,
adopter: Option<Adopter>,
pass_through: bool,
utility_alias: String,
runtime: RuntimeMode,
}
pub(crate) async fn serve(
browser_endpoint: &str,
options: CdpProxyOptions,
adopter: Option<Adopter>,
) -> Result<CdpProxy> {
let rest = browser_endpoint
.strip_prefix("ws://")
.ok_or_else(|| Error::invalid_argument("CDP proxy needs a ws:// browser endpoint"))?;
let (authority, path) = rest.split_at(rest.find('/').unwrap_or(rest.len()));
let (host, port) = authority
.rsplit_once(':')
.and_then(|(h, p)| Some((h.trim_matches(['[', ']']).to_owned(), p.parse().ok()?)))
.ok_or_else(|| Error::invalid_argument("CDP proxy cannot parse the browser endpoint"))?;
let listener = TcpListener::bind(("127.0.0.1", 0))
.await
.map_err(|e| Error::transport_io("bind CDP proxy", e))?;
let local = listener
.local_addr()
.map_err(|e| Error::transport_io("CDP proxy address", e))?;
let token = random_token()?;
let log = match options.log_path {
Some(path) => Some(spawn_logger(&path)?),
None => None,
};
let shared = Arc::new(Shared {
upstream_host: host,
upstream_port: port,
upstream_browser_path: path.to_owned(),
token,
port: local.port(),
log,
started: Instant::now(),
adopter: if options.pass_through { None } else { adopter },
pass_through: options.pass_through,
utility_alias: identifier_alias(),
runtime: if options.pass_through {
RuntimeMode::Forward
} else {
options.runtime
},
});
let ws_url = shared.proxy_ws(&shared.upstream_browser_path);
let http_url = format!("http://127.0.0.1:{}", local.port());
let task = tokio::spawn(accept_loop(listener, shared));
Ok(CdpProxy {
ws_url,
http_url,
task,
})
}
impl Shared {
fn proxy_ws(&self, upstream_path: &str) -> String {
format!(
"ws://127.0.0.1:{}/{}{}",
self.port, self.token, upstream_path
)
}
fn log(&self, line: Value) {
if let Some(log) = &self.log {
let mut line = line;
line["t"] = u64::try_from(self.started.elapsed().as_millis())
.unwrap_or(u64::MAX)
.into();
let _ = log.try_send(line.to_string());
}
}
}
fn spawn_logger(path: &std::path::Path) -> Result<mpsc::Sender<String>> {
let file = std::fs::OpenOptions::new()
.create(true)
.append(true)
.open(path)
.map_err(|e| Error::transport_io("open CDP proxy log", e))?;
let (sender, mut receiver) = mpsc::channel::<String>(65_536);
std::thread::spawn(move || {
use std::io::Write;
let mut file = std::io::BufWriter::new(file);
while let Some(line) = receiver.blocking_recv() {
if writeln!(file, "{line}")
.and_then(|()| file.flush())
.is_err()
{
break;
}
}
});
Ok(sender)
}
fn random_token() -> Result<String> {
let mut bytes = [0u8; 16];
#[cfg(unix)]
{
use std::io::Read;
std::fs::File::open("/dev/urandom")
.and_then(|mut f| f.read_exact(&mut bytes))
.map_err(|e| Error::transport_io("read /dev/urandom", e))?;
}
#[cfg(not(unix))]
{
use std::hash::{BuildHasher, Hasher};
for chunk in bytes.chunks_mut(8) {
let mut hasher = std::collections::hash_map::RandomState::new().build_hasher();
hasher.write_u128(
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap_or_default()
.as_nanos(),
);
chunk.copy_from_slice(&hasher.finish().to_le_bytes()[..chunk.len()]);
}
}
Ok(bytes.iter().map(|b| format!("{b:02x}")).collect())
}
async fn accept_loop(listener: TcpListener, shared: Arc<Shared>) {
let mut connections = JoinSet::new();
loop {
let stream = match listener.accept().await {
Ok((stream, _)) => stream,
Err(error) => {
tracing::debug!("CDP proxy accept failed: {error}");
tokio::time::sleep(Duration::from_millis(50)).await;
continue;
}
};
while connections.try_join_next().is_some() {}
let shared = Arc::clone(&shared);
connections.spawn(async move {
if let Err(error) = handle(stream, &shared).await {
tracing::debug!("CDP proxy connection ended: {error}");
}
});
}
}
struct Request {
path: String,
host: Option<String>,
origin: Option<String>,
upgrade: bool,
head_len: usize,
}
async fn read_head(stream: &TcpStream) -> Result<Request> {
let deadline = tokio::time::Instant::now() + HEADER_TIMEOUT;
let mut buffer = vec![0u8; HEADER_LIMIT];
loop {
let n = tokio::time::timeout_at(deadline, stream.peek(&mut buffer))
.await
.map_err(|_| Error::transport("CDP proxy request header timed out"))?
.map_err(|e| Error::transport_io("CDP proxy read", e))?;
if n == 0 {
return Err(Error::transport("CDP proxy client closed"));
}
if let Some(end) = find(&buffer[..n], b"\r\n\r\n") {
return parse_head(&buffer[..end], end + 4);
}
if n == HEADER_LIMIT {
return Err(Error::transport("CDP proxy request header too large"));
}
tokio::time::sleep(Duration::from_millis(5)).await;
}
}
fn find(haystack: &[u8], needle: &[u8]) -> Option<usize> {
haystack.windows(needle.len()).position(|w| w == needle)
}
fn parse_head(head: &[u8], head_len: usize) -> Result<Request> {
let text = std::str::from_utf8(head).map_err(|_| Error::transport("non-UTF-8 request"))?;
let mut lines = text.split("\r\n");
let request_line = lines.next().unwrap_or_default();
let mut parts = request_line.split(' ');
let (Some("GET"), Some(path)) = (parts.next(), parts.next()) else {
return Err(Error::transport("CDP proxy accepts only GET"));
};
let mut request = Request {
path: path.to_owned(),
host: None,
origin: None,
upgrade: false,
head_len,
};
for line in lines {
let Some((name, value)) = line.split_once(':') else {
continue;
};
let value = value.trim();
match name.trim().to_ascii_lowercase().as_str() {
"host" => request.host = Some(value.to_owned()),
"origin" => request.origin = Some(value.to_owned()),
"upgrade" => request.upgrade = value.eq_ignore_ascii_case("websocket"),
_ => {}
}
}
Ok(request)
}
fn loopback_host(host: Option<&str>) -> bool {
let Some(host) = host else { return false };
let name = match host.rsplit_once(':') {
Some((name, port)) if port.chars().all(|c| c.is_ascii_digit()) => name,
_ => host,
};
matches!(name, "127.0.0.1" | "localhost" | "[::1]")
}
async fn respond(mut stream: TcpStream, head_len: usize, status: &str, body: &str) -> Result<()> {
use tokio::io::AsyncReadExt;
let mut discard = vec![0u8; head_len];
let _ = stream.read_exact(&mut discard).await;
let response = format!(
"HTTP/1.1 {status}\r\nContent-Type: application/json; charset=UTF-8\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
body.len()
);
stream
.write_all(response.as_bytes())
.await
.map_err(|e| Error::transport_io("CDP proxy write", e))?;
let _ = stream.shutdown().await;
Ok(())
}
async fn handle(stream: TcpStream, shared: &Arc<Shared>) -> Result<()> {
let request = read_head(&stream).await?;
if !loopback_host(request.host.as_deref()) {
shared.log(serde_json::json!({"kind":"refused","reason":"host","path":request.path}));
return respond(stream, request.head_len, "403 Forbidden", "{}").await;
}
let token_prefix = format!("/{}", shared.token);
let path = request.path.strip_prefix(&token_prefix).map(str::to_owned);
if request.upgrade {
let allowed = if shared.pass_through {
"/devtools/"
} else {
"/devtools/browser/"
};
let Some(upstream_path) = path.filter(|p| p.starts_with(allowed)) else {
shared.log(serde_json::json!({"kind":"refused","reason":"token"}));
return respond(stream, request.head_len, "403 Forbidden", "{}").await;
};
if request.origin.is_some() {
shared.log(
serde_json::json!({"kind":"refused","reason":"origin","origin":request.origin}),
);
return respond(stream, request.head_len, "403 Forbidden", "{}").await;
}
return proxy_ws(stream, shared, &upstream_path).await;
}
let path = path.unwrap_or(request.path.clone());
let route = path.trim_end_matches('/');
let body = match route.split('?').next().unwrap_or_default() {
"/json/version" => rewrite_json(shared, "/json/version").await?,
"/json" | "/json/list" => rewrite_json(shared, "/json/list").await?,
_ => return respond(stream, request.head_len, "404 Not Found", "{}").await,
};
respond(stream, request.head_len, "200 OK", &body).await
}
async fn rewrite_json(shared: &Arc<Shared>, path: &'static str) -> Result<String> {
let (host, port) = (shared.upstream_host.clone(), shared.upstream_port);
let text = tokio::task::spawn_blocking(move || super::discover::http_get(&host, port, path))
.await
.map_err(|_| Error::transport("CDP proxy discovery task failed"))??;
let mut value: Value =
serde_json::from_str(&text).map_err(|e| Error::decode(format!("{path}: {e}")))?;
let pages_allowed = shared.pass_through;
let rewrite = |entry: &mut Value| {
if let Some(url) = entry.get("webSocketDebuggerUrl").and_then(Value::as_str) {
if let Some(index) = url.find("/devtools/") {
let path = &url[index..];
if path.starts_with("/devtools/browser/") || pages_allowed {
entry["webSocketDebuggerUrl"] = shared.proxy_ws(path).into();
} else if let Some(object) = entry.as_object_mut() {
object.remove("webSocketDebuggerUrl");
}
}
}
if let Some(object) = entry.as_object_mut() {
object.remove("devtoolsFrontendUrl");
}
};
match &mut value {
Value::Array(entries) => entries.iter_mut().for_each(rewrite),
entry => rewrite(entry),
}
Ok(value.to_string())
}
fn ws_config() -> WebSocketConfig {
WebSocketConfig::default()
.max_message_size(Some(MAX_MESSAGE_BYTES))
.max_frame_size(Some(MAX_MESSAGE_BYTES))
}
type Held = Arc<std::sync::Mutex<HashMap<String, Vec<Message>>>>;
const CLIENT_QUEUE: usize = 1024;
const DRAIN_TIMEOUT: Duration = Duration::from_secs(1);
async fn proxy_ws(stream: TcpStream, shared: &Arc<Shared>, upstream_path: &str) -> Result<()> {
let client = tokio_tungstenite::accept_async_with_config(stream, Some(ws_config()))
.await
.map_err(|e| Error::transport(format!("CDP proxy handshake: {e}")))?;
let upstream_url = format!(
"ws://{}:{}{}",
if shared.upstream_host.contains(':') {
format!("[{}]", shared.upstream_host)
} else {
shared.upstream_host.clone()
},
shared.upstream_port,
upstream_path
);
let (upstream, _) =
tokio_tungstenite::connect_async_with_config(&upstream_url, Some(ws_config()), false)
.await
.map_err(|e| Error::transport(format!("CDP proxy upstream: {e}")))?;
let connection = fastrand::u32(..);
shared.log(serde_json::json!({"kind":"open","conn":connection,"path":upstream_path}));
let (mut client_tx, mut client_rx) = client.split();
let (mut upstream_tx, mut upstream_rx) = upstream.split();
let (to_client, mut client_queue) = mpsc::channel::<Message>(CLIENT_QUEUE);
let (to_upstream, mut upstream_queue) = mpsc::unbounded_channel::<Message>();
let own = runtime::Own::new(to_upstream.clone());
let emulator = (shared.runtime == RuntimeMode::Emulate)
.then(|| runtime::Emulator::new(Arc::clone(&own), to_client.clone()));
let methods: Methods = Arc::default();
let attaches: Arc<std::sync::Mutex<HashMap<u64, String>>> = Arc::default();
let held: Held = Arc::default();
let mut writers = JoinSet::new();
let log_shared = Arc::clone(shared);
writers.spawn(async move {
while let Some(message) = client_queue.recv().await {
let close = message.is_close();
if let Message::Text(text) = &message {
log_to_client(&log_shared, connection, text);
}
if client_tx.send(message).await.is_err() || close {
break;
}
}
});
writers.spawn(async move {
while let Some(message) = upstream_queue.recv().await {
let close = message.is_close();
if upstream_tx.send(message).await.is_err() || close {
break;
}
}
});
let mut readers = JoinSet::new();
{
let shared = Arc::clone(shared);
let methods = Arc::clone(&methods);
let attaches = Arc::clone(&attaches);
let held = Arc::clone(&held);
let to_upstream = to_upstream.clone();
let emulator = emulator.clone();
readers.spawn(async move {
while let Some(Ok(message)) = client_rx.next().await {
let close = message.is_close();
let mut message = message;
if let Message::Text(text) = &message {
if let Ok(value) = serde_json::from_str::<Value>(text) {
if let Some(emulator) = &emulator {
if let runtime::Client::Answered = emulator.on_client(&value).await {
continue;
}
}
log_command(&shared, connection, &value, &methods);
if value["method"] == "Target.attachToTarget" {
if let (Some(id), Some(target)) =
(value["id"].as_u64(), value["params"]["targetId"].as_str())
{
attaches.lock_unpoisoned().insert(id, target.to_owned());
}
}
if !shared.pass_through {
if let Some(rewritten) = strip_source_url(&value, &shared.utility_alias)
{
message = Message::text(rewritten);
}
}
if let Some(session) = value["sessionId"].as_str() {
match hold(&held, session, message) {
Some(free) => message = free,
None => continue,
}
}
}
}
if to_upstream.send(message).is_err() || close {
break;
}
}
});
}
{
let shared = Arc::clone(shared);
let to_client = to_client.clone();
let emulator = emulator.clone();
readers.spawn(async move {
while let Some(Ok(message)) = upstream_rx.next().await {
let close = message.is_close();
let mut observed = None;
if let Message::Text(text) = &message {
if let Ok(value) = serde_json::from_str::<Value>(text) {
if own.take(&value) {
continue;
}
if value["method"] == "Target.attachedToTarget" {
let params = &value["params"];
if params["targetInfo"]["type"] == "page" {
if let (Some(session), Some(target)) = (
params["sessionId"].as_str(),
params["targetInfo"]["targetId"].as_str(),
) {
let fresh = params["waitingForDebugger"] == true;
adopt(&shared, &held, &to_upstream, session, target, fresh);
}
}
} else if let Some(id) = value["id"].as_u64() {
let target = attaches.lock_unpoisoned().remove(&id);
if let (Some(target), Some(session)) =
(target, value["result"]["sessionId"].as_str())
{
adopt(&shared, &held, &to_upstream, session, &target, false);
}
}
log_upstream(&shared, connection, &value, &methods);
observed = Some(value);
}
}
if to_client.send(message).await.is_err() || close {
break;
}
if let (Some(emulator), Some(value)) = (&emulator, &observed) {
emulator.on_upstream(value).await;
}
}
});
}
drop(to_client);
readers.join_next().await;
let _ = tokio::time::timeout(DRAIN_TIMEOUT, async {
while writers.join_next().await.is_some() {}
})
.await;
if let Some(emulator) = &emulator {
emulator.shutdown();
}
shared.log(serde_json::json!({"kind":"close","conn":connection}));
Ok(())
}
fn hold(held: &Held, session: &str, message: Message) -> Option<Message> {
match held.lock_unpoisoned().get_mut(session) {
Some(queue) => {
queue.push(message);
None
}
None => Some(message),
}
}
fn adopt(
shared: &Arc<Shared>,
held: &Held,
to_upstream: &mpsc::UnboundedSender<Message>,
session: &str,
target: &str,
fresh: bool,
) {
let Some(adopter) = shared.adopter.clone() else {
return;
};
{
let mut held = held.lock_unpoisoned();
if held.contains_key(session) {
return;
}
held.insert(session.to_owned(), Vec::new());
}
let (shared, held, to_upstream, session) = (
Arc::clone(shared),
Arc::clone(held),
to_upstream.clone(),
session.to_owned(),
);
let mut setup = tokio::spawn(adopter(target.to_owned(), fresh));
let target = target.to_owned();
tokio::spawn(async move {
let failure = match tokio::time::timeout(ADOPT_TIMEOUT, &mut setup).await {
Ok(Ok(Ok(()))) => None,
Ok(Ok(Err(error))) => Some(error.to_string()),
Ok(Err(_)) => Some("setup task failed".to_owned()),
Err(_) => Some("timed out".to_owned()),
};
if let Some(error) = failure {
tracing::debug!("CDP proxy could not set up page {target}: {error}");
shared.log(serde_json::json!({"kind":"adopt-error","error":error}));
}
let mut held = held.lock_unpoisoned();
for message in held.remove(&session).unwrap_or_default() {
let _ = to_upstream.send(message);
}
});
}
fn identifier_alias() -> String {
const LETTERS: &[u8] = b"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
const REST: &[u8] = b"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
let mut alias = String::new();
alias.push(char::from(LETTERS[fastrand::usize(..LETTERS.len())]));
for _ in 0..3 {
alias.push(char::from(REST[fastrand::usize(..REST.len())]));
}
alias
}
fn strip_source_url(value: &Value, alias: &str) -> Option<String> {
let field = match value["method"].as_str()? {
"Runtime.evaluate" => "expression",
"Runtime.callFunctionOn" => "functionDeclaration",
_ => return None,
};
let source = value["params"][field].as_str()?;
let marker = source.contains("//# sourceURL=");
let utility = source.contains("UtilityScript") && !source.contains(alias);
if !marker && !utility {
return None;
}
let mut rewritten: String = if marker {
source
.split_inclusive('\n')
.filter(|line| !line.trim_start().starts_with("//# sourceURL="))
.collect()
} else {
source.to_owned()
};
if utility {
rewritten = rewritten.replace("UtilityScript", alias);
}
if rewritten == source {
return None;
}
let mut value = value.clone();
value["params"][field] = rewritten.into();
Some(value.to_string())
}
type Methods = Arc<std::sync::Mutex<HashMap<u64, String>>>;
fn log_command(shared: &Shared, connection: u32, value: &Value, methods: &Methods) {
if shared.log.is_none() {
return;
}
let method = value["method"].as_str().unwrap_or_default();
if let Some(id) = value["id"].as_u64() {
methods.lock_unpoisoned().insert(id, method.to_owned());
}
shared.log(serde_json::json!({
"conn": connection, "kind": "cmd", "id": value["id"], "method": method,
"session": value["sessionId"],
}));
}
fn log_upstream(shared: &Shared, connection: u32, value: &Value, methods: &Methods) {
if shared.log.is_none() {
return;
}
if let Some(id) = value["id"].as_u64() {
let method = methods.lock_unpoisoned().remove(&id);
shared.log(serde_json::json!({
"conn": connection, "kind": "resp", "id": id, "method": method,
"error": value["error"]["message"], "session": value["sessionId"],
}));
} else {
shared.log(serde_json::json!({
"conn": connection, "kind": "event", "method": value["method"],
"session": value["sessionId"],
}));
}
}
fn log_to_client(shared: &Shared, connection: u32, text: &str) {
if shared.log.is_none() {
return;
}
if let Ok(value) = serde_json::from_str::<Value>(text) {
shared.log(serde_json::json!({
"conn": connection, "kind": "to-client", "id": value["id"],
"method": value["method"], "session": value["sessionId"],
"context": value["params"]["context"]["id"],
"frame": value["params"]["context"]["auxData"]["frameId"],
"name": value["params"]["context"]["name"],
}));
}
}
#[cfg(test)]
mod tests {
use super::*;
use tokio::io::AsyncReadExt;
#[test]
fn held_sessions_queue_and_other_sessions_pass() {
let held: Held = Arc::default();
held.lock_unpoisoned().insert("A".into(), Vec::new());
assert!(hold(&held, "A", Message::text("1")).is_none());
assert!(hold(&held, "B", Message::text("2")).is_some());
assert_eq!(held.lock_unpoisoned()["A"], [Message::text("1")]);
}
#[test]
fn loopback_hosts_only() {
assert!(loopback_host(Some("127.0.0.1:9222")));
assert!(loopback_host(Some("localhost")));
assert!(loopback_host(Some("[::1]:80")));
assert!(!loopback_host(Some("evil.example:9222")));
assert!(!loopback_host(Some("127.0.0.1.evil.example")));
assert!(!loopback_host(None));
}
#[test]
fn strips_source_url_markers_only_from_scripts() {
let pptr = r#"{"id":1,"method":"Runtime.callFunctionOn","params":{"functionDeclaration":"() => 1\n//# sourceURL=pptr:evaluate;x\n"}}"#;
let parse = |text: &str| serde_json::from_str::<Value>(text).unwrap();
let out = parse(&strip_source_url(&parse(pptr), "uS9x").unwrap());
assert_eq!(out["params"]["functionDeclaration"], "() => 1\n");
let other =
r#"{"id":2,"method":"Page.navigate","params":{"url":"https://x/?sourceURL=1"}}"#;
assert!(strip_source_url(&parse(other), "uS9x").is_none());
let plain =
r#"{"id":3,"method":"Runtime.evaluate","params":{"expression":"'sourceURL='"}}"#;
assert!(strip_source_url(&parse(plain), "uS9x").is_none());
let pw = r#"{"id":4,"method":"Runtime.evaluate","params":{"expression":"class UtilityScript {} new UtilityScript()"}}"#;
let out = parse(&strip_source_url(&parse(pw), "uS9x").unwrap());
assert_eq!(out["params"]["expression"], "class uS9x {} new uS9x()");
}
async fn fake_chrome() -> (u16, mpsc::UnboundedReceiver<Value>) {
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let port = listener.local_addr().unwrap().port();
let (seen, received) = mpsc::unbounded_channel();
tokio::spawn(async move {
loop {
let (mut stream, _) = listener.accept().await.unwrap();
let mut peek = [0u8; 64];
let n = stream.peek(&mut peek).await.unwrap();
if peek[..n].starts_with(b"GET /json") {
let mut request = [0u8; 1024];
let _ = stream.read(&mut request).await;
let body = format!(
r#"{{"Browser":"Chrome/156","webSocketDebuggerUrl":"ws://127.0.0.1:{port}/devtools/browser/abc"}}"#
);
let reply = format!(
"HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
body.len()
);
stream.write_all(reply.as_bytes()).await.unwrap();
continue;
}
let seen = seen.clone();
tokio::spawn(async move {
let mut ws = tokio_tungstenite::accept_async(stream).await.unwrap();
while let Some(Ok(Message::Text(text))) = ws.next().await {
let value: Value = serde_json::from_str(&text).unwrap();
if value["method"] == "Target.setAutoAttach" {
let event = serde_json::json!({"method":"Target.attachedToTarget","params":{"sessionId":"S1","targetInfo":{"targetId":"T1","type":"page"},"waitingForDebugger":true}});
ws.send(Message::text(event.to_string())).await.unwrap();
}
if let Some(id) = value["id"].as_u64() {
let result = match value["method"].as_str() {
Some("Page.getFrameTree") => {
serde_json::json!({"frameTree":{"frame":{"id":"F1","securityOrigin":"http://x"}}})
}
Some("Runtime.evaluate") => {
serde_json::json!({"result":{"objectId":"99.7.1"}})
}
_ => serde_json::json!({}),
};
let reply = serde_json::json!({"id": id, "result": result, "sessionId": value["sessionId"]});
ws.send(Message::text(reply.to_string())).await.unwrap();
}
let _ = seen.send(value);
}
});
}
});
(port, received)
}
async fn raw_get(port: u16, path: &str, extra: &str) -> String {
let mut stream = TcpStream::connect(("127.0.0.1", port)).await.unwrap();
let request = format!("GET {path} HTTP/1.1\r\nHost: 127.0.0.1:{port}\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Version: 13\r\nSec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n{extra}\r\n");
stream.write_all(request.as_bytes()).await.unwrap();
let mut response = vec![0u8; 256];
let n = stream.read(&mut response).await.unwrap();
String::from_utf8_lossy(&response[..n]).into_owned()
}
#[tokio::test]
async fn proxy_guards_the_endpoint_and_sets_up_client_pages() {
let (port, mut received) = fake_chrome().await;
let (adopted_tx, mut adopted_rx) = mpsc::unbounded_channel::<(String, bool)>();
let adopter: Adopter = Arc::new(move |target, fresh| {
let adopted_tx = adopted_tx.clone();
Box::pin(async move {
tokio::time::sleep(Duration::from_millis(200)).await;
let _ = adopted_tx.send((target, fresh));
Ok(())
})
});
let proxy = serve(
&format!("ws://127.0.0.1:{port}/devtools/browser/abc"),
CdpProxyOptions::default(),
Some(adopter),
)
.await
.unwrap();
let proxy_port: u16 = proxy
.http_url()
.rsplit(':')
.next()
.unwrap()
.parse()
.unwrap();
let path = proxy
.ws_url()
.split_once(&format!(":{proxy_port}"))
.unwrap()
.1
.to_owned();
assert!(
raw_get(proxy_port, &path, "Origin: https://evil.example\r\n")
.await
.starts_with("HTTP/1.1 403")
);
assert!(raw_get(proxy_port, "/devtools/browser/abc", "")
.await
.starts_with("HTTP/1.1 403"));
let version = tokio::task::spawn_blocking(move || {
super::super::discover::http_get("127.0.0.1", proxy_port, "/json/version")
})
.await
.unwrap()
.unwrap();
assert!(version.contains(proxy.ws_url()), "{version}");
let (mut client, _) = tokio_tungstenite::connect_async(proxy.ws_url())
.await
.unwrap();
client
.send(Message::text(
r#"{"id":1,"method":"Target.setAutoAttach","params":{}}"#,
))
.await
.unwrap();
let mut client_saw = Vec::new();
while client_saw.len() < 2 {
if let Some(Ok(Message::Text(text))) = client.next().await {
client_saw.push(serde_json::from_str::<Value>(&text).unwrap());
}
}
client
.send(Message::text(
r#"{"id":2,"method":"Runtime.runIfWaitingForDebugger","sessionId":"S1"}"#,
))
.await
.unwrap();
assert_eq!(
received.recv().await.unwrap()["method"],
"Target.setAutoAttach"
);
let release = received.recv().await.unwrap();
assert_eq!(release["method"], "Runtime.runIfWaitingForDebugger");
let (target, fresh) = adopted_rx
.try_recv()
.expect("adoption finished before the release was forwarded");
assert_eq!((target.as_str(), fresh), ("T1", true));
let reply = tokio::time::timeout(Duration::from_secs(2), client.next())
.await
.unwrap()
.unwrap()
.unwrap();
let reply: Value = serde_json::from_str(reply.to_text().unwrap()).unwrap();
assert_eq!(reply["id"], 2);
}
#[tokio::test]
async fn emulated_runtime_enable_never_reaches_chrome() {
let (port, mut received) = fake_chrome().await;
let options = CdpProxyOptions {
runtime: RuntimeMode::Emulate,
..Default::default()
};
let proxy = serve(
&format!("ws://127.0.0.1:{port}/devtools/browser/abc"),
options,
None,
)
.await
.unwrap();
let (mut client, _) = tokio_tungstenite::connect_async(proxy.ws_url())
.await
.unwrap();
client
.send(Message::text(
r#"{"id":5,"method":"Runtime.enable","sessionId":"S1"}"#,
))
.await
.unwrap();
let mut seen = Vec::new();
while seen.len() < 2 {
let message = tokio::time::timeout(Duration::from_secs(5), client.next())
.await
.unwrap()
.unwrap()
.unwrap();
seen.push(serde_json::from_str::<Value>(message.to_text().unwrap()).unwrap());
}
assert_eq!(seen[0]["id"], 5, "answered locally: {}", seen[0]);
assert_eq!(seen[1]["method"], "Runtime.executionContextCreated");
let context = &seen[1]["params"]["context"];
assert_eq!(context["id"], 7);
assert_eq!(context["auxData"]["frameId"], "F1");
assert_eq!(context["auxData"]["isDefault"], true);
let mut chrome_saw = Vec::new();
while let Ok(value) = received.try_recv() {
chrome_saw.push(value["method"].as_str().unwrap_or_default().to_owned());
}
assert!(
!chrome_saw.iter().any(|m| m == "Runtime.enable"),
"{chrome_saw:?}"
);
assert!(
chrome_saw.iter().any(|m| m == "Page.getFrameTree"),
"{chrome_saw:?}"
);
}
}