diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 0c131fe..39289da 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -78,6 +78,28 @@ jobs: -p weft-servo-shell -p weft-app-shell + # weft-runtime with its Wasm engine and fetch support, exercised on a real + # component under each kind of capability grant. + runtime-grants: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: dtolnay/rust-toolchain@stable + with: + toolchain: 1.93.0 + components: clippy + targets: wasm32-wasip2 + - name: cargo clippy (weft-runtime with wasmtime-runtime and net-fetch) + run: > + cargo clippy + -p weft-runtime + --features wasmtime-runtime,net-fetch + --all-targets -- -D warnings + - name: cargo build (weft-runtime with wasmtime-runtime and net-fetch) + run: cargo build -p weft-runtime --features wasmtime-runtime,net-fetch + - name: grants check + run: python3 -B tests/runtime/check_grants.py + # Type-check the servo-embed feature gate. # Full Servo compilation (30-60 min) is not run in CI; this job checks # that the feature-gated code at least type-checks against the declared deps. diff --git a/README.md b/README.md index 1371951..95d9671 100644 --- a/README.md +++ b/README.md @@ -75,10 +75,11 @@ See `docs/building.md` for full instructions including Wasm component builds, Ni ## CI -Three jobs on every push and pull request: +Jobs on every push and pull request: - `cross-platform` — fmt, clippy, tests on Ubuntu and Windows - `linux-only` — clippy and tests for compositor and shell crates +- `runtime-grants` — clippy for `weft-runtime` with its Wasm engine and fetch, and `tests/runtime/check_grants.py` - `servo-embed-linux` — `cargo check --features servo-embed` for both servo crates ## Security diff --git a/crates/weft-appd/src/grants.rs b/crates/weft-appd/src/grants.rs index 7dbd6a0..c9cdcb3 100644 --- a/crates/weft-appd/src/grants.rs +++ b/crates/weft-appd/src/grants.rs @@ -35,6 +35,25 @@ pub(crate) struct SessionGrants { pub imports: Vec, } +/// Why a launch is refused, with the error code reported to the client: +/// 400 for a malformed app ID, 404 for a package that is not installed, 403 +/// for a package this host will not run as declared and 500 for a host +/// fault. +#[derive(Debug, PartialEq, Eq)] +pub(crate) struct Refusal { + pub code: u32, + pub message: String, +} + +impl Refusal { + fn new(code: u32, message: impl Into) -> Self { + Self { + code, + message: message.into(), + } + } +} + /// Where the host resources behind filesystem capabilities live. pub(crate) struct HostDirs { /// Root under which each app's private data directory is created. @@ -44,12 +63,15 @@ pub(crate) struct HostDirs { } impl HostDirs { - pub fn from_env() -> Result { + pub fn from_env() -> Result { let home = std::env::var_os("HOME") .map(PathBuf::from) - .ok_or("HOME is not set")?; + .filter(|home| home.is_absolute()) + .ok_or_else(|| Refusal::new(500, "HOME is not set to an absolute path"))?; + // The XDG base directory specification ignores relative values. let config = std::env::var_os("XDG_CONFIG_HOME") .map(PathBuf::from) + .filter(|dir| dir.is_absolute()) .unwrap_or_else(|| home.join(".config")); Ok(Self { app_data_root: home.join(".local/share/weft/apps"), @@ -59,7 +81,7 @@ impl HostDirs { } /// Reads the package manifest of `app_id` and derives its grants. -pub(crate) fn for_app(app_id: &str) -> Result { +pub(crate) fn for_app(app_id: &str) -> Result { #[derive(serde::Deserialize)] struct Package { capabilities: Option>, @@ -69,61 +91,98 @@ pub(crate) fn for_app(app_id: &str) -> Result { package: Package, } + if !weft_ipc_types::package::is_valid_app_id(app_id) { + return Err(Refusal::new(400, "invalid app ID")); + } 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"))?; + .ok_or_else(|| Refusal::new(404, 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()))?; + .map_err(|e| Refusal::new(500, format!("cannot read {}: {e}", manifest.display())))?; + let manifest: Manifest = toml::from_str(&text) + .map_err(|e| Refusal::new(403, format!("invalid {}: {e}", manifest.display())))?; let declared = manifest.package.capabilities.unwrap_or_default(); - derive(app_id, &declared, &HostDirs::from_env()?) + 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. +/// Derives grants for the declared capabilities. Every capability is +/// checked before host directories are resolved or the app's data +/// directory is created, so a refused launch leaves nothing behind. pub(crate) fn derive( app_id: &str, declared: &[String], - host: &HostDirs, -) -> Result { - let mut grants = SessionGrants::default(); + host_dirs: impl FnOnce() -> Result, +) -> Result { + let mut capabilities = Vec::new(); 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") + let capability: Capability = + text.parse() + .map_err(|e: weft_ipc_types::capability::UnknownCapability| { + Refusal::new(403, e.to_string()) })?; - grant_dir(&mut grants, dir, "/xdg/documents", access); + if matches!(capability, Capability::GpuCompute | Capability::GpuRender) { + return Err(Refusal::new( + 403, + format!("{capability} is not supported by this host"), + )); + } + capabilities.push(capability); + } + + let mut grants = SessionGrants::default(); + let needs_dirs = capabilities + .iter() + .any(|c| matches!(c, Capability::AppData(_) | Capability::Documents(_))); + let host = if needs_dirs { Some(host_dirs()?) } else { None }; + for capability in capabilities { + match (&capability, &host) { + (Capability::AppData(access), Some(host)) => { + let dir = host.app_data_root.join(app_id).join("data"); + grant_dir(&mut grants, dir, "/data", *access)?; } - Capability::Fetch(_) - | Capability::Notifications - | Capability::ClipboardRead - | Capability::ClipboardWrite => { + (Capability::Documents(access), Some(host)) => { + let dir = host.documents.clone().ok_or_else(|| { + Refusal::new( + 403, + format!("{capability} requested, but no documents directory is configured"), + ) + })?; + grant_dir(&mut grants, dir, "/xdg/documents", *access)?; + } + _ => { if !grants.imports.contains(&capability) { grants.imports.push(capability); } } - Capability::GpuCompute | Capability::GpuRender => { - return Err(format!("{capability} is not supported by this host")); - } + } + } + for dir in &grants.dirs { + if dir.guest == "/data" { + std::fs::create_dir_all(&dir.host).map_err(|e| { + Refusal::new(500, format!("cannot create {}: {e}", dir.host.display())) + })?; } } 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) { +/// wider one. The host path must survive the `--preopen HOST::GUEST::MODE` +/// encoding unchanged: it must be UTF-8 and must not contain `::`. +fn grant_dir( + grants: &mut SessionGrants, + host: PathBuf, + guest: &'static str, + access: Access, +) -> Result<(), Refusal> { + if host.to_str().is_none_or(|path| path.contains("::")) { + return Err(Refusal::new( + 403, + format!("{} cannot be granted to a session", host.display()), + )); + } match grants.dirs.iter_mut().find(|dir| dir.guest == guest) { Some(existing) => { if access == Access::ReadWrite { @@ -136,21 +195,29 @@ fn grant_dir(grants: &mut SessionGrants, host: PathBuf, guest: &'static str, acc access, }), } + Ok(()) } /// 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. +/// to the home directory) or does not exist. Values are `"$HOME/path"` or +/// `"/absolute/path"`; the last assignment wins, as when the file is sourced +/// by a shell. Values with escapes are not interpreted and are ignored. 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 value = text + .lines() + .filter_map(|line| line.trim().strip_prefix("XDG_DOCUMENTS_DIR=")) + .next_back()? + .trim(); + let value = value.strip_prefix('"')?.strip_suffix('"')?; + if value.contains('\\') || value.contains('"') { + return None; + } let dir = match value.strip_prefix("$HOME") { - Some(rest) => home.join(rest.trim_start_matches('/')), - None => PathBuf::from(&value), + Some("") => home.to_path_buf(), + Some(rest) => home.join(rest.strip_prefix('/')?), + None => PathBuf::from(value), }; (dir.is_absolute() && dir != home && dir.is_dir()).then_some(dir) } @@ -166,22 +233,36 @@ mod tests { dir } - fn host(root: &Path, documents: Option) -> HostDirs { - HostDirs { - app_data_root: root.join("apps"), - documents, + fn host(root: &Path, documents: Option) -> impl FnOnce() -> Result { + let root = root.to_path_buf(); + move || { + Ok(HostDirs { + app_data_root: root.join("apps"), + documents, + }) } } + fn no_host() -> Result { + Err(Refusal::new(500, "HOME is not set to an absolute path")) + } + 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(); + fn no_capabilities_grant_nothing_and_need_no_home() { + let grants = derive("org.example.app", &[], no_host).unwrap(); assert_eq!(grants, SessionGrants::default()); + let grants = derive("org.example.app", &caps(&["sys:notifications"]), no_host).unwrap(); + assert_eq!(grants.imports, [Capability::Notifications]); + assert_eq!( + derive("org.example.app", &caps(&["fs:rw:app-data"]), no_host) + .unwrap_err() + .code, + 500 + ); } #[test] @@ -190,7 +271,7 @@ mod tests { let read = derive( "org.example.app", &caps(&["fs:read:app-data"]), - &host(&root, None), + host(&root, None), ) .unwrap(); assert_eq!(read.dirs[0].access, Access::Read); @@ -200,7 +281,7 @@ mod tests { let both = derive( "org.example.app", &caps(&["fs:read:app-data", "fs:rw:app-data"]), - &host(&root, None), + host(&root, None), ) .unwrap(); assert_eq!(both.dirs.len(), 1); @@ -217,7 +298,7 @@ mod tests { "net:fetch:api.example.org", "sys:notifications", ]), - &host(&root, None), + host(&root, None), ) .unwrap(); let listed: Vec = grants.imports.iter().map(|c| c.to_string()).collect(); @@ -226,14 +307,34 @@ mod tests { } #[test] - fn unknown_unsupported_and_unsatisfiable_capabilities_fail() { + fn refused_launches_create_nothing() { 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" - ); + for declared in [ + &["sys:everything"][..], + &["hw:gpu:compute"], + &["fs:read:xdg-documents"], + &["fs:rw:app-data", "hw:gpu:render"], + &["fs:rw:app-data", "fs:read:xdg-documents"], + ] { + let refusal = + derive("org.example.app", &caps(declared), host(&root, None)).unwrap_err(); + assert_eq!(refusal.code, 403, "{declared:?}"); } + assert!(!root.join("apps").exists()); + } + + #[test] + fn paths_that_cannot_be_encoded_are_refused() { + let root = temp("encode"); + let odd = root.join("a::b"); + std::fs::create_dir_all(&odd).unwrap(); + let refusal = derive( + "org.example.app", + &caps(&["fs:read:xdg-documents"]), + host(&root, Some(odd)), + ) + .unwrap_err(); + assert_eq!(refusal.code, 403); } #[test] @@ -241,34 +342,37 @@ mod tests { let home = temp("home"); let config = home.join(".config"); std::fs::create_dir_all(home.join("Docs")).unwrap(); + std::fs::create_dir_all(home.join("Later")).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(); + let write = |text: &str| std::fs::write(config.join("user-dirs.dirs"), text).unwrap(); + write("# comment\nXDG_DOCUMENTS_DIR=\"$HOME/Docs\"\n"); + assert_eq!(documents_dir(&home, &config), Some(home.join("Docs"))); + write("XDG_DOCUMENTS_DIR=\"$HOME/Docs\"\nXDG_DOCUMENTS_DIR=\"$HOME/Later\"\n"); + assert_eq!(documents_dir(&home, &config), Some(home.join("Later"))); + let absolute = format!("XDG_DOCUMENTS_DIR=\"{}\"\n", home.join("Docs").display()); + write(&absolute); 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"), + // Disabled, missing, relative, escaped and malformed values. + for text in [ "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\"\n", "XDG_DOCUMENTS_DIR=\"$HOME/Missing\"\n", - ) - .unwrap(); - assert_eq!(documents_dir(&home, &config), None); + "XDG_DOCUMENTS_DIR=\"$HOMEDocs\"\n", + "XDG_DOCUMENTS_DIR=\"Docs\"\n", + "XDG_DOCUMENTS_DIR=\"$HOME/Do\\\"cs\"\n", + "XDG_DOCUMENTS_DIR=$HOME/Docs\n", + ] { + write(text); + assert_eq!(documents_dir(&home, &config), None, "{text:?}"); + } let grants = derive( "org.example.app", &caps(&["fs:rw:xdg-documents"]), - &host(&home, Some(home.join("Docs"))), + host(&home, Some(home.join("Docs"))), ) .unwrap(); assert_eq!(grants.dirs[0].guest, "/xdg/documents"); diff --git a/crates/weft-appd/src/main.rs b/crates/weft-appd/src/main.rs index b02d642..8857ada 100644 --- a/crates/weft-appd/src/main.rs +++ b/crates/weft-appd/src/main.rs @@ -427,19 +427,25 @@ pub(crate) async fn dispatch(req: Request, registry: &Registry) -> Response { } => { // 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}"), - }; - } - } + let grants = if !weft_ipc_types::package::is_valid_app_id(&app_id) { + Err(grants::Refusal { + code: 400, + message: "invalid app ID".to_owned(), + }) + } else if std::env::var("WEFT_RUNTIME_BIN").is_ok() { + grants::for_app(&app_id) } else { - grants::SessionGrants::default() + Ok(grants::SessionGrants::default()) + }; + let grants = match grants { + Ok(grants) => grants, + Err(refusal) => { + tracing::warn!(%app_id, error = %refusal.message, "launch refused"); + return Response::Error { + code: refusal.code, + message: format!("{app_id}: {}", refusal.message), + }; + } }; let session_id = registry.lock().await.launch(&app_id); tracing::info!(session_id, %app_id, "launched"); @@ -628,7 +634,7 @@ mod tests { static ENV_LOCK: std::sync::OnceLock> = std::sync::OnceLock::new(); - fn env_lock() -> &'static tokio::sync::Mutex<()> { + pub(crate) fn env_lock() -> &'static tokio::sync::Mutex<()> { ENV_LOCK.get_or_init(|| tokio::sync::Mutex::new(())) } @@ -789,7 +795,7 @@ mod tests { let reg = make_registry(); let ack = dispatch( Request::LaunchApp { - app_id: "app".into(), + app_id: "com.test.app".into(), surface_id: 0, }, ®, diff --git a/crates/weft-appd/src/mount.rs b/crates/weft-appd/src/mount.rs index 6d978b8..30ebe3f 100644 --- a/crates/weft-appd/src/mount.rs +++ b/crates/weft-appd/src/mount.rs @@ -108,6 +108,7 @@ mod tests { #[test] fn find_image_returns_none_when_absent() { + let _env = crate::tests::env_lock().blocking_lock(); unsafe { std::env::set_var("WEFT_APP_STORE", "/tmp/nonexistent_weft_store_xyz") }; let result = find_image("com.example.missing"); unsafe { std::env::remove_var("WEFT_APP_STORE") }; diff --git a/crates/weft-ipc-types/src/capability.rs b/crates/weft-ipc-types/src/capability.rs index 8a0a31e..14f3bb4 100644 --- a/crates/weft-ipc-types/src/capability.rs +++ b/crates/weft-ipc-types/src/capability.rs @@ -101,11 +101,22 @@ impl fmt::Display for Capability { } } -/// A DNS host name in canonical lowercase form: dot-separated labels of -/// 1–63 letters, digits and inner hyphens, at most 253 characters. +/// A host in the canonical form URL parsing produces, so that a grant can +/// be compared with a request's host as a string: a lowercase DNS name of +/// 1–63 character labels of letters, digits and inner hyphens (at most 253 +/// characters) whose last label is not numeric, or an IPv4 address in +/// dotted-decimal form without leading zeros. IPv6 literals are not +/// supported. fn is_host_name(host: &str) -> bool { + let labels: Vec<&str> = host.split('.').collect(); + if labels + .last() + .is_some_and(|last| !last.is_empty() && last.bytes().all(|b| b.is_ascii_digit())) + { + return is_ipv4(&labels); + } host.len() <= 253 - && host.split('.').all(|label| { + && labels.iter().all(|label| { !label.is_empty() && label.len() <= 63 && !label.starts_with('-') @@ -116,6 +127,17 @@ fn is_host_name(host: &str) -> bool { }) } +fn is_ipv4(labels: &[&str]) -> bool { + labels.len() == 4 + && labels.iter().all(|octet| { + !octet.is_empty() + && octet.len() <= 3 + && (octet.len() == 1 || !octet.starts_with('0')) + && octet.bytes().all(|b| b.is_ascii_digit()) + && octet.parse::().is_ok_and(|n| n <= 255) + }) +} + #[cfg(test)] mod tests { use super::*; @@ -129,6 +151,8 @@ mod tests { "fs:rw:xdg-documents", "net:fetch:*", "net:fetch:api.example.org", + "net:fetch:127.0.0.1", + "net:fetch:a1.example", "sys:notifications", "sys:clipboard:read", "sys:clipboard:write", @@ -153,6 +177,11 @@ mod tests { "net:fetch:*.example.org", "net:fetch:-bad.example", "net:fetch:a..b", + "net:fetch:0177.0.0.1", + "net:fetch:999.1.1.1", + "net:fetch:1.2.3", + "net:fetch:example.123", + "net:fetch:[::1]", "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 7753053..f191540 100644 --- a/crates/weft-ipc-types/src/lib.rs +++ b/crates/weft-ipc-types/src/lib.rs @@ -1,4 +1,5 @@ pub mod capability; +pub mod package; use serde::{Deserialize, Serialize}; diff --git a/crates/weft-ipc-types/src/package.rs b/crates/weft-ipc-types/src/package.rs new file mode 100644 index 0000000..037eb64 --- /dev/null +++ b/crates/weft-ipc-types/src/package.rs @@ -0,0 +1,37 @@ +//! Package identity rules shared by the packaging tool and the supervisor. + +/// Whether `id` is a valid application ID: at least three dot-separated +/// segments, each starting with a lowercase ASCII letter and containing only +/// lowercase ASCII letters and digits. A valid ID is safe to use as a single +/// path component. +pub fn is_valid_app_id(id: &str) -> bool { + let parts: Vec<&str> = id.split('.').collect(); + parts.len() >= 3 + && parts.iter().all(|p| { + p.chars().next().is_some_and(|c| c.is_ascii_lowercase()) + && p.chars() + .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit()) + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn app_ids() { + assert!(is_valid_app_id("org.weft.demo")); + assert!(is_valid_app_id("com.example2.app3")); + for bad in [ + "", + "org.weft", + "Org.weft.demo", + "org..demo", + "../x.y.z", + "org.weft.a::b", + "org.1weft.demo", + ] { + assert!(!is_valid_app_id(bad), "{bad:?}"); + } + } +} diff --git a/crates/weft-pack/src/main.rs b/crates/weft-pack/src/main.rs index 62a1c58..83637e7 100644 --- a/crates/weft-pack/src/main.rs +++ b/crates/weft-pack/src/main.rs @@ -155,7 +155,7 @@ fn check_package(dir: &Path) -> anyhow::Result { }; if let Some(ref m) = manifest { - if !is_valid_app_id(&m.package.id) { + if !weft_ipc_types::package::is_valid_app_id(&m.package.id) { errors.push(format!( "package.id '{}' does not match required pattern", m.package.id @@ -229,22 +229,6 @@ fn print_info(m: &Manifest) { } } -fn is_valid_app_id(id: &str) -> bool { - let parts: Vec<&str> = id.split('.').collect(); - if parts.len() < 3 { - return false; - } - parts.iter().all(|p| { - !p.is_empty() - && p.chars() - .next() - .map(|c| c.is_ascii_lowercase()) - .unwrap_or(false) - && p.chars() - .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit()) - }) -} - fn is_wasm_module(path: &Path) -> bool { const MAGIC: [u8; 4] = [0x00, 0x61, 0x73, 0x6D]; let mut buf = [0u8; 4]; @@ -327,7 +311,7 @@ fn uninstall_package(app_id: &str) -> anyhow::Result<()> { } fn uninstall_package_from(app_id: &str, store_root: &Path) -> anyhow::Result<()> { - if !is_valid_app_id(app_id) { + if !weft_ipc_types::package::is_valid_app_id(app_id) { anyhow::bail!("'{}' is not a valid app ID", app_id); } let target = store_root.join(app_id); @@ -611,19 +595,33 @@ mod tests { #[test] fn app_id_valid() { - assert!(is_valid_app_id("com.example.notes")); - assert!(is_valid_app_id("org.weft.calculator")); - assert!(is_valid_app_id("io.github.username.app")); + assert!(weft_ipc_types::package::is_valid_app_id( + "com.example.notes" + )); + assert!(weft_ipc_types::package::is_valid_app_id( + "org.weft.calculator" + )); + assert!(weft_ipc_types::package::is_valid_app_id( + "io.github.username.app" + )); } #[test] fn app_id_invalid() { - assert!(!is_valid_app_id("com.example")); - assert!(!is_valid_app_id("Com.example.notes")); - assert!(!is_valid_app_id("com.example.notes-app")); - assert!(!is_valid_app_id("com..example.notes")); - assert!(!is_valid_app_id("")); - assert!(!is_valid_app_id("com.Example.notes")); + assert!(!weft_ipc_types::package::is_valid_app_id("com.example")); + assert!(!weft_ipc_types::package::is_valid_app_id( + "Com.example.notes" + )); + assert!(!weft_ipc_types::package::is_valid_app_id( + "com.example.notes-app" + )); + assert!(!weft_ipc_types::package::is_valid_app_id( + "com..example.notes" + )); + assert!(!weft_ipc_types::package::is_valid_app_id("")); + assert!(!weft_ipc_types::package::is_valid_app_id( + "com.Example.notes" + )); } #[test] diff --git a/crates/weft-runtime/src/grants.rs b/crates/weft-runtime/src/grants.rs index c296e5e..ab60c2d 100644 --- a/crates/weft-runtime/src/grants.rs +++ b/crates/weft-runtime/src/grants.rs @@ -93,8 +93,10 @@ impl Preopen { let (rest, mode) = spec .rsplit_once("::") .context("--preopen expects HOST::GUEST::ro|rw")?; + // Guest paths are fixed names without `::`; splitting from the right + // keeps a host path containing `::` whole. let (host, guest) = rest - .split_once("::") + .rsplit_once("::") .context("--preopen expects HOST::GUEST::ro|rw")?; let access = match mode { "ro" => Access::Read, @@ -166,6 +168,7 @@ mod tests { Preopen::parse("/a::/b::rw").unwrap().access, Access::ReadWrite ); + assert_eq!(Preopen::parse("/a::/b::/data::ro").unwrap().host, "/a::/b"); 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 63e31f1..934db44 100644 --- a/crates/weft-runtime/src/main.rs +++ b/crates/weft-runtime/src/main.rs @@ -385,6 +385,21 @@ struct FetchResponse { #[cfg(feature = "wasmtime-runtime")] type FetchResult = Result; +/// Request headers a component may not set. +#[cfg(all(feature = "wasmtime-runtime", feature = "net-fetch"))] +const FORBIDDEN_FETCH_HEADERS: &[&str] = &[ + "host", + "content-length", + "transfer-encoding", + "connection", + "keep-alive", + "proxy-authorization", + "proxy-connection", + "te", + "trailer", + "upgrade", +]; + /// Longest response body returned to a component. #[cfg(all(feature = "wasmtime-runtime", feature = "net-fetch"))] const MAX_FETCH_RESPONSE: u64 = 16 * 1024 * 1024; @@ -410,6 +425,25 @@ fn host_fetch( } let host = parsed.host_str().ok_or("URL has no host")?; grants.fetch_host(host)?; + // The method is written into the request line as given, so only known + // methods are accepted. + if !matches!( + method, + "GET" | "HEAD" | "POST" | "PUT" | "PATCH" | "DELETE" | "OPTIONS" + ) { + return Err(format!("unsupported HTTP method '{method}'")); + } + // The destination and message framing belong to the runtime: a component + // must not redirect a granted request to another host through `Host` or + // change how the body is delimited. + for (name, _) in headers { + if FORBIDDEN_FETCH_HEADERS + .iter() + .any(|forbidden| name.eq_ignore_ascii_case(forbidden)) + { + return Err(format!("header '{name}' is set by the runtime")); + } + } let agent = ureq::AgentBuilder::new() .redirects(0) .timeout_connect(Duration::from_secs(10)) diff --git a/crates/weft-runtime/wit/weft-app.wit b/crates/weft-runtime/wit/weft-app.wit index 818cfcb..405785f 100644 --- a/crates/weft-runtime/wit/weft-app.wit +++ b/crates/weft-runtime/wit/weft-app.wit @@ -21,8 +21,8 @@ interface ipc { recv: func() -> option; } -/// Host interface for outbound HTTP requests. Requires the net:fetch -/// capability to be declared in wapp.toml. +/// Host interface for outbound HTTP requests. Requires a net:fetch: +/// or net:fetch:* capability in wapp.toml covering the request's host. interface fetch { record response { status: u16, diff --git a/docs/architecture.md b/docs/architecture.md index f1bce47..8c386d0 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 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. +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. Paths are checked lexically, so `..` is blocked but symbolic links are followed. Accepts JSON-lines requests over a Unix socket. Components cannot currently reach that socket, because the runtime grants them no socket access. ### weft-mount-helper @@ -71,24 +71,26 @@ Every WebSocket connection must complete the upgrade and send `HELLO` as its fir 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: +`weft-appd` derives grants once, before a session exists. `LAUNCH_APP` is answered with an error and nothing starts when the app ID is malformed (code 400), the package is not installed (404), a declared capability is unknown, unsupported on this host or cannot be satisfied (403), or the host cannot provide the resources (500, for example without `HOME`). All capabilities are checked before the app's data directory is created. Without `WEFT_RUNTIME_BIN`, appd starts no processes and derives no grants. 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. +Each capability-controlled host import (fetch, notifications, clipboard) checks its grant on every call and returns an error naming the missing capability when it is not granted. `notify` and `ipc` need no capability. | Capability | Effect | |---|---| | `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 that exact host (a lowercase DNS name or dotted IPv4 address) over HTTP or HTTPS, on any port | | `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. +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. `tests/runtime/check_grants.py` runs the real runtime on a probe component (`tests/components/grants-probe`) under each kind of grant. diff --git a/docs/building.md b/docs/building.md index 0e97b0f..ef03486 100644 --- a/docs/building.md +++ b/docs/building.md @@ -122,8 +122,9 @@ See `infra/nixos/weft-packages.nix` for the package derivations. Its `outputHash ## CI -Three jobs run on every push to `main` and on pull requests: +Jobs run on every push to `main` and on pull requests: - `cross-platform` — fmt, clippy, tests on Ubuntu and Windows (excludes Wayland crates) - `linux-only` — clippy and tests for `weft-compositor`, `weft-servo-shell`, `weft-app-shell` +- `runtime-grants` — clippy and a build of `weft-runtime` with `wasmtime-runtime,net-fetch`, then `tests/runtime/check_grants.py`, which runs a probe component under each kind of capability grant - `servo-embed-linux` — `cargo check --features servo-embed` for servo-shell and app-shell diff --git a/tests/components/grants-probe/src/main.rs b/tests/components/grants-probe/src/main.rs index 0976240..ba18195 100644 --- a/tests/components/grants-probe/src/main.rs +++ b/tests/components/grants-probe/src/main.rs @@ -4,7 +4,8 @@ //! //! Fetch targets are read from `/probe/targets.txt` (` ` per //! line), a directory the harness preopens read-only next to the grants -//! under test. +//! under test. The target named `fetch-ok` is also requested with a forged +//! `Host` header and with a method carrying a second request line. wit_bindgen::generate!({ path: "wit", @@ -24,12 +25,33 @@ fn report(name: &str, result: Result