diff --git a/.gitignore b/.gitignore index 2c83625..1d7bf4c 100644 --- a/.gitignore +++ b/.gitignore @@ -25,6 +25,7 @@ Thumbs.db .env.* !.env.example mua.conf +tls.conf credentials* secrets* *.key diff --git a/AGENTS.md b/AGENTS.md index 5be377f..96ea3db 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -17,7 +17,10 @@ verify MUA on Unraid and connect an MCP client such as Hermes directly to it. ## Required workflow 1. Read `README.md` and `docs/HERMES.md` before changing anything. -2. Check `http://:3002/health`. +2. Check the configured `http://:3002/health` or native HTTPS URL. + For HTTPS, validate client trust and certificate SAN before sending a token; + never retry over plaintext or disable verification. See `docs/HTTPS.md`. + Native TLS is source-only until a separately authorized packaged release. 3. If health is successful, MUA is already installed. Do not rebuild or reinstall it. Register its `/mcp` URL in Hermes and test the connection. 4. If health fails, determine whether MUA is stopped or absent. Report that diff --git a/README.md b/README.md index c0b72e1..3e86cd9 100644 --- a/README.md +++ b/README.md @@ -62,6 +62,21 @@ einen Bearer-Token. Der Config-Server (Port 3013) läuft **nur auf localhost** und verlangt zusätzlich einen bei jedem Start neu erzeugten Admin-Token. Die WebGUI schützt schreibende Formulare außerdem mit einem CSRF-Token. +## Natives HTTPS (Entwicklungsstand) + +MUA kann den MCP-Listener selbst per TLS betreiben; ein Reverse Proxy ist nicht +nötig. HTTP bleibt der Standard für bestehende Installationen. Im Abschnitt +**HTTPS / TLS** der WebGUI werden Zertifikat-/Keypfade geprüft und gespeichert; +ein ausdrücklicher Neustart aktiviert HTTPS auf demselben Port. Bearer-Key und +Toolfreigaben bleiben unverändert. Fehlende/ungültige TLS-Dateien verhindern den +Start ohne HTTP-Fallback. Details zu `tls.conf`, Zertifikaten, Erneuerung, +Client-Trust und synthetischen Tests: **[docs/HTTPS.md](docs/HTTPS.md)**. + +Diese Quellcode-Erweiterung ist noch **nicht im veröffentlichten r033-Paket**. +Die bisherigen Downloadlinks/Plugin-Updates bleiben bis zu einem gesonderten +Release unverändert. Tests des aktuellen Entwicklungsstands bauen ein eigenes +Entwicklungsartefakt, keine Produktivinstallation. + ## Sicherheitsmodell - Neuinstallationen starten im Profil **Nur Lesen**. Container-Steuerung, diff --git a/docs/HERMES.md b/docs/HERMES.md index c488282..7873d16 100644 --- a/docs/HERMES.md +++ b/docs/HERMES.md @@ -27,7 +27,13 @@ Ein geeigneter kurzer Auftrag lautet: ## 1. Vorhandenen Server erkennen -Der offene Health-Endpunkt benötigt keinen API-Key: +Der offene Health-Endpunkt benötigt keinen API-Key. **Bei nativem HTTPS** die +URL als `https://ZERTIFIKAT-DNS-NAME:3002/health` verwenden und zuerst Client-Trust +herstellen; keine automatische HTTP-Rückstufung und keine deaktivierte +Zertifikatsprüfung. Die TLS-Erweiterung im Quellstand ist noch nicht im alten +r033-Paket enthalten. Konfiguration, Zertifikate und Erneuerung: +[HTTPS.md](HTTPS.md). Die folgenden HTTP-Beispiele gelten für bestehende +HTTP-Installationen; für HTTPS Schema und zertifizierten Namen konsistent ändern. ```bash curl -fsS http://UNRAID-IP:3002/health diff --git a/docs/HTTPS-VALIDATION.md b/docs/HTTPS-VALIDATION.md new file mode 100644 index 0000000..2514220 --- /dev/null +++ b/docs/HTTPS-VALIDATION.md @@ -0,0 +1,61 @@ +# Native TLS: Entwicklungsabnahme + +Prüfumgebung: Linux x86_64 im Entwicklungscheckout; Bun 1.3.14, +TypeScript 5.9.3, OpenSSL 3.5.7, PHP 8.4.27. Ausgangsstand: +`f2c792ce4819d94279d51223037f06c48900918d`. Prüfung am 2026-11-05. +Keine Produktivhosts oder tatsächlichen Zugangsdaten verwendet. + +## Tatsächlich ausgeführt + +| Prüfung | Ergebnis | +|---|---| +| Unveränderte Baseline mit Bun 1.3.14 | 37 Tests bestanden | +| `bun x --package typescript@5.9.3 tsc --noEmit` | Exit 0 | +| `bun test` nach Implementierung | 62/62 bestanden, 5 Dateien, keine Fehler | +| Transporttests gegen das aus dem neuen `.txz` entpackte Binary | 25/25 bestanden | +| PHP Notifications / Docker-Update / Storage / Admin | 9 / 10 / 10 / 23 Prüfungen bestanden | +| `php -l scripts/mua.page` | keine Syntaxfehler | +| `bash -n scripts/rc.mua scripts/package.sh` | Exit 0 | +| `xmllint --noout plugin/mua.plg` | Exit 0; bestehendes Release-Manifest unverändert | +| `git diff --check` | Exit 0 | +| `bash scripts/package.sh native-https-dev` | echtes Linux-Binary und xz-Tar erstellt | +| Archivinhalt | 21 Einträge; root:root, Binary/Service 0755, keine PEM-/Key-/Configdateien, kein Wurzeleintrag | + +Transportnachweise: verifizierter HTTPS-Health-Request, MCP-Initialisierung, +Werkzeugliste und erlaubter synthetischer Read-only-Aufruf; fehlender/falscher +Bearer → 401, gesperrtes Werkzeug bleibt gesperrt. OpenSSL bestätigt TLS 1.2 +und 1.3; der Server lehnt einen TLS-1.1-Client mit Protocol-Version-Alert ab. +Falscher Zertifikatname und fehlendes Vertrauen scheitern. Eine eigene Test-CA +mit Intermediate und Leaf funktioniert bei ausschließlich vertrauter Root-CA. + +Fehlende/unlesbare/verschlüsselte/nicht passende Keys, falsche PEM-Daten, +abgelaufene Zertifikate, relative Pfade, fehlende Pfade, doppelte Flags und +ungültige Aktivierungswerte verhindern den Start ohne HTTP-Fallback. Lokale +Verwaltung, WebGUI-CSRF, atomisches Speichern, Env-Vorrang/Sperre und expliziter +Neustart wurden ausgeführt. Ein fehlerhafter Renewal-Preflight lässt den alten +Listener bestehen; gültiger Neustart präsentiert nachweislich den neuen Key. +Loopback-Verwaltung funktioniert auch bei absichtlich falschem HTTP-Proxy-Env, +ohne den Admin-Token zum Proxy zu schicken. + +## Artefakt und Grenzen + +Lokales **Entwicklungs-/Prüfartefakt**, kein freigegebenes Plugin-Release: +`mua-native-https-dev-x86_64-1.txz`, 24.824.928 Bytes. +SHA256: `76704591a635b31e3cb114921ca75ee89556f397e76c57265933ce32527c5407`. + +Der Build belässt die bisherige interne Versionskonstante bewusst unverändert; +dieser Entwicklungsstand wird über Git-Commit und obigen Hash identifiziert. +Das Entwicklungslabel ist kein Installations-/Upgradepfad. Kein vorhandenes +r033-Paket und kein automatisch ausgeliefertes Update wurden ersetzt. +Für eine installierbare Ausgabe ist der reguläre versionierte Release-Prozess +inklusive zueinander passendem Manifest/Paket noch separat zu beauftragen. + +Kein Test auf einem echten Unraid-System, kein Browser-/WebGUI-Test innerhalb +von emhttp, kein Produktiv-TLS-/Hermes-Truststore-Test, kein ACME-/mTLS-/Hot-Reload. +PHP-WebGUI wurde real als PHP mit laufendem synthetischem MUA gerendert und über +Formularaktionen geprüft, nicht nur als Text gesucht. Self-Review durchgeführt; +kein unabhängiges Review behauptet (Bot-Auftrag/One-shot). + +Bun 1.4.4 fällt bereits beim unveränderten deleted-cwd-Reproducer der Baseline +fehl. Dafür wurde weder eine Regression unterdrückt noch ein Test umgeschrieben; +die oben dokumentierte vollständige Abnahme verwendet Bun 1.3.14. diff --git a/docs/HTTPS.md b/docs/HTTPS.md new file mode 100644 index 0000000..d9d92e4 --- /dev/null +++ b/docs/HTTPS.md @@ -0,0 +1,192 @@ +# Native HTTPS / TLS in MUA + +## Geltungsbereich und Kompatibilität + +Diese Funktion ist im **Quell-/Entwicklungsstand** enthalten. Das bisher auf `main` +veröffentlichte Pluginpaket **r033** und dessen Update-Manifest bleiben unverändert; +ein normales Plugin-Update installiert diese Entwicklung noch nicht. Für ein +Release müssen Version, Paket, SHA256 und Manifest gemeinsam aktualisiert werden. +Der Post-Install-Check im Release-Manifest muss dann wie der Paket-Hook +`/etc/rc.d/rc.mua health` verwenden, nicht den bisherigen fest kodierten HTTP-Test. + +- Ohne `tls.conf` bzw. mit `MUA_TLS_ENABLED=false`: bestehendes HTTP auf Port 3002. +- Mit `MUA_TLS_ENABLED=true`: **ausschließlich HTTPS auf demselben Port**, + einschließlich `/health`. Kein zusätzlicher HTTP-Port, kein Redirect und + insbesondere kein automatisches Zurückfallen auf HTTP. +- `/mcp` behält Bearer-Authentifizierung, Toolfreigaben, Sessions, Request-, Rate- + und Parallelitätsgrenzen. `/health` benötigt weiter keinen Bearer-Key, aber TLS. +- TLS 1.2 und 1.3; TLS 1.0/1.1 werden nicht angeboten. Keine neue Runtime-Abhängigkeit. +- Die Verwaltung bleibt bewusst **HTTP auf 127.0.0.1:3013**, mit eigenem + kurzlebigem Admin-Token und den bestehenden WebGUI-CSRF-Prüfungen. Sie wird + nicht ins LAN gebunden. TLS ersetzt weder Firewall noch Rechtebegrenzung. + +## Zertifikate vorbereiten + +MUA lädt PEM-Dateien: `fullchain.pem` (Serverzertifikat zuerst, danach nötige +Intermediate-Zertifikate) und den passenden **unverschlüsselten** PEM-Privatkey. +Der Root-CA-Schlüssel gehört **nie** auf den MUA-Server. Passwortgeschützte Keys, +PKCS#12/PFX, Key-Passphrasen, ACME-Accountverwaltung und mTLS werden hier nicht +unterstützt. MUA erzeugt oder bestellt keine Produktionszertifikate. + +Wähle einen DNS-Namen, den Clients tatsächlich verwenden. Das Zertifikat muss +**Subject Alternative Names (SAN)** für diesen Namen enthalten. Verbindungen +über eine IP benötigen genau diese IP als `IP`-SAN; ein DNS-SAN/CN genügt nicht. +Eine öffentliche oder interne CA kann das Zertifikat ausstellen. Die öffentlich +vertraute CA und eine vollständige Chain vereinfachen die Clientkonfiguration. + +Für einen isolierten lokalen Test (nicht als ungeprüfte Produktionsvorgabe): + +```bash +umask 077 +mkdir -p ./test-tls +openssl req -x509 -newkey rsa:3072 -sha256 -nodes -days 2 \ + -subj '/CN=localhost' \ + -addext 'subjectAltName=DNS:localhost,IP:127.0.0.1' \ + -keyout ./test-tls/privkey.pem -out ./test-tls/fullchain.pem +``` + +Zertifikate/Keys bleiben außerhalb Git und Chat. Beschränke Verzeichniszugriff +und Key-Leserechte auf den Dienstbenutzer (auf Unraid typischerweise root, +Verzeichnis 0700, Key 0600). Beachte: Unraids Bootmedium verwendet häufig FAT; +`chmod` ist dort **keine verlässliche individuelle Zugriffssperre**. Ein geschützter +persistenter Speicher oder bewusst verwaltetes Staging in einen root-eigenen +RAM-Pfad ist besser. Backups und das Bootmedium müssen ebenfalls geschützt sein. + +Dateien oder Symlink-Ziele müssen **vor jedem Dienststart/Boot** verfügbar sein. +Auf noch nicht gemountete Array-/Poolpfade zu zeigen führt absichtlich zum +Startabbruch. Dann Zertifikate sicher bereitstellen und MUA gezielt starten; +MUA mountet nichts und wartet nicht automatisch auf externe Speicher. + +## Einschalten + +### Unraid-WebGUI + +Unter **Settings → User Utilities → MUA → HTTPS / TLS**: + +1. Absoluten Pfad zur Fullchain und zum privaten Schlüssel eintragen. +2. **HTTPS aktivieren** wählen, dann **TLS prüfen und speichern**. +3. MUA prüft Lesbarkeit, PEM, Key-Zuordnung und Zertifikatsgültigkeit **vor** dem + Speichern. Ungültige Angaben ändern weder die Datei noch den laufenden Listener. +4. Der Transport bleibt bis zum **ausdrücklichen Dienstneustart** unverändert; + die GUI zeigt „noch nicht aktiv“. Das gilt auch beim bewussten Ausschalten. +5. Dienst neu starten und anschließend den Client auf `https://NAME:3002/mcp` + umstellen. Der bereits vorhandene Bearer-Key bleibt unverändert. + +Die angezeigte Server-IP gegebenenfalls durch den zertifizierten DNS-Namen +ersetzen. Die WebGUI zeigt aktive und gespeicherte Einstellungen getrennt und +übermittelt ausschließlich Dateipfade, niemals PEM-Inhalte oder Passphrasen. + +### Datei / Umgebung + +`/boot/config/plugins/mua/tls.conf` (lokaler Test: `$MUA_CONFIG_DIR/tls.conf`): + +```ini +MUA_TLS_ENABLED=true +MUA_TLS_CERT_FILE=/geschuetzter/persistenter/pfad/fullchain.pem +MUA_TLS_KEY_FILE=/geschuetzter/persistenter/pfad/privkey.pem +``` + +Die Datei ist einfaches `NAME=WERT`, ohne Shell-Quoting, Expansion oder `export`. +Kommentare beginnen mit `#`; doppelte/unbekannte Einträge und ungültige Flags +werden abgelehnt. `MUA_TLS_ENABLED` akzeptiert genau `true` oder `false`. +Absolute Dateipfade dürfen Leerzeichen und `=` enthalten, aber keine Steuerzeichen +oder äußeren Leerzeichen. Sie werden nie durch eine Shell ausgewertet. + +Die gleichnamigen Umgebungsvariablen überschreiben **einzeln** die Datei. +Sobald ein TLS-Env-Override gesetzt ist, sperrt die WebGUI das Speichern, damit +keine wirkungslose Parallelkonfiguration entsteht. Ein gesetztes leeres Flag +ist ein Fehler, nicht „HTTP“. Leere/nicht lesbare Zertifikats-/Keydateien, +Verzeichnisse statt Dateien und Dateien über 1 MiB werden abgelehnt. + +TLS liegt bewusst getrennt von `mua.conf`: bestehende API-Key-/Tool-/Toolbox- +Einstellungen und deren Speichervorgänge bleiben unverändert. Die WebGUI +schreibt `tls.conf` per atomarem Umbenennen (0600, soweit das Dateisystem es +unterstützt). Niemals `source tls.conf` verwenden. + +```bash +# Prüft nur Konfiguration/PEM/Gültigkeit, ohne Ports zu öffnen oder Keys zu rotieren +/usr/local/bin/mua --check-config +# Erst nach bewusster Freigabe: +/etc/rc.d/rc.mua restart +``` + +## Client-Trust und echte Abnahme + +Das Serverzertifikat muss zum Namen in der URL passen und der **Clientprozess** +muss seiner CA vertrauen. Bei privater CA deren **öffentliches CA-Zertifikat** +in den Truststore des jeweiligen Clients bzw. seines Containers aufnehmen, nicht +nur auf dem NAS. Browser, CLI, Hermes und andere Container können verschiedene +Truststores verwenden. Niemals private Keys an Clients verteilen, keine +`verify=false`-/`-k`-Dauerlösung und keinen Token vor erfolgreicher TLS-Prüfung senden. + +```bash +# Öffentliche CA: normalerweise ohne --cacert. +# Private CA / isolierter Selbstsignatur-Test: bewusst passendes öffentliches CA-PEM. +curl --fail --cacert /client/pfad/ca.pem https://NAME:3002/health +openssl s_client -connect NAME:3002 -servername NAME \ + -verify_hostname NAME -verify_return_error -CAfile /client/pfad/ca.pem true, CURLOPT_TIMEOUT => 5, CURLOPT_CONNECTTIMEOUT => 2, CURLOPT_HTTPHEADER => $headers]; + $options = [CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 5, CURLOPT_CONNECTTIMEOUT => 2, CURLOPT_HTTPHEADER => $headers, CURLOPT_PROXY => '']; if ($method === 'POST') { $options[CURLOPT_POST] = true; if ($payload !== null) { @@ -40,13 +39,11 @@ function csrf_value($token, $offset = 0) { return hash_hmac('sha256', gmdate('Y-m-d-H', time() + $offset * 3600), $token); } -function mua_health($port) { - $ch = curl_init('http://127.0.0.1:' . $port . '/health'); - curl_setopt_array($ch, [CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 3, CURLOPT_CONNECTTIMEOUT => 2]); - $raw = curl_exec($ch); - $code = curl_getinfo($ch, CURLINFO_HTTP_CODE); - curl_close($ch); - return $code === 200 && $raw !== false ? json_decode($raw, true) : null; +function mua_health($config_port, $admin_token) { + // Readiness via the protected loopback channel. No insecure TLS bypass or + // plaintext probe against a configured HTTPS MCP endpoint. + [$code, $status] = mua_api('GET', '/status', null, $admin_token, $config_port); + return $code === 200 && is_array($status) ? $status : null; } $running = false; @@ -56,9 +53,11 @@ if (file_exists($pidfile)) { $running = $pid && is_numeric($pid) && @posix_kill((int)$pid, 0); } -$health_data = mua_health($port); +$health_data = mua_health($config_port, $admin_token); $health_ok = is_array($health_data) && ($health_data['status'] ?? '') === 'ok'; $running_version = $health_data['version'] ?? ''; +$scheme = ($health_data['scheme'] ?? '') === 'https' ? 'https' : 'http'; +$endpoint = $health_ok ? $scheme . '://' . (str_contains($host_ip, ':') ? '[' . $host_ip . ']' : $host_ip) . ':' . ($health_data['port'] ?? $port) . '/mcp' : 'Nicht verfügbar – Dienst/Logs prüfen'; [$config_code, $config] = mua_api('GET', '/config', null, $admin_token, $config_port); $config_ok = $config_code === 200 && is_array($config); $flash_msg = ''; @@ -97,6 +96,11 @@ if ($_SERVER['REQUEST_METHOD'] === 'POST') { if ($action === 'preset_none') $payload = ['enabledTools' => [], 'allToolsEnabled' => false]; if ($action === 'preset_all') $payload = ['enabledTools' => [], 'allToolsEnabled' => true]; if ($action === 'save_toolbox') $payload = ['toolboxEnabled' => isset($_POST['toolbox_enabled'])]; + if ($action === 'save_tls') $payload = ['tls' => [ + 'enabled' => isset($_POST['tls_enabled']), + 'certFile' => $_POST['tls_cert_file'] ?? '', + 'keyFile' => $_POST['tls_key_file'] ?? '', + ]]; if ($action === 'save_tools') { $selected = []; foreach (($config['allTools'] ?? []) as $tool) { @@ -108,24 +112,27 @@ if ($_SERVER['REQUEST_METHOD'] === 'POST') { if ($action === 'restart') { [$code, $result] = mua_api('POST', '/restart', null, $admin_token, $config_port); - $flash_msg = $code === 200 ? 'MUA wird neu gestartet.' : 'Neustart fehlgeschlagen (HTTP ' . $code . ').'; + $flash_msg = $code === 200 ? 'MUA wird neu gestartet.' : 'Neustart fehlgeschlagen (HTTP ' . $code . ').' . (is_string($result['error'] ?? null) ? ' ' . $result['error'] : ''); $flash_type = $code === 200 ? 'ok' : 'err'; } elseif ($payload !== null) { [$code, $result] = mua_api('POST', '/config', $payload, $admin_token, $config_port); if ($code === 200 && is_array($result) && ($result['ok'] ?? false)) { $new_api_key = $result['generatedApiKey'] ?? ''; - $flash_msg = $new_api_key ? 'Neuer API-Key erzeugt. Jetzt kopieren – er wird nur dieses eine Mal angezeigt.' : 'Sicherheitseinstellungen gespeichert.'; + $flash_msg = $action === 'save_tls' ? 'TLS-Einstellungen geprüft und gespeichert. Zum Anwenden Dienst ausdrücklich neu starten.' : ($new_api_key ? 'Neuer API-Key erzeugt. Jetzt kopieren – er wird nur dieses eine Mal angezeigt.' : 'Sicherheitseinstellungen gespeichert.'); $flash_type = 'ok'; [$config_code, $config] = mua_api('GET', '/config', null, $admin_token, $config_port); $config_ok = $config_code === 200 && is_array($config); } else { - $flash_msg = 'Speichern fehlgeschlagen (HTTP ' . $code . ').'; + $flash_msg = 'Speichern fehlgeschlagen (HTTP ' . $code . ').' . ($action === 'save_tls' && is_string($result['error'] ?? null) ? ' ' . $result['error'] : ''); $flash_type = 'err'; } } } } +$transport = is_array($config['transport'] ?? null) ? $config['transport'] : []; +$tls = is_array($transport['tls'] ?? null) ? $transport['tls'] : []; +$tls_locked = !$config_ok || !empty($transport['envOverride']); $enabled_tools = $config['enabledTools'] ?? []; $all_tools_enabled = (bool)($config['allToolsEnabled'] ?? false); $all_tools = $config['allTools'] ?? []; @@ -159,13 +166,27 @@ $active_count = $all_tools_enabled ? count($all_tools) : count($enabled_tools);
Neuer API-Key – einmalige Anzeige
-

Dienst

Version · PID
+

Dienst

Version · PID

Zugriffsprofil

von Werkzeugen aktiv

Authentifizierung

MCP-Endpunkt

Streamable HTTP · JSON-RPC 2.0 · Bearer-Authentifizierung erforderlich

+

HTTPS / TLS

+

Aktiver Transport: . TLS schützt denselben MCP-Port inklusive /health; Bearer-Key und Toolfreigaben bleiben unverändert.

+
Gespeicherte Einstellungen sind noch nicht aktiv. Nach Prüfung Dienst ausdrücklich neu starten.
+
+

Durch Umgebungsvariablen verwaltet; WebGUI-Änderung gesperrt.

+
+
>TLS-Konfiguration + +

+

+
+

Nur Pfade, keine Schlüssel hochladen/einfügen. Dateien müssen beim Boot bereits lesbar sein. Clients benötigen die passende CA und einen Hostnamen/IP im Zertifikat-SAN; die angezeigte Server-IP gegebenenfalls durch den Zertifikat-DNS-Namen ersetzen. Zertifikatserneuerung erfordert Prüfung und Neustart. Verwaltung bleibt HTTP auf 127.0.0.1:. Lokale Bereitschaft ist kein Client-Trust-Test.

+
+

Agent-Werkzeugcontainer

✅ Gefunden: $container): ?> ()

diff --git a/scripts/package.sh b/scripts/package.sh index 68a3806..673519e 100755 --- a/scripts/package.sh +++ b/scripts/package.sh @@ -48,6 +48,9 @@ mkdir -p "${BUILD_DIR}/install" mkdir -p "${BUILD_DIR}/usr/local/bin" mkdir -p "${BUILD_DIR}/etc/rc.d" mkdir -p "${BUILD_DIR}/usr/local/emhttp/plugins/mua" +mkdir -p "${BUILD_DIR}/usr/doc/mua-${VERSION}" +cp "${ROOT}/docs/HTTPS.md" "${ROOT}/docs/HERMES.md" "${BUILD_DIR}/usr/doc/mua-${VERSION}/" +chmod 644 "${BUILD_DIR}/usr/doc/mua-${VERSION}/HTTPS.md" "${BUILD_DIR}/usr/doc/mua-${VERSION}/HERMES.md" # Binary cp "${DIST_DIR}/mua" "${BUILD_DIR}/usr/local/bin/mua" @@ -88,15 +91,16 @@ mkdir -p /boot/config/plugins/mua # Service starten /etc/rc.d/rc.mua start 2>/dev/null || true -# Health-Check +# Local readiness through the authenticated loopback management channel. +# It works for HTTP and HTTPS, but does not replace a client-side TLS test. sleep 2 -if curl -sf "http://127.0.0.1:3002/health" > /dev/null 2>&1; then +if /etc/rc.d/rc.mua health; then echo "" - echo " Health-Check: OK" - echo " Endpunkt: http://$(hostname -I | awk '{print $1}'):3002/mcp" + echo " Lokale Bereitschaft: OK (Transport siehe scheme oben)" + echo " MCP-Endpunkt und TLS-Einstellungen: Settings > User Utilities > MUA" else echo "" - echo " WARNUNG: Health-Check fehlgeschlagen" + echo " WARNUNG: Lokaler Bereitschaftstest fehlgeschlagen" echo " Logs: tail -f /var/log/plugins/mua.log" fi DOEOF diff --git a/scripts/rc.mua b/scripts/rc.mua index 6ac30a9..c535c5b 100644 --- a/scripts/rc.mua +++ b/scripts/rc.mua @@ -7,10 +7,13 @@ # Läuft das kompilierte TypeScript-Binary (Bun Runtime) — # kein PHP-Built-in-Server mehr. -DAEMON="/usr/local/bin/mua" -PIDFILE="/var/run/mua.pid" -LOGFILE="/var/log/plugins/mua.log" -PORT=3002 +DAEMON="${MUA_BINARY:-/usr/local/bin/mua}" +PIDFILE="${MUA_PIDFILE:-/var/run/mua.pid}" +LOGFILE="${MUA_LOGFILE:-/var/log/plugins/mua.log}" +PORT="${MUA_PORT:-3002}" +CONFIG_PORT="${MUA_CONFIG_PORT:-3013}" +ADMIN_TOKEN_FILE="${MUA_ADMIN_TOKEN_FILE:-/var/run/mua-admin.token}" +CONFIG_DIR="${MUA_CONFIG_DIR:-/boot/config/plugins/mua}" start() { if [ -f "$PIDFILE" ] && kill -0 "$(cat "$PIDFILE")" 2>/dev/null; then @@ -22,7 +25,11 @@ start() { return 1 fi # Config-Verzeichnis sicherstellen (für API-Key) - mkdir -p /boot/config/plugins/mua + mkdir -p "$CONFIG_DIR" "$(dirname "$LOGFILE")" "$(dirname "$PIDFILE")" + "$DAEMON" --check-config >> "$LOGFILE" 2>&1 || { + echo " FEHLER: TLS-Konfiguration ungültig; Logs prüfen. Kein HTTP-Fallback." + return 1 + } # Server starten (detached) (cd / && exec env MUA_PORT="$PORT" nohup "$DAEMON") >> "$LOGFILE" 2>&1 & echo $! > "$PIDFILE" @@ -33,6 +40,7 @@ start() { else echo " FEHLER: MUA konnte nicht gestartet werden" cat "$LOGFILE" 2>/dev/null | tail -5 + rm -f "$PIDFILE" return 1 fi } @@ -47,7 +55,7 @@ stop() { echo " MUA gestoppt (PID $pid)" fi rm -f "$PIDFILE" - rm -f /var/run/mua-admin.token + rm -f "$ADMIN_TOKEN_FILE" else # Fallback: per Port suchen local pid=$(lsof -ti :$PORT 2>/dev/null) @@ -57,7 +65,7 @@ stop() { else echo " MUA läuft nicht" fi - rm -f /var/run/mua-admin.token + rm -f "$ADMIN_TOKEN_FILE" fi } @@ -71,13 +79,33 @@ status() { fi } +health() { + # Local readiness only, not a remote TLS trust test. Keep the admin token + # off curl's argv and never disable certificate verification on MCP. + local token + [ -r "$ADMIN_TOKEN_FILE" ] || return 1 + IFS= read -r token < "$ADMIN_TOKEN_FILE" + [[ "$token" =~ ^[a-f0-9]{64}$ ]] || return 1 + printf 'header = "X-MUA-Admin-Token: %s"\n' "$token" | + curl -fsS --noproxy '*' --connect-timeout 2 --max-time 5 --config - "http://127.0.0.1:${CONFIG_PORT}/status" +} + case "$1" in start) start ;; stop) stop ;; - restart) stop; start ;; + restart) + # Renewal preflight before stopping the currently healthy process. + if "$DAEMON" --check-config >> "$LOGFILE" 2>&1; then + stop; start + else + echo " FEHLER: Konfiguration ungültig; laufender Dienst bleibt unverändert." + exit 1 + fi + ;; status) status ;; + health) health ;; *) - echo "Usage: $0 {start|stop|restart|status}" + echo "Usage: $0 {start|stop|restart|status|health}" exit 1 ;; esac diff --git a/src/index.ts b/src/index.ts index ec022a0..0a6c652 100644 --- a/src/index.ts +++ b/src/index.ts @@ -35,6 +35,20 @@ import { randomBytes } from "node:crypto"; import { spawn } from "node:child_process"; import { appendFile, chmodSync, statSync, writeFileSync } from "node:fs"; import { ToolCallGate, withHardTimeout } from "./concurrency"; +import { readTLSSettings, saveTLSSettings, tlsEnvOverride, tlsOptions, TLSConfigurationError } from "./tls"; + +if (process.argv.includes("--check-config")) { + try { + const settings = readTLSSettings(); + tlsOptions(settings); + console.log(`[MUA] TLS-Konfiguration OK (${settings.enabled ? "HTTPS" : "HTTP"}).`); + process.exit(0); + } catch (error) { + console.error("[MUA] Konfigurationsprüfung fehlgeschlagen. " + + (error instanceof TLSConfigurationError ? error.message : "TLS-Konfiguration prüfen.")); + process.exit(1); + } +} const PORT = Number(process.env["MUA_PORT"] ?? 3002); const HOST = process.env["MUA_HOST"] ?? "0.0.0.0"; @@ -282,8 +296,16 @@ async function handleMcpRequest( return null; } -// ── HTTP Server (Bun.serve — production-grade) ────────────────────────── -const server = Bun.serve({ +// ── HTTP(S) Server (Bun.serve — production-grade) ──────────────────────── +// Validate TLS before opening either listener. Configured HTTPS must never +// degrade to plaintext, even when a certificate is missing after reboot. +let activeTLS: ReturnType; +let server: ReturnType; +try { + activeTLS = readTLSSettings(); + const tls = tlsOptions(activeTLS); + server = Bun.serve({ + ...(tls ? { tls } : {}), port: PORT, hostname: HOST, idleTimeout: 120, // Sekunden (für lange docker stats / audit) @@ -441,7 +463,22 @@ const server = Bun.serve({ { status: 404, headers: corsHeaders }, ); }, -}); + }); +} catch (error) { + console.error("[MUA] Start abgebrochen; kein HTTP-Fallback. " + + (error instanceof TLSConfigurationError ? error.message : "MCP-Listener konnte nicht gestartet werden (TLS/Port prüfen).")); + process.exit(1); +} + +function transportStatus() { + let tls = activeTLS; + let error: string | undefined; + try { tls = readTLSSettings(); } + catch { error = "Gespeicherte TLS-Konfiguration ist ungültig oder nicht lesbar; vor Neustart prüfen."; } + return { scheme: activeTLS.enabled ? "https" : "http", port: PORT, tls, + restartRequired: !!error || JSON.stringify(tls) !== JSON.stringify(activeTLS), + envOverride: tlsEnvOverride(), ...(error ? { error } : {}) }; +} // ── Config-Server (nur localhost:127.0.0.1:3013) ─────────────────────── // Separater Server, nur von localhost erreichbar (WebGUI auf demselben Host). @@ -468,7 +505,7 @@ try { const path = url.pathname; const method = req.method; - if (path !== "/config" && path !== "/restart") { + if (path !== "/config" && path !== "/restart" && path !== "/status") { return Response.json({ error: "Not found" }, { status: 404 }); } @@ -476,8 +513,18 @@ try { return Response.json({ error: "Unauthorized" }, { status: 401 }); } + if (path === "/status") { + return method === "GET" + ? Response.json({ status: "ok", version: MUA_VERSION, scheme: activeTLS.enabled ? "https" : "http", port: PORT }) + : Response.json({ error: "Method not allowed" }, { status: 405 }); + } + // POST /restart: Service neu starten (für WebGUI-Button) if (path === "/restart" && method === "POST") { + try { tlsOptions(readTLSSettings()); } + catch (error) { + return Response.json({ error: error instanceof TLSConfigurationError ? error.message : "TLS-Konfiguration ungültig; kein Neustart." }, { status: 400 }); + } const rcScript = process.env["MUA_RC_SCRIPT"] ?? "/etc/rc.d/rc.mua"; try { const child = spawn(rcScript, ["restart"], { @@ -497,6 +544,7 @@ try { return Response.json({ apiKeyConfigured: true, apiKeyMasked: getMaskedApiKey(), + transport: transportStatus(), enabledTools: getEnabledTools(), allToolsEnabled: getAllToolsEnabled(), allTools: TOOLS.filter((t) => !TOOLBOX_TOOL_NAMES.has(t.name)).map((t) => ({ @@ -523,6 +571,18 @@ try { return Response.json({ error: "Invalid JSON" }, { status: 400 }); } + if (body && Object.prototype.hasOwnProperty.call(body, "tls")) { + if (Object.keys(body).some((key) => key !== "tls")) { + return Response.json({ error: "TLS separat von Auth-/Tool-Einstellungen speichern." }, { status: 400 }); + } + try { + saveTLSSettings(body["tls"]); + return Response.json({ ok: true, transport: transportStatus() }); + } catch (error) { + return Response.json({ error: error instanceof TLSConfigurationError ? error.message : "TLS konnte nicht gespeichert werden." }, { status: 400 }); + } + } + // "generate": neuen API-Key generieren let generatedApiKey: string | undefined; if (body["generate"] === true) generatedApiKey = generateApiKey(); @@ -544,6 +604,7 @@ try { ok: true, generatedApiKey, apiKeyMasked: getMaskedApiKey(), + transport: transportStatus(), enabledTools: getEnabledTools(), allToolsEnabled: getAllToolsEnabled(), toolbox: { @@ -567,7 +628,7 @@ try { } console.log( - `[MUA] ${MUA_SERVER_NAME} v${MUA_VERSION} listening on ${HOST}:${PORT} (MCP)` + + `[MUA] ${MUA_SERVER_NAME} v${MUA_VERSION} listening on ${activeTLS.enabled ? "https" : "http"}://${HOST}:${PORT} (MCP)` + (configServer ? ` + 127.0.0.1:${CONFIG_PORT} (config)` : " (config: NICHT VERFÜGBAR)"), ); diff --git a/src/tls.test.ts b/src/tls.test.ts new file mode 100644 index 0000000..65793ce --- /dev/null +++ b/src/tls.test.ts @@ -0,0 +1,444 @@ +import { afterAll, beforeAll, expect, test } from "bun:test"; +import { chmodSync, mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { connect } from "node:net"; +import { request } from "node:https"; + +// All listeners, certificates, tokens and tool data in this suite are synthetic. +let root: string; +let cert: string; +let key: string; +const testToken = "synthetic-mua-transport-test"; + +function openssl(...args: string[]) { + const result = Bun.spawnSync(["openssl", ...args], { stdout: "pipe", stderr: "pipe" }); + if (result.exitCode !== 0) throw new Error(result.stderr.toString()); +} + +beforeAll(() => { + root = mkdtempSync(join(tmpdir(), "mua-tls-test-")); + cert = join(root, "server.pem"); + key = join(root, "server.key"); + openssl("req", "-x509", "-newkey", "ec", "-pkeyopt", "ec_paramgen_curve:P-256", "-nodes", + "-days", "2", "-subj", "/CN=localhost", "-addext", "subjectAltName=DNS:localhost,IP:127.0.0.1", + "-keyout", key, "-out", cert); + chmodSync(key, 0o600); + mkdirSync(join(root, "bin")); + writeFileSync(join(root, "bin/docker"), "#!/bin/sh\nprintf '[]'\n", { mode: 0o755 }); +}); +afterAll(() => rmSync(root, { recursive: true, force: true })); + +async function freePort(): Promise { + const probe = Bun.serve({ hostname: "127.0.0.1", port: 0, fetch: () => new Response() }); + const port = probe.port!; + await probe.stop(true); + return port; +} + +async function tcpReady(port: number): Promise { + return new Promise((resolve) => { + const socket = connect({ host: "127.0.0.1", port }); + socket.setTimeout(100); + socket.once("connect", () => { socket.destroy(); resolve(true); }); + socket.once("error", () => { socket.destroy(); resolve(false); }); + socket.once("timeout", () => { socket.destroy(); resolve(false); }); + }); +} + +async function start(tlsConfig: string | null, overrides: Record = {}) { + const dir = mkdtempSync(join(root, "instance-")); + if (tlsConfig !== null) writeFileSync(join(dir, "tls.conf"), tlsConfig); + const port = await freePort(); + const configPort = await freePort(); + const entry = process.env.MUA_TEST_BINARY; + const child = Bun.spawn(entry ? [entry] : [process.execPath, join(import.meta.dir, "index.ts")], { + env: { ...process.env, MUA_TLS_ENABLED: undefined, MUA_TLS_CERT_FILE: undefined, + MUA_TLS_KEY_FILE: undefined, MUA_CONFIG_DIR: dir, MUA_PORT: String(port), + MUA_HOST: "127.0.0.1", MUA_CONFIG_PORT: String(configPort), + MUA_API_KEY: testToken, MUA_ENABLED_TOOLS: "unraid_system_shell_readonly", + MUA_ADMIN_TOKEN_FILE: join(dir, "admin.token"), MUA_AUDIT_LOG: join(dir, "audit.log"), + MUA_BINARY: join(dir, "no-update-binary"), PATH: join(root, "bin") + ":" + process.env.PATH, + ...overrides }, stdout: "pipe", stderr: "pipe", + }); + const stdout = new Response(child.stdout).text(); + const stderr = new Response(child.stderr).text(); + const deadline = performance.now() + 5000; + while (performance.now() < deadline && child.exitCode === null) { + if (await tcpReady(port) && await tcpReady(configPort)) break; + await Bun.sleep(20); + } + return { child, dir, port, configPort, stdout, stderr, async stop() { + child.kill(); + await child.exited; + } }; +} + +function httpsJson(port: number, path: string, body?: unknown, token?: string, ca = readFileSync(cert)): + Promise<{ status: number; data: any; headers: Record }> { + return new Promise((resolve, reject) => { + const req = request({ hostname: "127.0.0.1", port, path, method: body ? "POST" : "GET", + ca, rejectUnauthorized: true, headers: { + ...(body ? { "Content-Type": "application/json", Accept: "application/json, text/event-stream" } : {}), + ...(token ? { Authorization: `Bearer ${token}` } : {}), + }, timeout: 2000 }, (res) => { + let text = ""; + res.setEncoding("utf8"); + res.on("data", (part) => { text += part; }); + res.on("end", () => { + try { resolve({ status: res.statusCode!, data: JSON.parse(text), headers: res.headers }); } + catch (error) { reject(error); } + }); + }); + req.on("error", reject); + req.on("timeout", () => req.destroy(new Error("HTTPS test timed out"))); + if (body) req.write(JSON.stringify(body)); + req.end(); + }); +} + +test("local status authenticates admin token and reports actual HTTPS without PEM material", async () => { + const app = await start(tlsConfig()); + try { + const url = `http://127.0.0.1:${app.configPort}/status`; + expect((await fetch(url)).status).toBe(401); + const token = readFileSync(join(app.dir, "admin.token"), "utf8").trim(); + const response = await fetch(url, { headers: { "X-MUA-Admin-Token": token } }); + expect(response.status).toBe(200); + const status = await response.json() as any; + expect(status.status).toBe("ok"); + expect(status.scheme).toBe("https"); + expect(status.port).toBe(app.port); + expect(JSON.stringify(status)).not.toContain("PRIVATE KEY"); + expect(JSON.stringify(status)).not.toContain(testToken); + } finally { await app.stop(); } +}, 10_000); + +test("--check-config validates certificates and exits without opening listeners", async () => { + const dir = mkdtempSync(join(root, "preflight-")); + const port = await freePort(); + writeFileSync(join(dir, "tls.conf"), tlsConfig()); + const entry = process.env.MUA_TEST_BINARY; + const child = Bun.spawn(entry ? [entry, "--check-config"] : [process.execPath, join(import.meta.dir, "index.ts"), "--check-config"], { + env: { ...process.env, MUA_CONFIG_DIR: dir, MUA_PORT: String(port), MUA_HOST: "127.0.0.1", + MUA_CONFIG_PORT: String(await freePort()), MUA_ADMIN_TOKEN_FILE: join(dir, "admin.token") }, stdout: "pipe", stderr: "pipe", + }); + try { + const exit = await Promise.race([child.exited, Bun.sleep(500).then(() => "still-running")]); + expect(exit).toBe(0); + expect(await tcpReady(port)).toBe(false); + expect(await new Response(child.stderr).text()).toBe(""); + } finally { child.kill(); await child.exited; } +}, 5000); + +test("SysV health uses local authenticated status even when MCP requires HTTPS", async () => { + const app = await start(tlsConfig()); + try { + const result = Bun.spawnSync(["bash", join(import.meta.dir, "../scripts/rc.mua"), "health"], { + env: { ...process.env, MUA_CONFIG_PORT: String(app.configPort), MUA_ADMIN_TOKEN_FILE: join(app.dir, "admin.token"), + http_proxy: "http://127.0.0.1:1", no_proxy: "", NO_PROXY: "" }, + stdout: "pipe", stderr: "pipe", + }); + expect(result.exitCode).toBe(0); + const status = JSON.parse(result.stdout.toString()); + expect(status.scheme).toBe("https"); + expect(status.status).toBe("ok"); + expect(result.stdout.toString()).not.toContain(readFileSync(join(app.dir, "admin.token"), "utf8").trim()); + } finally { await app.stop(); } +}, 10_000); + +test("WebGUI renders HTTPS settings and active endpoint through the local config server", async () => { + const app = await start(tlsConfig()); + try { + const html = renderWebGUI(app); + expect(html.includes(`https://127.0.0.1:${app.port}/mcp`)).toBe(true); + expect(html).toContain('name="tls_cert_file"'); + expect(html).toContain('name="tls_key_file"'); + expect(html).toContain('name="tls_enabled"'); + expect(html).toContain(cert); + expect(html).not.toContain(readFileSync(key, "utf8").trim()); + } finally { await app.stop(); } +}, 10_000); + +test("SysV restart preflights bad renewed certificates before stopping a healthy HTTPS listener", async () => { + const dir = mkdtempSync(join(root, "service-")); + const port = await freePort(); + const configPort = await freePort(); + const wrapper = join(dir, "daemon"); + const quote = (s: string) => "'" + s.replaceAll("'", "'\\''") + "'"; + const command = process.env.MUA_TEST_BINARY ? quote(process.env.MUA_TEST_BINARY) : `${quote(process.execPath)} ${quote(join(import.meta.dir, "index.ts"))}`; + writeFileSync(wrapper, `#!/bin/sh\nexec ${command} "$@"\n`, { mode: 0o755 }); + writeFileSync(join(dir, "tls.conf"), tlsConfig()); + const env = { ...process.env, MUA_BINARY: wrapper, MUA_CONFIG_DIR: dir, MUA_HOST: "127.0.0.1", + MUA_PORT: String(port), MUA_CONFIG_PORT: String(configPort), MUA_PIDFILE: join(dir, "mua.pid"), + MUA_LOGFILE: join(dir, "mua.log"), MUA_ADMIN_TOKEN_FILE: join(dir, "admin.token"), + MUA_AUDIT_LOG: join(dir, "audit.log"), MUA_API_KEY: testToken, MUA_ENABLED_TOOLS: "none" }; + const service = (action: string) => Bun.spawnSync(["bash", join(import.meta.dir, "../scripts/rc.mua"), action], + { env, stdout: "pipe", stderr: "pipe" }); + try { + expect(service("start").exitCode).toBe(0); + expect((await httpsJson(port, "/health")).status).toBe(200); + writeFileSync(join(dir, "tls.conf"), tlsConfig(cert, join(root, "absent-renewal.key"))); + expect(service("restart").exitCode).not.toBe(0); + expect((await httpsJson(port, "/health")).status).toBe(200); + const renewedCert = join(dir, "renewed.pem"); + const renewedKey = join(dir, "renewed.key"); + openssl("req", "-x509", "-newkey", "ec", "-pkeyopt", "ec_paramgen_curve:P-256", "-nodes", "-days", "2", + "-subj", "/CN=localhost", "-addext", "subjectAltName=DNS:localhost,IP:127.0.0.1", "-keyout", renewedKey, "-out", renewedCert); + writeFileSync(join(dir, "tls.conf"), tlsConfig(renewedCert, renewedKey)); + expect(service("restart").exitCode).toBe(0); + expect((await httpsJson(port, "/health", undefined, undefined, readFileSync(renewedCert))).status).toBe(200); + await expect(httpsJson(port, "/health")).rejects.toThrow(); + } finally { service("stop"); } +}, 10_000); + +test("WebGUI enforces CSRF and saves TLS separately, with clear invalid-certificate errors", async () => { + const app = await start(""); + try { + const html = renderWebGUI(app); + const csrf = /name="mua_csrf" value="([a-f0-9]+)"/.exec(html)![1]; + const fields = { action: "save_tls", tls_enabled: "on", tls_cert_file: cert, tls_key_file: key }; + expect(renderWebGUI(app, { ...fields, mua_csrf: "invalid" }).includes("Sicherheitsprüfung fehlgeschlagen")).toBe(true); + expect(readFileSync(join(app.dir, "tls.conf"), "utf8")).toBe(""); + const saved = renderWebGUI(app, { ...fields, mua_csrf: csrf }); + expect(saved.includes("TLS-Einstellungen geprüft und gespeichert")).toBe(true); + expect(saved.includes("noch nicht aktiv")).toBe(true); + const content = readFileSync(join(app.dir, "tls.conf"), "utf8"); + const invalid = renderWebGUI(app, { ...fields, tls_key_file: join(root, "missing.key"), mua_csrf: csrf }); + expect(invalid.includes("PEM-Datei fehlt")).toBe(true); + expect(readFileSync(join(app.dir, "tls.conf"), "utf8")).toBe(content); + } finally { await app.stop(); } +}, 10_000); + +test("TLS environment overrides take precedence and prevent conflicting WebGUI saves", async () => { + const app = await start(tlsConfig(join(root, "absent.pem")), { MUA_TLS_ENABLED: "false" }); + try { + expect((await fetch(`http://127.0.0.1:${app.port}/health`)).status).toBe(200); + const token = readFileSync(join(app.dir, "admin.token"), "utf8").trim(); + const url = `http://127.0.0.1:${app.configPort}/config`; + const before = readFileSync(join(app.dir, "tls.conf"), "utf8"); + const result = await fetch(url, { method: "POST", headers: { "X-MUA-Admin-Token": token, + "Content-Type": "application/json" }, body: JSON.stringify({ tls: { enabled: true, certFile: cert, keyFile: key } }) }); + expect(result.status).toBe(400); + expect(readFileSync(join(app.dir, "tls.conf"), "utf8")).toBe(before); + expect(renderWebGUI(app).includes("WebGUI-Änderung gesperrt")).toBe(true); + } finally { await app.stop(); } +}, 10_000); + +test("invalid TLS admin input never alters persisted TLS or permissions", async () => { + const app = await start(""); + try { + const token = readFileSync(join(app.dir, "admin.token"), "utf8").trim(); + for (const tls of [null, [], { enabled: "true", certFile: cert, keyFile: key }, + { enabled: true, certFile: cert, keyFile: join(root, "absent.key") }, + { enabled: false, certFile: cert + "\nMUA_TLS_ENABLED=true", keyFile: key }]) { + const response = await fetch(`http://127.0.0.1:${app.configPort}/config`, { method: "POST", + headers: { "X-MUA-Admin-Token": token, "Content-Type": "application/json" }, body: JSON.stringify({ tls }) }); + expect(response.status).toBe(400); + expect(readFileSync(join(app.dir, "tls.conf"), "utf8")).toBe(""); + } + expect((await fetch(`http://127.0.0.1:${app.port}/health`)).status).toBe(200); + } finally { await app.stop(); } +}, 10_000); + +test("admin restart rejects invalid renewed TLS before spawning the service script", async () => { + const app = await start(tlsConfig(), { MUA_RC_SCRIPT: join(root, "no-such-service-script") }); + try { + writeFileSync(join(app.dir, "tls.conf"), tlsConfig(cert, join(root, "missing.key"))); + const token = readFileSync(join(app.dir, "admin.token"), "utf8").trim(); + const response = await fetch(`http://127.0.0.1:${app.configPort}/restart`, { method: "POST", + headers: { "X-MUA-Admin-Token": token } }); + expect(response.status).toBe(400); + expect((await httpsJson(app.port, "/health")).status).toBe(200); + } finally { await app.stop(); } +}, 10_000); + +test("native HTTPS sends intermediate certificates for a privately issued full chain", async () => { + const dir = mkdtempSync(join(root, "chain-")); + const intermediate = join(dir, "intermediate.pem"); + const intermediateKey = join(dir, "intermediate.key"); + const intermediateCSR = join(dir, "intermediate.csr"); + openssl("req", "-new", "-newkey", "ec", "-pkeyopt", "ec_paramgen_curve:P-256", "-nodes", + "-subj", "/CN=MUA synthetic intermediate", "-keyout", intermediateKey, "-out", intermediateCSR); + const extensions = join(dir, "extensions.cnf"); + writeFileSync(extensions, "[ca]\nbasicConstraints=critical,CA:TRUE,pathlen:0\nkeyUsage=critical,keyCertSign,cRLSign\n[server]\nbasicConstraints=critical,CA:FALSE\nkeyUsage=critical,digitalSignature\nextendedKeyUsage=serverAuth\nsubjectAltName=DNS:localhost,IP:127.0.0.1\n"); + openssl("x509", "-req", "-in", intermediateCSR, "-CA", cert, "-CAkey", key, "-set_serial", "2", + "-days", "2", "-extfile", extensions, "-extensions", "ca", "-out", intermediate); + const leafKey = join(dir, "leaf.key"); + const leafCSR = join(dir, "leaf.csr"); + const leaf = join(dir, "leaf.pem"); + openssl("req", "-new", "-newkey", "ec", "-pkeyopt", "ec_paramgen_curve:P-256", "-nodes", + "-subj", "/CN=localhost", "-keyout", leafKey, "-out", leafCSR); + openssl("x509", "-req", "-in", leafCSR, "-CA", intermediate, "-CAkey", intermediateKey, "-set_serial", "3", + "-days", "1", "-extfile", extensions, "-extensions", "server", "-out", leaf); + const chain = join(dir, "fullchain.pem"); + writeFileSync(chain, readFileSync(leaf, "utf8") + readFileSync(intermediate, "utf8")); + const app = await start(tlsConfig(chain, leafKey)); + try { expect((await httpsJson(app.port, "/health")).status).toBe(200); } + finally { await app.stop(); } +}, 10_000); + +function renderWebGUI(app: { port: number; configPort: number; dir: string }, post?: Record) { + const result = Bun.spawnSync(["php", "-r", '$_SERVER["REQUEST_METHOD"]=$argc>2?"POST":"GET"; $_SERVER["SERVER_ADDR"]="127.0.0.1"; $var=["csrf_token"=>"synthetic"]; if($argc>2) $_POST=json_decode($argv[2],true); require $argv[1];', + join(import.meta.dir, "../scripts/mua.page"), ...(post ? [JSON.stringify(post)] : [])], { + env: { ...process.env, MUA_PORT: String(app.port), MUA_CONFIG_PORT: String(app.configPort), + MUA_ADMIN_TOKEN_FILE: join(app.dir, "admin.token"), MUA_PIDFILE: join(app.dir, "pid"), + http_proxy: "http://127.0.0.1:1", no_proxy: "", NO_PROXY: "" }, + stdout: "pipe", stderr: "pipe", + }); + if (result.exitCode !== 0 || result.stderr.length) throw new Error(result.stderr.toString()); + return result.stdout.toString(); +} + +function tlsConfig(certFile = cert, keyFile = key) { + return `MUA_TLS_ENABLED=true\nMUA_TLS_CERT_FILE=${certFile}\nMUA_TLS_KEY_FILE=${keyFile}\n`; +} + +test("native HTTPS serves health with a verified certificate and authenticated MCP tool call", async () => { + const app = await start(tlsConfig()); + try { + const health = await httpsJson(app.port, "/health"); + expect(health.status).toBe(200); + expect(health.data.auth).toBe("required"); + const init = await httpsJson(app.port, "/mcp", { jsonrpc: "2.0", id: 1, method: "initialize", + params: { protocolVersion: "2025-03-26", capabilities: {}, clientInfo: { name: "tls-test", version: "1" } } }, testToken); + expect(init.status).toBe(200); + expect(init.data.result.serverInfo.name).toBeDefined(); + expect(init.headers["mcp-session-id"]).toBeTruthy(); + const list = await httpsJson(app.port, "/mcp", { jsonrpc: "2.0", id: 2, method: "tools/list" }, testToken); + expect(list.data.result.tools.map((tool: any) => tool.name)).toEqual(["unraid_files_inventory", "unraid_system_shell_readonly"]); + const result = await httpsJson(app.port, "/mcp", { jsonrpc: "2.0", id: 3, method: "tools/call", + params: { name: "unraid_system_shell_readonly", arguments: { program: "ls", args: ["-ld", app.dir] } } }, testToken); + expect(result.data.result.isError).toBeUndefined(); + expect(JSON.parse(result.data.result.content[0].text).exit_code).toBe(0); + expect((await httpsJson(app.port, "/mcp", { method: "ping" })).status).toBe(401); + expect((await httpsJson(app.port, "/mcp", { method: "ping" }, "incorrect")).status).toBe(401); + const blocked = await httpsJson(app.port, "/mcp", { jsonrpc: "2.0", id: 4, method: "tools/call", + params: { name: "unraid_system_shell", arguments: { command: "must-not-execute" } } }, testToken); + expect(blocked.data.result.isError).toBe(true); + expect(blocked.data.result.content[0].text).toContain("Tool disabled"); + } finally { await app.stop(); } +}, 10_000); + +test("local admin stages validated TLS without changing auth or the active listener", async () => { + const app = await start(""); + try { + const authFile = join(app.dir, "mua.conf"); + const authContents = "# synthetic existing credentials and permissions\nMUA_API_KEY=synthetic\nMUA_ENABLED_TOOLS=none\n"; + writeFileSync(authFile, authContents); + const admin = readFileSync(join(app.dir, "admin.token"), "utf8").trim(); + const url = `http://127.0.0.1:${app.configPort}/config`; + const before = await fetch(url, { headers: { "X-MUA-Admin-Token": admin } }); + expect((await before.json() as any).transport.scheme).toBe("http"); + const response = await fetch(url, { method: "POST", headers: { "X-MUA-Admin-Token": admin, + "Content-Type": "application/json" }, body: JSON.stringify({ tls: { enabled: true, certFile: cert, keyFile: key } }) }); + expect(response.status).toBe(200); + const result = await response.json() as any; + expect(result.transport.scheme).toBe("http"); + expect(result.transport.tls.enabled).toBe(true); + expect(result.transport.restartRequired).toBe(true); + expect(readFileSync(authFile, "utf8")).toBe(authContents); + expect(readFileSync(join(app.dir, "tls.conf"), "utf8")).toContain("MUA_TLS_ENABLED=true"); + expect((await fetch(`http://127.0.0.1:${app.port}/health`)).status).toBe(200); + } finally { await app.stop(); } +}, 10_000); + +for (const [name, config] of [ + ["missing certificate", () => tlsConfig(join(root, "absent.pem"))], + ["missing key", () => tlsConfig(cert, join(root, "absent.key"))], + ["unset paths", () => "MUA_TLS_ENABLED=true\n"], + ["relative path", () => tlsConfig("relative.pem")], + ["invalid boolean", () => "MUA_TLS_ENABLED=tru\n"], + ["duplicate enable flag", () => tlsConfig() + "MUA_TLS_ENABLED=false\n"], + ["malformed PEM", () => { + const path = join(root, "malformed.pem"); + writeFileSync(path, "SYNTHETIC-SECRET-MUST-NOT-APPEAR"); + return tlsConfig(path); + }], + ["mismatched key", () => { + const path = join(root, "other.key"); + openssl("genpkey", "-algorithm", "EC", "-pkeyopt", "ec_paramgen_curve:P-256", "-out", path); + return tlsConfig(cert, path); + }], + ["encrypted key", () => { + const path = join(root, "encrypted.key"); + openssl("pkey", "-in", key, "-aes-256-cbc", "-passout", "pass:synthetic-test-passphrase", "-out", path); + return tlsConfig(cert, path); + }], + ["expired certificate", () => { + const csr = join(root, "expired.csr"); + const path = join(root, "expired.pem"); + openssl("req", "-new", "-key", key, "-subj", "/CN=expired-test", "-out", csr); + const caConfig = join(root, "expiry-ca.cnf"); + writeFileSync(join(root, "expiry-index"), ""); + writeFileSync(join(root, "expiry-serial"), "01\n"); + writeFileSync(caConfig, `[ca]\ndefault_ca=test\n[test]\ndatabase=${join(root, "expiry-index")}\nserial=${join(root, "expiry-serial")}\nnew_certs_dir=${root}\ndefault_md=sha256\npolicy=policy\n[policy]\ncommonName=supplied\n`); + openssl("ca", "-selfsign", "-batch", "-config", caConfig, "-keyfile", key, "-in", csr, + "-startdate", "20200101000000Z", "-enddate", "20200102000000Z", "-out", path); + return tlsConfig(path); + }], + ["unreadable key", () => { + const path = join(root, "unreadable.key"); + writeFileSync(path, "not-readable", { mode: 0o000 }); + return tlsConfig(cert, path); + }], +] as const) { + test(`configured HTTPS fails closed for ${name}, without secret output`, async () => { + const app = await start(config()); + try { + const exit = await Promise.race([app.child.exited, Bun.sleep(1000).then(() => "still-running")]); + expect(exit).not.toBe("still-running"); + expect(exit).not.toBe(0); + expect(await tcpReady(app.port)).toBe(false); + expect(await tcpReady(app.configPort)).toBe(false); + const logs = (await app.stdout) + (await app.stderr); + expect(logs).toContain("kein HTTP-Fallback"); + expect(logs).not.toContain("SYNTHETIC-SECRET-MUST-NOT-APPEAR"); + expect(logs).not.toContain("BEGIN PRIVATE KEY"); + expect(logs).not.toContain("synthetic-test-passphrase"); + } finally { await app.stop(); } + }, 10_000); +} + +test("HTTP remains the default, including Bearer, tool dispatch and local admin protection", async () => { + const app = await start(null); + try { + const base = `http://127.0.0.1:${app.port}`; + expect((await fetch(base + "/health")).status).toBe(200); + expect((await fetch(base + "/mcp", { method: "POST", body: "{}" })).status).toBe(401); + const rpc = async (message: unknown) => (await fetch(base + "/mcp", { method: "POST", + headers: { Authorization: `Bearer ${testToken}`, "Content-Type": "application/json" }, body: JSON.stringify(message) })).json() as Promise; + expect((await rpc({ id: 1, method: "initialize", params: {} })).result.serverInfo).toBeDefined(); + const called = await rpc({ id: 2, method: "tools/call", params: { name: "unraid_system_shell_readonly", + arguments: { program: "ls", args: ["-ld", app.dir] } } }); + expect(called.result.isError).toBeUndefined(); + expect(JSON.parse(called.result.content[0].text).exit_code).toBe(0); + expect((await fetch(`http://127.0.0.1:${app.configPort}/config`)).status).toBe(401); + } finally { await app.stop(); } +}, 10_000); + +test("HTTPS rejects plaintext and untrusted clients; OpenSSL verifies TLS 1.2/1.3, not TLS 1.1", async () => { + const app = await start(tlsConfig()); + try { + await expect(fetch(`http://127.0.0.1:${app.port}/health`, { signal: AbortSignal.timeout(1500) })).rejects.toThrow(); + await expect(httpsJson(app.port, "/health", undefined, undefined, Buffer.from(""))).rejects.toThrow(); + for (const protocol of ["-tls1_2", "-tls1_3", "-tls1_1"]) { + const result = Bun.spawnSync(["openssl", "s_client", "-connect", `127.0.0.1:${app.port}`, + "-CAfile", cert, "-verify_return_error", "-verify_ip", "127.0.0.1", "-brief", "-cipher", "DEFAULT:@SECLEVEL=0", protocol], + { stdin: new Uint8Array(), stdout: "pipe", stderr: "pipe" }); + if (protocol === "-tls1_1") { + expect(result.exitCode).not.toBe(0); + expect(result.stderr.toString()).toContain("alert protocol version"); + } else { + expect(result.exitCode).toBe(0); + expect(result.stderr.toString()).toContain("Verification: OK"); + expect(result.stderr.toString()).toContain(protocol === "-tls1_2" ? "TLSv1.2" : "TLSv1.3"); + } + } + const wrongName = Bun.spawnSync(["openssl", "s_client", "-connect", `127.0.0.1:${app.port}`, + "-CAfile", cert, "-verify_return_error", "-verify_hostname", "incorrect.example.invalid", "-brief"], + { stdin: new Uint8Array(), stdout: "pipe", stderr: "pipe" }); + expect(wrongName.exitCode).not.toBe(0); + expect(wrongName.stderr.toString()).toContain("hostname mismatch"); + } finally { await app.stop(); } +}, 10_000); diff --git a/src/tls.ts b/src/tls.ts new file mode 100644 index 0000000..ca046fe --- /dev/null +++ b/src/tls.ts @@ -0,0 +1,112 @@ +import { mkdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs"; +import { isAbsolute, dirname, join } from "node:path"; +import { constants, randomBytes, X509Certificate } from "node:crypto"; +import { createSecureContext } from "node:tls"; + +export interface TLSSettings { + enabled: boolean; + certFile: string; + keyFile: string; +} + +export class TLSConfigurationError extends Error {} + +export function tlsConfigFile(): string { + return join(process.env.MUA_CONFIG_DIR ?? "/boot/config/plugins/mua", "tls.conf"); +} + +// TLS is deliberately independent of auth.ts: key rotation and tool saves must +// never erase the transport configuration. Never source this INI as shell code. +export function readTLSSettings(): TLSSettings { + const values: Record = {}; + let content = ""; + try { + content = readFileSync(tlsConfigFile(), "utf8"); + } catch (error) { + if ((error as NodeJS.ErrnoException).code !== "ENOENT") { + throw new TLSConfigurationError("TLS-Konfiguration ist nicht lesbar (tls.conf)."); + } + } + for (const line of content.split("\n")) { + const trimmed = line.trim(); + if (!trimmed || trimmed.startsWith("#")) continue; + const eq = trimmed.indexOf("="); + const name = trimmed.slice(0, eq).trim(); + if (!["MUA_TLS_ENABLED", "MUA_TLS_CERT_FILE", "MUA_TLS_KEY_FILE"].includes(name) || eq < 0) { + throw new TLSConfigurationError("Ungültige TLS-Konfiguration (tls.conf)."); + } + if (name in values) throw new TLSConfigurationError("Doppelter TLS-Konfigurationseintrag."); + values[name] = trimmed.slice(eq + 1).trim(); + } + for (const name of ["MUA_TLS_ENABLED", "MUA_TLS_CERT_FILE", "MUA_TLS_KEY_FILE"]) { + if (process.env[name] !== undefined) values[name] = process.env[name]!; + } + const enabled = values.MUA_TLS_ENABLED ?? "false"; + if (enabled !== "true" && enabled !== "false") { + throw new TLSConfigurationError("MUA_TLS_ENABLED muss true oder false sein."); + } + return { enabled: enabled === "true", certFile: values.MUA_TLS_CERT_FILE ?? "", keyFile: values.MUA_TLS_KEY_FILE ?? "" }; +} + +function readPEM(path: string, field: string): Buffer { + if (!isAbsolute(path) || /[\r\n\0]/.test(path)) { + throw new TLSConfigurationError(`${field} benötigt einen absoluten Dateipfad.`); + } + try { + const st = statSync(path); + if (!st.isFile() || st.size === 0 || st.size > 1_048_576) throw new Error(); + return readFileSync(path); + } catch { + throw new TLSConfigurationError(`${field}: PEM-Datei fehlt, ist leer, zu groß oder nicht lesbar.`); + } +} + +export function tlsEnvOverride(): boolean { + return ["MUA_TLS_ENABLED", "MUA_TLS_CERT_FILE", "MUA_TLS_KEY_FILE"].some((name) => process.env[name] !== undefined); +} + +export function saveTLSSettings(input: unknown): void { + if (tlsEnvOverride()) throw new TLSConfigurationError("TLS wird durch Umgebungsvariablen verwaltet; WebGUI-Änderung gesperrt."); + if (!input || typeof input !== "object" || Array.isArray(input)) throw new TLSConfigurationError("Ungültige TLS-Einstellungen."); + const value = input as Record; + if (typeof value.enabled !== "boolean" || typeof value.certFile !== "string" || typeof value.keyFile !== "string") { + throw new TLSConfigurationError("TLS erwartet enabled (boolean), certFile und keyFile (Dateipfade)."); + } + const settings: TLSSettings = { enabled: value.enabled, certFile: value.certFile, keyFile: value.keyFile }; + for (const path of [settings.certFile, settings.keyFile]) { + if (path.length > 4096 || /[\r\n\0]/.test(path) || path !== path.trim() || (path && !isAbsolute(path))) { + throw new TLSConfigurationError("TLS benötigt absolute Dateipfade ohne Steuerzeichen oder äußere Leerzeichen."); + } + } + tlsOptions(settings); // Validate before persisting or requesting a restart. + const file = tlsConfigFile(); + const temporary = `${file}.${randomBytes(8).toString("hex")}.tmp`; + try { + mkdirSync(dirname(file), { recursive: true }); + writeFileSync(temporary, ["# MUA TLS (separate from API key and tool permissions)", + `MUA_TLS_ENABLED=${settings.enabled}`, `MUA_TLS_CERT_FILE=${settings.certFile}`, + `MUA_TLS_KEY_FILE=${settings.keyFile}`, ""].join("\n"), { mode: 0o600, flag: "wx" }); + renameSync(temporary, file); + } catch { + throw new TLSConfigurationError("TLS-Konfiguration konnte nicht gespeichert werden."); + } finally { + rmSync(temporary, { force: true }); + } +} + +export function tlsOptions(settings: TLSSettings): Bun.TLSOptions | undefined { + if (!settings.enabled) return undefined; + const cert = readPEM(settings.certFile, "MUA_TLS_CERT_FILE"); + const key = readPEM(settings.keyFile, "MUA_TLS_KEY_FILE"); + try { + // Validates PEM, unencrypted key and matching certificate/key pair before + // opening any listener. Raw library errors can include PEM; never expose them. + createSecureContext({ cert, key, minVersion: "TLSv1.2" }); + const leaf = new X509Certificate(cert); + const now = Date.now(); + if (Date.parse(leaf.validFrom) > now || Date.parse(leaf.validTo) <= now) throw new Error(); + } catch { + throw new TLSConfigurationError("TLS-Zertifikat/Schlüssel ungültig, nicht passend, verschlüsselt oder Zertifikat außerhalb der Gültigkeit."); + } + return { cert, key, secureOptions: constants.SSL_OP_NO_TLSv1 | constants.SSL_OP_NO_TLSv1_1 }; +}