fix(app-shell): confine application pages to their UI files and bridge

An application page could load any local file through file: URLs and
reach any network destination with images, fetch, XHR or WebSockets,
bypassing the component's fetch grants. The shell now checks every
resource load: files inside the UI directory, inline data:, blob: and
about: resources and the session bridge are allowed; anything else
fails with a network error before a request leaves the renderer.

tests/frame/check_confinement.py probes each path on the nested desktop
and requires that no HTTP request or TCP connection reaches the host.
The frame check's slow stylesheet becomes a file next to the page held
back with a file lease, so it stays inside the confined scope.
This commit is contained in:
Marco Allegretti 2026-10-09 09:39:37 +00:00
parent 010573eb16
commit d60152f443
No known key found for this signature in database
6 changed files with 327 additions and 31 deletions

View file

@ -65,6 +65,9 @@ struct WeftWebViewDelegate {
signals: Arc<FrameSignals>, signals: Arc<FrameSignals>,
/// URL prefix of the application's UI directory; see `ui_scope`. /// URL prefix of the application's UI directory; see `ui_scope`.
scope: String, scope: String,
/// The bridge's WebSocket handshake URL, as the network layer requests it
/// (`ws:` becomes `http:`).
bridge: String,
} }
impl WebViewDelegate for WeftWebViewDelegate { impl WebViewDelegate for WeftWebViewDelegate {
@ -84,6 +87,21 @@ impl WebViewDelegate for WeftWebViewDelegate {
} }
} }
/// Every resource the page loads passes through here, including
/// `fetch()`, XHR, subresources, redirects and WebSocket handshakes. The
/// page may read its own UI files and open the session bridge; any other
/// local file or network destination is refused with a network error.
/// Network access belongs to the component, under its fetch grants.
fn load_web_resource(&self, _webview: servo::WebView, load: servo::WebResourceLoad) {
let url = load.request().url.clone();
if resource_allowed(url.as_str(), &self.scope, &self.bridge) {
return;
}
tracing::warn!(%url, "resource outside the application denied");
load.intercept(servo::WebResourceResponse::new(url))
.cancel();
}
fn notify_load_status_changed(&self, webview: servo::WebView, status: LoadStatus) { fn notify_load_status_changed(&self, webview: servo::WebView, status: LoadStatus) {
if status != LoadStatus::Complete { if status != LoadStatus::Complete {
return; return;
@ -142,6 +160,17 @@ fn in_scope(url: &str, scope: &str) -> bool {
}) })
} }
/// Whether an application page may load `url`: a file inside its UI
/// directory, an inline (`data:`, `blob:`, `about:`) resource, or the session
/// bridge.
fn resource_allowed(url: &str, scope: &str, bridge: &str) -> bool {
in_scope(url, scope)
|| url == bridge
|| ["data:", "blob:", "about:"]
.iter()
.any(|scheme| url.starts_with(scheme))
}
/// `value` as a single-quoted JavaScript string literal. /// `value` as a single-quoted JavaScript string literal.
fn js_string(value: &str) -> String { fn js_string(value: &str) -> String {
let mut literal = String::with_capacity(value.len() + 2); let mut literal = String::with_capacity(value.len() + 2);
@ -428,6 +457,7 @@ impl ApplicationHandler<ServoWake> for App {
.delegate(Rc::new(WeftWebViewDelegate { .delegate(Rc::new(WeftWebViewDelegate {
signals: Arc::clone(&self.signals), signals: Arc::clone(&self.signals),
scope: ui_scope(&self.url), scope: ui_scope(&self.url),
bridge: format!("http://127.0.0.1:{}/app", self.ws_port),
})) }))
.user_content_manager(ucm) .user_content_manager(ucm)
.url(self.url.clone().into_url()) .url(self.url.clone().into_url())

View file

@ -16,7 +16,7 @@ System UI host. Renders one WebView pointing at `system-ui.html` using the embed
### weft-app-shell ### weft-app-shell
Per-application Servo host. Spawned by `weft-appd` after the Wasm runtime signals READY. Takes `<app_id>` and `<session_id>` as arguments. Resolves `weft-app://<app_id>/ui/index.html` and injects the `weftIpc` WebSocket bridge into the page. The bridge authenticates with the per-session token from `WEFT_BRIDGE_TOKEN` and can only exchange messages with its own session. It is installed only in top-level documents inside the application's UI directory, and top-level navigation outside that directory is denied; framed documents never receive the bridge. 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>` and `<session_id>` as arguments. Resolves `weft-app://<app_id>/ui/index.html` and injects the `weftIpc` WebSocket bridge into the page. The bridge authenticates with the per-session token from `WEFT_BRIDGE_TOKEN` and can only exchange messages with its own session. It is installed only in top-level documents inside the application's UI directory, and top-level navigation outside that directory is denied; framed documents never receive the bridge. Every resource the page loads (subresources, `fetch()`, XHR, redirects and WebSocket handshakes) is checked by the shell: the page may load files inside its UI directory, inline `data:`, `blob:` and `about:` resources, and the session bridge; any other local file or network destination fails with a network error. Network access belongs to the Wasm component, under its fetch grants. Registers with the compositor as window type `application`. Exits when the appd session ends.
### weft-appd ### weft-appd

View file

@ -63,7 +63,9 @@ python3 tests/frame/check_frame.py --host app --slow-style 3
`--host app` also requires the page on screen within two seconds of `--host app` also requires the page on screen within two seconds of
`weft-app-shell` printing `READY`; `--slow-style` delays a stylesheet that `weft-app-shell` printing `READY`; `--slow-style` delays a stylesheet that
reveals the page so premature readiness becomes visible. reveals the page so premature readiness becomes visible. The stylesheet is a
file next to the page that the harness keeps from being opened with a file
lease, so the delay must stay below `/proc/sys/fs/lease-break-time`.
Logs and the last capture are written to `target/frame-check`. Logs and the last capture are written to `target/frame-check`.
@ -85,6 +87,7 @@ same nested desktop and drive the demo apps with real keyboard input:
python3 tests/frame/check_counter.py # Counter round trip through the session bridge 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
python3 tests/frame/check_app_data.py # Notes data from the earlier layout is moved and kept 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
``` ```
## Demo apps (wasm32-wasip2) ## Demo apps (wasm32-wasip2)

View file

@ -0,0 +1,191 @@
"""Check that an application page can reach only its own files and its bridge.
The harness installs a test package, using the Counter demo's component and
the page in tests/frame/confinement, in a temporary store and launches it
through weft-appd with the real runtime and app shell on the nested desktop.
The page probes, and paints one band per probe:
- an image from its own UI directory loads;
- the session bridge reaches the component, which answers;
- an image just outside its UI directory (../outside.png) fails to load;
- an image elsewhere on disk (a file: URL) fails to load;
- an image from a local HTTP server fails to load;
- a no-cors fetch from that server is rejected;
- a WebSocket to a local listener fails.
Each refused probe would succeed without the policy: the images are valid,
the fetch accepts an opaque response and the listener accepts connections.
Every band must be green, and the HTTP server and the TCP listener must see
no connection at all, so the refusals happen in the renderer, not after a
request left it.
Requires Xvfb, xwd and ImageMagick's convert.
"""
import argparse
import http.server
import shutil
import socket
import struct
import sys
import tempfile
import threading
import time
import zlib
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, parse_ppm, pixel # noqa: E402
APP_ID = "org.weft.test.confinement"
PROBES = ["own-image", "bridge", "outside-image", "other-image", "http-image", "http-fetch",
"websocket"]
GREEN = (0, 192, 0)
# The app window's page area on the 1024x768 nested desktop.
PAGE_TOP, PAGE_HEIGHT, PAGE_X = 35, 600, 400
def png():
"""A valid 1x1 PNG image."""
def chunk(kind, data):
body = kind + data
return struct.pack(">I", len(data)) + body + struct.pack(">I", zlib.crc32(body))
header = struct.pack(">IIBBBBB", 1, 1, 8, 2, 0, 0, 0)
pixels = zlib.compress(b"\x00\x00\x00\xff")
return (b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", header) + chunk(b"IDAT", pixels)
+ chunk(b"IEND", b""))
class Counting(http.server.BaseHTTPRequestHandler):
requests = 0
def do_GET(self):
Counting.requests += 1
body = png()
self.send_response(200)
self.send_header("Content-Type", "image/png")
self.send_header("Access-Control-Allow-Origin", "*")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def log_message(self, *args):
pass
def make_package(store, http_port, tcp_port, other):
package = store / APP_ID
(package / "ui").mkdir(parents=True)
(package / "wapp.toml").write_text(
f'[package]\nid = "{APP_ID}"\nname = "Confinement"\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")
page = (Path(__file__).parent / "confinement/index.html").read_text()
page = (page.replace("@HTTP_PORT@", str(http_port)).replace("@TCP_PORT@", str(tcp_port))
.replace("@OTHER_URL@", other.as_uri()))
(package / "ui/index.html").write_text(page)
(package / "ui/own.png").write_bytes(png())
(package / "outside.png").write_bytes(png())
other.write_bytes(png())
def run(args, desktop, store):
server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Counting)
threading.Thread(target=server.serve_forever, daemon=True).start()
listener = socket.socket()
listener.bind(("127.0.0.1", 0))
listener.listen()
listener.settimeout(0.2)
connections = []
def accept():
while not stop.is_set():
try:
connection = listener.accept()[0]
except OSError:
continue
connections.append(connection)
connection.close()
stop = threading.Event()
threading.Thread(target=accept, daemon=True).start()
try:
make_package(store, server.server_port, listener.getsockname()[1],
store.parent / f"{store.name}-other.png")
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()),
})
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"the test app did not start: {reply}")
deadline = time.monotonic() + 15
while True:
width, _, pixels = parse_ppm(desktop.capture())
colours = {}
for i, name in enumerate(PROBES):
y = PAGE_TOP + int((i + 0.5) * PAGE_HEIGHT / len(PROBES))
colours[name] = pixel(width, pixels, PAGE_X, y)
if all(c == GREEN for c in colours.values()) or time.monotonic() > deadline:
break
time.sleep(0.5)
failed = [name for name, c in colours.items() if c != GREEN]
if failed:
raise AssertionError(f"probes not as required: {failed} ({colours})")
if Counting.requests or connections:
raise AssertionError(f"requests left the renderer: {Counting.requests} HTTP, "
f"{len(connections)} TCP")
finally:
stop.set()
server.shutdown()
listener.close()
def main(argv=None):
parser = argparse.ArgumentParser(description=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("--compositor", type=Path, default=ROOT / "target/debug/weft-compositor")
parser.add_argument("--target", type=Path, default=ROOT / "target/debug",
help="directory with weft-appd, weft-runtime and weft-app-shell")
parser.add_argument("--output", type=Path, default=ROOT / "target/confinement-check")
args = parser.parse_args(argv)
missing = missing_tools() + [str(p) for p in (args.compositor, args.target / "weft-appd",
args.target / "weft-runtime",
args.target / "weft-app-shell")
if not p.is_file()]
if missing:
print("missing: " + ", ".join(missing), file=sys.stderr)
return 2
store = Path(tempfile.mkdtemp(prefix="weft-store-"))
try:
with Desktop(args.compositor, args.output, outputs=["appd.log", "confinement.ppm"]) \
as desktop:
try:
run(args, desktop, store)
except AssertionError:
(args.output / "confinement.ppm").write_bytes(desktop.capture())
raise
except (AssertionError, SessionError, TimeoutError) as failure:
print(f"confinement 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)
(store.parent / f"{store.name}-other.png").unlink(missing_ok=True)
print("confinement check passed")
return 0
if __name__ == "__main__":
raise SystemExit(main())

View file

@ -13,16 +13,19 @@ weft-app-shell for it. The host must print READY, and the page must be on
screen within a short grace period after READY, because the compositor shows screen within a short grace period after READY, because the compositor shows
a presented frame slightly later. READY printed within that grace before the a presented frame slightly later. READY printed within that grace before the
page is presented is therefore not detected. `--slow-style SECONDS` makes page is presented is therefore not detected. `--slow-style SECONDS` makes
early readiness observable: the page stays hidden until a stylesheet that a early readiness observable: the page stays hidden until a stylesheet next to it
local HTTP server delivers after the delay reveals it, so a host that reports reveals it, and the harness holds a file lease that keeps the stylesheet from
being opened until the delay has passed, so a host that reports
READY before the document has loaded shows no page within the grace period. READY before the document has loaded shows no page within the grace period.
Requires Xvfb, xwd and ImageMagick's convert; see session.py. Requires Xvfb, xwd and ImageMagick's convert; see session.py.
""" """
import argparse import argparse
import http.server import fcntl
import os
import shutil import shutil
import signal
import sys import sys
import threading import threading
import time import time
@ -101,31 +104,32 @@ def install_app(store, page):
return store return store
def slow_style_server(delay): def slow_style(directory, delay):
"""Serve a stylesheet that reveals the page after `delay` seconds.""" """Create `directory/reveal.css`, a stylesheet revealing the page, that
class Handler(http.server.BaseHTTPRequestHandler): cannot be opened until `delay` seconds have passed. A write lease makes
def do_GET(self): any other process's open() wait until the lease is released. The
time.sleep(delay) stylesheet is a local file next to the page, so an application host
body = b"body { visibility: visible; }" confined to its UI directory may load it."""
self.send_response(200) sheet = directory / "reveal.css"
self.send_header("Content-Type", "text/css") sheet.write_text("body { visibility: visible; }", encoding="utf-8")
self.send_header("Content-Length", str(len(body))) # The kernel signals the lease holder when another open() waits on it.
self.end_headers() signal.signal(signal.SIGIO, signal.SIG_IGN)
self.wfile.write(body) lease = os.open(sheet, os.O_WRONLY)
fcntl.fcntl(lease, fcntl.F_SETLEASE, fcntl.F_WRLCK)
def log_message(self, *args): def release():
pass time.sleep(delay)
fcntl.fcntl(lease, fcntl.F_SETLEASE, fcntl.F_UNLCK)
os.close(lease)
server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler) threading.Thread(target=release, daemon=True).start()
threading.Thread(target=server.serve_forever, daemon=True).start()
return server
def hidden_until_styled(page, destination, port): def hidden_until_styled(page, destination):
"""Copy `page`, hiding its body until the delayed stylesheet loads.""" """Copy `page`, hiding its body until the delayed stylesheet loads."""
html = page.read_text(encoding="utf-8") html = page.read_text(encoding="utf-8")
link = (f'<style>body {{ visibility: hidden; }}</style>\n' link = ('<style>body { visibility: hidden; }</style>\n'
f'<link rel="stylesheet" href="http://127.0.0.1:{port}/reveal.css">\n</head>') '<link rel="stylesheet" href="reveal.css">\n</head>')
if "</head>" not in html: if "</head>" not in html:
raise ValueError(f"{page} has no </head>") raise ValueError(f"{page} has no </head>")
destination.write_text(html.replace("</head>", link, 1), encoding="utf-8") destination.write_text(html.replace("</head>", link, 1), encoding="utf-8")
@ -149,6 +153,11 @@ def main(argv=None):
parser.add_argument("--output", type=Path, default=ROOT / "target/frame-check", parser.add_argument("--output", type=Path, default=ROOT / "target/frame-check",
help="directory for logs and the captured screenshot") help="directory for logs and the captured screenshot")
args = parser.parse_args(argv) args = parser.parse_args(argv)
if args.slow_style:
# The kernel revokes a lease that is held longer than this.
limit = int(Path("/proc/sys/fs/lease-break-time").read_text())
if not 0 < args.slow_style < limit:
parser.error(f"--slow-style must be between 0 and {limit} seconds")
if args.shell is None: if args.shell is None:
name = "weft-servo-shell" if args.host == "system" else "weft-app-shell" name = "weft-servo-shell" if args.host == "system" else "weft-app-shell"
args.shell = ROOT / "target/debug" / name args.shell = ROOT / "target/debug" / name
@ -158,28 +167,26 @@ def main(argv=None):
print("missing: " + ", ".join(missing), file=sys.stderr) print("missing: " + ", ".join(missing), file=sys.stderr)
return 2 return 2
style_server = None
try: try:
with Desktop(args.compositor, args.output, outputs=["frame.ppm"]) as desktop: with Desktop(args.compositor, args.output, outputs=["frame.ppm"]) as desktop:
page = args.page page = args.page
if args.slow_style: if args.slow_style:
style_server = slow_style_server(args.slow_style) page = hidden_until_styled(args.page, desktop.runtime / "page.html")
page = hidden_until_styled(args.page, desktop.runtime / "page.html",
style_server.server_address[1])
if args.host == "system": if args.host == "system":
if args.slow_style:
slow_style(desktop.runtime, args.slow_style)
shell = desktop.launch_client( shell = desktop.launch_client(
"shell", [args.shell], {"WEFT_SYSTEM_UI_HTML": str(page.resolve())}) "shell", [args.shell], {"WEFT_SYSTEM_UI_HTML": str(page.resolve())})
else: else:
store = install_app(desktop.runtime / "store", page) store = install_app(desktop.runtime / "store", page)
if args.slow_style:
slow_style(store / APP_ID / "ui", args.slow_style)
shell = desktop.launch_client( shell = desktop.launch_client(
"shell", [args.shell, APP_ID, "1"], {"WEFT_APP_STORE": str(store)}) "shell", [args.shell, APP_ID, "1"], {"WEFT_APP_STORE": str(store)})
problems, screenshot = watch(desktop, shell, args) problems, screenshot = watch(desktop, shell, args)
except SessionError as error: except SessionError as error:
print(error, file=sys.stderr) print(error, file=sys.stderr)
return 1 return 1
finally:
if style_server is not None:
style_server.shutdown()
if screenshot is not None: if screenshot is not None:
(args.output / "frame.ppm").write_bytes(screenshot) (args.output / "frame.ppm").write_bytes(screenshot)

View file

@ -0,0 +1,65 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>confinement</title>
<style>
html, body { margin: 0; height: 100%; }
body { display: flex; flex-direction: column; }
div { flex: 1; background: #808080; }
</style>
</head>
<body>
<div id="own-image"></div>
<div id="bridge"></div>
<div id="outside-image"></div>
<div id="other-image"></div>
<div id="http-image"></div>
<div id="http-fetch"></div>
<div id="websocket"></div>
<script>
// One band per probe: green when the outcome matches the policy, red when it
// does not. Every refused probe would succeed without the policy: the images
// are valid PNG files, the fetch uses no-cors, so an opaque response would
// resolve it, and the WebSocket listener accepts connections. The harness
// substitutes the ports and the path of a file outside the package.
var HTTP = 'http://127.0.0.1:@HTTP_PORT@/';
var TCP = 'ws://127.0.0.1:@TCP_PORT@/';
var OTHER = '@OTHER_URL@';
function mark(id, ok) {
document.getElementById(id).style.background = ok ? '#00c000' : '#e00000';
}
function image(id, src, shouldLoad) {
var img = new Image();
img.onload = function () { mark(id, shouldLoad); };
img.onerror = function () { mark(id, !shouldLoad); };
img.src = src;
}
image('own-image', 'own.png', true);
image('outside-image', '../outside.png', false);
image('other-image', OTHER, false);
image('http-image', HTTP + 'image.png', false);
fetch(HTTP + 'probe', { mode: 'no-cors' }).then(
function () { mark('http-fetch', false); },
function () { mark('http-fetch', true); });
try {
var ws = new WebSocket(TCP);
ws.onopen = function () { mark('websocket', false); };
ws.onerror = function () { mark('websocket', true); };
} catch (e) {
mark('websocket', true);
}
(function bridge() {
if (!window.weftIpc) { setTimeout(bridge, 50); return; }
window.weftIpc.onmessage = function (raw) {
try { mark('bridge', typeof JSON.parse(raw).count === 'number'); } catch (_) {}
};
window.weftIpc.send('get');
})();
</script>
</body>
</html>