diff --git a/crates/weft-runtime/src/desktop.rs b/crates/weft-runtime/src/desktop.rs new file mode 100644 index 0000000..afd5709 --- /dev/null +++ b/crates/weft-runtime/src/desktop.rs @@ -0,0 +1,269 @@ +//! The desktop services behind the clipboard and notification imports. +//! +//! Each import runs a helper program (`wl-paste`, `wl-copy`, +//! `notify-send`) with a bounded input, a bounded output and a deadline, +//! after which the helper is killed and the call fails. A notification +//! names the application that sent it, so an app cannot pass one off as +//! the system's. + +use std::io::{Read, Write}; +use std::process::{Command, Stdio}; +use std::time::{Duration, Instant}; + +/// How long a helper may run. +const HELPER_TIMEOUT: Duration = Duration::from_secs(5); +/// The most clipboard text read or written, in bytes. +pub const MAX_CLIPBOARD: usize = 1024 * 1024; +/// The longest notification title and body, in bytes. +pub const MAX_TITLE: usize = 256; +pub const MAX_BODY: usize = 4096; + +/// What a helper's output streams are connected to. +#[derive(Clone, Copy, PartialEq, Eq)] +enum Output { + /// Read: up to the limit from standard output, and standard error for + /// the failure message. + Captured, + /// Standard output discarded and standard error read only when the + /// helper fails, for a helper that leaves a process running which + /// keeps its streams open after succeeding, as `wl-copy` does to + /// serve the selection; it fails, if at all, before that. + ErrorsOnly, +} + +/// Runs `command` with `input` on its standard input and returns at most +/// `max_output` bytes of its standard output, or why it failed. +fn run( + mut command: Command, + input: Option>, + max_output: usize, + output: Output, +) -> Result, String> { + let program = command.get_program().to_string_lossy().into_owned(); + let mut child = command + .stdin(if input.is_some() { + Stdio::piped() + } else { + Stdio::null() + }) + .stdout(match output { + Output::Captured => Stdio::piped(), + Output::ErrorsOnly => Stdio::null(), + }) + .stderr(Stdio::piped()) + .spawn() + .map_err(|e| format!("cannot run {program}: {e}"))?; + if let (Some(mut stdin), Some(input)) = (child.stdin.take(), input) { + std::thread::spawn(move || { + let _ = stdin.write_all(&input); + }); + } + let reader = |stream: Option>, limit: usize| { + std::thread::spawn(move || { + let mut data = Vec::new(); + if let Some(stream) = stream { + let _ = stream.take(limit as u64 + 1).read_to_end(&mut data); + } + data + }) + }; + let stdout = reader( + child + .stdout + .take() + .map(|s| Box::new(s) as Box), + max_output, + ); + let stderr = reader( + child + .stderr + .take() + .map(|s| Box::new(s) as Box), + 4096, + ); + let deadline = Instant::now() + HELPER_TIMEOUT; + let status = loop { + match child.try_wait() { + Ok(Some(status)) => break status, + Ok(None) if Instant::now() < deadline => std::thread::sleep(Duration::from_millis(10)), + Ok(None) => { + let _ = child.kill(); + let _ = child.wait(); + return Err(format!( + "{program} did not finish within {} s", + HELPER_TIMEOUT.as_secs() + )); + } + Err(e) => { + let _ = child.kill(); + let _ = child.wait(); + return Err(e.to_string()); + } + } + }; + let output = stdout.join().unwrap_or_default(); + // Checked first: a helper whose output is cut off at the limit may die + // of the broken pipe. + if output.len() > max_output { + return Err(format!("{program} returned more than {max_output} bytes")); + } + if !status.success() { + let message = String::from_utf8_lossy(&stderr.join().unwrap_or_default()) + .trim() + .to_owned(); + return Err(if message.is_empty() { + format!("{program} exited with {status}") + } else { + format!("{program}: {message}") + }); + } + Ok(output) +} + +pub fn clipboard_read() -> Result { + let mut command = Command::new("wl-paste"); + // Any text type; the content must still be UTF-8. + command.args(["--no-newline", "--type", "text"]); + let data = run(command, None, MAX_CLIPBOARD, Output::Captured)?; + String::from_utf8(data).map_err(|_| "the clipboard does not hold UTF-8 text".to_owned()) +} + +pub fn clipboard_write(text: &str) -> Result<(), String> { + if text.len() > MAX_CLIPBOARD { + return Err(format!("clipboard text exceeds {MAX_CLIPBOARD} bytes")); + } + let mut command = Command::new("wl-copy"); + command.args(["--type", "text/plain;charset=utf-8"]); + run( + command, + Some(text.as_bytes().to_vec()), + 0, + Output::ErrorsOnly, + ) + .map(|_| ()) +} + +/// Checks a notification before it is sent. +pub fn check_notification(title: &str, body: &str, icon: Option<&str>) -> Result<(), String> { + if title.len() > MAX_TITLE { + return Err(format!("notification title exceeds {MAX_TITLE} bytes")); + } + if body.len() > MAX_BODY { + return Err(format!("notification body exceeds {MAX_BODY} bytes")); + } + // Only icon theme names: a path or URL would let the app show any file + // or reach the network through the notification service. + if let Some(icon) = icon + && !is_icon_name(icon) + { + return Err("a notification icon must be an icon theme name".to_owned()); + } + Ok(()) +} + +fn is_icon_name(icon: &str) -> bool { + !icon.is_empty() + && icon.len() <= 64 + && !icon.starts_with('.') + && icon + .bytes() + .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_' | b'.')) +} + +fn escape_markup(text: &str) -> String { + text.replace('&', "&") + .replace('<', "<") + .replace('>', ">") +} + +/// Sends a notification attributed to `app_id`. +pub fn notify(app_id: &str, title: &str, body: &str, icon: Option<&str>) -> Result<(), String> { + check_notification(title, body, icon)?; + let mut command = Command::new("notify-send"); + command.arg(format!("--app-name={app_id}")); + if let Some(icon) = icon { + command.arg(format!("--icon={icon}")); + } + // Notification servers may render markup in the body, including links + // and images, so it is sent as plain text. + command.arg("--").arg(title).arg(escape_markup(body)); + run(command, None, 0, Output::Captured).map(|_| ()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn notification_bodies_are_plain_text() { + assert_eq!( + escape_markup("a & b"), + "<a href=\"x\">a & b</a>" + ); + } + + #[test] + fn notifications_are_bounded_and_icons_are_theme_names() { + assert!(check_notification("t", "b", None).is_ok()); + assert!(check_notification("t", "b", Some("dialog-information")).is_ok()); + assert!(check_notification(&"t".repeat(MAX_TITLE + 1), "b", None).is_err()); + assert!(check_notification("t", &"b".repeat(MAX_BODY + 1), None).is_err()); + for icon in [ + "/etc/passwd", + "file:///x.png", + "https://x/i.png", + "../x", + "", + "a b", + ] { + assert!(check_notification("t", "b", Some(icon)).is_err(), "{icon}"); + } + } + + #[test] + fn helpers_are_bounded_in_time_and_output() { + let mut slow = Command::new("sleep"); + slow.arg("30"); + let started = Instant::now(); + let error = run(slow, None, 0, Output::Captured).unwrap_err(); + assert!(error.contains("did not finish"), "{error}"); + assert!(started.elapsed() < HELPER_TIMEOUT + Duration::from_secs(2)); + + let mut chatty = Command::new("head"); + // Far more than a pipe holds, so the cut-off kills the writer. + chatty.args(["-c", "10000000", "/dev/zero"]); + assert!( + run(chatty, None, 1000, Output::Captured) + .unwrap_err() + .contains("more than 1000 bytes") + ); + + let echo = Command::new("cat"); + assert_eq!( + run(echo, Some(b"text".to_vec()), 100, Output::Captured).unwrap(), + b"text" + ); + + // A helper that leaves a process behind returns once it exits + // itself when its streams are discarded. + let mut forking = Command::new("sh"); + forking.args(["-c", "sleep 30 & exit 0"]); + let started = Instant::now(); + assert!(run(forking, None, 0, Output::ErrorsOnly).is_ok()); + assert!(started.elapsed() < Duration::from_secs(2)); + + let mut failing = Command::new("sh"); + failing.args(["-c", "echo no display >&2; exit 1"]); + assert_eq!( + run(failing, None, 0, Output::ErrorsOnly).unwrap_err(), + "sh: no display" + ); + + let failing = Command::new("false"); + assert!( + run(failing, None, 0, Output::Captured) + .unwrap_err() + .contains("exited") + ); + } +} diff --git a/crates/weft-runtime/src/main.rs b/crates/weft-runtime/src/main.rs index 7774169..d570a49 100644 --- a/crates/weft-runtime/src/main.rs +++ b/crates/weft-runtime/src/main.rs @@ -2,6 +2,8 @@ use std::path::PathBuf; use anyhow::Context; +#[cfg(feature = "wasmtime-runtime")] +mod desktop; mod grants; #[cfg(feature = "wasmtime-runtime")] mod ipc; @@ -93,6 +95,7 @@ fn main() -> anyhow::Result<()> { tracing::info!(session_id, %app_id, wasm = %wasm_path.display(), "executing module"); run_module( + app_id, &wasm_path, &preopen, grants, @@ -116,6 +119,7 @@ fn ready_line() -> String { #[cfg(not(feature = "wasmtime-runtime"))] fn run_module( + _app_id: &str, _wasm_path: &std::path::Path, _preopen: &[Preopen], _grants: Grants, @@ -129,6 +133,7 @@ fn run_module( #[cfg(feature = "wasmtime-runtime")] fn run_module( + app_id: &str, wasm_path: &std::path::Path, preopen: &[Preopen], grants: Grants, @@ -241,6 +246,7 @@ fn run_module( .context("define weft:app/fetch#fetch")?; let notify_grants = Arc::clone(&grants); + let notify_app = app_id.to_owned(); linker .instance("weft:app/notifications@0.1.0") .context("define weft:app/notifications instance")? @@ -251,7 +257,7 @@ fn run_module( -> wasmtime::Result<(Result<(), String>,)> { let result = notify_grants .notifications() - .and_then(|()| host_notify(&title, &body, icon.as_deref())); + .and_then(|()| desktop::notify(¬ify_app, &title, &body, icon.as_deref())); Ok((result,)) }, ) @@ -270,7 +276,7 @@ fn run_module( -> wasmtime::Result<(Result,)> { Ok((read_grants .clipboard_read() - .and_then(|()| host_clipboard_read()),)) + .and_then(|()| desktop::clipboard_read()),)) }, ) .context("define weft:app/clipboard#read")?; @@ -283,7 +289,7 @@ fn run_module( -> wasmtime::Result<(Result<(), String>,)> { Ok((write_grants .clipboard_write() - .and_then(|()| host_clipboard_write(&text)),)) + .and_then(|()| desktop::clipboard_write(&text)),)) }, ) .context("define weft:app/clipboard#write")?; @@ -496,55 +502,6 @@ fn host_fetch( Err("this runtime was built without network fetch support".to_owned()) } -#[cfg(feature = "wasmtime-runtime")] -fn host_clipboard_read() -> Result { - let out = std::process::Command::new("wl-paste") - .arg("--no-newline") - .output() - .map_err(|e| e.to_string())?; - if out.status.success() { - String::from_utf8(out.stdout).map_err(|e| e.to_string()) - } else { - Err(String::from_utf8_lossy(&out.stderr).trim().to_owned()) - } -} - -#[cfg(feature = "wasmtime-runtime")] -fn host_clipboard_write(text: &str) -> Result<(), String> { - use std::io::Write; - let mut child = std::process::Command::new("wl-copy") - .stdin(std::process::Stdio::piped()) - .spawn() - .map_err(|e| e.to_string())?; - if let Some(stdin) = child.stdin.as_mut() { - stdin - .write_all(text.as_bytes()) - .map_err(|e| e.to_string())?; - } - let status = child.wait().map_err(|e| e.to_string())?; - if status.success() { - Ok(()) - } else { - Err(format!("wl-copy exited with {status}")) - } -} - -#[cfg(feature = "wasmtime-runtime")] -fn host_notify(title: &str, body: &str, icon: Option<&str>) -> Result<(), String> { - let mut cmd = std::process::Command::new("notify-send"); - if let Some(i) = icon { - cmd.arg("--icon").arg(i); - } - cmd.arg("--").arg(title).arg(body); - cmd.status().map_err(|e| e.to_string()).and_then(|s| { - if s.success() { - Ok(()) - } else { - Err(format!("notify-send exited with {s}")) - } - }) -} - #[cfg(feature = "seccomp")] fn apply_seccomp_filter() -> anyhow::Result<()> { use seccompiler::{BpfProgram, SeccompAction, SeccompFilter, SeccompRule}; @@ -611,6 +568,7 @@ mod tests { #[test] fn engine_disabled_build_refuses_to_run_components() { let err = run_module( + "org.weft.test", std::path::Path::new("app.wasm"), &[], Grants::default(), diff --git a/docs/architecture.md b/docs/architecture.md index 593456e..7f42309 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -88,6 +88,8 @@ Each capability-controlled host import (fetch, notifications, clipboard) checks | `sys:clipboard:read` / `sys:clipboard:write` | `weft:app/clipboard#read` / `#write` | | `hw:gpu:compute` / `hw:gpu:render` | Not supported; the launch fails | +Clipboard and notifications run `wl-paste`, `wl-copy` and `notify-send` from the runtime's environment, each bounded to 5 seconds, after which the helper is killed and the call fails. Clipboard text is UTF-8, of any text type, and at most 1 MiB in either direction. A notification's title is at most 256 bytes and its body 4096, sent as plain text with markup escaped; its icon must be an icon theme name, not a path or URL; and it is sent with the app's ID as the application name, so an app cannot pass a notification off as the system's. Where a helper is not installed the call fails with that error. + Fetch does not follow redirects: a redirect is returned to the component as a response, so every destination it requests is checked against its grants. HTTP error statuses are responses too; only policy and transport failures are errors. Only the methods GET, HEAD, POST, PUT, PATCH, DELETE and OPTIONS are accepted, and a component cannot set `Host`, `Content-Length`, `Transfer-Encoding` or other hop-by-hop headers. Connecting times out after 10 seconds and the whole request after 30 seconds, not counting DNS resolution; response bodies are limited to 16 MiB. Fetch requires a runtime built with the `net-fetch` feature. The runtime resolves a fetch destination itself and connects only to the addresses it allows. A grant for a name, and `net:fetch:*`, reach only public unicast addresses: loopback, unspecified, private, shared (100.64/10), link-local, multicast, broadcast, reserved, documentation and benchmarking addresses, and their IPv6 counterparts (unique local, site-local, Teredo and others), are refused, and an IPv6 address that carries an IPv4 address (mapped, compatible, translated, 6to4, NAT64) is judged by that address, so DNS cannot point a granted name at this machine or the local network. An IPv4 address named in a grant, such as `net:fetch:127.0.0.1`, is reached as declared. Fetch never goes through a proxy. Ports are not restricted. Credentials in a URL are refused; a component sends credentials in a header, and only to a host it is granted, since redirects are not followed. IPv6 literals cannot be granted.