From 3186e524ab58a5b47653398a15fda771e0d025de Mon Sep 17 00:00:00 2001 From: Marco Allegretti Date: Fri, 9 Oct 2026 19:10:15 +0000 Subject: [PATCH 1/3] feat: grant an app only the capabilities the user approved Every capability a package declared was granted at launch, so a signed package received all the permissions it asked for. Blueprint 5.2 rules that out. A package now gets only the capabilities the user approved. weft-pack install --approve approves those the installed package declares, and weft-pack approve approves those of the installed app later. Without approval, install lists what still needs it. The approval is recorded in $XDG_DATA_HOME/weft/approvals/. weft-appd refuses to launch an app declaring a capability the record does not hold, with 403 and the capabilities named, after refusing unknown or unsupported ones as before. An update that declares a new capability needs approval again, and uninstalling forgets the approval. Private app data is a minimal execution resource and needs no approval, so Notes and the existing fixtures are unchanged. Unit tests cover the approval record, install and approve, an update adding a capability, uninstall, and appd refusing and then launching. tests/frame/check_update.py launches a real app declaring notifications: it is refused until weft-pack approve, then runs. --- crates/weft-appd/src/main.rs | 87 +++++++++++++ crates/weft-ipc-types/src/approval.rs | 144 +++++++++++++++++++++ crates/weft-ipc-types/src/lib.rs | 1 + crates/weft-pack/src/main.rs | 175 ++++++++++++++++++++++++-- docs/architecture.md | 2 +- docs/security.md | 2 +- tests/frame/check_update.py | 15 ++- 7 files changed, 413 insertions(+), 13 deletions(-) create mode 100644 crates/weft-ipc-types/src/approval.rs diff --git a/crates/weft-appd/src/main.rs b/crates/weft-appd/src/main.rs index bf588fd..4516ac9 100644 --- a/crates/weft-appd/src/main.rs +++ b/crates/weft-appd/src/main.rs @@ -578,6 +578,29 @@ pub(crate) async fn dispatch(req: Request, registry: &Registry) -> Response { } } +/// Refuses a launch while the app declares a capability the user has not +/// approved; a signature, however trusted, approves nothing. +fn check_approval(app_id: &str, declared: &[String]) -> Result<(), grants::Refusal> { + use weft_ipc_types::approval::{approval_path, read_approved, unapproved}; + let data_home = weft_ipc_types::package::data_home().ok_or_else(|| { + grants::Refusal::new(500, "cannot locate the data home holding app approvals") + })?; + let record = approval_path(&data_home, app_id); + let approved = read_approved(&record) + .map_err(|e| grants::Refusal::new(500, format!("cannot read {}: {e}", record.display())))?; + let pending = unapproved(declared, &approved); + if pending.is_empty() { + return Ok(()); + } + Err(grants::Refusal::new( + 403, + format!( + "{app_id} needs approval for {}; approve it with weft-pack approve {app_id}", + pending.join(", ") + ), + )) +} + /// Resolves the package of `app_id` and derives its grants. Resolution may /// mount an image, so it runs off the async workers; a refused launch /// releases the mount the same way. @@ -586,6 +609,7 @@ async fn resolve_launch( ) -> Result<(launch::LaunchPackage, grants::SessionGrants), grants::Refusal> { tokio::task::spawn_blocking(move || { let package = launch::resolve(&app_id)?; + check_approval(&app_id, &package.capabilities)?; let grants = grants::derive(&app_id, &package.capabilities, grants::HostDirs::from_env)?; tracing::info!( %app_id, @@ -829,6 +853,69 @@ mod tests { assert!(result.is_err()); } + #[tokio::test] + async fn a_capability_launches_only_once_approved() { + let _env = env_lock().lock().await; + let store = std::env::temp_dir().join(format!("weft_approve_{}", std::process::id())); + let id = "org.example.notify"; + write_test_package( + &store.join(id), + id, + "capabilities = [\"sys:notifications\"]", + ); + 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. A + // configured runtime makes appd resolve the package. + unsafe { + std::env::set_var("WEFT_APP_STORE", &store); + std::env::set_var("WEFT_RUNTIME_BIN", "/nonexistent/weft-runtime"); + } + let launch = || async { + dispatch( + Request::LaunchApp { + app_id: id.into(), + surface_id: 0, + }, + &make_registry(), + ) + .await + }; + let refused = launch().await; + let data_home = weft_ipc_types::package::data_home().unwrap(); + let record = weft_ipc_types::approval::approval_path(&data_home, id); + weft_ipc_types::approval::write_approved(&record, &["sys:notifications".to_owned()]) + .unwrap(); + let approved = launch().await; + let _ = std::fs::remove_file(&record); + // 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 refused { + Response::Error { code, message } => { + assert_eq!(code, 403); + assert!( + message.contains("needs approval for sys:notifications"), + "{message}" + ); + } + other => panic!("an unapproved capability launched: {other:?}"), + } + assert!( + matches!(approved, Response::LaunchAck { .. }), + "{approved:?}" + ); + } + #[tokio::test] async fn launch_is_refused_when_capabilities_cannot_be_granted() { let _env = env_lock().lock().await; diff --git a/crates/weft-ipc-types/src/approval.rs b/crates/weft-ipc-types/src/approval.rs new file mode 100644 index 0000000..f553a39 --- /dev/null +++ b/crates/weft-ipc-types/src/approval.rs @@ -0,0 +1,144 @@ +//! The capabilities the user approved for an installed app. +//! +//! A package declares capabilities; it gets only those the user approved. +//! `weft-pack` records the approval, `$XDG_DATA_HOME/weft/approvals/`, +//! one capability per line, and weft-appd refuses to launch an app that +//! declares a capability the record does not hold. An app's own private +//! data is a minimal execution resource and needs no approval. Signature +//! verification and approval are separate decisions: a trusted signature +//! approves nothing. + +use std::collections::BTreeSet; +use std::path::{Path, PathBuf}; + +use crate::capability::Capability; + +/// Where the approval record of `app_id` lives. +pub fn approval_path(data_home: &Path, app_id: &str) -> PathBuf { + data_home.join("weft/approvals").join(app_id) +} + +/// Whether a declared capability needs the user's approval. Strings that +/// are not capabilities are left to the capability checks, which refuse +/// them. +pub fn needs_approval(capability: &str) -> bool { + capability + .parse::() + .is_ok_and(|c| !matches!(c, Capability::AppData(_))) +} + +/// The declared capabilities that need approval and are not in `approved`. +pub fn unapproved<'a>(declared: &'a [String], approved: &BTreeSet) -> Vec<&'a str> { + declared + .iter() + .map(String::as_str) + .filter(|c| needs_approval(c) && !approved.contains(*c)) + .collect() +} + +/// The capabilities approved for an app; none when there is no record. +pub fn read_approved(record: &Path) -> std::io::Result> { + match std::fs::read_to_string(record) { + Ok(text) => Ok(text + .lines() + .map(str::trim) + .filter(|l| !l.is_empty()) + .map(str::to_owned) + .collect()), + Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(BTreeSet::new()), + Err(e) => Err(e), + } +} + +/// Records exactly the capabilities of `declared` that need approval as the +/// app's approval, replacing an earlier one in one rename. With none to +/// approve, the record is removed. +pub fn write_approved(record: &Path, declared: &[String]) -> std::io::Result<()> { + use std::io::Write; + let approved: BTreeSet<&str> = declared + .iter() + .map(String::as_str) + .filter(|c| needs_approval(c)) + .collect(); + if approved.is_empty() { + return remove_approval(record); + } + let parent = record + .parent() + .expect("approval records live in a directory"); + std::fs::create_dir_all(parent)?; + let temp = parent.join(format!( + ".{}.{}.tmp", + record + .file_name() + .and_then(|n| n.to_str()) + .unwrap_or("record"), + std::process::id() + )); + let written = (|| { + let mut file = std::fs::File::create(&temp)?; + for capability in &approved { + writeln!(file, "{capability}")?; + } + file.sync_all()?; + std::fs::rename(&temp, record) + })(); + if written.is_err() { + let _ = std::fs::remove_file(&temp); + } + written?; + std::fs::File::open(parent).and_then(|dir| dir.sync_all()) +} + +/// Removes an app's approval, so a later installation asks again. +pub fn remove_approval(record: &Path) -> std::io::Result<()> { + match std::fs::remove_file(record) { + Err(e) if e.kind() != std::io::ErrorKind::NotFound => Err(e), + _ => Ok(()), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn caps(list: &[&str]) -> Vec { + list.iter().map(|c| (*c).to_owned()).collect() + } + + #[test] + fn private_app_data_needs_no_approval() { + assert!(!needs_approval("fs:rw:app-data")); + assert!(!needs_approval("fs:read:app-data")); + assert!(needs_approval("net:fetch:example.org")); + assert!(needs_approval("sys:notifications")); + assert!(needs_approval("fs:read:xdg-documents")); + // Not a capability: refused elsewhere, not reported as unapproved. + assert!(!needs_approval("sys:everything")); + } + + #[test] + fn approvals_cover_exactly_what_was_approved() { + let dir = std::env::temp_dir().join(format!("weft_approval_{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let record = approval_path(&dir, "org.weft.test"); + let declared = caps(&["fs:rw:app-data", "net:fetch:example.org"]); + assert_eq!(read_approved(&record).unwrap(), BTreeSet::new()); + assert_eq!( + unapproved(&declared, &read_approved(&record).unwrap()), + ["net:fetch:example.org"] + ); + write_approved(&record, &declared).unwrap(); + assert!(unapproved(&declared, &read_approved(&record).unwrap()).is_empty()); + // An update that asks for more needs approval for the new capability. + let updated = caps(&["net:fetch:example.org", "sys:clipboard:read"]); + assert_eq!( + unapproved(&updated, &read_approved(&record).unwrap()), + ["sys:clipboard:read"] + ); + // Nothing left to approve removes the record. + write_approved(&record, &caps(&["fs:rw:app-data"])).unwrap(); + assert!(!record.exists()); + std::fs::remove_dir_all(&dir).unwrap(); + } +} diff --git a/crates/weft-ipc-types/src/lib.rs b/crates/weft-ipc-types/src/lib.rs index 3521ee0..1db9aa1 100644 --- a/crates/weft-ipc-types/src/lib.rs +++ b/crates/weft-ipc-types/src/lib.rs @@ -1,3 +1,4 @@ +pub mod approval; pub mod capability; pub mod manifest; pub mod package; diff --git a/crates/weft-pack/src/main.rs b/crates/weft-pack/src/main.rs index aa4eaaf..93c1b35 100644 --- a/crates/weft-pack/src/main.rs +++ b/crates/weft-pack/src/main.rs @@ -20,23 +20,29 @@ fn main() -> anyhow::Result<()> { print_info(&manifest); } Some("install") => { - let usage = "usage: weft-pack install [--dev] [--claim-data]"; + let usage = "usage: weft-pack install [--dev] [--claim-data] [--approve]"; let dir = args.get(2).context(usage)?; let mut mode = InstallMode::Verified; let mut claim_data = false; + let mut approve = false; for arg in &args[3..] { match arg.as_str() { "--dev" => mode = InstallMode::Development, "--claim-data" => claim_data = true, + "--approve" => approve = true, other => anyhow::bail!("unexpected argument '{other}'; {usage}"), } } - install_package(Path::new(dir), mode, claim_data)?; + install_package(Path::new(dir), mode, claim_data, approve)?; } Some("uninstall") => { let app_id = args.get(2).context("usage: weft-pack uninstall ")?; uninstall_package(app_id)?; } + Some("approve") => { + let app_id = args.get(2).context("usage: weft-pack approve ")?; + approve_package(&resolve_install_root()?, app_id)?; + } Some("rollback") => { let app_id = args.get(2).context("usage: weft-pack rollback ")?; rollback_package(&resolve_install_root()?, app_id)?; @@ -123,8 +129,14 @@ fn main() -> anyhow::Result<()> { eprintln!( " --claim-data: adopt app data with no owner" ); + eprintln!( + " --approve: approve its declared capabilities" + ); eprintln!(" weft-pack uninstall remove installed package"); eprintln!(" weft-pack rollback activate the previous revision"); + eprintln!( + " weft-pack approve approve the app's declared capabilities" + ); eprintln!(" weft-pack list list installed packages"); eprintln!( " weft-pack build-image [--out ] create EROFS image with mkfs.erofs" @@ -270,14 +282,19 @@ enum InstallMode { Development, } -fn install_package(path: &Path, mode: InstallMode, claim_data: bool) -> anyhow::Result<()> { +fn install_package( + path: &Path, + mode: InstallMode, + claim_data: bool, + approve: bool, +) -> anyhow::Result<()> { let root = resolve_install_root()?; - install_into(path, &root, mode, claim_data) + install_into(path, &root, mode, claim_data, approve) } #[cfg(test)] fn install_package_to(path: &Path, store_root: &Path, mode: InstallMode) -> anyhow::Result<()> { - install_into(path, store_root, mode, false) + install_into(path, store_root, mode, false, false) } /// Installs the package at `path` into `store_root`. App data that exists @@ -289,12 +306,13 @@ fn install_into( store_root: &Path, mode: InstallMode, claim_data: bool, + approve: bool, ) -> anyhow::Result<()> { create_store(store_root)?; if !(path.extension().is_some_and(|e| e == "zst" || e == "tar") || path.to_string_lossy().ends_with(".app.tar.zst")) { - return install_dir(path, store_root, mode, claim_data); + return install_dir(path, store_root, mode, claim_data, approve); } let name = path .file_name() @@ -308,7 +326,7 @@ fn install_into( let _in_use = weft_ipc_types::store::try_claim(&unpacked) .with_context(|| format!("open {}", unpacked.display()))?; let result = unbundle_package(path, &unpacked) - .and_then(|()| install_dir(&unpacked.join(name), store_root, mode, claim_data)); + .and_then(|()| install_dir(&unpacked.join(name), store_root, mode, claim_data, approve)); let _ = std::fs::remove_dir_all(&unpacked); result } @@ -379,6 +397,7 @@ fn install_dir( store_root: &Path, mode: InstallMode, claim_data: bool, + approve: bool, ) -> anyhow::Result<()> { check_package(dir)?; // The package is copied into the store first and every decision, the app @@ -399,7 +418,7 @@ fn install_dir( // operation never takes it for abandoned. let in_use = weft_ipc_types::store::try_claim(&staging) .with_context(|| format!("open {}", staging.display()))?; - install_staged(&staging, store_root, mode, claim_data, in_use) + install_staged(&staging, store_root, mode, claim_data, approve, in_use) }); if result.is_err() { let _ = std::fs::remove_dir_all(&staging); @@ -415,6 +434,7 @@ fn install_staged( store_root: &Path, mode: InstallMode, claim_data: bool, + approve: bool, in_use: Option, ) -> anyhow::Result<()> { check_package(staging)?; @@ -457,6 +477,75 @@ fn install_staged( dest.display(), &revision[..12] ); + settle_approval(&data_home, app_id, manifest.capabilities(), approve) +} + +/// Records the installed package's capabilities as approved with +/// `approve`; otherwise reports those that still need approval, since the +/// app does not launch until they are approved. +fn settle_approval( + data_home: &Path, + app_id: &str, + declared: &[String], + approve: bool, +) -> anyhow::Result<()> { + use weft_ipc_types::approval::{approval_path, read_approved, unapproved, write_approved}; + let record = approval_path(data_home, app_id); + if approve { + write_approved(&record, declared) + .with_context(|| format!("record the approval of {app_id}"))?; + let approved: Vec<_> = declared + .iter() + .filter(|c| weft_ipc_types::approval::needs_approval(c)) + .collect(); + if !approved.is_empty() { + println!( + "approved for {app_id}: {}", + approved + .iter() + .map(|c| c.as_str()) + .collect::>() + .join(", ") + ); + } + return Ok(()); + } + let approved = read_approved(&record).with_context(|| format!("read {}", record.display()))?; + let pending = unapproved(declared, &approved); + if !pending.is_empty() { + println!( + "{app_id} needs approval for {} before it launches; run weft-pack approve {app_id}", + pending.join(", ") + ); + } + Ok(()) +} + +/// Approves the capabilities the active package of `app_id` declares. +fn approve_package(store_root: &Path, app_id: &str) -> anyhow::Result<()> { + anyhow::ensure!( + weft_ipc_types::package::is_valid_app_id(app_id), + "'{app_id}' is not a valid app ID" + ); + let data_home = weft_ipc_types::package::data_home() + .context("cannot locate the data home to record the approval")?; + let _lock = weft_ipc_types::trust::lock_owner(&data_home, app_id)?; + let found = active(store_root, app_id)? + .with_context(|| format!("{app_id} is not installed in {}", store_root.display()))?; + let manifest = load_manifest(found.dir())?; + anyhow::ensure!( + manifest.package.id == app_id, + "{} declares another app ID", + found.dir().display() + ); + settle_approval(&data_home, app_id, manifest.capabilities(), true)?; + if !manifest + .capabilities() + .iter() + .any(|c| weft_ipc_types::approval::needs_approval(c)) + { + println!("{app_id} declares nothing that needs approval"); + } Ok(()) } @@ -979,6 +1068,11 @@ fn uninstall_package_from(app_id: &str, store_root: &Path) -> anyhow::Result<()> && !installed_in_another_store(app_id, store_root) { release_owner_without_data(home, app_id); + // A later installation asks for approval again. + weft_ipc_types::approval::remove_approval(&weft_ipc_types::approval::approval_path( + home, app_id, + )) + .with_context(|| format!("remove the approval of {app_id}"))?; } println!("uninstalled {}", app_id); Ok(()) @@ -1931,6 +2025,55 @@ mod tests { let _ = std::fs::remove_dir_all(&home); } + #[test] + fn capabilities_are_approved_only_when_asked_and_again_for_new_ones() { + use weft_ipc_types::approval::{approval_path, read_approved, unapproved}; + let home = temp_root("approval"); + let store = home.join("store"); + let app_id = "org.weft.test.approval"; + let src = home.join("src"); + let record = approval_path(&home.join("share"), app_id); + let pending = |declared: &[&str]| { + let declared: Vec = declared.iter().map(|c| (*c).to_owned()).collect(); + unapproved(&declared, &read_approved(&record).unwrap()) + .into_iter() + .map(str::to_owned) + .collect::>() + }; + write_package(&src, app_id, "\"sys:notifications\", \"fs:rw:app-data\""); + with_home(&home, || { + install_package_to(&src, &store, InstallMode::Development) + }) + .unwrap(); + assert_eq!(pending(&["sys:notifications"]), ["sys:notifications"]); + with_home(&home, || approve_package(&store, app_id)).unwrap(); + assert!(pending(&["sys:notifications", "fs:rw:app-data"]).is_empty()); + // An update that asks for more is not approved by the earlier answer. + write_package( + &src, + app_id, + "\"sys:notifications\", \"sys:clipboard:read\"", + ); + with_home(&home, || { + install_package_to(&src, &store, InstallMode::Development) + }) + .unwrap(); + assert_eq!( + pending(&["sys:notifications", "sys:clipboard:read"]), + ["sys:clipboard:read"] + ); + // --approve approves what the installed package declares. + with_home(&home, || { + install_into(&src, &store, InstallMode::Development, false, true) + }) + .unwrap(); + assert!(pending(&["sys:notifications", "sys:clipboard:read"]).is_empty()); + // Uninstalling forgets the approval. + with_home(&home, || uninstall_package_from(app_id, &store)).unwrap(); + assert!(!record.exists()); + let _ = std::fs::remove_dir_all(&home); + } + #[test] fn leftovers_of_interrupted_operations_are_removed() { let home = temp_root("leftovers"); @@ -2309,7 +2452,13 @@ mod tests { assert!(message.contains("--claim-data"), "{message}"); assert_eq!(owner_of(&home, app_id), None); with_home(&home, || { - install_into(&home.join("src"), &other, InstallMode::Development, true) + install_into( + &home.join("src"), + &other, + InstallMode::Development, + true, + false, + ) }) .unwrap(); assert_eq!(owner_of(&home, app_id), Some(Owner::Development)); @@ -2550,7 +2699,13 @@ mod tests { assert!(message.contains("--claim-data"), "{message}"); assert!(!store.join(app_id).join("wapp.toml").exists()); with_home(&home, || { - install_into(&home.join("src"), &store, InstallMode::Development, true) + install_into( + &home.join("src"), + &store, + InstallMode::Development, + true, + false, + ) }) .unwrap(); assert!(store.join(app_id).join("wapp.toml").exists()); diff --git a/docs/architecture.md b/docs/architecture.md index 4114b6e..9d493c0 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -28,7 +28,7 @@ WASI Preview 2 + Component Model execution host (Wasmtime 30). Runs the componen ### weft-pack -Package management CLI. Subcommands: `check` (validate wapp.toml, entries and package content), `sign` (Ed25519 signature over every file), `verify` (verify signature), `generate-key`, `install` (requires a signature by a trusted key unless `--dev`; records the app ID's owner; installs or updates, see [Installing and updating](#installing-and-updating)), `uninstall`, `rollback`, `list`, `build-image` (EROFS dm-verity), `info`. +Package management CLI. Subcommands: `check` (validate wapp.toml, entries and package content), `sign` (Ed25519 signature over every file), `verify` (verify signature), `generate-key`, `install` (requires a signature by a trusted key unless `--dev`; records the app ID's owner; installs or updates, see [Installing and updating](#installing-and-updating)), `uninstall`, `rollback`, `approve` (approve the installed app's declared capabilities; `install --approve` does so at installation), `list`, `build-image` (EROFS dm-verity), `info`. ### weft-file-portal diff --git a/docs/security.md b/docs/security.md index 55bdf1d..e71560d 100644 --- a/docs/security.md +++ b/docs/security.md @@ -8,7 +8,7 @@ WEFT OS enforces a capability-based security model. No capability is granted by `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. +A package gets only the capabilities the user approved. `weft-pack install --approve` approves those the installed package declares, and `weft-pack approve ` approves those of the installed app later; without approval, `install` lists what still needs it. The approval is recorded in `$XDG_DATA_HOME/weft/approvals/`, and weft-appd refuses to launch an app that declares a capability it does not hold (403, naming the capabilities). An update that declares a new capability needs approval again; an earlier approval never extends to it. Uninstalling the app forgets the approval. Private app data (`fs:read:app-data`, `fs:rw:app-data`) is a minimal execution resource and needs no approval. Signature verification and approval are separate decisions: a trusted signature approves nothing. ## Process Isolation diff --git a/tests/frame/check_update.py b/tests/frame/check_update.py index 92e8c7b..88080c7 100755 --- a/tests/frame/check_update.py +++ b/tests/frame/check_update.py @@ -17,6 +17,8 @@ colour. In the presented pixels and the store: two active again. 5. Uninstalling while a session runs stops new launches (404) but not the session; the next uninstall, after it has ended, removes the revisions. +6. An app declaring a capability (notifications) is refused at launch (403) + until `weft-pack approve` approves it, and then launches. The application is unsigned development content using the Counter demo's component. @@ -41,11 +43,12 @@ VERSIONS = {"one": 1, "two": 2, "bad": 3, "three": 4} STARTUP_TIMEOUT = 120.0 -def write_revision(src, name, wasm=None): +def write_revision(src, name, wasm=None, capabilities="[]"): shutil.rmtree(src, ignore_errors=True) (src / "ui").mkdir(parents=True) (src / "wapp.toml").write_text( f'[package]\nid = "{APP_ID}"\nname = "Update"\nversion = "0.0.{VERSIONS[name]}"\n' + f'capabilities = {capabilities}\n' '[runtime]\nmodule = "app.wasm"\n[ui]\nentry = "ui/index.html"\n') if wasm is None: shutil.copy(ROOT / "examples/org.weft.demo.counter/app.wasm", src / "app.wasm") @@ -177,6 +180,16 @@ def run(args, desktop, store, home): if revisions.exists(): raise AssertionError(f"revisions left after uninstall: {list(revisions.iterdir())}") + # 6. A declared capability needs approval before the app launches. + write_revision(src, "one", capabilities='["sys:notifications"]') + pack("install", str(src), "--dev") + appd.send({"type": "LAUNCH_APP", "app_id": APP_ID, "surface_id": 0}) + refused = appd.wait_for(lambda m: m.get("type") in ("APP_READY", "ERROR"), 30) + if refused.get("code") != 403 or "needs approval" not in refused.get("message", ""): + raise AssertionError(f"an unapproved capability launched: {refused}") + pack("approve", APP_ID) + stop(launch()) + def main(argv=None): parser = argparse.ArgumentParser(description=__doc__, From 9b836257785928ccbfbf7178d426a7ec0c3303da Mon Sep 17 00:00:00 2001 From: Marco Allegretti Date: Fri, 9 Oct 2026 19:18:22 +0000 Subject: [PATCH 2/3] fix(pack): approve the package weft-appd launches, and drop approvals no longer declared weft-pack approve read only the user store, so an app in the system store, or installed as a verified image, could not be approved. The remedy the launch refusal named also did not work. approve now resolves the package in weft-appd's store order. It also accepts the capabilities by name, which is how an image is approved, since weft-pack cannot read its manifest. An install or rollback without --approve now drops approvals for capabilities the package no longer declares. A capability declared again later therefore asks again. Both commands report what still needs approval. weft-appd validates capabilities without side effects first, then refuses unapproved ones, then derives grants, so an unsupported capability is reported as such and not as one needing approval. The docs state that approvals are per user. --- crates/weft-appd/src/grants.rs | 22 +++--- crates/weft-appd/src/main.rs | 3 + crates/weft-pack/src/main.rs | 126 ++++++++++++++++++++++++++++----- docs/architecture.md | 2 +- docs/security.md | 4 +- 5 files changed, 131 insertions(+), 26 deletions(-) diff --git a/crates/weft-appd/src/grants.rs b/crates/weft-appd/src/grants.rs index 0a84f03..0343f99 100644 --- a/crates/weft-appd/src/grants.rs +++ b/crates/weft-appd/src/grants.rs @@ -87,14 +87,9 @@ impl HostDirs { } } -/// 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_dirs: impl FnOnce() -> Result, -) -> Result { +/// Parses the declared capabilities, refusing unknown ones and those this +/// host does not support, without touching the host. +pub(crate) fn validate(declared: &[String]) -> Result, Refusal> { let mut capabilities = Vec::new(); for text in declared { let capability: Capability = @@ -110,7 +105,18 @@ pub(crate) fn derive( } capabilities.push(capability); } + Ok(capabilities) +} +/// 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_dirs: impl FnOnce() -> Result, +) -> Result { + let capabilities = validate(declared)?; let mut grants = SessionGrants::default(); let needs_dirs = capabilities .iter() diff --git a/crates/weft-appd/src/main.rs b/crates/weft-appd/src/main.rs index 4516ac9..f7f1f1d 100644 --- a/crates/weft-appd/src/main.rs +++ b/crates/weft-appd/src/main.rs @@ -609,6 +609,9 @@ async fn resolve_launch( ) -> Result<(launch::LaunchPackage, grants::SessionGrants), grants::Refusal> { tokio::task::spawn_blocking(move || { let package = launch::resolve(&app_id)?; + // Unknown and unsupported capabilities are refused as such, then + // unapproved ones, before anything is prepared on the host. + grants::validate(&package.capabilities)?; check_approval(&app_id, &package.capabilities)?; let grants = grants::derive(&app_id, &package.capabilities, grants::HostDirs::from_env)?; tracing::info!( diff --git a/crates/weft-pack/src/main.rs b/crates/weft-pack/src/main.rs index 93c1b35..bb1dba4 100644 --- a/crates/weft-pack/src/main.rs +++ b/crates/weft-pack/src/main.rs @@ -40,8 +40,10 @@ fn main() -> anyhow::Result<()> { uninstall_package(app_id)?; } Some("approve") => { - let app_id = args.get(2).context("usage: weft-pack approve ")?; - approve_package(&resolve_install_root()?, app_id)?; + let app_id = args + .get(2) + .context("usage: weft-pack approve [...]")?; + approve_package(app_id, &args[3..])?; } Some("rollback") => { let app_id = args.get(2).context("usage: weft-pack rollback ")?; @@ -135,7 +137,7 @@ fn main() -> anyhow::Result<()> { eprintln!(" weft-pack uninstall remove installed package"); eprintln!(" weft-pack rollback activate the previous revision"); eprintln!( - " weft-pack approve approve the app's declared capabilities" + " weft-pack approve [...] approve its declared or listed capabilities" ); eprintln!(" weft-pack list list installed packages"); eprintln!( @@ -511,6 +513,18 @@ fn settle_approval( return Ok(()); } let approved = read_approved(&record).with_context(|| format!("read {}", record.display()))?; + // An approval covers what the installed package declares: a capability + // it no longer declares is dropped, so declaring it again later asks + // again. + let kept: Vec = declared + .iter() + .filter(|c| approved.contains(*c)) + .cloned() + .collect(); + if kept.len() != approved.len() { + write_approved(&record, &kept) + .with_context(|| format!("update the approval of {app_id}"))?; + } let pending = unapproved(declared, &approved); if !pending.is_empty() { println!( @@ -521,8 +535,13 @@ fn settle_approval( Ok(()) } -/// Approves the capabilities the active package of `app_id` declares. -fn approve_package(store_root: &Path, app_id: &str) -> anyhow::Result<()> { +/// Approves capabilities for `app_id`: those listed in `explicit`, or +/// without a list, those its installed package declares. The package is the +/// one weft-appd launches: the first store, in weft-appd's order, holding +/// the app. A verified image, whose manifest weft-pack cannot read, needs +/// the explicit list. +fn approve_package(app_id: &str, explicit: &[String]) -> anyhow::Result<()> { + use weft_ipc_types::approval::needs_approval; anyhow::ensure!( weft_ipc_types::package::is_valid_app_id(app_id), "'{app_id}' is not a valid app ID" @@ -530,23 +549,49 @@ fn approve_package(store_root: &Path, app_id: &str) -> anyhow::Result<()> { let data_home = weft_ipc_types::package::data_home() .context("cannot locate the data home to record the approval")?; let _lock = weft_ipc_types::trust::lock_owner(&data_home, app_id)?; - let found = active(store_root, app_id)? - .with_context(|| format!("{app_id} is not installed in {}", store_root.display()))?; + if !explicit.is_empty() { + for capability in explicit { + capability + .parse::() + .map_err(|e| anyhow::anyhow!("{e}"))?; + anyhow::ensure!(needs_approval(capability), "{capability} needs no approval"); + } + return settle_approval(&data_home, app_id, explicit, true); + } + let roots = list_installed_roots(); + if roots + .iter() + .any(|root| ImageFiles::in_store(root, app_id).any_present()) + { + anyhow::bail!( + "{app_id} is installed as a verified image, whose capabilities weft-pack cannot \ + read; approve them by name: weft-pack approve {app_id} ..." + ); + } + let found = roots + .iter() + .find_map(|root| match active(root, app_id) { + Ok(Some(found)) + if found + .dir() + .join(weft_ipc_types::manifest::MANIFEST_FILE) + .is_file() => + { + Some(found) + } + _ => None, + }) + .with_context(|| format!("{app_id} is not installed"))?; let manifest = load_manifest(found.dir())?; anyhow::ensure!( manifest.package.id == app_id, "{} declares another app ID", found.dir().display() ); - settle_approval(&data_home, app_id, manifest.capabilities(), true)?; - if !manifest - .capabilities() - .iter() - .any(|c| weft_ipc_types::approval::needs_approval(c)) - { + if !manifest.capabilities().iter().any(|c| needs_approval(c)) { println!("{app_id} declares nothing that needs approval"); } - Ok(()) + settle_approval(&data_home, app_id, manifest.capabilities(), true) } /// The active package of `app_id` in `store_root`. @@ -937,7 +982,8 @@ fn rollback_package(store_root: &Path, app_id: &str) -> anyhow::Result<()> { activate(store_root, app_id, &previous)?; collect(store_root, app_id); println!("rolled {app_id} back to revision {}", &previous[..12]); - Ok(()) + let manifest = load_manifest(&dir)?; + settle_approval(&data_home, app_id, manifest.capabilities(), false) } /// Establishes who owns the app ID of a checked, staged package: @@ -1556,6 +1602,22 @@ mod tests { .unwrap(); } + /// Runs `f` with WEFT_APP_STORE set to `store`. Callers run it inside + /// `with_home`, which holds env_lock. + fn with_store(store: &Path, f: impl FnOnce() -> T) -> T { + let prior = std::env::var_os("WEFT_APP_STORE"); + // SAFETY: the caller holds env_lock through with_home. + unsafe { std::env::set_var("WEFT_APP_STORE", store) }; + let result = f(); + unsafe { + match prior { + Some(v) => std::env::set_var("WEFT_APP_STORE", v), + None => std::env::remove_var("WEFT_APP_STORE"), + } + } + result + } + /// Runs `f` with HOME set to `home` and XDG_DATA_HOME to `home/share`. fn with_home(home: &Path, f: impl FnOnce() -> T) -> T { let _env = env_lock(); @@ -2046,7 +2108,10 @@ mod tests { }) .unwrap(); assert_eq!(pending(&["sys:notifications"]), ["sys:notifications"]); - with_home(&home, || approve_package(&store, app_id)).unwrap(); + with_home(&home, || { + with_store(&store, || approve_package(app_id, &[])) + }) + .unwrap(); assert!(pending(&["sys:notifications", "fs:rw:app-data"]).is_empty()); // An update that asks for more is not approved by the earlier answer. write_package( @@ -2068,6 +2133,35 @@ mod tests { }) .unwrap(); assert!(pending(&["sys:notifications", "sys:clipboard:read"]).is_empty()); + // A capability the package stops declaring is no longer approved. + write_package(&src, app_id, "\"sys:notifications\""); + with_home(&home, || { + install_package_to(&src, &store, InstallMode::Development) + }) + .unwrap(); + write_package( + &src, + app_id, + "\"sys:notifications\", \"sys:clipboard:read\"", + ); + with_home(&home, || { + install_package_to(&src, &store, InstallMode::Development) + }) + .unwrap(); + assert_eq!( + pending(&["sys:notifications", "sys:clipboard:read"]), + ["sys:clipboard:read"] + ); + // Capabilities can be approved by name, and only valid ones that + // need approval. + with_home(&home, || { + approve_package(app_id, &["sys:clipboard:read".to_owned()]) + }) + .unwrap(); + assert!(pending(&["sys:clipboard:read"]).is_empty()); + for refused in ["fs:rw:app-data", "sys:everything"] { + assert!(with_home(&home, || approve_package(app_id, &[refused.to_owned()])).is_err()); + } // Uninstalling forgets the approval. with_home(&home, || uninstall_package_from(app_id, &store)).unwrap(); assert!(!record.exists()); diff --git a/docs/architecture.md b/docs/architecture.md index 9d493c0..d2bc1f2 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -28,7 +28,7 @@ WASI Preview 2 + Component Model execution host (Wasmtime 30). Runs the componen ### weft-pack -Package management CLI. Subcommands: `check` (validate wapp.toml, entries and package content), `sign` (Ed25519 signature over every file), `verify` (verify signature), `generate-key`, `install` (requires a signature by a trusted key unless `--dev`; records the app ID's owner; installs or updates, see [Installing and updating](#installing-and-updating)), `uninstall`, `rollback`, `approve` (approve the installed app's declared capabilities; `install --approve` does so at installation), `list`, `build-image` (EROFS dm-verity), `info`. +Package management CLI. Subcommands: `check` (validate wapp.toml, entries and package content), `sign` (Ed25519 signature over every file), `verify` (verify signature), `generate-key`, `install` (requires a signature by a trusted key unless `--dev`; records the app ID's owner; installs or updates, see [Installing and updating](#installing-and-updating)), `uninstall`, `rollback`, `approve` (approve the app's declared capabilities, or those listed; `install --approve` does so at installation), `list`, `build-image` (EROFS dm-verity), `info`. ### weft-file-portal diff --git a/docs/security.md b/docs/security.md index e71560d..cf6aa38 100644 --- a/docs/security.md +++ b/docs/security.md @@ -8,7 +8,9 @@ WEFT OS enforces a capability-based security model. No capability is granted by `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`. -A package gets only the capabilities the user approved. `weft-pack install --approve` approves those the installed package declares, and `weft-pack approve ` approves those of the installed app later; without approval, `install` lists what still needs it. The approval is recorded in `$XDG_DATA_HOME/weft/approvals/`, and weft-appd refuses to launch an app that declares a capability it does not hold (403, naming the capabilities). An update that declares a new capability needs approval again; an earlier approval never extends to it. Uninstalling the app forgets the approval. Private app data (`fs:read:app-data`, `fs:rw:app-data`) is a minimal execution resource and needs no approval. Signature verification and approval are separate decisions: a trusted signature approves nothing. +A package gets only the capabilities the user approved. `weft-pack install --approve` approves those the installed package declares. `weft-pack approve ` approves those of the package weft-appd would launch, the first store in weft-appd's order that holds the app, which also covers packages in the system store. `weft-pack approve ...` approves the listed capabilities, which is the only way for an app installed as a verified image, since weft-pack cannot read an image's manifest. Without approval, `install` and `rollback` list what still needs it. + +The approval is recorded per user, in `$XDG_DATA_HOME/weft/approvals/`; weft-pack and weft-appd must use the same data home, as for owner records. An installation by another user, such as root installing into the system store, approves nothing for this user. weft-appd refuses to launch an app that declares a capability the record does not hold (403, naming the capabilities), after refusing unknown and unsupported capabilities and before preparing anything for the session. An approval covers what the installed package declares: an update or rollback drops approvals for capabilities the package no longer declares, so a capability declared again later, or newly, needs approval again. Uninstalling the app forgets its approval unless another store still holds the app. Approvals are keyed by app ID, not by store or publisher. Private app data (`fs:read:app-data`, `fs:rw:app-data`) is a minimal execution resource and needs no approval. Signature verification and approval are separate decisions: a trusted signature approves nothing. ## Process Isolation From e482fec07cc17d48978c4b9c25ea7995b182f310 Mon Sep 17 00:00:00 2001 From: Marco Allegretti Date: Fri, 9 Oct 2026 19:20:52 +0000 Subject: [PATCH 3/3] fix(pack): add approvals by name only for installed, declared capabilities Pruning compared a list of the declared capabilities with the set of approved ones by length. A manifest repeating a capability could therefore keep an approval it no longer declared. The two are now compared as sets. weft-pack approve ... replaced the app's approval instead of adding to it. It also accepted any app ID and any capability, which let an approval cover a capability declared later. It now adds to the approval, requires the app to be installed, and for a package weft-pack can read, requires each listed capability to be declared. The docs state the remaining limits for verified images. --- crates/weft-pack/src/main.rs | 82 +++++++++++++++++++++++++++--------- docs/security.md | 2 +- 2 files changed, 63 insertions(+), 21 deletions(-) diff --git a/crates/weft-pack/src/main.rs b/crates/weft-pack/src/main.rs index bb1dba4..ce1fcb5 100644 --- a/crates/weft-pack/src/main.rs +++ b/crates/weft-pack/src/main.rs @@ -516,13 +516,13 @@ fn settle_approval( // An approval covers what the installed package declares: a capability // it no longer declares is dropped, so declaring it again later asks // again. - let kept: Vec = declared + let kept: std::collections::BTreeSet = declared .iter() .filter(|c| approved.contains(*c)) .cloned() .collect(); - if kept.len() != approved.len() { - write_approved(&record, &kept) + if kept != approved { + write_approved(&record, &kept.into_iter().collect::>()) .with_context(|| format!("update the approval of {app_id}"))?; } let pending = unapproved(declared, &approved); @@ -549,6 +549,10 @@ fn approve_package(app_id: &str, explicit: &[String]) -> anyhow::Result<()> { let data_home = weft_ipc_types::package::data_home() .context("cannot locate the data home to record the approval")?; let _lock = weft_ipc_types::trust::lock_owner(&data_home, app_id)?; + let roots = list_installed_roots(); + let image = roots + .iter() + .any(|root| ImageFiles::in_store(root, app_id).any_present()); if !explicit.is_empty() { for capability in explicit { capability @@ -556,26 +560,50 @@ fn approve_package(app_id: &str, explicit: &[String]) -> anyhow::Result<()> { .map_err(|e| anyhow::anyhow!("{e}"))?; anyhow::ensure!(needs_approval(capability), "{capability} needs no approval"); } - return settle_approval(&data_home, app_id, explicit, true); + // Approvals by name add to the app's approval. They are for an + // installed app, and for a package weft-pack can read, only for + // what it declares. + if !image { + let manifest = launched_manifest(&roots, app_id)?; + if let Some(undeclared) = explicit + .iter() + .find(|c| !manifest.capabilities().contains(c)) + { + anyhow::bail!("{app_id} does not declare {undeclared}"); + } + } + let record = weft_ipc_types::approval::approval_path(&data_home, app_id); + let mut approved: Vec = weft_ipc_types::approval::read_approved(&record) + .with_context(|| format!("read {}", record.display()))? + .into_iter() + .collect(); + approved.extend(explicit.iter().cloned()); + return settle_approval(&data_home, app_id, &approved, true); } - let roots = list_installed_roots(); - if roots - .iter() - .any(|root| ImageFiles::in_store(root, app_id).any_present()) - { + if image { anyhow::bail!( "{app_id} is installed as a verified image, whose capabilities weft-pack cannot \ read; approve them by name: weft-pack approve {app_id} ..." ); } + let manifest = launched_manifest(&roots, app_id)?; + if !manifest.capabilities().iter().any(|c| needs_approval(c)) { + println!("{app_id} declares nothing that needs approval"); + } + settle_approval(&data_home, app_id, manifest.capabilities(), true) +} + +/// The manifest of the package of `app_id` that weft-appd launches from a +/// directory or revision: the first of `roots` holding one. +fn launched_manifest(roots: &[PathBuf], app_id: &str) -> anyhow::Result { let found = roots .iter() .find_map(|root| match active(root, app_id) { Ok(Some(found)) - if found - .dir() - .join(weft_ipc_types::manifest::MANIFEST_FILE) - .is_file() => + if std::fs::symlink_metadata( + found.dir().join(weft_ipc_types::manifest::MANIFEST_FILE), + ) + .is_ok() => { Some(found) } @@ -588,10 +616,7 @@ fn approve_package(app_id: &str, explicit: &[String]) -> anyhow::Result<()> { "{} declares another app ID", found.dir().display() ); - if !manifest.capabilities().iter().any(|c| needs_approval(c)) { - println!("{app_id} declares nothing that needs approval"); - } - settle_approval(&data_home, app_id, manifest.capabilities(), true) + Ok(manifest) } /// The active package of `app_id` in `store_root`. @@ -2155,12 +2180,29 @@ mod tests { // Capabilities can be approved by name, and only valid ones that // need approval. with_home(&home, || { - approve_package(app_id, &["sys:clipboard:read".to_owned()]) + with_store(&store, || { + approve_package(app_id, &["sys:clipboard:read".to_owned()]) + }) }) .unwrap(); - assert!(pending(&["sys:clipboard:read"]).is_empty()); + // Added to what was approved before. + assert!(pending(&["sys:notifications", "sys:clipboard:read"]).is_empty()); + let undeclared = with_home(&home, || { + with_store(&store, || { + approve_package(app_id, &["sys:clipboard:write".to_owned()]) + }) + }); + assert!( + undeclared.is_err(), + "approved a capability the package does not declare" + ); for refused in ["fs:rw:app-data", "sys:everything"] { - assert!(with_home(&home, || approve_package(app_id, &[refused.to_owned()])).is_err()); + assert!( + with_home(&home, || with_store(&store, || { + approve_package(app_id, &[refused.to_owned()]) + })) + .is_err() + ); } // Uninstalling forgets the approval. with_home(&home, || uninstall_package_from(app_id, &store)).unwrap(); diff --git a/docs/security.md b/docs/security.md index cf6aa38..affbee8 100644 --- a/docs/security.md +++ b/docs/security.md @@ -8,7 +8,7 @@ WEFT OS enforces a capability-based security model. No capability is granted by `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`. -A package gets only the capabilities the user approved. `weft-pack install --approve` approves those the installed package declares. `weft-pack approve ` approves those of the package weft-appd would launch, the first store in weft-appd's order that holds the app, which also covers packages in the system store. `weft-pack approve ...` approves the listed capabilities, which is the only way for an app installed as a verified image, since weft-pack cannot read an image's manifest. Without approval, `install` and `rollback` list what still needs it. +A package gets only the capabilities the user approved. `weft-pack install --approve` approves those the installed package declares. `weft-pack approve ` approves those of the package weft-appd would launch, the first store in weft-appd's order that holds the app, which also covers packages in the system store. `weft-pack approve ...` adds the listed capabilities to the app's approval; for a package weft-pack can read they must be ones it declares. Listing them is the only way to approve an app installed as a verified image, since weft-pack cannot read an image's manifest; for the same reason, approvals for an image are not reduced when it is updated, and uninstalling a directory copy of the app removes them although the image remains. Without approval, `install` and `rollback` list what still needs it. The approval is recorded per user, in `$XDG_DATA_HOME/weft/approvals/`; weft-pack and weft-appd must use the same data home, as for owner records. An installation by another user, such as root installing into the system store, approves nothing for this user. weft-appd refuses to launch an app that declares a capability the record does not hold (403, naming the capabilities), after refusing unknown and unsupported capabilities and before preparing anything for the session. An approval covers what the installed package declares: an update or rollback drops approvals for capabilities the package no longer declares, so a capability declared again later, or newly, needs approval again. Uninstalling the app forgets its approval unless another store still holds the app. Approvals are keyed by app ID, not by store or publisher. Private app data (`fs:read:app-data`, `fs:rw:app-data`) is a minimal execution resource and needs no approval. Signature verification and approval are separate decisions: a trusted signature approves nothing.