Skip to content

armgit / cua

Public Imported from GitHub
0

Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.

fix(cua-spacesd): preserve Unicode host caller metadata (#4501)

Iflaq khurshida6912c941aae
diff --git a/docs/content/docs/cua-sdk/reference/rust/cua-spaces.mdx b/docs/content/docs/cua-sdk/reference/rust/cua-spaces.mdx
index 9498a34e02..2655218e45 100644
--- a/docs/content/docs/cua-sdk/reference/rust/cua-spaces.mdx
+++ b/docs/content/docs/cua-sdk/reference/rust/cua-spaces.mdx
@@ -472,6 +472,7 @@ pub struct HostCaller {
impl HostCaller {
fn local() -> Self;
fn from_metadata(value: Option<&str>) -> Result<Self>;
+ fn from_grpc_metadata(metadata: &MetadataMap) -> Result<Self>;
fn label(&self) -> String;
fn is_owner(&self) -> bool;
fn may_create(&self) -> bool;
diff --git a/libs/cua-spacesd/crates/cua-spacesd-server/src/host_spaces.rs b/libs/cua-spacesd/crates/cua-spacesd-server/src/host_spaces.rs
index 5ac8d5a3da..4bebd2a77c 100644
--- a/libs/cua-spacesd/crates/cua-spacesd-server/src/host_spaces.rs
+++ b/libs/cua-spacesd/crates/cua-spacesd-server/src/host_spaces.rs
@@ -122,6 +122,28 @@ struct HostSpacesImpl {
policy_file: Arc<PathBuf>,
}
+// Keep the JSON readable as ASCII gRPC metadata without losing Unicode names.
+struct AsciiJsonFormatter;
+
+impl serde_json::ser::Formatter for AsciiJsonFormatter {
+ fn write_string_fragment<W: ?Sized + std::io::Write>(
+ &mut self,
+ writer: &mut W,
+ fragment: &str,
+ ) -> std::io::Result<()> {
+ for ch in fragment.chars() {
+ if ch.is_ascii() {
+ writer.write_all(&[ch as u8])?;
+ } else {
+ for unit in ch.encode_utf16(&mut [0; 2]) {
+ write!(writer, "\\u{unit:04x}")?;
+ }
+ }
+ }
+ Ok(())
+ }
+}
+
/// The verified caller as the daemon receives it.
fn caller_json<T>(req: &Request<T>) -> Result<String, Status> {
let who = caller(req);
@@ -148,7 +170,11 @@ fn caller_json<T>(req: &Request<T>) -> Result<String, Status> {
))
}
};
- Ok(value.to_string())
+ let mut bytes = Vec::new();
+ let mut serializer = serde_json::Serializer::with_formatter(&mut bytes, AsciiJsonFormatter);
+ serde::Serialize::serialize(&value, &mut serializer)
+ .map_err(|_| Status::internal("caller metadata JSON"))?;
+ String::from_utf8(bytes).map_err(|_| Status::internal("caller metadata UTF-8"))
}
/// One start of the host's daemon at a time (concurrent creates wait for
@@ -471,6 +497,47 @@ mod tests {
);
}
+ #[test]
+ fn caller_metadata_round_trips_unicode_and_json_escapes() {
+ for name in [
+ "Ada",
+ "Jos\u{e9} P\u{e9}rez",
+ "\u{65e5}\u{672c}\u{8a9e}",
+ "\u{1f680}",
+ "quote\" slash\\ newline\n",
+ ] {
+ let relayed = req(CallerIdentity {
+ asserted: true,
+ account: Some(RelayCaller {
+ account: "ada".into(),
+ email: Some("[email protected]".into()),
+ name: Some(name.into()),
+ role: "owner".into(),
+ }),
+ ..Default::default()
+ });
+ let json = caller_json(&relayed).unwrap();
+ let forwarded = with_caller((), &json, Some(Duration::from_secs(60))).unwrap();
+ let text = forwarded
+ .metadata()
+ .get(CALLER_METADATA)
+ .unwrap()
+ .to_str()
+ .unwrap();
+ assert!(text.is_ascii());
+ let value: serde_json::Value = serde_json::from_str(text).unwrap();
+ assert_eq!(value["name"], name);
+ assert_eq!(value["account"], "ada");
+ assert_eq!(value["email"], "[email protected]");
+ assert_eq!(value["role"], "owner");
+ assert_eq!(value["via"], "relay");
+ if name.is_ascii() {
+ assert_eq!(text, value.to_string());
+ }
+ assert!(forwarded.metadata().contains_key("grpc-timeout"));
+ }
+ }
+
#[test]
fn a_direct_host_takes_host_calls_only_from_private_peers() {
let peer = |s: &str| Some(s.parse::<SocketAddr>().unwrap());
diff --git a/libs/cua/crates/cua-daemon/src/host_svc.rs b/libs/cua/crates/cua-daemon/src/host_svc.rs
index 33cc5295b8..ec467263ac 100644
--- a/libs/cua/crates/cua-daemon/src/host_svc.rs
+++ b/libs/cua/crates/cua-daemon/src/host_svc.rs
@@ -8,7 +8,7 @@
use std::sync::Arc;
use cua_proto::env::v1::{self as pb, host_spaces_service_server::HostSpacesService};
-use cua_spaces::host_spaces::{CALLER_METADATA, HostCaller, to_status};
+use cua_spaces::host_spaces::{HostCaller, to_status};
use crate::server::Shared;
@@ -16,13 +16,7 @@ use crate::server::Shared;
pub(crate) struct HostSvc(pub(crate) Arc<Shared>);
fn caller<T>(req: &tonic::Request<T>) -> Result<HostCaller, tonic::Status> {
- let value = req
- .metadata()
- .get(CALLER_METADATA)
- .map(|v| v.to_str())
- .transpose()
- .map_err(|_| tonic::Status::invalid_argument(format!("{CALLER_METADATA}: not text")))?;
- HostCaller::from_metadata(value).map_err(|e| to_status(&e))
+ HostCaller::from_grpc_metadata(req.metadata()).map_err(|e| to_status(&e))
}
#[tonic::async_trait]
diff --git a/libs/cua/crates/cua-spaces/src/host_spaces.rs b/libs/cua/crates/cua-spaces/src/host_spaces.rs
index 4ed85f395e..709a0e0a10 100644
--- a/libs/cua/crates/cua-spaces/src/host_spaces.rs
+++ b/libs/cua/crates/cua-spaces/src/host_spaces.rs
@@ -104,6 +104,21 @@ impl HostCaller {
}
}
+ /// The caller in a request's [`CALLER_METADATA`]. cua-spacesd escapes
+ /// non-ASCII as JSON `\uXXXX`, but releases up to 0.3.0
+ /// sent a Unicode display name as raw UTF-8, which is not ASCII text, so
+ /// any valid UTF-8 value is accepted.
+ pub fn from_grpc_metadata(metadata: &tonic::metadata::MetadataMap) -> Result<Self> {
+ let value = metadata
+ .get(CALLER_METADATA)
+ .map(|v| {
+ std::str::from_utf8(v.as_bytes())
+ .map_err(|_| Error::invalid(format!("{CALLER_METADATA}: not UTF-8")))
+ })
+ .transpose()?;
+ Self::from_metadata(value)
+ }
+
/// `Name <email> (account)` for the audit and people.
pub fn label(&self) -> String {
if self.account == "local" {
@@ -2277,6 +2292,45 @@ mod tests {
assert!(HostCaller::from_metadata(Some("nope")).is_err());
}
+ /// A Unicode display name arrives as ASCII-escaped JSON (current
+ /// cua-spacesd) or as raw UTF-8 bytes (older cua-spacesd); both parse,
+ /// and bytes that are not UTF-8 are refused.
+ #[test]
+ fn callers_from_grpc_metadata() {
+ use tonic::metadata::{MetadataMap, MetadataValue};
+ let with = |v: MetadataValue<tonic::metadata::Ascii>| {
+ let mut m = MetadataMap::new();
+ m.insert(CALLER_METADATA, v);
+ m
+ };
+ let name = "Jos\u{e9} \u{65e5}\u{672c} \u{1f680}";
+
+ let escaped = r#"{"account":"ada","name":"Jos\u00e9 \u65e5\u672c \ud83d\ude80","role":"owner","via":"relay"}"#;
+ assert!(escaped.is_ascii());
+ let c = HostCaller::from_metadata(Some(escaped)).unwrap();
+ assert_eq!(c.name.as_deref(), Some(name));
+ let c = HostCaller::from_grpc_metadata(&with(escaped.parse().unwrap())).unwrap();
+ assert_eq!(c.name.as_deref(), Some(name));
+ assert!(c.is_owner());
+
+ let raw = format!(r#"{{"account":"ada","name":"{name}","role":"owner","via":"relay"}}"#);
+ // What cua-spacesd up to 0.3.0 sent: `str::parse` keeps the bytes.
+ let value: MetadataValue<tonic::metadata::Ascii> = raw.parse().unwrap();
+ assert!(value.to_str().is_err());
+ let c = HostCaller::from_grpc_metadata(&with(value)).unwrap();
+ assert_eq!(c.name.as_deref(), Some(name));
+ assert_eq!(c.account, "ada");
+
+ let not_utf8 = MetadataValue::try_from(&b"{\"account\":\"\xff\"}"[..]).unwrap();
+ let err = HostCaller::from_grpc_metadata(&with(not_utf8)).unwrap_err();
+ assert!(err.to_string().contains("not UTF-8"), "{err}");
+
+ assert_eq!(
+ HostCaller::from_grpc_metadata(&MetadataMap::new()).unwrap(),
+ HostCaller::local()
+ );
+ }
+
/// A host that answered is listed with its limits unless it does not
/// provide Spaces; one that did not answer only when it is known.
#[test]