diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 442179a..c563540 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -11,6 +11,7 @@ on: - 'cxbox' - 'ompbox' - 'lib/**' + - 'integrations/clipboard-ssh/**' - 'tests/**' - 'init-firewall.sh' - 'k8s/**' @@ -27,7 +28,7 @@ jobs: uses: actions/checkout@v7 - name: shellcheck - run: shellcheck ccbox ocbox qcbox cxbox ompbox lib/box-common.sh init-firewall.sh tests/render-test.sh k8s/entrypoint.sh k8s/gen-egress-firewall.sh + run: shellcheck ccbox ocbox qcbox cxbox ompbox lib/box-common.sh init-firewall.sh tests/render-test.sh tests/clipboard-bridge-test.sh integrations/clipboard-ssh/codebox-clipboard-serve k8s/entrypoint.sh k8s/gen-egress-firewall.sh - name: Render the kustomizations run: | @@ -40,3 +41,6 @@ jobs: - name: Golden test of the rendered command line run: tests/render-test.sh + + - name: Clipboard image bridge + run: tests/clipboard-bridge-test.sh diff --git a/AGENTS.md b/AGENTS.md index cb52e8f..2e6a657 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -120,10 +120,12 @@ For local development, you can build the image locally: - `init-firewall.sh` - Firewall initialization script (iptables/ipset) - `lib/box-common.sh` - Shared launcher engine (sourced by all five launchers): runtime-neutral session spec (`add_mount` / `add_env`) plus two runtime backends that render it, Podman (`podman run`, workstation) and Apptainer (`apptainer exec` on a SIF, long-lived pod; selected with `--runtime` / `CODEBOX_RUNTIME`) - `tests/render-test.sh` + `tests/golden/` - Golden test of the rendered command line for every launcher (stub runtime; run it, and re-record when a change to mounts/env is intended) +- `tests/clipboard-bridge-test.sh` - Functional test of the clipboard image bridge (host helper + container shim against a stub `wl-paste`, including the SSH-forwarded source) - `ccbox` / `ocbox` / `qcbox` / `cxbox` / `ompbox` - Host launch scripts (thin wrappers defining harness identity, mounts, and env passthrough) - `CLAUDE_VERSION` / `OPENCODE_VERSION` / `QWENCODE_VERSION` / `CODEX_VERSION` / `OMP_VERSION` - Version pin files (overridden by `--claude-version` / `--opencode-version` / `--qwen-version` / `--codex-version` / `--omp-version`) - `k8s/` - Running in a long-lived pod on Kubernetes/OpenShift: `Containerfile` + `entrypoint.sh` (CentOS Stream 9 pod image `quay.io/guimou/codebox-pod`: Apptainer, tmux, the launchers; no dev tooling, that is in the SIF), `cluster/` (SCC + ClusterRole, cluster-admin, once), `base/` + `overlays/example/` (kustomize: service account, PVC, Deployment; the overlay sets namespace, RWX storage class, optional env Secret), `gen-egress-firewall.sh` (OVN EgressFirewall from the firewall domain lists, the pod-level replacement for `--with-firewall`) - `integrations/herdr-app-agent-memory/` - Herdr app mod (gpui-kit JavaScript panel, installed as `~/.config/herdr-app/mods/agent-memory`): maps each agent to its codebox container via the terminal's foreground `podman run --name`, shows per-agent working set (cgroup `memory.current` minus `inactive_file`) and the `codebox.slice` budget, toasts near `memory.high`; `agent_mem.py` (stdlib Python) reads the cgroups/`/proc` for it, `logic.js` holds the pure helpers +- `integrations/clipboard-ssh/` - Clipboard image server for the machine the user types on (`codebox-clipboard-serve` + systemd user socket/service units), reached by a remote launcher's clipboard bridge through an SSH-forwarded unix socket - `docs/` - User-facing documentation: `usage.md`, `architecture.md`, `development.md`, `kubernetes.md` (README holds only the minimum and links here — keep them in sync when changing behavior) ## What's Included @@ -278,6 +280,7 @@ The launchers also run inside a long-lived pod (`docs/kubernetes.md`): the pod i - `~/.gitconfig` → `/home/coder/.gitconfig` (read-only, only with `--with-gitconfig`) - any host directory → the given absolute container path (read-write, or `ro`; only with `--mount HOST:CONTAINER[:ro]`, repeatable) - npm global prefix → `/home/coder/.npm-global` (read-only, auto-detected) + - Clipboard: the Wayland/X11 socket (read-only), or with SELinux enforcing the clipboard bridge directory → `/run/codebox-clipboard` plus its shim → `/usr/local/bin/wl-paste` and `/usr/local/bin/wl-copy` - PulseAudio socket (for audio support) - `/etc/localtime` (for timezone sync) - **SELinux**: Uses `:z` volume labels for shared relabeling (supports multi-session) @@ -295,6 +298,8 @@ Image pasting (CTRL+V) is enabled by default. The container mounts display socke - **Wayland**: Mounts `$XDG_RUNTIME_DIR/$WAYLAND_DISPLAY` (read-only) - **X11**: Mounts `/tmp/.X11-unix` and `~/.Xauthority` (read-only) +With SELinux enforcing, the display socket is not wired at all (`selinux_enforcing` in `lib/box-common.sh`): a confined container cannot connect to it. The clipboard goes through the clipboard bridge instead (`clipboard_bridge_*` in `lib/box-common.sh`): a host helper process started by the launcher runs the host's `wl-paste`/`wl-copy` (or `xclip`) on request, talking to a shim mounted as `/usr/local/bin/wl-paste` and `/usr/local/bin/wl-copy` through a FIFO and files in `$XDG_RUNTIME_DIR/codebox-clipboard//shared` (mounted at `/run/codebox-clipboard`). `WAYLAND_DISPLAY=codebox-clipboard-bridge` (not a socket) is set in the container because harnesses only use `wl-copy`/`wl-paste --primary` for selection copy and middle-click paste when it is set; without the shims they would fail instead of working. The bridge carries clipboard images (read), the selection (write to clipboard and primary, read of primary), and refuses reads of the regular clipboard text. The local source requires `wl-clipboard` (or `xclip`) on the host. For sessions used over SSH, the helper first asks a clipboard socket forwarded from the user's machine (`$XDG_RUNTIME_DIR/codebox-clipboard-ssh.sock`, `CODEBOX_CLIPBOARD_SOCKET` overrides; needs `python3` on the host), served there by `integrations/clipboard-ssh/` (socket-activated `codebox-clipboard-serve`); the source is chosen per paste. The bridge is also set up when that socket answers at launch or the host has no display. Setup is documented in docs/usage.md "Pasting Images over SSH". + To disable clipboard access: `./ccbox --no-clipboard` **Note**: Clipboard image pasting in containers has known limitations. If CTRL+V doesn't work, use file paths instead (e.g., paste `/path/to/image.png`). diff --git a/docs/usage.md b/docs/usage.md index c62e97c..78c20b4 100644 --- a/docs/usage.md +++ b/docs/usage.md @@ -344,10 +344,102 @@ Image pasting (CTRL+V) requires display server access: - **macOS**: requires [XQuartz](https://www.xquartz.org/) with "Allow connections from network clients" enabled - **None found**: the launcher prints a `[WARN] No display server found` line and reports `Clipboard: unavailable` in the status, so a clipboard-blind session is never silent +- **SELinux enforcing (Fedora, RHEL)**: the display socket is **not** wired. SELinux denies a confined container any connection to the compositor or X server, so the socket would be mounted but dead. The clipboard goes through a **host bridge** instead: the launcher starts a small helper on the host that runs the host's `wl-paste`/`wl-copy` (`xclip` on X11) on request, and mounts shims for `wl-paste` and `wl-copy` in the container that ask it through a per-session directory (`$XDG_RUNTIME_DIR/codebox-clipboard/`, removed when the session ends). `WAYLAND_DISPLAY` is set in the container to a name that is not a socket, only so that harnesses use those two commands. The container gets no display access. What the bridge carries: + - **Images** of the clipboard (CTRL+V), read-only. + - **The selection**: text selected in the harness is written to the host clipboard and primary selection, and the primary selection can be read back, so select + middle-click paste works in both directions (including text selected in another window). The terminal also still receives every copy (OSC 52). + - **Not** the text of the regular clipboard (what CTRL+C or a password manager put there): that request is refused. Paste it with the terminal's own paste (CTRL+SHIFT+V). + - It needs `wl-clipboard` (or `xclip` on X11) installed **on the host** (`sudo dnf install wl-clipboard`). Without it the launcher warns that this machine's clipboard cannot be read: middle-click then only pastes what was last selected in that session, and images can only come from an SSH-forwarded clipboard (below). + - The bridge uses the clipboard of the machine running the launcher. When you work on that machine over SSH, see [Pasting Images over SSH](#pasting-images-over-ssh) to make it read the images of the machine you are typing on instead. + To disable clipboard access: `ccbox --no-clipboard` **Note:** clipboard image pasting in containers has known limitations. If CTRL+V doesn't work, use file paths instead (e.g., paste `/path/to/image.png`). +## Pasting Images over SSH + +When the launcher runs on a remote machine (plain `ssh`, or a terminal such as Herdr or Ghostty connected through it), the image you copied is on the clipboard of the machine in front of you, which the remote machine cannot see. Text is not affected: copies reach your local clipboard through the terminal (OSC 52), and you paste with the terminal's own paste. Middle-click pastes the remote machine's primary selection, or what was last selected in that session; the local primary selection is not forwarded. + +For images, the clipboard bridge described above can ask your local machine, through a unix socket forwarded by SSH: + +``` + local machine (laptop) remote machine + ---------------------- -------------- + clipboard harness in the container: CTRL+V + ^ wl-paste / xclip | wl-paste shim + codebox-clipboard-serve v + ^ $XDG_RUNTIME_DIR/codebox-clipboard.sock bridge helper (started by the launcher) + | | + +------------ ssh RemoteForward <--------------+ $XDG_RUNTIME_DIR/codebox-clipboard-ssh.sock +``` + +Only image types are served (`png`, `jpeg`, `gif`, `webp`, `bmp`): the local server refuses anything else, so clipboard text never leaves your machine this way. + +### 1. Local machine: install the clipboard server + +Requires Linux with systemd and `wl-clipboard` (`xclip` on X11). From a checkout of this repository: + +```bash +sudo dnf install wl-clipboard +install -D -m 755 integrations/clipboard-ssh/codebox-clipboard-serve ~/.local/bin/codebox-clipboard-serve +install -D -m 644 -t ~/.config/systemd/user \ + integrations/clipboard-ssh/codebox-clipboard.socket \ + integrations/clipboard-ssh/codebox-clipboard@.service +systemctl --user daemon-reload +systemctl --user enable --now codebox-clipboard.socket +``` + +Nothing runs permanently: systemd listens on `$XDG_RUNTIME_DIR/codebox-clipboard.sock` (mode `0600`) and starts the script for the duration of one request. Check it with an image on the clipboard: + +```bash +printf 'list\n' | python3 -c 'import socket,sys,os; s=socket.socket(socket.AF_UNIX); s.connect(os.environ["XDG_RUNTIME_DIR"]+"/codebox-clipboard.sock"); s.sendall(sys.stdin.buffer.read()); s.shutdown(1); print(s.makefile().read())' +# ok +# image/png +``` + +### 2. Local machine: forward the socket in `~/.ssh/config` + +``` +Host my-remote + RemoteForward /run/user/REMOTE_UID/codebox-clipboard-ssh.sock /run/user/LOCAL_UID/codebox-clipboard.sock +``` + +`LOCAL_UID` is `id -u` on the local machine, `REMOTE_UID` is `id -u` on the remote one (the first path is where the socket appears on the remote machine: `$XDG_RUNTIME_DIR/codebox-clipboard-ssh.sock` there). Anything that connects with the system `ssh` and this host entry gets the forward, including terminals that open their remote sessions through it. + +### 3. Remote machine: let `sshd` replace a stale socket + +When a connection drops, the forwarded socket file stays behind and the next connection cannot create it again (`Warning: remote port forwarding failed for listen path ...`). Allow `sshd` to replace it, once, as root: + +```bash +echo 'StreamLocalBindUnlink yes' | sudo tee /etc/ssh/sshd_config.d/50-codebox-clipboard.conf +sudo systemctl reload sshd +``` + +The remote machine also needs `python3` on the host (the bridge helper uses it to talk to the socket). Nothing has to be installed in the container image. + +### 4. Use it + +Reconnect, then start the launcher on the remote machine as usual. The status lines tell which sources the bridge has: + +``` +[INFO] Clipboard: host bridge: images (SSH-forwarded clipboard), selection and middle-click paste +``` + +Copy an image locally and press CTRL+V in the harness. + +How the source is chosen: + +- It is decided **for each paste**, not at launch: if something answers on the forwarded socket, the image comes from there; otherwise from the remote machine's own clipboard, when it has a display (and `wl-clipboard`/`xclip`). A session started at the remote machine's own desk and later attached over SSH, or the reverse, pastes from wherever you are connected from. +- A session started while no socket was forwarded still picks it up later, provided the bridge is active for that session: it is whenever SELinux is enforcing on the remote machine or the remote machine has no display. On a remote machine with a display and SELinux not enforcing, the display socket is wired directly instead (see above) unless the forwarded socket answers at launch, so connect first, then launch. +- With several SSH connections to the same remote machine, the last one to connect owns the socket. +- `CODEBOX_CLIPBOARD_SOCKET=/some/path` on the remote machine overrides the socket location. + +Security: while you are connected, any process running as your user on the remote machine can fetch the **image** currently on your local clipboard (not text). Remove the `RemoteForward` line, or `systemctl --user disable --now codebox-clipboard.socket`, to turn it off. `--no-clipboard` disables the bridge for a session. + +Troubleshooting: + +- Status shows `images (host wl-paste)` only, or `images once a clipboard socket is forwarded over SSH`: nothing answers on the remote socket. Check `ls -l $XDG_RUNTIME_DIR/codebox-clipboard-ssh.sock` on the remote machine and run `ssh -v` to see whether the forward was refused (step 3). +- The socket answers but pasting does nothing: on the local machine, `journalctl --user -u 'codebox-clipboard@*'` shows the server's errors (typically a missing `wl-clipboard`). + ## Agent Teams (ccbox only, experimental) Agent teams let you coordinate multiple Claude Code instances working in parallel: diff --git a/integrations/clipboard-ssh/codebox-clipboard-serve b/integrations/clipboard-ssh/codebox-clipboard-serve new file mode 100755 index 0000000..3cee1e0 --- /dev/null +++ b/integrations/clipboard-ssh/codebox-clipboard-serve @@ -0,0 +1,64 @@ +#!/bin/bash +# Clipboard image server for codebox sessions running on another machine. +# +# Runs on the machine you are typing on, once per connection (systemd socket +# activation, see codebox-clipboard.socket): stdin/stdout are the connection. +# The launcher on the remote machine reaches it through a unix socket +# forwarded over SSH and asks for the clipboard image when you press CTRL+V +# in a harness (docs/usage.md, "Pasting Images over SSH"). +# +# Protocol: one request line, "list" or "get "; the answer is +# "ok\n" followed by the payload (the image types, one per line, or the raw +# image), or "no\n". Only image types are ever served: clipboard text is +# never sent, whatever is asked. + +TYPES='image/(png|jpeg|jpg|gif|webp|bmp)' + +op="" type="" +read -r -t 5 op type || true +type="${type%$'\r'}" + +runtime_dir="${XDG_RUNTIME_DIR:-/run/user/$(id -u)}" +tool="" +if [[ -n "${WAYLAND_DISPLAY:-}" || -S "${runtime_dir}/wayland-0" ]]; then + tool="wl-paste" + export XDG_RUNTIME_DIR="$runtime_dir" WAYLAND_DISPLAY="${WAYLAND_DISPLAY:-wayland-0}" +elif [[ -n "${DISPLAY:-}" ]]; then + tool="xclip" +fi +if [[ -z "$tool" ]] || ! command -v "$tool" > /dev/null 2>&1; then + echo "codebox-clipboard-serve: no clipboard tool (install wl-clipboard, or xclip on X11)" >&2 + printf 'no\n' + exit 0 +fi + +paste() { # list | get TYPE + if [[ "$tool" == wl-paste ]]; then + if [[ "$1" == list ]]; then timeout 3 wl-paste --list-types; else timeout 5 wl-paste --type "$2"; fi + else + if [[ "$1" == list ]]; then timeout 3 xclip -selection clipboard -t TARGETS -o; else timeout 5 xclip -selection clipboard -t "$2" -o; fi + fi 2> /dev/null +} + +case "$op" in + list) + if types=$(paste list | grep -E "^${TYPES}\$"); then + printf 'ok\n%s\n' "$types" + else + printf 'no\n' + fi + ;; + get) + tmp=$(mktemp) || { printf 'no\n'; exit 0; } + trap 'rm -f "$tmp"' EXIT + if [[ "$type" =~ ^${TYPES}$ ]] && paste get "$type" > "$tmp" && [[ -s "$tmp" ]]; then + printf 'ok\n' + cat "$tmp" + else + printf 'no\n' + fi + ;; + *) + printf 'no\n' + ;; +esac diff --git a/integrations/clipboard-ssh/codebox-clipboard.socket b/integrations/clipboard-ssh/codebox-clipboard.socket new file mode 100644 index 0000000..f0a4b27 --- /dev/null +++ b/integrations/clipboard-ssh/codebox-clipboard.socket @@ -0,0 +1,10 @@ +[Unit] +Description=codebox clipboard image server (image pasting in SSH sessions) + +[Socket] +ListenStream=%t/codebox-clipboard.sock +SocketMode=0600 +Accept=yes + +[Install] +WantedBy=sockets.target diff --git a/integrations/clipboard-ssh/codebox-clipboard@.service b/integrations/clipboard-ssh/codebox-clipboard@.service new file mode 100644 index 0000000..93bca8e --- /dev/null +++ b/integrations/clipboard-ssh/codebox-clipboard@.service @@ -0,0 +1,8 @@ +[Unit] +Description=codebox clipboard image request + +[Service] +ExecStart=%h/.local/bin/codebox-clipboard-serve +StandardInput=socket +StandardOutput=socket +StandardError=journal diff --git a/lib/box-common.sh b/lib/box-common.sh index 103a7a1..926e166 100644 --- a/lib/box-common.sh +++ b/lib/box-common.sh @@ -926,6 +926,312 @@ select_runtime() { # --- Host-side features (clipboard, audio, npm-global, GitHub token) -------- +# True when SELinux is enforcing on the host. A confined container +# (container_t) is then denied connect() on any unix socket served by a host +# process (Wayland compositor, X server), whatever the label of the socket +# file. CODEBOX_SELINUX_ROOT relocates selinuxfs for the tests. +selinux_enforcing() { + local enforce="${CODEBOX_SELINUX_ROOT:-/sys/fs/selinux}/enforce" + [[ "$OS_TYPE" == "linux" && -r "$enforce" && "$(< "$enforce")" == "1" ]] +} + +# --- Clipboard image bridge (SELinux enforcing hosts) ----------------------- +# The container cannot reach the display server there, so the host fetches +# clipboard images on its behalf. A helper process on the host (started +# here, exits with the session) reads requests from a FIFO in a per-session +# directory shared with the container and answers with files in that +# directory; a `wl-paste` shim mounted in the container speaks the other +# side. The container gets no display access at all. What crosses: +# - images of the clipboard (CTRL+V), read-only; +# - the selection: text selected in the harness is written to the host +# clipboard and primary selection, and the primary selection can be read +# back (middle-click paste). Harnesses do both with wl-copy/wl-paste as +# soon as WAYLAND_DISPLAY is set, so the bridge sets it to a name that +# is not a socket; +# - never the text of the regular clipboard (what CTRL+C, a password +# manager... put there): that request is refused. +# Selection text only uses this host's own clipboard, never the SSH socket. +# +# The helper has two sources, tried in this order for every request: +# 1. a clipboard socket forwarded over SSH from the machine the user is +# typing on (integrations/clipboard-ssh), when something answers on it; +# 2. the clipboard of this host (wl-paste / xclip), when it has a display. +# So a session started on a remote machine pastes the images of whoever is +# connected, and the bridge is also what a headless host uses. + +CLIPBOARD_IMAGE_TYPES='image/(png|jpeg|jpg|gif|webp|bmp)' + +# The shim mounted as /usr/local/bin/wl-paste and /usr/local/bin/wl-copy in +# the container. It answers the calls harnesses make: wl-paste for images +# (`-l`, `--type image/...`) and for the primary selection (`--primary`, +# middle-click paste), wl-copy for what is selected in the harness. Reading +# the regular clipboard as text fails, like a wl-paste without a display. +clipboard_bridge_shim() { + cat <<'SHIM' +#!/bin/bash +# codebox clipboard bridge: clipboard access through a helper on the host +dir="${CODEBOX_CLIPBOARD_DIR:-/run/codebox-clipboard}" +[[ -p "${dir}/req" ]] || exit 1 +id="$$.${RANDOM}" +op="" type="" primary=false +if [[ "${0##*/}" == wl-copy ]]; then + text="" has_text=false + while (( $# )); do + case "$1" in + -p|--primary) primary=true ;; + -c|--clear) exit 0 ;; + -t|--type) shift ;; + -*) ;; + *) text+="${text:+ }$1"; has_text=true ;; + esac + shift + done + if $has_text; then + printf '%s' "$text" > "${dir}/${id}.in" + else + head -c 1048576 > "${dir}/${id}.in" + fi + op="copy" + if $primary; then type="primary"; else type="clipboard"; fi +else + while (( $# )); do + case "$1" in + -l|--list-types) op=list ;; + -t|--type) type="${2:-}"; shift ;; + --type=*) type="${1#*=}" ;; + -p|--primary) primary=true ;; + esac + shift + done + if $primary; then + # text of the primary selection only + [[ -z "$op" && ( -z "$type" || "$type" == text/* ) ]] || exit 1 + op="primary" type="" + elif [[ -z "$op" && -n "$type" ]]; then + op="get" + fi + [[ -n "$op" ]] || exit 1 +fi +# The host keeps the FIFO open; if it is gone, opening blocks: give up +if ! timeout 2 bash -c 'printf "%s\n" "$1" > "$2"' _ "${id} ${op} ${type}" "${dir}/req" 2>/dev/null; then + rm -f "${dir}/${id}.in" + exit 1 +fi +for (( i = 0; i < 120; i++ )); do + [[ -f "${dir}/${id}.rc" ]] && break + sleep 0.05 +done +rc=1 +if [[ -f "${dir}/${id}.rc" ]]; then + rc=$(< "${dir}/${id}.rc") + [[ "$rc" =~ ^[0-9]+$ ]] || rc=1 + (( rc == 0 )) && cat "${dir}/${id}.out" +fi +rm -f "${dir}/${id}.rc" "${dir}/${id}.out" "${dir}/${id}.in" +exit "$rc" +SHIM +} + +# Forwarded clipboard socket (see docs/usage.md "Pasting Images over SSH") +clipboard_ssh_socket() { + echo "${CODEBOX_CLIPBOARD_SOCKET:-${XDG_RUNTIME_DIR:+${XDG_RUNTIME_DIR}/codebox-clipboard-ssh.sock}}" +} + +# Client for that socket: sends "$2[ $3]" (list | get TYPE) to socket $1 and +# prints the answer. The server replies "ok\n" + payload, or "no\n". +# Exit 0 answered, 1 no such content, 3 nothing reachable on the socket. +CLIPBOARD_SSH_CLIENT=' +import socket, sys +path, request = sys.argv[1], " ".join(a for a in sys.argv[2:] if a) +s = socket.socket(socket.AF_UNIX) +s.settimeout(10) +try: + s.connect(path) +except OSError: + sys.exit(3) +try: + s.sendall(request.encode() + b"\n") + s.shutdown(socket.SHUT_WR) + chunks = [] + while True: + chunk = s.recv(65536) + if not chunk: + break + chunks.append(chunk) +except OSError: + sys.exit(3) +data = b"".join(chunks) +if not data: + sys.exit(3) +if not data.startswith(b"ok\n"): + sys.exit(1) +sys.stdout.buffer.write(data[3:]) +' +clipboard_ssh_query() { + local sock + sock=$(clipboard_ssh_socket) + [[ -n "$sock" && -S "$sock" ]] || return 3 + command -v python3 > /dev/null 2>&1 || return 3 + python3 -c "$CLIPBOARD_SSH_CLIENT" "$sock" "$@" 2>/dev/null +} + +# Answer one request from the best source: $1 local tool (or empty), $2 +# list|get, $3 type. The forwarded socket wins whenever something answers. +clipboard_bridge_answer() { + local tool="$1" op="$2" type="$3" rc=0 + if [[ "$op" == list ]]; then + clipboard_ssh_query list | grep -E "^${CLIPBOARD_IMAGE_TYPES}\$" + rc=${PIPESTATUS[0]} + (( rc == 0 )) && return 0 + else + clipboard_ssh_query get "$type" || rc=$? + fi + (( rc == 3 )) || return "$rc" + clipboard_bridge_query "$tool" "$op" "$type" +} + +# Run one host clipboard query: $1 tool (wl-paste|xclip), $2 list|get, $3 type +clipboard_bridge_query() { + local tool="$1" op="$2" type="$3" + case "${tool}:${op}" in + wl-paste:list) WAYLAND_DISPLAY="$CLIPBOARD_BRIDGE_DISPLAY" timeout 3 wl-paste --list-types 2>/dev/null | grep -E "^${CLIPBOARD_IMAGE_TYPES}\$" ;; + wl-paste:get) WAYLAND_DISPLAY="$CLIPBOARD_BRIDGE_DISPLAY" timeout 5 wl-paste --type "$type" 2>/dev/null ;; + xclip:list) timeout 3 xclip -selection clipboard -t TARGETS -o 2>/dev/null | grep -E "^${CLIPBOARD_IMAGE_TYPES}\$" ;; + xclip:get) timeout 5 xclip -selection clipboard -t "$type" -o 2>/dev/null ;; + *) return 1 ;; + esac +} + +# Selection text on the host: $1 tool (or empty), $2 base dir. +# copy: put file $4 on the host selection $3 (clipboard|primary) and keep it +# as the session's last selection. primary: print the host primary +# selection, else that last selection (host without a display, or whose +# clipboard tool cannot answer). +clipboard_bridge_copy() { + local tool="$1" base="$2" sel="$3" file="$4" + cp -f "$file" "${base}/host/last-selection" + case "${tool}:${sel}" in + wl-paste:clipboard) WAYLAND_DISPLAY="$CLIPBOARD_BRIDGE_DISPLAY" timeout 3 wl-copy < "$file" ;; + wl-paste:primary) WAYLAND_DISPLAY="$CLIPBOARD_BRIDGE_DISPLAY" timeout 3 wl-copy --primary < "$file" ;; + xclip:*) timeout 3 xclip -selection "$sel" -i < "$file" ;; + esac > /dev/null 2>&1 + return 0 +} +clipboard_bridge_primary() { + local tool="$1" base="$2" out + out="${base}/host/primary.$$" + case "$tool" in + wl-paste) WAYLAND_DISPLAY="$CLIPBOARD_BRIDGE_DISPLAY" timeout 3 wl-paste --primary --no-newline ;; + xclip) timeout 3 xclip -selection primary -o ;; + *) false ;; + esac > "$out" 2>/dev/null + if [[ ! -s "$out" && -f "${base}/host/last-selection" ]]; then + cp -f "${base}/host/last-selection" "$out" + fi + if [[ -s "$out" ]]; then cat "$out"; rm -f "$out"; return 0; fi + rm -f "$out" + return 1 +} + +# Host side of the bridge: serve requests ("ID list", "ID get TYPE", +# "ID primary", "ID copy clipboard|primary" with the text in ID.in; one +# per line on fd 3) until process $2 (the session) is gone, then remove the +# session directory $1. Everything read from the container is validated, +# and answers are written in a host-only directory and renamed into the +# shared one: the container owns the shared directory, so a file opened +# there by name could be a symlink it planted. For the same reason the text +# to copy is read without following a link (it would otherwise be a way to +# read any host file back through the primary selection). +clipboard_bridge_serve() { + local base="$1" pid="$2" tool="$3" + local shared="${base}/shared" id op type tmp rc + trap '' INT QUIT + trap 'rm -rf "$base"; exit 0' HUP TERM + while kill -0 "$pid" 2>/dev/null; do + id="" op="" type="" + read -r -t 2 -u 3 id op type || continue + [[ "$id" =~ ^[0-9]+\.[0-9]+$ ]] || continue + tmp="${base}/host/${id}" + rc=0 + case "${op} ${type}" in + "list ") + clipboard_bridge_answer "$tool" list "" > "${tmp}.out" || rc=$? ;; + "get "*) + [[ "$type" =~ ^${CLIPBOARD_IMAGE_TYPES}$ ]] || continue + clipboard_bridge_answer "$tool" get "$type" > "${tmp}.out" || rc=$? ;; + "primary ") + clipboard_bridge_primary "$tool" "$base" > "${tmp}.out" || rc=$? ;; + "copy clipboard"|"copy primary") + : > "${tmp}.out" + if timeout 2 dd if="${shared}/${id}.in" of="${tmp}.in" iflag=nofollow bs=1M count=1 status=none 2>/dev/null \ + && [[ -s "${tmp}.in" ]]; then + clipboard_bridge_copy "$tool" "$base" "$type" "${tmp}.in" + else + rc=1 + fi + rm -f "${tmp}.in" ;; + *) + continue ;; + esac + echo "$rc" > "${tmp}.rc" + # New files carry the host label; give them the shared directory's + # (container-readable) one. A no-op failure without SELinux. + chcon --reference="$shared" "${tmp}.out" "${tmp}.rc" 2>/dev/null || true + mv -T "${tmp}.out" "${shared}/${id}.out" 2>/dev/null || true + mv -T "${tmp}.rc" "${shared}/${id}.rc" 2>/dev/null || true + rm -f "${tmp}.out" "${tmp}.rc" + done + rm -rf "$base" +} + +# Set up the bridge for this session: $1 Wayland display name (or empty), +# $2 X11 display (or empty; neither on a headless host). Sets +# CLIPBOARD_BRIDGE_TOOL to the local tool in use (empty if none) and +# CLIPBOARD_BRIDGE_NEEDS to the host package that would provide it when it +# is missing. Returns 1 when no source can ever answer. +clipboard_bridge_setup() { + local wl="$1" x11="$2" tool="" pkg="" + if [[ -n "$wl" ]]; then + tool="wl-paste"; pkg="wl-clipboard" + elif [[ -n "$x11" ]]; then + tool="xclip"; pkg="xclip" + fi + CLIPBOARD_BRIDGE_TOOL="" CLIPBOARD_BRIDGE_NEEDS="" + if [[ -n "$tool" ]] && ! command -v "$tool" > /dev/null 2>&1; then + CLIPBOARD_BRIDGE_NEEDS="$pkg" + tool="" + fi + [[ -n "$tool" ]] || command -v python3 > /dev/null 2>&1 || return 1 + [[ -n "$XDG_RUNTIME_DIR" && -d "$XDG_RUNTIME_DIR" && -w "$XDG_RUNTIME_DIR" ]] || return 1 + + local base="${XDG_RUNTIME_DIR}/codebox-clipboard/${CONTAINER_NAME}" + rm -rf "$base" + mkdir -p "$base" || return 1 + chmod 700 "${XDG_RUNTIME_DIR}/codebox-clipboard" "$base" + mkdir -m 700 "${base}/shared" "${base}/host" "${base}/shim" || return 1 + mkfifo -m 600 "${base}/shared/req" || return 1 + clipboard_bridge_shim > "${base}/shim/wl-paste" + chmod 755 "${base}/shim/wl-paste" + + add_mount "${base}/shared" /run/codebox-clipboard + add_mount "${base}/shim/wl-paste" /usr/local/bin/wl-paste "ro" + add_mount "${base}/shim/wl-paste" /usr/local/bin/wl-copy "ro" + # Not a socket: only makes harnesses pick wl-copy/wl-paste (the shim) + add_env WAYLAND_DISPLAY codebox-clipboard-bridge + + CLIPBOARD_BRIDGE_DISPLAY="$wl" + # $$ is the launcher, which later execs the runtime and keeps its PID: + # the helper lives exactly as long as the session. + ( + exec 3<> "${base}/shared/req" < /dev/null > /dev/null 2>&1 + set +e + clipboard_bridge_serve "$base" "$$" "$tool" + ) & + disown + CLIPBOARD_BRIDGE_TOOL="$tool" + return 0 +} + # Clipboard/display access for image pasting (CTRL+V) add_clipboard_mounts() { if [[ "$OS_TYPE" == "linux" ]]; then @@ -939,20 +1245,52 @@ add_clipboard_mounts() { elif [[ -n "$XDG_RUNTIME_DIR" && -S "${XDG_RUNTIME_DIR}/wayland-0" ]]; then wl_display="wayland-0" fi - if [[ -n "$wl_display" ]]; then + local x11_display="" + if [[ -z "$wl_display" && -n "$DISPLAY" && -d /tmp/.X11-unix ]]; then + x11_display="$DISPLAY" + fi + # Something answering on a forwarded clipboard socket means the + # user sits at another machine: its clipboard is the one to paste + local ssh_live=false ssh_rc=0 + clipboard_ssh_query list > /dev/null 2>&1 || ssh_rc=$? + (( ssh_rc == 3 )) || ssh_live=true + if [[ -n "$wl_display" ]] && ! selinux_enforcing && ! $ssh_live; then # Wayland clipboard access add_mount "${XDG_RUNTIME_DIR}/${wl_display}" "${XDG_RUNTIME_DIR}/${wl_display}" "ro,nolabel" add_env WAYLAND_DISPLAY "$wl_display" add_env XDG_RUNTIME_DIR "$XDG_RUNTIME_DIR" CLIPBOARD_STATUS="enabled (Wayland)" - elif [[ -n "$DISPLAY" && -d /tmp/.X11-unix ]]; then + elif [[ -n "$x11_display" ]] && ! selinux_enforcing && ! $ssh_live; then # X11 clipboard access add_mount /tmp/.X11-unix /tmp/.X11-unix "ro,nolabel" - add_env DISPLAY "$DISPLAY" + add_env DISPLAY "$x11_display" if [[ -f "${HOME}/.Xauthority" ]]; then add_mount "${HOME}/.Xauthority" /home/coder/.Xauthority "ro" fi CLIPBOARD_STATUS="enabled (X11)" + elif clipboard_bridge_setup "$wl_display" "$x11_display"; then + # No usable display socket for the container: SELinux denies a + # confined container the connection (and exporting + # WAYLAND_DISPLAY/DISPLAY next to a dead socket makes the + # harness use wl-copy/wl-paste, which fail, instead of the + # terminal's OSC 52 clipboard), the clipboard that matters is + # the SSH client's, or this host has no display. Images and the + # selection go through the bridge; the terminal still gets + # every copy too (OSC 52). + local sources="" + $ssh_live && sources="SSH-forwarded clipboard" + [[ -n "$CLIPBOARD_BRIDGE_TOOL" ]] && sources="${sources:+${sources}, }host ${CLIPBOARD_BRIDGE_TOOL}" + if [[ -n "$sources" ]]; then + CLIPBOARD_STATUS="host bridge: images (${sources}), selection and middle-click paste" + else + CLIPBOARD_STATUS="host bridge: selection and middle-click paste; images once a clipboard socket is forwarded over SSH" + fi + if [[ -n "$CLIPBOARD_BRIDGE_NEEDS" ]]; then + log_warn "Pasting images from this machine's clipboard needs ${CLIPBOARD_BRIDGE_NEEDS} installed on the host" + fi + elif [[ -n "${wl_display}${x11_display}" ]]; then + log_warn "Image pasting needs ${CLIPBOARD_BRIDGE_NEEDS:-wl-clipboard} on the host (SELinux blocks the display socket in the container)" + CLIPBOARD_STATUS="text only, via the terminal (install ${CLIPBOARD_BRIDGE_NEEDS:-wl-clipboard} on the host for images)" else log_warn "No display server found: clipboard image pasting will not work" CLIPBOARD_STATUS="unavailable (no display server)" diff --git a/tests/clipboard-bridge-test.sh b/tests/clipboard-bridge-test.sh new file mode 100755 index 0000000..993a781 --- /dev/null +++ b/tests/clipboard-bridge-test.sh @@ -0,0 +1,133 @@ +#!/bin/bash +# Functional test of the clipboard image bridge (lib/box-common.sh): starts +# the host helper against a stub `wl-paste` and drives it with the container +# shim, both running here. No container runtime or display is needed. + +set -euo pipefail + +TESTS_DIR="$(cd -P "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +ROOT="$(mktemp -d "${TMPDIR:-/tmp}/codebox-clip.XXXXXX")" +trap 'rm -rf "$ROOT"' EXIT + +mkdir -p "${ROOT}/stubs" "${ROOT}/run" +cat > "${ROOT}/stubs/wl-paste" <<'EOF' +#!/bin/bash +case "$*" in + --list-types) printf 'text/plain\nimage/png\nTARGETS\n' ;; + "--type image/png") printf 'PNGDATA' ;; + "--primary --no-newline") cat "${STATE}/primary" 2> /dev/null ;; + *) echo "secret text"; exit 0 ;; +esac +EOF +cat > "${ROOT}/stubs/wl-copy" <<'EOF' +#!/bin/bash +if [[ "$*" == --primary ]]; then cat > "${STATE}/primary"; else cat > "${STATE}/clipboard"; fi +EOF +chmod +x "${ROOT}/stubs/wl-paste" "${ROOT}/stubs/wl-copy" +export STATE="${ROOT}/state" +mkdir -p "$STATE" +export PATH="${ROOT}/stubs:${PATH}" +export XDG_RUNTIME_DIR="${ROOT}/run" + +# The engine is normally sourced by a launcher, which defines these +set +u +BOX_NAME="ccbox" +REGISTRY_IMAGE="guimou/ccbox" +SCRIPT_DIR="${TESTS_DIR}/.." +# shellcheck source=lib/box-common.sh +source "${TESTS_DIR}/../lib/box-common.sh" +set +e +CONTAINER_NAME="bridge-test" +clipboard_bridge_setup wayland-0 "" || { echo "FAIL setup"; exit 1; } + +BASE="${XDG_RUNTIME_DIR}/codebox-clipboard/${CONTAINER_NAME}" +export CODEBOX_CLIPBOARD_DIR="${BASE}/shared" +SHIM="${BASE}/shim/wl-paste" +ln -s "$SHIM" "${ROOT}/wl-copy" +COPY="${ROOT}/wl-copy" +status=0 +check() { # description, expected, actual + if [[ "$2" == "$3" ]]; then echo "ok $1"; else echo "FAIL $1: expected '$2', got '$3'"; status=1; fi +} + +check "mounts the shared dir and the shim" \ + "mount|${BASE}/shared|/run/codebox-clipboard| mount|${BASE}/shim/wl-paste|/usr/local/bin/wl-paste|ro mount|${BASE}/shim/wl-paste|/usr/local/bin/wl-copy|ro env|WAYLAND_DISPLAY|codebox-clipboard-bridge" \ + "${BOX_SPEC[*]}" +check "lists image types only" "image/png" "$("$SHIM" -l)" +check "returns the image" "PNGDATA" "$("$SHIM" --type image/png)" +check "image by short option" "PNGDATA" "$("$SHIM" -t image/png)" +check "refuses text by type" "rc=1:" "$(out=$("$SHIM" --type text/plain); echo "rc=$?:${out}")" +check "refuses plain text paste" "rc=1:" "$(out=$("$SHIM" --no-newline); echo "rc=$?:${out}")" +check "refuses the clipboard text even as primary type" "rc=1:" "$(out=$("$SHIM" --primary --type image/png); echo "rc=$?:${out}")" + +# Selection: written to the host clipboard and primary, primary read back +check "nothing selected yet" "rc=1:" "$(out=$("$SHIM" --primary --no-newline); echo "rc=$?:${out}")" +printf 'picked text' | "$COPY" +printf 'picked text' | "$COPY" --primary +check "copy reaches the host clipboard" "picked text" "$(cat "${STATE}/clipboard" 2> /dev/null)" +check "copy reaches the host primary selection" "picked text" "$(cat "${STATE}/primary" 2> /dev/null)" +check "middle-click reads the primary selection" "picked text" "$("$SHIM" --primary --no-newline)" +echo -n "selected in another window" > "${STATE}/primary" +check "the host primary selection wins" "selected in another window" "$("$SHIM" --primary --no-newline)" +rm -f "${STATE}/primary" +check "falls back to the last selection of the session" "picked text" "$("$SHIM" --primary --no-newline)" + +# The text to copy is not read through a link planted by the container +echo "host secret" > "${ROOT}/secret" +ln -s "${ROOT}/secret" "${BASE}/shared/5.5.in" +echo "5.5 copy primary" > "${BASE}/shared/req" +for (( i = 0; i < 100; i++ )); do [[ -f "${BASE}/shared/5.5.rc" ]] && break; sleep 0.05; done +check "does not copy a host file through a planted symlink" "1:picked text" "$(cat "${BASE}/shared/5.5.rc"):$("$SHIM" --primary --no-newline)" +rm -f "${BASE}/shared"/5.5.* + +# A symlink planted by the container where the answer goes is replaced, +# never written through +echo untouched > "${ROOT}/victim" +ln -s "${ROOT}/victim" "${BASE}/shared/7.7.out" +echo "7.7 get image/png" > "${BASE}/shared/req" +for (( i = 0; i < 100; i++ )); do [[ -f "${BASE}/shared/7.7.rc" ]] && break; sleep 0.05; done +check "does not write through a planted symlink" "untouched" "$(< "${ROOT}/victim")" +check "replaces the planted symlink with the answer" "regular:PNGDATA" \ + "$([[ ! -L "${BASE}/shared/7.7.out" ]] && echo "regular:$(< "${BASE}/shared/7.7.out")")" + +# Malformed requests are ignored and do not stop the helper +printf '%s\n' "../../x get image/png" "8.8 exec image/png" "9.9 get image/png;id" > "${BASE}/shared/req" +check "survives malformed requests" "PNGDATA" "$("$SHIM" --type image/png)" +check "answers nothing for malformed requests" "" "$(find "${BASE}/shared" -mindepth 1 ! -name req ! -name '7.7.*' -printf '%f ')" + +# --- SSH-forwarded clipboard ------------------------------------------------ +# The laptop-side server (integrations/clipboard-ssh) behind a unix socket, +# standing for the socket ssh forwards; its clipboard holds another image. +mkdir -p "${ROOT}/laptop" +cat > "${ROOT}/laptop/wl-paste" <<'EOF' +#!/bin/bash +case "$*" in + --list-types) printf 'text/plain\nimage/jpeg\n' ;; + "--type image/jpeg") printf 'LAPTOPJPEG' ;; + *) exit 1 ;; +esac +EOF +chmod +x "${ROOT}/laptop/wl-paste" +SOCK="${XDG_RUNTIME_DIR}/codebox-clipboard-ssh.sock" +PATH="${ROOT}/laptop:${PATH}" WAYLAND_DISPLAY=wayland-0 python3 -c ' +import socket, subprocess, sys +srv = socket.socket(socket.AF_UNIX); srv.bind(sys.argv[1]); srv.listen(8) +while True: + conn, _ = srv.accept() + subprocess.run([sys.argv[2]], stdin=conn, stdout=conn) + conn.close() +' "$SOCK" "${TESTS_DIR}/../integrations/clipboard-ssh/codebox-clipboard-serve" & +SERVER_PID=$! +for (( i = 0; i < 100; i++ )); do [[ -S "$SOCK" ]] && break; sleep 0.05; done + +check "ssh: lists the remote user's image types" "image/jpeg" "$("$SHIM" -l)" +check "ssh: returns the remote user's image" "LAPTOPJPEG" "$("$SHIM" --type image/jpeg)" +check "ssh: a type the laptop lacks is not taken from this host" "rc=1:" "$(out=$("$SHIM" --type image/png); echo "rc=$?:${out}")" +check "ssh: the server refuses text" "no" "$(clipboard_ssh_query get text/plain > /dev/null; [[ $? -eq 1 ]] && echo no)" + +# Connection gone (socket file left behind, as after an SSH disconnect): +# back to this host's clipboard +kill "$SERVER_PID"; wait "$SERVER_PID" 2> /dev/null +check "ssh: falls back to the host clipboard when disconnected" "PNGDATA" "$("$SHIM" --type image/png)" + +exit "$status" diff --git a/tests/golden/clipboard-selinux.txt b/tests/golden/clipboard-selinux.txt new file mode 100644 index 0000000..f2a4efd --- /dev/null +++ b/tests/golden/clipboard-selinux.txt @@ -0,0 +1,74 @@ +--cgroup-parent=codebox.slice +--hostname ccbox +--init +--log-driver=none +--name ccbox-demo-HASH-SESSION +--rm +--userns=keep-id:uid=1000,gid=1000 +-e ANTHROPIC_API_KEY=anthropic-stub +-e AWS_REGION=eu-west-1 +-e GH_TOKEN=ghp_stubtoken +-e GITHUB_TOKEN=ghp_stubtoken +-e LANG=C.UTF-8 +-e NO_COLOR=1 +-e PROJECT_NAME=demo +-e TERM=xterm-256color +-e TZ=UTC +-e WAYLAND_DISPLAY=codebox-clipboard-bridge +-it +-v /etc/localtime:/etc/localtime:ro +-v ROOT/home/.claude.json:/home/coder/.claude.json:z +-v ROOT/home/.claude/CLAUDE.md:/home/coder/.claude/CLAUDE.md:z +-v ROOT/home/.claude/RULES.md:/home/coder/.claude/RULES.md:ro,z +-v ROOT/home/.claude/agents:/home/coder/.claude/agents:z +-v ROOT/home/.claude/backups:/home/coder/.claude/backups:z +-v ROOT/home/.claude/cache:/home/coder/.claude/cache:z +-v ROOT/home/.claude/ccbox-projects/demo_HASH/debug:/home/coder/.claude/debug:z +-v ROOT/home/.claude/ccbox-projects/demo_HASH/history.jsonl:/home/coder/.claude/history.jsonl:z +-v ROOT/home/.claude/ccbox-projects/demo_HASH/logs:/home/coder/.claude/logs:z +-v ROOT/home/.claude/ccbox-projects/demo_HASH/plans:/home/coder/.claude/plans:z +-v ROOT/home/.claude/ccbox-projects/demo_HASH/plugins:/home/coder/.claude/plugins:z +-v ROOT/home/.claude/ccbox-projects/demo_HASH/projects:/home/coder/.claude/projects:z +-v ROOT/home/.claude/ccbox-projects/demo_HASH/session-env:/home/coder/.claude/session-env:z +-v ROOT/home/.claude/ccbox-projects/demo_HASH/shell-snapshots:/home/coder/.claude/shell-snapshots:z +-v ROOT/home/.claude/ccbox-projects/demo_HASH/tasks:/home/coder/.claude/tasks:z +-v ROOT/home/.claude/ccbox-projects/demo_HASH/teams:/home/coder/.claude/teams:z +-v ROOT/home/.claude/ccbox-projects/demo_HASH/todos:/home/coder/.claude/todos:z +-v ROOT/home/.claude/commands:/home/coder/.claude/commands:z +-v ROOT/home/.claude/file-history:/home/coder/.claude/file-history:z +-v ROOT/home/.claude/hooks:/home/coder/.claude/hooks:z +-v ROOT/home/.claude/keybindings.json:/home/coder/.claude/keybindings.json:z +-v ROOT/home/.claude/paste-cache:/home/coder/.claude/paste-cache:z +-v ROOT/home/.claude/rules:/home/coder/.claude/rules:z +-v ROOT/home/.claude/settings.json:/home/coder/.claude/settings.json:z +-v ROOT/home/.claude/settings.local.json:/home/coder/.claude/settings.local.json:z +-v ROOT/home/.claude/skills:/home/coder/.claude/skills:z +-v ROOT/home/.claude/stats-cache.json:/home/coder/.claude/stats-cache.json:z +-v ROOT/home/.claude/statsig:/home/coder/.claude/statsig:z +-v ROOT/home/.claude/status-line.sh:/home/coder/.claude/status-line.sh:ro,z +-v ROOT/home/.claude/themes:/home/coder/.claude/themes:z +-v ROOT/home/.claude/workflows:/home/coder/.claude/workflows:z +-v ROOT/npm-global:/home/coder/.npm-global:ro,z +-v ROOT/repos/demo:/workspace:z +-v ROOT/run/codebox-clipboard/ccbox-demo-HASH-SESSION/shared:/run/codebox-clipboard:z +-v ROOT/run/codebox-clipboard/ccbox-demo-HASH-SESSION/shim/wl-paste:/usr/local/bin/wl-copy:ro,z +-v ROOT/run/codebox-clipboard/ccbox-demo-HASH-SESSION/shim/wl-paste:/usr/local/bin/wl-paste:ro,z +-w /workspace +-- +quay.io/guimou/ccbox:TAG +claude +## .config/systemd/user/codebox.slice +# Generated by the codebox launchers (ccbox, ocbox, qcbox, cxbox, ompbox). +# Shared memory budget for all agent containers. Do not edit: set +# CODEBOX_MEMORY_MAX / CODEBOX_MEMORY_HIGH / CODEBOX_MEMORY_SWAP_MAX instead; +# the next launch rewrites this file when they change. +[Unit] +Description=Shared memory budget for codebox agent containers + +[Slice] +MemoryAccounting=yes +MemoryHigh=72% +MemoryMax=80% +MemorySwapMax=2G +## systemctl calls +systemctl --user daemon-reload diff --git a/tests/golden/clipboard-wayland.txt b/tests/golden/clipboard-wayland.txt new file mode 100644 index 0000000..3a1b9ff --- /dev/null +++ b/tests/golden/clipboard-wayland.txt @@ -0,0 +1,73 @@ +--cgroup-parent=codebox.slice +--hostname ccbox +--init +--log-driver=none +--name ccbox-demo-HASH-SESSION +--rm +--userns=keep-id:uid=1000,gid=1000 +-e ANTHROPIC_API_KEY=anthropic-stub +-e AWS_REGION=eu-west-1 +-e GH_TOKEN=ghp_stubtoken +-e GITHUB_TOKEN=ghp_stubtoken +-e LANG=C.UTF-8 +-e NO_COLOR=1 +-e PROJECT_NAME=demo +-e TERM=xterm-256color +-e TZ=UTC +-e WAYLAND_DISPLAY=wayland-0 +-e XDG_RUNTIME_DIR=ROOT/run +-it +-v /etc/localtime:/etc/localtime:ro +-v ROOT/home/.claude.json:/home/coder/.claude.json:z +-v ROOT/home/.claude/CLAUDE.md:/home/coder/.claude/CLAUDE.md:z +-v ROOT/home/.claude/RULES.md:/home/coder/.claude/RULES.md:ro,z +-v ROOT/home/.claude/agents:/home/coder/.claude/agents:z +-v ROOT/home/.claude/backups:/home/coder/.claude/backups:z +-v ROOT/home/.claude/cache:/home/coder/.claude/cache:z +-v ROOT/home/.claude/ccbox-projects/demo_HASH/debug:/home/coder/.claude/debug:z +-v ROOT/home/.claude/ccbox-projects/demo_HASH/history.jsonl:/home/coder/.claude/history.jsonl:z +-v ROOT/home/.claude/ccbox-projects/demo_HASH/logs:/home/coder/.claude/logs:z +-v ROOT/home/.claude/ccbox-projects/demo_HASH/plans:/home/coder/.claude/plans:z +-v ROOT/home/.claude/ccbox-projects/demo_HASH/plugins:/home/coder/.claude/plugins:z +-v ROOT/home/.claude/ccbox-projects/demo_HASH/projects:/home/coder/.claude/projects:z +-v ROOT/home/.claude/ccbox-projects/demo_HASH/session-env:/home/coder/.claude/session-env:z +-v ROOT/home/.claude/ccbox-projects/demo_HASH/shell-snapshots:/home/coder/.claude/shell-snapshots:z +-v ROOT/home/.claude/ccbox-projects/demo_HASH/tasks:/home/coder/.claude/tasks:z +-v ROOT/home/.claude/ccbox-projects/demo_HASH/teams:/home/coder/.claude/teams:z +-v ROOT/home/.claude/ccbox-projects/demo_HASH/todos:/home/coder/.claude/todos:z +-v ROOT/home/.claude/commands:/home/coder/.claude/commands:z +-v ROOT/home/.claude/file-history:/home/coder/.claude/file-history:z +-v ROOT/home/.claude/hooks:/home/coder/.claude/hooks:z +-v ROOT/home/.claude/keybindings.json:/home/coder/.claude/keybindings.json:z +-v ROOT/home/.claude/paste-cache:/home/coder/.claude/paste-cache:z +-v ROOT/home/.claude/rules:/home/coder/.claude/rules:z +-v ROOT/home/.claude/settings.json:/home/coder/.claude/settings.json:z +-v ROOT/home/.claude/settings.local.json:/home/coder/.claude/settings.local.json:z +-v ROOT/home/.claude/skills:/home/coder/.claude/skills:z +-v ROOT/home/.claude/stats-cache.json:/home/coder/.claude/stats-cache.json:z +-v ROOT/home/.claude/statsig:/home/coder/.claude/statsig:z +-v ROOT/home/.claude/status-line.sh:/home/coder/.claude/status-line.sh:ro,z +-v ROOT/home/.claude/themes:/home/coder/.claude/themes:z +-v ROOT/home/.claude/workflows:/home/coder/.claude/workflows:z +-v ROOT/npm-global:/home/coder/.npm-global:ro,z +-v ROOT/repos/demo:/workspace:z +-v ROOT/run/wayland-0:ROOT/run/wayland-0:ro +-w /workspace +-- +quay.io/guimou/ccbox:TAG +claude +## .config/systemd/user/codebox.slice +# Generated by the codebox launchers (ccbox, ocbox, qcbox, cxbox, ompbox). +# Shared memory budget for all agent containers. Do not edit: set +# CODEBOX_MEMORY_MAX / CODEBOX_MEMORY_HIGH / CODEBOX_MEMORY_SWAP_MAX instead; +# the next launch rewrites this file when they change. +[Unit] +Description=Shared memory budget for codebox agent containers + +[Slice] +MemoryAccounting=yes +MemoryHigh=72% +MemoryMax=80% +MemorySwapMax=2G +## systemctl calls +systemctl --user daemon-reload diff --git a/tests/render-test.sh b/tests/render-test.sh index 40efe43..46f4707 100755 --- a/tests/render-test.sh +++ b/tests/render-test.sh @@ -61,6 +61,13 @@ echo "cpuset cpu io memory hugetlb pids misc" > "${CGROUP_ROOT}/cgroup.controlle echo "cpu memory pids" > "${USER_CG}/cgroup.controllers" SLICE_DIR="${FAKE_HOME}/.config/systemd/user" +# Wayland socket and selinuxfs trees for the clipboard scenarios +RUNTIME_DIR="${ROOT}/run" +mkdir -p "$RUNTIME_DIR" "${ROOT}/selinux-enforcing" "${ROOT}/selinux-permissive" +python3 -c 'import socket,sys; socket.socket(socket.AF_UNIX).bind(sys.argv[1])' "${RUNTIME_DIR}/wayland-0" +echo 1 > "${ROOT}/selinux-enforcing/enforce" +echo 0 > "${ROOT}/selinux-permissive/enforce" + # --- stubs --------------------------------------------------------------- cat > "${STUBS}/podman" <<'EOF' @@ -113,6 +120,9 @@ cat > "${STUBS}/npm" <<'EOF' [[ "$*" == "config get prefix" ]] && echo "${NPM_PREFIX}" EOF +# Host clipboard tool: its presence enables the clipboard image bridge +printf '#!/bin/bash\nexit 1\n' > "${STUBS}/wl-paste" + chmod +x "${STUBS}"/* # Wrappers are invoked through symlinks in a bin dir, like a real install @@ -177,6 +187,11 @@ SCENARIOS=( "memory-env-off|cxbox|" "memory-flag-off|ccbox|--no-memory-limit" "memory-unavailable|qcbox|" + # clipboard: the Wayland socket is wired (found without $WAYLAND_DISPLAY), + # except when SELinux is enforcing, where a container cannot connect to + # it: the image bridge (shared dir + wl-paste shim) is mounted instead + "clipboard-wayland|ccbox|" + "clipboard-selinux|ccbox|" "!memory-invalid-max|ccbox|" "!memory-invalid-swap|ccbox|" "!memory-invalid-slice|ccbox|" @@ -256,6 +271,8 @@ for entry in "${SCENARIOS[@]}"; do memory-percent) EXTRA_ENV=(CODEBOX_MEMORY_MAX=60% CODEBOX_MEMORY_HIGH=50% CODEBOX_SLICE=agents.slice) ;; memory-env-off) EXTRA_ENV=(CODEBOX_MEMORY_MAX=off) ;; memory-unavailable) EXTRA_ENV=(STUB_CGROUP_MANAGER=cgroupfs) ;; + clipboard-wayland) EXTRA_ENV=("XDG_RUNTIME_DIR=${RUNTIME_DIR}" "CODEBOX_SELINUX_ROOT=${ROOT}/selinux-permissive") ;; + clipboard-selinux) EXTRA_ENV=("XDG_RUNTIME_DIR=${RUNTIME_DIR}" WAYLAND_DISPLAY=wayland-0 "CODEBOX_SELINUX_ROOT=${ROOT}/selinux-enforcing") ;; memory-invalid-max) EXTRA_ENV=(CODEBOX_MEMORY_MAX=lots) ;; memory-invalid-swap) EXTRA_ENV=(CODEBOX_MEMORY_SWAP_MAX=50%) ;; memory-invalid-slice) EXTRA_ENV=(CODEBOX_SLICE=../evil) ;;