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

262 lines
7.5 KiB
Python

"""Full host filesystem browser: list, read, edit, manage, up/download.
Every operation requires admin. Reads are not less dangerous than writes here:
the browser reaches whatever the backend container can see, which includes
every stack's ``.env`` and ``.secrets/*``. Reading a file and downloading one
are audit-logged just like the mutating operations; directory listing is not,
because the Files page polls it and would drown the log.
All paths are sandboxed by :mod:`services.file_service`.
"""
from __future__ import annotations
import os
import tempfile
from fastapi import (
APIRouter,
Depends,
File,
Form,
HTTPException,
Query,
Request,
UploadFile,
)
from fastapi.responses import FileResponse, StreamingResponse
from pydantic import BaseModel
from sqlmodel import Session
from auth import require_admin
from database import get_session
from models.user import User
from services import audit_service, device_service, file_service
router = APIRouter(prefix="/api/files", tags=["files"])
def _attachment(filename: str) -> str:
"""A safe ``Content-Disposition`` value for an arbitrary filename."""
safe = filename.replace("\\", "_").replace('"', "_")
return f'attachment; filename="{safe}"'
def _ip(request: Request) -> str:
return request.client.host if request.client else "unknown"
def _guard(fn, *args, **kwargs):
try:
return fn(*args, **kwargs)
except file_service.BrowseError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
# --------------------------------------------------------------------------- #
# Read-only
# --------------------------------------------------------------------------- #
@router.get("/list")
def list_dir(
path: str = Query("/"),
show_hidden: bool = Query(False),
_admin: User = Depends(require_admin),
) -> dict:
return _guard(device_service.browse, path, show_hidden)
@router.get("/read")
def read_file(
request: Request,
path: str = Query(...),
session: Session = Depends(get_session),
user: User = Depends(require_admin),
) -> dict:
result = _guard(file_service.read_file, path)
audit_service.record(
session, user=user.username, action="file.read", target=path, ip=_ip(request)
)
return result
@router.get("/download")
def download(
request: Request,
path: str = Query(...),
session: Session = Depends(get_session),
user: User = Depends(require_admin),
):
audit_service.record(
session, user=user.username, action="file.download", target=path, ip=_ip(request)
)
if _guard(file_service.is_dir, path):
filename, chunks = _guard(file_service.open_archive, path)
# Stream the zip as it's built so the response starts immediately
# (large folders no longer hit the proxy's read timeout).
return StreamingResponse(
chunks, media_type="application/zip",
headers={"Content-Disposition": _attachment(filename)},
)
real, filename = _guard(file_service.resolve_download, path)
return FileResponse(real, filename=filename, media_type="application/octet-stream")
# --------------------------------------------------------------------------- #
# Mutating (admin only)
# --------------------------------------------------------------------------- #
class WriteBody(BaseModel):
path: str
content: str
class NameBody(BaseModel):
path: str
name: str
class RenameBody(BaseModel):
path: str
new_name: str
class TransferBody(BaseModel):
src: str
dest_dir: str
overwrite: bool = False
@router.put("/write")
def write_file(
body: WriteBody,
request: Request,
session: Session = Depends(get_session),
user: User = Depends(require_admin),
) -> dict:
result = _guard(file_service.write_file, body.path, body.content)
audit_service.record(
session, user=user.username, action="file.write", target=body.path, ip=_ip(request)
)
return result
@router.post("/mkdir")
def mkdir(
body: NameBody,
request: Request,
session: Session = Depends(get_session),
user: User = Depends(require_admin),
) -> dict:
result = _guard(file_service.create_dir, body.path, body.name)
audit_service.record(
session, user=user.username, action="file.mkdir", target=result["path"], ip=_ip(request)
)
return result
@router.post("/touch")
def touch(
body: NameBody,
request: Request,
session: Session = Depends(get_session),
user: User = Depends(require_admin),
) -> dict:
result = _guard(file_service.create_file, body.path, body.name)
audit_service.record(
session, user=user.username, action="file.create", target=result["path"], ip=_ip(request)
)
return result
@router.post("/rename")
def rename(
body: RenameBody,
request: Request,
session: Session = Depends(get_session),
user: User = Depends(require_admin),
) -> dict:
result = _guard(file_service.rename, body.path, body.new_name)
audit_service.record(
session, user=user.username, action="file.rename",
target=body.path, detail=f"-> {result['path']}", ip=_ip(request),
)
return result
@router.post("/copy")
def copy(
body: TransferBody,
request: Request,
session: Session = Depends(get_session),
user: User = Depends(require_admin),
) -> dict:
result = _guard(file_service.copy, body.src, body.dest_dir, body.overwrite)
audit_service.record(
session, user=user.username, action="file.copy",
target=body.src, detail=f"-> {result['path']}", ip=_ip(request),
)
return result
@router.post("/move")
def move(
body: TransferBody,
request: Request,
session: Session = Depends(get_session),
user: User = Depends(require_admin),
) -> dict:
result = _guard(file_service.move, body.src, body.dest_dir, body.overwrite)
audit_service.record(
session, user=user.username, action="file.move",
target=body.src, detail=f"-> {result['path']}", ip=_ip(request),
)
return result
@router.delete("")
def delete(
request: Request,
path: str = Query(...),
recursive: bool = Query(False),
session: Session = Depends(get_session),
user: User = Depends(require_admin),
) -> dict:
result = _guard(file_service.delete, path, recursive)
audit_service.record(
session, user=user.username, action="file.delete", target=path,
detail="recursive" if recursive else None, ip=_ip(request),
)
return result
@router.post("/upload")
async def upload(
request: Request,
path: str = Form(...),
overwrite: bool = Form(False),
rel_path: str = Form(""),
file: UploadFile = File(...),
session: Session = Depends(get_session),
user: User = Depends(require_admin),
) -> dict:
real = _guard(
file_service.upload_target, path, file.filename or "", overwrite, rel_path or None
)
# Stream to a temp file first, then move into place atomically.
tmp = tempfile.NamedTemporaryFile(delete=False, dir=os.path.dirname(real))
try:
while chunk := await file.read(1024 * 1024):
tmp.write(chunk)
tmp.close()
os.replace(tmp.name, real)
except OSError as exc:
if os.path.exists(tmp.name):
os.unlink(tmp.name)
raise HTTPException(status_code=400, detail=f"Upload failed: {exc}") from exc
audit_service.record(
session, user=user.username, action="file.upload",
target=path, detail=rel_path or file.filename, ip=_ip(request),
)
return {"ok": True, "name": rel_path or file.filename}