fix(runtime): enforce effective capability grants per session

Every host import was registered and callable whatever the package
declared, read-only directory capabilities were preopened read-write,
and appd launched packages whose capabilities it could not satisfy. The
fetch import also could not be linked: the host returned a tuple where
the WIT declares the response record, so any component importing
weft:app/fetch failed to instantiate.

One capability vocabulary now lives in weft_ipc_types::capability and
is used by weft-pack, weft-appd and weft-runtime. weft-appd derives a
session's grants once, before the session exists, and refuses the launch
with error 403 when a capability is unknown, unsupported (hw:gpu:*) or
unsatisfiable (documents without an XDG documents directory). The
documents directory now comes from user-dirs.dirs instead of a guessed
~/Documents.

The runtime receives grants explicitly (--grant CAP, --preopen
HOST::GUEST::ro|rw), preopens read-only directories read-only, and checks
the grant on every notifications, clipboard and fetch call. Fetch accepts
only http and https to granted hosts, returns redirects and HTTP error
statuses as responses instead of following or failing them, and bounds
connect time, total time and response size. The file portal takes
read-only directories with --allow-read and refuses writes there.

tests/runtime/check_grants.py runs the real runtime on a probe component
under each kind of grant and checks the outcome of every operation; it
fails when read-only data is writable or an import ignores its grant.
The appd dispatch tests that read WEFT_RUNTIME_BIN now hold the env lock
shared with the tests that set it.
This commit is contained in:
Marco Allegretti 2026-10-09 08:08:58 +00:00
parent f41937bd7e
commit c28a829624
No known key found for this signature in database
22 changed files with 1552 additions and 190 deletions

1
.gitignore vendored
View file

@ -6,3 +6,4 @@
/infra/vm/*.qcow2 /infra/vm/*.qcow2
Thumbs.db Thumbs.db
/tests/components/*/target/

3
Cargo.lock generated
View file

@ -10544,6 +10544,7 @@ dependencies = [
"sha2", "sha2",
"tar", "tar",
"toml 0.8.23", "toml 0.8.23",
"weft-ipc-types",
"zstd", "zstd",
] ]
@ -10558,8 +10559,10 @@ dependencies = [
"tracing", "tracing",
"tracing-subscriber", "tracing-subscriber",
"ureq", "ureq",
"url",
"wasmtime", "wasmtime",
"wasmtime-wasi", "wasmtime-wasi",
"weft-ipc-types",
] ]
[[package]] [[package]]

View file

@ -14,6 +14,7 @@ members = [
exclude = [ exclude = [
"examples/org.weft.demo.counter", "examples/org.weft.demo.counter",
"examples/org.weft.demo.notes", "examples/org.weft.demo.notes",
"tests/components/grants-probe",
] ]
resolver = "2" resolver = "2"

View file

@ -0,0 +1,277 @@
//! Effective grants for a session, derived once from the package manifest.
//!
//! Every capability the package declares must be understood and satisfiable
//! by this host, or the session does not start. The result is passed to
//! weft-runtime explicitly (`--preopen`, `--grant`) and to the file portal;
//! neither reads the manifest itself.
use std::path::{Path, PathBuf};
use weft_ipc_types::capability::{Access, Capability};
/// A host directory made visible to the component.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct GrantedDir {
pub host: PathBuf,
pub guest: &'static str,
pub access: Access,
}
impl GrantedDir {
/// The `--preopen` argument for weft-runtime.
pub fn preopen_arg(&self) -> String {
let mode = match self.access {
Access::Read => "ro",
Access::ReadWrite => "rw",
};
format!("{}::{}::{mode}", self.host.display(), self.guest)
}
}
#[derive(Debug, Default, PartialEq, Eq)]
pub(crate) struct SessionGrants {
pub dirs: Vec<GrantedDir>,
/// Host-import capabilities, passed as `--grant`.
pub imports: Vec<Capability>,
}
/// Where the host resources behind filesystem capabilities live.
pub(crate) struct HostDirs {
/// Root under which each app's private data directory is created.
pub app_data_root: PathBuf,
/// The user's documents directory, if the platform configures one.
pub documents: Option<PathBuf>,
}
impl HostDirs {
pub fn from_env() -> Result<Self, String> {
let home = std::env::var_os("HOME")
.map(PathBuf::from)
.ok_or("HOME is not set")?;
let config = std::env::var_os("XDG_CONFIG_HOME")
.map(PathBuf::from)
.unwrap_or_else(|| home.join(".config"));
Ok(Self {
app_data_root: home.join(".local/share/weft/apps"),
documents: documents_dir(&home, &config),
})
}
}
/// Reads the package manifest of `app_id` and derives its grants.
pub(crate) fn for_app(app_id: &str) -> Result<SessionGrants, String> {
#[derive(serde::Deserialize)]
struct Package {
capabilities: Option<Vec<String>>,
}
#[derive(serde::Deserialize)]
struct Manifest {
package: Package,
}
let manifest = crate::app_store_roots()
.into_iter()
.map(|root| root.join(app_id).join("wapp.toml"))
.find(|path| path.exists())
.ok_or_else(|| format!("package {app_id} is not installed"))?;
let text = std::fs::read_to_string(&manifest)
.map_err(|e| format!("cannot read {}: {e}", manifest.display()))?;
let manifest: Manifest =
toml::from_str(&text).map_err(|e| format!("invalid {}: {e}", manifest.display()))?;
let declared = manifest.package.capabilities.unwrap_or_default();
derive(app_id, &declared, &HostDirs::from_env()?)
}
/// Derives grants for the declared capabilities. Creates the app's private
/// data directory when a data capability is declared.
pub(crate) fn derive(
app_id: &str,
declared: &[String],
host: &HostDirs,
) -> Result<SessionGrants, String> {
let mut grants = SessionGrants::default();
for text in declared {
let capability: Capability = text.parse().map_err(|e| format!("{e}"))?;
match capability {
Capability::AppData(access) => {
let dir = host.app_data_root.join(app_id).join("data");
std::fs::create_dir_all(&dir)
.map_err(|e| format!("cannot create {}: {e}", dir.display()))?;
grant_dir(&mut grants, dir, "/data", access);
}
Capability::Documents(access) => {
let dir = host.documents.clone().ok_or_else(|| {
format!("{capability} requested, but no documents directory is configured")
})?;
grant_dir(&mut grants, dir, "/xdg/documents", access);
}
Capability::Fetch(_)
| Capability::Notifications
| Capability::ClipboardRead
| Capability::ClipboardWrite => {
if !grants.imports.contains(&capability) {
grants.imports.push(capability);
}
}
Capability::GpuCompute | Capability::GpuRender => {
return Err(format!("{capability} is not supported by this host"));
}
}
}
Ok(grants)
}
/// Adds a directory grant; declaring both modes for one directory grants the
/// wider one.
fn grant_dir(grants: &mut SessionGrants, host: PathBuf, guest: &'static str, access: Access) {
match grants.dirs.iter_mut().find(|dir| dir.guest == guest) {
Some(existing) => {
if access == Access::ReadWrite {
existing.access = Access::ReadWrite;
}
}
None => grants.dirs.push(GrantedDir {
host,
guest,
access,
}),
}
}
/// The documents directory from the XDG user directories configuration
/// (`user-dirs.dirs`), or None when it is not configured, is disabled (set
/// to the home directory) or does not exist.
fn documents_dir(home: &Path, config: &Path) -> Option<PathBuf> {
let text = std::fs::read_to_string(config.join("user-dirs.dirs")).ok()?;
let value = text.lines().find_map(|line| {
line.trim()
.strip_prefix("XDG_DOCUMENTS_DIR=")
.map(|v| v.trim().trim_matches('"').to_owned())
})?;
let dir = match value.strip_prefix("$HOME") {
Some(rest) => home.join(rest.trim_start_matches('/')),
None => PathBuf::from(&value),
};
(dir.is_absolute() && dir != home && dir.is_dir()).then_some(dir)
}
#[cfg(test)]
mod tests {
use super::*;
fn temp(name: &str) -> PathBuf {
let dir = std::env::temp_dir().join(format!("weft_grants_{name}_{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
dir
}
fn host(root: &Path, documents: Option<PathBuf>) -> HostDirs {
HostDirs {
app_data_root: root.join("apps"),
documents,
}
}
fn caps(list: &[&str]) -> Vec<String> {
list.iter().map(|s| s.to_string()).collect()
}
#[test]
fn no_capabilities_grant_nothing() {
let root = temp("none");
let grants = derive("org.example.app", &[], &host(&root, None)).unwrap();
assert_eq!(grants, SessionGrants::default());
}
#[test]
fn data_access_modes_stay_distinct() {
let root = temp("modes");
let read = derive(
"org.example.app",
&caps(&["fs:read:app-data"]),
&host(&root, None),
)
.unwrap();
assert_eq!(read.dirs[0].access, Access::Read);
assert!(read.dirs[0].preopen_arg().ends_with("::/data::ro"));
assert!(root.join("apps/org.example.app/data").is_dir());
let both = derive(
"org.example.app",
&caps(&["fs:read:app-data", "fs:rw:app-data"]),
&host(&root, None),
)
.unwrap();
assert_eq!(both.dirs.len(), 1);
assert_eq!(both.dirs[0].access, Access::ReadWrite);
}
#[test]
fn imports_are_listed_once() {
let root = temp("imports");
let grants = derive(
"org.example.app",
&caps(&[
"sys:notifications",
"net:fetch:api.example.org",
"sys:notifications",
]),
&host(&root, None),
)
.unwrap();
let listed: Vec<String> = grants.imports.iter().map(|c| c.to_string()).collect();
assert_eq!(listed, ["sys:notifications", "net:fetch:api.example.org"]);
assert!(grants.dirs.is_empty());
}
#[test]
fn unknown_unsupported_and_unsatisfiable_capabilities_fail() {
let root = temp("fail");
for declared in ["sys:everything", "hw:gpu:compute", "fs:read:xdg-documents"] {
assert!(
derive("org.example.app", &caps(&[declared]), &host(&root, None)).is_err(),
"{declared} accepted"
);
}
}
#[test]
fn documents_come_from_user_dirs() {
let home = temp("home");
let config = home.join(".config");
std::fs::create_dir_all(home.join("Docs")).unwrap();
std::fs::create_dir_all(&config).unwrap();
assert_eq!(documents_dir(&home, &config), None);
std::fs::write(
config.join("user-dirs.dirs"),
"# comment\nXDG_DOCUMENTS_DIR=\"$HOME/Docs\"\n",
)
.unwrap();
assert_eq!(documents_dir(&home, &config), Some(home.join("Docs")));
// Disabled (the home directory itself) and missing directories.
std::fs::write(
config.join("user-dirs.dirs"),
"XDG_DOCUMENTS_DIR=\"$HOME/\"\n",
)
.unwrap();
assert_eq!(documents_dir(&home, &config), None);
std::fs::write(
config.join("user-dirs.dirs"),
"XDG_DOCUMENTS_DIR=\"$HOME/Missing\"\n",
)
.unwrap();
assert_eq!(documents_dir(&home, &config), None);
let grants = derive(
"org.example.app",
&caps(&["fs:rw:xdg-documents"]),
&host(&home, Some(home.join("Docs"))),
)
.unwrap();
assert_eq!(grants.dirs[0].guest, "/xdg/documents");
assert_eq!(grants.dirs[0].access, Access::ReadWrite);
}
}

View file

@ -17,6 +17,7 @@ mod compositor_client {
pub type CompositorSender = mpsc::Sender<AppdToCompositor>; pub type CompositorSender = mpsc::Sender<AppdToCompositor>;
} }
mod grants;
mod ipc; mod ipc;
mod mount; mod mount;
mod runtime; mod runtime;
@ -424,6 +425,22 @@ pub(crate) async fn dispatch(req: Request, registry: &Registry) -> Response {
app_id, app_id,
surface_id: _, surface_id: _,
} => { } => {
// The package's capabilities are granted before a session exists;
// a package this host cannot satisfy is refused, not started.
let grants = if std::env::var("WEFT_RUNTIME_BIN").is_ok() {
match grants::for_app(&app_id) {
Ok(grants) => grants,
Err(message) => {
tracing::warn!(%app_id, error = %message, "launch refused");
return Response::Error {
code: 403,
message: format!("{app_id}: {message}"),
};
}
}
} else {
grants::SessionGrants::default()
};
let session_id = registry.lock().await.launch(&app_id); let session_id = registry.lock().await.launch(&app_id);
tracing::info!(session_id, %app_id, "launched"); tracing::info!(session_id, %app_id, "launched");
let abort_rx = registry.lock().await.register_abort(session_id); let abort_rx = registry.lock().await.register_abort(session_id);
@ -456,8 +473,15 @@ pub(crate) async fn dispatch(req: Request, registry: &Registry) -> Response {
let reg = Arc::clone(registry); let reg = Arc::clone(registry);
let aid = app_id.clone(); let aid = app_id.clone();
tokio::spawn(async move { tokio::spawn(async move {
if let Err(e) = if let Err(e) = runtime::supervise(
runtime::supervise(session_id, &aid, reg, abort_rx, compositor_tx, ipc_socket) session_id,
&aid,
grants,
reg,
abort_rx,
compositor_tx,
ipc_socket,
)
.await .await
{ {
tracing::warn!(session_id, error = %e, "runtime supervisor error"); tracing::warn!(session_id, error = %e, "runtime supervisor error");
@ -677,8 +701,62 @@ mod tests {
assert!(result.is_err()); assert!(result.is_err());
} }
#[tokio::test]
async fn launch_is_refused_when_capabilities_cannot_be_granted() {
let _env = env_lock().lock().await;
let store = std::env::temp_dir().join(format!("weft_refuse_{}", std::process::id()));
let app_dir = store.join("org.example.gpu");
std::fs::create_dir_all(&app_dir).unwrap();
std::fs::write(
app_dir.join("wapp.toml"),
"[package]\nid = \"org.example.gpu\"\ncapabilities = [\"hw:gpu:compute\"]\n",
)
.unwrap();
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.
unsafe {
std::env::set_var("WEFT_APP_STORE", &store);
std::env::set_var("WEFT_RUNTIME_BIN", "/nonexistent/weft-runtime");
}
let reg = make_registry();
let resp = dispatch(
Request::LaunchApp {
app_id: "org.example.gpu".into(),
surface_id: 0,
},
&reg,
)
.await;
// 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 resp {
Response::Error { code, message } => {
assert_eq!(code, 403);
assert!(message.contains("hw:gpu:compute"), "{message}");
}
other => panic!("expected a refusal, got {other:?}"),
}
assert!(reg.lock().await.running_sessions().is_empty());
assert!(matches!(reg.lock().await.state(1), AppStateKind::NotFound));
}
#[tokio::test] #[tokio::test]
async fn dispatch_launch_returns_ack() { async fn dispatch_launch_returns_ack() {
let _env = env_lock().lock().await;
let reg = make_registry(); let reg = make_registry();
let mut rx = reg.lock().await.subscribe(); let mut rx = reg.lock().await.subscribe();
let resp = dispatch( let resp = dispatch(
@ -707,6 +785,7 @@ mod tests {
#[tokio::test] #[tokio::test]
async fn dispatch_terminate_known_returns_stopped() { async fn dispatch_terminate_known_returns_stopped() {
let _env = env_lock().lock().await;
let reg = make_registry(); let reg = make_registry();
let ack = dispatch( let ack = dispatch(
Request::LaunchApp { Request::LaunchApp {
@ -958,6 +1037,7 @@ mod tests {
runtime::supervise( runtime::supervise(
session_id, session_id,
"test.app", "test.app",
grants::SessionGrants::default(),
Arc::clone(&registry), Arc::clone(&registry),
abort_rx, abort_rx,
None, None,
@ -1027,6 +1107,7 @@ mod tests {
runtime::supervise( runtime::supervise(
session_id, session_id,
"test.abort.startup", "test.abort.startup",
grants::SessionGrants::default(),
Arc::clone(&registry), Arc::clone(&registry),
abort_rx, abort_rx,
None, None,
@ -1075,6 +1156,7 @@ mod tests {
runtime::supervise( runtime::supervise(
session_id, session_id,
"test.spawn.fail", "test.spawn.fail",
grants::SessionGrants::default(),
Arc::clone(&registry), Arc::clone(&registry),
abort_rx, abort_rx,
None, None,
@ -1233,6 +1315,7 @@ mod tests {
runtime::supervise( runtime::supervise(
session_id, session_id,
"test.app", "test.app",
grants::SessionGrants::default(),
Arc::clone(&registry), Arc::clone(&registry),
abort_rx, abort_rx,
None, None,

View file

@ -140,71 +140,6 @@ fn systemd_cgroup_available() -> bool {
.exists() .exists()
} }
fn resolve_preopens(app_id: &str) -> Vec<(String, String)> {
#[derive(serde::Deserialize)]
struct Pkg {
capabilities: Option<Vec<String>>,
}
#[derive(serde::Deserialize)]
struct M {
package: Pkg,
}
let pkg_dir = crate::app_store_roots().into_iter().find_map(|root| {
let dir = root.join(app_id);
if dir.join("wapp.toml").exists() {
Some(dir)
} else {
None
}
});
let caps = match pkg_dir {
None => return Vec::new(),
Some(dir) => {
let Ok(text) = std::fs::read_to_string(dir.join("wapp.toml")) else {
return Vec::new();
};
match toml::from_str::<M>(&text) {
Ok(m) => m.package.capabilities.unwrap_or_default(),
Err(_) => return Vec::new(),
}
}
};
let home = match std::env::var("HOME") {
Ok(h) => PathBuf::from(h),
Err(_) => return Vec::new(),
};
let mut preopens = Vec::new();
for cap in &caps {
match cap.as_str() {
"fs:rw:app-data" | "fs:read:app-data" => {
let data_dir = home
.join(".local/share/weft/apps")
.join(app_id)
.join("data");
let _ = std::fs::create_dir_all(&data_dir);
preopens.push((data_dir.to_string_lossy().into_owned(), "/data".to_string()));
}
"fs:rw:xdg-documents" | "fs:read:xdg-documents" => {
let docs = home.join("Documents");
if docs.exists() {
preopens.push((
docs.to_string_lossy().into_owned(),
"/xdg/documents".to_string(),
));
}
}
other => {
tracing::debug!(capability = other, "not mapped to preopen; skipped");
}
}
}
preopens
}
async fn kill_portal(portal: Option<(PathBuf, tokio::process::Child)>) { async fn kill_portal(portal: Option<(PathBuf, tokio::process::Child)>) {
if let Some((sock, mut child)) = portal { if let Some((sock, mut child)) = portal {
let _ = child.kill().await; let _ = child.kill().await;
@ -248,7 +183,7 @@ fn portal_socket_path(session_id: u64) -> Option<PathBuf> {
fn spawn_file_portal( fn spawn_file_portal(
session_id: u64, session_id: u64,
allowed_paths: &[(String, String)], dirs: &[crate::grants::GrantedDir],
) -> Option<(PathBuf, tokio::process::Child)> { ) -> Option<(PathBuf, tokio::process::Child)> {
let bin = std::env::var("WEFT_FILE_PORTAL_BIN").ok()?; let bin = std::env::var("WEFT_FILE_PORTAL_BIN").ok()?;
let socket = portal_socket_path(session_id)?; let socket = portal_socket_path(session_id)?;
@ -257,8 +192,12 @@ fn spawn_file_portal(
.stdin(std::process::Stdio::null()) .stdin(std::process::Stdio::null())
.stdout(std::process::Stdio::null()) .stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null()); .stderr(std::process::Stdio::null());
for (host, _) in allowed_paths { for dir in dirs {
cmd.arg("--allow").arg(host); let flag = match dir.access {
weft_ipc_types::capability::Access::Read => "--allow-read",
weft_ipc_types::capability::Access::ReadWrite => "--allow",
};
cmd.arg(flag).arg(&dir.host);
} }
let child = cmd.kill_on_drop(true).spawn().ok()?; let child = cmd.kill_on_drop(true).spawn().ok()?;
tracing::info!(session_id, socket = %socket.display(), "file portal spawned"); tracing::info!(session_id, socket = %socket.display(), "file portal spawned");
@ -268,6 +207,7 @@ fn spawn_file_portal(
pub(crate) async fn supervise( pub(crate) async fn supervise(
session_id: u64, session_id: u64,
app_id: &str, app_id: &str,
grants: crate::grants::SessionGrants,
registry: Registry, registry: Registry,
abort_rx: tokio::sync::oneshot::Receiver<()>, abort_rx: tokio::sync::oneshot::Receiver<()>,
compositor_tx: Option<CompositorSender>, compositor_tx: Option<CompositorSender>,
@ -297,8 +237,7 @@ pub(crate) async fn supervise(
let (mount_orch, store_override) = let (mount_orch, store_override) =
crate::mount::MountOrchestrator::mount_if_needed(app_id, session_id); crate::mount::MountOrchestrator::mount_if_needed(app_id, session_id);
let preopens = resolve_preopens(app_id); let portal = spawn_file_portal(session_id, &grants.dirs);
let portal = spawn_file_portal(session_id, &preopens);
let mut cmd = if systemd_cgroup_available() { let mut cmd = if systemd_cgroup_available() {
let mut c = tokio::process::Command::new("systemd-run"); let mut c = tokio::process::Command::new("systemd-run");
@ -327,8 +266,11 @@ pub(crate) async fn supervise(
cmd.env("WEFT_FILE_PORTAL_SOCKET", sock); cmd.env("WEFT_FILE_PORTAL_SOCKET", sock);
} }
for (host, guest) in &preopens { for dir in &grants.dirs {
cmd.arg("--preopen").arg(format!("{host}::{guest}")); cmd.arg("--preopen").arg(dir.preopen_arg());
}
for capability in &grants.imports {
cmd.arg("--grant").arg(capability.to_string());
} }
let mut session = OwnedSession { let mut session = OwnedSession {

View file

@ -42,7 +42,9 @@ impl Response {
fn main() -> anyhow::Result<()> { fn main() -> anyhow::Result<()> {
let args: Vec<String> = std::env::args().collect(); let args: Vec<String> = std::env::args().collect();
if args.len() < 2 { if args.len() < 2 {
eprintln!("usage: weft-file-portal <socket_path> [--allow <path>]..."); eprintln!(
"usage: weft-file-portal <socket_path> [--allow <path>]... [--allow-read <path>]..."
);
std::process::exit(1); std::process::exit(1);
} }
@ -75,19 +77,34 @@ fn main() -> anyhow::Result<()> {
anyhow::bail!("weft-file-portal requires a Unix platform") anyhow::bail!("weft-file-portal requires a Unix platform")
} }
/// A directory the session may use: `--allow` grants reading and writing,
/// `--allow-read` reading only.
#[derive(Debug, Clone, PartialEq, Eq)]
struct Allowed {
root: PathBuf,
writable: bool,
}
#[cfg_attr(not(any(unix, test)), allow(dead_code))] #[cfg_attr(not(any(unix, test)), allow(dead_code))]
fn parse_allowed(args: &[String]) -> Vec<PathBuf> { fn parse_allowed(args: &[String]) -> Vec<Allowed> {
let mut allowed = Vec::new(); let mut allowed = Vec::new();
let mut i = 0; let mut i = 0;
while i < args.len() { while i < args.len() {
if args[i] == "--allow" let writable = match args[i].as_str() {
&& let Some(p) = args.get(i + 1) "--allow" => true,
{ "--allow-read" => false,
allowed.push(PathBuf::from(p)); _ => {
i += 2; i += 1;
continue; continue;
} }
i += 1; };
if let Some(p) = args.get(i + 1) {
allowed.push(Allowed {
root: PathBuf::from(p),
writable,
});
}
i += 2;
} }
allowed allowed
} }
@ -108,16 +125,17 @@ fn normalize_path(path: &Path) -> PathBuf {
out out
} }
fn is_allowed(path: &Path, allowed: &[PathBuf]) -> bool { /// Whether `path` lies in an allowed directory, and for a write, in one
if allowed.is_empty() { /// granted read-write.
return false; fn is_allowed(path: &Path, allowed: &[Allowed], write: bool) -> bool {
}
let norm = normalize_path(path); let norm = normalize_path(path);
allowed.iter().any(|a| norm.starts_with(a)) allowed
.iter()
.any(|a| norm.starts_with(&a.root) && (a.writable || !write))
} }
#[cfg(unix)] #[cfg(unix)]
fn handle_connection(stream: UnixStream, allowed: &[PathBuf]) { fn handle_connection(stream: UnixStream, allowed: &[Allowed]) {
let mut writer = match stream.try_clone() { let mut writer = match stream.try_clone() {
Ok(s) => s, Ok(s) => s,
Err(e) => { Err(e) => {
@ -151,11 +169,11 @@ fn handle_connection(stream: UnixStream, allowed: &[PathBuf]) {
} }
#[cfg_attr(not(any(unix, test)), allow(dead_code))] #[cfg_attr(not(any(unix, test)), allow(dead_code))]
fn handle_request(req: Request, allowed: &[PathBuf]) -> Response { fn handle_request(req: Request, allowed: &[Allowed]) -> Response {
match req { match req {
Request::Read { path } => { Request::Read { path } => {
let p = PathBuf::from(&path); let p = PathBuf::from(&path);
if !is_allowed(&p, allowed) { if !is_allowed(&p, allowed, false) {
return Response::err(format!("access denied: {path}")); return Response::err(format!("access denied: {path}"));
} }
match std::fs::read(&p) { match std::fs::read(&p) {
@ -170,7 +188,7 @@ fn handle_request(req: Request, allowed: &[PathBuf]) -> Response {
} }
Request::Write { path, data_b64 } => { Request::Write { path, data_b64 } => {
let p = PathBuf::from(&path); let p = PathBuf::from(&path);
if !is_allowed(&p, allowed) { if !is_allowed(&p, allowed, true) {
return Response::err(format!("access denied: {path}")); return Response::err(format!("access denied: {path}"));
} }
let data = let data =
@ -189,7 +207,7 @@ fn handle_request(req: Request, allowed: &[PathBuf]) -> Response {
} }
Request::List { path } => { Request::List { path } => {
let p = PathBuf::from(&path); let p = PathBuf::from(&path);
if !is_allowed(&p, allowed) { if !is_allowed(&p, allowed, false) {
return Response::err(format!("access denied: {path}")); return Response::err(format!("access denied: {path}"));
} }
match std::fs::read_dir(&p) { match std::fs::read_dir(&p) {
@ -213,33 +231,49 @@ fn handle_request(req: Request, allowed: &[PathBuf]) -> Response {
mod tests { mod tests {
use super::*; use super::*;
fn rw(root: impl Into<PathBuf>) -> Allowed {
Allowed {
root: root.into(),
writable: true,
}
}
fn ro(root: impl Into<PathBuf>) -> Allowed {
Allowed {
root: root.into(),
writable: false,
}
}
#[test] #[test]
fn allowed_path_accepted() { fn allowed_path_accepted() {
let allowed = vec![PathBuf::from("/tmp/weft-test-allowed")]; let allowed = vec![rw("/tmp/weft-test-allowed")];
assert!(is_allowed( assert!(is_allowed(
Path::new("/tmp/weft-test-allowed/file.txt"), Path::new("/tmp/weft-test-allowed/file.txt"),
&allowed &allowed,
false
)); ));
} }
#[test] #[test]
fn disallowed_path_rejected() { fn disallowed_path_rejected() {
let allowed = vec![PathBuf::from("/tmp/weft-test-allowed")]; let allowed = vec![rw("/tmp/weft-test-allowed")];
assert!(!is_allowed(Path::new("/etc/passwd"), &allowed)); assert!(!is_allowed(Path::new("/etc/passwd"), &allowed, false));
} }
#[test] #[test]
fn dotdot_traversal_blocked() { fn dotdot_traversal_blocked() {
let allowed = vec![PathBuf::from("/tmp/weft-test-allowed")]; let allowed = vec![rw("/tmp/weft-test-allowed")];
assert!(!is_allowed( assert!(!is_allowed(
Path::new("/tmp/weft-test-allowed/../etc/passwd"), Path::new("/tmp/weft-test-allowed/../etc/passwd"),
&allowed &allowed,
false
)); ));
} }
#[test] #[test]
fn empty_allowlist_rejects_all() { fn empty_allowlist_rejects_all() {
assert!(!is_allowed(Path::new("/tmp/anything"), &[])); assert!(!is_allowed(Path::new("/tmp/anything"), &[], false));
} }
#[test] #[test]
@ -251,10 +285,9 @@ mod tests {
"/tmp/b".into(), "/tmp/b".into(),
]; ];
let result = parse_allowed(&args); let result = parse_allowed(&args);
assert_eq!( assert_eq!(result, vec![rw("/tmp/a"), rw("/tmp/b")]);
result, let args: Vec<String> = vec!["--allow-read".into(), "/tmp/c".into()];
vec![PathBuf::from("/tmp/a"), PathBuf::from("/tmp/b")] assert_eq!(parse_allowed(&args), vec![ro("/tmp/c")]);
);
} }
#[test] #[test]
@ -263,7 +296,7 @@ mod tests {
Request::Read { Request::Read {
path: "/etc/shadow".into(), path: "/etc/shadow".into(),
}, },
&[PathBuf::from("/tmp/safe")], &[rw("/tmp/safe")],
); );
let json = serde_json::to_string(&resp).unwrap(); let json = serde_json::to_string(&resp).unwrap();
assert!(json.contains("access denied")); assert!(json.contains("access denied"));
@ -277,7 +310,7 @@ mod tests {
let file = dir.join("hello.txt"); let file = dir.join("hello.txt");
fs::write(&file, b"hello world").unwrap(); fs::write(&file, b"hello world").unwrap();
let allowed = vec![dir.clone()]; let allowed = vec![rw(dir.clone())];
let resp = handle_request( let resp = handle_request(
Request::Read { Request::Read {
path: file.to_string_lossy().into(), path: file.to_string_lossy().into(),
@ -307,7 +340,7 @@ mod tests {
fs::write(dir.join("b.txt"), b"").unwrap(); fs::write(dir.join("b.txt"), b"").unwrap();
fs::write(dir.join("a.txt"), b"").unwrap(); fs::write(dir.join("a.txt"), b"").unwrap();
let allowed = vec![dir.clone()]; let allowed = vec![rw(dir.clone())];
let resp = handle_request( let resp = handle_request(
Request::List { Request::List {
path: dir.to_string_lossy().into(), path: dir.to_string_lossy().into(),
@ -333,7 +366,7 @@ mod tests {
&base64::engine::general_purpose::STANDARD, &base64::engine::general_purpose::STANDARD,
b"nested content", b"nested content",
); );
let allowed = vec![dir.clone()]; let allowed = vec![rw(dir.clone())];
let resp = handle_request( let resp = handle_request(
Request::Write { Request::Write {
path: nested.to_string_lossy().into(), path: nested.to_string_lossy().into(),
@ -345,4 +378,36 @@ mod tests {
assert_eq!(fs::read(&nested).unwrap(), b"nested content"); assert_eq!(fs::read(&nested).unwrap(), b"nested content");
let _ = fs::remove_dir_all(&dir); let _ = fs::remove_dir_all(&dir);
} }
#[test]
fn read_only_directories_refuse_writes() {
use std::fs;
let dir = std::env::temp_dir().join(format!("wfp_ro_{}", std::process::id()));
let _ = fs::remove_dir_all(&dir);
fs::create_dir_all(&dir).unwrap();
fs::write(dir.join("kept.txt"), b"original").unwrap();
let allowed = vec![ro(dir.clone())];
let data = base64::Engine::encode(&base64::engine::general_purpose::STANDARD, b"x");
let resp = handle_request(
Request::Write {
path: dir.join("kept.txt").to_string_lossy().into(),
data_b64: data,
},
&allowed,
);
assert!(
serde_json::to_string(&resp)
.unwrap()
.contains("access denied")
);
assert_eq!(fs::read(dir.join("kept.txt")).unwrap(), b"original");
let resp = handle_request(
Request::Read {
path: dir.join("kept.txt").to_string_lossy().into(),
},
&allowed,
);
assert!(matches!(resp, Response::OkData { .. }));
let _ = fs::remove_dir_all(&dir);
}
} }

View file

@ -0,0 +1,161 @@
//! Capabilities an application declares in `wapp.toml`.
//!
//! This is the one vocabulary shared by package validation (weft-pack), the
//! session supervisor that derives effective grants (weft-appd) and the
//! runtime that enforces them (weft-runtime).
use std::fmt;
use std::str::FromStr;
/// Access mode of a filesystem capability.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Access {
Read,
ReadWrite,
}
/// Destinations covered by a fetch capability.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum FetchScope {
/// `net:fetch:*`: any host.
AnyHost,
/// `net:fetch:<host>`: exactly this host, in lowercase.
Host(String),
}
/// One declared capability.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum Capability {
/// `fs:read:app-data` / `fs:rw:app-data`: the app's private data directory.
AppData(Access),
/// `fs:read:xdg-documents` / `fs:rw:xdg-documents`: the user's documents
/// directory.
Documents(Access),
/// `net:fetch:*` / `net:fetch:<host>`: the `weft:app/fetch` import.
Fetch(FetchScope),
/// `sys:notifications`: the `weft:app/notifications` import.
Notifications,
/// `sys:clipboard:read`: `weft:app/clipboard#read`.
ClipboardRead,
/// `sys:clipboard:write`: `weft:app/clipboard#write`.
ClipboardWrite,
/// `hw:gpu:compute`.
GpuCompute,
/// `hw:gpu:render`.
GpuRender,
}
/// A capability string outside the vocabulary.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct UnknownCapability(pub String);
impl fmt::Display for UnknownCapability {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "unknown capability '{}'", self.0)
}
}
impl std::error::Error for UnknownCapability {}
impl FromStr for Capability {
type Err = UnknownCapability;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let capability = match s {
"fs:read:app-data" => Self::AppData(Access::Read),
"fs:rw:app-data" => Self::AppData(Access::ReadWrite),
"fs:read:xdg-documents" => Self::Documents(Access::Read),
"fs:rw:xdg-documents" => Self::Documents(Access::ReadWrite),
"net:fetch:*" => Self::Fetch(FetchScope::AnyHost),
"sys:notifications" => Self::Notifications,
"sys:clipboard:read" => Self::ClipboardRead,
"sys:clipboard:write" => Self::ClipboardWrite,
"hw:gpu:compute" => Self::GpuCompute,
"hw:gpu:render" => Self::GpuRender,
_ => match s.strip_prefix("net:fetch:") {
Some(host) if is_host_name(host) => Self::Fetch(FetchScope::Host(host.to_owned())),
_ => return Err(UnknownCapability(s.to_owned())),
},
};
Ok(capability)
}
}
impl fmt::Display for Capability {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mode = |access: &Access| match access {
Access::Read => "read",
Access::ReadWrite => "rw",
};
match self {
Self::AppData(access) => write!(f, "fs:{}:app-data", mode(access)),
Self::Documents(access) => write!(f, "fs:{}:xdg-documents", mode(access)),
Self::Fetch(FetchScope::AnyHost) => f.write_str("net:fetch:*"),
Self::Fetch(FetchScope::Host(host)) => write!(f, "net:fetch:{host}"),
Self::Notifications => f.write_str("sys:notifications"),
Self::ClipboardRead => f.write_str("sys:clipboard:read"),
Self::ClipboardWrite => f.write_str("sys:clipboard:write"),
Self::GpuCompute => f.write_str("hw:gpu:compute"),
Self::GpuRender => f.write_str("hw:gpu:render"),
}
}
}
/// A DNS host name in canonical lowercase form: dot-separated labels of
/// 1–63 letters, digits and inner hyphens, at most 253 characters.
fn is_host_name(host: &str) -> bool {
host.len() <= 253
&& host.split('.').all(|label| {
!label.is_empty()
&& label.len() <= 63
&& !label.starts_with('-')
&& !label.ends_with('-')
&& label
.bytes()
.all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn every_capability_round_trips() {
for text in [
"fs:read:app-data",
"fs:rw:app-data",
"fs:read:xdg-documents",
"fs:rw:xdg-documents",
"net:fetch:*",
"net:fetch:api.example.org",
"sys:notifications",
"sys:clipboard:read",
"sys:clipboard:write",
"hw:gpu:compute",
"hw:gpu:render",
] {
let capability: Capability = text.parse().unwrap();
assert_eq!(capability.to_string(), text);
}
}
#[test]
fn malformed_capabilities_are_unknown() {
for text in [
"",
"fs:write:app-data",
"net:fetch",
"net:fetch:",
"net:fetch:Example.org",
"net:fetch:example.org:443",
"net:fetch:https://example.org",
"net:fetch:*.example.org",
"net:fetch:-bad.example",
"net:fetch:a..b",
"sys:clipboard",
] {
assert!(text.parse::<Capability>().is_err(), "{text:?} accepted");
}
}
}

View file

@ -1,3 +1,5 @@
pub mod capability;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
pub const MAX_FRAME_LEN: usize = 4 * 1024 * 1024; pub const MAX_FRAME_LEN: usize = 4 * 1024 * 1024;

View file

@ -9,6 +9,7 @@ name = "weft-pack"
path = "src/main.rs" path = "src/main.rs"
[dependencies] [dependencies]
weft-ipc-types = { path = "../weft-ipc-types" }
anyhow = "1.0" anyhow = "1.0"
serde = { version = "1", features = ["derive"] } serde = { version = "1", features = ["derive"] }
toml = "0.8" toml = "0.8"

View file

@ -190,8 +190,8 @@ fn check_package(dir: &Path) -> anyhow::Result<String> {
} }
for cap in m.package.capabilities.iter().flatten() { for cap in m.package.capabilities.iter().flatten() {
if !is_known_capability(cap) { if let Err(e) = cap.parse::<weft_ipc_types::capability::Capability>() {
errors.push(format!("unknown capability '{cap}'")); errors.push(e.to_string());
} }
} }
} }
@ -229,28 +229,6 @@ fn print_info(m: &Manifest) {
} }
} }
fn is_known_capability(cap: &str) -> bool {
const EXACT: &[&str] = &[
"fs:rw:app-data",
"fs:read:app-data",
"fs:rw:xdg-documents",
"fs:read:xdg-documents",
"net:fetch:*",
"hw:gpu:compute",
"hw:gpu:render",
"sys:notifications",
"sys:clipboard:read",
"sys:clipboard:write",
];
if EXACT.contains(&cap) {
return true;
}
if let Some(domain) = cap.strip_prefix("net:fetch:") {
return !domain.is_empty() && domain != "*";
}
false
}
fn is_valid_app_id(id: &str) -> bool { fn is_valid_app_id(id: &str) -> bool {
let parts: Vec<&str> = id.split('.').collect(); let parts: Vec<&str> = id.split('.').collect();
if parts.len() < 3 { if parts.len() < 3 {

View file

@ -12,7 +12,7 @@ path = "src/main.rs"
default = [] default = []
wasmtime-runtime = ["dep:wasmtime", "dep:wasmtime-wasi", "dep:cap-std"] wasmtime-runtime = ["dep:wasmtime", "dep:wasmtime-wasi", "dep:cap-std"]
seccomp = ["dep:seccompiler", "dep:libc"] seccomp = ["dep:seccompiler", "dep:libc"]
net-fetch = ["dep:ureq"] net-fetch = ["dep:ureq", "dep:url"]
[dependencies] [dependencies]
anyhow = "1.0" anyhow = "1.0"
@ -24,3 +24,5 @@ cap-std = { version = "3", optional = true }
seccompiler = { version = "0.4", optional = true } seccompiler = { version = "0.4", optional = true }
libc = { version = "0.2", optional = true } libc = { version = "0.2", optional = true }
ureq = { version = "2", optional = true } ureq = { version = "2", optional = true }
url = { version = "2", optional = true }
weft-ipc-types = { path = "../weft-ipc-types" }

View file

@ -0,0 +1,173 @@
//! The effective grants weft-appd derived for this session.
//!
//! weft-appd passes each host-import capability as `--grant <capability>` and
//! each filesystem capability as `--preopen HOST::GUEST::ro|rw`. Nothing here
//! reads the package manifest: the runtime enforces what the supervisor
//! granted, not what the package asks for.
use anyhow::Context;
use weft_ipc_types::capability::{Access, Capability, FetchScope};
/// Grants for the host imports in the `weft:app` world.
#[derive(Debug, Default)]
pub struct Grants {
fetch: Vec<FetchScope>,
notifications: bool,
clipboard_read: bool,
clipboard_write: bool,
}
// The checks are used by the import implementations, which only exist with
// the wasmtime-runtime feature.
#[cfg_attr(not(feature = "wasmtime-runtime"), allow(dead_code))]
impl Grants {
/// Adds a `--grant` argument. Filesystem capabilities arrive as preopens
/// and hardware capabilities have no import, so both are refused here.
pub fn add(&mut self, spec: &str) -> anyhow::Result<()> {
match spec.parse::<Capability>()? {
Capability::Fetch(scope) => self.fetch.push(scope),
Capability::Notifications => self.notifications = true,
Capability::ClipboardRead => self.clipboard_read = true,
Capability::ClipboardWrite => self.clipboard_write = true,
other => anyhow::bail!("'{other}' is not granted through --grant"),
}
Ok(())
}
pub fn notifications(&self) -> Result<(), String> {
granted(self.notifications, "sys:notifications")
}
pub fn clipboard_read(&self) -> Result<(), String> {
granted(self.clipboard_read, "sys:clipboard:read")
}
pub fn clipboard_write(&self) -> Result<(), String> {
granted(self.clipboard_write, "sys:clipboard:write")
}
#[cfg_attr(not(feature = "net-fetch"), allow(dead_code))]
/// Whether a request to `host` is covered by a fetch grant. `host` is the
/// URL's host in the lowercase form URL parsing produces.
pub fn fetch_host(&self, host: &str) -> Result<(), String> {
if self.fetch.is_empty() {
return Err("capability net:fetch is not granted".to_owned());
}
let covered = self.fetch.iter().any(|scope| match scope {
FetchScope::AnyHost => true,
FetchScope::Host(granted) => granted == host,
});
if covered {
Ok(())
} else {
Err(format!("capability net:fetch:{host} is not granted"))
}
}
/// Whether any fetch grant exists, before a URL is examined.
pub fn fetch_any(&self) -> Result<(), String> {
granted(!self.fetch.is_empty(), "net:fetch")
}
}
#[cfg_attr(not(feature = "wasmtime-runtime"), allow(dead_code))]
fn granted(present: bool, capability: &str) -> Result<(), String> {
if present {
Ok(())
} else {
Err(format!("capability {capability} is not granted"))
}
}
/// A directory made visible to the component.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Preopen {
pub host: String,
pub guest: String,
pub access: Access,
}
impl Preopen {
/// Parses `HOST::GUEST::ro` or `HOST::GUEST::rw`.
pub fn parse(spec: &str) -> anyhow::Result<Self> {
let (rest, mode) = spec
.rsplit_once("::")
.context("--preopen expects HOST::GUEST::ro|rw")?;
let (host, guest) = rest
.split_once("::")
.context("--preopen expects HOST::GUEST::ro|rw")?;
let access = match mode {
"ro" => Access::Read,
"rw" => Access::ReadWrite,
other => anyhow::bail!("--preopen mode must be ro or rw, not '{other}'"),
};
anyhow::ensure!(
!host.is_empty() && guest.starts_with('/'),
"--preopen needs a host path and an absolute guest path"
);
Ok(Self {
host: host.to_owned(),
guest: guest.to_owned(),
access,
})
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn imports_are_denied_without_grants() {
let grants = Grants::default();
assert!(grants.notifications().is_err());
assert!(grants.clipboard_read().is_err());
assert!(grants.clipboard_write().is_err());
assert!(grants.fetch_any().is_err());
assert!(grants.fetch_host("example.org").is_err());
}
#[test]
fn each_grant_opens_only_its_import() {
let mut grants = Grants::default();
grants.add("sys:clipboard:read").unwrap();
assert!(grants.clipboard_read().is_ok());
assert!(grants.clipboard_write().is_err());
assert!(grants.notifications().is_err());
}
#[test]
fn host_fetch_grants_match_exact_hosts() {
let mut grants = Grants::default();
grants.add("net:fetch:api.example.org").unwrap();
assert!(grants.fetch_any().is_ok());
assert!(grants.fetch_host("api.example.org").is_ok());
assert!(grants.fetch_host("example.org").is_err());
assert!(grants.fetch_host("evil.api.example.org").is_err());
grants.add("net:fetch:*").unwrap();
assert!(grants.fetch_host("example.org").is_ok());
}
#[test]
fn filesystem_and_unknown_grants_are_refused() {
let mut grants = Grants::default();
assert!(grants.add("fs:rw:app-data").is_err());
assert!(grants.add("hw:gpu:compute").is_err());
assert!(grants.add("sys:everything").is_err());
}
#[test]
fn preopens_carry_their_mode() {
let preopen = Preopen::parse("/home/u/data::/data::ro").unwrap();
assert_eq!(preopen.host, "/home/u/data");
assert_eq!(preopen.guest, "/data");
assert_eq!(preopen.access, Access::Read);
assert_eq!(
Preopen::parse("/a::/b::rw").unwrap().access,
Access::ReadWrite
);
for bad in ["/a::/b", "/a", "/a::/b::wx", "::/b::ro", "/a::b::ro"] {
assert!(Preopen::parse(bad).is_err(), "{bad} accepted");
}
}
}

View file

@ -2,6 +2,10 @@ use std::path::PathBuf;
use anyhow::Context; use anyhow::Context;
mod grants;
use grants::{Grants, Preopen};
fn main() -> anyhow::Result<()> { fn main() -> anyhow::Result<()> {
tracing_subscriber::fmt() tracing_subscriber::fmt()
.with_env_filter( .with_env_filter(
@ -14,7 +18,7 @@ fn main() -> anyhow::Result<()> {
if args.len() < 3 { if args.len() < 3 {
anyhow::bail!( anyhow::bail!(
"usage: weft-runtime <app_id> <session_id> \ "usage: weft-runtime <app_id> <session_id> \
[--preopen HOST::GUEST]... [--ipc-socket PATH]" [--preopen HOST::GUEST::ro|rw]... [--grant CAPABILITY]... [--ipc-socket PATH]"
); );
} }
let app_id = &args[1]; let app_id = &args[1];
@ -22,7 +26,8 @@ fn main() -> anyhow::Result<()> {
.parse() .parse()
.with_context(|| format!("invalid session_id: {}", args[2]))?; .with_context(|| format!("invalid session_id: {}", args[2]))?;
let mut preopen: Vec<(String, String)> = Vec::new(); let mut preopen: Vec<Preopen> = Vec::new();
let mut grants = Grants::default();
let mut ipc_socket: Option<String> = None; let mut ipc_socket: Option<String> = None;
let mut i = 3usize; let mut i = 3usize;
@ -31,11 +36,11 @@ fn main() -> anyhow::Result<()> {
"--preopen" => { "--preopen" => {
i += 1; i += 1;
let spec = args.get(i).context("--preopen requires an argument")?; let spec = args.get(i).context("--preopen requires an argument")?;
if let Some((host, guest)) = spec.split_once("::") { preopen.push(Preopen::parse(spec)?);
preopen.push((host.to_string(), guest.to_string()));
} else {
preopen.push((spec.clone(), spec.clone()));
} }
"--grant" => {
i += 1;
grants.add(args.get(i).context("--grant requires an argument")?)?;
} }
"--ipc-socket" => { "--ipc-socket" => {
i += 1; i += 1;
@ -64,7 +69,7 @@ fn main() -> anyhow::Result<()> {
} }
tracing::info!(session_id, %app_id, wasm = %wasm_path.display(), "executing module"); tracing::info!(session_id, %app_id, wasm = %wasm_path.display(), "executing module");
run_module(&wasm_path, &preopen, ipc_socket.as_deref())?; run_module(&wasm_path, &preopen, grants, ipc_socket.as_deref())?;
tracing::info!(session_id, %app_id, "exiting"); tracing::info!(session_id, %app_id, "exiting");
Ok(()) Ok(())
@ -94,7 +99,8 @@ fn resolve_package(app_id: &str) -> anyhow::Result<PathBuf> {
#[cfg(not(feature = "wasmtime-runtime"))] #[cfg(not(feature = "wasmtime-runtime"))]
fn run_module( fn run_module(
_wasm_path: &std::path::Path, _wasm_path: &std::path::Path,
_preopen: &[(String, String)], _preopen: &[Preopen],
_grants: Grants,
_ipc_socket: Option<&str>, _ipc_socket: Option<&str>,
) -> anyhow::Result<()> { ) -> anyhow::Result<()> {
anyhow::bail!( anyhow::bail!(
@ -105,7 +111,8 @@ fn run_module(
#[cfg(feature = "wasmtime-runtime")] #[cfg(feature = "wasmtime-runtime")]
fn run_module( fn run_module(
wasm_path: &std::path::Path, wasm_path: &std::path::Path,
preopen: &[(String, String)], preopen: &[Preopen],
grants: Grants,
ipc_socket: Option<&str>, ipc_socket: Option<&str>,
) -> anyhow::Result<()> { ) -> anyhow::Result<()> {
use std::sync::{Arc, Mutex}; use std::sync::{Arc, Mutex};
@ -117,6 +124,7 @@ fn run_module(
DirPerms, FilePerms, IoView, ResourceTable, WasiCtx, WasiCtxBuilder, WasiView, DirPerms, FilePerms, IoView, ResourceTable, WasiCtx, WasiCtxBuilder, WasiView,
add_to_linker_sync, bindings::sync::Command, add_to_linker_sync, bindings::sync::Command,
}; };
use weft_ipc_types::capability::Access;
struct IpcState { struct IpcState {
socket: std::os::unix::net::UnixStream, socket: std::os::unix::net::UnixStream,
@ -175,7 +183,6 @@ fn run_module(
struct State { struct State {
ctx: WasiCtx, ctx: WasiCtx,
table: ResourceTable, table: ResourceTable,
ipc: Arc<Mutex<Option<IpcState>>>,
} }
impl IoView for State { impl IoView for State {
@ -197,6 +204,7 @@ fn run_module(
let component = Component::from_file(&engine, wasm_path) let component = Component::from_file(&engine, wasm_path)
.with_context(|| format!("load component {}", wasm_path.display()))?; .with_context(|| format!("load component {}", wasm_path.display()))?;
let grants = Arc::new(grants);
let mut linker: Linker<State> = Linker::new(&engine); let mut linker: Linker<State> = Linker::new(&engine);
add_to_linker_sync(&mut linker).context("add WASI to linker")?; add_to_linker_sync(&mut linker).context("add WASI to linker")?;
let ipc_state: Arc<Mutex<Option<IpcState>>> = Arc::new(Mutex::new(None)); let ipc_state: Arc<Mutex<Option<IpcState>>> = Arc::new(Mutex::new(None));
@ -245,34 +253,35 @@ fn run_module(
.context("define weft:app/ipc#recv")?; .context("define weft:app/ipc#recv")?;
} }
// Every import below checks the session's grants on each call; an
// ungranted call returns an error to the component.
let fetch_grants = Arc::clone(&grants);
linker linker
.instance("weft:app/fetch@0.1.0") .instance("weft:app/fetch@0.1.0")
.context("define weft:app/fetch instance")? .context("define weft:app/fetch instance")?
.func_wrap( .func_wrap(
"fetch", "fetch",
|_: wasmtime::StoreContextMut<'_, State>, move |_: wasmtime::StoreContextMut<'_, State>,
(url, method, headers, body): ( (url, method, headers, body): FetchRequest|
String, -> wasmtime::Result<(FetchResult,)> {
String, let result = host_fetch(&fetch_grants, &url, &method, &headers, body.as_deref());
Vec<(String, String)>,
Option<Vec<u8>>,
)|
-> wasmtime::Result<(Result<(u16, String, Vec<u8>), String>,)> {
let result = host_fetch(&url, &method, &headers, body.as_deref());
Ok((result,)) Ok((result,))
}, },
) )
.context("define weft:app/fetch#fetch")?; .context("define weft:app/fetch#fetch")?;
let notify_grants = Arc::clone(&grants);
linker linker
.instance("weft:app/notifications@0.1.0") .instance("weft:app/notifications@0.1.0")
.context("define weft:app/notifications instance")? .context("define weft:app/notifications instance")?
.func_wrap( .func_wrap(
"notify", "notify",
|_: wasmtime::StoreContextMut<'_, State>, move |_: wasmtime::StoreContextMut<'_, State>,
(title, body, icon): (String, String, Option<String>)| (title, body, icon): (String, String, Option<String>)|
-> wasmtime::Result<(Result<(), String>,)> { -> wasmtime::Result<(Result<(), String>,)> {
let result = host_notify(&title, &body, icon.as_deref()); let result = notify_grants
.notifications()
.and_then(|()| host_notify(&title, &body, icon.as_deref()));
Ok((result,)) Ok((result,))
}, },
) )
@ -282,23 +291,29 @@ fn run_module(
let mut clipboard = linker let mut clipboard = linker
.instance("weft:app/clipboard@0.1.0") .instance("weft:app/clipboard@0.1.0")
.context("define weft:app/clipboard instance")?; .context("define weft:app/clipboard instance")?;
let read_grants = Arc::clone(&grants);
clipboard clipboard
.func_wrap( .func_wrap(
"read", "read",
|_: wasmtime::StoreContextMut<'_, State>, move |_: wasmtime::StoreContextMut<'_, State>,
()| ()|
-> wasmtime::Result<(Result<String, String>,)> { -> wasmtime::Result<(Result<String, String>,)> {
Ok((host_clipboard_read(),)) Ok((read_grants
.clipboard_read()
.and_then(|()| host_clipboard_read()),))
}, },
) )
.context("define weft:app/clipboard#read")?; .context("define weft:app/clipboard#read")?;
let write_grants = Arc::clone(&grants);
clipboard clipboard
.func_wrap( .func_wrap(
"write", "write",
|_: wasmtime::StoreContextMut<'_, State>, move |_: wasmtime::StoreContextMut<'_, State>,
(text,): (String,)| (text,): (String,)|
-> wasmtime::Result<(Result<(), String>,)> { -> wasmtime::Result<(Result<(), String>,)> {
Ok((host_clipboard_write(&text),)) Ok((write_grants
.clipboard_write()
.and_then(|()| host_clipboard_write(&text)),))
}, },
) )
.context("define weft:app/clipboard#write")?; .context("define weft:app/clipboard#write")?;
@ -320,10 +335,14 @@ fn run_module(
ctx_builder.env("WEFT_FILE_PORTAL_SOCKET", &portal_socket); ctx_builder.env("WEFT_FILE_PORTAL_SOCKET", &portal_socket);
} }
for (host_path, guest_path) in preopen { for dir in preopen {
let (dir_perms, file_perms) = match dir.access {
Access::Read => (DirPerms::READ, FilePerms::READ),
Access::ReadWrite => (DirPerms::all(), FilePerms::all()),
};
ctx_builder ctx_builder
.preopened_dir(host_path, guest_path, DirPerms::all(), FilePerms::all()) .preopened_dir(&dir.host, &dir.guest, dir_perms, file_perms)
.with_context(|| format!("preopen dir {host_path}"))?; .with_context(|| format!("preopen dir {}", dir.host))?;
} }
let ctx = ctx_builder.build(); let ctx = ctx_builder.build();
@ -332,7 +351,6 @@ fn run_module(
State { State {
ctx, ctx,
table: ResourceTable::new(), table: ResourceTable::new(),
ipc: ipc_state,
}, },
); );
@ -346,41 +364,97 @@ fn run_module(
.map_err(|()| anyhow::anyhow!("wasm component run exited with error")) .map_err(|()| anyhow::anyhow!("wasm component run exited with error"))
} }
/// Arguments of `weft:app/fetch#fetch`: URL, method, headers and body.
#[cfg(feature = "wasmtime-runtime")]
type FetchRequest = (String, String, Vec<(String, String)>, Option<Vec<u8>>);
/// `weft:app/fetch.response`.
#[cfg(feature = "wasmtime-runtime")]
#[derive(
wasmtime::component::ComponentType, wasmtime::component::Lift, wasmtime::component::Lower,
)]
#[component(record)]
struct FetchResponse {
status: u16,
#[component(name = "content-type")]
content_type: String,
body: Vec<u8>,
}
/// Result of `weft:app/fetch#fetch`.
#[cfg(feature = "wasmtime-runtime")]
type FetchResult = Result<FetchResponse, String>;
/// Longest response body returned to a component.
#[cfg(all(feature = "wasmtime-runtime", feature = "net-fetch"))]
const MAX_FETCH_RESPONSE: u64 = 16 * 1024 * 1024;
/// Performs a granted HTTP request. Redirects are returned to the component
/// as responses rather than followed, so every destination it reaches is
/// checked against its grants. HTTP error statuses are responses too; only
/// policy and transport failures are errors.
#[cfg(all(feature = "wasmtime-runtime", feature = "net-fetch"))] #[cfg(all(feature = "wasmtime-runtime", feature = "net-fetch"))]
fn host_fetch( fn host_fetch(
grants: &Grants,
url: &str, url: &str,
method: &str, method: &str,
headers: &[(String, String)], headers: &[(String, String)],
body: Option<&[u8]>, body: Option<&[u8]>,
) -> Result<(u16, String, Vec<u8>), String> { ) -> FetchResult {
use std::io::Read; use std::io::Read;
let mut req = ureq::request(method, url); use std::time::Duration;
grants.fetch_any()?;
let parsed = url::Url::parse(url).map_err(|e| format!("invalid URL: {e}"))?;
if !matches!(parsed.scheme(), "http" | "https") {
return Err(format!("unsupported URL scheme '{}'", parsed.scheme()));
}
let host = parsed.host_str().ok_or("URL has no host")?;
grants.fetch_host(host)?;
let agent = ureq::AgentBuilder::new()
.redirects(0)
.timeout_connect(Duration::from_secs(10))
.timeout(Duration::from_secs(30))
.build();
let mut req = agent.request_url(method, &parsed);
for (name, value) in headers { for (name, value) in headers {
req = req.set(name, value); req = req.set(name, value);
} }
let response = match body { let response = match body {
Some(b) => req.send_bytes(b), Some(b) => req.send_bytes(b),
None => req.call(), None => req.call(),
} };
.map_err(|e| e.to_string())?; let response = match response {
Ok(response) | Err(ureq::Error::Status(_, response)) => response,
Err(e) => return Err(e.to_string()),
};
let status = response.status(); let status = response.status();
let content_type = response.content_type().to_owned(); let content_type = response.content_type().to_owned();
let mut body_bytes = Vec::new(); let mut body_bytes = Vec::new();
response response
.into_reader() .into_reader()
.take(MAX_FETCH_RESPONSE + 1)
.read_to_end(&mut body_bytes) .read_to_end(&mut body_bytes)
.map_err(|e| e.to_string())?; .map_err(|e| e.to_string())?;
Ok((status, content_type, body_bytes)) if body_bytes.len() as u64 > MAX_FETCH_RESPONSE {
return Err(format!("response body exceeds {MAX_FETCH_RESPONSE} bytes"));
}
Ok(FetchResponse {
status,
content_type,
body: body_bytes,
})
} }
#[cfg(all(feature = "wasmtime-runtime", not(feature = "net-fetch")))] #[cfg(all(feature = "wasmtime-runtime", not(feature = "net-fetch")))]
fn host_fetch( fn host_fetch(
grants: &Grants,
_url: &str, _url: &str,
_method: &str, _method: &str,
_headers: &[(String, String)], _headers: &[(String, String)],
_body: Option<&[u8]>, _body: Option<&[u8]>,
) -> Result<(u16, String, Vec<u8>), String> { ) -> FetchResult {
Err("net-fetch capability not compiled in".to_owned()) grants.fetch_any()?;
Err("this runtime was built without network fetch support".to_owned())
} }
#[cfg(feature = "wasmtime-runtime")] #[cfg(feature = "wasmtime-runtime")]
@ -520,7 +594,12 @@ mod tests {
#[cfg(not(feature = "wasmtime-runtime"))] #[cfg(not(feature = "wasmtime-runtime"))]
#[test] #[test]
fn engine_disabled_build_refuses_to_run_components() { fn engine_disabled_build_refuses_to_run_components() {
let err = run_module(std::path::Path::new("app.wasm"), &[], None) let err = run_module(
std::path::Path::new("app.wasm"),
&[],
Grants::default(),
None,
)
.expect_err("a build without wasmtime-runtime must not report success"); .expect_err("a build without wasmtime-runtime must not report success");
assert!(err.to_string().contains("wasmtime-runtime")); assert!(err.to_string().contains("wasmtime-runtime"));
} }

View file

@ -32,7 +32,7 @@ Package management CLI. Subcommands: `check` (validate wapp.toml + wasm module),
### weft-file-portal ### weft-file-portal
Per-session file proxy. Runs as a separate process with a path allowlist derived from preopened directories. Accepts JSON-lines requests over a Unix socket. Blocks path traversal. Used by apps that require file access without direct WASI preopens. Per-session file proxy. Runs as a separate process with a path allowlist derived from the session's directory grants; read-only grants (`--allow-read`) refuse writes. Accepts JSON-lines requests over a Unix socket. Blocks path traversal. Used by apps that require file access without direct WASI preopens.
### weft-mount-helper ### weft-mount-helper
@ -46,9 +46,9 @@ systemd
├── weft-servo-shell (user, after compositor) ├── weft-servo-shell (user, after compositor)
└── weft-appd (user, after compositor + servo-shell) └── weft-appd (user, after compositor + servo-shell)
└── per-session: └── per-session:
├── weft-runtime <app_id> <session_id> [--preopen ...] [--ipc-socket ...] ├── weft-runtime <app_id> <session_id> [--preopen HOST::GUEST::ro|rw]... [--grant CAP]... [--ipc-socket ...]
├── weft-app-shell <app_id> <session_id> ├── weft-app-shell <app_id> <session_id>
└── weft-file-portal <socket> [--allow ...] └── weft-file-portal <socket> [--allow ...] [--allow-read ...]
``` ```
## IPC ## IPC
@ -69,15 +69,28 @@ Every WebSocket connection must complete the upgrade and send `HELLO` as its fir
## Capability Enforcement ## Capability Enforcement
Capabilities are declared in `wapp.toml` under `[package] capabilities`. `weft-pack check` validates that only known capabilities are listed. At runtime, `weft-appd` reads capabilities and maps them to WASI preopened directories and host function availability: Capabilities are declared in `wapp.toml` under `[package] capabilities`. One vocabulary (`weft_ipc_types::capability`) is used by `weft-pack check`, which rejects unknown strings, by `weft-appd`, which derives the session's effective grants, and by `weft-runtime`, which enforces them.
`weft-appd` derives grants once, before a session exists. If any declared capability is unknown, unsupported on this host or cannot be satisfied, `LAUNCH_APP` is answered with an error (code 403) and nothing starts. The runtime does not read the manifest; it receives the grants as arguments:
- `--preopen HOST::GUEST::ro|rw` for each directory, with the access mode the capability names;
- `--grant <capability>` for each host-import capability.
Each host import checks its grant on every call and returns an error naming the missing capability when it is not granted.
| Capability | Effect | | Capability | Effect |
|---|---| |---|---|
| `fs:rw:app-data` | Preopen `~/.local/share/weft/apps/<id>/data` as `/data` | | `fs:read:app-data` / `fs:rw:app-data` | Preopen `~/.local/share/weft/apps/<id>/data` as `/data`, read-only or read-write |
| `fs:read:app-data` | Same, read-only | | `fs:read:xdg-documents` / `fs:rw:xdg-documents` | Preopen the documents directory from the XDG user-dirs configuration (`XDG_DOCUMENTS_DIR`) as `/xdg/documents`; the launch fails when none is configured |
| `fs:rw:xdg-documents` | Preopen `~/Documents` as `/xdg/documents` | | `net:fetch:<host>` | `weft:app/fetch` to that exact host over HTTP or HTTPS |
| `net:fetch` | Enables `weft:app/fetch` host function | | `net:fetch:*` | `weft:app/fetch` to any host |
| `sys:notifications` | Enables `weft:app/notifications` host function | | `sys:notifications` | `weft:app/notifications` |
| `sys:clipboard:read` / `sys:clipboard:write` | `weft:app/clipboard#read` / `#write` |
| `hw:gpu:compute` / `hw:gpu:render` | Not supported; the launch fails |
Fetch does not follow redirects: a redirect is returned to the component as a response, so every destination it requests is checked against its grants. HTTP error statuses are responses too; only policy and transport failures are errors. Requests time out after 10 seconds to connect and 30 seconds overall, and response bodies are limited to 16 MiB. Fetch requires a runtime built with the `net-fetch` feature.
`tests/runtime/check_grants.py` runs the real runtime on a probe component (`tests/components/grants-probe`) under each kind of grant.
## Package Format ## Package Format

View file

@ -6,7 +6,9 @@ WEFT OS enforces a capability-based security model. No capability is granted by
## Capability Verification ## Capability Verification
`weft-pack check` validates capability strings against a known set (`KNOWN_CAPS`) before installation. Unknown capability strings are rejected. The validated capability list is read by `weft-appd` at session start to map capabilities to concrete resource grants. `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.
## Process Isolation ## Process Isolation
@ -14,7 +16,7 @@ Each app session runs as a separate OS process (`weft-runtime`). When systemd is
## Filesystem Isolation ## Filesystem Isolation
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 enforces path allowlists and blocks `..` traversal for apps that use the portal protocol. 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

337
tests/components/grants-probe/Cargo.lock generated Normal file
View file

@ -0,0 +1,337 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 4
[[package]]
name = "anyhow"
version = "1.0.104"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470"
[[package]]
name = "bitflags"
version = "2.13.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06"
[[package]]
name = "equivalent"
version = "1.0.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f"
[[package]]
name = "foldhash"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb"
[[package]]
name = "hashbrown"
version = "0.16.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100"
dependencies = [
"foldhash",
]
[[package]]
name = "hashbrown"
version = "0.17.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a"
[[package]]
name = "heck"
version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
[[package]]
name = "id-arena"
version = "2.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954"
[[package]]
name = "indexmap"
version = "2.14.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855"
dependencies = [
"equivalent",
"hashbrown 0.17.1",
"serde",
"serde_core",
]
[[package]]
name = "itoa"
version = "1.0.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682"
[[package]]
name = "leb128fmt"
version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "09edd9e8b54e49e587e4f6295a7d29c3ea94d469cb40ab8ca70b288248a81db2"
[[package]]
name = "log"
version = "0.4.34"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6"
[[package]]
name = "memchr"
version = "2.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
[[package]]
name = "prettyplease"
version = "0.2.37"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "479ca8adacdd7ce8f1fb39ce9ecccbfe93a3f1344b3d0d97f20bc0196208f62b"
dependencies = [
"proc-macro2",
"syn 2.0.119",
]
[[package]]
name = "proc-macro2"
version = "1.0.107"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"
dependencies = [
"unicode-ident",
]
[[package]]
name = "quote"
version = "1.0.47"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"
dependencies = [
"proc-macro2",
]
[[package]]
name = "semver"
version = "1.0.28"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd"
[[package]]
name = "serde"
version = "1.0.229"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba"
dependencies = [
"serde_core",
]
[[package]]
name = "serde_core"
version = "1.0.229"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48"
dependencies = [
"serde_derive",
]
[[package]]
name = "serde_derive"
version = "1.0.229"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348"
dependencies = [
"proc-macro2",
"quote",
"syn 3.0.6",
]
[[package]]
name = "serde_json"
version = "1.0.151"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c841b55ecdae098c80dcae9cf767f6f8a0c2cdb3416bbef72181df4d0fe73f14"
dependencies = [
"itoa",
"memchr",
"serde",
"serde_core",
"zmij",
]
[[package]]
name = "syn"
version = "2.0.119"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297"
dependencies = [
"proc-macro2",
"quote",
"unicode-ident",
]
[[package]]
name = "syn"
version = "3.0.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8593e8e72159ed2257d083c7a454a85cbf854f37a0966d8d483aff8c8a3ebcee"
dependencies = [
"proc-macro2",
"quote",
"unicode-ident",
]
[[package]]
name = "unicode-ident"
version = "1.0.26"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d245f478577f809a851594d02313b640fb437e0bb33866753cff937863096954"
[[package]]
name = "unicode-xid"
version = "0.2.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853"
[[package]]
name = "wasm-encoder"
version = "0.245.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3f9dca005e69bf015e45577e415b9af8c67e8ee3c0e38b5b0add5aa92581ed5c"
dependencies = [
"leb128fmt",
"wasmparser",
]
[[package]]
name = "wasm-metadata"
version = "0.245.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "da55e60097e8b37b475a0fa35c3420dd71d9eb7bd66109978ab55faf56a57efb"
dependencies = [
"anyhow",
"indexmap",
"wasm-encoder",
"wasmparser",
]
[[package]]
name = "wasmparser"
version = "0.245.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4f08c9adee0428b7bddf3890fc27e015ac4b761cc608c822667102b8bfd6995e"
dependencies = [
"bitflags",
"hashbrown 0.16.1",
"indexmap",
"semver",
]
[[package]]
name = "weft-grants-probe"
version = "0.1.0"
dependencies = [
"wit-bindgen",
]
[[package]]
name = "wit-bindgen"
version = "0.53.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6e915216dde3e818093168df8380a64fba25df468d626c80dd5d6a184c87e7c7"
dependencies = [
"bitflags",
"wit-bindgen-rust-macro",
]
[[package]]
name = "wit-bindgen-core"
version = "0.53.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3deda4b7e9f522d994906f6e6e0fc67965ea8660306940a776b76732be8f3933"
dependencies = [
"anyhow",
"heck",
"wit-parser",
]
[[package]]
name = "wit-bindgen-rust"
version = "0.53.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "863a7ab3c4dfee58db196811caeb0718b88412a0aef3d1c2b02fcbae1e37c688"
dependencies = [
"anyhow",
"heck",
"indexmap",
"prettyplease",
"syn 2.0.119",
"wasm-metadata",
"wit-bindgen-core",
"wit-component",
]
[[package]]
name = "wit-bindgen-rust-macro"
version = "0.53.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d14f3a9bfa3804bb0e9ab7f66da047f210eded6a1297ae3ba5805b384d64797f"
dependencies = [
"anyhow",
"prettyplease",
"proc-macro2",
"quote",
"syn 2.0.119",
"wit-bindgen-core",
"wit-bindgen-rust",
]
[[package]]
name = "wit-component"
version = "0.245.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4894f10d2d5cbc17c77e91f86a1e48e191a788da4425293b55c98b44ba3fcac9"
dependencies = [
"anyhow",
"bitflags",
"indexmap",
"log",
"serde",
"serde_derive",
"serde_json",
"wasm-encoder",
"wasm-metadata",
"wasmparser",
"wit-parser",
]
[[package]]
name = "wit-parser"
version = "0.245.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "330698718e82983499419494dd1e3d7811a457a9bf9f69734e8c5f07a2547929"
dependencies = [
"anyhow",
"hashbrown 0.16.1",
"id-arena",
"indexmap",
"log",
"semver",
"serde",
"serde_derive",
"serde_json",
"unicode-xid",
"wasmparser",
]
[[package]]
name = "zmij"
version = "1.0.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"

View file

@ -0,0 +1,12 @@
[package]
name = "weft-grants-probe"
version = "0.1.0"
edition = "2024"
publish = false
[[bin]]
name = "app"
path = "src/main.rs"
[dependencies]
wit-bindgen = "0.53"

View file

@ -0,0 +1,35 @@
//! Test component that calls every grant-controlled operation once and
//! prints one `PROBE <name> ok <detail>` or `PROBE <name> err <message>`
//! line for each.
//!
//! Fetch targets are read from `/probe/targets.txt` (`<name> <url>` per
//! line), a directory the harness preopens read-only next to the grants
//! under test.
wit_bindgen::generate!({
path: "wit",
world: "app",
generate_all,
});
use weft::app::{clipboard, fetch, notifications, notify};
fn report<T: std::fmt::Debug, E: std::fmt::Display>(name: &str, result: Result<T, E>) {
match result {
Ok(value) => println!("PROBE {name} ok {value:?}"),
Err(e) => println!("PROBE {name} err {}", e.to_string().replace('\n', " ")),
}
}
fn main() {
report("data-read", std::fs::read_to_string("/data/seed.txt"));
report("data-write", std::fs::write("/data/written.txt", "probe"));
report("notifications", notifications::notify("probe", "probe", None));
report("clipboard-read", clipboard::read());
report("clipboard-write", clipboard::write("probe"));
let targets = std::fs::read_to_string("/probe/targets.txt").unwrap_or_default();
for (name, url) in targets.lines().filter_map(|line| line.split_once(' ')) {
report(name, fetch::fetch(url, "GET", &[], None).map(|r| r.status));
}
notify::ready();
}

View file

@ -0,0 +1 @@
../../../../../crates/weft-runtime/wit

View file

@ -0,0 +1,8 @@
package weft:grants-probe@0.1.0;
world app {
import weft:app/notify@0.1.0;
import weft:app/fetch@0.1.0;
import weft:app/notifications@0.1.0;
import weft:app/clipboard@0.1.0;
}

View file

@ -0,0 +1,186 @@
"""Check that weft-runtime enforces the grants weft-appd passes it.
The harness runs the real runtime (built with wasmtime-runtime and
net-fetch) on the test component in tests/components/grants-probe, which
calls every grant-controlled operation once and prints its outcome. Each
scenario passes a different set of `--grant` and `--preopen` arguments:
- no grants: no /data, and every host import reports that its capability
is not granted;
- read-only data: /data can be read but not written, and nothing appears
on the host;
- read-write data: the write reaches the host directory;
- notifications and clipboard read: those imports are attempted (they may
still fail for lack of a desktop service) while clipboard write stays
denied;
- a host-specific fetch grant: requests to that host return their real
status (200, 404, and 302 without following the redirect to another
host), and requests to another host are denied;
- a wildcard fetch grant: the other host is reachable.
It also checks that the runtime refuses filesystem capabilities passed as
`--grant` and preopens without an access mode.
Requires cargo with the wasm32-wasip2 target.
"""
import argparse
import http.server
import shutil
import subprocess
import sys
import tempfile
import threading
from pathlib import Path
ROOT = Path(__file__).resolve().parents[2]
PROBE_DIR = ROOT / "tests/components/grants-probe"
APP_ID = "org.weft.test.grants"
NOT_GRANTED = "is not granted"
class Handler(http.server.BaseHTTPRequestHandler):
def do_GET(self):
if self.path == "/ok":
self.send_response(200)
elif self.path == "/redirect":
self.send_response(302)
self.send_header("Location", f"http://localhost:{self.server.server_port}/ok")
else:
self.send_response(404)
self.send_header("Content-Length", "0")
self.end_headers()
def log_message(self, *args):
pass
def build_probe():
subprocess.run(["cargo", "build", "-q", "--release", "--target", "wasm32-wasip2"],
cwd=PROBE_DIR, check=True)
return PROBE_DIR / "target/wasm32-wasip2/release/app.wasm"
class Runner:
def __init__(self, runtime, work, port):
self.runtime = runtime
self.work = work
self.store = work / "store"
package = self.store / APP_ID
package.mkdir(parents=True)
(package / "wapp.toml").write_text(
f'[package]\nid = "{APP_ID}"\nname = "Grants probe"\nversion = "0.1.0"\n'
'[runtime]\nmodule = "app.wasm"\n[ui]\nentry = "ui/index.html"\n')
self.package = package
self.targets = work / "targets"
self.targets.mkdir()
(self.targets / "targets.txt").write_text(
f"fetch-ok http://127.0.0.1:{port}/ok\n"
f"fetch-missing http://127.0.0.1:{port}/missing\n"
f"fetch-redirect http://127.0.0.1:{port}/redirect\n"
f"fetch-other-host http://localhost:{port}/ok\n")
def run(self, *arguments, expect_success=True):
command = [str(self.runtime), APP_ID, "1",
"--preopen", f"{self.targets}::/probe::ro", *arguments]
result = subprocess.run(command, capture_output=True, text=True, timeout=60,
env={"WEFT_APP_STORE": str(self.store), "PATH": "/usr/bin:/bin",
"RUST_LOG": "warn"})
if expect_success and result.returncode != 0:
raise AssertionError(f"runtime failed: {' '.join(arguments)}\n{result.stderr}")
probes = {}
for line in result.stdout.splitlines():
if line.startswith("PROBE "):
name, outcome = line[6:].split(" ", 1)
probes[name] = outcome
return result, probes
def expect(probes, name, ok, contains=None, absent=None):
outcome = probes.get(name)
if outcome is None:
raise AssertionError(f"{name}: no result")
if outcome.startswith("ok") != ok:
raise AssertionError(f"{name}: expected {'success' if ok else 'failure'}, got {outcome!r}")
if contains is not None and contains not in outcome:
raise AssertionError(f"{name}: expected {contains!r} in {outcome!r}")
if absent is not None and absent in outcome:
raise AssertionError(f"{name}: did not expect {absent!r} in {outcome!r}")
def check(runner, data):
_, probes = runner.run()
expect(probes, "data-read", False)
expect(probes, "data-write", False)
for name in ("notifications", "clipboard-read", "clipboard-write",
"fetch-ok", "fetch-other-host"):
expect(probes, name, False, contains=NOT_GRANTED)
(data / "seed.txt").write_text("seed")
_, probes = runner.run("--preopen", f"{data}::/data::ro")
expect(probes, "data-read", True, contains="seed")
expect(probes, "data-write", False)
if (data / "written.txt").exists():
raise AssertionError("read-only grant allowed a write on the host")
_, probes = runner.run("--preopen", f"{data}::/data::rw")
expect(probes, "data-write", True)
if (data / "written.txt").read_text() != "probe":
raise AssertionError("read-write grant did not write to the host directory")
_, probes = runner.run("--grant", "sys:notifications", "--grant", "sys:clipboard:read")
expect(probes, "notifications", probes.get("notifications", "").startswith("ok"),
absent=NOT_GRANTED)
expect(probes, "clipboard-read", probes.get("clipboard-read", "").startswith("ok"),
absent=NOT_GRANTED)
expect(probes, "clipboard-write", False, contains=NOT_GRANTED)
_, probes = runner.run("--grant", "net:fetch:127.0.0.1")
expect(probes, "fetch-ok", True, contains="200")
expect(probes, "fetch-missing", True, contains="404")
expect(probes, "fetch-redirect", True, contains="302")
expect(probes, "fetch-other-host", False, contains=NOT_GRANTED)
_, probes = runner.run("--grant", "net:fetch:*")
expect(probes, "fetch-other-host", True, contains="200")
for arguments in (["--grant", "fs:rw:app-data"], ["--preopen", f"{data}::/data"],
["--grant", "sys:everything"]):
result, _ = runner.run(*arguments, expect_success=False)
if result.returncode == 0:
raise AssertionError(f"runtime accepted {' '.join(arguments)}")
def main(argv=None):
parser = argparse.ArgumentParser(description=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("--runtime", type=Path, default=ROOT / "target/debug/weft-runtime",
help="weft-runtime built with wasmtime-runtime and net-fetch")
parser.add_argument("--probe", type=Path, help="prebuilt probe component")
args = parser.parse_args(argv)
if not args.runtime.is_file():
print(f"missing: {args.runtime}", file=sys.stderr)
return 2
probe = args.probe or build_probe()
server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler)
threading.Thread(target=server.serve_forever, daemon=True).start()
work = Path(tempfile.mkdtemp(prefix="weft-grants-"))
try:
runner = Runner(args.runtime, work, server.server_port)
shutil.copy(probe, runner.package / "app.wasm")
data = work / "data"
data.mkdir()
check(runner, data)
except AssertionError as failure:
print(f"grants check failed: {failure}", file=sys.stderr)
return 1
finally:
server.shutdown()
shutil.rmtree(work, ignore_errors=True)
print("grants check passed")
return 0
if __name__ == "__main__":
raise SystemExit(main())