Compare commits
2 commits
main
...
feature/li
| Author | SHA1 | Date | |
|---|---|---|---|
| 2db5617426 | |||
| e09d545b71 |
9 changed files with 12 additions and 2689 deletions
1
.gitignore
vendored
1
.gitignore
vendored
|
|
@ -3,4 +3,3 @@
|
||||||
vault-sync.log
|
vault-sync.log
|
||||||
__pycache__/
|
__pycache__/
|
||||||
*.pyc
|
*.pyc
|
||||||
state/
|
|
||||||
|
|
|
||||||
|
|
@ -45,7 +45,6 @@ Known secret response fields such as Dockhand's `hawserToken` and `webhookSecret
|
||||||
| `/docker/inspect/{host}/{container}` | GET | Sanitized image, runtime, resources, mounts and state |
|
| `/docker/inspect/{host}/{container}` | GET | Sanitized image, runtime, resources, mounts and state |
|
||||||
| `/docker/restart/{host}/{container}` | POST | Restart container; supports `dry_run=true` |
|
| `/docker/restart/{host}/{container}` | POST | Restart container; supports `dry_run=true` |
|
||||||
| `/config/reload` | POST | Reload YAML configuration and credential cache |
|
| `/config/reload` | POST | Reload YAML configuration and credential cache |
|
||||||
| `/media/verify` | POST | ffprobe duration check on a NAS media file to catch truncated Sonarr/Radarr imports; flags `suspect` if deviation from `expected_minutes` exceeds `tolerance_pct` |
|
|
||||||
|
|
||||||
## VM lifecycle and inventory
|
## VM lifecycle and inventory
|
||||||
|
|
||||||
|
|
@ -98,14 +97,6 @@ Integration Compose definition: `tests/compose.integration.yaml` (binds only to
|
||||||
|
|
||||||
## Changelog
|
## Changelog
|
||||||
|
|
||||||
### 2.4.8 — 17.09.2026
|
|
||||||
|
|
||||||
- Fixed `POST /media/verify` false-positive rejection: filenames containing a legitimate apostrophe (e.g. "La'An" in a Star Trek episode title) were blocked as "unsafe characters". Replaced the naive single-quote wrapping + apostrophe blocklist with proper `shlex.quote()` escaping for the remote ffprobe command; only newline/NUL byte injection is still rejected.
|
|
||||||
|
|
||||||
### 2.4.7 — 17.09.2026
|
|
||||||
|
|
||||||
- Added `POST /media/verify`: probes a media file's real duration via `ffprobe` (running inside the existing `bazarrUHD` container on `arrapps`, which already mounts `/data` and ships ffmpeg — no new service needed) and flags it as `suspect` when it deviates from an `expected_minutes` value beyond `tolerance_pct`. Catches truncated Sonarr/Radarr imports (e.g. a re-grab that lands as 1.8 GB instead of the expected 8 GB for a UHD episode) after the file is already on the NAS.
|
|
||||||
|
|
||||||
### 2.3.2 — 22.07.2026
|
### 2.3.2 — 22.07.2026
|
||||||
|
|
||||||
- Make Vaultwarden refresh durable: persistent named cache volume, protected runtime credentials, automatic API-key re-login and atomic cache writes.
|
- Make Vaultwarden refresh durable: persistent named cache volume, protected runtime credentials, automatic API-key re-login and atomic cache writes.
|
||||||
|
|
|
||||||
|
|
@ -105,10 +105,6 @@ services:
|
||||||
health_path: "/"
|
health_path: "/"
|
||||||
timeout: 300
|
timeout: 300
|
||||||
|
|
||||||
backup:
|
|
||||||
# guck-vps contains Git-managed edge configuration and has no Borgmatic installation.
|
|
||||||
exempt_hosts: [guck-vps]
|
|
||||||
|
|
||||||
# VM lifecycle settings
|
# VM lifecycle settings
|
||||||
vm:
|
vm:
|
||||||
automation_host: "sascha@10.5.85.5"
|
automation_host: "sascha@10.5.85.5"
|
||||||
|
|
|
||||||
|
|
@ -11,13 +11,10 @@ services:
|
||||||
- /home/sascha/.ssh:/root/.ssh:ro
|
- /home/sascha/.ssh:/root/.ssh:ro
|
||||||
- ./butler.yaml:/data/butler.yaml:ro
|
- ./butler.yaml:/data/butler.yaml:ro
|
||||||
- ./app.py:/app/app.py:ro
|
- ./app.py:/app/app.py:ro
|
||||||
- ./ui.html:/app/ui.html:ro
|
|
||||||
- ./state:/data/state
|
|
||||||
environment:
|
environment:
|
||||||
- API_KEY_DIR=/data/api
|
- API_KEY_DIR=/data/api
|
||||||
- VAULT_CACHE_DIR=/data/vault-cache
|
- VAULT_CACHE_DIR=/data/vault-cache
|
||||||
- BUTLER_TOKEN=${BUTLER_TOKEN}
|
- BUTLER_TOKEN=${BUTLER_TOKEN}
|
||||||
- AUDIT_DB_PATH=/data/state/audit.sqlite3
|
|
||||||
|
|
||||||
volumes:
|
volumes:
|
||||||
vault-cache:
|
vault-cache:
|
||||||
|
|
|
||||||
|
|
@ -1,7 +1,6 @@
|
||||||
import os
|
import os
|
||||||
import asyncio
|
import asyncio
|
||||||
import json
|
import json
|
||||||
import shlex
|
|
||||||
import time
|
import time
|
||||||
from datetime import datetime, timedelta, timezone
|
from datetime import datetime, timedelta, timezone
|
||||||
|
|
||||||
|
|
@ -44,431 +43,7 @@ def test_health_exposes_current_version():
|
||||||
with TestClient(app.app) as client:
|
with TestClient(app.app) as client:
|
||||||
response = client.get("/health")
|
response = client.get("/health")
|
||||||
assert response.status_code == 200
|
assert response.status_code == 200
|
||||||
assert response.json()["version"] == app.VERSION == "2.4.1"
|
assert response.json()["version"] == app.VERSION == "2.3.5"
|
||||||
|
|
||||||
|
|
||||||
def test_media_handoff_proxies_strict_category_contract(monkeypatch):
|
|
||||||
captured = {}
|
|
||||||
|
|
||||||
class FakeResponse:
|
|
||||||
status_code = 200
|
|
||||||
|
|
||||||
def json(self):
|
|
||||||
return {"ok": True, "jobId": "test-job-1234", "state": "registered"}
|
|
||||||
|
|
||||||
class FakeClient:
|
|
||||||
def __init__(self, **kwargs):
|
|
||||||
captured["client"] = kwargs
|
|
||||||
|
|
||||||
async def __aenter__(self):
|
|
||||||
return self
|
|
||||||
|
|
||||||
async def __aexit__(self, *_args):
|
|
||||||
return None
|
|
||||||
|
|
||||||
async def post(self, url, json, headers):
|
|
||||||
captured.update(url=url, json=json, headers=headers)
|
|
||||||
return FakeResponse()
|
|
||||||
|
|
||||||
monkeypatch.setattr(app.httpx, "AsyncClient", FakeClient)
|
|
||||||
with TestClient(app.app) as client:
|
|
||||||
monkeypatch.setattr(app, "SERVICES", {"n8n": {"url": "http://n8n:5678", "auth": "n8n"}})
|
|
||||||
response = client.post(
|
|
||||||
"/media/handoff",
|
|
||||||
headers={"Authorization": "Bearer test-token"},
|
|
||||||
json={
|
|
||||||
"action": "start",
|
|
||||||
"category": "serien4k",
|
|
||||||
"directory": "/usenet/complete/serien4k/Show.S01E01",
|
|
||||||
"release": "Show.S01E01-GRP",
|
|
||||||
"cleanName": "Show S01E01",
|
|
||||||
"expectedFiles": 2,
|
|
||||||
},
|
|
||||||
)
|
|
||||||
assert response.status_code == 200
|
|
||||||
assert response.json()["state"] == "registered"
|
|
||||||
assert captured["url"] == "http://n8n:5678/webhook/media-handoff"
|
|
||||||
assert captured["json"]["category"] == "serien4k"
|
|
||||||
assert captured["json"]["expectedFiles"] == 2
|
|
||||||
|
|
||||||
|
|
||||||
def test_media_handoff_rejects_untrusted_caller_before_proxy(monkeypatch):
|
|
||||||
monkeypatch.setattr(app.httpx, "AsyncClient", lambda **_kwargs: (_ for _ in ()).throw(AssertionError("must not proxy")))
|
|
||||||
with TestClient(app.app) as client:
|
|
||||||
response = client.post(
|
|
||||||
"/media/handoff",
|
|
||||||
json={"action": "status", "jobId": "test-job-1234"},
|
|
||||||
)
|
|
||||||
assert response.status_code == 403
|
|
||||||
|
|
||||||
|
|
||||||
def test_media_handoff_rejects_wrong_category_path(monkeypatch):
|
|
||||||
monkeypatch.setattr(app.httpx, "AsyncClient", lambda **_kwargs: (_ for _ in ()).throw(AssertionError("must not proxy")))
|
|
||||||
with TestClient(app.app) as client:
|
|
||||||
response = client.post(
|
|
||||||
"/media/handoff",
|
|
||||||
headers={"Authorization": "Bearer test-token"},
|
|
||||||
json={
|
|
||||||
"action": "start",
|
|
||||||
"category": "video4k",
|
|
||||||
"directory": "/usenet/complete/serien4k/Wrong",
|
|
||||||
"release": "Wrong",
|
|
||||||
},
|
|
||||||
)
|
|
||||||
assert response.status_code == 422
|
|
||||||
|
|
||||||
|
|
||||||
def test_media_handoff_accepts_english_arr_categories(monkeypatch):
|
|
||||||
"""serienen/videoen muessen durchgehen (sonarrEN 8991 / radarrEN 7880).
|
|
||||||
|
|
||||||
16.09.2026: fehlten in allowed_categories -> HTTP 422 -> movetdarr.sh
|
|
||||||
brach mit "n8n-Handoff konnte nicht registriert werden" ab und liess
|
|
||||||
Mutiny.2026 x2 tagelang in /usenet/complete/videoen liegen.
|
|
||||||
"""
|
|
||||||
seen = []
|
|
||||||
|
|
||||||
class FakeResponse:
|
|
||||||
status_code = 200
|
|
||||||
|
|
||||||
def json(self):
|
|
||||||
return {"ok": True, "jobId": "test-job-5678", "state": "registered"}
|
|
||||||
|
|
||||||
class FakeClient:
|
|
||||||
def __init__(self, **_kwargs):
|
|
||||||
pass
|
|
||||||
|
|
||||||
async def __aenter__(self):
|
|
||||||
return self
|
|
||||||
|
|
||||||
async def __aexit__(self, *_args):
|
|
||||||
return None
|
|
||||||
|
|
||||||
async def post(self, url, json, headers):
|
|
||||||
seen.append(json)
|
|
||||||
return FakeResponse()
|
|
||||||
|
|
||||||
monkeypatch.setattr(app.httpx, "AsyncClient", FakeClient)
|
|
||||||
with TestClient(app.app) as client:
|
|
||||||
monkeypatch.setattr(app, "SERVICES", {"n8n": {"url": "http://n8n:5678", "auth": "n8n"}})
|
|
||||||
for category in ("serienen", "videoen"):
|
|
||||||
response = client.post(
|
|
||||||
"/media/handoff",
|
|
||||||
headers={"Authorization": "Bearer test-token"},
|
|
||||||
json={
|
|
||||||
"action": "start",
|
|
||||||
"category": category,
|
|
||||||
"directory": f"/usenet/complete/{category}/Release.2026",
|
|
||||||
"release": "Release.2026-GRP",
|
|
||||||
"cleanName": "Release 2026",
|
|
||||||
"expectedFiles": 1,
|
|
||||||
},
|
|
||||||
)
|
|
||||||
assert response.status_code == 200, (category, response.text)
|
|
||||||
assert response.json()["state"] == "registered", category
|
|
||||||
|
|
||||||
assert [item["category"] for item in seen] == ["serienen", "videoen"]
|
|
||||||
|
|
||||||
|
|
||||||
def test_media_handoff_still_rejects_unknown_category(monkeypatch):
|
|
||||||
"""Fail-closed bleibt: eine frei erfundene Kategorie wird nicht geproxyt."""
|
|
||||||
monkeypatch.setattr(
|
|
||||||
app.httpx,
|
|
||||||
"AsyncClient",
|
|
||||||
lambda **_kwargs: (_ for _ in ()).throw(AssertionError("must not proxy")),
|
|
||||||
)
|
|
||||||
with TestClient(app.app) as client:
|
|
||||||
response = client.post(
|
|
||||||
"/media/handoff",
|
|
||||||
headers={"Authorization": "Bearer test-token"},
|
|
||||||
json={
|
|
||||||
"action": "start",
|
|
||||||
"category": "hoerbuecher",
|
|
||||||
"directory": "/usenet/complete/hoerbuecher/Buch",
|
|
||||||
"release": "Buch",
|
|
||||||
},
|
|
||||||
)
|
|
||||||
assert response.status_code == 422
|
|
||||||
|
|
||||||
|
|
||||||
def test_media_handoff_english_category_path_must_match(monkeypatch):
|
|
||||||
"""Pfadpruefung gilt auch fuer die neuen Kategorien."""
|
|
||||||
monkeypatch.setattr(
|
|
||||||
app.httpx,
|
|
||||||
"AsyncClient",
|
|
||||||
lambda **_kwargs: (_ for _ in ()).throw(AssertionError("must not proxy")),
|
|
||||||
)
|
|
||||||
with TestClient(app.app) as client:
|
|
||||||
response = client.post(
|
|
||||||
"/media/handoff",
|
|
||||||
headers={"Authorization": "Bearer test-token"},
|
|
||||||
json={
|
|
||||||
"action": "start",
|
|
||||||
"category": "videoen",
|
|
||||||
"directory": "/usenet/complete/video4k/Wrong",
|
|
||||||
"release": "Wrong",
|
|
||||||
},
|
|
||||||
)
|
|
||||||
assert response.status_code == 422
|
|
||||||
|
|
||||||
|
|
||||||
def test_paperless_import_queues_pdf_through_butler(monkeypatch):
|
|
||||||
captured = {}
|
|
||||||
|
|
||||||
def fake_upload(host, command, payload, timeout):
|
|
||||||
captured.update(host=host, command=command, payload=payload, timeout=timeout)
|
|
||||||
return 0, "", ""
|
|
||||||
|
|
||||||
monkeypatch.setattr(app, "_ssh_bytes", fake_upload)
|
|
||||||
pdf = b"%PDF-1.7\nvalid-test-payload"
|
|
||||||
with TestClient(app.app) as client:
|
|
||||||
response = client.post(
|
|
||||||
"/paperless/import?filename=Hausordnung%20Stand%2009.05.2022.pdf",
|
|
||||||
content=pdf,
|
|
||||||
headers={"Authorization": "Bearer test-token", "Content-Type": "application/pdf"},
|
|
||||||
)
|
|
||||||
assert response.status_code == 200
|
|
||||||
body = response.json()
|
|
||||||
assert body["status"] == "queued"
|
|
||||||
assert body["filename"].startswith("Hausordnung_Stand_09.05.2022-")
|
|
||||||
assert captured["host"] == app.PAPERLESS_GATEWAY
|
|
||||||
assert app.PAPERLESS_SSH in captured["command"]
|
|
||||||
assert captured["payload"] == pdf
|
|
||||||
assert app.PAPERLESS_CONSUME_DIR in captured["command"]
|
|
||||||
|
|
||||||
|
|
||||||
def test_paperless_import_rejects_non_pdf(monkeypatch):
|
|
||||||
monkeypatch.setattr(app, "_ssh_bytes", lambda *args: (_ for _ in ()).throw(AssertionError("must not upload")))
|
|
||||||
with TestClient(app.app) as client:
|
|
||||||
response = client.post(
|
|
||||||
"/paperless/import?filename=bad.pdf",
|
|
||||||
content=b"not a pdf",
|
|
||||||
headers={"Authorization": "Bearer test-token"},
|
|
||||||
)
|
|
||||||
assert response.status_code == 400
|
|
||||||
|
|
||||||
|
|
||||||
def test_ui_serves_self_contained_operator_console():
|
|
||||||
with TestClient(app.app) as client:
|
|
||||||
response = client.get("/ui")
|
|
||||||
assert response.status_code == 200
|
|
||||||
assert "Pfannkuchen Butler" in response.text
|
|
||||||
assert 'id="operations-grid"' in response.text
|
|
||||||
assert 'id="doctor-form"' in response.text
|
|
||||||
assert 'id="preflight-form"' in response.text
|
|
||||||
assert 'id="sharing-form"' in response.text
|
|
||||||
assert 'id="sharing-events"' in response.text
|
|
||||||
assert "/emby/account-sharing" in response.text
|
|
||||||
assert 'id="login"' not in response.text
|
|
||||||
assert "Butler-Token" not in response.text
|
|
||||||
assert "localStorage" not in response.text
|
|
||||||
|
|
||||||
|
|
||||||
def test_ui_asset_is_mounted_read_only_in_compose():
|
|
||||||
from pathlib import Path
|
|
||||||
import yaml
|
|
||||||
compose = yaml.safe_load(Path(app.__file__).with_name("compose.yaml").read_text(encoding="utf-8"))
|
|
||||||
mounts = compose["services"]["homelab-butler"]["volumes"]
|
|
||||||
assert "./ui.html:/app/ui.html:ro" in mounts
|
|
||||||
|
|
||||||
|
|
||||||
def test_ui_session_login_uses_httponly_cookie_and_csrf():
|
|
||||||
app._ui_sessions.clear()
|
|
||||||
with TestClient(app.app) as client:
|
|
||||||
denied = client.post("/ui/login", json={"token": "wrong"})
|
|
||||||
assert denied.status_code == 401
|
|
||||||
|
|
||||||
login = client.post("/ui/login", json={"token": "test-token"})
|
|
||||||
assert login.status_code == 200
|
|
||||||
assert "HttpOnly" in login.headers.get("set-cookie", "")
|
|
||||||
csrf = client.cookies.get("butler_csrf")
|
|
||||||
assert csrf
|
|
||||||
|
|
||||||
capabilities = client.get("/capabilities")
|
|
||||||
assert capabilities.status_code == 200
|
|
||||||
|
|
||||||
blocked = client.post("/config/reload")
|
|
||||||
assert blocked.status_code == 403
|
|
||||||
allowed = client.post("/config/reload", headers={"X-CSRF-Token": csrf})
|
|
||||||
assert allowed.status_code == 200
|
|
||||||
|
|
||||||
|
|
||||||
def test_ui_anonymous_session_is_automatic_and_strictly_read_only():
|
|
||||||
app._ui_sessions.clear()
|
|
||||||
with TestClient(app.app) as client:
|
|
||||||
session = client.get("/ui/session")
|
|
||||||
assert session.status_code == 200
|
|
||||||
assert session.json()["authenticated"] is True
|
|
||||||
assert session.json()["read_only"] is True
|
|
||||||
assert "HttpOnly" in session.headers.get("set-cookie", "")
|
|
||||||
|
|
||||||
capabilities = client.get("/capabilities")
|
|
||||||
assert capabilities.status_code == 200
|
|
||||||
|
|
||||||
csrf = client.cookies.get("butler_csrf")
|
|
||||||
mutation = client.post("/config/reload", headers={"X-CSRF-Token": csrf})
|
|
||||||
assert mutation.status_code == 403
|
|
||||||
assert "read-only" in mutation.json()["detail"].lower()
|
|
||||||
|
|
||||||
|
|
||||||
def test_emby_network_identity_normalizes_ipv4_and_ipv6_privacy_addresses():
|
|
||||||
ipv4 = app._emby_network_identity("203.0.113.9:443")
|
|
||||||
assert ipv4["ip"] == "203.0.113.9"
|
|
||||||
assert ipv4["network"] == "203.0.113.9/32"
|
|
||||||
assert ipv4["identity"] == "203.0.113.9/32"
|
|
||||||
|
|
||||||
first = app._emby_network_identity("2003:abcd:1234:5678::1")
|
|
||||||
privacy_peer = app._emby_network_identity("[2003:abcd:1234:5678:ffff::99]:443")
|
|
||||||
sibling_subnet = app._emby_network_identity("2003:abcd:1234:9999::1")
|
|
||||||
assert first["network"] == privacy_peer["network"] == "2003:abcd:1234:5678::/64"
|
|
||||||
assert first["parent"] == sibling_subnet["parent"] == "2003:abcd:1234::/48"
|
|
||||||
assert first["identity"] == sibling_subnet["identity"] == "2003:abcd:1234::/48"
|
|
||||||
|
|
||||||
|
|
||||||
def test_emby_sharing_flags_concurrent_distinct_networks_but_not_sibling_ipv6_subnets():
|
|
||||||
def series(endpoint, values, city):
|
|
||||||
return {
|
|
||||||
"metric": {
|
|
||||||
"job": "emby-sascha", "username": "Alice", "remoteEndPoint": endpoint,
|
|
||||||
"city": city, "region": "Test", "countryCode": "DE",
|
|
||||||
"latitude": "48.1", "longitude": "11.5",
|
|
||||||
},
|
|
||||||
"values": [[timestamp, "1"] for timestamp in values],
|
|
||||||
}
|
|
||||||
|
|
||||||
payload = [
|
|
||||||
series("2606:4700:1234:1000::1", [100, 160, 220, 280, 340, 400], "Home"),
|
|
||||||
series("2606:4700:1234:2000::2", [100, 160, 220, 280, 340, 400], "Home privacy subnet"),
|
|
||||||
series("2001:4860:9999:1000::1", [100, 160, 220, 280, 340, 400], "Away"),
|
|
||||||
]
|
|
||||||
|
|
||||||
result = app._analyze_emby_sharing(payload, step_seconds=60)
|
|
||||||
|
|
||||||
assert result["summary"]["concurrent_events"] == 1
|
|
||||||
event = result["events"][0]
|
|
||||||
assert event["type"] == "concurrent_networks"
|
|
||||||
assert event["username"] == "Alice"
|
|
||||||
assert len(event["evidence"]) == 2
|
|
||||||
assert {item["identity"] for item in event["evidence"]} == {
|
|
||||||
"2606:4700:1234::/48", "2001:4860:9999::/48"
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
def test_emby_sharing_ignores_short_overlap_inside_prometheus_staleness_window():
|
|
||||||
def series(endpoint):
|
|
||||||
return {"metric": {"job": "emby-sascha", "username": "Alice", "remoteEndPoint": endpoint,
|
|
||||||
"city": "Munich", "region": "Bavaria", "countryCode": "DE",
|
|
||||||
"latitude": "48.1", "longitude": "11.5"},
|
|
||||||
"values": [[100, "1"], [160, "1"]]}
|
|
||||||
|
|
||||||
result = app._analyze_emby_sharing([series("8.8.8.8"), series("1.1.1.1")], step_seconds=60)
|
|
||||||
|
|
||||||
assert result["summary"]["concurrent_events"] == 0
|
|
||||||
|
|
||||||
|
|
||||||
def test_emby_sharing_flags_geographically_impossible_network_change():
|
|
||||||
payload = [
|
|
||||||
{
|
|
||||||
"metric": {"job": "emby-chris", "username": "Bob", "remoteEndPoint": "8.8.8.8",
|
|
||||||
"city": "Berlin", "region": "Berlin", "countryCode": "DE",
|
|
||||||
"latitude": "52.5200", "longitude": "13.4050"},
|
|
||||||
"values": [[100, "1"], [160, "1"]],
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"metric": {"job": "emby-chris", "username": "Bob", "remoteEndPoint": "1.1.1.1",
|
|
||||||
"city": "New York", "region": "New York", "countryCode": "US",
|
|
||||||
"latitude": "40.7128", "longitude": "-74.0060"},
|
|
||||||
"values": [[400, "1"], [460, "1"]],
|
|
||||||
},
|
|
||||||
]
|
|
||||||
|
|
||||||
result = app._analyze_emby_sharing(payload, step_seconds=60)
|
|
||||||
|
|
||||||
assert result["summary"]["concurrent_events"] == 0
|
|
||||||
assert result["summary"]["impossible_travel_events"] == 1
|
|
||||||
event = result["events"][0]
|
|
||||||
assert event["type"] == "impossible_travel"
|
|
||||||
assert event["distance_km"] > 6000
|
|
||||||
assert event["required_speed_kmh"] > 1000
|
|
||||||
|
|
||||||
|
|
||||||
def test_emby_account_sharing_endpoint_is_read_only_and_filterable(monkeypatch):
|
|
||||||
async def history(days, server):
|
|
||||||
assert days == 7
|
|
||||||
assert server == "all"
|
|
||||||
return ([{
|
|
||||||
"metric": {"job": "emby-sascha", "username": "Alice", "remoteEndPoint": "8.8.8.8",
|
|
||||||
"city": "Munich", "region": "Bavaria", "countryCode": "DE",
|
|
||||||
"latitude": "48.1", "longitude": "11.5"},
|
|
||||||
"values": [[100, "1"], [160, "1"]],
|
|
||||||
}], 60)
|
|
||||||
|
|
||||||
monkeypatch.setattr(app, "_fetch_emby_session_history", history)
|
|
||||||
with TestClient(app.app) as client:
|
|
||||||
response = client.get(
|
|
||||||
"/emby/account-sharing?days=7&username=alice",
|
|
||||||
headers={"Authorization": "Bearer test-token"},
|
|
||||||
)
|
|
||||||
|
|
||||||
assert response.status_code == 200
|
|
||||||
payload = response.json()
|
|
||||||
assert payload["policy"]["mode"] == "conservative"
|
|
||||||
assert payload["policy"]["ipv6_detection_identity"] == "/48"
|
|
||||||
assert payload["summary"]["users_analyzed"] == 1
|
|
||||||
assert payload["users"][0]["username"] == "Alice"
|
|
||||||
|
|
||||||
|
|
||||||
def test_emby_history_step_stays_below_prometheus_resolution_limit():
|
|
||||||
assert app._emby_history_step(7) == 60
|
|
||||||
for days in (7, 30, 90):
|
|
||||||
step = app._emby_history_step(days)
|
|
||||||
assert step % 60 == 0
|
|
||||||
assert (days * 86400) / step <= 10_500
|
|
||||||
|
|
||||||
|
|
||||||
def test_emby_history_fetch_chunks_90_days_and_merges_equal_series(monkeypatch):
|
|
||||||
calls = []
|
|
||||||
|
|
||||||
class FakeResponse:
|
|
||||||
def __init__(self, params):
|
|
||||||
self.params = params
|
|
||||||
|
|
||||||
def raise_for_status(self):
|
|
||||||
return None
|
|
||||||
|
|
||||||
def json(self):
|
|
||||||
start = self.params["start"]
|
|
||||||
end = self.params["end"]
|
|
||||||
return {"status": "success", "data": {"result": [{
|
|
||||||
"metric": {"job": "emby-sascha", "username": "Alice", "remoteEndPoint": "8.8.8.8"},
|
|
||||||
"values": [[start, "1"], [end, "1"]],
|
|
||||||
}]}}
|
|
||||||
|
|
||||||
class FakeClient:
|
|
||||||
def __init__(self, **_kwargs):
|
|
||||||
pass
|
|
||||||
|
|
||||||
async def __aenter__(self):
|
|
||||||
return self
|
|
||||||
|
|
||||||
async def __aexit__(self, *_args):
|
|
||||||
return None
|
|
||||||
|
|
||||||
async def get(self, _url, params, headers, cookies):
|
|
||||||
calls.append(params)
|
|
||||||
return FakeResponse(params)
|
|
||||||
|
|
||||||
monkeypatch.setattr(app, "SERVICES", {"grafana": {"url": "http://grafana", "auth": "none"}})
|
|
||||||
monkeypatch.setattr(app.httpx, "AsyncClient", FakeClient)
|
|
||||||
monkeypatch.setattr(app.time, "time", lambda: 10_000_000)
|
|
||||||
|
|
||||||
series, step = asyncio.run(app._fetch_emby_session_history(90, "all"))
|
|
||||||
|
|
||||||
assert len(calls) == 3
|
|
||||||
assert all(call["end"] - call["start"] <= 30 * 86400 for call in calls)
|
|
||||||
assert step == 780
|
|
||||||
assert len(series) == 1
|
|
||||||
timestamps = [value[0] for value in series[0]["values"]]
|
|
||||||
assert timestamps == sorted(set(timestamps))
|
|
||||||
|
|
||||||
|
|
||||||
def test_capabilities_is_live_machine_readable_safety_map():
|
def test_capabilities_is_live_machine_readable_safety_map():
|
||||||
|
|
@ -486,9 +61,6 @@ def test_capabilities_is_live_machine_readable_safety_map():
|
||||||
assert removal["mode"] == "mutation"
|
assert removal["mode"] == "mutation"
|
||||||
assert removal["dry_run"] is True
|
assert removal["dry_run"] is True
|
||||||
assert removal["critical"] is True
|
assert removal["critical"] is True
|
||||||
tunnel = by_operation[("POST", "/network/media-tunnel/sascha")]
|
|
||||||
assert tunnel["dry_run"] is True
|
|
||||||
assert tunnel["critical"] is True
|
|
||||||
assert by_operation[("DELETE", "/vm/destroy/{vmid}")]["dry_run"] is True
|
assert by_operation[("DELETE", "/vm/destroy/{vmid}")]["dry_run"] is True
|
||||||
assert all(item["path"] != "/{service}/{path}" for item in payload["operations"])
|
assert all(item["path"] != "/{service}/{path}" for item in payload["operations"])
|
||||||
assert payload["model_contract"]["instruction"].startswith("Prefer read_only")
|
assert payload["model_contract"]["instruction"].startswith("Prefer read_only")
|
||||||
|
|
@ -499,62 +71,6 @@ def test_info_advertises_capabilities_endpoint():
|
||||||
response = client.get("/info", headers={"Authorization": "Bearer test-token"})
|
response = client.get("/info", headers={"Authorization": "Bearer test-token"})
|
||||||
assert response.status_code == 200
|
assert response.status_code == 200
|
||||||
assert response.json()["endpoints"]["capabilities"] == "/capabilities"
|
assert response.json()["endpoints"]["capabilities"] == "/capabilities"
|
||||||
assert response.json()["endpoints"]["doctor"] == "/doctor/{target}"
|
|
||||||
assert response.json()["endpoints"]["drift"] == "/drift"
|
|
||||||
assert response.json()["endpoints"]["maintenance_preflight"] == "/maintenance/preflight"
|
|
||||||
assert response.json()["endpoints"]["ui"] == "/ui"
|
|
||||||
|
|
||||||
|
|
||||||
def test_audit_persists_and_redacts_secrets(tmp_path, monkeypatch):
|
|
||||||
db = tmp_path / "audit.sqlite3"
|
|
||||||
monkeypatch.setattr(app, "AUDIT_DB_PATH", str(db))
|
|
||||||
app._init_audit_db()
|
|
||||||
app._audit("/danger", "POST", 200, "host=x token=abc password=hunter2 api_key=secret")
|
|
||||||
app._audit_log.clear()
|
|
||||||
|
|
||||||
with TestClient(app.app) as client:
|
|
||||||
response = client.get("/audit", headers={"Authorization": "Bearer test-token"})
|
|
||||||
|
|
||||||
assert response.status_code == 200
|
|
||||||
entry = response.json()[0]
|
|
||||||
assert entry["endpoint"] == "/danger"
|
|
||||||
assert "abc" not in entry["detail"]
|
|
||||||
assert "hunter2" not in entry["detail"]
|
|
||||||
assert "secret" not in entry["detail"]
|
|
||||||
assert entry["detail"].count("[REDACTED]") == 3
|
|
||||||
|
|
||||||
|
|
||||||
def test_audit_records_ai_and_web_ui_actor(tmp_path, monkeypatch):
|
|
||||||
db = tmp_path / "audit.sqlite3"
|
|
||||||
monkeypatch.setattr(app, "AUDIT_DB_PATH", str(db))
|
|
||||||
|
|
||||||
async def empty_status():
|
|
||||||
return {}
|
|
||||||
|
|
||||||
monkeypatch.setattr(app, "_collect_service_status", empty_status)
|
|
||||||
app._ui_sessions.clear()
|
|
||||||
with TestClient(app.app) as client:
|
|
||||||
ai = client.get(
|
|
||||||
"/status",
|
|
||||||
headers={"Authorization": "Bearer test-token", "X-Butler-Actor": "Trulla"},
|
|
||||||
)
|
|
||||||
assert ai.status_code == 200
|
|
||||||
|
|
||||||
client.headers.pop("Authorization", None)
|
|
||||||
client.get("/ui/session")
|
|
||||||
web = client.get("/status")
|
|
||||||
assert web.status_code == 200
|
|
||||||
|
|
||||||
entries = client.get("/audit").json()
|
|
||||||
|
|
||||||
assert [item["actor"] for item in entries[:2]] == ["Weboberfläche", "Trulla"]
|
|
||||||
|
|
||||||
|
|
||||||
def test_ui_audit_has_actor_column_and_filter():
|
|
||||||
with TestClient(app.app) as client:
|
|
||||||
response = client.get("/ui")
|
|
||||||
assert '<th>Akteur</th>' in response.text
|
|
||||||
assert 'id="audit-actor"' in response.text
|
|
||||||
|
|
||||||
|
|
||||||
def test_wireguard_status_returns_redacted_live_state(monkeypatch):
|
def test_wireguard_status_returns_redacted_live_state(monkeypatch):
|
||||||
|
|
@ -902,115 +418,6 @@ def test_uptime_monitor_remove_rejects_invalid_expected_name_before_ssh(monkeypa
|
||||||
assert response.status_code == 400
|
assert response.status_code == 400
|
||||||
|
|
||||||
|
|
||||||
def test_media_verify_returns_duration_and_not_suspect_when_within_tolerance(monkeypatch):
|
|
||||||
monkeypatch.setattr(app, "_find_inventory_host", lambda host: {"user": "sascha", "ip": "10.2.1.100"})
|
|
||||||
calls = []
|
|
||||||
|
|
||||||
def fake_ssh(host, command, timeout=30):
|
|
||||||
calls.append((host, command, timeout))
|
|
||||||
return 0, "2967.355000\n", ""
|
|
||||||
|
|
||||||
monkeypatch.setattr(app, "_ssh", fake_ssh)
|
|
||||||
with TestClient(app.app) as client:
|
|
||||||
response = client.post(
|
|
||||||
"/media/verify",
|
|
||||||
headers={"Authorization": "Bearer test-token"},
|
|
||||||
json={"host": "arrapps", "path": "/data/UHD/serien/Show/ep.mkv", "expected_minutes": 49.5},
|
|
||||||
)
|
|
||||||
assert response.status_code == 200
|
|
||||||
body = response.json()
|
|
||||||
assert body["duration_minutes"] == 49.46
|
|
||||||
assert body["suspect"] is False
|
|
||||||
assert calls[0][0] == "sascha@10.2.1.100"
|
|
||||||
assert "bazarrUHD" in calls[0][1]
|
|
||||||
assert "ffprobe" in calls[0][1]
|
|
||||||
|
|
||||||
|
|
||||||
def test_media_verify_flags_truncated_file_as_suspect(monkeypatch):
|
|
||||||
monkeypatch.setattr(app, "_find_inventory_host", lambda host: {"user": "sascha", "ip": "10.2.1.100"})
|
|
||||||
monkeypatch.setattr(app, "_ssh", lambda *_args, **_kwargs: (0, "1836.0\n", ""))
|
|
||||||
with TestClient(app.app) as client:
|
|
||||||
response = client.post(
|
|
||||||
"/media/verify",
|
|
||||||
headers={"Authorization": "Bearer test-token"},
|
|
||||||
json={"host": "arrapps", "path": "/data/UHD/serien/Show/ep.mkv", "expected_minutes": 49.5},
|
|
||||||
)
|
|
||||||
assert response.status_code == 200
|
|
||||||
body = response.json()
|
|
||||||
assert body["suspect"] is True
|
|
||||||
assert body["deviation_pct"] > 20
|
|
||||||
|
|
||||||
|
|
||||||
def test_media_verify_rejects_path_outside_data_before_ssh(monkeypatch):
|
|
||||||
monkeypatch.setattr(app, "_ssh", lambda *_args, **_kwargs: (_ for _ in ()).throw(AssertionError("must not SSH")))
|
|
||||||
with TestClient(app.app) as client:
|
|
||||||
response = client.post(
|
|
||||||
"/media/verify",
|
|
||||||
headers={"Authorization": "Bearer test-token"},
|
|
||||||
json={"host": "arrapps", "path": "/etc/passwd"},
|
|
||||||
)
|
|
||||||
assert response.status_code == 400
|
|
||||||
|
|
||||||
|
|
||||||
def test_media_verify_allows_apostrophe_in_filename_and_quotes_it_safely(monkeypatch):
|
|
||||||
monkeypatch.setattr(app, "_find_inventory_host", lambda host: {"user": "sascha", "ip": "10.2.1.100"})
|
|
||||||
calls = []
|
|
||||||
|
|
||||||
def fake_ssh(host, command, timeout=30):
|
|
||||||
calls.append((host, command, timeout))
|
|
||||||
return 0, "2967.0\n", ""
|
|
||||||
|
|
||||||
monkeypatch.setattr(app, "_ssh", fake_ssh)
|
|
||||||
path = "/data/FHD/serien/Star Trek - Strange New Worlds (2022)/Season 04/Once La'An a Time.mkv"
|
|
||||||
with TestClient(app.app) as client:
|
|
||||||
response = client.post(
|
|
||||||
"/media/verify",
|
|
||||||
headers={"Authorization": "Bearer test-token"},
|
|
||||||
json={"host": "arrapps", "path": path, "expected_minutes": 49.5},
|
|
||||||
)
|
|
||||||
assert response.status_code == 200
|
|
||||||
# shlex.quote must produce a command the remote shell parses as ONE argument,
|
|
||||||
# i.e. no unescaped apostrophe breaks out of quoting.
|
|
||||||
executed_cmd = calls[0][1]
|
|
||||||
quoted = shlex.quote(path)
|
|
||||||
assert quoted in executed_cmd
|
|
||||||
assert shlex.split(executed_cmd)[-1] == path
|
|
||||||
|
|
||||||
|
|
||||||
def test_media_verify_rejects_shell_metacharacters_before_ssh(monkeypatch):
|
|
||||||
monkeypatch.setattr(app, "_ssh", lambda *_args, **_kwargs: (_ for _ in ()).throw(AssertionError("must not SSH")))
|
|
||||||
with TestClient(app.app) as client:
|
|
||||||
response = client.post(
|
|
||||||
"/media/verify",
|
|
||||||
headers={"Authorization": "Bearer test-token"},
|
|
||||||
json={"host": "arrapps", "path": "/data/UHD/serien/a\x00.mkv"},
|
|
||||||
)
|
|
||||||
assert response.status_code == 400
|
|
||||||
|
|
||||||
|
|
||||||
def test_media_verify_rejects_unknown_host_before_ssh(monkeypatch):
|
|
||||||
monkeypatch.setattr(app, "_ssh", lambda *_args, **_kwargs: (_ for _ in ()).throw(AssertionError("must not SSH")))
|
|
||||||
with TestClient(app.app) as client:
|
|
||||||
response = client.post(
|
|
||||||
"/media/verify",
|
|
||||||
headers={"Authorization": "Bearer test-token"},
|
|
||||||
json={"host": "unknown-host", "path": "/data/UHD/serien/ep.mkv"},
|
|
||||||
)
|
|
||||||
assert response.status_code == 400
|
|
||||||
|
|
||||||
|
|
||||||
def test_media_verify_returns_502_on_unparsable_ffprobe_output(monkeypatch):
|
|
||||||
monkeypatch.setattr(app, "_find_inventory_host", lambda host: {"user": "sascha", "ip": "10.2.1.100"})
|
|
||||||
monkeypatch.setattr(app, "_ssh", lambda *_args, **_kwargs: (0, "N/A\n", ""))
|
|
||||||
with TestClient(app.app) as client:
|
|
||||||
response = client.post(
|
|
||||||
"/media/verify",
|
|
||||||
headers={"Authorization": "Bearer test-token"},
|
|
||||||
json={"host": "arrapps", "path": "/data/UHD/serien/ep.mkv", "expected_minutes": 49.5},
|
|
||||||
)
|
|
||||||
assert response.status_code == 502
|
|
||||||
|
|
||||||
|
|
||||||
def test_invalid_log_target_is_rejected_before_ssh():
|
def test_invalid_log_target_is_rejected_before_ssh():
|
||||||
with TestClient(app.app) as client:
|
with TestClient(app.app) as client:
|
||||||
response = client.get(
|
response = client.get(
|
||||||
|
|
@ -1226,7 +633,6 @@ def test_backup_collection_runs_hosts_concurrently(monkeypatch):
|
||||||
{"name": f"vm-{index}", "user": "sascha", "ip": f"10.1.1.{index}"}
|
{"name": f"vm-{index}", "user": "sascha", "ip": f"10.1.1.{index}"}
|
||||||
for index in range(1, 5)
|
for index in range(1, 5)
|
||||||
])
|
])
|
||||||
monkeypatch.setattr(app, "_config", {})
|
|
||||||
|
|
||||||
def fake_ssh(*_args, **_kwargs):
|
def fake_ssh(*_args, **_kwargs):
|
||||||
nonlocal active, max_active
|
nonlocal active, max_active
|
||||||
|
|
@ -1241,24 +647,7 @@ def test_backup_collection_runs_hosts_concurrently(monkeypatch):
|
||||||
|
|
||||||
assert max_active > 1
|
assert max_active > 1
|
||||||
assert result["summary"] == {
|
assert result["summary"] == {
|
||||||
"total": 4, "healthy": 4, "warning": 0, "critical": 0, "unknown": 0, "exempt": 0
|
"total": 4, "healthy": 4, "warning": 0, "critical": 0, "unknown": 0
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
def test_backup_policy_exempts_host_without_borg_call(monkeypatch):
|
|
||||||
monkeypatch.setattr(app, "_get_inventory_hosts", lambda: [
|
|
||||||
{"name": "guck-vps", "user": "debian", "ip": "141.94.237.199"}
|
|
||||||
])
|
|
||||||
monkeypatch.setattr(app, "_config", {"backup": {"exempt_hosts": ["guck-vps"]}})
|
|
||||||
monkeypatch.setattr(app, "_ssh", lambda *_args, **_kwargs: (_ for _ in ()).throw(AssertionError("must not call borg")))
|
|
||||||
|
|
||||||
result = asyncio.run(app._collect_backup_status())
|
|
||||||
|
|
||||||
assert result["summary"] == {
|
|
||||||
"total": 1, "healthy": 0, "warning": 0, "critical": 0, "unknown": 0, "exempt": 1
|
|
||||||
}
|
|
||||||
assert result["hosts"]["guck-vps"] == {
|
|
||||||
"state": "exempt", "ok": True, "reason": "backup policy exemption"
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
@ -1272,75 +661,6 @@ def test_overview_openapi_has_stable_enums_and_schema():
|
||||||
assert finding_schema["properties"]["severity"]["enum"] == ["healthy", "warning", "critical"]
|
assert finding_schema["properties"]["severity"]["enum"] == ["healthy", "warning", "critical"]
|
||||||
|
|
||||||
|
|
||||||
def test_doctor_correlates_host_layers(monkeypatch):
|
|
||||||
async def snapshot():
|
|
||||||
return {
|
|
||||||
"services": {},
|
|
||||||
"hosts": {"guck-vps": {"reachable": True, "containers": ["caddy: Up 3 days"]}},
|
|
||||||
"backups": {"summary": {}, "hosts": {"guck-vps": {"state": "exempt", "ok": True}}},
|
|
||||||
"disks": {"guck-vps": {"pct": "8%"}},
|
|
||||||
}
|
|
||||||
|
|
||||||
monkeypatch.setattr(app, "_collect_operational_snapshot", snapshot)
|
|
||||||
with TestClient(app.app) as client:
|
|
||||||
response = client.get("/doctor/guck-vps", headers={"Authorization": "Bearer test-token"})
|
|
||||||
|
|
||||||
assert response.status_code == 200
|
|
||||||
result = response.json()
|
|
||||||
assert result["state"] == "healthy"
|
|
||||||
assert result["layers"]["host"]["reachable"] is True
|
|
||||||
assert result["layers"]["backup"]["state"] == "exempt"
|
|
||||||
assert result["layers"]["disk"]["pct"] == "8%"
|
|
||||||
assert result["findings"] == []
|
|
||||||
|
|
||||||
|
|
||||||
def test_drift_reports_inventory_coverage_gaps(monkeypatch):
|
|
||||||
async def snapshot():
|
|
||||||
return {
|
|
||||||
"services": {},
|
|
||||||
"hosts": {"vm-a": {"reachable": True}, "vm-b": {"reachable": True}, "node1": {"reachable": True}},
|
|
||||||
"backups": {"summary": {}, "hosts": {"vm-a": {"state": "healthy"}, "orphan": {"state": "healthy"}}},
|
|
||||||
"disks": {"vm-a": {"pct": "10%"}, "node1": {"pct": "20%"}},
|
|
||||||
}
|
|
||||||
|
|
||||||
monkeypatch.setattr(app, "_collect_operational_snapshot", snapshot)
|
|
||||||
with TestClient(app.app) as client:
|
|
||||||
response = client.get("/drift", headers={"Authorization": "Bearer test-token"})
|
|
||||||
|
|
||||||
assert response.status_code == 200
|
|
||||||
result = response.json()
|
|
||||||
assert result["state"] == "warning"
|
|
||||||
assert {item["code"] for item in result["findings"]} == {
|
|
||||||
"inventory_missing_backup", "inventory_missing_disk", "backup_without_inventory"
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
def test_maintenance_preflight_blocks_active_target_backup(monkeypatch):
|
|
||||||
async def snapshot():
|
|
||||||
return {
|
|
||||||
"services": {},
|
|
||||||
"hosts": {"emby-chris": {"reachable": True, "containers": ["emby: Up 2 days"]}},
|
|
||||||
"backups": {"summary": {}, "hosts": {"emby-chris": {"state": "healthy"}}},
|
|
||||||
"disks": {"emby-chris": {"pct": "30%"}},
|
|
||||||
}
|
|
||||||
|
|
||||||
async def active_backups():
|
|
||||||
return {"emby-chris": "active"}
|
|
||||||
|
|
||||||
monkeypatch.setattr(app, "_collect_operational_snapshot", snapshot)
|
|
||||||
monkeypatch.setattr(app, "_collect_active_backups", active_backups)
|
|
||||||
with TestClient(app.app) as client:
|
|
||||||
response = client.get(
|
|
||||||
"/maintenance/preflight?action=docker&target=emby-chris",
|
|
||||||
headers={"Authorization": "Bearer test-token"},
|
|
||||||
)
|
|
||||||
|
|
||||||
assert response.status_code == 200
|
|
||||||
result = response.json()
|
|
||||||
assert result["safe"] is False
|
|
||||||
assert result["blockers"] == [{"code": "backup_active", "target": "emby-chris"}]
|
|
||||||
|
|
||||||
|
|
||||||
def test_overview_is_compact_deterministic_and_light_model_friendly(monkeypatch):
|
def test_overview_is_compact_deterministic_and_light_model_friendly(monkeypatch):
|
||||||
async def service_data():
|
async def service_data():
|
||||||
return {
|
return {
|
||||||
|
|
@ -1480,124 +800,3 @@ def test_speedtest_deploy_requires_strong_secrets_and_uses_full_git_app(monkeypa
|
||||||
assert deploy[1]["compose.yaml"] == "content:compose.yaml"
|
assert deploy[1]["compose.yaml"] == "content:compose.yaml"
|
||||||
assert deploy[2] == "correct-horse-battery-staple"
|
assert deploy[2] == "correct-horse-battery-staple"
|
||||||
assert deploy[3] == "streamscope-session-secret-with-entropy"
|
assert deploy[3] == "streamscope-session-secret-with-entropy"
|
||||||
|
|
||||||
|
|
||||||
def test_sascha_media_edge_audit_uses_fixed_hetzner_host(monkeypatch):
|
|
||||||
payload = {
|
|
||||||
"hostname": "pfannkuchen",
|
|
||||||
"caddy": {"container_running": True, "protocols": ["h1", "h2", "h3"], "upstreams": ["10.6.1.103:8096"]},
|
|
||||||
"network": {"wg_media": False, "udp_51821": False},
|
|
||||||
}
|
|
||||||
calls = []
|
|
||||||
monkeypatch.setattr(app, "_find_inventory_host", lambda name: {"name": name, "user": "root", "ip": "46.225.230.72"})
|
|
||||||
monkeypatch.setattr(app, "_ssh", lambda host, command, timeout=30: (calls.append((host, command, timeout)) or (0, json.dumps(payload), "")))
|
|
||||||
with TestClient(app.app) as client:
|
|
||||||
response = client.get("/media/edge/sascha", headers={"Authorization": "Bearer test-token"})
|
|
||||||
assert response.status_code == 200
|
|
||||||
assert response.json()["caddy"]["upstreams"] == ["10.6.1.103:8096"]
|
|
||||||
assert calls[0][0] == "root@46.225.230.72"
|
|
||||||
assert "PrivateKey" not in response.text
|
|
||||||
|
|
||||||
|
|
||||||
def test_sascha_media_tunnel_defaults_to_side_effect_free_dry_run(monkeypatch):
|
|
||||||
monkeypatch.setattr(app, "_ssh", lambda *_args, **_kwargs: (_ for _ in ()).throw(AssertionError("dry-run must not SSH")))
|
|
||||||
with TestClient(app.app) as client:
|
|
||||||
response = client.post(
|
|
||||||
"/network/media-tunnel/sascha",
|
|
||||||
headers={"Authorization": "Bearer test-token"},
|
|
||||||
json={},
|
|
||||||
)
|
|
||||||
assert response.status_code == 200
|
|
||||||
body = response.json()
|
|
||||||
assert body["status"] == "would_deploy"
|
|
||||||
assert body["vps_address"] == "10.11.13.1/32"
|
|
||||||
assert body["emby_address"] == "10.11.13.3/32"
|
|
||||||
assert body["listen_port"] == 51821
|
|
||||||
|
|
||||||
|
|
||||||
def test_sascha_media_tunnel_requires_explicit_confirmation(monkeypatch):
|
|
||||||
monkeypatch.setattr(app, "_ssh", lambda *_args, **_kwargs: (_ for _ in ()).throw(AssertionError("unconfirmed request must not SSH")))
|
|
||||||
with TestClient(app.app) as client:
|
|
||||||
response = client.post(
|
|
||||||
"/network/media-tunnel/sascha",
|
|
||||||
headers={"Authorization": "Bearer test-token"},
|
|
||||||
json={"dry_run": False},
|
|
||||||
)
|
|
||||||
assert response.status_code == 400
|
|
||||||
|
|
||||||
|
|
||||||
def test_sascha_media_tunnel_apply_returns_redacted_result(monkeypatch):
|
|
||||||
result = {
|
|
||||||
"status": "deployed",
|
|
||||||
"interface": "wg-media",
|
|
||||||
"vps_address": "10.11.13.1/32",
|
|
||||||
"emby_address": "10.11.13.3/32",
|
|
||||||
"listen_port": 51821,
|
|
||||||
"handshake": True,
|
|
||||||
"ping_vps_to_emby": True,
|
|
||||||
"ping_emby_to_vps": True,
|
|
||||||
}
|
|
||||||
monkeypatch.setattr(app, "_deploy_sascha_media_tunnel", lambda: result)
|
|
||||||
with TestClient(app.app) as client:
|
|
||||||
response = client.post(
|
|
||||||
"/network/media-tunnel/sascha",
|
|
||||||
headers={"Authorization": "Bearer test-token"},
|
|
||||||
json={"dry_run": False, "confirmation": "DEPLOY_DIRECT_SASCHA_MEDIA_TUNNEL"},
|
|
||||||
)
|
|
||||||
assert response.status_code == 200
|
|
||||||
assert response.json()["handshake"] is True
|
|
||||||
assert "private" not in response.text.lower()
|
|
||||||
|
|
||||||
|
|
||||||
def test_sascha_media_tunnel_candidate_uses_valid_wireguard_interface_name():
|
|
||||||
import base64
|
|
||||||
import re
|
|
||||||
|
|
||||||
command = app._media_tunnel_install_command("vps", "A" * 43 + "=")
|
|
||||||
encoded = re.search(r"b64decode\('([^']+)'\)", command).group(1)
|
|
||||||
script = base64.b64decode(encoded).decode()
|
|
||||||
assert 'root / "wgmtest.conf"' in script
|
|
||||||
assert len("wgmtest") <= 15
|
|
||||||
|
|
||||||
|
|
||||||
def test_sascha_media_path_benchmark_returns_both_fixed_routes(monkeypatch):
|
|
||||||
monkeypatch.setattr(app, "_benchmark_sascha_media_paths", lambda: {
|
|
||||||
"legacy_node6": {"bytes": 268435456, "seconds": 4.0, "mbit_s": 536.9},
|
|
||||||
"direct_wg_media": {"bytes": 268435456, "seconds": 3.0, "mbit_s": 715.8},
|
|
||||||
})
|
|
||||||
with TestClient(app.app) as client:
|
|
||||||
response = client.post(
|
|
||||||
"/network/media-tunnel/sascha/benchmark",
|
|
||||||
headers={"Authorization": "Bearer test-token"},
|
|
||||||
)
|
|
||||||
assert response.status_code == 200
|
|
||||||
assert response.json()["direction"] == "emby-sascha_to_hetzner"
|
|
||||||
assert set(response.json()["results"]) == {"legacy_node6", "direct_wg_media"}
|
|
||||||
|
|
||||||
|
|
||||||
def test_sascha_media_edge_optimize_is_dry_run_by_default(monkeypatch):
|
|
||||||
monkeypatch.setattr(app, "_optimize_sascha_media_edge", lambda: (_ for _ in ()).throw(AssertionError("dry-run must not mutate")))
|
|
||||||
with TestClient(app.app) as client:
|
|
||||||
response = client.post("/media/edge/sascha/optimize", headers={"Authorization": "Bearer test-token"}, json={})
|
|
||||||
assert response.status_code == 200
|
|
||||||
assert response.json()["protocols"] == ["h1", "h2"]
|
|
||||||
assert response.json()["upstream"] == "10.11.13.3:8096"
|
|
||||||
|
|
||||||
|
|
||||||
def test_sascha_media_edge_optimize_requires_confirmation(monkeypatch):
|
|
||||||
monkeypatch.setattr(app, "_optimize_sascha_media_edge", lambda: (_ for _ in ()).throw(AssertionError("must not mutate")))
|
|
||||||
with TestClient(app.app) as client:
|
|
||||||
response = client.post("/media/edge/sascha/optimize", headers={"Authorization": "Bearer test-token"}, json={"dry_run": False})
|
|
||||||
assert response.status_code == 400
|
|
||||||
|
|
||||||
|
|
||||||
def test_sascha_media_edge_optimize_applies_fixed_safe_result(monkeypatch):
|
|
||||||
monkeypatch.setattr(app, "_optimize_sascha_media_edge", lambda: {"status": "optimized", "upstream": "10.11.13.3:8096", "protocols": ["h1", "h2"], "backup": "/app-config/caddy/backup", "sha256": "a" * 64})
|
|
||||||
with TestClient(app.app) as client:
|
|
||||||
response = client.post(
|
|
||||||
"/media/edge/sascha/optimize",
|
|
||||||
headers={"Authorization": "Bearer test-token"},
|
|
||||||
json={"dry_run": False, "confirmation": "OPTIMIZE_TV_SASCHA_LUTZ_DE"},
|
|
||||||
)
|
|
||||||
assert response.status_code == 200
|
|
||||||
assert response.json()["status"] == "optimized"
|
|
||||||
|
|
|
||||||
|
|
@ -18,8 +18,6 @@ def load_app(monkeypatch):
|
||||||
|
|
||||||
def test_bw_manager_deploy_rejects_bundle_without_and_gate(monkeypatch):
|
def test_bw_manager_deploy_rejects_bundle_without_and_gate(monkeypatch):
|
||||||
app = load_app(monkeypatch)
|
app = load_app(monkeypatch)
|
||||||
if not hasattr(app, "BW_MANAGER_REPO_FILES"):
|
|
||||||
pytest.skip("BW-Manager was intentionally retired on 13.08.2026")
|
|
||||||
files = {path: "placeholder" for path in app.BW_MANAGER_REPO_FILES}
|
files = {path: "placeholder" for path in app.BW_MANAGER_REPO_FILES}
|
||||||
files["compose.yaml"] = "services:\n bw-manager:\n build: ./src\n"
|
files["compose.yaml"] = "services:\n bw-manager:\n build: ./src\n"
|
||||||
files["src/app.py"] = "def old_policy(): pass\n"
|
files["src/app.py"] = "def old_policy(): pass\n"
|
||||||
|
|
|
||||||
|
|
@ -1,54 +0,0 @@
|
||||||
import app
|
|
||||||
import pytest
|
|
||||||
from fastapi.testclient import TestClient
|
|
||||||
|
|
||||||
|
|
||||||
def valid_bundle():
|
|
||||||
files={path:'placeholder' for path in app.GUCK_ADMIN_REPO_FILES}
|
|
||||||
files['guck-admin/compose.yaml']='''services:\n guck-admin:\n build: .\n network_mode: host\n cap_add: [NET_ADMIN]\n environment:\n GUCK_LIMIT: /host/guck-limit.sh\n volumes:\n - /app-config/guck-admin/data:/data\n control-monitor:\n build: .\n network_mode: host\n cap_add: [NET_ADMIN]\n'''
|
|
||||||
files['guck-admin/src/control.py']='''CREATE TABLE IF NOT EXISTS custom_networks\n2a00:8c40:f000::/36\n45.58.235.0/24\ndef sync_custom_networks(): pass\n'''
|
|
||||||
return files
|
|
||||||
|
|
||||||
|
|
||||||
def test_guck_admin_bundle_requires_persistent_custom_network_policy():
|
|
||||||
files=valid_bundle()
|
|
||||||
files['guck-admin/src/control.py']='def old_control(): pass\n'
|
|
||||||
with pytest.raises(ValueError,match='custom VPN'):
|
|
||||||
app._validate_guck_admin_bundle(files)
|
|
||||||
|
|
||||||
|
|
||||||
def test_guck_admin_deploy_dry_run_has_no_remote_side_effect(monkeypatch):
|
|
||||||
calls=[]
|
|
||||||
monkeypatch.setattr(app,'_find_inventory_host',lambda host:{'user':'debian','ip':'141.94.237.199'})
|
|
||||||
monkeypatch.setattr(app,'_ssh',lambda *args,**kwargs:calls.append(args))
|
|
||||||
result=app._deploy_guck_admin_compose(valid_bundle(),dry_run=True)
|
|
||||||
assert result['status']=='validated'
|
|
||||||
assert result['host']=='guck-vps'
|
|
||||||
assert calls==[]
|
|
||||||
|
|
||||||
|
|
||||||
def test_guck_admin_deploy_uses_inventory_target_and_verifies_policy(monkeypatch):
|
|
||||||
calls=[]
|
|
||||||
monkeypatch.setattr(app,'_find_inventory_host',lambda host:{'user':'debian','ip':'141.94.237.199'})
|
|
||||||
def fake_ssh(host,command,timeout=600):
|
|
||||||
calls.append((host,command,timeout))
|
|
||||||
if 'ipset test vpn-v6' in command:
|
|
||||||
return 0,'policy ok',''
|
|
||||||
return 0,'ok',''
|
|
||||||
monkeypatch.setattr(app,'_ssh',fake_ssh)
|
|
||||||
result=app._deploy_guck_admin_compose(valid_bundle(),dry_run=False)
|
|
||||||
assert result['status']=='deployed'
|
|
||||||
assert result['policy']=='verified'
|
|
||||||
assert all(host=='debian@141.94.237.199' for host,_,_ in calls)
|
|
||||||
commands='\n'.join(command for _,command,_ in calls)
|
|
||||||
assert 'docker compose build' in commands
|
|
||||||
assert '127.0.0.1:9090/health' in commands
|
|
||||||
assert '/actions/limiter/refresh' in commands
|
|
||||||
assert 'ipset test vpn-v6 2a00:8c40:f02d:a34c::1' in commands
|
|
||||||
assert 'ipset test vpn-v4 45.58.235.7' in commands
|
|
||||||
|
|
||||||
|
|
||||||
def test_guck_admin_deploy_endpoint_requires_auth(monkeypatch):
|
|
||||||
monkeypatch.setattr(app,'BUTLER_TOKEN','test-token')
|
|
||||||
response=TestClient(app.app).post('/vps/guck-admin/deploy',json={'dry_run':True})
|
|
||||||
assert response.status_code in (401,403)
|
|
||||||
125
ui.html
125
ui.html
|
|
@ -1,125 +0,0 @@
|
||||||
<!doctype html>
|
|
||||||
<html lang="de">
|
|
||||||
<head>
|
|
||||||
<meta charset="utf-8">
|
|
||||||
<meta name="viewport" content="width=device-width,initial-scale=1">
|
|
||||||
<meta name="color-scheme" content="dark">
|
|
||||||
<title>Pfannkuchen Butler</title>
|
|
||||||
<style>
|
|
||||||
:root{--bg:#08090a;--panel:#0f1011;--surface:#191a1b;--surface2:#222326;--border:rgba(255,255,255,.08);--border2:rgba(255,255,255,.05);--text:#f7f8f8;--secondary:#d0d6e0;--muted:#8a8f98;--dim:#62666d;--accent:#7170ff;--accent2:#5e6ad2;--green:#10b981;--yellow:#f59e0b;--red:#ef4444;--radius:10px}
|
|
||||||
*{box-sizing:border-box}html{scroll-behavior:smooth}body{margin:0;background:radial-gradient(circle at 65% -20%,rgba(113,112,255,.14),transparent 34%),var(--bg);color:var(--text);font-family:Inter,ui-sans-serif,-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif;font-feature-settings:"cv01","ss03";min-height:100vh}button,input,select{font:inherit}button{cursor:pointer}a{color:inherit}.hidden{display:none!important}
|
|
||||||
.shell{display:grid;grid-template-columns:248px minmax(0,1fr);min-height:100vh}.sidebar{position:sticky;top:0;height:100vh;padding:22px 16px;border-right:1px solid var(--border2);background:rgba(15,16,17,.92);backdrop-filter:blur(18px);z-index:20}.brand{display:flex;align-items:center;gap:11px;padding:0 8px 24px}.logo{width:34px;height:34px;border:1px solid rgba(113,112,255,.35);border-radius:10px;display:grid;place-items:center;background:linear-gradient(145deg,rgba(113,112,255,.22),rgba(255,255,255,.03));box-shadow:inset 0 0 16px rgba(113,112,255,.12)}.brand strong{font-size:14px;font-weight:590}.brand small{display:block;color:var(--muted);font-size:11px;margin-top:2px}.nav-label{font-size:10px;text-transform:uppercase;letter-spacing:.1em;color:var(--dim);padding:15px 10px 7px}.nav button{width:100%;display:flex;align-items:center;gap:10px;border:0;background:transparent;color:var(--muted);padding:9px 10px;border-radius:7px;text-align:left;font-size:13px;font-weight:510}.nav button:hover,.nav button.active{background:rgba(255,255,255,.05);color:var(--text)}.nav .icon{width:18px;text-align:center;color:var(--dim)}.sidebar-foot{position:absolute;left:16px;right:16px;bottom:18px}.session-pill{display:flex;align-items:center;justify-content:space-between;border:1px solid var(--border);border-radius:8px;padding:9px 10px;color:var(--muted);font-size:11px;background:rgba(255,255,255,.02)}.dot{width:7px;height:7px;border-radius:50%;background:var(--green);box-shadow:0 0 10px rgba(16,185,129,.65)}
|
|
||||||
main{min-width:0}.topbar{height:68px;position:sticky;top:0;z-index:15;display:flex;align-items:center;justify-content:space-between;padding:0 30px;border-bottom:1px solid var(--border2);background:rgba(8,9,10,.78);backdrop-filter:blur(18px)}.topbar h1{font-size:15px;margin:0;font-weight:510}.top-actions{display:flex;gap:8px}.btn{border:1px solid var(--border);background:rgba(255,255,255,.03);color:var(--secondary);border-radius:7px;padding:8px 12px;font-size:12px;font-weight:510}.btn:hover{background:rgba(255,255,255,.07);color:var(--text)}.btn.primary{background:var(--accent2);border-color:transparent;color:white}.btn.danger{color:#fca5a5}.mobile-menu{display:none}.content{max-width:1440px;margin:0 auto;padding:30px}.view{display:none}.view.active{display:block}.eyebrow{font-size:11px;color:var(--accent);text-transform:uppercase;letter-spacing:.11em;font-weight:590}.hero{display:flex;justify-content:space-between;align-items:flex-end;gap:24px;margin:4px 0 26px}.hero h2{font-size:31px;letter-spacing:-.7px;font-weight:510;margin:8px 0 6px}.hero p{margin:0;color:var(--muted);font-size:14px;line-height:1.55}.updated{font:11px ui-monospace,SFMono-Regular,Menlo,monospace;color:var(--dim)}
|
|
||||||
.metrics{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:12px;margin-bottom:18px}.metric,.panel,.operation{border:1px solid var(--border);background:rgba(255,255,255,.025);border-radius:var(--radius)}.metric{padding:17px}.metric-label{font-size:11px;color:var(--muted);margin-bottom:12px}.metric-value{font-size:25px;letter-spacing:-.45px;font-weight:510}.metric-meta{font-size:11px;color:var(--dim);margin-top:7px}.metric.good .metric-value{color:#a7f3d0}.metric.warn .metric-value{color:#fcd34d}.metric.bad .metric-value{color:#fca5a5}.grid-2{display:grid;grid-template-columns:minmax(0,1.4fr) minmax(300px,.6fr);gap:14px}.panel{padding:18px;min-width:0}.panel-head{display:flex;align-items:center;justify-content:space-between;margin-bottom:15px}.panel-title{font-size:13px;font-weight:590}.panel-sub{font-size:11px;color:var(--dim)}.empty{border:1px dashed var(--border);border-radius:8px;color:var(--dim);padding:26px;text-align:center;font-size:12px}.finding{display:grid;grid-template-columns:9px 1fr auto;gap:10px;align-items:start;padding:11px 0;border-bottom:1px solid var(--border2)}.finding:last-child{border-bottom:0}.finding-dot{width:7px;height:7px;border-radius:50%;background:var(--yellow);margin-top:5px}.finding.critical .finding-dot{background:var(--red)}.finding strong{font-size:12px}.finding p{font-size:11px;color:var(--muted);margin:4px 0 0}.badge{display:inline-flex;align-items:center;border:1px solid var(--border);border-radius:999px;padding:3px 7px;font:10px ui-monospace,SFMono-Regular,Menlo,monospace;color:var(--muted);white-space:nowrap}.badge.get,.badge.read_only{color:#a7f3d0;border-color:rgba(16,185,129,.25);background:rgba(16,185,129,.06)}.badge.post,.badge.put,.badge.patch{color:#c4b5fd;border-color:rgba(113,112,255,.3);background:rgba(113,112,255,.07)}.badge.delete,.badge.destructive{color:#fca5a5;border-color:rgba(239,68,68,.25);background:rgba(239,68,68,.06)}
|
|
||||||
.form-row{display:grid;grid-template-columns:1fr auto;gap:9px}.form-row.triple{grid-template-columns:160px 1fr auto}.sharing-form{grid-template-columns:140px 170px minmax(180px,1fr) auto}.input{width:100%;border:1px solid var(--border);background:rgba(255,255,255,.025);color:var(--text);border-radius:7px;padding:10px 12px;outline:0;font-size:13px}.input:focus{border-color:rgba(113,112,255,.6);box-shadow:0 0 0 3px rgba(113,112,255,.1)}select.input{appearance:none}.result{margin-top:14px;min-height:110px}.layer-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(190px,1fr));gap:9px}.layer{border:1px solid var(--border2);background:rgba(255,255,255,.02);border-radius:8px;padding:12px}.layer h4{font-size:11px;margin:0 0 8px;text-transform:uppercase;color:var(--muted);letter-spacing:.07em}.layer pre,.json{white-space:pre-wrap;word-break:break-word;margin:0;color:var(--secondary);font:11px/1.55 ui-monospace,SFMono-Regular,Menlo,monospace}.safe-banner{display:flex;align-items:center;gap:12px;border-radius:9px;padding:14px;border:1px solid rgba(16,185,129,.25);background:rgba(16,185,129,.06)}.safe-banner.blocked{border-color:rgba(239,68,68,.25);background:rgba(239,68,68,.06)}.safe-icon{font-size:21px}
|
|
||||||
.toolbar{display:flex;align-items:center;gap:9px;flex-wrap:wrap;margin-bottom:15px}.toolbar .input{max-width:360px}.chips{display:flex;gap:6px;flex-wrap:wrap}.chip{border:1px solid var(--border);background:transparent;color:var(--muted);border-radius:999px;padding:6px 10px;font-size:11px}.chip.active,.chip:hover{color:var(--text);background:rgba(255,255,255,.05)}.operations{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:10px}.operation{padding:14px;display:flex;flex-direction:column;gap:10px;min-height:145px;transition:.16s ease}.operation:hover{border-color:rgba(113,112,255,.35);transform:translateY(-1px);background:rgba(255,255,255,.035)}.operation-top{display:flex;justify-content:space-between;gap:8px}.operation-path{font:11px/1.45 ui-monospace,SFMono-Regular,Menlo,monospace;color:var(--secondary);word-break:break-all}.operation h3{font-size:12px;font-weight:590;margin:0}.operation p{font-size:11px;color:var(--muted);line-height:1.45;margin:0;flex:1}.operation-badges{display:flex;gap:5px;flex-wrap:wrap}.table-wrap{overflow:auto;border:1px solid var(--border);border-radius:9px}table{width:100%;border-collapse:collapse;min-width:760px}th,td{text-align:left;padding:10px 12px;border-bottom:1px solid var(--border2);font-size:11px}th{color:var(--dim);text-transform:uppercase;letter-spacing:.07em;font-size:9px;background:rgba(255,255,255,.02)}td{color:var(--secondary)}td.mono{font-family:ui-monospace,SFMono-Regular,Menlo,monospace}.status-code.ok{color:#a7f3d0}.status-code.err{color:#fca5a5}
|
|
||||||
.login{position:fixed;inset:0;z-index:100;background:radial-gradient(circle at 50% 15%,rgba(113,112,255,.18),transparent 30%),#08090a;display:grid;place-items:center;padding:20px}.login-card{width:min(420px,100%);border:1px solid var(--border);background:#0f1011;border-radius:14px;padding:28px;box-shadow:0 28px 90px rgba(0,0,0,.5)}.login-card .logo{margin-bottom:22px}.login-card h1{font-size:25px;letter-spacing:-.5px;font-weight:510;margin:0 0 8px}.login-card p{font-size:13px;color:var(--muted);line-height:1.5;margin:0 0 20px}.login-card form{display:grid;gap:10px}.error{color:#fca5a5;font-size:11px;min-height:16px}.toast{position:fixed;right:20px;bottom:20px;z-index:120;background:#191a1b;border:1px solid var(--border);border-radius:9px;padding:11px 14px;font-size:12px;color:var(--secondary);box-shadow:0 12px 40px rgba(0,0,0,.35);transform:translateY(20px);opacity:0;pointer-events:none;transition:.2s}.toast.show{transform:none;opacity:1}.spinner{width:15px;height:15px;border:2px solid rgba(255,255,255,.15);border-top-color:var(--accent);border-radius:50%;animation:spin .7s linear infinite;display:inline-block}@keyframes spin{to{transform:rotate(360deg)}}
|
|
||||||
@media(max-width:1050px){.operations{grid-template-columns:repeat(2,minmax(0,1fr))}.metrics{grid-template-columns:repeat(2,minmax(0,1fr))}.grid-2{grid-template-columns:1fr}}
|
|
||||||
@media(max-width:760px){.shell{display:block}.sidebar{position:fixed;transform:translateX(-100%);transition:.2s;width:260px}.sidebar.open{transform:none}.mobile-menu{display:inline-flex}.topbar{padding:0 15px}.content{padding:20px 14px}.hero{align-items:flex-start;flex-direction:column}.hero h2{font-size:25px}.operations{grid-template-columns:1fr}.metrics{grid-template-columns:repeat(2,1fr)}.form-row,.form-row.triple,.sharing-form{grid-template-columns:1fr}.btn,.input{min-height:44px}.top-actions .desktop-only{display:none}}
|
|
||||||
@media(max-width:420px){.metrics{grid-template-columns:1fr}.content{padding:18px 10px}.panel{padding:14px}.metric{padding:14px}}
|
|
||||||
</style>
|
|
||||||
</head>
|
|
||||||
<body>
|
|
||||||
<div id="app" class="shell">
|
|
||||||
<aside id="sidebar" class="sidebar">
|
|
||||||
<div class="brand"><div class="logo">🍳</div><div><strong>Butler</strong><small>Pfannkuchen Operations</small></div></div>
|
|
||||||
<nav class="nav" aria-label="Hauptnavigation">
|
|
||||||
<div class="nav-label">Betrieb</div>
|
|
||||||
<button class="active" data-view="overview"><span class="icon">◫</span>Übersicht</button>
|
|
||||||
<button data-view="doctor"><span class="icon">⌕</span>Doctor</button>
|
|
||||||
<button data-view="sharing"><span class="icon">◉</span>Emby Account Sharing</button>
|
|
||||||
<button data-view="safety"><span class="icon">◇</span>Wartung & Drift</button>
|
|
||||||
<button data-view="audit"><span class="icon">≡</span>Audit</button>
|
|
||||||
<div class="nav-label">API</div>
|
|
||||||
<button data-view="functions"><span class="icon">⌘</span>Alle Funktionen</button>
|
|
||||||
<a class="btn" href="/docs" target="_blank" rel="noreferrer" style="display:block;margin:9px 6px;text-decoration:none;text-align:center">Swagger öffnen ↗</a>
|
|
||||||
</nav>
|
|
||||||
<div class="sidebar-foot"><div class="session-pill"><span>Read-only Sitzung</span><span class="dot"></span></div></div>
|
|
||||||
</aside>
|
|
||||||
<main>
|
|
||||||
<header class="topbar"><div style="display:flex;align-items:center;gap:9px"><button id="menu" class="btn mobile-menu" aria-label="Menü öffnen">☰</button><h1 id="view-title">Übersicht</h1></div><div class="top-actions"><button id="refresh" class="btn desktop-only">↻ Aktualisieren</button></div></header>
|
|
||||||
<div class="content">
|
|
||||||
<section id="view-overview" class="view active">
|
|
||||||
<div class="hero"><div><div class="eyebrow">Live Zustand</div><h2>Dein Homelab auf einen Blick.</h2><p>Deterministisch aus Butler-Collectoren – keine geschätzten Zustände.</p></div><div id="updated" class="updated">Noch nicht geladen</div></div>
|
|
||||||
<div class="metrics">
|
|
||||||
<article id="metric-state" class="metric"><div class="metric-label">Gesamtzustand</div><div class="metric-value">—</div><div class="metric-meta">Butler Overview</div></article>
|
|
||||||
<article class="metric"><div class="metric-label">Services</div><div id="metric-services" class="metric-value">—</div><div class="metric-meta">Funktionsprobes</div></article>
|
|
||||||
<article class="metric"><div class="metric-label">Hosts</div><div id="metric-hosts" class="metric-value">—</div><div class="metric-meta">Inventory erreichbar</div></article>
|
|
||||||
<article class="metric"><div class="metric-label">Backups</div><div id="metric-backups" class="metric-value">—</div><div class="metric-meta">inkl. Policy</div></article>
|
|
||||||
</div>
|
|
||||||
<div class="grid-2"><article class="panel"><div class="panel-head"><div class="panel-title">Findings</div><span id="finding-count" class="badge">0</span></div><div id="findings"><div class="empty">Overview wird geladen …</div></div></article><article class="panel"><div class="panel-head"><div class="panel-title">API-Abdeckung</div><span class="panel-sub">live aus OpenAPI</span></div><div id="capability-summary" class="layer-grid"></div></article></div>
|
|
||||||
</section>
|
|
||||||
|
|
||||||
<section id="view-doctor" class="view">
|
|
||||||
<div class="hero"><div><div class="eyebrow">Korrelierte Diagnose</div><h2>Doctor</h2><p>Service, Host, Container, Backup und Disk in einer Prüfung.</p></div></div>
|
|
||||||
<article class="panel"><form id="doctor-form" class="form-row"><input id="doctor-target" class="input" placeholder="z. B. emby-chris oder guck-vps" required><button class="btn primary" type="submit">Diagnose starten</button></form><div id="doctor-result" class="result"><div class="empty">Gib einen bekannten Host oder Service ein.</div></div></article>
|
|
||||||
</section>
|
|
||||||
|
|
||||||
<section id="view-sharing" class="view">
|
|
||||||
<div class="hero"><div><div class="eyebrow">Konservative Anomalieerkennung</div><h2>Emby Account Sharing</h2><p>Zeitgleiche öffentliche Netze und geografisch unmögliche Wechsel – über beide Emby-Server.</p></div><span class="badge read_only">read-only</span></div>
|
|
||||||
<article class="panel">
|
|
||||||
<form id="sharing-form" class="form-row sharing-form">
|
|
||||||
<select id="sharing-days" class="input" aria-label="Analysezeitraum"><option value="7">7 Tage</option><option value="30" selected>30 Tage</option><option value="90">90 Tage</option></select>
|
|
||||||
<select id="sharing-server" class="input" aria-label="Emby-Server"><option value="all">Beide Server</option><option value="emby-sascha">Emby Sascha</option><option value="emby-chris">Emby Chris</option></select>
|
|
||||||
<input id="sharing-username" class="input" placeholder="Benutzer optional" aria-label="Benutzerfilter">
|
|
||||||
<button class="btn primary" type="submit">Analysieren</button>
|
|
||||||
</form>
|
|
||||||
<div class="panel-sub" style="margin-top:10px">IPv4 wird exakt verglichen. IPv6 wird als /64 angezeigt und für die Haushaltserkennung konservativ auf /48 zusammengefasst.</div>
|
|
||||||
</article>
|
|
||||||
<div id="sharing-summary" class="metrics" style="margin-top:14px"><article class="metric"><div class="metric-label">Analysierte Benutzer</div><div class="metric-value">—</div></article><article class="metric"><div class="metric-label">Auffällige Benutzer</div><div class="metric-value">—</div></article><article class="metric"><div class="metric-label">Zeitgleiche Netze</div><div class="metric-value">—</div></article><article class="metric"><div class="metric-label">Unmögliche Wechsel</div><div class="metric-value">—</div></article></div>
|
|
||||||
<div class="grid-2"><article class="panel"><div class="panel-head"><div class="panel-title">Erkannte Ereignisse</div><span id="sharing-event-count" class="badge">0</span></div><div id="sharing-events"><div class="empty">Analyse noch nicht gestartet.</div></div></article><article class="panel"><div class="panel-head"><div class="panel-title">Benutzer-Risiko</div><span class="panel-sub">nur begründete Treffer</span></div><div id="sharing-users"><div class="empty">Noch keine Daten.</div></div></article></div>
|
|
||||||
</section>
|
|
||||||
|
|
||||||
<section id="view-safety" class="view">
|
|
||||||
<div class="hero"><div><div class="eyebrow">Read-only Safety Gate</div><h2>Wartung & Drift</h2><p>Blocker erkennen, bevor eine Änderung Schaden anrichtet.</p></div></div>
|
|
||||||
<div class="grid-2"><article class="panel"><div class="panel-head"><div class="panel-title">Maintenance Preflight</div></div><form id="preflight-form" class="form-row triple"><select id="preflight-action" class="input"><option value="general">Allgemein</option><option value="docker">Docker</option><option value="network">Netzwerk</option><option value="vm">VM</option></select><input id="preflight-target" class="input" placeholder="Zielhost (optional)"><button class="btn primary" type="submit">Prüfen</button></form><div id="preflight-result" class="result"><div class="empty">Noch kein Preflight ausgeführt.</div></div></article><article class="panel"><div class="panel-head"><div class="panel-title">Collector Drift</div><button id="drift-refresh" class="btn">Prüfen</button></div><div id="drift-result"><div class="empty">Drift wird geladen …</div></div></article></div>
|
|
||||||
</section>
|
|
||||||
|
|
||||||
<section id="view-audit" class="view">
|
|
||||||
<div class="hero"><div><div class="eyebrow">KI- und API-Protokoll</div><h2>Butler-Aktivitäten</h2><p>Wer hat wann welche Butler-Funktion aufgerufen? Sensible Werte bleiben redigiert.</p></div></div>
|
|
||||||
<article class="panel"><div class="panel-head"><div class="panel-title">Letzte Aktivitäten</div><div class="top-actions"><select id="audit-actor" class="input" aria-label="Akteur filtern" style="min-width:170px"><option value="all">Alle Akteure</option><option value="ai">Nur KI / API</option><option value="Weboberfläche">Nur Weboberfläche</option></select><button id="audit-refresh" class="btn">Aktualisieren</button></div></div><div class="table-wrap"><table><thead><tr><th>Zeit</th><th>Akteur</th><th>Methode</th><th>Endpoint</th><th>Status</th><th>Dry-run</th><th>Detail</th></tr></thead><tbody id="audit-body"><tr><td colspan="7">Wird geladen …</td></tr></tbody></table></div></article>
|
|
||||||
</section>
|
|
||||||
|
|
||||||
<section id="view-functions" class="view">
|
|
||||||
<div class="hero"><div><div class="eyebrow">Vollständiger Katalog</div><h2>Alle Butler-Funktionen</h2><p>Jede konkrete Operation aus OpenAPI sowie Proxy- und Metawege. Mutationen werden hier bewusst nicht blind ausgeführt.</p></div><div id="operation-total" class="updated">—</div></div>
|
|
||||||
<div class="toolbar"><input id="operation-search" class="input" type="search" placeholder="Pfad oder Funktion durchsuchen …"><div class="chips"><button class="chip active" data-filter="all">Alle</button><button class="chip" data-filter="read_only">Read-only</button><button class="chip" data-filter="mutation">Mutationen</button><button class="chip" data-filter="destructive">Destruktiv</button></div></div>
|
|
||||||
<div id="operations-grid" class="operations"></div>
|
|
||||||
</section>
|
|
||||||
</div>
|
|
||||||
</main>
|
|
||||||
</div>
|
|
||||||
<div id="toast" class="toast" role="status"></div>
|
|
||||||
|
|
||||||
<script>
|
|
||||||
(() => {
|
|
||||||
'use strict';
|
|
||||||
const state={capabilities:null,operations:[],audit:[],filter:'all'};
|
|
||||||
const $=s=>document.querySelector(s);
|
|
||||||
const $$=s=>[...document.querySelectorAll(s)];
|
|
||||||
const esc=v=>String(v??'').replace(/[&<>'"]/g,c=>({'&':'&','<':'<','>':'>',"'":''','"':'"'}[c]));
|
|
||||||
const cookie=name=>document.cookie.split('; ').find(x=>x.startsWith(name+'='))?.split('=').slice(1).join('=')||'';
|
|
||||||
const toast=msg=>{const el=$('#toast');el.textContent=msg;el.classList.add('show');setTimeout(()=>el.classList.remove('show'),2600)};
|
|
||||||
async function api(path,options={}){const method=(options.method||'GET').toUpperCase();const headers={...(options.headers||{})};if(!['GET','HEAD','OPTIONS'].includes(method))headers['X-CSRF-Token']=decodeURIComponent(cookie('butler_csrf'));if(options.body&&!headers['Content-Type'])headers['Content-Type']='application/json';const res=await fetch(path,{credentials:'same-origin',...options,headers});if(res.status===401){await fetch('/ui/session',{credentials:'same-origin'});location.reload();throw new Error('Read-only Sitzung wurde erneuert')}const text=await res.text();let data;try{data=JSON.parse(text)}catch{data=text}if(!res.ok)throw new Error(data?.detail||data?.error||`HTTP ${res.status}`);return data}
|
|
||||||
$$('.nav button[data-view]').forEach(btn=>btn.addEventListener('click',()=>switchView(btn.dataset.view)));
|
|
||||||
function switchView(name){$$('.view').forEach(v=>v.classList.toggle('active',v.id===`view-${name}`));$$('.nav button[data-view]').forEach(b=>b.classList.toggle('active',b.dataset.view===name));$('#view-title').textContent={overview:'Übersicht',doctor:'Doctor',sharing:'Emby Account Sharing',safety:'Wartung & Drift',audit:'Butler-Aktivitäten',functions:'Alle Funktionen'}[name];$('#sidebar').classList.remove('open')}
|
|
||||||
$('#menu').addEventListener('click',()=>$('#sidebar').classList.toggle('open'));
|
|
||||||
$('#refresh').addEventListener('click',refreshAll);$('#drift-refresh').addEventListener('click',loadDrift);$('#audit-refresh').addEventListener('click',loadAudit);$('#audit-actor').addEventListener('change',renderAudit);
|
|
||||||
async function refreshAll(){toast('Aktualisierung gestartet');await Promise.allSettled([loadOverview(),loadDrift(),loadAudit(),loadCapabilities()]);toast('Live-Daten aktualisiert')}
|
|
||||||
async function loadOverview(){try{const x=await api('/overview');const good=x.overall_state==='healthy';const box=$('#metric-state');box.className=`metric ${good?'good':x.overall_state==='warning'?'warn':'bad'}`;box.querySelector('.metric-value').textContent=x.overall_state;$('#metric-services').textContent=x.components.services.healthy;$('#metric-hosts').textContent=x.components.hosts.healthy;$('#metric-backups').textContent=x.components.backups.healthy;$('#finding-count').textContent=x.findings.length;$('#updated').textContent=new Date(x.generated).toLocaleString('de-DE');$('#findings').innerHTML=x.findings.length?x.findings.map(f=>`<div class="finding ${esc(f.severity)}"><span class="finding-dot"></span><div><strong>${esc(f.target)} · ${esc(f.code)}</strong><p>${esc(f.message)}</p></div><span class="badge">${esc(f.severity)}</span></div>`).join(''):'<div class="empty">Keine Findings. Alles sieht gut aus.</div>'}catch(e){$('#findings').innerHTML=`<div class="empty">${esc(e.message)}</div>`}}
|
|
||||||
async function loadCapabilities(){try{const x=await api('/capabilities');state.capabilities=x;state.operations=x.operations;$('#capability-summary').innerHTML=[['Operationen',x.counts.total],['Read-only',x.counts.read_only],['Mutationen',x.counts.mutations],['Destruktiv',x.counts.destructive]].map(([k,v])=>`<div class="layer"><h4>${k}</h4><div class="metric-value">${v}</div></div>`).join('');renderOperations()}catch(e){$('#operations-grid').innerHTML=`<div class="empty">${esc(e.message)}</div>`}}
|
|
||||||
function extraOperations(){return [{method:'PROXY',path:'/{service}/{path}',summary:'Generischer Service-Proxy',description:state.capabilities?.proxy?.note||'Backend-Proxy mit automatischer Authentifizierung',mode:'mutation',dry_run:false,critical:false,destructive:false},{method:'META',path:'/docs',summary:'Swagger UI',description:'Interaktive technische API-Dokumentation',mode:'read_only'},{method:'META',path:'/openapi.json',summary:'OpenAPI Schema',description:'Maschinenlesbare Schematruth',mode:'read_only'},{method:'META',path:'/health',summary:'Butler Health',description:'Öffentlicher Prozess- und Versionszustand',mode:'read_only'},{method:'META',path:'/',summary:'Self-Onboarding',description:'Service- und Endpoint-Übersicht',mode:'read_only'}]}
|
|
||||||
function renderOperations(){const q=$('#operation-search').value.trim().toLowerCase();const all=[...state.operations,...extraOperations()];const filtered=all.filter(o=>(state.filter==='all'||(state.filter==='destructive'?o.destructive:o.mode===state.filter))&&`${o.method} ${o.path} ${o.summary} ${o.description}`.toLowerCase().includes(q));$('#operation-total').textContent=`${filtered.length} von ${all.length} Punkten`;$('#operations-grid').innerHTML=filtered.map(o=>`<article class="operation"><div class="operation-top"><span class="badge ${esc(o.method.toLowerCase())}">${esc(o.method)}</span><div class="operation-badges">${o.critical?'<span class="badge">kritisch</span>':''}${o.destructive?'<span class="badge destructive">destruktiv</span>':''}</div></div><div class="operation-path">${esc(o.path)}</div><h3>${esc(o.summary||'Butler Operation')}</h3><p>${esc(o.description||'Keine zusätzliche Beschreibung im OpenAPI-Schema.')}</p><div class="operation-badges"><span class="badge ${esc(o.mode)}">${esc(o.mode)}</span>${o.dry_run?'<span class="badge">dry-run</span>':''}${o.confirmation_required?'<span class="badge">Bestätigung</span>':''}</div></article>`).join('')||'<div class="empty">Keine Funktion entspricht dem Filter.</div>'}
|
|
||||||
$('#operation-search').addEventListener('input',renderOperations);$$('.chip').forEach(c=>c.addEventListener('click',()=>{$$('.chip').forEach(x=>x.classList.remove('active'));c.classList.add('active');state.filter=c.dataset.filter;renderOperations()}));
|
|
||||||
$('#doctor-form').addEventListener('submit',async e=>{e.preventDefault();const target=$('#doctor-target').value.trim();const out=$('#doctor-result');out.innerHTML='<span class="spinner"></span>';try{const x=await api(`/doctor/${encodeURIComponent(target)}`);out.innerHTML=`<div class="safe-banner ${x.state==='critical'?'blocked':''}"><span class="safe-icon">${x.state==='healthy'?'✓':'!'}</span><div><strong>${esc(x.target)}: ${esc(x.state)}</strong><div class="panel-sub">${x.findings.length} Findings</div></div></div><div class="layer-grid" style="margin-top:10px">${Object.entries(x.layers).map(([k,v])=>`<div class="layer"><h4>${esc(k)}</h4><pre>${esc(JSON.stringify(v,null,2))}</pre></div>`).join('')}</div>`}catch(err){out.innerHTML=`<div class="empty">${esc(err.message)}</div>`}});
|
|
||||||
function sharingLocation(item){const l=item.location||{};return [l.city,l.region,l.country].filter(Boolean).map(esc).join(', ')||'Standort unbekannt'}
|
|
||||||
function renderSharing(x){const values=[x.summary.users_analyzed,x.summary.flagged_users,x.summary.concurrent_events,x.summary.impossible_travel_events],riskLabel={high:'hoch',medium:'mittel',none:'unauffällig'},flagged=x.users.filter(user=>user.risk!=='none');$$('#sharing-summary .metric-value').forEach((node,index)=>node.textContent=values[index]);$('#sharing-event-count').textContent=x.events.length;$('#sharing-events').innerHTML=x.events.length?x.events.map(event=>`<div class="finding ${event.severity==='high'?'critical':''}"><span class="finding-dot"></span><div><strong>${esc(event.username)} · ${event.type==='concurrent_networks'?'Zeitgleiche Netze':'Unplausibler Standortwechsel'}</strong><p>${esc(event.reason)}</p><p>${esc(new Date(event.start).toLocaleString('de-DE'))} – ${esc(new Date(event.end).toLocaleString('de-DE'))}${event.distance_km?` · ${esc(event.distance_km)} km · nötig: ${esc(event.required_speed_kmh)} km/h`:''}</p>${event.evidence.map(item=>`<div class="layer" style="margin-top:8px"><h4>${esc(item.server)} · ${sharingLocation(item)}</h4><div class="operation-path">IP ${esc(item.ip)}<br>Netz ${esc(item.network)}${item.version===6?`<br>IPv6-Elternblock ${esc(item.parent)}`:''}</div></div>`).join('')}</div><span class="badge ${event.severity==='high'?'destructive':''}">${esc(riskLabel[event.severity]||event.severity)}</span></div>`).join(''):'<div class="empty">Keine belastbaren Sharing-Hinweise im gewählten Zeitraum.</div>';$('#sharing-users').innerHTML=flagged.length?flagged.map(user=>`<div class="finding ${user.risk==='high'?'critical':''}"><span class="finding-dot" style="background:${user.risk==='medium'?'var(--yellow)':'var(--red)'}"></span><div><strong>${esc(user.username)}</strong><p>${esc(user.network_identities)} Netzidentitäten · ${esc(user.events)} Ereignisse · ${user.servers.map(esc).join(', ')}</p></div><span class="badge ${user.risk==='high'?'destructive':''}">${esc(riskLabel[user.risk]||user.risk)}</span></div>`).join(''):'<div class="empty">Keine Benutzer mit begründetem Sharing-Hinweis.</div>'}
|
|
||||||
$('#sharing-form').addEventListener('submit',async e=>{e.preventDefault();const q=new URLSearchParams({days:$('#sharing-days').value,server:$('#sharing-server').value});const username=$('#sharing-username').value.trim();if(username)q.set('username',username);$('#sharing-events').innerHTML='<div class="empty"><span class="spinner"></span> Sitzungsverlauf wird analysiert …</div>';$('#sharing-users').innerHTML='<div class="empty">Analyse läuft …</div>';try{renderSharing(await api(`/emby/account-sharing?${q}`))}catch(err){$('#sharing-events').innerHTML=`<div class="empty">${esc(err.message)}</div>`;$('#sharing-users').innerHTML='<div class="empty">Keine Auswertung verfügbar.</div>'}});
|
|
||||||
$('#preflight-form').addEventListener('submit',async e=>{e.preventDefault();const action=$('#preflight-action').value,target=$('#preflight-target').value.trim();const out=$('#preflight-result');out.innerHTML='<span class="spinner"></span>';try{const q=new URLSearchParams({action});if(target)q.set('target',target);const x=await api(`/maintenance/preflight?${q}`);out.innerHTML=`<div class="safe-banner ${x.safe?'':'blocked'}"><span class="safe-icon">${x.safe?'✓':'×'}</span><div><strong>${x.safe?'Wartung ist freigegeben':'Wartung ist blockiert'}</strong><div class="panel-sub">${x.blockers.length} Blocker · ${x.warnings.length} Warnungen</div></div></div>${x.blockers.concat(x.warnings).length?`<pre class="json" style="margin-top:12px">${esc(JSON.stringify({blockers:x.blockers,warnings:x.warnings},null,2))}</pre>`:''}`}catch(err){out.innerHTML=`<div class="empty">${esc(err.message)}</div>`}});
|
|
||||||
async function loadDrift(){const out=$('#drift-result');try{const x=await api('/drift');out.innerHTML=`<div class="safe-banner ${x.state==='healthy'?'':'blocked'}"><span class="safe-icon">${x.state==='healthy'?'✓':'!'}</span><div><strong>Drift: ${esc(x.state)}</strong><div class="panel-sub">${x.findings.length} Abdeckungslücken</div></div></div><div class="layer-grid" style="margin-top:10px">${Object.entries(x.coverage).map(([k,v])=>`<div class="layer"><h4>${esc(k)}</h4><div class="metric-value">${v}</div></div>`).join('')}</div>`}catch(e){out.innerHTML=`<div class="empty">${esc(e.message)}</div>`}}
|
|
||||||
function renderAudit(){const mode=$('#audit-actor').value;const rows=state.audit.filter(a=>mode==='all'||(mode==='ai'?a.actor!=='Weboberfläche'&&a.actor!=='System/Öffentlich':a.actor===mode));$('#audit-body').innerHTML=rows.length?rows.map(a=>`<tr><td>${esc(new Date(a.ts).toLocaleString('de-DE'))}</td><td><span class="badge">${esc(a.actor||'Legacy/API')}</span></td><td><span class="badge ${esc(a.method.toLowerCase())}">${esc(a.method)}</span></td><td class="mono">${esc(a.endpoint)}</td><td class="status-code ${a.status<400?'ok':'err'}">${esc(a.status)}</td><td>${a.dry_run?'ja':'nein'}</td><td>${esc(a.detail)}</td></tr>`).join(''):'<tr><td colspan="7">Keine Aktivitäten für diesen Filter.</td></tr>'}
|
|
||||||
async function loadAudit(){try{state.audit=await api('/audit?limit=100');renderAudit()}catch(e){$('#audit-body').innerHTML=`<tr><td colspan="7">${esc(e.message)}</td></tr>`}}
|
|
||||||
(async()=>{try{await fetch('/ui/session',{credentials:'same-origin'});await refreshAll()}catch{toast('Butler ist momentan nicht erreichbar')}})();
|
|
||||||
})();
|
|
||||||
</script>
|
|
||||||
</body>
|
|
||||||
</html>
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue