Files
MUA-Mikes-Unraid-Agent/scripts/test-release.py
T
Mikei386andClaude Opus 5.5 b8d89ffd9c release: MUA 2026.11.20.r036
Read-only shell
- Accept a full command line (`command`) and parse it without /bin/sh:
  quotes, escapes, ~, pipes between allowed programs, ; && ||, globs in
  absolute paths; 2>&1 and 2>/dev/null are tolerated. Pipeline stages run
  with strictly single-quoted, pre-validated literals only.
- Per-program option policies that understand combined short flags,
  --opt=value and GNU abbreviations. Closes bypasses: ip abbreviations
  (ip a a / ip r d / ip link s), dmesg -c/-Tc/--console-level=, ss -tK/-D,
  date operands, sort -o, uniq output file, file -C.
- Block credential files (shadow, SSH private keys, mua.conf, admin token,
  /proc/*/environ, docker config.v2.json); redact password hashes, private
  PEM keys and WireGuard keys in output. MUA API key and admin token are
  never emitted by any tool.
- More diagnostic programs (echo, printf, sort, uniq, cut, tr, findmnt,
  sensors, zpool/zfs read verbs, mdcmd status, ...). grep without matches
  is reported as no_match instead of an error.

Process handling
- Spawn every child in its own process group; timeouts kill the whole
  tree. The MCP hard timeout kills exactly the processes of that call.
- Async jobs: command in its own file (exit no longer loses the exit
  code), new unraid_system_job_cancel, finished jobs pruned after 7 days.

Other
- Cache toolbox discovery briefly; validate and bound session IDs; /health
  shows version/port only with a valid token; constant-time admin token
  check; auto-granted tools are logged and shown in the WebGUI.
- Remove the legacy PHP server (mcp/), drop old packages from dist/, pin
  @types/bun.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 21:51:14 +01:00

161 lines
8.7 KiB
Python

#!/usr/bin/env python3
"""Release/manifest checks without installing or touching a production host.
Run: python3 scripts/test-release.py
After building, also set MUA_RELEASE_ARCHIVE=/absolute/path/to/the.txz.
Only the post-install INLINE is executed, with its service path redirected to
an isolated test stub. Real rc.mua/TLS/MCP integration is covered by tls.test.ts.
"""
import hashlib
import json
import os
from pathlib import Path, PurePosixPath
import re
import subprocess
import tarfile
import tempfile
import unittest
import xml.etree.ElementTree as ET
ROOT = Path(__file__).resolve().parent.parent
BASE_URL = "https://git.casaderoll.de/michael/MUA-Mikes-Unraid-Agent/raw/branch/main"
def manifest():
# ElementTree expands this manifest's local internal entities, not remote DTDs.
return ET.fromstring((ROOT / "plugin/mua.plg").read_text())
def post_install():
return next(node.text for node in manifest().findall("FILE/INLINE")
if "rc.mua restart" in (node.text or ""))
def version():
return json.loads((ROOT / "package.json").read_text())["version"]
class ReleaseTests(unittest.TestCase):
def test_version_is_consistent(self):
current = version()
self.assertRegex(current, r"^\d{4}\.\d{2}\.\d{2}\.r\d{3}$")
self.assertEqual(manifest().attrib["version"], current)
self.assertEqual(json.loads((ROOT / "plugin/plugin.json").read_text())["version"], current)
for path in ("src/helpers.ts",):
with self.subTest(path=path):
declared = re.search(r'MUA_VERSION\s*=\s*[\'\"]([^\'\"]+)', (ROOT / path).read_text())
self.assertIsNotNone(declared)
self.assertEqual(declared[1], current)
self.assertTrue((manifest().findtext("CHANGES") or "").strip().startswith("### " + current))
def test_plugin_has_expected_https_download_and_install_path(self):
plugin = manifest()
self.assertEqual(plugin.attrib["pluginURL"], BASE_URL + "/plugin/mua.plg")
self.assertEqual(plugin.attrib["min"], "7.0.0")
payloads = [node for node in plugin.findall("FILE") if node.find("URL") is not None]
self.assertEqual(len(payloads), 1)
payload = payloads[0]
name = f"mua-{version()}-x86_64-1.txz"
self.assertEqual(payload.findtext("URL"), BASE_URL + "/dist/" + name)
self.assertEqual(payload.attrib["Name"], "/boot/config/plugins/mua/" + name)
self.assertEqual(payload.attrib["Run"], "upgradepkg --install-new")
self.assertRegex(payload.findtext("SHA256") or "", r"^[a-f0-9]{64}$")
def run_isolated_hook(self, healthy, scheme):
with tempfile.TemporaryDirectory(prefix="mua-release-hook-") as tmp:
directory = Path(tmp)
service = directory / "rc.mua"
service.write_text('#!/bin/sh\nprintf "%s\\n" "$1" >> "$CALLS"\n'
'if [ "$1" = health ]; then\n'
' [ "$HEALTHY" = 1 ] || exit 1\n'
' printf \'{"status":"ok","scheme":"%s"}\\n\' "$SCHEME"\n'
'fi\n')
service.chmod(0o755)
# Never contact even a local production service: shadow obsolete curl.
for name, body in {"sleep": "exit 0", "curl": 'printf "UNEXPECTED_CURL\\n" >> "$CALLS"; exit 22',
"hostname": "printf '127.0.0.1\\n'"}.items():
command = directory / name
command.write_text("#!/bin/sh\n" + body + "\n")
command.chmod(0o755)
calls = directory / "calls"
script = post_install().replace("/etc/rc.d/rc.mua", str(service))
result = subprocess.run(["bash"], input=script, text=True, capture_output=True, timeout=5,
env={**os.environ, "PATH": str(directory) + ":" + os.environ["PATH"],
"CALLS": str(calls), "HEALTHY": "1" if healthy else "0", "SCHEME": scheme})
return result, calls.read_text().splitlines()
def test_post_install_uses_transport_aware_readiness_for_http_and_https(self):
for scheme in ("http", "https"):
with self.subTest(scheme=scheme):
result, calls = self.run_isolated_hook(True, scheme)
self.assertEqual(result.returncode, 0, result.stderr)
self.assertEqual(calls, ["restart", "health"])
self.assertIn('"scheme":"' + scheme + '"', result.stdout)
self.assertNotIn("WARNUNG", result.stdout)
self.assertNotIn("http://", result.stdout)
def test_post_install_reports_failed_readiness(self):
result, calls = self.run_isolated_hook(False, "https")
self.assertEqual(result.returncode, 0) # Installer displays the actionable warning.
self.assertEqual(calls, ["restart", "health"])
self.assertIn("WARNUNG", result.stdout)
self.assertNotIn("Bereitschaft: OK", result.stdout)
def test_all_inline_hooks_are_valid_bash_without_executing_them(self):
for index, node in enumerate(manifest().findall("FILE/INLINE")):
with self.subTest(hook=index):
result = subprocess.run(["bash", "-n"], input=node.text, text=True, capture_output=True)
self.assertEqual(result.returncode, 0, result.stderr)
def test_dist_holds_only_the_current_release(self):
# Older packages stay available in git history; keeping only the
# current one in the tree keeps checkouts small (each is ~24 MB).
tracked = subprocess.run(["git", "ls-files", "dist"], cwd=ROOT, text=True,
capture_output=True, check=True).stdout.split()
name = f"dist/mua-{version()}-x86_64-1.txz"
self.assertEqual(sorted(tracked), [name, name + ".sha256"])
payload = next(node for node in manifest().findall("FILE") if node.find("URL") is not None)
digest = hashlib.sha256((ROOT / name).read_bytes()).hexdigest()
self.assertEqual(digest, payload.findtext("SHA256"))
self.assertEqual((ROOT / (name + ".sha256")).read_text().split()[0], digest)
@unittest.skipUnless(os.environ.get("MUA_RELEASE_ARCHIVE"), "set MUA_RELEASE_ARCHIVE after building")
def test_built_archive_matches_manifest_and_expected_files(self):
archive = Path(os.environ["MUA_RELEASE_ARCHIVE"])
payload = next(node for node in manifest().findall("FILE") if node.find("URL") is not None)
self.assertEqual(archive.name, PurePosixPath(payload.attrib["Name"]).name)
self.assertEqual(hashlib.sha256(archive.read_bytes()).hexdigest(), payload.findtext("SHA256"))
with tarfile.open(archive, "r:xz") as package:
for entry in package.getmembers():
with self.subTest(member=entry.name):
self.assertEqual((entry.uid, entry.gid), (0, 0))
self.assertFalse(entry.name.startswith("/"))
self.assertNotIn("..", PurePosixPath(entry.name).parts)
self.assertNotIn(entry.name, (".", "./"))
self.assertFalse(entry.issym() or entry.islnk() or entry.isdev())
self.assertTrue(PurePosixPath(entry.name).parts[0] in ("etc", "install", "usr"))
self.assertFalse(entry.name.endswith((".key", ".pem", ".conf")))
paths = {
"etc/rc.d/rc.mua": "scripts/rc.mua",
"usr/local/emhttp/plugins/mua/mua.page": "scripts/mua.page",
"usr/local/bin/unraid-docker-mcp-helper.php": "scripts/unraid-docker-mcp-helper.php",
"usr/local/bin/unraid-mcp-status-helper.php": "scripts/unraid-mcp-status-helper.php",
"usr/local/bin/unraid-admin-helper.php": "scripts/unraid-admin-helper.php",
f"usr/doc/mua-{version()}/HTTPS.md": "docs/HTTPS.md",
f"usr/doc/mua-{version()}/HERMES.md": "docs/HERMES.md",
f"usr/doc/mua-{version()}/UNRAID-CERTIFICATES.md": "docs/UNRAID-CERTIFICATES.md",
}
for packaged, source in paths.items():
self.assertEqual(package.extractfile(packaged).read(), (ROOT / source).read_bytes())
for executable in ("usr/local/bin/mua", "etc/rc.d/rc.mua", "install/doinst.sh"):
self.assertEqual(package.getmember(executable).mode, 0o755)
hook = package.extractfile("install/doinst.sh").read().decode()
self.assertIn("rc.mua health", hook)
self.assertNotIn("http://127.0.0.1:3002", hook)
result = subprocess.run(["bash", "-n"], input=hook, text=True, capture_output=True)
self.assertEqual(result.returncode, 0, result.stderr)
if __name__ == "__main__":
unittest.main(verbosity=2)