Files
stackpilot/backend/tests/test_convert_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

168 lines
6.3 KiB
Python

"""Converting `docker run` into compose.
The output has to be a compose file compose accepts and that means what the
command meant. Before 0.67.1 a boolean flag the converter did not know swallowed
the image name (``-dit ubuntu bash`` became a service running ``bash``),
``--network host`` and ``-v data:/data`` produced files compose rejects, and
``--gpus`` or ``--mount`` were dropped without a word.
"""
from __future__ import annotations
import pytest
import yaml
def _service(command: str) -> tuple[str, dict, dict]:
from services.convert_service import convert_docker_run
doc = yaml.safe_load(convert_docker_run(command))
((name, service),) = doc["services"].items()
return name, service, doc
@pytest.mark.parametrize(
"command, image",
[
("docker run -dit ubuntu bash", "ubuntu"),
("docker run -d --read-only nginx", "nginx"),
("docker run -P nginx", "nginx"),
("docker run --rm --init --privileged alpine", "alpine"),
("docker run -d --oom-kill-disable --no-healthcheck redis:7", "redis:7"),
],
)
def test_boolean_flags_never_swallow_the_image(command, image):
_name, service, _doc = _service(command)
assert service["image"] == image
def test_the_command_after_the_image_is_kept():
name, service, _doc = _service("docker run -it --rm ubuntu bash -lc 'echo hi'")
assert name == "ubuntu"
assert service["command"] == ["bash", "-lc", "echo hi"]
assert service["stdin_open"] is True and service["tty"] is True
@pytest.mark.parametrize("mode", ["host", "none", "bridge", "container:vpn"])
def test_special_networks_become_network_mode(mode):
_name, service, doc = _service(f"docker run -d --network {mode} alpine")
assert service["network_mode"] == mode
assert "networks" not in service and "networks" not in doc
def test_a_named_network_is_declared_external():
_name, service, doc = _service("docker run -d --net=proxy --network-alias web alpine")
assert service["networks"] == {"proxy": {"aliases": ["web"]}}
assert doc["networks"] == {"proxy": {"external": True}}
def test_named_volumes_are_declared_and_paths_are_not():
_name, service, doc = _service(
"docker run -d -v data:/data -v /srv/media:/media:ro -v ./conf:/conf alpine"
)
assert service["volumes"] == ["data:/data", "/srv/media:/media:ro", "./conf:/conf"]
assert doc["volumes"] == {"data": None}
def test_mount_becomes_long_syntax():
_name, service, doc = _service(
"docker run --mount type=bind,source=/srv,target=/srv,readonly "
"--mount type=volume,src=cache,dst=/cache alpine"
)
assert service["volumes"][0] == {
"type": "bind", "source": "/srv", "target": "/srv", "read_only": True,
}
assert service["volumes"][1] == {"type": "volume", "source": "cache", "target": "/cache"}
assert doc["volumes"] == {"cache": None}
@pytest.mark.parametrize(
"value, expected",
[
("all", {"count": "all"}),
("2", {"count": 2}),
('"device=0,1"', {"device_ids": ["0", "1"]}),
],
)
def test_gpus_become_a_device_reservation(value, expected):
_name, service, _doc = _service(f"docker run -d --gpus {value} ollama/ollama")
(device,) = service["deploy"]["resources"]["reservations"]["devices"]
assert device["driver"] == "nvidia"
assert device["capabilities"] == ["gpu"]
for key, val in expected.items():
assert device[key] == val
def test_attached_short_values_and_equals_forms():
_name, service, _doc = _service(
"docker run -p8080:80 -eTZ=Europe/Berlin --restart=always --name=web nginx"
)
assert service["ports"] == ["8080:80"]
assert service["environment"] == ["TZ=Europe/Berlin"]
assert service["restart"] == "always"
assert service["container_name"] == "web"
def test_common_runtime_flags_are_kept():
_name, service, _doc = _service(
"sudo docker run -d --name plex --entrypoint /init --shm-size 1g -m 2g --cpus 1.5 "
"--cap-add NET_ADMIN --cap-drop ALL --security-opt no-new-privileges "
"--sysctl net.ipv4.ip_forward=1 --add-host nas:10.0.0.2 --dns 1.1.1.1 "
"--ulimit nofile=1024:2048 --log-opt max-size=10m --tmpfs /run "
"--health-cmd 'curl -f http://localhost' --health-interval 30s --stop-timeout 30 "
"lscr.io/linuxserver/plex:latest"
)
assert service["entrypoint"] == "/init"
assert service["shm_size"] == "1g"
assert service["mem_limit"] == "2g"
assert service["cpus"] == 1.5
assert service["cap_add"] == ["NET_ADMIN"] and service["cap_drop"] == ["ALL"]
assert service["security_opt"] == ["no-new-privileges"]
assert service["sysctls"] == ["net.ipv4.ip_forward=1"]
assert service["extra_hosts"] == ["nas:10.0.0.2"]
assert service["dns"] == ["1.1.1.1"]
assert service["ulimits"] == {"nofile": {"soft": 1024, "hard": 2048}}
assert service["logging"] == {"options": {"max-size": "10m"}}
assert service["tmpfs"] == ["/run"]
assert service["healthcheck"] == {
"test": ["CMD-SHELL", "curl -f http://localhost"], "interval": "30s",
}
assert service["stop_grace_period"] == "30s"
def test_line_continuations_from_a_readme():
name, service, _doc = _service("docker run -d \\\n --name x \\\r\n -p 1:1 \\\n alpine")
assert name == "x"
assert service["ports"] == ["1:1"]
def test_the_service_name_comes_from_the_image_without_registry_or_tag():
name, _service_, _doc = _service("docker run -d ghcr.io/home-assistant/home-assistant:stable")
assert name == "home-assistant"
def test_no_image_is_an_error():
from services.convert_service import convert_docker_run
with pytest.raises(ValueError):
convert_docker_run("docker run -d --name x")
@pytest.mark.parametrize(
"command",
[
# Pasted into a one-line field: the newlines are gone, the backslashes
# and indentation are not.
"docker run -d \\ --name web \\ -p 8081:80 \\ -v data:/data \\ nginx:alpine",
"docker run -d \\ --name web \\ -p 8081:80 \\\n nginx:alpine",
],
)
def test_continuations_that_lost_their_newline(command):
name, web, _ = _service(command)
assert name == "web" and web["image"] == "nginx:alpine"
assert web["ports"] == ["8081:80"]
def test_an_escaped_space_in_a_path_is_still_one():
_, service, _ = _service("docker run -v /mnt/My\\ Files:/data nginx")
assert service["volumes"] == ["/mnt/My Files:/data"]