Files
stackpilot/backend/routers/volumes.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

110 lines
3.4 KiB
Python

"""Volume management, NFS/SMB YAML generation, and host path browser."""
from __future__ import annotations
from fastapi import APIRouter, Depends, HTTPException, Query, Request
from sqlmodel import Session
from auth import get_current_user, require_admin
from database import get_session
from models.user import User
from services import audit_service, device_service, volume_service
router = APIRouter(tags=["volumes"])
def _ip(request: Request) -> str:
return request.client.host if request.client else "unknown"
# --------------------------------------------------------------------------- #
# Volumes
# --------------------------------------------------------------------------- #
@router.get("/api/volumes")
def list_volumes(_user: User = Depends(get_current_user)) -> list[dict]:
return volume_service.list_volumes()
@router.get("/api/volumes/orphaned")
def orphaned(_user: User = Depends(get_current_user)) -> list[dict]:
return volume_service.orphaned_volumes()
@router.get("/api/volumes/sizes")
def volume_sizes(
force: bool = Query(False),
_user: User = Depends(get_current_user),
) -> dict:
"""Volume sizes in bytes ({name: size|null}). Expensive; cached ~60s."""
return volume_service.volume_sizes(force=force)
@router.delete("/api/volumes/{name}")
def delete_volume(
name: str,
request: Request,
force: bool = Query(False),
session: Session = Depends(get_session),
user: User = Depends(require_admin),
) -> dict:
vols = {v["name"]: v for v in volume_service.list_volumes()}
if name in vols and vols[name]["in_use"] and not force:
raise HTTPException(
status_code=409,
detail={
"error": "volume_in_use",
"detail": f"Volume '{name}' is used by: {', '.join(vols[name]['used_by'])}",
},
)
volume_service.remove_volume(name, force=force)
audit_service.record(
session, user=user.username, action="volume.delete", target=name, ip=_ip(request)
)
return {"ok": True}
@router.post("/api/volumes/prune")
def prune(
request: Request,
session: Session = Depends(get_session),
user: User = Depends(require_admin),
) -> dict:
result = volume_service.prune_volumes()
audit_service.record(
session, user=user.username, action="volume.prune", target="*",
detail=str(result.get("VolumesDeleted")), ip=_ip(request),
)
return result
@router.post("/api/volumes/generate-yaml")
def generate_yaml(
spec: dict,
_user: User = Depends(get_current_user),
) -> dict:
try:
return {"yaml": volume_service.generate_yaml(spec)}
except (KeyError, ValueError) as exc:
raise HTTPException(status_code=400, detail=f"Invalid volume spec: {exc}") from exc
# --------------------------------------------------------------------------- #
# Host path browser
# --------------------------------------------------------------------------- #
@router.get("/api/host/paths")
def host_paths(
path: str = Query("/"),
show_hidden: bool = Query(False),
_admin: User = Depends(require_admin),
) -> dict:
"""Directory picker for the volume wizard. Same browse() as the file
browser, so it carries the same admin requirement — and only admins can
create a volume with the result anyway."""
try:
return device_service.browse(path, show_hidden)
except device_service.BrowseError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc