Files
stackpilot/backend/services/device_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

216 lines
7.2 KiB
Python

"""Host device detection (USB, serial/TTY, DRI) and host filesystem browser."""
from __future__ import annotations
import glob
import os
from dataclasses import asdict, dataclass
from config import settings
@dataclass
class HostDevice:
path: str
kind: str # "usb" | "tty" | "dri" | "other"
name: str = ""
def to_dict(self) -> dict:
return asdict(self)
def _read(path: str) -> str:
try:
with open(path, "r", encoding="utf-8", errors="replace") as fh:
return fh.read().strip()
except OSError:
return ""
def _usb_devices() -> list[HostDevice]:
devices: list[HostDevice] = []
# /dev/bus/usb/<bus>/<dev>
for path in sorted(glob.glob("/dev/bus/usb/*/*")):
name = ""
# Best-effort name lookup via sysfs is non-trivial to map; leave generic.
devices.append(HostDevice(path=path, kind="usb", name=name or "USB device"))
return devices
def _usb_names_from_sysfs() -> list[HostDevice]:
"""Richer USB list from sysfs with product/manufacturer strings."""
out: list[HostDevice] = []
for dev in sorted(glob.glob("/sys/bus/usb/devices/*")):
busnum = _read(os.path.join(dev, "busnum"))
devnum = _read(os.path.join(dev, "devnum"))
if not busnum or not devnum:
continue
product = _read(os.path.join(dev, "product"))
manufacturer = _read(os.path.join(dev, "manufacturer"))
label = " ".join(p for p in (manufacturer, product) if p) or "USB device"
path = f"/dev/bus/usb/{int(busnum):03d}/{int(devnum):03d}"
out.append(HostDevice(path=path, kind="usb", name=label))
return out
def _tty_devices() -> list[HostDevice]:
devices: list[HostDevice] = []
patterns = ["/dev/ttyUSB*", "/dev/ttyACM*", "/dev/ttyAMA*", "/dev/serial/by-id/*"]
for pattern in patterns:
for path in sorted(glob.glob(pattern)):
base = os.path.basename(path)
driver = _read(f"/sys/class/tty/{base}/device/driver/module/name") or ""
devices.append(
HostDevice(path=path, kind="tty", name=driver or "Serial device")
)
return devices
def _dri_devices() -> list[HostDevice]:
return [
HostDevice(path=p, kind="dri", name="GPU render node")
for p in sorted(glob.glob("/dev/dri/*"))
]
def detect_devices() -> dict:
usb = _usb_names_from_sysfs() or _usb_devices()
return {
"usb": [d.to_dict() for d in usb],
"tty": [d.to_dict() for d in _tty_devices()],
"dri": [d.to_dict() for d in _dri_devices()],
}
# --------------------------------------------------------------------------- #
# Host filesystem browser (sandboxed)
# --------------------------------------------------------------------------- #
class BrowseError(Exception):
pass
def _real_root(path: str) -> str:
"""Map a logical host path into the container view (HOST_ROOT_PREFIX).
Refuses anything that resolves inside StackPilot's own ``DATA_DIR``. That
directory holds ``stackpilot.db`` — users, password hashes and
backup-destination credentials — and the API deliberately never hands those
out (destination secrets come back masked). Without this the file browser
would be a way around that, for admins too. Note this only bites when ``HOST_ROOT_PREFIX`` is empty: with a
prefix set, no logical path can reach the container's own ``/data`` at all.
"""
prefix = settings.HOST_ROOT_PREFIX.rstrip("/")
real = prefix + path if prefix else path
data_dir = os.path.normpath(settings.DATA_DIR)
norm = os.path.normpath(real)
if norm == data_dir or norm.startswith(data_dir + os.sep):
raise BrowseError("Path is inside StackPilot's own data directory")
return real
def _is_allowed(path: str) -> bool:
norm = os.path.normpath(path)
for root in settings.ALLOWED_BROWSE_ROOTS:
root = os.path.normpath(root)
if root == "/" or norm == root or norm.startswith(root + os.sep):
return True
return False
def _toward_roots(path: str) -> list[dict]:
"""For a path *above* the allowed roots: the folders below it that lead to
one (``/`` -> ``mnt``, ``opt``; ``/srv`` -> ``data`` for ``/srv/data``).
The browser opens at ``/``, which the default roots do not include, and the
breadcrumbs and "up" lead there too — so the page used to open on an error
with no way into any root at all.
"""
prefix = "/" if path == "/" else path + os.sep
names: set[str] = set()
for root in settings.ALLOWED_BROWSE_ROOTS:
root = os.path.normpath(root)
if not root.startswith(prefix):
continue
try:
if not os.path.isdir(_real_root(root)):
continue
except BrowseError:
continue
names.add(root[len(prefix):].split(os.sep, 1)[0])
entries = []
for name in sorted(names, key=str.lower):
try:
st = os.stat(_real_root(os.path.join(path, name)))
except (OSError, BrowseError):
continue
entries.append(
{
"name": name,
"type": "dir",
"size": None,
"permissions": oct(st.st_mode & 0o777),
"mtime": st.st_mtime,
"symlink": False,
}
)
return entries
def browse(path: str = "/", show_hidden: bool = False) -> dict:
path = os.path.normpath(path or "/")
if not path.startswith("/"):
raise BrowseError("Path must be absolute")
if not _is_allowed(path):
entries = _toward_roots(path)
if not entries:
raise BrowseError("Path is outside the allowed browse roots")
return {
"path": path,
"parent": os.path.dirname(path) if path != "/" else None,
"roots": settings.ALLOWED_BROWSE_ROOTS,
"entries": entries,
# Only a way through: nothing can be created or changed here.
"virtual": True,
}
real = _real_root(path)
if not os.path.isdir(real):
raise BrowseError(f"Not a directory: {path}")
entries = []
try:
names = os.listdir(real)
except PermissionError as exc:
raise BrowseError(f"Permission denied: {path}") from exc
for name in sorted(names):
if not show_hidden and name.startswith("."):
continue
full_real = os.path.join(real, name)
try:
st = os.lstat(full_real)
is_dir = os.path.isdir(full_real)
entries.append(
{
"name": name,
"type": "dir" if is_dir else "file",
"size": st.st_size if not is_dir else None,
"permissions": oct(st.st_mode & 0o777),
"mtime": st.st_mtime,
"symlink": os.path.islink(full_real),
}
)
except OSError:
continue
# Sort: dirs first, then files, both alphabetical.
entries.sort(key=lambda e: (e["type"] != "dir", e["name"].lower()))
parent = os.path.dirname(path) if path != "/" else None
return {
"path": path,
"parent": parent,
"roots": settings.ALLOWED_BROWSE_ROOTS,
"entries": entries,
}