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.
This commit is contained in:
Marco Allegretti 2026-10-09 14:36:06 +00:00
parent 11cea5e7e3
commit 39aacac822
No known key found for this signature in database
8 changed files with 244 additions and 72 deletions

View file

@ -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<Mount>) -> Result<Launch
),
));
}
let manifest = Manifest::read(&root).map_err(|e| match e {
ManifestError::Io(..) => Refusal::new(500, e.to_string()),
ManifestError::Parse(..) => Refusal::new(403, e.to_string()),
// 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<Mount>) -> Result<Launch
),
));
}
verify_owner(app_id, &root)?;
verify_owner(app_id, &root, &manifest_bytes)?;
let entry = |field: &str, value: &str| {
entry_path(&root, value).map_err(|e| Refusal::new(403, format!("{field}: {e}")))
};
@ -125,9 +132,16 @@ fn from_root(app_id: &str, root: PathBuf, image: Option<Mount>) -> Result<Launch
})
}
/// Checks that the package at `root` is what its owner installed.
fn verify_owner(app_id: &str, root: &Path) -> 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]

View file

@ -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 {

View file

@ -62,9 +62,19 @@ impl Manifest {
/// Reads `<package_root>/wapp.toml`.
pub fn read(package_root: &Path) -> Result<Self, ManifestError> {
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<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] {

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.
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<Self, TrustError> {
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<PublisherKey> {
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()));

View file

@ -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/<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.
`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.

View file

@ -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")

View file

@ -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),
})

View file

@ -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"], {