mirror of
https://github.com/marcoallegretti/WEFT_OS.git
synced 2026-11-22 08:13:59 +00:00
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.
This commit is contained in:
parent
7cf8639ae3
commit
4c778330a3
6 changed files with 265 additions and 36 deletions
|
|
@ -1,5 +1,7 @@
|
||||||
use std::os::fd::OwnedFd;
|
use std::os::fd::OwnedFd;
|
||||||
use std::path::PathBuf;
|
use std::path::PathBuf;
|
||||||
|
use std::sync::Arc;
|
||||||
|
use std::sync::atomic::{AtomicBool, Ordering};
|
||||||
|
|
||||||
use tokio::io::AsyncWriteExt;
|
use tokio::io::AsyncWriteExt;
|
||||||
use tokio::sync::mpsc;
|
use tokio::sync::mpsc;
|
||||||
|
|
@ -19,7 +21,27 @@ impl From<AppdToCompositor> for Outbound {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub type CompositorSender = mpsc::Sender<Outbound>;
|
/// Queues messages for the compositor and tells whether it is connected.
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub struct CompositorSender {
|
||||||
|
tx: mpsc::Sender<Outbound>,
|
||||||
|
connected: Arc<AtomicBool>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl CompositorSender {
|
||||||
|
pub fn new(tx: mpsc::Sender<Outbound>, connected: Arc<AtomicBool>) -> 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.
|
/// Resolve the compositor IPC socket path.
|
||||||
///
|
///
|
||||||
|
|
@ -37,16 +59,24 @@ pub fn socket_path() -> Option<PathBuf> {
|
||||||
|
|
||||||
/// Spawn the compositor IPC client task and return a sender for outbound messages.
|
/// 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
|
/// The task connects to `socket_path`, retrying every 2 s on failure. When
|
||||||
/// connection drops while sending, it waits 500 ms then reconnects. Incoming
|
/// 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.
|
/// `CompositorToAppd` frames are decoded and logged.
|
||||||
pub fn spawn(socket_path: PathBuf) -> CompositorSender {
|
pub fn spawn(socket_path: PathBuf) -> CompositorSender {
|
||||||
let (tx, rx) = mpsc::channel::<Outbound>(32);
|
let (tx, rx) = mpsc::channel::<Outbound>(32);
|
||||||
tokio::spawn(run_client(socket_path, rx));
|
let connected = Arc::new(AtomicBool::new(false));
|
||||||
tx
|
tokio::spawn(run_client(socket_path, rx, connected.clone()));
|
||||||
|
CompositorSender::new(tx, connected)
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn run_client(socket_path: PathBuf, mut rx: mpsc::Receiver<Outbound>) {
|
async fn run_client(
|
||||||
|
socket_path: PathBuf,
|
||||||
|
mut rx: mpsc::Receiver<Outbound>,
|
||||||
|
connected: Arc<AtomicBool>,
|
||||||
|
) {
|
||||||
|
let mut unsent: Option<Outbound> = None;
|
||||||
loop {
|
loop {
|
||||||
let stream = loop {
|
let stream = loop {
|
||||||
match tokio::net::UnixStream::connect(&socket_path).await {
|
match tokio::net::UnixStream::connect(&socket_path).await {
|
||||||
|
|
@ -61,12 +91,22 @@ async fn run_client(socket_path: PathBuf, mut rx: mpsc::Receiver<Outbound>) {
|
||||||
};
|
};
|
||||||
|
|
||||||
let (read_half, mut write_half) = stream.into_split();
|
let (read_half, mut write_half) = stream.into_split();
|
||||||
|
let mut reader = tokio::spawn(read_unix_incoming(read_half));
|
||||||
tokio::spawn(read_unix_incoming(read_half));
|
connected.store(true, Ordering::Release);
|
||||||
|
|
||||||
loop {
|
loop {
|
||||||
let Some(outbound) = rx.recv().await else {
|
let outbound = match unsent.take() {
|
||||||
return;
|
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) {
|
let frame = match frame_encode(&outbound.msg) {
|
||||||
Ok(frame) => frame,
|
Ok(frame) => frame,
|
||||||
|
|
@ -75,14 +115,17 @@ async fn run_client(socket_path: PathBuf, mut rx: mpsc::Receiver<Outbound>) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
if send_frame(&mut write_half, &frame, outbound.fd)
|
if send_frame(&mut write_half, &frame, outbound.fd.as_ref())
|
||||||
.await
|
.await
|
||||||
.is_err()
|
.is_err()
|
||||||
{
|
{
|
||||||
tracing::warn!("compositor IPC write failed; reconnecting");
|
tracing::warn!("compositor IPC write failed; reconnecting");
|
||||||
|
unsent = Some(outbound);
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
connected.store(false, Ordering::Release);
|
||||||
|
reader.abort();
|
||||||
|
|
||||||
tokio::time::sleep(tokio::time::Duration::from_millis(500)).await;
|
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<Outbound>) {
|
||||||
async fn send_frame(
|
async fn send_frame(
|
||||||
stream: &mut tokio::net::unix::OwnedWriteHalf,
|
stream: &mut tokio::net::unix::OwnedWriteHalf,
|
||||||
frame: &[u8],
|
frame: &[u8],
|
||||||
fd: Option<OwnedFd>,
|
fd: Option<&OwnedFd>,
|
||||||
) -> std::io::Result<()> {
|
) -> std::io::Result<()> {
|
||||||
use rustix::net::{SendAncillaryBuffer, SendAncillaryMessage, SendFlags, sendmsg};
|
use rustix::net::{SendAncillaryBuffer, SendAncillaryMessage, SendFlags, sendmsg};
|
||||||
use std::mem::MaybeUninit;
|
use std::mem::MaybeUninit;
|
||||||
|
|
|
||||||
|
|
@ -1241,6 +1241,85 @@ mod tests {
|
||||||
assert!(!session_ipc_socket_path(session_id).unwrap().exists());
|
assert!(!session_ipc_socket_path(session_id).unwrap().exists());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[tokio::test(flavor = "current_thread")]
|
||||||
|
async fn 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")]
|
#[tokio::test(flavor = "current_thread")]
|
||||||
async fn the_app_shell_connects_only_through_its_session_connection() {
|
async fn the_app_shell_connects_only_through_its_session_connection() {
|
||||||
use std::io::BufRead;
|
use std::io::BufRead;
|
||||||
|
|
@ -1280,7 +1359,10 @@ mod tests {
|
||||||
|
|
||||||
let registry = make_registry();
|
let registry = make_registry();
|
||||||
let (tx, mut compositor) = tokio::sync::mpsc::channel(8);
|
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 mut rx = registry.lock().await.subscribe();
|
||||||
let ack = dispatch(
|
let ack = dispatch(
|
||||||
Request::LaunchApp {
|
Request::LaunchApp {
|
||||||
|
|
|
||||||
|
|
@ -464,6 +464,9 @@ fn attach_client(
|
||||||
session_id: u64,
|
session_id: u64,
|
||||||
app_id: &str,
|
app_id: &str,
|
||||||
) -> Result<std::os::unix::net::UnixStream, String> {
|
) -> Result<std::os::unix::net::UnixStream, String> {
|
||||||
|
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()
|
let (shell, compositor) = std::os::unix::net::UnixStream::pair()
|
||||||
.map_err(|e| format!("cannot create the app's Wayland connection: {e}"))?;
|
.map_err(|e| format!("cannot create the app's Wayland connection: {e}"))?;
|
||||||
tx.try_send(crate::compositor_client::Outbound {
|
tx.try_send(crate::compositor_client::Outbound {
|
||||||
|
|
|
||||||
|
|
@ -31,6 +31,9 @@ pub struct WeftAppdIpc {
|
||||||
pub socket_path: PathBuf,
|
pub socket_path: PathBuf,
|
||||||
read_buf: Vec<u8>,
|
read_buf: Vec<u8>,
|
||||||
write_stream: Option<UnixStream>,
|
write_stream: Option<UnixStream>,
|
||||||
|
/// 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
|
/// Descriptors received with appd messages, in arrival order. Each
|
||||||
/// `AttachClient` frame is sent with exactly one, attached to its first
|
/// `AttachClient` frame is sent with exactly one, attached to its first
|
||||||
/// bytes, so it has arrived by the time the frame is decoded.
|
/// bytes, so it has arrived by the time the frame is decoded.
|
||||||
|
|
@ -50,6 +53,7 @@ impl WeftAppdIpc {
|
||||||
socket_path,
|
socket_path,
|
||||||
read_buf: Vec::new(),
|
read_buf: Vec::new(),
|
||||||
write_stream: None,
|
write_stream: None,
|
||||||
|
connected: false,
|
||||||
fds: VecDeque::new(),
|
fds: VecDeque::new(),
|
||||||
sessions: HashMap::new(),
|
sessions: HashMap::new(),
|
||||||
reported: HashSet::new(),
|
reported: HashSet::new(),
|
||||||
|
|
@ -65,6 +69,10 @@ impl WeftAppdIpc {
|
||||||
match frame_encode(msg) {
|
match frame_encode(msg) {
|
||||||
Ok(frame) => {
|
Ok(frame) => {
|
||||||
if stream.write_all(&frame).is_err() {
|
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;
|
self.write_stream = None;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -79,7 +87,10 @@ impl WeftAppdIpc {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn try_decode_frames(&mut self) -> Vec<AppdToCompositor> {
|
/// 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<AppdToCompositor>, bool) {
|
||||||
let mut out = Vec::new();
|
let mut out = Vec::new();
|
||||||
loop {
|
loop {
|
||||||
if self.read_buf.len() < 4 {
|
if self.read_buf.len() < 4 {
|
||||||
|
|
@ -93,9 +104,7 @@ impl WeftAppdIpc {
|
||||||
]) as usize;
|
]) as usize;
|
||||||
if declared_len > MAX_FRAME_LEN {
|
if declared_len > MAX_FRAME_LEN {
|
||||||
tracing::warn!(declared_len, "appd IPC frame too large; disconnecting");
|
tracing::warn!(declared_len, "appd IPC frame too large; disconnecting");
|
||||||
self.write_stream = None;
|
return (out, true);
|
||||||
self.read_buf.clear();
|
|
||||||
break;
|
|
||||||
}
|
}
|
||||||
if self.read_buf.len() < 4 + declared_len {
|
if self.read_buf.len() < 4 + declared_len {
|
||||||
break;
|
break;
|
||||||
|
|
@ -103,11 +112,14 @@ impl WeftAppdIpc {
|
||||||
let frame_end = 4 + declared_len;
|
let frame_end = 4 + declared_len;
|
||||||
match frame_decode::<AppdToCompositor>(&self.read_buf[..frame_end]) {
|
match frame_decode::<AppdToCompositor>(&self.read_buf[..frame_end]) {
|
||||||
Ok(msg) => out.push(msg),
|
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);
|
self.read_buf.drain(..frame_end);
|
||||||
}
|
}
|
||||||
out
|
(out, false)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Reads what is available, keeping descriptors that arrive with the
|
/// Reads what is available, keeping descriptors that arrive with the
|
||||||
|
|
@ -146,17 +158,28 @@ 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");
|
tracing::warn!("appd sent descriptors without messages; disconnecting");
|
||||||
eof = true;
|
eof = true;
|
||||||
}
|
}
|
||||||
let messages = self.try_decode_frames();
|
(messages, eof)
|
||||||
if 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<ClientId> {
|
||||||
|
self.connected = false;
|
||||||
self.write_stream = None;
|
self.write_stream = None;
|
||||||
self.read_buf.clear();
|
self.read_buf.clear();
|
||||||
self.fds.clear();
|
self.fds.clear();
|
||||||
}
|
self.reported.clear();
|
||||||
(messages, eof)
|
self.sessions.drain().map(|(_, client)| client).collect()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -299,11 +322,7 @@ pub fn setup(state: &mut WeftCompositorState) -> anyhow::Result<()> {
|
||||||
Ok((stream, _addr)) => {
|
Ok((stream, _addr)) => {
|
||||||
// One appd at a time: a second connection while
|
// One appd at a time: a second connection while
|
||||||
// one is live is refused rather than replacing it.
|
// one is live is refused rather than replacing it.
|
||||||
if state
|
if state.appd_ipc.as_ref().is_some_and(|ipc| ipc.connected) {
|
||||||
.appd_ipc
|
|
||||||
.as_ref()
|
|
||||||
.is_some_and(|ipc| ipc.write_stream.is_some())
|
|
||||||
{
|
|
||||||
tracing::warn!(
|
tracing::warn!(
|
||||||
"second compositor IPC connection refused; weft-appd is connected"
|
"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 {
|
if let Some(ipc) = &mut state.appd_ipc {
|
||||||
ipc.write_stream = Some(write_clone);
|
ipc.write_stream = Some(write_clone);
|
||||||
|
ipc.connected = true;
|
||||||
ipc.read_buf.clear();
|
ipc.read_buf.clear();
|
||||||
ipc.fds.clear();
|
ipc.fds.clear();
|
||||||
}
|
}
|
||||||
|
|
@ -338,8 +358,20 @@ pub fn setup(state: &mut WeftCompositorState) -> anyhow::Result<()> {
|
||||||
}
|
}
|
||||||
if eof {
|
if eof {
|
||||||
tracing::info!(
|
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)
|
Ok(PostAction::Remove)
|
||||||
} else {
|
} else {
|
||||||
Ok(PostAction::Continue)
|
Ok(PostAction::Continue)
|
||||||
|
|
@ -422,6 +454,64 @@ mod tests {
|
||||||
let (messages, eof) = ipc.on_read(&compositor);
|
let (messages, eof) = ipc.on_read(&compositor);
|
||||||
assert!(messages.is_empty());
|
assert!(messages.is_empty());
|
||||||
assert!(eof);
|
assert!(eof);
|
||||||
|
ipc.disconnect();
|
||||||
assert!(ipc.fds.is_empty());
|
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);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -67,6 +67,14 @@ pub struct SessionBinding {
|
||||||
pub disconnected: smithay::reexports::calloop::channel::Sender<u64>,
|
pub disconnected: smithay::reexports::calloop::channel::Sender<u64>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// 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::<WeftClientState>()
|
||||||
|
.is_none_or(|data| data.session.is_none())
|
||||||
|
}
|
||||||
|
|
||||||
impl ClientData for WeftClientState {
|
impl ClientData for WeftClientState {
|
||||||
fn initialized(&self, _client_id: ClientId) {}
|
fn initialized(&self, _client_id: ClientId) {}
|
||||||
fn disconnected(&self, _client_id: ClientId, _reason: DisconnectReason) {
|
fn disconnected(&self, _client_id: ClientId, _reason: DisconnectReason) {
|
||||||
|
|
@ -140,7 +148,10 @@ impl WeftCompositorState {
|
||||||
) -> Self {
|
) -> Self {
|
||||||
let compositor_state = CompositorState::new::<Self>(&display_handle);
|
let compositor_state = CompositorState::new::<Self>(&display_handle);
|
||||||
let xdg_shell_state = XdgShellState::new::<Self>(&display_handle);
|
let xdg_shell_state = XdgShellState::new::<Self>(&display_handle);
|
||||||
let layer_shell_state = WlrLayerShellState::new::<Self>(&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::<Self, _>(&display_handle, outside_sessions);
|
||||||
let shm_state = ShmState::new::<Self>(&display_handle, vec![]);
|
let shm_state = ShmState::new::<Self>(&display_handle, vec![]);
|
||||||
let dmabuf_state = DmabufState::new();
|
let dmabuf_state = DmabufState::new();
|
||||||
let output_manager_state = OutputManagerState::new_with_xdg_output::<Self>(&display_handle);
|
let output_manager_state = OutputManagerState::new_with_xdg_output::<Self>(&display_handle);
|
||||||
|
|
@ -148,7 +159,7 @@ impl WeftCompositorState {
|
||||||
let presentation_state = PresentationState::new::<Self>(&display_handle, 1);
|
let presentation_state = PresentationState::new::<Self>(&display_handle, 1);
|
||||||
let text_input_state = TextInputManagerState::new::<Self>(&display_handle);
|
let text_input_state = TextInputManagerState::new::<Self>(&display_handle);
|
||||||
let input_method_state =
|
let input_method_state =
|
||||||
InputMethodManagerState::new::<Self, _>(&display_handle, |_client| true);
|
InputMethodManagerState::new::<Self, _>(&display_handle, outside_sessions);
|
||||||
let pointer_constraints_state = PointerConstraintsState::new::<Self>(&display_handle);
|
let pointer_constraints_state = PointerConstraintsState::new::<Self>(&display_handle);
|
||||||
let cursor_shape_state = CursorShapeManagerState::new::<Self>(&display_handle);
|
let cursor_shape_state = CursorShapeManagerState::new::<Self>(&display_handle);
|
||||||
let weft_shell_state = WeftShellState::new::<Self>(&display_handle);
|
let weft_shell_state = WeftShellState::new::<Self>(&display_handle);
|
||||||
|
|
|
||||||
|
|
@ -30,9 +30,9 @@ For verified read-only package storage, `weft-pack build-image` produces an EROF
|
||||||
|
|
||||||
## Wayland Surface Isolation
|
## 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)
|
## JavaScript Engine (SpiderMonkey)
|
||||||
|
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue