fix(runtime): close fetch and preopen gaps in grant enforcement

A component with a host-specific fetch grant could reach another origin
by setting its own Host header, and could inject request lines through
the method string, which ureq writes unvalidated. Fetch now accepts only
standard methods and refuses Host, framing and hop-by-hop headers. Fetch
grants accept canonical DNS names and dotted IPv4 addresses only, so a
grant can never be written in a form that silently never matches.

--preopen split host and guest at the first `::`, so a host path
containing `::` widened the preopened directory; it now splits from the
right, and appd refuses host paths that are not UTF-8 or contain `::`.

appd validated capabilities one at a time, creating the data directory
before a later capability was refused, and required HOME even for
packages without filesystem capabilities. It now checks every capability
first, resolves host directories only when needed, validates the app ID
with the rule weft-pack uses (now shared in weft_ipc_types::package), and
reports 400, 404, 403 or 500 according to the cause. user-dirs.dirs is
read as a shell would: the last assignment wins, $HOME must be followed
by a slash, escaped values are ignored and a relative XDG_CONFIG_HOME is
not used.

The grants probe now also overwrites, renames, removes and creates
directories in read-only data, and sends a forged Host header, an
injected method and a file: URL; it fails when directory permissions of
a read-only preopen are widened or the header check is removed. A new
CI job builds the runtime with its engine and fetch support and runs the
check. The mount test that sets WEFT_APP_STORE now holds the env lock.

Package images are still located separately from directory installs;
deriving grants from the verified image is part of resolving one package
descriptor.
This commit is contained in:
Marco Allegretti 2026-10-09 08:25:40 +00:00
parent c28a829624
commit 51ca194acb
No known key found for this signature in database
16 changed files with 420 additions and 145 deletions

View file

@ -78,6 +78,28 @@ jobs:
-p weft-servo-shell -p weft-servo-shell
-p weft-app-shell -p weft-app-shell
# weft-runtime with its Wasm engine and fetch support, exercised on a real
# component under each kind of capability grant.
runtime-grants:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: dtolnay/rust-toolchain@stable
with:
toolchain: 1.93.0
components: clippy
targets: wasm32-wasip2
- name: cargo clippy (weft-runtime with wasmtime-runtime and net-fetch)
run: >
cargo clippy
-p weft-runtime
--features wasmtime-runtime,net-fetch
--all-targets -- -D warnings
- name: cargo build (weft-runtime with wasmtime-runtime and net-fetch)
run: cargo build -p weft-runtime --features wasmtime-runtime,net-fetch
- name: grants check
run: python3 -B tests/runtime/check_grants.py
# Type-check the servo-embed feature gate. # Type-check the servo-embed feature gate.
# Full Servo compilation (30-60 min) is not run in CI; this job checks # Full Servo compilation (30-60 min) is not run in CI; this job checks
# that the feature-gated code at least type-checks against the declared deps. # that the feature-gated code at least type-checks against the declared deps.

View file

@ -75,10 +75,11 @@ See `docs/building.md` for full instructions including Wasm component builds, Ni
## CI ## CI
Three jobs on every push and pull request: Jobs on every push and pull request:
- `cross-platform` — fmt, clippy, tests on Ubuntu and Windows - `cross-platform` — fmt, clippy, tests on Ubuntu and Windows
- `linux-only` — clippy and tests for compositor and shell crates - `linux-only` — clippy and tests for compositor and shell crates
- `runtime-grants` — clippy for `weft-runtime` with its Wasm engine and fetch, and `tests/runtime/check_grants.py`
- `servo-embed-linux` — `cargo check --features servo-embed` for both servo crates - `servo-embed-linux` — `cargo check --features servo-embed` for both servo crates
## Security ## Security

View file

@ -35,6 +35,25 @@ pub(crate) struct SessionGrants {
pub imports: Vec<Capability>, pub imports: Vec<Capability>,
} }
/// Why a launch is refused, with the error code reported to the client:
/// 400 for a malformed app ID, 404 for a package that is not installed, 403
/// for a package this host will not run as declared and 500 for a host
/// fault.
#[derive(Debug, PartialEq, Eq)]
pub(crate) struct Refusal {
pub code: u32,
pub message: String,
}
impl Refusal {
fn new(code: u32, message: impl Into<String>) -> Self {
Self {
code,
message: message.into(),
}
}
}
/// Where the host resources behind filesystem capabilities live. /// Where the host resources behind filesystem capabilities live.
pub(crate) struct HostDirs { pub(crate) struct HostDirs {
/// Root under which each app's private data directory is created. /// Root under which each app's private data directory is created.
@ -44,12 +63,15 @@ pub(crate) struct HostDirs {
} }
impl HostDirs { impl HostDirs {
pub fn from_env() -> Result<Self, String> { pub fn from_env() -> Result<Self, Refusal> {
let home = std::env::var_os("HOME") let home = std::env::var_os("HOME")
.map(PathBuf::from) .map(PathBuf::from)
.ok_or("HOME is not set")?; .filter(|home| home.is_absolute())
.ok_or_else(|| Refusal::new(500, "HOME is not set to an absolute path"))?;
// The XDG base directory specification ignores relative values.
let config = std::env::var_os("XDG_CONFIG_HOME") let config = std::env::var_os("XDG_CONFIG_HOME")
.map(PathBuf::from) .map(PathBuf::from)
.filter(|dir| dir.is_absolute())
.unwrap_or_else(|| home.join(".config")); .unwrap_or_else(|| home.join(".config"));
Ok(Self { Ok(Self {
app_data_root: home.join(".local/share/weft/apps"), app_data_root: home.join(".local/share/weft/apps"),
@ -59,7 +81,7 @@ impl HostDirs {
} }
/// Reads the package manifest of `app_id` and derives its grants. /// Reads the package manifest of `app_id` and derives its grants.
pub(crate) fn for_app(app_id: &str) -> Result<SessionGrants, String> { pub(crate) fn for_app(app_id: &str) -> Result<SessionGrants, Refusal> {
#[derive(serde::Deserialize)] #[derive(serde::Deserialize)]
struct Package { struct Package {
capabilities: Option<Vec<String>>, capabilities: Option<Vec<String>>,
@ -69,61 +91,98 @@ pub(crate) fn for_app(app_id: &str) -> Result<SessionGrants, String> {
package: Package, package: Package,
} }
if !weft_ipc_types::package::is_valid_app_id(app_id) {
return Err(Refusal::new(400, "invalid app ID"));
}
let manifest = crate::app_store_roots() let manifest = crate::app_store_roots()
.into_iter() .into_iter()
.map(|root| root.join(app_id).join("wapp.toml")) .map(|root| root.join(app_id).join("wapp.toml"))
.find(|path| path.exists()) .find(|path| path.exists())
.ok_or_else(|| format!("package {app_id} is not installed"))?; .ok_or_else(|| Refusal::new(404, format!("package {app_id} is not installed")))?;
let text = std::fs::read_to_string(&manifest) let text = std::fs::read_to_string(&manifest)
.map_err(|e| format!("cannot read {}: {e}", manifest.display()))?; .map_err(|e| Refusal::new(500, format!("cannot read {}: {e}", manifest.display())))?;
let manifest: Manifest = let manifest: Manifest = toml::from_str(&text)
toml::from_str(&text).map_err(|e| format!("invalid {}: {e}", manifest.display()))?; .map_err(|e| Refusal::new(403, format!("invalid {}: {e}", manifest.display())))?;
let declared = manifest.package.capabilities.unwrap_or_default(); let declared = manifest.package.capabilities.unwrap_or_default();
derive(app_id, &declared, &HostDirs::from_env()?) derive(app_id, &declared, HostDirs::from_env)
} }
/// Derives grants for the declared capabilities. Creates the app's private /// Derives grants for the declared capabilities. Every capability is
/// data directory when a data capability is declared. /// checked before host directories are resolved or the app's data
/// directory is created, so a refused launch leaves nothing behind.
pub(crate) fn derive( pub(crate) fn derive(
app_id: &str, app_id: &str,
declared: &[String], declared: &[String],
host: &HostDirs, host_dirs: impl FnOnce() -> Result<HostDirs, Refusal>,
) -> Result<SessionGrants, String> { ) -> Result<SessionGrants, Refusal> {
let mut grants = SessionGrants::default(); let mut capabilities = Vec::new();
for text in declared { for text in declared {
let capability: Capability = text.parse().map_err(|e| format!("{e}"))?; let capability: Capability =
match capability { text.parse()
Capability::AppData(access) => { .map_err(|e: weft_ipc_types::capability::UnknownCapability| {
let dir = host.app_data_root.join(app_id).join("data"); Refusal::new(403, e.to_string())
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); if matches!(capability, Capability::GpuCompute | Capability::GpuRender) {
return Err(Refusal::new(
403,
format!("{capability} is not supported by this host"),
));
}
capabilities.push(capability);
}
let mut grants = SessionGrants::default();
let needs_dirs = capabilities
.iter()
.any(|c| matches!(c, Capability::AppData(_) | Capability::Documents(_)));
let host = if needs_dirs { Some(host_dirs()?) } else { None };
for capability in capabilities {
match (&capability, &host) {
(Capability::AppData(access), Some(host)) => {
let dir = host.app_data_root.join(app_id).join("data");
grant_dir(&mut grants, dir, "/data", *access)?;
} }
Capability::Fetch(_) (Capability::Documents(access), Some(host)) => {
| Capability::Notifications let dir = host.documents.clone().ok_or_else(|| {
| Capability::ClipboardRead Refusal::new(
| Capability::ClipboardWrite => { 403,
format!("{capability} requested, but no documents directory is configured"),
)
})?;
grant_dir(&mut grants, dir, "/xdg/documents", *access)?;
}
_ => {
if !grants.imports.contains(&capability) { if !grants.imports.contains(&capability) {
grants.imports.push(capability); grants.imports.push(capability);
} }
} }
Capability::GpuCompute | Capability::GpuRender => { }
return Err(format!("{capability} is not supported by this host")); }
} for dir in &grants.dirs {
if dir.guest == "/data" {
std::fs::create_dir_all(&dir.host).map_err(|e| {
Refusal::new(500, format!("cannot create {}: {e}", dir.host.display()))
})?;
} }
} }
Ok(grants) Ok(grants)
} }
/// Adds a directory grant; declaring both modes for one directory grants the /// Adds a directory grant; declaring both modes for one directory grants the
/// wider one. /// wider one. The host path must survive the `--preopen HOST::GUEST::MODE`
fn grant_dir(grants: &mut SessionGrants, host: PathBuf, guest: &'static str, access: Access) { /// encoding unchanged: it must be UTF-8 and must not contain `::`.
fn grant_dir(
grants: &mut SessionGrants,
host: PathBuf,
guest: &'static str,
access: Access,
) -> Result<(), Refusal> {
if host.to_str().is_none_or(|path| path.contains("::")) {
return Err(Refusal::new(
403,
format!("{} cannot be granted to a session", host.display()),
));
}
match grants.dirs.iter_mut().find(|dir| dir.guest == guest) { match grants.dirs.iter_mut().find(|dir| dir.guest == guest) {
Some(existing) => { Some(existing) => {
if access == Access::ReadWrite { if access == Access::ReadWrite {
@ -136,21 +195,29 @@ fn grant_dir(grants: &mut SessionGrants, host: PathBuf, guest: &'static str, acc
access, access,
}), }),
} }
Ok(())
} }
/// The documents directory from the XDG user directories configuration /// The documents directory from the XDG user directories configuration
/// (`user-dirs.dirs`), or None when it is not configured, is disabled (set /// (`user-dirs.dirs`), or None when it is not configured, is disabled (set
/// to the home directory) or does not exist. /// to the home directory) or does not exist. Values are `"$HOME/path"` or
/// `"/absolute/path"`; the last assignment wins, as when the file is sourced
/// by a shell. Values with escapes are not interpreted and are ignored.
fn documents_dir(home: &Path, config: &Path) -> Option<PathBuf> { fn documents_dir(home: &Path, config: &Path) -> Option<PathBuf> {
let text = std::fs::read_to_string(config.join("user-dirs.dirs")).ok()?; let text = std::fs::read_to_string(config.join("user-dirs.dirs")).ok()?;
let value = text.lines().find_map(|line| { let value = text
line.trim() .lines()
.strip_prefix("XDG_DOCUMENTS_DIR=") .filter_map(|line| line.trim().strip_prefix("XDG_DOCUMENTS_DIR="))
.map(|v| v.trim().trim_matches('"').to_owned()) .next_back()?
})?; .trim();
let value = value.strip_prefix('"')?.strip_suffix('"')?;
if value.contains('\\') || value.contains('"') {
return None;
}
let dir = match value.strip_prefix("$HOME") { let dir = match value.strip_prefix("$HOME") {
Some(rest) => home.join(rest.trim_start_matches('/')), Some("") => home.to_path_buf(),
None => PathBuf::from(&value), Some(rest) => home.join(rest.strip_prefix('/')?),
None => PathBuf::from(value),
}; };
(dir.is_absolute() && dir != home && dir.is_dir()).then_some(dir) (dir.is_absolute() && dir != home && dir.is_dir()).then_some(dir)
} }
@ -166,22 +233,36 @@ mod tests {
dir dir
} }
fn host(root: &Path, documents: Option<PathBuf>) -> HostDirs { fn host(root: &Path, documents: Option<PathBuf>) -> impl FnOnce() -> Result<HostDirs, Refusal> {
HostDirs { let root = root.to_path_buf();
app_data_root: root.join("apps"), move || {
documents, Ok(HostDirs {
app_data_root: root.join("apps"),
documents,
})
} }
} }
fn no_host() -> Result<HostDirs, Refusal> {
Err(Refusal::new(500, "HOME is not set to an absolute path"))
}
fn caps(list: &[&str]) -> Vec<String> { fn caps(list: &[&str]) -> Vec<String> {
list.iter().map(|s| s.to_string()).collect() list.iter().map(|s| s.to_string()).collect()
} }
#[test] #[test]
fn no_capabilities_grant_nothing() { fn no_capabilities_grant_nothing_and_need_no_home() {
let root = temp("none"); let grants = derive("org.example.app", &[], no_host).unwrap();
let grants = derive("org.example.app", &[], &host(&root, None)).unwrap();
assert_eq!(grants, SessionGrants::default()); assert_eq!(grants, SessionGrants::default());
let grants = derive("org.example.app", &caps(&["sys:notifications"]), no_host).unwrap();
assert_eq!(grants.imports, [Capability::Notifications]);
assert_eq!(
derive("org.example.app", &caps(&["fs:rw:app-data"]), no_host)
.unwrap_err()
.code,
500
);
} }
#[test] #[test]
@ -190,7 +271,7 @@ mod tests {
let read = derive( let read = derive(
"org.example.app", "org.example.app",
&caps(&["fs:read:app-data"]), &caps(&["fs:read:app-data"]),
&host(&root, None), host(&root, None),
) )
.unwrap(); .unwrap();
assert_eq!(read.dirs[0].access, Access::Read); assert_eq!(read.dirs[0].access, Access::Read);
@ -200,7 +281,7 @@ mod tests {
let both = derive( let both = derive(
"org.example.app", "org.example.app",
&caps(&["fs:read:app-data", "fs:rw:app-data"]), &caps(&["fs:read:app-data", "fs:rw:app-data"]),
&host(&root, None), host(&root, None),
) )
.unwrap(); .unwrap();
assert_eq!(both.dirs.len(), 1); assert_eq!(both.dirs.len(), 1);
@ -217,7 +298,7 @@ mod tests {
"net:fetch:api.example.org", "net:fetch:api.example.org",
"sys:notifications", "sys:notifications",
]), ]),
&host(&root, None), host(&root, None),
) )
.unwrap(); .unwrap();
let listed: Vec<String> = grants.imports.iter().map(|c| c.to_string()).collect(); let listed: Vec<String> = grants.imports.iter().map(|c| c.to_string()).collect();
@ -226,14 +307,34 @@ mod tests {
} }
#[test] #[test]
fn unknown_unsupported_and_unsatisfiable_capabilities_fail() { fn refused_launches_create_nothing() {
let root = temp("fail"); let root = temp("fail");
for declared in ["sys:everything", "hw:gpu:compute", "fs:read:xdg-documents"] { for declared in [
assert!( &["sys:everything"][..],
derive("org.example.app", &caps(&[declared]), &host(&root, None)).is_err(), &["hw:gpu:compute"],
"{declared} accepted" &["fs:read:xdg-documents"],
); &["fs:rw:app-data", "hw:gpu:render"],
&["fs:rw:app-data", "fs:read:xdg-documents"],
] {
let refusal =
derive("org.example.app", &caps(declared), host(&root, None)).unwrap_err();
assert_eq!(refusal.code, 403, "{declared:?}");
} }
assert!(!root.join("apps").exists());
}
#[test]
fn paths_that_cannot_be_encoded_are_refused() {
let root = temp("encode");
let odd = root.join("a::b");
std::fs::create_dir_all(&odd).unwrap();
let refusal = derive(
"org.example.app",
&caps(&["fs:read:xdg-documents"]),
host(&root, Some(odd)),
)
.unwrap_err();
assert_eq!(refusal.code, 403);
} }
#[test] #[test]
@ -241,34 +342,37 @@ mod tests {
let home = temp("home"); let home = temp("home");
let config = home.join(".config"); let config = home.join(".config");
std::fs::create_dir_all(home.join("Docs")).unwrap(); std::fs::create_dir_all(home.join("Docs")).unwrap();
std::fs::create_dir_all(home.join("Later")).unwrap();
std::fs::create_dir_all(&config).unwrap(); std::fs::create_dir_all(&config).unwrap();
assert_eq!(documents_dir(&home, &config), None); assert_eq!(documents_dir(&home, &config), None);
std::fs::write( let write = |text: &str| std::fs::write(config.join("user-dirs.dirs"), text).unwrap();
config.join("user-dirs.dirs"), write("# comment\nXDG_DOCUMENTS_DIR=\"$HOME/Docs\"\n");
"# comment\nXDG_DOCUMENTS_DIR=\"$HOME/Docs\"\n", assert_eq!(documents_dir(&home, &config), Some(home.join("Docs")));
) write("XDG_DOCUMENTS_DIR=\"$HOME/Docs\"\nXDG_DOCUMENTS_DIR=\"$HOME/Later\"\n");
.unwrap(); assert_eq!(documents_dir(&home, &config), Some(home.join("Later")));
let absolute = format!("XDG_DOCUMENTS_DIR=\"{}\"\n", home.join("Docs").display());
write(&absolute);
assert_eq!(documents_dir(&home, &config), Some(home.join("Docs"))); assert_eq!(documents_dir(&home, &config), Some(home.join("Docs")));
// Disabled (the home directory itself) and missing directories. // Disabled, missing, relative, escaped and malformed values.
std::fs::write( for text in [
config.join("user-dirs.dirs"),
"XDG_DOCUMENTS_DIR=\"$HOME/\"\n", "XDG_DOCUMENTS_DIR=\"$HOME/\"\n",
) "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", "XDG_DOCUMENTS_DIR=\"$HOME/Missing\"\n",
) "XDG_DOCUMENTS_DIR=\"$HOMEDocs\"\n",
.unwrap(); "XDG_DOCUMENTS_DIR=\"Docs\"\n",
assert_eq!(documents_dir(&home, &config), None); "XDG_DOCUMENTS_DIR=\"$HOME/Do\\\"cs\"\n",
"XDG_DOCUMENTS_DIR=$HOME/Docs\n",
] {
write(text);
assert_eq!(documents_dir(&home, &config), None, "{text:?}");
}
let grants = derive( let grants = derive(
"org.example.app", "org.example.app",
&caps(&["fs:rw:xdg-documents"]), &caps(&["fs:rw:xdg-documents"]),
&host(&home, Some(home.join("Docs"))), host(&home, Some(home.join("Docs"))),
) )
.unwrap(); .unwrap();
assert_eq!(grants.dirs[0].guest, "/xdg/documents"); assert_eq!(grants.dirs[0].guest, "/xdg/documents");

View file

@ -427,19 +427,25 @@ pub(crate) async fn dispatch(req: Request, registry: &Registry) -> Response {
} => { } => {
// The package's capabilities are granted before a session exists; // The package's capabilities are granted before a session exists;
// a package this host cannot satisfy is refused, not started. // a package this host cannot satisfy is refused, not started.
let grants = if std::env::var("WEFT_RUNTIME_BIN").is_ok() { let grants = if !weft_ipc_types::package::is_valid_app_id(&app_id) {
match grants::for_app(&app_id) { Err(grants::Refusal {
Ok(grants) => grants, code: 400,
Err(message) => { message: "invalid app ID".to_owned(),
tracing::warn!(%app_id, error = %message, "launch refused"); })
return Response::Error { } else if std::env::var("WEFT_RUNTIME_BIN").is_ok() {
code: 403, grants::for_app(&app_id)
message: format!("{app_id}: {message}"),
};
}
}
} else { } else {
grants::SessionGrants::default() Ok(grants::SessionGrants::default())
};
let grants = match grants {
Ok(grants) => grants,
Err(refusal) => {
tracing::warn!(%app_id, error = %refusal.message, "launch refused");
return Response::Error {
code: refusal.code,
message: format!("{app_id}: {}", refusal.message),
};
}
}; };
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");
@ -628,7 +634,7 @@ mod tests {
static ENV_LOCK: std::sync::OnceLock<tokio::sync::Mutex<()>> = std::sync::OnceLock::new(); static ENV_LOCK: std::sync::OnceLock<tokio::sync::Mutex<()>> = std::sync::OnceLock::new();
fn env_lock() -> &'static tokio::sync::Mutex<()> { pub(crate) fn env_lock() -> &'static tokio::sync::Mutex<()> {
ENV_LOCK.get_or_init(|| tokio::sync::Mutex::new(())) ENV_LOCK.get_or_init(|| tokio::sync::Mutex::new(()))
} }
@ -789,7 +795,7 @@ mod tests {
let reg = make_registry(); let reg = make_registry();
let ack = dispatch( let ack = dispatch(
Request::LaunchApp { Request::LaunchApp {
app_id: "app".into(), app_id: "com.test.app".into(),
surface_id: 0, surface_id: 0,
}, },
&reg, &reg,

View file

@ -108,6 +108,7 @@ mod tests {
#[test] #[test]
fn find_image_returns_none_when_absent() { fn find_image_returns_none_when_absent() {
let _env = crate::tests::env_lock().blocking_lock();
unsafe { std::env::set_var("WEFT_APP_STORE", "/tmp/nonexistent_weft_store_xyz") }; unsafe { std::env::set_var("WEFT_APP_STORE", "/tmp/nonexistent_weft_store_xyz") };
let result = find_image("com.example.missing"); let result = find_image("com.example.missing");
unsafe { std::env::remove_var("WEFT_APP_STORE") }; unsafe { std::env::remove_var("WEFT_APP_STORE") };

View file

@ -101,11 +101,22 @@ impl fmt::Display for Capability {
} }
} }
/// A DNS host name in canonical lowercase form: dot-separated labels of /// A host in the canonical form URL parsing produces, so that a grant can
/// 1–63 letters, digits and inner hyphens, at most 253 characters. /// be compared with a request's host as a string: a lowercase DNS name of
/// 1–63 character labels of letters, digits and inner hyphens (at most 253
/// characters) whose last label is not numeric, or an IPv4 address in
/// dotted-decimal form without leading zeros. IPv6 literals are not
/// supported.
fn is_host_name(host: &str) -> bool { fn is_host_name(host: &str) -> bool {
let labels: Vec<&str> = host.split('.').collect();
if labels
.last()
.is_some_and(|last| !last.is_empty() && last.bytes().all(|b| b.is_ascii_digit()))
{
return is_ipv4(&labels);
}
host.len() <= 253 host.len() <= 253
&& host.split('.').all(|label| { && labels.iter().all(|label| {
!label.is_empty() !label.is_empty()
&& label.len() <= 63 && label.len() <= 63
&& !label.starts_with('-') && !label.starts_with('-')
@ -116,6 +127,17 @@ fn is_host_name(host: &str) -> bool {
}) })
} }
fn is_ipv4(labels: &[&str]) -> bool {
labels.len() == 4
&& labels.iter().all(|octet| {
!octet.is_empty()
&& octet.len() <= 3
&& (octet.len() == 1 || !octet.starts_with('0'))
&& octet.bytes().all(|b| b.is_ascii_digit())
&& octet.parse::<u16>().is_ok_and(|n| n <= 255)
})
}
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
@ -129,6 +151,8 @@ mod tests {
"fs:rw:xdg-documents", "fs:rw:xdg-documents",
"net:fetch:*", "net:fetch:*",
"net:fetch:api.example.org", "net:fetch:api.example.org",
"net:fetch:127.0.0.1",
"net:fetch:a1.example",
"sys:notifications", "sys:notifications",
"sys:clipboard:read", "sys:clipboard:read",
"sys:clipboard:write", "sys:clipboard:write",
@ -153,6 +177,11 @@ mod tests {
"net:fetch:*.example.org", "net:fetch:*.example.org",
"net:fetch:-bad.example", "net:fetch:-bad.example",
"net:fetch:a..b", "net:fetch:a..b",
"net:fetch:0177.0.0.1",
"net:fetch:999.1.1.1",
"net:fetch:1.2.3",
"net:fetch:example.123",
"net:fetch:[::1]",
"sys:clipboard", "sys:clipboard",
] { ] {
assert!(text.parse::<Capability>().is_err(), "{text:?} accepted"); assert!(text.parse::<Capability>().is_err(), "{text:?} accepted");

View file

@ -1,4 +1,5 @@
pub mod capability; pub mod capability;
pub mod package;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};

View file

@ -0,0 +1,37 @@
//! Package identity rules shared by the packaging tool and the supervisor.
/// Whether `id` is a valid application ID: at least three dot-separated
/// segments, each starting with a lowercase ASCII letter and containing only
/// lowercase ASCII letters and digits. A valid ID is safe to use as a single
/// path component.
pub fn is_valid_app_id(id: &str) -> bool {
let parts: Vec<&str> = id.split('.').collect();
parts.len() >= 3
&& parts.iter().all(|p| {
p.chars().next().is_some_and(|c| c.is_ascii_lowercase())
&& p.chars()
.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit())
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn app_ids() {
assert!(is_valid_app_id("org.weft.demo"));
assert!(is_valid_app_id("com.example2.app3"));
for bad in [
"",
"org.weft",
"Org.weft.demo",
"org..demo",
"../x.y.z",
"org.weft.a::b",
"org.1weft.demo",
] {
assert!(!is_valid_app_id(bad), "{bad:?}");
}
}
}

View file

@ -155,7 +155,7 @@ fn check_package(dir: &Path) -> anyhow::Result<String> {
}; };
if let Some(ref m) = manifest { if let Some(ref m) = manifest {
if !is_valid_app_id(&m.package.id) { if !weft_ipc_types::package::is_valid_app_id(&m.package.id) {
errors.push(format!( errors.push(format!(
"package.id '{}' does not match required pattern", "package.id '{}' does not match required pattern",
m.package.id m.package.id
@ -229,22 +229,6 @@ fn print_info(m: &Manifest) {
} }
} }
fn is_valid_app_id(id: &str) -> bool {
let parts: Vec<&str> = id.split('.').collect();
if parts.len() < 3 {
return false;
}
parts.iter().all(|p| {
!p.is_empty()
&& p.chars()
.next()
.map(|c| c.is_ascii_lowercase())
.unwrap_or(false)
&& p.chars()
.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit())
})
}
fn is_wasm_module(path: &Path) -> bool { fn is_wasm_module(path: &Path) -> bool {
const MAGIC: [u8; 4] = [0x00, 0x61, 0x73, 0x6D]; const MAGIC: [u8; 4] = [0x00, 0x61, 0x73, 0x6D];
let mut buf = [0u8; 4]; let mut buf = [0u8; 4];
@ -327,7 +311,7 @@ fn uninstall_package(app_id: &str) -> anyhow::Result<()> {
} }
fn uninstall_package_from(app_id: &str, store_root: &Path) -> anyhow::Result<()> { fn uninstall_package_from(app_id: &str, store_root: &Path) -> anyhow::Result<()> {
if !is_valid_app_id(app_id) { if !weft_ipc_types::package::is_valid_app_id(app_id) {
anyhow::bail!("'{}' is not a valid app ID", app_id); anyhow::bail!("'{}' is not a valid app ID", app_id);
} }
let target = store_root.join(app_id); let target = store_root.join(app_id);
@ -611,19 +595,33 @@ mod tests {
#[test] #[test]
fn app_id_valid() { fn app_id_valid() {
assert!(is_valid_app_id("com.example.notes")); assert!(weft_ipc_types::package::is_valid_app_id(
assert!(is_valid_app_id("org.weft.calculator")); "com.example.notes"
assert!(is_valid_app_id("io.github.username.app")); ));
assert!(weft_ipc_types::package::is_valid_app_id(
"org.weft.calculator"
));
assert!(weft_ipc_types::package::is_valid_app_id(
"io.github.username.app"
));
} }
#[test] #[test]
fn app_id_invalid() { fn app_id_invalid() {
assert!(!is_valid_app_id("com.example")); assert!(!weft_ipc_types::package::is_valid_app_id("com.example"));
assert!(!is_valid_app_id("Com.example.notes")); assert!(!weft_ipc_types::package::is_valid_app_id(
assert!(!is_valid_app_id("com.example.notes-app")); "Com.example.notes"
assert!(!is_valid_app_id("com..example.notes")); ));
assert!(!is_valid_app_id("")); assert!(!weft_ipc_types::package::is_valid_app_id(
assert!(!is_valid_app_id("com.Example.notes")); "com.example.notes-app"
));
assert!(!weft_ipc_types::package::is_valid_app_id(
"com..example.notes"
));
assert!(!weft_ipc_types::package::is_valid_app_id(""));
assert!(!weft_ipc_types::package::is_valid_app_id(
"com.Example.notes"
));
} }
#[test] #[test]

View file

@ -93,8 +93,10 @@ impl Preopen {
let (rest, mode) = spec let (rest, mode) = spec
.rsplit_once("::") .rsplit_once("::")
.context("--preopen expects HOST::GUEST::ro|rw")?; .context("--preopen expects HOST::GUEST::ro|rw")?;
// Guest paths are fixed names without `::`; splitting from the right
// keeps a host path containing `::` whole.
let (host, guest) = rest let (host, guest) = rest
.split_once("::") .rsplit_once("::")
.context("--preopen expects HOST::GUEST::ro|rw")?; .context("--preopen expects HOST::GUEST::ro|rw")?;
let access = match mode { let access = match mode {
"ro" => Access::Read, "ro" => Access::Read,
@ -166,6 +168,7 @@ mod tests {
Preopen::parse("/a::/b::rw").unwrap().access, Preopen::parse("/a::/b::rw").unwrap().access,
Access::ReadWrite Access::ReadWrite
); );
assert_eq!(Preopen::parse("/a::/b::/data::ro").unwrap().host, "/a::/b");
for bad in ["/a::/b", "/a", "/a::/b::wx", "::/b::ro", "/a::b::ro"] { for bad in ["/a::/b", "/a", "/a::/b::wx", "::/b::ro", "/a::b::ro"] {
assert!(Preopen::parse(bad).is_err(), "{bad} accepted"); assert!(Preopen::parse(bad).is_err(), "{bad} accepted");
} }

View file

@ -385,6 +385,21 @@ struct FetchResponse {
#[cfg(feature = "wasmtime-runtime")] #[cfg(feature = "wasmtime-runtime")]
type FetchResult = Result<FetchResponse, String>; type FetchResult = Result<FetchResponse, String>;
/// Request headers a component may not set.
#[cfg(all(feature = "wasmtime-runtime", feature = "net-fetch"))]
const FORBIDDEN_FETCH_HEADERS: &[&str] = &[
"host",
"content-length",
"transfer-encoding",
"connection",
"keep-alive",
"proxy-authorization",
"proxy-connection",
"te",
"trailer",
"upgrade",
];
/// Longest response body returned to a component. /// Longest response body returned to a component.
#[cfg(all(feature = "wasmtime-runtime", feature = "net-fetch"))] #[cfg(all(feature = "wasmtime-runtime", feature = "net-fetch"))]
const MAX_FETCH_RESPONSE: u64 = 16 * 1024 * 1024; const MAX_FETCH_RESPONSE: u64 = 16 * 1024 * 1024;
@ -410,6 +425,25 @@ fn host_fetch(
} }
let host = parsed.host_str().ok_or("URL has no host")?; let host = parsed.host_str().ok_or("URL has no host")?;
grants.fetch_host(host)?; grants.fetch_host(host)?;
// The method is written into the request line as given, so only known
// methods are accepted.
if !matches!(
method,
"GET" | "HEAD" | "POST" | "PUT" | "PATCH" | "DELETE" | "OPTIONS"
) {
return Err(format!("unsupported HTTP method '{method}'"));
}
// The destination and message framing belong to the runtime: a component
// must not redirect a granted request to another host through `Host` or
// change how the body is delimited.
for (name, _) in headers {
if FORBIDDEN_FETCH_HEADERS
.iter()
.any(|forbidden| name.eq_ignore_ascii_case(forbidden))
{
return Err(format!("header '{name}' is set by the runtime"));
}
}
let agent = ureq::AgentBuilder::new() let agent = ureq::AgentBuilder::new()
.redirects(0) .redirects(0)
.timeout_connect(Duration::from_secs(10)) .timeout_connect(Duration::from_secs(10))

View file

@ -21,8 +21,8 @@ interface ipc {
recv: func() -> option<string>; recv: func() -> option<string>;
} }
/// Host interface for outbound HTTP requests. Requires the net:fetch /// Host interface for outbound HTTP requests. Requires a net:fetch:<host>
/// capability to be declared in wapp.toml. /// or net:fetch:* capability in wapp.toml covering the request's host.
interface fetch { interface fetch {
record response { record response {
status: u16, status: u16,

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 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. 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. Paths are checked lexically, so `..` is blocked but symbolic links are followed. Accepts JSON-lines requests over a Unix socket. Components cannot currently reach that socket, because the runtime grants them no socket access.
### weft-mount-helper ### weft-mount-helper
@ -71,24 +71,26 @@ Every WebSocket connection must complete the upgrade and send `HELLO` as its fir
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. 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: `weft-appd` derives grants once, before a session exists. `LAUNCH_APP` is answered with an error and nothing starts when the app ID is malformed (code 400), the package is not installed (404), a declared capability is unknown, unsupported on this host or cannot be satisfied (403), or the host cannot provide the resources (500, for example without `HOME`). All capabilities are checked before the app's data directory is created. Without `WEFT_RUNTIME_BIN`, appd starts no processes and derives no grants. 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; - `--preopen HOST::GUEST::ro|rw` for each directory, with the access mode the capability names;
- `--grant <capability>` for each host-import capability. - `--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. Each capability-controlled host import (fetch, notifications, clipboard) checks its grant on every call and returns an error naming the missing capability when it is not granted. `notify` and `ipc` need no capability.
| Capability | Effect | | Capability | Effect |
|---|---| |---|---|
| `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` / `fs:rw:app-data` | Preopen `~/.local/share/weft/apps/<id>/data` as `/data`, read-only or read-write |
| `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: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 |
| `net:fetch:<host>` | `weft:app/fetch` to that exact host over HTTP or HTTPS | | `net:fetch:<host>` | `weft:app/fetch` to that exact host (a lowercase DNS name or dotted IPv4 address) over HTTP or HTTPS, on any port |
| `net:fetch:*` | `weft:app/fetch` to any host | | `net:fetch:*` | `weft:app/fetch` to any host |
| `sys:notifications` | `weft:app/notifications` | | `sys:notifications` | `weft:app/notifications` |
| `sys:clipboard:read` / `sys:clipboard:write` | `weft:app/clipboard#read` / `#write` | | `sys:clipboard:read` / `sys:clipboard:write` | `weft:app/clipboard#read` / `#write` |
| `hw:gpu:compute` / `hw:gpu:render` | Not supported; the launch fails | | `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. 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. Only the methods GET, HEAD, POST, PUT, PATCH, DELETE and OPTIONS are accepted, and a component cannot set `Host`, `Content-Length`, `Transfer-Encoding` or other hop-by-hop headers. Connecting times out after 10 seconds and the whole request after 30 seconds, not counting DNS resolution; response bodies are limited to 16 MiB. Fetch requires a runtime built with the `net-fetch` feature.
Fetch grants name hosts, not addresses: ports are not restricted, and a host that resolves to a loopback or private address (or `net:fetch:*`) can reach local services. IPv6 literals cannot be granted.
`tests/runtime/check_grants.py` runs the real runtime on a probe component (`tests/components/grants-probe`) under each kind of grant. `tests/runtime/check_grants.py` runs the real runtime on a probe component (`tests/components/grants-probe`) under each kind of grant.

View file

@ -122,8 +122,9 @@ See `infra/nixos/weft-packages.nix` for the package derivations. Its `outputHash
## CI ## CI
Three jobs run on every push to `main` and on pull requests: Jobs run on every push to `main` and on pull requests:
- `cross-platform` — fmt, clippy, tests on Ubuntu and Windows (excludes Wayland crates) - `cross-platform` — fmt, clippy, tests on Ubuntu and Windows (excludes Wayland crates)
- `linux-only` — clippy and tests for `weft-compositor`, `weft-servo-shell`, `weft-app-shell` - `linux-only` — clippy and tests for `weft-compositor`, `weft-servo-shell`, `weft-app-shell`
- `runtime-grants` — clippy and a build of `weft-runtime` with `wasmtime-runtime,net-fetch`, then `tests/runtime/check_grants.py`, which runs a probe component under each kind of capability grant
- `servo-embed-linux` — `cargo check --features servo-embed` for servo-shell and app-shell - `servo-embed-linux` — `cargo check --features servo-embed` for servo-shell and app-shell

View file

@ -4,7 +4,8 @@
//! //!
//! Fetch targets are read from `/probe/targets.txt` (`<name> <url>` per //! Fetch targets are read from `/probe/targets.txt` (`<name> <url>` per
//! line), a directory the harness preopens read-only next to the grants //! line), a directory the harness preopens read-only next to the grants
//! under test. //! under test. The target named `fetch-ok` is also requested with a forged
//! `Host` header and with a method carrying a second request line.
wit_bindgen::generate!({ wit_bindgen::generate!({
path: "wit", path: "wit",
@ -24,12 +25,33 @@ fn report<T: std::fmt::Debug, E: std::fmt::Display>(name: &str, result: Result<T
fn main() { fn main() {
report("data-read", std::fs::read_to_string("/data/seed.txt")); report("data-read", std::fs::read_to_string("/data/seed.txt"));
report("data-write", std::fs::write("/data/written.txt", "probe")); report("data-write", std::fs::write("/data/written.txt", "probe"));
report("data-overwrite", std::fs::write("/data/seed.txt", "changed"));
report("data-mkdir", std::fs::create_dir("/data/made"));
report("data-rename", std::fs::rename("/data/seed.txt", "/data/moved.txt"));
report("data-remove", std::fs::remove_file("/data/seed.txt"));
report("notifications", notifications::notify("probe", "probe", None)); report("notifications", notifications::notify("probe", "probe", None));
report("clipboard-read", clipboard::read()); report("clipboard-read", clipboard::read());
report("clipboard-write", clipboard::write("probe")); report("clipboard-write", clipboard::write("probe"));
let targets = std::fs::read_to_string("/probe/targets.txt").unwrap_or_default(); 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(' ')) { for (name, url) in targets.lines().filter_map(|line| line.split_once(' ')) {
report(name, fetch::fetch(url, "GET", &[], None).map(|r| r.status)); report(name, fetch::fetch(url, "GET", &[], None).map(|r| r.status));
if name == "fetch-ok" {
let forged = [("Host".to_owned(), "localhost".to_owned())];
report(
"fetch-host-header",
fetch::fetch(url, "GET", &forged, None).map(|r| r.status),
);
report(
"fetch-bad-method",
fetch::fetch(url, "GET / HTTP/1.1\r\nHost: localhost\r\n\r\nGET", &[], None)
.map(|r| r.status),
);
}
} }
report(
"fetch-file-scheme",
fetch::fetch("file:///etc/hostname", "GET", &[], None).map(|r| r.status),
);
notify::ready(); notify::ready();
} }

View file

@ -7,19 +7,22 @@ scenario passes a different set of `--grant` and `--preopen` arguments:
- no grants: no /data, and every host import reports that its capability - no grants: no /data, and every host import reports that its capability
is not granted; is not granted;
- read-only data: /data can be read but not written, and nothing appears - read-only data: /data can be read, but creating, overwriting, renaming
on the host; and removing files and creating directories all fail and the host
directory is unchanged;
- read-write data: the write reaches the host directory; - read-write data: the write reaches the host directory;
- notifications and clipboard read: those imports are attempted (they may - notifications and clipboard read: those imports are attempted (they may
still fail for lack of a desktop service) while clipboard write stays still fail for lack of a desktop service) while clipboard write stays
denied; denied;
- a host-specific fetch grant: requests to that host return their real - a host-specific fetch grant: requests to that host return their real
status (200, 404, and 302 without following the redirect to another status (200, 404, and 302 without following the redirect to another
host), and requests to another host are denied; host); requests to another host, a forged `Host` header, a method that
injects a request line and a `file:` URL are refused;
- a wildcard fetch grant: the other host is reachable. - a wildcard fetch grant: the other host is reachable.
It also checks that the runtime refuses filesystem capabilities passed as It also checks that the runtime refuses, with a specific error, filesystem
`--grant` and preopens without an access mode. capabilities passed as `--grant`, unknown capabilities and preopens
without an access mode.
Requires cargo with the wasm32-wasip2 target. Requires cargo with the wasm32-wasip2 target.
""" """
@ -119,14 +122,18 @@ def check(runner, data):
(data / "seed.txt").write_text("seed") (data / "seed.txt").write_text("seed")
_, probes = runner.run("--preopen", f"{data}::/data::ro") _, probes = runner.run("--preopen", f"{data}::/data::ro")
expect(probes, "data-read", True, contains="seed") expect(probes, "data-read", True, contains="seed")
expect(probes, "data-write", False) for name in ("data-write", "data-overwrite", "data-mkdir", "data-rename", "data-remove"):
if (data / "written.txt").exists(): expect(probes, name, False)
raise AssertionError("read-only grant allowed a write on the host") if sorted(p.name for p in data.iterdir()) != ["seed.txt"] or \
(data / "seed.txt").read_text() != "seed":
raise AssertionError("read-only grant allowed the host directory to change")
_, probes = runner.run("--preopen", f"{data}::/data::rw") _, probes = runner.run("--preopen", f"{data}::/data::rw")
expect(probes, "data-write", True) for name in ("data-write", "data-overwrite", "data-mkdir", "data-rename"):
if (data / "written.txt").read_text() != "probe": expect(probes, name, True)
raise AssertionError("read-write grant did not write to the host directory") if (data / "written.txt").read_text() != "probe" or \
(data / "moved.txt").read_text() != "changed" or not (data / "made").is_dir():
raise AssertionError("read-write grant did not change the host directory")
_, probes = runner.run("--grant", "sys:notifications", "--grant", "sys:clipboard:read") _, probes = runner.run("--grant", "sys:notifications", "--grant", "sys:clipboard:read")
expect(probes, "notifications", probes.get("notifications", "").startswith("ok"), expect(probes, "notifications", probes.get("notifications", "").startswith("ok"),
@ -140,15 +147,22 @@ def check(runner, data):
expect(probes, "fetch-missing", True, contains="404") expect(probes, "fetch-missing", True, contains="404")
expect(probes, "fetch-redirect", True, contains="302") expect(probes, "fetch-redirect", True, contains="302")
expect(probes, "fetch-other-host", False, contains=NOT_GRANTED) expect(probes, "fetch-other-host", False, contains=NOT_GRANTED)
expect(probes, "fetch-host-header", False, contains="set by the runtime")
expect(probes, "fetch-bad-method", False, contains="unsupported HTTP method")
expect(probes, "fetch-file-scheme", False, contains="unsupported URL scheme")
_, probes = runner.run("--grant", "net:fetch:*") _, probes = runner.run("--grant", "net:fetch:*")
expect(probes, "fetch-other-host", True, contains="200") expect(probes, "fetch-other-host", True, contains="200")
for arguments in (["--grant", "fs:rw:app-data"], ["--preopen", f"{data}::/data"], for arguments, message in (
["--grant", "sys:everything"]): (["--grant", "fs:rw:app-data"], "is not granted through --grant"),
(["--preopen", f"{data}::/data"], "--preopen expects HOST::GUEST::ro|rw"),
(["--preopen", f"{data}::/data::wx"], "--preopen mode must be ro or rw"),
(["--grant", "sys:everything"], "unknown capability 'sys:everything'")):
result, _ = runner.run(*arguments, expect_success=False) result, _ = runner.run(*arguments, expect_success=False)
if result.returncode == 0: if result.returncode == 0 or message not in result.stderr:
raise AssertionError(f"runtime accepted {' '.join(arguments)}") raise AssertionError(f"runtime did not refuse {' '.join(arguments)} with "
f"{message!r}:\n{result.stderr}")
def main(argv=None): def main(argv=None):