feat: add opt-in native HTTPS with fail-closed TLS validation
Keep existing HTTP/auth/tool settings compatible; isolate TLS persistence, validate PEM/key/validity before startup and saves, and require explicit restart. Integrate local status, WebGUI TLS controls and renewal preflight without insecure trust bypasses. Add synthetic HTTP/TLS/MCP, WebGUI and service regression tests plus operator documentation. Existing r033 binaries and automatic update manifest remain untouched; packaging was exercised as a local development artifact.
This commit is contained in:
1 parent
e18ce2e125
commit
454a3ed0fa
12 files changed
+988
-40
No files matched your search
@@ -25,6 +25,7 @@ Thumbs.db
|
||||
.env.*
|
||||
!.env.example
|
||||
mua.conf
|
||||
tls.conf
|
||||
credentials*
|
||||
secrets*
|
||||
*.key
|
||||
|
||||
@@ -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://<unraid-ip>:3002/health`.
|
||||
2. Check the configured `http://<unraid-ip>: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
|
||||
|
||||
@@ -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,
|
||||
|
||||
+7
-1
@@ -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
|
||||
|
||||
@@ -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.
|
||||
+192
@@ -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 </dev/null
|
||||
```
|
||||
|
||||
Danach denselben HTTPS-Endpunkt mit dem bestehenden, sicher gespeicherten
|
||||
Bearer-Key als MCP-Server registrieren; Schlüssel nicht in Shell-History/Logs
|
||||
oder Chat kopieren. Initialisierung, `tools/list` und einen ausdrücklich erlaubten
|
||||
harmlosen Leseaufruf testen. Ein Health-Check allein ist keine MCP-Abnahme.
|
||||
Für Hermes siehe [HERMES.md](HERMES.md): URL auf HTTPS umstellen und Client-Trust
|
||||
vorab herstellen; kein SSH-/Reverse-Proxy-Wrapper ist erforderlich.
|
||||
|
||||
`/etc/rc.d/rc.mua health` liefert dagegen **lokale Bereitschaft** über den
|
||||
Admin-geschützten Loopback-Kanal. Es gibt aktives `scheme`/`port` aus, funktioniert
|
||||
auch mit DNS-Zertifikaten ohne Loopback-IP-SAN und deaktiviert keine TLS-Prüfung.
|
||||
Es beweist nicht, dass entfernte Clients die Chain oder den Namen akzeptieren.
|
||||
Paket-Hook und WebGUI verwenden diesen lokalen Status bewusst getrennt von TLS.
|
||||
|
||||
## Erneuerung und Fehlerbehandlung
|
||||
|
||||
- Ein vorhandenes ACME-/PKI-Werkzeug darf nach Betreiberfreigabe die Dateien
|
||||
erneuern. Zertifikate und passende Keys konsistent veröffentlichen, danach
|
||||
`mua --check-config` und gezielt `rc.mua restart` ausführen.
|
||||
- `rc.mua restart` prüft die neue Konfiguration **vor dem Stoppen**. Bei einem
|
||||
erkannten Fehler bleibt der alte Prozess mit seinem bereits geladenen
|
||||
Zertifikat bestehen. Das ist kein HTTP-Fallback. Ein Fehler erst beim Binden
|
||||
des neuen Listeners kann trotzdem einen gestoppten Dienst bedeuten.
|
||||
- Der Prozess liest PEM **einmal beim Start**. Es gibt keinen Dateiwatcher,
|
||||
SIGHUP oder automatischen Zertifikatsreload. Auch ein Austausch unter demselben
|
||||
Pfad benötigt Neustart; dann kann die GUI keine Pfadänderung erkennen.
|
||||
- Fehlende/defekte/unlesbare/unpassende/verschlüsselte Dateien sowie abgelaufene
|
||||
oder noch nicht gültige Leaf-Zertifikate verhindern den Start (Exit 1).
|
||||
Kontrollierte Fehler nennen nur die betroffene Einstellung, keine PEM-Inhalte.
|
||||
- Die Gültigkeitsprüfung erfolgt beim Start, nicht als Erneuerungsdienst. Läuft
|
||||
ein Zertifikat später ab, werden korrekt prüfende Clients es ablehnen. Ablauf
|
||||
überwachen und rechtzeitig erneuern; Client-Trust/Chain/SAN sind separat zu prüfen.
|
||||
- Wenn der Start fehlschlägt, ist auch die lokale Verwaltung nicht verfügbar.
|
||||
`tls.conf`/Dateien über einen bereits autorisierten lokalen Administrationsweg
|
||||
reparieren, `--check-config` prüfen und gezielt starten. **Nicht** einfach eine
|
||||
TLS-Datei löschen oder HTTP aktivieren, um den Fehler zu verdecken.
|
||||
- Ein beabsichtigter Rückwechsel auf HTTP ist eine separate Betreiberentscheidung
|
||||
(`MUA_TLS_ENABLED=false`, Neustart und Client-URL anpassen). Token dann nicht
|
||||
über ungeschützte Netze senden.
|
||||
|
||||
## Entwicklung / reproduzierbare Tests
|
||||
|
||||
Geprüft mit Bun **1.3.14** (passend zum Typ-Lock), TypeScript **5.9.3**, OpenSSL
|
||||
**3.5.7** und PHP **8.4.27** mit curl/posix/SimpleXML/DOM/ctype/mbstring. Bun 1.4.4 verändert den
|
||||
vorhandenen, unveränderten deleted-cwd-Reproducer; dessen Baseline fällt dort
|
||||
bereits ohne TLS-Änderungen fehl. Die Regression wurde nicht deaktiviert.
|
||||
|
||||
```bash
|
||||
bun install --frozen-lockfile
|
||||
bun x --package typescript@5.9.3 tsc --noEmit
|
||||
bun test
|
||||
php -l scripts/mua.page
|
||||
bash -n scripts/rc.mua scripts/package.sh
|
||||
# Lokales Entwicklungsartefakt, keine Produktivinstallation/Release-Veröffentlichung:
|
||||
bash scripts/package.sh native-https-dev
|
||||
MUA_TEST_BINARY="$PWD/build/pkg/usr/local/bin/mua" bun test src/tls.test.ts
|
||||
xmllint --noout plugin/mua.plg
|
||||
```
|
||||
|
||||
Die Transporttests erzeugen kurzlebige Testzertifikate/-keys ausschließlich im
|
||||
Test-Tempverzeichnis, binden nur Loopback und nutzen synthetische Tooldaten.
|
||||
Sie prüfen echte TLS-Handshakes, CA-/SAN-Prüfung, MCP-Auth/-Aufrufe, HTTP-Regression,
|
||||
fehlende/defekte Keys, Fehlkonfiguration, Erneuerung/Neustart und PHP-WebGUI inkl.
|
||||
CSRF. Weder Unraid-/Docker-Produktionsdienste noch echte Zugangsdaten werden benötigt.
|
||||
+40
-19
@@ -6,21 +6,20 @@ Icon="cubes"
|
||||
---
|
||||
<?php
|
||||
/** MUA WebGUI — sicherheitsorientierte Verwaltung. */
|
||||
$port = 3002;
|
||||
$config_port = 3013;
|
||||
$pidfile = '/var/run/mua.pid';
|
||||
$binary = '/usr/local/bin/mua';
|
||||
$admin_token_file = '/var/run/mua-admin.token';
|
||||
$port = (int)(getenv('MUA_PORT') ?: 3002);
|
||||
$config_port = (int)(getenv('MUA_CONFIG_PORT') ?: 3013);
|
||||
$pidfile = getenv('MUA_PIDFILE') ?: '/var/run/mua.pid';
|
||||
$binary = getenv('MUA_BINARY') ?: '/usr/local/bin/mua';
|
||||
$admin_token_file = getenv('MUA_ADMIN_TOKEN_FILE') ?: '/var/run/mua-admin.token';
|
||||
$admin_token = is_readable($admin_token_file) ? trim(file_get_contents($admin_token_file)) : '';
|
||||
$unraid_csrf = $var['csrf_token'] ?? '';
|
||||
$host_ip = $_SERVER['SERVER_ADDR'] ?? '127.0.0.1';
|
||||
$endpoint = 'http://' . $host_ip . ':' . $port . '/mcp';
|
||||
|
||||
function mua_api($method, $path, $payload, $token, $port) {
|
||||
if (!$token) return [0, null];
|
||||
$ch = curl_init('http://127.0.0.1:' . $port . $path);
|
||||
$headers = ['X-MUA-Admin-Token: ' . $token];
|
||||
$options = [CURLOPT_RETURNTRANSFER => 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);
|
||||
<?php if ($new_api_key): ?><div class="mua-status ok"><strong>Neuer API-Key – einmalige Anzeige</strong><code class="mua-key" id="mua-new-key"><?= htmlspecialchars($new_api_key) ?></code><button type="button" class="mua-btn" onclick="navigator.clipboard.writeText(document.getElementById('mua-new-key').textContent)">In Zwischenablage kopieren</button></div><?php endif; ?>
|
||||
|
||||
<div class="mua-grid">
|
||||
<div class="mua-card"><h3>Dienst</h3><p class="mua-summary"><?= $health_ok ? '✅ MCP-Server antwortet' : '❌ Health-Check fehlgeschlagen' ?></p><div class="mua-muted">Version <?= htmlspecialchars($running_version ?: '—') ?> · PID <?= htmlspecialchars((string)($pid ?: '—')) ?></div></div>
|
||||
<div class="mua-card"><h3>Dienst</h3><p class="mua-summary"><?= $health_ok ? '✅ MCP-Listener gestartet (lokaler Status)' : '❌ Lokaler Bereitschaftstest fehlgeschlagen' ?></p><div class="mua-muted">Version <?= htmlspecialchars($running_version ?: '—') ?> · PID <?= htmlspecialchars((string)($pid ?: '—')) ?></div></div>
|
||||
<div class="mua-card"><h3>Zugriffsprofil</h3><p class="mua-summary"><strong><?= $active_count ?></strong> von <?= count($all_tools) ?> Werkzeugen aktiv</p><div class="mua-muted"><?= $all_tools_enabled ? 'Vollzugriff – einschließlich kritischer Werkzeuge' : ($active_count === 0 ? 'Komplett gesperrt' : 'Benutzerdefinierte Freigabe') ?></div></div>
|
||||
<div class="mua-card"><h3>Authentifizierung</h3><p class="mua-summary"><?= $config_ok ? '✅ Bearer-Key aktiv' : '❌ Verwaltung nicht erreichbar' ?></p><div class="mua-muted"><?= htmlspecialchars($config['apiKeyMasked'] ?? 'nicht verfügbar') ?></div></div>
|
||||
</div>
|
||||
|
||||
<div class="mua-card"><h3>MCP-Endpunkt</h3><code class="mua-endpoint"><?= htmlspecialchars($endpoint) ?></code><p class="mua-muted">Streamable HTTP · JSON-RPC 2.0 · Bearer-Authentifizierung erforderlich</p></div>
|
||||
|
||||
<div class="mua-section"><h2>HTTPS / TLS</h2><div class="mua-card">
|
||||
<p>Aktiver Transport: <strong><?= $health_ok ? strtoupper($scheme) : 'unbekannt' ?></strong>. TLS schützt denselben MCP-Port inklusive <code>/health</code>; Bearer-Key und Toolfreigaben bleiben unverändert.</p>
|
||||
<?php if (!empty($transport['restartRequired'])): ?><div class="mua-status warn">Gespeicherte Einstellungen sind noch nicht aktiv. Nach Prüfung Dienst ausdrücklich neu starten.</div><?php endif; ?>
|
||||
<?php if (!empty($transport['error'])): ?><div class="mua-status err"><?= htmlspecialchars($transport['error']) ?></div><?php endif; ?>
|
||||
<?php if (!empty($transport['envOverride'])): ?><p>Durch Umgebungsvariablen verwaltet; WebGUI-Änderung gesperrt.</p><?php endif; ?>
|
||||
<form method="post"><input type="hidden" name="csrf_token" value="<?= htmlspecialchars($unraid_csrf) ?>"><input type="hidden" name="mua_csrf" value="<?= htmlspecialchars($csrf) ?>"><input type="hidden" name="action" value="save_tls">
|
||||
<fieldset <?= $tls_locked ? 'disabled' : '' ?>><legend>TLS-Konfiguration</legend>
|
||||
<label class="mua-switch"><input type="checkbox" name="tls_enabled" <?= !empty($tls['enabled']) ? 'checked' : '' ?>><span><strong>HTTPS aktivieren</strong><br>Ohne gültiges Zertifikat und passenden Schlüssel startet MUA nicht. Kein automatischer HTTP-Fallback.</span></label>
|
||||
<p><label>Zertifikat / Fullchain (PEM, absoluter Pfad)<br><input type="text" name="tls_cert_file" maxlength="4096" style="width:95%" value="<?= htmlspecialchars($tls['certFile'] ?? '') ?>" placeholder="/persistenter/pfad/fullchain.pem"></label></p>
|
||||
<p><label>Privater Schlüssel (PEM, unverschlüsselt, absoluter Pfad)<br><input type="text" name="tls_key_file" maxlength="4096" style="width:95%" value="<?= htmlspecialchars($tls['keyFile'] ?? '') ?>" placeholder="/persistenter/pfad/privkey.pem"></label></p>
|
||||
<button type="submit" class="mua-btn mua-btn-primary">TLS prüfen und speichern</button></fieldset></form>
|
||||
<p class="mua-muted">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:<?= $config_port ?>. Lokale Bereitschaft ist kein Client-Trust-Test.</p>
|
||||
</div></div>
|
||||
|
||||
<div class="mua-section"><h2>Agent-Werkzeugcontainer</h2><div class="mua-card <?= !$toolbox_available ? '' : ($toolbox_enabled ? 'mua-risk-safe' : 'mua-risk-notice') ?>">
|
||||
<?php if ($toolbox_available): ?>
|
||||
<p class="mua-summary">✅ Gefunden: <?php foreach ($toolbox_containers as $i => $container): ?><?= $i ? ', ' : '' ?><strong><?= htmlspecialchars($container['name'] ?? 'unbekannt') ?></strong> <span class="mua-muted">(<?= htmlspecialchars($container['state'] ?? 'unbekannt') ?>)</span><?php endforeach; ?></p>
|
||||
|
||||
+9
-5
@@ -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
|
||||
|
||||
+37
-9
@@ -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
|
||||
+66
-5
@@ -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<typeof readTLSSettings>;
|
||||
let server: ReturnType<typeof Bun.serve>;
|
||||
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)"),
|
||||
);
|
||||
|
||||
|
||||
+444
@@ -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<number> {
|
||||
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<boolean> {
|
||||
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<string, string> = {}) {
|
||||
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<string, unknown> }> {
|
||||
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<string, string>) {
|
||||
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<any>;
|
||||
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);
|
||||
+112
@@ -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<string, string> = {};
|
||||
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<string, unknown>;
|
||||
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 };
|
||||
}
|
||||
Reference in new issue
Block a user