From f96e9abfd4b929b6d293bfca166c92f24adcea91 Mon Sep 17 00:00:00 2001 From: sascha Date: Sat, 8 Aug 2026 22:15:19 +0200 Subject: [PATCH 1/9] =?UTF-8?q?feat:=20read-only=20sysctl=20audit=20erg?= =?UTF-8?q?=C3=A4nzen?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app.py | 74 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 73 insertions(+), 1 deletion(-) diff --git a/app.py b/app.py index 080259c..1496ad1 100644 --- a/app.py +++ b/app.py @@ -11,7 +11,7 @@ from fastapi.responses import JSONResponse, RedirectResponse from contextlib import asynccontextmanager log = logging.getLogger("butler") -VERSION = "2.3.2" +VERSION = "2.3.3" API_DIR = os.environ.get("API_KEY_DIR", "/data/api") VAULT_CACHE_DIR = os.environ.get("VAULT_CACHE_DIR", "/data/vault-cache") @@ -278,6 +278,7 @@ async def root(): "status": "GET /status - health of all backends", "overview": "GET /overview?details=false - deterministic homelab verdict for small models", "audit": "GET /audit - recent API calls", + "sysctl_audit": "GET /system/sysctl/{host} - read-only live and persistent network tuning", }, "vault_items": len(_vault_cache), } @@ -1049,6 +1050,7 @@ SPEEDTEST_REPO_FILES = ( "streamscope/static/index.html", "streamscope/static/assets/app.css", "streamscope/static/assets/app.js", + "streamscope/static/assets/longterm-metrics.js", ) @@ -1185,6 +1187,76 @@ def _ssh(host, cmd, timeout=600): except _sp.TimeoutExpired: return 124, "", f"SSH command timed out after {timeout} seconds" + +SYSCTL_AUDIT_KEYS = ( + "net.core.default_qdisc", + "net.core.rmem_default", + "net.core.rmem_max", + "net.core.wmem_default", + "net.core.wmem_max", + "net.core.netdev_max_backlog", + "net.core.somaxconn", + "net.ipv4.ip_forward", + "net.ipv4.tcp_congestion_control", + "net.ipv4.tcp_fastopen", + "net.ipv4.tcp_mtu_probing", + "net.ipv4.tcp_no_metrics_save", + "net.ipv4.tcp_rmem", + "net.ipv4.tcp_slow_start_after_idle", + "net.ipv4.tcp_window_scaling", + "net.ipv4.tcp_wmem", +) + + +def _sysctl_audit_command() -> str: + script = f'''import glob, json, subprocess +keys = {SYSCTL_AUDIT_KEYS!r} +live, errors = {{}}, {{}} +for key in keys: + result = subprocess.run(["sysctl", "-n", key], capture_output=True, text=True) + if result.returncode == 0: + live[key] = result.stdout.strip() + else: + errors[key] = result.stderr.strip()[:160] +persistent = {{}} +for path in ["/etc/sysctl.conf", *sorted(glob.glob("/etc/sysctl.d/*.conf"))]: + try: + with open(path, encoding="utf-8", errors="replace") as handle: + for raw in handle: + line = raw.split("#", 1)[0].strip() + if "=" not in line: + continue + key, value = (part.strip() for part in line.split("=", 1)) + if key in keys: + persistent.setdefault(key, []).append({{"file": path, "value": value}}) + except (FileNotFoundError, PermissionError): + pass +print(json.dumps({{"live": live, "persistent": persistent, "errors": errors}})) +''' + encoded = base64.b64encode(script.encode()).decode() + return f'python3 -c "import base64;exec(base64.b64decode(\'{encoded}\'))"' + + +@app.get("/system/sysctl/{host}") +async def system_sysctl_audit(host: str, _=Depends(_verify)): + if not re.fullmatch(r"[a-z0-9][a-z0-9-]{0,62}", host): + raise HTTPException(400, "Invalid host name") + if host == "vps": + target = VPS_SSH + else: + inventory = await asyncio.to_thread(_find_inventory_host, host) + if not inventory: + raise HTTPException(404, f"Host {host} not found") + target = f'{inventory["user"]}@{inventory["ip"]}' + rc, out, err = await asyncio.to_thread(_ssh, target, _sysctl_audit_command(), 30) + if rc != 0: + raise HTTPException(502, (err or out).strip()[:300] or "sysctl audit failed") + try: + result = json.loads(out) + except json.JSONDecodeError as exc: + raise HTTPException(502, "sysctl audit returned invalid JSON") from exc + return {"host": host, **result} + def _pve_auth(): pv = _parse_kv("proxmox") return f"PVEAPIToken={pv.get('tokenid','')}={pv.get('secret','')}" From 497e917a86276f92c12734c56d68a2729d98239f Mon Sep 17 00:00:00 2001 From: sascha Date: Sat, 8 Aug 2026 22:15:19 +0200 Subject: [PATCH 2/9] =?UTF-8?q?feat:=20read-only=20sysctl=20audit=20erg?= =?UTF-8?q?=C3=A4nzen?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- tests/test_app.py | 27 ++++++++++++++++++++++++++- 1 file changed, 26 insertions(+), 1 deletion(-) diff --git a/tests/test_app.py b/tests/test_app.py index df4c85f..ba473b0 100644 --- a/tests/test_app.py +++ b/tests/test_app.py @@ -42,7 +42,32 @@ def test_health_exposes_current_version(): with TestClient(app.app) as client: response = client.get("/health") assert response.status_code == 200 - assert response.json()["version"] == app.VERSION == "2.3.2" + assert response.json()["version"] == app.VERSION == "2.3.3" + + +def test_sysctl_audit_reads_fixed_keys_from_inventory_host(monkeypatch): + payload = { + "live": {"net.ipv4.tcp_congestion_control": "bbr"}, + "persistent": {"net.ipv4.tcp_congestion_control": [{"file": "/etc/sysctl.d/99-net-tuning.conf", "value": "bbr"}]}, + "errors": {}, + } + calls = [] + monkeypatch.setattr(app, "_find_inventory_host", lambda name: {"name": name, "user": "root", "ip": "10.5.85.16"}) + monkeypatch.setattr(app, "_ssh", lambda host, command, timeout=600: (calls.append((host, command, timeout)) or (0, __import__("json").dumps(payload), ""))) + with TestClient(app.app) as client: + response = client.get("/system/sysctl/node6", headers={"Authorization": "Bearer test-token"}) + assert response.status_code == 200 + assert response.json()["live"]["net.ipv4.tcp_congestion_control"] == "bbr" + assert calls[0][0] == "root@10.5.85.16" + assert "base64.b64decode" in calls[0][1] + + +def test_sysctl_audit_rejects_unknown_host_without_ssh(monkeypatch): + monkeypatch.setattr(app, "_find_inventory_host", lambda _name: None) + monkeypatch.setattr(app, "_ssh", lambda *_args, **_kwargs: (_ for _ in ()).throw(AssertionError("must not SSH"))) + with TestClient(app.app) as client: + response = client.get("/system/sysctl/not-there", headers={"Authorization": "Bearer test-token"}) + assert response.status_code == 404 def test_invalid_log_target_is_rejected_before_ssh(): From e2140135684bccec06522e80a1b7ab856c92d884 Mon Sep 17 00:00:00 2001 From: sascha Date: Sat, 8 Aug 2026 22:15:20 +0200 Subject: [PATCH 3/9] =?UTF-8?q?feat:=20read-only=20sysctl=20audit=20erg?= =?UTF-8?q?=C3=A4nzen?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- tests/test_streamscope_deploy.py | 1 + 1 file changed, 1 insertion(+) diff --git a/tests/test_streamscope_deploy.py b/tests/test_streamscope_deploy.py index 65bd7b0..f8ca0a8 100644 --- a/tests/test_streamscope_deploy.py +++ b/tests/test_streamscope_deploy.py @@ -2,6 +2,7 @@ import app def test_streamscope_deploy_replaces_legacy_container_before_compose(monkeypatch): + assert "streamscope/static/assets/longterm-metrics.js" in app.SPEEDTEST_REPO_FILES files = {path: "placeholder" for path in app.SPEEDTEST_REPO_FILES} files["compose.yaml"] = """services: streamscope: From fcf1fb38160f14f1838606124b39211d26ac1bce Mon Sep 17 00:00:00 2001 From: sascha Date: Sat, 8 Aug 2026 22:25:43 +0200 Subject: [PATCH 4/9] fix: sysctl remote error tail report --- app.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app.py b/app.py index 1496ad1..660a9aa 100644 --- a/app.py +++ b/app.py @@ -1250,7 +1250,7 @@ async def system_sysctl_audit(host: str, _=Depends(_verify)): target = f'{inventory["user"]}@{inventory["ip"]}' rc, out, err = await asyncio.to_thread(_ssh, target, _sysctl_audit_command(), 30) if rc != 0: - raise HTTPException(502, (err or out).strip()[:300] or "sysctl audit failed") + raise HTTPException(502, (err or out).strip()[-500:] or "sysctl audit failed") try: result = json.loads(out) except json.JSONDecodeError as exc: From 3a674d9e3bdb1e766d6d01fcc1f868d0f15e5822 Mon Sep 17 00:00:00 2001 From: sascha Date: Sat, 8 Aug 2026 22:27:13 +0200 Subject: [PATCH 5/9] fix: sysctl audit via procfs --- app.py | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/app.py b/app.py index 660a9aa..9eb1ddd 100644 --- a/app.py +++ b/app.py @@ -1209,15 +1209,15 @@ SYSCTL_AUDIT_KEYS = ( def _sysctl_audit_command() -> str: - script = f'''import glob, json, subprocess + script = f'''import glob, json +from pathlib import Path keys = {SYSCTL_AUDIT_KEYS!r} live, errors = {{}}, {{}} for key in keys: - result = subprocess.run(["sysctl", "-n", key], capture_output=True, text=True) - if result.returncode == 0: - live[key] = result.stdout.strip() - else: - errors[key] = result.stderr.strip()[:160] + try: + live[key] = Path("/proc/sys/" + key.replace(".", "/")).read_text().strip() + except OSError as exc: + errors[key] = str(exc)[:160] persistent = {{}} for path in ["/etc/sysctl.conf", *sorted(glob.glob("/etc/sysctl.d/*.conf"))]: try: From 964774ca6b0802d2b960ce77c790f6f168b6ad8b Mon Sep 17 00:00:00 2001 From: sascha Date: Sat, 8 Aug 2026 22:42:57 +0200 Subject: [PATCH 6/9] feat: sichere Ansible-Tuning-Aktionen --- app.py | 25 ++++++++++++++++++++++--- 1 file changed, 22 insertions(+), 3 deletions(-) diff --git a/app.py b/app.py index 9eb1ddd..83a2186 100644 --- a/app.py +++ b/app.py @@ -11,7 +11,7 @@ from fastapi.responses import JSONResponse, RedirectResponse from contextlib import asynccontextmanager log = logging.getLogger("butler") -VERSION = "2.3.3" +VERSION = "2.3.4" API_DIR = os.environ.get("API_KEY_DIR", "/data/api") VAULT_CACHE_DIR = os.environ.get("VAULT_CACHE_DIR", "/data/vault-cache") @@ -1567,10 +1567,29 @@ print("updated" if updated else "added")''' async def ansible_run(request: Request, _=Depends(_verify)): body = await request.json() hostname = body.get("limit", body.get("hostname", "")) - template_id = body.get("template_id", 10) if not hostname: return JSONResponse({"error": "limit/hostname required"}, status_code=400) - rc, out, err = _ssh(AUTOMATION1, f"cd /app-config/ansible && bash pfannkuchen.sh setup {hostname}", timeout=600) + action = body.get("action", "setup") + if action not in {"setup", "tune", "pvetune"}: + return JSONResponse({"error": "action must be setup, tune or pvetune"}, status_code=400) + if not re.fullmatch(r"[a-zA-Z0-9_.:-]+", hostname): + return JSONResponse({"error": "invalid hostname/limit"}, status_code=400) + command = ( + "cd /app-config/ansible && " + "git pull --ff-only origin master && " + f"bash pfannkuchen.sh {action} {hostname}" + ) + rc, out, err = _ssh(AUTOMATION1, command, timeout=600) + _audit("/ansible/run", "POST", 200 if rc == 0 else 502, f"{action} {hostname}") + if action != "setup": + return { + "status": "ok" if rc == 0 else "error", + "action": action, + "hostname": hostname, + "rc": rc, + "output": out[-4000:], + "error": err[-1000:] if rc != 0 else "", + } # After successful ansible run: sync Hawser token to Dockhand if rc == 0: From 3c72ea6545ee23a09b0efb84d6d4ccca3edf16fc Mon Sep 17 00:00:00 2001 From: sascha Date: Sat, 8 Aug 2026 22:42:58 +0200 Subject: [PATCH 7/9] feat: sichere Ansible-Tuning-Aktionen --- tests/test_app.py | 40 +++++++++++++++++++++++++++++++++++++++- 1 file changed, 39 insertions(+), 1 deletion(-) diff --git a/tests/test_app.py b/tests/test_app.py index ba473b0..1b0f3bf 100644 --- a/tests/test_app.py +++ b/tests/test_app.py @@ -42,7 +42,7 @@ def test_health_exposes_current_version(): with TestClient(app.app) as client: response = client.get("/health") assert response.status_code == 200 - assert response.json()["version"] == app.VERSION == "2.3.3" + assert response.json()["version"] == app.VERSION == "2.3.4" def test_sysctl_audit_reads_fixed_keys_from_inventory_host(monkeypatch): @@ -108,6 +108,44 @@ def test_inventory_upsert_uses_base64_script(monkeypatch): assert "\\nname =" not in calls[0][1] +def test_ansible_run_supports_safe_tune_action_and_syncs_git(monkeypatch): + calls = [] + + def fake_ssh(host, command, timeout=600): + calls.append((host, command, timeout)) + return 0, "changed=1 failed=0", "" + + monkeypatch.setattr(app, "_ssh", fake_ssh) + with TestClient(app.app) as client: + response = client.post( + "/ansible/run", + headers={"Authorization": "Bearer test-token"}, + json={"hostname": "emby-sascha", "action": "tune"}, + ) + assert response.status_code == 200 + assert response.json()["action"] == "tune" + assert "git pull --ff-only origin master" in calls[0][1] + assert "bash pfannkuchen.sh tune emby-sascha" in calls[0][1] + assert len(calls) == 1 + + +def test_ansible_run_rejects_unknown_action_and_shell_metacharacters(monkeypatch): + monkeypatch.setattr(app, "_ssh", lambda *_args, **_kwargs: (_ for _ in ()).throw(AssertionError("must not SSH"))) + with TestClient(app.app) as client: + bad_action = client.post( + "/ansible/run", + headers={"Authorization": "Bearer test-token"}, + json={"hostname": "emby-sascha", "action": "shell"}, + ) + bad_host = client.post( + "/ansible/run", + headers={"Authorization": "Bearer test-token"}, + json={"hostname": "emby-sascha;id", "action": "tune"}, + ) + assert bad_action.status_code == 400 + assert bad_host.status_code == 400 + + def test_docker_inspect_returns_sanitized_summary(monkeypatch): raw = [{ "Name": "/fileflows", From f1f855c59693675fdf1589598abf010a9d194931 Mon Sep 17 00:00:00 2001 From: sascha Date: Sat, 8 Aug 2026 22:49:35 +0200 Subject: [PATCH 8/9] fix: sichere Tuning-Dateisynchronisation trotz lokaler Ansible-Abweichungen --- app.py | 30 ++++++++++++++++++++++++------ 1 file changed, 24 insertions(+), 6 deletions(-) diff --git a/app.py b/app.py index 83a2186..70fd72a 100644 --- a/app.py +++ b/app.py @@ -11,7 +11,7 @@ from fastapi.responses import JSONResponse, RedirectResponse from contextlib import asynccontextmanager log = logging.getLogger("butler") -VERSION = "2.3.4" +VERSION = "2.3.5" API_DIR = os.environ.get("API_KEY_DIR", "/data/api") VAULT_CACHE_DIR = os.environ.get("VAULT_CACHE_DIR", "/data/vault-cache") @@ -1574,11 +1574,29 @@ async def ansible_run(request: Request, _=Depends(_verify)): return JSONResponse({"error": "action must be setup, tune or pvetune"}, status_code=400) if not re.fullmatch(r"[a-zA-Z0-9_.:-]+", hostname): return JSONResponse({"error": "invalid hostname/limit"}, status_code=400) - command = ( - "cd /app-config/ansible && " - "git pull --ff-only origin master && " - f"bash pfannkuchen.sh {action} {hostname}" - ) + if action in {"tune", "pvetune"}: + approved_files = ( + "roles/sysctl/defaults/main.yml", + "roles/sysctl/tasks/main.yml", + "group_vars/vps/sysctl.yml", + "sysctl-proxmox.yaml", + "roles/sysctl_proxmox/tasks/main.yml", + ) + file_sync = " && ".join( + f"git show origin/master:{path} > {path}" for path in approved_files + ) + command = ( + "cd /app-config/ansible && " + "git fetch origin master && " + f"{file_sync} && " + f"bash pfannkuchen.sh {action} {hostname}" + ) + else: + command = ( + "cd /app-config/ansible && " + "git pull --ff-only origin master && " + f"bash pfannkuchen.sh {action} {hostname}" + ) rc, out, err = _ssh(AUTOMATION1, command, timeout=600) _audit("/ansible/run", "POST", 200 if rc == 0 else 502, f"{action} {hostname}") if action != "setup": From 815b5acf8d173f043873f9ed2855a53225370893 Mon Sep 17 00:00:00 2001 From: sascha Date: Sat, 8 Aug 2026 22:49:35 +0200 Subject: [PATCH 9/9] fix: sichere Tuning-Dateisynchronisation trotz lokaler Ansible-Abweichungen --- tests/test_app.py | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/tests/test_app.py b/tests/test_app.py index 1b0f3bf..e9960d4 100644 --- a/tests/test_app.py +++ b/tests/test_app.py @@ -42,7 +42,7 @@ def test_health_exposes_current_version(): with TestClient(app.app) as client: response = client.get("/health") assert response.status_code == 200 - assert response.json()["version"] == app.VERSION == "2.3.4" + assert response.json()["version"] == app.VERSION == "2.3.5" def test_sysctl_audit_reads_fixed_keys_from_inventory_host(monkeypatch): @@ -108,7 +108,7 @@ def test_inventory_upsert_uses_base64_script(monkeypatch): assert "\\nname =" not in calls[0][1] -def test_ansible_run_supports_safe_tune_action_and_syncs_git(monkeypatch): +def test_ansible_run_supports_safe_tune_action_and_syncs_approved_files(monkeypatch): calls = [] def fake_ssh(host, command, timeout=600): @@ -124,7 +124,9 @@ def test_ansible_run_supports_safe_tune_action_and_syncs_git(monkeypatch): ) assert response.status_code == 200 assert response.json()["action"] == "tune" - assert "git pull --ff-only origin master" in calls[0][1] + assert "git fetch origin master" in calls[0][1] + assert "git show origin/master:roles/sysctl/tasks/main.yml" in calls[0][1] + assert "git pull --ff-only" not in calls[0][1] assert "bash pfannkuchen.sh tune emby-sascha" in calls[0][1] assert len(calls) == 1