Files
menzeljandClaude Opus 5 a1cd14a1cd
CI / check (push) Successful in 13m2s
CI / build-and-push (push) Successful in 1m53s
Scan images for known vulnerabilities (0.59.0)
The Images page knew what was running and whether it was current. It could not
say whether any of it was exploitable, which is the question people actually
have about a homelab full of images they pulled once and forgot.

Trivy runs as a throwaway container rather than being installed into
StackPilot's image, reusing the helper-container pattern backups already use for
volume contents. Three reasons: a 100 MB security tool and a vulnerability
database that changes weekly have no business in a release artifact, pinning
SCANNER_IMAGE is then a real version control, and the scanner updates itself by
pulling a newer tag. It gets the socket read-only so it inspects images the
daemon already has instead of pulling them again, and a named volume for its
database so the ~50 MB download happens once rather than per scan.

The number the UI leads with is "fixable", not the total. A base image with 300
unfixable low-severity CVEs is not a task and a page that shows 300 in red
teaches people to ignore it; three findings with a fixed version available are
something to do this afternoon. Counts are stored per severity, findings are
sorted worst-first and capped at 200 — every finding is counted, only the list
is trimmed, so the cap can never hide the severity distribution.

The failure mode this had to avoid is a security feature that reads as clean
when it is broken. A scanner that cannot run stores the error and *keeps the
previous counts* rather than resetting to zero, so a transient daemon problem
does not silently turn a bad image green. There is a test for exactly that, and
another for unparseable output. Staleness is handled the same way: the local
image id is recorded with the scan, and pulling the image marks the result stale
instead of presenting yesterday's numbers for today's bytes.

Sweeps are deliberately serial and singly-locked. Scanning is CPU- and IO-heavy,
and running eight at once on a homelab box would starve the very containers the
scan is meant to protect. docker-py is synchronous, so the scan itself goes to a
thread — otherwise a ten-minute scan blocks every other request on the loop.

Reading results is allowed for the read-only role, which the authorization
matrix made me justify in writing: CVE ids and package versions for images whose
tags and compose files that role can already see, and polling them is the
monitoring use case a read-only API token exists for. Running a scan stays
admin-only because it spends real CPU.

20 tests against a report shaped like Trivy's real output, covering the counting,
the fixable number, worst-first ordering, the cap, both failure paths, staleness,
and that two sweeps cannot overlap. Verified end to end through the API as well,
including that a failed rescan keeps its previous counts and shows the error.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-18 01:16:45 +02:00

121 lines
4.0 KiB
Python

"""Application settings, loaded from environment variables."""
from __future__ import annotations
import os
import secrets
import stat
from functools import lru_cache
from typing import Annotated
from pydantic import ValidationInfo, field_validator
from pydantic_settings import BaseSettings, NoDecode, SettingsConfigDict
class Settings(BaseSettings):
model_config = SettingsConfigDict(env_file=".env", extra="ignore")
# Paths
STACKS_DIR: str = "/opt/stackpilot/stacks"
DATA_DIR: str = "/opt/stackpilot/data"
# Security
# Auto-generated and persisted to ${DATA_DIR}/secret_key when left empty.
SECRET_KEY: str = ""
ALGORITHM: str = "HS256"
ACCESS_TOKEN_EXPIRE_MINUTES: int = 60
REFRESH_TOKEN_EXPIRE_DAYS: int = 30
# Update checker
UPDATE_CHECK_INTERVAL_MINUTES: int = 60
# Notifications (webhook URLs)
NOTIFY_WEBHOOKS: Annotated[list[str], NoDecode] = []
# Docker
DOCKER_SOCKET: str = "/var/run/docker.sock"
HOST_PROC_PATH: str = "/host_proc"
# Throwaway image used to read/write named-volume contents during backup.
BACKUP_HELPER_IMAGE: str = "alpine:latest"
# Vulnerability scanner, run as a throwaway container (services/scan_service).
# Pinning a tag here is the supported way to hold a scanner version still.
SCANNER_IMAGE: str = "aquasec/trivy:latest"
# Host browser sandbox roots. Deliberately does NOT contain "/": that entry
# makes _is_allowed() wave through every path, i.e. it switches the sandbox
# off. Add it back explicitly if you really want the whole filesystem.
ALLOWED_BROWSE_ROOTS: Annotated[list[str], NoDecode] = [
"/mnt", "/media", "/srv", "/opt", "/home",
]
HOST_ROOT_PREFIX: str = "" # e.g. "/host_root" when host / is bind-mounted
# CORS
CORS_ORIGINS: Annotated[list[str], NoDecode] = [
"http://localhost:5009", "http://localhost:5173",
]
# Server
PORT: int = 5008
@field_validator("SECRET_KEY", mode="after")
@classmethod
def _ensure_secret(cls, v: str, info: ValidationInfo) -> str:
"""Return the configured key, or a persisted auto-generated one.
Generating a fresh key per process (the old behaviour) silently
invalidated every session on each restart, and would now also make the
encrypted backup-destination credentials undecryptable. So the
generated key is written next to the database instead, mode 0600, and
read back on the next start. An explicitly configured SECRET_KEY always
wins and nothing is written.
"""
if v:
return v
data_dir = info.data.get("DATA_DIR") or "/opt/stackpilot/data"
key_file = os.path.join(data_dir, "secret_key")
try:
with open(key_file, "r", encoding="utf-8") as fh:
if existing := fh.read().strip():
return existing
except OSError:
pass
generated = secrets.token_urlsafe(48)
try:
os.makedirs(data_dir, exist_ok=True)
with open(key_file, "w", encoding="utf-8") as fh:
fh.write(generated + "\n")
os.chmod(key_file, stat.S_IRUSR | stat.S_IWUSR)
except OSError:
# Read-only data dir: fall back to the old per-process behaviour
# rather than refusing to boot. Sessions won't survive a restart.
pass
return generated
@field_validator(
"NOTIFY_WEBHOOKS", "ALLOWED_BROWSE_ROOTS", "CORS_ORIGINS", mode="before"
)
@classmethod
def _split_csv(cls, v):
if isinstance(v, str):
v = v.strip()
if not v:
return []
if v.startswith("["): # tolerate a JSON list too
import json
try:
return json.loads(v)
except json.JSONDecodeError:
pass
return [item.strip() for item in v.split(",") if item.strip()]
return v
@lru_cache
def get_settings() -> Settings:
return Settings()
settings = get_settings()