A pass over every feature against a real Docker daemon, then clicking through the UI as admin and read-only user, on a desktop and a phone. Security. /ws/deploy ran compose up for the read-only role; it is admin-only now. A container's inspect view, a stack's compose file (POSTGRES_PASSWORD: hunter2) and the viewer's .env tab no longer show credentials to that role. Git branch and URL values that git would read as options (-x, ext::) are refused. SFTP host keys are checked: pinned on first use or entered by hand (key line or SHA256 fingerprint), a different key is refused before the password is sent. A backup name from the API can no longer reach outside the destination folder. The file browser refuses to move or rename a browse root, as delete did. Docker lifecycle. Closing the deploy console released the stack lock while compose was still running and logged rc=None as success; deploys and updates are now background runs that hold the lock to the end, report the real exit code and can be re-attached to. Every closed log view left a `compose logs -f` behind. A dozen open tabs exhausted the default thread pool and hung the API; event and exec streams have their own threads. Auto-update and the update endpoint ignored failed pulls. A deleted git stack was recreated and started by the next webhook or poll; deleting a stack now drops its git source, auto-update policy and schedule entries. Deleting no longer walks into mounted shares, is refused while a backup runs, and removes the containers even when the compose file is broken. Stack folders compose has to normalise (Nextcloud -> nextcloud) work everywhere and group correctly on the volumes, networks and images pages. Detection. Host port conflicts read the container's own network namespace; /proc/1/net is read instead. Images referenced as docker.io/… were never update-checked; local builds no longer report "needs credentials". NVIDIA GPUs are read from the driver's procfs. The backup dialog's "path mismatch" warning came from mountinfo's filesystem-relative root and fired for any stacks folder on its own disk, ZFS dataset or btrfs subvolume; the host path now comes from Docker's mounts. Backups and destinations. The download ignored the folder/volume selection (axios sent binds[]). Restoring under a new name kept the old one. A report header past nginx's buffer turned a good backup into a 502. SFTP/S3 errors were bare 500s and "Test" did not try to write. A destination used by a schedule could be deleted. Backup file names are in the schedule's or the browser's time zone instead of UTC. Editor and converter. `docker run` conversion produced invalid compose for --network host, named volumes and -dit; --gpus and --mount were dropped; a multi-line command pasted into the one-line field became `image: ' '` (now a textarea, and flattened continuations are read). Validation failed for env_file stacks. The editor overwrote unsaved edits on every container event, lost them on a stray click (now asks), threw when closing the diff, and its helper panel listed the starter service "app" for every existing stack. Monaco is bundled instead of loaded from jsdelivr, so the editor works offline (and monaco-editor 0.57 drops the dompurify advisory; axios and react-router updated). UI. All times were two hours off: offset-less UTC from SQLite was read as local time, and "next run" always said "just now". A token refresh mid-session duplicated deploys, reset terminals and doubled logs. A backend restart (update, self-update) signed everyone out on reload; the page now waits for it. The editor was unusable on a phone, tables and tabs overflowed, dialog text was black on the dark theme, and the file browser opened on an error with the default roots. Read-only users get "Admin only" pages instead of 403s; in-use networks offer no delete; "Scan all" covers StackPilot's own stacks only and runs in the background instead of timing out at 600s. Deployment. nginx passes the port in Host (the OIDC redirect URI lost :5009) and keeps an outer proxy's X-Forwarded-Proto. The frontend waits for a healthy backend (healthcheck probes every 2s while starting). The frontend image builds with npm ci. Secrets are 0644 in a 0700 folder so non-root containers can read them; existing files are fixed at startup. The test suite no longer starts real containers on a host with Docker. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Fx7gcuy8d6nPd95g43rGHu
157 lines
5.3 KiB
Python
157 lines
5.3 KiB
Python
"""Outbound notification webhooks.
|
|
|
|
Webhooks are configured two ways:
|
|
* DB-managed (the ``Webhook`` table) — per-webhook type + event subscriptions,
|
|
editable from the Settings page.
|
|
* Env ``NOTIFY_WEBHOOKS`` — a comma-separated list of generic JSON endpoints
|
|
that receive every event (kept for backward compatibility / GitOps setups).
|
|
|
|
Supported types: ntfy, discord, slack, gotify, generic (JSON POST).
|
|
All delivery is best-effort: failures are logged, never raised to the caller.
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
import base64
|
|
import logging
|
|
from typing import Optional
|
|
|
|
import httpx
|
|
from sqlmodel import Session, select
|
|
|
|
from config import settings as env_settings
|
|
from database import engine
|
|
from models.setting import Webhook
|
|
|
|
logger = logging.getLogger("stackpilot.notify")
|
|
|
|
_TIMEOUT = 10.0
|
|
|
|
|
|
# --------------------------------------------------------------------------- #
|
|
# Payload formatting per webhook type
|
|
# --------------------------------------------------------------------------- #
|
|
|
|
|
|
def _build_request(wtype: str, url: str, event: str, title: str, message: str):
|
|
"""Return (method-kwargs) for httpx.post for the given webhook type."""
|
|
if wtype == "ntfy":
|
|
return {
|
|
"url": url,
|
|
"content": message.encode("utf-8"),
|
|
"headers": {"Title": _header_value(title), "Tags": _ntfy_tag(event)},
|
|
}
|
|
if wtype == "discord":
|
|
return {"url": url, "json": {"content": f"**{title}**\n{message}"}}
|
|
if wtype == "slack":
|
|
return {"url": url, "json": {"text": f"*{title}*\n{message}"}}
|
|
if wtype == "gotify":
|
|
priority = 8 if event in _URGENT_EVENTS else 5
|
|
return {
|
|
"url": url,
|
|
"json": {"title": title, "message": message, "priority": priority},
|
|
}
|
|
# generic
|
|
return {
|
|
"url": url,
|
|
"json": {"event": event, "title": title, "message": message},
|
|
}
|
|
|
|
|
|
_URGENT_EVENTS = {"stack_error", "pull_failed", "backup_failed"}
|
|
|
|
|
|
def _header_value(text: str) -> str:
|
|
"""A header value httpx can send, keeping non-ASCII readable.
|
|
|
|
HTTP headers are ASCII; httpx raises UnicodeEncodeError on anything else,
|
|
so a title with an umlaut or a dash ("Backup to NAS Büro failed") never
|
|
reached ntfy at all. RFC 2047 encoded-words are what ntfy decodes.
|
|
"""
|
|
try:
|
|
text.encode("ascii")
|
|
return text
|
|
except UnicodeEncodeError:
|
|
encoded = base64.b64encode(text.encode("utf-8")).decode("ascii")
|
|
return f"=?UTF-8?B?{encoded}?="
|
|
|
|
|
|
def _ntfy_tag(event: str) -> str:
|
|
return {
|
|
"update_available": "arrow_up",
|
|
"stack_start": "white_check_mark",
|
|
"stack_stop": "stop_button",
|
|
"stack_error": "rotating_light",
|
|
"pull_failed": "warning",
|
|
"backup_failed": "floppy_disk",
|
|
"stack_auto_updated": "arrows_counterclockwise",
|
|
}.get(event, "bell")
|
|
|
|
|
|
async def _deliver(client: httpx.AsyncClient, wtype: str, url: str, event: str, title: str, message: str) -> bool:
|
|
try:
|
|
kwargs = _build_request(wtype, url, event, title, message)
|
|
target = kwargs.pop("url")
|
|
resp = await client.post(target, timeout=_TIMEOUT, **kwargs)
|
|
resp.raise_for_status()
|
|
return True
|
|
except Exception as exc: # noqa: BLE001 - one bad webhook must not stop the rest
|
|
# Not just httpx.HTTPError: an invalid URL or an unencodable header
|
|
# raised past this and aborted delivery to every webhook after it.
|
|
logger.warning("Webhook delivery failed (%s): %s", wtype, exc)
|
|
return False
|
|
|
|
|
|
# --------------------------------------------------------------------------- #
|
|
# Public API
|
|
# --------------------------------------------------------------------------- #
|
|
|
|
|
|
def _targets_for_event(session: Session, event: str) -> list[tuple[str, str]]:
|
|
"""Return [(type, url)] of all destinations subscribed to ``event``."""
|
|
targets: list[tuple[str, str]] = []
|
|
for wh in session.exec(select(Webhook)).all():
|
|
if not wh.enabled:
|
|
continue
|
|
subscribed = [e.strip() for e in (wh.events or "").split(",") if e.strip()]
|
|
if event in subscribed:
|
|
targets.append((wh.type, wh.url))
|
|
# Env-configured generic endpoints receive everything.
|
|
for url in env_settings.NOTIFY_WEBHOOKS:
|
|
targets.append(("generic", url))
|
|
return targets
|
|
|
|
|
|
async def notify(
|
|
event: str,
|
|
title: str,
|
|
message: str,
|
|
session: Optional[Session] = None,
|
|
) -> int:
|
|
"""Fan out ``event`` to all subscribed webhooks. Returns delivered count."""
|
|
if session is None:
|
|
with Session(engine) as own:
|
|
return await notify(event, title, message, own)
|
|
|
|
targets = _targets_for_event(session, event)
|
|
if not targets:
|
|
return 0
|
|
delivered = 0
|
|
async with httpx.AsyncClient(follow_redirects=True) as client:
|
|
for wtype, url in targets:
|
|
if await _deliver(client, wtype, url, event, title, message):
|
|
delivered += 1
|
|
return delivered
|
|
|
|
|
|
async def test_webhook(wtype: str, url: str) -> bool:
|
|
"""Send a one-off test notification to a single destination."""
|
|
async with httpx.AsyncClient(follow_redirects=True) as client:
|
|
return await _deliver(
|
|
client,
|
|
wtype,
|
|
url,
|
|
"update_available",
|
|
"StackPilot test notification",
|
|
"If you can read this, your webhook is configured correctly. 🚀",
|
|
)
|