From c28a829624224b73fb119cb6953207ff514b56bd Mon Sep 17 00:00:00 2001 From: Marco Allegretti Date: Fri, 9 Oct 2026 08:08:58 +0000 Subject: [PATCH] fix(runtime): enforce effective capability grants per session Every host import was registered and callable whatever the package declared, read-only directory capabilities were preopened read-write, and appd launched packages whose capabilities it could not satisfy. The fetch import also could not be linked: the host returned a tuple where the WIT declares the response record, so any component importing weft:app/fetch failed to instantiate. One capability vocabulary now lives in weft_ipc_types::capability and is used by weft-pack, weft-appd and weft-runtime. weft-appd derives a session's grants once, before the session exists, and refuses the launch with error 403 when a capability is unknown, unsupported (hw:gpu:*) or unsatisfiable (documents without an XDG documents directory). The documents directory now comes from user-dirs.dirs instead of a guessed ~/Documents. The runtime receives grants explicitly (--grant CAP, --preopen HOST::GUEST::ro|rw), preopens read-only directories read-only, and checks the grant on every notifications, clipboard and fetch call. Fetch accepts only http and https to granted hosts, returns redirects and HTTP error statuses as responses instead of following or failing them, and bounds connect time, total time and response size. The file portal takes read-only directories with --allow-read and refuses writes there. tests/runtime/check_grants.py runs the real runtime on a probe component under each kind of grant and checks the outcome of every operation; it fails when read-only data is writable or an import ignores its grant. The appd dispatch tests that read WEFT_RUNTIME_BIN now hold the env lock shared with the tests that set it. --- .gitignore | 1 + Cargo.lock | 3 + Cargo.toml | 1 + crates/weft-appd/src/grants.rs | 277 ++++++++++++++ crates/weft-appd/src/main.rs | 89 ++++- crates/weft-appd/src/runtime.rs | 86 +---- crates/weft-file-portal/src/main.rs | 133 +++++-- crates/weft-ipc-types/src/capability.rs | 161 +++++++++ crates/weft-ipc-types/src/lib.rs | 2 + crates/weft-pack/Cargo.toml | 1 + crates/weft-pack/src/main.rs | 26 +- crates/weft-runtime/Cargo.toml | 4 +- crates/weft-runtime/src/grants.rs | 173 +++++++++ crates/weft-runtime/src/main.rs | 169 ++++++--- docs/architecture.md | 31 +- docs/security.md | 6 +- tests/components/grants-probe/Cargo.lock | 337 ++++++++++++++++++ tests/components/grants-probe/Cargo.toml | 12 + tests/components/grants-probe/src/main.rs | 35 ++ .../components/grants-probe/wit/deps/weft-app | 1 + tests/components/grants-probe/wit/world.wit | 8 + tests/runtime/check_grants.py | 186 ++++++++++ 22 files changed, 1552 insertions(+), 190 deletions(-) create mode 100644 crates/weft-appd/src/grants.rs create mode 100644 crates/weft-ipc-types/src/capability.rs create mode 100644 crates/weft-runtime/src/grants.rs create mode 100644 tests/components/grants-probe/Cargo.lock create mode 100644 tests/components/grants-probe/Cargo.toml create mode 100644 tests/components/grants-probe/src/main.rs create mode 120000 tests/components/grants-probe/wit/deps/weft-app create mode 100644 tests/components/grants-probe/wit/world.wit create mode 100644 tests/runtime/check_grants.py diff --git a/.gitignore b/.gitignore index 0bea95b..c642375 100644 --- a/.gitignore +++ b/.gitignore @@ -6,3 +6,4 @@ /infra/vm/*.qcow2 Thumbs.db +/tests/components/*/target/ diff --git a/Cargo.lock b/Cargo.lock index 278fcb4..2420198 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -10544,6 +10544,7 @@ dependencies = [ "sha2", "tar", "toml 0.8.23", + "weft-ipc-types", "zstd", ] @@ -10558,8 +10559,10 @@ dependencies = [ "tracing", "tracing-subscriber", "ureq", + "url", "wasmtime", "wasmtime-wasi", + "weft-ipc-types", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index d8573d6..0560b47 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -14,6 +14,7 @@ members = [ exclude = [ "examples/org.weft.demo.counter", "examples/org.weft.demo.notes", + "tests/components/grants-probe", ] resolver = "2" diff --git a/crates/weft-appd/src/grants.rs b/crates/weft-appd/src/grants.rs new file mode 100644 index 0000000..7dbd6a0 --- /dev/null +++ b/crates/weft-appd/src/grants.rs @@ -0,0 +1,277 @@ +//! Effective grants for a session, derived once from the package manifest. +//! +//! Every capability the package declares must be understood and satisfiable +//! by this host, or the session does not start. The result is passed to +//! weft-runtime explicitly (`--preopen`, `--grant`) and to the file portal; +//! neither reads the manifest itself. + +use std::path::{Path, PathBuf}; + +use weft_ipc_types::capability::{Access, Capability}; + +/// A host directory made visible to the component. +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) struct GrantedDir { + pub host: PathBuf, + pub guest: &'static str, + pub access: Access, +} + +impl GrantedDir { + /// The `--preopen` argument for weft-runtime. + pub fn preopen_arg(&self) -> String { + let mode = match self.access { + Access::Read => "ro", + Access::ReadWrite => "rw", + }; + format!("{}::{}::{mode}", self.host.display(), self.guest) + } +} + +#[derive(Debug, Default, PartialEq, Eq)] +pub(crate) struct SessionGrants { + pub dirs: Vec, + /// Host-import capabilities, passed as `--grant`. + pub imports: Vec, +} + +/// Where the host resources behind filesystem capabilities live. +pub(crate) struct HostDirs { + /// Root under which each app's private data directory is created. + pub app_data_root: PathBuf, + /// The user's documents directory, if the platform configures one. + pub documents: Option, +} + +impl HostDirs { + pub fn from_env() -> Result { + let home = std::env::var_os("HOME") + .map(PathBuf::from) + .ok_or("HOME is not set")?; + let config = std::env::var_os("XDG_CONFIG_HOME") + .map(PathBuf::from) + .unwrap_or_else(|| home.join(".config")); + Ok(Self { + app_data_root: home.join(".local/share/weft/apps"), + documents: documents_dir(&home, &config), + }) + } +} + +/// Reads the package manifest of `app_id` and derives its grants. +pub(crate) fn for_app(app_id: &str) -> Result { + #[derive(serde::Deserialize)] + struct Package { + capabilities: Option>, + } + #[derive(serde::Deserialize)] + struct Manifest { + package: Package, + } + + let manifest = crate::app_store_roots() + .into_iter() + .map(|root| root.join(app_id).join("wapp.toml")) + .find(|path| path.exists()) + .ok_or_else(|| format!("package {app_id} is not installed"))?; + let text = std::fs::read_to_string(&manifest) + .map_err(|e| format!("cannot read {}: {e}", manifest.display()))?; + let manifest: Manifest = + toml::from_str(&text).map_err(|e| format!("invalid {}: {e}", manifest.display()))?; + let declared = manifest.package.capabilities.unwrap_or_default(); + derive(app_id, &declared, &HostDirs::from_env()?) +} + +/// Derives grants for the declared capabilities. Creates the app's private +/// data directory when a data capability is declared. +pub(crate) fn derive( + app_id: &str, + declared: &[String], + host: &HostDirs, +) -> Result { + let mut grants = SessionGrants::default(); + for text in declared { + let capability: Capability = text.parse().map_err(|e| format!("{e}"))?; + match capability { + Capability::AppData(access) => { + let dir = host.app_data_root.join(app_id).join("data"); + std::fs::create_dir_all(&dir) + .map_err(|e| format!("cannot create {}: {e}", dir.display()))?; + grant_dir(&mut grants, dir, "/data", access); + } + Capability::Documents(access) => { + let dir = host.documents.clone().ok_or_else(|| { + format!("{capability} requested, but no documents directory is configured") + })?; + grant_dir(&mut grants, dir, "/xdg/documents", access); + } + Capability::Fetch(_) + | Capability::Notifications + | Capability::ClipboardRead + | Capability::ClipboardWrite => { + if !grants.imports.contains(&capability) { + grants.imports.push(capability); + } + } + Capability::GpuCompute | Capability::GpuRender => { + return Err(format!("{capability} is not supported by this host")); + } + } + } + Ok(grants) +} + +/// Adds a directory grant; declaring both modes for one directory grants the +/// wider one. +fn grant_dir(grants: &mut SessionGrants, host: PathBuf, guest: &'static str, access: Access) { + match grants.dirs.iter_mut().find(|dir| dir.guest == guest) { + Some(existing) => { + if access == Access::ReadWrite { + existing.access = Access::ReadWrite; + } + } + None => grants.dirs.push(GrantedDir { + host, + guest, + access, + }), + } +} + +/// The documents directory from the XDG user directories configuration +/// (`user-dirs.dirs`), or None when it is not configured, is disabled (set +/// to the home directory) or does not exist. +fn documents_dir(home: &Path, config: &Path) -> Option { + let text = std::fs::read_to_string(config.join("user-dirs.dirs")).ok()?; + let value = text.lines().find_map(|line| { + line.trim() + .strip_prefix("XDG_DOCUMENTS_DIR=") + .map(|v| v.trim().trim_matches('"').to_owned()) + })?; + let dir = match value.strip_prefix("$HOME") { + Some(rest) => home.join(rest.trim_start_matches('/')), + None => PathBuf::from(&value), + }; + (dir.is_absolute() && dir != home && dir.is_dir()).then_some(dir) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn temp(name: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!("weft_grants_{name}_{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + dir + } + + fn host(root: &Path, documents: Option) -> HostDirs { + HostDirs { + app_data_root: root.join("apps"), + documents, + } + } + + fn caps(list: &[&str]) -> Vec { + list.iter().map(|s| s.to_string()).collect() + } + + #[test] + fn no_capabilities_grant_nothing() { + let root = temp("none"); + let grants = derive("org.example.app", &[], &host(&root, None)).unwrap(); + assert_eq!(grants, SessionGrants::default()); + } + + #[test] + fn data_access_modes_stay_distinct() { + let root = temp("modes"); + let read = derive( + "org.example.app", + &caps(&["fs:read:app-data"]), + &host(&root, None), + ) + .unwrap(); + assert_eq!(read.dirs[0].access, Access::Read); + assert!(read.dirs[0].preopen_arg().ends_with("::/data::ro")); + assert!(root.join("apps/org.example.app/data").is_dir()); + + let both = derive( + "org.example.app", + &caps(&["fs:read:app-data", "fs:rw:app-data"]), + &host(&root, None), + ) + .unwrap(); + assert_eq!(both.dirs.len(), 1); + assert_eq!(both.dirs[0].access, Access::ReadWrite); + } + + #[test] + fn imports_are_listed_once() { + let root = temp("imports"); + let grants = derive( + "org.example.app", + &caps(&[ + "sys:notifications", + "net:fetch:api.example.org", + "sys:notifications", + ]), + &host(&root, None), + ) + .unwrap(); + let listed: Vec = grants.imports.iter().map(|c| c.to_string()).collect(); + assert_eq!(listed, ["sys:notifications", "net:fetch:api.example.org"]); + assert!(grants.dirs.is_empty()); + } + + #[test] + fn unknown_unsupported_and_unsatisfiable_capabilities_fail() { + let root = temp("fail"); + for declared in ["sys:everything", "hw:gpu:compute", "fs:read:xdg-documents"] { + assert!( + derive("org.example.app", &caps(&[declared]), &host(&root, None)).is_err(), + "{declared} accepted" + ); + } + } + + #[test] + fn documents_come_from_user_dirs() { + let home = temp("home"); + let config = home.join(".config"); + std::fs::create_dir_all(home.join("Docs")).unwrap(); + std::fs::create_dir_all(&config).unwrap(); + assert_eq!(documents_dir(&home, &config), None); + + std::fs::write( + config.join("user-dirs.dirs"), + "# comment\nXDG_DOCUMENTS_DIR=\"$HOME/Docs\"\n", + ) + .unwrap(); + assert_eq!(documents_dir(&home, &config), Some(home.join("Docs"))); + + // Disabled (the home directory itself) and missing directories. + std::fs::write( + config.join("user-dirs.dirs"), + "XDG_DOCUMENTS_DIR=\"$HOME/\"\n", + ) + .unwrap(); + assert_eq!(documents_dir(&home, &config), None); + std::fs::write( + config.join("user-dirs.dirs"), + "XDG_DOCUMENTS_DIR=\"$HOME/Missing\"\n", + ) + .unwrap(); + assert_eq!(documents_dir(&home, &config), None); + + let grants = derive( + "org.example.app", + &caps(&["fs:rw:xdg-documents"]), + &host(&home, Some(home.join("Docs"))), + ) + .unwrap(); + assert_eq!(grants.dirs[0].guest, "/xdg/documents"); + assert_eq!(grants.dirs[0].access, Access::ReadWrite); + } +} diff --git a/crates/weft-appd/src/main.rs b/crates/weft-appd/src/main.rs index f9a6af1..b02d642 100644 --- a/crates/weft-appd/src/main.rs +++ b/crates/weft-appd/src/main.rs @@ -17,6 +17,7 @@ mod compositor_client { pub type CompositorSender = mpsc::Sender; } +mod grants; mod ipc; mod mount; mod runtime; @@ -424,6 +425,22 @@ pub(crate) async fn dispatch(req: Request, registry: &Registry) -> Response { app_id, surface_id: _, } => { + // The package's capabilities are granted before a session exists; + // a package this host cannot satisfy is refused, not started. + let grants = if std::env::var("WEFT_RUNTIME_BIN").is_ok() { + match grants::for_app(&app_id) { + Ok(grants) => grants, + Err(message) => { + tracing::warn!(%app_id, error = %message, "launch refused"); + return Response::Error { + code: 403, + message: format!("{app_id}: {message}"), + }; + } + } + } else { + grants::SessionGrants::default() + }; let session_id = registry.lock().await.launch(&app_id); tracing::info!(session_id, %app_id, "launched"); let abort_rx = registry.lock().await.register_abort(session_id); @@ -456,9 +473,16 @@ pub(crate) async fn dispatch(req: Request, registry: &Registry) -> Response { let reg = Arc::clone(registry); let aid = app_id.clone(); tokio::spawn(async move { - if let Err(e) = - runtime::supervise(session_id, &aid, reg, abort_rx, compositor_tx, ipc_socket) - .await + if let Err(e) = runtime::supervise( + session_id, + &aid, + grants, + reg, + abort_rx, + compositor_tx, + ipc_socket, + ) + .await { tracing::warn!(session_id, error = %e, "runtime supervisor error"); } @@ -677,8 +701,62 @@ mod tests { assert!(result.is_err()); } + #[tokio::test] + async fn launch_is_refused_when_capabilities_cannot_be_granted() { + let _env = env_lock().lock().await; + let store = std::env::temp_dir().join(format!("weft_refuse_{}", std::process::id())); + let app_dir = store.join("org.example.gpu"); + std::fs::create_dir_all(&app_dir).unwrap(); + std::fs::write( + app_dir.join("wapp.toml"), + "[package]\nid = \"org.example.gpu\"\ncapabilities = [\"hw:gpu:compute\"]\n", + ) + .unwrap(); + let prior_store = std::env::var("WEFT_APP_STORE").ok(); + let prior_bin = std::env::var("WEFT_RUNTIME_BIN").ok(); + // SAFETY: env_lock is held and the runtime is current_thread. + unsafe { + std::env::set_var("WEFT_APP_STORE", &store); + std::env::set_var("WEFT_RUNTIME_BIN", "/nonexistent/weft-runtime"); + } + + let reg = make_registry(); + let resp = dispatch( + Request::LaunchApp { + app_id: "org.example.gpu".into(), + surface_id: 0, + }, + ®, + ) + .await; + + // SAFETY: as above. + unsafe { + match prior_store { + Some(v) => std::env::set_var("WEFT_APP_STORE", v), + None => std::env::remove_var("WEFT_APP_STORE"), + } + match prior_bin { + Some(v) => std::env::set_var("WEFT_RUNTIME_BIN", v), + None => std::env::remove_var("WEFT_RUNTIME_BIN"), + } + } + let _ = std::fs::remove_dir_all(&store); + + match resp { + Response::Error { code, message } => { + assert_eq!(code, 403); + assert!(message.contains("hw:gpu:compute"), "{message}"); + } + other => panic!("expected a refusal, got {other:?}"), + } + assert!(reg.lock().await.running_sessions().is_empty()); + assert!(matches!(reg.lock().await.state(1), AppStateKind::NotFound)); + } + #[tokio::test] async fn dispatch_launch_returns_ack() { + let _env = env_lock().lock().await; let reg = make_registry(); let mut rx = reg.lock().await.subscribe(); let resp = dispatch( @@ -707,6 +785,7 @@ mod tests { #[tokio::test] async fn dispatch_terminate_known_returns_stopped() { + let _env = env_lock().lock().await; let reg = make_registry(); let ack = dispatch( Request::LaunchApp { @@ -958,6 +1037,7 @@ mod tests { runtime::supervise( session_id, "test.app", + grants::SessionGrants::default(), Arc::clone(®istry), abort_rx, None, @@ -1027,6 +1107,7 @@ mod tests { runtime::supervise( session_id, "test.abort.startup", + grants::SessionGrants::default(), Arc::clone(®istry), abort_rx, None, @@ -1075,6 +1156,7 @@ mod tests { runtime::supervise( session_id, "test.spawn.fail", + grants::SessionGrants::default(), Arc::clone(®istry), abort_rx, None, @@ -1233,6 +1315,7 @@ mod tests { runtime::supervise( session_id, "test.app", + grants::SessionGrants::default(), Arc::clone(®istry), abort_rx, None, diff --git a/crates/weft-appd/src/runtime.rs b/crates/weft-appd/src/runtime.rs index 67cfec5..516d31d 100644 --- a/crates/weft-appd/src/runtime.rs +++ b/crates/weft-appd/src/runtime.rs @@ -140,71 +140,6 @@ fn systemd_cgroup_available() -> bool { .exists() } -fn resolve_preopens(app_id: &str) -> Vec<(String, String)> { - #[derive(serde::Deserialize)] - struct Pkg { - capabilities: Option>, - } - #[derive(serde::Deserialize)] - struct M { - package: Pkg, - } - - let pkg_dir = crate::app_store_roots().into_iter().find_map(|root| { - let dir = root.join(app_id); - if dir.join("wapp.toml").exists() { - Some(dir) - } else { - None - } - }); - - let caps = match pkg_dir { - None => return Vec::new(), - Some(dir) => { - let Ok(text) = std::fs::read_to_string(dir.join("wapp.toml")) else { - return Vec::new(); - }; - match toml::from_str::(&text) { - Ok(m) => m.package.capabilities.unwrap_or_default(), - Err(_) => return Vec::new(), - } - } - }; - - let home = match std::env::var("HOME") { - Ok(h) => PathBuf::from(h), - Err(_) => return Vec::new(), - }; - - let mut preopens = Vec::new(); - for cap in &caps { - match cap.as_str() { - "fs:rw:app-data" | "fs:read:app-data" => { - let data_dir = home - .join(".local/share/weft/apps") - .join(app_id) - .join("data"); - let _ = std::fs::create_dir_all(&data_dir); - preopens.push((data_dir.to_string_lossy().into_owned(), "/data".to_string())); - } - "fs:rw:xdg-documents" | "fs:read:xdg-documents" => { - let docs = home.join("Documents"); - if docs.exists() { - preopens.push(( - docs.to_string_lossy().into_owned(), - "/xdg/documents".to_string(), - )); - } - } - other => { - tracing::debug!(capability = other, "not mapped to preopen; skipped"); - } - } - } - preopens -} - async fn kill_portal(portal: Option<(PathBuf, tokio::process::Child)>) { if let Some((sock, mut child)) = portal { let _ = child.kill().await; @@ -248,7 +183,7 @@ fn portal_socket_path(session_id: u64) -> Option { fn spawn_file_portal( session_id: u64, - allowed_paths: &[(String, String)], + dirs: &[crate::grants::GrantedDir], ) -> Option<(PathBuf, tokio::process::Child)> { let bin = std::env::var("WEFT_FILE_PORTAL_BIN").ok()?; let socket = portal_socket_path(session_id)?; @@ -257,8 +192,12 @@ fn spawn_file_portal( .stdin(std::process::Stdio::null()) .stdout(std::process::Stdio::null()) .stderr(std::process::Stdio::null()); - for (host, _) in allowed_paths { - cmd.arg("--allow").arg(host); + for dir in dirs { + let flag = match dir.access { + weft_ipc_types::capability::Access::Read => "--allow-read", + weft_ipc_types::capability::Access::ReadWrite => "--allow", + }; + cmd.arg(flag).arg(&dir.host); } let child = cmd.kill_on_drop(true).spawn().ok()?; tracing::info!(session_id, socket = %socket.display(), "file portal spawned"); @@ -268,6 +207,7 @@ fn spawn_file_portal( pub(crate) async fn supervise( session_id: u64, app_id: &str, + grants: crate::grants::SessionGrants, registry: Registry, abort_rx: tokio::sync::oneshot::Receiver<()>, compositor_tx: Option, @@ -297,8 +237,7 @@ pub(crate) async fn supervise( let (mount_orch, store_override) = crate::mount::MountOrchestrator::mount_if_needed(app_id, session_id); - let preopens = resolve_preopens(app_id); - let portal = spawn_file_portal(session_id, &preopens); + let portal = spawn_file_portal(session_id, &grants.dirs); let mut cmd = if systemd_cgroup_available() { let mut c = tokio::process::Command::new("systemd-run"); @@ -327,8 +266,11 @@ pub(crate) async fn supervise( cmd.env("WEFT_FILE_PORTAL_SOCKET", sock); } - for (host, guest) in &preopens { - cmd.arg("--preopen").arg(format!("{host}::{guest}")); + for dir in &grants.dirs { + cmd.arg("--preopen").arg(dir.preopen_arg()); + } + for capability in &grants.imports { + cmd.arg("--grant").arg(capability.to_string()); } let mut session = OwnedSession { diff --git a/crates/weft-file-portal/src/main.rs b/crates/weft-file-portal/src/main.rs index c8f3ad3..822e535 100644 --- a/crates/weft-file-portal/src/main.rs +++ b/crates/weft-file-portal/src/main.rs @@ -42,7 +42,9 @@ impl Response { fn main() -> anyhow::Result<()> { let args: Vec = std::env::args().collect(); if args.len() < 2 { - eprintln!("usage: weft-file-portal [--allow ]..."); + eprintln!( + "usage: weft-file-portal [--allow ]... [--allow-read ]..." + ); std::process::exit(1); } @@ -75,19 +77,34 @@ fn main() -> anyhow::Result<()> { anyhow::bail!("weft-file-portal requires a Unix platform") } +/// A directory the session may use: `--allow` grants reading and writing, +/// `--allow-read` reading only. +#[derive(Debug, Clone, PartialEq, Eq)] +struct Allowed { + root: PathBuf, + writable: bool, +} + #[cfg_attr(not(any(unix, test)), allow(dead_code))] -fn parse_allowed(args: &[String]) -> Vec { +fn parse_allowed(args: &[String]) -> Vec { let mut allowed = Vec::new(); let mut i = 0; while i < args.len() { - if args[i] == "--allow" - && let Some(p) = args.get(i + 1) - { - allowed.push(PathBuf::from(p)); - i += 2; - continue; + let writable = match args[i].as_str() { + "--allow" => true, + "--allow-read" => false, + _ => { + i += 1; + continue; + } + }; + if let Some(p) = args.get(i + 1) { + allowed.push(Allowed { + root: PathBuf::from(p), + writable, + }); } - i += 1; + i += 2; } allowed } @@ -108,16 +125,17 @@ fn normalize_path(path: &Path) -> PathBuf { out } -fn is_allowed(path: &Path, allowed: &[PathBuf]) -> bool { - if allowed.is_empty() { - return false; - } +/// Whether `path` lies in an allowed directory, and for a write, in one +/// granted read-write. +fn is_allowed(path: &Path, allowed: &[Allowed], write: bool) -> bool { let norm = normalize_path(path); - allowed.iter().any(|a| norm.starts_with(a)) + allowed + .iter() + .any(|a| norm.starts_with(&a.root) && (a.writable || !write)) } #[cfg(unix)] -fn handle_connection(stream: UnixStream, allowed: &[PathBuf]) { +fn handle_connection(stream: UnixStream, allowed: &[Allowed]) { let mut writer = match stream.try_clone() { Ok(s) => s, Err(e) => { @@ -151,11 +169,11 @@ fn handle_connection(stream: UnixStream, allowed: &[PathBuf]) { } #[cfg_attr(not(any(unix, test)), allow(dead_code))] -fn handle_request(req: Request, allowed: &[PathBuf]) -> Response { +fn handle_request(req: Request, allowed: &[Allowed]) -> Response { match req { Request::Read { path } => { let p = PathBuf::from(&path); - if !is_allowed(&p, allowed) { + if !is_allowed(&p, allowed, false) { return Response::err(format!("access denied: {path}")); } match std::fs::read(&p) { @@ -170,7 +188,7 @@ fn handle_request(req: Request, allowed: &[PathBuf]) -> Response { } Request::Write { path, data_b64 } => { let p = PathBuf::from(&path); - if !is_allowed(&p, allowed) { + if !is_allowed(&p, allowed, true) { return Response::err(format!("access denied: {path}")); } let data = @@ -189,7 +207,7 @@ fn handle_request(req: Request, allowed: &[PathBuf]) -> Response { } Request::List { path } => { let p = PathBuf::from(&path); - if !is_allowed(&p, allowed) { + if !is_allowed(&p, allowed, false) { return Response::err(format!("access denied: {path}")); } match std::fs::read_dir(&p) { @@ -213,33 +231,49 @@ fn handle_request(req: Request, allowed: &[PathBuf]) -> Response { mod tests { use super::*; + fn rw(root: impl Into) -> Allowed { + Allowed { + root: root.into(), + writable: true, + } + } + + fn ro(root: impl Into) -> Allowed { + Allowed { + root: root.into(), + writable: false, + } + } + #[test] fn allowed_path_accepted() { - let allowed = vec![PathBuf::from("/tmp/weft-test-allowed")]; + let allowed = vec![rw("/tmp/weft-test-allowed")]; assert!(is_allowed( Path::new("/tmp/weft-test-allowed/file.txt"), - &allowed + &allowed, + false )); } #[test] fn disallowed_path_rejected() { - let allowed = vec![PathBuf::from("/tmp/weft-test-allowed")]; - assert!(!is_allowed(Path::new("/etc/passwd"), &allowed)); + let allowed = vec![rw("/tmp/weft-test-allowed")]; + assert!(!is_allowed(Path::new("/etc/passwd"), &allowed, false)); } #[test] fn dotdot_traversal_blocked() { - let allowed = vec![PathBuf::from("/tmp/weft-test-allowed")]; + let allowed = vec![rw("/tmp/weft-test-allowed")]; assert!(!is_allowed( Path::new("/tmp/weft-test-allowed/../etc/passwd"), - &allowed + &allowed, + false )); } #[test] fn empty_allowlist_rejects_all() { - assert!(!is_allowed(Path::new("/tmp/anything"), &[])); + assert!(!is_allowed(Path::new("/tmp/anything"), &[], false)); } #[test] @@ -251,10 +285,9 @@ mod tests { "/tmp/b".into(), ]; let result = parse_allowed(&args); - assert_eq!( - result, - vec![PathBuf::from("/tmp/a"), PathBuf::from("/tmp/b")] - ); + assert_eq!(result, vec![rw("/tmp/a"), rw("/tmp/b")]); + let args: Vec = vec!["--allow-read".into(), "/tmp/c".into()]; + assert_eq!(parse_allowed(&args), vec![ro("/tmp/c")]); } #[test] @@ -263,7 +296,7 @@ mod tests { Request::Read { path: "/etc/shadow".into(), }, - &[PathBuf::from("/tmp/safe")], + &[rw("/tmp/safe")], ); let json = serde_json::to_string(&resp).unwrap(); assert!(json.contains("access denied")); @@ -277,7 +310,7 @@ mod tests { let file = dir.join("hello.txt"); fs::write(&file, b"hello world").unwrap(); - let allowed = vec![dir.clone()]; + let allowed = vec![rw(dir.clone())]; let resp = handle_request( Request::Read { path: file.to_string_lossy().into(), @@ -307,7 +340,7 @@ mod tests { fs::write(dir.join("b.txt"), b"").unwrap(); fs::write(dir.join("a.txt"), b"").unwrap(); - let allowed = vec![dir.clone()]; + let allowed = vec![rw(dir.clone())]; let resp = handle_request( Request::List { path: dir.to_string_lossy().into(), @@ -333,7 +366,7 @@ mod tests { &base64::engine::general_purpose::STANDARD, b"nested content", ); - let allowed = vec![dir.clone()]; + let allowed = vec![rw(dir.clone())]; let resp = handle_request( Request::Write { path: nested.to_string_lossy().into(), @@ -345,4 +378,36 @@ mod tests { assert_eq!(fs::read(&nested).unwrap(), b"nested content"); let _ = fs::remove_dir_all(&dir); } + + #[test] + fn read_only_directories_refuse_writes() { + use std::fs; + let dir = std::env::temp_dir().join(format!("wfp_ro_{}", std::process::id())); + let _ = fs::remove_dir_all(&dir); + fs::create_dir_all(&dir).unwrap(); + fs::write(dir.join("kept.txt"), b"original").unwrap(); + let allowed = vec![ro(dir.clone())]; + let data = base64::Engine::encode(&base64::engine::general_purpose::STANDARD, b"x"); + let resp = handle_request( + Request::Write { + path: dir.join("kept.txt").to_string_lossy().into(), + data_b64: data, + }, + &allowed, + ); + assert!( + serde_json::to_string(&resp) + .unwrap() + .contains("access denied") + ); + assert_eq!(fs::read(dir.join("kept.txt")).unwrap(), b"original"); + let resp = handle_request( + Request::Read { + path: dir.join("kept.txt").to_string_lossy().into(), + }, + &allowed, + ); + assert!(matches!(resp, Response::OkData { .. })); + let _ = fs::remove_dir_all(&dir); + } } diff --git a/crates/weft-ipc-types/src/capability.rs b/crates/weft-ipc-types/src/capability.rs new file mode 100644 index 0000000..8a0a31e --- /dev/null +++ b/crates/weft-ipc-types/src/capability.rs @@ -0,0 +1,161 @@ +//! Capabilities an application declares in `wapp.toml`. +//! +//! This is the one vocabulary shared by package validation (weft-pack), the +//! session supervisor that derives effective grants (weft-appd) and the +//! runtime that enforces them (weft-runtime). + +use std::fmt; +use std::str::FromStr; + +/// Access mode of a filesystem capability. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum Access { + Read, + ReadWrite, +} + +/// Destinations covered by a fetch capability. +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub enum FetchScope { + /// `net:fetch:*`: any host. + AnyHost, + /// `net:fetch:`: exactly this host, in lowercase. + Host(String), +} + +/// One declared capability. +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub enum Capability { + /// `fs:read:app-data` / `fs:rw:app-data`: the app's private data directory. + AppData(Access), + /// `fs:read:xdg-documents` / `fs:rw:xdg-documents`: the user's documents + /// directory. + Documents(Access), + /// `net:fetch:*` / `net:fetch:`: the `weft:app/fetch` import. + Fetch(FetchScope), + /// `sys:notifications`: the `weft:app/notifications` import. + Notifications, + /// `sys:clipboard:read`: `weft:app/clipboard#read`. + ClipboardRead, + /// `sys:clipboard:write`: `weft:app/clipboard#write`. + ClipboardWrite, + /// `hw:gpu:compute`. + GpuCompute, + /// `hw:gpu:render`. + GpuRender, +} + +/// A capability string outside the vocabulary. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct UnknownCapability(pub String); + +impl fmt::Display for UnknownCapability { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "unknown capability '{}'", self.0) + } +} + +impl std::error::Error for UnknownCapability {} + +impl FromStr for Capability { + type Err = UnknownCapability; + + fn from_str(s: &str) -> Result { + let capability = match s { + "fs:read:app-data" => Self::AppData(Access::Read), + "fs:rw:app-data" => Self::AppData(Access::ReadWrite), + "fs:read:xdg-documents" => Self::Documents(Access::Read), + "fs:rw:xdg-documents" => Self::Documents(Access::ReadWrite), + "net:fetch:*" => Self::Fetch(FetchScope::AnyHost), + "sys:notifications" => Self::Notifications, + "sys:clipboard:read" => Self::ClipboardRead, + "sys:clipboard:write" => Self::ClipboardWrite, + "hw:gpu:compute" => Self::GpuCompute, + "hw:gpu:render" => Self::GpuRender, + _ => match s.strip_prefix("net:fetch:") { + Some(host) if is_host_name(host) => Self::Fetch(FetchScope::Host(host.to_owned())), + _ => return Err(UnknownCapability(s.to_owned())), + }, + }; + Ok(capability) + } +} + +impl fmt::Display for Capability { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let mode = |access: &Access| match access { + Access::Read => "read", + Access::ReadWrite => "rw", + }; + match self { + Self::AppData(access) => write!(f, "fs:{}:app-data", mode(access)), + Self::Documents(access) => write!(f, "fs:{}:xdg-documents", mode(access)), + Self::Fetch(FetchScope::AnyHost) => f.write_str("net:fetch:*"), + Self::Fetch(FetchScope::Host(host)) => write!(f, "net:fetch:{host}"), + Self::Notifications => f.write_str("sys:notifications"), + Self::ClipboardRead => f.write_str("sys:clipboard:read"), + Self::ClipboardWrite => f.write_str("sys:clipboard:write"), + Self::GpuCompute => f.write_str("hw:gpu:compute"), + Self::GpuRender => f.write_str("hw:gpu:render"), + } + } +} + +/// A DNS host name in canonical lowercase form: dot-separated labels of +/// 1–63 letters, digits and inner hyphens, at most 253 characters. +fn is_host_name(host: &str) -> bool { + host.len() <= 253 + && host.split('.').all(|label| { + !label.is_empty() + && label.len() <= 63 + && !label.starts_with('-') + && !label.ends_with('-') + && label + .bytes() + .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-') + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn every_capability_round_trips() { + for text in [ + "fs:read:app-data", + "fs:rw:app-data", + "fs:read:xdg-documents", + "fs:rw:xdg-documents", + "net:fetch:*", + "net:fetch:api.example.org", + "sys:notifications", + "sys:clipboard:read", + "sys:clipboard:write", + "hw:gpu:compute", + "hw:gpu:render", + ] { + let capability: Capability = text.parse().unwrap(); + assert_eq!(capability.to_string(), text); + } + } + + #[test] + fn malformed_capabilities_are_unknown() { + for text in [ + "", + "fs:write:app-data", + "net:fetch", + "net:fetch:", + "net:fetch:Example.org", + "net:fetch:example.org:443", + "net:fetch:https://example.org", + "net:fetch:*.example.org", + "net:fetch:-bad.example", + "net:fetch:a..b", + "sys:clipboard", + ] { + assert!(text.parse::().is_err(), "{text:?} accepted"); + } + } +} diff --git a/crates/weft-ipc-types/src/lib.rs b/crates/weft-ipc-types/src/lib.rs index 753ef2b..7753053 100644 --- a/crates/weft-ipc-types/src/lib.rs +++ b/crates/weft-ipc-types/src/lib.rs @@ -1,3 +1,5 @@ +pub mod capability; + use serde::{Deserialize, Serialize}; pub const MAX_FRAME_LEN: usize = 4 * 1024 * 1024; diff --git a/crates/weft-pack/Cargo.toml b/crates/weft-pack/Cargo.toml index 0db5cee..d16a092 100644 --- a/crates/weft-pack/Cargo.toml +++ b/crates/weft-pack/Cargo.toml @@ -9,6 +9,7 @@ name = "weft-pack" path = "src/main.rs" [dependencies] +weft-ipc-types = { path = "../weft-ipc-types" } anyhow = "1.0" serde = { version = "1", features = ["derive"] } toml = "0.8" diff --git a/crates/weft-pack/src/main.rs b/crates/weft-pack/src/main.rs index 73434b3..62a1c58 100644 --- a/crates/weft-pack/src/main.rs +++ b/crates/weft-pack/src/main.rs @@ -190,8 +190,8 @@ fn check_package(dir: &Path) -> anyhow::Result { } for cap in m.package.capabilities.iter().flatten() { - if !is_known_capability(cap) { - errors.push(format!("unknown capability '{cap}'")); + if let Err(e) = cap.parse::() { + errors.push(e.to_string()); } } } @@ -229,28 +229,6 @@ fn print_info(m: &Manifest) { } } -fn is_known_capability(cap: &str) -> bool { - const EXACT: &[&str] = &[ - "fs:rw:app-data", - "fs:read:app-data", - "fs:rw:xdg-documents", - "fs:read:xdg-documents", - "net:fetch:*", - "hw:gpu:compute", - "hw:gpu:render", - "sys:notifications", - "sys:clipboard:read", - "sys:clipboard:write", - ]; - if EXACT.contains(&cap) { - return true; - } - if let Some(domain) = cap.strip_prefix("net:fetch:") { - return !domain.is_empty() && domain != "*"; - } - false -} - fn is_valid_app_id(id: &str) -> bool { let parts: Vec<&str> = id.split('.').collect(); if parts.len() < 3 { diff --git a/crates/weft-runtime/Cargo.toml b/crates/weft-runtime/Cargo.toml index 532a7e0..8fd3c2a 100644 --- a/crates/weft-runtime/Cargo.toml +++ b/crates/weft-runtime/Cargo.toml @@ -12,7 +12,7 @@ path = "src/main.rs" default = [] wasmtime-runtime = ["dep:wasmtime", "dep:wasmtime-wasi", "dep:cap-std"] seccomp = ["dep:seccompiler", "dep:libc"] -net-fetch = ["dep:ureq"] +net-fetch = ["dep:ureq", "dep:url"] [dependencies] anyhow = "1.0" @@ -24,3 +24,5 @@ cap-std = { version = "3", optional = true } seccompiler = { version = "0.4", optional = true } libc = { version = "0.2", optional = true } ureq = { version = "2", optional = true } +url = { version = "2", optional = true } +weft-ipc-types = { path = "../weft-ipc-types" } diff --git a/crates/weft-runtime/src/grants.rs b/crates/weft-runtime/src/grants.rs new file mode 100644 index 0000000..c296e5e --- /dev/null +++ b/crates/weft-runtime/src/grants.rs @@ -0,0 +1,173 @@ +//! The effective grants weft-appd derived for this session. +//! +//! weft-appd passes each host-import capability as `--grant ` and +//! each filesystem capability as `--preopen HOST::GUEST::ro|rw`. Nothing here +//! reads the package manifest: the runtime enforces what the supervisor +//! granted, not what the package asks for. + +use anyhow::Context; +use weft_ipc_types::capability::{Access, Capability, FetchScope}; + +/// Grants for the host imports in the `weft:app` world. +#[derive(Debug, Default)] +pub struct Grants { + fetch: Vec, + notifications: bool, + clipboard_read: bool, + clipboard_write: bool, +} + +// The checks are used by the import implementations, which only exist with +// the wasmtime-runtime feature. +#[cfg_attr(not(feature = "wasmtime-runtime"), allow(dead_code))] +impl Grants { + /// Adds a `--grant` argument. Filesystem capabilities arrive as preopens + /// and hardware capabilities have no import, so both are refused here. + pub fn add(&mut self, spec: &str) -> anyhow::Result<()> { + match spec.parse::()? { + Capability::Fetch(scope) => self.fetch.push(scope), + Capability::Notifications => self.notifications = true, + Capability::ClipboardRead => self.clipboard_read = true, + Capability::ClipboardWrite => self.clipboard_write = true, + other => anyhow::bail!("'{other}' is not granted through --grant"), + } + Ok(()) + } + + pub fn notifications(&self) -> Result<(), String> { + granted(self.notifications, "sys:notifications") + } + + pub fn clipboard_read(&self) -> Result<(), String> { + granted(self.clipboard_read, "sys:clipboard:read") + } + + pub fn clipboard_write(&self) -> Result<(), String> { + granted(self.clipboard_write, "sys:clipboard:write") + } + + #[cfg_attr(not(feature = "net-fetch"), allow(dead_code))] + /// Whether a request to `host` is covered by a fetch grant. `host` is the + /// URL's host in the lowercase form URL parsing produces. + pub fn fetch_host(&self, host: &str) -> Result<(), String> { + if self.fetch.is_empty() { + return Err("capability net:fetch is not granted".to_owned()); + } + let covered = self.fetch.iter().any(|scope| match scope { + FetchScope::AnyHost => true, + FetchScope::Host(granted) => granted == host, + }); + if covered { + Ok(()) + } else { + Err(format!("capability net:fetch:{host} is not granted")) + } + } + + /// Whether any fetch grant exists, before a URL is examined. + pub fn fetch_any(&self) -> Result<(), String> { + granted(!self.fetch.is_empty(), "net:fetch") + } +} + +#[cfg_attr(not(feature = "wasmtime-runtime"), allow(dead_code))] +fn granted(present: bool, capability: &str) -> Result<(), String> { + if present { + Ok(()) + } else { + Err(format!("capability {capability} is not granted")) + } +} + +/// A directory made visible to the component. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Preopen { + pub host: String, + pub guest: String, + pub access: Access, +} + +impl Preopen { + /// Parses `HOST::GUEST::ro` or `HOST::GUEST::rw`. + pub fn parse(spec: &str) -> anyhow::Result { + let (rest, mode) = spec + .rsplit_once("::") + .context("--preopen expects HOST::GUEST::ro|rw")?; + let (host, guest) = rest + .split_once("::") + .context("--preopen expects HOST::GUEST::ro|rw")?; + let access = match mode { + "ro" => Access::Read, + "rw" => Access::ReadWrite, + other => anyhow::bail!("--preopen mode must be ro or rw, not '{other}'"), + }; + anyhow::ensure!( + !host.is_empty() && guest.starts_with('/'), + "--preopen needs a host path and an absolute guest path" + ); + Ok(Self { + host: host.to_owned(), + guest: guest.to_owned(), + access, + }) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn imports_are_denied_without_grants() { + let grants = Grants::default(); + assert!(grants.notifications().is_err()); + assert!(grants.clipboard_read().is_err()); + assert!(grants.clipboard_write().is_err()); + assert!(grants.fetch_any().is_err()); + assert!(grants.fetch_host("example.org").is_err()); + } + + #[test] + fn each_grant_opens_only_its_import() { + let mut grants = Grants::default(); + grants.add("sys:clipboard:read").unwrap(); + assert!(grants.clipboard_read().is_ok()); + assert!(grants.clipboard_write().is_err()); + assert!(grants.notifications().is_err()); + } + + #[test] + fn host_fetch_grants_match_exact_hosts() { + let mut grants = Grants::default(); + grants.add("net:fetch:api.example.org").unwrap(); + assert!(grants.fetch_any().is_ok()); + assert!(grants.fetch_host("api.example.org").is_ok()); + assert!(grants.fetch_host("example.org").is_err()); + assert!(grants.fetch_host("evil.api.example.org").is_err()); + grants.add("net:fetch:*").unwrap(); + assert!(grants.fetch_host("example.org").is_ok()); + } + + #[test] + fn filesystem_and_unknown_grants_are_refused() { + let mut grants = Grants::default(); + assert!(grants.add("fs:rw:app-data").is_err()); + assert!(grants.add("hw:gpu:compute").is_err()); + assert!(grants.add("sys:everything").is_err()); + } + + #[test] + fn preopens_carry_their_mode() { + let preopen = Preopen::parse("/home/u/data::/data::ro").unwrap(); + assert_eq!(preopen.host, "/home/u/data"); + assert_eq!(preopen.guest, "/data"); + assert_eq!(preopen.access, Access::Read); + assert_eq!( + Preopen::parse("/a::/b::rw").unwrap().access, + Access::ReadWrite + ); + for bad in ["/a::/b", "/a", "/a::/b::wx", "::/b::ro", "/a::b::ro"] { + assert!(Preopen::parse(bad).is_err(), "{bad} accepted"); + } + } +} diff --git a/crates/weft-runtime/src/main.rs b/crates/weft-runtime/src/main.rs index 8c6f3e1..63e31f1 100644 --- a/crates/weft-runtime/src/main.rs +++ b/crates/weft-runtime/src/main.rs @@ -2,6 +2,10 @@ use std::path::PathBuf; use anyhow::Context; +mod grants; + +use grants::{Grants, Preopen}; + fn main() -> anyhow::Result<()> { tracing_subscriber::fmt() .with_env_filter( @@ -14,7 +18,7 @@ fn main() -> anyhow::Result<()> { if args.len() < 3 { anyhow::bail!( "usage: weft-runtime \ - [--preopen HOST::GUEST]... [--ipc-socket PATH]" + [--preopen HOST::GUEST::ro|rw]... [--grant CAPABILITY]... [--ipc-socket PATH]" ); } let app_id = &args[1]; @@ -22,7 +26,8 @@ fn main() -> anyhow::Result<()> { .parse() .with_context(|| format!("invalid session_id: {}", args[2]))?; - let mut preopen: Vec<(String, String)> = Vec::new(); + let mut preopen: Vec = Vec::new(); + let mut grants = Grants::default(); let mut ipc_socket: Option = None; let mut i = 3usize; @@ -31,11 +36,11 @@ fn main() -> anyhow::Result<()> { "--preopen" => { i += 1; let spec = args.get(i).context("--preopen requires an argument")?; - if let Some((host, guest)) = spec.split_once("::") { - preopen.push((host.to_string(), guest.to_string())); - } else { - preopen.push((spec.clone(), spec.clone())); - } + preopen.push(Preopen::parse(spec)?); + } + "--grant" => { + i += 1; + grants.add(args.get(i).context("--grant requires an argument")?)?; } "--ipc-socket" => { i += 1; @@ -64,7 +69,7 @@ fn main() -> anyhow::Result<()> { } tracing::info!(session_id, %app_id, wasm = %wasm_path.display(), "executing module"); - run_module(&wasm_path, &preopen, ipc_socket.as_deref())?; + run_module(&wasm_path, &preopen, grants, ipc_socket.as_deref())?; tracing::info!(session_id, %app_id, "exiting"); Ok(()) @@ -94,7 +99,8 @@ fn resolve_package(app_id: &str) -> anyhow::Result { #[cfg(not(feature = "wasmtime-runtime"))] fn run_module( _wasm_path: &std::path::Path, - _preopen: &[(String, String)], + _preopen: &[Preopen], + _grants: Grants, _ipc_socket: Option<&str>, ) -> anyhow::Result<()> { anyhow::bail!( @@ -105,7 +111,8 @@ fn run_module( #[cfg(feature = "wasmtime-runtime")] fn run_module( wasm_path: &std::path::Path, - preopen: &[(String, String)], + preopen: &[Preopen], + grants: Grants, ipc_socket: Option<&str>, ) -> anyhow::Result<()> { use std::sync::{Arc, Mutex}; @@ -117,6 +124,7 @@ fn run_module( DirPerms, FilePerms, IoView, ResourceTable, WasiCtx, WasiCtxBuilder, WasiView, add_to_linker_sync, bindings::sync::Command, }; + use weft_ipc_types::capability::Access; struct IpcState { socket: std::os::unix::net::UnixStream, @@ -175,7 +183,6 @@ fn run_module( struct State { ctx: WasiCtx, table: ResourceTable, - ipc: Arc>>, } impl IoView for State { @@ -197,6 +204,7 @@ fn run_module( let component = Component::from_file(&engine, wasm_path) .with_context(|| format!("load component {}", wasm_path.display()))?; + let grants = Arc::new(grants); let mut linker: Linker = Linker::new(&engine); add_to_linker_sync(&mut linker).context("add WASI to linker")?; let ipc_state: Arc>> = Arc::new(Mutex::new(None)); @@ -245,34 +253,35 @@ fn run_module( .context("define weft:app/ipc#recv")?; } + // Every import below checks the session's grants on each call; an + // ungranted call returns an error to the component. + let fetch_grants = Arc::clone(&grants); linker .instance("weft:app/fetch@0.1.0") .context("define weft:app/fetch instance")? .func_wrap( "fetch", - |_: wasmtime::StoreContextMut<'_, State>, - (url, method, headers, body): ( - String, - String, - Vec<(String, String)>, - Option>, - )| - -> wasmtime::Result<(Result<(u16, String, Vec), String>,)> { - let result = host_fetch(&url, &method, &headers, body.as_deref()); + move |_: wasmtime::StoreContextMut<'_, State>, + (url, method, headers, body): FetchRequest| + -> wasmtime::Result<(FetchResult,)> { + let result = host_fetch(&fetch_grants, &url, &method, &headers, body.as_deref()); Ok((result,)) }, ) .context("define weft:app/fetch#fetch")?; + let notify_grants = Arc::clone(&grants); linker .instance("weft:app/notifications@0.1.0") .context("define weft:app/notifications instance")? .func_wrap( "notify", - |_: wasmtime::StoreContextMut<'_, State>, - (title, body, icon): (String, String, Option)| - -> wasmtime::Result<(Result<(), String>,)> { - let result = host_notify(&title, &body, icon.as_deref()); + move |_: wasmtime::StoreContextMut<'_, State>, + (title, body, icon): (String, String, Option)| + -> wasmtime::Result<(Result<(), String>,)> { + let result = notify_grants + .notifications() + .and_then(|()| host_notify(&title, &body, icon.as_deref())); Ok((result,)) }, ) @@ -282,23 +291,29 @@ fn run_module( let mut clipboard = linker .instance("weft:app/clipboard@0.1.0") .context("define weft:app/clipboard instance")?; + let read_grants = Arc::clone(&grants); clipboard .func_wrap( "read", - |_: wasmtime::StoreContextMut<'_, State>, - ()| - -> wasmtime::Result<(Result,)> { - Ok((host_clipboard_read(),)) + move |_: wasmtime::StoreContextMut<'_, State>, + ()| + -> wasmtime::Result<(Result,)> { + Ok((read_grants + .clipboard_read() + .and_then(|()| host_clipboard_read()),)) }, ) .context("define weft:app/clipboard#read")?; + let write_grants = Arc::clone(&grants); clipboard .func_wrap( "write", - |_: wasmtime::StoreContextMut<'_, State>, - (text,): (String,)| - -> wasmtime::Result<(Result<(), String>,)> { - Ok((host_clipboard_write(&text),)) + move |_: wasmtime::StoreContextMut<'_, State>, + (text,): (String,)| + -> wasmtime::Result<(Result<(), String>,)> { + Ok((write_grants + .clipboard_write() + .and_then(|()| host_clipboard_write(&text)),)) }, ) .context("define weft:app/clipboard#write")?; @@ -320,10 +335,14 @@ fn run_module( ctx_builder.env("WEFT_FILE_PORTAL_SOCKET", &portal_socket); } - for (host_path, guest_path) in preopen { + for dir in preopen { + let (dir_perms, file_perms) = match dir.access { + Access::Read => (DirPerms::READ, FilePerms::READ), + Access::ReadWrite => (DirPerms::all(), FilePerms::all()), + }; ctx_builder - .preopened_dir(host_path, guest_path, DirPerms::all(), FilePerms::all()) - .with_context(|| format!("preopen dir {host_path}"))?; + .preopened_dir(&dir.host, &dir.guest, dir_perms, file_perms) + .with_context(|| format!("preopen dir {}", dir.host))?; } let ctx = ctx_builder.build(); @@ -332,7 +351,6 @@ fn run_module( State { ctx, table: ResourceTable::new(), - ipc: ipc_state, }, ); @@ -346,41 +364,97 @@ fn run_module( .map_err(|()| anyhow::anyhow!("wasm component run exited with error")) } +/// Arguments of `weft:app/fetch#fetch`: URL, method, headers and body. +#[cfg(feature = "wasmtime-runtime")] +type FetchRequest = (String, String, Vec<(String, String)>, Option>); + +/// `weft:app/fetch.response`. +#[cfg(feature = "wasmtime-runtime")] +#[derive( + wasmtime::component::ComponentType, wasmtime::component::Lift, wasmtime::component::Lower, +)] +#[component(record)] +struct FetchResponse { + status: u16, + #[component(name = "content-type")] + content_type: String, + body: Vec, +} + +/// Result of `weft:app/fetch#fetch`. +#[cfg(feature = "wasmtime-runtime")] +type FetchResult = Result; + +/// Longest response body returned to a component. +#[cfg(all(feature = "wasmtime-runtime", feature = "net-fetch"))] +const MAX_FETCH_RESPONSE: u64 = 16 * 1024 * 1024; + +/// Performs a granted HTTP request. Redirects are returned to the component +/// as responses rather than followed, so every destination it reaches is +/// checked against its grants. HTTP error statuses are responses too; only +/// policy and transport failures are errors. #[cfg(all(feature = "wasmtime-runtime", feature = "net-fetch"))] fn host_fetch( + grants: &Grants, url: &str, method: &str, headers: &[(String, String)], body: Option<&[u8]>, -) -> Result<(u16, String, Vec), String> { +) -> FetchResult { use std::io::Read; - let mut req = ureq::request(method, url); + use std::time::Duration; + grants.fetch_any()?; + let parsed = url::Url::parse(url).map_err(|e| format!("invalid URL: {e}"))?; + if !matches!(parsed.scheme(), "http" | "https") { + return Err(format!("unsupported URL scheme '{}'", parsed.scheme())); + } + let host = parsed.host_str().ok_or("URL has no host")?; + grants.fetch_host(host)?; + let agent = ureq::AgentBuilder::new() + .redirects(0) + .timeout_connect(Duration::from_secs(10)) + .timeout(Duration::from_secs(30)) + .build(); + let mut req = agent.request_url(method, &parsed); for (name, value) in headers { req = req.set(name, value); } let response = match body { Some(b) => req.send_bytes(b), None => req.call(), - } - .map_err(|e| e.to_string())?; + }; + let response = match response { + Ok(response) | Err(ureq::Error::Status(_, response)) => response, + Err(e) => return Err(e.to_string()), + }; let status = response.status(); let content_type = response.content_type().to_owned(); let mut body_bytes = Vec::new(); response .into_reader() + .take(MAX_FETCH_RESPONSE + 1) .read_to_end(&mut body_bytes) .map_err(|e| e.to_string())?; - Ok((status, content_type, body_bytes)) + if body_bytes.len() as u64 > MAX_FETCH_RESPONSE { + return Err(format!("response body exceeds {MAX_FETCH_RESPONSE} bytes")); + } + Ok(FetchResponse { + status, + content_type, + body: body_bytes, + }) } #[cfg(all(feature = "wasmtime-runtime", not(feature = "net-fetch")))] fn host_fetch( + grants: &Grants, _url: &str, _method: &str, _headers: &[(String, String)], _body: Option<&[u8]>, -) -> Result<(u16, String, Vec), String> { - Err("net-fetch capability not compiled in".to_owned()) +) -> FetchResult { + grants.fetch_any()?; + Err("this runtime was built without network fetch support".to_owned()) } #[cfg(feature = "wasmtime-runtime")] @@ -520,8 +594,13 @@ mod tests { #[cfg(not(feature = "wasmtime-runtime"))] #[test] fn engine_disabled_build_refuses_to_run_components() { - let err = run_module(std::path::Path::new("app.wasm"), &[], None) - .expect_err("a build without wasmtime-runtime must not report success"); + let err = run_module( + std::path::Path::new("app.wasm"), + &[], + Grants::default(), + None, + ) + .expect_err("a build without wasmtime-runtime must not report success"); assert!(err.to_string().contains("wasmtime-runtime")); } diff --git a/docs/architecture.md b/docs/architecture.md index ca77f3c..f1bce47 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -32,7 +32,7 @@ Package management CLI. Subcommands: `check` (validate wapp.toml + wasm module), ### weft-file-portal -Per-session file proxy. Runs as a separate process with a path allowlist derived from preopened directories. Accepts JSON-lines requests over a Unix socket. Blocks path traversal. Used by apps that require file access without direct WASI preopens. +Per-session file proxy. Runs as a separate process with a path allowlist derived from the session's directory grants; read-only grants (`--allow-read`) refuse writes. Accepts JSON-lines requests over a Unix socket. Blocks path traversal. Used by apps that require file access without direct WASI preopens. ### weft-mount-helper @@ -46,9 +46,9 @@ systemd ├── weft-servo-shell (user, after compositor) └── weft-appd (user, after compositor + servo-shell) └── per-session: - ├── weft-runtime [--preopen ...] [--ipc-socket ...] + ├── weft-runtime [--preopen HOST::GUEST::ro|rw]... [--grant CAP]... [--ipc-socket ...] ├── weft-app-shell - └── weft-file-portal [--allow ...] + └── weft-file-portal [--allow ...] [--allow-read ...] ``` ## IPC @@ -69,15 +69,28 @@ Every WebSocket connection must complete the upgrade and send `HELLO` as its fir ## Capability Enforcement -Capabilities are declared in `wapp.toml` under `[package] capabilities`. `weft-pack check` validates that only known capabilities are listed. At runtime, `weft-appd` reads capabilities and maps them to WASI preopened directories and host function availability: +Capabilities are declared in `wapp.toml` under `[package] capabilities`. One vocabulary (`weft_ipc_types::capability`) is used by `weft-pack check`, which rejects unknown strings, by `weft-appd`, which derives the session's effective grants, and by `weft-runtime`, which enforces them. + +`weft-appd` derives grants once, before a session exists. If any declared capability is unknown, unsupported on this host or cannot be satisfied, `LAUNCH_APP` is answered with an error (code 403) and nothing starts. The runtime does not read the manifest; it receives the grants as arguments: + +- `--preopen HOST::GUEST::ro|rw` for each directory, with the access mode the capability names; +- `--grant ` for each host-import capability. + +Each host import checks its grant on every call and returns an error naming the missing capability when it is not granted. | Capability | Effect | |---|---| -| `fs:rw:app-data` | Preopen `~/.local/share/weft/apps//data` as `/data` | -| `fs:read:app-data` | Same, read-only | -| `fs:rw:xdg-documents` | Preopen `~/Documents` as `/xdg/documents` | -| `net:fetch` | Enables `weft:app/fetch` host function | -| `sys:notifications` | Enables `weft:app/notifications` host function | +| `fs:read:app-data` / `fs:rw:app-data` | Preopen `~/.local/share/weft/apps//data` as `/data`, read-only or read-write | +| `fs:read:xdg-documents` / `fs:rw:xdg-documents` | Preopen the documents directory from the XDG user-dirs configuration (`XDG_DOCUMENTS_DIR`) as `/xdg/documents`; the launch fails when none is configured | +| `net:fetch:` | `weft:app/fetch` to that exact host over HTTP or HTTPS | +| `net:fetch:*` | `weft:app/fetch` to any host | +| `sys:notifications` | `weft:app/notifications` | +| `sys:clipboard:read` / `sys:clipboard:write` | `weft:app/clipboard#read` / `#write` | +| `hw:gpu:compute` / `hw:gpu:render` | Not supported; the launch fails | + +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. Requests time out after 10 seconds to connect and 30 seconds overall, and response bodies are limited to 16 MiB. Fetch requires a runtime built with the `net-fetch` feature. + +`tests/runtime/check_grants.py` runs the real runtime on a probe component (`tests/components/grants-probe`) under each kind of grant. ## Package Format diff --git a/docs/security.md b/docs/security.md index 5fdda69..09a6b4a 100644 --- a/docs/security.md +++ b/docs/security.md @@ -6,7 +6,9 @@ WEFT OS enforces a capability-based security model. No capability is granted by ## Capability Verification -`weft-pack check` validates capability strings against a known set (`KNOWN_CAPS`) before installation. Unknown capability strings are rejected. The validated capability list is read by `weft-appd` at session start to map capabilities to concrete resource grants. +`weft-pack check` validates capability strings against the shared vocabulary in `weft_ipc_types::capability`. Unknown capability strings are rejected. At launch, `weft-appd` derives the session's grants from the manifest and refuses to start a package with a capability that is unknown, unsupported or unsatisfiable. `weft-runtime` enforces the grants it is given: read-only directories are preopened read-only, and each host import checks its grant on every call. See the capability table in `architecture.md`. + +Installing a package does not yet ask the user to approve its capabilities; every declared, supported capability is granted at launch. ## Process Isolation @@ -14,7 +16,7 @@ Each app session runs as a separate OS process (`weft-runtime`). When systemd is ## Filesystem Isolation -Apps access the filesystem only through WASI preopened directories. Each capability maps to a specific host path preopened at a fixed guest path. The `weft-file-portal` process enforces path allowlists and blocks `..` traversal for apps that use the portal protocol. +Apps access the filesystem only through WASI preopened directories. Each capability maps to a specific host path preopened at a fixed guest path. The `weft-file-portal` process applies the same directory grants and access modes, but checks paths lexically: it blocks `..` traversal, not symbolic links. Components cannot currently reach its socket, since the runtime grants them no socket access. ## Package Signing diff --git a/tests/components/grants-probe/Cargo.lock b/tests/components/grants-probe/Cargo.lock new file mode 100644 index 0000000..20f8187 --- /dev/null +++ b/tests/components/grants-probe/Cargo.lock @@ -0,0 +1,337 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "anyhow" +version = "1.0.104" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" + +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" + +[[package]] +name = "equivalent" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f" + +[[package]] +name = "foldhash" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" + +[[package]] +name = "hashbrown" +version = "0.16.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100" +dependencies = [ + "foldhash", +] + +[[package]] +name = "hashbrown" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "id-arena" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954" + +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown 0.17.1", + "serde", + "serde_core", +] + +[[package]] +name = "itoa" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" + +[[package]] +name = "leb128fmt" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09edd9e8b54e49e587e4f6295a7d29c3ea94d469cb40ab8ca70b288248a81db2" + +[[package]] +name = "log" +version = "0.4.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6" + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "prettyplease" +version = "0.2.37" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "479ca8adacdd7ce8f1fb39ce9ecccbfe93a3f1344b3d0d97f20bc0196208f62b" +dependencies = [ + "proc-macro2", + "syn 2.0.119", +] + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "semver" +version = "1.0.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.6", +] + +[[package]] +name = "serde_json" +version = "1.0.151" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c841b55ecdae098c80dcae9cf767f6f8a0c2cdb3416bbef72181df4d0fe73f14" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "3.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8593e8e72159ed2257d083c7a454a85cbf854f37a0966d8d483aff8c8a3ebcee" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "unicode-ident" +version = "1.0.26" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d245f478577f809a851594d02313b640fb437e0bb33866753cff937863096954" + +[[package]] +name = "unicode-xid" +version = "0.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853" + +[[package]] +name = "wasm-encoder" +version = "0.245.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f9dca005e69bf015e45577e415b9af8c67e8ee3c0e38b5b0add5aa92581ed5c" +dependencies = [ + "leb128fmt", + "wasmparser", +] + +[[package]] +name = "wasm-metadata" +version = "0.245.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da55e60097e8b37b475a0fa35c3420dd71d9eb7bd66109978ab55faf56a57efb" +dependencies = [ + "anyhow", + "indexmap", + "wasm-encoder", + "wasmparser", +] + +[[package]] +name = "wasmparser" +version = "0.245.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4f08c9adee0428b7bddf3890fc27e015ac4b761cc608c822667102b8bfd6995e" +dependencies = [ + "bitflags", + "hashbrown 0.16.1", + "indexmap", + "semver", +] + +[[package]] +name = "weft-grants-probe" +version = "0.1.0" +dependencies = [ + "wit-bindgen", +] + +[[package]] +name = "wit-bindgen" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e915216dde3e818093168df8380a64fba25df468d626c80dd5d6a184c87e7c7" +dependencies = [ + "bitflags", + "wit-bindgen-rust-macro", +] + +[[package]] +name = "wit-bindgen-core" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3deda4b7e9f522d994906f6e6e0fc67965ea8660306940a776b76732be8f3933" +dependencies = [ + "anyhow", + "heck", + "wit-parser", +] + +[[package]] +name = "wit-bindgen-rust" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "863a7ab3c4dfee58db196811caeb0718b88412a0aef3d1c2b02fcbae1e37c688" +dependencies = [ + "anyhow", + "heck", + "indexmap", + "prettyplease", + "syn 2.0.119", + "wasm-metadata", + "wit-bindgen-core", + "wit-component", +] + +[[package]] +name = "wit-bindgen-rust-macro" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d14f3a9bfa3804bb0e9ab7f66da047f210eded6a1297ae3ba5805b384d64797f" +dependencies = [ + "anyhow", + "prettyplease", + "proc-macro2", + "quote", + "syn 2.0.119", + "wit-bindgen-core", + "wit-bindgen-rust", +] + +[[package]] +name = "wit-component" +version = "0.245.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4894f10d2d5cbc17c77e91f86a1e48e191a788da4425293b55c98b44ba3fcac9" +dependencies = [ + "anyhow", + "bitflags", + "indexmap", + "log", + "serde", + "serde_derive", + "serde_json", + "wasm-encoder", + "wasm-metadata", + "wasmparser", + "wit-parser", +] + +[[package]] +name = "wit-parser" +version = "0.245.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "330698718e82983499419494dd1e3d7811a457a9bf9f69734e8c5f07a2547929" +dependencies = [ + "anyhow", + "hashbrown 0.16.1", + "id-arena", + "indexmap", + "log", + "semver", + "serde", + "serde_derive", + "serde_json", + "unicode-xid", + "wasmparser", +] + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/tests/components/grants-probe/Cargo.toml b/tests/components/grants-probe/Cargo.toml new file mode 100644 index 0000000..3ff4f2c --- /dev/null +++ b/tests/components/grants-probe/Cargo.toml @@ -0,0 +1,12 @@ +[package] +name = "weft-grants-probe" +version = "0.1.0" +edition = "2024" +publish = false + +[[bin]] +name = "app" +path = "src/main.rs" + +[dependencies] +wit-bindgen = "0.53" diff --git a/tests/components/grants-probe/src/main.rs b/tests/components/grants-probe/src/main.rs new file mode 100644 index 0000000..0976240 --- /dev/null +++ b/tests/components/grants-probe/src/main.rs @@ -0,0 +1,35 @@ +//! Test component that calls every grant-controlled operation once and +//! prints one `PROBE ok ` or `PROBE err ` +//! line for each. +//! +//! Fetch targets are read from `/probe/targets.txt` (` ` per +//! line), a directory the harness preopens read-only next to the grants +//! under test. + +wit_bindgen::generate!({ + path: "wit", + world: "app", + generate_all, +}); + +use weft::app::{clipboard, fetch, notifications, notify}; + +fn report(name: &str, result: Result) { + match result { + Ok(value) => println!("PROBE {name} ok {value:?}"), + Err(e) => println!("PROBE {name} err {}", e.to_string().replace('\n', " ")), + } +} + +fn main() { + report("data-read", std::fs::read_to_string("/data/seed.txt")); + report("data-write", std::fs::write("/data/written.txt", "probe")); + report("notifications", notifications::notify("probe", "probe", None)); + report("clipboard-read", clipboard::read()); + report("clipboard-write", clipboard::write("probe")); + let targets = std::fs::read_to_string("/probe/targets.txt").unwrap_or_default(); + for (name, url) in targets.lines().filter_map(|line| line.split_once(' ')) { + report(name, fetch::fetch(url, "GET", &[], None).map(|r| r.status)); + } + notify::ready(); +} diff --git a/tests/components/grants-probe/wit/deps/weft-app b/tests/components/grants-probe/wit/deps/weft-app new file mode 120000 index 0000000..6764e61 --- /dev/null +++ b/tests/components/grants-probe/wit/deps/weft-app @@ -0,0 +1 @@ +../../../../../crates/weft-runtime/wit \ No newline at end of file diff --git a/tests/components/grants-probe/wit/world.wit b/tests/components/grants-probe/wit/world.wit new file mode 100644 index 0000000..0949bf8 --- /dev/null +++ b/tests/components/grants-probe/wit/world.wit @@ -0,0 +1,8 @@ +package weft:grants-probe@0.1.0; + +world app { + import weft:app/notify@0.1.0; + import weft:app/fetch@0.1.0; + import weft:app/notifications@0.1.0; + import weft:app/clipboard@0.1.0; +} diff --git a/tests/runtime/check_grants.py b/tests/runtime/check_grants.py new file mode 100644 index 0000000..abb2ad3 --- /dev/null +++ b/tests/runtime/check_grants.py @@ -0,0 +1,186 @@ +"""Check that weft-runtime enforces the grants weft-appd passes it. + +The harness runs the real runtime (built with wasmtime-runtime and +net-fetch) on the test component in tests/components/grants-probe, which +calls every grant-controlled operation once and prints its outcome. Each +scenario passes a different set of `--grant` and `--preopen` arguments: + +- no grants: no /data, and every host import reports that its capability + is not granted; +- read-only data: /data can be read but not written, and nothing appears + on the host; +- read-write data: the write reaches the host directory; +- notifications and clipboard read: those imports are attempted (they may + still fail for lack of a desktop service) while clipboard write stays + denied; +- a host-specific fetch grant: requests to that host return their real + status (200, 404, and 302 without following the redirect to another + host), and requests to another host are denied; +- a wildcard fetch grant: the other host is reachable. + +It also checks that the runtime refuses filesystem capabilities passed as +`--grant` and preopens without an access mode. + +Requires cargo with the wasm32-wasip2 target. +""" + +import argparse +import http.server +import shutil +import subprocess +import sys +import tempfile +import threading +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[2] +PROBE_DIR = ROOT / "tests/components/grants-probe" +APP_ID = "org.weft.test.grants" +NOT_GRANTED = "is not granted" + + +class Handler(http.server.BaseHTTPRequestHandler): + def do_GET(self): + if self.path == "/ok": + self.send_response(200) + elif self.path == "/redirect": + self.send_response(302) + self.send_header("Location", f"http://localhost:{self.server.server_port}/ok") + else: + self.send_response(404) + self.send_header("Content-Length", "0") + self.end_headers() + + def log_message(self, *args): + pass + + +def build_probe(): + subprocess.run(["cargo", "build", "-q", "--release", "--target", "wasm32-wasip2"], + cwd=PROBE_DIR, check=True) + return PROBE_DIR / "target/wasm32-wasip2/release/app.wasm" + + +class Runner: + def __init__(self, runtime, work, port): + self.runtime = runtime + self.work = work + self.store = work / "store" + package = self.store / APP_ID + package.mkdir(parents=True) + (package / "wapp.toml").write_text( + f'[package]\nid = "{APP_ID}"\nname = "Grants probe"\nversion = "0.1.0"\n' + '[runtime]\nmodule = "app.wasm"\n[ui]\nentry = "ui/index.html"\n') + self.package = package + self.targets = work / "targets" + self.targets.mkdir() + (self.targets / "targets.txt").write_text( + f"fetch-ok http://127.0.0.1:{port}/ok\n" + f"fetch-missing http://127.0.0.1:{port}/missing\n" + f"fetch-redirect http://127.0.0.1:{port}/redirect\n" + f"fetch-other-host http://localhost:{port}/ok\n") + + def run(self, *arguments, expect_success=True): + command = [str(self.runtime), APP_ID, "1", + "--preopen", f"{self.targets}::/probe::ro", *arguments] + result = subprocess.run(command, capture_output=True, text=True, timeout=60, + env={"WEFT_APP_STORE": str(self.store), "PATH": "/usr/bin:/bin", + "RUST_LOG": "warn"}) + if expect_success and result.returncode != 0: + raise AssertionError(f"runtime failed: {' '.join(arguments)}\n{result.stderr}") + probes = {} + for line in result.stdout.splitlines(): + if line.startswith("PROBE "): + name, outcome = line[6:].split(" ", 1) + probes[name] = outcome + return result, probes + + +def expect(probes, name, ok, contains=None, absent=None): + outcome = probes.get(name) + if outcome is None: + raise AssertionError(f"{name}: no result") + if outcome.startswith("ok") != ok: + raise AssertionError(f"{name}: expected {'success' if ok else 'failure'}, got {outcome!r}") + if contains is not None and contains not in outcome: + raise AssertionError(f"{name}: expected {contains!r} in {outcome!r}") + if absent is not None and absent in outcome: + raise AssertionError(f"{name}: did not expect {absent!r} in {outcome!r}") + + +def check(runner, data): + _, probes = runner.run() + expect(probes, "data-read", False) + expect(probes, "data-write", False) + for name in ("notifications", "clipboard-read", "clipboard-write", + "fetch-ok", "fetch-other-host"): + expect(probes, name, False, contains=NOT_GRANTED) + + (data / "seed.txt").write_text("seed") + _, probes = runner.run("--preopen", f"{data}::/data::ro") + expect(probes, "data-read", True, contains="seed") + expect(probes, "data-write", False) + if (data / "written.txt").exists(): + raise AssertionError("read-only grant allowed a write on the host") + + _, probes = runner.run("--preopen", f"{data}::/data::rw") + expect(probes, "data-write", True) + if (data / "written.txt").read_text() != "probe": + raise AssertionError("read-write grant did not write to the host directory") + + _, probes = runner.run("--grant", "sys:notifications", "--grant", "sys:clipboard:read") + expect(probes, "notifications", probes.get("notifications", "").startswith("ok"), + absent=NOT_GRANTED) + expect(probes, "clipboard-read", probes.get("clipboard-read", "").startswith("ok"), + absent=NOT_GRANTED) + expect(probes, "clipboard-write", False, contains=NOT_GRANTED) + + _, probes = runner.run("--grant", "net:fetch:127.0.0.1") + expect(probes, "fetch-ok", True, contains="200") + expect(probes, "fetch-missing", True, contains="404") + expect(probes, "fetch-redirect", True, contains="302") + expect(probes, "fetch-other-host", False, contains=NOT_GRANTED) + + _, probes = runner.run("--grant", "net:fetch:*") + expect(probes, "fetch-other-host", True, contains="200") + + for arguments in (["--grant", "fs:rw:app-data"], ["--preopen", f"{data}::/data"], + ["--grant", "sys:everything"]): + result, _ = runner.run(*arguments, expect_success=False) + if result.returncode == 0: + raise AssertionError(f"runtime accepted {' '.join(arguments)}") + + +def main(argv=None): + parser = argparse.ArgumentParser(description=__doc__, + formatter_class=argparse.RawDescriptionHelpFormatter) + parser.add_argument("--runtime", type=Path, default=ROOT / "target/debug/weft-runtime", + help="weft-runtime built with wasmtime-runtime and net-fetch") + parser.add_argument("--probe", type=Path, help="prebuilt probe component") + args = parser.parse_args(argv) + if not args.runtime.is_file(): + print(f"missing: {args.runtime}", file=sys.stderr) + return 2 + + probe = args.probe or build_probe() + server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler) + threading.Thread(target=server.serve_forever, daemon=True).start() + work = Path(tempfile.mkdtemp(prefix="weft-grants-")) + try: + runner = Runner(args.runtime, work, server.server_port) + shutil.copy(probe, runner.package / "app.wasm") + data = work / "data" + data.mkdir() + check(runner, data) + except AssertionError as failure: + print(f"grants check failed: {failure}", file=sys.stderr) + return 1 + finally: + server.shutdown() + shutil.rmtree(work, ignore_errors=True) + print("grants check passed") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main())