mirror of
https://github.com/marcoallegretti/WEFT_OS.git
synced 2026-11-22 08:13:59 +00:00
Merge remote-tracking branch 'origin/main' into fix/keyboard-system-navigation
# Conflicts: # docs/building.md
This commit is contained in:
commit
373cec1bab
22 changed files with 4171 additions and 290 deletions
4
Cargo.lock
generated
4
Cargo.lock
generated
|
|
@ -10521,9 +10521,12 @@ dependencies = [
|
||||||
name = "weft-ipc-types"
|
name = "weft-ipc-types"
|
||||||
version = "0.1.0"
|
version = "0.1.0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
|
"ed25519-dalek",
|
||||||
|
"hex",
|
||||||
"rmp-serde",
|
"rmp-serde",
|
||||||
"rustix 1.1.4",
|
"rustix 1.1.4",
|
||||||
"serde",
|
"serde",
|
||||||
|
"sha2",
|
||||||
"toml 0.8.23",
|
"toml 0.8.23",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
|
@ -10542,6 +10545,7 @@ dependencies = [
|
||||||
"ed25519-dalek",
|
"ed25519-dalek",
|
||||||
"hex",
|
"hex",
|
||||||
"rand 0.8.5",
|
"rand 0.8.5",
|
||||||
|
"rustix 1.1.4",
|
||||||
"sha2",
|
"sha2",
|
||||||
"tar",
|
"tar",
|
||||||
"weft-ipc-types",
|
"weft-ipc-types",
|
||||||
|
|
|
||||||
|
|
@ -14,7 +14,7 @@ WEFT OS is a Wayland compositor and application runtime where every app is a Web
|
||||||
|
|
||||||
**Runtime** — `weft-runtime` runs WASI Component Model binaries under Wasmtime 30 (`--features wasmtime-runtime`). Provides `weft:app/notify`, `weft:app/ipc`, `weft:app/fetch`, `weft:app/notifications`, and `weft:app/clipboard` host imports. Preopens filesystem paths according to declared capabilities.
|
**Runtime** — `weft-runtime` runs WASI Component Model binaries under Wasmtime 30 (`--features wasmtime-runtime`). Provides `weft:app/notify`, `weft:app/ipc`, `weft:app/fetch`, `weft:app/notifications`, and `weft:app/clipboard` host imports. Preopens filesystem paths according to declared capabilities.
|
||||||
|
|
||||||
**Package management** — `weft-pack` handles check, sign, verify, install, uninstall, list, build-image (EROFS dm-verity), and info. Validates capability strings at check time. App data is stored apart from packages and survives uninstall.
|
**Package management** — `weft-pack` handles check, sign, verify, install and update, rollback, uninstall, list, build-image (EROFS dm-verity), and info. Validates capability strings at check time. Installs only packages signed by a trusted key (or explicitly as development content) and binds each app ID to its first publisher. App data is stored apart from packages and survives uninstall.
|
||||||
|
|
||||||
**File portal** — `weft-file-portal` is a per-session file proxy with a path allowlist and `..` blocking.
|
**File portal** — `weft-file-portal` is a per-session file proxy with a path allowlist and `..` blocking.
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -87,14 +87,9 @@ impl HostDirs {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Derives grants for the declared capabilities. Every capability is
|
/// Parses the declared capabilities, refusing unknown ones and those this
|
||||||
/// checked before host directories are resolved or the app's data
|
/// host does not support, without touching the host.
|
||||||
/// directory is created, so a refused launch leaves nothing behind.
|
pub(crate) fn validate(declared: &[String]) -> Result<Vec<Capability>, Refusal> {
|
||||||
pub(crate) fn derive(
|
|
||||||
app_id: &str,
|
|
||||||
declared: &[String],
|
|
||||||
host_dirs: impl FnOnce() -> Result<HostDirs, Refusal>,
|
|
||||||
) -> Result<SessionGrants, Refusal> {
|
|
||||||
let mut capabilities = Vec::new();
|
let mut capabilities = Vec::new();
|
||||||
for text in declared {
|
for text in declared {
|
||||||
let capability: Capability =
|
let capability: Capability =
|
||||||
|
|
@ -110,7 +105,18 @@ pub(crate) fn derive(
|
||||||
}
|
}
|
||||||
capabilities.push(capability);
|
capabilities.push(capability);
|
||||||
}
|
}
|
||||||
|
Ok(capabilities)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Derives grants for the declared capabilities. Every capability is
|
||||||
|
/// checked before host directories are resolved or the app's data
|
||||||
|
/// directory is created, so a refused launch leaves nothing behind.
|
||||||
|
pub(crate) fn derive(
|
||||||
|
app_id: &str,
|
||||||
|
declared: &[String],
|
||||||
|
host_dirs: impl FnOnce() -> Result<HostDirs, Refusal>,
|
||||||
|
) -> Result<SessionGrants, Refusal> {
|
||||||
|
let capabilities = validate(declared)?;
|
||||||
let mut grants = SessionGrants::default();
|
let mut grants = SessionGrants::default();
|
||||||
let needs_dirs = capabilities
|
let needs_dirs = capabilities
|
||||||
.iter()
|
.iter()
|
||||||
|
|
|
||||||
|
|
@ -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::{ClosePolicy, MANIFEST_FILE, Manifest, ManifestError, entry_path};
|
use weft_ipc_types::manifest::{ClosePolicy, 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;
|
||||||
|
|
@ -26,6 +37,9 @@ pub(crate) struct LaunchPackage {
|
||||||
/// The image the package root is mounted from, held for as long as the
|
/// The image the package root is mounted from, held for as long as the
|
||||||
/// session runs.
|
/// session runs.
|
||||||
pub(crate) image: Option<Mount>,
|
pub(crate) image: Option<Mount>,
|
||||||
|
/// The lock that keeps an installed revision from being removed while
|
||||||
|
/// the session runs from it.
|
||||||
|
pub(crate) pin: Option<weft_ipc_types::store::Pin>,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Resolves `app_id` in the package stores.
|
/// Resolves `app_id` in the package stores.
|
||||||
|
|
@ -59,16 +73,47 @@ fn resolve_in(app_id: &str, stores: &[PathBuf]) -> Result<LaunchPackage, Refusal
|
||||||
let root = image.root().to_path_buf();
|
let root = image.root().to_path_buf();
|
||||||
return from_root(app_id, root, Some(image));
|
return from_root(app_id, root, Some(image));
|
||||||
}
|
}
|
||||||
|
// A store whose entry for the app cannot be used does not hide the app
|
||||||
|
// in a later store, as it does not in the list of installed apps; the
|
||||||
|
// first such problem is reported when no store has the app.
|
||||||
|
let mut unusable = None;
|
||||||
for store in stores {
|
for store in stores {
|
||||||
let dir = store.join(app_id);
|
let active = match weft_ipc_types::store::active(store, app_id) {
|
||||||
if std::fs::symlink_metadata(dir.join(MANIFEST_FILE)).is_ok() {
|
Ok(Some(active)) => active,
|
||||||
return from_root(app_id, dir, None);
|
Ok(None) => continue,
|
||||||
|
Err(e) => {
|
||||||
|
tracing::warn!(app_id, error = %e, "package entry skipped");
|
||||||
|
unusable.get_or_insert(match e {
|
||||||
|
weft_ipc_types::store::StoreError::NotAPackage(_) => {
|
||||||
|
Refusal::new(403, e.to_string())
|
||||||
}
|
}
|
||||||
|
weft_ipc_types::store::StoreError::Io(..) => Refusal::new(500, e.to_string()),
|
||||||
|
});
|
||||||
|
continue;
|
||||||
}
|
}
|
||||||
Err(Refusal::new(
|
};
|
||||||
404,
|
let dir = active.dir().to_path_buf();
|
||||||
format!("package {app_id} is not installed"),
|
// A directory left with only app data by an earlier layout is not a
|
||||||
))
|
// package.
|
||||||
|
if std::fs::symlink_metadata(dir.join(MANIFEST_FILE)).is_err() {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
// The session runs from the revision itself, not the link, so an
|
||||||
|
// update or rollback that switches the link while it runs leaves it
|
||||||
|
// on the bytes it started with. From here on a refusal is final: a
|
||||||
|
// package that is being changed, or that fails its checks, is not
|
||||||
|
// silently replaced by another store's copy.
|
||||||
|
let pin = weft_ipc_types::store::pin(&dir).map_err(|e| {
|
||||||
|
Refusal::new(
|
||||||
|
500,
|
||||||
|
format!("cannot hold {} while it runs: {e}", dir.display()),
|
||||||
|
)
|
||||||
|
})?;
|
||||||
|
let mut package = from_root(app_id, dir, None)?;
|
||||||
|
package.pin = Some(pin);
|
||||||
|
return Ok(package);
|
||||||
|
}
|
||||||
|
Err(unusable.unwrap_or_else(|| Refusal::new(404, format!("package {app_id} is not installed"))))
|
||||||
}
|
}
|
||||||
|
|
||||||
fn from_root(app_id: &str, root: PathBuf, image: Option<Mount>) -> Result<LaunchPackage, Refusal> {
|
fn from_root(app_id: &str, root: PathBuf, image: Option<Mount>) -> Result<LaunchPackage, Refusal> {
|
||||||
|
|
@ -87,9 +132,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(
|
||||||
|
|
@ -101,6 +151,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,9 +166,115 @@ fn from_root(app_id: &str, root: PathBuf, image: Option<Mount>) -> Result<Launch
|
||||||
close: manifest.ui.close,
|
close: manifest.ui.close,
|
||||||
root,
|
root,
|
||||||
image,
|
image,
|
||||||
|
pin: None,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// 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)]
|
||||||
|
|
@ -131,6 +288,7 @@ impl LaunchPackage {
|
||||||
close: ClosePolicy::Immediate,
|
close: ClosePolicy::Immediate,
|
||||||
capabilities: Vec::new(),
|
capabilities: Vec::new(),
|
||||||
image: None,
|
image: None,
|
||||||
|
pin: None,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -145,6 +303,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 {
|
||||||
|
|
@ -164,8 +326,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
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -174,6 +347,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);
|
||||||
}
|
}
|
||||||
|
|
@ -243,13 +422,275 @@ mod tests {
|
||||||
std::os::unix::fs::symlink(store.join("manifest.toml"), &manifest).unwrap();
|
std::os::unix::fs::symlink(store.join("manifest.toml"), &manifest).unwrap();
|
||||||
let manifest_link = refusal(resolve(ID));
|
let manifest_link = refusal(resolve(ID));
|
||||||
finish(&store);
|
finish(&store);
|
||||||
for refused in [root_link, manifest_link] {
|
// Only a link to one of the app's own revisions is followed.
|
||||||
|
assert_eq!(root_link.code, 403, "{}", root_link.message);
|
||||||
|
assert!(
|
||||||
|
root_link
|
||||||
|
.message
|
||||||
|
.contains("nor a link to one of its revisions"),
|
||||||
|
"{}",
|
||||||
|
root_link.message
|
||||||
|
);
|
||||||
|
assert_eq!(manifest_link.code, 403, "{}", manifest_link.message);
|
||||||
|
assert!(
|
||||||
|
manifest_link.message.contains("not a link"),
|
||||||
|
"{}",
|
||||||
|
manifest_link.message
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(unix)]
|
||||||
|
#[test]
|
||||||
|
fn an_unusable_store_entry_does_not_hide_a_later_store() {
|
||||||
|
let _env = crate::tests::env_lock().blocking_lock();
|
||||||
|
let user = store("unusable_user", ID, "app.wasm");
|
||||||
|
let system = std::env::temp_dir().join(format!(
|
||||||
|
"weft_appd_launch_unusable_system_{}",
|
||||||
|
std::process::id()
|
||||||
|
));
|
||||||
|
let _ = std::fs::remove_dir_all(&system);
|
||||||
|
std::fs::create_dir_all(&system).unwrap();
|
||||||
|
std::fs::rename(user.join(ID), system.join(ID)).unwrap();
|
||||||
|
// A link to something other than one of the app's revisions.
|
||||||
|
std::os::unix::fs::symlink("/tmp", user.join(ID)).unwrap();
|
||||||
|
let found = resolve_in(ID, &[user.clone(), system.clone()]).map(|p| p.root);
|
||||||
|
let alone = refusal(resolve_in(ID, std::slice::from_ref(&user)));
|
||||||
|
finish(&user);
|
||||||
|
let _ = std::fs::remove_dir_all(&system);
|
||||||
|
assert_eq!(found.ok(), Some(system.join(ID)));
|
||||||
|
// With no other store, its problem is reported, not "not installed".
|
||||||
|
assert_eq!(alone.code, 403, "{}", alone.message);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(unix)]
|
||||||
|
#[test]
|
||||||
|
fn a_session_runs_from_its_revision_and_holds_it() {
|
||||||
|
use weft_ipc_types::store::{link_target, revisions_of, try_claim};
|
||||||
|
let _env = crate::tests::env_lock().blocking_lock();
|
||||||
|
let store = store("revision", ID, "app.wasm");
|
||||||
|
let revision = "ab".repeat(32);
|
||||||
|
let dir = revisions_of(&store, ID).join(&revision);
|
||||||
|
std::fs::create_dir_all(dir.parent().unwrap()).unwrap();
|
||||||
|
std::fs::rename(store.join(ID), &dir).unwrap();
|
||||||
|
std::os::unix::fs::symlink(link_target(ID, &revision), store.join(ID)).unwrap();
|
||||||
|
let package = resolve(ID).unwrap();
|
||||||
|
let held = try_claim(&dir).unwrap().is_none();
|
||||||
|
let root = package.root.clone();
|
||||||
|
let module = package.module.clone();
|
||||||
|
drop(package);
|
||||||
|
let released = try_claim(&dir).unwrap().is_some();
|
||||||
|
finish(&store);
|
||||||
|
// The children get the revision's own paths, not the link's.
|
||||||
|
assert_eq!(root, dir);
|
||||||
|
assert_eq!(module, dir.join("app.wasm"));
|
||||||
|
assert!(held, "the revision is not held while the session runs");
|
||||||
|
assert!(released, "the revision is still held after the session");
|
||||||
|
}
|
||||||
|
|
||||||
|
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_eq!(refused.code, 403, "{}", refused.message);
|
||||||
assert!(
|
assert!(
|
||||||
refused.message.contains("not a link"),
|
refused.message.contains("--claim-data"),
|
||||||
"{}",
|
"{}",
|
||||||
refused.message
|
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);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -701,6 +701,29 @@ pub(crate) async fn dispatch(req: Request, registry: &Registry) -> Response {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Refuses a launch while the app declares a capability the user has not
|
||||||
|
/// approved; a signature, however trusted, approves nothing.
|
||||||
|
fn check_approval(app_id: &str, declared: &[String]) -> Result<(), grants::Refusal> {
|
||||||
|
use weft_ipc_types::approval::{approval_path, read_approved, unapproved};
|
||||||
|
let data_home = weft_ipc_types::package::data_home().ok_or_else(|| {
|
||||||
|
grants::Refusal::new(500, "cannot locate the data home holding app approvals")
|
||||||
|
})?;
|
||||||
|
let record = approval_path(&data_home, app_id);
|
||||||
|
let approved = read_approved(&record)
|
||||||
|
.map_err(|e| grants::Refusal::new(500, format!("cannot read {}: {e}", record.display())))?;
|
||||||
|
let pending = unapproved(declared, &approved);
|
||||||
|
if pending.is_empty() {
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
Err(grants::Refusal::new(
|
||||||
|
403,
|
||||||
|
format!(
|
||||||
|
"{app_id} needs approval for {}; approve it with weft-pack approve {app_id}",
|
||||||
|
pending.join(", ")
|
||||||
|
),
|
||||||
|
))
|
||||||
|
}
|
||||||
|
|
||||||
/// Resolves the package of `app_id` and derives its grants. Resolution may
|
/// Resolves the package of `app_id` and derives its grants. Resolution may
|
||||||
/// mount an image, so it runs off the async workers; a refused launch
|
/// mount an image, so it runs off the async workers; a refused launch
|
||||||
/// releases the mount the same way.
|
/// releases the mount the same way.
|
||||||
|
|
@ -709,6 +732,10 @@ async fn resolve_launch(
|
||||||
) -> Result<(launch::LaunchPackage, grants::SessionGrants), grants::Refusal> {
|
) -> Result<(launch::LaunchPackage, grants::SessionGrants), grants::Refusal> {
|
||||||
tokio::task::spawn_blocking(move || {
|
tokio::task::spawn_blocking(move || {
|
||||||
let package = launch::resolve(&app_id)?;
|
let package = launch::resolve(&app_id)?;
|
||||||
|
// Unknown and unsupported capabilities are refused as such, then
|
||||||
|
// unapproved ones, before anything is prepared on the host.
|
||||||
|
grants::validate(&package.capabilities)?;
|
||||||
|
check_approval(&app_id, &package.capabilities)?;
|
||||||
let grants = grants::derive(&app_id, &package.capabilities, grants::HostDirs::from_env)?;
|
let grants = grants::derive(&app_id, &package.capabilities, grants::HostDirs::from_env)?;
|
||||||
tracing::info!(
|
tracing::info!(
|
||||||
%app_id,
|
%app_id,
|
||||||
|
|
@ -754,9 +781,24 @@ fn scan_installed_apps() -> Vec<AppInfo> {
|
||||||
continue;
|
continue;
|
||||||
};
|
};
|
||||||
for entry in entries.flatten() {
|
for entry in entries.flatten() {
|
||||||
let Ok(m) = weft_ipc_types::manifest::Manifest::read(&entry.path()) else {
|
// Only an app's active package, named after the ID its manifest
|
||||||
|
// declares, is installed; staging copies, revisions and stray
|
||||||
|
// directories or links are not.
|
||||||
|
let Some(name) = entry.file_name().to_str().map(str::to_owned) else {
|
||||||
continue;
|
continue;
|
||||||
};
|
};
|
||||||
|
if !weft_ipc_types::package::is_valid_app_id(&name) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let Ok(Some(found)) = weft_ipc_types::store::active(&root, &name) else {
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
let Ok(m) = weft_ipc_types::manifest::Manifest::read(found.dir()) else {
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
if m.package.id != name {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
if seen.insert(m.package.id.clone()) {
|
if seen.insert(m.package.id.clone()) {
|
||||||
apps.push(AppInfo {
|
apps.push(AppInfo {
|
||||||
app_id: m.package.id,
|
app_id: m.package.id,
|
||||||
|
|
@ -833,6 +875,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 {
|
||||||
|
|
@ -904,6 +982,69 @@ mod tests {
|
||||||
assert!(result.is_err());
|
assert!(result.is_err());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn a_capability_launches_only_once_approved() {
|
||||||
|
let _env = env_lock().lock().await;
|
||||||
|
let store = std::env::temp_dir().join(format!("weft_approve_{}", std::process::id()));
|
||||||
|
let id = "org.example.notify";
|
||||||
|
write_test_package(
|
||||||
|
&store.join(id),
|
||||||
|
id,
|
||||||
|
"capabilities = [\"sys:notifications\"]",
|
||||||
|
);
|
||||||
|
let prior_store = std::env::var("WEFT_APP_STORE").ok();
|
||||||
|
let prior_bin = std::env::var("WEFT_RUNTIME_BIN").ok();
|
||||||
|
// SAFETY: env_lock is held and the runtime is current_thread. A
|
||||||
|
// configured runtime makes appd resolve the package.
|
||||||
|
unsafe {
|
||||||
|
std::env::set_var("WEFT_APP_STORE", &store);
|
||||||
|
std::env::set_var("WEFT_RUNTIME_BIN", "/nonexistent/weft-runtime");
|
||||||
|
}
|
||||||
|
let launch = || async {
|
||||||
|
dispatch(
|
||||||
|
Request::LaunchApp {
|
||||||
|
app_id: id.into(),
|
||||||
|
surface_id: 0,
|
||||||
|
},
|
||||||
|
&make_registry(),
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
};
|
||||||
|
let refused = launch().await;
|
||||||
|
let data_home = weft_ipc_types::package::data_home().unwrap();
|
||||||
|
let record = weft_ipc_types::approval::approval_path(&data_home, id);
|
||||||
|
weft_ipc_types::approval::write_approved(&record, &["sys:notifications".to_owned()])
|
||||||
|
.unwrap();
|
||||||
|
let approved = launch().await;
|
||||||
|
let _ = std::fs::remove_file(&record);
|
||||||
|
// SAFETY: as above.
|
||||||
|
unsafe {
|
||||||
|
match prior_store {
|
||||||
|
Some(v) => std::env::set_var("WEFT_APP_STORE", v),
|
||||||
|
None => std::env::remove_var("WEFT_APP_STORE"),
|
||||||
|
}
|
||||||
|
match prior_bin {
|
||||||
|
Some(v) => std::env::set_var("WEFT_RUNTIME_BIN", v),
|
||||||
|
None => std::env::remove_var("WEFT_RUNTIME_BIN"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let _ = std::fs::remove_dir_all(&store);
|
||||||
|
match refused {
|
||||||
|
Response::Error { code, message } => {
|
||||||
|
assert_eq!(code, 403);
|
||||||
|
assert!(
|
||||||
|
message.contains("needs approval for sys:notifications"),
|
||||||
|
"{message}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
other => panic!("an unapproved capability launched: {other:?}"),
|
||||||
|
}
|
||||||
|
assert!(
|
||||||
|
matches!(approved, Response::LaunchAck { .. }),
|
||||||
|
"{approved:?}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn launch_is_refused_when_capabilities_cannot_be_granted() {
|
async fn launch_is_refused_when_capabilities_cannot_be_granted() {
|
||||||
let _env = env_lock().lock().await;
|
let _env = env_lock().lock().await;
|
||||||
|
|
|
||||||
|
|
@ -12,6 +12,9 @@ path = "src/lib.rs"
|
||||||
serde = { version = "1", features = ["derive"] }
|
serde = { version = "1", features = ["derive"] }
|
||||||
rmp-serde = "1"
|
rmp-serde = "1"
|
||||||
toml = "0.8"
|
toml = "0.8"
|
||||||
|
sha2 = "0.10"
|
||||||
|
hex = "0.4"
|
||||||
|
ed25519-dalek = "2"
|
||||||
|
|
||||||
[lints]
|
[lints]
|
||||||
workspace = true
|
workspace = true
|
||||||
|
|
|
||||||
144
crates/weft-ipc-types/src/approval.rs
Normal file
144
crates/weft-ipc-types/src/approval.rs
Normal file
|
|
@ -0,0 +1,144 @@
|
||||||
|
//! The capabilities the user approved for an installed app.
|
||||||
|
//!
|
||||||
|
//! A package declares capabilities; it gets only those the user approved.
|
||||||
|
//! `weft-pack` records the approval, `$XDG_DATA_HOME/weft/approvals/<id>`,
|
||||||
|
//! one capability per line, and weft-appd refuses to launch an app that
|
||||||
|
//! declares a capability the record does not hold. An app's own private
|
||||||
|
//! data is a minimal execution resource and needs no approval. Signature
|
||||||
|
//! verification and approval are separate decisions: a trusted signature
|
||||||
|
//! approves nothing.
|
||||||
|
|
||||||
|
use std::collections::BTreeSet;
|
||||||
|
use std::path::{Path, PathBuf};
|
||||||
|
|
||||||
|
use crate::capability::Capability;
|
||||||
|
|
||||||
|
/// Where the approval record of `app_id` lives.
|
||||||
|
pub fn approval_path(data_home: &Path, app_id: &str) -> PathBuf {
|
||||||
|
data_home.join("weft/approvals").join(app_id)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether a declared capability needs the user's approval. Strings that
|
||||||
|
/// are not capabilities are left to the capability checks, which refuse
|
||||||
|
/// them.
|
||||||
|
pub fn needs_approval(capability: &str) -> bool {
|
||||||
|
capability
|
||||||
|
.parse::<Capability>()
|
||||||
|
.is_ok_and(|c| !matches!(c, Capability::AppData(_)))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The declared capabilities that need approval and are not in `approved`.
|
||||||
|
pub fn unapproved<'a>(declared: &'a [String], approved: &BTreeSet<String>) -> Vec<&'a str> {
|
||||||
|
declared
|
||||||
|
.iter()
|
||||||
|
.map(String::as_str)
|
||||||
|
.filter(|c| needs_approval(c) && !approved.contains(*c))
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The capabilities approved for an app; none when there is no record.
|
||||||
|
pub fn read_approved(record: &Path) -> std::io::Result<BTreeSet<String>> {
|
||||||
|
match std::fs::read_to_string(record) {
|
||||||
|
Ok(text) => Ok(text
|
||||||
|
.lines()
|
||||||
|
.map(str::trim)
|
||||||
|
.filter(|l| !l.is_empty())
|
||||||
|
.map(str::to_owned)
|
||||||
|
.collect()),
|
||||||
|
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(BTreeSet::new()),
|
||||||
|
Err(e) => Err(e),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Records exactly the capabilities of `declared` that need approval as the
|
||||||
|
/// app's approval, replacing an earlier one in one rename. With none to
|
||||||
|
/// approve, the record is removed.
|
||||||
|
pub fn write_approved(record: &Path, declared: &[String]) -> std::io::Result<()> {
|
||||||
|
use std::io::Write;
|
||||||
|
let approved: BTreeSet<&str> = declared
|
||||||
|
.iter()
|
||||||
|
.map(String::as_str)
|
||||||
|
.filter(|c| needs_approval(c))
|
||||||
|
.collect();
|
||||||
|
if approved.is_empty() {
|
||||||
|
return remove_approval(record);
|
||||||
|
}
|
||||||
|
let parent = record
|
||||||
|
.parent()
|
||||||
|
.expect("approval records live in a directory");
|
||||||
|
std::fs::create_dir_all(parent)?;
|
||||||
|
let temp = parent.join(format!(
|
||||||
|
".{}.{}.tmp",
|
||||||
|
record
|
||||||
|
.file_name()
|
||||||
|
.and_then(|n| n.to_str())
|
||||||
|
.unwrap_or("record"),
|
||||||
|
std::process::id()
|
||||||
|
));
|
||||||
|
let written = (|| {
|
||||||
|
let mut file = std::fs::File::create(&temp)?;
|
||||||
|
for capability in &approved {
|
||||||
|
writeln!(file, "{capability}")?;
|
||||||
|
}
|
||||||
|
file.sync_all()?;
|
||||||
|
std::fs::rename(&temp, record)
|
||||||
|
})();
|
||||||
|
if written.is_err() {
|
||||||
|
let _ = std::fs::remove_file(&temp);
|
||||||
|
}
|
||||||
|
written?;
|
||||||
|
std::fs::File::open(parent).and_then(|dir| dir.sync_all())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Removes an app's approval, so a later installation asks again.
|
||||||
|
pub fn remove_approval(record: &Path) -> std::io::Result<()> {
|
||||||
|
match std::fs::remove_file(record) {
|
||||||
|
Err(e) if e.kind() != std::io::ErrorKind::NotFound => Err(e),
|
||||||
|
_ => Ok(()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
fn caps(list: &[&str]) -> Vec<String> {
|
||||||
|
list.iter().map(|c| (*c).to_owned()).collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn private_app_data_needs_no_approval() {
|
||||||
|
assert!(!needs_approval("fs:rw:app-data"));
|
||||||
|
assert!(!needs_approval("fs:read:app-data"));
|
||||||
|
assert!(needs_approval("net:fetch:example.org"));
|
||||||
|
assert!(needs_approval("sys:notifications"));
|
||||||
|
assert!(needs_approval("fs:read:xdg-documents"));
|
||||||
|
// Not a capability: refused elsewhere, not reported as unapproved.
|
||||||
|
assert!(!needs_approval("sys:everything"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn approvals_cover_exactly_what_was_approved() {
|
||||||
|
let dir = std::env::temp_dir().join(format!("weft_approval_{}", std::process::id()));
|
||||||
|
let _ = std::fs::remove_dir_all(&dir);
|
||||||
|
let record = approval_path(&dir, "org.weft.test");
|
||||||
|
let declared = caps(&["fs:rw:app-data", "net:fetch:example.org"]);
|
||||||
|
assert_eq!(read_approved(&record).unwrap(), BTreeSet::new());
|
||||||
|
assert_eq!(
|
||||||
|
unapproved(&declared, &read_approved(&record).unwrap()),
|
||||||
|
["net:fetch:example.org"]
|
||||||
|
);
|
||||||
|
write_approved(&record, &declared).unwrap();
|
||||||
|
assert!(unapproved(&declared, &read_approved(&record).unwrap()).is_empty());
|
||||||
|
// An update that asks for more needs approval for the new capability.
|
||||||
|
let updated = caps(&["net:fetch:example.org", "sys:clipboard:read"]);
|
||||||
|
assert_eq!(
|
||||||
|
unapproved(&updated, &read_approved(&record).unwrap()),
|
||||||
|
["sys:clipboard:read"]
|
||||||
|
);
|
||||||
|
// Nothing left to approve removes the record.
|
||||||
|
write_approved(&record, &caps(&["fs:rw:app-data"])).unwrap();
|
||||||
|
assert!(!record.exists());
|
||||||
|
std::fs::remove_dir_all(&dir).unwrap();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -1,6 +1,9 @@
|
||||||
|
pub mod approval;
|
||||||
pub mod capability;
|
pub mod capability;
|
||||||
pub mod manifest;
|
pub mod manifest;
|
||||||
pub mod package;
|
pub mod package;
|
||||||
|
pub mod store;
|
||||||
|
pub mod trust;
|
||||||
|
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -87,9 +87,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] {
|
||||||
|
|
|
||||||
|
|
@ -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 {
|
||||||
|
|
@ -180,13 +213,13 @@ pub fn migrate_app_data(legacy: &Path, target: &Path) -> Result<Migration, Migra
|
||||||
/// Renames `from` to `to`, failing with `AlreadyExists` instead of replacing
|
/// Renames `from` to `to`, failing with `AlreadyExists` instead of replacing
|
||||||
/// an existing `to`, even one created after the caller checked for it.
|
/// an existing `to`, even one created after the caller checked for it.
|
||||||
#[cfg(target_os = "linux")]
|
#[cfg(target_os = "linux")]
|
||||||
fn rename_no_replace(from: &Path, to: &Path) -> std::io::Result<()> {
|
pub fn rename_no_replace(from: &Path, to: &Path) -> std::io::Result<()> {
|
||||||
use rustix::fs::{CWD, RenameFlags, renameat_with};
|
use rustix::fs::{CWD, RenameFlags, renameat_with};
|
||||||
renameat_with(CWD, from, CWD, to, RenameFlags::NOREPLACE).map_err(std::io::Error::from)
|
renameat_with(CWD, from, CWD, to, RenameFlags::NOREPLACE).map_err(std::io::Error::from)
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(not(target_os = "linux"))]
|
#[cfg(not(target_os = "linux"))]
|
||||||
fn rename_no_replace(from: &Path, to: &Path) -> std::io::Result<()> {
|
pub fn rename_no_replace(from: &Path, to: &Path) -> std::io::Result<()> {
|
||||||
if std::fs::symlink_metadata(to).is_ok() {
|
if std::fs::symlink_metadata(to).is_ok() {
|
||||||
return Err(std::io::ErrorKind::AlreadyExists.into());
|
return Err(std::io::ErrorKind::AlreadyExists.into());
|
||||||
}
|
}
|
||||||
|
|
|
||||||
238
crates/weft-ipc-types/src/store.rs
Normal file
238
crates/weft-ipc-types/src/store.rs
Normal file
|
|
@ -0,0 +1,238 @@
|
||||||
|
//! The layout of a package store and the revisions it holds.
|
||||||
|
//!
|
||||||
|
//! Each installed revision of a package is an immutable directory named by
|
||||||
|
//! its content digest, `<store>/.revisions/<app_id>/<digest>`. The active
|
||||||
|
//! revision is chosen by `<store>/<app_id>`, a symbolic link to it that one
|
||||||
|
//! rename replaces, so an update or rollback switches every new launch at
|
||||||
|
//! once and an interrupted one leaves the previous choice in place. Stores
|
||||||
|
//! written before revisions existed hold the package directly in
|
||||||
|
//! `<store>/<app_id>`; that layout is still read.
|
||||||
|
//!
|
||||||
|
//! A session pins the revision it was launched from with a shared lock on
|
||||||
|
//! the revision directory, held for the session's lifetime. Package
|
||||||
|
//! operations remove a revision only after taking that lock exclusively, so
|
||||||
|
//! a live session keeps running on the bytes it started with.
|
||||||
|
|
||||||
|
use std::fs::File;
|
||||||
|
use std::path::{Path, PathBuf};
|
||||||
|
|
||||||
|
/// The directory of a store that holds package revisions.
|
||||||
|
pub const REVISIONS_DIR: &str = ".revisions";
|
||||||
|
|
||||||
|
/// The directory holding the revisions of `app_id`.
|
||||||
|
pub fn revisions_of(store_root: &Path, app_id: &str) -> PathBuf {
|
||||||
|
store_root.join(REVISIONS_DIR).join(app_id)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The link target that makes `revision` the active revision of `app_id`,
|
||||||
|
/// relative to the store root.
|
||||||
|
pub fn link_target(app_id: &str, revision: &str) -> PathBuf {
|
||||||
|
Path::new(REVISIONS_DIR).join(app_id).join(revision)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether `name` is a revision name: the hex content digest of a package.
|
||||||
|
pub fn is_revision_name(name: &str) -> bool {
|
||||||
|
name.len() == 64 && name.bytes().all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f'))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Where the active package of `app_id` is in a store.
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub enum Active {
|
||||||
|
/// A revision, by name, in `.revisions/<app_id>/`.
|
||||||
|
Revision { name: String, dir: PathBuf },
|
||||||
|
/// A package directory installed before revisions existed.
|
||||||
|
Directory(PathBuf),
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Active {
|
||||||
|
/// The package root.
|
||||||
|
pub fn dir(&self) -> &Path {
|
||||||
|
match self {
|
||||||
|
Self::Revision { dir, .. } | Self::Directory(dir) => dir,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Why the active package of a store cannot be determined.
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub enum StoreError {
|
||||||
|
Io(PathBuf, std::io::Error),
|
||||||
|
/// `<store>/<app_id>` is neither a package directory nor a link to one
|
||||||
|
/// of its revisions.
|
||||||
|
NotAPackage(PathBuf),
|
||||||
|
}
|
||||||
|
|
||||||
|
impl std::fmt::Display for StoreError {
|
||||||
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||||
|
match self {
|
||||||
|
Self::Io(path, e) => write!(f, "cannot read {}: {e}", path.display()),
|
||||||
|
Self::NotAPackage(path) => write!(
|
||||||
|
f,
|
||||||
|
"{} is neither a package directory nor a link to one of its revisions",
|
||||||
|
path.display()
|
||||||
|
),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl std::error::Error for StoreError {}
|
||||||
|
|
||||||
|
/// The active package of `app_id` in `store_root`, if any. A link is
|
||||||
|
/// followed only when it names one of the app's own revisions, exactly as
|
||||||
|
/// package operations write it, and that revision is a directory.
|
||||||
|
pub fn active(store_root: &Path, app_id: &str) -> Result<Option<Active>, StoreError> {
|
||||||
|
let entry = store_root.join(app_id);
|
||||||
|
let metadata = match std::fs::symlink_metadata(&entry) {
|
||||||
|
Ok(m) => m,
|
||||||
|
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
|
||||||
|
Err(e) => return Err(StoreError::Io(entry, e)),
|
||||||
|
};
|
||||||
|
if metadata.is_dir() {
|
||||||
|
return Ok(Some(Active::Directory(entry)));
|
||||||
|
}
|
||||||
|
if !metadata.file_type().is_symlink() {
|
||||||
|
return Err(StoreError::NotAPackage(entry));
|
||||||
|
}
|
||||||
|
let target = std::fs::read_link(&entry).map_err(|e| StoreError::Io(entry.clone(), e))?;
|
||||||
|
let name = target
|
||||||
|
.file_name()
|
||||||
|
.and_then(|n| n.to_str())
|
||||||
|
.filter(|n| is_revision_name(n))
|
||||||
|
.map(str::to_owned);
|
||||||
|
let Some(name) = name.filter(|n| target == link_target(app_id, n)) else {
|
||||||
|
return Err(StoreError::NotAPackage(entry));
|
||||||
|
};
|
||||||
|
let dir = revisions_of(store_root, app_id).join(&name);
|
||||||
|
match std::fs::symlink_metadata(&dir) {
|
||||||
|
Ok(m) if m.is_dir() => Ok(Some(Active::Revision { name, dir })),
|
||||||
|
Ok(_) => Err(StoreError::NotAPackage(entry)),
|
||||||
|
Err(e) => Err(StoreError::Io(dir, e)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A shared lock on a package directory, held while a session runs from it.
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub struct Pin {
|
||||||
|
_dir: File,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Pins the package directory `dir`. The lock is taken on the directory
|
||||||
|
/// that is opened, and the path must still name that directory afterwards:
|
||||||
|
/// a revision removed or replaced in between is not pinned. A directory a
|
||||||
|
/// package operation holds is not waited for, so nobody able to lock a
|
||||||
|
/// package directory can stall launches; the launch is refused instead.
|
||||||
|
pub fn pin(dir: &Path) -> std::io::Result<Pin> {
|
||||||
|
let file = File::open(dir)?;
|
||||||
|
match file.try_lock_shared() {
|
||||||
|
Ok(()) => {}
|
||||||
|
Err(std::fs::TryLockError::WouldBlock) => {
|
||||||
|
return Err(std::io::Error::other(format!(
|
||||||
|
"{} is being changed; try again",
|
||||||
|
dir.display()
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
Err(std::fs::TryLockError::Error(e)) => return Err(e),
|
||||||
|
}
|
||||||
|
if !same_file(&file, dir)? {
|
||||||
|
return Err(std::io::Error::other(format!(
|
||||||
|
"{} changed while it was being pinned",
|
||||||
|
dir.display()
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
Ok(Pin { _dir: file })
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Takes the exclusive lock on a package directory that no session pins,
|
||||||
|
/// or returns `None` while one does.
|
||||||
|
pub fn try_claim(dir: &Path) -> std::io::Result<Option<File>> {
|
||||||
|
let file = File::open(dir)?;
|
||||||
|
match file.try_lock() {
|
||||||
|
Ok(()) => Ok(Some(file)),
|
||||||
|
Err(std::fs::TryLockError::WouldBlock) => Ok(None),
|
||||||
|
Err(std::fs::TryLockError::Error(e)) => Err(e),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(unix)]
|
||||||
|
fn same_file(file: &File, path: &Path) -> std::io::Result<bool> {
|
||||||
|
use std::os::unix::fs::MetadataExt;
|
||||||
|
let opened = file.metadata()?;
|
||||||
|
let named = std::fs::symlink_metadata(path)?;
|
||||||
|
Ok(opened.dev() == named.dev() && opened.ino() == named.ino())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(not(unix))]
|
||||||
|
fn same_file(_file: &File, _path: &Path) -> std::io::Result<bool> {
|
||||||
|
Ok(true)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
fn store(name: &str) -> PathBuf {
|
||||||
|
let dir = std::env::temp_dir().join(format!("weft_store_{name}_{}", std::process::id()));
|
||||||
|
let _ = std::fs::remove_dir_all(&dir);
|
||||||
|
std::fs::create_dir_all(&dir).unwrap();
|
||||||
|
dir
|
||||||
|
}
|
||||||
|
|
||||||
|
const REV: &str = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";
|
||||||
|
|
||||||
|
#[cfg(unix)]
|
||||||
|
#[test]
|
||||||
|
fn only_links_to_the_apps_own_revisions_are_followed() {
|
||||||
|
use std::os::unix::fs::symlink;
|
||||||
|
let root = store("links");
|
||||||
|
std::fs::create_dir_all(revisions_of(&root, "org.a").join(REV)).unwrap();
|
||||||
|
std::fs::create_dir_all(revisions_of(&root, "org.b").join(REV)).unwrap();
|
||||||
|
assert!(active(&root, "org.a").unwrap().is_none());
|
||||||
|
|
||||||
|
symlink(link_target("org.a", REV), root.join("org.a")).unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
active(&root, "org.a").unwrap(),
|
||||||
|
Some(Active::Revision {
|
||||||
|
name: REV.to_owned(),
|
||||||
|
dir: revisions_of(&root, "org.a").join(REV),
|
||||||
|
})
|
||||||
|
);
|
||||||
|
// Another app's revision, an absolute target, a non-revision name.
|
||||||
|
for target in [
|
||||||
|
link_target("org.b", REV),
|
||||||
|
revisions_of(&root, "org.c").join(REV),
|
||||||
|
PathBuf::from(".revisions/org.c/latest"),
|
||||||
|
] {
|
||||||
|
let _ = std::fs::remove_file(root.join("org.c"));
|
||||||
|
std::fs::create_dir_all(revisions_of(&root, "org.c").join(REV)).unwrap();
|
||||||
|
symlink(&target, root.join("org.c")).unwrap();
|
||||||
|
assert!(
|
||||||
|
matches!(active(&root, "org.c"), Err(StoreError::NotAPackage(_))),
|
||||||
|
"{}",
|
||||||
|
target.display()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
// A package installed before revisions existed.
|
||||||
|
std::fs::create_dir(root.join("org.d")).unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
active(&root, "org.d").unwrap(),
|
||||||
|
Some(Active::Directory(root.join("org.d")))
|
||||||
|
);
|
||||||
|
std::fs::remove_dir_all(&root).unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_pinned_directory_cannot_be_claimed() {
|
||||||
|
let root = store("pin");
|
||||||
|
let dir = root.join("rev");
|
||||||
|
std::fs::create_dir(&dir).unwrap();
|
||||||
|
let pinned = pin(&dir).unwrap();
|
||||||
|
assert!(try_claim(&dir).unwrap().is_none());
|
||||||
|
// Other sessions can pin it too.
|
||||||
|
let again = pin(&dir).unwrap();
|
||||||
|
drop((pinned, again));
|
||||||
|
let claimed = try_claim(&dir).unwrap();
|
||||||
|
assert!(claimed.is_some());
|
||||||
|
drop(claimed);
|
||||||
|
std::fs::remove_dir_all(&root).unwrap();
|
||||||
|
}
|
||||||
|
}
|
||||||
521
crates/weft-ipc-types/src/trust.rs
Normal file
521
crates/weft-ipc-types/src/trust.rs
Normal file
|
|
@ -0,0 +1,521 @@
|
||||||
|
//! Package content identity, publisher keys and the trust decisions made
|
||||||
|
//! before a package is installed or launched.
|
||||||
|
//!
|
||||||
|
//! A package is signed over its content digest: the SHA-256 of a canonical
|
||||||
|
//! inventory listing every file except the root `signature.sig`, one
|
||||||
|
//! `<relative path>\t<hex sha-256>\n` line per file, sorted by path. Paths use
|
||||||
|
//! `/` and must be UTF-8 without control characters, so no name can imitate
|
||||||
|
//! the separators of other lines. Symbolic links and special files are
|
||||||
|
//! refused, so the signed bytes are exactly the files a package holds.
|
||||||
|
|
||||||
|
use std::fmt;
|
||||||
|
use std::path::{Path, PathBuf};
|
||||||
|
|
||||||
|
use ed25519_dalek::{Signature, VerifyingKey};
|
||||||
|
use sha2::{Digest, Sha256};
|
||||||
|
|
||||||
|
/// The signature file at the root of a signed package.
|
||||||
|
pub const SIGNATURE_FILE: &str = "signature.sig";
|
||||||
|
|
||||||
|
/// Why a package's content or trust could not be established.
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub enum TrustError {
|
||||||
|
/// The package holds a symbolic link.
|
||||||
|
Link(PathBuf),
|
||||||
|
/// The package holds something other than directories and regular files.
|
||||||
|
NotAFile(PathBuf),
|
||||||
|
/// A path in the package is not UTF-8.
|
||||||
|
NonUtf8(PathBuf),
|
||||||
|
/// A name in the package holds a control character.
|
||||||
|
ControlCharacter(PathBuf),
|
||||||
|
/// A key, signature or owner record is malformed.
|
||||||
|
Malformed(PathBuf, String),
|
||||||
|
Io(PathBuf, std::io::Error),
|
||||||
|
}
|
||||||
|
|
||||||
|
impl fmt::Display for TrustError {
|
||||||
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||||
|
match self {
|
||||||
|
Self::Link(p) => write!(f, "{} is a symbolic link", p.display()),
|
||||||
|
Self::NotAFile(p) => write!(f, "{} is not a regular file or directory", p.display()),
|
||||||
|
Self::NonUtf8(p) => write!(f, "{} is not a UTF-8 path", p.display()),
|
||||||
|
Self::ControlCharacter(p) => {
|
||||||
|
write!(f, "{:?} has a control character in its name", p.display())
|
||||||
|
}
|
||||||
|
Self::Malformed(p, why) => write!(f, "{}: {why}", p.display()),
|
||||||
|
Self::Io(p, e) => write!(f, "{}: {e}", p.display()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl std::error::Error for TrustError {}
|
||||||
|
|
||||||
|
fn io(path: &Path) -> impl FnOnce(std::io::Error) -> TrustError + '_ {
|
||||||
|
move |e| TrustError::Io(path.to_path_buf(), e)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The SHA-256 content digest a package signature covers.
|
||||||
|
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();
|
||||||
|
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)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn collect(
|
||||||
|
root: &Path,
|
||||||
|
dir: &Path,
|
||||||
|
entries: &mut Vec<(String, [u8; 32])>,
|
||||||
|
) -> Result<(), TrustError> {
|
||||||
|
for entry in std::fs::read_dir(dir).map_err(io(dir))? {
|
||||||
|
let path = entry.map_err(io(dir))?.path();
|
||||||
|
let relative = path
|
||||||
|
.strip_prefix(root)
|
||||||
|
.expect("read_dir yields children of the directory it reads")
|
||||||
|
.to_str()
|
||||||
|
.ok_or_else(|| TrustError::NonUtf8(path.clone()))?
|
||||||
|
.to_owned();
|
||||||
|
if relative.chars().any(char::is_control) {
|
||||||
|
return Err(TrustError::ControlCharacter(path));
|
||||||
|
}
|
||||||
|
let kind = std::fs::symlink_metadata(&path)
|
||||||
|
.map_err(io(&path))?
|
||||||
|
.file_type();
|
||||||
|
if kind.is_symlink() {
|
||||||
|
return Err(TrustError::Link(path));
|
||||||
|
} else if kind.is_dir() {
|
||||||
|
collect(root, &path, entries)?;
|
||||||
|
} else if !kind.is_file() {
|
||||||
|
return Err(TrustError::NotAFile(path));
|
||||||
|
} else if relative != SIGNATURE_FILE {
|
||||||
|
let bytes = std::fs::read(&path).map_err(io(&path))?;
|
||||||
|
entries.push((relative, Sha256::digest(&bytes).into()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A publisher's Ed25519 public key.
|
||||||
|
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||||
|
pub struct PublisherKey(VerifyingKey);
|
||||||
|
|
||||||
|
impl fmt::Debug for PublisherKey {
|
||||||
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||||
|
write!(f, "PublisherKey({})", self.to_hex())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl PublisherKey {
|
||||||
|
/// Parses 64 hex digits, the format `weft-pack generate-key` writes.
|
||||||
|
pub fn from_hex(text: &str) -> Result<Self, String> {
|
||||||
|
let bytes: [u8; 32] = hex::decode(text.trim())
|
||||||
|
.map_err(|_| "expected 64 hex digits".to_owned())?
|
||||||
|
.try_into()
|
||||||
|
.map_err(|_| "expected a 32-byte key".to_owned())?;
|
||||||
|
VerifyingKey::from_bytes(&bytes)
|
||||||
|
.map(Self)
|
||||||
|
.map_err(|_| "not a valid Ed25519 public key".to_owned())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn from_file(path: &Path) -> Result<Self, TrustError> {
|
||||||
|
let text = std::fs::read_to_string(path).map_err(io(path))?;
|
||||||
|
Self::from_hex(&text).map_err(|why| TrustError::Malformed(path.to_path_buf(), why))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The key as 64 lowercase hex digits; it also identifies the publisher.
|
||||||
|
pub fn to_hex(&self) -> String {
|
||||||
|
hex::encode(self.0.as_bytes())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether `signature` signs `digest` with this key.
|
||||||
|
pub fn signed(&self, digest: &[u8; 32], signature: &Signature) -> bool {
|
||||||
|
self.0.verify_strict(digest, signature).is_ok()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Reads the package's signature, or `None` when the package is unsigned.
|
||||||
|
pub fn read_signature(package_root: &Path) -> Result<Option<Signature>, TrustError> {
|
||||||
|
let path = package_root.join(SIGNATURE_FILE);
|
||||||
|
match std::fs::symlink_metadata(&path) {
|
||||||
|
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
|
||||||
|
Err(e) => return Err(TrustError::Io(path, e)),
|
||||||
|
Ok(m) if !m.file_type().is_file() => return Err(TrustError::NotAFile(path)),
|
||||||
|
Ok(_) => {}
|
||||||
|
}
|
||||||
|
let text = std::fs::read_to_string(&path).map_err(io(&path))?;
|
||||||
|
let bytes: [u8; 64] = hex::decode(text.trim())
|
||||||
|
.ok()
|
||||||
|
.and_then(|b| b.try_into().ok())
|
||||||
|
.ok_or_else(|| TrustError::Malformed(path, "expected 128 hex digits".to_owned()))?;
|
||||||
|
Ok(Some(Signature::from_bytes(&bytes)))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The publisher keys this host trusts to sign packages.
|
||||||
|
#[derive(Debug, Default)]
|
||||||
|
pub struct TrustStore {
|
||||||
|
keys: Vec<PublisherKey>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl TrustStore {
|
||||||
|
/// The trust store directories, in order: `$WEFT_TRUSTED_KEYS` alone when
|
||||||
|
/// set; otherwise the user's `$XDG_CONFIG_HOME/weft/trusted-keys` (or
|
||||||
|
/// `~/.config/weft/trusted-keys`) and the system `/etc/weft/trusted-keys`.
|
||||||
|
pub fn directories() -> Vec<PathBuf> {
|
||||||
|
if let Some(dir) = std::env::var_os("WEFT_TRUSTED_KEYS") {
|
||||||
|
return vec![PathBuf::from(dir)];
|
||||||
|
}
|
||||||
|
let config = std::env::var_os("XDG_CONFIG_HOME")
|
||||||
|
.map(PathBuf::from)
|
||||||
|
.filter(|dir| dir.is_absolute())
|
||||||
|
.or_else(|| {
|
||||||
|
std::env::var_os("HOME")
|
||||||
|
.map(PathBuf::from)
|
||||||
|
.filter(|home| home.is_absolute())
|
||||||
|
.map(|home| home.join(".config"))
|
||||||
|
});
|
||||||
|
let mut dirs: Vec<PathBuf> = config
|
||||||
|
.map(|dir| dir.join("weft/trusted-keys"))
|
||||||
|
.into_iter()
|
||||||
|
.collect();
|
||||||
|
dirs.push(PathBuf::from("/etc/weft/trusted-keys"));
|
||||||
|
dirs
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Loads every `*.pub` file in `directories`. A missing directory holds no
|
||||||
|
/// keys; a malformed key file is an error rather than silently ignored.
|
||||||
|
pub fn load(directories: &[PathBuf]) -> Result<Self, TrustError> {
|
||||||
|
let mut keys = Vec::new();
|
||||||
|
for dir in directories {
|
||||||
|
let entries = match std::fs::read_dir(dir) {
|
||||||
|
Err(e) if e.kind() == std::io::ErrorKind::NotFound => continue,
|
||||||
|
other => other.map_err(io(dir))?,
|
||||||
|
};
|
||||||
|
let mut files: Vec<PathBuf> = entries
|
||||||
|
.map(|e| e.map(|e| e.path()).map_err(io(dir)))
|
||||||
|
.collect::<Result<_, _>>()?;
|
||||||
|
files.sort();
|
||||||
|
for file in files
|
||||||
|
.into_iter()
|
||||||
|
.filter(|f| f.extension().is_some_and(|e| e == "pub"))
|
||||||
|
{
|
||||||
|
keys.push(PublisherKey::from_file(&file)?);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(Self { keys })
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn keys(&self) -> &[PublisherKey] {
|
||||||
|
&self.keys
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The trusted key that signed the package at `package_root`, if any.
|
||||||
|
pub fn signer(&self, package_root: &Path) -> Result<Option<PublisherKey>, TrustError> {
|
||||||
|
let Some(signature) = read_signature(package_root)? else {
|
||||||
|
return Ok(None);
|
||||||
|
};
|
||||||
|
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))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Who an application ID belongs to on this host. The record outlives the
|
||||||
|
/// package while the app's data remains, so another publisher cannot take
|
||||||
|
/// over the ID, and the data with it, by reusing it.
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
pub enum Owner {
|
||||||
|
/// Installed from packages signed by this trusted key.
|
||||||
|
Verified(PublisherKey),
|
||||||
|
/// Installed as development content, without a trusted signature.
|
||||||
|
Development,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl fmt::Display for Owner {
|
||||||
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||||
|
match self {
|
||||||
|
Self::Verified(key) => write!(f, "publisher {}", key.to_hex()),
|
||||||
|
Self::Development => f.write_str("development installation"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Where the owner of `app_id` is recorded, beside the app's data. Callers
|
||||||
|
/// pass a valid app ID, which cannot leave the owners directory.
|
||||||
|
pub fn owner_record_path(data_home: &Path, app_id: &str) -> PathBuf {
|
||||||
|
data_home.join("weft/owners").join(app_id)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Reads an owner record: `verified <key>` or `development`.
|
||||||
|
pub fn read_owner(record: &Path) -> Result<Option<Owner>, TrustError> {
|
||||||
|
let text = match std::fs::read_to_string(record) {
|
||||||
|
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
|
||||||
|
other => other.map_err(io(record))?,
|
||||||
|
};
|
||||||
|
let malformed = |why: &str| TrustError::Malformed(record.to_path_buf(), why.to_owned());
|
||||||
|
match text.trim().split_once(' ') {
|
||||||
|
Some(("verified", key)) => PublisherKey::from_hex(key)
|
||||||
|
.map(|k| Some(Owner::Verified(k)))
|
||||||
|
.map_err(|why| malformed(&why)),
|
||||||
|
None if text.trim() == "development" => Ok(Some(Owner::Development)),
|
||||||
|
_ => Err(malformed("expected 'verified <key>' or 'development'")),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Records the owner of an app ID. An existing record is never replaced, and
|
||||||
|
/// a record is either absent or complete: it is written and synced under a
|
||||||
|
/// temporary name, then linked into place.
|
||||||
|
pub fn write_owner(record: &Path, owner: Owner) -> Result<(), TrustError> {
|
||||||
|
use std::io::Write;
|
||||||
|
let parent = record.parent().expect("owner records live in a directory");
|
||||||
|
std::fs::create_dir_all(parent).map_err(io(parent))?;
|
||||||
|
let text = match owner {
|
||||||
|
Owner::Verified(key) => format!("verified {}\n", key.to_hex()),
|
||||||
|
Owner::Development => "development\n".to_owned(),
|
||||||
|
};
|
||||||
|
let name = record
|
||||||
|
.file_name()
|
||||||
|
.and_then(|n| n.to_str())
|
||||||
|
.unwrap_or("record");
|
||||||
|
let temp = parent.join(format!(".{name}.{}.tmp", std::process::id()));
|
||||||
|
let _ = std::fs::remove_file(&temp);
|
||||||
|
let written = (|| {
|
||||||
|
let mut file = std::fs::OpenOptions::new()
|
||||||
|
.write(true)
|
||||||
|
.create_new(true)
|
||||||
|
.open(&temp)?;
|
||||||
|
file.write_all(text.as_bytes())?;
|
||||||
|
file.sync_all()
|
||||||
|
})()
|
||||||
|
.map_err(io(&temp));
|
||||||
|
let linked = written.and_then(|()| std::fs::hard_link(&temp, record).map_err(io(record)));
|
||||||
|
let _ = std::fs::remove_file(&temp);
|
||||||
|
linked?;
|
||||||
|
std::fs::File::open(parent)
|
||||||
|
.and_then(|dir| dir.sync_all())
|
||||||
|
.map_err(io(parent))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Takes the lock that serialises every change to the installation and
|
||||||
|
/// owner record of `app_id`, held until the returned file is dropped.
|
||||||
|
pub fn lock_owner(data_home: &Path, app_id: &str) -> Result<std::fs::File, TrustError> {
|
||||||
|
let dir = data_home.join("weft/owners");
|
||||||
|
if !crate::package::is_valid_app_id(app_id) {
|
||||||
|
return Err(TrustError::Malformed(
|
||||||
|
dir,
|
||||||
|
format!("'{app_id}' is not a valid app ID"),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
std::fs::create_dir_all(&dir).map_err(io(&dir))?;
|
||||||
|
let path = dir.join(format!(".{app_id}.lock"));
|
||||||
|
let file = std::fs::OpenOptions::new()
|
||||||
|
.write(true)
|
||||||
|
.create(true)
|
||||||
|
.truncate(false)
|
||||||
|
.open(&path)
|
||||||
|
.map_err(io(&path))?;
|
||||||
|
file.lock().map_err(io(&path))?;
|
||||||
|
Ok(file)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use ed25519_dalek::{Signer, SigningKey};
|
||||||
|
|
||||||
|
fn dir(name: &str) -> PathBuf {
|
||||||
|
let dir = std::env::temp_dir().join(format!("weft_trust_{name}_{}", std::process::id()));
|
||||||
|
let _ = std::fs::remove_dir_all(&dir);
|
||||||
|
std::fs::create_dir_all(dir.join("ui")).unwrap();
|
||||||
|
std::fs::write(dir.join("wapp.toml"), b"[package]\n").unwrap();
|
||||||
|
std::fs::write(dir.join("ui/index.html"), b"<p>").unwrap();
|
||||||
|
dir
|
||||||
|
}
|
||||||
|
|
||||||
|
fn sign(dir: &Path, seed: u8) -> PublisherKey {
|
||||||
|
let key = SigningKey::from_bytes(&[seed; 32]);
|
||||||
|
let signature = key.sign(&content_digest(dir).unwrap());
|
||||||
|
std::fs::write(dir.join(SIGNATURE_FILE), hex::encode(signature.to_bytes())).unwrap();
|
||||||
|
PublisherKey(key.verifying_key())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn store(keys: &[PublisherKey]) -> TrustStore {
|
||||||
|
TrustStore {
|
||||||
|
keys: keys.to_vec(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_committed_demo_signatures_verify_with_the_demo_key() {
|
||||||
|
let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../..");
|
||||||
|
let key = PublisherKey::from_file(&root.join("examples/keys/weft-sign.pub")).unwrap();
|
||||||
|
for demo in ["org.weft.demo.counter", "org.weft.demo.notes"] {
|
||||||
|
let package = root.join("examples").join(demo);
|
||||||
|
assert_eq!(store(&[key]).signer(&package).unwrap(), Some(key), "{demo}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn any_changed_file_breaks_the_signature() {
|
||||||
|
let dir = dir("tamper");
|
||||||
|
let key = sign(&dir, 1);
|
||||||
|
assert_eq!(store(&[key]).signer(&dir).unwrap(), Some(key));
|
||||||
|
std::fs::write(dir.join("ui/index.html"), b"<p>changed").unwrap();
|
||||||
|
assert_eq!(store(&[key]).signer(&dir).unwrap(), None);
|
||||||
|
std::fs::write(dir.join("ui/index.html"), b"<p>").unwrap();
|
||||||
|
std::fs::write(dir.join("ui/extra.js"), b"").unwrap();
|
||||||
|
assert_eq!(store(&[key]).signer(&dir).unwrap(), None);
|
||||||
|
std::fs::remove_dir_all(&dir).unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn only_trusted_keys_are_signers_and_unsigned_packages_have_none() {
|
||||||
|
let dir = dir("untrusted");
|
||||||
|
assert_eq!(store(&[]).signer(&dir).unwrap(), None);
|
||||||
|
let key = sign(&dir, 2);
|
||||||
|
let other = PublisherKey(SigningKey::from_bytes(&[3; 32]).verifying_key());
|
||||||
|
assert_eq!(store(&[other]).signer(&dir).unwrap(), None);
|
||||||
|
assert_eq!(store(&[other, key]).signer(&dir).unwrap(), Some(key));
|
||||||
|
std::fs::remove_dir_all(&dir).unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(unix)]
|
||||||
|
#[test]
|
||||||
|
fn names_cannot_imitate_other_inventory_lines() {
|
||||||
|
// With files ui/policy.txt and ui/z.css signed, a directory named
|
||||||
|
// "ui/policy.txt\t<hash>\nui" holding z.css would reproduce the
|
||||||
|
// inventory without policy.txt. Such names have no digest.
|
||||||
|
let dir = dir("forged");
|
||||||
|
std::fs::write(dir.join("ui/policy.txt"), b"default-src 'self'").unwrap();
|
||||||
|
std::fs::write(dir.join("ui/z.css"), b"p{}").unwrap();
|
||||||
|
let signed = content_digest(&dir).unwrap();
|
||||||
|
let policy_hash = hex::encode(Sha256::digest(b"default-src 'self'"));
|
||||||
|
std::fs::remove_file(dir.join("ui/policy.txt")).unwrap();
|
||||||
|
let forged = dir.join(format!("ui/policy.txt\t{policy_hash}\nui"));
|
||||||
|
std::fs::create_dir_all(&forged).unwrap();
|
||||||
|
std::fs::rename(dir.join("ui/z.css"), forged.join("z.css")).unwrap();
|
||||||
|
let refused = content_digest(&dir);
|
||||||
|
assert!(matches!(refused, Err(TrustError::ControlCharacter(_))));
|
||||||
|
assert_ne!(refused.ok(), Some(signed));
|
||||||
|
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()));
|
||||||
|
let held = lock_owner(&home, "org.weft.test.lock").unwrap();
|
||||||
|
let path = home.join("weft/owners/.org.weft.test.lock.lock");
|
||||||
|
let other = std::fs::OpenOptions::new().write(true).open(&path).unwrap();
|
||||||
|
assert!(other.try_lock().is_err());
|
||||||
|
drop(held);
|
||||||
|
assert!(other.try_lock().is_ok());
|
||||||
|
// A name that would open fine but is not an app ID is refused.
|
||||||
|
assert!(lock_owner(&home, "Org.weft.test").is_err());
|
||||||
|
assert!(!home.join("weft/owners/.Org.weft.test.lock").exists());
|
||||||
|
std::fs::remove_dir_all(&home).unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(target_os = "linux")]
|
||||||
|
#[test]
|
||||||
|
fn links_and_special_files_have_no_content_digest() {
|
||||||
|
let dir = dir("links");
|
||||||
|
std::os::unix::fs::symlink("/etc/hostname", dir.join("ui/linked")).unwrap();
|
||||||
|
assert!(matches!(content_digest(&dir), Err(TrustError::Link(_))));
|
||||||
|
std::fs::remove_file(dir.join("ui/linked")).unwrap();
|
||||||
|
std::os::unix::fs::symlink(dir.join("ui"), dir.join("view")).unwrap();
|
||||||
|
assert!(matches!(content_digest(&dir), Err(TrustError::Link(_))));
|
||||||
|
std::fs::remove_file(dir.join("view")).unwrap();
|
||||||
|
rustix::fs::mknodat(
|
||||||
|
rustix::fs::CWD,
|
||||||
|
dir.join("fifo"),
|
||||||
|
rustix::fs::FileType::Fifo,
|
||||||
|
rustix::fs::Mode::from_raw_mode(0o600),
|
||||||
|
0,
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
assert!(matches!(content_digest(&dir), Err(TrustError::NotAFile(_))));
|
||||||
|
std::fs::remove_dir_all(&dir).unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn trust_stores_load_pub_files_and_refuse_malformed_keys() {
|
||||||
|
let dir = dir("store");
|
||||||
|
let keys = dir.join("keys");
|
||||||
|
std::fs::create_dir_all(&keys).unwrap();
|
||||||
|
let key = PublisherKey(SigningKey::from_bytes(&[4; 32]).verifying_key());
|
||||||
|
std::fs::write(keys.join("a.pub"), key.to_hex()).unwrap();
|
||||||
|
std::fs::write(keys.join("notes.txt"), "not a key").unwrap();
|
||||||
|
let loaded = TrustStore::load(&[keys.clone(), dir.join("missing")]).unwrap();
|
||||||
|
assert_eq!(loaded.keys(), [key]);
|
||||||
|
std::fs::write(keys.join("b.pub"), "zz").unwrap();
|
||||||
|
assert!(matches!(
|
||||||
|
TrustStore::load(&[keys]),
|
||||||
|
Err(TrustError::Malformed(..))
|
||||||
|
));
|
||||||
|
std::fs::remove_dir_all(&dir).unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn owner_records_round_trip_and_are_never_replaced() {
|
||||||
|
let dir = dir("owners");
|
||||||
|
let key = PublisherKey(SigningKey::from_bytes(&[5; 32]).verifying_key());
|
||||||
|
let verified = owner_record_path(&dir, "org.weft.test.a");
|
||||||
|
let development = owner_record_path(&dir, "org.weft.test.b");
|
||||||
|
assert_eq!(read_owner(&verified).unwrap(), None);
|
||||||
|
write_owner(&verified, Owner::Verified(key)).unwrap();
|
||||||
|
write_owner(&development, Owner::Development).unwrap();
|
||||||
|
assert_eq!(read_owner(&verified).unwrap(), Some(Owner::Verified(key)));
|
||||||
|
assert_eq!(read_owner(&development).unwrap(), Some(Owner::Development));
|
||||||
|
assert!(write_owner(&verified, Owner::Development).is_err());
|
||||||
|
assert_eq!(read_owner(&verified).unwrap(), Some(Owner::Verified(key)));
|
||||||
|
std::fs::write(&development, "someone else\n").unwrap();
|
||||||
|
assert!(read_owner(&development).is_err());
|
||||||
|
std::fs::remove_dir_all(&dir).unwrap();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -17,3 +17,6 @@ rand = "0.8"
|
||||||
hex = "0.4"
|
hex = "0.4"
|
||||||
tar = "0.4"
|
tar = "0.4"
|
||||||
zstd = "0.13"
|
zstd = "0.13"
|
||||||
|
|
||||||
|
[target.'cfg(unix)'.dependencies]
|
||||||
|
rustix = { version = "1", features = ["fs"] }
|
||||||
|
|
|
||||||
File diff suppressed because it is too large
Load diff
|
|
@ -28,7 +28,7 @@ WASI Preview 2 + Component Model execution host (Wasmtime 30). Runs the componen
|
||||||
|
|
||||||
### weft-pack
|
### weft-pack
|
||||||
|
|
||||||
Package management CLI. Subcommands: `check` (validate wapp.toml + wasm module), `sign` (Ed25519 signature), `verify` (verify signature), `generate-key`, `install`, `uninstall`, `list`, `build-image` (EROFS dm-verity), `info`.
|
Package management CLI. Subcommands: `check` (validate wapp.toml, entries and package content), `sign` (Ed25519 signature over every file), `verify` (verify signature), `generate-key`, `install` (requires a signature by a trusted key unless `--dev`; records the app ID's owner; installs or updates, see [Installing and updating](#installing-and-updating)), `uninstall`, `rollback`, `approve` (approve the app's declared capabilities, or those listed; `install --approve` does so at installation), `list`, `build-image` (EROFS dm-verity), `info`.
|
||||||
|
|
||||||
### weft-file-portal
|
### weft-file-portal
|
||||||
|
|
||||||
|
|
@ -102,7 +102,7 @@ Fetch grants name hosts, not addresses: ports are not restricted, and a host tha
|
||||||
app.wasm — WASI Component Model binary
|
app.wasm — WASI Component Model binary
|
||||||
ui/
|
ui/
|
||||||
index.html — entry point served by weft-app-shell
|
index.html — entry point served by weft-app-shell
|
||||||
signature.sig — Ed25519 signature over SHA-256 of (wapp.toml + app.wasm)
|
signature.sig — Ed25519 signature over the content digest of every other file (see security.md)
|
||||||
```
|
```
|
||||||
|
|
||||||
Package store roots (in priority order):
|
Package store roots (in priority order):
|
||||||
|
|
@ -115,11 +115,19 @@ Package store roots (in priority order):
|
||||||
`weft-appd` resolves a launch once. A verified image in any store root takes precedence over a directory install in any root, so a user's directory cannot shadow a system image; otherwise the first root with a directory install is used:
|
`weft-appd` resolves a launch once. A verified image in any store root takes precedence over a directory install in any root, so a user's directory cannot shadow a system image; otherwise the first root with a directory install is used:
|
||||||
|
|
||||||
- **Verified image:** `<root>/<id>.app.img` with its dm-verity hash tree `<id>.app.hash` and root hash `<id>.app.roothash`, the names `weft-pack build-image` and `build-verity` produce. When any of the three exists, the image must mount through `weft-mount-helper`; a missing companion, a malformed root hash, a missing helper or a failed mount refuses the launch, and appd never falls back to a directory install. The root hash is read from the store next to the image and is not yet authenticated, so dm-verity detects corruption but not a store whose image, hash tree and root hash were replaced together. The mount belongs to the session and is released when the session stops.
|
- **Verified image:** `<root>/<id>.app.img` with its dm-verity hash tree `<id>.app.hash` and root hash `<id>.app.roothash`, the names `weft-pack build-image` and `build-verity` produce. When any of the three exists, the image must mount through `weft-mount-helper`; a missing companion, a malformed root hash, a missing helper or a failed mount refuses the launch, and appd never falls back to a directory install. The root hash is read from the store next to the image and is not yet authenticated, so dm-verity detects corruption but not a store whose image, hash tree and root hash were replaced together. The mount belongs to the session and is released when the session stops.
|
||||||
- **Directory install:** `<root>/<id>/wapp.toml`.
|
- **Directory install:** `<root>/<id>`, a link to the active revision `.revisions/<id>/<digest>` written by `weft-pack`, or, for a store written before revisions, a package directory. A link is followed only in exactly that form, to one of the app's own revisions; any other link is refused (403). The session runs from the revision directory itself and holds a shared lock on it until it stops, so it keeps its bytes while an update or rollback switches the link.
|
||||||
|
|
||||||
The package root must be a directory and its manifest a regular file, neither a symbolic link, and the manifest must declare the requested ID. `[runtime].module` and `[ui].entry` must be relative paths of plain components, without symbolic links, naming regular files inside that root. The component, the UI document and the capabilities all come from that one manifest. A refused launch reports 400 (invalid ID), 404 (not installed), 403 (invalid package, image or image metadata) or 500 (the host cannot read the package or mount the image).
|
The package root must be a directory and its manifest a regular file, neither a symbolic link, and the manifest must declare the requested ID. `[runtime].module` and `[ui].entry` must be relative paths of plain components, without symbolic links, naming regular files inside that root. The component, the UI document and the capabilities all come from that one manifest. A refused launch reports 400 (invalid ID), 404 (not installed), 403 (invalid package, image or image metadata) or 500 (the host cannot read the package or mount the image).
|
||||||
|
|
||||||
A directory install can still be changed by its owner while a session runs, and nothing verifies its content at launch.
|
A directory install can still be changed by its owner while a session runs; for a verified owner, appd checks its content against the signature at launch, with the limits security.md describes.
|
||||||
|
|
||||||
|
### Installing and updating
|
||||||
|
|
||||||
|
`weft-pack install` copies the package into a staging directory in the store and checks, verifies and admits that copy, so the bytes that are checked are the bytes that are installed. The copy is flushed to disk and renamed to an immutable revision named by its content digest, `<root>/.revisions/<id>/<digest>`; installing the same content again reuses it. One rename of the link `<root>/<id>` then makes it active. The rename of the link is the commit point. An installation that fails before it leaves the previously active revision active, or, for a first installation, nothing installed; a failed first installation also removes the owner record it created, while one interrupted by a crash leaves that record until `weft-pack uninstall <id>` releases it. After the commit point the update stands, and what an interruption leaves to tidy is collected later. A revision is reused only when it still holds the same content and signature file; otherwise the new copy replaces it in one exchange, unless a running session uses it. Such a replacement, for the same content with another signature file, is visible under the revision's name at once, even if the installation then fails. A package directory from before revisions is replaced in one exchange with the new link, only while no session runs from it and only after the app data an earlier weft-appd kept in its `data` directory has been moved to the app data directory, under the same rules as for uninstall; otherwise the update stops before replacing anything. Data moved this way stays in the app data directory even if the update is then refused.
|
||||||
|
|
||||||
|
The revision active before an update is kept for `weft-pack rollback <id>`, which makes it active again, keeping the revision it replaces in turn; it is checked against the owner record again, so a revision whose publisher key was withdrawn is not rolled back to. Other revisions are removed by each install, rollback or uninstall of the app, except those a session still runs from; those stay until a later operation on the app finds them unused. Temporary links of interrupted activations are removed then too, and staging, unpacking and removal directories once they are an hour old. `weft-pack uninstall` removes the link, so new launches no longer find the app, and the kept revision; running sessions continue on their revisions. Apart from that move of data from the earlier layout, app data is never touched by these operations. Package revisions and app data are independent: rolling back a package does not roll back its data.
|
||||||
|
|
||||||
|
A launch is refused (500, try again) while a package operation holds the revision it would run from, rather than waiting for it. Only sessions started by this weft-appd hold their revisions: a session left from an earlier version, or processes that outlive weft-appd, do not, and a package directory from before revisions such sessions run from can be replaced under them. Package operations on one app are serialised by the owner lock in the data home of the user running them; the store itself is not locked against users with other data homes.
|
||||||
|
|
||||||
## Closing an application
|
## Closing an application
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -90,6 +90,7 @@ python3 tests/frame/check_app_data.py # Notes data from the earlier layout is m
|
||||||
python3 tests/frame/check_confinement.py # an app page reaches only its UI files and its session bridge
|
python3 tests/frame/check_confinement.py # an app page reaches only its UI files and its session bridge
|
||||||
python3 tests/frame/check_activation.py # apps fill the work area above the taskbar; launch and ACTIVATE_APP raise and focus
|
python3 tests/frame/check_activation.py # apps fill the work area above the taskbar; launch and ACTIVATE_APP raise and focus
|
||||||
python3 tests/frame/check_system_ui.py # the system UI's launcher and taskbar work from the keyboard alone, reached with a Super tap
|
python3 tests/frame/check_system_ui.py # the system UI's launcher and taskbar work from the keyboard alone, reached with a Super tap
|
||||||
|
python3 tests/frame/check_update.py # updates leave running sessions on their revision; failed updates, rollback and uninstall
|
||||||
```
|
```
|
||||||
|
|
||||||
## Demo apps (wasm32-wasip2)
|
## Demo apps (wasm32-wasip2)
|
||||||
|
|
@ -127,6 +128,16 @@ weft-pack sign ./examples/org.weft.demo.counter --key ./keys/weft-sign.key
|
||||||
weft-pack verify ./examples/org.weft.demo.counter --key ./keys/weft-sign.pub
|
weft-pack verify ./examples/org.weft.demo.counter --key ./keys/weft-sign.pub
|
||||||
```
|
```
|
||||||
|
|
||||||
|
Installation requires a signature by a trusted key. To install the demos with the demo key, trust it for your user (the key is a test fixture; do not trust it on a system you depend on):
|
||||||
|
|
||||||
|
```sh
|
||||||
|
mkdir -p ~/.config/weft/trusted-keys
|
||||||
|
cp examples/keys/weft-sign.pub ~/.config/weft/trusted-keys/weft-demo.pub
|
||||||
|
weft-pack install examples/org.weft.demo.notes
|
||||||
|
```
|
||||||
|
|
||||||
|
Unsigned packages under development install with `weft-pack install <dir> --dev`, recorded as development content and marked `(development)` by `weft-pack list`. See `docs/security.md` for the trust store and app ID ownership.
|
||||||
|
|
||||||
## NixOS VM (requires Nix with flakes)
|
## NixOS VM (requires Nix with flakes)
|
||||||
|
|
||||||
Build the VM image:
|
Build the VM image:
|
||||||
|
|
|
||||||
|
|
@ -8,7 +8,9 @@ WEFT OS enforces a capability-based security model. No capability is granted by
|
||||||
|
|
||||||
`weft-pack check` validates capability strings against the shared vocabulary in `weft_ipc_types::capability`. Unknown capability strings are rejected. At launch, `weft-appd` derives the session's grants from the manifest and refuses to start a package with a capability that is unknown, unsupported or unsatisfiable. `weft-runtime` enforces the grants it is given: read-only directories are preopened read-only, and each host import checks its grant on every call. See the capability table in `architecture.md`.
|
`weft-pack check` validates capability strings against the shared vocabulary in `weft_ipc_types::capability`. Unknown capability strings are rejected. At launch, `weft-appd` derives the session's grants from the manifest and refuses to start a package with a capability that is unknown, unsupported or unsatisfiable. `weft-runtime` enforces the grants it is given: read-only directories are preopened read-only, and each host import checks its grant on every call. See the capability table in `architecture.md`.
|
||||||
|
|
||||||
Installing a package does not yet ask the user to approve its capabilities; every declared, supported capability is granted at launch.
|
A package gets only the capabilities the user approved. `weft-pack install --approve` approves those the installed package declares. `weft-pack approve <id>` approves those of the package weft-appd would launch, the first store in weft-appd's order that holds the app, which also covers packages in the system store. `weft-pack approve <id> <capability>...` adds the listed capabilities to the app's approval; for a package weft-pack can read they must be ones it declares. Listing them is the only way to approve an app installed as a verified image, since weft-pack cannot read an image's manifest; for the same reason, approvals for an image are not reduced when it is updated, and uninstalling a directory copy of the app removes them although the image remains. Without approval, `install` and `rollback` list what still needs it.
|
||||||
|
|
||||||
|
The approval is recorded per user, in `$XDG_DATA_HOME/weft/approvals/<id>`; weft-pack and weft-appd must use the same data home, as for owner records. An installation by another user, such as root installing into the system store, approves nothing for this user. weft-appd refuses to launch an app that declares a capability the record does not hold (403, naming the capabilities), after refusing unknown and unsupported capabilities and before preparing anything for the session. An approval covers what the installed package declares: an update or rollback drops approvals for capabilities the package no longer declares, so a capability declared again later, or newly, needs approval again. Uninstalling the app forgets its approval unless another store still holds the app. Approvals are keyed by app ID, not by store or publisher. Private app data (`fs:read:app-data`, `fs:rw:app-data`) is a minimal execution resource and needs no approval. Signature verification and approval are separate decisions: a trusted signature approves nothing.
|
||||||
|
|
||||||
## Process Isolation
|
## Process Isolation
|
||||||
|
|
||||||
|
|
@ -18,11 +20,19 @@ Each app session runs as a separate OS process (`weft-runtime`). When systemd is
|
||||||
|
|
||||||
Apps access the filesystem only through WASI preopened directories. Each capability maps to a specific host path preopened at a fixed guest path. The `weft-file-portal` process applies the same directory grants and access modes, but checks paths lexically: it blocks `..` traversal, not symbolic links. Components cannot currently reach its socket, since the runtime grants them no socket access.
|
Apps access the filesystem only through WASI preopened directories. Each capability maps to a specific host path preopened at a fixed guest path. The `weft-file-portal` process applies the same directory grants and access modes, but checks paths lexically: it blocks `..` traversal, not symbolic links. Components cannot currently reach its socket, since the runtime grants them no socket access.
|
||||||
|
|
||||||
## Package Signing
|
## Package Signing and Trust
|
||||||
|
|
||||||
Packages are signed with Ed25519 (`ed25519-dalek`). The signature covers the SHA-256 hash of `wapp.toml` and `app.wasm`. `weft-pack verify` checks the signature before installation.
|
Packages are signed with Ed25519 over their content digest: the SHA-256 of an inventory listing every file in the package except the root `signature.sig`, one `<path>\t<sha-256>` line per file sorted by path. Every file is covered, including the UI. Names must be UTF-8 without control characters, so no name can imitate other inventory lines. Packages may hold only directories and regular files; a symbolic link or special file makes `weft-pack check`, `sign`, `verify` and `install` refuse the package. The committed demo signatures verify under this rule.
|
||||||
|
|
||||||
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`.
|
`weft-pack install` admits a package only when its signature verifies with a key in the trust store: `*.pub` files (64 hex digits) in `$XDG_CONFIG_HOME/weft/trusted-keys` and `/etc/weft/trusted-keys`, or only in `$WEFT_TRUSTED_KEYS` when that is set. A malformed key file is an error, not skipped. An unsigned or untrusted package is refused unless the developer passes `--dev`, which installs it as development content. The package is copied into the store first and checked on that copy, which is then renamed into place, so the bytes that are verified are the bytes that are installed. The copy holds each source directory open and opens its entries relative to it, never following links, so replacing a directory with a link while the copy runs cannot redirect it. Each entry must keep the type, device and inode it had when it was examined just before it was opened, and a FIFO is never waited on. A device node hard-linked in place of a file in that interval is opened before it is refused; `fs.protected_hardlinks`, on by default, prevents such links to devices unless the attacker owns them or holds CAP_FOWNER. Installed files are set to 0644, or 0755 when the source is executable, and directories to 0755, whatever the umask, so no installed file is writable by other users; a store, and any of its parents, that does not exist yet is created at 0755. The app ID is read from the staged copy. Archives are unpacked into a fresh private directory in the store, which is always removed.
|
||||||
|
|
||||||
|
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, 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`).
|
||||||
|
|
||||||
## Seccomp
|
## Seccomp
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -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),
|
||||||
|
|
|
||||||
|
|
@ -152,6 +152,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):
|
||||||
|
|
@ -167,6 +173,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()),
|
||||||
})
|
})
|
||||||
|
|
|
||||||
|
|
@ -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),
|
||||||
})
|
})
|
||||||
|
|
|
||||||
|
|
@ -219,12 +219,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),
|
||||||
|
|
|
||||||
232
tests/frame/check_update.py
Executable file
232
tests/frame/check_update.py
Executable file
|
|
@ -0,0 +1,232 @@
|
||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Check that package updates are transactional and leave running sessions alone.
|
||||||
|
|
||||||
|
The harness installs a test application with weft-pack into a private store
|
||||||
|
and runs weft-appd with the real runtime and app shell on a nested desktop
|
||||||
|
(see session.py). Each revision of the application's page shows its own
|
||||||
|
colour. In the presented pixels and the store:
|
||||||
|
|
||||||
|
1. A session started from revision one keeps showing it after the package is
|
||||||
|
updated to revision two, and its app shell runs from revision one's own
|
||||||
|
directory, which the update keeps while the session runs.
|
||||||
|
2. An update that fails (an invalid component) changes nothing: revision two
|
||||||
|
stays active.
|
||||||
|
3. A session launched after the update shows revision two.
|
||||||
|
4. Once the first session has ended, the next update removes revision one,
|
||||||
|
and keeps revision two for rollback; `weft-pack rollback` makes revision
|
||||||
|
two active again.
|
||||||
|
5. Uninstalling while a session runs stops new launches (404) but not the
|
||||||
|
session; the next uninstall, after it has ended, removes the revisions.
|
||||||
|
6. An app declaring a capability (notifications) is refused at launch (403)
|
||||||
|
until `weft-pack approve` approves it, and then launches.
|
||||||
|
|
||||||
|
The application is unsigned development content using the Counter demo's
|
||||||
|
component.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import argparse
|
||||||
|
import os
|
||||||
|
import shutil
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
import tempfile
|
||||||
|
import time
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
||||||
|
from check_counter import AppdClient, free_port, read_endpoint # noqa: E402
|
||||||
|
from session import ROOT, Desktop, SessionError, bounding_box, missing_tools, parse_ppm # noqa: E402
|
||||||
|
|
||||||
|
APP_ID = "org.weft.test.update"
|
||||||
|
COLOURS = {"one": (200, 0, 0), "two": (0, 0, 200), "three": (0, 160, 0)}
|
||||||
|
VERSIONS = {"one": 1, "two": 2, "bad": 3, "three": 4}
|
||||||
|
STARTUP_TIMEOUT = 120.0
|
||||||
|
|
||||||
|
|
||||||
|
def write_revision(src, name, wasm=None, capabilities="[]"):
|
||||||
|
shutil.rmtree(src, ignore_errors=True)
|
||||||
|
(src / "ui").mkdir(parents=True)
|
||||||
|
(src / "wapp.toml").write_text(
|
||||||
|
f'[package]\nid = "{APP_ID}"\nname = "Update"\nversion = "0.0.{VERSIONS[name]}"\n'
|
||||||
|
f'capabilities = {capabilities}\n'
|
||||||
|
'[runtime]\nmodule = "app.wasm"\n[ui]\nentry = "ui/index.html"\n')
|
||||||
|
if wasm is None:
|
||||||
|
shutil.copy(ROOT / "examples/org.weft.demo.counter/app.wasm", src / "app.wasm")
|
||||||
|
else:
|
||||||
|
(src / "app.wasm").write_bytes(wasm)
|
||||||
|
colour = COLOURS.get(name, (0, 0, 0))
|
||||||
|
(src / "ui/index.html").write_text(
|
||||||
|
'<!DOCTYPE html><html><body style="margin:0;width:100vw;height:100vh;'
|
||||||
|
f'background:rgb{colour}"></body></html>')
|
||||||
|
|
||||||
|
|
||||||
|
def shows(desktop, colour, timeout=20):
|
||||||
|
deadline = time.monotonic() + timeout
|
||||||
|
while time.monotonic() < deadline:
|
||||||
|
width, height, pixels = parse_ppm(desktop.capture())
|
||||||
|
if bounding_box(width, height, pixels, colour) is not None:
|
||||||
|
return True
|
||||||
|
time.sleep(0.3)
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
def run(args, desktop, store, home):
|
||||||
|
t = Path(args.target)
|
||||||
|
env = dict(os.environ, WEFT_APP_STORE=str(store), HOME=str(home),
|
||||||
|
XDG_DATA_HOME=str(home / "share"))
|
||||||
|
|
||||||
|
def pack(*arguments, ok=True):
|
||||||
|
done = subprocess.run([t / "weft-pack", *arguments], env=env,
|
||||||
|
capture_output=True, text=True, timeout=60)
|
||||||
|
if ok and done.returncode != 0:
|
||||||
|
raise AssertionError(f"weft-pack {' '.join(arguments)} failed: {done.stderr}")
|
||||||
|
if not ok and done.returncode == 0:
|
||||||
|
raise AssertionError(f"weft-pack {' '.join(arguments)} succeeded: {done.stdout}")
|
||||||
|
return done.stdout + done.stderr
|
||||||
|
|
||||||
|
revisions = store / ".revisions" / APP_ID
|
||||||
|
|
||||||
|
def active():
|
||||||
|
return os.readlink(store / APP_ID)
|
||||||
|
|
||||||
|
src = home / "src"
|
||||||
|
write_revision(src, "one")
|
||||||
|
pack("install", str(src), "--dev")
|
||||||
|
one = store / active()
|
||||||
|
|
||||||
|
desktop.launch_client("appd", [t / "weft-appd"], {
|
||||||
|
"WEFT_RUNTIME_BIN": str(t / "weft-runtime"),
|
||||||
|
"WEFT_APP_SHELL_BIN": str(t / "weft-app-shell"),
|
||||||
|
"WEFT_APP_STORE": str(store),
|
||||||
|
"WEFT_DISABLE_CGROUP": "1",
|
||||||
|
"WEFT_APPD_WS_PORT": str(free_port()),
|
||||||
|
"HOME": str(home),
|
||||||
|
"XDG_DATA_HOME": str(home / "share"),
|
||||||
|
})
|
||||||
|
port, token = read_endpoint(desktop.runtime, 30)
|
||||||
|
appd = AppdClient(port, token)
|
||||||
|
|
||||||
|
def launch():
|
||||||
|
appd.send({"type": "LAUNCH_APP", "app_id": APP_ID, "surface_id": 0})
|
||||||
|
reply = appd.wait_for(lambda m: m.get("type") in ("APP_READY", "ERROR"), STARTUP_TIMEOUT)
|
||||||
|
if reply.get("type") != "APP_READY":
|
||||||
|
raise AssertionError(f"the app did not start: {reply}")
|
||||||
|
return reply["session_id"]
|
||||||
|
|
||||||
|
def stop(session_id):
|
||||||
|
appd.send({"type": "TERMINATE_APP", "session_id": session_id, "force": True})
|
||||||
|
appd.wait_for(lambda m: m.get("type") == "APP_STATE" and m.get("state") == "stopped"
|
||||||
|
and m.get("session_id") == session_id, 20)
|
||||||
|
|
||||||
|
first = launch()
|
||||||
|
if not shows(desktop, COLOURS["one"]):
|
||||||
|
raise AssertionError("revision one is not shown")
|
||||||
|
shells = subprocess.run(["pgrep", "-af", "weft-app-shell"], capture_output=True,
|
||||||
|
text=True).stdout
|
||||||
|
if str(one / "ui/index.html") not in shells:
|
||||||
|
raise AssertionError(f"the app shell does not run from revision one: {shells}")
|
||||||
|
|
||||||
|
# 1. An update leaves the running session on its revision.
|
||||||
|
write_revision(src, "two")
|
||||||
|
pack("install", str(src), "--dev")
|
||||||
|
two = store / active()
|
||||||
|
if two == one:
|
||||||
|
raise AssertionError("the update did not activate a new revision")
|
||||||
|
time.sleep(2)
|
||||||
|
if not shows(desktop, COLOURS["one"], 5) or shows(desktop, COLOURS["two"], 1):
|
||||||
|
raise AssertionError("the update changed what the running session shows")
|
||||||
|
if (one / "ui/index.html").read_text().find("200, 0, 0") < 0:
|
||||||
|
raise AssertionError("the running session's revision changed")
|
||||||
|
|
||||||
|
# 2. A failed update changes nothing.
|
||||||
|
write_revision(src, "bad", wasm=b"not a component")
|
||||||
|
pack("install", str(src), "--dev", ok=False)
|
||||||
|
if store / active() != two:
|
||||||
|
raise AssertionError("a failed update changed the active revision")
|
||||||
|
|
||||||
|
# 3. A new launch gets the update.
|
||||||
|
second = launch()
|
||||||
|
if not shows(desktop, COLOURS["two"]):
|
||||||
|
raise AssertionError("a launch after the update does not show revision two")
|
||||||
|
stop(second)
|
||||||
|
|
||||||
|
# 4. With the first session ended, the next update collects revision one.
|
||||||
|
if not one.is_dir():
|
||||||
|
raise AssertionError("revision one was removed while its session ran")
|
||||||
|
stop(first)
|
||||||
|
write_revision(src, "three")
|
||||||
|
pack("install", str(src), "--dev")
|
||||||
|
if one.exists():
|
||||||
|
raise AssertionError("revision one was kept after its session ended")
|
||||||
|
if not two.is_dir():
|
||||||
|
raise AssertionError("the previous revision was not kept for rollback")
|
||||||
|
pack("rollback", APP_ID)
|
||||||
|
if store / active() != two:
|
||||||
|
raise AssertionError("rollback did not make revision two active")
|
||||||
|
third = launch()
|
||||||
|
if not shows(desktop, COLOURS["two"]):
|
||||||
|
raise AssertionError("a launch after rollback does not show revision two")
|
||||||
|
|
||||||
|
# 5. Uninstall stops new launches, not the running session.
|
||||||
|
pack("uninstall", APP_ID)
|
||||||
|
appd.send({"type": "LAUNCH_APP", "app_id": APP_ID, "surface_id": 0})
|
||||||
|
refused = appd.wait_for(lambda m: m.get("type") in ("APP_READY", "ERROR"), 30)
|
||||||
|
if refused.get("code") != 404:
|
||||||
|
raise AssertionError(f"a launch after uninstall was not refused: {refused}")
|
||||||
|
if not two.is_dir() or not shows(desktop, COLOURS["two"], 5):
|
||||||
|
raise AssertionError("uninstall disturbed the running session")
|
||||||
|
stop(third)
|
||||||
|
pack("uninstall", APP_ID, ok=False)
|
||||||
|
if revisions.exists():
|
||||||
|
raise AssertionError(f"revisions left after uninstall: {list(revisions.iterdir())}")
|
||||||
|
|
||||||
|
# 6. A declared capability needs approval before the app launches.
|
||||||
|
write_revision(src, "one", capabilities='["sys:notifications"]')
|
||||||
|
pack("install", str(src), "--dev")
|
||||||
|
appd.send({"type": "LAUNCH_APP", "app_id": APP_ID, "surface_id": 0})
|
||||||
|
refused = appd.wait_for(lambda m: m.get("type") in ("APP_READY", "ERROR"), 30)
|
||||||
|
if refused.get("code") != 403 or "needs approval" not in refused.get("message", ""):
|
||||||
|
raise AssertionError(f"an unapproved capability launched: {refused}")
|
||||||
|
pack("approve", APP_ID)
|
||||||
|
stop(launch())
|
||||||
|
|
||||||
|
|
||||||
|
def main(argv=None):
|
||||||
|
parser = argparse.ArgumentParser(description=__doc__,
|
||||||
|
formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||||
|
parser.add_argument("--compositor", type=Path, default=ROOT / "target/debug/weft-compositor")
|
||||||
|
parser.add_argument("--target", type=Path, default=ROOT / "target/debug",
|
||||||
|
help="directory with weft-appd, weft-pack, weft-runtime and weft-app-shell")
|
||||||
|
parser.add_argument("--output", type=Path, default=ROOT / "target/update-check")
|
||||||
|
args = parser.parse_args(argv)
|
||||||
|
|
||||||
|
missing = missing_tools() + [str(p) for p in (args.compositor, args.target / "weft-appd",
|
||||||
|
args.target / "weft-pack",
|
||||||
|
args.target / "weft-runtime",
|
||||||
|
args.target / "weft-app-shell")
|
||||||
|
if not p.is_file()]
|
||||||
|
if missing:
|
||||||
|
print("missing: " + ", ".join(missing), file=sys.stderr)
|
||||||
|
return 2
|
||||||
|
store = Path(tempfile.mkdtemp(prefix="weft-store-"))
|
||||||
|
home = Path(tempfile.mkdtemp(prefix="weft-home-"))
|
||||||
|
try:
|
||||||
|
with Desktop(args.compositor, args.output, outputs=["appd.log", "update.ppm"]) as desktop:
|
||||||
|
try:
|
||||||
|
run(args, desktop, store, home)
|
||||||
|
except AssertionError:
|
||||||
|
(args.output / "update.ppm").write_bytes(desktop.capture())
|
||||||
|
raise
|
||||||
|
except (AssertionError, SessionError, TimeoutError) as failure:
|
||||||
|
print(f"update check failed: {failure}", file=sys.stderr)
|
||||||
|
print(f"logs and capture in {args.output}", file=sys.stderr)
|
||||||
|
return 1
|
||||||
|
finally:
|
||||||
|
shutil.rmtree(store, ignore_errors=True)
|
||||||
|
shutil.rmtree(home, ignore_errors=True)
|
||||||
|
print("update check passed")
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
sys.exit(main())
|
||||||
Loading…
Reference in a new issue