Skip to content

wayland

wayland

Select a desktop endpoint and restrict the proxy's compositor protocols.

Wayland grants protocol access, not merely permission to draw a window. The filtered mode exposes only the globals listed here. Direct mode deliberately retains the compositor's full client interface. Neither mode forwards audio, X11, the desktop runtime directory, or inherited display file descriptors.

WAYLAND_ENV_UNSET = ('WAYLAND_SOCKET', 'DISPLAY', 'XAUTHORITY') module-attribute

Endpoints that must not override the selected Wayland socket.

MOUNTS_NOT_PREPARED = 'desktop mounts were not prepared; recreate the task to enable Wayland' module-attribute

Why a container created without desktop mounts stays without GUI on every restart.

ALLOWED_GLOBALS = ('wl_compositor', 'wl_subcompositor', 'wl_shm', 'wl_output', 'wl_seat', 'xdg_wm_base', 'zxdg_decoration_manager_v1', 'wp_viewporter', 'wp_fractional_scale_manager_v1', 'wp_presentation', 'zwp_linux_dmabuf_v1', 'zwp_linux_explicit_synchronization_v1', 'wp_linux_drm_syncobj_manager_v1', 'wp_single_pixel_buffer_manager_v1', 'zwp_relative_pointer_manager_v1', 'zwp_pointer_constraints_v1', 'wp_cursor_shape_manager_v1') module-attribute

App surfaces, focused input, and rendering; unknown globals stay denied.

Clipboard/data devices, capture, input injection, DRM leasing, and desktop management are intentionally absent. FD transport remains wl-mitm's job.

WAYLAND_PROBE = ['python3', '-c', "import socket, struct, sys\nwith socket.socket(socket.AF_UNIX) as peer:\n peer.settimeout(2)\n peer.connect(sys.argv[1])\n peer.sendall(struct.pack('=III', 1, 12 << 16, 2))\n with peer.makefile('rb') as replies:\n reply = replies.read(12)\n if len(reply) != 12 or struct.unpack('=III', reply)[:2] != (2, 12 << 16):\n raise RuntimeError('compositor did not acknowledge Wayland sync')\n", CONTAINER_WAYLAND_SOCKET] module-attribute

Bounded wl_display.sync roundtrip from the container's security domain.

The proxy connects upstream only after accepting a client. A successful connect alone cannot detect denied or unavailable compositor access.

WaylandMode

Bases: StrEnum

The desktop access explicitly granted to a task.

NONE = 'none' class-attribute instance-attribute

MITM = 'wl-mitm' class-attribute instance-attribute

DIRECT = 'wl-direct' class-attribute instance-attribute

WaylandSession(mode=WaylandMode.NONE, upstream=None, binary=None, error=None, disabled_reason=None, direct_selinux=False) dataclass

Host-selected endpoints captured before a supervisor crosses namespaces.

mode = WaylandMode.NONE class-attribute instance-attribute

upstream = None class-attribute instance-attribute

binary = None class-attribute instance-attribute

error = None class-attribute instance-attribute

disabled_reason = None class-attribute instance-attribute

Immutable isolation constraint: a restart must not add a mount creation refused.

direct_selinux = False class-attribute instance-attribute

Immutable selection of the direct-access process domain at container creation.

proxied property

Whether this start has enough host wiring to launch the proxy.

mounted property

Whether creation gave the container its desktop mounts.

wired property

Whether this start has a complete path from the container to a compositor.

bound_socket property

The compositor socket a direct container holds as a bind mount, if it holds one.

malformed property

Whether the saved wiring could not be read back.

refreshed()

Resolve this start's endpoints for the same grant.

What creation decided — the process domain, and whether desktop mounts exist at all — carries over unchanged, so one start from an unsuitable shell cannot cost a container the mounts it has.

Raises:

Type Description
WaylandRecreationRequired

The saved wiring is unreadable, or a direct container's bound socket is gone or no longer the session's; Podman cannot retarget a saved bind mount.

Source code in src/terok_sandbox/wayland.py
def refreshed(self) -> WaylandSession:
    """Resolve this start's endpoints for the same grant.

    What creation decided — the process domain, and whether desktop
    mounts exist at all — carries over unchanged, so one start from an
    unsuitable shell cannot cost a container the mounts it has.

    Raises:
        WaylandRecreationRequired: The saved wiring is unreadable, or a
            direct container's bound socket is gone or no longer the
            session's; Podman cannot retarget a saved bind mount.
    """
    if self.malformed:
        raise WaylandRecreationRequired(
            f"Wayland recreation required: cannot verify saved desktop access: {self.error}"
        )
    current = replace(
        resolve_session(self.mode, unavailable=self.disabled_reason),
        direct_selinux=self.direct_selinux,
        disabled_reason=self.disabled_reason,
    )
    keeps_bind = self.mode == WaylandMode.DIRECT and self.mounted
    if keeps_bind and (current.upstream is None or current.upstream != self.upstream):
        raise WaylandRecreationRequired(
            "wl-direct recreation required: the saved compositor socket is missing "
            "or the current session selects another socket"
        )
    return current

payload()

Return the JSON representation stored in the private task sidecar.

Source code in src/terok_sandbox/wayland.py
def payload(self) -> dict[str, str | bool | None]:
    """Return the JSON representation stored in the private task sidecar."""
    return {
        "mode": self.mode.value,
        "upstream": str(self.upstream) if self.upstream else None,
        "binary": str(self.binary) if self.binary else None,
        "error": self.error,
        "disabled_reason": self.disabled_reason,
        "direct_selinux": self.direct_selinux,
    }

from_payload(value) classmethod

Decode saved wiring, retaining malformed data as an explicit error.

Source code in src/terok_sandbox/wayland.py
@classmethod
def from_payload(cls, value: object) -> WaylandSession:
    """Decode saved wiring, retaining malformed data as an explicit error."""
    if value is None:
        return cls()
    try:
        if not isinstance(value, dict):
            raise ValueError("expected an object")
        mode = WaylandMode(value["mode"])
        upstream, binary = (
            Path(value[key]) if value.get(key) else None for key in ("upstream", "binary")
        )
        if any(path is not None and not path.is_absolute() for path in (upstream, binary)):
            raise ValueError("paths must be absolute")
        direct_selinux = value.get("direct_selinux", False)
        if not isinstance(direct_selinux, bool):
            raise ValueError("direct_selinux must be a boolean")
        return cls(
            mode,
            upstream=upstream,
            binary=binary,
            error=value.get("error"),
            disabled_reason=value.get("disabled_reason"),
            direct_selinux=direct_selinux,
        )
    except (KeyError, TypeError, ValueError) as exc:
        return cls(error=f"invalid Wayland sidecar: {exc}")

WaylandRecreationRequired

Bases: RuntimeError

A saved socket bind or process domain cannot change without recreation.

resolve_session(mode, *, unavailable=None)

Resolve the invoking user's current desktop; failure costs only GUI access.

Source code in src/terok_sandbox/wayland.py
def resolve_session(mode: WaylandMode, *, unavailable: str | None = None) -> WaylandSession:
    """Resolve the invoking user's current desktop; failure costs only GUI access."""
    if mode == WaylandMode.NONE:
        return WaylandSession()
    try:
        if unavailable:
            raise ValueError(unavailable)
        if os.geteuid() == 0:
            raise ValueError("requires rootless Podman, invoked as the desktop user")
        if any(os.environ.get(name) for name in ("CONTAINER_HOST", "CONTAINER_CONNECTION")):
            unavailable = "Wayland requires local Podman; remote connections are unsupported"
            raise ValueError(unavailable)
        upstream = _session_socket()
        binary = None
        if mode == WaylandMode.MITM:
            executable = find_host_tool("wl-mitm")
            if executable is None:
                raise ValueError("wl-mitm not found; install it on the host and restart the task")
            binary = Path(executable).resolve(strict=True)
        return WaylandSession(mode, upstream, binary)
    except (OSError, ValueError) as exc:
        return WaylandSession(mode, error=str(exc), disabled_reason=unavailable)

proxy_config(upstream, listener)

Build stock wl-mitm TOML with no command hooks or permissive dry run.

JSON string syntax doubles as TOML basic strings once non-ASCII text is left unescaped: TOML rejects the surrogate pairs JSON would write.

Source code in src/terok_sandbox/wayland.py
def proxy_config(upstream: Path, listener: Path) -> bytes:
    """Build stock wl-mitm TOML with no command hooks or permissive dry run.

    JSON string syntax doubles as TOML basic strings once non-ASCII text is
    left unescaped: TOML rejects the surrogate pairs JSON would write.
    """
    quoted = partial(json.dumps, ensure_ascii=False)
    return (
        f"[socket]\nlisten = {quoted(str(listener))}\n"
        f"upstream = {quoted(str(upstream))}\n"
        f"[filter]\nallowed_globals = {quoted(ALLOWED_GLOBALS)}\n"
        "requests = []\ndry_run = false\n"
    ).encode()

warn_wayland(mode, reason, *, log=None, observer=None)

Make optional desktop failure visible without claiming its cause is SELinux.

Source code in src/terok_sandbox/wayland.py
def warn_wayland(
    mode: WaylandMode,
    reason: str,
    *,
    log: Path | None = None,
    observer: Callable[[str], None] | None = None,
) -> None:
    """Make optional desktop failure visible without claiming its cause is SELinux."""
    emit_warning(
        f"WARNING: Wayland ({mode}) unavailable: {reason}. "
        "Task continues without GUI access."
        + (" No direct-socket fallback." if mode == WaylandMode.MITM else "")
        + (f" Supervisor log: {log}" if log else ""),
        observer=observer,
    )

warn_desktop_access(mode, *, observer=None)

Keep the host-desktop attack surface explicit in both opt-in modes.

Source code in src/terok_sandbox/wayland.py
def warn_desktop_access(
    mode: WaylandMode, *, observer: Callable[[str], None] | None = None
) -> None:
    """Keep the host-desktop attack surface explicit in both opt-in modes."""
    if mode == WaylandMode.NONE:
        return
    access = (
        "Direct mode exposes the compositor's full client interface without protocol filtering."
        if mode == WaylandMode.DIRECT
        else "Protocol filtering reduces exposure but does not isolate the host desktop."
    )
    emit_warning(
        f"WARNING: Wayland ({mode}) significantly increases host attack surface. {access}",
        observer=observer,
    )

emit_warning(message, *, observer=None)

Present one startup warning on stderr, terminal-safe, and hand it to observer as plain text.

The single renderer of these warnings: a front-end that repeats what a LifecycleHooks observer collected passes each message back through here.

Source code in src/terok_sandbox/wayland.py
def emit_warning(message: str, *, observer: Callable[[str], None] | None = None) -> None:
    """Present one startup warning on stderr, terminal-safe, and hand it to *observer* as plain text.

    The single renderer of these warnings: a front-end that repeats what a
    [`LifecycleHooks`][terok_sandbox.sandbox.LifecycleHooks] observer
    collected passes each message back through here.
    """
    message = sanitize_tty(message)
    rendered = message
    if message.startswith(f"WARNING: Wayland ({WaylandMode.DIRECT})"):
        prefix = red("WARNING:", enabled=sys.stderr.isatty() and "NO_COLOR" not in os.environ)
        rendered = message.replace("WARNING:", prefix, 1)
    print(rendered, file=sys.stderr)
    if observer is not None:
        try:
            observer(message)
        except Exception as exc:  # noqa: BLE001 - warning observers never control task startup
            _logger.warning("Wayland warning observer failed: %s", exc)