Merge fix/verify-packages-at-launch: verify package owner and signature before a session starts (#19)

This commit is contained in:
Marco Allegretti 2026-10-10 09:21:40 +02:00 committed by GitHub
commit 76839f6ec2
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
11 changed files with 586 additions and 32 deletions

View file

@ -3,11 +3,22 @@
//! The runtime and the app shell receive the exact files resolved here and //! 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 //! 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. //! 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, 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 std::path::{Path, PathBuf};
use weft_ipc_types::manifest::{MANIFEST_FILE, Manifest, ManifestError, entry_path}; 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::package::{ImageFiles, is_valid_app_id};
use weft_ipc_types::trust::{
Inventory, Owner, PublisherKey, TrustError, TrustStore, lock_owner, owner_record_path,
read_owner, read_signature, write_owner,
};
use crate::grants::Refusal; use crate::grants::Refusal;
use crate::mount::Mount; use crate::mount::Mount;
@ -85,9 +96,14 @@ fn from_root(app_id: &str, root: PathBuf, image: Option<Mount>) -> Result<Launch
), ),
)); ));
} }
let manifest = Manifest::read(&root).map_err(|e| match e { // The manifest is read once; the same bytes are parsed and checked
ManifestError::Io(..) => Refusal::new(500, e.to_string()), // against the signed inventory, so the capabilities and entries a
ManifestError::Parse(..) => Refusal::new(403, e.to_string()), // 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 { if manifest.package.id != app_id {
return Err(Refusal::new( return Err(Refusal::new(
@ -99,6 +115,7 @@ fn from_root(app_id: &str, root: PathBuf, image: Option<Mount>) -> Result<Launch
), ),
)); ));
} }
verify_owner(app_id, &root, &manifest_bytes)?;
let entry = |field: &str, value: &str| { let entry = |field: &str, value: &str| {
entry_path(&root, value).map_err(|e| Refusal::new(403, format!("{field}: {e}"))) entry_path(&root, value).map_err(|e| Refusal::new(403, format!("{field}: {e}")))
}; };
@ -115,6 +132,111 @@ fn from_root(app_id: &str, root: PathBuf, image: Option<Mount>) -> Result<Launch
}) })
} }
/// 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()),
};
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 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!(
"{app_id} belongs to {existing}, not publisher {}",
signer.to_hex()
),
));
}
None => {}
}
// Data in the earlier layout counts: it would be moved to this app's
// data directory when the session starts.
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}"),
)),
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),
}
}
impl LaunchPackage { impl LaunchPackage {
/// A package for supervisor tests whose children ignore their files. /// A package for supervisor tests whose children ignore their files.
#[cfg(test)] #[cfg(test)]
@ -141,6 +263,10 @@ mod tests {
const ID: &str = "org.weft.test.resolve"; const ID: &str = "org.weft.test.resolve";
/// HOME as the test process found it, restored by `finish`.
static HOME_AT_START: std::sync::OnceLock<Option<std::ffi::OsString>> =
std::sync::OnceLock::new();
/// A store holding a directory install of `ID`, with WEFT_APP_STORE /// A store holding a directory install of `ID`, with WEFT_APP_STORE
/// pointing at it. Callers hold env_lock. /// pointing at it. Callers hold env_lock.
fn store(name: &str, manifest_id: &str, module: &str) -> PathBuf { fn store(name: &str, manifest_id: &str, module: &str) -> PathBuf {
@ -160,8 +286,19 @@ mod tests {
), ),
) )
.unwrap(); .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();
HOME_AT_START.get_or_init(|| std::env::var_os("HOME"));
// SAFETY: callers hold env_lock, which serialises environment changes. // 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"));
std::env::set_var("HOME", store.join("home"));
}
store store
} }
@ -170,6 +307,12 @@ mod tests {
unsafe { unsafe {
std::env::remove_var("WEFT_APP_STORE"); std::env::remove_var("WEFT_APP_STORE");
std::env::remove_var("WEFT_MOUNT_HELPER"); 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); let _ = std::fs::remove_dir_all(store);
} }
@ -249,6 +392,213 @@ 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 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!(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 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 legacy = weft_ipc_types::package::legacy_app_data_dir(&store.join("home"), DEMO);
std::fs::create_dir_all(&legacy).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("no recorded owner"),
"{}",
refused.message
);
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();
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();
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]
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("<script>changed</script>");
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] #[test]
fn a_package_declaring_another_id_is_refused() { fn a_package_declaring_another_id_is_refused() {
let _env = crate::tests::env_lock().blocking_lock(); let _env = crate::tests::env_lock().blocking_lock();

View file

@ -712,6 +712,42 @@ mod tests {
), ),
) )
.unwrap(); .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, 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 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()
.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 {
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);
std::env::set_var("WEFT_TRUSTED_KEYS", &keys);
}
} }
fn make_registry() -> Registry { fn make_registry() -> Registry {

View file

@ -62,9 +62,19 @@ impl Manifest {
/// Reads `<package_root>/wapp.toml`. /// Reads `<package_root>/wapp.toml`.
pub fn read(package_root: &Path) -> Result<Self, ManifestError> { pub fn read(package_root: &Path) -> Result<Self, ManifestError> {
let path = package_root.join(MANIFEST_FILE); let path = package_root.join(MANIFEST_FILE);
let text = let bytes = std::fs::read(&path).map_err(|e| ManifestError::Io(path.clone(), e))?;
std::fs::read_to_string(&path).map_err(|e| ManifestError::Io(path.clone(), e))?; Self::parse(&path, &bytes)
toml::from_str(&text).map_err(|e| ManifestError::Parse(path, e)) }
/// Parses manifest bytes already read from `path`.
pub fn parse(path: &Path, bytes: &[u8]) -> Result<Self, ManifestError> {
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] { pub fn capabilities(&self) -> &[String] {

View file

@ -79,6 +79,39 @@ pub fn legacy_app_data_dir(home: &Path, app_id: &str) -> PathBuf {
.join("data") .join("data")
} }
/// The home directory, when `HOME` is set to an absolute path.
pub fn home_dir() -> Option<PathBuf> {
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: &Path,
app_id: &str,
) -> std::io::Result<Option<PathBuf>> {
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)),
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. /// The result of moving data from the earlier layout.
#[derive(Debug, PartialEq, Eq)] #[derive(Debug, PartialEq, Eq)]
pub enum Migration { pub enum Migration {

View file

@ -56,17 +56,40 @@ fn io(path: &Path) -> impl FnOnce(std::io::Error) -> TrustError + '_ {
/// The SHA-256 content digest a package signature covers. /// The SHA-256 content digest a package signature covers.
pub fn content_digest(package_root: &Path) -> Result<[u8; 32], TrustError> { pub fn content_digest(package_root: &Path) -> Result<[u8; 32], TrustError> {
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<Self, TrustError> {
let mut entries = Vec::new(); let mut entries = Vec::new();
collect(package_root, package_root, &mut entries)?; collect(package_root, package_root, &mut entries)?;
entries.sort(); entries.sort();
Ok(Self(entries))
}
/// The content digest a package signature covers.
pub fn digest(&self) -> [u8; 32] {
let mut inventory = String::new(); let mut inventory = String::new();
for (path, hash) in &entries { for (path, hash) in &self.0 {
inventory.push_str(path); inventory.push_str(path);
inventory.push('\t'); inventory.push('\t');
inventory.push_str(&hex::encode(hash)); inventory.push_str(&hex::encode(hash));
inventory.push('\n'); inventory.push('\n');
} }
Ok(Sha256::digest(inventory.as_bytes()).into()) 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)
}
} }
fn collect( fn collect(
@ -220,12 +243,15 @@ impl TrustStore {
let Some(signature) = read_signature(package_root)? else { let Some(signature) = read_signature(package_root)? else {
return Ok(None); return Ok(None);
}; };
let digest = content_digest(package_root)?; Ok(self.signer_of(&content_digest(package_root)?, &signature))
Ok(self }
.keys
/// The trusted key that made `signature` over `digest`, if any.
pub fn signer_of(&self, digest: &[u8; 32], signature: &Signature) -> Option<PublisherKey> {
self.keys
.iter() .iter()
.copied() .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(); 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] #[test]
fn owner_locks_exclude_each_other() { fn owner_locks_exclude_each_other() {
let home = std::env::temp_dir().join(format!("weft_trust_lock_{}", std::process::id())); let home = std::env::temp_dir().join(format!("weft_trust_lock_{}", std::process::id()));

View file

@ -490,14 +490,19 @@ fn admit(
"{app_id} belongs to {existing}; this package is {owner}. Its app data stays with \ "{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" 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 => { None => {
let data = weft_ipc_types::package::app_data_dir(data_home, app_id); // Data in the earlier layout counts: weft-appd moves it to the
let no_data = match std::fs::symlink_metadata(&data) { // app's data directory when the app next launches.
Err(e) if e.kind() == std::io::ErrorKind::NotFound => true, let home = weft_ipc_types::package::home_dir().context(
Err(e) => return Err(e).with_context(|| format!("inspect {}", data.display())), "HOME is not set to an absolute path, so earlier app data cannot be found",
Ok(_) => false, )?;
}; let existing = weft_ipc_types::package::existing_app_data(data_home, &home, app_id)
if !no_data && !claim_data { .with_context(|| format!("inspect the app data of {app_id}"))?;
if let Some(data) = existing {
anyhow::bail!( anyhow::bail!(
"{} holds app data for {app_id} with no recorded owner; install with \ "{} holds app data for {app_id} with no recorded owner; install with \
--claim-data to give it to {owner}, or move it aside", --claim-data to give it to {owner}, or move it aside",
@ -600,9 +605,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 /// Removes the owner record of `app_id` when the app has no data, and
/// reports whether a record was removed. /// reports whether a record was removed.
fn release_owner_without_data(data_home: &Path, app_id: &str) -> bool { fn release_owner_without_data(data_home: &Path, app_id: &str) -> bool {
let no_data = // Data in either layout keeps the record; so does not being able to look.
std::fs::symlink_metadata(weft_ipc_types::package::app_data_dir(data_home, app_id)) let no_data = weft_ipc_types::package::home_dir().is_some_and(|home| {
.is_err_and(|e| e.kind() == std::io::ErrorKind::NotFound); matches!(
weft_ipc_types::package::existing_app_data(data_home, &home, app_id),
Ok(None)
)
});
no_data no_data
&& std::fs::remove_file(weft_ipc_types::trust::owner_record_path(data_home, app_id)).is_ok() && std::fs::remove_file(weft_ipc_types::trust::owner_record_path(data_home, app_id)).is_ok()
} }
@ -1341,6 +1350,13 @@ mod tests {
std::fs::remove_dir_all(&data).unwrap(); std::fs::remove_dir_all(&data).unwrap();
with_home(&home, || uninstall_package_from(app_id, &store)).unwrap(); with_home(&home, || uninstall_package_from(app_id, &store)).unwrap();
assert!(!record.exists()); 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); let _ = std::fs::remove_dir_all(&home);
} }
@ -1399,6 +1415,46 @@ mod tests {
let _ = std::fs::remove_dir_all(&home); 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 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] #[test]
fn uninstalling_one_of_two_copies_keeps_the_record() { fn uninstalling_one_of_two_copies_keeps_the_record() {
let home = temp_root("two_copies"); let home = temp_root("two_copies");

View file

@ -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/<id>`: 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 <id>` 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. The first installation of an app ID records its owner in `$XDG_DATA_HOME/weft/owners/<id>`: 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 <id>` 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, 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.
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`). 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`).

View file

@ -41,12 +41,20 @@ def run(args, desktop, home, xdotool):
(legacy / "notes.txt").write_bytes(NOTES) (legacy / "notes.txt").write_bytes(NOTES)
data_home = home / "data-home" data_home = home / "data-home"
target = data_home / "weft/app-data" / APP_ID target = data_home / "weft/app-data" / APP_ID
# 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()
owner.write_text(f"verified {key}\n")
t = Path(args.target) t = Path(args.target)
desktop.launch_client("appd", [t / "weft-appd"], { desktop.launch_client("appd", [t / "weft-appd"], {
"WEFT_RUNTIME_BIN": str(t / "weft-runtime"), "WEFT_RUNTIME_BIN": str(t / "weft-runtime"),
"WEFT_APP_SHELL_BIN": str(t / "weft-app-shell"), "WEFT_APP_SHELL_BIN": str(t / "weft-app-shell"),
"WEFT_APP_STORE": str(args.store), "WEFT_APP_STORE": str(args.store),
"WEFT_TRUSTED_KEYS": str(ROOT / "examples/keys"),
"WEFT_DISABLE_CGROUP": "1", "WEFT_DISABLE_CGROUP": "1",
"WEFT_APPD_WS_PORT": str(free_port()), "WEFT_APPD_WS_PORT": str(free_port()),
"HOME": str(home), "HOME": str(home),

View file

@ -142,6 +142,12 @@ def make_package(store, http_port, ws_port, other_dir):
(package / "outside.png").write_bytes(png()) (package / "outside.png").write_bytes(png())
other.write_bytes(png()) other.write_bytes(png())
(package / "ui/linked").symlink_to(other_dir) (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, exist_ok=True)
record.write_text("development\n")
def run(args, desktop, store, other_dir): 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_RUNTIME_BIN": str(t / "weft-runtime"),
"WEFT_APP_SHELL_BIN": str(t / "weft-app-shell"), "WEFT_APP_SHELL_BIN": str(t / "weft-app-shell"),
"WEFT_APP_STORE": str(store), "WEFT_APP_STORE": str(store),
"HOME": str(store / "home"),
"XDG_DATA_HOME": str(store / "home/share"),
"WEFT_DISABLE_CGROUP": "1", "WEFT_DISABLE_CGROUP": "1",
"WEFT_APPD_WS_PORT": str(free_port()), "WEFT_APPD_WS_PORT": str(free_port()),
}) })

View file

@ -158,10 +158,17 @@ def count_area(screenshot, card):
def run(args, desktop, xdotool): def run(args, desktop, xdotool):
port = free_port() port = free_port()
target = Path(args.target) 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"], { desktop.launch_client("appd", [target / "weft-appd"], {
"WEFT_RUNTIME_BIN": str(target / "weft-runtime"), "WEFT_RUNTIME_BIN": str(target / "weft-runtime"),
"WEFT_APP_SHELL_BIN": str(target / "weft-app-shell"), "WEFT_APP_SHELL_BIN": str(target / "weft-app-shell"),
"WEFT_APP_STORE": str(args.store), "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_DISABLE_CGROUP": "1",
"WEFT_APPD_WS_PORT": str(port), "WEFT_APPD_WS_PORT": str(port),
}) })

View file

@ -69,12 +69,19 @@ def run(args, desktop, home, xdotool):
notes = data_home / "weft/app-data" / APP_ID / "notes.txt" notes = data_home / "weft/app-data" / APP_ID / "notes.txt"
notes.parent.mkdir(parents=True) notes.parent.mkdir(parents=True)
notes.write_text(SEED, encoding="utf-8") 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) t = Path(args.target)
desktop.launch_client("appd", [t / "weft-appd"], { desktop.launch_client("appd", [t / "weft-appd"], {
"WEFT_RUNTIME_BIN": str(t / "weft-runtime"), "WEFT_RUNTIME_BIN": str(t / "weft-runtime"),
"WEFT_APP_SHELL_BIN": str(t / "weft-app-shell"), "WEFT_APP_SHELL_BIN": str(t / "weft-app-shell"),
"WEFT_APP_STORE": str(args.store), "WEFT_APP_STORE": str(args.store),
"WEFT_TRUSTED_KEYS": str(ROOT / "examples/keys"),
"WEFT_DISABLE_CGROUP": "1", "WEFT_DISABLE_CGROUP": "1",
"WEFT_APPD_WS_PORT": str(free_port()), "WEFT_APPD_WS_PORT": str(free_port()),
"HOME": str(home), "HOME": str(home),