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

187 lines
6.9 KiB
Python

"""Deleting a stack: what goes with it, and what must not.
Before 0.67.1 a deleted stack left its Git source behind — and the poll loop or
the next push webhook recreated the folder from the repository and started the
stack again. Its auto-update policy was inherited by the next stack of the same
name, and every backup schedule naming it failed from then on. Deleting the
folder also walked into whatever was mounted inside it (a NAS share at
``./media``) and deleted that too.
"""
from __future__ import annotations
import asyncio
import json
import os
import pytest
from sqlmodel import Session, delete, select
@pytest.fixture(autouse=True)
def clean(db):
from database import engine
from models.auto_update import AutoUpdate
from models.backup_schedule import BackupSchedule
from models.git_source import GitSource
from models.runtime_state import StackLock
def wipe():
with Session(engine) as session:
for model in (GitSource, AutoUpdate, BackupSchedule, StackLock):
session.exec(delete(model))
session.commit()
wipe()
yield
wipe()
def _schedule(session, stack_ids, all_stacks=False):
from models.backup_schedule import BackupSchedule, set_stacks
schedule = BackupSchedule(destination_id=1, all_stacks=all_stacks)
set_stacks(schedule, stack_ids)
session.add(schedule)
session.commit()
session.refresh(schedule)
return schedule.id
def test_forget_stack_drops_what_refers_to_it(db):
from database import engine
from models.auto_update import AutoUpdate
from models.backup_schedule import BackupSchedule, stacks_of
from models.git_source import GitSource
from services import stack_cleanup_service
with Session(engine) as session:
session.add(GitSource(stack_id="gone", url="https://example.invalid/x.git"))
session.add(AutoUpdate(stack_id="gone"))
session.add(AutoUpdate(stack_id="stays"))
both = _schedule(session, ["gone", "stays"])
only = _schedule(session, ["gone"])
everything = _schedule(session, [], all_stacks=True)
report = stack_cleanup_service.forget_stack(session, "gone")
assert report["git"] is True and report["auto_update"] == 1
assert session.exec(select(GitSource)).all() == []
assert [p.stack_id for p in session.exec(select(AutoUpdate)).all()] == ["stays"]
assert stacks_of(session.get(BackupSchedule, both)) == ["stays"]
lonely = session.get(BackupSchedule, only)
assert stacks_of(lonely) == [] and lonely.enabled is False
assert "was deleted" in lonely.last_status
assert session.get(BackupSchedule, everything).enabled is True
def test_orphans_from_older_versions_are_forgotten_at_startup(db):
from database import engine
from models.git_source import GitSource
from models.stack import Stack
from services import stack_cleanup_service
with Session(engine) as session:
if not session.get(Stack, "alive"):
session.add(Stack(id="alive", name="alive"))
session.add(GitSource(stack_id="alive", url="https://example.invalid/a.git"))
session.add(GitSource(stack_id="long-deleted", url="https://example.invalid/b.git"))
session.commit()
assert stack_cleanup_service.prune_orphans(session) == ["long-deleted"]
assert [g.stack_id for g in session.exec(select(GitSource)).all()] == ["alive"]
def test_git_never_syncs_a_stack_that_no_longer_exists(db):
from database import engine
from models.git_source import GitSource
from services import git_service
with Session(engine) as session:
source = GitSource(stack_id="ghost", url="https://example.invalid/g.git")
session.add(source)
session.commit()
session.refresh(source)
with pytest.raises(git_service.GitError, match="no longer exists"):
asyncio.run(git_service.sync(session, source))
def test_deleting_a_busy_stack_is_refused(as_admin, db):
from database import engine
from models.stack import Stack
from services import stack_lock_service
with Session(engine) as session:
if not session.get(Stack, "busy-del"):
session.add(Stack(id="busy-del", name="busy"))
session.commit()
stack_lock_service.acquire(session, "busy-del", "backup", "scheduled")
response = as_admin.delete("/api/stacks/busy-del")
assert response.status_code == 409
assert "backup" in response.json()["detail"]
def test_folder_removal_stops_at_mount_points(tmp_path, monkeypatch):
from services import compose_service
stack = tmp_path / "media-stack"
(stack / "config").mkdir(parents=True)
(stack / "config" / "app.db").write_text("x")
(stack / "compose.yaml").write_text("services: {}\n")
share = stack / "media"
share.mkdir()
(share / "movie.mkv").write_text("precious")
monkeypatch.setattr(compose_service, "_mount_points", lambda: {str(share)})
kept = compose_service.delete_stack_files("media-stack", override=str(tmp_path))
assert kept == [str(share)]
assert (share / "movie.mkv").read_text() == "precious"
assert not (stack / "config").exists() and not (stack / "compose.yaml").exists()
def test_cloning_copies_links_as_links_and_skips_sockets(tmp_path):
import socket
from services import compose_service
src = tmp_path / "orig"
src.mkdir()
(src / "compose.yaml").write_text("services: {}\n")
os.symlink("/definitely/not/there", src / "dangling")
sock = socket.socket(socket.AF_UNIX)
sock.bind(str(src / "app.sock"))
try:
compose_service.clone_stack_files("orig", "copy", override=str(tmp_path))
finally:
sock.close()
dst = tmp_path / "copy"
assert (dst / "compose.yaml").exists()
assert os.readlink(dst / "dangling") == "/definitely/not/there"
assert not os.path.lexists(dst / "app.sock")
def test_a_deleted_stack_name_does_not_inherit_its_schedules(as_admin, db, monkeypatch):
"""End to end through the API, with Docker stubbed out."""
from database import engine
from models.backup_schedule import BackupSchedule, stacks_of
from services import compose_service
async def down(stack_id, override=None):
return {"returncode": 0, "stdout": "", "stderr": ""}
monkeypatch.setattr(compose_service, "down", down)
assert as_admin.post("/api/stacks", json={"name": "del-me"}).status_code == 201
with Session(engine) as session:
schedule_id = _schedule(session, ["del-me"])
response = as_admin.delete("/api/stacks/del-me")
assert response.status_code == 200, response.text
assert response.json()["kept"] == []
with Session(engine) as session:
schedule = session.get(BackupSchedule, schedule_id)
assert stacks_of(schedule) == [] and not schedule.enabled
assert not os.path.isdir(compose_service.stack_dir("del-me"))
assert json.loads(as_admin.get("/api/stacks").text) is not None