From 7cf8639ae35d8e4f4407c4913012c77b75ac1c64 Mon Sep 17 00:00:00 2001 From: Marco Allegretti Date: Fri, 9 Oct 2026 15:07:33 +0000 Subject: [PATCH 1/5] fix(compositor): bind each app session's Wayland client to its session through appd The compositor stored appd's (pid, session) announcements and never used them, so no surface could be attributed to a session and any client could claim any app ID or the panel role. weft-appd now creates a connected socket pair for each session, gives the app shell one end as standard input with WAYLAND_SOCKET=0 and no WAYLAND_DISPLAY, and sends the other end to the compositor with the session and app ID over the compositor IPC socket (SCM_RIGHTS). The compositor inserts it as a client bound to that session: holding the connection is the session's identity. A session's zweft_shell windows carry its app ID, the panel and overlay roles are refused to sessions with a new role_not_permitted error, the session's first toplevel is reported to appd, an ended session's client is closed, and a client's disconnection is reported. The compositor accepts one appd connection at a time. The counter desktop check now requires the compositor to bind the app's client to its session and to close it when the session is terminated. --- Cargo.lock | 2 + crates/weft-appd/Cargo.toml | 1 + crates/weft-appd/src/compositor_client.rs | 86 ++++++-- crates/weft-appd/src/main.rs | 118 ++++++++++- crates/weft-appd/src/runtime.rs | 102 ++++++--- crates/weft-compositor/Cargo.toml | 1 + crates/weft-compositor/src/appd_ipc.rs | 246 ++++++++++++++++++++-- crates/weft-compositor/src/state.rs | 48 ++++- crates/weft-ipc-types/src/lib.rs | 31 +-- docs/architecture.md | 4 +- docs/security.md | 4 +- protocol/weft-shell-unstable-v1.xml | 7 + tests/frame/check_counter.py | 18 +- 13 files changed, 570 insertions(+), 98 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 20cbbdf..82580ef 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -10473,6 +10473,7 @@ dependencies = [ "futures-util", "libc", "rmp-serde", + "rustix 1.1.4", "sd-notify", "serde", "serde_json", @@ -10494,6 +10495,7 @@ version = "0.1.0" dependencies = [ "anyhow", "bitflags 2.11.0", + "rustix 1.1.4", "sd-notify", "smithay", "smithay-drm-extras", diff --git a/crates/weft-appd/Cargo.toml b/crates/weft-appd/Cargo.toml index 62b004e..d1fbeea 100644 --- a/crates/weft-appd/Cargo.toml +++ b/crates/weft-appd/Cargo.toml @@ -21,6 +21,7 @@ futures-util = { version = "0.3", default-features = false, features = ["sink", tracing = "0.1" tracing-subscriber = { version = "0.3", features = ["env-filter"] } libc = "0.2" +rustix = { version = "1", features = ["net"] } [target.'cfg(unix)'.dependencies] sd-notify = "0.4" diff --git a/crates/weft-appd/src/compositor_client.rs b/crates/weft-appd/src/compositor_client.rs index 3b97437..01bb1ac 100644 --- a/crates/weft-appd/src/compositor_client.rs +++ b/crates/weft-appd/src/compositor_client.rs @@ -1,3 +1,4 @@ +use std::os::fd::OwnedFd; use std::path::PathBuf; use tokio::io::AsyncWriteExt; @@ -6,7 +7,19 @@ use weft_ipc_types::{ AppdToCompositor, CompositorToAppd, MAX_FRAME_LEN, frame_decode, frame_encode, }; -pub type CompositorSender = mpsc::Sender; +/// A message for the compositor and the file descriptor it carries, if any. +pub struct Outbound { + pub msg: AppdToCompositor, + pub fd: Option, +} + +impl From for Outbound { + fn from(msg: AppdToCompositor) -> Self { + Self { msg, fd: None } + } +} + +pub type CompositorSender = mpsc::Sender; /// Resolve the compositor IPC socket path. /// @@ -26,15 +39,14 @@ pub fn socket_path() -> Option { /// /// The task connects to `socket_path`, retrying every 2 s on failure. If the /// connection drops while sending, it waits 500 ms then reconnects. Incoming -/// `CompositorToAppd` frames are decoded and logged; no behavioural action is -/// taken yet (surface lifecycle hookup happens in a later task). +/// `CompositorToAppd` frames are decoded and logged. pub fn spawn(socket_path: PathBuf) -> CompositorSender { - let (tx, rx) = mpsc::channel::(32); + let (tx, rx) = mpsc::channel::(32); tokio::spawn(run_client(socket_path, rx)); tx } -async fn run_client(socket_path: PathBuf, mut rx: mpsc::Receiver) { +async fn run_client(socket_path: PathBuf, mut rx: mpsc::Receiver) { loop { let stream = loop { match tokio::net::UnixStream::connect(&socket_path).await { @@ -53,17 +65,22 @@ async fn run_client(socket_path: PathBuf, mut rx: mpsc::Receiver { - if write_half.write_all(&frame).await.is_err() { - tracing::warn!("compositor IPC write failed; reconnecting"); - break; - } + let frame = match frame_encode(&outbound.msg) { + Ok(frame) => frame, + Err(e) => { + tracing::warn!(?e, "compositor IPC encode error"); + continue; } - Err(e) => tracing::warn!(?e, "compositor IPC encode error"), + }; + if send_frame(&mut write_half, &frame, outbound.fd) + .await + .is_err() + { + tracing::warn!("compositor IPC write failed; reconnecting"); + break; } } @@ -71,6 +88,45 @@ async fn run_client(socket_path: PathBuf, mut rx: mpsc::Receiver, +) -> std::io::Result<()> { + use rustix::net::{SendAncillaryBuffer, SendAncillaryMessage, SendFlags, sendmsg}; + use std::mem::MaybeUninit; + use std::os::fd::AsFd; + let Some(fd) = fd else { + return stream.write_all(frame).await; + }; + let socket: &tokio::net::UnixStream = stream.as_ref(); + let sent = loop { + socket.writable().await?; + let result = socket.try_io(tokio::io::Interest::WRITABLE, || { + let mut space = [MaybeUninit::uninit(); rustix::cmsg_space!(ScmRights(1))]; + let mut control = SendAncillaryBuffer::new(&mut space); + let fds = [fd.as_fd()]; + control.push(SendAncillaryMessage::ScmRights(&fds)); + sendmsg( + socket, + &[std::io::IoSlice::new(frame)], + &mut control, + SendFlags::NOSIGNAL, + ) + .map_err(std::io::Error::from) + }); + match result { + Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => continue, + other => break other?, + } + }; + // The descriptor travelled with the first bytes; the rest of a partly + // sent frame follows as plain data. + stream.write_all(&frame[sent..]).await +} + async fn read_unix_incoming(mut reader: tokio::net::unix::OwnedReadHalf) { use tokio::io::AsyncReadExt; @@ -110,8 +166,8 @@ fn handle_incoming(msg: CompositorToAppd) { CompositorToAppd::SurfaceReady { session_id } => { tracing::debug!(session_id, "SurfaceReady from compositor"); } - CompositorToAppd::ClientDisconnected { pid } => { - tracing::debug!(pid, "ClientDisconnected from compositor"); + CompositorToAppd::ClientDisconnected { session_id } => { + tracing::debug!(session_id, "ClientDisconnected from compositor"); } } } diff --git a/crates/weft-appd/src/main.rs b/crates/weft-appd/src/main.rs index 433b0e8..a8c75ac 100644 --- a/crates/weft-appd/src/main.rs +++ b/crates/weft-appd/src/main.rs @@ -8,15 +8,7 @@ use anyhow::Context; use tokio::io::AsyncWriteExt; use tokio::sync::Mutex; -#[cfg(unix)] mod compositor_client; -#[cfg(not(unix))] -mod compositor_client { - use tokio::sync::mpsc; - use weft_ipc_types::AppdToCompositor; - - pub type CompositorSender = mpsc::Sender; -} mod grants; mod ipc; mod launch; @@ -1249,6 +1241,116 @@ mod tests { assert!(!session_ipc_socket_path(session_id).unwrap().exists()); } + #[tokio::test(flavor = "current_thread")] + async fn the_app_shell_connects_only_through_its_session_connection() { + use std::io::BufRead; + 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_attach_{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let app = dir.join("store/org.example.attach"); + write_test_package(&app, "org.example.attach", ""); + // Each child writes its Wayland environment to its standard input, + // which only the app shell has connected to anything. + let child = dir.join("child.sh"); + std::fs::write( + &child, + "#!/bin/sh\nprintf '%s %s\\n' \"${WAYLAND_SOCKET-unset}\" \ + \"${WAYLAND_DISPLAY-unset}\" >&0 2>/dev/null\n\ + echo READY $WEFT_READY_TOKEN\nexec sleep 1\n", + ) + .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()), + ("WAYLAND_DISPLAY", "wayland-ambient".into()), + ]; + 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 (tx, mut compositor) = tokio::sync::mpsc::channel(8); + registry.lock().await.compositor_tx = Some(tx); + let mut rx = registry.lock().await.subscribe(); + let ack = dispatch( + Request::LaunchApp { + app_id: "org.example.attach".into(), + surface_id: 0, + }, + ®istry, + ) + .await; + let attached = tokio::time::timeout(std::time::Duration::from_secs(10), compositor.recv()) + .await + .ok() + .flatten(); + 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 released = compositor.try_recv().ok().map(|out| out.msg); + + 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); + let Response::LaunchAck { session_id, .. } = ack else { + panic!("{ack:?}"); + }; + assert!(stopped.is_ok(), "session did not stop"); + let attached = attached.expect("no connection was handed to the compositor"); + assert!( + matches!( + &attached.msg, + weft_ipc_types::AppdToCompositor::AttachClient { session_id: s, app_id } + if *s == session_id && app_id == "org.example.attach" + ), + "{:?}", + attached.msg + ); + // The compositor's end reaches the app shell, which sees only + // WAYLAND_SOCKET and no display to connect to instead. + let stream = std::os::unix::net::UnixStream::from(attached.fd.expect("no descriptor")); + stream + .set_read_timeout(Some(std::time::Duration::from_secs(5))) + .unwrap(); + let mut line = String::new(); + std::io::BufReader::new(stream) + .read_line(&mut line) + .unwrap(); + assert_eq!(line.trim(), "0 unset"); + assert!( + matches!( + released, + Some(weft_ipc_types::AppdToCompositor::AppSurfaceDestroyed { session_id: s }) + if s == session_id + ), + "{released:?}" + ); + } + #[tokio::test(flavor = "current_thread")] async fn children_receive_the_resolved_package_files() { use std::os::unix::fs::PermissionsExt; diff --git a/crates/weft-appd/src/runtime.rs b/crates/weft-appd/src/runtime.rs index 6f9cce9..1106155 100644 --- a/crates/weft-appd/src/runtime.rs +++ b/crates/weft-appd/src/runtime.rs @@ -191,8 +191,26 @@ fn spawn_app_shell( package: &LaunchPackage, token: &str, bridge_token: Option, + wayland: Option, ) -> std::io::Result { let mut command = tokio::process::Command::new(bin); + match wayland { + // The app shell's only Wayland connection is the one created for its + // session, handed over as its standard input: WAYLAND_SOCKET names + // that descriptor, and no display socket is offered to connect + // anywhere else. Only this child receives the descriptor. + Some(stream) => { + command + .stdin(std::process::Stdio::from(std::os::fd::OwnedFd::from( + stream, + ))) + .env("WAYLAND_SOCKET", "0") + .env_remove("WAYLAND_DISPLAY"); + } + None => { + command.stdin(std::process::Stdio::null()); + } + } 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. @@ -204,7 +222,6 @@ fn spawn_app_shell( .arg("--ui") .arg(&package.ui_entry) .env(READY_TOKEN_ENV, token) - .stdin(std::process::Stdio::null()) .stdout(std::process::Stdio::piped()) .stderr(std::process::Stdio::piped()) .kill_on_drop(true) @@ -330,7 +347,7 @@ pub(crate) async fn supervise( relay: Some(relay), image, compositor_tx, - surface_announced: false, + client_attached: false, }; let mut runtime = match cmd.spawn() { @@ -341,23 +358,6 @@ pub(crate) async fn supervise( .await; } }; - if let Some(tx) = &session.compositor_tx { - let pid = runtime.id().unwrap_or(0); - // A full queue (compositor disconnected) must not stall the session. - session.surface_announced = tx - .try_send(AppdToCompositor::AppSurfaceCreated { - app_id: app_id.to_owned(), - session_id, - pid, - }) - .is_ok(); - if !session.surface_announced { - tracing::warn!( - session_id, - "compositor queue unavailable; surface not announced" - ); - } - } let runtime_stdout = runtime.stdout.take().expect("stdout piped"); tokio::spawn(drain_stderr( runtime.stderr.take().expect("stderr piped"), @@ -377,16 +377,35 @@ pub(crate) async fn supervise( }; tokio::spawn(drain_stdout(runtime_stdout, session_id)); - let bridge_token = registry.lock().await.bridge_token(session_id); - let mut app_shell = - match spawn_app_shell(&shell_bin, session_id, &package, &token, bridge_token) { - Ok(child) => child, - Err(e) => { - return session - .settle(®istry, &format!("failed to spawn app shell: {e}")) - .await; + // With a compositor, the app shell connects only through a connection + // the compositor received for this session, so every surface it creates + // is bound to the session. + let wayland = match &session.compositor_tx { + None => None, + Some(tx) => match attach_client(tx, session_id, app_id) { + Ok(stream) => { + session.client_attached = true; + Some(stream) } - }; + Err(reason) => return session.settle(®istry, &reason).await, + }, + }; + let bridge_token = registry.lock().await.bridge_token(session_id); + let mut app_shell = match spawn_app_shell( + &shell_bin, + session_id, + &package, + &token, + bridge_token, + wayland, + ) { + Ok(child) => child, + Err(e) => { + return session + .settle(®istry, &format!("failed to spawn app shell: {e}")) + .await; + } + }; let shell_stdout = app_shell.stdout.take().expect("stdout piped"); tokio::spawn(drain_stderr( app_shell.stderr.take().expect("stderr piped"), @@ -438,6 +457,26 @@ pub(crate) async fn supervise( session.settle(®istry, &reason).await } +/// Creates the session's Wayland connection and queues the compositor's end +/// for the compositor, returning the app shell's end. +fn attach_client( + tx: &CompositorSender, + session_id: u64, + app_id: &str, +) -> Result { + let (shell, compositor) = std::os::unix::net::UnixStream::pair() + .map_err(|e| format!("cannot create the app's Wayland connection: {e}"))?; + tx.try_send(crate::compositor_client::Outbound { + msg: AppdToCompositor::AttachClient { + session_id, + app_id: app_id.to_owned(), + }, + fd: Some(compositor.into()), + }) + .map_err(|_| "the compositor connection is not available".to_owned())?; + Ok(shell) +} + /// Marks a session that never started any process as stopped. async fn stop_unstarted( registry: &Registry, @@ -467,7 +506,8 @@ struct OwnedSession { /// The mounted package image, released after both children have exited. image: Option, compositor_tx: Option, - surface_announced: bool, + /// Whether the compositor was given this session's client connection. + client_attached: bool, } impl OwnedSession { @@ -476,10 +516,10 @@ impl OwnedSession { tracing::info!(session_id, reason, "stopping session"); kill_child(self.app_shell).await; kill_child(self.runtime).await; - if self.surface_announced + if self.client_attached && let Some(tx) = &self.compositor_tx && tx - .try_send(AppdToCompositor::AppSurfaceDestroyed { session_id }) + .try_send(AppdToCompositor::AppSurfaceDestroyed { session_id }.into()) .is_err() { tracing::warn!( diff --git a/crates/weft-compositor/Cargo.toml b/crates/weft-compositor/Cargo.toml index 3db3c76..e3d4ce1 100644 --- a/crates/weft-compositor/Cargo.toml +++ b/crates/weft-compositor/Cargo.toml @@ -26,6 +26,7 @@ wayland-scanner = "0.31" wayland-server = "0.31" wayland-backend = "0.3" bitflags = "2" +rustix = { version = "1", features = ["net"] } # DRM/KMS and hardware input depend on Linux kernel interfaces; compile only on Linux. [target.'cfg(target_os = "linux")'.dependencies] diff --git a/crates/weft-compositor/src/appd_ipc.rs b/crates/weft-compositor/src/appd_ipc.rs index 4fdadef..d1a5532 100644 --- a/crates/weft-compositor/src/appd_ipc.rs +++ b/crates/weft-compositor/src/appd_ipc.rs @@ -1,13 +1,17 @@ #[cfg(unix)] use std::{ - collections::HashMap, - io::{self, Read, Write}, + collections::{HashMap, HashSet, VecDeque}, + io, + os::fd::OwnedFd, os::unix::net::{UnixListener, UnixStream}, path::PathBuf, + sync::Arc, }; #[cfg(unix)] -use smithay::reexports::calloop::{Interest, Mode, PostAction, generic::Generic}; +use smithay::reexports::calloop::{Interest, Mode, PostAction, channel, generic::Generic}; +#[cfg(unix)] +use smithay::reexports::wayland_server::backend::{ClientId, DisconnectReason}; #[cfg(unix)] use weft_ipc_types::{ @@ -15,15 +19,28 @@ use weft_ipc_types::{ }; #[cfg(unix)] -use crate::state::WeftCompositorState; +use crate::state::{SessionBinding, WeftClientState, WeftCompositorState}; + +/// Descriptors received ahead of the messages that claim them; more than +/// this means the peer is not following the protocol. +#[cfg(unix)] +const MAX_PENDING_FDS: usize = 16; #[cfg(unix)] pub struct WeftAppdIpc { pub socket_path: PathBuf, read_buf: Vec, write_stream: Option, - /// pid → (app_id, session_id) for Wayland clients whose surface has not yet arrived. - pub pending_pids: HashMap, + /// Descriptors received with appd messages, in arrival order. Each + /// `AttachClient` frame is sent with exactly one, attached to its first + /// bytes, so it has arrived by the time the frame is decoded. + fds: VecDeque, + /// The Wayland client of each appd session. + sessions: HashMap, + /// Sessions whose first toplevel was reported to appd. + reported: HashSet, + /// Where clients report their session's disconnection. + disconnected: Option>, } #[cfg(unix)] @@ -33,12 +50,15 @@ impl WeftAppdIpc { socket_path, read_buf: Vec::new(), write_stream: None, - pending_pids: HashMap::new(), + fds: VecDeque::new(), + sessions: HashMap::new(), + reported: HashSet::new(), + disconnected: None, } } - #[allow(dead_code)] pub fn send(&mut self, msg: &CompositorToAppd) { + use std::io::Write; let Some(stream) = &mut self.write_stream else { return; }; @@ -52,6 +72,13 @@ impl WeftAppdIpc { } } + /// Reports a session's first toplevel to appd. + pub fn surface_created(&mut self, session_id: u64) { + if self.sessions.contains_key(&session_id) && self.reported.insert(session_id) { + self.send(&CompositorToAppd::SurfaceReady { session_id }); + } + } + fn try_decode_frames(&mut self) -> Vec { let mut out = Vec::new(); loop { @@ -83,17 +110,35 @@ impl WeftAppdIpc { out } - pub fn on_read(&mut self, stream: &mut UnixStream) -> (Vec, bool) { + /// Reads what is available, keeping descriptors that arrive with the + /// data, and returns the complete messages and whether appd hung up. + pub fn on_read(&mut self, stream: &UnixStream) -> (Vec, bool) { + use rustix::net::{RecvAncillaryBuffer, RecvAncillaryMessage, RecvFlags, recvmsg}; + use std::mem::MaybeUninit; let mut buf = [0u8; 8192]; let mut eof = false; loop { - match stream.read(&mut buf) { - Ok(0) => { + let mut space = [MaybeUninit::uninit(); rustix::cmsg_space!(ScmRights(4))]; + let mut control = RecvAncillaryBuffer::new(&mut space); + let received = recvmsg( + stream, + &mut [io::IoSliceMut::new(&mut buf)], + &mut control, + RecvFlags::CMSG_CLOEXEC | RecvFlags::DONTWAIT, + ); + for message in control.drain() { + if let RecvAncillaryMessage::ScmRights(fds) = message { + self.fds.extend(fds); + } + } + match received { + Ok(msg) if msg.bytes == 0 => { eof = true; break; } - Ok(n) => self.read_buf.extend_from_slice(&buf[..n]), - Err(e) if e.kind() == io::ErrorKind::WouldBlock => break, + Ok(msg) => self.read_buf.extend_from_slice(&buf[..msg.bytes]), + Err(rustix::io::Errno::AGAIN) => break, + Err(rustix::io::Errno::INTR) => continue, Err(e) => { tracing::warn!(?e, "appd IPC stream read error"); eof = true; @@ -101,10 +146,15 @@ impl WeftAppdIpc { } } } + if self.fds.len() > MAX_PENDING_FDS { + tracing::warn!("appd sent descriptors without messages; disconnecting"); + eof = true; + } let messages = self.try_decode_frames(); if eof { self.write_stream = None; self.read_buf.clear(); + self.fds.clear(); } (messages, eof) } @@ -113,18 +163,21 @@ impl WeftAppdIpc { #[cfg(unix)] fn handle_message(state: &mut WeftCompositorState, msg: AppdToCompositor) { match msg { - AppdToCompositor::AppSurfaceCreated { - app_id, - session_id, - pid, - } => { - tracing::debug!(app_id, session_id, pid, "AppSurfaceCreated"); - if let Some(ipc) = &mut state.appd_ipc { - ipc.pending_pids.insert(pid, (app_id, session_id)); - } + AppdToCompositor::AttachClient { session_id, app_id } => { + attach_client(state, session_id, app_id); } AppdToCompositor::AppSurfaceDestroyed { session_id } => { - tracing::debug!(session_id, "AppSurfaceDestroyed"); + let Some(ipc) = state.appd_ipc.as_mut() else { + return; + }; + ipc.reported.remove(&session_id); + if let Some(client) = ipc.sessions.remove(&session_id) { + tracing::info!(session_id, "closing the client of an ended session"); + state + .display_handle + .backend_handle() + .kill_client(client, DisconnectReason::ConnectionClosed); + } } AppdToCompositor::AppFocusRequest { session_id } => { tracing::debug!(session_id, "AppFocusRequest"); @@ -132,6 +185,54 @@ fn handle_message(state: &mut WeftCompositorState, msg: AppdToCompositor) { } } +/// Makes the descriptor that came with an `AttachClient` message a Wayland +/// client bound to `session_id`. +#[cfg(unix)] +fn attach_client(state: &mut WeftCompositorState, session_id: u64, app_id: String) { + let Some(ipc) = state.appd_ipc.as_mut() else { + return; + }; + let Some(fd) = ipc.fds.pop_front() else { + tracing::warn!( + session_id, + "AttachClient arrived without a connection; ignored" + ); + return; + }; + if !weft_ipc_types::package::is_valid_app_id(&app_id) { + tracing::warn!(session_id, "AttachClient with an invalid app ID; ignored"); + return; + } + if ipc.sessions.contains_key(&session_id) { + tracing::warn!( + session_id, + "session already has a client; connection refused" + ); + return; + } + let Some(disconnected) = ipc.disconnected.clone() else { + return; + }; + let stream = UnixStream::from(fd); + let data = Arc::new(WeftClientState { + session: Some(SessionBinding { + session_id, + app_id: app_id.clone(), + disconnected, + }), + ..WeftClientState::default() + }); + match state.display_handle.insert_client(stream, data) { + Ok(client) => { + tracing::info!(session_id, %app_id, "client bound to session"); + if let Some(ipc) = state.appd_ipc.as_mut() { + ipc.sessions.insert(session_id, client.id()); + } + } + Err(e) => tracing::warn!(session_id, ?e, "cannot add the session's client"), + } +} + #[cfg(unix)] pub fn compositor_socket_path() -> PathBuf { if let Ok(p) = std::env::var("WEFT_COMPOSITOR_SOCKET") { @@ -168,6 +269,25 @@ pub fn setup(state: &mut WeftCompositorState) -> anyhow::Result<()> { tracing::info!(path = %socket_path.display(), "compositor IPC socket open"); + // Clients bound to a session report their disconnection here. + let (sender, receiver) = channel::channel::(); + if let Some(ipc) = state.appd_ipc.as_mut() { + ipc.disconnected = Some(sender); + } + state + .loop_handle + .insert_source(receiver, |event, _, state| { + if let channel::Event::Msg(session_id) = event + && let Some(ipc) = state.appd_ipc.as_mut() + { + ipc.sessions.remove(&session_id); + ipc.reported.remove(&session_id); + tracing::info!(session_id, "session client disconnected"); + ipc.send(&CompositorToAppd::ClientDisconnected { session_id }); + } + }) + .map_err(|e| anyhow::anyhow!("insert session disconnect source: {e}"))?; + let handle = state.loop_handle.clone(); state .loop_handle @@ -177,6 +297,18 @@ pub fn setup(state: &mut WeftCompositorState) -> anyhow::Result<()> { loop { match listener.accept() { Ok((stream, _addr)) => { + // One appd at a time: a second connection while + // one is live is refused rather than replacing it. + if state + .appd_ipc + .as_ref() + .is_some_and(|ipc| ipc.write_stream.is_some()) + { + tracing::warn!( + "second compositor IPC connection refused; weft-appd is connected" + ); + continue; + } tracing::info!("weft-appd connected to compositor IPC"); let write_clone = match stream.try_clone() { Ok(c) => c, @@ -188,6 +320,7 @@ pub fn setup(state: &mut WeftCompositorState) -> anyhow::Result<()> { if let Some(ipc) = &mut state.appd_ipc { ipc.write_stream = Some(write_clone); ipc.read_buf.clear(); + ipc.fds.clear(); } stream.set_nonblocking(true).ok(); let _ = handle.insert_source( @@ -225,3 +358,70 @@ pub fn setup(state: &mut WeftCompositorState) -> anyhow::Result<()> { Ok(()) } + +#[cfg(all(test, unix))] +mod tests { + use super::*; + use rustix::net::{SendAncillaryBuffer, SendAncillaryMessage, SendFlags, sendmsg}; + use std::mem::MaybeUninit; + use std::os::fd::AsFd; + + fn send_with_fd(stream: &UnixStream, bytes: &[u8], fd: &impl AsFd) { + let mut space = [MaybeUninit::uninit(); rustix::cmsg_space!(ScmRights(1))]; + let mut control = SendAncillaryBuffer::new(&mut space); + let fds = [fd.as_fd()]; + assert!(control.push(SendAncillaryMessage::ScmRights(&fds))); + let sent = sendmsg( + stream, + &[io::IoSlice::new(bytes)], + &mut control, + SendFlags::empty(), + ) + .unwrap(); + assert_eq!(sent, bytes.len()); + } + + #[test] + fn a_connection_arrives_with_the_message_that_claims_it() { + let (appd, compositor) = UnixStream::pair().unwrap(); + compositor.set_nonblocking(true).unwrap(); + let (shell, client) = UnixStream::pair().unwrap(); + let frame = frame_encode(&AppdToCompositor::AttachClient { + session_id: 7, + app_id: "org.weft.demo.counter".into(), + }) + .unwrap(); + send_with_fd(&appd, &frame, &client); + drop(client); + + let mut ipc = WeftAppdIpc::new(PathBuf::from("/nonexistent")); + let (messages, eof) = ipc.on_read(&compositor); + assert!(!eof); + assert!(matches!( + messages.as_slice(), + [AppdToCompositor::AttachClient { session_id: 7, .. }] + )); + // The received descriptor is the other end of the shell's connection. + let received = UnixStream::from(ipc.fds.pop_front().expect("no descriptor")); + use std::io::{Read, Write}; + (&shell).write_all(b"hello").unwrap(); + let mut buf = [0u8; 5]; + (&received).read_exact(&mut buf).unwrap(); + assert_eq!(&buf, b"hello"); + } + + #[test] + fn descriptors_without_messages_end_the_connection() { + let (appd, compositor) = UnixStream::pair().unwrap(); + compositor.set_nonblocking(true).unwrap(); + let (_shell, client) = UnixStream::pair().unwrap(); + let mut ipc = WeftAppdIpc::new(PathBuf::from("/nonexistent")); + for _ in 0..=MAX_PENDING_FDS { + send_with_fd(&appd, &[0], &client); + } + let (messages, eof) = ipc.on_read(&compositor); + assert!(messages.is_empty()); + assert!(eof); + assert!(ipc.fds.is_empty()); + } +} diff --git a/crates/weft-compositor/src/state.rs b/crates/weft-compositor/src/state.rs index 82960da..b0dac77 100644 --- a/crates/weft-compositor/src/state.rs +++ b/crates/weft-compositor/src/state.rs @@ -53,11 +53,27 @@ use smithay::{ #[derive(Default)] pub struct WeftClientState { pub compositor_state: CompositorClientState, + /// The appd session this client's connection was created for. Clients + /// that connect through the display socket have none. + pub session: Option, +} + +/// The appd session a client belongs to, established by weft-appd handing +/// the compositor the client's connection, never by the client itself. +pub struct SessionBinding { + pub session_id: u64, + pub app_id: String, + /// Reports the session's disconnection to the event loop. + pub disconnected: smithay::reexports::calloop::channel::Sender, } impl ClientData for WeftClientState { fn initialized(&self, _client_id: ClientId) {} - fn disconnected(&self, _client_id: ClientId, _reason: DisconnectReason) {} + fn disconnected(&self, _client_id: ClientId, _reason: DisconnectReason) { + if let Some(binding) = &self.session { + let _ = binding.disconnected.send(binding.session_id); + } + } } /// Accumulated state for a multi-touch swipe gesture in progress. @@ -241,8 +257,16 @@ impl XdgShellHandler for WeftCompositorState { fn new_toplevel(&mut self, surface: ToplevelSurface) { surface.send_configure(); + let session = surface.wl_surface().client().and_then(|client| { + client + .get_data::() + .and_then(|data| data.session.as_ref().map(|s| s.session_id)) + }); let window = Window::new_wayland_window(surface); self.space.map_element(window, (0, 0), false); + if let (Some(session_id), Some(ipc)) = (session, self.appd_ipc.as_mut()) { + ipc.surface_created(session_id); + } } fn new_popup(&mut self, surface: PopupSurface, positioner: PositionerState) { @@ -466,7 +490,7 @@ impl GlobalDispatch for WeftCompositorState { impl Dispatch for WeftCompositorState { fn request( state: &mut Self, - _client: &Client, + client: &Client, _resource: &ZweftShellManagerV1, request: zweft_shell_manager_v1::Request, _data: &(), @@ -486,6 +510,14 @@ impl Dispatch for WeftCompositorState { width, height, } => { + // An application session's windows carry the identity appd + // bound to its connection, and only the trusted shell, which + // connects through the display socket, may take shell roles. + let session = client + .get_data::() + .and_then(|data| data.session.as_ref()); + let shell_role = matches!(role.as_str(), "panel" | "overlay"); + let app_id = session.map_or(app_id, |s| s.app_id.clone()); let is_panel = role == "panel"; let window = data_init.init( id, @@ -497,6 +529,18 @@ impl Dispatch for WeftCompositorState { closed: std::sync::atomic::AtomicBool::new(false), }, ); + if let Some(session) = session + && shell_role + { + window.post_error( + crate::protocols::server::zweft_shell_window_v1::Error::RoleNotPermitted, + format!( + "session {} ({}) may not create shell windows", + session.session_id, session.app_id + ), + ); + return; + } if is_panel { let (ox, oy, ow, oh) = state .space diff --git a/crates/weft-ipc-types/src/lib.rs b/crates/weft-ipc-types/src/lib.rs index 0590c77..c7d74f8 100644 --- a/crates/weft-ipc-types/src/lib.rs +++ b/crates/weft-ipc-types/src/lib.rs @@ -10,11 +10,16 @@ pub const MAX_FRAME_LEN: usize = 4 * 1024 * 1024; #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(tag = "type", rename_all = "snake_case")] pub enum AppdToCompositor { - AppSurfaceCreated { - app_id: String, + /// Hands the compositor its end of the Wayland connection weft-appd + /// created for the session's app shell. The frame is sent with exactly + /// one file descriptor attached (SCM_RIGHTS): the compositor end of that + /// connection. Holding the connection is the session's identity; no + /// client-supplied ID or process ID is trusted for it. + AttachClient { session_id: u64, - pid: u32, + app_id: String, }, + /// The session ended; the compositor closes its client and windows. AppSurfaceDestroyed { session_id: u64, }, @@ -27,8 +32,10 @@ pub enum AppdToCompositor { #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(tag = "type", rename_all = "snake_case")] pub enum CompositorToAppd { + /// The session's client mapped its first toplevel. SurfaceReady { session_id: u64 }, - ClientDisconnected { pid: u32 }, + /// The session's Wayland client disconnected. + ClientDisconnected { session_id: u64 }, } /// Encode a message as a length-prefixed MessagePack frame. @@ -111,23 +118,17 @@ mod tests { use super::*; #[test] - fn roundtrip_appd_to_compositor_surface_created() { - let msg = AppdToCompositor::AppSurfaceCreated { + fn roundtrip_appd_to_compositor_attach_client() { + let msg = AppdToCompositor::AttachClient { app_id: "com.example.app".into(), session_id: 42, - pid: 1234, }; let frame = frame_encode(&msg).unwrap(); let decoded: AppdToCompositor = frame_decode(&frame).unwrap(); match decoded { - AppdToCompositor::AppSurfaceCreated { - app_id, - session_id, - pid, - } => { + AppdToCompositor::AttachClient { app_id, session_id } => { assert_eq!(app_id, "com.example.app"); assert_eq!(session_id, 42); - assert_eq!(pid, 1234); } _ => panic!("unexpected variant"), } @@ -168,11 +169,11 @@ mod tests { #[test] fn roundtrip_compositor_to_appd_disconnected() { - let msg = CompositorToAppd::ClientDisconnected { pid: 5678 }; + let msg = CompositorToAppd::ClientDisconnected { session_id: 5678 }; let frame = frame_encode(&msg).unwrap(); let decoded: CompositorToAppd = frame_decode(&frame).unwrap(); match decoded { - CompositorToAppd::ClientDisconnected { pid } => assert_eq!(pid, 5678), + CompositorToAppd::ClientDisconnected { session_id } => assert_eq!(session_id, 5678), _ => panic!("unexpected variant"), } } diff --git a/docs/architecture.md b/docs/architecture.md index ee92a31..33f0f8a 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -8,7 +8,7 @@ WEFT OS is a Wayland compositor and application runtime where every app is a Web ### weft-compositor -Smithay-based Wayland compositor. Implements the `zweft-shell-unstable-v1` protocol extension, which allows shell clients (servo-shell, app-shell) to register their surfaces as typed shell slots. Supports DRM/KMS and winit (software/dev) backends. +Smithay-based Wayland compositor. Implements the `zweft-shell-unstable-v1` protocol extension, which allows shell clients (servo-shell, app-shell) to register their surfaces as typed shell slots. Each application session's Wayland connection is handed to the compositor by weft-appd, which binds the client to that session (see `security.md`). Supports DRM/KMS and winit (software/dev) backends. ### weft-servo-shell @@ -16,7 +16,7 @@ System UI host. Renders one WebView pointing at `system-ui.html` using the embed ### weft-app-shell -Per-application Servo host. Spawned by `weft-appd` after the Wasm runtime signals READY. Takes ``, `` and `--ui `, 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. +Per-application Servo host. Spawned by `weft-appd` after the Wasm runtime signals READY. Takes ``, `` and `--ui `, 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`, over the one Wayland connection weft-appd created for its session and passed as standard input (`WAYLAND_SOCKET=0`). Exits when the appd session ends. ### weft-appd diff --git a/docs/security.md b/docs/security.md index 09a6b4a..d17bd78 100644 --- a/docs/security.md +++ b/docs/security.md @@ -30,7 +30,9 @@ For verified read-only package storage, `weft-pack build-image` produces an EROF ## Wayland Surface Isolation -Each app registers its surface with the compositor via `zweft_shell_manager_v1`. The compositor enforces that each surface belongs to the session that created it. The app cannot render outside its assigned surface slot. +Each app shell has exactly one Wayland connection, created for its session. weft-appd creates a connected socket pair, gives one end to the app shell as its standard input with `WAYLAND_SOCKET=0` and no `WAYLAND_DISPLAY`, and sends the other end to the compositor over the compositor IPC socket (`SCM_RIGHTS`) with the session ID and app ID. The compositor adds that end as a client bound to the session; the binding comes from appd holding the connection, never from an ID or process ID the client supplies. A session's `zweft_shell` windows carry the session's app ID whatever the client requests, and the shell-only `panel` and `overlay` roles are refused with a protocol error. When the session ends, the compositor closes its client; when the client disconnects, the compositor reports it to appd. The compositor accepts one appd connection at a time. + +Not yet covered: the compositor IPC socket accepts any process of the user while no appd is connected, so the first connection after a restart is trusted as appd; window placement, stacking, focus and close are not yet decided by the compositor per session (all toplevels start at the origin); and the trusted system shell is identified only by connecting through the display socket, which any process of the user can open. ## JavaScript Engine (SpiderMonkey) diff --git a/protocol/weft-shell-unstable-v1.xml b/protocol/weft-shell-unstable-v1.xml index 339eb11..f208b62 100644 --- a/protocol/weft-shell-unstable-v1.xml +++ b/protocol/weft-shell-unstable-v1.xml @@ -65,6 +65,11 @@ object identity; no separate window_id is exchanged. The compositor will emit configure on the new object to communicate the effective initial geometry and state. + + For a client that the compositor associated with an application + session, the session's application identifier replaces the app_id + argument, and the panel and overlay roles are refused with the + role_not_permitted error on the new window. @@ -114,6 +119,8 @@ + diff --git a/tests/frame/check_counter.py b/tests/frame/check_counter.py index aa8ecdb..ed4a8e1 100644 --- a/tests/frame/check_counter.py +++ b/tests/frame/check_counter.py @@ -169,9 +169,16 @@ def run(args, desktop, xdotool): 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) + ready = appd.wait_for(lambda m: m.get("type") == "APP_READY", STARTUP_TIMEOUT) except TimeoutError: raise AssertionError("no APP_READY") + session_id = ready["session_id"] + + # The app's only Wayland connection is the one appd handed the + # compositor for this session. + bound = f"client bound to session session_id={session_id} app_id={APP_ID}" + if bound not in desktop.log_text("compositor"): + raise AssertionError(f"the compositor did not bind the app's client: {bound!r}") def capture_card(): deadline = time.monotonic() + 10 @@ -213,6 +220,15 @@ def run(args, desktop, xdotool): if states[3] != states[1]: raise AssertionError("count after ArrowDown does not match the count after one ArrowUp") + # Ending the session closes its client in the compositor. + appd.send({"type": "TERMINATE_APP", "session_id": session_id}) + deadline = time.monotonic() + 15 + closed = f"closing the client of an ended session session_id={session_id}" + while closed not in desktop.log_text("compositor"): + if time.monotonic() > deadline: + raise AssertionError(f"the compositor did not close the session's client: {closed!r}") + time.sleep(0.3) + def subprocess_run(xdotool, display, arguments): import subprocess From 4c778330a37d63279f5cb5d31af617d5cb2c0500 Mon Sep 17 00:00:00 2001 From: Marco Allegretti Date: Fri, 9 Oct 2026 15:15:01 +0000 Subject: [PATCH 2/5] fix(compositor): keep shell-level interfaces from sessions and harden the appd connection Session clients could still create layer-shell surfaces, including full-screen overlays with exclusive keyboard input, and bind the input method, which bypassed the refusal of shell roles. Both globals are now hidden from clients bound to a session. The compositor IPC connection is tracked by its read source, so a write error can no longer let a second peer feed the same buffers; a failed write shuts the connection down. An undecodable or oversized frame ends the connection, since descriptors could otherwise pair with the wrong messages, and the descriptor limit counts only descriptors no message claims, so a burst of launches is not taken for abuse. When appd's connection ends, the compositor closes the clients of the sessions it attached. weft-appd notices when the compositor closes the connection, resends a message whose write failed after reconnecting, and refuses a launch while the compositor is not connected instead of starting an app shell that can never connect. --- crates/weft-appd/src/compositor_client.rs | 67 +++++++++-- crates/weft-appd/src/main.rs | 84 +++++++++++++- crates/weft-appd/src/runtime.rs | 3 + crates/weft-compositor/src/appd_ipc.rs | 128 ++++++++++++++++++---- crates/weft-compositor/src/state.rs | 15 ++- docs/security.md | 4 +- 6 files changed, 265 insertions(+), 36 deletions(-) diff --git a/crates/weft-appd/src/compositor_client.rs b/crates/weft-appd/src/compositor_client.rs index 01bb1ac..84d6b81 100644 --- a/crates/weft-appd/src/compositor_client.rs +++ b/crates/weft-appd/src/compositor_client.rs @@ -1,5 +1,7 @@ use std::os::fd::OwnedFd; use std::path::PathBuf; +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, Ordering}; use tokio::io::AsyncWriteExt; use tokio::sync::mpsc; @@ -19,7 +21,27 @@ impl From for Outbound { } } -pub type CompositorSender = mpsc::Sender; +/// Queues messages for the compositor and tells whether it is connected. +#[derive(Clone)] +pub struct CompositorSender { + tx: mpsc::Sender, + connected: Arc, +} + +impl CompositorSender { + pub fn new(tx: mpsc::Sender, connected: Arc) -> Self { + Self { tx, connected } + } + + /// Whether the compositor IPC connection is currently up. + pub fn is_connected(&self) -> bool { + self.connected.load(Ordering::Acquire) + } + + pub fn try_send(&self, outbound: Outbound) -> Result<(), Outbound> { + self.tx.try_send(outbound).map_err(|e| e.into_inner()) + } +} /// Resolve the compositor IPC socket path. /// @@ -37,16 +59,24 @@ pub fn socket_path() -> Option { /// Spawn the compositor IPC client task and return a sender for outbound messages. /// -/// The task connects to `socket_path`, retrying every 2 s on failure. If the -/// connection drops while sending, it waits 500 ms then reconnects. Incoming +/// The task connects to `socket_path`, retrying every 2 s on failure. When +/// the connection drops, whether noticed by a failed write or by the +/// compositor closing it, it waits 500 ms and reconnects; a message whose +/// write failed is sent again on the new connection. Incoming /// `CompositorToAppd` frames are decoded and logged. pub fn spawn(socket_path: PathBuf) -> CompositorSender { let (tx, rx) = mpsc::channel::(32); - tokio::spawn(run_client(socket_path, rx)); - tx + let connected = Arc::new(AtomicBool::new(false)); + tokio::spawn(run_client(socket_path, rx, connected.clone())); + CompositorSender::new(tx, connected) } -async fn run_client(socket_path: PathBuf, mut rx: mpsc::Receiver) { +async fn run_client( + socket_path: PathBuf, + mut rx: mpsc::Receiver, + connected: Arc, +) { + let mut unsent: Option = None; loop { let stream = loop { match tokio::net::UnixStream::connect(&socket_path).await { @@ -61,12 +91,22 @@ async fn run_client(socket_path: PathBuf, mut rx: mpsc::Receiver) { }; let (read_half, mut write_half) = stream.into_split(); - - tokio::spawn(read_unix_incoming(read_half)); + let mut reader = tokio::spawn(read_unix_incoming(read_half)); + connected.store(true, Ordering::Release); loop { - let Some(outbound) = rx.recv().await else { - return; + let outbound = match unsent.take() { + Some(outbound) => outbound, + None => tokio::select! { + next = rx.recv() => match next { + Some(outbound) => outbound, + None => return, + }, + _ = &mut reader => { + tracing::warn!("compositor closed the IPC connection; reconnecting"); + break; + } + }, }; let frame = match frame_encode(&outbound.msg) { Ok(frame) => frame, @@ -75,14 +115,17 @@ async fn run_client(socket_path: PathBuf, mut rx: mpsc::Receiver) { continue; } }; - if send_frame(&mut write_half, &frame, outbound.fd) + if send_frame(&mut write_half, &frame, outbound.fd.as_ref()) .await .is_err() { tracing::warn!("compositor IPC write failed; reconnecting"); + unsent = Some(outbound); break; } } + connected.store(false, Ordering::Release); + reader.abort(); tokio::time::sleep(tokio::time::Duration::from_millis(500)).await; } @@ -93,7 +136,7 @@ async fn run_client(socket_path: PathBuf, mut rx: mpsc::Receiver) { async fn send_frame( stream: &mut tokio::net::unix::OwnedWriteHalf, frame: &[u8], - fd: Option, + fd: Option<&OwnedFd>, ) -> std::io::Result<()> { use rustix::net::{SendAncillaryBuffer, SendAncillaryMessage, SendFlags, sendmsg}; use std::mem::MaybeUninit; diff --git a/crates/weft-appd/src/main.rs b/crates/weft-appd/src/main.rs index a8c75ac..e367f39 100644 --- a/crates/weft-appd/src/main.rs +++ b/crates/weft-appd/src/main.rs @@ -1241,6 +1241,85 @@ mod tests { assert!(!session_ipc_socket_path(session_id).unwrap().exists()); } + #[tokio::test(flavor = "current_thread")] + async fn without_a_connected_compositor_the_app_shell_is_not_started() { + 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_nocomp_{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let app = dir.join("store/org.example.nocomp"); + write_test_package(&app, "org.example.nocomp", ""); + // Each child records that it started. + let log = dir.join("started.log"); + let child = dir.join("child.sh"); + std::fs::write( + &child, + format!( + "#!/bin/sh\necho started >> '{}'\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 (tx, mut compositor) = tokio::sync::mpsc::channel(8); + registry.lock().await.compositor_tx = Some(compositor_client::CompositorSender::new( + tx, + std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)), + )); + let mut rx = registry.lock().await.subscribe(); + let _ = dispatch( + Request::LaunchApp { + app_id: "org.example.nocomp".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 started = 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!(stopped.is_ok(), "session did not stop"); + // Only the runtime started; no app shell, and nothing was queued. + assert_eq!(started.lines().count(), 1, "{started}"); + assert!(compositor.try_recv().is_err()); + } + #[tokio::test(flavor = "current_thread")] async fn the_app_shell_connects_only_through_its_session_connection() { use std::io::BufRead; @@ -1280,7 +1359,10 @@ mod tests { let registry = make_registry(); let (tx, mut compositor) = tokio::sync::mpsc::channel(8); - registry.lock().await.compositor_tx = Some(tx); + registry.lock().await.compositor_tx = Some(compositor_client::CompositorSender::new( + tx, + std::sync::Arc::new(std::sync::atomic::AtomicBool::new(true)), + )); let mut rx = registry.lock().await.subscribe(); let ack = dispatch( Request::LaunchApp { diff --git a/crates/weft-appd/src/runtime.rs b/crates/weft-appd/src/runtime.rs index 1106155..95e8fbd 100644 --- a/crates/weft-appd/src/runtime.rs +++ b/crates/weft-appd/src/runtime.rs @@ -464,6 +464,9 @@ fn attach_client( session_id: u64, app_id: &str, ) -> Result { + if !tx.is_connected() { + return Err("weft-compositor is not connected, so the app cannot show a window".to_owned()); + } let (shell, compositor) = std::os::unix::net::UnixStream::pair() .map_err(|e| format!("cannot create the app's Wayland connection: {e}"))?; tx.try_send(crate::compositor_client::Outbound { diff --git a/crates/weft-compositor/src/appd_ipc.rs b/crates/weft-compositor/src/appd_ipc.rs index d1a5532..2f129d2 100644 --- a/crates/weft-compositor/src/appd_ipc.rs +++ b/crates/weft-compositor/src/appd_ipc.rs @@ -31,6 +31,9 @@ pub struct WeftAppdIpc { pub socket_path: PathBuf, read_buf: Vec, write_stream: Option, + /// Whether an appd connection's read source is registered. Only one + /// connection is served at a time. + connected: bool, /// Descriptors received with appd messages, in arrival order. Each /// `AttachClient` frame is sent with exactly one, attached to its first /// bytes, so it has arrived by the time the frame is decoded. @@ -50,6 +53,7 @@ impl WeftAppdIpc { socket_path, read_buf: Vec::new(), write_stream: None, + connected: false, fds: VecDeque::new(), sessions: HashMap::new(), reported: HashSet::new(), @@ -65,6 +69,10 @@ impl WeftAppdIpc { match frame_encode(msg) { Ok(frame) => { if stream.write_all(&frame).is_err() { + // A partly written frame breaks the stream's framing: + // end the connection, whose read side then cleans up. + tracing::warn!("compositor IPC write failed; closing the appd connection"); + let _ = stream.shutdown(std::net::Shutdown::Both); self.write_stream = None; } } @@ -79,7 +87,10 @@ impl WeftAppdIpc { } } - fn try_decode_frames(&mut self) -> Vec { + /// Decodes the complete frames in the buffer, and reports whether the + /// stream can no longer be trusted: after an oversized or undecodable + /// frame, descriptors could be paired with the wrong messages. + fn try_decode_frames(&mut self) -> (Vec, bool) { let mut out = Vec::new(); loop { if self.read_buf.len() < 4 { @@ -93,9 +104,7 @@ impl WeftAppdIpc { ]) as usize; if declared_len > MAX_FRAME_LEN { tracing::warn!(declared_len, "appd IPC frame too large; disconnecting"); - self.write_stream = None; - self.read_buf.clear(); - break; + return (out, true); } if self.read_buf.len() < 4 + declared_len { break; @@ -103,11 +112,14 @@ impl WeftAppdIpc { let frame_end = 4 + declared_len; match frame_decode::(&self.read_buf[..frame_end]) { Ok(msg) => out.push(msg), - Err(e) => tracing::warn!(?e, "appd IPC frame decode error"), + Err(e) => { + tracing::warn!(?e, "appd IPC frame decode error; disconnecting"); + return (out, true); + } } self.read_buf.drain(..frame_end); } - out + (out, false) } /// Reads what is available, keeping descriptors that arrive with the @@ -146,18 +158,29 @@ impl WeftAppdIpc { } } } - if self.fds.len() > MAX_PENDING_FDS { + let (messages, broken) = self.try_decode_frames(); + eof |= broken; + let claimed = messages + .iter() + .filter(|m| matches!(m, AppdToCompositor::AttachClient { .. })) + .count(); + if self.fds.len().saturating_sub(claimed) > MAX_PENDING_FDS { tracing::warn!("appd sent descriptors without messages; disconnecting"); eof = true; } - let messages = self.try_decode_frames(); - if eof { - self.write_stream = None; - self.read_buf.clear(); - self.fds.clear(); - } (messages, eof) } + + /// Forgets the appd connection once its read source is gone. The + /// sessions it started are closed: they belong to that appd. + fn disconnect(&mut self) -> Vec { + self.connected = false; + self.write_stream = None; + self.read_buf.clear(); + self.fds.clear(); + self.reported.clear(); + self.sessions.drain().map(|(_, client)| client).collect() + } } #[cfg(unix)] @@ -299,11 +322,7 @@ pub fn setup(state: &mut WeftCompositorState) -> anyhow::Result<()> { Ok((stream, _addr)) => { // One appd at a time: a second connection while // one is live is refused rather than replacing it. - if state - .appd_ipc - .as_ref() - .is_some_and(|ipc| ipc.write_stream.is_some()) - { + if state.appd_ipc.as_ref().is_some_and(|ipc| ipc.connected) { tracing::warn!( "second compositor IPC connection refused; weft-appd is connected" ); @@ -319,6 +338,7 @@ pub fn setup(state: &mut WeftCompositorState) -> anyhow::Result<()> { }; if let Some(ipc) = &mut state.appd_ipc { ipc.write_stream = Some(write_clone); + ipc.connected = true; ipc.read_buf.clear(); ipc.fds.clear(); } @@ -338,8 +358,20 @@ pub fn setup(state: &mut WeftCompositorState) -> anyhow::Result<()> { } if eof { tracing::info!( - "weft-appd disconnected from compositor IPC" + "weft-appd disconnected from compositor IPC; \ + closing its sessions' clients" ); + let orphans = state + .appd_ipc + .as_mut() + .map(WeftAppdIpc::disconnect) + .unwrap_or_default(); + for client in orphans { + state.display_handle.backend_handle().kill_client( + client, + DisconnectReason::ConnectionClosed, + ); + } Ok(PostAction::Remove) } else { Ok(PostAction::Continue) @@ -422,6 +454,64 @@ mod tests { let (messages, eof) = ipc.on_read(&compositor); assert!(messages.is_empty()); assert!(eof); + ipc.disconnect(); assert!(ipc.fds.is_empty()); } + + #[test] + fn a_burst_of_attachments_is_not_mistaken_for_abuse() { + let (appd, compositor) = UnixStream::pair().unwrap(); + compositor.set_nonblocking(true).unwrap(); + let mut keep = Vec::new(); + for session_id in 0..(MAX_PENDING_FDS as u64 + 4) { + let (shell, client) = UnixStream::pair().unwrap(); + let frame = frame_encode(&AppdToCompositor::AttachClient { + session_id, + app_id: "org.weft.demo.counter".into(), + }) + .unwrap(); + send_with_fd(&appd, &frame, &client); + // A plain frame between attachments keeps its place. + let plain = frame_encode(&AppdToCompositor::AppFocusRequest { session_id }).unwrap(); + use std::io::Write; + (&appd).write_all(&plain).unwrap(); + keep.push(shell); + } + let mut ipc = WeftAppdIpc::new(PathBuf::from("/nonexistent")); + let mut messages = Vec::new(); + let mut connections = 0; + loop { + let (batch, eof) = ipc.on_read(&compositor); + assert!(!eof, "a legitimate burst ended the connection"); + if batch.is_empty() { + break; + } + // As the handler does, each attachment takes its connection. + for message in &batch { + if matches!(message, AppdToCompositor::AttachClient { .. }) { + ipc.fds + .pop_front() + .expect("an attachment without its connection"); + connections += 1; + } + } + messages.extend(batch); + } + assert_eq!(connections, MAX_PENDING_FDS + 4); + assert_eq!(messages.len(), 2 * (MAX_PENDING_FDS + 4)); + assert!(ipc.fds.is_empty()); + } + + #[test] + fn an_undecodable_frame_ends_the_connection() { + let (appd, compositor) = UnixStream::pair().unwrap(); + compositor.set_nonblocking(true).unwrap(); + use std::io::Write; + let mut frame = 3u32.to_le_bytes().to_vec(); + frame.extend_from_slice(&[0xc1, 0xc1, 0xc1]); + (&appd).write_all(&frame).unwrap(); + let mut ipc = WeftAppdIpc::new(PathBuf::from("/nonexistent")); + let (_, eof) = ipc.on_read(&compositor); + assert!(eof); + } } diff --git a/crates/weft-compositor/src/state.rs b/crates/weft-compositor/src/state.rs index b0dac77..f02ff23 100644 --- a/crates/weft-compositor/src/state.rs +++ b/crates/weft-compositor/src/state.rs @@ -67,6 +67,14 @@ pub struct SessionBinding { pub disconnected: smithay::reexports::calloop::channel::Sender, } +/// Whether `client` connected through the display socket rather than +/// through a connection weft-appd created for an application session. +pub fn outside_sessions(client: &Client) -> bool { + client + .get_data::() + .is_none_or(|data| data.session.is_none()) +} + impl ClientData for WeftClientState { fn initialized(&self, _client_id: ClientId) {} fn disconnected(&self, _client_id: ClientId, _reason: DisconnectReason) { @@ -140,7 +148,10 @@ impl WeftCompositorState { ) -> Self { let compositor_state = CompositorState::new::(&display_handle); let xdg_shell_state = XdgShellState::new::(&display_handle); - let layer_shell_state = WlrLayerShellState::new::(&display_handle); + // Layer surfaces and input methods are shell-level: an application + // session's client is not offered them. + let layer_shell_state = + WlrLayerShellState::new_with_filter::(&display_handle, outside_sessions); let shm_state = ShmState::new::(&display_handle, vec![]); let dmabuf_state = DmabufState::new(); let output_manager_state = OutputManagerState::new_with_xdg_output::(&display_handle); @@ -148,7 +159,7 @@ impl WeftCompositorState { let presentation_state = PresentationState::new::(&display_handle, 1); let text_input_state = TextInputManagerState::new::(&display_handle); let input_method_state = - InputMethodManagerState::new::(&display_handle, |_client| true); + InputMethodManagerState::new::(&display_handle, outside_sessions); let pointer_constraints_state = PointerConstraintsState::new::(&display_handle); let cursor_shape_state = CursorShapeManagerState::new::(&display_handle); let weft_shell_state = WeftShellState::new::(&display_handle); diff --git a/docs/security.md b/docs/security.md index d17bd78..3c4310c 100644 --- a/docs/security.md +++ b/docs/security.md @@ -30,9 +30,9 @@ For verified read-only package storage, `weft-pack build-image` produces an EROF ## Wayland Surface Isolation -Each app shell has exactly one Wayland connection, created for its session. weft-appd creates a connected socket pair, gives one end to the app shell as its standard input with `WAYLAND_SOCKET=0` and no `WAYLAND_DISPLAY`, and sends the other end to the compositor over the compositor IPC socket (`SCM_RIGHTS`) with the session ID and app ID. The compositor adds that end as a client bound to the session; the binding comes from appd holding the connection, never from an ID or process ID the client supplies. A session's `zweft_shell` windows carry the session's app ID whatever the client requests, and the shell-only `panel` and `overlay` roles are refused with a protocol error. When the session ends, the compositor closes its client; when the client disconnects, the compositor reports it to appd. The compositor accepts one appd connection at a time. +Each app shell is given exactly one Wayland connection, created for its session. weft-appd creates a connected socket pair, gives one end to the app shell as its standard input with `WAYLAND_SOCKET=0` and no `WAYLAND_DISPLAY`, and sends the other end to the compositor over the compositor IPC socket (`SCM_RIGHTS`) with the session ID and app ID. The compositor adds that end as a client bound to the session; the binding comes from appd holding the connection, never from an ID or process ID the client supplies. A session's `zweft_shell` windows carry the session's app ID whatever the client requests, and the shell-only `panel` and `overlay` roles are refused with a protocol error; layer-shell surfaces and the input-method interface are not offered to session clients at all. When the session ends, the compositor closes its client; when the client disconnects, the compositor reports it to appd; when appd's connection ends, the compositor closes every session client appd attached. The compositor accepts one appd connection at a time. A launch is refused while appd is not connected to the compositor, rather than starting an app that could never show a window. -Not yet covered: the compositor IPC socket accepts any process of the user while no appd is connected, so the first connection after a restart is trusted as appd; window placement, stacking, focus and close are not yet decided by the compositor per session (all toplevels start at the origin); and the trusted system shell is identified only by connecting through the display socket, which any process of the user can open. +Not yet covered: the compositor IPC socket accepts any process of the user while no appd is connected, so the first connection after a restart is trusted as appd; window placement, stacking, focus and close are not yet decided by the compositor per session (all toplevels start at the origin); and the trusted system shell is identified only by connecting through the display socket, which any process of the user, including an app shell, can open. ## JavaScript Engine (SpiderMonkey) From d6a2f94a1da60bd7fcce18ad0dfe8096b9aab39e Mon Sep 17 00:00:00 2001 From: Marco Allegretti Date: Fri, 9 Oct 2026 15:20:29 +0000 Subject: [PATCH 3/5] fix(compositor): buffer appd-bound frames and ignore stale session disconnects A full socket buffer toward a stalled appd closed the connection and with it every app. Frames for appd are now queued whole and flushed on each send and read, and only a backlog beyond the frame limit or a write error ends the connection. A disconnect report is applied only when it comes from the session's current client, so a client closed with an earlier appd cannot remove the mapping of a new session that reused its ID. A failure to watch a new appd connection no longer leaves the compositor refusing every later one. weft-appd refuses a launch with 503 before anything starts while the compositor is not connected, and waits up to 10 s for the connection before restoring the previous session. --- crates/weft-appd/src/main.rs | 45 +++++---- crates/weft-compositor/src/appd_ipc.rs | 123 ++++++++++++++++++++++--- crates/weft-compositor/src/state.rs | 6 +- docs/security.md | 2 +- 4 files changed, 142 insertions(+), 34 deletions(-) diff --git a/crates/weft-appd/src/main.rs b/crates/weft-appd/src/main.rs index e367f39..92a4c72 100644 --- a/crates/weft-appd/src/main.rs +++ b/crates/weft-appd/src/main.rs @@ -218,6 +218,14 @@ async fn run() -> anyhow::Result<()> { } if let Some(app_ids) = load_session() { + // Apps need the compositor connection; give it a moment to come up. + let compositor = registry.lock().await.compositor_tx.clone(); + if let Some(compositor) = compositor { + let deadline = tokio::time::Instant::now() + std::time::Duration::from_secs(10); + while !compositor.is_connected() && tokio::time::Instant::now() < deadline { + tokio::time::sleep(std::time::Duration::from_millis(100)).await; + } + } tracing::info!(count = app_ids.len(), "restoring previous session"); for app_id in app_ids { let _ = dispatch( @@ -438,8 +446,20 @@ pub(crate) async fn dispatch(req: Request, registry: &Registry) -> Response { // The package is resolved and its capabilities granted before a // session exists; a package this host cannot satisfy is refused, // not started. + let compositor_down = registry + .lock() + .await + .compositor_tx + .as_ref() + .is_some_and(|tx| !tx.is_connected()); let launch = if !weft_ipc_types::package::is_valid_app_id(&app_id) { Err(grants::Refusal::new(400, "invalid app ID")) + } else if compositor_down { + // An app started now could never show a window. + Err(grants::Refusal::new( + 503, + "weft-compositor is not connected", + )) } else if std::env::var("WEFT_RUNTIME_BIN").is_ok() { resolve_launch(app_id.clone()).await.map(Some) } else { @@ -1242,7 +1262,7 @@ mod tests { } #[tokio::test(flavor = "current_thread")] - async fn without_a_connected_compositor_the_app_shell_is_not_started() { + async fn without_a_connected_compositor_nothing_is_started() { use std::os::unix::fs::PermissionsExt; let _env = env_lock().lock().await; use_test_runtime_dir(); @@ -1283,8 +1303,7 @@ mod tests { tx, std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)), )); - let mut rx = registry.lock().await.subscribe(); - let _ = dispatch( + let refused = dispatch( Request::LaunchApp { app_id: "org.example.nocomp".into(), surface_id: 0, @@ -1292,16 +1311,7 @@ mod tests { ®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; + tokio::time::sleep(std::time::Duration::from_millis(500)).await; let started = std::fs::read_to_string(&log).unwrap_or_default(); for (key, value) in prior { @@ -1314,9 +1324,12 @@ mod tests { } } let _ = std::fs::remove_dir_all(&dir); - assert!(stopped.is_ok(), "session did not stop"); - // Only the runtime started; no app shell, and nothing was queued. - assert_eq!(started.lines().count(), 1, "{started}"); + assert!( + matches!(refused, Response::Error { code: 503, .. }), + "{refused:?}" + ); + // Nothing started and nothing was queued for the compositor. + assert_eq!(started, ""); assert!(compositor.try_recv().is_err()); } diff --git a/crates/weft-compositor/src/appd_ipc.rs b/crates/weft-compositor/src/appd_ipc.rs index 2f129d2..bcf658c 100644 --- a/crates/weft-compositor/src/appd_ipc.rs +++ b/crates/weft-compositor/src/appd_ipc.rs @@ -43,7 +43,10 @@ pub struct WeftAppdIpc { /// Sessions whose first toplevel was reported to appd. reported: HashSet, /// Where clients report their session's disconnection. - disconnected: Option>, + disconnected: Option>, + /// Bytes for appd that did not fit in the socket buffer, sent before + /// anything else so frames stay whole. + out_buf: Vec, } #[cfg(unix)] @@ -58,28 +61,59 @@ impl WeftAppdIpc { sessions: HashMap::new(), reported: HashSet::new(), disconnected: None, + out_buf: Vec::new(), } } pub fn send(&mut self, msg: &CompositorToAppd) { - use std::io::Write; - let Some(stream) = &mut self.write_stream else { - return; - }; match frame_encode(msg) { Ok(frame) => { - if stream.write_all(&frame).is_err() { - // A partly written frame breaks the stream's framing: - // end the connection, whose read side then cleans up. - tracing::warn!("compositor IPC write failed; closing the appd connection"); - let _ = stream.shutdown(std::net::Shutdown::Both); - self.write_stream = None; + if self.write_stream.is_some() { + self.out_buf.extend_from_slice(&frame); + self.flush(); } } Err(e) => tracing::warn!(?e, "failed to encode compositor IPC message"), } } + /// Writes what appd's socket accepts now; the rest waits for the next + /// send or read. A backlog appd never drains, or a write error, ends the + /// connection, whose read side then cleans up. + fn flush(&mut self) { + use std::io::Write; + let Some(stream) = &mut self.write_stream else { + self.out_buf.clear(); + return; + }; + while !self.out_buf.is_empty() { + match stream.write(&self.out_buf) { + Ok(0) => break, + Ok(n) => { + self.out_buf.drain(..n); + } + Err(e) if e.kind() == io::ErrorKind::WouldBlock => break, + Err(e) if e.kind() == io::ErrorKind::Interrupted => {} + Err(e) => { + tracing::warn!( + ?e, + "compositor IPC write failed; closing the appd connection" + ); + let _ = stream.shutdown(std::net::Shutdown::Both); + self.write_stream = None; + self.out_buf.clear(); + return; + } + } + } + if self.out_buf.len() > MAX_FRAME_LEN { + tracing::warn!("weft-appd is not reading compositor IPC; closing the connection"); + let _ = stream.shutdown(std::net::Shutdown::Both); + self.write_stream = None; + self.out_buf.clear(); + } + } + /// Reports a session's first toplevel to appd. pub fn surface_created(&mut self, session_id: u64) { if self.sessions.contains_key(&session_id) && self.reported.insert(session_id) { @@ -176,6 +210,7 @@ impl WeftAppdIpc { fn disconnect(&mut self) -> Vec { self.connected = false; self.write_stream = None; + self.out_buf.clear(); self.read_buf.clear(); self.fds.clear(); self.reported.clear(); @@ -293,15 +328,18 @@ pub fn setup(state: &mut WeftCompositorState) -> anyhow::Result<()> { tracing::info!(path = %socket_path.display(), "compositor IPC socket open"); // Clients bound to a session report their disconnection here. - let (sender, receiver) = channel::channel::(); + let (sender, receiver) = channel::channel::<(u64, ClientId)>(); if let Some(ipc) = state.appd_ipc.as_mut() { ipc.disconnected = Some(sender); } state .loop_handle .insert_source(receiver, |event, _, state| { - if let channel::Event::Msg(session_id) = event + // Only the session's current client: a client closed when its + // appd went away may report after a new appd reused the ID. + if let channel::Event::Msg((session_id, client)) = event && let Some(ipc) = state.appd_ipc.as_mut() + && ipc.sessions.get(&session_id) == Some(&client) { ipc.sessions.remove(&session_id); ipc.reported.remove(&session_id); @@ -343,7 +381,7 @@ pub fn setup(state: &mut WeftCompositorState) -> anyhow::Result<()> { ipc.fds.clear(); } stream.set_nonblocking(true).ok(); - let _ = handle.insert_source( + let registered = handle.insert_source( Generic::new(stream, Interest::READ, Mode::Edge), |_, stream, state| { // Safety: calloop wraps the fd in NoIoDrop to prevent @@ -356,6 +394,9 @@ pub fn setup(state: &mut WeftCompositorState) -> anyhow::Result<()> { for msg in messages { handle_message(state, msg); } + if let Some(ipc) = state.appd_ipc.as_mut() { + ipc.flush(); + } if eof { tracing::info!( "weft-appd disconnected from compositor IPC; \ @@ -378,6 +419,12 @@ pub fn setup(state: &mut WeftCompositorState) -> anyhow::Result<()> { } }, ); + if let Err(e) = registered { + tracing::warn!(?e, "cannot watch the appd IPC connection"); + if let Some(ipc) = state.appd_ipc.as_mut() { + ipc.disconnect(); + } + } } Err(e) if e.kind() == io::ErrorKind::WouldBlock => break, Err(e) => tracing::warn!(?e, "accept error on compositor IPC socket"), @@ -502,6 +549,54 @@ mod tests { assert!(ipc.fds.is_empty()); } + #[test] + fn a_slow_appd_gets_whole_frames_later_instead_of_losing_its_apps() { + let (appd, compositor) = UnixStream::pair().unwrap(); + compositor.set_nonblocking(true).unwrap(); + let mut ipc = WeftAppdIpc::new(PathBuf::from("/nonexistent")); + ipc.write_stream = Some(compositor); + ipc.connected = true; + // More than the socket buffer holds while appd is not reading. + let count = 20_000u64; + for session_id in 0..count { + ipc.send(&CompositorToAppd::SurfaceReady { session_id }); + } + assert!( + ipc.write_stream.is_some(), + "a full buffer closed the connection" + ); + assert!(!ipc.out_buf.is_empty()); + + // appd reads; every flush moves more, and every frame arrives whole. + appd.set_nonblocking(true).unwrap(); + let mut received = Vec::new(); + let mut buf = [0u8; 65536]; + loop { + ipc.flush(); + use std::io::Read; + match (&appd).read(&mut buf) { + Ok(n) => received.extend_from_slice(&buf[..n]), + Err(e) if e.kind() == io::ErrorKind::WouldBlock => { + if ipc.out_buf.is_empty() { + break; + } + } + Err(e) => panic!("{e}"), + } + } + let mut frames = 0u64; + while !received.is_empty() { + let len = u32::from_le_bytes(received[..4].try_into().unwrap()) as usize; + let frame: CompositorToAppd = frame_decode(&received[..4 + len]).unwrap(); + assert!( + matches!(frame, CompositorToAppd::SurfaceReady { session_id } if session_id == frames) + ); + received.drain(..4 + len); + frames += 1; + } + assert_eq!(frames, count); + } + #[test] fn an_undecodable_frame_ends_the_connection() { let (appd, compositor) = UnixStream::pair().unwrap(); diff --git a/crates/weft-compositor/src/state.rs b/crates/weft-compositor/src/state.rs index f02ff23..8c6a303 100644 --- a/crates/weft-compositor/src/state.rs +++ b/crates/weft-compositor/src/state.rs @@ -64,7 +64,7 @@ pub struct SessionBinding { pub session_id: u64, pub app_id: String, /// Reports the session's disconnection to the event loop. - pub disconnected: smithay::reexports::calloop::channel::Sender, + pub disconnected: smithay::reexports::calloop::channel::Sender<(u64, ClientId)>, } /// Whether `client` connected through the display socket rather than @@ -77,9 +77,9 @@ pub fn outside_sessions(client: &Client) -> bool { impl ClientData for WeftClientState { fn initialized(&self, _client_id: ClientId) {} - fn disconnected(&self, _client_id: ClientId, _reason: DisconnectReason) { + fn disconnected(&self, client_id: ClientId, _reason: DisconnectReason) { if let Some(binding) = &self.session { - let _ = binding.disconnected.send(binding.session_id); + let _ = binding.disconnected.send((binding.session_id, client_id)); } } } diff --git a/docs/security.md b/docs/security.md index 3c4310c..e16c9b0 100644 --- a/docs/security.md +++ b/docs/security.md @@ -30,7 +30,7 @@ For verified read-only package storage, `weft-pack build-image` produces an EROF ## Wayland Surface Isolation -Each app shell is given exactly one Wayland connection, created for its session. weft-appd creates a connected socket pair, gives one end to the app shell as its standard input with `WAYLAND_SOCKET=0` and no `WAYLAND_DISPLAY`, and sends the other end to the compositor over the compositor IPC socket (`SCM_RIGHTS`) with the session ID and app ID. The compositor adds that end as a client bound to the session; the binding comes from appd holding the connection, never from an ID or process ID the client supplies. A session's `zweft_shell` windows carry the session's app ID whatever the client requests, and the shell-only `panel` and `overlay` roles are refused with a protocol error; layer-shell surfaces and the input-method interface are not offered to session clients at all. When the session ends, the compositor closes its client; when the client disconnects, the compositor reports it to appd; when appd's connection ends, the compositor closes every session client appd attached. The compositor accepts one appd connection at a time. A launch is refused while appd is not connected to the compositor, rather than starting an app that could never show a window. +Each app shell is given exactly one Wayland connection, created for its session. weft-appd creates a connected socket pair, gives one end to the app shell as its standard input with `WAYLAND_SOCKET=0` and no `WAYLAND_DISPLAY`, and sends the other end to the compositor over the compositor IPC socket (`SCM_RIGHTS`) with the session ID and app ID. The compositor adds that end as a client bound to the session; the binding comes from appd holding the connection, never from an ID or process ID the client supplies. A session's `zweft_shell` windows carry the session's app ID whatever the client requests, and the shell-only `panel` and `overlay` roles are refused with a protocol error; layer-shell surfaces and the input-method interface are not offered to session clients at all. When the session ends, the compositor closes its client; when the client disconnects, the compositor reports it to appd; when appd's connection ends, the compositor closes every session client appd attached. The compositor accepts one appd connection at a time. A launch is refused (503) while appd is not connected to the compositor, before any process starts, rather than starting an app that could never show a window. Not yet covered: the compositor IPC socket accepts any process of the user while no appd is connected, so the first connection after a restart is trusted as appd; window placement, stacking, focus and close are not yet decided by the compositor per session (all toplevels start at the origin); and the trusted system shell is identified only by connecting through the display socket, which any process of the user, including an app shell, can open. From 2e27adc4f65b1801702c46c89269ae90356f6552 Mon Sep 17 00:00:00 2001 From: Marco Allegretti Date: Fri, 9 Oct 2026 15:23:41 +0000 Subject: [PATCH 4/5] fix(compositor): retry queued appd frames until sent and restore sessions in the background Frames queued for a slow appd were sent only on later traffic, so the end of a burst could wait indefinitely. A timer now retries the flush every 20 ms, armed only while frames are queued. weft-appd restores the previous session in its own task, so waiting for the compositor no longer delays clients or shutdown, and the security docs describe the launch refusal and the backlog limit exactly. --- crates/weft-appd/src/main.rs | 41 +++++++++++++++----------- crates/weft-compositor/src/appd_ipc.rs | 41 +++++++++++++++++++++++++- docs/security.md | 2 +- 3 files changed, 64 insertions(+), 20 deletions(-) diff --git a/crates/weft-appd/src/main.rs b/crates/weft-appd/src/main.rs index 92a4c72..eaf99f5 100644 --- a/crates/weft-appd/src/main.rs +++ b/crates/weft-appd/src/main.rs @@ -218,25 +218,30 @@ async fn run() -> anyhow::Result<()> { } if let Some(app_ids) = load_session() { - // Apps need the compositor connection; give it a moment to come up. - let compositor = registry.lock().await.compositor_tx.clone(); - if let Some(compositor) = compositor { - let deadline = tokio::time::Instant::now() + std::time::Duration::from_secs(10); - while !compositor.is_connected() && tokio::time::Instant::now() < deadline { - tokio::time::sleep(std::time::Duration::from_millis(100)).await; + // Restoring runs beside the request loops, so waiting for the + // compositor delays neither clients nor shutdown. + let registry = Arc::clone(®istry); + tokio::spawn(async move { + // Apps need the compositor connection; give it a moment. + let compositor = registry.lock().await.compositor_tx.clone(); + if let Some(compositor) = compositor { + let deadline = tokio::time::Instant::now() + std::time::Duration::from_secs(10); + while !compositor.is_connected() && tokio::time::Instant::now() < deadline { + tokio::time::sleep(std::time::Duration::from_millis(100)).await; + } } - } - tracing::info!(count = app_ids.len(), "restoring previous session"); - for app_id in app_ids { - let _ = dispatch( - crate::ipc::Request::LaunchApp { - app_id, - surface_id: 0, - }, - ®istry, - ) - .await; - } + tracing::info!(count = app_ids.len(), "restoring previous session"); + for app_id in app_ids { + let _ = dispatch( + crate::ipc::Request::LaunchApp { + app_id, + surface_id: 0, + }, + ®istry, + ) + .await; + } + }); } #[cfg(unix)] diff --git a/crates/weft-compositor/src/appd_ipc.rs b/crates/weft-compositor/src/appd_ipc.rs index bcf658c..95f37dc 100644 --- a/crates/weft-compositor/src/appd_ipc.rs +++ b/crates/weft-compositor/src/appd_ipc.rs @@ -9,7 +9,11 @@ use std::{ }; #[cfg(unix)] -use smithay::reexports::calloop::{Interest, Mode, PostAction, channel, generic::Generic}; +use smithay::reexports::calloop::{ + Interest, LoopHandle, Mode, PostAction, RegistrationToken, channel, + generic::Generic, + timer::{TimeoutAction, Timer}, +}; #[cfg(unix)] use smithay::reexports::wayland_server::backend::{ClientId, DisconnectReason}; @@ -47,6 +51,9 @@ pub struct WeftAppdIpc { /// Bytes for appd that did not fit in the socket buffer, sent before /// anything else so frames stay whole. out_buf: Vec, + /// Retries `flush` while `out_buf` holds bytes; armed only then. + flush_retry: Option, + loop_handle: Option>, } #[cfg(unix)] @@ -62,6 +69,8 @@ impl WeftAppdIpc { reported: HashSet::new(), disconnected: None, out_buf: Vec::new(), + flush_retry: None, + loop_handle: None, } } @@ -71,6 +80,7 @@ impl WeftAppdIpc { if self.write_stream.is_some() { self.out_buf.extend_from_slice(&frame); self.flush(); + self.schedule_flush(); } } Err(e) => tracing::warn!(?e, "failed to encode compositor IPC message"), @@ -114,6 +124,32 @@ impl WeftAppdIpc { } } + /// Retries the flush until appd has taken every queued byte, so the + /// last frames of a burst do not wait for unrelated traffic. + fn schedule_flush(&mut self) { + if self.out_buf.is_empty() || self.flush_retry.is_some() { + return; + } + let Some(handle) = &self.loop_handle else { + return; + }; + let retry = Timer::from_duration(std::time::Duration::from_millis(20)); + self.flush_retry = handle + .insert_source(retry, |_, _, state| { + let Some(ipc) = state.appd_ipc.as_mut() else { + return TimeoutAction::Drop; + }; + ipc.flush(); + if ipc.out_buf.is_empty() { + ipc.flush_retry = None; + TimeoutAction::Drop + } else { + TimeoutAction::ToDuration(std::time::Duration::from_millis(20)) + } + }) + .ok(); + } + /// Reports a session's first toplevel to appd. pub fn surface_created(&mut self, session_id: u64) { if self.sessions.contains_key(&session_id) && self.reported.insert(session_id) { @@ -327,6 +363,9 @@ pub fn setup(state: &mut WeftCompositorState) -> anyhow::Result<()> { tracing::info!(path = %socket_path.display(), "compositor IPC socket open"); + if let Some(ipc) = state.appd_ipc.as_mut() { + ipc.loop_handle = Some(state.loop_handle.clone()); + } // Clients bound to a session report their disconnection here. let (sender, receiver) = channel::channel::<(u64, ClientId)>(); if let Some(ipc) = state.appd_ipc.as_mut() { diff --git a/docs/security.md b/docs/security.md index e16c9b0..f145533 100644 --- a/docs/security.md +++ b/docs/security.md @@ -30,7 +30,7 @@ For verified read-only package storage, `weft-pack build-image` produces an EROF ## Wayland Surface Isolation -Each app shell is given exactly one Wayland connection, created for its session. weft-appd creates a connected socket pair, gives one end to the app shell as its standard input with `WAYLAND_SOCKET=0` and no `WAYLAND_DISPLAY`, and sends the other end to the compositor over the compositor IPC socket (`SCM_RIGHTS`) with the session ID and app ID. The compositor adds that end as a client bound to the session; the binding comes from appd holding the connection, never from an ID or process ID the client supplies. A session's `zweft_shell` windows carry the session's app ID whatever the client requests, and the shell-only `panel` and `overlay` roles are refused with a protocol error; layer-shell surfaces and the input-method interface are not offered to session clients at all. When the session ends, the compositor closes its client; when the client disconnects, the compositor reports it to appd; when appd's connection ends, the compositor closes every session client appd attached. The compositor accepts one appd connection at a time. A launch is refused (503) while appd is not connected to the compositor, before any process starts, rather than starting an app that could never show a window. +Each app shell is given exactly one Wayland connection, created for its session. weft-appd creates a connected socket pair, gives one end to the app shell as its standard input with `WAYLAND_SOCKET=0` and no `WAYLAND_DISPLAY`, and sends the other end to the compositor over the compositor IPC socket (`SCM_RIGHTS`) with the session ID and app ID. The compositor adds that end as a client bound to the session; the binding comes from appd holding the connection, never from an ID or process ID the client supplies. A session's `zweft_shell` windows carry the session's app ID whatever the client requests, and the shell-only `panel` and `overlay` roles are refused with a protocol error; layer-shell surfaces and the input-method interface are not offered to session clients at all. When the session ends, the compositor closes its client; when the client disconnects, the compositor reports it to appd; when appd's connection ends, the compositor closes every session client appd attached. The compositor accepts one appd connection at a time. A launch is refused (503) while appd is not connected to the compositor, rather than starting an app that could never show a window; if the connection drops between that check and the app shell's start, the session is stopped before the app shell starts. Frames for appd that its socket cannot take at once are queued and retried; a backlog beyond 4 MiB, from an appd that stopped reading, ends the connection and with it the sessions' clients. Not yet covered: the compositor IPC socket accepts any process of the user while no appd is connected, so the first connection after a restart is trusted as appd; window placement, stacking, focus and close are not yet decided by the compositor per session (all toplevels start at the origin); and the trusted system shell is identified only by connecting through the display socket, which any process of the user, including an app shell, can open. From db042fcb5c16652595065b9d1442ee578cbb502b Mon Sep 17 00:00:00 2001 From: Marco Allegretti Date: Fri, 9 Oct 2026 15:25:57 +0000 Subject: [PATCH 5/5] fix(appd): keep the previous session when shutdown interrupts its restore The session file is read and removed at startup, and restoring now runs in its own task, so a shutdown during the restore would have saved only the apps launched so far. Until the restore finishes, a shutdown stops it and saves the restored list unchanged. --- crates/weft-appd/src/main.rs | 22 ++++++++++++++++------ docs/security.md | 2 +- 2 files changed, 17 insertions(+), 7 deletions(-) diff --git a/crates/weft-appd/src/main.rs b/crates/weft-appd/src/main.rs index eaf99f5..37e706f 100644 --- a/crates/weft-appd/src/main.rs +++ b/crates/weft-appd/src/main.rs @@ -217,11 +217,13 @@ async fn run() -> anyhow::Result<()> { let _ = sd_notify::notify(false, &[sd_notify::NotifyState::Ready]); } - if let Some(app_ids) = load_session() { - // Restoring runs beside the request loops, so waiting for the - // compositor delays neither clients nor shutdown. + // Restoring runs beside the request loops, so waiting for the + // compositor delays neither clients nor shutdown. Until it finishes, + // the restored list is what a shutdown saves. + let restore = load_session().map(|app_ids| { + let saved = app_ids.clone(); let registry = Arc::clone(®istry); - tokio::spawn(async move { + let task = tokio::spawn(async move { // Apps need the compositor connection; give it a moment. let compositor = registry.lock().await.compositor_tx.clone(); if let Some(compositor) = compositor { @@ -242,7 +244,8 @@ async fn run() -> anyhow::Result<()> { .await; } }); - } + (task, saved) + }); #[cfg(unix)] let mut sigterm = { @@ -288,7 +291,14 @@ async fn run() -> anyhow::Result<()> { } } - save_session(registry.lock().await.running_app_ids()).await; + let app_ids = match restore { + Some((task, saved)) if !task.is_finished() => { + task.abort(); + saved + } + _ => registry.lock().await.running_app_ids(), + }; + save_session(app_ids).await; registry.lock().await.shutdown_all(); tokio::time::sleep(tokio::time::Duration::from_millis(200)).await; let _ = std::fs::remove_file(&socket_path); diff --git a/docs/security.md b/docs/security.md index f145533..81fd57e 100644 --- a/docs/security.md +++ b/docs/security.md @@ -30,7 +30,7 @@ For verified read-only package storage, `weft-pack build-image` produces an EROF ## Wayland Surface Isolation -Each app shell is given exactly one Wayland connection, created for its session. weft-appd creates a connected socket pair, gives one end to the app shell as its standard input with `WAYLAND_SOCKET=0` and no `WAYLAND_DISPLAY`, and sends the other end to the compositor over the compositor IPC socket (`SCM_RIGHTS`) with the session ID and app ID. The compositor adds that end as a client bound to the session; the binding comes from appd holding the connection, never from an ID or process ID the client supplies. A session's `zweft_shell` windows carry the session's app ID whatever the client requests, and the shell-only `panel` and `overlay` roles are refused with a protocol error; layer-shell surfaces and the input-method interface are not offered to session clients at all. When the session ends, the compositor closes its client; when the client disconnects, the compositor reports it to appd; when appd's connection ends, the compositor closes every session client appd attached. The compositor accepts one appd connection at a time. A launch is refused (503) while appd is not connected to the compositor, rather than starting an app that could never show a window; if the connection drops between that check and the app shell's start, the session is stopped before the app shell starts. Frames for appd that its socket cannot take at once are queued and retried; a backlog beyond 4 MiB, from an appd that stopped reading, ends the connection and with it the sessions' clients. +Each app shell is given exactly one Wayland connection, created for its session. weft-appd creates a connected socket pair, gives one end to the app shell as its standard input with `WAYLAND_SOCKET=0` and no `WAYLAND_DISPLAY`, and sends the other end to the compositor over the compositor IPC socket (`SCM_RIGHTS`) with the session ID and app ID. The compositor adds that end as a client bound to the session; the binding comes from appd holding the connection, never from an ID or process ID the client supplies. A session's `zweft_shell` windows carry the session's app ID whatever the client requests, and the shell-only `panel` and `overlay` roles are refused with a protocol error; layer-shell surfaces and the input-method interface are not offered to session clients at all. When the session ends, the compositor closes its client; when the client disconnects, the compositor reports it to appd; when appd's connection ends, the compositor closes every session client appd attached. The compositor accepts one appd connection at a time. A launch is refused (503) while appd is not connected to the compositor, rather than starting an app that could never show a window; if the compositor connection is lost before the session's connection is handed over, the session is stopped before the app shell starts. Frames for appd that its socket cannot take at once are queued and retried; a backlog beyond 4 MiB, from an appd that stopped reading, ends the connection and with it the sessions' clients. Not yet covered: the compositor IPC socket accepts any process of the user while no appd is connected, so the first connection after a restart is trusted as appd; window placement, stacking, focus and close are not yet decided by the compositor per session (all toplevels start at the origin); and the trusted system shell is identified only by connecting through the display socket, which any process of the user, including an app shell, can open.