diff --git a/crates/weft-appd/src/launch.rs b/crates/weft-appd/src/launch.rs index 8ab2a94..85b5bbc 100644 --- a/crates/weft-appd/src/launch.rs +++ b/crates/weft-appd/src/launch.rs @@ -6,7 +6,7 @@ use std::path::{Path, PathBuf}; -use weft_ipc_types::manifest::{MANIFEST_FILE, Manifest, entry_path}; +use weft_ipc_types::manifest::{MANIFEST_FILE, Manifest, ManifestError, entry_path}; use weft_ipc_types::package::{ImageFiles, is_valid_app_id}; use crate::grants::Refusal; @@ -26,23 +26,38 @@ pub(crate) struct LaunchPackage { pub(crate) image: Option, } -/// Resolves `app_id` in the package stores, in order. In each store a -/// verified image takes precedence over a directory install. When any image -/// file is present for the ID, the image must mount: a missing or damaged -/// image never falls back to a directory, which nothing verifies. +/// Resolves `app_id` in the package stores. pub(crate) fn resolve(app_id: &str) -> Result { + resolve_in(app_id, &crate::app_store_roots()) +} + +/// Resolves `app_id` in `stores`. A verified image in any store takes +/// precedence over a directory install in any store, so a writable user +/// directory cannot shadow a system image. When any image file is present +/// for the ID, the image must mount: a missing or damaged image never falls +/// back to a directory, which nothing verifies. +fn resolve_in(app_id: &str, stores: &[PathBuf]) -> Result { + use crate::mount::MountError; if !is_valid_app_id(app_id) { return Err(Refusal::new(400, "invalid app ID")); } - for store in crate::app_store_roots() { - let files = ImageFiles::in_store(&store, app_id); - if files.any_present() { - let image = crate::mount::mount(app_id, &files).map_err(|e| { + if let Some(files) = stores + .iter() + .map(|store| ImageFiles::in_store(store, app_id)) + .find(ImageFiles::any_present) + { + let image = crate::mount::mount(app_id, &files).map_err(|e| match e { + MountError::Invalid(e) => { + Refusal::new(403, format!("the verified image is invalid: {e}")) + } + MountError::Host(e) => { Refusal::new(500, format!("the verified image cannot be mounted: {e}")) - })?; - let root = image.root().to_path_buf(); - return from_root(app_id, root, Some(image)); - } + } + })?; + let root = image.root().to_path_buf(); + return from_root(app_id, root, Some(image)); + } + for store in stores { let dir = store.join(app_id); if std::fs::symlink_metadata(dir.join(MANIFEST_FILE)).is_ok() { return from_root(app_id, dir, None); @@ -55,7 +70,25 @@ pub(crate) fn resolve(app_id: &str) -> Result { } fn from_root(app_id: &str, root: PathBuf, image: Option) -> Result { - let manifest = Manifest::read(&root).map_err(|e| Refusal::new(403, e.to_string()))?; + // The entries are checked inside `root`, so the root and its manifest + // must be the directory and file they appear to be, not links to + // something else. + let is_dir = std::fs::symlink_metadata(&root).is_ok_and(|m| m.file_type().is_dir()); + let manifest_is_file = + std::fs::symlink_metadata(root.join(MANIFEST_FILE)).is_ok_and(|m| m.file_type().is_file()); + if !is_dir || !manifest_is_file { + return Err(Refusal::new( + 403, + format!( + "{} must be a directory holding a regular {MANIFEST_FILE}, not a link", + root.display() + ), + )); + } + let manifest = Manifest::read(&root).map_err(|e| match e { + ManifestError::Io(..) => Refusal::new(500, e.to_string()), + ManifestError::Parse(..) => Refusal::new(403, e.to_string()), + })?; if manifest.package.id != app_id { return Err(Refusal::new( 403, @@ -162,6 +195,60 @@ mod tests { assert!(package.image.is_none()); } + #[test] + fn an_image_in_a_later_store_is_not_shadowed_by_a_directory() { + let _env = crate::tests::env_lock().blocking_lock(); + crate::tests::use_test_runtime_dir(); + // A directory install in the user store, an incomplete image in the + // system store: the image is chosen, and refused. + let user = store("shadow_user", ID, "app.wasm"); + let system = std::env::temp_dir().join(format!( + "weft_appd_launch_shadow_system_{}", + std::process::id() + )); + let _ = std::fs::remove_dir_all(&system); + std::fs::create_dir_all(&system).unwrap(); + std::fs::write(ImageFiles::in_store(&system, ID).image, b"image").unwrap(); + let refused = refusal(resolve_in(ID, &[user.clone(), system.clone()])); + finish(&user); + let _ = std::fs::remove_dir_all(&system); + assert_eq!(refused.code, 403, "{}", refused.message); + assert!( + refused.message.contains("verified image"), + "{}", + refused.message + ); + } + + #[cfg(unix)] + #[test] + fn a_linked_package_root_or_manifest_is_refused() { + let _env = crate::tests::env_lock().blocking_lock(); + let store = store("linked", ID, "app.wasm"); + let elsewhere = + std::env::temp_dir().join(format!("weft_appd_launch_elsewhere_{}", std::process::id())); + let _ = std::fs::remove_dir_all(&elsewhere); + std::fs::rename(store.join(ID), &elsewhere).unwrap(); + std::os::unix::fs::symlink(&elsewhere, store.join(ID)).unwrap(); + let root_link = refusal(resolve(ID)); + + std::fs::remove_file(store.join(ID)).unwrap(); + std::fs::rename(&elsewhere, store.join(ID)).unwrap(); + let manifest = store.join(ID).join(MANIFEST_FILE); + std::fs::rename(&manifest, store.join("manifest.toml")).unwrap(); + std::os::unix::fs::symlink(store.join("manifest.toml"), &manifest).unwrap(); + let manifest_link = refusal(resolve(ID)); + finish(&store); + for refused in [root_link, manifest_link] { + assert_eq!(refused.code, 403, "{}", refused.message); + assert!( + refused.message.contains("not a link"), + "{}", + refused.message + ); + } + } + #[test] fn a_package_declaring_another_id_is_refused() { let _env = crate::tests::env_lock().blocking_lock(); @@ -236,8 +323,13 @@ mod tests { .map_or(0, Iterator::count); finish(&store); - for refused in [&partial, &failed, &absent, &malformed] { + for refused in [&partial, &malformed] { + assert_eq!(refused.code, 403, "{}", refused.message); + } + for refused in [&failed, &absent] { assert_eq!(refused.code, 500, "{}", refused.message); + } + for refused in [&partial, &failed, &absent, &malformed] { assert!( refused.message.contains("verified image"), "{}", diff --git a/crates/weft-appd/src/main.rs b/crates/weft-appd/src/main.rs index ed135c0..433b0e8 100644 --- a/crates/weft-appd/src/main.rs +++ b/crates/weft-appd/src/main.rs @@ -1249,6 +1249,93 @@ mod tests { assert!(!session_ipc_socket_path(session_id).unwrap().exists()); } + #[tokio::test(flavor = "current_thread")] + async fn children_receive_the_resolved_package_files() { + use std::os::unix::fs::PermissionsExt; + let _env = env_lock().lock().await; + use_test_runtime_dir(); + let dir = std::env::temp_dir().join(format!("weft_test_args_{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let app = dir.join("store/org.example.args"); + write_test_package(&app, "org.example.args", ""); + // Each child records its arguments, one per line, then reports ready. + let log = dir.join("args.log"); + let child = dir.join("child.sh"); + std::fs::write( + &child, + format!( + "#!/bin/sh\nprintf '%s\\n' \"$@\" -- >> '{}'\necho READY $WEFT_READY_TOKEN\nexec sleep 1\n", + log.display() + ), + ) + .unwrap(); + std::fs::set_permissions(&child, std::fs::Permissions::from_mode(0o755)).unwrap(); + let vars = [ + ("WEFT_RUNTIME_BIN", child.clone().into_os_string()), + ("WEFT_APP_SHELL_BIN", child.clone().into_os_string()), + ("WEFT_DISABLE_CGROUP", "1".into()), + ("WEFT_APP_STORE", dir.join("store").into_os_string()), + ]; + let prior: Vec<_> = vars + .iter() + .map(|(k, _)| (*k, std::env::var_os(k))) + .collect(); + for (key, value) in &vars { + // SAFETY: env_lock is held on a current_thread runtime. + unsafe { std::env::set_var(key, value) }; + } + + let registry = make_registry(); + let mut rx = registry.lock().await.subscribe(); + let ack = dispatch( + Request::LaunchApp { + app_id: "org.example.args".into(), + surface_id: 0, + }, + ®istry, + ) + .await; + let stopped = tokio::time::timeout(std::time::Duration::from_secs(10), async { + while !matches!( + rx.recv().await, + Ok(Response::AppState { + state: AppStateKind::Stopped, + .. + }) + ) {} + }) + .await; + let recorded = std::fs::read_to_string(&log).unwrap_or_default(); + + for (key, value) in prior { + // SAFETY: as above. + unsafe { + match value { + Some(v) => std::env::set_var(key, v), + None => std::env::remove_var(key), + } + } + } + let _ = std::fs::remove_dir_all(&dir); + assert!(matches!(ack, Response::LaunchAck { .. }), "{ack:?}"); + assert!(stopped.is_ok(), "session did not stop"); + let runs: Vec> = recorded + .split("--\n") + .filter(|run| !run.is_empty()) + .map(|run| run.lines().collect()) + .collect(); + let after = |run: &[&str], flag: &str| { + run.iter() + .position(|arg| *arg == flag) + .and_then(|i| run.get(i + 1).map(|value| value.to_string())) + }; + let module = app.join("app.wasm").display().to_string(); + let ui = app.join("ui/index.html").display().to_string(); + assert_eq!(runs.len(), 2, "{recorded}"); + assert_eq!(after(&runs[0], "--module"), Some(module), "{recorded}"); + assert_eq!(after(&runs[1], "--ui"), Some(ui), "{recorded}"); + } + #[tokio::test(flavor = "current_thread")] async fn supervisor_transitions_through_ready_to_stopped() { use std::os::unix::fs::PermissionsExt; diff --git a/crates/weft-appd/src/mount.rs b/crates/weft-appd/src/mount.rs index 289274d..271d552 100644 --- a/crates/weft-appd/src/mount.rs +++ b/crates/weft-appd/src/mount.rs @@ -49,33 +49,48 @@ impl Drop for Mount { } } +/// Why an image was not mounted. +pub(crate) enum MountError { + /// The image files are incomplete or malformed. + Invalid(String), + /// The host could not mount a well-formed image. + Host(String), +} + /// Mounts the verified image `files` of `app_id`. Every failure is returned: /// the caller must not fall back to another copy of the package. -pub(crate) fn mount(app_id: &str, files: &ImageFiles) -> Result { - let helper = mount_helper_bin().ok_or("weft-mount-helper is not installed")?; +pub(crate) fn mount(app_id: &str, files: &ImageFiles) -> Result { + use MountError::{Host, Invalid}; for path in [&files.image, &files.hash_tree, &files.root_hash] { let is_file = std::fs::symlink_metadata(path).is_ok_and(|m| m.file_type().is_file()); if !is_file { - return Err(format!( + return Err(Invalid(format!( "{} is missing or not a regular file", path.display() - )); + ))); } } let root_hash = std::fs::read_to_string(&files.root_hash) - .map_err(|e| format!("cannot read {}: {e}", files.root_hash.display()))?; + .map_err(|e| Host(format!("cannot read {}: {e}", files.root_hash.display())))?; let root_hash = root_hash.trim(); if !is_root_hash(root_hash) { - return Err(format!("{} holds no root hash", files.root_hash.display())); + return Err(Invalid(format!( + "{} holds no root hash", + files.root_hash.display() + ))); } + let helper = mount_helper_bin().ok_or(Host("weft-mount-helper is not installed".into()))?; - let runtime_dir = std::env::var_os("XDG_RUNTIME_DIR").ok_or("XDG_RUNTIME_DIR is not set")?; + let runtime_dir = + std::env::var_os("XDG_RUNTIME_DIR").ok_or(Host("XDG_RUNTIME_DIR is not set".into()))?; let base = PathBuf::from(runtime_dir).join("weft/mnt"); - crate::private_dir(&base).map_err(|e| format!("cannot create {}: {e}", base.display()))?; - let name = crate::runtime::random_token().map_err(|e| format!("no mountpoint name: {e}"))?; + crate::private_dir(&base) + .map_err(|e| Host(format!("cannot create {}: {e}", base.display())))?; + let name = + crate::runtime::random_token().map_err(|e| Host(format!("no mountpoint name: {e}")))?; let mountpoint = base.join(name); std::fs::create_dir(&mountpoint) - .map_err(|e| format!("cannot create {}: {e}", mountpoint.display()))?; + .map_err(|e| Host(format!("cannot create {}: {e}", mountpoint.display())))?; let status = std::process::Command::new(&helper) .arg("mount") @@ -91,10 +106,10 @@ pub(crate) fn mount(app_id: &str, files: &ImageFiles) -> Result { } outcome => { let _ = std::fs::remove_dir(&mountpoint); - Err(match outcome { + Err(Host(match outcome { Ok(status) => format!("weft-mount-helper failed: {status}"), Err(e) => format!("cannot run {}: {e}", helper.display()), - }) + })) } } } diff --git a/docs/architecture.md b/docs/architecture.md index 2252531..ee92a31 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -112,12 +112,12 @@ Package store roots (in priority order): ### Package resolution -`weft-appd` resolves a launch once, in the first store root that holds the app: +`weft-appd` resolves a launch once. A verified image in any store root takes precedence over a directory install in any root, so a user's directory cannot shadow a system image; otherwise the first root with a directory install is used: -- **Verified image:** `/.app.img` with its dm-verity hash tree `.app.hash` and root hash `.app.roothash`, the names `weft-pack build-image` and `build-verity` produce. When any of the three exists, the image must mount through `weft-mount-helper`; a missing companion, a malformed root hash, a missing helper or a failed mount refuses the launch, and appd never falls back to a directory install. The mount belongs to the session and is released when the session stops. +- **Verified image:** `/.app.img` with its dm-verity hash tree `.app.hash` and root hash `.app.roothash`, the names `weft-pack build-image` and `build-verity` produce. When any of the three exists, the image must mount through `weft-mount-helper`; a missing companion, a malformed root hash, a missing helper or a failed mount refuses the launch, and appd never falls back to a directory install. The root hash is read from the store next to the image and is not yet authenticated, so dm-verity detects corruption but not a store whose image, hash tree and root hash were replaced together. The mount belongs to the session and is released when the session stops. - **Directory install:** `//wapp.toml`. -The manifest in the selected package root must declare the requested ID. `[runtime].module` and `[ui].entry` must be relative paths of plain components, without symbolic links, naming regular files inside that root. The component, the UI document and the capabilities all come from that one manifest. A refused launch reports 400 (invalid ID), 404 (not installed), 403 (invalid package) or 500 (the image cannot be used). +The package root must be a directory and its manifest a regular file, neither a symbolic link, and the manifest must declare the requested ID. `[runtime].module` and `[ui].entry` must be relative paths of plain components, without symbolic links, naming regular files inside that root. The component, the UI document and the capabilities all come from that one manifest. A refused launch reports 400 (invalid ID), 404 (not installed), 403 (invalid package, image or image metadata) or 500 (the host cannot read the package or mount the image). A directory install can still be changed by its owner while a session runs, and nothing verifies its content at launch.