mirror of
https://github.com/marcoallegretti/WEFT_OS.git
synced 2026-11-22 08:13:59 +00:00
Merge fix/resolve-verified-package: resolve each launch to one package and fail closed on images (#16)
weft-appd resolves each launch once: a verified image in any store wins over a directory install and must mount or the launch is refused, with no fallback to a mutable directory. The manifest must declare the requested ID and its entries must be contained regular files without links. weft-runtime receives --module and weft-app-shell --ui; neither searches the stores. Grants come from the same manifest and the mount belongs to the session. The manifest parser and image file names are shared through weft-ipc-types with weft-pack.
This commit is contained in:
commit
5c82b540e6
21 changed files with 1081 additions and 528 deletions
5
Cargo.lock
generated
5
Cargo.lock
generated
|
|
@ -10455,10 +10455,8 @@ version = "0.1.0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"anyhow",
|
"anyhow",
|
||||||
"bitflags 2.11.0",
|
"bitflags 2.11.0",
|
||||||
"serde",
|
|
||||||
"servo",
|
"servo",
|
||||||
"softbuffer",
|
"softbuffer",
|
||||||
"toml 0.8.23",
|
|
||||||
"tracing",
|
"tracing",
|
||||||
"tracing-subscriber",
|
"tracing-subscriber",
|
||||||
"wayland-backend",
|
"wayland-backend",
|
||||||
|
|
@ -10524,6 +10522,7 @@ dependencies = [
|
||||||
"rmp-serde",
|
"rmp-serde",
|
||||||
"rustix 1.1.4",
|
"rustix 1.1.4",
|
||||||
"serde",
|
"serde",
|
||||||
|
"toml 0.8.23",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
|
|
@ -10541,10 +10540,8 @@ dependencies = [
|
||||||
"ed25519-dalek",
|
"ed25519-dalek",
|
||||||
"hex",
|
"hex",
|
||||||
"rand 0.8.5",
|
"rand 0.8.5",
|
||||||
"serde",
|
|
||||||
"sha2",
|
"sha2",
|
||||||
"tar",
|
"tar",
|
||||||
"toml 0.8.23",
|
|
||||||
"weft-ipc-types",
|
"weft-ipc-types",
|
||||||
"zstd",
|
"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.
|
**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.
|
**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
|
# 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
|
# 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.
|
# 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]
|
[dependencies]
|
||||||
anyhow = "1.0"
|
anyhow = "1.0"
|
||||||
|
|
@ -22,8 +22,6 @@ wayland-client = "0.31"
|
||||||
wayland-backend = "0.3"
|
wayland-backend = "0.3"
|
||||||
wayland-scanner = "0.31"
|
wayland-scanner = "0.31"
|
||||||
bitflags = "2"
|
bitflags = "2"
|
||||||
serde = { version = "1", features = ["derive"], optional = true }
|
|
||||||
toml = { version = "0.8", optional = true }
|
|
||||||
|
|
||||||
[dependencies.servo]
|
[dependencies.servo]
|
||||||
git = "https://github.com/marcoallegretti/servo"
|
git = "https://github.com/marcoallegretti/servo"
|
||||||
|
|
|
||||||
|
|
@ -1,5 +1,4 @@
|
||||||
use std::num::NonZeroU32;
|
use std::num::NonZeroU32;
|
||||||
use std::path::PathBuf;
|
|
||||||
use std::rc::Rc;
|
use std::rc::Rc;
|
||||||
use std::sync::atomic::{AtomicBool, Ordering};
|
use std::sync::atomic::{AtomicBool, Ordering};
|
||||||
use std::sync::{Arc, Mutex};
|
use std::sync::{Arc, Mutex};
|
||||||
|
|
@ -666,73 +665,17 @@ fn resolve_weft_system_url(url: &ServoUrl) -> Option<ServoUrl> {
|
||||||
ServoUrl::parse(&format!("file://{}", file.display())).ok()
|
ServoUrl::parse(&format!("file://{}", file.display())).ok()
|
||||||
}
|
}
|
||||||
|
|
||||||
fn read_ui_entry(app_id: &str) -> Option<String> {
|
/// Shows the UI document `ui` of `app_id`, the file weft-appd resolved from
|
||||||
#[derive(serde::Deserialize)]
|
/// the package; the shell never looks for the package itself.
|
||||||
struct Ui {
|
pub fn run(
|
||||||
entry: String,
|
app_id: &str,
|
||||||
}
|
session_id: u64,
|
||||||
#[derive(serde::Deserialize)]
|
ws_port: u16,
|
||||||
struct Manifest {
|
ui: &std::path::Path,
|
||||||
ui: Ui,
|
) -> anyhow::Result<()> {
|
||||||
}
|
let url = ServoUrl::from_file_path(ui)
|
||||||
|
.map_err(|_| anyhow::anyhow!("{} is not an absolute path", ui.display()))?;
|
||||||
let erofs_manifest = std::path::Path::new("/run/weft/apps")
|
tracing::info!(%app_id, %url, "showing application UI");
|
||||||
.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}"))?;
|
|
||||||
|
|
||||||
let event_loop = EventLoop::<ServoWake>::with_user_event()
|
let event_loop = EventLoop::<ServoWake>::with_user_event()
|
||||||
.build()
|
.build()
|
||||||
|
|
|
||||||
|
|
@ -18,19 +18,22 @@ fn main() -> anyhow::Result<()> {
|
||||||
)
|
)
|
||||||
.init();
|
.init();
|
||||||
|
|
||||||
|
const USAGE: &str = "usage: weft-app-shell <app_id> <session_id> --ui <path>";
|
||||||
let mut args = std::env::args().skip(1);
|
let mut args = std::env::args().skip(1);
|
||||||
let app_id = args
|
let app_id = args.next().context(USAGE)?;
|
||||||
.next()
|
|
||||||
.context("usage: weft-app-shell <app_id> <session_id>")?;
|
|
||||||
let session_id: u64 = args
|
let session_id: u64 = args
|
||||||
.next()
|
.next()
|
||||||
.context("usage: weft-app-shell <app_id> <session_id>")?
|
.context(USAGE)?
|
||||||
.parse()
|
.parse()
|
||||||
.context("session_id must be a number")?;
|
.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();
|
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 {
|
fn appd_ws_port() -> u16 {
|
||||||
|
|
@ -50,13 +53,18 @@ fn appd_ws_port() -> u16 {
|
||||||
7410
|
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")]
|
#[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"))]
|
#[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")
|
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 {
|
impl Refusal {
|
||||||
fn new(code: u32, message: impl Into<String>) -> Self {
|
pub(crate) fn new(code: u32, message: impl Into<String>) -> Self {
|
||||||
Self {
|
Self {
|
||||||
code,
|
code,
|
||||||
message: message.into(),
|
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
|
/// Derives grants for the declared capabilities. Every capability is
|
||||||
/// checked before host directories are resolved or the app's data
|
/// checked before host directories are resolved or the app's data
|
||||||
/// directory is created, so a refused launch leaves nothing behind.
|
/// directory is created, so a refused launch leaves nothing behind.
|
||||||
|
|
|
||||||
342
crates/weft-appd/src/launch.rs
Normal file
342
crates/weft-appd/src/launch.rs
Normal file
|
|
@ -0,0 +1,342 @@
|
||||||
|
//! 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, ManifestError, 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.
|
||||||
|
pub(crate) fn resolve(app_id: &str) -> Result<LaunchPackage, Refusal> {
|
||||||
|
resolve_in(app_id, &crate::app_store_roots())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Resolves `app_id` in `stores`. A verified image in any store takes
|
||||||
|
/// precedence over a directory install in any store, so a writable user
|
||||||
|
/// directory cannot shadow a system image. 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.
|
||||||
|
fn resolve_in(app_id: &str, stores: &[PathBuf]) -> Result<LaunchPackage, Refusal> {
|
||||||
|
use crate::mount::MountError;
|
||||||
|
if !is_valid_app_id(app_id) {
|
||||||
|
return Err(Refusal::new(400, "invalid app ID"));
|
||||||
|
}
|
||||||
|
if let Some(files) = stores
|
||||||
|
.iter()
|
||||||
|
.map(|store| ImageFiles::in_store(store, app_id))
|
||||||
|
.find(ImageFiles::any_present)
|
||||||
|
{
|
||||||
|
let image = crate::mount::mount(app_id, &files).map_err(|e| match e {
|
||||||
|
MountError::Invalid(e) => {
|
||||||
|
Refusal::new(403, format!("the verified image is invalid: {e}"))
|
||||||
|
}
|
||||||
|
MountError::Host(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));
|
||||||
|
}
|
||||||
|
for store in stores {
|
||||||
|
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> {
|
||||||
|
// The entries are checked inside `root`, so the root and its manifest
|
||||||
|
// must be the directory and file they appear to be, not links to
|
||||||
|
// something else.
|
||||||
|
let is_dir = std::fs::symlink_metadata(&root).is_ok_and(|m| m.file_type().is_dir());
|
||||||
|
let manifest_is_file =
|
||||||
|
std::fs::symlink_metadata(root.join(MANIFEST_FILE)).is_ok_and(|m| m.file_type().is_file());
|
||||||
|
if !is_dir || !manifest_is_file {
|
||||||
|
return Err(Refusal::new(
|
||||||
|
403,
|
||||||
|
format!(
|
||||||
|
"{} must be a directory holding a regular {MANIFEST_FILE}, not a link",
|
||||||
|
root.display()
|
||||||
|
),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
let manifest = Manifest::read(&root).map_err(|e| match e {
|
||||||
|
ManifestError::Io(..) => Refusal::new(500, e.to_string()),
|
||||||
|
ManifestError::Parse(..) => 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 an_image_in_a_later_store_is_not_shadowed_by_a_directory() {
|
||||||
|
let _env = crate::tests::env_lock().blocking_lock();
|
||||||
|
crate::tests::use_test_runtime_dir();
|
||||||
|
// A directory install in the user store, an incomplete image in the
|
||||||
|
// system store: the image is chosen, and refused.
|
||||||
|
let user = store("shadow_user", ID, "app.wasm");
|
||||||
|
let system = std::env::temp_dir().join(format!(
|
||||||
|
"weft_appd_launch_shadow_system_{}",
|
||||||
|
std::process::id()
|
||||||
|
));
|
||||||
|
let _ = std::fs::remove_dir_all(&system);
|
||||||
|
std::fs::create_dir_all(&system).unwrap();
|
||||||
|
std::fs::write(ImageFiles::in_store(&system, ID).image, b"image").unwrap();
|
||||||
|
let refused = refusal(resolve_in(ID, &[user.clone(), system.clone()]));
|
||||||
|
finish(&user);
|
||||||
|
let _ = std::fs::remove_dir_all(&system);
|
||||||
|
assert_eq!(refused.code, 403, "{}", refused.message);
|
||||||
|
assert!(
|
||||||
|
refused.message.contains("verified image"),
|
||||||
|
"{}",
|
||||||
|
refused.message
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(unix)]
|
||||||
|
#[test]
|
||||||
|
fn a_linked_package_root_or_manifest_is_refused() {
|
||||||
|
let _env = crate::tests::env_lock().blocking_lock();
|
||||||
|
let store = store("linked", ID, "app.wasm");
|
||||||
|
let elsewhere =
|
||||||
|
std::env::temp_dir().join(format!("weft_appd_launch_elsewhere_{}", std::process::id()));
|
||||||
|
let _ = std::fs::remove_dir_all(&elsewhere);
|
||||||
|
std::fs::rename(store.join(ID), &elsewhere).unwrap();
|
||||||
|
std::os::unix::fs::symlink(&elsewhere, store.join(ID)).unwrap();
|
||||||
|
let root_link = refusal(resolve(ID));
|
||||||
|
|
||||||
|
std::fs::remove_file(store.join(ID)).unwrap();
|
||||||
|
std::fs::rename(&elsewhere, store.join(ID)).unwrap();
|
||||||
|
let manifest = store.join(ID).join(MANIFEST_FILE);
|
||||||
|
std::fs::rename(&manifest, store.join("manifest.toml")).unwrap();
|
||||||
|
std::os::unix::fs::symlink(store.join("manifest.toml"), &manifest).unwrap();
|
||||||
|
let manifest_link = refusal(resolve(ID));
|
||||||
|
finish(&store);
|
||||||
|
for refused in [root_link, manifest_link] {
|
||||||
|
assert_eq!(refused.code, 403, "{}", refused.message);
|
||||||
|
assert!(
|
||||||
|
refused.message.contains("not a link"),
|
||||||
|
"{}",
|
||||||
|
refused.message
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[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, &malformed] {
|
||||||
|
assert_eq!(refused.code, 403, "{}", refused.message);
|
||||||
|
}
|
||||||
|
for refused in [&failed, &absent] {
|
||||||
|
assert_eq!(refused.code, 500, "{}", refused.message);
|
||||||
|
}
|
||||||
|
for refused in [&partial, &failed, &absent, &malformed] {
|
||||||
|
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 grants;
|
||||||
mod ipc;
|
mod ipc;
|
||||||
|
mod launch;
|
||||||
mod mount;
|
mod mount;
|
||||||
mod runtime;
|
mod runtime;
|
||||||
mod ws;
|
mod ws;
|
||||||
|
|
@ -442,20 +443,19 @@ pub(crate) async fn dispatch(req: Request, registry: &Registry) -> Response {
|
||||||
app_id,
|
app_id,
|
||||||
surface_id: _,
|
surface_id: _,
|
||||||
} => {
|
} => {
|
||||||
// The package's capabilities are granted before a session exists;
|
// The package is resolved and its capabilities granted before a
|
||||||
// a package this host cannot satisfy is refused, not started.
|
// session exists; a package this host cannot satisfy is refused,
|
||||||
let grants = if !weft_ipc_types::package::is_valid_app_id(&app_id) {
|
// not started.
|
||||||
Err(grants::Refusal {
|
let launch = if !weft_ipc_types::package::is_valid_app_id(&app_id) {
|
||||||
code: 400,
|
Err(grants::Refusal::new(400, "invalid app ID"))
|
||||||
message: "invalid app ID".to_owned(),
|
|
||||||
})
|
|
||||||
} else if std::env::var("WEFT_RUNTIME_BIN").is_ok() {
|
} else if std::env::var("WEFT_RUNTIME_BIN").is_ok() {
|
||||||
grants::for_app(&app_id)
|
resolve_launch(app_id.clone()).await.map(Some)
|
||||||
} else {
|
} else {
|
||||||
Ok(grants::SessionGrants::default())
|
Ok(None)
|
||||||
};
|
};
|
||||||
let grants = match grants {
|
let (package, grants) = match launch {
|
||||||
Ok(grants) => grants,
|
Ok(Some((package, grants))) => (Some(package), grants),
|
||||||
|
Ok(None) => (None, grants::SessionGrants::default()),
|
||||||
Err(refusal) => {
|
Err(refusal) => {
|
||||||
tracing::warn!(%app_id, error = %refusal.message, "launch refused");
|
tracing::warn!(%app_id, error = %refusal.message, "launch refused");
|
||||||
return Response::Error {
|
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 abort_rx = registry.lock().await.register_abort(session_id);
|
||||||
let compositor_tx = registry.lock().await.compositor_tx.clone();
|
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 {
|
let _ = registry.lock().await.broadcast().send(Response::LaunchAck {
|
||||||
session_id,
|
session_id,
|
||||||
app_id: app_id.clone(),
|
app_id: app_id.clone(),
|
||||||
|
|
@ -484,12 +486,12 @@ pub(crate) async fn dispatch(req: Request, registry: &Registry) -> Response {
|
||||||
state: AppStateKind::Stopped,
|
state: AppStateKind::Stopped,
|
||||||
});
|
});
|
||||||
return Response::LaunchAck { session_id, app_id };
|
return Response::LaunchAck { session_id, app_id };
|
||||||
}
|
};
|
||||||
let reg = Arc::clone(registry);
|
let reg = Arc::clone(registry);
|
||||||
let aid = app_id.clone();
|
|
||||||
tokio::spawn(async move {
|
tokio::spawn(async move {
|
||||||
if let Err(e) =
|
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");
|
tracing::warn!(session_id, error = %e, "runtime supervisor error");
|
||||||
}
|
}
|
||||||
|
|
@ -576,6 +578,33 @@ 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> {
|
pub(crate) fn app_store_roots() -> Vec<std::path::PathBuf> {
|
||||||
if let Ok(explicit) = std::env::var("WEFT_APP_STORE") {
|
if let Ok(explicit) = std::env::var("WEFT_APP_STORE") {
|
||||||
return vec![std::path::PathBuf::from(explicit)];
|
return vec![std::path::PathBuf::from(explicit)];
|
||||||
|
|
@ -594,18 +623,6 @@ pub(crate) fn app_store_roots() -> Vec<std::path::PathBuf> {
|
||||||
roots
|
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> {
|
fn scan_installed_apps() -> Vec<AppInfo> {
|
||||||
let mut seen = std::collections::HashSet::new();
|
let mut seen = std::collections::HashSet::new();
|
||||||
let mut apps = Vec::new();
|
let mut apps = Vec::new();
|
||||||
|
|
@ -614,11 +631,7 @@ fn scan_installed_apps() -> Vec<AppInfo> {
|
||||||
continue;
|
continue;
|
||||||
};
|
};
|
||||||
for entry in entries.flatten() {
|
for entry in entries.flatten() {
|
||||||
let manifest_path = entry.path().join("wapp.toml");
|
let Ok(m) = weft_ipc_types::manifest::Manifest::read(&entry.path()) else {
|
||||||
let Ok(contents) = std::fs::read_to_string(&manifest_path) else {
|
|
||||||
continue;
|
|
||||||
};
|
|
||||||
let Ok(m) = toml::from_str::<WappManifest>(&contents) else {
|
|
||||||
continue;
|
continue;
|
||||||
};
|
};
|
||||||
if seen.insert(m.package.id.clone()) {
|
if seen.insert(m.package.id.clone()) {
|
||||||
|
|
@ -655,7 +668,7 @@ mod tests {
|
||||||
/// since session sockets are named by session ID and every test registry
|
/// since session sockets are named by session ID and every test registry
|
||||||
/// starts at 1. Directories of test processes that have ended are
|
/// starts at 1. Directories of test processes that have ended are
|
||||||
/// removed. Callers hold env_lock.
|
/// 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");
|
let base = std::env::temp_dir().join("weft-appd-tests");
|
||||||
if let Ok(entries) = std::fs::read_dir(&base) {
|
if let Ok(entries) = std::fs::read_dir(&base) {
|
||||||
for entry in entries.flatten() {
|
for entry in entries.flatten() {
|
||||||
|
|
@ -680,6 +693,22 @@ mod tests {
|
||||||
ENV_LOCK.get_or_init(|| tokio::sync::Mutex::new(()))
|
ENV_LOCK.get_or_init(|| tokio::sync::Mutex::new(()))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Writes a complete package `id` into `dir`; `extra` adds lines to its
|
||||||
|
/// `[package]` table.
|
||||||
|
fn write_test_package(dir: &std::path::Path, id: &str, extra: &str) {
|
||||||
|
std::fs::create_dir_all(dir.join("ui")).unwrap();
|
||||||
|
std::fs::write(dir.join("app.wasm"), b"\0asm\x01\0\0\0").unwrap();
|
||||||
|
std::fs::write(dir.join("ui/index.html"), b"<p>").unwrap();
|
||||||
|
std::fs::write(
|
||||||
|
dir.join("wapp.toml"),
|
||||||
|
format!(
|
||||||
|
"[package]\nid = \"{id}\"\nname = \"T\"\nversion = \"0.1.0\"\n{extra}\n\
|
||||||
|
[runtime]\nmodule = \"app.wasm\"\n[ui]\nentry = \"ui/index.html\"\n"
|
||||||
|
),
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
fn make_registry() -> Registry {
|
fn make_registry() -> Registry {
|
||||||
Arc::new(Mutex::new(SessionRegistry::default()))
|
Arc::new(Mutex::new(SessionRegistry::default()))
|
||||||
}
|
}
|
||||||
|
|
@ -754,12 +783,11 @@ mod tests {
|
||||||
let _env = env_lock().lock().await;
|
let _env = env_lock().lock().await;
|
||||||
let store = std::env::temp_dir().join(format!("weft_refuse_{}", std::process::id()));
|
let store = std::env::temp_dir().join(format!("weft_refuse_{}", std::process::id()));
|
||||||
let app_dir = store.join("org.example.gpu");
|
let app_dir = store.join("org.example.gpu");
|
||||||
std::fs::create_dir_all(&app_dir).unwrap();
|
write_test_package(
|
||||||
std::fs::write(
|
&app_dir,
|
||||||
app_dir.join("wapp.toml"),
|
"org.example.gpu",
|
||||||
"[package]\nid = \"org.example.gpu\"\ncapabilities = [\"hw:gpu:compute\"]\n",
|
"capabilities = [\"hw:gpu:compute\"]",
|
||||||
)
|
);
|
||||||
.unwrap();
|
|
||||||
let prior_store = std::env::var("WEFT_APP_STORE").ok();
|
let prior_store = std::env::var("WEFT_APP_STORE").ok();
|
||||||
let prior_bin = std::env::var("WEFT_RUNTIME_BIN").ok();
|
let prior_bin = std::env::var("WEFT_RUNTIME_BIN").ok();
|
||||||
// SAFETY: env_lock is held and the runtime is current_thread.
|
// SAFETY: env_lock is held and the runtime is current_thread.
|
||||||
|
|
@ -1120,7 +1148,7 @@ mod tests {
|
||||||
};
|
};
|
||||||
let supervised = runtime::supervise(
|
let supervised = runtime::supervise(
|
||||||
session_id,
|
session_id,
|
||||||
"test.app",
|
launch::LaunchPackage::unresolved("test.app"),
|
||||||
grants::SessionGrants::default(),
|
grants::SessionGrants::default(),
|
||||||
Arc::clone(®istry),
|
Arc::clone(®istry),
|
||||||
abort_rx,
|
abort_rx,
|
||||||
|
|
@ -1155,12 +1183,7 @@ mod tests {
|
||||||
use_test_runtime_dir();
|
use_test_runtime_dir();
|
||||||
let dir = std::env::temp_dir().join(format!("weft_test_relay_{}", std::process::id()));
|
let dir = std::env::temp_dir().join(format!("weft_test_relay_{}", std::process::id()));
|
||||||
let app = dir.join("store/org.example.relay");
|
let app = dir.join("store/org.example.relay");
|
||||||
std::fs::create_dir_all(&app).unwrap();
|
write_test_package(&app, "org.example.relay", "");
|
||||||
std::fs::write(
|
|
||||||
app.join("wapp.toml"),
|
|
||||||
"[package]\nid = \"org.example.relay\"\n",
|
|
||||||
)
|
|
||||||
.unwrap();
|
|
||||||
// The runtime reports ready and exits without connecting to the relay.
|
// The runtime reports ready and exits without connecting to the relay.
|
||||||
let child = dir.join("child.sh");
|
let child = dir.join("child.sh");
|
||||||
std::fs::write(
|
std::fs::write(
|
||||||
|
|
@ -1226,6 +1249,93 @@ mod tests {
|
||||||
assert!(!session_ipc_socket_path(session_id).unwrap().exists());
|
assert!(!session_ipc_socket_path(session_id).unwrap().exists());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[tokio::test(flavor = "current_thread")]
|
||||||
|
async fn children_receive_the_resolved_package_files() {
|
||||||
|
use std::os::unix::fs::PermissionsExt;
|
||||||
|
let _env = env_lock().lock().await;
|
||||||
|
use_test_runtime_dir();
|
||||||
|
let dir = std::env::temp_dir().join(format!("weft_test_args_{}", std::process::id()));
|
||||||
|
let _ = std::fs::remove_dir_all(&dir);
|
||||||
|
let app = dir.join("store/org.example.args");
|
||||||
|
write_test_package(&app, "org.example.args", "");
|
||||||
|
// Each child records its arguments, one per line, then reports ready.
|
||||||
|
let log = dir.join("args.log");
|
||||||
|
let child = dir.join("child.sh");
|
||||||
|
std::fs::write(
|
||||||
|
&child,
|
||||||
|
format!(
|
||||||
|
"#!/bin/sh\nprintf '%s\\n' \"$@\" -- >> '{}'\necho READY $WEFT_READY_TOKEN\nexec sleep 1\n",
|
||||||
|
log.display()
|
||||||
|
),
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
std::fs::set_permissions(&child, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||||
|
let vars = [
|
||||||
|
("WEFT_RUNTIME_BIN", child.clone().into_os_string()),
|
||||||
|
("WEFT_APP_SHELL_BIN", child.clone().into_os_string()),
|
||||||
|
("WEFT_DISABLE_CGROUP", "1".into()),
|
||||||
|
("WEFT_APP_STORE", dir.join("store").into_os_string()),
|
||||||
|
];
|
||||||
|
let prior: Vec<_> = vars
|
||||||
|
.iter()
|
||||||
|
.map(|(k, _)| (*k, std::env::var_os(k)))
|
||||||
|
.collect();
|
||||||
|
for (key, value) in &vars {
|
||||||
|
// SAFETY: env_lock is held on a current_thread runtime.
|
||||||
|
unsafe { std::env::set_var(key, value) };
|
||||||
|
}
|
||||||
|
|
||||||
|
let registry = make_registry();
|
||||||
|
let mut rx = registry.lock().await.subscribe();
|
||||||
|
let ack = dispatch(
|
||||||
|
Request::LaunchApp {
|
||||||
|
app_id: "org.example.args".into(),
|
||||||
|
surface_id: 0,
|
||||||
|
},
|
||||||
|
®istry,
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
let stopped = tokio::time::timeout(std::time::Duration::from_secs(10), async {
|
||||||
|
while !matches!(
|
||||||
|
rx.recv().await,
|
||||||
|
Ok(Response::AppState {
|
||||||
|
state: AppStateKind::Stopped,
|
||||||
|
..
|
||||||
|
})
|
||||||
|
) {}
|
||||||
|
})
|
||||||
|
.await;
|
||||||
|
let recorded = std::fs::read_to_string(&log).unwrap_or_default();
|
||||||
|
|
||||||
|
for (key, value) in prior {
|
||||||
|
// SAFETY: as above.
|
||||||
|
unsafe {
|
||||||
|
match value {
|
||||||
|
Some(v) => std::env::set_var(key, v),
|
||||||
|
None => std::env::remove_var(key),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let _ = std::fs::remove_dir_all(&dir);
|
||||||
|
assert!(matches!(ack, Response::LaunchAck { .. }), "{ack:?}");
|
||||||
|
assert!(stopped.is_ok(), "session did not stop");
|
||||||
|
let runs: Vec<Vec<&str>> = recorded
|
||||||
|
.split("--\n")
|
||||||
|
.filter(|run| !run.is_empty())
|
||||||
|
.map(|run| run.lines().collect())
|
||||||
|
.collect();
|
||||||
|
let after = |run: &[&str], flag: &str| {
|
||||||
|
run.iter()
|
||||||
|
.position(|arg| *arg == flag)
|
||||||
|
.and_then(|i| run.get(i + 1).map(|value| value.to_string()))
|
||||||
|
};
|
||||||
|
let module = app.join("app.wasm").display().to_string();
|
||||||
|
let ui = app.join("ui/index.html").display().to_string();
|
||||||
|
assert_eq!(runs.len(), 2, "{recorded}");
|
||||||
|
assert_eq!(after(&runs[0], "--module"), Some(module), "{recorded}");
|
||||||
|
assert_eq!(after(&runs[1], "--ui"), Some(ui), "{recorded}");
|
||||||
|
}
|
||||||
|
|
||||||
#[tokio::test(flavor = "current_thread")]
|
#[tokio::test(flavor = "current_thread")]
|
||||||
async fn supervisor_transitions_through_ready_to_stopped() {
|
async fn supervisor_transitions_through_ready_to_stopped() {
|
||||||
use std::os::unix::fs::PermissionsExt;
|
use std::os::unix::fs::PermissionsExt;
|
||||||
|
|
@ -1267,7 +1377,7 @@ mod tests {
|
||||||
|
|
||||||
runtime::supervise(
|
runtime::supervise(
|
||||||
session_id,
|
session_id,
|
||||||
"test.app",
|
launch::LaunchPackage::unresolved("test.app"),
|
||||||
grants::SessionGrants::default(),
|
grants::SessionGrants::default(),
|
||||||
Arc::clone(®istry),
|
Arc::clone(®istry),
|
||||||
abort_rx,
|
abort_rx,
|
||||||
|
|
@ -1342,7 +1452,7 @@ mod tests {
|
||||||
|
|
||||||
runtime::supervise(
|
runtime::supervise(
|
||||||
session_id,
|
session_id,
|
||||||
"test.abort.startup",
|
launch::LaunchPackage::unresolved("test.abort.startup"),
|
||||||
grants::SessionGrants::default(),
|
grants::SessionGrants::default(),
|
||||||
Arc::clone(®istry),
|
Arc::clone(®istry),
|
||||||
abort_rx,
|
abort_rx,
|
||||||
|
|
@ -1392,7 +1502,7 @@ mod tests {
|
||||||
|
|
||||||
runtime::supervise(
|
runtime::supervise(
|
||||||
session_id,
|
session_id,
|
||||||
"test.spawn.fail",
|
launch::LaunchPackage::unresolved("test.spawn.fail"),
|
||||||
grants::SessionGrants::default(),
|
grants::SessionGrants::default(),
|
||||||
Arc::clone(®istry),
|
Arc::clone(®istry),
|
||||||
abort_rx,
|
abort_rx,
|
||||||
|
|
@ -1551,7 +1661,7 @@ mod tests {
|
||||||
std::time::Duration::from_secs(20),
|
std::time::Duration::from_secs(20),
|
||||||
runtime::supervise(
|
runtime::supervise(
|
||||||
session_id,
|
session_id,
|
||||||
"test.app",
|
launch::LaunchPackage::unresolved("test.app"),
|
||||||
grants::SessionGrants::default(),
|
grants::SessionGrants::default(),
|
||||||
Arc::clone(®istry),
|
Arc::clone(®istry),
|
||||||
abort_rx,
|
abort_rx,
|
||||||
|
|
|
||||||
|
|
@ -1,105 +1,124 @@
|
||||||
|
//! Verified package images, mounted read-only for the session that runs
|
||||||
|
//! them.
|
||||||
|
|
||||||
use std::path::{Path, PathBuf};
|
use std::path::{Path, PathBuf};
|
||||||
|
|
||||||
fn mount_helper_bin() -> Option<String> {
|
use weft_ipc_types::package::ImageFiles;
|
||||||
if let Ok(v) = std::env::var("WEFT_MOUNT_HELPER") {
|
|
||||||
return Some(v);
|
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/lib/weft/weft-mount-helper",
|
||||||
"/usr/local/lib/weft/weft-mount-helper",
|
"/usr/local/lib/weft/weft-mount-helper",
|
||||||
] {
|
]
|
||||||
if Path::new(candidate).exists() {
|
.into_iter()
|
||||||
return Some(candidate.to_string());
|
.map(PathBuf::from)
|
||||||
}
|
.find(|candidate| candidate.exists())
|
||||||
}
|
|
||||||
None
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub struct MountOrchestrator {
|
/// A mounted image. Dropping it unmounts the image and removes the empty
|
||||||
mountpoint: Option<PathBuf>,
|
/// mountpoint; a mountpoint that cannot be unmounted is left in place.
|
||||||
|
pub(crate) struct Mount {
|
||||||
|
helper: PathBuf,
|
||||||
|
mountpoint: PathBuf,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl MountOrchestrator {
|
impl Mount {
|
||||||
pub fn mount_if_needed(app_id: &str, session_id: u64) -> (Self, Option<PathBuf>) {
|
/// The package root inside the image.
|
||||||
let Some(helper) = mount_helper_bin() else {
|
pub(crate) fn root(&self) -> &Path {
|
||||||
return (Self { mountpoint: None }, None);
|
&self.mountpoint
|
||||||
};
|
|
||||||
|
|
||||||
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);
|
|
||||||
}
|
|
||||||
|
|
||||||
let status = std::process::Command::new(&helper)
|
|
||||||
.args([
|
|
||||||
"mount",
|
|
||||||
&img.to_string_lossy(),
|
|
||||||
&hash_dev.to_string_lossy(),
|
|
||||||
&root_hash,
|
|
||||||
&mountpoint.to_string_lossy(),
|
|
||||||
])
|
|
||||||
.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(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)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
pub fn umount(&self) {
|
impl Drop for Mount {
|
||||||
let Some(ref mp) = self.mountpoint else {
|
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;
|
return;
|
||||||
};
|
}
|
||||||
let Some(helper) = mount_helper_bin() else {
|
if let Err(e) = std::fs::remove_dir(&self.mountpoint) {
|
||||||
return;
|
tracing::warn!(path = %self.mountpoint.display(), error = %e, "cannot remove mountpoint");
|
||||||
};
|
|
||||||
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)> {
|
/// Why an image was not mounted.
|
||||||
for root in crate::app_store_roots() {
|
pub(crate) enum MountError {
|
||||||
let img = root.join(format!("{app_id}.app.img"));
|
/// The image files are incomplete or malformed.
|
||||||
let hash_dev = root.join(format!("{app_id}.hash"));
|
Invalid(String),
|
||||||
let roothash_file = root.join(format!("{app_id}.roothash"));
|
/// The host could not mount a well-formed image.
|
||||||
if img.exists() && hash_dev.exists() && roothash_file.exists() {
|
Host(String),
|
||||||
let Ok(root_hash) = std::fs::read_to_string(&roothash_file) else {
|
}
|
||||||
continue;
|
|
||||||
};
|
/// Mounts the verified image `files` of `app_id`. Every failure is returned:
|
||||||
return Some((img, hash_dev, root_hash.trim().to_string()));
|
/// the caller must not fall back to another copy of the package.
|
||||||
|
pub(crate) fn mount(app_id: &str, files: &ImageFiles) -> Result<Mount, MountError> {
|
||||||
|
use MountError::{Host, Invalid};
|
||||||
|
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(Invalid(format!(
|
||||||
|
"{} is missing or not a regular file",
|
||||||
|
path.display()
|
||||||
|
)));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
None
|
let root_hash = std::fs::read_to_string(&files.root_hash)
|
||||||
|
.map_err(|e| Host(format!("cannot read {}: {e}", files.root_hash.display())))?;
|
||||||
|
let root_hash = root_hash.trim();
|
||||||
|
if !is_root_hash(root_hash) {
|
||||||
|
return Err(Invalid(format!(
|
||||||
|
"{} holds no root hash",
|
||||||
|
files.root_hash.display()
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
let helper = mount_helper_bin().ok_or(Host("weft-mount-helper is not installed".into()))?;
|
||||||
|
|
||||||
|
let runtime_dir =
|
||||||
|
std::env::var_os("XDG_RUNTIME_DIR").ok_or(Host("XDG_RUNTIME_DIR is not set".into()))?;
|
||||||
|
let base = PathBuf::from(runtime_dir).join("weft/mnt");
|
||||||
|
crate::private_dir(&base)
|
||||||
|
.map_err(|e| Host(format!("cannot create {}: {e}", base.display())))?;
|
||||||
|
let name =
|
||||||
|
crate::runtime::random_token().map_err(|e| Host(format!("no mountpoint name: {e}")))?;
|
||||||
|
let mountpoint = base.join(name);
|
||||||
|
std::fs::create_dir(&mountpoint)
|
||||||
|
.map_err(|e| Host(format!("cannot create {}: {e}", mountpoint.display())))?;
|
||||||
|
|
||||||
|
let status = std::process::Command::new(&helper)
|
||||||
|
.arg("mount")
|
||||||
|
.arg(&files.image)
|
||||||
|
.arg(&files.hash_tree)
|
||||||
|
.arg(root_hash)
|
||||||
|
.arg(&mountpoint)
|
||||||
|
.status();
|
||||||
|
match status {
|
||||||
|
Ok(status) if status.success() => {
|
||||||
|
tracing::info!(%app_id, path = %mountpoint.display(), "package image mounted");
|
||||||
|
Ok(Mount { helper, mountpoint })
|
||||||
|
}
|
||||||
|
outcome => {
|
||||||
|
let _ = std::fs::remove_dir(&mountpoint);
|
||||||
|
Err(Host(match outcome {
|
||||||
|
Ok(status) => format!("weft-mount-helper failed: {status}"),
|
||||||
|
Err(e) => format!("cannot run {}: {e}", helper.display()),
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 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().is_multiple_of(2)
|
||||||
|
&& text.bytes().all(|b| b.is_ascii_hexdigit())
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
|
|
@ -107,11 +126,17 @@ mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn find_image_returns_none_when_absent() {
|
fn root_hashes_are_hex_digests() {
|
||||||
let _env = crate::tests::env_lock().blocking_lock();
|
assert!(is_root_hash(&"a".repeat(64)));
|
||||||
unsafe { std::env::set_var("WEFT_APP_STORE", "/tmp/nonexistent_weft_store_xyz") };
|
assert!(is_root_hash(&"0F".repeat(64)));
|
||||||
let result = find_image("com.example.missing");
|
for bad in [
|
||||||
unsafe { std::env::remove_var("WEFT_APP_STORE") };
|
"",
|
||||||
assert!(result.is_none());
|
"abc",
|
||||||
|
&"g".repeat(64),
|
||||||
|
&"a".repeat(65),
|
||||||
|
&"a".repeat(130),
|
||||||
|
] {
|
||||||
|
assert!(!is_root_hash(bad), "{bad:?}");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -7,6 +7,8 @@ use weft_ipc_types::AppdToCompositor;
|
||||||
use crate::Registry;
|
use crate::Registry;
|
||||||
use crate::compositor_client::CompositorSender;
|
use crate::compositor_client::CompositorSender;
|
||||||
use crate::ipc::{AppStateKind, Response};
|
use crate::ipc::{AppStateKind, Response};
|
||||||
|
use crate::launch::LaunchPackage;
|
||||||
|
use crate::mount::Mount;
|
||||||
|
|
||||||
/// The per-session relay between the component's IPC socket and the app
|
/// The per-session relay between the component's IPC socket and the app
|
||||||
/// bridge. It belongs to the session: closing it stops the relay task and
|
/// bridge. It belongs to the session: closing it stops the relay task and
|
||||||
|
|
@ -186,7 +188,7 @@ async fn kill_portal(portal: Option<(PathBuf, tokio::process::Child)>) {
|
||||||
fn spawn_app_shell(
|
fn spawn_app_shell(
|
||||||
bin: &str,
|
bin: &str,
|
||||||
session_id: u64,
|
session_id: u64,
|
||||||
app_id: &str,
|
package: &LaunchPackage,
|
||||||
token: &str,
|
token: &str,
|
||||||
bridge_token: Option<String>,
|
bridge_token: Option<String>,
|
||||||
) -> std::io::Result<tokio::process::Child> {
|
) -> std::io::Result<tokio::process::Child> {
|
||||||
|
|
@ -197,15 +199,17 @@ fn spawn_app_shell(
|
||||||
command.env(BRIDGE_TOKEN_ENV, bridge_token);
|
command.env(BRIDGE_TOKEN_ENV, bridge_token);
|
||||||
}
|
}
|
||||||
let child = command
|
let child = command
|
||||||
.arg(app_id)
|
.arg(&package.app_id)
|
||||||
.arg(session_id.to_string())
|
.arg(session_id.to_string())
|
||||||
|
.arg("--ui")
|
||||||
|
.arg(&package.ui_entry)
|
||||||
.env(READY_TOKEN_ENV, token)
|
.env(READY_TOKEN_ENV, token)
|
||||||
.stdin(std::process::Stdio::null())
|
.stdin(std::process::Stdio::null())
|
||||||
.stdout(std::process::Stdio::piped())
|
.stdout(std::process::Stdio::piped())
|
||||||
.stderr(std::process::Stdio::piped())
|
.stderr(std::process::Stdio::piped())
|
||||||
.kill_on_drop(true)
|
.kill_on_drop(true)
|
||||||
.spawn()?;
|
.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)
|
Ok(child)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -241,36 +245,39 @@ fn spawn_file_portal(
|
||||||
|
|
||||||
pub(crate) async fn supervise(
|
pub(crate) async fn supervise(
|
||||||
session_id: u64,
|
session_id: u64,
|
||||||
app_id: &str,
|
mut package: LaunchPackage,
|
||||||
grants: crate::grants::SessionGrants,
|
grants: crate::grants::SessionGrants,
|
||||||
registry: Registry,
|
registry: Registry,
|
||||||
abort_rx: tokio::sync::oneshot::Receiver<()>,
|
abort_rx: tokio::sync::oneshot::Receiver<()>,
|
||||||
compositor_tx: Option<CompositorSender>,
|
compositor_tx: Option<CompositorSender>,
|
||||||
) -> anyhow::Result<()> {
|
) -> anyhow::Result<()> {
|
||||||
let mut abort_rx = abort_rx;
|
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") {
|
let bin = match std::env::var("WEFT_RUNTIME_BIN") {
|
||||||
Ok(b) => b,
|
Ok(b) => b,
|
||||||
Err(_) => {
|
Err(_) => {
|
||||||
tracing::debug!(session_id, %app_id, "WEFT_RUNTIME_BIN not set; skipping process spawn");
|
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 {
|
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");
|
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() {
|
let token = match random_token() {
|
||||||
Ok(token) => token,
|
Ok(token) => token,
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
tracing::error!(session_id, %app_id, error = %e, "cannot create readiness token");
|
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 {
|
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");
|
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 broadcast = registry.lock().await.broadcast().clone();
|
||||||
let relay = match spawn_ipc_relay(session_id, ipc_socket_path.clone(), broadcast) {
|
let relay = match spawn_ipc_relay(session_id, ipc_socket_path.clone(), broadcast) {
|
||||||
|
|
@ -280,13 +287,10 @@ pub(crate) async fn supervise(
|
||||||
}
|
}
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
tracing::warn!(session_id, %app_id, error = %e, "cannot open the IPC socket");
|
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 portal = spawn_file_portal(session_id, &grants.dirs);
|
||||||
|
|
||||||
let mut cmd = if systemd_cgroup_available() {
|
let mut cmd = if systemd_cgroup_available() {
|
||||||
|
|
@ -305,10 +309,7 @@ pub(crate) async fn supervise(
|
||||||
.kill_on_drop(true);
|
.kill_on_drop(true);
|
||||||
|
|
||||||
cmd.arg("--ipc-socket").arg(&ipc_socket_path);
|
cmd.arg("--ipc-socket").arg(&ipc_socket_path);
|
||||||
|
cmd.arg("--module").arg(&package.module);
|
||||||
if let Some(ref root) = store_override {
|
|
||||||
cmd.env("WEFT_APP_STORE", root);
|
|
||||||
}
|
|
||||||
|
|
||||||
if let Some((ref sock, _)) = portal {
|
if let Some((ref sock, _)) = portal {
|
||||||
cmd.env("WEFT_FILE_PORTAL_SOCKET", sock);
|
cmd.env("WEFT_FILE_PORTAL_SOCKET", sock);
|
||||||
|
|
@ -327,7 +328,7 @@ pub(crate) async fn supervise(
|
||||||
app_shell: None,
|
app_shell: None,
|
||||||
portal,
|
portal,
|
||||||
relay: Some(relay),
|
relay: Some(relay),
|
||||||
mount: mount_orch,
|
image,
|
||||||
compositor_tx,
|
compositor_tx,
|
||||||
surface_announced: false,
|
surface_announced: false,
|
||||||
};
|
};
|
||||||
|
|
@ -377,15 +378,15 @@ pub(crate) async fn supervise(
|
||||||
tokio::spawn(drain_stdout(runtime_stdout, session_id));
|
tokio::spawn(drain_stdout(runtime_stdout, session_id));
|
||||||
|
|
||||||
let bridge_token = registry.lock().await.bridge_token(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,
|
Ok(child) => child,
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
return session
|
return session
|
||||||
.settle(®istry, &format!("failed to spawn app shell: {e}"))
|
.settle(®istry, &format!("failed to spawn app shell: {e}"))
|
||||||
.await;
|
.await;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
let shell_stdout = app_shell.stdout.take().expect("stdout piped");
|
let shell_stdout = app_shell.stdout.take().expect("stdout piped");
|
||||||
tokio::spawn(drain_stderr(
|
tokio::spawn(drain_stderr(
|
||||||
app_shell.stderr.take().expect("stderr piped"),
|
app_shell.stderr.take().expect("stderr piped"),
|
||||||
|
|
@ -438,7 +439,12 @@ pub(crate) async fn supervise(
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Marks a session that never started any process as stopped.
|
/// 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;
|
let mut reg = registry.lock().await;
|
||||||
reg.set_state(session_id, AppStateKind::Stopped);
|
reg.set_state(session_id, AppStateKind::Stopped);
|
||||||
reg.remove_abort_sender(session_id);
|
reg.remove_abort_sender(session_id);
|
||||||
|
|
@ -458,7 +464,8 @@ struct OwnedSession {
|
||||||
app_shell: Option<tokio::process::Child>,
|
app_shell: Option<tokio::process::Child>,
|
||||||
portal: Option<(PathBuf, tokio::process::Child)>,
|
portal: Option<(PathBuf, tokio::process::Child)>,
|
||||||
relay: Option<IpcRelay>,
|
relay: Option<IpcRelay>,
|
||||||
mount: crate::mount::MountOrchestrator,
|
/// The mounted package image, released after both children have exited.
|
||||||
|
image: Option<Mount>,
|
||||||
compositor_tx: Option<CompositorSender>,
|
compositor_tx: Option<CompositorSender>,
|
||||||
surface_announced: bool,
|
surface_announced: bool,
|
||||||
}
|
}
|
||||||
|
|
@ -480,7 +487,7 @@ impl OwnedSession {
|
||||||
"compositor queue unavailable; surface not released"
|
"compositor queue unavailable; surface not released"
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
self.mount.umount();
|
release_image(self.image).await;
|
||||||
kill_portal(self.portal).await;
|
kill_portal(self.portal).await;
|
||||||
drop(self.relay);
|
drop(self.relay);
|
||||||
let mut reg = registry.lock().await;
|
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>) {
|
async fn kill_child(child: Option<tokio::process::Child>) {
|
||||||
if let Some(mut child) = child {
|
if let Some(mut child) = child {
|
||||||
let _ = child.kill().await;
|
let _ = child.kill().await;
|
||||||
|
|
|
||||||
|
|
@ -11,6 +11,7 @@ path = "src/lib.rs"
|
||||||
[dependencies]
|
[dependencies]
|
||||||
serde = { version = "1", features = ["derive"] }
|
serde = { version = "1", features = ["derive"] }
|
||||||
rmp-serde = "1"
|
rmp-serde = "1"
|
||||||
|
toml = "0.8"
|
||||||
|
|
||||||
[lints]
|
[lints]
|
||||||
workspace = true
|
workspace = true
|
||||||
|
|
|
||||||
|
|
@ -1,4 +1,5 @@
|
||||||
pub mod capability;
|
pub mod capability;
|
||||||
|
pub mod manifest;
|
||||||
pub mod package;
|
pub mod package;
|
||||||
|
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
|
||||||
222
crates/weft-ipc-types/src/manifest.rs
Normal file
222
crates/weft-ipc-types/src/manifest.rs
Normal file
|
|
@ -0,0 +1,222 @@
|
||||||
|
//! 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,
|
/// The user's data home: `$XDG_DATA_HOME` when it is an absolute path,
|
||||||
/// otherwise `$HOME/.local/share`.
|
/// otherwise `$HOME/.local/share`.
|
||||||
pub fn data_home() -> Option<PathBuf> {
|
pub fn data_home() -> Option<PathBuf> {
|
||||||
|
|
@ -181,6 +215,21 @@ pub fn make_private(dir: &Path) -> std::io::Result<()> {
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
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]
|
#[test]
|
||||||
fn app_ids() {
|
fn app_ids() {
|
||||||
assert!(is_valid_app_id("org.weft.demo"));
|
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 {
|
fn device_name(mountpoint: &Path) -> String {
|
||||||
let s = mountpoint.to_string_lossy();
|
let leaf = mountpoint
|
||||||
let sanitized: String = s
|
.file_name()
|
||||||
|
.map(|name| name.to_string_lossy())
|
||||||
|
.unwrap_or_default();
|
||||||
|
let sanitized: String = leaf
|
||||||
.chars()
|
.chars()
|
||||||
.map(|c| if c.is_ascii_alphanumeric() { c } else { '-' })
|
.map(|c| if c.is_ascii_alphanumeric() { c } else { '-' })
|
||||||
|
.take(120)
|
||||||
.collect();
|
.collect();
|
||||||
let suffix: String = sanitized
|
format!("weft-{sanitized}")
|
||||||
.trim_matches('-')
|
|
||||||
.chars()
|
|
||||||
.take(26)
|
|
||||||
.collect::<String>()
|
|
||||||
.trim_end_matches('-')
|
|
||||||
.to_string();
|
|
||||||
format!("weft-{suffix}")
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn cmd_mount(
|
fn cmd_mount(
|
||||||
|
|
@ -145,18 +146,20 @@ mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn device_name_sanitizes_path() {
|
fn device_names_follow_the_mountpoint_name() {
|
||||||
let mp = Path::new("/run/weft/mounts/com.example.myapp");
|
let name = device_name(Path::new("/run/user/1000/weft/mnt/0123abcd"));
|
||||||
let name = device_name(mp);
|
assert_eq!(name, "weft-0123abcd");
|
||||||
assert!(name.starts_with("weft-"));
|
assert_ne!(
|
||||||
assert!(name.chars().all(|c| c.is_ascii_alphanumeric() || c == '-'));
|
device_name(Path::new("/run/user/1000/weft/mnt/aaaa")),
|
||||||
assert!(name.len() <= 31);
|
device_name(Path::new("/run/user/1000/weft/mnt/bbbb"))
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn device_name_truncates_long_paths() {
|
fn device_names_are_sanitized_and_bounded() {
|
||||||
let mp = Path::new("/run/weft/mounts/com.example.averylongappidthatexceedsthemaximum");
|
let long = format!("/mnt/{}", "x.y".repeat(100));
|
||||||
let name = device_name(mp);
|
let name = device_name(Path::new(&long));
|
||||||
assert!(name.len() <= 31);
|
assert!(name.len() <= 127);
|
||||||
|
assert!(name.chars().all(|c| c.is_ascii_alphanumeric() || c == '-'));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -11,8 +11,6 @@ path = "src/main.rs"
|
||||||
[dependencies]
|
[dependencies]
|
||||||
weft-ipc-types = { path = "../weft-ipc-types" }
|
weft-ipc-types = { path = "../weft-ipc-types" }
|
||||||
anyhow = "1.0"
|
anyhow = "1.0"
|
||||||
serde = { version = "1", features = ["derive"] }
|
|
||||||
toml = "0.8"
|
|
||||||
ed25519-dalek = { version = "2", features = ["rand_core"] }
|
ed25519-dalek = { version = "2", features = ["rand_core"] }
|
||||||
sha2 = "0.10"
|
sha2 = "0.10"
|
||||||
rand = "0.8"
|
rand = "0.8"
|
||||||
|
|
|
||||||
|
|
@ -1,34 +1,8 @@
|
||||||
use std::path::{Path, PathBuf};
|
use std::path::{Path, PathBuf};
|
||||||
|
|
||||||
use anyhow::Context;
|
use anyhow::Context;
|
||||||
use serde::Deserialize;
|
use weft_ipc_types::manifest::{Manifest, entry_path};
|
||||||
|
use weft_ipc_types::package::ImageFiles;
|
||||||
#[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,
|
|
||||||
}
|
|
||||||
|
|
||||||
fn main() -> anyhow::Result<()> {
|
fn main() -> anyhow::Result<()> {
|
||||||
let args: Vec<String> = std::env::args().collect();
|
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);
|
match entry_path(dir, &m.runtime.module) {
|
||||||
if !wasm_path.exists() {
|
Err(e) => errors.push(format!("runtime.module: {e}")),
|
||||||
errors.push(format!(
|
Ok(wasm_path) if !is_wasm_module(&wasm_path) => errors.push(format!(
|
||||||
"runtime.module '{}' not found",
|
|
||||||
wasm_path.display()
|
|
||||||
));
|
|
||||||
} else if !is_wasm_module(&wasm_path) {
|
|
||||||
errors.push(format!(
|
|
||||||
"runtime.module '{}' is not a valid Wasm module (bad magic bytes)",
|
"runtime.module '{}' is not a valid Wasm module (bad magic bytes)",
|
||||||
wasm_path.display()
|
wasm_path.display()
|
||||||
));
|
)),
|
||||||
|
Ok(_) => {}
|
||||||
}
|
}
|
||||||
|
|
||||||
let ui_path = dir.join(&m.ui.entry);
|
if let Err(e) = entry_path(dir, &m.ui.entry) {
|
||||||
if !ui_path.exists() {
|
errors.push(format!("ui.entry: {e}"));
|
||||||
errors.push(format!("ui.entry '{}' not found", ui_path.display()));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
for cap in m.package.capabilities.iter().flatten() {
|
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> {
|
fn load_manifest(dir: &Path) -> anyhow::Result<Manifest> {
|
||||||
let manifest_path = dir.join("wapp.toml");
|
Ok(Manifest::read(dir)?)
|
||||||
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()))
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn print_info(m: &Manifest) {
|
fn print_info(m: &Manifest) {
|
||||||
|
|
@ -447,11 +413,7 @@ fn list_installed() {
|
||||||
};
|
};
|
||||||
let mut pkgs: Vec<(String, String, String)> = Vec::new();
|
let mut pkgs: Vec<(String, String, String)> = Vec::new();
|
||||||
for entry in entries.flatten() {
|
for entry in entries.flatten() {
|
||||||
let manifest_path = entry.path().join("wapp.toml");
|
let Ok(m) = Manifest::read(&entry.path()) else {
|
||||||
let Ok(contents) = std::fs::read_to_string(&manifest_path) else {
|
|
||||||
continue;
|
|
||||||
};
|
|
||||||
let Ok(m) = toml::from_str::<Manifest>(&contents) else {
|
|
||||||
continue;
|
continue;
|
||||||
};
|
};
|
||||||
if seen.insert(m.package.id.clone()) {
|
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<()> {
|
fn build_image(dir: &Path, out_path: Option<&Path>) -> anyhow::Result<()> {
|
||||||
let manifest = load_manifest(dir)?;
|
let manifest = load_manifest(dir)?;
|
||||||
let app_id = &manifest.package.id;
|
let app_id = &manifest.package.id;
|
||||||
let default_name = format!("{app_id}.app.img");
|
|
||||||
let output = match out_path {
|
let output = match out_path {
|
||||||
Some(p) => p.to_path_buf(),
|
Some(p) => p.to_path_buf(),
|
||||||
None => PathBuf::from(&default_name),
|
None => ImageFiles::in_store(Path::new(""), app_id).image,
|
||||||
};
|
};
|
||||||
if output.exists() {
|
if output.exists() {
|
||||||
anyhow::bail!("{} already exists", output.display());
|
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<()> {
|
fn build_verity(img: &Path, hash_out: Option<&Path>) -> anyhow::Result<()> {
|
||||||
let stem = img.file_stem().context("no file stem")?.to_string_lossy();
|
let companions = ImageFiles::for_image(img);
|
||||||
let default_hash = img.with_file_name(format!("{stem}.hash"));
|
let hash_path = hash_out
|
||||||
let hash_path = hash_out.map(|p| p.to_path_buf()).unwrap_or(default_hash);
|
.map(|p| p.to_path_buf())
|
||||||
|
.unwrap_or(companions.hash_tree);
|
||||||
if hash_path.exists() {
|
if hash_path.exists() {
|
||||||
anyhow::bail!("{} already exists", hash_path.display());
|
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:"))
|
.find(|l| l.starts_with("Root hash:"))
|
||||||
.context("root hash not found in veritysetup output")?;
|
.context("root hash not found in veritysetup output")?;
|
||||||
let hash_value = root_hash.trim_start_matches("Root hash:").trim();
|
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)
|
std::fs::write(&roothash_path, hash_value)
|
||||||
.with_context(|| format!("write {}", roothash_path.display()))?;
|
.with_context(|| format!("write {}", roothash_path.display()))?;
|
||||||
println!("hash image: {}", hash_path.display());
|
println!("hash image: {}", hash_path.display());
|
||||||
|
|
@ -1304,6 +1266,39 @@ entry = "ui/index.html"
|
||||||
.unwrap();
|
.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]
|
#[test]
|
||||||
fn check_package_unknown_capability_errors() {
|
fn check_package_unknown_capability_errors() {
|
||||||
let tmp = std::env::temp_dir().join(format!("weft_pack_caps_bad_{}", std::process::id()));
|
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();
|
let args: Vec<String> = std::env::args().collect();
|
||||||
if args.len() < 3 {
|
if args.len() < 3 {
|
||||||
anyhow::bail!(
|
anyhow::bail!(
|
||||||
"usage: weft-runtime <app_id> <session_id> \
|
"usage: weft-runtime <app_id> <session_id> --module PATH \
|
||||||
[--preopen HOST::GUEST::ro|rw]... [--grant CAPABILITY]... [--ipc-socket 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 preopen: Vec<Preopen> = Vec::new();
|
||||||
let mut grants = Grants::default();
|
let mut grants = Grants::default();
|
||||||
let mut ipc_socket: Option<String> = None;
|
let mut ipc_socket: Option<String> = None;
|
||||||
|
let mut module: Option<PathBuf> = None;
|
||||||
|
|
||||||
let mut i = 3usize;
|
let mut i = 3usize;
|
||||||
while i < args.len() {
|
while i < args.len() {
|
||||||
|
|
@ -42,6 +43,12 @@ fn main() -> anyhow::Result<()> {
|
||||||
i += 1;
|
i += 1;
|
||||||
grants.add(args.get(i).context("--grant requires an argument")?)?;
|
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" => {
|
"--ipc-socket" => {
|
||||||
i += 1;
|
i += 1;
|
||||||
ipc_socket = Some(
|
ipc_socket = Some(
|
||||||
|
|
@ -60,13 +67,9 @@ fn main() -> anyhow::Result<()> {
|
||||||
|
|
||||||
tracing::info!(session_id, %app_id, "weft-runtime starting");
|
tracing::info!(session_id, %app_id, "weft-runtime starting");
|
||||||
|
|
||||||
let pkg_dir = resolve_package(app_id)?;
|
// weft-appd resolves the package and passes the component it selected;
|
||||||
tracing::info!(path = %pkg_dir.display(), "package resolved");
|
// the runtime never looks for the package itself.
|
||||||
|
let wasm_path = module.context("--module is required")?;
|
||||||
let wasm_path = pkg_dir.join("app.wasm");
|
|
||||||
if !wasm_path.exists() {
|
|
||||||
anyhow::bail!("app.wasm not found at {}", wasm_path.display());
|
|
||||||
}
|
|
||||||
|
|
||||||
tracing::info!(session_id, %app_id, wasm = %wasm_path.display(), "executing module");
|
tracing::info!(session_id, %app_id, wasm = %wasm_path.display(), "executing module");
|
||||||
run_module(&wasm_path, &preopen, grants, ipc_socket.as_deref())?;
|
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"))]
|
#[cfg(not(feature = "wasmtime-runtime"))]
|
||||||
fn run_module(
|
fn run_module(
|
||||||
_wasm_path: &std::path::Path,
|
_wasm_path: &std::path::Path,
|
||||||
|
|
@ -599,41 +591,10 @@ fn apply_seccomp_filter() -> anyhow::Result<()> {
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
fn package_store_roots() -> Vec<PathBuf> {
|
#[cfg(all(test, not(feature = "wasmtime-runtime")))]
|
||||||
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 {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
|
|
||||||
/// Serialises the tests that read or change WEFT_APP_STORE; the test
|
|
||||||
/// harness runs tests on parallel threads that share the environment.
|
|
||||||
static ENV_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
|
|
||||||
|
|
||||||
fn env_lock() -> std::sync::MutexGuard<'static, ()> {
|
|
||||||
ENV_LOCK.lock().unwrap_or_else(|p| p.into_inner())
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(not(feature = "wasmtime-runtime"))]
|
|
||||||
#[test]
|
#[test]
|
||||||
fn engine_disabled_build_refuses_to_run_components() {
|
fn engine_disabled_build_refuses_to_run_components() {
|
||||||
let err = run_module(
|
let err = run_module(
|
||||||
|
|
@ -645,85 +606,4 @@ mod tests {
|
||||||
.expect_err("a build without wasmtime-runtime must not report success");
|
.expect_err("a build without wasmtime-runtime must not report success");
|
||||||
assert!(err.to_string().contains("wasmtime-runtime"));
|
assert!(err.to_string().contains("wasmtime-runtime"));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn package_store_roots_includes_system_path() {
|
|
||||||
let _env = env_lock();
|
|
||||||
let prior = std::env::var_os("WEFT_APP_STORE");
|
|
||||||
// SAFETY: env_lock serialises every test that touches the environment.
|
|
||||||
unsafe { std::env::remove_var("WEFT_APP_STORE") };
|
|
||||||
let roots = package_store_roots();
|
|
||||||
if let Some(v) = prior {
|
|
||||||
unsafe { std::env::set_var("WEFT_APP_STORE", v) };
|
|
||||||
}
|
|
||||||
assert!(
|
|
||||||
roots
|
|
||||||
.iter()
|
|
||||||
.any(|p| p == &PathBuf::from("/usr/share/weft/apps"))
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn package_store_roots_uses_weft_app_store_when_set() {
|
|
||||||
let _env = env_lock();
|
|
||||||
// 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() {
|
|
||||||
let _env = env_lock();
|
|
||||||
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 _env = env_lock();
|
|
||||||
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
|
### 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, workers and WebSocket handshakes) is checked by the shell: the page may load files inside its UI directory, also after symbolic links are resolved, inline `data:` and `blob:` resources, `about:blank` and the session bridge; any other local file or network destination, and every redirect, fails with a network error. Loads Servo does not attribute to the webview, such as `navigator.sendBeacon()`, are all refused. Network access belongs to the Wasm component, under its fetch grants. Servo's privileged `navigator.servo` interface, which can change engine preferences, is not exposed to `about:blank` or `about:srcdoc` documents (a fork patch; see `crates/weft-servo-shell/SERVO_PIN.md`). 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, workers and WebSocket handshakes) is checked by the shell: the page may load files inside its UI directory, also after symbolic links are resolved, inline `data:` and `blob:` resources, `about:blank` and the session bridge; any other local file or network destination, and every redirect, fails with a network error. Loads Servo does not attribute to the webview, such as `navigator.sendBeacon()`, are all refused. Network access belongs to the Wasm component, under its fetch grants. Servo's privileged `navigator.servo` interface, which can change engine preferences, is not exposed to `about:blank` or `about:srcdoc` documents (a fork patch; see `crates/weft-servo-shell/SERVO_PIN.md`). Registers with the compositor as window type `application`. Exits when the appd session ends.
|
||||||
|
|
||||||
### weft-appd
|
### 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
|
### 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
|
### weft-pack
|
||||||
|
|
||||||
|
|
@ -36,7 +36,7 @@ Per-session file proxy. Runs as a separate process with a path allowlist derived
|
||||||
|
|
||||||
### weft-mount-helper
|
### 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
|
## Process Topology
|
||||||
|
|
||||||
|
|
@ -46,8 +46,8 @@ systemd
|
||||||
├── weft-servo-shell (user, after compositor)
|
├── weft-servo-shell (user, after compositor)
|
||||||
└── weft-appd (user, after compositor + servo-shell)
|
└── weft-appd (user, after compositor + servo-shell)
|
||||||
└── per-session:
|
└── per-session:
|
||||||
├── weft-runtime <app_id> <session_id> [--preopen HOST::GUEST::ro|rw]... [--grant CAP]... [--ipc-socket ...]
|
├── 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>
|
├── weft-app-shell <app_id> <session_id> --ui <path>
|
||||||
└── weft-file-portal <socket> [--allow ...] [--allow-read ...]
|
└── weft-file-portal <socket> [--allow ...] [--allow-read ...]
|
||||||
```
|
```
|
||||||
|
|
||||||
|
|
@ -110,6 +110,17 @@ Package store roots (in priority order):
|
||||||
2. `~/.local/share/weft/apps/`
|
2. `~/.local/share/weft/apps/`
|
||||||
3. `/usr/share/weft/apps/`
|
3. `/usr/share/weft/apps/`
|
||||||
|
|
||||||
|
### Package resolution
|
||||||
|
|
||||||
|
`weft-appd` resolves a launch once. A verified image in any store root takes precedence over a directory install in any root, so a user's directory cannot shadow a system image; otherwise the first root with a directory install is used:
|
||||||
|
|
||||||
|
- **Verified image:** `<root>/<id>.app.img` with its dm-verity hash tree `<id>.app.hash` and root hash `<id>.app.roothash`, the names `weft-pack build-image` and `build-verity` produce. When any of the three exists, the image must mount through `weft-mount-helper`; a missing companion, a malformed root hash, a missing helper or a failed mount refuses the launch, and appd never falls back to a directory install. The root hash is read from the store next to the image and is not yet authenticated, so dm-verity detects corruption but not a store whose image, hash tree and root hash were replaced together. The mount belongs to the session and is released when the session stops.
|
||||||
|
- **Directory install:** `<root>/<id>/wapp.toml`.
|
||||||
|
|
||||||
|
The package root must be a directory and its manifest a regular file, neither a symbolic link, and the manifest must declare the requested ID. `[runtime].module` and `[ui].entry` must be relative paths of plain components, without symbolic links, naming regular files inside that root. The component, the UI document and the capabilities all come from that one manifest. A refused launch reports 400 (invalid ID), 404 (not installed), 403 (invalid package, image or image metadata) or 500 (the host cannot read the package or mount the image).
|
||||||
|
|
||||||
|
A directory install can still be changed by its owner while a session runs, and nothing verifies its content at launch.
|
||||||
|
|
||||||
## App data
|
## 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`.
|
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.
|
does not match.
|
||||||
|
|
||||||
`--host system` runs weft-servo-shell with the page as its system UI.
|
`--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
|
`--host app` copies the page into a package's UI directory and runs
|
||||||
weft-app-shell for it. The host must print READY, and the page must be on
|
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
|
screen within a short grace period after READY, because the compositor shows
|
||||||
a presented frame slightly later. READY printed within that grace before the
|
a presented frame slightly later. READY printed within that grace before the
|
||||||
page is presented is therefore not detected. `--slow-style SECONDS` makes
|
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
|
COMPOSITE_GRACE = 2.0
|
||||||
|
|
||||||
|
|
||||||
def install_app(store, page):
|
def app_ui(package, page):
|
||||||
"""Install `page` as the UI entry of a minimal package and return the store root."""
|
"""Copy `page` into the UI directory of a package and return the UI
|
||||||
package = store / APP_ID
|
document, the file weft-appd would pass to weft-app-shell."""
|
||||||
(package / "ui").mkdir(parents=True)
|
(package / "ui").mkdir(parents=True)
|
||||||
shutil.copyfile(page, package / "ui" / "index.html")
|
entry = package / "ui" / "index.html"
|
||||||
(package / "wapp.toml").write_text(
|
shutil.copyfile(page, entry)
|
||||||
"[package]\n"
|
return entry
|
||||||
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
|
|
||||||
|
|
||||||
|
|
||||||
def slow_style(directory, delay):
|
def slow_style(directory, delay):
|
||||||
|
|
@ -188,11 +178,11 @@ def main(argv=None):
|
||||||
shell = desktop.launch_client(
|
shell = desktop.launch_client(
|
||||||
"shell", [args.shell], {"WEFT_SYSTEM_UI_HTML": str(page.resolve())})
|
"shell", [args.shell], {"WEFT_SYSTEM_UI_HTML": str(page.resolve())})
|
||||||
else:
|
else:
|
||||||
store = install_app(desktop.runtime / "store", page)
|
entry = app_ui(desktop.runtime / APP_ID, page)
|
||||||
if args.slow_style:
|
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 = 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)
|
problems, screenshot = watch(desktop, shell, args)
|
||||||
except SessionError as error:
|
except SessionError as error:
|
||||||
print(error, file=sys.stderr)
|
print(error, file=sys.stderr)
|
||||||
|
|
|
||||||
|
|
@ -68,13 +68,7 @@ class Runner:
|
||||||
def __init__(self, runtime, work, port):
|
def __init__(self, runtime, work, port):
|
||||||
self.runtime = runtime
|
self.runtime = runtime
|
||||||
self.work = work
|
self.work = work
|
||||||
self.store = work / "store"
|
self.module = work / "app.wasm"
|
||||||
package = self.store / APP_ID
|
|
||||||
package.mkdir(parents=True)
|
|
||||||
(package / "wapp.toml").write_text(
|
|
||||||
f'[package]\nid = "{APP_ID}"\nname = "Grants probe"\nversion = "0.1.0"\n'
|
|
||||||
'[runtime]\nmodule = "app.wasm"\n[ui]\nentry = "ui/index.html"\n')
|
|
||||||
self.package = package
|
|
||||||
self.targets = work / "targets"
|
self.targets = work / "targets"
|
||||||
self.targets.mkdir()
|
self.targets.mkdir()
|
||||||
(self.targets / "targets.txt").write_text(
|
(self.targets / "targets.txt").write_text(
|
||||||
|
|
@ -84,11 +78,10 @@ class Runner:
|
||||||
f"fetch-other-host http://localhost:{port}/ok\n")
|
f"fetch-other-host http://localhost:{port}/ok\n")
|
||||||
|
|
||||||
def run(self, *arguments, expect_success=True):
|
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]
|
"--preopen", f"{self.targets}::/probe::ro", *arguments]
|
||||||
result = subprocess.run(command, capture_output=True, text=True, timeout=60,
|
result = subprocess.run(command, capture_output=True, text=True, timeout=60,
|
||||||
env={"WEFT_APP_STORE": str(self.store), "PATH": "/usr/bin:/bin",
|
env={"PATH": "/usr/bin:/bin", "RUST_LOG": "warn"})
|
||||||
"RUST_LOG": "warn"})
|
|
||||||
if expect_success and result.returncode != 0:
|
if expect_success and result.returncode != 0:
|
||||||
raise AssertionError(f"runtime failed: {' '.join(arguments)}\n{result.stderr}")
|
raise AssertionError(f"runtime failed: {' '.join(arguments)}\n{result.stderr}")
|
||||||
probes = {}
|
probes = {}
|
||||||
|
|
@ -182,7 +175,7 @@ def main(argv=None):
|
||||||
work = Path(tempfile.mkdtemp(prefix="weft-grants-"))
|
work = Path(tempfile.mkdtemp(prefix="weft-grants-"))
|
||||||
try:
|
try:
|
||||||
runner = Runner(args.runtime, work, server.server_port)
|
runner = Runner(args.runtime, work, server.server_port)
|
||||||
shutil.copy(probe, runner.package / "app.wasm")
|
shutil.copy(probe, runner.module)
|
||||||
data = work / "data"
|
data = work / "data"
|
||||||
data.mkdir()
|
data.mkdir()
|
||||||
check(runner, data)
|
check(runner, data)
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue