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

160 lines
5.6 KiB
Python

"""Template library endpoints.
Templates are stack-shaped folders on disk. Listing reads them; "instantiate"
(pull) copies the whole folder into a new stack, which is then editable.
"""
from __future__ import annotations
import os
from fastapi import APIRouter, Depends, HTTPException, Request
from sqlmodel import Session
from auth import get_current_user, require_admin
from database import get_session
from models.agent import Agent
from models.stack import Stack
from models.template import (
TemplateFromStackRequest,
TemplateInstantiateRequest,
TemplateSaveRequest,
)
from models.user import User
from services import agent_service, audit_service, compose_service, template_service
from services.agent_service import AgentError
router = APIRouter(prefix="/api/templates", tags=["templates"])
def _ip(request: Request) -> str:
return request.client.host if request.client else "unknown"
@router.get("")
def list_templates(
_user: User = Depends(get_current_user),
) -> list[dict]:
return template_service.list_templates()
@router.get("/{template_id}")
def get_template(
template_id: str,
_admin: User = Depends(require_admin),
) -> dict:
"""Full template incl. compose and env. Admin only: "save stack as
template" snapshots the stack's real ``.env`` into the template, so this
can carry live credentials. Only admins can instantiate a template anyway;
the listing above stays open to everyone."""
tpl = template_service.get_template(template_id)
if not tpl:
raise HTTPException(status_code=404, detail="Template not found")
return tpl
@router.post("")
def save_template(
body: TemplateSaveRequest,
request: Request,
session: Session = Depends(get_session),
user: User = Depends(require_admin),
) -> dict:
slug = template_service.save_custom(
body.name, body.compose, body.env, body.description or "", body.tags, body.gpu
)
audit_service.record(
session, user=user.username, action="template.save", target=slug, ip=_ip(request)
)
return {"id": f"custom:{slug}", "name": body.name}
@router.post("/from-stack")
def save_from_stack(
body: TemplateFromStackRequest,
request: Request,
session: Session = Depends(get_session),
user: User = Depends(require_admin),
) -> dict:
if not session.get(Stack, body.stack_id) and not os.path.isdir(
compose_service.stack_dir(body.stack_id)
):
raise HTTPException(status_code=404, detail=f"Stack '{body.stack_id}' not found")
slug = template_service.save_from_stack(body.stack_id, body.name, body.description or "")
audit_service.record(
session, user=user.username, action="template.save",
target=slug, detail=body.stack_id, ip=_ip(request),
)
return {"id": f"custom:{slug}", "name": body.name}
@router.delete("/custom/{slug}")
def delete_template(
slug: str,
request: Request,
session: Session = Depends(get_session),
user: User = Depends(require_admin),
) -> dict:
if not template_service.delete_custom(slug):
raise HTTPException(status_code=404, detail="Custom template not found")
audit_service.record(
session, user=user.username, action="template.delete", target=slug, ip=_ip(request)
)
return {"ok": True}
@router.post("/{template_id}/instantiate", status_code=201)
async def instantiate(
template_id: str,
body: TemplateInstantiateRequest,
request: Request,
session: Session = Depends(get_session),
user: User = Depends(require_admin),
) -> dict:
tpl = template_service.get_template(template_id)
if not tpl:
raise HTTPException(status_code=404, detail="Template not found")
# Remote host: agents don't share our filesystem, so ship compose + env.
if body.agent_id is not None:
agent = session.get(Agent, body.agent_id)
if not agent:
raise HTTPException(status_code=404, detail=f"Agent {body.agent_id} not found")
try:
result = await agent_service.call(
session, agent, "POST", "/agent/stacks",
json={"name": body.name, "yaml": tpl["compose"], "env": tpl["env"] or None},
)
except AgentError as exc:
raise HTTPException(
status_code=exc.status if exc.status >= 400 else 502,
detail={"error": exc.error, "detail": exc.detail},
) from exc
audit_service.record(
session, user=user.username, action="template.instantiate",
target=f"{agent.name}/{result.get('id')}", detail=template_id, ip=_ip(request),
)
return {"id": result.get("id"), "name": body.name, "agent_id": agent.id}
# Local host: copy the whole template folder into a new stack.
stack_id = compose_service.slugify(body.name)
if session.get(Stack, stack_id) or os.path.isdir(compose_service.stack_dir(stack_id)):
raise HTTPException(status_code=409, detail=f"Stack '{stack_id}' already exists")
try:
template_service.copy_into_stack(template_id, stack_id)
except FileExistsError as exc:
raise HTTPException(
status_code=409, detail=f"Stack '{stack_id}' already exists"
) from exc
except FileNotFoundError as exc:
raise HTTPException(status_code=404, detail="Template not found") from exc
stack = Stack(id=stack_id, name=body.name, description=tpl.get("description"))
session.add(stack)
session.commit()
audit_service.record(
session, user=user.username, action="template.instantiate",
target=stack_id, detail=template_id, ip=_ip(request),
)
return {"id": stack_id, "name": body.name, "agent_id": None}