feat: grant an app only the capabilities the user approved

Every capability a package declared was granted at launch, so a signed
package received all the permissions it asked for. Blueprint 5.2 rules
that out.

A package now gets only the capabilities the user approved. weft-pack
install --approve approves those the installed package declares, and
weft-pack approve <id> approves those of the installed app later.
Without approval, install lists what still needs it. The approval is
recorded in $XDG_DATA_HOME/weft/approvals/<id>. weft-appd refuses to
launch an app declaring a capability the record does not hold, with
403 and the capabilities named, after refusing unknown or unsupported
ones as before.

An update that declares a new capability needs approval again, and
uninstalling forgets the approval. Private app data is a minimal
execution resource and needs no approval, so Notes and the existing
fixtures are unchanged.

Unit tests cover the approval record, install and approve, an update
adding a capability, uninstall, and appd refusing and then launching.
tests/frame/check_update.py launches a real app declaring notifications:
it is refused until weft-pack approve, then runs.
This commit is contained in:
Marco Allegretti 2026-10-09 19:10:15 +00:00
parent d76d4c726d
commit 3186e524ab
No known key found for this signature in database
7 changed files with 413 additions and 13 deletions

View file

@ -578,6 +578,29 @@ pub(crate) async fn dispatch(req: Request, registry: &Registry) -> Response {
} }
} }
/// Refuses a launch while the app declares a capability the user has not
/// approved; a signature, however trusted, approves nothing.
fn check_approval(app_id: &str, declared: &[String]) -> Result<(), grants::Refusal> {
use weft_ipc_types::approval::{approval_path, read_approved, unapproved};
let data_home = weft_ipc_types::package::data_home().ok_or_else(|| {
grants::Refusal::new(500, "cannot locate the data home holding app approvals")
})?;
let record = approval_path(&data_home, app_id);
let approved = read_approved(&record)
.map_err(|e| grants::Refusal::new(500, format!("cannot read {}: {e}", record.display())))?;
let pending = unapproved(declared, &approved);
if pending.is_empty() {
return Ok(());
}
Err(grants::Refusal::new(
403,
format!(
"{app_id} needs approval for {}; approve it with weft-pack approve {app_id}",
pending.join(", ")
),
))
}
/// Resolves the package of `app_id` and derives its grants. Resolution may /// 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.
@ -586,6 +609,7 @@ 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)?;
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,
@ -829,6 +853,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;

View 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();
}
}

View file

@ -1,3 +1,4 @@
pub mod approval;
pub mod capability; pub mod capability;
pub mod manifest; pub mod manifest;
pub mod package; pub mod package;

View file

@ -20,23 +20,29 @@ fn main() -> anyhow::Result<()> {
print_info(&manifest); print_info(&manifest);
} }
Some("install") => { Some("install") => {
let usage = "usage: weft-pack install <dir|archive> [--dev] [--claim-data]"; let usage = "usage: weft-pack install <dir|archive> [--dev] [--claim-data] [--approve]";
let dir = args.get(2).context(usage)?; let dir = args.get(2).context(usage)?;
let mut mode = InstallMode::Verified; let mut mode = InstallMode::Verified;
let mut claim_data = false; let mut claim_data = false;
let mut approve = false;
for arg in &args[3..] { for arg in &args[3..] {
match arg.as_str() { match arg.as_str() {
"--dev" => mode = InstallMode::Development, "--dev" => mode = InstallMode::Development,
"--claim-data" => claim_data = true, "--claim-data" => claim_data = true,
"--approve" => approve = true,
other => anyhow::bail!("unexpected argument '{other}'; {usage}"), other => anyhow::bail!("unexpected argument '{other}'; {usage}"),
} }
} }
install_package(Path::new(dir), mode, claim_data)?; install_package(Path::new(dir), mode, claim_data, approve)?;
} }
Some("uninstall") => { Some("uninstall") => {
let app_id = args.get(2).context("usage: weft-pack uninstall <app_id>")?; let app_id = args.get(2).context("usage: weft-pack uninstall <app_id>")?;
uninstall_package(app_id)?; uninstall_package(app_id)?;
} }
Some("approve") => {
let app_id = args.get(2).context("usage: weft-pack approve <app_id>")?;
approve_package(&resolve_install_root()?, app_id)?;
}
Some("rollback") => { Some("rollback") => {
let app_id = args.get(2).context("usage: weft-pack rollback <app_id>")?; let app_id = args.get(2).context("usage: weft-pack rollback <app_id>")?;
rollback_package(&resolve_install_root()?, app_id)?; rollback_package(&resolve_install_root()?, app_id)?;
@ -123,8 +129,14 @@ fn main() -> anyhow::Result<()> {
eprintln!( eprintln!(
" --claim-data: adopt app data with no owner" " --claim-data: adopt app data with no owner"
); );
eprintln!(
" --approve: approve its declared capabilities"
);
eprintln!(" weft-pack uninstall <app_id> remove installed package"); eprintln!(" weft-pack uninstall <app_id> remove installed package");
eprintln!(" weft-pack rollback <app_id> activate the previous revision"); eprintln!(" weft-pack rollback <app_id> activate the previous revision");
eprintln!(
" weft-pack approve <app_id> approve the app's declared capabilities"
);
eprintln!(" weft-pack list list installed packages"); eprintln!(" weft-pack list list installed packages");
eprintln!( eprintln!(
" weft-pack build-image <dir> [--out <img>] create EROFS image with mkfs.erofs" " weft-pack build-image <dir> [--out <img>] create EROFS image with mkfs.erofs"
@ -270,14 +282,19 @@ enum InstallMode {
Development, Development,
} }
fn install_package(path: &Path, mode: InstallMode, claim_data: bool) -> anyhow::Result<()> { fn install_package(
path: &Path,
mode: InstallMode,
claim_data: bool,
approve: bool,
) -> anyhow::Result<()> {
let root = resolve_install_root()?; let root = resolve_install_root()?;
install_into(path, &root, mode, claim_data) install_into(path, &root, mode, claim_data, approve)
} }
#[cfg(test)] #[cfg(test)]
fn install_package_to(path: &Path, store_root: &Path, mode: InstallMode) -> anyhow::Result<()> { fn install_package_to(path: &Path, store_root: &Path, mode: InstallMode) -> anyhow::Result<()> {
install_into(path, store_root, mode, false) install_into(path, store_root, mode, false, false)
} }
/// Installs the package at `path` into `store_root`. App data that exists /// Installs the package at `path` into `store_root`. App data that exists
@ -289,12 +306,13 @@ fn install_into(
store_root: &Path, store_root: &Path,
mode: InstallMode, mode: InstallMode,
claim_data: bool, claim_data: bool,
approve: bool,
) -> anyhow::Result<()> { ) -> anyhow::Result<()> {
create_store(store_root)?; create_store(store_root)?;
if !(path.extension().is_some_and(|e| e == "zst" || e == "tar") if !(path.extension().is_some_and(|e| e == "zst" || e == "tar")
|| path.to_string_lossy().ends_with(".app.tar.zst")) || path.to_string_lossy().ends_with(".app.tar.zst"))
{ {
return install_dir(path, store_root, mode, claim_data); return install_dir(path, store_root, mode, claim_data, approve);
} }
let name = path let name = path
.file_name() .file_name()
@ -308,7 +326,7 @@ fn install_into(
let _in_use = weft_ipc_types::store::try_claim(&unpacked) let _in_use = weft_ipc_types::store::try_claim(&unpacked)
.with_context(|| format!("open {}", unpacked.display()))?; .with_context(|| format!("open {}", unpacked.display()))?;
let result = unbundle_package(path, &unpacked) let result = unbundle_package(path, &unpacked)
.and_then(|()| install_dir(&unpacked.join(name), store_root, mode, claim_data)); .and_then(|()| install_dir(&unpacked.join(name), store_root, mode, claim_data, approve));
let _ = std::fs::remove_dir_all(&unpacked); let _ = std::fs::remove_dir_all(&unpacked);
result result
} }
@ -379,6 +397,7 @@ fn install_dir(
store_root: &Path, store_root: &Path,
mode: InstallMode, mode: InstallMode,
claim_data: bool, claim_data: bool,
approve: bool,
) -> anyhow::Result<()> { ) -> anyhow::Result<()> {
check_package(dir)?; check_package(dir)?;
// The package is copied into the store first and every decision, the app // The package is copied into the store first and every decision, the app
@ -399,7 +418,7 @@ fn install_dir(
// operation never takes it for abandoned. // operation never takes it for abandoned.
let in_use = weft_ipc_types::store::try_claim(&staging) let in_use = weft_ipc_types::store::try_claim(&staging)
.with_context(|| format!("open {}", staging.display()))?; .with_context(|| format!("open {}", staging.display()))?;
install_staged(&staging, store_root, mode, claim_data, in_use) install_staged(&staging, store_root, mode, claim_data, approve, in_use)
}); });
if result.is_err() { if result.is_err() {
let _ = std::fs::remove_dir_all(&staging); let _ = std::fs::remove_dir_all(&staging);
@ -415,6 +434,7 @@ fn install_staged(
store_root: &Path, store_root: &Path,
mode: InstallMode, mode: InstallMode,
claim_data: bool, claim_data: bool,
approve: bool,
in_use: Option<std::fs::File>, in_use: Option<std::fs::File>,
) -> anyhow::Result<()> { ) -> anyhow::Result<()> {
check_package(staging)?; check_package(staging)?;
@ -457,6 +477,75 @@ fn install_staged(
dest.display(), dest.display(),
&revision[..12] &revision[..12]
); );
settle_approval(&data_home, app_id, manifest.capabilities(), approve)
}
/// Records the installed package's capabilities as approved with
/// `approve`; otherwise reports those that still need approval, since the
/// app does not launch until they are approved.
fn settle_approval(
data_home: &Path,
app_id: &str,
declared: &[String],
approve: bool,
) -> anyhow::Result<()> {
use weft_ipc_types::approval::{approval_path, read_approved, unapproved, write_approved};
let record = approval_path(data_home, app_id);
if approve {
write_approved(&record, declared)
.with_context(|| format!("record the approval of {app_id}"))?;
let approved: Vec<_> = declared
.iter()
.filter(|c| weft_ipc_types::approval::needs_approval(c))
.collect();
if !approved.is_empty() {
println!(
"approved for {app_id}: {}",
approved
.iter()
.map(|c| c.as_str())
.collect::<Vec<_>>()
.join(", ")
);
}
return Ok(());
}
let approved = read_approved(&record).with_context(|| format!("read {}", record.display()))?;
let pending = unapproved(declared, &approved);
if !pending.is_empty() {
println!(
"{app_id} needs approval for {} before it launches; run weft-pack approve {app_id}",
pending.join(", ")
);
}
Ok(())
}
/// Approves the capabilities the active package of `app_id` declares.
fn approve_package(store_root: &Path, app_id: &str) -> anyhow::Result<()> {
anyhow::ensure!(
weft_ipc_types::package::is_valid_app_id(app_id),
"'{app_id}' is not a valid app ID"
);
let data_home = weft_ipc_types::package::data_home()
.context("cannot locate the data home to record the approval")?;
let _lock = weft_ipc_types::trust::lock_owner(&data_home, app_id)?;
let found = active(store_root, app_id)?
.with_context(|| format!("{app_id} is not installed in {}", store_root.display()))?;
let manifest = load_manifest(found.dir())?;
anyhow::ensure!(
manifest.package.id == app_id,
"{} declares another app ID",
found.dir().display()
);
settle_approval(&data_home, app_id, manifest.capabilities(), true)?;
if !manifest
.capabilities()
.iter()
.any(|c| weft_ipc_types::approval::needs_approval(c))
{
println!("{app_id} declares nothing that needs approval");
}
Ok(()) Ok(())
} }
@ -979,6 +1068,11 @@ fn uninstall_package_from(app_id: &str, store_root: &Path) -> anyhow::Result<()>
&& !installed_in_another_store(app_id, store_root) && !installed_in_another_store(app_id, store_root)
{ {
release_owner_without_data(home, app_id); release_owner_without_data(home, app_id);
// A later installation asks for approval again.
weft_ipc_types::approval::remove_approval(&weft_ipc_types::approval::approval_path(
home, app_id,
))
.with_context(|| format!("remove the approval of {app_id}"))?;
} }
println!("uninstalled {}", app_id); println!("uninstalled {}", app_id);
Ok(()) Ok(())
@ -1931,6 +2025,55 @@ mod tests {
let _ = std::fs::remove_dir_all(&home); let _ = std::fs::remove_dir_all(&home);
} }
#[test]
fn capabilities_are_approved_only_when_asked_and_again_for_new_ones() {
use weft_ipc_types::approval::{approval_path, read_approved, unapproved};
let home = temp_root("approval");
let store = home.join("store");
let app_id = "org.weft.test.approval";
let src = home.join("src");
let record = approval_path(&home.join("share"), app_id);
let pending = |declared: &[&str]| {
let declared: Vec<String> = declared.iter().map(|c| (*c).to_owned()).collect();
unapproved(&declared, &read_approved(&record).unwrap())
.into_iter()
.map(str::to_owned)
.collect::<Vec<_>>()
};
write_package(&src, app_id, "\"sys:notifications\", \"fs:rw:app-data\"");
with_home(&home, || {
install_package_to(&src, &store, InstallMode::Development)
})
.unwrap();
assert_eq!(pending(&["sys:notifications"]), ["sys:notifications"]);
with_home(&home, || approve_package(&store, app_id)).unwrap();
assert!(pending(&["sys:notifications", "fs:rw:app-data"]).is_empty());
// An update that asks for more is not approved by the earlier answer.
write_package(
&src,
app_id,
"\"sys:notifications\", \"sys:clipboard:read\"",
);
with_home(&home, || {
install_package_to(&src, &store, InstallMode::Development)
})
.unwrap();
assert_eq!(
pending(&["sys:notifications", "sys:clipboard:read"]),
["sys:clipboard:read"]
);
// --approve approves what the installed package declares.
with_home(&home, || {
install_into(&src, &store, InstallMode::Development, false, true)
})
.unwrap();
assert!(pending(&["sys:notifications", "sys:clipboard:read"]).is_empty());
// Uninstalling forgets the approval.
with_home(&home, || uninstall_package_from(app_id, &store)).unwrap();
assert!(!record.exists());
let _ = std::fs::remove_dir_all(&home);
}
#[test] #[test]
fn leftovers_of_interrupted_operations_are_removed() { fn leftovers_of_interrupted_operations_are_removed() {
let home = temp_root("leftovers"); let home = temp_root("leftovers");
@ -2309,7 +2452,13 @@ mod tests {
assert!(message.contains("--claim-data"), "{message}"); assert!(message.contains("--claim-data"), "{message}");
assert_eq!(owner_of(&home, app_id), None); assert_eq!(owner_of(&home, app_id), None);
with_home(&home, || { with_home(&home, || {
install_into(&home.join("src"), &other, InstallMode::Development, true) install_into(
&home.join("src"),
&other,
InstallMode::Development,
true,
false,
)
}) })
.unwrap(); .unwrap();
assert_eq!(owner_of(&home, app_id), Some(Owner::Development)); assert_eq!(owner_of(&home, app_id), Some(Owner::Development));
@ -2550,7 +2699,13 @@ mod tests {
assert!(message.contains("--claim-data"), "{message}"); assert!(message.contains("--claim-data"), "{message}");
assert!(!store.join(app_id).join("wapp.toml").exists()); assert!(!store.join(app_id).join("wapp.toml").exists());
with_home(&home, || { with_home(&home, || {
install_into(&home.join("src"), &store, InstallMode::Development, true) install_into(
&home.join("src"),
&store,
InstallMode::Development,
true,
false,
)
}) })
.unwrap(); .unwrap();
assert!(store.join(app_id).join("wapp.toml").exists()); assert!(store.join(app_id).join("wapp.toml").exists());

View file

@ -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, entries and package content), `sign` (Ed25519 signature over every file), `verify` (verify signature), `generate-key`, `install` (requires a signature by a trusted key unless `--dev`; records the app ID's owner; installs or updates, see [Installing and updating](#installing-and-updating)), `uninstall`, `rollback`, `list`, `build-image` (EROFS dm-verity), `info`. Package management CLI. Subcommands: `check` (validate wapp.toml, entries and package content), `sign` (Ed25519 signature over every file), `verify` (verify signature), `generate-key`, `install` (requires a signature by a trusted key unless `--dev`; records the app ID's owner; installs or updates, see [Installing and updating](#installing-and-updating)), `uninstall`, `rollback`, `approve` (approve the installed app's declared capabilities; `install --approve` does so at installation), `list`, `build-image` (EROFS dm-verity), `info`.
### weft-file-portal ### weft-file-portal

View file

@ -8,7 +8,7 @@ WEFT OS enforces a capability-based security model. No capability is granted by
`weft-pack check` validates capability strings against the shared vocabulary in `weft_ipc_types::capability`. Unknown capability strings are rejected. At launch, `weft-appd` derives the session's grants from the manifest and refuses to start a package with a capability that is unknown, unsupported or unsatisfiable. `weft-runtime` enforces the grants it is given: read-only directories are preopened read-only, and each host import checks its grant on every call. See the capability table in `architecture.md`. `weft-pack check` validates capability strings against the shared vocabulary in `weft_ipc_types::capability`. Unknown capability strings are rejected. At launch, `weft-appd` derives the session's grants from the manifest and refuses to start a package with a capability that is unknown, unsupported or unsatisfiable. `weft-runtime` enforces the grants it is given: read-only directories are preopened read-only, and each host import checks its grant on every call. See the capability table in `architecture.md`.
Installing a package does not yet ask the user to approve its capabilities; every declared, supported capability is granted at launch. A package gets only the capabilities the user approved. `weft-pack install --approve` approves those the installed package declares, and `weft-pack approve <id>` approves those of the installed app later; without approval, `install` lists what still needs it. The approval is recorded in `$XDG_DATA_HOME/weft/approvals/<id>`, and weft-appd refuses to launch an app that declares a capability it does not hold (403, naming the capabilities). An update that declares a new capability needs approval again; an earlier approval never extends to it. Uninstalling the app forgets the approval. Private app data (`fs:read:app-data`, `fs:rw:app-data`) is a minimal execution resource and needs no approval. Signature verification and approval are separate decisions: a trusted signature approves nothing.
## Process Isolation ## Process Isolation

View file

@ -17,6 +17,8 @@ colour. In the presented pixels and the store:
two active again. two active again.
5. Uninstalling while a session runs stops new launches (404) but not the 5. Uninstalling while a session runs stops new launches (404) but not the
session; the next uninstall, after it has ended, removes the revisions. 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 The application is unsigned development content using the Counter demo's
component. component.
@ -41,11 +43,12 @@ VERSIONS = {"one": 1, "two": 2, "bad": 3, "three": 4}
STARTUP_TIMEOUT = 120.0 STARTUP_TIMEOUT = 120.0
def write_revision(src, name, wasm=None): def write_revision(src, name, wasm=None, capabilities="[]"):
shutil.rmtree(src, ignore_errors=True) shutil.rmtree(src, ignore_errors=True)
(src / "ui").mkdir(parents=True) (src / "ui").mkdir(parents=True)
(src / "wapp.toml").write_text( (src / "wapp.toml").write_text(
f'[package]\nid = "{APP_ID}"\nname = "Update"\nversion = "0.0.{VERSIONS[name]}"\n' 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') '[runtime]\nmodule = "app.wasm"\n[ui]\nentry = "ui/index.html"\n')
if wasm is None: if wasm is None:
shutil.copy(ROOT / "examples/org.weft.demo.counter/app.wasm", src / "app.wasm") shutil.copy(ROOT / "examples/org.weft.demo.counter/app.wasm", src / "app.wasm")
@ -177,6 +180,16 @@ def run(args, desktop, store, home):
if revisions.exists(): if revisions.exists():
raise AssertionError(f"revisions left after uninstall: {list(revisions.iterdir())}") 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): def main(argv=None):
parser = argparse.ArgumentParser(description=__doc__, parser = argparse.ArgumentParser(description=__doc__,