Files
stackpilot/backend/routers/secrets.py
T
menzeljandClaude Opus 5 60a7ccff93
CI / check (push) Successful in 7m40s
CI / build-and-push (push) Successful in 1m55s
Add a test suite, a linter and a CI gate in front of the build (0.45.0)
The repo had no tests, no lint config, and a CI that went straight from push
to docker push. That is the reason F1 could ship: authorization lives in the
routers, each of 171 routes independently picks require_admin or
get_current_user, and nothing checked the choice was right.

670 tests, no Docker daemon needed. The app is driven through TestClient
without entering it as a context manager, which skips the lifespan — no
background loops, no socket — and conftest points DATA_DIR/STACKS_DIR at a
temp directory before anything is imported.

test_route_authorization.py is the load-bearing one. Rather than 171 implied
decisions it states the policy once — every route requires admin unless it is
listed in USER_READABLE or PUBLIC — and fails on any route that disagrees. A
new route defaults to admin, which is the safe direction; what it catches is a
route written with get_current_user that nobody weighed against "can this
return a credential". Writing the allowlist meant auditing all 53 user-readable
routes, which turned up one more leak: GET /api/templates/{id} returns a
template's env, and "save stack as template" snapshots the stack's real .env
into it. Now admin-only; the listing stays open.

test_agent_authorization.py pins the same invariant on the agent, where the
whole access model is one shared token declared per route and a single
forgotten Depends(verify_token) would hand over the host.

Both were checked by reintroducing the bug: re-opening /api/files/read fails
three tests with actionable messages, dropping a token guard fails two.

test_bundled_templates.py covers the 83 templates — parse, image per service,
.env.example in sync with what compose reads, every bind-mounted file actually
shipped, and no working default password. It found one on its first run:
authentik shipped PG_PASS=change-me and AUTHENTIK_SECRET_KEY=change-me against
a compose that marks both required, so the stack would have come up with a
known password instead of refusing to start. Fixed.

The rest ports the ad-hoc harnesses from 0.44.0 into permanent tests (crypto
round-trip incl. plaintext passthrough and key-loss handling, the browse
sandbox) and covers compose_service's slug/status/file handling and
secret_service's name validation.

ruff is configured as a floor, not a style bar: F, E9 and B only. Import
sorting is deliberately out — it is style, and enabling it would rewrite the
imports of nine files that have nothing else wrong. The 12 findings it did have
are fixed here (unused imports, an unused local, four raise-without-from that
were swallowing exception context).

CI now runs check (ruff, pytest, tsc) and only builds if it passes.

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

140 lines
4.3 KiB
Python

"""Per-stack file-based secrets & configs (compose) — local host.
CRUD over the secret/config files stored in the stack directory, plus
attach/detach which rewrite the stack's compose file to reference (or stop
referencing) a secret/config from a service. A redeploy is required for changes
to take effect on running containers.
"""
from __future__ import annotations
from fastapi import APIRouter, Depends, HTTPException, Request
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, secret_service
from services.compose_edit_service import EditError
from services.secret_service import SecretError
router = APIRouter(prefix="/api/stacks/{stack_id}/secrets", tags=["secrets"])
class SecretWrite(BaseModel):
kind: str = "secret" # "secret" | "config"
name: str
content: str
class AttachBody(BaseModel):
kind: str = "secret"
name: str
service: str
target: str | None = None # required for configs (mount path)
class DetachBody(BaseModel):
kind: str = "secret"
name: str
service: str
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 (SecretError, EditError) as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
# --- These functions are shared verbatim by the agent (see agent_app.py). ---
def list_secrets(stack_id: str) -> list[dict]:
return secret_service.list_all(stack_id)
def write_secret(stack_id: str, body: SecretWrite) -> dict:
return _guard(secret_service.write_secret, stack_id, body.kind, body.name, body.content)
def delete_secret(stack_id: str, kind: str, name: str) -> dict:
_guard(secret_service.delete_secret, stack_id, kind, name)
return {"ok": True}
def attach_secret(stack_id: str, body: AttachBody) -> dict:
if not secret_service.exists(stack_id, body.kind, body.name):
raise HTTPException(status_code=404, detail="secret not found")
new_yaml = _guard(secret_service.attach, stack_id, body.kind, body.name, body.service, body.target)
return {"ok": True, "yaml": new_yaml}
def detach_secret(stack_id: str, body: DetachBody) -> dict:
new_yaml = _guard(secret_service.detach, stack_id, body.kind, body.name, body.service)
return {"ok": True, "yaml": new_yaml}
# --- HTTP endpoints (admin only; secrets are sensitive) ---
@router.get("")
def http_list(stack_id: str, _user: User = Depends(require_admin)) -> list[dict]:
return list_secrets(stack_id)
@router.put("")
def http_write(
stack_id: str, body: SecretWrite, request: Request,
session: Session = Depends(get_session), user: User = Depends(require_admin),
) -> dict:
result = write_secret(stack_id, body)
audit_service.record(
session, user=user.username, action="secret.write",
target=f"{stack_id}/{body.kind}/{body.name}", ip=_ip(request),
)
return result
@router.delete("/{kind}/{name}")
def http_delete(
stack_id: str, kind: str, name: str, request: Request,
session: Session = Depends(get_session), user: User = Depends(require_admin),
) -> dict:
result = delete_secret(stack_id, kind, name)
audit_service.record(
session, user=user.username, action="secret.delete",
target=f"{stack_id}/{kind}/{name}", ip=_ip(request),
)
return result
@router.post("/attach")
def http_attach(
stack_id: str, body: AttachBody, request: Request,
session: Session = Depends(get_session), user: User = Depends(require_admin),
) -> dict:
result = attach_secret(stack_id, body)
audit_service.record(
session, user=user.username, action="secret.attach",
target=f"{stack_id}/{body.kind}/{body.name}->{body.service}", ip=_ip(request),
)
return result
@router.post("/detach")
def http_detach(
stack_id: str, body: DetachBody, request: Request,
session: Session = Depends(get_session), user: User = Depends(require_admin),
) -> dict:
result = detach_secret(stack_id, body)
audit_service.record(
session, user=user.username, action="secret.detach",
target=f"{stack_id}/{body.kind}/{body.name}->{body.service}", ip=_ip(request),
)
return result