diff --git a/crates/weft-runtime/src/desktop.rs b/crates/weft-runtime/src/desktop.rs new file mode 100644 index 0000000..528cb4f --- /dev/null +++ b/crates/weft-runtime/src/desktop.rs @@ -0,0 +1,197 @@ +//! 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; + +/// 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) -> 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(Stdio::piped()) + .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) => return Err(e.to_string()), + } + }; + let output = stdout.join().unwrap_or_default(); + 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 { + message + }); + } + if output.len() > max_output { + return Err(format!("{program} returned more than {max_output} bytes")); + } + Ok(output) +} + +pub fn clipboard_read() -> Result { + let mut command = Command::new("wl-paste"); + command.args(["--no-newline", "--type", "text/plain;charset=utf-8"]); + let data = run(command, None, MAX_CLIPBOARD)?; + 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).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'.')) +} + +/// 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}")); + } + command.arg("--").arg(title).arg(body); + run(command, None, 0).map(|_| ()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[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).unwrap_err(); + assert!(error.contains("did not finish"), "{error}"); + assert!(started.elapsed() < HELPER_TIMEOUT + Duration::from_secs(2)); + + let mut chatty = Command::new("head"); + chatty.args(["-c", "2000", "/dev/zero"]); + assert!( + run(chatty, None, 1000) + .unwrap_err() + .contains("more than 1000 bytes") + ); + + let mut echo = Command::new("cat"); + echo.stdin(Stdio::piped()); + assert_eq!(run(echo, Some(b"text".to_vec()), 100).unwrap(), b"text"); + + let failing = Command::new("false"); + assert!(run(failing, None, 0).unwrap_err().contains("exited")); + } +} diff --git a/crates/weft-runtime/src/main.rs b/crates/weft-runtime/src/main.rs index 9c5b92d..94e6d47 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")?; @@ -463,55 +469,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}; @@ -578,6 +535,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 93af5ec..d808d06 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 and at most 1 MiB in either direction. A notification's title is at most 256 bytes and its body 4096; 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. Fetch grants name hosts, not addresses: ports are not restricted, and a host that resolves to a loopback or private address (or `net:fetch:*`) can reach local services. IPv6 literals cannot be granted.