The repo had no tests, no lint config, and a CI that went straight from push
to docker push. That is the reason F1 could ship: authorization lives in the
routers, each of 171 routes independently picks require_admin or
get_current_user, and nothing checked the choice was right.
670 tests, no Docker daemon needed. The app is driven through TestClient
without entering it as a context manager, which skips the lifespan — no
background loops, no socket — and conftest points DATA_DIR/STACKS_DIR at a
temp directory before anything is imported.
test_route_authorization.py is the load-bearing one. Rather than 171 implied
decisions it states the policy once — every route requires admin unless it is
listed in USER_READABLE or PUBLIC — and fails on any route that disagrees. A
new route defaults to admin, which is the safe direction; what it catches is a
route written with get_current_user that nobody weighed against "can this
return a credential". Writing the allowlist meant auditing all 53 user-readable
routes, which turned up one more leak: GET /api/templates/{id} returns a
template's env, and "save stack as template" snapshots the stack's real .env
into it. Now admin-only; the listing stays open.
test_agent_authorization.py pins the same invariant on the agent, where the
whole access model is one shared token declared per route and a single
forgotten Depends(verify_token) would hand over the host.
Both were checked by reintroducing the bug: re-opening /api/files/read fails
three tests with actionable messages, dropping a token guard fails two.
test_bundled_templates.py covers the 83 templates — parse, image per service,
.env.example in sync with what compose reads, every bind-mounted file actually
shipped, and no working default password. It found one on its first run:
authentik shipped PG_PASS=change-me and AUTHENTIK_SECRET_KEY=change-me against
a compose that marks both required, so the stack would have come up with a
known password instead of refusing to start. Fixed.
The rest ports the ad-hoc harnesses from 0.44.0 into permanent tests (crypto
round-trip incl. plaintext passthrough and key-loss handling, the browse
sandbox) and covers compose_service's slug/status/file handling and
secret_service's name validation.
ruff is configured as a floor, not a style bar: F, E9 and B only. Import
sorting is deliberately out — it is style, and enabling it would rewrite the
imports of nine files that have nothing else wrong. The 12 findings it did have
are fixed here (unused imports, an unused local, four raise-without-from that
were swallowing exception context).
CI now runs check (ruff, pytest, tsc) and only builds if it passes.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Dk43rmEeRfYi5wsLDbmfyG
137 lines
4.8 KiB
Python
137 lines
4.8 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 contextlib
|
|
import json
|
|
import socket as _socket
|
|
|
|
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.
|
|
|
|
Shared by the central app and the agent (both pass a Starlette 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`` runs in the default executor; on teardown we shut the
|
|
socket down so that orphaned recv thread unblocks and exits.
|
|
"""
|
|
raw.setblocking(True)
|
|
loop = asyncio.get_event_loop()
|
|
closed = asyncio.Event()
|
|
|
|
async def to_browser() -> None:
|
|
try:
|
|
while True:
|
|
data = await loop.run_in_executor(None, raw.recv, 4096)
|
|
if not data:
|
|
break
|
|
await websocket.send_text(
|
|
json.dumps({"type": "data", "data": data.decode("utf-8", "replace")})
|
|
)
|
|
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:
|
|
await loop.run_in_executor(None, raw.sendall, str(obj["data"]).encode())
|
|
else:
|
|
await loop.run_in_executor(None, raw.sendall, 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()
|
|
|
|
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}))
|