Skip to content

Quickly sandbox your AI agent.

Python

Merge multi-user support with streaming stdin

Tyler Payne3b0cce05d685
diff --cc docs/under-the-hood/03-running-commands.md
index 9aab076,41b5d3f..d6fcbd3
--- a/docs/under-the-hood/03-running-commands.md
+++ b/docs/under-the-hood/03-running-commands.md
@@@ -77,31 -70,3 +77,45 @@@ data: {"stream": "exit", "exit_code": 0
```
The HTTP connection stays open until the command finishes. Callbacks fire for each chunk as it arrives.
+
+## Incremental stdin
+
+Authentication responses advertise `capabilities: ["stdin_streaming"]` when the
+guest supports input streaming. The host requires this capability before
+starting a command with stdin, so old agents cannot silently ignore the input.
+
+The host adds a unique `stdin_id` to `execute_stream`. Once the process and its
+input channel are ready, the agent sends `{"stream": "ready"}`. The host then
+sends separate `stdin` requests (HTTP `POST /stdin` or serial method `stdin`):
+
+```json
+{"stdin_id": "<execution>", "data": "<base64-encoded bytes>"}
+```
+
+Each chunk contains at most 64 KiB of decoded input. The agent acknowledges it
+after writing to the child pipe, and the host waits for that acknowledgement
+before requesting more input. Exhausting the input iterable sends
+`{"stdin_id": "<execution>", "eof": true}` to close the pipe.
+
+Input and cancellation requests bypass the HTTP execution lock and remain
+available during exclusive commands. They are not retried: replaying a write
+after a lost acknowledgement could duplicate input. Output continues on the
+original stream while input is being supplied.
+
+Cancellation uses HTTP `POST /cancel` or serial method `cancel`, with the same
+`stdin_id`. The agent terminates the execution's process group and releases its
+input and exclusive-command state. Guest timeouts perform the same cleanup.
++
++## Guest user identity
++
++Both execution methods accept an optional `user`. The guest resolves the account
++before launching a command, sets `HOME`, `USER`, and `LOGNAME`, and changes to its
++home unless `cwd` is supplied. Before executing the shell, the child initializes
++supplementary groups and drops its GID and UID. This also applies to commands
++with streaming stdin; input is written to the already user-scoped child pipe.
++
++The authenticated `create_user` and `delete_user` methods (or HTTP endpoints with
++the same names) manage guest accounts. They serialize updates to the guest
++account files. Deletion stops that user's processes and optionally removes the
++home directory. Accounts share the guest kernel and filesystem; they do not
++create additional VM isolation.
diff --cc docs/user-guide/03-running-commands.md
index 4d47ac5,ad3b006..50874e6
--- a/docs/user-guide/03-running-commands.md
+++ b/docs/user-guide/03-running-commands.md
@@@ -52,51 -52,8 +52,77 @@@ result = await sb.execute
)
```
-The callbacks receive chunks of output in real time via Server-Sent Events. The final `ExecuteResult` still contains the complete stdout/stderr.
+The callbacks receive chunks of output in real time over virtio-serial, or via
+Server-Sent Events when using the HTTP fallback. The final `ExecuteResult` still
+contains the complete stdout/stderr.
+
+## Streaming stdin
+
+Pass an async iterable of byte chunks to feed a running command incrementally:
+
+```python
+async def input_chunks():
+ yield b"first line\n"
+ yield b"second line\n"
+
+result = await sb.execute(
+ "cat",
+ stdin=input_chunks(),
+ on_stdout=lambda chunk: print(chunk, end=""),
+)
+```
+
+The producer is advanced as the guest accepts input, rather than being buffered
+in full. Output callbacks run concurrently, so the producer can wait for output
+before supplying its next chunk. Finishing the iterable closes stdin (EOF).
+
+For small inputs, `stdin` also accepts `bytes` or a UTF-8 string:
+
+```python
+result = await sb.execute("wc -c", stdin=b"hello")
+result = await sb.execute("cat", stdin="hello\n")
+result = await sb.execute("cat", stdin=b"") # Send EOF immediately
+```
+
+Async iterables must yield `bytes`, including for binary data. Quicksand splits
+large chunks automatically. Omitting `stdin` preserves the usual execution
+behavior.
+
+Input consumption stops when the command exits. Cancelling the call or reaching
+its timeout terminates the stdin-enabled command's process group. Exceptions
+from the input producer propagate to the caller after the command is cancelled.
+
+Streaming stdin requires a guest image whose agent advertises the
+`stdin_streaming` capability. Older images return an explicit error without
+starting the command or consuming input. Update or rebuild the image with the
+new guest agent; upgrading the host Python package alone is not sufficient.
+
++## Running as separate users
++
++Create guest OS accounts when multiple workloads should have separate home
++directories and file ownership within one VM:
++
++```python
++alice = await sb.create_user("alice")
++result = await alice.execute("cat > input.txt", stdin=b"hello\n")
++print(alice.uid, alice.gid, alice.home)
++
++# Equivalent explicit user selection:
++result = await sb.execute("cat input.txt", user="alice")
++
++await sb.delete_user("alice") # Stops the user's processes and removes its home
++```
++
++User-scoped commands run with that account's UID, GID, supplementary groups, and
++`HOME`, `USER`, and `LOGNAME`. The working directory defaults to the user's home;
++an explicit `cwd` overrides it. `SandboxUser.execute()` accepts the same stdin
++and output-streaming options as `Sandbox.execute()`.
++
++Usernames must match `[a-z_][a-z0-9_-]*` and contain at most 32 characters.
++Pass `remove_home=False` to `delete_user()` to keep the home directory. These are
++ordinary OS accounts sharing one VM, not separate VM isolation boundaries.
++Creating users requires an image containing the updated guest agent.
+
## Multi-step workflows
Commands run in independent shell sessions. There's no persistent shell state between calls. Use `&&` to chain commands, or write a script.
diff --cc packages/contrib/quicksand-alpine/hatch_build.py
index e46498d,e46498d..79701cb
--- a/packages/contrib/quicksand-alpine/hatch_build.py
+++ b/packages/contrib/quicksand-alpine/hatch_build.py
@@@ -42,9 -42,9 +42,9 @@@ class AlpineImageBuildHook(BuildHookInt
image_path = images_dir / f"alpine-{distro_version}-{arch}.qcow2"
dockerfile_path = Path(self.root) / "quicksand_alpine" / "docker" / "Dockerfile"
-- if not image_path.exists():
-- self.app.display_info(f"Image not found: {image_path.name}, building...")
-- self._build_image(dockerfile_path, image_path)
++ # build_image checks the Dockerfile and agent-source hash before reusing an image.
++ self.app.display_info(f"Ensuring image is up to date: {image_path.name}")
++ self._build_image(dockerfile_path, image_path)
self.app.display_info(f"Including image: {image_path}")
diff --cc packages/dev/quicksand-image-tools/quicksand_image_tools/agent-openapi.yaml
index 381b3d3,eb6ae2b..2e363d9
--- a/packages/dev/quicksand-image-tools/quicksand_image_tools/agent-openapi.yaml
+++ b/packages/dev/quicksand-image-tools/quicksand_image_tools/agent-openapi.yaml
@@@ -83,88 -62,6 +83,122 @@@ components
type: string
nullable: true
description: Working directory for command execution
+ exclusive:
+ type: boolean
+ default: false
+ description: Reject other execution requests while this command runs
++ user:
++ type: string
++ nullable: true
++ description: |
++ Existing guest OS account to run as, using its UID, GID,
++ supplementary groups, HOME, USER, and LOGNAME. When cwd is omitted,
++ it defaults to this user's home. Applies to both execution methods,
++ including stdin-enabled execution.
++
++ UserRequest:
++ type: object
++ required: [name]
++ properties:
++ name:
++ type: string
++ pattern: '^[a-z_][a-z0-9_-]*$'
++ maxLength: 32
++ remove_home:
++ type: boolean
++ default: false
++ description: |
++ Used by delete_user. The Python API defaults this to true and sends
++ it explicitly; the wire default when omitted is false.
++
++ UserCreatedResponse:
++ type: object
++ required: [uid, gid, home]
++ properties:
++ uid:
++ type: integer
++ gid:
++ type: integer
++ home:
++ type: string
+
+ StdinId:
+ type: string
+ pattern: '^[0-9a-fA-F]{32}$'
+ description: Random UUID hex string identifying one stdin-enabled execution
+
+ ExecuteStreamRequest:
+ allOf:
+ - $ref: '#/components/schemas/ExecuteRequest'
+ - type: object
+ properties:
+ stdin_id:
+ $ref: '#/components/schemas/StdinId'
+ shell:
+ type: string
+ default: /bin/sh
+ description: |
+ Shell executable for stdin-enabled execution, invoked with -c.
+ Without stdin_id, execution retains the legacy /bin/sh behavior.
+
+ StdinRequest:
+ oneOf:
+ - type: object
+ additionalProperties: false
+ required: [stdin_id, data]
+ properties:
+ stdin_id:
+ $ref: '#/components/schemas/StdinId'
+ data:
+ type: string
+ contentEncoding: base64
+ maxLength: 87384
+ description: |
+ Standard padded base64, decoding to at most 65536 bytes.
+ Empty data is allowed and is not EOF. Invalid base64, oversized
+ decoded chunks, and data combined with eof are rejected.
+ - type: object
+ additionalProperties: false
+ required: [stdin_id, eof]
+ properties:
+ stdin_id:
+ $ref: '#/components/schemas/StdinId'
+ eof:
+ type: boolean
+ const: true
+ description: Close the child's stdin pipe; false or null is invalid
+
+ StdinResponse:
+ type: object
+ required: [closed]
+ properties:
+ closed:
+ type: boolean
+ description: |
+ False only after the entire chunk has actually been written to the
+ child pipe, not merely queued. True after EOF or if input is already
+ closed, the child exited, or stdin_id is absent/completed. A broken
+ pipe is closed input, not a failure of an otherwise successful command.
+ EOF/BrokenPipe closes only stdin: stdin_id remains cancellable while
+ the command continues processing, until execution cleanup completes.
+
+ CancelRequest:
+ type: object
+ additionalProperties: false
+ required: [stdin_id]
+ properties:
+ stdin_id:
+ $ref: '#/components/schemas/StdinId'
+
+ CancelResponse:
+ type: object
+ required: [cancelled]
+ properties:
+ cancelled:
+ type: boolean
+ description: |
+ True after cancelling a live stdin execution and completing its
+ process cleanup. False when absent, completed, or already cancelled.
ExecuteResponse:
type: object
@@@ -322,108 -198,7 +356,163 @@@ paths
application/json:
schema:
$ref: '#/components/schemas/ErrorResponse'
+ '400':
+ description: Invalid stdin_id or stdin-enabled execution parameters
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/ErrorResponse'
+ '409':
+ description: stdin_id is already active
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/ErrorResponse'
+ '503':
+ description: An exclusive command is already running
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/ErrorResponse'
+
+ /stdin:
+ post:
+ summary: Write an acknowledged binary stdin chunk or close stdin
+ description: |
+ Requires bearer authentication, including while an exclusive command
+ runs. Submit either a base64 data chunk or eof: true, never both.
+ Hosts send one chunk at a time and await its acknowledgement. Do not
+ retry requests: chunks are not deduplicated. Buffering is bounded;
+ excess concurrent writes are rejected rather than queued indefinitely.
+ On closed: true, stop producing input and await the execution's final
+ output. When the input iterable is exhausted, send eof: true.
+ requestBody:
+ required: true
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/StdinRequest'
+ responses:
+ '200':
+ description: Chunk written, EOF applied, or input already closed
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/StdinResponse'
+ '400':
+ description: Malformed request, invalid base64, or decoded chunk over 65536 bytes
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/ErrorResponse'
+ '401':
+ description: Invalid or missing token
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/ErrorResponse'
+ '409':
+ description: A stdin request is already pending and the bounded queue is full
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/ErrorResponse'
+ '500':
+ description: Unexpected pipe write error
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/ErrorResponse'
+
+ /cancel:
+ post:
+ summary: Cancel a stdin-enabled execution and clean up its process group
+ description: |
+ Requires bearer authentication. Works during exclusive execution and
+ while a stdin write is blocked. Hosts cancel when their input producer
+ raises or the execute operation is cancelled. Unrelated executions
+ are not cancelled.
+ requestBody:
+ required: true
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/CancelRequest'
+ responses:
+ '200':
+ description: Execution cancelled and reaped, or already absent/completed
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/CancelResponse'
+ '400':
+ description: Malformed cancel request or invalid stdin_id
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/ErrorResponse'
+ '401':
+ description: Invalid or missing token
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/ErrorResponse'
+
++ /create_user:
++ post:
++ summary: Create a guest OS account with a private home directory
++ requestBody:
++ required: true
++ content:
++ application/json:
++ schema:
++ $ref: '#/components/schemas/UserRequest'
++ responses:
++ '200':
++ description: Account created
++ content:
++ application/json:
++ schema:
++ $ref: '#/components/schemas/UserCreatedResponse'
++ '400':
++ description: Invalid or existing username, or account creation failed
++ content:
++ application/json:
++ schema:
++ $ref: '#/components/schemas/ErrorResponse'
++ '401':
++ description: Invalid or missing token
++
++ /delete_user:
++ post:
++ summary: Stop a guest user's processes and remove the account
++ requestBody:
++ required: true
++ content:
++ application/json:
++ schema:
++ $ref: '#/components/schemas/UserRequest'
++ responses:
++ '200':
++ description: Account removed
++ content:
++ application/json:
++ schema:
++ type: object
++ required: [removed]
++ properties:
++ removed:
++ type: boolean
++ const: true
++ '400':
++ description: Invalid or missing username, or account deletion failed
++ content:
++ application/json:
++ schema:
++ $ref: '#/components/schemas/ErrorResponse'
++ '401':
++ description: Invalid or missing token
+
/ping:
get:
summary: Health check
diff --cc packages/dev/quicksand-image-tools/quicksand_image_tools/quicksand-guest-agent/Cargo.toml
index 17bbb91,074cb1a..419a5e5
--- a/packages/dev/quicksand-image-tools/quicksand_image_tools/quicksand-guest-agent/Cargo.toml
+++ b/packages/dev/quicksand-image-tools/quicksand_image_tools/quicksand-guest-agent/Cargo.toml
@@@ -24,11 -23,10 +24,13 @@@ tokio-stream = "0.1
# single open handle and a buffered `tokio::fs::File` seeks when reads and
# writes interleave (ESPIPE on a non-seekable char device), so the transport
# drives one non-blocking fd through `tokio::io::unix::AsyncFd` instead.
+ # Also used for privilege drop (setuid/setgid/initgroups) and chown/kill in
+ # multi-user mode.
libc = "0.2"
+[dev-dependencies]
+tower = { version = "0.5", features = ["util"] }
+
[profile.release]
opt-level = "z" # Optimize for size
lto = true # Link-time optimization
diff --cc packages/dev/quicksand-image-tools/quicksand_image_tools/quicksand-guest-agent/src/main.rs
index baecc02,e197386..11cb4cf
--- a/packages/dev/quicksand-image-tools/quicksand_image_tools/quicksand-guest-agent/src/main.rs
+++ b/packages/dev/quicksand-image-tools/quicksand_image_tools/quicksand-guest-agent/src/main.rs
@@@ -113,23 -96,13 +116,29 @@@ struct ExecuteRequest
/// When true, reject all other execute requests while this one is running.
#[serde(default)]
exclusive: bool,
+ shell: Option<String>,
+ stdin_id: Option<String>,
+ /// Optional OS user to run the command as. When set, the command is
+ /// executed with that user's uid/gid/groups and HOME, defaulting cwd to
+ /// the user's home directory.
+ #[serde(default)]
+ user: Option<String>,
}
+impl ExecuteRequest {
+ fn into_stdin_execution(self) -> ExecutionRequest {
+ ExecutionRequest {
+ stdin_id: self.stdin_id.expect("stdin_id was checked"),
+ command: self.command,
+ shell: self.shell.unwrap_or_else(|| "/bin/sh".into()),
+ cwd: self.cwd,
++ user: self.user,
+ timeout: self.timeout,
+ exclusive: self.exclusive,
+ }
+ }
+}
+
fn default_timeout() -> f64 {
30.0
}
@@@ -176,6 -164,231 +200,233 @@@ fn verify_token(headers: &axum::http::H
}
}
+ // ============================================================================
+ // Multi-user support
+ // ============================================================================
+ //
+ // Users are managed by editing the standard POSIX account files directly
+ // (/etc/passwd, /etc/group, /etc/shadow). This keeps the behaviour identical
+ // across every distro (Alpine, Ubuntu, ...) because those formats are
+ // standardised and every minimal guest defaults to the `files` nsswitch
+ // backend — no dependency on distro-specific `adduser`/`useradd` tools.
+
+ /// uid/gid range for quicksand-managed users.
+ const UID_MIN: u32 = 1000;
+ const UID_MAX: u32 = 60000;
+
+ /// Serializes account-file mutations so concurrent create/delete requests
+ /// (the agent multiplexes requests) can't produce a torn /etc/passwd write.
+ static USER_MGMT_LOCK: Mutex<()> = Mutex::new(());
+
+ #[derive(Clone)]
+ struct PwEntry {
+ uid: u32,
+ gid: u32,
+ home: String,
+ }
+
+ /// Look up an existing user in /etc/passwd. Returns None if absent.
+ fn lookup_user(name: &str) -> Option<PwEntry> {
+ let content = fs::read_to_string("/etc/passwd").ok()?;
+ for line in content.lines() {
+ let f: Vec<&str> = line.split(':').collect();
+ if f.len() >= 7 && f[0] == name {
+ return Some(PwEntry {
+ uid: f[2].parse().ok()?,
+ gid: f[3].parse().ok()?,
+ home: f[5].to_string(),
+ });
+ }
+ }
+ None
+ }
+
+ /// Validate a username to prevent injection into the colon/newline-delimited
+ /// account files. POSIX-portable subset: starts with [a-z_], then [a-z0-9_-].
+ fn valid_username(name: &str) -> bool {
+ !name.is_empty()
+ && name.len() <= 32
+ && name.bytes().enumerate().all(|(i, b)| match b {
+ b'a'..=b'z' | b'_' => true,
+ b'0'..=b'9' | b'-' if i > 0 => true,
+ _ => false,
+ })
+ }
+
+ /// Highest id in [UID_MIN, UID_MAX) across passwd+group, plus one.
+ fn next_free_id() -> u32 {
+ let mut max = UID_MIN - 1;
+ for (path, field) in [("/etc/passwd", 2usize), ("/etc/group", 2usize)] {
+ if let Ok(content) = fs::read_to_string(path) {
+ for line in content.lines() {
+ let f: Vec<&str> = line.split(':').collect();
+ if f.len() > field {
+ if let Ok(id) = f[field].parse::<u32>() {
+ if (UID_MIN..UID_MAX).contains(&id) && id > max {
+ max = id;
+ }
+ }
+ }
+ }
+ }
+ }
+ max + 1
+ }
+
+ fn append_line(path: &str, line: &str) -> std::io::Result<()> {
+ let mut f = fs::OpenOptions::new().append(true).create(true).open(path)?;
+ f.write_all(line.as_bytes())?;
+ f.write_all(b"\n")
+ }
+
+ fn remove_lines_for_user(path: &str, name: &str) -> std::io::Result<()> {
+ let content = match fs::read_to_string(path) {
+ Ok(c) => c,
+ Err(_) => return Ok(()), // file may not exist (e.g. shadow); nothing to do
+ };
+ let prefix = format!("{}:", name);
+ let mut out: String = content
+ .lines()
+ .filter(|l| !l.starts_with(&prefix))
+ .collect::<Vec<_>>()
+ .join("\n");
+ if !out.is_empty() {
+ out.push('\n');
+ }
+ fs::write(path, out)
+ }
+
+ /// SIGKILL every process owned by `uid` (each /proc/<pid> dir is owned by the
+ /// process's real uid).
+ fn kill_user_processes(uid: u32) {
+ if let Ok(entries) = fs::read_dir("/proc") {
+ for entry in entries.flatten() {
+ let fname = entry.file_name();
+ let pid = match fname.to_string_lossy().parse::<i32>() {
+ Ok(p) => p,
+ Err(_) => continue,
+ };
+ if let Ok(meta) = fs::metadata(format!("/proc/{}", pid)) {
+ if meta.uid() == uid {
+ unsafe {
+ libc::kill(pid, libc::SIGKILL);
+ }
+ }
+ }
+ }
+ }
+ }
+
+ /// Create a new user account (distro-agnostic, native file manipulation).
+ fn create_user(name: &str) -> Result<PwEntry, String> {
+ let _guard = USER_MGMT_LOCK.lock().unwrap();
+
+ if !valid_username(name) {
+ return Err(format!("Invalid username: {}", name));
+ }
+ if lookup_user(name).is_some() {
+ return Err(format!("User already exists: {}", name));
+ }
+
+ let id = next_free_id();
+ if id >= UID_MAX {
+ return Err("No free uid available".to_string());
+ }
+ let home = format!("/home/{}", name);
+
+ // group: name:x:gid:
+ append_line("/etc/group", &format!("{}:x:{}:", name, id))
+ .map_err(|e| format!("write /etc/group: {}", e))?;
+ // passwd: name:x:uid:gid:gecos:home:shell (gecos empty; /bin/sh is universal)
+ append_line(
+ "/etc/passwd",
+ &format!("{}:x:{}:{}::{}:/bin/sh", name, id, id, home),
+ )
+ .map_err(|e| format!("write /etc/passwd: {}", e))?;
+ // shadow: locked password (`!`); we never password-auth, only setuid.
+ let _ = append_line("/etc/shadow", &format!("{}:!::0:99999:7:::", name));
+
+ fs::create_dir_all(&home).map_err(|e| format!("create {}: {}", home, e))?;
+ let c_home = CString::new(home.as_str()).map_err(|e| e.to_string())?;
+ unsafe {
+ if libc::chown(c_home.as_ptr(), id as _, id as _) != 0 {
+ return Err(format!("chown {}: {}", home, std::io::Error::last_os_error()));
+ }
+ }
+ fs::set_permissions(&home, fs::Permissions::from_mode(0o700))
+ .map_err(|e| format!("chmod {}: {}", home, e))?;
+
+ Ok(PwEntry { uid: id, gid: id, home })
+ }
+
+ /// Delete a user: kill its processes, strip account-file entries, optionally
+ /// remove its home directory.
+ fn delete_user(name: &str, remove_home: bool) -> Result<(), String> {
+ let _guard = USER_MGMT_LOCK.lock().unwrap();
+
+ if !valid_username(name) {
+ return Err(format!("Invalid username: {}", name));
+ }
+ let pw = lookup_user(name).ok_or_else(|| format!("No such user: {}", name))?;
+
+ kill_user_processes(pw.uid);
+
+ remove_lines_for_user("/etc/passwd", name).map_err(|e| format!("edit /etc/passwd: {}", e))?;
+ remove_lines_for_user("/etc/group", name).map_err(|e| format!("edit /etc/group: {}", e))?;
+ let _ = remove_lines_for_user("/etc/shadow", name);
+
+ if remove_home {
+ let _ = fs::remove_dir_all(&pw.home);
+ }
+ Ok(())
+ }
+
+ /// Resolve an optional username into a `PwEntry`, returning an error string if
+ /// the user is requested but doesn't exist.
+ fn resolve_user(user: &Option<String>) -> Result<Option<(String, PwEntry)>, String> {
+ match user {
+ None => Ok(None),
+ Some(u) => match lookup_user(u) {
+ Some(pw) => Ok(Some((u.clone(), pw))),
+ None => Err(format!("No such user: {}", u)),
+ },
+ }
+ }
+
-/// Configure a Command (std or tokio) to run as `name`/`pw`: set HOME/USER and
-/// register a pre_exec hook that, in order, joins the user's supplementary
-/// groups then drops gid and uid. Everything happens while still root in the
-/// forked child, before exec — ordering is explicit so the privilege drop is
-/// correct regardless of std internals.
-macro_rules! configure_user {
- ($cmd:expr, $pw:expr, $name:expr) => {{
- let pw_ref: &PwEntry = $pw;
- let nm: &str = $name;
- let uid = pw_ref.uid;
- let gid = pw_ref.gid;
- let name_c = CString::new(nm).expect("validated username");
- $cmd.env("HOME", &pw_ref.home).env("USER", nm).env("LOGNAME", nm);
++/// Configure std commands and tokio commands (via `as_std_mut`) identically:
++/// explicit cwd overrides the user's home, and the child joins supplementary
++/// groups before dropping gid and uid. The privilege drop happens only in
++/// pre_exec, while the forked child is still root.
++fn configure_user(cmd: &mut Command, cwd: Option<&str>, user_pw: Option<&(String, PwEntry)>) {
++ if let Some(cwd) = cwd {
++ cmd.current_dir(cwd);
++ } else if let Some((_, pw)) = user_pw {
++ cmd.current_dir(&pw.home);
++ }
++ if let Some((name, pw)) = user_pw {
++ let uid = pw.uid;
++ let gid = pw.gid;
++ let name_c = CString::new(name.as_str()).expect("validated username");
++ cmd.env("HOME", &pw.home).env("USER", name).env("LOGNAME", name);
+ unsafe {
- $cmd.pre_exec(move || {
++ cmd.pre_exec(move || {
+ // `as _` adapts to the target's libc types (e.g. initgroups'
+ // basegroup is gid_t on Linux but c_int on macOS).
+ if libc::initgroups(name_c.as_ptr(), gid as _) != 0 {
+ return Err(std::io::Error::last_os_error());
+ }
+ if libc::setgid(gid as _) != 0 {
+ return Err(std::io::Error::last_os_error());
+ }
+ if libc::setuid(uid as _) != 0 {
+ return Err(std::io::Error::last_os_error());
+ }
+ Ok(())
+ });
+ }
- }};
++ }
+ }
+
// ============================================================================
// Handlers
// ============================================================================
@@@ -236,9 -456,14 +494,7 @@@ async fn execute
cmd.stdout(Stdio::piped());
cmd.stderr(Stdio::piped());
-- if let Some(cwd) = &req.cwd {
-- cmd.current_dir(cwd);
- } else if let Some((_, pw)) = &user_pw {
- cmd.current_dir(&pw.home);
- }
- if let Some((name, pw)) = &user_pw {
- configure_user!(cmd, pw, name.as_str());
-- }
++ configure_user(&mut cmd, req.cwd.as_deref(), user_pw.as_ref());
cmd.output()
})
@@@ -279,22 -504,12 +535,28 @@@ async fn execute_stream
return e.into_response();
}
+ if req.stdin_id.is_some() {
+ let output = match state.stdin_executions.start(
+ req.into_stdin_execution(),
+ Arc::clone(&state.exclusive_busy),
+ ) {
+ Ok(output) => output,
+ Err(error) => return stdin_request_error(error),
+ };
+ let stream = ReceiverStream::new(output).map(|event| {
+ Ok::<_, Infallible>(
+ Event::default().data(serde_json::to_string(&event).expect("serializable output")),
+ )
+ });
+ return Sse::new(stream).into_response();
+ }
+
+ // Resolve the target user (if any) before touching the exclusive lock.
+ let user_pw = match resolve_user(&req.user) {
+ Ok(v) => v,
+ Err(e) => return (StatusCode::BAD_REQUEST, Json(ErrorResponse { detail: e })).into_response(),
+ };
+
// Reject if an exclusive command is already running.
if state.exclusive_busy.load(Ordering::SeqCst) {
return (
@@@ -335,9 -550,14 +597,7 @@@
cmd.stdout(Stdio::piped());
cmd.stderr(Stdio::piped());
-- if let Some(cwd) = &req.cwd {
-- cmd.current_dir(cwd);
- } else if let Some((_, pw)) = &user_pw {
- cmd.current_dir(&pw.home);
- }
- if let Some((name, pw)) = &user_pw {
- configure_user!(cmd, pw, name.as_str());
-- }
++ configure_user(cmd.as_std_mut(), req.cwd.as_deref(), user_pw.as_ref());
let mut child = match cmd.spawn() {
Ok(c) => c,
@@@ -490,7 -696,23 +786,12 @@@ struct ExecResult
exit_code: i32,
}
- async fn run_command(command: &str, timeout_secs: f64, cwd: Option<&str>) -> ExecResult {
+ async fn run_command(
+ command: &str,
+ timeout_secs: f64,
+ cwd: Option<&str>,
- user: Option<&str>,
++ user_pw: Option<&(String, PwEntry)>,
+ ) -> ExecResult {
- let user_pw = match resolve_user(&user.map(|s| s.to_string())) {
- Ok(v) => v,
- Err(e) => {
- return ExecResult {
- stdout: String::new(),
- stderr: e,
- exit_code: -1,
- }
- }
- };
-
let timeout_duration = Duration::from_secs_f64(timeout_secs);
let result = timeout(timeout_duration, async {
@@@ -498,9 -720,14 +799,7 @@@
cmd.arg("-c").arg(command);
cmd.stdout(Stdio::piped());
cmd.stderr(Stdio::piped());
-- if let Some(dir) = cwd {
-- cmd.current_dir(dir);
- } else if let Some((_, pw)) = &user_pw {
- cmd.current_dir(&pw.home);
- }
- if let Some((name, pw)) = &user_pw {
- configure_user!(cmd, pw, name.as_str());
-- }
++ configure_user(&mut cmd, cwd, user_pw);
cmd.output()
})
.await;
@@@ -737,8 -942,9 +1036,17 @@@ async fn serve_virtio_serial
let command = params.get("command").and_then(|v| v.as_str()).unwrap_or("").to_string();
let timeout_secs = params.get("timeout").and_then(|v| v.as_f64()).unwrap_or(30.0);
let cwd = params.get("cwd").and_then(|v| v.as_str()).map(|s| s.to_string());
+ let user = params.get("user").and_then(|v| v.as_str()).map(|s| s.to_string());
let is_exclusive = params.get("exclusive").and_then(|v| v.as_bool()).unwrap_or(false);
++ let user_pw = match resolve_user(&user) {
++ Ok(v) => v,
++ Err(e) => {
++ send_frame(&tx, serde_json::json!({"id": id, "result": {"stdout": "", "stderr": e, "exit_code": -1}}));
++ continue;
++ }
++ };
++
if exclusive_busy.load(Ordering::SeqCst) {
send_frame(&tx, serde_json::json!({"id": id, "error": {"message": "Exclusive command in progress"}}));
continue;
@@@ -755,7 -961,8 +1063,8 @@@
let tx = tx.clone();
let exclusive_busy = Arc::clone(&exclusive_busy);
tokio::spawn(async move {
- let result = run_command(&command, timeout_secs, cwd.as_deref()).await;
+ let result =
- run_command(&command, timeout_secs, cwd.as_deref(), user.as_deref()).await;
++ run_command(&command, timeout_secs, cwd.as_deref(), user_pw.as_ref()).await;
if is_exclusive {
exclusive_busy.store(false, Ordering::SeqCst);
@@@ -830,9 -1018,14 +1150,7 @@@
cmd.arg("-c").arg(&command);
cmd.stdout(Stdio::piped());
cmd.stderr(Stdio::piped());
-- if let Some(dir) = &cwd {
-- cmd.current_dir(dir);
- } else if let Some((_, pw)) = &user_pw {
- cmd.current_dir(&pw.home);
- }
- if let Some((name, pw)) = &user_pw {
- configure_user!(cmd, pw, name.as_str());
-- }
++ configure_user(cmd.as_std_mut(), cwd.as_deref(), user_pw.as_ref());
let mut child = match cmd.spawn() {
Ok(c) => c,
@@@ -891,33 -1084,23 +1209,50 @@@
}
});
}
+ "stdin" if authenticated => {
+ match InputRequest::parse(params).and_then(|input| stdin_executions.submit(input)) {
+ Ok(ack) => {
+ let tx = tx.clone();
+ tokio::spawn(async move {
+ match ack.wait().await {
+ Ok(closed) => send_frame(&tx, serde_json::json!({"id": id, "result": {"closed": closed}})),
+ Err(error) => send_frame(&tx, serde_json::json!({"id": id, "error": {"message": error.to_string()}})),
+ }
+ });
+ }
+ Err(error) => send_frame(&tx, serde_json::json!({"id": id, "error": {"message": error.to_string()}})),
+ }
+ }
+ "cancel" if authenticated => {
+ match stdin_execution::parse_cancel(params) {
+ Ok(stdin_id) => {
+ let executions = stdin_executions.clone();
+ let tx = tx.clone();
+ tokio::spawn(async move {
+ let cancelled = executions.cancel(&stdin_id).await;
+ send_frame(&tx, serde_json::json!({"id": id, "result": {"cancelled": cancelled}}));
+ });
+ }
+ Err(error) => send_frame(&tx, serde_json::json!({"id": id, "error": {"message": error.to_string()}})),
+ }
+ }
+ "create_user" if authenticated => {
+ let name = params.get("name").and_then(|v| v.as_str()).unwrap_or("");
+ let resp = match create_user(name) {
+ Ok(pw) => serde_json::json!({"id": id, "result": {"uid": pw.uid, "gid": pw.gid, "home": pw.home}}),
+ Err(e) => serde_json::json!({"id": id, "error": {"message": e}}),
+ };
+ send_frame(&tx, resp);
+ }
+ "delete_user" if authenticated => {
+ let name = params.get("name").and_then(|v| v.as_str()).unwrap_or("");
+ let remove_home = params.get("remove_home").and_then(|v| v.as_bool()).unwrap_or(false);
+ let resp = match delete_user(name, remove_home) {
+ Ok(()) => serde_json::json!({"id": id, "result": {"removed": true}}),
+ Err(e) => serde_json::json!({"id": id, "error": {"message": e}}),
+ };
+ send_frame(&tx, resp);
+ }
_ if !authenticated => {
send_frame(&tx, serde_json::json!({"id": id, "error": {"message": "Not authenticated"}}));
}
@@@ -942,17 -1120,6 +1277,19 @@@
// Main
// ============================================================================
+fn http_router(state: AppState) -> Router {
+ Router::new()
+ .route("/authenticate", post(authenticate))
+ .route("/execute", post(execute))
+ .route("/execute_stream", post(execute_stream))
+ .route("/stdin", post(stdin))
+ .route("/cancel", post(cancel))
++ .route("/create_user", post(create_user_handler))
++ .route("/delete_user", post(delete_user_handler))
+ .route("/ping", get(ping))
+ .with_state(state)
+}
+
#[tokio::main]
async fn main() {
log("Rust agent starting...");
diff --cc packages/dev/quicksand-image-tools/quicksand_image_tools/quicksand-guest-agent/src/stdin_execution.rs
index abb4a7b,0000000..ab26f8d
mode 100644,000000..100644
--- a/packages/dev/quicksand-image-tools/quicksand_image_tools/quicksand-guest-agent/src/stdin_execution.rs
+++ b/packages/dev/quicksand-image-tools/quicksand_image_tools/quicksand-guest-agent/src/stdin_execution.rs
@@@ -1,655 -1,0 +1,666 @@@
+use base64::{engine::general_purpose::STANDARD, Engine};
+use serde::{Deserialize, Serialize};
+use std::{
+ collections::HashMap,
+ fmt, io,
+ process::Stdio,
+ sync::{
+ atomic::{AtomicBool, Ordering},
+ Arc, Mutex,
+ },
+ time::Duration,
+};
+use tokio::{
+ io::{AsyncRead, AsyncReadExt, AsyncWriteExt},
+ process::{Child, ChildStdin, Command},
+ sync::{mpsc, oneshot, watch},
+ time::{sleep_until, Instant},
+};
+
+pub const MAX_STDIN_CHUNK: usize = 65_536;
+const MAX_ENCODED_CHUNK: usize = MAX_STDIN_CHUNK.div_ceil(3) * 4;
+const OUTPUT_CHUNK: usize = 8192;
+
+#[derive(Debug)]
+pub enum RequestError {
+ Invalid(String),
+ Conflict(&'static str),
+ ExclusiveBusy,
+ Io(String),
+}
+
+impl fmt::Display for RequestError {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ match self {
+ Self::Invalid(message) | Self::Io(message) => f.write_str(message),
+ Self::Conflict(message) => f.write_str(message),
+ Self::ExclusiveBusy => f.write_str("Exclusive command in progress"),
+ }
+ }
+}
+
+#[derive(Debug, Serialize)]
+#[serde(tag = "stream", rename_all = "lowercase")]
+pub enum OutputEvent {
+ Ready,
+ Stdout { data: String },
+ Stderr { data: String },
+ Exit { exit_code: i32 },
+}
+
+pub struct ExecutionRequest {
+ pub stdin_id: String,
+ pub command: String,
+ pub shell: String,
+ pub cwd: Option<String>,
++ pub user: Option<String>,
+ pub timeout: f64,
+ pub exclusive: bool,
+}
+
++impl ExecutionRequest {
++ fn build_command(&self) -> Result<Command, RequestError> {
++ let user_pw = crate::resolve_user(&self.user).map_err(RequestError::Invalid)?;
++ let mut command = Command::new(&self.shell);
++ command
++ .arg("-c")
++ .arg(&self.command)
++ .stdin(Stdio::piped())
++ .stdout(Stdio::piped())
++ .stderr(Stdio::piped())
++ .process_group(0)
++ .kill_on_drop(true);
++ crate::configure_user(command.as_std_mut(), self.cwd.as_deref(), user_pw.as_ref());
++ Ok(command)
++ }
++}
++
+#[derive(Deserialize)]
+#[serde(untagged, deny_unknown_fields)]
+enum StdinWireRequest {
+ Data { stdin_id: String, data: String },
+ Eof { stdin_id: String, eof: bool },
+}
+
+pub struct InputRequest {
+ stdin_id: String,
+ input: Input,
+}
+
+enum Input {
+ Data(Vec<u8>),
+ Eof,
+}
+
+fn validate_id(stdin_id: &str) -> Result<(), RequestError> {
+ if stdin_id.len() != 32 || !stdin_id.bytes().all(|byte| byte.is_ascii_hexdigit()) {
+ return Err(RequestError::Invalid(
+ "stdin_id must be a 32-character UUID hex string".into(),
+ ));
+ }
+ Ok(())
+}
+
+impl InputRequest {
+ pub fn parse(value: serde_json::Value) -> Result<Self, RequestError> {
+ let request = serde_json::from_value(value).map_err(|error| {
+ RequestError::Invalid(format!(
+ "Expected stdin_id and either base64 data or eof: true: {error}"
+ ))
+ })?;
+ let (stdin_id, input) = match request {
+ StdinWireRequest::Data { stdin_id, data } => {
+ if data.len() > MAX_ENCODED_CHUNK {
+ return Err(RequestError::Invalid(
+ "stdin data exceeds the maximum decoded chunk size of 65536 bytes".into(),
+ ));
+ }
+ let bytes = STANDARD.decode(data).map_err(|error| {
+ RequestError::Invalid(format!("Invalid base64 stdin data: {error}"))
+ })?;
+ if bytes.len() > MAX_STDIN_CHUNK {
+ return Err(RequestError::Invalid(
+ "stdin data exceeds the maximum decoded chunk size of 65536 bytes".into(),
+ ));
+ }
+ (stdin_id, Input::Data(bytes))
+ }
+ StdinWireRequest::Eof { stdin_id, eof } => {
+ if !eof {
+ return Err(RequestError::Invalid("eof must be true".into()));
+ }
+ (stdin_id, Input::Eof)
+ }
+ };
+ validate_id(&stdin_id)?;
+ Ok(Self { stdin_id, input })
+ }
+}
+
+pub fn parse_cancel(value: serde_json::Value) -> Result<String, RequestError> {
+ #[derive(Deserialize)]
+ #[serde(deny_unknown_fields)]
+ struct CancelRequest {
+ stdin_id: String,
+ }
+
+ let request: CancelRequest = serde_json::from_value(value)
+ .map_err(|error| RequestError::Invalid(format!("Invalid cancel request: {error}")))?;
+ validate_id(&request.stdin_id)?;
+ Ok(request.stdin_id)
+}
+
+struct InputWrite {
+ input: Input,
+ ack: oneshot::Sender<Result<bool, String>>,
+}
+
+pub struct InputAck {
+ pending: Option<oneshot::Receiver<Result<bool, String>>>,
+}
+
+impl InputAck {
+ pub async fn wait(self) -> Result<bool, RequestError> {
+ match self.pending {
+ Some(ack) => match ack.await {
+ Ok(result) => result.map_err(RequestError::Io),
+ // Dropping the writer closes its pipe and any outstanding ACKs.
+ Err(_) => Ok(true),
+ },
+ None => Ok(true),
+ }
+ }
+}
+
+struct Control {
+ input: mpsc::Sender<InputWrite>,
+ input_closed: Arc<AtomicBool>,
+ cancel: watch::Sender<bool>,
+ done: watch::Receiver<bool>,
+}
+
+#[derive(Clone, Default)]
+pub struct StdinExecutions {
+ entries: Arc<Mutex<HashMap<String, Arc<Control>>>>,
+}
+
+impl StdinExecutions {
+ pub fn start(
+ &self,
+ request: ExecutionRequest,
+ exclusive_busy: Arc<AtomicBool>,
+ ) -> Result<mpsc::Receiver<OutputEvent>, RequestError> {
+ validate_id(&request.stdin_id)?;
+ let duration = Duration::try_from_secs_f64(request.timeout)
+ .map_err(|_| RequestError::Invalid("timeout must be finite and nonnegative".into()))?;
+ let deadline = Instant::now()
+ .checked_add(duration)
+ .ok_or_else(|| RequestError::Invalid("timeout is too large".into()))?;
++ // Resolve and configure the requested user before reserving an ID or
++ // claiming exclusivity; an unknown user must never start a child.
++ let command = request.build_command()?;
+
+ let mut entries = self.entries.lock().expect("stdin registry poisoned");
+ if entries.contains_key(&request.stdin_id) {
+ return Err(RequestError::Conflict("stdin_id is already active"));
+ }
+ let exclusive = ExclusiveGuard::acquire(exclusive_busy, request.exclusive)?;
+ let (input_tx, input_rx) = mpsc::channel(1);
+ let (cancel_tx, cancel_rx) = watch::channel(false);
+ let (done_tx, done_rx) = watch::channel(false);
+ let control = Arc::new(Control {
+ input: input_tx,
+ input_closed: Arc::new(AtomicBool::new(false)),
+ cancel: cancel_tx,
+ done: done_rx,
+ });
+ // A following serial cancel frame must find the ID even before the
+ // execution task runs or emits ready.
+ entries.insert(request.stdin_id.clone(), Arc::clone(&control));
+ let registration = Registration {
+ executions: self.clone(),
+ stdin_id: request.stdin_id.clone(),
+ control,
+ exclusive,
+ done: done_tx,
+ };
+ drop(entries);
+
+ let (output_tx, output_rx) = mpsc::channel(16);
+ tokio::spawn(run(
- request,
++ command,
++ request.timeout,
+ deadline,
+ input_rx,
+ cancel_rx,
+ output_tx,
+ registration,
+ ));
+ Ok(output_rx)
+ }
+
+ pub fn submit(&self, request: InputRequest) -> Result<InputAck, RequestError> {
+ let control = self
+ .entries
+ .lock()
+ .expect("stdin registry poisoned")
+ .get(&request.stdin_id)
+ .cloned();
+ let Some(control) = control else {
+ return Ok(InputAck { pending: None });
+ };
+ if control.input_closed.load(Ordering::SeqCst) || *control.cancel.borrow() {
+ return Ok(InputAck { pending: None });
+ }
+ let (ack_tx, ack_rx) = oneshot::channel();
+ // Never retain an unbounded number of chunks in pending HTTP/serial tasks.
+ // There is one in-flight write and at most one queued request.
+ match control.input.try_send(InputWrite {
+ input: request.input,
+ ack: ack_tx,
+ }) {
+ Ok(()) => Ok(InputAck {
+ pending: Some(ack_rx),
+ }),
+ Err(mpsc::error::TrySendError::Closed(_)) => Ok(InputAck { pending: None }),
+ Err(mpsc::error::TrySendError::Full(_)) => {
+ Err(RequestError::Conflict("A stdin request is already pending"))
+ }
+ }
+ }
+
+ pub async fn cancel(&self, stdin_id: &str) -> bool {
+ let control = self
+ .entries
+ .lock()
+ .expect("stdin registry poisoned")
+ .get(stdin_id)
+ .cloned();
+ let Some(control) = control else {
+ return false;
+ };
+ // EOF/BrokenPipe can precede command completion; input_closed must not
+ // disable cancellation of a command that is still processing.
+ if *control.done.borrow() {
+ return false;
+ }
+ let already_cancelled = control.cancel.send_replace(true);
+ let mut done = control.done.clone();
+ // The registration owns the sender, so closure also means it was dropped.
+ let _ = done.wait_for(|done| *done).await;
+ !already_cancelled
+ }
+
+ pub async fn cancel_all(&self) {
+ let controls: Vec<_> = self
+ .entries
+ .lock()
+ .expect("stdin registry poisoned")
+ .values()
+ .cloned()
+ .collect();
+ for control in &controls {
+ control.cancel.send_replace(true);
+ }
+ for control in controls {
+ let mut done = control.done.clone();
+ let _ = done.wait_for(|done| *done).await;
+ }
+ }
+}
+
+struct ExclusiveGuard {
+ busy: Arc<AtomicBool>,
+}
+
+impl ExclusiveGuard {
+ fn acquire(busy: Arc<AtomicBool>, exclusive: bool) -> Result<Option<Self>, RequestError> {
+ if busy.load(Ordering::SeqCst) {
+ return Err(RequestError::ExclusiveBusy);
+ }
+ if exclusive {
+ busy.compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst)
+ .map_err(|_| RequestError::ExclusiveBusy)?;
+ Ok(Some(Self { busy }))
+ } else {
+ Ok(None)
+ }
+ }
+}
+
+impl Drop for ExclusiveGuard {
+ fn drop(&mut self) {
+ self.busy.store(false, Ordering::SeqCst);
+ }
+}
+
+struct Registration {
+ executions: StdinExecutions,
+ stdin_id: String,
+ control: Arc<Control>,
+ exclusive: Option<ExclusiveGuard>,
+ done: watch::Sender<bool>,
+}
+
+impl Drop for Registration {
+ fn drop(&mut self) {
+ self.control.input_closed.store(true, Ordering::SeqCst);
+ let mut entries = self
+ .executions
+ .entries
+ .lock()
+ .expect("stdin registry poisoned");
+ if entries
+ .get(&self.stdin_id)
+ .is_some_and(|entry| Arc::ptr_eq(entry, &self.control))
+ {
+ entries.remove(&self.stdin_id);
+ }
+ drop(entries);
+ self.exclusive.take();
+ self.done.send_replace(true);
+ }
+}
+
+struct ProcessGroup {
+ child: Child,
+ pgid: i32,
+ armed: bool,
+}
+
+impl ProcessGroup {
+ fn new(child: Child) -> Self {
+ Self {
+ pgid: child.id().expect("new child has no PID") as i32,
+ child,
+ armed: true,
+ }
+ }
+
+ fn kill_group(&mut self) -> io::Result<()> {
+ if self.armed {
+ // Each stdin execution is a new process group, never the agent's group.
+ let result = unsafe { libc::kill(-self.pgid, libc::SIGKILL) };
+ if result < 0 {
+ let error = io::Error::last_os_error();
+ if error.raw_os_error() != Some(libc::ESRCH) {
+ return Err(error);
+ }
+ }
+ self.armed = false;
+ }
+ Ok(())
+ }
+
+ async fn terminate_and_reap(&mut self) -> io::Result<()> {
+ if let Err(group_error) = self.kill_group() {
+ // Still reap the direct child if signalling the group failed.
+ self.child.kill().await?;
+ return Err(group_error);
+ }
+ self.child.wait().await?;
+ Ok(())
+ }
+}
+
+impl Drop for ProcessGroup {
+ fn drop(&mut self) {
+ if let Err(error) = self.kill_group() {
+ crate::log(&format!("Failed to kill stdin process group: {error}"));
+ }
+ // Child::kill_on_drop is a second guard; normal paths explicitly reap it.
+ }
+}
+
+enum Outcome {
+ Exit(i32),
+ Failed(String),
+ Disconnected,
+}
+
+async fn run(
- request: ExecutionRequest,
++ mut command: Command,
++ timeout_seconds: f64,
+ deadline: Instant,
+ input: mpsc::Receiver<InputWrite>,
+ mut cancel: watch::Receiver<bool>,
+ output: mpsc::Sender<OutputEvent>,
+ registration: Registration,
+) {
+ let outcome = {
+ // On startup failure, drop any queued input ACKs before terminal output.
+ let input_requests = input;
+ if output.is_closed() {
+ Outcome::Disconnected
+ } else if *cancel.borrow() {
+ Outcome::Failed("Command cancelled".into())
+ } else {
- let mut command = Command::new(&request.shell);
- command
- .arg("-c")
- .arg(&request.command)
- .stdin(Stdio::piped())
- .stdout(Stdio::piped())
- .stderr(Stdio::piped())
- .process_group(0)
- .kill_on_drop(true);
- if let Some(cwd) = &request.cwd {
- command.current_dir(cwd);
- }
+ match command.spawn() {
+ Err(error) => Outcome::Failed(format!("Failed to start command: {error}")),
+ Ok(child) => {
+ let mut process = ProcessGroup::new(child);
+ let input_closed = Arc::clone(&registration.control.input_closed);
+ let result = tokio::select! {
+ biased;
+ _ = cancel.wait_for(|cancelled| *cancelled) => {
+ Outcome::Failed("Command cancelled".into())
+ }
+ _ = output.closed() => Outcome::Disconnected,
+ _ = sleep_until(deadline) => {
- Outcome::Failed(format!("Command timed out after {} seconds", request.timeout))
++ Outcome::Failed(format!("Command timed out after {} seconds", timeout_seconds))
+ }
+ result = drive(&mut process, input_requests, input_closed, &output) => {
+ match result {
+ Ok(code) => Outcome::Exit(code),
+ Err(error) => Outcome::Failed(error),
+ }
+ }
+ };
+ match process.terminate_and_reap().await {
+ Ok(()) => result,
+ Err(error) => {
+ Outcome::Failed(format!("Failed to terminate command: {error}"))
+ }
+ }
+ }
+ }
+ }
+ };
+
+ // Reaping, closing stdin and releasing exclusivity must not depend on a slow
+ // output consumer accepting the final events.
+ drop(registration);
+ let exit_code = match outcome {
+ Outcome::Disconnected => return,
+ Outcome::Exit(code) => code,
+ Outcome::Failed(message) => {
+ if output
+ .send(OutputEvent::Stderr { data: message })
+ .await
+ .is_err()
+ {
+ return;
+ }
+ -1
+ }
+ };
+ // The receiver disappearing here is an ordinary transport disconnection.
+ let _ = output.send(OutputEvent::Exit { exit_code }).await;
+}
+
+async fn drive(
+ process: &mut ProcessGroup,
+ input: mpsc::Receiver<InputWrite>,
+ input_closed: Arc<AtomicBool>,
+ output: &mpsc::Sender<OutputEvent>,
+) -> Result<i32, String> {
+ let stdin = process.child.stdin.take().expect("stdin was piped");
+ let stdout = process.child.stdout.take().expect("stdout was piped");
+ let stderr = process.child.stderr.take().expect("stderr was piped");
+ let mut writer = Some(Box::pin(write_input(
+ stdin,
+ input,
+ Arc::clone(&input_closed),
+ )));
+ let stdout = read_output(stdout, false, output);
+ let stderr = read_output(stderr, true, output);
+ tokio::pin!(stdout, stderr);
+ output
+ .send(OutputEvent::Ready)
+ .await
+ .map_err(|_| "Output transport closed".to_string())?;
+
+ let mut exit_code = None;
+ let mut stdout_done = false;
+ let mut stderr_done = false;
+ loop {
+ if stdout_done && stderr_done {
+ if let Some(code) = exit_code {
+ return Ok(code);
+ }
+ }
+ // These are independent futures: a blocked pipe write or output send
+ // cannot keep the child wait (or the outer cancellation) from progressing.
+ tokio::select! {
+ result = process.child.wait(), if exit_code.is_none() => {
+ input_closed.store(true, Ordering::SeqCst);
+ writer.take();
+ exit_code = Some(result.map_err(|error| format!("Failed to wait for command: {error}"))?
+ .code().unwrap_or(-1));
+ // Background descendants must not hold the pipes open after the
+ // command exits, or outlive an otherwise successful execution.
+ process.kill_group().map_err(|error| format!("Failed to kill command descendants: {error}"))?;
+ }
+ result = async { writer.as_mut().expect("input writer exists").await }, if writer.is_some() => {
+ writer.take();
+ result?;
+ }
+ result = &mut stdout, if !stdout_done => {
+ stdout_done = true;
+ result?;
+ }
+ result = &mut stderr, if !stderr_done => {
+ stderr_done = true;
+ result?;
+ }
+ }
+ }
+}
+
+struct InputClosed(Arc<AtomicBool>);
+
+impl Drop for InputClosed {
+ fn drop(&mut self) {
+ self.0.store(true, Ordering::SeqCst);
+ }
+}
+
+async fn write_input(
+ mut stdin: ChildStdin,
+ mut input: mpsc::Receiver<InputWrite>,
+ closed: Arc<AtomicBool>,
+) -> Result<(), String> {
+ let _closed = InputClosed(closed);
+ while let Some(request) = input.recv().await {
+ match request.input {
+ Input::Eof => {
+ drop(stdin);
+ // A lost ACK receiver means the host abandoned its control request.
+ let _ = request.ack.send(Ok(true));
+ return Ok(());
+ }
+ Input::Data(bytes) => match stdin.write_all(&bytes).await {
+ Ok(()) => {
+ let _ = request.ack.send(Ok(false));
+ }
+ Err(error) if error.kind() == io::ErrorKind::BrokenPipe => {
+ let _ = request.ack.send(Ok(true));
+ return Ok(());
+ }
+ Err(error) => {
+ let message = format!("Failed to write stdin: {error}");
+ let _ = request.ack.send(Err(message.clone()));
+ return Err(message);
+ }
+ },
+ }
+ }
+ Ok(())
+}
+
+#[derive(Default)]
+struct Utf8Decoder {
+ pending: Vec<u8>,
+}
+
+impl Utf8Decoder {
+ fn decode(&mut self, bytes: &[u8], eof: bool) -> String {
+ self.pending.extend_from_slice(bytes);
+ let mut text = String::new();
+ let mut consumed = 0;
+ while consumed < self.pending.len() {
+ match std::str::from_utf8(&self.pending[consumed..]) {
+ Ok(valid) => {
+ text.push_str(valid);
+ consumed = self.pending.len();
+ }
+ Err(error) => {
+ let valid_end = consumed + error.valid_up_to();
+ text.push_str(
+ std::str::from_utf8(&self.pending[consumed..valid_end])
+ .expect("UTF-8 valid prefix"),
+ );
+ consumed = valid_end;
+ match error.error_len() {
+ Some(length) => {
+ text.push('\u{fffd}');
+ consumed += length;
+ }
+ None => {
+ if eof {
+ text.push('\u{fffd}');
+ consumed = self.pending.len();
+ }
+ break;
+ }
+ }
+ }
+ }
+ }
+ self.pending.drain(..consumed);
+ text
+ }
+}
+
+async fn read_output(
+ mut reader: impl AsyncRead + Unpin,
+ is_stderr: bool,
+ output: &mpsc::Sender<OutputEvent>,
+) -> Result<(), String> {
+ let mut buffer = [0; OUTPUT_CHUNK];
+ let mut decoder = Utf8Decoder::default();
+ loop {
+ let length = reader
+ .read(&mut buffer)
+ .await
+ .map_err(|error| format!("Failed to read command output: {error}"))?;
+ let data = decoder.decode(&buffer[..length], length == 0);
+ if !data.is_empty() {
+ let event = if is_stderr {
+ OutputEvent::Stderr { data }
+ } else {
+ OutputEvent::Stdout { data }
+ };
+ output
+ .send(event)
+ .await
+ .map_err(|_| "Output transport closed".to_string())?;
+ }
+ if length == 0 {
+ return Ok(());
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests;
diff --cc packages/dev/quicksand-image-tools/quicksand_image_tools/quicksand-guest-agent/src/stdin_execution/tests.rs
index 7cfb152,0000000..26dd00e
mode 100644,000000..100644
--- a/packages/dev/quicksand-image-tools/quicksand_image_tools/quicksand-guest-agent/src/stdin_execution/tests.rs
+++ b/packages/dev/quicksand-image-tools/quicksand_image_tools/quicksand-guest-agent/src/stdin_execution/tests.rs
@@@ -1,513 -1,0 +1,580 @@@
+use super::*;
+use serde_json::json;
+use tokio::time::{sleep, timeout};
+
+const ID: &str = "0123456789abcdef0123456789abcdef";
+const OTHER_ID: &str = "fedcba9876543210fedcba9876543210";
+
+fn request(command: &str) -> ExecutionRequest {
+ ExecutionRequest {
+ stdin_id: ID.into(),
+ command: command.into(),
+ shell: "/bin/sh".into(),
+ cwd: None,
++ user: None,
+ timeout: 5.0,
+ exclusive: false,
+ }
+}
+
+fn data(stdin_id: &str, bytes: &[u8]) -> InputRequest {
+ InputRequest::parse(json!({"stdin_id": stdin_id, "data": STANDARD.encode(bytes)})).unwrap()
+}
+
+async fn write(executions: &StdinExecutions, stdin_id: &str, bytes: &[u8]) -> bool {
+ executions
+ .submit(data(stdin_id, bytes))
+ .unwrap()
+ .wait()
+ .await
+ .unwrap()
+}
+
+async fn eof(executions: &StdinExecutions, stdin_id: &str) -> bool {
+ executions
+ .submit(InputRequest::parse(json!({"stdin_id": stdin_id, "eof": true})).unwrap())
+ .unwrap()
+ .wait()
+ .await
+ .unwrap()
+}
+
+async fn next(output: &mut mpsc::Receiver<OutputEvent>) -> OutputEvent {
+ timeout(Duration::from_secs(3), output.recv())
+ .await
+ .expect("output timed out")
+ .expect("output closed before exit")
+}
+
+async fn ready(output: &mut mpsc::Receiver<OutputEvent>) {
+ assert!(matches!(next(output).await, OutputEvent::Ready));
+}
+
+async fn finish(mut output: mpsc::Receiver<OutputEvent>) -> (String, String, i32) {
+ let mut stdout = String::new();
+ let mut stderr = String::new();
+ loop {
+ match next(&mut output).await {
+ OutputEvent::Stdout { data } => stdout.push_str(&data),
+ OutputEvent::Stderr { data } => stderr.push_str(&data),
+ OutputEvent::Exit { exit_code } => return (stdout, stderr, exit_code),
+ OutputEvent::Ready => panic!("unexpected ready event"),
+ }
+ }
+}
+
+fn assert_clean(executions: &StdinExecutions, busy: &AtomicBool) {
+ assert!(executions.entries.lock().unwrap().is_empty());
+ assert!(!busy.load(Ordering::SeqCst));
+}
+
++#[test]
++fn requested_user_configuration_matches_legacy_and_preserves_cwd_override() {
++ let user = (
++ "root".to_string(),
++ crate::lookup_user("root").expect("root must exist in /etc/passwd"),
++ );
++ for cwd in [None, Some("src")] {
++ let mut request = request("cat");
++ request.user = Some(user.0.clone());
++ request.cwd = cwd.map(str::to_string);
++ // Inspect configured commands without spawning a privilege-changing
++ // child or modifying accounts on the host running these tests.
++ let streaming = request.build_command().unwrap();
++ let mut legacy = std::process::Command::new("/bin/sh");
++ crate::configure_user(&mut legacy, cwd, Some(&user));
++ for command in [streaming.as_std(), &legacy] {
++ assert_eq!(
++ command.get_current_dir(),
++ Some(std::path::Path::new(cwd.unwrap_or(&user.1.home)))
++ );
++ for (key, value) in [
++ ("HOME", user.1.home.as_str()),
++ ("USER", user.0.as_str()),
++ ("LOGNAME", user.0.as_str()),
++ ] {
++ let actual = command
++ .get_envs()
++ .find(|(name, _)| *name == key)
++ .and_then(|(_, value)| value);
++ assert_eq!(actual, Some(std::ffi::OsStr::new(value)));
++ }
++ }
++ }
++}
++
++#[tokio::test]
++async fn unknown_user_is_rejected_before_registration_or_exclusivity() {
++ let executions = StdinExecutions::default();
++ let busy = Arc::new(AtomicBool::new(false));
++ let missing_user = "quicksand-no-such-stdin-user";
++ assert!(crate::lookup_user(missing_user).is_none());
++ for already_busy in [false, true] {
++ busy.store(already_busy, Ordering::SeqCst);
++ let mut request = request("printf should-not-run");
++ request.user = Some(missing_user.into());
++ request.exclusive = true;
++ assert!(matches!(
++ executions.start(request, Arc::clone(&busy)),
++ Err(RequestError::Invalid(message)) if message == format!("No such user: {missing_user}")
++ ));
++ assert!(executions.entries.lock().unwrap().is_empty());
++ assert_eq!(busy.load(Ordering::SeqCst), already_busy);
++ assert!(write(&executions, ID, b"not registered").await);
++ assert!(!executions.cancel(ID).await);
++ }
++
++ busy.store(false, Ordering::SeqCst);
++ let mut output = executions
++ .start(request("cat >/dev/null"), Arc::clone(&busy))
++ .unwrap();
++ ready(&mut output).await;
++ assert!(eof(&executions, ID).await);
++ assert_eq!(finish(output).await, ("".into(), "".into(), 0));
++ assert_clean(&executions, &busy);
++}
++
+pub(super) async fn assert_process_stopped(pid: i32) {
+ timeout(Duration::from_secs(3), async {
+ loop {
+ if unsafe { libc::kill(pid, 0) } < 0 {
+ assert_eq!(io::Error::last_os_error().raw_os_error(), Some(libc::ESRCH));
+ return;
+ }
+ // Orphan descendants may be zombies until the platform's init reaps
+ // them. They are terminated; the directly owned child is reaped here.
+ let status = std::process::Command::new("ps")
+ .args(["-o", "stat=", "-p", &pid.to_string()])
+ .output()
+ .unwrap();
+ if String::from_utf8_lossy(&status.stdout)
+ .trim_start()
+ .starts_with('Z')
+ {
+ return;
+ }
+ sleep(Duration::from_millis(10)).await;
+ }
+ })
+ .await
+ .expect("command process survived cleanup");
+}
+
+#[test]
+fn input_validation_is_strict_and_bounded() {
+ for value in [
+ json!({}),
+ json!({"stdin_id": ID}),
+ json!({"stdin_id": "invalid", "data": ""}),
+ json!({"stdin_id": ID, "data": null}),
+ json!({"stdin_id": ID, "data": "%%%"}),
+ json!({"stdin_id": ID, "data": "Zg"}),
+ json!({"stdin_id": ID, "data": "Zg==", "eof": true}),
+ json!({"stdin_id": ID, "data": "Zg==", "eof": null}),
+ json!({"stdin_id": ID, "eof": false}),
+ json!({"stdin_id": ID, "eof": null}),
+ json!({"stdin_id": ID, "eof": "true"}),
+ json!({"stdin_id": ID, "eof": true, "extra": 1}),
+ json!({"stdin_id": ID, "data": STANDARD.encode(vec![0; MAX_STDIN_CHUNK + 1])}),
+ json!({"stdin_id": ID, "data": "A".repeat(MAX_ENCODED_CHUNK + 4)}),
+ ] {
+ assert!(
+ matches!(
+ InputRequest::parse(value.clone()),
+ Err(RequestError::Invalid(_))
+ ),
+ "accepted malformed input: {value}"
+ );
+ }
+ assert!(InputRequest::parse(json!({"stdin_id": ID, "data": ""})).is_ok());
+ assert!(InputRequest::parse(json!({"stdin_id": ID, "eof": true})).is_ok());
+ assert!(InputRequest::parse(json!({
+ "stdin_id": ID, "data": STANDARD.encode(vec![255; MAX_STDIN_CHUNK])
+ }))
+ .is_ok());
+ assert_eq!(parse_cancel(json!({"stdin_id": ID})).unwrap(), ID);
+ for value in [
+ json!({}),
+ json!({"stdin_id": null}),
+ json!({"stdin_id": "invalid"}),
+ json!({"stdin_id": ID, "eof": true}),
+ ] {
+ assert!(parse_cancel(value).is_err());
+ }
+}
+
+#[test]
+fn utf8_decoder_preserves_split_characters_and_replaces_invalid_bytes() {
+ let mut decoder = Utf8Decoder::default();
+ assert_eq!(decoder.decode(b"prompt:\xf0", false), "prompt:");
+ assert_eq!(decoder.decode(b"\x9f\x98", false), "");
+ assert_eq!(decoder.decode(b"\x80!", false), "😀!");
+ assert_eq!(decoder.decode(b"\xffx\xe2\x82", false), "�x");
+ assert_eq!(decoder.decode(b"", true), "�");
+ assert!(decoder.pending.is_empty());
+
+ let bytes = "hello € 😀 world".as_bytes();
+ for split in 0..=bytes.len() {
+ let mut decoder = Utf8Decoder::default();
+ let actual =
+ decoder.decode(&bytes[..split], false) + &decoder.decode(&bytes[split..], true);
+ assert_eq!(actual, "hello € 😀 world");
+ }
+}
+
+#[tokio::test]
+async fn output_is_incremental_without_newlines_or_utf8_corruption() {
+ let (mut producer, reader) = tokio::io::duplex(32);
+ let (tx, mut rx) = mpsc::channel(4);
+ let reader = tokio::spawn(async move { read_output(reader, false, &tx).await });
+ producer.write_all(b"prompt:\xe2").await.unwrap();
+ assert!(matches!(next(&mut rx).await, OutputEvent::Stdout { data } if data == "prompt:"));
+ producer.write_all(b"\x82").await.unwrap();
+ assert!(timeout(Duration::from_millis(20), rx.recv()).await.is_err());
+ producer.write_all(b"\xac!").await.unwrap();
+ assert!(matches!(next(&mut rx).await, OutputEvent::Stdout { data } if data == "€!"));
+ producer.write_all(b"\xf0\x9f").await.unwrap();
+ drop(producer);
+ assert!(matches!(next(&mut rx).await, OutputEvent::Stdout { data } if data == "�"));
+ reader.await.unwrap().unwrap();
+ assert!(rx.recv().await.is_none());
+}
+
+#[tokio::test]
+async fn binary_chunks_are_written_exactly_once_and_eof_finishes() {
+ let executions = StdinExecutions::default();
+ let busy = Arc::new(AtomicBool::new(false));
+ let mut output = executions
+ .start(request("od -An -v -tx1"), Arc::clone(&busy))
+ .unwrap();
+ ready(&mut output).await;
+ let output = tokio::spawn(finish(output));
+ let maximum: Vec<_> = (0u8..=255).cycle().take(MAX_STDIN_CHUNK).collect();
+ let chunks: [&[u8]; 4] = [b"\0\xff\n", &maximum, b"", b"\x80\r\0end"];
+ for chunk in chunks {
+ assert!(!write(&executions, ID, chunk).await);
+ }
+ assert!(eof(&executions, ID).await);
+ let (stdout, stderr, code) = output.await.unwrap();
+ let actual: Vec<_> = stdout
+ .split_whitespace()
+ .map(|hex| u8::from_str_radix(hex, 16).unwrap())
+ .collect();
+ assert_eq!(actual, chunks.concat());
+ assert_eq!((stderr.as_str(), code), ("", 0));
+ assert_clean(&executions, &busy);
+ assert!(write(&executions, ID, b"late").await);
+ assert!(eof(&executions, ID).await);
+ assert!(!executions.cancel(ID).await);
+}
+
+#[tokio::test]
+async fn command_can_prompt_before_input_is_produced() {
+ let executions = StdinExecutions::default();
+ let busy = Arc::new(AtomicBool::new(false));
+ let mut output = executions
+ .start(
+ request("printf 'prompt:'; IFS= read -r line; printf '<%s>' \"$line\"; printf err >&2"),
+ Arc::clone(&busy),
+ )
+ .unwrap();
+ ready(&mut output).await;
+ assert!(matches!(next(&mut output).await, OutputEvent::Stdout { data } if data == "prompt:"));
+ assert!(!write(&executions, ID, b"hello\n").await);
+ assert!(eof(&executions, ID).await);
+ assert_eq!(finish(output).await, ("<hello>".into(), "err".into(), 0));
+ assert_clean(&executions, &busy);
+}
+
+#[tokio::test]
+async fn requested_shell_and_cwd_are_honored() {
+ let executions = StdinExecutions::default();
+ let busy = Arc::new(AtomicBool::new(false));
+ let mut request =
+ request("test -n \"$BASH_VERSION\" || exit 42; printf '%s' \"$PWD\"; cat >/dev/null");
+ request.shell = "/bin/bash".into();
+ request.cwd = Some("src".into());
+ let mut output = executions.start(request, Arc::clone(&busy)).unwrap();
+ ready(&mut output).await;
+ assert!(eof(&executions, ID).await);
+ let (stdout, stderr, code) = finish(output).await;
+ assert_eq!(
+ stdout,
+ std::env::current_dir()
+ .unwrap()
+ .join("src")
+ .to_string_lossy()
+ );
+ assert_eq!((stderr.as_str(), code), ("", 0));
+ assert_clean(&executions, &busy);
+}
+
+#[tokio::test]
+async fn broken_pipe_is_closed_input_not_a_command_failure() {
+ let executions = StdinExecutions::default();
+ let busy = Arc::new(AtomicBool::new(false));
+ let mut output = executions
+ .start(
+ request("exec 0<&-; printf done; sleep 0.1"),
+ Arc::clone(&busy),
+ )
+ .unwrap();
+ ready(&mut output).await;
+ assert!(matches!(next(&mut output).await, OutputEvent::Stdout { data } if data == "done"));
+ assert!(write(&executions, ID, b"not consumed").await);
+ assert_eq!(finish(output).await, ("".into(), "".into(), 0));
+ assert_clean(&executions, &busy);
+}
+
+#[tokio::test]
+async fn closed_input_remains_cancellable_while_the_command_is_processing() {
+ let executions = StdinExecutions::default();
+ let busy = Arc::new(AtomicBool::new(false));
+ for (command, close_with_eof) in [
+ ("cat >/dev/null; printf processing; sleep 30", true),
+ ("exec 0<&-; printf processing; sleep 30", false),
+ ] {
+ let mut request = request(command);
+ request.exclusive = true;
+ let mut output = executions.start(request, Arc::clone(&busy)).unwrap();
+ ready(&mut output).await;
+ if close_with_eof {
+ assert!(!write(&executions, ID, b"input").await);
+ assert!(eof(&executions, ID).await);
+ }
+ assert!(
+ matches!(next(&mut output).await, OutputEvent::Stdout { data } if data == "processing")
+ );
+ if !close_with_eof {
+ assert!(write(&executions, ID, b"broken pipe").await);
+ }
+ assert!(write(&executions, ID, b"already closed").await);
+ assert!(executions.entries.lock().unwrap().contains_key(ID));
+ assert!(busy.load(Ordering::SeqCst));
+ assert!(timeout(Duration::from_secs(2), executions.cancel(ID))
+ .await
+ .unwrap());
+ let (stdout, stderr, code) = finish(output).await;
+ assert_eq!((stdout.as_str(), code), ("", -1));
+ assert!(stderr.contains("Command cancelled"));
+ assert_clean(&executions, &busy);
+ }
+}
+
+#[tokio::test]
+async fn early_exit_does_not_wait_for_input_or_eof() {
+ let executions = StdinExecutions::default();
+ let busy = Arc::new(AtomicBool::new(false));
+ let mut output = executions
+ .start(request("printf done"), Arc::clone(&busy))
+ .unwrap();
+ ready(&mut output).await;
+ assert_eq!(finish(output).await, ("done".into(), "".into(), 0));
+ assert!(write(&executions, ID, b"late").await);
+ assert_clean(&executions, &busy);
+}
+
+#[tokio::test]
+async fn duplicate_ids_and_exclusive_commands_are_rejected_without_overwriting() {
+ let executions = StdinExecutions::default();
+ let busy = Arc::new(AtomicBool::new(false));
+ let mut first = request("cat >/dev/null");
+ first.exclusive = true;
+ let mut output = executions.start(first, Arc::clone(&busy)).unwrap();
+ ready(&mut output).await;
+ assert!(matches!(
+ executions.start(request("printf wrong"), Arc::clone(&busy)),
+ Err(RequestError::Conflict(_))
+ ));
+ let mut other = request("printf wrong");
+ other.stdin_id = OTHER_ID.into();
+ assert!(matches!(
+ executions.start(other, Arc::clone(&busy)),
+ Err(RequestError::ExclusiveBusy)
+ ));
+ assert!(!write(&executions, ID, b"data").await);
+ assert!(eof(&executions, ID).await);
+ assert_eq!(finish(output).await, ("".into(), "".into(), 0));
+ assert_clean(&executions, &busy);
+}
+
+#[tokio::test]
+async fn queued_input_has_no_ack_until_written_and_is_bounded() {
+ let executions = StdinExecutions::default();
+ let busy = Arc::new(AtomicBool::new(false));
+ let output = executions
+ .start(request("cat >/dev/null"), Arc::clone(&busy))
+ .unwrap();
+ let mut ack = executions.submit(data(ID, b"one")).unwrap();
+ assert!(matches!(
+ ack.pending.as_mut().unwrap().try_recv(),
+ Err(oneshot::error::TryRecvError::Empty)
+ ));
+ assert!(matches!(
+ executions.submit(data(ID, b"two")),
+ Err(RequestError::Conflict(_))
+ ));
+ assert!(executions.cancel(ID).await);
+ assert!(ack.wait().await.unwrap());
+ drop(output);
+ assert_clean(&executions, &busy);
+}
+
+#[tokio::test]
+async fn startup_failures_are_terminal_and_release_exclusivity() {
+ let executions = StdinExecutions::default();
+ let busy = Arc::new(AtomicBool::new(false));
+ for invalid_shell in [true, false] {
+ let mut request = request("cat");
+ request.exclusive = true;
+ if invalid_shell {
+ request.shell = "./quicksand-no-such-shell".into();
+ } else {
+ request.cwd = Some("./quicksand-no-such-working-directory".into());
+ }
+ let output = executions.start(request, Arc::clone(&busy)).unwrap();
+ let (stdout, stderr, code) = finish(output).await;
+ assert_eq!((stdout.as_str(), code), ("", -1));
+ assert!(stderr.contains("Failed to start command"));
+ assert_clean(&executions, &busy);
+ assert!(write(&executions, ID, b"late").await);
+ }
+}
+
+#[tokio::test]
+async fn invalid_timeouts_do_not_create_executions() {
+ let executions = StdinExecutions::default();
+ let busy = Arc::new(AtomicBool::new(false));
+ for seconds in [f64::NAN, f64::INFINITY, -1.0, f64::MAX] {
+ let mut request = request("cat");
+ request.timeout = seconds;
+ request.exclusive = true;
+ assert!(matches!(
+ executions.start(request, Arc::clone(&busy)),
+ Err(RequestError::Invalid(_))
+ ));
+ assert_clean(&executions, &busy);
+ }
+}
+
+#[tokio::test]
+async fn timeout_kills_the_process_group_and_releases_exclusivity() {
+ let executions = StdinExecutions::default();
+ let busy = Arc::new(AtomicBool::new(false));
+ let mut request = request("sleep 30 & printf '%s %s\\n' $$ $!; wait");
+ request.timeout = 0.3;
+ request.exclusive = true;
+ let mut output = executions.start(request, Arc::clone(&busy)).unwrap();
+ ready(&mut output).await;
+ let (stdout, stderr, code) = finish(output).await;
+ assert_eq!(code, -1);
+ assert!(stderr.contains("Command timed out after 0.3 seconds"));
+ for pid in stdout.split_whitespace() {
+ assert_process_stopped(pid.parse().unwrap()).await;
+ }
+ assert_eq!(stdout.split_whitespace().count(), 2);
+ assert!(write(&executions, ID, b"late").await);
+ assert_clean(&executions, &busy);
+}
+
+#[tokio::test]
+async fn cancellation_interrupts_a_blocked_write_and_preserves_unrelated_execution() {
+ let executions = StdinExecutions::default();
+ let busy = Arc::new(AtomicBool::new(false));
+ let mut other = request("IFS= read -r line; printf '%s' \"$line\"");
+ other.stdin_id = OTHER_ID.into();
+ let mut other_output = executions.start(other, Arc::clone(&busy)).unwrap();
+ ready(&mut other_output).await;
+
+ let mut blocked = request("sleep 30 & printf '%s %s\\n' $$ $!; wait");
+ blocked.exclusive = true;
+ let mut output = executions.start(blocked, Arc::clone(&busy)).unwrap();
+ ready(&mut output).await;
+ let writer_executions = executions.clone();
+ let writer = tokio::spawn(async move {
+ for _ in 0..128 {
+ if write(&writer_executions, ID, &vec![0; MAX_STDIN_CHUNK]).await {
+ return true;
+ }
+ }
+ false
+ });
+ sleep(Duration::from_millis(100)).await;
+ assert!(
+ !writer.is_finished(),
+ "a non-reading child should backpressure input"
+ );
+ assert!(timeout(Duration::from_secs(2), executions.cancel(ID))
+ .await
+ .unwrap());
+ assert!(timeout(Duration::from_secs(2), writer)
+ .await
+ .unwrap()
+ .unwrap());
+ let (stdout, stderr, code) = finish(output).await;
+ assert_eq!(code, -1);
+ assert!(stderr.contains("Command cancelled"));
+ for pid in stdout.split_whitespace() {
+ assert_process_stopped(pid.parse().unwrap()).await;
+ }
+ assert!(!busy.load(Ordering::SeqCst));
+ assert!(!write(&executions, OTHER_ID, b"survived\n").await);
+ assert!(eof(&executions, OTHER_ID).await);
+ assert_eq!(
+ finish(other_output).await,
+ ("survived".into(), "".into(), 0)
+ );
+ assert_clean(&executions, &busy);
+}
+
+#[tokio::test]
+async fn cancellation_does_not_wait_for_a_blocked_output_consumer() {
+ let executions = StdinExecutions::default();
+ let busy = Arc::new(AtomicBool::new(false));
+ let mut request = request("while :; do printf 'output without newline'; done");
+ request.exclusive = true;
+ let mut output = executions.start(request, Arc::clone(&busy)).unwrap();
+ ready(&mut output).await;
+ sleep(Duration::from_millis(50)).await;
+ assert!(timeout(Duration::from_secs(2), executions.cancel(ID))
+ .await
+ .unwrap());
+ assert_clean(&executions, &busy);
+ drop(output);
+}
+
+#[tokio::test]
+async fn output_disconnection_cancels_and_reaps_execution() {
+ let executions = StdinExecutions::default();
+ let busy = Arc::new(AtomicBool::new(false));
+ let mut request = request("printf '%s' $$; sleep 30");
+ request.exclusive = true;
+ let mut output = executions.start(request, Arc::clone(&busy)).unwrap();
+ ready(&mut output).await;
+ let pid = match next(&mut output).await {
+ OutputEvent::Stdout { data } => data.parse().unwrap(),
+ event => panic!("unexpected event: {event:?}"),
+ };
+ let mut done = executions.entries.lock().unwrap()[ID].done.clone();
+ drop(output);
+ timeout(Duration::from_secs(2), done.wait_for(|done| *done))
+ .await
+ .unwrap()
+ .unwrap();
+ assert_process_stopped(pid).await;
+ assert_clean(&executions, &busy);
+}
+
+#[tokio::test]
+async fn successful_exit_kills_background_descendants() {
+ let executions = StdinExecutions::default();
+ let busy = Arc::new(AtomicBool::new(false));
+ let mut output = executions
+ .start(request("sleep 30 & printf '%s' $!"), Arc::clone(&busy))
+ .unwrap();
+ ready(&mut output).await;
+ let (stdout, stderr, code) = finish(output).await;
+ assert_eq!((stderr.as_str(), code), ("", 0));
+ assert_process_stopped(stdout.parse().unwrap()).await;
+ assert_clean(&executions, &busy);
+}
diff --cc packages/dev/quicksand-image-tools/quicksand_image_tools/quicksand-guest-agent/src/transport_tests.rs
index f135352,0000000..42f59ca
mode 100644,000000..100644
--- a/packages/dev/quicksand-image-tools/quicksand_image_tools/quicksand-guest-agent/src/transport_tests.rs
+++ b/packages/dev/quicksand-image-tools/quicksand_image_tools/quicksand-guest-agent/src/transport_tests.rs
@@@ -1,641 -1,0 +1,785 @@@
+use super::*;
+use axum::{
+ body::{to_bytes, Body, BodyDataStream},
+ http::Request,
+ response::Response,
+};
+use base64::{engine::general_purpose::STANDARD, Engine};
+use serde_json::{json, Value};
+use tokio::time::sleep;
+use tower::ServiceExt;
+
+const ID: &str = "0123456789abcdef0123456789abcdef";
+const TOKEN: &str = "test-token";
++const MISSING_USER: &str = "quicksand-no-such-stdin-user";
++
++#[test]
++fn stdin_request_conversion_preserves_user_and_execution_options() {
++ let request: ExecuteRequest = serde_json::from_value(json!({
++ "stdin_id": ID,
++ "command": "cat",
++ "shell": "/bin/bash",
++ "cwd": "src",
++ "user": "quicksand-stream-user",
++ "timeout": 12.5,
++ "exclusive": true
++ }))
++ .unwrap();
++ let execution = request.into_stdin_execution();
++ assert_eq!(execution.stdin_id, ID);
++ assert_eq!(execution.command, "cat");
++ assert_eq!(execution.shell, "/bin/bash");
++ assert_eq!(execution.cwd.as_deref(), Some("src"));
++ assert_eq!(execution.user.as_deref(), Some("quicksand-stream-user"));
++ assert_eq!(execution.timeout, 12.5);
++ assert!(execution.exclusive);
++
++ let request: ExecuteRequest =
++ serde_json::from_value(json!({"stdin_id": ID, "command": "cat"})).unwrap();
++ let execution = request.into_stdin_execution();
++ assert_eq!(execution.shell, "/bin/sh");
++ assert!(execution.cwd.is_none());
++ assert!(execution.user.is_none());
++ assert_eq!(execution.timeout, 30.0);
++ assert!(!execution.exclusive);
++}
+
+fn state() -> AppState {
+ AppState {
+ token: Arc::new(TOKEN.into()),
+ exclusive_busy: Arc::new(AtomicBool::new(false)),
+ stdin_executions: StdinExecutions::default(),
+ }
+}
+
+async fn post_json(app: &Router, path: &str, value: Value, authenticated: bool) -> Response {
+ let mut request = Request::builder()
+ .method("POST")
+ .uri(path)
+ .header(header::CONTENT_TYPE, "application/json");
+ if authenticated {
+ request = request.header(header::AUTHORIZATION, format!("Bearer {TOKEN}"));
+ }
+ app.clone()
+ .oneshot(request.body(Body::from(value.to_string())).unwrap())
+ .await
+ .unwrap()
+}
+
+async fn response_json(response: Response) -> Value {
+ let bytes = to_bytes(response.into_body(), 1024 * 1024).await.unwrap();
+ serde_json::from_slice(&bytes).unwrap()
+}
+
+async fn sse_next(stream: &mut BodyDataStream) -> Value {
+ let frame = timeout(Duration::from_secs(3), stream.next())
+ .await
+ .expect("SSE event timed out")
+ .expect("SSE ended before exit")
+ .unwrap();
+ let frame = std::str::from_utf8(&frame).unwrap();
+ serde_json::from_str(frame.trim().strip_prefix("data:").unwrap().trim_start()).unwrap()
+}
+
+async fn wait_until_idle(busy: &AtomicBool) {
+ timeout(Duration::from_secs(3), async {
+ while busy.load(Ordering::SeqCst) {
+ sleep(Duration::from_millis(5)).await;
+ }
+ })
+ .await
+ .expect("exclusive state was not released");
+}
+
+#[tokio::test]
+async fn http_capability_gating_and_control_authentication() {
+ let app = http_router(state());
+ let response = post_json(&app, "/authenticate", json!({"token": TOKEN}), false).await;
+ assert_eq!(response.status(), StatusCode::OK);
+ assert_eq!(
+ response_json(response).await,
+ json!({"authenticated": true, "capabilities": ["stdin_streaming"]})
+ );
+ let response = post_json(&app, "/authenticate", json!({"token": "wrong"}), false).await;
+ assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
+ assert_eq!(
+ response_json(response).await,
+ json!({"authenticated": false})
+ );
+ for (path, params) in [
+ ("/stdin", json!({"stdin_id": ID, "data": ""})),
+ ("/stdin", json!({"stdin_id": ID, "eof": true})),
+ ("/cancel", json!({"stdin_id": ID})),
++ ("/create_user", json!({"name": "invalid:name"})),
++ ("/delete_user", json!({"name": "invalid:name"})),
+ ] {
+ let response = post_json(&app, path, params, false).await;
+ assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
+ assert_eq!(
+ response_json(response).await,
+ json!({"detail": "Invalid token"})
+ );
+ }
+}
+
++#[tokio::test]
++async fn http_account_management_routes_remain_available() {
++ let app = http_router(state());
++ // Invalid names exercise both handlers without touching any host accounts.
++ for path in ["/create_user", "/delete_user"] {
++ let response = post_json(&app, path, json!({"name": "invalid:name"}), true).await;
++ assert_eq!(response.status(), StatusCode::BAD_REQUEST);
++ assert_eq!(
++ response_json(response).await,
++ json!({"detail": "Invalid username: invalid:name"})
++ );
++ }
++}
++
++#[tokio::test]
++async fn http_unknown_users_are_rejected_before_exclusive_state_changes() {
++ assert!(lookup_user(MISSING_USER).is_none());
++ let state = state();
++ let app = http_router(state.clone());
++ for already_busy in [false, true] {
++ state.exclusive_busy.store(already_busy, Ordering::SeqCst);
++ for (path, piped) in [
++ ("/execute", false),
++ ("/execute_stream", false),
++ ("/execute_stream", true),
++ ] {
++ let mut params = json!({
++ "command": "printf should-not-run",
++ "user": MISSING_USER,
++ "exclusive": true
++ });
++ if piped {
++ params["stdin_id"] = json!(ID);
++ }
++ let response = post_json(&app, path, params, true).await;
++ assert_eq!(response.status(), StatusCode::BAD_REQUEST);
++ assert_eq!(
++ response_json(response).await,
++ json!({"detail": format!("No such user: {MISSING_USER}")})
++ );
++ assert_eq!(
++ state.exclusive_busy.load(Ordering::SeqCst),
++ already_busy
++ );
++ let response = post_json(&app, "/cancel", json!({"stdin_id": ID}), true).await;
++ assert_eq!(response_json(response).await, json!({"cancelled": false}));
++ }
++ }
++}
++
+#[tokio::test]
+async fn http_binary_input_eof_and_exclusive_controls() {
+ let state = state();
+ let app = http_router(state.clone());
+ let response = post_json(
+ &app,
+ "/execute_stream",
+ json!({"stdin_id": ID, "command": "od -An -v -tx1", "exclusive": true}),
+ true,
+ )
+ .await;
+ assert_eq!(response.status(), StatusCode::OK);
+ assert_eq!(
+ response.headers()[header::CONTENT_TYPE],
+ "text/event-stream"
+ );
+ let mut output = response.into_body().into_data_stream();
+ assert_eq!(sse_next(&mut output).await, json!({"stream": "ready"}));
+ let response = post_json(&app, "/execute", json!({"command": "printf wrong"}), true).await;
+ assert_eq!(response.status(), StatusCode::SERVICE_UNAVAILABLE);
+ for bytes in [&b"\0\xff"[..], &b"\x80\n\r"[..]] {
+ let response = post_json(
+ &app,
+ "/stdin",
+ json!({"stdin_id": ID, "data": STANDARD.encode(bytes)}),
+ true,
+ )
+ .await;
+ assert_eq!(response.status(), StatusCode::OK);
+ assert_eq!(response_json(response).await, json!({"closed": false}));
+ }
+ let response = post_json(&app, "/stdin", json!({"stdin_id": ID, "eof": true}), true).await;
+ assert_eq!(response_json(response).await, json!({"closed": true}));
+ let mut stdout = String::new();
+ loop {
+ let event = sse_next(&mut output).await;
+ assert!(event.get("id").is_none());
+ match event["stream"].as_str().unwrap() {
+ "stdout" => stdout.push_str(event["data"].as_str().unwrap()),
+ "exit" => {
+ assert_eq!(event["exit_code"], 0);
+ break;
+ }
+ stream => panic!("unexpected stream {stream}: {event}"),
+ }
+ }
+ assert_eq!(
+ stdout.split_whitespace().collect::<Vec<_>>(),
+ ["00", "ff", "80", "0a", "0d"]
+ );
+ assert!(!state.exclusive_busy.load(Ordering::SeqCst));
+ let response = post_json(&app, "/stdin", json!({"stdin_id": ID, "data": ""}), true).await;
+ assert_eq!(response_json(response).await, json!({"closed": true}));
+ let response = post_json(&app, "/cancel", json!({"stdin_id": ID}), true).await;
+ assert_eq!(response_json(response).await, json!({"cancelled": false}));
+}
+
+#[tokio::test]
+async fn http_validation_duplicate_ids_and_startup_errors_are_explicit() {
+ let state = state();
+ let app = http_router(state.clone());
+ for params in [
+ json!({"stdin_id": ID, "eof": false}),
+ json!({"stdin_id": ID, "eof": true, "data": ""}),
+ json!({"stdin_id": ID, "data": "!!!"}),
+ json!({"stdin_id": ID, "data": STANDARD.encode(vec![0; 65537])}),
+ ] {
+ let response = post_json(&app, "/stdin", params, true).await;
+ assert_eq!(response.status(), StatusCode::BAD_REQUEST);
+ assert!(response_json(response).await["detail"].is_string());
+ }
+ for params in [
+ json!({"stdin_id": "invalid", "command": "cat"}),
+ json!({"stdin_id": ID, "command": "cat", "timeout": -1}),
+ ] {
+ let response = post_json(&app, "/execute_stream", params, true).await;
+ assert_eq!(response.status(), StatusCode::BAD_REQUEST);
+ }
+ let params = json!({"stdin_id": ID, "command": "cat", "exclusive": true});
+ let response = post_json(&app, "/execute_stream", params.clone(), true).await;
+ let mut output = response.into_body().into_data_stream();
+ assert_eq!(sse_next(&mut output).await["stream"], "ready");
+ let duplicate = post_json(&app, "/execute_stream", params, true).await;
+ assert_eq!(duplicate.status(), StatusCode::CONFLICT);
+ let response = post_json(&app, "/cancel", json!({"stdin_id": ID}), true).await;
+ assert_eq!(response_json(response).await, json!({"cancelled": true}));
+ assert!(!state.exclusive_busy.load(Ordering::SeqCst));
+ assert_eq!(sse_next(&mut output).await["stream"], "stderr");
+ assert_eq!(
+ sse_next(&mut output).await,
+ json!({"stream": "exit", "exit_code": -1})
+ );
+ let response = post_json(
+ &app,
+ "/execute_stream",
+ json!({"stdin_id": ID, "command": "cat", "shell": "./quicksand-no-such-shell", "exclusive": true}),
+ true,
+ )
+ .await;
+ let mut output = response.into_body().into_data_stream();
+ let error = sse_next(&mut output).await;
+ assert_eq!(error["stream"], "stderr");
+ assert!(error["data"]
+ .as_str()
+ .unwrap()
+ .contains("Failed to start command"));
+ assert_eq!(
+ sse_next(&mut output).await,
+ json!({"stream": "exit", "exit_code": -1})
+ );
+ assert!(!state.exclusive_busy.load(Ordering::SeqCst));
+}
+
+#[tokio::test]
+async fn http_sse_disconnection_cancels_the_execution() {
+ let state = state();
+ let app = http_router(state.clone());
+ let response = post_json(
+ &app,
+ "/execute_stream",
+ json!({"stdin_id": ID, "command": "sleep 30", "exclusive": true}),
+ true,
+ )
+ .await;
+ let mut output = response.into_body().into_data_stream();
+ assert_eq!(sse_next(&mut output).await["stream"], "ready");
+ drop(output);
+ wait_until_idle(&state.exclusive_busy).await;
+ assert!(!state.stdin_executions.cancel(ID).await);
+}
+
+#[tokio::test]
+async fn http_disconnection_before_ready_cancels_execution() {
+ let state = state();
+ let app = http_router(state.clone());
+ let response = post_json(
+ &app,
+ "/execute_stream",
+ json!({"stdin_id": ID, "command": "sleep 30", "exclusive": true}),
+ true,
+ )
+ .await;
+ assert!(state.exclusive_busy.load(Ordering::SeqCst));
+ // Abandon the response without ever polling its SSE body.
+ drop(response);
+ wait_until_idle(&state.exclusive_busy).await;
+ assert!(!state.stdin_executions.cancel(ID).await);
+}
+
+#[tokio::test]
+async fn http_legacy_execution_shapes_and_line_streaming_are_unchanged() {
+ let app = http_router(state());
+ let response = post_json(&app, "/execute", json!({"command": "printf legacy"}), true).await;
+ assert_eq!(
+ response_json(response).await,
+ json!({"stdout": "legacy", "stderr": "", "exit_code": 0})
+ );
+ let response = post_json(
+ &app,
+ "/execute_stream",
+ json!({"command": "printf legacy"}),
+ true,
+ )
+ .await;
+ let mut output = response.into_body().into_data_stream();
+ assert_eq!(
+ sse_next(&mut output).await,
+ json!({"stream": "stdout", "data": "legacy\n"})
+ );
+ assert_eq!(
+ sse_next(&mut output).await,
+ json!({"stream": "exit", "exit_code": 0})
+ );
+}
+
+struct SerialTest {
+ peer: Arc<SerialChannel>,
+ server: tokio::task::JoinHandle<()>,
+ executions: StdinExecutions,
+ busy: Arc<AtomicBool>,
+}
+
+impl SerialTest {
+ fn new() -> Self {
+ let (server, peer) = std::os::unix::net::UnixStream::pair().unwrap();
+ server.set_nonblocking(true).unwrap();
+ peer.set_nonblocking(true).unwrap();
+ let channel = |socket: std::os::unix::net::UnixStream| {
+ Arc::new(SerialChannel {
+ fd: tokio::io::unix::AsyncFd::new(std::os::fd::OwnedFd::from(socket)).unwrap(),
+ })
+ };
+ let executions = StdinExecutions::default();
+ let busy = Arc::new(AtomicBool::new(false));
+ let server = tokio::spawn(serve_virtio_serial(
+ channel(server),
+ TOKEN.into(),
+ Arc::clone(&busy),
+ executions.clone(),
+ ));
+ Self {
+ peer: channel(peer),
+ server,
+ executions,
+ busy,
+ }
+ }
+
+ async fn send(&self, id: u64, method: &str, params: Value) {
+ write_frame_serial(
+ &self.peer,
+ &json!({"id": id, "method": method, "params": params}),
+ )
+ .await
+ .unwrap();
+ }
+
+ async fn recv(&self) -> Value {
+ timeout(Duration::from_secs(3), read_frame_serial(&self.peer))
+ .await
+ .expect("serial response timed out")
+ .unwrap()
+ }
+
+ async fn authenticate(&self) {
+ self.send(1, "authenticate", json!({"token": TOKEN})).await;
+ assert_eq!(
+ self.recv().await,
+ json!({"id": 1, "result": {"authenticated": true, "capabilities": ["stdin_streaming"]}})
+ );
+ }
+
+ async fn disconnect(self) {
+ drop(self.peer);
+ timeout(Duration::from_secs(3), self.server)
+ .await
+ .expect("serial server did not shut down")
+ .unwrap();
+ assert!(!self.busy.load(Ordering::SeqCst));
+ assert!(!self.executions.cancel(ID).await);
+ }
+}
+
+#[tokio::test]
+async fn serial_controls_require_authentication_and_legacy_execution_still_works() {
+ let serial = SerialTest::new();
+ for (id, method, params) in [
+ (10, "stdin", json!({"stdin_id": ID, "data": ""})),
+ (11, "cancel", json!({"stdin_id": ID})),
++ (15, "create_user", json!({"name": "invalid:name"})),
++ (16, "delete_user", json!({"name": "invalid:name"})),
+ ] {
+ serial.send(id, method, params).await;
+ assert_eq!(
+ serial.recv().await,
+ json!({"id": id, "error": {"message": "Not authenticated"}})
+ );
+ }
+ serial
+ .send(12, "authenticate", json!({"token": "wrong"}))
+ .await;
+ assert_eq!(
+ serial.recv().await,
+ json!({"id": 12, "result": {"authenticated": false}})
+ );
+ serial.authenticate().await;
+ serial
+ .send(13, "execute", json!({"command": "printf legacy"}))
+ .await;
+ assert_eq!(
+ serial.recv().await,
+ json!({"id": 13, "result": {"stdout": "legacy", "stderr": "", "exit_code": 0}})
+ );
+ serial
+ .send(14, "execute_stream", json!({"command": "printf legacy"}))
+ .await;
+ assert_eq!(
+ serial.recv().await,
+ json!({"id": 14, "stream": "stdout", "data": "legacy\n"})
+ );
+ assert_eq!(
+ serial.recv().await,
+ json!({"id": 14, "stream": "exit", "exit_code": 0})
+ );
+ serial.disconnect().await;
+}
+
++#[tokio::test]
++async fn serial_account_management_methods_remain_available() {
++ let serial = SerialTest::new();
++ serial.authenticate().await;
++ for (id, method) in [(2, "create_user"), (3, "delete_user")] {
++ serial.send(id, method, json!({"name": "invalid:name"})).await;
++ assert_eq!(
++ serial.recv().await,
++ json!({"id": id, "error": {"message": "Invalid username: invalid:name"}})
++ );
++ }
++ serial.disconnect().await;
++}
++
++#[tokio::test]
++async fn serial_unknown_users_are_rejected_before_exclusive_state_changes() {
++ assert!(lookup_user(MISSING_USER).is_none());
++ let serial = SerialTest::new();
++ serial.authenticate().await;
++ for already_busy in [false, true] {
++ serial.busy.store(already_busy, Ordering::SeqCst);
++ for (id, method, piped) in [
++ (2, "execute", false),
++ (3, "execute_stream", false),
++ (4, "execute_stream", true),
++ ] {
++ let mut params = json!({
++ "command": "printf should-not-run",
++ "user": MISSING_USER,
++ "exclusive": true
++ });
++ if piped {
++ params["stdin_id"] = json!(ID);
++ }
++ serial.send(id, method, params).await;
++ let message = format!("No such user: {MISSING_USER}");
++ let expected = if method == "execute" {
++ json!({"id": id, "result": {"stdout": "", "stderr": message, "exit_code": -1}})
++ } else if piped {
++ json!({"id": id, "error": {"message": message}})
++ } else {
++ json!({"id": id, "stream": "stderr", "data": format!("{message}\n")})
++ };
++ assert_eq!(serial.recv().await, expected);
++ if method == "execute_stream" {
++ assert_eq!(
++ serial.recv().await,
++ json!({"id": id, "stream": "exit", "exit_code": -1})
++ );
++ }
++ assert_eq!(serial.busy.load(Ordering::SeqCst), already_busy);
++ assert!(!serial.executions.cancel(ID).await);
++ }
++ }
++ serial.busy.store(false, Ordering::SeqCst);
++ serial.disconnect().await;
++}
++
+#[tokio::test]
+async fn serial_ready_incremental_output_shell_and_control_ack_ids() {
+ let serial = SerialTest::new();
+ serial.authenticate().await;
+ serial
+ .send(
+ 2,
+ "execute_stream",
+ json!({
+ "stdin_id": ID,
+ "command": "test -n \"$BASH_VERSION\" || exit 42; printf 'prompt:'; IFS= read -r line; printf '<%s>' \"$line\"; printf err >&2",
+ "shell": "/bin/bash",
+ "exclusive": true
+ }),
+ )
+ .await;
+ assert_eq!(serial.recv().await, json!({"id": 2, "stream": "ready"}));
+ assert_eq!(
+ serial.recv().await,
+ json!({"id": 2, "stream": "stdout", "data": "prompt:"})
+ );
+ serial
+ .send(
+ 3,
+ "stdin",
+ json!({"stdin_id": ID, "data": STANDARD.encode(b"hello\n")}),
+ )
+ .await;
+ let mut events = Vec::new();
+ loop {
+ let frame = serial.recv().await;
+ if frame["id"] == 3 {
+ assert_eq!(frame, json!({"id": 3, "result": {"closed": false}}));
+ break;
+ }
+ events.push(frame);
+ }
+ serial
+ .send(4, "stdin", json!({"stdin_id": ID, "eof": true}))
+ .await;
+ let mut eof_ack = false;
+ while !eof_ack || !events.iter().any(|event| event["stream"] == "exit") {
+ let frame = serial.recv().await;
+ if frame["id"] == 4 {
+ assert_eq!(frame, json!({"id": 4, "result": {"closed": true}}));
+ eof_ack = true;
+ } else {
+ events.push(frame);
+ }
+ }
+ let mut stdout = String::new();
+ let mut stderr = String::new();
+ for event in events {
+ assert_eq!(event["id"], 2);
+ match event["stream"].as_str().unwrap() {
+ "stdout" => stdout.push_str(event["data"].as_str().unwrap()),
+ "stderr" => stderr.push_str(event["data"].as_str().unwrap()),
+ "exit" => assert_eq!(event["exit_code"], 0),
+ stream => panic!("unexpected stream {stream}"),
+ }
+ }
+ assert_eq!((stdout.as_str(), stderr.as_str()), ("<hello>", "err"));
+ serial.disconnect().await;
+}
+
+#[tokio::test]
+async fn serial_cancel_before_ready_observation_finds_registered_execution() {
+ let serial = SerialTest::new();
+ serial.authenticate().await;
+ let mut frames = Vec::new();
+ for frame in [
+ json!({
+ "id": 2,
+ "method": "execute_stream",
+ "params": {"stdin_id": ID, "command": "sleep 30", "exclusive": true}
+ }),
+ json!({"id": 3, "method": "cancel", "params": {"stdin_id": ID}}),
+ ] {
+ let payload = serde_json::to_vec(&frame).unwrap();
+ frames.extend_from_slice(&(payload.len() as u32).to_be_bytes());
+ frames.extend_from_slice(&payload);
+ }
+ // Queue both frames in order, without waiting for or reading ready.
+ serial.peer.write_all(&frames).await.unwrap();
+ let mut cancelled = false;
+ let mut exited = false;
+ while !cancelled || !exited {
+ let response = serial.recv().await;
+ if response["id"] == 3 {
+ assert_eq!(response, json!({"id": 3, "result": {"cancelled": true}}));
+ cancelled = true;
+ } else {
+ assert_eq!(response["id"], 2);
+ match response["stream"].as_str().unwrap() {
+ "ready" => {}
+ "stderr" => assert!(response["data"].as_str().unwrap().contains("cancelled")),
+ "exit" => {
+ assert_eq!(response["exit_code"], -1);
+ exited = true;
+ }
+ stream => panic!("unexpected stream {stream}"),
+ }
+ }
+ }
+ assert!(!serial.busy.load(Ordering::SeqCst));
+ serial
+ .send(4, "stdin", json!({"stdin_id": ID, "eof": true}))
+ .await;
+ assert_eq!(
+ serial.recv().await,
+ json!({"id": 4, "result": {"closed": true}})
+ );
+ serial.disconnect().await;
+}
+
+#[tokio::test]
+async fn serial_cancel_is_dispatched_while_a_pipe_write_is_blocked() {
+ let serial = SerialTest::new();
+ serial.authenticate().await;
+ serial
+ .send(
+ 2,
+ "execute_stream",
+ json!({"stdin_id": ID, "command": "sleep 30", "exclusive": true}),
+ )
+ .await;
+ assert_eq!(serial.recv().await, json!({"id": 2, "stream": "ready"}));
+ let mut blocked_id = None;
+ let mut events = Vec::new();
+ for id in 10..42 {
+ serial
+ .send(
+ id,
+ "stdin",
+ json!({"stdin_id": ID, "data": STANDARD.encode(vec![0; 65536])}),
+ )
+ .await;
+ let response = read_frame_serial(&serial.peer);
+ tokio::pin!(response);
+ match timeout(Duration::from_millis(50), &mut response).await {
+ Ok(frame) => assert_eq!(
+ frame.unwrap(),
+ json!({"id": id, "result": {"closed": false}})
+ ),
+ Err(_) => {
+ serial.send(100, "cancel", json!({"stdin_id": ID})).await;
+ events.push(
+ timeout(Duration::from_secs(3), &mut response)
+ .await
+ .unwrap()
+ .unwrap(),
+ );
+ blocked_id = Some(id);
+ break;
+ }
+ }
+ }
+ let blocked_id = blocked_id.expect("non-reading child did not backpressure stdin");
+ while !events.iter().any(|event| event["id"] == 100)
+ || !events.iter().any(|event| event["id"] == blocked_id)
+ || !events.iter().any(|event| event["stream"] == "exit")
+ {
+ events.push(serial.recv().await);
+ }
+ assert!(events.contains(&json!({"id": 100, "result": {"cancelled": true}})));
+ assert!(events.contains(&json!({"id": blocked_id, "result": {"closed": true}})));
+ assert!(events.contains(&json!({"id": 2, "stream": "exit", "exit_code": -1})));
+ assert!(!serial.busy.load(Ordering::SeqCst));
+ serial.send(101, "ping", json!({})).await;
+ let ping = serial.recv().await;
+ assert_eq!(ping["id"], 101);
+ assert_eq!(ping["result"]["pong"], true);
+ serial.disconnect().await;
+}
+
+#[tokio::test]
+async fn serial_validation_duplicate_ids_and_startup_errors_are_terminal() {
+ let serial = SerialTest::new();
+ serial.authenticate().await;
+ for (id, method, params) in [
+ (10, "stdin", json!({"stdin_id": ID, "eof": false})),
+ (11, "cancel", json!({"stdin_id": ID, "data": ""})),
+ ] {
+ serial.send(id, method, params).await;
+ let response = serial.recv().await;
+ assert_eq!(response["id"], id);
+ assert!(response["error"]["message"].is_string());
+ }
+ serial
+ .send(
+ 20,
+ "execute_stream",
+ json!({"stdin_id": ID, "command": "cat >/dev/null"}),
+ )
+ .await;
+ assert_eq!(serial.recv().await, json!({"id": 20, "stream": "ready"}));
+ serial
+ .send(
+ 21,
+ "execute_stream",
+ json!({"stdin_id": ID, "command": "printf wrong"}),
+ )
+ .await;
+ assert_eq!(
+ serial.recv().await,
+ json!({"id": 21, "error": {"message": "stdin_id is already active"}})
+ );
+ assert_eq!(
+ serial.recv().await,
+ json!({"id": 21, "stream": "exit", "exit_code": -1})
+ );
+ serial
+ .send(22, "stdin", json!({"stdin_id": ID, "eof": true}))
+ .await;
+ let mut completed = false;
+ let mut acknowledged = false;
+ while !completed || !acknowledged {
+ let response = serial.recv().await;
+ if response["id"] == 20 {
+ assert_eq!(
+ response,
+ json!({"id": 20, "stream": "exit", "exit_code": 0})
+ );
+ completed = true;
+ } else {
+ assert_eq!(response, json!({"id": 22, "result": {"closed": true}}));
+ acknowledged = true;
+ }
+ }
+ serial
+ .send(
+ 30,
+ "execute_stream",
+ json!({"stdin_id": ID, "command": "cat", "shell": "./quicksand-no-such-shell", "exclusive": true}),
+ )
+ .await;
+ let error = serial.recv().await;
+ assert_eq!(error["id"], 30);
+ assert_eq!(error["stream"], "stderr");
+ assert!(error["data"]
+ .as_str()
+ .unwrap()
+ .contains("Failed to start command"));
+ assert_eq!(
+ serial.recv().await,
+ json!({"id": 30, "stream": "exit", "exit_code": -1})
+ );
+ assert!(!serial.busy.load(Ordering::SeqCst));
+ serial.disconnect().await;
+}
+
+#[tokio::test]
+async fn serial_disconnect_cancels_active_stdin_executions() {
+ let serial = SerialTest::new();
+ serial.authenticate().await;
+ serial
+ .send(
+ 2,
+ "execute_stream",
+ json!({"stdin_id": ID, "command": "sleep 30", "exclusive": true}),
+ )
+ .await;
+ assert_eq!(serial.recv().await, json!({"id": 2, "stream": "ready"}));
+ assert!(serial.busy.load(Ordering::SeqCst));
+ serial.disconnect().await;
+}
diff --cc packages/quicksand-core/quicksand_core/_types.py
index 79b0e51,4855f6f..d8f9fe1
--- a/packages/quicksand-core/quicksand_core/_types.py
+++ b/packages/quicksand-core/quicksand_core/_types.py
@@@ -243,10 -242,10 +243,12 @@@ class QuicksandGuestAgentMethod(StrEnum
EXECUTE = "execute"
EXECUTE_STREAM = "execute_stream"
+ STDIN = "stdin"
+ CANCEL = "cancel"
PING = "ping"
AUTHENTICATE = "authenticate"
+ CREATE_USER = "create_user"
+ DELETE_USER = "delete_user"
# =============================================================================
diff --cc packages/quicksand-core/quicksand_core/host/virtio_serial_agent_client.py
index c853816,bd780d4..85acb1d
--- a/packages/quicksand-core/quicksand_core/host/virtio_serial_agent_client.py
+++ b/packages/quicksand-core/quicksand_core/host/virtio_serial_agent_client.py
@@@ -306,8 -294,8 +306,10 @@@ class VirtioSerialAgentClient
method_map = {
QuicksandGuestAgentMethod.EXECUTE: "execute",
QuicksandGuestAgentMethod.PING: "ping",
+ QuicksandGuestAgentMethod.STDIN: "stdin",
+ QuicksandGuestAgentMethod.CANCEL: "cancel",
+ QuicksandGuestAgentMethod.CREATE_USER: "create_user",
+ QuicksandGuestAgentMethod.DELETE_USER: "delete_user",
}
method_name = method_map.get(method)
if method_name is None:
diff --cc packages/quicksand-core/quicksand_core/sandbox/_execution.py
index 639c3a8,35fe2af..f2ff8ed
--- a/packages/quicksand-core/quicksand_core/sandbox/_execution.py
+++ b/packages/quicksand-core/quicksand_core/sandbox/_execution.py
@@@ -37,8 -36,7 +37,9 @@@ class _ExecutionMixin(_SandboxProtocol)
on_stdout: Callable[[str], None] | None = None,
on_stderr: Callable[[str], None] | None = None,
exclusive: bool = False,
+ user: str | None = None,
+ *,
+ stdin: StdinSource | None = None,
) -> ExecuteResult:
"""
Execute a shell command inside the sandbox.
@@@ -58,10 -56,11 +59,15 @@@
exclusive: If True, the guest agent will reject other requests
while this command is running. Used for system commands
like sync/fstrim that need exclusive access.
+ user: Optional OS user to run the command as. The command runs
+ with that user's uid/gid/groups and HOME, defaulting cwd to
+ the user's home directory. The user must already exist (see
+ ``create_user``). Prefer obtaining a ``SandboxUser`` via
+ ``create_user`` and calling ``.execute()`` on it.
+ stdin: Input bytes, a UTF-8 string, or an async iterable of byte
+ chunks. Iterable exhaustion closes stdin. Input is consumed
+ incrementally and stops when the command exits. Requires
+ an image with a stdin-capable guest agent.
Returns:
ExecuteResult with stdout, stderr, and exit_code.
@@@ -98,3 -96,108 +104,111 @@@
result = ExecuteResponseResult(**response["result"])
return ExecuteResult(stdout=result.stdout, stderr=result.stderr, exit_code=result.exit_code)
+
+ async def create_user(self, name: str) -> SandboxUser:
+ """Create an OS user in the sandbox and return a handle scoped to it.
+
+ Distro-agnostic: the guest agent creates the account by writing the
+ standard POSIX files (``/etc/passwd``, ``/etc/group``, ``/etc/shadow``),
+ so it behaves identically on Alpine, Ubuntu, and any other guest with
+ no dependency on distro-specific ``adduser``/``useradd`` tools.
+
+ Multiple users share one VM, giving logical per-user isolation
+ (separate ``$HOME``, ownership, credentials) without the memory cost of
+ a separate VM per user.
+
+ Args:
+ name: Username. Must match ``[a-z_][a-z0-9_-]*`` (max 32 chars).
+
+ Returns:
+ A ``SandboxUser`` whose ``execute`` runs commands as this user.
+
+ Raises:
+ RuntimeError: If the sandbox is not running, or creation fails
+ (e.g. invalid name or the user already exists).
+ """
+ if not self.is_running:
+ raise RuntimeError("Sandbox is not running")
+ response = await self._send_request(QuicksandGuestAgentMethod.CREATE_USER, {"name": name})
+ if "error" in response:
+ message = response["error"].get("message", "unknown error")
+ raise RuntimeError(f"Failed to create user {name!r}: {message}")
+ result = response["result"]
+ return SandboxUser(self, name, uid=result["uid"], gid=result["gid"], home=result["home"])
+
+ async def delete_user(self, name: str, *, remove_home: bool = True) -> None:
+ """Delete an OS user from the sandbox.
+
+ Kills the user's running processes, removes the account entries, and
+ (by default) deletes the home directory.
+
+ Args:
+ name: Username to delete.
+ remove_home: If True (default), also remove ``/home/<name>``.
+
+ Raises:
+ RuntimeError: If the sandbox is not running, or deletion fails.
+ """
+ if not self.is_running:
+ raise RuntimeError("Sandbox is not running")
+ response = await self._send_request(
+ QuicksandGuestAgentMethod.DELETE_USER,
+ {"name": name, "remove_home": remove_home},
+ )
+ if "error" in response:
+ message = response["error"].get("message", "unknown error")
+ raise RuntimeError(f"Failed to delete user {name!r}: {message}")
+
+
+ class SandboxUser:
+ """A handle to an OS user inside a running sandbox.
+
+ Returned by :meth:`Sandbox.create_user`. Its :meth:`execute` runs commands
+ as this user (uid/gid/supplementary groups and ``HOME``), defaulting the
+ working directory to the user's home. It is a thin view over the sandbox's
+ single control channel — every user multiplexes over the same agent
+ connection, so there is no per-user VM overhead.
+ """
+
+ def __init__(
+ self,
+ sandbox: _ExecutionMixin,
+ name: str,
+ *,
+ uid: int,
+ gid: int,
+ home: str,
+ ):
+ self._sandbox = sandbox
+ self.name = name
+ self.uid = uid
+ self.gid = gid
+ self.home = home
+
+ async def execute(
+ self,
+ command: str,
+ timeout: float = Timeouts.GUEST_AGENT_REQUEST,
+ cwd: str | None = None,
+ shell: str = GuestCommands.SHELL,
+ on_stdout: Callable[[str], None] | None = None,
+ on_stderr: Callable[[str], None] | None = None,
+ exclusive: bool = False,
++ *,
++ stdin: StdinSource | None = None,
+ ) -> ExecuteResult:
+ """Execute a command as this user. See :meth:`Sandbox.execute`."""
+ return await self._sandbox.execute(
+ command,
+ timeout=timeout,
+ cwd=cwd,
+ shell=shell,
+ on_stdout=on_stdout,
+ on_stderr=on_stderr,
+ exclusive=exclusive,
+ user=self.name,
++ stdin=stdin,
+ )
+
+ def __repr__(self) -> str:
+ return f"SandboxUser(name={self.name!r}, uid={self.uid}, home={self.home!r})"
diff --cc packages/quicksand-core/quicksand_core/sandbox/_protocol.py
index 2eccfb6,9714407..f268d93
--- a/packages/quicksand-core/quicksand_core/sandbox/_protocol.py
+++ b/packages/quicksand-core/quicksand_core/sandbox/_protocol.py
@@@ -78,8 -77,7 +78,9 @@@ class _SandboxProtocol(Protocol)
on_stdout: Callable[[str], None] | None = None,
on_stderr: Callable[[str], None] | None = None,
exclusive: bool = False,
+ user: str | None = None,
+ *,
+ stdin: StdinSource | None = None,
) -> ExecuteResult: ...
async def save(
diff --cc tests/integration/execution/test_stdin.py
index 07e0e1c,0000000..98a273c
mode 100644,000000..100644
--- a/tests/integration/execution/test_stdin.py
+++ b/tests/integration/execution/test_stdin.py
@@@ -1,178 -1,0 +1,237 @@@
+"""End-to-end stdin behavior with a stdin-capable guest image."""
+
+from __future__ import annotations
+
+import asyncio
+import contextlib
+import hashlib
+import os
+
+import pytest
+import pytest_asyncio
+from quicksand import Sandbox
+from quicksand_core.host.quicksand_guest_agent_client import QuicksandGuestAgentClient
+from quicksand_core.host.virtio_serial_agent_client import VirtioSerialAgentClient
+
+from tests.conftest import has_qemu
+from tests.integration.conftest import get_vm_type
+
+
+class _HttpSandbox(Sandbox):
+ def _build_vm_command(self) -> list[str]:
+ self._agent_socket_path = None
+ self._agent_socket_port = None
+ return super()._build_vm_command()
+
+
+@pytest_asyncio.fixture(scope="module", params=["virtio", "http"])
+async def stdin_sandbox(request):
+ if not has_qemu():
+ pytest.skip("QEMU not installed")
+ image = os.environ.get("QUICKSAND_STDIN_TEST_IMAGE", get_vm_type())
+ sandbox_class = _HttpSandbox if request.param == "http" else Sandbox
+ sandbox = sandbox_class(image=image)
+ try:
+ await sandbox.start()
+ assert sandbox._agent_client is not None
+ if not sandbox._agent_client.supports_stdin:
+ pytest.skip("Guest image must be rebuilt with stdin_streaming support")
+ expected_client = (
+ QuicksandGuestAgentClient if request.param == "http" else VirtioSerialAgentClient
+ )
+ assert isinstance(sandbox._agent_client, expected_client)
+ yield sandbox
+ finally:
+ await sandbox.stop()
+
+
+async def test_binary_stdin_is_streamed_without_corruption(stdin_sandbox):
+ payload = bytes(range(256)) * 4096
+
+ async def chunks():
+ yield b""
+ yield payload[:1]
+ yield payload[1:100001]
+ yield payload[100001:]
+
+ result = await stdin_sandbox.execute("sha256sum", stdin=chunks())
+ assert result.exit_code == 0, result.stderr
+ assert result.stdout.split()[0] == hashlib.sha256(payload).hexdigest()
+
+
+async def test_stdin_can_wait_for_output_without_a_newline(stdin_sandbox):
+ prompt = asyncio.Event()
+ reply = asyncio.Event()
+ output = []
+
+ async def chunks():
+ await prompt.wait()
+ yield b"hello\n"
+ await reply.wait()
+ yield b"world\n"
+
+ def on_stdout(chunk):
+ output.append(chunk)
+ text = "".join(output)
+ if "prompt>" in text:
+ prompt.set()
+ if "received:hello" in text:
+ reply.set()
+
+ result = await stdin_sandbox.execute(
+ "printf 'prompt>'; IFS= read -r line; printf 'received:%s' \"$line\"; cat",
+ stdin=chunks(),
+ on_stdout=on_stdout,
+ timeout=10,
+ exclusive=True,
+ )
+ assert result.exit_code == 0, result.stderr
+ assert result.stdout == "prompt>received:helloworld\n"
+
+
+async def test_empty_stdin_sends_eof(stdin_sandbox):
+ result = await stdin_sandbox.execute("wc -c", stdin=b"")
+ assert result.exit_code == 0, result.stderr
+ assert result.stdout.strip() == "0"
+
+
+async def test_early_exit_stops_stdin_producer(stdin_sandbox):
+ closed = asyncio.Event()
+
+ async def chunks():
+ try:
+ yield b"first"
+ await asyncio.Event().wait()
+ finally:
+ closed.set()
+
+ result = await stdin_sandbox.execute("head -c 1", stdin=chunks())
+ assert result.exit_code == 0, result.stderr
+ assert result.stdout == "f"
+ assert closed.is_set()
+
+
+async def test_stdin_cancellation_kills_process_group(stdin_sandbox):
+ started = asyncio.Event()
+ output = []
+
+ def on_stdout(chunk):
+ output.append(chunk)
+ if "\n" in "".join(output):
+ started.set()
+
+ async def chunks():
+ await asyncio.Event().wait()
+ yield b"unused"
+
+ task = asyncio.create_task(
+ stdin_sandbox.execute(
+ 'sleep 30 & printf \'%s %s\\n\' "$$" "$!"; wait',
+ stdin=chunks(),
+ on_stdout=on_stdout,
+ exclusive=True,
+ )
+ )
+ try:
+ await asyncio.wait_for(started.wait(), timeout=5)
+ pids = [int(part) for part in "".join(output).strip().split()]
+ assert len(pids) == 2
+ task.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await task
+ finally:
+ if not task.done():
+ task.cancel()
+ with contextlib.suppress(asyncio.CancelledError):
+ await task
+
+ for _ in range(50):
+ result = await stdin_sandbox.execute(" && ".join(f"test ! -d /proc/{pid}" for pid in pids))
+ if result.exit_code == 0:
+ break
+ await asyncio.sleep(0.05)
+ assert result.exit_code == 0, "Cancelled command or descendant is still running"
+
+
+async def test_stdin_timeout_releases_exclusive_command(stdin_sandbox):
+ async def chunks():
+ await asyncio.Event().wait()
+ yield b"unused"
+
+ result = await stdin_sandbox.execute("sleep 30", stdin=chunks(), timeout=0.2, exclusive=True)
+ assert result.exit_code == -1
+ assert "timed out" in result.stderr
+ result = await stdin_sandbox.execute("printf available")
+ assert result.exit_code == 0, result.stderr
+ assert result.stdout == "available"
++
++
++async def test_stdin_runs_as_sandbox_user(stdin_sandbox):
++ user = await stdin_sandbox.create_user("stdin_alice")
++ try:
++
++ async def chunks():
++ yield b"owned by "
++ yield b"alice"
++
++ result = await user.execute(
++ "id -u; id -g; id -G;"
++ ' printf \'%s\\n\' "$HOME" "$USER" "$LOGNAME" "$PWD";'
++ " cat > payload; cat payload",
++ stdin=chunks(),
++ )
++ assert result.exit_code == 0, result.stderr
++ lines = result.stdout.splitlines()
++ assert lines[:2] == [str(user.uid), str(user.gid)]
++ assert str(user.gid) in lines[2].split()
++ assert lines[3:] == [user.home, user.name, user.name, user.home, "owned by alice"]
++ result = await stdin_sandbox.execute(f"stat -c '%u:%g' {user.home}/payload")
++ assert result.exit_code == 0, result.stderr
++ assert result.stdout.strip() == f"{user.uid}:{user.gid}"
++
++ result = await stdin_sandbox.execute(
++ 'printf "%s\\n" "$PWD"; cat',
++ user=user.name,
++ cwd="/tmp",
++ stdin=b"explicit cwd",
++ )
++ assert result.exit_code == 0, result.stderr
++ assert result.stdout == "/tmp\nexplicit cwd"
++ finally:
++ await stdin_sandbox.delete_user(user.name)
++
++
++async def test_stdin_unknown_user_does_not_start_or_claim_exclusivity(stdin_sandbox):
++ produced = []
++
++ async def chunks():
++ produced.append(True)
++ yield b"unused"
++
++ result = await stdin_sandbox.execute(
++ "touch /tmp/quicksand-invalid-stdin-user",
++ user="quicksand_missing_user",
++ stdin=chunks(),
++ exclusive=True,
++ )
++ assert result.exit_code == -1
++ assert result.stderr
++ assert not produced
++ result = await stdin_sandbox.execute("test ! -e /tmp/quicksand-invalid-stdin-user")
++ assert result.exit_code == 0, result.stderr
diff --cc tests/unit/test_checkpoint_ops.py
index ad3ca3f,dfe1b39..0e59a5d
--- a/tests/unit/test_checkpoint_ops.py
+++ b/tests/unit/test_checkpoint_ops.py
@@@ -206,8 -206,7 +206,9 @@@ class TestHotSave
on_stdout=None,
on_stderr=None,
exclusive=False,
+ user=None,
+ *,
+ stdin=None,
):
return MagicMock(stdout="", stderr="", exit_code=0)
@@@ -374,8 -373,7 +375,9 @@@ class TestCheckpointRevert
on_stdout=None,
on_stderr=None,
exclusive=False,
+ user=None,
+ *,
+ stdin=None,
):
return MagicMock(stdout="", stderr="", exit_code=0)
diff --cc tests/unit/test_dev_build.py
index 9351029,4a744c9..0dced95
--- a/tests/unit/test_dev_build.py
+++ b/tests/unit/test_dev_build.py
@@@ -2,8 -2,8 +2,9 @@@
from __future__ import annotations
++import importlib.util
from pathlib import Path
--from unittest.mock import patch
++from unittest.mock import MagicMock, patch
import pytest
from quicksand_image_tools.build import (
@@@ -167,3 -172,3 +173,47 @@@ class TestBuildImage
with patch("shutil.which", return_value="/usr/bin/docker"):
result = build_image(dockerfile_path, cache_dir=cache_dir)
assert result == cached_image
++
++
++ ("distro", "hook_name"),
++ [("alpine", "AlpineImageBuildHook"), ("ubuntu", "UbuntuImageBuildHook")],
++)
++def test_base_image_hook_checks_existing_image_inputs(tmp_path, distro, hook_name):
++ hook_path = (
++ Path(__file__).parents[2]
++ / "packages"
++ / "contrib"
++ / f"quicksand-{distro}"
++ / "hatch_build.py"
++ )
++ spec = importlib.util.spec_from_file_location(f"{distro}_build_hook", hook_path)
++ assert spec is not None and spec.loader is not None
++ module = importlib.util.module_from_spec(spec)
++ spec.loader.exec_module(module)
++ hook_class = getattr(module, hook_name)
++
++ package_dir = tmp_path / f"quicksand_{distro}"
++ images_dir = package_dir / "images"
++ images_dir.mkdir(parents=True)
++ (package_dir / "__init__.py").write_text('DISTRO_VERSION = "1.0"\n')
++ image_path = images_dir / f"{distro}-1.0-arm64.qcow2"
++ image_path.touch()
++ hook = hook_class(
++ root=str(tmp_path),
++ config={},
++ build_config=MagicMock(),
++ metadata=MagicMock(),
++ directory=str(tmp_path),
++ target_name="wheel",
++ app=MagicMock(),
++ )
++
++ with (
++ patch("quicksand_image_tools.build_utils.set_platform_wheel_tag", return_value=True),
++ patch("quicksand_image_tools.build_utils.get_image_arch", return_value="arm64"),
++ patch.object(hook, "_build_image") as build,
++ ):
++ hook.initialize("standard", {})
++
++ build.assert_called_once_with(package_dir / "docker" / "Dockerfile", image_path)
diff --cc tests/unit/test_disk.py
index d706b19,6f50577..1ea436b
--- a/tests/unit/test_disk.py
+++ b/tests/unit/test_disk.py
@@@ -54,8 -54,7 +54,9 @@@ class _MockSandbox(_LifecycleMixin)
on_stdout=None,
on_stderr=None,
exclusive=False,
+ user=None,
+ *,
+ stdin=None,
):
return self._execute_fn(command, timeout)
diff --cc tests/unit/test_mounts.py
index ab9302e,af3b01f..fc035ba
--- a/tests/unit/test_mounts.py
+++ b/tests/unit/test_mounts.py
@@@ -64,8 -58,7 +64,9 @@@ class _MockSandbox(_MountMixin)
on_stdout=None,
on_stderr=None,
exclusive=False,
+ user=None,
+ *,
+ stdin=None,
):
return self._execute_fn(command, timeout)
diff --cc tests/unit/test_multiuser.py
index 0000000,4427ab8..b9a64fb
mode 000000,100644..100644
--- a/tests/unit/test_multiuser.py
+++ b/tests/unit/test_multiuser.py
@@@ -1,0 -1,100 +1,129 @@@
+ """Unit tests for multi-user support (SandboxUser, create/delete, exec routing).
+
+ These exercise the host-side wiring with a mocked agent client, so no VM boots.
+ """
+
+ from __future__ import annotations
+
+ from unittest.mock import AsyncMock, MagicMock
+
+ import pytest
+ from quicksand_core import Sandbox, SandboxUser
+ from quicksand_core._types import QuicksandGuestAgentMethod
+
+
+ def _running_sandbox(send_request: AsyncMock) -> Sandbox:
+ """A Sandbox marked running with a mocked agent transport."""
+ sb = Sandbox(image="alpine")
+ sb._is_running = True
+ sb._process_manager = MagicMock(is_running=True)
+ client = AsyncMock()
+ client.send_request = send_request
+ sb._agent_client = client
+ return sb
+
+
+ @pytest.mark.asyncio
+ async def test_execute_threads_user_into_params():
+ send = AsyncMock(return_value={"result": {"stdout": "alice", "stderr": "", "exit_code": 0}})
+ sb = _running_sandbox(send)
+
+ result = await sb.execute("whoami", user="alice")
+
+ assert result.stdout == "alice"
+ method, params, *_ = send.call_args.args
+ assert method == QuicksandGuestAgentMethod.EXECUTE
+ assert params["user"] == "alice"
+
+
+ @pytest.mark.asyncio
+ async def test_execute_omits_user_when_none():
+ send = AsyncMock(return_value={"result": {"stdout": "", "stderr": "", "exit_code": 0}})
+ sb = _running_sandbox(send)
+
+ await sb.execute("true")
+
+ _, params, *_ = send.call_args.args
+ assert "user" not in params # None fields are dropped before sending
+
+
+ @pytest.mark.asyncio
+ async def test_create_user_returns_handle_and_routes():
+ send = AsyncMock(return_value={"result": {"uid": 1000, "gid": 1000, "home": "/home/alice"}})
+ sb = _running_sandbox(send)
+
+ user = await sb.create_user("alice")
+
+ assert isinstance(user, SandboxUser)
+ assert (user.name, user.uid, user.gid, user.home) == ("alice", 1000, 1000, "/home/alice")
+ method, params, *_ = send.call_args.args
+ assert method == QuicksandGuestAgentMethod.CREATE_USER
+ assert params == {"name": "alice"}
+
+
+ @pytest.mark.asyncio
+ async def test_create_user_raises_on_agent_error():
+ send = AsyncMock(return_value={"error": {"message": "User already exists: alice"}})
+ sb = _running_sandbox(send)
+
+ with pytest.raises(RuntimeError, match="already exists"):
+ await sb.create_user("alice")
+
+
+ @pytest.mark.asyncio
+ async def test_sandbox_user_execute_injects_user():
+ send = AsyncMock()
+ # First call: create_user; subsequent: execute.
+ send.side_effect = [
+ {"result": {"uid": 1000, "gid": 1000, "home": "/home/alice"}},
+ {"result": {"stdout": "alice", "stderr": "", "exit_code": 0}},
+ ]
+ sb = _running_sandbox(send)
+
+ user = await sb.create_user("alice")
+ await user.execute("whoami")
+
+ method, params, *_ = send.call_args.args
+ assert method == QuicksandGuestAgentMethod.EXECUTE
+ assert params["user"] == "alice"
+
+
+ @pytest.mark.asyncio
+ async def test_delete_user_routes_with_remove_home():
+ send = AsyncMock(return_value={"result": {"removed": True}})
+ sb = _running_sandbox(send)
+
+ await sb.delete_user("alice", remove_home=False)
+
+ method, params, *_ = send.call_args.args
+ assert method == QuicksandGuestAgentMethod.DELETE_USER
+ assert params == {"name": "alice", "remove_home": False}
++
++
[email protected]("use_handle", [False, True])
++async def test_streaming_stdin_preserves_target_user(use_handle):
++ sb = _running_sandbox(AsyncMock())
++ client = AsyncMock()
++ client.send_stream_request.return_value = {
++ "result": {"stdout": "input", "stderr": "", "exit_code": 0}
++ }
++ sb._agent_client = client
++
++ async def chunks():
++ yield b"input"
++
++ source = chunks()
++ callback = MagicMock()
++ if use_handle:
++ user = SandboxUser(sb, "alice", uid=1000, gid=1000, home="/home/alice")
++ result = await user.execute("cat", stdin=source, on_stdout=callback)
++ else:
++ result = await sb.execute("cat", user="alice", stdin=source, on_stdout=callback)
++
++ assert result.stdout == "input"
++ call = client.send_stream_request.await_args
++ assert call is not None
++ assert call.args[0]["user"] == "alice"
++ assert call.kwargs["stdin"] is source
++ assert call.kwargs["on_stdout"] is callback