mirror of
https://github.com/marcoallegretti/WEFT_OS.git
synced 2026-11-22 08:13:59 +00:00
fix(appd): resolve each launch to one package and fail closed on images
The runtime, the app shell and grant derivation each searched the package stores and parsed wapp.toml on their own, so they could use different roots; the runtime ignored [runtime].module, the image loader looked for companion files the builder never wrote, and a failed image mount fell back to the mutable directory install. weft-appd now resolves a launch once: a verified image wins over a directory in the same store, and when any image file exists the image must mount or the launch is refused. The manifest must declare the requested ID, and both entries must be plain relative paths to regular files without links. The runtime receives --module and the app shell --ui; neither looks for the package. Grants come from the same manifest, and the mount belongs to the session. The manifest parser and the image file names move to weft-ipc-types, shared with weft-pack, whose check now applies the same entry rules. Mapper devices are named after their per-launch mountpoint, so concurrent sessions no longer collide.
This commit is contained in:
parent
d60152f443
commit
2148ffc8ae
21 changed files with 811 additions and 485 deletions
3
Cargo.lock
generated
3
Cargo.lock
generated
|
|
@ -10524,6 +10524,7 @@ dependencies = [
|
|||
"rmp-serde",
|
||||
"rustix 1.1.4",
|
||||
"serde",
|
||||
"toml 0.8.23",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
|
|
@ -10541,10 +10542,8 @@ dependencies = [
|
|||
"ed25519-dalek",
|
||||
"hex",
|
||||
"rand 0.8.5",
|
||||
"serde",
|
||||
"sha2",
|
||||
"tar",
|
||||
"toml 0.8.23",
|
||||
"weft-ipc-types",
|
||||
"zstd",
|
||||
]
|
||||
|
|
|
|||
|
|
@ -8,7 +8,7 @@ WEFT OS is a Wayland compositor and application runtime where every app is a Web
|
|||
|
||||
**System shell** — `weft-servo-shell` embeds Servo (feature-gated, `--features servo-embed`) and renders `system-ui.html` as a Wayland panel. Without `servo-embed`, the binary exits with an error instead of rendering. Navigation gestures from the compositor are forwarded to `weft-appd` over WebSocket.
|
||||
|
||||
**App shell** — `weft-app-shell` is a per-process Servo host for application WebViews. It resolves `weft-app://<id>/ui/index.html`, injects a `weftIpc` WebSocket bridge into the page, and registers with the compositor as an application surface. Also feature-gated behind `servo-embed`.
|
||||
**App shell** — `weft-app-shell` is a per-process Servo host for application WebViews. It shows the UI document `weft-appd` resolved from the package, injects a `weftIpc` WebSocket bridge into the page, and registers with the compositor as an application surface. Also feature-gated behind `servo-embed`.
|
||||
|
||||
**App daemon** — `weft-appd` supervises sessions: spawns `weft-runtime`, waits for its READY, spawns `weft-app-shell` and reports the session running only after the app shell's READY, manages the per-session IPC relay between the Wasm component and the WebView, and handles session teardown. Wraps processes in systemd scopes (`CPUQuota=200%`, `MemoryMax=512M`) when available.
|
||||
|
||||
|
|
|
|||
|
|
@ -12,7 +12,7 @@ path = "src/main.rs"
|
|||
# Enable actual Servo rendering. Deps are declared as optional below and only
|
||||
# fetched when this feature is active. The Servo monorepo (~1 GB) is not
|
||||
# downloaded during a plain `cargo check` or `cargo build` without this feature.
|
||||
servo-embed = ["dep:servo", "dep:winit", "dep:softbuffer", "dep:serde", "dep:toml"]
|
||||
servo-embed = ["dep:servo", "dep:winit", "dep:softbuffer"]
|
||||
|
||||
[dependencies]
|
||||
anyhow = "1.0"
|
||||
|
|
@ -22,8 +22,6 @@ wayland-client = "0.31"
|
|||
wayland-backend = "0.3"
|
||||
wayland-scanner = "0.31"
|
||||
bitflags = "2"
|
||||
serde = { version = "1", features = ["derive"], optional = true }
|
||||
toml = { version = "0.8", optional = true }
|
||||
|
||||
[dependencies.servo]
|
||||
git = "https://github.com/marcoallegretti/servo"
|
||||
|
|
|
|||
|
|
@ -1,5 +1,4 @@
|
|||
use std::num::NonZeroU32;
|
||||
use std::path::PathBuf;
|
||||
use std::rc::Rc;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
|
@ -627,73 +626,12 @@ fn resolve_weft_system_url(url: &ServoUrl) -> Option<ServoUrl> {
|
|||
ServoUrl::parse(&format!("file://{}", file.display())).ok()
|
||||
}
|
||||
|
||||
fn read_ui_entry(app_id: &str) -> Option<String> {
|
||||
#[derive(serde::Deserialize)]
|
||||
struct Ui {
|
||||
entry: String,
|
||||
}
|
||||
#[derive(serde::Deserialize)]
|
||||
struct Manifest {
|
||||
ui: Ui,
|
||||
}
|
||||
|
||||
let erofs_manifest = std::path::Path::new("/run/weft/apps")
|
||||
.join(app_id)
|
||||
.join("merged")
|
||||
.join("wapp.toml");
|
||||
let toml_text = std::fs::read_to_string(&erofs_manifest).ok().or_else(|| {
|
||||
app_store_roots()
|
||||
.into_iter()
|
||||
.find_map(|r| std::fs::read_to_string(r.join(app_id).join("wapp.toml")).ok())
|
||||
})?;
|
||||
let m: Manifest = toml::from_str(&toml_text).ok()?;
|
||||
Some(m.ui.entry)
|
||||
}
|
||||
|
||||
fn resolve_app_file_path(app_id: &str, rel: &str) -> Option<std::path::PathBuf> {
|
||||
let erofs_root = std::path::Path::new("/run/weft/apps")
|
||||
.join(app_id)
|
||||
.join("merged");
|
||||
if erofs_root.exists() {
|
||||
let p = erofs_root.join(rel);
|
||||
if p.exists() {
|
||||
return Some(p);
|
||||
}
|
||||
}
|
||||
app_store_roots()
|
||||
.into_iter()
|
||||
.map(|r| r.join(app_id).join(rel))
|
||||
.find(|p| p.exists())
|
||||
}
|
||||
|
||||
fn resolve_weft_app_url(app_id: &str) -> Option<ServoUrl> {
|
||||
let entry = read_ui_entry(app_id).unwrap_or_else(|| "ui/index.html".to_owned());
|
||||
let file_path = resolve_app_file_path(app_id, &entry)?;
|
||||
let s = format!("file://{}", file_path.display());
|
||||
ServoUrl::parse(&s).ok()
|
||||
}
|
||||
|
||||
fn app_store_roots() -> Vec<PathBuf> {
|
||||
if let Ok(v) = std::env::var("WEFT_APP_STORE") {
|
||||
return vec![PathBuf::from(v)];
|
||||
}
|
||||
let mut roots = Vec::new();
|
||||
if let Ok(home) = std::env::var("HOME") {
|
||||
roots.push(
|
||||
PathBuf::from(home)
|
||||
.join(".local")
|
||||
.join("share")
|
||||
.join("weft")
|
||||
.join("apps"),
|
||||
);
|
||||
}
|
||||
roots.push(PathBuf::from("/usr/share/weft/apps"));
|
||||
roots
|
||||
}
|
||||
|
||||
pub fn run(app_id: &str, session_id: u64, ws_port: u16) -> anyhow::Result<()> {
|
||||
let url = resolve_weft_app_url(app_id)
|
||||
.ok_or_else(|| anyhow::anyhow!("no ui/index.html found for app {app_id}"))?;
|
||||
/// Shows the UI document `ui` of `app_id`, the file weft-appd resolved from
|
||||
/// the package; the shell never looks for the package itself.
|
||||
pub fn run(app_id: &str, session_id: u64, ws_port: u16, ui: &std::path::Path) -> anyhow::Result<()> {
|
||||
let url = ServoUrl::from_file_path(ui)
|
||||
.map_err(|()| anyhow::anyhow!("{} is not an absolute path", ui.display()))?;
|
||||
tracing::info!(%app_id, %url, "showing application UI");
|
||||
|
||||
let event_loop = EventLoop::<ServoWake>::with_user_event()
|
||||
.build()
|
||||
|
|
|
|||
|
|
@ -18,19 +18,22 @@ fn main() -> anyhow::Result<()> {
|
|||
)
|
||||
.init();
|
||||
|
||||
const USAGE: &str = "usage: weft-app-shell <app_id> <session_id> --ui <path>";
|
||||
let mut args = std::env::args().skip(1);
|
||||
let app_id = args
|
||||
.next()
|
||||
.context("usage: weft-app-shell <app_id> <session_id>")?;
|
||||
let app_id = args.next().context(USAGE)?;
|
||||
let session_id: u64 = args
|
||||
.next()
|
||||
.context("usage: weft-app-shell <app_id> <session_id>")?
|
||||
.context(USAGE)?
|
||||
.parse()
|
||||
.context("session_id must be a number")?;
|
||||
let ui = match (args.next().as_deref(), args.next(), args.next()) {
|
||||
(Some("--ui"), Some(path), None) => std::path::PathBuf::from(path),
|
||||
_ => anyhow::bail!(USAGE),
|
||||
};
|
||||
|
||||
let ws_port = appd_ws_port();
|
||||
|
||||
embed_app(&app_id, session_id, ws_port)
|
||||
embed_app(&app_id, session_id, ws_port, &ui)
|
||||
}
|
||||
|
||||
fn appd_ws_port() -> u16 {
|
||||
|
|
@ -50,13 +53,18 @@ fn appd_ws_port() -> u16 {
|
|||
7410
|
||||
}
|
||||
|
||||
fn embed_app(app_id: &str, session_id: u64, ws_port: u16) -> anyhow::Result<()> {
|
||||
fn embed_app(
|
||||
app_id: &str,
|
||||
session_id: u64,
|
||||
ws_port: u16,
|
||||
ui: &std::path::Path,
|
||||
) -> anyhow::Result<()> {
|
||||
#[cfg(feature = "servo-embed")]
|
||||
return embedder::run(app_id, session_id, ws_port);
|
||||
return embedder::run(app_id, session_id, ws_port, ui);
|
||||
|
||||
#[cfg(not(feature = "servo-embed"))]
|
||||
{
|
||||
let _ = (app_id, session_id, ws_port);
|
||||
let _ = (app_id, session_id, ws_port, ui);
|
||||
anyhow::bail!("weft-app-shell was built without the servo-embed feature and cannot render")
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -46,7 +46,7 @@ pub(crate) struct Refusal {
|
|||
}
|
||||
|
||||
impl Refusal {
|
||||
fn new(code: u32, message: impl Into<String>) -> Self {
|
||||
pub(crate) fn new(code: u32, message: impl Into<String>) -> Self {
|
||||
Self {
|
||||
code,
|
||||
message: message.into(),
|
||||
|
|
@ -87,33 +87,6 @@ impl HostDirs {
|
|||
}
|
||||
}
|
||||
|
||||
/// Reads the package manifest of `app_id` and derives its grants.
|
||||
pub(crate) fn for_app(app_id: &str) -> Result<SessionGrants, Refusal> {
|
||||
#[derive(serde::Deserialize)]
|
||||
struct Package {
|
||||
capabilities: Option<Vec<String>>,
|
||||
}
|
||||
#[derive(serde::Deserialize)]
|
||||
struct Manifest {
|
||||
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()
|
||||
.into_iter()
|
||||
.map(|root| root.join(app_id).join("wapp.toml"))
|
||||
.find(|path| path.exists())
|
||||
.ok_or_else(|| Refusal::new(404, format!("package {app_id} is not installed")))?;
|
||||
let text = std::fs::read_to_string(&manifest)
|
||||
.map_err(|e| Refusal::new(500, format!("cannot read {}: {e}", manifest.display())))?;
|
||||
let manifest: Manifest = toml::from_str(&text)
|
||||
.map_err(|e| Refusal::new(403, 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. Every capability is
|
||||
/// checked before host directories are resolved or the app's data
|
||||
/// directory is created, so a refused launch leaves nothing behind.
|
||||
|
|
|
|||
241
crates/weft-appd/src/launch.rs
Normal file
241
crates/weft-appd/src/launch.rs
Normal file
|
|
@ -0,0 +1,241 @@
|
|||
//! The package a session runs, resolved once before anything is started.
|
||||
//!
|
||||
//! The runtime and the app shell receive the exact files resolved here and
|
||||
//! never look for the package themselves, so the component, the UI and the
|
||||
//! capabilities a session is granted all come from the same package root.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use weft_ipc_types::manifest::{MANIFEST_FILE, Manifest, entry_path};
|
||||
use weft_ipc_types::package::{ImageFiles, is_valid_app_id};
|
||||
|
||||
use crate::grants::Refusal;
|
||||
use crate::mount::Mount;
|
||||
|
||||
pub(crate) struct LaunchPackage {
|
||||
pub(crate) app_id: String,
|
||||
pub(crate) version: String,
|
||||
pub(crate) root: PathBuf,
|
||||
/// The Wasm component, from `[runtime].module`.
|
||||
pub(crate) module: PathBuf,
|
||||
/// The UI document, from `[ui].entry`.
|
||||
pub(crate) ui_entry: PathBuf,
|
||||
pub(crate) capabilities: Vec<String>,
|
||||
/// The image the package root is mounted from, held for as long as the
|
||||
/// session runs.
|
||||
pub(crate) image: Option<Mount>,
|
||||
}
|
||||
|
||||
/// Resolves `app_id` in the package stores, in order. In each store a
|
||||
/// verified image takes precedence over a directory install. When any image
|
||||
/// file is present for the ID, the image must mount: a missing or damaged
|
||||
/// image never falls back to a directory, which nothing verifies.
|
||||
pub(crate) fn resolve(app_id: &str) -> Result<LaunchPackage, Refusal> {
|
||||
if !is_valid_app_id(app_id) {
|
||||
return Err(Refusal::new(400, "invalid app ID"));
|
||||
}
|
||||
for store in crate::app_store_roots() {
|
||||
let files = ImageFiles::in_store(&store, app_id);
|
||||
if files.any_present() {
|
||||
let image = crate::mount::mount(app_id, &files).map_err(|e| {
|
||||
Refusal::new(500, format!("the verified image cannot be mounted: {e}"))
|
||||
})?;
|
||||
let root = image.root().to_path_buf();
|
||||
return from_root(app_id, root, Some(image));
|
||||
}
|
||||
let dir = store.join(app_id);
|
||||
if std::fs::symlink_metadata(dir.join(MANIFEST_FILE)).is_ok() {
|
||||
return from_root(app_id, dir, None);
|
||||
}
|
||||
}
|
||||
Err(Refusal::new(404, format!("package {app_id} is not installed")))
|
||||
}
|
||||
|
||||
fn from_root(
|
||||
app_id: &str,
|
||||
root: PathBuf,
|
||||
image: Option<Mount>,
|
||||
) -> Result<LaunchPackage, Refusal> {
|
||||
let manifest = Manifest::read(&root).map_err(|e| Refusal::new(403, e.to_string()))?;
|
||||
if manifest.package.id != app_id {
|
||||
return Err(Refusal::new(
|
||||
403,
|
||||
format!(
|
||||
"the package in {} declares ID '{}'",
|
||||
root.display(),
|
||||
manifest.package.id
|
||||
),
|
||||
));
|
||||
}
|
||||
let entry = |field: &str, value: &str| {
|
||||
entry_path(&root, value).map_err(|e| Refusal::new(403, format!("{field}: {e}")))
|
||||
};
|
||||
let module = entry("runtime.module", &manifest.runtime.module)?;
|
||||
let ui_entry = entry("ui.entry", &manifest.ui.entry)?;
|
||||
Ok(LaunchPackage {
|
||||
app_id: app_id.to_owned(),
|
||||
version: manifest.package.version.clone(),
|
||||
capabilities: manifest.capabilities().to_vec(),
|
||||
module,
|
||||
ui_entry,
|
||||
root,
|
||||
image,
|
||||
})
|
||||
}
|
||||
|
||||
impl LaunchPackage {
|
||||
/// A package for supervisor tests whose children ignore their files.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn unresolved(app_id: &str) -> Self {
|
||||
Self {
|
||||
app_id: app_id.to_owned(),
|
||||
version: "0.0.0".to_owned(),
|
||||
root: PathBuf::from("/nonexistent"),
|
||||
module: PathBuf::from("/nonexistent/app.wasm"),
|
||||
ui_entry: PathBuf::from("/nonexistent/ui/index.html"),
|
||||
capabilities: Vec::new(),
|
||||
image: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn root(&self) -> &Path {
|
||||
&self.root
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const ID: &str = "org.weft.test.resolve";
|
||||
|
||||
/// A store holding a directory install of `ID`, with WEFT_APP_STORE
|
||||
/// pointing at it. Callers hold env_lock.
|
||||
fn store(name: &str, manifest_id: &str, module: &str) -> PathBuf {
|
||||
let store = std::env::temp_dir().join(format!(
|
||||
"weft_appd_launch_{name}_{}",
|
||||
std::process::id()
|
||||
));
|
||||
let _ = std::fs::remove_dir_all(&store);
|
||||
let package = store.join(ID);
|
||||
std::fs::create_dir_all(package.join("ui")).unwrap();
|
||||
std::fs::write(package.join("app.wasm"), b"\0asm\x01\0\0\0").unwrap();
|
||||
std::fs::write(package.join("ui/index.html"), b"<p>").unwrap();
|
||||
std::fs::write(
|
||||
package.join(MANIFEST_FILE),
|
||||
format!(
|
||||
"[package]\nid = \"{manifest_id}\"\nname = \"T\"\nversion = \"1.2.3\"\n\
|
||||
capabilities = [\"sys:notifications\"]\n\
|
||||
[runtime]\nmodule = \"{module}\"\n[ui]\nentry = \"ui/index.html\"\n"
|
||||
),
|
||||
)
|
||||
.unwrap();
|
||||
// SAFETY: callers hold env_lock, which serialises environment changes.
|
||||
unsafe { std::env::set_var("WEFT_APP_STORE", &store) };
|
||||
store
|
||||
}
|
||||
|
||||
fn finish(store: &Path) {
|
||||
// SAFETY: as in `store`.
|
||||
unsafe {
|
||||
std::env::remove_var("WEFT_APP_STORE");
|
||||
std::env::remove_var("WEFT_MOUNT_HELPER");
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(store);
|
||||
}
|
||||
|
||||
fn refusal(result: Result<LaunchPackage, Refusal>) -> Refusal {
|
||||
match result {
|
||||
Ok(package) => panic!("resolved {}", package.root.display()),
|
||||
Err(refusal) => refusal,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_directory_install_resolves_to_its_own_files() {
|
||||
let _env = crate::tests::env_lock().blocking_lock();
|
||||
let store = store("dir", ID, "app.wasm");
|
||||
let package = resolve(ID).unwrap();
|
||||
finish(&store);
|
||||
assert_eq!(package.root, store.join(ID));
|
||||
assert_eq!(package.module, store.join(ID).join("app.wasm"));
|
||||
assert_eq!(package.ui_entry, store.join(ID).join("ui/index.html"));
|
||||
assert_eq!(package.version, "1.2.3");
|
||||
assert_eq!(package.capabilities, ["sys:notifications"]);
|
||||
assert!(package.image.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_package_declaring_another_id_is_refused() {
|
||||
let _env = crate::tests::env_lock().blocking_lock();
|
||||
let store = store("id", "org.weft.test.other", "app.wasm");
|
||||
let refused = refusal(resolve(ID));
|
||||
finish(&store);
|
||||
assert_eq!(refused.code, 403);
|
||||
assert!(refused.message.contains("org.weft.test.other"), "{}", refused.message);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn entries_outside_the_package_are_refused() {
|
||||
let _env = crate::tests::env_lock().blocking_lock();
|
||||
let store = store("entry", ID, "../escape.wasm");
|
||||
std::fs::write(store.join("escape.wasm"), b"\0asm").unwrap();
|
||||
let refused = refusal(resolve(ID));
|
||||
finish(&store);
|
||||
assert_eq!(refused.code, 403);
|
||||
assert!(refused.message.contains("runtime.module"), "{}", refused.message);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_packages_and_invalid_ids_are_refused() {
|
||||
let _env = crate::tests::env_lock().blocking_lock();
|
||||
let store = store("missing", ID, "app.wasm");
|
||||
let missing = refusal(resolve("org.weft.test.absent"));
|
||||
let invalid = refusal(resolve("../etc"));
|
||||
finish(&store);
|
||||
assert_eq!(missing.code, 404);
|
||||
assert_eq!(invalid.code, 400);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_image_that_cannot_be_used_never_falls_back_to_the_directory() {
|
||||
let _env = crate::tests::env_lock().blocking_lock();
|
||||
crate::tests::use_test_runtime_dir();
|
||||
let store = store("image", ID, "app.wasm");
|
||||
let files = ImageFiles::in_store(&store, ID);
|
||||
|
||||
// Only the image: its companions are missing.
|
||||
std::fs::write(&files.image, b"image").unwrap();
|
||||
// SAFETY: as in `store`.
|
||||
unsafe { std::env::set_var("WEFT_MOUNT_HELPER", "/bin/true") };
|
||||
let partial = refusal(resolve(ID));
|
||||
|
||||
// All three files, but the helper fails to mount them.
|
||||
std::fs::write(&files.hash_tree, b"tree").unwrap();
|
||||
std::fs::write(&files.root_hash, "ab".repeat(32)).unwrap();
|
||||
unsafe { std::env::set_var("WEFT_MOUNT_HELPER", "/bin/false") };
|
||||
let failed = refusal(resolve(ID));
|
||||
|
||||
// The helper is not installed.
|
||||
unsafe { std::env::set_var("WEFT_MOUNT_HELPER", "/nonexistent/weft-mount-helper") };
|
||||
let absent = refusal(resolve(ID));
|
||||
|
||||
// A root hash that is not one.
|
||||
std::fs::write(&files.root_hash, "not a hash").unwrap();
|
||||
unsafe { std::env::set_var("WEFT_MOUNT_HELPER", "/bin/true") };
|
||||
let malformed = refusal(resolve(ID));
|
||||
|
||||
let mountpoints = std::env::var_os("XDG_RUNTIME_DIR")
|
||||
.map(|dir| PathBuf::from(dir).join("weft/mnt"))
|
||||
.and_then(|dir| std::fs::read_dir(dir).ok())
|
||||
.map_or(0, Iterator::count);
|
||||
finish(&store);
|
||||
|
||||
for refused in [&partial, &failed, &absent, &malformed] {
|
||||
assert_eq!(refused.code, 500, "{}", refused.message);
|
||||
assert!(refused.message.contains("verified image"), "{}", refused.message);
|
||||
}
|
||||
assert!(partial.message.contains(".app.hash"), "{}", partial.message);
|
||||
assert_eq!(mountpoints, 0, "a failed mount left its mountpoint behind");
|
||||
}
|
||||
}
|
||||
|
|
@ -19,6 +19,7 @@ mod compositor_client {
|
|||
}
|
||||
mod grants;
|
||||
mod ipc;
|
||||
mod launch;
|
||||
mod mount;
|
||||
mod runtime;
|
||||
mod ws;
|
||||
|
|
@ -442,20 +443,19 @@ pub(crate) async fn dispatch(req: Request, registry: &Registry) -> Response {
|
|||
app_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 !weft_ipc_types::package::is_valid_app_id(&app_id) {
|
||||
Err(grants::Refusal {
|
||||
code: 400,
|
||||
message: "invalid app ID".to_owned(),
|
||||
})
|
||||
// The package is resolved and its capabilities granted before a
|
||||
// session exists; a package this host cannot satisfy is refused,
|
||||
// not started.
|
||||
let launch = if !weft_ipc_types::package::is_valid_app_id(&app_id) {
|
||||
Err(grants::Refusal::new(400, "invalid app ID"))
|
||||
} else if std::env::var("WEFT_RUNTIME_BIN").is_ok() {
|
||||
grants::for_app(&app_id)
|
||||
resolve_launch(app_id.clone()).await.map(Some)
|
||||
} else {
|
||||
Ok(grants::SessionGrants::default())
|
||||
Ok(None)
|
||||
};
|
||||
let grants = match grants {
|
||||
Ok(grants) => grants,
|
||||
let (package, grants) = match launch {
|
||||
Ok(Some((package, grants))) => (Some(package), grants),
|
||||
Ok(None) => (None, grants::SessionGrants::default()),
|
||||
Err(refusal) => {
|
||||
tracing::warn!(%app_id, error = %refusal.message, "launch refused");
|
||||
return Response::Error {
|
||||
|
|
@ -469,7 +469,9 @@ pub(crate) async fn dispatch(req: Request, registry: &Registry) -> Response {
|
|||
let abort_rx = registry.lock().await.register_abort(session_id);
|
||||
let compositor_tx = registry.lock().await.compositor_tx.clone();
|
||||
|
||||
if std::env::var("WEFT_RUNTIME_BIN").is_err() {
|
||||
// Without a configured runtime, nothing was resolved and the
|
||||
// session stops at once.
|
||||
let Some(package) = package else {
|
||||
let _ = registry.lock().await.broadcast().send(Response::LaunchAck {
|
||||
session_id,
|
||||
app_id: app_id.clone(),
|
||||
|
|
@ -484,12 +486,12 @@ pub(crate) async fn dispatch(req: Request, registry: &Registry) -> Response {
|
|||
state: AppStateKind::Stopped,
|
||||
});
|
||||
return Response::LaunchAck { session_id, app_id };
|
||||
}
|
||||
};
|
||||
let reg = Arc::clone(registry);
|
||||
let aid = app_id.clone();
|
||||
tokio::spawn(async move {
|
||||
if let Err(e) =
|
||||
runtime::supervise(session_id, &aid, grants, reg, abort_rx, compositor_tx).await
|
||||
runtime::supervise(session_id, package, grants, reg, abort_rx, compositor_tx)
|
||||
.await
|
||||
{
|
||||
tracing::warn!(session_id, error = %e, "runtime supervisor error");
|
||||
}
|
||||
|
|
@ -576,6 +578,28 @@ pub(crate) async fn dispatch(req: Request, registry: &Registry) -> Response {
|
|||
}
|
||||
}
|
||||
|
||||
/// Resolves the package of `app_id` and derives its grants. Resolution may
|
||||
/// mount an image, so it runs off the async workers; a refused launch
|
||||
/// releases the mount the same way.
|
||||
async fn resolve_launch(
|
||||
app_id: String,
|
||||
) -> Result<(launch::LaunchPackage, grants::SessionGrants), grants::Refusal> {
|
||||
tokio::task::spawn_blocking(move || {
|
||||
let package = launch::resolve(&app_id)?;
|
||||
let grants = grants::derive(&app_id, &package.capabilities, grants::HostDirs::from_env)?;
|
||||
tracing::info!(
|
||||
%app_id,
|
||||
version = %package.version,
|
||||
root = %package.root().display(),
|
||||
image = package.image.is_some(),
|
||||
"package resolved"
|
||||
);
|
||||
Ok((package, grants))
|
||||
})
|
||||
.await
|
||||
.unwrap_or_else(|e| Err(grants::Refusal::new(500, format!("package resolution failed: {e}"))))
|
||||
}
|
||||
|
||||
pub(crate) fn app_store_roots() -> Vec<std::path::PathBuf> {
|
||||
if let Ok(explicit) = std::env::var("WEFT_APP_STORE") {
|
||||
return vec![std::path::PathBuf::from(explicit)];
|
||||
|
|
@ -594,18 +618,6 @@ pub(crate) fn app_store_roots() -> Vec<std::path::PathBuf> {
|
|||
roots
|
||||
}
|
||||
|
||||
#[derive(serde::Deserialize)]
|
||||
struct WappPackage {
|
||||
id: String,
|
||||
name: String,
|
||||
version: String,
|
||||
}
|
||||
|
||||
#[derive(serde::Deserialize)]
|
||||
struct WappManifest {
|
||||
package: WappPackage,
|
||||
}
|
||||
|
||||
fn scan_installed_apps() -> Vec<AppInfo> {
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
let mut apps = Vec::new();
|
||||
|
|
@ -614,11 +626,7 @@ fn scan_installed_apps() -> Vec<AppInfo> {
|
|||
continue;
|
||||
};
|
||||
for entry in entries.flatten() {
|
||||
let manifest_path = entry.path().join("wapp.toml");
|
||||
let Ok(contents) = std::fs::read_to_string(&manifest_path) else {
|
||||
continue;
|
||||
};
|
||||
let Ok(m) = toml::from_str::<WappManifest>(&contents) else {
|
||||
let Ok(m) = weft_ipc_types::manifest::Manifest::read(&entry.path()) else {
|
||||
continue;
|
||||
};
|
||||
if seen.insert(m.package.id.clone()) {
|
||||
|
|
@ -655,7 +663,7 @@ mod tests {
|
|||
/// since session sockets are named by session ID and every test registry
|
||||
/// starts at 1. Directories of test processes that have ended are
|
||||
/// removed. Callers hold env_lock.
|
||||
fn use_test_runtime_dir() {
|
||||
pub(crate) fn use_test_runtime_dir() {
|
||||
let base = std::env::temp_dir().join("weft-appd-tests");
|
||||
if let Ok(entries) = std::fs::read_dir(&base) {
|
||||
for entry in entries.flatten() {
|
||||
|
|
@ -1120,7 +1128,7 @@ mod tests {
|
|||
};
|
||||
let supervised = runtime::supervise(
|
||||
session_id,
|
||||
"test.app",
|
||||
launch::LaunchPackage::unresolved("test.app"),
|
||||
grants::SessionGrants::default(),
|
||||
Arc::clone(®istry),
|
||||
abort_rx,
|
||||
|
|
@ -1267,7 +1275,7 @@ mod tests {
|
|||
|
||||
runtime::supervise(
|
||||
session_id,
|
||||
"test.app",
|
||||
launch::LaunchPackage::unresolved("test.app"),
|
||||
grants::SessionGrants::default(),
|
||||
Arc::clone(®istry),
|
||||
abort_rx,
|
||||
|
|
@ -1342,7 +1350,7 @@ mod tests {
|
|||
|
||||
runtime::supervise(
|
||||
session_id,
|
||||
"test.abort.startup",
|
||||
launch::LaunchPackage::unresolved("test.abort.startup"),
|
||||
grants::SessionGrants::default(),
|
||||
Arc::clone(®istry),
|
||||
abort_rx,
|
||||
|
|
@ -1392,7 +1400,7 @@ mod tests {
|
|||
|
||||
runtime::supervise(
|
||||
session_id,
|
||||
"test.spawn.fail",
|
||||
launch::LaunchPackage::unresolved("test.spawn.fail"),
|
||||
grants::SessionGrants::default(),
|
||||
Arc::clone(®istry),
|
||||
abort_rx,
|
||||
|
|
|
|||
|
|
@ -1,105 +1,106 @@
|
|||
//! Verified package images, mounted read-only for the session that runs
|
||||
//! them.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
fn mount_helper_bin() -> Option<String> {
|
||||
if let Ok(v) = std::env::var("WEFT_MOUNT_HELPER") {
|
||||
return Some(v);
|
||||
use weft_ipc_types::package::ImageFiles;
|
||||
|
||||
fn mount_helper_bin() -> Option<PathBuf> {
|
||||
if let Some(path) = std::env::var_os("WEFT_MOUNT_HELPER") {
|
||||
return Some(PathBuf::from(path));
|
||||
}
|
||||
for candidate in [
|
||||
[
|
||||
"/usr/lib/weft/weft-mount-helper",
|
||||
"/usr/local/lib/weft/weft-mount-helper",
|
||||
] {
|
||||
if Path::new(candidate).exists() {
|
||||
return Some(candidate.to_string());
|
||||
}
|
||||
}
|
||||
None
|
||||
]
|
||||
.into_iter()
|
||||
.map(PathBuf::from)
|
||||
.find(|candidate| candidate.exists())
|
||||
}
|
||||
|
||||
pub struct MountOrchestrator {
|
||||
mountpoint: Option<PathBuf>,
|
||||
/// A mounted image. Dropping it unmounts the image and removes the empty
|
||||
/// mountpoint; a mountpoint that cannot be unmounted is left in place.
|
||||
pub(crate) struct Mount {
|
||||
helper: PathBuf,
|
||||
mountpoint: PathBuf,
|
||||
}
|
||||
|
||||
impl MountOrchestrator {
|
||||
pub fn mount_if_needed(app_id: &str, session_id: u64) -> (Self, Option<PathBuf>) {
|
||||
let Some(helper) = mount_helper_bin() else {
|
||||
return (Self { mountpoint: None }, None);
|
||||
};
|
||||
|
||||
let (img, hash_dev, root_hash) = match find_image(app_id) {
|
||||
Some(t) => t,
|
||||
None => return (Self { mountpoint: None }, None),
|
||||
};
|
||||
|
||||
let base = std::env::temp_dir().join(format!("weft-mnt-{session_id}"));
|
||||
let mountpoint = base.join(app_id);
|
||||
|
||||
if let Err(e) = std::fs::create_dir_all(&mountpoint) {
|
||||
tracing::warn!(session_id, %app_id, error=%e, "cannot create mount dir; skipping image mount");
|
||||
return (Self { mountpoint: None }, None);
|
||||
impl Mount {
|
||||
/// The package root inside the image.
|
||||
pub(crate) fn root(&self) -> &Path {
|
||||
&self.mountpoint
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Mount {
|
||||
fn drop(&mut self) {
|
||||
let unmounted = std::process::Command::new(&self.helper)
|
||||
.arg("umount")
|
||||
.arg(&self.mountpoint)
|
||||
.status()
|
||||
.is_ok_and(|status| status.success());
|
||||
if !unmounted {
|
||||
tracing::error!(path = %self.mountpoint.display(), "cannot unmount package image");
|
||||
return;
|
||||
}
|
||||
if let Err(e) = std::fs::remove_dir(&self.mountpoint) {
|
||||
tracing::warn!(path = %self.mountpoint.display(), error = %e, "cannot remove mountpoint");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Mounts the verified image `files` of `app_id`. Every failure is returned:
|
||||
/// the caller must not fall back to another copy of the package.
|
||||
pub(crate) fn mount(app_id: &str, files: &ImageFiles) -> Result<Mount, String> {
|
||||
let helper = mount_helper_bin().ok_or("weft-mount-helper is not installed")?;
|
||||
for path in [&files.image, &files.hash_tree, &files.root_hash] {
|
||||
let is_file = std::fs::symlink_metadata(path).is_ok_and(|m| m.file_type().is_file());
|
||||
if !is_file {
|
||||
return Err(format!("{} is missing or not a regular file", path.display()));
|
||||
}
|
||||
}
|
||||
let root_hash = std::fs::read_to_string(&files.root_hash)
|
||||
.map_err(|e| format!("cannot read {}: {e}", files.root_hash.display()))?;
|
||||
let root_hash = root_hash.trim();
|
||||
if !is_root_hash(root_hash) {
|
||||
return Err(format!("{} holds no root hash", files.root_hash.display()));
|
||||
}
|
||||
|
||||
let runtime_dir = std::env::var_os("XDG_RUNTIME_DIR").ok_or("XDG_RUNTIME_DIR is not set")?;
|
||||
let base = PathBuf::from(runtime_dir).join("weft/mnt");
|
||||
crate::private_dir(&base).map_err(|e| format!("cannot create {}: {e}", base.display()))?;
|
||||
let name = crate::runtime::random_token().map_err(|e| format!("no mountpoint name: {e}"))?;
|
||||
let mountpoint = base.join(name);
|
||||
std::fs::create_dir(&mountpoint)
|
||||
.map_err(|e| format!("cannot create {}: {e}", mountpoint.display()))?;
|
||||
|
||||
let status = std::process::Command::new(&helper)
|
||||
.args([
|
||||
"mount",
|
||||
&img.to_string_lossy(),
|
||||
&hash_dev.to_string_lossy(),
|
||||
&root_hash,
|
||||
&mountpoint.to_string_lossy(),
|
||||
])
|
||||
.arg("mount")
|
||||
.arg(&files.image)
|
||||
.arg(&files.hash_tree)
|
||||
.arg(root_hash)
|
||||
.arg(&mountpoint)
|
||||
.status();
|
||||
|
||||
match status {
|
||||
Ok(s) if s.success() => {
|
||||
tracing::info!(session_id, %app_id, path=%mountpoint.display(), "EROFS image mounted");
|
||||
(
|
||||
Self {
|
||||
mountpoint: Some(mountpoint),
|
||||
},
|
||||
Some(base),
|
||||
)
|
||||
Ok(status) if status.success() => {
|
||||
tracing::info!(%app_id, path = %mountpoint.display(), "package image mounted");
|
||||
Ok(Mount { helper, mountpoint })
|
||||
}
|
||||
Ok(s) => {
|
||||
tracing::warn!(session_id, %app_id, status=%s, "mount-helper failed; using directory install");
|
||||
let _ = std::fs::remove_dir_all(&base);
|
||||
(Self { mountpoint: None }, None)
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::warn!(session_id, %app_id, error=%e, "spawn mount-helper failed; using directory install");
|
||||
let _ = std::fs::remove_dir_all(&base);
|
||||
(Self { mountpoint: None }, None)
|
||||
outcome => {
|
||||
let _ = std::fs::remove_dir(&mountpoint);
|
||||
Err(match outcome {
|
||||
Ok(status) => format!("weft-mount-helper failed: {status}"),
|
||||
Err(e) => format!("cannot run {}: {e}", helper.display()),
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn umount(&self) {
|
||||
let Some(ref mp) = self.mountpoint else {
|
||||
return;
|
||||
};
|
||||
let Some(helper) = mount_helper_bin() else {
|
||||
return;
|
||||
};
|
||||
let _ = std::process::Command::new(&helper)
|
||||
.args(["umount", &mp.to_string_lossy()])
|
||||
.status();
|
||||
if let Some(parent) = mp.parent() {
|
||||
let _ = std::fs::remove_dir_all(parent);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn find_image(app_id: &str) -> Option<(PathBuf, PathBuf, String)> {
|
||||
for root in crate::app_store_roots() {
|
||||
let img = root.join(format!("{app_id}.app.img"));
|
||||
let hash_dev = root.join(format!("{app_id}.hash"));
|
||||
let roothash_file = root.join(format!("{app_id}.roothash"));
|
||||
if img.exists() && hash_dev.exists() && roothash_file.exists() {
|
||||
let Ok(root_hash) = std::fs::read_to_string(&roothash_file) else {
|
||||
continue;
|
||||
};
|
||||
return Some((img, hash_dev, root_hash.trim().to_string()));
|
||||
}
|
||||
}
|
||||
None
|
||||
/// A dm-verity root hash in hex, as `veritysetup format` prints it.
|
||||
fn is_root_hash(text: &str) -> bool {
|
||||
(64..=128).contains(&text.len())
|
||||
&& text.len() % 2 == 0
|
||||
&& text.bytes().all(|b| b.is_ascii_hexdigit())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
|
@ -107,11 +108,11 @@ mod tests {
|
|||
use super::*;
|
||||
|
||||
#[test]
|
||||
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") };
|
||||
let result = find_image("com.example.missing");
|
||||
unsafe { std::env::remove_var("WEFT_APP_STORE") };
|
||||
assert!(result.is_none());
|
||||
fn root_hashes_are_hex_digests() {
|
||||
assert!(is_root_hash(&"a".repeat(64)));
|
||||
assert!(is_root_hash(&"0F".repeat(64)));
|
||||
for bad in ["", "abc", &"g".repeat(64), &"a".repeat(65), &"a".repeat(130)] {
|
||||
assert!(!is_root_hash(bad), "{bad:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -6,6 +6,8 @@ use weft_ipc_types::AppdToCompositor;
|
|||
|
||||
use crate::Registry;
|
||||
use crate::compositor_client::CompositorSender;
|
||||
use crate::launch::LaunchPackage;
|
||||
use crate::mount::Mount;
|
||||
use crate::ipc::{AppStateKind, Response};
|
||||
|
||||
/// The per-session relay between the component's IPC socket and the app
|
||||
|
|
@ -186,7 +188,7 @@ async fn kill_portal(portal: Option<(PathBuf, tokio::process::Child)>) {
|
|||
fn spawn_app_shell(
|
||||
bin: &str,
|
||||
session_id: u64,
|
||||
app_id: &str,
|
||||
package: &LaunchPackage,
|
||||
token: &str,
|
||||
bridge_token: Option<String>,
|
||||
) -> std::io::Result<tokio::process::Child> {
|
||||
|
|
@ -197,15 +199,17 @@ fn spawn_app_shell(
|
|||
command.env(BRIDGE_TOKEN_ENV, bridge_token);
|
||||
}
|
||||
let child = command
|
||||
.arg(app_id)
|
||||
.arg(&package.app_id)
|
||||
.arg(session_id.to_string())
|
||||
.arg("--ui")
|
||||
.arg(&package.ui_entry)
|
||||
.env(READY_TOKEN_ENV, token)
|
||||
.stdin(std::process::Stdio::null())
|
||||
.stdout(std::process::Stdio::piped())
|
||||
.stderr(std::process::Stdio::piped())
|
||||
.kill_on_drop(true)
|
||||
.spawn()?;
|
||||
tracing::info!(session_id, %app_id, bin, "app shell spawned");
|
||||
tracing::info!(session_id, app_id = %package.app_id, bin, "app shell spawned");
|
||||
Ok(child)
|
||||
}
|
||||
|
||||
|
|
@ -241,36 +245,39 @@ fn spawn_file_portal(
|
|||
|
||||
pub(crate) async fn supervise(
|
||||
session_id: u64,
|
||||
app_id: &str,
|
||||
mut package: LaunchPackage,
|
||||
grants: crate::grants::SessionGrants,
|
||||
registry: Registry,
|
||||
abort_rx: tokio::sync::oneshot::Receiver<()>,
|
||||
compositor_tx: Option<CompositorSender>,
|
||||
) -> anyhow::Result<()> {
|
||||
let mut abort_rx = abort_rx;
|
||||
let app_id = package.app_id.clone();
|
||||
let app_id = app_id.as_str();
|
||||
let image = package.image.take();
|
||||
let bin = match std::env::var("WEFT_RUNTIME_BIN") {
|
||||
Ok(b) => b,
|
||||
Err(_) => {
|
||||
tracing::debug!(session_id, %app_id, "WEFT_RUNTIME_BIN not set; skipping process spawn");
|
||||
return stop_unstarted(®istry, session_id).await;
|
||||
return stop_unstarted(®istry, session_id, image).await;
|
||||
}
|
||||
};
|
||||
|
||||
let Ok(shell_bin) = std::env::var("WEFT_APP_SHELL_BIN") else {
|
||||
tracing::warn!(session_id, %app_id, "WEFT_APP_SHELL_BIN not set; no UI host to start");
|
||||
return stop_unstarted(®istry, session_id).await;
|
||||
return stop_unstarted(®istry, session_id, image).await;
|
||||
};
|
||||
let token = match random_token() {
|
||||
Ok(token) => token,
|
||||
Err(e) => {
|
||||
tracing::error!(session_id, %app_id, error = %e, "cannot create readiness token");
|
||||
return stop_unstarted(®istry, session_id).await;
|
||||
return stop_unstarted(®istry, session_id, image).await;
|
||||
}
|
||||
};
|
||||
|
||||
let Some(ipc_socket_path) = crate::session_ipc_socket_path(session_id) else {
|
||||
tracing::warn!(session_id, %app_id, "no runtime directory for the IPC socket");
|
||||
return stop_unstarted(®istry, session_id).await;
|
||||
return stop_unstarted(®istry, session_id, image).await;
|
||||
};
|
||||
let broadcast = registry.lock().await.broadcast().clone();
|
||||
let relay = match spawn_ipc_relay(session_id, ipc_socket_path.clone(), broadcast) {
|
||||
|
|
@ -280,13 +287,10 @@ pub(crate) async fn supervise(
|
|||
}
|
||||
Err(e) => {
|
||||
tracing::warn!(session_id, %app_id, error = %e, "cannot open the IPC socket");
|
||||
return stop_unstarted(®istry, session_id).await;
|
||||
return stop_unstarted(®istry, session_id, image).await;
|
||||
}
|
||||
};
|
||||
|
||||
let (mount_orch, store_override) =
|
||||
crate::mount::MountOrchestrator::mount_if_needed(app_id, session_id);
|
||||
|
||||
let portal = spawn_file_portal(session_id, &grants.dirs);
|
||||
|
||||
let mut cmd = if systemd_cgroup_available() {
|
||||
|
|
@ -305,10 +309,7 @@ pub(crate) async fn supervise(
|
|||
.kill_on_drop(true);
|
||||
|
||||
cmd.arg("--ipc-socket").arg(&ipc_socket_path);
|
||||
|
||||
if let Some(ref root) = store_override {
|
||||
cmd.env("WEFT_APP_STORE", root);
|
||||
}
|
||||
cmd.arg("--module").arg(&package.module);
|
||||
|
||||
if let Some((ref sock, _)) = portal {
|
||||
cmd.env("WEFT_FILE_PORTAL_SOCKET", sock);
|
||||
|
|
@ -327,7 +328,7 @@ pub(crate) async fn supervise(
|
|||
app_shell: None,
|
||||
portal,
|
||||
relay: Some(relay),
|
||||
mount: mount_orch,
|
||||
image,
|
||||
compositor_tx,
|
||||
surface_announced: false,
|
||||
};
|
||||
|
|
@ -377,7 +378,7 @@ pub(crate) async fn supervise(
|
|||
tokio::spawn(drain_stdout(runtime_stdout, session_id));
|
||||
|
||||
let bridge_token = registry.lock().await.bridge_token(session_id);
|
||||
let mut app_shell = match spawn_app_shell(&shell_bin, session_id, app_id, &token, bridge_token)
|
||||
let mut app_shell = match spawn_app_shell(&shell_bin, session_id, &package, &token, bridge_token)
|
||||
{
|
||||
Ok(child) => child,
|
||||
Err(e) => {
|
||||
|
|
@ -438,7 +439,12 @@ pub(crate) async fn supervise(
|
|||
}
|
||||
|
||||
/// Marks a session that never started any process as stopped.
|
||||
async fn stop_unstarted(registry: &Registry, session_id: u64) -> anyhow::Result<()> {
|
||||
async fn stop_unstarted(
|
||||
registry: &Registry,
|
||||
session_id: u64,
|
||||
image: Option<Mount>,
|
||||
) -> anyhow::Result<()> {
|
||||
release_image(image).await;
|
||||
let mut reg = registry.lock().await;
|
||||
reg.set_state(session_id, AppStateKind::Stopped);
|
||||
reg.remove_abort_sender(session_id);
|
||||
|
|
@ -458,7 +464,8 @@ struct OwnedSession {
|
|||
app_shell: Option<tokio::process::Child>,
|
||||
portal: Option<(PathBuf, tokio::process::Child)>,
|
||||
relay: Option<IpcRelay>,
|
||||
mount: crate::mount::MountOrchestrator,
|
||||
/// The mounted package image, released after both children have exited.
|
||||
image: Option<Mount>,
|
||||
compositor_tx: Option<CompositorSender>,
|
||||
surface_announced: bool,
|
||||
}
|
||||
|
|
@ -480,7 +487,7 @@ impl OwnedSession {
|
|||
"compositor queue unavailable; surface not released"
|
||||
);
|
||||
}
|
||||
self.mount.umount();
|
||||
release_image(self.image).await;
|
||||
kill_portal(self.portal).await;
|
||||
drop(self.relay);
|
||||
let mut reg = registry.lock().await;
|
||||
|
|
@ -495,6 +502,13 @@ impl OwnedSession {
|
|||
}
|
||||
}
|
||||
|
||||
/// Unmounts a package image without blocking the async workers.
|
||||
async fn release_image(image: Option<Mount>) {
|
||||
if let Some(image) = image {
|
||||
let _ = tokio::task::spawn_blocking(move || drop(image)).await;
|
||||
}
|
||||
}
|
||||
|
||||
async fn kill_child(child: Option<tokio::process::Child>) {
|
||||
if let Some(mut child) = child {
|
||||
let _ = child.kill().await;
|
||||
|
|
|
|||
|
|
@ -11,6 +11,7 @@ path = "src/lib.rs"
|
|||
[dependencies]
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
rmp-serde = "1"
|
||||
toml = "0.8"
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
pub mod capability;
|
||||
pub mod manifest;
|
||||
pub mod package;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
|
|
|||
218
crates/weft-ipc-types/src/manifest.rs
Normal file
218
crates/weft-ipc-types/src/manifest.rs
Normal file
|
|
@ -0,0 +1,218 @@
|
|||
//! The package manifest, `wapp.toml`, and the package files it names.
|
||||
//!
|
||||
//! This is the one parser for manifests: the packaging tool validates
|
||||
//! packages with it and the session supervisor resolves launches with it.
|
||||
|
||||
use std::fmt;
|
||||
use std::path::{Component, Path, PathBuf};
|
||||
|
||||
use serde::Deserialize;
|
||||
|
||||
/// The manifest's file name at the root of a package.
|
||||
pub const MANIFEST_FILE: &str = "wapp.toml";
|
||||
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
pub struct Manifest {
|
||||
pub package: PackageMeta,
|
||||
pub runtime: RuntimeMeta,
|
||||
pub ui: UiMeta,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
pub struct PackageMeta {
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
pub version: String,
|
||||
pub description: Option<String>,
|
||||
pub author: Option<String>,
|
||||
pub capabilities: Option<Vec<String>>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
pub struct RuntimeMeta {
|
||||
/// The Wasm component, relative to the package root.
|
||||
pub module: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
pub struct UiMeta {
|
||||
/// The UI document, relative to the package root.
|
||||
pub entry: String,
|
||||
}
|
||||
|
||||
/// Why a manifest could not be read.
|
||||
#[derive(Debug)]
|
||||
pub enum ManifestError {
|
||||
Io(PathBuf, std::io::Error),
|
||||
Parse(PathBuf, toml::de::Error),
|
||||
}
|
||||
|
||||
impl fmt::Display for ManifestError {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
Self::Io(path, e) => write!(f, "cannot read {}: {e}", path.display()),
|
||||
Self::Parse(path, e) => write!(f, "invalid {}: {e}", path.display()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for ManifestError {}
|
||||
|
||||
impl Manifest {
|
||||
/// Reads `<package_root>/wapp.toml`.
|
||||
pub fn read(package_root: &Path) -> Result<Self, ManifestError> {
|
||||
let path = package_root.join(MANIFEST_FILE);
|
||||
let text = std::fs::read_to_string(&path).map_err(|e| ManifestError::Io(path.clone(), e))?;
|
||||
toml::from_str(&text).map_err(|e| ManifestError::Parse(path, e))
|
||||
}
|
||||
|
||||
pub fn capabilities(&self) -> &[String] {
|
||||
self.package.capabilities.as_deref().unwrap_or_default()
|
||||
}
|
||||
}
|
||||
|
||||
/// Why a manifest entry does not name a usable package file.
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub enum EntryError {
|
||||
/// The entry is empty, absolute, or has `.` or `..` components.
|
||||
NotContained(String),
|
||||
/// A component of the entry is a symbolic link.
|
||||
Link(String),
|
||||
/// The entry does not exist, or is not a regular file.
|
||||
NotAFile(String),
|
||||
}
|
||||
|
||||
impl fmt::Display for EntryError {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
Self::NotContained(entry) => {
|
||||
write!(f, "'{entry}' is not a relative path inside the package")
|
||||
}
|
||||
Self::Link(entry) => write!(f, "'{entry}' passes through a symbolic link"),
|
||||
Self::NotAFile(entry) => write!(f, "'{entry}' is not a file in the package"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for EntryError {}
|
||||
|
||||
/// The package file a manifest entry names: `entry` must be a relative path
|
||||
/// of plain components, none of them a symbolic link, ending at a regular
|
||||
/// file inside `package_root`.
|
||||
pub fn entry_path(package_root: &Path, entry: &str) -> Result<PathBuf, EntryError> {
|
||||
let relative = Path::new(entry);
|
||||
let mut components = relative.components().peekable();
|
||||
if components.peek().is_none()
|
||||
|| !relative
|
||||
.components()
|
||||
.all(|c| matches!(c, Component::Normal(_)))
|
||||
{
|
||||
return Err(EntryError::NotContained(entry.to_owned()));
|
||||
}
|
||||
let mut path = package_root.to_path_buf();
|
||||
while let Some(component) = components.next() {
|
||||
path.push(component);
|
||||
let metadata = std::fs::symlink_metadata(&path)
|
||||
.map_err(|_| EntryError::NotAFile(entry.to_owned()))?;
|
||||
if metadata.file_type().is_symlink() {
|
||||
return Err(EntryError::Link(entry.to_owned()));
|
||||
}
|
||||
let last = components.peek().is_none();
|
||||
if (last && !metadata.is_file()) || (!last && !metadata.is_dir()) {
|
||||
return Err(EntryError::NotAFile(entry.to_owned()));
|
||||
}
|
||||
}
|
||||
Ok(path)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn package(name: &str) -> PathBuf {
|
||||
let dir = std::env::temp_dir().join(format!(
|
||||
"weft_manifest_{name}_{}",
|
||||
std::process::id()
|
||||
));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(dir.join("ui")).unwrap();
|
||||
std::fs::write(dir.join("app.wasm"), b"\0asm").unwrap();
|
||||
std::fs::write(dir.join("ui/index.html"), b"<p>").unwrap();
|
||||
dir
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn entries_resolve_to_package_files() {
|
||||
let dir = package("files");
|
||||
assert_eq!(entry_path(&dir, "app.wasm").unwrap(), dir.join("app.wasm"));
|
||||
assert_eq!(
|
||||
entry_path(&dir, "ui/index.html").unwrap(),
|
||||
dir.join("ui/index.html")
|
||||
);
|
||||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn entries_must_stay_inside_the_package() {
|
||||
let dir = package("contained");
|
||||
for entry in ["", "/etc/passwd", "../app.wasm", "ui/../app.wasm", "./app.wasm"] {
|
||||
assert_eq!(
|
||||
entry_path(&dir, entry),
|
||||
Err(EntryError::NotContained(entry.to_owned())),
|
||||
"{entry:?}"
|
||||
);
|
||||
}
|
||||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn entries_must_name_existing_regular_files() {
|
||||
let dir = package("kinds");
|
||||
for entry in ["missing.wasm", "ui", "app.wasm/x"] {
|
||||
assert_eq!(
|
||||
entry_path(&dir, entry),
|
||||
Err(EntryError::NotAFile(entry.to_owned())),
|
||||
"{entry:?}"
|
||||
);
|
||||
}
|
||||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn entries_never_follow_links() {
|
||||
let dir = package("links");
|
||||
std::os::unix::fs::symlink(dir.join("app.wasm"), dir.join("linked.wasm")).unwrap();
|
||||
std::os::unix::fs::symlink(dir.join("ui"), dir.join("view")).unwrap();
|
||||
assert_eq!(
|
||||
entry_path(&dir, "linked.wasm"),
|
||||
Err(EntryError::Link("linked.wasm".to_owned()))
|
||||
);
|
||||
assert_eq!(
|
||||
entry_path(&dir, "view/index.html"),
|
||||
Err(EntryError::Link("view/index.html".to_owned()))
|
||||
);
|
||||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn manifests_parse_with_their_entries() {
|
||||
let dir = package("parse");
|
||||
std::fs::write(
|
||||
dir.join(MANIFEST_FILE),
|
||||
"[package]\nid = \"org.weft.test\"\nname = \"T\"\nversion = \"1.0.0\"\n\
|
||||
capabilities = [\"sys:notifications\"]\n\
|
||||
[runtime]\nmodule = \"app.wasm\"\n[ui]\nentry = \"ui/index.html\"\n",
|
||||
)
|
||||
.unwrap();
|
||||
let manifest = Manifest::read(&dir).unwrap();
|
||||
assert_eq!(manifest.package.id, "org.weft.test");
|
||||
assert_eq!(manifest.capabilities(), ["sys:notifications"]);
|
||||
std::fs::write(dir.join(MANIFEST_FILE), "[package]\nid = \"x\"\n").unwrap();
|
||||
assert!(matches!(
|
||||
Manifest::read(&dir),
|
||||
Err(ManifestError::Parse(..))
|
||||
));
|
||||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
}
|
||||
|
|
@ -17,6 +17,40 @@ pub fn is_valid_app_id(id: &str) -> bool {
|
|||
})
|
||||
}
|
||||
|
||||
/// The files of a verified package image in a package store: the EROFS
|
||||
/// image, its dm-verity hash tree and the hex root hash, named after the
|
||||
/// application ID. `weft-pack build-image` and `build-verity` produce these
|
||||
/// names and the supervisor looks for them.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct ImageFiles {
|
||||
pub image: PathBuf,
|
||||
pub hash_tree: PathBuf,
|
||||
pub root_hash: PathBuf,
|
||||
}
|
||||
|
||||
impl ImageFiles {
|
||||
pub fn in_store(store_root: &Path, app_id: &str) -> Self {
|
||||
Self::for_image(&store_root.join(format!("{app_id}.app.img")))
|
||||
}
|
||||
|
||||
/// The companions of `image`, named by replacing its extension.
|
||||
pub fn for_image(image: &Path) -> Self {
|
||||
Self {
|
||||
image: image.to_path_buf(),
|
||||
hash_tree: image.with_extension("hash"),
|
||||
root_hash: image.with_extension("roothash"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether any of the three files is present, whether or not it is
|
||||
/// usable.
|
||||
pub fn any_present(&self) -> bool {
|
||||
[&self.image, &self.hash_tree, &self.root_hash]
|
||||
.iter()
|
||||
.any(|path| std::fs::symlink_metadata(path).is_ok())
|
||||
}
|
||||
}
|
||||
|
||||
/// The user's data home: `$XDG_DATA_HOME` when it is an absolute path,
|
||||
/// otherwise `$HOME/.local/share`.
|
||||
pub fn data_home() -> Option<PathBuf> {
|
||||
|
|
@ -181,6 +215,18 @@ pub fn make_private(dir: &Path) -> std::io::Result<()> {
|
|||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn image_companions_share_the_image_name() {
|
||||
let files = ImageFiles::in_store(Path::new("/store"), "org.weft.demo.notes");
|
||||
assert_eq!(files.image, Path::new("/store/org.weft.demo.notes.app.img"));
|
||||
assert_eq!(files.hash_tree, Path::new("/store/org.weft.demo.notes.app.hash"));
|
||||
assert_eq!(
|
||||
files.root_hash,
|
||||
Path::new("/store/org.weft.demo.notes.app.roothash")
|
||||
);
|
||||
assert_eq!(ImageFiles::for_image(&files.image), files);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn app_ids() {
|
||||
assert!(is_valid_app_id("org.weft.demo"));
|
||||
|
|
|
|||
|
|
@ -54,20 +54,21 @@ fn require_root() -> anyhow::Result<()> {
|
|||
}
|
||||
}
|
||||
|
||||
/// The device-mapper name for an image mounted at `mountpoint`: `weft-`
|
||||
/// followed by the mountpoint's last component. weft-appd names each
|
||||
/// mountpoint with a random token, so concurrent sessions get distinct
|
||||
/// devices. Device-mapper names are limited to 127 bytes.
|
||||
fn device_name(mountpoint: &Path) -> String {
|
||||
let s = mountpoint.to_string_lossy();
|
||||
let sanitized: String = s
|
||||
let leaf = mountpoint
|
||||
.file_name()
|
||||
.map(|name| name.to_string_lossy())
|
||||
.unwrap_or_default();
|
||||
let sanitized: String = leaf
|
||||
.chars()
|
||||
.map(|c| if c.is_ascii_alphanumeric() { c } else { '-' })
|
||||
.take(120)
|
||||
.collect();
|
||||
let suffix: String = sanitized
|
||||
.trim_matches('-')
|
||||
.chars()
|
||||
.take(26)
|
||||
.collect::<String>()
|
||||
.trim_end_matches('-')
|
||||
.to_string();
|
||||
format!("weft-{suffix}")
|
||||
format!("weft-{sanitized}")
|
||||
}
|
||||
|
||||
fn cmd_mount(
|
||||
|
|
@ -145,18 +146,20 @@ mod tests {
|
|||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn device_name_sanitizes_path() {
|
||||
let mp = Path::new("/run/weft/mounts/com.example.myapp");
|
||||
let name = device_name(mp);
|
||||
assert!(name.starts_with("weft-"));
|
||||
assert!(name.chars().all(|c| c.is_ascii_alphanumeric() || c == '-'));
|
||||
assert!(name.len() <= 31);
|
||||
fn device_names_follow_the_mountpoint_name() {
|
||||
let name = device_name(Path::new("/run/user/1000/weft/mnt/0123abcd"));
|
||||
assert_eq!(name, "weft-0123abcd");
|
||||
assert_ne!(
|
||||
device_name(Path::new("/run/user/1000/weft/mnt/aaaa")),
|
||||
device_name(Path::new("/run/user/1000/weft/mnt/bbbb"))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn device_name_truncates_long_paths() {
|
||||
let mp = Path::new("/run/weft/mounts/com.example.averylongappidthatexceedsthemaximum");
|
||||
let name = device_name(mp);
|
||||
assert!(name.len() <= 31);
|
||||
fn device_names_are_sanitized_and_bounded() {
|
||||
let long = format!("/mnt/{}", "x.y".repeat(100));
|
||||
let name = device_name(Path::new(&long));
|
||||
assert!(name.len() <= 127);
|
||||
assert!(name.chars().all(|c| c.is_ascii_alphanumeric() || c == '-'));
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -11,8 +11,6 @@ path = "src/main.rs"
|
|||
[dependencies]
|
||||
weft-ipc-types = { path = "../weft-ipc-types" }
|
||||
anyhow = "1.0"
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
toml = "0.8"
|
||||
ed25519-dalek = { version = "2", features = ["rand_core"] }
|
||||
sha2 = "0.10"
|
||||
rand = "0.8"
|
||||
|
|
|
|||
|
|
@ -1,34 +1,8 @@
|
|||
use std::path::{Path, PathBuf};
|
||||
|
||||
use anyhow::Context;
|
||||
use serde::Deserialize;
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct Manifest {
|
||||
package: PackageMeta,
|
||||
runtime: RuntimeMeta,
|
||||
ui: UiMeta,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct PackageMeta {
|
||||
id: String,
|
||||
name: String,
|
||||
version: String,
|
||||
description: Option<String>,
|
||||
author: Option<String>,
|
||||
capabilities: Option<Vec<String>>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct RuntimeMeta {
|
||||
module: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct UiMeta {
|
||||
entry: String,
|
||||
}
|
||||
use weft_ipc_types::manifest::{Manifest, entry_path};
|
||||
use weft_ipc_types::package::ImageFiles;
|
||||
|
||||
fn main() -> anyhow::Result<()> {
|
||||
let args: Vec<String> = std::env::args().collect();
|
||||
|
|
@ -177,22 +151,17 @@ fn check_package(dir: &Path) -> anyhow::Result<String> {
|
|||
));
|
||||
}
|
||||
|
||||
let wasm_path = dir.join(&m.runtime.module);
|
||||
if !wasm_path.exists() {
|
||||
errors.push(format!(
|
||||
"runtime.module '{}' not found",
|
||||
wasm_path.display()
|
||||
));
|
||||
} else if !is_wasm_module(&wasm_path) {
|
||||
errors.push(format!(
|
||||
match entry_path(dir, &m.runtime.module) {
|
||||
Err(e) => errors.push(format!("runtime.module: {e}")),
|
||||
Ok(wasm_path) if !is_wasm_module(&wasm_path) => errors.push(format!(
|
||||
"runtime.module '{}' is not a valid Wasm module (bad magic bytes)",
|
||||
wasm_path.display()
|
||||
));
|
||||
)),
|
||||
Ok(_) => {}
|
||||
}
|
||||
|
||||
let ui_path = dir.join(&m.ui.entry);
|
||||
if !ui_path.exists() {
|
||||
errors.push(format!("ui.entry '{}' not found", ui_path.display()));
|
||||
if let Err(e) = entry_path(dir, &m.ui.entry) {
|
||||
errors.push(format!("ui.entry: {e}"));
|
||||
}
|
||||
|
||||
for cap in m.package.capabilities.iter().flatten() {
|
||||
|
|
@ -210,10 +179,7 @@ fn check_package(dir: &Path) -> anyhow::Result<String> {
|
|||
}
|
||||
|
||||
fn load_manifest(dir: &Path) -> anyhow::Result<Manifest> {
|
||||
let manifest_path = dir.join("wapp.toml");
|
||||
let text = std::fs::read_to_string(&manifest_path)
|
||||
.with_context(|| format!("read {}", manifest_path.display()))?;
|
||||
toml::from_str(&text).with_context(|| format!("parse {}", manifest_path.display()))
|
||||
Ok(Manifest::read(dir)?)
|
||||
}
|
||||
|
||||
fn print_info(m: &Manifest) {
|
||||
|
|
@ -447,11 +413,7 @@ fn list_installed() {
|
|||
};
|
||||
let mut pkgs: Vec<(String, String, String)> = Vec::new();
|
||||
for entry in entries.flatten() {
|
||||
let manifest_path = entry.path().join("wapp.toml");
|
||||
let Ok(contents) = std::fs::read_to_string(&manifest_path) else {
|
||||
continue;
|
||||
};
|
||||
let Ok(m) = toml::from_str::<Manifest>(&contents) else {
|
||||
let Ok(m) = Manifest::read(&entry.path()) else {
|
||||
continue;
|
||||
};
|
||||
if seen.insert(m.package.id.clone()) {
|
||||
|
|
@ -488,10 +450,9 @@ fn copy_dir(src: &Path, dst: &Path) -> anyhow::Result<()> {
|
|||
fn build_image(dir: &Path, out_path: Option<&Path>) -> anyhow::Result<()> {
|
||||
let manifest = load_manifest(dir)?;
|
||||
let app_id = &manifest.package.id;
|
||||
let default_name = format!("{app_id}.app.img");
|
||||
let output = match out_path {
|
||||
Some(p) => p.to_path_buf(),
|
||||
None => PathBuf::from(&default_name),
|
||||
None => ImageFiles::in_store(Path::new(""), app_id).image,
|
||||
};
|
||||
if output.exists() {
|
||||
anyhow::bail!("{} already exists", output.display());
|
||||
|
|
@ -509,9 +470,10 @@ fn build_image(dir: &Path, out_path: Option<&Path>) -> anyhow::Result<()> {
|
|||
}
|
||||
|
||||
fn build_verity(img: &Path, hash_out: Option<&Path>) -> anyhow::Result<()> {
|
||||
let stem = img.file_stem().context("no file stem")?.to_string_lossy();
|
||||
let default_hash = img.with_file_name(format!("{stem}.hash"));
|
||||
let hash_path = hash_out.map(|p| p.to_path_buf()).unwrap_or(default_hash);
|
||||
let companions = ImageFiles::for_image(img);
|
||||
let hash_path = hash_out
|
||||
.map(|p| p.to_path_buf())
|
||||
.unwrap_or(companions.hash_tree);
|
||||
if hash_path.exists() {
|
||||
anyhow::bail!("{} already exists", hash_path.display());
|
||||
}
|
||||
|
|
@ -535,7 +497,7 @@ fn build_verity(img: &Path, hash_out: Option<&Path>) -> anyhow::Result<()> {
|
|||
.find(|l| l.starts_with("Root hash:"))
|
||||
.context("root hash not found in veritysetup output")?;
|
||||
let hash_value = root_hash.trim_start_matches("Root hash:").trim();
|
||||
let roothash_path = img.with_extension("roothash");
|
||||
let roothash_path = companions.root_hash;
|
||||
std::fs::write(&roothash_path, hash_value)
|
||||
.with_context(|| format!("write {}", roothash_path.display()))?;
|
||||
println!("hash image: {}", hash_path.display());
|
||||
|
|
@ -1304,6 +1266,30 @@ entry = "ui/index.html"
|
|||
.unwrap();
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn check_package_refuses_entries_outside_the_package() {
|
||||
let tmp = std::env::temp_dir().join(format!("weft_pack_entries_{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&tmp);
|
||||
make_valid_package(&tmp, "com.example.entries", "");
|
||||
std::fs::write(tmp.with_extension("wasm"), b"\0asm\x01\0\0\0").unwrap();
|
||||
std::os::unix::fs::symlink("index.html", tmp.join("ui/linked.html")).unwrap();
|
||||
let manifest = std::fs::read_to_string(tmp.join("wapp.toml")).unwrap();
|
||||
let escaping = format!("../{}", tmp.with_extension("wasm").file_name().unwrap().display());
|
||||
std::fs::write(
|
||||
tmp.join("wapp.toml"),
|
||||
manifest
|
||||
.replace("module = \"app.wasm\"", &format!("module = \"{escaping}\""))
|
||||
.replace("ui/index.html", "ui/linked.html"),
|
||||
)
|
||||
.unwrap();
|
||||
let msg = check_package(&tmp).unwrap_err().to_string();
|
||||
let _ = std::fs::remove_dir_all(&tmp);
|
||||
let _ = std::fs::remove_file(tmp.with_extension("wasm"));
|
||||
assert!(msg.contains("runtime.module") && msg.contains("not a relative path"), "{msg}");
|
||||
assert!(msg.contains("ui.entry") && msg.contains("symbolic link"), "{msg}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn check_package_unknown_capability_errors() {
|
||||
let tmp = std::env::temp_dir().join(format!("weft_pack_caps_bad_{}", std::process::id()));
|
||||
|
|
|
|||
|
|
@ -17,7 +17,7 @@ fn main() -> anyhow::Result<()> {
|
|||
let args: Vec<String> = std::env::args().collect();
|
||||
if args.len() < 3 {
|
||||
anyhow::bail!(
|
||||
"usage: weft-runtime <app_id> <session_id> \
|
||||
"usage: weft-runtime <app_id> <session_id> --module PATH \
|
||||
[--preopen HOST::GUEST::ro|rw]... [--grant CAPABILITY]... [--ipc-socket PATH]"
|
||||
);
|
||||
}
|
||||
|
|
@ -29,6 +29,7 @@ fn main() -> anyhow::Result<()> {
|
|||
let mut preopen: Vec<Preopen> = Vec::new();
|
||||
let mut grants = Grants::default();
|
||||
let mut ipc_socket: Option<String> = None;
|
||||
let mut module: Option<PathBuf> = None;
|
||||
|
||||
let mut i = 3usize;
|
||||
while i < args.len() {
|
||||
|
|
@ -42,6 +43,12 @@ fn main() -> anyhow::Result<()> {
|
|||
i += 1;
|
||||
grants.add(args.get(i).context("--grant requires an argument")?)?;
|
||||
}
|
||||
"--module" => {
|
||||
i += 1;
|
||||
module = Some(PathBuf::from(
|
||||
args.get(i).context("--module requires an argument")?,
|
||||
));
|
||||
}
|
||||
"--ipc-socket" => {
|
||||
i += 1;
|
||||
ipc_socket = Some(
|
||||
|
|
@ -60,13 +67,9 @@ fn main() -> anyhow::Result<()> {
|
|||
|
||||
tracing::info!(session_id, %app_id, "weft-runtime starting");
|
||||
|
||||
let pkg_dir = resolve_package(app_id)?;
|
||||
tracing::info!(path = %pkg_dir.display(), "package resolved");
|
||||
|
||||
let wasm_path = pkg_dir.join("app.wasm");
|
||||
if !wasm_path.exists() {
|
||||
anyhow::bail!("app.wasm not found at {}", wasm_path.display());
|
||||
}
|
||||
// weft-appd resolves the package and passes the component it selected;
|
||||
// the runtime never looks for the package itself.
|
||||
let wasm_path = module.context("--module is required")?;
|
||||
|
||||
tracing::info!(session_id, %app_id, wasm = %wasm_path.display(), "executing module");
|
||||
run_module(&wasm_path, &preopen, grants, ipc_socket.as_deref())?;
|
||||
|
|
@ -85,17 +88,6 @@ fn ready_line() -> String {
|
|||
}
|
||||
}
|
||||
|
||||
fn resolve_package(app_id: &str) -> anyhow::Result<PathBuf> {
|
||||
for store_root in package_store_roots() {
|
||||
let pkg_dir = store_root.join(app_id);
|
||||
let manifest = pkg_dir.join("wapp.toml");
|
||||
if manifest.exists() {
|
||||
return Ok(pkg_dir);
|
||||
}
|
||||
}
|
||||
anyhow::bail!("package '{}' not found in any package store", app_id)
|
||||
}
|
||||
|
||||
#[cfg(not(feature = "wasmtime-runtime"))]
|
||||
fn run_module(
|
||||
_wasm_path: &std::path::Path,
|
||||
|
|
@ -599,28 +591,6 @@ fn apply_seccomp_filter() -> anyhow::Result<()> {
|
|||
Ok(())
|
||||
}
|
||||
|
||||
fn package_store_roots() -> Vec<PathBuf> {
|
||||
if let Ok(explicit) = std::env::var("WEFT_APP_STORE") {
|
||||
return vec![PathBuf::from(explicit)];
|
||||
}
|
||||
|
||||
let mut roots = Vec::new();
|
||||
|
||||
if let Ok(home) = std::env::var("HOME") {
|
||||
roots.push(
|
||||
PathBuf::from(home)
|
||||
.join(".local")
|
||||
.join("share")
|
||||
.join("weft")
|
||||
.join("apps"),
|
||||
);
|
||||
}
|
||||
|
||||
roots.push(PathBuf::from("/usr/share/weft/apps"));
|
||||
|
||||
roots
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
|
@ -637,75 +607,4 @@ mod tests {
|
|||
.expect_err("a build without wasmtime-runtime must not report success");
|
||||
assert!(err.to_string().contains("wasmtime-runtime"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn package_store_roots_includes_system_path() {
|
||||
let roots = package_store_roots();
|
||||
assert!(
|
||||
roots
|
||||
.iter()
|
||||
.any(|p| p == &PathBuf::from("/usr/share/weft/apps"))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn package_store_roots_uses_weft_app_store_when_set() {
|
||||
// SAFETY: test binary is single-threaded at this point.
|
||||
unsafe { std::env::set_var("WEFT_APP_STORE", "/custom/store") };
|
||||
let roots = package_store_roots();
|
||||
assert_eq!(roots, vec![PathBuf::from("/custom/store")]);
|
||||
unsafe { std::env::remove_var("WEFT_APP_STORE") };
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resolve_package_finds_installed_package() {
|
||||
use std::fs;
|
||||
let store =
|
||||
std::env::temp_dir().join(format!("weft_runtime_resolve_{}", std::process::id()));
|
||||
let pkg_dir = store.join("com.example.resolve");
|
||||
fs::create_dir_all(&pkg_dir).unwrap();
|
||||
fs::write(
|
||||
pkg_dir.join("wapp.toml"),
|
||||
"[package]\nid=\"com.example.resolve\"\n",
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let prior = std::env::var("WEFT_APP_STORE").ok();
|
||||
unsafe { std::env::set_var("WEFT_APP_STORE", &store) };
|
||||
|
||||
let result = resolve_package("com.example.resolve");
|
||||
|
||||
unsafe {
|
||||
match prior {
|
||||
Some(v) => std::env::set_var("WEFT_APP_STORE", v),
|
||||
None => std::env::remove_var("WEFT_APP_STORE"),
|
||||
}
|
||||
}
|
||||
let _ = fs::remove_dir_all(&store);
|
||||
|
||||
assert!(result.is_ok());
|
||||
assert!(result.unwrap().ends_with("com.example.resolve"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resolve_package_errors_on_unknown_id() {
|
||||
let store =
|
||||
std::env::temp_dir().join(format!("weft_runtime_resolve_empty_{}", std::process::id()));
|
||||
let _ = std::fs::create_dir_all(&store);
|
||||
|
||||
let prior = std::env::var("WEFT_APP_STORE").ok();
|
||||
unsafe { std::env::set_var("WEFT_APP_STORE", &store) };
|
||||
|
||||
let result = resolve_package("com.does.not.exist");
|
||||
|
||||
unsafe {
|
||||
match prior {
|
||||
Some(v) => std::env::set_var("WEFT_APP_STORE", v),
|
||||
None => std::env::remove_var("WEFT_APP_STORE"),
|
||||
}
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(&store);
|
||||
|
||||
assert!(result.is_err());
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -16,15 +16,15 @@ System UI host. Renders one WebView pointing at `system-ui.html` using the embed
|
|||
|
||||
### weft-app-shell
|
||||
|
||||
Per-application Servo host. Spawned by `weft-appd` after the Wasm runtime signals READY. Takes `<app_id>` and `<session_id>` as arguments. Resolves `weft-app://<app_id>/ui/index.html` and injects the `weftIpc` WebSocket bridge into the page. The bridge authenticates with the per-session token from `WEFT_BRIDGE_TOKEN` and can only exchange messages with its own session. It is installed only in top-level documents inside the application's UI directory, and top-level navigation outside that directory is denied; framed documents never receive the bridge. Every resource the page loads (subresources, `fetch()`, XHR, redirects and WebSocket handshakes) is checked by the shell: the page may load files inside its UI directory, inline `data:`, `blob:` and `about:` resources, and the session bridge; any other local file or network destination fails with a network error. Network access belongs to the Wasm component, under its fetch grants. Registers with the compositor as window type `application`. Exits when the appd session ends.
|
||||
Per-application Servo host. Spawned by `weft-appd` after the Wasm runtime signals READY. Takes `<app_id>`, `<session_id>` and `--ui <path>`, the UI document weft-appd resolved from the package; it never looks for the package itself. Injects the `weftIpc` WebSocket bridge into the page. The bridge authenticates with the per-session token from `WEFT_BRIDGE_TOKEN` and can only exchange messages with its own session. It is installed only in top-level documents inside the application's UI directory, and top-level navigation outside that directory is denied; framed documents never receive the bridge. Every resource the page loads (subresources, `fetch()`, XHR, redirects and WebSocket handshakes) is checked by the shell: the page may load files inside its UI directory, inline `data:`, `blob:` and `about:` resources, and the session bridge; any other local file or network destination fails with a network error. Network access belongs to the Wasm component, under its fetch grants. Registers with the compositor as window type `application`. Exits when the appd session ends.
|
||||
|
||||
### weft-appd
|
||||
|
||||
Session supervisor. Listens on a Unix socket (MessagePack protocol) and a WebSocket port (JSON). For each session: spawns `weft-runtime` and waits for its READY, spawns `weft-app-shell` (`WEFT_APP_SHELL_BIN` is required) and waits for its READY, and only then reports the session running (`APP_READY`). A child reports readiness by printing `READY <token>` on stdout, where the token is a random per-session value appd passes in `WEFT_READY_TOKEN`; Wasm guests and pages share those stdout streams but cannot read the token, so their output cannot fake readiness. Each wait times out after 30 seconds. If either child fails to start, fails to become ready or exits, or the session is terminated, the whole session is stopped: both children, the IPC relay (its task, socket and registered sender), the file portal, the compositor association and any image mount are released. The IPC relay is created with the session in `$XDG_RUNTIME_DIR/weft` (a session cannot start without it); its socket is accessible only to the user and accepts a single connection, which the session's runtime makes before it starts the component. If that connection closes while the session runs, the session is stopped. `IPC_FORWARD` on the Unix socket never waits: it reports an error when the session has no relay or its queue is full. appd applies cgroup resource limits to the runtime via systemd-run when available.
|
||||
Session supervisor. Listens on a Unix socket (MessagePack protocol) and a WebSocket port (JSON). Before a session exists, appd resolves the package once (see [Package resolution](#package-resolution)) and derives its grants from that package's manifest; the runtime and the app shell receive the resolved component and UI document and do not search the stores themselves. For each session: spawns `weft-runtime` and waits for its READY, spawns `weft-app-shell` (`WEFT_APP_SHELL_BIN` is required) and waits for its READY, and only then reports the session running (`APP_READY`). A child reports readiness by printing `READY <token>` on stdout, where the token is a random per-session value appd passes in `WEFT_READY_TOKEN`; Wasm guests and pages share those stdout streams but cannot read the token, so their output cannot fake readiness. Each wait times out after 30 seconds. If either child fails to start, fails to become ready or exits, or the session is terminated, the whole session is stopped: both children, the IPC relay (its task, socket and registered sender), the file portal, the compositor association and any image mount are released. The IPC relay is created with the session in `$XDG_RUNTIME_DIR/weft` (a session cannot start without it); its socket is accessible only to the user and accepts a single connection, which the session's runtime makes before it starts the component. If that connection closes while the session runs, the session is stopped. `IPC_FORWARD` on the Unix socket never waits: it reports an error when the session has no relay or its queue is full. appd applies cgroup resource limits to the runtime via systemd-run when available.
|
||||
|
||||
### weft-runtime
|
||||
|
||||
WASI Preview 2 + Component Model execution host (Wasmtime 30). Loads `app.wasm` from the installed package directory. Provides host imports for `weft:app/notify`, `weft:app/ipc`, `weft:app/fetch`, `weft:app/notifications`, and `weft:app/clipboard`. Preopens filesystem paths according to capabilities declared in `wapp.toml`.
|
||||
WASI Preview 2 + Component Model execution host (Wasmtime 30). Runs the component weft-appd passes with `--module <path>`, the package's `[runtime].module`. Provides host imports for `weft:app/notify`, `weft:app/ipc`, `weft:app/fetch`, `weft:app/notifications`, and `weft:app/clipboard`. Preopens filesystem paths according to capabilities declared in `wapp.toml`.
|
||||
|
||||
### weft-pack
|
||||
|
||||
|
|
@ -36,7 +36,7 @@ Per-session file proxy. Runs as a separate process with a path allowlist derived
|
|||
|
||||
### weft-mount-helper
|
||||
|
||||
Setuid helper binary. Calls `veritysetup` and mounts EROFS images for dm-verity-protected packages.
|
||||
Setuid helper binary. Calls `veritysetup` and mounts EROFS images for dm-verity-protected packages. Its device-mapper device is named after the mountpoint, which weft-appd names with a random token in `$XDG_RUNTIME_DIR/weft/mnt`. The helper does not yet restrict its callers or the images and mountpoints they pass, so it is not part of a supported installation.
|
||||
|
||||
## Process Topology
|
||||
|
||||
|
|
@ -46,8 +46,8 @@ systemd
|
|||
├── weft-servo-shell (user, after compositor)
|
||||
└── weft-appd (user, after compositor + servo-shell)
|
||||
└── per-session:
|
||||
├── weft-runtime <app_id> <session_id> [--preopen HOST::GUEST::ro|rw]... [--grant CAP]... [--ipc-socket ...]
|
||||
├── weft-app-shell <app_id> <session_id>
|
||||
├── weft-runtime <app_id> <session_id> --ipc-socket <path> --module <path> [--preopen HOST::GUEST::ro|rw]... [--grant CAP]...
|
||||
├── weft-app-shell <app_id> <session_id> --ui <path>
|
||||
└── weft-file-portal <socket> [--allow ...] [--allow-read ...]
|
||||
```
|
||||
|
||||
|
|
@ -110,6 +110,17 @@ Package store roots (in priority order):
|
|||
2. `~/.local/share/weft/apps/`
|
||||
3. `/usr/share/weft/apps/`
|
||||
|
||||
### Package resolution
|
||||
|
||||
`weft-appd` resolves a launch once, in the first store root that holds the app:
|
||||
|
||||
- **Verified image:** `<root>/<id>.app.img` with its dm-verity hash tree `<id>.app.hash` and root hash `<id>.app.roothash`, the names `weft-pack build-image` and `build-verity` produce. When any of the three exists, the image must mount through `weft-mount-helper`; a missing companion, a malformed root hash, a missing helper or a failed mount refuses the launch, and appd never falls back to a directory install. The mount belongs to the session and is released when the session stops.
|
||||
- **Directory install:** `<root>/<id>/wapp.toml`.
|
||||
|
||||
The manifest in the selected package root must declare the requested ID. `[runtime].module` and `[ui].entry` must be relative paths of plain components, without symbolic links, naming regular files inside that root. The component, the UI document and the capabilities all come from that one manifest. A refused launch reports 400 (invalid ID), 404 (not installed), 403 (invalid package) or 500 (the image cannot be used).
|
||||
|
||||
A directory install can still be changed by its owner while a session runs, and nothing verifies its content at launch.
|
||||
|
||||
## App data
|
||||
|
||||
Each app's private data lives in `$XDG_DATA_HOME/weft/app-data/<id>` (`~/.local/share/weft/app-data/<id>` by default), apart from installed packages. Installing, updating or uninstalling a package never removes it. `weft-appd` creates the directory when a session with an app-data capability starts and makes it accessible only to the user (mode 0700); a symbolic link in its place is refused rather than followed. `weft-appd` and `weft-pack` must run with the same `HOME` and `XDG_DATA_HOME` to agree on this location; the systemd unit allows `weft-appd` to write under `~/.local/share/weft`.
|
||||
|
|
|
|||
|
|
@ -8,8 +8,8 @@ inside the white quadrant. It exits non-zero when the frame never appears or
|
|||
does not match.
|
||||
|
||||
`--host system` runs weft-servo-shell with the page as its system UI.
|
||||
`--host app` installs the page as a package in a temporary app store and runs
|
||||
weft-app-shell for it. The host must print READY, and the page must be on
|
||||
`--host app` copies the page into a package's UI directory and runs
|
||||
weft-app-shell with it as the UI document, as weft-appd would. The host must print READY, and the page must be on
|
||||
screen within a short grace period after READY, because the compositor shows
|
||||
a presented frame slightly later. READY printed within that grace before the
|
||||
page is presented is therefore not detected. `--slow-style SECONDS` makes
|
||||
|
|
@ -85,23 +85,13 @@ APP_ID = "org.weft.test.frame"
|
|||
COMPOSITE_GRACE = 2.0
|
||||
|
||||
|
||||
def install_app(store, page):
|
||||
"""Install `page` as the UI entry of a minimal package and return the store root."""
|
||||
package = store / APP_ID
|
||||
def app_ui(package, page):
|
||||
"""Copy `page` into the UI directory of a package and return the UI
|
||||
document, the file weft-appd would pass to weft-app-shell."""
|
||||
(package / "ui").mkdir(parents=True)
|
||||
shutil.copyfile(page, package / "ui" / "index.html")
|
||||
(package / "wapp.toml").write_text(
|
||||
"[package]\n"
|
||||
f'id = "{APP_ID}"\n'
|
||||
'name = "Frame reference"\n'
|
||||
'version = "0.0.0"\n'
|
||||
"\n[runtime]\n"
|
||||
'module = "app.wasm"\n'
|
||||
"\n[ui]\n"
|
||||
'entry = "ui/index.html"\n',
|
||||
encoding="utf-8",
|
||||
)
|
||||
return store
|
||||
entry = package / "ui" / "index.html"
|
||||
shutil.copyfile(page, entry)
|
||||
return entry
|
||||
|
||||
|
||||
def slow_style(directory, delay):
|
||||
|
|
@ -178,11 +168,11 @@ def main(argv=None):
|
|||
shell = desktop.launch_client(
|
||||
"shell", [args.shell], {"WEFT_SYSTEM_UI_HTML": str(page.resolve())})
|
||||
else:
|
||||
store = install_app(desktop.runtime / "store", page)
|
||||
entry = app_ui(desktop.runtime / APP_ID, page)
|
||||
if args.slow_style:
|
||||
slow_style(store / APP_ID / "ui", args.slow_style)
|
||||
slow_style(entry.parent, args.slow_style)
|
||||
shell = desktop.launch_client(
|
||||
"shell", [args.shell, APP_ID, "1"], {"WEFT_APP_STORE": str(store)})
|
||||
"shell", [args.shell, APP_ID, "1", "--ui", str(entry)])
|
||||
problems, screenshot = watch(desktop, shell, args)
|
||||
except SessionError as error:
|
||||
print(error, file=sys.stderr)
|
||||
|
|
|
|||
|
|
@ -68,13 +68,7 @@ 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.module = work / "app.wasm"
|
||||
self.targets = work / "targets"
|
||||
self.targets.mkdir()
|
||||
(self.targets / "targets.txt").write_text(
|
||||
|
|
@ -84,11 +78,10 @@ class Runner:
|
|||
f"fetch-other-host http://localhost:{port}/ok\n")
|
||||
|
||||
def run(self, *arguments, expect_success=True):
|
||||
command = [str(self.runtime), APP_ID, "1",
|
||||
command = [str(self.runtime), APP_ID, "1", "--module", str(self.module),
|
||||
"--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"})
|
||||
env={"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 = {}
|
||||
|
|
@ -182,7 +175,7 @@ def main(argv=None):
|
|||
work = Path(tempfile.mkdtemp(prefix="weft-grants-"))
|
||||
try:
|
||||
runner = Runner(args.runtime, work, server.server_port)
|
||||
shutil.copy(probe, runner.package / "app.wasm")
|
||||
shutil.copy(probe, runner.module)
|
||||
data = work / "data"
|
||||
data.mkdir()
|
||||
check(runner, data)
|
||||
|
|
|
|||
Loading…
Reference in a new issue