Files
stackpilot/backend/routers/destinations.py
T
menzeljandClaude Opus 5 54c835b032
CI / build-and-push (push) Successful in 3m53s
Close the read-side privilege escalation and fix proxy-aware IPs (0.44.0)
F1 — Any authenticated user could read any file the backend could see.
/api/files/read and /download hung on get_current_user, and the sandbox that
should have caught that was open by default: ALLOWED_BROWSE_ROOTS contained
"/", for which _is_allowed() waves through every path. So the `user` role could
download stackpilot.db (password hashes, agent tokens, backup credentials),
every stack's .env and every .secrets/* file — with no audit trail, because
only mutations were logged.

Implementing that turned up three more doors into the same room, all fixed
here since closing only the first would have made the fix cosmetic:
GET /api/stacks/{id} handed the .env to any user, /export tarred the whole
stack dir including .secrets/*, and both the agent file proxies and
/api/agents/{id}/stacks/{id} repeated the leak for every remote host. All 24
filesystem-touching routes are now admin-only; reads and downloads are audited
(listing is not — the Files page polls it). DATA_DIR is refused outright, since
the API deliberately masks agent tokens and destination secrets and the browser
would otherwise be the way around that. "/" is out of the default browse roots.

F2 — Backup destination credentials were plaintext JSON in the DB, which is
what made F1 worth exploiting. They are now Fernet-encrypted at rest behind
parse_config/dump_config, with existing rows migrated at startup.

This needed a prerequisite from F6: the key is derived from SECRET_KEY, which
was regenerated on every boot when unset. Encrypting against a key that changes
per restart would be worse than plaintext, so an auto-generated SECRET_KEY is
now persisted to ${DATA_DIR}/secret_key at mode 0600. Sessions surviving a
restart is a welcome side effect.

F3 — /api/audit is admin-only. Also hidden from the dashboard and the nav for
non-admins, so nobody polls into a 403.

F4 — uvicorn now runs with --proxy-headers, so nginx's X-Forwarded-For is
honoured. Without it request.client.host was the frontend container's IP for
every request, which made the login rate limit global instead of per-IP (10
failures locked out everyone) and filled the audit log's IP column with one
useless value.

Verified: encrypt/decrypt round-trip incl. plaintext passthrough, idempotent
re-encryption and wrong-key handling; sandbox denial for DATA_DIR, traversal
into it, and paths outside the roots, with the allowed roots still reachable.
Both against stubbed settings — there is no Docker here, so nothing was run
end to end.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Dk43rmEeRfYi5wsLDbmfyG
2026-08-31 13:01:53 +02:00

173 lines
5.2 KiB
Python

"""Backup destination management (SFTP / S3-compatible)."""
from __future__ import annotations
import asyncio
from fastapi import APIRouter, Depends, HTTPException, Request
from sqlmodel import Session, select
from auth import require_admin
from database import get_session
from models.backup_destination import (
DESTINATION_TYPES,
SECRET_KEYS,
BackupDestination,
DestinationCreate,
DestinationRead,
DestinationUpdate,
)
from models.user import User
from services import audit_service, backup_destination_service as dest_service
router = APIRouter(prefix="/api/backups/destinations", tags=["backups"])
def _ip(request: Request) -> str:
return request.client.host if request.client else "unknown"
def _mask(config: dict) -> dict:
return {k: ("••••••" if k in SECRET_KEYS and v else v) for k, v in config.items()}
def _to_read(d: BackupDestination) -> DestinationRead:
return DestinationRead(
id=d.id,
name=d.name,
type=d.type,
config=_mask(dest_service.parse_config(d)),
created_at=d.created_at,
)
def _get_or_404(session: Session, dest_id: int) -> BackupDestination:
d = session.get(BackupDestination, dest_id)
if not d:
raise HTTPException(status_code=404, detail=f"Destination {dest_id} not found")
return d
@router.get("", response_model=list[DestinationRead])
def list_destinations(
session: Session = Depends(get_session),
_user: User = Depends(require_admin),
) -> list[DestinationRead]:
rows = session.exec(select(BackupDestination).order_by(BackupDestination.id)).all()
return [_to_read(d) for d in rows]
@router.post("", response_model=DestinationRead, status_code=201)
def create_destination(
body: DestinationCreate,
request: Request,
session: Session = Depends(get_session),
user: User = Depends(require_admin),
) -> DestinationRead:
if body.type not in DESTINATION_TYPES:
raise HTTPException(status_code=400, detail=f"Unknown type '{body.type}'")
d = BackupDestination(
name=body.name, type=body.type, config=dest_service.dump_config(body.config)
)
session.add(d)
session.commit()
session.refresh(d)
audit_service.record(
session, user=user.username, action="destination.create", target=body.name,
detail=body.type, ip=_ip(request),
)
return _to_read(d)
@router.put("/{dest_id}", response_model=DestinationRead)
def update_destination(
dest_id: int,
body: DestinationUpdate,
request: Request,
session: Session = Depends(get_session),
user: User = Depends(require_admin),
) -> DestinationRead:
d = _get_or_404(session, dest_id)
if body.name is not None:
d.name = body.name
if body.config is not None:
# Merge so masked/blank secrets don't wipe stored ones.
existing = dest_service.parse_config(d)
for k, v in body.config.items():
if k in SECRET_KEYS and (v == "" or v == "••••••"):
continue # keep existing secret
existing[k] = v
d.config = dest_service.dump_config(existing)
session.add(d)
session.commit()
session.refresh(d)
audit_service.record(
session, user=user.username, action="destination.update", target=d.name,
ip=_ip(request),
)
return _to_read(d)
@router.delete("/{dest_id}")
def delete_destination(
dest_id: int,
request: Request,
session: Session = Depends(get_session),
user: User = Depends(require_admin),
) -> dict:
d = _get_or_404(session, dest_id)
name = d.name
session.delete(d)
session.commit()
audit_service.record(
session, user=user.username, action="destination.delete", target=name,
ip=_ip(request),
)
return {"ok": True}
@router.post("/{dest_id}/test")
async def test_destination(
dest_id: int,
session: Session = Depends(get_session),
_user: User = Depends(require_admin),
) -> dict:
d = _get_or_404(session, dest_id)
try:
await asyncio.to_thread(dest_service.test, d)
return {"ok": True}
except dest_service.DestinationError as exc:
return {"ok": False, "error": str(exc)}
@router.get("/{dest_id}/backups")
async def list_destination_backups(
dest_id: int,
session: Session = Depends(get_session),
_user: User = Depends(require_admin),
) -> list[dict]:
d = _get_or_404(session, dest_id)
try:
return await asyncio.to_thread(dest_service.list_backups, d)
except dest_service.DestinationError as exc:
raise HTTPException(status_code=502, detail=str(exc)) from exc
@router.delete("/{dest_id}/backups/{name}")
async def delete_destination_backup(
dest_id: int,
name: str,
request: Request,
session: Session = Depends(get_session),
user: User = Depends(require_admin),
) -> dict:
d = _get_or_404(session, dest_id)
try:
await asyncio.to_thread(dest_service.delete, d, name)
except dest_service.DestinationError as exc:
raise HTTPException(status_code=502, detail=str(exc)) from exc
audit_service.record(
session, user=user.username, action="destination.backup.delete",
target=f"{d.name}/{name}", ip=_ip(request),
)
return {"ok": True}