diff --git a/crates/weft-app-shell/src/embedder.rs b/crates/weft-app-shell/src/embedder.rs index 37880f1..bb72692 100644 --- a/crates/weft-app-shell/src/embedder.rs +++ b/crates/weft-app-shell/src/embedder.rs @@ -65,6 +65,9 @@ struct WeftWebViewDelegate { signals: Arc, /// URL prefix of the application's UI directory; see `ui_scope`. scope: String, + /// The bridge's WebSocket handshake URL, as the network layer requests it + /// (`ws:` becomes `http:`). + bridge: String, } 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) { if status != LoadStatus::Complete { 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. fn js_string(value: &str) -> String { let mut literal = String::with_capacity(value.len() + 2); @@ -428,6 +457,7 @@ impl ApplicationHandler for App { .delegate(Rc::new(WeftWebViewDelegate { signals: Arc::clone(&self.signals), scope: ui_scope(&self.url), + bridge: format!("http://127.0.0.1:{}/app", self.ws_port), })) .user_content_manager(ucm) .url(self.url.clone().into_url()) diff --git a/docs/architecture.md b/docs/architecture.md index fd59065..6806fc5 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -16,7 +16,7 @@ System UI host. Renders one WebView pointing at `system-ui.html` using the embed ### weft-app-shell -Per-application Servo host. Spawned by `weft-appd` after the Wasm runtime signals READY. Takes `` and `` as arguments. Resolves `weft-app:///ui/index.html` and injects the `weftIpc` WebSocket bridge into the page. The bridge authenticates with the per-session token from `WEFT_BRIDGE_TOKEN` and can only exchange messages with its own session. It is installed only in top-level documents inside the application's UI directory, and 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 `` and `` as arguments. Resolves `weft-app:///ui/index.html` and injects the `weftIpc` WebSocket bridge into the page. The bridge authenticates with the per-session token from `WEFT_BRIDGE_TOKEN` and can only exchange messages with its own session. It is installed only in top-level documents inside the application's UI directory, and 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 diff --git a/docs/building.md b/docs/building.md index e0cb837..57697dd 100644 --- a/docs/building.md +++ b/docs/building.md @@ -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 `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`. @@ -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_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_confinement.py # an app page reaches only its UI files and its session bridge ``` ## Demo apps (wasm32-wasip2) diff --git a/tests/frame/check_confinement.py b/tests/frame/check_confinement.py new file mode 100644 index 0000000..e62f86e --- /dev/null +++ b/tests/frame/check_confinement.py @@ -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()) diff --git a/tests/frame/check_frame.py b/tests/frame/check_frame.py index 8fd89a0..60eb243 100644 --- a/tests/frame/check_frame.py +++ b/tests/frame/check_frame.py @@ -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 a presented frame slightly later. READY printed within that grace before the page is presented is therefore not detected. `--slow-style SECONDS` makes -early readiness observable: the page stays hidden until a stylesheet that a -local HTTP server delivers after the delay reveals it, so a host that reports +early readiness observable: the page stays hidden until a stylesheet next to it +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. Requires Xvfb, xwd and ImageMagick's convert; see session.py. """ import argparse -import http.server +import fcntl +import os import shutil +import signal import sys import threading import time @@ -101,31 +104,32 @@ def install_app(store, page): return store -def slow_style_server(delay): - """Serve a stylesheet that reveals the page after `delay` seconds.""" - class Handler(http.server.BaseHTTPRequestHandler): - def do_GET(self): - time.sleep(delay) - body = b"body { visibility: visible; }" - self.send_response(200) - self.send_header("Content-Type", "text/css") - self.send_header("Content-Length", str(len(body))) - self.end_headers() - self.wfile.write(body) +def slow_style(directory, delay): + """Create `directory/reveal.css`, a stylesheet revealing the page, that + cannot be opened until `delay` seconds have passed. A write lease makes + any other process's open() wait until the lease is released. The + stylesheet is a local file next to the page, so an application host + confined to its UI directory may load it.""" + sheet = directory / "reveal.css" + sheet.write_text("body { visibility: visible; }", encoding="utf-8") + # The kernel signals the lease holder when another open() waits on it. + signal.signal(signal.SIGIO, signal.SIG_IGN) + lease = os.open(sheet, os.O_WRONLY) + fcntl.fcntl(lease, fcntl.F_SETLEASE, fcntl.F_WRLCK) - def log_message(self, *args): - pass + def release(): + 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=server.serve_forever, daemon=True).start() - return server + threading.Thread(target=release, daemon=True).start() -def hidden_until_styled(page, destination, port): +def hidden_until_styled(page, destination): """Copy `page`, hiding its body until the delayed stylesheet loads.""" html = page.read_text(encoding="utf-8") - link = (f'\n' - f'\n') + link = ('\n' + '\n') if "" not in html: raise ValueError(f"{page} has no ") destination.write_text(html.replace("", link, 1), encoding="utf-8") @@ -149,6 +153,11 @@ def main(argv=None): parser.add_argument("--output", type=Path, default=ROOT / "target/frame-check", help="directory for logs and the captured screenshot") 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: name = "weft-servo-shell" if args.host == "system" else "weft-app-shell" args.shell = ROOT / "target/debug" / name @@ -158,28 +167,26 @@ def main(argv=None): print("missing: " + ", ".join(missing), file=sys.stderr) return 2 - style_server = None try: with Desktop(args.compositor, args.output, outputs=["frame.ppm"]) as desktop: page = args.page if args.slow_style: - style_server = slow_style_server(args.slow_style) - page = hidden_until_styled(args.page, desktop.runtime / "page.html", - style_server.server_address[1]) + page = hidden_until_styled(args.page, desktop.runtime / "page.html") if args.host == "system": + if args.slow_style: + slow_style(desktop.runtime, args.slow_style) shell = desktop.launch_client( "shell", [args.shell], {"WEFT_SYSTEM_UI_HTML": str(page.resolve())}) else: 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", [args.shell, APP_ID, "1"], {"WEFT_APP_STORE": str(store)}) problems, screenshot = watch(desktop, shell, args) except SessionError as error: print(error, file=sys.stderr) return 1 - finally: - if style_server is not None: - style_server.shutdown() if screenshot is not None: (args.output / "frame.ppm").write_bytes(screenshot) diff --git a/tests/frame/confinement/index.html b/tests/frame/confinement/index.html new file mode 100644 index 0000000..23b7bda --- /dev/null +++ b/tests/frame/confinement/index.html @@ -0,0 +1,65 @@ + + + + +confinement + + + +
+
+
+
+
+
+
+ + +