mirror of
https://github.com/marcoallegretti/WEFT_OS.git
synced 2026-11-22 08:13:59 +00:00
Merge remote-tracking branch 'origin/main' into fix/end-runtime-on-ipc-hangup
# Conflicts: # docs/architecture.md
This commit is contained in:
commit
a454efa869
55 changed files with 9172 additions and 931 deletions
7
Cargo.lock
generated
7
Cargo.lock
generated
|
|
@ -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",
|
||||
|
|
@ -10511,6 +10513,7 @@ version = "0.1.0"
|
|||
dependencies = [
|
||||
"anyhow",
|
||||
"base64 0.22.1",
|
||||
"rustix 1.1.4",
|
||||
"serde",
|
||||
"serde_json",
|
||||
]
|
||||
|
|
@ -10519,9 +10522,12 @@ dependencies = [
|
|||
name = "weft-ipc-types"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"ed25519-dalek",
|
||||
"hex",
|
||||
"rmp-serde",
|
||||
"rustix 1.1.4",
|
||||
"serde",
|
||||
"sha2",
|
||||
"toml 0.8.23",
|
||||
]
|
||||
|
||||
|
|
@ -10540,6 +10546,7 @@ dependencies = [
|
|||
"ed25519-dalek",
|
||||
"hex",
|
||||
"rand 0.8.5",
|
||||
"rustix 1.1.4",
|
||||
"sha2",
|
||||
"tar",
|
||||
"weft-ipc-types",
|
||||
|
|
|
|||
|
|
@ -14,9 +14,9 @@ WEFT OS is a Wayland compositor and application runtime where every app is a Web
|
|||
|
||||
**Runtime** — `weft-runtime` runs WASI Component Model binaries under Wasmtime 30 (`--features wasmtime-runtime`). Provides `weft:app/notify`, `weft:app/ipc`, `weft:app/fetch`, `weft:app/notifications`, and `weft:app/clipboard` host imports. Preopens filesystem paths according to declared capabilities.
|
||||
|
||||
**Package management** — `weft-pack` handles check, sign, verify, install, uninstall, list, build-image (EROFS dm-verity), and info. Validates capability strings at check time. App data is stored apart from packages and survives uninstall.
|
||||
**Package management** — `weft-pack` handles check, sign, verify, install and update, rollback, uninstall, list, build-image (EROFS dm-verity), and info. Validates capability strings at check time. Installs only packages signed by a trusted key (or explicitly as development content) and binds each app ID to its first publisher. App data is stored apart from packages and survives uninstall.
|
||||
|
||||
**File portal** — `weft-file-portal` is a per-session file proxy with a path allowlist and `..` blocking.
|
||||
**File portal** — `weft-file-portal` is a per-session file proxy for the session's directory grants, with every operation confined beneath the granted directory by the kernel.
|
||||
|
||||
**Mount helper** — `weft-mount-helper` is a setuid helper for EROFS dm-verity mount/umount via `veritysetup`.
|
||||
|
||||
|
|
|
|||
|
|
@ -68,6 +68,33 @@ struct FrameSignals {
|
|||
content: AtomicBool,
|
||||
/// The document has loaded and Servo reports its rendering is up to date.
|
||||
settled: AtomicBool,
|
||||
/// The page closed itself with `window.close()`.
|
||||
page_closed: AtomicBool,
|
||||
/// The page's answer to the pending close request; see `CloseAnswer`.
|
||||
close_answer: std::sync::atomic::AtomicU8,
|
||||
}
|
||||
|
||||
/// The page's answer to a close request, as stored in `close_answer`.
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
#[repr(u8)]
|
||||
enum CloseAnswer {
|
||||
Pending = 0,
|
||||
Close = 1,
|
||||
Cancel = 2,
|
||||
}
|
||||
|
||||
/// How long a page with the `ask` close policy has to answer a close
|
||||
/// request; a page that does not answer in time is closed.
|
||||
const CLOSE_ANSWER_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(2);
|
||||
|
||||
/// Asks the page whether it may close: dispatches a cancelable `weftclose`
|
||||
/// event on the top-level window. The page cancels the close by calling
|
||||
/// `preventDefault()` and closes itself later with `window.close()`.
|
||||
const ASK_CLOSE_SCRIPT: &str = "window.dispatchEvent(new Event('weftclose', { cancelable: true }))";
|
||||
|
||||
/// The application's declared close policy, from `WEFT_APP_CLOSE`.
|
||||
fn close_policy_asks() -> bool {
|
||||
std::env::var("WEFT_APP_CLOSE").is_ok_and(|v| v == "ask")
|
||||
}
|
||||
|
||||
struct WeftWebViewDelegate {
|
||||
|
|
@ -87,6 +114,12 @@ impl WebViewDelegate for WeftWebViewDelegate {
|
|||
self.signals.redraw.store(true, Ordering::Relaxed);
|
||||
}
|
||||
|
||||
/// The application page called `window.close()`, which Servo allows for
|
||||
/// a top-level document with a single history entry.
|
||||
fn notify_closed(&self, _webview: servo::WebView) {
|
||||
self.signals.page_closed.store(true, Ordering::Relaxed);
|
||||
}
|
||||
|
||||
/// The webview carries the session's bridge, so it stays within the
|
||||
/// application's own UI files.
|
||||
fn request_navigation(&self, _webview: servo::WebView, request: NavigationRequest) {
|
||||
|
|
@ -368,6 +401,10 @@ struct App {
|
|||
modifiers: ModifiersState,
|
||||
cursor_pos: DevicePoint,
|
||||
shell_client: Option<crate::shell_client::ShellClient>,
|
||||
/// Whether the page is asked before its window closes.
|
||||
ask_before_close: bool,
|
||||
/// When the pending close request is closed regardless of the page.
|
||||
close_deadline: Option<std::time::Instant>,
|
||||
}
|
||||
|
||||
impl App {
|
||||
|
|
@ -394,9 +431,70 @@ impl App {
|
|||
modifiers: ModifiersState::default(),
|
||||
cursor_pos: DevicePoint::origin(),
|
||||
shell_client: None,
|
||||
ask_before_close: close_policy_asks(),
|
||||
close_deadline: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Handles a request to close the window. Under the `ask` policy the
|
||||
/// page answers first; otherwise, or without a page, the app closes.
|
||||
fn request_close(&mut self, event_loop: &ActiveEventLoop) {
|
||||
if self.close_deadline.is_some() {
|
||||
return;
|
||||
}
|
||||
let Some(webview) = self.webview.as_ref().filter(|_| self.ask_before_close) else {
|
||||
self.shut_down();
|
||||
event_loop.exit();
|
||||
return;
|
||||
};
|
||||
self.signals
|
||||
.close_answer
|
||||
.store(CloseAnswer::Pending as u8, Ordering::Relaxed);
|
||||
self.close_deadline = Some(std::time::Instant::now() + CLOSE_ANSWER_TIMEOUT);
|
||||
let signals = Arc::clone(&self.signals);
|
||||
webview.evaluate_javascript(ASK_CLOSE_SCRIPT, move |result| {
|
||||
// dispatchEvent returns false when the page cancelled the event.
|
||||
let answer = match result {
|
||||
Ok(servo::JSValue::Boolean(false)) => CloseAnswer::Cancel,
|
||||
Ok(_) => CloseAnswer::Close,
|
||||
Err(e) => {
|
||||
tracing::warn!(?e, "the page could not be asked to close; closing");
|
||||
CloseAnswer::Close
|
||||
}
|
||||
};
|
||||
signals.close_answer.store(answer as u8, Ordering::Relaxed);
|
||||
});
|
||||
}
|
||||
|
||||
/// Acts on the page's answer to a pending close request, or on its
|
||||
/// absence once the answer is due. Returns whether the app is closing.
|
||||
fn settle_close_request(&mut self) -> bool {
|
||||
let Some(deadline) = self.close_deadline else {
|
||||
return false;
|
||||
};
|
||||
let answer = self.signals.close_answer.load(Ordering::Relaxed);
|
||||
if answer == CloseAnswer::Cancel as u8 {
|
||||
self.close_deadline = None;
|
||||
tracing::info!("the page cancelled the close");
|
||||
// weft-appd learns that the session keeps running; the token
|
||||
// keeps page output from forging this report.
|
||||
if let Ok(token) = std::env::var("WEFT_READY_TOKEN") {
|
||||
use std::io::Write;
|
||||
println!("CLOSE_CANCELLED {token}");
|
||||
let _ = std::io::stdout().flush();
|
||||
}
|
||||
return false;
|
||||
}
|
||||
if answer == CloseAnswer::Close as u8 {
|
||||
return true;
|
||||
}
|
||||
if std::time::Instant::now() >= deadline {
|
||||
tracing::warn!("the page did not answer the close request in time; closing");
|
||||
return true;
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// Paints and presents once Servo has requested its first repaint.
|
||||
///
|
||||
/// Nothing is presented before that request; the first frames can still be
|
||||
|
|
@ -431,6 +529,19 @@ impl App {
|
|||
}
|
||||
|
||||
impl ApplicationHandler<ServoWake> for App {
|
||||
/// Releases everything that holds Wayland objects of winit's display
|
||||
/// (Servo, the rendering context, whose software and EGL paths keep
|
||||
/// their own proxies on it, the shell protocol client and the window)
|
||||
/// while that display is still connected; dropped after the event loop,
|
||||
/// they would be destroyed on a display that is gone. A panic unwinding
|
||||
/// out of a handler skips this.
|
||||
fn exiting(&mut self, _event_loop: &ActiveEventLoop) {
|
||||
self.shut_down();
|
||||
self.rendering_context = None;
|
||||
self.shell_client = None;
|
||||
self.window = None;
|
||||
}
|
||||
|
||||
fn resumed(&mut self, event_loop: &ActiveEventLoop) {
|
||||
if self.window.is_some() {
|
||||
return;
|
||||
|
|
@ -533,6 +644,17 @@ impl ApplicationHandler<ServoWake> for App {
|
|||
if let Some(servo) = &self.servo {
|
||||
servo.spin_event_loop();
|
||||
}
|
||||
// The page answers a close request while Servo spins.
|
||||
if self.signals.page_closed.load(Ordering::Relaxed) || self.settle_close_request() {
|
||||
self.shut_down();
|
||||
event_loop.exit();
|
||||
return;
|
||||
}
|
||||
// Wake for the close answer's deadline even when nothing else happens.
|
||||
event_loop.set_control_flow(match self.close_deadline {
|
||||
Some(deadline) => winit::event_loop::ControlFlow::WaitUntil(deadline),
|
||||
None => winit::event_loop::ControlFlow::Wait,
|
||||
});
|
||||
if self.signals.redraw.swap(false, Ordering::Relaxed)
|
||||
&& let Some(w) = &self.window
|
||||
{
|
||||
|
|
@ -592,10 +714,7 @@ impl ApplicationHandler<ServoWake> for App {
|
|||
)));
|
||||
}
|
||||
}
|
||||
WindowEvent::CloseRequested => {
|
||||
self.shut_down();
|
||||
event_loop.exit();
|
||||
}
|
||||
WindowEvent::CloseRequested => self.request_close(event_loop),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -57,7 +57,8 @@ fn named_key(n: NamedKey) -> servo::NamedKey {
|
|||
NamedKey::Control => S::Control,
|
||||
NamedKey::Fn => S::Fn,
|
||||
NamedKey::FnLock => S::FnLock,
|
||||
NamedKey::Meta => S::Meta,
|
||||
// winit names the Super keys Super; the DOM names them Meta.
|
||||
NamedKey::Meta | NamedKey::Super => S::Meta,
|
||||
NamedKey::NumLock => S::NumLock,
|
||||
NamedKey::ScrollLock => S::ScrollLock,
|
||||
NamedKey::Shift => S::Shift,
|
||||
|
|
|
|||
|
|
@ -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"
|
||||
|
|
|
|||
|
|
@ -1,4 +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;
|
||||
|
|
@ -6,7 +9,39 @@ use weft_ipc_types::{
|
|||
AppdToCompositor, CompositorToAppd, MAX_FRAME_LEN, frame_decode, frame_encode,
|
||||
};
|
||||
|
||||
pub type CompositorSender = mpsc::Sender<AppdToCompositor>;
|
||||
/// A message for the compositor and the file descriptor it carries, if any.
|
||||
pub struct Outbound {
|
||||
pub msg: AppdToCompositor,
|
||||
pub fd: Option<OwnedFd>,
|
||||
}
|
||||
|
||||
impl From<AppdToCompositor> for Outbound {
|
||||
fn from(msg: AppdToCompositor) -> Self {
|
||||
Self { msg, fd: None }
|
||||
}
|
||||
}
|
||||
|
||||
/// 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.
|
||||
///
|
||||
|
|
@ -24,17 +59,24 @@ pub fn socket_path() -> Option<PathBuf> {
|
|||
|
||||
/// 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
|
||||
/// `CompositorToAppd` frames are decoded and logged; no behavioural action is
|
||||
/// taken yet (surface lifecycle hookup happens in a later task).
|
||||
/// 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::<AppdToCompositor>(32);
|
||||
tokio::spawn(run_client(socket_path, rx));
|
||||
tx
|
||||
let (tx, rx) = mpsc::channel::<Outbound>(32);
|
||||
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<AppdToCompositor>) {
|
||||
async fn run_client(
|
||||
socket_path: PathBuf,
|
||||
mut rx: mpsc::Receiver<Outbound>,
|
||||
connected: Arc<AtomicBool>,
|
||||
) {
|
||||
let mut unsent: Option<Outbound> = None;
|
||||
loop {
|
||||
let stream = loop {
|
||||
match tokio::net::UnixStream::connect(&socket_path).await {
|
||||
|
|
@ -49,28 +91,85 @@ async fn run_client(socket_path: PathBuf, mut rx: mpsc::Receiver<AppdToComposito
|
|||
};
|
||||
|
||||
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(msg) = rx.recv().await else {
|
||||
return;
|
||||
};
|
||||
match frame_encode(&msg) {
|
||||
Ok(frame) => {
|
||||
if write_half.write_all(&frame).await.is_err() {
|
||||
tracing::warn!("compositor IPC write failed; reconnecting");
|
||||
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,
|
||||
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.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;
|
||||
}
|
||||
}
|
||||
|
||||
/// Writes `frame`, attaching `fd` to its first bytes so the compositor
|
||||
/// receives the descriptor together with the message it belongs to.
|
||||
async fn send_frame(
|
||||
stream: &mut tokio::net::unix::OwnedWriteHalf,
|
||||
frame: &[u8],
|
||||
fd: Option<&OwnedFd>,
|
||||
) -> 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 +209,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");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -87,14 +87,9 @@ impl HostDirs {
|
|||
}
|
||||
}
|
||||
|
||||
/// Derives grants for the declared capabilities. Every capability is
|
||||
/// checked before host directories are resolved or the app's data
|
||||
/// directory is created, so a refused launch leaves nothing behind.
|
||||
pub(crate) fn derive(
|
||||
app_id: &str,
|
||||
declared: &[String],
|
||||
host_dirs: impl FnOnce() -> Result<HostDirs, Refusal>,
|
||||
) -> Result<SessionGrants, Refusal> {
|
||||
/// Parses the declared capabilities, refusing unknown ones and those this
|
||||
/// host does not support, without touching the host.
|
||||
pub(crate) fn validate(declared: &[String]) -> Result<Vec<Capability>, Refusal> {
|
||||
let mut capabilities = Vec::new();
|
||||
for text in declared {
|
||||
let capability: Capability =
|
||||
|
|
@ -110,7 +105,18 @@ pub(crate) fn derive(
|
|||
}
|
||||
capabilities.push(capability);
|
||||
}
|
||||
Ok(capabilities)
|
||||
}
|
||||
|
||||
/// Derives grants for the declared capabilities. Every capability is
|
||||
/// checked before host directories are resolved or the app's data
|
||||
/// directory is created, so a refused launch leaves nothing behind.
|
||||
pub(crate) fn derive(
|
||||
app_id: &str,
|
||||
declared: &[String],
|
||||
host_dirs: impl FnOnce() -> Result<HostDirs, Refusal>,
|
||||
) -> Result<SessionGrants, Refusal> {
|
||||
let capabilities = validate(declared)?;
|
||||
let mut grants = SessionGrants::default();
|
||||
let needs_dirs = capabilities
|
||||
.iter()
|
||||
|
|
|
|||
|
|
@ -8,8 +8,16 @@ pub enum Request {
|
|||
app_id: String,
|
||||
surface_id: u64,
|
||||
},
|
||||
/// Asks a running session to close as a user close would, or with
|
||||
/// `force`, terminates it without asking.
|
||||
TerminateApp {
|
||||
session_id: u64,
|
||||
#[serde(default)]
|
||||
force: bool,
|
||||
},
|
||||
/// Brings the session's window to the front with keyboard focus.
|
||||
ActivateApp {
|
||||
session_id: u64,
|
||||
},
|
||||
QueryRunning,
|
||||
QueryAppState {
|
||||
|
|
@ -211,10 +219,19 @@ mod tests {
|
|||
|
||||
#[test]
|
||||
fn terminate_app_request_roundtrip() {
|
||||
let req = Request::TerminateApp { session_id: 42 };
|
||||
let req = Request::TerminateApp {
|
||||
session_id: 42,
|
||||
force: false,
|
||||
};
|
||||
let bytes = rmp_serde::to_vec(&req).unwrap();
|
||||
let decoded: Request = rmp_serde::from_slice(&bytes).unwrap();
|
||||
assert!(matches!(decoded, Request::TerminateApp { session_id: 42 }));
|
||||
assert!(matches!(
|
||||
decoded,
|
||||
Request::TerminateApp {
|
||||
session_id: 42,
|
||||
force: false
|
||||
}
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
|
|
|||
|
|
@ -3,11 +3,22 @@
|
|||
//! The runtime and the app shell receive the exact files resolved here and
|
||||
//! never look for the package themselves, so the component, the UI and the
|
||||
//! capabilities a session is granted all come from the same package root.
|
||||
//!
|
||||
//! Before anything starts, the package must still be what its owner
|
||||
//! installed: a package recorded as a publisher's must carry that
|
||||
//! publisher's valid signature over its current content, and a package with
|
||||
//! no record must be signed by a trusted key, which is then recorded as its
|
||||
//! owner. Development content, recorded as such by `weft-pack install
|
||||
//! --dev`, runs unverified.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use weft_ipc_types::manifest::{MANIFEST_FILE, Manifest, ManifestError, entry_path};
|
||||
use weft_ipc_types::manifest::{ClosePolicy, MANIFEST_FILE, Manifest, ManifestError, entry_path};
|
||||
use weft_ipc_types::package::{ImageFiles, is_valid_app_id};
|
||||
use weft_ipc_types::trust::{
|
||||
Inventory, Owner, PublisherKey, TrustError, TrustStore, lock_owner, owner_record_path,
|
||||
read_owner, read_signature, write_owner,
|
||||
};
|
||||
|
||||
use crate::grants::Refusal;
|
||||
use crate::mount::Mount;
|
||||
|
|
@ -20,10 +31,15 @@ pub(crate) struct LaunchPackage {
|
|||
pub(crate) module: PathBuf,
|
||||
/// The UI document, from `[ui].entry`.
|
||||
pub(crate) ui_entry: PathBuf,
|
||||
/// What a user close does, from `[ui].close`.
|
||||
pub(crate) close: ClosePolicy,
|
||||
pub(crate) capabilities: Vec<String>,
|
||||
/// The image the package root is mounted from, held for as long as the
|
||||
/// session runs.
|
||||
pub(crate) image: Option<Mount>,
|
||||
/// The lock that keeps an installed revision from being removed while
|
||||
/// the session runs from it.
|
||||
pub(crate) pin: Option<weft_ipc_types::store::Pin>,
|
||||
}
|
||||
|
||||
/// Resolves `app_id` in the package stores.
|
||||
|
|
@ -57,16 +73,47 @@ fn resolve_in(app_id: &str, stores: &[PathBuf]) -> Result<LaunchPackage, Refusal
|
|||
let root = image.root().to_path_buf();
|
||||
return from_root(app_id, root, Some(image));
|
||||
}
|
||||
// A store whose entry for the app cannot be used does not hide the app
|
||||
// in a later store, as it does not in the list of installed apps; the
|
||||
// first such problem is reported when no store has the app.
|
||||
let mut unusable = None;
|
||||
for store in stores {
|
||||
let dir = store.join(app_id);
|
||||
if std::fs::symlink_metadata(dir.join(MANIFEST_FILE)).is_ok() {
|
||||
return from_root(app_id, dir, None);
|
||||
let active = match weft_ipc_types::store::active(store, app_id) {
|
||||
Ok(Some(active)) => active,
|
||||
Ok(None) => continue,
|
||||
Err(e) => {
|
||||
tracing::warn!(app_id, error = %e, "package entry skipped");
|
||||
unusable.get_or_insert(match e {
|
||||
weft_ipc_types::store::StoreError::NotAPackage(_) => {
|
||||
Refusal::new(403, e.to_string())
|
||||
}
|
||||
weft_ipc_types::store::StoreError::Io(..) => Refusal::new(500, e.to_string()),
|
||||
});
|
||||
continue;
|
||||
}
|
||||
};
|
||||
let dir = active.dir().to_path_buf();
|
||||
// A directory left with only app data by an earlier layout is not a
|
||||
// package.
|
||||
if std::fs::symlink_metadata(dir.join(MANIFEST_FILE)).is_err() {
|
||||
continue;
|
||||
}
|
||||
// The session runs from the revision itself, not the link, so an
|
||||
// update or rollback that switches the link while it runs leaves it
|
||||
// on the bytes it started with. From here on a refusal is final: a
|
||||
// package that is being changed, or that fails its checks, is not
|
||||
// silently replaced by another store's copy.
|
||||
let pin = weft_ipc_types::store::pin(&dir).map_err(|e| {
|
||||
Refusal::new(
|
||||
500,
|
||||
format!("cannot hold {} while it runs: {e}", dir.display()),
|
||||
)
|
||||
})?;
|
||||
let mut package = from_root(app_id, dir, None)?;
|
||||
package.pin = Some(pin);
|
||||
return Ok(package);
|
||||
}
|
||||
Err(Refusal::new(
|
||||
404,
|
||||
format!("package {app_id} is not installed"),
|
||||
))
|
||||
Err(unusable.unwrap_or_else(|| Refusal::new(404, format!("package {app_id} is not installed"))))
|
||||
}
|
||||
|
||||
fn from_root(app_id: &str, root: PathBuf, image: Option<Mount>) -> Result<LaunchPackage, Refusal> {
|
||||
|
|
@ -85,9 +132,14 @@ fn from_root(app_id: &str, root: PathBuf, image: Option<Mount>) -> Result<Launch
|
|||
),
|
||||
));
|
||||
}
|
||||
let manifest = Manifest::read(&root).map_err(|e| match e {
|
||||
ManifestError::Io(..) => Refusal::new(500, e.to_string()),
|
||||
ManifestError::Parse(..) => Refusal::new(403, e.to_string()),
|
||||
// The manifest is read once; the same bytes are parsed and checked
|
||||
// against the signed inventory, so the capabilities and entries a
|
||||
// session gets are the ones the owner signed.
|
||||
let manifest_path = root.join(MANIFEST_FILE);
|
||||
let manifest_bytes = std::fs::read(&manifest_path)
|
||||
.map_err(|e| Refusal::new(500, format!("cannot read {}: {e}", manifest_path.display())))?;
|
||||
let manifest = Manifest::parse(&manifest_path, &manifest_bytes).map_err(|e| match e {
|
||||
ManifestError::Io(..) | ManifestError::Parse(..) => Refusal::new(403, e.to_string()),
|
||||
})?;
|
||||
if manifest.package.id != app_id {
|
||||
return Err(Refusal::new(
|
||||
|
|
@ -99,6 +151,7 @@ fn from_root(app_id: &str, root: PathBuf, image: Option<Mount>) -> Result<Launch
|
|||
),
|
||||
));
|
||||
}
|
||||
verify_owner(app_id, &root, &manifest_bytes)?;
|
||||
let entry = |field: &str, value: &str| {
|
||||
entry_path(&root, value).map_err(|e| Refusal::new(403, format!("{field}: {e}")))
|
||||
};
|
||||
|
|
@ -110,11 +163,118 @@ fn from_root(app_id: &str, root: PathBuf, image: Option<Mount>) -> Result<Launch
|
|||
capabilities: manifest.capabilities().to_vec(),
|
||||
module,
|
||||
ui_entry,
|
||||
close: manifest.ui.close,
|
||||
root,
|
||||
image,
|
||||
pin: None,
|
||||
})
|
||||
}
|
||||
|
||||
/// Checks that the package at `root`, whose manifest was read as
|
||||
/// `manifest_bytes`, is what its owner installed. A trusted package with no
|
||||
/// owner record is recorded as its signer's on its first launch, so its app
|
||||
/// data stays with that publisher; existing app data with no recorded owner
|
||||
/// is not handed to whichever publisher launches first.
|
||||
fn verify_owner(app_id: &str, root: &Path, manifest_bytes: &[u8]) -> Result<(), Refusal> {
|
||||
// Errors in the host's trust store or owner records are the host's, not
|
||||
// the package's.
|
||||
let host = |e: TrustError| Refusal::new(500, e.to_string());
|
||||
let package = |e: TrustError| match e {
|
||||
TrustError::Io(..) => Refusal::new(500, e.to_string()),
|
||||
_ => Refusal::new(403, e.to_string()),
|
||||
};
|
||||
let data_home = weft_ipc_types::package::data_home().ok_or_else(|| {
|
||||
Refusal::new(
|
||||
500,
|
||||
"cannot locate the data home holding package owner records",
|
||||
)
|
||||
})?;
|
||||
let record = owner_record_path(&data_home, app_id);
|
||||
let owner = read_owner(&record).map_err(host)?;
|
||||
if owner == Some(Owner::Development) {
|
||||
return Ok(());
|
||||
}
|
||||
let trusted = TrustStore::load(&TrustStore::directories()).map_err(host)?;
|
||||
let inventory = Inventory::read(root).map_err(package)?;
|
||||
if !inventory.holds(MANIFEST_FILE, manifest_bytes) {
|
||||
return Err(Refusal::new(
|
||||
403,
|
||||
format!("{} changed while it was checked", root.display()),
|
||||
));
|
||||
}
|
||||
let digest = inventory.digest();
|
||||
let signature = read_signature(root).map_err(package)?;
|
||||
let signer = signature.and_then(|sig| trusted.signer_of(&digest, &sig));
|
||||
match (owner, signer) {
|
||||
(Some(Owner::Verified(key)), Some(signer)) if key == signer => Ok(()),
|
||||
(Some(Owner::Verified(key)), _) => Err(Refusal::new(
|
||||
403,
|
||||
format!(
|
||||
"{} is not signed by its owner, publisher {}, or that key is no longer \
|
||||
trusted; the package was changed or its key was withdrawn",
|
||||
root.display(),
|
||||
key.to_hex()
|
||||
),
|
||||
)),
|
||||
(_, None) => Err(Refusal::new(
|
||||
403,
|
||||
format!(
|
||||
"{} has no recorded owner and is not signed by a trusted key; install it \
|
||||
with weft-pack",
|
||||
root.display()
|
||||
),
|
||||
)),
|
||||
(_, Some(signer)) => record_first_owner(app_id, &data_home, &record, signer),
|
||||
}
|
||||
}
|
||||
|
||||
/// Records `signer` as the owner of `app_id` on the first launch of a trusted
|
||||
/// package that has no owner record and no app data yet.
|
||||
fn record_first_owner(
|
||||
app_id: &str,
|
||||
data_home: &Path,
|
||||
record: &Path,
|
||||
signer: PublisherKey,
|
||||
) -> Result<(), Refusal> {
|
||||
let host = |e: TrustError| Refusal::new(500, e.to_string());
|
||||
let _lock = lock_owner(data_home, app_id).map_err(host)?;
|
||||
match read_owner(record).map_err(host)? {
|
||||
Some(Owner::Verified(key)) if key == signer => return Ok(()),
|
||||
Some(existing) => {
|
||||
return Err(Refusal::new(
|
||||
403,
|
||||
format!(
|
||||
"{app_id} belongs to {existing}, not publisher {}",
|
||||
signer.to_hex()
|
||||
),
|
||||
));
|
||||
}
|
||||
None => {}
|
||||
}
|
||||
// Data in the earlier layout counts: it would be moved to this app's
|
||||
// data directory when the session starts.
|
||||
let home = weft_ipc_types::package::home_dir()
|
||||
.ok_or_else(|| Refusal::new(500, "HOME is not set to an absolute path"))?;
|
||||
match weft_ipc_types::package::existing_app_data(data_home, &home, app_id) {
|
||||
Err(e) => Err(Refusal::new(
|
||||
500,
|
||||
format!("cannot inspect the app data of {app_id}: {e}"),
|
||||
)),
|
||||
Ok(Some(data)) => Err(Refusal::new(
|
||||
403,
|
||||
format!(
|
||||
"{} holds app data for {app_id} with no recorded owner, so it is not given to \
|
||||
publisher {}. To give it to this publisher, install the package into the user \
|
||||
store with weft-pack install --claim-data (uninstalling it there first); \
|
||||
otherwise move the data aside",
|
||||
data.display(),
|
||||
signer.to_hex()
|
||||
),
|
||||
)),
|
||||
Ok(None) => write_owner(record, Owner::Verified(signer)).map_err(host),
|
||||
}
|
||||
}
|
||||
|
||||
impl LaunchPackage {
|
||||
/// A package for supervisor tests whose children ignore their files.
|
||||
#[cfg(test)]
|
||||
|
|
@ -125,8 +285,10 @@ impl LaunchPackage {
|
|||
root: PathBuf::from("/nonexistent"),
|
||||
module: PathBuf::from("/nonexistent/app.wasm"),
|
||||
ui_entry: PathBuf::from("/nonexistent/ui/index.html"),
|
||||
close: ClosePolicy::Immediate,
|
||||
capabilities: Vec::new(),
|
||||
image: None,
|
||||
pin: None,
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -141,6 +303,10 @@ mod tests {
|
|||
|
||||
const ID: &str = "org.weft.test.resolve";
|
||||
|
||||
/// HOME as the test process found it, restored by `finish`.
|
||||
static HOME_AT_START: std::sync::OnceLock<Option<std::ffi::OsString>> =
|
||||
std::sync::OnceLock::new();
|
||||
|
||||
/// A store holding a directory install of `ID`, with WEFT_APP_STORE
|
||||
/// pointing at it. Callers hold env_lock.
|
||||
fn store(name: &str, manifest_id: &str, module: &str) -> PathBuf {
|
||||
|
|
@ -160,8 +326,19 @@ mod tests {
|
|||
),
|
||||
)
|
||||
.unwrap();
|
||||
// The fixture is unsigned development content, recorded as such.
|
||||
weft_ipc_types::trust::write_owner(
|
||||
&owner_record_path(&store.join("share"), ID),
|
||||
Owner::Development,
|
||||
)
|
||||
.unwrap();
|
||||
HOME_AT_START.get_or_init(|| std::env::var_os("HOME"));
|
||||
// SAFETY: callers hold env_lock, which serialises environment changes.
|
||||
unsafe { std::env::set_var("WEFT_APP_STORE", &store) };
|
||||
unsafe {
|
||||
std::env::set_var("WEFT_APP_STORE", &store);
|
||||
std::env::set_var("XDG_DATA_HOME", store.join("share"));
|
||||
std::env::set_var("HOME", store.join("home"));
|
||||
}
|
||||
store
|
||||
}
|
||||
|
||||
|
|
@ -170,6 +347,12 @@ mod tests {
|
|||
unsafe {
|
||||
std::env::remove_var("WEFT_APP_STORE");
|
||||
std::env::remove_var("WEFT_MOUNT_HELPER");
|
||||
std::env::remove_var("XDG_DATA_HOME");
|
||||
std::env::remove_var("WEFT_TRUSTED_KEYS");
|
||||
match HOME_AT_START.get() {
|
||||
Some(Some(home)) => std::env::set_var("HOME", home),
|
||||
_ => std::env::remove_var("HOME"),
|
||||
}
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(store);
|
||||
}
|
||||
|
|
@ -239,13 +422,275 @@ mod tests {
|
|||
std::os::unix::fs::symlink(store.join("manifest.toml"), &manifest).unwrap();
|
||||
let manifest_link = refusal(resolve(ID));
|
||||
finish(&store);
|
||||
for refused in [root_link, manifest_link] {
|
||||
// Only a link to one of the app's own revisions is followed.
|
||||
assert_eq!(root_link.code, 403, "{}", root_link.message);
|
||||
assert!(
|
||||
root_link
|
||||
.message
|
||||
.contains("nor a link to one of its revisions"),
|
||||
"{}",
|
||||
root_link.message
|
||||
);
|
||||
assert_eq!(manifest_link.code, 403, "{}", manifest_link.message);
|
||||
assert!(
|
||||
manifest_link.message.contains("not a link"),
|
||||
"{}",
|
||||
manifest_link.message
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn an_unusable_store_entry_does_not_hide_a_later_store() {
|
||||
let _env = crate::tests::env_lock().blocking_lock();
|
||||
let user = store("unusable_user", ID, "app.wasm");
|
||||
let system = std::env::temp_dir().join(format!(
|
||||
"weft_appd_launch_unusable_system_{}",
|
||||
std::process::id()
|
||||
));
|
||||
let _ = std::fs::remove_dir_all(&system);
|
||||
std::fs::create_dir_all(&system).unwrap();
|
||||
std::fs::rename(user.join(ID), system.join(ID)).unwrap();
|
||||
// A link to something other than one of the app's revisions.
|
||||
std::os::unix::fs::symlink("/tmp", user.join(ID)).unwrap();
|
||||
let found = resolve_in(ID, &[user.clone(), system.clone()]).map(|p| p.root);
|
||||
let alone = refusal(resolve_in(ID, std::slice::from_ref(&user)));
|
||||
finish(&user);
|
||||
let _ = std::fs::remove_dir_all(&system);
|
||||
assert_eq!(found.ok(), Some(system.join(ID)));
|
||||
// With no other store, its problem is reported, not "not installed".
|
||||
assert_eq!(alone.code, 403, "{}", alone.message);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_session_runs_from_its_revision_and_holds_it() {
|
||||
use weft_ipc_types::store::{link_target, revisions_of, try_claim};
|
||||
let _env = crate::tests::env_lock().blocking_lock();
|
||||
let store = store("revision", ID, "app.wasm");
|
||||
let revision = "ab".repeat(32);
|
||||
let dir = revisions_of(&store, ID).join(&revision);
|
||||
std::fs::create_dir_all(dir.parent().unwrap()).unwrap();
|
||||
std::fs::rename(store.join(ID), &dir).unwrap();
|
||||
std::os::unix::fs::symlink(link_target(ID, &revision), store.join(ID)).unwrap();
|
||||
let package = resolve(ID).unwrap();
|
||||
let held = try_claim(&dir).unwrap().is_none();
|
||||
let root = package.root.clone();
|
||||
let module = package.module.clone();
|
||||
drop(package);
|
||||
let released = try_claim(&dir).unwrap().is_some();
|
||||
finish(&store);
|
||||
// The children get the revision's own paths, not the link's.
|
||||
assert_eq!(root, dir);
|
||||
assert_eq!(module, dir.join("app.wasm"));
|
||||
assert!(held, "the revision is not held while the session runs");
|
||||
assert!(released, "the revision is still held after the session");
|
||||
}
|
||||
|
||||
const DEMO: &str = "org.weft.demo.counter";
|
||||
|
||||
/// A store holding a copy of the signed Counter demo, with the demo key
|
||||
/// trusted when `trusted`. Callers hold env_lock.
|
||||
fn demo_store(name: &str, trusted: bool) -> PathBuf {
|
||||
let store = store(name, ID, "app.wasm");
|
||||
let examples = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../examples");
|
||||
copy_tree(&examples.join(DEMO), &store.join(DEMO));
|
||||
let keys = store.join("keys");
|
||||
std::fs::create_dir_all(&keys).unwrap();
|
||||
if trusted {
|
||||
std::fs::copy(examples.join("keys/weft-sign.pub"), keys.join("demo.pub")).unwrap();
|
||||
}
|
||||
// SAFETY: as in `store`.
|
||||
unsafe { std::env::set_var("WEFT_TRUSTED_KEYS", &keys) };
|
||||
store
|
||||
}
|
||||
|
||||
fn copy_tree(src: &Path, dst: &Path) {
|
||||
std::fs::create_dir_all(dst).unwrap();
|
||||
for entry in std::fs::read_dir(src).unwrap().flatten() {
|
||||
let to = dst.join(entry.file_name());
|
||||
if entry.file_type().unwrap().is_dir() {
|
||||
copy_tree(&entry.path(), &to);
|
||||
} else {
|
||||
std::fs::copy(entry.path(), to).unwrap();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn record(store: &Path, app_id: &str, owner: Owner) {
|
||||
weft_ipc_types::trust::write_owner(&owner_record_path(&store.join("share"), app_id), owner)
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
fn demo_key() -> weft_ipc_types::trust::PublisherKey {
|
||||
weft_ipc_types::trust::PublisherKey::from_file(
|
||||
&Path::new(env!("CARGO_MANIFEST_DIR")).join("../../examples/keys/weft-sign.pub"),
|
||||
)
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_package_signed_by_its_owner_launches() {
|
||||
let _env = crate::tests::env_lock().blocking_lock();
|
||||
// Recorded as the publisher's, and with no record but a trusted
|
||||
// signature.
|
||||
let store = demo_store("signed", true);
|
||||
let first = resolve(DEMO).map(|p| p.root);
|
||||
let owner = read_owner(&owner_record_path(&store.join("share"), DEMO)).unwrap();
|
||||
let again = resolve(DEMO).map(|p| p.root);
|
||||
finish(&store);
|
||||
assert_eq!(first.ok(), Some(store.join(DEMO)));
|
||||
assert_eq!(owner, Some(Owner::Verified(demo_key())));
|
||||
assert_eq!(again.ok(), Some(store.join(DEMO)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unowned_app_data_is_not_given_to_the_first_publisher() {
|
||||
let _env = crate::tests::env_lock().blocking_lock();
|
||||
let store = demo_store("unowned_data", true);
|
||||
let data = weft_ipc_types::package::app_data_dir(&store.join("share"), DEMO);
|
||||
std::fs::create_dir_all(&data).unwrap();
|
||||
let refused = refusal(resolve(DEMO));
|
||||
let owner = read_owner(&owner_record_path(&store.join("share"), DEMO)).unwrap();
|
||||
finish(&store);
|
||||
assert_eq!(refused.code, 403, "{}", refused.message);
|
||||
assert!(
|
||||
refused.message.contains("--claim-data"),
|
||||
"{}",
|
||||
refused.message
|
||||
);
|
||||
assert_eq!(owner, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unowned_data_in_the_earlier_layout_is_not_given_away() {
|
||||
let _env = crate::tests::env_lock().blocking_lock();
|
||||
let store = demo_store("legacy_data", true);
|
||||
let legacy = weft_ipc_types::package::legacy_app_data_dir(&store.join("home"), DEMO);
|
||||
std::fs::create_dir_all(&legacy).unwrap();
|
||||
let refused = refusal(resolve(DEMO));
|
||||
let owner = read_owner(&owner_record_path(&store.join("share"), DEMO)).unwrap();
|
||||
finish(&store);
|
||||
assert_eq!(refused.code, 403, "{}", refused.message);
|
||||
assert!(
|
||||
refused.message.contains("no recorded owner"),
|
||||
"{}",
|
||||
refused.message
|
||||
);
|
||||
assert_eq!(owner, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_first_launch_without_a_usable_home_records_nothing() {
|
||||
let _env = crate::tests::env_lock().blocking_lock();
|
||||
let store = demo_store("no_home", true);
|
||||
// SAFETY: env_lock is held; finish restores HOME.
|
||||
unsafe { std::env::set_var("HOME", "relative") };
|
||||
let refused = refusal(resolve(DEMO));
|
||||
let owner = read_owner(&owner_record_path(&store.join("share"), DEMO)).unwrap();
|
||||
finish(&store);
|
||||
assert_eq!(refused.code, 500, "{}", refused.message);
|
||||
assert_eq!(owner, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_the_signed_manifest_is_accepted() {
|
||||
let _env = crate::tests::env_lock().blocking_lock();
|
||||
let store = demo_store("manifest", true);
|
||||
record(&store, DEMO, Owner::Verified(demo_key()));
|
||||
let root = store.join(DEMO);
|
||||
let signed = std::fs::read(root.join(MANIFEST_FILE)).unwrap();
|
||||
let mut other = signed.clone();
|
||||
other.extend_from_slice(b"\n# other\n");
|
||||
let accepted = verify_owner(DEMO, &root, &signed);
|
||||
let refused = verify_owner(DEMO, &root, &other).err();
|
||||
finish(&store);
|
||||
assert!(accepted.is_ok());
|
||||
let refused = refused.expect("a manifest that was not signed was accepted");
|
||||
assert_eq!(refused.code, 403, "{}", refused.message);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn development_content_does_not_depend_on_the_trust_store() {
|
||||
let _env = crate::tests::env_lock().blocking_lock();
|
||||
let store = store("dev_store", ID, "app.wasm");
|
||||
let keys = store.join("keys");
|
||||
std::fs::create_dir_all(&keys).unwrap();
|
||||
std::fs::write(keys.join("broken.pub"), "not a key").unwrap();
|
||||
// SAFETY: as in `store`.
|
||||
unsafe { std::env::set_var("WEFT_TRUSTED_KEYS", &keys) };
|
||||
let resolved = resolve(ID).map(|p| p.root);
|
||||
finish(&store);
|
||||
assert_eq!(resolved.ok(), Some(store.join(ID)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_damaged_trust_store_or_record_is_a_host_error() {
|
||||
let _env = crate::tests::env_lock().blocking_lock();
|
||||
let store = demo_store("damaged", true);
|
||||
std::fs::write(store.join("keys/broken.pub"), "not a key").unwrap();
|
||||
let bad_key = refusal(resolve(DEMO));
|
||||
std::fs::remove_file(store.join("keys/broken.pub")).unwrap();
|
||||
let record = owner_record_path(&store.join("share"), DEMO);
|
||||
std::fs::write(&record, "nonsense\n").unwrap();
|
||||
let bad_record = refusal(resolve(DEMO));
|
||||
finish(&store);
|
||||
for refused in [bad_key, bad_record] {
|
||||
assert_eq!(refused.code, 500, "{}", refused.message);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_package_changed_after_installation_is_refused() {
|
||||
let _env = crate::tests::env_lock().blocking_lock();
|
||||
let store = demo_store("changed", true);
|
||||
record(&store, DEMO, Owner::Verified(demo_key()));
|
||||
let page = store.join(DEMO).join("ui/index.html");
|
||||
let mut text = std::fs::read_to_string(&page).unwrap();
|
||||
text.push_str("<script>changed</script>");
|
||||
std::fs::write(&page, text).unwrap();
|
||||
let changed = refusal(resolve(DEMO));
|
||||
// Without a record, the changed package matches no trusted key.
|
||||
std::fs::remove_file(owner_record_path(&store.join("share"), DEMO)).unwrap();
|
||||
let unrecorded = refusal(resolve(DEMO));
|
||||
finish(&store);
|
||||
assert_eq!(changed.code, 403, "{}", changed.message);
|
||||
assert!(
|
||||
changed.message.contains("not signed by its owner"),
|
||||
"{}",
|
||||
changed.message
|
||||
);
|
||||
assert_eq!(unrecorded.code, 403, "{}", unrecorded.message);
|
||||
assert!(
|
||||
unrecorded.message.contains("no recorded owner"),
|
||||
"{}",
|
||||
unrecorded.message
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_withdrawn_key_no_longer_launches_its_packages() {
|
||||
let _env = crate::tests::env_lock().blocking_lock();
|
||||
let store = demo_store("withdrawn", false);
|
||||
record(&store, DEMO, Owner::Verified(demo_key()));
|
||||
let refused = refusal(resolve(DEMO));
|
||||
finish(&store);
|
||||
assert_eq!(refused.code, 403, "{}", refused.message);
|
||||
assert!(refused.message.contains("no longer"), "{}", refused.message);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unsigned_content_needs_a_development_record() {
|
||||
let _env = crate::tests::env_lock().blocking_lock();
|
||||
let store = store("unrecorded", ID, "app.wasm");
|
||||
std::fs::remove_file(owner_record_path(&store.join("share"), ID)).unwrap();
|
||||
let refused = refusal(resolve(ID));
|
||||
// Another owner's record does not admit it either.
|
||||
record(&store, ID, Owner::Verified(demo_key()));
|
||||
let other_owner = refusal(resolve(ID));
|
||||
finish(&store);
|
||||
for refused in [refused, other_owner] {
|
||||
assert_eq!(refused.code, 403, "{}", refused.message);
|
||||
assert!(
|
||||
refused.message.contains("not a link"),
|
||||
"{}",
|
||||
refused.message
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load diff
|
|
@ -1,7 +1,7 @@
|
|||
use std::path::PathBuf;
|
||||
use std::time::Duration;
|
||||
|
||||
use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader, BufWriter};
|
||||
use tokio::io::{AsyncBufReadExt, AsyncReadExt, AsyncWriteExt, BufReader, BufWriter};
|
||||
use weft_ipc_types::AppdToCompositor;
|
||||
|
||||
use crate::Registry;
|
||||
|
|
@ -33,6 +33,11 @@ impl Drop for IpcRelay {
|
|||
}
|
||||
}
|
||||
|
||||
/// The longest message from a component, its line break included: the
|
||||
/// runtime refuses longer ones, so a longer line ends the relay.
|
||||
#[cfg(unix)]
|
||||
const MAX_RELAY_FRAME: usize = 64 * 1024 + 2;
|
||||
|
||||
/// Listens on `socket_path` for the session's component and relays
|
||||
/// newline-delimited messages between it and the returned sender (towards
|
||||
/// the component) and the broadcast channel (from the component).
|
||||
|
|
@ -69,14 +74,29 @@ pub(crate) fn spawn_ipc_relay(
|
|||
let (reader, writer) = tokio::io::split(stream);
|
||||
let mut reader = BufReader::new(reader);
|
||||
let mut writer = BufWriter::new(writer);
|
||||
// The frame being read lives outside the loop: `read_until` keeps
|
||||
// what it has read when the other branch wins, so a message from the
|
||||
// page never splits a message from the component.
|
||||
let mut frame = Vec::new();
|
||||
loop {
|
||||
let mut line = String::new();
|
||||
let mut limited = (&mut reader).take((MAX_RELAY_FRAME + 1 - frame.len()) as u64);
|
||||
tokio::select! {
|
||||
n = reader.read_line(&mut line) => {
|
||||
n = limited.read_until(b'\n', &mut frame) => {
|
||||
match n {
|
||||
Ok(0) | Err(_) => break,
|
||||
Ok(_) if frame.len() > MAX_RELAY_FRAME => {
|
||||
tracing::warn!(session_id, "IPC relay: message over the size limit");
|
||||
break;
|
||||
}
|
||||
// The rest of the message is still to come.
|
||||
Ok(_) if !frame.ends_with(b"\n") => {}
|
||||
Ok(_) => {
|
||||
let payload = line.trim_end().to_owned();
|
||||
let line = std::mem::take(&mut frame);
|
||||
let Ok(text) = String::from_utf8(line) else {
|
||||
tracing::warn!(session_id, "IPC relay: message is not UTF-8");
|
||||
break;
|
||||
};
|
||||
let payload = text.trim_end_matches(['\n', '\r']).to_owned();
|
||||
let _ = broadcast.send(Response::IpcMessage { session_id, payload });
|
||||
}
|
||||
}
|
||||
|
|
@ -120,6 +140,8 @@ const READY_TIMEOUT: Duration = Duration::from_secs(30);
|
|||
/// runtime passes the guest only the variables it names and pages cannot read
|
||||
/// the host process environment.
|
||||
const READY_TOKEN_ENV: &str = "WEFT_READY_TOKEN";
|
||||
/// The application's close policy, `immediate` or `ask`, for the app shell.
|
||||
const CLOSE_POLICY_ENV: &str = "WEFT_APP_CLOSE";
|
||||
|
||||
/// Environment variable carrying the session's application bridge credential
|
||||
/// to weft-app-shell.
|
||||
|
|
@ -197,8 +219,26 @@ fn spawn_app_shell(
|
|||
package: &LaunchPackage,
|
||||
token: &str,
|
||||
bridge_token: Option<String>,
|
||||
wayland: Option<std::os::unix::net::UnixStream>,
|
||||
) -> std::io::Result<tokio::process::Child> {
|
||||
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.
|
||||
|
|
@ -210,7 +250,7 @@ fn spawn_app_shell(
|
|||
.arg("--ui")
|
||||
.arg(&package.ui_entry)
|
||||
.env(READY_TOKEN_ENV, token)
|
||||
.stdin(std::process::Stdio::null())
|
||||
.env(CLOSE_POLICY_ENV, package.close.as_str())
|
||||
.stdout(std::process::Stdio::piped())
|
||||
.stderr(std::process::Stdio::piped())
|
||||
.kill_on_drop(true)
|
||||
|
|
@ -249,12 +289,27 @@ fn spawn_file_portal(
|
|||
Some((socket, child))
|
||||
}
|
||||
|
||||
/// A request to end a session, from `TERMINATE_APP`.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(crate) enum Stop {
|
||||
/// Close as a user close would; the application may decline.
|
||||
Close,
|
||||
/// Terminate without asking.
|
||||
Force,
|
||||
}
|
||||
|
||||
/// Repeated requests carry nothing new, so a few queued ones are enough.
|
||||
pub(crate) const STOP_QUEUE: usize = 2;
|
||||
pub(crate) type StopSender = tokio::sync::mpsc::Sender<Stop>;
|
||||
/// Ends when appd shuts down and drops the sender.
|
||||
pub(crate) type StopReceiver = tokio::sync::mpsc::Receiver<Stop>;
|
||||
|
||||
pub(crate) async fn supervise(
|
||||
session_id: u64,
|
||||
mut package: LaunchPackage,
|
||||
grants: crate::grants::SessionGrants,
|
||||
registry: Registry,
|
||||
abort_rx: tokio::sync::oneshot::Receiver<()>,
|
||||
abort_rx: StopReceiver,
|
||||
compositor_tx: Option<CompositorSender>,
|
||||
) -> anyhow::Result<()> {
|
||||
let mut abort_rx = abort_rx;
|
||||
|
|
@ -317,10 +372,6 @@ pub(crate) async fn supervise(
|
|||
cmd.arg("--ipc-socket").arg(&ipc_socket_path);
|
||||
cmd.arg("--module").arg(&package.module);
|
||||
|
||||
if let Some((ref sock, _)) = portal {
|
||||
cmd.env("WEFT_FILE_PORTAL_SOCKET", sock);
|
||||
}
|
||||
|
||||
for dir in &grants.dirs {
|
||||
cmd.arg("--preopen").arg(dir.preopen_arg());
|
||||
}
|
||||
|
|
@ -336,7 +387,7 @@ pub(crate) async fn supervise(
|
|||
relay: Some(relay),
|
||||
image,
|
||||
compositor_tx,
|
||||
surface_announced: false,
|
||||
client_attached: false,
|
||||
};
|
||||
|
||||
let mut runtime = match cmd.spawn() {
|
||||
|
|
@ -347,23 +398,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"),
|
||||
|
|
@ -383,16 +417,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"),
|
||||
|
|
@ -417,10 +470,22 @@ pub(crate) async fn supervise(
|
|||
Ok(reader) => reader,
|
||||
Err(reason) => return session.settle(®istry, &reason).await,
|
||||
};
|
||||
tokio::spawn(drain_stdout(shell_stdout, session_id));
|
||||
let (cancel_tx, mut cancelled) = tokio::sync::mpsc::channel(1);
|
||||
tokio::spawn(watch_app_shell_stdout(
|
||||
shell_stdout,
|
||||
session_id,
|
||||
token.clone(),
|
||||
cancel_tx,
|
||||
));
|
||||
|
||||
{
|
||||
let mut reg = registry.lock().await;
|
||||
// A stop requested while starting can still be queued here, or lose
|
||||
// the race with READY; the session is then stopped, not shown.
|
||||
if matches!(reg.state(session_id), AppStateKind::Stopping) || abort_rx.try_recv().is_ok() {
|
||||
drop(reg);
|
||||
return session.settle(®istry, "startup aborted").await;
|
||||
}
|
||||
reg.set_state(session_id, AppStateKind::Running);
|
||||
let _ = reg.broadcast().send(Response::AppReady {
|
||||
session_id,
|
||||
|
|
@ -429,21 +494,111 @@ pub(crate) async fn supervise(
|
|||
}
|
||||
tracing::info!(session_id, %app_id, "app ready");
|
||||
|
||||
let reason = tokio::select! {
|
||||
status = session.runtime.as_mut().expect("runtime spawned").wait() => {
|
||||
format!("runtime exited ({status:?})")
|
||||
}
|
||||
status = session.app_shell.as_mut().expect("app shell spawned").wait() => {
|
||||
format!("app shell exited ({status:?})")
|
||||
}
|
||||
_ = &mut abort_rx => "terminate requested".to_owned(),
|
||||
_ = session.relay.as_mut().expect("relay opened").ended() => {
|
||||
"component closed its IPC connection".to_owned()
|
||||
// Whether the user asked the application to close, so that a clean exit
|
||||
// afterwards, also one the application makes after declining, is a
|
||||
// close on request.
|
||||
let mut close_asked = false;
|
||||
let reason = loop {
|
||||
tokio::select! {
|
||||
status = session.runtime.as_mut().expect("runtime spawned").wait() => {
|
||||
break format!("runtime exited ({status:?})");
|
||||
}
|
||||
status = session.app_shell.as_mut().expect("app shell spawned").wait() => {
|
||||
break match status {
|
||||
Ok(status) if close_asked && status.success() => {
|
||||
format!("closed on request; app shell exited ({status:?})")
|
||||
}
|
||||
status => format!("app shell exited ({status:?})"),
|
||||
};
|
||||
}
|
||||
stop = abort_rx.recv() => match stop {
|
||||
Some(Stop::Force) => break "terminated by force".to_owned(),
|
||||
Some(Stop::Close) => {
|
||||
close_asked = true;
|
||||
match session.close(session_id, &mut cancelled, &mut abort_rx).await {
|
||||
Close::Settle(reason) => break reason,
|
||||
// The application keeps running, as its close
|
||||
// policy allows; its window comes to the front so
|
||||
// the user sees why. A later request asks again.
|
||||
Close::Cancelled => {
|
||||
tracing::info!(session_id, "the application declined the close");
|
||||
session.focus(session_id);
|
||||
}
|
||||
}
|
||||
}
|
||||
// The senders are dropped only when appd shuts down.
|
||||
None => break "appd is shutting down".to_owned(),
|
||||
},
|
||||
_ = session.relay.as_mut().expect("relay opened").ended() => {
|
||||
break "component closed its IPC connection".to_owned();
|
||||
}
|
||||
}
|
||||
};
|
||||
session.settle(®istry, &reason).await
|
||||
}
|
||||
|
||||
/// How a close request ended.
|
||||
enum Close {
|
||||
/// The session ends, for this reason.
|
||||
Settle(String),
|
||||
/// The application declined the close and keeps running.
|
||||
Cancelled,
|
||||
}
|
||||
|
||||
/// The app shell's report that its page declined a close, followed by the
|
||||
/// session's readiness token so page output cannot fake it.
|
||||
const CLOSE_CANCELLED: &str = "CLOSE_CANCELLED";
|
||||
|
||||
/// Passes the app shell's close reports on to the supervisor and logs
|
||||
/// everything else it prints.
|
||||
async fn watch_app_shell_stdout(
|
||||
mut reader: BufReader<tokio::process::ChildStdout>,
|
||||
session_id: u64,
|
||||
token: String,
|
||||
cancelled: tokio::sync::mpsc::Sender<()>,
|
||||
) {
|
||||
while let Ok(Some(line)) = read_child_line(&mut reader).await {
|
||||
// Earlier output without a trailing newline can precede the
|
||||
// report, as it can precede READY; the token alone establishes it.
|
||||
if line.rsplit_once(' ').is_some_and(|(head, t)| {
|
||||
head.ends_with(CLOSE_CANCELLED) && crate::ws::tokens_match(&token, t)
|
||||
}) {
|
||||
// One pending report is enough; the supervisor drops stale ones
|
||||
// before it asks again.
|
||||
let _ = cancelled.try_send(());
|
||||
} else {
|
||||
tracing::debug!(session_id, stdout = %line, "child stdout");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// How long an application may take to close after being asked, for
|
||||
/// example to save, before its processes are terminated.
|
||||
pub(crate) const CLOSE_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(5);
|
||||
|
||||
/// 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<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()
|
||||
.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,
|
||||
|
|
@ -473,19 +628,112 @@ struct OwnedSession {
|
|||
/// The mounted package image, released after both children have exited.
|
||||
image: Option<Mount>,
|
||||
compositor_tx: Option<CompositorSender>,
|
||||
surface_announced: bool,
|
||||
/// Whether the compositor was given this session's client connection.
|
||||
client_attached: bool,
|
||||
}
|
||||
|
||||
impl OwnedSession {
|
||||
/// Closes a running session as a user close would: the compositor asks
|
||||
/// its windows to close and the app shell gets `CLOSE_TIMEOUT` to exit by
|
||||
/// itself. Returns the terminal reason; settling terminates whatever is
|
||||
/// still running.
|
||||
async fn close(
|
||||
&mut self,
|
||||
session_id: u64,
|
||||
cancelled: &mut tokio::sync::mpsc::Receiver<()>,
|
||||
stops: &mut StopReceiver,
|
||||
) -> Close {
|
||||
// A report already read from an earlier close, for example one the
|
||||
// user started in the compositor, does not answer this one. One
|
||||
// still in the pipe can: the session then reads as declined while
|
||||
// the app shell is still asking, and the app shell's own answer
|
||||
// timeout still closes a page that does not answer.
|
||||
while cancelled.try_recv().is_ok() {}
|
||||
let asked = self.client_attached
|
||||
&& self.compositor_tx.as_ref().is_some_and(|tx| {
|
||||
tx.is_connected()
|
||||
&& tx
|
||||
.try_send(AppdToCompositor::AppCloseRequest { session_id }.into())
|
||||
.is_ok()
|
||||
});
|
||||
if !asked {
|
||||
return Close::Settle(
|
||||
"terminate requested; the compositor could not ask the app to close".to_owned(),
|
||||
);
|
||||
}
|
||||
let (Some(app_shell), Some(runtime), Some(relay)) = (
|
||||
self.app_shell.as_mut(),
|
||||
self.runtime.as_mut(),
|
||||
self.relay.as_mut(),
|
||||
) else {
|
||||
return Close::Settle("terminate requested".to_owned());
|
||||
};
|
||||
let wait = async {
|
||||
loop {
|
||||
tokio::select! {
|
||||
status = app_shell.wait() => break Close::Settle(match status {
|
||||
Ok(status) if status.success() => {
|
||||
format!("closed on request; app shell exited ({status:?})")
|
||||
}
|
||||
status => format!("app shell failed while closing ({status:?})"),
|
||||
}),
|
||||
status = runtime.wait() => {
|
||||
break Close::Settle(format!("runtime exited while closing ({status:?})"));
|
||||
}
|
||||
_ = relay.ended() => break Close::Settle(
|
||||
"component closed its IPC connection while closing".to_owned(),
|
||||
),
|
||||
Some(()) = cancelled.recv() => break Close::Cancelled,
|
||||
stop = stops.recv() => match stop {
|
||||
// Asking again while the application answers changes
|
||||
// nothing.
|
||||
Some(Stop::Close) => {}
|
||||
Some(Stop::Force) => {
|
||||
break Close::Settle("terminated by force while closing".to_owned());
|
||||
}
|
||||
None => break Close::Settle("appd is shutting down".to_owned()),
|
||||
},
|
||||
}
|
||||
}
|
||||
};
|
||||
tokio::time::timeout(CLOSE_TIMEOUT, wait)
|
||||
.await
|
||||
.unwrap_or_else(|_| {
|
||||
Close::Settle(format!(
|
||||
"close requested; the app shell did not exit within {} s and was terminated",
|
||||
CLOSE_TIMEOUT.as_secs()
|
||||
))
|
||||
})
|
||||
}
|
||||
|
||||
/// Brings the session's window to the front with keyboard focus.
|
||||
fn focus(&self, session_id: u64) {
|
||||
if self.client_attached
|
||||
&& let Some(tx) = &self.compositor_tx
|
||||
{
|
||||
let _ = tx.try_send(AppdToCompositor::AppFocusRequest { session_id }.into());
|
||||
}
|
||||
}
|
||||
|
||||
async fn settle(self, registry: &Registry, reason: &str) -> anyhow::Result<()> {
|
||||
let session_id = self.session_id;
|
||||
tracing::info!(session_id, reason, "stopping session");
|
||||
{
|
||||
let mut reg = registry.lock().await;
|
||||
if !matches!(reg.state(session_id), AppStateKind::Stopping) {
|
||||
reg.set_state(session_id, AppStateKind::Stopping);
|
||||
let _ = reg.broadcast().send(Response::AppState {
|
||||
session_id,
|
||||
state: AppStateKind::Stopping,
|
||||
});
|
||||
}
|
||||
}
|
||||
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!(
|
||||
|
|
@ -526,7 +774,7 @@ async fn kill_child(child: Option<tokio::process::Child>) {
|
|||
async fn wait_for_child_ready(
|
||||
stdout: tokio::process::ChildStdout,
|
||||
token: &str,
|
||||
abort_rx: &mut tokio::sync::oneshot::Receiver<()>,
|
||||
abort_rx: &mut StopReceiver,
|
||||
) -> Result<BufReader<tokio::process::ChildStdout>, String> {
|
||||
tokio::select! {
|
||||
r = tokio::time::timeout(READY_TIMEOUT, wait_for_ready(stdout, token)) => match r {
|
||||
|
|
@ -534,7 +782,8 @@ async fn wait_for_child_ready(
|
|||
Ok(Err(e)) => Err(format!("did not become ready: {e}")),
|
||||
Err(_) => Err(format!("not ready after {}s", READY_TIMEOUT.as_secs())),
|
||||
},
|
||||
_ = abort_rx => Err("startup aborted".to_owned()),
|
||||
// Any stop request, or appd shutting down, ends a startup.
|
||||
_ = abort_rx.recv() => Err("startup aborted".to_owned()),
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -572,6 +821,62 @@ async fn drain_stderr(stderr: tokio::process::ChildStderr, session_id: u64, proc
|
|||
mod tests {
|
||||
use super::SYSTEMD_SCOPE_ARGS;
|
||||
|
||||
fn relay_socket(name: &str) -> std::path::PathBuf {
|
||||
std::env::temp_dir().join(format!("weft-relay-{name}-{}.sock", std::process::id()))
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_message_from_the_page_does_not_split_one_from_the_component() {
|
||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||
let path = relay_socket("split");
|
||||
let (broadcast, mut messages) = tokio::sync::broadcast::channel(16);
|
||||
let (to_component, mut relay) = super::spawn_ipc_relay(7, path.clone(), broadcast).unwrap();
|
||||
let mut component = tokio::net::UnixStream::connect(&path).await.unwrap();
|
||||
component.write_all(b"{\"half\":").await.unwrap();
|
||||
// The relay starts reading the component's message, then the page's
|
||||
// message wins the select.
|
||||
tokio::time::sleep(std::time::Duration::from_millis(50)).await;
|
||||
to_component.send("from the page".to_owned()).await.unwrap();
|
||||
let mut received = vec![0; 14];
|
||||
component.read_exact(&mut received).await.unwrap();
|
||||
assert_eq!(received, b"from the page\n");
|
||||
component.write_all(b"\"whole\"}\n").await.unwrap();
|
||||
let message = tokio::time::timeout(std::time::Duration::from_secs(5), messages.recv())
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert!(
|
||||
matches!(&message, crate::ipc::Response::IpcMessage { session_id: 7, payload } if payload == "{\"half\":\"whole\"}"),
|
||||
"{message:?}"
|
||||
);
|
||||
|
||||
// A message at the limit, ending in a carriage return and line
|
||||
// feed, arrives whole.
|
||||
let mut at_limit = vec![b'y'; super::MAX_RELAY_FRAME - 2];
|
||||
at_limit.extend_from_slice(b"\r\n");
|
||||
component.write_all(&at_limit).await.unwrap();
|
||||
let message = tokio::time::timeout(std::time::Duration::from_secs(5), messages.recv())
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert!(
|
||||
matches!(&message, crate::ipc::Response::IpcMessage { payload, .. } if payload.len() == super::MAX_RELAY_FRAME - 2),
|
||||
"a message at the limit did not arrive whole"
|
||||
);
|
||||
|
||||
// A line longer than any message ends the relay, even when its line
|
||||
// break comes in the same read.
|
||||
let mut over = vec![b'x'; super::MAX_RELAY_FRAME];
|
||||
over.push(b'\n');
|
||||
component.write_all(&over).await.unwrap();
|
||||
tokio::time::timeout(std::time::Duration::from_secs(5), relay.ended())
|
||||
.await
|
||||
.expect("the relay did not end on an overlong line");
|
||||
assert!(messages.try_recv().is_err());
|
||||
drop(relay);
|
||||
assert!(!path.exists());
|
||||
}
|
||||
|
||||
/// systemd-run checks its options and their combinations before it
|
||||
/// connects to the service manager. Run against an empty runtime
|
||||
/// directory and bus address, it must get as far as the connection
|
||||
|
|
|
|||
|
|
@ -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]
|
||||
|
|
|
|||
|
|
@ -1,13 +1,21 @@
|
|||
#[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, LoopHandle, Mode, PostAction, RegistrationToken, channel,
|
||||
generic::Generic,
|
||||
timer::{TimeoutAction, Timer},
|
||||
};
|
||||
#[cfg(unix)]
|
||||
use smithay::reexports::wayland_server::backend::{ClientId, DisconnectReason};
|
||||
|
||||
#[cfg(unix)]
|
||||
use weft_ipc_types::{
|
||||
|
|
@ -15,15 +23,40 @@ 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<u8>,
|
||||
write_stream: Option<UnixStream>,
|
||||
/// pid → (app_id, session_id) for Wayland clients whose surface has not yet arrived.
|
||||
pub pending_pids: HashMap<u32, (String, u64)>,
|
||||
/// 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.
|
||||
fds: VecDeque<OwnedFd>,
|
||||
/// The Wayland client of each appd session.
|
||||
sessions: HashMap<u64, ClientId>,
|
||||
/// Sessions whose first toplevel was reported to appd.
|
||||
reported: HashSet<u64>,
|
||||
/// Sessions that already received keyboard focus for a mapped window;
|
||||
/// kept until the session ends, so recreating a window gains nothing.
|
||||
focused_on_map: HashSet<u64>,
|
||||
/// Where clients report their session's disconnection.
|
||||
disconnected: Option<channel::Sender<(u64, ClientId)>>,
|
||||
/// Bytes for appd that did not fit in the socket buffer, sent before
|
||||
/// anything else so frames stay whole.
|
||||
out_buf: Vec<u8>,
|
||||
/// Retries `flush` while `out_buf` holds bytes; armed only then.
|
||||
flush_retry: Option<RegistrationToken>,
|
||||
loop_handle: Option<LoopHandle<'static, WeftCompositorState>>,
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
|
|
@ -33,26 +66,111 @@ impl WeftAppdIpc {
|
|||
socket_path,
|
||||
read_buf: Vec::new(),
|
||||
write_stream: None,
|
||||
pending_pids: HashMap::new(),
|
||||
connected: false,
|
||||
fds: VecDeque::new(),
|
||||
sessions: HashMap::new(),
|
||||
reported: HashSet::new(),
|
||||
focused_on_map: HashSet::new(),
|
||||
disconnected: None,
|
||||
out_buf: Vec::new(),
|
||||
flush_retry: None,
|
||||
loop_handle: None,
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
pub fn send(&mut self, msg: &CompositorToAppd) {
|
||||
let Some(stream) = &mut self.write_stream else {
|
||||
return;
|
||||
};
|
||||
match frame_encode(msg) {
|
||||
Ok(frame) => {
|
||||
if stream.write_all(&frame).is_err() {
|
||||
self.write_stream = None;
|
||||
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"),
|
||||
}
|
||||
}
|
||||
|
||||
fn try_decode_frames(&mut self) -> Vec<AppdToCompositor> {
|
||||
/// 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();
|
||||
}
|
||||
}
|
||||
|
||||
/// 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();
|
||||
}
|
||||
|
||||
/// Whether a window `session_id` maps now may take keyboard focus: only
|
||||
/// the first one in the session's lifetime.
|
||||
pub fn take_focus_on_map(&mut self, session_id: u64) -> bool {
|
||||
self.sessions.contains_key(&session_id) && self.focused_on_map.insert(session_id)
|
||||
}
|
||||
|
||||
/// 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 });
|
||||
}
|
||||
}
|
||||
|
||||
/// 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();
|
||||
loop {
|
||||
if self.read_buf.len() < 4 {
|
||||
|
|
@ -66,9 +184,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;
|
||||
|
|
@ -76,24 +192,45 @@ impl WeftAppdIpc {
|
|||
let frame_end = 4 + declared_len;
|
||||
match frame_decode::<AppdToCompositor>(&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)
|
||||
}
|
||||
|
||||
pub fn on_read(&mut self, stream: &mut UnixStream) -> (Vec<AppdToCompositor>, 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<AppdToCompositor>, 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,37 +238,118 @@ impl WeftAppdIpc {
|
|||
}
|
||||
}
|
||||
}
|
||||
let messages = self.try_decode_frames();
|
||||
if eof {
|
||||
self.write_stream = None;
|
||||
self.read_buf.clear();
|
||||
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;
|
||||
}
|
||||
(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<ClientId> {
|
||||
self.connected = false;
|
||||
self.write_stream = None;
|
||||
self.out_buf.clear();
|
||||
self.read_buf.clear();
|
||||
self.fds.clear();
|
||||
self.reported.clear();
|
||||
self.focused_on_map.clear();
|
||||
self.sessions.drain().map(|(_, client)| client).collect()
|
||||
}
|
||||
}
|
||||
|
||||
#[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);
|
||||
ipc.focused_on_map.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::AppCloseRequest { session_id } => {
|
||||
let closed = state.close_session_windows(session_id);
|
||||
tracing::info!(session_id, windows = closed, "session asked to close");
|
||||
}
|
||||
AppdToCompositor::AppFocusRequest { session_id } => {
|
||||
tracing::debug!(session_id, "AppFocusRequest");
|
||||
if state.activate_session(session_id) {
|
||||
tracing::info!(session_id, "session activated");
|
||||
} else {
|
||||
tracing::info!(
|
||||
session_id,
|
||||
"activation requested for a session with no window"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 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 +386,32 @@ 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() {
|
||||
ipc.disconnected = Some(sender);
|
||||
}
|
||||
state
|
||||
.loop_handle
|
||||
.insert_source(receiver, |event, _, state| {
|
||||
// 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);
|
||||
ipc.focused_on_map.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 +421,14 @@ 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.connected) {
|
||||
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,
|
||||
|
|
@ -187,10 +439,12 @@ 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();
|
||||
}
|
||||
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
|
||||
|
|
@ -203,16 +457,37 @@ 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"
|
||||
"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)
|
||||
}
|
||||
},
|
||||
);
|
||||
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"),
|
||||
|
|
@ -225,3 +500,176 @@ 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);
|
||||
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 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();
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -550,6 +550,7 @@ fn connector_connected(
|
|||
tracing::info!(?name, "output connected");
|
||||
let (pw, ph) = (wl_mode.size.w, wl_mode.size.h);
|
||||
state.weft_shell_state.reconfigure_panels(0, 0, pw, ph);
|
||||
state.layout_app_windows();
|
||||
state.weft_shell_state.retain_alive_panels();
|
||||
render_output(state, node, crtc);
|
||||
}
|
||||
|
|
@ -578,6 +579,7 @@ fn connector_disconnected(
|
|||
.map(|g| (g.size.w, g.size.h))
|
||||
.unwrap_or((0, 0));
|
||||
state.weft_shell_state.reconfigure_panels(0, 0, pw, ph);
|
||||
state.layout_app_windows();
|
||||
state.weft_shell_state.retain_alive_panels();
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -124,6 +124,7 @@ pub fn run() -> anyhow::Result<()> {
|
|||
state
|
||||
.weft_shell_state
|
||||
.reconfigure_panels(0, 0, size.w, size.h);
|
||||
state.layout_app_windows();
|
||||
state.weft_shell_state.retain_alive_panels();
|
||||
}
|
||||
WinitEvent::Input(input_event) => {
|
||||
|
|
|
|||
|
|
@ -6,7 +6,7 @@ use smithay::{
|
|||
TouchEvent,
|
||||
},
|
||||
input::{
|
||||
keyboard::FilterResult,
|
||||
keyboard::{FilterResult, KeyboardTarget},
|
||||
pointer::{AxisFrame, ButtonEvent, MotionEvent},
|
||||
},
|
||||
utils::{Logical, Point, SERIAL_COUNTER},
|
||||
|
|
@ -42,20 +42,97 @@ pub fn process_input_event<B: InputBackend>(state: &mut WeftCompositorState, eve
|
|||
}
|
||||
}
|
||||
|
||||
/// What the compositor does with a key instead of forwarding it.
|
||||
enum Shortcut {
|
||||
/// Alt+F4: close the focused application window.
|
||||
Close,
|
||||
/// A Super key tap: show the shell.
|
||||
Shell,
|
||||
/// Nothing: a suppressed key.
|
||||
None,
|
||||
}
|
||||
|
||||
fn handle_keyboard<B: InputBackend>(state: &mut WeftCompositorState, event: B::KeyboardKeyEvent) {
|
||||
use smithay::backend::input::KeyState;
|
||||
use smithay::input::keyboard::keysyms;
|
||||
|
||||
let serial = SERIAL_COUNTER.next_serial();
|
||||
let time = event.time_msec();
|
||||
let key_state = event.state();
|
||||
let Some(keyboard) = state.seat.get_keyboard() else {
|
||||
return;
|
||||
};
|
||||
|
||||
if let Some(keyboard) = state.seat.get_keyboard() {
|
||||
keyboard.input::<(), _>(
|
||||
state,
|
||||
event.key_code(),
|
||||
key_state,
|
||||
serial,
|
||||
time,
|
||||
|_state, _mods, _keysym| FilterResult::Forward,
|
||||
);
|
||||
// Alt+F4 and the Super keys belong to the compositor. Alt+F4 asks the
|
||||
// focused application window to close. Super's key events are never
|
||||
// delivered to an application: tapped alone, without another key or a
|
||||
// button, it brings the shell's panel to the front with keyboard focus
|
||||
// and is then delivered to the shell, which opens or closes its
|
||||
// launcher. Held, it still sets the Super modifier for other keys.
|
||||
let (filtered, mods_changed) = keyboard.input_intercept::<_, _>(
|
||||
state,
|
||||
event.key_code(),
|
||||
key_state,
|
||||
|state, mods, keysym| {
|
||||
// A release is taken only when its press was, so no client
|
||||
// sees half of a key.
|
||||
let code = keysym.raw_code().raw();
|
||||
let sym = keysym.modified_sym();
|
||||
if key_state == KeyState::Pressed {
|
||||
if mods.alt && sym == keysyms::KEY_F4.into() {
|
||||
state.super_tap = None;
|
||||
state.suppressed_keys.push(code);
|
||||
return FilterResult::Intercept(Shortcut::Close);
|
||||
}
|
||||
if sym == keysyms::KEY_Super_L.into() || sym == keysyms::KEY_Super_R.into() {
|
||||
state.super_tap = (!mods.ctrl && !mods.alt && !mods.shift).then_some(code);
|
||||
state.suppressed_keys.push(code);
|
||||
return FilterResult::Intercept(Shortcut::None);
|
||||
}
|
||||
state.super_tap = None;
|
||||
} else if let Some(i) = state.suppressed_keys.iter().position(|&k| k == code) {
|
||||
state.suppressed_keys.remove(i);
|
||||
if state.super_tap.take() == Some(code) {
|
||||
return FilterResult::Intercept(Shortcut::Shell);
|
||||
}
|
||||
return FilterResult::Intercept(Shortcut::None);
|
||||
}
|
||||
FilterResult::Forward
|
||||
},
|
||||
);
|
||||
let shortcut = match filtered {
|
||||
FilterResult::Forward => {
|
||||
keyboard.input_forward(
|
||||
state,
|
||||
event.key_code(),
|
||||
key_state,
|
||||
serial,
|
||||
time,
|
||||
mods_changed,
|
||||
);
|
||||
return;
|
||||
}
|
||||
FilterResult::Intercept(shortcut) => shortcut,
|
||||
};
|
||||
// The focused client follows the modifiers even when the key that
|
||||
// changed them is taken, so none stays held there.
|
||||
if mods_changed && let Some(focus) = keyboard.current_focus() {
|
||||
let seat = state.seat.clone();
|
||||
focus.modifiers(&seat, state, keyboard.modifier_state(), serial);
|
||||
}
|
||||
match shortcut {
|
||||
Shortcut::Close => state.close_focused_window(),
|
||||
Shortcut::Shell => {
|
||||
if state.activate_panel() {
|
||||
// The tap itself, for the shell; the keyboard's own state
|
||||
// already saw it.
|
||||
let code = event.key_code();
|
||||
keyboard.input_forward(state, code, KeyState::Pressed, serial, time, false);
|
||||
let release = SERIAL_COUNTER.next_serial();
|
||||
keyboard.input_forward(state, code, KeyState::Released, release, time, false);
|
||||
}
|
||||
}
|
||||
Shortcut::None => {}
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -122,10 +199,19 @@ fn handle_pointer_button<B: InputBackend>(
|
|||
let button = event.button_code();
|
||||
let button_state = event.state();
|
||||
|
||||
// On press: focus the surface under the pointer.
|
||||
// On press: activate the window under the pointer, which raises an
|
||||
// application window and focuses it. A held Super key is then no
|
||||
// longer a tap.
|
||||
if button_state == ButtonState::Pressed {
|
||||
state.super_tap = None;
|
||||
let pointer_location = state.pointer_location;
|
||||
if let Some((surface, _loc)) = surface_under(state, pointer_location) {
|
||||
let window = state
|
||||
.space
|
||||
.element_under(pointer_location)
|
||||
.map(|(window, _)| window.clone());
|
||||
if let Some(window) = window {
|
||||
state.activate_window(&window);
|
||||
} else if let Some((surface, _loc)) = surface_under(state, pointer_location) {
|
||||
if let Some(keyboard) = state.seat.get_keyboard() {
|
||||
keyboard.set_focus(state, Some(surface), serial);
|
||||
}
|
||||
|
|
@ -193,6 +279,7 @@ fn handle_pointer_axis<B: InputBackend>(
|
|||
}
|
||||
|
||||
fn handle_touch_down<B: InputBackend>(state: &mut WeftCompositorState, event: B::TouchDownEvent) {
|
||||
state.super_tap = None;
|
||||
let serial = SERIAL_COUNTER.next_serial();
|
||||
let output = state.space.outputs().next().cloned();
|
||||
if let Some(output) = output {
|
||||
|
|
|
|||
|
|
@ -5,6 +5,7 @@ mod backend;
|
|||
mod input;
|
||||
mod protocols;
|
||||
mod state;
|
||||
mod windows;
|
||||
|
||||
fn main() -> anyhow::Result<()> {
|
||||
tracing_subscriber::fmt()
|
||||
|
|
|
|||
|
|
@ -33,6 +33,8 @@ pub struct WeftShellWindowData {
|
|||
pub role: String,
|
||||
pub surface: Option<wayland_server::protocol::wl_surface::WlSurface>,
|
||||
pub closed: std::sync::atomic::AtomicBool,
|
||||
/// The edge strip a panel reserved with set_exclusive_zone.
|
||||
pub exclusive_zone: std::sync::Mutex<Option<(server::zweft_shell_window_v1::Edge, i32)>>,
|
||||
}
|
||||
|
||||
impl WeftShellState {
|
||||
|
|
@ -41,7 +43,7 @@ impl WeftShellState {
|
|||
D: GlobalDispatch<ZweftShellManagerV1, ()>,
|
||||
D: 'static,
|
||||
{
|
||||
let global = display.create_global::<D, ZweftShellManagerV1, ()>(2, ());
|
||||
let global = display.create_global::<D, ZweftShellManagerV1, ()>(3, ());
|
||||
Self {
|
||||
_global: global,
|
||||
panels: Vec::new(),
|
||||
|
|
@ -52,6 +54,13 @@ impl WeftShellState {
|
|||
self.panels.push(window);
|
||||
}
|
||||
|
||||
/// Forgets a panel; returns whether it was one.
|
||||
pub fn remove_panel(&mut self, window: &ZweftShellWindowV1) -> bool {
|
||||
let before = self.panels.len();
|
||||
self.panels.retain(|panel| panel != window);
|
||||
self.panels.len() != before
|
||||
}
|
||||
|
||||
pub fn reconfigure_panels(&self, x: i32, y: i32, width: i32, height: i32) {
|
||||
for panel in &self.panels {
|
||||
if panel.is_alive() {
|
||||
|
|
@ -97,6 +106,7 @@ mod tests {
|
|||
role: "normal".into(),
|
||||
surface: None,
|
||||
closed: std::sync::atomic::AtomicBool::new(false),
|
||||
exclusive_zone: std::sync::Mutex::new(None),
|
||||
};
|
||||
assert_eq!(d.app_id, "com.example.test");
|
||||
assert_eq!(d.title, "Test Window");
|
||||
|
|
@ -112,6 +122,7 @@ mod tests {
|
|||
role: String::new(),
|
||||
surface: None,
|
||||
closed: std::sync::atomic::AtomicBool::new(false),
|
||||
exclusive_zone: std::sync::Mutex::new(None),
|
||||
};
|
||||
assert!(!d.closed.load(Ordering::Relaxed));
|
||||
d.closed.store(true, Ordering::Relaxed);
|
||||
|
|
@ -122,14 +133,14 @@ mod tests {
|
|||
fn manager_interface_name_and_version() {
|
||||
let iface = ZweftShellManagerV1::interface();
|
||||
assert_eq!(iface.name, "zweft_shell_manager_v1");
|
||||
assert_eq!(iface.version, 2);
|
||||
assert_eq!(iface.version, 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn window_interface_name_and_version() {
|
||||
let iface = ZweftShellWindowV1::interface();
|
||||
assert_eq!(iface.name, "zweft_shell_window_v1");
|
||||
assert_eq!(iface.version, 2);
|
||||
assert_eq!(iface.version, 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
|
|
|||
|
|
@ -53,11 +53,35 @@ 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<SessionBinding>,
|
||||
}
|
||||
|
||||
/// 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<(u64, ClientId)>,
|
||||
}
|
||||
|
||||
/// 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 {
|
||||
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, client_id));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Accumulated state for a multi-touch swipe gesture in progress.
|
||||
|
|
@ -74,6 +98,12 @@ pub struct WeftCompositorState {
|
|||
pub loop_signal: LoopSignal,
|
||||
pub loop_handle: LoopHandle<'static, WeftCompositorState>,
|
||||
pub gesture_state: GestureState,
|
||||
/// Keycodes whose press a compositor shortcut took, so their release is
|
||||
/// taken as well and no client sees half of a key.
|
||||
pub suppressed_keys: Vec<u32>,
|
||||
/// The Super key held down while no other key was pressed since; its
|
||||
/// release is a tap that opens the shell.
|
||||
pub super_tap: Option<u32>,
|
||||
|
||||
pub compositor_state: CompositorState,
|
||||
pub xdg_shell_state: XdgShellState,
|
||||
|
|
@ -124,7 +154,10 @@ impl WeftCompositorState {
|
|||
) -> Self {
|
||||
let compositor_state = CompositorState::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 dmabuf_state = DmabufState::new();
|
||||
let output_manager_state = OutputManagerState::new_with_xdg_output::<Self>(&display_handle);
|
||||
|
|
@ -132,7 +165,7 @@ impl WeftCompositorState {
|
|||
let presentation_state = PresentationState::new::<Self>(&display_handle, 1);
|
||||
let text_input_state = TextInputManagerState::new::<Self>(&display_handle);
|
||||
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 cursor_shape_state = CursorShapeManagerState::new::<Self>(&display_handle);
|
||||
let weft_shell_state = WeftShellState::new::<Self>(&display_handle);
|
||||
|
|
@ -169,6 +202,8 @@ impl WeftCompositorState {
|
|||
dmabuf_global: None,
|
||||
running: true,
|
||||
gesture_state: GestureState::default(),
|
||||
suppressed_keys: Vec::new(),
|
||||
super_tap: None,
|
||||
#[cfg(unix)]
|
||||
appd_ipc: None,
|
||||
#[cfg(target_os = "linux")]
|
||||
|
|
@ -239,10 +274,22 @@ impl XdgShellHandler for WeftCompositorState {
|
|||
&mut self.xdg_shell_state
|
||||
}
|
||||
|
||||
fn toplevel_destroyed(&mut self, surface: ToplevelSurface) {
|
||||
self.window_closed(surface.wl_surface());
|
||||
}
|
||||
|
||||
fn new_toplevel(&mut self, surface: ToplevelSurface) {
|
||||
surface.send_configure();
|
||||
let session = surface.wl_surface().client().and_then(|client| {
|
||||
client
|
||||
.get_data::<WeftClientState>()
|
||||
.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);
|
||||
self.map_new_window(window);
|
||||
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 +513,7 @@ impl GlobalDispatch<ZweftShellManagerV1, ()> for WeftCompositorState {
|
|||
impl Dispatch<ZweftShellManagerV1, ()> for WeftCompositorState {
|
||||
fn request(
|
||||
state: &mut Self,
|
||||
_client: &Client,
|
||||
client: &Client,
|
||||
_resource: &ZweftShellManagerV1,
|
||||
request: zweft_shell_manager_v1::Request,
|
||||
_data: &(),
|
||||
|
|
@ -486,6 +533,14 @@ impl Dispatch<ZweftShellManagerV1, ()> 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::<WeftClientState>()
|
||||
.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,
|
||||
|
|
@ -495,8 +550,21 @@ impl Dispatch<ZweftShellManagerV1, ()> for WeftCompositorState {
|
|||
role,
|
||||
surface,
|
||||
closed: std::sync::atomic::AtomicBool::new(false),
|
||||
exclusive_zone: std::sync::Mutex::new(None),
|
||||
},
|
||||
);
|
||||
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
|
||||
|
|
@ -515,8 +583,13 @@ impl Dispatch<ZweftShellManagerV1, ()> for WeftCompositorState {
|
|||
),
|
||||
);
|
||||
state.weft_shell_state.add_panel(window);
|
||||
state.fit_panels();
|
||||
} else {
|
||||
window.configure(x, y, width, height, 0);
|
||||
// The compositor decides application geometry: the work
|
||||
// area, whatever was requested.
|
||||
let _ = (x, y, width, height);
|
||||
let (x, y, w, h) = state.app_geometry();
|
||||
window.configure(x, y, w, h, 0);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -525,7 +598,7 @@ impl Dispatch<ZweftShellManagerV1, ()> for WeftCompositorState {
|
|||
|
||||
impl Dispatch<ZweftShellWindowV1, WeftShellWindowData> for WeftCompositorState {
|
||||
fn request(
|
||||
_state: &mut Self,
|
||||
state: &mut Self,
|
||||
_client: &Client,
|
||||
resource: &ZweftShellWindowV1,
|
||||
request: zweft_shell_window_v1::Request,
|
||||
|
|
@ -545,14 +618,64 @@ impl Dispatch<ZweftShellWindowV1, WeftShellWindowData> for WeftCompositorState {
|
|||
zweft_shell_window_v1::Request::UpdateMetadata { title, role } => {
|
||||
let _ = (title, role);
|
||||
}
|
||||
zweft_shell_window_v1::Request::SetGeometry {
|
||||
x,
|
||||
y,
|
||||
width,
|
||||
height,
|
||||
} => {
|
||||
resource.configure(x, y, width, height, 0);
|
||||
zweft_shell_window_v1::Request::SetGeometry { .. } => {
|
||||
// The request is advisory: the configure reports the
|
||||
// geometry the compositor's layout gives the window.
|
||||
let is_panel = state
|
||||
.weft_shell_state
|
||||
.panels()
|
||||
.any(|panel| panel == resource);
|
||||
let (x, y, w, h) = if is_panel {
|
||||
state.output_geometry()
|
||||
} else {
|
||||
state.app_geometry()
|
||||
};
|
||||
let flags = if is_panel {
|
||||
u32::from(crate::protocols::server::zweft_shell_window_v1::State::Maximized)
|
||||
} else {
|
||||
0
|
||||
};
|
||||
resource.configure(x, y, w, h, flags);
|
||||
}
|
||||
zweft_shell_window_v1::Request::SetExclusiveZone { edge, size } => {
|
||||
let is_panel = state
|
||||
.weft_shell_state
|
||||
.panels()
|
||||
.any(|panel| panel == resource);
|
||||
let edge = edge.into_result().ok();
|
||||
match edge {
|
||||
Some(edge) if is_panel && size >= 0 => {
|
||||
let zone = (size > 0).then_some((edge, size));
|
||||
*data
|
||||
.exclusive_zone
|
||||
.lock()
|
||||
.unwrap_or_else(|p| p.into_inner()) = zone;
|
||||
state.layout_app_windows();
|
||||
}
|
||||
_ => resource.post_error(
|
||||
crate::protocols::server::zweft_shell_window_v1::Error::InvalidExclusiveZone,
|
||||
"only a panel may reserve an edge, with a size of at least 0",
|
||||
),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn destroyed(
|
||||
state: &mut Self,
|
||||
_client: wayland_server::backend::ClientId,
|
||||
resource: &ZweftShellWindowV1,
|
||||
data: &WeftShellWindowData,
|
||||
) {
|
||||
// A panel that goes away, by destroy or with its client, releases
|
||||
// its reserved strip and its window slot; applications take the
|
||||
// space back. The surface's window is not mapped again if it
|
||||
// registers once more.
|
||||
if state.weft_shell_state.remove_panel(resource) {
|
||||
if let Some(surface) = &data.surface {
|
||||
state.window_closed(surface);
|
||||
}
|
||||
state.layout_app_windows();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
362
crates/weft-compositor/src/windows.rs
Normal file
362
crates/weft-compositor/src/windows.rs
Normal file
|
|
@ -0,0 +1,362 @@
|
|||
//! Stacking, focus and activation of toplevel windows.
|
||||
//!
|
||||
//! The compositor decides the order and the geometry. The trusted shell's
|
||||
//! panel fills the output and starts beneath every application window;
|
||||
//! application windows fill the work area, the output less the strips the
|
||||
//! panel reserves. A session's first window, a clicked window (the panel
|
||||
//! included, which then shows the shell's home over the applications), one
|
||||
//! appd asks to activate and the panel when a Super key is tapped are
|
||||
//! raised to the top, marked activated and given keyboard focus; apart
|
||||
//! from a panel being lowered when it registers, nothing else changes the
|
||||
//! order, and a window that maps without taking focus goes beneath the
|
||||
//! window in front. When the focused window closes, the topmost remaining
|
||||
//! application window gets focus.
|
||||
|
||||
use smithay::desktop::Window;
|
||||
use smithay::reexports::wayland_protocols::xdg::shell::server::xdg_toplevel;
|
||||
use smithay::reexports::wayland_server::Resource;
|
||||
use smithay::reexports::wayland_server::protocol::wl_surface::WlSurface;
|
||||
use smithay::utils::{Logical, Rectangle, SERIAL_COUNTER};
|
||||
use smithay::wayland::seat::WaylandFocus;
|
||||
|
||||
use crate::protocols::WeftShellWindowData;
|
||||
use crate::state::{WeftClientState, WeftCompositorState};
|
||||
|
||||
impl WeftCompositorState {
|
||||
/// Whether `surface` backs a window the trusted shell registered as its
|
||||
/// panel.
|
||||
pub fn is_panel_surface(&self, surface: &WlSurface) -> bool {
|
||||
self.weft_shell_state
|
||||
.panels()
|
||||
.filter(|p| p.is_alive())
|
||||
.any(|panel| {
|
||||
panel
|
||||
.data::<WeftShellWindowData>()
|
||||
.and_then(|data| data.surface.as_ref())
|
||||
.is_some_and(|s| s == surface)
|
||||
})
|
||||
}
|
||||
|
||||
fn is_panel(&self, window: &Window) -> bool {
|
||||
window
|
||||
.wl_surface()
|
||||
.is_some_and(|surface| self.is_panel_surface(&surface))
|
||||
}
|
||||
|
||||
/// Raises `window` to the top, marks it activated and gives it keyboard
|
||||
/// focus. Activating the panel shows the shell's home, with its launcher,
|
||||
/// over the applications until one is activated again.
|
||||
pub fn activate_window(&mut self, window: &Window) {
|
||||
self.space.raise_element(window, true);
|
||||
self.send_pending_configures();
|
||||
if let (Some(keyboard), Some(surface)) = (self.seat.get_keyboard(), window.wl_surface()) {
|
||||
keyboard.set_focus(
|
||||
self,
|
||||
Some(surface.into_owned()),
|
||||
SERIAL_COUNTER.next_serial(),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Activates the shell's panel; returns whether one is registered. With
|
||||
/// several, the first registered is the shell's.
|
||||
pub fn activate_panel(&mut self) -> bool {
|
||||
let panel = self
|
||||
.weft_shell_state
|
||||
.panels()
|
||||
.filter(|p| p.is_alive())
|
||||
.find_map(|panel| {
|
||||
let surface = panel
|
||||
.data::<WeftShellWindowData>()
|
||||
.and_then(|data| data.surface.clone())?;
|
||||
self.space
|
||||
.elements()
|
||||
.find(|window| window.wl_surface().is_some_and(|s| *s == surface))
|
||||
.cloned()
|
||||
});
|
||||
match panel {
|
||||
Some(panel) => {
|
||||
self.activate_window(&panel);
|
||||
true
|
||||
}
|
||||
None => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Asks the focused application window to close. Its client decides
|
||||
/// how to end; for an app shell that ends the session. The panel is not
|
||||
/// closed this way.
|
||||
pub fn close_focused_window(&mut self) {
|
||||
let Some(focus) = self
|
||||
.seat
|
||||
.get_keyboard()
|
||||
.and_then(|keyboard| keyboard.current_focus())
|
||||
else {
|
||||
return;
|
||||
};
|
||||
if self.is_panel_surface(&focus) {
|
||||
return;
|
||||
}
|
||||
let window = self
|
||||
.space
|
||||
.elements()
|
||||
.find(|window| window.wl_surface().is_some_and(|s| *s == focus))
|
||||
.cloned();
|
||||
if let Some(toplevel) = window.as_ref().and_then(|w| w.toplevel()) {
|
||||
tracing::info!(session = ?window.as_ref().and_then(window_session), "closing the focused window");
|
||||
toplevel.send_close();
|
||||
}
|
||||
}
|
||||
|
||||
/// Asks every window of `session_id` to close; returns how many.
|
||||
pub fn close_session_windows(&mut self, session_id: u64) -> usize {
|
||||
let mut closed = 0;
|
||||
for window in self.space.elements() {
|
||||
if window_session(window) == Some(session_id)
|
||||
&& let Some(toplevel) = window.toplevel()
|
||||
{
|
||||
toplevel.send_close();
|
||||
closed += 1;
|
||||
}
|
||||
}
|
||||
closed
|
||||
}
|
||||
|
||||
/// Activates the topmost window of `session_id`; returns whether the
|
||||
/// session has one.
|
||||
pub fn activate_session(&mut self, session_id: u64) -> bool {
|
||||
let window = self
|
||||
.space
|
||||
.elements()
|
||||
.rev()
|
||||
.find(|window| window_session(window) == Some(session_id))
|
||||
.cloned();
|
||||
match window {
|
||||
Some(window) => {
|
||||
self.activate_window(&window);
|
||||
true
|
||||
}
|
||||
None => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Sizes the panels to the output and keeps them beneath every
|
||||
/// application window; used when a panel registers.
|
||||
pub fn fit_panels(&mut self) {
|
||||
self.place_windows(true, None);
|
||||
// A shell that took focus before registering as the panel, such as
|
||||
// one restarted while applications run, hands it to the window that
|
||||
// is now in front.
|
||||
let focus_on_panel = self
|
||||
.seat
|
||||
.get_keyboard()
|
||||
.and_then(|keyboard| keyboard.current_focus())
|
||||
.is_some_and(|focus| self.is_panel_surface(&focus));
|
||||
let front = self.space.elements().last().cloned();
|
||||
if focus_on_panel
|
||||
&& let Some(front) = front
|
||||
&& !self.is_panel(&front)
|
||||
{
|
||||
self.activate_window(&front);
|
||||
}
|
||||
}
|
||||
|
||||
/// Places every window for the current output and reservations: panels
|
||||
/// fill the output, application windows the work area. The stacking
|
||||
/// order is kept, except that `lower_panels` moves the panels beneath
|
||||
/// the applications, and `below_top` slips that window under the
|
||||
/// window that was on top.
|
||||
pub fn place_windows(&mut self, lower_panels: bool, below_top: Option<&Window>) {
|
||||
// Without an output the order still changes; windows keep their
|
||||
// size and place until one is mapped.
|
||||
let output = self
|
||||
.space
|
||||
.outputs()
|
||||
.next()
|
||||
.and_then(|output| self.space.output_geometry(output));
|
||||
let area = self.work_area();
|
||||
let mut order: Vec<Window> = self.space.elements().cloned().collect();
|
||||
if lower_panels {
|
||||
let (panels, apps): (Vec<Window>, Vec<Window>) =
|
||||
order.into_iter().partition(|window| self.is_panel(window));
|
||||
order = panels.into_iter().chain(apps).collect();
|
||||
}
|
||||
if let Some(window) = below_top
|
||||
&& let Some(position) = order.iter().position(|w| w == window)
|
||||
&& position + 1 == order.len()
|
||||
&& order.len() > 1
|
||||
{
|
||||
order.swap(position, position - 1);
|
||||
}
|
||||
for window in &order {
|
||||
let panel = self.is_panel(window);
|
||||
let Some(geometry) = (if panel { output } else { area }) else {
|
||||
let location = self.space.element_location(window).unwrap_or_default();
|
||||
self.space.map_element(window.clone(), location, false);
|
||||
continue;
|
||||
};
|
||||
if let Some(toplevel) = window.toplevel() {
|
||||
toplevel.with_pending_state(|state| {
|
||||
state.size = Some(geometry.size);
|
||||
state.states.set(xdg_toplevel::State::Maximized);
|
||||
});
|
||||
toplevel.send_pending_configure();
|
||||
}
|
||||
// Mapping puts a window on top; mapping all of them in `order`
|
||||
// leaves exactly that order.
|
||||
self.space.map_element(window.clone(), geometry.loc, false);
|
||||
}
|
||||
}
|
||||
|
||||
/// Maps a new toplevel. The first window a session maps in its lifetime
|
||||
/// comes to the front with keyboard focus; its later windows, including
|
||||
/// recreated ones, are shown without taking focus, so a session cannot
|
||||
/// take keystrokes meant for another application by creating windows.
|
||||
/// A client outside any session (one connected through the display
|
||||
/// socket) takes focus only while no other such window is mapped. A
|
||||
/// panel is fitted and kept beneath.
|
||||
pub fn map_new_window(&mut self, window: Window) {
|
||||
let session = window_session(&window);
|
||||
let first = match session {
|
||||
Some(session_id) => self
|
||||
.appd_ipc
|
||||
.as_mut()
|
||||
.is_some_and(|ipc| ipc.take_focus_on_map(session_id)),
|
||||
None => !self
|
||||
.space
|
||||
.elements()
|
||||
.any(|other| window_session(other).is_none()),
|
||||
};
|
||||
self.space.map_element(window.clone(), (0, 0), false);
|
||||
if self.is_panel(&window) {
|
||||
self.fit_panels();
|
||||
} else if first {
|
||||
self.layout_app_windows();
|
||||
self.activate_window(&window);
|
||||
} else {
|
||||
// A window that does not take focus does not cover the window
|
||||
// in front either, the shell's home included.
|
||||
self.place_windows(false, Some(&window));
|
||||
}
|
||||
}
|
||||
|
||||
/// Unmaps a closed toplevel and, if it had keyboard focus, gives focus
|
||||
/// to the topmost remaining application window, or the panel.
|
||||
pub fn window_closed(&mut self, surface: &WlSurface) {
|
||||
let Some(window) = self
|
||||
.space
|
||||
.elements()
|
||||
.find(|window| window.wl_surface().is_some_and(|s| *s == *surface))
|
||||
.cloned()
|
||||
else {
|
||||
return;
|
||||
};
|
||||
self.space.unmap_elem(&window);
|
||||
let had_focus = self
|
||||
.seat
|
||||
.get_keyboard()
|
||||
.and_then(|keyboard| keyboard.current_focus())
|
||||
.is_none_or(|focus| focus == *surface);
|
||||
if !had_focus {
|
||||
return;
|
||||
}
|
||||
let next = self
|
||||
.space
|
||||
.elements()
|
||||
.rev()
|
||||
.find(|window| !self.is_panel(window))
|
||||
.or_else(|| self.space.elements().next())
|
||||
.cloned();
|
||||
match next {
|
||||
Some(next) => self.activate_window(&next),
|
||||
None => {
|
||||
if let Some(keyboard) = self.seat.get_keyboard() {
|
||||
keyboard.set_focus(self, None, SERIAL_COUNTER.next_serial());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The part of the output that application windows occupy: the output
|
||||
/// less the strips the panels reserved.
|
||||
pub fn work_area(&self) -> Option<Rectangle<i32, Logical>> {
|
||||
use crate::protocols::server::zweft_shell_window_v1::Edge;
|
||||
let output = self.space.outputs().next()?;
|
||||
let mut area = self.space.output_geometry(output)?;
|
||||
for panel in self.weft_shell_state.panels().filter(|p| p.is_alive()) {
|
||||
let Some(data) = panel.data::<WeftShellWindowData>() else {
|
||||
continue;
|
||||
};
|
||||
let zone = *data
|
||||
.exclusive_zone
|
||||
.lock()
|
||||
.unwrap_or_else(|p| p.into_inner());
|
||||
let Some((edge, size)) = zone else {
|
||||
continue;
|
||||
};
|
||||
match edge {
|
||||
Edge::Top => {
|
||||
let size = size.min(area.size.h);
|
||||
area.loc.y += size;
|
||||
area.size.h -= size;
|
||||
}
|
||||
Edge::Bottom => area.size.h -= size.min(area.size.h),
|
||||
Edge::Left => {
|
||||
let size = size.min(area.size.w);
|
||||
area.loc.x += size;
|
||||
area.size.w -= size;
|
||||
}
|
||||
Edge::Right => area.size.w -= size.min(area.size.w),
|
||||
}
|
||||
}
|
||||
// A zone covering the output still leaves applications a size the
|
||||
// client must honour, never 0, which would let it pick its own.
|
||||
area.size.w = area.size.w.max(1);
|
||||
area.size.h = area.size.h.max(1);
|
||||
Some(area)
|
||||
}
|
||||
|
||||
/// The output's geometry as (x, y, width, height).
|
||||
pub fn output_geometry(&self) -> (i32, i32, i32, i32) {
|
||||
self.space
|
||||
.outputs()
|
||||
.next()
|
||||
.and_then(|output| self.space.output_geometry(output))
|
||||
.map_or((0, 0, 0, 0), |g| (g.loc.x, g.loc.y, g.size.w, g.size.h))
|
||||
}
|
||||
|
||||
/// The geometry the layout gives application windows, as
|
||||
/// (x, y, width, height).
|
||||
pub fn app_geometry(&self) -> (i32, i32, i32, i32) {
|
||||
self.work_area()
|
||||
.map_or((0, 0, 0, 0), |a| (a.loc.x, a.loc.y, a.size.w, a.size.h))
|
||||
}
|
||||
|
||||
/// Lays the windows out again after the work area changed, keeping the
|
||||
/// stacking order.
|
||||
pub fn layout_app_windows(&mut self) {
|
||||
self.place_windows(false, None);
|
||||
}
|
||||
|
||||
/// Sends the configure for every toplevel whose pending state changed,
|
||||
/// such as its activated state.
|
||||
fn send_pending_configures(&self) {
|
||||
for window in self.space.elements() {
|
||||
if let Some(toplevel) = window.toplevel() {
|
||||
toplevel.send_pending_configure();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The appd session `window`'s client is bound to, if any.
|
||||
pub fn window_session(window: &Window) -> Option<u64> {
|
||||
window
|
||||
.toplevel()?
|
||||
.wl_surface()
|
||||
.client()?
|
||||
.get_data::<WeftClientState>()?
|
||||
.session
|
||||
.as_ref()
|
||||
.map(|binding| binding.session_id)
|
||||
}
|
||||
|
|
@ -13,3 +13,6 @@ anyhow = "1.0"
|
|||
serde = { version = "1", features = ["derive"] }
|
||||
serde_json = "1"
|
||||
base64 = "0.22"
|
||||
|
||||
[target.'cfg(target_os = "linux")'.dependencies]
|
||||
rustix = { version = "1", features = ["fs"] }
|
||||
|
|
|
|||
|
|
@ -1,17 +1,37 @@
|
|||
#[cfg(unix)]
|
||||
use std::io::{BufRead, BufReader, Write};
|
||||
use std::path::{Path, PathBuf};
|
||||
//! A per-session file proxy for the directories a session is granted.
|
||||
//!
|
||||
//! Requests name absolute host paths inside a granted directory. Each
|
||||
//! granted directory is opened once at startup, and every operation resolves
|
||||
//! the rest of the path relative to that descriptor with `openat2` and
|
||||
//! `RESOLVE_BENEATH`, so the kernel keeps it inside the directory while it
|
||||
//! runs: `..`, absolute symbolic links, links that point outside and links
|
||||
//! replaced during the operation cannot leave it. Paths must name their
|
||||
//! location directly, without `.` or `..` components. Writes replace a file
|
||||
//! atomically and never create directories.
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
use std::io::{BufRead, BufReader, Read, Write};
|
||||
use std::path::{Component, Path, PathBuf};
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[cfg(unix)]
|
||||
use std::sync::Arc;
|
||||
|
||||
#[cfg(unix)]
|
||||
use anyhow::Context;
|
||||
|
||||
#[cfg(unix)]
|
||||
use std::os::unix::net::{UnixListener, UnixStream};
|
||||
/// The largest file read or written, in bytes.
|
||||
const MAX_FILE: usize = 16 * 1024 * 1024;
|
||||
/// The longest request line: a write of the largest file, base64-encoded,
|
||||
/// with room for its path.
|
||||
#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
|
||||
const MAX_LINE: usize = MAX_FILE / 3 * 4 + 64 * 1024;
|
||||
/// The most entries one listing returns.
|
||||
const MAX_ENTRIES: usize = 10_000;
|
||||
/// The most connections served at once.
|
||||
#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
|
||||
const MAX_CONNECTIONS: usize = 4;
|
||||
/// How long a connection may stay silent before it is closed.
|
||||
#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
|
||||
const IDLE_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(60);
|
||||
/// The prefix of the temporary files writes create, never listed.
|
||||
#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
|
||||
const TEMPORARY_PREFIX: &str = ".weft-portal-";
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(tag = "op", rename_all = "snake_case")]
|
||||
|
|
@ -38,8 +58,13 @@ impl Response {
|
|||
}
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[cfg(target_os = "linux")]
|
||||
fn main() -> anyhow::Result<()> {
|
||||
use anyhow::Context;
|
||||
use std::os::unix::net::UnixListener;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
|
||||
let args: Vec<String> = std::env::args().collect();
|
||||
if args.len() < 2 {
|
||||
eprintln!(
|
||||
|
|
@ -49,32 +74,59 @@ fn main() -> anyhow::Result<()> {
|
|||
}
|
||||
|
||||
let socket_path = &args[1];
|
||||
let allowed = Arc::new(parse_allowed(&args[2..]));
|
||||
let mut roots = Vec::new();
|
||||
for grant in parse_allowed(&args[2..]) {
|
||||
match Root::open(grant) {
|
||||
Ok(root) => roots.push(root),
|
||||
Err((path, e)) => eprintln!("cannot open granted directory {}: {e}", path.display()),
|
||||
}
|
||||
}
|
||||
let roots = Arc::new(roots);
|
||||
|
||||
if Path::new(socket_path).exists() {
|
||||
std::fs::remove_file(socket_path)
|
||||
.with_context(|| format!("remove stale socket {socket_path}"))?;
|
||||
}
|
||||
|
||||
let listener =
|
||||
UnixListener::bind(socket_path).with_context(|| format!("bind {socket_path}"))?;
|
||||
|
||||
let active = Arc::new(AtomicUsize::new(0));
|
||||
for stream in listener.incoming() {
|
||||
match stream {
|
||||
Ok(s) => {
|
||||
let allowed = Arc::clone(&allowed);
|
||||
std::thread::spawn(move || handle_connection(s, &allowed));
|
||||
let mut stream = match stream {
|
||||
Ok(s) => s,
|
||||
Err(e) => {
|
||||
eprintln!("accept error: {e}");
|
||||
continue;
|
||||
}
|
||||
Err(e) => eprintln!("accept error: {e}"),
|
||||
};
|
||||
if active.fetch_add(1, Ordering::SeqCst) >= MAX_CONNECTIONS {
|
||||
active.fetch_sub(1, Ordering::SeqCst);
|
||||
let _ = stream.write_all(b"{\"error\":\"too many connections\"}\n");
|
||||
continue;
|
||||
}
|
||||
// The slot is released however the connection ends, a panic
|
||||
// included.
|
||||
struct Slot(Arc<AtomicUsize>);
|
||||
impl Drop for Slot {
|
||||
fn drop(&mut self) {
|
||||
self.0.fetch_sub(1, Ordering::SeqCst);
|
||||
}
|
||||
}
|
||||
let slot = Slot(Arc::clone(&active));
|
||||
let roots = Arc::clone(&roots);
|
||||
if let Err(e) = std::thread::Builder::new().spawn(move || {
|
||||
let _slot = slot;
|
||||
handle_connection(stream, &roots);
|
||||
}) {
|
||||
eprintln!("cannot serve a connection: {e}");
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(not(unix))]
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
fn main() -> anyhow::Result<()> {
|
||||
anyhow::bail!("weft-file-portal requires a Unix platform")
|
||||
anyhow::bail!("weft-file-portal requires Linux")
|
||||
}
|
||||
|
||||
/// A directory the session may use: `--allow` grants reading and writing,
|
||||
|
|
@ -85,7 +137,6 @@ struct Allowed {
|
|||
writable: bool,
|
||||
}
|
||||
|
||||
#[cfg_attr(not(any(unix, test)), allow(dead_code))]
|
||||
fn parse_allowed(args: &[String]) -> Vec<Allowed> {
|
||||
let mut allowed = Vec::new();
|
||||
let mut i = 0;
|
||||
|
|
@ -109,33 +160,105 @@ fn parse_allowed(args: &[String]) -> Vec<Allowed> {
|
|||
allowed
|
||||
}
|
||||
|
||||
#[cfg_attr(not(any(unix, test)), allow(dead_code))]
|
||||
fn normalize_path(path: &Path) -> PathBuf {
|
||||
use std::path::Component;
|
||||
let mut out = PathBuf::new();
|
||||
for c in path.components() {
|
||||
match c {
|
||||
Component::ParentDir => {
|
||||
out.pop();
|
||||
}
|
||||
Component::CurDir => {}
|
||||
other => out.push(other),
|
||||
/// The part of `path` inside the granted directory `root`, if `path` lies
|
||||
/// in it and names its location directly: an absolute path of plain
|
||||
/// components only, without `.`, `..`, empty components or a trailing `/`.
|
||||
/// The text is checked as given, since path parsing drops `.` and repeated
|
||||
/// separators.
|
||||
fn relative_to<'a>(path: &'a Path, root: &Path) -> Option<&'a Path> {
|
||||
let text = path.to_str()?;
|
||||
let direct = text.starts_with('/')
|
||||
&& text[1..]
|
||||
.split('/')
|
||||
.all(|segment| !matches!(segment, "" | "." | ".."));
|
||||
if !direct {
|
||||
return None;
|
||||
}
|
||||
let rest = path.strip_prefix(root).ok()?;
|
||||
rest.components()
|
||||
.all(|c| matches!(c, Component::Normal(_)))
|
||||
.then_some(rest)
|
||||
}
|
||||
|
||||
/// A granted directory, held open for the life of the portal.
|
||||
#[cfg(target_os = "linux")]
|
||||
struct Root {
|
||||
path: PathBuf,
|
||||
dir: rustix::fd::OwnedFd,
|
||||
writable: bool,
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
impl Root {
|
||||
fn open(grant: Allowed) -> Result<Self, (PathBuf, std::io::Error)> {
|
||||
use rustix::fs::{Mode, OFlags};
|
||||
match rustix::fs::open(
|
||||
&grant.root,
|
||||
OFlags::RDONLY | OFlags::DIRECTORY | OFlags::CLOEXEC,
|
||||
Mode::empty(),
|
||||
) {
|
||||
Ok(dir) => Ok(Self {
|
||||
path: grant.root,
|
||||
dir,
|
||||
writable: grant.writable,
|
||||
}),
|
||||
Err(e) => Err((grant.root, e.into())),
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Whether `path` lies in an allowed directory, and for a write, in one
|
||||
/// granted read-write.
|
||||
fn is_allowed(path: &Path, allowed: &[Allowed], write: bool) -> bool {
|
||||
let norm = normalize_path(path);
|
||||
allowed
|
||||
/// The granted directory holding `path` and the path inside it, for an
|
||||
/// operation that writes when `write` is set.
|
||||
#[cfg(target_os = "linux")]
|
||||
fn locate<'a, 'p>(
|
||||
roots: &'a [Root],
|
||||
path: &'p str,
|
||||
write: bool,
|
||||
) -> Result<(&'a Root, &'p Path), Response> {
|
||||
let requested = Path::new(path);
|
||||
roots
|
||||
.iter()
|
||||
.any(|a| norm.starts_with(&a.root) && (a.writable || !write))
|
||||
.filter(|root| root.writable || !write)
|
||||
.find_map(|root| relative_to(requested, &root.path).map(|rest| (root, rest)))
|
||||
.ok_or_else(|| Response::err(format!("access denied: {path}")))
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
fn handle_connection(stream: UnixStream, allowed: &[Allowed]) {
|
||||
/// Opens `rest` inside `root`, never leaving it.
|
||||
#[cfg(target_os = "linux")]
|
||||
fn open_beneath(
|
||||
root: &Root,
|
||||
rest: &Path,
|
||||
flags: rustix::fs::OFlags,
|
||||
) -> std::io::Result<rustix::fd::OwnedFd> {
|
||||
use rustix::fs::{Mode, OFlags, ResolveFlags};
|
||||
let rest = if rest.as_os_str().is_empty() {
|
||||
Path::new(".")
|
||||
} else {
|
||||
rest
|
||||
};
|
||||
rustix::fs::openat2(
|
||||
&root.dir,
|
||||
rest,
|
||||
flags | OFlags::CLOEXEC | OFlags::NOCTTY,
|
||||
Mode::empty(),
|
||||
ResolveFlags::BENEATH | ResolveFlags::NO_MAGICLINKS,
|
||||
)
|
||||
.map_err(|e| {
|
||||
// The kernel reports a resolution that would leave the directory as
|
||||
// EXDEV.
|
||||
if e == rustix::io::Errno::XDEV {
|
||||
std::io::Error::new(
|
||||
std::io::ErrorKind::PermissionDenied,
|
||||
"access denied: the path leads out of the granted directory",
|
||||
)
|
||||
} else {
|
||||
e.into()
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
fn handle_connection(stream: std::os::unix::net::UnixStream, roots: &[Root]) {
|
||||
let mut writer = match stream.try_clone() {
|
||||
Ok(s) => s,
|
||||
Err(e) => {
|
||||
|
|
@ -143,22 +266,33 @@ fn handle_connection(stream: UnixStream, allowed: &[Allowed]) {
|
|||
return;
|
||||
}
|
||||
};
|
||||
let reader = BufReader::new(stream);
|
||||
|
||||
for line in reader.lines() {
|
||||
let line = match line {
|
||||
Ok(l) => l,
|
||||
Err(_) => break,
|
||||
};
|
||||
if line.is_empty() {
|
||||
let _ = stream.set_read_timeout(Some(IDLE_TIMEOUT));
|
||||
let _ = stream.set_write_timeout(Some(IDLE_TIMEOUT));
|
||||
let mut reader = BufReader::new(stream);
|
||||
let mut line = Vec::new();
|
||||
loop {
|
||||
line.clear();
|
||||
match (&mut reader)
|
||||
.take(MAX_LINE as u64 + 3)
|
||||
.read_until(b'\n', &mut line)
|
||||
{
|
||||
Ok(0) | Err(_) => break,
|
||||
Ok(_) => {}
|
||||
}
|
||||
let content = line.strip_suffix(b"\n").unwrap_or(&line);
|
||||
if content.strip_suffix(b"\r").unwrap_or(content).len() > MAX_LINE {
|
||||
let _ = writer.write_all(b"{\"error\":\"request too long\"}\n");
|
||||
break;
|
||||
}
|
||||
let text = String::from_utf8_lossy(&line);
|
||||
let text = text.trim_end_matches(['\n', '\r']);
|
||||
if text.is_empty() {
|
||||
continue;
|
||||
}
|
||||
|
||||
let response = match serde_json::from_str::<Request>(&line) {
|
||||
Ok(req) => handle_request(req, allowed),
|
||||
let response = match serde_json::from_str::<Request>(text) {
|
||||
Ok(req) => handle_request(req, roots),
|
||||
Err(e) => Response::err(format!("bad request: {e}")),
|
||||
};
|
||||
|
||||
let mut out = serde_json::to_string(&response)
|
||||
.unwrap_or_else(|_| r#"{"error":"serialize"}"#.to_string());
|
||||
out.push('\n');
|
||||
|
|
@ -168,246 +302,453 @@ fn handle_connection(stream: UnixStream, allowed: &[Allowed]) {
|
|||
}
|
||||
}
|
||||
|
||||
#[cfg_attr(not(any(unix, test)), allow(dead_code))]
|
||||
fn handle_request(req: Request, allowed: &[Allowed]) -> Response {
|
||||
match req {
|
||||
#[cfg(target_os = "linux")]
|
||||
fn handle_request(req: Request, roots: &[Root]) -> Response {
|
||||
let result = match req {
|
||||
Request::Read { path } => {
|
||||
let p = PathBuf::from(&path);
|
||||
if !is_allowed(&p, allowed, false) {
|
||||
return Response::err(format!("access denied: {path}"));
|
||||
}
|
||||
match std::fs::read(&p) {
|
||||
Ok(data) => Response::OkData {
|
||||
data_b64: base64::Engine::encode(
|
||||
&base64::engine::general_purpose::STANDARD,
|
||||
&data,
|
||||
),
|
||||
},
|
||||
Err(e) => Response::err(e),
|
||||
}
|
||||
locate(roots, &path, false).and_then(|(root, rest)| read(root, rest))
|
||||
}
|
||||
Request::Write { path, data_b64 } => {
|
||||
let p = PathBuf::from(&path);
|
||||
if !is_allowed(&p, allowed, true) {
|
||||
return Response::err(format!("access denied: {path}"));
|
||||
}
|
||||
Request::Write { path, data_b64 } => locate(roots, &path, true).and_then(|(root, rest)| {
|
||||
let data =
|
||||
match base64::Engine::decode(&base64::engine::general_purpose::STANDARD, &data_b64)
|
||||
{
|
||||
Ok(d) => d,
|
||||
Err(e) => return Response::err(format!("bad base64: {e}")),
|
||||
};
|
||||
if let Some(Err(e)) = p.parent().map(std::fs::create_dir_all) {
|
||||
return Response::err(e);
|
||||
}
|
||||
match std::fs::write(&p, &data) {
|
||||
Ok(()) => Response::Ok,
|
||||
Err(e) => Response::err(e),
|
||||
}
|
||||
}
|
||||
base64::Engine::decode(&base64::engine::general_purpose::STANDARD, &data_b64)
|
||||
.map_err(|e| Response::err(format!("bad base64: {e}")))?;
|
||||
write(root, rest, &data)
|
||||
}),
|
||||
Request::List { path } => {
|
||||
let p = PathBuf::from(&path);
|
||||
if !is_allowed(&p, allowed, false) {
|
||||
return Response::err(format!("access denied: {path}"));
|
||||
}
|
||||
match std::fs::read_dir(&p) {
|
||||
Ok(entries) => {
|
||||
let mut names = Vec::new();
|
||||
for entry in entries.flatten() {
|
||||
if let Some(name) = entry.file_name().to_str() {
|
||||
names.push(name.to_string());
|
||||
}
|
||||
}
|
||||
names.sort();
|
||||
Response::OkEntries { entries: names }
|
||||
}
|
||||
Err(e) => Response::err(e),
|
||||
}
|
||||
locate(roots, &path, false).and_then(|(root, rest)| list(root, rest))
|
||||
}
|
||||
}
|
||||
};
|
||||
result.unwrap_or_else(|response| response)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[cfg(target_os = "linux")]
|
||||
fn read(root: &Root, rest: &Path) -> Result<Response, Response> {
|
||||
use rustix::fs::{FileType, OFlags};
|
||||
let fd = open_beneath(root, rest, OFlags::RDONLY | OFlags::NONBLOCK).map_err(Response::err)?;
|
||||
let stat = rustix::fs::fstat(&fd).map_err(Response::err)?;
|
||||
if FileType::from_raw_mode(stat.st_mode) != FileType::RegularFile {
|
||||
return Err(Response::err("not a regular file"));
|
||||
}
|
||||
let mut data = Vec::new();
|
||||
std::fs::File::from(fd)
|
||||
.take(MAX_FILE as u64 + 1)
|
||||
.read_to_end(&mut data)
|
||||
.map_err(Response::err)?;
|
||||
if data.len() > MAX_FILE {
|
||||
return Err(Response::err(format!("file larger than {MAX_FILE} bytes")));
|
||||
}
|
||||
Ok(Response::OkData {
|
||||
data_b64: base64::Engine::encode(&base64::engine::general_purpose::STANDARD, &data),
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
fn list(root: &Root, rest: &Path) -> Result<Response, Response> {
|
||||
use rustix::fs::OFlags;
|
||||
let fd = open_beneath(root, rest, OFlags::RDONLY | OFlags::DIRECTORY).map_err(Response::err)?;
|
||||
let mut entries = rustix::fs::Dir::read_from(&fd).map_err(Response::err)?;
|
||||
let mut names = Vec::new();
|
||||
while let Some(entry) = entries.read() {
|
||||
let entry = entry.map_err(Response::err)?;
|
||||
let Ok(name) = entry.file_name().to_str() else {
|
||||
continue;
|
||||
};
|
||||
if name == "." || name == ".." || name.starts_with(TEMPORARY_PREFIX) {
|
||||
continue;
|
||||
}
|
||||
if names.len() == MAX_ENTRIES {
|
||||
return Err(Response::err(format!("more than {MAX_ENTRIES} entries")));
|
||||
}
|
||||
names.push(name.to_owned());
|
||||
}
|
||||
names.sort();
|
||||
Ok(Response::OkEntries { entries: names })
|
||||
}
|
||||
|
||||
/// Replaces the file `rest` in `root` with `data`: the data is written to a
|
||||
/// new file in the same directory, flushed and renamed over the name, so
|
||||
/// the file holds either the old or the new content.
|
||||
#[cfg(target_os = "linux")]
|
||||
fn write(root: &Root, rest: &Path, data: &[u8]) -> Result<Response, Response> {
|
||||
use rustix::fs::{Mode, OFlags};
|
||||
if data.len() > MAX_FILE {
|
||||
return Err(Response::err(format!("file larger than {MAX_FILE} bytes")));
|
||||
}
|
||||
let name = rest
|
||||
.file_name()
|
||||
.ok_or_else(|| Response::err("a write needs a file name"))?;
|
||||
let parent = open_beneath(
|
||||
root,
|
||||
rest.parent().unwrap_or(Path::new("")),
|
||||
OFlags::RDONLY | OFlags::DIRECTORY,
|
||||
)
|
||||
.map_err(Response::err)?;
|
||||
static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
|
||||
// Unique within this portal by the counter, and across restarts by the
|
||||
// time of its first write, so a file left by an earlier instance does
|
||||
// not collide.
|
||||
static STARTED: std::sync::OnceLock<u128> = std::sync::OnceLock::new();
|
||||
let started = STARTED.get_or_init(|| {
|
||||
std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.map_or(0, |d| d.as_nanos())
|
||||
});
|
||||
let temporary = format!(
|
||||
"{TEMPORARY_PREFIX}{}-{started}-{}",
|
||||
std::process::id(),
|
||||
NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
|
||||
);
|
||||
// A replaced file keeps its permission bits; a new one is private.
|
||||
let mode = match rustix::fs::statat(&parent, name, rustix::fs::AtFlags::SYMLINK_NOFOLLOW) {
|
||||
Ok(stat)
|
||||
if rustix::fs::FileType::from_raw_mode(stat.st_mode)
|
||||
== rustix::fs::FileType::RegularFile =>
|
||||
{
|
||||
stat.st_mode & 0o777
|
||||
}
|
||||
_ => 0o600,
|
||||
};
|
||||
let file = rustix::fs::openat(
|
||||
&parent,
|
||||
temporary.as_str(),
|
||||
OFlags::WRONLY | OFlags::CREATE | OFlags::EXCL | OFlags::NOFOLLOW | OFlags::CLOEXEC,
|
||||
Mode::from_raw_mode(0o600),
|
||||
)
|
||||
.map_err(Response::err)?;
|
||||
let _ = rustix::fs::fchmod(&file, Mode::from_raw_mode(mode));
|
||||
let mut file = std::fs::File::from(file);
|
||||
let written = file
|
||||
.write_all(data)
|
||||
.and_then(|()| file.sync_all())
|
||||
.and_then(|()| {
|
||||
rustix::fs::renameat(&parent, temporary.as_str(), &parent, name)
|
||||
.map_err(std::io::Error::from)
|
||||
});
|
||||
if let Err(e) = written {
|
||||
let _ = rustix::fs::unlinkat(&parent, temporary.as_str(), rustix::fs::AtFlags::empty());
|
||||
return Err(Response::err(e));
|
||||
}
|
||||
let _ = rustix::fs::fsync(&parent);
|
||||
Ok(Response::Ok)
|
||||
}
|
||||
|
||||
#[cfg(all(test, target_os = "linux"))]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::fs;
|
||||
|
||||
fn rw(root: impl Into<PathBuf>) -> Allowed {
|
||||
Allowed {
|
||||
root: root.into(),
|
||||
writable: true,
|
||||
fn grant(root: &Path, writable: bool) -> Vec<Root> {
|
||||
vec![
|
||||
Root::open(Allowed {
|
||||
root: root.to_path_buf(),
|
||||
writable,
|
||||
})
|
||||
.unwrap(),
|
||||
]
|
||||
}
|
||||
|
||||
fn temp(name: &str) -> PathBuf {
|
||||
let dir = std::env::temp_dir().join(format!("wfp_{name}_{}", std::process::id()));
|
||||
let _ = fs::remove_dir_all(&dir);
|
||||
fs::create_dir_all(dir.join("granted")).unwrap();
|
||||
dir
|
||||
}
|
||||
|
||||
fn path(p: &Path) -> String {
|
||||
p.to_string_lossy().into_owned()
|
||||
}
|
||||
|
||||
fn denied(resp: &Response) -> bool {
|
||||
matches!(resp, Response::Err { .. })
|
||||
}
|
||||
|
||||
fn read_req(p: &Path) -> Request {
|
||||
Request::Read { path: path(p) }
|
||||
}
|
||||
|
||||
fn write_req(p: &Path, data: &[u8]) -> Request {
|
||||
Request::Write {
|
||||
path: path(p),
|
||||
data_b64: base64::Engine::encode(&base64::engine::general_purpose::STANDARD, data),
|
||||
}
|
||||
}
|
||||
|
||||
fn ro(root: impl Into<PathBuf>) -> Allowed {
|
||||
Allowed {
|
||||
root: root.into(),
|
||||
writable: false,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn allowed_path_accepted() {
|
||||
let allowed = vec![rw("/tmp/weft-test-allowed")];
|
||||
assert!(is_allowed(
|
||||
Path::new("/tmp/weft-test-allowed/file.txt"),
|
||||
&allowed,
|
||||
false
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn disallowed_path_rejected() {
|
||||
let allowed = vec![rw("/tmp/weft-test-allowed")];
|
||||
assert!(!is_allowed(Path::new("/etc/passwd"), &allowed, false));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dotdot_traversal_blocked() {
|
||||
let allowed = vec![rw("/tmp/weft-test-allowed")];
|
||||
assert!(!is_allowed(
|
||||
Path::new("/tmp/weft-test-allowed/../etc/passwd"),
|
||||
&allowed,
|
||||
false
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_allowlist_rejects_all() {
|
||||
assert!(!is_allowed(Path::new("/tmp/anything"), &[], false));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_allowed_extracts_paths() {
|
||||
let args: Vec<String> = vec![
|
||||
"--allow".into(),
|
||||
"/tmp/a".into(),
|
||||
"--allow".into(),
|
||||
"/tmp/b".into(),
|
||||
"--allow-read".into(),
|
||||
"/tmp/c".into(),
|
||||
];
|
||||
let result = parse_allowed(&args);
|
||||
assert_eq!(result, vec![rw("/tmp/a"), rw("/tmp/b")]);
|
||||
let args: Vec<String> = vec!["--allow-read".into(), "/tmp/c".into()];
|
||||
assert_eq!(parse_allowed(&args), vec![ro("/tmp/c")]);
|
||||
assert_eq!(
|
||||
parse_allowed(&args),
|
||||
vec![
|
||||
Allowed {
|
||||
root: "/tmp/a".into(),
|
||||
writable: true
|
||||
},
|
||||
Allowed {
|
||||
root: "/tmp/c".into(),
|
||||
writable: false
|
||||
},
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn handle_request_read_denied() {
|
||||
let resp = handle_request(
|
||||
Request::Read {
|
||||
path: "/etc/shadow".into(),
|
||||
},
|
||||
&[rw("/tmp/safe")],
|
||||
fn paths_must_name_a_place_inside_a_granted_directory_directly() {
|
||||
let root = Path::new("/srv/granted");
|
||||
assert_eq!(
|
||||
relative_to(Path::new("/srv/granted/a/b"), root),
|
||||
Some(Path::new("a/b"))
|
||||
);
|
||||
let json = serde_json::to_string(&resp).unwrap();
|
||||
assert!(json.contains("access denied"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn handle_request_read_roundtrip() {
|
||||
use std::fs;
|
||||
let dir = std::env::temp_dir().join(format!("wfp_test_{}", std::process::id()));
|
||||
let _ = fs::create_dir_all(&dir);
|
||||
let file = dir.join("hello.txt");
|
||||
fs::write(&file, b"hello world").unwrap();
|
||||
|
||||
let allowed = vec![rw(dir.clone())];
|
||||
let resp = handle_request(
|
||||
Request::Read {
|
||||
path: file.to_string_lossy().into(),
|
||||
},
|
||||
&allowed,
|
||||
assert_eq!(
|
||||
relative_to(Path::new("/srv/granted"), root),
|
||||
Some(Path::new(""))
|
||||
);
|
||||
let json = serde_json::to_string(&resp).unwrap();
|
||||
assert!(json.contains("data_b64"));
|
||||
|
||||
if let Response::OkData { data_b64 } = resp {
|
||||
let decoded =
|
||||
base64::Engine::decode(&base64::engine::general_purpose::STANDARD, &data_b64)
|
||||
.unwrap();
|
||||
assert_eq!(decoded, b"hello world");
|
||||
} else {
|
||||
panic!("expected OkData");
|
||||
for outside in [
|
||||
"/srv/grantedx/a",
|
||||
"/srv/granted/../x",
|
||||
"/srv/granted/a/../../x",
|
||||
"/etc",
|
||||
"/srv/granted/a/./b",
|
||||
"/srv/granted/a/.",
|
||||
"/srv/granted/a/",
|
||||
"/srv/granted//a",
|
||||
"srv/granted/a",
|
||||
] {
|
||||
assert_eq!(relative_to(Path::new(outside), root), None, "{outside}");
|
||||
}
|
||||
|
||||
let _ = fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn handle_request_list() {
|
||||
use std::fs;
|
||||
let dir = std::env::temp_dir().join(format!("wfp_list_{}", std::process::id()));
|
||||
let _ = fs::create_dir_all(&dir);
|
||||
fs::write(dir.join("b.txt"), b"").unwrap();
|
||||
fs::write(dir.join("a.txt"), b"").unwrap();
|
||||
|
||||
let allowed = vec![rw(dir.clone())];
|
||||
let resp = handle_request(
|
||||
fn reads_writes_and_lists_inside_the_directory() {
|
||||
let dir = temp("roundtrip");
|
||||
let granted = dir.join("granted");
|
||||
let roots = grant(&granted, true);
|
||||
assert!(matches!(
|
||||
handle_request(write_req(&granted.join("b.txt"), b"hello"), &roots),
|
||||
Response::Ok
|
||||
));
|
||||
fs::write(granted.join("a.txt"), b"").unwrap();
|
||||
match handle_request(read_req(&granted.join("b.txt")), &roots) {
|
||||
Response::OkData { data_b64 } => assert_eq!(
|
||||
base64::Engine::decode(&base64::engine::general_purpose::STANDARD, data_b64)
|
||||
.unwrap(),
|
||||
b"hello"
|
||||
),
|
||||
_ => panic!("expected data"),
|
||||
}
|
||||
match handle_request(
|
||||
Request::List {
|
||||
path: dir.to_string_lossy().into(),
|
||||
path: path(&granted),
|
||||
},
|
||||
&allowed,
|
||||
);
|
||||
if let Response::OkEntries { entries } = resp {
|
||||
assert_eq!(entries, vec!["a.txt", "b.txt"]);
|
||||
} else {
|
||||
panic!("expected OkEntries");
|
||||
&roots,
|
||||
) {
|
||||
Response::OkEntries { entries } => assert_eq!(entries, ["a.txt", "b.txt"]),
|
||||
_ => panic!("expected entries"),
|
||||
}
|
||||
|
||||
let _ = fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn handle_request_write_creates_parent_dirs() {
|
||||
use std::fs;
|
||||
let dir = std::env::temp_dir().join(format!("wfp_write_{}", std::process::id()));
|
||||
fn links_cannot_lead_out_of_the_directory() {
|
||||
let dir = temp("links");
|
||||
let granted = dir.join("granted");
|
||||
fs::write(dir.join("secret.txt"), b"secret").unwrap();
|
||||
fs::create_dir(granted.join("sub")).unwrap();
|
||||
std::os::unix::fs::symlink("/", granted.join("root")).unwrap();
|
||||
std::os::unix::fs::symlink("../secret.txt", granted.join("up")).unwrap();
|
||||
std::os::unix::fs::symlink(&dir, granted.join("parent")).unwrap();
|
||||
let roots = grant(&granted, true);
|
||||
for escape in [
|
||||
granted.join("root/etc/passwd"),
|
||||
granted.join("up"),
|
||||
granted.join("parent/secret.txt"),
|
||||
// The check this replaced normalised `link/..` away and then
|
||||
// followed the link.
|
||||
granted.join("root/../secret.txt"),
|
||||
] {
|
||||
assert!(
|
||||
denied(&handle_request(read_req(&escape), &roots)),
|
||||
"{}",
|
||||
escape.display()
|
||||
);
|
||||
if escape != granted.join("up") {
|
||||
assert!(
|
||||
denied(&handle_request(write_req(&escape, b"x"), &roots)),
|
||||
"{}",
|
||||
escape.display()
|
||||
);
|
||||
}
|
||||
}
|
||||
// A write to a name that is a link replaces the link, inside the
|
||||
// directory, rather than writing where it points.
|
||||
match handle_request(read_req(&granted.join("root/etc/passwd")), &roots) {
|
||||
Response::Err { error } => assert!(error.contains("leads out"), "{error}"),
|
||||
_ => panic!("read through a link out of the directory"),
|
||||
}
|
||||
assert!(matches!(
|
||||
handle_request(write_req(&granted.join("up"), b"x"), &roots),
|
||||
Response::Ok
|
||||
));
|
||||
assert!(fs::symlink_metadata(granted.join("up")).unwrap().is_file());
|
||||
assert_eq!(fs::read(dir.join("secret.txt")).unwrap(), b"secret");
|
||||
// A link that stays inside is followed.
|
||||
std::os::unix::fs::symlink("sub", granted.join("inside")).unwrap();
|
||||
assert!(matches!(
|
||||
handle_request(write_req(&granted.join("inside/f"), b"ok"), &roots),
|
||||
Response::Ok
|
||||
));
|
||||
assert_eq!(fs::read(granted.join("sub/f")).unwrap(), b"ok");
|
||||
let _ = fs::remove_dir_all(&dir);
|
||||
let nested = dir.join("sub").join("deep").join("file.txt");
|
||||
let data = base64::Engine::encode(
|
||||
&base64::engine::general_purpose::STANDARD,
|
||||
b"nested content",
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_directory_swapped_for_a_link_mid_operation_cannot_lead_out() {
|
||||
let dir = temp("race");
|
||||
let granted = dir.join("granted");
|
||||
fs::create_dir(dir.join("outside")).unwrap();
|
||||
fs::write(dir.join("outside/f"), b"secret").unwrap();
|
||||
fs::create_dir(granted.join("real")).unwrap();
|
||||
fs::write(granted.join("real/f"), b"inside").unwrap();
|
||||
let roots = grant(&granted, true);
|
||||
// `swap` is a link, replaced in a loop, alternately to the inside
|
||||
// directory and out of the granted one, absolute and relative.
|
||||
std::os::unix::fs::symlink("real", granted.join("swap")).unwrap();
|
||||
let stop = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
|
||||
let swapper = {
|
||||
let (granted, outside, stop) = (granted.clone(), dir.join("outside"), stop.clone());
|
||||
std::thread::spawn(move || {
|
||||
let targets = [PathBuf::from("real"), outside, PathBuf::from("../outside")];
|
||||
for target in targets.iter().cycle() {
|
||||
if stop.load(std::sync::atomic::Ordering::Relaxed) {
|
||||
break;
|
||||
}
|
||||
let _ = std::os::unix::fs::symlink(target, granted.join("next"));
|
||||
let _ = fs::rename(granted.join("next"), granted.join("swap"));
|
||||
}
|
||||
})
|
||||
};
|
||||
let (mut inside, mut refused) = (0, 0);
|
||||
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(20);
|
||||
while (inside < 50 || refused < 50) && std::time::Instant::now() < deadline {
|
||||
match handle_request(read_req(&granted.join("swap/f")), &roots) {
|
||||
Response::OkData { data_b64 } => {
|
||||
let data = base64::Engine::decode(
|
||||
&base64::engine::general_purpose::STANDARD,
|
||||
data_b64,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(data, b"inside", "a read left the directory");
|
||||
inside += 1;
|
||||
}
|
||||
Response::Err { error } if error.contains("leads out") => refused += 1,
|
||||
_ => {}
|
||||
}
|
||||
let _ = handle_request(write_req(&granted.join("swap/f"), b"inside"), &roots);
|
||||
}
|
||||
stop.store(true, std::sync::atomic::Ordering::Relaxed);
|
||||
swapper.join().unwrap();
|
||||
assert_eq!(fs::read(dir.join("outside/f")).unwrap(), b"secret");
|
||||
assert!(
|
||||
inside >= 50 && refused >= 50,
|
||||
"the race was not exercised: {inside} reads inside, {refused} refused"
|
||||
);
|
||||
let allowed = vec![rw(dir.clone())];
|
||||
let resp = handle_request(
|
||||
Request::Write {
|
||||
path: nested.to_string_lossy().into(),
|
||||
data_b64: data,
|
||||
},
|
||||
&allowed,
|
||||
);
|
||||
assert!(matches!(resp, Response::Ok), "expected Ok response");
|
||||
assert_eq!(fs::read(&nested).unwrap(), b"nested content");
|
||||
let _ = fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_replaced_file_keeps_its_mode() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let dir = temp("mode");
|
||||
let granted = dir.join("granted");
|
||||
fs::write(granted.join("shared.txt"), b"old").unwrap();
|
||||
fs::set_permissions(
|
||||
granted.join("shared.txt"),
|
||||
fs::Permissions::from_mode(0o644),
|
||||
)
|
||||
.unwrap();
|
||||
let roots = grant(&granted, true);
|
||||
assert!(matches!(
|
||||
handle_request(write_req(&granted.join("shared.txt"), b"new"), &roots),
|
||||
Response::Ok
|
||||
));
|
||||
let mode = fs::metadata(granted.join("shared.txt"))
|
||||
.unwrap()
|
||||
.permissions()
|
||||
.mode();
|
||||
assert_eq!(mode & 0o777, 0o644);
|
||||
let _ = fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn read_only_directories_refuse_writes() {
|
||||
use std::fs;
|
||||
let dir = std::env::temp_dir().join(format!("wfp_ro_{}", std::process::id()));
|
||||
let dir = temp("ro");
|
||||
let granted = dir.join("granted");
|
||||
fs::write(granted.join("kept.txt"), b"original").unwrap();
|
||||
let roots = grant(&granted, false);
|
||||
assert!(denied(&handle_request(
|
||||
write_req(&granted.join("kept.txt"), b"x"),
|
||||
&roots
|
||||
)));
|
||||
assert_eq!(fs::read(granted.join("kept.txt")).unwrap(), b"original");
|
||||
assert!(matches!(
|
||||
handle_request(read_req(&granted.join("kept.txt")), &roots),
|
||||
Response::OkData { .. }
|
||||
));
|
||||
let _ = fs::remove_dir_all(&dir);
|
||||
fs::create_dir_all(&dir).unwrap();
|
||||
fs::write(dir.join("kept.txt"), b"original").unwrap();
|
||||
let allowed = vec![ro(dir.clone())];
|
||||
let data = base64::Engine::encode(&base64::engine::general_purpose::STANDARD, b"x");
|
||||
let resp = handle_request(
|
||||
Request::Write {
|
||||
path: dir.join("kept.txt").to_string_lossy().into(),
|
||||
data_b64: data,
|
||||
},
|
||||
&allowed,
|
||||
);
|
||||
assert!(
|
||||
serde_json::to_string(&resp)
|
||||
.unwrap()
|
||||
.contains("access denied")
|
||||
);
|
||||
assert_eq!(fs::read(dir.join("kept.txt")).unwrap(), b"original");
|
||||
let resp = handle_request(
|
||||
Request::Read {
|
||||
path: dir.join("kept.txt").to_string_lossy().into(),
|
||||
},
|
||||
&allowed,
|
||||
);
|
||||
assert!(matches!(resp, Response::OkData { .. }));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn writes_create_no_directories_and_leave_no_temporary_files() {
|
||||
let dir = temp("nodirs");
|
||||
let granted = dir.join("granted");
|
||||
let roots = grant(&granted, true);
|
||||
assert!(denied(&handle_request(
|
||||
write_req(&granted.join("missing/f"), b"x"),
|
||||
&roots
|
||||
)));
|
||||
assert!(!granted.join("missing").exists());
|
||||
assert!(denied(&handle_request(write_req(&granted, b"x"), &roots)));
|
||||
let left: Vec<_> = fs::read_dir(&granted).unwrap().flatten().collect();
|
||||
assert!(left.is_empty(), "{left:?}");
|
||||
let _ = fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn oversized_files_are_refused() {
|
||||
let dir = temp("size");
|
||||
let granted = dir.join("granted");
|
||||
fs::File::create(granted.join("big"))
|
||||
.unwrap()
|
||||
.set_len(MAX_FILE as u64 + 1)
|
||||
.unwrap();
|
||||
let roots = grant(&granted, true);
|
||||
assert!(denied(&handle_request(
|
||||
read_req(&granted.join("big")),
|
||||
&roots
|
||||
)));
|
||||
let _ = fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn overlong_requests_end_the_connection() {
|
||||
let dir = temp("line");
|
||||
let granted = dir.join("granted");
|
||||
let roots = grant(&granted, true);
|
||||
let (client, server) = std::os::unix::net::UnixStream::pair().unwrap();
|
||||
let serve = std::thread::spawn(move || handle_connection(server, &roots));
|
||||
let mut writer = client.try_clone().unwrap();
|
||||
let sent = std::thread::spawn(move || {
|
||||
let _ = writer.write_all(&vec![b'x'; MAX_LINE + 64]);
|
||||
});
|
||||
let mut reply = String::new();
|
||||
BufReader::new(client).read_line(&mut reply).unwrap();
|
||||
serve.join().unwrap();
|
||||
let _ = sent.join();
|
||||
assert!(reply.contains("request too long"), "{reply}");
|
||||
let _ = fs::remove_dir_all(&dir);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -12,6 +12,9 @@ path = "src/lib.rs"
|
|||
serde = { version = "1", features = ["derive"] }
|
||||
rmp-serde = "1"
|
||||
toml = "0.8"
|
||||
sha2 = "0.10"
|
||||
hex = "0.4"
|
||||
ed25519-dalek = "2"
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
|
|
|||
144
crates/weft-ipc-types/src/approval.rs
Normal file
144
crates/weft-ipc-types/src/approval.rs
Normal file
|
|
@ -0,0 +1,144 @@
|
|||
//! The capabilities the user approved for an installed app.
|
||||
//!
|
||||
//! A package declares capabilities; it gets only those the user approved.
|
||||
//! `weft-pack` records the approval, `$XDG_DATA_HOME/weft/approvals/<id>`,
|
||||
//! one capability per line, and weft-appd refuses to launch an app that
|
||||
//! declares a capability the record does not hold. An app's own private
|
||||
//! data is a minimal execution resource and needs no approval. Signature
|
||||
//! verification and approval are separate decisions: a trusted signature
|
||||
//! approves nothing.
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use crate::capability::Capability;
|
||||
|
||||
/// Where the approval record of `app_id` lives.
|
||||
pub fn approval_path(data_home: &Path, app_id: &str) -> PathBuf {
|
||||
data_home.join("weft/approvals").join(app_id)
|
||||
}
|
||||
|
||||
/// Whether a declared capability needs the user's approval. Strings that
|
||||
/// are not capabilities are left to the capability checks, which refuse
|
||||
/// them.
|
||||
pub fn needs_approval(capability: &str) -> bool {
|
||||
capability
|
||||
.parse::<Capability>()
|
||||
.is_ok_and(|c| !matches!(c, Capability::AppData(_)))
|
||||
}
|
||||
|
||||
/// The declared capabilities that need approval and are not in `approved`.
|
||||
pub fn unapproved<'a>(declared: &'a [String], approved: &BTreeSet<String>) -> Vec<&'a str> {
|
||||
declared
|
||||
.iter()
|
||||
.map(String::as_str)
|
||||
.filter(|c| needs_approval(c) && !approved.contains(*c))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The capabilities approved for an app; none when there is no record.
|
||||
pub fn read_approved(record: &Path) -> std::io::Result<BTreeSet<String>> {
|
||||
match std::fs::read_to_string(record) {
|
||||
Ok(text) => Ok(text
|
||||
.lines()
|
||||
.map(str::trim)
|
||||
.filter(|l| !l.is_empty())
|
||||
.map(str::to_owned)
|
||||
.collect()),
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(BTreeSet::new()),
|
||||
Err(e) => Err(e),
|
||||
}
|
||||
}
|
||||
|
||||
/// Records exactly the capabilities of `declared` that need approval as the
|
||||
/// app's approval, replacing an earlier one in one rename. With none to
|
||||
/// approve, the record is removed.
|
||||
pub fn write_approved(record: &Path, declared: &[String]) -> std::io::Result<()> {
|
||||
use std::io::Write;
|
||||
let approved: BTreeSet<&str> = declared
|
||||
.iter()
|
||||
.map(String::as_str)
|
||||
.filter(|c| needs_approval(c))
|
||||
.collect();
|
||||
if approved.is_empty() {
|
||||
return remove_approval(record);
|
||||
}
|
||||
let parent = record
|
||||
.parent()
|
||||
.expect("approval records live in a directory");
|
||||
std::fs::create_dir_all(parent)?;
|
||||
let temp = parent.join(format!(
|
||||
".{}.{}.tmp",
|
||||
record
|
||||
.file_name()
|
||||
.and_then(|n| n.to_str())
|
||||
.unwrap_or("record"),
|
||||
std::process::id()
|
||||
));
|
||||
let written = (|| {
|
||||
let mut file = std::fs::File::create(&temp)?;
|
||||
for capability in &approved {
|
||||
writeln!(file, "{capability}")?;
|
||||
}
|
||||
file.sync_all()?;
|
||||
std::fs::rename(&temp, record)
|
||||
})();
|
||||
if written.is_err() {
|
||||
let _ = std::fs::remove_file(&temp);
|
||||
}
|
||||
written?;
|
||||
std::fs::File::open(parent).and_then(|dir| dir.sync_all())
|
||||
}
|
||||
|
||||
/// Removes an app's approval, so a later installation asks again.
|
||||
pub fn remove_approval(record: &Path) -> std::io::Result<()> {
|
||||
match std::fs::remove_file(record) {
|
||||
Err(e) if e.kind() != std::io::ErrorKind::NotFound => Err(e),
|
||||
_ => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn caps(list: &[&str]) -> Vec<String> {
|
||||
list.iter().map(|c| (*c).to_owned()).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn private_app_data_needs_no_approval() {
|
||||
assert!(!needs_approval("fs:rw:app-data"));
|
||||
assert!(!needs_approval("fs:read:app-data"));
|
||||
assert!(needs_approval("net:fetch:example.org"));
|
||||
assert!(needs_approval("sys:notifications"));
|
||||
assert!(needs_approval("fs:read:xdg-documents"));
|
||||
// Not a capability: refused elsewhere, not reported as unapproved.
|
||||
assert!(!needs_approval("sys:everything"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn approvals_cover_exactly_what_was_approved() {
|
||||
let dir = std::env::temp_dir().join(format!("weft_approval_{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
let record = approval_path(&dir, "org.weft.test");
|
||||
let declared = caps(&["fs:rw:app-data", "net:fetch:example.org"]);
|
||||
assert_eq!(read_approved(&record).unwrap(), BTreeSet::new());
|
||||
assert_eq!(
|
||||
unapproved(&declared, &read_approved(&record).unwrap()),
|
||||
["net:fetch:example.org"]
|
||||
);
|
||||
write_approved(&record, &declared).unwrap();
|
||||
assert!(unapproved(&declared, &read_approved(&record).unwrap()).is_empty());
|
||||
// An update that asks for more needs approval for the new capability.
|
||||
let updated = caps(&["net:fetch:example.org", "sys:clipboard:read"]);
|
||||
assert_eq!(
|
||||
unapproved(&updated, &read_approved(&record).unwrap()),
|
||||
["sys:clipboard:read"]
|
||||
);
|
||||
// Nothing left to approve removes the record.
|
||||
write_approved(&record, &caps(&["fs:rw:app-data"])).unwrap();
|
||||
assert!(!record.exists());
|
||||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
}
|
||||
|
|
@ -1,6 +1,9 @@
|
|||
pub mod approval;
|
||||
pub mod capability;
|
||||
pub mod manifest;
|
||||
pub mod package;
|
||||
pub mod store;
|
||||
pub mod trust;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
|
|
@ -10,25 +13,36 @@ 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,
|
||||
},
|
||||
AppFocusRequest {
|
||||
session_id: u64,
|
||||
},
|
||||
/// Asks the session's windows to close, as a user close would.
|
||||
AppCloseRequest {
|
||||
session_id: u64,
|
||||
},
|
||||
}
|
||||
|
||||
/// Messages sent from weft-compositor to weft-appd.
|
||||
#[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 +125,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 +176,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"),
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -38,6 +38,31 @@ pub struct RuntimeMeta {
|
|||
pub struct UiMeta {
|
||||
/// The UI document, relative to the package root.
|
||||
pub entry: String,
|
||||
/// What happens when the user asks the application's window to close.
|
||||
#[serde(default)]
|
||||
pub close: ClosePolicy,
|
||||
}
|
||||
|
||||
/// An application's declared unsaved-change policy: what a user close does.
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum ClosePolicy {
|
||||
/// The window closes at once; the application keeps no unsaved state.
|
||||
#[default]
|
||||
Immediate,
|
||||
/// The page is asked first and may cancel the close, for example to
|
||||
/// offer saving unsaved changes; it then closes itself when done.
|
||||
Ask,
|
||||
}
|
||||
|
||||
impl ClosePolicy {
|
||||
/// The value weft-appd passes to the app shell in `WEFT_APP_CLOSE`.
|
||||
pub fn as_str(self) -> &'static str {
|
||||
match self {
|
||||
Self::Immediate => "immediate",
|
||||
Self::Ask => "ask",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Why a manifest could not be read.
|
||||
|
|
@ -62,9 +87,19 @@ impl Manifest {
|
|||
/// Reads `<package_root>/wapp.toml`.
|
||||
pub fn read(package_root: &Path) -> Result<Self, ManifestError> {
|
||||
let path = package_root.join(MANIFEST_FILE);
|
||||
let text =
|
||||
std::fs::read_to_string(&path).map_err(|e| ManifestError::Io(path.clone(), e))?;
|
||||
toml::from_str(&text).map_err(|e| ManifestError::Parse(path, e))
|
||||
let bytes = std::fs::read(&path).map_err(|e| ManifestError::Io(path.clone(), e))?;
|
||||
Self::parse(&path, &bytes)
|
||||
}
|
||||
|
||||
/// Parses manifest bytes already read from `path`.
|
||||
pub fn parse(path: &Path, bytes: &[u8]) -> Result<Self, ManifestError> {
|
||||
let text = std::str::from_utf8(bytes).map_err(|e| {
|
||||
ManifestError::Io(
|
||||
path.to_path_buf(),
|
||||
std::io::Error::new(std::io::ErrorKind::InvalidData, e),
|
||||
)
|
||||
})?;
|
||||
toml::from_str(text).map_err(|e| ManifestError::Parse(path.to_path_buf(), e))
|
||||
}
|
||||
|
||||
pub fn capabilities(&self) -> &[String] {
|
||||
|
|
@ -212,6 +247,24 @@ mod tests {
|
|||
let manifest = Manifest::read(&dir).unwrap();
|
||||
assert_eq!(manifest.package.id, "org.weft.test");
|
||||
assert_eq!(manifest.capabilities(), ["sys:notifications"]);
|
||||
assert_eq!(manifest.ui.close, ClosePolicy::Immediate);
|
||||
std::fs::write(
|
||||
dir.join(MANIFEST_FILE),
|
||||
"[package]\nid = \"org.weft.test\"\nname = \"T\"\nversion = \"1.0.0\"\n\
|
||||
[runtime]\nmodule = \"app.wasm\"\n[ui]\nentry = \"ui/index.html\"\nclose = \"ask\"\n",
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(Manifest::read(&dir).unwrap().ui.close, ClosePolicy::Ask);
|
||||
std::fs::write(
|
||||
dir.join(MANIFEST_FILE),
|
||||
"[package]\nid = \"org.weft.test\"\nname = \"T\"\nversion = \"1.0.0\"\n\
|
||||
[runtime]\nmodule = \"app.wasm\"\n[ui]\nentry = \"ui/index.html\"\nclose = \"later\"\n",
|
||||
)
|
||||
.unwrap();
|
||||
assert!(matches!(
|
||||
Manifest::read(&dir),
|
||||
Err(ManifestError::Parse(..))
|
||||
));
|
||||
std::fs::write(dir.join(MANIFEST_FILE), "[package]\nid = \"x\"\n").unwrap();
|
||||
assert!(matches!(
|
||||
Manifest::read(&dir),
|
||||
|
|
|
|||
|
|
@ -79,6 +79,39 @@ pub fn legacy_app_data_dir(home: &Path, app_id: &str) -> PathBuf {
|
|||
.join("data")
|
||||
}
|
||||
|
||||
/// The home directory, when `HOME` is set to an absolute path.
|
||||
pub fn home_dir() -> Option<PathBuf> {
|
||||
std::env::var_os("HOME")
|
||||
.map(PathBuf::from)
|
||||
.filter(|home| home.is_absolute())
|
||||
}
|
||||
|
||||
/// Where app data for `app_id` already exists, in the current layout or in
|
||||
/// the earlier one under `home`, if anywhere. Data in the earlier layout is
|
||||
/// moved to the current one when the app next launches, so it counts too.
|
||||
pub fn existing_app_data(
|
||||
data_home: &Path,
|
||||
home: &Path,
|
||||
app_id: &str,
|
||||
) -> std::io::Result<Option<PathBuf>> {
|
||||
let places = [
|
||||
app_data_dir(data_home, app_id),
|
||||
legacy_app_data_dir(home, app_id),
|
||||
];
|
||||
for place in places {
|
||||
match std::fs::symlink_metadata(&place) {
|
||||
Ok(_) => return Ok(Some(place)),
|
||||
Err(e)
|
||||
if matches!(
|
||||
e.kind(),
|
||||
std::io::ErrorKind::NotFound | std::io::ErrorKind::NotADirectory
|
||||
) => {}
|
||||
Err(e) => return Err(e),
|
||||
}
|
||||
}
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
/// The result of moving data from the earlier layout.
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub enum Migration {
|
||||
|
|
@ -180,13 +213,13 @@ pub fn migrate_app_data(legacy: &Path, target: &Path) -> Result<Migration, Migra
|
|||
/// Renames `from` to `to`, failing with `AlreadyExists` instead of replacing
|
||||
/// an existing `to`, even one created after the caller checked for it.
|
||||
#[cfg(target_os = "linux")]
|
||||
fn rename_no_replace(from: &Path, to: &Path) -> std::io::Result<()> {
|
||||
pub fn rename_no_replace(from: &Path, to: &Path) -> std::io::Result<()> {
|
||||
use rustix::fs::{CWD, RenameFlags, renameat_with};
|
||||
renameat_with(CWD, from, CWD, to, RenameFlags::NOREPLACE).map_err(std::io::Error::from)
|
||||
}
|
||||
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
fn rename_no_replace(from: &Path, to: &Path) -> std::io::Result<()> {
|
||||
pub fn rename_no_replace(from: &Path, to: &Path) -> std::io::Result<()> {
|
||||
if std::fs::symlink_metadata(to).is_ok() {
|
||||
return Err(std::io::ErrorKind::AlreadyExists.into());
|
||||
}
|
||||
|
|
|
|||
238
crates/weft-ipc-types/src/store.rs
Normal file
238
crates/weft-ipc-types/src/store.rs
Normal file
|
|
@ -0,0 +1,238 @@
|
|||
//! The layout of a package store and the revisions it holds.
|
||||
//!
|
||||
//! Each installed revision of a package is an immutable directory named by
|
||||
//! its content digest, `<store>/.revisions/<app_id>/<digest>`. The active
|
||||
//! revision is chosen by `<store>/<app_id>`, a symbolic link to it that one
|
||||
//! rename replaces, so an update or rollback switches every new launch at
|
||||
//! once and an interrupted one leaves the previous choice in place. Stores
|
||||
//! written before revisions existed hold the package directly in
|
||||
//! `<store>/<app_id>`; that layout is still read.
|
||||
//!
|
||||
//! A session pins the revision it was launched from with a shared lock on
|
||||
//! the revision directory, held for the session's lifetime. Package
|
||||
//! operations remove a revision only after taking that lock exclusively, so
|
||||
//! a live session keeps running on the bytes it started with.
|
||||
|
||||
use std::fs::File;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
/// The directory of a store that holds package revisions.
|
||||
pub const REVISIONS_DIR: &str = ".revisions";
|
||||
|
||||
/// The directory holding the revisions of `app_id`.
|
||||
pub fn revisions_of(store_root: &Path, app_id: &str) -> PathBuf {
|
||||
store_root.join(REVISIONS_DIR).join(app_id)
|
||||
}
|
||||
|
||||
/// The link target that makes `revision` the active revision of `app_id`,
|
||||
/// relative to the store root.
|
||||
pub fn link_target(app_id: &str, revision: &str) -> PathBuf {
|
||||
Path::new(REVISIONS_DIR).join(app_id).join(revision)
|
||||
}
|
||||
|
||||
/// Whether `name` is a revision name: the hex content digest of a package.
|
||||
pub fn is_revision_name(name: &str) -> bool {
|
||||
name.len() == 64 && name.bytes().all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f'))
|
||||
}
|
||||
|
||||
/// Where the active package of `app_id` is in a store.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum Active {
|
||||
/// A revision, by name, in `.revisions/<app_id>/`.
|
||||
Revision { name: String, dir: PathBuf },
|
||||
/// A package directory installed before revisions existed.
|
||||
Directory(PathBuf),
|
||||
}
|
||||
|
||||
impl Active {
|
||||
/// The package root.
|
||||
pub fn dir(&self) -> &Path {
|
||||
match self {
|
||||
Self::Revision { dir, .. } | Self::Directory(dir) => dir,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Why the active package of a store cannot be determined.
|
||||
#[derive(Debug)]
|
||||
pub enum StoreError {
|
||||
Io(PathBuf, std::io::Error),
|
||||
/// `<store>/<app_id>` is neither a package directory nor a link to one
|
||||
/// of its revisions.
|
||||
NotAPackage(PathBuf),
|
||||
}
|
||||
|
||||
impl std::fmt::Display for StoreError {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
Self::Io(path, e) => write!(f, "cannot read {}: {e}", path.display()),
|
||||
Self::NotAPackage(path) => write!(
|
||||
f,
|
||||
"{} is neither a package directory nor a link to one of its revisions",
|
||||
path.display()
|
||||
),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for StoreError {}
|
||||
|
||||
/// The active package of `app_id` in `store_root`, if any. A link is
|
||||
/// followed only when it names one of the app's own revisions, exactly as
|
||||
/// package operations write it, and that revision is a directory.
|
||||
pub fn active(store_root: &Path, app_id: &str) -> Result<Option<Active>, StoreError> {
|
||||
let entry = store_root.join(app_id);
|
||||
let metadata = match std::fs::symlink_metadata(&entry) {
|
||||
Ok(m) => m,
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
|
||||
Err(e) => return Err(StoreError::Io(entry, e)),
|
||||
};
|
||||
if metadata.is_dir() {
|
||||
return Ok(Some(Active::Directory(entry)));
|
||||
}
|
||||
if !metadata.file_type().is_symlink() {
|
||||
return Err(StoreError::NotAPackage(entry));
|
||||
}
|
||||
let target = std::fs::read_link(&entry).map_err(|e| StoreError::Io(entry.clone(), e))?;
|
||||
let name = target
|
||||
.file_name()
|
||||
.and_then(|n| n.to_str())
|
||||
.filter(|n| is_revision_name(n))
|
||||
.map(str::to_owned);
|
||||
let Some(name) = name.filter(|n| target == link_target(app_id, n)) else {
|
||||
return Err(StoreError::NotAPackage(entry));
|
||||
};
|
||||
let dir = revisions_of(store_root, app_id).join(&name);
|
||||
match std::fs::symlink_metadata(&dir) {
|
||||
Ok(m) if m.is_dir() => Ok(Some(Active::Revision { name, dir })),
|
||||
Ok(_) => Err(StoreError::NotAPackage(entry)),
|
||||
Err(e) => Err(StoreError::Io(dir, e)),
|
||||
}
|
||||
}
|
||||
|
||||
/// A shared lock on a package directory, held while a session runs from it.
|
||||
#[derive(Debug)]
|
||||
pub struct Pin {
|
||||
_dir: File,
|
||||
}
|
||||
|
||||
/// Pins the package directory `dir`. The lock is taken on the directory
|
||||
/// that is opened, and the path must still name that directory afterwards:
|
||||
/// a revision removed or replaced in between is not pinned. A directory a
|
||||
/// package operation holds is not waited for, so nobody able to lock a
|
||||
/// package directory can stall launches; the launch is refused instead.
|
||||
pub fn pin(dir: &Path) -> std::io::Result<Pin> {
|
||||
let file = File::open(dir)?;
|
||||
match file.try_lock_shared() {
|
||||
Ok(()) => {}
|
||||
Err(std::fs::TryLockError::WouldBlock) => {
|
||||
return Err(std::io::Error::other(format!(
|
||||
"{} is being changed; try again",
|
||||
dir.display()
|
||||
)));
|
||||
}
|
||||
Err(std::fs::TryLockError::Error(e)) => return Err(e),
|
||||
}
|
||||
if !same_file(&file, dir)? {
|
||||
return Err(std::io::Error::other(format!(
|
||||
"{} changed while it was being pinned",
|
||||
dir.display()
|
||||
)));
|
||||
}
|
||||
Ok(Pin { _dir: file })
|
||||
}
|
||||
|
||||
/// Takes the exclusive lock on a package directory that no session pins,
|
||||
/// or returns `None` while one does.
|
||||
pub fn try_claim(dir: &Path) -> std::io::Result<Option<File>> {
|
||||
let file = File::open(dir)?;
|
||||
match file.try_lock() {
|
||||
Ok(()) => Ok(Some(file)),
|
||||
Err(std::fs::TryLockError::WouldBlock) => Ok(None),
|
||||
Err(std::fs::TryLockError::Error(e)) => Err(e),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
fn same_file(file: &File, path: &Path) -> std::io::Result<bool> {
|
||||
use std::os::unix::fs::MetadataExt;
|
||||
let opened = file.metadata()?;
|
||||
let named = std::fs::symlink_metadata(path)?;
|
||||
Ok(opened.dev() == named.dev() && opened.ino() == named.ino())
|
||||
}
|
||||
|
||||
#[cfg(not(unix))]
|
||||
fn same_file(_file: &File, _path: &Path) -> std::io::Result<bool> {
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn store(name: &str) -> PathBuf {
|
||||
let dir = std::env::temp_dir().join(format!("weft_store_{name}_{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
dir
|
||||
}
|
||||
|
||||
const REV: &str = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn only_links_to_the_apps_own_revisions_are_followed() {
|
||||
use std::os::unix::fs::symlink;
|
||||
let root = store("links");
|
||||
std::fs::create_dir_all(revisions_of(&root, "org.a").join(REV)).unwrap();
|
||||
std::fs::create_dir_all(revisions_of(&root, "org.b").join(REV)).unwrap();
|
||||
assert!(active(&root, "org.a").unwrap().is_none());
|
||||
|
||||
symlink(link_target("org.a", REV), root.join("org.a")).unwrap();
|
||||
assert_eq!(
|
||||
active(&root, "org.a").unwrap(),
|
||||
Some(Active::Revision {
|
||||
name: REV.to_owned(),
|
||||
dir: revisions_of(&root, "org.a").join(REV),
|
||||
})
|
||||
);
|
||||
// Another app's revision, an absolute target, a non-revision name.
|
||||
for target in [
|
||||
link_target("org.b", REV),
|
||||
revisions_of(&root, "org.c").join(REV),
|
||||
PathBuf::from(".revisions/org.c/latest"),
|
||||
] {
|
||||
let _ = std::fs::remove_file(root.join("org.c"));
|
||||
std::fs::create_dir_all(revisions_of(&root, "org.c").join(REV)).unwrap();
|
||||
symlink(&target, root.join("org.c")).unwrap();
|
||||
assert!(
|
||||
matches!(active(&root, "org.c"), Err(StoreError::NotAPackage(_))),
|
||||
"{}",
|
||||
target.display()
|
||||
);
|
||||
}
|
||||
// A package installed before revisions existed.
|
||||
std::fs::create_dir(root.join("org.d")).unwrap();
|
||||
assert_eq!(
|
||||
active(&root, "org.d").unwrap(),
|
||||
Some(Active::Directory(root.join("org.d")))
|
||||
);
|
||||
std::fs::remove_dir_all(&root).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_pinned_directory_cannot_be_claimed() {
|
||||
let root = store("pin");
|
||||
let dir = root.join("rev");
|
||||
std::fs::create_dir(&dir).unwrap();
|
||||
let pinned = pin(&dir).unwrap();
|
||||
assert!(try_claim(&dir).unwrap().is_none());
|
||||
// Other sessions can pin it too.
|
||||
let again = pin(&dir).unwrap();
|
||||
drop((pinned, again));
|
||||
let claimed = try_claim(&dir).unwrap();
|
||||
assert!(claimed.is_some());
|
||||
drop(claimed);
|
||||
std::fs::remove_dir_all(&root).unwrap();
|
||||
}
|
||||
}
|
||||
521
crates/weft-ipc-types/src/trust.rs
Normal file
521
crates/weft-ipc-types/src/trust.rs
Normal file
|
|
@ -0,0 +1,521 @@
|
|||
//! Package content identity, publisher keys and the trust decisions made
|
||||
//! before a package is installed or launched.
|
||||
//!
|
||||
//! A package is signed over its content digest: the SHA-256 of a canonical
|
||||
//! inventory listing every file except the root `signature.sig`, one
|
||||
//! `<relative path>\t<hex sha-256>\n` line per file, sorted by path. Paths use
|
||||
//! `/` and must be UTF-8 without control characters, so no name can imitate
|
||||
//! the separators of other lines. Symbolic links and special files are
|
||||
//! refused, so the signed bytes are exactly the files a package holds.
|
||||
|
||||
use std::fmt;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use ed25519_dalek::{Signature, VerifyingKey};
|
||||
use sha2::{Digest, Sha256};
|
||||
|
||||
/// The signature file at the root of a signed package.
|
||||
pub const SIGNATURE_FILE: &str = "signature.sig";
|
||||
|
||||
/// Why a package's content or trust could not be established.
|
||||
#[derive(Debug)]
|
||||
pub enum TrustError {
|
||||
/// The package holds a symbolic link.
|
||||
Link(PathBuf),
|
||||
/// The package holds something other than directories and regular files.
|
||||
NotAFile(PathBuf),
|
||||
/// A path in the package is not UTF-8.
|
||||
NonUtf8(PathBuf),
|
||||
/// A name in the package holds a control character.
|
||||
ControlCharacter(PathBuf),
|
||||
/// A key, signature or owner record is malformed.
|
||||
Malformed(PathBuf, String),
|
||||
Io(PathBuf, std::io::Error),
|
||||
}
|
||||
|
||||
impl fmt::Display for TrustError {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
Self::Link(p) => write!(f, "{} is a symbolic link", p.display()),
|
||||
Self::NotAFile(p) => write!(f, "{} is not a regular file or directory", p.display()),
|
||||
Self::NonUtf8(p) => write!(f, "{} is not a UTF-8 path", p.display()),
|
||||
Self::ControlCharacter(p) => {
|
||||
write!(f, "{:?} has a control character in its name", p.display())
|
||||
}
|
||||
Self::Malformed(p, why) => write!(f, "{}: {why}", p.display()),
|
||||
Self::Io(p, e) => write!(f, "{}: {e}", p.display()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for TrustError {}
|
||||
|
||||
fn io(path: &Path) -> impl FnOnce(std::io::Error) -> TrustError + '_ {
|
||||
move |e| TrustError::Io(path.to_path_buf(), e)
|
||||
}
|
||||
|
||||
/// The SHA-256 content digest a package signature covers.
|
||||
pub fn content_digest(package_root: &Path) -> Result<[u8; 32], TrustError> {
|
||||
Inventory::read(package_root).map(|inventory| inventory.digest())
|
||||
}
|
||||
|
||||
/// The files of a package and their SHA-256 hashes, as read once: the digest
|
||||
/// and the hash of any one file come from the same reading.
|
||||
#[derive(Debug)]
|
||||
pub struct Inventory(Vec<(String, [u8; 32])>);
|
||||
|
||||
impl Inventory {
|
||||
pub fn read(package_root: &Path) -> Result<Self, TrustError> {
|
||||
let mut entries = Vec::new();
|
||||
collect(package_root, package_root, &mut entries)?;
|
||||
entries.sort();
|
||||
Ok(Self(entries))
|
||||
}
|
||||
|
||||
/// The content digest a package signature covers.
|
||||
pub fn digest(&self) -> [u8; 32] {
|
||||
let mut inventory = String::new();
|
||||
for (path, hash) in &self.0 {
|
||||
inventory.push_str(path);
|
||||
inventory.push('\t');
|
||||
inventory.push_str(&hex::encode(hash));
|
||||
inventory.push('\n');
|
||||
}
|
||||
Sha256::digest(inventory.as_bytes()).into()
|
||||
}
|
||||
|
||||
/// Whether the file at `path`, relative to the package root, had exactly
|
||||
/// these bytes when the inventory was read.
|
||||
pub fn holds(&self, path: &str, bytes: &[u8]) -> bool {
|
||||
let hash: [u8; 32] = Sha256::digest(bytes).into();
|
||||
self.0.iter().any(|(p, h)| p == path && *h == hash)
|
||||
}
|
||||
}
|
||||
|
||||
fn collect(
|
||||
root: &Path,
|
||||
dir: &Path,
|
||||
entries: &mut Vec<(String, [u8; 32])>,
|
||||
) -> Result<(), TrustError> {
|
||||
for entry in std::fs::read_dir(dir).map_err(io(dir))? {
|
||||
let path = entry.map_err(io(dir))?.path();
|
||||
let relative = path
|
||||
.strip_prefix(root)
|
||||
.expect("read_dir yields children of the directory it reads")
|
||||
.to_str()
|
||||
.ok_or_else(|| TrustError::NonUtf8(path.clone()))?
|
||||
.to_owned();
|
||||
if relative.chars().any(char::is_control) {
|
||||
return Err(TrustError::ControlCharacter(path));
|
||||
}
|
||||
let kind = std::fs::symlink_metadata(&path)
|
||||
.map_err(io(&path))?
|
||||
.file_type();
|
||||
if kind.is_symlink() {
|
||||
return Err(TrustError::Link(path));
|
||||
} else if kind.is_dir() {
|
||||
collect(root, &path, entries)?;
|
||||
} else if !kind.is_file() {
|
||||
return Err(TrustError::NotAFile(path));
|
||||
} else if relative != SIGNATURE_FILE {
|
||||
let bytes = std::fs::read(&path).map_err(io(&path))?;
|
||||
entries.push((relative, Sha256::digest(&bytes).into()));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A publisher's Ed25519 public key.
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
pub struct PublisherKey(VerifyingKey);
|
||||
|
||||
impl fmt::Debug for PublisherKey {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
write!(f, "PublisherKey({})", self.to_hex())
|
||||
}
|
||||
}
|
||||
|
||||
impl PublisherKey {
|
||||
/// Parses 64 hex digits, the format `weft-pack generate-key` writes.
|
||||
pub fn from_hex(text: &str) -> Result<Self, String> {
|
||||
let bytes: [u8; 32] = hex::decode(text.trim())
|
||||
.map_err(|_| "expected 64 hex digits".to_owned())?
|
||||
.try_into()
|
||||
.map_err(|_| "expected a 32-byte key".to_owned())?;
|
||||
VerifyingKey::from_bytes(&bytes)
|
||||
.map(Self)
|
||||
.map_err(|_| "not a valid Ed25519 public key".to_owned())
|
||||
}
|
||||
|
||||
pub fn from_file(path: &Path) -> Result<Self, TrustError> {
|
||||
let text = std::fs::read_to_string(path).map_err(io(path))?;
|
||||
Self::from_hex(&text).map_err(|why| TrustError::Malformed(path.to_path_buf(), why))
|
||||
}
|
||||
|
||||
/// The key as 64 lowercase hex digits; it also identifies the publisher.
|
||||
pub fn to_hex(&self) -> String {
|
||||
hex::encode(self.0.as_bytes())
|
||||
}
|
||||
|
||||
/// Whether `signature` signs `digest` with this key.
|
||||
pub fn signed(&self, digest: &[u8; 32], signature: &Signature) -> bool {
|
||||
self.0.verify_strict(digest, signature).is_ok()
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads the package's signature, or `None` when the package is unsigned.
|
||||
pub fn read_signature(package_root: &Path) -> Result<Option<Signature>, TrustError> {
|
||||
let path = package_root.join(SIGNATURE_FILE);
|
||||
match std::fs::symlink_metadata(&path) {
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
|
||||
Err(e) => return Err(TrustError::Io(path, e)),
|
||||
Ok(m) if !m.file_type().is_file() => return Err(TrustError::NotAFile(path)),
|
||||
Ok(_) => {}
|
||||
}
|
||||
let text = std::fs::read_to_string(&path).map_err(io(&path))?;
|
||||
let bytes: [u8; 64] = hex::decode(text.trim())
|
||||
.ok()
|
||||
.and_then(|b| b.try_into().ok())
|
||||
.ok_or_else(|| TrustError::Malformed(path, "expected 128 hex digits".to_owned()))?;
|
||||
Ok(Some(Signature::from_bytes(&bytes)))
|
||||
}
|
||||
|
||||
/// The publisher keys this host trusts to sign packages.
|
||||
#[derive(Debug, Default)]
|
||||
pub struct TrustStore {
|
||||
keys: Vec<PublisherKey>,
|
||||
}
|
||||
|
||||
impl TrustStore {
|
||||
/// The trust store directories, in order: `$WEFT_TRUSTED_KEYS` alone when
|
||||
/// set; otherwise the user's `$XDG_CONFIG_HOME/weft/trusted-keys` (or
|
||||
/// `~/.config/weft/trusted-keys`) and the system `/etc/weft/trusted-keys`.
|
||||
pub fn directories() -> Vec<PathBuf> {
|
||||
if let Some(dir) = std::env::var_os("WEFT_TRUSTED_KEYS") {
|
||||
return vec![PathBuf::from(dir)];
|
||||
}
|
||||
let config = std::env::var_os("XDG_CONFIG_HOME")
|
||||
.map(PathBuf::from)
|
||||
.filter(|dir| dir.is_absolute())
|
||||
.or_else(|| {
|
||||
std::env::var_os("HOME")
|
||||
.map(PathBuf::from)
|
||||
.filter(|home| home.is_absolute())
|
||||
.map(|home| home.join(".config"))
|
||||
});
|
||||
let mut dirs: Vec<PathBuf> = config
|
||||
.map(|dir| dir.join("weft/trusted-keys"))
|
||||
.into_iter()
|
||||
.collect();
|
||||
dirs.push(PathBuf::from("/etc/weft/trusted-keys"));
|
||||
dirs
|
||||
}
|
||||
|
||||
/// Loads every `*.pub` file in `directories`. A missing directory holds no
|
||||
/// keys; a malformed key file is an error rather than silently ignored.
|
||||
pub fn load(directories: &[PathBuf]) -> Result<Self, TrustError> {
|
||||
let mut keys = Vec::new();
|
||||
for dir in directories {
|
||||
let entries = match std::fs::read_dir(dir) {
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => continue,
|
||||
other => other.map_err(io(dir))?,
|
||||
};
|
||||
let mut files: Vec<PathBuf> = entries
|
||||
.map(|e| e.map(|e| e.path()).map_err(io(dir)))
|
||||
.collect::<Result<_, _>>()?;
|
||||
files.sort();
|
||||
for file in files
|
||||
.into_iter()
|
||||
.filter(|f| f.extension().is_some_and(|e| e == "pub"))
|
||||
{
|
||||
keys.push(PublisherKey::from_file(&file)?);
|
||||
}
|
||||
}
|
||||
Ok(Self { keys })
|
||||
}
|
||||
|
||||
pub fn keys(&self) -> &[PublisherKey] {
|
||||
&self.keys
|
||||
}
|
||||
|
||||
/// The trusted key that signed the package at `package_root`, if any.
|
||||
pub fn signer(&self, package_root: &Path) -> Result<Option<PublisherKey>, TrustError> {
|
||||
let Some(signature) = read_signature(package_root)? else {
|
||||
return Ok(None);
|
||||
};
|
||||
Ok(self.signer_of(&content_digest(package_root)?, &signature))
|
||||
}
|
||||
|
||||
/// The trusted key that made `signature` over `digest`, if any.
|
||||
pub fn signer_of(&self, digest: &[u8; 32], signature: &Signature) -> Option<PublisherKey> {
|
||||
self.keys
|
||||
.iter()
|
||||
.copied()
|
||||
.find(|k| k.signed(digest, signature))
|
||||
}
|
||||
}
|
||||
|
||||
/// Who an application ID belongs to on this host. The record outlives the
|
||||
/// package while the app's data remains, so another publisher cannot take
|
||||
/// over the ID, and the data with it, by reusing it.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum Owner {
|
||||
/// Installed from packages signed by this trusted key.
|
||||
Verified(PublisherKey),
|
||||
/// Installed as development content, without a trusted signature.
|
||||
Development,
|
||||
}
|
||||
|
||||
impl fmt::Display for Owner {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
Self::Verified(key) => write!(f, "publisher {}", key.to_hex()),
|
||||
Self::Development => f.write_str("development installation"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Where the owner of `app_id` is recorded, beside the app's data. Callers
|
||||
/// pass a valid app ID, which cannot leave the owners directory.
|
||||
pub fn owner_record_path(data_home: &Path, app_id: &str) -> PathBuf {
|
||||
data_home.join("weft/owners").join(app_id)
|
||||
}
|
||||
|
||||
/// Reads an owner record: `verified <key>` or `development`.
|
||||
pub fn read_owner(record: &Path) -> Result<Option<Owner>, TrustError> {
|
||||
let text = match std::fs::read_to_string(record) {
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
|
||||
other => other.map_err(io(record))?,
|
||||
};
|
||||
let malformed = |why: &str| TrustError::Malformed(record.to_path_buf(), why.to_owned());
|
||||
match text.trim().split_once(' ') {
|
||||
Some(("verified", key)) => PublisherKey::from_hex(key)
|
||||
.map(|k| Some(Owner::Verified(k)))
|
||||
.map_err(|why| malformed(&why)),
|
||||
None if text.trim() == "development" => Ok(Some(Owner::Development)),
|
||||
_ => Err(malformed("expected 'verified <key>' or 'development'")),
|
||||
}
|
||||
}
|
||||
|
||||
/// Records the owner of an app ID. An existing record is never replaced, and
|
||||
/// a record is either absent or complete: it is written and synced under a
|
||||
/// temporary name, then linked into place.
|
||||
pub fn write_owner(record: &Path, owner: Owner) -> Result<(), TrustError> {
|
||||
use std::io::Write;
|
||||
let parent = record.parent().expect("owner records live in a directory");
|
||||
std::fs::create_dir_all(parent).map_err(io(parent))?;
|
||||
let text = match owner {
|
||||
Owner::Verified(key) => format!("verified {}\n", key.to_hex()),
|
||||
Owner::Development => "development\n".to_owned(),
|
||||
};
|
||||
let name = record
|
||||
.file_name()
|
||||
.and_then(|n| n.to_str())
|
||||
.unwrap_or("record");
|
||||
let temp = parent.join(format!(".{name}.{}.tmp", std::process::id()));
|
||||
let _ = std::fs::remove_file(&temp);
|
||||
let written = (|| {
|
||||
let mut file = std::fs::OpenOptions::new()
|
||||
.write(true)
|
||||
.create_new(true)
|
||||
.open(&temp)?;
|
||||
file.write_all(text.as_bytes())?;
|
||||
file.sync_all()
|
||||
})()
|
||||
.map_err(io(&temp));
|
||||
let linked = written.and_then(|()| std::fs::hard_link(&temp, record).map_err(io(record)));
|
||||
let _ = std::fs::remove_file(&temp);
|
||||
linked?;
|
||||
std::fs::File::open(parent)
|
||||
.and_then(|dir| dir.sync_all())
|
||||
.map_err(io(parent))
|
||||
}
|
||||
|
||||
/// Takes the lock that serialises every change to the installation and
|
||||
/// owner record of `app_id`, held until the returned file is dropped.
|
||||
pub fn lock_owner(data_home: &Path, app_id: &str) -> Result<std::fs::File, TrustError> {
|
||||
let dir = data_home.join("weft/owners");
|
||||
if !crate::package::is_valid_app_id(app_id) {
|
||||
return Err(TrustError::Malformed(
|
||||
dir,
|
||||
format!("'{app_id}' is not a valid app ID"),
|
||||
));
|
||||
}
|
||||
std::fs::create_dir_all(&dir).map_err(io(&dir))?;
|
||||
let path = dir.join(format!(".{app_id}.lock"));
|
||||
let file = std::fs::OpenOptions::new()
|
||||
.write(true)
|
||||
.create(true)
|
||||
.truncate(false)
|
||||
.open(&path)
|
||||
.map_err(io(&path))?;
|
||||
file.lock().map_err(io(&path))?;
|
||||
Ok(file)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use ed25519_dalek::{Signer, SigningKey};
|
||||
|
||||
fn dir(name: &str) -> PathBuf {
|
||||
let dir = std::env::temp_dir().join(format!("weft_trust_{name}_{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(dir.join("ui")).unwrap();
|
||||
std::fs::write(dir.join("wapp.toml"), b"[package]\n").unwrap();
|
||||
std::fs::write(dir.join("ui/index.html"), b"<p>").unwrap();
|
||||
dir
|
||||
}
|
||||
|
||||
fn sign(dir: &Path, seed: u8) -> PublisherKey {
|
||||
let key = SigningKey::from_bytes(&[seed; 32]);
|
||||
let signature = key.sign(&content_digest(dir).unwrap());
|
||||
std::fs::write(dir.join(SIGNATURE_FILE), hex::encode(signature.to_bytes())).unwrap();
|
||||
PublisherKey(key.verifying_key())
|
||||
}
|
||||
|
||||
fn store(keys: &[PublisherKey]) -> TrustStore {
|
||||
TrustStore {
|
||||
keys: keys.to_vec(),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_committed_demo_signatures_verify_with_the_demo_key() {
|
||||
let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../..");
|
||||
let key = PublisherKey::from_file(&root.join("examples/keys/weft-sign.pub")).unwrap();
|
||||
for demo in ["org.weft.demo.counter", "org.weft.demo.notes"] {
|
||||
let package = root.join("examples").join(demo);
|
||||
assert_eq!(store(&[key]).signer(&package).unwrap(), Some(key), "{demo}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn any_changed_file_breaks_the_signature() {
|
||||
let dir = dir("tamper");
|
||||
let key = sign(&dir, 1);
|
||||
assert_eq!(store(&[key]).signer(&dir).unwrap(), Some(key));
|
||||
std::fs::write(dir.join("ui/index.html"), b"<p>changed").unwrap();
|
||||
assert_eq!(store(&[key]).signer(&dir).unwrap(), None);
|
||||
std::fs::write(dir.join("ui/index.html"), b"<p>").unwrap();
|
||||
std::fs::write(dir.join("ui/extra.js"), b"").unwrap();
|
||||
assert_eq!(store(&[key]).signer(&dir).unwrap(), None);
|
||||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_trusted_keys_are_signers_and_unsigned_packages_have_none() {
|
||||
let dir = dir("untrusted");
|
||||
assert_eq!(store(&[]).signer(&dir).unwrap(), None);
|
||||
let key = sign(&dir, 2);
|
||||
let other = PublisherKey(SigningKey::from_bytes(&[3; 32]).verifying_key());
|
||||
assert_eq!(store(&[other]).signer(&dir).unwrap(), None);
|
||||
assert_eq!(store(&[other, key]).signer(&dir).unwrap(), Some(key));
|
||||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn names_cannot_imitate_other_inventory_lines() {
|
||||
// With files ui/policy.txt and ui/z.css signed, a directory named
|
||||
// "ui/policy.txt\t<hash>\nui" holding z.css would reproduce the
|
||||
// inventory without policy.txt. Such names have no digest.
|
||||
let dir = dir("forged");
|
||||
std::fs::write(dir.join("ui/policy.txt"), b"default-src 'self'").unwrap();
|
||||
std::fs::write(dir.join("ui/z.css"), b"p{}").unwrap();
|
||||
let signed = content_digest(&dir).unwrap();
|
||||
let policy_hash = hex::encode(Sha256::digest(b"default-src 'self'"));
|
||||
std::fs::remove_file(dir.join("ui/policy.txt")).unwrap();
|
||||
let forged = dir.join(format!("ui/policy.txt\t{policy_hash}\nui"));
|
||||
std::fs::create_dir_all(&forged).unwrap();
|
||||
std::fs::rename(dir.join("ui/z.css"), forged.join("z.css")).unwrap();
|
||||
let refused = content_digest(&dir);
|
||||
assert!(matches!(refused, Err(TrustError::ControlCharacter(_))));
|
||||
assert_ne!(refused.ok(), Some(signed));
|
||||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_inventory_knows_the_bytes_it_hashed() {
|
||||
let dir = dir("inventory");
|
||||
let inventory = Inventory::read(&dir).unwrap();
|
||||
assert_eq!(inventory.digest(), content_digest(&dir).unwrap());
|
||||
assert!(inventory.holds("wapp.toml", b"[package]\n"));
|
||||
assert!(!inventory.holds("wapp.toml", b"[package]\ncapabilities = []\n"));
|
||||
assert!(!inventory.holds("absent.toml", b"[package]\n"));
|
||||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn owner_locks_exclude_each_other() {
|
||||
let home = std::env::temp_dir().join(format!("weft_trust_lock_{}", std::process::id()));
|
||||
let held = lock_owner(&home, "org.weft.test.lock").unwrap();
|
||||
let path = home.join("weft/owners/.org.weft.test.lock.lock");
|
||||
let other = std::fs::OpenOptions::new().write(true).open(&path).unwrap();
|
||||
assert!(other.try_lock().is_err());
|
||||
drop(held);
|
||||
assert!(other.try_lock().is_ok());
|
||||
// A name that would open fine but is not an app ID is refused.
|
||||
assert!(lock_owner(&home, "Org.weft.test").is_err());
|
||||
assert!(!home.join("weft/owners/.Org.weft.test.lock").exists());
|
||||
std::fs::remove_dir_all(&home).unwrap();
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
#[test]
|
||||
fn links_and_special_files_have_no_content_digest() {
|
||||
let dir = dir("links");
|
||||
std::os::unix::fs::symlink("/etc/hostname", dir.join("ui/linked")).unwrap();
|
||||
assert!(matches!(content_digest(&dir), Err(TrustError::Link(_))));
|
||||
std::fs::remove_file(dir.join("ui/linked")).unwrap();
|
||||
std::os::unix::fs::symlink(dir.join("ui"), dir.join("view")).unwrap();
|
||||
assert!(matches!(content_digest(&dir), Err(TrustError::Link(_))));
|
||||
std::fs::remove_file(dir.join("view")).unwrap();
|
||||
rustix::fs::mknodat(
|
||||
rustix::fs::CWD,
|
||||
dir.join("fifo"),
|
||||
rustix::fs::FileType::Fifo,
|
||||
rustix::fs::Mode::from_raw_mode(0o600),
|
||||
0,
|
||||
)
|
||||
.unwrap();
|
||||
assert!(matches!(content_digest(&dir), Err(TrustError::NotAFile(_))));
|
||||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn trust_stores_load_pub_files_and_refuse_malformed_keys() {
|
||||
let dir = dir("store");
|
||||
let keys = dir.join("keys");
|
||||
std::fs::create_dir_all(&keys).unwrap();
|
||||
let key = PublisherKey(SigningKey::from_bytes(&[4; 32]).verifying_key());
|
||||
std::fs::write(keys.join("a.pub"), key.to_hex()).unwrap();
|
||||
std::fs::write(keys.join("notes.txt"), "not a key").unwrap();
|
||||
let loaded = TrustStore::load(&[keys.clone(), dir.join("missing")]).unwrap();
|
||||
assert_eq!(loaded.keys(), [key]);
|
||||
std::fs::write(keys.join("b.pub"), "zz").unwrap();
|
||||
assert!(matches!(
|
||||
TrustStore::load(&[keys]),
|
||||
Err(TrustError::Malformed(..))
|
||||
));
|
||||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn owner_records_round_trip_and_are_never_replaced() {
|
||||
let dir = dir("owners");
|
||||
let key = PublisherKey(SigningKey::from_bytes(&[5; 32]).verifying_key());
|
||||
let verified = owner_record_path(&dir, "org.weft.test.a");
|
||||
let development = owner_record_path(&dir, "org.weft.test.b");
|
||||
assert_eq!(read_owner(&verified).unwrap(), None);
|
||||
write_owner(&verified, Owner::Verified(key)).unwrap();
|
||||
write_owner(&development, Owner::Development).unwrap();
|
||||
assert_eq!(read_owner(&verified).unwrap(), Some(Owner::Verified(key)));
|
||||
assert_eq!(read_owner(&development).unwrap(), Some(Owner::Development));
|
||||
assert!(write_owner(&verified, Owner::Development).is_err());
|
||||
assert_eq!(read_owner(&verified).unwrap(), Some(Owner::Verified(key)));
|
||||
std::fs::write(&development, "someone else\n").unwrap();
|
||||
assert!(read_owner(&development).is_err());
|
||||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
}
|
||||
|
|
@ -17,3 +17,6 @@ rand = "0.8"
|
|||
hex = "0.4"
|
||||
tar = "0.4"
|
||||
zstd = "0.13"
|
||||
|
||||
[target.'cfg(unix)'.dependencies]
|
||||
rustix = { version = "1", features = ["fs"] }
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load diff
269
crates/weft-runtime/src/desktop.rs
Normal file
269
crates/weft-runtime/src/desktop.rs
Normal file
|
|
@ -0,0 +1,269 @@
|
|||
//! The desktop services behind the clipboard and notification imports.
|
||||
//!
|
||||
//! Each import runs a helper program (`wl-paste`, `wl-copy`,
|
||||
//! `notify-send`) with a bounded input, a bounded output and a deadline,
|
||||
//! after which the helper is killed and the call fails. A notification
|
||||
//! names the application that sent it, so an app cannot pass one off as
|
||||
//! the system's.
|
||||
|
||||
use std::io::{Read, Write};
|
||||
use std::process::{Command, Stdio};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
/// How long a helper may run.
|
||||
const HELPER_TIMEOUT: Duration = Duration::from_secs(5);
|
||||
/// The most clipboard text read or written, in bytes.
|
||||
pub const MAX_CLIPBOARD: usize = 1024 * 1024;
|
||||
/// The longest notification title and body, in bytes.
|
||||
pub const MAX_TITLE: usize = 256;
|
||||
pub const MAX_BODY: usize = 4096;
|
||||
|
||||
/// What a helper's output streams are connected to.
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
enum Output {
|
||||
/// Read: up to the limit from standard output, and standard error for
|
||||
/// the failure message.
|
||||
Captured,
|
||||
/// Standard output discarded and standard error read only when the
|
||||
/// helper fails, for a helper that leaves a process running which
|
||||
/// keeps its streams open after succeeding, as `wl-copy` does to
|
||||
/// serve the selection; it fails, if at all, before that.
|
||||
ErrorsOnly,
|
||||
}
|
||||
|
||||
/// Runs `command` with `input` on its standard input and returns at most
|
||||
/// `max_output` bytes of its standard output, or why it failed.
|
||||
fn run(
|
||||
mut command: Command,
|
||||
input: Option<Vec<u8>>,
|
||||
max_output: usize,
|
||||
output: Output,
|
||||
) -> Result<Vec<u8>, String> {
|
||||
let program = command.get_program().to_string_lossy().into_owned();
|
||||
let mut child = command
|
||||
.stdin(if input.is_some() {
|
||||
Stdio::piped()
|
||||
} else {
|
||||
Stdio::null()
|
||||
})
|
||||
.stdout(match output {
|
||||
Output::Captured => Stdio::piped(),
|
||||
Output::ErrorsOnly => Stdio::null(),
|
||||
})
|
||||
.stderr(Stdio::piped())
|
||||
.spawn()
|
||||
.map_err(|e| format!("cannot run {program}: {e}"))?;
|
||||
if let (Some(mut stdin), Some(input)) = (child.stdin.take(), input) {
|
||||
std::thread::spawn(move || {
|
||||
let _ = stdin.write_all(&input);
|
||||
});
|
||||
}
|
||||
let reader = |stream: Option<Box<dyn Read + Send>>, limit: usize| {
|
||||
std::thread::spawn(move || {
|
||||
let mut data = Vec::new();
|
||||
if let Some(stream) = stream {
|
||||
let _ = stream.take(limit as u64 + 1).read_to_end(&mut data);
|
||||
}
|
||||
data
|
||||
})
|
||||
};
|
||||
let stdout = reader(
|
||||
child
|
||||
.stdout
|
||||
.take()
|
||||
.map(|s| Box::new(s) as Box<dyn Read + Send>),
|
||||
max_output,
|
||||
);
|
||||
let stderr = reader(
|
||||
child
|
||||
.stderr
|
||||
.take()
|
||||
.map(|s| Box::new(s) as Box<dyn Read + Send>),
|
||||
4096,
|
||||
);
|
||||
let deadline = Instant::now() + HELPER_TIMEOUT;
|
||||
let status = loop {
|
||||
match child.try_wait() {
|
||||
Ok(Some(status)) => break status,
|
||||
Ok(None) if Instant::now() < deadline => std::thread::sleep(Duration::from_millis(10)),
|
||||
Ok(None) => {
|
||||
let _ = child.kill();
|
||||
let _ = child.wait();
|
||||
return Err(format!(
|
||||
"{program} did not finish within {} s",
|
||||
HELPER_TIMEOUT.as_secs()
|
||||
));
|
||||
}
|
||||
Err(e) => {
|
||||
let _ = child.kill();
|
||||
let _ = child.wait();
|
||||
return Err(e.to_string());
|
||||
}
|
||||
}
|
||||
};
|
||||
let output = stdout.join().unwrap_or_default();
|
||||
// Checked first: a helper whose output is cut off at the limit may die
|
||||
// of the broken pipe.
|
||||
if output.len() > max_output {
|
||||
return Err(format!("{program} returned more than {max_output} bytes"));
|
||||
}
|
||||
if !status.success() {
|
||||
let message = String::from_utf8_lossy(&stderr.join().unwrap_or_default())
|
||||
.trim()
|
||||
.to_owned();
|
||||
return Err(if message.is_empty() {
|
||||
format!("{program} exited with {status}")
|
||||
} else {
|
||||
format!("{program}: {message}")
|
||||
});
|
||||
}
|
||||
Ok(output)
|
||||
}
|
||||
|
||||
pub fn clipboard_read() -> Result<String, String> {
|
||||
let mut command = Command::new("wl-paste");
|
||||
// Any text type; the content must still be UTF-8.
|
||||
command.args(["--no-newline", "--type", "text"]);
|
||||
let data = run(command, None, MAX_CLIPBOARD, Output::Captured)?;
|
||||
String::from_utf8(data).map_err(|_| "the clipboard does not hold UTF-8 text".to_owned())
|
||||
}
|
||||
|
||||
pub fn clipboard_write(text: &str) -> Result<(), String> {
|
||||
if text.len() > MAX_CLIPBOARD {
|
||||
return Err(format!("clipboard text exceeds {MAX_CLIPBOARD} bytes"));
|
||||
}
|
||||
let mut command = Command::new("wl-copy");
|
||||
command.args(["--type", "text/plain;charset=utf-8"]);
|
||||
run(
|
||||
command,
|
||||
Some(text.as_bytes().to_vec()),
|
||||
0,
|
||||
Output::ErrorsOnly,
|
||||
)
|
||||
.map(|_| ())
|
||||
}
|
||||
|
||||
/// Checks a notification before it is sent.
|
||||
pub fn check_notification(title: &str, body: &str, icon: Option<&str>) -> Result<(), String> {
|
||||
if title.len() > MAX_TITLE {
|
||||
return Err(format!("notification title exceeds {MAX_TITLE} bytes"));
|
||||
}
|
||||
if body.len() > MAX_BODY {
|
||||
return Err(format!("notification body exceeds {MAX_BODY} bytes"));
|
||||
}
|
||||
// Only icon theme names: a path or URL would let the app show any file
|
||||
// or reach the network through the notification service.
|
||||
if let Some(icon) = icon
|
||||
&& !is_icon_name(icon)
|
||||
{
|
||||
return Err("a notification icon must be an icon theme name".to_owned());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn is_icon_name(icon: &str) -> bool {
|
||||
!icon.is_empty()
|
||||
&& icon.len() <= 64
|
||||
&& !icon.starts_with('.')
|
||||
&& icon
|
||||
.bytes()
|
||||
.all(|b| b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_' | b'.'))
|
||||
}
|
||||
|
||||
fn escape_markup(text: &str) -> String {
|
||||
text.replace('&', "&")
|
||||
.replace('<', "<")
|
||||
.replace('>', ">")
|
||||
}
|
||||
|
||||
/// Sends a notification attributed to `app_id`.
|
||||
pub fn notify(app_id: &str, title: &str, body: &str, icon: Option<&str>) -> Result<(), String> {
|
||||
check_notification(title, body, icon)?;
|
||||
let mut command = Command::new("notify-send");
|
||||
command.arg(format!("--app-name={app_id}"));
|
||||
if let Some(icon) = icon {
|
||||
command.arg(format!("--icon={icon}"));
|
||||
}
|
||||
// Notification servers may render markup in the body, including links
|
||||
// and images, so it is sent as plain text.
|
||||
command.arg("--").arg(title).arg(escape_markup(body));
|
||||
run(command, None, 0, Output::Captured).map(|_| ())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn notification_bodies_are_plain_text() {
|
||||
assert_eq!(
|
||||
escape_markup("<a href=\"x\">a & b</a>"),
|
||||
"<a href=\"x\">a & b</a>"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn notifications_are_bounded_and_icons_are_theme_names() {
|
||||
assert!(check_notification("t", "b", None).is_ok());
|
||||
assert!(check_notification("t", "b", Some("dialog-information")).is_ok());
|
||||
assert!(check_notification(&"t".repeat(MAX_TITLE + 1), "b", None).is_err());
|
||||
assert!(check_notification("t", &"b".repeat(MAX_BODY + 1), None).is_err());
|
||||
for icon in [
|
||||
"/etc/passwd",
|
||||
"file:///x.png",
|
||||
"https://x/i.png",
|
||||
"../x",
|
||||
"",
|
||||
"a b",
|
||||
] {
|
||||
assert!(check_notification("t", "b", Some(icon)).is_err(), "{icon}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn helpers_are_bounded_in_time_and_output() {
|
||||
let mut slow = Command::new("sleep");
|
||||
slow.arg("30");
|
||||
let started = Instant::now();
|
||||
let error = run(slow, None, 0, Output::Captured).unwrap_err();
|
||||
assert!(error.contains("did not finish"), "{error}");
|
||||
assert!(started.elapsed() < HELPER_TIMEOUT + Duration::from_secs(2));
|
||||
|
||||
let mut chatty = Command::new("head");
|
||||
// Far more than a pipe holds, so the cut-off kills the writer.
|
||||
chatty.args(["-c", "10000000", "/dev/zero"]);
|
||||
assert!(
|
||||
run(chatty, None, 1000, Output::Captured)
|
||||
.unwrap_err()
|
||||
.contains("more than 1000 bytes")
|
||||
);
|
||||
|
||||
let echo = Command::new("cat");
|
||||
assert_eq!(
|
||||
run(echo, Some(b"text".to_vec()), 100, Output::Captured).unwrap(),
|
||||
b"text"
|
||||
);
|
||||
|
||||
// A helper that leaves a process behind returns once it exits
|
||||
// itself when its streams are discarded.
|
||||
let mut forking = Command::new("sh");
|
||||
forking.args(["-c", "sleep 30 & exit 0"]);
|
||||
let started = Instant::now();
|
||||
assert!(run(forking, None, 0, Output::ErrorsOnly).is_ok());
|
||||
assert!(started.elapsed() < Duration::from_secs(2));
|
||||
|
||||
let mut failing = Command::new("sh");
|
||||
failing.args(["-c", "echo no display >&2; exit 1"]);
|
||||
assert_eq!(
|
||||
run(failing, None, 0, Output::ErrorsOnly).unwrap_err(),
|
||||
"sh: no display"
|
||||
);
|
||||
|
||||
let failing = Command::new("false");
|
||||
assert!(
|
||||
run(failing, None, 0, Output::Captured)
|
||||
.unwrap_err()
|
||||
.contains("exited")
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
@ -47,18 +47,31 @@ impl Grants {
|
|||
}
|
||||
|
||||
#[cfg_attr(not(feature = "net-fetch"), allow(dead_code))]
|
||||
/// Whether a request to `host` is covered by a fetch grant. `host` is the
|
||||
/// URL's host in the lowercase form URL parsing produces.
|
||||
pub fn fetch_host(&self, host: &str) -> Result<(), String> {
|
||||
/// Whether a request to `host` is covered by a fetch grant, and which
|
||||
/// addresses it may reach. `host` is the URL's host in the lowercase form
|
||||
/// URL parsing produces.
|
||||
pub fn fetch_host(&self, host: &str) -> Result<Reach, String> {
|
||||
if self.fetch.is_empty() {
|
||||
return Err("capability net:fetch is not granted".to_owned());
|
||||
}
|
||||
// An address named in a grant is reached as declared, wherever it
|
||||
// is; a name, or any host, reaches only public addresses, so a
|
||||
// granted name cannot be pointed at this machine or the local
|
||||
// network through DNS.
|
||||
if host.parse::<std::net::Ipv4Addr>().is_ok()
|
||||
&& self
|
||||
.fetch
|
||||
.iter()
|
||||
.any(|scope| matches!(scope, FetchScope::Host(granted) if granted == host))
|
||||
{
|
||||
return Ok(Reach::Declared);
|
||||
}
|
||||
let covered = self.fetch.iter().any(|scope| match scope {
|
||||
FetchScope::AnyHost => true,
|
||||
FetchScope::Host(granted) => granted == host,
|
||||
});
|
||||
if covered {
|
||||
Ok(())
|
||||
Ok(Reach::Public)
|
||||
} else {
|
||||
Err(format!("capability net:fetch:{host} is not granted"))
|
||||
}
|
||||
|
|
@ -115,6 +128,86 @@ impl Preopen {
|
|||
}
|
||||
}
|
||||
|
||||
/// The addresses a granted request may connect to.
|
||||
#[cfg_attr(not(feature = "net-fetch"), allow(dead_code))]
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum Reach {
|
||||
/// Only public addresses.
|
||||
Public,
|
||||
/// The address the grant names, public or not.
|
||||
Declared,
|
||||
}
|
||||
|
||||
/// Whether `ip` is a public unicast address: not loopback, unspecified,
|
||||
/// private, shared (CGNAT), link-local, multicast, broadcast, reserved,
|
||||
/// documentation or benchmarking space, nor an IPv6 form of one.
|
||||
#[cfg_attr(not(feature = "net-fetch"), allow(dead_code))]
|
||||
pub fn is_public(ip: std::net::IpAddr) -> bool {
|
||||
use std::net::IpAddr;
|
||||
match ip {
|
||||
IpAddr::V4(v4) => {
|
||||
let [a, b, c, _] = v4.octets();
|
||||
!(v4.is_unspecified()
|
||||
|| v4.is_loopback()
|
||||
|| v4.is_private()
|
||||
|| v4.is_link_local()
|
||||
|| v4.is_multicast()
|
||||
|| v4.is_broadcast()
|
||||
|| v4.is_documentation()
|
||||
|| a == 0
|
||||
|| a >= 240
|
||||
|| (a == 100 && (64..128).contains(&b))
|
||||
|| (a == 192 && b == 0 && c == 0)
|
||||
|| (a == 198 && (18..20).contains(&b)))
|
||||
}
|
||||
IpAddr::V6(v6) => {
|
||||
let seg = v6.segments();
|
||||
let embedded = |high: u16, low: u16| {
|
||||
IpAddr::V4(std::net::Ipv4Addr::new(
|
||||
(high >> 8) as u8,
|
||||
high as u8,
|
||||
(low >> 8) as u8,
|
||||
low as u8,
|
||||
))
|
||||
};
|
||||
// Forms that carry an IPv4 address are judged by that address:
|
||||
// mapped and compatible addresses, 6to4 and NAT64.
|
||||
if let Some(v4) = v6.to_ipv4_mapped() {
|
||||
return is_public(IpAddr::V4(v4));
|
||||
}
|
||||
// IPv4-translated (::ffff:0:a.b.c.d).
|
||||
if seg[..6] == [0, 0, 0, 0, 0xffff, 0] {
|
||||
return is_public(embedded(seg[6], seg[7]));
|
||||
}
|
||||
if seg[..6] == [0; 6] && !(seg[6] == 0 && seg[7] <= 1) {
|
||||
return is_public(embedded(seg[6], seg[7]));
|
||||
}
|
||||
if seg[0] == 0x2002 {
|
||||
return is_public(embedded(seg[1], seg[2]));
|
||||
}
|
||||
if seg[..6] == [0x0064, 0xff9b, 0, 0, 0, 0] {
|
||||
return is_public(embedded(seg[6], seg[7]));
|
||||
}
|
||||
!(v6.is_unspecified()
|
||||
|| v6.is_loopback()
|
||||
|| v6.is_multicast()
|
||||
// Unique local, link-local and the deprecated site-local.
|
||||
|| (seg[0] & 0xfe00) == 0xfc00
|
||||
|| (seg[0] & 0xffc0) == 0xfe80
|
||||
|| (seg[0] & 0xffc0) == 0xfec0
|
||||
// NAT64 for local use, discard-only.
|
||||
|| (seg[0] == 0x0064 && seg[1] == 0xff9b)
|
||||
|| (seg[0] == 0x0100 && seg[1..4] == [0, 0, 0])
|
||||
// Teredo, benchmarking, ORCHID and documentation.
|
||||
|| (seg[0] == 0x2001 && seg[1] == 0)
|
||||
|| (seg[0] == 0x2001 && seg[1] == 0x0002 && seg[2] == 0)
|
||||
|| (seg[0] == 0x2001 && matches!(seg[1] & 0xfff0, 0x0010 | 0x0020))
|
||||
|| (seg[0] == 0x2001 && seg[1] == 0x0db8)
|
||||
|| (seg[0] == 0x3fff && (seg[1] & 0xf000) == 0))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
|
@ -138,6 +231,73 @@ mod tests {
|
|||
assert!(grants.notifications().is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn named_and_wildcard_grants_reach_only_public_addresses() {
|
||||
let mut grants = Grants::default();
|
||||
grants.add("net:fetch:api.example.org").unwrap();
|
||||
grants.add("net:fetch:127.0.0.1").unwrap();
|
||||
assert_eq!(grants.fetch_host("api.example.org"), Ok(Reach::Public));
|
||||
// An address named in a grant is reached as declared.
|
||||
assert_eq!(grants.fetch_host("127.0.0.1"), Ok(Reach::Declared));
|
||||
let mut any = Grants::default();
|
||||
any.add("net:fetch:*").unwrap();
|
||||
assert_eq!(any.fetch_host("10.0.0.1"), Ok(Reach::Public));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_public_unicast_addresses_are_public() {
|
||||
// NAT64 and 6to4 forms of a public address are public, so DNS64
|
||||
// networks keep working.
|
||||
for public in [
|
||||
"93.184.216.34",
|
||||
"1.1.1.1",
|
||||
"2606:4700::1111",
|
||||
"64:ff9b::5db8:d822",
|
||||
"2002:5db8:d822::1",
|
||||
"3ffe::1",
|
||||
] {
|
||||
assert!(is_public(public.parse().unwrap()), "{public}");
|
||||
}
|
||||
for local in [
|
||||
"127.0.0.1",
|
||||
"0.0.0.0",
|
||||
"10.1.2.3",
|
||||
"172.16.0.1",
|
||||
"192.168.1.1",
|
||||
"169.254.169.254",
|
||||
"100.64.0.1",
|
||||
"224.0.0.1",
|
||||
"255.255.255.255",
|
||||
"192.0.2.1",
|
||||
"198.18.0.1",
|
||||
"240.0.0.1",
|
||||
"::1",
|
||||
"::",
|
||||
"fd00::1",
|
||||
"fe80::1",
|
||||
"ff02::1",
|
||||
"::ffff:127.0.0.1",
|
||||
"::ffff:10.0.0.1",
|
||||
"64:ff9b::a00:1",
|
||||
"64:ff9b:1::1",
|
||||
"64:ff9b:0:0:1::1",
|
||||
"::ffff:0:a00:1",
|
||||
"2001:20::1",
|
||||
"2001:db8::1",
|
||||
"fec0::1",
|
||||
"::7f00:1",
|
||||
"2002:7f00:1::",
|
||||
"2002:a00:1::",
|
||||
"2001::1",
|
||||
"2001:2::1",
|
||||
"2001:10::1",
|
||||
"3fff::1",
|
||||
"100::1",
|
||||
] {
|
||||
assert!(!is_public(local.parse().unwrap()), "{local}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn host_fetch_grants_match_exact_hosts() {
|
||||
let mut grants = Grants::default();
|
||||
|
|
|
|||
|
|
@ -2,6 +2,8 @@ use std::path::PathBuf;
|
|||
|
||||
use anyhow::Context;
|
||||
|
||||
#[cfg(feature = "wasmtime-runtime")]
|
||||
mod desktop;
|
||||
mod grants;
|
||||
#[cfg(feature = "wasmtime-runtime")]
|
||||
mod ipc;
|
||||
|
|
@ -97,6 +99,7 @@ fn main() -> anyhow::Result<()> {
|
|||
|
||||
tracing::info!(session_id, %app_id, wasm = %wasm_path.display(), "executing module");
|
||||
run_module(
|
||||
app_id,
|
||||
&wasm_path,
|
||||
&preopen,
|
||||
grants,
|
||||
|
|
@ -120,6 +123,7 @@ fn ready_line() -> String {
|
|||
|
||||
#[cfg(not(feature = "wasmtime-runtime"))]
|
||||
fn run_module(
|
||||
_app_id: &str,
|
||||
_wasm_path: &std::path::Path,
|
||||
_preopen: &[Preopen],
|
||||
_grants: Grants,
|
||||
|
|
@ -133,6 +137,7 @@ fn run_module(
|
|||
|
||||
#[cfg(feature = "wasmtime-runtime")]
|
||||
fn run_module(
|
||||
app_id: &str,
|
||||
wasm_path: &std::path::Path,
|
||||
preopen: &[Preopen],
|
||||
grants: Grants,
|
||||
|
|
@ -245,6 +250,7 @@ fn run_module(
|
|||
.context("define weft:app/fetch#fetch")?;
|
||||
|
||||
let notify_grants = Arc::clone(&grants);
|
||||
let notify_app = app_id.to_owned();
|
||||
linker
|
||||
.instance("weft:app/notifications@0.1.0")
|
||||
.context("define weft:app/notifications instance")?
|
||||
|
|
@ -255,7 +261,7 @@ fn run_module(
|
|||
-> wasmtime::Result<(Result<(), String>,)> {
|
||||
let result = notify_grants
|
||||
.notifications()
|
||||
.and_then(|()| host_notify(&title, &body, icon.as_deref()));
|
||||
.and_then(|()| desktop::notify(¬ify_app, &title, &body, icon.as_deref()));
|
||||
Ok((result,))
|
||||
},
|
||||
)
|
||||
|
|
@ -274,7 +280,7 @@ fn run_module(
|
|||
-> wasmtime::Result<(Result<String, String>,)> {
|
||||
Ok((read_grants
|
||||
.clipboard_read()
|
||||
.and_then(|()| host_clipboard_read()),))
|
||||
.and_then(|()| desktop::clipboard_read()),))
|
||||
},
|
||||
)
|
||||
.context("define weft:app/clipboard#read")?;
|
||||
|
|
@ -287,7 +293,7 @@ fn run_module(
|
|||
-> wasmtime::Result<(Result<(), String>,)> {
|
||||
Ok((write_grants
|
||||
.clipboard_write()
|
||||
.and_then(|()| host_clipboard_write(&text)),))
|
||||
.and_then(|()| desktop::clipboard_write(&text)),))
|
||||
},
|
||||
)
|
||||
.context("define weft:app/clipboard#write")?;
|
||||
|
|
@ -308,10 +314,6 @@ fn run_module(
|
|||
}
|
||||
}
|
||||
|
||||
if let Ok(portal_socket) = std::env::var("WEFT_FILE_PORTAL_SOCKET") {
|
||||
ctx_builder.env("WEFT_FILE_PORTAL_SOCKET", &portal_socket);
|
||||
}
|
||||
|
||||
for dir in preopen {
|
||||
let (dir_perms, file_perms) = match dir.access {
|
||||
Access::Read => (DirPerms::READ, FilePerms::READ),
|
||||
|
|
@ -403,7 +405,14 @@ fn host_fetch(
|
|||
return Err(format!("unsupported URL scheme '{}'", parsed.scheme()));
|
||||
}
|
||||
let host = parsed.host_str().ok_or("URL has no host")?;
|
||||
grants.fetch_host(host)?;
|
||||
let reach = grants.fetch_host(host)?;
|
||||
// Credentials are never taken from a URL; a component that needs them
|
||||
// sends them in a header to the host it is granted.
|
||||
if !parsed.username().is_empty() || parsed.password().is_some() {
|
||||
return Err(
|
||||
"URLs with credentials are not supported; send an Authorization header".to_owned(),
|
||||
);
|
||||
}
|
||||
// The method is written into the request line as given, so only known
|
||||
// methods are accepted.
|
||||
if !matches!(
|
||||
|
|
@ -424,6 +433,9 @@ fn host_fetch(
|
|||
}
|
||||
}
|
||||
let agent = ureq::AgentBuilder::new()
|
||||
.resolver(GrantedResolver(reach))
|
||||
// A proxy would be connected to instead of the checked address.
|
||||
.try_proxy_from_env(false)
|
||||
.redirects(0)
|
||||
.timeout_connect(Duration::from_secs(10))
|
||||
.timeout(Duration::from_secs(30))
|
||||
|
|
@ -458,6 +470,33 @@ fn host_fetch(
|
|||
})
|
||||
}
|
||||
|
||||
/// Resolves a fetch destination and keeps only the addresses its grant
|
||||
/// may reach; the connection is made to those addresses alone, so the
|
||||
/// check cannot be bypassed by a second, different DNS answer.
|
||||
#[cfg(all(feature = "wasmtime-runtime", feature = "net-fetch"))]
|
||||
struct GrantedResolver(grants::Reach);
|
||||
|
||||
#[cfg(all(feature = "wasmtime-runtime", feature = "net-fetch"))]
|
||||
impl ureq::Resolver for GrantedResolver {
|
||||
fn resolve(&self, netloc: &str) -> std::io::Result<Vec<std::net::SocketAddr>> {
|
||||
use std::net::ToSocketAddrs;
|
||||
let addresses: Vec<_> = netloc
|
||||
.to_socket_addrs()?
|
||||
.filter(|a| self.0 == grants::Reach::Declared || grants::is_public(a.ip()))
|
||||
.collect();
|
||||
if addresses.is_empty() {
|
||||
return Err(std::io::Error::new(
|
||||
std::io::ErrorKind::PermissionDenied,
|
||||
format!(
|
||||
"{netloc} resolves only to addresses on this machine or a local network, \
|
||||
which only a grant naming that address covers"
|
||||
),
|
||||
));
|
||||
}
|
||||
Ok(addresses)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(all(feature = "wasmtime-runtime", not(feature = "net-fetch")))]
|
||||
fn host_fetch(
|
||||
grants: &Grants,
|
||||
|
|
@ -470,55 +509,6 @@ fn host_fetch(
|
|||
Err("this runtime was built without network fetch support".to_owned())
|
||||
}
|
||||
|
||||
#[cfg(feature = "wasmtime-runtime")]
|
||||
fn host_clipboard_read() -> Result<String, String> {
|
||||
let out = std::process::Command::new("wl-paste")
|
||||
.arg("--no-newline")
|
||||
.output()
|
||||
.map_err(|e| e.to_string())?;
|
||||
if out.status.success() {
|
||||
String::from_utf8(out.stdout).map_err(|e| e.to_string())
|
||||
} else {
|
||||
Err(String::from_utf8_lossy(&out.stderr).trim().to_owned())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "wasmtime-runtime")]
|
||||
fn host_clipboard_write(text: &str) -> Result<(), String> {
|
||||
use std::io::Write;
|
||||
let mut child = std::process::Command::new("wl-copy")
|
||||
.stdin(std::process::Stdio::piped())
|
||||
.spawn()
|
||||
.map_err(|e| e.to_string())?;
|
||||
if let Some(stdin) = child.stdin.as_mut() {
|
||||
stdin
|
||||
.write_all(text.as_bytes())
|
||||
.map_err(|e| e.to_string())?;
|
||||
}
|
||||
let status = child.wait().map_err(|e| e.to_string())?;
|
||||
if status.success() {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(format!("wl-copy exited with {status}"))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "wasmtime-runtime")]
|
||||
fn host_notify(title: &str, body: &str, icon: Option<&str>) -> Result<(), String> {
|
||||
let mut cmd = std::process::Command::new("notify-send");
|
||||
if let Some(i) = icon {
|
||||
cmd.arg("--icon").arg(i);
|
||||
}
|
||||
cmd.arg("--").arg(title).arg(body);
|
||||
cmd.status().map_err(|e| e.to_string()).and_then(|s| {
|
||||
if s.success() {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(format!("notify-send exited with {s}"))
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(feature = "seccomp")]
|
||||
fn apply_seccomp_filter() -> anyhow::Result<()> {
|
||||
use seccompiler::{BpfProgram, SeccompAction, SeccompFilter, SeccompRule};
|
||||
|
|
@ -585,6 +575,7 @@ mod tests {
|
|||
#[test]
|
||||
fn engine_disabled_build_refuses_to_run_components() {
|
||||
let err = run_module(
|
||||
"org.weft.test",
|
||||
std::path::Path::new("app.wasm"),
|
||||
&[],
|
||||
Grants::default(),
|
||||
|
|
|
|||
|
|
@ -296,12 +296,25 @@ impl App {
|
|||
self.next_endpoint_check,
|
||||
));
|
||||
self.endpoint = appd_endpoint(self.ws_port);
|
||||
let (Some(endpoint), Some(webview)) = (&self.endpoint, &self.webview) else {
|
||||
let Some(endpoint) = &self.endpoint else {
|
||||
return;
|
||||
};
|
||||
// The credential goes only to the system UI document.
|
||||
let call = format!(
|
||||
"window.weftAppdEndpoint({}, '{}')",
|
||||
endpoint.port, endpoint.token
|
||||
);
|
||||
self.call_system_ui("weftAppdEndpoint", &call);
|
||||
}
|
||||
|
||||
/// Runs `call` in the system UI document if it defines the function
|
||||
/// `name`. Navigation away from the document is denied; the script
|
||||
/// checks the document again because a load can still be under way when
|
||||
/// it runs.
|
||||
fn call_system_ui(&self, name: &str, call: &str) {
|
||||
let Some(webview) = &self.webview else {
|
||||
return;
|
||||
};
|
||||
// The credential goes only to the system UI document. Navigation away
|
||||
// from it is denied; the script checks the document again because a
|
||||
// load can still be under way when it runs.
|
||||
if !webview
|
||||
.url()
|
||||
.is_some_and(|url| same_document(url.as_str(), self.url.as_str()))
|
||||
|
|
@ -313,9 +326,8 @@ impl App {
|
|||
format!(
|
||||
"window === window.top && \
|
||||
location.href.split('#')[0] === {document} && \
|
||||
typeof window.weftAppdEndpoint === 'function' && \
|
||||
window.weftAppdEndpoint({}, '{}')",
|
||||
endpoint.port, endpoint.token
|
||||
typeof window.{name} === 'function' && \
|
||||
{call}"
|
||||
),
|
||||
|_| {},
|
||||
);
|
||||
|
|
@ -346,6 +358,19 @@ impl App {
|
|||
}
|
||||
|
||||
impl ApplicationHandler<ServoWake> for App {
|
||||
/// Releases everything that holds Wayland objects of winit's display
|
||||
/// (Servo, the rendering context, whose software and EGL paths keep
|
||||
/// their own proxies on it, the shell protocol client and the window)
|
||||
/// while that display is still connected; dropped after the event loop,
|
||||
/// they would be destroyed on a display that is gone. A panic unwinding
|
||||
/// out of a handler skips this.
|
||||
fn exiting(&mut self, _event_loop: &ActiveEventLoop) {
|
||||
self.shut_down();
|
||||
self.rendering_context = None;
|
||||
self.shell_client = None;
|
||||
self.window = None;
|
||||
}
|
||||
|
||||
fn resumed(&mut self, event_loop: &ActiveEventLoop) {
|
||||
if self.window.is_some() {
|
||||
return;
|
||||
|
|
@ -481,6 +506,11 @@ impl ApplicationHandler<ServoWake> for App {
|
|||
WindowEvent::ModifiersChanged(mods) => {
|
||||
self.modifiers = mods.state();
|
||||
}
|
||||
// Servo does not tell the page when its window loses keyboard
|
||||
// focus; the system UI closes its launcher then.
|
||||
WindowEvent::Focused(false) => {
|
||||
self.call_system_ui("weftShellBlurred", "window.weftShellBlurred()");
|
||||
}
|
||||
WindowEvent::KeyboardInput { event, .. } => {
|
||||
if let Some(wv) = &self.webview {
|
||||
let ev = super::keyutils::keyboard_event_from_winit(&event, self.modifiers);
|
||||
|
|
|
|||
|
|
@ -57,7 +57,8 @@ fn named_key(n: NamedKey) -> servo::NamedKey {
|
|||
NamedKey::Control => S::Control,
|
||||
NamedKey::Fn => S::Fn,
|
||||
NamedKey::FnLock => S::FnLock,
|
||||
NamedKey::Meta => S::Meta,
|
||||
// winit names the Super keys Super; the DOM names them Meta.
|
||||
NamedKey::Meta | NamedKey::Super => S::Meta,
|
||||
NamedKey::NumLock => S::NumLock,
|
||||
NamedKey::ScrollLock => S::ScrollLock,
|
||||
NamedKey::Shift => S::Shift,
|
||||
|
|
|
|||
|
|
@ -9,6 +9,11 @@ use crate::protocols::{
|
|||
client::{zweft_shell_manager_v1, zweft_shell_window_v1},
|
||||
};
|
||||
|
||||
/// Height in logical pixels of the taskbar strip the system UI draws along
|
||||
/// the bottom of the output; it matches `--taskbar-height` in
|
||||
/// `infra/shell/system-ui.html`.
|
||||
pub const TASKBAR_HEIGHT: i32 = 48;
|
||||
|
||||
// ── Window state ──────────────────────────────────────────────────────────────
|
||||
|
||||
pub struct ShellWindowState {
|
||||
|
|
@ -72,7 +77,7 @@ impl Dispatch<wl_registry::WlRegistry, ()> for AppData {
|
|||
} = event
|
||||
&& interface == "zweft_shell_manager_v1"
|
||||
{
|
||||
let mgr = registry.bind::<ZweftShellManagerV1, _, _>(name, version.min(2), qh, ());
|
||||
let mgr = registry.bind::<ZweftShellManagerV1, _, _>(name, version.min(3), qh, ());
|
||||
state.manager = Some(mgr);
|
||||
}
|
||||
}
|
||||
|
|
@ -213,6 +218,11 @@ impl ShellClient {
|
|||
&qh,
|
||||
(),
|
||||
);
|
||||
// The taskbar's strip at the bottom of the output is kept free of
|
||||
// application windows.
|
||||
if window.version() >= 3 {
|
||||
window.set_exclusive_zone(zweft_shell_window_v1::Edge::Bottom, TASKBAR_HEIGHT);
|
||||
}
|
||||
data.window = Some(window);
|
||||
|
||||
event_queue
|
||||
|
|
|
|||
|
|
@ -8,19 +8,19 @@ 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`). The compositor owns stacking and focus: the system shell's panel is sized to the output and starts beneath application windows, and clicking it brings it to the front as the shell's home, with its launcher, until an application is activated or opens its first window; layout changes keep the stacking order, and a window that maps without taking focus goes beneath the window in front; a session's first window, a clicked window and an activated one are raised, marked activated and given keyboard focus, and when the focused window closes the topmost remaining application window gets focus. Alt+F4 is the compositor's: it asks the focused application window to close (never the panel), and the app shell then exits and its session ends. The Super keys are the compositor's too and never reach an application: a Super tap, pressed and released without another key or a pointer button, brings the panel (the first registered) to the front with keyboard focus and then delivers the tap to it, so the shell's launcher is reachable from any application; keys pressed while Super is held reach the focused window with the Super modifier, but Super's own key events do not. A session's later windows are shown without taking focus. The panel reserves a strip along an output edge for the taskbar with `set_exclusive_zone` (weft-servo-shell reserves 48 logical pixels at the bottom), and the compositor lays every application window out to fill the remaining work area. weft-appd's `ACTIVATE_APP` request, which the taskbar sends, asks the compositor to activate a running session's window. Supports DRM/KMS and winit (software/dev) backends.
|
||||
|
||||
### weft-servo-shell
|
||||
|
||||
System UI host. Renders one WebView pointing at `system-ui.html` using the embedded Servo engine (feature-gated behind `servo-embed`). Connects to the compositor as window type `panel`. Dispatches the `zweft_shell_manager_v1` event queue each frame. Forwards navigation gestures received from the compositor to `weft-appd` over WebSocket. Reads the appd WebSocket port and system token from `$XDG_RUNTIME_DIR/weft/` and hands both to the page through `window.weftAppdEndpoint(port, token)`; the shell hands the token only to the system UI document and denies top-level navigation away from it, and the launcher shows package names as text, never markup.
|
||||
System UI host. Renders one WebView pointing at `system-ui.html` using the embedded Servo engine (feature-gated behind `servo-embed`). Connects to the compositor as window type `panel`. Dispatches the `zweft_shell_manager_v1` event queue each frame. Forwards navigation gestures received from the compositor to `weft-appd` over WebSocket. Reads the appd WebSocket port and system token from `$XDG_RUNTIME_DIR/weft/` and hands both to the page through `window.weftAppdEndpoint(port, token)`; the shell hands the token only to the system UI document and denies top-level navigation away from it, and the launcher shows package names as text, never markup. The system UI works from the keyboard: a Super tap opens or closes the launcher, which lists installed apps by name and keeps focus while open (Tab moves between apps, Enter opens one, Escape closes it and returns focus to the Apps button, with the shell's home still in front); every taskbar entry and its close button is a button reachable with Tab, and Enter on an entry brings its app back. The shell tells the page through `window.weftShellBlurred()` when it loses keyboard focus, which Servo does not report to the document, and the launcher closes. The page has no transitions or animations, since Servo does not evaluate `prefers-reduced-motion`.
|
||||
|
||||
### weft-app-shell
|
||||
|
||||
Per-application Servo host. Spawned by `weft-appd` after the Wasm runtime signals READY. Takes `<app_id>`, `<session_id>` and `--ui <path>`, the UI document weft-appd resolved from the package; it never looks for the package itself. Injects the `weftIpc` WebSocket bridge into the page. The bridge authenticates with the per-session token from `WEFT_BRIDGE_TOKEN` and can only exchange messages with its own session. It is installed only in top-level documents inside the application's UI directory, and top-level navigation outside that directory is denied; framed documents never receive the bridge. Every resource the page loads (subresources, `fetch()`, XHR, workers and WebSocket handshakes) is checked by the shell: the page may load files inside its UI directory, also after symbolic links are resolved, inline `data:` and `blob:` resources, `about:blank` and the session bridge; any other local file or network destination, and every redirect, fails with a network error. Loads Servo does not attribute to the webview, such as `navigator.sendBeacon()`, are all refused. Network access belongs to the Wasm component, under its fetch grants. Servo's privileged `navigator.servo` interface, which can change engine preferences, is not exposed to `about:blank` or `about:srcdoc` documents (a fork patch; see `crates/weft-servo-shell/SERVO_PIN.md`). Registers with the compositor as window type `application`. Exits when the appd session ends.
|
||||
Per-application Servo host. Spawned by `weft-appd` after the Wasm runtime signals READY. Takes `<app_id>`, `<session_id>` and `--ui <path>`, the UI document weft-appd resolved from the package; it never looks for the package itself. Injects the `weftIpc` WebSocket bridge into the page. The bridge authenticates with the per-session token from `WEFT_BRIDGE_TOKEN` and can only exchange messages with its own session. It is installed only in top-level documents inside the application's UI directory, and top-level navigation outside that directory is denied; framed documents never receive the bridge. Every resource the page loads (subresources, `fetch()`, XHR, workers and WebSocket handshakes) is checked by the shell: the page may load files inside its UI directory, also after symbolic links are resolved, inline `data:` and `blob:` resources, `about:blank` and the session bridge; any other local file or network destination, and every redirect, fails with a network error. Loads Servo does not attribute to the webview, such as `navigator.sendBeacon()`, are all refused. Network access belongs to the Wasm component, under its fetch grants. Servo's privileged `navigator.servo` interface, which can change engine preferences, is not exposed to `about:blank` or `about:srcdoc` documents (a fork patch; see `crates/weft-servo-shell/SERVO_PIN.md`). Registers with the compositor as window type `application`, 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
|
||||
|
||||
Session supervisor. Listens on a Unix socket (MessagePack protocol) and a WebSocket port (JSON). Before a session exists, appd resolves the package once (see [Package resolution](#package-resolution)) and derives its grants from that package's manifest; the runtime and the app shell receive the resolved component and UI document and do not search the stores themselves. For each session: spawns `weft-runtime` and waits for its READY, spawns `weft-app-shell` (`WEFT_APP_SHELL_BIN` is required) and waits for its READY, and only then reports the session running (`APP_READY`). A child reports readiness by printing `READY <token>` on stdout, where the token is a random per-session value appd passes in `WEFT_READY_TOKEN`; Wasm guests and pages share those stdout streams but cannot read the token, so their output cannot fake readiness. The two children log to stderr, which appd records at info level; their stdout carries the readiness line, and anything else printed there is recorded only at debug level. Each wait times out after 30 seconds. If either child fails to start, fails to become ready or exits, or the session is terminated, the whole session is stopped: both children, the IPC relay (its task, socket and registered sender), the file portal, the compositor association and any image mount are released. The IPC relay is created with the session in `$XDG_RUNTIME_DIR/weft` (a session cannot start without it); its socket is accessible only to the user and accepts a single connection, which the session's runtime makes before it starts the component. If that connection closes while the session runs, the session is stopped. `IPC_FORWARD` on the Unix socket never waits: it reports an error when the session has no relay or its queue is full. appd applies cgroup resource limits to the runtime via systemd-run when available.
|
||||
Session supervisor. Listens on a Unix socket (MessagePack protocol) and a WebSocket port (JSON). Before a session exists, appd resolves the package once (see [Package resolution](#package-resolution)) and derives its grants from that package's manifest; the runtime and the app shell receive the resolved component and UI document and do not search the stores themselves. For each session: spawns `weft-runtime` and waits for its READY, spawns `weft-app-shell` (`WEFT_APP_SHELL_BIN` is required) and waits for its READY, and only then reports the session running (`APP_READY`). A child reports readiness by printing `READY <token>` on stdout, where the token is a random per-session value appd passes in `WEFT_READY_TOKEN`; Wasm guests and pages share those stdout streams but cannot read the token, so their output cannot fake readiness. The two children log to stderr, which appd records at info level; their stdout carries the readiness line, and anything else printed there is recorded only at debug level. Each wait times out after 30 seconds. `TERMINATE_APP` on a running session closes it as a user close would: appd asks the compositor to close the session's windows and gives the app shell 5 seconds to exit by itself, for example after saving, before terminating it. The session stays `running` while the application answers (appd replies with that state), and enters `stopping` only once it is ending. An application that declares the `ask` close policy may decline the close (see [Closing an application](#closing-an-application)); its window is brought to the front and the session keeps running. A repeated request while the application answers changes nothing, and a session being asked to close is still restored at the next start if appd stops meanwhile. `TERMINATE_APP` with `"force": true` terminates the session without asking; the taskbar offers it, as Force quit, for an app still running once it has had time to answer. The stop reason records what happened: a close on request with a clean exit, a failure while closing, the timeout, or a forced stop; `stopped` is broadcast once the session has settled. A session still starting is stopped at once, also when the request races its readiness, and when appd itself shuts down its sessions are terminated without a close. appd keeps the final state of at most 32 stopped sessions, forgetting those launched earliest. If either child fails to start, fails to become ready or exits, or the session is terminated, the whole session is stopped: both children, the IPC relay (its task, socket and registered sender), the file portal, the compositor association and any image mount are released. The IPC relay is created with the session in `$XDG_RUNTIME_DIR/weft` (a session cannot start without it); its socket is accessible only to the user and accepts a single connection, which the session's runtime makes before it starts the component. If that connection closes while the session runs, the session is stopped. `IPC_FORWARD` on the Unix socket never waits: it reports an error when the session has no relay or its queue is full. appd applies cgroup resource limits to the runtime via systemd-run when available.
|
||||
|
||||
### weft-runtime
|
||||
|
||||
|
|
@ -28,11 +28,11 @@ WASI Preview 2 + Component Model execution host (Wasmtime 30). Runs the componen
|
|||
|
||||
### weft-pack
|
||||
|
||||
Package management CLI. Subcommands: `check` (validate wapp.toml + wasm module), `sign` (Ed25519 signature), `verify` (verify signature), `generate-key`, `install`, `uninstall`, `list`, `build-image` (EROFS dm-verity), `info`.
|
||||
Package management CLI. Subcommands: `check` (validate wapp.toml, entries and package content), `sign` (Ed25519 signature over every file), `verify` (verify signature), `generate-key`, `install` (requires a signature by a trusted key unless `--dev`; records the app ID's owner; installs or updates, see [Installing and updating](#installing-and-updating)), `uninstall`, `rollback`, `approve` (approve the app's declared capabilities, or those listed; `install --approve` does so at installation), `list`, `build-image` (EROFS dm-verity), `info`.
|
||||
|
||||
### weft-file-portal
|
||||
|
||||
Per-session file proxy. Runs as a separate process with a path allowlist derived from the session's directory grants; read-only grants (`--allow-read`) refuse writes. Paths are checked lexically, so `..` is blocked but symbolic links are followed. Accepts JSON-lines requests over a Unix socket. Components cannot currently reach that socket, because the runtime grants them no socket access.
|
||||
Per-session file proxy. Runs as a separate process with the session's directory grants; read-only grants (`--allow-read`) refuse writes. Every operation is resolved beneath the granted directory's descriptor by the kernel (see security.md), with bounded file, listing and request sizes. Accepts JSON-lines requests over a Unix socket. Components cannot currently reach that socket, because the runtime grants them no socket access.
|
||||
|
||||
### weft-mount-helper
|
||||
|
||||
|
|
@ -83,14 +83,16 @@ Each capability-controlled host import (fetch, notifications, clipboard) checks
|
|||
| `fs:read:app-data` / `fs:rw:app-data` | Preopen the app's data directory (see *App data*) as `/data`, read-only or read-write |
|
||||
| `fs:read:xdg-documents` / `fs:rw:xdg-documents` | Preopen the documents directory from the XDG user-dirs configuration (`XDG_DOCUMENTS_DIR`) as `/xdg/documents`; the launch fails when none is configured |
|
||||
| `net:fetch:<host>` | `weft:app/fetch` to that exact host (a lowercase DNS name or dotted IPv4 address) over HTTP or HTTPS, on any port |
|
||||
| `net:fetch:*` | `weft:app/fetch` to any host |
|
||||
| `net:fetch:*` | `weft:app/fetch` to any host at a public address |
|
||||
| `sys:notifications` | `weft:app/notifications` |
|
||||
| `sys:clipboard:read` / `sys:clipboard:write` | `weft:app/clipboard#read` / `#write` |
|
||||
| `hw:gpu:compute` / `hw:gpu:render` | Not supported; the launch fails |
|
||||
|
||||
Clipboard and notifications run `wl-paste`, `wl-copy` and `notify-send` from the runtime's environment, each bounded to 5 seconds, after which the helper is killed and the call fails. Clipboard text is UTF-8, of any text type, and at most 1 MiB in either direction. A notification's title is at most 256 bytes and its body 4096, sent as plain text with markup escaped; its icon must be an icon theme name, not a path or URL; and it is sent with the app's ID as the application name, so an app cannot pass a notification off as the system's. Where a helper is not installed the call fails with that error.
|
||||
|
||||
Fetch does not follow redirects: a redirect is returned to the component as a response, so every destination it requests is checked against its grants. HTTP error statuses are responses too; only policy and transport failures are errors. Only the methods GET, HEAD, POST, PUT, PATCH, DELETE and OPTIONS are accepted, and a component cannot set `Host`, `Content-Length`, `Transfer-Encoding` or other hop-by-hop headers. Connecting times out after 10 seconds and the whole request after 30 seconds, not counting DNS resolution; response bodies are limited to 16 MiB. Fetch requires a runtime built with the `net-fetch` feature.
|
||||
|
||||
Fetch grants name hosts, not addresses: ports are not restricted, and a host that resolves to a loopback or private address (or `net:fetch:*`) can reach local services. IPv6 literals cannot be granted.
|
||||
The runtime resolves a fetch destination itself and connects only to the addresses it allows. A grant for a name, and `net:fetch:*`, reach only public unicast addresses: loopback, unspecified, private, shared (100.64/10), link-local, multicast, broadcast, reserved, documentation and benchmarking addresses, and their IPv6 counterparts (unique local, site-local, Teredo and others), are refused, and an IPv6 address that carries an IPv4 address (mapped, compatible, translated, 6to4, NAT64) is judged by that address, so DNS cannot point a granted name at this machine or the local network. An IPv4 address named in a grant, such as `net:fetch:127.0.0.1`, is reached as declared. Fetch never goes through a proxy. Ports are not restricted. Credentials in a URL are refused; a component sends credentials in a header, and only to a host it is granted, since redirects are not followed. IPv6 literals cannot be granted.
|
||||
|
||||
`tests/runtime/check_grants.py` runs the real runtime on a probe component (`tests/components/grants-probe`) under each kind of grant.
|
||||
|
||||
|
|
@ -102,7 +104,7 @@ Fetch grants name hosts, not addresses: ports are not restricted, and a host tha
|
|||
app.wasm — WASI Component Model binary
|
||||
ui/
|
||||
index.html — entry point served by weft-app-shell
|
||||
signature.sig — Ed25519 signature over SHA-256 of (wapp.toml + app.wasm)
|
||||
signature.sig — Ed25519 signature over the content digest of every other file (see security.md)
|
||||
```
|
||||
|
||||
Package store roots (in priority order):
|
||||
|
|
@ -115,11 +117,30 @@ Package store roots (in priority order):
|
|||
`weft-appd` resolves a launch once. A verified image in any store root takes precedence over a directory install in any root, so a user's directory cannot shadow a system image; otherwise the first root with a directory install is used:
|
||||
|
||||
- **Verified image:** `<root>/<id>.app.img` with its dm-verity hash tree `<id>.app.hash` and root hash `<id>.app.roothash`, the names `weft-pack build-image` and `build-verity` produce. When any of the three exists, the image must mount through `weft-mount-helper`; a missing companion, a malformed root hash, a missing helper or a failed mount refuses the launch, and appd never falls back to a directory install. The root hash is read from the store next to the image and is not yet authenticated, so dm-verity detects corruption but not a store whose image, hash tree and root hash were replaced together. The mount belongs to the session and is released when the session stops.
|
||||
- **Directory install:** `<root>/<id>/wapp.toml`.
|
||||
- **Directory install:** `<root>/<id>`, a link to the active revision `.revisions/<id>/<digest>` written by `weft-pack`, or, for a store written before revisions, a package directory. A link is followed only in exactly that form, to one of the app's own revisions; any other link is refused (403). The session runs from the revision directory itself and holds a shared lock on it until it stops, so it keeps its bytes while an update or rollback switches the link.
|
||||
|
||||
The package root must be a directory and its manifest a regular file, neither a symbolic link, and the manifest must declare the requested ID. `[runtime].module` and `[ui].entry` must be relative paths of plain components, without symbolic links, naming regular files inside that root. The component, the UI document and the capabilities all come from that one manifest. A refused launch reports 400 (invalid ID), 404 (not installed), 403 (invalid package, image or image metadata) or 500 (the host cannot read the package or mount the image).
|
||||
|
||||
A directory install can still be changed by its owner while a session runs, and nothing verifies its content at launch.
|
||||
A directory install can still be changed by its owner while a session runs; for a verified owner, appd checks its content against the signature at launch, with the limits security.md describes.
|
||||
|
||||
### Installing and updating
|
||||
|
||||
`weft-pack install` copies the package into a staging directory in the store and checks, verifies and admits that copy, so the bytes that are checked are the bytes that are installed. The copy is flushed to disk and renamed to an immutable revision named by its content digest, `<root>/.revisions/<id>/<digest>`; installing the same content again reuses it. One rename of the link `<root>/<id>` then makes it active. The rename of the link is the commit point. An installation that fails before it leaves the previously active revision active, or, for a first installation, nothing installed; a failed first installation also removes the owner record it created, while one interrupted by a crash leaves that record until `weft-pack uninstall <id>` releases it. After the commit point the update stands, and what an interruption leaves to tidy is collected later. A revision is reused only when it still holds the same content and signature file; otherwise the new copy replaces it in one exchange, unless a running session uses it. Such a replacement, for the same content with another signature file, is visible under the revision's name at once, even if the installation then fails. A package directory from before revisions is replaced in one exchange with the new link, only while no session runs from it and only after the app data an earlier weft-appd kept in its `data` directory has been moved to the app data directory, under the same rules as for uninstall; otherwise the update stops before replacing anything. Data moved this way stays in the app data directory even if the update is then refused.
|
||||
|
||||
The revision active before an update is kept for `weft-pack rollback <id>`, which makes it active again, keeping the revision it replaces in turn; it is checked against the owner record again, so a revision whose publisher key was withdrawn is not rolled back to. Other revisions are removed by each install, rollback or uninstall of the app, except those a session still runs from; those stay until a later operation on the app finds them unused. Temporary links of interrupted activations are removed then too, and staging, unpacking and removal directories once they are an hour old. `weft-pack uninstall` removes the link, so new launches no longer find the app, and the kept revision; running sessions continue on their revisions. Apart from that move of data from the earlier layout, app data is never touched by these operations. Package revisions and app data are independent: rolling back a package does not roll back its data.
|
||||
|
||||
A launch is refused (500, try again) while a package operation holds the revision it would run from, rather than waiting for it. Only sessions started by this weft-appd hold their revisions: a session left from an earlier version, or processes that outlive weft-appd, do not, and a package directory from before revisions such sessions run from can be replaced under them. Package operations on one app are serialised by the owner lock in the data home of the user running them; the store itself is not locked against users with other data homes.
|
||||
|
||||
## Closing an application
|
||||
|
||||
A user closes an application from the taskbar, which sends `TERMINATE_APP`, or with Alt+F4 in the compositor; both ask the application's window to close. What happens next is the application's declared unsaved-change policy, `[ui].close` in `wapp.toml`:
|
||||
|
||||
- `immediate` (the default): the app shell exits at once.
|
||||
- `ask`: the app shell dispatches a cancelable `weftclose` event on the page's top-level window and waits up to 2 seconds for it to be handled. If no listener calls `preventDefault()`, or the page does not answer in time, the app shell exits. Otherwise the close is declined: the app shell reports this to weft-appd with its readiness token on standard output, so page output cannot forge it, and the session keeps running. The page then lets the user decide, and closes itself with `window.close()`, which Servo allows while the top-level document has a single history entry. A clean exit after a close request, including one the page makes after declining, is recorded as a close on request. A report still unread when a new request arrives can answer that request early; the app shell still closes a page that does not answer.
|
||||
|
||||
Notes uses `ask`: with unsaved changes it offers "Save and close", which closes only after the save is acknowledged and stays open with the error shown when the save fails, "Close without saving", and Cancel.
|
||||
|
||||
The close timeout of weft-appd still applies to a close that is not declined: an app shell that neither exits nor declines within 5 seconds is terminated, and the stop reason says so. An application can decline every close, so a forced stop never asks it: it is the user's way to end an application that will not close. A forced stop, the timeout, a crash and appd's own shutdown are never reported as a close on request, and say nothing about whether the application saved.
|
||||
|
||||
## App data
|
||||
|
||||
|
|
@ -147,5 +168,4 @@ A package directory left empty by the move is removed. Nothing is moved, and `we
|
|||
| `WEFT_APPD_WS_PORT` | `7410` | WebSocket port for weft-appd |
|
||||
| `WEFT_EGL_RENDERING` | — | Set to `1` to use EGL rendering in Servo shell |
|
||||
| `WEFT_DISABLE_CGROUP` | — | Set to disable systemd-run cgroup wrapping |
|
||||
| `WEFT_FILE_PORTAL_SOCKET` | — | Path forwarded to app runtime for file portal |
|
||||
| `XDG_RUNTIME_DIR` | — | Standard XDG runtime dir (sockets written here) |
|
||||
|
|
|
|||
|
|
@ -85,9 +85,12 @@ same nested desktop and drive the demo apps with real keyboard input:
|
|||
|
||||
```sh
|
||||
python3 tests/frame/check_counter.py # Counter round trip through the session bridge
|
||||
python3 tests/frame/check_notes.py # Notes stores exactly what is typed, refuses stale saves
|
||||
python3 tests/frame/check_notes.py # Notes stores exactly what is typed, refuses stale saves, asks before closing unsaved text
|
||||
python3 tests/frame/check_app_data.py # Notes data from the earlier layout is moved and kept
|
||||
python3 tests/frame/check_confinement.py # an app page reaches only its UI files and its session bridge
|
||||
python3 tests/frame/check_activation.py # apps fill the work area above the taskbar; launch and ACTIVATE_APP raise and focus
|
||||
python3 tests/frame/check_system_ui.py # the system UI's launcher and taskbar work from the keyboard alone, reached with a Super tap
|
||||
python3 tests/frame/check_update.py # updates leave running sessions on their revision; failed updates, rollback and uninstall
|
||||
```
|
||||
|
||||
## Demo apps (wasm32-wasip2)
|
||||
|
|
@ -125,6 +128,16 @@ weft-pack sign ./examples/org.weft.demo.counter --key ./keys/weft-sign.key
|
|||
weft-pack verify ./examples/org.weft.demo.counter --key ./keys/weft-sign.pub
|
||||
```
|
||||
|
||||
Installation requires a signature by a trusted key. To install the demos with the demo key, trust it for your user (the key is a test fixture; do not trust it on a system you depend on):
|
||||
|
||||
```sh
|
||||
mkdir -p ~/.config/weft/trusted-keys
|
||||
cp examples/keys/weft-sign.pub ~/.config/weft/trusted-keys/weft-demo.pub
|
||||
weft-pack install examples/org.weft.demo.notes
|
||||
```
|
||||
|
||||
Unsigned packages under development install with `weft-pack install <dir> --dev`, recorded as development content and marked `(development)` by `weft-pack list`. See `docs/security.md` for the trust store and app ID ownership.
|
||||
|
||||
## NixOS VM (requires Nix with flakes)
|
||||
|
||||
Build the VM image:
|
||||
|
|
|
|||
|
|
@ -8,7 +8,9 @@ WEFT OS enforces a capability-based security model. No capability is granted by
|
|||
|
||||
`weft-pack check` validates capability strings against the shared vocabulary in `weft_ipc_types::capability`. Unknown capability strings are rejected. At launch, `weft-appd` derives the session's grants from the manifest and refuses to start a package with a capability that is unknown, unsupported or unsatisfiable. `weft-runtime` enforces the grants it is given: read-only directories are preopened read-only, and each host import checks its grant on every call. See the capability table in `architecture.md`.
|
||||
|
||||
Installing a package does not yet ask the user to approve its capabilities; every declared, supported capability is granted at launch.
|
||||
A package gets only the capabilities the user approved. `weft-pack install --approve` approves those the installed package declares. `weft-pack approve <id>` approves those of the package weft-appd would launch, the first store in weft-appd's order that holds the app, which also covers packages in the system store. `weft-pack approve <id> <capability>...` adds the listed capabilities to the app's approval; for a package weft-pack can read they must be ones it declares. Listing them is the only way to approve an app installed as a verified image, since weft-pack cannot read an image's manifest; for the same reason, approvals for an image are not reduced when it is updated, and uninstalling a directory copy of the app removes them although the image remains. Without approval, `install` and `rollback` list what still needs it.
|
||||
|
||||
The approval is recorded per user, in `$XDG_DATA_HOME/weft/approvals/<id>`; weft-pack and weft-appd must use the same data home, as for owner records. An installation by another user, such as root installing into the system store, approves nothing for this user. weft-appd refuses to launch an app that declares a capability the record does not hold (403, naming the capabilities), after refusing unknown and unsupported capabilities and before preparing anything for the session. An approval covers what the installed package declares: an update or rollback drops approvals for capabilities the package no longer declares, so a capability declared again later, or newly, needs approval again. Uninstalling the app forgets its approval unless another store still holds the app. Approvals are keyed by app ID, not by store or publisher. Private app data (`fs:read:app-data`, `fs:rw:app-data`) is a minimal execution resource and needs no approval. Signature verification and approval are separate decisions: a trusted signature approves nothing.
|
||||
|
||||
## Process Isolation
|
||||
|
||||
|
|
@ -16,13 +18,21 @@ Each app session runs as a separate OS process (`weft-runtime`). When systemd is
|
|||
|
||||
## Filesystem Isolation
|
||||
|
||||
Apps access the filesystem only through WASI preopened directories. Each capability maps to a specific host path preopened at a fixed guest path. The `weft-file-portal` process applies the same directory grants and access modes, but checks paths lexically: it blocks `..` traversal, not symbolic links. Components cannot currently reach its socket, since the runtime grants them no socket access.
|
||||
Apps access the filesystem only through WASI preopened directories. Each capability maps to a specific host path preopened at a fixed guest path. The `weft-file-portal` process applies the same directory grants and access modes. It opens each granted directory once and resolves every request beneath that descriptor with `openat2(RESOLVE_BENEATH)`, so the kernel keeps the operation inside the directory: `..` and links pointing outside are refused, also when a link is swapped in while the operation runs; links that stay inside are followed. This needs Linux 5.6 or later; without `openat2` every operation fails. Requests must name an absolute path without `.`, `..` or empty components; files are limited to 16 MiB, listings to 10,000 entries, requests to one line of about 22 MiB, and the portal to 4 connections at a time, each closed when it sends or accepts no data for 60 seconds. Writes replace a file atomically, keeping its permission bits but not its owner, extended attributes or hard links (a write to a name that is a link replaces the link), and never create directories. A granted directory that cannot be opened when the portal starts is not served. Components cannot currently reach its socket, since the runtime grants them no socket access, and the socket's path is not passed to them.
|
||||
|
||||
## Package Signing
|
||||
## Package Signing and Trust
|
||||
|
||||
Packages are signed with Ed25519 (`ed25519-dalek`). The signature covers the SHA-256 hash of `wapp.toml` and `app.wasm`. `weft-pack verify` checks the signature before installation.
|
||||
Packages are signed with Ed25519 over their content digest: the SHA-256 of an inventory listing every file in the package except the root `signature.sig`, one `<path>\t<sha-256>` line per file sorted by path. Every file is covered, including the UI. Names must be UTF-8 without control characters, so no name can imitate other inventory lines. Packages may hold only directories and regular files; a symbolic link or special file makes `weft-pack check`, `sign`, `verify` and `install` refuse the package. The committed demo signatures verify under this rule.
|
||||
|
||||
For verified read-only package storage, `weft-pack build-image` produces an EROFS image protected with dm-verity. Mounting requires the setuid `weft-mount-helper` which calls `veritysetup`.
|
||||
`weft-pack install` admits a package only when its signature verifies with a key in the trust store: `*.pub` files (64 hex digits) in `$XDG_CONFIG_HOME/weft/trusted-keys` and `/etc/weft/trusted-keys`, or only in `$WEFT_TRUSTED_KEYS` when that is set. A malformed key file is an error, not skipped. An unsigned or untrusted package is refused unless the developer passes `--dev`, which installs it as development content. The package is copied into the store first and checked on that copy, which is then renamed into place, so the bytes that are verified are the bytes that are installed. The copy holds each source directory open and opens its entries relative to it, never following links, so replacing a directory with a link while the copy runs cannot redirect it. Each entry must keep the type, device and inode it had when it was examined just before it was opened, and a FIFO is never waited on. A device node hard-linked in place of a file in that interval is opened before it is refused; `fs.protected_hardlinks`, on by default, prevents such links to devices unless the attacker owns them or holds CAP_FOWNER. Installed files are set to 0644, or 0755 when the source is executable, and directories to 0755, whatever the umask, so no installed file is writable by other users; a store, and any of its parents, that does not exist yet is created at 0755. The app ID is read from the staged copy. Archives are unpacked into a fresh private directory in the store, which is always removed.
|
||||
|
||||
The first installation of an app ID records its owner in `$XDG_DATA_HOME/weft/owners/<id>`: the publisher key, or development. Installations and uninstallations of one ID under one data home hold a per-ID lock, so concurrent installations cannot leave a placed package without its record. Every later installation of that ID must have the same owner, so neither another trusted publisher nor a development build can take over an ID, and with it the app's data. The record survives uninstall while the app's data remains; uninstalling with no data left frees the ID. App data with no recorded owner, as left by installations from before owner records, is given to a new owner only with `--claim-data`. A record is written under a temporary name and linked into place, so it is never partial, and a record created by an installation that then fails to place its package is removed. A record left by an installation that was killed before placing its package is released by `weft-pack uninstall <id>` once no data remains. A record is only released while no known store (the user store, the system store and `$WEFT_APP_STORE`) holds the package; a package installed into another custom store is uninstalled with that store selected. The demo key in `examples/keys` is a test fixture, not a signing authority.
|
||||
|
||||
`weft-appd` checks every package again before a session starts. A package recorded as a publisher's runs only while that key is still trusted and its signature covers the package's current content. A package with no record runs only when a trusted key signed it, and that key is then recorded as its owner; if app data already exists for the ID without a recorded owner, in the current layout or the earlier one that is migrated at launch, the launch is refused rather than handing the data to that publisher; `weft-pack install` applies the same rule unless given `--claim-data`. The record is written before the session starts, so it remains even if that first launch then fails; `weft-pack uninstall` releases it once no data exists in either layout and no known store holds the package. Finding earlier-layout data needs `HOME`: without an absolute `HOME`, a first launch is refused (500), a first install fails unless it claims the data, and uninstall keeps the record. While an ID is recorded as development content, whatever package is found for it runs unverified, from any store. A changed package, or one whose key was removed from the trust store, is refused with code 403; a damaged trust store or owner record is a host error, 500. The manifest is read once and its bytes must be the ones in the verified inventory, so a session's capabilities and entries come from the signed manifest. The module and UI files are read again when the session starts, so a directory install changed by its owning user after the check, or while the session runs, is not detected; verified images are not writable.
|
||||
|
||||
Not yet covered: key rotation and ownership transfer have no workflow, and removing a key is the only revocation; and capabilities are granted at launch without asking the user, independently of the signature.
|
||||
|
||||
For verified read-only package storage, `weft-pack build-image` produces an EROFS image protected with dm-verity. Mounting requires the setuid `weft-mount-helper` which calls `veritysetup`. The image's root hash is not yet authenticated (see `architecture.md`).
|
||||
|
||||
## Seccomp
|
||||
|
||||
|
|
@ -30,7 +40,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 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; close is not yet decided by the compositor per session; there is no user placement or resizing, since application windows fill the work area the panel leaves, one in front at a time; only the first window a session maps in its lifetime takes keyboard focus when it maps, and a client connected through the display socket takes focus on map only while no other such window is mapped; 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. Such a client registered as a panel would also be raised and focused by a Super tap; the compositor picks the first panel registered.
|
||||
|
||||
## JavaScript Engine (SpiderMonkey)
|
||||
|
||||
|
|
|
|||
|
|
@ -1 +1 @@
|
|||
e8c10750b142b9df4405fd33ea0c060e63d44b5293e7f9ffa5b076989146b05e81f716e9b92aaeeb139ce1dc9b13ed26f356385d6a61a19c7f3dcaf6e95d2d03
|
||||
3c5155af4973c453e5c09b04aa0eaf71e943b6564d9aaa81a5fb023fe3ebea091a793ef493234a5a862b9752acf7cafbb0d11a2ec9c962331606ebde75c7b803
|
||||
|
|
@ -80,6 +80,15 @@
|
|||
font-size: 12px;
|
||||
color: #444;
|
||||
}
|
||||
#closing {
|
||||
display: none;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
flex-shrink: 0;
|
||||
font-size: 13px;
|
||||
}
|
||||
#closing.shown { display: flex; }
|
||||
#closing span { flex: 1; }
|
||||
#charcount {
|
||||
font-size: 12px;
|
||||
color: #444;
|
||||
|
|
@ -95,6 +104,12 @@
|
|||
<button class="primary" id="save">Save</button>
|
||||
</div>
|
||||
</header>
|
||||
<div id="closing" role="alertdialog" aria-label="Unsaved changes">
|
||||
<span>These notes have unsaved changes.</span>
|
||||
<button class="primary" id="close-save">Save and close</button>
|
||||
<button id="close-discard">Close without saving</button>
|
||||
<button id="close-cancel">Cancel</button>
|
||||
</div>
|
||||
<textarea id="editor" placeholder="Start typing…" spellcheck="false"></textarea>
|
||||
<footer>
|
||||
<span id="status">connecting…</span>
|
||||
|
|
@ -121,6 +136,8 @@
|
|||
var lastSent = null;
|
||||
var loading = null; // timer of the outstanding load, if any
|
||||
var encoder = new TextEncoder();
|
||||
var closing = document.getElementById('closing');
|
||||
var closeAfterSave = false;
|
||||
|
||||
function setStatus(msg) { statusEl.textContent = msg; }
|
||||
function countChars() { charEl.textContent = editor.value.length + ' chars'; }
|
||||
|
|
@ -138,8 +155,48 @@
|
|||
setLoaded(rev !== null);
|
||||
}
|
||||
|
||||
// Close policy ("ask" in wapp.toml): when the window is asked to close
|
||||
// with unsaved changes, the close is cancelled and the user chooses to
|
||||
// save first, close without saving, or keep editing. The window closes
|
||||
// after a save only once the save is acknowledged, saving again first if
|
||||
// the text changed meanwhile; a failed save keeps it open with the error
|
||||
// shown. Text typed while the notes are not loaded cannot be saved, so it
|
||||
// does not hold the window open.
|
||||
function unsaved() {
|
||||
return pending !== null || (rev !== null && editor.value !== saved);
|
||||
}
|
||||
|
||||
function hideClosing() {
|
||||
closing.classList.remove('shown');
|
||||
closeAfterSave = false;
|
||||
}
|
||||
|
||||
window.addEventListener('weftclose', function (e) {
|
||||
if (!unsaved()) return;
|
||||
e.preventDefault();
|
||||
// Asked again while the prompt is up, keep the user's choice so far.
|
||||
closing.classList.add('shown');
|
||||
});
|
||||
|
||||
document.getElementById('close-save').addEventListener('click', function () {
|
||||
closeAfterSave = true;
|
||||
if (!pending) saveButton.click();
|
||||
// The save could not start (status says why): stay open.
|
||||
if (!pending) hideClosing();
|
||||
});
|
||||
|
||||
document.getElementById('close-discard').addEventListener('click', function () {
|
||||
window.close();
|
||||
});
|
||||
|
||||
document.getElementById('close-cancel').addEventListener('click', hideClosing);
|
||||
|
||||
saveButton.addEventListener('click', function () {
|
||||
if (!window.weftIpc || pending) return;
|
||||
if (pending) return;
|
||||
if (!window.weftIpc) {
|
||||
setStatus('not saved: not connected');
|
||||
return;
|
||||
}
|
||||
if (rev === null) {
|
||||
setStatus('the notes have not loaded; use Discard to reload them');
|
||||
return;
|
||||
|
|
@ -162,6 +219,7 @@
|
|||
text: request.text,
|
||||
timer: setTimeout(function () {
|
||||
finishSave();
|
||||
hideClosing();
|
||||
setStatus('not saved: no reply; try again');
|
||||
}, REPLY_TIMEOUT),
|
||||
};
|
||||
|
|
@ -225,8 +283,17 @@
|
|||
rev = msg.rev;
|
||||
finishSave();
|
||||
setStatus(editor.value === saved ? 'saved' : 'saved; newer changes are not saved yet');
|
||||
if (closeAfterSave) {
|
||||
if (editor.value === saved) window.close();
|
||||
// Text typed after this save began is saved before closing.
|
||||
else saveButton.click();
|
||||
if (!pending && editor.value !== saved) hideClosing();
|
||||
}
|
||||
} else if (msg.op === 'error') {
|
||||
if (pending && msg.seq === pending.seq) finishSave();
|
||||
if (pending && msg.seq === pending.seq) {
|
||||
finishSave();
|
||||
hideClosing();
|
||||
}
|
||||
if (loading && msg.seq === undefined) finishLoad();
|
||||
setStatus(msg.conflict
|
||||
? 'not saved: changed in another window. Copy your text, then Discard to reload.'
|
||||
|
|
|
|||
|
|
@ -11,3 +11,4 @@ module = "app.wasm"
|
|||
|
||||
[ui]
|
||||
entry = "ui/index.html"
|
||||
close = "ask"
|
||||
|
|
|
|||
|
|
@ -27,7 +27,7 @@
|
|||
|
||||
hardware.graphics = {
|
||||
enable = true;
|
||||
extraPackages = with pkgs; [ mesa.drivers virglrenderer ];
|
||||
extraPackages = with pkgs; [ mesa virglrenderer ];
|
||||
};
|
||||
|
||||
networking = {
|
||||
|
|
|
|||
|
|
@ -9,10 +9,12 @@
|
|||
color-scheme: dark;
|
||||
--surface-bg: rgba(255, 255, 255, 0.07);
|
||||
--surface-border: rgba(255, 255, 255, 0.12);
|
||||
/* weft-servo-shell reserves this strip (TASKBAR_HEIGHT); keep them equal. */
|
||||
--taskbar-height: 48px;
|
||||
--text-primary: rgba(255, 255, 255, 0.92);
|
||||
--text-secondary: rgba(255, 255, 255, 0.55);
|
||||
--accent: #5b8af5;
|
||||
--focus-ring: #9db8ff;
|
||||
}
|
||||
|
||||
*, *::before, *::after {
|
||||
|
|
@ -62,19 +64,30 @@
|
|||
-webkit-backdrop-filter: blur(20px);
|
||||
}
|
||||
|
||||
weft-taskbar-launcher {
|
||||
button {
|
||||
font: inherit;
|
||||
color: inherit;
|
||||
border: 0;
|
||||
margin: 0;
|
||||
background: transparent;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
:focus-visible {
|
||||
outline: 2px solid var(--focus-ring);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
|
||||
#launcher-btn {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 36px;
|
||||
height: 36px;
|
||||
border-radius: 8px;
|
||||
cursor: pointer;
|
||||
background: transparent;
|
||||
transition: background 0.15s;
|
||||
}
|
||||
|
||||
weft-taskbar-launcher:hover {
|
||||
#launcher-btn:hover {
|
||||
background: var(--surface-border);
|
||||
}
|
||||
|
||||
|
|
@ -110,55 +123,56 @@
|
|||
margin: 0 auto;
|
||||
}
|
||||
|
||||
weft-app-icon {
|
||||
.app-icon {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
padding: 12px 8px;
|
||||
border-radius: 12px;
|
||||
cursor: pointer;
|
||||
color: var(--text-primary);
|
||||
font-size: 12px;
|
||||
text-align: center;
|
||||
word-break: break-word;
|
||||
transition: background 0.15s;
|
||||
}
|
||||
|
||||
weft-app-icon:hover {
|
||||
.app-icon:hover {
|
||||
background: var(--surface-border);
|
||||
}
|
||||
|
||||
weft-app-icon svg {
|
||||
.app-icon svg {
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
weft-taskbar-app {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
gap: 2px;
|
||||
font-size: 12px;
|
||||
color: var(--text-secondary);
|
||||
padding: 0 4px 0 6px;
|
||||
cursor: pointer;
|
||||
border-radius: 6px;
|
||||
transition: background 0.15s;
|
||||
}
|
||||
|
||||
weft-taskbar-app:hover {
|
||||
background: var(--surface-border);
|
||||
}
|
||||
|
||||
weft-taskbar-app .task-activate {
|
||||
padding: 4px 2px 4px 6px;
|
||||
border-radius: 6px;
|
||||
}
|
||||
|
||||
weft-taskbar-app .task-close {
|
||||
opacity: 0;
|
||||
font-size: 11px;
|
||||
line-height: 1;
|
||||
padding: 1px 3px;
|
||||
padding: 3px 4px;
|
||||
border-radius: 3px;
|
||||
transition: opacity 0.1s, background 0.1s;
|
||||
}
|
||||
|
||||
weft-taskbar-app:hover .task-close {
|
||||
/* Shown on hover and whenever the entry has keyboard focus. */
|
||||
weft-taskbar-app:hover .task-close,
|
||||
weft-taskbar-app:focus-within .task-close {
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
|
|
@ -166,6 +180,10 @@
|
|||
background: rgba(255,80,80,0.3);
|
||||
}
|
||||
|
||||
weft-taskbar-app .task-close.force {
|
||||
color: #ff6b6b;
|
||||
}
|
||||
|
||||
weft-notification-center {
|
||||
position: fixed;
|
||||
top: 8px;
|
||||
|
|
@ -187,7 +205,8 @@
|
|||
<weft-desktop>
|
||||
<weft-wallpaper></weft-wallpaper>
|
||||
<weft-taskbar>
|
||||
<weft-taskbar-launcher id="launcher-btn" title="Apps">
|
||||
<button id="launcher-btn" type="button" title="Apps" aria-label="Apps"
|
||||
aria-haspopup="dialog" aria-expanded="false" aria-controls="launcher">
|
||||
<svg width="18" height="18" viewBox="0 0 18 18" fill="none"
|
||||
xmlns="http://www.w3.org/2000/svg" aria-hidden="true">
|
||||
<rect x="1" y="1" width="6" height="6" rx="1.5"
|
||||
|
|
@ -199,15 +218,15 @@
|
|||
<rect x="11" y="11" width="6" height="6" rx="1.5"
|
||||
fill="rgba(255,255,255,0.7)" />
|
||||
</svg>
|
||||
</weft-taskbar-launcher>
|
||||
</button>
|
||||
<weft-taskbar-clock id="clock"></weft-taskbar-clock>
|
||||
</weft-taskbar>
|
||||
</weft-desktop>
|
||||
|
||||
<weft-launcher hidden id="launcher">
|
||||
<weft-launcher hidden id="launcher" tabindex="-1" role="dialog" aria-modal="true" aria-label="Apps">
|
||||
<weft-app-grid id="app-grid"></weft-app-grid>
|
||||
</weft-launcher>
|
||||
<weft-notification-center id="notifications"></weft-notification-center>
|
||||
<weft-notification-center id="notifications" role="status" aria-live="polite"></weft-notification-center>
|
||||
|
||||
<script>
|
||||
(function () {
|
||||
|
|
@ -221,27 +240,76 @@
|
|||
updateClock();
|
||||
setInterval(updateClock, 10000);
|
||||
|
||||
document.getElementById('launcher-btn').addEventListener('click', function () {
|
||||
var launcher = document.getElementById('launcher');
|
||||
if (launcher.hasAttribute('hidden')) {
|
||||
launcher.removeAttribute('hidden');
|
||||
if (ws && ws.readyState === WebSocket.OPEN) {
|
||||
ws.send(JSON.stringify({ type: 'QUERY_INSTALLED_APPS' }));
|
||||
}
|
||||
} else {
|
||||
launcher.setAttribute('hidden', '');
|
||||
var launcher = document.getElementById('launcher');
|
||||
var launcherBtn = document.getElementById('launcher-btn');
|
||||
var appGrid = document.getElementById('app-grid');
|
||||
|
||||
function launcherOpen() {
|
||||
return !launcher.hasAttribute('hidden');
|
||||
}
|
||||
|
||||
// Opening the launcher moves keyboard focus into it; closing it
|
||||
// returns focus to the Apps button.
|
||||
function openLauncher() {
|
||||
launcher.removeAttribute('hidden');
|
||||
launcherBtn.setAttribute('aria-expanded', 'true');
|
||||
focusInLauncher(null);
|
||||
if (ws && ws.readyState === WebSocket.OPEN) {
|
||||
ws.send(JSON.stringify({ type: 'QUERY_INSTALLED_APPS' }));
|
||||
}
|
||||
}
|
||||
|
||||
function closeLauncher() {
|
||||
if (!launcherOpen()) return;
|
||||
launcher.setAttribute('hidden', '');
|
||||
launcherBtn.setAttribute('aria-expanded', 'false');
|
||||
launcherBtn.focus();
|
||||
}
|
||||
|
||||
// Focuses the icon of `appId`, else the first one, else the dialog.
|
||||
function focusInLauncher(appId) {
|
||||
var icons = appGrid.querySelectorAll('.app-icon');
|
||||
var target = null;
|
||||
icons.forEach(function (icon) {
|
||||
if (icon.dataset.appId === appId) target = icon;
|
||||
});
|
||||
(target || icons[0] || launcher).focus();
|
||||
}
|
||||
|
||||
launcherBtn.addEventListener('click', function () {
|
||||
if (launcherOpen()) closeLauncher(); else openLauncher();
|
||||
});
|
||||
|
||||
document.addEventListener('keydown', function (e) {
|
||||
if (e.key === 'Escape') {
|
||||
document.getElementById('launcher').setAttribute('hidden', '');
|
||||
// The compositor brings the shell to the front when a Super key is
|
||||
// tapped, then delivers the tap here; it opens or closes the
|
||||
// launcher.
|
||||
if (e.key === 'Meta' && !e.repeat && !e.altKey && !e.ctrlKey && !e.shiftKey) {
|
||||
e.preventDefault();
|
||||
if (launcherOpen()) closeLauncher(); else openLauncher();
|
||||
} else if (e.key === 'Escape' && launcherOpen()) {
|
||||
e.preventDefault();
|
||||
closeLauncher();
|
||||
} else if (e.key === 'Tab' && launcherOpen()) {
|
||||
// The launcher is modal: Tab cycles through its apps, and Escape
|
||||
// leaves it.
|
||||
var icons = Array.prototype.slice.call(appGrid.querySelectorAll('.app-icon'));
|
||||
e.preventDefault();
|
||||
if (icons.length === 0) { launcher.focus(); return; }
|
||||
var at = icons.indexOf(document.activeElement);
|
||||
var next = at === -1 ? 0 : (at + (e.shiftKey ? icons.length - 1 : 1)) % icons.length;
|
||||
icons[next].focus();
|
||||
}
|
||||
});
|
||||
|
||||
document.getElementById('launcher').addEventListener('click', function (e) {
|
||||
// weft-servo-shell calls this when the shell loses keyboard focus, as
|
||||
// when an application window is clicked; the launcher closes, so the
|
||||
// next Super tap opens it.
|
||||
window.weftShellBlurred = closeLauncher;
|
||||
|
||||
launcher.addEventListener('click', function (e) {
|
||||
if (e.target === this) {
|
||||
this.setAttribute('hidden', '');
|
||||
closeLauncher();
|
||||
}
|
||||
});
|
||||
|
||||
|
|
@ -284,7 +352,7 @@
|
|||
if (ws !== socket) return;
|
||||
wsReconnectDelay = 1000;
|
||||
socket.send(JSON.stringify({ type: 'HELLO', role: 'system', token: endpoint.token }));
|
||||
document.querySelectorAll('weft-taskbar-app').forEach(function (el) { el.remove(); });
|
||||
document.querySelectorAll('weft-taskbar-app').forEach(removeEntryElement);
|
||||
socket.send(JSON.stringify({ type: 'QUERY_RUNNING' }));
|
||||
socket.send(JSON.stringify({ type: 'QUERY_INSTALLED_APPS' }));
|
||||
});
|
||||
|
|
@ -319,6 +387,8 @@
|
|||
} else if (msg.type === 'APP_STATE') {
|
||||
if (msg.state === 'stopped') {
|
||||
removeTaskbarEntry(msg.session_id);
|
||||
} else if (msg.state === 'stopping') {
|
||||
setTaskbarEntryClosing(msg.session_id);
|
||||
}
|
||||
} else if (msg.type === 'RUNNING_APPS') {
|
||||
msg.sessions.forEach(function (s) {
|
||||
|
|
@ -344,17 +414,25 @@
|
|||
}
|
||||
|
||||
function renderLauncher(apps) {
|
||||
var grid = document.getElementById('app-grid');
|
||||
var grid = appGrid;
|
||||
// Replacing the icons would drop keyboard focus; it returns to the
|
||||
// same app's new icon.
|
||||
var focused = grid.contains(document.activeElement) ? document.activeElement.dataset.appId : null;
|
||||
var active = document.activeElement;
|
||||
var refocus = launcherOpen() && (!active || active === document.body || launcher.contains(active));
|
||||
grid.innerHTML = '';
|
||||
if (apps.length === 0) {
|
||||
var empty = document.createElement('p');
|
||||
empty.textContent = 'No apps installed';
|
||||
empty.style.cssText = 'color:var(--text-secondary);font-size:13px;';
|
||||
grid.appendChild(empty);
|
||||
if (refocus) focusInLauncher(null);
|
||||
return;
|
||||
}
|
||||
apps.forEach(function (app) {
|
||||
var icon = document.createElement('weft-app-icon');
|
||||
var icon = document.createElement('button');
|
||||
icon.type = 'button';
|
||||
icon.className = 'app-icon';
|
||||
icon.dataset.appId = app.app_id;
|
||||
icon.title = app.app_id + (app.version ? ' v' + app.version : '');
|
||||
// Names come from package manifests; they are set as text, never markup.
|
||||
|
|
@ -366,16 +444,23 @@
|
|||
'</text></svg><span></span>';
|
||||
icon.querySelector('text').textContent = app.name ? app.name.charAt(0).toUpperCase() : '?';
|
||||
icon.querySelector('span').textContent = app.name || app.app_id;
|
||||
icon.setAttribute('aria-label', 'Open ' + (app.name || app.app_id));
|
||||
icon.addEventListener('click', function () {
|
||||
if (ws && ws.readyState === WebSocket.OPEN) {
|
||||
ws.send(JSON.stringify({ type: 'LAUNCH_APP', app_id: app.app_id, surface_id: 0 }));
|
||||
}
|
||||
document.getElementById('launcher').setAttribute('hidden', '');
|
||||
closeLauncher();
|
||||
});
|
||||
grid.appendChild(icon);
|
||||
});
|
||||
if (refocus) focusInLauncher(focused);
|
||||
}
|
||||
|
||||
// Longer than weft-appd's close timeout, so an app that neither closes
|
||||
// nor declines has already been terminated.
|
||||
var FORCE_QUIT_DELAY = 6000;
|
||||
var FORCE_QUIT_OFFER = 20000;
|
||||
|
||||
function ensureTaskbarEntry(sessionId, appId) {
|
||||
var id = 'task-' + sessionId;
|
||||
if (document.getElementById(id)) { return; }
|
||||
|
|
@ -384,29 +469,96 @@
|
|||
el.id = id;
|
||||
el.dataset.sessionId = sessionId;
|
||||
if (appId) { el.dataset.appId = appId; }
|
||||
el.setAttribute('role', 'group');
|
||||
el.setAttribute('aria-label', label);
|
||||
el.title = appId ? appId + ' (session ' + sessionId + ')' : 'Session ' + sessionId;
|
||||
var span = document.createElement('span');
|
||||
var span = document.createElement('button');
|
||||
span.type = 'button';
|
||||
span.className = 'task-activate';
|
||||
span.textContent = '● ' + label;
|
||||
var close = document.createElement('span');
|
||||
span.setAttribute('aria-label', 'Show ' + label);
|
||||
var close = document.createElement('button');
|
||||
close.type = 'button';
|
||||
close.className = 'task-close';
|
||||
close.textContent = '×';
|
||||
close.title = 'Terminate';
|
||||
close.title = 'Close';
|
||||
close.setAttribute('aria-label', 'Close ' + label);
|
||||
// The first click asks the app to close; it may decline, for example
|
||||
// to offer saving. An app still running once it has had time to
|
||||
// answer can then be force quit, losing what it has not saved.
|
||||
var closeTimer = null;
|
||||
close.addEventListener('click', function (e) {
|
||||
e.stopPropagation();
|
||||
if (ws && ws.readyState === WebSocket.OPEN) {
|
||||
ws.send(JSON.stringify({ type: 'TERMINATE_APP', session_id: sessionId }));
|
||||
}
|
||||
if (!ws || ws.readyState !== WebSocket.OPEN) { return; }
|
||||
var force = close.dataset.force === '1';
|
||||
ws.send(JSON.stringify({ type: 'TERMINATE_APP', session_id: sessionId, force: force }));
|
||||
if (force || close.dataset.asked) { return; }
|
||||
close.dataset.asked = '1';
|
||||
closeTimer = setTimeout(function () {
|
||||
if (!document.getElementById(el.id) || el.dataset.closing) { return; }
|
||||
close.dataset.force = '1';
|
||||
close.textContent = 'Force quit';
|
||||
close.title = 'Force quit: changes the app has not saved are lost';
|
||||
close.setAttribute('aria-label', 'Force quit ' + label + '; changes it has not saved are lost');
|
||||
close.classList.add('force');
|
||||
showNotification(label + ' did not close; its close button now force quits it');
|
||||
// Offered only for a while: an app that declined to let the user
|
||||
// keep working is closed normally next time.
|
||||
closeTimer = setTimeout(resetClose, FORCE_QUIT_OFFER);
|
||||
}, FORCE_QUIT_DELAY);
|
||||
});
|
||||
function resetClose() {
|
||||
clearTimeout(closeTimer);
|
||||
closeTimer = null;
|
||||
delete close.dataset.asked;
|
||||
delete close.dataset.force;
|
||||
close.textContent = '×';
|
||||
close.title = 'Close';
|
||||
close.setAttribute('aria-label', 'Close ' + label);
|
||||
close.classList.remove('force');
|
||||
}
|
||||
el.appendChild(span);
|
||||
el.appendChild(close);
|
||||
// Choosing the entry brings the app's window to the front.
|
||||
el.addEventListener('click', function () {
|
||||
if (el.dataset.closing) { return; }
|
||||
resetClose();
|
||||
if (ws && ws.readyState === WebSocket.OPEN) {
|
||||
ws.send(JSON.stringify({ type: 'ACTIVATE_APP', session_id: sessionId }));
|
||||
}
|
||||
});
|
||||
var taskbar = document.querySelector('weft-taskbar');
|
||||
var clock = document.getElementById('clock');
|
||||
taskbar.insertBefore(el, clock);
|
||||
}
|
||||
|
||||
// The session is ending; its entry stays until it has stopped.
|
||||
function setTaskbarEntryClosing(sessionId) {
|
||||
var el = document.getElementById('task-' + sessionId);
|
||||
if (!el || el.dataset.closing) { return; }
|
||||
el.dataset.closing = '1';
|
||||
el.style.opacity = '0.5';
|
||||
el.title += ' (closing)';
|
||||
var activate = el.querySelector('.task-activate');
|
||||
activate.setAttribute('aria-disabled', 'true');
|
||||
activate.setAttribute('aria-label', activate.getAttribute('aria-label') + ' (closing)');
|
||||
var close = el.querySelector('.task-close');
|
||||
if (close) {
|
||||
if (document.activeElement === close) { activate.focus(); }
|
||||
close.style.display = 'none';
|
||||
}
|
||||
}
|
||||
|
||||
function removeTaskbarEntry(sessionId) {
|
||||
var el = document.getElementById('task-' + sessionId);
|
||||
if (el) { el.remove(); }
|
||||
if (el) { removeEntryElement(el); }
|
||||
}
|
||||
|
||||
// Focus on a removed entry would be lost; it moves to the Apps button.
|
||||
function removeEntryElement(el) {
|
||||
var hadFocus = el.contains(document.activeElement);
|
||||
el.remove();
|
||||
if (hadFocus) { launcherBtn.focus(); }
|
||||
}
|
||||
|
||||
function showNotification(text) {
|
||||
|
|
|
|||
|
|
@ -43,7 +43,7 @@
|
|||
|
||||
<!-- ───────────────────────────── Manager ───────────────────────────── -->
|
||||
|
||||
<interface name="zweft_shell_manager_v1" version="2">
|
||||
<interface name="zweft_shell_manager_v1" version="3">
|
||||
|
||||
<description summary="shell session manager">
|
||||
Bound once by weft-servo-shell. The manager owns the shell session.
|
||||
|
|
@ -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.
|
||||
</description>
|
||||
<arg name="id" type="new_id" interface="zweft_shell_window_v1"
|
||||
summary="new window object"/>
|
||||
|
|
@ -90,7 +95,7 @@
|
|||
|
||||
<!-- ───────────────────────────── Window ────────────────────────────── -->
|
||||
|
||||
<interface name="zweft_shell_window_v1" version="2">
|
||||
<interface name="zweft_shell_window_v1" version="3">
|
||||
|
||||
<description summary="a compositor-managed window slot">
|
||||
Represents one visual window. The compositor controls the effective
|
||||
|
|
@ -114,6 +119,18 @@
|
|||
<description summary="protocol errors"/>
|
||||
<entry name="defunct_window" value="0"
|
||||
summary="request sent after window_closed was received"/>
|
||||
<entry name="role_not_permitted" value="1"
|
||||
summary="an application session requested a shell-only role"/>
|
||||
<entry name="invalid_exclusive_zone" value="2"
|
||||
summary="set_exclusive_zone on a window that is not a panel, or with a negative size"/>
|
||||
</enum>
|
||||
|
||||
<enum name="edge">
|
||||
<description summary="output edge"/>
|
||||
<entry name="top" value="1"/>
|
||||
<entry name="bottom" value="2"/>
|
||||
<entry name="left" value="3"/>
|
||||
<entry name="right" value="4"/>
|
||||
</enum>
|
||||
|
||||
<request name="destroy" type="destructor">
|
||||
|
|
@ -148,6 +165,19 @@
|
|||
<arg name="height" type="int" summary="requested height"/>
|
||||
</request>
|
||||
|
||||
<request name="set_exclusive_zone" since="3">
|
||||
<description summary="reserve an edge of the output for the panel">
|
||||
Reserves a strip of the given size, in logical pixels, along an
|
||||
edge of the output for shell chrome drawn by this panel, such as a
|
||||
taskbar. The compositor places application windows only in the
|
||||
work area that remains, so they never cover the strip. A size of 0
|
||||
releases the reservation; a later request replaces the earlier one.
|
||||
Only a panel window may reserve a zone.
|
||||
</description>
|
||||
<arg name="edge" type="uint" enum="edge" summary="edge to reserve"/>
|
||||
<arg name="size" type="int" summary="thickness of the strip"/>
|
||||
</request>
|
||||
|
||||
<event name="configure">
|
||||
<description summary="compositor sets effective geometry and state">
|
||||
Sent by the compositor when the effective geometry or state
|
||||
|
|
|
|||
290
tests/frame/check_activation.py
Executable file
290
tests/frame/check_activation.py
Executable file
|
|
@ -0,0 +1,290 @@
|
|||
#!/usr/bin/env python3
|
||||
"""Check that the compositor stacks, focuses and activates windows.
|
||||
|
||||
The harness runs weft-servo-shell with a solid green page as the system
|
||||
panel, and weft-appd with two test applications, one red and one blue, on a
|
||||
nested desktop (see session.py). Each application page switches between its
|
||||
colour and a lighter shade on every key press. In the presented pixels:
|
||||
|
||||
- the panel fills the compositor output and starts beneath the applications;
|
||||
- application windows fill the work area: the output less the strip the
|
||||
shell reserves for its taskbar along the bottom, which stays visible;
|
||||
- each newly launched application is shown on top and receives keys;
|
||||
- ACTIVATE_APP, the request the taskbar sends, brings the other session's
|
||||
window back to the front with keyboard focus;
|
||||
- clicking the taskbar strip brings the panel, the shell's home, over the
|
||||
applications, and activating an application brings it back;
|
||||
- when the focused application ends, the remaining one gets keyboard focus;
|
||||
- Alt+F4 asks the focused application window to close; its app shell exits
|
||||
cleanly and the session ends; Alt+F4 does not close the shell's panel;
|
||||
- ACTIVATE_APP for a session that is not running is refused.
|
||||
|
||||
The applications are unsigned test packages, recorded as development content
|
||||
in a private data home, using the Counter demo's component.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
||||
from check_counter import AppdClient, free_port, read_endpoint # noqa: E402
|
||||
from session import ROOT, Desktop, SessionError, bounding_box, missing_tools, parse_ppm # noqa: E402
|
||||
|
||||
GREEN = (0, 160, 0)
|
||||
APPS = {
|
||||
"org.weft.test.red": ((200, 0, 0), (255, 120, 120)),
|
||||
"org.weft.test.blue": ((0, 0, 200), (120, 120, 255)),
|
||||
}
|
||||
STARTUP_TIMEOUT = 120.0
|
||||
# The strip weft-servo-shell reserves at the bottom (TASKBAR_HEIGHT).
|
||||
TASKBAR = 48
|
||||
|
||||
PANEL_PAGE = ('<!DOCTYPE html><html><body style="margin:0;background:rgb(0,160,0);'
|
||||
'width:100vw;height:100vh"></body></html>')
|
||||
|
||||
|
||||
def app_page(color, pressed):
|
||||
return ('<!DOCTYPE html><html><body style="margin:0;width:100vw;height:100vh;'
|
||||
f'background:rgb{color}"><script>'
|
||||
'var pressed = false;'
|
||||
'addEventListener("keydown", function () { pressed = !pressed;'
|
||||
f'document.body.style.background = pressed ? "rgb{pressed}" : "rgb{color}"; }});'
|
||||
'</script></body></html>')
|
||||
|
||||
|
||||
def make_store(store, home):
|
||||
for app_id, (color, pressed) in APPS.items():
|
||||
package = store / app_id
|
||||
(package / "ui").mkdir(parents=True)
|
||||
(package / "wapp.toml").write_text(
|
||||
f'[package]\nid = "{app_id}"\nname = "Test"\nversion = "0.1.0"\n'
|
||||
'[runtime]\nmodule = "app.wasm"\n[ui]\nentry = "ui/index.html"\n')
|
||||
shutil.copy(ROOT / "examples/org.weft.demo.counter/app.wasm", package / "app.wasm")
|
||||
(package / "ui/index.html").write_text(app_page(color, pressed))
|
||||
record = home / "share/weft/owners" / app_id
|
||||
record.parent.mkdir(parents=True, exist_ok=True)
|
||||
record.write_text("development\n")
|
||||
|
||||
|
||||
def area(screenshot, color):
|
||||
width, height, pixels = parse_ppm(screenshot)
|
||||
box = bounding_box(width, height, pixels, color)
|
||||
return box, width, height
|
||||
|
||||
|
||||
def wait_for_color(desktop, color, timeout=20):
|
||||
deadline = time.monotonic() + timeout
|
||||
while time.monotonic() < deadline:
|
||||
shot = desktop.capture()
|
||||
box, _, _ = area(shot, color)
|
||||
if box is not None:
|
||||
return shot, box
|
||||
time.sleep(0.3)
|
||||
return desktop.capture(), None
|
||||
|
||||
|
||||
def wait_until_gone(desktop, color, timeout=10):
|
||||
deadline = time.monotonic() + timeout
|
||||
while time.monotonic() < deadline:
|
||||
box, _, _ = area(desktop.capture(), color)
|
||||
if box is None:
|
||||
return True
|
||||
time.sleep(0.3)
|
||||
return False
|
||||
|
||||
|
||||
def run(args, desktop, store, home):
|
||||
panel_page = desktop.runtime / "panel.html"
|
||||
panel_page.write_text(PANEL_PAGE)
|
||||
desktop.launch_client("shell", [args.shell], {"WEFT_SYSTEM_UI_HTML": str(panel_page)})
|
||||
shot, panel = wait_for_color(desktop, GREEN, 60)
|
||||
if panel is None:
|
||||
raise AssertionError("the panel was not shown")
|
||||
# The compositor sizes the panel to its whole output, larger than a
|
||||
# toplevel's default size.
|
||||
if panel[2] - panel[0] + 1 < 1000 or panel[3] - panel[1] + 1 < 700:
|
||||
raise AssertionError(f"the panel does not fill the output: {panel}")
|
||||
|
||||
t = Path(args.target)
|
||||
desktop.launch_client("appd", [t / "weft-appd"], {
|
||||
"WEFT_RUNTIME_BIN": str(t / "weft-runtime"),
|
||||
"WEFT_APP_SHELL_BIN": str(t / "weft-app-shell"),
|
||||
"WEFT_APP_STORE": str(store),
|
||||
"WEFT_DISABLE_CGROUP": "1",
|
||||
"WEFT_APPD_WS_PORT": str(free_port()),
|
||||
"HOME": str(home),
|
||||
"XDG_DATA_HOME": str(home / "share"),
|
||||
})
|
||||
port, token = read_endpoint(desktop.runtime, 30)
|
||||
appd = AppdClient(port, token)
|
||||
|
||||
def key(name):
|
||||
subprocess.run([args.xdotool, "search", "--class", "weft-compositor",
|
||||
"windowfocus", "--sync"], env={"DISPLAY": desktop.display},
|
||||
check=True, timeout=20)
|
||||
subprocess.run([args.xdotool, "key", name], env={"DISPLAY": desktop.display},
|
||||
check=True, timeout=20)
|
||||
|
||||
def shown(app_id, pressed=False):
|
||||
"""Waits until `app_id` is the visible application, alone on top."""
|
||||
color = APPS[app_id][1 if pressed else 0]
|
||||
others = [c for other, cs in APPS.items() for c in cs if other != app_id]
|
||||
deadline = time.monotonic() + 20
|
||||
while time.monotonic() < deadline:
|
||||
shot = desktop.capture()
|
||||
box, _, _ = area(shot, color)
|
||||
hidden = all(area(shot, c)[0] is None for c in others)
|
||||
if box is not None and hidden:
|
||||
# The application fills the work area: the panel's whole
|
||||
# width, down to the reserved strip, which stays visible.
|
||||
if box[0] != panel[0] or box[2] != panel[2] or box[1] != panel[1]:
|
||||
raise AssertionError(f"{app_id} does not fill the work area: {box}")
|
||||
if box[3] != panel[3] - TASKBAR:
|
||||
raise AssertionError(
|
||||
f"{app_id} does not end at the reserved strip: {box}, panel {panel}")
|
||||
return
|
||||
time.sleep(0.3)
|
||||
state = "pressed " if pressed else ""
|
||||
raise AssertionError(f"{app_id} is not shown {state}on top")
|
||||
|
||||
sessions = {}
|
||||
for app_id in APPS:
|
||||
appd.send({"type": "LAUNCH_APP", "app_id": app_id, "surface_id": 0})
|
||||
try:
|
||||
ready = appd.wait_for(
|
||||
lambda m, a=app_id: m.get("type") == "APP_READY" and m.get("app_id") == a,
|
||||
STARTUP_TIMEOUT)
|
||||
except TimeoutError:
|
||||
raise AssertionError(f"{app_id} did not start")
|
||||
sessions[app_id] = ready["session_id"]
|
||||
# A newly launched application comes to the front.
|
||||
shown(app_id)
|
||||
|
||||
red, blue = "org.weft.test.red", "org.weft.test.blue"
|
||||
# The last launched application has keyboard focus.
|
||||
key("a")
|
||||
shown(blue, pressed=True)
|
||||
|
||||
def activate(app_id):
|
||||
appd.send({"type": "ACTIVATE_APP", "session_id": sessions[app_id]})
|
||||
reply = appd.wait_for(lambda m: m.get("type") in ("APP_STATE", "ERROR")
|
||||
and m.get("session_id", sessions[app_id]) == sessions[app_id],
|
||||
10)
|
||||
if reply.get("type") != "APP_STATE":
|
||||
raise AssertionError(f"activating {app_id} was refused: {reply}")
|
||||
|
||||
# Activation brings the other session back with keyboard focus.
|
||||
activate(red)
|
||||
shown(red)
|
||||
key("a")
|
||||
shown(red, pressed=True)
|
||||
activate(blue)
|
||||
shown(blue, pressed=True)
|
||||
|
||||
# A click on the taskbar strip shows the shell's home over the
|
||||
# applications; activating one brings it back.
|
||||
x, y = (panel[0] + panel[2]) // 2, panel[3] - TASKBAR // 2
|
||||
subprocess.run([args.xdotool, "mousemove", "--sync", str(x), str(y)],
|
||||
env={"DISPLAY": desktop.display}, check=True, timeout=20)
|
||||
subprocess.run([args.xdotool, "click", "1"], env={"DISPLAY": desktop.display},
|
||||
check=True, timeout=20)
|
||||
deadline = time.monotonic() + 20
|
||||
while True:
|
||||
shot = desktop.capture()
|
||||
if area(shot, GREEN)[0] == panel and all(
|
||||
area(shot, c)[0] is None for cs in APPS.values() for c in cs):
|
||||
break
|
||||
if time.monotonic() > deadline:
|
||||
raise AssertionError("clicking the taskbar did not show the shell over the apps")
|
||||
time.sleep(0.3)
|
||||
activate(blue)
|
||||
shown(blue, pressed=True)
|
||||
|
||||
# When the focused application ends, keyboard focus returns to the other.
|
||||
appd.send({"type": "TERMINATE_APP", "session_id": sessions[blue]})
|
||||
shown(red, pressed=True)
|
||||
key("a")
|
||||
shown(red)
|
||||
|
||||
# Alt+F4 closes the focused application window, which ends its session;
|
||||
# with the panel focused, it closes nothing.
|
||||
key("alt+F4")
|
||||
try:
|
||||
appd.wait_for(lambda m: m.get("type") == "APP_STATE" and m.get("state") == "stopped"
|
||||
and m.get("session_id") == sessions[red], 20)
|
||||
except TimeoutError:
|
||||
raise AssertionError("Alt+F4 did not end the focused application's session")
|
||||
# The app shell ended by closing, with exit status 0, not by a crash.
|
||||
clean = (f'stopping session session_id={sessions[red]} '
|
||||
'reason="app shell exited (Ok(ExitStatus(unix_wait_status(0))))"')
|
||||
if clean not in desktop.log_text("appd"):
|
||||
raise AssertionError("the closed app shell did not exit cleanly; see appd.log")
|
||||
deadline = time.monotonic() + 20
|
||||
while any(area(desktop.capture(), c)[0] is not None for cs in APPS.values() for c in cs):
|
||||
if time.monotonic() > deadline:
|
||||
raise AssertionError("the closed application is still shown")
|
||||
time.sleep(0.3)
|
||||
key("alt+F4")
|
||||
deadline = time.monotonic() + 6
|
||||
while time.monotonic() < deadline:
|
||||
if area(desktop.capture(), GREEN)[0] != panel:
|
||||
raise AssertionError("Alt+F4 closed or moved the shell's panel")
|
||||
time.sleep(0.5)
|
||||
|
||||
appd.send({"type": "ACTIVATE_APP", "session_id": 999})
|
||||
reply = appd.wait_for(lambda m: m.get("type") == "ERROR", 10)
|
||||
if reply.get("code") != 404:
|
||||
raise AssertionError(f"activating a session that does not run: {reply}")
|
||||
|
||||
|
||||
def main(argv=None):
|
||||
parser = argparse.ArgumentParser(description=__doc__,
|
||||
formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||
parser.add_argument("--compositor", type=Path, default=ROOT / "target/debug/weft-compositor")
|
||||
parser.add_argument("--shell", type=Path, default=ROOT / "target/debug/weft-servo-shell")
|
||||
parser.add_argument("--target", type=Path, default=ROOT / "target/debug",
|
||||
help="directory with weft-appd, weft-runtime and weft-app-shell")
|
||||
parser.add_argument("--output", type=Path, default=ROOT / "target/activation-check")
|
||||
parser.add_argument("--xdotool", default=shutil.which("xdotool"))
|
||||
args = parser.parse_args(argv)
|
||||
if not args.xdotool:
|
||||
print("missing: xdotool", file=sys.stderr)
|
||||
return 2
|
||||
|
||||
missing = missing_tools() + [str(p) for p in (args.compositor, args.shell,
|
||||
args.target / "weft-appd",
|
||||
args.target / "weft-runtime",
|
||||
args.target / "weft-app-shell")
|
||||
if not p.is_file()]
|
||||
if missing:
|
||||
print("missing: " + ", ".join(missing), file=sys.stderr)
|
||||
return 2
|
||||
store = Path(tempfile.mkdtemp(prefix="weft-store-"))
|
||||
home = Path(tempfile.mkdtemp(prefix="weft-home-"))
|
||||
try:
|
||||
make_store(store, home)
|
||||
with Desktop(args.compositor, args.output, outputs=["appd.log", "activation.ppm"]) \
|
||||
as desktop:
|
||||
try:
|
||||
run(args, desktop, store, home)
|
||||
except AssertionError:
|
||||
(args.output / "activation.ppm").write_bytes(desktop.capture())
|
||||
raise
|
||||
except (AssertionError, SessionError, TimeoutError) as failure:
|
||||
print(f"activation check failed: {failure}", file=sys.stderr)
|
||||
print(f"logs and capture in {args.output}", file=sys.stderr)
|
||||
return 1
|
||||
finally:
|
||||
shutil.rmtree(store, ignore_errors=True)
|
||||
shutil.rmtree(home, ignore_errors=True)
|
||||
print("activation check passed")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
|
|
@ -41,12 +41,20 @@ def run(args, desktop, home, xdotool):
|
|||
(legacy / "notes.txt").write_bytes(NOTES)
|
||||
data_home = home / "data-home"
|
||||
target = data_home / "weft/app-data" / APP_ID
|
||||
# The earlier data is recorded as the demo publisher's. Data from before
|
||||
# owner records has no record and is refused until claimed with
|
||||
# weft-pack install --claim-data.
|
||||
owner = data_home / "weft/owners" / APP_ID
|
||||
owner.parent.mkdir(parents=True)
|
||||
key = (ROOT / "examples/keys/weft-sign.pub").read_text().strip()
|
||||
owner.write_text(f"verified {key}\n")
|
||||
|
||||
t = Path(args.target)
|
||||
desktop.launch_client("appd", [t / "weft-appd"], {
|
||||
"WEFT_RUNTIME_BIN": str(t / "weft-runtime"),
|
||||
"WEFT_APP_SHELL_BIN": str(t / "weft-app-shell"),
|
||||
"WEFT_APP_STORE": str(args.store),
|
||||
"WEFT_TRUSTED_KEYS": str(ROOT / "examples/keys"),
|
||||
"WEFT_DISABLE_CGROUP": "1",
|
||||
"WEFT_APPD_WS_PORT": str(free_port()),
|
||||
"HOME": str(home),
|
||||
|
|
|
|||
|
|
@ -52,8 +52,18 @@ APP_ID = "org.weft.test.confinement"
|
|||
PROBES = ["own-image", "bridge", "outside-image", "other-image", "linked-image", "http-image",
|
||||
"http-fetch", "websocket", "worker-fetch", "srcdoc-internals"]
|
||||
GREEN = (0, 192, 0)
|
||||
# The app window's page area on the 1024x768 nested desktop.
|
||||
PAGE_TOP, PAGE_HEIGHT, PAGE_X = 35, 600, 400
|
||||
# Where the probe bands are sampled across the app window's page.
|
||||
PAGE_X = 400
|
||||
# The X root behind the nested compositor window.
|
||||
ROOT_COLOUR = (0, 0, 0)
|
||||
|
||||
|
||||
def page_rows(width, height, pixels):
|
||||
"""The first and last rows the app window's page covers at PAGE_X: the
|
||||
compositor gives the application its whole work area. No shell runs in
|
||||
this check, so every row of the output that is not the X root is page."""
|
||||
rows = [y for y in range(height) if pixel(width, pixels, PAGE_X, y) != ROOT_COLOUR]
|
||||
return (rows[0], rows[-1]) if rows else None
|
||||
|
||||
|
||||
def png():
|
||||
|
|
@ -142,6 +152,12 @@ def make_package(store, http_port, ws_port, other_dir):
|
|||
(package / "outside.png").write_bytes(png())
|
||||
other.write_bytes(png())
|
||||
(package / "ui/linked").symlink_to(other_dir)
|
||||
# The package holds a link, which weft-pack refuses to install, so it is
|
||||
# planted directly and recorded as development content, which runs
|
||||
# unverified: the renderer's own confinement is what this check probes.
|
||||
record = store / "home/share/weft/owners" / APP_ID
|
||||
record.parent.mkdir(parents=True, exist_ok=True)
|
||||
record.write_text("development\n")
|
||||
|
||||
|
||||
def run(args, desktop, store, other_dir):
|
||||
|
|
@ -157,6 +173,8 @@ def run(args, desktop, store, other_dir):
|
|||
"WEFT_RUNTIME_BIN": str(t / "weft-runtime"),
|
||||
"WEFT_APP_SHELL_BIN": str(t / "weft-app-shell"),
|
||||
"WEFT_APP_STORE": str(store),
|
||||
"HOME": str(store / "home"),
|
||||
"XDG_DATA_HOME": str(store / "home/share"),
|
||||
"WEFT_DISABLE_CGROUP": "1",
|
||||
"WEFT_APPD_WS_PORT": str(free_port()),
|
||||
})
|
||||
|
|
@ -169,10 +187,14 @@ def run(args, desktop, store, other_dir):
|
|||
|
||||
deadline = time.monotonic() + 15
|
||||
while True:
|
||||
width, _, pixels = parse_ppm(desktop.capture())
|
||||
width, height, pixels = parse_ppm(desktop.capture())
|
||||
rows = page_rows(width, height, pixels)
|
||||
if rows is None:
|
||||
raise AssertionError("the test app's page is not on screen")
|
||||
top, bottom = rows
|
||||
colours = {}
|
||||
for i, name in enumerate(PROBES):
|
||||
y = PAGE_TOP + int((i + 0.5) * PAGE_HEIGHT / len(PROBES))
|
||||
y = top + int((i + 0.5) * (bottom - top + 1) / len(PROBES))
|
||||
colours[name] = pixel(width, pixels, PAGE_X, y)
|
||||
if all(c == GREEN for c in colours.values()) or time.monotonic() > deadline:
|
||||
break
|
||||
|
|
|
|||
|
|
@ -158,10 +158,17 @@ def count_area(screenshot, card):
|
|||
def run(args, desktop, xdotool):
|
||||
port = free_port()
|
||||
target = Path(args.target)
|
||||
# A private home, so owner records appd writes stay out of the user's.
|
||||
home = args.output / "home"
|
||||
shutil.rmtree(home, ignore_errors=True)
|
||||
home.mkdir(parents=True)
|
||||
desktop.launch_client("appd", [target / "weft-appd"], {
|
||||
"WEFT_RUNTIME_BIN": str(target / "weft-runtime"),
|
||||
"WEFT_APP_SHELL_BIN": str(target / "weft-app-shell"),
|
||||
"WEFT_APP_STORE": str(args.store),
|
||||
"WEFT_TRUSTED_KEYS": str(ROOT / "examples/keys"),
|
||||
"HOME": str(home),
|
||||
"XDG_DATA_HOME": str(home / "share"),
|
||||
"WEFT_DISABLE_CGROUP": "1",
|
||||
"WEFT_APPD_WS_PORT": str(port),
|
||||
})
|
||||
|
|
@ -169,9 +176,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 +227,20 @@ 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 the app as a user close would: the
|
||||
# compositor asks its window to close and the app shell exits by itself.
|
||||
appd.send({"type": "TERMINATE_APP", "session_id": session_id})
|
||||
deadline = time.monotonic() + 15
|
||||
asked = f"session asked to close session_id={session_id} windows=1"
|
||||
# appd records "closed on request" only when the app shell exits cleanly.
|
||||
closed = (f'stopping session session_id={session_id} reason="closed on request; '
|
||||
'app shell exited')
|
||||
while asked not in desktop.log_text("compositor") or closed not in desktop.log_text("appd"):
|
||||
if time.monotonic() > deadline:
|
||||
raise AssertionError("the session did not close on request; see compositor.log "
|
||||
"and appd.log")
|
||||
time.sleep(0.3)
|
||||
|
||||
|
||||
def subprocess_run(xdotool, display, arguments):
|
||||
import subprocess
|
||||
|
|
|
|||
|
|
@ -19,6 +19,13 @@ sequence, quotes, a tab and non-ASCII characters, launches
|
|||
5. A load that fails (the stored notes are not valid UTF-8) leaves Discard
|
||||
usable: after the file is repaired, Discard loads it and it can be edited
|
||||
and saved again.
|
||||
6. Notes declares the `ask` close policy. With unsaved changes, a close
|
||||
request (TERMINATE_APP or Alt+F4) is declined and a prompt is shown: the
|
||||
session keeps running and Cancel keeps the text; "Save and close" stores
|
||||
the text before the app shell exits cleanly; "Close without saving"
|
||||
leaves the stored notes unchanged. A forced TERMINATE_APP ends a session
|
||||
whose close was declined at once, saving nothing. Without unsaved
|
||||
changes, Notes closes at once.
|
||||
|
||||
Requires Xvfb, xwd, ImageMagick's convert and xdotool.
|
||||
"""
|
||||
|
|
@ -35,14 +42,18 @@ from pathlib import Path
|
|||
|
||||
sys.dont_write_bytecode = True
|
||||
from check_counter import AppdClient, free_port, read_endpoint # noqa: E402
|
||||
from session import ROOT, Desktop, SessionError, missing_tools # noqa: E402
|
||||
from session import ROOT, Desktop, SessionError, bounding_box, missing_tools, parse_ppm # noqa: E402
|
||||
|
||||
APP_ID = "org.weft.demo.notes"
|
||||
SEED = 'path C:\\new\\table "quoted"\tcaf\u00e9 \u2603'
|
||||
|
||||
|
||||
# The Discard button in the 800x600 Notes window at the desktop's origin.
|
||||
DISCARD = ("663", "68")
|
||||
PAGE = (15, 15, 15) # The Notes page's background, #0f0f0f.
|
||||
# The Discard button, right-aligned in the header: its offset from the
|
||||
# window's right edge, and its height on the desktop.
|
||||
DISCARD_FROM_RIGHT, DISCARD_Y = 137, 68
|
||||
# The row through the close prompt's buttons, below the header.
|
||||
PROMPT_Y = DISCARD_Y + 48
|
||||
|
||||
|
||||
def runtime_pid():
|
||||
|
|
@ -64,17 +75,163 @@ def wait_for_file(path, expected, timeout=15):
|
|||
raise AssertionError(f"stored notes {actual!r}, expected {expected!r}")
|
||||
|
||||
|
||||
def prompt_buttons(desktop, page):
|
||||
"""The close prompt's buttons, left to right, as (left, right) columns,
|
||||
or None when the prompt is not shown."""
|
||||
width, _, pixels = parse_ppm(desktop.capture())
|
||||
runs, start = [], None
|
||||
for x in range(page[0], page[2] + 2):
|
||||
i = (PROMPT_Y * width + x) * 3
|
||||
background = x > page[2] or tuple(pixels[i:i + 3]) == PAGE
|
||||
if not background and start is None:
|
||||
start = x
|
||||
elif background and start is not None:
|
||||
runs.append((start, x - 1))
|
||||
start = None
|
||||
buttons = [r for r in runs if r[1] - r[0] >= 40]
|
||||
# Shown, the row holds the prompt's text and its three buttons, with the
|
||||
# page between them; hidden, it crosses the editor from edge to edge.
|
||||
if len(buttons) < 3 or buttons[-1][1] - buttons[0][0] > (page[2] - page[0]) * 0.8:
|
||||
return None
|
||||
return buttons[-3:]
|
||||
|
||||
|
||||
def wait_for_prompt(desktop, page, shown, timeout=10):
|
||||
deadline = time.monotonic() + timeout
|
||||
while time.monotonic() < deadline:
|
||||
buttons = prompt_buttons(desktop, page)
|
||||
if (buttons is not None) == shown:
|
||||
return buttons
|
||||
time.sleep(0.3)
|
||||
raise AssertionError("the close prompt was " + ("not shown" if shown else "not dismissed"))
|
||||
|
||||
|
||||
def launch(appd):
|
||||
appd.send({"type": "LAUNCH_APP", "app_id": APP_ID, "surface_id": 0})
|
||||
reply = appd.wait_for(lambda m: m.get("type") in ("APP_READY", "ERROR"), 120)
|
||||
if reply.get("type") != "APP_READY":
|
||||
raise AssertionError(f"Notes did not start: {reply}")
|
||||
return reply["session_id"]
|
||||
|
||||
|
||||
def wait_for_state(appd, session_id, state, timeout):
|
||||
try:
|
||||
appd.wait_for(lambda m: m.get("type") == "APP_STATE" and m.get("state") == state
|
||||
and m.get("session_id") == session_id, timeout)
|
||||
except TimeoutError:
|
||||
raise AssertionError(f"session {session_id} did not become {state}")
|
||||
|
||||
|
||||
def wait_for_decline(desktop, session_id, timeout=10):
|
||||
marker = f"the application declined the close session_id={session_id}"
|
||||
deadline = time.monotonic() + timeout
|
||||
while marker not in desktop.log_text("appd"):
|
||||
if time.monotonic() > deadline:
|
||||
raise AssertionError(f"session {session_id} did not decline the close")
|
||||
time.sleep(0.2)
|
||||
|
||||
|
||||
def stop_reason(desktop, session_id):
|
||||
marker = f"stopping session session_id={session_id} reason=\""
|
||||
for line in desktop.log_text("appd").splitlines():
|
||||
if marker in line:
|
||||
return line.split(marker, 1)[1].rsplit('"', 1)[0]
|
||||
return None
|
||||
|
||||
|
||||
def check_close_policy(desktop, appd, page, act, notes, session_id):
|
||||
"""Step 6, from a running Notes session whose text is saved."""
|
||||
def click(column):
|
||||
act("mousemove", "--sync", str((column[0] + column[1]) // 2), str(PROMPT_Y))
|
||||
act("click", "1")
|
||||
|
||||
def type_at_end(text):
|
||||
act("mousemove", "--sync", "100", "400")
|
||||
act("click", "1")
|
||||
act("key", "ctrl+End")
|
||||
act("type", "--delay", "40", text)
|
||||
|
||||
stored = notes.read_text(encoding="utf-8")
|
||||
type_at_end(" unsaved")
|
||||
# The page declines the close; the session keeps running.
|
||||
appd.send({"type": "TERMINATE_APP", "session_id": session_id})
|
||||
wait_for_decline(desktop, session_id)
|
||||
buttons = wait_for_prompt(desktop, page, True)
|
||||
click(buttons[2]) # Cancel
|
||||
wait_for_prompt(desktop, page, False)
|
||||
# The compositor's close (Alt+F4) asks the page the same way.
|
||||
act("key", "alt+F4")
|
||||
buttons = wait_for_prompt(desktop, page, True)
|
||||
time.sleep(1)
|
||||
if stop_reason(desktop, session_id) is not None:
|
||||
raise AssertionError("the session stopped although the close was cancelled")
|
||||
click(buttons[0]) # Save and close
|
||||
wait_for_state(appd, session_id, "stopped", 20)
|
||||
if notes.read_text(encoding="utf-8") != stored + " unsaved":
|
||||
raise AssertionError("Save and close did not store the text before closing")
|
||||
reason = stop_reason(desktop, session_id)
|
||||
if reason is None or not reason.startswith("closed on request; app shell exited"):
|
||||
raise AssertionError(f"Notes did not exit cleanly after saving: {reason}")
|
||||
|
||||
# Close without saving keeps the stored notes.
|
||||
session_id = launch(appd)
|
||||
time.sleep(2)
|
||||
act("search", "--class", "weft-compositor", "windowfocus", "--sync")
|
||||
type_at_end(" dropped")
|
||||
appd.send({"type": "TERMINATE_APP", "session_id": session_id})
|
||||
wait_for_decline(desktop, session_id)
|
||||
buttons = wait_for_prompt(desktop, page, True)
|
||||
click(buttons[1]) # Close without saving
|
||||
wait_for_state(appd, session_id, "stopped", 20)
|
||||
if notes.read_text(encoding="utf-8") != stored + " unsaved":
|
||||
raise AssertionError("closing without saving changed the stored notes")
|
||||
|
||||
# A forced stop ends a session that declined its close, without asking.
|
||||
session_id = launch(appd)
|
||||
time.sleep(2)
|
||||
act("search", "--class", "weft-compositor", "windowfocus", "--sync")
|
||||
type_at_end(" forced")
|
||||
appd.send({"type": "TERMINATE_APP", "session_id": session_id})
|
||||
wait_for_decline(desktop, session_id)
|
||||
wait_for_prompt(desktop, page, True)
|
||||
forced = time.monotonic()
|
||||
appd.send({"type": "TERMINATE_APP", "session_id": session_id, "force": True})
|
||||
wait_for_state(appd, session_id, "stopped", 10)
|
||||
if time.monotonic() - forced > 3:
|
||||
raise AssertionError("a forced stop waited for the application")
|
||||
if stop_reason(desktop, session_id) != "terminated by force":
|
||||
raise AssertionError(f"a forced stop reported {stop_reason(desktop, session_id)!r}")
|
||||
if notes.read_text(encoding="utf-8") != stored + " unsaved":
|
||||
raise AssertionError("a forced stop changed the stored notes")
|
||||
|
||||
# Without unsaved changes, a close request closes Notes at once.
|
||||
session_id = launch(appd)
|
||||
time.sleep(2)
|
||||
appd.send({"type": "TERMINATE_APP", "session_id": session_id})
|
||||
wait_for_state(appd, session_id, "stopped", 10)
|
||||
reason = stop_reason(desktop, session_id)
|
||||
if reason is None or not reason.startswith("closed on request; app shell exited"):
|
||||
raise AssertionError(f"Notes without changes did not close on request: {reason}")
|
||||
|
||||
|
||||
def run(args, desktop, home, xdotool):
|
||||
data_home = home / "share"
|
||||
notes = data_home / "weft/app-data" / APP_ID / "notes.txt"
|
||||
notes.parent.mkdir(parents=True)
|
||||
notes.write_text(SEED, encoding="utf-8")
|
||||
# The seeded data belongs to the demo publisher, as installing the signed
|
||||
# package with weft-pack would have recorded.
|
||||
owner = data_home / "weft/owners" / APP_ID
|
||||
owner.parent.mkdir(parents=True)
|
||||
key = (ROOT / "examples/keys/weft-sign.pub").read_text().strip()
|
||||
owner.write_text(f"verified {key}\n")
|
||||
|
||||
t = Path(args.target)
|
||||
desktop.launch_client("appd", [t / "weft-appd"], {
|
||||
"WEFT_RUNTIME_BIN": str(t / "weft-runtime"),
|
||||
"WEFT_APP_SHELL_BIN": str(t / "weft-app-shell"),
|
||||
"WEFT_APP_STORE": str(args.store),
|
||||
"WEFT_TRUSTED_KEYS": str(ROOT / "examples/keys"),
|
||||
"WEFT_DISABLE_CGROUP": "1",
|
||||
"WEFT_APPD_WS_PORT": str(free_port()),
|
||||
"HOME": str(home),
|
||||
|
|
@ -82,11 +239,13 @@ def run(args, desktop, home, xdotool):
|
|||
})
|
||||
port, token = read_endpoint(desktop.runtime, 30)
|
||||
appd = AppdClient(port, token)
|
||||
appd.send({"type": "LAUNCH_APP", "app_id": APP_ID, "surface_id": 0})
|
||||
reply = appd.wait_for(lambda m: m.get("type") in ("APP_READY", "ERROR"), 120)
|
||||
if reply.get("type") != "APP_READY":
|
||||
raise AssertionError(f"Notes did not start: {reply}")
|
||||
session_id = launch(appd)
|
||||
time.sleep(2)
|
||||
width, height, pixels = parse_ppm(desktop.capture())
|
||||
page = bounding_box(width, height, pixels, PAGE)
|
||||
if page is None:
|
||||
raise AssertionError("the Notes page is not on screen")
|
||||
discard = (str(page[2] + 1 - DISCARD_FROM_RIGHT), str(DISCARD_Y))
|
||||
|
||||
def act(*arguments):
|
||||
subprocess.run([xdotool, *arguments], env={"DISPLAY": desktop.display},
|
||||
|
|
@ -125,7 +284,7 @@ def run(args, desktop, home, xdotool):
|
|||
|
||||
os.kill(runtime, signal.SIGSTOP)
|
||||
try:
|
||||
act("mousemove", "--sync", *DISCARD)
|
||||
act("mousemove", "--sync", *discard)
|
||||
act("click", "1")
|
||||
act("mousemove", "--sync", "100", "300")
|
||||
act("click", "1")
|
||||
|
|
@ -140,7 +299,7 @@ def run(args, desktop, home, xdotool):
|
|||
act("key", "ctrl+s")
|
||||
wait_for_file(notes, other + "!")
|
||||
notes.write_bytes(b"\xff not text")
|
||||
act("mousemove", "--sync", *DISCARD)
|
||||
act("mousemove", "--sync", *discard)
|
||||
act("click", "1")
|
||||
time.sleep(2)
|
||||
# The editor stays read-only and nothing can be saved over the file.
|
||||
|
|
@ -151,7 +310,7 @@ def run(args, desktop, home, xdotool):
|
|||
time.sleep(2)
|
||||
if notes.read_bytes() != b"\xff not text":
|
||||
raise AssertionError("a failed load changed the stored notes")
|
||||
act("mousemove", "--sync", *DISCARD)
|
||||
act("mousemove", "--sync", *discard)
|
||||
notes.write_text("repaired", encoding="utf-8")
|
||||
act("click", "1")
|
||||
time.sleep(2)
|
||||
|
|
@ -166,6 +325,8 @@ def run(args, desktop, home, xdotool):
|
|||
if leftovers:
|
||||
raise AssertionError(f"files left beside the notes: {leftovers}")
|
||||
|
||||
check_close_policy(desktop, appd, page, act, notes, session_id)
|
||||
|
||||
|
||||
def main(argv=None):
|
||||
parser = argparse.ArgumentParser(description=__doc__,
|
||||
|
|
|
|||
281
tests/frame/check_system_ui.py
Normal file
281
tests/frame/check_system_ui.py
Normal file
|
|
@ -0,0 +1,281 @@
|
|||
#!/usr/bin/env python3
|
||||
"""Check that the system UI can be operated with the keyboard alone.
|
||||
|
||||
The harness runs weft-servo-shell with the real system UI page
|
||||
(infra/shell/system-ui.html) and weft-appd with two test applications,
|
||||
"Blue" and "Red", on a nested desktop (see session.py). Each application
|
||||
page switches between its colour and a lighter shade on every key press.
|
||||
Every action below is a key press, apart from one activation request; the
|
||||
results are observed in weft-appd's lifecycle messages and in the presented
|
||||
pixels:
|
||||
|
||||
- a Super tap brings the shell to the front from an application and opens
|
||||
the launcher with focus on its first app, in name order; Super pressed
|
||||
with another key leaves the application in front, and that key reaches it
|
||||
with the Super modifier, which the application no longer sees once Super
|
||||
is released;
|
||||
- Enter opens the focused app, whose window takes keyboard focus; Tab
|
||||
moves through the launcher's apps;
|
||||
- Escape closes the launcher and returns focus to the Apps button, from
|
||||
which Tab reaches each taskbar entry and its close button;
|
||||
- Enter on a taskbar entry brings its app's window back with keyboard
|
||||
focus, and Enter on its close button ends its session;
|
||||
- the launcher closes when the shell loses focus, so the next Super tap
|
||||
opens it, and a second Super tap closes it, leaving focus on the Apps
|
||||
button.
|
||||
|
||||
The applications are unsigned test packages, recorded as development content
|
||||
in a private data home, using the Counter demo's component.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
||||
from check_activation import APPS, area # noqa: E402
|
||||
from check_counter import AppdClient, free_port, read_endpoint # noqa: E402
|
||||
from session import ROOT, Desktop, SessionError, missing_tools # noqa: E402
|
||||
|
||||
BLUE, RED = "org.weft.test.blue", "org.weft.test.red"
|
||||
NAMES = {BLUE: "Blue", RED: "Red"}
|
||||
STARTUP_TIMEOUT = 120.0
|
||||
# The strip weft-servo-shell reserves at the bottom (TASKBAR_HEIGHT).
|
||||
TASKBAR = 48
|
||||
|
||||
|
||||
def app_page(color, pressed):
|
||||
"""A page that switches shade on every key press without the Super
|
||||
(Meta) modifier, so a modifier left held shows as a missed switch."""
|
||||
return ('<!DOCTYPE html><html><body style="margin:0;width:100vw;height:100vh;'
|
||||
f'background:rgb{color}"><script>'
|
||||
'var pressed = false;'
|
||||
'addEventListener("keydown", function (e) { if (e.metaKey) return;'
|
||||
'pressed = !pressed;'
|
||||
f'document.body.style.background = pressed ? "rgb{pressed}" : "rgb{color}"; }});'
|
||||
'</script></body></html>')
|
||||
|
||||
|
||||
def make_store(store, home):
|
||||
for app_id, (color, pressed) in APPS.items():
|
||||
package = store / app_id
|
||||
(package / "ui").mkdir(parents=True)
|
||||
(package / "wapp.toml").write_text(
|
||||
f'[package]\nid = "{app_id}"\nname = "{NAMES[app_id]}"\nversion = "0.1.0"\n'
|
||||
'[runtime]\nmodule = "app.wasm"\n[ui]\nentry = "ui/index.html"\n')
|
||||
shutil.copy(ROOT / "examples/org.weft.demo.counter/app.wasm", package / "app.wasm")
|
||||
(package / "ui/index.html").write_text(app_page(color, pressed))
|
||||
record = home / "share/weft/owners" / app_id
|
||||
record.parent.mkdir(parents=True, exist_ok=True)
|
||||
record.write_text("development\n")
|
||||
|
||||
|
||||
def run(args, desktop, store, home):
|
||||
t = Path(args.target)
|
||||
desktop.launch_client("appd", [t / "weft-appd"], {
|
||||
"WEFT_RUNTIME_BIN": str(t / "weft-runtime"),
|
||||
"WEFT_APP_SHELL_BIN": str(t / "weft-app-shell"),
|
||||
"WEFT_APP_STORE": str(store),
|
||||
"WEFT_DISABLE_CGROUP": "1",
|
||||
"WEFT_APPD_WS_PORT": str(free_port()),
|
||||
"HOME": str(home),
|
||||
"XDG_DATA_HOME": str(home / "share"),
|
||||
"RUST_LOG": "info,weft_appd::ws=debug",
|
||||
})
|
||||
port, token = read_endpoint(desktop.runtime, 30)
|
||||
appd = AppdClient(port, token)
|
||||
desktop.launch_client("shell", [args.shell],
|
||||
{"WEFT_SYSTEM_UI_HTML": str(ROOT / "infra/shell/system-ui.html")})
|
||||
# This check's client and the system UI page.
|
||||
deadline = time.monotonic() + 90
|
||||
while desktop.log_text("appd").count("system client connected") < 2:
|
||||
if time.monotonic() > deadline:
|
||||
raise AssertionError("the system UI did not connect to weft-appd")
|
||||
time.sleep(0.5)
|
||||
|
||||
def key(*names):
|
||||
subprocess.run([args.xdotool, "search", "--class", "weft-compositor",
|
||||
"windowfocus", "--sync"], env={"DISPLAY": desktop.display},
|
||||
check=True, timeout=20)
|
||||
for name in names:
|
||||
subprocess.run([args.xdotool, "key", name], env={"DISPLAY": desktop.display},
|
||||
check=True, timeout=20)
|
||||
time.sleep(0.3)
|
||||
|
||||
def colors(shot):
|
||||
return {c for cs in APPS.values() for c in cs if area(shot, c)[0] is not None}
|
||||
|
||||
def shown(app_id, pressed=False):
|
||||
"""Waits until `app_id` is the visible application, alone on top."""
|
||||
color = APPS[app_id][1 if pressed else 0]
|
||||
deadline = time.monotonic() + 20
|
||||
while time.monotonic() < deadline:
|
||||
if colors(desktop.capture()) == {color}:
|
||||
return
|
||||
time.sleep(0.3)
|
||||
state = "pressed " if pressed else ""
|
||||
raise AssertionError(f"{NAMES[app_id]} is not shown {state}on top")
|
||||
|
||||
def shell_in_front():
|
||||
deadline = time.monotonic() + 20
|
||||
while time.monotonic() < deadline:
|
||||
if not colors(desktop.capture()):
|
||||
return
|
||||
time.sleep(0.3)
|
||||
raise AssertionError("the shell did not come to the front")
|
||||
|
||||
def ready(app_id, timeout=STARTUP_TIMEOUT):
|
||||
try:
|
||||
message = appd.wait_for(lambda m: m.get("type") == "APP_READY", timeout)
|
||||
except TimeoutError:
|
||||
raise AssertionError(f"{NAMES[app_id]} was not opened")
|
||||
if message.get("app_id") != app_id:
|
||||
raise AssertionError(f"expected {NAMES[app_id]} to open, got {message}")
|
||||
return message["session_id"]
|
||||
|
||||
def no_launch(seconds=3):
|
||||
try:
|
||||
message = appd.wait_for(lambda m: m.get("type") == "APP_READY", seconds)
|
||||
except TimeoutError:
|
||||
return
|
||||
raise AssertionError(f"an app opened unexpectedly: {message}")
|
||||
|
||||
# A Super tap opens the launcher on the first app by name; Enter opens
|
||||
# it. The page asks for the catalog once connected; until it has
|
||||
# arrived, Enter finds no app, so the first attempt may be repeated.
|
||||
for attempt in range(10):
|
||||
key("Escape", "super", "Return")
|
||||
try:
|
||||
appd.wait_for(lambda m: m.get("type") == "LAUNCH_ACK", 5)
|
||||
break
|
||||
except TimeoutError:
|
||||
if attempt == 9:
|
||||
raise AssertionError("the launcher opened no app")
|
||||
blue = ready(BLUE)
|
||||
shown(BLUE)
|
||||
# The new window has keyboard focus.
|
||||
key("a")
|
||||
shown(BLUE, pressed=True)
|
||||
|
||||
# Super pressed with another key is not a tap: the key reaches the
|
||||
# application with the Super modifier, and the shell stays behind it.
|
||||
key("super+a")
|
||||
time.sleep(1)
|
||||
shown(BLUE, pressed=True)
|
||||
# Once Super is released, the application's keys carry no Super
|
||||
# modifier, even when another modifier changed while it was held.
|
||||
xdo = [args.xdotool]
|
||||
for step in (["keydown", "super"], ["key", "shift"], ["keyup", "super"]):
|
||||
subprocess.run(xdo + step, env={"DISPLAY": desktop.display}, check=True, timeout=20)
|
||||
time.sleep(0.3)
|
||||
shown(BLUE, pressed=True)
|
||||
key("a")
|
||||
shown(BLUE)
|
||||
key("a")
|
||||
shown(BLUE, pressed=True)
|
||||
|
||||
# A Super tap from an application brings the shell and its launcher to
|
||||
# the front; Tab moves to the next app.
|
||||
key("super")
|
||||
shell_in_front()
|
||||
key("Tab", "Return")
|
||||
red = ready(RED)
|
||||
shown(RED)
|
||||
|
||||
# Escape closes the launcher, so Tab leaves the Apps button for the
|
||||
# first taskbar entry rather than an app; Enter activates it.
|
||||
key("super")
|
||||
shell_in_front()
|
||||
key("Escape", "Tab", "Return")
|
||||
shown(BLUE, pressed=True)
|
||||
no_launch()
|
||||
key("a")
|
||||
shown(BLUE)
|
||||
|
||||
# The launcher closes when the shell loses focus, here to an
|
||||
# activation, so the next Super tap opens it rather than closing it.
|
||||
key("super")
|
||||
shell_in_front()
|
||||
appd.send({"type": "ACTIVATE_APP", "session_id": red})
|
||||
shown(RED)
|
||||
key("super")
|
||||
shell_in_front()
|
||||
key("Return")
|
||||
extra = ready(BLUE)
|
||||
shown(BLUE)
|
||||
|
||||
# Tab passes Blue's entry and close button and Red's entry to reach
|
||||
# Red's close button; Enter ends Red's session.
|
||||
key("super")
|
||||
shell_in_front()
|
||||
key("Escape", "Tab", "Tab", "Tab", "Tab", "Return")
|
||||
try:
|
||||
appd.wait_for(lambda m: m.get("type") == "APP_STATE" and m.get("state") == "stopped"
|
||||
and m.get("session_id") == red, 20)
|
||||
except TimeoutError:
|
||||
raise AssertionError("Enter on Red's close button did not end its session")
|
||||
appd.send({"type": "QUERY_RUNNING"})
|
||||
running = appd.wait_for(lambda m: m.get("type") == "RUNNING_APPS", 10)
|
||||
if sorted(s["session_id"] for s in running["sessions"]) != sorted([blue, extra]):
|
||||
raise AssertionError(f"after closing Red, expected only the Blue sessions: {running}")
|
||||
|
||||
# A second Super tap closes the launcher and leaves focus on the Apps
|
||||
# button: Tab then reaches the first taskbar entry, and Enter shows
|
||||
# that app instead of opening another.
|
||||
key("super", "super")
|
||||
no_launch()
|
||||
key("Tab", "Return")
|
||||
shown(BLUE)
|
||||
no_launch()
|
||||
|
||||
|
||||
def main(argv=None):
|
||||
parser = argparse.ArgumentParser(description=__doc__,
|
||||
formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||
parser.add_argument("--compositor", type=Path, default=ROOT / "target/debug/weft-compositor")
|
||||
parser.add_argument("--shell", type=Path, default=ROOT / "target/debug/weft-servo-shell")
|
||||
parser.add_argument("--target", type=Path, default=ROOT / "target/debug",
|
||||
help="directory with weft-appd, weft-runtime and weft-app-shell")
|
||||
parser.add_argument("--output", type=Path, default=ROOT / "target/system-ui-check")
|
||||
parser.add_argument("--xdotool", default=shutil.which("xdotool"))
|
||||
args = parser.parse_args(argv)
|
||||
if not args.xdotool:
|
||||
print("missing: xdotool", file=sys.stderr)
|
||||
return 2
|
||||
|
||||
missing = missing_tools() + [str(p) for p in (args.compositor, args.shell,
|
||||
args.target / "weft-appd",
|
||||
args.target / "weft-runtime",
|
||||
args.target / "weft-app-shell")
|
||||
if not p.is_file()]
|
||||
if missing:
|
||||
print("missing: " + ", ".join(missing), file=sys.stderr)
|
||||
return 2
|
||||
store = Path(tempfile.mkdtemp(prefix="weft-store-"))
|
||||
home = Path(tempfile.mkdtemp(prefix="weft-home-"))
|
||||
try:
|
||||
make_store(store, home)
|
||||
with Desktop(args.compositor, args.output,
|
||||
outputs=["appd.log", "system-ui.ppm"]) as desktop:
|
||||
try:
|
||||
run(args, desktop, store, home)
|
||||
except AssertionError:
|
||||
(args.output / "system-ui.ppm").write_bytes(desktop.capture())
|
||||
raise
|
||||
except (AssertionError, SessionError, TimeoutError) as failure:
|
||||
print(f"system UI check failed: {failure}", file=sys.stderr)
|
||||
print(f"logs and capture in {args.output}", file=sys.stderr)
|
||||
return 1
|
||||
finally:
|
||||
shutil.rmtree(store, ignore_errors=True)
|
||||
shutil.rmtree(home, ignore_errors=True)
|
||||
print("system UI check passed")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
232
tests/frame/check_update.py
Executable file
232
tests/frame/check_update.py
Executable file
|
|
@ -0,0 +1,232 @@
|
|||
#!/usr/bin/env python3
|
||||
"""Check that package updates are transactional and leave running sessions alone.
|
||||
|
||||
The harness installs a test application with weft-pack into a private store
|
||||
and runs weft-appd with the real runtime and app shell on a nested desktop
|
||||
(see session.py). Each revision of the application's page shows its own
|
||||
colour. In the presented pixels and the store:
|
||||
|
||||
1. A session started from revision one keeps showing it after the package is
|
||||
updated to revision two, and its app shell runs from revision one's own
|
||||
directory, which the update keeps while the session runs.
|
||||
2. An update that fails (an invalid component) changes nothing: revision two
|
||||
stays active.
|
||||
3. A session launched after the update shows revision two.
|
||||
4. Once the first session has ended, the next update removes revision one,
|
||||
and keeps revision two for rollback; `weft-pack rollback` makes revision
|
||||
two active again.
|
||||
5. Uninstalling while a session runs stops new launches (404) but not the
|
||||
session; the next uninstall, after it has ended, removes the revisions.
|
||||
6. An app declaring a capability (notifications) is refused at launch (403)
|
||||
until `weft-pack approve` approves it, and then launches.
|
||||
|
||||
The application is unsigned development content using the Counter demo's
|
||||
component.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import os
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
||||
from check_counter import AppdClient, free_port, read_endpoint # noqa: E402
|
||||
from session import ROOT, Desktop, SessionError, bounding_box, missing_tools, parse_ppm # noqa: E402
|
||||
|
||||
APP_ID = "org.weft.test.update"
|
||||
COLOURS = {"one": (200, 0, 0), "two": (0, 0, 200), "three": (0, 160, 0)}
|
||||
VERSIONS = {"one": 1, "two": 2, "bad": 3, "three": 4}
|
||||
STARTUP_TIMEOUT = 120.0
|
||||
|
||||
|
||||
def write_revision(src, name, wasm=None, capabilities="[]"):
|
||||
shutil.rmtree(src, ignore_errors=True)
|
||||
(src / "ui").mkdir(parents=True)
|
||||
(src / "wapp.toml").write_text(
|
||||
f'[package]\nid = "{APP_ID}"\nname = "Update"\nversion = "0.0.{VERSIONS[name]}"\n'
|
||||
f'capabilities = {capabilities}\n'
|
||||
'[runtime]\nmodule = "app.wasm"\n[ui]\nentry = "ui/index.html"\n')
|
||||
if wasm is None:
|
||||
shutil.copy(ROOT / "examples/org.weft.demo.counter/app.wasm", src / "app.wasm")
|
||||
else:
|
||||
(src / "app.wasm").write_bytes(wasm)
|
||||
colour = COLOURS.get(name, (0, 0, 0))
|
||||
(src / "ui/index.html").write_text(
|
||||
'<!DOCTYPE html><html><body style="margin:0;width:100vw;height:100vh;'
|
||||
f'background:rgb{colour}"></body></html>')
|
||||
|
||||
|
||||
def shows(desktop, colour, timeout=20):
|
||||
deadline = time.monotonic() + timeout
|
||||
while time.monotonic() < deadline:
|
||||
width, height, pixels = parse_ppm(desktop.capture())
|
||||
if bounding_box(width, height, pixels, colour) is not None:
|
||||
return True
|
||||
time.sleep(0.3)
|
||||
return False
|
||||
|
||||
|
||||
def run(args, desktop, store, home):
|
||||
t = Path(args.target)
|
||||
env = dict(os.environ, WEFT_APP_STORE=str(store), HOME=str(home),
|
||||
XDG_DATA_HOME=str(home / "share"))
|
||||
|
||||
def pack(*arguments, ok=True):
|
||||
done = subprocess.run([t / "weft-pack", *arguments], env=env,
|
||||
capture_output=True, text=True, timeout=60)
|
||||
if ok and done.returncode != 0:
|
||||
raise AssertionError(f"weft-pack {' '.join(arguments)} failed: {done.stderr}")
|
||||
if not ok and done.returncode == 0:
|
||||
raise AssertionError(f"weft-pack {' '.join(arguments)} succeeded: {done.stdout}")
|
||||
return done.stdout + done.stderr
|
||||
|
||||
revisions = store / ".revisions" / APP_ID
|
||||
|
||||
def active():
|
||||
return os.readlink(store / APP_ID)
|
||||
|
||||
src = home / "src"
|
||||
write_revision(src, "one")
|
||||
pack("install", str(src), "--dev")
|
||||
one = store / active()
|
||||
|
||||
desktop.launch_client("appd", [t / "weft-appd"], {
|
||||
"WEFT_RUNTIME_BIN": str(t / "weft-runtime"),
|
||||
"WEFT_APP_SHELL_BIN": str(t / "weft-app-shell"),
|
||||
"WEFT_APP_STORE": str(store),
|
||||
"WEFT_DISABLE_CGROUP": "1",
|
||||
"WEFT_APPD_WS_PORT": str(free_port()),
|
||||
"HOME": str(home),
|
||||
"XDG_DATA_HOME": str(home / "share"),
|
||||
})
|
||||
port, token = read_endpoint(desktop.runtime, 30)
|
||||
appd = AppdClient(port, token)
|
||||
|
||||
def launch():
|
||||
appd.send({"type": "LAUNCH_APP", "app_id": APP_ID, "surface_id": 0})
|
||||
reply = appd.wait_for(lambda m: m.get("type") in ("APP_READY", "ERROR"), STARTUP_TIMEOUT)
|
||||
if reply.get("type") != "APP_READY":
|
||||
raise AssertionError(f"the app did not start: {reply}")
|
||||
return reply["session_id"]
|
||||
|
||||
def stop(session_id):
|
||||
appd.send({"type": "TERMINATE_APP", "session_id": session_id, "force": True})
|
||||
appd.wait_for(lambda m: m.get("type") == "APP_STATE" and m.get("state") == "stopped"
|
||||
and m.get("session_id") == session_id, 20)
|
||||
|
||||
first = launch()
|
||||
if not shows(desktop, COLOURS["one"]):
|
||||
raise AssertionError("revision one is not shown")
|
||||
shells = subprocess.run(["pgrep", "-af", "weft-app-shell"], capture_output=True,
|
||||
text=True).stdout
|
||||
if str(one / "ui/index.html") not in shells:
|
||||
raise AssertionError(f"the app shell does not run from revision one: {shells}")
|
||||
|
||||
# 1. An update leaves the running session on its revision.
|
||||
write_revision(src, "two")
|
||||
pack("install", str(src), "--dev")
|
||||
two = store / active()
|
||||
if two == one:
|
||||
raise AssertionError("the update did not activate a new revision")
|
||||
time.sleep(2)
|
||||
if not shows(desktop, COLOURS["one"], 5) or shows(desktop, COLOURS["two"], 1):
|
||||
raise AssertionError("the update changed what the running session shows")
|
||||
if (one / "ui/index.html").read_text().find("200, 0, 0") < 0:
|
||||
raise AssertionError("the running session's revision changed")
|
||||
|
||||
# 2. A failed update changes nothing.
|
||||
write_revision(src, "bad", wasm=b"not a component")
|
||||
pack("install", str(src), "--dev", ok=False)
|
||||
if store / active() != two:
|
||||
raise AssertionError("a failed update changed the active revision")
|
||||
|
||||
# 3. A new launch gets the update.
|
||||
second = launch()
|
||||
if not shows(desktop, COLOURS["two"]):
|
||||
raise AssertionError("a launch after the update does not show revision two")
|
||||
stop(second)
|
||||
|
||||
# 4. With the first session ended, the next update collects revision one.
|
||||
if not one.is_dir():
|
||||
raise AssertionError("revision one was removed while its session ran")
|
||||
stop(first)
|
||||
write_revision(src, "three")
|
||||
pack("install", str(src), "--dev")
|
||||
if one.exists():
|
||||
raise AssertionError("revision one was kept after its session ended")
|
||||
if not two.is_dir():
|
||||
raise AssertionError("the previous revision was not kept for rollback")
|
||||
pack("rollback", APP_ID)
|
||||
if store / active() != two:
|
||||
raise AssertionError("rollback did not make revision two active")
|
||||
third = launch()
|
||||
if not shows(desktop, COLOURS["two"]):
|
||||
raise AssertionError("a launch after rollback does not show revision two")
|
||||
|
||||
# 5. Uninstall stops new launches, not the running session.
|
||||
pack("uninstall", APP_ID)
|
||||
appd.send({"type": "LAUNCH_APP", "app_id": APP_ID, "surface_id": 0})
|
||||
refused = appd.wait_for(lambda m: m.get("type") in ("APP_READY", "ERROR"), 30)
|
||||
if refused.get("code") != 404:
|
||||
raise AssertionError(f"a launch after uninstall was not refused: {refused}")
|
||||
if not two.is_dir() or not shows(desktop, COLOURS["two"], 5):
|
||||
raise AssertionError("uninstall disturbed the running session")
|
||||
stop(third)
|
||||
pack("uninstall", APP_ID, ok=False)
|
||||
if revisions.exists():
|
||||
raise AssertionError(f"revisions left after uninstall: {list(revisions.iterdir())}")
|
||||
|
||||
# 6. A declared capability needs approval before the app launches.
|
||||
write_revision(src, "one", capabilities='["sys:notifications"]')
|
||||
pack("install", str(src), "--dev")
|
||||
appd.send({"type": "LAUNCH_APP", "app_id": APP_ID, "surface_id": 0})
|
||||
refused = appd.wait_for(lambda m: m.get("type") in ("APP_READY", "ERROR"), 30)
|
||||
if refused.get("code") != 403 or "needs approval" not in refused.get("message", ""):
|
||||
raise AssertionError(f"an unapproved capability launched: {refused}")
|
||||
pack("approve", APP_ID)
|
||||
stop(launch())
|
||||
|
||||
|
||||
def main(argv=None):
|
||||
parser = argparse.ArgumentParser(description=__doc__,
|
||||
formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||
parser.add_argument("--compositor", type=Path, default=ROOT / "target/debug/weft-compositor")
|
||||
parser.add_argument("--target", type=Path, default=ROOT / "target/debug",
|
||||
help="directory with weft-appd, weft-pack, weft-runtime and weft-app-shell")
|
||||
parser.add_argument("--output", type=Path, default=ROOT / "target/update-check")
|
||||
args = parser.parse_args(argv)
|
||||
|
||||
missing = missing_tools() + [str(p) for p in (args.compositor, args.target / "weft-appd",
|
||||
args.target / "weft-pack",
|
||||
args.target / "weft-runtime",
|
||||
args.target / "weft-app-shell")
|
||||
if not p.is_file()]
|
||||
if missing:
|
||||
print("missing: " + ", ".join(missing), file=sys.stderr)
|
||||
return 2
|
||||
store = Path(tempfile.mkdtemp(prefix="weft-store-"))
|
||||
home = Path(tempfile.mkdtemp(prefix="weft-home-"))
|
||||
try:
|
||||
with Desktop(args.compositor, args.output, outputs=["appd.log", "update.ppm"]) as desktop:
|
||||
try:
|
||||
run(args, desktop, store, home)
|
||||
except AssertionError:
|
||||
(args.output / "update.ppm").write_bytes(desktop.capture())
|
||||
raise
|
||||
except (AssertionError, SessionError, TimeoutError) as failure:
|
||||
print(f"update check failed: {failure}", file=sys.stderr)
|
||||
print(f"logs and capture in {args.output}", file=sys.stderr)
|
||||
return 1
|
||||
finally:
|
||||
shutil.rmtree(store, ignore_errors=True)
|
||||
shutil.rmtree(home, ignore_errors=True)
|
||||
print("update check passed")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
|
|
@ -17,7 +17,8 @@ from pathlib import Path
|
|||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
SCREEN = (1024, 768)
|
||||
# Large enough to show the nested compositor's whole 1280x800 output.
|
||||
SCREEN = (1400, 900)
|
||||
ANSI_ESCAPE = re.compile(r"\x1b\[[0-9;]*m")
|
||||
REQUIRED_TOOLS = ("Xvfb", "xwd", "convert")
|
||||
|
||||
|
|
@ -111,9 +112,11 @@ def _stop(process):
|
|||
class Desktop:
|
||||
"""Xvfb plus weft-compositor; logs are written to `output/<name>.log`."""
|
||||
|
||||
def __init__(self, compositor, output, outputs=()):
|
||||
"""`outputs` names further files in `output` that this run will write."""
|
||||
def __init__(self, compositor, output, outputs=(), screen=SCREEN):
|
||||
"""`outputs` names further files in `output` that this run will write;
|
||||
`screen` is the X screen size."""
|
||||
self.compositor = Path(compositor)
|
||||
self.screen = screen
|
||||
self.output = Path(output)
|
||||
self.own_outputs = ["xvfb.log", "compositor.log", "shell.log", *outputs]
|
||||
self.processes = []
|
||||
|
|
@ -180,7 +183,7 @@ class Desktop:
|
|||
try:
|
||||
xvfb = subprocess.Popen(
|
||||
["Xvfb", "-displayfd", str(write_end), "-screen", "0",
|
||||
f"{SCREEN[0]}x{SCREEN[1]}x24", "-nolisten", "tcp"],
|
||||
f"{self.screen[0]}x{self.screen[1]}x24", "-nolisten", "tcp"],
|
||||
stdout=log, stderr=subprocess.STDOUT, env=self.env,
|
||||
start_new_session=True, pass_fds=(write_end,))
|
||||
finally:
|
||||
|
|
|
|||
|
|
@ -16,9 +16,12 @@ scenario passes a different set of `--grant` and `--preopen` arguments:
|
|||
denied;
|
||||
- a host-specific fetch grant: requests to that host return their real
|
||||
status (200, 404, and 302 without following the redirect to another
|
||||
host); requests to another host, a forged `Host` header, a method that
|
||||
injects a request line and a `file:` URL are refused;
|
||||
- a wildcard fetch grant: the other host is reachable;
|
||||
host); requests to another host, credentials in the URL, a forged
|
||||
`Host` header, a method that injects a request line and a `file:` URL
|
||||
are refused;
|
||||
- a wildcard fetch grant, and a grant for the name `localhost`: the local
|
||||
server is refused, since only an address named in a grant reaches this
|
||||
machine or a local network; the connection is never made;
|
||||
- limits: an allocation beyond the default memory limit (256 MiB) fails
|
||||
inside the component, and succeeds with `--max-memory-mib 512`; app
|
||||
messages longer than 64 KiB or containing a line break are refused.
|
||||
|
|
@ -49,8 +52,13 @@ APP_ID = "org.weft.test.grants"
|
|||
NOT_GRANTED = "is not granted"
|
||||
|
||||
|
||||
# Paths the test server was asked for.
|
||||
REQUESTS = []
|
||||
|
||||
|
||||
class Handler(http.server.BaseHTTPRequestHandler):
|
||||
def do_GET(self):
|
||||
REQUESTS.append(self.path)
|
||||
if self.path == "/ok":
|
||||
self.send_response(200)
|
||||
elif self.path == "/redirect":
|
||||
|
|
@ -82,7 +90,8 @@ class Runner:
|
|||
f"fetch-ok http://127.0.0.1:{port}/ok\n"
|
||||
f"fetch-missing http://127.0.0.1:{port}/missing\n"
|
||||
f"fetch-redirect http://127.0.0.1:{port}/redirect\n"
|
||||
f"fetch-other-host http://localhost:{port}/ok\n")
|
||||
f"fetch-other-host http://localhost:{port}/ok\n"
|
||||
f"fetch-credentials http://user:secret@127.0.0.1:{port}/ok\n")
|
||||
|
||||
def run(self, *arguments, expect_success=True):
|
||||
command = [str(self.runtime), APP_ID, "1", "--module", str(self.module),
|
||||
|
|
@ -147,12 +156,20 @@ def check(runner, data):
|
|||
expect(probes, "fetch-missing", True, contains="404")
|
||||
expect(probes, "fetch-redirect", True, contains="302")
|
||||
expect(probes, "fetch-other-host", False, contains=NOT_GRANTED)
|
||||
expect(probes, "fetch-credentials", False, contains="credentials")
|
||||
expect(probes, "fetch-host-header", False, contains="set by the runtime")
|
||||
expect(probes, "fetch-bad-method", False, contains="unsupported HTTP method")
|
||||
expect(probes, "fetch-file-scheme", False, contains="unsupported URL scheme")
|
||||
|
||||
local = "local network"
|
||||
REQUESTS.clear()
|
||||
_, probes = runner.run("--grant", "net:fetch:*")
|
||||
expect(probes, "fetch-other-host", True, contains="200")
|
||||
expect(probes, "fetch-other-host", False, contains=local)
|
||||
expect(probes, "fetch-ok", False, contains=local)
|
||||
_, probes = runner.run("--grant", "net:fetch:localhost")
|
||||
expect(probes, "fetch-other-host", False, contains=local)
|
||||
if REQUESTS:
|
||||
raise AssertionError(f"refused fetches reached the server: {REQUESTS}")
|
||||
|
||||
_, probes = runner.run()
|
||||
expect(probes, "memory-grow", False)
|
||||
|
|
|
|||
Loading…
Reference in a new issue