From 11cea5e7e3b0c862c0dc5579d8cef41960608501 Mon Sep 17 00:00:00 2001 From: Marco Allegretti Date: Fri, 9 Oct 2026 14:29:14 +0000 Subject: [PATCH 1/5] fix(appd): verify package owner and signature before a session starts weft-appd trusted an installed directory as installed, so content changed after installation, or signed by a key since removed from the trust store, still ran with the owner's app data. Before anything starts, a package recorded as a publisher's must carry that publisher's valid signature over its current content, with the key still trusted; a package with no record must be signed by a trusted key; development content, recorded by weft-pack install --dev, runs unverified. Failures are refused with code 403. The desktop checks trust the demo key, and the confinement check, whose package deliberately holds a link, records it as development content. --- crates/weft-appd/src/launch.rs | 184 ++++++++++++++++++++++++++++++- crates/weft-appd/src/main.rs | 16 +++ docs/security.md | 4 +- tests/frame/check_app_data.py | 1 + tests/frame/check_confinement.py | 8 ++ tests/frame/check_counter.py | 1 + tests/frame/check_notes.py | 1 + 7 files changed, 213 insertions(+), 2 deletions(-) diff --git a/crates/weft-appd/src/launch.rs b/crates/weft-appd/src/launch.rs index 85b5bbc..2e777f5 100644 --- a/crates/weft-appd/src/launch.rs +++ b/crates/weft-appd/src/launch.rs @@ -3,11 +3,20 @@ //! The runtime and the app shell receive the exact files resolved here and //! never look for the package themselves, so the component, the UI and the //! capabilities a session is granted all come from the same package root. +//! +//! Before anything starts, the package must still be what its owner +//! installed: a package recorded as a publisher's must carry that +//! publisher's valid signature over its current content, and a package with +//! no record must be signed by a trusted key. Development content, recorded +//! as such by `weft-pack install --dev`, runs unverified. use std::path::{Path, PathBuf}; use weft_ipc_types::manifest::{MANIFEST_FILE, Manifest, ManifestError, entry_path}; use weft_ipc_types::package::{ImageFiles, is_valid_app_id}; +use weft_ipc_types::trust::{ + Owner, TrustError, TrustStore, content_digest, owner_record_path, read_owner, read_signature, +}; use crate::grants::Refusal; use crate::mount::Mount; @@ -99,6 +108,7 @@ fn from_root(app_id: &str, root: PathBuf, image: Option) -> Result) -> Result Result<(), Refusal> { + let refused = |e: TrustError| match e { + TrustError::Io(..) => Refusal::new(500, e.to_string()), + _ => Refusal::new(403, e.to_string()), + }; + let data_home = weft_ipc_types::package::data_home().ok_or_else(|| { + Refusal::new( + 500, + "cannot locate the data home holding package owner records", + ) + })?; + let owner = read_owner(&owner_record_path(&data_home, app_id)).map_err(refused)?; + let trusted = TrustStore::load(&TrustStore::directories()).map_err(refused)?; + match owner { + Some(Owner::Development) => Ok(()), + Some(Owner::Verified(key)) => { + // The key must still be trusted, and its signature must cover + // the package's current content. + let signature = read_signature(root).map_err(refused)?; + let digest = content_digest(root).map_err(refused)?; + let valid = trusted.keys().contains(&key) + && signature.is_some_and(|sig| key.signed(&digest, &sig)); + if valid { + Ok(()) + } else { + Err(Refusal::new( + 403, + format!( + "{} is not signed by its owner, publisher {}, or that key is no longer \ + trusted; the package was changed or its key was withdrawn", + root.display(), + key.to_hex() + ), + )) + } + } + None => match trusted.signer(root).map_err(refused)? { + Some(_) => Ok(()), + None => Err(Refusal::new( + 403, + format!( + "{} has no recorded owner and is not signed by a trusted key; install it \ + with weft-pack", + root.display() + ), + )), + }, + } +} + impl LaunchPackage { /// A package for supervisor tests whose children ignore their files. #[cfg(test)] @@ -160,8 +221,17 @@ mod tests { ), ) .unwrap(); + // The fixture is unsigned development content, recorded as such. + weft_ipc_types::trust::write_owner( + &owner_record_path(&store.join("share"), ID), + Owner::Development, + ) + .unwrap(); // SAFETY: callers hold env_lock, which serialises environment changes. - unsafe { std::env::set_var("WEFT_APP_STORE", &store) }; + unsafe { + std::env::set_var("WEFT_APP_STORE", &store); + std::env::set_var("XDG_DATA_HOME", store.join("share")); + } store } @@ -170,6 +240,8 @@ mod tests { unsafe { std::env::remove_var("WEFT_APP_STORE"); std::env::remove_var("WEFT_MOUNT_HELPER"); + std::env::remove_var("XDG_DATA_HOME"); + std::env::remove_var("WEFT_TRUSTED_KEYS"); } let _ = std::fs::remove_dir_all(store); } @@ -249,6 +321,116 @@ mod tests { } } + const DEMO: &str = "org.weft.demo.counter"; + + /// A store holding a copy of the signed Counter demo, with the demo key + /// trusted when `trusted`. Callers hold env_lock. + fn demo_store(name: &str, trusted: bool) -> PathBuf { + let store = store(name, ID, "app.wasm"); + let examples = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../examples"); + copy_tree(&examples.join(DEMO), &store.join(DEMO)); + let keys = store.join("keys"); + std::fs::create_dir_all(&keys).unwrap(); + if trusted { + std::fs::copy(examples.join("keys/weft-sign.pub"), keys.join("demo.pub")).unwrap(); + } + // SAFETY: as in `store`. + unsafe { std::env::set_var("WEFT_TRUSTED_KEYS", &keys) }; + store + } + + fn copy_tree(src: &Path, dst: &Path) { + std::fs::create_dir_all(dst).unwrap(); + for entry in std::fs::read_dir(src).unwrap().flatten() { + let to = dst.join(entry.file_name()); + if entry.file_type().unwrap().is_dir() { + copy_tree(&entry.path(), &to); + } else { + std::fs::copy(entry.path(), to).unwrap(); + } + } + } + + fn record(store: &Path, app_id: &str, owner: Owner) { + weft_ipc_types::trust::write_owner(&owner_record_path(&store.join("share"), app_id), owner) + .unwrap(); + } + + fn demo_key() -> weft_ipc_types::trust::PublisherKey { + weft_ipc_types::trust::PublisherKey::from_file( + &Path::new(env!("CARGO_MANIFEST_DIR")).join("../../examples/keys/weft-sign.pub"), + ) + .unwrap() + } + + #[test] + fn a_package_signed_by_its_owner_launches() { + let _env = crate::tests::env_lock().blocking_lock(); + // Recorded as the publisher's, and with no record but a trusted + // signature. + let store = demo_store("signed", true); + let unrecorded = resolve(DEMO).map(|p| p.root); + record(&store, DEMO, Owner::Verified(demo_key())); + let recorded = resolve(DEMO).map(|p| p.root); + finish(&store); + assert_eq!(unrecorded.ok(), Some(store.join(DEMO))); + assert_eq!(recorded.ok(), Some(store.join(DEMO))); + } + + #[test] + fn a_package_changed_after_installation_is_refused() { + let _env = crate::tests::env_lock().blocking_lock(); + let store = demo_store("changed", true); + record(&store, DEMO, Owner::Verified(demo_key())); + let page = store.join(DEMO).join("ui/index.html"); + let mut text = std::fs::read_to_string(&page).unwrap(); + text.push_str(""); + std::fs::write(&page, text).unwrap(); + let changed = refusal(resolve(DEMO)); + // Without a record, the changed package matches no trusted key. + std::fs::remove_file(owner_record_path(&store.join("share"), DEMO)).unwrap(); + let unrecorded = refusal(resolve(DEMO)); + finish(&store); + assert_eq!(changed.code, 403, "{}", changed.message); + assert!( + changed.message.contains("not signed by its owner"), + "{}", + changed.message + ); + assert_eq!(unrecorded.code, 403, "{}", unrecorded.message); + assert!( + unrecorded.message.contains("no recorded owner"), + "{}", + unrecorded.message + ); + } + + #[test] + fn a_withdrawn_key_no_longer_launches_its_packages() { + let _env = crate::tests::env_lock().blocking_lock(); + let store = demo_store("withdrawn", false); + record(&store, DEMO, Owner::Verified(demo_key())); + let refused = refusal(resolve(DEMO)); + finish(&store); + assert_eq!(refused.code, 403, "{}", refused.message); + assert!(refused.message.contains("no longer"), "{}", refused.message); + } + + #[test] + fn unsigned_content_needs_a_development_record() { + let _env = crate::tests::env_lock().blocking_lock(); + let store = store("unrecorded", ID, "app.wasm"); + std::fs::remove_file(owner_record_path(&store.join("share"), ID)).unwrap(); + let refused = refusal(resolve(ID)); + // Another owner's record does not admit it either. + record(&store, ID, Owner::Verified(demo_key())); + let other_owner = refusal(resolve(ID)); + finish(&store); + for refused in [refused, other_owner] { + assert_eq!(refused.code, 403, "{}", refused.message); + } + } + #[test] fn a_package_declaring_another_id_is_refused() { let _env = crate::tests::env_lock().blocking_lock(); diff --git a/crates/weft-appd/src/main.rs b/crates/weft-appd/src/main.rs index 4512211..d0c549d 100644 --- a/crates/weft-appd/src/main.rs +++ b/crates/weft-appd/src/main.rs @@ -712,6 +712,22 @@ mod tests { ), ) .unwrap(); + record_development(id); + } + + /// Records `id` as development content in a data home private to this + /// test process, which XDG_DATA_HOME then points at. Callers hold + /// env_lock. + fn record_development(id: &str) { + let data_home = + std::env::temp_dir().join(format!("weft-appd-tests-data-{}", std::process::id())); + let record = weft_ipc_types::trust::owner_record_path(&data_home, id); + if !record.exists() { + weft_ipc_types::trust::write_owner(&record, weft_ipc_types::trust::Owner::Development) + .unwrap(); + } + // SAFETY: callers hold env_lock, which serialises environment changes. + unsafe { std::env::set_var("XDG_DATA_HOME", &data_home) }; } fn make_registry() -> Registry { diff --git a/docs/security.md b/docs/security.md index 5ac7ff2..12016fa 100644 --- a/docs/security.md +++ b/docs/security.md @@ -26,7 +26,9 @@ Packages are signed with Ed25519 over their content digest: the SHA-256 of an in The first installation of an app ID records its owner in `$XDG_DATA_HOME/weft/owners/`: the publisher key, or development. Installations and uninstallations of one ID under one data home hold a per-ID lock, so concurrent installations cannot leave a placed package without its record. Every later installation of that ID must have the same owner, so neither another trusted publisher nor a development build can take over an ID, and with it the app's data. The record survives uninstall while the app's data remains; uninstalling with no data left frees the ID. App data with no recorded owner, as left by installations from before owner records, is given to a new owner only with `--claim-data`. A record is written under a temporary name and linked into place, so it is never partial, and a record created by an installation that then fails to place its package is removed. A record left by an installation that was killed before placing its package is released by `weft-pack uninstall ` once no data remains. A record is only released while no known store (the user store, the system store and `$WEFT_APP_STORE`) holds the package; a package installed into another custom store is uninstalled with that store selected. The demo key in `examples/keys` is a test fixture, not a signing authority. -Not yet covered: `weft-appd` does not check signatures or owners at launch, so the installed directory is trusted as installed; key revocation, rotation and ownership transfer have no workflow; and capabilities are granted at launch without asking the user, independently of the signature. +`weft-appd` checks every package again before a session starts. A package recorded as a publisher's runs only while that key is still trusted and its signature covers the package's current content; a package with no record runs only when a trusted key signed it; development content runs unverified. A changed package, or one whose key was removed from the trust store, is refused with code 403. The check reads the package before the session starts, so a directory install changed by its owning user while the session runs is not detected; verified images are not writable. + +Not yet covered: key rotation and ownership transfer have no workflow, and removing a key is the only revocation; and capabilities are granted at launch without asking the user, independently of the signature. For verified read-only package storage, `weft-pack build-image` produces an EROFS image protected with dm-verity. Mounting requires the setuid `weft-mount-helper` which calls `veritysetup`. The image's root hash is not yet authenticated (see `architecture.md`). diff --git a/tests/frame/check_app_data.py b/tests/frame/check_app_data.py index 2f43cb8..50d10e2 100644 --- a/tests/frame/check_app_data.py +++ b/tests/frame/check_app_data.py @@ -47,6 +47,7 @@ def run(args, desktop, home, xdotool): "WEFT_RUNTIME_BIN": str(t / "weft-runtime"), "WEFT_APP_SHELL_BIN": str(t / "weft-app-shell"), "WEFT_APP_STORE": str(args.store), + "WEFT_TRUSTED_KEYS": str(ROOT / "examples/keys"), "WEFT_DISABLE_CGROUP": "1", "WEFT_APPD_WS_PORT": str(free_port()), "HOME": str(home), diff --git a/tests/frame/check_confinement.py b/tests/frame/check_confinement.py index c484905..d027921 100644 --- a/tests/frame/check_confinement.py +++ b/tests/frame/check_confinement.py @@ -142,6 +142,12 @@ def make_package(store, http_port, ws_port, other_dir): (package / "outside.png").write_bytes(png()) other.write_bytes(png()) (package / "ui/linked").symlink_to(other_dir) + # The package holds a link, which weft-pack refuses to install, so it is + # planted directly and recorded as development content, which runs + # unverified: the renderer's own confinement is what this check probes. + record = store / "home/share/weft/owners" / APP_ID + record.parent.mkdir(parents=True) + record.write_text("development\n") def run(args, desktop, store, other_dir): @@ -157,6 +163,8 @@ def run(args, desktop, store, other_dir): "WEFT_RUNTIME_BIN": str(t / "weft-runtime"), "WEFT_APP_SHELL_BIN": str(t / "weft-app-shell"), "WEFT_APP_STORE": str(store), + "HOME": str(store / "home"), + "XDG_DATA_HOME": str(store / "home/share"), "WEFT_DISABLE_CGROUP": "1", "WEFT_APPD_WS_PORT": str(free_port()), }) diff --git a/tests/frame/check_counter.py b/tests/frame/check_counter.py index aa8ecdb..0da4e88 100644 --- a/tests/frame/check_counter.py +++ b/tests/frame/check_counter.py @@ -162,6 +162,7 @@ def run(args, desktop, xdotool): "WEFT_RUNTIME_BIN": str(target / "weft-runtime"), "WEFT_APP_SHELL_BIN": str(target / "weft-app-shell"), "WEFT_APP_STORE": str(args.store), + "WEFT_TRUSTED_KEYS": str(ROOT / "examples/keys"), "WEFT_DISABLE_CGROUP": "1", "WEFT_APPD_WS_PORT": str(port), }) diff --git a/tests/frame/check_notes.py b/tests/frame/check_notes.py index 2d562ee..6ee3cba 100644 --- a/tests/frame/check_notes.py +++ b/tests/frame/check_notes.py @@ -75,6 +75,7 @@ def run(args, desktop, home, xdotool): "WEFT_RUNTIME_BIN": str(t / "weft-runtime"), "WEFT_APP_SHELL_BIN": str(t / "weft-app-shell"), "WEFT_APP_STORE": str(args.store), + "WEFT_TRUSTED_KEYS": str(ROOT / "examples/keys"), "WEFT_DISABLE_CGROUP": "1", "WEFT_APPD_WS_PORT": str(free_port()), "HOME": str(home), From 39aacac8226c56b56f0d98415ef6ab932518897a Mon Sep 17 00:00:00 2001 From: Marco Allegretti Date: Fri, 9 Oct 2026 14:36:06 +0000 Subject: [PATCH 2/5] fix(appd): bind the launched manifest to the signature and record first owners The manifest is now read once, and its bytes must match the verified inventory, so a manifest swapped in around the check cannot grant capabilities or entries the owner did not sign. A trusted package with no owner record is recorded as its signer's on its first launch, and app data without a recorded owner is refused rather than handed to the first publisher, matching weft-pack's --claim-data rule. A damaged trust store or owner record is a host error (500), and the trust store is not consulted for development content. Supervisor tests use a private data home and an empty trust store; the counter check runs with a private home, and the notes check records the owner of the data it seeds. --- crates/weft-appd/src/launch.rs | 192 +++++++++++++++++++------- crates/weft-appd/src/main.rs | 27 +++- crates/weft-ipc-types/src/manifest.rs | 16 ++- crates/weft-ipc-types/src/trust.rs | 65 +++++++-- docs/security.md | 2 +- tests/frame/check_confinement.py | 2 +- tests/frame/check_counter.py | 6 + tests/frame/check_notes.py | 6 + 8 files changed, 244 insertions(+), 72 deletions(-) diff --git a/crates/weft-appd/src/launch.rs b/crates/weft-appd/src/launch.rs index 2e777f5..8f8f2cc 100644 --- a/crates/weft-appd/src/launch.rs +++ b/crates/weft-appd/src/launch.rs @@ -7,15 +7,17 @@ //! Before anything starts, the package must still be what its owner //! installed: a package recorded as a publisher's must carry that //! publisher's valid signature over its current content, and a package with -//! no record must be signed by a trusted key. Development content, recorded -//! as such by `weft-pack install --dev`, runs unverified. +//! no record must be signed by a trusted key, which is then recorded as its +//! owner. Development content, recorded as such by `weft-pack install +//! --dev`, runs unverified. use std::path::{Path, PathBuf}; use weft_ipc_types::manifest::{MANIFEST_FILE, Manifest, ManifestError, entry_path}; use weft_ipc_types::package::{ImageFiles, is_valid_app_id}; use weft_ipc_types::trust::{ - Owner, TrustError, TrustStore, content_digest, owner_record_path, read_owner, read_signature, + Inventory, Owner, PublisherKey, TrustError, TrustStore, lock_owner, owner_record_path, + read_owner, read_signature, write_owner, }; use crate::grants::Refusal; @@ -94,9 +96,14 @@ fn from_root(app_id: &str, root: PathBuf, image: Option) -> Result Refusal::new(500, e.to_string()), - ManifestError::Parse(..) => Refusal::new(403, e.to_string()), + // The manifest is read once; the same bytes are parsed and checked + // against the signed inventory, so the capabilities and entries a + // session gets are the ones the owner signed. + let manifest_path = root.join(MANIFEST_FILE); + let manifest_bytes = std::fs::read(&manifest_path) + .map_err(|e| Refusal::new(500, format!("cannot read {}: {e}", manifest_path.display())))?; + let manifest = Manifest::parse(&manifest_path, &manifest_bytes).map_err(|e| match e { + ManifestError::Io(..) | ManifestError::Parse(..) => Refusal::new(403, e.to_string()), })?; if manifest.package.id != app_id { return Err(Refusal::new( @@ -108,7 +115,7 @@ fn from_root(app_id: &str, root: PathBuf, image: Option) -> Result) -> Result Result<(), Refusal> { - let refused = |e: TrustError| match e { +/// Checks that the package at `root`, whose manifest was read as +/// `manifest_bytes`, is what its owner installed. A trusted package with no +/// owner record is recorded as its signer's on its first launch, so its app +/// data stays with that publisher; existing app data with no recorded owner +/// is not handed to whichever publisher launches first. +fn verify_owner(app_id: &str, root: &Path, manifest_bytes: &[u8]) -> Result<(), Refusal> { + // Errors in the host's trust store or owner records are the host's, not + // the package's. + let host = |e: TrustError| Refusal::new(500, e.to_string()); + let package = |e: TrustError| match e { TrustError::Io(..) => Refusal::new(500, e.to_string()), _ => Refusal::new(403, e.to_string()), }; @@ -137,43 +151,90 @@ fn verify_owner(app_id: &str, root: &Path) -> Result<(), Refusal> { "cannot locate the data home holding package owner records", ) })?; - let owner = read_owner(&owner_record_path(&data_home, app_id)).map_err(refused)?; - let trusted = TrustStore::load(&TrustStore::directories()).map_err(refused)?; - match owner { - Some(Owner::Development) => Ok(()), - Some(Owner::Verified(key)) => { - // The key must still be trusted, and its signature must cover - // the package's current content. - let signature = read_signature(root).map_err(refused)?; - let digest = content_digest(root).map_err(refused)?; - let valid = trusted.keys().contains(&key) - && signature.is_some_and(|sig| key.signed(&digest, &sig)); - if valid { - Ok(()) - } else { - Err(Refusal::new( - 403, - format!( - "{} is not signed by its owner, publisher {}, or that key is no longer \ - trusted; the package was changed or its key was withdrawn", - root.display(), - key.to_hex() - ), - )) - } - } - None => match trusted.signer(root).map_err(refused)? { - Some(_) => Ok(()), - None => Err(Refusal::new( + let record = owner_record_path(&data_home, app_id); + let owner = read_owner(&record).map_err(host)?; + if owner == Some(Owner::Development) { + return Ok(()); + } + let trusted = TrustStore::load(&TrustStore::directories()).map_err(host)?; + let inventory = Inventory::read(root).map_err(package)?; + if !inventory.holds(MANIFEST_FILE, manifest_bytes) { + return Err(Refusal::new( + 403, + format!("{} changed while it was checked", root.display()), + )); + } + let digest = inventory.digest(); + let signature = read_signature(root).map_err(package)?; + let signer = signature.and_then(|sig| trusted.signer_of(&digest, &sig)); + match (owner, signer) { + (Some(Owner::Verified(key)), Some(signer)) if key == signer => Ok(()), + (Some(Owner::Verified(key)), _) => Err(Refusal::new( + 403, + format!( + "{} is not signed by its owner, publisher {}, or that key is no longer \ + trusted; the package was changed or its key was withdrawn", + root.display(), + key.to_hex() + ), + )), + (_, None) => Err(Refusal::new( + 403, + format!( + "{} has no recorded owner and is not signed by a trusted key; install it \ + with weft-pack", + root.display() + ), + )), + (_, Some(signer)) => record_first_owner(app_id, &data_home, &record, signer), + } +} + +/// Records `signer` as the owner of `app_id` on the first launch of a trusted +/// package that has no owner record and no app data yet. +fn record_first_owner( + app_id: &str, + data_home: &Path, + record: &Path, + signer: PublisherKey, +) -> Result<(), Refusal> { + let host = |e: TrustError| Refusal::new(500, e.to_string()); + let _lock = lock_owner(data_home, app_id).map_err(host)?; + match read_owner(record).map_err(host)? { + Some(Owner::Verified(key)) if key == signer => return Ok(()), + Some(existing) => { + return Err(Refusal::new( 403, format!( - "{} has no recorded owner and is not signed by a trusted key; install it \ - with weft-pack", - root.display() + "{app_id} belongs to {existing}, not publisher {}", + signer.to_hex() ), - )), - }, + )); + } + None => {} } + let data = weft_ipc_types::package::app_data_dir(data_home, app_id); + match std::fs::symlink_metadata(&data) { + Err(e) if e.kind() == std::io::ErrorKind::NotFound => {} + Err(e) => { + return Err(Refusal::new( + 500, + format!("cannot inspect {}: {e}", data.display()), + )); + } + Ok(_) => { + return Err(Refusal::new( + 403, + format!( + "{} holds app data for {app_id} with no recorded owner; it is not given to \ + publisher {} without weft-pack install --claim-data", + data.display(), + signer.to_hex() + ), + )); + } + } + write_owner(record, Owner::Verified(signer)).map_err(host) } impl LaunchPackage { @@ -369,12 +430,47 @@ mod tests { // Recorded as the publisher's, and with no record but a trusted // signature. let store = demo_store("signed", true); - let unrecorded = resolve(DEMO).map(|p| p.root); - record(&store, DEMO, Owner::Verified(demo_key())); - let recorded = resolve(DEMO).map(|p| p.root); + let first = resolve(DEMO).map(|p| p.root); + let owner = read_owner(&owner_record_path(&store.join("share"), DEMO)).unwrap(); + let again = resolve(DEMO).map(|p| p.root); finish(&store); - assert_eq!(unrecorded.ok(), Some(store.join(DEMO))); - assert_eq!(recorded.ok(), Some(store.join(DEMO))); + assert_eq!(first.ok(), Some(store.join(DEMO))); + assert_eq!(owner, Some(Owner::Verified(demo_key()))); + assert_eq!(again.ok(), Some(store.join(DEMO))); + } + + #[test] + fn unowned_app_data_is_not_given_to_the_first_publisher() { + let _env = crate::tests::env_lock().blocking_lock(); + let store = demo_store("unowned_data", true); + let data = weft_ipc_types::package::app_data_dir(&store.join("share"), DEMO); + std::fs::create_dir_all(&data).unwrap(); + let refused = refusal(resolve(DEMO)); + let owner = read_owner(&owner_record_path(&store.join("share"), DEMO)).unwrap(); + finish(&store); + assert_eq!(refused.code, 403, "{}", refused.message); + assert!( + refused.message.contains("--claim-data"), + "{}", + refused.message + ); + assert_eq!(owner, None); + } + + #[test] + fn a_damaged_trust_store_or_record_is_a_host_error() { + let _env = crate::tests::env_lock().blocking_lock(); + let store = demo_store("damaged", true); + std::fs::write(store.join("keys/broken.pub"), "not a key").unwrap(); + let bad_key = refusal(resolve(DEMO)); + std::fs::remove_file(store.join("keys/broken.pub")).unwrap(); + let record = owner_record_path(&store.join("share"), DEMO); + std::fs::write(&record, "nonsense\n").unwrap(); + let bad_record = refusal(resolve(DEMO)); + finish(&store); + for refused in [bad_key, bad_record] { + assert_eq!(refused.code, 500, "{}", refused.message); + } } #[test] diff --git a/crates/weft-appd/src/main.rs b/crates/weft-appd/src/main.rs index d0c549d..0df9632 100644 --- a/crates/weft-appd/src/main.rs +++ b/crates/weft-appd/src/main.rs @@ -716,18 +716,35 @@ mod tests { } /// Records `id` as development content in a data home private to this - /// test process, which XDG_DATA_HOME then points at. Callers hold - /// env_lock. + /// test process, which XDG_DATA_HOME then points at, with an empty trust + /// store so the host's keys never affect a test. Data homes left by + /// earlier test processes are removed. Callers hold env_lock. fn record_development(id: &str) { - let data_home = - std::env::temp_dir().join(format!("weft-appd-tests-data-{}", std::process::id())); + let name = format!("weft-appd-tests-data-{}", std::process::id()); + if let Ok(entries) = std::fs::read_dir(std::env::temp_dir()) { + for entry in entries.flatten() { + let stale = entry + .file_name() + .to_str() + .is_some_and(|n| n.starts_with("weft-appd-tests-data-") && n != name); + if stale { + let _ = std::fs::remove_dir_all(entry.path()); + } + } + } + let data_home = std::env::temp_dir().join(name); + let keys = data_home.join("trusted-keys"); + std::fs::create_dir_all(&keys).unwrap(); let record = weft_ipc_types::trust::owner_record_path(&data_home, id); if !record.exists() { weft_ipc_types::trust::write_owner(&record, weft_ipc_types::trust::Owner::Development) .unwrap(); } // SAFETY: callers hold env_lock, which serialises environment changes. - unsafe { std::env::set_var("XDG_DATA_HOME", &data_home) }; + unsafe { + std::env::set_var("XDG_DATA_HOME", &data_home); + std::env::set_var("WEFT_TRUSTED_KEYS", &keys); + } } fn make_registry() -> Registry { diff --git a/crates/weft-ipc-types/src/manifest.rs b/crates/weft-ipc-types/src/manifest.rs index 0115bc4..c15ff3b 100644 --- a/crates/weft-ipc-types/src/manifest.rs +++ b/crates/weft-ipc-types/src/manifest.rs @@ -62,9 +62,19 @@ impl Manifest { /// Reads `/wapp.toml`. pub fn read(package_root: &Path) -> Result { let path = package_root.join(MANIFEST_FILE); - let text = - std::fs::read_to_string(&path).map_err(|e| ManifestError::Io(path.clone(), e))?; - toml::from_str(&text).map_err(|e| ManifestError::Parse(path, e)) + let bytes = std::fs::read(&path).map_err(|e| ManifestError::Io(path.clone(), e))?; + Self::parse(&path, &bytes) + } + + /// Parses manifest bytes already read from `path`. + pub fn parse(path: &Path, bytes: &[u8]) -> Result { + let text = std::str::from_utf8(bytes).map_err(|e| { + ManifestError::Io( + path.to_path_buf(), + std::io::Error::new(std::io::ErrorKind::InvalidData, e), + ) + })?; + toml::from_str(text).map_err(|e| ManifestError::Parse(path.to_path_buf(), e)) } pub fn capabilities(&self) -> &[String] { diff --git a/crates/weft-ipc-types/src/trust.rs b/crates/weft-ipc-types/src/trust.rs index 79143b5..0547b5a 100644 --- a/crates/weft-ipc-types/src/trust.rs +++ b/crates/weft-ipc-types/src/trust.rs @@ -56,17 +56,40 @@ fn io(path: &Path) -> impl FnOnce(std::io::Error) -> TrustError + '_ { /// The SHA-256 content digest a package signature covers. pub fn content_digest(package_root: &Path) -> Result<[u8; 32], TrustError> { - let mut entries = Vec::new(); - collect(package_root, package_root, &mut entries)?; - entries.sort(); - let mut inventory = String::new(); - for (path, hash) in &entries { - inventory.push_str(path); - inventory.push('\t'); - inventory.push_str(&hex::encode(hash)); - inventory.push('\n'); + Inventory::read(package_root).map(|inventory| inventory.digest()) +} + +/// The files of a package and their SHA-256 hashes, as read once: the digest +/// and the hash of any one file come from the same reading. +#[derive(Debug)] +pub struct Inventory(Vec<(String, [u8; 32])>); + +impl Inventory { + pub fn read(package_root: &Path) -> Result { + let mut entries = Vec::new(); + collect(package_root, package_root, &mut entries)?; + entries.sort(); + Ok(Self(entries)) + } + + /// The content digest a package signature covers. + pub fn digest(&self) -> [u8; 32] { + let mut inventory = String::new(); + for (path, hash) in &self.0 { + inventory.push_str(path); + inventory.push('\t'); + inventory.push_str(&hex::encode(hash)); + inventory.push('\n'); + } + Sha256::digest(inventory.as_bytes()).into() + } + + /// Whether the file at `path`, relative to the package root, had exactly + /// these bytes when the inventory was read. + pub fn holds(&self, path: &str, bytes: &[u8]) -> bool { + let hash: [u8; 32] = Sha256::digest(bytes).into(); + self.0.iter().any(|(p, h)| p == path && *h == hash) } - Ok(Sha256::digest(inventory.as_bytes()).into()) } fn collect( @@ -220,12 +243,15 @@ impl TrustStore { let Some(signature) = read_signature(package_root)? else { return Ok(None); }; - let digest = content_digest(package_root)?; - Ok(self - .keys + Ok(self.signer_of(&content_digest(package_root)?, &signature)) + } + + /// The trusted key that made `signature` over `digest`, if any. + pub fn signer_of(&self, digest: &[u8; 32], signature: &Signature) -> Option { + self.keys .iter() .copied() - .find(|k| k.signed(&digest, &signature))) + .find(|k| k.signed(digest, signature)) } } @@ -409,6 +435,17 @@ mod tests { std::fs::remove_dir_all(&dir).unwrap(); } + #[test] + fn an_inventory_knows_the_bytes_it_hashed() { + let dir = dir("inventory"); + let inventory = Inventory::read(&dir).unwrap(); + assert_eq!(inventory.digest(), content_digest(&dir).unwrap()); + assert!(inventory.holds("wapp.toml", b"[package]\n")); + assert!(!inventory.holds("wapp.toml", b"[package]\ncapabilities = []\n")); + assert!(!inventory.holds("absent.toml", b"[package]\n")); + std::fs::remove_dir_all(&dir).unwrap(); + } + #[test] fn owner_locks_exclude_each_other() { let home = std::env::temp_dir().join(format!("weft_trust_lock_{}", std::process::id())); diff --git a/docs/security.md b/docs/security.md index 12016fa..24c289d 100644 --- a/docs/security.md +++ b/docs/security.md @@ -26,7 +26,7 @@ Packages are signed with Ed25519 over their content digest: the SHA-256 of an in The first installation of an app ID records its owner in `$XDG_DATA_HOME/weft/owners/`: the publisher key, or development. Installations and uninstallations of one ID under one data home hold a per-ID lock, so concurrent installations cannot leave a placed package without its record. Every later installation of that ID must have the same owner, so neither another trusted publisher nor a development build can take over an ID, and with it the app's data. The record survives uninstall while the app's data remains; uninstalling with no data left frees the ID. App data with no recorded owner, as left by installations from before owner records, is given to a new owner only with `--claim-data`. A record is written under a temporary name and linked into place, so it is never partial, and a record created by an installation that then fails to place its package is removed. A record left by an installation that was killed before placing its package is released by `weft-pack uninstall ` once no data remains. A record is only released while no known store (the user store, the system store and `$WEFT_APP_STORE`) holds the package; a package installed into another custom store is uninstalled with that store selected. The demo key in `examples/keys` is a test fixture, not a signing authority. -`weft-appd` checks every package again before a session starts. A package recorded as a publisher's runs only while that key is still trusted and its signature covers the package's current content; a package with no record runs only when a trusted key signed it; development content runs unverified. A changed package, or one whose key was removed from the trust store, is refused with code 403. The check reads the package before the session starts, so a directory install changed by its owning user while the session runs is not detected; verified images are not writable. +`weft-appd` checks every package again before a session starts. A package recorded as a publisher's runs only while that key is still trusted and its signature covers the package's current content. A package with no record runs only when a trusted key signed it, and that key is then recorded as its owner; if app data already exists for the ID without a recorded owner, the launch is refused rather than handing the data to that publisher. While an ID is recorded as development content, whatever package is found for it runs unverified, from any store. A changed package, or one whose key was removed from the trust store, is refused with code 403; a damaged trust store or owner record is a host error, 500. The manifest is read once and its bytes must be the ones in the verified inventory, so a session's capabilities and entries come from the signed manifest. The module and UI files are read again when the session starts, so a directory install changed by its owning user after the check, or while the session runs, is not detected; verified images are not writable. Not yet covered: key rotation and ownership transfer have no workflow, and removing a key is the only revocation; and capabilities are granted at launch without asking the user, independently of the signature. diff --git a/tests/frame/check_confinement.py b/tests/frame/check_confinement.py index d027921..88e76f8 100644 --- a/tests/frame/check_confinement.py +++ b/tests/frame/check_confinement.py @@ -146,7 +146,7 @@ def make_package(store, http_port, ws_port, other_dir): # planted directly and recorded as development content, which runs # unverified: the renderer's own confinement is what this check probes. record = store / "home/share/weft/owners" / APP_ID - record.parent.mkdir(parents=True) + record.parent.mkdir(parents=True, exist_ok=True) record.write_text("development\n") diff --git a/tests/frame/check_counter.py b/tests/frame/check_counter.py index 0da4e88..33086ef 100644 --- a/tests/frame/check_counter.py +++ b/tests/frame/check_counter.py @@ -158,11 +158,17 @@ def count_area(screenshot, card): def run(args, desktop, xdotool): port = free_port() target = Path(args.target) + # A private home, so owner records appd writes stay out of the user's. + home = args.output / "home" + shutil.rmtree(home, ignore_errors=True) + home.mkdir(parents=True) desktop.launch_client("appd", [target / "weft-appd"], { "WEFT_RUNTIME_BIN": str(target / "weft-runtime"), "WEFT_APP_SHELL_BIN": str(target / "weft-app-shell"), "WEFT_APP_STORE": str(args.store), "WEFT_TRUSTED_KEYS": str(ROOT / "examples/keys"), + "HOME": str(home), + "XDG_DATA_HOME": str(home / "share"), "WEFT_DISABLE_CGROUP": "1", "WEFT_APPD_WS_PORT": str(port), }) diff --git a/tests/frame/check_notes.py b/tests/frame/check_notes.py index 6ee3cba..42f3d47 100644 --- a/tests/frame/check_notes.py +++ b/tests/frame/check_notes.py @@ -69,6 +69,12 @@ def run(args, desktop, home, xdotool): notes = data_home / "weft/app-data" / APP_ID / "notes.txt" notes.parent.mkdir(parents=True) notes.write_text(SEED, encoding="utf-8") + # The seeded data belongs to the demo publisher, as installing the signed + # package with weft-pack would have recorded. + owner = data_home / "weft/owners" / APP_ID + owner.parent.mkdir(parents=True) + key = (ROOT / "examples/keys/weft-sign.pub").read_text().strip() + owner.write_text(f"verified {key}\n") t = Path(args.target) desktop.launch_client("appd", [t / "weft-appd"], { From 95db80a86d4c206e3e962197c729c603b74b0099 Mon Sep 17 00:00:00 2001 From: Marco Allegretti Date: Fri, 9 Oct 2026 14:41:23 +0000 Subject: [PATCH 3/5] fix(appd): count app data in the earlier layout as existing before recording an owner App data in the earlier layout, /.local/share/weft/apps//data, is migrated to the app data directory after the owner check, so a trusted package from another store could be recorded as owner on its first launch and then receive that data. Both layouts now count as existing data, in weft-appd and in weft-pack install, so unowned data is only given away with --claim-data. The refusal says how to claim it. Stale test data homes are removed only when their process has exited, and the app-data check records the owner of the data it seeds. --- crates/weft-appd/src/launch.rs | 102 +++++++++++++++++++++------ crates/weft-appd/src/main.rs | 4 +- crates/weft-ipc-types/src/package.rs | 24 +++++++ crates/weft-pack/src/main.rs | 38 ++++++++-- docs/security.md | 2 +- tests/frame/check_app_data.py | 6 ++ 6 files changed, 146 insertions(+), 30 deletions(-) diff --git a/crates/weft-appd/src/launch.rs b/crates/weft-appd/src/launch.rs index 8f8f2cc..f12c6bb 100644 --- a/crates/weft-appd/src/launch.rs +++ b/crates/weft-appd/src/launch.rs @@ -213,28 +213,29 @@ fn record_first_owner( } None => {} } - let data = weft_ipc_types::package::app_data_dir(data_home, app_id); - match std::fs::symlink_metadata(&data) { - Err(e) if e.kind() == std::io::ErrorKind::NotFound => {} - Err(e) => { - return Err(Refusal::new( - 500, - format!("cannot inspect {}: {e}", data.display()), - )); - } - Ok(_) => { - return Err(Refusal::new( - 403, - format!( - "{} holds app data for {app_id} with no recorded owner; it is not given to \ - publisher {} without weft-pack install --claim-data", - data.display(), - signer.to_hex() - ), - )); - } + // Data in the earlier layout counts: it would be moved to this app's + // data directory when the session starts. + let home = std::env::var_os("HOME") + .map(std::path::PathBuf::from) + .filter(|home| home.is_absolute()); + match weft_ipc_types::package::existing_app_data(data_home, home.as_deref(), app_id) { + Err(e) => Err(Refusal::new( + 500, + format!("cannot inspect the app data of {app_id}: {e}"), + )), + Ok(Some(data)) => Err(Refusal::new( + 403, + format!( + "{} holds app data for {app_id} with no recorded owner, so it is not given to \ + publisher {}. To give it to this publisher, install the package into the user \ + store with weft-pack install --claim-data (uninstalling it there first); \ + otherwise move the data aside", + data.display(), + signer.to_hex() + ), + )), + Ok(None) => write_owner(record, Owner::Verified(signer)).map_err(host), } - write_owner(record, Owner::Verified(signer)).map_err(host) } impl LaunchPackage { @@ -457,6 +458,65 @@ mod tests { assert_eq!(owner, None); } + #[test] + fn unowned_data_in_the_earlier_layout_is_not_given_away() { + let _env = crate::tests::env_lock().blocking_lock(); + let store = demo_store("legacy_data", true); + let home = store.join("home"); + let legacy = weft_ipc_types::package::legacy_app_data_dir(&home, DEMO); + std::fs::create_dir_all(&legacy).unwrap(); + let prior = std::env::var_os("HOME"); + // SAFETY: env_lock is held. + unsafe { std::env::set_var("HOME", &home) }; + let refused = refusal(resolve(DEMO)); + unsafe { + match prior { + Some(v) => std::env::set_var("HOME", v), + None => std::env::remove_var("HOME"), + } + } + let owner = read_owner(&owner_record_path(&store.join("share"), DEMO)).unwrap(); + finish(&store); + assert_eq!(refused.code, 403, "{}", refused.message); + assert!( + refused.message.contains("no recorded owner"), + "{}", + refused.message + ); + assert_eq!(owner, None); + } + + #[test] + fn only_the_signed_manifest_is_accepted() { + let _env = crate::tests::env_lock().blocking_lock(); + let store = demo_store("manifest", true); + record(&store, DEMO, Owner::Verified(demo_key())); + let root = store.join(DEMO); + let signed = std::fs::read(root.join(MANIFEST_FILE)).unwrap(); + let mut other = signed.clone(); + other.extend_from_slice(b"\n# other\n"); + let accepted = verify_owner(DEMO, &root, &signed); + let refused = verify_owner(DEMO, &root, &other).err(); + finish(&store); + assert!(accepted.is_ok()); + let refused = refused.expect("a manifest that was not signed was accepted"); + assert_eq!(refused.code, 403, "{}", refused.message); + } + + #[test] + fn development_content_does_not_depend_on_the_trust_store() { + let _env = crate::tests::env_lock().blocking_lock(); + let store = store("dev_store", ID, "app.wasm"); + let keys = store.join("keys"); + std::fs::create_dir_all(&keys).unwrap(); + std::fs::write(keys.join("broken.pub"), "not a key").unwrap(); + // SAFETY: as in `store`. + unsafe { std::env::set_var("WEFT_TRUSTED_KEYS", &keys) }; + let resolved = resolve(ID).map(|p| p.root); + finish(&store); + assert_eq!(resolved.ok(), Some(store.join(ID))); + } + #[test] fn a_damaged_trust_store_or_record_is_a_host_error() { let _env = crate::tests::env_lock().blocking_lock(); diff --git a/crates/weft-appd/src/main.rs b/crates/weft-appd/src/main.rs index 0df9632..3956896 100644 --- a/crates/weft-appd/src/main.rs +++ b/crates/weft-appd/src/main.rs @@ -723,10 +723,12 @@ mod tests { let name = format!("weft-appd-tests-data-{}", std::process::id()); if let Ok(entries) = std::fs::read_dir(std::env::temp_dir()) { for entry in entries.flatten() { + // Only data homes of test processes that have exited. let stale = entry .file_name() .to_str() - .is_some_and(|n| n.starts_with("weft-appd-tests-data-") && n != name); + .and_then(|n| n.strip_prefix("weft-appd-tests-data-")) + .is_some_and(|pid| !std::path::Path::new("/proc").join(pid).exists()); if stale { let _ = std::fs::remove_dir_all(entry.path()); } diff --git a/crates/weft-ipc-types/src/package.rs b/crates/weft-ipc-types/src/package.rs index 6018c3a..ac9b5b2 100644 --- a/crates/weft-ipc-types/src/package.rs +++ b/crates/weft-ipc-types/src/package.rs @@ -79,6 +79,30 @@ pub fn legacy_app_data_dir(home: &Path, app_id: &str) -> PathBuf { .join("data") } +/// Where app data for `app_id` already exists, in the current layout or in +/// the earlier one under `home`, if anywhere. Data in the earlier layout is +/// moved to the current one when the app next launches, so it counts too. +pub fn existing_app_data( + data_home: &Path, + home: Option<&Path>, + app_id: &str, +) -> std::io::Result> { + let places = std::iter::once(app_data_dir(data_home, app_id)) + .chain(home.map(|home| legacy_app_data_dir(home, app_id))); + for place in places { + match std::fs::symlink_metadata(&place) { + Ok(_) => return Ok(Some(place)), + Err(e) + if matches!( + e.kind(), + std::io::ErrorKind::NotFound | std::io::ErrorKind::NotADirectory + ) => {} + Err(e) => return Err(e), + } + } + Ok(None) +} + /// The result of moving data from the earlier layout. #[derive(Debug, PartialEq, Eq)] pub enum Migration { diff --git a/crates/weft-pack/src/main.rs b/crates/weft-pack/src/main.rs index b76cbd1..9b0cd87 100644 --- a/crates/weft-pack/src/main.rs +++ b/crates/weft-pack/src/main.rs @@ -491,13 +491,15 @@ fn admit( its owner, so another publisher or a development build cannot take the ID over" ), None => { - let data = weft_ipc_types::package::app_data_dir(data_home, app_id); - let no_data = match std::fs::symlink_metadata(&data) { - Err(e) if e.kind() == std::io::ErrorKind::NotFound => true, - Err(e) => return Err(e).with_context(|| format!("inspect {}", data.display())), - Ok(_) => false, - }; - if !no_data && !claim_data { + // Data in the earlier layout counts: weft-appd moves it to the + // app's data directory when the app next launches. + let home = std::env::var_os("HOME") + .map(PathBuf::from) + .filter(|home| home.is_absolute()); + let existing = + weft_ipc_types::package::existing_app_data(data_home, home.as_deref(), app_id) + .with_context(|| format!("inspect the app data of {app_id}"))?; + if let Some(data) = existing.filter(|_| !claim_data) { anyhow::bail!( "{} holds app data for {app_id} with no recorded owner; install with \ --claim-data to give it to {owner}, or move it aside", @@ -1399,6 +1401,28 @@ mod tests { let _ = std::fs::remove_dir_all(&home); } + #[test] + fn unowned_data_in_the_earlier_layout_needs_a_claim() { + let home = temp_root("legacy_claim"); + let app_id = "org.weft.test.legacyclaim"; + write_package(&home.join("src"), app_id, APP_DATA); + let legacy = weft_ipc_types::package::legacy_app_data_dir(&home, app_id); + std::fs::create_dir_all(&legacy).unwrap(); + let other = home.join("other"); + let unclaimed = with_home(&home, || { + install_package_to(&home.join("src"), &other, InstallMode::Development) + }); + let message = format!("{:#}", unclaimed.unwrap_err()); + 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) + }) + .unwrap(); + assert_eq!(owner_of(&home, app_id), Some(Owner::Development)); + let _ = std::fs::remove_dir_all(&home); + } + #[test] fn uninstalling_one_of_two_copies_keeps_the_record() { let home = temp_root("two_copies"); diff --git a/docs/security.md b/docs/security.md index 24c289d..8987b0d 100644 --- a/docs/security.md +++ b/docs/security.md @@ -26,7 +26,7 @@ Packages are signed with Ed25519 over their content digest: the SHA-256 of an in The first installation of an app ID records its owner in `$XDG_DATA_HOME/weft/owners/`: the publisher key, or development. Installations and uninstallations of one ID under one data home hold a per-ID lock, so concurrent installations cannot leave a placed package without its record. Every later installation of that ID must have the same owner, so neither another trusted publisher nor a development build can take over an ID, and with it the app's data. The record survives uninstall while the app's data remains; uninstalling with no data left frees the ID. App data with no recorded owner, as left by installations from before owner records, is given to a new owner only with `--claim-data`. A record is written under a temporary name and linked into place, so it is never partial, and a record created by an installation that then fails to place its package is removed. A record left by an installation that was killed before placing its package is released by `weft-pack uninstall ` once no data remains. A record is only released while no known store (the user store, the system store and `$WEFT_APP_STORE`) holds the package; a package installed into another custom store is uninstalled with that store selected. The demo key in `examples/keys` is a test fixture, not a signing authority. -`weft-appd` checks every package again before a session starts. A package recorded as a publisher's runs only while that key is still trusted and its signature covers the package's current content. A package with no record runs only when a trusted key signed it, and that key is then recorded as its owner; if app data already exists for the ID without a recorded owner, the launch is refused rather than handing the data to that publisher. While an ID is recorded as development content, whatever package is found for it runs unverified, from any store. A changed package, or one whose key was removed from the trust store, is refused with code 403; a damaged trust store or owner record is a host error, 500. The manifest is read once and its bytes must be the ones in the verified inventory, so a session's capabilities and entries come from the signed manifest. The module and UI files are read again when the session starts, so a directory install changed by its owning user after the check, or while the session runs, is not detected; verified images are not writable. +`weft-appd` checks every package again before a session starts. A package recorded as a publisher's runs only while that key is still trusted and its signature covers the package's current content. A package with no record runs only when a trusted key signed it, and that key is then recorded as its owner; if app data already exists for the ID without a recorded owner, in the current layout or the earlier one that is migrated at launch, the launch is refused rather than handing the data to that publisher; `weft-pack install` applies the same rule unless given `--claim-data`. The record is written before the session starts, so it remains even if that first launch then fails; `weft-pack uninstall` releases it once no data exists and no known store holds the package. While an ID is recorded as development content, whatever package is found for it runs unverified, from any store. A changed package, or one whose key was removed from the trust store, is refused with code 403; a damaged trust store or owner record is a host error, 500. The manifest is read once and its bytes must be the ones in the verified inventory, so a session's capabilities and entries come from the signed manifest. The module and UI files are read again when the session starts, so a directory install changed by its owning user after the check, or while the session runs, is not detected; verified images are not writable. Not yet covered: key rotation and ownership transfer have no workflow, and removing a key is the only revocation; and capabilities are granted at launch without asking the user, independently of the signature. diff --git a/tests/frame/check_app_data.py b/tests/frame/check_app_data.py index 50d10e2..d1fad5e 100644 --- a/tests/frame/check_app_data.py +++ b/tests/frame/check_app_data.py @@ -41,6 +41,12 @@ def run(args, desktop, home, xdotool): (legacy / "notes.txt").write_bytes(NOTES) data_home = home / "data-home" target = data_home / "weft/app-data" / APP_ID + # The earlier data belongs to the demo publisher, as installing the + # signed package with weft-pack would have recorded. + owner = data_home / "weft/owners" / APP_ID + owner.parent.mkdir(parents=True) + key = (ROOT / "examples/keys/weft-sign.pub").read_text().strip() + owner.write_text(f"verified {key}\n") t = Path(args.target) desktop.launch_client("appd", [t / "weft-appd"], { From d3adced897b2276e9cc3b77b029fb15e1aaf1480 Mon Sep 17 00:00:00 2001 From: Marco Allegretti Date: Fri, 9 Oct 2026 14:46:21 +0000 Subject: [PATCH 4/5] fix(appd): require a usable HOME for ownership decisions and keep records for earlier-layout data Without an absolute HOME the earlier data layout could not be checked, so a first-launch or install owner record was written anyway and that data was migrated to the new owner later. Both now refuse instead. Uninstall keeps an owner record while data exists in either layout, or while it cannot tell. Launch tests use a private HOME, and the test data-home cleanup never removes the running process's own. --- crates/weft-appd/src/launch.rs | 29 ++++++++++++++-------------- crates/weft-appd/src/main.rs | 1 + crates/weft-ipc-types/src/package.rs | 15 +++++++++++--- crates/weft-pack/src/main.rs | 28 ++++++++++++++++++--------- docs/security.md | 2 +- tests/frame/check_app_data.py | 5 +++-- 6 files changed, 50 insertions(+), 30 deletions(-) diff --git a/crates/weft-appd/src/launch.rs b/crates/weft-appd/src/launch.rs index f12c6bb..10203d6 100644 --- a/crates/weft-appd/src/launch.rs +++ b/crates/weft-appd/src/launch.rs @@ -215,10 +215,9 @@ fn record_first_owner( } // Data in the earlier layout counts: it would be moved to this app's // data directory when the session starts. - let home = std::env::var_os("HOME") - .map(std::path::PathBuf::from) - .filter(|home| home.is_absolute()); - match weft_ipc_types::package::existing_app_data(data_home, home.as_deref(), app_id) { + let home = weft_ipc_types::package::home_dir() + .ok_or_else(|| Refusal::new(500, "HOME is not set to an absolute path"))?; + match weft_ipc_types::package::existing_app_data(data_home, &home, app_id) { Err(e) => Err(Refusal::new( 500, format!("cannot inspect the app data of {app_id}: {e}"), @@ -264,6 +263,10 @@ mod tests { const ID: &str = "org.weft.test.resolve"; + /// HOME as the test process found it, restored by `finish`. + static HOME_AT_START: std::sync::OnceLock> = + std::sync::OnceLock::new(); + /// A store holding a directory install of `ID`, with WEFT_APP_STORE /// pointing at it. Callers hold env_lock. fn store(name: &str, manifest_id: &str, module: &str) -> PathBuf { @@ -289,10 +292,12 @@ mod tests { Owner::Development, ) .unwrap(); + HOME_AT_START.get_or_init(|| std::env::var_os("HOME")); // SAFETY: callers hold env_lock, which serialises environment changes. unsafe { std::env::set_var("WEFT_APP_STORE", &store); std::env::set_var("XDG_DATA_HOME", store.join("share")); + std::env::set_var("HOME", store.join("home")); } store } @@ -304,6 +309,10 @@ mod tests { std::env::remove_var("WEFT_MOUNT_HELPER"); std::env::remove_var("XDG_DATA_HOME"); std::env::remove_var("WEFT_TRUSTED_KEYS"); + match HOME_AT_START.get() { + Some(Some(home)) => std::env::set_var("HOME", home), + _ => std::env::remove_var("HOME"), + } } let _ = std::fs::remove_dir_all(store); } @@ -462,19 +471,9 @@ mod tests { fn unowned_data_in_the_earlier_layout_is_not_given_away() { let _env = crate::tests::env_lock().blocking_lock(); let store = demo_store("legacy_data", true); - let home = store.join("home"); - let legacy = weft_ipc_types::package::legacy_app_data_dir(&home, DEMO); + let legacy = weft_ipc_types::package::legacy_app_data_dir(&store.join("home"), DEMO); std::fs::create_dir_all(&legacy).unwrap(); - let prior = std::env::var_os("HOME"); - // SAFETY: env_lock is held. - unsafe { std::env::set_var("HOME", &home) }; let refused = refusal(resolve(DEMO)); - unsafe { - match prior { - Some(v) => std::env::set_var("HOME", v), - None => std::env::remove_var("HOME"), - } - } let owner = read_owner(&owner_record_path(&store.join("share"), DEMO)).unwrap(); finish(&store); assert_eq!(refused.code, 403, "{}", refused.message); diff --git a/crates/weft-appd/src/main.rs b/crates/weft-appd/src/main.rs index 3956896..a681762 100644 --- a/crates/weft-appd/src/main.rs +++ b/crates/weft-appd/src/main.rs @@ -727,6 +727,7 @@ mod tests { let stale = entry .file_name() .to_str() + .filter(|n| *n != name) .and_then(|n| n.strip_prefix("weft-appd-tests-data-")) .is_some_and(|pid| !std::path::Path::new("/proc").join(pid).exists()); if stale { diff --git a/crates/weft-ipc-types/src/package.rs b/crates/weft-ipc-types/src/package.rs index ac9b5b2..9da0a2f 100644 --- a/crates/weft-ipc-types/src/package.rs +++ b/crates/weft-ipc-types/src/package.rs @@ -79,16 +79,25 @@ pub fn legacy_app_data_dir(home: &Path, app_id: &str) -> PathBuf { .join("data") } +/// The home directory, when `HOME` is set to an absolute path. +pub fn home_dir() -> Option { + std::env::var_os("HOME") + .map(PathBuf::from) + .filter(|home| home.is_absolute()) +} + /// Where app data for `app_id` already exists, in the current layout or in /// the earlier one under `home`, if anywhere. Data in the earlier layout is /// moved to the current one when the app next launches, so it counts too. pub fn existing_app_data( data_home: &Path, - home: Option<&Path>, + home: &Path, app_id: &str, ) -> std::io::Result> { - let places = std::iter::once(app_data_dir(data_home, app_id)) - .chain(home.map(|home| legacy_app_data_dir(home, app_id))); + let places = [ + app_data_dir(data_home, app_id), + legacy_app_data_dir(home, app_id), + ]; for place in places { match std::fs::symlink_metadata(&place) { Ok(_) => return Ok(Some(place)), diff --git a/crates/weft-pack/src/main.rs b/crates/weft-pack/src/main.rs index 9b0cd87..66ba655 100644 --- a/crates/weft-pack/src/main.rs +++ b/crates/weft-pack/src/main.rs @@ -493,12 +493,11 @@ fn admit( None => { // Data in the earlier layout counts: weft-appd moves it to the // app's data directory when the app next launches. - let home = std::env::var_os("HOME") - .map(PathBuf::from) - .filter(|home| home.is_absolute()); - let existing = - weft_ipc_types::package::existing_app_data(data_home, home.as_deref(), app_id) - .with_context(|| format!("inspect the app data of {app_id}"))?; + let home = weft_ipc_types::package::home_dir().context( + "HOME is not set to an absolute path, so earlier app data cannot be found", + )?; + let existing = weft_ipc_types::package::existing_app_data(data_home, &home, app_id) + .with_context(|| format!("inspect the app data of {app_id}"))?; if let Some(data) = existing.filter(|_| !claim_data) { anyhow::bail!( "{} holds app data for {app_id} with no recorded owner; install with \ @@ -602,9 +601,13 @@ fn installed_in_another_store(app_id: &str, store_root: &Path) -> bool { /// Removes the owner record of `app_id` when the app has no data, and /// reports whether a record was removed. fn release_owner_without_data(data_home: &Path, app_id: &str) -> bool { - let no_data = - std::fs::symlink_metadata(weft_ipc_types::package::app_data_dir(data_home, app_id)) - .is_err_and(|e| e.kind() == std::io::ErrorKind::NotFound); + // Data in either layout keeps the record; so does not being able to look. + let no_data = weft_ipc_types::package::home_dir().is_some_and(|home| { + matches!( + weft_ipc_types::package::existing_app_data(data_home, &home, app_id), + Ok(None) + ) + }); no_data && std::fs::remove_file(weft_ipc_types::trust::owner_record_path(data_home, app_id)).is_ok() } @@ -1343,6 +1346,13 @@ mod tests { std::fs::remove_dir_all(&data).unwrap(); with_home(&home, || uninstall_package_from(app_id, &store)).unwrap(); assert!(!record.exists()); + + // Data in the earlier layout keeps the record too. + weft_ipc_types::trust::write_owner(&record, Owner::Development).unwrap(); + let legacy = weft_ipc_types::package::legacy_app_data_dir(&home, app_id); + std::fs::create_dir_all(&legacy).unwrap(); + assert!(with_home(&home, || uninstall_package_from(app_id, &store)).is_err()); + assert!(record.exists()); let _ = std::fs::remove_dir_all(&home); } diff --git a/docs/security.md b/docs/security.md index 8987b0d..39020fc 100644 --- a/docs/security.md +++ b/docs/security.md @@ -26,7 +26,7 @@ Packages are signed with Ed25519 over their content digest: the SHA-256 of an in The first installation of an app ID records its owner in `$XDG_DATA_HOME/weft/owners/`: the publisher key, or development. Installations and uninstallations of one ID under one data home hold a per-ID lock, so concurrent installations cannot leave a placed package without its record. Every later installation of that ID must have the same owner, so neither another trusted publisher nor a development build can take over an ID, and with it the app's data. The record survives uninstall while the app's data remains; uninstalling with no data left frees the ID. App data with no recorded owner, as left by installations from before owner records, is given to a new owner only with `--claim-data`. A record is written under a temporary name and linked into place, so it is never partial, and a record created by an installation that then fails to place its package is removed. A record left by an installation that was killed before placing its package is released by `weft-pack uninstall ` once no data remains. A record is only released while no known store (the user store, the system store and `$WEFT_APP_STORE`) holds the package; a package installed into another custom store is uninstalled with that store selected. The demo key in `examples/keys` is a test fixture, not a signing authority. -`weft-appd` checks every package again before a session starts. A package recorded as a publisher's runs only while that key is still trusted and its signature covers the package's current content. A package with no record runs only when a trusted key signed it, and that key is then recorded as its owner; if app data already exists for the ID without a recorded owner, in the current layout or the earlier one that is migrated at launch, the launch is refused rather than handing the data to that publisher; `weft-pack install` applies the same rule unless given `--claim-data`. The record is written before the session starts, so it remains even if that first launch then fails; `weft-pack uninstall` releases it once no data exists and no known store holds the package. While an ID is recorded as development content, whatever package is found for it runs unverified, from any store. A changed package, or one whose key was removed from the trust store, is refused with code 403; a damaged trust store or owner record is a host error, 500. The manifest is read once and its bytes must be the ones in the verified inventory, so a session's capabilities and entries come from the signed manifest. The module and UI files are read again when the session starts, so a directory install changed by its owning user after the check, or while the session runs, is not detected; verified images are not writable. +`weft-appd` checks every package again before a session starts. A package recorded as a publisher's runs only while that key is still trusted and its signature covers the package's current content. A package with no record runs only when a trusted key signed it, and that key is then recorded as its owner; if app data already exists for the ID without a recorded owner, in the current layout or the earlier one that is migrated at launch, the launch is refused rather than handing the data to that publisher; `weft-pack install` applies the same rule unless given `--claim-data`. The record is written before the session starts, so it remains even if that first launch then fails; `weft-pack uninstall` releases it once no data exists in either layout and no known store holds the package. Upgrading from installations made before owner records: data with no record is refused at launch until it is claimed. While an ID is recorded as development content, whatever package is found for it runs unverified, from any store. A changed package, or one whose key was removed from the trust store, is refused with code 403; a damaged trust store or owner record is a host error, 500. The manifest is read once and its bytes must be the ones in the verified inventory, so a session's capabilities and entries come from the signed manifest. The module and UI files are read again when the session starts, so a directory install changed by its owning user after the check, or while the session runs, is not detected; verified images are not writable. Not yet covered: key rotation and ownership transfer have no workflow, and removing a key is the only revocation; and capabilities are granted at launch without asking the user, independently of the signature. diff --git a/tests/frame/check_app_data.py b/tests/frame/check_app_data.py index d1fad5e..95130af 100644 --- a/tests/frame/check_app_data.py +++ b/tests/frame/check_app_data.py @@ -41,8 +41,9 @@ def run(args, desktop, home, xdotool): (legacy / "notes.txt").write_bytes(NOTES) data_home = home / "data-home" target = data_home / "weft/app-data" / APP_ID - # The earlier data belongs to the demo publisher, as installing the - # signed package with weft-pack would have recorded. + # The earlier data is recorded as the demo publisher's. Data from before + # owner records has no record and is refused until claimed with + # weft-pack install --claim-data. owner = data_home / "weft/owners" / APP_ID owner.parent.mkdir(parents=True) key = (ROOT / "examples/keys/weft-sign.pub").read_text().strip() From af6f716823b3727a8a3fbbc28b8cbe783395dfa2 Mon Sep 17 00:00:00 2001 From: Marco Allegretti Date: Fri, 9 Oct 2026 14:56:42 +0000 Subject: [PATCH 5/5] fix(pack): let --claim-data install without HOME and test HOME refusals Claiming data does not depend on finding earlier-layout data, so an install that claims it no longer needs HOME. Tests cover a first launch and a first install with an unusable HOME refusing and recording no owner, and the security docs state the HOME requirement. --- crates/weft-appd/src/launch.rs | 13 +++++++++++++ crates/weft-pack/src/main.rs | 24 +++++++++++++++++++++++- docs/security.md | 2 +- 3 files changed, 37 insertions(+), 2 deletions(-) diff --git a/crates/weft-appd/src/launch.rs b/crates/weft-appd/src/launch.rs index 10203d6..89efc67 100644 --- a/crates/weft-appd/src/launch.rs +++ b/crates/weft-appd/src/launch.rs @@ -485,6 +485,19 @@ mod tests { assert_eq!(owner, None); } + #[test] + fn a_first_launch_without_a_usable_home_records_nothing() { + let _env = crate::tests::env_lock().blocking_lock(); + let store = demo_store("no_home", true); + // SAFETY: env_lock is held; finish restores HOME. + unsafe { std::env::set_var("HOME", "relative") }; + let refused = refusal(resolve(DEMO)); + let owner = read_owner(&owner_record_path(&store.join("share"), DEMO)).unwrap(); + finish(&store); + assert_eq!(refused.code, 500, "{}", refused.message); + assert_eq!(owner, None); + } + #[test] fn only_the_signed_manifest_is_accepted() { let _env = crate::tests::env_lock().blocking_lock(); diff --git a/crates/weft-pack/src/main.rs b/crates/weft-pack/src/main.rs index 66ba655..c8f56c1 100644 --- a/crates/weft-pack/src/main.rs +++ b/crates/weft-pack/src/main.rs @@ -490,6 +490,10 @@ fn admit( "{app_id} belongs to {existing}; this package is {owner}. Its app data stays with \ its owner, so another publisher or a development build cannot take the ID over" ), + None if claim_data => { + write_owner(&record, owner)?; + Some(record) + } None => { // Data in the earlier layout counts: weft-appd moves it to the // app's data directory when the app next launches. @@ -498,7 +502,7 @@ fn admit( )?; let existing = weft_ipc_types::package::existing_app_data(data_home, &home, app_id) .with_context(|| format!("inspect the app data of {app_id}"))?; - if let Some(data) = existing.filter(|_| !claim_data) { + if let Some(data) = existing { anyhow::bail!( "{} holds app data for {app_id} with no recorded owner; install with \ --claim-data to give it to {owner}, or move it aside", @@ -1433,6 +1437,24 @@ mod tests { let _ = std::fs::remove_dir_all(&home); } + #[test] + fn a_first_install_without_a_usable_home_records_nothing() { + let home = temp_root("no_home"); + let app_id = "org.weft.test.nohome"; + write_package(&home.join("src"), app_id, ""); + let store = home.join("store"); + let refused = with_home(&home, || { + // SAFETY: with_home holds env_lock and restores HOME afterwards. + unsafe { std::env::set_var("HOME", "relative") }; + install_package_to(&home.join("src"), &store, InstallMode::Development) + }); + let message = format!("{:#}", refused.unwrap_err()); + assert!(message.contains("HOME"), "{message}"); + assert_eq!(owner_of(&home, app_id), None); + assert!(!store.join(app_id).exists()); + let _ = std::fs::remove_dir_all(&home); + } + #[test] fn uninstalling_one_of_two_copies_keeps_the_record() { let home = temp_root("two_copies"); diff --git a/docs/security.md b/docs/security.md index 39020fc..55bdf1d 100644 --- a/docs/security.md +++ b/docs/security.md @@ -26,7 +26,7 @@ Packages are signed with Ed25519 over their content digest: the SHA-256 of an in The first installation of an app ID records its owner in `$XDG_DATA_HOME/weft/owners/`: the publisher key, or development. Installations and uninstallations of one ID under one data home hold a per-ID lock, so concurrent installations cannot leave a placed package without its record. Every later installation of that ID must have the same owner, so neither another trusted publisher nor a development build can take over an ID, and with it the app's data. The record survives uninstall while the app's data remains; uninstalling with no data left frees the ID. App data with no recorded owner, as left by installations from before owner records, is given to a new owner only with `--claim-data`. A record is written under a temporary name and linked into place, so it is never partial, and a record created by an installation that then fails to place its package is removed. A record left by an installation that was killed before placing its package is released by `weft-pack uninstall ` once no data remains. A record is only released while no known store (the user store, the system store and `$WEFT_APP_STORE`) holds the package; a package installed into another custom store is uninstalled with that store selected. The demo key in `examples/keys` is a test fixture, not a signing authority. -`weft-appd` checks every package again before a session starts. A package recorded as a publisher's runs only while that key is still trusted and its signature covers the package's current content. A package with no record runs only when a trusted key signed it, and that key is then recorded as its owner; if app data already exists for the ID without a recorded owner, in the current layout or the earlier one that is migrated at launch, the launch is refused rather than handing the data to that publisher; `weft-pack install` applies the same rule unless given `--claim-data`. The record is written before the session starts, so it remains even if that first launch then fails; `weft-pack uninstall` releases it once no data exists in either layout and no known store holds the package. Upgrading from installations made before owner records: data with no record is refused at launch until it is claimed. While an ID is recorded as development content, whatever package is found for it runs unverified, from any store. A changed package, or one whose key was removed from the trust store, is refused with code 403; a damaged trust store or owner record is a host error, 500. The manifest is read once and its bytes must be the ones in the verified inventory, so a session's capabilities and entries come from the signed manifest. The module and UI files are read again when the session starts, so a directory install changed by its owning user after the check, or while the session runs, is not detected; verified images are not writable. +`weft-appd` checks every package again before a session starts. A package recorded as a publisher's runs only while that key is still trusted and its signature covers the package's current content. A package with no record runs only when a trusted key signed it, and that key is then recorded as its owner; if app data already exists for the ID without a recorded owner, in the current layout or the earlier one that is migrated at launch, the launch is refused rather than handing the data to that publisher; `weft-pack install` applies the same rule unless given `--claim-data`. The record is written before the session starts, so it remains even if that first launch then fails; `weft-pack uninstall` releases it once no data exists in either layout and no known store holds the package. Finding earlier-layout data needs `HOME`: without an absolute `HOME`, a first launch is refused (500), a first install fails unless it claims the data, and uninstall keeps the record. While an ID is recorded as development content, whatever package is found for it runs unverified, from any store. A changed package, or one whose key was removed from the trust store, is refused with code 403; a damaged trust store or owner record is a host error, 500. The manifest is read once and its bytes must be the ones in the verified inventory, so a session's capabilities and entries come from the signed manifest. The module and UI files are read again when the session starts, so a directory install changed by its owning user after the check, or while the session runs, is not detected; verified images are not writable. Not yet covered: key rotation and ownership transfer have no workflow, and removing a key is the only revocation; and capabilities are granted at launch without asking the user, independently of the signature.