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-compat): name the user on file calls to an agent that switches users (#6523)

injaneity1e1b9489f736
diff --git a/libs/cua/crates/cua-compat/src/daytona/api.rs b/libs/cua/crates/cua-compat/src/daytona/api.rs
index 45d8003499..d251481e47 100644
--- a/libs/cua/crates/cua-compat/src/daytona/api.rs
+++ b/libs/cua/crates/cua-compat/src/daytona/api.rs
@@ -391,11 +391,7 @@ pub(super) async fn prepare_user(d: &Daytona, r: &Record) {
return;
}
let Ok(c) = d.spacesd(r).await else { return };
- let script = format!(
- "id -u {user} >/dev/null 2>&1 && exit 0; \
- (useradd -m -s /bin/bash {user} || adduser -D -s /bin/sh {user}) >/dev/null 2>&1 || exit 1; \
- if [ -d /etc/sudoers.d ]; then echo '{user} ALL=(ALL:ALL) NOPASSWD: ALL' > /etc/sudoers.d/90-{user} && chmod 440 /etc/sudoers.d/90-{user}; fi"
- );
+ let script = crate::guest::create_user_script(&user);
let driver = d.drivers.of(&r.id, &c).await;
if let Ok(out) = crate::guest::run_as(&c, &driver, "root", &script, &[]).await
&& !out.success()
diff --git a/libs/cua/crates/cua-compat/src/daytona/toolbox.rs b/libs/cua/crates/cua-compat/src/daytona/toolbox.rs
index 20d1f5cb89..fa9a54b230 100644
--- a/libs/cua/crates/cua-compat/src/daytona/toolbox.rs
+++ b/libs/cua/crates/cua-compat/src/daytona/toolbox.rs
@@ -1881,8 +1881,10 @@ async fn create_folder(
Err(e) => e,
};
}
- let from = if crate::guest::without_sudo(&driver) && user != "root" {
- crate::guestfs::first_missing(&c, &path).await
+ // An agent that switches users makes them as `user`; one that cannot
+ // makes them as itself, and they are given to `user` after.
+ let from = if driver == crate::guest::UNNAMED && user != "root" {
+ crate::guestfs::first_missing(&c, &driver, &path).await
} else {
None
};
@@ -1892,7 +1894,7 @@ async fn create_folder(
path: path.clone(),
parents: true,
mode,
- ..Default::default()
+ run_as: crate::guest::file_run_as(&driver, &user),
})
.await
{
@@ -1942,7 +1944,7 @@ async fn delete_file(
path,
recursive: q.recursive.unwrap_or(false),
missing_ok: false,
- ..Default::default()
+ run_as: crate::guest::file_run_as(&driver, &user),
})
.await
{
@@ -1975,6 +1977,7 @@ async fn move_file(
.stat(pb::StatRequest {
path: target.clone(),
no_follow_symlinks: true,
+ run_as: crate::guest::file_run_as(&driver, &user),
..Default::default()
})
.await
@@ -1999,7 +2002,7 @@ async fn move_file(
destination: resolve_path(dst, &home),
overwrite: true,
create_parents: false,
- ..Default::default()
+ run_as: crate::guest::file_run_as(&driver, &user),
})
.await
{
diff --git a/libs/cua/crates/cua-compat/src/e2b/api.rs b/libs/cua/crates/cua-compat/src/e2b/api.rs
index b2e17b4f33..25361fb902 100644
--- a/libs/cua/crates/cua-compat/src/e2b/api.rs
+++ b/libs/cua/crates/cua-compat/src/e2b/api.rs
@@ -500,11 +500,7 @@ pub(super) async fn ensure_default_user(
if !e.cfg.create_default_user || user == "root" {
return;
}
- let script = format!(
- "id -u {user} >/dev/null 2>&1 && exit 0; \
- (useradd -m -s /bin/bash {user} || adduser -D -s /bin/sh {user}) >/dev/null 2>&1 || exit 1; \
- if [ -d /etc/sudoers.d ]; then echo '{user} ALL=(ALL:ALL) NOPASSWD: ALL' > /etc/sudoers.d/90-{user} && chmod 440 /etc/sudoers.d/90-{user}; fi"
- );
+ let script = crate::guest::create_user_script(user);
match crate::guest::run_as_idempotent(c, driver, "root", &script, &[]).await {
Ok(out) if out.success() => {}
Ok(out) => tracing::warn!(
diff --git a/libs/cua/crates/cua-compat/src/e2b/files.rs b/libs/cua/crates/cua-compat/src/e2b/files.rs
index c4d539fb44..034a6aa506 100644
--- a/libs/cua/crates/cua-compat/src/e2b/files.rs
+++ b/libs/cua/crates/cua-compat/src/e2b/files.rs
@@ -169,12 +169,15 @@ pub async fn read(
};
let _ = user;
let path = resolve_path(&path, &home);
+ // envd reads with root's rights.
+ let driver = e.drivers.of(&r.id, &c).await;
let call = pb::ReadFileRequest {
path: path.clone(),
offset: 0,
length: 0,
chunk_size: 0,
compute_sha256: false,
+ run_as: crate::guest::file_run_as(&driver, "root"),
..Default::default()
};
let mut stream = match c.filesystem().read_file(call).await {
@@ -186,8 +189,6 @@ pub async fn read(
);
}
Err(s) if s.code() == tonic::Code::PermissionDenied => {
- // envd reads with root's rights.
- let driver = e.drivers.of(&r.id, &c).await;
return read_as_user(&c, &driver, "root", &path).await;
}
Err(s) => return read_error(&s, &path),
diff --git a/libs/cua/crates/cua-compat/src/e2b/fsops.rs b/libs/cua/crates/cua-compat/src/e2b/fsops.rs
index c4620020b0..2ce69670b6 100644
--- a/libs/cua/crates/cua-compat/src/e2b/fsops.rs
+++ b/libs/cua/crates/cua-compat/src/e2b/fsops.rs
@@ -280,7 +280,7 @@ impl Fs<'_> {
))
}),
Err(Some(e)) => Err(e),
- Err(None) => native::stat(self.c, path).await,
+ Err(None) => native::stat(self.c, self.driver, path).await,
}
}
@@ -298,7 +298,7 @@ impl Fs<'_> {
})
.collect()),
Err(Some(e)) => Err(e),
- Err(None) => native::list(self.c, path, depth.max(1)).await,
+ Err(None) => native::list(self.c, self.driver, path, depth.max(1)).await,
}
}
@@ -318,7 +318,7 @@ impl Fs<'_> {
{
Ok(o) => o,
Err(Some(e)) => return Err(e),
- Err(None) => return native::make_dir(self.c, path).await,
+ Err(None) => return native::make_dir(self.c, self.driver, path, user).await,
};
match out.status.code {
Some(0) => {}
@@ -350,7 +350,7 @@ impl Fs<'_> {
/// `Remove`: recursive; a missing path is fine. cua-spacesd removes
/// what it may; the rest goes through root.
pub async fn remove(&self, path: &str) -> Result<(), RpcError> {
- match native::remove(self.c, path).await {
+ match native::remove(self.c, self.driver, path).await {
Ok(()) => {}
Err(e) if e.code == Code::PermissionDenied => {}
Err(e) => return Err(e),
@@ -386,7 +386,7 @@ impl Fs<'_> {
{
Ok(o) => o,
Err(Some(e)) => return Err(e),
- Err(None) => return native::rename(self.c, src, dst).await,
+ Err(None) => return native::rename(self.c, self.driver, src, dst, user).await,
};
match out.status.code {
Some(0) => {}
@@ -413,7 +413,8 @@ impl Fs<'_> {
/// cua-spacesd's own filesystem calls: what a guest without GNU tools
/// (Windows, macOS, bare containers) gets. Same messages, less detail
-/// (cua-spacesd hides the special mode bits and device kinds).
+/// (cua-spacesd hides the special mode bits and device kinds). Like envd
+/// they act with root's rights where the agent can switch users itself.
mod native {
use super::*;
use cua_spacesd_client::pb;
@@ -451,8 +452,13 @@ mod native {
))
}
+ fn root(driver: &str) -> String {
+ crate::guest::file_run_as(driver, "root")
+ }
+
async fn lstat(
c: &SpacesdClient,
+ driver: &str,
path: &str,
follow: bool,
) -> Result<pb::EntryInfo, tonic::Status> {
@@ -460,6 +466,7 @@ mod native {
.stat(pb::StatRequest {
path: path.to_string(),
no_follow_symlinks: !follow,
+ run_as: root(driver),
..Default::default()
})
.await?
@@ -468,8 +475,8 @@ mod native {
.unwrap_or_default())
}
- pub async fn stat(c: &SpacesdClient, path: &str) -> Result<Ent, RpcError> {
- let raw = lstat(c, path, false).await.map_err(|s| {
+ pub async fn stat(c: &SpacesdClient, driver: &str, path: &str) -> Result<Ent, RpcError> {
+ let raw = lstat(c, driver, path, false).await.map_err(|s| {
if s.code() == tonic::Code::NotFound {
missing(path, "file")
} else {
@@ -478,7 +485,7 @@ mod native {
})?;
let mut e = ent(&raw);
if e.kind == 'l' {
- let followed = lstat(c, path, true).await;
+ let followed = lstat(c, driver, path, true).await;
e.target_kind = match &followed {
Ok(t) => match t.r#type {
2 => 'd',
@@ -502,7 +509,12 @@ mod native {
Ok(e)
}
- pub async fn list(c: &SpacesdClient, path: &str, depth: u32) -> Result<Vec<Ent>, RpcError> {
+ pub async fn list(
+ c: &SpacesdClient,
+ driver: &str,
+ path: &str,
+ depth: u32,
+ ) -> Result<Vec<Ent>, RpcError> {
let mut out = Vec::new();
let mut token = String::new();
loop {
@@ -514,6 +526,7 @@ mod native {
include_hidden: true,
page_size: 0,
page_token: token,
+ run_as: root(driver),
..Default::default()
})
.await
@@ -535,14 +548,33 @@ mod native {
Ok(out)
}
- pub async fn make_dir(c: &SpacesdClient, path: &str) -> Result<Ent, RpcError> {
+ /// What a call making `path`'s parents created, for `user`.
+ async fn created_for(
+ c: &SpacesdClient,
+ driver: &str,
+ user: &str,
+ path: &str,
+ ) -> Option<String> {
+ if user == "root" || driver != "root" {
+ return None;
+ }
+ crate::guestfs::first_missing(c, driver, path).await
+ }
+
+ pub async fn make_dir(
+ c: &SpacesdClient,
+ driver: &str,
+ path: &str,
+ user: &str,
+ ) -> Result<Ent, RpcError> {
+ let from = created_for(c, driver, user, path).await;
let resp = c
.filesystem()
.make_dir(pb::MakeDirRequest {
path: path.to_string(),
parents: true,
mode: 0,
- ..Default::default()
+ run_as: root(driver),
})
.await?
.into_inner();
@@ -552,36 +584,61 @@ mod native {
format!("directory '{path}' already exists"),
));
}
- stat(c, path).await
+ if let Some(from) = from {
+ crate::guestfs::chown_created(c, user, &from).await;
+ }
+ stat(c, driver, path).await
}
- pub async fn remove(c: &SpacesdClient, path: &str) -> Result<(), RpcError> {
+ pub async fn remove(c: &SpacesdClient, driver: &str, path: &str) -> Result<(), RpcError> {
c.filesystem()
.remove(pb::RemoveRequest {
path: path.to_string(),
recursive: true,
missing_ok: true,
- ..Default::default()
+ run_as: root(driver),
})
.await?;
Ok(())
}
- pub async fn rename(c: &SpacesdClient, src: &str, dst: &str) -> Result<Ent, RpcError> {
- if let Ok(d) = lstat(c, dst, false).await
+ pub async fn rename(
+ c: &SpacesdClient,
+ driver: &str,
+ src: &str,
+ dst: &str,
+ user: &str,
+ ) -> Result<Ent, RpcError> {
+ if let Ok(d) = lstat(c, driver, dst, false).await
&& d.r#type == 2
{
return Err(RpcError::internal(format!(
"error renaming: rename {src} {dst}: file exists"
)));
}
+ // The destination's new parents go to `user` before the move, so
+ // what is moved keeps its owner.
+ let parent = dst.rsplit_once('/').map_or("", |(p, _)| p);
+ if !parent.is_empty()
+ && let Some(from) = created_for(c, driver, user, parent).await
+ {
+ c.filesystem()
+ .make_dir(pb::MakeDirRequest {
+ path: parent.to_string(),
+ parents: true,
+ mode: 0,
+ run_as: root(driver),
+ })
+ .await?;
+ crate::guestfs::chown_created(c, user, &from).await;
+ }
c.filesystem()
.r#move(pb::MoveRequest {
source: src.to_string(),
destination: dst.to_string(),
overwrite: true,
create_parents: true,
- ..Default::default()
+ run_as: root(driver),
})
.await
.map_err(|s| {
@@ -593,7 +650,7 @@ mod native {
s.into()
}
})?;
- stat(c, dst).await
+ stat(c, driver, dst).await
}
}
diff --git a/libs/cua/crates/cua-compat/src/guest.rs b/libs/cua/crates/cua-compat/src/guest.rs
index 76bd50320c..6ca54b7bc1 100644
--- a/libs/cua/crates/cua-compat/src/guest.rs
+++ b/libs/cua/crates/cua-compat/src/guest.rs
@@ -105,6 +105,29 @@ pub fn as_user(
("/usr/bin/sudo".to_string(), a, String::new())
}
+/// The `run_as` of a cua-spacesd file call made as `user`. An agent that
+/// switches users itself (driver "root") may be `cua` holding CAP_SETUID,
+/// which an unnamed call runs as, so the user is named, root included.
+/// Any other agent runs the call as itself (callers switch through `sudo`
+/// where that is not enough).
+pub fn file_run_as(driver: &str, user: &str) -> String {
+ if driver == "root" {
+ user.to_string()
+ } else {
+ String::new()
+ }
+}
+
+/// The script that creates guest user `user` with a home directory and
+/// passwordless `sudo`. Its stderr says why a creation failed.
+pub fn create_user_script(user: &str) -> String {
+ format!(
+ "id -u {user} >/dev/null 2>&1 && exit 0; \
+ (useradd -m -s /bin/bash {user} || adduser -D -s /bin/sh {user}) >/dev/null || exit 1; \
+ if [ -d /etc/sudoers.d ]; then echo '{user} ALL=(ALL:ALL) NOPASSWD: ALL' > /etc/sudoers.d/90-{user} && chmod 440 /etc/sudoers.d/90-{user}; fi"
+ )
+}
+
/// [`as_user`] with a working directory: when the switch goes through
/// `sudo`, the directory is entered after it (the driver may not be allowed
/// into another user's home), so the cwd for cua-spacesd is empty.
@@ -335,6 +358,37 @@ mod tests {
}
}
+#[cfg(all(test, unix))]
+mod create_user_tests {
+ use std::os::unix::fs::PermissionsExt;
+
+ #[test]
+ fn a_failed_useradd_says_why() {
+ let bin = tempfile::tempdir().unwrap();
+ for (name, body) in [
+ ("id", "exit 1"),
+ (
+ "useradd",
+ "echo 'useradd: cannot lock /etc/passwd' >&2; exit 1",
+ ),
+ ("adduser", "echo 'adduser: not found' >&2; exit 127"),
+ ] {
+ let p = bin.path().join(name);
+ std::fs::write(&p, format!("#!/bin/sh\n{body}\n")).unwrap();
+ std::fs::set_permissions(&p, std::fs::Permissions::from_mode(0o755)).unwrap();
+ }
+ let out = std::process::Command::new("/bin/sh")
+ .arg("-c")
+ .arg(super::create_user_script("user"))
+ .env("PATH", bin.path())
+ .output()
+ .unwrap();
+ assert_eq!(out.status.code(), Some(1));
+ let err = String::from_utf8_lossy(&out.stderr);
+ assert!(err.contains("useradd: cannot lock /etc/passwd"), "{err:?}");
+ }
+}
+
#[cfg(test)]
mod run_as_tests {
use super::*;
diff --git a/libs/cua/crates/cua-compat/src/guestfs.rs b/libs/cua/crates/cua-compat/src/guestfs.rs
index cff9c89b64..742e05b3b8 100644
--- a/libs/cua/crates/cua-compat/src/guestfs.rs
+++ b/libs/cua/crates/cua-compat/src/guestfs.rs
@@ -41,17 +41,29 @@ pub fn status_of(s: &tonic::Status) -> StatusCode {
/// The top-most ancestor of `path` (or `path` itself) that does not exist
/// yet, i.e. what a write with parents will create. `None`: it exists.
-pub async fn first_missing(c: &cua_spacesd_client::SpacesdClient, path: &str) -> Option<String> {
- let exists = |p: String| async move {
- !matches!(
- c.filesystem()
- .stat(pb::StatRequest {
- path: p,
- no_follow_symlinks: true, ..Default::default()
- })
- .await,
- Err(ref s) if s.code() == tonic::Code::NotFound
- )
+/// Looked up with root's rights, so a directory the agent may not enter
+/// does not hide what is missing below it.
+pub async fn first_missing(
+ c: &cua_spacesd_client::SpacesdClient,
+ driver: &str,
+ path: &str,
+) -> Option<String> {
+ let run_as = crate::guest::file_run_as(driver, "root");
+ let exists = |p: String| {
+ let run_as = run_as.clone();
+ async move {
+ !matches!(
+ c.filesystem()
+ .stat(pb::StatRequest {
+ path: p,
+ no_follow_symlinks: true,
+ run_as,
+ ..Default::default()
+ })
+ .await,
+ Err(ref s) if s.code() == tonic::Code::NotFound
+ )
+ }
};
if exists(path.to_string()).await {
return None;
@@ -142,7 +154,7 @@ impl<'a> Writer<'a> {
) -> Result<Writer<'a>, FsError> {
let staged = !crate::guest::without_sudo(driver);
let created_from = if !staged && !user.is_empty() && user != "root" {
- first_missing(c, path).await
+ first_missing(c, driver, path).await
} else {
None
};
@@ -159,11 +171,7 @@ impl<'a> Writer<'a> {
expected_size: 0,
expected_sha256: String::new(),
// An agent that switches users itself may not be root: name it.
- run_as: if driver == "root" {
- "root".into()
- } else {
- String::new()
- },
+ run_as: crate::guest::file_run_as(driver, "root"),
..Default::default()
};
let sink = if c.transport() == Transport::Native {
diff --git a/libs/cua/crates/cua-compat/tests/daytona_toolbox.rs b/libs/cua/crates/cua-compat/tests/daytona_toolbox.rs
index 997f8c663f..81d7549158 100644
--- a/libs/cua/crates/cua-compat/tests/daytona_toolbox.rs
+++ b/libs/cua/crates/cua-compat/tests/daytona_toolbox.rs
@@ -12,6 +12,7 @@ struct Gw {
http: reqwest::Client,
api: String,
id: String,
+ mock: Arc<MockBackend>,
_dir: tempfile::TempDir,
}
@@ -22,9 +23,10 @@ async fn start() -> Gw {
o.host_port = 0;
o.dir = Some(dir.path().to_path_buf());
o.create_default_user = false;
- let gw = Gateway::start(o, Some(Arc::new(MockBackend::new())))
- .await
- .unwrap();
+ // A user the mock guest has: file calls name it to the agent.
+ o.default_user = "alice".into();
+ let mock = Arc::new(MockBackend::new());
+ let gw = Gateway::start(o, Some(mock.clone())).await.unwrap();
let api = format!("http://{}/api", gw.api_addr);
let http = reqwest::Client::new();
let sb: Value = http
@@ -43,6 +45,7 @@ async fn start() -> Gw {
http,
api,
id,
+ mock,
_dir: dir,
}
}
@@ -223,3 +226,43 @@ async fn sandbox_level_errors_come_from_the_api_not_the_daemon() {
assert_eq!(r.status(), 404);
assert_eq!(r.json::<Value>().await.unwrap()["source"], "DAYTONA_API");
}
+
+#[tokio::test]
+async fn file_calls_name_the_sandbox_user_to_an_agent_that_switches_users() {
+ // The mock agent switches users by capability and is not root itself:
+ // a file call without `run_as` would run as the agent, not as the
+ // sandbox's user (`alice` here).
+ let g = start().await;
+ let r = g
+ .tb(
+ reqwest::Method::POST,
+ "/files/folder?path=/tmp/new/d&mode=755",
+ )
+ .send()
+ .await
+ .unwrap();
+ assert_eq!(r.status(), 201, "{}", r.text().await.unwrap());
+ g.upload("/tmp/m1", b"1").await;
+ let r = g
+ .tb(
+ reqwest::Method::POST,
+ "/files/move?source=/tmp/m1&destination=/tmp/m2",
+ )
+ .send()
+ .await
+ .unwrap();
+ assert_eq!(r.status(), 200, "{}", r.text().await.unwrap());
+ let r = g
+ .tb(reqwest::Method::DELETE, "/files?path=/tmp/m2")
+ .send()
+ .await
+ .unwrap();
+ assert_eq!(r.status(), 204);
+ let name = g.mock.created.lock().await[0].name.clone();
+ let st = g.mock.state(&name).await.unwrap();
+ let o = &st.observed;
+ assert_eq!(o.run_as_of("MakeDir", "/tmp/new/d"), ["alice"]);
+ assert_eq!(o.run_as_of("Stat", "/tmp/m2"), ["alice"]);
+ assert_eq!(o.run_as_of("Move", "/tmp/m1"), ["alice"]);
+ assert_eq!(o.run_as_of("Remove", "/tmp/m2"), ["alice"]);
+}
diff --git a/libs/cua/crates/cua-compat/tests/gateway.rs b/libs/cua/crates/cua-compat/tests/gateway.rs
index b171eb7a3d..8d0638f5b7 100644
--- a/libs/cua/crates/cua-compat/tests/gateway.rs
+++ b/libs/cua/crates/cua-compat/tests/gateway.rs
@@ -1080,3 +1080,103 @@ async fn set_timeout_zero_kills_before_it_answers() {
"gone the moment set_timeout(0) answered"
);
}
+
+#[tokio::test]
+async fn root_file_calls_name_root_to_an_agent_that_switches_users() {
+ // The mock agent switches users by capability and is not root itself
+ // (as the Linux image's `cua` agent): a file call without `run_as` runs
+ // as the agent. envd acts with root's rights, so each call names root,
+ // including cua-spacesd's own calls a guest without GNU tools gets.
+ let g = start(&[]).await;
+ let sb = g.sandbox(json!({"templateID": "base"})).await;
+ let name = g.mock.created.lock().await[0].name.clone();
+ let st = g.mock.state(&name).await.unwrap();
+ st.put_file("/tmp/r/a", b"1".to_vec());
+ let call = |method: &str, body: Value| {
+ g.envd(&sb, &format!("filesystem.Filesystem/{method}"))
+ .header("content-type", "application/json")
+ .header("authorization", "Basic cm9vdDo=")
+ .body(body.to_string())
+ .send()
+ };
+ for (method, body) in [
+ ("Stat", json!({"path": "/tmp/r/a"})),
+ ("ListDir", json!({"path": "/tmp/r", "depth": 1})),
+ ("MakeDir", json!({"path": "/tmp/r/d"})),
+ (
+ "Move",
+ json!({"source": "/tmp/r/a", "destination": "/tmp/r/b"}),
+ ),
+ ("Remove", json!({"path": "/tmp/r/b"})),
+ ] {
+ let r = call(method, body).await.unwrap();
+ assert_eq!(r.status(), 200, "{method}: {}", r.text().await.unwrap());
+ }
+ st.put_file("/tmp/r/c", b"2".to_vec());
+ let r = g
+ .http
+ .get(format!("{}/files?path=/tmp/r/c&username=root", g.base))
+ .header("e2b-sandbox-id", sb["sandboxID"].as_str().unwrap())
+ .header("x-access-token", sb["envdAccessToken"].as_str().unwrap())
+ .send()
+ .await
+ .unwrap();
+ assert_eq!(r.status(), 200);
+ assert_eq!(r.text().await.unwrap(), "2");
+ for (call, path) in [
+ ("Stat", "/tmp/r/a"),
+ ("ListDir", "/tmp/r"),
+ ("MakeDir", "/tmp/r/d"),
+ ("Move", "/tmp/r/a"),
+ ("Remove", "/tmp/r/b"),
+ ("ReadFile", "/tmp/r/c"),
+ ] {
+ let seen = st.observed.run_as_of(call, path);
+ assert!(!seen.is_empty(), "{call} {path} reached the agent");
+ assert!(seen.iter().all(|u| u == "root"), "{call} {path}: {seen:?}");
+ }
+}
+
+#[tokio::test]
+async fn native_file_calls_give_what_they_make_to_the_user() {
+ // Without the guest's `sh` scripts (the mock runs none), MakeDir and
+ // Move make directories as root; the ones a call created go to the
+ // request's user, and a moved file keeps its owner.
+ let g = start(&[]).await;
+ let sb = g.sandbox(json!({"templateID": "base"})).await;
+ let name = g.mock.created.lock().await[0].name.clone();
+ let st = g.mock.state(&name).await.unwrap();
+ st.put_file("/tmp/a", b"1".to_vec());
+ for (method, body) in [
+ ("MakeDir", json!({"path": "/tmp/new/d"})),
+ (
+ "Move",
+ json!({"source": "/tmp/a", "destination": "/tmp/moved/a"}),
+ ),
+ ] {
+ let r = g
+ .envd(&sb, &format!("filesystem.Filesystem/{method}"))
+ .header("content-type", "application/json")
+ .header("authorization", "Basic YWxpY2U6")
+ .body(body.to_string())
+ .send()
+ .await
+ .unwrap();
+ assert_eq!(r.status(), 200, "{method}: {}", r.text().await.unwrap());
+ }
+ let chowns: Vec<Vec<String>> = st
+ .started_processes()
+ .iter()
+ .filter_map(|p| p.config.as_ref())
+ .filter(|c| c.command == "chown")
+ .map(|c| c.args.clone())
+ .collect();
+ assert_eq!(
+ chowns,
+ [["-R", "alice:", "/tmp/new"], ["-R", "alice:", "/tmp/moved"]]
+ );
+ // The parent was made before the move, not by it, and what the calls
+ // created was looked up as root.
+ assert_eq!(st.observed.run_as_of("MakeDir", "/tmp/moved"), ["root"]);
+ assert_eq!(st.observed.run_as_of("Stat", "/tmp/new"), ["root"]);
+}
diff --git a/libs/cua/crates/cua-spacesd-client/src/testing.rs b/libs/cua/crates/cua-spacesd-client/src/testing.rs
index a52f78f023..18f0ded523 100644
--- a/libs/cua/crates/cua-spacesd-client/src/testing.rs
+++ b/libs/cua/crates/cua-spacesd-client/src/testing.rs
@@ -107,6 +107,35 @@ pub struct Observed {
pub accessibility: Mutex<Vec<String>>,
/// Screenshot requests.
pub screenshots: Mutex<Vec<pb::ScreenshotRequest>>,
+ /// `(call, path, run_as)` of every `Stat`, `ListDir`, `MakeDir`, `Move`
+ /// (the source), `Remove` and `ReadFile`, in order.
+ pub fs_run_as: Mutex<Vec<(String, String, String)>>,
+}
+
+impl Observed {
+ /// The `run_as` of each recorded `call` on `path`.
+ pub fn run_as_of(&self, call: &str, path: &str) -> Vec<String> {
+ self.fs_run_as
+ .lock()
+ .unwrap()
+ .iter()
+ .filter(|(c, p, _)| c == call && p == path)
+ .map(|(_, _, u)| u.clone())
+ .collect()
+ }
+}
+
+impl Svc {
+ /// Records a file call's `run_as`, then checks it.
+ fn run_as(&self, call: &str, path: &str, user: &str) -> Result<(), Status> {
+ self.0
+ .observed
+ .fs_run_as
+ .lock()
+ .unwrap()
+ .push((call.into(), path.into(), user.into()));
+ check_run_as(user)
+ }
}
/// What the mock records about a file besides its bytes: the user it was
@@ -120,8 +149,9 @@ struct FileAttrs {
/// Users the mock's guest has. `run_as` of any other user is
/// `INVALID_ARGUMENT`, like a real guest without that account; `locked` is a
-/// user the agent may not act as (`PERMISSION_DENIED`).
-pub const MOCK_USERS: &[&str] = &["root", "mock", "cua", "alice", "bob"];
+/// user the agent may not act as (`PERMISSION_DENIED`). `daytona` is the
+/// sandbox user the Daytona gateway creates on a real guest.
+pub const MOCK_USERS: &[&str] = &["root", "mock", "cua", "alice", "bob", "daytona"];
/// The user whose identity the mock's agent refuses to take.
pub const MOCK_LOCKED_USER: &str = "locked";
/// The user the mock agent runs as unless `run_as_mode` is `root`, like the
@@ -1928,7 +1958,7 @@ impl FilesystemService for Svc {
req: tonic::Request<pb::StatRequest>,
) -> Result<tonic::Response<pb::StatResponse>, Status> {
let req = req.into_inner();
- check_run_as(&req.run_as)?;
+ self.run_as("Stat", &req.path, &req.run_as)?;
let namespace = mock_namespace(&req.xattr_namespace)?;
let path = req.path;
if self.0.is_dir(&path) {
@@ -1957,7 +1987,7 @@ impl FilesystemService for Svc {
req: tonic::Request<pb::ListDirRequest>,
) -> Result<tonic::Response<pb::ListDirResponse>, Status> {
let req = req.into_inner();
- check_run_as(&req.run_as)?;
+ self.run_as("ListDir", &req.path, &req.run_as)?;
let namespace = mock_namespace(&req.xattr_namespace)?;
let dir = req.path.trim_end_matches('/').to_string() + "/";
// Entries at most `depth` levels below `dir` (0: no limit, the
@@ -2003,7 +2033,7 @@ impl FilesystemService for Svc {
req: tonic::Request<pb::MakeDirRequest>,
) -> Result<tonic::Response<pb::MakeDirResponse>, Status> {
let req = req.into_inner();
- check_run_as(&req.run_as)?;
+ self.run_as("MakeDir", &req.path, &req.run_as)?;
let path = req.path.trim_end_matches('/').to_string();
let created = !self.0.is_dir(&path);
{
@@ -2040,7 +2070,7 @@ impl FilesystemService for Svc {
req: tonic::Request<pb::MoveRequest>,
) -> Result<tonic::Response<pb::MoveResponse>, Status> {
let req = req.into_inner();
- check_run_as(&req.run_as)?;
+ self.run_as("Move", &req.source, &req.run_as)?;
let mut files = self.0.files.lock().unwrap();
let data = files.remove(&req.source).ok_or_else(|| {
fs_err(
@@ -2068,7 +2098,7 @@ impl FilesystemService for Svc {
req: tonic::Request<pb::RemoveRequest>,
) -> Result<tonic::Response<pb::RemoveResponse>, Status> {
let req = req.into_inner();
- check_run_as(&req.run_as)?;
+ self.run_as("Remove", &req.path, &req.run_as)?;
let path = req.path.trim_end_matches('/').to_string();
self.0.file_attrs.lock().unwrap().remove(&path);
let removed = self.0.files.lock().unwrap().remove(&path);
@@ -2136,7 +2166,7 @@ impl FilesystemService for Svc {
req: tonic::Request<pb::ReadFileRequest>,
) -> Result<tonic::Response<Self::ReadFileStream>, Status> {
let req = req.into_inner();
- check_run_as(&req.run_as)?;
+ self.run_as("ReadFile", &req.path, &req.run_as)?;
let namespace = mock_namespace(&req.xattr_namespace)?;
let data = self.0.file(&req.path).ok_or_else(|| {
fs_err(