Files
stackpilot/backend/services/exec_service.py
T
menzeljandClaude Opus 5.5 d6cebb3371
CI / check (push) Successful in 4m9s
CI / build-and-push (push) Failing after 16m10s
Fix what a review of the whole app found, end to end (0.67.1)
A pass over every feature against a real Docker daemon, then clicking
through the UI as admin and read-only user, on a desktop and a phone.

Security. /ws/deploy ran compose up for the read-only role; it is
admin-only now. A container's inspect view, a stack's compose file
(POSTGRES_PASSWORD: hunter2) and the viewer's .env tab no longer show
credentials to that role. Git branch and URL values that git would read
as options (-x, ext::) are refused. SFTP host keys are checked: pinned
on first use or entered by hand (key line or SHA256 fingerprint), a
different key is refused before the password is sent. A backup name
from the API can no longer reach outside the destination folder. The
file browser refuses to move or rename a browse root, as delete did.

Docker lifecycle. Closing the deploy console released the stack lock
while compose was still running and logged rc=None as success; deploys
and updates are now background runs that hold the lock to the end,
report the real exit code and can be re-attached to. Every closed log
view left a `compose logs -f` behind. A dozen open tabs exhausted the
default thread pool and hung the API; event and exec streams have their
own threads. Auto-update and the update endpoint ignored failed pulls.
A deleted git stack was recreated and started by the next webhook or
poll; deleting a stack now drops its git source, auto-update policy and
schedule entries. Deleting no longer walks into mounted shares, is
refused while a backup runs, and removes the containers even when the
compose file is broken. Stack folders compose has to normalise
(Nextcloud -> nextcloud) work everywhere and group correctly on the
volumes, networks and images pages.

Detection. Host port conflicts read the container's own network
namespace; /proc/1/net is read instead. Images referenced as docker.io/…
were never update-checked; local builds no longer report "needs
credentials". NVIDIA GPUs are read from the driver's procfs. The backup
dialog's "path mismatch" warning came from mountinfo's filesystem-relative
root and fired for any stacks folder on its own disk, ZFS dataset or
btrfs subvolume; the host path now comes from Docker's mounts.

Backups and destinations. The download ignored the folder/volume
selection (axios sent binds[]). Restoring under a new name kept the old
one. A report header past nginx's buffer turned a good backup into a
502. SFTP/S3 errors were bare 500s and "Test" did not try to write.
A destination used by a schedule could be deleted. Backup file names
are in the schedule's or the browser's time zone instead of UTC.

Editor and converter. `docker run` conversion produced invalid compose
for --network host, named volumes and -dit; --gpus and --mount were
dropped; a multi-line command pasted into the one-line field became
`image: ' '` (now a textarea, and flattened continuations are read).
Validation failed for env_file stacks. The editor overwrote unsaved
edits on every container event, lost them on a stray click (now asks),
threw when closing the diff, and its helper panel listed the starter
service "app" for every existing stack. Monaco is bundled instead of
loaded from jsdelivr, so the editor works offline (and monaco-editor
0.57 drops the dompurify advisory; axios and react-router updated).

UI. All times were two hours off: offset-less UTC from SQLite was read
as local time, and "next run" always said "just now". A token refresh
mid-session duplicated deploys, reset terminals and doubled logs. A
backend restart (update, self-update) signed everyone out on reload; the
page now waits for it. The editor was unusable on a phone, tables and
tabs overflowed, dialog text was black on the dark theme, and the file
browser opened on an error with the default roots. Read-only users get
"Admin only" pages instead of 403s; in-use networks offer no delete;
"Scan all" covers StackPilot's own stacks only and runs in the
background instead of timing out at 600s.

Deployment. nginx passes the port in Host (the OIDC redirect URI lost
:5009) and keeps an outer proxy's X-Forwarded-Proto. The frontend waits
for a healthy backend (healthcheck probes every 2s while starting). The
frontend image builds with npm ci. Secrets are 0644 in a 0700 folder so
non-root containers can read them; existing files are fixed at startup.
The test suite no longer starts real containers on a host with Docker.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Fx7gcuy8d6nPd95g43rGHu
2026-10-15 13:51:26 +02:00

182 lines
6.3 KiB
Python

"""Interactive exec (web terminal) into compose-managed containers.
Reuses ``container_service._get_managed`` so a terminal can only be opened on a
container that belongs to a compose-managed stack — never an arbitrary host
container. The raw exec socket is bidirectional (stdin + a TTY-merged
stdout/stderr stream), suitable for piping straight to xterm.js.
"""
from __future__ import annotations
import asyncio
import codecs
import contextlib
import json
import queue
import socket as _socket
import threading
from starlette.websockets import WebSocketDisconnect
from docker_client import get_client, safe_call
from services.container_service import _get_managed
DEFAULT_SHELL = "/bin/sh"
def create_exec(container_id: str, cmd: list[str] | None = None, tty: bool = True) -> str:
"""Create an exec instance on a managed container and return its id."""
container = _get_managed(container_id)
client = get_client()
created = safe_call(
client.api.exec_create,
container.id,
cmd or [DEFAULT_SHELL],
stdin=True,
tty=tty,
stdout=True,
stderr=True,
)
return created["Id"]
def start_exec(exec_id: str, tty: bool = True):
"""Start the exec and return ``(holder, raw_socket)``.
docker-py 7.x returns a ``socket.SocketIO`` wrapper whose real, recv/sendall
-capable fd lives at ``._sock``; older versions hand back the socket
directly. We keep both: ``holder`` is what we close, ``raw`` is what we
recv/sendall on.
"""
client = get_client()
holder = safe_call(client.api.exec_start, exec_id, socket=True, tty=tty, demux=False)
raw = getattr(holder, "_sock", None) or holder
return holder, raw
def resize_exec(exec_id: str, height: int, width: int) -> None:
"""Resize the exec's TTY (rows x cols) so the shell wraps correctly."""
client = get_client()
safe_call(client.api.exec_resize, exec_id, height=height, width=width)
def exec_exit_code(exec_id: str):
"""Return the exec's ExitCode once it has finished (None while running)."""
client = get_client()
info = safe_call(client.api.exec_inspect, exec_id)
return info.get("ExitCode")
async def pump_exec(websocket, exec_id: str, holder, raw) -> None:
"""Bidirectionally pump an exec socket <-> a WebSocket.
Browser -> container: JSON ``{"type":"data","data":...}`` keystrokes and
``{"type":"resize","rows","cols"}`` control frames (raw text is also
accepted as keystrokes). Container -> browser: ``{"type":"data","data":...}``
then a final ``{"type":"exit","code":...}``.
The blocking ``recv`` and ``sendall`` run on two threads of this session's
own. They used to run on the event loop's default executor, where an open
terminal held a worker for its whole lifetime — shared with every
``asyncio.to_thread`` in the app. On teardown the socket is shut down, which
is what unblocks the reader.
"""
raw.setblocking(True)
loop = asyncio.get_running_loop()
closed = asyncio.Event()
incoming: asyncio.Queue = asyncio.Queue()
outgoing: queue.Queue = queue.Queue()
def post(item) -> None:
try:
loop.call_soon_threadsafe(incoming.put_nowait, item)
except RuntimeError: # loop closed
pass
def reader() -> None:
try:
while True:
data = raw.recv(4096)
if not data:
break
post(data)
except Exception: # noqa: BLE001 - shutdown on teardown lands here
pass
finally:
post(None)
def writer() -> None:
while True:
data = outgoing.get()
if data is None:
return
try:
raw.sendall(data)
except Exception: # noqa: BLE001
return
name = exec_id[:12]
threading.Thread(target=reader, name=f"exec-read-{name}", daemon=True).start()
threading.Thread(target=writer, name=f"exec-write-{name}", daemon=True).start()
async def to_browser() -> None:
# Incremental: a multi-byte character (an umlaut, a box-drawing glyph in
# htop) split across two reads would otherwise turn into two U+FFFD.
decoder = codecs.getincrementaldecoder("utf-8")(errors="replace")
try:
while True:
data = await incoming.get()
if data is None:
break
text = decoder.decode(data)
if text:
await websocket.send_text(json.dumps({"type": "data", "data": text}))
if tail := decoder.decode(b"", final=True):
await websocket.send_text(json.dumps({"type": "data", "data": tail}))
except Exception: # noqa: BLE001
pass
finally:
closed.set()
async def from_browser() -> None:
try:
while True:
msg = await websocket.receive_text()
obj = None
try:
obj = json.loads(msg)
except (json.JSONDecodeError, TypeError):
obj = None
if isinstance(obj, dict) and obj.get("type") == "resize":
with contextlib.suppress(Exception):
resize_exec(exec_id, int(obj.get("rows", 24)), int(obj.get("cols", 80)))
elif isinstance(obj, dict) and "data" in obj:
outgoing.put(str(obj["data"]).encode())
else:
outgoing.put(msg.encode())
except WebSocketDisconnect:
pass
except Exception: # noqa: BLE001
pass
finally:
closed.set()
out_task = asyncio.create_task(to_browser())
in_task = asyncio.create_task(from_browser())
await closed.wait()
outgoing.put(None)
with contextlib.suppress(Exception):
raw.shutdown(_socket.SHUT_RDWR)
with contextlib.suppress(Exception):
holder.close()
for task in (out_task, in_task):
task.cancel()
with contextlib.suppress(Exception):
await asyncio.gather(out_task, in_task, return_exceptions=True)
code = None
with contextlib.suppress(Exception):
code = exec_exit_code(exec_id)
with contextlib.suppress(Exception):
await websocket.send_text(json.dumps({"type": "exit", "code": code}))