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
248 lines
8.4 KiB
Python
248 lines
8.4 KiB
Python
"""Deploying stacks from Git.
|
|
|
|
Everything here is admin-only except the webhook, which cannot be: a Git forge
|
|
has no StackPilot credentials to present. It authenticates with an HMAC over the
|
|
request body instead, against a secret generated per stack — see
|
|
``git_service.verify_webhook``.
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
from datetime import datetime, timezone
|
|
|
|
from fastapi import APIRouter, Depends, HTTPException, Request
|
|
from sqlmodel import Session, select
|
|
|
|
from auth import require_admin
|
|
from database import get_session
|
|
from models.git_source import (
|
|
AUTH_TYPES,
|
|
GitSource,
|
|
GitSourceRead,
|
|
GitSourceWrite,
|
|
SyncResult,
|
|
)
|
|
from models.stack import Stack
|
|
from models.user import User
|
|
from services import audit_service, crypto_service, git_service
|
|
|
|
router = APIRouter(prefix="/api/stacks/{stack_id}/git", tags=["git"])
|
|
|
|
|
|
def _ip(request: Request) -> str:
|
|
return request.client.host if request.client else "unknown"
|
|
|
|
|
|
def _stack_or_404(session: Session, stack_id: str) -> Stack:
|
|
stack = session.get(Stack, stack_id)
|
|
if not stack:
|
|
raise HTTPException(status_code=404, detail=f"Stack '{stack_id}' not found")
|
|
return stack
|
|
|
|
|
|
def _source(session: Session, stack_id: str) -> GitSource:
|
|
row = session.exec(select(GitSource).where(GitSource.stack_id == stack_id)).first()
|
|
if not row:
|
|
raise HTTPException(
|
|
status_code=404, detail=f"Stack '{stack_id}' is not connected to a repository"
|
|
)
|
|
return row
|
|
|
|
|
|
def _to_read(row: GitSource) -> GitSourceRead:
|
|
return GitSourceRead(
|
|
stack_id=row.stack_id,
|
|
url=row.url,
|
|
branch=row.branch,
|
|
subdir=row.subdir,
|
|
auth_type=row.auth_type,
|
|
username=row.username,
|
|
has_secret=bool(row.secret),
|
|
auto_deploy=row.auto_deploy,
|
|
poll_interval_minutes=row.poll_interval_minutes,
|
|
# Relative on purpose: StackPilot does not know its own external URL,
|
|
# and guessing one into a forge's webhook settings would be worse than
|
|
# letting the UI prefix the address the admin is already looking at.
|
|
webhook_url=f"/api/git/webhook/{row.stack_id}",
|
|
last_commit=row.last_commit,
|
|
last_synced_at=row.last_synced_at,
|
|
last_error=row.last_error,
|
|
managed_file_count=len(git_service._managed(row)),
|
|
)
|
|
|
|
|
|
@router.get("", response_model=GitSourceRead)
|
|
def get_source(
|
|
stack_id: str,
|
|
session: Session = Depends(get_session),
|
|
_user: User = Depends(require_admin),
|
|
) -> GitSourceRead:
|
|
return _to_read(_source(session, stack_id))
|
|
|
|
|
|
@router.put("", response_model=GitSourceRead)
|
|
def connect(
|
|
stack_id: str,
|
|
body: GitSourceWrite,
|
|
request: Request,
|
|
session: Session = Depends(get_session),
|
|
user: User = Depends(require_admin),
|
|
) -> GitSourceRead:
|
|
"""Connect a stack to a repository, or change how it is connected.
|
|
|
|
Does not sync — the caller decides when, because the first sync overwrites
|
|
the stack's compose file with whatever the repository says.
|
|
"""
|
|
_stack_or_404(session, stack_id)
|
|
if body.auth_type not in AUTH_TYPES:
|
|
raise HTTPException(status_code=400, detail=f"Unknown auth type '{body.auth_type}'")
|
|
if not (body.url or "").strip():
|
|
raise HTTPException(status_code=400, detail="A repository URL is required")
|
|
try:
|
|
git_service.validate_url(body.url)
|
|
git_service.validate_branch(body.branch or "main")
|
|
except git_service.GitError as exc:
|
|
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
|
|
|
row = session.exec(select(GitSource).where(GitSource.stack_id == stack_id)).first()
|
|
if row is None:
|
|
row = GitSource(stack_id=stack_id, url="", webhook_secret=git_service.new_webhook_secret())
|
|
|
|
row.url = body.url.strip()
|
|
row.branch = (body.branch or "main").strip() or "main"
|
|
row.subdir = (body.subdir or "").strip().strip("/")
|
|
row.auth_type = body.auth_type
|
|
row.username = body.username
|
|
if body.secret:
|
|
row.secret = crypto_service.encrypt(body.secret)
|
|
elif body.auth_type == "none":
|
|
row.secret = None
|
|
row.auto_deploy = body.auto_deploy
|
|
row.poll_interval_minutes = body.poll_interval_minutes or None
|
|
row.updated_at = datetime.now(timezone.utc)
|
|
session.add(row)
|
|
session.commit()
|
|
session.refresh(row)
|
|
audit_service.record(
|
|
session, user=user.username, action="stack.git-connect", target=stack_id,
|
|
detail=f"{row.url}#{row.branch}", ip=_ip(request),
|
|
)
|
|
return _to_read(row)
|
|
|
|
|
|
@router.delete("")
|
|
def disconnect(
|
|
stack_id: str,
|
|
request: Request,
|
|
session: Session = Depends(get_session),
|
|
user: User = Depends(require_admin),
|
|
) -> dict:
|
|
"""Stop tracking the repository. The stack's files are left exactly as they are."""
|
|
row = _source(session, stack_id)
|
|
session.delete(row)
|
|
session.commit()
|
|
git_service.forget(stack_id)
|
|
audit_service.record(
|
|
session, user=user.username, action="stack.git-disconnect", target=stack_id,
|
|
ip=_ip(request),
|
|
)
|
|
return {"ok": True}
|
|
|
|
|
|
@router.post("/sync", response_model=SyncResult)
|
|
async def sync_now(
|
|
stack_id: str,
|
|
request: Request,
|
|
session: Session = Depends(get_session),
|
|
user: User = Depends(require_admin),
|
|
) -> SyncResult:
|
|
row = _source(session, stack_id)
|
|
try:
|
|
result = await git_service.sync(session, row, actor=user.username)
|
|
except git_service.GitError as exc:
|
|
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
|
audit_service.record(
|
|
session, user=user.username, action="stack.git-sync", target=stack_id,
|
|
detail=f"{(result.commit or '')[:8]} {'changed' if result.changed else 'no change'}",
|
|
ip=_ip(request),
|
|
)
|
|
return result
|
|
|
|
|
|
@router.get("/webhook-secret")
|
|
def reveal_webhook_secret(
|
|
stack_id: str,
|
|
session: Session = Depends(get_session),
|
|
_user: User = Depends(require_admin),
|
|
) -> dict:
|
|
"""The secret to paste into the forge's webhook settings.
|
|
|
|
Readable rather than shown-once: it lives in the forge's configuration too,
|
|
so hiding it here would only mean re-pointing the webhook to see it again.
|
|
"""
|
|
return {"secret": _source(session, stack_id).webhook_secret}
|
|
|
|
|
|
@router.post("/webhook-secret")
|
|
def rotate_webhook_secret(
|
|
stack_id: str,
|
|
request: Request,
|
|
session: Session = Depends(get_session),
|
|
user: User = Depends(require_admin),
|
|
) -> dict:
|
|
row = _source(session, stack_id)
|
|
row.webhook_secret = git_service.new_webhook_secret()
|
|
row.updated_at = datetime.now(timezone.utc)
|
|
session.add(row)
|
|
session.commit()
|
|
audit_service.record(
|
|
session, user=user.username, action="stack.git-rotate-secret", target=stack_id,
|
|
ip=_ip(request),
|
|
)
|
|
return {"secret": row.webhook_secret}
|
|
|
|
|
|
# --------------------------------------------------------------------------- #
|
|
# The webhook
|
|
# --------------------------------------------------------------------------- #
|
|
|
|
hook_router = APIRouter(prefix="/api/git", tags=["git"])
|
|
|
|
|
|
@hook_router.post("/webhook/{stack_id}")
|
|
async def webhook(
|
|
stack_id: str,
|
|
request: Request,
|
|
session: Session = Depends(get_session),
|
|
) -> dict:
|
|
"""Push webhook from a Git forge.
|
|
|
|
Unauthenticated in the usual sense — a forge holds no StackPilot session —
|
|
and authorized by an HMAC over the body instead. An unsigned or wrongly
|
|
signed call is a 404, not a 403: without credentials to present, telling a
|
|
caller that a given stack *is* connected to a repository is information it
|
|
has not earned.
|
|
"""
|
|
row = session.exec(select(GitSource).where(GitSource.stack_id == stack_id)).first()
|
|
body = await request.body()
|
|
if not row or not git_service.verify_webhook(row, body, request.headers):
|
|
raise HTTPException(status_code=404, detail="Not found")
|
|
if not session.get(Stack, stack_id):
|
|
# Signed, but for a stack that was deleted: never bring it back.
|
|
raise HTTPException(status_code=404, detail="Not found")
|
|
|
|
try:
|
|
result = await git_service.sync(session, row, actor="webhook")
|
|
except git_service.GitError as exc:
|
|
raise HTTPException(status_code=502, detail=str(exc)) from exc
|
|
audit_service.record(
|
|
session, user="webhook", action="stack.git-sync", target=stack_id,
|
|
detail=f"{(result.commit or '')[:8]} {'changed' if result.changed else 'no change'}",
|
|
ip=_ip(request),
|
|
)
|
|
return {
|
|
"ok": True,
|
|
"changed": result.changed,
|
|
"commit": result.commit,
|
|
"deployed": result.deployed,
|
|
}
|