From db712e056e153249439594e6aac1c3b1b9ee71b9 Mon Sep 17 00:00:00 2001 From: Marco Allegretti Date: Fri, 9 Oct 2026 07:45:49 +0000 Subject: [PATCH] fix(appd): authorize WebSocket clients by role and session The browser-facing WebSocket accepted requests from any local page, so a page could launch or terminate apps and inject messages into any session. Every connection now completes the upgrade and sends HELLO within five seconds. The system role authenticates with a token appd writes to $XDG_RUNTIME_DIR/weft/appd.systoken (mode 0600) and may manage sessions, but never sees or sends application messages. The app role authenticates with a per-session bridge token passed to weft-app-shell in WEFT_BRIDGE_TOKEN and exchanges APP_MESSAGE envelopes with its own session only; it is disconnected when that session stops. weft-servo-shell hands the system endpoint only to the system UI document and denies navigation away from it. weft-app-shell installs the bridge only in top-level documents inside the application's UI directory and denies navigation outside it. The launcher renders package names as text. tests/frame/check_counter.py drives the Counter demo end to end through the compositor, appd, the Wasm runtime and the app shell. --- crates/weft-app-shell/src/embedder.rs | 107 ++++- crates/weft-appd/src/main.rs | 70 ++- crates/weft-appd/src/runtime.rs | 23 +- crates/weft-appd/src/ws.rs | 553 ++++++++++++++++++++++-- crates/weft-servo-shell/src/embedder.rs | 153 ++++++- docs/architecture.md | 14 +- infra/shell/system-ui.html | 57 ++- tests/frame/check_counter.py | 258 +++++++++++ 8 files changed, 1163 insertions(+), 72 deletions(-) create mode 100644 tests/frame/check_counter.py diff --git a/crates/weft-app-shell/src/embedder.rs b/crates/weft-app-shell/src/embedder.rs index 73048a0..4d30cee 100644 --- a/crates/weft-app-shell/src/embedder.rs +++ b/crates/weft-app-shell/src/embedder.rs @@ -7,8 +7,8 @@ use std::sync::{Arc, Mutex}; use servo::{ DeviceIntRect, DeviceIntSize, DevicePoint, EventLoopWaker, InputEvent, LoadStatus, MouseButton as ServoMouseButton, MouseButtonAction, MouseButtonEvent, MouseMoveEvent, - RenderingContext, RgbaImage, ServoBuilder, ServoDelegate, ServoUrl, UserContentManager, - UserScript, WebViewBuilder, WebViewDelegate, + NavigationRequest, RenderingContext, RgbaImage, ServoBuilder, ServoDelegate, ServoUrl, + UserContentManager, UserScript, WebViewBuilder, WebViewDelegate, }; use winit::{ application::ApplicationHandler, @@ -63,6 +63,8 @@ struct FrameSignals { struct WeftWebViewDelegate { signals: Arc, + /// URL prefix of the application's UI directory; see `ui_scope`. + scope: String, } impl WebViewDelegate for WeftWebViewDelegate { @@ -71,6 +73,17 @@ impl WebViewDelegate for WeftWebViewDelegate { self.signals.redraw.store(true, Ordering::Relaxed); } + /// The webview carries the session's bridge, so it stays within the + /// application's own UI files. + fn request_navigation(&self, _webview: servo::WebView, request: NavigationRequest) { + if request.url.as_str().starts_with(&self.scope) { + request.allow(); + } else { + tracing::warn!(url = %request.url, "navigation outside the application UI denied"); + request.deny(); + } + } + fn notify_load_status_changed(&self, webview: servo::WebView, status: LoadStatus) { if status != LoadStatus::Complete { return; @@ -98,6 +111,80 @@ fn ready_line() -> String { } } +/// The session's application bridge credential from weft-appd. +/// +/// Only 32 lowercase hex characters are accepted, so the value can be placed +/// in the injected script without escaping. +fn bridge_token() -> Option { + let token = std::env::var("WEFT_BRIDGE_TOKEN").ok()?; + (token.len() == 32 + && token + .bytes() + .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))) + .then_some(token) +} + +/// The URL prefix covering the application's UI: the directory holding its +/// entry document. +fn ui_scope(entry: &ServoUrl) -> String { + let url = entry.as_str(); + let end = url.rfind('/').map_or(url.len(), |slash| slash + 1); + url[..end].to_owned() +} + +/// `value` as a single-quoted JavaScript string literal. +fn js_string(value: &str) -> String { + let mut literal = String::with_capacity(value.len() + 2); + literal.push('\''); + for c in value.chars() { + match c { + ' '..='~' if c != '\'' && c != '\\' => literal.push(c), + _ => literal.push_str(&format!("\\u{{{:x}}}", u32::from(c))), + } + } + literal.push('\''); + literal +} + +/// The `window.weftIpc` bridge injected into the application document. +/// +/// Servo runs user scripts in every document, frames included, so the bridge +/// installs itself only in a top-level document within the application's UI +/// directory `scope`. It authenticates as this session's application bridge and exchanges +/// `APP_MESSAGE` envelopes with weft-appd. `send` accepts a string or a +/// JSON-serialisable value; `onmessage` receives each payload string. The +/// credential stays inside the closure. +fn bridge_script(port: u16, session_id: u64, token: &str, scope: &str) -> String { + let scope = js_string(scope); + format!( + r#"(function () {{ + if (window !== window.top || location.href.indexOf({scope}) !== 0) return; + var ws = new WebSocket('ws://127.0.0.1:{port}/app'); + var queue = []; + var open = false; + function envelope(m) {{ + return JSON.stringify({{ type: 'APP_MESSAGE', payload: typeof m === 'string' ? m : JSON.stringify(m) }}); + }} + ws.onopen = function () {{ + ws.send(JSON.stringify({{ type: 'HELLO', role: 'app', session_id: {session_id}, token: '{token}' }})); + open = true; + queue.forEach(function (m) {{ ws.send(envelope(m)); }}); + queue.length = 0; + }}; + ws.onmessage = function (e) {{ + var msg; + try {{ msg = JSON.parse(e.data); }} catch (_) {{ return; }} + if (msg.type === 'APP_MESSAGE' && window.weftIpc.onmessage) window.weftIpc.onmessage(msg.payload); + }}; + window.weftSessionId = {session_id}; + window.weftIpc = {{ + send: function (m) {{ if (open) ws.send(envelope(m)); else queue.push(m); }}, + onmessage: null + }}; +}})();"# + ) +} + /// Servo preferences shared by the WEFT hosts. fn host_preferences() -> servo::Preferences { servo::Preferences { @@ -316,16 +403,20 @@ impl ApplicationHandler for App { if let Some(kit_js) = load_ui_kit_script() { ucm.add_script(Rc::new(UserScript::new(kit_js, None))); } - let bridge_js = format!( - r#"(function(){{var ws=new WebSocket('ws://127.0.0.1:{p}');var sid={sid};var q=[];var r=false;ws.onopen=function(){{r=true;q.forEach(function(m){{ws.send(JSON.stringify(m))}});q.length=0}};window.weftSessionId=sid;window.weftIpc={{send:function(m){{if(r)ws.send(JSON.stringify(m));else q.push(m)}},onmessage:null}};ws.onmessage=function(e){{if(window.weftIpc.onmessage)window.weftIpc.onmessage(JSON.parse(e.data))}}}})()"#, - p = self.ws_port, - sid = self.session_id, - ); - ucm.add_script(Rc::new(UserScript::new(bridge_js, None))); + match bridge_token() { + Some(token) => ucm.add_script(Rc::new(UserScript::new( + bridge_script(self.ws_port, self.session_id, &token, &ui_scope(&self.url)), + None, + ))), + None => { + tracing::warn!("WEFT_BRIDGE_TOKEN missing or malformed; app messaging disabled") + } + } let webview = WebViewBuilder::new(&servo, rendering_context.as_dyn()) .delegate(Rc::new(WeftWebViewDelegate { signals: Arc::clone(&self.signals), + scope: ui_scope(&self.url), })) .user_content_manager(ucm) .url(self.url.clone().into_url()) diff --git a/crates/weft-appd/src/main.rs b/crates/weft-appd/src/main.rs index 0eaab0e..6754373 100644 --- a/crates/weft-appd/src/main.rs +++ b/crates/weft-appd/src/main.rs @@ -29,6 +29,8 @@ pub(crate) type Registry = Arc>; struct SessionEntry { app_id: String, state: AppStateKind, + /// Credential binding one application bridge connection to this session. + bridge_token: Option, } struct SessionRegistry { @@ -63,11 +65,33 @@ impl SessionRegistry { SessionEntry { app_id: app_id.to_owned(), state: AppStateKind::Starting, + bridge_token: match runtime::random_token() { + Ok(token) => Some(token), + Err(e) => { + tracing::error!(session_id = id, error = %e, "no bridge token; app messages disabled"); + None + } + }, }, ); id } + pub(crate) fn bridge_token(&self, session_id: u64) -> Option { + self.sessions.get(&session_id)?.bridge_token.clone() + } + + /// Whether `token` authorizes an application bridge for a live session. + pub(crate) fn authorize_bridge(&self, session_id: u64, token: &str) -> bool { + self.sessions.get(&session_id).is_some_and(|entry| { + !matches!(entry.state, AppStateKind::Stopped) + && entry + .bridge_token + .as_deref() + .is_some_and(|expected| ws::tokens_match(expected, token)) + }) + } + fn terminate(&mut self, session_id: u64) -> bool { let found = self.sessions.remove(&session_id).is_some(); self.abort_senders.remove(&session_id); @@ -189,6 +213,10 @@ async fn run() -> anyhow::Result<()> { if let Err(e) = write_ws_port(ws_bound_port) { tracing::warn!(error = %e, "could not write appd.wsport; servo-shell port discovery will fall back to default"); } + let ws_auth = Arc::new(ws::WsAuth { + system_token: runtime::random_token().context("create system token")?, + }); + write_system_token(&ws_auth.system_token).context("write appd.systoken")?; #[cfg(unix)] { @@ -235,8 +263,9 @@ async fn run() -> anyhow::Result<()> { let (stream, _) = result.context("ws accept")?; let reg = Arc::clone(®istry); let rx = registry.lock().await.subscribe(); + let auth = Arc::clone(&ws_auth); tokio::spawn(async move { - if let Err(e) = ws::handle_ws_connection(stream, reg, rx).await { + if let Err(e) = ws::handle_ws_connection(stream, reg, rx, auth).await { tracing::warn!(error = %e, "ws connection error"); } }); @@ -256,6 +285,9 @@ async fn run() -> anyhow::Result<()> { registry.lock().await.shutdown_all(); tokio::time::sleep(tokio::time::Duration::from_millis(200)).await; let _ = std::fs::remove_file(&socket_path); + if let Ok(path) = system_token_path() { + let _ = std::fs::remove_file(path); + } Ok(()) } @@ -297,6 +329,42 @@ fn ws_port() -> u16 { .unwrap_or(7410) } +/// Writes the system-role WebSocket credential to a file only the user can read. +#[cfg_attr(not(unix), allow(dead_code))] +fn write_system_token(token: &str) -> std::io::Result<()> { + use std::io::Write; + #[cfg(unix)] + use std::os::unix::fs::OpenOptionsExt; + let path = system_token_path()?; + let staging = path.with_extension(format!("systoken.{}", std::process::id())); + // A leftover staging file could carry other permissions; the file is + // always created afresh so the mode below applies. + let _ = std::fs::remove_file(&staging); + let mut options = std::fs::OpenOptions::new(); + options.write(true).create_new(true); + #[cfg(unix)] + options.mode(0o600); + let written = options.open(&staging).and_then(|mut file| { + file.write_all(token.as_bytes())?; + file.sync_all() + }); + let result = written.and_then(|()| std::fs::rename(&staging, &path)); + if result.is_err() { + let _ = std::fs::remove_file(&staging); + } + result +} + +fn system_token_path() -> std::io::Result { + let dir = PathBuf::from( + std::env::var("XDG_RUNTIME_DIR") + .map_err(|_| std::io::Error::other("XDG_RUNTIME_DIR not set"))?, + ) + .join("weft"); + std::fs::create_dir_all(&dir)?; + Ok(dir.join("appd.systoken")) +} + #[cfg_attr(not(any(unix, test)), allow(dead_code))] fn write_ws_port(port: u16) -> anyhow::Result<()> { let runtime_dir = std::env::var("XDG_RUNTIME_DIR").context("XDG_RUNTIME_DIR not set")?; diff --git a/crates/weft-appd/src/runtime.rs b/crates/weft-appd/src/runtime.rs index e7d6fba..67cfec5 100644 --- a/crates/weft-appd/src/runtime.rs +++ b/crates/weft-appd/src/runtime.rs @@ -23,6 +23,7 @@ pub(crate) async fn spawn_ipc_relay( let _ = std::fs::remove_file(&socket_path); return; }; + tracing::debug!(session_id, "IPC relay: component connected"); let (reader, writer) = tokio::io::split(stream); let mut reader = BufReader::new(reader); let mut writer = BufWriter::new(writer); @@ -79,10 +80,15 @@ const READY_TIMEOUT: Duration = Duration::from_secs(30); /// the host process environment. const READY_TOKEN_ENV: &str = "WEFT_READY_TOKEN"; +/// Environment variable carrying the session's application bridge credential +/// to weft-app-shell. +const BRIDGE_TOKEN_ENV: &str = "WEFT_BRIDGE_TOKEN"; + /// Longest line read from a child's output; longer lines are split. const MAX_LINE: u64 = 64 * 1024; -fn readiness_token() -> std::io::Result { +/// A random 128-bit credential as 32 hex characters. +pub(crate) fn random_token() -> std::io::Result { use std::io::Read; let mut bytes = [0u8; 16]; std::fs::File::open("/dev/urandom")?.read_exact(&mut bytes)?; @@ -212,8 +218,15 @@ fn spawn_app_shell( session_id: u64, app_id: &str, token: &str, + bridge_token: Option, ) -> std::io::Result { - let child = tokio::process::Command::new(bin) + let mut command = tokio::process::Command::new(bin); + if let Some(bridge_token) = bridge_token { + // The page holds this credential; it must differ from the readiness + // token, which page output could otherwise use to fake readiness. + command.env(BRIDGE_TOKEN_ENV, bridge_token); + } + let child = command .arg(app_id) .arg(session_id.to_string()) .env(READY_TOKEN_ENV, token) @@ -273,7 +286,7 @@ pub(crate) async fn supervise( tracing::warn!(session_id, %app_id, "WEFT_APP_SHELL_BIN not set; no UI host to start"); return stop_unstarted(®istry, session_id).await; }; - let token = match readiness_token() { + let token = match random_token() { Ok(token) => token, Err(e) => { tracing::error!(session_id, %app_id, error = %e, "cannot create readiness token"); @@ -372,7 +385,9 @@ pub(crate) async fn supervise( }; tokio::spawn(drain_stdout(runtime_stdout, session_id)); - let mut app_shell = match spawn_app_shell(&shell_bin, session_id, app_id, &token) { + 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) + { Ok(child) => child, Err(e) => { return session diff --git a/crates/weft-appd/src/ws.rs b/crates/weft-appd/src/ws.rs index 39fff81..38238c4 100644 --- a/crates/weft-appd/src/ws.rs +++ b/crates/weft-appd/src/ws.rs @@ -1,54 +1,553 @@ -use futures_util::{SinkExt, StreamExt}; -use tokio::sync::broadcast; -use tokio_tungstenite::{accept_async, tungstenite::Message}; +//! Browser-facing WebSocket endpoint with role-separated authority. +//! +//! Every connection starts with a `HELLO` message naming its role and +//! credential: +//! +//! - `{"type":"HELLO","role":"system","token":…}` — the trusted system shell, +//! holding the token appd writes to `$XDG_RUNTIME_DIR/weft/appd.systoken`. +//! It may use the catalog, lifecycle and gesture requests and receives +//! session state notifications, but never application payloads. +//! - `{"type":"HELLO","role":"app","session_id":N,"token":…}` — the bridge of +//! one application session, holding the token appd gave that session's app +//! shell. It may only exchange `{"type":"APP_MESSAGE","payload":"…"}` +//! messages with its own session's component. +//! +//! Connections that do not complete the upgrade and authenticate within +//! `HELLO_TIMEOUT` are closed. -use crate::{Registry, dispatch, ipc::Request, ipc::Response}; +use std::sync::Arc; +use std::time::Duration; + +use futures_util::{SinkExt, StreamExt}; +use serde::Deserialize; +use tokio::sync::{broadcast, mpsc}; +use tokio_tungstenite::tungstenite::Message; +use tokio_tungstenite::tungstenite::protocol::WebSocketConfig; + +use crate::ipc::{AppStateKind, Request, Response}; +use crate::{Registry, dispatch}; + +const HELLO_TIMEOUT: Duration = if cfg!(test) { + Duration::from_millis(500) +} else { + Duration::from_secs(5) +}; +/// Largest WebSocket message accepted from any client. +const MAX_MESSAGE: usize = 1024 * 1024; +/// Largest application payload forwarded to a component. +const MAX_APP_PAYLOAD: usize = 64 * 1024; + +pub struct WsAuth { + pub system_token: String, +} + +/// Compares credentials without exiting early on the first differing byte. +pub(crate) fn tokens_match(expected: &str, given: &str) -> bool { + let (expected, given) = (expected.as_bytes(), given.as_bytes()); + expected.len() == given.len() + && expected + .iter() + .zip(given) + .fold(0u8, |acc, (a, b)| acc | (a ^ b)) + == 0 +} + +#[derive(Deserialize)] +#[serde(tag = "role", rename_all = "lowercase")] +enum Hello { + System { token: String }, + App { session_id: u64, token: String }, +} + +#[derive(Deserialize)] +struct HelloEnvelope { + #[serde(rename = "type")] + kind: String, + #[serde(flatten)] + hello: Hello, +} + +#[derive(Deserialize)] +#[serde(tag = "type", rename_all = "SCREAMING_SNAKE_CASE")] +enum AppRequest { + AppMessage { payload: String }, +} + +enum Role { + System, + App(u64), +} pub async fn handle_ws_connection( stream: tokio::net::TcpStream, registry: Registry, broadcast_rx: broadcast::Receiver, + auth: Arc, ) -> anyhow::Result<()> { - let ws_stream = accept_async(stream).await?; - let (mut ws_write, mut ws_read) = ws_stream.split(); - let mut broadcast_rx = broadcast_rx; + let config = WebSocketConfig { + max_message_size: Some(MAX_MESSAGE), + max_frame_size: Some(MAX_MESSAGE), + ..Default::default() + }; + // The upgrade and HELLO share one deadline, so a client that never + // completes either holds nothing for longer than HELLO_TIMEOUT. + let handshake = async { + let ws_stream = tokio_tungstenite::accept_async_with_config(stream, Some(config)).await?; + let (ws_write, mut ws_read) = ws_stream.split(); + let hello = match ws_read.next().await { + Some(Ok(Message::Text(text))) => serde_json::from_str::(&text).ok(), + _ => None, + }; + anyhow::Ok((ws_write, ws_read, hello)) + }; + let Ok(handshake) = tokio::time::timeout(HELLO_TIMEOUT, handshake).await else { + tracing::debug!("WebSocket client did not complete its handshake in time"); + return Ok(()); + }; + let (mut ws_write, mut ws_read, hello) = handshake?; + let role = match hello { + Some(HelloEnvelope { + kind, + hello: Hello::System { token }, + }) if kind == "HELLO" && tokens_match(&auth.system_token, &token) => Role::System, + Some(HelloEnvelope { + kind, + hello: Hello::App { session_id, token }, + }) if kind == "HELLO" && registry.lock().await.authorize_bridge(session_id, &token) => { + Role::App(session_id) + } + _ => { + tracing::warn!("WebSocket client failed to authenticate; closing"); + let refusal = Response::Error { + code: 401, + message: "authentication required".to_owned(), + }; + let _ = ws_write + .send(Message::Text(serde_json::to_string(&refusal)?)) + .await; + let _ = ws_write.close().await; + return Ok(()); + } + }; + match role { + Role::System => tracing::debug!("system client connected"), + Role::App(session_id) => tracing::debug!(session_id, "application bridge connected"), + } + + let mut broadcast_rx = broadcast_rx; loop { tokio::select! { msg = ws_read.next() => { - match msg { - Some(Ok(Message::Text(text))) => { - let req: Request = match serde_json::from_str(&text) { - Ok(r) => r, - Err(e) => { - tracing::debug!(error = %e, "unrecognised WS message"); - continue; - } - }; - tracing::debug!(?req, "ws request"); - let resp = dispatch(req, ®istry).await; - let json = serde_json::to_string(&resp)?; - ws_write.send(Message::Text(json)).await?; - } + let text = match msg { + Some(Ok(Message::Text(text))) => text, Some(Ok(Message::Close(_))) | None => break, - Some(Ok(_)) => {} + Some(Ok(_)) => continue, Some(Err(e)) => { tracing::warn!(error = %e, "ws error"); break; } + }; + let reply = match role { + Role::System => system_request(&text, ®istry).await, + Role::App(session_id) => { + app_request(&text, session_id, ®istry).await; + None + } + }; + if let Some(reply) = reply { + ws_write.send(Message::Text(serde_json::to_string(&reply)?)).await?; } } notification = broadcast_rx.recv() => { - match notification { - Ok(resp) => { - let json = serde_json::to_string(&resp)?; - ws_write.send(Message::Text(json)).await?; + let notification = match notification { + Ok(notification) => notification, + Err(broadcast::error::RecvError::Lagged(missed)) => { + tracing::warn!(missed, "ws client missed notifications"); + continue; } - Err(broadcast::error::RecvError::Lagged(_)) => {} Err(broadcast::error::RecvError::Closed) => break, + }; + match (&role, notification) { + (Role::System, Response::IpcMessage { .. }) => {} + (Role::System, other) => { + ws_write.send(Message::Text(serde_json::to_string(&other)?)).await?; + } + (Role::App(bound), Response::IpcMessage { session_id, payload }) + if *bound == session_id => + { + let message = serde_json::json!({ "type": "APP_MESSAGE", "payload": payload }); + ws_write.send(Message::Text(message.to_string())).await?; + } + (Role::App(bound), Response::AppState { session_id, state: AppStateKind::Stopped }) + if *bound == session_id => break, + (Role::App(_), _) => {} } } } } + let _ = ws_write.close().await; Ok(()) } + +/// Dispatches a system-role request. Application messages are not part of +/// the system role's authority. +async fn system_request(text: &str, registry: &Registry) -> Option { + let request: Request = match serde_json::from_str(text) { + Ok(request) => request, + Err(e) => { + tracing::debug!(error = %e, "unrecognised system ws message"); + return None; + } + }; + if matches!(request, Request::IpcForward { .. }) { + return Some(Response::Error { + code: 403, + message: "application messages are not available to the system role".to_owned(), + }); + } + Some(dispatch(request, registry).await) +} + +/// Forwards an application message to the bound session's component. +async fn app_request(text: &str, session_id: u64, registry: &Registry) { + let payload = match serde_json::from_str::(text) { + Ok(AppRequest::AppMessage { payload }) => payload, + Err(e) => { + tracing::debug!(session_id, error = %e, "unrecognised app ws message"); + return; + } + }; + // The component reads newline-delimited messages; a payload is dropped + // rather than altered when it cannot be framed that way. + if payload.len() > MAX_APP_PAYLOAD || payload.contains('\n') { + tracing::warn!( + session_id, + len = payload.len(), + "application payload rejected" + ); + return; + } + let Some(tx) = registry.lock().await.ipc_sender_for(session_id) else { + tracing::debug!(session_id, "no IPC relay for session; message dropped"); + return; + }; + // A component that stops reading must not stall this connection, which + // also has to see its session stop. + match tx.try_send(payload) { + Ok(()) => {} + Err(mpsc::error::TrySendError::Full(_)) => { + tracing::warn!( + session_id, + "component is not reading; application message dropped" + ); + } + Err(mpsc::error::TrySendError::Closed(_)) => { + tracing::warn!(session_id, "IPC relay closed"); + registry.lock().await.remove_ipc_sender(session_id); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::{SessionRegistry, ipc::Response}; + use tokio::sync::Mutex; + use tokio_tungstenite::{MaybeTlsStream, WebSocketStream}; + + type Client = WebSocketStream>; + + const SYSTEM_TOKEN: &str = "0123456789abcdef0123456789abcdef"; + + /// Serves one WebSocket connection with `handle_ws_connection`. + async fn serve(registry: Registry) -> Client { + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = listener.local_addr().unwrap(); + let reg = Arc::clone(®istry); + tokio::spawn(async move { + let (stream, _) = listener.accept().await.unwrap(); + let rx = reg.lock().await.subscribe(); + let auth = Arc::new(WsAuth { + system_token: SYSTEM_TOKEN.to_owned(), + }); + handle_ws_connection(stream, reg, rx, auth).await.unwrap(); + }); + let (client, _) = tokio_tungstenite::connect_async(format!("ws://{addr}/")) + .await + .unwrap(); + client + } + + async fn send(client: &mut Client, value: serde_json::Value) { + client.send(Message::Text(value.to_string())).await.unwrap(); + } + + /// The next text message, or None if the server closed the connection. + async fn next(client: &mut Client) -> Option { + loop { + match tokio::time::timeout(Duration::from_secs(2), client.next()).await { + Ok(Some(Ok(Message::Text(text)))) => return serde_json::from_str(&text).ok(), + Ok(Some(Ok(Message::Close(_)))) | Ok(None) | Ok(Some(Err(_))) => return None, + Ok(Some(Ok(_))) => continue, + Err(_) => panic!("no message within 2 s"), + } + } + } + + /// True if nothing arrives within 300 ms. + async fn silent(client: &mut Client) -> bool { + tokio::time::timeout(Duration::from_millis(300), client.next()) + .await + .is_err() + } + + fn registry() -> Registry { + Arc::new(Mutex::new(SessionRegistry::default())) + } + + /// A session with an IPC relay channel standing in for its component. + async fn session(registry: &Registry) -> (u64, String, tokio::sync::mpsc::Receiver) { + let mut reg = registry.lock().await; + let id = reg.launch("test.app"); + let (tx, rx) = tokio::sync::mpsc::channel(8); + reg.register_ipc_sender(id, tx); + let token = reg.bridge_token(id).unwrap(); + (id, token, rx) + } + + fn refused(message: &Option) -> bool { + matches!(message, Some(m) if m["type"] == "ERROR" && m["code"] == 401) + } + + #[tokio::test] + async fn requests_before_hello_are_refused() { + let mut client = serve(registry()).await; + send(&mut client, serde_json::json!({ "type": "QUERY_RUNNING" })).await; + assert!(refused(&next(&mut client).await)); + assert!(next(&mut client).await.is_none()); + } + + #[tokio::test] + async fn wrong_system_token_is_refused() { + let mut client = serve(registry()).await; + let token = "fedcba9876543210fedcba9876543210"; + send( + &mut client, + serde_json::json!({ "type": "HELLO", "role": "system", "token": token }), + ) + .await; + assert!(refused(&next(&mut client).await)); + } + + #[tokio::test] + async fn system_role_controls_sessions_but_not_app_messages() { + let registry = registry(); + let (id, _, mut component) = session(®istry).await; + let mut client = serve(Arc::clone(®istry)).await; + send( + &mut client, + serde_json::json!({ "type": "HELLO", "role": "system", "token": SYSTEM_TOKEN }), + ) + .await; + send(&mut client, serde_json::json!({ "type": "QUERY_RUNNING" })).await; + assert_eq!(next(&mut client).await.unwrap()["type"], "RUNNING_APPS"); + + send( + &mut client, + serde_json::json!({ "type": "IPC_FORWARD", "session_id": id, "payload": "x" }), + ) + .await; + assert_eq!(next(&mut client).await.unwrap()["code"], 403); + assert!(component.try_recv().is_err()); + + let broadcast = registry.lock().await.broadcast().clone(); + let _ = broadcast.send(Response::IpcMessage { + session_id: id, + payload: "private".to_owned(), + }); + let _ = broadcast.send(Response::AppState { + session_id: id, + state: AppStateKind::Running, + }); + assert_eq!(next(&mut client).await.unwrap()["type"], "APP_STATE"); + } + + #[tokio::test] + async fn app_role_reaches_only_its_own_session() { + let registry = registry(); + let (id, token, mut component) = session(®istry).await; + let (other, _, mut other_component) = session(®istry).await; + let mut client = serve(Arc::clone(®istry)).await; + send( + &mut client, + serde_json::json!({ "type": "HELLO", "role": "app", "session_id": id, "token": token }), + ) + .await; + + send( + &mut client, + serde_json::json!({ "type": "APP_MESSAGE", "payload": "increment" }), + ) + .await; + let delivered = tokio::time::timeout(Duration::from_secs(2), component.recv()).await; + assert_eq!(delivered.unwrap().as_deref(), Some("increment")); + + // System requests and other sessions are out of reach. + send( + &mut client, + serde_json::json!({ "type": "TERMINATE_APP", "session_id": other }), + ) + .await; + send( + &mut client, + serde_json::json!({ "type": "IPC_FORWARD", "session_id": other, "payload": "x" }), + ) + .await; + assert!(silent(&mut client).await); + assert!(other_component.try_recv().is_err()); + assert!(!matches!( + registry.lock().await.state(other), + AppStateKind::NotFound + )); + + let broadcast = registry.lock().await.broadcast().clone(); + let _ = broadcast.send(Response::IpcMessage { + session_id: other, + payload: "not yours".to_owned(), + }); + let _ = broadcast.send(Response::IpcMessage { + session_id: id, + payload: "{\"count\":1}".to_owned(), + }); + let received = next(&mut client).await.unwrap(); + assert_eq!(received["type"], "APP_MESSAGE"); + assert_eq!(received["payload"], "{\"count\":1}"); + + let _ = broadcast.send(Response::AppState { + session_id: id, + state: AppStateKind::Stopped, + }); + assert!(next(&mut client).await.is_none()); + } + + #[tokio::test] + async fn app_token_of_another_or_stopped_session_is_refused() { + let registry = registry(); + let (id, _, _component) = session(®istry).await; + let (_, other_token, _other_component) = session(®istry).await; + let mut client = serve(Arc::clone(®istry)).await; + send( + &mut client, + serde_json::json!({ "type": "HELLO", "role": "app", "session_id": id, "token": other_token }), + ) + .await; + assert!(refused(&next(&mut client).await)); + + let (stopped, token, _stopped_component) = session(®istry).await; + registry + .lock() + .await + .set_state(stopped, AppStateKind::Stopped); + let mut client = serve(Arc::clone(®istry)).await; + send( + &mut client, + serde_json::json!({ "type": "HELLO", "role": "app", "session_id": stopped, "token": token }), + ) + .await; + assert!(refused(&next(&mut client).await)); + } + + #[tokio::test] + async fn app_payloads_that_cannot_be_framed_are_dropped() { + let registry = registry(); + let (id, token, mut component) = session(®istry).await; + let mut client = serve(Arc::clone(®istry)).await; + send( + &mut client, + serde_json::json!({ "type": "HELLO", "role": "app", "session_id": id, "token": token }), + ) + .await; + send( + &mut client, + serde_json::json!({ "type": "APP_MESSAGE", "payload": "a\nb" }), + ) + .await; + send( + &mut client, + serde_json::json!({ "type": "APP_MESSAGE", "payload": "ok" }), + ) + .await; + let delivered = tokio::time::timeout(Duration::from_secs(2), component.recv()).await; + assert_eq!(delivered.unwrap().as_deref(), Some("ok")); + } + + #[tokio::test] + async fn stalled_upgrade_is_closed() { + use tokio::io::AsyncReadExt; + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = listener.local_addr().unwrap(); + let reg = registry(); + let handler = tokio::spawn(async move { + let (stream, _) = listener.accept().await.unwrap(); + let rx = reg.lock().await.subscribe(); + let auth = Arc::new(WsAuth { + system_token: SYSTEM_TOKEN.to_owned(), + }); + handle_ws_connection(stream, reg, rx, auth).await + }); + // Connects but never sends the HTTP upgrade request. + let mut stream = tokio::net::TcpStream::connect(addr).await.unwrap(); + let finished = tokio::time::timeout(HELLO_TIMEOUT * 4, handler).await; + assert!(finished.expect("handler still waiting").unwrap().is_ok()); + let mut byte = [0u8; 1]; + assert_eq!(stream.read(&mut byte).await.unwrap(), 0); + } + + #[tokio::test] + async fn component_that_stops_reading_does_not_stall_the_bridge() { + let registry = registry(); + let id = { + let mut reg = registry.lock().await; + let id = reg.launch("test.app"); + let (tx, rx) = tokio::sync::mpsc::channel(1); + // The receiver stays alive but is never read. + std::mem::forget(rx); + reg.register_ipc_sender(id, tx); + id + }; + let token = registry.lock().await.bridge_token(id).unwrap(); + let mut client = serve(Arc::clone(®istry)).await; + send( + &mut client, + serde_json::json!({ "type": "HELLO", "role": "app", "session_id": id, "token": token }), + ) + .await; + for _ in 0..4 { + send( + &mut client, + serde_json::json!({ "type": "APP_MESSAGE", "payload": "increment" }), + ) + .await; + } + let broadcast = registry.lock().await.broadcast().clone(); + let _ = broadcast.send(Response::IpcMessage { + session_id: id, + payload: "still here".to_owned(), + }); + assert_eq!(next(&mut client).await.unwrap()["payload"], "still here"); + let _ = broadcast.send(Response::AppState { + session_id: id, + state: AppStateKind::Stopped, + }); + assert!(next(&mut client).await.is_none()); + } + + #[test] + fn tokens_match_requires_equal_length_and_bytes() { + assert!(tokens_match("abc", "abc")); + assert!(!tokens_match("abc", "abd")); + assert!(!tokens_match("abc", "abcd")); + assert!(!tokens_match("abc", "")); + } +} diff --git a/crates/weft-servo-shell/src/embedder.rs b/crates/weft-servo-shell/src/embedder.rs index e8c9a8c..db30713 100644 --- a/crates/weft-servo-shell/src/embedder.rs +++ b/crates/weft-servo-shell/src/embedder.rs @@ -7,8 +7,8 @@ use std::sync::{Arc, Mutex}; use servo::{ DeviceIntRect, DeviceIntSize, DevicePoint, EventLoopWaker, InputEvent, MouseButton as ServoMouseButton, MouseButtonAction, MouseButtonEvent, MouseMoveEvent, - RenderingContext, RgbaImage, ServoBuilder, ServoDelegate, ServoUrl, UserContentManager, - UserScript, WebViewBuilder, WebViewDelegate, + NavigationRequest, RenderingContext, RgbaImage, ServoBuilder, ServoDelegate, ServoUrl, + UserContentManager, UserScript, WebViewBuilder, WebViewDelegate, }; use winit::{ application::ApplicationHandler, @@ -67,6 +67,8 @@ struct FrameSignals { struct WeftWebViewDelegate { signals: Arc, + /// The system UI document; the only one the webview may show. + document: String, } impl WebViewDelegate for WeftWebViewDelegate { @@ -74,6 +76,39 @@ impl WebViewDelegate for WeftWebViewDelegate { self.signals.content.store(true, Ordering::Relaxed); self.signals.redraw.store(true, Ordering::Relaxed); } + + /// The system UI holds appd's system credential, so its webview never + /// leaves the system UI document. + fn request_navigation(&self, _webview: servo::WebView, request: NavigationRequest) { + if same_document(request.url.as_str(), &self.document) { + request.allow(); + } else { + tracing::warn!(url = %request.url, "navigation away from the system UI denied"); + request.deny(); + } + } +} + +/// Whether two URLs name the same document, ignoring any fragment. +fn same_document(a: &str, b: &str) -> bool { + fn document(url: &str) -> &str { + url.split_once('#').map_or(url, |(document, _)| document) + } + document(a) == document(b) +} + +/// `value` as a single-quoted JavaScript string literal. +fn js_string(value: &str) -> String { + let mut literal = String::with_capacity(value.len() + 2); + literal.push('\''); + for c in value.chars() { + match c { + ' '..='~' if c != '\'' && c != '\\' => literal.push(c), + _ => literal.push_str(&format!("\\u{{{:x}}}", u32::from(c))), + } + } + literal.push('\''); + literal } /// Servo preferences shared by the WEFT hosts. @@ -182,6 +217,49 @@ struct App { cursor_pos: DevicePoint, shell_client: Option, gesture_thread: Option>, + /// weft-appd's WebSocket port and system token, once both are available. + endpoint: Option, + next_endpoint_check: std::time::Instant, +} + +/// How the system UI reaches weft-appd. +#[derive(Clone, PartialEq)] +struct AppdEndpoint { + port: u16, + token: String, +} + +/// How often the shell rereads weft-appd's port and token files, which change +/// when weft-appd restarts. +const ENDPOINT_CHECK_INTERVAL: std::time::Duration = std::time::Duration::from_secs(2); + +/// Reads weft-appd's port (`WEFT_APPD_WS_PORT`, then `appd.wsport`, then +/// `default_port`) and its system token from `appd.systoken`. Only a token of +/// 32 lowercase hex characters is accepted, so it can be placed in a script. +fn appd_endpoint(default_port: u16) -> Option { + let dir = PathBuf::from(std::env::var("XDG_RUNTIME_DIR").ok()?).join("weft"); + let token = std::fs::read_to_string(dir.join("appd.systoken")).ok()?; + let token = token.trim(); + if token.len() != 32 + || !token + .bytes() + .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)) + { + return None; + } + let port = std::env::var("WEFT_APPD_WS_PORT") + .ok() + .and_then(|p| p.trim().parse().ok()) + .or_else(|| { + std::fs::read_to_string(dir.join("appd.wsport")) + .ok() + .and_then(|p| p.trim().parse().ok()) + }) + .unwrap_or(default_port); + Some(AppdEndpoint { + port, + token: token.to_owned(), + }) } impl App { @@ -200,9 +278,49 @@ impl App { cursor_pos: DevicePoint::origin(), shell_client: None, gesture_thread: None, + endpoint: None, + next_endpoint_check: std::time::Instant::now(), } } + /// Rereads the appd endpoint and hands it to the system UI. The page's + /// `weftAppdEndpoint` reconnects only when the endpoint changed, so + /// repeating the call also covers page reloads. + fn deliver_endpoint(&mut self, event_loop: &ActiveEventLoop) { + let now = std::time::Instant::now(); + if now < self.next_endpoint_check { + return; + } + self.next_endpoint_check = now + ENDPOINT_CHECK_INTERVAL; + event_loop.set_control_flow(winit::event_loop::ControlFlow::WaitUntil( + self.next_endpoint_check, + )); + self.endpoint = appd_endpoint(self.ws_port); + let (Some(endpoint), Some(webview)) = (&self.endpoint, &self.webview) else { + return; + }; + // The credential goes only to the system UI document. Navigation away + // from it is denied; the script checks the document again because a + // load can still be under way when it runs. + if !webview + .url() + .is_some_and(|url| same_document(url.as_str(), self.url.as_str())) + { + return; + } + let document = js_string(self.url.as_str().split('#').next().unwrap_or_default()); + webview.evaluate_javascript( + format!( + "window === window.top && \ + location.href.split('#')[0] === {document} && \ + typeof window.weftAppdEndpoint === 'function' && \ + window.weftAppdEndpoint({}, '{}')", + endpoint.port, endpoint.token + ), + |_| {}, + ); + } + /// Paints and presents once Servo has requested its first repaint. /// /// Nothing is presented before that request; the first frames can still be @@ -271,15 +389,11 @@ impl ApplicationHandler for App { if let Some(kit_js) = load_ui_kit_script() { user_content_manager.add_script(Rc::new(UserScript::new(kit_js, None))); } - let bridge_js = format!( - r#"(function(){{var ws=new WebSocket('ws://127.0.0.1:{p}');var q=[];var r=false;ws.onopen=function(){{r=true;q.forEach(function(m){{ws.send(JSON.stringify(m))}});q.length=0}};window.weftIpc={{send:function(m){{if(r)ws.send(JSON.stringify(m));else q.push(m)}},onmessage:null}};ws.onmessage=function(e){{if(window.weftIpc.onmessage)window.weftIpc.onmessage(JSON.parse(e.data))}}}})()"#, - p = self.ws_port - ); - user_content_manager.add_script(Rc::new(UserScript::new(bridge_js, None))); let webview = WebViewBuilder::new(&servo, rendering_context.as_dyn()) .delegate(Rc::new(WeftWebViewDelegate { signals: Arc::clone(&self.signals), + document: self.url.as_str().to_owned(), })) .user_content_manager(Rc::clone(&user_content_manager)) .url(self.url.clone().into_url()) @@ -315,16 +429,20 @@ impl ApplicationHandler for App { .as_ref() .map(|h| h.is_finished()) .unwrap_or(true); - if prev_done { - let ws_port = self.ws_port; + if let (true, Some(endpoint)) = (prev_done, self.endpoint.clone()) { self.gesture_thread = Some(std::thread::spawn(move || { - forward_gestures_to_appd(ws_port, &gestures); + forward_gestures_to_appd(&endpoint, &gestures); })); - } else { + } else if !prev_done { tracing::debug!( count = gestures.len(), "gesture forwarding in progress; dropping batch" ); + } else { + tracing::debug!( + count = gestures.len(), + "weft-appd endpoint unknown; dropping gestures" + ); } } } @@ -333,6 +451,7 @@ impl ApplicationHandler for App { event_loop.exit(); return; } + self.deliver_endpoint(event_loop); if let Some(servo) = &self.servo { servo.spin_event_loop(); } @@ -507,9 +626,12 @@ pub fn run(html_path: &Path, ws_port: u16) -> anyhow::Result<()> { .map_err(|e| anyhow::anyhow!("event loop run: {e}")) } -fn forward_gestures_to_appd(ws_port: u16, gestures: &[crate::shell_client::PendingGesture]) { +fn forward_gestures_to_appd( + endpoint: &AppdEndpoint, + gestures: &[crate::shell_client::PendingGesture], +) { use std::net::TcpStream; - let addr = format!("127.0.0.1:{ws_port}"); + let addr = format!("127.0.0.1:{}", endpoint.port); let stream = match TcpStream::connect(&addr) { Ok(s) => s, Err(e) => { @@ -525,6 +647,11 @@ fn forward_gestures_to_appd(ws_port: u16, gestures: &[crate::shell_client::Pendi return; } }; + let hello = serde_json::json!({ "type": "HELLO", "role": "system", "token": endpoint.token }); + if let Err(e) = ws.send(tungstenite::Message::Text(hello.to_string())) { + tracing::warn!("gesture forward: authentication failed: {e}"); + return; + } for g in gestures { let json = format!( r#"{{"type":"PANEL_GESTURE","gesture_type":{},"fingers":{},"dx":{},"dy":{}}}"#, diff --git a/docs/architecture.md b/docs/architecture.md index 4830af1..db9a4d6 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -12,11 +12,11 @@ Smithay-based Wayland compositor. Implements the `zweft-shell-unstable-v1` proto ### weft-servo-shell -System UI host. Renders one WebView pointing at `system-ui.html` using the embedded Servo engine (feature-gated behind `servo-embed`). Connects to the compositor as window type `panel`. Dispatches the `zweft_shell_manager_v1` event queue each frame. Forwards navigation gestures received from the compositor to `weft-appd` over WebSocket. +System UI host. Renders one WebView pointing at `system-ui.html` using the embedded Servo engine (feature-gated behind `servo-embed`). Connects to the compositor as window type `panel`. Dispatches the `zweft_shell_manager_v1` event queue each frame. Forwards navigation gestures received from the compositor to `weft-appd` over WebSocket. Reads the appd WebSocket port and system token from `$XDG_RUNTIME_DIR/weft/` and hands both to the page through `window.weftAppdEndpoint(port, token)`; the shell hands the token only to the system UI document and denies navigation away from it, and the launcher shows package names as text, never markup. ### weft-app-shell -Per-application Servo host. Spawned by `weft-appd` after the Wasm runtime signals READY. Takes `` and `` as arguments. Resolves `weft-app:///ui/index.html` and injects the `weftIpc` WebSocket bridge into the page. 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 `` and `` as arguments. Resolves `weft-app:///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 navigation outside that directory is denied. Registers with the compositor as window type `application`. Exits when the appd session ends. ### weft-appd @@ -56,10 +56,17 @@ systemd | Channel | Protocol | Purpose | |---|---|---| | weft-appd Unix socket | MessagePack | appd ↔ other system daemons | -| weft-appd WebSocket (:7410) | JSON | system-ui.html ↔ appd (gesture events, app lifecycle) | +| weft-appd WebSocket (:7410) | JSON | system-ui.html and servo-shell ↔ appd (system role: gestures, app lifecycle); app pages ↔ their session (app role) | | per-session IPC socket | newline-delimited JSON | weft-runtime ↔ weft-app-shell (weft:app/ipc) | | weft-file-portal socket | JSON-lines | weft-runtime ↔ file proxy | +### WebSocket roles + +Every WebSocket connection must complete the upgrade and send `HELLO` as its first message within 5 seconds, or appd closes it; a first message that is not a valid `HELLO` is answered with an error (code 401) before the connection is closed. Messages are limited to 1 MiB. + +- `{"type":"HELLO","role":"system","token":""}` — the token is the content of `$XDG_RUNTIME_DIR/weft/appd.systoken` (mode 0600), regenerated each time appd starts. A system client may launch, terminate and query sessions. It receives lifecycle broadcasts but never application messages, and cannot inject them (`IPC_FORWARD` is refused with code 403). +- `{"type":"HELLO","role":"app","session_id":,"token":""}` — the token is the session's bridge token, passed to `weft-app-shell` in `WEFT_BRIDGE_TOKEN` and distinct from its readiness token. An app client may only send `{"type":"APP_MESSAGE","payload":""}` (at most 64 KiB, no newlines); the payload goes to its own session's Wasm component. It receives only its own session's replies, as `APP_MESSAGE`, and is disconnected when the session stops. + ## Capability Enforcement Capabilities are declared in `wapp.toml` under `[package] capabilities`. `weft-pack check` validates that only known capabilities are listed. At runtime, `weft-appd` reads capabilities and maps them to WASI preopened directories and host function availability: @@ -95,6 +102,7 @@ Package store roots (in priority order): | `WEFT_RUNTIME_BIN` | — | Path to `weft-runtime` binary | | `WEFT_APP_SHELL_BIN` | — | Path to `weft-app-shell` binary; required to launch apps | | `WEFT_READY_TOKEN` | set by appd | Per-session readiness token passed to `weft-runtime` and `weft-app-shell` | +| `WEFT_BRIDGE_TOKEN` | set by appd | Per-session token `weft-app-shell` uses to join its session on the appd WebSocket | | `WEFT_FILE_PORTAL_BIN` | — | Path to `weft-file-portal` binary | | `WEFT_MOUNT_HELPER` | — | Path to `weft-mount-helper` binary | | `WEFT_APP_STORE` | — | Override package store root | diff --git a/infra/shell/system-ui.html b/infra/shell/system-ui.html index 1241163..1f8aeef 100644 --- a/infra/shell/system-ui.html +++ b/infra/shell/system-ui.html @@ -245,43 +245,68 @@ } }); - var APPD_WS_PORT = window.WEFT_APPD_WS_PORT || 7410; + // weft-servo-shell supplies weft-appd's port and system token through + // window.weftAppdEndpoint once weft-appd is running, and again after it + // restarts. Nothing connects before then. + var appd = null; var ws = null; var wsReconnectDelay = 1000; + var wsReconnectTimer = null; + + window.weftAppdEndpoint = function (port, token) { + if (appd && appd.port === port && appd.token === token) return; + appd = { port: port, token: token }; + wsReconnectDelay = 1000; + if (ws) { + // The close handler reconnects with the new endpoint. + ws.close(); + } else { + clearTimeout(wsReconnectTimer); + wsReconnectTimer = null; + appdConnect(); + } + }; function appdConnect() { + wsReconnectTimer = null; + if (!appd || ws) return; + var endpoint = appd; + var socket; try { - ws = new WebSocket('ws://127.0.0.1:' + APPD_WS_PORT + '/appd'); + socket = new WebSocket('ws://127.0.0.1:' + endpoint.port + '/appd'); } catch (e) { scheduleReconnect(); return; } + ws = socket; - ws.addEventListener('open', function () { + socket.addEventListener('open', function () { + if (ws !== socket) return; wsReconnectDelay = 1000; + socket.send(JSON.stringify({ type: 'HELLO', role: 'system', token: endpoint.token })); document.querySelectorAll('weft-taskbar-app').forEach(function (el) { el.remove(); }); - ws.send(JSON.stringify({ type: 'QUERY_RUNNING' })); - ws.send(JSON.stringify({ type: 'QUERY_INSTALLED_APPS' })); + socket.send(JSON.stringify({ type: 'QUERY_RUNNING' })); + socket.send(JSON.stringify({ type: 'QUERY_INSTALLED_APPS' })); }); - ws.addEventListener('message', function (ev) { + socket.addEventListener('message', function (ev) { + if (ws !== socket) return; var msg; try { msg = JSON.parse(ev.data); } catch (e) { return; } handleAppdMessage(msg); }); - ws.addEventListener('close', function () { + // A failed socket also fires close, so reconnection is handled there. + socket.addEventListener('close', function () { + if (ws !== socket) return; ws = null; scheduleReconnect(); }); - - ws.addEventListener('error', function () { - ws = null; - }); } function scheduleReconnect() { - setTimeout(appdConnect, wsReconnectDelay); + if (wsReconnectTimer !== null) return; + wsReconnectTimer = setTimeout(appdConnect, wsReconnectDelay); wsReconnectDelay = Math.min(wsReconnectDelay * 2, 16000); } @@ -329,14 +354,15 @@ var icon = document.createElement('weft-app-icon'); icon.dataset.appId = app.app_id; icon.title = app.app_id + (app.version ? ' v' + app.version : ''); + // Names come from package manifests; they are set as text, never markup. icon.innerHTML = '' + - '' + (app.name || app.app_id) + ''; + ''; + icon.querySelector('text').textContent = app.name ? app.name.charAt(0).toUpperCase() : '?'; + icon.querySelector('span').textContent = app.name || app.app_id; icon.addEventListener('click', function () { if (ws && ws.readyState === WebSocket.OPEN) { ws.send(JSON.stringify({ type: 'LAUNCH_APP', app_id: app.app_id, surface_id: 0 })); @@ -398,7 +424,6 @@ setTimeout(function () { note.remove(); }, 4000); } - appdConnect(); }()); diff --git a/tests/frame/check_counter.py b/tests/frame/check_counter.py new file mode 100644 index 0000000..aa8ecdb --- /dev/null +++ b/tests/frame/check_counter.py @@ -0,0 +1,258 @@ +"""Check that the Counter demo's UI actions reach its Wasm component and back. + +The harness runs weft-appd on a nested desktop (see session.py) with +weft-runtime (built with wasmtime-runtime) and weft-app-shell, launches +`org.weft.demo.counter` as the trusted system client, and drives the page +with real keyboard input routed by weft-compositor: + +1. The page must appear once weft-appd reports APP_READY. +2. ArrowUp, ArrowUp, ArrowDown are sent. The page keeps no count of its own; + it shows the value the component returns over the authenticated session + bridge. The count area must therefore change after each key (0 -> 1 -> 2) + and look exactly as it did at 1 after ArrowDown. + +Requires Xvfb, xwd, ImageMagick's convert and xdotool. +""" + +import argparse +import base64 +import json +import os +import shutil +import socket +import struct +import sys +import time +from pathlib import Path + +sys.dont_write_bytecode = True +from session import ROOT, Desktop, SessionError, bounding_box, missing_tools, parse_ppm # noqa: E402 + + +APP_ID = "org.weft.demo.counter" +PAGE = (15, 15, 15) # The Counter page's background, #0f0f0f. +CARD = (26, 26, 26) # The Counter card's background, #1a1a1a. +STARTUP_TIMEOUT = 120.0 + + +class AppdClient: + """Minimal WebSocket client for weft-appd's system role.""" + + def __init__(self, port, token): + self.sock = socket.create_connection(("127.0.0.1", port), timeout=10) + key = base64.b64encode(os.urandom(16)).decode() + self.sock.sendall((f"GET /appd HTTP/1.1\r\nHost: 127.0.0.1:{port}\r\n" + "Upgrade: websocket\r\nConnection: Upgrade\r\n" + f"Sec-WebSocket-Key: {key}\r\nSec-WebSocket-Version: 13\r\n\r\n") + .encode()) + response = b"" + while b"\r\n\r\n" not in response: + chunk = self.sock.recv(1) + if not chunk: + raise SessionError("weft-appd closed the WebSocket handshake") + response += chunk + if b" 101 " not in response.split(b"\r\n", 1)[0]: + raise SessionError("weft-appd refused the WebSocket handshake") + self.send({"type": "HELLO", "role": "system", "token": token}) + + def send(self, message): + data = json.dumps(message).encode() + mask = os.urandom(4) + if len(data) < 126: + header = bytes([0x81, 0x80 | len(data)]) + else: + header = bytes([0x81, 0x80 | 126]) + struct.pack(">H", len(data)) + self.sock.sendall(header + mask + bytes(b ^ mask[i % 4] for i, b in enumerate(data))) + + def _exact(self, count): + data = b"" + while len(data) < count: + chunk = self.sock.recv(count - len(data)) + if not chunk: + raise EOFError + data += chunk + return data + + def receive(self, timeout): + """The next JSON message, or None when the connection closes.""" + self.sock.settimeout(timeout) + try: + header = self._exact(2) + except EOFError: + return None + length = header[1] & 0x7F + if length == 126: + length = struct.unpack(">H", self._exact(2))[0] + elif length == 127: + length = struct.unpack(">Q", self._exact(8))[0] + payload = self._exact(length) + if header[0] & 0x0F == 0x8: + return None + return json.loads(payload) + + def wait_for(self, predicate, timeout): + deadline = time.monotonic() + timeout + while time.monotonic() < deadline: + message = self.receive(max(0.1, deadline - time.monotonic())) + if message is None: + raise SessionError("weft-appd closed the connection") + if predicate(message): + return message + raise TimeoutError + + +def read_endpoint(runtime, timeout): + """weft-appd's port and system token once it has written both.""" + def endpoint(): + try: + port = int((runtime / "weft/appd.wsport").read_text().strip()) + token = (runtime / "weft/appd.systoken").read_text().strip() + except (OSError, ValueError): + return None + return port, token + + deadline = time.monotonic() + timeout + while time.monotonic() < deadline: + found = endpoint() + if found: + return found + time.sleep(0.2) + raise SessionError("weft-appd did not publish its endpoint") + + +def free_port(): + with socket.socket() as probe: + probe.bind(("127.0.0.1", 0)) + return probe.getsockname()[1] + + +def find_card(screenshot): + """The Counter card's bounds, searched inside the page. + + The desktop around the application window has the card's colour too, so + the search is limited to the area the page background spans. + """ + width, height, pixels = parse_ppm(screenshot) + page = bounding_box(width, height, pixels, PAGE) + if not page: + return None + x0, y0, x1, y1 = page + crop_width = x1 - x0 + 1 + crop = b"".join(pixels[(y * width + x0) * 3:(y * width + x1 + 1) * 3] for y in range(y0, y1 + 1)) + card = bounding_box(crop_width, y1 - y0 + 1, crop, CARD) + if not card: + return None + return card[0] + x0, card[1] + y0, card[2] + x0, card[3] + y0 + + +def count_area(screenshot, card): + """Pixels of the count, the upper middle of the Counter card.""" + width, _, pixels = parse_ppm(screenshot) + x0, y0, x1, y1 = card + cx = (x0 + x1) // 2 + top, bottom = y0 + (y1 - y0) // 5, y0 + (y1 - y0) // 2 + rows = [pixels[(y * width + cx - 80) * 3:(y * width + cx + 80) * 3] for y in range(top, bottom)] + return b"".join(rows) + + +def run(args, desktop, xdotool): + port = free_port() + target = Path(args.target) + desktop.launch_client("appd", [target / "weft-appd"], { + "WEFT_RUNTIME_BIN": str(target / "weft-runtime"), + "WEFT_APP_SHELL_BIN": str(target / "weft-app-shell"), + "WEFT_APP_STORE": str(args.store), + "WEFT_DISABLE_CGROUP": "1", + "WEFT_APPD_WS_PORT": str(port), + }) + port, token = read_endpoint(desktop.runtime, 30) + appd = AppdClient(port, token) + appd.send({"type": "LAUNCH_APP", "app_id": APP_ID, "surface_id": 0}) + try: + appd.wait_for(lambda m: m.get("type") == "APP_READY", STARTUP_TIMEOUT) + except TimeoutError: + raise AssertionError("no APP_READY") + + def capture_card(): + deadline = time.monotonic() + 10 + while time.monotonic() < deadline: + shot = desktop.capture() + card = find_card(shot) + if card and card[2] - card[0] > 200 and card[3] - card[1] > 200: + return shot, card + time.sleep(0.3) + raise AssertionError("Counter card not on screen") + + shot, card = capture_card() + states = [count_area(shot, card)] + + def act(*arguments): + subprocess_run(xdotool, desktop.display, arguments) + + act("search", "--class", "weft-compositor", "windowfocus", "--sync") + # Click inside the card, away from the buttons, for keyboard focus. + act("mousemove", "--sync", str((card[0] + card[2]) // 2), str(card[1] + 12)) + act("click", "1") + + def press(key, description, expect_change_from): + act("key", key) + deadline = time.monotonic() + 10 + while time.monotonic() < deadline: + area = count_area(desktop.capture(), card) + if area != expect_change_from: + time.sleep(0.5) + return count_area(desktop.capture(), card) + time.sleep(0.2) + raise AssertionError(f"{description}: count did not change") + + states.append(press("Up", "first ArrowUp", states[0])) + states.append(press("Up", "second ArrowUp", states[1])) + states.append(press("Down", "ArrowDown", states[2])) + if len({states[0], states[1], states[2]}) != 3: + raise AssertionError("counts 0, 1 and 2 are not distinct on screen") + if states[3] != states[1]: + raise AssertionError("count after ArrowDown does not match the count after one ArrowUp") + + +def subprocess_run(xdotool, display, arguments): + import subprocess + subprocess.run([xdotool, *arguments], env={"DISPLAY": display}, check=True, timeout=20) + + +def main(argv=None): + parser = argparse.ArgumentParser(description=__doc__, + formatter_class=argparse.RawDescriptionHelpFormatter) + parser.add_argument("--compositor", type=Path, default=ROOT / "target/debug/weft-compositor") + parser.add_argument("--target", type=Path, default=ROOT / "target/debug", + help="directory with weft-appd, weft-runtime and weft-app-shell") + parser.add_argument("--store", type=Path, default=ROOT / "examples", + help="app store containing org.weft.demo.counter") + parser.add_argument("--output", type=Path, default=ROOT / "target/counter-check") + args = parser.parse_args(argv) + + xdotool = shutil.which("xdotool") + missing = missing_tools() + ([] if xdotool else ["xdotool"]) + missing += [str(p) for p in (args.compositor, args.target / "weft-appd", + args.target / "weft-runtime", args.target / "weft-app-shell") + if not p.is_file()] + if missing: + print("missing: " + ", ".join(missing), file=sys.stderr) + return 2 + try: + with Desktop(args.compositor, args.output, outputs=["appd.log", "counter.ppm"]) as desktop: + try: + run(args, desktop, xdotool) + except AssertionError as failure: + (args.output / "counter.ppm").write_bytes(desktop.capture()) + print(f"counter check failed: {failure}", file=sys.stderr) + print(f"logs and capture in {args.output}", file=sys.stderr) + return 1 + except SessionError as error: + print(error, file=sys.stderr) + return 1 + print("counter check passed") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main())