Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
108 changes: 81 additions & 27 deletions libs/cua-driver/rust/crates/cua-driver/src/serve.rs
Original file line number Diff line number Diff line change
Expand Up @@ -203,9 +203,9 @@ fn is_session_lifecycle_tool(tool_name: &str) -> bool {
fn history_control_response(
registry: &crate::sdk_adapter::SdkAdapter,
request: &DaemonRequest,
trusted_cli_connection: bool,
trusted_cli_request: bool,
) -> DaemonResponse {
if !trusted_cli_connection
if !trusted_cli_request
|| request.client_kind != Some(cua_driver_core::daemon::DaemonClientKind::Cli)
|| request.observation_origin != Some(ToolObservationOrigin::Direct)
{
Expand Down Expand Up @@ -319,15 +319,15 @@ fn history_control_response(
async fn history_control_response_async(
registry: std::sync::Arc<crate::sdk_adapter::SdkAdapter>,
request: DaemonRequest,
trusted_cli_connection: bool,
trusted_cli_request: bool,
) -> DaemonResponse {
// Native credential stores are synchronous at this boundary. Linux's
// Secret Service adapter may drive its own async runtime internally, which
// must not be entered from a Tokio request worker. Keep key creation,
// deletion, and encrypted-store I/O off the daemon's async executor on all
// platforms so one control request cannot stall unrelated clients.
tokio::task::spawn_blocking(move || {
history_control_response(&registry, &request, trusted_cli_connection)
history_control_response(&registry, &request, trusted_cli_request)
})
.await
.unwrap_or_else(|error| {
Expand All @@ -337,9 +337,9 @@ async fn history_control_response_async(

fn history_relaunch_state_response(
request: &DaemonRequest,
trusted_cli_connection: bool,
trusted_cli_request: bool,
) -> DaemonResponse {
if !trusted_cli_connection
if !trusted_cli_request
|| request.client_kind != Some(cua_driver_core::daemon::DaemonClientKind::Cli)
|| request.observation_origin != Some(ToolObservationOrigin::Direct)
{
Expand Down Expand Up @@ -763,7 +763,9 @@ fn authenticate_embedded_host_connection(stream: &tokio::net::UnixStream) -> any
}

#[cfg(target_os = "macos")]
fn authenticate_history_cli_connection(stream: &tokio::net::UnixStream) -> anyhow::Result<()> {
fn history_cli_executable_path(
stream: &tokio::net::UnixStream,
) -> anyhow::Result<std::path::PathBuf> {
use std::os::unix::ffi::OsStringExt as _;

let peer_pid = stream
Expand All @@ -782,21 +784,46 @@ fn authenticate_history_cli_connection(stream: &tokio::net::UnixStream) -> anyho
.position(|byte| *byte == 0)
.unwrap_or(length as usize);
buffer.truncate(path_length);
let path = std::path::PathBuf::from(std::ffi::OsString::from_vec(buffer));
crate::history_runtime::verify_history_cli_executable_path(&path)
Ok(std::path::PathBuf::from(std::ffi::OsString::from_vec(
buffer,
)))
}

#[cfg(target_os = "linux")]
fn authenticate_history_cli_connection(stream: &tokio::net::UnixStream) -> anyhow::Result<()> {
fn history_cli_executable_path(
stream: &tokio::net::UnixStream,
) -> anyhow::Result<std::path::PathBuf> {
let peer_pid = stream
.peer_cred()
.map_err(|error| anyhow::anyhow!("read history control peer credentials: {error}"))?
.pid()
.ok_or_else(|| anyhow::anyhow!("history control peer PID is unavailable"))?;
let path = std::fs::read_link(format!("/proc/{peer_pid}/exe")).map_err(|error| {
anyhow::anyhow!("history control peer executable is unavailable: {error}")
})?;
crate::history_runtime::verify_history_cli_executable_path(&path)
std::fs::read_link(format!("/proc/{peer_pid}/exe"))
.map_err(|error| anyhow::anyhow!("history control peer executable is unavailable: {error}"))
}

fn history_cli_authentication_path(
method: &str,
executable_path: Option<&std::path::Path>,
) -> Option<std::path::PathBuf> {
if !matches!(method, "history_control" | "history_relaunch_state") {
return None;
}
executable_path.map(std::path::Path::to_path_buf)
}

async fn authenticate_history_cli_request(
method: &str,
executable_path: Option<&std::path::Path>,
) -> bool {
let Some(executable_path) = history_cli_authentication_path(method, executable_path) else {
return false;
};
tokio::task::spawn_blocking(move || {
crate::history_runtime::verify_history_cli_executable_path(&executable_path).is_ok()
})
.await
.unwrap_or(false)
}

fn service_authorization_status(trusted_host_connection: bool) -> serde_json::Value {
Expand Down Expand Up @@ -828,8 +855,8 @@ fn service_authorization_status(trusted_host_connection: bool) -> serde_json::Va
#[cfg(all(test, unix))]
mod peer_authentication_tests {
use super::{
authenticate_unix_peer, authenticate_unix_uid, history_relaunch_state_response,
shutdown_response, DaemonRequest, ToolObservationOrigin,
authenticate_unix_peer, authenticate_unix_uid, history_cli_authentication_path,
history_relaunch_state_response, shutdown_response, DaemonRequest, ToolObservationOrigin,
};

#[tokio::test]
Expand All @@ -845,6 +872,27 @@ mod peer_authentication_tests {
assert!(error.to_string().contains("reject Unix peer uid 502"));
}

#[test]
fn only_history_methods_select_the_peer_for_authentication() {
let path = std::path::Path::new("/installed/cua-driver");
for method in [
"list",
"metadata",
"authorization_status",
"call",
"shutdown",
] {
assert_eq!(history_cli_authentication_path(method, Some(path)), None);
}
for method in ["history_control", "history_relaunch_state"] {
assert_eq!(
history_cli_authentication_path(method, Some(path)).as_deref(),
Some(path)
);
assert_eq!(history_cli_authentication_path(method, None), None);
}
}

#[test]
fn forged_cli_metadata_does_not_authenticate_history_control() {
let request = DaemonRequest {
Expand Down Expand Up @@ -969,8 +1017,7 @@ pub async fn run_serve(
}
let trusted_host_connection =
authenticate_embedded_host_connection(&stream).is_ok();
let trusted_history_cli_connection =
authenticate_history_cli_connection(&stream).is_ok();
let history_cli_executable_path = history_cli_executable_path(&stream).ok();
let reg = sdk.clone();
let shutdown_tx2 = shutdown_tx.clone();
let trusted_resume_registry = trusted_resume_registry.clone();
Expand Down Expand Up @@ -1002,6 +1049,11 @@ pub async fn run_serve(
}
};

let trusted_history_cli_request = authenticate_history_cli_request(
&req.method,
history_cli_executable_path.as_deref(),
).await;

match req.method.as_str() {
"metadata" => {
let resp = daemon_metadata_response();
Expand All @@ -1012,7 +1064,7 @@ pub async fn run_serve(
"history_relaunch_state" => {
let resp = history_relaunch_state_response(
&req,
trusted_history_cli_connection,
trusted_history_cli_request,
);
let _ = writer.write_all(
(serde_json::to_string(&resp).unwrap() + "\n").as_bytes()
Expand Down Expand Up @@ -1080,7 +1132,7 @@ pub async fn run_serve(
let resp = history_control_response_async(
reg.clone(),
req,
trusted_history_cli_connection,
trusted_history_cli_request,
).await;
let _ = writer.write_all(
(serde_json::to_string(&resp).unwrap() + "\n").as_bytes()
Expand Down Expand Up @@ -1709,11 +1761,8 @@ pub async fn run_serve(
expected_host_process_id,
client_process_id,
);
let trusted_history_cli_connection = client_process_id
.and_then(platform_windows::history::process_executable_path)
.is_some_and(|path| {
crate::history_runtime::verify_history_cli_executable_path(&path).is_ok()
});
let history_cli_executable_path =
client_process_id.and_then(platform_windows::history::process_executable_path);

let reg = sdk.clone();
let shutdown_tx2 = shutdown_tx.clone();
Expand Down Expand Up @@ -1743,6 +1792,11 @@ pub async fn run_serve(
}
};

let trusted_history_cli_request = authenticate_history_cli_request(
&req.method,
history_cli_executable_path.as_deref(),
).await;

match req.method.as_str() {
"metadata" => {
let resp = daemon_metadata_response();
Expand All @@ -1753,7 +1807,7 @@ pub async fn run_serve(
"history_relaunch_state" => {
let resp = history_relaunch_state_response(
&req,
trusted_history_cli_connection,
trusted_history_cli_request,
);
let _ = writer.write_all(
(serde_json::to_string(&resp).unwrap() + "\n").as_bytes()
Expand Down Expand Up @@ -1804,7 +1858,7 @@ pub async fn run_serve(
let resp = history_control_response_async(
reg.clone(),
req,
trusted_history_cli_connection,
trusted_history_cli_request,
).await;
let _ = writer.write_all(
(serde_json::to_string(&resp).unwrap() + "\n").as_bytes()
Expand Down
Loading